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