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