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