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