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