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