xref: /freebsd/sys/dev/iwi/if_iwi.c (revision b6de9e91bd2c47efaeec72a08642f8fd99cc7b20)
1 /*	$FreeBSD$	*/
2 
3 /*-
4  * Copyright (c) 2004, 2005
5  *      Damien Bergamini <damien.bergamini@free.fr>. All rights reserved.
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/module.h>
47 #include <sys/bus.h>
48 #include <sys/endian.h>
49 
50 #include <machine/bus.h>
51 #include <machine/resource.h>
52 #include <machine/clock.h>
53 #include <sys/rman.h>
54 
55 #include <dev/pci/pcireg.h>
56 #include <dev/pci/pcivar.h>
57 
58 #include <net/bpf.h>
59 #include <net/if.h>
60 #include <net/if_arp.h>
61 #include <net/ethernet.h>
62 #include <net/if_dl.h>
63 #include <net/if_media.h>
64 #include <net/if_types.h>
65 
66 #include <net80211/ieee80211_var.h>
67 #include <net80211/ieee80211_radiotap.h>
68 
69 #include <netinet/in.h>
70 #include <netinet/in_systm.h>
71 #include <netinet/in_var.h>
72 #include <netinet/ip.h>
73 #include <netinet/if_ether.h>
74 
75 #include <dev/iwi/if_iwireg.h>
76 #include <dev/iwi/if_iwivar.h>
77 
78 #ifdef IWI_DEBUG
79 #define DPRINTF(x)	do { if (iwi_debug > 0) printf x; } while (0)
80 #define DPRINTFN(n, x)	do { if (iwi_debug >= (n)) printf x; } while (0)
81 int iwi_debug = 0;
82 SYSCTL_INT(_debug, OID_AUTO, iwi, CTLFLAG_RW, &iwi_debug, 0, "iwi debug level");
83 #else
84 #define DPRINTF(x)
85 #define DPRINTFN(n, x)
86 #endif
87 
88 MODULE_DEPEND(iwi, pci,  1, 1, 1);
89 MODULE_DEPEND(iwi, wlan, 1, 1, 1);
90 
91 struct iwi_ident {
92 	uint16_t	vendor;
93 	uint16_t	device;
94 	const char	*name;
95 };
96 
97 static const struct iwi_ident iwi_ident_table[] = {
98 	{ 0x8086, 0x4220, "Intel(R) PRO/Wireless 2200BG" },
99 	{ 0x8086, 0x4221, "Intel(R) PRO/Wireless 2225BG" },
100 	{ 0x8086, 0x4223, "Intel(R) PRO/Wireless 2915ABG" },
101 	{ 0x8086, 0x4224, "Intel(R) PRO/Wireless 2915ABG" },
102 
103 	{ 0, 0, NULL }
104 };
105 
106 static void	iwi_dma_map_addr(void *, bus_dma_segment_t *, int, int);
107 static int	iwi_alloc_cmd_ring(struct iwi_softc *, struct iwi_cmd_ring *,
108 		    int);
109 static void	iwi_reset_cmd_ring(struct iwi_softc *, struct iwi_cmd_ring *);
110 static void	iwi_free_cmd_ring(struct iwi_softc *, struct iwi_cmd_ring *);
111 static int	iwi_alloc_tx_ring(struct iwi_softc *, struct iwi_tx_ring *,
112 		    int, bus_addr_t, bus_addr_t);
113 static void	iwi_reset_tx_ring(struct iwi_softc *, struct iwi_tx_ring *);
114 static void	iwi_free_tx_ring(struct iwi_softc *, struct iwi_tx_ring *);
115 static int	iwi_alloc_rx_ring(struct iwi_softc *, struct iwi_rx_ring *,
116 		    int);
117 static void	iwi_reset_rx_ring(struct iwi_softc *, struct iwi_rx_ring *);
118 static void	iwi_free_rx_ring(struct iwi_softc *, struct iwi_rx_ring *);
119 static struct	ieee80211_node *iwi_node_alloc(struct ieee80211_node_table *);
120 static void	iwi_node_free(struct ieee80211_node *);
121 static int	iwi_media_change(struct ifnet *);
122 static void	iwi_media_status(struct ifnet *, struct ifmediareq *);
123 static int	iwi_newstate(struct ieee80211com *, enum ieee80211_state, int);
124 static int	iwi_wme_update(struct ieee80211com *);
125 static uint16_t	iwi_read_prom_word(struct iwi_softc *, uint8_t);
126 static void	iwi_fix_channel(struct ieee80211com *, struct mbuf *);
127 static void	iwi_frame_intr(struct iwi_softc *, struct iwi_rx_data *, int,
128 		    struct iwi_frame *);
129 static void	iwi_notification_intr(struct iwi_softc *, struct iwi_notif *);
130 static void	iwi_rx_intr(struct iwi_softc *);
131 static void	iwi_tx_intr(struct iwi_softc *, struct iwi_tx_ring *);
132 static void	iwi_intr(void *);
133 static int	iwi_cmd(struct iwi_softc *, uint8_t, void *, uint8_t, int);
134 static void	iwi_write_ibssnode(struct iwi_softc *, const struct iwi_node *);
135 static int	iwi_tx_start(struct ifnet *, struct mbuf *,
136 		    struct ieee80211_node *, int);
137 static void	iwi_start(struct ifnet *);
138 static void	iwi_watchdog(struct ifnet *);
139 static int	iwi_ioctl(struct ifnet *, u_long, caddr_t);
140 static void	iwi_stop_master(struct iwi_softc *);
141 static int	iwi_reset(struct iwi_softc *);
142 static int	iwi_load_ucode(struct iwi_softc *, void *, int);
143 static int	iwi_load_firmware(struct iwi_softc *, void *, int);
144 static int	iwi_cache_firmware(struct iwi_softc *, void *);
145 static void	iwi_free_firmware(struct iwi_softc *);
146 static int	iwi_config(struct iwi_softc *);
147 static int	iwi_set_chan(struct iwi_softc *, struct ieee80211_channel *);
148 static int	iwi_scan(struct iwi_softc *);
149 static int	iwi_auth_and_assoc(struct iwi_softc *);
150 static void	iwi_init(void *);
151 static void	iwi_stop(void *);
152 static int	iwi_sysctl_stats(SYSCTL_HANDLER_ARGS);
153 static int	iwi_sysctl_radio(SYSCTL_HANDLER_ARGS);
154 
155 static int iwi_probe(device_t);
156 static int iwi_attach(device_t);
157 static int iwi_detach(device_t);
158 static int iwi_shutdown(device_t);
159 static int iwi_suspend(device_t);
160 static int iwi_resume(device_t);
161 
162 static device_method_t iwi_methods[] = {
163 	/* Device interface */
164 	DEVMETHOD(device_probe,		iwi_probe),
165 	DEVMETHOD(device_attach,	iwi_attach),
166 	DEVMETHOD(device_detach,	iwi_detach),
167 	DEVMETHOD(device_shutdown,	iwi_shutdown),
168 	DEVMETHOD(device_suspend,	iwi_suspend),
169 	DEVMETHOD(device_resume,	iwi_resume),
170 
171 	{ 0, 0 }
172 };
173 
174 static driver_t iwi_driver = {
175 	"iwi",
176 	iwi_methods,
177 	sizeof (struct iwi_softc)
178 };
179 
180 static devclass_t iwi_devclass;
181 
182 DRIVER_MODULE(iwi, pci, iwi_driver, iwi_devclass, 0, 0);
183 
184 /*
185  * Supported rates for 802.11a/b/g modes (in 500Kbps unit).
186  */
187 static const struct ieee80211_rateset iwi_rateset_11a =
188 	{ 8, { 12, 18, 24, 36, 48, 72, 96, 108 } };
189 
190 static const struct ieee80211_rateset iwi_rateset_11b =
191 	{ 4, { 2, 4, 11, 22 } };
192 
193 static const struct ieee80211_rateset iwi_rateset_11g =
194 	{ 12, { 2, 4, 11, 22, 12, 18, 24, 36, 48, 72, 96, 108 } };
195 
196 static __inline uint8_t
197 MEM_READ_1(struct iwi_softc *sc, uint32_t addr)
198 {
199 	CSR_WRITE_4(sc, IWI_CSR_INDIRECT_ADDR, addr);
200 	return CSR_READ_1(sc, IWI_CSR_INDIRECT_DATA);
201 }
202 
203 static __inline uint32_t
204 MEM_READ_4(struct iwi_softc *sc, uint32_t addr)
205 {
206 	CSR_WRITE_4(sc, IWI_CSR_INDIRECT_ADDR, addr);
207 	return CSR_READ_4(sc, IWI_CSR_INDIRECT_DATA);
208 }
209 
210 static int
211 iwi_probe(device_t dev)
212 {
213 	const struct iwi_ident *ident;
214 
215 	for (ident = iwi_ident_table; ident->name != NULL; ident++) {
216 		if (pci_get_vendor(dev) == ident->vendor &&
217 		    pci_get_device(dev) == ident->device) {
218 			device_set_desc(dev, ident->name);
219 			return 0;
220 		}
221 	}
222 	return ENXIO;
223 }
224 
225 /* Base Address Register */
226 #define IWI_PCI_BAR0	0x10
227 
228 static int
229 iwi_attach(device_t dev)
230 {
231 	struct iwi_softc *sc = device_get_softc(dev);
232 	struct ifnet *ifp;
233 	struct ieee80211com *ic = &sc->sc_ic;
234 	uint16_t val;
235 	int error, i;
236 
237 	sc->sc_dev = dev;
238 
239 	mtx_init(&sc->sc_mtx, device_get_nameunit(dev), MTX_NETWORK_LOCK,
240 	    MTX_DEF | MTX_RECURSE);
241 
242 	sc->sc_unr = new_unrhdr(0, IWI_MAX_IBSSNODE, &sc->sc_mtx);
243 
244 	if (pci_get_powerstate(dev) != PCI_POWERSTATE_D0) {
245 		device_printf(dev, "chip is in D%d power mode "
246 		    "-- setting to D0\n", pci_get_powerstate(dev));
247 		pci_set_powerstate(dev, PCI_POWERSTATE_D0);
248 	}
249 
250 	pci_write_config(dev, 0x41, 0, 1);
251 
252 	/* enable bus-mastering */
253 	pci_enable_busmaster(dev);
254 
255 	sc->mem_rid = IWI_PCI_BAR0;
256 	sc->mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &sc->mem_rid,
257 	    RF_ACTIVE);
258 	if (sc->mem == NULL) {
259 		device_printf(dev, "could not allocate memory resource\n");
260 		goto fail;
261 	}
262 
263 	sc->sc_st = rman_get_bustag(sc->mem);
264 	sc->sc_sh = rman_get_bushandle(sc->mem);
265 
266 	sc->irq_rid = 0;
267 	sc->irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &sc->irq_rid,
268 	    RF_ACTIVE | RF_SHAREABLE);
269 	if (sc->irq == NULL) {
270 		device_printf(dev, "could not allocate interrupt resource\n");
271 		goto fail;
272 	}
273 
274 	if (iwi_reset(sc) != 0) {
275 		device_printf(dev, "could not reset adapter\n");
276 		goto fail;
277 	}
278 
279 	/*
280 	 * Allocate rings.
281 	 */
282 	if (iwi_alloc_cmd_ring(sc, &sc->cmdq, IWI_CMD_RING_COUNT) != 0) {
283 		device_printf(dev, "could not allocate Cmd ring\n");
284 		goto fail;
285 	}
286 
287 	error = iwi_alloc_tx_ring(sc, &sc->txq[0], IWI_TX_RING_COUNT,
288 	    IWI_CSR_TX1_RIDX, IWI_CSR_TX1_WIDX);
289 	if (error != 0) {
290 		device_printf(dev, "could not allocate Tx ring 1\n");
291 		goto fail;
292 	}
293 
294 	error = iwi_alloc_tx_ring(sc, &sc->txq[1], IWI_TX_RING_COUNT,
295 	    IWI_CSR_TX2_RIDX, IWI_CSR_TX2_WIDX);
296 	if (error != 0) {
297 		device_printf(dev, "could not allocate Tx ring 2\n");
298 		goto fail;
299 	}
300 
301 	error = iwi_alloc_tx_ring(sc, &sc->txq[2], IWI_TX_RING_COUNT,
302 	    IWI_CSR_TX3_RIDX, IWI_CSR_TX3_WIDX);
303 	if (error != 0) {
304 		device_printf(dev, "could not allocate Tx ring 3\n");
305 		goto fail;
306 	}
307 
308 	error = iwi_alloc_tx_ring(sc, &sc->txq[3], IWI_TX_RING_COUNT,
309 	    IWI_CSR_TX4_RIDX, IWI_CSR_TX4_WIDX);
310 	if (error != 0) {
311 		device_printf(dev, "could not allocate Tx ring 4\n");
312 		goto fail;
313 	}
314 
315 	if (iwi_alloc_rx_ring(sc, &sc->rxq, IWI_RX_RING_COUNT) != 0) {
316 		device_printf(dev, "could not allocate Rx ring\n");
317 		goto fail;
318 	}
319 
320 	ifp = sc->sc_ifp = if_alloc(IFT_ETHER);
321 	if (ifp == NULL) {
322 		device_printf(dev, "can not if_alloc()\n");
323 		goto fail;
324 	}
325 	ifp->if_softc = sc;
326 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
327 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
328 	ifp->if_init = iwi_init;
329 	ifp->if_ioctl = iwi_ioctl;
330 	ifp->if_start = iwi_start;
331 	ifp->if_watchdog = iwi_watchdog;
332 	IFQ_SET_MAXLEN(&ifp->if_snd, IFQ_MAXLEN);
333 	ifp->if_snd.ifq_drv_maxlen = IFQ_MAXLEN;
334 	IFQ_SET_READY(&ifp->if_snd);
335 
336 	ic->ic_ifp = ifp;
337 	ic->ic_wme.wme_update = iwi_wme_update;
338 	ic->ic_phytype = IEEE80211_T_OFDM; /* not only, but not used */
339 	ic->ic_opmode = IEEE80211_M_STA; /* default to BSS mode */
340 	ic->ic_state = IEEE80211_S_INIT;
341 
342 	/* set device capabilities */
343 	ic->ic_caps =
344 	    IEEE80211_C_IBSS |		/* IBSS mode supported */
345 	    IEEE80211_C_MONITOR |	/* monitor mode supported */
346 	    IEEE80211_C_TXPMGT |	/* tx power management */
347 	    IEEE80211_C_SHPREAMBLE |	/* short preamble supported */
348 	    IEEE80211_C_WPA |		/* 802.11i */
349 	    IEEE80211_C_WME;		/* 802.11e */
350 
351 	/* read MAC address from EEPROM */
352 	val = iwi_read_prom_word(sc, IWI_EEPROM_MAC + 0);
353 	ic->ic_myaddr[0] = val >> 8;
354 	ic->ic_myaddr[1] = val & 0xff;
355 	val = iwi_read_prom_word(sc, IWI_EEPROM_MAC + 1);
356 	ic->ic_myaddr[2] = val >> 8;
357 	ic->ic_myaddr[3] = val & 0xff;
358 	val = iwi_read_prom_word(sc, IWI_EEPROM_MAC + 2);
359 	ic->ic_myaddr[4] = val >> 8;
360 	ic->ic_myaddr[5] = val & 0xff;
361 
362 #if 0
363 	if (pci_get_device(dev) >= 0x4223) {
364 		/* set supported .11a rates (2915ABG only) */
365 		ic->ic_sup_rates[IEEE80211_MODE_11A] = iwi_rateset_11a;
366 
367 		/* set supported .11a channels */
368 		for (i = 36; i <= 64; i += 4) {
369 			ic->ic_channels[i].ic_freq =
370 			    ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
371 			ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
372 		}
373 		for (i = 149; i <= 165; i += 4) {
374 			ic->ic_channels[i].ic_freq =
375 			    ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
376 			ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
377 		}
378 	}
379 #endif
380 
381 	/* set supported .11b and .11g rates */
382 	ic->ic_sup_rates[IEEE80211_MODE_11B] = iwi_rateset_11b;
383 	ic->ic_sup_rates[IEEE80211_MODE_11G] = iwi_rateset_11g;
384 
385 	/* set supported .11b and .11g channels (1 through 14) */
386 	for (i = 1; i <= 14; i++) {
387 		ic->ic_channels[i].ic_freq =
388 		    ieee80211_ieee2mhz(i, IEEE80211_CHAN_2GHZ);
389 		ic->ic_channels[i].ic_flags =
390 		    IEEE80211_CHAN_CCK | IEEE80211_CHAN_OFDM |
391 		    IEEE80211_CHAN_DYN | IEEE80211_CHAN_2GHZ;
392 	}
393 
394 	ieee80211_ifattach(ic);
395 	/* override default methods */
396 	ic->ic_node_alloc = iwi_node_alloc;
397 	sc->sc_node_free = ic->ic_node_free;
398 	ic->ic_node_free = iwi_node_free;
399 	/* override state transition machine */
400 	sc->sc_newstate = ic->ic_newstate;
401 	ic->ic_newstate = iwi_newstate;
402 	ieee80211_media_init(ic, iwi_media_change, iwi_media_status);
403 
404 	bpfattach2(ifp, DLT_IEEE802_11_RADIO,
405 	    sizeof (struct ieee80211_frame) + 64, &sc->sc_drvbpf);
406 
407 	sc->sc_rxtap_len = sizeof sc->sc_rxtapu;
408 	sc->sc_rxtap.wr_ihdr.it_len = htole16(sc->sc_rxtap_len);
409 	sc->sc_rxtap.wr_ihdr.it_present = htole32(IWI_RX_RADIOTAP_PRESENT);
410 
411 	sc->sc_txtap_len = sizeof sc->sc_txtapu;
412 	sc->sc_txtap.wt_ihdr.it_len = htole16(sc->sc_txtap_len);
413 	sc->sc_txtap.wt_ihdr.it_present = htole32(IWI_TX_RADIOTAP_PRESENT);
414 
415 	/*
416 	 * Add a few sysctl knobs.
417 	 */
418 	sc->dwelltime = 100;
419 	sc->bluetooth = 1;
420 	sc->antenna = 0;
421 
422 	SYSCTL_ADD_PROC(device_get_sysctl_ctx(dev),
423 	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO, "radio",
424 	    CTLTYPE_INT | CTLFLAG_RD, sc, 0, iwi_sysctl_radio, "I",
425 	    "radio transmitter switch state (0=off, 1=on)");
426 
427 	SYSCTL_ADD_PROC(device_get_sysctl_ctx(dev),
428 	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO, "stats",
429 	    CTLTYPE_OPAQUE | CTLFLAG_RD, sc, 0, iwi_sysctl_stats, "S",
430 	    "statistics");
431 
432 	SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
433 	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO, "dwell",
434 	    CTLFLAG_RW, &sc->dwelltime, 0,
435 	    "channel dwell time (ms) for AP/station scanning");
436 
437 	SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
438 	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO, "bluetooth",
439 	    CTLFLAG_RW, &sc->bluetooth, 0, "bluetooth coexistence");
440 
441 	SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
442 	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO, "antenna",
443 	    CTLFLAG_RW, &sc->antenna, 0, "antenna (0=auto)");
444 
445 	/*
446 	 * Hook our interrupt after all initialization is complete.
447 	 */
448 	error = bus_setup_intr(dev, sc->irq, INTR_TYPE_NET | INTR_MPSAFE,
449 	    iwi_intr, sc, &sc->sc_ih);
450 	if (error != 0) {
451 		device_printf(dev, "could not set up interrupt\n");
452 		goto fail;
453 	}
454 
455 	if (bootverbose)
456 		ieee80211_announce(ic);
457 
458 	return 0;
459 
460 fail:	iwi_detach(dev);
461 	return ENXIO;
462 }
463 
464 static int
465 iwi_detach(device_t dev)
466 {
467 	struct iwi_softc *sc = device_get_softc(dev);
468 	struct ieee80211com *ic = &sc->sc_ic;
469 	struct ifnet *ifp = ic->ic_ifp;
470 
471 	iwi_stop(sc);
472 
473 	iwi_free_firmware(sc);
474 
475 	if (ifp != NULL) {
476 		bpfdetach(ifp);
477 		ieee80211_ifdetach(ic);
478 	}
479 
480 	iwi_free_cmd_ring(sc, &sc->cmdq);
481 	iwi_free_tx_ring(sc, &sc->txq[0]);
482 	iwi_free_tx_ring(sc, &sc->txq[1]);
483 	iwi_free_tx_ring(sc, &sc->txq[2]);
484 	iwi_free_tx_ring(sc, &sc->txq[3]);
485 	iwi_free_rx_ring(sc, &sc->rxq);
486 
487 	if (sc->irq != NULL) {
488 		bus_teardown_intr(dev, sc->irq, sc->sc_ih);
489 		bus_release_resource(dev, SYS_RES_IRQ, sc->irq_rid, sc->irq);
490 	}
491 
492 	if (sc->mem != NULL)
493 		bus_release_resource(dev, SYS_RES_MEMORY, sc->mem_rid, sc->mem);
494 
495 	if (ifp != NULL)
496 		if_free(ifp);
497 
498 	if (sc->sc_unr != NULL)
499 		delete_unrhdr(sc->sc_unr);
500 
501 	mtx_destroy(&sc->sc_mtx);
502 
503 	return 0;
504 }
505 
506 static void
507 iwi_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
508 {
509 	if (error != 0)
510 		return;
511 
512 	KASSERT(nseg == 1, ("too many DMA segments, %d should be 1", nseg));
513 
514 	*(bus_addr_t *)arg = segs[0].ds_addr;
515 }
516 
517 static int
518 iwi_alloc_cmd_ring(struct iwi_softc *sc, struct iwi_cmd_ring *ring, int count)
519 {
520 	int error;
521 
522 	ring->count = count;
523 	ring->queued = 0;
524 	ring->cur = ring->next = 0;
525 
526 	error = bus_dma_tag_create(NULL, 4, 0, BUS_SPACE_MAXADDR_32BIT,
527 	    BUS_SPACE_MAXADDR, NULL, NULL, count * IWI_CMD_DESC_SIZE, 1,
528 	    count * IWI_CMD_DESC_SIZE, 0, NULL, NULL, &ring->desc_dmat);
529 	if (error != 0) {
530 		device_printf(sc->sc_dev, "could not create desc DMA tag\n");
531 		goto fail;
532 	}
533 
534 	error = bus_dmamem_alloc(ring->desc_dmat, (void **)&ring->desc,
535 	    BUS_DMA_NOWAIT | BUS_DMA_ZERO, &ring->desc_map);
536 	if (error != 0) {
537 		device_printf(sc->sc_dev, "could not allocate DMA memory\n");
538 		goto fail;
539 	}
540 
541 	error = bus_dmamap_load(ring->desc_dmat, ring->desc_map, ring->desc,
542 	    count * IWI_CMD_DESC_SIZE, iwi_dma_map_addr, &ring->physaddr, 0);
543 	if (error != 0) {
544 		device_printf(sc->sc_dev, "could not load desc DMA map\n");
545 		goto fail;
546 	}
547 
548 	return 0;
549 
550 fail:	iwi_free_cmd_ring(sc, ring);
551 	return error;
552 }
553 
554 static void
555 iwi_reset_cmd_ring(struct iwi_softc *sc, struct iwi_cmd_ring *ring)
556 {
557 	ring->queued = 0;
558 	ring->cur = ring->next = 0;
559 }
560 
561 static void
562 iwi_free_cmd_ring(struct iwi_softc *sc, struct iwi_cmd_ring *ring)
563 {
564 	if (ring->desc != NULL) {
565 		bus_dmamap_sync(ring->desc_dmat, ring->desc_map,
566 		    BUS_DMASYNC_POSTWRITE);
567 		bus_dmamap_unload(ring->desc_dmat, ring->desc_map);
568 		bus_dmamem_free(ring->desc_dmat, ring->desc, ring->desc_map);
569 	}
570 
571 	if (ring->desc_dmat != NULL)
572 		bus_dma_tag_destroy(ring->desc_dmat);
573 }
574 
575 static int
576 iwi_alloc_tx_ring(struct iwi_softc *sc, struct iwi_tx_ring *ring, int count,
577     bus_addr_t csr_ridx, bus_addr_t csr_widx)
578 {
579 	int i, error;
580 
581 	ring->count = count;
582 	ring->queued = 0;
583 	ring->cur = ring->next = 0;
584 	ring->csr_ridx = csr_ridx;
585 	ring->csr_widx = csr_widx;
586 
587 	error = bus_dma_tag_create(NULL, 4, 0, BUS_SPACE_MAXADDR_32BIT,
588 	    BUS_SPACE_MAXADDR, NULL, NULL, count * IWI_TX_DESC_SIZE, 1,
589 	    count * IWI_TX_DESC_SIZE, 0, NULL, NULL, &ring->desc_dmat);
590 	if (error != 0) {
591 		device_printf(sc->sc_dev, "could not create desc DMA tag\n");
592 		goto fail;
593 	}
594 
595 	error = bus_dmamem_alloc(ring->desc_dmat, (void **)&ring->desc,
596 	    BUS_DMA_NOWAIT | BUS_DMA_ZERO, &ring->desc_map);
597 	if (error != 0) {
598 		device_printf(sc->sc_dev, "could not allocate DMA memory\n");
599 		goto fail;
600 	}
601 
602 	error = bus_dmamap_load(ring->desc_dmat, ring->desc_map, ring->desc,
603 	    count * IWI_TX_DESC_SIZE, iwi_dma_map_addr, &ring->physaddr, 0);
604 	if (error != 0) {
605 		device_printf(sc->sc_dev, "could not load desc DMA map\n");
606 		goto fail;
607 	}
608 
609 	ring->data = malloc(count * sizeof (struct iwi_tx_data), M_DEVBUF,
610 	    M_NOWAIT | M_ZERO);
611 	if (ring->data == NULL) {
612 		device_printf(sc->sc_dev, "could not allocate soft data\n");
613 		error = ENOMEM;
614 		goto fail;
615 	}
616 
617 	error = bus_dma_tag_create(NULL, 1, 0, BUS_SPACE_MAXADDR_32BIT,
618 	    BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES, 1, MCLBYTES, 0, NULL,
619 	    NULL, &ring->data_dmat);
620 	if (error != 0) {
621 		device_printf(sc->sc_dev, "could not create data DMA tag\n");
622 		goto fail;
623 	}
624 
625 	for (i = 0; i < count; i++) {
626 		error = bus_dmamap_create(ring->data_dmat, 0,
627 		    &ring->data[i].map);
628 		if (error != 0) {
629 			device_printf(sc->sc_dev, "could not create DMA map\n");
630 			goto fail;
631 		}
632 	}
633 
634 	return 0;
635 
636 fail:	iwi_free_tx_ring(sc, ring);
637 	return error;
638 }
639 
640 static void
641 iwi_reset_tx_ring(struct iwi_softc *sc, struct iwi_tx_ring *ring)
642 {
643 	struct iwi_tx_data *data;
644 	int i;
645 
646 	for (i = 0; i < ring->count; i++) {
647 		data = &ring->data[i];
648 
649 		if (data->m != NULL) {
650 			bus_dmamap_sync(ring->data_dmat, data->map,
651 			    BUS_DMASYNC_POSTWRITE);
652 			bus_dmamap_unload(ring->data_dmat, data->map);
653 			m_freem(data->m);
654 			data->m = NULL;
655 		}
656 
657 		if (data->ni != NULL) {
658 			ieee80211_free_node(data->ni);
659 			data->ni = NULL;
660 		}
661 	}
662 
663 	ring->queued = 0;
664 	ring->cur = ring->next = 0;
665 }
666 
667 static void
668 iwi_free_tx_ring(struct iwi_softc *sc, struct iwi_tx_ring *ring)
669 {
670 	struct iwi_tx_data *data;
671 	int i;
672 
673 	if (ring->desc != NULL) {
674 		bus_dmamap_sync(ring->desc_dmat, ring->desc_map,
675 		    BUS_DMASYNC_POSTWRITE);
676 		bus_dmamap_unload(ring->desc_dmat, ring->desc_map);
677 		bus_dmamem_free(ring->desc_dmat, ring->desc, ring->desc_map);
678 	}
679 
680 	if (ring->desc_dmat != NULL)
681 		bus_dma_tag_destroy(ring->desc_dmat);
682 
683 	if (ring->data != NULL) {
684 		for (i = 0; i < ring->count; i++) {
685 			data = &ring->data[i];
686 
687 			if (data->m != NULL) {
688 				bus_dmamap_sync(ring->data_dmat, data->map,
689 				    BUS_DMASYNC_POSTWRITE);
690 				bus_dmamap_unload(ring->data_dmat, data->map);
691 				m_freem(data->m);
692 			}
693 
694 			if (data->ni != NULL)
695 				ieee80211_free_node(data->ni);
696 
697 			if (data->map != NULL)
698 				bus_dmamap_destroy(ring->data_dmat, data->map);
699 		}
700 
701 		free(ring->data, M_DEVBUF);
702 	}
703 
704 	if (ring->data_dmat != NULL)
705 		bus_dma_tag_destroy(ring->data_dmat);
706 }
707 
708 static int
709 iwi_alloc_rx_ring(struct iwi_softc *sc, struct iwi_rx_ring *ring, int count)
710 {
711 	struct iwi_rx_data *data;
712 	int i, error;
713 
714 	ring->count = count;
715 	ring->cur = 0;
716 
717 	ring->data = malloc(count * sizeof (struct iwi_rx_data), M_DEVBUF,
718 	    M_NOWAIT | M_ZERO);
719 	if (ring->data == NULL) {
720 		device_printf(sc->sc_dev, "could not allocate soft data\n");
721 		error = ENOMEM;
722 		goto fail;
723 	}
724 
725 	error = bus_dma_tag_create(NULL, 1, 0, BUS_SPACE_MAXADDR_32BIT,
726 	    BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES, 1, MCLBYTES, 0, NULL,
727 	    NULL, &ring->data_dmat);
728 	if (error != 0) {
729 		device_printf(sc->sc_dev, "could not create data DMA tag\n");
730 		goto fail;
731 	}
732 
733 	for (i = 0; i < count; i++) {
734 		data = &ring->data[i];
735 
736 		error = bus_dmamap_create(ring->data_dmat, 0, &data->map);
737 		if (error != 0) {
738 			device_printf(sc->sc_dev, "could not create DMA map\n");
739 			goto fail;
740 		}
741 
742 		data->m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
743 		if (data->m == NULL) {
744 			device_printf(sc->sc_dev,
745 			    "could not allocate rx mbuf\n");
746 			error = ENOMEM;
747 			goto fail;
748 		}
749 
750 		error = bus_dmamap_load(ring->data_dmat, data->map,
751 		    mtod(data->m, void *), MCLBYTES, iwi_dma_map_addr,
752 		    &data->physaddr, 0);
753 		if (error != 0) {
754 			device_printf(sc->sc_dev,
755 			    "could not load rx buf DMA map");
756 			goto fail;
757 		}
758 
759 		data->reg = IWI_CSR_RX_BASE + i * 4;
760 	}
761 
762 	return 0;
763 
764 fail:	iwi_free_rx_ring(sc, ring);
765 	return error;
766 }
767 
768 static void
769 iwi_reset_rx_ring(struct iwi_softc *sc, struct iwi_rx_ring *ring)
770 {
771 	ring->cur = 0;
772 }
773 
774 static void
775 iwi_free_rx_ring(struct iwi_softc *sc, struct iwi_rx_ring *ring)
776 {
777 	struct iwi_rx_data *data;
778 	int i;
779 
780 	if (ring->data != NULL) {
781 		for (i = 0; i < ring->count; i++) {
782 			data = &ring->data[i];
783 
784 			if (data->m != NULL) {
785 				bus_dmamap_sync(ring->data_dmat, data->map,
786 				    BUS_DMASYNC_POSTREAD);
787 				bus_dmamap_unload(ring->data_dmat, data->map);
788 				m_freem(data->m);
789 			}
790 
791 			if (data->map != NULL)
792 				bus_dmamap_destroy(ring->data_dmat, data->map);
793 		}
794 
795 		free(ring->data, M_DEVBUF);
796 	}
797 
798 	if (ring->data_dmat != NULL)
799 		bus_dma_tag_destroy(ring->data_dmat);
800 }
801 
802 static int
803 iwi_shutdown(device_t dev)
804 {
805 	struct iwi_softc *sc = device_get_softc(dev);
806 
807 	iwi_stop(sc);
808 
809 	return 0;
810 }
811 
812 static int
813 iwi_suspend(device_t dev)
814 {
815 	struct iwi_softc *sc = device_get_softc(dev);
816 
817 	iwi_stop(sc);
818 
819 	return 0;
820 }
821 
822 static int
823 iwi_resume(device_t dev)
824 {
825 	struct iwi_softc *sc = device_get_softc(dev);
826 	struct ifnet *ifp = sc->sc_ic.ic_ifp;
827 
828 	IWI_LOCK(sc);
829 
830 	pci_write_config(dev, 0x41, 0, 1);
831 
832 	if (ifp->if_flags & IFF_UP) {
833 		ifp->if_init(ifp->if_softc);
834 		if (ifp->if_drv_flags & IFF_DRV_RUNNING)
835 			ifp->if_start(ifp);
836 	}
837 
838 	IWI_UNLOCK(sc);
839 
840 	return 0;
841 }
842 
843 static struct ieee80211_node *
844 iwi_node_alloc(struct ieee80211_node_table *nt)
845 {
846 	struct iwi_node *in;
847 
848 	in = malloc(sizeof (struct iwi_node), M_80211_NODE, M_NOWAIT | M_ZERO);
849 	if (in == NULL)
850 		return NULL;
851 
852 	in->in_station = -1;
853 
854 	return &in->in_node;
855 }
856 
857 static void
858 iwi_node_free(struct ieee80211_node *ni)
859 {
860 	struct ieee80211com *ic = ni->ni_ic;
861 	struct iwi_softc *sc = ic->ic_ifp->if_softc;
862 	struct iwi_node *in = (struct iwi_node *)ni;
863 
864 	if (in->in_station != -1)
865 		free_unr(sc->sc_unr, in->in_station);
866 
867 	sc->sc_node_free(ni);
868 }
869 
870 static int
871 iwi_media_change(struct ifnet *ifp)
872 {
873 	struct iwi_softc *sc = ifp->if_softc;
874 	int error;
875 
876 	IWI_LOCK(sc);
877 
878 	error = ieee80211_media_change(ifp);
879 	if (error != ENETRESET) {
880 		IWI_UNLOCK(sc);
881 		return error;
882 	}
883 
884 	if ((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags & IFF_DRV_RUNNING))
885 		iwi_init(sc);
886 
887 	IWI_UNLOCK(sc);
888 
889 	return 0;
890 }
891 
892 /*
893  * The firmware automatically adapts the transmit speed.  We report its current
894  * value here.
895  */
896 static void
897 iwi_media_status(struct ifnet *ifp, struct ifmediareq *imr)
898 {
899 	struct iwi_softc *sc = ifp->if_softc;
900 	struct ieee80211com *ic = &sc->sc_ic;
901 #define N(a)	(sizeof (a) / sizeof (a[0]))
902 	static const struct {
903 		uint32_t	val;
904 		int		rate;
905 	} rates[] = {
906 		{ IWI_RATE_DS1,      2 },
907 		{ IWI_RATE_DS2,      4 },
908 		{ IWI_RATE_DS5,     11 },
909 		{ IWI_RATE_DS11,    22 },
910 		{ IWI_RATE_OFDM6,   12 },
911 		{ IWI_RATE_OFDM9,   18 },
912 		{ IWI_RATE_OFDM12,  24 },
913 		{ IWI_RATE_OFDM18,  36 },
914 		{ IWI_RATE_OFDM24,  48 },
915 		{ IWI_RATE_OFDM36,  72 },
916 		{ IWI_RATE_OFDM48,  96 },
917 		{ IWI_RATE_OFDM54, 108 },
918 	};
919 	uint32_t val;
920 	int rate, i;
921 
922 	imr->ifm_status = IFM_AVALID;
923 	imr->ifm_active = IFM_IEEE80211;
924 	if (ic->ic_state == IEEE80211_S_RUN)
925 		imr->ifm_status |= IFM_ACTIVE;
926 
927 	/* read current transmission rate from adapter */
928 	val = CSR_READ_4(sc, IWI_CSR_CURRENT_TX_RATE);
929 
930 	/* convert rate to 802.11 rate */
931 	for (i = 0; i < N(rates) && rates[i].val != val; i++);
932 	rate = (i < N(rates)) ? rates[i].rate : 0;
933 
934 	imr->ifm_active |= ieee80211_rate2media(ic, rate, ic->ic_curmode);
935 	switch (ic->ic_opmode) {
936 	case IEEE80211_M_STA:
937 		break;
938 
939 	case IEEE80211_M_IBSS:
940 		imr->ifm_active |= IFM_IEEE80211_ADHOC;
941 		break;
942 
943 	case IEEE80211_M_MONITOR:
944 		imr->ifm_active |= IFM_IEEE80211_MONITOR;
945 		break;
946 
947 	case IEEE80211_M_AHDEMO:
948 	case IEEE80211_M_HOSTAP:
949 		/* should not get there */
950 		break;
951 	}
952 #undef N
953 }
954 
955 static int
956 iwi_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
957 {
958 	struct ifnet *ifp = ic->ic_ifp;
959 	struct iwi_softc *sc = ifp->if_softc;
960 
961 	switch (nstate) {
962 	case IEEE80211_S_SCAN:
963 		if (sc->flags & IWI_FLAG_SCANNING)
964 			break;
965 
966 		ieee80211_node_table_reset(&ic->ic_scan);
967 		ic->ic_flags |= IEEE80211_F_SCAN | IEEE80211_F_ASCAN;
968 		sc->flags |= IWI_FLAG_SCANNING;
969 		iwi_scan(sc);
970 		break;
971 
972 	case IEEE80211_S_AUTH:
973 		iwi_auth_and_assoc(sc);
974 		break;
975 
976 	case IEEE80211_S_RUN:
977 		if (ic->ic_opmode == IEEE80211_M_IBSS)
978 			ieee80211_new_state(ic, IEEE80211_S_AUTH, -1);
979 		else if (ic->ic_opmode == IEEE80211_M_MONITOR)
980 			iwi_set_chan(sc, ic->ic_ibss_chan);
981 
982 		return sc->sc_newstate(ic, nstate,
983 		    IEEE80211_FC0_SUBTYPE_ASSOC_RESP);
984 
985 	case IEEE80211_S_ASSOC:
986 		break;
987 
988 	case IEEE80211_S_INIT:
989 		sc->flags &= ~IWI_FLAG_SCANNING;
990 		break;
991 	}
992 
993 	ic->ic_state = nstate;
994 	return 0;
995 }
996 
997 /*
998  * WME parameters coming from IEEE 802.11e specification.  These values are
999  * already declared in ieee80211_proto.c, but they are static so they can't
1000  * be reused here.
1001  */
1002 static const struct wmeParams iwi_wme_cck_params[WME_NUM_AC] = {
1003 	{ 0, 3, 5,  7,   0 },	/* WME_AC_BE */
1004 	{ 0, 3, 5, 10,   0 },	/* WME_AC_BK */
1005 	{ 0, 2, 4,  5, 188 },	/* WME_AC_VI */
1006 	{ 0, 2, 3,  4, 102 }	/* WME_AC_VO */
1007 };
1008 
1009 static const struct wmeParams iwi_wme_ofdm_params[WME_NUM_AC] = {
1010 	{ 0, 3, 4,  6,   0 },	/* WME_AC_BE */
1011 	{ 0, 3, 4, 10,   0 },	/* WME_AC_BK */
1012 	{ 0, 2, 3,  4,  94 },	/* WME_AC_VI */
1013 	{ 0, 2, 2,  3,  47 }	/* WME_AC_VO */
1014 };
1015 
1016 static int
1017 iwi_wme_update(struct ieee80211com *ic)
1018 {
1019 #define IWI_EXP2(v)	htole16((1 << (v)) - 1)
1020 #define IWI_USEC(v)	htole16(IEEE80211_TXOP_TO_US(v))
1021 	struct iwi_softc *sc = ic->ic_ifp->if_softc;
1022 	struct iwi_wme_params wme[3];
1023 	const struct wmeParams *wmep;
1024 	int ac;
1025 
1026 	/*
1027 	 * We shall not override firmware default WME values if WME is not
1028 	 * actually enabled.
1029 	 */
1030 	if (!(ic->ic_flags & IEEE80211_F_WME))
1031 		return 0;
1032 
1033 	for (ac = 0; ac < WME_NUM_AC; ac++) {
1034 		/* set WME values for current operating mode */
1035 		wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
1036 		wme[0].aifsn[ac] = wmep->wmep_aifsn;
1037 		wme[0].cwmin[ac] = IWI_EXP2(wmep->wmep_logcwmin);
1038 		wme[0].cwmax[ac] = IWI_EXP2(wmep->wmep_logcwmax);
1039 		wme[0].burst[ac] = IWI_USEC(wmep->wmep_txopLimit);
1040 		wme[0].acm[ac]   = wmep->wmep_acm;
1041 
1042 		/* set WME values for CCK modulation */
1043 		wmep = &iwi_wme_cck_params[ac];
1044 		wme[1].aifsn[ac] = wmep->wmep_aifsn;
1045 		wme[1].cwmin[ac] = IWI_EXP2(wmep->wmep_logcwmin);
1046 		wme[1].cwmax[ac] = IWI_EXP2(wmep->wmep_logcwmax);
1047 		wme[1].burst[ac] = IWI_USEC(wmep->wmep_txopLimit);
1048 		wme[1].acm[ac]   = wmep->wmep_acm;
1049 
1050 		/* set WME values for OFDM modulation */
1051 		wmep = &iwi_wme_ofdm_params[ac];
1052 		wme[2].aifsn[ac] = wmep->wmep_aifsn;
1053 		wme[2].cwmin[ac] = IWI_EXP2(wmep->wmep_logcwmin);
1054 		wme[2].cwmax[ac] = IWI_EXP2(wmep->wmep_logcwmax);
1055 		wme[2].burst[ac] = IWI_USEC(wmep->wmep_txopLimit);
1056 		wme[2].acm[ac]   = wmep->wmep_acm;
1057 	}
1058 
1059 	DPRINTF(("Setting WME parameters\n"));
1060 	return iwi_cmd(sc, IWI_CMD_SET_WME_PARAMS, wme, sizeof wme, 1);
1061 #undef IWI_USEC
1062 #undef IWI_EXP2
1063 }
1064 
1065 /*
1066  * Read 16 bits at address 'addr' from the serial EEPROM.
1067  */
1068 static uint16_t
1069 iwi_read_prom_word(struct iwi_softc *sc, uint8_t addr)
1070 {
1071 	uint32_t tmp;
1072 	uint16_t val;
1073 	int n;
1074 
1075 	/* clock C once before the first command */
1076 	IWI_EEPROM_CTL(sc, 0);
1077 	IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1078 	IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_C);
1079 	IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1080 
1081 	/* write start bit (1) */
1082 	IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_D);
1083 	IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_D | IWI_EEPROM_C);
1084 
1085 	/* write READ opcode (10) */
1086 	IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_D);
1087 	IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_D | IWI_EEPROM_C);
1088 	IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1089 	IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_C);
1090 
1091 	/* write address A7-A0 */
1092 	for (n = 7; n >= 0; n--) {
1093 		IWI_EEPROM_CTL(sc, IWI_EEPROM_S |
1094 		    (((addr >> n) & 1) << IWI_EEPROM_SHIFT_D));
1095 		IWI_EEPROM_CTL(sc, IWI_EEPROM_S |
1096 		    (((addr >> n) & 1) << IWI_EEPROM_SHIFT_D) | IWI_EEPROM_C);
1097 	}
1098 
1099 	IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1100 
1101 	/* read data Q15-Q0 */
1102 	val = 0;
1103 	for (n = 15; n >= 0; n--) {
1104 		IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_C);
1105 		IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1106 		tmp = MEM_READ_4(sc, IWI_MEM_EEPROM_CTL);
1107 		val |= ((tmp & IWI_EEPROM_Q) >> IWI_EEPROM_SHIFT_Q) << n;
1108 	}
1109 
1110 	IWI_EEPROM_CTL(sc, 0);
1111 
1112 	/* clear Chip Select and clock C */
1113 	IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1114 	IWI_EEPROM_CTL(sc, 0);
1115 	IWI_EEPROM_CTL(sc, IWI_EEPROM_C);
1116 
1117 	return be16toh(val);
1118 }
1119 
1120 /*
1121  * XXX: Hack to set the current channel to the value advertised in beacons or
1122  * probe responses. Only used during AP detection.
1123  */
1124 static void
1125 iwi_fix_channel(struct ieee80211com *ic, struct mbuf *m)
1126 {
1127 	struct ieee80211_frame *wh;
1128 	uint8_t subtype;
1129 	uint8_t *frm, *efrm;
1130 
1131 	wh = mtod(m, struct ieee80211_frame *);
1132 
1133 	if ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) != IEEE80211_FC0_TYPE_MGT)
1134 		return;
1135 
1136 	subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
1137 
1138 	if (subtype != IEEE80211_FC0_SUBTYPE_BEACON &&
1139 	    subtype != IEEE80211_FC0_SUBTYPE_PROBE_RESP)
1140 		return;
1141 
1142 	frm = (uint8_t *)(wh + 1);
1143 	efrm = mtod(m, uint8_t *) + m->m_len;
1144 
1145 	frm += 12;	/* skip tstamp, bintval and capinfo fields */
1146 	while (frm < efrm) {
1147 		if (*frm == IEEE80211_ELEMID_DSPARMS)
1148 #if IEEE80211_CHAN_MAX < 255
1149 		if (frm[2] <= IEEE80211_CHAN_MAX)
1150 #endif
1151 			ic->ic_curchan = &ic->ic_channels[frm[2]];
1152 
1153 		frm += frm[1] + 2;
1154 	}
1155 }
1156 
1157 static void
1158 iwi_frame_intr(struct iwi_softc *sc, struct iwi_rx_data *data, int i,
1159     struct iwi_frame *frame)
1160 {
1161 	struct ieee80211com *ic = &sc->sc_ic;
1162 	struct ifnet *ifp = ic->ic_ifp;
1163 	struct mbuf *m;
1164 	struct ieee80211_frame *wh;
1165 	struct ieee80211_node *ni;
1166 	int error;
1167 
1168 	DPRINTFN(5, ("received frame len=%u chan=%u rssi=%u\n",
1169 	    le16toh(frame->len), frame->chan, frame->rssi_dbm));
1170 
1171 	if (le16toh(frame->len) < sizeof (struct ieee80211_frame))
1172 		return;
1173 
1174 	bus_dmamap_unload(sc->rxq.data_dmat, data->map);
1175 
1176 	/* finalize mbuf */
1177 	m = data->m;
1178 	m->m_pkthdr.rcvif = ifp;
1179 	m->m_pkthdr.len = m->m_len = sizeof (struct iwi_hdr) +
1180 	    sizeof (struct iwi_frame) + le16toh(frame->len);
1181 
1182 	m_adj(m, sizeof (struct iwi_hdr) + sizeof (struct iwi_frame));
1183 
1184 	if (ic->ic_state == IEEE80211_S_SCAN)
1185 		iwi_fix_channel(ic, m);
1186 
1187 	if (sc->sc_drvbpf != NULL) {
1188 		struct iwi_rx_radiotap_header *tap = &sc->sc_rxtap;
1189 
1190 		tap->wr_flags = 0;
1191 		tap->wr_rate = frame->rate;
1192 		tap->wr_chan_freq =
1193 		    htole16(ic->ic_channels[frame->chan].ic_freq);
1194 		tap->wr_chan_flags =
1195 		    htole16(ic->ic_channels[frame->chan].ic_flags);
1196 		tap->wr_antsignal = frame->signal;
1197 		tap->wr_antenna = frame->antenna;
1198 
1199 		bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_rxtap_len, m);
1200 	}
1201 
1202 	wh = mtod(m, struct ieee80211_frame *);
1203 	ni = ieee80211_find_rxnode(ic, (struct ieee80211_frame_min *)wh);
1204 
1205 	/* send the frame to the 802.11 layer */
1206 	ieee80211_input(ic, m, ni, frame->rssi_dbm, 0);
1207 
1208 	/* node is no longer needed */
1209 	ieee80211_free_node(ni);
1210 
1211 	data->m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
1212 	if (data->m == NULL) {
1213 		device_printf(sc->sc_dev, "could not allocate rx mbuf\n");
1214 		return;
1215 	}
1216 
1217 	error = bus_dmamap_load(sc->rxq.data_dmat, data->map,
1218 	    mtod(data->m, void *), MCLBYTES, iwi_dma_map_addr, &data->physaddr,
1219 	    0);
1220 	if (error != 0) {
1221 		device_printf(sc->sc_dev, "could not load rx buf DMA map\n");
1222 		m_freem(data->m);
1223 		data->m = NULL;
1224 		return;
1225 	}
1226 
1227 	CSR_WRITE_4(sc, data->reg, data->physaddr);
1228 }
1229 
1230 static void
1231 iwi_notification_intr(struct iwi_softc *sc, struct iwi_notif *notif)
1232 {
1233 	struct ieee80211com *ic = &sc->sc_ic;
1234 	struct iwi_notif_scan_channel *chan;
1235 	struct iwi_notif_scan_complete *scan;
1236 	struct iwi_notif_authentication *auth;
1237 	struct iwi_notif_association *assoc;
1238 
1239 	switch (notif->type) {
1240 	case IWI_NOTIF_TYPE_SCAN_CHANNEL:
1241 		chan = (struct iwi_notif_scan_channel *)(notif + 1);
1242 
1243 		DPRINTFN(2, ("Scanning channel (%u)\n", chan->nchan));
1244 		break;
1245 
1246 	case IWI_NOTIF_TYPE_SCAN_COMPLETE:
1247 		scan = (struct iwi_notif_scan_complete *)(notif + 1);
1248 
1249 		DPRINTFN(2, ("Scan completed (%u, %u)\n", scan->nchan,
1250 		    scan->status));
1251 
1252 		/* monitor mode uses scan to set the channel ... */
1253 		if (ic->ic_opmode != IEEE80211_M_MONITOR) {
1254 			sc->flags &= ~IWI_FLAG_SCANNING;
1255 			ieee80211_end_scan(ic);
1256 		} else
1257 			iwi_set_chan(sc, ic->ic_ibss_chan);
1258 		break;
1259 
1260 	case IWI_NOTIF_TYPE_AUTHENTICATION:
1261 		auth = (struct iwi_notif_authentication *)(notif + 1);
1262 
1263 		DPRINTFN(2, ("Authentication (%u)\n", auth->state));
1264 
1265 		switch (auth->state) {
1266 		case IWI_AUTHENTICATED:
1267 			ieee80211_node_authorize(ic->ic_bss);
1268 			ieee80211_new_state(ic, IEEE80211_S_ASSOC, -1);
1269 			break;
1270 
1271 		case IWI_DEAUTHENTICATED:
1272 			break;
1273 
1274 		default:
1275 			device_printf(sc->sc_dev,
1276 			    "unknown authentication state %u\n", auth->state);
1277 		}
1278 		break;
1279 
1280 	case IWI_NOTIF_TYPE_ASSOCIATION:
1281 		assoc = (struct iwi_notif_association *)(notif + 1);
1282 
1283 		DPRINTFN(2, ("Association (%u, %u)\n", assoc->state,
1284 		    assoc->status));
1285 
1286 		switch (assoc->state) {
1287 		case IWI_AUTHENTICATED:
1288 			/* re-association, do nothing */
1289 			break;
1290 
1291 		case IWI_ASSOCIATED:
1292 			ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
1293 			break;
1294 
1295 		case IWI_DEASSOCIATED:
1296 			ieee80211_begin_scan(ic, 1);
1297 			break;
1298 
1299 		default:
1300 			device_printf(sc->sc_dev,
1301 			    "unknown association state %u\n", assoc->state);
1302 		}
1303 		break;
1304 
1305 	case IWI_NOTIF_TYPE_CALIBRATION:
1306 	case IWI_NOTIF_TYPE_BEACON:
1307 	case IWI_NOTIF_TYPE_NOISE:
1308 		DPRINTFN(5, ("Notification (%u)\n", notif->type));
1309 		break;
1310 
1311 	default:
1312 		device_printf(sc->sc_dev, "unknown notification type %u\n",
1313 		    notif->type);
1314 	}
1315 }
1316 
1317 static void
1318 iwi_rx_intr(struct iwi_softc *sc)
1319 {
1320 	struct iwi_rx_data *data;
1321 	struct iwi_hdr *hdr;
1322 	uint32_t hw;
1323 
1324 	hw = CSR_READ_4(sc, IWI_CSR_RX_RIDX);
1325 
1326 	for (; sc->rxq.cur != hw;) {
1327 		data = &sc->rxq.data[sc->rxq.cur];
1328 
1329 		bus_dmamap_sync(sc->rxq.data_dmat, data->map,
1330 		    BUS_DMASYNC_POSTREAD);
1331 
1332 		hdr = mtod(data->m, struct iwi_hdr *);
1333 
1334 		switch (hdr->type) {
1335 		case IWI_HDR_TYPE_FRAME:
1336 			iwi_frame_intr(sc, data, sc->rxq.cur,
1337 			    (struct iwi_frame *)(hdr + 1));
1338 			break;
1339 
1340 		case IWI_HDR_TYPE_NOTIF:
1341 			iwi_notification_intr(sc,
1342 			    (struct iwi_notif *)(hdr + 1));
1343 			break;
1344 
1345 		default:
1346 			device_printf(sc->sc_dev, "unknown hdr type %u\n",
1347 			    hdr->type);
1348 		}
1349 
1350 		DPRINTFN(15, ("rx done idx=%u\n", sc->rxq.cur));
1351 
1352 		sc->rxq.cur = (sc->rxq.cur + 1) % IWI_RX_RING_COUNT;
1353 	}
1354 
1355 	/* tell the firmware what we have processed */
1356 	hw = (hw == 0) ? IWI_RX_RING_COUNT - 1 : hw - 1;
1357 	CSR_WRITE_4(sc, IWI_CSR_RX_WIDX, hw);
1358 }
1359 
1360 static void
1361 iwi_tx_intr(struct iwi_softc *sc, struct iwi_tx_ring *txq)
1362 {
1363 	struct ieee80211com *ic = &sc->sc_ic;
1364 	struct ifnet *ifp = ic->ic_ifp;
1365 	struct iwi_tx_data *data;
1366 	uint32_t hw;
1367 
1368 	hw = CSR_READ_4(sc, txq->csr_ridx);
1369 
1370 	for (; txq->next != hw;) {
1371 		data = &txq->data[txq->next];
1372 
1373 		bus_dmamap_sync(txq->data_dmat, data->map,
1374 		    BUS_DMASYNC_POSTWRITE);
1375 		bus_dmamap_unload(txq->data_dmat, data->map);
1376 		m_freem(data->m);
1377 		data->m = NULL;
1378 		ieee80211_free_node(data->ni);
1379 		data->ni = NULL;
1380 
1381 		DPRINTFN(15, ("tx done idx=%u\n", txq->next));
1382 
1383 		ifp->if_opackets++;
1384 
1385 		txq->queued--;
1386 		txq->next = (txq->next + 1) % IWI_TX_RING_COUNT;
1387 	}
1388 
1389 	sc->sc_tx_timer = 0;
1390 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1391 	iwi_start(ifp);
1392 }
1393 
1394 static void
1395 iwi_intr(void *arg)
1396 {
1397 	struct iwi_softc *sc = arg;
1398 	uint32_t r;
1399 
1400 	IWI_LOCK(sc);
1401 
1402 	if ((r = CSR_READ_4(sc, IWI_CSR_INTR)) == 0 || r == 0xffffffff) {
1403 		IWI_UNLOCK(sc);
1404 		return;
1405 	}
1406 
1407 	/* disable interrupts */
1408 	CSR_WRITE_4(sc, IWI_CSR_INTR_MASK, 0);
1409 
1410 	if (r & (IWI_INTR_FATAL_ERROR | IWI_INTR_PARITY_ERROR)) {
1411 		device_printf(sc->sc_dev, "fatal error\n");
1412 		sc->sc_ic.ic_ifp->if_flags &= ~IFF_UP;
1413 		iwi_stop(sc);
1414 	}
1415 
1416 	if (r & IWI_INTR_FW_INITED) {
1417 		if (!(r & (IWI_INTR_FATAL_ERROR | IWI_INTR_PARITY_ERROR)))
1418 			wakeup(sc);
1419 	}
1420 
1421 	if (r & IWI_INTR_RADIO_OFF) {
1422 		DPRINTF(("radio transmitter turned off\n"));
1423 		sc->sc_ic.ic_ifp->if_flags &= ~IFF_UP;
1424 		iwi_stop(sc);
1425 	}
1426 
1427 	if (r & IWI_INTR_CMD_DONE)
1428 		wakeup(sc);
1429 
1430 	if (r & IWI_INTR_TX1_DONE)
1431 		iwi_tx_intr(sc, &sc->txq[0]);
1432 
1433 	if (r & IWI_INTR_TX2_DONE)
1434 		iwi_tx_intr(sc, &sc->txq[1]);
1435 
1436 	if (r & IWI_INTR_TX3_DONE)
1437 		iwi_tx_intr(sc, &sc->txq[2]);
1438 
1439 	if (r & IWI_INTR_TX4_DONE)
1440 		iwi_tx_intr(sc, &sc->txq[3]);
1441 
1442 	if (r & IWI_INTR_RX_DONE)
1443 		iwi_rx_intr(sc);
1444 
1445 	/* acknowledge interrupts */
1446 	CSR_WRITE_4(sc, IWI_CSR_INTR, r);
1447 
1448 	/* re-enable interrupts */
1449 	CSR_WRITE_4(sc, IWI_CSR_INTR_MASK, IWI_INTR_MASK);
1450 
1451 	IWI_UNLOCK(sc);
1452 }
1453 
1454 static int
1455 iwi_cmd(struct iwi_softc *sc, uint8_t type, void *data, uint8_t len, int async)
1456 {
1457 	struct iwi_cmd_desc *desc;
1458 
1459 	desc = &sc->cmdq.desc[sc->cmdq.cur];
1460 
1461 	desc->hdr.type = IWI_HDR_TYPE_COMMAND;
1462 	desc->hdr.flags = IWI_HDR_FLAG_IRQ;
1463 	desc->type = type;
1464 	desc->len = len;
1465 	memcpy(desc->data, data, len);
1466 
1467 	bus_dmamap_sync(sc->cmdq.desc_dmat, sc->cmdq.desc_map,
1468 	    BUS_DMASYNC_PREWRITE);
1469 
1470 	DPRINTFN(2, ("sending command idx=%u type=%u len=%u\n", sc->cmdq.cur,
1471 	    type, len));
1472 
1473 	sc->cmdq.cur = (sc->cmdq.cur + 1) % IWI_CMD_RING_COUNT;
1474 	CSR_WRITE_4(sc, IWI_CSR_CMD_WIDX, sc->cmdq.cur);
1475 
1476 	return async ? 0 : msleep(sc, &sc->sc_mtx, 0, "iwicmd", hz);
1477 }
1478 
1479 static void
1480 iwi_write_ibssnode(struct iwi_softc *sc, const struct iwi_node *in)
1481 {
1482 	struct iwi_ibssnode node;
1483 
1484 	/* write node information into NIC memory */
1485 	memset(&node, 0, sizeof node);
1486 	IEEE80211_ADDR_COPY(node.bssid, in->in_node.ni_macaddr);
1487 
1488 	CSR_WRITE_REGION_1(sc,
1489 	    IWI_CSR_NODE_BASE + in->in_station * sizeof node,
1490 	    (uint8_t *)&node, sizeof node);
1491 }
1492 
1493 static int
1494 iwi_tx_start(struct ifnet *ifp, struct mbuf *m0, struct ieee80211_node *ni,
1495     int ac)
1496 {
1497 	struct iwi_softc *sc = ifp->if_softc;
1498 	struct ieee80211com *ic = &sc->sc_ic;
1499 	struct iwi_node *in = (struct iwi_node *)ni;
1500 	struct ieee80211_frame *wh;
1501 	struct ieee80211_key *k;
1502 	const struct chanAccParams *cap;
1503 	struct iwi_tx_ring *txq = &sc->txq[ac];
1504 	struct iwi_tx_data *data;
1505 	struct iwi_tx_desc *desc;
1506 	struct mbuf *mnew;
1507 	bus_dma_segment_t segs[IWI_MAX_NSEG];
1508 	int error, nsegs, hdrlen, i, noack = 0;
1509 
1510 	wh = mtod(m0, struct ieee80211_frame *);
1511 
1512 	if (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_QOS) {
1513 		hdrlen = sizeof (struct ieee80211_qosframe);
1514 		cap = &ic->ic_wme.wme_chanParams;
1515 		noack = cap->cap_wmeParams[ac].wmep_noackPolicy;
1516 	} else
1517 		hdrlen = sizeof (struct ieee80211_frame);
1518 
1519 	/*
1520 	 * This is only used in IBSS mode where the firmware expect an index
1521 	 * in a h/w table instead of a destination address.
1522 	 */
1523 	if (ic->ic_opmode == IEEE80211_M_IBSS && in->in_station == -1) {
1524 		in->in_station = alloc_unr(sc->sc_unr);
1525 		if (in->in_station == -1) {	/* h/w table is full */
1526 			m_freem(m0);
1527 			ieee80211_free_node(ni);
1528 			ifp->if_oerrors++;
1529 			return 0;
1530 		}
1531 		iwi_write_ibssnode(sc, in);
1532 	}
1533 
1534 	if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1535 		k = ieee80211_crypto_encap(ic, ni, m0);
1536 		if (k == NULL) {
1537 			m_freem(m0);
1538 			return ENOBUFS;
1539 		}
1540 
1541 		/* packet header may have moved, reset our local pointer */
1542 		wh = mtod(m0, struct ieee80211_frame *);
1543 	}
1544 
1545 	if (sc->sc_drvbpf != NULL) {
1546 		struct iwi_tx_radiotap_header *tap = &sc->sc_txtap;
1547 
1548 		tap->wt_flags = 0;
1549 		tap->wt_chan_freq = htole16(ic->ic_ibss_chan->ic_freq);
1550 		tap->wt_chan_flags = htole16(ic->ic_ibss_chan->ic_flags);
1551 
1552 		bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_txtap_len, m0);
1553 	}
1554 
1555 	data = &txq->data[txq->cur];
1556 	desc = &txq->desc[txq->cur];
1557 
1558 	/* save and trim IEEE802.11 header */
1559 	m_copydata(m0, 0, hdrlen, (caddr_t)&desc->wh);
1560 	m_adj(m0, hdrlen);
1561 
1562 	error = bus_dmamap_load_mbuf_sg(txq->data_dmat, data->map, m0, segs,
1563 	    &nsegs, 0);
1564 	if (error != 0 && error != EFBIG) {
1565 		device_printf(sc->sc_dev, "could not map mbuf (error %d)\n",
1566 		    error);
1567 		m_freem(m0);
1568 		return error;
1569 	}
1570 	if (error != 0) {
1571 		mnew = m_defrag(m0, M_DONTWAIT);
1572 		if (mnew == NULL) {
1573 			device_printf(sc->sc_dev,
1574 			    "could not defragment mbuf\n");
1575 			m_freem(m0);
1576 			return ENOBUFS;
1577 		}
1578 		m0 = mnew;
1579 
1580 		error = bus_dmamap_load_mbuf_sg(txq->data_dmat, data->map,
1581 		    m0, segs, &nsegs, 0);
1582 		if (error != 0) {
1583 			device_printf(sc->sc_dev,
1584 			    "could not map mbuf (error %d)\n", error);
1585 			m_freem(m0);
1586 			return error;
1587 		}
1588 	}
1589 
1590 	data->m = m0;
1591 	data->ni = ni;
1592 
1593 	desc->hdr.type = IWI_HDR_TYPE_DATA;
1594 	desc->hdr.flags = IWI_HDR_FLAG_IRQ;
1595 	desc->station =
1596 	    (ic->ic_opmode == IEEE80211_M_IBSS) ? in->in_station : 0;
1597 	desc->cmd = IWI_DATA_CMD_TX;
1598 	desc->len = htole16(m0->m_pkthdr.len);
1599 	desc->flags = 0;
1600 	desc->xflags = 0;
1601 
1602 	if (!noack && !IEEE80211_IS_MULTICAST(desc->wh.i_addr1))
1603 		desc->flags |= IWI_DATA_FLAG_NEED_ACK;
1604 
1605 #if 0
1606 	if (ic->ic_flags & IEEE80211_F_PRIVACY) {
1607 		desc->wh.i_fc[1] |= IEEE80211_FC1_WEP;
1608 		desc->wep_txkey = ic->ic_crypto.cs_def_txkey;
1609 	} else
1610 #endif
1611 		desc->flags |= IWI_DATA_FLAG_NO_WEP;
1612 
1613 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
1614 		desc->flags |= IWI_DATA_FLAG_SHPREAMBLE;
1615 
1616 	if (desc->wh.i_fc[0] & IEEE80211_FC0_SUBTYPE_QOS)
1617 		desc->xflags |= IWI_DATA_XFLAG_QOS;
1618 
1619 	desc->nseg = htole32(nsegs);
1620 	for (i = 0; i < nsegs; i++) {
1621 		desc->seg_addr[i] = htole32(segs[i].ds_addr);
1622 		desc->seg_len[i]  = htole32(segs[i].ds_len);
1623 	}
1624 
1625 	bus_dmamap_sync(txq->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
1626 	bus_dmamap_sync(txq->desc_dmat, txq->desc_map, BUS_DMASYNC_PREWRITE);
1627 
1628 	DPRINTFN(5, ("sending data frame txq=%u idx=%u len=%u nseg=%u\n",
1629 	    ac, txq->cur, desc->len, desc->nseg));
1630 
1631 	txq->queued++;
1632 	txq->cur = (txq->cur + 1) % IWI_TX_RING_COUNT;
1633 	CSR_WRITE_4(sc, txq->csr_widx, txq->cur);
1634 
1635 	return 0;
1636 }
1637 
1638 static void
1639 iwi_start(struct ifnet *ifp)
1640 {
1641 	struct iwi_softc *sc = ifp->if_softc;
1642 	struct ieee80211com *ic = &sc->sc_ic;
1643 	struct mbuf *m0;
1644 	struct ether_header *eh;
1645 	struct ieee80211_node *ni;
1646 	int ac;
1647 
1648 	IWI_LOCK(sc);
1649 
1650 	if (ic->ic_state != IEEE80211_S_RUN) {
1651 		IWI_UNLOCK(sc);
1652 		return;
1653 	}
1654 
1655 	for (;;) {
1656 		IFQ_DRV_DEQUEUE(&ifp->if_snd, m0);
1657 		if (m0 == NULL)
1658 			break;
1659 
1660 		if (m0->m_len < sizeof (struct ether_header) &&
1661 		    (m0 = m_pullup(m0, sizeof (struct ether_header))) == NULL) {
1662 			ifp->if_oerrors++;
1663 			continue;
1664 		}
1665 		eh = mtod(m0, struct ether_header *);
1666 		ni = ieee80211_find_txnode(ic, eh->ether_dhost);
1667 		if (ni == NULL) {
1668 			m_freem(m0);
1669 			ifp->if_oerrors++;
1670 			continue;
1671 		}
1672 
1673 		/* classify mbuf so we can find which tx ring to use */
1674 		if (ieee80211_classify(ic, m0, ni) != 0) {
1675 			m_freem(m0);
1676 			ieee80211_free_node(ni);
1677 			ifp->if_oerrors++;
1678 			continue;
1679 		}
1680 
1681 		/* no QoS encapsulation for EAPOL frames */
1682 		ac = (eh->ether_type != htons(ETHERTYPE_PAE)) ?
1683 		    M_WME_GETAC(m0) : WME_AC_BE;
1684 
1685 		if (sc->txq[ac].queued > IWI_TX_RING_COUNT - 8) {
1686 			/* there is no place left in this ring */
1687 			IFQ_DRV_PREPEND(&ifp->if_snd, m0);
1688 			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1689 			break;
1690 		}
1691 
1692 		BPF_MTAP(ifp, m0);
1693 
1694 		m0 = ieee80211_encap(ic, m0, ni);
1695 		if (m0 == NULL) {
1696 			ieee80211_free_node(ni);
1697 			ifp->if_oerrors++;
1698 			continue;
1699 		}
1700 
1701 		if (ic->ic_rawbpf != NULL)
1702 			bpf_mtap(ic->ic_rawbpf, m0);
1703 
1704 		if (iwi_tx_start(ifp, m0, ni, ac) != 0) {
1705 			ieee80211_free_node(ni);
1706 			ifp->if_oerrors++;
1707 			break;
1708 		}
1709 
1710 		sc->sc_tx_timer = 5;
1711 		ifp->if_timer = 1;
1712 	}
1713 
1714 	IWI_UNLOCK(sc);
1715 }
1716 
1717 static void
1718 iwi_watchdog(struct ifnet *ifp)
1719 {
1720 	struct iwi_softc *sc = ifp->if_softc;
1721 	struct ieee80211com *ic = &sc->sc_ic;
1722 
1723 	IWI_LOCK(sc);
1724 
1725 	ifp->if_timer = 0;
1726 
1727 	if (sc->sc_tx_timer > 0) {
1728 		if (--sc->sc_tx_timer == 0) {
1729 			if_printf(ifp, "device timeout\n");
1730 			ifp->if_oerrors++;
1731 			ifp->if_flags &= ~IFF_UP;
1732 			iwi_stop(sc);
1733 			IWI_UNLOCK(sc);
1734 			return;
1735 		}
1736 		ifp->if_timer = 1;
1737 	}
1738 
1739 	ieee80211_watchdog(ic);
1740 
1741 	IWI_UNLOCK(sc);
1742 }
1743 
1744 static int
1745 iwi_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1746 {
1747 	struct iwi_softc *sc = ifp->if_softc;
1748 	struct ieee80211com *ic = &sc->sc_ic;
1749 	struct ifreq *ifr;
1750 	int error = 0;
1751 
1752 	IWI_LOCK(sc);
1753 
1754 	switch (cmd) {
1755 	case SIOCSIFFLAGS:
1756 		if (ifp->if_flags & IFF_UP) {
1757 			if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
1758 				iwi_init(sc);
1759 		} else {
1760 			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1761 				iwi_stop(sc);
1762 		}
1763 		break;
1764 
1765 	case SIOCSLOADFW:
1766 		/* only super-user can do that! */
1767 		if ((error = suser(curthread)) != 0)
1768 			break;
1769 
1770 		ifr = (struct ifreq *)data;
1771 		error = iwi_cache_firmware(sc, ifr->ifr_data);
1772 		break;
1773 
1774 	case SIOCSKILLFW:
1775 		/* only super-user can do that! */
1776 		if ((error = suser(curthread)) != 0)
1777 			break;
1778 
1779 		ifp->if_flags &= ~IFF_UP;
1780 		iwi_stop(sc);
1781 		iwi_free_firmware(sc);
1782 		break;
1783 
1784 	default:
1785 		error = ieee80211_ioctl(ic, cmd, data);
1786 	}
1787 
1788 	if (error == ENETRESET) {
1789 		if ((ifp->if_flags & IFF_UP) &&
1790 		    (ifp->if_drv_flags & IFF_DRV_RUNNING) &&
1791 		    (ic->ic_roaming != IEEE80211_ROAMING_MANUAL))
1792 			iwi_init(sc);
1793 		error = 0;
1794 	}
1795 
1796 	IWI_UNLOCK(sc);
1797 
1798 	return error;
1799 }
1800 
1801 static void
1802 iwi_stop_master(struct iwi_softc *sc)
1803 {
1804 	uint32_t tmp;
1805 	int ntries;
1806 
1807 	/* disable interrupts */
1808 	CSR_WRITE_4(sc, IWI_CSR_INTR_MASK, 0);
1809 
1810 	CSR_WRITE_4(sc, IWI_CSR_RST, IWI_RST_STOP_MASTER);
1811 	for (ntries = 0; ntries < 5; ntries++) {
1812 		if (CSR_READ_4(sc, IWI_CSR_RST) & IWI_RST_MASTER_DISABLED)
1813 			break;
1814 		DELAY(10);
1815 	}
1816 	if (ntries == 5)
1817 		device_printf(sc->sc_dev, "timeout waiting for master\n");
1818 
1819 	tmp = CSR_READ_4(sc, IWI_CSR_RST);
1820 	CSR_WRITE_4(sc, IWI_CSR_RST, tmp | IWI_RST_PRINCETON_RESET);
1821 
1822 	sc->flags &= ~IWI_FLAG_FW_INITED;
1823 }
1824 
1825 static int
1826 iwi_reset(struct iwi_softc *sc)
1827 {
1828 	uint32_t tmp;
1829 	int i, ntries;
1830 
1831 	iwi_stop_master(sc);
1832 
1833 	tmp = CSR_READ_4(sc, IWI_CSR_CTL);
1834 	CSR_WRITE_4(sc, IWI_CSR_CTL, tmp | IWI_CTL_INIT);
1835 
1836 	CSR_WRITE_4(sc, IWI_CSR_READ_INT, IWI_READ_INT_INIT_HOST);
1837 
1838 	/* wait for clock stabilization */
1839 	for (ntries = 0; ntries < 1000; ntries++) {
1840 		if (CSR_READ_4(sc, IWI_CSR_CTL) & IWI_CTL_CLOCK_READY)
1841 			break;
1842 		DELAY(200);
1843 	}
1844 	if (ntries == 1000) {
1845 		device_printf(sc->sc_dev,
1846 		    "timeout waiting for clock stabilization\n");
1847 		return EIO;
1848 	}
1849 
1850 	tmp = CSR_READ_4(sc, IWI_CSR_RST);
1851 	CSR_WRITE_4(sc, IWI_CSR_RST, tmp | IWI_RST_SOFT_RESET);
1852 
1853 	DELAY(10);
1854 
1855 	tmp = CSR_READ_4(sc, IWI_CSR_CTL);
1856 	CSR_WRITE_4(sc, IWI_CSR_CTL, tmp | IWI_CTL_INIT);
1857 
1858 	/* clear NIC memory */
1859 	CSR_WRITE_4(sc, IWI_CSR_AUTOINC_ADDR, 0);
1860 	for (i = 0; i < 0xc000; i++)
1861 		CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, 0);
1862 
1863 	return 0;
1864 }
1865 
1866 static int
1867 iwi_load_ucode(struct iwi_softc *sc, void *uc, int size)
1868 {
1869 	uint32_t tmp;
1870 	uint16_t *w;
1871 	int ntries, i;
1872 
1873 	CSR_WRITE_4(sc, IWI_CSR_RST, CSR_READ_4(sc, IWI_CSR_RST) |
1874 	    IWI_RST_STOP_MASTER);
1875 	for (ntries = 0; ntries < 5; ntries++) {
1876 		if (CSR_READ_4(sc, IWI_CSR_RST) & IWI_RST_MASTER_DISABLED)
1877 			break;
1878 		DELAY(10);
1879 	}
1880 	if (ntries == 5) {
1881 		device_printf(sc->sc_dev, "timeout waiting for master\n");
1882 		return EIO;
1883 	}
1884 
1885 	MEM_WRITE_4(sc, 0x3000e0, 0x80000000);
1886 	DELAY(5000);
1887 
1888 	tmp = CSR_READ_4(sc, IWI_CSR_RST);
1889 	tmp &= ~IWI_RST_PRINCETON_RESET;
1890 	CSR_WRITE_4(sc, IWI_CSR_RST, tmp);
1891 
1892 	DELAY(5000);
1893 	MEM_WRITE_4(sc, 0x3000e0, 0);
1894 	DELAY(1000);
1895 	MEM_WRITE_4(sc, 0x300004, 1);
1896 	DELAY(1000);
1897 	MEM_WRITE_4(sc, 0x300004, 0);
1898 	DELAY(1000);
1899 	MEM_WRITE_1(sc, 0x200000, 0x00);
1900 	MEM_WRITE_1(sc, 0x200000, 0x40);
1901 	DELAY(1000);
1902 
1903 	/* write microcode into adapter memory */
1904 	for (w = uc; size > 0; w++, size -= 2)
1905 		MEM_WRITE_2(sc, 0x200010, *w);
1906 
1907 	MEM_WRITE_1(sc, 0x200000, 0x00);
1908 	MEM_WRITE_1(sc, 0x200000, 0x80);
1909 
1910 	/* wait until we get an answer */
1911 	for (ntries = 0; ntries < 100; ntries++) {
1912 		if (MEM_READ_1(sc, 0x200000) & 1)
1913 			break;
1914 		DELAY(100);
1915 	}
1916 	if (ntries == 100) {
1917 		device_printf(sc->sc_dev,
1918 		    "timeout waiting for ucode to initialize\n");
1919 		return EIO;
1920 	}
1921 
1922 	/* read the answer or the firmware will not initialize properly */
1923 	for (i = 0; i < 7; i++)
1924 		MEM_READ_4(sc, 0x200004);
1925 
1926 	MEM_WRITE_1(sc, 0x200000, 0x00);
1927 
1928 	return 0;
1929 }
1930 
1931 /* macro to handle unaligned little endian data in firmware image */
1932 #define GETLE32(p) ((p)[0] | (p)[1] << 8 | (p)[2] << 16 | (p)[3] << 24)
1933 
1934 static int
1935 iwi_load_firmware(struct iwi_softc *sc, void *fw, int size)
1936 {
1937 	bus_dma_tag_t dmat;
1938 	bus_dmamap_t map;
1939 	bus_addr_t physaddr;
1940 	void *virtaddr;
1941 	u_char *p, *end;
1942 	uint32_t sentinel, ctl, src, dst, sum, len, mlen, tmp;
1943 	int ntries, error = 0;
1944 
1945 	/* allocate DMA memory for mapping firmware image */
1946 	error = bus_dma_tag_create(NULL, 4, 0, BUS_SPACE_MAXADDR_32BIT,
1947 	    BUS_SPACE_MAXADDR, NULL, NULL, size, 1, size, 0, NULL, NULL, &dmat);
1948 	if (error != 0) {
1949 		device_printf(sc->sc_dev,
1950 		    "could not create firmware DMA tag\n");
1951 		goto fail1;
1952 	}
1953 
1954 	error = bus_dmamem_alloc(dmat, &virtaddr, BUS_DMA_NOWAIT, &map);
1955 	if (error != 0) {
1956 		device_printf(sc->sc_dev,
1957 		    "could not allocate firmware DMA memory\n");
1958 		goto fail2;
1959 	}
1960 
1961 	error = bus_dmamap_load(dmat, map, virtaddr, size, iwi_dma_map_addr,
1962 	    &physaddr, 0);
1963 	if (error != 0) {
1964 		device_printf(sc->sc_dev, "could not load firmware DMA map\n");
1965 		goto fail3;
1966 	}
1967 
1968 	/* copy firmware image to DMA memory */
1969 	memcpy(virtaddr, fw, size);
1970 
1971 	/* make sure the adapter will get up-to-date values */
1972 	bus_dmamap_sync(dmat, map, BUS_DMASYNC_PREWRITE);
1973 
1974 	/* tell the adapter where the command blocks are stored */
1975 	MEM_WRITE_4(sc, 0x3000a0, 0x27000);
1976 
1977 	/*
1978 	 * Store command blocks into adapter's internal memory using register
1979 	 * indirections. The adapter will read the firmware image through DMA
1980 	 * using information stored in command blocks.
1981 	 */
1982 	src = physaddr;
1983 	p = virtaddr;
1984 	end = p + size;
1985 	CSR_WRITE_4(sc, IWI_CSR_AUTOINC_ADDR, 0x27000);
1986 
1987 	while (p < end) {
1988 		dst = GETLE32(p); p += 4; src += 4;
1989 		len = GETLE32(p); p += 4; src += 4;
1990 		p += len;
1991 
1992 		while (len > 0) {
1993 			mlen = min(len, IWI_CB_MAXDATALEN);
1994 
1995 			ctl = IWI_CB_DEFAULT_CTL | mlen;
1996 			sum = ctl ^ src ^ dst;
1997 
1998 			/* write a command block */
1999 			CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, ctl);
2000 			CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, src);
2001 			CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, dst);
2002 			CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, sum);
2003 
2004 			src += mlen;
2005 			dst += mlen;
2006 			len -= mlen;
2007 		}
2008 	}
2009 
2010 	/* write a fictive final command block (sentinel) */
2011 	sentinel = CSR_READ_4(sc, IWI_CSR_AUTOINC_ADDR);
2012 	CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, 0);
2013 
2014 	tmp = CSR_READ_4(sc, IWI_CSR_RST);
2015 	tmp &= ~(IWI_RST_MASTER_DISABLED | IWI_RST_STOP_MASTER);
2016 	CSR_WRITE_4(sc, IWI_CSR_RST, tmp);
2017 
2018 	/* tell the adapter to start processing command blocks */
2019 	MEM_WRITE_4(sc, 0x3000a4, 0x540100);
2020 
2021 	/* wait until the adapter reach the sentinel */
2022 	for (ntries = 0; ntries < 400; ntries++) {
2023 		if (MEM_READ_4(sc, 0x3000d0) >= sentinel)
2024 			break;
2025 		DELAY(100);
2026 	}
2027 	if (ntries == 400) {
2028 		device_printf(sc->sc_dev,
2029 		    "timeout processing command blocks\n");
2030 		error = EIO;
2031 		goto fail4;
2032 	}
2033 
2034 	/* we're done with command blocks processing */
2035 	MEM_WRITE_4(sc, 0x3000a4, 0x540c00);
2036 
2037 	/* allow interrupts so we know when the firmware is inited */
2038 	CSR_WRITE_4(sc, IWI_CSR_INTR_MASK, IWI_INTR_MASK);
2039 
2040 	/* tell the adapter to initialize the firmware */
2041 	CSR_WRITE_4(sc, IWI_CSR_RST, 0);
2042 
2043 	tmp = CSR_READ_4(sc, IWI_CSR_CTL);
2044 	CSR_WRITE_4(sc, IWI_CSR_CTL, tmp | IWI_CTL_ALLOW_STANDBY);
2045 
2046 	/* wait at most one second for firmware initialization to complete */
2047 	if ((error = msleep(sc, &sc->sc_mtx, 0, "iwiinit", hz)) != 0) {
2048 		device_printf(sc->sc_dev, "timeout waiting for firmware "
2049 		    "initialization to complete\n");
2050 		goto fail4;
2051 	}
2052 
2053 fail4:	bus_dmamap_sync(dmat, map, BUS_DMASYNC_POSTWRITE);
2054 	bus_dmamap_unload(dmat, map);
2055 fail3:	bus_dmamem_free(dmat, virtaddr, map);
2056 fail2:	bus_dma_tag_destroy(dmat);
2057 fail1:
2058 	return error;
2059 }
2060 
2061 /*
2062  * Store firmware into kernel memory so we can download it when we need to,
2063  * e.g when the adapter wakes up from suspend mode.
2064  */
2065 static int
2066 iwi_cache_firmware(struct iwi_softc *sc, void *data)
2067 {
2068 	struct iwi_firmware *kfw = &sc->fw;
2069 	struct iwi_firmware ufw;
2070 	int error;
2071 
2072 	iwi_free_firmware(sc);
2073 
2074 	IWI_UNLOCK(sc);
2075 
2076 	if ((error = copyin(data, &ufw, sizeof ufw)) != 0)
2077 		goto fail1;
2078 
2079 	kfw->boot_size  = ufw.boot_size;
2080 	kfw->ucode_size = ufw.ucode_size;
2081 	kfw->main_size  = ufw.main_size;
2082 
2083 	kfw->boot = malloc(kfw->boot_size, M_DEVBUF, M_NOWAIT);
2084 	if (kfw->boot == NULL) {
2085 		error = ENOMEM;
2086 		goto fail1;
2087 	}
2088 
2089 	kfw->ucode = malloc(kfw->ucode_size, M_DEVBUF, M_NOWAIT);
2090 	if (kfw->ucode == NULL) {
2091 		error = ENOMEM;
2092 		goto fail2;
2093 	}
2094 
2095 	kfw->main = malloc(kfw->main_size, M_DEVBUF, M_NOWAIT);
2096 	if (kfw->main == NULL) {
2097 		error = ENOMEM;
2098 		goto fail3;
2099 	}
2100 
2101 	if ((error = copyin(ufw.boot, kfw->boot, kfw->boot_size)) != 0)
2102 		goto fail4;
2103 
2104 	if ((error = copyin(ufw.ucode, kfw->ucode, kfw->ucode_size)) != 0)
2105 		goto fail4;
2106 
2107 	if ((error = copyin(ufw.main, kfw->main, kfw->main_size)) != 0)
2108 		goto fail4;
2109 
2110 	DPRINTF(("Firmware cached: boot %u, ucode %u, main %u\n",
2111 	    kfw->boot_size, kfw->ucode_size, kfw->main_size));
2112 
2113 	IWI_LOCK(sc);
2114 
2115 	sc->flags |= IWI_FLAG_FW_CACHED;
2116 
2117 	return 0;
2118 
2119 fail4:	free(kfw->boot, M_DEVBUF);
2120 fail3:	free(kfw->ucode, M_DEVBUF);
2121 fail2:	free(kfw->main, M_DEVBUF);
2122 fail1:	IWI_LOCK(sc);
2123 
2124 	return error;
2125 }
2126 
2127 static void
2128 iwi_free_firmware(struct iwi_softc *sc)
2129 {
2130 	if (!(sc->flags & IWI_FLAG_FW_CACHED))
2131 		return;
2132 
2133 	free(sc->fw.boot, M_DEVBUF);
2134 	free(sc->fw.ucode, M_DEVBUF);
2135 	free(sc->fw.main, M_DEVBUF);
2136 
2137 	sc->flags &= ~IWI_FLAG_FW_CACHED;
2138 }
2139 
2140 static int
2141 iwi_config(struct iwi_softc *sc)
2142 {
2143 	struct ieee80211com *ic = &sc->sc_ic;
2144 	struct ifnet *ifp = ic->ic_ifp;
2145 	struct iwi_configuration config;
2146 	struct iwi_rateset rs;
2147 	struct iwi_txpower power;
2148 	struct ieee80211_key *wk;
2149 	struct iwi_wep_key wepkey;
2150 	uint32_t data;
2151 	int error, i;
2152 
2153 	IEEE80211_ADDR_COPY(ic->ic_myaddr, IF_LLADDR(ifp));
2154 	DPRINTF(("Setting MAC address to %6D\n", ic->ic_myaddr, ":"));
2155 	error = iwi_cmd(sc, IWI_CMD_SET_MAC_ADDRESS, ic->ic_myaddr,
2156 	    IEEE80211_ADDR_LEN, 0);
2157 	if (error != 0)
2158 		return error;
2159 
2160 	memset(&config, 0, sizeof config);
2161 	config.bluetooth_coexistence = sc->bluetooth;
2162 	config.antenna = sc->antenna;
2163 	config.multicast_enabled = 1;
2164 	config.answer_pbreq = (ic->ic_opmode == IEEE80211_M_IBSS) ? 1 : 0;
2165 	config.disable_unicast_decryption = 1;
2166 	config.disable_multicast_decryption = 1;
2167 	DPRINTF(("Configuring adapter\n"));
2168 	error = iwi_cmd(sc, IWI_CMD_SET_CONFIG, &config, sizeof config, 0);
2169 	if (error != 0)
2170 		return error;
2171 
2172 	data = htole32(IWI_POWER_MODE_CAM);
2173 	DPRINTF(("Setting power mode to %u\n", le32toh(data)));
2174 	error = iwi_cmd(sc, IWI_CMD_SET_POWER_MODE, &data, sizeof data, 0);
2175 	if (error != 0)
2176 		return error;
2177 
2178 	data = htole32(ic->ic_rtsthreshold);
2179 	DPRINTF(("Setting RTS threshold to %u\n", le32toh(data)));
2180 	error = iwi_cmd(sc, IWI_CMD_SET_RTS_THRESHOLD, &data, sizeof data, 0);
2181 	if (error != 0)
2182 		return error;
2183 
2184 	data = htole32(ic->ic_fragthreshold);
2185 	DPRINTF(("Setting fragmentation threshold to %u\n", le32toh(data)));
2186 	error = iwi_cmd(sc, IWI_CMD_SET_FRAG_THRESHOLD, &data, sizeof data, 0);
2187 	if (error != 0)
2188 		return error;
2189 
2190 	if (ic->ic_opmode == IEEE80211_M_IBSS) {
2191 		power.mode = IWI_MODE_11B;
2192 		power.nchan = 11;
2193 		for (i = 0; i < 11; i++) {
2194 			power.chan[i].chan = i + 1;
2195 			power.chan[i].power = IWI_TXPOWER_MAX;
2196 		}
2197 		DPRINTF(("Setting .11b channels tx power\n"));
2198 		error = iwi_cmd(sc, IWI_CMD_SET_TX_POWER, &power, sizeof power,
2199 		    0);
2200 		if (error != 0)
2201 			return error;
2202 
2203 		power.mode = IWI_MODE_11G;
2204 		DPRINTF(("Setting .11g channels tx power\n"));
2205 		error = iwi_cmd(sc, IWI_CMD_SET_TX_POWER, &power, sizeof power,
2206 		    0);
2207 		if (error != 0)
2208 			return error;
2209 	}
2210 
2211 	rs.mode = IWI_MODE_11G;
2212 	rs.type = IWI_RATESET_TYPE_SUPPORTED;
2213 	rs.nrates = ic->ic_sup_rates[IEEE80211_MODE_11G].rs_nrates;
2214 	memcpy(rs.rates, ic->ic_sup_rates[IEEE80211_MODE_11G].rs_rates,
2215 	    rs.nrates);
2216 	DPRINTF(("Setting .11bg supported rates (%u)\n", rs.nrates));
2217 	error = iwi_cmd(sc, IWI_CMD_SET_RATES, &rs, sizeof rs, 0);
2218 	if (error != 0)
2219 		return error;
2220 
2221 	rs.mode = IWI_MODE_11A;
2222 	rs.type = IWI_RATESET_TYPE_SUPPORTED;
2223 	rs.nrates = ic->ic_sup_rates[IEEE80211_MODE_11A].rs_nrates;
2224 	memcpy(rs.rates, ic->ic_sup_rates[IEEE80211_MODE_11A].rs_rates,
2225 	    rs.nrates);
2226 	DPRINTF(("Setting .11a supported rates (%u)\n", rs.nrates));
2227 	error = iwi_cmd(sc, IWI_CMD_SET_RATES, &rs, sizeof rs, 0);
2228 	if (error != 0)
2229 		return error;
2230 
2231 	/* if we have a desired ESSID, set it now */
2232 	if (ic->ic_des_esslen != 0) {
2233 #ifdef IWI_DEBUG
2234 		if (iwi_debug > 0) {
2235 			printf("Setting desired ESSID to ");
2236 			ieee80211_print_essid(ic->ic_des_essid,
2237 			    ic->ic_des_esslen);
2238 			printf("\n");
2239 		}
2240 #endif
2241 		error = iwi_cmd(sc, IWI_CMD_SET_ESSID, ic->ic_des_essid,
2242 		    ic->ic_des_esslen, 0);
2243 		if (error != 0)
2244 			return error;
2245 	}
2246 
2247 	data = htole32(arc4random());
2248 	DPRINTF(("Setting initialization vector to %u\n", le32toh(data)));
2249 	error = iwi_cmd(sc, IWI_CMD_SET_IV, &data, sizeof data, 0);
2250 	if (error != 0)
2251 		return error;
2252 
2253 	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
2254 		wk = &ic->ic_crypto.cs_nw_keys[i];
2255 
2256 		wepkey.cmd = IWI_WEP_KEY_CMD_SETKEY;
2257 		wepkey.idx = i;
2258 		wepkey.len = wk->wk_keylen;
2259 		memset(wepkey.key, 0, sizeof wepkey.key);
2260 		memcpy(wepkey.key, wk->wk_key, wk->wk_keylen);
2261 		DPRINTF(("Setting wep key index %u len %u\n", wepkey.idx,
2262 		    wepkey.len));
2263 		error = iwi_cmd(sc, IWI_CMD_SET_WEP_KEY, &wepkey,
2264 		    sizeof wepkey, 0);
2265 		if (error != 0)
2266 			return error;
2267 	}
2268 
2269 	/* enable adapter */
2270 	DPRINTF(("Enabling adapter\n"));
2271 	return iwi_cmd(sc, IWI_CMD_ENABLE, NULL, 0, 0);
2272 }
2273 
2274 static int
2275 iwi_set_chan(struct iwi_softc *sc, struct ieee80211_channel *chan)
2276 {
2277 	struct ieee80211com *ic = &sc->sc_ic;
2278 	struct iwi_scan scan;
2279 
2280 	memset(&scan, 0, sizeof scan);
2281 	scan.type = IWI_SCAN_TYPE_PASSIVE;
2282 	scan.dwelltime = htole16(2000);
2283 	scan.channels[0] = 1 | (IEEE80211_IS_CHAN_5GHZ(chan) ? IWI_CHAN_5GHZ :
2284 	    IWI_CHAN_2GHZ);
2285 	scan.channels[1] = ieee80211_chan2ieee(ic, chan);
2286 
2287 	DPRINTF(("Setting channel to %u\n", ieee80211_chan2ieee(ic, chan)));
2288 	return iwi_cmd(sc, IWI_CMD_SCAN, &scan, sizeof scan, 1);
2289 }
2290 
2291 static int
2292 iwi_scan(struct iwi_softc *sc)
2293 {
2294 	struct ieee80211com *ic = &sc->sc_ic;
2295 	struct iwi_scan scan;
2296 	uint8_t *p;
2297 	int i, count;
2298 
2299 	memset(&scan, 0, sizeof scan);
2300 	scan.type = (ic->ic_des_esslen != 0) ? IWI_SCAN_TYPE_BDIRECTED :
2301 	    IWI_SCAN_TYPE_BROADCAST;
2302 	scan.dwelltime = htole16(sc->dwelltime);
2303 
2304 	p = scan.channels;
2305 	count = 0;
2306 	for (i = 0; i <= IEEE80211_CHAN_MAX; i++) {
2307 		if (IEEE80211_IS_CHAN_5GHZ(&ic->ic_channels[i]) &&
2308 		    isset(ic->ic_chan_active, i)) {
2309 			*++p = i;
2310 			count++;
2311 		}
2312 	}
2313 	*(p - count) = IWI_CHAN_5GHZ | count;
2314 
2315 	count = 0;
2316 	for (i = 0; i <= IEEE80211_CHAN_MAX; i++) {
2317 		if (IEEE80211_IS_CHAN_2GHZ(&ic->ic_channels[i]) &&
2318 		    isset(ic->ic_chan_active, i)) {
2319 			*++p = i;
2320 			count++;
2321 		}
2322 	}
2323 	*(p - count) = IWI_CHAN_2GHZ | count;
2324 
2325 	DPRINTF(("Start scanning\n"));
2326 	return iwi_cmd(sc, IWI_CMD_SCAN, &scan, sizeof scan, 1);
2327 }
2328 
2329 static int
2330 iwi_auth_and_assoc(struct iwi_softc *sc)
2331 {
2332 	struct ieee80211com *ic = &sc->sc_ic;
2333 	struct ifnet *ifp = ic->ic_ifp;
2334 	struct ieee80211_node *ni = ic->ic_bss;
2335 	struct ieee80211_wme_info wme;
2336 	struct iwi_configuration config;
2337 	struct iwi_associate assoc;
2338 	struct iwi_rateset rs;
2339 	uint16_t capinfo;
2340 	uint32_t data;
2341 	int error;
2342 
2343 	if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan)) {
2344 		memset(&config, 0, sizeof config);
2345 		config.bluetooth_coexistence = sc->bluetooth;
2346 		config.antenna = sc->antenna;
2347 		config.multicast_enabled = 1;
2348 		config.use_protection = 1;
2349 		config.answer_pbreq =
2350 		    (ic->ic_opmode == IEEE80211_M_IBSS) ? 1 : 0;
2351 		config.disable_unicast_decryption = 1;
2352 		config.disable_multicast_decryption = 1;
2353 		DPRINTF(("Configuring adapter\n"));
2354 		error = iwi_cmd(sc, IWI_CMD_SET_CONFIG, &config, sizeof config,
2355 		    1);
2356 		if (error != 0)
2357 			return error;
2358 	}
2359 
2360 #ifdef IWI_DEBUG
2361 	if (iwi_debug > 0) {
2362 		printf("Setting ESSID to ");
2363 		ieee80211_print_essid(ni->ni_essid, ni->ni_esslen);
2364 		printf("\n");
2365 	}
2366 #endif
2367 	error = iwi_cmd(sc, IWI_CMD_SET_ESSID, ni->ni_essid, ni->ni_esslen, 1);
2368 	if (error != 0)
2369 		return error;
2370 
2371 	/* the rate set has already been "negociated" */
2372 	rs.mode = IEEE80211_IS_CHAN_5GHZ(ni->ni_chan) ? IWI_MODE_11A :
2373 	    IWI_MODE_11G;
2374 	rs.type = IWI_RATESET_TYPE_NEGOCIATED;
2375 	rs.nrates = ni->ni_rates.rs_nrates;
2376 	memcpy(rs.rates, ni->ni_rates.rs_rates, rs.nrates);
2377 	DPRINTF(("Setting negociated rates (%u)\n", rs.nrates));
2378 	error = iwi_cmd(sc, IWI_CMD_SET_RATES, &rs, sizeof rs, 1);
2379 	if (error != 0)
2380 		return error;
2381 
2382 	if ((ic->ic_flags & IEEE80211_F_WME) && ni->ni_wme_ie != NULL) {
2383 		wme.wme_id = IEEE80211_ELEMID_VENDOR;
2384 		wme.wme_len = sizeof (struct ieee80211_wme_info) - 2;
2385 		wme.wme_oui[0] = 0x00;
2386 		wme.wme_oui[1] = 0x50;
2387 		wme.wme_oui[2] = 0xf2;
2388 		wme.wme_type = WME_OUI_TYPE;
2389 		wme.wme_subtype = WME_INFO_OUI_SUBTYPE;
2390 		wme.wme_version = WME_VERSION;
2391 		wme.wme_info = 0;
2392 
2393 		DPRINTF(("Setting WME IE (len=%u)\n", wme.wme_len));
2394 		error = iwi_cmd(sc, IWI_CMD_SET_WMEIE, &wme, sizeof wme, 1);
2395 		if (error != 0)
2396 			return error;
2397 	}
2398 
2399 	if (ic->ic_opt_ie != NULL) {
2400 		DPRINTF(("Setting optional IE (len=%u)\n", ic->ic_opt_ie_len));
2401 		error = iwi_cmd(sc, IWI_CMD_SET_OPTIE, ic->ic_opt_ie,
2402 		    ic->ic_opt_ie_len, 1);
2403 		if (error != 0)
2404 			return error;
2405 	}
2406 
2407 	data = htole32(ni->ni_rssi);
2408 	DPRINTF(("Setting sensitivity to %d\n", (int8_t)ni->ni_rssi));
2409 	error = iwi_cmd(sc, IWI_CMD_SET_SENSITIVITY, &data, sizeof data, 1);
2410 	if (error != 0)
2411 		return error;
2412 
2413 	memset(&assoc, 0, sizeof assoc);
2414 	assoc.mode = IEEE80211_IS_CHAN_5GHZ(ni->ni_chan) ? IWI_MODE_11A :
2415 	    IWI_MODE_11G;
2416 	assoc.chan = ieee80211_chan2ieee(ic, ni->ni_chan);
2417 	if (ni->ni_authmode == IEEE80211_AUTH_SHARED)
2418 		assoc.auth = ic->ic_crypto.cs_def_txkey << 4 | IWI_AUTH_SHARED;
2419 	if ((ic->ic_flags & IEEE80211_F_WME) && ni->ni_wme_ie != NULL)
2420 		assoc.policy |= htole16(IWI_POLICY_WME);
2421 	if (ic->ic_opt_ie != NULL)
2422 		assoc.policy |= htole16(IWI_POLICY_WPA);
2423 	memcpy(assoc.tstamp, ni->ni_tstamp.data, 8);
2424 
2425 	if (ic->ic_opmode == IEEE80211_M_IBSS)
2426 		capinfo = IEEE80211_CAPINFO_IBSS;
2427 	else
2428 		capinfo = IEEE80211_CAPINFO_ESS;
2429 	if (ic->ic_flags & IEEE80211_F_PRIVACY)
2430 		capinfo |= IEEE80211_CAPINFO_PRIVACY;
2431 	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
2432 	    IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
2433 		capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
2434 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
2435 		capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
2436 	assoc.capinfo = htole16(capinfo);
2437 
2438 	assoc.lintval = htole16(ic->ic_lintval);
2439 	assoc.intval = htole16(ni->ni_intval);
2440 	IEEE80211_ADDR_COPY(assoc.bssid, ni->ni_bssid);
2441 	if (ic->ic_opmode == IEEE80211_M_IBSS)
2442 		IEEE80211_ADDR_COPY(assoc.dst, ifp->if_broadcastaddr);
2443 	else
2444 		IEEE80211_ADDR_COPY(assoc.dst, ni->ni_bssid);
2445 
2446 	DPRINTF(("Trying to associate to %6D channel %u auth %u\n",
2447 	    assoc.bssid, ":", assoc.chan, assoc.auth));
2448 	return iwi_cmd(sc, IWI_CMD_ASSOCIATE, &assoc, sizeof assoc, 1);
2449 }
2450 
2451 static void
2452 iwi_init(void *priv)
2453 {
2454 	struct iwi_softc *sc = priv;
2455 	struct ieee80211com *ic = &sc->sc_ic;
2456 	struct ifnet *ifp = ic->ic_ifp;
2457 	struct iwi_firmware *fw = &sc->fw;
2458 	struct iwi_rx_data *data;
2459 	int i;
2460 
2461 	/* exit immediately if firmware has not been ioctl'd */
2462 	if (!(sc->flags & IWI_FLAG_FW_CACHED)) {
2463 		if (!(sc->flags & IWI_FLAG_FW_WARNED))
2464 			device_printf(sc->sc_dev, "Please load firmware\n");
2465 		sc->flags |= IWI_FLAG_FW_WARNED;
2466 		ifp->if_flags &= ~IFF_UP;
2467 		return;
2468 	}
2469 
2470 	iwi_stop(sc);
2471 
2472 	if (iwi_reset(sc) != 0) {
2473 		device_printf(sc->sc_dev, "could not reset adapter\n");
2474 		goto fail;
2475 	}
2476 
2477 	if (iwi_load_firmware(sc, fw->boot, fw->boot_size) != 0) {
2478 		device_printf(sc->sc_dev, "could not load boot firmware\n");
2479 		goto fail;
2480 	}
2481 
2482 	if (iwi_load_ucode(sc, fw->ucode, fw->ucode_size) != 0) {
2483 		device_printf(sc->sc_dev, "could not load microcode\n");
2484 		goto fail;
2485 	}
2486 
2487 	iwi_stop_master(sc);
2488 
2489 	CSR_WRITE_4(sc, IWI_CSR_CMD_BASE, sc->cmdq.physaddr);
2490 	CSR_WRITE_4(sc, IWI_CSR_CMD_SIZE, sc->cmdq.count);
2491 	CSR_WRITE_4(sc, IWI_CSR_CMD_WIDX, sc->cmdq.cur);
2492 
2493 	CSR_WRITE_4(sc, IWI_CSR_TX1_BASE, sc->txq[0].physaddr);
2494 	CSR_WRITE_4(sc, IWI_CSR_TX1_SIZE, sc->txq[0].count);
2495 	CSR_WRITE_4(sc, IWI_CSR_TX1_WIDX, sc->txq[0].cur);
2496 
2497 	CSR_WRITE_4(sc, IWI_CSR_TX2_BASE, sc->txq[1].physaddr);
2498 	CSR_WRITE_4(sc, IWI_CSR_TX2_SIZE, sc->txq[1].count);
2499 	CSR_WRITE_4(sc, IWI_CSR_TX2_WIDX, sc->txq[1].cur);
2500 
2501 	CSR_WRITE_4(sc, IWI_CSR_TX3_BASE, sc->txq[2].physaddr);
2502 	CSR_WRITE_4(sc, IWI_CSR_TX3_SIZE, sc->txq[2].count);
2503 	CSR_WRITE_4(sc, IWI_CSR_TX3_WIDX, sc->txq[2].cur);
2504 
2505 	CSR_WRITE_4(sc, IWI_CSR_TX4_BASE, sc->txq[3].physaddr);
2506 	CSR_WRITE_4(sc, IWI_CSR_TX4_SIZE, sc->txq[3].count);
2507 	CSR_WRITE_4(sc, IWI_CSR_TX4_WIDX, sc->txq[3].cur);
2508 
2509 	for (i = 0; i < sc->rxq.count; i++) {
2510 		data = &sc->rxq.data[i];
2511 		CSR_WRITE_4(sc, data->reg, data->physaddr);
2512 	}
2513 
2514 	CSR_WRITE_4(sc, IWI_CSR_RX_WIDX, sc->rxq.count - 1);
2515 
2516 	if (iwi_load_firmware(sc, fw->main, fw->main_size) != 0) {
2517 		device_printf(sc->sc_dev, "could not load main firmware\n");
2518 		goto fail;
2519 	}
2520 
2521 	sc->flags |= IWI_FLAG_FW_INITED;
2522 
2523 	if (iwi_config(sc) != 0) {
2524 		device_printf(sc->sc_dev, "device configuration failed\n");
2525 		goto fail;
2526 	}
2527 
2528 	if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2529 		if (ic->ic_roaming != IEEE80211_ROAMING_MANUAL)
2530 			ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
2531 	} else
2532 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
2533 
2534 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
2535 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
2536 
2537 	return;
2538 
2539 fail:	ifp->if_flags &= ~IFF_UP;
2540 	iwi_stop(sc);
2541 }
2542 
2543 static void
2544 iwi_stop(void *priv)
2545 {
2546 	struct iwi_softc *sc = priv;
2547 	struct ieee80211com *ic = &sc->sc_ic;
2548 	struct ifnet *ifp = ic->ic_ifp;
2549 
2550 	iwi_stop_master(sc);
2551 
2552 	CSR_WRITE_4(sc, IWI_CSR_RST, IWI_RST_SOFT_RESET);
2553 
2554 	/* reset rings */
2555 	iwi_reset_cmd_ring(sc, &sc->cmdq);
2556 	iwi_reset_tx_ring(sc, &sc->txq[0]);
2557 	iwi_reset_tx_ring(sc, &sc->txq[1]);
2558 	iwi_reset_tx_ring(sc, &sc->txq[2]);
2559 	iwi_reset_tx_ring(sc, &sc->txq[3]);
2560 	iwi_reset_rx_ring(sc, &sc->rxq);
2561 
2562 	sc->sc_tx_timer = 0;
2563 	ifp->if_timer = 0;
2564 	ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
2565 
2566 	ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
2567 }
2568 
2569 static int
2570 iwi_sysctl_stats(SYSCTL_HANDLER_ARGS)
2571 {
2572 	struct iwi_softc *sc = arg1;
2573 	uint32_t size, buf[128];
2574 
2575 	if (!(sc->flags & IWI_FLAG_FW_INITED)) {
2576 		memset(buf, 0, sizeof buf);
2577 		return SYSCTL_OUT(req, buf, sizeof buf);
2578 	}
2579 
2580 	size = min(CSR_READ_4(sc, IWI_CSR_TABLE0_SIZE), 128 - 1);
2581 	CSR_READ_REGION_4(sc, IWI_CSR_TABLE0_BASE, &buf[1], size);
2582 
2583 	return SYSCTL_OUT(req, buf, sizeof buf);
2584 }
2585 
2586 static int
2587 iwi_sysctl_radio(SYSCTL_HANDLER_ARGS)
2588 {
2589 	struct iwi_softc *sc = arg1;
2590 	int val;
2591 
2592 	val = (CSR_READ_4(sc, IWI_CSR_IO) & IWI_IO_RADIO_ENABLED) ? 1 : 0;
2593 
2594 	return SYSCTL_OUT(req, &val, sizeof val);
2595 }
2596