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