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