if_iwi.c revision 166848
1/*-
2 * Copyright (c) 2004, 2005
3 *      Damien Bergamini <damien.bergamini@free.fr>. All rights reserved.
4 * Copyright (c) 2005-2006 Sam Leffler, Errno Consulting
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 *    notice unmodified, this list of conditions, and the following
11 *    disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29#include <sys/cdefs.h>
30__FBSDID("$FreeBSD: head/sys/dev/iwi/if_iwi.c 166848 2007-02-20 15:45:59Z luigi $");
31
32/*-
33 * Intel(R) PRO/Wireless 2200BG/2225BG/2915ABG driver
34 * http://www.intel.com/network/connectivity/products/wireless/prowireless_mobile.htm
35 */
36
37#include <sys/param.h>
38#include <sys/sysctl.h>
39#include <sys/sockio.h>
40#include <sys/mbuf.h>
41#include <sys/kernel.h>
42#include <sys/socket.h>
43#include <sys/systm.h>
44#include <sys/malloc.h>
45#include <sys/lock.h>
46#include <sys/mutex.h>
47#include <sys/module.h>
48#include <sys/bus.h>
49#include <sys/endian.h>
50#include <sys/proc.h>
51#include <sys/mount.h>
52#include <sys/namei.h>
53#include <sys/linker.h>
54#include <sys/firmware.h>
55#include <sys/kthread.h>
56#include <sys/taskqueue.h>
57
58#include <machine/bus.h>
59#include <machine/resource.h>
60#include <sys/rman.h>
61
62#include <dev/pci/pcireg.h>
63#include <dev/pci/pcivar.h>
64
65#include <net/bpf.h>
66#include <net/if.h>
67#include <net/if_arp.h>
68#include <net/ethernet.h>
69#include <net/if_dl.h>
70#include <net/if_media.h>
71#include <net/if_types.h>
72
73#include <net80211/ieee80211_var.h>
74#include <net80211/ieee80211_radiotap.h>
75
76#include <netinet/in.h>
77#include <netinet/in_systm.h>
78#include <netinet/in_var.h>
79#include <netinet/ip.h>
80#include <netinet/if_ether.h>
81
82#include <dev/iwi/if_iwireg.h>
83#include <dev/iwi/if_iwivar.h>
84
85#define IWI_DEBUG
86#ifdef IWI_DEBUG
87#define DPRINTF(x)	do { if (iwi_debug > 0) printf x; } while (0)
88#define DPRINTFN(n, x)	do { if (iwi_debug >= (n)) printf x; } while (0)
89int iwi_debug = 0;
90SYSCTL_INT(_debug, OID_AUTO, iwi, CTLFLAG_RW, &iwi_debug, 0, "iwi debug level");
91#else
92#define DPRINTF(x)
93#define DPRINTFN(n, x)
94#endif
95
96MODULE_DEPEND(iwi, pci,  1, 1, 1);
97MODULE_DEPEND(iwi, wlan, 1, 1, 1);
98MODULE_DEPEND(iwi, firmware, 1, 1, 1);
99
100enum {
101	IWI_LED_TX,
102	IWI_LED_RX,
103	IWI_LED_POLL,
104};
105
106struct iwi_ident {
107	uint16_t	vendor;
108	uint16_t	device;
109	const char	*name;
110};
111
112static const struct iwi_ident iwi_ident_table[] = {
113	{ 0x8086, 0x4220, "Intel(R) PRO/Wireless 2200BG" },
114	{ 0x8086, 0x4221, "Intel(R) PRO/Wireless 2225BG" },
115	{ 0x8086, 0x4223, "Intel(R) PRO/Wireless 2915ABG" },
116	{ 0x8086, 0x4224, "Intel(R) PRO/Wireless 2915ABG" },
117
118	{ 0, 0, NULL }
119};
120
121static void	iwi_dma_map_addr(void *, bus_dma_segment_t *, int, int);
122static int	iwi_alloc_cmd_ring(struct iwi_softc *, struct iwi_cmd_ring *,
123		    int);
124static void	iwi_reset_cmd_ring(struct iwi_softc *, struct iwi_cmd_ring *);
125static void	iwi_free_cmd_ring(struct iwi_softc *, struct iwi_cmd_ring *);
126static int	iwi_alloc_tx_ring(struct iwi_softc *, struct iwi_tx_ring *,
127		    int, bus_addr_t, bus_addr_t);
128static void	iwi_reset_tx_ring(struct iwi_softc *, struct iwi_tx_ring *);
129static void	iwi_free_tx_ring(struct iwi_softc *, struct iwi_tx_ring *);
130static int	iwi_alloc_rx_ring(struct iwi_softc *, struct iwi_rx_ring *,
131		    int);
132static void	iwi_reset_rx_ring(struct iwi_softc *, struct iwi_rx_ring *);
133static void	iwi_free_rx_ring(struct iwi_softc *, struct iwi_rx_ring *);
134static struct	ieee80211_node *iwi_node_alloc(struct ieee80211_node_table *);
135static void	iwi_node_free(struct ieee80211_node *);
136static int	iwi_media_change(struct ifnet *);
137static void	iwi_media_status(struct ifnet *, struct ifmediareq *);
138static int	iwi_newstate(struct ieee80211com *, enum ieee80211_state, int);
139static void	iwi_wme_init(struct iwi_softc *);
140static void	iwi_wme_setparams(void *, int);
141static int	iwi_wme_update(struct ieee80211com *);
142static uint16_t	iwi_read_prom_word(struct iwi_softc *, uint8_t);
143static void	iwi_frame_intr(struct iwi_softc *, struct iwi_rx_data *, int,
144		    struct iwi_frame *);
145static void	iwi_notification_intr(struct iwi_softc *, struct iwi_notif *);
146static void	iwi_rx_intr(struct iwi_softc *);
147static void	iwi_tx_intr(struct iwi_softc *, struct iwi_tx_ring *);
148static void	iwi_intr(void *);
149static int	iwi_cmd(struct iwi_softc *, uint8_t, void *, uint8_t);
150static void	iwi_write_ibssnode(struct iwi_softc *, const u_int8_t [], int);
151static int	iwi_tx_start(struct ifnet *, struct mbuf *,
152		    struct ieee80211_node *, int);
153static void	iwi_start(struct ifnet *);
154static void	iwi_watchdog(struct ifnet *);
155static int	iwi_ioctl(struct ifnet *, u_long, caddr_t);
156static void	iwi_stop_master(struct iwi_softc *);
157static int	iwi_reset(struct iwi_softc *);
158static int	iwi_load_ucode(struct iwi_softc *, const struct iwi_fw *);
159static int	iwi_load_firmware(struct iwi_softc *, const struct iwi_fw *);
160static void	iwi_release_fw_dma(struct iwi_softc *sc);
161static int	iwi_config(struct iwi_softc *);
162static int	iwi_get_firmware(struct iwi_softc *);
163static void	iwi_put_firmware(struct iwi_softc *);
164static void	iwi_scanabort(void *, int);
165static void	iwi_scandone(void *, int);
166static void	iwi_scanstart(void *, int);
167static void	iwi_scanchan(void *, int);
168static int	iwi_auth_and_assoc(struct iwi_softc *);
169static int	iwi_disassociate(struct iwi_softc *, int quiet);
170static void	iwi_down(void *, int);
171static void	iwi_init(void *);
172static void	iwi_init_locked(void *, int);
173static void	iwi_stop(void *);
174static void	iwi_restart(void *, int);
175static int	iwi_getrfkill(struct iwi_softc *);
176static void	iwi_radio_on(void *, int);
177static void	iwi_radio_off(void *, int);
178static void	iwi_sysctlattach(struct iwi_softc *);
179static void	iwi_led_event(struct iwi_softc *, int);
180static void	iwi_ledattach(struct iwi_softc *);
181
182static int iwi_probe(device_t);
183static int iwi_attach(device_t);
184static int iwi_detach(device_t);
185static int iwi_shutdown(device_t);
186static int iwi_suspend(device_t);
187static int iwi_resume(device_t);
188
189static device_method_t iwi_methods[] = {
190	/* Device interface */
191	DEVMETHOD(device_probe,		iwi_probe),
192	DEVMETHOD(device_attach,	iwi_attach),
193	DEVMETHOD(device_detach,	iwi_detach),
194	DEVMETHOD(device_shutdown,	iwi_shutdown),
195	DEVMETHOD(device_suspend,	iwi_suspend),
196	DEVMETHOD(device_resume,	iwi_resume),
197
198	{ 0, 0 }
199};
200
201static driver_t iwi_driver = {
202	"iwi",
203	iwi_methods,
204	sizeof (struct iwi_softc)
205};
206
207static devclass_t iwi_devclass;
208
209DRIVER_MODULE(iwi, pci, iwi_driver, iwi_devclass, 0, 0);
210
211/*
212 * Supported rates for 802.11a/b/g modes (in 500Kbps unit).
213 */
214static const struct ieee80211_rateset iwi_rateset_11a =
215	{ 8, { 12, 18, 24, 36, 48, 72, 96, 108 } };
216
217static const struct ieee80211_rateset iwi_rateset_11b =
218	{ 4, { 2, 4, 11, 22 } };
219
220static const struct ieee80211_rateset iwi_rateset_11g =
221	{ 12, { 2, 4, 11, 22, 12, 18, 24, 36, 48, 72, 96, 108 } };
222
223static __inline uint8_t
224MEM_READ_1(struct iwi_softc *sc, uint32_t addr)
225{
226	CSR_WRITE_4(sc, IWI_CSR_INDIRECT_ADDR, addr);
227	return CSR_READ_1(sc, IWI_CSR_INDIRECT_DATA);
228}
229
230static __inline uint32_t
231MEM_READ_4(struct iwi_softc *sc, uint32_t addr)
232{
233	CSR_WRITE_4(sc, IWI_CSR_INDIRECT_ADDR, addr);
234	return CSR_READ_4(sc, IWI_CSR_INDIRECT_DATA);
235}
236
237static int
238iwi_probe(device_t dev)
239{
240	const struct iwi_ident *ident;
241
242	for (ident = iwi_ident_table; ident->name != NULL; ident++) {
243		if (pci_get_vendor(dev) == ident->vendor &&
244		    pci_get_device(dev) == ident->device) {
245			device_set_desc(dev, ident->name);
246			return 0;
247		}
248	}
249	return ENXIO;
250}
251
252/* Base Address Register */
253#define IWI_PCI_BAR0	0x10
254
255static int
256iwi_attach(device_t dev)
257{
258	struct iwi_softc *sc = device_get_softc(dev);
259	struct ifnet *ifp;
260	struct ieee80211com *ic = &sc->sc_ic;
261	uint16_t val;
262	int error, i;
263
264	sc->sc_dev = dev;
265
266	mtx_init(&sc->sc_mtx, device_get_nameunit(dev), MTX_NETWORK_LOCK,
267	    MTX_DEF);
268
269	sc->sc_unr = new_unrhdr(1, IWI_MAX_IBSSNODE-1, &sc->sc_mtx);
270
271#if __FreeBSD_version >= 700000
272	sc->sc_tq = taskqueue_create("iwi_taskq", M_NOWAIT,
273		taskqueue_thread_enqueue, &sc->sc_tq);
274	taskqueue_start_threads(&sc->sc_tq, 1, PI_NET, "%s taskq",
275		device_get_nameunit(dev));
276#else
277	sc->sc_tq = taskqueue_create("iwi_taskq", M_NOWAIT,
278		taskqueue_thread_enqueue, &sc->sc_tq, &sc->sc_tqproc);
279	kthread_create(taskqueue_thread_loop, &sc->sc_tq, &sc->sc_tqproc,
280		0, 0, "%s taskq", device_get_nameunit(dev));
281#endif
282	TASK_INIT(&sc->sc_radiontask, 0, iwi_radio_on, sc);
283	TASK_INIT(&sc->sc_radiofftask, 0, iwi_radio_off, sc);
284	TASK_INIT(&sc->sc_scanstarttask, 0, iwi_scanstart, sc);
285	TASK_INIT(&sc->sc_scanaborttask, 0, iwi_scanabort, sc);
286	TASK_INIT(&sc->sc_scandonetask, 0, iwi_scandone, sc);
287	TASK_INIT(&sc->sc_scantask, 0, iwi_scanchan, sc);
288	TASK_INIT(&sc->sc_setwmetask, 0, iwi_wme_setparams, sc);
289	TASK_INIT(&sc->sc_downtask, 0, iwi_down, sc);
290	TASK_INIT(&sc->sc_restarttask, 0, iwi_restart, sc);
291
292	if (pci_get_powerstate(dev) != PCI_POWERSTATE_D0) {
293		device_printf(dev, "chip is in D%d power mode "
294		    "-- setting to D0\n", pci_get_powerstate(dev));
295		pci_set_powerstate(dev, PCI_POWERSTATE_D0);
296	}
297
298	pci_write_config(dev, 0x41, 0, 1);
299
300	/* enable bus-mastering */
301	pci_enable_busmaster(dev);
302
303	sc->mem_rid = IWI_PCI_BAR0;
304	sc->mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &sc->mem_rid,
305	    RF_ACTIVE);
306	if (sc->mem == NULL) {
307		device_printf(dev, "could not allocate memory resource\n");
308		goto fail;
309	}
310
311	sc->sc_st = rman_get_bustag(sc->mem);
312	sc->sc_sh = rman_get_bushandle(sc->mem);
313
314	sc->irq_rid = 0;
315	sc->irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &sc->irq_rid,
316	    RF_ACTIVE | RF_SHAREABLE);
317	if (sc->irq == NULL) {
318		device_printf(dev, "could not allocate interrupt resource\n");
319		goto fail;
320	}
321
322	if (iwi_reset(sc) != 0) {
323		device_printf(dev, "could not reset adapter\n");
324		goto fail;
325	}
326
327	/*
328	 * Allocate rings.
329	 */
330	if (iwi_alloc_cmd_ring(sc, &sc->cmdq, IWI_CMD_RING_COUNT) != 0) {
331		device_printf(dev, "could not allocate Cmd ring\n");
332		goto fail;
333	}
334
335	for (i = 0; i < 4; i++) {
336		error = iwi_alloc_tx_ring(sc, &sc->txq[i], IWI_TX_RING_COUNT,
337		    IWI_CSR_TX1_RIDX + i * 4,
338		    IWI_CSR_TX1_WIDX + i * 4);
339		if (error != 0) {
340			device_printf(dev, "could not allocate Tx ring %d\n",
341				i+i);
342			goto fail;
343		}
344	}
345
346	if (iwi_alloc_rx_ring(sc, &sc->rxq, IWI_RX_RING_COUNT) != 0) {
347		device_printf(dev, "could not allocate Rx ring\n");
348		goto fail;
349	}
350
351	iwi_wme_init(sc);
352
353	ifp = sc->sc_ifp = if_alloc(IFT_ETHER);
354	if (ifp == NULL) {
355		device_printf(dev, "can not if_alloc()\n");
356		goto fail;
357	}
358	ifp->if_softc = sc;
359	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
360	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
361	ifp->if_init = iwi_init;
362	ifp->if_ioctl = iwi_ioctl;
363	ifp->if_start = iwi_start;
364	ifp->if_watchdog = iwi_watchdog;
365	IFQ_SET_MAXLEN(&ifp->if_snd, IFQ_MAXLEN);
366	ifp->if_snd.ifq_drv_maxlen = IFQ_MAXLEN;
367	IFQ_SET_READY(&ifp->if_snd);
368
369	ic->ic_ifp = ifp;
370	ic->ic_wme.wme_update = iwi_wme_update;
371	ic->ic_phytype = IEEE80211_T_OFDM; /* not only, but not used */
372	ic->ic_opmode = IEEE80211_M_STA; /* default to BSS mode */
373	ic->ic_state = IEEE80211_S_INIT;
374
375	/* set device capabilities */
376	ic->ic_caps =
377	    IEEE80211_C_IBSS |		/* IBSS mode supported */
378	    IEEE80211_C_MONITOR |	/* monitor mode supported */
379	    IEEE80211_C_PMGT |		/* power save supported */
380	    IEEE80211_C_SHPREAMBLE |	/* short preamble supported */
381	    IEEE80211_C_WPA |		/* 802.11i */
382	    IEEE80211_C_WME;		/* 802.11e */
383
384	/* read MAC address from EEPROM */
385	val = iwi_read_prom_word(sc, IWI_EEPROM_MAC + 0);
386	ic->ic_myaddr[0] = val & 0xff;
387	ic->ic_myaddr[1] = val >> 8;
388	val = iwi_read_prom_word(sc, IWI_EEPROM_MAC + 1);
389	ic->ic_myaddr[2] = val & 0xff;
390	ic->ic_myaddr[3] = val >> 8;
391	val = iwi_read_prom_word(sc, IWI_EEPROM_MAC + 2);
392	ic->ic_myaddr[4] = val & 0xff;
393	ic->ic_myaddr[5] = val >> 8;
394
395	if (pci_get_device(dev) >= 0x4223) {
396		/* set supported .11a rates (2915ABG only) */
397		ic->ic_sup_rates[IEEE80211_MODE_11A] = iwi_rateset_11a;
398
399		/* set supported .11a channels */
400		for (i = 36; i <= 64; i += 4) {
401			ic->ic_channels[i].ic_freq =
402			    ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
403			ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
404		}
405		for (i = 149; i <= 165; i += 4) {
406			ic->ic_channels[i].ic_freq =
407			    ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
408			ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
409		}
410	}
411
412	/* set supported .11b and .11g rates */
413	ic->ic_sup_rates[IEEE80211_MODE_11B] = iwi_rateset_11b;
414	ic->ic_sup_rates[IEEE80211_MODE_11G] = iwi_rateset_11g;
415
416	/* set supported .11b and .11g channels (1 through 14) */
417	for (i = 1; i <= 14; i++) {
418		ic->ic_channels[i].ic_freq =
419		    ieee80211_ieee2mhz(i, IEEE80211_CHAN_2GHZ);
420		ic->ic_channels[i].ic_flags =
421		    IEEE80211_CHAN_CCK | IEEE80211_CHAN_OFDM |
422		    IEEE80211_CHAN_DYN | IEEE80211_CHAN_2GHZ;
423	}
424
425	ieee80211_ifattach(ic);
426	ic->ic_bmissthreshold = 10;		/* override default */
427	/* override default methods */
428	ic->ic_node_alloc = iwi_node_alloc;
429	sc->sc_node_free = ic->ic_node_free;
430	ic->ic_node_free = iwi_node_free;
431	/* override state transition machine */
432	sc->sc_newstate = ic->ic_newstate;
433	ic->ic_newstate = iwi_newstate;
434	ieee80211_media_init(ic, iwi_media_change, iwi_media_status);
435
436	bpfattach2(ifp, DLT_IEEE802_11_RADIO,
437	    sizeof (struct ieee80211_frame) + sizeof (sc->sc_txtap),
438	    &sc->sc_drvbpf);
439
440	sc->sc_rxtap_len = sizeof sc->sc_rxtap;
441	sc->sc_rxtap.wr_ihdr.it_len = htole16(sc->sc_rxtap_len);
442	sc->sc_rxtap.wr_ihdr.it_present = htole32(IWI_RX_RADIOTAP_PRESENT);
443
444	sc->sc_txtap_len = sizeof sc->sc_txtap;
445	sc->sc_txtap.wt_ihdr.it_len = htole16(sc->sc_txtap_len);
446	sc->sc_txtap.wt_ihdr.it_present = htole32(IWI_TX_RADIOTAP_PRESENT);
447
448	iwi_sysctlattach(sc);
449	iwi_ledattach(sc);
450
451	/*
452	 * Hook our interrupt after all initialization is complete.
453	 */
454	error = bus_setup_intr(dev, sc->irq, INTR_TYPE_NET | INTR_MPSAFE,
455	    iwi_intr, sc, &sc->sc_ih);
456	if (error != 0) {
457		device_printf(dev, "could not set up interrupt\n");
458		goto fail;
459	}
460
461	if (bootverbose)
462		ieee80211_announce(ic);
463
464	return 0;
465
466fail:	iwi_detach(dev);
467	return ENXIO;
468}
469
470static int
471iwi_detach(device_t dev)
472{
473	struct iwi_softc *sc = device_get_softc(dev);
474	struct ieee80211com *ic = &sc->sc_ic;
475	struct ifnet *ifp = ic->ic_ifp;
476
477	if (ifp != NULL) {
478		iwi_stop(sc);
479		bpfdetach(ifp);
480		ieee80211_ifdetach(ic);
481	}
482	iwi_put_firmware(sc);
483	iwi_release_fw_dma(sc);
484
485	iwi_free_cmd_ring(sc, &sc->cmdq);
486	iwi_free_tx_ring(sc, &sc->txq[0]);
487	iwi_free_tx_ring(sc, &sc->txq[1]);
488	iwi_free_tx_ring(sc, &sc->txq[2]);
489	iwi_free_tx_ring(sc, &sc->txq[3]);
490	iwi_free_rx_ring(sc, &sc->rxq);
491
492	if (sc->irq != NULL) {
493		bus_teardown_intr(dev, sc->irq, sc->sc_ih);
494		bus_release_resource(dev, SYS_RES_IRQ, sc->irq_rid, sc->irq);
495	}
496
497	if (sc->mem != NULL)
498		bus_release_resource(dev, SYS_RES_MEMORY, sc->mem_rid, sc->mem);
499
500	if (ifp != NULL)
501		if_free(ifp);
502
503	taskqueue_free(sc->sc_tq);
504
505	if (sc->sc_unr != NULL)
506		delete_unrhdr(sc->sc_unr);
507
508	mtx_destroy(&sc->sc_mtx);
509
510	return 0;
511}
512
513static void
514iwi_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
515{
516	if (error != 0)
517		return;
518
519	KASSERT(nseg == 1, ("too many DMA segments, %d should be 1", nseg));
520
521	*(bus_addr_t *)arg = segs[0].ds_addr;
522}
523
524static int
525iwi_alloc_cmd_ring(struct iwi_softc *sc, struct iwi_cmd_ring *ring, int count)
526{
527	int error;
528
529	ring->count = count;
530	ring->queued = 0;
531	ring->cur = ring->next = 0;
532
533	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 4, 0,
534	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
535	    count * IWI_CMD_DESC_SIZE, 1, count * IWI_CMD_DESC_SIZE, 0,
536	    NULL, NULL, &ring->desc_dmat);
537	if (error != 0) {
538		device_printf(sc->sc_dev, "could not create desc DMA tag\n");
539		goto fail;
540	}
541
542	error = bus_dmamem_alloc(ring->desc_dmat, (void **)&ring->desc,
543	    BUS_DMA_NOWAIT | BUS_DMA_ZERO, &ring->desc_map);
544	if (error != 0) {
545		device_printf(sc->sc_dev, "could not allocate DMA memory\n");
546		goto fail;
547	}
548
549	error = bus_dmamap_load(ring->desc_dmat, ring->desc_map, ring->desc,
550	    count * IWI_CMD_DESC_SIZE, iwi_dma_map_addr, &ring->physaddr, 0);
551	if (error != 0) {
552		device_printf(sc->sc_dev, "could not load desc DMA map\n");
553		goto fail;
554	}
555
556	return 0;
557
558fail:	iwi_free_cmd_ring(sc, ring);
559	return error;
560}
561
562static void
563iwi_reset_cmd_ring(struct iwi_softc *sc, struct iwi_cmd_ring *ring)
564{
565	ring->queued = 0;
566	ring->cur = ring->next = 0;
567}
568
569static void
570iwi_free_cmd_ring(struct iwi_softc *sc, struct iwi_cmd_ring *ring)
571{
572	if (ring->desc != NULL) {
573		bus_dmamap_sync(ring->desc_dmat, ring->desc_map,
574		    BUS_DMASYNC_POSTWRITE);
575		bus_dmamap_unload(ring->desc_dmat, ring->desc_map);
576		bus_dmamem_free(ring->desc_dmat, ring->desc, ring->desc_map);
577	}
578
579	if (ring->desc_dmat != NULL)
580		bus_dma_tag_destroy(ring->desc_dmat);
581}
582
583static int
584iwi_alloc_tx_ring(struct iwi_softc *sc, struct iwi_tx_ring *ring, int count,
585    bus_addr_t csr_ridx, bus_addr_t csr_widx)
586{
587	int i, error;
588
589	ring->count = count;
590	ring->queued = 0;
591	ring->cur = ring->next = 0;
592	ring->csr_ridx = csr_ridx;
593	ring->csr_widx = csr_widx;
594
595	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 4, 0,
596	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
597	    count * IWI_TX_DESC_SIZE, 1, count * IWI_TX_DESC_SIZE, 0, NULL,
598	    NULL, &ring->desc_dmat);
599	if (error != 0) {
600		device_printf(sc->sc_dev, "could not create desc DMA tag\n");
601		goto fail;
602	}
603
604	error = bus_dmamem_alloc(ring->desc_dmat, (void **)&ring->desc,
605	    BUS_DMA_NOWAIT | BUS_DMA_ZERO, &ring->desc_map);
606	if (error != 0) {
607		device_printf(sc->sc_dev, "could not allocate DMA memory\n");
608		goto fail;
609	}
610
611	error = bus_dmamap_load(ring->desc_dmat, ring->desc_map, ring->desc,
612	    count * IWI_TX_DESC_SIZE, iwi_dma_map_addr, &ring->physaddr, 0);
613	if (error != 0) {
614		device_printf(sc->sc_dev, "could not load desc DMA map\n");
615		goto fail;
616	}
617
618	ring->data = malloc(count * sizeof (struct iwi_tx_data), M_DEVBUF,
619	    M_NOWAIT | M_ZERO);
620	if (ring->data == NULL) {
621		device_printf(sc->sc_dev, "could not allocate soft data\n");
622		error = ENOMEM;
623		goto fail;
624	}
625
626	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 1, 0,
627	BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES,
628	IWI_MAX_NSEG, MCLBYTES, 0, NULL, NULL, &ring->data_dmat);
629	if (error != 0) {
630		device_printf(sc->sc_dev, "could not create data DMA tag\n");
631		goto fail;
632	}
633
634	for (i = 0; i < count; i++) {
635		error = bus_dmamap_create(ring->data_dmat, 0,
636		    &ring->data[i].map);
637		if (error != 0) {
638			device_printf(sc->sc_dev, "could not create DMA map\n");
639			goto fail;
640		}
641	}
642
643	return 0;
644
645fail:	iwi_free_tx_ring(sc, ring);
646	return error;
647}
648
649static void
650iwi_reset_tx_ring(struct iwi_softc *sc, struct iwi_tx_ring *ring)
651{
652	struct iwi_tx_data *data;
653	int i;
654
655	for (i = 0; i < ring->count; i++) {
656		data = &ring->data[i];
657
658		if (data->m != NULL) {
659			bus_dmamap_sync(ring->data_dmat, data->map,
660			    BUS_DMASYNC_POSTWRITE);
661			bus_dmamap_unload(ring->data_dmat, data->map);
662			m_freem(data->m);
663			data->m = NULL;
664		}
665
666		if (data->ni != NULL) {
667			ieee80211_free_node(data->ni);
668			data->ni = NULL;
669		}
670	}
671
672	ring->queued = 0;
673	ring->cur = ring->next = 0;
674}
675
676static void
677iwi_free_tx_ring(struct iwi_softc *sc, struct iwi_tx_ring *ring)
678{
679	struct iwi_tx_data *data;
680	int i;
681
682	if (ring->desc != NULL) {
683		bus_dmamap_sync(ring->desc_dmat, ring->desc_map,
684		    BUS_DMASYNC_POSTWRITE);
685		bus_dmamap_unload(ring->desc_dmat, ring->desc_map);
686		bus_dmamem_free(ring->desc_dmat, ring->desc, ring->desc_map);
687	}
688
689	if (ring->desc_dmat != NULL)
690		bus_dma_tag_destroy(ring->desc_dmat);
691
692	if (ring->data != NULL) {
693		for (i = 0; i < ring->count; i++) {
694			data = &ring->data[i];
695
696			if (data->m != NULL) {
697				bus_dmamap_sync(ring->data_dmat, data->map,
698				    BUS_DMASYNC_POSTWRITE);
699				bus_dmamap_unload(ring->data_dmat, data->map);
700				m_freem(data->m);
701			}
702
703			if (data->ni != NULL)
704				ieee80211_free_node(data->ni);
705
706			if (data->map != NULL)
707				bus_dmamap_destroy(ring->data_dmat, data->map);
708		}
709
710		free(ring->data, M_DEVBUF);
711	}
712
713	if (ring->data_dmat != NULL)
714		bus_dma_tag_destroy(ring->data_dmat);
715}
716
717static int
718iwi_alloc_rx_ring(struct iwi_softc *sc, struct iwi_rx_ring *ring, int count)
719{
720	struct iwi_rx_data *data;
721	int i, error;
722
723	ring->count = count;
724	ring->cur = 0;
725
726	ring->data = malloc(count * sizeof (struct iwi_rx_data), M_DEVBUF,
727	    M_NOWAIT | M_ZERO);
728	if (ring->data == NULL) {
729		device_printf(sc->sc_dev, "could not allocate soft data\n");
730		error = ENOMEM;
731		goto fail;
732	}
733
734	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 1, 0,
735	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES,
736	    1, MCLBYTES, 0, NULL, NULL, &ring->data_dmat);
737	if (error != 0) {
738		device_printf(sc->sc_dev, "could not create data DMA tag\n");
739		goto fail;
740	}
741
742	for (i = 0; i < count; i++) {
743		data = &ring->data[i];
744
745		error = bus_dmamap_create(ring->data_dmat, 0, &data->map);
746		if (error != 0) {
747			device_printf(sc->sc_dev, "could not create DMA map\n");
748			goto fail;
749		}
750
751		data->m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
752		if (data->m == NULL) {
753			device_printf(sc->sc_dev,
754			    "could not allocate rx mbuf\n");
755			error = ENOMEM;
756			goto fail;
757		}
758
759		error = bus_dmamap_load(ring->data_dmat, data->map,
760		    mtod(data->m, void *), MCLBYTES, iwi_dma_map_addr,
761		    &data->physaddr, 0);
762		if (error != 0) {
763			device_printf(sc->sc_dev,
764			    "could not load rx buf DMA map");
765			goto fail;
766		}
767
768		data->reg = IWI_CSR_RX_BASE + i * 4;
769	}
770
771	return 0;
772
773fail:	iwi_free_rx_ring(sc, ring);
774	return error;
775}
776
777static void
778iwi_reset_rx_ring(struct iwi_softc *sc, struct iwi_rx_ring *ring)
779{
780	ring->cur = 0;
781}
782
783static void
784iwi_free_rx_ring(struct iwi_softc *sc, struct iwi_rx_ring *ring)
785{
786	struct iwi_rx_data *data;
787	int i;
788
789	if (ring->data != NULL) {
790		for (i = 0; i < ring->count; i++) {
791			data = &ring->data[i];
792
793			if (data->m != NULL) {
794				bus_dmamap_sync(ring->data_dmat, data->map,
795				    BUS_DMASYNC_POSTREAD);
796				bus_dmamap_unload(ring->data_dmat, data->map);
797				m_freem(data->m);
798			}
799
800			if (data->map != NULL)
801				bus_dmamap_destroy(ring->data_dmat, data->map);
802		}
803
804		free(ring->data, M_DEVBUF);
805	}
806
807	if (ring->data_dmat != NULL)
808		bus_dma_tag_destroy(ring->data_dmat);
809}
810
811static int
812iwi_shutdown(device_t dev)
813{
814	struct iwi_softc *sc = device_get_softc(dev);
815
816	iwi_stop(sc);
817	iwi_put_firmware(sc);		/* ??? XXX */
818
819	return 0;
820}
821
822static int
823iwi_suspend(device_t dev)
824{
825	struct iwi_softc *sc = device_get_softc(dev);
826
827	iwi_stop(sc);
828
829	return 0;
830}
831
832static int
833iwi_resume(device_t dev)
834{
835	struct iwi_softc *sc = device_get_softc(dev);
836	struct ifnet *ifp = sc->sc_ic.ic_ifp;
837	IWI_LOCK_DECL;
838
839	IWI_LOCK(sc);
840
841	pci_write_config(dev, 0x41, 0, 1);
842
843	if (ifp->if_flags & IFF_UP) {
844		ifp->if_init(ifp->if_softc);
845		if (ifp->if_drv_flags & IFF_DRV_RUNNING)
846			ifp->if_start(ifp);
847	}
848
849	IWI_UNLOCK(sc);
850
851	return 0;
852}
853
854static struct ieee80211_node *
855iwi_node_alloc(struct ieee80211_node_table *nt)
856{
857	struct iwi_node *in;
858
859	in = malloc(sizeof (struct iwi_node), M_80211_NODE, M_NOWAIT | M_ZERO);
860	if (in == NULL)
861		return NULL;
862
863	in->in_station = -1;
864
865	return &in->in_node;
866}
867
868static void
869iwi_node_free(struct ieee80211_node *ni)
870{
871	struct ieee80211com *ic = ni->ni_ic;
872	struct iwi_softc *sc = ic->ic_ifp->if_softc;
873	struct iwi_node *in = (struct iwi_node *)ni;
874
875	if (in->in_station != -1) {
876		DPRINTF(("%s mac %6D station %u\n", __func__,
877		    ni->ni_macaddr, ":", in->in_station));
878		free_unr(sc->sc_unr, in->in_station);
879	}
880
881	sc->sc_node_free(ni);
882}
883
884static int
885iwi_media_change(struct ifnet *ifp)
886{
887	struct iwi_softc *sc = ifp->if_softc;
888	int error;
889	IWI_LOCK_DECL;
890
891	IWI_LOCK(sc);
892
893	error = ieee80211_media_change(ifp);
894	if (error == ENETRESET &&
895	    (ifp->if_flags & IFF_UP) && (ifp->if_drv_flags & IFF_DRV_RUNNING))
896		iwi_init_locked(sc, 0);
897
898	IWI_UNLOCK(sc);
899
900	return error;
901}
902
903/*
904 * Convert h/w rate code to IEEE rate code.
905 */
906static int
907iwi_cvtrate(int iwirate)
908{
909	switch (iwirate) {
910	case IWI_RATE_DS1:	return 2;
911	case IWI_RATE_DS2:	return 4;
912	case IWI_RATE_DS5:	return 11;
913	case IWI_RATE_DS11:	return 22;
914	case IWI_RATE_OFDM6:	return 12;
915	case IWI_RATE_OFDM9:	return 18;
916	case IWI_RATE_OFDM12:	return 24;
917	case IWI_RATE_OFDM18:	return 36;
918	case IWI_RATE_OFDM24:	return 48;
919	case IWI_RATE_OFDM36:	return 72;
920	case IWI_RATE_OFDM48:	return 96;
921	case IWI_RATE_OFDM54:	return 108;
922	}
923	return 0;
924}
925
926/*
927 * The firmware automatically adapts the transmit speed.  We report its current
928 * value here.
929 */
930static void
931iwi_media_status(struct ifnet *ifp, struct ifmediareq *imr)
932{
933	struct iwi_softc *sc = ifp->if_softc;
934	struct ieee80211com *ic = &sc->sc_ic;
935	int rate;
936
937	imr->ifm_status = IFM_AVALID;
938	imr->ifm_active = IFM_IEEE80211;
939	if (ic->ic_state == IEEE80211_S_RUN)
940		imr->ifm_status |= IFM_ACTIVE;
941
942	/* read current transmission rate from adapter */
943	rate = iwi_cvtrate(CSR_READ_4(sc, IWI_CSR_CURRENT_TX_RATE));
944	imr->ifm_active |= ieee80211_rate2media(ic, rate, ic->ic_curmode);
945
946	if (ic->ic_opmode == IEEE80211_M_IBSS)
947		imr->ifm_active |= IFM_IEEE80211_ADHOC;
948	else if (ic->ic_opmode == IEEE80211_M_MONITOR)
949		imr->ifm_active |= IFM_IEEE80211_MONITOR;
950}
951
952static int
953iwi_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
954{
955	struct ifnet *ifp = ic->ic_ifp;
956	struct iwi_softc *sc = ifp->if_softc;
957
958	IWI_LOCK_ASSERT(sc);
959	DPRINTF(("%s: %s -> %s flags 0x%x\n", __func__,
960		ieee80211_state_name[ic->ic_state],
961		ieee80211_state_name[nstate], sc->flags));
962
963	/* XXX state change race with taskqueue */
964	switch (nstate) {
965	case IEEE80211_S_SCAN:
966		if (ic->ic_state == IEEE80211_S_RUN) {
967			/*
968			 * Beacon miss, send disassoc and wait for a reply
969			 * from the card; we'll start a scan then.  Note
970			 * this only happens with auto roaming; otherwise
971			 * just notify users and wait to be directed.
972			 */
973			/* notify directly as we bypass net80211 */
974			ieee80211_sta_leave(ic, ic->ic_bss);
975			if (ic->ic_roaming == IEEE80211_ROAMING_AUTO)
976				taskqueue_enqueue(sc->sc_tq, &sc->sc_downtask);
977			break;
978		}
979		if ((sc->flags & IWI_FLAG_SCANNING) == 0) {
980			sc->flags |= IWI_FLAG_SCANNING;
981			taskqueue_enqueue(sc->sc_tq, &sc->sc_scanstarttask);
982		}
983		break;
984
985	case IEEE80211_S_AUTH:
986		iwi_auth_and_assoc(sc);
987		break;
988
989	case IEEE80211_S_RUN:
990		if (ic->ic_opmode == IEEE80211_M_IBSS) {
991			/*
992			 * XXX when joining an ibss network we are called
993			 * with a SCAN -> RUN transition on scan complete.
994			 * Use that to call iwi_auth_and_assoc.  On completing
995			 * the join we are then called again with an
996			 * AUTH -> RUN transition and we want to do nothing.
997			 * This is all totally bogus and needs to be redone.
998			 */
999			if (ic->ic_state == IEEE80211_S_SCAN)
1000				iwi_auth_and_assoc(sc);
1001		} else if (ic->ic_opmode == IEEE80211_M_MONITOR)
1002			taskqueue_enqueue(sc->sc_tq, &sc->sc_scantask);
1003
1004		/* XXX way wrong */
1005		return sc->sc_newstate(ic, nstate,
1006		    IEEE80211_FC0_SUBTYPE_ASSOC_RESP);
1007
1008	case IEEE80211_S_ASSOC:
1009		break;
1010
1011	case IEEE80211_S_INIT:
1012		/*
1013		 * NB: don't try to do this if iwi_stop_master has
1014		 *     shutdown the firmware and disabled interrupts.
1015		 */
1016		if (ic->ic_state == IEEE80211_S_RUN &&
1017		    (sc->flags & IWI_FLAG_FW_INITED))
1018			taskqueue_enqueue(sc->sc_tq, &sc->sc_downtask);
1019		break;
1020	}
1021
1022	ic->ic_state = nstate;
1023	return 0;
1024}
1025
1026/*
1027 * WME parameters coming from IEEE 802.11e specification.  These values are
1028 * already declared in ieee80211_proto.c, but they are static so they can't
1029 * be reused here.
1030 */
1031static const struct wmeParams iwi_wme_cck_params[WME_NUM_AC] = {
1032	{ 0, 3, 5,  7,   0 },	/* WME_AC_BE */
1033	{ 0, 3, 5, 10,   0 },	/* WME_AC_BK */
1034	{ 0, 2, 4,  5, 188 },	/* WME_AC_VI */
1035	{ 0, 2, 3,  4, 102 }	/* WME_AC_VO */
1036};
1037
1038static const struct wmeParams iwi_wme_ofdm_params[WME_NUM_AC] = {
1039	{ 0, 3, 4,  6,   0 },	/* WME_AC_BE */
1040	{ 0, 3, 4, 10,   0 },	/* WME_AC_BK */
1041	{ 0, 2, 3,  4,  94 },	/* WME_AC_VI */
1042	{ 0, 2, 2,  3,  47 }	/* WME_AC_VO */
1043};
1044#define IWI_EXP2(v)	htole16((1 << (v)) - 1)
1045#define IWI_USEC(v)	htole16(IEEE80211_TXOP_TO_US(v))
1046
1047static void
1048iwi_wme_init(struct iwi_softc *sc)
1049{
1050	const struct wmeParams *wmep;
1051	int ac;
1052
1053	memset(sc->wme, 0, sizeof sc->wme);
1054	for (ac = 0; ac < WME_NUM_AC; ac++) {
1055		/* set WME values for CCK modulation */
1056		wmep = &iwi_wme_cck_params[ac];
1057		sc->wme[1].aifsn[ac] = wmep->wmep_aifsn;
1058		sc->wme[1].cwmin[ac] = IWI_EXP2(wmep->wmep_logcwmin);
1059		sc->wme[1].cwmax[ac] = IWI_EXP2(wmep->wmep_logcwmax);
1060		sc->wme[1].burst[ac] = IWI_USEC(wmep->wmep_txopLimit);
1061		sc->wme[1].acm[ac]   = wmep->wmep_acm;
1062
1063		/* set WME values for OFDM modulation */
1064		wmep = &iwi_wme_ofdm_params[ac];
1065		sc->wme[2].aifsn[ac] = wmep->wmep_aifsn;
1066		sc->wme[2].cwmin[ac] = IWI_EXP2(wmep->wmep_logcwmin);
1067		sc->wme[2].cwmax[ac] = IWI_EXP2(wmep->wmep_logcwmax);
1068		sc->wme[2].burst[ac] = IWI_USEC(wmep->wmep_txopLimit);
1069		sc->wme[2].acm[ac]   = wmep->wmep_acm;
1070	}
1071}
1072
1073static int
1074iwi_wme_setparams_locked(struct iwi_softc *sc)
1075{
1076	struct ieee80211com *ic = &sc->sc_ic;
1077	const struct wmeParams *wmep;
1078	int ac;
1079
1080	for (ac = 0; ac < WME_NUM_AC; ac++) {
1081		/* set WME values for current operating mode */
1082		wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
1083		sc->wme[0].aifsn[ac] = wmep->wmep_aifsn;
1084		sc->wme[0].cwmin[ac] = IWI_EXP2(wmep->wmep_logcwmin);
1085		sc->wme[0].cwmax[ac] = IWI_EXP2(wmep->wmep_logcwmax);
1086		sc->wme[0].burst[ac] = IWI_USEC(wmep->wmep_txopLimit);
1087		sc->wme[0].acm[ac]   = wmep->wmep_acm;
1088	}
1089
1090	DPRINTF(("Setting WME parameters\n"));
1091	return iwi_cmd(sc, IWI_CMD_SET_WME_PARAMS, sc->wme, sizeof sc->wme);
1092}
1093
1094static void
1095iwi_wme_setparams(void *arg, int npending)
1096{
1097	struct iwi_softc *sc = arg;
1098	IWI_LOCK_DECL;
1099
1100	IWI_LOCK(sc);
1101	(void) iwi_wme_setparams_locked(sc);
1102	IWI_UNLOCK(sc);
1103}
1104#undef IWI_USEC
1105#undef IWI_EXP2
1106
1107static int
1108iwi_wme_update(struct ieee80211com *ic)
1109{
1110	struct iwi_softc *sc = ic->ic_ifp->if_softc;
1111
1112	/*
1113	 * We may be called to update the WME parameters in
1114	 * the adapter at various places.  If we're already
1115	 * associated then initiate the request immediately
1116	 * (via the taskqueue); otherwise we assume the params
1117	 * will get sent down to the adapter as part of the
1118	 * work iwi_auth_and_assoc does.
1119	 */
1120	if (ic->ic_state == IEEE80211_S_RUN)
1121		taskqueue_enqueue(sc->sc_tq, &sc->sc_setwmetask);
1122	return 0;
1123}
1124
1125static int
1126iwi_wme_setie(struct iwi_softc *sc)
1127{
1128	struct ieee80211_wme_info wme;
1129
1130	memset(&wme, 0, sizeof wme);
1131	wme.wme_id = IEEE80211_ELEMID_VENDOR;
1132	wme.wme_len = sizeof (struct ieee80211_wme_info) - 2;
1133	wme.wme_oui[0] = 0x00;
1134	wme.wme_oui[1] = 0x50;
1135	wme.wme_oui[2] = 0xf2;
1136	wme.wme_type = WME_OUI_TYPE;
1137	wme.wme_subtype = WME_INFO_OUI_SUBTYPE;
1138	wme.wme_version = WME_VERSION;
1139	wme.wme_info = 0;
1140
1141	DPRINTF(("Setting WME IE (len=%u)\n", wme.wme_len));
1142	return iwi_cmd(sc, IWI_CMD_SET_WMEIE, &wme, sizeof wme);
1143}
1144
1145/*
1146 * Read 16 bits at address 'addr' from the serial EEPROM.
1147 */
1148static uint16_t
1149iwi_read_prom_word(struct iwi_softc *sc, uint8_t addr)
1150{
1151	uint32_t tmp;
1152	uint16_t val;
1153	int n;
1154
1155	/* clock C once before the first command */
1156	IWI_EEPROM_CTL(sc, 0);
1157	IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1158	IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_C);
1159	IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1160
1161	/* write start bit (1) */
1162	IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_D);
1163	IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_D | IWI_EEPROM_C);
1164
1165	/* write READ opcode (10) */
1166	IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_D);
1167	IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_D | IWI_EEPROM_C);
1168	IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1169	IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_C);
1170
1171	/* write address A7-A0 */
1172	for (n = 7; n >= 0; n--) {
1173		IWI_EEPROM_CTL(sc, IWI_EEPROM_S |
1174		    (((addr >> n) & 1) << IWI_EEPROM_SHIFT_D));
1175		IWI_EEPROM_CTL(sc, IWI_EEPROM_S |
1176		    (((addr >> n) & 1) << IWI_EEPROM_SHIFT_D) | IWI_EEPROM_C);
1177	}
1178
1179	IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1180
1181	/* read data Q15-Q0 */
1182	val = 0;
1183	for (n = 15; n >= 0; n--) {
1184		IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_C);
1185		IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1186		tmp = MEM_READ_4(sc, IWI_MEM_EEPROM_CTL);
1187		val |= ((tmp & IWI_EEPROM_Q) >> IWI_EEPROM_SHIFT_Q) << n;
1188	}
1189
1190	IWI_EEPROM_CTL(sc, 0);
1191
1192	/* clear Chip Select and clock C */
1193	IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1194	IWI_EEPROM_CTL(sc, 0);
1195	IWI_EEPROM_CTL(sc, IWI_EEPROM_C);
1196
1197	return val;
1198}
1199
1200static void
1201iwi_setcurchan(struct iwi_softc *sc, int chan)
1202{
1203	struct ieee80211com *ic = &sc->sc_ic;
1204
1205	IWI_LOCK_ASSERT(sc);
1206	ic->ic_curchan = &ic->ic_channels[chan];
1207	sc->curchan = chan;
1208
1209	sc->sc_rxtap.wr_chan_freq = sc->sc_txtap.wt_chan_freq =
1210		htole16(ic->ic_curchan->ic_freq);
1211	sc->sc_rxtap.wr_chan_flags = sc->sc_txtap.wt_chan_flags =
1212		htole16(ic->ic_curchan->ic_flags);
1213}
1214
1215static void
1216iwi_frame_intr(struct iwi_softc *sc, struct iwi_rx_data *data, int i,
1217    struct iwi_frame *frame)
1218{
1219	struct ieee80211com *ic = &sc->sc_ic;
1220	struct ifnet *ifp = ic->ic_ifp;
1221	struct mbuf *mnew, *m;
1222	struct ieee80211_node *ni;
1223	int type, error, framelen;
1224	IWI_LOCK_DECL;
1225
1226	framelen = le16toh(frame->len);
1227	if (framelen < IEEE80211_MIN_LEN || framelen > MCLBYTES) {
1228		/*
1229		 * XXX >MCLBYTES is bogus as it means the h/w dma'd
1230		 *     out of bounds; need to figure out how to limit
1231		 *     frame size in the firmware
1232		 */
1233		/* XXX stat */
1234		DPRINTFN(1,
1235		    ("drop rx frame len=%u chan=%u rssi=%u rssi_dbm=%u\n",
1236		    le16toh(frame->len), frame->chan, frame->rssi,
1237		    frame->rssi_dbm));
1238		return;
1239	}
1240
1241	DPRINTFN(5, ("received frame len=%u chan=%u rssi=%u rssi_dbm=%u\n",
1242	    le16toh(frame->len), frame->chan, frame->rssi, frame->rssi_dbm));
1243
1244	if (frame->chan != sc->curchan)
1245		iwi_setcurchan(sc, frame->chan);
1246
1247	/*
1248	 * Try to allocate a new mbuf for this ring element and load it before
1249	 * processing the current mbuf. If the ring element cannot be loaded,
1250	 * drop the received packet and reuse the old mbuf. In the unlikely
1251	 * case that the old mbuf can't be reloaded either, explicitly panic.
1252	 */
1253	mnew = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
1254	if (mnew == NULL) {
1255		ifp->if_ierrors++;
1256		return;
1257	}
1258
1259	bus_dmamap_unload(sc->rxq.data_dmat, data->map);
1260
1261	error = bus_dmamap_load(sc->rxq.data_dmat, data->map,
1262	    mtod(mnew, void *), MCLBYTES, iwi_dma_map_addr, &data->physaddr,
1263	    0);
1264	if (error != 0) {
1265		m_freem(mnew);
1266
1267		/* try to reload the old mbuf */
1268		error = bus_dmamap_load(sc->rxq.data_dmat, data->map,
1269		    mtod(data->m, void *), MCLBYTES, iwi_dma_map_addr,
1270		    &data->physaddr, 0);
1271		if (error != 0) {
1272			/* very unlikely that it will fail... */
1273			panic("%s: could not load old rx mbuf",
1274			    device_get_name(sc->sc_dev));
1275		}
1276		ifp->if_ierrors++;
1277		return;
1278	}
1279
1280	/*
1281	 * New mbuf successfully loaded, update Rx ring and continue
1282	 * processing.
1283	 */
1284	m = data->m;
1285	data->m = mnew;
1286	CSR_WRITE_4(sc, data->reg, data->physaddr);
1287
1288	/* finalize mbuf */
1289	m->m_pkthdr.rcvif = ifp;
1290	m->m_pkthdr.len = m->m_len = sizeof (struct iwi_hdr) +
1291	    sizeof (struct iwi_frame) + framelen;
1292
1293	m_adj(m, sizeof (struct iwi_hdr) + sizeof (struct iwi_frame));
1294
1295	if (bpf_peers_present(sc->sc_drvbpf)) {
1296		struct iwi_rx_radiotap_header *tap = &sc->sc_rxtap;
1297
1298		tap->wr_flags = 0;
1299		tap->wr_rate = iwi_cvtrate(frame->rate);
1300		tap->wr_antsignal = frame->signal;
1301		tap->wr_antenna = frame->antenna;
1302
1303		bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_rxtap_len, m);
1304	}
1305	IWI_UNLOCK(sc);
1306
1307	ni = ieee80211_find_rxnode(ic, mtod(m, struct ieee80211_frame_min *));
1308
1309	/* send the frame to the 802.11 layer */
1310	type = ieee80211_input(ic, m, ni, frame->rssi_dbm, 0);
1311
1312	/* node is no longer needed */
1313	ieee80211_free_node(ni);
1314
1315	IWI_LOCK(sc);
1316	if (sc->sc_softled) {
1317		/*
1318		 * Blink for any data frame.  Otherwise do a
1319		 * heartbeat-style blink when idle.  The latter
1320		 * is mainly for station mode where we depend on
1321		 * periodic beacon frames to trigger the poll event.
1322		 */
1323		if (type == IEEE80211_FC0_TYPE_DATA) {
1324			sc->sc_rxrate = frame->rate;
1325			iwi_led_event(sc, IWI_LED_RX);
1326		} else if (ticks - sc->sc_ledevent >= sc->sc_ledidle)
1327			iwi_led_event(sc, IWI_LED_POLL);
1328	}
1329}
1330
1331/* unaligned little endian access */
1332#define LE_READ_2(p)					\
1333	((u_int16_t)					\
1334	 ((((const u_int8_t *)(p))[0]      ) |		\
1335	  (((const u_int8_t *)(p))[1] <<  8)))
1336#define LE_READ_4(p)					\
1337	((u_int32_t)					\
1338	 ((((const u_int8_t *)(p))[0]      ) |		\
1339	  (((const u_int8_t *)(p))[1] <<  8) |		\
1340	  (((const u_int8_t *)(p))[2] << 16) |		\
1341	  (((const u_int8_t *)(p))[3] << 24)))
1342
1343#define	IEEE80211_VERIFY_LENGTH(_len, _minlen) do {			\
1344	if ((_len) < (_minlen)) {					\
1345		return;							\
1346	}								\
1347} while (0)
1348
1349static int __inline
1350iswmeoui(const u_int8_t *frm)
1351{
1352	return frm[1] > 3 && LE_READ_4(frm+2) == ((WME_OUI_TYPE<<24)|WME_OUI);
1353}
1354
1355/*
1356 * Check for an association response frame to see if QoS
1357 * has been negotiated.  We parse just enough to figure
1358 * out if we're supposed to use QoS.  The proper solution
1359 * is to pass the frame up so ieee80211_input can do the
1360 * work but that's made hard by how things currently are
1361 * done in the driver.
1362 */
1363static void
1364iwi_checkforqos(struct iwi_softc *sc, const struct ieee80211_frame *wh, int len)
1365{
1366#define	SUBTYPE(wh)	((wh)->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK)
1367	const uint8_t *frm, *efrm, *wme;
1368	struct ieee80211_node *ni;
1369
1370	/* NB: +8 for capinfo, status, associd, and first ie */
1371	if (!(sizeof(*wh)+8 < len && len < IEEE80211_MAX_LEN) ||
1372	    SUBTYPE(wh) != IEEE80211_FC0_SUBTYPE_ASSOC_RESP)
1373		return;
1374	/*
1375	 * asresp frame format
1376	 *	[2] capability information
1377	 *	[2] status
1378	 *	[2] association ID
1379	 *	[tlv] supported rates
1380	 *	[tlv] extended supported rates
1381	 *	[tlv] WME
1382	 */
1383	frm = (const uint8_t *)&wh[1];
1384	efrm = ((const uint8_t *) wh) + len;
1385	frm += 6;
1386
1387	wme = NULL;
1388	while (frm < efrm) {
1389		IEEE80211_VERIFY_LENGTH(efrm - frm, frm[1]);
1390		switch (*frm) {
1391		case IEEE80211_ELEMID_VENDOR:
1392			if (iswmeoui(frm))
1393				wme = frm;
1394			break;
1395		}
1396		frm += frm[1] + 2;
1397	}
1398
1399	ni = sc->sc_ic.ic_bss;
1400	if (wme != NULL)
1401		ni->ni_flags |= IEEE80211_NODE_QOS;
1402	else
1403		ni->ni_flags &= ~IEEE80211_NODE_QOS;
1404#undef SUBTYPE
1405}
1406
1407static void
1408iwi_notification_intr(struct iwi_softc *sc, struct iwi_notif *notif)
1409{
1410	struct ieee80211com *ic = &sc->sc_ic;
1411	struct iwi_notif_scan_channel *chan;
1412	struct iwi_notif_scan_complete *scan;
1413	struct iwi_notif_authentication *auth;
1414	struct iwi_notif_association *assoc;
1415	struct iwi_notif_beacon_state *beacon;
1416
1417	switch (notif->type) {
1418	case IWI_NOTIF_TYPE_SCAN_CHANNEL:
1419		chan = (struct iwi_notif_scan_channel *)(notif + 1);
1420
1421		DPRINTFN(3, ("Scan of channel %u complete (%u)\n",
1422		    ic->ic_channels[chan->nchan].ic_freq, chan->nchan));
1423		break;
1424
1425	case IWI_NOTIF_TYPE_SCAN_COMPLETE:
1426		scan = (struct iwi_notif_scan_complete *)(notif + 1);
1427
1428		DPRINTFN(2, ("Scan completed (%u, %u)\n", scan->nchan,
1429		    scan->status));
1430
1431		sc->sc_scan_timer = 0;
1432
1433		if (ic->ic_opmode == IEEE80211_M_MONITOR) {
1434			/*
1435			 * Monitor mode works by doing a passive scan to set
1436			 * the channel and enable rx.  Because we don't want
1437			 * to abort a scan lest the firmware crash we scan
1438			 * for a short period of time and automatically restart
1439			 * the scan when notified the sweep has completed.
1440			 */
1441			taskqueue_enqueue(sc->sc_tq, &sc->sc_scantask);
1442		} else {
1443			sc->flags &= ~IWI_FLAG_SCANNING;
1444			taskqueue_enqueue(sc->sc_tq, &sc->sc_scandonetask);
1445		}
1446		break;
1447
1448	case IWI_NOTIF_TYPE_AUTHENTICATION:
1449		auth = (struct iwi_notif_authentication *)(notif + 1);
1450
1451		switch (auth->state) {
1452		case IWI_AUTH_SUCCESS:
1453			DPRINTFN(2, ("Authentication succeeeded\n"));
1454			ieee80211_node_authorize(ic->ic_bss);
1455			ieee80211_new_state(ic, IEEE80211_S_ASSOC, -1);
1456			break;
1457
1458		case IWI_AUTH_FAIL:
1459			DPRINTFN(2, ("Authentication failed\n"));
1460			sc->flags &= ~IWI_FLAG_ASSOCIATED;
1461			/* XXX */
1462			break;
1463
1464		case IWI_AUTH_SENT_1:
1465		case IWI_AUTH_RECV_2:
1466		case IWI_AUTH_SEQ1_PASS:
1467			break;
1468
1469		case IWI_AUTH_SEQ1_FAIL:
1470			DPRINTFN(2, ("Initial authentication handshake failed; "
1471				"you probably need shared key\n"));
1472			/* XXX retry shared key when in auto */
1473			break;
1474
1475		default:
1476			device_printf(sc->sc_dev,
1477			    "unknown authentication state %u\n", auth->state);
1478		}
1479		break;
1480
1481	case IWI_NOTIF_TYPE_ASSOCIATION:
1482		assoc = (struct iwi_notif_association *)(notif + 1);
1483
1484		switch (assoc->state) {
1485		case IWI_AUTH_SUCCESS:
1486			/* re-association, do nothing */
1487			break;
1488
1489		case IWI_ASSOC_SUCCESS:
1490			DPRINTFN(2, ("Association succeeded\n"));
1491			sc->flags |= IWI_FLAG_ASSOCIATED;
1492			iwi_checkforqos(sc,
1493			    (const struct ieee80211_frame *)(assoc+1),
1494			    le16toh(notif->len) - sizeof(*assoc));
1495			ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
1496			break;
1497
1498		case IWI_ASSOC_FAIL:
1499			DPRINTFN(2, ("Association failed\n"));
1500			sc->flags &= ~IWI_FLAG_ASSOCIATED;
1501			ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
1502			break;
1503
1504		default:
1505			device_printf(sc->sc_dev,
1506			    "unknown association state %u\n", assoc->state);
1507		}
1508		break;
1509
1510	case IWI_NOTIF_TYPE_BEACON:
1511		/* XXX check struct length */
1512		beacon = (struct iwi_notif_beacon_state *)(notif + 1);
1513
1514		DPRINTFN(5, ("Beacon state (%u, %u)\n",
1515		    beacon->state, le32toh(beacon->number)));
1516
1517		if (beacon->state == IWI_BEACON_MISS) {
1518#if 0
1519			if (sc->flags & IWI_FLAG_SCANNING) {
1520				/* XXX terminate scan, linux driver
1521				  says fw can get stuck */
1522				/* XXX should be handled in iwi_newstate */
1523				taskqueue_enqueue(sc->sc_tq,
1524					&sc->sc_scanaborttask);
1525			}
1526#endif
1527			/*
1528			 * The firmware notifies us of every beacon miss
1529			 * so we need to track the count against the
1530			 * configured threshold before notifying the
1531			 * 802.11 layer.
1532			 * XXX try to roam, drop assoc only on much higher count
1533			 */
1534			if (le32toh(beacon->number) >= ic->ic_bmissthreshold) {
1535				DPRINTF(("Beacon miss: %u >= %u\n",
1536				    le32toh(beacon->number),
1537				    ic->ic_bmissthreshold));
1538				ieee80211_beacon_miss(ic);
1539			}
1540		}
1541		break;
1542
1543	case IWI_NOTIF_TYPE_CALIBRATION:
1544	case IWI_NOTIF_TYPE_NOISE:
1545	case IWI_NOTIF_TYPE_LINK_QUALITY:
1546		DPRINTFN(5, ("Notification (%u)\n", notif->type));
1547		break;
1548
1549	default:
1550		DPRINTF(("unknown notification type %u flags 0x%x len %u\n",
1551		    notif->type, notif->flags, le16toh(notif->len)));
1552	}
1553}
1554
1555static void
1556iwi_rx_intr(struct iwi_softc *sc)
1557{
1558	struct iwi_rx_data *data;
1559	struct iwi_hdr *hdr;
1560	uint32_t hw;
1561
1562	hw = CSR_READ_4(sc, IWI_CSR_RX_RIDX);
1563
1564	for (; sc->rxq.cur != hw;) {
1565		data = &sc->rxq.data[sc->rxq.cur];
1566
1567		bus_dmamap_sync(sc->rxq.data_dmat, data->map,
1568		    BUS_DMASYNC_POSTREAD);
1569
1570		hdr = mtod(data->m, struct iwi_hdr *);
1571
1572		switch (hdr->type) {
1573		case IWI_HDR_TYPE_FRAME:
1574			iwi_frame_intr(sc, data, sc->rxq.cur,
1575			    (struct iwi_frame *)(hdr + 1));
1576			break;
1577
1578		case IWI_HDR_TYPE_NOTIF:
1579			iwi_notification_intr(sc,
1580			    (struct iwi_notif *)(hdr + 1));
1581			break;
1582
1583		default:
1584			device_printf(sc->sc_dev, "unknown hdr type %u\n",
1585			    hdr->type);
1586		}
1587
1588		DPRINTFN(15, ("rx done idx=%u\n", sc->rxq.cur));
1589
1590		sc->rxq.cur = (sc->rxq.cur + 1) % IWI_RX_RING_COUNT;
1591	}
1592
1593	/* tell the firmware what we have processed */
1594	hw = (hw == 0) ? IWI_RX_RING_COUNT - 1 : hw - 1;
1595	CSR_WRITE_4(sc, IWI_CSR_RX_WIDX, hw);
1596}
1597
1598static void
1599iwi_tx_intr(struct iwi_softc *sc, struct iwi_tx_ring *txq)
1600{
1601	struct ieee80211com *ic = &sc->sc_ic;
1602	struct ifnet *ifp = ic->ic_ifp;
1603	struct iwi_tx_data *data;
1604	uint32_t hw;
1605
1606	hw = CSR_READ_4(sc, txq->csr_ridx);
1607
1608	for (; txq->next != hw;) {
1609		data = &txq->data[txq->next];
1610
1611		bus_dmamap_sync(txq->data_dmat, data->map,
1612		    BUS_DMASYNC_POSTWRITE);
1613		bus_dmamap_unload(txq->data_dmat, data->map);
1614		m_freem(data->m);
1615		data->m = NULL;
1616		ieee80211_free_node(data->ni);
1617		data->ni = NULL;
1618
1619		DPRINTFN(15, ("tx done idx=%u\n", txq->next));
1620
1621		ifp->if_opackets++;
1622
1623		txq->queued--;
1624		txq->next = (txq->next + 1) % IWI_TX_RING_COUNT;
1625	}
1626
1627	sc->sc_tx_timer = 0;
1628	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1629
1630	if (sc->sc_softled)
1631		iwi_led_event(sc, IWI_LED_TX);
1632
1633	iwi_start(ifp);
1634}
1635
1636static void
1637iwi_intr(void *arg)
1638{
1639	struct iwi_softc *sc = arg;
1640	uint32_t r;
1641	IWI_LOCK_DECL;
1642
1643	IWI_LOCK(sc);
1644
1645	if ((r = CSR_READ_4(sc, IWI_CSR_INTR)) == 0 || r == 0xffffffff) {
1646		IWI_UNLOCK(sc);
1647		return;
1648	}
1649
1650	/* acknowledge interrupts */
1651	CSR_WRITE_4(sc, IWI_CSR_INTR, r);
1652
1653	if (r & IWI_INTR_FATAL_ERROR) {
1654		device_printf(sc->sc_dev, "firmware error\n");
1655		taskqueue_enqueue(sc->sc_tq, &sc->sc_restarttask);
1656	}
1657
1658	if (r & IWI_INTR_FW_INITED) {
1659		if (!(r & (IWI_INTR_FATAL_ERROR | IWI_INTR_PARITY_ERROR)))
1660			wakeup(sc);
1661	}
1662
1663	if (r & IWI_INTR_RADIO_OFF)
1664		taskqueue_enqueue(sc->sc_tq, &sc->sc_radiofftask);
1665
1666	if (r & IWI_INTR_CMD_DONE) {
1667		sc->flags &= ~IWI_FLAG_BUSY;
1668		wakeup(sc);
1669	}
1670
1671	if (r & IWI_INTR_TX1_DONE)
1672		iwi_tx_intr(sc, &sc->txq[0]);
1673
1674	if (r & IWI_INTR_TX2_DONE)
1675		iwi_tx_intr(sc, &sc->txq[1]);
1676
1677	if (r & IWI_INTR_TX3_DONE)
1678		iwi_tx_intr(sc, &sc->txq[2]);
1679
1680	if (r & IWI_INTR_TX4_DONE)
1681		iwi_tx_intr(sc, &sc->txq[3]);
1682
1683	if (r & IWI_INTR_RX_DONE)
1684		iwi_rx_intr(sc);
1685
1686	if (r & IWI_INTR_PARITY_ERROR) {
1687		/* XXX rate-limit */
1688		device_printf(sc->sc_dev, "parity error\n");
1689	}
1690
1691	IWI_UNLOCK(sc);
1692}
1693
1694static int
1695iwi_cmd(struct iwi_softc *sc, uint8_t type, void *data, uint8_t len)
1696{
1697	struct iwi_cmd_desc *desc;
1698
1699	IWI_LOCK_ASSERT(sc);
1700
1701	if (sc->flags & IWI_FLAG_BUSY) {
1702		device_printf(sc->sc_dev, "%s: cmd %d not sent, busy\n",
1703			__func__, type);
1704		return EAGAIN;
1705	}
1706	sc->flags |= IWI_FLAG_BUSY;
1707
1708	desc = &sc->cmdq.desc[sc->cmdq.cur];
1709
1710	desc->hdr.type = IWI_HDR_TYPE_COMMAND;
1711	desc->hdr.flags = IWI_HDR_FLAG_IRQ;
1712	desc->type = type;
1713	desc->len = len;
1714	memcpy(desc->data, data, len);
1715
1716	bus_dmamap_sync(sc->cmdq.desc_dmat, sc->cmdq.desc_map,
1717	    BUS_DMASYNC_PREWRITE);
1718
1719	DPRINTFN(2, ("sending command idx=%u type=%u len=%u\n", sc->cmdq.cur,
1720	    type, len));
1721
1722	sc->cmdq.cur = (sc->cmdq.cur + 1) % IWI_CMD_RING_COUNT;
1723	CSR_WRITE_4(sc, IWI_CSR_CMD_WIDX, sc->cmdq.cur);
1724
1725	return msleep(sc, &sc->sc_mtx, 0, "iwicmd", hz);
1726}
1727
1728static void
1729iwi_write_ibssnode(struct iwi_softc *sc,
1730	const u_int8_t addr[IEEE80211_ADDR_LEN], int entry)
1731{
1732	struct iwi_ibssnode node;
1733
1734	/* write node information into NIC memory */
1735	memset(&node, 0, sizeof node);
1736	IEEE80211_ADDR_COPY(node.bssid, addr);
1737
1738	DPRINTF(("%s mac %6D station %u\n", __func__, node.bssid, ":", entry));
1739
1740	CSR_WRITE_REGION_1(sc,
1741	    IWI_CSR_NODE_BASE + entry * sizeof node,
1742	    (uint8_t *)&node, sizeof node);
1743}
1744
1745static int
1746iwi_tx_start(struct ifnet *ifp, struct mbuf *m0, struct ieee80211_node *ni,
1747    int ac)
1748{
1749	struct iwi_softc *sc = ifp->if_softc;
1750	struct ieee80211com *ic = &sc->sc_ic;
1751	struct iwi_node *in = (struct iwi_node *)ni;
1752	const struct ieee80211_frame *wh;
1753	struct ieee80211_key *k;
1754	const struct chanAccParams *cap;
1755	struct iwi_tx_ring *txq = &sc->txq[ac];
1756	struct iwi_tx_data *data;
1757	struct iwi_tx_desc *desc;
1758	struct mbuf *mnew;
1759	bus_dma_segment_t segs[IWI_MAX_NSEG];
1760	int error, nsegs, hdrlen, i;
1761	int ismcast, flags, xflags, staid;
1762
1763	IWI_LOCK_ASSERT(sc);
1764	wh = mtod(m0, const struct ieee80211_frame *);
1765	/* NB: only data frames use this path */
1766	hdrlen = ieee80211_hdrsize(wh);
1767	ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
1768	flags = xflags = 0;
1769
1770	if (!ismcast)
1771		flags |= IWI_DATA_FLAG_NEED_ACK;
1772	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
1773		flags |= IWI_DATA_FLAG_SHPREAMBLE;
1774	if (IEEE80211_QOS_HAS_SEQ(wh)) {
1775		xflags |= IWI_DATA_XFLAG_QOS;
1776		cap = &ic->ic_wme.wme_chanParams;
1777		if (!cap->cap_wmeParams[ac].wmep_noackPolicy)
1778			flags &= ~IWI_DATA_FLAG_NEED_ACK;
1779	}
1780
1781	/*
1782	 * This is only used in IBSS mode where the firmware expect an index
1783	 * in a h/w table instead of a destination address.
1784	 */
1785	if (ic->ic_opmode == IEEE80211_M_IBSS) {
1786		if (!ismcast) {
1787			if (in->in_station == -1) {
1788				in->in_station = alloc_unr(sc->sc_unr);
1789				if (in->in_station == -1) {
1790					/* h/w table is full */
1791					m_freem(m0);
1792					ieee80211_free_node(ni);
1793					ifp->if_oerrors++;
1794					return 0;
1795				}
1796				iwi_write_ibssnode(sc,
1797					ni->ni_macaddr, in->in_station);
1798			}
1799			staid = in->in_station;
1800		} else {
1801			/*
1802			 * Multicast addresses have no associated node
1803			 * so there will be no station entry.  We reserve
1804			 * entry 0 for one mcast address and use that.
1805			 * If there are many being used this will be
1806			 * expensive and we'll need to do a better job
1807			 * but for now this handles the broadcast case.
1808			 */
1809			if (!IEEE80211_ADDR_EQ(wh->i_addr1, sc->sc_mcast)) {
1810				IEEE80211_ADDR_COPY(sc->sc_mcast, wh->i_addr1);
1811				iwi_write_ibssnode(sc, sc->sc_mcast, 0);
1812			}
1813			staid = 0;
1814		}
1815	} else
1816		staid = 0;
1817
1818	if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1819		k = ieee80211_crypto_encap(ic, ni, m0);
1820		if (k == NULL) {
1821			m_freem(m0);
1822			return ENOBUFS;
1823		}
1824
1825		/* packet header may have moved, reset our local pointer */
1826		wh = mtod(m0, struct ieee80211_frame *);
1827	}
1828
1829	if (bpf_peers_present(sc->sc_drvbpf)) {
1830		struct iwi_tx_radiotap_header *tap = &sc->sc_txtap;
1831
1832		tap->wt_flags = 0;
1833
1834		bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_txtap_len, m0);
1835	}
1836
1837	data = &txq->data[txq->cur];
1838	desc = &txq->desc[txq->cur];
1839
1840	/* save and trim IEEE802.11 header */
1841	m_copydata(m0, 0, hdrlen, (caddr_t)&desc->wh);
1842	m_adj(m0, hdrlen);
1843
1844	error = bus_dmamap_load_mbuf_sg(txq->data_dmat, data->map, m0, segs,
1845	    &nsegs, 0);
1846	if (error != 0 && error != EFBIG) {
1847		device_printf(sc->sc_dev, "could not map mbuf (error %d)\n",
1848		    error);
1849		m_freem(m0);
1850		return error;
1851	}
1852	if (error != 0) {
1853		mnew = m_defrag(m0, M_DONTWAIT);
1854		if (mnew == NULL) {
1855			device_printf(sc->sc_dev,
1856			    "could not defragment mbuf\n");
1857			m_freem(m0);
1858			return ENOBUFS;
1859		}
1860		m0 = mnew;
1861
1862		error = bus_dmamap_load_mbuf_sg(txq->data_dmat, data->map,
1863		    m0, segs, &nsegs, 0);
1864		if (error != 0) {
1865			device_printf(sc->sc_dev,
1866			    "could not map mbuf (error %d)\n", error);
1867			m_freem(m0);
1868			return error;
1869		}
1870	}
1871
1872	data->m = m0;
1873	data->ni = ni;
1874
1875	desc->hdr.type = IWI_HDR_TYPE_DATA;
1876	desc->hdr.flags = IWI_HDR_FLAG_IRQ;
1877	desc->station = staid;
1878	desc->cmd = IWI_DATA_CMD_TX;
1879	desc->len = htole16(m0->m_pkthdr.len);
1880	desc->flags = flags;
1881	desc->xflags = xflags;
1882
1883#if 0
1884	if (ic->ic_flags & IEEE80211_F_PRIVACY)
1885		desc->wep_txkey = ic->ic_crypto.cs_def_txkey;
1886	else
1887#endif
1888		desc->flags |= IWI_DATA_FLAG_NO_WEP;
1889
1890	desc->nseg = htole32(nsegs);
1891	for (i = 0; i < nsegs; i++) {
1892		desc->seg_addr[i] = htole32(segs[i].ds_addr);
1893		desc->seg_len[i]  = htole16(segs[i].ds_len);
1894	}
1895
1896	bus_dmamap_sync(txq->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
1897	bus_dmamap_sync(txq->desc_dmat, txq->desc_map, BUS_DMASYNC_PREWRITE);
1898
1899	DPRINTFN(5, ("sending data frame txq=%u idx=%u len=%u nseg=%u\n",
1900	    ac, txq->cur, le16toh(desc->len), nsegs));
1901
1902	txq->queued++;
1903	txq->cur = (txq->cur + 1) % IWI_TX_RING_COUNT;
1904	CSR_WRITE_4(sc, txq->csr_widx, txq->cur);
1905
1906	return 0;
1907}
1908
1909static void
1910iwi_start(struct ifnet *ifp)
1911{
1912	struct iwi_softc *sc = ifp->if_softc;
1913	struct ieee80211com *ic = &sc->sc_ic;
1914	struct mbuf *m0;
1915	struct ether_header *eh;
1916	struct ieee80211_node *ni;
1917	int ac;
1918	IWI_LOCK_DECL;
1919
1920	IWI_LOCK(sc);
1921
1922	if (ic->ic_state != IEEE80211_S_RUN) {
1923		IWI_UNLOCK(sc);
1924		return;
1925	}
1926
1927	for (;;) {
1928		IF_DEQUEUE(&ic->ic_mgtq, m0);
1929		if (m0 == NULL) {
1930			IFQ_DRV_DEQUEUE(&ifp->if_snd, m0);
1931			if (m0 == NULL)
1932				break;
1933
1934			if (m0->m_len < sizeof (struct ether_header) &&
1935			    (m0 = m_pullup(m0, sizeof (struct ether_header))) == NULL) {
1936				ifp->if_oerrors++;
1937				continue;
1938			}
1939			eh = mtod(m0, struct ether_header *);
1940			ni = ieee80211_find_txnode(ic, eh->ether_dhost);
1941			if (ni == NULL) {
1942				m_freem(m0);
1943				ifp->if_oerrors++;
1944				continue;
1945			}
1946
1947			/* classify mbuf so we can find which tx ring to use */
1948			if (ieee80211_classify(ic, m0, ni) != 0) {
1949				m_freem(m0);
1950				ieee80211_free_node(ni);
1951				ifp->if_oerrors++;
1952				continue;
1953			}
1954
1955			/* XXX does not belong here */
1956			/* no QoS encapsulation for EAPOL frames */
1957			ac = (eh->ether_type != htons(ETHERTYPE_PAE)) ?
1958			    M_WME_GETAC(m0) : WME_AC_BE;
1959
1960			if (sc->txq[ac].queued > IWI_TX_RING_COUNT - 8) {
1961				/* there is no place left in this ring */
1962				IFQ_DRV_PREPEND(&ifp->if_snd, m0);
1963				ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1964				break;
1965			}
1966
1967			BPF_MTAP(ifp, m0);
1968
1969			m0 = ieee80211_encap(ic, m0, ni);
1970			if (m0 == NULL) {
1971				ieee80211_free_node(ni);
1972				ifp->if_oerrors++;
1973				continue;
1974			}
1975		} else {
1976			ni = (struct ieee80211_node *) m0->m_pkthdr.rcvif;
1977			m0->m_pkthdr.rcvif = NULL;
1978			/* XXX no way to send mgt frames (yet), discard */
1979			m_freem(m0);
1980			ieee80211_free_node(ni);
1981			continue;
1982		}
1983
1984		if (bpf_peers_present(ic->ic_rawbpf))
1985			bpf_mtap(ic->ic_rawbpf, m0);
1986
1987		if (iwi_tx_start(ifp, m0, ni, ac) != 0) {
1988			ieee80211_free_node(ni);
1989			ifp->if_oerrors++;
1990			break;
1991		}
1992
1993		sc->sc_tx_timer = 5;
1994		ifp->if_timer = 1;
1995	}
1996
1997	IWI_UNLOCK(sc);
1998}
1999
2000static void
2001iwi_watchdog(struct ifnet *ifp)
2002{
2003	struct iwi_softc *sc = ifp->if_softc;
2004	struct ieee80211com *ic = &sc->sc_ic;
2005	IWI_LOCK_DECL;
2006
2007	IWI_LOCK(sc);
2008
2009	if (sc->sc_tx_timer > 0) {
2010		if (--sc->sc_tx_timer == 0) {
2011			if_printf(ifp, "device timeout\n");
2012			ifp->if_oerrors++;
2013			taskqueue_enqueue(sc->sc_tq, &sc->sc_restarttask);
2014		}
2015	}
2016	if (sc->sc_rfkill_timer > 0) {
2017		if (--sc->sc_rfkill_timer == 0) {
2018			/*
2019			 * Check for a change in rfkill state.  We get an
2020			 * interrupt when a radio is disabled but not when
2021			 * it is enabled so we must poll for the latter.
2022			 */
2023			if (!iwi_getrfkill(sc))
2024				taskqueue_enqueue(sc->sc_tq, &sc->sc_radiontask);
2025			else
2026				sc->sc_rfkill_timer = 2;
2027		}
2028	}
2029	if (sc->sc_scan_timer > 0) {
2030		if (--sc->sc_scan_timer == 0) {
2031			if (sc->flags & IWI_FLAG_SCANNING) {
2032				if_printf(ifp, "scan stuck\n");
2033				taskqueue_enqueue(sc->sc_tq, &sc->sc_restarttask);
2034			}
2035		}
2036	}
2037	if (sc->sc_tx_timer || sc->sc_rfkill_timer || sc->sc_scan_timer)
2038		ifp->if_timer = 1;
2039	else
2040		ifp->if_timer = 0;
2041
2042	ieee80211_watchdog(ic);
2043
2044	IWI_UNLOCK(sc);
2045}
2046
2047static int
2048iwi_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
2049{
2050	struct iwi_softc *sc = ifp->if_softc;
2051	struct ieee80211com *ic = &sc->sc_ic;
2052	int error = 0;
2053	IWI_LOCK_DECL;
2054
2055	IWI_LOCK(sc);
2056
2057	switch (cmd) {
2058	case SIOCSIFFLAGS:
2059		if (ifp->if_flags & IFF_UP) {
2060			if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
2061				iwi_init_locked(sc, 0);
2062		} else {
2063			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
2064				iwi_stop(sc);
2065			else {
2066				/*
2067				 * If device was stopped due to rfkill then
2068				 * marked down we'll have the polling thread
2069				 * running; stop it explicitly.
2070				 */
2071				sc->sc_rfkill_timer = 0;
2072			}
2073		}
2074		break;
2075
2076	default:
2077		/*
2078		 * XXX the driver has a tendency to freeze the machine
2079		 * when initializing the interface. This seems due to
2080		 * a race condition, whose origin is still unclear.
2081		 * Adding a printf in this particular condition seems to cure
2082		 * the symptom, so we do it until we find a proper fix.
2083		 */
2084		if (sc->flags & IWI_FLAG_BUSY)
2085			device_printf(sc->sc_dev, "%s: flags %x cmd 0x%lx\n",
2086				__func__, sc->flags, cmd);
2087		error = ieee80211_ioctl(ic, cmd, data);
2088	}
2089
2090	if (error == ENETRESET) {
2091		if ((ifp->if_flags & IFF_UP) &&
2092		    (ifp->if_drv_flags & IFF_DRV_RUNNING) &&
2093		    (ic->ic_roaming != IEEE80211_ROAMING_MANUAL))
2094			iwi_init_locked(sc, 0);
2095		error = 0;
2096	}
2097
2098	IWI_UNLOCK(sc);
2099
2100	return error;
2101}
2102
2103static void
2104iwi_stop_master(struct iwi_softc *sc)
2105{
2106	uint32_t tmp;
2107	int ntries;
2108
2109	IWI_LOCK_ASSERT(sc);
2110
2111	/* disable interrupts */
2112	CSR_WRITE_4(sc, IWI_CSR_INTR_MASK, 0);
2113
2114	CSR_WRITE_4(sc, IWI_CSR_RST, IWI_RST_STOP_MASTER);
2115	for (ntries = 0; ntries < 5; ntries++) {
2116		if (CSR_READ_4(sc, IWI_CSR_RST) & IWI_RST_MASTER_DISABLED)
2117			break;
2118		DELAY(10);
2119	}
2120	if (ntries == 5)
2121		device_printf(sc->sc_dev, "timeout waiting for master\n");
2122
2123	tmp = CSR_READ_4(sc, IWI_CSR_RST);
2124	CSR_WRITE_4(sc, IWI_CSR_RST, tmp | IWI_RST_PRINCETON_RESET);
2125
2126	sc->flags &= ~IWI_FLAG_FW_INITED;
2127}
2128
2129static int
2130iwi_reset(struct iwi_softc *sc)
2131{
2132	uint32_t tmp;
2133	int i, ntries;
2134
2135	iwi_stop_master(sc);
2136
2137	tmp = CSR_READ_4(sc, IWI_CSR_CTL);
2138	CSR_WRITE_4(sc, IWI_CSR_CTL, tmp | IWI_CTL_INIT);
2139
2140	CSR_WRITE_4(sc, IWI_CSR_READ_INT, IWI_READ_INT_INIT_HOST);
2141
2142	/* wait for clock stabilization */
2143	for (ntries = 0; ntries < 1000; ntries++) {
2144		if (CSR_READ_4(sc, IWI_CSR_CTL) & IWI_CTL_CLOCK_READY)
2145			break;
2146		DELAY(200);
2147	}
2148	if (ntries == 1000) {
2149		device_printf(sc->sc_dev,
2150		    "timeout waiting for clock stabilization\n");
2151		return EIO;
2152	}
2153
2154	tmp = CSR_READ_4(sc, IWI_CSR_RST);
2155	CSR_WRITE_4(sc, IWI_CSR_RST, tmp | IWI_RST_SOFT_RESET);
2156
2157	DELAY(10);
2158
2159	tmp = CSR_READ_4(sc, IWI_CSR_CTL);
2160	CSR_WRITE_4(sc, IWI_CSR_CTL, tmp | IWI_CTL_INIT);
2161
2162	/* clear NIC memory */
2163	CSR_WRITE_4(sc, IWI_CSR_AUTOINC_ADDR, 0);
2164	for (i = 0; i < 0xc000; i++)
2165		CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, 0);
2166
2167	return 0;
2168}
2169
2170static const struct iwi_firmware_ohdr *
2171iwi_setup_ofw(struct iwi_softc *sc, struct iwi_fw *fw)
2172{
2173	const struct firmware *fp = fw->fp;
2174	const struct iwi_firmware_ohdr *hdr;
2175
2176	if (fp->datasize < sizeof (struct iwi_firmware_ohdr)) {
2177		device_printf(sc->sc_dev, "image '%s' too small\n", fp->name);
2178		return NULL;
2179	}
2180	hdr = (const struct iwi_firmware_ohdr *)fp->data;
2181	if ((IWI_FW_GET_MAJOR(le32toh(hdr->version)) != IWI_FW_REQ_MAJOR) ||
2182	    (IWI_FW_GET_MINOR(le32toh(hdr->version)) != IWI_FW_REQ_MINOR)) {
2183		device_printf(sc->sc_dev, "version for '%s' %d.%d != %d.%d\n",
2184		    fp->name, IWI_FW_GET_MAJOR(le32toh(hdr->version)),
2185		    IWI_FW_GET_MINOR(le32toh(hdr->version)), IWI_FW_REQ_MAJOR,
2186		    IWI_FW_REQ_MINOR);
2187		return NULL;
2188	}
2189	fw->data = ((const char *) fp->data) + sizeof(struct iwi_firmware_ohdr);
2190	fw->size = fp->datasize - sizeof(struct iwi_firmware_ohdr);
2191	fw->name = fp->name;
2192	return hdr;
2193}
2194
2195static const struct iwi_firmware_ohdr *
2196iwi_setup_oucode(struct iwi_softc *sc, struct iwi_fw *fw)
2197{
2198	const struct iwi_firmware_ohdr *hdr;
2199
2200	hdr = iwi_setup_ofw(sc, fw);
2201	if (hdr != NULL && le32toh(hdr->mode) != IWI_FW_MODE_UCODE) {
2202		device_printf(sc->sc_dev, "%s is not a ucode image\n",
2203		    fw->name);
2204		hdr = NULL;
2205	}
2206	return hdr;
2207}
2208
2209static void
2210iwi_getfw(struct iwi_fw *fw, const char *fwname,
2211	  struct iwi_fw *uc, const char *ucname)
2212{
2213	if (fw->fp == NULL)
2214		fw->fp = firmware_get(fwname);
2215	/* NB: pre-3.0 ucode is packaged separately */
2216	if (uc->fp == NULL && fw->fp != NULL && fw->fp->version < 300)
2217		uc->fp = firmware_get(ucname);
2218}
2219
2220/*
2221 * Get the required firmware images if not already loaded.
2222 * Note that we hold firmware images so long as the device
2223 * is marked up in case we need to reload them on device init.
2224 * This is necessary because we re-init the device sometimes
2225 * from a context where we cannot read from the filesystem
2226 * (e.g. from the taskqueue thread when rfkill is re-enabled).
2227 * XXX return 0 on success, 1 on error.
2228 *
2229 * NB: the order of get'ing and put'ing images here is
2230 * intentional to support handling firmware images bundled
2231 * by operating mode and/or all together in one file with
2232 * the boot firmware as "master".
2233 */
2234static int
2235iwi_get_firmware(struct iwi_softc *sc)
2236{
2237	struct ieee80211com *ic = &sc->sc_ic;
2238	const struct iwi_firmware_hdr *hdr;
2239	const struct firmware *fp;
2240
2241	/* invalidate cached firmware on mode change */
2242	if (sc->fw_mode != ic->ic_opmode)
2243		iwi_put_firmware(sc);
2244
2245	switch (ic->ic_opmode) {
2246	case IEEE80211_M_STA:
2247		iwi_getfw(&sc->fw_fw, "iwi_bss", &sc->fw_uc, "iwi_ucode_bss");
2248		break;
2249
2250	case IEEE80211_M_IBSS:
2251		iwi_getfw(&sc->fw_fw, "iwi_ibss", &sc->fw_uc, "iwi_ucode_ibss");
2252		break;
2253
2254	case IEEE80211_M_MONITOR:
2255		iwi_getfw(&sc->fw_fw, "iwi_monitor",
2256			  &sc->fw_uc, "iwi_ucode_monitor");
2257		break;
2258
2259	default:
2260		break;
2261	}
2262	fp = sc->fw_fw.fp;
2263	if (fp == NULL) {
2264		device_printf(sc->sc_dev, "could not load firmware\n");
2265		goto bad;
2266	}
2267	if (fp->version < 300) {
2268		/*
2269		 * Firmware prior to 3.0 was packaged as separate
2270		 * boot, firmware, and ucode images.  Verify the
2271		 * ucode image was read in, retrieve the boot image
2272		 * if needed, and check version stamps for consistency.
2273		 * The version stamps in the data are also checked
2274		 * above; this is a bit paranoid but is a cheap
2275		 * safeguard against mis-packaging.
2276		 */
2277		if (sc->fw_uc.fp == NULL) {
2278			device_printf(sc->sc_dev, "could not load ucode\n");
2279			goto bad;
2280		}
2281		if (sc->fw_boot.fp == NULL) {
2282			sc->fw_boot.fp = firmware_get("iwi_boot");
2283			if (sc->fw_boot.fp == NULL) {
2284				device_printf(sc->sc_dev,
2285					"could not load boot firmware\n");
2286				goto bad;
2287			}
2288		}
2289		if (sc->fw_boot.fp->version != sc->fw_fw.fp->version ||
2290		    sc->fw_boot.fp->version != sc->fw_uc.fp->version) {
2291			device_printf(sc->sc_dev,
2292			    "firmware version mismatch: "
2293			    "'%s' is %d, '%s' is %d, '%s' is %d\n",
2294			    sc->fw_boot.fp->name, sc->fw_boot.fp->version,
2295			    sc->fw_uc.fp->name, sc->fw_uc.fp->version,
2296			    sc->fw_fw.fp->name, sc->fw_fw.fp->version
2297			);
2298			goto bad;
2299		}
2300		/*
2301		 * Check and setup each image.
2302		 */
2303		if (iwi_setup_oucode(sc, &sc->fw_uc) == NULL ||
2304		    iwi_setup_ofw(sc, &sc->fw_boot) == NULL ||
2305		    iwi_setup_ofw(sc, &sc->fw_fw) == NULL)
2306			goto bad;
2307	} else {
2308		/*
2309		 * Check and setup combined image.
2310		 */
2311		if (fp->datasize < sizeof(struct iwi_firmware_hdr)) {
2312			device_printf(sc->sc_dev, "image '%s' too small\n",
2313			    fp->name);
2314			goto bad;
2315		}
2316		hdr = (const struct iwi_firmware_hdr *)fp->data;
2317		if (fp->datasize < sizeof(*hdr) + le32toh(hdr->bsize) + le32toh(hdr->usize)
2318				+ le32toh(hdr->fsize)) {
2319			device_printf(sc->sc_dev, "image '%s' too small (2)\n",
2320			    fp->name);
2321			goto bad;
2322		}
2323		sc->fw_boot.data = ((const char *) fp->data) + sizeof(*hdr);
2324		sc->fw_boot.size = le32toh(hdr->bsize);
2325		sc->fw_boot.name = fp->name;
2326		sc->fw_uc.data = sc->fw_boot.data + sc->fw_boot.size;
2327		sc->fw_uc.size = le32toh(hdr->usize);
2328		sc->fw_uc.name = fp->name;
2329		sc->fw_fw.data = sc->fw_uc.data + sc->fw_uc.size;
2330		sc->fw_fw.size = le32toh(hdr->fsize);
2331		sc->fw_fw.name = fp->name;
2332	}
2333#if 0
2334	device_printf(sc->sc_dev, "boot %d ucode %d fw %d bytes\n",
2335		sc->fw_boot.size, sc->fw_uc.size, sc->fw_fw.size);
2336#endif
2337
2338	sc->fw_mode = ic->ic_opmode;
2339	return 0;
2340bad:
2341	iwi_put_firmware(sc);
2342	return 1;
2343}
2344
2345static void
2346iwi_put_fw(struct iwi_fw *fw)
2347{
2348	if (fw->fp != NULL) {
2349		firmware_put(fw->fp, FIRMWARE_UNLOAD);
2350		fw->fp = NULL;
2351	}
2352	fw->data = NULL;
2353	fw->size = 0;
2354	fw->name = NULL;
2355}
2356
2357/*
2358 * Release any cached firmware images.
2359 */
2360static void
2361iwi_put_firmware(struct iwi_softc *sc)
2362{
2363	iwi_put_fw(&sc->fw_uc);
2364	iwi_put_fw(&sc->fw_fw);
2365	iwi_put_fw(&sc->fw_boot);
2366}
2367
2368static int
2369iwi_load_ucode(struct iwi_softc *sc, const struct iwi_fw *fw)
2370{
2371	uint32_t tmp;
2372	const uint16_t *w;
2373	const char *uc = fw->data;
2374	size_t size = fw->size;
2375	int i, ntries, error;
2376
2377	IWI_LOCK_ASSERT(sc);
2378	error = 0;
2379	CSR_WRITE_4(sc, IWI_CSR_RST, CSR_READ_4(sc, IWI_CSR_RST) |
2380	    IWI_RST_STOP_MASTER);
2381	for (ntries = 0; ntries < 5; ntries++) {
2382		if (CSR_READ_4(sc, IWI_CSR_RST) & IWI_RST_MASTER_DISABLED)
2383			break;
2384		DELAY(10);
2385	}
2386	if (ntries == 5) {
2387		device_printf(sc->sc_dev, "timeout waiting for master\n");
2388		error = EIO;
2389		goto fail;
2390	}
2391
2392	MEM_WRITE_4(sc, 0x3000e0, 0x80000000);
2393	DELAY(5000);
2394
2395	tmp = CSR_READ_4(sc, IWI_CSR_RST);
2396	tmp &= ~IWI_RST_PRINCETON_RESET;
2397	CSR_WRITE_4(sc, IWI_CSR_RST, tmp);
2398
2399	DELAY(5000);
2400	MEM_WRITE_4(sc, 0x3000e0, 0);
2401	DELAY(1000);
2402	MEM_WRITE_4(sc, IWI_MEM_EEPROM_EVENT, 1);
2403	DELAY(1000);
2404	MEM_WRITE_4(sc, IWI_MEM_EEPROM_EVENT, 0);
2405	DELAY(1000);
2406	MEM_WRITE_1(sc, 0x200000, 0x00);
2407	MEM_WRITE_1(sc, 0x200000, 0x40);
2408	DELAY(1000);
2409
2410	/* write microcode into adapter memory */
2411	for (w = (const uint16_t *)uc; size > 0; w++, size -= 2)
2412		MEM_WRITE_2(sc, 0x200010, htole16(*w));
2413
2414	MEM_WRITE_1(sc, 0x200000, 0x00);
2415	MEM_WRITE_1(sc, 0x200000, 0x80);
2416
2417	/* wait until we get an answer */
2418	for (ntries = 0; ntries < 100; ntries++) {
2419		if (MEM_READ_1(sc, 0x200000) & 1)
2420			break;
2421		DELAY(100);
2422	}
2423	if (ntries == 100) {
2424		device_printf(sc->sc_dev,
2425		    "timeout waiting for ucode to initialize\n");
2426		error = EIO;
2427		goto fail;
2428	}
2429
2430	/* read the answer or the firmware will not initialize properly */
2431	for (i = 0; i < 7; i++)
2432		MEM_READ_4(sc, 0x200004);
2433
2434	MEM_WRITE_1(sc, 0x200000, 0x00);
2435
2436fail:
2437	return error;
2438}
2439
2440/* macro to handle unaligned little endian data in firmware image */
2441#define GETLE32(p) ((p)[0] | (p)[1] << 8 | (p)[2] << 16 | (p)[3] << 24)
2442
2443static int
2444iwi_load_firmware(struct iwi_softc *sc, const struct iwi_fw *fw)
2445{
2446	u_char *p, *end;
2447	uint32_t sentinel, ctl, src, dst, sum, len, mlen, tmp;
2448	int ntries, error;
2449
2450	IWI_LOCK_ASSERT(sc);
2451	/* copy firmware image to DMA memory */
2452	memcpy(sc->fw_virtaddr, fw->data, fw->size);
2453
2454	/* make sure the adapter will get up-to-date values */
2455	bus_dmamap_sync(sc->fw_dmat, sc->fw_map, BUS_DMASYNC_PREWRITE);
2456
2457	/* tell the adapter where the command blocks are stored */
2458	MEM_WRITE_4(sc, 0x3000a0, 0x27000);
2459
2460	/*
2461	 * Store command blocks into adapter's internal memory using register
2462	 * indirections. The adapter will read the firmware image through DMA
2463	 * using information stored in command blocks.
2464	 */
2465	src = sc->fw_physaddr;
2466	p = sc->fw_virtaddr;
2467	end = p + fw->size;
2468	CSR_WRITE_4(sc, IWI_CSR_AUTOINC_ADDR, 0x27000);
2469
2470	while (p < end) {
2471		dst = GETLE32(p); p += 4; src += 4;
2472		len = GETLE32(p); p += 4; src += 4;
2473		p += len;
2474
2475		while (len > 0) {
2476			mlen = min(len, IWI_CB_MAXDATALEN);
2477
2478			ctl = IWI_CB_DEFAULT_CTL | mlen;
2479			sum = ctl ^ src ^ dst;
2480
2481			/* write a command block */
2482			CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, ctl);
2483			CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, src);
2484			CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, dst);
2485			CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, sum);
2486
2487			src += mlen;
2488			dst += mlen;
2489			len -= mlen;
2490		}
2491	}
2492
2493	/* write a fictive final command block (sentinel) */
2494	sentinel = CSR_READ_4(sc, IWI_CSR_AUTOINC_ADDR);
2495	CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, 0);
2496
2497	tmp = CSR_READ_4(sc, IWI_CSR_RST);
2498	tmp &= ~(IWI_RST_MASTER_DISABLED | IWI_RST_STOP_MASTER);
2499	CSR_WRITE_4(sc, IWI_CSR_RST, tmp);
2500
2501	/* tell the adapter to start processing command blocks */
2502	MEM_WRITE_4(sc, 0x3000a4, 0x540100);
2503
2504	/* wait until the adapter reaches the sentinel */
2505	for (ntries = 0; ntries < 400; ntries++) {
2506		if (MEM_READ_4(sc, 0x3000d0) >= sentinel)
2507			break;
2508		DELAY(100);
2509	}
2510	/* sync dma, just in case */
2511	bus_dmamap_sync(sc->fw_dmat, sc->fw_map, BUS_DMASYNC_POSTWRITE);
2512	if (ntries == 400) {
2513		device_printf(sc->sc_dev,
2514		    "timeout processing command blocks for %s firmware\n",
2515		    fw->name);
2516		return EIO;
2517	}
2518
2519	/* we're done with command blocks processing */
2520	MEM_WRITE_4(sc, 0x3000a4, 0x540c00);
2521
2522	/* allow interrupts so we know when the firmware is ready */
2523	CSR_WRITE_4(sc, IWI_CSR_INTR_MASK, IWI_INTR_MASK);
2524
2525	/* tell the adapter to initialize the firmware */
2526	CSR_WRITE_4(sc, IWI_CSR_RST, 0);
2527
2528	tmp = CSR_READ_4(sc, IWI_CSR_CTL);
2529	CSR_WRITE_4(sc, IWI_CSR_CTL, tmp | IWI_CTL_ALLOW_STANDBY);
2530
2531	/* wait at most one second for firmware initialization to complete */
2532	if ((error = msleep(sc, &sc->sc_mtx, 0, "iwiinit", hz)) != 0) {
2533		device_printf(sc->sc_dev, "timeout waiting for %s firmware "
2534		    "initialization to complete\n", fw->name);
2535	}
2536
2537	return error;
2538}
2539
2540static int
2541iwi_setpowermode(struct iwi_softc *sc)
2542{
2543	struct ieee80211com *ic = &sc->sc_ic;
2544	uint32_t data;
2545
2546	if (ic->ic_flags & IEEE80211_F_PMGTON) {
2547		/* XXX set more fine-grained operation */
2548		data = htole32(IWI_POWER_MODE_MAX);
2549	} else
2550		data = htole32(IWI_POWER_MODE_CAM);
2551
2552	DPRINTF(("Setting power mode to %u\n", le32toh(data)));
2553	return iwi_cmd(sc, IWI_CMD_SET_POWER_MODE, &data, sizeof data);
2554}
2555
2556static int
2557iwi_setwepkeys(struct iwi_softc *sc)
2558{
2559	struct ieee80211com *ic = &sc->sc_ic;
2560	struct iwi_wep_key wepkey;
2561	struct ieee80211_key *wk;
2562	int error, i;
2563
2564	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
2565		wk = &ic->ic_crypto.cs_nw_keys[i];
2566
2567		wepkey.cmd = IWI_WEP_KEY_CMD_SETKEY;
2568		wepkey.idx = i;
2569		wepkey.len = wk->wk_keylen;
2570		memset(wepkey.key, 0, sizeof wepkey.key);
2571		memcpy(wepkey.key, wk->wk_key, wk->wk_keylen);
2572		DPRINTF(("Setting wep key index %u len %u\n", wepkey.idx,
2573		    wepkey.len));
2574		error = iwi_cmd(sc, IWI_CMD_SET_WEP_KEY, &wepkey,
2575		    sizeof wepkey);
2576		if (error != 0)
2577			return error;
2578	}
2579	return 0;
2580}
2581
2582static int
2583iwi_config(struct iwi_softc *sc)
2584{
2585	struct ieee80211com *ic = &sc->sc_ic;
2586	struct ifnet *ifp = ic->ic_ifp;
2587	struct iwi_configuration config;
2588	struct iwi_rateset rs;
2589	struct iwi_txpower power;
2590	uint32_t data;
2591	int error, i;
2592	IWI_LOCK_ASSERT(sc);
2593
2594	IEEE80211_ADDR_COPY(ic->ic_myaddr, IF_LLADDR(ifp));
2595	DPRINTF(("Setting MAC address to %6D\n", ic->ic_myaddr, ":"));
2596	error = iwi_cmd(sc, IWI_CMD_SET_MAC_ADDRESS, ic->ic_myaddr,
2597	    IEEE80211_ADDR_LEN);
2598	if (error != 0)
2599		return error;
2600
2601	memset(&config, 0, sizeof config);
2602	config.bluetooth_coexistence = sc->bluetooth;
2603	config.silence_threshold = 0x1e;
2604	config.antenna = sc->antenna;
2605	config.multicast_enabled = 1;
2606	config.answer_pbreq = (ic->ic_opmode == IEEE80211_M_IBSS) ? 1 : 0;
2607	config.disable_unicast_decryption = 1;
2608	config.disable_multicast_decryption = 1;
2609	DPRINTF(("Configuring adapter\n"));
2610	error = iwi_cmd(sc, IWI_CMD_SET_CONFIG, &config, sizeof config);
2611	if (error != 0)
2612		return error;
2613
2614	error = iwi_setpowermode(sc);
2615	if (error != 0)
2616		return error;
2617
2618	data = htole32(ic->ic_rtsthreshold);
2619	DPRINTF(("Setting RTS threshold to %u\n", le32toh(data)));
2620	error = iwi_cmd(sc, IWI_CMD_SET_RTS_THRESHOLD, &data, sizeof data);
2621	if (error != 0)
2622		return error;
2623
2624	data = htole32(ic->ic_fragthreshold);
2625	DPRINTF(("Setting fragmentation threshold to %u\n", le32toh(data)));
2626	error = iwi_cmd(sc, IWI_CMD_SET_FRAG_THRESHOLD, &data, sizeof data);
2627	if (error != 0)
2628		return error;
2629
2630	if (ic->ic_opmode == IEEE80211_M_IBSS) {
2631		power.mode = IWI_MODE_11B;
2632		power.nchan = 11;
2633		for (i = 0; i < 11; i++) {
2634			power.chan[i].chan = i + 1;
2635			power.chan[i].power = IWI_TXPOWER_MAX;
2636		}
2637		DPRINTF(("Setting .11b channels tx power\n"));
2638		error = iwi_cmd(sc, IWI_CMD_SET_TX_POWER, &power, sizeof power);
2639		if (error != 0)
2640			return error;
2641
2642		power.mode = IWI_MODE_11G;
2643		DPRINTF(("Setting .11g channels tx power\n"));
2644		error = iwi_cmd(sc, IWI_CMD_SET_TX_POWER, &power, sizeof power);
2645		if (error != 0)
2646			return error;
2647	}
2648
2649	rs.mode = IWI_MODE_11G;
2650	rs.type = IWI_RATESET_TYPE_SUPPORTED;
2651	rs.nrates = ic->ic_sup_rates[IEEE80211_MODE_11G].rs_nrates;
2652	memcpy(rs.rates, ic->ic_sup_rates[IEEE80211_MODE_11G].rs_rates,
2653	    rs.nrates);
2654	DPRINTF(("Setting .11bg supported rates (%u)\n", rs.nrates));
2655	error = iwi_cmd(sc, IWI_CMD_SET_RATES, &rs, sizeof rs);
2656	if (error != 0)
2657		return error;
2658
2659	rs.mode = IWI_MODE_11A;
2660	rs.type = IWI_RATESET_TYPE_SUPPORTED;
2661	rs.nrates = ic->ic_sup_rates[IEEE80211_MODE_11A].rs_nrates;
2662	memcpy(rs.rates, ic->ic_sup_rates[IEEE80211_MODE_11A].rs_rates,
2663	    rs.nrates);
2664	DPRINTF(("Setting .11a supported rates (%u)\n", rs.nrates));
2665	error = iwi_cmd(sc, IWI_CMD_SET_RATES, &rs, sizeof rs);
2666	if (error != 0)
2667		return error;
2668
2669	/* if we have a desired ESSID, set it now */
2670	if (ic->ic_des_esslen != 0) {
2671#ifdef IWI_DEBUG
2672		if (iwi_debug > 0) {
2673			printf("Setting desired ESSID to ");
2674			ieee80211_print_essid(ic->ic_des_essid,
2675			    ic->ic_des_esslen);
2676			printf("\n");
2677		}
2678#endif
2679		error = iwi_cmd(sc, IWI_CMD_SET_ESSID, ic->ic_des_essid,
2680		    ic->ic_des_esslen);
2681		if (error != 0)
2682			return error;
2683	}
2684
2685	data = htole32(arc4random());
2686	DPRINTF(("Setting initialization vector to %u\n", le32toh(data)));
2687	error = iwi_cmd(sc, IWI_CMD_SET_IV, &data, sizeof data);
2688	if (error != 0)
2689		return error;
2690
2691	error = iwi_setwepkeys(sc);
2692	if (error != 0)
2693		return error;
2694
2695	/* enable adapter */
2696	DPRINTF(("Enabling adapter\n"));
2697	return iwi_cmd(sc, IWI_CMD_ENABLE, NULL, 0);
2698}
2699
2700static __inline void
2701set_scan_type(struct iwi_scan_ext *scan, int ix, int scan_type)
2702{
2703	uint8_t *st = &scan->scan_type[ix / 2];
2704	if (ix % 2)
2705		*st = (*st & 0xf0) | ((scan_type & 0xf) << 0);
2706	else
2707		*st = (*st & 0x0f) | ((scan_type & 0xf) << 4);
2708}
2709
2710static int
2711iwi_scan(struct iwi_softc *sc)
2712{
2713#define	IEEE80211_MODE_5GHZ	(1<<IEEE80211_MODE_11A)
2714#define	IEEE80211_MODE_2GHZ	((1<<IEEE80211_MODE_11B)|1<<IEEE80211_MODE_11G)
2715	struct ieee80211com *ic = &sc->sc_ic;
2716	const struct ieee80211_channel *c;
2717	struct iwi_scan_ext scan;
2718	int i, ix, start, scan_type, error;
2719
2720	IWI_LOCK_ASSERT(sc);
2721
2722	memset(&scan, 0, sizeof scan);
2723
2724	/* XXX different dwell times for different scan types */
2725	scan.dwell_time[IWI_SCAN_TYPE_PASSIVE] = htole16(sc->dwelltime);
2726	scan.dwell_time[IWI_SCAN_TYPE_BROADCAST] = htole16(sc->dwelltime);
2727	scan.dwell_time[IWI_SCAN_TYPE_BDIRECTED] = htole16(sc->dwelltime);
2728
2729	scan.full_scan_index = htole32(ic->ic_scan.nt_scangen);
2730
2731	if (ic->ic_des_esslen != 0) {
2732		scan_type = IWI_SCAN_TYPE_BDIRECTED;
2733#ifdef IWI_DEBUG
2734		if (iwi_debug > 0) {
2735			printf("Setting desired ESSID to ");
2736			ieee80211_print_essid(ic->ic_des_essid,
2737			    ic->ic_des_esslen);
2738			printf("\n");
2739		}
2740#endif
2741		error = iwi_cmd(sc, IWI_CMD_SET_ESSID, ic->ic_des_essid,
2742		    ic->ic_des_esslen);
2743		if (error != 0)
2744			return error;
2745	} else
2746		scan_type = IWI_SCAN_TYPE_BROADCAST;
2747
2748	ix = 0;
2749	if (ic->ic_modecaps & IEEE80211_MODE_5GHZ) {
2750		start = ix;
2751		for (i = 0; i <= IEEE80211_CHAN_MAX; i++) {
2752			c = &ic->ic_channels[i];
2753			/*
2754			 * NB: ieee80211_next_scan clears curchan from the
2755			 * channel list so we must explicitly check; this
2756			 * will be fixed when the new scanning support arrives.
2757			 */
2758			if (!IEEE80211_IS_CHAN_5GHZ(c) ||
2759			    !(isset(ic->ic_chan_scan,i) || c == ic->ic_curchan))
2760				continue;
2761			ix++;
2762			scan.channels[ix] = i;
2763			if (c->ic_flags & IEEE80211_CHAN_PASSIVE)
2764				set_scan_type(&scan, ix, IWI_SCAN_TYPE_PASSIVE);
2765			else
2766				set_scan_type(&scan, ix, scan_type);
2767		}
2768		if (start != ix) {
2769			scan.channels[start] = IWI_CHAN_5GHZ | (ix - start);
2770			ix++;
2771		}
2772	}
2773	if (ic->ic_modecaps & IEEE80211_MODE_2GHZ) {
2774		start = ix;
2775		for (i = 0; i <= IEEE80211_CHAN_MAX; i++) {
2776			c = &ic->ic_channels[i];
2777			/* NB: see above */
2778			if (!IEEE80211_IS_CHAN_2GHZ(c) ||
2779			    !(isset(ic->ic_chan_scan,i) || c == ic->ic_curchan))
2780				continue;
2781			ix++;
2782			scan.channels[ix] = i;
2783			if (c->ic_flags & IEEE80211_CHAN_PASSIVE)
2784				set_scan_type(&scan, ix, IWI_SCAN_TYPE_PASSIVE);
2785			else
2786				set_scan_type(&scan, ix, scan_type);
2787		}
2788		if (start != ix)
2789			scan.channels[start] = IWI_CHAN_2GHZ | (ix - start);
2790	}
2791
2792	DPRINTF(("Start scanning\n"));
2793	/*
2794	 * With 100ms/channel dwell time and a max of ~20 channels
2795	 * 5 seconds may be too tight; leave a bit more slack.
2796	 */
2797	sc->sc_scan_timer = 7;			/* seconds to complete */
2798	sc->sc_ifp->if_timer = 1;
2799	sc->flags |= IWI_FLAG_SCANNING;
2800	return iwi_cmd(sc, IWI_CMD_SCAN_EXT, &scan, sizeof scan);
2801#undef IEEE80211_MODE_5GHZ
2802#undef IEEE80211_MODE_2GHZ
2803}
2804
2805static void
2806iwi_scanabort(void *arg, int npending)
2807{
2808	struct iwi_softc *sc = arg;
2809	IWI_LOCK_DECL;
2810
2811	IWI_LOCK(sc);
2812	/* NB: make sure we're still scanning */
2813	if (sc->flags & IWI_FLAG_SCANNING)
2814		iwi_cmd(sc, IWI_CMD_ABORT_SCAN, NULL, 0);
2815	IWI_UNLOCK(sc);
2816}
2817
2818static void
2819iwi_scanstart(void *arg, int npending)
2820{
2821	struct iwi_softc *sc = arg;
2822	struct ieee80211com *ic = &sc->sc_ic;
2823	IWI_LOCK_DECL;
2824
2825	IWI_LOCK(sc);
2826	/*
2827	 * Tell the card to kick off a scan.  We guard this
2828	 * by checking IWI_FLAG_SCANNING as otherwise we'll
2829	 * do this twice because ieee80211_begin_scan will
2830	 * immediately call us back to scan the first channel
2831	 * in the list.
2832	 */
2833	if (sc->flags & IWI_FLAG_SCANNING) {
2834		ieee80211_begin_scan(ic, 1);
2835		if (iwi_scan(sc) != 0) {
2836			/* XXX should not happen */
2837			sc->flags &= ~IWI_FLAG_SCANNING;
2838			ieee80211_new_state(ic, IEEE80211_S_INIT, 0);
2839		}
2840	}
2841	IWI_UNLOCK(sc);
2842}
2843
2844static void
2845iwi_scandone(void *arg, int npending)
2846{
2847	struct iwi_softc *sc = arg;
2848	struct ieee80211com *ic = &sc->sc_ic;
2849	IWI_LOCK_DECL;
2850
2851	IWI_LOCK(sc);
2852	if (sc->flags & IWI_FLAG_ASSOCIATED)
2853		iwi_disassociate(sc, 0);
2854	ieee80211_end_scan(ic);
2855	IWI_UNLOCK(sc);
2856}
2857
2858/*
2859 * Set the current channel by doing a passive scan.  Note this
2860 * is explicitly for monitor mode operation; do not use it for
2861 * anything else (sigh).
2862 */
2863static void
2864iwi_scanchan(void *arg, int npending)
2865{
2866	struct iwi_softc *sc = arg;
2867	struct ieee80211com *ic;
2868	struct ieee80211_channel *chan;
2869	struct iwi_scan_ext scan;
2870	IWI_LOCK_DECL;
2871
2872	IWI_LOCK(sc);
2873	ic = &sc->sc_ic;
2874	KASSERT(ic->ic_opmode == IEEE80211_M_MONITOR,
2875		("opmode %u", ic->ic_opmode));
2876	chan = ic->ic_ibss_chan;
2877
2878	memset(&scan, 0, sizeof scan);
2879	/*
2880	 * Set the dwell time to a fairly small value.  The firmware
2881	 * is prone to crash when aborting a scan so it's better to
2882	 * let a scan complete before changing channels--such as when
2883	 * channel hopping in monitor mode.
2884	 */
2885	scan.dwell_time[IWI_SCAN_TYPE_PASSIVE] = htole16(2000);
2886	scan.full_scan_index = htole32(ic->ic_scan.nt_scangen);
2887	if (IEEE80211_IS_CHAN_5GHZ(chan))
2888		scan.channels[0] = 1 | IWI_CHAN_5GHZ;
2889	else
2890		scan.channels[0] = 1 | IWI_CHAN_2GHZ;
2891	scan.channels[1] = ieee80211_chan2ieee(ic, chan);
2892	set_scan_type(&scan, 1, IWI_SCAN_TYPE_PASSIVE);
2893
2894	DPRINTF(("Setting channel to %u\n", ieee80211_chan2ieee(ic, chan)));
2895	sc->flags |= IWI_FLAG_SCANNING;
2896	(void) iwi_cmd(sc, IWI_CMD_SCAN_EXT, &scan, sizeof scan);
2897	IWI_UNLOCK(sc);
2898}
2899
2900static int
2901iwi_set_sensitivity(struct iwi_softc *sc, int8_t rssi_dbm)
2902{
2903	struct iwi_sensitivity sens;
2904
2905	DPRINTF(("Setting sensitivity to %d\n", rssi_dbm));
2906
2907	memset(&sens, 0, sizeof sens);
2908	sens.rssi = htole16(rssi_dbm);
2909	return iwi_cmd(sc, IWI_CMD_SET_SENSITIVITY, &sens, sizeof sens);
2910}
2911
2912static int
2913iwi_auth_and_assoc(struct iwi_softc *sc)
2914{
2915	struct ieee80211com *ic = &sc->sc_ic;
2916	struct ifnet *ifp = ic->ic_ifp;
2917	struct ieee80211_node *ni = ic->ic_bss;
2918	struct iwi_configuration config;
2919	struct iwi_associate *assoc = &sc->assoc;
2920	struct iwi_rateset rs;
2921	uint16_t capinfo;
2922	int error;
2923
2924	IWI_LOCK_ASSERT(sc);
2925	if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan)) {
2926		memset(&config, 0, sizeof config);
2927		config.bluetooth_coexistence = sc->bluetooth;
2928		config.antenna = sc->antenna;
2929		config.multicast_enabled = 1;
2930		config.use_protection = 1;
2931		config.answer_pbreq =
2932		    (ic->ic_opmode == IEEE80211_M_IBSS) ? 1 : 0;
2933		config.disable_unicast_decryption = 1;
2934		config.disable_multicast_decryption = 1;
2935		DPRINTF(("Configuring adapter\n"));
2936		error = iwi_cmd(sc, IWI_CMD_SET_CONFIG, &config, sizeof config);
2937		if (error != 0)
2938			return error;
2939	}
2940
2941#ifdef IWI_DEBUG
2942	if (iwi_debug > 0) {
2943		printf("Setting ESSID to ");
2944		ieee80211_print_essid(ni->ni_essid, ni->ni_esslen);
2945		printf("\n");
2946	}
2947#endif
2948	error = iwi_cmd(sc, IWI_CMD_SET_ESSID, ni->ni_essid, ni->ni_esslen);
2949	if (error != 0)
2950		return error;
2951
2952	/* the rate set has already been "negotiated" */
2953	rs.mode = IEEE80211_IS_CHAN_5GHZ(ni->ni_chan) ? IWI_MODE_11A :
2954	    IWI_MODE_11G;
2955	rs.type = IWI_RATESET_TYPE_NEGOTIATED;
2956	rs.nrates = ni->ni_rates.rs_nrates;
2957	if (rs.nrates > IWI_RATESET_SIZE) {
2958		DPRINTF(("Truncating negotiated rate set from %u\n",
2959		    rs.nrates));
2960		rs.nrates = IWI_RATESET_SIZE;
2961	}
2962	memcpy(rs.rates, ni->ni_rates.rs_rates, rs.nrates);
2963	DPRINTF(("Setting negotiated rates (%u)\n", rs.nrates));
2964	error = iwi_cmd(sc, IWI_CMD_SET_RATES, &rs, sizeof rs);
2965	if (error != 0)
2966		return error;
2967
2968	memset(assoc, 0, sizeof *assoc);
2969
2970	if ((ic->ic_flags & IEEE80211_F_WME) && ni->ni_wme_ie != NULL) {
2971		/* NB: don't treat WME setup as failure */
2972		if (iwi_wme_setparams_locked(sc) == 0 && iwi_wme_setie(sc) == 0)
2973			assoc->policy |= htole16(IWI_POLICY_WME);
2974		/* XXX complain on failure? */
2975	}
2976
2977	if (ic->ic_opt_ie != NULL) {
2978		DPRINTF(("Setting optional IE (len=%u)\n", ic->ic_opt_ie_len));
2979		error = iwi_cmd(sc, IWI_CMD_SET_OPTIE, ic->ic_opt_ie,
2980		    ic->ic_opt_ie_len);
2981		if (error != 0)
2982			return error;
2983	}
2984
2985	error = iwi_set_sensitivity(sc, ni->ni_rssi);
2986	if (error != 0)
2987		return error;
2988
2989	if (IEEE80211_IS_CHAN_A(ni->ni_chan))
2990		assoc->mode = IWI_MODE_11A;
2991	else if (IEEE80211_IS_CHAN_G(ni->ni_chan))
2992		assoc->mode = IWI_MODE_11G;
2993	else if (IEEE80211_IS_CHAN_B(ni->ni_chan))
2994		assoc->mode = IWI_MODE_11B;
2995	/* XXX else error */
2996	assoc->chan = ieee80211_chan2ieee(ic, ni->ni_chan);
2997	/*
2998	 * NB: do not arrange for shared key auth w/o privacy
2999	 *     (i.e. a wep key); it causes a firmware error.
3000	 */
3001	if ((ic->ic_flags & IEEE80211_F_PRIVACY) &&
3002	    ni->ni_authmode == IEEE80211_AUTH_SHARED) {
3003		assoc->auth = IWI_AUTH_SHARED;
3004		/*
3005		 * It's possible to have privacy marked but no default
3006		 * key setup.  This typically is due to a user app bug
3007		 * but if we blindly grab the key the firmware will
3008		 * barf so avoid it for now.
3009		 */
3010		if (ic->ic_crypto.cs_def_txkey != IEEE80211_KEYIX_NONE)
3011			assoc->auth |= ic->ic_crypto.cs_def_txkey << 4;
3012
3013		error = iwi_setwepkeys(sc);
3014		if (error != 0)
3015			return error;
3016	}
3017	if (ic->ic_flags & IEEE80211_F_WPA)
3018		assoc->policy |= htole16(IWI_POLICY_WPA);
3019	if (ic->ic_opmode == IEEE80211_M_IBSS && ni->ni_tstamp.tsf == 0)
3020		assoc->type = IWI_HC_IBSS_START;
3021	else
3022		assoc->type = IWI_HC_ASSOC;
3023	memcpy(assoc->tstamp, ni->ni_tstamp.data, 8);
3024
3025	if (ic->ic_opmode == IEEE80211_M_IBSS)
3026		capinfo = IEEE80211_CAPINFO_IBSS;
3027	else
3028		capinfo = IEEE80211_CAPINFO_ESS;
3029	if (ic->ic_flags & IEEE80211_F_PRIVACY)
3030		capinfo |= IEEE80211_CAPINFO_PRIVACY;
3031	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
3032	    IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
3033		capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
3034	if (ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME)
3035		capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
3036	assoc->capinfo = htole16(capinfo);
3037
3038	assoc->lintval = htole16(ic->ic_lintval);
3039	assoc->intval = htole16(ni->ni_intval);
3040	IEEE80211_ADDR_COPY(assoc->bssid, ni->ni_bssid);
3041	if (ic->ic_opmode == IEEE80211_M_IBSS)
3042		IEEE80211_ADDR_COPY(assoc->dst, ifp->if_broadcastaddr);
3043	else
3044		IEEE80211_ADDR_COPY(assoc->dst, ni->ni_bssid);
3045
3046	DPRINTF(("%s bssid %6D dst %6D channel %u policy 0x%x "
3047	    "auth %u capinfo 0x%x lintval %u bintval %u\n",
3048	    assoc->type == IWI_HC_IBSS_START ? "Start" : "Join",
3049	    assoc->bssid, ":", assoc->dst, ":",
3050	    assoc->chan, le16toh(assoc->policy), assoc->auth,
3051	    le16toh(assoc->capinfo), le16toh(assoc->lintval),
3052	    le16toh(assoc->intval)));
3053	return iwi_cmd(sc, IWI_CMD_ASSOCIATE, assoc, sizeof *assoc);
3054}
3055
3056static int
3057iwi_disassociate(struct iwi_softc *sc, int quiet)
3058{
3059	struct iwi_associate *assoc = &sc->assoc;
3060
3061	if (quiet)
3062		assoc->type = IWI_HC_DISASSOC_QUIET;
3063	else
3064		assoc->type = IWI_HC_DISASSOC;
3065
3066	DPRINTF(("Trying to disassociate from %6D channel %u\n",
3067	    assoc->bssid, ":", assoc->chan));
3068	return iwi_cmd(sc, IWI_CMD_ASSOCIATE, assoc, sizeof *assoc);
3069}
3070
3071static void
3072iwi_down(void *arg, int npending)
3073{
3074	struct iwi_softc *sc = arg;
3075	IWI_LOCK_DECL;
3076
3077	IWI_LOCK(sc);
3078	iwi_disassociate(sc, 0);
3079	IWI_UNLOCK(sc);
3080}
3081
3082static void
3083iwi_init(void *priv)
3084{
3085	struct iwi_softc *sc = priv;
3086	IWI_LOCK_DECL;
3087
3088	IWI_LOCK(sc);
3089	iwi_init_locked(sc, 0);
3090	IWI_UNLOCK(sc);
3091}
3092
3093/*
3094 * release dma resources for the firmware
3095 */
3096static void
3097iwi_release_fw_dma(struct iwi_softc *sc)
3098{
3099	if (sc->fw_flags & IWI_FW_HAVE_PHY)
3100		bus_dmamap_unload(sc->fw_dmat, sc->fw_map);
3101	if (sc->fw_flags & IWI_FW_HAVE_MAP)
3102		bus_dmamem_free(sc->fw_dmat, sc->fw_virtaddr, sc->fw_map);
3103	if (sc->fw_flags & IWI_FW_HAVE_DMAT)
3104		bus_dma_tag_destroy(sc->fw_dmat);
3105
3106	sc->fw_flags = 0;
3107	sc->fw_dma_size = 0;
3108	sc->fw_dmat = NULL;
3109	sc->fw_map = NULL;
3110	sc->fw_physaddr = 0;
3111	sc->fw_virtaddr = NULL;
3112}
3113
3114/*
3115 * allocate the dma descriptor for the firmware.
3116 * Return 0 on success, 1 on error.
3117 * Must be called unlocked, protected by IWI_FLAG_FW_LOADING.
3118 */
3119static int
3120iwi_init_fw_dma(struct iwi_softc *sc, int size)
3121{
3122	if (sc->fw_dma_size > size)
3123		return 0;
3124	if (bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 4, 0,
3125	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
3126	    size, 1, size, 0, NULL, NULL, &sc->fw_dmat) != 0) {
3127		device_printf(sc->sc_dev,
3128		    "could not create firmware DMA tag\n");
3129		goto error;
3130	}
3131	sc->fw_flags |= IWI_FW_HAVE_DMAT;
3132	if (bus_dmamem_alloc(sc->fw_dmat, &sc->fw_virtaddr, 0,
3133	    &sc->fw_map) != 0) {
3134		device_printf(sc->sc_dev,
3135		    "could not allocate firmware DMA memory\n");
3136		goto error;
3137	}
3138	sc->fw_flags |= IWI_FW_HAVE_MAP;
3139	if (bus_dmamap_load(sc->fw_dmat, sc->fw_map, sc->fw_virtaddr,
3140	    size, iwi_dma_map_addr, &sc->fw_physaddr, 0) != 0) {
3141		device_printf(sc->sc_dev, "could not load firmware DMA map\n");
3142		goto error;
3143	}
3144	sc->fw_flags |= IWI_FW_HAVE_PHY;
3145	sc->fw_dma_size = size;
3146	return 0;
3147
3148error:
3149	iwi_release_fw_dma(sc);
3150	return 1;
3151}
3152
3153static void
3154iwi_init_locked(void *priv, int force)
3155{
3156	struct iwi_softc *sc = priv;
3157	struct ieee80211com *ic = &sc->sc_ic;
3158	struct ifnet *ifp = ic->ic_ifp;
3159	struct iwi_rx_data *data;
3160	int i;
3161	IWI_LOCK_DECL;
3162
3163	IWI_LOCK_ASSERT(sc);
3164	if (sc->flags & IWI_FLAG_FW_LOADING) {
3165		device_printf(sc->sc_dev, "%s: already loading\n", __func__);
3166		return;		/* XXX: condvar? */
3167	}
3168
3169	iwi_stop(sc);
3170
3171	if (iwi_reset(sc) != 0) {
3172		device_printf(sc->sc_dev, "could not reset adapter\n");
3173		goto fail;
3174	}
3175
3176	sc->flags |= IWI_FLAG_FW_LOADING;
3177
3178	IWI_UNLOCK(sc);
3179	if (iwi_get_firmware(sc)) {
3180		IWI_LOCK(sc);
3181		goto fail;
3182	}
3183
3184	/* allocate DMA memory for mapping firmware image */
3185	i = sc->fw_fw.size;
3186	if (sc->fw_boot.size > i)
3187		i = sc->fw_boot.size;
3188	/* XXX do we dma the ucode as well ? */
3189	if (sc->fw_uc.size > i)
3190		i = sc->fw_uc.size;
3191	if (iwi_init_fw_dma(sc, i)) {
3192		IWI_LOCK(sc);
3193		goto fail;
3194	}
3195	IWI_LOCK(sc);
3196
3197	if (iwi_load_firmware(sc, &sc->fw_boot) != 0) {
3198		device_printf(sc->sc_dev,
3199		    "could not load boot firmware %s\n", sc->fw_boot.name);
3200		goto fail;
3201	}
3202
3203	if (iwi_load_ucode(sc, &sc->fw_uc) != 0) {
3204		device_printf(sc->sc_dev,
3205		    "could not load microcode %s\n", sc->fw_uc.name);
3206		goto fail;
3207	}
3208
3209	iwi_stop_master(sc);
3210
3211	CSR_WRITE_4(sc, IWI_CSR_CMD_BASE, sc->cmdq.physaddr);
3212	CSR_WRITE_4(sc, IWI_CSR_CMD_SIZE, sc->cmdq.count);
3213	CSR_WRITE_4(sc, IWI_CSR_CMD_WIDX, sc->cmdq.cur);
3214
3215	CSR_WRITE_4(sc, IWI_CSR_TX1_BASE, sc->txq[0].physaddr);
3216	CSR_WRITE_4(sc, IWI_CSR_TX1_SIZE, sc->txq[0].count);
3217	CSR_WRITE_4(sc, IWI_CSR_TX1_WIDX, sc->txq[0].cur);
3218
3219	CSR_WRITE_4(sc, IWI_CSR_TX2_BASE, sc->txq[1].physaddr);
3220	CSR_WRITE_4(sc, IWI_CSR_TX2_SIZE, sc->txq[1].count);
3221	CSR_WRITE_4(sc, IWI_CSR_TX2_WIDX, sc->txq[1].cur);
3222
3223	CSR_WRITE_4(sc, IWI_CSR_TX3_BASE, sc->txq[2].physaddr);
3224	CSR_WRITE_4(sc, IWI_CSR_TX3_SIZE, sc->txq[2].count);
3225	CSR_WRITE_4(sc, IWI_CSR_TX3_WIDX, sc->txq[2].cur);
3226
3227	CSR_WRITE_4(sc, IWI_CSR_TX4_BASE, sc->txq[3].physaddr);
3228	CSR_WRITE_4(sc, IWI_CSR_TX4_SIZE, sc->txq[3].count);
3229	CSR_WRITE_4(sc, IWI_CSR_TX4_WIDX, sc->txq[3].cur);
3230
3231	for (i = 0; i < sc->rxq.count; i++) {
3232		data = &sc->rxq.data[i];
3233		CSR_WRITE_4(sc, data->reg, data->physaddr);
3234	}
3235
3236	CSR_WRITE_4(sc, IWI_CSR_RX_WIDX, sc->rxq.count - 1);
3237
3238	if (iwi_load_firmware(sc, &sc->fw_fw) != 0) {
3239		device_printf(sc->sc_dev,
3240		    "could not load main firmware %s\n", sc->fw_fw.name);
3241		goto fail;
3242	}
3243	sc->flags |= IWI_FLAG_FW_INITED;
3244
3245	if (iwi_config(sc) != 0) {
3246		device_printf(sc->sc_dev, "device configuration failed\n");
3247		goto fail;
3248	}
3249
3250	if (ic->ic_opmode != IEEE80211_M_MONITOR) {
3251		/*
3252		 * NB: When restarting the adapter clock the state
3253		 * machine regardless of the roaming mode; otherwise
3254		 * we need to notify user apps so they can manually
3255		 * get us going again.
3256		 */
3257		if (ic->ic_roaming != IEEE80211_ROAMING_MANUAL || force)
3258			ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
3259	} else
3260		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
3261
3262	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3263	ifp->if_drv_flags |= IFF_DRV_RUNNING;
3264
3265	sc->flags &= ~IWI_FLAG_FW_LOADING;
3266	return;
3267
3268fail:	ifp->if_flags &= ~IFF_UP;
3269	sc->flags &= ~IWI_FLAG_FW_LOADING;
3270	iwi_stop(sc);
3271	iwi_put_firmware(sc);
3272}
3273
3274static void
3275iwi_stop(void *priv)
3276{
3277	struct iwi_softc *sc = priv;
3278	struct ieee80211com *ic = &sc->sc_ic;
3279	struct ifnet *ifp = ic->ic_ifp;
3280
3281	IWI_LOCK_ASSERT(sc);	/* XXX: pretty sure this triggers */
3282	if (sc->sc_softled) {
3283		callout_stop(&sc->sc_ledtimer);
3284		sc->sc_blinking = 0;
3285	}
3286
3287	iwi_stop_master(sc);
3288
3289	CSR_WRITE_4(sc, IWI_CSR_RST, IWI_RST_SOFT_RESET);
3290
3291	/* reset rings */
3292	iwi_reset_cmd_ring(sc, &sc->cmdq);
3293	iwi_reset_tx_ring(sc, &sc->txq[0]);
3294	iwi_reset_tx_ring(sc, &sc->txq[1]);
3295	iwi_reset_tx_ring(sc, &sc->txq[2]);
3296	iwi_reset_tx_ring(sc, &sc->txq[3]);
3297	iwi_reset_rx_ring(sc, &sc->rxq);
3298
3299	ifp->if_timer = 0;
3300	ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
3301
3302	sc->sc_tx_timer = 0;
3303	sc->sc_rfkill_timer = 0;
3304	sc->sc_scan_timer = 0;
3305	sc->flags &= ~(IWI_FLAG_BUSY | IWI_FLAG_SCANNING | IWI_FLAG_ASSOCIATED);
3306
3307	ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
3308}
3309
3310static void
3311iwi_restart(void *arg, int npending)
3312{
3313	struct iwi_softc *sc = arg;
3314	IWI_LOCK_DECL;
3315
3316	IWI_LOCK(sc);
3317	iwi_init_locked(sc, 1);		/* NB: force state machine */
3318	IWI_UNLOCK(sc);
3319}
3320
3321/*
3322 * Return whether or not the radio is enabled in hardware
3323 * (i.e. the rfkill switch is "off").
3324 */
3325static int
3326iwi_getrfkill(struct iwi_softc *sc)
3327{
3328	return (CSR_READ_4(sc, IWI_CSR_IO) & IWI_IO_RADIO_ENABLED) == 0;
3329}
3330
3331static void
3332iwi_radio_on(void *arg, int pending)
3333{
3334	struct iwi_softc *sc = arg;
3335
3336	device_printf(sc->sc_dev, "radio turned on\n");
3337	iwi_init(sc);
3338}
3339
3340static void
3341iwi_radio_off(void *arg, int pending)
3342{
3343	struct iwi_softc *sc = arg;
3344
3345	device_printf(sc->sc_dev, "radio turned off\n");
3346	iwi_stop(sc);
3347	sc->sc_rfkill_timer = 2;
3348	sc->sc_ifp->if_timer = 1;
3349}
3350
3351static int
3352iwi_sysctl_stats(SYSCTL_HANDLER_ARGS)
3353{
3354	struct iwi_softc *sc = arg1;
3355	uint32_t size, buf[128];
3356
3357	if (!(sc->flags & IWI_FLAG_FW_INITED)) {
3358		memset(buf, 0, sizeof buf);
3359		return SYSCTL_OUT(req, buf, sizeof buf);
3360	}
3361
3362	size = min(CSR_READ_4(sc, IWI_CSR_TABLE0_SIZE), 128 - 1);
3363	CSR_READ_REGION_4(sc, IWI_CSR_TABLE0_BASE, &buf[1], size);
3364
3365	return SYSCTL_OUT(req, buf, sizeof buf);
3366}
3367
3368static int
3369iwi_sysctl_radio(SYSCTL_HANDLER_ARGS)
3370{
3371	struct iwi_softc *sc = arg1;
3372	int val = !iwi_getrfkill(sc);
3373
3374	return SYSCTL_OUT(req, &val, sizeof val);
3375}
3376
3377/*
3378 * Add sysctl knobs.
3379 */
3380static void
3381iwi_sysctlattach(struct iwi_softc *sc)
3382{
3383	struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->sc_dev);
3384	struct sysctl_oid *tree = device_get_sysctl_tree(sc->sc_dev);
3385
3386	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "radio",
3387	    CTLTYPE_INT | CTLFLAG_RD, sc, 0, iwi_sysctl_radio, "I",
3388	    "radio transmitter switch state (0=off, 1=on)");
3389
3390	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "stats",
3391	    CTLTYPE_OPAQUE | CTLFLAG_RD, sc, 0, iwi_sysctl_stats, "S",
3392	    "statistics");
3393
3394	sc->dwelltime = 100;
3395	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "dwell",
3396	    CTLFLAG_RW, &sc->dwelltime, 0,
3397	    "channel dwell time (ms) for AP/station scanning");
3398
3399	sc->bluetooth = 0;
3400	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "bluetooth",
3401	    CTLFLAG_RW, &sc->bluetooth, 0, "bluetooth coexistence");
3402
3403	sc->antenna = IWI_ANTENNA_AUTO;
3404	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "antenna",
3405	    CTLFLAG_RW, &sc->antenna, 0, "antenna (0=auto)");
3406}
3407
3408/*
3409 * LED support.
3410 *
3411 * Different cards have different capabilities.  Some have three
3412 * led's while others have only one.  The linux ipw driver defines
3413 * led's for link state (associated or not), band (11a, 11g, 11b),
3414 * and for link activity.  We use one led and vary the blink rate
3415 * according to the tx/rx traffic a la the ath driver.
3416 */
3417
3418static __inline uint32_t
3419iwi_toggle_event(uint32_t r)
3420{
3421	return r &~ (IWI_RST_STANDBY | IWI_RST_GATE_ODMA |
3422		     IWI_RST_GATE_IDMA | IWI_RST_GATE_ADMA);
3423}
3424
3425static uint32_t
3426iwi_read_event(struct iwi_softc *sc)
3427{
3428	return MEM_READ_4(sc, IWI_MEM_EEPROM_EVENT);
3429}
3430
3431static void
3432iwi_write_event(struct iwi_softc *sc, uint32_t v)
3433{
3434	MEM_WRITE_4(sc, IWI_MEM_EEPROM_EVENT, v);
3435}
3436
3437static void
3438iwi_led_done(void *arg)
3439{
3440	struct iwi_softc *sc = arg;
3441
3442	sc->sc_blinking = 0;
3443}
3444
3445/*
3446 * Turn the activity LED off: flip the pin and then set a timer so no
3447 * update will happen for the specified duration.
3448 */
3449static void
3450iwi_led_off(void *arg)
3451{
3452	struct iwi_softc *sc = arg;
3453	uint32_t v;
3454
3455	v = iwi_read_event(sc);
3456	v &= ~sc->sc_ledpin;
3457	iwi_write_event(sc, iwi_toggle_event(v));
3458	callout_reset(&sc->sc_ledtimer, sc->sc_ledoff, iwi_led_done, sc);
3459}
3460
3461/*
3462 * Blink the LED according to the specified on/off times.
3463 */
3464static void
3465iwi_led_blink(struct iwi_softc *sc, int on, int off)
3466{
3467	uint32_t v;
3468
3469	v = iwi_read_event(sc);
3470	v |= sc->sc_ledpin;
3471	iwi_write_event(sc, iwi_toggle_event(v));
3472	sc->sc_blinking = 1;
3473	sc->sc_ledoff = off;
3474	callout_reset(&sc->sc_ledtimer, on, iwi_led_off, sc);
3475}
3476
3477static void
3478iwi_led_event(struct iwi_softc *sc, int event)
3479{
3480#define	N(a)	(sizeof(a)/sizeof(a[0]))
3481	/* NB: on/off times from the Atheros NDIS driver, w/ permission */
3482	static const struct {
3483		u_int		rate;		/* tx/rx iwi rate */
3484		u_int16_t	timeOn;		/* LED on time (ms) */
3485		u_int16_t	timeOff;	/* LED off time (ms) */
3486	} blinkrates[] = {
3487		{ IWI_RATE_OFDM54, 40,  10 },
3488		{ IWI_RATE_OFDM48, 44,  11 },
3489		{ IWI_RATE_OFDM36, 50,  13 },
3490		{ IWI_RATE_OFDM24, 57,  14 },
3491		{ IWI_RATE_OFDM18, 67,  16 },
3492		{ IWI_RATE_OFDM12, 80,  20 },
3493		{ IWI_RATE_DS11,  100,  25 },
3494		{ IWI_RATE_OFDM9, 133,  34 },
3495		{ IWI_RATE_OFDM6, 160,  40 },
3496		{ IWI_RATE_DS5,   200,  50 },
3497		{            6,   240,  58 },	/* XXX 3Mb/s if it existed */
3498		{ IWI_RATE_DS2,   267,  66 },
3499		{ IWI_RATE_DS1,   400, 100 },
3500		{            0,   500, 130 },	/* unknown rate/polling */
3501	};
3502	uint32_t txrate;
3503	int j = 0;			/* XXX silence compiler */
3504
3505	sc->sc_ledevent = ticks;	/* time of last event */
3506	if (sc->sc_blinking)		/* don't interrupt active blink */
3507		return;
3508	switch (event) {
3509	case IWI_LED_POLL:
3510		j = N(blinkrates)-1;
3511		break;
3512	case IWI_LED_TX:
3513		/* read current transmission rate from adapter */
3514		txrate = CSR_READ_4(sc, IWI_CSR_CURRENT_TX_RATE);
3515		if (blinkrates[sc->sc_txrix].rate != txrate) {
3516			for (j = 0; j < N(blinkrates)-1; j++)
3517				if (blinkrates[j].rate == txrate)
3518					break;
3519			sc->sc_txrix = j;
3520		} else
3521			j = sc->sc_txrix;
3522		break;
3523	case IWI_LED_RX:
3524		if (blinkrates[sc->sc_rxrix].rate != sc->sc_rxrate) {
3525			for (j = 0; j < N(blinkrates)-1; j++)
3526				if (blinkrates[j].rate == sc->sc_rxrate)
3527					break;
3528			sc->sc_rxrix = j;
3529		} else
3530			j = sc->sc_rxrix;
3531		break;
3532	}
3533	/* XXX beware of overflow */
3534	iwi_led_blink(sc, (blinkrates[j].timeOn * hz) / 1000,
3535		(blinkrates[j].timeOff * hz) / 1000);
3536#undef N
3537}
3538
3539static int
3540iwi_sysctl_softled(SYSCTL_HANDLER_ARGS)
3541{
3542	struct iwi_softc *sc = arg1;
3543	int softled = sc->sc_softled;
3544	int error;
3545
3546	error = sysctl_handle_int(oidp, &softled, 0, req);
3547	if (error || !req->newptr)
3548		return error;
3549	softled = (softled != 0);
3550	if (softled != sc->sc_softled) {
3551		if (softled) {
3552			uint32_t v = iwi_read_event(sc);
3553			v &= ~sc->sc_ledpin;
3554			iwi_write_event(sc, iwi_toggle_event(v));
3555		}
3556		sc->sc_softled = softled;
3557	}
3558	return 0;
3559}
3560
3561static void
3562iwi_ledattach(struct iwi_softc *sc)
3563{
3564	struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->sc_dev);
3565	struct sysctl_oid *tree = device_get_sysctl_tree(sc->sc_dev);
3566
3567	sc->sc_blinking = 0;
3568	sc->sc_ledstate = 1;
3569	sc->sc_ledidle = (2700*hz)/1000;	/* 2.7sec */
3570	callout_init_mtx(&sc->sc_ledtimer, &sc->sc_mtx, 0);
3571
3572	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
3573		"softled", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
3574		iwi_sysctl_softled, "I", "enable/disable software LED support");
3575	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
3576		"ledpin", CTLFLAG_RW, &sc->sc_ledpin, 0,
3577		"pin setting to turn activity LED on");
3578	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
3579		"ledidle", CTLFLAG_RW, &sc->sc_ledidle, 0,
3580		"idle time for inactivity LED (ticks)");
3581	/* XXX for debugging */
3582	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
3583		"nictype", CTLFLAG_RD, &sc->sc_nictype, 0,
3584		"NIC type from EEPROM");
3585
3586	sc->sc_ledpin = IWI_RST_LED_ACTIVITY;
3587	sc->sc_softled = 1;
3588
3589	sc->sc_nictype = (iwi_read_prom_word(sc, IWI_EEPROM_NIC) >> 8) & 0xff;
3590	if (sc->sc_nictype == 1) {
3591		/*
3592		 * NB: led's are reversed.
3593		 */
3594		sc->sc_ledpin = IWI_RST_LED_ASSOCIATED;
3595	}
3596}
3597