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