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