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