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