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