xref: /netbsd-src/sys/dev/pci/if_iwi.c (revision 796c32c94f6e154afc9de0f63da35c91bb739b45)
1 /*	$NetBSD: if_iwi.c,v 1.104 2017/10/23 09:28:13 msaitoh 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.104 2017/10/23 09:28:13 msaitoh 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 < 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 		frm += frm[1] + 2;
1137 	}
1138 }
1139 
1140 static struct mbuf *
1141 iwi_alloc_rx_buf(struct iwi_softc *sc)
1142 {
1143 	struct mbuf *m;
1144 
1145 	MGETHDR(m, M_DONTWAIT, MT_DATA);
1146 	if (m == NULL) {
1147 		aprint_error_dev(sc->sc_dev, "could not allocate rx mbuf\n");
1148 		return NULL;
1149 	}
1150 
1151 	MCLGET(m, M_DONTWAIT);
1152 	if (!(m->m_flags & M_EXT)) {
1153 		aprint_error_dev(sc->sc_dev,
1154 		    "could not allocate rx mbuf cluster\n");
1155 		m_freem(m);
1156 		return NULL;
1157 	}
1158 
1159 	m->m_pkthdr.len = m->m_len = m->m_ext.ext_size;
1160 	return m;
1161 }
1162 
1163 static void
1164 iwi_frame_intr(struct iwi_softc *sc, struct iwi_rx_data *data, int i,
1165     struct iwi_frame *frame)
1166 {
1167 	struct ieee80211com *ic = &sc->sc_ic;
1168 	struct ifnet *ifp = ic->ic_ifp;
1169 	struct mbuf *m, *m_new;
1170 	struct ieee80211_frame *wh;
1171 	struct ieee80211_node *ni;
1172 	int error, s;
1173 
1174 	DPRINTFN(5, ("received frame len=%u chan=%u rssi=%u\n",
1175 	    le16toh(frame->len), frame->chan, frame->rssi_dbm));
1176 
1177 	if (le16toh(frame->len) < sizeof (struct ieee80211_frame) ||
1178 	    le16toh(frame->len) > MCLBYTES) {
1179 		DPRINTF(("%s: bad frame length\n", device_xname(sc->sc_dev)));
1180 		ifp->if_ierrors++;
1181 		return;
1182 	}
1183 
1184 	/*
1185 	 * Try to allocate a new mbuf for this ring element and
1186 	 * load it before processing the current mbuf. If the ring
1187 	 * element cannot be reloaded, drop the received packet
1188 	 * and reuse the old mbuf. In the unlikely case that
1189 	 * the old mbuf can't be reloaded either, explicitly panic.
1190 	 *
1191 	 * XXX Reorganize buffer by moving elements from the logical
1192 	 * end of the ring to the front instead of dropping.
1193 	 */
1194 	if ((m_new = iwi_alloc_rx_buf(sc)) == NULL) {
1195 		ifp->if_ierrors++;
1196 		return;
1197 	}
1198 
1199 	bus_dmamap_unload(sc->sc_dmat, data->map);
1200 
1201 	error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m_new,
1202 	    BUS_DMA_READ | BUS_DMA_NOWAIT);
1203 	if (error != 0) {
1204 		aprint_error_dev(sc->sc_dev,
1205 		    "could not load rx buf DMA map\n");
1206 		m_freem(m_new);
1207 		ifp->if_ierrors++;
1208 		error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map,
1209 		    data->m, BUS_DMA_READ | BUS_DMA_NOWAIT);
1210 		if (error)
1211 			panic("%s: unable to remap rx buf",
1212 			    device_xname(sc->sc_dev));
1213 		return;
1214 	}
1215 
1216 	/*
1217 	 * New mbuf successfully loaded, update RX ring and continue
1218 	 * processing.
1219 	 */
1220 	m = data->m;
1221 	data->m = m_new;
1222 	CSR_WRITE_4(sc, IWI_CSR_RX_BASE + i * 4, data->map->dm_segs[0].ds_addr);
1223 
1224 	/* Finalize mbuf */
1225 	m_set_rcvif(m, ifp);
1226 	m->m_pkthdr.len = m->m_len = sizeof (struct iwi_hdr) +
1227 	    sizeof (struct iwi_frame) + le16toh(frame->len);
1228 
1229 	m_adj(m, sizeof (struct iwi_hdr) + sizeof (struct iwi_frame));
1230 
1231 	s = splnet();
1232 
1233 	if (ic->ic_state == IEEE80211_S_SCAN)
1234 		iwi_fix_channel(ic, m);
1235 
1236 	if (sc->sc_drvbpf != NULL) {
1237 		struct iwi_rx_radiotap_header *tap = &sc->sc_rxtap;
1238 
1239 		tap->wr_flags = 0;
1240 		tap->wr_rate = iwi_cvtrate(frame->rate);
1241 		tap->wr_chan_freq =
1242 		    htole16(ic->ic_channels[frame->chan].ic_freq);
1243 		tap->wr_chan_flags =
1244 		    htole16(ic->ic_channels[frame->chan].ic_flags);
1245 		tap->wr_antsignal = frame->signal;
1246 		tap->wr_antenna = frame->antenna;
1247 
1248 		bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_rxtap_len, m);
1249 	}
1250 	wh = mtod(m, struct ieee80211_frame *);
1251 	ni = ieee80211_find_rxnode(ic, (struct ieee80211_frame_min *)wh);
1252 
1253 	/* Send the frame to the upper layer */
1254 	ieee80211_input(ic, m, ni, frame->rssi_dbm, 0);
1255 
1256 	/* node is no longer needed */
1257 	ieee80211_free_node(ni);
1258 
1259 	splx(s);
1260 }
1261 
1262 static void
1263 iwi_notification_intr(struct iwi_softc *sc, struct iwi_notif *notif)
1264 {
1265 	struct ieee80211com *ic = &sc->sc_ic;
1266 	struct iwi_notif_authentication *auth;
1267 	struct iwi_notif_association *assoc;
1268 	struct iwi_notif_beacon_state *beacon;
1269 	int s;
1270 
1271 	switch (notif->type) {
1272 	case IWI_NOTIF_TYPE_SCAN_CHANNEL:
1273 #ifdef IWI_DEBUG
1274 		{
1275 			struct iwi_notif_scan_channel *chan =
1276 			    (struct iwi_notif_scan_channel *)(notif + 1);
1277 
1278 			DPRINTFN(2, ("Scan of channel %u complete (%u)\n",
1279 			    ic->ic_channels[chan->nchan].ic_freq, chan->nchan));
1280 		}
1281 #endif
1282 		break;
1283 
1284 	case IWI_NOTIF_TYPE_SCAN_COMPLETE:
1285 #ifdef IWI_DEBUG
1286 		{
1287 			struct iwi_notif_scan_complete *scan =
1288 			    (struct iwi_notif_scan_complete *)(notif + 1);
1289 
1290 			DPRINTFN(2, ("Scan completed (%u, %u)\n", scan->nchan,
1291 			    scan->status));
1292 		}
1293 #endif
1294 
1295 		/* monitor mode uses scan to set the channel ... */
1296 		s = splnet();
1297 		if (ic->ic_opmode != IEEE80211_M_MONITOR) {
1298 			sc->flags &= ~IWI_FLAG_SCANNING;
1299 			ieee80211_end_scan(ic);
1300 		} else
1301 			iwi_set_chan(sc, ic->ic_ibss_chan);
1302 		splx(s);
1303 		break;
1304 
1305 	case IWI_NOTIF_TYPE_AUTHENTICATION:
1306 		auth = (struct iwi_notif_authentication *)(notif + 1);
1307 
1308 		DPRINTFN(2, ("Authentication (%u)\n", auth->state));
1309 
1310 		switch (auth->state) {
1311 		case IWI_AUTH_SUCCESS:
1312 			s = splnet();
1313 			ieee80211_node_authorize(ic->ic_bss);
1314 			ieee80211_new_state(ic, IEEE80211_S_ASSOC, -1);
1315 			splx(s);
1316 			break;
1317 
1318 		case IWI_AUTH_FAIL:
1319 			break;
1320 
1321 		case IWI_AUTH_SENT_1:
1322 		case IWI_AUTH_RECV_2:
1323 		case IWI_AUTH_SEQ1_PASS:
1324 			break;
1325 
1326 		case IWI_AUTH_SEQ1_FAIL:
1327 			break;
1328 
1329 		default:
1330 			aprint_error_dev(sc->sc_dev,
1331 			    "unknown authentication state %u\n", auth->state);
1332 		}
1333 		break;
1334 
1335 	case IWI_NOTIF_TYPE_ASSOCIATION:
1336 		assoc = (struct iwi_notif_association *)(notif + 1);
1337 
1338 		DPRINTFN(2, ("Association (%u, %u)\n", assoc->state,
1339 		    assoc->status));
1340 
1341 		switch (assoc->state) {
1342 		case IWI_AUTH_SUCCESS:
1343 			/* re-association, do nothing */
1344 			break;
1345 
1346 		case IWI_ASSOC_SUCCESS:
1347 			s = splnet();
1348 			ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
1349 			splx(s);
1350 			break;
1351 
1352 		case IWI_ASSOC_FAIL:
1353 			s = splnet();
1354 			ieee80211_begin_scan(ic, 1);
1355 			splx(s);
1356 			break;
1357 
1358 		default:
1359 			aprint_error_dev(sc->sc_dev,
1360 			    "unknown association state %u\n", assoc->state);
1361 		}
1362 		break;
1363 
1364 	case IWI_NOTIF_TYPE_BEACON:
1365 		beacon = (struct iwi_notif_beacon_state *)(notif + 1);
1366 
1367 		if (beacon->state == IWI_BEACON_MISS) {
1368 			DPRINTFN(5, ("%s: %u beacon(s) missed\n",
1369 			    device_xname(sc->sc_dev), le32toh(beacon->number)));
1370 		}
1371 		break;
1372 
1373 	case IWI_NOTIF_TYPE_FRAG_LENGTH:
1374 	case IWI_NOTIF_TYPE_LINK_QUALITY:
1375 	case IWI_NOTIF_TYPE_TGI_TX_KEY:
1376 	case IWI_NOTIF_TYPE_CALIBRATION:
1377 	case IWI_NOTIF_TYPE_NOISE:
1378 		DPRINTFN(5, ("Notification (%u)\n", notif->type));
1379 		break;
1380 
1381 	default:
1382 		DPRINTF(("%s: unknown notification type %u flags 0x%x len %d\n",
1383 		    device_xname(sc->sc_dev), notif->type, notif->flags,
1384 		    le16toh(notif->len)));
1385 	}
1386 }
1387 
1388 static void
1389 iwi_cmd_intr(struct iwi_softc *sc)
1390 {
1391 
1392 	(void)CSR_READ_4(sc, IWI_CSR_CMD_RIDX);
1393 
1394 	bus_dmamap_sync(sc->sc_dmat, sc->cmdq.desc_map,
1395 	    sc->cmdq.next * IWI_CMD_DESC_SIZE, IWI_CMD_DESC_SIZE,
1396 	    BUS_DMASYNC_POSTWRITE);
1397 
1398 	wakeup(&sc->cmdq.desc[sc->cmdq.next]);
1399 
1400 	sc->cmdq.next = (sc->cmdq.next + 1) % sc->cmdq.count;
1401 
1402 	if (--sc->cmdq.queued > 0) {
1403 		CSR_WRITE_4(sc, IWI_CSR_CMD_WIDX,
1404 		    (sc->cmdq.next + 1) % sc->cmdq.count);
1405 	}
1406 }
1407 
1408 static void
1409 iwi_rx_intr(struct iwi_softc *sc)
1410 {
1411 	struct iwi_rx_data *data;
1412 	struct iwi_hdr *hdr;
1413 	uint32_t hw;
1414 
1415 	hw = CSR_READ_4(sc, IWI_CSR_RX_RIDX);
1416 
1417 	for (; sc->rxq.cur != hw;) {
1418 		data = &sc->rxq.data[sc->rxq.cur];
1419 
1420 		bus_dmamap_sync(sc->sc_dmat, data->map, 0,
1421 		    data->map->dm_mapsize, BUS_DMASYNC_POSTREAD);
1422 
1423 		hdr = mtod(data->m, struct iwi_hdr *);
1424 
1425 		switch (hdr->type) {
1426 		case IWI_HDR_TYPE_FRAME:
1427 			iwi_frame_intr(sc, data, sc->rxq.cur,
1428 			    (struct iwi_frame *)(hdr + 1));
1429 			break;
1430 
1431 		case IWI_HDR_TYPE_NOTIF:
1432 			iwi_notification_intr(sc,
1433 			    (struct iwi_notif *)(hdr + 1));
1434 			break;
1435 
1436 		default:
1437 			aprint_error_dev(sc->sc_dev, "unknown hdr type %u\n",
1438 			    hdr->type);
1439 		}
1440 
1441 		bus_dmamap_sync(sc->sc_dmat, data->map, 0,
1442 		    data->map->dm_mapsize, BUS_DMASYNC_PREREAD);
1443 
1444 		DPRINTFN(15, ("rx done idx=%u\n", sc->rxq.cur));
1445 
1446 		sc->rxq.cur = (sc->rxq.cur + 1) % sc->rxq.count;
1447 	}
1448 
1449 	/* Tell the firmware what we have processed */
1450 	hw = (hw == 0) ? sc->rxq.count - 1 : hw - 1;
1451 	CSR_WRITE_4(sc, IWI_CSR_RX_WIDX, hw);
1452 }
1453 
1454 static void
1455 iwi_tx_intr(struct iwi_softc *sc, struct iwi_tx_ring *txq)
1456 {
1457 	struct ifnet *ifp = &sc->sc_if;
1458 	struct iwi_tx_data *data;
1459 	uint32_t hw;
1460 	int s;
1461 
1462 	s = splnet();
1463 
1464 	hw = CSR_READ_4(sc, txq->csr_ridx);
1465 
1466 	for (; txq->next != hw;) {
1467 		data = &txq->data[txq->next];
1468 
1469 		bus_dmamap_sync(sc->sc_dmat, data->map, 0,
1470 		    data->map->dm_mapsize, BUS_DMASYNC_POSTWRITE);
1471 		bus_dmamap_unload(sc->sc_dmat, data->map);
1472 		m_freem(data->m);
1473 		data->m = NULL;
1474 		ieee80211_free_node(data->ni);
1475 		data->ni = NULL;
1476 
1477 		DPRINTFN(15, ("tx done idx=%u\n", txq->next));
1478 
1479 		ifp->if_opackets++;
1480 
1481 		txq->queued--;
1482 		txq->next = (txq->next + 1) % txq->count;
1483 	}
1484 
1485 	sc->sc_tx_timer = 0;
1486 
1487 	if (txq->queued < txq->count - 8 - 8 && (ifp->if_flags & IFF_OACTIVE)) {
1488 		ifp->if_flags &= ~IFF_OACTIVE;
1489 
1490 		/* Call start() since some buffer descriptors have been released */
1491 		iwi_start(ifp); /* in softint */
1492 	}
1493 
1494 	splx(s);
1495 }
1496 
1497 static int
1498 iwi_intr(void *arg)
1499 {
1500 	struct iwi_softc *sc = arg;
1501 	uint32_t r;
1502 
1503 	if ((r = CSR_READ_4(sc, IWI_CSR_INTR)) == 0 || r == 0xffffffff)
1504 		return 0;
1505 
1506 	/* Disable interrupts */
1507 	CSR_WRITE_4(sc, IWI_CSR_INTR_MASK, 0);
1508 
1509 	softint_schedule(sc->sc_soft_ih);
1510 	return 1;
1511 }
1512 
1513 static void
1514 iwi_softintr(void *arg)
1515 {
1516 	struct iwi_softc *sc = arg;
1517 	uint32_t r;
1518 	int s;
1519 
1520 	if ((r = CSR_READ_4(sc, IWI_CSR_INTR)) == 0 || r == 0xffffffff)
1521 		goto out;
1522 
1523 	/* Acknowledge interrupts */
1524 	CSR_WRITE_4(sc, IWI_CSR_INTR, r);
1525 
1526 	if (r & IWI_INTR_FATAL_ERROR) {
1527 		aprint_error_dev(sc->sc_dev, "fatal error\n");
1528 		s = splnet();
1529 		sc->sc_ic.ic_ifp->if_flags &= ~IFF_UP;
1530 		iwi_stop(&sc->sc_if, 1);
1531 		splx(s);
1532 		return;
1533 	}
1534 
1535 	if (r & IWI_INTR_FW_INITED) {
1536 		if (!(r & (IWI_INTR_FATAL_ERROR | IWI_INTR_PARITY_ERROR)))
1537 			wakeup(sc);
1538 	}
1539 
1540 	if (r & IWI_INTR_RADIO_OFF) {
1541 		DPRINTF(("radio transmitter off\n"));
1542 		s = splnet();
1543 		sc->sc_ic.ic_ifp->if_flags &= ~IFF_UP;
1544 		iwi_stop(&sc->sc_if, 1);
1545 		splx(s);
1546 		return;
1547 	}
1548 
1549 	if (r & IWI_INTR_CMD_DONE)
1550 		iwi_cmd_intr(sc);
1551 
1552 	if (r & IWI_INTR_TX1_DONE)
1553 		iwi_tx_intr(sc, &sc->txq[0]);
1554 
1555 	if (r & IWI_INTR_TX2_DONE)
1556 		iwi_tx_intr(sc, &sc->txq[1]);
1557 
1558 	if (r & IWI_INTR_TX3_DONE)
1559 		iwi_tx_intr(sc, &sc->txq[2]);
1560 
1561 	if (r & IWI_INTR_TX4_DONE)
1562 		iwi_tx_intr(sc, &sc->txq[3]);
1563 
1564 	if (r & IWI_INTR_RX_DONE)
1565 		iwi_rx_intr(sc);
1566 
1567 	if (r & IWI_INTR_PARITY_ERROR)
1568 		aprint_error_dev(sc->sc_dev, "parity error\n");
1569 
1570  out:
1571 	/* Re-enable interrupts */
1572 	CSR_WRITE_4(sc, IWI_CSR_INTR_MASK, IWI_INTR_MASK);
1573 }
1574 
1575 static int
1576 iwi_cmd(struct iwi_softc *sc, uint8_t type, void *data, uint8_t len,
1577     int async)
1578 {
1579 	struct iwi_cmd_desc *desc;
1580 
1581 	desc = &sc->cmdq.desc[sc->cmdq.cur];
1582 
1583 	desc->hdr.type = IWI_HDR_TYPE_COMMAND;
1584 	desc->hdr.flags = IWI_HDR_FLAG_IRQ;
1585 	desc->type = type;
1586 	desc->len = len;
1587 	memcpy(desc->data, data, len);
1588 
1589 	bus_dmamap_sync(sc->sc_dmat, sc->cmdq.desc_map,
1590 	    sc->cmdq.cur * IWI_CMD_DESC_SIZE,
1591 	    IWI_CMD_DESC_SIZE, BUS_DMASYNC_PREWRITE);
1592 
1593 	DPRINTFN(2, ("sending command idx=%u type=%u len=%u async=%d\n",
1594 	    sc->cmdq.cur, type, len, async));
1595 
1596 	sc->cmdq.cur = (sc->cmdq.cur + 1) % sc->cmdq.count;
1597 
1598 	if (++sc->cmdq.queued == 1)
1599 		CSR_WRITE_4(sc, IWI_CSR_CMD_WIDX, sc->cmdq.cur);
1600 
1601 	return async ? 0 : tsleep(desc, 0, "iwicmd", hz);
1602 }
1603 
1604 static void
1605 iwi_write_ibssnode(struct iwi_softc *sc, const struct iwi_node *in)
1606 {
1607 	struct iwi_ibssnode node;
1608 
1609 	/* write node information into NIC memory */
1610 	memset(&node, 0, sizeof node);
1611 	IEEE80211_ADDR_COPY(node.bssid, in->in_node.ni_macaddr);
1612 
1613 	CSR_WRITE_REGION_1(sc,
1614 	    IWI_CSR_NODE_BASE + in->in_station * sizeof node,
1615 	    (uint8_t *)&node, sizeof node);
1616 }
1617 
1618 static int
1619 iwi_tx_start(struct ifnet *ifp, struct mbuf *m0, struct ieee80211_node *ni,
1620     int ac)
1621 {
1622 	struct iwi_softc *sc = ifp->if_softc;
1623 	struct ieee80211com *ic = &sc->sc_ic;
1624 	struct iwi_node *in = (struct iwi_node *)ni;
1625 	struct ieee80211_frame *wh;
1626 	struct ieee80211_key *k;
1627 	const struct chanAccParams *cap;
1628 	struct iwi_tx_ring *txq = &sc->txq[ac];
1629 	struct iwi_tx_data *data;
1630 	struct iwi_tx_desc *desc;
1631 	struct mbuf *mnew;
1632 	int error, hdrlen, i, noack = 0;
1633 
1634 	wh = mtod(m0, struct ieee80211_frame *);
1635 
1636 	if (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_QOS) {
1637 		hdrlen = sizeof (struct ieee80211_qosframe);
1638 		cap = &ic->ic_wme.wme_chanParams;
1639 		noack = cap->cap_wmeParams[ac].wmep_noackPolicy;
1640 	} else
1641 		hdrlen = sizeof (struct ieee80211_frame);
1642 
1643 	/*
1644 	 * This is only used in IBSS mode where the firmware expect an index
1645 	 * in a h/w table instead of a destination address.
1646 	 */
1647 	if (ic->ic_opmode == IEEE80211_M_IBSS && in->in_station == -1) {
1648 		in->in_station = iwi_alloc_unr(sc);
1649 
1650 		if (in->in_station == -1) {	/* h/w table is full */
1651 			m_freem(m0);
1652 			ieee80211_free_node(ni);
1653 			ifp->if_oerrors++;
1654 			return 0;
1655 		}
1656 		iwi_write_ibssnode(sc, in);
1657 	}
1658 
1659 	if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1660 		k = ieee80211_crypto_encap(ic, ni, m0);
1661 		if (k == NULL) {
1662 			m_freem(m0);
1663 			return ENOBUFS;
1664 		}
1665 
1666 		/* packet header may have moved, reset our local pointer */
1667 		wh = mtod(m0, struct ieee80211_frame *);
1668 	}
1669 
1670 	if (sc->sc_drvbpf != NULL) {
1671 		struct iwi_tx_radiotap_header *tap = &sc->sc_txtap;
1672 
1673 		tap->wt_flags = 0;
1674 		tap->wt_chan_freq = htole16(ic->ic_ibss_chan->ic_freq);
1675 		tap->wt_chan_flags = htole16(ic->ic_ibss_chan->ic_flags);
1676 
1677 		bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_txtap_len, m0);
1678 	}
1679 
1680 	data = &txq->data[txq->cur];
1681 	desc = &txq->desc[txq->cur];
1682 
1683 	/* save and trim IEEE802.11 header */
1684 	m_copydata(m0, 0, hdrlen, (void *)&desc->wh);
1685 	m_adj(m0, hdrlen);
1686 
1687 	error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m0,
1688 	    BUS_DMA_WRITE | BUS_DMA_NOWAIT);
1689 	if (error != 0 && error != EFBIG) {
1690 		aprint_error_dev(sc->sc_dev, "could not map mbuf (error %d)\n",
1691 		    error);
1692 		m_freem(m0);
1693 		return error;
1694 	}
1695 	if (error != 0) {
1696 		/* too many fragments, linearize */
1697 
1698 		MGETHDR(mnew, M_DONTWAIT, MT_DATA);
1699 		if (mnew == NULL) {
1700 			m_freem(m0);
1701 			return ENOMEM;
1702 		}
1703 
1704 		M_COPY_PKTHDR(mnew, m0);
1705 
1706 		/* If the data won't fit in the header, get a cluster */
1707 		if (m0->m_pkthdr.len > MHLEN) {
1708 			MCLGET(mnew, M_DONTWAIT);
1709 			if (!(mnew->m_flags & M_EXT)) {
1710 				m_freem(m0);
1711 				m_freem(mnew);
1712 				return ENOMEM;
1713 			}
1714 		}
1715 		m_copydata(m0, 0, m0->m_pkthdr.len, mtod(mnew, void *));
1716 		m_freem(m0);
1717 		mnew->m_len = mnew->m_pkthdr.len;
1718 		m0 = mnew;
1719 
1720 		error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m0,
1721 		    BUS_DMA_WRITE | BUS_DMA_NOWAIT);
1722 		if (error != 0) {
1723 			aprint_error_dev(sc->sc_dev,
1724 			    "could not map mbuf (error %d)\n", error);
1725 			m_freem(m0);
1726 			return error;
1727 		}
1728 	}
1729 
1730 	data->m = m0;
1731 	data->ni = ni;
1732 
1733 	desc->hdr.type = IWI_HDR_TYPE_DATA;
1734 	desc->hdr.flags = IWI_HDR_FLAG_IRQ;
1735 	desc->station =
1736 	    (ic->ic_opmode == IEEE80211_M_IBSS) ? in->in_station : 0;
1737 	desc->cmd = IWI_DATA_CMD_TX;
1738 	desc->len = htole16(m0->m_pkthdr.len);
1739 	desc->flags = 0;
1740 	desc->xflags = 0;
1741 
1742 	if (!noack && !IEEE80211_IS_MULTICAST(desc->wh.i_addr1))
1743 		desc->flags |= IWI_DATA_FLAG_NEED_ACK;
1744 
1745 #if 0
1746 	if (ic->ic_flags & IEEE80211_F_PRIVACY) {
1747 		desc->wh.i_fc[1] |= IEEE80211_FC1_WEP;
1748 		desc->wep_txkey = ic->ic_crypto.cs_def_txkey;
1749 	} else
1750 #endif
1751 		desc->flags |= IWI_DATA_FLAG_NO_WEP;
1752 
1753 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
1754 		desc->flags |= IWI_DATA_FLAG_SHPREAMBLE;
1755 
1756 	if (desc->wh.i_fc[0] & IEEE80211_FC0_SUBTYPE_QOS)
1757 		desc->xflags |= IWI_DATA_XFLAG_QOS;
1758 
1759 	if (ic->ic_curmode == IEEE80211_MODE_11B)
1760 		desc->xflags |= IWI_DATA_XFLAG_CCK;
1761 
1762 	desc->nseg = htole32(data->map->dm_nsegs);
1763 	for (i = 0; i < data->map->dm_nsegs; i++) {
1764 		desc->seg_addr[i] = htole32(data->map->dm_segs[i].ds_addr);
1765 		desc->seg_len[i]  = htole16(data->map->dm_segs[i].ds_len);
1766 	}
1767 
1768 	bus_dmamap_sync(sc->sc_dmat, txq->desc_map,
1769 	    txq->cur * IWI_TX_DESC_SIZE,
1770 	    IWI_TX_DESC_SIZE, BUS_DMASYNC_PREWRITE);
1771 
1772 	bus_dmamap_sync(sc->sc_dmat, data->map, 0, data->map->dm_mapsize,
1773 	    BUS_DMASYNC_PREWRITE);
1774 
1775 	DPRINTFN(5, ("sending data frame txq=%u idx=%u len=%u nseg=%u\n",
1776 	    ac, txq->cur, le16toh(desc->len), le32toh(desc->nseg)));
1777 
1778 	/* Inform firmware about this new packet */
1779 	txq->queued++;
1780 	txq->cur = (txq->cur + 1) % txq->count;
1781 	CSR_WRITE_4(sc, txq->csr_widx, txq->cur);
1782 
1783 	return 0;
1784 }
1785 
1786 static void
1787 iwi_start(struct ifnet *ifp)
1788 {
1789 	struct iwi_softc *sc = ifp->if_softc;
1790 	struct ieee80211com *ic = &sc->sc_ic;
1791 	struct mbuf *m0;
1792 	struct ether_header *eh;
1793 	struct ieee80211_node *ni;
1794 	int ac;
1795 
1796 	if (ic->ic_state != IEEE80211_S_RUN)
1797 		return;
1798 
1799 	for (;;) {
1800 		IFQ_DEQUEUE(&ifp->if_snd, m0);
1801 		if (m0 == NULL)
1802 			break;
1803 
1804 		if (m0->m_len < sizeof (struct ether_header) &&
1805 		    (m0 = m_pullup(m0, sizeof (struct ether_header))) == NULL) {
1806 			ifp->if_oerrors++;
1807 			continue;
1808 		}
1809 
1810 		eh = mtod(m0, struct ether_header *);
1811 		ni = ieee80211_find_txnode(ic, eh->ether_dhost);
1812 		if (ni == NULL) {
1813 			m_freem(m0);
1814 			ifp->if_oerrors++;
1815 			continue;
1816 		}
1817 
1818 		/* classify mbuf so we can find which tx ring to use */
1819 		if (ieee80211_classify(ic, m0, ni) != 0) {
1820 			m_freem(m0);
1821 			ieee80211_free_node(ni);
1822 			ifp->if_oerrors++;
1823 			continue;
1824 		}
1825 
1826 		/* no QoS encapsulation for EAPOL frames */
1827 		ac = (eh->ether_type != htons(ETHERTYPE_PAE)) ?
1828 		    M_WME_GETAC(m0) : WME_AC_BE;
1829 
1830 		if (sc->txq[ac].queued > sc->txq[ac].count - 8) {
1831 			/* there is no place left in this ring */
1832 			IFQ_LOCK(&ifp->if_snd);
1833 			IF_PREPEND(&ifp->if_snd, m0);
1834 			IFQ_UNLOCK(&ifp->if_snd);
1835 			ifp->if_flags |= IFF_OACTIVE;
1836 			break;
1837 		}
1838 
1839 		bpf_mtap(ifp, m0);
1840 
1841 		m0 = ieee80211_encap(ic, m0, ni);
1842 		if (m0 == NULL) {
1843 			ieee80211_free_node(ni);
1844 			ifp->if_oerrors++;
1845 			continue;
1846 		}
1847 
1848 		bpf_mtap3(ic->ic_rawbpf, m0);
1849 
1850 		if (iwi_tx_start(ifp, m0, ni, ac) != 0) {
1851 			ieee80211_free_node(ni);
1852 			ifp->if_oerrors++;
1853 			break;
1854 		}
1855 
1856 		/* start watchdog timer */
1857 		sc->sc_tx_timer = 5;
1858 		ifp->if_timer = 1;
1859 	}
1860 }
1861 
1862 static void
1863 iwi_watchdog(struct ifnet *ifp)
1864 {
1865 	struct iwi_softc *sc = ifp->if_softc;
1866 
1867 	ifp->if_timer = 0;
1868 
1869 	if (sc->sc_tx_timer > 0) {
1870 		if (--sc->sc_tx_timer == 0) {
1871 			aprint_error_dev(sc->sc_dev, "device timeout\n");
1872 			ifp->if_oerrors++;
1873 			ifp->if_flags &= ~IFF_UP;
1874 			iwi_stop(ifp, 1);
1875 			return;
1876 		}
1877 		ifp->if_timer = 1;
1878 	}
1879 
1880 	ieee80211_watchdog(&sc->sc_ic);
1881 }
1882 
1883 static int
1884 iwi_get_table0(struct iwi_softc *sc, uint32_t *tbl)
1885 {
1886 	uint32_t size, buf[128];
1887 
1888 	if (!(sc->flags & IWI_FLAG_FW_INITED)) {
1889 		memset(buf, 0, sizeof buf);
1890 		return copyout(buf, tbl, sizeof buf);
1891 	}
1892 
1893 	size = min(CSR_READ_4(sc, IWI_CSR_TABLE0_SIZE), 128 - 1);
1894 	CSR_READ_REGION_4(sc, IWI_CSR_TABLE0_BASE, &buf[1], size);
1895 
1896 	return copyout(buf, tbl, sizeof buf);
1897 }
1898 
1899 static int
1900 iwi_ioctl(struct ifnet *ifp, u_long cmd, void *data)
1901 {
1902 #define	IS_RUNNING(ifp) \
1903 	((ifp->if_flags & IFF_UP) && (ifp->if_flags & IFF_RUNNING))
1904 
1905 	struct iwi_softc *sc = ifp->if_softc;
1906 	struct ieee80211com *ic = &sc->sc_ic;
1907 	struct ifreq *ifr = (struct ifreq *)data;
1908 	int s, error = 0;
1909 	int val;
1910 
1911 	s = splnet();
1912 
1913 	switch (cmd) {
1914 	case SIOCSIFFLAGS:
1915 		if ((error = ifioctl_common(ifp, cmd, data)) != 0)
1916 			break;
1917 		if (ifp->if_flags & IFF_UP) {
1918 			if (!(ifp->if_flags & IFF_RUNNING))
1919 				iwi_init(ifp);
1920 		} else {
1921 			if (ifp->if_flags & IFF_RUNNING)
1922 				iwi_stop(ifp, 1);
1923 		}
1924 		break;
1925 
1926 	case SIOCADDMULTI:
1927 	case SIOCDELMULTI:
1928 		/* XXX no h/w multicast filter? --dyoung */
1929 		if ((error = ether_ioctl(ifp, cmd, data)) == ENETRESET) {
1930 			/* setup multicast filter, etc */
1931 			error = 0;
1932 		}
1933 		break;
1934 
1935 	case SIOCGTABLE0:
1936 		error = iwi_get_table0(sc, (uint32_t *)ifr->ifr_data);
1937 		break;
1938 
1939 	case SIOCGRADIO:
1940 		val = !iwi_getrfkill(sc);
1941 		error = copyout(&val, (int *)ifr->ifr_data, sizeof val);
1942 		break;
1943 
1944 	case SIOCSIFMEDIA:
1945 		if (ifr->ifr_media & IFM_IEEE80211_ADHOC) {
1946 			sc->sc_fwname = "ipw2200-ibss.fw";
1947 		} else if (ifr->ifr_media & IFM_IEEE80211_MONITOR) {
1948 			sc->sc_fwname = "ipw2200-sniffer.fw";
1949 		} else {
1950 			sc->sc_fwname = "ipw2200-bss.fw";
1951 		}
1952 		error = iwi_cache_firmware(sc);
1953 		if (error)
1954  			break;
1955  		/* FALLTRHOUGH */
1956 
1957 	default:
1958 		error = ieee80211_ioctl(&sc->sc_ic, cmd, data);
1959 
1960 		if (error == ENETRESET) {
1961 			if (IS_RUNNING(ifp) &&
1962 			    (ic->ic_roaming != IEEE80211_ROAMING_MANUAL))
1963 				iwi_init(ifp);
1964 			error = 0;
1965 		}
1966 	}
1967 
1968 	splx(s);
1969 	return error;
1970 #undef IS_RUNNING
1971 }
1972 
1973 static void
1974 iwi_stop_master(struct iwi_softc *sc)
1975 {
1976 	int ntries;
1977 
1978 	/* Disable interrupts */
1979 	CSR_WRITE_4(sc, IWI_CSR_INTR_MASK, 0);
1980 
1981 	CSR_WRITE_4(sc, IWI_CSR_RST, IWI_RST_STOP_MASTER);
1982 	for (ntries = 0; ntries < 5; ntries++) {
1983 		if (CSR_READ_4(sc, IWI_CSR_RST) & IWI_RST_MASTER_DISABLED)
1984 			break;
1985 		DELAY(10);
1986 	}
1987 	if (ntries == 5)
1988 		aprint_error_dev(sc->sc_dev, "timeout waiting for master\n");
1989 
1990 	CSR_WRITE_4(sc, IWI_CSR_RST, CSR_READ_4(sc, IWI_CSR_RST) |
1991 	    IWI_RST_PRINCETON_RESET);
1992 
1993 	sc->flags &= ~IWI_FLAG_FW_INITED;
1994 }
1995 
1996 static int
1997 iwi_reset(struct iwi_softc *sc)
1998 {
1999 	int i, ntries;
2000 
2001 	iwi_stop_master(sc);
2002 
2003 	/* Move adapter to D0 state */
2004 	CSR_WRITE_4(sc, IWI_CSR_CTL, CSR_READ_4(sc, IWI_CSR_CTL) |
2005 	    IWI_CTL_INIT);
2006 
2007 	/* Initialize Phase-Locked Level  (PLL) */
2008 	CSR_WRITE_4(sc, IWI_CSR_READ_INT, IWI_READ_INT_INIT_HOST);
2009 
2010 	/* Wait for clock stabilization */
2011 	for (ntries = 0; ntries < 1000; ntries++) {
2012 		if (CSR_READ_4(sc, IWI_CSR_CTL) & IWI_CTL_CLOCK_READY)
2013 			break;
2014 		DELAY(200);
2015 	}
2016 	if (ntries == 1000) {
2017 		aprint_error_dev(sc->sc_dev,
2018 		    "timeout waiting for clock stabilization\n");
2019 		return ETIMEDOUT;
2020 	}
2021 
2022 	CSR_WRITE_4(sc, IWI_CSR_RST, CSR_READ_4(sc, IWI_CSR_RST) |
2023 	    IWI_RST_SW_RESET);
2024 
2025 	DELAY(10);
2026 
2027 	CSR_WRITE_4(sc, IWI_CSR_CTL, CSR_READ_4(sc, IWI_CSR_CTL) |
2028 	    IWI_CTL_INIT);
2029 
2030 	/* Clear NIC memory */
2031 	CSR_WRITE_4(sc, IWI_CSR_AUTOINC_ADDR, 0);
2032 	for (i = 0; i < 0xc000; i++)
2033 		CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, 0);
2034 
2035 	return 0;
2036 }
2037 
2038 static int
2039 iwi_load_ucode(struct iwi_softc *sc, void *uc, int size)
2040 {
2041 	uint16_t *w;
2042 	int ntries, i;
2043 
2044 	CSR_WRITE_4(sc, IWI_CSR_RST, CSR_READ_4(sc, IWI_CSR_RST) |
2045 	    IWI_RST_STOP_MASTER);
2046 	for (ntries = 0; ntries < 5; ntries++) {
2047 		if (CSR_READ_4(sc, IWI_CSR_RST) & IWI_RST_MASTER_DISABLED)
2048 			break;
2049 		DELAY(10);
2050 	}
2051 	if (ntries == 5) {
2052 		aprint_error_dev(sc->sc_dev, "timeout waiting for master\n");
2053 		return ETIMEDOUT;
2054 	}
2055 
2056 	MEM_WRITE_4(sc, 0x3000e0, 0x80000000);
2057 	DELAY(5000);
2058 	CSR_WRITE_4(sc, IWI_CSR_RST, CSR_READ_4(sc, IWI_CSR_RST) &
2059 	    ~IWI_RST_PRINCETON_RESET);
2060 	DELAY(5000);
2061 	MEM_WRITE_4(sc, 0x3000e0, 0);
2062 	DELAY(1000);
2063 	MEM_WRITE_4(sc, 0x300004, 1);
2064 	DELAY(1000);
2065 	MEM_WRITE_4(sc, 0x300004, 0);
2066 	DELAY(1000);
2067 	MEM_WRITE_1(sc, 0x200000, 0x00);
2068 	MEM_WRITE_1(sc, 0x200000, 0x40);
2069 	DELAY(1000);
2070 
2071 	/* Adapter is buggy, we must set the address for each word */
2072 	for (w = uc; size > 0; w++, size -= 2)
2073 		MEM_WRITE_2(sc, 0x200010, htole16(*w));
2074 
2075 	MEM_WRITE_1(sc, 0x200000, 0x00);
2076 	MEM_WRITE_1(sc, 0x200000, 0x80);
2077 
2078 	/* Wait until we get a response in the uc queue */
2079 	for (ntries = 0; ntries < 100; ntries++) {
2080 		if (MEM_READ_1(sc, 0x200000) & 1)
2081 			break;
2082 		DELAY(100);
2083 	}
2084 	if (ntries == 100) {
2085 		aprint_error_dev(sc->sc_dev,
2086 		    "timeout waiting for ucode to initialize\n");
2087 		return ETIMEDOUT;
2088 	}
2089 
2090 	/* Empty the uc queue or the firmware will not initialize properly */
2091 	for (i = 0; i < 7; i++)
2092 		MEM_READ_4(sc, 0x200004);
2093 
2094 	MEM_WRITE_1(sc, 0x200000, 0x00);
2095 
2096 	return 0;
2097 }
2098 
2099 /* macro to handle unaligned little endian data in firmware image */
2100 #define GETLE32(p) ((p)[0] | (p)[1] << 8 | (p)[2] << 16 | (p)[3] << 24)
2101 static int
2102 iwi_load_firmware(struct iwi_softc *sc, void *fw, int size)
2103 {
2104 	bus_dmamap_t map;
2105 	u_char *p, *end;
2106 	uint32_t sentinel, ctl, sum;
2107 	uint32_t cs, sl, cd, cl;
2108 	int ntries, nsegs, error;
2109 	int sn;
2110 
2111 	nsegs = atop((vaddr_t)fw+size-1) - atop((vaddr_t)fw) + 1;
2112 
2113 	/* Create a DMA map for the firmware image */
2114 	error = bus_dmamap_create(sc->sc_dmat, size, nsegs, size, 0,
2115 	    BUS_DMA_NOWAIT, &map);
2116 	if (error != 0) {
2117 		aprint_error_dev(sc->sc_dev,
2118 		    "could not create firmware DMA map\n");
2119 		map = NULL;
2120 		goto fail1;
2121 	}
2122 
2123 	error = bus_dmamap_load(sc->sc_dmat, map, fw, size, NULL,
2124 	    BUS_DMA_NOWAIT | BUS_DMA_WRITE);
2125 	if (error != 0) {
2126 		aprint_error_dev(sc->sc_dev, "could not load fw dma map(%d)\n",
2127 		    error);
2128 		goto fail2;
2129 	}
2130 
2131 	/* Make sure the adapter will get up-to-date values */
2132 	bus_dmamap_sync(sc->sc_dmat, map, 0, size, BUS_DMASYNC_PREWRITE);
2133 
2134 	/* Tell the adapter where the command blocks are stored */
2135 	MEM_WRITE_4(sc, 0x3000a0, 0x27000);
2136 
2137 	/*
2138 	 * Store command blocks into adapter's internal memory using register
2139 	 * indirections. The adapter will read the firmware image through DMA
2140 	 * using information stored in command blocks.
2141 	 */
2142 	p = fw;
2143 	end = p + size;
2144 	CSR_WRITE_4(sc, IWI_CSR_AUTOINC_ADDR, 0x27000);
2145 
2146 	sn = 0;
2147 	sl = cl = 0;
2148 	cs = cd = 0;
2149 	while (p < end) {
2150 		if (sl == 0) {
2151 			cs = map->dm_segs[sn].ds_addr;
2152 			sl = map->dm_segs[sn].ds_len;
2153 			sn++;
2154 		}
2155 		if (cl == 0) {
2156 			cd = GETLE32(p); p += 4; cs += 4; sl -= 4;
2157 			cl = GETLE32(p); p += 4; cs += 4; sl -= 4;
2158 		}
2159 		while (sl > 0 && cl > 0) {
2160 			int len = min(cl, sl);
2161 
2162 			sl -= len;
2163 			cl -= len;
2164 			p += len;
2165 
2166 			while (len > 0) {
2167 				int mlen = min(len, IWI_CB_MAXDATALEN);
2168 
2169 				ctl = IWI_CB_DEFAULT_CTL | mlen;
2170 				sum = ctl ^ cs ^ cd;
2171 
2172 				/* Write a command block */
2173 				CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, ctl);
2174 				CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, cs);
2175 				CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, cd);
2176 				CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, sum);
2177 
2178 				cs += mlen;
2179 				cd += mlen;
2180 				len -= mlen;
2181 			}
2182 		}
2183 	}
2184 
2185 	/* Write a fictive final command block (sentinel) */
2186 	sentinel = CSR_READ_4(sc, IWI_CSR_AUTOINC_ADDR);
2187 	CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, 0);
2188 
2189 	CSR_WRITE_4(sc, IWI_CSR_RST, CSR_READ_4(sc, IWI_CSR_RST) &
2190 	    ~(IWI_RST_MASTER_DISABLED | IWI_RST_STOP_MASTER));
2191 
2192 	/* Tell the adapter to start processing command blocks */
2193 	MEM_WRITE_4(sc, 0x3000a4, 0x540100);
2194 
2195 	/* Wait until the adapter has processed all command blocks */
2196 	for (ntries = 0; ntries < 400; ntries++) {
2197 		if (MEM_READ_4(sc, 0x3000d0) >= sentinel)
2198 			break;
2199 		DELAY(100);
2200 	}
2201 	if (ntries == 400) {
2202 		aprint_error_dev(sc->sc_dev, "timeout processing cb\n");
2203 		error = ETIMEDOUT;
2204 		goto fail3;
2205 	}
2206 
2207 	/* We're done with command blocks processing */
2208 	MEM_WRITE_4(sc, 0x3000a4, 0x540c00);
2209 
2210 	/* Allow interrupts so we know when the firmware is inited */
2211 	CSR_WRITE_4(sc, IWI_CSR_INTR_MASK, IWI_INTR_MASK);
2212 
2213 	/* Tell the adapter to initialize the firmware */
2214 	CSR_WRITE_4(sc, IWI_CSR_RST, 0);
2215 	CSR_WRITE_4(sc, IWI_CSR_CTL, CSR_READ_4(sc, IWI_CSR_CTL) |
2216 	    IWI_CTL_ALLOW_STANDBY);
2217 
2218 	/* Wait at most one second for firmware initialization to complete */
2219 	if ((error = tsleep(sc, 0, "iwiinit", hz)) != 0) {
2220 		aprint_error_dev(sc->sc_dev,
2221 		    "timeout waiting for firmware initialization to complete\n");
2222 		goto fail3;
2223 	}
2224 
2225 fail3:
2226 	bus_dmamap_sync(sc->sc_dmat, map, 0, size, BUS_DMASYNC_POSTWRITE);
2227 	bus_dmamap_unload(sc->sc_dmat, map);
2228 fail2:
2229 	if (map != NULL)
2230 		bus_dmamap_destroy(sc->sc_dmat, map);
2231 
2232 fail1:
2233 	return error;
2234 }
2235 
2236 /*
2237  * Store firmware into kernel memory so we can download it when we need to,
2238  * e.g when the adapter wakes up from suspend mode.
2239  */
2240 static int
2241 iwi_cache_firmware(struct iwi_softc *sc)
2242 {
2243 	struct iwi_firmware *kfw = &sc->fw;
2244 	firmware_handle_t fwh;
2245 	struct iwi_firmware_hdr *hdr;
2246 	off_t size;
2247 	char *fw;
2248 	int error;
2249 
2250 	if (iwi_accept_eula == 0) {
2251 		aprint_error_dev(sc->sc_dev,
2252 		    "EULA not accepted; please see the iwi(4) man page.\n");
2253 		return EPERM;
2254 	}
2255 
2256 	iwi_free_firmware(sc);
2257 	error = firmware_open("if_iwi", sc->sc_fwname, &fwh);
2258 	if (error != 0) {
2259 		aprint_error_dev(sc->sc_dev, "firmware_open failed\n");
2260 		goto fail1;
2261 	}
2262 
2263 	size = firmware_get_size(fwh);
2264 	if (size < sizeof(struct iwi_firmware_hdr)) {
2265 		aprint_error_dev(sc->sc_dev, "image '%s' has no header\n",
2266 		    sc->sc_fwname);
2267 		error = EIO;
2268 		goto fail1;
2269 	}
2270 	sc->sc_blobsize = size;
2271 
2272 	sc->sc_blob = firmware_malloc(size);
2273 	if (sc->sc_blob == NULL) {
2274 		error = ENOMEM;
2275 		firmware_close(fwh);
2276 		goto fail1;
2277 	}
2278 
2279 	error = firmware_read(fwh, 0, sc->sc_blob, size);
2280 	firmware_close(fwh);
2281 	if (error != 0)
2282 		goto fail2;
2283 
2284 	hdr = (struct iwi_firmware_hdr *)sc->sc_blob;
2285 	hdr->version = le32toh(hdr->version);
2286 	hdr->bsize = le32toh(hdr->bsize);
2287 	hdr->usize = le32toh(hdr->usize);
2288 	hdr->fsize = le32toh(hdr->fsize);
2289 
2290 	if (size < sizeof(struct iwi_firmware_hdr) + hdr->bsize + hdr->usize + hdr->fsize) {
2291 		aprint_error_dev(sc->sc_dev, "image '%s' too small\n",
2292 		    sc->sc_fwname);
2293 		error = EIO;
2294 		goto fail2;
2295 	}
2296 
2297 	DPRINTF(("firmware version = %d\n", hdr->version));
2298 	if ((IWI_FW_GET_MAJOR(hdr->version) != IWI_FW_REQ_MAJOR) ||
2299 	    (IWI_FW_GET_MINOR(hdr->version) != IWI_FW_REQ_MINOR)) {
2300 		aprint_error_dev(sc->sc_dev,
2301 		    "version for '%s' %d.%d != %d.%d\n", sc->sc_fwname,
2302 		    IWI_FW_GET_MAJOR(hdr->version),
2303 		    IWI_FW_GET_MINOR(hdr->version),
2304 		    IWI_FW_REQ_MAJOR, IWI_FW_REQ_MINOR);
2305 		error = EIO;
2306 		goto fail2;
2307 	}
2308 
2309 	kfw->boot_size = hdr->bsize;
2310 	kfw->ucode_size = hdr->usize;
2311 	kfw->main_size = hdr->fsize;
2312 
2313 	fw = sc->sc_blob + sizeof(struct iwi_firmware_hdr);
2314 	kfw->boot = fw;
2315 	fw += kfw->boot_size;
2316 	kfw->ucode = fw;
2317 	fw += kfw->ucode_size;
2318 	kfw->main = fw;
2319 
2320 	DPRINTF(("Firmware cached: boot %p, ucode %p, main %p\n",
2321 	    kfw->boot, kfw->ucode, kfw->main));
2322 	DPRINTF(("Firmware cached: boot %u, ucode %u, main %u\n",
2323 	    kfw->boot_size, kfw->ucode_size, kfw->main_size));
2324 
2325 	sc->flags |= IWI_FLAG_FW_CACHED;
2326 
2327 	return 0;
2328 
2329 
2330 fail2:	firmware_free(sc->sc_blob, sc->sc_blobsize);
2331 fail1:
2332 	return error;
2333 }
2334 
2335 static void
2336 iwi_free_firmware(struct iwi_softc *sc)
2337 {
2338 
2339 	if (!(sc->flags & IWI_FLAG_FW_CACHED))
2340 		return;
2341 
2342 	firmware_free(sc->sc_blob, sc->sc_blobsize);
2343 
2344 	sc->flags &= ~IWI_FLAG_FW_CACHED;
2345 }
2346 
2347 static int
2348 iwi_config(struct iwi_softc *sc)
2349 {
2350 	struct ieee80211com *ic = &sc->sc_ic;
2351 	struct ifnet *ifp = &sc->sc_if;
2352 	struct iwi_configuration config;
2353 	struct iwi_rateset rs;
2354 	struct iwi_txpower power;
2355 	struct ieee80211_key *wk;
2356 	struct iwi_wep_key wepkey;
2357 	uint32_t data;
2358 	int error, nchan, i;
2359 
2360 	IEEE80211_ADDR_COPY(ic->ic_myaddr, CLLADDR(ifp->if_sadl));
2361 	DPRINTF(("Setting MAC address to %s\n", ether_sprintf(ic->ic_myaddr)));
2362 	error = iwi_cmd(sc, IWI_CMD_SET_MAC_ADDRESS, ic->ic_myaddr,
2363 	    IEEE80211_ADDR_LEN, 0);
2364 	if (error != 0)
2365 		return error;
2366 
2367 	memset(&config, 0, sizeof config);
2368 	config.bluetooth_coexistence = sc->bluetooth;
2369 	config.antenna = sc->antenna;
2370 	config.silence_threshold = 0x1e;
2371 	config.multicast_enabled = 1;
2372 	config.answer_pbreq = (ic->ic_opmode == IEEE80211_M_IBSS) ? 1 : 0;
2373 	config.disable_unicast_decryption = 1;
2374 	config.disable_multicast_decryption = 1;
2375 	DPRINTF(("Configuring adapter\n"));
2376 	error = iwi_cmd(sc, IWI_CMD_SET_CONFIGURATION, &config, sizeof config,
2377 	    0);
2378 	if (error != 0)
2379 		return error;
2380 
2381 	data = htole32(IWI_POWER_MODE_CAM);
2382 	DPRINTF(("Setting power mode to %u\n", le32toh(data)));
2383 	error = iwi_cmd(sc, IWI_CMD_SET_POWER_MODE, &data, sizeof data, 0);
2384 	if (error != 0)
2385 		return error;
2386 
2387 	data = htole32(ic->ic_rtsthreshold);
2388 	DPRINTF(("Setting RTS threshold to %u\n", le32toh(data)));
2389 	error = iwi_cmd(sc, IWI_CMD_SET_RTS_THRESHOLD, &data, sizeof data, 0);
2390 	if (error != 0)
2391 		return error;
2392 
2393 	data = htole32(ic->ic_fragthreshold);
2394 	DPRINTF(("Setting fragmentation threshold to %u\n", le32toh(data)));
2395 	error = iwi_cmd(sc, IWI_CMD_SET_FRAG_THRESHOLD, &data, sizeof data, 0);
2396 	if (error != 0)
2397 		return error;
2398 
2399 	/*
2400 	 * Set default Tx power for 802.11b/g and 802.11a channels.
2401 	 */
2402 	nchan = 0;
2403 	for (i = 0; i <= IEEE80211_CHAN_MAX; i++) {
2404 		if (!IEEE80211_IS_CHAN_2GHZ(&ic->ic_channels[i]))
2405 			continue;
2406 		power.chan[nchan].chan = i;
2407 		power.chan[nchan].power = IWI_TXPOWER_MAX;
2408 		nchan++;
2409 	}
2410 	power.nchan = nchan;
2411 
2412 	power.mode = IWI_MODE_11G;
2413 	DPRINTF(("Setting .11g channels tx power\n"));
2414 	error = iwi_cmd(sc, IWI_CMD_SET_TX_POWER, &power, sizeof power, 0);
2415 	if (error != 0)
2416 		return error;
2417 
2418 	power.mode = IWI_MODE_11B;
2419 	DPRINTF(("Setting .11b channels tx power\n"));
2420 	error = iwi_cmd(sc, IWI_CMD_SET_TX_POWER, &power, sizeof power, 0);
2421 	if (error != 0)
2422 		return error;
2423 
2424 	nchan = 0;
2425 	for (i = 0; i <= IEEE80211_CHAN_MAX; i++) {
2426 		if (!IEEE80211_IS_CHAN_5GHZ(&ic->ic_channels[i]))
2427 			continue;
2428 		power.chan[nchan].chan = i;
2429 		power.chan[nchan].power = IWI_TXPOWER_MAX;
2430 		nchan++;
2431 	}
2432 	power.nchan = nchan;
2433 
2434 	if (nchan > 0) {	/* 2915ABG only */
2435 		power.mode = IWI_MODE_11A;
2436 		DPRINTF(("Setting .11a channels tx power\n"));
2437 		error = iwi_cmd(sc, IWI_CMD_SET_TX_POWER, &power, sizeof power,
2438 		    0);
2439 		if (error != 0)
2440 			return error;
2441 	}
2442 
2443 	rs.mode = IWI_MODE_11G;
2444 	rs.type = IWI_RATESET_TYPE_SUPPORTED;
2445 	rs.nrates = ic->ic_sup_rates[IEEE80211_MODE_11G].rs_nrates;
2446 	memcpy(rs.rates, ic->ic_sup_rates[IEEE80211_MODE_11G].rs_rates,
2447 	    rs.nrates);
2448 	DPRINTF(("Setting .11bg supported rates (%u)\n", rs.nrates));
2449 	error = iwi_cmd(sc, IWI_CMD_SET_RATES, &rs, sizeof rs, 0);
2450 	if (error != 0)
2451 		return error;
2452 
2453 	rs.mode = IWI_MODE_11A;
2454 	rs.type = IWI_RATESET_TYPE_SUPPORTED;
2455 	rs.nrates = ic->ic_sup_rates[IEEE80211_MODE_11A].rs_nrates;
2456 	memcpy(rs.rates, ic->ic_sup_rates[IEEE80211_MODE_11A].rs_rates,
2457 	    rs.nrates);
2458 	DPRINTF(("Setting .11a supported rates (%u)\n", rs.nrates));
2459 	error = iwi_cmd(sc, IWI_CMD_SET_RATES, &rs, sizeof rs, 0);
2460 	if (error != 0)
2461 		return error;
2462 
2463 	/* if we have a desired ESSID, set it now */
2464 	if (ic->ic_des_esslen != 0) {
2465 #ifdef IWI_DEBUG
2466 		if (iwi_debug > 0) {
2467 			printf("Setting desired ESSID to ");
2468 			ieee80211_print_essid(ic->ic_des_essid,
2469 			    ic->ic_des_esslen);
2470 			printf("\n");
2471 		}
2472 #endif
2473 		error = iwi_cmd(sc, IWI_CMD_SET_ESSID, ic->ic_des_essid,
2474 		    ic->ic_des_esslen, 0);
2475 		if (error != 0)
2476 			return error;
2477 	}
2478 
2479 	cprng_fast(&data, sizeof(data));
2480 	data = htole32(data);
2481 	DPRINTF(("Setting initialization vector to %u\n", le32toh(data)));
2482 	error = iwi_cmd(sc, IWI_CMD_SET_IV, &data, sizeof data, 0);
2483 	if (error != 0)
2484 		return error;
2485 
2486 	if (ic->ic_flags & IEEE80211_F_PRIVACY) {
2487 		/* XXX iwi_setwepkeys? */
2488 		for (i = 0; i < IEEE80211_WEP_NKID; i++) {
2489 			wk = &ic->ic_crypto.cs_nw_keys[i];
2490 
2491 			wepkey.cmd = IWI_WEP_KEY_CMD_SETKEY;
2492 			wepkey.idx = i;
2493 			wepkey.len = wk->wk_keylen;
2494 			memset(wepkey.key, 0, sizeof wepkey.key);
2495 			memcpy(wepkey.key, wk->wk_key, wk->wk_keylen);
2496 			DPRINTF(("Setting wep key index %u len %u\n",
2497 			    wepkey.idx, wepkey.len));
2498 			error = iwi_cmd(sc, IWI_CMD_SET_WEP_KEY, &wepkey,
2499 			    sizeof wepkey, 0);
2500 			if (error != 0)
2501 				return error;
2502 		}
2503 	}
2504 
2505 	/* Enable adapter */
2506 	DPRINTF(("Enabling adapter\n"));
2507 	return iwi_cmd(sc, IWI_CMD_ENABLE, NULL, 0, 0);
2508 }
2509 
2510 static int
2511 iwi_set_chan(struct iwi_softc *sc, struct ieee80211_channel *chan)
2512 {
2513 	struct ieee80211com *ic = &sc->sc_ic;
2514 	struct iwi_scan_v2 scan;
2515 
2516 	(void)memset(&scan, 0, sizeof scan);
2517 
2518 	scan.dwelltime[IWI_SCAN_TYPE_PASSIVE] = htole16(2000);
2519 	scan.channels[0] = 1 |
2520 	    (IEEE80211_IS_CHAN_5GHZ(chan) ? IWI_CHAN_5GHZ : IWI_CHAN_2GHZ);
2521 	scan.channels[1] = ieee80211_chan2ieee(ic, chan);
2522 	iwi_scan_type_set(scan, 1, IWI_SCAN_TYPE_PASSIVE);
2523 
2524 	DPRINTF(("Setting channel to %u\n", ieee80211_chan2ieee(ic, chan)));
2525 	return iwi_cmd(sc, IWI_CMD_SCAN_V2, &scan, sizeof scan, 1);
2526 }
2527 
2528 static int
2529 iwi_scan(struct iwi_softc *sc)
2530 {
2531 	struct ieee80211com *ic = &sc->sc_ic;
2532 	struct iwi_scan_v2 scan;
2533 	uint32_t type;
2534 	uint8_t *p;
2535 	int i, count, idx;
2536 
2537 	(void)memset(&scan, 0, sizeof scan);
2538 	scan.dwelltime[IWI_SCAN_TYPE_ACTIVE_BROADCAST] =
2539 	    htole16(sc->dwelltime);
2540 	scan.dwelltime[IWI_SCAN_TYPE_ACTIVE_BDIRECT] =
2541 	    htole16(sc->dwelltime);
2542 
2543 	/* tell the firmware about the desired essid */
2544 	if (ic->ic_des_esslen) {
2545 		int error;
2546 
2547 		DPRINTF(("%s: Setting adapter desired ESSID to %s\n",
2548 		    __func__, ic->ic_des_essid));
2549 
2550 		error = iwi_cmd(sc, IWI_CMD_SET_ESSID,
2551 		    ic->ic_des_essid, ic->ic_des_esslen, 1);
2552 		if (error)
2553 			return error;
2554 
2555 		type = IWI_SCAN_TYPE_ACTIVE_BDIRECT;
2556 	} else {
2557 		type = IWI_SCAN_TYPE_ACTIVE_BROADCAST;
2558 	}
2559 
2560 	p = &scan.channels[0];
2561 	count = idx = 0;
2562 	for (i = 0; i <= IEEE80211_CHAN_MAX; i++) {
2563 		if (IEEE80211_IS_CHAN_5GHZ(&ic->ic_channels[i]) &&
2564 		    isset(ic->ic_chan_active, i)) {
2565 			*++p = i;
2566 			count++;
2567 			idx++;
2568  			iwi_scan_type_set(scan, idx, type);
2569 		}
2570 	}
2571 	if (count) {
2572 		*(p - count) = IWI_CHAN_5GHZ | count;
2573 		p++;
2574 	}
2575 
2576 	count = 0;
2577 	for (i = 0; i <= IEEE80211_CHAN_MAX; i++) {
2578 		if (IEEE80211_IS_CHAN_2GHZ(&ic->ic_channels[i]) &&
2579 		    isset(ic->ic_chan_active, i)) {
2580 			*++p = i;
2581 			count++;
2582 			idx++;
2583 			iwi_scan_type_set(scan, idx, type);
2584 		}
2585 	}
2586 	*(p - count) = IWI_CHAN_2GHZ | count;
2587 
2588 	DPRINTF(("Start scanning\n"));
2589 	return iwi_cmd(sc, IWI_CMD_SCAN_V2, &scan, sizeof scan, 1);
2590 }
2591 
2592 static int
2593 iwi_auth_and_assoc(struct iwi_softc *sc)
2594 {
2595 	struct ieee80211com *ic = &sc->sc_ic;
2596 	struct ieee80211_node *ni = ic->ic_bss;
2597 	struct ifnet *ifp = &sc->sc_if;
2598 	struct ieee80211_wme_info wme;
2599 	struct iwi_configuration config;
2600 	struct iwi_associate assoc;
2601 	struct iwi_rateset rs;
2602 	uint16_t capinfo;
2603 	uint32_t data;
2604 	int error;
2605 
2606 	memset(&config, 0, sizeof config);
2607 	config.bluetooth_coexistence = sc->bluetooth;
2608 	config.antenna = sc->antenna;
2609 	config.multicast_enabled = 1;
2610 	config.silence_threshold = 0x1e;
2611 	if (ic->ic_curmode == IEEE80211_MODE_11G)
2612 		config.use_protection = 1;
2613 	config.answer_pbreq = (ic->ic_opmode == IEEE80211_M_IBSS) ? 1 : 0;
2614 	config.disable_unicast_decryption = 1;
2615 	config.disable_multicast_decryption = 1;
2616 
2617 	DPRINTF(("Configuring adapter\n"));
2618 	error = iwi_cmd(sc, IWI_CMD_SET_CONFIGURATION, &config,
2619 	    sizeof config, 1);
2620 	if (error != 0)
2621 		return error;
2622 
2623 #ifdef IWI_DEBUG
2624 	if (iwi_debug > 0) {
2625 		aprint_debug_dev(sc->sc_dev, "Setting ESSID to ");
2626 		ieee80211_print_essid(ni->ni_essid, ni->ni_esslen);
2627 		aprint_debug("\n");
2628 	}
2629 #endif
2630 	error = iwi_cmd(sc, IWI_CMD_SET_ESSID, ni->ni_essid, ni->ni_esslen, 1);
2631 	if (error != 0)
2632 		return error;
2633 
2634 	/* the rate set has already been "negotiated" */
2635 	rs.mode = IEEE80211_IS_CHAN_5GHZ(ni->ni_chan) ? IWI_MODE_11A :
2636 	    IWI_MODE_11G;
2637 	rs.type = IWI_RATESET_TYPE_NEGOTIATED;
2638 	rs.nrates = ni->ni_rates.rs_nrates;
2639 
2640 	if (rs.nrates > IWI_RATESET_SIZE) {
2641 		DPRINTF(("Truncating negotiated rate set from %u\n",
2642 		    rs.nrates));
2643 		rs.nrates = IWI_RATESET_SIZE;
2644 	}
2645 	memcpy(rs.rates, ni->ni_rates.rs_rates, rs.nrates);
2646 	DPRINTF(("Setting negotiated rates (%u)\n", rs.nrates));
2647 	error = iwi_cmd(sc, IWI_CMD_SET_RATES, &rs, sizeof rs, 1);
2648 	if (error != 0)
2649 		return error;
2650 
2651 	if ((ic->ic_flags & IEEE80211_F_WME) && ni->ni_wme_ie != NULL) {
2652 		wme.wme_id = IEEE80211_ELEMID_VENDOR;
2653 		wme.wme_len = sizeof (struct ieee80211_wme_info) - 2;
2654 		wme.wme_oui[0] = 0x00;
2655 		wme.wme_oui[1] = 0x50;
2656 		wme.wme_oui[2] = 0xf2;
2657 		wme.wme_type = WME_OUI_TYPE;
2658 		wme.wme_subtype = WME_INFO_OUI_SUBTYPE;
2659 		wme.wme_version = WME_VERSION;
2660 		wme.wme_info = 0;
2661 
2662 		DPRINTF(("Setting WME IE (len=%u)\n", wme.wme_len));
2663 		error = iwi_cmd(sc, IWI_CMD_SET_WMEIE, &wme, sizeof wme, 1);
2664 		if (error != 0)
2665 			return error;
2666 	}
2667 
2668 	if (ic->ic_opt_ie != NULL) {
2669 		DPRINTF(("Setting optional IE (len=%u)\n", ic->ic_opt_ie_len));
2670 		error = iwi_cmd(sc, IWI_CMD_SET_OPTIE, ic->ic_opt_ie,
2671 		    ic->ic_opt_ie_len, 1);
2672 		if (error != 0)
2673 			return error;
2674 	}
2675 	data = htole32(ni->ni_rssi);
2676 	DPRINTF(("Setting sensitivity to %d\n", (int8_t)ni->ni_rssi));
2677 	error = iwi_cmd(sc, IWI_CMD_SET_SENSITIVITY, &data, sizeof data, 1);
2678 	if (error != 0)
2679 		return error;
2680 
2681 	memset(&assoc, 0, sizeof assoc);
2682 	if (IEEE80211_IS_CHAN_A(ni->ni_chan))
2683 		assoc.mode = IWI_MODE_11A;
2684 	else if (IEEE80211_IS_CHAN_G(ni->ni_chan))
2685 		assoc.mode = IWI_MODE_11G;
2686 	else if (IEEE80211_IS_CHAN_B(ni->ni_chan))
2687 		assoc.mode = IWI_MODE_11B;
2688 
2689 	assoc.chan = ieee80211_chan2ieee(ic, ni->ni_chan);
2690 
2691 	if (ni->ni_authmode == IEEE80211_AUTH_SHARED)
2692 		assoc.auth = (ic->ic_crypto.cs_def_txkey << 4) | IWI_AUTH_SHARED;
2693 
2694 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
2695 		assoc.plen = IWI_ASSOC_SHPREAMBLE;
2696 
2697 	if ((ic->ic_flags & IEEE80211_F_WME) && ni->ni_wme_ie != NULL)
2698 		assoc.policy |= htole16(IWI_POLICY_WME);
2699 	if (ic->ic_flags & IEEE80211_F_WPA)
2700 		assoc.policy |= htole16(IWI_POLICY_WPA);
2701 	if (ic->ic_opmode == IEEE80211_M_IBSS && ni->ni_tstamp.tsf == 0)
2702 		assoc.type = IWI_HC_IBSS_START;
2703 	else
2704 		assoc.type = IWI_HC_ASSOC;
2705 	memcpy(assoc.tstamp, ni->ni_tstamp.data, 8);
2706 
2707 	if (ic->ic_opmode == IEEE80211_M_IBSS)
2708 		capinfo = IEEE80211_CAPINFO_IBSS;
2709 	else
2710 		capinfo = IEEE80211_CAPINFO_ESS;
2711 	if (ic->ic_flags & IEEE80211_F_PRIVACY)
2712 		capinfo |= IEEE80211_CAPINFO_PRIVACY;
2713 	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
2714 	    IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
2715 		capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
2716 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
2717 		capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
2718 	assoc.capinfo = htole16(capinfo);
2719 
2720 	assoc.lintval = htole16(ic->ic_lintval);
2721 	assoc.intval = htole16(ni->ni_intval);
2722 	IEEE80211_ADDR_COPY(assoc.bssid, ni->ni_bssid);
2723 	if (ic->ic_opmode == IEEE80211_M_IBSS)
2724 		IEEE80211_ADDR_COPY(assoc.dst, ifp->if_broadcastaddr);
2725 	else
2726 		IEEE80211_ADDR_COPY(assoc.dst, ni->ni_bssid);
2727 
2728 	DPRINTF(("%s bssid %s dst %s channel %u policy 0x%x "
2729 	    "auth %u capinfo 0x%x lintval %u bintval %u\n",
2730 	    assoc.type == IWI_HC_IBSS_START ? "Start" : "Join",
2731 	    ether_sprintf(assoc.bssid), ether_sprintf(assoc.dst),
2732 	    assoc.chan, le16toh(assoc.policy), assoc.auth,
2733 	    le16toh(assoc.capinfo), le16toh(assoc.lintval),
2734 	    le16toh(assoc.intval)));
2735 
2736 	return iwi_cmd(sc, IWI_CMD_ASSOCIATE, &assoc, sizeof assoc, 1);
2737 }
2738 
2739 static int
2740 iwi_init(struct ifnet *ifp)
2741 {
2742 	struct iwi_softc *sc = ifp->if_softc;
2743 	struct ieee80211com *ic = &sc->sc_ic;
2744 	struct iwi_firmware *fw = &sc->fw;
2745 	int i, error;
2746 
2747 	/* exit immediately if firmware has not been ioctl'd */
2748 	if (!(sc->flags & IWI_FLAG_FW_CACHED)) {
2749 		if ((error = iwi_cache_firmware(sc)) != 0) {
2750 			aprint_error_dev(sc->sc_dev,
2751 			    "could not cache the firmware\n");
2752 			goto fail;
2753 		}
2754 	}
2755 
2756 	iwi_stop(ifp, 0);
2757 
2758 	if ((error = iwi_reset(sc)) != 0) {
2759 		aprint_error_dev(sc->sc_dev, "could not reset adapter\n");
2760 		goto fail;
2761 	}
2762 
2763 	if ((error = iwi_load_firmware(sc, fw->boot, fw->boot_size)) != 0) {
2764 		aprint_error_dev(sc->sc_dev, "could not load boot firmware\n");
2765 		goto fail;
2766 	}
2767 
2768 	if ((error = iwi_load_ucode(sc, fw->ucode, fw->ucode_size)) != 0) {
2769 		aprint_error_dev(sc->sc_dev, "could not load microcode\n");
2770 		goto fail;
2771 	}
2772 
2773 	iwi_stop_master(sc);
2774 
2775 	CSR_WRITE_4(sc, IWI_CSR_CMD_BASE, sc->cmdq.desc_map->dm_segs[0].ds_addr);
2776 	CSR_WRITE_4(sc, IWI_CSR_CMD_SIZE, sc->cmdq.count);
2777 	CSR_WRITE_4(sc, IWI_CSR_CMD_WIDX, sc->cmdq.cur);
2778 
2779 	CSR_WRITE_4(sc, IWI_CSR_TX1_BASE, sc->txq[0].desc_map->dm_segs[0].ds_addr);
2780 	CSR_WRITE_4(sc, IWI_CSR_TX1_SIZE, sc->txq[0].count);
2781 	CSR_WRITE_4(sc, IWI_CSR_TX1_WIDX, sc->txq[0].cur);
2782 
2783 	CSR_WRITE_4(sc, IWI_CSR_TX2_BASE, sc->txq[1].desc_map->dm_segs[0].ds_addr);
2784 	CSR_WRITE_4(sc, IWI_CSR_TX2_SIZE, sc->txq[1].count);
2785 	CSR_WRITE_4(sc, IWI_CSR_TX2_WIDX, sc->txq[1].cur);
2786 
2787 	CSR_WRITE_4(sc, IWI_CSR_TX3_BASE, sc->txq[2].desc_map->dm_segs[0].ds_addr);
2788 	CSR_WRITE_4(sc, IWI_CSR_TX3_SIZE, sc->txq[2].count);
2789 	CSR_WRITE_4(sc, IWI_CSR_TX3_WIDX, sc->txq[2].cur);
2790 
2791 	CSR_WRITE_4(sc, IWI_CSR_TX4_BASE, sc->txq[3].desc_map->dm_segs[0].ds_addr);
2792 	CSR_WRITE_4(sc, IWI_CSR_TX4_SIZE, sc->txq[3].count);
2793 	CSR_WRITE_4(sc, IWI_CSR_TX4_WIDX, sc->txq[3].cur);
2794 
2795 	for (i = 0; i < sc->rxq.count; i++)
2796 		CSR_WRITE_4(sc, IWI_CSR_RX_BASE + i * 4,
2797 		    sc->rxq.data[i].map->dm_segs[0].ds_addr);
2798 
2799 	CSR_WRITE_4(sc, IWI_CSR_RX_WIDX, sc->rxq.count -1);
2800 
2801 	if ((error = iwi_load_firmware(sc, fw->main, fw->main_size)) != 0) {
2802 		aprint_error_dev(sc->sc_dev, "could not load main firmware\n");
2803 		goto fail;
2804 	}
2805 
2806 	sc->flags |= IWI_FLAG_FW_INITED;
2807 
2808 	if ((error = iwi_config(sc)) != 0) {
2809 		aprint_error_dev(sc->sc_dev, "device configuration failed\n");
2810 		goto fail;
2811 	}
2812 
2813 	ic->ic_state = IEEE80211_S_INIT;
2814 
2815 	ifp->if_flags &= ~IFF_OACTIVE;
2816 	ifp->if_flags |= IFF_RUNNING;
2817 
2818 	if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2819 		if (ic->ic_roaming != IEEE80211_ROAMING_MANUAL)
2820 			ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
2821 	} else
2822 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
2823 
2824 	return 0;
2825 
2826 fail:	ifp->if_flags &= ~IFF_UP;
2827 	iwi_stop(ifp, 0);
2828 
2829 	return error;
2830 }
2831 
2832 
2833 /*
2834  * Return whether or not the radio is enabled in hardware
2835  * (i.e. the rfkill switch is "off").
2836  */
2837 static int
2838 iwi_getrfkill(struct iwi_softc *sc)
2839 {
2840 	return (CSR_READ_4(sc, IWI_CSR_IO) & IWI_IO_RADIO_ENABLED) == 0;
2841 }
2842 
2843 static int
2844 iwi_sysctl_radio(SYSCTLFN_ARGS)
2845 {
2846 	struct sysctlnode node;
2847 	struct iwi_softc *sc;
2848 	int val, error;
2849 
2850 	node = *rnode;
2851 	sc = (struct iwi_softc *)node.sysctl_data;
2852 
2853 	val = !iwi_getrfkill(sc);
2854 
2855 	node.sysctl_data = &val;
2856 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
2857 
2858 	if (error || newp == NULL)
2859 		return error;
2860 
2861 	return 0;
2862 }
2863 
2864 #ifdef IWI_DEBUG
2865 SYSCTL_SETUP(sysctl_iwi, "sysctl iwi(4) subtree setup")
2866 {
2867 	int rc;
2868 	const struct sysctlnode *rnode;
2869 	const struct sysctlnode *cnode;
2870 
2871 	if ((rc = sysctl_createv(clog, 0, NULL, &rnode,
2872 	    CTLFLAG_PERMANENT, CTLTYPE_NODE, "iwi",
2873 	    SYSCTL_DESCR("iwi global controls"),
2874 	    NULL, 0, NULL, 0, CTL_HW, CTL_CREATE, CTL_EOL)) != 0)
2875 		goto err;
2876 
2877 	/* control debugging printfs */
2878 	if ((rc = sysctl_createv(clog, 0, &rnode, &cnode,
2879 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT,
2880 	    "debug", SYSCTL_DESCR("Enable debugging output"),
2881 	    NULL, 0, &iwi_debug, 0, CTL_CREATE, CTL_EOL)) != 0)
2882 		goto err;
2883 
2884 	return;
2885 err:
2886 	aprint_error("%s: sysctl_createv failed (rc = %d)\n", __func__, rc);
2887 }
2888 
2889 #endif /* IWI_DEBUG */
2890 
2891 /*
2892  * Add sysctl knobs.
2893  */
2894 static void
2895 iwi_sysctlattach(struct iwi_softc *sc)
2896 {
2897 	int rc;
2898 	const struct sysctlnode *rnode;
2899 	const struct sysctlnode *cnode;
2900 
2901 	struct sysctllog **clog = &sc->sc_sysctllog;
2902 
2903 	if ((rc = sysctl_createv(clog, 0, NULL, &rnode,
2904 	    CTLFLAG_PERMANENT, CTLTYPE_NODE, device_xname(sc->sc_dev),
2905 	    SYSCTL_DESCR("iwi controls and statistics"),
2906 	    NULL, 0, NULL, 0, CTL_HW, CTL_CREATE, CTL_EOL)) != 0)
2907 		goto err;
2908 
2909 	if ((rc = sysctl_createv(clog, 0, &rnode, &cnode,
2910 	    CTLFLAG_PERMANENT, CTLTYPE_INT, "radio",
2911 	    SYSCTL_DESCR("radio transmitter switch state (0=off, 1=on)"),
2912 	    iwi_sysctl_radio, 0, (void *)sc, 0, CTL_CREATE, CTL_EOL)) != 0)
2913 		goto err;
2914 
2915 	sc->dwelltime = 100;
2916 	if ((rc = sysctl_createv(clog, 0, &rnode, &cnode,
2917 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT,
2918 	    "dwell", SYSCTL_DESCR("channel dwell time (ms) for AP/station scanning"),
2919 	    NULL, 0, &sc->dwelltime, 0, CTL_CREATE, CTL_EOL)) != 0)
2920 		goto err;
2921 
2922 	sc->bluetooth = 0;
2923 	if ((rc = sysctl_createv(clog, 0, &rnode, &cnode,
2924 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT,
2925 	    "bluetooth", SYSCTL_DESCR("bluetooth coexistence"),
2926 	    NULL, 0, &sc->bluetooth, 0, CTL_CREATE, CTL_EOL)) != 0)
2927 		goto err;
2928 
2929 	sc->antenna = IWI_ANTENNA_AUTO;
2930 	if ((rc = sysctl_createv(clog, 0, &rnode, &cnode,
2931 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT,
2932 	    "antenna", SYSCTL_DESCR("antenna (0=auto)"),
2933 	    NULL, 0, &sc->antenna, 0, CTL_CREATE, CTL_EOL)) != 0)
2934 		goto err;
2935 
2936 	return;
2937 err:
2938 	aprint_error("%s: sysctl_createv failed (rc = %d)\n", __func__, rc);
2939 }
2940 
2941 static void
2942 iwi_stop(struct ifnet *ifp, int disable)
2943 {
2944 	struct iwi_softc *sc = ifp->if_softc;
2945 	struct ieee80211com *ic = &sc->sc_ic;
2946 
2947 	IWI_LED_OFF(sc);
2948 
2949 	iwi_stop_master(sc);
2950 	CSR_WRITE_4(sc, IWI_CSR_RST, IWI_RST_SW_RESET);
2951 
2952 	/* reset rings */
2953 	iwi_reset_cmd_ring(sc, &sc->cmdq);
2954 	iwi_reset_tx_ring(sc, &sc->txq[0]);
2955 	iwi_reset_tx_ring(sc, &sc->txq[1]);
2956 	iwi_reset_tx_ring(sc, &sc->txq[2]);
2957 	iwi_reset_tx_ring(sc, &sc->txq[3]);
2958 	iwi_reset_rx_ring(sc, &sc->rxq);
2959 
2960 	ifp->if_timer = 0;
2961 	ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
2962 
2963 	ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
2964 }
2965 
2966 static void
2967 iwi_led_set(struct iwi_softc *sc, uint32_t state, int toggle)
2968 {
2969 	uint32_t val;
2970 
2971 	val = MEM_READ_4(sc, IWI_MEM_EVENT_CTL);
2972 
2973 	switch (sc->nictype) {
2974 	case 1:
2975 		/* special NIC type: reversed leds */
2976 		if (state == IWI_LED_ACTIVITY) {
2977 			state &= ~IWI_LED_ACTIVITY;
2978 			state |= IWI_LED_ASSOCIATED;
2979 		} else if (state == IWI_LED_ASSOCIATED) {
2980 			state &= ~IWI_LED_ASSOCIATED;
2981 			state |= IWI_LED_ACTIVITY;
2982 		}
2983 		/* and ignore toggle effect */
2984 		val |= state;
2985 		break;
2986 	case 0:
2987 	case 2:
2988 	case 3:
2989 	case 4:
2990 		val = (toggle && (val & state)) ? val & ~state : val | state;
2991 		break;
2992 	default:
2993 		aprint_normal_dev(sc->sc_dev, "unknown NIC type %d\n",
2994 		    sc->nictype);
2995 		return;
2996 		break;
2997 	}
2998 
2999 	MEM_WRITE_4(sc, IWI_MEM_EVENT_CTL, val);
3000 
3001 	return;
3002 }
3003 
3004 SYSCTL_SETUP(sysctl_hw_iwi_accept_eula_setup, "sysctl hw.iwi.accept_eula")
3005 {
3006 	const struct sysctlnode *rnode;
3007 	const struct sysctlnode *cnode;
3008 
3009 	sysctl_createv(NULL, 0, NULL, &rnode,
3010 		CTLFLAG_PERMANENT,
3011 		CTLTYPE_NODE, "iwi",
3012 		NULL,
3013 		NULL, 0,
3014 		NULL, 0,
3015 		CTL_HW, CTL_CREATE, CTL_EOL);
3016 
3017 	sysctl_createv(NULL, 0, &rnode, &cnode,
3018 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
3019 		CTLTYPE_INT, "accept_eula",
3020 		SYSCTL_DESCR("Accept Intel EULA and permit use of iwi(4) firmware"),
3021 		NULL, 0,
3022 		&iwi_accept_eula, sizeof(iwi_accept_eula),
3023 		CTL_CREATE, CTL_EOL);
3024 }
3025