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