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