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