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