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