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