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