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