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