xref: /netbsd-src/sys/dev/pci/if_iwi.c (revision 16dce51364ebe8aeafbae46bc5aa167b8115bc45)
1 /*	$NetBSD: if_iwi.c,v 1.105 2018/01/16 07:05:24 maxv Exp $  */
2 /*	$OpenBSD: if_iwi.c,v 1.111 2010/11/15 19:11:57 damien Exp $	*/
3 
4 /*-
5  * Copyright (c) 2004-2008
6  *      Damien Bergamini <damien.bergamini@free.fr>. All rights reserved.
7  *
8  * Permission to use, copy, modify, and distribute this software for any
9  * purpose with or without fee is hereby granted, provided that the above
10  * copyright notice and this permission notice appear in all copies.
11  *
12  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19  */
20 
21 #include <sys/cdefs.h>
22 __KERNEL_RCSID(0, "$NetBSD: if_iwi.c,v 1.105 2018/01/16 07:05:24 maxv Exp $");
23 
24 /*-
25  * Intel(R) PRO/Wireless 2200BG/2225BG/2915ABG driver
26  * http://www.intel.com/network/connectivity/products/wireless/prowireless_mobile.htm
27  */
28 
29 
30 #include <sys/param.h>
31 #include <sys/sockio.h>
32 #include <sys/sysctl.h>
33 #include <sys/mbuf.h>
34 #include <sys/kernel.h>
35 #include <sys/socket.h>
36 #include <sys/systm.h>
37 #include <sys/malloc.h>
38 #include <sys/conf.h>
39 #include <sys/kauth.h>
40 #include <sys/proc.h>
41 #include <sys/cprng.h>
42 
43 #include <sys/bus.h>
44 #include <machine/endian.h>
45 #include <sys/intr.h>
46 
47 #include <dev/firmload.h>
48 
49 #include <dev/pci/pcireg.h>
50 #include <dev/pci/pcivar.h>
51 #include <dev/pci/pcidevs.h>
52 
53 #include <net/bpf.h>
54 #include <net/if.h>
55 #include <net/if_arp.h>
56 #include <net/if_dl.h>
57 #include <net/if_ether.h>
58 #include <net/if_media.h>
59 #include <net/if_types.h>
60 
61 #include <net80211/ieee80211_var.h>
62 #include <net80211/ieee80211_radiotap.h>
63 
64 #include <netinet/in.h>
65 #include <netinet/in_systm.h>
66 #include <netinet/in_var.h>
67 #include <netinet/ip.h>
68 
69 #include <dev/pci/if_iwireg.h>
70 #include <dev/pci/if_iwivar.h>
71 
72 #ifdef IWI_DEBUG
73 #define DPRINTF(x)	if (iwi_debug > 0) printf x
74 #define DPRINTFN(n, x)	if (iwi_debug >= (n)) printf x
75 int iwi_debug = 4;
76 #else
77 #define DPRINTF(x)
78 #define DPRINTFN(n, x)
79 #endif
80 
81 /* Permit loading the Intel firmware */
82 static int iwi_accept_eula;
83 
84 static int	iwi_match(device_t, cfdata_t, void *);
85 static void	iwi_attach(device_t, device_t, void *);
86 static int	iwi_detach(device_t, int);
87 
88 static int	iwi_alloc_cmd_ring(struct iwi_softc *, struct iwi_cmd_ring *,
89     int);
90 static void	iwi_reset_cmd_ring(struct iwi_softc *, struct iwi_cmd_ring *);
91 static void	iwi_free_cmd_ring(struct iwi_softc *, struct iwi_cmd_ring *);
92 static int	iwi_alloc_tx_ring(struct iwi_softc *, struct iwi_tx_ring *,
93     int, bus_size_t, bus_size_t);
94 static void	iwi_reset_tx_ring(struct iwi_softc *, struct iwi_tx_ring *);
95 static void	iwi_free_tx_ring(struct iwi_softc *, struct iwi_tx_ring *);
96 static struct mbuf *
97 		iwi_alloc_rx_buf(struct iwi_softc *sc);
98 static int	iwi_alloc_rx_ring(struct iwi_softc *, struct iwi_rx_ring *,
99     int);
100 static void	iwi_reset_rx_ring(struct iwi_softc *, struct iwi_rx_ring *);
101 static void	iwi_free_rx_ring(struct iwi_softc *, struct iwi_rx_ring *);
102 
103 static struct	ieee80211_node *iwi_node_alloc(struct ieee80211_node_table *);
104 static void	iwi_node_free(struct ieee80211_node *);
105 
106 static int	iwi_cvtrate(int);
107 static int	iwi_media_change(struct ifnet *);
108 static void	iwi_media_status(struct ifnet *, struct ifmediareq *);
109 static int	iwi_wme_update(struct ieee80211com *);
110 static uint16_t	iwi_read_prom_word(struct iwi_softc *, uint8_t);
111 static int	iwi_newstate(struct ieee80211com *, enum ieee80211_state, int);
112 static void	iwi_fix_channel(struct ieee80211com *, struct mbuf *);
113 static void	iwi_frame_intr(struct iwi_softc *, struct iwi_rx_data *, int,
114     struct iwi_frame *);
115 static void	iwi_notification_intr(struct iwi_softc *, struct iwi_notif *);
116 static void	iwi_cmd_intr(struct iwi_softc *);
117 static void	iwi_rx_intr(struct iwi_softc *);
118 static void	iwi_tx_intr(struct iwi_softc *, struct iwi_tx_ring *);
119 static int	iwi_intr(void *);
120 static void	iwi_softintr(void *);
121 static int	iwi_cmd(struct iwi_softc *, uint8_t, void *, uint8_t, int);
122 static void	iwi_write_ibssnode(struct iwi_softc *, const struct iwi_node *);
123 static int	iwi_tx_start(struct ifnet *, struct mbuf *, struct ieee80211_node *,
124     int);
125 static void	iwi_start(struct ifnet *);
126 static void	iwi_watchdog(struct ifnet *);
127 
128 static int	iwi_alloc_unr(struct iwi_softc *);
129 static void	iwi_free_unr(struct iwi_softc *, int);
130 
131 static int	iwi_get_table0(struct iwi_softc *, uint32_t *);
132 
133 static int	iwi_ioctl(struct ifnet *, u_long, void *);
134 static void	iwi_stop_master(struct iwi_softc *);
135 static int	iwi_reset(struct iwi_softc *);
136 static int	iwi_load_ucode(struct iwi_softc *, void *, int);
137 static int	iwi_load_firmware(struct iwi_softc *, void *, int);
138 static int	iwi_cache_firmware(struct iwi_softc *);
139 static void	iwi_free_firmware(struct iwi_softc *);
140 static int	iwi_config(struct iwi_softc *);
141 static int	iwi_set_chan(struct iwi_softc *, struct ieee80211_channel *);
142 static int	iwi_scan(struct iwi_softc *);
143 static int	iwi_auth_and_assoc(struct iwi_softc *);
144 static int	iwi_init(struct ifnet *);
145 static void	iwi_stop(struct ifnet *, int);
146 static int	iwi_getrfkill(struct iwi_softc *);
147 static void	iwi_led_set(struct iwi_softc *, uint32_t, int);
148 static void	iwi_sysctlattach(struct iwi_softc *);
149 
150 /*
151  * Supported rates for 802.11a/b/g modes (in 500Kbps unit).
152  */
153 static const struct ieee80211_rateset iwi_rateset_11a =
154 	{ 8, { 12, 18, 24, 36, 48, 72, 96, 108 } };
155 
156 static const struct ieee80211_rateset iwi_rateset_11b =
157 	{ 4, { 2, 4, 11, 22 } };
158 
159 static const struct ieee80211_rateset iwi_rateset_11g =
160 	{ 12, { 2, 4, 11, 22, 12, 18, 24, 36, 48, 72, 96, 108 } };
161 
162 static inline uint8_t
163 MEM_READ_1(struct iwi_softc *sc, uint32_t addr)
164 {
165 	CSR_WRITE_4(sc, IWI_CSR_INDIRECT_ADDR, addr);
166 	return CSR_READ_1(sc, IWI_CSR_INDIRECT_DATA);
167 }
168 
169 static inline uint32_t
170 MEM_READ_4(struct iwi_softc *sc, uint32_t addr)
171 {
172 	CSR_WRITE_4(sc, IWI_CSR_INDIRECT_ADDR, addr);
173 	return CSR_READ_4(sc, IWI_CSR_INDIRECT_DATA);
174 }
175 
176 CFATTACH_DECL_NEW(iwi, sizeof (struct iwi_softc), iwi_match, iwi_attach,
177     iwi_detach, NULL);
178 
179 static int
180 iwi_match(device_t parent, cfdata_t match, void *aux)
181 {
182 	struct pci_attach_args *pa = aux;
183 
184 	if (PCI_VENDOR(pa->pa_id) != PCI_VENDOR_INTEL)
185 		return 0;
186 
187 	if (PCI_PRODUCT(pa->pa_id) == PCI_PRODUCT_INTEL_PRO_WL_2200BG ||
188 	    PCI_PRODUCT(pa->pa_id) == PCI_PRODUCT_INTEL_PRO_WL_2225BG ||
189 	    PCI_PRODUCT(pa->pa_id) == PCI_PRODUCT_INTEL_PRO_WL_2915ABG_1 ||
190 	    PCI_PRODUCT(pa->pa_id) == PCI_PRODUCT_INTEL_PRO_WL_2915ABG_2)
191 		return 1;
192 
193 	return 0;
194 }
195 
196 /* Base Address Register */
197 #define IWI_PCI_BAR0	0x10
198 
199 static void
200 iwi_attach(device_t parent, device_t self, void *aux)
201 {
202 	struct iwi_softc *sc = device_private(self);
203 	struct ieee80211com *ic = &sc->sc_ic;
204 	struct ifnet *ifp = &sc->sc_if;
205 	struct pci_attach_args *pa = aux;
206 	const char *intrstr;
207 	bus_space_tag_t memt;
208 	bus_space_handle_t memh;
209 	pci_intr_handle_t ih;
210 	pcireg_t data;
211 	uint16_t val;
212 	int error, i;
213 	char intrbuf[PCI_INTRSTR_LEN];
214 
215 	sc->sc_dev = self;
216 	sc->sc_pct = pa->pa_pc;
217 	sc->sc_pcitag = pa->pa_tag;
218 
219 	pci_aprint_devinfo(pa, NULL);
220 
221 	/* clear unit numbers allocated to IBSS */
222 	sc->sc_unr = 0;
223 
224 	/* power up chip */
225 	if ((error = pci_activate(pa->pa_pc, pa->pa_tag, self,
226 	    NULL)) && error != EOPNOTSUPP) {
227 		aprint_error_dev(self, "cannot activate %d\n", error);
228 		return;
229 	}
230 
231 	/* clear device specific PCI configuration register 0x41 */
232 	data = pci_conf_read(sc->sc_pct, sc->sc_pcitag, 0x40);
233 	data &= ~0x0000ff00;
234 	pci_conf_write(sc->sc_pct, sc->sc_pcitag, 0x40, data);
235 
236 
237 	/* enable bus-mastering */
238 	data = pci_conf_read(sc->sc_pct, sc->sc_pcitag, PCI_COMMAND_STATUS_REG);
239 	data |= PCI_COMMAND_MASTER_ENABLE;
240 	pci_conf_write(sc->sc_pct, sc->sc_pcitag, PCI_COMMAND_STATUS_REG, data);
241 
242 	/* map the register window */
243 	error = pci_mapreg_map(pa, IWI_PCI_BAR0, PCI_MAPREG_TYPE_MEM |
244 	    PCI_MAPREG_MEM_TYPE_32BIT, 0, &memt, &memh, NULL, &sc->sc_sz);
245 	if (error != 0) {
246 		aprint_error_dev(self, "could not map memory space\n");
247 		return;
248 	}
249 
250 	sc->sc_st = memt;
251 	sc->sc_sh = memh;
252 	sc->sc_dmat = pa->pa_dmat;
253 
254 	/* disable interrupts */
255 	CSR_WRITE_4(sc, IWI_CSR_INTR_MASK, 0);
256 
257 	sc->sc_soft_ih = softint_establish(SOFTINT_NET, iwi_softintr, sc);
258 	if (sc->sc_soft_ih == NULL) {
259 		aprint_error_dev(self, "could not establish softint\n");
260 		return;
261 	}
262 
263 	if (pci_intr_map(pa, &ih) != 0) {
264 		softint_disestablish(sc->sc_soft_ih);
265 		sc->sc_soft_ih = NULL;
266 		aprint_error_dev(self, "could not map interrupt\n");
267 		return;
268 	}
269 
270 	intrstr = pci_intr_string(sc->sc_pct, ih, intrbuf, sizeof(intrbuf));
271 	sc->sc_ih = pci_intr_establish(sc->sc_pct, ih, IPL_NET, iwi_intr, sc);
272 	if (sc->sc_ih == NULL) {
273 		softint_disestablish(sc->sc_soft_ih);
274 		sc->sc_soft_ih = NULL;
275 		aprint_error_dev(self, "could not establish interrupt");
276 		if (intrstr != NULL)
277 			aprint_error(" at %s", intrstr);
278 		aprint_error("\n");
279 		return;
280 	}
281 	aprint_normal_dev(self, "interrupting at %s\n", intrstr);
282 
283 	if (iwi_reset(sc) != 0) {
284 		pci_intr_disestablish(sc->sc_pct, sc->sc_ih);
285 		softint_disestablish(sc->sc_soft_ih);
286 		sc->sc_soft_ih = NULL;
287 		aprint_error_dev(self, "could not reset adapter\n");
288 		return;
289 	}
290 
291 	ic->ic_ifp = ifp;
292 	ic->ic_wme.wme_update = iwi_wme_update;
293 	ic->ic_phytype = IEEE80211_T_OFDM; /* not only, but not used */
294 	ic->ic_opmode = IEEE80211_M_STA; /* default to BSS mode */
295 	ic->ic_state = IEEE80211_S_INIT;
296 
297 	sc->sc_fwname = "ipw2200-bss.fw";
298 
299 	/* set device capabilities */
300 	ic->ic_caps =
301 	    IEEE80211_C_IBSS |		/* IBSS mode supported */
302 	    IEEE80211_C_MONITOR |	/* monitor mode supported */
303 	    IEEE80211_C_TXPMGT |	/* tx power management */
304 	    IEEE80211_C_SHPREAMBLE |	/* short preamble supported */
305 	    IEEE80211_C_SHSLOT |	/* short slot time supported */
306 	    IEEE80211_C_WPA |		/* 802.11i */
307 	    IEEE80211_C_WME;		/* 802.11e */
308 
309 	/* read MAC address from EEPROM */
310 	val = iwi_read_prom_word(sc, IWI_EEPROM_MAC + 0);
311 	ic->ic_myaddr[0] = val & 0xff;
312 	ic->ic_myaddr[1] = val >> 8;
313 	val = iwi_read_prom_word(sc, IWI_EEPROM_MAC + 1);
314 	ic->ic_myaddr[2] = val & 0xff;
315 	ic->ic_myaddr[3] = val >> 8;
316 	val = iwi_read_prom_word(sc, IWI_EEPROM_MAC + 2);
317 	ic->ic_myaddr[4] = val & 0xff;
318 	ic->ic_myaddr[5] = val >> 8;
319 
320 	aprint_verbose_dev(self, "802.11 address %s\n",
321 	    ether_sprintf(ic->ic_myaddr));
322 
323 	/* read the NIC type from EEPROM */
324 	val = iwi_read_prom_word(sc, IWI_EEPROM_NIC_TYPE);
325 	sc->nictype = val & 0xff;
326 
327 	DPRINTF(("%s: NIC type %d\n", device_xname(self), sc->nictype));
328 
329 	if (PCI_PRODUCT(pa->pa_id) == PCI_PRODUCT_INTEL_PRO_WL_2915ABG_1 ||
330 	    PCI_PRODUCT(pa->pa_id) == PCI_PRODUCT_INTEL_PRO_WL_2915ABG_2) {
331 		/* set supported .11a rates (2915ABG only) */
332 		ic->ic_sup_rates[IEEE80211_MODE_11A] = iwi_rateset_11a;
333 
334 		/* set supported .11a channels */
335 		for (i = 36; i <= 64; i += 4) {
336 			ic->ic_channels[i].ic_freq =
337 			    ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
338 			ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
339 		}
340 		for (i = 149; i <= 165; i += 4) {
341 			ic->ic_channels[i].ic_freq =
342 			    ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
343 			ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
344 		}
345 	}
346 
347 	/* set supported .11b and .11g rates */
348 	ic->ic_sup_rates[IEEE80211_MODE_11B] = iwi_rateset_11b;
349 	ic->ic_sup_rates[IEEE80211_MODE_11G] = iwi_rateset_11g;
350 
351 	/* set supported .11b and .11g channels (1 through 14) */
352 	for (i = 1; i <= 14; i++) {
353 		ic->ic_channels[i].ic_freq =
354 		    ieee80211_ieee2mhz(i, IEEE80211_CHAN_2GHZ);
355 		ic->ic_channels[i].ic_flags =
356 		    IEEE80211_CHAN_CCK | IEEE80211_CHAN_OFDM |
357 		    IEEE80211_CHAN_DYN | IEEE80211_CHAN_2GHZ;
358 	}
359 
360 	ifp->if_softc = sc;
361 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
362 	ifp->if_init = iwi_init;
363 	ifp->if_stop = iwi_stop;
364 	ifp->if_ioctl = iwi_ioctl;
365 	ifp->if_start = iwi_start;
366 	ifp->if_watchdog = iwi_watchdog;
367 	IFQ_SET_READY(&ifp->if_snd);
368 	memcpy(ifp->if_xname, device_xname(self), IFNAMSIZ);
369 
370 	error = if_initialize(ifp);
371 	if (error != 0) {
372 		ifp->if_softc = NULL; /* For iwi_detach() */
373 		aprint_error_dev(sc->sc_dev, "if_initialize failed(%d)\n",
374 		    error);
375 		goto fail;
376 	}
377 	ieee80211_ifattach(ic);
378 	/* Use common softint-based if_input */
379 	ifp->if_percpuq = if_percpuq_create(ifp);
380 	if_register(ifp);
381 
382 	/* override default methods */
383 	ic->ic_node_alloc = iwi_node_alloc;
384 	sc->sc_node_free = ic->ic_node_free;
385 	ic->ic_node_free = iwi_node_free;
386 	/* override state transition machine */
387 	sc->sc_newstate = ic->ic_newstate;
388 	ic->ic_newstate = iwi_newstate;
389 	ieee80211_media_init(ic, iwi_media_change, iwi_media_status);
390 
391 	/*
392 	 * Allocate rings.
393 	 */
394 	if (iwi_alloc_cmd_ring(sc, &sc->cmdq, IWI_CMD_RING_COUNT) != 0) {
395 		aprint_error_dev(self, "could not allocate command ring\n");
396 		goto fail;
397 	}
398 
399 	error = iwi_alloc_tx_ring(sc, &sc->txq[0], IWI_TX_RING_COUNT,
400 	    IWI_CSR_TX1_RIDX, IWI_CSR_TX1_WIDX);
401 	if (error != 0) {
402 		aprint_error_dev(self, "could not allocate Tx ring 1\n");
403 		goto fail;
404 	}
405 
406 	error = iwi_alloc_tx_ring(sc, &sc->txq[1], IWI_TX_RING_COUNT,
407 	    IWI_CSR_TX2_RIDX, IWI_CSR_TX2_WIDX);
408 	if (error != 0) {
409 		aprint_error_dev(self, "could not allocate Tx ring 2\n");
410 		goto fail;
411 	}
412 
413 	error = iwi_alloc_tx_ring(sc, &sc->txq[2], IWI_TX_RING_COUNT,
414 	    IWI_CSR_TX3_RIDX, IWI_CSR_TX3_WIDX);
415 	if (error != 0) {
416 		aprint_error_dev(self, "could not allocate Tx ring 3\n");
417 		goto fail;
418 	}
419 
420 	error = iwi_alloc_tx_ring(sc, &sc->txq[3], IWI_TX_RING_COUNT,
421 	    IWI_CSR_TX4_RIDX, IWI_CSR_TX4_WIDX);
422 	if (error != 0) {
423 		aprint_error_dev(self, "could not allocate Tx ring 4\n");
424 		goto fail;
425 	}
426 
427 	if (iwi_alloc_rx_ring(sc, &sc->rxq, IWI_RX_RING_COUNT) != 0) {
428 		aprint_error_dev(self, "could not allocate Rx ring\n");
429 		goto fail;
430 	}
431 
432 	bpf_attach2(ifp, DLT_IEEE802_11_RADIO,
433 	    sizeof(struct ieee80211_frame) + 64, &sc->sc_drvbpf);
434 
435 	sc->sc_rxtap_len = sizeof sc->sc_rxtapu;
436 	sc->sc_rxtap.wr_ihdr.it_len = htole16(sc->sc_rxtap_len);
437 	sc->sc_rxtap.wr_ihdr.it_present = htole32(IWI_RX_RADIOTAP_PRESENT);
438 
439 	sc->sc_txtap_len = sizeof sc->sc_txtapu;
440 	sc->sc_txtap.wt_ihdr.it_len = htole16(sc->sc_txtap_len);
441 	sc->sc_txtap.wt_ihdr.it_present = htole32(IWI_TX_RADIOTAP_PRESENT);
442 
443 	iwi_sysctlattach(sc);
444 
445 	if (pmf_device_register(self, NULL, NULL))
446 		pmf_class_network_register(self, ifp);
447 	else
448 		aprint_error_dev(self, "couldn't establish power handler\n");
449 
450 	ieee80211_announce(ic);
451 
452 	return;
453 
454 fail:	iwi_detach(self, 0);
455 }
456 
457 static int
458 iwi_detach(device_t self, int flags)
459 {
460 	struct iwi_softc *sc = device_private(self);
461 	struct ifnet *ifp = &sc->sc_if;
462 
463 	if (ifp->if_softc != NULL) {
464 		pmf_device_deregister(self);
465 		iwi_stop(ifp, 1);
466 		iwi_free_firmware(sc);
467 		ieee80211_ifdetach(&sc->sc_ic);
468 		if_detach(ifp);
469 	}
470 
471 	iwi_free_cmd_ring(sc, &sc->cmdq);
472 	iwi_free_tx_ring(sc, &sc->txq[0]);
473 	iwi_free_tx_ring(sc, &sc->txq[1]);
474 	iwi_free_tx_ring(sc, &sc->txq[2]);
475 	iwi_free_tx_ring(sc, &sc->txq[3]);
476 	iwi_free_rx_ring(sc, &sc->rxq);
477 
478 	if (sc->sc_ih != NULL) {
479 		pci_intr_disestablish(sc->sc_pct, sc->sc_ih);
480 		sc->sc_ih = NULL;
481 	}
482 
483 	if (sc->sc_soft_ih != NULL) {
484 		softint_disestablish(sc->sc_soft_ih);
485 		sc->sc_soft_ih = NULL;
486 	}
487 
488 	bus_space_unmap(sc->sc_st, sc->sc_sh, sc->sc_sz);
489 
490 	return 0;
491 }
492 
493 static int
494 iwi_alloc_cmd_ring(struct iwi_softc *sc, struct iwi_cmd_ring *ring,
495     int count)
496 {
497 	int error, nsegs;
498 
499 	ring->count = count;
500 	ring->queued = 0;
501 	ring->cur = ring->next = 0;
502 
503 	/*
504 	 * Allocate and map command ring
505 	 */
506 	error = bus_dmamap_create(sc->sc_dmat,
507 	    IWI_CMD_DESC_SIZE * count, 1,
508 	    IWI_CMD_DESC_SIZE * count, 0,
509 	    BUS_DMA_NOWAIT, &ring->desc_map);
510 	if (error != 0) {
511 		aprint_error_dev(sc->sc_dev,
512 		    "could not create command ring DMA map\n");
513 		ring->desc_map = NULL;
514 		goto fail;
515 	}
516 
517 	error = bus_dmamem_alloc(sc->sc_dmat,
518 	    IWI_CMD_DESC_SIZE * count, PAGE_SIZE, 0,
519 	    &sc->cmdq.desc_seg, 1, &nsegs, BUS_DMA_NOWAIT);
520 	if (error != 0) {
521 		aprint_error_dev(sc->sc_dev,
522 		    "could not allocate command ring DMA memory\n");
523 		goto fail;
524 	}
525 
526 	error = bus_dmamem_map(sc->sc_dmat, &sc->cmdq.desc_seg, nsegs,
527 	    IWI_CMD_DESC_SIZE * count,
528 	    (void **)&sc->cmdq.desc, BUS_DMA_NOWAIT);
529 	if (error != 0) {
530 		aprint_error_dev(sc->sc_dev,
531 		    "could not map command ring DMA memory\n");
532 		goto fail;
533 	}
534 
535 	error = bus_dmamap_load(sc->sc_dmat, sc->cmdq.desc_map, sc->cmdq.desc,
536 	    IWI_CMD_DESC_SIZE * count, NULL,
537 	    BUS_DMA_NOWAIT);
538 	if (error != 0) {
539 		aprint_error_dev(sc->sc_dev,
540 		    "could not load command ring DMA map\n");
541 		goto fail;
542 	}
543 
544 	memset(sc->cmdq.desc, 0,
545 	    IWI_CMD_DESC_SIZE * count);
546 
547 	return 0;
548 
549 fail:	return error;
550 }
551 
552 static void
553 iwi_reset_cmd_ring(struct iwi_softc *sc, struct iwi_cmd_ring *ring)
554 {
555 	int i;
556 
557 	for (i = ring->next; i != ring->cur;) {
558 		bus_dmamap_sync(sc->sc_dmat, sc->cmdq.desc_map,
559 		    i * IWI_CMD_DESC_SIZE, IWI_CMD_DESC_SIZE,
560 		    BUS_DMASYNC_POSTWRITE);
561 
562 		wakeup(&ring->desc[i]);
563 		i = (i + 1) % ring->count;
564 	}
565 
566 	ring->queued = 0;
567 	ring->cur = ring->next = 0;
568 }
569 
570 static void
571 iwi_free_cmd_ring(struct iwi_softc *sc, struct iwi_cmd_ring *ring)
572 {
573 	if (ring->desc_map != NULL) {
574 		if (ring->desc != NULL) {
575 			bus_dmamap_unload(sc->sc_dmat, ring->desc_map);
576 			bus_dmamem_unmap(sc->sc_dmat, (void *)ring->desc,
577 			    IWI_CMD_DESC_SIZE * ring->count);
578 			bus_dmamem_free(sc->sc_dmat, &ring->desc_seg, 1);
579 		}
580 		bus_dmamap_destroy(sc->sc_dmat, ring->desc_map);
581 	}
582 }
583 
584 static int
585 iwi_alloc_tx_ring(struct iwi_softc *sc, struct iwi_tx_ring *ring,
586     int count, bus_size_t csr_ridx, bus_size_t csr_widx)
587 {
588 	int i, error, nsegs;
589 
590 	ring->count  = 0;
591 	ring->queued = 0;
592 	ring->cur = ring->next = 0;
593 	ring->csr_ridx = csr_ridx;
594 	ring->csr_widx = csr_widx;
595 
596 	/*
597 	 * Allocate and map Tx ring
598 	 */
599 	error = bus_dmamap_create(sc->sc_dmat,
600 	    IWI_TX_DESC_SIZE * count, 1,
601 	    IWI_TX_DESC_SIZE * count, 0, BUS_DMA_NOWAIT,
602 	    &ring->desc_map);
603 	if (error != 0) {
604 		aprint_error_dev(sc->sc_dev,
605 		    "could not create tx ring DMA map\n");
606 		ring->desc_map = NULL;
607 		goto fail;
608 	}
609 
610 	error = bus_dmamem_alloc(sc->sc_dmat,
611 	    IWI_TX_DESC_SIZE * count, PAGE_SIZE, 0,
612 	    &ring->desc_seg, 1, &nsegs, BUS_DMA_NOWAIT);
613 	if (error != 0) {
614 		aprint_error_dev(sc->sc_dev,
615 		    "could not allocate tx ring DMA memory\n");
616 		goto fail;
617 	}
618 
619 	error = bus_dmamem_map(sc->sc_dmat, &ring->desc_seg, nsegs,
620 	    IWI_TX_DESC_SIZE * count,
621 	    (void **)&ring->desc, BUS_DMA_NOWAIT);
622 	if (error != 0) {
623 		aprint_error_dev(sc->sc_dev,
624 		    "could not map tx ring DMA memory\n");
625 		goto fail;
626 	}
627 
628 	error = bus_dmamap_load(sc->sc_dmat, ring->desc_map, ring->desc,
629 	    IWI_TX_DESC_SIZE * count, NULL,
630 	    BUS_DMA_NOWAIT);
631 	if (error != 0) {
632 		aprint_error_dev(sc->sc_dev,
633 		    "could not load tx ring DMA map\n");
634 		goto fail;
635 	}
636 
637 	memset(ring->desc, 0, IWI_TX_DESC_SIZE * count);
638 
639 	ring->data = malloc(count * sizeof (struct iwi_tx_data), M_DEVBUF,
640 	    M_NOWAIT | M_ZERO);
641 	if (ring->data == NULL) {
642 		aprint_error_dev(sc->sc_dev, "could not allocate soft data\n");
643 		error = ENOMEM;
644 		goto fail;
645 	}
646 	ring->count = count;
647 
648 	/*
649 	 * Allocate Tx buffers DMA maps
650 	 */
651 	for (i = 0; i < count; i++) {
652 		error = bus_dmamap_create(sc->sc_dmat, MCLBYTES, IWI_MAX_NSEG,
653 		    MCLBYTES, 0, BUS_DMA_NOWAIT, &ring->data[i].map);
654 		if (error != 0) {
655 			aprint_error_dev(sc->sc_dev,
656 			    "could not create tx buf DMA map");
657 			ring->data[i].map = NULL;
658 			goto fail;
659 		}
660 	}
661 	return 0;
662 
663 fail:	return error;
664 }
665 
666 static void
667 iwi_reset_tx_ring(struct iwi_softc *sc, struct iwi_tx_ring *ring)
668 {
669 	struct iwi_tx_data *data;
670 	int i;
671 
672 	for (i = 0; i < ring->count; i++) {
673 		data = &ring->data[i];
674 
675 		if (data->m != NULL) {
676 			m_freem(data->m);
677 			data->m = NULL;
678 		}
679 
680 		if (data->map != NULL) {
681 			bus_dmamap_sync(sc->sc_dmat, data->map, 0,
682 			    data->map->dm_mapsize, BUS_DMASYNC_POSTWRITE);
683 			bus_dmamap_unload(sc->sc_dmat, data->map);
684 		}
685 
686 		if (data->ni != NULL) {
687 			ieee80211_free_node(data->ni);
688 			data->ni = NULL;
689 		}
690 	}
691 
692 	ring->queued = 0;
693 	ring->cur = ring->next = 0;
694 }
695 
696 static void
697 iwi_free_tx_ring(struct iwi_softc *sc, struct iwi_tx_ring *ring)
698 {
699 	int i;
700 	struct iwi_tx_data *data;
701 
702 	if (ring->desc_map != NULL) {
703 		if (ring->desc != NULL) {
704 			bus_dmamap_unload(sc->sc_dmat, ring->desc_map);
705 			bus_dmamem_unmap(sc->sc_dmat, (void *)ring->desc,
706 			    IWI_TX_DESC_SIZE * ring->count);
707 			bus_dmamem_free(sc->sc_dmat, &ring->desc_seg, 1);
708 		}
709 		bus_dmamap_destroy(sc->sc_dmat, ring->desc_map);
710 	}
711 
712 	for (i = 0; i < ring->count; i++) {
713 		data = &ring->data[i];
714 
715 		if (data->m != NULL) {
716 			m_freem(data->m);
717 		}
718 
719 		if (data->map != NULL) {
720 			bus_dmamap_unload(sc->sc_dmat, data->map);
721 			bus_dmamap_destroy(sc->sc_dmat, data->map);
722 		}
723 	}
724 }
725 
726 static int
727 iwi_alloc_rx_ring(struct iwi_softc *sc, struct iwi_rx_ring *ring, int count)
728 {
729 	int i, error;
730 
731 	ring->count = 0;
732 	ring->cur = 0;
733 
734 	ring->data = malloc(count * sizeof (struct iwi_rx_data), M_DEVBUF,
735 	    M_NOWAIT | M_ZERO);
736 	if (ring->data == NULL) {
737 		aprint_error_dev(sc->sc_dev, "could not allocate soft data\n");
738 		error = ENOMEM;
739 		goto fail;
740 	}
741 
742 	ring->count = count;
743 
744 	/*
745 	 * Allocate and map Rx buffers
746 	 */
747 	for (i = 0; i < count; i++) {
748 
749 		error = bus_dmamap_create(sc->sc_dmat, MCLBYTES, 1, MCLBYTES,
750 		    0, BUS_DMA_WAITOK | BUS_DMA_ALLOCNOW, &ring->data[i].map);
751 		if (error != 0) {
752 			aprint_error_dev(sc->sc_dev,
753 			    "could not create rx buf DMA map");
754 			ring->data[i].map = NULL;
755 			goto fail;
756 		}
757 
758 		if ((ring->data[i].m = iwi_alloc_rx_buf(sc)) == NULL) {
759 			error = ENOMEM;
760 			goto fail;
761 		}
762 
763 		error = bus_dmamap_load_mbuf(sc->sc_dmat, ring->data[i].map,
764 		    ring->data[i].m, BUS_DMA_READ | BUS_DMA_NOWAIT);
765 		if (error != 0) {
766 			aprint_error_dev(sc->sc_dev,
767 			    "could not load rx buffer DMA map\n");
768 			goto fail;
769 		}
770 
771 		bus_dmamap_sync(sc->sc_dmat, ring->data[i].map, 0,
772 		    ring->data[i].map->dm_mapsize, BUS_DMASYNC_PREREAD);
773 	}
774 
775 	return 0;
776 
777 fail:	return error;
778 }
779 
780 static void
781 iwi_reset_rx_ring(struct iwi_softc *sc, struct iwi_rx_ring *ring)
782 {
783 	ring->cur = 0;
784 }
785 
786 static void
787 iwi_free_rx_ring(struct iwi_softc *sc, struct iwi_rx_ring *ring)
788 {
789 	int i;
790 	struct iwi_rx_data *data;
791 
792 	for (i = 0; i < ring->count; i++) {
793 		data = &ring->data[i];
794 
795 		if (data->m != NULL) {
796 			m_freem(data->m);
797 		}
798 
799 		if (data->map != NULL) {
800 			bus_dmamap_unload(sc->sc_dmat, data->map);
801 			bus_dmamap_destroy(sc->sc_dmat, data->map);
802 		}
803 
804 	}
805 }
806 
807 static struct ieee80211_node *
808 iwi_node_alloc(struct ieee80211_node_table *nt)
809 {
810 	struct iwi_node *in;
811 
812 	in = malloc(sizeof (struct iwi_node), M_80211_NODE, M_NOWAIT | M_ZERO);
813 	if (in == NULL)
814 		return NULL;
815 
816 	in->in_station = -1;
817 
818 	return &in->in_node;
819 }
820 
821 static int
822 iwi_alloc_unr(struct iwi_softc *sc)
823 {
824 	int i;
825 
826 	for (i = 0; i < IWI_MAX_IBSSNODE - 1; i++)
827 		if ((sc->sc_unr & (1 << i)) == 0) {
828 			sc->sc_unr |= 1 << i;
829 			return i;
830 		}
831 
832 	return -1;
833 }
834 
835 static void
836 iwi_free_unr(struct iwi_softc *sc, int r)
837 {
838 
839 	sc->sc_unr &= 1 << r;
840 }
841 
842 static void
843 iwi_node_free(struct ieee80211_node *ni)
844 {
845 	struct ieee80211com *ic = ni->ni_ic;
846 	struct iwi_softc *sc = ic->ic_ifp->if_softc;
847 	struct iwi_node *in = (struct iwi_node *)ni;
848 
849 	if (in->in_station != -1)
850 		iwi_free_unr(sc, in->in_station);
851 
852 	sc->sc_node_free(ni);
853 }
854 
855 static int
856 iwi_media_change(struct ifnet *ifp)
857 {
858 	int error;
859 
860 	error = ieee80211_media_change(ifp);
861 	if (error != ENETRESET)
862 		return error;
863 
864 	if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) == (IFF_UP | IFF_RUNNING))
865 		iwi_init(ifp);
866 
867 	return 0;
868 }
869 
870 /*
871  * Convert h/w rate code to IEEE rate code.
872  */
873 static int
874 iwi_cvtrate(int iwirate)
875 {
876 	switch (iwirate) {
877 	case IWI_RATE_DS1:	return 2;
878 	case IWI_RATE_DS2:	return 4;
879 	case IWI_RATE_DS5:	return 11;
880 	case IWI_RATE_DS11:	return 22;
881 	case IWI_RATE_OFDM6:	return 12;
882 	case IWI_RATE_OFDM9:	return 18;
883 	case IWI_RATE_OFDM12:	return 24;
884 	case IWI_RATE_OFDM18:	return 36;
885 	case IWI_RATE_OFDM24:	return 48;
886 	case IWI_RATE_OFDM36:	return 72;
887 	case IWI_RATE_OFDM48:	return 96;
888 	case IWI_RATE_OFDM54:	return 108;
889 	}
890 	return 0;
891 }
892 
893 /*
894  * The firmware automatically adapts the transmit speed.  We report its current
895  * value here.
896  */
897 static void
898 iwi_media_status(struct ifnet *ifp, struct ifmediareq *imr)
899 {
900 	struct iwi_softc *sc = ifp->if_softc;
901 	struct ieee80211com *ic = &sc->sc_ic;
902 	int rate;
903 
904 	imr->ifm_status = IFM_AVALID;
905 	imr->ifm_active = IFM_IEEE80211;
906 	if (ic->ic_state == IEEE80211_S_RUN)
907 		imr->ifm_status |= IFM_ACTIVE;
908 
909 	/* read current transmission rate from adapter */
910 	rate = iwi_cvtrate(CSR_READ_4(sc, IWI_CSR_CURRENT_TX_RATE));
911 	imr->ifm_active |= ieee80211_rate2media(ic, rate, ic->ic_curmode);
912 
913 	switch (ic->ic_opmode) {
914 	case IEEE80211_M_STA:
915 		break;
916 
917 	case IEEE80211_M_IBSS:
918 		imr->ifm_active |= IFM_IEEE80211_ADHOC;
919 		break;
920 
921 	case IEEE80211_M_MONITOR:
922 		imr->ifm_active |= IFM_IEEE80211_MONITOR;
923 		break;
924 
925 	case IEEE80211_M_AHDEMO:
926 	case IEEE80211_M_HOSTAP:
927 		/* should not get there */
928 		break;
929 	}
930 }
931 
932 static int
933 iwi_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
934 {
935 	struct iwi_softc *sc = ic->ic_ifp->if_softc;
936 
937 	DPRINTF(("%s: %s -> %s flags 0x%x\n", __func__,
938 	    ieee80211_state_name[ic->ic_state],
939 	    ieee80211_state_name[nstate], sc->flags));
940 
941 	switch (nstate) {
942 	case IEEE80211_S_SCAN:
943 		if (sc->flags & IWI_FLAG_SCANNING)
944 			break;
945 
946 		ieee80211_node_table_reset(&ic->ic_scan);
947 		ic->ic_flags |= IEEE80211_F_SCAN | IEEE80211_F_ASCAN;
948 		sc->flags |= IWI_FLAG_SCANNING;
949 		/* blink the led while scanning */
950 		iwi_led_set(sc, IWI_LED_ASSOCIATED, 1);
951 		iwi_scan(sc);
952 		break;
953 
954 	case IEEE80211_S_AUTH:
955 		iwi_auth_and_assoc(sc);
956 		break;
957 
958 	case IEEE80211_S_RUN:
959 		if (ic->ic_opmode == IEEE80211_M_IBSS &&
960 		    ic->ic_state == IEEE80211_S_SCAN)
961 			iwi_auth_and_assoc(sc);
962 		else if (ic->ic_opmode == IEEE80211_M_MONITOR)
963 			iwi_set_chan(sc, ic->ic_ibss_chan);
964 		break;
965 	case IEEE80211_S_ASSOC:
966 		iwi_led_set(sc, IWI_LED_ASSOCIATED, 0);
967 		if (ic->ic_state == IEEE80211_S_AUTH)
968 			break;
969 		iwi_auth_and_assoc(sc);
970 		break;
971 
972 	case IEEE80211_S_INIT:
973 		sc->flags &= ~IWI_FLAG_SCANNING;
974 		break;
975 	}
976 
977 	return sc->sc_newstate(ic, nstate, arg);
978 }
979 
980 /*
981  * WME parameters coming from IEEE 802.11e specification.  These values are
982  * already declared in ieee80211_proto.c, but they are static so they can't
983  * be reused here.
984  */
985 static const struct wmeParams iwi_wme_cck_params[WME_NUM_AC] = {
986 	{ 0, 3, 5,  7,   0, 0, },	/* WME_AC_BE */
987 	{ 0, 3, 5, 10,   0, 0, },	/* WME_AC_BK */
988 	{ 0, 2, 4,  5, 188, 0, },	/* WME_AC_VI */
989 	{ 0, 2, 3,  4, 102, 0, },	/* WME_AC_VO */
990 };
991 
992 static const struct wmeParams iwi_wme_ofdm_params[WME_NUM_AC] = {
993 	{ 0, 3, 4,  6,   0, 0, },	/* WME_AC_BE */
994 	{ 0, 3, 4, 10,   0, 0, },	/* WME_AC_BK */
995 	{ 0, 2, 3,  4,  94, 0, },	/* WME_AC_VI */
996 	{ 0, 2, 2,  3,  47, 0, },	/* WME_AC_VO */
997 };
998 
999 static int
1000 iwi_wme_update(struct ieee80211com *ic)
1001 {
1002 #define IWI_EXP2(v)	htole16((1 << (v)) - 1)
1003 #define IWI_USEC(v)	htole16(IEEE80211_TXOP_TO_US(v))
1004 	struct iwi_softc *sc = ic->ic_ifp->if_softc;
1005 	struct iwi_wme_params wme[3];
1006 	const struct wmeParams *wmep;
1007 	int ac;
1008 
1009 	/*
1010 	 * We shall not override firmware default WME values if WME is not
1011 	 * actually enabled.
1012 	 */
1013 	if (!(ic->ic_flags & IEEE80211_F_WME))
1014 		return 0;
1015 
1016 	for (ac = 0; ac < WME_NUM_AC; ac++) {
1017 		/* set WME values for current operating mode */
1018 		wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
1019 		wme[0].aifsn[ac] = wmep->wmep_aifsn;
1020 		wme[0].cwmin[ac] = IWI_EXP2(wmep->wmep_logcwmin);
1021 		wme[0].cwmax[ac] = IWI_EXP2(wmep->wmep_logcwmax);
1022 		wme[0].burst[ac] = IWI_USEC(wmep->wmep_txopLimit);
1023 		wme[0].acm[ac]   = wmep->wmep_acm;
1024 
1025 		/* set WME values for CCK modulation */
1026 		wmep = &iwi_wme_cck_params[ac];
1027 		wme[1].aifsn[ac] = wmep->wmep_aifsn;
1028 		wme[1].cwmin[ac] = IWI_EXP2(wmep->wmep_logcwmin);
1029 		wme[1].cwmax[ac] = IWI_EXP2(wmep->wmep_logcwmax);
1030 		wme[1].burst[ac] = IWI_USEC(wmep->wmep_txopLimit);
1031 		wme[1].acm[ac]   = wmep->wmep_acm;
1032 
1033 		/* set WME values for OFDM modulation */
1034 		wmep = &iwi_wme_ofdm_params[ac];
1035 		wme[2].aifsn[ac] = wmep->wmep_aifsn;
1036 		wme[2].cwmin[ac] = IWI_EXP2(wmep->wmep_logcwmin);
1037 		wme[2].cwmax[ac] = IWI_EXP2(wmep->wmep_logcwmax);
1038 		wme[2].burst[ac] = IWI_USEC(wmep->wmep_txopLimit);
1039 		wme[2].acm[ac]   = wmep->wmep_acm;
1040 	}
1041 
1042 	DPRINTF(("Setting WME parameters\n"));
1043 	return iwi_cmd(sc, IWI_CMD_SET_WME_PARAMS, wme, sizeof wme, 1);
1044 #undef IWI_USEC
1045 #undef IWI_EXP2
1046 }
1047 
1048 /*
1049  * Read 16 bits at address 'addr' from the serial EEPROM.
1050  */
1051 static uint16_t
1052 iwi_read_prom_word(struct iwi_softc *sc, uint8_t addr)
1053 {
1054 	uint32_t tmp;
1055 	uint16_t val;
1056 	int n;
1057 
1058 	/* Clock C once before the first command */
1059 	IWI_EEPROM_CTL(sc, 0);
1060 	IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1061 	IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_C);
1062 	IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1063 
1064 	/* Write start bit (1) */
1065 	IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_D);
1066 	IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_D | IWI_EEPROM_C);
1067 
1068 	/* Write READ opcode (10) */
1069 	IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_D);
1070 	IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_D | IWI_EEPROM_C);
1071 	IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1072 	IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_C);
1073 
1074 	/* Write address A7-A0 */
1075 	for (n = 7; n >= 0; n--) {
1076 		IWI_EEPROM_CTL(sc, IWI_EEPROM_S |
1077 		    (((addr >> n) & 1) << IWI_EEPROM_SHIFT_D));
1078 		IWI_EEPROM_CTL(sc, IWI_EEPROM_S |
1079 		    (((addr >> n) & 1) << IWI_EEPROM_SHIFT_D) | IWI_EEPROM_C);
1080 	}
1081 
1082 	IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1083 
1084 	/* Read data Q15-Q0 */
1085 	val = 0;
1086 	for (n = 15; n >= 0; n--) {
1087 		IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_C);
1088 		IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1089 		tmp = MEM_READ_4(sc, IWI_MEM_EEPROM_CTL);
1090 		val |= ((tmp & IWI_EEPROM_Q) >> IWI_EEPROM_SHIFT_Q) << n;
1091 	}
1092 
1093 	IWI_EEPROM_CTL(sc, 0);
1094 
1095 	/* Clear Chip Select and clock C */
1096 	IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1097 	IWI_EEPROM_CTL(sc, 0);
1098 	IWI_EEPROM_CTL(sc, IWI_EEPROM_C);
1099 
1100 	return val;
1101 }
1102 
1103 /*
1104  * XXX: Hack to set the current channel to the value advertised in beacons or
1105  * probe responses. Only used during AP detection.
1106  */
1107 static void
1108 iwi_fix_channel(struct ieee80211com *ic, struct mbuf *m)
1109 {
1110 	struct ieee80211_frame *wh;
1111 	uint8_t subtype;
1112 	uint8_t *frm, *efrm;
1113 
1114 	wh = mtod(m, struct ieee80211_frame *);
1115 
1116 	if ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) != IEEE80211_FC0_TYPE_MGT)
1117 		return;
1118 
1119 	subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
1120 
1121 	if (subtype != IEEE80211_FC0_SUBTYPE_BEACON &&
1122 	    subtype != IEEE80211_FC0_SUBTYPE_PROBE_RESP)
1123 		return;
1124 
1125 	frm = (uint8_t *)(wh + 1);
1126 	efrm = mtod(m, uint8_t *) + m->m_len;
1127 
1128 	frm += 12;	/* skip tstamp, bintval and capinfo fields */
1129 	while (frm + 2 < efrm) {
1130 		if (*frm == IEEE80211_ELEMID_DSPARMS) {
1131 #if IEEE80211_CHAN_MAX < 255
1132 			if (frm[2] <= IEEE80211_CHAN_MAX)
1133 #endif
1134 				ic->ic_curchan = &ic->ic_channels[frm[2]];
1135 		}
1136 
1137 		frm += frm[1] + 2;
1138 	}
1139 }
1140 
1141 static struct mbuf *
1142 iwi_alloc_rx_buf(struct iwi_softc *sc)
1143 {
1144 	struct mbuf *m;
1145 
1146 	MGETHDR(m, M_DONTWAIT, MT_DATA);
1147 	if (m == NULL) {
1148 		aprint_error_dev(sc->sc_dev, "could not allocate rx mbuf\n");
1149 		return NULL;
1150 	}
1151 
1152 	MCLGET(m, M_DONTWAIT);
1153 	if (!(m->m_flags & M_EXT)) {
1154 		aprint_error_dev(sc->sc_dev,
1155 		    "could not allocate rx mbuf cluster\n");
1156 		m_freem(m);
1157 		return NULL;
1158 	}
1159 
1160 	m->m_pkthdr.len = m->m_len = m->m_ext.ext_size;
1161 	return m;
1162 }
1163 
1164 static void
1165 iwi_frame_intr(struct iwi_softc *sc, struct iwi_rx_data *data, int i,
1166     struct iwi_frame *frame)
1167 {
1168 	struct ieee80211com *ic = &sc->sc_ic;
1169 	struct ifnet *ifp = ic->ic_ifp;
1170 	struct mbuf *m, *m_new;
1171 	struct ieee80211_frame *wh;
1172 	struct ieee80211_node *ni;
1173 	int error, s;
1174 
1175 	DPRINTFN(5, ("received frame len=%u chan=%u rssi=%u\n",
1176 	    le16toh(frame->len), frame->chan, frame->rssi_dbm));
1177 
1178 	if (le16toh(frame->len) < sizeof (struct ieee80211_frame) ||
1179 	    le16toh(frame->len) > MCLBYTES) {
1180 		DPRINTF(("%s: bad frame length\n", device_xname(sc->sc_dev)));
1181 		ifp->if_ierrors++;
1182 		return;
1183 	}
1184 
1185 	/*
1186 	 * Try to allocate a new mbuf for this ring element and
1187 	 * load it before processing the current mbuf. If the ring
1188 	 * element cannot be reloaded, drop the received packet
1189 	 * and reuse the old mbuf. In the unlikely case that
1190 	 * the old mbuf can't be reloaded either, explicitly panic.
1191 	 *
1192 	 * XXX Reorganize buffer by moving elements from the logical
1193 	 * end of the ring to the front instead of dropping.
1194 	 */
1195 	if ((m_new = iwi_alloc_rx_buf(sc)) == NULL) {
1196 		ifp->if_ierrors++;
1197 		return;
1198 	}
1199 
1200 	bus_dmamap_unload(sc->sc_dmat, data->map);
1201 
1202 	error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m_new,
1203 	    BUS_DMA_READ | BUS_DMA_NOWAIT);
1204 	if (error != 0) {
1205 		aprint_error_dev(sc->sc_dev,
1206 		    "could not load rx buf DMA map\n");
1207 		m_freem(m_new);
1208 		ifp->if_ierrors++;
1209 		error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map,
1210 		    data->m, BUS_DMA_READ | BUS_DMA_NOWAIT);
1211 		if (error)
1212 			panic("%s: unable to remap rx buf",
1213 			    device_xname(sc->sc_dev));
1214 		return;
1215 	}
1216 
1217 	/*
1218 	 * New mbuf successfully loaded, update RX ring and continue
1219 	 * processing.
1220 	 */
1221 	m = data->m;
1222 	data->m = m_new;
1223 	CSR_WRITE_4(sc, IWI_CSR_RX_BASE + i * 4, data->map->dm_segs[0].ds_addr);
1224 
1225 	/* Finalize mbuf */
1226 	m_set_rcvif(m, ifp);
1227 	m->m_pkthdr.len = m->m_len = sizeof (struct iwi_hdr) +
1228 	    sizeof (struct iwi_frame) + le16toh(frame->len);
1229 
1230 	m_adj(m, sizeof (struct iwi_hdr) + sizeof (struct iwi_frame));
1231 
1232 	s = splnet();
1233 
1234 	if (ic->ic_state == IEEE80211_S_SCAN)
1235 		iwi_fix_channel(ic, m);
1236 
1237 	if (sc->sc_drvbpf != NULL) {
1238 		struct iwi_rx_radiotap_header *tap = &sc->sc_rxtap;
1239 
1240 		tap->wr_flags = 0;
1241 		tap->wr_rate = iwi_cvtrate(frame->rate);
1242 		tap->wr_chan_freq =
1243 		    htole16(ic->ic_channels[frame->chan].ic_freq);
1244 		tap->wr_chan_flags =
1245 		    htole16(ic->ic_channels[frame->chan].ic_flags);
1246 		tap->wr_antsignal = frame->signal;
1247 		tap->wr_antenna = frame->antenna;
1248 
1249 		bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_rxtap_len, m);
1250 	}
1251 	wh = mtod(m, struct ieee80211_frame *);
1252 	ni = ieee80211_find_rxnode(ic, (struct ieee80211_frame_min *)wh);
1253 
1254 	/* Send the frame to the upper layer */
1255 	ieee80211_input(ic, m, ni, frame->rssi_dbm, 0);
1256 
1257 	/* node is no longer needed */
1258 	ieee80211_free_node(ni);
1259 
1260 	splx(s);
1261 }
1262 
1263 static void
1264 iwi_notification_intr(struct iwi_softc *sc, struct iwi_notif *notif)
1265 {
1266 	struct ieee80211com *ic = &sc->sc_ic;
1267 	struct iwi_notif_authentication *auth;
1268 	struct iwi_notif_association *assoc;
1269 	struct iwi_notif_beacon_state *beacon;
1270 	int s;
1271 
1272 	switch (notif->type) {
1273 	case IWI_NOTIF_TYPE_SCAN_CHANNEL:
1274 #ifdef IWI_DEBUG
1275 		{
1276 			struct iwi_notif_scan_channel *chan =
1277 			    (struct iwi_notif_scan_channel *)(notif + 1);
1278 
1279 			DPRINTFN(2, ("Scan of channel %u complete (%u)\n",
1280 			    ic->ic_channels[chan->nchan].ic_freq, chan->nchan));
1281 		}
1282 #endif
1283 		break;
1284 
1285 	case IWI_NOTIF_TYPE_SCAN_COMPLETE:
1286 #ifdef IWI_DEBUG
1287 		{
1288 			struct iwi_notif_scan_complete *scan =
1289 			    (struct iwi_notif_scan_complete *)(notif + 1);
1290 
1291 			DPRINTFN(2, ("Scan completed (%u, %u)\n", scan->nchan,
1292 			    scan->status));
1293 		}
1294 #endif
1295 
1296 		/* monitor mode uses scan to set the channel ... */
1297 		s = splnet();
1298 		if (ic->ic_opmode != IEEE80211_M_MONITOR) {
1299 			sc->flags &= ~IWI_FLAG_SCANNING;
1300 			ieee80211_end_scan(ic);
1301 		} else
1302 			iwi_set_chan(sc, ic->ic_ibss_chan);
1303 		splx(s);
1304 		break;
1305 
1306 	case IWI_NOTIF_TYPE_AUTHENTICATION:
1307 		auth = (struct iwi_notif_authentication *)(notif + 1);
1308 
1309 		DPRINTFN(2, ("Authentication (%u)\n", auth->state));
1310 
1311 		switch (auth->state) {
1312 		case IWI_AUTH_SUCCESS:
1313 			s = splnet();
1314 			ieee80211_node_authorize(ic->ic_bss);
1315 			ieee80211_new_state(ic, IEEE80211_S_ASSOC, -1);
1316 			splx(s);
1317 			break;
1318 
1319 		case IWI_AUTH_FAIL:
1320 			break;
1321 
1322 		case IWI_AUTH_SENT_1:
1323 		case IWI_AUTH_RECV_2:
1324 		case IWI_AUTH_SEQ1_PASS:
1325 			break;
1326 
1327 		case IWI_AUTH_SEQ1_FAIL:
1328 			break;
1329 
1330 		default:
1331 			aprint_error_dev(sc->sc_dev,
1332 			    "unknown authentication state %u\n", auth->state);
1333 		}
1334 		break;
1335 
1336 	case IWI_NOTIF_TYPE_ASSOCIATION:
1337 		assoc = (struct iwi_notif_association *)(notif + 1);
1338 
1339 		DPRINTFN(2, ("Association (%u, %u)\n", assoc->state,
1340 		    assoc->status));
1341 
1342 		switch (assoc->state) {
1343 		case IWI_AUTH_SUCCESS:
1344 			/* re-association, do nothing */
1345 			break;
1346 
1347 		case IWI_ASSOC_SUCCESS:
1348 			s = splnet();
1349 			ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
1350 			splx(s);
1351 			break;
1352 
1353 		case IWI_ASSOC_FAIL:
1354 			s = splnet();
1355 			ieee80211_begin_scan(ic, 1);
1356 			splx(s);
1357 			break;
1358 
1359 		default:
1360 			aprint_error_dev(sc->sc_dev,
1361 			    "unknown association state %u\n", assoc->state);
1362 		}
1363 		break;
1364 
1365 	case IWI_NOTIF_TYPE_BEACON:
1366 		beacon = (struct iwi_notif_beacon_state *)(notif + 1);
1367 
1368 		if (beacon->state == IWI_BEACON_MISS) {
1369 			DPRINTFN(5, ("%s: %u beacon(s) missed\n",
1370 			    device_xname(sc->sc_dev), le32toh(beacon->number)));
1371 		}
1372 		break;
1373 
1374 	case IWI_NOTIF_TYPE_FRAG_LENGTH:
1375 	case IWI_NOTIF_TYPE_LINK_QUALITY:
1376 	case IWI_NOTIF_TYPE_TGI_TX_KEY:
1377 	case IWI_NOTIF_TYPE_CALIBRATION:
1378 	case IWI_NOTIF_TYPE_NOISE:
1379 		DPRINTFN(5, ("Notification (%u)\n", notif->type));
1380 		break;
1381 
1382 	default:
1383 		DPRINTF(("%s: unknown notification type %u flags 0x%x len %d\n",
1384 		    device_xname(sc->sc_dev), notif->type, notif->flags,
1385 		    le16toh(notif->len)));
1386 	}
1387 }
1388 
1389 static void
1390 iwi_cmd_intr(struct iwi_softc *sc)
1391 {
1392 
1393 	(void)CSR_READ_4(sc, IWI_CSR_CMD_RIDX);
1394 
1395 	bus_dmamap_sync(sc->sc_dmat, sc->cmdq.desc_map,
1396 	    sc->cmdq.next * IWI_CMD_DESC_SIZE, IWI_CMD_DESC_SIZE,
1397 	    BUS_DMASYNC_POSTWRITE);
1398 
1399 	wakeup(&sc->cmdq.desc[sc->cmdq.next]);
1400 
1401 	sc->cmdq.next = (sc->cmdq.next + 1) % sc->cmdq.count;
1402 
1403 	if (--sc->cmdq.queued > 0) {
1404 		CSR_WRITE_4(sc, IWI_CSR_CMD_WIDX,
1405 		    (sc->cmdq.next + 1) % sc->cmdq.count);
1406 	}
1407 }
1408 
1409 static void
1410 iwi_rx_intr(struct iwi_softc *sc)
1411 {
1412 	struct iwi_rx_data *data;
1413 	struct iwi_hdr *hdr;
1414 	uint32_t hw;
1415 
1416 	hw = CSR_READ_4(sc, IWI_CSR_RX_RIDX);
1417 
1418 	for (; sc->rxq.cur != hw;) {
1419 		data = &sc->rxq.data[sc->rxq.cur];
1420 
1421 		bus_dmamap_sync(sc->sc_dmat, data->map, 0,
1422 		    data->map->dm_mapsize, BUS_DMASYNC_POSTREAD);
1423 
1424 		hdr = mtod(data->m, struct iwi_hdr *);
1425 
1426 		switch (hdr->type) {
1427 		case IWI_HDR_TYPE_FRAME:
1428 			iwi_frame_intr(sc, data, sc->rxq.cur,
1429 			    (struct iwi_frame *)(hdr + 1));
1430 			break;
1431 
1432 		case IWI_HDR_TYPE_NOTIF:
1433 			iwi_notification_intr(sc,
1434 			    (struct iwi_notif *)(hdr + 1));
1435 			break;
1436 
1437 		default:
1438 			aprint_error_dev(sc->sc_dev, "unknown hdr type %u\n",
1439 			    hdr->type);
1440 		}
1441 
1442 		bus_dmamap_sync(sc->sc_dmat, data->map, 0,
1443 		    data->map->dm_mapsize, BUS_DMASYNC_PREREAD);
1444 
1445 		DPRINTFN(15, ("rx done idx=%u\n", sc->rxq.cur));
1446 
1447 		sc->rxq.cur = (sc->rxq.cur + 1) % sc->rxq.count;
1448 	}
1449 
1450 	/* Tell the firmware what we have processed */
1451 	hw = (hw == 0) ? sc->rxq.count - 1 : hw - 1;
1452 	CSR_WRITE_4(sc, IWI_CSR_RX_WIDX, hw);
1453 }
1454 
1455 static void
1456 iwi_tx_intr(struct iwi_softc *sc, struct iwi_tx_ring *txq)
1457 {
1458 	struct ifnet *ifp = &sc->sc_if;
1459 	struct iwi_tx_data *data;
1460 	uint32_t hw;
1461 	int s;
1462 
1463 	s = splnet();
1464 
1465 	hw = CSR_READ_4(sc, txq->csr_ridx);
1466 
1467 	for (; txq->next != hw;) {
1468 		data = &txq->data[txq->next];
1469 
1470 		bus_dmamap_sync(sc->sc_dmat, data->map, 0,
1471 		    data->map->dm_mapsize, BUS_DMASYNC_POSTWRITE);
1472 		bus_dmamap_unload(sc->sc_dmat, data->map);
1473 		m_freem(data->m);
1474 		data->m = NULL;
1475 		ieee80211_free_node(data->ni);
1476 		data->ni = NULL;
1477 
1478 		DPRINTFN(15, ("tx done idx=%u\n", txq->next));
1479 
1480 		ifp->if_opackets++;
1481 
1482 		txq->queued--;
1483 		txq->next = (txq->next + 1) % txq->count;
1484 	}
1485 
1486 	sc->sc_tx_timer = 0;
1487 
1488 	if (txq->queued < txq->count - 8 - 8 && (ifp->if_flags & IFF_OACTIVE)) {
1489 		ifp->if_flags &= ~IFF_OACTIVE;
1490 
1491 		/* Call start() since some buffer descriptors have been released */
1492 		iwi_start(ifp); /* in softint */
1493 	}
1494 
1495 	splx(s);
1496 }
1497 
1498 static int
1499 iwi_intr(void *arg)
1500 {
1501 	struct iwi_softc *sc = arg;
1502 	uint32_t r;
1503 
1504 	if ((r = CSR_READ_4(sc, IWI_CSR_INTR)) == 0 || r == 0xffffffff)
1505 		return 0;
1506 
1507 	/* Disable interrupts */
1508 	CSR_WRITE_4(sc, IWI_CSR_INTR_MASK, 0);
1509 
1510 	softint_schedule(sc->sc_soft_ih);
1511 	return 1;
1512 }
1513 
1514 static void
1515 iwi_softintr(void *arg)
1516 {
1517 	struct iwi_softc *sc = arg;
1518 	uint32_t r;
1519 	int s;
1520 
1521 	if ((r = CSR_READ_4(sc, IWI_CSR_INTR)) == 0 || r == 0xffffffff)
1522 		goto out;
1523 
1524 	/* Acknowledge interrupts */
1525 	CSR_WRITE_4(sc, IWI_CSR_INTR, r);
1526 
1527 	if (r & IWI_INTR_FATAL_ERROR) {
1528 		aprint_error_dev(sc->sc_dev, "fatal error\n");
1529 		s = splnet();
1530 		sc->sc_ic.ic_ifp->if_flags &= ~IFF_UP;
1531 		iwi_stop(&sc->sc_if, 1);
1532 		splx(s);
1533 		return;
1534 	}
1535 
1536 	if (r & IWI_INTR_FW_INITED) {
1537 		if (!(r & (IWI_INTR_FATAL_ERROR | IWI_INTR_PARITY_ERROR)))
1538 			wakeup(sc);
1539 	}
1540 
1541 	if (r & IWI_INTR_RADIO_OFF) {
1542 		DPRINTF(("radio transmitter off\n"));
1543 		s = splnet();
1544 		sc->sc_ic.ic_ifp->if_flags &= ~IFF_UP;
1545 		iwi_stop(&sc->sc_if, 1);
1546 		splx(s);
1547 		return;
1548 	}
1549 
1550 	if (r & IWI_INTR_CMD_DONE)
1551 		iwi_cmd_intr(sc);
1552 
1553 	if (r & IWI_INTR_TX1_DONE)
1554 		iwi_tx_intr(sc, &sc->txq[0]);
1555 
1556 	if (r & IWI_INTR_TX2_DONE)
1557 		iwi_tx_intr(sc, &sc->txq[1]);
1558 
1559 	if (r & IWI_INTR_TX3_DONE)
1560 		iwi_tx_intr(sc, &sc->txq[2]);
1561 
1562 	if (r & IWI_INTR_TX4_DONE)
1563 		iwi_tx_intr(sc, &sc->txq[3]);
1564 
1565 	if (r & IWI_INTR_RX_DONE)
1566 		iwi_rx_intr(sc);
1567 
1568 	if (r & IWI_INTR_PARITY_ERROR)
1569 		aprint_error_dev(sc->sc_dev, "parity error\n");
1570 
1571  out:
1572 	/* Re-enable interrupts */
1573 	CSR_WRITE_4(sc, IWI_CSR_INTR_MASK, IWI_INTR_MASK);
1574 }
1575 
1576 static int
1577 iwi_cmd(struct iwi_softc *sc, uint8_t type, void *data, uint8_t len,
1578     int async)
1579 {
1580 	struct iwi_cmd_desc *desc;
1581 
1582 	desc = &sc->cmdq.desc[sc->cmdq.cur];
1583 
1584 	desc->hdr.type = IWI_HDR_TYPE_COMMAND;
1585 	desc->hdr.flags = IWI_HDR_FLAG_IRQ;
1586 	desc->type = type;
1587 	desc->len = len;
1588 	memcpy(desc->data, data, len);
1589 
1590 	bus_dmamap_sync(sc->sc_dmat, sc->cmdq.desc_map,
1591 	    sc->cmdq.cur * IWI_CMD_DESC_SIZE,
1592 	    IWI_CMD_DESC_SIZE, BUS_DMASYNC_PREWRITE);
1593 
1594 	DPRINTFN(2, ("sending command idx=%u type=%u len=%u async=%d\n",
1595 	    sc->cmdq.cur, type, len, async));
1596 
1597 	sc->cmdq.cur = (sc->cmdq.cur + 1) % sc->cmdq.count;
1598 
1599 	if (++sc->cmdq.queued == 1)
1600 		CSR_WRITE_4(sc, IWI_CSR_CMD_WIDX, sc->cmdq.cur);
1601 
1602 	return async ? 0 : tsleep(desc, 0, "iwicmd", hz);
1603 }
1604 
1605 static void
1606 iwi_write_ibssnode(struct iwi_softc *sc, const struct iwi_node *in)
1607 {
1608 	struct iwi_ibssnode node;
1609 
1610 	/* write node information into NIC memory */
1611 	memset(&node, 0, sizeof node);
1612 	IEEE80211_ADDR_COPY(node.bssid, in->in_node.ni_macaddr);
1613 
1614 	CSR_WRITE_REGION_1(sc,
1615 	    IWI_CSR_NODE_BASE + in->in_station * sizeof node,
1616 	    (uint8_t *)&node, sizeof node);
1617 }
1618 
1619 static int
1620 iwi_tx_start(struct ifnet *ifp, struct mbuf *m0, struct ieee80211_node *ni,
1621     int ac)
1622 {
1623 	struct iwi_softc *sc = ifp->if_softc;
1624 	struct ieee80211com *ic = &sc->sc_ic;
1625 	struct iwi_node *in = (struct iwi_node *)ni;
1626 	struct ieee80211_frame *wh;
1627 	struct ieee80211_key *k;
1628 	const struct chanAccParams *cap;
1629 	struct iwi_tx_ring *txq = &sc->txq[ac];
1630 	struct iwi_tx_data *data;
1631 	struct iwi_tx_desc *desc;
1632 	struct mbuf *mnew;
1633 	int error, hdrlen, i, noack = 0;
1634 
1635 	wh = mtod(m0, struct ieee80211_frame *);
1636 
1637 	if (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_QOS) {
1638 		hdrlen = sizeof (struct ieee80211_qosframe);
1639 		cap = &ic->ic_wme.wme_chanParams;
1640 		noack = cap->cap_wmeParams[ac].wmep_noackPolicy;
1641 	} else
1642 		hdrlen = sizeof (struct ieee80211_frame);
1643 
1644 	/*
1645 	 * This is only used in IBSS mode where the firmware expect an index
1646 	 * in a h/w table instead of a destination address.
1647 	 */
1648 	if (ic->ic_opmode == IEEE80211_M_IBSS && in->in_station == -1) {
1649 		in->in_station = iwi_alloc_unr(sc);
1650 
1651 		if (in->in_station == -1) {	/* h/w table is full */
1652 			m_freem(m0);
1653 			ieee80211_free_node(ni);
1654 			ifp->if_oerrors++;
1655 			return 0;
1656 		}
1657 		iwi_write_ibssnode(sc, in);
1658 	}
1659 
1660 	if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1661 		k = ieee80211_crypto_encap(ic, ni, m0);
1662 		if (k == NULL) {
1663 			m_freem(m0);
1664 			return ENOBUFS;
1665 		}
1666 
1667 		/* packet header may have moved, reset our local pointer */
1668 		wh = mtod(m0, struct ieee80211_frame *);
1669 	}
1670 
1671 	if (sc->sc_drvbpf != NULL) {
1672 		struct iwi_tx_radiotap_header *tap = &sc->sc_txtap;
1673 
1674 		tap->wt_flags = 0;
1675 		tap->wt_chan_freq = htole16(ic->ic_ibss_chan->ic_freq);
1676 		tap->wt_chan_flags = htole16(ic->ic_ibss_chan->ic_flags);
1677 
1678 		bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_txtap_len, m0);
1679 	}
1680 
1681 	data = &txq->data[txq->cur];
1682 	desc = &txq->desc[txq->cur];
1683 
1684 	/* save and trim IEEE802.11 header */
1685 	m_copydata(m0, 0, hdrlen, (void *)&desc->wh);
1686 	m_adj(m0, hdrlen);
1687 
1688 	error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m0,
1689 	    BUS_DMA_WRITE | BUS_DMA_NOWAIT);
1690 	if (error != 0 && error != EFBIG) {
1691 		aprint_error_dev(sc->sc_dev, "could not map mbuf (error %d)\n",
1692 		    error);
1693 		m_freem(m0);
1694 		return error;
1695 	}
1696 	if (error != 0) {
1697 		/* too many fragments, linearize */
1698 
1699 		MGETHDR(mnew, M_DONTWAIT, MT_DATA);
1700 		if (mnew == NULL) {
1701 			m_freem(m0);
1702 			return ENOMEM;
1703 		}
1704 
1705 		M_COPY_PKTHDR(mnew, m0);
1706 
1707 		/* If the data won't fit in the header, get a cluster */
1708 		if (m0->m_pkthdr.len > MHLEN) {
1709 			MCLGET(mnew, M_DONTWAIT);
1710 			if (!(mnew->m_flags & M_EXT)) {
1711 				m_freem(m0);
1712 				m_freem(mnew);
1713 				return ENOMEM;
1714 			}
1715 		}
1716 		m_copydata(m0, 0, m0->m_pkthdr.len, mtod(mnew, void *));
1717 		m_freem(m0);
1718 		mnew->m_len = mnew->m_pkthdr.len;
1719 		m0 = mnew;
1720 
1721 		error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m0,
1722 		    BUS_DMA_WRITE | BUS_DMA_NOWAIT);
1723 		if (error != 0) {
1724 			aprint_error_dev(sc->sc_dev,
1725 			    "could not map mbuf (error %d)\n", error);
1726 			m_freem(m0);
1727 			return error;
1728 		}
1729 	}
1730 
1731 	data->m = m0;
1732 	data->ni = ni;
1733 
1734 	desc->hdr.type = IWI_HDR_TYPE_DATA;
1735 	desc->hdr.flags = IWI_HDR_FLAG_IRQ;
1736 	desc->station =
1737 	    (ic->ic_opmode == IEEE80211_M_IBSS) ? in->in_station : 0;
1738 	desc->cmd = IWI_DATA_CMD_TX;
1739 	desc->len = htole16(m0->m_pkthdr.len);
1740 	desc->flags = 0;
1741 	desc->xflags = 0;
1742 
1743 	if (!noack && !IEEE80211_IS_MULTICAST(desc->wh.i_addr1))
1744 		desc->flags |= IWI_DATA_FLAG_NEED_ACK;
1745 
1746 #if 0
1747 	if (ic->ic_flags & IEEE80211_F_PRIVACY) {
1748 		desc->wh.i_fc[1] |= IEEE80211_FC1_WEP;
1749 		desc->wep_txkey = ic->ic_crypto.cs_def_txkey;
1750 	} else
1751 #endif
1752 		desc->flags |= IWI_DATA_FLAG_NO_WEP;
1753 
1754 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
1755 		desc->flags |= IWI_DATA_FLAG_SHPREAMBLE;
1756 
1757 	if (desc->wh.i_fc[0] & IEEE80211_FC0_SUBTYPE_QOS)
1758 		desc->xflags |= IWI_DATA_XFLAG_QOS;
1759 
1760 	if (ic->ic_curmode == IEEE80211_MODE_11B)
1761 		desc->xflags |= IWI_DATA_XFLAG_CCK;
1762 
1763 	desc->nseg = htole32(data->map->dm_nsegs);
1764 	for (i = 0; i < data->map->dm_nsegs; i++) {
1765 		desc->seg_addr[i] = htole32(data->map->dm_segs[i].ds_addr);
1766 		desc->seg_len[i]  = htole16(data->map->dm_segs[i].ds_len);
1767 	}
1768 
1769 	bus_dmamap_sync(sc->sc_dmat, txq->desc_map,
1770 	    txq->cur * IWI_TX_DESC_SIZE,
1771 	    IWI_TX_DESC_SIZE, BUS_DMASYNC_PREWRITE);
1772 
1773 	bus_dmamap_sync(sc->sc_dmat, data->map, 0, data->map->dm_mapsize,
1774 	    BUS_DMASYNC_PREWRITE);
1775 
1776 	DPRINTFN(5, ("sending data frame txq=%u idx=%u len=%u nseg=%u\n",
1777 	    ac, txq->cur, le16toh(desc->len), le32toh(desc->nseg)));
1778 
1779 	/* Inform firmware about this new packet */
1780 	txq->queued++;
1781 	txq->cur = (txq->cur + 1) % txq->count;
1782 	CSR_WRITE_4(sc, txq->csr_widx, txq->cur);
1783 
1784 	return 0;
1785 }
1786 
1787 static void
1788 iwi_start(struct ifnet *ifp)
1789 {
1790 	struct iwi_softc *sc = ifp->if_softc;
1791 	struct ieee80211com *ic = &sc->sc_ic;
1792 	struct mbuf *m0;
1793 	struct ether_header *eh;
1794 	struct ieee80211_node *ni;
1795 	int ac;
1796 
1797 	if (ic->ic_state != IEEE80211_S_RUN)
1798 		return;
1799 
1800 	for (;;) {
1801 		IFQ_DEQUEUE(&ifp->if_snd, m0);
1802 		if (m0 == NULL)
1803 			break;
1804 
1805 		if (m0->m_len < sizeof (struct ether_header) &&
1806 		    (m0 = m_pullup(m0, sizeof (struct ether_header))) == NULL) {
1807 			ifp->if_oerrors++;
1808 			continue;
1809 		}
1810 
1811 		eh = mtod(m0, struct ether_header *);
1812 		ni = ieee80211_find_txnode(ic, eh->ether_dhost);
1813 		if (ni == NULL) {
1814 			m_freem(m0);
1815 			ifp->if_oerrors++;
1816 			continue;
1817 		}
1818 
1819 		/* classify mbuf so we can find which tx ring to use */
1820 		if (ieee80211_classify(ic, m0, ni) != 0) {
1821 			m_freem(m0);
1822 			ieee80211_free_node(ni);
1823 			ifp->if_oerrors++;
1824 			continue;
1825 		}
1826 
1827 		/* no QoS encapsulation for EAPOL frames */
1828 		ac = (eh->ether_type != htons(ETHERTYPE_PAE)) ?
1829 		    M_WME_GETAC(m0) : WME_AC_BE;
1830 
1831 		if (sc->txq[ac].queued > sc->txq[ac].count - 8) {
1832 			/* there is no place left in this ring */
1833 			IFQ_LOCK(&ifp->if_snd);
1834 			IF_PREPEND(&ifp->if_snd, m0);
1835 			IFQ_UNLOCK(&ifp->if_snd);
1836 			ifp->if_flags |= IFF_OACTIVE;
1837 			break;
1838 		}
1839 
1840 		bpf_mtap(ifp, m0);
1841 
1842 		m0 = ieee80211_encap(ic, m0, ni);
1843 		if (m0 == NULL) {
1844 			ieee80211_free_node(ni);
1845 			ifp->if_oerrors++;
1846 			continue;
1847 		}
1848 
1849 		bpf_mtap3(ic->ic_rawbpf, m0);
1850 
1851 		if (iwi_tx_start(ifp, m0, ni, ac) != 0) {
1852 			ieee80211_free_node(ni);
1853 			ifp->if_oerrors++;
1854 			break;
1855 		}
1856 
1857 		/* start watchdog timer */
1858 		sc->sc_tx_timer = 5;
1859 		ifp->if_timer = 1;
1860 	}
1861 }
1862 
1863 static void
1864 iwi_watchdog(struct ifnet *ifp)
1865 {
1866 	struct iwi_softc *sc = ifp->if_softc;
1867 
1868 	ifp->if_timer = 0;
1869 
1870 	if (sc->sc_tx_timer > 0) {
1871 		if (--sc->sc_tx_timer == 0) {
1872 			aprint_error_dev(sc->sc_dev, "device timeout\n");
1873 			ifp->if_oerrors++;
1874 			ifp->if_flags &= ~IFF_UP;
1875 			iwi_stop(ifp, 1);
1876 			return;
1877 		}
1878 		ifp->if_timer = 1;
1879 	}
1880 
1881 	ieee80211_watchdog(&sc->sc_ic);
1882 }
1883 
1884 static int
1885 iwi_get_table0(struct iwi_softc *sc, uint32_t *tbl)
1886 {
1887 	uint32_t size, buf[128];
1888 
1889 	if (!(sc->flags & IWI_FLAG_FW_INITED)) {
1890 		memset(buf, 0, sizeof buf);
1891 		return copyout(buf, tbl, sizeof buf);
1892 	}
1893 
1894 	size = min(CSR_READ_4(sc, IWI_CSR_TABLE0_SIZE), 128 - 1);
1895 	CSR_READ_REGION_4(sc, IWI_CSR_TABLE0_BASE, &buf[1], size);
1896 
1897 	return copyout(buf, tbl, sizeof buf);
1898 }
1899 
1900 static int
1901 iwi_ioctl(struct ifnet *ifp, u_long cmd, void *data)
1902 {
1903 #define	IS_RUNNING(ifp) \
1904 	((ifp->if_flags & IFF_UP) && (ifp->if_flags & IFF_RUNNING))
1905 
1906 	struct iwi_softc *sc = ifp->if_softc;
1907 	struct ieee80211com *ic = &sc->sc_ic;
1908 	struct ifreq *ifr = (struct ifreq *)data;
1909 	int s, error = 0;
1910 	int val;
1911 
1912 	s = splnet();
1913 
1914 	switch (cmd) {
1915 	case SIOCSIFFLAGS:
1916 		if ((error = ifioctl_common(ifp, cmd, data)) != 0)
1917 			break;
1918 		if (ifp->if_flags & IFF_UP) {
1919 			if (!(ifp->if_flags & IFF_RUNNING))
1920 				iwi_init(ifp);
1921 		} else {
1922 			if (ifp->if_flags & IFF_RUNNING)
1923 				iwi_stop(ifp, 1);
1924 		}
1925 		break;
1926 
1927 	case SIOCADDMULTI:
1928 	case SIOCDELMULTI:
1929 		/* XXX no h/w multicast filter? --dyoung */
1930 		if ((error = ether_ioctl(ifp, cmd, data)) == ENETRESET) {
1931 			/* setup multicast filter, etc */
1932 			error = 0;
1933 		}
1934 		break;
1935 
1936 	case SIOCGTABLE0:
1937 		error = iwi_get_table0(sc, (uint32_t *)ifr->ifr_data);
1938 		break;
1939 
1940 	case SIOCGRADIO:
1941 		val = !iwi_getrfkill(sc);
1942 		error = copyout(&val, (int *)ifr->ifr_data, sizeof val);
1943 		break;
1944 
1945 	case SIOCSIFMEDIA:
1946 		if (ifr->ifr_media & IFM_IEEE80211_ADHOC) {
1947 			sc->sc_fwname = "ipw2200-ibss.fw";
1948 		} else if (ifr->ifr_media & IFM_IEEE80211_MONITOR) {
1949 			sc->sc_fwname = "ipw2200-sniffer.fw";
1950 		} else {
1951 			sc->sc_fwname = "ipw2200-bss.fw";
1952 		}
1953 		error = iwi_cache_firmware(sc);
1954 		if (error)
1955  			break;
1956  		/* FALLTRHOUGH */
1957 
1958 	default:
1959 		error = ieee80211_ioctl(&sc->sc_ic, cmd, data);
1960 
1961 		if (error == ENETRESET) {
1962 			if (IS_RUNNING(ifp) &&
1963 			    (ic->ic_roaming != IEEE80211_ROAMING_MANUAL))
1964 				iwi_init(ifp);
1965 			error = 0;
1966 		}
1967 	}
1968 
1969 	splx(s);
1970 	return error;
1971 #undef IS_RUNNING
1972 }
1973 
1974 static void
1975 iwi_stop_master(struct iwi_softc *sc)
1976 {
1977 	int ntries;
1978 
1979 	/* Disable interrupts */
1980 	CSR_WRITE_4(sc, IWI_CSR_INTR_MASK, 0);
1981 
1982 	CSR_WRITE_4(sc, IWI_CSR_RST, IWI_RST_STOP_MASTER);
1983 	for (ntries = 0; ntries < 5; ntries++) {
1984 		if (CSR_READ_4(sc, IWI_CSR_RST) & IWI_RST_MASTER_DISABLED)
1985 			break;
1986 		DELAY(10);
1987 	}
1988 	if (ntries == 5)
1989 		aprint_error_dev(sc->sc_dev, "timeout waiting for master\n");
1990 
1991 	CSR_WRITE_4(sc, IWI_CSR_RST, CSR_READ_4(sc, IWI_CSR_RST) |
1992 	    IWI_RST_PRINCETON_RESET);
1993 
1994 	sc->flags &= ~IWI_FLAG_FW_INITED;
1995 }
1996 
1997 static int
1998 iwi_reset(struct iwi_softc *sc)
1999 {
2000 	int i, ntries;
2001 
2002 	iwi_stop_master(sc);
2003 
2004 	/* Move adapter to D0 state */
2005 	CSR_WRITE_4(sc, IWI_CSR_CTL, CSR_READ_4(sc, IWI_CSR_CTL) |
2006 	    IWI_CTL_INIT);
2007 
2008 	/* Initialize Phase-Locked Level  (PLL) */
2009 	CSR_WRITE_4(sc, IWI_CSR_READ_INT, IWI_READ_INT_INIT_HOST);
2010 
2011 	/* Wait for clock stabilization */
2012 	for (ntries = 0; ntries < 1000; ntries++) {
2013 		if (CSR_READ_4(sc, IWI_CSR_CTL) & IWI_CTL_CLOCK_READY)
2014 			break;
2015 		DELAY(200);
2016 	}
2017 	if (ntries == 1000) {
2018 		aprint_error_dev(sc->sc_dev,
2019 		    "timeout waiting for clock stabilization\n");
2020 		return ETIMEDOUT;
2021 	}
2022 
2023 	CSR_WRITE_4(sc, IWI_CSR_RST, CSR_READ_4(sc, IWI_CSR_RST) |
2024 	    IWI_RST_SW_RESET);
2025 
2026 	DELAY(10);
2027 
2028 	CSR_WRITE_4(sc, IWI_CSR_CTL, CSR_READ_4(sc, IWI_CSR_CTL) |
2029 	    IWI_CTL_INIT);
2030 
2031 	/* Clear NIC memory */
2032 	CSR_WRITE_4(sc, IWI_CSR_AUTOINC_ADDR, 0);
2033 	for (i = 0; i < 0xc000; i++)
2034 		CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, 0);
2035 
2036 	return 0;
2037 }
2038 
2039 static int
2040 iwi_load_ucode(struct iwi_softc *sc, void *uc, int size)
2041 {
2042 	uint16_t *w;
2043 	int ntries, i;
2044 
2045 	CSR_WRITE_4(sc, IWI_CSR_RST, CSR_READ_4(sc, IWI_CSR_RST) |
2046 	    IWI_RST_STOP_MASTER);
2047 	for (ntries = 0; ntries < 5; ntries++) {
2048 		if (CSR_READ_4(sc, IWI_CSR_RST) & IWI_RST_MASTER_DISABLED)
2049 			break;
2050 		DELAY(10);
2051 	}
2052 	if (ntries == 5) {
2053 		aprint_error_dev(sc->sc_dev, "timeout waiting for master\n");
2054 		return ETIMEDOUT;
2055 	}
2056 
2057 	MEM_WRITE_4(sc, 0x3000e0, 0x80000000);
2058 	DELAY(5000);
2059 	CSR_WRITE_4(sc, IWI_CSR_RST, CSR_READ_4(sc, IWI_CSR_RST) &
2060 	    ~IWI_RST_PRINCETON_RESET);
2061 	DELAY(5000);
2062 	MEM_WRITE_4(sc, 0x3000e0, 0);
2063 	DELAY(1000);
2064 	MEM_WRITE_4(sc, 0x300004, 1);
2065 	DELAY(1000);
2066 	MEM_WRITE_4(sc, 0x300004, 0);
2067 	DELAY(1000);
2068 	MEM_WRITE_1(sc, 0x200000, 0x00);
2069 	MEM_WRITE_1(sc, 0x200000, 0x40);
2070 	DELAY(1000);
2071 
2072 	/* Adapter is buggy, we must set the address for each word */
2073 	for (w = uc; size > 0; w++, size -= 2)
2074 		MEM_WRITE_2(sc, 0x200010, htole16(*w));
2075 
2076 	MEM_WRITE_1(sc, 0x200000, 0x00);
2077 	MEM_WRITE_1(sc, 0x200000, 0x80);
2078 
2079 	/* Wait until we get a response in the uc queue */
2080 	for (ntries = 0; ntries < 100; ntries++) {
2081 		if (MEM_READ_1(sc, 0x200000) & 1)
2082 			break;
2083 		DELAY(100);
2084 	}
2085 	if (ntries == 100) {
2086 		aprint_error_dev(sc->sc_dev,
2087 		    "timeout waiting for ucode to initialize\n");
2088 		return ETIMEDOUT;
2089 	}
2090 
2091 	/* Empty the uc queue or the firmware will not initialize properly */
2092 	for (i = 0; i < 7; i++)
2093 		MEM_READ_4(sc, 0x200004);
2094 
2095 	MEM_WRITE_1(sc, 0x200000, 0x00);
2096 
2097 	return 0;
2098 }
2099 
2100 /* macro to handle unaligned little endian data in firmware image */
2101 #define GETLE32(p) ((p)[0] | (p)[1] << 8 | (p)[2] << 16 | (p)[3] << 24)
2102 static int
2103 iwi_load_firmware(struct iwi_softc *sc, void *fw, int size)
2104 {
2105 	bus_dmamap_t map;
2106 	u_char *p, *end;
2107 	uint32_t sentinel, ctl, sum;
2108 	uint32_t cs, sl, cd, cl;
2109 	int ntries, nsegs, error;
2110 	int sn;
2111 
2112 	nsegs = atop((vaddr_t)fw+size-1) - atop((vaddr_t)fw) + 1;
2113 
2114 	/* Create a DMA map for the firmware image */
2115 	error = bus_dmamap_create(sc->sc_dmat, size, nsegs, size, 0,
2116 	    BUS_DMA_NOWAIT, &map);
2117 	if (error != 0) {
2118 		aprint_error_dev(sc->sc_dev,
2119 		    "could not create firmware DMA map\n");
2120 		map = NULL;
2121 		goto fail1;
2122 	}
2123 
2124 	error = bus_dmamap_load(sc->sc_dmat, map, fw, size, NULL,
2125 	    BUS_DMA_NOWAIT | BUS_DMA_WRITE);
2126 	if (error != 0) {
2127 		aprint_error_dev(sc->sc_dev, "could not load fw dma map(%d)\n",
2128 		    error);
2129 		goto fail2;
2130 	}
2131 
2132 	/* Make sure the adapter will get up-to-date values */
2133 	bus_dmamap_sync(sc->sc_dmat, map, 0, size, BUS_DMASYNC_PREWRITE);
2134 
2135 	/* Tell the adapter where the command blocks are stored */
2136 	MEM_WRITE_4(sc, 0x3000a0, 0x27000);
2137 
2138 	/*
2139 	 * Store command blocks into adapter's internal memory using register
2140 	 * indirections. The adapter will read the firmware image through DMA
2141 	 * using information stored in command blocks.
2142 	 */
2143 	p = fw;
2144 	end = p + size;
2145 	CSR_WRITE_4(sc, IWI_CSR_AUTOINC_ADDR, 0x27000);
2146 
2147 	sn = 0;
2148 	sl = cl = 0;
2149 	cs = cd = 0;
2150 	while (p < end) {
2151 		if (sl == 0) {
2152 			cs = map->dm_segs[sn].ds_addr;
2153 			sl = map->dm_segs[sn].ds_len;
2154 			sn++;
2155 		}
2156 		if (cl == 0) {
2157 			cd = GETLE32(p); p += 4; cs += 4; sl -= 4;
2158 			cl = GETLE32(p); p += 4; cs += 4; sl -= 4;
2159 		}
2160 		while (sl > 0 && cl > 0) {
2161 			int len = min(cl, sl);
2162 
2163 			sl -= len;
2164 			cl -= len;
2165 			p += len;
2166 
2167 			while (len > 0) {
2168 				int mlen = min(len, IWI_CB_MAXDATALEN);
2169 
2170 				ctl = IWI_CB_DEFAULT_CTL | mlen;
2171 				sum = ctl ^ cs ^ cd;
2172 
2173 				/* Write a command block */
2174 				CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, ctl);
2175 				CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, cs);
2176 				CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, cd);
2177 				CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, sum);
2178 
2179 				cs += mlen;
2180 				cd += mlen;
2181 				len -= mlen;
2182 			}
2183 		}
2184 	}
2185 
2186 	/* Write a fictive final command block (sentinel) */
2187 	sentinel = CSR_READ_4(sc, IWI_CSR_AUTOINC_ADDR);
2188 	CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, 0);
2189 
2190 	CSR_WRITE_4(sc, IWI_CSR_RST, CSR_READ_4(sc, IWI_CSR_RST) &
2191 	    ~(IWI_RST_MASTER_DISABLED | IWI_RST_STOP_MASTER));
2192 
2193 	/* Tell the adapter to start processing command blocks */
2194 	MEM_WRITE_4(sc, 0x3000a4, 0x540100);
2195 
2196 	/* Wait until the adapter has processed all command blocks */
2197 	for (ntries = 0; ntries < 400; ntries++) {
2198 		if (MEM_READ_4(sc, 0x3000d0) >= sentinel)
2199 			break;
2200 		DELAY(100);
2201 	}
2202 	if (ntries == 400) {
2203 		aprint_error_dev(sc->sc_dev, "timeout processing cb\n");
2204 		error = ETIMEDOUT;
2205 		goto fail3;
2206 	}
2207 
2208 	/* We're done with command blocks processing */
2209 	MEM_WRITE_4(sc, 0x3000a4, 0x540c00);
2210 
2211 	/* Allow interrupts so we know when the firmware is inited */
2212 	CSR_WRITE_4(sc, IWI_CSR_INTR_MASK, IWI_INTR_MASK);
2213 
2214 	/* Tell the adapter to initialize the firmware */
2215 	CSR_WRITE_4(sc, IWI_CSR_RST, 0);
2216 	CSR_WRITE_4(sc, IWI_CSR_CTL, CSR_READ_4(sc, IWI_CSR_CTL) |
2217 	    IWI_CTL_ALLOW_STANDBY);
2218 
2219 	/* Wait at most one second for firmware initialization to complete */
2220 	if ((error = tsleep(sc, 0, "iwiinit", hz)) != 0) {
2221 		aprint_error_dev(sc->sc_dev,
2222 		    "timeout waiting for firmware initialization to complete\n");
2223 		goto fail3;
2224 	}
2225 
2226 fail3:
2227 	bus_dmamap_sync(sc->sc_dmat, map, 0, size, BUS_DMASYNC_POSTWRITE);
2228 	bus_dmamap_unload(sc->sc_dmat, map);
2229 fail2:
2230 	if (map != NULL)
2231 		bus_dmamap_destroy(sc->sc_dmat, map);
2232 
2233 fail1:
2234 	return error;
2235 }
2236 
2237 /*
2238  * Store firmware into kernel memory so we can download it when we need to,
2239  * e.g when the adapter wakes up from suspend mode.
2240  */
2241 static int
2242 iwi_cache_firmware(struct iwi_softc *sc)
2243 {
2244 	struct iwi_firmware *kfw = &sc->fw;
2245 	firmware_handle_t fwh;
2246 	struct iwi_firmware_hdr *hdr;
2247 	off_t size;
2248 	char *fw;
2249 	int error;
2250 
2251 	if (iwi_accept_eula == 0) {
2252 		aprint_error_dev(sc->sc_dev,
2253 		    "EULA not accepted; please see the iwi(4) man page.\n");
2254 		return EPERM;
2255 	}
2256 
2257 	iwi_free_firmware(sc);
2258 	error = firmware_open("if_iwi", sc->sc_fwname, &fwh);
2259 	if (error != 0) {
2260 		aprint_error_dev(sc->sc_dev, "firmware_open failed\n");
2261 		goto fail1;
2262 	}
2263 
2264 	size = firmware_get_size(fwh);
2265 	if (size < sizeof(struct iwi_firmware_hdr)) {
2266 		aprint_error_dev(sc->sc_dev, "image '%s' has no header\n",
2267 		    sc->sc_fwname);
2268 		error = EIO;
2269 		goto fail1;
2270 	}
2271 	sc->sc_blobsize = size;
2272 
2273 	sc->sc_blob = firmware_malloc(size);
2274 	if (sc->sc_blob == NULL) {
2275 		error = ENOMEM;
2276 		firmware_close(fwh);
2277 		goto fail1;
2278 	}
2279 
2280 	error = firmware_read(fwh, 0, sc->sc_blob, size);
2281 	firmware_close(fwh);
2282 	if (error != 0)
2283 		goto fail2;
2284 
2285 	hdr = (struct iwi_firmware_hdr *)sc->sc_blob;
2286 	hdr->version = le32toh(hdr->version);
2287 	hdr->bsize = le32toh(hdr->bsize);
2288 	hdr->usize = le32toh(hdr->usize);
2289 	hdr->fsize = le32toh(hdr->fsize);
2290 
2291 	if (size < sizeof(struct iwi_firmware_hdr) + hdr->bsize + hdr->usize + hdr->fsize) {
2292 		aprint_error_dev(sc->sc_dev, "image '%s' too small\n",
2293 		    sc->sc_fwname);
2294 		error = EIO;
2295 		goto fail2;
2296 	}
2297 
2298 	DPRINTF(("firmware version = %d\n", hdr->version));
2299 	if ((IWI_FW_GET_MAJOR(hdr->version) != IWI_FW_REQ_MAJOR) ||
2300 	    (IWI_FW_GET_MINOR(hdr->version) != IWI_FW_REQ_MINOR)) {
2301 		aprint_error_dev(sc->sc_dev,
2302 		    "version for '%s' %d.%d != %d.%d\n", sc->sc_fwname,
2303 		    IWI_FW_GET_MAJOR(hdr->version),
2304 		    IWI_FW_GET_MINOR(hdr->version),
2305 		    IWI_FW_REQ_MAJOR, IWI_FW_REQ_MINOR);
2306 		error = EIO;
2307 		goto fail2;
2308 	}
2309 
2310 	kfw->boot_size = hdr->bsize;
2311 	kfw->ucode_size = hdr->usize;
2312 	kfw->main_size = hdr->fsize;
2313 
2314 	fw = sc->sc_blob + sizeof(struct iwi_firmware_hdr);
2315 	kfw->boot = fw;
2316 	fw += kfw->boot_size;
2317 	kfw->ucode = fw;
2318 	fw += kfw->ucode_size;
2319 	kfw->main = fw;
2320 
2321 	DPRINTF(("Firmware cached: boot %p, ucode %p, main %p\n",
2322 	    kfw->boot, kfw->ucode, kfw->main));
2323 	DPRINTF(("Firmware cached: boot %u, ucode %u, main %u\n",
2324 	    kfw->boot_size, kfw->ucode_size, kfw->main_size));
2325 
2326 	sc->flags |= IWI_FLAG_FW_CACHED;
2327 
2328 	return 0;
2329 
2330 
2331 fail2:	firmware_free(sc->sc_blob, sc->sc_blobsize);
2332 fail1:
2333 	return error;
2334 }
2335 
2336 static void
2337 iwi_free_firmware(struct iwi_softc *sc)
2338 {
2339 
2340 	if (!(sc->flags & IWI_FLAG_FW_CACHED))
2341 		return;
2342 
2343 	firmware_free(sc->sc_blob, sc->sc_blobsize);
2344 
2345 	sc->flags &= ~IWI_FLAG_FW_CACHED;
2346 }
2347 
2348 static int
2349 iwi_config(struct iwi_softc *sc)
2350 {
2351 	struct ieee80211com *ic = &sc->sc_ic;
2352 	struct ifnet *ifp = &sc->sc_if;
2353 	struct iwi_configuration config;
2354 	struct iwi_rateset rs;
2355 	struct iwi_txpower power;
2356 	struct ieee80211_key *wk;
2357 	struct iwi_wep_key wepkey;
2358 	uint32_t data;
2359 	int error, nchan, i;
2360 
2361 	IEEE80211_ADDR_COPY(ic->ic_myaddr, CLLADDR(ifp->if_sadl));
2362 	DPRINTF(("Setting MAC address to %s\n", ether_sprintf(ic->ic_myaddr)));
2363 	error = iwi_cmd(sc, IWI_CMD_SET_MAC_ADDRESS, ic->ic_myaddr,
2364 	    IEEE80211_ADDR_LEN, 0);
2365 	if (error != 0)
2366 		return error;
2367 
2368 	memset(&config, 0, sizeof config);
2369 	config.bluetooth_coexistence = sc->bluetooth;
2370 	config.antenna = sc->antenna;
2371 	config.silence_threshold = 0x1e;
2372 	config.multicast_enabled = 1;
2373 	config.answer_pbreq = (ic->ic_opmode == IEEE80211_M_IBSS) ? 1 : 0;
2374 	config.disable_unicast_decryption = 1;
2375 	config.disable_multicast_decryption = 1;
2376 	DPRINTF(("Configuring adapter\n"));
2377 	error = iwi_cmd(sc, IWI_CMD_SET_CONFIGURATION, &config, sizeof config,
2378 	    0);
2379 	if (error != 0)
2380 		return error;
2381 
2382 	data = htole32(IWI_POWER_MODE_CAM);
2383 	DPRINTF(("Setting power mode to %u\n", le32toh(data)));
2384 	error = iwi_cmd(sc, IWI_CMD_SET_POWER_MODE, &data, sizeof data, 0);
2385 	if (error != 0)
2386 		return error;
2387 
2388 	data = htole32(ic->ic_rtsthreshold);
2389 	DPRINTF(("Setting RTS threshold to %u\n", le32toh(data)));
2390 	error = iwi_cmd(sc, IWI_CMD_SET_RTS_THRESHOLD, &data, sizeof data, 0);
2391 	if (error != 0)
2392 		return error;
2393 
2394 	data = htole32(ic->ic_fragthreshold);
2395 	DPRINTF(("Setting fragmentation threshold to %u\n", le32toh(data)));
2396 	error = iwi_cmd(sc, IWI_CMD_SET_FRAG_THRESHOLD, &data, sizeof data, 0);
2397 	if (error != 0)
2398 		return error;
2399 
2400 	/*
2401 	 * Set default Tx power for 802.11b/g and 802.11a channels.
2402 	 */
2403 	nchan = 0;
2404 	for (i = 0; i <= IEEE80211_CHAN_MAX; i++) {
2405 		if (!IEEE80211_IS_CHAN_2GHZ(&ic->ic_channels[i]))
2406 			continue;
2407 		power.chan[nchan].chan = i;
2408 		power.chan[nchan].power = IWI_TXPOWER_MAX;
2409 		nchan++;
2410 	}
2411 	power.nchan = nchan;
2412 
2413 	power.mode = IWI_MODE_11G;
2414 	DPRINTF(("Setting .11g channels tx power\n"));
2415 	error = iwi_cmd(sc, IWI_CMD_SET_TX_POWER, &power, sizeof power, 0);
2416 	if (error != 0)
2417 		return error;
2418 
2419 	power.mode = IWI_MODE_11B;
2420 	DPRINTF(("Setting .11b channels tx power\n"));
2421 	error = iwi_cmd(sc, IWI_CMD_SET_TX_POWER, &power, sizeof power, 0);
2422 	if (error != 0)
2423 		return error;
2424 
2425 	nchan = 0;
2426 	for (i = 0; i <= IEEE80211_CHAN_MAX; i++) {
2427 		if (!IEEE80211_IS_CHAN_5GHZ(&ic->ic_channels[i]))
2428 			continue;
2429 		power.chan[nchan].chan = i;
2430 		power.chan[nchan].power = IWI_TXPOWER_MAX;
2431 		nchan++;
2432 	}
2433 	power.nchan = nchan;
2434 
2435 	if (nchan > 0) {	/* 2915ABG only */
2436 		power.mode = IWI_MODE_11A;
2437 		DPRINTF(("Setting .11a channels tx power\n"));
2438 		error = iwi_cmd(sc, IWI_CMD_SET_TX_POWER, &power, sizeof power,
2439 		    0);
2440 		if (error != 0)
2441 			return error;
2442 	}
2443 
2444 	rs.mode = IWI_MODE_11G;
2445 	rs.type = IWI_RATESET_TYPE_SUPPORTED;
2446 	rs.nrates = ic->ic_sup_rates[IEEE80211_MODE_11G].rs_nrates;
2447 	memcpy(rs.rates, ic->ic_sup_rates[IEEE80211_MODE_11G].rs_rates,
2448 	    rs.nrates);
2449 	DPRINTF(("Setting .11bg supported rates (%u)\n", rs.nrates));
2450 	error = iwi_cmd(sc, IWI_CMD_SET_RATES, &rs, sizeof rs, 0);
2451 	if (error != 0)
2452 		return error;
2453 
2454 	rs.mode = IWI_MODE_11A;
2455 	rs.type = IWI_RATESET_TYPE_SUPPORTED;
2456 	rs.nrates = ic->ic_sup_rates[IEEE80211_MODE_11A].rs_nrates;
2457 	memcpy(rs.rates, ic->ic_sup_rates[IEEE80211_MODE_11A].rs_rates,
2458 	    rs.nrates);
2459 	DPRINTF(("Setting .11a supported rates (%u)\n", rs.nrates));
2460 	error = iwi_cmd(sc, IWI_CMD_SET_RATES, &rs, sizeof rs, 0);
2461 	if (error != 0)
2462 		return error;
2463 
2464 	/* if we have a desired ESSID, set it now */
2465 	if (ic->ic_des_esslen != 0) {
2466 #ifdef IWI_DEBUG
2467 		if (iwi_debug > 0) {
2468 			printf("Setting desired ESSID to ");
2469 			ieee80211_print_essid(ic->ic_des_essid,
2470 			    ic->ic_des_esslen);
2471 			printf("\n");
2472 		}
2473 #endif
2474 		error = iwi_cmd(sc, IWI_CMD_SET_ESSID, ic->ic_des_essid,
2475 		    ic->ic_des_esslen, 0);
2476 		if (error != 0)
2477 			return error;
2478 	}
2479 
2480 	cprng_fast(&data, sizeof(data));
2481 	data = htole32(data);
2482 	DPRINTF(("Setting initialization vector to %u\n", le32toh(data)));
2483 	error = iwi_cmd(sc, IWI_CMD_SET_IV, &data, sizeof data, 0);
2484 	if (error != 0)
2485 		return error;
2486 
2487 	if (ic->ic_flags & IEEE80211_F_PRIVACY) {
2488 		/* XXX iwi_setwepkeys? */
2489 		for (i = 0; i < IEEE80211_WEP_NKID; i++) {
2490 			wk = &ic->ic_crypto.cs_nw_keys[i];
2491 
2492 			wepkey.cmd = IWI_WEP_KEY_CMD_SETKEY;
2493 			wepkey.idx = i;
2494 			wepkey.len = wk->wk_keylen;
2495 			memset(wepkey.key, 0, sizeof wepkey.key);
2496 			memcpy(wepkey.key, wk->wk_key, wk->wk_keylen);
2497 			DPRINTF(("Setting wep key index %u len %u\n",
2498 			    wepkey.idx, wepkey.len));
2499 			error = iwi_cmd(sc, IWI_CMD_SET_WEP_KEY, &wepkey,
2500 			    sizeof wepkey, 0);
2501 			if (error != 0)
2502 				return error;
2503 		}
2504 	}
2505 
2506 	/* Enable adapter */
2507 	DPRINTF(("Enabling adapter\n"));
2508 	return iwi_cmd(sc, IWI_CMD_ENABLE, NULL, 0, 0);
2509 }
2510 
2511 static int
2512 iwi_set_chan(struct iwi_softc *sc, struct ieee80211_channel *chan)
2513 {
2514 	struct ieee80211com *ic = &sc->sc_ic;
2515 	struct iwi_scan_v2 scan;
2516 
2517 	(void)memset(&scan, 0, sizeof scan);
2518 
2519 	scan.dwelltime[IWI_SCAN_TYPE_PASSIVE] = htole16(2000);
2520 	scan.channels[0] = 1 |
2521 	    (IEEE80211_IS_CHAN_5GHZ(chan) ? IWI_CHAN_5GHZ : IWI_CHAN_2GHZ);
2522 	scan.channels[1] = ieee80211_chan2ieee(ic, chan);
2523 	iwi_scan_type_set(scan, 1, IWI_SCAN_TYPE_PASSIVE);
2524 
2525 	DPRINTF(("Setting channel to %u\n", ieee80211_chan2ieee(ic, chan)));
2526 	return iwi_cmd(sc, IWI_CMD_SCAN_V2, &scan, sizeof scan, 1);
2527 }
2528 
2529 static int
2530 iwi_scan(struct iwi_softc *sc)
2531 {
2532 	struct ieee80211com *ic = &sc->sc_ic;
2533 	struct iwi_scan_v2 scan;
2534 	uint32_t type;
2535 	uint8_t *p;
2536 	int i, count, idx;
2537 
2538 	(void)memset(&scan, 0, sizeof scan);
2539 	scan.dwelltime[IWI_SCAN_TYPE_ACTIVE_BROADCAST] =
2540 	    htole16(sc->dwelltime);
2541 	scan.dwelltime[IWI_SCAN_TYPE_ACTIVE_BDIRECT] =
2542 	    htole16(sc->dwelltime);
2543 
2544 	/* tell the firmware about the desired essid */
2545 	if (ic->ic_des_esslen) {
2546 		int error;
2547 
2548 		DPRINTF(("%s: Setting adapter desired ESSID to %s\n",
2549 		    __func__, ic->ic_des_essid));
2550 
2551 		error = iwi_cmd(sc, IWI_CMD_SET_ESSID,
2552 		    ic->ic_des_essid, ic->ic_des_esslen, 1);
2553 		if (error)
2554 			return error;
2555 
2556 		type = IWI_SCAN_TYPE_ACTIVE_BDIRECT;
2557 	} else {
2558 		type = IWI_SCAN_TYPE_ACTIVE_BROADCAST;
2559 	}
2560 
2561 	p = &scan.channels[0];
2562 	count = idx = 0;
2563 	for (i = 0; i <= IEEE80211_CHAN_MAX; i++) {
2564 		if (IEEE80211_IS_CHAN_5GHZ(&ic->ic_channels[i]) &&
2565 		    isset(ic->ic_chan_active, i)) {
2566 			*++p = i;
2567 			count++;
2568 			idx++;
2569  			iwi_scan_type_set(scan, idx, type);
2570 		}
2571 	}
2572 	if (count) {
2573 		*(p - count) = IWI_CHAN_5GHZ | count;
2574 		p++;
2575 	}
2576 
2577 	count = 0;
2578 	for (i = 0; i <= IEEE80211_CHAN_MAX; i++) {
2579 		if (IEEE80211_IS_CHAN_2GHZ(&ic->ic_channels[i]) &&
2580 		    isset(ic->ic_chan_active, i)) {
2581 			*++p = i;
2582 			count++;
2583 			idx++;
2584 			iwi_scan_type_set(scan, idx, type);
2585 		}
2586 	}
2587 	*(p - count) = IWI_CHAN_2GHZ | count;
2588 
2589 	DPRINTF(("Start scanning\n"));
2590 	return iwi_cmd(sc, IWI_CMD_SCAN_V2, &scan, sizeof scan, 1);
2591 }
2592 
2593 static int
2594 iwi_auth_and_assoc(struct iwi_softc *sc)
2595 {
2596 	struct ieee80211com *ic = &sc->sc_ic;
2597 	struct ieee80211_node *ni = ic->ic_bss;
2598 	struct ifnet *ifp = &sc->sc_if;
2599 	struct ieee80211_wme_info wme;
2600 	struct iwi_configuration config;
2601 	struct iwi_associate assoc;
2602 	struct iwi_rateset rs;
2603 	uint16_t capinfo;
2604 	uint32_t data;
2605 	int error;
2606 
2607 	memset(&config, 0, sizeof config);
2608 	config.bluetooth_coexistence = sc->bluetooth;
2609 	config.antenna = sc->antenna;
2610 	config.multicast_enabled = 1;
2611 	config.silence_threshold = 0x1e;
2612 	if (ic->ic_curmode == IEEE80211_MODE_11G)
2613 		config.use_protection = 1;
2614 	config.answer_pbreq = (ic->ic_opmode == IEEE80211_M_IBSS) ? 1 : 0;
2615 	config.disable_unicast_decryption = 1;
2616 	config.disable_multicast_decryption = 1;
2617 
2618 	DPRINTF(("Configuring adapter\n"));
2619 	error = iwi_cmd(sc, IWI_CMD_SET_CONFIGURATION, &config,
2620 	    sizeof config, 1);
2621 	if (error != 0)
2622 		return error;
2623 
2624 #ifdef IWI_DEBUG
2625 	if (iwi_debug > 0) {
2626 		aprint_debug_dev(sc->sc_dev, "Setting ESSID to ");
2627 		ieee80211_print_essid(ni->ni_essid, ni->ni_esslen);
2628 		aprint_debug("\n");
2629 	}
2630 #endif
2631 	error = iwi_cmd(sc, IWI_CMD_SET_ESSID, ni->ni_essid, ni->ni_esslen, 1);
2632 	if (error != 0)
2633 		return error;
2634 
2635 	/* the rate set has already been "negotiated" */
2636 	rs.mode = IEEE80211_IS_CHAN_5GHZ(ni->ni_chan) ? IWI_MODE_11A :
2637 	    IWI_MODE_11G;
2638 	rs.type = IWI_RATESET_TYPE_NEGOTIATED;
2639 	rs.nrates = ni->ni_rates.rs_nrates;
2640 
2641 	if (rs.nrates > IWI_RATESET_SIZE) {
2642 		DPRINTF(("Truncating negotiated rate set from %u\n",
2643 		    rs.nrates));
2644 		rs.nrates = IWI_RATESET_SIZE;
2645 	}
2646 	memcpy(rs.rates, ni->ni_rates.rs_rates, rs.nrates);
2647 	DPRINTF(("Setting negotiated rates (%u)\n", rs.nrates));
2648 	error = iwi_cmd(sc, IWI_CMD_SET_RATES, &rs, sizeof rs, 1);
2649 	if (error != 0)
2650 		return error;
2651 
2652 	if ((ic->ic_flags & IEEE80211_F_WME) && ni->ni_wme_ie != NULL) {
2653 		wme.wme_id = IEEE80211_ELEMID_VENDOR;
2654 		wme.wme_len = sizeof (struct ieee80211_wme_info) - 2;
2655 		wme.wme_oui[0] = 0x00;
2656 		wme.wme_oui[1] = 0x50;
2657 		wme.wme_oui[2] = 0xf2;
2658 		wme.wme_type = WME_OUI_TYPE;
2659 		wme.wme_subtype = WME_INFO_OUI_SUBTYPE;
2660 		wme.wme_version = WME_VERSION;
2661 		wme.wme_info = 0;
2662 
2663 		DPRINTF(("Setting WME IE (len=%u)\n", wme.wme_len));
2664 		error = iwi_cmd(sc, IWI_CMD_SET_WMEIE, &wme, sizeof wme, 1);
2665 		if (error != 0)
2666 			return error;
2667 	}
2668 
2669 	if (ic->ic_opt_ie != NULL) {
2670 		DPRINTF(("Setting optional IE (len=%u)\n", ic->ic_opt_ie_len));
2671 		error = iwi_cmd(sc, IWI_CMD_SET_OPTIE, ic->ic_opt_ie,
2672 		    ic->ic_opt_ie_len, 1);
2673 		if (error != 0)
2674 			return error;
2675 	}
2676 	data = htole32(ni->ni_rssi);
2677 	DPRINTF(("Setting sensitivity to %d\n", (int8_t)ni->ni_rssi));
2678 	error = iwi_cmd(sc, IWI_CMD_SET_SENSITIVITY, &data, sizeof data, 1);
2679 	if (error != 0)
2680 		return error;
2681 
2682 	memset(&assoc, 0, sizeof assoc);
2683 	if (IEEE80211_IS_CHAN_A(ni->ni_chan))
2684 		assoc.mode = IWI_MODE_11A;
2685 	else if (IEEE80211_IS_CHAN_G(ni->ni_chan))
2686 		assoc.mode = IWI_MODE_11G;
2687 	else if (IEEE80211_IS_CHAN_B(ni->ni_chan))
2688 		assoc.mode = IWI_MODE_11B;
2689 
2690 	assoc.chan = ieee80211_chan2ieee(ic, ni->ni_chan);
2691 
2692 	if (ni->ni_authmode == IEEE80211_AUTH_SHARED)
2693 		assoc.auth = (ic->ic_crypto.cs_def_txkey << 4) | IWI_AUTH_SHARED;
2694 
2695 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
2696 		assoc.plen = IWI_ASSOC_SHPREAMBLE;
2697 
2698 	if ((ic->ic_flags & IEEE80211_F_WME) && ni->ni_wme_ie != NULL)
2699 		assoc.policy |= htole16(IWI_POLICY_WME);
2700 	if (ic->ic_flags & IEEE80211_F_WPA)
2701 		assoc.policy |= htole16(IWI_POLICY_WPA);
2702 	if (ic->ic_opmode == IEEE80211_M_IBSS && ni->ni_tstamp.tsf == 0)
2703 		assoc.type = IWI_HC_IBSS_START;
2704 	else
2705 		assoc.type = IWI_HC_ASSOC;
2706 	memcpy(assoc.tstamp, ni->ni_tstamp.data, 8);
2707 
2708 	if (ic->ic_opmode == IEEE80211_M_IBSS)
2709 		capinfo = IEEE80211_CAPINFO_IBSS;
2710 	else
2711 		capinfo = IEEE80211_CAPINFO_ESS;
2712 	if (ic->ic_flags & IEEE80211_F_PRIVACY)
2713 		capinfo |= IEEE80211_CAPINFO_PRIVACY;
2714 	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
2715 	    IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
2716 		capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
2717 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
2718 		capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
2719 	assoc.capinfo = htole16(capinfo);
2720 
2721 	assoc.lintval = htole16(ic->ic_lintval);
2722 	assoc.intval = htole16(ni->ni_intval);
2723 	IEEE80211_ADDR_COPY(assoc.bssid, ni->ni_bssid);
2724 	if (ic->ic_opmode == IEEE80211_M_IBSS)
2725 		IEEE80211_ADDR_COPY(assoc.dst, ifp->if_broadcastaddr);
2726 	else
2727 		IEEE80211_ADDR_COPY(assoc.dst, ni->ni_bssid);
2728 
2729 	DPRINTF(("%s bssid %s dst %s channel %u policy 0x%x "
2730 	    "auth %u capinfo 0x%x lintval %u bintval %u\n",
2731 	    assoc.type == IWI_HC_IBSS_START ? "Start" : "Join",
2732 	    ether_sprintf(assoc.bssid), ether_sprintf(assoc.dst),
2733 	    assoc.chan, le16toh(assoc.policy), assoc.auth,
2734 	    le16toh(assoc.capinfo), le16toh(assoc.lintval),
2735 	    le16toh(assoc.intval)));
2736 
2737 	return iwi_cmd(sc, IWI_CMD_ASSOCIATE, &assoc, sizeof assoc, 1);
2738 }
2739 
2740 static int
2741 iwi_init(struct ifnet *ifp)
2742 {
2743 	struct iwi_softc *sc = ifp->if_softc;
2744 	struct ieee80211com *ic = &sc->sc_ic;
2745 	struct iwi_firmware *fw = &sc->fw;
2746 	int i, error;
2747 
2748 	/* exit immediately if firmware has not been ioctl'd */
2749 	if (!(sc->flags & IWI_FLAG_FW_CACHED)) {
2750 		if ((error = iwi_cache_firmware(sc)) != 0) {
2751 			aprint_error_dev(sc->sc_dev,
2752 			    "could not cache the firmware\n");
2753 			goto fail;
2754 		}
2755 	}
2756 
2757 	iwi_stop(ifp, 0);
2758 
2759 	if ((error = iwi_reset(sc)) != 0) {
2760 		aprint_error_dev(sc->sc_dev, "could not reset adapter\n");
2761 		goto fail;
2762 	}
2763 
2764 	if ((error = iwi_load_firmware(sc, fw->boot, fw->boot_size)) != 0) {
2765 		aprint_error_dev(sc->sc_dev, "could not load boot firmware\n");
2766 		goto fail;
2767 	}
2768 
2769 	if ((error = iwi_load_ucode(sc, fw->ucode, fw->ucode_size)) != 0) {
2770 		aprint_error_dev(sc->sc_dev, "could not load microcode\n");
2771 		goto fail;
2772 	}
2773 
2774 	iwi_stop_master(sc);
2775 
2776 	CSR_WRITE_4(sc, IWI_CSR_CMD_BASE, sc->cmdq.desc_map->dm_segs[0].ds_addr);
2777 	CSR_WRITE_4(sc, IWI_CSR_CMD_SIZE, sc->cmdq.count);
2778 	CSR_WRITE_4(sc, IWI_CSR_CMD_WIDX, sc->cmdq.cur);
2779 
2780 	CSR_WRITE_4(sc, IWI_CSR_TX1_BASE, sc->txq[0].desc_map->dm_segs[0].ds_addr);
2781 	CSR_WRITE_4(sc, IWI_CSR_TX1_SIZE, sc->txq[0].count);
2782 	CSR_WRITE_4(sc, IWI_CSR_TX1_WIDX, sc->txq[0].cur);
2783 
2784 	CSR_WRITE_4(sc, IWI_CSR_TX2_BASE, sc->txq[1].desc_map->dm_segs[0].ds_addr);
2785 	CSR_WRITE_4(sc, IWI_CSR_TX2_SIZE, sc->txq[1].count);
2786 	CSR_WRITE_4(sc, IWI_CSR_TX2_WIDX, sc->txq[1].cur);
2787 
2788 	CSR_WRITE_4(sc, IWI_CSR_TX3_BASE, sc->txq[2].desc_map->dm_segs[0].ds_addr);
2789 	CSR_WRITE_4(sc, IWI_CSR_TX3_SIZE, sc->txq[2].count);
2790 	CSR_WRITE_4(sc, IWI_CSR_TX3_WIDX, sc->txq[2].cur);
2791 
2792 	CSR_WRITE_4(sc, IWI_CSR_TX4_BASE, sc->txq[3].desc_map->dm_segs[0].ds_addr);
2793 	CSR_WRITE_4(sc, IWI_CSR_TX4_SIZE, sc->txq[3].count);
2794 	CSR_WRITE_4(sc, IWI_CSR_TX4_WIDX, sc->txq[3].cur);
2795 
2796 	for (i = 0; i < sc->rxq.count; i++)
2797 		CSR_WRITE_4(sc, IWI_CSR_RX_BASE + i * 4,
2798 		    sc->rxq.data[i].map->dm_segs[0].ds_addr);
2799 
2800 	CSR_WRITE_4(sc, IWI_CSR_RX_WIDX, sc->rxq.count -1);
2801 
2802 	if ((error = iwi_load_firmware(sc, fw->main, fw->main_size)) != 0) {
2803 		aprint_error_dev(sc->sc_dev, "could not load main firmware\n");
2804 		goto fail;
2805 	}
2806 
2807 	sc->flags |= IWI_FLAG_FW_INITED;
2808 
2809 	if ((error = iwi_config(sc)) != 0) {
2810 		aprint_error_dev(sc->sc_dev, "device configuration failed\n");
2811 		goto fail;
2812 	}
2813 
2814 	ic->ic_state = IEEE80211_S_INIT;
2815 
2816 	ifp->if_flags &= ~IFF_OACTIVE;
2817 	ifp->if_flags |= IFF_RUNNING;
2818 
2819 	if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2820 		if (ic->ic_roaming != IEEE80211_ROAMING_MANUAL)
2821 			ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
2822 	} else
2823 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
2824 
2825 	return 0;
2826 
2827 fail:	ifp->if_flags &= ~IFF_UP;
2828 	iwi_stop(ifp, 0);
2829 
2830 	return error;
2831 }
2832 
2833 
2834 /*
2835  * Return whether or not the radio is enabled in hardware
2836  * (i.e. the rfkill switch is "off").
2837  */
2838 static int
2839 iwi_getrfkill(struct iwi_softc *sc)
2840 {
2841 	return (CSR_READ_4(sc, IWI_CSR_IO) & IWI_IO_RADIO_ENABLED) == 0;
2842 }
2843 
2844 static int
2845 iwi_sysctl_radio(SYSCTLFN_ARGS)
2846 {
2847 	struct sysctlnode node;
2848 	struct iwi_softc *sc;
2849 	int val, error;
2850 
2851 	node = *rnode;
2852 	sc = (struct iwi_softc *)node.sysctl_data;
2853 
2854 	val = !iwi_getrfkill(sc);
2855 
2856 	node.sysctl_data = &val;
2857 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
2858 
2859 	if (error || newp == NULL)
2860 		return error;
2861 
2862 	return 0;
2863 }
2864 
2865 #ifdef IWI_DEBUG
2866 SYSCTL_SETUP(sysctl_iwi, "sysctl iwi(4) subtree setup")
2867 {
2868 	int rc;
2869 	const struct sysctlnode *rnode;
2870 	const struct sysctlnode *cnode;
2871 
2872 	if ((rc = sysctl_createv(clog, 0, NULL, &rnode,
2873 	    CTLFLAG_PERMANENT, CTLTYPE_NODE, "iwi",
2874 	    SYSCTL_DESCR("iwi global controls"),
2875 	    NULL, 0, NULL, 0, CTL_HW, CTL_CREATE, CTL_EOL)) != 0)
2876 		goto err;
2877 
2878 	/* control debugging printfs */
2879 	if ((rc = sysctl_createv(clog, 0, &rnode, &cnode,
2880 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT,
2881 	    "debug", SYSCTL_DESCR("Enable debugging output"),
2882 	    NULL, 0, &iwi_debug, 0, CTL_CREATE, CTL_EOL)) != 0)
2883 		goto err;
2884 
2885 	return;
2886 err:
2887 	aprint_error("%s: sysctl_createv failed (rc = %d)\n", __func__, rc);
2888 }
2889 
2890 #endif /* IWI_DEBUG */
2891 
2892 /*
2893  * Add sysctl knobs.
2894  */
2895 static void
2896 iwi_sysctlattach(struct iwi_softc *sc)
2897 {
2898 	int rc;
2899 	const struct sysctlnode *rnode;
2900 	const struct sysctlnode *cnode;
2901 
2902 	struct sysctllog **clog = &sc->sc_sysctllog;
2903 
2904 	if ((rc = sysctl_createv(clog, 0, NULL, &rnode,
2905 	    CTLFLAG_PERMANENT, CTLTYPE_NODE, device_xname(sc->sc_dev),
2906 	    SYSCTL_DESCR("iwi controls and statistics"),
2907 	    NULL, 0, NULL, 0, CTL_HW, CTL_CREATE, CTL_EOL)) != 0)
2908 		goto err;
2909 
2910 	if ((rc = sysctl_createv(clog, 0, &rnode, &cnode,
2911 	    CTLFLAG_PERMANENT, CTLTYPE_INT, "radio",
2912 	    SYSCTL_DESCR("radio transmitter switch state (0=off, 1=on)"),
2913 	    iwi_sysctl_radio, 0, (void *)sc, 0, CTL_CREATE, CTL_EOL)) != 0)
2914 		goto err;
2915 
2916 	sc->dwelltime = 100;
2917 	if ((rc = sysctl_createv(clog, 0, &rnode, &cnode,
2918 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT,
2919 	    "dwell", SYSCTL_DESCR("channel dwell time (ms) for AP/station scanning"),
2920 	    NULL, 0, &sc->dwelltime, 0, CTL_CREATE, CTL_EOL)) != 0)
2921 		goto err;
2922 
2923 	sc->bluetooth = 0;
2924 	if ((rc = sysctl_createv(clog, 0, &rnode, &cnode,
2925 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT,
2926 	    "bluetooth", SYSCTL_DESCR("bluetooth coexistence"),
2927 	    NULL, 0, &sc->bluetooth, 0, CTL_CREATE, CTL_EOL)) != 0)
2928 		goto err;
2929 
2930 	sc->antenna = IWI_ANTENNA_AUTO;
2931 	if ((rc = sysctl_createv(clog, 0, &rnode, &cnode,
2932 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT,
2933 	    "antenna", SYSCTL_DESCR("antenna (0=auto)"),
2934 	    NULL, 0, &sc->antenna, 0, CTL_CREATE, CTL_EOL)) != 0)
2935 		goto err;
2936 
2937 	return;
2938 err:
2939 	aprint_error("%s: sysctl_createv failed (rc = %d)\n", __func__, rc);
2940 }
2941 
2942 static void
2943 iwi_stop(struct ifnet *ifp, int disable)
2944 {
2945 	struct iwi_softc *sc = ifp->if_softc;
2946 	struct ieee80211com *ic = &sc->sc_ic;
2947 
2948 	IWI_LED_OFF(sc);
2949 
2950 	iwi_stop_master(sc);
2951 	CSR_WRITE_4(sc, IWI_CSR_RST, IWI_RST_SW_RESET);
2952 
2953 	/* reset rings */
2954 	iwi_reset_cmd_ring(sc, &sc->cmdq);
2955 	iwi_reset_tx_ring(sc, &sc->txq[0]);
2956 	iwi_reset_tx_ring(sc, &sc->txq[1]);
2957 	iwi_reset_tx_ring(sc, &sc->txq[2]);
2958 	iwi_reset_tx_ring(sc, &sc->txq[3]);
2959 	iwi_reset_rx_ring(sc, &sc->rxq);
2960 
2961 	ifp->if_timer = 0;
2962 	ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
2963 
2964 	ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
2965 }
2966 
2967 static void
2968 iwi_led_set(struct iwi_softc *sc, uint32_t state, int toggle)
2969 {
2970 	uint32_t val;
2971 
2972 	val = MEM_READ_4(sc, IWI_MEM_EVENT_CTL);
2973 
2974 	switch (sc->nictype) {
2975 	case 1:
2976 		/* special NIC type: reversed leds */
2977 		if (state == IWI_LED_ACTIVITY) {
2978 			state &= ~IWI_LED_ACTIVITY;
2979 			state |= IWI_LED_ASSOCIATED;
2980 		} else if (state == IWI_LED_ASSOCIATED) {
2981 			state &= ~IWI_LED_ASSOCIATED;
2982 			state |= IWI_LED_ACTIVITY;
2983 		}
2984 		/* and ignore toggle effect */
2985 		val |= state;
2986 		break;
2987 	case 0:
2988 	case 2:
2989 	case 3:
2990 	case 4:
2991 		val = (toggle && (val & state)) ? val & ~state : val | state;
2992 		break;
2993 	default:
2994 		aprint_normal_dev(sc->sc_dev, "unknown NIC type %d\n",
2995 		    sc->nictype);
2996 		return;
2997 		break;
2998 	}
2999 
3000 	MEM_WRITE_4(sc, IWI_MEM_EVENT_CTL, val);
3001 
3002 	return;
3003 }
3004 
3005 SYSCTL_SETUP(sysctl_hw_iwi_accept_eula_setup, "sysctl hw.iwi.accept_eula")
3006 {
3007 	const struct sysctlnode *rnode;
3008 	const struct sysctlnode *cnode;
3009 
3010 	sysctl_createv(NULL, 0, NULL, &rnode,
3011 		CTLFLAG_PERMANENT,
3012 		CTLTYPE_NODE, "iwi",
3013 		NULL,
3014 		NULL, 0,
3015 		NULL, 0,
3016 		CTL_HW, CTL_CREATE, CTL_EOL);
3017 
3018 	sysctl_createv(NULL, 0, &rnode, &cnode,
3019 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
3020 		CTLTYPE_INT, "accept_eula",
3021 		SYSCTL_DESCR("Accept Intel EULA and permit use of iwi(4) firmware"),
3022 		NULL, 0,
3023 		&iwi_accept_eula, sizeof(iwi_accept_eula),
3024 		CTL_CREATE, CTL_EOL);
3025 }
3026