1/*-
2 * Copyright (c) 2004, 2005
3 *      Damien Bergamini <damien.bergamini@free.fr>. All rights reserved.
4 * Copyright (c) 2005-2006 Sam Leffler, Errno Consulting
5 * Copyright (c) 2007 Andrew Thompson <thompsa@FreeBSD.org>
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice unmodified, this list of conditions, and the following
12 *    disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 */
29
30#include <sys/cdefs.h>
31__FBSDID("$FreeBSD: stable/11/sys/dev/iwi/if_iwi.c 347511 2019-05-12 12:30:45Z avos $");
32
33/*-
34 * Intel(R) PRO/Wireless 2200BG/2225BG/2915ABG driver
35 * http://www.intel.com/network/connectivity/products/wireless/prowireless_mobile.htm
36 */
37
38#include <sys/param.h>
39#include <sys/sysctl.h>
40#include <sys/sockio.h>
41#include <sys/mbuf.h>
42#include <sys/kernel.h>
43#include <sys/socket.h>
44#include <sys/systm.h>
45#include <sys/malloc.h>
46#include <sys/lock.h>
47#include <sys/mutex.h>
48#include <sys/module.h>
49#include <sys/bus.h>
50#include <sys/endian.h>
51#include <sys/proc.h>
52#include <sys/mount.h>
53#include <sys/namei.h>
54#include <sys/linker.h>
55#include <sys/firmware.h>
56#include <sys/taskqueue.h>
57
58#include <machine/bus.h>
59#include <machine/resource.h>
60#include <sys/rman.h>
61
62#include <dev/pci/pcireg.h>
63#include <dev/pci/pcivar.h>
64
65#include <net/bpf.h>
66#include <net/if.h>
67#include <net/if_var.h>
68#include <net/if_arp.h>
69#include <net/ethernet.h>
70#include <net/if_dl.h>
71#include <net/if_media.h>
72#include <net/if_types.h>
73
74#include <net80211/ieee80211_var.h>
75#include <net80211/ieee80211_radiotap.h>
76#include <net80211/ieee80211_input.h>
77#include <net80211/ieee80211_regdomain.h>
78
79#include <netinet/in.h>
80#include <netinet/in_systm.h>
81#include <netinet/in_var.h>
82#include <netinet/ip.h>
83#include <netinet/if_ether.h>
84
85#include <dev/iwi/if_iwireg.h>
86#include <dev/iwi/if_iwivar.h>
87#include <dev/iwi/if_iwi_ioctl.h>
88
89#define IWI_DEBUG
90#ifdef IWI_DEBUG
91#define DPRINTF(x)	do { if (iwi_debug > 0) printf x; } while (0)
92#define DPRINTFN(n, x)	do { if (iwi_debug >= (n)) printf x; } while (0)
93int iwi_debug = 0;
94SYSCTL_INT(_debug, OID_AUTO, iwi, CTLFLAG_RW, &iwi_debug, 0, "iwi debug level");
95
96static const char *iwi_fw_states[] = {
97	"IDLE", 		/* IWI_FW_IDLE */
98	"LOADING",		/* IWI_FW_LOADING */
99	"ASSOCIATING",		/* IWI_FW_ASSOCIATING */
100	"DISASSOCIATING",	/* IWI_FW_DISASSOCIATING */
101	"SCANNING",		/* IWI_FW_SCANNING */
102};
103#else
104#define DPRINTF(x)
105#define DPRINTFN(n, x)
106#endif
107
108MODULE_DEPEND(iwi, pci,  1, 1, 1);
109MODULE_DEPEND(iwi, wlan, 1, 1, 1);
110MODULE_DEPEND(iwi, firmware, 1, 1, 1);
111
112enum {
113	IWI_LED_TX,
114	IWI_LED_RX,
115	IWI_LED_POLL,
116};
117
118struct iwi_ident {
119	uint16_t	vendor;
120	uint16_t	device;
121	const char	*name;
122};
123
124static const struct iwi_ident iwi_ident_table[] = {
125	{ 0x8086, 0x4220, "Intel(R) PRO/Wireless 2200BG" },
126	{ 0x8086, 0x4221, "Intel(R) PRO/Wireless 2225BG" },
127	{ 0x8086, 0x4223, "Intel(R) PRO/Wireless 2915ABG" },
128	{ 0x8086, 0x4224, "Intel(R) PRO/Wireless 2915ABG" },
129
130	{ 0, 0, NULL }
131};
132
133static const uint8_t def_chan_5ghz_band1[] =
134	{ 36, 40, 44, 48, 52, 56, 60, 64 };
135static const uint8_t def_chan_5ghz_band2[] =
136	{ 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140 };
137static const uint8_t def_chan_5ghz_band3[] =
138	{ 149, 153, 157, 161, 165 };
139
140static struct ieee80211vap *iwi_vap_create(struct ieee80211com *,
141		    const char [IFNAMSIZ], int, enum ieee80211_opmode, int,
142		    const uint8_t [IEEE80211_ADDR_LEN],
143		    const uint8_t [IEEE80211_ADDR_LEN]);
144static void	iwi_vap_delete(struct ieee80211vap *);
145static void	iwi_dma_map_addr(void *, bus_dma_segment_t *, int, int);
146static int	iwi_alloc_cmd_ring(struct iwi_softc *, struct iwi_cmd_ring *,
147		    int);
148static void	iwi_reset_cmd_ring(struct iwi_softc *, struct iwi_cmd_ring *);
149static void	iwi_free_cmd_ring(struct iwi_softc *, struct iwi_cmd_ring *);
150static int	iwi_alloc_tx_ring(struct iwi_softc *, struct iwi_tx_ring *,
151		    int, bus_addr_t, bus_addr_t);
152static void	iwi_reset_tx_ring(struct iwi_softc *, struct iwi_tx_ring *);
153static void	iwi_free_tx_ring(struct iwi_softc *, struct iwi_tx_ring *);
154static int	iwi_alloc_rx_ring(struct iwi_softc *, struct iwi_rx_ring *,
155		    int);
156static void	iwi_reset_rx_ring(struct iwi_softc *, struct iwi_rx_ring *);
157static void	iwi_free_rx_ring(struct iwi_softc *, struct iwi_rx_ring *);
158static struct ieee80211_node *iwi_node_alloc(struct ieee80211vap *,
159		    const uint8_t [IEEE80211_ADDR_LEN]);
160static void	iwi_node_free(struct ieee80211_node *);
161static void	iwi_media_status(struct ifnet *, struct ifmediareq *);
162static int	iwi_newstate(struct ieee80211vap *, enum ieee80211_state, int);
163static void	iwi_wme_init(struct iwi_softc *);
164static int	iwi_wme_setparams(struct iwi_softc *);
165static int	iwi_wme_update(struct ieee80211com *);
166static uint16_t	iwi_read_prom_word(struct iwi_softc *, uint8_t);
167static void	iwi_frame_intr(struct iwi_softc *, struct iwi_rx_data *, int,
168		    struct iwi_frame *);
169static void	iwi_notification_intr(struct iwi_softc *, struct iwi_notif *);
170static void	iwi_rx_intr(struct iwi_softc *);
171static void	iwi_tx_intr(struct iwi_softc *, struct iwi_tx_ring *);
172static void	iwi_intr(void *);
173static int	iwi_cmd(struct iwi_softc *, uint8_t, void *, uint8_t);
174static void	iwi_write_ibssnode(struct iwi_softc *, const u_int8_t [], int);
175static int	iwi_tx_start(struct iwi_softc *, struct mbuf *,
176		    struct ieee80211_node *, int);
177static int	iwi_raw_xmit(struct ieee80211_node *, struct mbuf *,
178		    const struct ieee80211_bpf_params *);
179static void	iwi_start(struct iwi_softc *);
180static int	iwi_transmit(struct ieee80211com *, struct mbuf *);
181static void	iwi_watchdog(void *);
182static int	iwi_ioctl(struct ieee80211com *, u_long, void *);
183static void	iwi_parent(struct ieee80211com *);
184static void	iwi_stop_master(struct iwi_softc *);
185static int	iwi_reset(struct iwi_softc *);
186static int	iwi_load_ucode(struct iwi_softc *, const struct iwi_fw *);
187static int	iwi_load_firmware(struct iwi_softc *, const struct iwi_fw *);
188static void	iwi_release_fw_dma(struct iwi_softc *sc);
189static int	iwi_config(struct iwi_softc *);
190static int	iwi_get_firmware(struct iwi_softc *, enum ieee80211_opmode);
191static void	iwi_put_firmware(struct iwi_softc *);
192static void	iwi_monitor_scan(void *, int);
193static int	iwi_scanchan(struct iwi_softc *, unsigned long, int);
194static void	iwi_scan_start(struct ieee80211com *);
195static void	iwi_scan_end(struct ieee80211com *);
196static void	iwi_set_channel(struct ieee80211com *);
197static void	iwi_scan_curchan(struct ieee80211_scan_state *, unsigned long maxdwell);
198static void	iwi_scan_mindwell(struct ieee80211_scan_state *);
199static int	iwi_auth_and_assoc(struct iwi_softc *, struct ieee80211vap *);
200static void	iwi_disassoc(void *, int);
201static int	iwi_disassociate(struct iwi_softc *, int quiet);
202static void	iwi_init_locked(struct iwi_softc *);
203static void	iwi_init(void *);
204static int	iwi_init_fw_dma(struct iwi_softc *, int);
205static void	iwi_stop_locked(void *);
206static void	iwi_stop(struct iwi_softc *);
207static void	iwi_restart(void *, int);
208static int	iwi_getrfkill(struct iwi_softc *);
209static void	iwi_radio_on(void *, int);
210static void	iwi_radio_off(void *, int);
211static void	iwi_sysctlattach(struct iwi_softc *);
212static void	iwi_led_event(struct iwi_softc *, int);
213static void	iwi_ledattach(struct iwi_softc *);
214static void	iwi_collect_bands(struct ieee80211com *, uint8_t [], size_t);
215static void	iwi_getradiocaps(struct ieee80211com *, int, int *,
216		    struct ieee80211_channel []);
217
218static int iwi_probe(device_t);
219static int iwi_attach(device_t);
220static int iwi_detach(device_t);
221static int iwi_shutdown(device_t);
222static int iwi_suspend(device_t);
223static int iwi_resume(device_t);
224
225static device_method_t iwi_methods[] = {
226	/* Device interface */
227	DEVMETHOD(device_probe,		iwi_probe),
228	DEVMETHOD(device_attach,	iwi_attach),
229	DEVMETHOD(device_detach,	iwi_detach),
230	DEVMETHOD(device_shutdown,	iwi_shutdown),
231	DEVMETHOD(device_suspend,	iwi_suspend),
232	DEVMETHOD(device_resume,	iwi_resume),
233
234	DEVMETHOD_END
235};
236
237static driver_t iwi_driver = {
238	"iwi",
239	iwi_methods,
240	sizeof (struct iwi_softc)
241};
242
243static devclass_t iwi_devclass;
244
245DRIVER_MODULE(iwi, pci, iwi_driver, iwi_devclass, NULL, NULL);
246
247MODULE_VERSION(iwi, 1);
248
249static __inline uint8_t
250MEM_READ_1(struct iwi_softc *sc, uint32_t addr)
251{
252	CSR_WRITE_4(sc, IWI_CSR_INDIRECT_ADDR, addr);
253	return CSR_READ_1(sc, IWI_CSR_INDIRECT_DATA);
254}
255
256static __inline uint32_t
257MEM_READ_4(struct iwi_softc *sc, uint32_t addr)
258{
259	CSR_WRITE_4(sc, IWI_CSR_INDIRECT_ADDR, addr);
260	return CSR_READ_4(sc, IWI_CSR_INDIRECT_DATA);
261}
262
263static int
264iwi_probe(device_t dev)
265{
266	const struct iwi_ident *ident;
267
268	for (ident = iwi_ident_table; ident->name != NULL; ident++) {
269		if (pci_get_vendor(dev) == ident->vendor &&
270		    pci_get_device(dev) == ident->device) {
271			device_set_desc(dev, ident->name);
272			return (BUS_PROBE_DEFAULT);
273		}
274	}
275	return ENXIO;
276}
277
278static int
279iwi_attach(device_t dev)
280{
281	struct iwi_softc *sc = device_get_softc(dev);
282	struct ieee80211com *ic = &sc->sc_ic;
283	uint16_t val;
284	int i, error;
285
286	sc->sc_dev = dev;
287	sc->sc_ledevent = ticks;
288
289	IWI_LOCK_INIT(sc);
290	mbufq_init(&sc->sc_snd, ifqmaxlen);
291
292	sc->sc_unr = new_unrhdr(1, IWI_MAX_IBSSNODE-1, &sc->sc_mtx);
293
294	TASK_INIT(&sc->sc_radiontask, 0, iwi_radio_on, sc);
295	TASK_INIT(&sc->sc_radiofftask, 0, iwi_radio_off, sc);
296	TASK_INIT(&sc->sc_restarttask, 0, iwi_restart, sc);
297	TASK_INIT(&sc->sc_disassoctask, 0, iwi_disassoc, sc);
298	TASK_INIT(&sc->sc_monitortask, 0, iwi_monitor_scan, sc);
299
300	callout_init_mtx(&sc->sc_wdtimer, &sc->sc_mtx, 0);
301	callout_init_mtx(&sc->sc_rftimer, &sc->sc_mtx, 0);
302
303	pci_write_config(dev, 0x41, 0, 1);
304
305	/* enable bus-mastering */
306	pci_enable_busmaster(dev);
307
308	i = PCIR_BAR(0);
309	sc->mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &i, RF_ACTIVE);
310	if (sc->mem == NULL) {
311		device_printf(dev, "could not allocate memory resource\n");
312		goto fail;
313	}
314
315	sc->sc_st = rman_get_bustag(sc->mem);
316	sc->sc_sh = rman_get_bushandle(sc->mem);
317
318	i = 0;
319	sc->irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &i,
320	    RF_ACTIVE | RF_SHAREABLE);
321	if (sc->irq == NULL) {
322		device_printf(dev, "could not allocate interrupt resource\n");
323		goto fail;
324	}
325
326	if (iwi_reset(sc) != 0) {
327		device_printf(dev, "could not reset adapter\n");
328		goto fail;
329	}
330
331	/*
332	 * Allocate rings.
333	 */
334	if (iwi_alloc_cmd_ring(sc, &sc->cmdq, IWI_CMD_RING_COUNT) != 0) {
335		device_printf(dev, "could not allocate Cmd ring\n");
336		goto fail;
337	}
338
339	for (i = 0; i < 4; i++) {
340		error = iwi_alloc_tx_ring(sc, &sc->txq[i], IWI_TX_RING_COUNT,
341		    IWI_CSR_TX1_RIDX + i * 4,
342		    IWI_CSR_TX1_WIDX + i * 4);
343		if (error != 0) {
344			device_printf(dev, "could not allocate Tx ring %d\n",
345				i+i);
346			goto fail;
347		}
348	}
349
350	if (iwi_alloc_rx_ring(sc, &sc->rxq, IWI_RX_RING_COUNT) != 0) {
351		device_printf(dev, "could not allocate Rx ring\n");
352		goto fail;
353	}
354
355	iwi_wme_init(sc);
356
357	ic->ic_softc = sc;
358	ic->ic_name = device_get_nameunit(dev);
359	ic->ic_opmode = IEEE80211_M_STA;
360	ic->ic_phytype = IEEE80211_T_OFDM; /* not only, but not used */
361
362	/* set device capabilities */
363	ic->ic_caps =
364	      IEEE80211_C_STA		/* station mode supported */
365	    | IEEE80211_C_IBSS		/* IBSS mode supported */
366	    | IEEE80211_C_MONITOR	/* monitor mode supported */
367	    | IEEE80211_C_PMGT		/* power save supported */
368	    | IEEE80211_C_SHPREAMBLE	/* short preamble supported */
369	    | IEEE80211_C_WPA		/* 802.11i */
370	    | IEEE80211_C_WME		/* 802.11e */
371#if 0
372	    | IEEE80211_C_BGSCAN	/* capable of bg scanning */
373#endif
374	    ;
375
376	/* read MAC address from EEPROM */
377	val = iwi_read_prom_word(sc, IWI_EEPROM_MAC + 0);
378	ic->ic_macaddr[0] = val & 0xff;
379	ic->ic_macaddr[1] = val >> 8;
380	val = iwi_read_prom_word(sc, IWI_EEPROM_MAC + 1);
381	ic->ic_macaddr[2] = val & 0xff;
382	ic->ic_macaddr[3] = val >> 8;
383	val = iwi_read_prom_word(sc, IWI_EEPROM_MAC + 2);
384	ic->ic_macaddr[4] = val & 0xff;
385	ic->ic_macaddr[5] = val >> 8;
386
387	iwi_getradiocaps(ic, IEEE80211_CHAN_MAX, &ic->ic_nchans,
388	    ic->ic_channels);
389
390	ieee80211_ifattach(ic);
391	/* override default methods */
392	ic->ic_node_alloc = iwi_node_alloc;
393	sc->sc_node_free = ic->ic_node_free;
394	ic->ic_node_free = iwi_node_free;
395	ic->ic_raw_xmit = iwi_raw_xmit;
396	ic->ic_scan_start = iwi_scan_start;
397	ic->ic_scan_end = iwi_scan_end;
398	ic->ic_set_channel = iwi_set_channel;
399	ic->ic_scan_curchan = iwi_scan_curchan;
400	ic->ic_scan_mindwell = iwi_scan_mindwell;
401	ic->ic_wme.wme_update = iwi_wme_update;
402
403	ic->ic_vap_create = iwi_vap_create;
404	ic->ic_vap_delete = iwi_vap_delete;
405	ic->ic_ioctl = iwi_ioctl;
406	ic->ic_transmit = iwi_transmit;
407	ic->ic_parent = iwi_parent;
408	ic->ic_getradiocaps = iwi_getradiocaps;
409
410	ieee80211_radiotap_attach(ic,
411	    &sc->sc_txtap.wt_ihdr, sizeof(sc->sc_txtap),
412		IWI_TX_RADIOTAP_PRESENT,
413	    &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap),
414		IWI_RX_RADIOTAP_PRESENT);
415
416	iwi_sysctlattach(sc);
417	iwi_ledattach(sc);
418
419	/*
420	 * Hook our interrupt after all initialization is complete.
421	 */
422	error = bus_setup_intr(dev, sc->irq, INTR_TYPE_NET | INTR_MPSAFE,
423	    NULL, iwi_intr, sc, &sc->sc_ih);
424	if (error != 0) {
425		device_printf(dev, "could not set up interrupt\n");
426		goto fail;
427	}
428
429	if (bootverbose)
430		ieee80211_announce(ic);
431
432	return 0;
433fail:
434	/* XXX fix */
435	iwi_detach(dev);
436	return ENXIO;
437}
438
439static int
440iwi_detach(device_t dev)
441{
442	struct iwi_softc *sc = device_get_softc(dev);
443	struct ieee80211com *ic = &sc->sc_ic;
444
445	bus_teardown_intr(dev, sc->irq, sc->sc_ih);
446
447	/* NB: do early to drain any pending tasks */
448	ieee80211_draintask(ic, &sc->sc_radiontask);
449	ieee80211_draintask(ic, &sc->sc_radiofftask);
450	ieee80211_draintask(ic, &sc->sc_restarttask);
451	ieee80211_draintask(ic, &sc->sc_disassoctask);
452	ieee80211_draintask(ic, &sc->sc_monitortask);
453
454	iwi_stop(sc);
455
456	ieee80211_ifdetach(ic);
457
458	iwi_put_firmware(sc);
459	iwi_release_fw_dma(sc);
460
461	iwi_free_cmd_ring(sc, &sc->cmdq);
462	iwi_free_tx_ring(sc, &sc->txq[0]);
463	iwi_free_tx_ring(sc, &sc->txq[1]);
464	iwi_free_tx_ring(sc, &sc->txq[2]);
465	iwi_free_tx_ring(sc, &sc->txq[3]);
466	iwi_free_rx_ring(sc, &sc->rxq);
467
468	bus_release_resource(dev, SYS_RES_IRQ, rman_get_rid(sc->irq), sc->irq);
469
470	bus_release_resource(dev, SYS_RES_MEMORY, rman_get_rid(sc->mem),
471	    sc->mem);
472
473	delete_unrhdr(sc->sc_unr);
474	mbufq_drain(&sc->sc_snd);
475
476	IWI_LOCK_DESTROY(sc);
477
478	return 0;
479}
480
481static struct ieee80211vap *
482iwi_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
483    enum ieee80211_opmode opmode, int flags,
484    const uint8_t bssid[IEEE80211_ADDR_LEN],
485    const uint8_t mac[IEEE80211_ADDR_LEN])
486{
487	struct iwi_softc *sc = ic->ic_softc;
488	struct iwi_vap *ivp;
489	struct ieee80211vap *vap;
490	int i;
491
492	if (!TAILQ_EMPTY(&ic->ic_vaps))		/* only one at a time */
493		return NULL;
494	/*
495	 * Get firmware image (and possibly dma memory) on mode change.
496	 */
497	if (iwi_get_firmware(sc, opmode))
498		return NULL;
499	/* allocate DMA memory for mapping firmware image */
500	i = sc->fw_fw.size;
501	if (sc->fw_boot.size > i)
502		i = sc->fw_boot.size;
503	/* XXX do we dma the ucode as well ? */
504	if (sc->fw_uc.size > i)
505		i = sc->fw_uc.size;
506	if (iwi_init_fw_dma(sc, i))
507		return NULL;
508
509	ivp = malloc(sizeof(struct iwi_vap), M_80211_VAP, M_WAITOK | M_ZERO);
510	vap = &ivp->iwi_vap;
511	ieee80211_vap_setup(ic, vap, name, unit, opmode, flags, bssid);
512	/* override the default, the setting comes from the linux driver */
513	vap->iv_bmissthreshold = 24;
514	/* override with driver methods */
515	ivp->iwi_newstate = vap->iv_newstate;
516	vap->iv_newstate = iwi_newstate;
517
518	/* complete setup */
519	ieee80211_vap_attach(vap, ieee80211_media_change, iwi_media_status,
520	    mac);
521	ic->ic_opmode = opmode;
522	return vap;
523}
524
525static void
526iwi_vap_delete(struct ieee80211vap *vap)
527{
528	struct iwi_vap *ivp = IWI_VAP(vap);
529
530	ieee80211_vap_detach(vap);
531	free(ivp, M_80211_VAP);
532}
533
534static void
535iwi_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
536{
537	if (error != 0)
538		return;
539
540	KASSERT(nseg == 1, ("too many DMA segments, %d should be 1", nseg));
541
542	*(bus_addr_t *)arg = segs[0].ds_addr;
543}
544
545static int
546iwi_alloc_cmd_ring(struct iwi_softc *sc, struct iwi_cmd_ring *ring, int count)
547{
548	int error;
549
550	ring->count = count;
551	ring->queued = 0;
552	ring->cur = ring->next = 0;
553
554	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 4, 0,
555	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
556	    count * IWI_CMD_DESC_SIZE, 1, count * IWI_CMD_DESC_SIZE, 0,
557	    NULL, NULL, &ring->desc_dmat);
558	if (error != 0) {
559		device_printf(sc->sc_dev, "could not create desc DMA tag\n");
560		goto fail;
561	}
562
563	error = bus_dmamem_alloc(ring->desc_dmat, (void **)&ring->desc,
564	    BUS_DMA_NOWAIT | BUS_DMA_ZERO, &ring->desc_map);
565	if (error != 0) {
566		device_printf(sc->sc_dev, "could not allocate DMA memory\n");
567		goto fail;
568	}
569
570	error = bus_dmamap_load(ring->desc_dmat, ring->desc_map, ring->desc,
571	    count * IWI_CMD_DESC_SIZE, iwi_dma_map_addr, &ring->physaddr, 0);
572	if (error != 0) {
573		device_printf(sc->sc_dev, "could not load desc DMA map\n");
574		goto fail;
575	}
576
577	return 0;
578
579fail:	iwi_free_cmd_ring(sc, ring);
580	return error;
581}
582
583static void
584iwi_reset_cmd_ring(struct iwi_softc *sc, struct iwi_cmd_ring *ring)
585{
586	ring->queued = 0;
587	ring->cur = ring->next = 0;
588}
589
590static void
591iwi_free_cmd_ring(struct iwi_softc *sc, struct iwi_cmd_ring *ring)
592{
593	if (ring->desc != NULL) {
594		bus_dmamap_sync(ring->desc_dmat, ring->desc_map,
595		    BUS_DMASYNC_POSTWRITE);
596		bus_dmamap_unload(ring->desc_dmat, ring->desc_map);
597		bus_dmamem_free(ring->desc_dmat, ring->desc, ring->desc_map);
598	}
599
600	if (ring->desc_dmat != NULL)
601		bus_dma_tag_destroy(ring->desc_dmat);
602}
603
604static int
605iwi_alloc_tx_ring(struct iwi_softc *sc, struct iwi_tx_ring *ring, int count,
606    bus_addr_t csr_ridx, bus_addr_t csr_widx)
607{
608	int i, error;
609
610	ring->count = count;
611	ring->queued = 0;
612	ring->cur = ring->next = 0;
613	ring->csr_ridx = csr_ridx;
614	ring->csr_widx = csr_widx;
615
616	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 4, 0,
617	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
618	    count * IWI_TX_DESC_SIZE, 1, count * IWI_TX_DESC_SIZE, 0, NULL,
619	    NULL, &ring->desc_dmat);
620	if (error != 0) {
621		device_printf(sc->sc_dev, "could not create desc DMA tag\n");
622		goto fail;
623	}
624
625	error = bus_dmamem_alloc(ring->desc_dmat, (void **)&ring->desc,
626	    BUS_DMA_NOWAIT | BUS_DMA_ZERO, &ring->desc_map);
627	if (error != 0) {
628		device_printf(sc->sc_dev, "could not allocate DMA memory\n");
629		goto fail;
630	}
631
632	error = bus_dmamap_load(ring->desc_dmat, ring->desc_map, ring->desc,
633	    count * IWI_TX_DESC_SIZE, iwi_dma_map_addr, &ring->physaddr, 0);
634	if (error != 0) {
635		device_printf(sc->sc_dev, "could not load desc DMA map\n");
636		goto fail;
637	}
638
639	ring->data = malloc(count * sizeof (struct iwi_tx_data), M_DEVBUF,
640	    M_NOWAIT | M_ZERO);
641	if (ring->data == NULL) {
642		device_printf(sc->sc_dev, "could not allocate soft data\n");
643		error = ENOMEM;
644		goto fail;
645	}
646
647	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 1, 0,
648	BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES,
649	IWI_MAX_NSEG, MCLBYTES, 0, NULL, NULL, &ring->data_dmat);
650	if (error != 0) {
651		device_printf(sc->sc_dev, "could not create data DMA tag\n");
652		goto fail;
653	}
654
655	for (i = 0; i < count; i++) {
656		error = bus_dmamap_create(ring->data_dmat, 0,
657		    &ring->data[i].map);
658		if (error != 0) {
659			device_printf(sc->sc_dev, "could not create DMA map\n");
660			goto fail;
661		}
662	}
663
664	return 0;
665
666fail:	iwi_free_tx_ring(sc, ring);
667	return error;
668}
669
670static void
671iwi_reset_tx_ring(struct iwi_softc *sc, struct iwi_tx_ring *ring)
672{
673	struct iwi_tx_data *data;
674	int i;
675
676	for (i = 0; i < ring->count; i++) {
677		data = &ring->data[i];
678
679		if (data->m != NULL) {
680			bus_dmamap_sync(ring->data_dmat, data->map,
681			    BUS_DMASYNC_POSTWRITE);
682			bus_dmamap_unload(ring->data_dmat, data->map);
683			m_freem(data->m);
684			data->m = NULL;
685		}
686
687		if (data->ni != NULL) {
688			ieee80211_free_node(data->ni);
689			data->ni = NULL;
690		}
691	}
692
693	ring->queued = 0;
694	ring->cur = ring->next = 0;
695}
696
697static void
698iwi_free_tx_ring(struct iwi_softc *sc, struct iwi_tx_ring *ring)
699{
700	struct iwi_tx_data *data;
701	int i;
702
703	if (ring->desc != NULL) {
704		bus_dmamap_sync(ring->desc_dmat, ring->desc_map,
705		    BUS_DMASYNC_POSTWRITE);
706		bus_dmamap_unload(ring->desc_dmat, ring->desc_map);
707		bus_dmamem_free(ring->desc_dmat, ring->desc, ring->desc_map);
708	}
709
710	if (ring->desc_dmat != NULL)
711		bus_dma_tag_destroy(ring->desc_dmat);
712
713	if (ring->data != NULL) {
714		for (i = 0; i < ring->count; i++) {
715			data = &ring->data[i];
716
717			if (data->m != NULL) {
718				bus_dmamap_sync(ring->data_dmat, data->map,
719				    BUS_DMASYNC_POSTWRITE);
720				bus_dmamap_unload(ring->data_dmat, data->map);
721				m_freem(data->m);
722			}
723
724			if (data->ni != NULL)
725				ieee80211_free_node(data->ni);
726
727			if (data->map != NULL)
728				bus_dmamap_destroy(ring->data_dmat, data->map);
729		}
730
731		free(ring->data, M_DEVBUF);
732	}
733
734	if (ring->data_dmat != NULL)
735		bus_dma_tag_destroy(ring->data_dmat);
736}
737
738static int
739iwi_alloc_rx_ring(struct iwi_softc *sc, struct iwi_rx_ring *ring, int count)
740{
741	struct iwi_rx_data *data;
742	int i, error;
743
744	ring->count = count;
745	ring->cur = 0;
746
747	ring->data = malloc(count * sizeof (struct iwi_rx_data), M_DEVBUF,
748	    M_NOWAIT | M_ZERO);
749	if (ring->data == NULL) {
750		device_printf(sc->sc_dev, "could not allocate soft data\n");
751		error = ENOMEM;
752		goto fail;
753	}
754
755	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 1, 0,
756	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES,
757	    1, MCLBYTES, 0, NULL, NULL, &ring->data_dmat);
758	if (error != 0) {
759		device_printf(sc->sc_dev, "could not create data DMA tag\n");
760		goto fail;
761	}
762
763	for (i = 0; i < count; i++) {
764		data = &ring->data[i];
765
766		error = bus_dmamap_create(ring->data_dmat, 0, &data->map);
767		if (error != 0) {
768			device_printf(sc->sc_dev, "could not create DMA map\n");
769			goto fail;
770		}
771
772		data->m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
773		if (data->m == NULL) {
774			device_printf(sc->sc_dev,
775			    "could not allocate rx mbuf\n");
776			error = ENOMEM;
777			goto fail;
778		}
779
780		error = bus_dmamap_load(ring->data_dmat, data->map,
781		    mtod(data->m, void *), MCLBYTES, iwi_dma_map_addr,
782		    &data->physaddr, 0);
783		if (error != 0) {
784			device_printf(sc->sc_dev,
785			    "could not load rx buf DMA map");
786			goto fail;
787		}
788
789		data->reg = IWI_CSR_RX_BASE + i * 4;
790	}
791
792	return 0;
793
794fail:	iwi_free_rx_ring(sc, ring);
795	return error;
796}
797
798static void
799iwi_reset_rx_ring(struct iwi_softc *sc, struct iwi_rx_ring *ring)
800{
801	ring->cur = 0;
802}
803
804static void
805iwi_free_rx_ring(struct iwi_softc *sc, struct iwi_rx_ring *ring)
806{
807	struct iwi_rx_data *data;
808	int i;
809
810	if (ring->data != NULL) {
811		for (i = 0; i < ring->count; i++) {
812			data = &ring->data[i];
813
814			if (data->m != NULL) {
815				bus_dmamap_sync(ring->data_dmat, data->map,
816				    BUS_DMASYNC_POSTREAD);
817				bus_dmamap_unload(ring->data_dmat, data->map);
818				m_freem(data->m);
819			}
820
821			if (data->map != NULL)
822				bus_dmamap_destroy(ring->data_dmat, data->map);
823		}
824
825		free(ring->data, M_DEVBUF);
826	}
827
828	if (ring->data_dmat != NULL)
829		bus_dma_tag_destroy(ring->data_dmat);
830}
831
832static int
833iwi_shutdown(device_t dev)
834{
835	struct iwi_softc *sc = device_get_softc(dev);
836
837	iwi_stop(sc);
838	iwi_put_firmware(sc);		/* ??? XXX */
839
840	return 0;
841}
842
843static int
844iwi_suspend(device_t dev)
845{
846	struct iwi_softc *sc = device_get_softc(dev);
847	struct ieee80211com *ic = &sc->sc_ic;
848
849	ieee80211_suspend_all(ic);
850	return 0;
851}
852
853static int
854iwi_resume(device_t dev)
855{
856	struct iwi_softc *sc = device_get_softc(dev);
857	struct ieee80211com *ic = &sc->sc_ic;
858
859	pci_write_config(dev, 0x41, 0, 1);
860
861	ieee80211_resume_all(ic);
862	return 0;
863}
864
865static struct ieee80211_node *
866iwi_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
867{
868	struct iwi_node *in;
869
870	in = malloc(sizeof (struct iwi_node), M_80211_NODE, M_NOWAIT | M_ZERO);
871	if (in == NULL)
872		return NULL;
873	/* XXX assign sta table entry for adhoc */
874	in->in_station = -1;
875
876	return &in->in_node;
877}
878
879static void
880iwi_node_free(struct ieee80211_node *ni)
881{
882	struct ieee80211com *ic = ni->ni_ic;
883	struct iwi_softc *sc = ic->ic_softc;
884	struct iwi_node *in = (struct iwi_node *)ni;
885
886	if (in->in_station != -1) {
887		DPRINTF(("%s mac %6D station %u\n", __func__,
888		    ni->ni_macaddr, ":", in->in_station));
889		free_unr(sc->sc_unr, in->in_station);
890	}
891
892	sc->sc_node_free(ni);
893}
894
895/*
896 * Convert h/w rate code to IEEE rate code.
897 */
898static int
899iwi_cvtrate(int iwirate)
900{
901	switch (iwirate) {
902	case IWI_RATE_DS1:	return 2;
903	case IWI_RATE_DS2:	return 4;
904	case IWI_RATE_DS5:	return 11;
905	case IWI_RATE_DS11:	return 22;
906	case IWI_RATE_OFDM6:	return 12;
907	case IWI_RATE_OFDM9:	return 18;
908	case IWI_RATE_OFDM12:	return 24;
909	case IWI_RATE_OFDM18:	return 36;
910	case IWI_RATE_OFDM24:	return 48;
911	case IWI_RATE_OFDM36:	return 72;
912	case IWI_RATE_OFDM48:	return 96;
913	case IWI_RATE_OFDM54:	return 108;
914	}
915	return 0;
916}
917
918/*
919 * The firmware automatically adapts the transmit speed.  We report its current
920 * value here.
921 */
922static void
923iwi_media_status(struct ifnet *ifp, struct ifmediareq *imr)
924{
925	struct ieee80211vap *vap = ifp->if_softc;
926	struct ieee80211com *ic = vap->iv_ic;
927	struct iwi_softc *sc = ic->ic_softc;
928	struct ieee80211_node *ni;
929
930	/* read current transmission rate from adapter */
931	ni = ieee80211_ref_node(vap->iv_bss);
932	ni->ni_txrate =
933	    iwi_cvtrate(CSR_READ_4(sc, IWI_CSR_CURRENT_TX_RATE));
934	ieee80211_free_node(ni);
935	ieee80211_media_status(ifp, imr);
936}
937
938static int
939iwi_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
940{
941	struct iwi_vap *ivp = IWI_VAP(vap);
942	struct ieee80211com *ic = vap->iv_ic;
943	struct iwi_softc *sc = ic->ic_softc;
944	IWI_LOCK_DECL;
945
946	DPRINTF(("%s: %s -> %s flags 0x%x\n", __func__,
947		ieee80211_state_name[vap->iv_state],
948		ieee80211_state_name[nstate], sc->flags));
949
950	IEEE80211_UNLOCK(ic);
951	IWI_LOCK(sc);
952	switch (nstate) {
953	case IEEE80211_S_INIT:
954		/*
955		 * NB: don't try to do this if iwi_stop_master has
956		 *     shutdown the firmware and disabled interrupts.
957		 */
958		if (vap->iv_state == IEEE80211_S_RUN &&
959		    (sc->flags & IWI_FLAG_FW_INITED))
960			iwi_disassociate(sc, 0);
961		break;
962	case IEEE80211_S_AUTH:
963		iwi_auth_and_assoc(sc, vap);
964		break;
965	case IEEE80211_S_RUN:
966		if (vap->iv_opmode == IEEE80211_M_IBSS &&
967		    vap->iv_state == IEEE80211_S_SCAN) {
968			/*
969			 * XXX when joining an ibss network we are called
970			 * with a SCAN -> RUN transition on scan complete.
971			 * Use that to call iwi_auth_and_assoc.  On completing
972			 * the join we are then called again with an
973			 * AUTH -> RUN transition and we want to do nothing.
974			 * This is all totally bogus and needs to be redone.
975			 */
976			iwi_auth_and_assoc(sc, vap);
977		} else if (vap->iv_opmode == IEEE80211_M_MONITOR)
978			ieee80211_runtask(ic, &sc->sc_monitortask);
979		break;
980	case IEEE80211_S_ASSOC:
981		/*
982		 * If we are transitioning from AUTH then just wait
983		 * for the ASSOC status to come back from the firmware.
984		 * Otherwise we need to issue the association request.
985		 */
986		if (vap->iv_state == IEEE80211_S_AUTH)
987			break;
988		iwi_auth_and_assoc(sc, vap);
989		break;
990	default:
991		break;
992	}
993	IWI_UNLOCK(sc);
994	IEEE80211_LOCK(ic);
995	return ivp->iwi_newstate(vap, nstate, arg);
996}
997
998/*
999 * WME parameters coming from IEEE 802.11e specification.  These values are
1000 * already declared in ieee80211_proto.c, but they are static so they can't
1001 * be reused here.
1002 */
1003static const struct wmeParams iwi_wme_cck_params[WME_NUM_AC] = {
1004	{ 0, 3, 5,  7,   0 },	/* WME_AC_BE */
1005	{ 0, 3, 5, 10,   0 },	/* WME_AC_BK */
1006	{ 0, 2, 4,  5, 188 },	/* WME_AC_VI */
1007	{ 0, 2, 3,  4, 102 }	/* WME_AC_VO */
1008};
1009
1010static const struct wmeParams iwi_wme_ofdm_params[WME_NUM_AC] = {
1011	{ 0, 3, 4,  6,   0 },	/* WME_AC_BE */
1012	{ 0, 3, 4, 10,   0 },	/* WME_AC_BK */
1013	{ 0, 2, 3,  4,  94 },	/* WME_AC_VI */
1014	{ 0, 2, 2,  3,  47 }	/* WME_AC_VO */
1015};
1016#define IWI_EXP2(v)	htole16((1 << (v)) - 1)
1017#define IWI_USEC(v)	htole16(IEEE80211_TXOP_TO_US(v))
1018
1019static void
1020iwi_wme_init(struct iwi_softc *sc)
1021{
1022	const struct wmeParams *wmep;
1023	int ac;
1024
1025	memset(sc->wme, 0, sizeof sc->wme);
1026	for (ac = 0; ac < WME_NUM_AC; ac++) {
1027		/* set WME values for CCK modulation */
1028		wmep = &iwi_wme_cck_params[ac];
1029		sc->wme[1].aifsn[ac] = wmep->wmep_aifsn;
1030		sc->wme[1].cwmin[ac] = IWI_EXP2(wmep->wmep_logcwmin);
1031		sc->wme[1].cwmax[ac] = IWI_EXP2(wmep->wmep_logcwmax);
1032		sc->wme[1].burst[ac] = IWI_USEC(wmep->wmep_txopLimit);
1033		sc->wme[1].acm[ac]   = wmep->wmep_acm;
1034
1035		/* set WME values for OFDM modulation */
1036		wmep = &iwi_wme_ofdm_params[ac];
1037		sc->wme[2].aifsn[ac] = wmep->wmep_aifsn;
1038		sc->wme[2].cwmin[ac] = IWI_EXP2(wmep->wmep_logcwmin);
1039		sc->wme[2].cwmax[ac] = IWI_EXP2(wmep->wmep_logcwmax);
1040		sc->wme[2].burst[ac] = IWI_USEC(wmep->wmep_txopLimit);
1041		sc->wme[2].acm[ac]   = wmep->wmep_acm;
1042	}
1043}
1044
1045static int
1046iwi_wme_setparams(struct iwi_softc *sc)
1047{
1048	struct ieee80211com *ic = &sc->sc_ic;
1049	const struct wmeParams *wmep;
1050	int ac;
1051
1052	for (ac = 0; ac < WME_NUM_AC; ac++) {
1053		/* set WME values for current operating mode */
1054		wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
1055		sc->wme[0].aifsn[ac] = wmep->wmep_aifsn;
1056		sc->wme[0].cwmin[ac] = IWI_EXP2(wmep->wmep_logcwmin);
1057		sc->wme[0].cwmax[ac] = IWI_EXP2(wmep->wmep_logcwmax);
1058		sc->wme[0].burst[ac] = IWI_USEC(wmep->wmep_txopLimit);
1059		sc->wme[0].acm[ac]   = wmep->wmep_acm;
1060	}
1061
1062	DPRINTF(("Setting WME parameters\n"));
1063	return iwi_cmd(sc, IWI_CMD_SET_WME_PARAMS, sc->wme, sizeof sc->wme);
1064}
1065#undef IWI_USEC
1066#undef IWI_EXP2
1067
1068static int
1069iwi_wme_update(struct ieee80211com *ic)
1070{
1071	struct iwi_softc *sc = ic->ic_softc;
1072	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1073	IWI_LOCK_DECL;
1074
1075	/*
1076	 * We may be called to update the WME parameters in
1077	 * the adapter at various places.  If we're already
1078	 * associated then initiate the request immediately;
1079	 * otherwise we assume the params will get sent down
1080	 * to the adapter as part of the work iwi_auth_and_assoc
1081	 * does.
1082	 */
1083	if (vap->iv_state == IEEE80211_S_RUN) {
1084		IWI_LOCK(sc);
1085		iwi_wme_setparams(sc);
1086		IWI_UNLOCK(sc);
1087	}
1088	return (0);
1089}
1090
1091static int
1092iwi_wme_setie(struct iwi_softc *sc)
1093{
1094	struct ieee80211_wme_info wme;
1095
1096	memset(&wme, 0, sizeof wme);
1097	wme.wme_id = IEEE80211_ELEMID_VENDOR;
1098	wme.wme_len = sizeof (struct ieee80211_wme_info) - 2;
1099	wme.wme_oui[0] = 0x00;
1100	wme.wme_oui[1] = 0x50;
1101	wme.wme_oui[2] = 0xf2;
1102	wme.wme_type = WME_OUI_TYPE;
1103	wme.wme_subtype = WME_INFO_OUI_SUBTYPE;
1104	wme.wme_version = WME_VERSION;
1105	wme.wme_info = 0;
1106
1107	DPRINTF(("Setting WME IE (len=%u)\n", wme.wme_len));
1108	return iwi_cmd(sc, IWI_CMD_SET_WMEIE, &wme, sizeof wme);
1109}
1110
1111/*
1112 * Read 16 bits at address 'addr' from the serial EEPROM.
1113 */
1114static uint16_t
1115iwi_read_prom_word(struct iwi_softc *sc, uint8_t addr)
1116{
1117	uint32_t tmp;
1118	uint16_t val;
1119	int n;
1120
1121	/* clock C once before the first command */
1122	IWI_EEPROM_CTL(sc, 0);
1123	IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1124	IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_C);
1125	IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1126
1127	/* write start bit (1) */
1128	IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_D);
1129	IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_D | IWI_EEPROM_C);
1130
1131	/* write READ opcode (10) */
1132	IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_D);
1133	IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_D | IWI_EEPROM_C);
1134	IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1135	IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_C);
1136
1137	/* write address A7-A0 */
1138	for (n = 7; n >= 0; n--) {
1139		IWI_EEPROM_CTL(sc, IWI_EEPROM_S |
1140		    (((addr >> n) & 1) << IWI_EEPROM_SHIFT_D));
1141		IWI_EEPROM_CTL(sc, IWI_EEPROM_S |
1142		    (((addr >> n) & 1) << IWI_EEPROM_SHIFT_D) | IWI_EEPROM_C);
1143	}
1144
1145	IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1146
1147	/* read data Q15-Q0 */
1148	val = 0;
1149	for (n = 15; n >= 0; n--) {
1150		IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_C);
1151		IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1152		tmp = MEM_READ_4(sc, IWI_MEM_EEPROM_CTL);
1153		val |= ((tmp & IWI_EEPROM_Q) >> IWI_EEPROM_SHIFT_Q) << n;
1154	}
1155
1156	IWI_EEPROM_CTL(sc, 0);
1157
1158	/* clear Chip Select and clock C */
1159	IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1160	IWI_EEPROM_CTL(sc, 0);
1161	IWI_EEPROM_CTL(sc, IWI_EEPROM_C);
1162
1163	return val;
1164}
1165
1166static void
1167iwi_setcurchan(struct iwi_softc *sc, int chan)
1168{
1169	struct ieee80211com *ic = &sc->sc_ic;
1170
1171	sc->curchan = chan;
1172	ieee80211_radiotap_chan_change(ic);
1173}
1174
1175static void
1176iwi_frame_intr(struct iwi_softc *sc, struct iwi_rx_data *data, int i,
1177    struct iwi_frame *frame)
1178{
1179	struct ieee80211com *ic = &sc->sc_ic;
1180	struct mbuf *mnew, *m;
1181	struct ieee80211_node *ni;
1182	int type, error, framelen;
1183	int8_t rssi, nf;
1184	IWI_LOCK_DECL;
1185
1186	framelen = le16toh(frame->len);
1187	if (framelen < IEEE80211_MIN_LEN || framelen > MCLBYTES) {
1188		/*
1189		 * XXX >MCLBYTES is bogus as it means the h/w dma'd
1190		 *     out of bounds; need to figure out how to limit
1191		 *     frame size in the firmware
1192		 */
1193		/* XXX stat */
1194		DPRINTFN(1,
1195		    ("drop rx frame len=%u chan=%u rssi=%u rssi_dbm=%u\n",
1196		    le16toh(frame->len), frame->chan, frame->rssi,
1197		    frame->rssi_dbm));
1198		return;
1199	}
1200
1201	DPRINTFN(5, ("received frame len=%u chan=%u rssi=%u rssi_dbm=%u\n",
1202	    le16toh(frame->len), frame->chan, frame->rssi, frame->rssi_dbm));
1203
1204	if (frame->chan != sc->curchan)
1205		iwi_setcurchan(sc, frame->chan);
1206
1207	/*
1208	 * Try to allocate a new mbuf for this ring element and load it before
1209	 * processing the current mbuf. If the ring element cannot be loaded,
1210	 * drop the received packet and reuse the old mbuf. In the unlikely
1211	 * case that the old mbuf can't be reloaded either, explicitly panic.
1212	 */
1213	mnew = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
1214	if (mnew == NULL) {
1215		counter_u64_add(ic->ic_ierrors, 1);
1216		return;
1217	}
1218
1219	bus_dmamap_unload(sc->rxq.data_dmat, data->map);
1220
1221	error = bus_dmamap_load(sc->rxq.data_dmat, data->map,
1222	    mtod(mnew, void *), MCLBYTES, iwi_dma_map_addr, &data->physaddr,
1223	    0);
1224	if (error != 0) {
1225		m_freem(mnew);
1226
1227		/* try to reload the old mbuf */
1228		error = bus_dmamap_load(sc->rxq.data_dmat, data->map,
1229		    mtod(data->m, void *), MCLBYTES, iwi_dma_map_addr,
1230		    &data->physaddr, 0);
1231		if (error != 0) {
1232			/* very unlikely that it will fail... */
1233			panic("%s: could not load old rx mbuf",
1234			    device_get_name(sc->sc_dev));
1235		}
1236		counter_u64_add(ic->ic_ierrors, 1);
1237		return;
1238	}
1239
1240	/*
1241	 * New mbuf successfully loaded, update Rx ring and continue
1242	 * processing.
1243	 */
1244	m = data->m;
1245	data->m = mnew;
1246	CSR_WRITE_4(sc, data->reg, data->physaddr);
1247
1248	/* finalize mbuf */
1249	m->m_pkthdr.len = m->m_len = sizeof (struct iwi_hdr) +
1250	    sizeof (struct iwi_frame) + framelen;
1251
1252	m_adj(m, sizeof (struct iwi_hdr) + sizeof (struct iwi_frame));
1253
1254	rssi = frame->rssi_dbm;
1255	nf = -95;
1256	if (ieee80211_radiotap_active(ic)) {
1257		struct iwi_rx_radiotap_header *tap = &sc->sc_rxtap;
1258
1259		tap->wr_flags = 0;
1260		tap->wr_antsignal = rssi;
1261		tap->wr_antnoise = nf;
1262		tap->wr_rate = iwi_cvtrate(frame->rate);
1263		tap->wr_antenna = frame->antenna;
1264	}
1265	IWI_UNLOCK(sc);
1266
1267	ni = ieee80211_find_rxnode(ic, mtod(m, struct ieee80211_frame_min *));
1268	if (ni != NULL) {
1269		type = ieee80211_input(ni, m, rssi, nf);
1270		ieee80211_free_node(ni);
1271	} else
1272		type = ieee80211_input_all(ic, m, rssi, nf);
1273
1274	IWI_LOCK(sc);
1275	if (sc->sc_softled) {
1276		/*
1277		 * Blink for any data frame.  Otherwise do a
1278		 * heartbeat-style blink when idle.  The latter
1279		 * is mainly for station mode where we depend on
1280		 * periodic beacon frames to trigger the poll event.
1281		 */
1282		if (type == IEEE80211_FC0_TYPE_DATA) {
1283			sc->sc_rxrate = frame->rate;
1284			iwi_led_event(sc, IWI_LED_RX);
1285		} else if (ticks - sc->sc_ledevent >= sc->sc_ledidle)
1286			iwi_led_event(sc, IWI_LED_POLL);
1287	}
1288}
1289
1290/*
1291 * Check for an association response frame to see if QoS
1292 * has been negotiated.  We parse just enough to figure
1293 * out if we're supposed to use QoS.  The proper solution
1294 * is to pass the frame up so ieee80211_input can do the
1295 * work but that's made hard by how things currently are
1296 * done in the driver.
1297 */
1298static void
1299iwi_checkforqos(struct ieee80211vap *vap,
1300	const struct ieee80211_frame *wh, int len)
1301{
1302#define	SUBTYPE(wh)	((wh)->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK)
1303	const uint8_t *frm, *efrm, *wme;
1304	struct ieee80211_node *ni;
1305	uint16_t capinfo, status, associd;
1306
1307	/* NB: +8 for capinfo, status, associd, and first ie */
1308	if (!(sizeof(*wh)+8 < len && len < IEEE80211_MAX_LEN) ||
1309	    SUBTYPE(wh) != IEEE80211_FC0_SUBTYPE_ASSOC_RESP)
1310		return;
1311	/*
1312	 * asresp frame format
1313	 *	[2] capability information
1314	 *	[2] status
1315	 *	[2] association ID
1316	 *	[tlv] supported rates
1317	 *	[tlv] extended supported rates
1318	 *	[tlv] WME
1319	 */
1320	frm = (const uint8_t *)&wh[1];
1321	efrm = ((const uint8_t *) wh) + len;
1322
1323	capinfo = le16toh(*(const uint16_t *)frm);
1324	frm += 2;
1325	status = le16toh(*(const uint16_t *)frm);
1326	frm += 2;
1327	associd = le16toh(*(const uint16_t *)frm);
1328	frm += 2;
1329
1330	wme = NULL;
1331	while (efrm - frm > 1) {
1332		IEEE80211_VERIFY_LENGTH(efrm - frm, frm[1] + 2, return);
1333		switch (*frm) {
1334		case IEEE80211_ELEMID_VENDOR:
1335			if (iswmeoui(frm))
1336				wme = frm;
1337			break;
1338		}
1339		frm += frm[1] + 2;
1340	}
1341
1342	ni = ieee80211_ref_node(vap->iv_bss);
1343	ni->ni_capinfo = capinfo;
1344	ni->ni_associd = associd & 0x3fff;
1345	if (wme != NULL)
1346		ni->ni_flags |= IEEE80211_NODE_QOS;
1347	else
1348		ni->ni_flags &= ~IEEE80211_NODE_QOS;
1349	ieee80211_free_node(ni);
1350#undef SUBTYPE
1351}
1352
1353static void
1354iwi_notif_link_quality(struct iwi_softc *sc, struct iwi_notif *notif)
1355{
1356	struct iwi_notif_link_quality *lq;
1357	int len;
1358
1359	len = le16toh(notif->len);
1360
1361	DPRINTFN(5, ("Notification (%u) - len=%d, sizeof=%zu\n",
1362	    notif->type,
1363	    len,
1364	    sizeof(struct iwi_notif_link_quality)
1365	    ));
1366
1367	/* enforce length */
1368	if (len != sizeof(struct iwi_notif_link_quality)) {
1369		DPRINTFN(5, ("Notification: (%u) too short (%d)\n",
1370		    notif->type,
1371		    len));
1372		return;
1373	}
1374
1375	lq = (struct iwi_notif_link_quality *)(notif + 1);
1376	memcpy(&sc->sc_linkqual, lq, sizeof(sc->sc_linkqual));
1377	sc->sc_linkqual_valid = 1;
1378}
1379
1380/*
1381 * Task queue callbacks for iwi_notification_intr used to avoid LOR's.
1382 */
1383
1384static void
1385iwi_notification_intr(struct iwi_softc *sc, struct iwi_notif *notif)
1386{
1387	struct ieee80211com *ic = &sc->sc_ic;
1388	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1389	struct iwi_notif_scan_channel *chan;
1390	struct iwi_notif_scan_complete *scan;
1391	struct iwi_notif_authentication *auth;
1392	struct iwi_notif_association *assoc;
1393	struct iwi_notif_beacon_state *beacon;
1394
1395	switch (notif->type) {
1396	case IWI_NOTIF_TYPE_SCAN_CHANNEL:
1397		chan = (struct iwi_notif_scan_channel *)(notif + 1);
1398
1399		DPRINTFN(3, ("Scan of channel %u complete (%u)\n",
1400		    ieee80211_ieee2mhz(chan->nchan, 0), chan->nchan));
1401
1402		/* Reset the timer, the scan is still going */
1403		sc->sc_state_timer = 3;
1404		break;
1405
1406	case IWI_NOTIF_TYPE_SCAN_COMPLETE:
1407		scan = (struct iwi_notif_scan_complete *)(notif + 1);
1408
1409		DPRINTFN(2, ("Scan completed (%u, %u)\n", scan->nchan,
1410		    scan->status));
1411
1412		IWI_STATE_END(sc, IWI_FW_SCANNING);
1413
1414		/*
1415		 * Monitor mode works by doing a passive scan to set
1416		 * the channel and enable rx.  Because we don't want
1417		 * to abort a scan lest the firmware crash we scan
1418		 * for a short period of time and automatically restart
1419		 * the scan when notified the sweep has completed.
1420		 */
1421		if (vap->iv_opmode == IEEE80211_M_MONITOR) {
1422			ieee80211_runtask(ic, &sc->sc_monitortask);
1423			break;
1424		}
1425
1426		if (scan->status == IWI_SCAN_COMPLETED) {
1427			/* NB: don't need to defer, net80211 does it for us */
1428			ieee80211_scan_next(vap);
1429		}
1430		break;
1431
1432	case IWI_NOTIF_TYPE_AUTHENTICATION:
1433		auth = (struct iwi_notif_authentication *)(notif + 1);
1434		switch (auth->state) {
1435		case IWI_AUTH_SUCCESS:
1436			DPRINTFN(2, ("Authentication succeeeded\n"));
1437			ieee80211_new_state(vap, IEEE80211_S_ASSOC, -1);
1438			break;
1439		case IWI_AUTH_FAIL:
1440			/*
1441			 * These are delivered as an unsolicited deauth
1442			 * (e.g. due to inactivity) or in response to an
1443			 * associate request.
1444			 */
1445			sc->flags &= ~IWI_FLAG_ASSOCIATED;
1446			if (vap->iv_state != IEEE80211_S_RUN) {
1447				DPRINTFN(2, ("Authentication failed\n"));
1448				vap->iv_stats.is_rx_auth_fail++;
1449				IWI_STATE_END(sc, IWI_FW_ASSOCIATING);
1450			} else {
1451				DPRINTFN(2, ("Deauthenticated\n"));
1452				vap->iv_stats.is_rx_deauth++;
1453			}
1454			ieee80211_new_state(vap, IEEE80211_S_SCAN, -1);
1455			break;
1456		case IWI_AUTH_SENT_1:
1457		case IWI_AUTH_RECV_2:
1458		case IWI_AUTH_SEQ1_PASS:
1459			break;
1460		case IWI_AUTH_SEQ1_FAIL:
1461			DPRINTFN(2, ("Initial authentication handshake failed; "
1462				"you probably need shared key\n"));
1463			vap->iv_stats.is_rx_auth_fail++;
1464			IWI_STATE_END(sc, IWI_FW_ASSOCIATING);
1465			/* XXX retry shared key when in auto */
1466			break;
1467		default:
1468			device_printf(sc->sc_dev,
1469			    "unknown authentication state %u\n", auth->state);
1470			break;
1471		}
1472		break;
1473
1474	case IWI_NOTIF_TYPE_ASSOCIATION:
1475		assoc = (struct iwi_notif_association *)(notif + 1);
1476		switch (assoc->state) {
1477		case IWI_AUTH_SUCCESS:
1478			/* re-association, do nothing */
1479			break;
1480		case IWI_ASSOC_SUCCESS:
1481			DPRINTFN(2, ("Association succeeded\n"));
1482			sc->flags |= IWI_FLAG_ASSOCIATED;
1483			IWI_STATE_END(sc, IWI_FW_ASSOCIATING);
1484			iwi_checkforqos(vap,
1485			    (const struct ieee80211_frame *)(assoc+1),
1486			    le16toh(notif->len) - sizeof(*assoc) - 1);
1487			ieee80211_new_state(vap, IEEE80211_S_RUN, -1);
1488			break;
1489		case IWI_ASSOC_INIT:
1490			sc->flags &= ~IWI_FLAG_ASSOCIATED;
1491			switch (sc->fw_state) {
1492			case IWI_FW_ASSOCIATING:
1493				DPRINTFN(2, ("Association failed\n"));
1494				IWI_STATE_END(sc, IWI_FW_ASSOCIATING);
1495				ieee80211_new_state(vap, IEEE80211_S_SCAN, -1);
1496				break;
1497
1498			case IWI_FW_DISASSOCIATING:
1499				DPRINTFN(2, ("Dissassociated\n"));
1500				IWI_STATE_END(sc, IWI_FW_DISASSOCIATING);
1501				vap->iv_stats.is_rx_disassoc++;
1502				ieee80211_new_state(vap, IEEE80211_S_SCAN, -1);
1503				break;
1504			}
1505			break;
1506		default:
1507			device_printf(sc->sc_dev,
1508			    "unknown association state %u\n", assoc->state);
1509			break;
1510		}
1511		break;
1512
1513	case IWI_NOTIF_TYPE_BEACON:
1514		/* XXX check struct length */
1515		beacon = (struct iwi_notif_beacon_state *)(notif + 1);
1516
1517		DPRINTFN(5, ("Beacon state (%u, %u)\n",
1518		    beacon->state, le32toh(beacon->number)));
1519
1520		if (beacon->state == IWI_BEACON_MISS) {
1521			/*
1522			 * The firmware notifies us of every beacon miss
1523			 * so we need to track the count against the
1524			 * configured threshold before notifying the
1525			 * 802.11 layer.
1526			 * XXX try to roam, drop assoc only on much higher count
1527			 */
1528			if (le32toh(beacon->number) >= vap->iv_bmissthreshold) {
1529				DPRINTF(("Beacon miss: %u >= %u\n",
1530				    le32toh(beacon->number),
1531				    vap->iv_bmissthreshold));
1532				vap->iv_stats.is_beacon_miss++;
1533				/*
1534				 * It's pointless to notify the 802.11 layer
1535				 * as it'll try to send a probe request (which
1536				 * we'll discard) and then timeout and drop us
1537				 * into scan state.  Instead tell the firmware
1538				 * to disassociate and then on completion we'll
1539				 * kick the state machine to scan.
1540				 */
1541				ieee80211_runtask(ic, &sc->sc_disassoctask);
1542			}
1543		}
1544		break;
1545
1546	case IWI_NOTIF_TYPE_CALIBRATION:
1547	case IWI_NOTIF_TYPE_NOISE:
1548		/* XXX handle? */
1549		DPRINTFN(5, ("Notification (%u)\n", notif->type));
1550		break;
1551	case IWI_NOTIF_TYPE_LINK_QUALITY:
1552		iwi_notif_link_quality(sc, notif);
1553		break;
1554
1555	default:
1556		DPRINTF(("unknown notification type %u flags 0x%x len %u\n",
1557		    notif->type, notif->flags, le16toh(notif->len)));
1558		break;
1559	}
1560}
1561
1562static void
1563iwi_rx_intr(struct iwi_softc *sc)
1564{
1565	struct iwi_rx_data *data;
1566	struct iwi_hdr *hdr;
1567	uint32_t hw;
1568
1569	hw = CSR_READ_4(sc, IWI_CSR_RX_RIDX);
1570
1571	for (; sc->rxq.cur != hw;) {
1572		data = &sc->rxq.data[sc->rxq.cur];
1573
1574		bus_dmamap_sync(sc->rxq.data_dmat, data->map,
1575		    BUS_DMASYNC_POSTREAD);
1576
1577		hdr = mtod(data->m, struct iwi_hdr *);
1578
1579		switch (hdr->type) {
1580		case IWI_HDR_TYPE_FRAME:
1581			iwi_frame_intr(sc, data, sc->rxq.cur,
1582			    (struct iwi_frame *)(hdr + 1));
1583			break;
1584
1585		case IWI_HDR_TYPE_NOTIF:
1586			iwi_notification_intr(sc,
1587			    (struct iwi_notif *)(hdr + 1));
1588			break;
1589
1590		default:
1591			device_printf(sc->sc_dev, "unknown hdr type %u\n",
1592			    hdr->type);
1593		}
1594
1595		DPRINTFN(15, ("rx done idx=%u\n", sc->rxq.cur));
1596
1597		sc->rxq.cur = (sc->rxq.cur + 1) % IWI_RX_RING_COUNT;
1598	}
1599
1600	/* tell the firmware what we have processed */
1601	hw = (hw == 0) ? IWI_RX_RING_COUNT - 1 : hw - 1;
1602	CSR_WRITE_4(sc, IWI_CSR_RX_WIDX, hw);
1603}
1604
1605static void
1606iwi_tx_intr(struct iwi_softc *sc, struct iwi_tx_ring *txq)
1607{
1608	struct iwi_tx_data *data;
1609	uint32_t hw;
1610
1611	hw = CSR_READ_4(sc, txq->csr_ridx);
1612
1613	while (txq->next != hw) {
1614		data = &txq->data[txq->next];
1615		DPRINTFN(15, ("tx done idx=%u\n", txq->next));
1616		bus_dmamap_sync(txq->data_dmat, data->map,
1617		    BUS_DMASYNC_POSTWRITE);
1618		bus_dmamap_unload(txq->data_dmat, data->map);
1619		ieee80211_tx_complete(data->ni, data->m, 0);
1620		data->ni = NULL;
1621		data->m = NULL;
1622		txq->queued--;
1623		txq->next = (txq->next + 1) % IWI_TX_RING_COUNT;
1624	}
1625	sc->sc_tx_timer = 0;
1626	if (sc->sc_softled)
1627		iwi_led_event(sc, IWI_LED_TX);
1628	iwi_start(sc);
1629}
1630
1631static void
1632iwi_fatal_error_intr(struct iwi_softc *sc)
1633{
1634	struct ieee80211com *ic = &sc->sc_ic;
1635	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1636
1637	device_printf(sc->sc_dev, "firmware error\n");
1638	if (vap != NULL)
1639		ieee80211_cancel_scan(vap);
1640	ieee80211_runtask(ic, &sc->sc_restarttask);
1641
1642	sc->flags &= ~IWI_FLAG_BUSY;
1643	sc->sc_busy_timer = 0;
1644	wakeup(sc);
1645}
1646
1647static void
1648iwi_radio_off_intr(struct iwi_softc *sc)
1649{
1650
1651	ieee80211_runtask(&sc->sc_ic, &sc->sc_radiofftask);
1652}
1653
1654static void
1655iwi_intr(void *arg)
1656{
1657	struct iwi_softc *sc = arg;
1658	uint32_t r;
1659	IWI_LOCK_DECL;
1660
1661	IWI_LOCK(sc);
1662
1663	if ((r = CSR_READ_4(sc, IWI_CSR_INTR)) == 0 || r == 0xffffffff) {
1664		IWI_UNLOCK(sc);
1665		return;
1666	}
1667
1668	/* acknowledge interrupts */
1669	CSR_WRITE_4(sc, IWI_CSR_INTR, r);
1670
1671	if (r & IWI_INTR_FATAL_ERROR) {
1672		iwi_fatal_error_intr(sc);
1673		goto done;
1674	}
1675
1676	if (r & IWI_INTR_FW_INITED) {
1677		if (!(r & (IWI_INTR_FATAL_ERROR | IWI_INTR_PARITY_ERROR)))
1678			wakeup(sc);
1679	}
1680
1681	if (r & IWI_INTR_RADIO_OFF)
1682		iwi_radio_off_intr(sc);
1683
1684	if (r & IWI_INTR_CMD_DONE) {
1685		sc->flags &= ~IWI_FLAG_BUSY;
1686		sc->sc_busy_timer = 0;
1687		wakeup(sc);
1688	}
1689
1690	if (r & IWI_INTR_TX1_DONE)
1691		iwi_tx_intr(sc, &sc->txq[0]);
1692
1693	if (r & IWI_INTR_TX2_DONE)
1694		iwi_tx_intr(sc, &sc->txq[1]);
1695
1696	if (r & IWI_INTR_TX3_DONE)
1697		iwi_tx_intr(sc, &sc->txq[2]);
1698
1699	if (r & IWI_INTR_TX4_DONE)
1700		iwi_tx_intr(sc, &sc->txq[3]);
1701
1702	if (r & IWI_INTR_RX_DONE)
1703		iwi_rx_intr(sc);
1704
1705	if (r & IWI_INTR_PARITY_ERROR) {
1706		/* XXX rate-limit */
1707		device_printf(sc->sc_dev, "parity error\n");
1708	}
1709done:
1710	IWI_UNLOCK(sc);
1711}
1712
1713static int
1714iwi_cmd(struct iwi_softc *sc, uint8_t type, void *data, uint8_t len)
1715{
1716	struct iwi_cmd_desc *desc;
1717
1718	IWI_LOCK_ASSERT(sc);
1719
1720	if (sc->flags & IWI_FLAG_BUSY) {
1721		device_printf(sc->sc_dev, "%s: cmd %d not sent, busy\n",
1722			__func__, type);
1723		return EAGAIN;
1724	}
1725	sc->flags |= IWI_FLAG_BUSY;
1726	sc->sc_busy_timer = 2;
1727
1728	desc = &sc->cmdq.desc[sc->cmdq.cur];
1729
1730	desc->hdr.type = IWI_HDR_TYPE_COMMAND;
1731	desc->hdr.flags = IWI_HDR_FLAG_IRQ;
1732	desc->type = type;
1733	desc->len = len;
1734	memcpy(desc->data, data, len);
1735
1736	bus_dmamap_sync(sc->cmdq.desc_dmat, sc->cmdq.desc_map,
1737	    BUS_DMASYNC_PREWRITE);
1738
1739	DPRINTFN(2, ("sending command idx=%u type=%u len=%u\n", sc->cmdq.cur,
1740	    type, len));
1741
1742	sc->cmdq.cur = (sc->cmdq.cur + 1) % IWI_CMD_RING_COUNT;
1743	CSR_WRITE_4(sc, IWI_CSR_CMD_WIDX, sc->cmdq.cur);
1744
1745	return msleep(sc, &sc->sc_mtx, 0, "iwicmd", hz);
1746}
1747
1748static void
1749iwi_write_ibssnode(struct iwi_softc *sc,
1750	const u_int8_t addr[IEEE80211_ADDR_LEN], int entry)
1751{
1752	struct iwi_ibssnode node;
1753
1754	/* write node information into NIC memory */
1755	memset(&node, 0, sizeof node);
1756	IEEE80211_ADDR_COPY(node.bssid, addr);
1757
1758	DPRINTF(("%s mac %6D station %u\n", __func__, node.bssid, ":", entry));
1759
1760	CSR_WRITE_REGION_1(sc,
1761	    IWI_CSR_NODE_BASE + entry * sizeof node,
1762	    (uint8_t *)&node, sizeof node);
1763}
1764
1765static int
1766iwi_tx_start(struct iwi_softc *sc, struct mbuf *m0, struct ieee80211_node *ni,
1767    int ac)
1768{
1769	struct ieee80211vap *vap = ni->ni_vap;
1770	struct ieee80211com *ic = ni->ni_ic;
1771	struct iwi_node *in = (struct iwi_node *)ni;
1772	const struct ieee80211_frame *wh;
1773	struct ieee80211_key *k;
1774	const struct chanAccParams *cap;
1775	struct iwi_tx_ring *txq = &sc->txq[ac];
1776	struct iwi_tx_data *data;
1777	struct iwi_tx_desc *desc;
1778	struct mbuf *mnew;
1779	bus_dma_segment_t segs[IWI_MAX_NSEG];
1780	int error, nsegs, hdrlen, i;
1781	int ismcast, flags, xflags, staid;
1782
1783	IWI_LOCK_ASSERT(sc);
1784	wh = mtod(m0, const struct ieee80211_frame *);
1785	/* NB: only data frames use this path */
1786	hdrlen = ieee80211_hdrsize(wh);
1787	ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
1788	flags = xflags = 0;
1789
1790	if (!ismcast)
1791		flags |= IWI_DATA_FLAG_NEED_ACK;
1792	if (vap->iv_flags & IEEE80211_F_SHPREAMBLE)
1793		flags |= IWI_DATA_FLAG_SHPREAMBLE;
1794	if (IEEE80211_QOS_HAS_SEQ(wh)) {
1795		xflags |= IWI_DATA_XFLAG_QOS;
1796		cap = &ic->ic_wme.wme_chanParams;
1797		if (!cap->cap_wmeParams[ac].wmep_noackPolicy)
1798			flags &= ~IWI_DATA_FLAG_NEED_ACK;
1799	}
1800
1801	/*
1802	 * This is only used in IBSS mode where the firmware expect an index
1803	 * in a h/w table instead of a destination address.
1804	 */
1805	if (vap->iv_opmode == IEEE80211_M_IBSS) {
1806		if (!ismcast) {
1807			if (in->in_station == -1) {
1808				in->in_station = alloc_unr(sc->sc_unr);
1809				if (in->in_station == -1) {
1810					/* h/w table is full */
1811					if_inc_counter(ni->ni_vap->iv_ifp,
1812					    IFCOUNTER_OERRORS, 1);
1813					m_freem(m0);
1814					ieee80211_free_node(ni);
1815					return 0;
1816				}
1817				iwi_write_ibssnode(sc,
1818					ni->ni_macaddr, in->in_station);
1819			}
1820			staid = in->in_station;
1821		} else {
1822			/*
1823			 * Multicast addresses have no associated node
1824			 * so there will be no station entry.  We reserve
1825			 * entry 0 for one mcast address and use that.
1826			 * If there are many being used this will be
1827			 * expensive and we'll need to do a better job
1828			 * but for now this handles the broadcast case.
1829			 */
1830			if (!IEEE80211_ADDR_EQ(wh->i_addr1, sc->sc_mcast)) {
1831				IEEE80211_ADDR_COPY(sc->sc_mcast, wh->i_addr1);
1832				iwi_write_ibssnode(sc, sc->sc_mcast, 0);
1833			}
1834			staid = 0;
1835		}
1836	} else
1837		staid = 0;
1838
1839	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
1840		k = ieee80211_crypto_encap(ni, m0);
1841		if (k == NULL) {
1842			m_freem(m0);
1843			return ENOBUFS;
1844		}
1845
1846		/* packet header may have moved, reset our local pointer */
1847		wh = mtod(m0, struct ieee80211_frame *);
1848	}
1849
1850	if (ieee80211_radiotap_active_vap(vap)) {
1851		struct iwi_tx_radiotap_header *tap = &sc->sc_txtap;
1852
1853		tap->wt_flags = 0;
1854
1855		ieee80211_radiotap_tx(vap, m0);
1856	}
1857
1858	data = &txq->data[txq->cur];
1859	desc = &txq->desc[txq->cur];
1860
1861	/* save and trim IEEE802.11 header */
1862	m_copydata(m0, 0, hdrlen, (caddr_t)&desc->wh);
1863	m_adj(m0, hdrlen);
1864
1865	error = bus_dmamap_load_mbuf_sg(txq->data_dmat, data->map, m0, segs,
1866	    &nsegs, 0);
1867	if (error != 0 && error != EFBIG) {
1868		device_printf(sc->sc_dev, "could not map mbuf (error %d)\n",
1869		    error);
1870		m_freem(m0);
1871		return error;
1872	}
1873	if (error != 0) {
1874		mnew = m_defrag(m0, M_NOWAIT);
1875		if (mnew == NULL) {
1876			device_printf(sc->sc_dev,
1877			    "could not defragment mbuf\n");
1878			m_freem(m0);
1879			return ENOBUFS;
1880		}
1881		m0 = mnew;
1882
1883		error = bus_dmamap_load_mbuf_sg(txq->data_dmat, data->map,
1884		    m0, segs, &nsegs, 0);
1885		if (error != 0) {
1886			device_printf(sc->sc_dev,
1887			    "could not map mbuf (error %d)\n", error);
1888			m_freem(m0);
1889			return error;
1890		}
1891	}
1892
1893	data->m = m0;
1894	data->ni = ni;
1895
1896	desc->hdr.type = IWI_HDR_TYPE_DATA;
1897	desc->hdr.flags = IWI_HDR_FLAG_IRQ;
1898	desc->station = staid;
1899	desc->cmd = IWI_DATA_CMD_TX;
1900	desc->len = htole16(m0->m_pkthdr.len);
1901	desc->flags = flags;
1902	desc->xflags = xflags;
1903
1904#if 0
1905	if (vap->iv_flags & IEEE80211_F_PRIVACY)
1906		desc->wep_txkey = vap->iv_def_txkey;
1907	else
1908#endif
1909		desc->flags |= IWI_DATA_FLAG_NO_WEP;
1910
1911	desc->nseg = htole32(nsegs);
1912	for (i = 0; i < nsegs; i++) {
1913		desc->seg_addr[i] = htole32(segs[i].ds_addr);
1914		desc->seg_len[i]  = htole16(segs[i].ds_len);
1915	}
1916
1917	bus_dmamap_sync(txq->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
1918	bus_dmamap_sync(txq->desc_dmat, txq->desc_map, BUS_DMASYNC_PREWRITE);
1919
1920	DPRINTFN(5, ("sending data frame txq=%u idx=%u len=%u nseg=%u\n",
1921	    ac, txq->cur, le16toh(desc->len), nsegs));
1922
1923	txq->queued++;
1924	txq->cur = (txq->cur + 1) % IWI_TX_RING_COUNT;
1925	CSR_WRITE_4(sc, txq->csr_widx, txq->cur);
1926
1927	return 0;
1928}
1929
1930static int
1931iwi_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
1932	const struct ieee80211_bpf_params *params)
1933{
1934	/* no support; just discard */
1935	m_freem(m);
1936	ieee80211_free_node(ni);
1937	return 0;
1938}
1939
1940static int
1941iwi_transmit(struct ieee80211com *ic, struct mbuf *m)
1942{
1943	struct iwi_softc *sc = ic->ic_softc;
1944	int error;
1945	IWI_LOCK_DECL;
1946
1947	IWI_LOCK(sc);
1948	if (!sc->sc_running) {
1949		IWI_UNLOCK(sc);
1950		return (ENXIO);
1951	}
1952	error = mbufq_enqueue(&sc->sc_snd, m);
1953	if (error) {
1954		IWI_UNLOCK(sc);
1955		return (error);
1956	}
1957	iwi_start(sc);
1958	IWI_UNLOCK(sc);
1959	return (0);
1960}
1961
1962static void
1963iwi_start(struct iwi_softc *sc)
1964{
1965	struct mbuf *m;
1966	struct ieee80211_node *ni;
1967	int ac;
1968
1969	IWI_LOCK_ASSERT(sc);
1970
1971	while ((m =  mbufq_dequeue(&sc->sc_snd)) != NULL) {
1972		ac = M_WME_GETAC(m);
1973		if (sc->txq[ac].queued > IWI_TX_RING_COUNT - 8) {
1974			/* there is no place left in this ring; tail drop */
1975			/* XXX tail drop */
1976			mbufq_prepend(&sc->sc_snd, m);
1977			break;
1978		}
1979		ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
1980		if (iwi_tx_start(sc, m, ni, ac) != 0) {
1981			if_inc_counter(ni->ni_vap->iv_ifp,
1982			    IFCOUNTER_OERRORS, 1);
1983			ieee80211_free_node(ni);
1984			break;
1985		}
1986		sc->sc_tx_timer = 5;
1987	}
1988}
1989
1990static void
1991iwi_watchdog(void *arg)
1992{
1993	struct iwi_softc *sc = arg;
1994	struct ieee80211com *ic = &sc->sc_ic;
1995
1996	IWI_LOCK_ASSERT(sc);
1997
1998	if (sc->sc_tx_timer > 0) {
1999		if (--sc->sc_tx_timer == 0) {
2000			device_printf(sc->sc_dev, "device timeout\n");
2001			counter_u64_add(ic->ic_oerrors, 1);
2002			ieee80211_runtask(ic, &sc->sc_restarttask);
2003		}
2004	}
2005	if (sc->sc_state_timer > 0) {
2006		if (--sc->sc_state_timer == 0) {
2007			device_printf(sc->sc_dev,
2008			    "firmware stuck in state %d, resetting\n",
2009			    sc->fw_state);
2010			if (sc->fw_state == IWI_FW_SCANNING)
2011				ieee80211_cancel_scan(TAILQ_FIRST(&ic->ic_vaps));
2012			ieee80211_runtask(ic, &sc->sc_restarttask);
2013			sc->sc_state_timer = 3;
2014		}
2015	}
2016	if (sc->sc_busy_timer > 0) {
2017		if (--sc->sc_busy_timer == 0) {
2018			device_printf(sc->sc_dev,
2019			    "firmware command timeout, resetting\n");
2020			ieee80211_runtask(ic, &sc->sc_restarttask);
2021		}
2022	}
2023	callout_reset(&sc->sc_wdtimer, hz, iwi_watchdog, sc);
2024}
2025
2026static void
2027iwi_parent(struct ieee80211com *ic)
2028{
2029	struct iwi_softc *sc = ic->ic_softc;
2030	int startall = 0;
2031	IWI_LOCK_DECL;
2032
2033	IWI_LOCK(sc);
2034	if (ic->ic_nrunning > 0) {
2035		if (!sc->sc_running) {
2036			iwi_init_locked(sc);
2037			startall = 1;
2038		}
2039	} else if (sc->sc_running)
2040		iwi_stop_locked(sc);
2041	IWI_UNLOCK(sc);
2042	if (startall)
2043		ieee80211_start_all(ic);
2044}
2045
2046static int
2047iwi_ioctl(struct ieee80211com *ic, u_long cmd, void *data)
2048{
2049	struct ifreq *ifr = data;
2050	struct iwi_softc *sc = ic->ic_softc;
2051	int error;
2052	IWI_LOCK_DECL;
2053
2054	IWI_LOCK(sc);
2055	switch (cmd) {
2056	case SIOCGIWISTATS:
2057		/* XXX validate permissions/memory/etc? */
2058		error = copyout(&sc->sc_linkqual, ifr_data_get_ptr(ifr),
2059		    sizeof(struct iwi_notif_link_quality));
2060		break;
2061	case SIOCZIWISTATS:
2062		memset(&sc->sc_linkqual, 0,
2063		    sizeof(struct iwi_notif_link_quality));
2064		error = 0;
2065		break;
2066	default:
2067		error = ENOTTY;
2068		break;
2069	}
2070	IWI_UNLOCK(sc);
2071
2072	return (error);
2073}
2074
2075static void
2076iwi_stop_master(struct iwi_softc *sc)
2077{
2078	uint32_t tmp;
2079	int ntries;
2080
2081	/* disable interrupts */
2082	CSR_WRITE_4(sc, IWI_CSR_INTR_MASK, 0);
2083
2084	CSR_WRITE_4(sc, IWI_CSR_RST, IWI_RST_STOP_MASTER);
2085	for (ntries = 0; ntries < 5; ntries++) {
2086		if (CSR_READ_4(sc, IWI_CSR_RST) & IWI_RST_MASTER_DISABLED)
2087			break;
2088		DELAY(10);
2089	}
2090	if (ntries == 5)
2091		device_printf(sc->sc_dev, "timeout waiting for master\n");
2092
2093	tmp = CSR_READ_4(sc, IWI_CSR_RST);
2094	CSR_WRITE_4(sc, IWI_CSR_RST, tmp | IWI_RST_PRINCETON_RESET);
2095
2096	sc->flags &= ~IWI_FLAG_FW_INITED;
2097}
2098
2099static int
2100iwi_reset(struct iwi_softc *sc)
2101{
2102	uint32_t tmp;
2103	int i, ntries;
2104
2105	iwi_stop_master(sc);
2106
2107	tmp = CSR_READ_4(sc, IWI_CSR_CTL);
2108	CSR_WRITE_4(sc, IWI_CSR_CTL, tmp | IWI_CTL_INIT);
2109
2110	CSR_WRITE_4(sc, IWI_CSR_READ_INT, IWI_READ_INT_INIT_HOST);
2111
2112	/* wait for clock stabilization */
2113	for (ntries = 0; ntries < 1000; ntries++) {
2114		if (CSR_READ_4(sc, IWI_CSR_CTL) & IWI_CTL_CLOCK_READY)
2115			break;
2116		DELAY(200);
2117	}
2118	if (ntries == 1000) {
2119		device_printf(sc->sc_dev,
2120		    "timeout waiting for clock stabilization\n");
2121		return EIO;
2122	}
2123
2124	tmp = CSR_READ_4(sc, IWI_CSR_RST);
2125	CSR_WRITE_4(sc, IWI_CSR_RST, tmp | IWI_RST_SOFT_RESET);
2126
2127	DELAY(10);
2128
2129	tmp = CSR_READ_4(sc, IWI_CSR_CTL);
2130	CSR_WRITE_4(sc, IWI_CSR_CTL, tmp | IWI_CTL_INIT);
2131
2132	/* clear NIC memory */
2133	CSR_WRITE_4(sc, IWI_CSR_AUTOINC_ADDR, 0);
2134	for (i = 0; i < 0xc000; i++)
2135		CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, 0);
2136
2137	return 0;
2138}
2139
2140static const struct iwi_firmware_ohdr *
2141iwi_setup_ofw(struct iwi_softc *sc, struct iwi_fw *fw)
2142{
2143	const struct firmware *fp = fw->fp;
2144	const struct iwi_firmware_ohdr *hdr;
2145
2146	if (fp->datasize < sizeof (struct iwi_firmware_ohdr)) {
2147		device_printf(sc->sc_dev, "image '%s' too small\n", fp->name);
2148		return NULL;
2149	}
2150	hdr = (const struct iwi_firmware_ohdr *)fp->data;
2151	if ((IWI_FW_GET_MAJOR(le32toh(hdr->version)) != IWI_FW_REQ_MAJOR) ||
2152	    (IWI_FW_GET_MINOR(le32toh(hdr->version)) != IWI_FW_REQ_MINOR)) {
2153		device_printf(sc->sc_dev, "version for '%s' %d.%d != %d.%d\n",
2154		    fp->name, IWI_FW_GET_MAJOR(le32toh(hdr->version)),
2155		    IWI_FW_GET_MINOR(le32toh(hdr->version)), IWI_FW_REQ_MAJOR,
2156		    IWI_FW_REQ_MINOR);
2157		return NULL;
2158	}
2159	fw->data = ((const char *) fp->data) + sizeof(struct iwi_firmware_ohdr);
2160	fw->size = fp->datasize - sizeof(struct iwi_firmware_ohdr);
2161	fw->name = fp->name;
2162	return hdr;
2163}
2164
2165static const struct iwi_firmware_ohdr *
2166iwi_setup_oucode(struct iwi_softc *sc, struct iwi_fw *fw)
2167{
2168	const struct iwi_firmware_ohdr *hdr;
2169
2170	hdr = iwi_setup_ofw(sc, fw);
2171	if (hdr != NULL && le32toh(hdr->mode) != IWI_FW_MODE_UCODE) {
2172		device_printf(sc->sc_dev, "%s is not a ucode image\n",
2173		    fw->name);
2174		hdr = NULL;
2175	}
2176	return hdr;
2177}
2178
2179static void
2180iwi_getfw(struct iwi_fw *fw, const char *fwname,
2181	  struct iwi_fw *uc, const char *ucname)
2182{
2183	if (fw->fp == NULL)
2184		fw->fp = firmware_get(fwname);
2185	/* NB: pre-3.0 ucode is packaged separately */
2186	if (uc->fp == NULL && fw->fp != NULL && fw->fp->version < 300)
2187		uc->fp = firmware_get(ucname);
2188}
2189
2190/*
2191 * Get the required firmware images if not already loaded.
2192 * Note that we hold firmware images so long as the device
2193 * is marked up in case we need to reload them on device init.
2194 * This is necessary because we re-init the device sometimes
2195 * from a context where we cannot read from the filesystem
2196 * (e.g. from the taskqueue thread when rfkill is re-enabled).
2197 * XXX return 0 on success, 1 on error.
2198 *
2199 * NB: the order of get'ing and put'ing images here is
2200 * intentional to support handling firmware images bundled
2201 * by operating mode and/or all together in one file with
2202 * the boot firmware as "master".
2203 */
2204static int
2205iwi_get_firmware(struct iwi_softc *sc, enum ieee80211_opmode opmode)
2206{
2207	const struct iwi_firmware_hdr *hdr;
2208	const struct firmware *fp;
2209
2210	/* invalidate cached firmware on mode change */
2211	if (sc->fw_mode != opmode)
2212		iwi_put_firmware(sc);
2213
2214	switch (opmode) {
2215	case IEEE80211_M_STA:
2216		iwi_getfw(&sc->fw_fw, "iwi_bss", &sc->fw_uc, "iwi_ucode_bss");
2217		break;
2218	case IEEE80211_M_IBSS:
2219		iwi_getfw(&sc->fw_fw, "iwi_ibss", &sc->fw_uc, "iwi_ucode_ibss");
2220		break;
2221	case IEEE80211_M_MONITOR:
2222		iwi_getfw(&sc->fw_fw, "iwi_monitor",
2223			  &sc->fw_uc, "iwi_ucode_monitor");
2224		break;
2225	default:
2226		device_printf(sc->sc_dev, "unknown opmode %d\n", opmode);
2227		return EINVAL;
2228	}
2229	fp = sc->fw_fw.fp;
2230	if (fp == NULL) {
2231		device_printf(sc->sc_dev, "could not load firmware\n");
2232		goto bad;
2233	}
2234	if (fp->version < 300) {
2235		/*
2236		 * Firmware prior to 3.0 was packaged as separate
2237		 * boot, firmware, and ucode images.  Verify the
2238		 * ucode image was read in, retrieve the boot image
2239		 * if needed, and check version stamps for consistency.
2240		 * The version stamps in the data are also checked
2241		 * above; this is a bit paranoid but is a cheap
2242		 * safeguard against mis-packaging.
2243		 */
2244		if (sc->fw_uc.fp == NULL) {
2245			device_printf(sc->sc_dev, "could not load ucode\n");
2246			goto bad;
2247		}
2248		if (sc->fw_boot.fp == NULL) {
2249			sc->fw_boot.fp = firmware_get("iwi_boot");
2250			if (sc->fw_boot.fp == NULL) {
2251				device_printf(sc->sc_dev,
2252					"could not load boot firmware\n");
2253				goto bad;
2254			}
2255		}
2256		if (sc->fw_boot.fp->version != sc->fw_fw.fp->version ||
2257		    sc->fw_boot.fp->version != sc->fw_uc.fp->version) {
2258			device_printf(sc->sc_dev,
2259			    "firmware version mismatch: "
2260			    "'%s' is %d, '%s' is %d, '%s' is %d\n",
2261			    sc->fw_boot.fp->name, sc->fw_boot.fp->version,
2262			    sc->fw_uc.fp->name, sc->fw_uc.fp->version,
2263			    sc->fw_fw.fp->name, sc->fw_fw.fp->version
2264			);
2265			goto bad;
2266		}
2267		/*
2268		 * Check and setup each image.
2269		 */
2270		if (iwi_setup_oucode(sc, &sc->fw_uc) == NULL ||
2271		    iwi_setup_ofw(sc, &sc->fw_boot) == NULL ||
2272		    iwi_setup_ofw(sc, &sc->fw_fw) == NULL)
2273			goto bad;
2274	} else {
2275		/*
2276		 * Check and setup combined image.
2277		 */
2278		if (fp->datasize < sizeof(struct iwi_firmware_hdr)) {
2279			device_printf(sc->sc_dev, "image '%s' too small\n",
2280			    fp->name);
2281			goto bad;
2282		}
2283		hdr = (const struct iwi_firmware_hdr *)fp->data;
2284		if (fp->datasize < sizeof(*hdr) + le32toh(hdr->bsize) + le32toh(hdr->usize)
2285				+ le32toh(hdr->fsize)) {
2286			device_printf(sc->sc_dev, "image '%s' too small (2)\n",
2287			    fp->name);
2288			goto bad;
2289		}
2290		sc->fw_boot.data = ((const char *) fp->data) + sizeof(*hdr);
2291		sc->fw_boot.size = le32toh(hdr->bsize);
2292		sc->fw_boot.name = fp->name;
2293		sc->fw_uc.data = sc->fw_boot.data + sc->fw_boot.size;
2294		sc->fw_uc.size = le32toh(hdr->usize);
2295		sc->fw_uc.name = fp->name;
2296		sc->fw_fw.data = sc->fw_uc.data + sc->fw_uc.size;
2297		sc->fw_fw.size = le32toh(hdr->fsize);
2298		sc->fw_fw.name = fp->name;
2299	}
2300#if 0
2301	device_printf(sc->sc_dev, "boot %d ucode %d fw %d bytes\n",
2302		sc->fw_boot.size, sc->fw_uc.size, sc->fw_fw.size);
2303#endif
2304
2305	sc->fw_mode = opmode;
2306	return 0;
2307bad:
2308	iwi_put_firmware(sc);
2309	return 1;
2310}
2311
2312static void
2313iwi_put_fw(struct iwi_fw *fw)
2314{
2315	if (fw->fp != NULL) {
2316		firmware_put(fw->fp, FIRMWARE_UNLOAD);
2317		fw->fp = NULL;
2318	}
2319	fw->data = NULL;
2320	fw->size = 0;
2321	fw->name = NULL;
2322}
2323
2324/*
2325 * Release any cached firmware images.
2326 */
2327static void
2328iwi_put_firmware(struct iwi_softc *sc)
2329{
2330	iwi_put_fw(&sc->fw_uc);
2331	iwi_put_fw(&sc->fw_fw);
2332	iwi_put_fw(&sc->fw_boot);
2333}
2334
2335static int
2336iwi_load_ucode(struct iwi_softc *sc, const struct iwi_fw *fw)
2337{
2338	uint32_t tmp;
2339	const uint16_t *w;
2340	const char *uc = fw->data;
2341	size_t size = fw->size;
2342	int i, ntries, error;
2343
2344	IWI_LOCK_ASSERT(sc);
2345	error = 0;
2346	CSR_WRITE_4(sc, IWI_CSR_RST, CSR_READ_4(sc, IWI_CSR_RST) |
2347	    IWI_RST_STOP_MASTER);
2348	for (ntries = 0; ntries < 5; ntries++) {
2349		if (CSR_READ_4(sc, IWI_CSR_RST) & IWI_RST_MASTER_DISABLED)
2350			break;
2351		DELAY(10);
2352	}
2353	if (ntries == 5) {
2354		device_printf(sc->sc_dev, "timeout waiting for master\n");
2355		error = EIO;
2356		goto fail;
2357	}
2358
2359	MEM_WRITE_4(sc, 0x3000e0, 0x80000000);
2360	DELAY(5000);
2361
2362	tmp = CSR_READ_4(sc, IWI_CSR_RST);
2363	tmp &= ~IWI_RST_PRINCETON_RESET;
2364	CSR_WRITE_4(sc, IWI_CSR_RST, tmp);
2365
2366	DELAY(5000);
2367	MEM_WRITE_4(sc, 0x3000e0, 0);
2368	DELAY(1000);
2369	MEM_WRITE_4(sc, IWI_MEM_EEPROM_EVENT, 1);
2370	DELAY(1000);
2371	MEM_WRITE_4(sc, IWI_MEM_EEPROM_EVENT, 0);
2372	DELAY(1000);
2373	MEM_WRITE_1(sc, 0x200000, 0x00);
2374	MEM_WRITE_1(sc, 0x200000, 0x40);
2375	DELAY(1000);
2376
2377	/* write microcode into adapter memory */
2378	for (w = (const uint16_t *)uc; size > 0; w++, size -= 2)
2379		MEM_WRITE_2(sc, 0x200010, htole16(*w));
2380
2381	MEM_WRITE_1(sc, 0x200000, 0x00);
2382	MEM_WRITE_1(sc, 0x200000, 0x80);
2383
2384	/* wait until we get an answer */
2385	for (ntries = 0; ntries < 100; ntries++) {
2386		if (MEM_READ_1(sc, 0x200000) & 1)
2387			break;
2388		DELAY(100);
2389	}
2390	if (ntries == 100) {
2391		device_printf(sc->sc_dev,
2392		    "timeout waiting for ucode to initialize\n");
2393		error = EIO;
2394		goto fail;
2395	}
2396
2397	/* read the answer or the firmware will not initialize properly */
2398	for (i = 0; i < 7; i++)
2399		MEM_READ_4(sc, 0x200004);
2400
2401	MEM_WRITE_1(sc, 0x200000, 0x00);
2402
2403fail:
2404	return error;
2405}
2406
2407/* macro to handle unaligned little endian data in firmware image */
2408#define GETLE32(p) ((p)[0] | (p)[1] << 8 | (p)[2] << 16 | (p)[3] << 24)
2409
2410static int
2411iwi_load_firmware(struct iwi_softc *sc, const struct iwi_fw *fw)
2412{
2413	u_char *p, *end;
2414	uint32_t sentinel, ctl, src, dst, sum, len, mlen, tmp;
2415	int ntries, error;
2416
2417	IWI_LOCK_ASSERT(sc);
2418
2419	/* copy firmware image to DMA memory */
2420	memcpy(sc->fw_virtaddr, fw->data, fw->size);
2421
2422	/* make sure the adapter will get up-to-date values */
2423	bus_dmamap_sync(sc->fw_dmat, sc->fw_map, BUS_DMASYNC_PREWRITE);
2424
2425	/* tell the adapter where the command blocks are stored */
2426	MEM_WRITE_4(sc, 0x3000a0, 0x27000);
2427
2428	/*
2429	 * Store command blocks into adapter's internal memory using register
2430	 * indirections. The adapter will read the firmware image through DMA
2431	 * using information stored in command blocks.
2432	 */
2433	src = sc->fw_physaddr;
2434	p = sc->fw_virtaddr;
2435	end = p + fw->size;
2436	CSR_WRITE_4(sc, IWI_CSR_AUTOINC_ADDR, 0x27000);
2437
2438	while (p < end) {
2439		dst = GETLE32(p); p += 4; src += 4;
2440		len = GETLE32(p); p += 4; src += 4;
2441		p += len;
2442
2443		while (len > 0) {
2444			mlen = min(len, IWI_CB_MAXDATALEN);
2445
2446			ctl = IWI_CB_DEFAULT_CTL | mlen;
2447			sum = ctl ^ src ^ dst;
2448
2449			/* write a command block */
2450			CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, ctl);
2451			CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, src);
2452			CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, dst);
2453			CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, sum);
2454
2455			src += mlen;
2456			dst += mlen;
2457			len -= mlen;
2458		}
2459	}
2460
2461	/* write a fictive final command block (sentinel) */
2462	sentinel = CSR_READ_4(sc, IWI_CSR_AUTOINC_ADDR);
2463	CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, 0);
2464
2465	tmp = CSR_READ_4(sc, IWI_CSR_RST);
2466	tmp &= ~(IWI_RST_MASTER_DISABLED | IWI_RST_STOP_MASTER);
2467	CSR_WRITE_4(sc, IWI_CSR_RST, tmp);
2468
2469	/* tell the adapter to start processing command blocks */
2470	MEM_WRITE_4(sc, 0x3000a4, 0x540100);
2471
2472	/* wait until the adapter reaches the sentinel */
2473	for (ntries = 0; ntries < 400; ntries++) {
2474		if (MEM_READ_4(sc, 0x3000d0) >= sentinel)
2475			break;
2476		DELAY(100);
2477	}
2478	/* sync dma, just in case */
2479	bus_dmamap_sync(sc->fw_dmat, sc->fw_map, BUS_DMASYNC_POSTWRITE);
2480	if (ntries == 400) {
2481		device_printf(sc->sc_dev,
2482		    "timeout processing command blocks for %s firmware\n",
2483		    fw->name);
2484		return EIO;
2485	}
2486
2487	/* we're done with command blocks processing */
2488	MEM_WRITE_4(sc, 0x3000a4, 0x540c00);
2489
2490	/* allow interrupts so we know when the firmware is ready */
2491	CSR_WRITE_4(sc, IWI_CSR_INTR_MASK, IWI_INTR_MASK);
2492
2493	/* tell the adapter to initialize the firmware */
2494	CSR_WRITE_4(sc, IWI_CSR_RST, 0);
2495
2496	tmp = CSR_READ_4(sc, IWI_CSR_CTL);
2497	CSR_WRITE_4(sc, IWI_CSR_CTL, tmp | IWI_CTL_ALLOW_STANDBY);
2498
2499	/* wait at most one second for firmware initialization to complete */
2500	if ((error = msleep(sc, &sc->sc_mtx, 0, "iwiinit", hz)) != 0) {
2501		device_printf(sc->sc_dev, "timeout waiting for %s firmware "
2502		    "initialization to complete\n", fw->name);
2503	}
2504
2505	return error;
2506}
2507
2508static int
2509iwi_setpowermode(struct iwi_softc *sc, struct ieee80211vap *vap)
2510{
2511	uint32_t data;
2512
2513	if (vap->iv_flags & IEEE80211_F_PMGTON) {
2514		/* XXX set more fine-grained operation */
2515		data = htole32(IWI_POWER_MODE_MAX);
2516	} else
2517		data = htole32(IWI_POWER_MODE_CAM);
2518
2519	DPRINTF(("Setting power mode to %u\n", le32toh(data)));
2520	return iwi_cmd(sc, IWI_CMD_SET_POWER_MODE, &data, sizeof data);
2521}
2522
2523static int
2524iwi_setwepkeys(struct iwi_softc *sc, struct ieee80211vap *vap)
2525{
2526	struct iwi_wep_key wepkey;
2527	struct ieee80211_key *wk;
2528	int error, i;
2529
2530	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
2531		wk = &vap->iv_nw_keys[i];
2532
2533		wepkey.cmd = IWI_WEP_KEY_CMD_SETKEY;
2534		wepkey.idx = i;
2535		wepkey.len = wk->wk_keylen;
2536		memset(wepkey.key, 0, sizeof wepkey.key);
2537		memcpy(wepkey.key, wk->wk_key, wk->wk_keylen);
2538		DPRINTF(("Setting wep key index %u len %u\n", wepkey.idx,
2539		    wepkey.len));
2540		error = iwi_cmd(sc, IWI_CMD_SET_WEP_KEY, &wepkey,
2541		    sizeof wepkey);
2542		if (error != 0)
2543			return error;
2544	}
2545	return 0;
2546}
2547
2548static int
2549iwi_config(struct iwi_softc *sc)
2550{
2551	struct ieee80211com *ic = &sc->sc_ic;
2552	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2553	struct iwi_configuration config;
2554	struct iwi_rateset rs;
2555	struct iwi_txpower power;
2556	uint8_t *macaddr;
2557	uint32_t data;
2558	int error, i;
2559
2560	IWI_LOCK_ASSERT(sc);
2561
2562	macaddr = vap ? vap->iv_myaddr : ic->ic_macaddr;
2563	DPRINTF(("Setting MAC address to %6D\n", macaddr, ":"));
2564	error = iwi_cmd(sc, IWI_CMD_SET_MAC_ADDRESS, macaddr,
2565	    IEEE80211_ADDR_LEN);
2566	if (error != 0)
2567		return error;
2568
2569	memset(&config, 0, sizeof config);
2570	config.bluetooth_coexistence = sc->bluetooth;
2571	config.silence_threshold = 0x1e;
2572	config.antenna = sc->antenna;
2573	config.multicast_enabled = 1;
2574	config.answer_pbreq = (ic->ic_opmode == IEEE80211_M_IBSS) ? 1 : 0;
2575	config.disable_unicast_decryption = 1;
2576	config.disable_multicast_decryption = 1;
2577	if (ic->ic_opmode == IEEE80211_M_MONITOR) {
2578		config.allow_invalid_frames = 1;
2579		config.allow_beacon_and_probe_resp = 1;
2580		config.allow_mgt = 1;
2581	}
2582	DPRINTF(("Configuring adapter\n"));
2583	error = iwi_cmd(sc, IWI_CMD_SET_CONFIG, &config, sizeof config);
2584	if (error != 0)
2585		return error;
2586	if (ic->ic_opmode == IEEE80211_M_IBSS) {
2587		power.mode = IWI_MODE_11B;
2588		power.nchan = 11;
2589		for (i = 0; i < 11; i++) {
2590			power.chan[i].chan = i + 1;
2591			power.chan[i].power = IWI_TXPOWER_MAX;
2592		}
2593		DPRINTF(("Setting .11b channels tx power\n"));
2594		error = iwi_cmd(sc, IWI_CMD_SET_TX_POWER, &power, sizeof power);
2595		if (error != 0)
2596			return error;
2597
2598		power.mode = IWI_MODE_11G;
2599		DPRINTF(("Setting .11g channels tx power\n"));
2600		error = iwi_cmd(sc, IWI_CMD_SET_TX_POWER, &power, sizeof power);
2601		if (error != 0)
2602			return error;
2603	}
2604
2605	memset(&rs, 0, sizeof rs);
2606	rs.mode = IWI_MODE_11G;
2607	rs.type = IWI_RATESET_TYPE_SUPPORTED;
2608	rs.nrates = ic->ic_sup_rates[IEEE80211_MODE_11G].rs_nrates;
2609	memcpy(rs.rates, ic->ic_sup_rates[IEEE80211_MODE_11G].rs_rates,
2610	    rs.nrates);
2611	DPRINTF(("Setting .11bg supported rates (%u)\n", rs.nrates));
2612	error = iwi_cmd(sc, IWI_CMD_SET_RATES, &rs, sizeof rs);
2613	if (error != 0)
2614		return error;
2615
2616	memset(&rs, 0, sizeof rs);
2617	rs.mode = IWI_MODE_11A;
2618	rs.type = IWI_RATESET_TYPE_SUPPORTED;
2619	rs.nrates = ic->ic_sup_rates[IEEE80211_MODE_11A].rs_nrates;
2620	memcpy(rs.rates, ic->ic_sup_rates[IEEE80211_MODE_11A].rs_rates,
2621	    rs.nrates);
2622	DPRINTF(("Setting .11a supported rates (%u)\n", rs.nrates));
2623	error = iwi_cmd(sc, IWI_CMD_SET_RATES, &rs, sizeof rs);
2624	if (error != 0)
2625		return error;
2626
2627	data = htole32(arc4random());
2628	DPRINTF(("Setting initialization vector to %u\n", le32toh(data)));
2629	error = iwi_cmd(sc, IWI_CMD_SET_IV, &data, sizeof data);
2630	if (error != 0)
2631		return error;
2632
2633	/* enable adapter */
2634	DPRINTF(("Enabling adapter\n"));
2635	return iwi_cmd(sc, IWI_CMD_ENABLE, NULL, 0);
2636}
2637
2638static __inline void
2639set_scan_type(struct iwi_scan_ext *scan, int ix, int scan_type)
2640{
2641	uint8_t *st = &scan->scan_type[ix / 2];
2642	if (ix % 2)
2643		*st = (*st & 0xf0) | ((scan_type & 0xf) << 0);
2644	else
2645		*st = (*st & 0x0f) | ((scan_type & 0xf) << 4);
2646}
2647
2648static int
2649scan_type(const struct ieee80211_scan_state *ss,
2650	const struct ieee80211_channel *chan)
2651{
2652	/* We can only set one essid for a directed scan */
2653	if (ss->ss_nssid != 0)
2654		return IWI_SCAN_TYPE_BDIRECTED;
2655	if ((ss->ss_flags & IEEE80211_SCAN_ACTIVE) &&
2656	    (chan->ic_flags & IEEE80211_CHAN_PASSIVE) == 0)
2657		return IWI_SCAN_TYPE_BROADCAST;
2658	return IWI_SCAN_TYPE_PASSIVE;
2659}
2660
2661static __inline int
2662scan_band(const struct ieee80211_channel *c)
2663{
2664	return IEEE80211_IS_CHAN_5GHZ(c) ?  IWI_CHAN_5GHZ : IWI_CHAN_2GHZ;
2665}
2666
2667static void
2668iwi_monitor_scan(void *arg, int npending)
2669{
2670	struct iwi_softc *sc = arg;
2671	IWI_LOCK_DECL;
2672
2673	IWI_LOCK(sc);
2674	(void) iwi_scanchan(sc, 2000, 0);
2675	IWI_UNLOCK(sc);
2676}
2677
2678/*
2679 * Start a scan on the current channel or all channels.
2680 */
2681static int
2682iwi_scanchan(struct iwi_softc *sc, unsigned long maxdwell, int allchan)
2683{
2684	struct ieee80211com *ic = &sc->sc_ic;
2685	struct ieee80211_channel *chan;
2686	struct ieee80211_scan_state *ss;
2687	struct iwi_scan_ext scan;
2688	int error = 0;
2689
2690	IWI_LOCK_ASSERT(sc);
2691	if (sc->fw_state == IWI_FW_SCANNING) {
2692		/*
2693		 * This should not happen as we only trigger scan_next after
2694		 * completion
2695		 */
2696		DPRINTF(("%s: called too early - still scanning\n", __func__));
2697		return (EBUSY);
2698	}
2699	IWI_STATE_BEGIN(sc, IWI_FW_SCANNING);
2700
2701	ss = ic->ic_scan;
2702
2703	memset(&scan, 0, sizeof scan);
2704	scan.full_scan_index = htole32(++sc->sc_scangen);
2705	scan.dwell_time[IWI_SCAN_TYPE_PASSIVE] = htole16(maxdwell);
2706	if (ic->ic_flags_ext & IEEE80211_FEXT_BGSCAN) {
2707		/*
2708		 * Use very short dwell times for when we send probe request
2709		 * frames.  Without this bg scans hang.  Ideally this should
2710		 * be handled with early-termination as done by net80211 but
2711		 * that's not feasible (aborting a scan is problematic).
2712		 */
2713		scan.dwell_time[IWI_SCAN_TYPE_BROADCAST] = htole16(30);
2714		scan.dwell_time[IWI_SCAN_TYPE_BDIRECTED] = htole16(30);
2715	} else {
2716		scan.dwell_time[IWI_SCAN_TYPE_BROADCAST] = htole16(maxdwell);
2717		scan.dwell_time[IWI_SCAN_TYPE_BDIRECTED] = htole16(maxdwell);
2718	}
2719
2720	/* We can only set one essid for a directed scan */
2721	if (ss->ss_nssid != 0) {
2722		error = iwi_cmd(sc, IWI_CMD_SET_ESSID, ss->ss_ssid[0].ssid,
2723		    ss->ss_ssid[0].len);
2724		if (error)
2725			return (error);
2726	}
2727
2728	if (allchan) {
2729		int i, next, band, b, bstart;
2730		/*
2731		 * Convert scan list to run-length encoded channel list
2732		 * the firmware requires (preserving the order setup by
2733		 * net80211).  The first entry in each run specifies the
2734		 * band and the count of items in the run.
2735		 */
2736		next = 0;		/* next open slot */
2737		bstart = 0;		/* NB: not needed, silence compiler */
2738		band = -1;		/* NB: impossible value */
2739		KASSERT(ss->ss_last > 0, ("no channels"));
2740		for (i = 0; i < ss->ss_last; i++) {
2741			chan = ss->ss_chans[i];
2742			b = scan_band(chan);
2743			if (b != band) {
2744				if (band != -1)
2745					scan.channels[bstart] =
2746					    (next - bstart) | band;
2747				/* NB: this allocates a slot for the run-len */
2748				band = b, bstart = next++;
2749			}
2750			if (next >= IWI_SCAN_CHANNELS) {
2751				DPRINTF(("truncating scan list\n"));
2752				break;
2753			}
2754			scan.channels[next] = ieee80211_chan2ieee(ic, chan);
2755			set_scan_type(&scan, next, scan_type(ss, chan));
2756			next++;
2757		}
2758		scan.channels[bstart] = (next - bstart) | band;
2759	} else {
2760		/* Scan the current channel only */
2761		chan = ic->ic_curchan;
2762		scan.channels[0] = 1 | scan_band(chan);
2763		scan.channels[1] = ieee80211_chan2ieee(ic, chan);
2764		set_scan_type(&scan, 1, scan_type(ss, chan));
2765	}
2766#ifdef IWI_DEBUG
2767	if (iwi_debug > 0) {
2768		static const char *scantype[8] =
2769		   { "PSTOP", "PASV", "DIR", "BCAST", "BDIR", "5", "6", "7" };
2770		int i;
2771		printf("Scan request: index %u dwell %d/%d/%d\n"
2772		    , le32toh(scan.full_scan_index)
2773		    , le16toh(scan.dwell_time[IWI_SCAN_TYPE_PASSIVE])
2774		    , le16toh(scan.dwell_time[IWI_SCAN_TYPE_BROADCAST])
2775		    , le16toh(scan.dwell_time[IWI_SCAN_TYPE_BDIRECTED])
2776		);
2777		i = 0;
2778		do {
2779			int run = scan.channels[i];
2780			if (run == 0)
2781				break;
2782			printf("Scan %d %s channels:", run & 0x3f,
2783			    run & IWI_CHAN_2GHZ ? "2.4GHz" : "5GHz");
2784			for (run &= 0x3f, i++; run > 0; run--, i++) {
2785				uint8_t type = scan.scan_type[i/2];
2786				printf(" %u/%s", scan.channels[i],
2787				    scantype[(i & 1 ? type : type>>4) & 7]);
2788			}
2789			printf("\n");
2790		} while (i < IWI_SCAN_CHANNELS);
2791	}
2792#endif
2793
2794	return (iwi_cmd(sc, IWI_CMD_SCAN_EXT, &scan, sizeof scan));
2795}
2796
2797static int
2798iwi_set_sensitivity(struct iwi_softc *sc, int8_t rssi_dbm)
2799{
2800	struct iwi_sensitivity sens;
2801
2802	DPRINTF(("Setting sensitivity to %d\n", rssi_dbm));
2803
2804	memset(&sens, 0, sizeof sens);
2805	sens.rssi = htole16(rssi_dbm);
2806	return iwi_cmd(sc, IWI_CMD_SET_SENSITIVITY, &sens, sizeof sens);
2807}
2808
2809static int
2810iwi_auth_and_assoc(struct iwi_softc *sc, struct ieee80211vap *vap)
2811{
2812	struct ieee80211com *ic = vap->iv_ic;
2813	struct ifnet *ifp = vap->iv_ifp;
2814	struct ieee80211_node *ni;
2815	struct iwi_configuration config;
2816	struct iwi_associate *assoc = &sc->assoc;
2817	struct iwi_rateset rs;
2818	uint16_t capinfo;
2819	uint32_t data;
2820	int error, mode;
2821
2822	IWI_LOCK_ASSERT(sc);
2823
2824	if (sc->flags & IWI_FLAG_ASSOCIATED) {
2825		DPRINTF(("Already associated\n"));
2826		return (-1);
2827	}
2828
2829	ni = ieee80211_ref_node(vap->iv_bss);
2830
2831	IWI_STATE_BEGIN(sc, IWI_FW_ASSOCIATING);
2832	error = 0;
2833	mode = 0;
2834
2835	if (IEEE80211_IS_CHAN_A(ic->ic_curchan))
2836		mode = IWI_MODE_11A;
2837	else if (IEEE80211_IS_CHAN_G(ic->ic_curchan))
2838		mode = IWI_MODE_11G;
2839	if (IEEE80211_IS_CHAN_B(ic->ic_curchan))
2840		mode = IWI_MODE_11B;
2841
2842	if (IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan)) {
2843		memset(&config, 0, sizeof config);
2844		config.bluetooth_coexistence = sc->bluetooth;
2845		config.antenna = sc->antenna;
2846		config.multicast_enabled = 1;
2847		if (mode == IWI_MODE_11G)
2848			config.use_protection = 1;
2849		config.answer_pbreq =
2850		    (vap->iv_opmode == IEEE80211_M_IBSS) ? 1 : 0;
2851		config.disable_unicast_decryption = 1;
2852		config.disable_multicast_decryption = 1;
2853		DPRINTF(("Configuring adapter\n"));
2854		error = iwi_cmd(sc, IWI_CMD_SET_CONFIG, &config, sizeof config);
2855		if (error != 0)
2856			goto done;
2857	}
2858
2859#ifdef IWI_DEBUG
2860	if (iwi_debug > 0) {
2861		printf("Setting ESSID to ");
2862		ieee80211_print_essid(ni->ni_essid, ni->ni_esslen);
2863		printf("\n");
2864	}
2865#endif
2866	error = iwi_cmd(sc, IWI_CMD_SET_ESSID, ni->ni_essid, ni->ni_esslen);
2867	if (error != 0)
2868		goto done;
2869
2870	error = iwi_setpowermode(sc, vap);
2871	if (error != 0)
2872		goto done;
2873
2874	data = htole32(vap->iv_rtsthreshold);
2875	DPRINTF(("Setting RTS threshold to %u\n", le32toh(data)));
2876	error = iwi_cmd(sc, IWI_CMD_SET_RTS_THRESHOLD, &data, sizeof data);
2877	if (error != 0)
2878		goto done;
2879
2880	data = htole32(vap->iv_fragthreshold);
2881	DPRINTF(("Setting fragmentation threshold to %u\n", le32toh(data)));
2882	error = iwi_cmd(sc, IWI_CMD_SET_FRAG_THRESHOLD, &data, sizeof data);
2883	if (error != 0)
2884		goto done;
2885
2886	/* the rate set has already been "negotiated" */
2887	memset(&rs, 0, sizeof rs);
2888	rs.mode = mode;
2889	rs.type = IWI_RATESET_TYPE_NEGOTIATED;
2890	rs.nrates = ni->ni_rates.rs_nrates;
2891	if (rs.nrates > IWI_RATESET_SIZE) {
2892		DPRINTF(("Truncating negotiated rate set from %u\n",
2893		    rs.nrates));
2894		rs.nrates = IWI_RATESET_SIZE;
2895	}
2896	memcpy(rs.rates, ni->ni_rates.rs_rates, rs.nrates);
2897	DPRINTF(("Setting negotiated rates (%u)\n", rs.nrates));
2898	error = iwi_cmd(sc, IWI_CMD_SET_RATES, &rs, sizeof rs);
2899	if (error != 0)
2900		goto done;
2901
2902	memset(assoc, 0, sizeof *assoc);
2903
2904	if ((vap->iv_flags & IEEE80211_F_WME) && ni->ni_ies.wme_ie != NULL) {
2905		/* NB: don't treat WME setup as failure */
2906		if (iwi_wme_setparams(sc) == 0 && iwi_wme_setie(sc) == 0)
2907			assoc->policy |= htole16(IWI_POLICY_WME);
2908		/* XXX complain on failure? */
2909	}
2910
2911	if (vap->iv_appie_wpa != NULL) {
2912		struct ieee80211_appie *ie = vap->iv_appie_wpa;
2913
2914		DPRINTF(("Setting optional IE (len=%u)\n", ie->ie_len));
2915		error = iwi_cmd(sc, IWI_CMD_SET_OPTIE, ie->ie_data, ie->ie_len);
2916		if (error != 0)
2917			goto done;
2918	}
2919
2920	error = iwi_set_sensitivity(sc, ic->ic_node_getrssi(ni));
2921	if (error != 0)
2922		goto done;
2923
2924	assoc->mode = mode;
2925	assoc->chan = ic->ic_curchan->ic_ieee;
2926	/*
2927	 * NB: do not arrange for shared key auth w/o privacy
2928	 *     (i.e. a wep key); it causes a firmware error.
2929	 */
2930	if ((vap->iv_flags & IEEE80211_F_PRIVACY) &&
2931	    ni->ni_authmode == IEEE80211_AUTH_SHARED) {
2932		assoc->auth = IWI_AUTH_SHARED;
2933		/*
2934		 * It's possible to have privacy marked but no default
2935		 * key setup.  This typically is due to a user app bug
2936		 * but if we blindly grab the key the firmware will
2937		 * barf so avoid it for now.
2938		 */
2939		if (vap->iv_def_txkey != IEEE80211_KEYIX_NONE)
2940			assoc->auth |= vap->iv_def_txkey << 4;
2941
2942		error = iwi_setwepkeys(sc, vap);
2943		if (error != 0)
2944			goto done;
2945	}
2946	if (vap->iv_flags & IEEE80211_F_WPA)
2947		assoc->policy |= htole16(IWI_POLICY_WPA);
2948	if (vap->iv_opmode == IEEE80211_M_IBSS && ni->ni_tstamp.tsf == 0)
2949		assoc->type = IWI_HC_IBSS_START;
2950	else
2951		assoc->type = IWI_HC_ASSOC;
2952	memcpy(assoc->tstamp, ni->ni_tstamp.data, 8);
2953
2954	if (vap->iv_opmode == IEEE80211_M_IBSS)
2955		capinfo = IEEE80211_CAPINFO_IBSS;
2956	else
2957		capinfo = IEEE80211_CAPINFO_ESS;
2958	if (vap->iv_flags & IEEE80211_F_PRIVACY)
2959		capinfo |= IEEE80211_CAPINFO_PRIVACY;
2960	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
2961	    IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan))
2962		capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
2963	if (ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME)
2964		capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
2965	assoc->capinfo = htole16(capinfo);
2966
2967	assoc->lintval = htole16(ic->ic_lintval);
2968	assoc->intval = htole16(ni->ni_intval);
2969	IEEE80211_ADDR_COPY(assoc->bssid, ni->ni_bssid);
2970	if (vap->iv_opmode == IEEE80211_M_IBSS)
2971		IEEE80211_ADDR_COPY(assoc->dst, ifp->if_broadcastaddr);
2972	else
2973		IEEE80211_ADDR_COPY(assoc->dst, ni->ni_bssid);
2974
2975	DPRINTF(("%s bssid %6D dst %6D channel %u policy 0x%x "
2976	    "auth %u capinfo 0x%x lintval %u bintval %u\n",
2977	    assoc->type == IWI_HC_IBSS_START ? "Start" : "Join",
2978	    assoc->bssid, ":", assoc->dst, ":",
2979	    assoc->chan, le16toh(assoc->policy), assoc->auth,
2980	    le16toh(assoc->capinfo), le16toh(assoc->lintval),
2981	    le16toh(assoc->intval)));
2982	error = iwi_cmd(sc, IWI_CMD_ASSOCIATE, assoc, sizeof *assoc);
2983done:
2984	ieee80211_free_node(ni);
2985	if (error)
2986		IWI_STATE_END(sc, IWI_FW_ASSOCIATING);
2987
2988	return (error);
2989}
2990
2991static void
2992iwi_disassoc(void *arg, int pending)
2993{
2994	struct iwi_softc *sc = arg;
2995	IWI_LOCK_DECL;
2996
2997	IWI_LOCK(sc);
2998	iwi_disassociate(sc, 0);
2999	IWI_UNLOCK(sc);
3000}
3001
3002static int
3003iwi_disassociate(struct iwi_softc *sc, int quiet)
3004{
3005	struct iwi_associate *assoc = &sc->assoc;
3006
3007	if ((sc->flags & IWI_FLAG_ASSOCIATED) == 0) {
3008		DPRINTF(("Not associated\n"));
3009		return (-1);
3010	}
3011
3012	IWI_STATE_BEGIN(sc, IWI_FW_DISASSOCIATING);
3013
3014	if (quiet)
3015		assoc->type = IWI_HC_DISASSOC_QUIET;
3016	else
3017		assoc->type = IWI_HC_DISASSOC;
3018
3019	DPRINTF(("Trying to disassociate from %6D channel %u\n",
3020	    assoc->bssid, ":", assoc->chan));
3021	return iwi_cmd(sc, IWI_CMD_ASSOCIATE, assoc, sizeof *assoc);
3022}
3023
3024/*
3025 * release dma resources for the firmware
3026 */
3027static void
3028iwi_release_fw_dma(struct iwi_softc *sc)
3029{
3030	if (sc->fw_flags & IWI_FW_HAVE_PHY)
3031		bus_dmamap_unload(sc->fw_dmat, sc->fw_map);
3032	if (sc->fw_flags & IWI_FW_HAVE_MAP)
3033		bus_dmamem_free(sc->fw_dmat, sc->fw_virtaddr, sc->fw_map);
3034	if (sc->fw_flags & IWI_FW_HAVE_DMAT)
3035		bus_dma_tag_destroy(sc->fw_dmat);
3036
3037	sc->fw_flags = 0;
3038	sc->fw_dma_size = 0;
3039	sc->fw_dmat = NULL;
3040	sc->fw_map = NULL;
3041	sc->fw_physaddr = 0;
3042	sc->fw_virtaddr = NULL;
3043}
3044
3045/*
3046 * allocate the dma descriptor for the firmware.
3047 * Return 0 on success, 1 on error.
3048 * Must be called unlocked, protected by IWI_FLAG_FW_LOADING.
3049 */
3050static int
3051iwi_init_fw_dma(struct iwi_softc *sc, int size)
3052{
3053	if (sc->fw_dma_size >= size)
3054		return 0;
3055	if (bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 4, 0,
3056	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
3057	    size, 1, size, 0, NULL, NULL, &sc->fw_dmat) != 0) {
3058		device_printf(sc->sc_dev,
3059		    "could not create firmware DMA tag\n");
3060		goto error;
3061	}
3062	sc->fw_flags |= IWI_FW_HAVE_DMAT;
3063	if (bus_dmamem_alloc(sc->fw_dmat, &sc->fw_virtaddr, 0,
3064	    &sc->fw_map) != 0) {
3065		device_printf(sc->sc_dev,
3066		    "could not allocate firmware DMA memory\n");
3067		goto error;
3068	}
3069	sc->fw_flags |= IWI_FW_HAVE_MAP;
3070	if (bus_dmamap_load(sc->fw_dmat, sc->fw_map, sc->fw_virtaddr,
3071	    size, iwi_dma_map_addr, &sc->fw_physaddr, 0) != 0) {
3072		device_printf(sc->sc_dev, "could not load firmware DMA map\n");
3073		goto error;
3074	}
3075	sc->fw_flags |= IWI_FW_HAVE_PHY;
3076	sc->fw_dma_size = size;
3077	return 0;
3078
3079error:
3080	iwi_release_fw_dma(sc);
3081	return 1;
3082}
3083
3084static void
3085iwi_init_locked(struct iwi_softc *sc)
3086{
3087	struct iwi_rx_data *data;
3088	int i;
3089
3090	IWI_LOCK_ASSERT(sc);
3091
3092	if (sc->fw_state == IWI_FW_LOADING) {
3093		device_printf(sc->sc_dev, "%s: already loading\n", __func__);
3094		return;		/* XXX: condvar? */
3095	}
3096
3097	iwi_stop_locked(sc);
3098
3099	IWI_STATE_BEGIN(sc, IWI_FW_LOADING);
3100
3101	if (iwi_reset(sc) != 0) {
3102		device_printf(sc->sc_dev, "could not reset adapter\n");
3103		goto fail;
3104	}
3105	if (iwi_load_firmware(sc, &sc->fw_boot) != 0) {
3106		device_printf(sc->sc_dev,
3107		    "could not load boot firmware %s\n", sc->fw_boot.name);
3108		goto fail;
3109	}
3110	if (iwi_load_ucode(sc, &sc->fw_uc) != 0) {
3111		device_printf(sc->sc_dev,
3112		    "could not load microcode %s\n", sc->fw_uc.name);
3113		goto fail;
3114	}
3115
3116	iwi_stop_master(sc);
3117
3118	CSR_WRITE_4(sc, IWI_CSR_CMD_BASE, sc->cmdq.physaddr);
3119	CSR_WRITE_4(sc, IWI_CSR_CMD_SIZE, sc->cmdq.count);
3120	CSR_WRITE_4(sc, IWI_CSR_CMD_WIDX, sc->cmdq.cur);
3121
3122	CSR_WRITE_4(sc, IWI_CSR_TX1_BASE, sc->txq[0].physaddr);
3123	CSR_WRITE_4(sc, IWI_CSR_TX1_SIZE, sc->txq[0].count);
3124	CSR_WRITE_4(sc, IWI_CSR_TX1_WIDX, sc->txq[0].cur);
3125
3126	CSR_WRITE_4(sc, IWI_CSR_TX2_BASE, sc->txq[1].physaddr);
3127	CSR_WRITE_4(sc, IWI_CSR_TX2_SIZE, sc->txq[1].count);
3128	CSR_WRITE_4(sc, IWI_CSR_TX2_WIDX, sc->txq[1].cur);
3129
3130	CSR_WRITE_4(sc, IWI_CSR_TX3_BASE, sc->txq[2].physaddr);
3131	CSR_WRITE_4(sc, IWI_CSR_TX3_SIZE, sc->txq[2].count);
3132	CSR_WRITE_4(sc, IWI_CSR_TX3_WIDX, sc->txq[2].cur);
3133
3134	CSR_WRITE_4(sc, IWI_CSR_TX4_BASE, sc->txq[3].physaddr);
3135	CSR_WRITE_4(sc, IWI_CSR_TX4_SIZE, sc->txq[3].count);
3136	CSR_WRITE_4(sc, IWI_CSR_TX4_WIDX, sc->txq[3].cur);
3137
3138	for (i = 0; i < sc->rxq.count; i++) {
3139		data = &sc->rxq.data[i];
3140		CSR_WRITE_4(sc, data->reg, data->physaddr);
3141	}
3142
3143	CSR_WRITE_4(sc, IWI_CSR_RX_WIDX, sc->rxq.count - 1);
3144
3145	if (iwi_load_firmware(sc, &sc->fw_fw) != 0) {
3146		device_printf(sc->sc_dev,
3147		    "could not load main firmware %s\n", sc->fw_fw.name);
3148		goto fail;
3149	}
3150	sc->flags |= IWI_FLAG_FW_INITED;
3151
3152	IWI_STATE_END(sc, IWI_FW_LOADING);
3153
3154	if (iwi_config(sc) != 0) {
3155		device_printf(sc->sc_dev, "unable to enable adapter\n");
3156		goto fail2;
3157	}
3158
3159	callout_reset(&sc->sc_wdtimer, hz, iwi_watchdog, sc);
3160	sc->sc_running = 1;
3161	return;
3162fail:
3163	IWI_STATE_END(sc, IWI_FW_LOADING);
3164fail2:
3165	iwi_stop_locked(sc);
3166}
3167
3168static void
3169iwi_init(void *priv)
3170{
3171	struct iwi_softc *sc = priv;
3172	struct ieee80211com *ic = &sc->sc_ic;
3173	IWI_LOCK_DECL;
3174
3175	IWI_LOCK(sc);
3176	iwi_init_locked(sc);
3177	IWI_UNLOCK(sc);
3178
3179	if (sc->sc_running)
3180		ieee80211_start_all(ic);
3181}
3182
3183static void
3184iwi_stop_locked(void *priv)
3185{
3186	struct iwi_softc *sc = priv;
3187
3188	IWI_LOCK_ASSERT(sc);
3189
3190	sc->sc_running = 0;
3191
3192	if (sc->sc_softled) {
3193		callout_stop(&sc->sc_ledtimer);
3194		sc->sc_blinking = 0;
3195	}
3196	callout_stop(&sc->sc_wdtimer);
3197	callout_stop(&sc->sc_rftimer);
3198
3199	iwi_stop_master(sc);
3200
3201	CSR_WRITE_4(sc, IWI_CSR_RST, IWI_RST_SOFT_RESET);
3202
3203	/* reset rings */
3204	iwi_reset_cmd_ring(sc, &sc->cmdq);
3205	iwi_reset_tx_ring(sc, &sc->txq[0]);
3206	iwi_reset_tx_ring(sc, &sc->txq[1]);
3207	iwi_reset_tx_ring(sc, &sc->txq[2]);
3208	iwi_reset_tx_ring(sc, &sc->txq[3]);
3209	iwi_reset_rx_ring(sc, &sc->rxq);
3210
3211	sc->sc_tx_timer = 0;
3212	sc->sc_state_timer = 0;
3213	sc->sc_busy_timer = 0;
3214	sc->flags &= ~(IWI_FLAG_BUSY | IWI_FLAG_ASSOCIATED);
3215	sc->fw_state = IWI_FW_IDLE;
3216	wakeup(sc);
3217}
3218
3219static void
3220iwi_stop(struct iwi_softc *sc)
3221{
3222	IWI_LOCK_DECL;
3223
3224	IWI_LOCK(sc);
3225	iwi_stop_locked(sc);
3226	IWI_UNLOCK(sc);
3227}
3228
3229static void
3230iwi_restart(void *arg, int npending)
3231{
3232	struct iwi_softc *sc = arg;
3233
3234	iwi_init(sc);
3235}
3236
3237/*
3238 * Return whether or not the radio is enabled in hardware
3239 * (i.e. the rfkill switch is "off").
3240 */
3241static int
3242iwi_getrfkill(struct iwi_softc *sc)
3243{
3244	return (CSR_READ_4(sc, IWI_CSR_IO) & IWI_IO_RADIO_ENABLED) == 0;
3245}
3246
3247static void
3248iwi_radio_on(void *arg, int pending)
3249{
3250	struct iwi_softc *sc = arg;
3251	struct ieee80211com *ic = &sc->sc_ic;
3252
3253	device_printf(sc->sc_dev, "radio turned on\n");
3254
3255	iwi_init(sc);
3256	ieee80211_notify_radio(ic, 1);
3257}
3258
3259static void
3260iwi_rfkill_poll(void *arg)
3261{
3262	struct iwi_softc *sc = arg;
3263
3264	IWI_LOCK_ASSERT(sc);
3265
3266	/*
3267	 * Check for a change in rfkill state.  We get an
3268	 * interrupt when a radio is disabled but not when
3269	 * it is enabled so we must poll for the latter.
3270	 */
3271	if (!iwi_getrfkill(sc)) {
3272		ieee80211_runtask(&sc->sc_ic, &sc->sc_radiontask);
3273		return;
3274	}
3275	callout_reset(&sc->sc_rftimer, 2*hz, iwi_rfkill_poll, sc);
3276}
3277
3278static void
3279iwi_radio_off(void *arg, int pending)
3280{
3281	struct iwi_softc *sc = arg;
3282	struct ieee80211com *ic = &sc->sc_ic;
3283	IWI_LOCK_DECL;
3284
3285	device_printf(sc->sc_dev, "radio turned off\n");
3286
3287	ieee80211_notify_radio(ic, 0);
3288
3289	IWI_LOCK(sc);
3290	iwi_stop_locked(sc);
3291	iwi_rfkill_poll(sc);
3292	IWI_UNLOCK(sc);
3293}
3294
3295static int
3296iwi_sysctl_stats(SYSCTL_HANDLER_ARGS)
3297{
3298	struct iwi_softc *sc = arg1;
3299	uint32_t size, buf[128];
3300
3301	memset(buf, 0, sizeof buf);
3302
3303	if (!(sc->flags & IWI_FLAG_FW_INITED))
3304		return SYSCTL_OUT(req, buf, sizeof buf);
3305
3306	size = min(CSR_READ_4(sc, IWI_CSR_TABLE0_SIZE), 128 - 1);
3307	CSR_READ_REGION_4(sc, IWI_CSR_TABLE0_BASE, &buf[1], size);
3308
3309	return SYSCTL_OUT(req, buf, size);
3310}
3311
3312static int
3313iwi_sysctl_radio(SYSCTL_HANDLER_ARGS)
3314{
3315	struct iwi_softc *sc = arg1;
3316	int val = !iwi_getrfkill(sc);
3317
3318	return SYSCTL_OUT(req, &val, sizeof val);
3319}
3320
3321/*
3322 * Add sysctl knobs.
3323 */
3324static void
3325iwi_sysctlattach(struct iwi_softc *sc)
3326{
3327	struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->sc_dev);
3328	struct sysctl_oid *tree = device_get_sysctl_tree(sc->sc_dev);
3329
3330	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "radio",
3331	    CTLTYPE_INT | CTLFLAG_RD, sc, 0, iwi_sysctl_radio, "I",
3332	    "radio transmitter switch state (0=off, 1=on)");
3333
3334	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "stats",
3335	    CTLTYPE_OPAQUE | CTLFLAG_RD, sc, 0, iwi_sysctl_stats, "S",
3336	    "statistics");
3337
3338	sc->bluetooth = 0;
3339	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "bluetooth",
3340	    CTLFLAG_RW, &sc->bluetooth, 0, "bluetooth coexistence");
3341
3342	sc->antenna = IWI_ANTENNA_AUTO;
3343	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "antenna",
3344	    CTLFLAG_RW, &sc->antenna, 0, "antenna (0=auto)");
3345}
3346
3347/*
3348 * LED support.
3349 *
3350 * Different cards have different capabilities.  Some have three
3351 * led's while others have only one.  The linux ipw driver defines
3352 * led's for link state (associated or not), band (11a, 11g, 11b),
3353 * and for link activity.  We use one led and vary the blink rate
3354 * according to the tx/rx traffic a la the ath driver.
3355 */
3356
3357static __inline uint32_t
3358iwi_toggle_event(uint32_t r)
3359{
3360	return r &~ (IWI_RST_STANDBY | IWI_RST_GATE_ODMA |
3361		     IWI_RST_GATE_IDMA | IWI_RST_GATE_ADMA);
3362}
3363
3364static uint32_t
3365iwi_read_event(struct iwi_softc *sc)
3366{
3367	return MEM_READ_4(sc, IWI_MEM_EEPROM_EVENT);
3368}
3369
3370static void
3371iwi_write_event(struct iwi_softc *sc, uint32_t v)
3372{
3373	MEM_WRITE_4(sc, IWI_MEM_EEPROM_EVENT, v);
3374}
3375
3376static void
3377iwi_led_done(void *arg)
3378{
3379	struct iwi_softc *sc = arg;
3380
3381	sc->sc_blinking = 0;
3382}
3383
3384/*
3385 * Turn the activity LED off: flip the pin and then set a timer so no
3386 * update will happen for the specified duration.
3387 */
3388static void
3389iwi_led_off(void *arg)
3390{
3391	struct iwi_softc *sc = arg;
3392	uint32_t v;
3393
3394	v = iwi_read_event(sc);
3395	v &= ~sc->sc_ledpin;
3396	iwi_write_event(sc, iwi_toggle_event(v));
3397	callout_reset(&sc->sc_ledtimer, sc->sc_ledoff, iwi_led_done, sc);
3398}
3399
3400/*
3401 * Blink the LED according to the specified on/off times.
3402 */
3403static void
3404iwi_led_blink(struct iwi_softc *sc, int on, int off)
3405{
3406	uint32_t v;
3407
3408	v = iwi_read_event(sc);
3409	v |= sc->sc_ledpin;
3410	iwi_write_event(sc, iwi_toggle_event(v));
3411	sc->sc_blinking = 1;
3412	sc->sc_ledoff = off;
3413	callout_reset(&sc->sc_ledtimer, on, iwi_led_off, sc);
3414}
3415
3416static void
3417iwi_led_event(struct iwi_softc *sc, int event)
3418{
3419	/* NB: on/off times from the Atheros NDIS driver, w/ permission */
3420	static const struct {
3421		u_int		rate;		/* tx/rx iwi rate */
3422		u_int16_t	timeOn;		/* LED on time (ms) */
3423		u_int16_t	timeOff;	/* LED off time (ms) */
3424	} blinkrates[] = {
3425		{ IWI_RATE_OFDM54, 40,  10 },
3426		{ IWI_RATE_OFDM48, 44,  11 },
3427		{ IWI_RATE_OFDM36, 50,  13 },
3428		{ IWI_RATE_OFDM24, 57,  14 },
3429		{ IWI_RATE_OFDM18, 67,  16 },
3430		{ IWI_RATE_OFDM12, 80,  20 },
3431		{ IWI_RATE_DS11,  100,  25 },
3432		{ IWI_RATE_OFDM9, 133,  34 },
3433		{ IWI_RATE_OFDM6, 160,  40 },
3434		{ IWI_RATE_DS5,   200,  50 },
3435		{            6,   240,  58 },	/* XXX 3Mb/s if it existed */
3436		{ IWI_RATE_DS2,   267,  66 },
3437		{ IWI_RATE_DS1,   400, 100 },
3438		{            0,   500, 130 },	/* unknown rate/polling */
3439	};
3440	uint32_t txrate;
3441	int j = 0;			/* XXX silence compiler */
3442
3443	sc->sc_ledevent = ticks;	/* time of last event */
3444	if (sc->sc_blinking)		/* don't interrupt active blink */
3445		return;
3446	switch (event) {
3447	case IWI_LED_POLL:
3448		j = nitems(blinkrates)-1;
3449		break;
3450	case IWI_LED_TX:
3451		/* read current transmission rate from adapter */
3452		txrate = CSR_READ_4(sc, IWI_CSR_CURRENT_TX_RATE);
3453		if (blinkrates[sc->sc_txrix].rate != txrate) {
3454			for (j = 0; j < nitems(blinkrates)-1; j++)
3455				if (blinkrates[j].rate == txrate)
3456					break;
3457			sc->sc_txrix = j;
3458		} else
3459			j = sc->sc_txrix;
3460		break;
3461	case IWI_LED_RX:
3462		if (blinkrates[sc->sc_rxrix].rate != sc->sc_rxrate) {
3463			for (j = 0; j < nitems(blinkrates)-1; j++)
3464				if (blinkrates[j].rate == sc->sc_rxrate)
3465					break;
3466			sc->sc_rxrix = j;
3467		} else
3468			j = sc->sc_rxrix;
3469		break;
3470	}
3471	/* XXX beware of overflow */
3472	iwi_led_blink(sc, (blinkrates[j].timeOn * hz) / 1000,
3473		(blinkrates[j].timeOff * hz) / 1000);
3474}
3475
3476static int
3477iwi_sysctl_softled(SYSCTL_HANDLER_ARGS)
3478{
3479	struct iwi_softc *sc = arg1;
3480	int softled = sc->sc_softled;
3481	int error;
3482
3483	error = sysctl_handle_int(oidp, &softled, 0, req);
3484	if (error || !req->newptr)
3485		return error;
3486	softled = (softled != 0);
3487	if (softled != sc->sc_softled) {
3488		if (softled) {
3489			uint32_t v = iwi_read_event(sc);
3490			v &= ~sc->sc_ledpin;
3491			iwi_write_event(sc, iwi_toggle_event(v));
3492		}
3493		sc->sc_softled = softled;
3494	}
3495	return 0;
3496}
3497
3498static void
3499iwi_ledattach(struct iwi_softc *sc)
3500{
3501	struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->sc_dev);
3502	struct sysctl_oid *tree = device_get_sysctl_tree(sc->sc_dev);
3503
3504	sc->sc_blinking = 0;
3505	sc->sc_ledstate = 1;
3506	sc->sc_ledidle = (2700*hz)/1000;	/* 2.7sec */
3507	callout_init_mtx(&sc->sc_ledtimer, &sc->sc_mtx, 0);
3508
3509	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
3510		"softled", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
3511		iwi_sysctl_softled, "I", "enable/disable software LED support");
3512	SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
3513		"ledpin", CTLFLAG_RW, &sc->sc_ledpin, 0,
3514		"pin setting to turn activity LED on");
3515	SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
3516		"ledidle", CTLFLAG_RW, &sc->sc_ledidle, 0,
3517		"idle time for inactivity LED (ticks)");
3518	/* XXX for debugging */
3519	SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
3520		"nictype", CTLFLAG_RD, &sc->sc_nictype, 0,
3521		"NIC type from EEPROM");
3522
3523	sc->sc_ledpin = IWI_RST_LED_ACTIVITY;
3524	sc->sc_softled = 1;
3525
3526	sc->sc_nictype = (iwi_read_prom_word(sc, IWI_EEPROM_NIC) >> 8) & 0xff;
3527	if (sc->sc_nictype == 1) {
3528		/*
3529		 * NB: led's are reversed.
3530		 */
3531		sc->sc_ledpin = IWI_RST_LED_ASSOCIATED;
3532	}
3533}
3534
3535static void
3536iwi_scan_start(struct ieee80211com *ic)
3537{
3538	/* ignore */
3539}
3540
3541static void
3542iwi_set_channel(struct ieee80211com *ic)
3543{
3544	struct iwi_softc *sc = ic->ic_softc;
3545
3546	if (sc->fw_state == IWI_FW_IDLE)
3547		iwi_setcurchan(sc, ic->ic_curchan->ic_ieee);
3548}
3549
3550static void
3551iwi_scan_curchan(struct ieee80211_scan_state *ss, unsigned long maxdwell)
3552{
3553	struct ieee80211vap *vap = ss->ss_vap;
3554	struct iwi_softc *sc = vap->iv_ic->ic_softc;
3555	IWI_LOCK_DECL;
3556
3557	IWI_LOCK(sc);
3558	if (iwi_scanchan(sc, maxdwell, 0))
3559		ieee80211_cancel_scan(vap);
3560	IWI_UNLOCK(sc);
3561}
3562
3563static void
3564iwi_scan_mindwell(struct ieee80211_scan_state *ss)
3565{
3566	/* NB: don't try to abort scan; wait for firmware to finish */
3567}
3568
3569static void
3570iwi_scan_end(struct ieee80211com *ic)
3571{
3572	struct iwi_softc *sc = ic->ic_softc;
3573	IWI_LOCK_DECL;
3574
3575	IWI_LOCK(sc);
3576	sc->flags &= ~IWI_FLAG_CHANNEL_SCAN;
3577	/* NB: make sure we're still scanning */
3578	if (sc->fw_state == IWI_FW_SCANNING)
3579		iwi_cmd(sc, IWI_CMD_ABORT_SCAN, NULL, 0);
3580	IWI_UNLOCK(sc);
3581}
3582
3583static void
3584iwi_collect_bands(struct ieee80211com *ic, uint8_t bands[], size_t bands_sz)
3585{
3586	struct iwi_softc *sc = ic->ic_softc;
3587	device_t dev = sc->sc_dev;
3588
3589	memset(bands, 0, bands_sz);
3590	setbit(bands, IEEE80211_MODE_11B);
3591	setbit(bands, IEEE80211_MODE_11G);
3592	if (pci_get_device(dev) >= 0x4223)
3593		setbit(bands, IEEE80211_MODE_11A);
3594}
3595
3596static void
3597iwi_getradiocaps(struct ieee80211com *ic,
3598    int maxchans, int *nchans, struct ieee80211_channel chans[])
3599{
3600	uint8_t bands[IEEE80211_MODE_BYTES];
3601
3602	iwi_collect_bands(ic, bands, sizeof(bands));
3603	*nchans = 0;
3604	if (isset(bands, IEEE80211_MODE_11B) || isset(bands, IEEE80211_MODE_11G))
3605		ieee80211_add_channels_default_2ghz(chans, maxchans, nchans,
3606		    bands, 0);
3607	if (isset(bands, IEEE80211_MODE_11A)) {
3608		ieee80211_add_channel_list_5ghz(chans, maxchans, nchans,
3609		    def_chan_5ghz_band1, nitems(def_chan_5ghz_band1),
3610		    bands, 0);
3611		ieee80211_add_channel_list_5ghz(chans, maxchans, nchans,
3612		    def_chan_5ghz_band2, nitems(def_chan_5ghz_band2),
3613		    bands, 0);
3614		ieee80211_add_channel_list_5ghz(chans, maxchans, nchans,
3615		    def_chan_5ghz_band3, nitems(def_chan_5ghz_band3),
3616		    bands, 0);
3617	}
3618}
3619