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