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