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