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