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