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