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