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