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