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