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