if_iwi.c revision 152389
1/*	$FreeBSD: head/sys/dev/iwi/if_iwi.c 152389 2005-11-13 17:38:02Z damien $	*/
2
3/*-
4 * Copyright (c) 2004, 2005
5 *      Damien Bergamini <damien.bergamini@free.fr>. All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice unmodified, this list of conditions, and the following
12 *    disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 */
29
30#include <sys/cdefs.h>
31__FBSDID("$FreeBSD: head/sys/dev/iwi/if_iwi.c 152389 2005-11-13 17:38:02Z damien $");
32
33/*-
34 * Intel(R) PRO/Wireless 2200BG/2225BG/2915ABG driver
35 * http://www.intel.com/network/connectivity/products/wireless/prowireless_mobile.htm
36 */
37
38#include <sys/param.h>
39#include <sys/sysctl.h>
40#include <sys/sockio.h>
41#include <sys/mbuf.h>
42#include <sys/kernel.h>
43#include <sys/socket.h>
44#include <sys/systm.h>
45#include <sys/malloc.h>
46#include <sys/module.h>
47#include <sys/bus.h>
48#include <sys/endian.h>
49
50#include <machine/bus.h>
51#include <machine/resource.h>
52#include <machine/clock.h>
53#include <sys/rman.h>
54
55#include <dev/pci/pcireg.h>
56#include <dev/pci/pcivar.h>
57
58#include <net/bpf.h>
59#include <net/if.h>
60#include <net/if_arp.h>
61#include <net/ethernet.h>
62#include <net/if_dl.h>
63#include <net/if_media.h>
64#include <net/if_types.h>
65
66#include <net80211/ieee80211_var.h>
67#include <net80211/ieee80211_radiotap.h>
68
69#include <netinet/in.h>
70#include <netinet/in_systm.h>
71#include <netinet/in_var.h>
72#include <netinet/ip.h>
73#include <netinet/if_ether.h>
74
75#include <dev/iwi/if_iwireg.h>
76#include <dev/iwi/if_iwivar.h>
77
78#ifdef IWI_DEBUG
79#define DPRINTF(x)	do { if (iwi_debug > 0) printf x; } while (0)
80#define DPRINTFN(n, x)	do { if (iwi_debug >= (n)) printf x; } while (0)
81int iwi_debug = 0;
82SYSCTL_INT(_debug, OID_AUTO, iwi, CTLFLAG_RW, &iwi_debug, 0, "iwi debug level");
83#else
84#define DPRINTF(x)
85#define DPRINTFN(n, x)
86#endif
87
88MODULE_DEPEND(iwi, pci,  1, 1, 1);
89MODULE_DEPEND(iwi, wlan, 1, 1, 1);
90
91struct iwi_ident {
92	uint16_t	vendor;
93	uint16_t	device;
94	const char	*name;
95};
96
97static const struct iwi_ident iwi_ident_table[] = {
98	{ 0x8086, 0x4220, "Intel(R) PRO/Wireless 2200BG" },
99	{ 0x8086, 0x4221, "Intel(R) PRO/Wireless 2225BG" },
100	{ 0x8086, 0x4223, "Intel(R) PRO/Wireless 2915ABG" },
101	{ 0x8086, 0x4224, "Intel(R) PRO/Wireless 2915ABG" },
102
103	{ 0, 0, NULL }
104};
105
106static void	iwi_dma_map_addr(void *, bus_dma_segment_t *, int, int);
107static int	iwi_alloc_cmd_ring(struct iwi_softc *, struct iwi_cmd_ring *,
108		    int);
109static void	iwi_reset_cmd_ring(struct iwi_softc *, struct iwi_cmd_ring *);
110static void	iwi_free_cmd_ring(struct iwi_softc *, struct iwi_cmd_ring *);
111static int	iwi_alloc_tx_ring(struct iwi_softc *, struct iwi_tx_ring *,
112		    int, bus_addr_t, bus_addr_t);
113static void	iwi_reset_tx_ring(struct iwi_softc *, struct iwi_tx_ring *);
114static void	iwi_free_tx_ring(struct iwi_softc *, struct iwi_tx_ring *);
115static int	iwi_alloc_rx_ring(struct iwi_softc *, struct iwi_rx_ring *,
116		    int);
117static void	iwi_reset_rx_ring(struct iwi_softc *, struct iwi_rx_ring *);
118static void	iwi_free_rx_ring(struct iwi_softc *, struct iwi_rx_ring *);
119static struct	ieee80211_node *iwi_node_alloc(struct ieee80211_node_table *);
120static void	iwi_node_free(struct ieee80211_node *);
121static int	iwi_media_change(struct ifnet *);
122static void	iwi_media_status(struct ifnet *, struct ifmediareq *);
123static int	iwi_newstate(struct ieee80211com *, enum ieee80211_state, int);
124static int	iwi_wme_update(struct ieee80211com *);
125static uint16_t	iwi_read_prom_word(struct iwi_softc *, uint8_t);
126static void	iwi_fix_channel(struct ieee80211com *, struct mbuf *);
127static void	iwi_frame_intr(struct iwi_softc *, struct iwi_rx_data *, int,
128		    struct iwi_frame *);
129static void	iwi_notification_intr(struct iwi_softc *, struct iwi_notif *);
130static void	iwi_rx_intr(struct iwi_softc *);
131static void	iwi_tx_intr(struct iwi_softc *, struct iwi_tx_ring *);
132static void	iwi_intr(void *);
133static int	iwi_cmd(struct iwi_softc *, uint8_t, void *, uint8_t, int);
134static void	iwi_write_ibssnode(struct iwi_softc *, const struct iwi_node *);
135static int	iwi_tx_start(struct ifnet *, struct mbuf *,
136		    struct ieee80211_node *, int);
137static void	iwi_start(struct ifnet *);
138static void	iwi_watchdog(struct ifnet *);
139static int	iwi_ioctl(struct ifnet *, u_long, caddr_t);
140static void	iwi_stop_master(struct iwi_softc *);
141static int	iwi_reset(struct iwi_softc *);
142static int	iwi_load_ucode(struct iwi_softc *, void *, int);
143static int	iwi_load_firmware(struct iwi_softc *, void *, int);
144static int	iwi_cache_firmware(struct iwi_softc *, void *);
145static void	iwi_free_firmware(struct iwi_softc *);
146static int	iwi_config(struct iwi_softc *);
147static int	iwi_set_chan(struct iwi_softc *, struct ieee80211_channel *);
148static int	iwi_scan(struct iwi_softc *);
149static int	iwi_auth_and_assoc(struct iwi_softc *);
150static void	iwi_init(void *);
151static void	iwi_stop(void *);
152static int	iwi_sysctl_stats(SYSCTL_HANDLER_ARGS);
153static int	iwi_sysctl_radio(SYSCTL_HANDLER_ARGS);
154
155static int iwi_probe(device_t);
156static int iwi_attach(device_t);
157static int iwi_detach(device_t);
158static int iwi_shutdown(device_t);
159static int iwi_suspend(device_t);
160static int iwi_resume(device_t);
161
162static device_method_t iwi_methods[] = {
163	/* Device interface */
164	DEVMETHOD(device_probe,		iwi_probe),
165	DEVMETHOD(device_attach,	iwi_attach),
166	DEVMETHOD(device_detach,	iwi_detach),
167	DEVMETHOD(device_shutdown,	iwi_shutdown),
168	DEVMETHOD(device_suspend,	iwi_suspend),
169	DEVMETHOD(device_resume,	iwi_resume),
170
171	{ 0, 0 }
172};
173
174static driver_t iwi_driver = {
175	"iwi",
176	iwi_methods,
177	sizeof (struct iwi_softc)
178};
179
180static devclass_t iwi_devclass;
181
182DRIVER_MODULE(iwi, pci, iwi_driver, iwi_devclass, 0, 0);
183
184/*
185 * Supported rates for 802.11a/b/g modes (in 500Kbps unit).
186 */
187static const struct ieee80211_rateset iwi_rateset_11a =
188	{ 8, { 12, 18, 24, 36, 48, 72, 96, 108 } };
189
190static const struct ieee80211_rateset iwi_rateset_11b =
191	{ 4, { 2, 4, 11, 22 } };
192
193static const struct ieee80211_rateset iwi_rateset_11g =
194	{ 12, { 2, 4, 11, 22, 12, 18, 24, 36, 48, 72, 96, 108 } };
195
196static __inline uint8_t
197MEM_READ_1(struct iwi_softc *sc, uint32_t addr)
198{
199	CSR_WRITE_4(sc, IWI_CSR_INDIRECT_ADDR, addr);
200	return CSR_READ_1(sc, IWI_CSR_INDIRECT_DATA);
201}
202
203static __inline uint32_t
204MEM_READ_4(struct iwi_softc *sc, uint32_t addr)
205{
206	CSR_WRITE_4(sc, IWI_CSR_INDIRECT_ADDR, addr);
207	return CSR_READ_4(sc, IWI_CSR_INDIRECT_DATA);
208}
209
210static int
211iwi_probe(device_t dev)
212{
213	const struct iwi_ident *ident;
214
215	for (ident = iwi_ident_table; ident->name != NULL; ident++) {
216		if (pci_get_vendor(dev) == ident->vendor &&
217		    pci_get_device(dev) == ident->device) {
218			device_set_desc(dev, ident->name);
219			return 0;
220		}
221	}
222	return ENXIO;
223}
224
225/* Base Address Register */
226#define IWI_PCI_BAR0	0x10
227
228static int
229iwi_attach(device_t dev)
230{
231	struct iwi_softc *sc = device_get_softc(dev);
232	struct ifnet *ifp;
233	struct ieee80211com *ic = &sc->sc_ic;
234	uint16_t val;
235	int error, i;
236
237	sc->sc_dev = dev;
238
239	mtx_init(&sc->sc_mtx, device_get_nameunit(dev), MTX_NETWORK_LOCK,
240	    MTX_DEF | MTX_RECURSE);
241
242	sc->sc_unr = new_unrhdr(0, IWI_MAX_IBSSNODE, &sc->sc_mtx);
243
244	if (pci_get_powerstate(dev) != PCI_POWERSTATE_D0) {
245		device_printf(dev, "chip is in D%d power mode "
246		    "-- setting to D0\n", pci_get_powerstate(dev));
247		pci_set_powerstate(dev, PCI_POWERSTATE_D0);
248	}
249
250	pci_write_config(dev, 0x41, 0, 1);
251
252	/* enable bus-mastering */
253	pci_enable_busmaster(dev);
254
255	sc->mem_rid = IWI_PCI_BAR0;
256	sc->mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &sc->mem_rid,
257	    RF_ACTIVE);
258	if (sc->mem == NULL) {
259		device_printf(dev, "could not allocate memory resource\n");
260		goto fail;
261	}
262
263	sc->sc_st = rman_get_bustag(sc->mem);
264	sc->sc_sh = rman_get_bushandle(sc->mem);
265
266	sc->irq_rid = 0;
267	sc->irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &sc->irq_rid,
268	    RF_ACTIVE | RF_SHAREABLE);
269	if (sc->irq == NULL) {
270		device_printf(dev, "could not allocate interrupt resource\n");
271		goto fail;
272	}
273
274	if (iwi_reset(sc) != 0) {
275		device_printf(dev, "could not reset adapter\n");
276		goto fail;
277	}
278
279	/*
280	 * Allocate rings.
281	 */
282	if (iwi_alloc_cmd_ring(sc, &sc->cmdq, IWI_CMD_RING_COUNT) != 0) {
283		device_printf(dev, "could not allocate Cmd ring\n");
284		goto fail;
285	}
286
287	error = iwi_alloc_tx_ring(sc, &sc->txq[0], IWI_TX_RING_COUNT,
288	    IWI_CSR_TX1_RIDX, IWI_CSR_TX1_WIDX);
289	if (error != 0) {
290		device_printf(dev, "could not allocate Tx ring 1\n");
291		goto fail;
292	}
293
294	error = iwi_alloc_tx_ring(sc, &sc->txq[1], IWI_TX_RING_COUNT,
295	    IWI_CSR_TX2_RIDX, IWI_CSR_TX2_WIDX);
296	if (error != 0) {
297		device_printf(dev, "could not allocate Tx ring 2\n");
298		goto fail;
299	}
300
301	error = iwi_alloc_tx_ring(sc, &sc->txq[2], IWI_TX_RING_COUNT,
302	    IWI_CSR_TX3_RIDX, IWI_CSR_TX3_WIDX);
303	if (error != 0) {
304		device_printf(dev, "could not allocate Tx ring 3\n");
305		goto fail;
306	}
307
308	error = iwi_alloc_tx_ring(sc, &sc->txq[3], IWI_TX_RING_COUNT,
309	    IWI_CSR_TX4_RIDX, IWI_CSR_TX4_WIDX);
310	if (error != 0) {
311		device_printf(dev, "could not allocate Tx ring 4\n");
312		goto fail;
313	}
314
315	if (iwi_alloc_rx_ring(sc, &sc->rxq, IWI_RX_RING_COUNT) != 0) {
316		device_printf(dev, "could not allocate Rx ring\n");
317		goto fail;
318	}
319
320	ifp = sc->sc_ifp = if_alloc(IFT_ETHER);
321	if (ifp == NULL) {
322		device_printf(dev, "can not if_alloc()\n");
323		goto fail;
324	}
325	ifp->if_softc = sc;
326	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
327	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
328	ifp->if_init = iwi_init;
329	ifp->if_ioctl = iwi_ioctl;
330	ifp->if_start = iwi_start;
331	ifp->if_watchdog = iwi_watchdog;
332	IFQ_SET_MAXLEN(&ifp->if_snd, IFQ_MAXLEN);
333	ifp->if_snd.ifq_drv_maxlen = IFQ_MAXLEN;
334	IFQ_SET_READY(&ifp->if_snd);
335
336	ic->ic_ifp = ifp;
337	ic->ic_wme.wme_update = iwi_wme_update;
338	ic->ic_phytype = IEEE80211_T_OFDM; /* not only, but not used */
339	ic->ic_opmode = IEEE80211_M_STA; /* default to BSS mode */
340	ic->ic_state = IEEE80211_S_INIT;
341
342	/* set device capabilities */
343	ic->ic_caps =
344	    IEEE80211_C_IBSS |		/* IBSS mode supported */
345	    IEEE80211_C_MONITOR |	/* monitor mode supported */
346	    IEEE80211_C_TXPMGT |	/* tx power management */
347	    IEEE80211_C_SHPREAMBLE |	/* short preamble supported */
348	    IEEE80211_C_WPA |		/* 802.11i */
349	    IEEE80211_C_WME;		/* 802.11e */
350
351	/* read MAC address from EEPROM */
352	val = iwi_read_prom_word(sc, IWI_EEPROM_MAC + 0);
353	ic->ic_myaddr[0] = val & 0xff;
354	ic->ic_myaddr[1] = val >> 8;
355	val = iwi_read_prom_word(sc, IWI_EEPROM_MAC + 1);
356	ic->ic_myaddr[2] = val & 0xff;
357	ic->ic_myaddr[3] = val >> 8;
358	val = iwi_read_prom_word(sc, IWI_EEPROM_MAC + 2);
359	ic->ic_myaddr[4] = val & 0xff;
360	ic->ic_myaddr[5] = val >> 8;
361
362	if (pci_get_device(dev) >= 0x4223) {
363		/* set supported .11a rates (2915ABG only) */
364		ic->ic_sup_rates[IEEE80211_MODE_11A] = iwi_rateset_11a;
365
366		/* set supported .11a channels */
367		for (i = 36; i <= 64; i += 4) {
368			ic->ic_channels[i].ic_freq =
369			    ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
370			ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
371		}
372		for (i = 149; i <= 165; i += 4) {
373			ic->ic_channels[i].ic_freq =
374			    ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
375			ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
376		}
377	}
378
379	/* set supported .11b and .11g rates */
380	ic->ic_sup_rates[IEEE80211_MODE_11B] = iwi_rateset_11b;
381	ic->ic_sup_rates[IEEE80211_MODE_11G] = iwi_rateset_11g;
382
383	/* set supported .11b and .11g channels (1 through 14) */
384	for (i = 1; i <= 14; i++) {
385		ic->ic_channels[i].ic_freq =
386		    ieee80211_ieee2mhz(i, IEEE80211_CHAN_2GHZ);
387		ic->ic_channels[i].ic_flags =
388		    IEEE80211_CHAN_CCK | IEEE80211_CHAN_OFDM |
389		    IEEE80211_CHAN_DYN | IEEE80211_CHAN_2GHZ;
390	}
391
392	ieee80211_ifattach(ic);
393	/* override default methods */
394	ic->ic_node_alloc = iwi_node_alloc;
395	sc->sc_node_free = ic->ic_node_free;
396	ic->ic_node_free = iwi_node_free;
397	/* override state transition machine */
398	sc->sc_newstate = ic->ic_newstate;
399	ic->ic_newstate = iwi_newstate;
400	ieee80211_media_init(ic, iwi_media_change, iwi_media_status);
401
402	bpfattach2(ifp, DLT_IEEE802_11_RADIO,
403	    sizeof (struct ieee80211_frame) + 64, &sc->sc_drvbpf);
404
405	sc->sc_rxtap_len = sizeof sc->sc_rxtapu;
406	sc->sc_rxtap.wr_ihdr.it_len = htole16(sc->sc_rxtap_len);
407	sc->sc_rxtap.wr_ihdr.it_present = htole32(IWI_RX_RADIOTAP_PRESENT);
408
409	sc->sc_txtap_len = sizeof sc->sc_txtapu;
410	sc->sc_txtap.wt_ihdr.it_len = htole16(sc->sc_txtap_len);
411	sc->sc_txtap.wt_ihdr.it_present = htole32(IWI_TX_RADIOTAP_PRESENT);
412
413	/*
414	 * Add a few sysctl knobs.
415	 */
416	sc->dwelltime = 100;
417	sc->bluetooth = 1;
418	sc->antenna = 0;
419
420	SYSCTL_ADD_PROC(device_get_sysctl_ctx(dev),
421	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO, "radio",
422	    CTLTYPE_INT | CTLFLAG_RD, sc, 0, iwi_sysctl_radio, "I",
423	    "radio transmitter switch state (0=off, 1=on)");
424
425	SYSCTL_ADD_PROC(device_get_sysctl_ctx(dev),
426	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO, "stats",
427	    CTLTYPE_OPAQUE | CTLFLAG_RD, sc, 0, iwi_sysctl_stats, "S",
428	    "statistics");
429
430	SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
431	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO, "dwell",
432	    CTLFLAG_RW, &sc->dwelltime, 0,
433	    "channel dwell time (ms) for AP/station scanning");
434
435	SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
436	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO, "bluetooth",
437	    CTLFLAG_RW, &sc->bluetooth, 0, "bluetooth coexistence");
438
439	SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
440	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO, "antenna",
441	    CTLFLAG_RW, &sc->antenna, 0, "antenna (0=auto)");
442
443	/*
444	 * Hook our interrupt after all initialization is complete.
445	 */
446	error = bus_setup_intr(dev, sc->irq, INTR_TYPE_NET | INTR_MPSAFE,
447	    iwi_intr, sc, &sc->sc_ih);
448	if (error != 0) {
449		device_printf(dev, "could not set up interrupt\n");
450		goto fail;
451	}
452
453	if (bootverbose)
454		ieee80211_announce(ic);
455
456	return 0;
457
458fail:	iwi_detach(dev);
459	return ENXIO;
460}
461
462static int
463iwi_detach(device_t dev)
464{
465	struct iwi_softc *sc = device_get_softc(dev);
466	struct ieee80211com *ic = &sc->sc_ic;
467	struct ifnet *ifp = ic->ic_ifp;
468
469	iwi_stop(sc);
470
471	iwi_free_firmware(sc);
472
473	if (ifp != NULL) {
474		bpfdetach(ifp);
475		ieee80211_ifdetach(ic);
476	}
477
478	iwi_free_cmd_ring(sc, &sc->cmdq);
479	iwi_free_tx_ring(sc, &sc->txq[0]);
480	iwi_free_tx_ring(sc, &sc->txq[1]);
481	iwi_free_tx_ring(sc, &sc->txq[2]);
482	iwi_free_tx_ring(sc, &sc->txq[3]);
483	iwi_free_rx_ring(sc, &sc->rxq);
484
485	if (sc->irq != NULL) {
486		bus_teardown_intr(dev, sc->irq, sc->sc_ih);
487		bus_release_resource(dev, SYS_RES_IRQ, sc->irq_rid, sc->irq);
488	}
489
490	if (sc->mem != NULL)
491		bus_release_resource(dev, SYS_RES_MEMORY, sc->mem_rid, sc->mem);
492
493	if (ifp != NULL)
494		if_free(ifp);
495
496	if (sc->sc_unr != NULL)
497		delete_unrhdr(sc->sc_unr);
498
499	mtx_destroy(&sc->sc_mtx);
500
501	return 0;
502}
503
504static void
505iwi_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
506{
507	if (error != 0)
508		return;
509
510	KASSERT(nseg == 1, ("too many DMA segments, %d should be 1", nseg));
511
512	*(bus_addr_t *)arg = segs[0].ds_addr;
513}
514
515static int
516iwi_alloc_cmd_ring(struct iwi_softc *sc, struct iwi_cmd_ring *ring, int count)
517{
518	int error;
519
520	ring->count = count;
521	ring->queued = 0;
522	ring->cur = ring->next = 0;
523
524	error = bus_dma_tag_create(NULL, 4, 0, BUS_SPACE_MAXADDR_32BIT,
525	    BUS_SPACE_MAXADDR, NULL, NULL, count * IWI_CMD_DESC_SIZE, 1,
526	    count * IWI_CMD_DESC_SIZE, 0, NULL, NULL, &ring->desc_dmat);
527	if (error != 0) {
528		device_printf(sc->sc_dev, "could not create desc DMA tag\n");
529		goto fail;
530	}
531
532	error = bus_dmamem_alloc(ring->desc_dmat, (void **)&ring->desc,
533	    BUS_DMA_NOWAIT | BUS_DMA_ZERO, &ring->desc_map);
534	if (error != 0) {
535		device_printf(sc->sc_dev, "could not allocate DMA memory\n");
536		goto fail;
537	}
538
539	error = bus_dmamap_load(ring->desc_dmat, ring->desc_map, ring->desc,
540	    count * IWI_CMD_DESC_SIZE, iwi_dma_map_addr, &ring->physaddr, 0);
541	if (error != 0) {
542		device_printf(sc->sc_dev, "could not load desc DMA map\n");
543		goto fail;
544	}
545
546	return 0;
547
548fail:	iwi_free_cmd_ring(sc, ring);
549	return error;
550}
551
552static void
553iwi_reset_cmd_ring(struct iwi_softc *sc, struct iwi_cmd_ring *ring)
554{
555	ring->queued = 0;
556	ring->cur = ring->next = 0;
557}
558
559static void
560iwi_free_cmd_ring(struct iwi_softc *sc, struct iwi_cmd_ring *ring)
561{
562	if (ring->desc != NULL) {
563		bus_dmamap_sync(ring->desc_dmat, ring->desc_map,
564		    BUS_DMASYNC_POSTWRITE);
565		bus_dmamap_unload(ring->desc_dmat, ring->desc_map);
566		bus_dmamem_free(ring->desc_dmat, ring->desc, ring->desc_map);
567	}
568
569	if (ring->desc_dmat != NULL)
570		bus_dma_tag_destroy(ring->desc_dmat);
571}
572
573static int
574iwi_alloc_tx_ring(struct iwi_softc *sc, struct iwi_tx_ring *ring, int count,
575    bus_addr_t csr_ridx, bus_addr_t csr_widx)
576{
577	int i, error;
578
579	ring->count = count;
580	ring->queued = 0;
581	ring->cur = ring->next = 0;
582	ring->csr_ridx = csr_ridx;
583	ring->csr_widx = csr_widx;
584
585	error = bus_dma_tag_create(NULL, 4, 0, BUS_SPACE_MAXADDR_32BIT,
586	    BUS_SPACE_MAXADDR, NULL, NULL, count * IWI_TX_DESC_SIZE, 1,
587	    count * IWI_TX_DESC_SIZE, 0, NULL, NULL, &ring->desc_dmat);
588	if (error != 0) {
589		device_printf(sc->sc_dev, "could not create desc DMA tag\n");
590		goto fail;
591	}
592
593	error = bus_dmamem_alloc(ring->desc_dmat, (void **)&ring->desc,
594	    BUS_DMA_NOWAIT | BUS_DMA_ZERO, &ring->desc_map);
595	if (error != 0) {
596		device_printf(sc->sc_dev, "could not allocate DMA memory\n");
597		goto fail;
598	}
599
600	error = bus_dmamap_load(ring->desc_dmat, ring->desc_map, ring->desc,
601	    count * IWI_TX_DESC_SIZE, iwi_dma_map_addr, &ring->physaddr, 0);
602	if (error != 0) {
603		device_printf(sc->sc_dev, "could not load desc DMA map\n");
604		goto fail;
605	}
606
607	ring->data = malloc(count * sizeof (struct iwi_tx_data), M_DEVBUF,
608	    M_NOWAIT | M_ZERO);
609	if (ring->data == NULL) {
610		device_printf(sc->sc_dev, "could not allocate soft data\n");
611		error = ENOMEM;
612		goto fail;
613	}
614
615	error = bus_dma_tag_create(NULL, 1, 0, BUS_SPACE_MAXADDR_32BIT,
616	    BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES, 1, MCLBYTES, 0, NULL,
617	    NULL, &ring->data_dmat);
618	if (error != 0) {
619		device_printf(sc->sc_dev, "could not create data DMA tag\n");
620		goto fail;
621	}
622
623	for (i = 0; i < count; i++) {
624		error = bus_dmamap_create(ring->data_dmat, 0,
625		    &ring->data[i].map);
626		if (error != 0) {
627			device_printf(sc->sc_dev, "could not create DMA map\n");
628			goto fail;
629		}
630	}
631
632	return 0;
633
634fail:	iwi_free_tx_ring(sc, ring);
635	return error;
636}
637
638static void
639iwi_reset_tx_ring(struct iwi_softc *sc, struct iwi_tx_ring *ring)
640{
641	struct iwi_tx_data *data;
642	int i;
643
644	for (i = 0; i < ring->count; i++) {
645		data = &ring->data[i];
646
647		if (data->m != NULL) {
648			bus_dmamap_sync(ring->data_dmat, data->map,
649			    BUS_DMASYNC_POSTWRITE);
650			bus_dmamap_unload(ring->data_dmat, data->map);
651			m_freem(data->m);
652			data->m = NULL;
653		}
654
655		if (data->ni != NULL) {
656			ieee80211_free_node(data->ni);
657			data->ni = NULL;
658		}
659	}
660
661	ring->queued = 0;
662	ring->cur = ring->next = 0;
663}
664
665static void
666iwi_free_tx_ring(struct iwi_softc *sc, struct iwi_tx_ring *ring)
667{
668	struct iwi_tx_data *data;
669	int i;
670
671	if (ring->desc != NULL) {
672		bus_dmamap_sync(ring->desc_dmat, ring->desc_map,
673		    BUS_DMASYNC_POSTWRITE);
674		bus_dmamap_unload(ring->desc_dmat, ring->desc_map);
675		bus_dmamem_free(ring->desc_dmat, ring->desc, ring->desc_map);
676	}
677
678	if (ring->desc_dmat != NULL)
679		bus_dma_tag_destroy(ring->desc_dmat);
680
681	if (ring->data != NULL) {
682		for (i = 0; i < ring->count; i++) {
683			data = &ring->data[i];
684
685			if (data->m != NULL) {
686				bus_dmamap_sync(ring->data_dmat, data->map,
687				    BUS_DMASYNC_POSTWRITE);
688				bus_dmamap_unload(ring->data_dmat, data->map);
689				m_freem(data->m);
690			}
691
692			if (data->ni != NULL)
693				ieee80211_free_node(data->ni);
694
695			if (data->map != NULL)
696				bus_dmamap_destroy(ring->data_dmat, data->map);
697		}
698
699		free(ring->data, M_DEVBUF);
700	}
701
702	if (ring->data_dmat != NULL)
703		bus_dma_tag_destroy(ring->data_dmat);
704}
705
706static int
707iwi_alloc_rx_ring(struct iwi_softc *sc, struct iwi_rx_ring *ring, int count)
708{
709	struct iwi_rx_data *data;
710	int i, error;
711
712	ring->count = count;
713	ring->cur = 0;
714
715	ring->data = malloc(count * sizeof (struct iwi_rx_data), M_DEVBUF,
716	    M_NOWAIT | M_ZERO);
717	if (ring->data == NULL) {
718		device_printf(sc->sc_dev, "could not allocate soft data\n");
719		error = ENOMEM;
720		goto fail;
721	}
722
723	error = bus_dma_tag_create(NULL, 1, 0, BUS_SPACE_MAXADDR_32BIT,
724	    BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES, 1, MCLBYTES, 0, NULL,
725	    NULL, &ring->data_dmat);
726	if (error != 0) {
727		device_printf(sc->sc_dev, "could not create data DMA tag\n");
728		goto fail;
729	}
730
731	for (i = 0; i < count; i++) {
732		data = &ring->data[i];
733
734		error = bus_dmamap_create(ring->data_dmat, 0, &data->map);
735		if (error != 0) {
736			device_printf(sc->sc_dev, "could not create DMA map\n");
737			goto fail;
738		}
739
740		data->m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
741		if (data->m == NULL) {
742			device_printf(sc->sc_dev,
743			    "could not allocate rx mbuf\n");
744			error = ENOMEM;
745			goto fail;
746		}
747
748		error = bus_dmamap_load(ring->data_dmat, data->map,
749		    mtod(data->m, void *), MCLBYTES, iwi_dma_map_addr,
750		    &data->physaddr, 0);
751		if (error != 0) {
752			device_printf(sc->sc_dev,
753			    "could not load rx buf DMA map");
754			goto fail;
755		}
756
757		data->reg = IWI_CSR_RX_BASE + i * 4;
758	}
759
760	return 0;
761
762fail:	iwi_free_rx_ring(sc, ring);
763	return error;
764}
765
766static void
767iwi_reset_rx_ring(struct iwi_softc *sc, struct iwi_rx_ring *ring)
768{
769	ring->cur = 0;
770}
771
772static void
773iwi_free_rx_ring(struct iwi_softc *sc, struct iwi_rx_ring *ring)
774{
775	struct iwi_rx_data *data;
776	int i;
777
778	if (ring->data != NULL) {
779		for (i = 0; i < ring->count; i++) {
780			data = &ring->data[i];
781
782			if (data->m != NULL) {
783				bus_dmamap_sync(ring->data_dmat, data->map,
784				    BUS_DMASYNC_POSTREAD);
785				bus_dmamap_unload(ring->data_dmat, data->map);
786				m_freem(data->m);
787			}
788
789			if (data->map != NULL)
790				bus_dmamap_destroy(ring->data_dmat, data->map);
791		}
792
793		free(ring->data, M_DEVBUF);
794	}
795
796	if (ring->data_dmat != NULL)
797		bus_dma_tag_destroy(ring->data_dmat);
798}
799
800static int
801iwi_shutdown(device_t dev)
802{
803	struct iwi_softc *sc = device_get_softc(dev);
804
805	iwi_stop(sc);
806
807	return 0;
808}
809
810static int
811iwi_suspend(device_t dev)
812{
813	struct iwi_softc *sc = device_get_softc(dev);
814
815	iwi_stop(sc);
816
817	return 0;
818}
819
820static int
821iwi_resume(device_t dev)
822{
823	struct iwi_softc *sc = device_get_softc(dev);
824	struct ifnet *ifp = sc->sc_ic.ic_ifp;
825
826	IWI_LOCK(sc);
827
828	pci_write_config(dev, 0x41, 0, 1);
829
830	if (ifp->if_flags & IFF_UP) {
831		ifp->if_init(ifp->if_softc);
832		if (ifp->if_drv_flags & IFF_DRV_RUNNING)
833			ifp->if_start(ifp);
834	}
835
836	IWI_UNLOCK(sc);
837
838	return 0;
839}
840
841static struct ieee80211_node *
842iwi_node_alloc(struct ieee80211_node_table *nt)
843{
844	struct iwi_node *in;
845
846	in = malloc(sizeof (struct iwi_node), M_80211_NODE, M_NOWAIT | M_ZERO);
847	if (in == NULL)
848		return NULL;
849
850	in->in_station = -1;
851
852	return &in->in_node;
853}
854
855static void
856iwi_node_free(struct ieee80211_node *ni)
857{
858	struct ieee80211com *ic = ni->ni_ic;
859	struct iwi_softc *sc = ic->ic_ifp->if_softc;
860	struct iwi_node *in = (struct iwi_node *)ni;
861
862	if (in->in_station != -1)
863		free_unr(sc->sc_unr, in->in_station);
864
865	sc->sc_node_free(ni);
866}
867
868static int
869iwi_media_change(struct ifnet *ifp)
870{
871	struct iwi_softc *sc = ifp->if_softc;
872	int error;
873
874	IWI_LOCK(sc);
875
876	error = ieee80211_media_change(ifp);
877	if (error != ENETRESET) {
878		IWI_UNLOCK(sc);
879		return error;
880	}
881
882	if ((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags & IFF_DRV_RUNNING))
883		iwi_init(sc);
884
885	IWI_UNLOCK(sc);
886
887	return 0;
888}
889
890/*
891 * The firmware automatically adapts the transmit speed.  We report its current
892 * value here.
893 */
894static void
895iwi_media_status(struct ifnet *ifp, struct ifmediareq *imr)
896{
897	struct iwi_softc *sc = ifp->if_softc;
898	struct ieee80211com *ic = &sc->sc_ic;
899#define N(a)	(sizeof (a) / sizeof (a[0]))
900	static const struct {
901		uint32_t	val;
902		int		rate;
903	} rates[] = {
904		{ IWI_RATE_DS1,      2 },
905		{ IWI_RATE_DS2,      4 },
906		{ IWI_RATE_DS5,     11 },
907		{ IWI_RATE_DS11,    22 },
908		{ IWI_RATE_OFDM6,   12 },
909		{ IWI_RATE_OFDM9,   18 },
910		{ IWI_RATE_OFDM12,  24 },
911		{ IWI_RATE_OFDM18,  36 },
912		{ IWI_RATE_OFDM24,  48 },
913		{ IWI_RATE_OFDM36,  72 },
914		{ IWI_RATE_OFDM48,  96 },
915		{ IWI_RATE_OFDM54, 108 },
916	};
917	uint32_t val;
918	int rate, i;
919
920	imr->ifm_status = IFM_AVALID;
921	imr->ifm_active = IFM_IEEE80211;
922	if (ic->ic_state == IEEE80211_S_RUN)
923		imr->ifm_status |= IFM_ACTIVE;
924
925	/* read current transmission rate from adapter */
926	val = CSR_READ_4(sc, IWI_CSR_CURRENT_TX_RATE);
927
928	/* convert rate to 802.11 rate */
929	for (i = 0; i < N(rates) && rates[i].val != val; i++);
930	rate = (i < N(rates)) ? rates[i].rate : 0;
931
932	imr->ifm_active |= ieee80211_rate2media(ic, rate, ic->ic_curmode);
933	switch (ic->ic_opmode) {
934	case IEEE80211_M_STA:
935		break;
936
937	case IEEE80211_M_IBSS:
938		imr->ifm_active |= IFM_IEEE80211_ADHOC;
939		break;
940
941	case IEEE80211_M_MONITOR:
942		imr->ifm_active |= IFM_IEEE80211_MONITOR;
943		break;
944
945	case IEEE80211_M_AHDEMO:
946	case IEEE80211_M_HOSTAP:
947		/* should not get there */
948		break;
949	}
950#undef N
951}
952
953static int
954iwi_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
955{
956	struct ifnet *ifp = ic->ic_ifp;
957	struct iwi_softc *sc = ifp->if_softc;
958
959	switch (nstate) {
960	case IEEE80211_S_SCAN:
961		if (sc->flags & IWI_FLAG_SCANNING)
962			break;
963
964		ieee80211_node_table_reset(&ic->ic_scan);
965		ic->ic_flags |= IEEE80211_F_SCAN | IEEE80211_F_ASCAN;
966		sc->flags |= IWI_FLAG_SCANNING;
967		iwi_scan(sc);
968		break;
969
970	case IEEE80211_S_AUTH:
971		iwi_auth_and_assoc(sc);
972		break;
973
974	case IEEE80211_S_RUN:
975		if (ic->ic_opmode == IEEE80211_M_IBSS)
976			ieee80211_new_state(ic, IEEE80211_S_AUTH, -1);
977		else if (ic->ic_opmode == IEEE80211_M_MONITOR)
978			iwi_set_chan(sc, ic->ic_ibss_chan);
979
980		return sc->sc_newstate(ic, nstate,
981		    IEEE80211_FC0_SUBTYPE_ASSOC_RESP);
982
983	case IEEE80211_S_ASSOC:
984		break;
985
986	case IEEE80211_S_INIT:
987		sc->flags &= ~IWI_FLAG_SCANNING;
988		break;
989	}
990
991	ic->ic_state = nstate;
992	return 0;
993}
994
995/*
996 * WME parameters coming from IEEE 802.11e specification.  These values are
997 * already declared in ieee80211_proto.c, but they are static so they can't
998 * be reused here.
999 */
1000static const struct wmeParams iwi_wme_cck_params[WME_NUM_AC] = {
1001	{ 0, 3, 5,  7,   0 },	/* WME_AC_BE */
1002	{ 0, 3, 5, 10,   0 },	/* WME_AC_BK */
1003	{ 0, 2, 4,  5, 188 },	/* WME_AC_VI */
1004	{ 0, 2, 3,  4, 102 }	/* WME_AC_VO */
1005};
1006
1007static const struct wmeParams iwi_wme_ofdm_params[WME_NUM_AC] = {
1008	{ 0, 3, 4,  6,   0 },	/* WME_AC_BE */
1009	{ 0, 3, 4, 10,   0 },	/* WME_AC_BK */
1010	{ 0, 2, 3,  4,  94 },	/* WME_AC_VI */
1011	{ 0, 2, 2,  3,  47 }	/* WME_AC_VO */
1012};
1013
1014static int
1015iwi_wme_update(struct ieee80211com *ic)
1016{
1017#define IWI_EXP2(v)	htole16((1 << (v)) - 1)
1018#define IWI_USEC(v)	htole16(IEEE80211_TXOP_TO_US(v))
1019	struct iwi_softc *sc = ic->ic_ifp->if_softc;
1020	struct iwi_wme_params wme[3];
1021	const struct wmeParams *wmep;
1022	int ac;
1023
1024	/*
1025	 * We shall not override firmware default WME values if WME is not
1026	 * actually enabled.
1027	 */
1028	if (!(ic->ic_flags & IEEE80211_F_WME))
1029		return 0;
1030
1031	for (ac = 0; ac < WME_NUM_AC; ac++) {
1032		/* set WME values for current operating mode */
1033		wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
1034		wme[0].aifsn[ac] = wmep->wmep_aifsn;
1035		wme[0].cwmin[ac] = IWI_EXP2(wmep->wmep_logcwmin);
1036		wme[0].cwmax[ac] = IWI_EXP2(wmep->wmep_logcwmax);
1037		wme[0].burst[ac] = IWI_USEC(wmep->wmep_txopLimit);
1038		wme[0].acm[ac]   = wmep->wmep_acm;
1039
1040		/* set WME values for CCK modulation */
1041		wmep = &iwi_wme_cck_params[ac];
1042		wme[1].aifsn[ac] = wmep->wmep_aifsn;
1043		wme[1].cwmin[ac] = IWI_EXP2(wmep->wmep_logcwmin);
1044		wme[1].cwmax[ac] = IWI_EXP2(wmep->wmep_logcwmax);
1045		wme[1].burst[ac] = IWI_USEC(wmep->wmep_txopLimit);
1046		wme[1].acm[ac]   = wmep->wmep_acm;
1047
1048		/* set WME values for OFDM modulation */
1049		wmep = &iwi_wme_ofdm_params[ac];
1050		wme[2].aifsn[ac] = wmep->wmep_aifsn;
1051		wme[2].cwmin[ac] = IWI_EXP2(wmep->wmep_logcwmin);
1052		wme[2].cwmax[ac] = IWI_EXP2(wmep->wmep_logcwmax);
1053		wme[2].burst[ac] = IWI_USEC(wmep->wmep_txopLimit);
1054		wme[2].acm[ac]   = wmep->wmep_acm;
1055	}
1056
1057	DPRINTF(("Setting WME parameters\n"));
1058	return iwi_cmd(sc, IWI_CMD_SET_WME_PARAMS, wme, sizeof wme, 1);
1059#undef IWI_USEC
1060#undef IWI_EXP2
1061}
1062
1063/*
1064 * Read 16 bits at address 'addr' from the serial EEPROM.
1065 */
1066static uint16_t
1067iwi_read_prom_word(struct iwi_softc *sc, uint8_t addr)
1068{
1069	uint32_t tmp;
1070	uint16_t val;
1071	int n;
1072
1073	/* clock C once before the first command */
1074	IWI_EEPROM_CTL(sc, 0);
1075	IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1076	IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_C);
1077	IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1078
1079	/* write start bit (1) */
1080	IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_D);
1081	IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_D | IWI_EEPROM_C);
1082
1083	/* write READ opcode (10) */
1084	IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_D);
1085	IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_D | IWI_EEPROM_C);
1086	IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1087	IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_C);
1088
1089	/* write address A7-A0 */
1090	for (n = 7; n >= 0; n--) {
1091		IWI_EEPROM_CTL(sc, IWI_EEPROM_S |
1092		    (((addr >> n) & 1) << IWI_EEPROM_SHIFT_D));
1093		IWI_EEPROM_CTL(sc, IWI_EEPROM_S |
1094		    (((addr >> n) & 1) << IWI_EEPROM_SHIFT_D) | IWI_EEPROM_C);
1095	}
1096
1097	IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1098
1099	/* read data Q15-Q0 */
1100	val = 0;
1101	for (n = 15; n >= 0; n--) {
1102		IWI_EEPROM_CTL(sc, IWI_EEPROM_S | IWI_EEPROM_C);
1103		IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1104		tmp = MEM_READ_4(sc, IWI_MEM_EEPROM_CTL);
1105		val |= ((tmp & IWI_EEPROM_Q) >> IWI_EEPROM_SHIFT_Q) << n;
1106	}
1107
1108	IWI_EEPROM_CTL(sc, 0);
1109
1110	/* clear Chip Select and clock C */
1111	IWI_EEPROM_CTL(sc, IWI_EEPROM_S);
1112	IWI_EEPROM_CTL(sc, 0);
1113	IWI_EEPROM_CTL(sc, IWI_EEPROM_C);
1114
1115	return val;
1116}
1117
1118/*
1119 * XXX: Hack to set the current channel to the value advertised in beacons or
1120 * probe responses. Only used during AP detection.
1121 */
1122static void
1123iwi_fix_channel(struct ieee80211com *ic, struct mbuf *m)
1124{
1125	struct ieee80211_frame *wh;
1126	uint8_t subtype;
1127	uint8_t *frm, *efrm;
1128
1129	wh = mtod(m, struct ieee80211_frame *);
1130
1131	if ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) != IEEE80211_FC0_TYPE_MGT)
1132		return;
1133
1134	subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
1135
1136	if (subtype != IEEE80211_FC0_SUBTYPE_BEACON &&
1137	    subtype != IEEE80211_FC0_SUBTYPE_PROBE_RESP)
1138		return;
1139
1140	frm = (uint8_t *)(wh + 1);
1141	efrm = mtod(m, uint8_t *) + m->m_len;
1142
1143	frm += 12;	/* skip tstamp, bintval and capinfo fields */
1144	while (frm < efrm) {
1145		if (*frm == IEEE80211_ELEMID_DSPARMS)
1146#if IEEE80211_CHAN_MAX < 255
1147		if (frm[2] <= IEEE80211_CHAN_MAX)
1148#endif
1149			ic->ic_curchan = &ic->ic_channels[frm[2]];
1150
1151		frm += frm[1] + 2;
1152	}
1153}
1154
1155static void
1156iwi_frame_intr(struct iwi_softc *sc, struct iwi_rx_data *data, int i,
1157    struct iwi_frame *frame)
1158{
1159	struct ieee80211com *ic = &sc->sc_ic;
1160	struct ifnet *ifp = ic->ic_ifp;
1161	struct mbuf *mnew, *m;
1162	struct ieee80211_frame *wh;
1163	struct ieee80211_node *ni;
1164	int error;
1165
1166	DPRINTFN(5, ("received frame len=%u chan=%u rssi=%u\n",
1167	    le16toh(frame->len), frame->chan, frame->rssi_dbm));
1168
1169	if (le16toh(frame->len) < sizeof (struct ieee80211_frame))
1170		return;
1171
1172	/*
1173	 * Try to allocate a new mbuf for this ring element and load it before
1174	 * processing the current mbuf. If the ring element cannot be loaded,
1175	 * drop the received packet and reuse the old mbuf. In the unlikely
1176	 * case that the old mbuf can't be reloaded either, explicitly panic.
1177	 */
1178	mnew = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
1179	if (mnew == NULL) {
1180		ifp->if_ierrors++;
1181		return;
1182	}
1183
1184	bus_dmamap_unload(sc->rxq.data_dmat, data->map);
1185
1186	error = bus_dmamap_load(sc->rxq.data_dmat, data->map,
1187	    mtod(mnew, void *), MCLBYTES, iwi_dma_map_addr, &data->physaddr,
1188	    0);
1189	if (error != 0) {
1190		m_freem(mnew);
1191
1192		/* try to reload the old mbuf */
1193		error = bus_dmamap_load(sc->rxq.data_dmat, data->map,
1194		    mtod(data->m, void *), MCLBYTES, iwi_dma_map_addr,
1195		    &data->physaddr, 0);
1196		if (error != 0) {
1197			/* very unlikely that it will fail... */
1198			panic("%s: could not load old rx mbuf",
1199			    device_get_name(sc->sc_dev));
1200		}
1201		ifp->if_ierrors++;
1202		return;
1203	}
1204
1205	/*
1206	 * New mbuf successfully loaded, update Rx ring and continue
1207	 * processing.
1208	 */
1209	m = data->m;
1210	data->m = mnew;
1211	CSR_WRITE_4(sc, data->reg, data->physaddr);
1212
1213	/* finalize mbuf */
1214	m->m_pkthdr.rcvif = ifp;
1215	m->m_pkthdr.len = m->m_len = sizeof (struct iwi_hdr) +
1216	    sizeof (struct iwi_frame) + le16toh(frame->len);
1217
1218	m_adj(m, sizeof (struct iwi_hdr) + sizeof (struct iwi_frame));
1219
1220	if (ic->ic_state == IEEE80211_S_SCAN)
1221		iwi_fix_channel(ic, m);
1222
1223	if (sc->sc_drvbpf != NULL) {
1224		struct iwi_rx_radiotap_header *tap = &sc->sc_rxtap;
1225
1226		tap->wr_flags = 0;
1227		tap->wr_rate = frame->rate;
1228		tap->wr_chan_freq =
1229		    htole16(ic->ic_channels[frame->chan].ic_freq);
1230		tap->wr_chan_flags =
1231		    htole16(ic->ic_channels[frame->chan].ic_flags);
1232		tap->wr_antsignal = frame->signal;
1233		tap->wr_antenna = frame->antenna;
1234
1235		bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_rxtap_len, m);
1236	}
1237
1238	wh = mtod(m, struct ieee80211_frame *);
1239	ni = ieee80211_find_rxnode(ic, (struct ieee80211_frame_min *)wh);
1240
1241	/* send the frame to the 802.11 layer */
1242	ieee80211_input(ic, m, ni, frame->rssi_dbm, 0);
1243
1244	/* node is no longer needed */
1245	ieee80211_free_node(ni);
1246}
1247
1248static void
1249iwi_notification_intr(struct iwi_softc *sc, struct iwi_notif *notif)
1250{
1251	struct ieee80211com *ic = &sc->sc_ic;
1252	struct iwi_notif_scan_channel *chan;
1253	struct iwi_notif_scan_complete *scan;
1254	struct iwi_notif_authentication *auth;
1255	struct iwi_notif_association *assoc;
1256
1257	switch (notif->type) {
1258	case IWI_NOTIF_TYPE_SCAN_CHANNEL:
1259		chan = (struct iwi_notif_scan_channel *)(notif + 1);
1260
1261		DPRINTFN(2, ("Scanning channel (%u)\n", chan->nchan));
1262		break;
1263
1264	case IWI_NOTIF_TYPE_SCAN_COMPLETE:
1265		scan = (struct iwi_notif_scan_complete *)(notif + 1);
1266
1267		DPRINTFN(2, ("Scan completed (%u, %u)\n", scan->nchan,
1268		    scan->status));
1269
1270		/* monitor mode uses scan to set the channel ... */
1271		if (ic->ic_opmode != IEEE80211_M_MONITOR) {
1272			sc->flags &= ~IWI_FLAG_SCANNING;
1273			ieee80211_end_scan(ic);
1274		} else
1275			iwi_set_chan(sc, ic->ic_ibss_chan);
1276		break;
1277
1278	case IWI_NOTIF_TYPE_AUTHENTICATION:
1279		auth = (struct iwi_notif_authentication *)(notif + 1);
1280
1281		DPRINTFN(2, ("Authentication (%u)\n", auth->state));
1282
1283		switch (auth->state) {
1284		case IWI_AUTHENTICATED:
1285			ieee80211_node_authorize(ic->ic_bss);
1286			ieee80211_new_state(ic, IEEE80211_S_ASSOC, -1);
1287			break;
1288
1289		case IWI_DEAUTHENTICATED:
1290			break;
1291
1292		default:
1293			device_printf(sc->sc_dev,
1294			    "unknown authentication state %u\n", auth->state);
1295		}
1296		break;
1297
1298	case IWI_NOTIF_TYPE_ASSOCIATION:
1299		assoc = (struct iwi_notif_association *)(notif + 1);
1300
1301		DPRINTFN(2, ("Association (%u, %u)\n", assoc->state,
1302		    assoc->status));
1303
1304		switch (assoc->state) {
1305		case IWI_AUTHENTICATED:
1306			/* re-association, do nothing */
1307			break;
1308
1309		case IWI_ASSOCIATED:
1310			ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
1311			break;
1312
1313		case IWI_DEASSOCIATED:
1314			ieee80211_begin_scan(ic, 1);
1315			break;
1316
1317		default:
1318			device_printf(sc->sc_dev,
1319			    "unknown association state %u\n", assoc->state);
1320		}
1321		break;
1322
1323	case IWI_NOTIF_TYPE_CALIBRATION:
1324	case IWI_NOTIF_TYPE_BEACON:
1325	case IWI_NOTIF_TYPE_NOISE:
1326		DPRINTFN(5, ("Notification (%u)\n", notif->type));
1327		break;
1328
1329	default:
1330		device_printf(sc->sc_dev, "unknown notification type %u\n",
1331		    notif->type);
1332	}
1333}
1334
1335static void
1336iwi_rx_intr(struct iwi_softc *sc)
1337{
1338	struct iwi_rx_data *data;
1339	struct iwi_hdr *hdr;
1340	uint32_t hw;
1341
1342	hw = CSR_READ_4(sc, IWI_CSR_RX_RIDX);
1343
1344	for (; sc->rxq.cur != hw;) {
1345		data = &sc->rxq.data[sc->rxq.cur];
1346
1347		bus_dmamap_sync(sc->rxq.data_dmat, data->map,
1348		    BUS_DMASYNC_POSTREAD);
1349
1350		hdr = mtod(data->m, struct iwi_hdr *);
1351
1352		switch (hdr->type) {
1353		case IWI_HDR_TYPE_FRAME:
1354			iwi_frame_intr(sc, data, sc->rxq.cur,
1355			    (struct iwi_frame *)(hdr + 1));
1356			break;
1357
1358		case IWI_HDR_TYPE_NOTIF:
1359			iwi_notification_intr(sc,
1360			    (struct iwi_notif *)(hdr + 1));
1361			break;
1362
1363		default:
1364			device_printf(sc->sc_dev, "unknown hdr type %u\n",
1365			    hdr->type);
1366		}
1367
1368		DPRINTFN(15, ("rx done idx=%u\n", sc->rxq.cur));
1369
1370		sc->rxq.cur = (sc->rxq.cur + 1) % IWI_RX_RING_COUNT;
1371	}
1372
1373	/* tell the firmware what we have processed */
1374	hw = (hw == 0) ? IWI_RX_RING_COUNT - 1 : hw - 1;
1375	CSR_WRITE_4(sc, IWI_CSR_RX_WIDX, hw);
1376}
1377
1378static void
1379iwi_tx_intr(struct iwi_softc *sc, struct iwi_tx_ring *txq)
1380{
1381	struct ieee80211com *ic = &sc->sc_ic;
1382	struct ifnet *ifp = ic->ic_ifp;
1383	struct iwi_tx_data *data;
1384	uint32_t hw;
1385
1386	hw = CSR_READ_4(sc, txq->csr_ridx);
1387
1388	for (; txq->next != hw;) {
1389		data = &txq->data[txq->next];
1390
1391		bus_dmamap_sync(txq->data_dmat, data->map,
1392		    BUS_DMASYNC_POSTWRITE);
1393		bus_dmamap_unload(txq->data_dmat, data->map);
1394		m_freem(data->m);
1395		data->m = NULL;
1396		ieee80211_free_node(data->ni);
1397		data->ni = NULL;
1398
1399		DPRINTFN(15, ("tx done idx=%u\n", txq->next));
1400
1401		ifp->if_opackets++;
1402
1403		txq->queued--;
1404		txq->next = (txq->next + 1) % IWI_TX_RING_COUNT;
1405	}
1406
1407	sc->sc_tx_timer = 0;
1408	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1409	iwi_start(ifp);
1410}
1411
1412static void
1413iwi_intr(void *arg)
1414{
1415	struct iwi_softc *sc = arg;
1416	uint32_t r;
1417
1418	IWI_LOCK(sc);
1419
1420	if ((r = CSR_READ_4(sc, IWI_CSR_INTR)) == 0 || r == 0xffffffff) {
1421		IWI_UNLOCK(sc);
1422		return;
1423	}
1424
1425	/* disable interrupts */
1426	CSR_WRITE_4(sc, IWI_CSR_INTR_MASK, 0);
1427
1428	if (r & (IWI_INTR_FATAL_ERROR | IWI_INTR_PARITY_ERROR)) {
1429		device_printf(sc->sc_dev, "fatal error\n");
1430		sc->sc_ic.ic_ifp->if_flags &= ~IFF_UP;
1431		iwi_stop(sc);
1432	}
1433
1434	if (r & IWI_INTR_FW_INITED) {
1435		if (!(r & (IWI_INTR_FATAL_ERROR | IWI_INTR_PARITY_ERROR)))
1436			wakeup(sc);
1437	}
1438
1439	if (r & IWI_INTR_RADIO_OFF) {
1440		DPRINTF(("radio transmitter turned off\n"));
1441		sc->sc_ic.ic_ifp->if_flags &= ~IFF_UP;
1442		iwi_stop(sc);
1443	}
1444
1445	if (r & IWI_INTR_CMD_DONE)
1446		wakeup(sc);
1447
1448	if (r & IWI_INTR_TX1_DONE)
1449		iwi_tx_intr(sc, &sc->txq[0]);
1450
1451	if (r & IWI_INTR_TX2_DONE)
1452		iwi_tx_intr(sc, &sc->txq[1]);
1453
1454	if (r & IWI_INTR_TX3_DONE)
1455		iwi_tx_intr(sc, &sc->txq[2]);
1456
1457	if (r & IWI_INTR_TX4_DONE)
1458		iwi_tx_intr(sc, &sc->txq[3]);
1459
1460	if (r & IWI_INTR_RX_DONE)
1461		iwi_rx_intr(sc);
1462
1463	/* acknowledge interrupts */
1464	CSR_WRITE_4(sc, IWI_CSR_INTR, r);
1465
1466	/* re-enable interrupts */
1467	CSR_WRITE_4(sc, IWI_CSR_INTR_MASK, IWI_INTR_MASK);
1468
1469	IWI_UNLOCK(sc);
1470}
1471
1472static int
1473iwi_cmd(struct iwi_softc *sc, uint8_t type, void *data, uint8_t len, int async)
1474{
1475	struct iwi_cmd_desc *desc;
1476
1477	desc = &sc->cmdq.desc[sc->cmdq.cur];
1478
1479	desc->hdr.type = IWI_HDR_TYPE_COMMAND;
1480	desc->hdr.flags = IWI_HDR_FLAG_IRQ;
1481	desc->type = type;
1482	desc->len = len;
1483	memcpy(desc->data, data, len);
1484
1485	bus_dmamap_sync(sc->cmdq.desc_dmat, sc->cmdq.desc_map,
1486	    BUS_DMASYNC_PREWRITE);
1487
1488	DPRINTFN(2, ("sending command idx=%u type=%u len=%u\n", sc->cmdq.cur,
1489	    type, len));
1490
1491	sc->cmdq.cur = (sc->cmdq.cur + 1) % IWI_CMD_RING_COUNT;
1492	CSR_WRITE_4(sc, IWI_CSR_CMD_WIDX, sc->cmdq.cur);
1493
1494	return async ? 0 : msleep(sc, &sc->sc_mtx, 0, "iwicmd", hz);
1495}
1496
1497static void
1498iwi_write_ibssnode(struct iwi_softc *sc, const struct iwi_node *in)
1499{
1500	struct iwi_ibssnode node;
1501
1502	/* write node information into NIC memory */
1503	memset(&node, 0, sizeof node);
1504	IEEE80211_ADDR_COPY(node.bssid, in->in_node.ni_macaddr);
1505
1506	CSR_WRITE_REGION_1(sc,
1507	    IWI_CSR_NODE_BASE + in->in_station * sizeof node,
1508	    (uint8_t *)&node, sizeof node);
1509}
1510
1511static int
1512iwi_tx_start(struct ifnet *ifp, struct mbuf *m0, struct ieee80211_node *ni,
1513    int ac)
1514{
1515	struct iwi_softc *sc = ifp->if_softc;
1516	struct ieee80211com *ic = &sc->sc_ic;
1517	struct iwi_node *in = (struct iwi_node *)ni;
1518	struct ieee80211_frame *wh;
1519	struct ieee80211_key *k;
1520	const struct chanAccParams *cap;
1521	struct iwi_tx_ring *txq = &sc->txq[ac];
1522	struct iwi_tx_data *data;
1523	struct iwi_tx_desc *desc;
1524	struct mbuf *mnew;
1525	bus_dma_segment_t segs[IWI_MAX_NSEG];
1526	int error, nsegs, hdrlen, i, noack = 0;
1527
1528	wh = mtod(m0, struct ieee80211_frame *);
1529
1530	if (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_QOS) {
1531		hdrlen = sizeof (struct ieee80211_qosframe);
1532		cap = &ic->ic_wme.wme_chanParams;
1533		noack = cap->cap_wmeParams[ac].wmep_noackPolicy;
1534	} else
1535		hdrlen = sizeof (struct ieee80211_frame);
1536
1537	/*
1538	 * This is only used in IBSS mode where the firmware expect an index
1539	 * in a h/w table instead of a destination address.
1540	 */
1541	if (ic->ic_opmode == IEEE80211_M_IBSS && in->in_station == -1) {
1542		in->in_station = alloc_unr(sc->sc_unr);
1543		if (in->in_station == -1) {	/* h/w table is full */
1544			m_freem(m0);
1545			ieee80211_free_node(ni);
1546			ifp->if_oerrors++;
1547			return 0;
1548		}
1549		iwi_write_ibssnode(sc, in);
1550	}
1551
1552	if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1553		k = ieee80211_crypto_encap(ic, ni, m0);
1554		if (k == NULL) {
1555			m_freem(m0);
1556			return ENOBUFS;
1557		}
1558
1559		/* packet header may have moved, reset our local pointer */
1560		wh = mtod(m0, struct ieee80211_frame *);
1561	}
1562
1563	if (sc->sc_drvbpf != NULL) {
1564		struct iwi_tx_radiotap_header *tap = &sc->sc_txtap;
1565
1566		tap->wt_flags = 0;
1567		tap->wt_chan_freq = htole16(ic->ic_ibss_chan->ic_freq);
1568		tap->wt_chan_flags = htole16(ic->ic_ibss_chan->ic_flags);
1569
1570		bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_txtap_len, m0);
1571	}
1572
1573	data = &txq->data[txq->cur];
1574	desc = &txq->desc[txq->cur];
1575
1576	/* save and trim IEEE802.11 header */
1577	m_copydata(m0, 0, hdrlen, (caddr_t)&desc->wh);
1578	m_adj(m0, hdrlen);
1579
1580	error = bus_dmamap_load_mbuf_sg(txq->data_dmat, data->map, m0, segs,
1581	    &nsegs, 0);
1582	if (error != 0 && error != EFBIG) {
1583		device_printf(sc->sc_dev, "could not map mbuf (error %d)\n",
1584		    error);
1585		m_freem(m0);
1586		return error;
1587	}
1588	if (error != 0) {
1589		mnew = m_defrag(m0, M_DONTWAIT);
1590		if (mnew == NULL) {
1591			device_printf(sc->sc_dev,
1592			    "could not defragment mbuf\n");
1593			m_freem(m0);
1594			return ENOBUFS;
1595		}
1596		m0 = mnew;
1597
1598		error = bus_dmamap_load_mbuf_sg(txq->data_dmat, data->map,
1599		    m0, segs, &nsegs, 0);
1600		if (error != 0) {
1601			device_printf(sc->sc_dev,
1602			    "could not map mbuf (error %d)\n", error);
1603			m_freem(m0);
1604			return error;
1605		}
1606	}
1607
1608	data->m = m0;
1609	data->ni = ni;
1610
1611	desc->hdr.type = IWI_HDR_TYPE_DATA;
1612	desc->hdr.flags = IWI_HDR_FLAG_IRQ;
1613	desc->station =
1614	    (ic->ic_opmode == IEEE80211_M_IBSS) ? in->in_station : 0;
1615	desc->cmd = IWI_DATA_CMD_TX;
1616	desc->len = htole16(m0->m_pkthdr.len);
1617	desc->flags = 0;
1618	desc->xflags = 0;
1619
1620	if (!noack && !IEEE80211_IS_MULTICAST(desc->wh.i_addr1))
1621		desc->flags |= IWI_DATA_FLAG_NEED_ACK;
1622
1623#if 0
1624	if (ic->ic_flags & IEEE80211_F_PRIVACY) {
1625		desc->wh.i_fc[1] |= IEEE80211_FC1_WEP;
1626		desc->wep_txkey = ic->ic_crypto.cs_def_txkey;
1627	} else
1628#endif
1629		desc->flags |= IWI_DATA_FLAG_NO_WEP;
1630
1631	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
1632		desc->flags |= IWI_DATA_FLAG_SHPREAMBLE;
1633
1634	if (desc->wh.i_fc[0] & IEEE80211_FC0_SUBTYPE_QOS)
1635		desc->xflags |= IWI_DATA_XFLAG_QOS;
1636
1637	desc->nseg = htole32(nsegs);
1638	for (i = 0; i < nsegs; i++) {
1639		desc->seg_addr[i] = htole32(segs[i].ds_addr);
1640		desc->seg_len[i]  = htole16(segs[i].ds_len);
1641	}
1642
1643	bus_dmamap_sync(txq->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
1644	bus_dmamap_sync(txq->desc_dmat, txq->desc_map, BUS_DMASYNC_PREWRITE);
1645
1646	DPRINTFN(5, ("sending data frame txq=%u idx=%u len=%u nseg=%u\n",
1647	    ac, txq->cur, le16toh(desc->len), nsegs));
1648
1649	txq->queued++;
1650	txq->cur = (txq->cur + 1) % IWI_TX_RING_COUNT;
1651	CSR_WRITE_4(sc, txq->csr_widx, txq->cur);
1652
1653	return 0;
1654}
1655
1656static void
1657iwi_start(struct ifnet *ifp)
1658{
1659	struct iwi_softc *sc = ifp->if_softc;
1660	struct ieee80211com *ic = &sc->sc_ic;
1661	struct mbuf *m0;
1662	struct ether_header *eh;
1663	struct ieee80211_node *ni;
1664	int ac;
1665
1666	IWI_LOCK(sc);
1667
1668	if (ic->ic_state != IEEE80211_S_RUN) {
1669		IWI_UNLOCK(sc);
1670		return;
1671	}
1672
1673	for (;;) {
1674		IFQ_DRV_DEQUEUE(&ifp->if_snd, m0);
1675		if (m0 == NULL)
1676			break;
1677
1678		if (m0->m_len < sizeof (struct ether_header) &&
1679		    (m0 = m_pullup(m0, sizeof (struct ether_header))) == NULL) {
1680			ifp->if_oerrors++;
1681			continue;
1682		}
1683		eh = mtod(m0, struct ether_header *);
1684		ni = ieee80211_find_txnode(ic, eh->ether_dhost);
1685		if (ni == NULL) {
1686			m_freem(m0);
1687			ifp->if_oerrors++;
1688			continue;
1689		}
1690
1691		/* classify mbuf so we can find which tx ring to use */
1692		if (ieee80211_classify(ic, m0, ni) != 0) {
1693			m_freem(m0);
1694			ieee80211_free_node(ni);
1695			ifp->if_oerrors++;
1696			continue;
1697		}
1698
1699		/* no QoS encapsulation for EAPOL frames */
1700		ac = (eh->ether_type != htons(ETHERTYPE_PAE)) ?
1701		    M_WME_GETAC(m0) : WME_AC_BE;
1702
1703		if (sc->txq[ac].queued > IWI_TX_RING_COUNT - 8) {
1704			/* there is no place left in this ring */
1705			IFQ_DRV_PREPEND(&ifp->if_snd, m0);
1706			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1707			break;
1708		}
1709
1710		BPF_MTAP(ifp, m0);
1711
1712		m0 = ieee80211_encap(ic, m0, ni);
1713		if (m0 == NULL) {
1714			ieee80211_free_node(ni);
1715			ifp->if_oerrors++;
1716			continue;
1717		}
1718
1719		if (ic->ic_rawbpf != NULL)
1720			bpf_mtap(ic->ic_rawbpf, m0);
1721
1722		if (iwi_tx_start(ifp, m0, ni, ac) != 0) {
1723			ieee80211_free_node(ni);
1724			ifp->if_oerrors++;
1725			break;
1726		}
1727
1728		sc->sc_tx_timer = 5;
1729		ifp->if_timer = 1;
1730	}
1731
1732	IWI_UNLOCK(sc);
1733}
1734
1735static void
1736iwi_watchdog(struct ifnet *ifp)
1737{
1738	struct iwi_softc *sc = ifp->if_softc;
1739	struct ieee80211com *ic = &sc->sc_ic;
1740
1741	IWI_LOCK(sc);
1742
1743	ifp->if_timer = 0;
1744
1745	if (sc->sc_tx_timer > 0) {
1746		if (--sc->sc_tx_timer == 0) {
1747			if_printf(ifp, "device timeout\n");
1748			ifp->if_oerrors++;
1749			ifp->if_flags &= ~IFF_UP;
1750			iwi_stop(sc);
1751			IWI_UNLOCK(sc);
1752			return;
1753		}
1754		ifp->if_timer = 1;
1755	}
1756
1757	ieee80211_watchdog(ic);
1758
1759	IWI_UNLOCK(sc);
1760}
1761
1762static int
1763iwi_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1764{
1765	struct iwi_softc *sc = ifp->if_softc;
1766	struct ieee80211com *ic = &sc->sc_ic;
1767	struct ifreq *ifr;
1768	int error = 0;
1769
1770	IWI_LOCK(sc);
1771
1772	switch (cmd) {
1773	case SIOCSIFFLAGS:
1774		if (ifp->if_flags & IFF_UP) {
1775			if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
1776				iwi_init(sc);
1777		} else {
1778			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1779				iwi_stop(sc);
1780		}
1781		break;
1782
1783	case SIOCSLOADFW:
1784		/* only super-user can do that! */
1785		if ((error = suser(curthread)) != 0)
1786			break;
1787
1788		ifr = (struct ifreq *)data;
1789		error = iwi_cache_firmware(sc, ifr->ifr_data);
1790		break;
1791
1792	case SIOCSKILLFW:
1793		/* only super-user can do that! */
1794		if ((error = suser(curthread)) != 0)
1795			break;
1796
1797		ifp->if_flags &= ~IFF_UP;
1798		iwi_stop(sc);
1799		iwi_free_firmware(sc);
1800		break;
1801
1802	default:
1803		error = ieee80211_ioctl(ic, cmd, data);
1804	}
1805
1806	if (error == ENETRESET) {
1807		if ((ifp->if_flags & IFF_UP) &&
1808		    (ifp->if_drv_flags & IFF_DRV_RUNNING) &&
1809		    (ic->ic_roaming != IEEE80211_ROAMING_MANUAL))
1810			iwi_init(sc);
1811		error = 0;
1812	}
1813
1814	IWI_UNLOCK(sc);
1815
1816	return error;
1817}
1818
1819static void
1820iwi_stop_master(struct iwi_softc *sc)
1821{
1822	uint32_t tmp;
1823	int ntries;
1824
1825	/* disable interrupts */
1826	CSR_WRITE_4(sc, IWI_CSR_INTR_MASK, 0);
1827
1828	CSR_WRITE_4(sc, IWI_CSR_RST, IWI_RST_STOP_MASTER);
1829	for (ntries = 0; ntries < 5; ntries++) {
1830		if (CSR_READ_4(sc, IWI_CSR_RST) & IWI_RST_MASTER_DISABLED)
1831			break;
1832		DELAY(10);
1833	}
1834	if (ntries == 5)
1835		device_printf(sc->sc_dev, "timeout waiting for master\n");
1836
1837	tmp = CSR_READ_4(sc, IWI_CSR_RST);
1838	CSR_WRITE_4(sc, IWI_CSR_RST, tmp | IWI_RST_PRINCETON_RESET);
1839
1840	sc->flags &= ~IWI_FLAG_FW_INITED;
1841}
1842
1843static int
1844iwi_reset(struct iwi_softc *sc)
1845{
1846	uint32_t tmp;
1847	int i, ntries;
1848
1849	iwi_stop_master(sc);
1850
1851	tmp = CSR_READ_4(sc, IWI_CSR_CTL);
1852	CSR_WRITE_4(sc, IWI_CSR_CTL, tmp | IWI_CTL_INIT);
1853
1854	CSR_WRITE_4(sc, IWI_CSR_READ_INT, IWI_READ_INT_INIT_HOST);
1855
1856	/* wait for clock stabilization */
1857	for (ntries = 0; ntries < 1000; ntries++) {
1858		if (CSR_READ_4(sc, IWI_CSR_CTL) & IWI_CTL_CLOCK_READY)
1859			break;
1860		DELAY(200);
1861	}
1862	if (ntries == 1000) {
1863		device_printf(sc->sc_dev,
1864		    "timeout waiting for clock stabilization\n");
1865		return EIO;
1866	}
1867
1868	tmp = CSR_READ_4(sc, IWI_CSR_RST);
1869	CSR_WRITE_4(sc, IWI_CSR_RST, tmp | IWI_RST_SOFT_RESET);
1870
1871	DELAY(10);
1872
1873	tmp = CSR_READ_4(sc, IWI_CSR_CTL);
1874	CSR_WRITE_4(sc, IWI_CSR_CTL, tmp | IWI_CTL_INIT);
1875
1876	/* clear NIC memory */
1877	CSR_WRITE_4(sc, IWI_CSR_AUTOINC_ADDR, 0);
1878	for (i = 0; i < 0xc000; i++)
1879		CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, 0);
1880
1881	return 0;
1882}
1883
1884static int
1885iwi_load_ucode(struct iwi_softc *sc, void *uc, int size)
1886{
1887	uint32_t tmp;
1888	uint16_t *w;
1889	int ntries, i;
1890
1891	CSR_WRITE_4(sc, IWI_CSR_RST, CSR_READ_4(sc, IWI_CSR_RST) |
1892	    IWI_RST_STOP_MASTER);
1893	for (ntries = 0; ntries < 5; ntries++) {
1894		if (CSR_READ_4(sc, IWI_CSR_RST) & IWI_RST_MASTER_DISABLED)
1895			break;
1896		DELAY(10);
1897	}
1898	if (ntries == 5) {
1899		device_printf(sc->sc_dev, "timeout waiting for master\n");
1900		return EIO;
1901	}
1902
1903	MEM_WRITE_4(sc, 0x3000e0, 0x80000000);
1904	DELAY(5000);
1905
1906	tmp = CSR_READ_4(sc, IWI_CSR_RST);
1907	tmp &= ~IWI_RST_PRINCETON_RESET;
1908	CSR_WRITE_4(sc, IWI_CSR_RST, tmp);
1909
1910	DELAY(5000);
1911	MEM_WRITE_4(sc, 0x3000e0, 0);
1912	DELAY(1000);
1913	MEM_WRITE_4(sc, 0x300004, 1);
1914	DELAY(1000);
1915	MEM_WRITE_4(sc, 0x300004, 0);
1916	DELAY(1000);
1917	MEM_WRITE_1(sc, 0x200000, 0x00);
1918	MEM_WRITE_1(sc, 0x200000, 0x40);
1919	DELAY(1000);
1920
1921	/* write microcode into adapter memory */
1922	for (w = uc; size > 0; w++, size -= 2)
1923		MEM_WRITE_2(sc, 0x200010, htole16(*w));
1924
1925	MEM_WRITE_1(sc, 0x200000, 0x00);
1926	MEM_WRITE_1(sc, 0x200000, 0x80);
1927
1928	/* wait until we get an answer */
1929	for (ntries = 0; ntries < 100; ntries++) {
1930		if (MEM_READ_1(sc, 0x200000) & 1)
1931			break;
1932		DELAY(100);
1933	}
1934	if (ntries == 100) {
1935		device_printf(sc->sc_dev,
1936		    "timeout waiting for ucode to initialize\n");
1937		return EIO;
1938	}
1939
1940	/* read the answer or the firmware will not initialize properly */
1941	for (i = 0; i < 7; i++)
1942		MEM_READ_4(sc, 0x200004);
1943
1944	MEM_WRITE_1(sc, 0x200000, 0x00);
1945
1946	return 0;
1947}
1948
1949/* macro to handle unaligned little endian data in firmware image */
1950#define GETLE32(p) ((p)[0] | (p)[1] << 8 | (p)[2] << 16 | (p)[3] << 24)
1951
1952static int
1953iwi_load_firmware(struct iwi_softc *sc, void *fw, int size)
1954{
1955	bus_dma_tag_t dmat;
1956	bus_dmamap_t map;
1957	bus_addr_t physaddr;
1958	void *virtaddr;
1959	u_char *p, *end;
1960	uint32_t sentinel, ctl, src, dst, sum, len, mlen, tmp;
1961	int ntries, error = 0;
1962
1963	/* allocate DMA memory for mapping firmware image */
1964	error = bus_dma_tag_create(NULL, 4, 0, BUS_SPACE_MAXADDR_32BIT,
1965	    BUS_SPACE_MAXADDR, NULL, NULL, size, 1, size, 0, NULL, NULL, &dmat);
1966	if (error != 0) {
1967		device_printf(sc->sc_dev,
1968		    "could not create firmware DMA tag\n");
1969		goto fail1;
1970	}
1971
1972	error = bus_dmamem_alloc(dmat, &virtaddr, BUS_DMA_NOWAIT, &map);
1973	if (error != 0) {
1974		device_printf(sc->sc_dev,
1975		    "could not allocate firmware DMA memory\n");
1976		goto fail2;
1977	}
1978
1979	error = bus_dmamap_load(dmat, map, virtaddr, size, iwi_dma_map_addr,
1980	    &physaddr, 0);
1981	if (error != 0) {
1982		device_printf(sc->sc_dev, "could not load firmware DMA map\n");
1983		goto fail3;
1984	}
1985
1986	/* copy firmware image to DMA memory */
1987	memcpy(virtaddr, fw, size);
1988
1989	/* make sure the adapter will get up-to-date values */
1990	bus_dmamap_sync(dmat, map, BUS_DMASYNC_PREWRITE);
1991
1992	/* tell the adapter where the command blocks are stored */
1993	MEM_WRITE_4(sc, 0x3000a0, 0x27000);
1994
1995	/*
1996	 * Store command blocks into adapter's internal memory using register
1997	 * indirections. The adapter will read the firmware image through DMA
1998	 * using information stored in command blocks.
1999	 */
2000	src = physaddr;
2001	p = virtaddr;
2002	end = p + size;
2003	CSR_WRITE_4(sc, IWI_CSR_AUTOINC_ADDR, 0x27000);
2004
2005	while (p < end) {
2006		dst = GETLE32(p); p += 4; src += 4;
2007		len = GETLE32(p); p += 4; src += 4;
2008		p += len;
2009
2010		while (len > 0) {
2011			mlen = min(len, IWI_CB_MAXDATALEN);
2012
2013			ctl = IWI_CB_DEFAULT_CTL | mlen;
2014			sum = ctl ^ src ^ dst;
2015
2016			/* write a command block */
2017			CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, ctl);
2018			CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, src);
2019			CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, dst);
2020			CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, sum);
2021
2022			src += mlen;
2023			dst += mlen;
2024			len -= mlen;
2025		}
2026	}
2027
2028	/* write a fictive final command block (sentinel) */
2029	sentinel = CSR_READ_4(sc, IWI_CSR_AUTOINC_ADDR);
2030	CSR_WRITE_4(sc, IWI_CSR_AUTOINC_DATA, 0);
2031
2032	tmp = CSR_READ_4(sc, IWI_CSR_RST);
2033	tmp &= ~(IWI_RST_MASTER_DISABLED | IWI_RST_STOP_MASTER);
2034	CSR_WRITE_4(sc, IWI_CSR_RST, tmp);
2035
2036	/* tell the adapter to start processing command blocks */
2037	MEM_WRITE_4(sc, 0x3000a4, 0x540100);
2038
2039	/* wait until the adapter reach the sentinel */
2040	for (ntries = 0; ntries < 400; ntries++) {
2041		if (MEM_READ_4(sc, 0x3000d0) >= sentinel)
2042			break;
2043		DELAY(100);
2044	}
2045	if (ntries == 400) {
2046		device_printf(sc->sc_dev,
2047		    "timeout processing command blocks\n");
2048		error = EIO;
2049		goto fail4;
2050	}
2051
2052	/* we're done with command blocks processing */
2053	MEM_WRITE_4(sc, 0x3000a4, 0x540c00);
2054
2055	/* allow interrupts so we know when the firmware is inited */
2056	CSR_WRITE_4(sc, IWI_CSR_INTR_MASK, IWI_INTR_MASK);
2057
2058	/* tell the adapter to initialize the firmware */
2059	CSR_WRITE_4(sc, IWI_CSR_RST, 0);
2060
2061	tmp = CSR_READ_4(sc, IWI_CSR_CTL);
2062	CSR_WRITE_4(sc, IWI_CSR_CTL, tmp | IWI_CTL_ALLOW_STANDBY);
2063
2064	/* wait at most one second for firmware initialization to complete */
2065	if ((error = msleep(sc, &sc->sc_mtx, 0, "iwiinit", hz)) != 0) {
2066		device_printf(sc->sc_dev, "timeout waiting for firmware "
2067		    "initialization to complete\n");
2068		goto fail4;
2069	}
2070
2071fail4:	bus_dmamap_sync(dmat, map, BUS_DMASYNC_POSTWRITE);
2072	bus_dmamap_unload(dmat, map);
2073fail3:	bus_dmamem_free(dmat, virtaddr, map);
2074fail2:	bus_dma_tag_destroy(dmat);
2075fail1:
2076	return error;
2077}
2078
2079/*
2080 * Store firmware into kernel memory so we can download it when we need to,
2081 * e.g when the adapter wakes up from suspend mode.
2082 */
2083static int
2084iwi_cache_firmware(struct iwi_softc *sc, void *data)
2085{
2086	struct iwi_firmware *kfw = &sc->fw;
2087	struct iwi_firmware ufw;
2088	int error;
2089
2090	iwi_free_firmware(sc);
2091
2092	IWI_UNLOCK(sc);
2093
2094	if ((error = copyin(data, &ufw, sizeof ufw)) != 0)
2095		goto fail1;
2096
2097	kfw->boot_size  = ufw.boot_size;
2098	kfw->ucode_size = ufw.ucode_size;
2099	kfw->main_size  = ufw.main_size;
2100
2101	kfw->boot = malloc(kfw->boot_size, M_DEVBUF, M_NOWAIT);
2102	if (kfw->boot == NULL) {
2103		error = ENOMEM;
2104		goto fail1;
2105	}
2106
2107	kfw->ucode = malloc(kfw->ucode_size, M_DEVBUF, M_NOWAIT);
2108	if (kfw->ucode == NULL) {
2109		error = ENOMEM;
2110		goto fail2;
2111	}
2112
2113	kfw->main = malloc(kfw->main_size, M_DEVBUF, M_NOWAIT);
2114	if (kfw->main == NULL) {
2115		error = ENOMEM;
2116		goto fail3;
2117	}
2118
2119	if ((error = copyin(ufw.boot, kfw->boot, kfw->boot_size)) != 0)
2120		goto fail4;
2121
2122	if ((error = copyin(ufw.ucode, kfw->ucode, kfw->ucode_size)) != 0)
2123		goto fail4;
2124
2125	if ((error = copyin(ufw.main, kfw->main, kfw->main_size)) != 0)
2126		goto fail4;
2127
2128	DPRINTF(("Firmware cached: boot %u, ucode %u, main %u\n",
2129	    kfw->boot_size, kfw->ucode_size, kfw->main_size));
2130
2131	IWI_LOCK(sc);
2132
2133	sc->flags |= IWI_FLAG_FW_CACHED;
2134
2135	return 0;
2136
2137fail4:	free(kfw->boot, M_DEVBUF);
2138fail3:	free(kfw->ucode, M_DEVBUF);
2139fail2:	free(kfw->main, M_DEVBUF);
2140fail1:	IWI_LOCK(sc);
2141
2142	return error;
2143}
2144
2145static void
2146iwi_free_firmware(struct iwi_softc *sc)
2147{
2148	if (!(sc->flags & IWI_FLAG_FW_CACHED))
2149		return;
2150
2151	free(sc->fw.boot, M_DEVBUF);
2152	free(sc->fw.ucode, M_DEVBUF);
2153	free(sc->fw.main, M_DEVBUF);
2154
2155	sc->flags &= ~IWI_FLAG_FW_CACHED;
2156}
2157
2158static int
2159iwi_config(struct iwi_softc *sc)
2160{
2161	struct ieee80211com *ic = &sc->sc_ic;
2162	struct ifnet *ifp = ic->ic_ifp;
2163	struct iwi_configuration config;
2164	struct iwi_rateset rs;
2165	struct iwi_txpower power;
2166	struct ieee80211_key *wk;
2167	struct iwi_wep_key wepkey;
2168	uint32_t data;
2169	int error, i;
2170
2171	IEEE80211_ADDR_COPY(ic->ic_myaddr, IF_LLADDR(ifp));
2172	DPRINTF(("Setting MAC address to %6D\n", ic->ic_myaddr, ":"));
2173	error = iwi_cmd(sc, IWI_CMD_SET_MAC_ADDRESS, ic->ic_myaddr,
2174	    IEEE80211_ADDR_LEN, 0);
2175	if (error != 0)
2176		return error;
2177
2178	memset(&config, 0, sizeof config);
2179	config.bluetooth_coexistence = sc->bluetooth;
2180	config.antenna = sc->antenna;
2181	config.multicast_enabled = 1;
2182	config.answer_pbreq = (ic->ic_opmode == IEEE80211_M_IBSS) ? 1 : 0;
2183	config.disable_unicast_decryption = 1;
2184	config.disable_multicast_decryption = 1;
2185	DPRINTF(("Configuring adapter\n"));
2186	error = iwi_cmd(sc, IWI_CMD_SET_CONFIG, &config, sizeof config, 0);
2187	if (error != 0)
2188		return error;
2189
2190	data = htole32(IWI_POWER_MODE_CAM);
2191	DPRINTF(("Setting power mode to %u\n", le32toh(data)));
2192	error = iwi_cmd(sc, IWI_CMD_SET_POWER_MODE, &data, sizeof data, 0);
2193	if (error != 0)
2194		return error;
2195
2196	data = htole32(ic->ic_rtsthreshold);
2197	DPRINTF(("Setting RTS threshold to %u\n", le32toh(data)));
2198	error = iwi_cmd(sc, IWI_CMD_SET_RTS_THRESHOLD, &data, sizeof data, 0);
2199	if (error != 0)
2200		return error;
2201
2202	data = htole32(ic->ic_fragthreshold);
2203	DPRINTF(("Setting fragmentation threshold to %u\n", le32toh(data)));
2204	error = iwi_cmd(sc, IWI_CMD_SET_FRAG_THRESHOLD, &data, sizeof data, 0);
2205	if (error != 0)
2206		return error;
2207
2208	if (ic->ic_opmode == IEEE80211_M_IBSS) {
2209		power.mode = IWI_MODE_11B;
2210		power.nchan = 11;
2211		for (i = 0; i < 11; i++) {
2212			power.chan[i].chan = i + 1;
2213			power.chan[i].power = IWI_TXPOWER_MAX;
2214		}
2215		DPRINTF(("Setting .11b channels tx power\n"));
2216		error = iwi_cmd(sc, IWI_CMD_SET_TX_POWER, &power, sizeof power,
2217		    0);
2218		if (error != 0)
2219			return error;
2220
2221		power.mode = IWI_MODE_11G;
2222		DPRINTF(("Setting .11g channels tx power\n"));
2223		error = iwi_cmd(sc, IWI_CMD_SET_TX_POWER, &power, sizeof power,
2224		    0);
2225		if (error != 0)
2226			return error;
2227	}
2228
2229	rs.mode = IWI_MODE_11G;
2230	rs.type = IWI_RATESET_TYPE_SUPPORTED;
2231	rs.nrates = ic->ic_sup_rates[IEEE80211_MODE_11G].rs_nrates;
2232	memcpy(rs.rates, ic->ic_sup_rates[IEEE80211_MODE_11G].rs_rates,
2233	    rs.nrates);
2234	DPRINTF(("Setting .11bg supported rates (%u)\n", rs.nrates));
2235	error = iwi_cmd(sc, IWI_CMD_SET_RATES, &rs, sizeof rs, 0);
2236	if (error != 0)
2237		return error;
2238
2239	rs.mode = IWI_MODE_11A;
2240	rs.type = IWI_RATESET_TYPE_SUPPORTED;
2241	rs.nrates = ic->ic_sup_rates[IEEE80211_MODE_11A].rs_nrates;
2242	memcpy(rs.rates, ic->ic_sup_rates[IEEE80211_MODE_11A].rs_rates,
2243	    rs.nrates);
2244	DPRINTF(("Setting .11a supported rates (%u)\n", rs.nrates));
2245	error = iwi_cmd(sc, IWI_CMD_SET_RATES, &rs, sizeof rs, 0);
2246	if (error != 0)
2247		return error;
2248
2249	/* if we have a desired ESSID, set it now */
2250	if (ic->ic_des_esslen != 0) {
2251#ifdef IWI_DEBUG
2252		if (iwi_debug > 0) {
2253			printf("Setting desired ESSID to ");
2254			ieee80211_print_essid(ic->ic_des_essid,
2255			    ic->ic_des_esslen);
2256			printf("\n");
2257		}
2258#endif
2259		error = iwi_cmd(sc, IWI_CMD_SET_ESSID, ic->ic_des_essid,
2260		    ic->ic_des_esslen, 0);
2261		if (error != 0)
2262			return error;
2263	}
2264
2265	data = htole32(arc4random());
2266	DPRINTF(("Setting initialization vector to %u\n", le32toh(data)));
2267	error = iwi_cmd(sc, IWI_CMD_SET_IV, &data, sizeof data, 0);
2268	if (error != 0)
2269		return error;
2270
2271	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
2272		wk = &ic->ic_crypto.cs_nw_keys[i];
2273
2274		wepkey.cmd = IWI_WEP_KEY_CMD_SETKEY;
2275		wepkey.idx = i;
2276		wepkey.len = wk->wk_keylen;
2277		memset(wepkey.key, 0, sizeof wepkey.key);
2278		memcpy(wepkey.key, wk->wk_key, wk->wk_keylen);
2279		DPRINTF(("Setting wep key index %u len %u\n", wepkey.idx,
2280		    wepkey.len));
2281		error = iwi_cmd(sc, IWI_CMD_SET_WEP_KEY, &wepkey,
2282		    sizeof wepkey, 0);
2283		if (error != 0)
2284			return error;
2285	}
2286
2287	/* enable adapter */
2288	DPRINTF(("Enabling adapter\n"));
2289	return iwi_cmd(sc, IWI_CMD_ENABLE, NULL, 0, 0);
2290}
2291
2292static int
2293iwi_set_chan(struct iwi_softc *sc, struct ieee80211_channel *chan)
2294{
2295	struct ieee80211com *ic = &sc->sc_ic;
2296	struct iwi_scan scan;
2297
2298	memset(&scan, 0, sizeof scan);
2299	memset(scan.type, IWI_SCAN_TYPE_PASSIVE, sizeof scan.type);
2300	scan.passive = htole16(2000);
2301	scan.channels[0] = 1 |
2302	    (IEEE80211_IS_CHAN_5GHZ(chan) ? IWI_CHAN_5GHZ : IWI_CHAN_2GHZ);
2303	scan.channels[1] = ieee80211_chan2ieee(ic, chan);
2304
2305	DPRINTF(("Setting channel to %u\n", ieee80211_chan2ieee(ic, chan)));
2306	return iwi_cmd(sc, IWI_CMD_SCAN, &scan, sizeof scan, 1);
2307}
2308
2309static int
2310iwi_scan(struct iwi_softc *sc)
2311{
2312	struct ieee80211com *ic = &sc->sc_ic;
2313	struct iwi_scan scan;
2314	uint8_t *p;
2315	int i, count;
2316
2317	memset(&scan, 0, sizeof scan);
2318
2319	if (ic->ic_des_esslen != 0) {
2320		scan.bdirected = htole16(sc->dwelltime);
2321		memset(scan.type, IWI_SCAN_TYPE_BDIRECTED, sizeof scan.type);
2322	} else {
2323		scan.broadcast = htole16(sc->dwelltime);
2324		memset(scan.type, IWI_SCAN_TYPE_BROADCAST, sizeof scan.type);
2325	}
2326
2327	p = scan.channels;
2328	count = 0;
2329	for (i = 0; i <= IEEE80211_CHAN_MAX; i++) {
2330		if (IEEE80211_IS_CHAN_5GHZ(&ic->ic_channels[i]) &&
2331		    isset(ic->ic_chan_active, i)) {
2332			*++p = i;
2333			count++;
2334		}
2335	}
2336	*(p - count) = IWI_CHAN_5GHZ | count;
2337
2338	count = 0;
2339	for (i = 0; i <= IEEE80211_CHAN_MAX; i++) {
2340		if (IEEE80211_IS_CHAN_2GHZ(&ic->ic_channels[i]) &&
2341		    isset(ic->ic_chan_active, i)) {
2342			*++p = i;
2343			count++;
2344		}
2345	}
2346	*(p - count) = IWI_CHAN_2GHZ | count;
2347
2348	DPRINTF(("Start scanning\n"));
2349	return iwi_cmd(sc, IWI_CMD_SCAN, &scan, sizeof scan, 1);
2350}
2351
2352static int
2353iwi_auth_and_assoc(struct iwi_softc *sc)
2354{
2355	struct ieee80211com *ic = &sc->sc_ic;
2356	struct ifnet *ifp = ic->ic_ifp;
2357	struct ieee80211_node *ni = ic->ic_bss;
2358	struct ieee80211_wme_info wme;
2359	struct iwi_configuration config;
2360	struct iwi_associate assoc;
2361	struct iwi_rateset rs;
2362	uint16_t capinfo;
2363	uint32_t data;
2364	int error;
2365
2366	if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan)) {
2367		memset(&config, 0, sizeof config);
2368		config.bluetooth_coexistence = sc->bluetooth;
2369		config.antenna = sc->antenna;
2370		config.multicast_enabled = 1;
2371		config.use_protection = 1;
2372		config.answer_pbreq =
2373		    (ic->ic_opmode == IEEE80211_M_IBSS) ? 1 : 0;
2374		config.disable_unicast_decryption = 1;
2375		config.disable_multicast_decryption = 1;
2376		DPRINTF(("Configuring adapter\n"));
2377		error = iwi_cmd(sc, IWI_CMD_SET_CONFIG, &config, sizeof config,
2378		    1);
2379		if (error != 0)
2380			return error;
2381	}
2382
2383#ifdef IWI_DEBUG
2384	if (iwi_debug > 0) {
2385		printf("Setting ESSID to ");
2386		ieee80211_print_essid(ni->ni_essid, ni->ni_esslen);
2387		printf("\n");
2388	}
2389#endif
2390	error = iwi_cmd(sc, IWI_CMD_SET_ESSID, ni->ni_essid, ni->ni_esslen, 1);
2391	if (error != 0)
2392		return error;
2393
2394	/* the rate set has already been "negotiated" */
2395	rs.mode = IEEE80211_IS_CHAN_5GHZ(ni->ni_chan) ? IWI_MODE_11A :
2396	    IWI_MODE_11G;
2397	rs.type = IWI_RATESET_TYPE_NEGOTIATED;
2398	rs.nrates = ni->ni_rates.rs_nrates;
2399	memcpy(rs.rates, ni->ni_rates.rs_rates, rs.nrates);
2400	DPRINTF(("Setting negociated rates (%u)\n", rs.nrates));
2401	error = iwi_cmd(sc, IWI_CMD_SET_RATES, &rs, sizeof rs, 1);
2402	if (error != 0)
2403		return error;
2404
2405	if ((ic->ic_flags & IEEE80211_F_WME) && ni->ni_wme_ie != NULL) {
2406		wme.wme_id = IEEE80211_ELEMID_VENDOR;
2407		wme.wme_len = sizeof (struct ieee80211_wme_info) - 2;
2408		wme.wme_oui[0] = 0x00;
2409		wme.wme_oui[1] = 0x50;
2410		wme.wme_oui[2] = 0xf2;
2411		wme.wme_type = WME_OUI_TYPE;
2412		wme.wme_subtype = WME_INFO_OUI_SUBTYPE;
2413		wme.wme_version = WME_VERSION;
2414		wme.wme_info = 0;
2415
2416		DPRINTF(("Setting WME IE (len=%u)\n", wme.wme_len));
2417		error = iwi_cmd(sc, IWI_CMD_SET_WMEIE, &wme, sizeof wme, 1);
2418		if (error != 0)
2419			return error;
2420	}
2421
2422	if (ic->ic_opt_ie != NULL) {
2423		DPRINTF(("Setting optional IE (len=%u)\n", ic->ic_opt_ie_len));
2424		error = iwi_cmd(sc, IWI_CMD_SET_OPTIE, ic->ic_opt_ie,
2425		    ic->ic_opt_ie_len, 1);
2426		if (error != 0)
2427			return error;
2428	}
2429
2430	data = htole32(ni->ni_rssi);
2431	DPRINTF(("Setting sensitivity to %d\n", (int8_t)ni->ni_rssi));
2432	error = iwi_cmd(sc, IWI_CMD_SET_SENSITIVITY, &data, sizeof data, 1);
2433	if (error != 0)
2434		return error;
2435
2436	memset(&assoc, 0, sizeof assoc);
2437	assoc.mode = IEEE80211_IS_CHAN_5GHZ(ni->ni_chan) ? IWI_MODE_11A :
2438	    IWI_MODE_11G;
2439	assoc.chan = ieee80211_chan2ieee(ic, ni->ni_chan);
2440	if (ni->ni_authmode == IEEE80211_AUTH_SHARED)
2441		assoc.auth = ic->ic_crypto.cs_def_txkey << 4 | IWI_AUTH_SHARED;
2442	if ((ic->ic_flags & IEEE80211_F_WME) && ni->ni_wme_ie != NULL)
2443		assoc.policy |= htole16(IWI_POLICY_WME);
2444	if (ic->ic_opt_ie != NULL)
2445		assoc.policy |= htole16(IWI_POLICY_WPA);
2446	memcpy(assoc.tstamp, ni->ni_tstamp.data, 8);
2447
2448	if (ic->ic_opmode == IEEE80211_M_IBSS)
2449		capinfo = IEEE80211_CAPINFO_IBSS;
2450	else
2451		capinfo = IEEE80211_CAPINFO_ESS;
2452	if (ic->ic_flags & IEEE80211_F_PRIVACY)
2453		capinfo |= IEEE80211_CAPINFO_PRIVACY;
2454	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
2455	    IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
2456		capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
2457	if (ic->ic_flags & IEEE80211_F_SHSLOT)
2458		capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
2459	assoc.capinfo = htole16(capinfo);
2460
2461	assoc.lintval = htole16(ic->ic_lintval);
2462	assoc.intval = htole16(ni->ni_intval);
2463	IEEE80211_ADDR_COPY(assoc.bssid, ni->ni_bssid);
2464	if (ic->ic_opmode == IEEE80211_M_IBSS)
2465		IEEE80211_ADDR_COPY(assoc.dst, ifp->if_broadcastaddr);
2466	else
2467		IEEE80211_ADDR_COPY(assoc.dst, ni->ni_bssid);
2468
2469	DPRINTF(("Trying to associate to %6D channel %u auth %u\n",
2470	    assoc.bssid, ":", assoc.chan, assoc.auth));
2471	return iwi_cmd(sc, IWI_CMD_ASSOCIATE, &assoc, sizeof assoc, 1);
2472}
2473
2474static void
2475iwi_init(void *priv)
2476{
2477	struct iwi_softc *sc = priv;
2478	struct ieee80211com *ic = &sc->sc_ic;
2479	struct ifnet *ifp = ic->ic_ifp;
2480	struct iwi_firmware *fw = &sc->fw;
2481	struct iwi_rx_data *data;
2482	int i;
2483
2484	/* exit immediately if firmware has not been ioctl'd */
2485	if (!(sc->flags & IWI_FLAG_FW_CACHED)) {
2486		if (!(sc->flags & IWI_FLAG_FW_WARNED))
2487			device_printf(sc->sc_dev, "Please load firmware\n");
2488		sc->flags |= IWI_FLAG_FW_WARNED;
2489		ifp->if_flags &= ~IFF_UP;
2490		return;
2491	}
2492
2493	iwi_stop(sc);
2494
2495	if (iwi_reset(sc) != 0) {
2496		device_printf(sc->sc_dev, "could not reset adapter\n");
2497		goto fail;
2498	}
2499
2500	if (iwi_load_firmware(sc, fw->boot, fw->boot_size) != 0) {
2501		device_printf(sc->sc_dev, "could not load boot firmware\n");
2502		goto fail;
2503	}
2504
2505	if (iwi_load_ucode(sc, fw->ucode, fw->ucode_size) != 0) {
2506		device_printf(sc->sc_dev, "could not load microcode\n");
2507		goto fail;
2508	}
2509
2510	iwi_stop_master(sc);
2511
2512	CSR_WRITE_4(sc, IWI_CSR_CMD_BASE, sc->cmdq.physaddr);
2513	CSR_WRITE_4(sc, IWI_CSR_CMD_SIZE, sc->cmdq.count);
2514	CSR_WRITE_4(sc, IWI_CSR_CMD_WIDX, sc->cmdq.cur);
2515
2516	CSR_WRITE_4(sc, IWI_CSR_TX1_BASE, sc->txq[0].physaddr);
2517	CSR_WRITE_4(sc, IWI_CSR_TX1_SIZE, sc->txq[0].count);
2518	CSR_WRITE_4(sc, IWI_CSR_TX1_WIDX, sc->txq[0].cur);
2519
2520	CSR_WRITE_4(sc, IWI_CSR_TX2_BASE, sc->txq[1].physaddr);
2521	CSR_WRITE_4(sc, IWI_CSR_TX2_SIZE, sc->txq[1].count);
2522	CSR_WRITE_4(sc, IWI_CSR_TX2_WIDX, sc->txq[1].cur);
2523
2524	CSR_WRITE_4(sc, IWI_CSR_TX3_BASE, sc->txq[2].physaddr);
2525	CSR_WRITE_4(sc, IWI_CSR_TX3_SIZE, sc->txq[2].count);
2526	CSR_WRITE_4(sc, IWI_CSR_TX3_WIDX, sc->txq[2].cur);
2527
2528	CSR_WRITE_4(sc, IWI_CSR_TX4_BASE, sc->txq[3].physaddr);
2529	CSR_WRITE_4(sc, IWI_CSR_TX4_SIZE, sc->txq[3].count);
2530	CSR_WRITE_4(sc, IWI_CSR_TX4_WIDX, sc->txq[3].cur);
2531
2532	for (i = 0; i < sc->rxq.count; i++) {
2533		data = &sc->rxq.data[i];
2534		CSR_WRITE_4(sc, data->reg, data->physaddr);
2535	}
2536
2537	CSR_WRITE_4(sc, IWI_CSR_RX_WIDX, sc->rxq.count - 1);
2538
2539	if (iwi_load_firmware(sc, fw->main, fw->main_size) != 0) {
2540		device_printf(sc->sc_dev, "could not load main firmware\n");
2541		goto fail;
2542	}
2543
2544	sc->flags |= IWI_FLAG_FW_INITED;
2545
2546	if (iwi_config(sc) != 0) {
2547		device_printf(sc->sc_dev, "device configuration failed\n");
2548		goto fail;
2549	}
2550
2551	if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2552		if (ic->ic_roaming != IEEE80211_ROAMING_MANUAL)
2553			ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
2554	} else
2555		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
2556
2557	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
2558	ifp->if_drv_flags |= IFF_DRV_RUNNING;
2559
2560	return;
2561
2562fail:	ifp->if_flags &= ~IFF_UP;
2563	iwi_stop(sc);
2564}
2565
2566static void
2567iwi_stop(void *priv)
2568{
2569	struct iwi_softc *sc = priv;
2570	struct ieee80211com *ic = &sc->sc_ic;
2571	struct ifnet *ifp = ic->ic_ifp;
2572
2573	iwi_stop_master(sc);
2574
2575	CSR_WRITE_4(sc, IWI_CSR_RST, IWI_RST_SOFT_RESET);
2576
2577	/* reset rings */
2578	iwi_reset_cmd_ring(sc, &sc->cmdq);
2579	iwi_reset_tx_ring(sc, &sc->txq[0]);
2580	iwi_reset_tx_ring(sc, &sc->txq[1]);
2581	iwi_reset_tx_ring(sc, &sc->txq[2]);
2582	iwi_reset_tx_ring(sc, &sc->txq[3]);
2583	iwi_reset_rx_ring(sc, &sc->rxq);
2584
2585	sc->sc_tx_timer = 0;
2586	ifp->if_timer = 0;
2587	ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
2588
2589	ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
2590}
2591
2592static int
2593iwi_sysctl_stats(SYSCTL_HANDLER_ARGS)
2594{
2595	struct iwi_softc *sc = arg1;
2596	uint32_t size, buf[128];
2597
2598	if (!(sc->flags & IWI_FLAG_FW_INITED)) {
2599		memset(buf, 0, sizeof buf);
2600		return SYSCTL_OUT(req, buf, sizeof buf);
2601	}
2602
2603	size = min(CSR_READ_4(sc, IWI_CSR_TABLE0_SIZE), 128 - 1);
2604	CSR_READ_REGION_4(sc, IWI_CSR_TABLE0_BASE, &buf[1], size);
2605
2606	return SYSCTL_OUT(req, buf, sizeof buf);
2607}
2608
2609static int
2610iwi_sysctl_radio(SYSCTL_HANDLER_ARGS)
2611{
2612	struct iwi_softc *sc = arg1;
2613	int val;
2614
2615	val = (CSR_READ_4(sc, IWI_CSR_IO) & IWI_IO_RADIO_ENABLED) ? 1 : 0;
2616
2617	return SYSCTL_OUT(req, &val, sizeof val);
2618}
2619