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