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