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