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