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