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