if_wpi.c revision 280098
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 280098 2015-03-15 21:08:54Z 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		return 0;
1177
1178	size = WPI_TX_RING_COUNT * sizeof (struct wpi_tx_cmd);
1179	error = wpi_dma_contig_alloc(sc, &ring->cmd_dma, (void **)&ring->cmd,
1180	    size, 4);
1181	if (error != 0) {
1182		device_printf(sc->sc_dev,
1183		    "%s: could not allocate TX cmd DMA memory, error %d\n",
1184		    __func__, error);
1185		goto fail;
1186	}
1187
1188	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 1, 0,
1189	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES,
1190	    WPI_MAX_SCATTER - 1, MCLBYTES, BUS_DMA_NOWAIT, NULL, NULL,
1191	    &ring->data_dmat);
1192	if (error != 0) {
1193		device_printf(sc->sc_dev,
1194		    "%s: could not create TX buf DMA tag, error %d\n",
1195		    __func__, error);
1196		goto fail;
1197	}
1198
1199	paddr = ring->cmd_dma.paddr;
1200	for (i = 0; i < WPI_TX_RING_COUNT; i++) {
1201		struct wpi_tx_data *data = &ring->data[i];
1202
1203		data->cmd_paddr = paddr;
1204		paddr += sizeof (struct wpi_tx_cmd);
1205
1206		error = bus_dmamap_create(ring->data_dmat, 0, &data->map);
1207		if (error != 0) {
1208			device_printf(sc->sc_dev,
1209			    "%s: could not create TX buf DMA map, error %d\n",
1210			    __func__, error);
1211			goto fail;
1212		}
1213	}
1214
1215	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
1216
1217	return 0;
1218
1219fail:	wpi_free_tx_ring(sc, ring);
1220	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR, __func__);
1221	return error;
1222}
1223
1224static void
1225wpi_update_tx_ring(struct wpi_softc *sc, struct wpi_tx_ring *ring)
1226{
1227	if (ring->update != 0) {
1228		/* Wait for INT_WAKEUP event. */
1229		return;
1230	}
1231
1232	if (WPI_READ(sc, WPI_UCODE_GP1) & WPI_UCODE_GP1_MAC_SLEEP) {
1233		DPRINTF(sc, WPI_DEBUG_PWRSAVE, "%s (%d): requesting wakeup\n",
1234		    __func__, ring->qid);
1235
1236		WPI_SETBITS(sc, WPI_GP_CNTRL, WPI_GP_CNTRL_MAC_ACCESS_REQ);
1237		ring->update = 1;
1238	} else
1239		WPI_WRITE(sc, WPI_HBUS_TARG_WRPTR, ring->qid << 8 | ring->cur);
1240}
1241
1242static void
1243wpi_reset_tx_ring(struct wpi_softc *sc, struct wpi_tx_ring *ring)
1244{
1245	int i;
1246
1247	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
1248
1249	for (i = 0; i < WPI_TX_RING_COUNT; i++) {
1250		struct wpi_tx_data *data = &ring->data[i];
1251
1252		if (data->m != NULL) {
1253			bus_dmamap_sync(ring->data_dmat, data->map,
1254			    BUS_DMASYNC_POSTWRITE);
1255			bus_dmamap_unload(ring->data_dmat, data->map);
1256			m_freem(data->m);
1257			data->m = NULL;
1258		}
1259	}
1260	/* Clear TX descriptors. */
1261	memset(ring->desc, 0, ring->desc_dma.size);
1262	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
1263	    BUS_DMASYNC_PREWRITE);
1264	sc->qfullmsk &= ~(1 << ring->qid);
1265	ring->queued = 0;
1266	ring->cur = 0;
1267	ring->update = 0;
1268}
1269
1270static void
1271wpi_free_tx_ring(struct wpi_softc *sc, struct wpi_tx_ring *ring)
1272{
1273	int i;
1274
1275	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
1276
1277	wpi_dma_contig_free(&ring->desc_dma);
1278	wpi_dma_contig_free(&ring->cmd_dma);
1279
1280	for (i = 0; i < WPI_TX_RING_COUNT; i++) {
1281		struct wpi_tx_data *data = &ring->data[i];
1282
1283		if (data->m != NULL) {
1284			bus_dmamap_sync(ring->data_dmat, data->map,
1285			    BUS_DMASYNC_POSTWRITE);
1286			bus_dmamap_unload(ring->data_dmat, data->map);
1287			m_freem(data->m);
1288		}
1289		if (data->map != NULL)
1290			bus_dmamap_destroy(ring->data_dmat, data->map);
1291	}
1292	if (ring->data_dmat != NULL) {
1293		bus_dma_tag_destroy(ring->data_dmat);
1294		ring->data_dmat = NULL;
1295	}
1296}
1297
1298/*
1299 * Extract various information from EEPROM.
1300 */
1301static int
1302wpi_read_eeprom(struct wpi_softc *sc, uint8_t macaddr[IEEE80211_ADDR_LEN])
1303{
1304#define WPI_CHK(res) do {		\
1305	if ((error = res) != 0)		\
1306		goto fail;		\
1307} while (0)
1308	int error, i;
1309
1310	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
1311
1312	/* Adapter has to be powered on for EEPROM access to work. */
1313	if ((error = wpi_apm_init(sc)) != 0) {
1314		device_printf(sc->sc_dev,
1315		    "%s: could not power ON adapter, error %d\n", __func__,
1316		    error);
1317		return error;
1318	}
1319
1320	if ((WPI_READ(sc, WPI_EEPROM_GP) & 0x6) == 0) {
1321		device_printf(sc->sc_dev, "bad EEPROM signature\n");
1322		error = EIO;
1323		goto fail;
1324	}
1325	/* Clear HW ownership of EEPROM. */
1326	WPI_CLRBITS(sc, WPI_EEPROM_GP, WPI_EEPROM_GP_IF_OWNER);
1327
1328	/* Read the hardware capabilities, revision and SKU type. */
1329	WPI_CHK(wpi_read_prom_data(sc, WPI_EEPROM_SKU_CAP, &sc->cap,
1330	    sizeof(sc->cap)));
1331	WPI_CHK(wpi_read_prom_data(sc, WPI_EEPROM_REVISION, &sc->rev,
1332	    sizeof(sc->rev)));
1333	WPI_CHK(wpi_read_prom_data(sc, WPI_EEPROM_TYPE, &sc->type,
1334	    sizeof(sc->type)));
1335
1336	sc->rev = le16toh(sc->rev);
1337	DPRINTF(sc, WPI_DEBUG_EEPROM, "cap=%x rev=%x type=%x\n", sc->cap,
1338	    sc->rev, sc->type);
1339
1340	/* Read the regulatory domain (4 ASCII characters.) */
1341	WPI_CHK(wpi_read_prom_data(sc, WPI_EEPROM_DOMAIN, sc->domain,
1342	    sizeof(sc->domain)));
1343
1344	/* Read MAC address. */
1345	WPI_CHK(wpi_read_prom_data(sc, WPI_EEPROM_MAC, macaddr,
1346	    IEEE80211_ADDR_LEN));
1347
1348	/* Read the list of authorized channels. */
1349	for (i = 0; i < WPI_CHAN_BANDS_COUNT; i++)
1350		WPI_CHK(wpi_read_eeprom_channels(sc, i));
1351
1352	/* Read the list of TX power groups. */
1353	for (i = 0; i < WPI_POWER_GROUPS_COUNT; i++)
1354		WPI_CHK(wpi_read_eeprom_group(sc, i));
1355
1356fail:	wpi_apm_stop(sc);	/* Power OFF adapter. */
1357
1358	DPRINTF(sc, WPI_DEBUG_TRACE, error ? TRACE_STR_END_ERR : TRACE_STR_END,
1359	    __func__);
1360
1361	return error;
1362#undef WPI_CHK
1363}
1364
1365/*
1366 * Translate EEPROM flags to net80211.
1367 */
1368static uint32_t
1369wpi_eeprom_channel_flags(struct wpi_eeprom_chan *channel)
1370{
1371	uint32_t nflags;
1372
1373	nflags = 0;
1374	if ((channel->flags & WPI_EEPROM_CHAN_ACTIVE) == 0)
1375		nflags |= IEEE80211_CHAN_PASSIVE;
1376	if ((channel->flags & WPI_EEPROM_CHAN_IBSS) == 0)
1377		nflags |= IEEE80211_CHAN_NOADHOC;
1378	if (channel->flags & WPI_EEPROM_CHAN_RADAR) {
1379		nflags |= IEEE80211_CHAN_DFS;
1380		/* XXX apparently IBSS may still be marked */
1381		nflags |= IEEE80211_CHAN_NOADHOC;
1382	}
1383
1384	return nflags;
1385}
1386
1387static void
1388wpi_read_eeprom_band(struct wpi_softc *sc, int n)
1389{
1390	struct ifnet *ifp = sc->sc_ifp;
1391	struct ieee80211com *ic = ifp->if_l2com;
1392	struct wpi_eeprom_chan *channels = sc->eeprom_channels[n];
1393	const struct wpi_chan_band *band = &wpi_bands[n];
1394	struct ieee80211_channel *c;
1395	uint8_t chan;
1396	int i, nflags;
1397
1398	for (i = 0; i < band->nchan; i++) {
1399		if (!(channels[i].flags & WPI_EEPROM_CHAN_VALID)) {
1400			DPRINTF(sc, WPI_DEBUG_EEPROM,
1401			    "Channel Not Valid: %d, band %d\n",
1402			     band->chan[i],n);
1403			continue;
1404		}
1405
1406		chan = band->chan[i];
1407		nflags = wpi_eeprom_channel_flags(&channels[i]);
1408
1409		c = &ic->ic_channels[ic->ic_nchans++];
1410		c->ic_ieee = chan;
1411		c->ic_maxregpower = channels[i].maxpwr;
1412		c->ic_maxpower = 2*c->ic_maxregpower;
1413
1414		if (n == 0) {	/* 2GHz band */
1415			c->ic_freq = ieee80211_ieee2mhz(chan,
1416			    IEEE80211_CHAN_G);
1417
1418			/* G =>'s B is supported */
1419			c->ic_flags = IEEE80211_CHAN_B | nflags;
1420			c = &ic->ic_channels[ic->ic_nchans++];
1421			c[0] = c[-1];
1422			c->ic_flags = IEEE80211_CHAN_G | nflags;
1423		} else {	/* 5GHz band */
1424			c->ic_freq = ieee80211_ieee2mhz(chan,
1425			    IEEE80211_CHAN_A);
1426
1427			c->ic_flags = IEEE80211_CHAN_A | nflags;
1428		}
1429
1430		/* Save maximum allowed TX power for this channel. */
1431		sc->maxpwr[chan] = channels[i].maxpwr;
1432
1433		DPRINTF(sc, WPI_DEBUG_EEPROM,
1434		    "adding chan %d (%dMHz) flags=0x%x maxpwr=%d passive=%d,"
1435		    " offset %d\n", chan, c->ic_freq,
1436		    channels[i].flags, sc->maxpwr[chan],
1437		    IEEE80211_IS_CHAN_PASSIVE(c), ic->ic_nchans);
1438	}
1439}
1440
1441/**
1442 * Read the eeprom to find out what channels are valid for the given
1443 * band and update net80211 with what we find.
1444 */
1445static int
1446wpi_read_eeprom_channels(struct wpi_softc *sc, int n)
1447{
1448	struct ifnet *ifp = sc->sc_ifp;
1449	struct ieee80211com *ic = ifp->if_l2com;
1450	const struct wpi_chan_band *band = &wpi_bands[n];
1451	int error;
1452
1453	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
1454
1455	error = wpi_read_prom_data(sc, band->addr, &sc->eeprom_channels[n],
1456	    band->nchan * sizeof (struct wpi_eeprom_chan));
1457	if (error != 0) {
1458		DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR, __func__);
1459		return error;
1460	}
1461
1462	wpi_read_eeprom_band(sc, n);
1463
1464	ieee80211_sort_channels(ic->ic_channels, ic->ic_nchans);
1465
1466	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
1467
1468	return 0;
1469}
1470
1471static struct wpi_eeprom_chan *
1472wpi_find_eeprom_channel(struct wpi_softc *sc, struct ieee80211_channel *c)
1473{
1474	int i, j;
1475
1476	for (j = 0; j < WPI_CHAN_BANDS_COUNT; j++)
1477		for (i = 0; i < wpi_bands[j].nchan; i++)
1478			if (wpi_bands[j].chan[i] == c->ic_ieee)
1479				return &sc->eeprom_channels[j][i];
1480
1481	return NULL;
1482}
1483
1484/*
1485 * Enforce flags read from EEPROM.
1486 */
1487static int
1488wpi_setregdomain(struct ieee80211com *ic, struct ieee80211_regdomain *rd,
1489    int nchan, struct ieee80211_channel chans[])
1490{
1491	struct ifnet *ifp = ic->ic_ifp;
1492	struct wpi_softc *sc = ifp->if_softc;
1493	int i;
1494
1495	for (i = 0; i < nchan; i++) {
1496		struct ieee80211_channel *c = &chans[i];
1497		struct wpi_eeprom_chan *channel;
1498
1499		channel = wpi_find_eeprom_channel(sc, c);
1500		if (channel == NULL) {
1501			if_printf(ic->ic_ifp,
1502			    "%s: invalid channel %u freq %u/0x%x\n",
1503			    __func__, c->ic_ieee, c->ic_freq, c->ic_flags);
1504			return EINVAL;
1505		}
1506		c->ic_flags |= wpi_eeprom_channel_flags(channel);
1507	}
1508
1509	return 0;
1510}
1511
1512static int
1513wpi_read_eeprom_group(struct wpi_softc *sc, int n)
1514{
1515	struct wpi_power_group *group = &sc->groups[n];
1516	struct wpi_eeprom_group rgroup;
1517	int i, error;
1518
1519	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
1520
1521	if ((error = wpi_read_prom_data(sc, WPI_EEPROM_POWER_GRP + n * 32,
1522	    &rgroup, sizeof rgroup)) != 0) {
1523		DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR, __func__);
1524		return error;
1525	}
1526
1527	/* Save TX power group information. */
1528	group->chan   = rgroup.chan;
1529	group->maxpwr = rgroup.maxpwr;
1530	/* Retrieve temperature at which the samples were taken. */
1531	group->temp   = (int16_t)le16toh(rgroup.temp);
1532
1533	DPRINTF(sc, WPI_DEBUG_EEPROM,
1534	    "power group %d: chan=%d maxpwr=%d temp=%d\n", n, group->chan,
1535	    group->maxpwr, group->temp);
1536
1537	for (i = 0; i < WPI_SAMPLES_COUNT; i++) {
1538		group->samples[i].index = rgroup.samples[i].index;
1539		group->samples[i].power = rgroup.samples[i].power;
1540
1541		DPRINTF(sc, WPI_DEBUG_EEPROM,
1542		    "\tsample %d: index=%d power=%d\n", i,
1543		    group->samples[i].index, group->samples[i].power);
1544	}
1545
1546	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
1547
1548	return 0;
1549}
1550
1551static int
1552wpi_add_node_entry_adhoc(struct wpi_softc *sc)
1553{
1554	int newid = WPI_ID_IBSS_MIN;
1555
1556	for (; newid <= WPI_ID_IBSS_MAX; newid++) {
1557		if ((sc->nodesmsk & (1 << newid)) == 0) {
1558			sc->nodesmsk |= 1 << newid;
1559			return newid;
1560		}
1561	}
1562
1563	return WPI_ID_UNDEFINED;
1564}
1565
1566static __inline int
1567wpi_add_node_entry_sta(struct wpi_softc *sc)
1568{
1569	sc->nodesmsk |= 1 << WPI_ID_BSS;
1570
1571	return WPI_ID_BSS;
1572}
1573
1574static __inline int
1575wpi_check_node_entry(struct wpi_softc *sc, uint8_t id)
1576{
1577	if (id == WPI_ID_UNDEFINED)
1578		return 0;
1579
1580	return (sc->nodesmsk >> id) & 1;
1581}
1582
1583static __inline void
1584wpi_clear_node_table(struct wpi_softc *sc)
1585{
1586	sc->nodesmsk = 0;
1587}
1588
1589static __inline void
1590wpi_del_node_entry(struct wpi_softc *sc, uint8_t id)
1591{
1592	sc->nodesmsk &= ~(1 << id);
1593}
1594
1595static struct ieee80211_node *
1596wpi_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
1597{
1598	struct wpi_node *wn;
1599
1600	wn = malloc(sizeof (struct wpi_node), M_80211_NODE,
1601	    M_NOWAIT | M_ZERO);
1602
1603	if (wn == NULL)
1604		return NULL;
1605
1606	wn->id = WPI_ID_UNDEFINED;
1607
1608	return &wn->ni;
1609}
1610
1611static void
1612wpi_node_free(struct ieee80211_node *ni)
1613{
1614	struct ieee80211com *ic = ni->ni_ic;
1615	struct wpi_softc *sc = ic->ic_ifp->if_softc;
1616	struct wpi_node *wn = WPI_NODE(ni);
1617
1618	if (wn->id != WPI_ID_UNDEFINED) {
1619		WPI_NT_LOCK(sc);
1620		if (wpi_check_node_entry(sc, wn->id)) {
1621			wpi_del_node_entry(sc, wn->id);
1622			wpi_del_node(sc, ni);
1623		}
1624		WPI_NT_UNLOCK(sc);
1625	}
1626
1627	sc->sc_node_free(ni);
1628}
1629
1630/**
1631 * Called by net80211 when ever there is a change to 80211 state machine
1632 */
1633static int
1634wpi_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
1635{
1636	struct wpi_vap *wvp = WPI_VAP(vap);
1637	struct ieee80211com *ic = vap->iv_ic;
1638	struct ifnet *ifp = ic->ic_ifp;
1639	struct wpi_softc *sc = ifp->if_softc;
1640	int error = 0;
1641
1642	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
1643
1644	DPRINTF(sc, WPI_DEBUG_STATE, "%s: %s -> %s\n", __func__,
1645		ieee80211_state_name[vap->iv_state],
1646		ieee80211_state_name[nstate]);
1647
1648	IEEE80211_UNLOCK(ic);
1649	WPI_LOCK(sc);
1650	switch (nstate) {
1651	case IEEE80211_S_SCAN:
1652		if ((vap->iv_opmode == IEEE80211_M_IBSS ||
1653		    vap->iv_opmode == IEEE80211_M_AHDEMO) &&
1654		    (sc->rxon.filter & htole32(WPI_FILTER_BSS))) {
1655			sc->rxon.filter &= ~htole32(WPI_FILTER_BSS);
1656			if ((error = wpi_send_rxon(sc, 0, 1)) != 0) {
1657				device_printf(sc->sc_dev,
1658				    "%s: could not send RXON\n", __func__);
1659			}
1660		}
1661		break;
1662
1663	case IEEE80211_S_ASSOC:
1664		if (vap->iv_state != IEEE80211_S_RUN)
1665			break;
1666		/* FALLTHROUGH */
1667	case IEEE80211_S_AUTH:
1668		/*
1669		 * The node must be registered in the firmware before auth.
1670		 * Also the associd must be cleared on RUN -> ASSOC
1671		 * transitions.
1672		 */
1673		if ((error = wpi_auth(sc, vap)) != 0) {
1674			device_printf(sc->sc_dev,
1675			    "%s: could not move to AUTH state, error %d\n",
1676			    __func__, error);
1677		}
1678		break;
1679
1680	case IEEE80211_S_RUN:
1681		/*
1682		 * RUN -> RUN transition; Just restart the timers.
1683		 */
1684		if (vap->iv_state == IEEE80211_S_RUN) {
1685			wpi_calib_timeout(sc);
1686			break;
1687		}
1688
1689		/*
1690		 * !RUN -> RUN requires setting the association id
1691		 * which is done with a firmware cmd.  We also defer
1692		 * starting the timers until that work is done.
1693		 */
1694		if ((error = wpi_run(sc, vap)) != 0) {
1695			device_printf(sc->sc_dev,
1696			    "%s: could not move to RUN state\n", __func__);
1697		}
1698		break;
1699
1700	default:
1701		break;
1702	}
1703	WPI_UNLOCK(sc);
1704	IEEE80211_LOCK(ic);
1705	if (error != 0) {
1706		DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR, __func__);
1707		return error;
1708	}
1709
1710	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
1711
1712	return wvp->wv_newstate(vap, nstate, arg);
1713}
1714
1715static void
1716wpi_calib_timeout(void *arg)
1717{
1718	struct wpi_softc *sc = arg;
1719	struct ifnet *ifp = sc->sc_ifp;
1720	struct ieee80211com *ic = ifp->if_l2com;
1721	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1722
1723	if (vap->iv_state != IEEE80211_S_RUN)
1724		return;
1725
1726	wpi_power_calibration(sc);
1727
1728	callout_reset(&sc->calib_to, 60*hz, wpi_calib_timeout, sc);
1729}
1730
1731static __inline uint8_t
1732rate2plcp(const uint8_t rate)
1733{
1734	switch (rate) {
1735	case 12:	return 0xd;
1736	case 18:	return 0xf;
1737	case 24:	return 0x5;
1738	case 36:	return 0x7;
1739	case 48:	return 0x9;
1740	case 72:	return 0xb;
1741	case 96:	return 0x1;
1742	case 108:	return 0x3;
1743	case 2:		return 10;
1744	case 4:		return 20;
1745	case 11:	return 55;
1746	case 22:	return 110;
1747	default:	return 0;
1748	}
1749}
1750
1751static __inline uint8_t
1752plcp2rate(const uint8_t plcp)
1753{
1754	switch (plcp) {
1755	case 0xd:	return 12;
1756	case 0xf:	return 18;
1757	case 0x5:	return 24;
1758	case 0x7:	return 36;
1759	case 0x9:	return 48;
1760	case 0xb:	return 72;
1761	case 0x1:	return 96;
1762	case 0x3:	return 108;
1763	case 10:	return 2;
1764	case 20:	return 4;
1765	case 55:	return 11;
1766	case 110:	return 22;
1767	default:	return 0;
1768	}
1769}
1770
1771/* Quickly determine if a given rate is CCK or OFDM. */
1772#define WPI_RATE_IS_OFDM(rate)	((rate) >= 12 && (rate) != 22)
1773
1774static void
1775wpi_rx_done(struct wpi_softc *sc, struct wpi_rx_desc *desc,
1776    struct wpi_rx_data *data)
1777{
1778	struct ifnet *ifp = sc->sc_ifp;
1779	struct ieee80211com *ic = ifp->if_l2com;
1780	struct wpi_rx_ring *ring = &sc->rxq;
1781	struct wpi_rx_stat *stat;
1782	struct wpi_rx_head *head;
1783	struct wpi_rx_tail *tail;
1784	struct ieee80211_frame *wh;
1785	struct ieee80211_node *ni;
1786	struct mbuf *m, *m1;
1787	bus_addr_t paddr;
1788	uint32_t flags;
1789	uint16_t len;
1790	int error;
1791
1792	stat = (struct wpi_rx_stat *)(desc + 1);
1793
1794	if (stat->len > WPI_STAT_MAXLEN) {
1795		device_printf(sc->sc_dev, "invalid RX statistic header\n");
1796		goto fail1;
1797	}
1798
1799	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTREAD);
1800	head = (struct wpi_rx_head *)((caddr_t)(stat + 1) + stat->len);
1801	len = le16toh(head->len);
1802	tail = (struct wpi_rx_tail *)((caddr_t)(head + 1) + len);
1803	flags = le32toh(tail->flags);
1804
1805	DPRINTF(sc, WPI_DEBUG_RECV, "%s: idx %d len %d stat len %u rssi %d"
1806	    " rate %x chan %d tstamp %ju\n", __func__, ring->cur,
1807	    le32toh(desc->len), len, (int8_t)stat->rssi,
1808	    head->plcp, head->chan, (uintmax_t)le64toh(tail->tstamp));
1809
1810	/* Discard frames with a bad FCS early. */
1811	if ((flags & WPI_RX_NOERROR) != WPI_RX_NOERROR) {
1812		DPRINTF(sc, WPI_DEBUG_RECV, "%s: RX flags error %x\n",
1813		    __func__, flags);
1814		goto fail1;
1815	}
1816	/* Discard frames that are too short. */
1817	if (len < sizeof (*wh)) {
1818		DPRINTF(sc, WPI_DEBUG_RECV, "%s: frame too short: %d\n",
1819		    __func__, len);
1820		goto fail1;
1821	}
1822
1823	m1 = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, MJUMPAGESIZE);
1824	if (m1 == NULL) {
1825		DPRINTF(sc, WPI_DEBUG_ANY, "%s: no mbuf to restock ring\n",
1826		    __func__);
1827		goto fail1;
1828	}
1829	bus_dmamap_unload(ring->data_dmat, data->map);
1830
1831	error = bus_dmamap_load(ring->data_dmat, data->map, mtod(m1, void *),
1832	    MJUMPAGESIZE, wpi_dma_map_addr, &paddr, BUS_DMA_NOWAIT);
1833	if (error != 0 && error != EFBIG) {
1834		device_printf(sc->sc_dev,
1835		    "%s: bus_dmamap_load failed, error %d\n", __func__, error);
1836		m_freem(m1);
1837
1838		/* Try to reload the old mbuf. */
1839		error = bus_dmamap_load(ring->data_dmat, data->map,
1840		    mtod(data->m, void *), MJUMPAGESIZE, wpi_dma_map_addr,
1841		    &paddr, BUS_DMA_NOWAIT);
1842		if (error != 0 && error != EFBIG) {
1843			panic("%s: could not load old RX mbuf", __func__);
1844		}
1845		/* Physical address may have changed. */
1846		ring->desc[ring->cur] = htole32(paddr);
1847		bus_dmamap_sync(ring->data_dmat, ring->desc_dma.map,
1848		    BUS_DMASYNC_PREWRITE);
1849		goto fail1;
1850	}
1851
1852	m = data->m;
1853	data->m = m1;
1854	/* Update RX descriptor. */
1855	ring->desc[ring->cur] = htole32(paddr);
1856	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
1857	    BUS_DMASYNC_PREWRITE);
1858
1859	/* Finalize mbuf. */
1860	m->m_pkthdr.rcvif = ifp;
1861	m->m_data = (caddr_t)(head + 1);
1862	m->m_pkthdr.len = m->m_len = len;
1863
1864	/* Grab a reference to the source node. */
1865	wh = mtod(m, struct ieee80211_frame *);
1866
1867	if ((wh->i_fc[1] & IEEE80211_FC1_PROTECTED) &&
1868	    (flags & WPI_RX_CIPHER_MASK) == WPI_RX_CIPHER_CCMP) {
1869		/* Check whether decryption was successful or not. */
1870		if ((flags & WPI_RX_DECRYPT_MASK) != WPI_RX_DECRYPT_OK) {
1871			DPRINTF(sc, WPI_DEBUG_RECV,
1872			    "CCMP decryption failed 0x%x\n", flags);
1873			goto fail2;
1874		}
1875		m->m_flags |= M_WEP;
1876	}
1877
1878	ni = ieee80211_find_rxnode(ic, (struct ieee80211_frame_min *)wh);
1879
1880	if (ieee80211_radiotap_active(ic)) {
1881		struct wpi_rx_radiotap_header *tap = &sc->sc_rxtap;
1882
1883		tap->wr_flags = 0;
1884		if (head->flags & htole16(WPI_STAT_FLAG_SHPREAMBLE))
1885			tap->wr_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
1886		tap->wr_dbm_antsignal = (int8_t)(stat->rssi + WPI_RSSI_OFFSET);
1887		tap->wr_dbm_antnoise = WPI_RSSI_OFFSET;
1888		tap->wr_tsft = tail->tstamp;
1889		tap->wr_antenna = (le16toh(head->flags) >> 4) & 0xf;
1890		tap->wr_rate = plcp2rate(head->plcp);
1891	}
1892
1893	WPI_UNLOCK(sc);
1894
1895	/* Send the frame to the 802.11 layer. */
1896	if (ni != NULL) {
1897		(void)ieee80211_input(ni, m, stat->rssi, WPI_RSSI_OFFSET);
1898		/* Node is no longer needed. */
1899		ieee80211_free_node(ni);
1900	} else
1901		(void)ieee80211_input_all(ic, m, stat->rssi, WPI_RSSI_OFFSET);
1902
1903	WPI_LOCK(sc);
1904
1905	return;
1906
1907fail2:	m_freem(m);
1908
1909fail1:	if_inc_counter(ifp, IFCOUNTER_IERRORS, 1);
1910}
1911
1912static void
1913wpi_rx_statistics(struct wpi_softc *sc, struct wpi_rx_desc *desc,
1914    struct wpi_rx_data *data)
1915{
1916	/* Ignore */
1917}
1918
1919static void
1920wpi_tx_done(struct wpi_softc *sc, struct wpi_rx_desc *desc)
1921{
1922	struct ifnet *ifp = sc->sc_ifp;
1923	struct wpi_tx_ring *ring = &sc->txq[desc->qid & 0x3];
1924	struct wpi_tx_data *data = &ring->data[desc->idx];
1925	struct wpi_tx_stat *stat = (struct wpi_tx_stat *)(desc + 1);
1926	struct mbuf *m;
1927	struct ieee80211_node *ni;
1928	struct ieee80211vap *vap;
1929	struct ieee80211com *ic;
1930	int ackfailcnt = stat->ackfailcnt / 2;	/* wpi_mrr_setup() */
1931	int status = le32toh(stat->status);
1932
1933	KASSERT(data->ni != NULL, ("no node"));
1934
1935	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
1936
1937	DPRINTF(sc, WPI_DEBUG_XMIT, "%s: "
1938	    "qid %d idx %d retries %d btkillcnt %d rate %x duration %d "
1939	    "status %x\n", __func__, desc->qid, desc->idx, ackfailcnt,
1940	    stat->btkillcnt, stat->rate, le32toh(stat->duration), status);
1941
1942	/* Unmap and free mbuf. */
1943	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTWRITE);
1944	bus_dmamap_unload(ring->data_dmat, data->map);
1945	m = data->m, data->m = NULL;
1946	ni = data->ni, data->ni = NULL;
1947	vap = ni->ni_vap;
1948	ic = vap->iv_ic;
1949
1950	/*
1951	 * Update rate control statistics for the node.
1952	 */
1953	WPI_UNLOCK(sc);
1954	if ((status & 0xff) != 1) {
1955		if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
1956		ieee80211_ratectl_tx_complete(vap, ni,
1957		    IEEE80211_RATECTL_TX_FAILURE, &ackfailcnt, NULL);
1958	} else {
1959		if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
1960		ieee80211_ratectl_tx_complete(vap, ni,
1961		    IEEE80211_RATECTL_TX_SUCCESS, &ackfailcnt, NULL);
1962	}
1963
1964	ieee80211_tx_complete(ni, m, (status & 0xff) != 1);
1965	WPI_LOCK(sc);
1966
1967	sc->sc_tx_timer = 0;
1968	if (--ring->queued < WPI_TX_RING_LOMARK) {
1969		sc->qfullmsk &= ~(1 << ring->qid);
1970		IF_LOCK(&ifp->if_snd);
1971		if (sc->qfullmsk == 0 &&
1972		    (ifp->if_drv_flags & IFF_DRV_OACTIVE)) {
1973			ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1974			IF_UNLOCK(&ifp->if_snd);
1975			ieee80211_runtask(ic, &sc->sc_start_task);
1976		} else
1977			IF_UNLOCK(&ifp->if_snd);
1978	}
1979
1980	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
1981}
1982
1983/*
1984 * Process a "command done" firmware notification.  This is where we wakeup
1985 * processes waiting for a synchronous command completion.
1986 */
1987static void
1988wpi_cmd_done(struct wpi_softc *sc, struct wpi_rx_desc *desc)
1989{
1990	struct wpi_tx_ring *ring = &sc->txq[WPI_CMD_QUEUE_NUM];
1991	struct wpi_tx_data *data;
1992
1993	DPRINTF(sc, WPI_DEBUG_CMD, "cmd notification qid=%x idx=%d flags=%x "
1994				   "type=%s len=%d\n", desc->qid, desc->idx,
1995				   desc->flags, wpi_cmd_str(desc->type),
1996				   le32toh(desc->len));
1997
1998	if ((desc->qid & WPI_RX_DESC_QID_MSK) != WPI_CMD_QUEUE_NUM)
1999		return;	/* Not a command ack. */
2000
2001	KASSERT(ring->queued == 0, ("ring->queued must be 0"));
2002
2003	data = &ring->data[desc->idx];
2004
2005	/* If the command was mapped in an mbuf, free it. */
2006	if (data->m != NULL) {
2007		bus_dmamap_sync(ring->data_dmat, data->map,
2008		    BUS_DMASYNC_POSTWRITE);
2009		bus_dmamap_unload(ring->data_dmat, data->map);
2010		m_freem(data->m);
2011		data->m = NULL;
2012	}
2013
2014	wakeup(&ring->cmd[desc->idx]);
2015}
2016
2017static void
2018wpi_notif_intr(struct wpi_softc *sc)
2019{
2020	struct ifnet *ifp = sc->sc_ifp;
2021	struct ieee80211com *ic = ifp->if_l2com;
2022	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2023	int hw;
2024
2025	bus_dmamap_sync(sc->shared_dma.tag, sc->shared_dma.map,
2026	    BUS_DMASYNC_POSTREAD);
2027
2028	hw = le32toh(sc->shared->next);
2029	hw = (hw == 0) ? WPI_RX_RING_COUNT - 1 : hw - 1;
2030
2031	while (sc->rxq.cur != hw) {
2032		sc->rxq.cur = (sc->rxq.cur + 1) % WPI_RX_RING_COUNT;
2033
2034		struct wpi_rx_data *data = &sc->rxq.data[sc->rxq.cur];
2035		struct wpi_rx_desc *desc;
2036
2037		bus_dmamap_sync(sc->rxq.data_dmat, data->map,
2038		    BUS_DMASYNC_POSTREAD);
2039		desc = mtod(data->m, struct wpi_rx_desc *);
2040
2041		DPRINTF(sc, WPI_DEBUG_NOTIFY,
2042		    "%s: cur=%d; qid %x idx %d flags %x type %d(%s) len %d\n",
2043		    __func__, sc->rxq.cur, desc->qid, desc->idx, desc->flags,
2044		    desc->type, wpi_cmd_str(desc->type), le32toh(desc->len));
2045
2046		if (!(desc->qid & WPI_UNSOLICITED_RX_NOTIF)) {
2047			/* Reply to a command. */
2048			wpi_cmd_done(sc, desc);
2049		}
2050
2051		switch (desc->type) {
2052		case WPI_RX_DONE:
2053			/* An 802.11 frame has been received. */
2054			wpi_rx_done(sc, desc, data);
2055
2056			if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
2057				/* wpi_stop() was called. */
2058				return;
2059			}
2060
2061			break;
2062
2063		case WPI_TX_DONE:
2064			/* An 802.11 frame has been transmitted. */
2065			wpi_tx_done(sc, desc);
2066			break;
2067
2068		case WPI_RX_STATISTICS:
2069		case WPI_BEACON_STATISTICS:
2070			wpi_rx_statistics(sc, desc, data);
2071			break;
2072
2073		case WPI_BEACON_MISSED:
2074		{
2075			struct wpi_beacon_missed *miss =
2076			    (struct wpi_beacon_missed *)(desc + 1);
2077			int misses;
2078
2079			bus_dmamap_sync(sc->rxq.data_dmat, data->map,
2080			    BUS_DMASYNC_POSTREAD);
2081			misses = le32toh(miss->consecutive);
2082
2083			DPRINTF(sc, WPI_DEBUG_STATE,
2084			    "%s: beacons missed %d/%d\n", __func__, misses,
2085			    le32toh(miss->total));
2086
2087			if (vap->iv_state == IEEE80211_S_RUN &&
2088			    (ic->ic_flags & IEEE80211_F_SCAN) == 0) {
2089				if (misses >=  vap->iv_bmissthreshold) {
2090					WPI_UNLOCK(sc);
2091					ieee80211_beacon_miss(ic);
2092					WPI_LOCK(sc);
2093				}
2094			}
2095			break;
2096		}
2097		case WPI_UC_READY:
2098		{
2099			struct wpi_ucode_info *uc =
2100			    (struct wpi_ucode_info *)(desc + 1);
2101
2102			/* The microcontroller is ready. */
2103			bus_dmamap_sync(sc->rxq.data_dmat, data->map,
2104			    BUS_DMASYNC_POSTREAD);
2105			DPRINTF(sc, WPI_DEBUG_RESET,
2106			    "microcode alive notification version=%d.%d "
2107			    "subtype=%x alive=%x\n", uc->major, uc->minor,
2108			    uc->subtype, le32toh(uc->valid));
2109
2110			if (le32toh(uc->valid) != 1) {
2111				device_printf(sc->sc_dev,
2112				    "microcontroller initialization failed\n");
2113				wpi_stop_locked(sc);
2114			}
2115			/* Save the address of the error log in SRAM. */
2116			sc->errptr = le32toh(uc->errptr);
2117			break;
2118		}
2119		case WPI_STATE_CHANGED:
2120		{
2121			bus_dmamap_sync(sc->rxq.data_dmat, data->map,
2122			    BUS_DMASYNC_POSTREAD);
2123
2124			uint32_t *status = (uint32_t *)(desc + 1);
2125
2126			DPRINTF(sc, WPI_DEBUG_STATE, "state changed to %x\n",
2127			    le32toh(*status));
2128
2129			if (le32toh(*status) & 1) {
2130				WPI_NT_LOCK(sc);
2131				wpi_clear_node_table(sc);
2132				WPI_NT_UNLOCK(sc);
2133				ieee80211_runtask(ic, &sc->sc_radiooff_task);
2134				return;
2135			}
2136			break;
2137		}
2138		case WPI_START_SCAN:
2139		{
2140			bus_dmamap_sync(sc->rxq.data_dmat, data->map,
2141			    BUS_DMASYNC_POSTREAD);
2142#ifdef WPI_DEBUG
2143			struct wpi_start_scan *scan =
2144			    (struct wpi_start_scan *)(desc + 1);
2145			DPRINTF(sc, WPI_DEBUG_SCAN,
2146			    "%s: scanning channel %d status %x\n",
2147			    __func__, scan->chan, le32toh(scan->status));
2148#endif
2149			break;
2150		}
2151		case WPI_STOP_SCAN:
2152		{
2153			bus_dmamap_sync(sc->rxq.data_dmat, data->map,
2154			    BUS_DMASYNC_POSTREAD);
2155#ifdef WPI_DEBUG
2156			struct wpi_stop_scan *scan =
2157			    (struct wpi_stop_scan *)(desc + 1);
2158			DPRINTF(sc, WPI_DEBUG_SCAN,
2159			    "scan finished nchan=%d status=%d chan=%d\n",
2160			    scan->nchan, scan->status, scan->chan);
2161#endif
2162			sc->sc_scan_timer = 0;
2163			WPI_UNLOCK(sc);
2164			ieee80211_scan_next(vap);
2165			WPI_LOCK(sc);
2166			break;
2167		}
2168		}
2169	}
2170
2171	/* Tell the firmware what we have processed. */
2172	wpi_update_rx_ring(sc);
2173}
2174
2175/*
2176 * Process an INT_WAKEUP interrupt raised when the microcontroller wakes up
2177 * from power-down sleep mode.
2178 */
2179static void
2180wpi_wakeup_intr(struct wpi_softc *sc)
2181{
2182	int qid;
2183
2184	DPRINTF(sc, WPI_DEBUG_PWRSAVE,
2185	    "%s: ucode wakeup from power-down sleep\n", __func__);
2186
2187	/* Wakeup RX and TX rings. */
2188	if (sc->rxq.update) {
2189		sc->rxq.update = 0;
2190		wpi_update_rx_ring(sc);
2191	}
2192	WPI_TXQ_LOCK(sc);
2193	for (qid = 0; qid < WPI_DRV_NTXQUEUES; qid++) {
2194		struct wpi_tx_ring *ring = &sc->txq[qid];
2195
2196		if (ring->update) {
2197			ring->update = 0;
2198			wpi_update_tx_ring(sc, ring);
2199		}
2200	}
2201	WPI_TXQ_UNLOCK(sc);
2202
2203	WPI_CLRBITS(sc, WPI_GP_CNTRL, WPI_GP_CNTRL_MAC_ACCESS_REQ);
2204}
2205
2206/*
2207 * This function prints firmware registers
2208 */
2209#ifdef WPI_DEBUG
2210static void
2211wpi_debug_registers(struct wpi_softc *sc)
2212{
2213#define COUNTOF(array) (sizeof(array) / sizeof(array[0]))
2214	int i;
2215	static const uint32_t csr_tbl[] = {
2216		WPI_HW_IF_CONFIG,
2217		WPI_INT,
2218		WPI_INT_MASK,
2219		WPI_FH_INT,
2220		WPI_GPIO_IN,
2221		WPI_RESET,
2222		WPI_GP_CNTRL,
2223		WPI_EEPROM,
2224		WPI_EEPROM_GP,
2225		WPI_GIO,
2226		WPI_UCODE_GP1,
2227		WPI_UCODE_GP2,
2228		WPI_GIO_CHICKEN,
2229		WPI_ANA_PLL,
2230		WPI_DBG_HPET_MEM,
2231	};
2232	static const uint32_t prph_tbl[] = {
2233		WPI_APMG_CLK_CTRL,
2234		WPI_APMG_PS,
2235		WPI_APMG_PCI_STT,
2236		WPI_APMG_RFKILL,
2237	};
2238
2239	DPRINTF(sc, WPI_DEBUG_REGISTER,"%s","\n");
2240
2241	for (i = 0; i <  COUNTOF(csr_tbl); i++) {
2242		DPRINTF(sc, WPI_DEBUG_REGISTER, "  %-18s: 0x%08x ",
2243		    wpi_get_csr_string(csr_tbl[i]), WPI_READ(sc, csr_tbl[i]));
2244
2245		if ((i + 1) % 2 == 0)
2246			DPRINTF(sc, WPI_DEBUG_REGISTER, "\n");
2247	}
2248	DPRINTF(sc, WPI_DEBUG_REGISTER, "\n\n");
2249
2250	if (wpi_nic_lock(sc) == 0) {
2251		for (i = 0; i < COUNTOF(prph_tbl); i++) {
2252			DPRINTF(sc, WPI_DEBUG_REGISTER, "  %-18s: 0x%08x ",
2253			    wpi_get_prph_string(prph_tbl[i]),
2254			    wpi_prph_read(sc, prph_tbl[i]));
2255
2256			if ((i + 1) % 2 == 0)
2257				DPRINTF(sc, WPI_DEBUG_REGISTER, "\n");
2258		}
2259		DPRINTF(sc, WPI_DEBUG_REGISTER, "\n");
2260		wpi_nic_unlock(sc);
2261	} else {
2262		DPRINTF(sc, WPI_DEBUG_REGISTER,
2263		    "Cannot access internal registers.\n");
2264	}
2265#undef COUNTOF
2266}
2267#endif
2268
2269/*
2270 * Dump the error log of the firmware when a firmware panic occurs.  Although
2271 * we can't debug the firmware because it is neither open source nor free, it
2272 * can help us to identify certain classes of problems.
2273 */
2274static void
2275wpi_fatal_intr(struct wpi_softc *sc)
2276{
2277	struct wpi_fw_dump dump;
2278	uint32_t i, offset, count;
2279	const uint32_t size_errmsg =
2280	    (sizeof (wpi_fw_errmsg) / sizeof ((wpi_fw_errmsg)[0]));
2281
2282	/* Check that the error log address is valid. */
2283	if (sc->errptr < WPI_FW_DATA_BASE ||
2284	    sc->errptr + sizeof (dump) >
2285	    WPI_FW_DATA_BASE + WPI_FW_DATA_MAXSZ) {
2286		printf("%s: bad firmware error log address 0x%08x\n", __func__,
2287		    sc->errptr);
2288		return;
2289	}
2290	if (wpi_nic_lock(sc) != 0) {
2291		printf("%s: could not read firmware error log\n", __func__);
2292		return;
2293	}
2294	/* Read number of entries in the log. */
2295	count = wpi_mem_read(sc, sc->errptr);
2296	if (count == 0 || count * sizeof (dump) > WPI_FW_DATA_MAXSZ) {
2297		printf("%s: invalid count field (count = %u)\n", __func__,
2298		    count);
2299		wpi_nic_unlock(sc);
2300		return;
2301	}
2302	/* Skip "count" field. */
2303	offset = sc->errptr + sizeof (uint32_t);
2304	printf("firmware error log (count = %u):\n", count);
2305	for (i = 0; i < count; i++) {
2306		wpi_mem_read_region_4(sc, offset, (uint32_t *)&dump,
2307		    sizeof (dump) / sizeof (uint32_t));
2308
2309		printf("  error type = \"%s\" (0x%08X)\n",
2310		    (dump.desc < size_errmsg) ?
2311		        wpi_fw_errmsg[dump.desc] : "UNKNOWN",
2312		    dump.desc);
2313		printf("  error data      = 0x%08X\n",
2314		    dump.data);
2315		printf("  branch link     = 0x%08X%08X\n",
2316		    dump.blink[0], dump.blink[1]);
2317		printf("  interrupt link  = 0x%08X%08X\n",
2318		    dump.ilink[0], dump.ilink[1]);
2319		printf("  time            = %u\n", dump.time);
2320
2321		offset += sizeof (dump);
2322	}
2323	wpi_nic_unlock(sc);
2324	/* Dump driver status (TX and RX rings) while we're here. */
2325	printf("driver status:\n");
2326	WPI_TXQ_LOCK(sc);
2327	for (i = 0; i < WPI_DRV_NTXQUEUES; i++) {
2328		struct wpi_tx_ring *ring = &sc->txq[i];
2329		printf("  tx ring %2d: qid=%-2d cur=%-3d queued=%-3d\n",
2330		    i, ring->qid, ring->cur, ring->queued);
2331	}
2332	WPI_TXQ_UNLOCK(sc);
2333	printf("  rx ring: cur=%d\n", sc->rxq.cur);
2334}
2335
2336static void
2337wpi_intr(void *arg)
2338{
2339	struct wpi_softc *sc = arg;
2340	struct ifnet *ifp = sc->sc_ifp;
2341	uint32_t r1, r2;
2342
2343	WPI_LOCK(sc);
2344
2345	/* Disable interrupts. */
2346	WPI_WRITE(sc, WPI_INT_MASK, 0);
2347
2348	r1 = WPI_READ(sc, WPI_INT);
2349
2350	if (r1 == 0xffffffff || (r1 & 0xfffffff0) == 0xa5a5a5a0)
2351		goto end;	/* Hardware gone! */
2352
2353	r2 = WPI_READ(sc, WPI_FH_INT);
2354
2355	DPRINTF(sc, WPI_DEBUG_INTR, "%s: reg1=0x%08x reg2=0x%08x\n", __func__,
2356	    r1, r2);
2357
2358	if (r1 == 0 && r2 == 0)
2359		goto done;	/* Interrupt not for us. */
2360
2361	/* Acknowledge interrupts. */
2362	WPI_WRITE(sc, WPI_INT, r1);
2363	WPI_WRITE(sc, WPI_FH_INT, r2);
2364
2365	if (r1 & (WPI_INT_SW_ERR | WPI_INT_HW_ERR)) {
2366		struct ieee80211com *ic = ifp->if_l2com;
2367
2368		device_printf(sc->sc_dev, "fatal firmware error\n");
2369#ifdef WPI_DEBUG
2370		wpi_debug_registers(sc);
2371#endif
2372		wpi_fatal_intr(sc);
2373		DPRINTF(sc, WPI_DEBUG_HW,
2374		    "(%s)\n", (r1 & WPI_INT_SW_ERR) ? "(Software Error)" :
2375		    "(Hardware Error)");
2376		ieee80211_runtask(ic, &sc->sc_reinittask);
2377		goto end;
2378	}
2379
2380	if ((r1 & (WPI_INT_FH_RX | WPI_INT_SW_RX)) ||
2381	    (r2 & WPI_FH_INT_RX))
2382		wpi_notif_intr(sc);
2383
2384	if (r1 & WPI_INT_ALIVE)
2385		wakeup(sc);	/* Firmware is alive. */
2386
2387	if (r1 & WPI_INT_WAKEUP)
2388		wpi_wakeup_intr(sc);
2389
2390done:
2391	/* Re-enable interrupts. */
2392	if (ifp->if_flags & IFF_UP)
2393		WPI_WRITE(sc, WPI_INT_MASK, WPI_INT_MASK_DEF);
2394
2395end:	WPI_UNLOCK(sc);
2396}
2397
2398static int
2399wpi_cmd2(struct wpi_softc *sc, struct wpi_buf *buf)
2400{
2401	struct ieee80211_frame *wh;
2402	struct wpi_tx_cmd *cmd;
2403	struct wpi_tx_data *data;
2404	struct wpi_tx_desc *desc;
2405	struct wpi_tx_ring *ring;
2406	struct mbuf *m1;
2407	bus_dma_segment_t *seg, segs[WPI_MAX_SCATTER];
2408	int error, i, hdrlen, nsegs, totlen, pad;
2409
2410	WPI_TXQ_LOCK(sc);
2411
2412	KASSERT(buf->size <= sizeof(buf->data), ("buffer overflow"));
2413
2414	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
2415
2416	if (sc->txq_active == 0) {
2417		/* wpi_stop() was called */
2418		error = ENETDOWN;
2419		goto fail;
2420	}
2421
2422	wh = mtod(buf->m, struct ieee80211_frame *);
2423	hdrlen = ieee80211_anyhdrsize(wh);
2424	totlen = buf->m->m_pkthdr.len;
2425
2426	if (hdrlen & 3) {
2427		/* First segment length must be a multiple of 4. */
2428		pad = 4 - (hdrlen & 3);
2429	} else
2430		pad = 0;
2431
2432	ring = &sc->txq[buf->ac];
2433	desc = &ring->desc[ring->cur];
2434	data = &ring->data[ring->cur];
2435
2436	/* Prepare TX firmware command. */
2437	cmd = &ring->cmd[ring->cur];
2438	cmd->code = buf->code;
2439	cmd->flags = 0;
2440	cmd->qid = ring->qid;
2441	cmd->idx = ring->cur;
2442
2443	memcpy(cmd->data, buf->data, buf->size);
2444
2445	/* Save and trim IEEE802.11 header. */
2446	memcpy((uint8_t *)(cmd->data + buf->size), wh, hdrlen);
2447	m_adj(buf->m, hdrlen);
2448
2449	error = bus_dmamap_load_mbuf_sg(ring->data_dmat, data->map, buf->m,
2450	    segs, &nsegs, BUS_DMA_NOWAIT);
2451	if (error != 0 && error != EFBIG) {
2452		device_printf(sc->sc_dev,
2453		    "%s: can't map mbuf (error %d)\n", __func__, error);
2454		goto fail;
2455	}
2456	if (error != 0) {
2457		/* Too many DMA segments, linearize mbuf. */
2458		m1 = m_collapse(buf->m, M_NOWAIT, WPI_MAX_SCATTER - 1);
2459		if (m1 == NULL) {
2460			device_printf(sc->sc_dev,
2461			    "%s: could not defrag mbuf\n", __func__);
2462			error = ENOBUFS;
2463			goto fail;
2464		}
2465		buf->m = m1;
2466
2467		error = bus_dmamap_load_mbuf_sg(ring->data_dmat, data->map,
2468		    buf->m, segs, &nsegs, BUS_DMA_NOWAIT);
2469		if (error != 0) {
2470			device_printf(sc->sc_dev,
2471			    "%s: can't map mbuf (error %d)\n", __func__,
2472			    error);
2473			goto fail;
2474		}
2475	}
2476
2477	KASSERT(nsegs < WPI_MAX_SCATTER,
2478	    ("too many DMA segments, nsegs (%d) should be less than %d",
2479	     nsegs, WPI_MAX_SCATTER));
2480
2481	data->m = buf->m;
2482	data->ni = buf->ni;
2483
2484	DPRINTF(sc, WPI_DEBUG_XMIT, "%s: qid %d idx %d len %d nsegs %d\n",
2485	    __func__, ring->qid, ring->cur, totlen, nsegs);
2486
2487	/* Fill TX descriptor. */
2488	desc->nsegs = WPI_PAD32(totlen + pad) << 4 | (1 + nsegs);
2489	/* First DMA segment is used by the TX command. */
2490	desc->segs[0].addr = htole32(data->cmd_paddr);
2491	desc->segs[0].len  = htole32(4 + buf->size + hdrlen + pad);
2492	/* Other DMA segments are for data payload. */
2493	seg = &segs[0];
2494	for (i = 1; i <= nsegs; i++) {
2495		desc->segs[i].addr = htole32(seg->ds_addr);
2496		desc->segs[i].len  = htole32(seg->ds_len);
2497		seg++;
2498	}
2499
2500	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
2501	bus_dmamap_sync(ring->data_dmat, ring->cmd_dma.map,
2502	    BUS_DMASYNC_PREWRITE);
2503	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
2504	    BUS_DMASYNC_PREWRITE);
2505
2506	/* Kick TX ring. */
2507	ring->cur = (ring->cur + 1) % WPI_TX_RING_COUNT;
2508	wpi_update_tx_ring(sc, ring);
2509
2510	if (ring->qid < WPI_CMD_QUEUE_NUM) {
2511		/* Mark TX ring as full if we reach a certain threshold. */
2512		if (++ring->queued > WPI_TX_RING_HIMARK)
2513			sc->qfullmsk |= 1 << ring->qid;
2514
2515		sc->sc_tx_timer = 5;
2516	}
2517
2518	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
2519
2520	WPI_TXQ_UNLOCK(sc);
2521
2522	return 0;
2523
2524fail:	m_freem(buf->m);
2525
2526	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR, __func__);
2527
2528	WPI_TXQ_UNLOCK(sc);
2529
2530	return error;
2531}
2532
2533/*
2534 * Construct the data packet for a transmit buffer.
2535 */
2536static int
2537wpi_tx_data(struct wpi_softc *sc, struct mbuf *m, struct ieee80211_node *ni)
2538{
2539	const struct ieee80211_txparam *tp;
2540	struct ieee80211vap *vap = ni->ni_vap;
2541	struct ieee80211com *ic = ni->ni_ic;
2542	struct wpi_node *wn = WPI_NODE(ni);
2543	struct ieee80211_channel *chan;
2544	struct ieee80211_frame *wh;
2545	struct ieee80211_key *k = NULL;
2546	struct wpi_buf tx_data;
2547	struct wpi_cmd_data *tx = (struct wpi_cmd_data *)&tx_data.data;
2548	uint32_t flags;
2549	uint16_t qos;
2550	uint8_t tid, type;
2551	int ac, error, swcrypt, rate, ismcast, totlen;
2552
2553	wh = mtod(m, struct ieee80211_frame *);
2554	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
2555	ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
2556
2557	/* Select EDCA Access Category and TX ring for this frame. */
2558	if (IEEE80211_QOS_HAS_SEQ(wh)) {
2559 		qos = ((const struct ieee80211_qosframe *)wh)->i_qos[0];
2560		tid = qos & IEEE80211_QOS_TID;
2561	} else {
2562		qos = 0;
2563		tid = 0;
2564	}
2565	ac = M_WME_GETAC(m);
2566
2567	chan = (ni->ni_chan != IEEE80211_CHAN_ANYC) ?
2568		ni->ni_chan : ic->ic_curchan;
2569	tp = &vap->iv_txparms[ieee80211_chan2mode(chan)];
2570
2571	/* Choose a TX rate index. */
2572	if (type == IEEE80211_FC0_TYPE_MGT)
2573		rate = tp->mgmtrate;
2574	else if (ismcast)
2575		rate = tp->mcastrate;
2576	else if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE)
2577		rate = tp->ucastrate;
2578	else if (m->m_flags & M_EAPOL)
2579		rate = tp->mgmtrate;
2580	else {
2581		/* XXX pass pktlen */
2582		(void) ieee80211_ratectl_rate(ni, NULL, 0);
2583		rate = ni->ni_txrate;
2584	}
2585
2586	/* Encrypt the frame if need be. */
2587	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
2588		/* Retrieve key for TX. */
2589		k = ieee80211_crypto_encap(ni, m);
2590		if (k == NULL) {
2591			error = ENOBUFS;
2592			goto fail;
2593		}
2594		swcrypt = k->wk_flags & IEEE80211_KEY_SWCRYPT;
2595
2596		/* 802.11 header may have moved. */
2597		wh = mtod(m, struct ieee80211_frame *);
2598	}
2599	totlen = m->m_pkthdr.len;
2600
2601	if (ieee80211_radiotap_active_vap(vap)) {
2602		struct wpi_tx_radiotap_header *tap = &sc->sc_txtap;
2603
2604		tap->wt_flags = 0;
2605		tap->wt_rate = rate;
2606		if (k != NULL)
2607			tap->wt_flags |= IEEE80211_RADIOTAP_F_WEP;
2608
2609		ieee80211_radiotap_tx(vap, m);
2610	}
2611
2612	flags = 0;
2613	if (!ismcast) {
2614		/* Unicast frame, check if an ACK is expected. */
2615		if (!qos || (qos & IEEE80211_QOS_ACKPOLICY) !=
2616		    IEEE80211_QOS_ACKPOLICY_NOACK)
2617			flags |= WPI_TX_NEED_ACK;
2618	}
2619
2620	if (wh->i_fc[1] & IEEE80211_FC1_MORE_FRAG)
2621		flags |= WPI_TX_MORE_FRAG;	/* Cannot happen yet. */
2622
2623	/* Check if frame must be protected using RTS/CTS or CTS-to-self. */
2624	if (!ismcast) {
2625		/* NB: Group frames are sent using CCK in 802.11b/g. */
2626		if (totlen + IEEE80211_CRC_LEN > vap->iv_rtsthreshold) {
2627			flags |= WPI_TX_NEED_RTS;
2628		} else if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
2629		    WPI_RATE_IS_OFDM(rate)) {
2630			if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
2631				flags |= WPI_TX_NEED_CTS;
2632			else if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
2633				flags |= WPI_TX_NEED_RTS;
2634		}
2635
2636		if (flags & (WPI_TX_NEED_RTS | WPI_TX_NEED_CTS))
2637			flags |= WPI_TX_FULL_TXOP;
2638	}
2639
2640	memset(tx, 0, sizeof (struct wpi_cmd_data));
2641	if (type == IEEE80211_FC0_TYPE_MGT) {
2642		uint8_t subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
2643
2644		/* Tell HW to set timestamp in probe responses. */
2645		if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
2646			flags |= WPI_TX_INSERT_TSTAMP;
2647		if (subtype == IEEE80211_FC0_SUBTYPE_ASSOC_REQ ||
2648		    subtype == IEEE80211_FC0_SUBTYPE_REASSOC_REQ)
2649			tx->timeout = htole16(3);
2650		else
2651			tx->timeout = htole16(2);
2652	}
2653
2654	if (ismcast || type != IEEE80211_FC0_TYPE_DATA)
2655		tx->id = WPI_ID_BROADCAST;
2656	else {
2657		if (wn->id == WPI_ID_UNDEFINED) {
2658			device_printf(sc->sc_dev,
2659			    "%s: undefined node id\n", __func__);
2660			error = EINVAL;
2661			goto fail;
2662		}
2663
2664		tx->id = wn->id;
2665	}
2666
2667	if (type != IEEE80211_FC0_TYPE_MGT)
2668		tx->data_ntries = tp->maxretry;
2669
2670	if (k != NULL && !swcrypt) {
2671		switch (k->wk_cipher->ic_cipher) {
2672		case IEEE80211_CIPHER_AES_CCM:
2673			tx->security = WPI_CIPHER_CCMP;
2674			break;
2675
2676		default:
2677			break;
2678		}
2679
2680		memcpy(tx->key, k->wk_key, k->wk_keylen);
2681	}
2682
2683	tx->len = htole16(totlen);
2684	tx->flags = htole32(flags);
2685	tx->plcp = rate2plcp(rate);
2686	tx->tid = tid;
2687	tx->lifetime = htole32(WPI_LIFETIME_INFINITE);
2688	tx->ofdm_mask = 0xff;
2689	tx->cck_mask = 0x0f;
2690	tx->rts_ntries = 7;
2691
2692	tx_data.ni = ni;
2693	tx_data.m = m;
2694	tx_data.size = sizeof(struct wpi_cmd_data);
2695	tx_data.code = WPI_CMD_TX_DATA;
2696	tx_data.ac = ac;
2697
2698	return wpi_cmd2(sc, &tx_data);
2699
2700fail:	m_freem(m);
2701	return error;
2702}
2703
2704static int
2705wpi_tx_data_raw(struct wpi_softc *sc, struct mbuf *m,
2706    struct ieee80211_node *ni, const struct ieee80211_bpf_params *params)
2707{
2708	struct ieee80211vap *vap = ni->ni_vap;
2709	struct ieee80211_key *k = NULL;
2710	struct ieee80211_frame *wh;
2711	struct wpi_buf tx_data;
2712	struct wpi_cmd_data *tx = (struct wpi_cmd_data *)&tx_data.data;
2713	uint32_t flags;
2714	uint8_t type;
2715	int ac, rate, swcrypt, totlen;
2716
2717	wh = mtod(m, struct ieee80211_frame *);
2718	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
2719
2720	ac = params->ibp_pri & 3;
2721
2722	/* Choose a TX rate index. */
2723	rate = params->ibp_rate0;
2724
2725	flags = 0;
2726	if ((params->ibp_flags & IEEE80211_BPF_NOACK) == 0)
2727		flags |= WPI_TX_NEED_ACK;
2728	if (params->ibp_flags & IEEE80211_BPF_RTS)
2729		flags |= WPI_TX_NEED_RTS;
2730	if (params->ibp_flags & IEEE80211_BPF_CTS)
2731		flags |= WPI_TX_NEED_CTS;
2732	if (flags & (WPI_TX_NEED_RTS | WPI_TX_NEED_CTS))
2733		flags |= WPI_TX_FULL_TXOP;
2734
2735	/* Encrypt the frame if need be. */
2736	if (params->ibp_flags & IEEE80211_BPF_CRYPTO) {
2737		/* Retrieve key for TX. */
2738		k = ieee80211_crypto_encap(ni, m);
2739		if (k == NULL) {
2740			m_freem(m);
2741			return ENOBUFS;
2742		}
2743		swcrypt = k->wk_flags & IEEE80211_KEY_SWCRYPT;
2744
2745		/* 802.11 header may have moved. */
2746		wh = mtod(m, struct ieee80211_frame *);
2747	}
2748	totlen = m->m_pkthdr.len;
2749
2750	if (ieee80211_radiotap_active_vap(vap)) {
2751		struct wpi_tx_radiotap_header *tap = &sc->sc_txtap;
2752
2753		tap->wt_flags = 0;
2754		tap->wt_rate = rate;
2755		if (params->ibp_flags & IEEE80211_BPF_CRYPTO)
2756			tap->wt_flags |= IEEE80211_RADIOTAP_F_WEP;
2757
2758		ieee80211_radiotap_tx(vap, m);
2759	}
2760
2761	memset(tx, 0, sizeof (struct wpi_cmd_data));
2762	if (type == IEEE80211_FC0_TYPE_MGT) {
2763		uint8_t subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
2764
2765		/* Tell HW to set timestamp in probe responses. */
2766		if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
2767			flags |= WPI_TX_INSERT_TSTAMP;
2768		if (subtype == IEEE80211_FC0_SUBTYPE_ASSOC_REQ ||
2769		    subtype == IEEE80211_FC0_SUBTYPE_REASSOC_REQ)
2770			tx->timeout = htole16(3);
2771		else
2772			tx->timeout = htole16(2);
2773	}
2774
2775	if (k != NULL && !swcrypt) {
2776		switch (k->wk_cipher->ic_cipher) {
2777		case IEEE80211_CIPHER_AES_CCM:
2778			tx->security = WPI_CIPHER_CCMP;
2779			break;
2780
2781		default:
2782			break;
2783		}
2784
2785		memcpy(tx->key, k->wk_key, k->wk_keylen);
2786	}
2787
2788	tx->len = htole16(totlen);
2789	tx->flags = htole32(flags);
2790	tx->plcp = rate2plcp(rate);
2791	tx->id = WPI_ID_BROADCAST;
2792	tx->lifetime = htole32(WPI_LIFETIME_INFINITE);
2793	tx->rts_ntries = params->ibp_try1;
2794	tx->data_ntries = params->ibp_try0;
2795
2796	tx_data.ni = ni;
2797	tx_data.m = m;
2798	tx_data.size = sizeof(struct wpi_cmd_data);
2799	tx_data.code = WPI_CMD_TX_DATA;
2800	tx_data.ac = ac;
2801
2802	return wpi_cmd2(sc, &tx_data);
2803}
2804
2805static int
2806wpi_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
2807    const struct ieee80211_bpf_params *params)
2808{
2809	struct ieee80211com *ic = ni->ni_ic;
2810	struct ifnet *ifp = ic->ic_ifp;
2811	struct wpi_softc *sc = ifp->if_softc;
2812	int error = 0;
2813
2814	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
2815
2816	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
2817		ieee80211_free_node(ni);
2818		m_freem(m);
2819		return ENETDOWN;
2820	}
2821
2822	WPI_LOCK(sc);
2823	if (params == NULL) {
2824		/*
2825		 * Legacy path; interpret frame contents to decide
2826		 * precisely how to send the frame.
2827		 */
2828		error = wpi_tx_data(sc, m, ni);
2829	} else {
2830		/*
2831		 * Caller supplied explicit parameters to use in
2832		 * sending the frame.
2833		 */
2834		error = wpi_tx_data_raw(sc, m, ni, params);
2835	}
2836	WPI_UNLOCK(sc);
2837
2838	if (error != 0) {
2839		/* NB: m is reclaimed on tx failure */
2840		ieee80211_free_node(ni);
2841		if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
2842
2843		DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR, __func__);
2844
2845		return error;
2846	}
2847
2848	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
2849
2850	return 0;
2851}
2852
2853/**
2854 * Process data waiting to be sent on the IFNET output queue
2855 */
2856static void
2857wpi_start(struct ifnet *ifp)
2858{
2859	struct wpi_softc *sc = ifp->if_softc;
2860
2861	WPI_LOCK(sc);
2862	wpi_start_locked(ifp);
2863	WPI_UNLOCK(sc);
2864}
2865
2866static void
2867wpi_start_locked(struct ifnet *ifp)
2868{
2869	struct wpi_softc *sc = ifp->if_softc;
2870	struct ieee80211_node *ni;
2871	struct mbuf *m;
2872
2873	WPI_LOCK_ASSERT(sc);
2874
2875	DPRINTF(sc, WPI_DEBUG_XMIT, "%s: called\n", __func__);
2876
2877	IF_LOCK(&ifp->if_snd);
2878	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 ||
2879	    (ifp->if_drv_flags & IFF_DRV_OACTIVE)) {
2880		IF_UNLOCK(&ifp->if_snd);
2881		return;
2882	}
2883	IF_UNLOCK(&ifp->if_snd);
2884
2885	for (;;) {
2886		if (sc->qfullmsk != 0) {
2887			IF_LOCK(&ifp->if_snd);
2888			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
2889			IF_UNLOCK(&ifp->if_snd);
2890			break;
2891		}
2892		IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
2893		if (m == NULL)
2894			break;
2895		ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
2896		if (wpi_tx_data(sc, m, ni) != 0) {
2897			WPI_UNLOCK(sc);
2898			ieee80211_free_node(ni);
2899			WPI_LOCK(sc);
2900			if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
2901		}
2902	}
2903
2904	DPRINTF(sc, WPI_DEBUG_XMIT, "%s: done\n", __func__);
2905}
2906
2907static void
2908wpi_start_task(void *arg0, int pending)
2909{
2910	struct wpi_softc *sc = arg0;
2911	struct ifnet *ifp = sc->sc_ifp;
2912
2913	wpi_start(ifp);
2914}
2915
2916static void
2917wpi_watchdog_rfkill(void *arg)
2918{
2919	struct wpi_softc *sc = arg;
2920	struct ifnet *ifp = sc->sc_ifp;
2921	struct ieee80211com *ic = ifp->if_l2com;
2922
2923	DPRINTF(sc, WPI_DEBUG_WATCHDOG, "RFkill Watchdog: tick\n");
2924
2925	/* No need to lock firmware memory. */
2926	if ((wpi_prph_read(sc, WPI_APMG_RFKILL) & 0x1) == 0) {
2927		/* Radio kill switch is still off. */
2928		callout_reset(&sc->watchdog_rfkill, hz, wpi_watchdog_rfkill,
2929		    sc);
2930	} else
2931		ieee80211_runtask(ic, &sc->sc_radioon_task);
2932}
2933
2934/**
2935 * Called every second, wpi_watchdog used by the watch dog timer
2936 * to check that the card is still alive
2937 */
2938static void
2939wpi_watchdog(void *arg)
2940{
2941	struct wpi_softc *sc = arg;
2942	struct ifnet *ifp = sc->sc_ifp;
2943	struct ieee80211com *ic = ifp->if_l2com;
2944
2945	DPRINTF(sc, WPI_DEBUG_WATCHDOG, "Watchdog: tick\n");
2946
2947	if (sc->sc_tx_timer > 0) {
2948		if (--sc->sc_tx_timer == 0) {
2949			if_printf(ifp, "device timeout\n");
2950			if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
2951			ieee80211_runtask(ic, &sc->sc_reinittask);
2952		}
2953	}
2954
2955	if (sc->sc_scan_timer > 0) {
2956		struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2957		if (--sc->sc_scan_timer == 0 && vap != NULL) {
2958			if_printf(ifp, "scan timeout\n");
2959			ieee80211_cancel_scan(vap);
2960			ieee80211_runtask(ic, &sc->sc_reinittask);
2961		}
2962	}
2963
2964	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
2965		callout_reset(&sc->watchdog_to, hz, wpi_watchdog, sc);
2966}
2967
2968static int
2969wpi_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
2970{
2971	struct wpi_softc *sc = ifp->if_softc;
2972	struct ieee80211com *ic = ifp->if_l2com;
2973	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2974	struct ifreq *ifr = (struct ifreq *) data;
2975	int error = 0;
2976
2977	switch (cmd) {
2978	case SIOCGIFADDR:
2979		error = ether_ioctl(ifp, cmd, data);
2980		break;
2981	case SIOCSIFFLAGS:
2982		if (ifp->if_flags & IFF_UP) {
2983			wpi_init(sc);
2984
2985			if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 &&
2986			    vap != NULL)
2987				ieee80211_stop(vap);
2988		} else if ((ifp->if_drv_flags & IFF_DRV_RUNNING) != 0)
2989			wpi_stop(sc);
2990		break;
2991	case SIOCGIFMEDIA:
2992		error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
2993		break;
2994	default:
2995		error = EINVAL;
2996		break;
2997	}
2998	return error;
2999}
3000
3001/*
3002 * Send a command to the firmware.
3003 */
3004static int
3005wpi_cmd(struct wpi_softc *sc, int code, const void *buf, size_t size,
3006    int async)
3007{
3008	struct wpi_tx_ring *ring = &sc->txq[WPI_CMD_QUEUE_NUM];
3009	struct wpi_tx_desc *desc;
3010	struct wpi_tx_data *data;
3011	struct wpi_tx_cmd *cmd;
3012	struct mbuf *m;
3013	bus_addr_t paddr;
3014	int totlen, error;
3015
3016	WPI_TXQ_LOCK(sc);
3017
3018	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
3019
3020	if (sc->txq_active == 0) {
3021		/* wpi_stop() was called */
3022		error = 0;
3023		goto fail;
3024	}
3025
3026	if (async == 0)
3027		WPI_LOCK_ASSERT(sc);
3028
3029	DPRINTF(sc, WPI_DEBUG_CMD, "wpi_cmd %s size %zu async %d\n",
3030	    wpi_cmd_str(code), size, async);
3031
3032	desc = &ring->desc[ring->cur];
3033	data = &ring->data[ring->cur];
3034	totlen = 4 + size;
3035
3036	if (size > sizeof cmd->data) {
3037		/* Command is too large to fit in a descriptor. */
3038		if (totlen > MCLBYTES) {
3039			error = EINVAL;
3040			goto fail;
3041		}
3042		m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, MJUMPAGESIZE);
3043		if (m == NULL) {
3044			error = ENOMEM;
3045			goto fail;
3046		}
3047		cmd = mtod(m, struct wpi_tx_cmd *);
3048		error = bus_dmamap_load(ring->data_dmat, data->map, cmd,
3049		    totlen, wpi_dma_map_addr, &paddr, BUS_DMA_NOWAIT);
3050		if (error != 0) {
3051			m_freem(m);
3052			goto fail;
3053		}
3054		data->m = m;
3055	} else {
3056		cmd = &ring->cmd[ring->cur];
3057		paddr = data->cmd_paddr;
3058	}
3059
3060	cmd->code = code;
3061	cmd->flags = 0;
3062	cmd->qid = ring->qid;
3063	cmd->idx = ring->cur;
3064	memcpy(cmd->data, buf, size);
3065
3066	desc->nsegs = 1 + (WPI_PAD32(size) << 4);
3067	desc->segs[0].addr = htole32(paddr);
3068	desc->segs[0].len  = htole32(totlen);
3069
3070	if (size > sizeof cmd->data) {
3071		bus_dmamap_sync(ring->data_dmat, data->map,
3072		    BUS_DMASYNC_PREWRITE);
3073	} else {
3074		bus_dmamap_sync(ring->data_dmat, ring->cmd_dma.map,
3075		    BUS_DMASYNC_PREWRITE);
3076	}
3077	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
3078	    BUS_DMASYNC_PREWRITE);
3079
3080	/* Kick command ring. */
3081	ring->cur = (ring->cur + 1) % WPI_TX_RING_COUNT;
3082	wpi_update_tx_ring(sc, ring);
3083
3084	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
3085
3086	WPI_TXQ_UNLOCK(sc);
3087
3088	if (async)
3089		return 0;
3090
3091	return mtx_sleep(cmd, &sc->sc_mtx, PCATCH, "wpicmd", hz);
3092
3093fail:	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR, __func__);
3094
3095	WPI_TXQ_UNLOCK(sc);
3096
3097	return error;
3098}
3099
3100/*
3101 * Configure HW multi-rate retries.
3102 */
3103static int
3104wpi_mrr_setup(struct wpi_softc *sc)
3105{
3106	struct ifnet *ifp = sc->sc_ifp;
3107	struct ieee80211com *ic = ifp->if_l2com;
3108	struct wpi_mrr_setup mrr;
3109	int i, error;
3110
3111	/* CCK rates (not used with 802.11a). */
3112	for (i = WPI_RIDX_CCK1; i <= WPI_RIDX_CCK11; i++) {
3113		mrr.rates[i].flags = 0;
3114		mrr.rates[i].plcp = wpi_ridx_to_plcp[i];
3115		/* Fallback to the immediate lower CCK rate (if any.) */
3116		mrr.rates[i].next =
3117		    (i == WPI_RIDX_CCK1) ? WPI_RIDX_CCK1 : i - 1;
3118		/* Try one time at this rate before falling back to "next". */
3119		mrr.rates[i].ntries = 1;
3120	}
3121	/* OFDM rates (not used with 802.11b). */
3122	for (i = WPI_RIDX_OFDM6; i <= WPI_RIDX_OFDM54; i++) {
3123		mrr.rates[i].flags = 0;
3124		mrr.rates[i].plcp = wpi_ridx_to_plcp[i];
3125		/* Fallback to the immediate lower rate (if any.) */
3126		/* We allow fallback from OFDM/6 to CCK/2 in 11b/g mode. */
3127		mrr.rates[i].next = (i == WPI_RIDX_OFDM6) ?
3128		    ((ic->ic_curmode == IEEE80211_MODE_11A) ?
3129			WPI_RIDX_OFDM6 : WPI_RIDX_CCK2) :
3130		    i - 1;
3131		/* Try one time at this rate before falling back to "next". */
3132		mrr.rates[i].ntries = 1;
3133	}
3134	/* Setup MRR for control frames. */
3135	mrr.which = htole32(WPI_MRR_CTL);
3136	error = wpi_cmd(sc, WPI_CMD_MRR_SETUP, &mrr, sizeof mrr, 0);
3137	if (error != 0) {
3138		device_printf(sc->sc_dev,
3139		    "could not setup MRR for control frames\n");
3140		return error;
3141	}
3142	/* Setup MRR for data frames. */
3143	mrr.which = htole32(WPI_MRR_DATA);
3144	error = wpi_cmd(sc, WPI_CMD_MRR_SETUP, &mrr, sizeof mrr, 0);
3145	if (error != 0) {
3146		device_printf(sc->sc_dev,
3147		    "could not setup MRR for data frames\n");
3148		return error;
3149	}
3150	return 0;
3151}
3152
3153static int
3154wpi_add_node(struct wpi_softc *sc, struct ieee80211_node *ni)
3155{
3156	struct ieee80211com *ic = ni->ni_ic;
3157	struct wpi_vap *wvp = WPI_VAP(ni->ni_vap);
3158	struct wpi_node *wn = WPI_NODE(ni);
3159	struct wpi_node_info node;
3160	int error;
3161
3162	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
3163
3164	if (wn->id == WPI_ID_UNDEFINED)
3165		return EINVAL;
3166
3167	memset(&node, 0, sizeof node);
3168	IEEE80211_ADDR_COPY(node.macaddr, ni->ni_macaddr);
3169	node.id = wn->id;
3170	node.plcp = (ic->ic_curmode == IEEE80211_MODE_11A) ?
3171	    wpi_ridx_to_plcp[WPI_RIDX_OFDM6] : wpi_ridx_to_plcp[WPI_RIDX_CCK1];
3172	node.action = htole32(WPI_ACTION_SET_RATE);
3173	node.antenna = WPI_ANTENNA_BOTH;
3174
3175	DPRINTF(sc, WPI_DEBUG_NODE, "%s: adding node %d (%s)\n", __func__,
3176	    wn->id, ether_sprintf(ni->ni_macaddr));
3177
3178	error = wpi_cmd(sc, WPI_CMD_ADD_NODE, &node, sizeof node, 1);
3179	if (error != 0) {
3180		device_printf(sc->sc_dev,
3181		    "%s: wpi_cmd() call failed with error code %d\n", __func__,
3182		    error);
3183		return error;
3184	}
3185
3186	if (wvp->wv_gtk != 0) {
3187		error = wpi_set_global_keys(ni);
3188		if (error != 0) {
3189			device_printf(sc->sc_dev,
3190			    "%s: error while setting global keys\n", __func__);
3191			return ENXIO;
3192		}
3193	}
3194
3195	return 0;
3196}
3197
3198/*
3199 * Broadcast node is used to send group-addressed and management frames.
3200 */
3201static int
3202wpi_add_broadcast_node(struct wpi_softc *sc, int async)
3203{
3204	struct ifnet *ifp = sc->sc_ifp;
3205	struct ieee80211com *ic = ifp->if_l2com;
3206	struct wpi_node_info node;
3207
3208	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
3209
3210	memset(&node, 0, sizeof node);
3211	IEEE80211_ADDR_COPY(node.macaddr, ifp->if_broadcastaddr);
3212	node.id = WPI_ID_BROADCAST;
3213	node.plcp = (ic->ic_curmode == IEEE80211_MODE_11A) ?
3214	    wpi_ridx_to_plcp[WPI_RIDX_OFDM6] : wpi_ridx_to_plcp[WPI_RIDX_CCK1];
3215	node.action = htole32(WPI_ACTION_SET_RATE);
3216	node.antenna = WPI_ANTENNA_BOTH;
3217
3218	DPRINTF(sc, WPI_DEBUG_NODE, "%s: adding broadcast node\n", __func__);
3219
3220	return wpi_cmd(sc, WPI_CMD_ADD_NODE, &node, sizeof node, async);
3221}
3222
3223static int
3224wpi_add_sta_node(struct wpi_softc *sc, struct ieee80211_node *ni)
3225{
3226	struct wpi_node *wn = WPI_NODE(ni);
3227	int error;
3228
3229	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
3230
3231	wn->id = wpi_add_node_entry_sta(sc);
3232
3233	if ((error = wpi_add_node(sc, ni)) != 0) {
3234		wpi_del_node_entry(sc, wn->id);
3235		wn->id = WPI_ID_UNDEFINED;
3236		return error;
3237	}
3238
3239	return 0;
3240}
3241
3242static int
3243wpi_add_ibss_node(struct wpi_softc *sc, struct ieee80211_node *ni)
3244{
3245	struct wpi_node *wn = WPI_NODE(ni);
3246	int error;
3247
3248	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
3249
3250	if (wn->id != WPI_ID_UNDEFINED)
3251		return EINVAL;
3252
3253	if ((wn->id = wpi_add_node_entry_adhoc(sc)) == WPI_ID_UNDEFINED) {
3254		device_printf(sc->sc_dev, "%s: h/w table is full\n", __func__);
3255		return ENOMEM;
3256	}
3257
3258	if ((error = wpi_add_node(sc, ni)) != 0) {
3259		wpi_del_node_entry(sc, wn->id);
3260		wn->id = WPI_ID_UNDEFINED;
3261		return error;
3262	}
3263
3264	return 0;
3265}
3266
3267static void
3268wpi_del_node(struct wpi_softc *sc, struct ieee80211_node *ni)
3269{
3270	struct wpi_node *wn = WPI_NODE(ni);
3271	struct wpi_cmd_del_node node;
3272	int error;
3273
3274	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
3275
3276	if (wn->id == WPI_ID_UNDEFINED) {
3277		device_printf(sc->sc_dev, "%s: undefined node id passed\n",
3278		    __func__);
3279		return;
3280	}
3281
3282	memset(&node, 0, sizeof node);
3283	IEEE80211_ADDR_COPY(node.macaddr, ni->ni_macaddr);
3284	node.count = 1;
3285
3286	DPRINTF(sc, WPI_DEBUG_NODE, "%s: deleting node %d (%s)\n", __func__,
3287	    wn->id, ether_sprintf(ni->ni_macaddr));
3288
3289	error = wpi_cmd(sc, WPI_CMD_DEL_NODE, &node, sizeof node, 1);
3290	if (error != 0) {
3291		device_printf(sc->sc_dev,
3292		    "%s: could not delete node %u, error %d\n", __func__,
3293		    wn->id, error);
3294	}
3295}
3296
3297static int
3298wpi_updateedca(struct ieee80211com *ic)
3299{
3300#define WPI_EXP2(x)	((1 << (x)) - 1)	/* CWmin = 2^ECWmin - 1 */
3301	struct wpi_softc *sc = ic->ic_ifp->if_softc;
3302	struct wpi_edca_params cmd;
3303	int aci, error;
3304
3305	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
3306
3307	memset(&cmd, 0, sizeof cmd);
3308	cmd.flags = htole32(WPI_EDCA_UPDATE);
3309	for (aci = 0; aci < WME_NUM_AC; aci++) {
3310		const struct wmeParams *ac =
3311		    &ic->ic_wme.wme_chanParams.cap_wmeParams[aci];
3312		cmd.ac[aci].aifsn = ac->wmep_aifsn;
3313		cmd.ac[aci].cwmin = htole16(WPI_EXP2(ac->wmep_logcwmin));
3314		cmd.ac[aci].cwmax = htole16(WPI_EXP2(ac->wmep_logcwmax));
3315		cmd.ac[aci].txoplimit =
3316		    htole16(IEEE80211_TXOP_TO_US(ac->wmep_txopLimit));
3317
3318		DPRINTF(sc, WPI_DEBUG_EDCA,
3319		    "setting WME for queue %d aifsn=%d cwmin=%d cwmax=%d "
3320		    "txoplimit=%d\n", aci, cmd.ac[aci].aifsn,
3321		    cmd.ac[aci].cwmin, cmd.ac[aci].cwmax,
3322		    cmd.ac[aci].txoplimit);
3323	}
3324	error = wpi_cmd(sc, WPI_CMD_EDCA_PARAMS, &cmd, sizeof cmd, 1);
3325
3326	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
3327
3328	return error;
3329#undef WPI_EXP2
3330}
3331
3332static void
3333wpi_set_promisc(struct wpi_softc *sc)
3334{
3335	struct ifnet *ifp = sc->sc_ifp;
3336	uint32_t promisc_filter;
3337
3338	promisc_filter = WPI_FILTER_PROMISC | WPI_FILTER_CTL;
3339
3340	if (ifp->if_flags & IFF_PROMISC)
3341		sc->rxon.filter |= htole32(promisc_filter);
3342	else
3343		sc->rxon.filter &= ~htole32(promisc_filter);
3344}
3345
3346static void
3347wpi_update_promisc(struct ifnet *ifp)
3348{
3349	struct wpi_softc *sc = ifp->if_softc;
3350
3351	WPI_LOCK(sc);
3352	wpi_set_promisc(sc);
3353
3354	if (wpi_send_rxon(sc, 1, 1) != 0) {
3355		device_printf(sc->sc_dev, "%s: could not send RXON\n",
3356		    __func__);
3357	}
3358	WPI_UNLOCK(sc);
3359}
3360
3361static void
3362wpi_update_mcast(struct ifnet *ifp)
3363{
3364	/* Ignore */
3365}
3366
3367static void
3368wpi_set_led(struct wpi_softc *sc, uint8_t which, uint8_t off, uint8_t on)
3369{
3370	struct wpi_cmd_led led;
3371
3372	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
3373
3374	led.which = which;
3375	led.unit = htole32(100000);	/* on/off in unit of 100ms */
3376	led.off = off;
3377	led.on = on;
3378	(void)wpi_cmd(sc, WPI_CMD_SET_LED, &led, sizeof led, 1);
3379}
3380
3381static int
3382wpi_set_timing(struct wpi_softc *sc, struct ieee80211_node *ni)
3383{
3384	struct wpi_cmd_timing cmd;
3385	uint64_t val, mod;
3386
3387	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
3388
3389	memset(&cmd, 0, sizeof cmd);
3390	memcpy(&cmd.tstamp, ni->ni_tstamp.data, sizeof (uint64_t));
3391	cmd.bintval = htole16(ni->ni_intval);
3392	cmd.lintval = htole16(10);
3393
3394	/* Compute remaining time until next beacon. */
3395	val = (uint64_t)ni->ni_intval * IEEE80211_DUR_TU;
3396	mod = le64toh(cmd.tstamp) % val;
3397	cmd.binitval = htole32((uint32_t)(val - mod));
3398
3399	DPRINTF(sc, WPI_DEBUG_RESET, "timing bintval=%u tstamp=%ju, init=%u\n",
3400	    ni->ni_intval, le64toh(cmd.tstamp), (uint32_t)(val - mod));
3401
3402	return wpi_cmd(sc, WPI_CMD_TIMING, &cmd, sizeof cmd, 1);
3403}
3404
3405/*
3406 * This function is called periodically (every 60 seconds) to adjust output
3407 * power to temperature changes.
3408 */
3409static void
3410wpi_power_calibration(struct wpi_softc *sc)
3411{
3412	int temp;
3413
3414	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
3415
3416	/* Update sensor data. */
3417	temp = (int)WPI_READ(sc, WPI_UCODE_GP2);
3418	DPRINTF(sc, WPI_DEBUG_TEMP, "Temp in calibration is: %d\n", temp);
3419
3420	/* Sanity-check read value. */
3421	if (temp < -260 || temp > 25) {
3422		/* This can't be correct, ignore. */
3423		DPRINTF(sc, WPI_DEBUG_TEMP,
3424		    "out-of-range temperature reported: %d\n", temp);
3425		return;
3426	}
3427
3428	DPRINTF(sc, WPI_DEBUG_TEMP, "temperature %d->%d\n", sc->temp, temp);
3429
3430	/* Adjust Tx power if need be. */
3431	if (abs(temp - sc->temp) <= 6)
3432		return;
3433
3434	sc->temp = temp;
3435
3436	if (wpi_set_txpower(sc, 1) != 0) {
3437		/* just warn, too bad for the automatic calibration... */
3438		device_printf(sc->sc_dev,"could not adjust Tx power\n");
3439	}
3440}
3441
3442/*
3443 * Set TX power for current channel.
3444 */
3445static int
3446wpi_set_txpower(struct wpi_softc *sc, int async)
3447{
3448	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
3449	struct ieee80211_channel *ch;
3450	struct wpi_power_group *group;
3451	struct wpi_cmd_txpower cmd;
3452	uint8_t chan;
3453	int idx, i;
3454
3455	/* Retrieve current channel from last RXON. */
3456	chan = sc->rxon.chan;
3457	ch = &ic->ic_channels[chan];
3458
3459	/* Find the TX power group to which this channel belongs. */
3460	if (IEEE80211_IS_CHAN_5GHZ(ch)) {
3461		for (group = &sc->groups[1]; group < &sc->groups[4]; group++)
3462			if (chan <= group->chan)
3463				break;
3464	} else
3465		group = &sc->groups[0];
3466
3467	memset(&cmd, 0, sizeof cmd);
3468	cmd.band = IEEE80211_IS_CHAN_5GHZ(ch) ? 0 : 1;
3469	cmd.chan = htole16(chan);
3470
3471	/* Set TX power for all OFDM and CCK rates. */
3472	for (i = 0; i <= WPI_RIDX_MAX ; i++) {
3473		/* Retrieve TX power for this channel/rate. */
3474		idx = wpi_get_power_index(sc, group, ch, i);
3475
3476		cmd.rates[i].plcp = wpi_ridx_to_plcp[i];
3477
3478		if (IEEE80211_IS_CHAN_5GHZ(ch)) {
3479			cmd.rates[i].rf_gain = wpi_rf_gain_5ghz[idx];
3480			cmd.rates[i].dsp_gain = wpi_dsp_gain_5ghz[idx];
3481		} else {
3482			cmd.rates[i].rf_gain = wpi_rf_gain_2ghz[idx];
3483			cmd.rates[i].dsp_gain = wpi_dsp_gain_2ghz[idx];
3484		}
3485		DPRINTF(sc, WPI_DEBUG_TEMP,
3486		    "chan %d/ridx %d: power index %d\n", chan, i, idx);
3487	}
3488
3489	return wpi_cmd(sc, WPI_CMD_TXPOWER, &cmd, sizeof cmd, async);
3490}
3491
3492/*
3493 * Determine Tx power index for a given channel/rate combination.
3494 * This takes into account the regulatory information from EEPROM and the
3495 * current temperature.
3496 */
3497static int
3498wpi_get_power_index(struct wpi_softc *sc, struct wpi_power_group *group,
3499    struct ieee80211_channel *c, int ridx)
3500{
3501/* Fixed-point arithmetic division using a n-bit fractional part. */
3502#define fdivround(a, b, n)	\
3503	((((1 << n) * (a)) / (b) + (1 << n) / 2) / (1 << n))
3504
3505/* Linear interpolation. */
3506#define interpolate(x, x1, y1, x2, y2, n)	\
3507	((y1) + fdivround(((x) - (x1)) * ((y2) - (y1)), (x2) - (x1), n))
3508
3509	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
3510	struct wpi_power_sample *sample;
3511	int pwr, idx;
3512	u_int chan;
3513
3514	/* Get channel number. */
3515	chan = ieee80211_chan2ieee(ic, c);
3516
3517	/* Default TX power is group maximum TX power minus 3dB. */
3518	pwr = group->maxpwr / 2;
3519
3520	/* Decrease TX power for highest OFDM rates to reduce distortion. */
3521	switch (ridx) {
3522	case WPI_RIDX_OFDM36:
3523		pwr -= IEEE80211_IS_CHAN_2GHZ(c) ? 0 :  5;
3524		break;
3525	case WPI_RIDX_OFDM48:
3526		pwr -= IEEE80211_IS_CHAN_2GHZ(c) ? 7 : 10;
3527		break;
3528	case WPI_RIDX_OFDM54:
3529		pwr -= IEEE80211_IS_CHAN_2GHZ(c) ? 9 : 12;
3530		break;
3531	}
3532
3533	/* Never exceed the channel maximum allowed TX power. */
3534	pwr = min(pwr, sc->maxpwr[chan]);
3535
3536	/* Retrieve TX power index into gain tables from samples. */
3537	for (sample = group->samples; sample < &group->samples[3]; sample++)
3538		if (pwr > sample[1].power)
3539			break;
3540	/* Fixed-point linear interpolation using a 19-bit fractional part. */
3541	idx = interpolate(pwr, sample[0].power, sample[0].index,
3542	    sample[1].power, sample[1].index, 19);
3543
3544	/*-
3545	 * Adjust power index based on current temperature:
3546	 * - if cooler than factory-calibrated: decrease output power
3547	 * - if warmer than factory-calibrated: increase output power
3548	 */
3549	idx -= (sc->temp - group->temp) * 11 / 100;
3550
3551	/* Decrease TX power for CCK rates (-5dB). */
3552	if (ridx >= WPI_RIDX_CCK1)
3553		idx += 10;
3554
3555	/* Make sure idx stays in a valid range. */
3556	if (idx < 0)
3557		return 0;
3558	if (idx > WPI_MAX_PWR_INDEX)
3559		return WPI_MAX_PWR_INDEX;
3560	return idx;
3561
3562#undef interpolate
3563#undef fdivround
3564}
3565
3566/*
3567 * Set STA mode power saving level (between 0 and 5).
3568 * Level 0 is CAM (Continuously Aware Mode), 5 is for maximum power saving.
3569 */
3570static int
3571wpi_set_pslevel(struct wpi_softc *sc, uint8_t dtim, int level, int async)
3572{
3573	struct wpi_pmgt_cmd cmd;
3574	const struct wpi_pmgt *pmgt;
3575	uint32_t max, skip_dtim;
3576	uint32_t reg;
3577	int i;
3578
3579	DPRINTF(sc, WPI_DEBUG_PWRSAVE,
3580	    "%s: dtim=%d, level=%d, async=%d\n",
3581	    __func__, dtim, level, async);
3582
3583	/* Select which PS parameters to use. */
3584	if (dtim <= 10)
3585		pmgt = &wpi_pmgt[0][level];
3586	else
3587		pmgt = &wpi_pmgt[1][level];
3588
3589	memset(&cmd, 0, sizeof cmd);
3590	if (level != 0)	/* not CAM */
3591		cmd.flags |= htole16(WPI_PS_ALLOW_SLEEP);
3592	/* Retrieve PCIe Active State Power Management (ASPM). */
3593	reg = pci_read_config(sc->sc_dev, sc->sc_cap_off + 0x10, 1);
3594	if (!(reg & 0x1))	/* L0s Entry disabled. */
3595		cmd.flags |= htole16(WPI_PS_PCI_PMGT);
3596
3597	cmd.rxtimeout = htole32(pmgt->rxtimeout * IEEE80211_DUR_TU);
3598	cmd.txtimeout = htole32(pmgt->txtimeout * IEEE80211_DUR_TU);
3599
3600	if (dtim == 0) {
3601		dtim = 1;
3602		skip_dtim = 0;
3603	} else
3604		skip_dtim = pmgt->skip_dtim;
3605
3606	if (skip_dtim != 0) {
3607		cmd.flags |= htole16(WPI_PS_SLEEP_OVER_DTIM);
3608		max = pmgt->intval[4];
3609		if (max == (uint32_t)-1)
3610			max = dtim * (skip_dtim + 1);
3611		else if (max > dtim)
3612			max = (max / dtim) * dtim;
3613	} else
3614		max = dtim;
3615
3616	for (i = 0; i < 5; i++)
3617		cmd.intval[i] = htole32(MIN(max, pmgt->intval[i]));
3618
3619	return wpi_cmd(sc, WPI_CMD_SET_POWER_MODE, &cmd, sizeof cmd, async);
3620}
3621
3622static int
3623wpi_send_btcoex(struct wpi_softc *sc)
3624{
3625	struct wpi_bluetooth cmd;
3626
3627	memset(&cmd, 0, sizeof cmd);
3628	cmd.flags = WPI_BT_COEX_MODE_4WIRE;
3629	cmd.lead_time = WPI_BT_LEAD_TIME_DEF;
3630	cmd.max_kill = WPI_BT_MAX_KILL_DEF;
3631	DPRINTF(sc, WPI_DEBUG_RESET, "%s: configuring bluetooth coexistence\n",
3632	    __func__);
3633	return wpi_cmd(sc, WPI_CMD_BT_COEX, &cmd, sizeof(cmd), 0);
3634}
3635
3636static int
3637wpi_send_rxon(struct wpi_softc *sc, int assoc, int async)
3638{
3639	int error;
3640
3641	if (assoc && (sc->rxon.filter & htole32(WPI_FILTER_BSS))) {
3642		struct wpi_assoc rxon_assoc;
3643
3644		rxon_assoc.flags = sc->rxon.flags;
3645		rxon_assoc.filter = sc->rxon.filter;
3646		rxon_assoc.ofdm_mask = sc->rxon.ofdm_mask;
3647		rxon_assoc.cck_mask = sc->rxon.cck_mask;
3648		rxon_assoc.reserved = 0;
3649
3650		error = wpi_cmd(sc, WPI_CMD_RXON_ASSOC, &rxon_assoc,
3651		    sizeof (struct wpi_assoc), async);
3652	} else {
3653		if (async)
3654			WPI_NT_LOCK(sc);
3655
3656		error = wpi_cmd(sc, WPI_CMD_RXON, &sc->rxon,
3657		    sizeof (struct wpi_rxon), async);
3658
3659		wpi_clear_node_table(sc);
3660
3661		if (async)
3662			WPI_NT_UNLOCK(sc);
3663	}
3664	if (error != 0) {
3665		device_printf(sc->sc_dev, "RXON command failed, error %d\n",
3666		    error);
3667		return error;
3668	}
3669
3670	/* Configuration has changed, set Tx power accordingly. */
3671	if ((error = wpi_set_txpower(sc, async)) != 0) {
3672		device_printf(sc->sc_dev,
3673		    "%s: could not set TX power, error %d\n", __func__, error);
3674		return error;
3675	}
3676
3677	if (!(sc->rxon.filter & htole32(WPI_FILTER_BSS))) {
3678		/* Add broadcast node. */
3679		error = wpi_add_broadcast_node(sc, async);
3680		if (error != 0) {
3681			device_printf(sc->sc_dev,
3682			    "could not add broadcast node, error %d\n", error);
3683			return error;
3684		}
3685	}
3686
3687	return 0;
3688}
3689
3690/**
3691 * Configure the card to listen to a particular channel, this transisions the
3692 * card in to being able to receive frames from remote devices.
3693 */
3694static int
3695wpi_config(struct wpi_softc *sc)
3696{
3697	struct ifnet *ifp = sc->sc_ifp;
3698	struct ieee80211com *ic = ifp->if_l2com;
3699	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3700	uint32_t flags;
3701	int error;
3702
3703	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
3704
3705	/* Set power saving level to CAM during initialization. */
3706	if ((error = wpi_set_pslevel(sc, 0, 0, 0)) != 0) {
3707		device_printf(sc->sc_dev,
3708		    "%s: could not set power saving level\n", __func__);
3709		return error;
3710	}
3711
3712	/* Configure bluetooth coexistence. */
3713	if ((error = wpi_send_btcoex(sc)) != 0) {
3714		device_printf(sc->sc_dev,
3715		    "could not configure bluetooth coexistence\n");
3716		return error;
3717	}
3718
3719	/* Configure adapter. */
3720	memset(&sc->rxon, 0, sizeof (struct wpi_rxon));
3721	IEEE80211_ADDR_COPY(sc->rxon.myaddr, vap->iv_myaddr);
3722
3723	/* Set default channel. */
3724	sc->rxon.chan = ieee80211_chan2ieee(ic, ic->ic_curchan);
3725	sc->rxon.flags = htole32(WPI_RXON_TSF | WPI_RXON_CTS_TO_SELF);
3726	if (IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan))
3727		sc->rxon.flags |= htole32(WPI_RXON_AUTO | WPI_RXON_24GHZ);
3728
3729	sc->rxon.filter = WPI_FILTER_MULTICAST;
3730	switch (ic->ic_opmode) {
3731	case IEEE80211_M_STA:
3732		sc->rxon.mode = WPI_MODE_STA;
3733		break;
3734	case IEEE80211_M_IBSS:
3735		sc->rxon.mode = WPI_MODE_IBSS;
3736		sc->rxon.filter |= WPI_FILTER_BEACON;
3737		break;
3738	/* XXX workaround for passive channels selection */
3739	case IEEE80211_M_AHDEMO:
3740	case IEEE80211_M_HOSTAP:
3741		sc->rxon.mode = WPI_MODE_HOSTAP;
3742		break;
3743	case IEEE80211_M_MONITOR:
3744		sc->rxon.mode = WPI_MODE_MONITOR;
3745		break;
3746	default:
3747		device_printf(sc->sc_dev, "unknown opmode %d\n",
3748		    ic->ic_opmode);
3749		return EINVAL;
3750	}
3751	sc->rxon.filter = htole32(sc->rxon.filter);
3752	wpi_set_promisc(sc);
3753	sc->rxon.cck_mask  = 0x0f;	/* not yet negotiated */
3754	sc->rxon.ofdm_mask = 0xff;	/* not yet negotiated */
3755
3756	if ((error = wpi_send_rxon(sc, 0, 0)) != 0) {
3757		device_printf(sc->sc_dev, "%s: could not send RXON\n",
3758		    __func__);
3759		return error;
3760	}
3761
3762	/* Setup rate scalling. */
3763	if ((error = wpi_mrr_setup(sc)) != 0) {
3764		device_printf(sc->sc_dev, "could not setup MRR, error %d\n",
3765		    error);
3766		return error;
3767	}
3768
3769	/* Disable beacon notifications (unused). */
3770	flags = WPI_STATISTICS_BEACON_DISABLE;
3771	error = wpi_cmd(sc, WPI_CMD_GET_STATISTICS, &flags, sizeof flags, 1);
3772	if (error != 0) {
3773		device_printf(sc->sc_dev,
3774		    "could not disable beacon statistics, error %d\n", error);
3775		return error;
3776	}
3777
3778	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
3779
3780	return 0;
3781}
3782
3783static uint16_t
3784wpi_get_active_dwell_time(struct wpi_softc *sc,
3785    struct ieee80211_channel *c, uint8_t n_probes)
3786{
3787	/* No channel? Default to 2GHz settings. */
3788	if (c == NULL || IEEE80211_IS_CHAN_2GHZ(c)) {
3789		return (WPI_ACTIVE_DWELL_TIME_2GHZ +
3790		WPI_ACTIVE_DWELL_FACTOR_2GHZ * (n_probes + 1));
3791	}
3792
3793	/* 5GHz dwell time. */
3794	return (WPI_ACTIVE_DWELL_TIME_5GHZ +
3795	    WPI_ACTIVE_DWELL_FACTOR_5GHZ * (n_probes + 1));
3796}
3797
3798/*
3799 * Limit the total dwell time to 85% of the beacon interval.
3800 *
3801 * Returns the dwell time in milliseconds.
3802 */
3803static uint16_t
3804wpi_limit_dwell(struct wpi_softc *sc, uint16_t dwell_time)
3805{
3806	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
3807	struct ieee80211vap *vap = NULL;
3808	int bintval = 0;
3809
3810	/* bintval is in TU (1.024mS) */
3811	if (! TAILQ_EMPTY(&ic->ic_vaps)) {
3812		vap = TAILQ_FIRST(&ic->ic_vaps);
3813		bintval = vap->iv_bss->ni_intval;
3814	}
3815
3816	/*
3817	 * If it's non-zero, we should calculate the minimum of
3818	 * it and the DWELL_BASE.
3819	 *
3820	 * XXX Yes, the math should take into account that bintval
3821	 * is 1.024mS, not 1mS..
3822	 */
3823	if (bintval > 0) {
3824		DPRINTF(sc, WPI_DEBUG_SCAN, "%s: bintval=%d\n", __func__,
3825		    bintval);
3826		return (MIN(WPI_PASSIVE_DWELL_BASE, ((bintval * 85) / 100)));
3827	}
3828
3829	/* No association context? Default. */
3830	return (WPI_PASSIVE_DWELL_BASE);
3831}
3832
3833static uint16_t
3834wpi_get_passive_dwell_time(struct wpi_softc *sc, struct ieee80211_channel *c)
3835{
3836	uint16_t passive;
3837
3838	if (c == NULL || IEEE80211_IS_CHAN_2GHZ(c))
3839		passive = WPI_PASSIVE_DWELL_BASE + WPI_PASSIVE_DWELL_TIME_2GHZ;
3840	else
3841		passive = WPI_PASSIVE_DWELL_BASE + WPI_PASSIVE_DWELL_TIME_5GHZ;
3842
3843	/* Clamp to the beacon interval if we're associated. */
3844	return (wpi_limit_dwell(sc, passive));
3845}
3846
3847/*
3848 * Send a scan request to the firmware.
3849 */
3850static int
3851wpi_scan(struct wpi_softc *sc, struct ieee80211_channel *c)
3852{
3853	struct ifnet *ifp = sc->sc_ifp;
3854	struct ieee80211com *ic = ifp->if_l2com;
3855	struct ieee80211_scan_state *ss = ic->ic_scan;
3856	struct ieee80211vap *vap = ss->ss_vap;
3857	struct wpi_scan_hdr *hdr;
3858	struct wpi_cmd_data *tx;
3859	struct wpi_scan_essid *essids;
3860	struct wpi_scan_chan *chan;
3861	struct ieee80211_frame *wh;
3862	struct ieee80211_rateset *rs;
3863	uint16_t dwell_active, dwell_passive;
3864	uint8_t *buf, *frm;
3865	int buflen, error, i, nssid;
3866
3867	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
3868
3869	/*
3870	 * We are absolutely not allowed to send a scan command when another
3871	 * scan command is pending.
3872	 */
3873	if (sc->sc_scan_timer) {
3874		device_printf(sc->sc_dev, "%s: called whilst scanning!\n",
3875		    __func__);
3876
3877		DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR, __func__);
3878
3879		return (EAGAIN);
3880	}
3881
3882	buf = malloc(WPI_SCAN_MAXSZ, M_DEVBUF, M_NOWAIT | M_ZERO);
3883	if (buf == NULL) {
3884		device_printf(sc->sc_dev,
3885		    "%s: could not allocate buffer for scan command\n",
3886		    __func__);
3887		error = ENOMEM;
3888		goto fail;
3889	}
3890	hdr = (struct wpi_scan_hdr *)buf;
3891
3892	/*
3893	 * Move to the next channel if no packets are received within 10 msecs
3894	 * after sending the probe request.
3895	 */
3896	hdr->quiet_time = htole16(10);		/* timeout in milliseconds */
3897	hdr->quiet_threshold = htole16(1);	/* min # of packets */
3898	/*
3899	 * Max needs to be greater than active and passive and quiet!
3900	 * It's also in microseconds!
3901	 */
3902	hdr->max_svc = htole32(250 * IEEE80211_DUR_TU);
3903	hdr->pause_svc = htole32((4 << 24) |
3904	    (100 * IEEE80211_DUR_TU));	/* Hardcode for now */
3905	hdr->filter = htole32(WPI_FILTER_MULTICAST | WPI_FILTER_BEACON);
3906
3907	tx = (struct wpi_cmd_data *)(hdr + 1);
3908	tx->flags = htole32(WPI_TX_AUTO_SEQ);
3909	tx->id = WPI_ID_BROADCAST;
3910	tx->lifetime = htole32(WPI_LIFETIME_INFINITE);
3911
3912	if (IEEE80211_IS_CHAN_5GHZ(c)) {
3913		/* Send probe requests at 6Mbps. */
3914		tx->plcp = wpi_ridx_to_plcp[WPI_RIDX_OFDM6];
3915		rs = &ic->ic_sup_rates[IEEE80211_MODE_11A];
3916	} else {
3917		hdr->flags = htole32(WPI_RXON_24GHZ | WPI_RXON_AUTO);
3918		/* Send probe requests at 1Mbps. */
3919		tx->plcp = wpi_ridx_to_plcp[WPI_RIDX_CCK1];
3920		rs = &ic->ic_sup_rates[IEEE80211_MODE_11G];
3921	}
3922
3923	essids = (struct wpi_scan_essid *)(tx + 1);
3924	nssid = MIN(ss->ss_nssid, WPI_SCAN_MAX_ESSIDS);
3925	for (i = 0; i < nssid; i++) {
3926		essids[i].id = IEEE80211_ELEMID_SSID;
3927		essids[i].len = MIN(ss->ss_ssid[i].len, IEEE80211_NWID_LEN);
3928		memcpy(essids[i].data, ss->ss_ssid[i].ssid, essids[i].len);
3929#ifdef WPI_DEBUG
3930		if (sc->sc_debug & WPI_DEBUG_SCAN) {
3931			printf("Scanning Essid: ");
3932			ieee80211_print_essid(essids[i].data, essids[i].len);
3933			printf("\n");
3934		}
3935#endif
3936	}
3937
3938	/*
3939	 * Build a probe request frame.  Most of the following code is a
3940	 * copy & paste of what is done in net80211.
3941	 */
3942	wh = (struct ieee80211_frame *)(essids + WPI_SCAN_MAX_ESSIDS);
3943	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
3944		IEEE80211_FC0_SUBTYPE_PROBE_REQ;
3945	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
3946	IEEE80211_ADDR_COPY(wh->i_addr1, ifp->if_broadcastaddr);
3947	IEEE80211_ADDR_COPY(wh->i_addr2, vap->iv_myaddr);
3948	IEEE80211_ADDR_COPY(wh->i_addr3, ifp->if_broadcastaddr);
3949	*(uint16_t *)&wh->i_dur[0] = 0;	/* filled by h/w */
3950	*(uint16_t *)&wh->i_seq[0] = 0;	/* filled by h/w */
3951
3952	frm = (uint8_t *)(wh + 1);
3953	frm = ieee80211_add_ssid(frm, NULL, 0);
3954	frm = ieee80211_add_rates(frm, rs);
3955	if (rs->rs_nrates > IEEE80211_RATE_SIZE)
3956		frm = ieee80211_add_xrates(frm, rs);
3957
3958	/* Set length of probe request. */
3959	tx->len = htole16(frm - (uint8_t *)wh);
3960
3961	/*
3962	 * Construct information about the channel that we
3963	 * want to scan. The firmware expects this to be directly
3964	 * after the scan probe request
3965	 */
3966	chan = (struct wpi_scan_chan *)frm;
3967	chan->chan = htole16(ieee80211_chan2ieee(ic, c));
3968	chan->flags = 0;
3969	if (nssid) {
3970		hdr->crc_threshold = WPI_SCAN_CRC_TH_DEFAULT;
3971		chan->flags |= WPI_CHAN_NPBREQS(nssid);
3972	} else
3973		hdr->crc_threshold = WPI_SCAN_CRC_TH_NEVER;
3974
3975	if (!IEEE80211_IS_CHAN_PASSIVE(c))
3976		chan->flags |= WPI_CHAN_ACTIVE;
3977
3978	/*
3979	 * Calculate the active/passive dwell times.
3980	 */
3981
3982	dwell_active = wpi_get_active_dwell_time(sc, c, nssid);
3983	dwell_passive = wpi_get_passive_dwell_time(sc, c);
3984
3985	/* Make sure they're valid. */
3986	if (dwell_passive <= dwell_active)
3987		dwell_passive = dwell_active + 1;
3988
3989	chan->active = htole16(dwell_active);
3990	chan->passive = htole16(dwell_passive);
3991
3992	chan->dsp_gain = 0x6e;  /* Default level */
3993
3994	if (IEEE80211_IS_CHAN_5GHZ(c))
3995		chan->rf_gain = 0x3b;
3996	else
3997		chan->rf_gain = 0x28;
3998
3999	DPRINTF(sc, WPI_DEBUG_SCAN, "Scanning %u Passive: %d\n",
4000	    chan->chan, IEEE80211_IS_CHAN_PASSIVE(c));
4001
4002	hdr->nchan++;
4003	chan++;
4004
4005	buflen = (uint8_t *)chan - buf;
4006	hdr->len = htole16(buflen);
4007
4008	DPRINTF(sc, WPI_DEBUG_CMD, "sending scan command nchan=%d\n",
4009	    hdr->nchan);
4010	error = wpi_cmd(sc, WPI_CMD_SCAN, buf, buflen, 1);
4011	free(buf, M_DEVBUF);
4012
4013	if (error != 0)
4014		goto fail;
4015
4016	sc->sc_scan_timer = 5;
4017
4018	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
4019
4020	return 0;
4021
4022fail:	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR, __func__);
4023
4024	return error;
4025}
4026
4027static int
4028wpi_auth(struct wpi_softc *sc, struct ieee80211vap *vap)
4029{
4030	struct ieee80211com *ic = vap->iv_ic;
4031	struct ieee80211_node *ni = vap->iv_bss;
4032	int error;
4033
4034	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
4035
4036	/* Update adapter configuration. */
4037	sc->rxon.associd = 0;
4038	sc->rxon.filter &= ~htole32(WPI_FILTER_BSS);
4039	IEEE80211_ADDR_COPY(sc->rxon.bssid, ni->ni_bssid);
4040	sc->rxon.chan = ieee80211_chan2ieee(ic, ni->ni_chan);
4041	sc->rxon.flags = htole32(WPI_RXON_TSF | WPI_RXON_CTS_TO_SELF);
4042	if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
4043		sc->rxon.flags |= htole32(WPI_RXON_AUTO | WPI_RXON_24GHZ);
4044	if (ic->ic_flags & IEEE80211_F_SHSLOT)
4045		sc->rxon.flags |= htole32(WPI_RXON_SHSLOT);
4046	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
4047		sc->rxon.flags |= htole32(WPI_RXON_SHPREAMBLE);
4048	if (IEEE80211_IS_CHAN_A(ni->ni_chan)) {
4049		sc->rxon.cck_mask  = 0;
4050		sc->rxon.ofdm_mask = 0x15;
4051	} else if (IEEE80211_IS_CHAN_B(ni->ni_chan)) {
4052		sc->rxon.cck_mask  = 0x03;
4053		sc->rxon.ofdm_mask = 0;
4054	} else {
4055		/* Assume 802.11b/g. */
4056		sc->rxon.cck_mask  = 0x0f;
4057		sc->rxon.ofdm_mask = 0x15;
4058	}
4059
4060	DPRINTF(sc, WPI_DEBUG_STATE, "rxon chan %d flags %x cck %x ofdm %x\n",
4061	    sc->rxon.chan, sc->rxon.flags, sc->rxon.cck_mask,
4062	    sc->rxon.ofdm_mask);
4063
4064	if ((error = wpi_send_rxon(sc, 0, 1)) != 0) {
4065		device_printf(sc->sc_dev, "%s: could not send RXON\n",
4066		    __func__);
4067	}
4068
4069	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
4070
4071	return error;
4072}
4073
4074static int
4075wpi_config_beacon(struct wpi_vap *wvp)
4076{
4077	struct ieee80211com *ic = wvp->wv_vap.iv_ic;
4078	struct ieee80211_beacon_offsets *bo = &wvp->wv_boff;
4079	struct wpi_buf *bcn = &wvp->wv_bcbuf;
4080	struct wpi_softc *sc = ic->ic_ifp->if_softc;
4081	struct wpi_cmd_beacon *cmd = (struct wpi_cmd_beacon *)&bcn->data;
4082	struct ieee80211_tim_ie *tie;
4083	struct mbuf *m;
4084	uint8_t *ptr;
4085	int error;
4086
4087	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
4088
4089	WPI_VAP_LOCK_ASSERT(wvp);
4090
4091	cmd->len = htole16(bcn->m->m_pkthdr.len);
4092	cmd->plcp = (ic->ic_curmode == IEEE80211_MODE_11A) ?
4093	    wpi_ridx_to_plcp[WPI_RIDX_OFDM6] : wpi_ridx_to_plcp[WPI_RIDX_CCK1];
4094
4095	/* XXX seems to be unused */
4096	if (*(bo->bo_tim) == IEEE80211_ELEMID_TIM) {
4097		tie = (struct ieee80211_tim_ie *) bo->bo_tim;
4098		ptr = mtod(bcn->m, uint8_t *);
4099
4100		cmd->tim = htole16(bo->bo_tim - ptr);
4101		cmd->timsz = tie->tim_len;
4102	}
4103
4104	/* Necessary for recursion in ieee80211_beacon_update(). */
4105	m = bcn->m;
4106	bcn->m = m_dup(m, M_NOWAIT);
4107	if (bcn->m == NULL) {
4108		device_printf(sc->sc_dev,
4109		    "%s: could not copy beacon frame\n", __func__);
4110		error = ENOMEM;
4111		goto end;
4112	}
4113
4114	if ((error = wpi_cmd2(sc, bcn)) != 0) {
4115		device_printf(sc->sc_dev,
4116		    "%s: could not update beacon frame, error %d", __func__,
4117		    error);
4118	}
4119
4120	/* Restore mbuf. */
4121end:	bcn->m = m;
4122
4123	return error;
4124}
4125
4126static int
4127wpi_setup_beacon(struct wpi_softc *sc, struct ieee80211_node *ni)
4128{
4129	struct wpi_vap *wvp = WPI_VAP(ni->ni_vap);
4130	struct wpi_buf *bcn = &wvp->wv_bcbuf;
4131	struct ieee80211_beacon_offsets *bo = &wvp->wv_boff;
4132	struct mbuf *m;
4133	int error;
4134
4135	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
4136
4137	if (ni->ni_chan == IEEE80211_CHAN_ANYC)
4138		return EINVAL;
4139
4140	m = ieee80211_beacon_alloc(ni, bo);
4141	if (m == NULL) {
4142		device_printf(sc->sc_dev,
4143		    "%s: could not allocate beacon frame\n", __func__);
4144		return ENOMEM;
4145	}
4146
4147	WPI_VAP_LOCK(wvp);
4148	if (bcn->m != NULL)
4149		m_freem(bcn->m);
4150
4151	bcn->m = m;
4152
4153	error = wpi_config_beacon(wvp);
4154	WPI_VAP_UNLOCK(wvp);
4155
4156	return error;
4157}
4158
4159static void
4160wpi_update_beacon(struct ieee80211vap *vap, int item)
4161{
4162	struct wpi_softc *sc = vap->iv_ic->ic_ifp->if_softc;
4163	struct wpi_vap *wvp = WPI_VAP(vap);
4164	struct wpi_buf *bcn = &wvp->wv_bcbuf;
4165	struct ieee80211_beacon_offsets *bo = &wvp->wv_boff;
4166	struct ieee80211_node *ni = vap->iv_bss;
4167	int mcast = 0;
4168
4169	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
4170
4171	WPI_VAP_LOCK(wvp);
4172	if (bcn->m == NULL) {
4173		bcn->m = ieee80211_beacon_alloc(ni, bo);
4174		if (bcn->m == NULL) {
4175			device_printf(sc->sc_dev,
4176			    "%s: could not allocate beacon frame\n", __func__);
4177
4178			DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR,
4179			    __func__);
4180
4181			WPI_VAP_UNLOCK(wvp);
4182			return;
4183		}
4184	}
4185	WPI_VAP_UNLOCK(wvp);
4186
4187	if (item == IEEE80211_BEACON_TIM)
4188		mcast = 1;	/* TODO */
4189
4190	setbit(bo->bo_flags, item);
4191	ieee80211_beacon_update(ni, bo, bcn->m, mcast);
4192
4193	WPI_VAP_LOCK(wvp);
4194	wpi_config_beacon(wvp);
4195	WPI_VAP_UNLOCK(wvp);
4196
4197	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
4198}
4199
4200static void
4201wpi_newassoc(struct ieee80211_node *ni, int isnew)
4202{
4203	struct ieee80211vap *vap = ni->ni_vap;
4204	struct wpi_softc *sc = ni->ni_ic->ic_ifp->if_softc;
4205	struct wpi_node *wn = WPI_NODE(ni);
4206	int error;
4207
4208	WPI_NT_LOCK(sc);
4209
4210	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
4211
4212	if (vap->iv_opmode != IEEE80211_M_STA && wn->id == WPI_ID_UNDEFINED) {
4213		if ((error = wpi_add_ibss_node(sc, ni)) != 0) {
4214			device_printf(sc->sc_dev,
4215			    "%s: could not add IBSS node, error %d\n",
4216			    __func__, error);
4217		}
4218	}
4219	WPI_NT_UNLOCK(sc);
4220}
4221
4222static int
4223wpi_run(struct wpi_softc *sc, struct ieee80211vap *vap)
4224{
4225	struct ieee80211com *ic = vap->iv_ic;
4226	struct ieee80211_node *ni = vap->iv_bss;
4227	int error;
4228
4229	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
4230
4231	if (vap->iv_opmode == IEEE80211_M_MONITOR) {
4232		/* Link LED blinks while monitoring. */
4233		wpi_set_led(sc, WPI_LED_LINK, 5, 5);
4234		return 0;
4235	}
4236
4237	/* XXX kernel panic workaround */
4238	if (ni->ni_chan == IEEE80211_CHAN_ANYC) {
4239		device_printf(sc->sc_dev, "%s: incomplete configuration\n",
4240		    __func__);
4241		return EINVAL;
4242	}
4243
4244	if ((error = wpi_set_timing(sc, ni)) != 0) {
4245		device_printf(sc->sc_dev,
4246		    "%s: could not set timing, error %d\n", __func__, error);
4247		return error;
4248	}
4249
4250	/* Update adapter configuration. */
4251	IEEE80211_ADDR_COPY(sc->rxon.bssid, ni->ni_bssid);
4252	sc->rxon.associd = htole16(IEEE80211_NODE_AID(ni));
4253	sc->rxon.chan = ieee80211_chan2ieee(ic, ni->ni_chan);
4254	sc->rxon.flags = htole32(WPI_RXON_TSF | WPI_RXON_CTS_TO_SELF);
4255	if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
4256		sc->rxon.flags |= htole32(WPI_RXON_AUTO | WPI_RXON_24GHZ);
4257	/* Short preamble and slot time are negotiated when associating. */
4258	sc->rxon.flags &= ~htole32(WPI_RXON_SHPREAMBLE | WPI_RXON_SHSLOT);
4259	if (ic->ic_flags & IEEE80211_F_SHSLOT)
4260		sc->rxon.flags |= htole32(WPI_RXON_SHSLOT);
4261	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
4262		sc->rxon.flags |= htole32(WPI_RXON_SHPREAMBLE);
4263	if (IEEE80211_IS_CHAN_A(ni->ni_chan)) {
4264		sc->rxon.cck_mask  = 0;
4265		sc->rxon.ofdm_mask = 0x15;
4266	} else if (IEEE80211_IS_CHAN_B(ni->ni_chan)) {
4267		sc->rxon.cck_mask  = 0x03;
4268		sc->rxon.ofdm_mask = 0;
4269	} else {
4270		/* Assume 802.11b/g. */
4271		sc->rxon.cck_mask  = 0x0f;
4272		sc->rxon.ofdm_mask = 0x15;
4273	}
4274	sc->rxon.filter |= htole32(WPI_FILTER_BSS);
4275
4276	DPRINTF(sc, WPI_DEBUG_STATE, "rxon chan %d flags %x\n",
4277	    sc->rxon.chan, sc->rxon.flags);
4278
4279	if ((error = wpi_send_rxon(sc, 0, 1)) != 0) {
4280		device_printf(sc->sc_dev, "%s: could not send RXON\n",
4281		    __func__);
4282		return error;
4283	}
4284
4285	if (vap->iv_opmode == IEEE80211_M_IBSS) {
4286		if ((error = wpi_setup_beacon(sc, ni)) != 0) {
4287			device_printf(sc->sc_dev,
4288			    "%s: could not setup beacon, error %d\n", __func__,
4289			    error);
4290			return error;
4291		}
4292	}
4293
4294	if (vap->iv_opmode == IEEE80211_M_STA) {
4295		/* Add BSS node. */
4296		WPI_NT_LOCK(sc);
4297		error = wpi_add_sta_node(sc, ni);
4298		WPI_NT_UNLOCK(sc);
4299		if (error != 0) {
4300			device_printf(sc->sc_dev,
4301			    "%s: could not add BSS node, error %d\n", __func__,
4302			    error);
4303			return error;
4304		}
4305	}
4306
4307	/* Link LED always on while associated. */
4308	wpi_set_led(sc, WPI_LED_LINK, 0, 1);
4309
4310	/* Start periodic calibration timer. */
4311	callout_reset(&sc->calib_to, 60*hz, wpi_calib_timeout, sc);
4312
4313	/* Enable power-saving mode if requested by user. */
4314	if (vap->iv_flags & IEEE80211_F_PMGTON)
4315		(void)wpi_set_pslevel(sc, 0, 3, 1);
4316	else
4317		(void)wpi_set_pslevel(sc, 0, 0, 1);
4318
4319	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
4320
4321	return 0;
4322}
4323
4324static int
4325wpi_load_key(struct ieee80211_node *ni, const struct ieee80211_key *k)
4326{
4327	const struct ieee80211_cipher *cip = k->wk_cipher;
4328	struct ieee80211vap *vap = ni->ni_vap;
4329	struct wpi_softc *sc = ni->ni_ic->ic_ifp->if_softc;
4330	struct wpi_node *wn = WPI_NODE(ni);
4331	struct wpi_node_info node;
4332	uint16_t kflags;
4333	int error;
4334
4335	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
4336
4337	if (wpi_check_node_entry(sc, wn->id) == 0) {
4338		device_printf(sc->sc_dev, "%s: node does not exist\n",
4339		    __func__);
4340		return 0;
4341	}
4342
4343	switch (cip->ic_cipher) {
4344	case IEEE80211_CIPHER_AES_CCM:
4345		kflags = WPI_KFLAG_CCMP;
4346		break;
4347
4348	default:
4349		device_printf(sc->sc_dev, "%s: unknown cipher %d\n", __func__,
4350		    cip->ic_cipher);
4351		return 0;
4352	}
4353
4354	kflags |= WPI_KFLAG_KID(k->wk_keyix);
4355	if (k->wk_flags & IEEE80211_KEY_GROUP)
4356		kflags |= WPI_KFLAG_MULTICAST;
4357
4358	memset(&node, 0, sizeof node);
4359	node.id = wn->id;
4360	node.control = WPI_NODE_UPDATE;
4361	node.flags = WPI_FLAG_KEY_SET;
4362	node.kflags = htole16(kflags);
4363	memcpy(node.key, k->wk_key, k->wk_keylen);
4364again:
4365	DPRINTF(sc, WPI_DEBUG_KEY,
4366	    "%s: setting %s key id %d for node %d (%s)\n", __func__,
4367	    (kflags & WPI_KFLAG_MULTICAST) ? "group" : "ucast", k->wk_keyix,
4368	    node.id, ether_sprintf(ni->ni_macaddr));
4369
4370	error = wpi_cmd(sc, WPI_CMD_ADD_NODE, &node, sizeof node, 1);
4371	if (error != 0) {
4372		device_printf(sc->sc_dev, "can't update node info, error %d\n",
4373		    error);
4374		return !error;
4375	}
4376
4377	if (!(kflags & WPI_KFLAG_MULTICAST) && &vap->iv_nw_keys[0] <= k &&
4378	    k < &vap->iv_nw_keys[IEEE80211_WEP_NKID]) {
4379		kflags |= WPI_KFLAG_MULTICAST;
4380		node.kflags = htole16(kflags);
4381
4382		goto again;
4383	}
4384
4385	return 1;
4386}
4387
4388static void
4389wpi_load_key_cb(void *arg, struct ieee80211_node *ni)
4390{
4391	const struct ieee80211_key *k = arg;
4392	struct ieee80211vap *vap = ni->ni_vap;
4393	struct wpi_softc *sc = ni->ni_ic->ic_ifp->if_softc;
4394	struct wpi_node *wn = WPI_NODE(ni);
4395	int error;
4396
4397	if (vap->iv_bss == ni && wn->id == WPI_ID_UNDEFINED)
4398		return;
4399
4400	WPI_NT_LOCK(sc);
4401	error = wpi_load_key(ni, k);
4402	WPI_NT_UNLOCK(sc);
4403
4404	if (error == 0) {
4405		device_printf(sc->sc_dev, "%s: error while setting key\n",
4406		    __func__);
4407	}
4408}
4409
4410static int
4411wpi_set_global_keys(struct ieee80211_node *ni)
4412{
4413	struct ieee80211vap *vap = ni->ni_vap;
4414	struct ieee80211_key *wk = &vap->iv_nw_keys[0];
4415	int error = 1;
4416
4417	for (; wk < &vap->iv_nw_keys[IEEE80211_WEP_NKID] && error; wk++)
4418		if (wk->wk_keyix != IEEE80211_KEYIX_NONE)
4419			error = wpi_load_key(ni, wk);
4420
4421	return !error;
4422}
4423
4424static int
4425wpi_del_key(struct ieee80211_node *ni, const struct ieee80211_key *k)
4426{
4427	struct ieee80211vap *vap = ni->ni_vap;
4428	struct wpi_softc *sc = ni->ni_ic->ic_ifp->if_softc;
4429	struct wpi_node *wn = WPI_NODE(ni);
4430	struct wpi_node_info node;
4431	uint16_t kflags;
4432	int error;
4433
4434	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
4435
4436	if (wpi_check_node_entry(sc, wn->id) == 0) {
4437		DPRINTF(sc, WPI_DEBUG_KEY, "%s: node was removed\n", __func__);
4438		return 1;	/* Nothing to do. */
4439	}
4440
4441	kflags = WPI_KFLAG_KID(k->wk_keyix);
4442	if (k->wk_flags & IEEE80211_KEY_GROUP)
4443		kflags |= WPI_KFLAG_MULTICAST;
4444
4445	memset(&node, 0, sizeof node);
4446	node.id = wn->id;
4447	node.control = WPI_NODE_UPDATE;
4448	node.flags = WPI_FLAG_KEY_SET;
4449	node.kflags = htole16(kflags);
4450again:
4451	DPRINTF(sc, WPI_DEBUG_KEY, "%s: deleting %s key %d for node %d (%s)\n",
4452	    __func__, (kflags & WPI_KFLAG_MULTICAST) ? "group" : "ucast",
4453	    k->wk_keyix, node.id, ether_sprintf(ni->ni_macaddr));
4454
4455	error = wpi_cmd(sc, WPI_CMD_ADD_NODE, &node, sizeof node, 1);
4456	if (error != 0) {
4457		device_printf(sc->sc_dev, "can't update node info, error %d\n",
4458		    error);
4459		return !error;
4460	}
4461
4462	if (!(kflags & WPI_KFLAG_MULTICAST) && &vap->iv_nw_keys[0] <= k &&
4463	    k < &vap->iv_nw_keys[IEEE80211_WEP_NKID]) {
4464		kflags |= WPI_KFLAG_MULTICAST;
4465		node.kflags = htole16(kflags);
4466
4467		goto again;
4468	}
4469
4470	return 1;
4471}
4472
4473static void
4474wpi_del_key_cb(void *arg, struct ieee80211_node *ni)
4475{
4476	const struct ieee80211_key *k = arg;
4477	struct ieee80211vap *vap = ni->ni_vap;
4478	struct wpi_softc *sc = ni->ni_ic->ic_ifp->if_softc;
4479	struct wpi_node *wn = WPI_NODE(ni);
4480	int error;
4481
4482	if (vap->iv_bss == ni && wn->id == WPI_ID_UNDEFINED)
4483		return;
4484
4485	WPI_NT_LOCK(sc);
4486	error = wpi_del_key(ni, k);
4487	WPI_NT_UNLOCK(sc);
4488
4489	if (error == 0) {
4490		device_printf(sc->sc_dev, "%s: error while deleting key\n",
4491		    __func__);
4492	}
4493}
4494
4495static int
4496wpi_process_key(struct ieee80211vap *vap, const struct ieee80211_key *k,
4497    int set)
4498{
4499	struct ieee80211com *ic = vap->iv_ic;
4500	struct wpi_softc *sc = ic->ic_ifp->if_softc;
4501	struct wpi_vap *wvp = WPI_VAP(vap);
4502	struct ieee80211_node *ni;
4503	int error, ni_ref = 0;
4504
4505	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
4506
4507	if (k->wk_flags & IEEE80211_KEY_SWCRYPT) {
4508		/* Not for us. */
4509		return 1;
4510	}
4511
4512	if (!(k->wk_flags & IEEE80211_KEY_RECV)) {
4513		/* XMIT keys are handled in wpi_tx_data(). */
4514		return 1;
4515	}
4516
4517	/* Handle group keys. */
4518	if (&vap->iv_nw_keys[0] <= k &&
4519	    k < &vap->iv_nw_keys[IEEE80211_WEP_NKID]) {
4520		WPI_NT_LOCK(sc);
4521		if (set)
4522			wvp->wv_gtk |= WPI_VAP_KEY(k->wk_keyix);
4523		else
4524			wvp->wv_gtk &= ~WPI_VAP_KEY(k->wk_keyix);
4525		WPI_NT_UNLOCK(sc);
4526
4527		if (vap->iv_state == IEEE80211_S_RUN) {
4528			ieee80211_iterate_nodes(&ic->ic_sta,
4529			    set ? wpi_load_key_cb : wpi_del_key_cb, (void *)k);
4530		}
4531
4532		return 1;
4533	}
4534
4535	switch (vap->iv_opmode) {
4536	case IEEE80211_M_STA:
4537		ni = vap->iv_bss;
4538		break;
4539
4540	case IEEE80211_M_IBSS:
4541	case IEEE80211_M_AHDEMO:
4542		ni = ieee80211_find_vap_node(&ic->ic_sta, vap, k->wk_macaddr);
4543		if (ni == NULL)
4544			return 0;	/* should not happen */
4545
4546		ni_ref = 1;
4547		break;
4548
4549	default:
4550		device_printf(sc->sc_dev, "%s: unknown opmode %d\n", __func__,
4551		    vap->iv_opmode);
4552		return 0;
4553	}
4554
4555	WPI_NT_LOCK(sc);
4556	if (set)
4557		error = wpi_load_key(ni, k);
4558	else
4559		error = wpi_del_key(ni, k);
4560	WPI_NT_UNLOCK(sc);
4561
4562	if (ni_ref)
4563		ieee80211_node_decref(ni);
4564
4565	return error;
4566}
4567
4568static int
4569wpi_key_set(struct ieee80211vap *vap, const struct ieee80211_key *k,
4570    const uint8_t mac[IEEE80211_ADDR_LEN])
4571{
4572	return wpi_process_key(vap, k, 1);
4573}
4574
4575static int
4576wpi_key_delete(struct ieee80211vap *vap, const struct ieee80211_key *k)
4577{
4578	return wpi_process_key(vap, k, 0);
4579}
4580
4581/*
4582 * This function is called after the runtime firmware notifies us of its
4583 * readiness (called in a process context).
4584 */
4585static int
4586wpi_post_alive(struct wpi_softc *sc)
4587{
4588	int ntries, error;
4589
4590	/* Check (again) that the radio is not disabled. */
4591	if ((error = wpi_nic_lock(sc)) != 0)
4592		return error;
4593
4594	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
4595
4596	/* NB: Runtime firmware must be up and running. */
4597	if (!(wpi_prph_read(sc, WPI_APMG_RFKILL) & 1)) {
4598 		device_printf(sc->sc_dev,
4599		    "RF switch: radio disabled (%s)\n", __func__);
4600		wpi_nic_unlock(sc);
4601		return EPERM;   /* :-) */
4602	}
4603	wpi_nic_unlock(sc);
4604
4605	/* Wait for thermal sensor to calibrate. */
4606	for (ntries = 0; ntries < 1000; ntries++) {
4607		if ((sc->temp = (int)WPI_READ(sc, WPI_UCODE_GP2)) != 0)
4608			break;
4609		DELAY(10);
4610	}
4611
4612	if (ntries == 1000) {
4613		device_printf(sc->sc_dev,
4614		    "timeout waiting for thermal sensor calibration\n");
4615		return ETIMEDOUT;
4616	}
4617
4618	DPRINTF(sc, WPI_DEBUG_TEMP, "temperature %d\n", sc->temp);
4619	return 0;
4620}
4621
4622/*
4623 * The firmware boot code is small and is intended to be copied directly into
4624 * the NIC internal memory (no DMA transfer).
4625 */
4626static int
4627wpi_load_bootcode(struct wpi_softc *sc, const uint8_t *ucode, int size)
4628{
4629	int error, ntries;
4630
4631	DPRINTF(sc, WPI_DEBUG_HW, "Loading microcode size 0x%x\n", size);
4632
4633	size /= sizeof (uint32_t);
4634
4635	if ((error = wpi_nic_lock(sc)) != 0)
4636		return error;
4637
4638	/* Copy microcode image into NIC memory. */
4639	wpi_prph_write_region_4(sc, WPI_BSM_SRAM_BASE,
4640	    (const uint32_t *)ucode, size);
4641
4642	wpi_prph_write(sc, WPI_BSM_WR_MEM_SRC, 0);
4643	wpi_prph_write(sc, WPI_BSM_WR_MEM_DST, WPI_FW_TEXT_BASE);
4644	wpi_prph_write(sc, WPI_BSM_WR_DWCOUNT, size);
4645
4646	/* Start boot load now. */
4647	wpi_prph_write(sc, WPI_BSM_WR_CTRL, WPI_BSM_WR_CTRL_START);
4648
4649	/* Wait for transfer to complete. */
4650	for (ntries = 0; ntries < 1000; ntries++) {
4651		uint32_t status = WPI_READ(sc, WPI_FH_TX_STATUS);
4652		DPRINTF(sc, WPI_DEBUG_HW,
4653		    "firmware status=0x%x, val=0x%x, result=0x%x\n", status,
4654		    WPI_FH_TX_STATUS_IDLE(6),
4655		    status & WPI_FH_TX_STATUS_IDLE(6));
4656		if (status & WPI_FH_TX_STATUS_IDLE(6)) {
4657			DPRINTF(sc, WPI_DEBUG_HW,
4658			    "Status Match! - ntries = %d\n", ntries);
4659			break;
4660		}
4661		DELAY(10);
4662	}
4663	if (ntries == 1000) {
4664		device_printf(sc->sc_dev, "%s: could not load boot firmware\n",
4665		    __func__);
4666		wpi_nic_unlock(sc);
4667		return ETIMEDOUT;
4668	}
4669
4670	/* Enable boot after power up. */
4671	wpi_prph_write(sc, WPI_BSM_WR_CTRL, WPI_BSM_WR_CTRL_START_EN);
4672
4673	wpi_nic_unlock(sc);
4674	return 0;
4675}
4676
4677static int
4678wpi_load_firmware(struct wpi_softc *sc)
4679{
4680	struct wpi_fw_info *fw = &sc->fw;
4681	struct wpi_dma_info *dma = &sc->fw_dma;
4682	int error;
4683
4684	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
4685
4686	/* Copy initialization sections into pre-allocated DMA-safe memory. */
4687	memcpy(dma->vaddr, fw->init.data, fw->init.datasz);
4688	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
4689	memcpy(dma->vaddr + WPI_FW_DATA_MAXSZ, fw->init.text, fw->init.textsz);
4690	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
4691
4692	/* Tell adapter where to find initialization sections. */
4693	if ((error = wpi_nic_lock(sc)) != 0)
4694		return error;
4695	wpi_prph_write(sc, WPI_BSM_DRAM_DATA_ADDR, dma->paddr);
4696	wpi_prph_write(sc, WPI_BSM_DRAM_DATA_SIZE, fw->init.datasz);
4697	wpi_prph_write(sc, WPI_BSM_DRAM_TEXT_ADDR,
4698	    dma->paddr + WPI_FW_DATA_MAXSZ);
4699	wpi_prph_write(sc, WPI_BSM_DRAM_TEXT_SIZE, fw->init.textsz);
4700	wpi_nic_unlock(sc);
4701
4702	/* Load firmware boot code. */
4703	error = wpi_load_bootcode(sc, fw->boot.text, fw->boot.textsz);
4704	if (error != 0) {
4705		device_printf(sc->sc_dev, "%s: could not load boot firmware\n",
4706		    __func__);
4707		return error;
4708	}
4709
4710	/* Now press "execute". */
4711	WPI_WRITE(sc, WPI_RESET, 0);
4712
4713	/* Wait at most one second for first alive notification. */
4714	if ((error = mtx_sleep(sc, &sc->sc_mtx, PCATCH, "wpiinit", hz)) != 0) {
4715		device_printf(sc->sc_dev,
4716		    "%s: timeout waiting for adapter to initialize, error %d\n",
4717		    __func__, error);
4718		return error;
4719	}
4720
4721	/* Copy runtime sections into pre-allocated DMA-safe memory. */
4722	memcpy(dma->vaddr, fw->main.data, fw->main.datasz);
4723	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
4724	memcpy(dma->vaddr + WPI_FW_DATA_MAXSZ, fw->main.text, fw->main.textsz);
4725	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
4726
4727	/* Tell adapter where to find runtime sections. */
4728	if ((error = wpi_nic_lock(sc)) != 0)
4729		return error;
4730	wpi_prph_write(sc, WPI_BSM_DRAM_DATA_ADDR, dma->paddr);
4731	wpi_prph_write(sc, WPI_BSM_DRAM_DATA_SIZE, fw->main.datasz);
4732	wpi_prph_write(sc, WPI_BSM_DRAM_TEXT_ADDR,
4733	    dma->paddr + WPI_FW_DATA_MAXSZ);
4734	wpi_prph_write(sc, WPI_BSM_DRAM_TEXT_SIZE,
4735	    WPI_FW_UPDATED | fw->main.textsz);
4736	wpi_nic_unlock(sc);
4737
4738	return 0;
4739}
4740
4741static int
4742wpi_read_firmware(struct wpi_softc *sc)
4743{
4744	const struct firmware *fp;
4745	struct wpi_fw_info *fw = &sc->fw;
4746	const struct wpi_firmware_hdr *hdr;
4747	int error;
4748
4749	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
4750
4751	DPRINTF(sc, WPI_DEBUG_FIRMWARE,
4752	    "Attempting Loading Firmware from %s module\n", WPI_FW_NAME);
4753
4754	WPI_UNLOCK(sc);
4755	fp = firmware_get(WPI_FW_NAME);
4756	WPI_LOCK(sc);
4757
4758	if (fp == NULL) {
4759		device_printf(sc->sc_dev,
4760		    "could not load firmware image '%s'\n", WPI_FW_NAME);
4761		return EINVAL;
4762	}
4763
4764	sc->fw_fp = fp;
4765
4766	if (fp->datasize < sizeof (struct wpi_firmware_hdr)) {
4767		device_printf(sc->sc_dev,
4768		    "firmware file too short: %zu bytes\n", fp->datasize);
4769		error = EINVAL;
4770		goto fail;
4771	}
4772
4773	fw->size = fp->datasize;
4774	fw->data = (const uint8_t *)fp->data;
4775
4776	/* Extract firmware header information. */
4777	hdr = (const struct wpi_firmware_hdr *)fw->data;
4778
4779	/*     |  RUNTIME FIRMWARE   |    INIT FIRMWARE    | BOOT FW  |
4780	   |HDR|<--TEXT-->|<--DATA-->|<--TEXT-->|<--DATA-->|<--TEXT-->| */
4781
4782	fw->main.textsz = le32toh(hdr->rtextsz);
4783	fw->main.datasz = le32toh(hdr->rdatasz);
4784	fw->init.textsz = le32toh(hdr->itextsz);
4785	fw->init.datasz = le32toh(hdr->idatasz);
4786	fw->boot.textsz = le32toh(hdr->btextsz);
4787	fw->boot.datasz = 0;
4788
4789	/* Sanity-check firmware header. */
4790	if (fw->main.textsz > WPI_FW_TEXT_MAXSZ ||
4791	    fw->main.datasz > WPI_FW_DATA_MAXSZ ||
4792	    fw->init.textsz > WPI_FW_TEXT_MAXSZ ||
4793	    fw->init.datasz > WPI_FW_DATA_MAXSZ ||
4794	    fw->boot.textsz > WPI_FW_BOOT_TEXT_MAXSZ ||
4795	    (fw->boot.textsz & 3) != 0) {
4796		device_printf(sc->sc_dev, "invalid firmware header\n");
4797		error = EINVAL;
4798		goto fail;
4799	}
4800
4801	/* Check that all firmware sections fit. */
4802	if (fw->size < sizeof (*hdr) + fw->main.textsz + fw->main.datasz +
4803	    fw->init.textsz + fw->init.datasz + fw->boot.textsz) {
4804		device_printf(sc->sc_dev,
4805		    "firmware file too short: %zu bytes\n", fw->size);
4806		error = EINVAL;
4807		goto fail;
4808	}
4809
4810	/* Get pointers to firmware sections. */
4811	fw->main.text = (const uint8_t *)(hdr + 1);
4812	fw->main.data = fw->main.text + fw->main.textsz;
4813	fw->init.text = fw->main.data + fw->main.datasz;
4814	fw->init.data = fw->init.text + fw->init.textsz;
4815	fw->boot.text = fw->init.data + fw->init.datasz;
4816
4817	DPRINTF(sc, WPI_DEBUG_FIRMWARE,
4818	    "Firmware Version: Major %d, Minor %d, Driver %d, \n"
4819	    "runtime (text: %u, data: %u) init (text: %u, data %u) "
4820	    "boot (text %u)\n", hdr->major, hdr->minor, le32toh(hdr->driver),
4821	    fw->main.textsz, fw->main.datasz,
4822	    fw->init.textsz, fw->init.datasz, fw->boot.textsz);
4823
4824	DPRINTF(sc, WPI_DEBUG_FIRMWARE, "fw->main.text %p\n", fw->main.text);
4825	DPRINTF(sc, WPI_DEBUG_FIRMWARE, "fw->main.data %p\n", fw->main.data);
4826	DPRINTF(sc, WPI_DEBUG_FIRMWARE, "fw->init.text %p\n", fw->init.text);
4827	DPRINTF(sc, WPI_DEBUG_FIRMWARE, "fw->init.data %p\n", fw->init.data);
4828	DPRINTF(sc, WPI_DEBUG_FIRMWARE, "fw->boot.text %p\n", fw->boot.text);
4829
4830	return 0;
4831
4832fail:	wpi_unload_firmware(sc);
4833	return error;
4834}
4835
4836/**
4837 * Free the referenced firmware image
4838 */
4839static void
4840wpi_unload_firmware(struct wpi_softc *sc)
4841{
4842	if (sc->fw_fp != NULL) {
4843		firmware_put(sc->fw_fp, FIRMWARE_UNLOAD);
4844		sc->fw_fp = NULL;
4845	}
4846}
4847
4848static int
4849wpi_clock_wait(struct wpi_softc *sc)
4850{
4851	int ntries;
4852
4853	/* Set "initialization complete" bit. */
4854	WPI_SETBITS(sc, WPI_GP_CNTRL, WPI_GP_CNTRL_INIT_DONE);
4855
4856	/* Wait for clock stabilization. */
4857	for (ntries = 0; ntries < 2500; ntries++) {
4858		if (WPI_READ(sc, WPI_GP_CNTRL) & WPI_GP_CNTRL_MAC_CLOCK_READY)
4859			return 0;
4860		DELAY(100);
4861	}
4862	device_printf(sc->sc_dev,
4863	    "%s: timeout waiting for clock stabilization\n", __func__);
4864
4865	return ETIMEDOUT;
4866}
4867
4868static int
4869wpi_apm_init(struct wpi_softc *sc)
4870{
4871	uint32_t reg;
4872	int error;
4873
4874	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
4875
4876	/* Disable L0s exit timer (NMI bug workaround). */
4877	WPI_SETBITS(sc, WPI_GIO_CHICKEN, WPI_GIO_CHICKEN_DIS_L0S_TIMER);
4878	/* Don't wait for ICH L0s (ICH bug workaround). */
4879	WPI_SETBITS(sc, WPI_GIO_CHICKEN, WPI_GIO_CHICKEN_L1A_NO_L0S_RX);
4880
4881	/* Set FH wait threshold to max (HW bug under stress workaround). */
4882	WPI_SETBITS(sc, WPI_DBG_HPET_MEM, 0xffff0000);
4883
4884	/* Cleanup. */
4885	wpi_prph_write(sc, WPI_APMG_CLK_DIS, 0x00000400);
4886	wpi_prph_clrbits(sc, WPI_APMG_PS, 0x00000E00);
4887
4888	/* Retrieve PCIe Active State Power Management (ASPM). */
4889	reg = pci_read_config(sc->sc_dev, sc->sc_cap_off + 0x10, 1);
4890	/* Workaround for HW instability in PCIe L0->L0s->L1 transition. */
4891	if (reg & 0x02)	/* L1 Entry enabled. */
4892		WPI_SETBITS(sc, WPI_GIO, WPI_GIO_L0S_ENA);
4893	else
4894		WPI_CLRBITS(sc, WPI_GIO, WPI_GIO_L0S_ENA);
4895
4896	WPI_SETBITS(sc, WPI_ANA_PLL, WPI_ANA_PLL_INIT);
4897
4898	/* Wait for clock stabilization before accessing prph. */
4899	if ((error = wpi_clock_wait(sc)) != 0)
4900		return error;
4901
4902	if ((error = wpi_nic_lock(sc)) != 0)
4903		return error;
4904	/* Enable DMA and BSM (Bootstrap State Machine). */
4905	wpi_prph_write(sc, WPI_APMG_CLK_EN,
4906	    WPI_APMG_CLK_CTRL_DMA_CLK_RQT | WPI_APMG_CLK_CTRL_BSM_CLK_RQT);
4907	DELAY(20);
4908	/* Disable L1-Active. */
4909	wpi_prph_setbits(sc, WPI_APMG_PCI_STT, WPI_APMG_PCI_STT_L1A_DIS);
4910	wpi_nic_unlock(sc);
4911
4912	return 0;
4913}
4914
4915static void
4916wpi_apm_stop_master(struct wpi_softc *sc)
4917{
4918	int ntries;
4919
4920	/* Stop busmaster DMA activity. */
4921	WPI_SETBITS(sc, WPI_RESET, WPI_RESET_STOP_MASTER);
4922
4923	if ((WPI_READ(sc, WPI_GP_CNTRL) & WPI_GP_CNTRL_PS_MASK) ==
4924	    WPI_GP_CNTRL_MAC_PS)
4925		return; /* Already asleep. */
4926
4927	for (ntries = 0; ntries < 100; ntries++) {
4928		if (WPI_READ(sc, WPI_RESET) & WPI_RESET_MASTER_DISABLED)
4929			return;
4930		DELAY(10);
4931	}
4932	device_printf(sc->sc_dev, "%s: timeout waiting for master\n",
4933	    __func__);
4934}
4935
4936static void
4937wpi_apm_stop(struct wpi_softc *sc)
4938{
4939	wpi_apm_stop_master(sc);
4940
4941	/* Reset the entire device. */
4942	WPI_SETBITS(sc, WPI_RESET, WPI_RESET_SW);
4943	DELAY(10);
4944	/* Clear "initialization complete" bit. */
4945	WPI_CLRBITS(sc, WPI_GP_CNTRL, WPI_GP_CNTRL_INIT_DONE);
4946}
4947
4948static void
4949wpi_nic_config(struct wpi_softc *sc)
4950{
4951	uint32_t rev;
4952
4953	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
4954
4955	/* voodoo from the Linux "driver".. */
4956	rev = pci_read_config(sc->sc_dev, PCIR_REVID, 1);
4957	if ((rev & 0xc0) == 0x40)
4958		WPI_SETBITS(sc, WPI_HW_IF_CONFIG, WPI_HW_IF_CONFIG_ALM_MB);
4959	else if (!(rev & 0x80))
4960		WPI_SETBITS(sc, WPI_HW_IF_CONFIG, WPI_HW_IF_CONFIG_ALM_MM);
4961
4962	if (sc->cap == 0x80)
4963		WPI_SETBITS(sc, WPI_HW_IF_CONFIG, WPI_HW_IF_CONFIG_SKU_MRC);
4964
4965	if ((sc->rev & 0xf0) == 0xd0)
4966		WPI_SETBITS(sc, WPI_HW_IF_CONFIG, WPI_HW_IF_CONFIG_REV_D);
4967	else
4968		WPI_CLRBITS(sc, WPI_HW_IF_CONFIG, WPI_HW_IF_CONFIG_REV_D);
4969
4970	if (sc->type > 1)
4971		WPI_SETBITS(sc, WPI_HW_IF_CONFIG, WPI_HW_IF_CONFIG_TYPE_B);
4972}
4973
4974static int
4975wpi_hw_init(struct wpi_softc *sc)
4976{
4977	int chnl, ntries, error;
4978
4979	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
4980
4981	/* Clear pending interrupts. */
4982	WPI_WRITE(sc, WPI_INT, 0xffffffff);
4983
4984	if ((error = wpi_apm_init(sc)) != 0) {
4985		device_printf(sc->sc_dev,
4986		    "%s: could not power ON adapter, error %d\n", __func__,
4987		    error);
4988		return error;
4989	}
4990
4991	/* Select VMAIN power source. */
4992	if ((error = wpi_nic_lock(sc)) != 0)
4993		return error;
4994	wpi_prph_clrbits(sc, WPI_APMG_PS, WPI_APMG_PS_PWR_SRC_MASK);
4995	wpi_nic_unlock(sc);
4996	/* Spin until VMAIN gets selected. */
4997	for (ntries = 0; ntries < 5000; ntries++) {
4998		if (WPI_READ(sc, WPI_GPIO_IN) & WPI_GPIO_IN_VMAIN)
4999			break;
5000		DELAY(10);
5001	}
5002	if (ntries == 5000) {
5003		device_printf(sc->sc_dev, "timeout selecting power source\n");
5004		return ETIMEDOUT;
5005	}
5006
5007	/* Perform adapter initialization. */
5008	wpi_nic_config(sc);
5009
5010	/* Initialize RX ring. */
5011	if ((error = wpi_nic_lock(sc)) != 0)
5012		return error;
5013	/* Set physical address of RX ring. */
5014	WPI_WRITE(sc, WPI_FH_RX_BASE, sc->rxq.desc_dma.paddr);
5015	/* Set physical address of RX read pointer. */
5016	WPI_WRITE(sc, WPI_FH_RX_RPTR_ADDR, sc->shared_dma.paddr +
5017	    offsetof(struct wpi_shared, next));
5018	WPI_WRITE(sc, WPI_FH_RX_WPTR, 0);
5019	/* Enable RX. */
5020	WPI_WRITE(sc, WPI_FH_RX_CONFIG,
5021	    WPI_FH_RX_CONFIG_DMA_ENA |
5022	    WPI_FH_RX_CONFIG_RDRBD_ENA |
5023	    WPI_FH_RX_CONFIG_WRSTATUS_ENA |
5024	    WPI_FH_RX_CONFIG_MAXFRAG |
5025	    WPI_FH_RX_CONFIG_NRBD(WPI_RX_RING_COUNT_LOG) |
5026	    WPI_FH_RX_CONFIG_IRQ_DST_HOST |
5027	    WPI_FH_RX_CONFIG_IRQ_TIMEOUT(1));
5028	(void)WPI_READ(sc, WPI_FH_RSSR_TBL);	/* barrier */
5029	wpi_nic_unlock(sc);
5030	WPI_WRITE(sc, WPI_FH_RX_WPTR, (WPI_RX_RING_COUNT - 1) & ~7);
5031
5032	/* Initialize TX rings. */
5033	if ((error = wpi_nic_lock(sc)) != 0)
5034		return error;
5035	wpi_prph_write(sc, WPI_ALM_SCHED_MODE, 2);	/* bypass mode */
5036	wpi_prph_write(sc, WPI_ALM_SCHED_ARASTAT, 1);	/* enable RA0 */
5037	/* Enable all 6 TX rings. */
5038	wpi_prph_write(sc, WPI_ALM_SCHED_TXFACT, 0x3f);
5039	wpi_prph_write(sc, WPI_ALM_SCHED_SBYPASS_MODE1, 0x10000);
5040	wpi_prph_write(sc, WPI_ALM_SCHED_SBYPASS_MODE2, 0x30002);
5041	wpi_prph_write(sc, WPI_ALM_SCHED_TXF4MF, 4);
5042	wpi_prph_write(sc, WPI_ALM_SCHED_TXF5MF, 5);
5043	/* Set physical address of TX rings. */
5044	WPI_WRITE(sc, WPI_FH_TX_BASE, sc->shared_dma.paddr);
5045	WPI_WRITE(sc, WPI_FH_MSG_CONFIG, 0xffff05a5);
5046
5047	/* Enable all DMA channels. */
5048	for (chnl = 0; chnl < WPI_NDMACHNLS; chnl++) {
5049		WPI_WRITE(sc, WPI_FH_CBBC_CTRL(chnl), 0);
5050		WPI_WRITE(sc, WPI_FH_CBBC_BASE(chnl), 0);
5051		WPI_WRITE(sc, WPI_FH_TX_CONFIG(chnl), 0x80200008);
5052	}
5053	wpi_nic_unlock(sc);
5054	(void)WPI_READ(sc, WPI_FH_TX_BASE);	/* barrier */
5055
5056	/* Clear "radio off" and "commands blocked" bits. */
5057	WPI_WRITE(sc, WPI_UCODE_GP1_CLR, WPI_UCODE_GP1_RFKILL);
5058	WPI_WRITE(sc, WPI_UCODE_GP1_CLR, WPI_UCODE_GP1_CMD_BLOCKED);
5059
5060	/* Clear pending interrupts. */
5061	WPI_WRITE(sc, WPI_INT, 0xffffffff);
5062	/* Enable interrupts. */
5063	WPI_WRITE(sc, WPI_INT_MASK, WPI_INT_MASK_DEF);
5064
5065	/* _Really_ make sure "radio off" bit is cleared! */
5066	WPI_WRITE(sc, WPI_UCODE_GP1_CLR, WPI_UCODE_GP1_RFKILL);
5067	WPI_WRITE(sc, WPI_UCODE_GP1_CLR, WPI_UCODE_GP1_RFKILL);
5068
5069	if ((error = wpi_load_firmware(sc)) != 0) {
5070		device_printf(sc->sc_dev,
5071		    "%s: could not load firmware, error %d\n", __func__,
5072		    error);
5073		return error;
5074	}
5075	/* Wait at most one second for firmware alive notification. */
5076	if ((error = mtx_sleep(sc, &sc->sc_mtx, PCATCH, "wpiinit", hz)) != 0) {
5077		device_printf(sc->sc_dev,
5078		    "%s: timeout waiting for adapter to initialize, error %d\n",
5079		    __func__, error);
5080		return error;
5081	}
5082
5083	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
5084
5085	/* Do post-firmware initialization. */
5086	return wpi_post_alive(sc);
5087}
5088
5089static void
5090wpi_hw_stop(struct wpi_softc *sc)
5091{
5092	int chnl, qid, ntries;
5093
5094	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
5095
5096	if (WPI_READ(sc, WPI_UCODE_GP1) & WPI_UCODE_GP1_MAC_SLEEP)
5097		wpi_nic_lock(sc);
5098
5099	WPI_WRITE(sc, WPI_RESET, WPI_RESET_NEVO);
5100
5101	/* Disable interrupts. */
5102	WPI_WRITE(sc, WPI_INT_MASK, 0);
5103	WPI_WRITE(sc, WPI_INT, 0xffffffff);
5104	WPI_WRITE(sc, WPI_FH_INT, 0xffffffff);
5105
5106	/* Make sure we no longer hold the NIC lock. */
5107	wpi_nic_unlock(sc);
5108
5109	if (wpi_nic_lock(sc) == 0) {
5110		/* Stop TX scheduler. */
5111		wpi_prph_write(sc, WPI_ALM_SCHED_MODE, 0);
5112		wpi_prph_write(sc, WPI_ALM_SCHED_TXFACT, 0);
5113
5114		/* Stop all DMA channels. */
5115		for (chnl = 0; chnl < WPI_NDMACHNLS; chnl++) {
5116			WPI_WRITE(sc, WPI_FH_TX_CONFIG(chnl), 0);
5117			for (ntries = 0; ntries < 200; ntries++) {
5118				if (WPI_READ(sc, WPI_FH_TX_STATUS) &
5119				    WPI_FH_TX_STATUS_IDLE(chnl))
5120					break;
5121				DELAY(10);
5122			}
5123		}
5124		wpi_nic_unlock(sc);
5125	}
5126
5127	/* Stop RX ring. */
5128	wpi_reset_rx_ring(sc);
5129
5130	/* Reset all TX rings. */
5131	for (qid = 0; qid < WPI_NTXQUEUES; qid++)
5132		wpi_reset_tx_ring(sc, &sc->txq[qid]);
5133
5134	if (wpi_nic_lock(sc) == 0) {
5135		wpi_prph_write(sc, WPI_APMG_CLK_DIS,
5136		    WPI_APMG_CLK_CTRL_DMA_CLK_RQT);
5137		wpi_nic_unlock(sc);
5138	}
5139	DELAY(5);
5140	/* Power OFF adapter. */
5141	wpi_apm_stop(sc);
5142}
5143
5144static void
5145wpi_radio_on(void *arg0, int pending)
5146{
5147	struct wpi_softc *sc = arg0;
5148	struct ifnet *ifp = sc->sc_ifp;
5149	struct ieee80211com *ic = ifp->if_l2com;
5150	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
5151
5152	device_printf(sc->sc_dev, "RF switch: radio enabled\n");
5153
5154	if (vap != NULL) {
5155		wpi_init(sc);
5156		ieee80211_init(vap);
5157	}
5158
5159	if (WPI_READ(sc, WPI_GP_CNTRL) & WPI_GP_CNTRL_RFKILL) {
5160		WPI_LOCK(sc);
5161		callout_stop(&sc->watchdog_rfkill);
5162		WPI_UNLOCK(sc);
5163	}
5164}
5165
5166static void
5167wpi_radio_off(void *arg0, int pending)
5168{
5169	struct wpi_softc *sc = arg0;
5170	struct ifnet *ifp = sc->sc_ifp;
5171	struct ieee80211com *ic = ifp->if_l2com;
5172	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
5173
5174	device_printf(sc->sc_dev, "RF switch: radio disabled\n");
5175
5176	wpi_stop(sc);
5177	if (vap != NULL)
5178		ieee80211_stop(vap);
5179
5180	WPI_LOCK(sc);
5181	callout_reset(&sc->watchdog_rfkill, hz, wpi_watchdog_rfkill, sc);
5182	WPI_UNLOCK(sc);
5183}
5184
5185static void
5186wpi_init(void *arg)
5187{
5188	struct wpi_softc *sc = arg;
5189	struct ifnet *ifp = sc->sc_ifp;
5190	struct ieee80211com *ic = ifp->if_l2com;
5191	int error;
5192
5193	WPI_LOCK(sc);
5194
5195	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
5196
5197	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) != 0)
5198		goto end;
5199
5200	/* Check that the radio is not disabled by hardware switch. */
5201	if (!(WPI_READ(sc, WPI_GP_CNTRL) & WPI_GP_CNTRL_RFKILL)) {
5202		device_printf(sc->sc_dev,
5203		    "RF switch: radio disabled (%s)\n", __func__);
5204		callout_reset(&sc->watchdog_rfkill, hz, wpi_watchdog_rfkill,
5205		    sc);
5206		goto end;
5207	}
5208
5209	/* Read firmware images from the filesystem. */
5210	if ((error = wpi_read_firmware(sc)) != 0) {
5211		device_printf(sc->sc_dev,
5212		    "%s: could not read firmware, error %d\n", __func__,
5213		    error);
5214		goto fail;
5215	}
5216
5217	/* Initialize hardware and upload firmware. */
5218	error = wpi_hw_init(sc);
5219	wpi_unload_firmware(sc);
5220	if (error != 0) {
5221		device_printf(sc->sc_dev,
5222		    "%s: could not initialize hardware, error %d\n", __func__,
5223		    error);
5224		goto fail;
5225	}
5226
5227	/* Configure adapter now that it is ready. */
5228	sc->txq_active = 1;
5229	if ((error = wpi_config(sc)) != 0) {
5230		device_printf(sc->sc_dev,
5231		    "%s: could not configure device, error %d\n", __func__,
5232		    error);
5233		goto fail;
5234	}
5235
5236	IF_LOCK(&ifp->if_snd);
5237	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
5238	ifp->if_drv_flags |= IFF_DRV_RUNNING;
5239	IF_UNLOCK(&ifp->if_snd);
5240
5241	callout_reset(&sc->watchdog_to, hz, wpi_watchdog, sc);
5242
5243	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
5244
5245	WPI_UNLOCK(sc);
5246
5247	ieee80211_start_all(ic);
5248
5249	return;
5250
5251fail:	wpi_stop_locked(sc);
5252end:	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR, __func__);
5253	WPI_UNLOCK(sc);
5254}
5255
5256static void
5257wpi_stop_locked(struct wpi_softc *sc)
5258{
5259	struct ifnet *ifp = sc->sc_ifp;
5260
5261	WPI_LOCK_ASSERT(sc);
5262
5263	WPI_TXQ_LOCK(sc);
5264	sc->txq_active = 0;
5265	WPI_TXQ_UNLOCK(sc);
5266
5267	sc->sc_scan_timer = 0;
5268	sc->sc_tx_timer = 0;
5269	callout_stop(&sc->watchdog_to);
5270	callout_stop(&sc->calib_to);
5271
5272	IF_LOCK(&ifp->if_snd);
5273	ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
5274	IF_UNLOCK(&ifp->if_snd);
5275
5276	/* Power OFF hardware. */
5277	wpi_hw_stop(sc);
5278}
5279
5280static void
5281wpi_stop(struct wpi_softc *sc)
5282{
5283	WPI_LOCK(sc);
5284	wpi_stop_locked(sc);
5285	WPI_UNLOCK(sc);
5286}
5287
5288/*
5289 * Callback from net80211 to start a scan.
5290 */
5291static void
5292wpi_scan_start(struct ieee80211com *ic)
5293{
5294	struct wpi_softc *sc = ic->ic_ifp->if_softc;
5295
5296	wpi_set_led(sc, WPI_LED_LINK, 20, 2);
5297}
5298
5299/*
5300 * Callback from net80211 to terminate a scan.
5301 */
5302static void
5303wpi_scan_end(struct ieee80211com *ic)
5304{
5305	struct ifnet *ifp = ic->ic_ifp;
5306	struct wpi_softc *sc = ifp->if_softc;
5307	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
5308
5309	if (vap->iv_state == IEEE80211_S_RUN)
5310		wpi_set_led(sc, WPI_LED_LINK, 0, 1);
5311}
5312
5313/**
5314 * Called by the net80211 framework to indicate to the driver
5315 * that the channel should be changed
5316 */
5317static void
5318wpi_set_channel(struct ieee80211com *ic)
5319{
5320	const struct ieee80211_channel *c = ic->ic_curchan;
5321	struct ifnet *ifp = ic->ic_ifp;
5322	struct wpi_softc *sc = ifp->if_softc;
5323	int error;
5324
5325	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
5326
5327	WPI_LOCK(sc);
5328	sc->sc_rxtap.wr_chan_freq = htole16(c->ic_freq);
5329	sc->sc_rxtap.wr_chan_flags = htole16(c->ic_flags);
5330	sc->sc_txtap.wt_chan_freq = htole16(c->ic_freq);
5331	sc->sc_txtap.wt_chan_flags = htole16(c->ic_flags);
5332
5333	/*
5334	 * Only need to set the channel in Monitor mode. AP scanning and auth
5335	 * are already taken care of by their respective firmware commands.
5336	 */
5337	if (ic->ic_opmode == IEEE80211_M_MONITOR) {
5338		sc->rxon.chan = ieee80211_chan2ieee(ic, c);
5339		if (IEEE80211_IS_CHAN_2GHZ(c)) {
5340			sc->rxon.flags |= htole32(WPI_RXON_AUTO |
5341			    WPI_RXON_24GHZ);
5342		} else {
5343			sc->rxon.flags &= ~htole32(WPI_RXON_AUTO |
5344			    WPI_RXON_24GHZ);
5345		}
5346		if ((error = wpi_send_rxon(sc, 0, 0)) != 0)
5347			device_printf(sc->sc_dev,
5348			    "%s: error %d settting channel\n", __func__,
5349			    error);
5350	}
5351	WPI_UNLOCK(sc);
5352}
5353
5354/**
5355 * Called by net80211 to indicate that we need to scan the current
5356 * channel. The channel is previously be set via the wpi_set_channel
5357 * callback.
5358 */
5359static void
5360wpi_scan_curchan(struct ieee80211_scan_state *ss, unsigned long maxdwell)
5361{
5362	struct ieee80211vap *vap = ss->ss_vap;
5363	struct ieee80211com *ic = vap->iv_ic;
5364	struct wpi_softc *sc = ic->ic_ifp->if_softc;
5365	int error;
5366
5367	if (sc->rxon.chan != ieee80211_chan2ieee(ic, ic->ic_curchan)) {
5368		WPI_LOCK(sc);
5369		error = wpi_scan(sc, ic->ic_curchan);
5370		WPI_UNLOCK(sc);
5371		if (error != 0)
5372			ieee80211_cancel_scan(vap);
5373	} else {
5374		/* Send probe request when associated. */
5375		sc->sc_scan_curchan(ss, maxdwell);
5376	}
5377}
5378
5379/**
5380 * Called by the net80211 framework to indicate
5381 * the minimum dwell time has been met, terminate the scan.
5382 * We don't actually terminate the scan as the firmware will notify
5383 * us when it's finished and we have no way to interrupt it.
5384 */
5385static void
5386wpi_scan_mindwell(struct ieee80211_scan_state *ss)
5387{
5388	/* NB: don't try to abort scan; wait for firmware to finish */
5389}
5390
5391static void
5392wpi_hw_reset(void *arg, int pending)
5393{
5394	struct wpi_softc *sc = arg;
5395	struct ifnet *ifp = sc->sc_ifp;
5396	struct ieee80211com *ic = ifp->if_l2com;
5397	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
5398
5399	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
5400
5401	wpi_stop(sc);
5402	if (vap != NULL)
5403		ieee80211_stop(vap);
5404	wpi_init(sc);
5405	if (vap != NULL)
5406		ieee80211_init(vap);
5407}
5408