if_iwn.c revision 184233
1/*-
2 * Copyright (c) 2007
3 *	Damien Bergamini <damien.bergamini@free.fr>
4 * Copyright (c) 2008
5 *	Benjamin Close <benjsc@FreeBSD.org>
6 * Copyright (c) 2008 Sam Leffler, Errno Consulting
7 *
8 * Permission to use, copy, modify, and distribute this software for any
9 * purpose with or without fee is hereby granted, provided that the above
10 * copyright notice and this permission notice appear in all copies.
11 *
12 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 */
20
21/*
22 * Driver for Intel Wireless WiFi Link 4965AGN 802.11 network adapters.
23 */
24
25#include <sys/cdefs.h>
26__FBSDID("$FreeBSD: head/sys/dev/iwn/if_iwn.c 184233 2008-10-24 21:21:43Z mav $");
27
28#include <sys/param.h>
29#include <sys/sockio.h>
30#include <sys/sysctl.h>
31#include <sys/mbuf.h>
32#include <sys/kernel.h>
33#include <sys/socket.h>
34#include <sys/systm.h>
35#include <sys/malloc.h>
36#include <sys/bus.h>
37#include <sys/rman.h>
38#include <sys/endian.h>
39#include <sys/firmware.h>
40#include <sys/limits.h>
41#include <sys/module.h>
42#include <sys/queue.h>
43#include <sys/taskqueue.h>
44
45#include <machine/bus.h>
46#include <machine/resource.h>
47#include <machine/clock.h>
48
49#include <dev/pci/pcireg.h>
50#include <dev/pci/pcivar.h>
51
52#include <net/bpf.h>
53#include <net/if.h>
54#include <net/if_arp.h>
55#include <net/ethernet.h>
56#include <net/if_dl.h>
57#include <net/if_media.h>
58#include <net/if_types.h>
59
60#include <netinet/in.h>
61#include <netinet/in_systm.h>
62#include <netinet/in_var.h>
63#include <netinet/if_ether.h>
64#include <netinet/ip.h>
65
66#include <net80211/ieee80211_var.h>
67#include <net80211/ieee80211_amrr.h>
68#include <net80211/ieee80211_radiotap.h>
69#include <net80211/ieee80211_regdomain.h>
70
71#include <dev/iwn/if_iwnreg.h>
72#include <dev/iwn/if_iwnvar.h>
73
74static int	iwn_probe(device_t);
75static int	iwn_attach(device_t);
76static int 	iwn_detach(device_t);
77static int	iwn_cleanup(device_t);
78static struct ieee80211vap *iwn_vap_create(struct ieee80211com *,
79		    const char name[IFNAMSIZ], int unit, int opmode,
80		    int flags, const uint8_t bssid[IEEE80211_ADDR_LEN],
81		    const uint8_t mac[IEEE80211_ADDR_LEN]);
82static void	iwn_vap_delete(struct ieee80211vap *);
83static int	iwn_shutdown(device_t);
84static int	iwn_suspend(device_t);
85static int	iwn_resume(device_t);
86static int	iwn_dma_contig_alloc(struct iwn_softc *, struct iwn_dma_info *,
87		    void **, bus_size_t, bus_size_t, int);
88static void	iwn_dma_contig_free(struct iwn_dma_info *);
89int		iwn_alloc_shared(struct iwn_softc *);
90void		iwn_free_shared(struct iwn_softc *);
91int		iwn_alloc_kw(struct iwn_softc *);
92void		iwn_free_kw(struct iwn_softc *);
93int		iwn_alloc_fwmem(struct iwn_softc *);
94void		iwn_free_fwmem(struct iwn_softc *);
95struct		iwn_rbuf *iwn_alloc_rbuf(struct iwn_softc *);
96void		iwn_free_rbuf(void *, void *);
97int		iwn_alloc_rpool(struct iwn_softc *);
98void		iwn_free_rpool(struct iwn_softc *);
99int		iwn_alloc_rx_ring(struct iwn_softc *, struct iwn_rx_ring *);
100void		iwn_reset_rx_ring(struct iwn_softc *, struct iwn_rx_ring *);
101void		iwn_free_rx_ring(struct iwn_softc *, struct iwn_rx_ring *);
102int		iwn_alloc_tx_ring(struct iwn_softc *, struct iwn_tx_ring *,
103		    int);
104void		iwn_reset_tx_ring(struct iwn_softc *, struct iwn_tx_ring *);
105void		iwn_free_tx_ring(struct iwn_softc *, struct iwn_tx_ring *);
106static struct ieee80211_node *iwn_node_alloc(struct ieee80211vap *,
107		    const uint8_t [IEEE80211_ADDR_LEN]);
108void		iwn_newassoc(struct ieee80211_node *, int);
109int		iwn_media_change(struct ifnet *);
110int		iwn_newstate(struct ieee80211vap *, enum ieee80211_state, int);
111void		iwn_mem_lock(struct iwn_softc *);
112void		iwn_mem_unlock(struct iwn_softc *);
113uint32_t	iwn_mem_read(struct iwn_softc *, uint32_t);
114void		iwn_mem_write(struct iwn_softc *, uint32_t, uint32_t);
115void		iwn_mem_write_region_4(struct iwn_softc *, uint32_t,
116		    const uint32_t *, int);
117int		iwn_eeprom_lock(struct iwn_softc *);
118void		iwn_eeprom_unlock(struct iwn_softc *);
119int		iwn_read_prom_data(struct iwn_softc *, uint32_t, void *, int);
120int		iwn_transfer_microcode(struct iwn_softc *, const uint8_t *, int);
121int		iwn_transfer_firmware(struct iwn_softc *);
122int		iwn_load_firmware(struct iwn_softc *);
123void		iwn_unload_firmware(struct iwn_softc *);
124static void	iwn_timer_timeout(void *);
125static void	iwn_calib_reset(struct iwn_softc *);
126void		iwn_ampdu_rx_start(struct iwn_softc *, struct iwn_rx_desc *);
127void		iwn_rx_intr(struct iwn_softc *, struct iwn_rx_desc *,
128		    struct iwn_rx_data *);
129void		iwn_rx_statistics(struct iwn_softc *, struct iwn_rx_desc *);
130void		iwn_tx_intr(struct iwn_softc *, struct iwn_rx_desc *);
131void		iwn_cmd_intr(struct iwn_softc *, struct iwn_rx_desc *);
132static void	iwn_bmiss(void *, int);
133void		iwn_notif_intr(struct iwn_softc *);
134void		iwn_intr(void *);
135void		iwn_read_eeprom(struct iwn_softc *);
136static void	iwn_read_eeprom_channels(struct iwn_softc *);
137void		iwn_print_power_group(struct iwn_softc *, int);
138uint8_t		iwn_plcp_signal(int);
139int		iwn_tx_data(struct iwn_softc *, struct mbuf *,
140		    struct ieee80211_node *, struct iwn_tx_ring *);
141void		iwn_start(struct ifnet *);
142void		iwn_start_locked(struct ifnet *);
143static int	iwn_raw_xmit(struct ieee80211_node *, struct mbuf *,
144		    const struct ieee80211_bpf_params *);
145static void	iwn_watchdog(struct iwn_softc *);
146int		iwn_ioctl(struct ifnet *, u_long, caddr_t);
147int		iwn_cmd(struct iwn_softc *, int, const void *, int, int);
148int		iwn_set_link_quality(struct iwn_softc *, uint8_t,
149		    const struct ieee80211_channel *, int);
150int		iwn_set_key(struct ieee80211com *, struct ieee80211_node *,
151		    const struct ieee80211_key *);
152int		iwn_wme_update(struct ieee80211com *);
153void		iwn_set_led(struct iwn_softc *, uint8_t, uint8_t, uint8_t);
154int		iwn_set_critical_temp(struct iwn_softc *);
155void		iwn_enable_tsf(struct iwn_softc *, struct ieee80211_node *);
156void		iwn_power_calibration(struct iwn_softc *, int);
157int		iwn_set_txpower(struct iwn_softc *,
158		    struct ieee80211_channel *, int);
159int8_t		iwn_get_rssi(struct iwn_softc *, const struct iwn_rx_stat *);
160int		iwn_get_noise(const struct iwn_rx_general_stats *);
161int		iwn_get_temperature(struct iwn_softc *);
162int		iwn_init_sensitivity(struct iwn_softc *);
163void		iwn_compute_differential_gain(struct iwn_softc *,
164		    const struct iwn_rx_general_stats *);
165void		iwn_tune_sensitivity(struct iwn_softc *,
166		    const struct iwn_rx_stats *);
167int		iwn_send_sensitivity(struct iwn_softc *);
168int		iwn_auth(struct iwn_softc *);
169int		iwn_run(struct iwn_softc *);
170int		iwn_scan(struct iwn_softc *);
171int		iwn_config(struct iwn_softc *);
172void		iwn_post_alive(struct iwn_softc *);
173void		iwn_stop_master(struct iwn_softc *);
174int		iwn_reset(struct iwn_softc *);
175void		iwn_hw_config(struct iwn_softc *);
176void		iwn_init_locked(struct iwn_softc *);
177void		iwn_init(void *);
178void		iwn_stop_locked(struct iwn_softc *);
179void		iwn_stop(struct iwn_softc *);
180static void 	iwn_scan_start(struct ieee80211com *);
181static void 	iwn_scan_end(struct ieee80211com *);
182static void 	iwn_set_channel(struct ieee80211com *);
183static void 	iwn_scan_curchan(struct ieee80211_scan_state *, unsigned long);
184static void 	iwn_scan_mindwell(struct ieee80211_scan_state *);
185static void 	iwn_ops(void *, int);
186static int 	iwn_queue_cmd( struct iwn_softc *, int, int, int);
187static void	iwn_bpfattach(struct iwn_softc *);
188static void	iwn_sysctlattach(struct iwn_softc *);
189
190#define IWN_DEBUG
191#ifdef IWN_DEBUG
192enum {
193	IWN_DEBUG_XMIT		= 0x00000001,	/* basic xmit operation */
194	IWN_DEBUG_RECV		= 0x00000002,	/* basic recv operation */
195	IWN_DEBUG_STATE		= 0x00000004,	/* 802.11 state transitions */
196	IWN_DEBUG_TXPOW		= 0x00000008,	/* tx power processing */
197	IWN_DEBUG_RESET		= 0x00000010,	/* reset processing */
198	IWN_DEBUG_OPS		= 0x00000020,	/* iwn_ops processing */
199	IWN_DEBUG_BEACON 	= 0x00000040,	/* beacon handling */
200	IWN_DEBUG_WATCHDOG 	= 0x00000080,	/* watchdog timeout */
201	IWN_DEBUG_INTR		= 0x00000100,	/* ISR */
202	IWN_DEBUG_CALIBRATE	= 0x00000200,	/* periodic calibration */
203	IWN_DEBUG_NODE		= 0x00000400,	/* node management */
204	IWN_DEBUG_LED		= 0x00000800,	/* led management */
205	IWN_DEBUG_CMD		= 0x00001000,	/* cmd submission */
206	IWN_DEBUG_FATAL		= 0x80000000,	/* fatal errors */
207	IWN_DEBUG_ANY		= 0xffffffff
208};
209
210#define DPRINTF(sc, m, fmt, ...) do {			\
211	if (sc->sc_debug & (m))				\
212		printf(fmt, __VA_ARGS__);		\
213} while (0)
214
215static const char *iwn_ops_str(int);
216static const char *iwn_intr_str(uint8_t);
217#else
218#define DPRINTF(sc, m, fmt, ...) do { (void) sc; } while (0)
219#endif
220
221struct iwn_ident {
222	uint16_t	vendor;
223	uint16_t	device;
224	const char	*name;
225};
226
227static const struct iwn_ident iwn_ident_table [] = {
228        { 0x8086, 0x4229, "Intel(R) PRO/Wireless 4965BGN" },
229        { 0x8086, 0x422D, "Intel(R) PRO/Wireless 4965BGN" },
230        { 0x8086, 0x4230, "Intel(R) PRO/Wireless 4965BGN" },
231        { 0x8086, 0x4233, "Intel(R) PRO/Wireless 4965BGN" },
232        { 0, 0, NULL }
233};
234
235static int
236iwn_probe(device_t dev)
237{
238        const struct iwn_ident *ident;
239
240        for (ident = iwn_ident_table; ident->name != NULL; ident++) {
241                if (pci_get_vendor(dev) == ident->vendor &&
242                    pci_get_device(dev) == ident->device) {
243                        device_set_desc(dev, ident->name);
244                        return 0;
245                }
246        }
247        return ENXIO;
248}
249
250static int
251iwn_attach(device_t dev)
252{
253	struct iwn_softc *sc = (struct iwn_softc *)device_get_softc(dev);
254	struct ieee80211com *ic;
255	struct ifnet *ifp;
256	int i, error, result;
257
258	sc->sc_dev = dev;
259
260	/* XXX */
261	if (pci_get_powerstate(dev) != PCI_POWERSTATE_D0) {
262		device_printf(dev, "chip is in D%d power mode "
263		    "-- setting to D0\n", pci_get_powerstate(dev));
264		pci_set_powerstate(dev, PCI_POWERSTATE_D0);
265	}
266
267	/* clear device specific PCI configuration register 0x41 */
268	pci_write_config(dev, 0x41, 0, 1);
269
270	/* enable bus-mastering */
271	pci_enable_busmaster(dev);
272
273	sc->mem_rid= PCIR_BAR(0);
274	sc->mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &sc->mem_rid,
275					 RF_ACTIVE);
276	if (sc->mem == NULL ) {
277		device_printf(dev, "could not allocate memory resources\n");
278		error = ENOMEM;
279		return error;
280	}
281
282	sc->sc_st = rman_get_bustag(sc->mem);
283	sc->sc_sh = rman_get_bushandle(sc->mem);
284	sc->irq_rid = 0;
285	if ((result = pci_msi_count(dev)) == 1 &&
286	    pci_alloc_msi(dev, &result) == 0)
287		sc->irq_rid = 1;
288	sc->irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &sc->irq_rid,
289					 RF_ACTIVE | RF_SHAREABLE);
290	if (sc->irq == NULL) {
291		device_printf(dev, "could not allocate interrupt resource\n");
292		error = ENOMEM;
293		return error;
294	}
295
296	IWN_LOCK_INIT(sc);
297	IWN_CMD_LOCK_INIT(sc);
298	callout_init_mtx(&sc->sc_timer_to, &sc->sc_mtx, 0);
299
300        /*
301         * Create the taskqueues used by the driver. Primarily
302         * sc_tq handles most the task
303         */
304        sc->sc_tq = taskqueue_create("iwn_taskq", M_NOWAIT | M_ZERO,
305                taskqueue_thread_enqueue, &sc->sc_tq);
306        taskqueue_start_threads(&sc->sc_tq, 1, PI_NET, "%s taskq",
307                device_get_nameunit(dev));
308
309        TASK_INIT(&sc->sc_ops_task, 0, iwn_ops, sc );
310	TASK_INIT(&sc->sc_bmiss_task, 0, iwn_bmiss, sc);
311
312	/*
313	 * Put adapter into a known state.
314	 */
315	error = iwn_reset(sc);
316	if (error != 0) {
317		device_printf(dev,
318		    "could not reset adapter, error %d\n", error);
319		goto fail;
320	}
321
322	/*
323	 * Allocate DMA memory for firmware transfers.
324	 */
325	error = iwn_alloc_fwmem(sc);
326	if (error != 0) {
327		device_printf(dev,
328		    "could not allocate firmware memory, error %d\n", error);
329		goto fail;
330	}
331
332	/*
333	 * Allocate a "keep warm" page.
334	 */
335	error = iwn_alloc_kw(sc);
336	if (error != 0) {
337		device_printf(dev,
338		    "could not allocate keep-warm page, error %d\n", error);
339		goto fail;
340	}
341
342	/*
343	 * Allocate shared area (communication area).
344	 */
345	error = iwn_alloc_shared(sc);
346	if (error != 0) {
347		device_printf(dev,
348		    "could not allocate shared area, error %d\n", error);
349		goto fail;
350	}
351
352	/*
353	 * Allocate Tx rings.
354	 */
355	for (i = 0; i < IWN_NTXQUEUES; i++) {
356		error = iwn_alloc_tx_ring(sc, &sc->txq[i], i);
357		if (error != 0) {
358			device_printf(dev,
359			    "could not allocate Tx ring %d, error %d\n",
360			    i, error);
361			goto fail;
362		}
363	}
364
365	error = iwn_alloc_rx_ring(sc, &sc->rxq);
366	if (error != 0 ){
367		device_printf(dev,
368		    "could not allocate Rx ring, error %d\n", error);
369		goto fail;
370	}
371
372	ifp = sc->sc_ifp = if_alloc(IFT_IEEE80211);
373	if (ifp == NULL) {
374		device_printf(dev, "can not allocate ifnet structure\n");
375		goto fail;
376	}
377	ic = ifp->if_l2com;
378
379	ic->ic_ifp = ifp;
380	ic->ic_phytype = IEEE80211_T_OFDM;	/* not only, but not used */
381	ic->ic_opmode = IEEE80211_M_STA;	/* default to BSS mode */
382
383	/* set device capabilities */
384	ic->ic_caps =
385		  IEEE80211_C_STA		/* station mode supported */
386		| IEEE80211_C_MONITOR		/* monitor mode supported */
387		| IEEE80211_C_TXPMGT		/* tx power management */
388		| IEEE80211_C_SHSLOT		/* short slot time supported */
389		| IEEE80211_C_WPA
390		| IEEE80211_C_SHPREAMBLE	/* short preamble supported */
391#if 0
392		| IEEE80211_C_BGSCAN		/* background scanning */
393		| IEEE80211_C_IBSS		/* ibss/adhoc mode */
394#endif
395		| IEEE80211_C_WME		/* WME */
396		;
397#if 0
398	/* XXX disable until HT channel setup works */
399	ic->ic_htcaps =
400		  IEEE80211_HTCAP_SMPS_ENA	/* SM PS mode enabled */
401		| IEEE80211_HTCAP_CHWIDTH40	/* 40MHz channel width */
402		| IEEE80211_HTCAP_SHORTGI20	/* short GI in 20MHz */
403		| IEEE80211_HTCAP_SHORTGI40	/* short GI in 40MHz */
404		| IEEE80211_HTCAP_RXSTBC_2STREAM/* 1-2 spatial streams */
405		| IEEE80211_HTCAP_MAXAMSDU_3839	/* max A-MSDU length */
406		/* s/w capabilities */
407		| IEEE80211_HTC_HT		/* HT operation */
408		| IEEE80211_HTC_AMPDU		/* tx A-MPDU */
409		| IEEE80211_HTC_AMSDU		/* tx A-MSDU */
410		;
411#endif
412	/* read supported channels and MAC address from EEPROM */
413	iwn_read_eeprom(sc);
414
415	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
416	ifp->if_softc = sc;
417	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
418	ifp->if_init = iwn_init;
419	ifp->if_ioctl = iwn_ioctl;
420	ifp->if_start = iwn_start;
421        IFQ_SET_MAXLEN(&ifp->if_snd, IFQ_MAXLEN);
422	ifp->if_snd.ifq_drv_maxlen = IFQ_MAXLEN;
423	IFQ_SET_READY(&ifp->if_snd);
424
425	ieee80211_ifattach(ic);
426	ic->ic_vap_create = iwn_vap_create;
427	ic->ic_vap_delete = iwn_vap_delete;
428	ic->ic_raw_xmit = iwn_raw_xmit;
429	ic->ic_node_alloc = iwn_node_alloc;
430	ic->ic_newassoc = iwn_newassoc;
431        ic->ic_wme.wme_update = iwn_wme_update;
432        ic->ic_scan_start = iwn_scan_start;
433        ic->ic_scan_end = iwn_scan_end;
434        ic->ic_set_channel = iwn_set_channel;
435        ic->ic_scan_curchan = iwn_scan_curchan;
436        ic->ic_scan_mindwell = iwn_scan_mindwell;
437
438	iwn_bpfattach(sc);
439	iwn_sysctlattach(sc);
440
441        /*
442         * Hook our interrupt after all initialization is complete.
443         */
444        error = bus_setup_intr(dev, sc->irq, INTR_TYPE_NET | INTR_MPSAFE,
445	    NULL, iwn_intr, sc, &sc->sc_ih);
446        if (error != 0) {
447                device_printf(dev, "could not set up interrupt, error %d\n", error);
448                goto fail;
449        }
450
451        ieee80211_announce(ic);
452	return 0;
453fail:
454	iwn_cleanup(dev);
455	return error;
456}
457
458static int
459iwn_detach(device_t dev)
460{
461	iwn_cleanup(dev);
462        return 0;
463}
464
465/*
466 * Cleanup any device resources that were allocated
467 */
468int
469iwn_cleanup(device_t dev)
470{
471	struct iwn_softc *sc = device_get_softc(dev);
472	struct ifnet *ifp = sc->sc_ifp;
473	struct ieee80211com *ic = ifp->if_l2com;
474	int i;
475
476	if (ifp != NULL) {
477		iwn_stop(sc);
478		callout_drain(&sc->sc_timer_to);
479		bpfdetach(ifp);
480		ieee80211_ifdetach(ic);
481	}
482
483	iwn_unload_firmware(sc);
484
485	iwn_free_rx_ring(sc, &sc->rxq);
486	for (i = 0; i < IWN_NTXQUEUES; i++)
487		iwn_free_tx_ring(sc, &sc->txq[i]);
488	iwn_free_kw(sc);
489	iwn_free_fwmem(sc);
490	if (sc->irq != NULL) {
491		bus_teardown_intr(dev, sc->irq, sc->sc_ih);
492		bus_release_resource(dev, SYS_RES_IRQ, sc->irq_rid, sc->irq);
493		if (sc->irq_rid == 1)
494			pci_release_msi(dev);
495	}
496	if (sc->mem != NULL)
497		bus_release_resource(dev, SYS_RES_MEMORY, sc->mem_rid, sc->mem);
498	if (ifp != NULL)
499		if_free(ifp);
500	taskqueue_free(sc->sc_tq);
501	IWN_CMD_LOCK_DESTROY(sc);
502	IWN_LOCK_DESTROY(sc);
503	return 0;
504}
505
506static struct ieee80211vap *
507iwn_vap_create(struct ieee80211com *ic,
508	const char name[IFNAMSIZ], int unit, int opmode, int flags,
509	const uint8_t bssid[IEEE80211_ADDR_LEN],
510	const uint8_t mac[IEEE80211_ADDR_LEN])
511{
512	struct iwn_vap *ivp;
513	struct ieee80211vap *vap;
514
515	if (!TAILQ_EMPTY(&ic->ic_vaps))		/* only one at a time */
516		return NULL;
517	ivp = (struct iwn_vap *) malloc(sizeof(struct iwn_vap),
518	    M_80211_VAP, M_NOWAIT | M_ZERO);
519	if (ivp == NULL)
520		return NULL;
521	vap = &ivp->iv_vap;
522	ieee80211_vap_setup(ic, vap, name, unit, opmode, flags, bssid, mac);
523	vap->iv_bmissthreshold = 10;		/* override default */
524	/* override with driver methods */
525	ivp->iv_newstate = vap->iv_newstate;
526	vap->iv_newstate = iwn_newstate;
527
528	ieee80211_amrr_init(&ivp->iv_amrr, vap,
529	    IEEE80211_AMRR_MIN_SUCCESS_THRESHOLD,
530	    IEEE80211_AMRR_MAX_SUCCESS_THRESHOLD,
531	    500 /*ms*/);
532
533	/* complete setup */
534	ieee80211_vap_attach(vap, ieee80211_media_change, ieee80211_media_status);
535	ic->ic_opmode = opmode;
536	return vap;
537}
538
539static void
540iwn_vap_delete(struct ieee80211vap *vap)
541{
542	struct iwn_vap *ivp = IWN_VAP(vap);
543
544	ieee80211_amrr_cleanup(&ivp->iv_amrr);
545	ieee80211_vap_detach(vap);
546	free(ivp, M_80211_VAP);
547}
548
549static int
550iwn_shutdown(device_t dev)
551{
552	struct iwn_softc *sc = device_get_softc(dev);
553
554	iwn_stop(sc);
555	return 0;
556}
557
558static int
559iwn_suspend(device_t dev)
560{
561	struct iwn_softc *sc = device_get_softc(dev);
562
563	iwn_stop(sc);
564	return 0;
565}
566
567static int
568iwn_resume(device_t dev)
569{
570	struct iwn_softc *sc = device_get_softc(dev);
571	struct ifnet *ifp = sc->sc_ifp;
572
573	pci_write_config(dev, 0x41, 0, 1);
574
575	if (ifp->if_flags & IFF_UP)
576		iwn_init(sc);
577	return 0;
578}
579
580static void
581iwn_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
582{
583        if (error != 0)
584                return;
585        KASSERT(nsegs == 1, ("too many DMA segments, %d should be 1", nsegs));
586        *(bus_addr_t *)arg = segs[0].ds_addr;
587}
588
589static int
590iwn_dma_contig_alloc(struct iwn_softc *sc, struct iwn_dma_info *dma,
591	void **kvap, bus_size_t size, bus_size_t alignment, int flags)
592{
593	int error, lalignment, i;
594
595	/*
596	 * FreeBSD can't guarrenty 16k alignment at the moment (11/2007) so
597	 * we allocate an extra 12k with 4k alignement and walk through
598	 * it trying to find where the alignment is. It's a nasty fix for
599	 * a bigger problem.
600	*/
601	DPRINTF(sc, IWN_DEBUG_RESET,
602	    "Size: %zd - alignment %zd\n", size, alignment);
603	if (alignment == 0x4000) {
604		size += 12*1024;
605		lalignment = 4096;
606		DPRINTF(sc, IWN_DEBUG_RESET, "%s\n",
607		    "Attempting to find a 16k boundary");
608	} else
609		lalignment = alignment;
610	dma->size = size;
611	dma->tag = NULL;
612
613	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), lalignment,
614	    0, BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, size,
615	    1, size, flags, NULL, NULL, &dma->tag);
616	if (error != 0) {
617		device_printf(sc->sc_dev,
618		    "%s: bus_dma_tag_create failed, error %d\n",
619		    __func__, error);
620		goto fail;
621	}
622	error = bus_dmamem_alloc(dma->tag, (void **)&dma->vaddr,
623	    flags | BUS_DMA_ZERO, &dma->map);
624	if (error != 0) {
625		device_printf(sc->sc_dev,
626		   "%s: bus_dmamem_alloc failed, error %d\n",
627		   __func__, error);
628		goto fail;
629	}
630	if (alignment == 0x4000) {
631		for (i = 0; i < 3 && (((uintptr_t)dma->vaddr) & 0x3fff); i++) {
632			DPRINTF(sc, IWN_DEBUG_RESET,  "%s\n",
633			    "Memory Unaligned, shifting pointer by 4k");
634			dma->vaddr += 4096;
635			size -= 4096;
636		}
637		if ((((uintptr_t)dma->vaddr ) & (alignment-1))) {
638			DPRINTF(sc, IWN_DEBUG_ANY,
639			    "%s: failed to align memory, vaddr %p, align %zd\n",
640			    __func__, dma->vaddr, alignment);
641			error = ENOMEM;
642			goto fail;
643		}
644	}
645
646	error = bus_dmamap_load(dma->tag, dma->map, dma->vaddr,
647	    size, iwn_dma_map_addr, &dma->paddr, flags);
648	if (error != 0) {
649		device_printf(sc->sc_dev,
650		    "%s: bus_dmamap_load failed, error %d\n", __func__, error);
651		goto fail;
652	}
653
654	if (kvap != NULL)
655		*kvap = dma->vaddr;
656	return 0;
657fail:
658	iwn_dma_contig_free(dma);
659	return error;
660}
661
662static void
663iwn_dma_contig_free(struct iwn_dma_info *dma)
664{
665	if (dma->tag != NULL) {
666		if (dma->map != NULL) {
667			if (dma->paddr == 0) {
668				bus_dmamap_sync(dma->tag, dma->map,
669				    BUS_DMASYNC_POSTREAD|BUS_DMASYNC_POSTWRITE);
670				bus_dmamap_unload(dma->tag, dma->map);
671			}
672			bus_dmamem_free(dma->tag, &dma->vaddr, dma->map);
673		}
674		bus_dma_tag_destroy(dma->tag);
675	}
676}
677
678int
679iwn_alloc_shared(struct iwn_softc *sc)
680{
681	/* must be aligned on a 1KB boundary */
682	return iwn_dma_contig_alloc(sc, &sc->shared_dma,
683	    (void **)&sc->shared, sizeof (struct iwn_shared), 1024,
684	    BUS_DMA_NOWAIT);
685}
686
687void
688iwn_free_shared(struct iwn_softc *sc)
689{
690	iwn_dma_contig_free(&sc->shared_dma);
691}
692
693int
694iwn_alloc_kw(struct iwn_softc *sc)
695{
696	/* must be aligned on a 4k boundary */
697	return iwn_dma_contig_alloc(sc, &sc->kw_dma, NULL,
698	    PAGE_SIZE, PAGE_SIZE, BUS_DMA_NOWAIT);
699}
700
701void
702iwn_free_kw(struct iwn_softc *sc)
703{
704	iwn_dma_contig_free(&sc->kw_dma);
705}
706
707int
708iwn_alloc_fwmem(struct iwn_softc *sc)
709{
710	/* allocate enough contiguous space to store text and data */
711	return iwn_dma_contig_alloc(sc, &sc->fw_dma, NULL,
712	    IWN_FW_MAIN_TEXT_MAXSZ + IWN_FW_MAIN_DATA_MAXSZ, 16,
713	    BUS_DMA_NOWAIT);
714}
715
716void
717iwn_free_fwmem(struct iwn_softc *sc)
718{
719	iwn_dma_contig_free(&sc->fw_dma);
720}
721
722int
723iwn_alloc_rx_ring(struct iwn_softc *sc, struct iwn_rx_ring *ring)
724{
725	int i, error;
726
727	ring->cur = 0;
728
729	error = iwn_dma_contig_alloc(sc, &ring->desc_dma,
730	    (void **)&ring->desc, IWN_RX_RING_COUNT * sizeof (uint32_t),
731	    IWN_RING_DMA_ALIGN, BUS_DMA_NOWAIT);
732	if (error != 0) {
733		device_printf(sc->sc_dev,
734		    "%s: could not allocate rx ring DMA memory, error %d\n",
735		    __func__, error);
736		goto fail;
737	}
738
739        error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 1, 0,
740	    BUS_SPACE_MAXADDR_32BIT,
741            BUS_SPACE_MAXADDR, NULL, NULL, MJUMPAGESIZE, 1,
742            MJUMPAGESIZE, BUS_DMA_NOWAIT, NULL, NULL, &ring->data_dmat);
743        if (error != 0) {
744                device_printf(sc->sc_dev,
745		    "%s: bus_dma_tag_create_failed, error %d\n",
746		    __func__, error);
747                goto fail;
748        }
749
750	/*
751	 * Setup Rx buffers.
752	 */
753	for (i = 0; i < IWN_RX_RING_COUNT; i++) {
754		struct iwn_rx_data *data = &ring->data[i];
755		struct mbuf *m;
756		bus_addr_t paddr;
757
758		error = bus_dmamap_create(ring->data_dmat, 0, &data->map);
759		if (error != 0) {
760			device_printf(sc->sc_dev,
761			    "%s: bus_dmamap_create failed, error %d\n",
762			    __func__, error);
763			goto fail;
764		}
765		m = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, MJUMPAGESIZE);
766		if (m == NULL) {
767			device_printf(sc->sc_dev,
768			   "%s: could not allocate rx mbuf\n", __func__);
769			error = ENOMEM;
770			goto fail;
771		}
772		/* map page */
773		error = bus_dmamap_load(ring->data_dmat, data->map,
774		    mtod(m, caddr_t), MJUMPAGESIZE,
775		    iwn_dma_map_addr, &paddr, BUS_DMA_NOWAIT);
776		if (error != 0 && error != EFBIG) {
777			device_printf(sc->sc_dev,
778			    "%s: bus_dmamap_load failed, error %d\n",
779			    __func__, error);
780			m_freem(m);
781			error = ENOMEM;	/* XXX unique code */
782			goto fail;
783		}
784		bus_dmamap_sync(ring->data_dmat, data->map,
785		    BUS_DMASYNC_PREWRITE);
786
787		data->m = m;
788		/* Rx buffers are aligned on a 256-byte boundary */
789		ring->desc[i] = htole32(paddr >> 8);
790	}
791	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
792	    BUS_DMASYNC_PREWRITE);
793	return 0;
794fail:
795	iwn_free_rx_ring(sc, ring);
796	return error;
797}
798
799void
800iwn_reset_rx_ring(struct iwn_softc *sc, struct iwn_rx_ring *ring)
801{
802	int ntries;
803
804	iwn_mem_lock(sc);
805
806	IWN_WRITE(sc, IWN_RX_CONFIG, 0);
807	for (ntries = 0; ntries < 100; ntries++) {
808		if (IWN_READ(sc, IWN_RX_STATUS) & IWN_RX_IDLE)
809			break;
810		DELAY(10);
811	}
812#ifdef IWN_DEBUG
813	if (ntries == 100)
814		DPRINTF(sc, IWN_DEBUG_ANY, "%s\n", "timeout resetting Rx ring");
815#endif
816	iwn_mem_unlock(sc);
817
818	ring->cur = 0;
819}
820
821void
822iwn_free_rx_ring(struct iwn_softc *sc, struct iwn_rx_ring *ring)
823{
824	int i;
825
826	iwn_dma_contig_free(&ring->desc_dma);
827
828	for (i = 0; i < IWN_RX_RING_COUNT; i++)
829		if (ring->data[i].m != NULL)
830			m_freem(ring->data[i].m);
831}
832
833int
834iwn_alloc_tx_ring(struct iwn_softc *sc, struct iwn_tx_ring *ring, int qid)
835{
836	bus_size_t size;
837	int i, error;
838
839	ring->qid = qid;
840	ring->queued = 0;
841	ring->cur = 0;
842
843	size = IWN_TX_RING_COUNT * sizeof(struct iwn_tx_desc);
844	error = iwn_dma_contig_alloc(sc, &ring->desc_dma,
845	    (void **)&ring->desc, size, IWN_RING_DMA_ALIGN, BUS_DMA_NOWAIT);
846	if (error != 0) {
847		device_printf(sc->sc_dev,
848		    "%s: could not allocate tx ring DMA memory, error %d\n",
849		    __func__, error);
850		goto fail;
851	}
852
853	size = IWN_TX_RING_COUNT * sizeof(struct iwn_tx_cmd);
854	error = iwn_dma_contig_alloc(sc, &ring->cmd_dma,
855	    (void **)&ring->cmd, size, 4, BUS_DMA_NOWAIT);
856	if (error != 0) {
857		device_printf(sc->sc_dev,
858		    "%s: could not allocate tx cmd DMA memory, error %d\n",
859		    __func__, error);
860		goto fail;
861	}
862
863        error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 1, 0,
864	    BUS_SPACE_MAXADDR_32BIT,
865            BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES, IWN_MAX_SCATTER - 1,
866            MCLBYTES, BUS_DMA_NOWAIT, NULL, NULL, &ring->data_dmat);
867        if (error != 0) {
868                device_printf(sc->sc_dev,
869		    "%s: bus_dma_tag_create_failed, error %d\n",
870		    __func__, error);
871                goto fail;
872        }
873
874	for (i = 0; i < IWN_TX_RING_COUNT; i++) {
875		struct iwn_tx_data *data = &ring->data[i];
876
877		error = bus_dmamap_create(ring->data_dmat, 0, &data->map);
878		if (error != 0) {
879			device_printf(sc->sc_dev,
880			    "%s: bus_dmamap_create failed, error %d\n",
881			    __func__, error);
882			goto fail;
883		}
884		bus_dmamap_sync(ring->data_dmat, data->map,
885		    BUS_DMASYNC_PREWRITE);
886	}
887	return 0;
888fail:
889	iwn_free_tx_ring(sc, ring);
890	return error;
891}
892
893void
894iwn_reset_tx_ring(struct iwn_softc *sc, struct iwn_tx_ring *ring)
895{
896	uint32_t tmp;
897	int i, ntries;
898
899	iwn_mem_lock(sc);
900
901	IWN_WRITE(sc, IWN_TX_CONFIG(ring->qid), 0);
902	for (ntries = 0; ntries < 20; ntries++) {
903		tmp = IWN_READ(sc, IWN_TX_STATUS);
904		if ((tmp & IWN_TX_IDLE(ring->qid)) == IWN_TX_IDLE(ring->qid))
905			break;
906		DELAY(10);
907	}
908#ifdef IWN_DEBUG
909	if (ntries == 20)
910		DPRINTF(sc, IWN_DEBUG_RESET,
911		    "%s: timeout resetting Tx ring %d\n", __func__, ring->qid);
912#endif
913	iwn_mem_unlock(sc);
914
915	for (i = 0; i < IWN_TX_RING_COUNT; i++) {
916		struct iwn_tx_data *data = &ring->data[i];
917
918		if (data->m != NULL) {
919			bus_dmamap_unload(ring->data_dmat, data->map);
920			m_freem(data->m);
921			data->m = NULL;
922		}
923	}
924
925	ring->queued = 0;
926	ring->cur = 0;
927}
928
929void
930iwn_free_tx_ring(struct iwn_softc *sc, struct iwn_tx_ring *ring)
931{
932	int i;
933
934	iwn_dma_contig_free(&ring->desc_dma);
935	iwn_dma_contig_free(&ring->cmd_dma);
936
937	if (ring->data != NULL) {
938		for (i = 0; i < IWN_TX_RING_COUNT; i++) {
939			struct iwn_tx_data *data = &ring->data[i];
940
941			if (data->m != NULL) {
942				bus_dmamap_unload(ring->data_dmat, data->map);
943				m_freem(data->m);
944			}
945		}
946	}
947}
948
949struct ieee80211_node *
950iwn_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
951{
952	return malloc(sizeof (struct iwn_node), M_80211_NODE,M_NOWAIT | M_ZERO);
953}
954
955void
956iwn_newassoc(struct ieee80211_node *ni, int isnew)
957{
958	struct ieee80211vap *vap = ni->ni_vap;
959
960	ieee80211_amrr_node_init(&IWN_VAP(vap)->iv_amrr,
961	   &IWN_NODE(ni)->amn, ni);
962}
963
964int
965iwn_media_change(struct ifnet *ifp)
966{
967	int error = ieee80211_media_change(ifp);
968	/* NB: only the fixed rate can change and that doesn't need a reset */
969	return (error == ENETRESET ? 0 : error);
970}
971
972int
973iwn_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
974{
975	struct iwn_vap *ivp = IWN_VAP(vap);
976	struct ieee80211com *ic = vap->iv_ic;
977	struct iwn_softc *sc = ic->ic_ifp->if_softc;
978	int error;
979
980	DPRINTF(sc, IWN_DEBUG_STATE, "%s: %s -> %s\n", __func__,
981		ieee80211_state_name[vap->iv_state],
982		ieee80211_state_name[nstate]);
983
984	IWN_LOCK(sc);
985	callout_stop(&sc->sc_timer_to);
986	IWN_UNLOCK(sc);
987
988	/*
989	 * Some state transitions require issuing a configure request
990	 * to the adapter.  This must be done in a blocking context
991	 * so we toss control to the task q thread where the state
992	 * change will be finished after the command completes.
993	 */
994	if (nstate == IEEE80211_S_AUTH && vap->iv_state != IEEE80211_S_AUTH) {
995		/* !AUTH -> AUTH requires adapter config */
996		error = iwn_queue_cmd(sc, IWN_AUTH, arg, IWN_QUEUE_NORMAL);
997		return (error != 0 ? error : EINPROGRESS);
998	}
999	if (nstate == IEEE80211_S_RUN && vap->iv_state != IEEE80211_S_RUN) {
1000		/*
1001		 * !RUN -> RUN requires setting the association id
1002		 * which is done with a firmware cmd.  We also defer
1003		 * starting the timers until that work is done.
1004		 */
1005		error = iwn_queue_cmd(sc, IWN_RUN, arg, IWN_QUEUE_NORMAL);
1006		return (error != 0 ? error : EINPROGRESS);
1007	}
1008	if (nstate == IEEE80211_S_RUN) {
1009		/*
1010		 * RUN -> RUN transition; just restart the timers.
1011		 */
1012		iwn_calib_reset(sc);
1013	}
1014	return ivp->iv_newstate(vap, nstate, arg);
1015}
1016
1017/*
1018 * Grab exclusive access to NIC memory.
1019 */
1020void
1021iwn_mem_lock(struct iwn_softc *sc)
1022{
1023	uint32_t tmp;
1024	int ntries;
1025
1026	tmp = IWN_READ(sc, IWN_GPIO_CTL);
1027	IWN_WRITE(sc, IWN_GPIO_CTL, tmp | IWN_GPIO_MAC);
1028
1029	/* spin until we actually get the lock */
1030	for (ntries = 0; ntries < 1000; ntries++) {
1031		if ((IWN_READ(sc, IWN_GPIO_CTL) &
1032		    (IWN_GPIO_CLOCK | IWN_GPIO_SLEEP)) == IWN_GPIO_CLOCK)
1033			break;
1034		DELAY(10);
1035	}
1036	if (ntries == 1000)
1037		device_printf(sc->sc_dev,
1038		    "%s: could not lock memory\n", __func__);
1039}
1040
1041/*
1042 * Release lock on NIC memory.
1043 */
1044void
1045iwn_mem_unlock(struct iwn_softc *sc)
1046{
1047	uint32_t tmp = IWN_READ(sc, IWN_GPIO_CTL);
1048	IWN_WRITE(sc, IWN_GPIO_CTL, tmp & ~IWN_GPIO_MAC);
1049}
1050
1051uint32_t
1052iwn_mem_read(struct iwn_softc *sc, uint32_t addr)
1053{
1054	IWN_WRITE(sc, IWN_READ_MEM_ADDR, IWN_MEM_4 | addr);
1055	return IWN_READ(sc, IWN_READ_MEM_DATA);
1056}
1057
1058void
1059iwn_mem_write(struct iwn_softc *sc, uint32_t addr, uint32_t data)
1060{
1061	IWN_WRITE(sc, IWN_WRITE_MEM_ADDR, IWN_MEM_4 | addr);
1062	IWN_WRITE(sc, IWN_WRITE_MEM_DATA, data);
1063}
1064
1065void
1066iwn_mem_write_region_4(struct iwn_softc *sc, uint32_t addr,
1067    const uint32_t *data, int wlen)
1068{
1069	for (; wlen > 0; wlen--, data++, addr += 4)
1070		iwn_mem_write(sc, addr, *data);
1071}
1072
1073int
1074iwn_eeprom_lock(struct iwn_softc *sc)
1075{
1076	uint32_t tmp;
1077	int ntries;
1078
1079	tmp = IWN_READ(sc, IWN_HWCONFIG);
1080	IWN_WRITE(sc, IWN_HWCONFIG, tmp | IWN_HW_EEPROM_LOCKED);
1081
1082	/* spin until we actually get the lock */
1083	for (ntries = 0; ntries < 100; ntries++) {
1084		if (IWN_READ(sc, IWN_HWCONFIG) & IWN_HW_EEPROM_LOCKED)
1085			return 0;
1086		DELAY(10);
1087	}
1088	return ETIMEDOUT;
1089}
1090
1091void
1092iwn_eeprom_unlock(struct iwn_softc *sc)
1093{
1094	uint32_t tmp = IWN_READ(sc, IWN_HWCONFIG);
1095	IWN_WRITE(sc, IWN_HWCONFIG, tmp & ~IWN_HW_EEPROM_LOCKED);
1096}
1097
1098/*
1099 * Read `len' bytes from the EEPROM.  We access the EEPROM through the MAC
1100 * instead of using the traditional bit-bang method.
1101 */
1102int
1103iwn_read_prom_data(struct iwn_softc *sc, uint32_t addr, void *data, int len)
1104{
1105	uint8_t *out = data;
1106	uint32_t val;
1107	int ntries, tmp;
1108
1109	iwn_mem_lock(sc);
1110	for (; len > 0; len -= 2, addr++) {
1111		IWN_WRITE(sc, IWN_EEPROM_CTL, addr << 2);
1112		tmp = IWN_READ(sc, IWN_EEPROM_CTL);
1113		IWN_WRITE(sc, IWN_EEPROM_CTL, tmp & ~IWN_EEPROM_MSK );
1114
1115		for (ntries = 0; ntries < 10; ntries++) {
1116			if ((val = IWN_READ(sc, IWN_EEPROM_CTL)) &
1117			    IWN_EEPROM_READY)
1118				break;
1119			DELAY(5);
1120		}
1121		if (ntries == 10) {
1122			device_printf(sc->sc_dev,"could not read EEPROM\n");
1123			return ETIMEDOUT;
1124		}
1125		*out++ = val >> 16;
1126		if (len > 1)
1127			*out++ = val >> 24;
1128	}
1129	iwn_mem_unlock(sc);
1130
1131	return 0;
1132}
1133
1134/*
1135 * The firmware boot code is small and is intended to be copied directly into
1136 * the NIC internal memory.
1137 */
1138int
1139iwn_transfer_microcode(struct iwn_softc *sc, const uint8_t *ucode, int size)
1140{
1141	int ntries;
1142
1143	size /= sizeof (uint32_t);
1144
1145	iwn_mem_lock(sc);
1146
1147	/* copy microcode image into NIC memory */
1148	iwn_mem_write_region_4(sc, IWN_MEM_UCODE_BASE,
1149	    (const uint32_t *)ucode, size);
1150
1151	iwn_mem_write(sc, IWN_MEM_UCODE_SRC, 0);
1152	iwn_mem_write(sc, IWN_MEM_UCODE_DST, IWN_FW_TEXT);
1153	iwn_mem_write(sc, IWN_MEM_UCODE_SIZE, size);
1154
1155	/* run microcode */
1156	iwn_mem_write(sc, IWN_MEM_UCODE_CTL, IWN_UC_RUN);
1157
1158	/* wait for transfer to complete */
1159	for (ntries = 0; ntries < 1000; ntries++) {
1160		if (!(iwn_mem_read(sc, IWN_MEM_UCODE_CTL) & IWN_UC_RUN))
1161			break;
1162		DELAY(10);
1163	}
1164	if (ntries == 1000) {
1165		iwn_mem_unlock(sc);
1166		device_printf(sc->sc_dev,
1167		    "%s: could not load boot firmware\n", __func__);
1168		return ETIMEDOUT;
1169	}
1170	iwn_mem_write(sc, IWN_MEM_UCODE_CTL, IWN_UC_ENABLE);
1171
1172	iwn_mem_unlock(sc);
1173
1174	return 0;
1175}
1176
1177int
1178iwn_load_firmware(struct iwn_softc *sc)
1179{
1180	int error;
1181
1182	KASSERT(sc->fw_fp == NULL, ("firmware already loaded"));
1183
1184	IWN_UNLOCK(sc);
1185	/* load firmware image from disk */
1186	sc->fw_fp = firmware_get("iwnfw");
1187	if (sc->fw_fp == NULL) {
1188		device_printf(sc->sc_dev,
1189		    "%s: could not load firmare image \"iwnfw\"\n", __func__);
1190		error = EINVAL;
1191	} else
1192		error = 0;
1193	IWN_LOCK(sc);
1194	return error;
1195}
1196
1197int
1198iwn_transfer_firmware(struct iwn_softc *sc)
1199{
1200	struct iwn_dma_info *dma = &sc->fw_dma;
1201	const struct iwn_firmware_hdr *hdr;
1202	const uint8_t *init_text, *init_data, *main_text, *main_data;
1203	const uint8_t *boot_text;
1204	uint32_t init_textsz, init_datasz, main_textsz, main_datasz;
1205	uint32_t boot_textsz;
1206	int error = 0;
1207	const struct firmware *fp = sc->fw_fp;
1208
1209	/* extract firmware header information */
1210	if (fp->datasize < sizeof (struct iwn_firmware_hdr)) {
1211		device_printf(sc->sc_dev,
1212		    "%s: truncated firmware header: %zu bytes, expecting %zu\n",
1213		    __func__, fp->datasize, sizeof (struct iwn_firmware_hdr));
1214		error = EINVAL;
1215		goto fail;
1216	}
1217	hdr = (const struct iwn_firmware_hdr *)fp->data;
1218	main_textsz = le32toh(hdr->main_textsz);
1219	main_datasz = le32toh(hdr->main_datasz);
1220	init_textsz = le32toh(hdr->init_textsz);
1221	init_datasz = le32toh(hdr->init_datasz);
1222	boot_textsz = le32toh(hdr->boot_textsz);
1223
1224	/* sanity-check firmware segments sizes */
1225	if (main_textsz > IWN_FW_MAIN_TEXT_MAXSZ ||
1226	    main_datasz > IWN_FW_MAIN_DATA_MAXSZ ||
1227	    init_textsz > IWN_FW_INIT_TEXT_MAXSZ ||
1228	    init_datasz > IWN_FW_INIT_DATA_MAXSZ ||
1229	    boot_textsz > IWN_FW_BOOT_TEXT_MAXSZ ||
1230	    (boot_textsz & 3) != 0) {
1231		device_printf(sc->sc_dev,
1232		    "%s: invalid firmware header, main [%d,%d], init [%d,%d] "
1233		    "boot %d\n", __func__, main_textsz, main_datasz,
1234		    init_textsz, init_datasz, boot_textsz);
1235		error = EINVAL;
1236		goto fail;
1237	}
1238
1239	/* check that all firmware segments are present */
1240	if (fp->datasize < sizeof (struct iwn_firmware_hdr) + main_textsz +
1241	    main_datasz + init_textsz + init_datasz + boot_textsz) {
1242		device_printf(sc->sc_dev, "%s: firmware file too short: "
1243		    "%zu bytes, main [%d, %d], init [%d,%d] boot %d\n",
1244		    __func__, fp->datasize, main_textsz, main_datasz,
1245		    init_textsz, init_datasz, boot_textsz);
1246		error = EINVAL;
1247		goto fail;
1248	}
1249
1250	/* get pointers to firmware segments */
1251	main_text = (const uint8_t *)(hdr + 1);
1252	main_data = main_text + main_textsz;
1253	init_text = main_data + main_datasz;
1254	init_data = init_text + init_textsz;
1255	boot_text = init_data + init_datasz;
1256
1257	/* copy initialization images into pre-allocated DMA-safe memory */
1258	memcpy(dma->vaddr, init_data, init_datasz);
1259	memcpy(dma->vaddr + IWN_FW_INIT_DATA_MAXSZ, init_text, init_textsz);
1260
1261	/* tell adapter where to find initialization images */
1262	iwn_mem_lock(sc);
1263	iwn_mem_write(sc, IWN_MEM_DATA_BASE, dma->paddr >> 4);
1264	iwn_mem_write(sc, IWN_MEM_DATA_SIZE, init_datasz);
1265	iwn_mem_write(sc, IWN_MEM_TEXT_BASE,
1266	    (dma->paddr + IWN_FW_INIT_DATA_MAXSZ) >> 4);
1267	iwn_mem_write(sc, IWN_MEM_TEXT_SIZE, init_textsz);
1268	iwn_mem_unlock(sc);
1269
1270	/* load firmware boot code */
1271	error = iwn_transfer_microcode(sc, boot_text, boot_textsz);
1272	if (error != 0) {
1273		device_printf(sc->sc_dev,
1274		    "%s: could not load boot firmware, error %d\n",
1275		    __func__, error);
1276		goto fail;
1277	}
1278
1279	/* now press "execute" ;-) */
1280	IWN_WRITE(sc, IWN_RESET, 0);
1281
1282	/* wait at most one second for first alive notification */
1283	error = msleep(sc, &sc->sc_mtx, PCATCH, "iwninit", hz);
1284	if (error != 0) {
1285		/* this isn't what was supposed to happen.. */
1286		device_printf(sc->sc_dev,
1287		    "%s: timeout waiting for first alive notice, error %d\n",
1288		    __func__, error);
1289		goto fail;
1290	}
1291
1292	/* copy runtime images into pre-allocated DMA-safe memory */
1293	memcpy(dma->vaddr, main_data, main_datasz);
1294	memcpy(dma->vaddr + IWN_FW_MAIN_DATA_MAXSZ, main_text, main_textsz);
1295
1296	/* tell adapter where to find runtime images */
1297	iwn_mem_lock(sc);
1298	iwn_mem_write(sc, IWN_MEM_DATA_BASE, dma->paddr >> 4);
1299	iwn_mem_write(sc, IWN_MEM_DATA_SIZE, main_datasz);
1300	iwn_mem_write(sc, IWN_MEM_TEXT_BASE,
1301	    (dma->paddr + IWN_FW_MAIN_DATA_MAXSZ) >> 4);
1302	iwn_mem_write(sc, IWN_MEM_TEXT_SIZE, IWN_FW_UPDATED | main_textsz);
1303	iwn_mem_unlock(sc);
1304
1305	/* wait at most one second for second alive notification */
1306	error = msleep(sc, &sc->sc_mtx, PCATCH, "iwninit", hz);
1307	if (error != 0) {
1308		/* this isn't what was supposed to happen.. */
1309		device_printf(sc->sc_dev,
1310		   "%s: timeout waiting for second alive notice, error %d\n",
1311		   __func__, error);
1312		goto fail;
1313	}
1314	return 0;
1315fail:
1316	return error;
1317}
1318
1319void
1320iwn_unload_firmware(struct iwn_softc *sc)
1321{
1322        if (sc->fw_fp != NULL) {
1323                firmware_put(sc->fw_fp, FIRMWARE_UNLOAD);
1324                sc->fw_fp = NULL;
1325        }
1326}
1327
1328static void
1329iwn_timer_timeout(void *arg)
1330{
1331	struct iwn_softc *sc = arg;
1332
1333	IWN_LOCK_ASSERT(sc);
1334
1335	if (sc->calib_cnt && --sc->calib_cnt == 0) {
1336		DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s\n",
1337		    "send statistics request");
1338		(void) iwn_cmd(sc, IWN_CMD_GET_STATISTICS, NULL, 0, 1);
1339		sc->calib_cnt = 60;	/* do calibration every 60s */
1340	}
1341	iwn_watchdog(sc);		/* NB: piggyback tx watchdog */
1342	callout_reset(&sc->sc_timer_to, hz, iwn_timer_timeout, sc);
1343}
1344
1345static void
1346iwn_calib_reset(struct iwn_softc *sc)
1347{
1348	callout_reset(&sc->sc_timer_to, hz, iwn_timer_timeout, sc);
1349	sc->calib_cnt = 60;		/* do calibration every 60s */
1350}
1351
1352void
1353iwn_ampdu_rx_start(struct iwn_softc *sc, struct iwn_rx_desc *desc)
1354{
1355	struct iwn_rx_stat *stat;
1356
1357	DPRINTF(sc, IWN_DEBUG_RECV, "%s\n", "received AMPDU stats");
1358	/* save Rx statistics, they will be used on IWN_AMPDU_RX_DONE */
1359	stat = (struct iwn_rx_stat *)(desc + 1);
1360	memcpy(&sc->last_rx_stat, stat, sizeof (*stat));
1361	sc->last_rx_valid = 1;
1362}
1363
1364static __inline int
1365maprate(int iwnrate)
1366{
1367	switch (iwnrate) {
1368	/* CCK rates */
1369	case  10: return   2;
1370	case  20: return   4;
1371	case  55: return  11;
1372	case 110: return  22;
1373	/* OFDM rates */
1374	case 0xd: return  12;
1375	case 0xf: return  18;
1376	case 0x5: return  24;
1377	case 0x7: return  36;
1378	case 0x9: return  48;
1379	case 0xb: return  72;
1380	case 0x1: return  96;
1381	case 0x3: return 108;
1382	/* XXX MCS */
1383	}
1384	/* unknown rate: should not happen */
1385	return 0;
1386}
1387
1388void
1389iwn_rx_intr(struct iwn_softc *sc, struct iwn_rx_desc *desc,
1390    struct iwn_rx_data *data)
1391{
1392	struct ifnet *ifp = sc->sc_ifp;
1393	struct ieee80211com *ic = ifp->if_l2com;
1394	struct iwn_rx_ring *ring = &sc->rxq;
1395	struct ieee80211_frame *wh;
1396	struct ieee80211_node *ni;
1397	struct mbuf *m, *mnew;
1398	struct iwn_rx_stat *stat;
1399	caddr_t head;
1400	uint32_t *tail;
1401	int8_t rssi, nf;
1402	int len, error;
1403	bus_addr_t paddr;
1404
1405	if (desc->type == IWN_AMPDU_RX_DONE) {
1406		/* check for prior AMPDU_RX_START */
1407		if (!sc->last_rx_valid) {
1408			DPRINTF(sc, IWN_DEBUG_ANY,
1409			    "%s: missing AMPDU_RX_START\n", __func__);
1410			ifp->if_ierrors++;
1411			return;
1412		}
1413		sc->last_rx_valid = 0;
1414		stat = &sc->last_rx_stat;
1415	} else
1416		stat = (struct iwn_rx_stat *)(desc + 1);
1417
1418	if (stat->cfg_phy_len > IWN_STAT_MAXLEN) {
1419		device_printf(sc->sc_dev,
1420		    "%s: invalid rx statistic header, len %d\n",
1421		    __func__, stat->cfg_phy_len);
1422		ifp->if_ierrors++;
1423		return;
1424	}
1425	if (desc->type == IWN_AMPDU_RX_DONE) {
1426		struct iwn_rx_ampdu *ampdu = (struct iwn_rx_ampdu *)(desc + 1);
1427		head = (caddr_t)(ampdu + 1);
1428		len = le16toh(ampdu->len);
1429	} else {
1430		head = (caddr_t)(stat + 1) + stat->cfg_phy_len;
1431		len = le16toh(stat->len);
1432	}
1433
1434	/* discard Rx frames with bad CRC early */
1435	tail = (uint32_t *)(head + len);
1436	if ((le32toh(*tail) & IWN_RX_NOERROR) != IWN_RX_NOERROR) {
1437		DPRINTF(sc, IWN_DEBUG_RECV, "%s: rx flags error %x\n",
1438		    __func__, le32toh(*tail));
1439		ifp->if_ierrors++;
1440		return;
1441	}
1442	if (len < sizeof (struct ieee80211_frame)) {
1443		DPRINTF(sc, IWN_DEBUG_RECV, "%s: frame too short: %d\n",
1444		    __func__, len);
1445		ic->ic_stats.is_rx_tooshort++;
1446		ifp->if_ierrors++;
1447		return;
1448	}
1449
1450	/* XXX don't need mbuf, just dma buffer */
1451	mnew = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, MJUMPAGESIZE);
1452	if (mnew == NULL) {
1453		DPRINTF(sc, IWN_DEBUG_ANY, "%s: no mbuf to restock ring\n",
1454		    __func__);
1455		ic->ic_stats.is_rx_nobuf++;
1456		ifp->if_ierrors++;
1457		return;
1458	}
1459	error = bus_dmamap_load(ring->data_dmat, data->map,
1460	    mtod(mnew, caddr_t), MJUMPAGESIZE,
1461	    iwn_dma_map_addr, &paddr, BUS_DMA_NOWAIT);
1462	if (error != 0 && error != EFBIG) {
1463		device_printf(sc->sc_dev,
1464		    "%s: bus_dmamap_load failed, error %d\n", __func__, error);
1465		m_freem(mnew);
1466		ic->ic_stats.is_rx_nobuf++;	/* XXX need stat */
1467		ifp->if_ierrors++;
1468		return;
1469	}
1470	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
1471
1472	/* finalize mbuf and swap in new one */
1473	m = data->m;
1474	m->m_pkthdr.rcvif = ifp;
1475	m->m_data = head;
1476	m->m_pkthdr.len = m->m_len = len;
1477
1478	data->m = mnew;
1479	/* update Rx descriptor */
1480	ring->desc[ring->cur] = htole32(paddr >> 8);
1481
1482	rssi = iwn_get_rssi(sc, stat);
1483
1484	/* grab a reference to the source node */
1485	wh = mtod(m, struct ieee80211_frame *);
1486	ni = ieee80211_find_rxnode(ic, (struct ieee80211_frame_min *)wh);
1487
1488	nf = (ni != NULL && ni->ni_vap->iv_state == IEEE80211_S_RUN &&
1489	    (ic->ic_flags & IEEE80211_F_SCAN) == 0) ? sc->noise : -95;
1490
1491	if (bpf_peers_present(ifp->if_bpf)) {
1492		struct iwn_rx_radiotap_header *tap = &sc->sc_rxtap;
1493
1494		tap->wr_flags = 0;
1495		tap->wr_dbm_antsignal = rssi;
1496		tap->wr_dbm_antnoise = nf;
1497		tap->wr_rate = maprate(stat->rate);
1498		tap->wr_tsft = htole64(stat->tstamp);
1499
1500		if (stat->flags & htole16(IWN_CONFIG_SHPREAMBLE))
1501			tap->wr_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
1502
1503		bpf_mtap2(ifp->if_bpf, tap, sc->sc_rxtap_len, m);
1504	}
1505
1506	IWN_UNLOCK(sc);
1507
1508	/* send the frame to the 802.11 layer */
1509	if (ni != NULL) {
1510		(void) ieee80211_input(ni, m, rssi - nf, nf, 0);
1511		ieee80211_free_node(ni);
1512	} else
1513		(void) ieee80211_input_all(ic, m, rssi - nf, nf, 0);
1514
1515	IWN_LOCK(sc);
1516}
1517
1518void
1519iwn_rx_statistics(struct iwn_softc *sc, struct iwn_rx_desc *desc)
1520{
1521	struct ifnet *ifp = sc->sc_ifp;
1522	struct ieee80211com *ic = ifp->if_l2com;
1523	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1524	struct iwn_calib_state *calib = &sc->calib;
1525	struct iwn_stats *stats = (struct iwn_stats *)(desc + 1);
1526
1527	/* beacon stats are meaningful only when associated and not scanning */
1528	if (vap->iv_state != IEEE80211_S_RUN ||
1529	    (ic->ic_flags & IEEE80211_F_SCAN))
1530		return;
1531
1532	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: cmd %d\n", __func__, desc->type);
1533	iwn_calib_reset(sc);
1534
1535	/* test if temperature has changed */
1536	if (stats->general.temp != sc->rawtemp) {
1537		int temp;
1538
1539		sc->rawtemp = stats->general.temp;
1540		temp = iwn_get_temperature(sc);
1541		DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: temperature %d\n",
1542		    __func__, temp);
1543
1544		/* update Tx power if need be */
1545		iwn_power_calibration(sc, temp);
1546	}
1547
1548	if (desc->type != IWN_BEACON_STATISTICS)
1549		return;	/* reply to a statistics request */
1550
1551	sc->noise = iwn_get_noise(&stats->rx.general);
1552	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: noise %d\n", __func__, sc->noise);
1553
1554	/* test that RSSI and noise are present in stats report */
1555	if (stats->rx.general.flags != htole32(1)) {
1556		DPRINTF(sc, IWN_DEBUG_ANY, "%s\n",
1557		    "received statistics without RSSI");
1558		return;
1559	}
1560
1561	if (calib->state == IWN_CALIB_STATE_ASSOC)
1562		iwn_compute_differential_gain(sc, &stats->rx.general);
1563	else if (calib->state == IWN_CALIB_STATE_RUN)
1564		iwn_tune_sensitivity(sc, &stats->rx);
1565}
1566
1567void
1568iwn_tx_intr(struct iwn_softc *sc, struct iwn_rx_desc *desc)
1569{
1570	struct ifnet *ifp = sc->sc_ifp;
1571	struct iwn_tx_ring *ring = &sc->txq[desc->qid & 0xf];
1572	struct iwn_tx_data *data = &ring->data[desc->idx];
1573	struct iwn_tx_stat *stat = (struct iwn_tx_stat *)(desc + 1);
1574	struct iwn_node *wn = IWN_NODE(data->ni);
1575	struct mbuf *m;
1576	struct ieee80211_node *ni;
1577	uint32_t status;
1578
1579	KASSERT(data->ni != NULL, ("no node"));
1580
1581	DPRINTF(sc, IWN_DEBUG_XMIT, "%s: "
1582	    "qid %d idx %d retries %d nkill %d rate %x duration %d status %x\n",
1583	    __func__, desc->qid, desc->idx, stat->ntries,
1584	    stat->nkill, stat->rate, le16toh(stat->duration),
1585	    le32toh(stat->status));
1586
1587	/*
1588	 * Update rate control statistics for the node.
1589	 */
1590	status = le32toh(stat->status) & 0xff;
1591	if (status & 0x80) {
1592		DPRINTF(sc, IWN_DEBUG_ANY, "%s: status 0x%x\n",
1593		    __func__, le32toh(stat->status));
1594		ifp->if_oerrors++;
1595		ieee80211_amrr_tx_complete(&wn->amn,
1596		    IEEE80211_AMRR_FAILURE, stat->ntries);
1597	} else {
1598		ieee80211_amrr_tx_complete(&wn->amn,
1599		    IEEE80211_AMRR_SUCCESS, stat->ntries);
1600	}
1601
1602	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTWRITE);
1603	bus_dmamap_unload(ring->data_dmat, data->map);
1604
1605	m = data->m, data->m = NULL;
1606	ni = data->ni, data->ni = NULL;
1607
1608	if (m->m_flags & M_TXCB) {
1609		/*
1610		 * Channels marked for "radar" require traffic to be received
1611		 * to unlock before we can transmit.  Until traffic is seen
1612		 * any attempt to transmit is returned immediately with status
1613		 * set to IWN_TX_FAIL_TX_LOCKED.  Unfortunately this can easily
1614		 * happen on first authenticate after scanning.  To workaround
1615		 * this we ignore a failure of this sort in AUTH state so the
1616		 * 802.11 layer will fall back to using a timeout to wait for
1617		 * the AUTH reply.  This allows the firmware time to see
1618		 * traffic so a subsequent retry of AUTH succeeds.  It's
1619		 * unclear why the firmware does not maintain state for
1620		 * channels recently visited as this would allow immediate
1621		 * use of the channel after a scan (where we see traffic).
1622		 */
1623		if (status == IWN_TX_FAIL_TX_LOCKED &&
1624		    ni->ni_vap->iv_state == IEEE80211_S_AUTH)
1625			ieee80211_process_callback(ni, m, 0);
1626		else
1627			ieee80211_process_callback(ni, m,
1628			    (status & IWN_TX_FAIL) != 0);
1629	}
1630	m_freem(m);
1631	ieee80211_free_node(ni);
1632
1633	ring->queued--;
1634
1635	sc->sc_tx_timer = 0;
1636	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1637	iwn_start_locked(ifp);
1638}
1639
1640void
1641iwn_cmd_intr(struct iwn_softc *sc, struct iwn_rx_desc *desc)
1642{
1643	struct iwn_tx_ring *ring = &sc->txq[4];
1644	struct iwn_tx_data *data;
1645
1646	if ((desc->qid & 0xf) != 4)
1647		return;	/* not a command ack */
1648
1649	data = &ring->data[desc->idx];
1650
1651	/* if the command was mapped in a mbuf, free it */
1652	if (data->m != NULL) {
1653		bus_dmamap_unload(ring->data_dmat, data->map);
1654		m_freem(data->m);
1655		data->m = NULL;
1656	}
1657
1658	wakeup(&ring->cmd[desc->idx]);
1659}
1660
1661static void
1662iwn_bmiss(void *arg, int npending)
1663{
1664	struct iwn_softc *sc = arg;
1665	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
1666
1667	ieee80211_beacon_miss(ic);
1668}
1669
1670void
1671iwn_notif_intr(struct iwn_softc *sc)
1672{
1673	struct ifnet *ifp = sc->sc_ifp;
1674	struct ieee80211com *ic = ifp->if_l2com;
1675	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1676	uint16_t hw;
1677
1678	hw = le16toh(sc->shared->closed_count) & 0xfff;
1679	while (sc->rxq.cur != hw) {
1680		struct iwn_rx_data *data = &sc->rxq.data[sc->rxq.cur];
1681		struct iwn_rx_desc *desc = (void *)data->m->m_ext.ext_buf;
1682
1683		DPRINTF(sc, IWN_DEBUG_RECV,
1684		    "%s: qid %x idx %d flags %x type %d(%s) len %d\n",
1685		    __func__, desc->qid, desc->idx, desc->flags,
1686		    desc->type, iwn_intr_str(desc->type),
1687		    le16toh(desc->len));
1688
1689		if (!(desc->qid & 0x80))	/* reply to a command */
1690			iwn_cmd_intr(sc, desc);
1691
1692		switch (desc->type) {
1693		case IWN_RX_DONE:
1694		case IWN_AMPDU_RX_DONE:
1695			iwn_rx_intr(sc, desc, data);
1696			break;
1697
1698		case IWN_AMPDU_RX_START:
1699			iwn_ampdu_rx_start(sc, desc);
1700			break;
1701
1702		case IWN_TX_DONE:
1703			/* a 802.11 frame has been transmitted */
1704			iwn_tx_intr(sc, desc);
1705			break;
1706
1707		case IWN_RX_STATISTICS:
1708		case IWN_BEACON_STATISTICS:
1709			iwn_rx_statistics(sc, desc);
1710			break;
1711
1712		case IWN_BEACON_MISSED: {
1713			struct iwn_beacon_missed *miss =
1714			    (struct iwn_beacon_missed *)(desc + 1);
1715			int misses = le32toh(miss->consecutive);
1716
1717			/* XXX not sure why we're notified w/ zero */
1718			if (misses == 0)
1719				break;
1720			DPRINTF(sc, IWN_DEBUG_STATE,
1721			    "%s: beacons missed %d/%d\n", __func__,
1722			    misses, le32toh(miss->total));
1723			/*
1724			 * If more than 5 consecutive beacons are missed,
1725			 * reinitialize the sensitivity state machine.
1726			 */
1727			if (vap->iv_state == IEEE80211_S_RUN && misses > 5)
1728				(void) iwn_init_sensitivity(sc);
1729			if (misses >= vap->iv_bmissthreshold)
1730				taskqueue_enqueue(taskqueue_swi,
1731				    &sc->sc_bmiss_task);
1732			break;
1733		}
1734		case IWN_UC_READY: {
1735			struct iwn_ucode_info *uc =
1736			    (struct iwn_ucode_info *)(desc + 1);
1737
1738			/* the microcontroller is ready */
1739			DPRINTF(sc, IWN_DEBUG_RESET,
1740			    "microcode alive notification version=%d.%d "
1741			    "subtype=%x alive=%x\n", uc->major, uc->minor,
1742			    uc->subtype, le32toh(uc->valid));
1743
1744			if (le32toh(uc->valid) != 1) {
1745				device_printf(sc->sc_dev,
1746				"microcontroller initialization failed");
1747				break;
1748			}
1749			if (uc->subtype == IWN_UCODE_INIT) {
1750				/* save microcontroller's report */
1751				memcpy(&sc->ucode_info, uc, sizeof (*uc));
1752			}
1753			break;
1754		}
1755		case IWN_STATE_CHANGED: {
1756			uint32_t *status = (uint32_t *)(desc + 1);
1757
1758			/*
1759			 * State change allows hardware switch change to be
1760			 * noted. However, we handle this in iwn_intr as we
1761			 * get both the enable/disble intr.
1762			 */
1763			DPRINTF(sc, IWN_DEBUG_INTR, "state changed to %x\n",
1764			    le32toh(*status));
1765			break;
1766		}
1767		case IWN_START_SCAN: {
1768			struct iwn_start_scan *scan =
1769			    (struct iwn_start_scan *)(desc + 1);
1770
1771			DPRINTF(sc, IWN_DEBUG_ANY,
1772			    "%s: scanning channel %d status %x\n",
1773			    __func__, scan->chan, le32toh(scan->status));
1774			break;
1775		}
1776		case IWN_STOP_SCAN: {
1777			struct iwn_stop_scan *scan =
1778			    (struct iwn_stop_scan *)(desc + 1);
1779
1780			DPRINTF(sc, IWN_DEBUG_STATE,
1781			    "scan finished nchan=%d status=%d chan=%d\n",
1782			    scan->nchan, scan->status, scan->chan);
1783
1784			iwn_queue_cmd(sc, IWN_SCAN_NEXT, 0, IWN_QUEUE_NORMAL);
1785			break;
1786		}
1787		}
1788		sc->rxq.cur = (sc->rxq.cur + 1) % IWN_RX_RING_COUNT;
1789	}
1790
1791	/* tell the firmware what we have processed */
1792	hw = (hw == 0) ? IWN_RX_RING_COUNT - 1 : hw - 1;
1793	IWN_WRITE(sc, IWN_RX_WIDX, hw & ~7);
1794}
1795
1796void
1797iwn_intr(void *arg)
1798{
1799	struct iwn_softc *sc = arg;
1800	uint32_t r1, r2;
1801
1802	IWN_LOCK(sc);
1803
1804	/* disable interrupts */
1805	IWN_WRITE(sc, IWN_MASK, 0);
1806
1807	r1 = IWN_READ(sc, IWN_INTR);
1808	r2 = IWN_READ(sc, IWN_INTR_STATUS);
1809
1810	if (r1 == 0 && r2 == 0) {
1811		IWN_WRITE(sc, IWN_MASK, IWN_INTR_MASK);
1812		goto done;	/* not for us */
1813	}
1814
1815	if (r1 == 0xffffffff)
1816		goto done;	/* hardware gone */
1817
1818	/* ack interrupts */
1819	IWN_WRITE(sc, IWN_INTR, r1);
1820	IWN_WRITE(sc, IWN_INTR_STATUS, r2);
1821
1822	DPRINTF(sc, IWN_DEBUG_INTR, "interrupt reg1=%x reg2=%x\n", r1, r2);
1823
1824	if (r1 & IWN_RF_TOGGLED) {
1825		uint32_t tmp = IWN_READ(sc, IWN_GPIO_CTL);
1826		device_printf(sc->sc_dev, "RF switch: radio %s\n",
1827		    (tmp & IWN_GPIO_RF_ENABLED) ? "enabled" : "disabled");
1828		if (tmp & IWN_GPIO_RF_ENABLED)
1829			iwn_queue_cmd(sc, IWN_RADIO_ENABLE, 0, IWN_QUEUE_CLEAR);
1830		else
1831			iwn_queue_cmd(sc, IWN_RADIO_DISABLE, 0, IWN_QUEUE_CLEAR);
1832	}
1833	if (r1 & IWN_CT_REACHED)
1834		device_printf(sc->sc_dev, "critical temperature reached!\n");
1835	if (r1 & (IWN_SW_ERROR | IWN_HW_ERROR)) {
1836		device_printf(sc->sc_dev, "error, INTR=%b STATUS=0x%x\n",
1837		    r1, IWN_INTR_BITS, r2);
1838		iwn_queue_cmd(sc, IWN_REINIT, 0, IWN_QUEUE_CLEAR);
1839		goto done;
1840	}
1841	if ((r1 & (IWN_RX_INTR | IWN_SW_RX_INTR)) || (r2 & IWN_RX_STATUS_INTR))
1842		iwn_notif_intr(sc);
1843	if (r1 & IWN_ALIVE_INTR)
1844		wakeup(sc);
1845
1846	/* re-enable interrupts */
1847	IWN_WRITE(sc, IWN_MASK, IWN_INTR_MASK);
1848done:
1849	IWN_UNLOCK(sc);
1850}
1851
1852uint8_t
1853iwn_plcp_signal(int rate)
1854{
1855	switch (rate) {
1856	/* CCK rates (returned values are device-dependent) */
1857	case 2:		return 10;
1858	case 4:		return 20;
1859	case 11:	return 55;
1860	case 22:	return 110;
1861
1862	/* OFDM rates (cf IEEE Std 802.11a-1999, pp. 14 Table 80) */
1863	/* R1-R4, (u)ral is R4-R1 */
1864	case 12:	return 0xd;
1865	case 18:	return 0xf;
1866	case 24:	return 0x5;
1867	case 36:	return 0x7;
1868	case 48:	return 0x9;
1869	case 72:	return 0xb;
1870	case 96:	return 0x1;
1871	case 108:	return 0x3;
1872	case 120:	return 0x3;
1873	}
1874	/* unknown rate (should not get there) */
1875	return 0;
1876}
1877
1878/* determine if a given rate is CCK or OFDM */
1879#define IWN_RATE_IS_OFDM(rate) ((rate) >= 12 && (rate) != 22)
1880
1881int
1882iwn_tx_data(struct iwn_softc *sc, struct mbuf *m0, struct ieee80211_node *ni,
1883    struct iwn_tx_ring *ring)
1884{
1885	struct ieee80211vap *vap = ni->ni_vap;
1886	struct ieee80211com *ic = ni->ni_ic;
1887	struct ifnet *ifp = sc->sc_ifp;
1888	const struct ieee80211_txparam *tp;
1889	struct iwn_tx_desc *desc;
1890	struct iwn_tx_data *data;
1891	struct iwn_tx_cmd *cmd;
1892	struct iwn_cmd_data *tx;
1893	struct ieee80211_frame *wh;
1894	struct ieee80211_key *k;
1895	bus_addr_t paddr;
1896	uint32_t flags;
1897	uint16_t timeout;
1898	uint8_t type;
1899	u_int hdrlen;
1900	struct mbuf *mnew;
1901	int rate, error, pad, nsegs, i, ismcast, id;
1902	bus_dma_segment_t segs[IWN_MAX_SCATTER];
1903
1904	IWN_LOCK_ASSERT(sc);
1905
1906	wh = mtod(m0, struct ieee80211_frame *);
1907	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
1908	ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
1909	hdrlen = ieee80211_anyhdrsize(wh);
1910
1911	/* pick a tx rate */
1912	/* XXX ni_chan */
1913	tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)];
1914	if (type == IEEE80211_FC0_TYPE_MGT)
1915		rate = tp->mgmtrate;
1916	else if (ismcast)
1917		rate = tp->mcastrate;
1918	else if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE)
1919		rate = tp->ucastrate;
1920	else {
1921		(void) ieee80211_amrr_choose(ni, &IWN_NODE(ni)->amn);
1922		rate = ni->ni_txrate;
1923	}
1924
1925	if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1926		k = ieee80211_crypto_encap(ni, m0);
1927		if (k == NULL) {
1928			m_freem(m0);
1929			return ENOBUFS;
1930		}
1931		/* packet header may have moved, reset our local pointer */
1932		wh = mtod(m0, struct ieee80211_frame *);
1933	} else
1934		k = NULL;
1935
1936	if (bpf_peers_present(ifp->if_bpf)) {
1937		struct iwn_tx_radiotap_header *tap = &sc->sc_txtap;
1938
1939		tap->wt_flags = 0;
1940		tap->wt_rate = rate;
1941		if (k != NULL)
1942			tap->wt_flags |= IEEE80211_RADIOTAP_F_WEP;
1943
1944		bpf_mtap2(ifp->if_bpf, tap, sc->sc_txtap_len, m0);
1945	}
1946
1947	flags = IWN_TX_AUTO_SEQ;
1948	/* XXX honor ACM */
1949	if (!ismcast)
1950		flags |= IWN_TX_NEED_ACK;
1951
1952	if (ismcast || type != IEEE80211_FC0_TYPE_DATA)
1953		id = IWN_ID_BROADCAST;
1954	else
1955		id = IWN_ID_BSS;
1956
1957	/* check if RTS/CTS or CTS-to-self protection must be used */
1958	if (!ismcast) {
1959		/* multicast frames are not sent at OFDM rates in 802.11b/g */
1960		if (m0->m_pkthdr.len+IEEE80211_CRC_LEN > vap->iv_rtsthreshold) {
1961			flags |= IWN_TX_NEED_RTS | IWN_TX_FULL_TXOP;
1962		} else if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
1963		    IWN_RATE_IS_OFDM(rate)) {
1964			if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
1965				flags |= IWN_TX_NEED_CTS | IWN_TX_FULL_TXOP;
1966			else if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
1967				flags |= IWN_TX_NEED_RTS | IWN_TX_FULL_TXOP;
1968		}
1969	}
1970
1971	if (type == IEEE80211_FC0_TYPE_MGT) {
1972		uint8_t subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
1973
1974		/* tell h/w to set timestamp in probe responses */
1975		if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
1976			flags |= IWN_TX_INSERT_TSTAMP;
1977
1978		if (subtype == IEEE80211_FC0_SUBTYPE_ASSOC_REQ ||
1979		    subtype == IEEE80211_FC0_SUBTYPE_REASSOC_REQ)
1980			timeout = htole16(3);
1981		else
1982			timeout = htole16(2);
1983	} else
1984		timeout = htole16(0);
1985
1986	if (hdrlen & 3) {
1987		/* first segment's length must be a multiple of 4 */
1988		flags |= IWN_TX_NEED_PADDING;
1989		pad = 4 - (hdrlen & 3);
1990	} else
1991		pad = 0;
1992
1993	desc = &ring->desc[ring->cur];
1994	data = &ring->data[ring->cur];
1995
1996	cmd = &ring->cmd[ring->cur];
1997	cmd->code = IWN_CMD_TX_DATA;
1998	cmd->flags = 0;
1999	cmd->qid = ring->qid;
2000	cmd->idx = ring->cur;
2001
2002	tx = (struct iwn_cmd_data *)cmd->data;
2003	/* NB: no need to bzero tx, all fields are reinitialized here */
2004	tx->id = id;
2005	tx->flags = htole32(flags);
2006	tx->len = htole16(m0->m_pkthdr.len);
2007	tx->rate = iwn_plcp_signal(rate);
2008	tx->rts_ntries = 60;		/* XXX? */
2009	tx->data_ntries = 15;		/* XXX? */
2010	tx->lifetime = htole32(IWN_LIFETIME_INFINITE);
2011	tx->timeout = timeout;
2012
2013	if (k != NULL) {
2014		/* XXX fill in */;
2015	} else
2016		tx->security = 0;
2017
2018	/* XXX alternate between Ant A and Ant B ? */
2019	tx->rflags = IWN_RFLAG_ANT_B;
2020	if (tx->id == IWN_ID_BROADCAST) {
2021		tx->ridx = IWN_MAX_TX_RETRIES - 1;
2022		if (!IWN_RATE_IS_OFDM(rate))
2023			tx->rflags |= IWN_RFLAG_CCK;
2024	} else {
2025		tx->ridx = 0;
2026		/* tell adapter to ignore rflags */
2027		tx->flags |= htole32(IWN_TX_USE_NODE_RATE);
2028	}
2029
2030	/* copy and trim IEEE802.11 header */
2031	memcpy((uint8_t *)(tx + 1), wh, hdrlen);
2032	m_adj(m0, hdrlen);
2033
2034	error = bus_dmamap_load_mbuf_sg(ring->data_dmat, data->map, m0, segs,
2035	    &nsegs, BUS_DMA_NOWAIT);
2036	if (error != 0) {
2037		if (error == EFBIG) {
2038			/* too many fragments, linearize */
2039			mnew = m_collapse(m0, M_DONTWAIT, IWN_MAX_SCATTER);
2040			if (mnew == NULL) {
2041				IWN_UNLOCK(sc);
2042				device_printf(sc->sc_dev,
2043				    "%s: could not defrag mbuf\n", __func__);
2044				m_freem(m0);
2045				return ENOBUFS;
2046			}
2047			m0 = mnew;
2048			error = bus_dmamap_load_mbuf_sg(ring->data_dmat,
2049			    data->map, m0, segs, &nsegs, BUS_DMA_NOWAIT);
2050		}
2051		if (error != 0) {
2052			IWN_UNLOCK(sc);
2053			device_printf(sc->sc_dev,
2054			    "%s: bus_dmamap_load_mbuf_sg failed, error %d\n",
2055			     __func__, error);
2056			m_freem(m0);
2057			return error;
2058		}
2059	}
2060
2061	data->m = m0;
2062	data->ni = ni;
2063
2064	DPRINTF(sc, IWN_DEBUG_XMIT, "%s: qid %d idx %d len %d nsegs %d\n",
2065	    __func__, ring->qid, ring->cur, m0->m_pkthdr.len, nsegs);
2066
2067	paddr = ring->cmd_dma.paddr + ring->cur * sizeof (struct iwn_tx_cmd);
2068	tx->loaddr = htole32(paddr + 4 +
2069	    offsetof(struct iwn_cmd_data, ntries));
2070	tx->hiaddr = 0;	/* limit to 32-bit physical addresses */
2071
2072	/* first scatter/gather segment is used by the tx data command */
2073	IWN_SET_DESC_NSEGS(desc, 1 + nsegs);
2074	IWN_SET_DESC_SEG(desc, 0, paddr, 4 + sizeof (*tx) + hdrlen + pad);
2075	for (i = 1; i <= nsegs; i++) {
2076		IWN_SET_DESC_SEG(desc, i, segs[i - 1].ds_addr,
2077		     segs[i - 1].ds_len);
2078	}
2079	sc->shared->len[ring->qid][ring->cur] =
2080	    htole16(hdrlen + m0->m_pkthdr.len + 8);
2081
2082	if (ring->cur < IWN_TX_WINDOW)
2083		sc->shared->len[ring->qid][ring->cur + IWN_TX_RING_COUNT] =
2084			htole16(hdrlen + m0->m_pkthdr.len + 8);
2085
2086	ring->queued++;
2087
2088	/* kick Tx ring */
2089	ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT;
2090	IWN_WRITE(sc, IWN_TX_WIDX, ring->qid << 8 | ring->cur);
2091
2092	ifp->if_opackets++;
2093	sc->sc_tx_timer = 5;
2094
2095	return 0;
2096}
2097
2098void
2099iwn_start(struct ifnet *ifp)
2100{
2101	struct iwn_softc *sc = ifp->if_softc;
2102
2103	IWN_LOCK(sc);
2104	iwn_start_locked(ifp);
2105	IWN_UNLOCK(sc);
2106}
2107
2108void
2109iwn_start_locked(struct ifnet *ifp)
2110{
2111	struct iwn_softc *sc = ifp->if_softc;
2112	struct ieee80211_node *ni;
2113	struct iwn_tx_ring *txq;
2114	struct mbuf *m;
2115	int pri;
2116
2117	IWN_LOCK_ASSERT(sc);
2118
2119	for (;;) {
2120		IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
2121		if (m == NULL)
2122			break;
2123		ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
2124		pri = M_WME_GETAC(m);
2125		txq = &sc->txq[pri];
2126		m = ieee80211_encap(ni, m);
2127		if (m == NULL) {
2128			ifp->if_oerrors++;
2129			ieee80211_free_node(ni);
2130			continue;
2131		}
2132		if (txq->queued >= IWN_TX_RING_COUNT - 8) {
2133			/* XXX not right */
2134			/* ring is nearly full, stop flow */
2135			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
2136		}
2137		if (iwn_tx_data(sc, m, ni, txq) != 0) {
2138			ifp->if_oerrors++;
2139			ieee80211_free_node(ni);
2140			IWN_UNLOCK(sc);
2141			break;
2142		}
2143	}
2144}
2145
2146static int
2147iwn_tx_handoff(struct iwn_softc *sc,
2148	struct iwn_tx_ring *ring,
2149	struct iwn_tx_cmd *cmd,
2150	struct iwn_cmd_data *tx,
2151	struct ieee80211_node *ni,
2152	struct mbuf *m0, u_int hdrlen, int pad)
2153{
2154	struct ifnet *ifp = sc->sc_ifp;
2155	struct iwn_tx_desc *desc;
2156	struct iwn_tx_data *data;
2157	bus_addr_t paddr;
2158	struct mbuf *mnew;
2159	int error, nsegs, i;
2160	bus_dma_segment_t segs[IWN_MAX_SCATTER];
2161
2162	/* copy and trim IEEE802.11 header */
2163	memcpy((uint8_t *)(tx + 1), mtod(m0, uint8_t *), hdrlen);
2164	m_adj(m0, hdrlen);
2165
2166	desc = &ring->desc[ring->cur];
2167	data = &ring->data[ring->cur];
2168
2169	error = bus_dmamap_load_mbuf_sg(ring->data_dmat, data->map, m0, segs,
2170	    &nsegs, BUS_DMA_NOWAIT);
2171	if (error != 0) {
2172		if (error == EFBIG) {
2173			/* too many fragments, linearize */
2174			mnew = m_collapse(m0, M_DONTWAIT, IWN_MAX_SCATTER);
2175			if (mnew == NULL) {
2176				IWN_UNLOCK(sc);
2177				device_printf(sc->sc_dev,
2178				    "%s: could not defrag mbuf\n", __func__);
2179				m_freem(m0);
2180				return ENOBUFS;
2181			}
2182			m0 = mnew;
2183			error = bus_dmamap_load_mbuf_sg(ring->data_dmat,
2184			    data->map, m0, segs, &nsegs, BUS_DMA_NOWAIT);
2185		}
2186		if (error != 0) {
2187			IWN_UNLOCK(sc);
2188			device_printf(sc->sc_dev,
2189			    "%s: bus_dmamap_load_mbuf_sg failed, error %d\n",
2190			     __func__, error);
2191			m_freem(m0);
2192			return error;
2193		}
2194	}
2195
2196	data->m = m0;
2197	data->ni = ni;
2198
2199	DPRINTF(sc, IWN_DEBUG_XMIT, "%s: qid %d idx %d len %d nsegs %d\n",
2200	    __func__, ring->qid, ring->cur, m0->m_pkthdr.len, nsegs);
2201
2202	paddr = ring->cmd_dma.paddr + ring->cur * sizeof (struct iwn_tx_cmd);
2203	tx->loaddr = htole32(paddr + 4 +
2204	    offsetof(struct iwn_cmd_data, ntries));
2205	tx->hiaddr = 0;	/* limit to 32-bit physical addresses */
2206
2207	/* first scatter/gather segment is used by the tx data command */
2208	IWN_SET_DESC_NSEGS(desc, 1 + nsegs);
2209	IWN_SET_DESC_SEG(desc, 0, paddr, 4 + sizeof (*tx) + hdrlen + pad);
2210	for (i = 1; i <= nsegs; i++) {
2211		IWN_SET_DESC_SEG(desc, i, segs[i - 1].ds_addr,
2212		     segs[i - 1].ds_len);
2213	}
2214	sc->shared->len[ring->qid][ring->cur] =
2215	    htole16(hdrlen + m0->m_pkthdr.len + 8);
2216
2217	if (ring->cur < IWN_TX_WINDOW)
2218		sc->shared->len[ring->qid][ring->cur + IWN_TX_RING_COUNT] =
2219			htole16(hdrlen + m0->m_pkthdr.len + 8);
2220
2221	ring->queued++;
2222
2223	/* kick Tx ring */
2224	ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT;
2225	IWN_WRITE(sc, IWN_TX_WIDX, ring->qid << 8 | ring->cur);
2226
2227	ifp->if_opackets++;
2228	sc->sc_tx_timer = 5;
2229
2230	return 0;
2231}
2232
2233static int
2234iwn_tx_data_raw(struct iwn_softc *sc, struct mbuf *m0,
2235    struct ieee80211_node *ni, struct iwn_tx_ring *ring,
2236    const struct ieee80211_bpf_params *params)
2237{
2238	struct ifnet *ifp = sc->sc_ifp;
2239	struct iwn_tx_cmd *cmd;
2240	struct iwn_cmd_data *tx;
2241	struct ieee80211_frame *wh;
2242	uint32_t flags;
2243	uint8_t type, subtype;
2244	u_int hdrlen;
2245	int rate, pad;
2246
2247	IWN_LOCK_ASSERT(sc);
2248
2249	wh = mtod(m0, struct ieee80211_frame *);
2250	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
2251	subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
2252	hdrlen = ieee80211_anyhdrsize(wh);
2253
2254	flags = IWN_TX_AUTO_SEQ;
2255	if ((params->ibp_flags & IEEE80211_BPF_NOACK) == 0)
2256		flags |= IWN_TX_NEED_ACK;
2257	if (params->ibp_flags & IEEE80211_BPF_RTS)
2258		flags |= IWN_TX_NEED_RTS | IWN_TX_FULL_TXOP;
2259	if (params->ibp_flags & IEEE80211_BPF_CTS)
2260		flags |= IWN_TX_NEED_CTS | IWN_TX_FULL_TXOP;
2261	if (type == IEEE80211_FC0_TYPE_MGT &&
2262	    subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP) {
2263		/* tell h/w to set timestamp in probe responses */
2264		flags |= IWN_TX_INSERT_TSTAMP;
2265	}
2266	if (hdrlen & 3) {
2267		/* first segment's length must be a multiple of 4 */
2268		flags |= IWN_TX_NEED_PADDING;
2269		pad = 4 - (hdrlen & 3);
2270	} else
2271		pad = 0;
2272
2273	/* pick a tx rate */
2274	rate = params->ibp_rate0;
2275
2276	if (bpf_peers_present(ifp->if_bpf)) {
2277		struct iwn_tx_radiotap_header *tap = &sc->sc_txtap;
2278
2279		tap->wt_flags = 0;
2280		tap->wt_rate = rate;
2281
2282		bpf_mtap2(ifp->if_bpf, tap, sc->sc_txtap_len, m0);
2283	}
2284
2285	cmd = &ring->cmd[ring->cur];
2286	cmd->code = IWN_CMD_TX_DATA;
2287	cmd->flags = 0;
2288	cmd->qid = ring->qid;
2289	cmd->idx = ring->cur;
2290
2291	tx = (struct iwn_cmd_data *)cmd->data;
2292	/* NB: no need to bzero tx, all fields are reinitialized here */
2293	tx->id = IWN_ID_BROADCAST;
2294	tx->flags = htole32(flags);
2295	tx->len = htole16(m0->m_pkthdr.len);
2296	tx->rate = iwn_plcp_signal(rate);
2297	tx->rts_ntries = params->ibp_try1;		/* XXX? */
2298	tx->data_ntries = params->ibp_try0;
2299	tx->lifetime = htole32(IWN_LIFETIME_INFINITE);
2300	/* XXX use try count? */
2301	if (type == IEEE80211_FC0_TYPE_MGT) {
2302		if (subtype == IEEE80211_FC0_SUBTYPE_ASSOC_REQ ||
2303		    subtype == IEEE80211_FC0_SUBTYPE_REASSOC_REQ)
2304			tx->timeout = htole16(3);
2305		else
2306			tx->timeout = htole16(2);
2307	} else
2308		tx->timeout = htole16(0);
2309	tx->security = 0;
2310	/* XXX alternate between Ant A and Ant B ? */
2311	tx->rflags = IWN_RFLAG_ANT_B;	/* XXX params->ibp_pri >> 2 */
2312	tx->ridx = IWN_MAX_TX_RETRIES - 1;
2313	if (!IWN_RATE_IS_OFDM(rate))
2314		tx->rflags |= IWN_RFLAG_CCK;
2315
2316	return iwn_tx_handoff(sc, ring, cmd, tx, ni, m0, hdrlen, pad);
2317}
2318
2319static int
2320iwn_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
2321	const struct ieee80211_bpf_params *params)
2322{
2323	struct ieee80211com *ic = ni->ni_ic;
2324	struct ifnet *ifp = ic->ic_ifp;
2325	struct iwn_softc *sc = ifp->if_softc;
2326	struct iwn_tx_ring *txq;
2327	int error;
2328
2329	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
2330		ieee80211_free_node(ni);
2331		m_freem(m);
2332		return ENETDOWN;
2333	}
2334
2335	IWN_LOCK(sc);
2336	if (params == NULL)
2337		txq = &sc->txq[M_WME_GETAC(m)];
2338	else
2339		txq = &sc->txq[params->ibp_pri & 3];
2340	if (txq->queued >= IWN_TX_RING_COUNT - 8) {
2341		/* XXX not right */
2342		/* ring is nearly full, stop flow */
2343		ifp->if_drv_flags |= IFF_DRV_OACTIVE;
2344	}
2345	if (params == NULL) {
2346		/*
2347		 * Legacy path; interpret frame contents to decide
2348		 * precisely how to send the frame.
2349		 */
2350		error = iwn_tx_data(sc, m, ni, txq);
2351	} else {
2352		/*
2353		 * Caller supplied explicit parameters to use in
2354		 * sending the frame.
2355		 */
2356		error = iwn_tx_data_raw(sc, m, ni, txq, params);
2357	}
2358	if (error != 0) {
2359		/* NB: m is reclaimed on tx failure */
2360		ieee80211_free_node(ni);
2361		ifp->if_oerrors++;
2362	}
2363	IWN_UNLOCK(sc);
2364	return error;
2365}
2366
2367static void
2368iwn_watchdog(struct iwn_softc *sc)
2369{
2370	if (sc->sc_tx_timer > 0 && --sc->sc_tx_timer == 0) {
2371		struct ifnet *ifp = sc->sc_ifp;
2372
2373		if_printf(ifp, "device timeout\n");
2374		iwn_queue_cmd(sc, IWN_REINIT, 0, IWN_QUEUE_CLEAR);
2375	}
2376}
2377
2378int
2379iwn_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
2380{
2381	struct iwn_softc *sc = ifp->if_softc;
2382	struct ieee80211com *ic = ifp->if_l2com;
2383	struct ifreq *ifr = (struct ifreq *) data;
2384	int error = 0, startall = 0;
2385
2386	switch (cmd) {
2387	case SIOCSIFFLAGS:
2388		IWN_LOCK(sc);
2389		if (ifp->if_flags & IFF_UP) {
2390			if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
2391				iwn_init_locked(sc);
2392				startall = 1;
2393			}
2394		} else {
2395			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
2396				iwn_stop_locked(sc);
2397		}
2398		IWN_UNLOCK(sc);
2399		if (startall)
2400			ieee80211_start_all(ic);
2401		break;
2402	case SIOCGIFMEDIA:
2403		error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
2404		break;
2405	case SIOCGIFADDR:
2406		error = ether_ioctl(ifp, cmd, data);
2407		break;
2408	default:
2409		error = EINVAL;
2410		break;
2411	}
2412	return error;
2413}
2414
2415void
2416iwn_read_eeprom(struct iwn_softc *sc)
2417{
2418	struct ifnet *ifp = sc->sc_ifp;
2419	struct ieee80211com *ic = ifp->if_l2com;
2420	char domain[4];
2421	uint16_t val;
2422	int i, error;
2423
2424	if ((error = iwn_eeprom_lock(sc)) != 0) {
2425		device_printf(sc->sc_dev,
2426		    "%s: could not lock EEPROM, error %d\n", __func__, error);
2427		return;
2428	}
2429	/* read and print regulatory domain */
2430	iwn_read_prom_data(sc, IWN_EEPROM_DOMAIN, domain, 4);
2431	device_printf(sc->sc_dev,"Reg Domain: %.4s", domain);
2432
2433	/* read and print MAC address */
2434	iwn_read_prom_data(sc, IWN_EEPROM_MAC, ic->ic_myaddr, 6);
2435	printf(", address %s\n", ether_sprintf(ic->ic_myaddr));
2436
2437	/* read the list of authorized channels */
2438	iwn_read_eeprom_channels(sc);
2439
2440	/* read maximum allowed Tx power for 2GHz and 5GHz bands */
2441	iwn_read_prom_data(sc, IWN_EEPROM_MAXPOW, &val, 2);
2442	sc->maxpwr2GHz = val & 0xff;
2443	sc->maxpwr5GHz = val >> 8;
2444	/* check that EEPROM values are correct */
2445	if (sc->maxpwr5GHz < 20 || sc->maxpwr5GHz > 50)
2446		sc->maxpwr5GHz = 38;
2447	if (sc->maxpwr2GHz < 20 || sc->maxpwr2GHz > 50)
2448		sc->maxpwr2GHz = 38;
2449	DPRINTF(sc, IWN_DEBUG_RESET, "maxpwr 2GHz=%d 5GHz=%d\n",
2450	    sc->maxpwr2GHz, sc->maxpwr5GHz);
2451
2452	/* read voltage at which samples were taken */
2453	iwn_read_prom_data(sc, IWN_EEPROM_VOLTAGE, &val, 2);
2454	sc->eeprom_voltage = (int16_t)le16toh(val);
2455	DPRINTF(sc, IWN_DEBUG_RESET, "voltage=%d (in 0.3V)\n",
2456	    sc->eeprom_voltage);
2457
2458	/* read power groups */
2459	iwn_read_prom_data(sc, IWN_EEPROM_BANDS, sc->bands, sizeof sc->bands);
2460#ifdef IWN_DEBUG
2461	if (sc->sc_debug & IWN_DEBUG_ANY) {
2462		for (i = 0; i < IWN_NBANDS; i++)
2463			iwn_print_power_group(sc, i);
2464	}
2465#endif
2466	iwn_eeprom_unlock(sc);
2467}
2468
2469struct iwn_chan_band {
2470	uint32_t	addr;	/* offset in EEPROM */
2471	uint32_t	flags;	/* net80211 flags */
2472	uint8_t		nchan;
2473#define IWN_MAX_CHAN_PER_BAND	14
2474	uint8_t		chan[IWN_MAX_CHAN_PER_BAND];
2475};
2476
2477static void
2478iwn_read_eeprom_band(struct iwn_softc *sc, const struct iwn_chan_band *band)
2479{
2480	struct ifnet *ifp = sc->sc_ifp;
2481	struct ieee80211com *ic = ifp->if_l2com;
2482	struct iwn_eeprom_chan channels[IWN_MAX_CHAN_PER_BAND];
2483	struct ieee80211_channel *c;
2484	int i, chan, flags;
2485
2486	iwn_read_prom_data(sc, band->addr, channels,
2487	    band->nchan * sizeof (struct iwn_eeprom_chan));
2488
2489	for (i = 0; i < band->nchan; i++) {
2490		if (!(channels[i].flags & IWN_EEPROM_CHAN_VALID)) {
2491			DPRINTF(sc, IWN_DEBUG_RESET,
2492			    "skip chan %d flags 0x%x maxpwr %d\n",
2493			    band->chan[i], channels[i].flags,
2494			    channels[i].maxpwr);
2495			continue;
2496		}
2497		chan = band->chan[i];
2498
2499		/* translate EEPROM flags to net80211 */
2500		flags = 0;
2501		if ((channels[i].flags & IWN_EEPROM_CHAN_ACTIVE) == 0)
2502			flags |= IEEE80211_CHAN_PASSIVE;
2503		if ((channels[i].flags & IWN_EEPROM_CHAN_IBSS) == 0)
2504			flags |= IEEE80211_CHAN_NOADHOC;
2505		if (channels[i].flags & IWN_EEPROM_CHAN_RADAR) {
2506			flags |= IEEE80211_CHAN_DFS;
2507			/* XXX apparently IBSS may still be marked */
2508			flags |= IEEE80211_CHAN_NOADHOC;
2509		}
2510
2511		DPRINTF(sc, IWN_DEBUG_RESET,
2512		    "add chan %d flags 0x%x maxpwr %d\n",
2513		    chan, channels[i].flags, channels[i].maxpwr);
2514
2515		c = &ic->ic_channels[ic->ic_nchans++];
2516		c->ic_ieee = chan;
2517		c->ic_freq = ieee80211_ieee2mhz(chan, band->flags);
2518		c->ic_maxregpower = channels[i].maxpwr;
2519		c->ic_maxpower = 2*c->ic_maxregpower;
2520		if (band->flags & IEEE80211_CHAN_2GHZ) {
2521			/* G =>'s B is supported */
2522			c->ic_flags = IEEE80211_CHAN_B | flags;
2523
2524			c = &ic->ic_channels[ic->ic_nchans++];
2525			c[0] = c[-1];
2526			c->ic_flags = IEEE80211_CHAN_G | flags;
2527		} else {	/* 5GHz band */
2528			c->ic_flags = IEEE80211_CHAN_A | flags;
2529		}
2530		/* XXX no constraints on using HT20 */
2531		/* add HT20, HT40 added separately */
2532		c = &ic->ic_channels[ic->ic_nchans++];
2533		c[0] = c[-1];
2534		c->ic_flags |= IEEE80211_CHAN_HT20;
2535		/* XXX NARROW =>'s 1/2 and 1/4 width? */
2536	}
2537}
2538
2539static void
2540iwn_read_eeprom_ht40(struct iwn_softc *sc, const struct iwn_chan_band *band)
2541{
2542	struct ifnet *ifp = sc->sc_ifp;
2543	struct ieee80211com *ic = ifp->if_l2com;
2544	struct iwn_eeprom_chan channels[IWN_MAX_CHAN_PER_BAND];
2545	struct ieee80211_channel *c, *cent, *extc;
2546	int i;
2547
2548	iwn_read_prom_data(sc, band->addr, channels,
2549	    band->nchan * sizeof (struct iwn_eeprom_chan));
2550
2551	for (i = 0; i < band->nchan; i++) {
2552		if (!(channels[i].flags & IWN_EEPROM_CHAN_VALID) ||
2553		    !(channels[i].flags & IWN_EEPROM_CHAN_WIDE)) {
2554			DPRINTF(sc, IWN_DEBUG_RESET,
2555			    "skip chan %d flags 0x%x maxpwr %d\n",
2556			    band->chan[i], channels[i].flags,
2557			    channels[i].maxpwr);
2558			continue;
2559		}
2560		/*
2561		 * Each entry defines an HT40 channel pair; find the
2562		 * center channel, then the extension channel above.
2563		 */
2564		cent = ieee80211_find_channel_byieee(ic, band->chan[i],
2565		    band->flags & ~IEEE80211_CHAN_HT);
2566		if (cent == NULL) {	/* XXX shouldn't happen */
2567			device_printf(sc->sc_dev,
2568			    "%s: no entry for channel %d\n",
2569			    __func__, band->chan[i]);
2570			continue;
2571		}
2572		extc = ieee80211_find_channel(ic, cent->ic_freq+20,
2573		    band->flags & ~IEEE80211_CHAN_HT);
2574		if (extc == NULL) {
2575			DPRINTF(sc, IWN_DEBUG_RESET,
2576			    "skip chan %d, extension channel not found\n",
2577			    band->chan[i]);
2578			continue;
2579		}
2580
2581		DPRINTF(sc, IWN_DEBUG_RESET,
2582		    "add ht40 chan %d flags 0x%x maxpwr %d\n",
2583		    band->chan[i], channels[i].flags, channels[i].maxpwr);
2584
2585		c = &ic->ic_channels[ic->ic_nchans++];
2586		c[0] = cent[0];
2587		c->ic_extieee = extc->ic_ieee;
2588		c->ic_flags &= ~IEEE80211_CHAN_HT;
2589		c->ic_flags |= IEEE80211_CHAN_HT40U;
2590		c = &ic->ic_channels[ic->ic_nchans++];
2591		c[0] = extc[0];
2592		c->ic_extieee = cent->ic_ieee;
2593		c->ic_flags &= ~IEEE80211_CHAN_HT;
2594		c->ic_flags |= IEEE80211_CHAN_HT40D;
2595	}
2596}
2597
2598static void
2599iwn_read_eeprom_channels(struct iwn_softc *sc)
2600{
2601#define	N(a)	(sizeof(a)/sizeof(a[0]))
2602	static const struct iwn_chan_band iwn_bands[] = {
2603	    { IWN_EEPROM_BAND1, IEEE80211_CHAN_G, 14,
2604		{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 } },
2605	    { IWN_EEPROM_BAND2, IEEE80211_CHAN_A, 13,
2606		{ 183, 184, 185, 187, 188, 189, 192, 196, 7, 8, 11, 12, 16 } },
2607	    { IWN_EEPROM_BAND3, IEEE80211_CHAN_A, 12,
2608		{ 34, 36, 38, 40, 42, 44, 46, 48, 52, 56, 60, 64 } },
2609	    { IWN_EEPROM_BAND4, IEEE80211_CHAN_A, 11,
2610		{ 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140 } },
2611	    { IWN_EEPROM_BAND5, IEEE80211_CHAN_A, 6,
2612		{ 145, 149, 153, 157, 161, 165 } },
2613	    { IWN_EEPROM_BAND6, IEEE80211_CHAN_G | IEEE80211_CHAN_HT40, 7,
2614		{ 1, 2, 3, 4, 5, 6, 7 } },
2615	    { IWN_EEPROM_BAND7, IEEE80211_CHAN_A | IEEE80211_CHAN_HT40, 11,
2616		{ 36, 44, 52, 60, 100, 108, 116, 124, 132, 149, 157 } }
2617	};
2618	struct ifnet *ifp = sc->sc_ifp;
2619	struct ieee80211com *ic = ifp->if_l2com;
2620	int i;
2621
2622	/* read the list of authorized channels */
2623	for (i = 0; i < N(iwn_bands)-2; i++)
2624		iwn_read_eeprom_band(sc, &iwn_bands[i]);
2625	for (; i < N(iwn_bands); i++)
2626		iwn_read_eeprom_ht40(sc, &iwn_bands[i]);
2627	ieee80211_sort_channels(ic->ic_channels, ic->ic_nchans);
2628#undef N
2629}
2630
2631#ifdef IWN_DEBUG
2632void
2633iwn_print_power_group(struct iwn_softc *sc, int i)
2634{
2635	struct iwn_eeprom_band *band = &sc->bands[i];
2636	struct iwn_eeprom_chan_samples *chans = band->chans;
2637	int j, c;
2638
2639	printf("===band %d===\n", i);
2640	printf("chan lo=%d, chan hi=%d\n", band->lo, band->hi);
2641	printf("chan1 num=%d\n", chans[0].num);
2642	for (c = 0; c < IWN_NTXCHAINS; c++) {
2643		for (j = 0; j < IWN_NSAMPLES; j++) {
2644			printf("chain %d, sample %d: temp=%d gain=%d "
2645			    "power=%d pa_det=%d\n", c, j,
2646			    chans[0].samples[c][j].temp,
2647			    chans[0].samples[c][j].gain,
2648			    chans[0].samples[c][j].power,
2649			    chans[0].samples[c][j].pa_det);
2650		}
2651	}
2652	printf("chan2 num=%d\n", chans[1].num);
2653	for (c = 0; c < IWN_NTXCHAINS; c++) {
2654		for (j = 0; j < IWN_NSAMPLES; j++) {
2655			printf("chain %d, sample %d: temp=%d gain=%d "
2656			    "power=%d pa_det=%d\n", c, j,
2657			    chans[1].samples[c][j].temp,
2658			    chans[1].samples[c][j].gain,
2659			    chans[1].samples[c][j].power,
2660			    chans[1].samples[c][j].pa_det);
2661		}
2662	}
2663}
2664#endif
2665
2666/*
2667 * Send a command to the firmware.
2668 */
2669int
2670iwn_cmd(struct iwn_softc *sc, int code, const void *buf, int size, int async)
2671{
2672	struct iwn_tx_ring *ring = &sc->txq[4];
2673	struct iwn_tx_desc *desc;
2674	struct iwn_tx_cmd *cmd;
2675	bus_addr_t paddr;
2676
2677	IWN_LOCK_ASSERT(sc);
2678
2679	KASSERT(size <= sizeof cmd->data, ("Command too big"));
2680
2681	desc = &ring->desc[ring->cur];
2682	cmd = &ring->cmd[ring->cur];
2683
2684	cmd->code = code;
2685	cmd->flags = 0;
2686	cmd->qid = ring->qid;
2687	cmd->idx = ring->cur;
2688	memcpy(cmd->data, buf, size);
2689
2690	paddr = ring->cmd_dma.paddr + ring->cur * sizeof (struct iwn_tx_cmd);
2691
2692	IWN_SET_DESC_NSEGS(desc, 1);
2693	IWN_SET_DESC_SEG(desc, 0, paddr, 4 + size);
2694	sc->shared->len[ring->qid][ring->cur] = htole16(8);
2695	if (ring->cur < IWN_TX_WINDOW) {
2696	    sc->shared->len[ring->qid][ring->cur + IWN_TX_RING_COUNT] =
2697		htole16(8);
2698	}
2699
2700	DPRINTF(sc, IWN_DEBUG_CMD, "%s: %s (0x%x) flags %d qid %d idx %d\n",
2701	    __func__, iwn_intr_str(cmd->code), cmd->code,
2702	    cmd->flags, cmd->qid, cmd->idx);
2703
2704	/* kick cmd ring */
2705	ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT;
2706	IWN_WRITE(sc, IWN_TX_WIDX, ring->qid << 8 | ring->cur);
2707
2708	return async ? 0 : msleep(cmd, &sc->sc_mtx, PCATCH, "iwncmd", hz);
2709}
2710
2711static const uint8_t iwn_ridx_to_plcp[] = {
2712	10, 20, 55, 110, /* CCK */
2713	0xd, 0xf, 0x5, 0x7, 0x9, 0xb, 0x1, 0x3, 0x3 /* OFDM R1-R4 */
2714};
2715static const uint8_t iwn_siso_mcs_to_plcp[] = {
2716	0, 0, 0, 0, 			/* CCK */
2717	0, 0, 1, 2, 3, 4, 5, 6, 7	/* HT */
2718};
2719static const uint8_t iwn_mimo_mcs_to_plcp[] = {
2720	0, 0, 0, 0, 			/* CCK */
2721	8, 8, 9, 10, 11, 12, 13, 14, 15	/* HT */
2722};
2723static const uint8_t iwn_prev_ridx[] = {
2724	/* NB: allow fallback from CCK11 to OFDM9 and from OFDM6 to CCK5 */
2725	0, 0, 1, 5,			/* CCK */
2726	2, 4, 3, 6, 7, 8, 9, 10, 10	/* OFDM */
2727};
2728
2729/*
2730 * Configure hardware link parameters for the specified
2731 * node operating on the specified channel.
2732 */
2733int
2734iwn_set_link_quality(struct iwn_softc *sc, uint8_t id,
2735	const struct ieee80211_channel *c, int async)
2736{
2737	struct iwn_cmd_link_quality lq;
2738	int i, ridx;
2739
2740	memset(&lq, 0, sizeof(lq));
2741	lq.id = id;
2742	if (IEEE80211_IS_CHAN_HT(c)) {
2743		lq.mimo = 1;
2744		lq.ssmask = 0x1;
2745	} else
2746		lq.ssmask = 0x2;
2747
2748	if (id == IWN_ID_BSS)
2749		ridx = IWN_RATE_OFDM54;
2750	else if (IEEE80211_IS_CHAN_A(c))
2751		ridx = IWN_RATE_OFDM6;
2752	else
2753		ridx = IWN_RATE_CCK1;
2754	for (i = 0; i < IWN_MAX_TX_RETRIES; i++) {
2755		/* XXX toggle antenna for retry patterns */
2756		if (IEEE80211_IS_CHAN_HT40(c)) {
2757			lq.table[i].rate = iwn_mimo_mcs_to_plcp[ridx]
2758					 | IWN_RATE_MCS;
2759			lq.table[i].rflags = IWN_RFLAG_HT
2760					 | IWN_RFLAG_HT40
2761					 | IWN_RFLAG_ANT_A;
2762			/* XXX shortGI */
2763		} else if (IEEE80211_IS_CHAN_HT(c)) {
2764			lq.table[i].rate = iwn_siso_mcs_to_plcp[ridx]
2765					 | IWN_RATE_MCS;
2766			lq.table[i].rflags = IWN_RFLAG_HT
2767					 | IWN_RFLAG_ANT_A;
2768			/* XXX shortGI */
2769		} else {
2770			lq.table[i].rate = iwn_ridx_to_plcp[ridx];
2771			if (ridx <= IWN_RATE_CCK11)
2772				lq.table[i].rflags = IWN_RFLAG_CCK;
2773			lq.table[i].rflags |= IWN_RFLAG_ANT_B;
2774		}
2775		ridx = iwn_prev_ridx[ridx];
2776	}
2777
2778	lq.dsmask = 0x3;
2779	lq.ampdu_disable = 3;
2780	lq.ampdu_limit = htole16(4000);
2781#ifdef IWN_DEBUG
2782	if (sc->sc_debug & IWN_DEBUG_STATE) {
2783		printf("%s: set link quality for node %d, mimo %d ssmask %d\n",
2784		    __func__, id, lq.mimo, lq.ssmask);
2785		printf("%s:", __func__);
2786		for (i = 0; i < IWN_MAX_TX_RETRIES; i++)
2787			printf(" %d:%x", lq.table[i].rate, lq.table[i].rflags);
2788		printf("\n");
2789	}
2790#endif
2791	return iwn_cmd(sc, IWN_CMD_TX_LINK_QUALITY, &lq, sizeof(lq), async);
2792}
2793
2794#if 0
2795
2796/*
2797 * Install a pairwise key into the hardware.
2798 */
2799int
2800iwn_set_key(struct ieee80211com *ic, struct ieee80211_node *ni,
2801    const struct ieee80211_key *k)
2802{
2803	struct iwn_softc *sc = ic->ic_softc;
2804	struct iwn_node_info node;
2805
2806	if (k->k_flags & IEEE80211_KEY_GROUP)
2807		return 0;
2808
2809	memset(&node, 0, sizeof node);
2810
2811	switch (k->k_cipher) {
2812	case IEEE80211_CIPHER_CCMP:
2813		node.security = htole16(IWN_CIPHER_CCMP);
2814		memcpy(node.key, k->k_key, k->k_len);
2815		break;
2816	default:
2817		return 0;
2818	}
2819
2820	node.id = IWN_ID_BSS;
2821	IEEE80211_ADDR_COPY(node.macaddr, ni->ni_macaddr);
2822	node.control = IWN_NODE_UPDATE;
2823	node.flags = IWN_FLAG_SET_KEY;
2824
2825	return iwn_cmd(sc, IWN_CMD_ADD_NODE, &node, sizeof node, 1);
2826}
2827#endif
2828
2829int
2830iwn_wme_update(struct ieee80211com *ic)
2831{
2832#define IWN_EXP2(x)	((1 << (x)) - 1)	/* CWmin = 2^ECWmin - 1 */
2833#define	IWN_TXOP_TO_US(v)		(v<<5)
2834	struct iwn_softc *sc = ic->ic_ifp->if_softc;
2835	struct iwn_edca_params cmd;
2836	int i;
2837
2838	memset(&cmd, 0, sizeof cmd);
2839	cmd.flags = htole32(IWN_EDCA_UPDATE);
2840	for (i = 0; i < WME_NUM_AC; i++) {
2841		const struct wmeParams *wmep =
2842		    &ic->ic_wme.wme_chanParams.cap_wmeParams[i];
2843		cmd.ac[i].aifsn = wmep->wmep_aifsn;
2844		cmd.ac[i].cwmin = htole16(IWN_EXP2(wmep->wmep_logcwmin));
2845		cmd.ac[i].cwmax = htole16(IWN_EXP2(wmep->wmep_logcwmax));
2846		cmd.ac[i].txoplimit =
2847		    htole16(IWN_TXOP_TO_US(wmep->wmep_txopLimit));
2848	}
2849	IWN_LOCK(sc);
2850	(void) iwn_cmd(sc, IWN_CMD_EDCA_PARAMS, &cmd, sizeof cmd, 1 /*async*/);
2851	IWN_UNLOCK(sc);
2852	return 0;
2853#undef IWN_TXOP_TO_US
2854#undef IWN_EXP2
2855}
2856
2857void
2858iwn_set_led(struct iwn_softc *sc, uint8_t which, uint8_t off, uint8_t on)
2859{
2860	struct iwn_cmd_led led;
2861
2862	led.which = which;
2863	led.unit = htole32(100000);	/* on/off in unit of 100ms */
2864	led.off = off;
2865	led.on = on;
2866
2867	(void) iwn_cmd(sc, IWN_CMD_SET_LED, &led, sizeof led, 1);
2868}
2869
2870/*
2871 * Set the critical temperature at which the firmware will automatically stop
2872 * the radio transmitter.
2873 */
2874int
2875iwn_set_critical_temp(struct iwn_softc *sc)
2876{
2877	struct iwn_ucode_info *uc = &sc->ucode_info;
2878	struct iwn_critical_temp crit;
2879	uint32_t r1, r2, r3, temp;
2880
2881	r1 = le32toh(uc->temp[0].chan20MHz);
2882	r2 = le32toh(uc->temp[1].chan20MHz);
2883	r3 = le32toh(uc->temp[2].chan20MHz);
2884	/* inverse function of iwn_get_temperature() */
2885	temp = r2 + (IWN_CTOK(110) * (r3 - r1)) / 259;
2886
2887	IWN_WRITE(sc, IWN_UCODE_CLR, IWN_CTEMP_STOP_RF);
2888
2889	memset(&crit, 0, sizeof crit);
2890	crit.tempR = htole32(temp);
2891	DPRINTF(sc, IWN_DEBUG_RESET, "setting critical temp to %u\n", temp);
2892	return iwn_cmd(sc, IWN_CMD_SET_CRITICAL_TEMP, &crit, sizeof crit, 0);
2893}
2894
2895void
2896iwn_enable_tsf(struct iwn_softc *sc, struct ieee80211_node *ni)
2897{
2898	struct iwn_cmd_tsf tsf;
2899	uint64_t val, mod;
2900
2901	memset(&tsf, 0, sizeof tsf);
2902	memcpy(&tsf.tstamp, ni->ni_tstamp.data, sizeof (uint64_t));
2903	tsf.bintval = htole16(ni->ni_intval);
2904	tsf.lintval = htole16(10);
2905
2906	/* XXX all wrong */
2907	/* compute remaining time until next beacon */
2908	val = (uint64_t)ni->ni_intval * 1024;	/* msecs -> usecs */
2909	DPRINTF(sc, IWN_DEBUG_ANY, "%s: val = %ju %s\n", __func__,
2910	    val, val == 0 ? "correcting" : "");
2911	if (val == 0)
2912		val = 1;
2913	mod = le64toh(tsf.tstamp) % val;
2914	tsf.binitval = htole32((uint32_t)(val - mod));
2915
2916	DPRINTF(sc, IWN_DEBUG_RESET, "TSF bintval=%u tstamp=%ju, init=%u\n",
2917	    ni->ni_intval, le64toh(tsf.tstamp), (uint32_t)(val - mod));
2918
2919	if (iwn_cmd(sc, IWN_CMD_TSF, &tsf, sizeof tsf, 1) != 0)
2920		device_printf(sc->sc_dev,
2921		    "%s: could not enable TSF\n", __func__);
2922}
2923
2924void
2925iwn_power_calibration(struct iwn_softc *sc, int temp)
2926{
2927	struct ifnet *ifp = sc->sc_ifp;
2928	struct ieee80211com *ic = ifp->if_l2com;
2929#if 0
2930	KASSERT(ic->ic_state == IEEE80211_S_RUN, ("not running"));
2931#endif
2932	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: temperature %d->%d\n",
2933	    __func__, sc->temp, temp);
2934
2935	/* adjust Tx power if need be (delta >= 3�C) */
2936	if (abs(temp - sc->temp) < 3)
2937		return;
2938
2939	sc->temp = temp;
2940
2941	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: set Tx power for channel %d\n",
2942	    __func__, ieee80211_chan2ieee(ic, ic->ic_bsschan));
2943	if (iwn_set_txpower(sc, ic->ic_bsschan, 1) != 0) {
2944		/* just warn, too bad for the automatic calibration... */
2945		device_printf(sc->sc_dev,
2946		    "%s: could not adjust Tx power\n", __func__);
2947	}
2948}
2949
2950/*
2951 * Set Tx power for a given channel (each rate has its own power settings).
2952 * This function takes into account the regulatory information from EEPROM,
2953 * the current temperature and the current voltage.
2954 */
2955int
2956iwn_set_txpower(struct iwn_softc *sc, struct ieee80211_channel *ch, int async)
2957{
2958/* fixed-point arithmetic division using a n-bit fractional part */
2959#define fdivround(a, b, n)	\
2960	((((1 << n) * (a)) / (b) + (1 << n) / 2) / (1 << n))
2961/* linear interpolation */
2962#define interpolate(x, x1, y1, x2, y2, n)	\
2963	((y1) + fdivround(((int)(x) - (x1)) * ((y2) - (y1)), (x2) - (x1), n))
2964
2965	static const int tdiv[IWN_NATTEN_GROUPS] = { 9, 8, 8, 8, 6 };
2966	struct ifnet *ifp = sc->sc_ifp;
2967	struct ieee80211com *ic = ifp->if_l2com;
2968	struct iwn_ucode_info *uc = &sc->ucode_info;
2969	struct iwn_cmd_txpower cmd;
2970	struct iwn_eeprom_chan_samples *chans;
2971	const uint8_t *rf_gain, *dsp_gain;
2972	int32_t vdiff, tdiff;
2973	int i, c, grp, maxpwr;
2974	u_int chan;
2975
2976	/* get channel number */
2977	chan = ieee80211_chan2ieee(ic, ch);
2978
2979	memset(&cmd, 0, sizeof cmd);
2980	cmd.band = IEEE80211_IS_CHAN_5GHZ(ch) ? 0 : 1;
2981	cmd.chan = chan;
2982
2983	if (IEEE80211_IS_CHAN_5GHZ(ch)) {
2984		maxpwr   = sc->maxpwr5GHz;
2985		rf_gain  = iwn_rf_gain_5ghz;
2986		dsp_gain = iwn_dsp_gain_5ghz;
2987	} else {
2988		maxpwr   = sc->maxpwr2GHz;
2989		rf_gain  = iwn_rf_gain_2ghz;
2990		dsp_gain = iwn_dsp_gain_2ghz;
2991	}
2992
2993	/* compute voltage compensation */
2994	vdiff = ((int32_t)le32toh(uc->volt) - sc->eeprom_voltage) / 7;
2995	if (vdiff > 0)
2996		vdiff *= 2;
2997	if (abs(vdiff) > 2)
2998		vdiff = 0;
2999	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
3000	    "%s: voltage compensation=%d (UCODE=%d, EEPROM=%d)\n",
3001	    __func__, vdiff, le32toh(uc->volt), sc->eeprom_voltage);
3002
3003	/* get channel's attenuation group */
3004	if (chan <= 20)		/* 1-20 */
3005		grp = 4;
3006	else if (chan <= 43)	/* 34-43 */
3007		grp = 0;
3008	else if (chan <= 70)	/* 44-70 */
3009		grp = 1;
3010	else if (chan <= 124)	/* 71-124 */
3011		grp = 2;
3012	else			/* 125-200 */
3013		grp = 3;
3014	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
3015	    "%s: chan %d, attenuation group=%d\n", __func__, chan, grp);
3016
3017	/* get channel's sub-band */
3018	for (i = 0; i < IWN_NBANDS; i++)
3019		if (sc->bands[i].lo != 0 &&
3020		    sc->bands[i].lo <= chan && chan <= sc->bands[i].hi)
3021			break;
3022	chans = sc->bands[i].chans;
3023	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
3024	    "%s: chan %d sub-band=%d\n", __func__, chan, i);
3025
3026	for (c = 0; c < IWN_NTXCHAINS; c++) {
3027		uint8_t power, gain, temp;
3028		int maxchpwr, pwr, ridx, idx;
3029
3030		power = interpolate(chan,
3031		    chans[0].num, chans[0].samples[c][1].power,
3032		    chans[1].num, chans[1].samples[c][1].power, 1);
3033		gain  = interpolate(chan,
3034		    chans[0].num, chans[0].samples[c][1].gain,
3035		    chans[1].num, chans[1].samples[c][1].gain, 1);
3036		temp  = interpolate(chan,
3037		    chans[0].num, chans[0].samples[c][1].temp,
3038		    chans[1].num, chans[1].samples[c][1].temp, 1);
3039		DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
3040		    "%s: Tx chain %d: power=%d gain=%d temp=%d\n",
3041		    __func__, c, power, gain, temp);
3042
3043		/* compute temperature compensation */
3044		tdiff = ((sc->temp - temp) * 2) / tdiv[grp];
3045		DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
3046		    "%s: temperature compensation=%d (current=%d, EEPROM=%d)\n",
3047		    __func__, tdiff, sc->temp, temp);
3048
3049		for (ridx = 0; ridx <= IWN_RIDX_MAX; ridx++) {
3050			maxchpwr = ch->ic_maxpower;
3051			if ((ridx / 8) & 1) {
3052				/* MIMO: decrease Tx power (-3dB) */
3053				maxchpwr -= 6;
3054			}
3055
3056			pwr = maxpwr - 10;
3057
3058			/* decrease power for highest OFDM rates */
3059			if ((ridx % 8) == 5)		/* 48Mbit/s */
3060				pwr -= 5;
3061			else if ((ridx % 8) == 6)	/* 54Mbit/s */
3062				pwr -= 7;
3063			else if ((ridx % 8) == 7)	/* 60Mbit/s */
3064				pwr -= 10;
3065
3066			if (pwr > maxchpwr)
3067				pwr = maxchpwr;
3068
3069			idx = gain - (pwr - power) - tdiff - vdiff;
3070			if ((ridx / 8) & 1)	/* MIMO */
3071				idx += (int32_t)le32toh(uc->atten[grp][c]);
3072
3073			if (cmd.band == 0)
3074				idx += 9;	/* 5GHz */
3075			if (ridx == IWN_RIDX_MAX)
3076				idx += 5;	/* CCK */
3077
3078			/* make sure idx stays in a valid range */
3079			if (idx < 0)
3080				idx = 0;
3081			else if (idx > IWN_MAX_PWR_INDEX)
3082				idx = IWN_MAX_PWR_INDEX;
3083
3084			DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
3085			    "%s: Tx chain %d, rate idx %d: power=%d\n",
3086			    __func__, c, ridx, idx);
3087			cmd.power[ridx].rf_gain[c] = rf_gain[idx];
3088			cmd.power[ridx].dsp_gain[c] = dsp_gain[idx];
3089		}
3090	}
3091
3092	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
3093	    "%s: set tx power for chan %d\n", __func__, chan);
3094	return iwn_cmd(sc, IWN_CMD_TXPOWER, &cmd, sizeof cmd, async);
3095
3096#undef interpolate
3097#undef fdivround
3098}
3099
3100/*
3101 * Get the best (maximum) RSSI among the
3102 * connected antennas and convert to dBm.
3103 */
3104int8_t
3105iwn_get_rssi(struct iwn_softc *sc, const struct iwn_rx_stat *stat)
3106{
3107	int mask, agc, rssi;
3108
3109	mask = (le16toh(stat->antenna) >> 4) & 0x7;
3110	agc  = (le16toh(stat->agc) >> 7) & 0x7f;
3111
3112	rssi = 0;
3113#if 0
3114	if (mask & (1 << 0))	/* Ant A */
3115		rssi = max(rssi, stat->rssi[0]);
3116	if (mask & (1 << 1))	/* Ant B */
3117		rssi = max(rssi, stat->rssi[2]);
3118	if (mask & (1 << 2))	/* Ant C */
3119		rssi = max(rssi, stat->rssi[4]);
3120#else
3121	rssi = max(rssi, stat->rssi[0]);
3122	rssi = max(rssi, stat->rssi[2]);
3123	rssi = max(rssi, stat->rssi[4]);
3124#endif
3125	DPRINTF(sc, IWN_DEBUG_RECV, "%s: agc %d mask 0x%x rssi %d %d %d "
3126	    "result %d\n", __func__, agc, mask,
3127	    stat->rssi[0], stat->rssi[2], stat->rssi[4],
3128	    rssi - agc - IWN_RSSI_TO_DBM);
3129	return rssi - agc - IWN_RSSI_TO_DBM;
3130}
3131
3132/*
3133 * Get the average noise among Rx antennas (in dBm).
3134 */
3135int
3136iwn_get_noise(const struct iwn_rx_general_stats *stats)
3137{
3138	int i, total, nbant, noise;
3139
3140	total = nbant = 0;
3141	for (i = 0; i < 3; i++) {
3142		noise = le32toh(stats->noise[i]) & 0xff;
3143		if (noise != 0) {
3144			total += noise;
3145			nbant++;
3146		}
3147	}
3148	/* there should be at least one antenna but check anyway */
3149	return (nbant == 0) ? -127 : (total / nbant) - 107;
3150}
3151
3152/*
3153 * Read temperature (in degC) from the on-board thermal sensor.
3154 */
3155int
3156iwn_get_temperature(struct iwn_softc *sc)
3157{
3158	struct iwn_ucode_info *uc = &sc->ucode_info;
3159	int32_t r1, r2, r3, r4, temp;
3160
3161	r1 = le32toh(uc->temp[0].chan20MHz);
3162	r2 = le32toh(uc->temp[1].chan20MHz);
3163	r3 = le32toh(uc->temp[2].chan20MHz);
3164	r4 = le32toh(sc->rawtemp);
3165
3166	if (r1 == r3)	/* prevents division by 0 (should not happen) */
3167		return 0;
3168
3169	/* sign-extend 23-bit R4 value to 32-bit */
3170	r4 = (r4 << 8) >> 8;
3171	/* compute temperature */
3172	temp = (259 * (r4 - r2)) / (r3 - r1);
3173	temp = (temp * 97) / 100 + 8;
3174
3175	return IWN_KTOC(temp);
3176}
3177
3178/*
3179 * Initialize sensitivity calibration state machine.
3180 */
3181int
3182iwn_init_sensitivity(struct iwn_softc *sc)
3183{
3184	struct iwn_calib_state *calib = &sc->calib;
3185	struct iwn_phy_calib_cmd cmd;
3186	int error;
3187
3188	/* reset calibration state */
3189	memset(calib, 0, sizeof (*calib));
3190	calib->state = IWN_CALIB_STATE_INIT;
3191	calib->cck_state = IWN_CCK_STATE_HIFA;
3192	/* initial values taken from the reference driver */
3193	calib->corr_ofdm_x1     = 105;
3194	calib->corr_ofdm_mrc_x1 = 220;
3195	calib->corr_ofdm_x4     =  90;
3196	calib->corr_ofdm_mrc_x4 = 170;
3197	calib->corr_cck_x4      = 125;
3198	calib->corr_cck_mrc_x4  = 200;
3199	calib->energy_cck       = 100;
3200
3201	/* write initial sensitivity values */
3202	error = iwn_send_sensitivity(sc);
3203	if (error != 0)
3204		return error;
3205
3206	memset(&cmd, 0, sizeof cmd);
3207	cmd.code = IWN_SET_DIFF_GAIN;
3208	/* differential gains initially set to 0 for all 3 antennas */
3209	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: calibrate phy\n", __func__);
3210	return iwn_cmd(sc, IWN_PHY_CALIB, &cmd, sizeof cmd, 1);
3211}
3212
3213/*
3214 * Collect noise and RSSI statistics for the first 20 beacons received
3215 * after association and use them to determine connected antennas and
3216 * set differential gains.
3217 */
3218void
3219iwn_compute_differential_gain(struct iwn_softc *sc,
3220    const struct iwn_rx_general_stats *stats)
3221{
3222	struct iwn_calib_state *calib = &sc->calib;
3223	struct iwn_phy_calib_cmd cmd;
3224	int i, val;
3225
3226	/* accumulate RSSI and noise for all 3 antennas */
3227	for (i = 0; i < 3; i++) {
3228		calib->rssi[i] += le32toh(stats->rssi[i]) & 0xff;
3229		calib->noise[i] += le32toh(stats->noise[i]) & 0xff;
3230	}
3231
3232	/* we update differential gain only once after 20 beacons */
3233	if (++calib->nbeacons < 20)
3234		return;
3235
3236	/* determine antenna with highest average RSSI */
3237	val = max(calib->rssi[0], calib->rssi[1]);
3238	val = max(calib->rssi[2], val);
3239
3240	/* determine which antennas are connected */
3241	sc->antmsk = 0;
3242	for (i = 0; i < 3; i++)
3243		if (val - calib->rssi[i] <= 15 * 20)
3244			sc->antmsk |= 1 << i;
3245	/* if neither Ant A and Ant B are connected.. */
3246	if ((sc->antmsk & (1 << 0 | 1 << 1)) == 0)
3247		sc->antmsk |= 1 << 1;	/* ..mark Ant B as connected! */
3248
3249	/* get minimal noise among connected antennas */
3250	val = INT_MAX;	/* ok, there's at least one */
3251	for (i = 0; i < 3; i++)
3252		if (sc->antmsk & (1 << i))
3253			val = min(calib->noise[i], val);
3254
3255	memset(&cmd, 0, sizeof cmd);
3256	cmd.code = IWN_SET_DIFF_GAIN;
3257	/* set differential gains for connected antennas */
3258	for (i = 0; i < 3; i++) {
3259		if (sc->antmsk & (1 << i)) {
3260			cmd.gain[i] = (calib->noise[i] - val) / 30;
3261			/* limit differential gain to 3 */
3262			cmd.gain[i] = min(cmd.gain[i], 3);
3263			cmd.gain[i] |= IWN_GAIN_SET;
3264		}
3265	}
3266	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
3267	    "%s: set differential gains Ant A/B/C: %x/%x/%x (%x)\n",
3268	    __func__,cmd.gain[0], cmd.gain[1], cmd.gain[2], sc->antmsk);
3269	if (iwn_cmd(sc, IWN_PHY_CALIB, &cmd, sizeof cmd, 1) == 0)
3270		calib->state = IWN_CALIB_STATE_RUN;
3271}
3272
3273/*
3274 * Tune RF Rx sensitivity based on the number of false alarms detected
3275 * during the last beacon period.
3276 */
3277void
3278iwn_tune_sensitivity(struct iwn_softc *sc, const struct iwn_rx_stats *stats)
3279{
3280#define inc_clip(val, inc, max)			\
3281	if ((val) < (max)) {			\
3282		if ((val) < (max) - (inc))	\
3283			(val) += (inc);		\
3284		else				\
3285			(val) = (max);		\
3286		needs_update = 1;		\
3287	}
3288#define dec_clip(val, dec, min)			\
3289	if ((val) > (min)) {			\
3290		if ((val) > (min) + (dec))	\
3291			(val) -= (dec);		\
3292		else				\
3293			(val) = (min);		\
3294		needs_update = 1;		\
3295	}
3296
3297	struct iwn_calib_state *calib = &sc->calib;
3298	uint32_t val, rxena, fa;
3299	uint32_t energy[3], energy_min;
3300	uint8_t noise[3], noise_ref;
3301	int i, needs_update = 0;
3302
3303	/* check that we've been enabled long enough */
3304	if ((rxena = le32toh(stats->general.load)) == 0)
3305		return;
3306
3307	/* compute number of false alarms since last call for OFDM */
3308	fa  = le32toh(stats->ofdm.bad_plcp) - calib->bad_plcp_ofdm;
3309	fa += le32toh(stats->ofdm.fa) - calib->fa_ofdm;
3310	fa *= 200 * 1024;	/* 200TU */
3311
3312	/* save counters values for next call */
3313	calib->bad_plcp_ofdm = le32toh(stats->ofdm.bad_plcp);
3314	calib->fa_ofdm = le32toh(stats->ofdm.fa);
3315
3316	if (fa > 50 * rxena) {
3317		/* high false alarm count, decrease sensitivity */
3318		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
3319		    "%s: OFDM high false alarm count: %u\n", __func__, fa);
3320		inc_clip(calib->corr_ofdm_x1,     1, 140);
3321		inc_clip(calib->corr_ofdm_mrc_x1, 1, 270);
3322		inc_clip(calib->corr_ofdm_x4,     1, 120);
3323		inc_clip(calib->corr_ofdm_mrc_x4, 1, 210);
3324
3325	} else if (fa < 5 * rxena) {
3326		/* low false alarm count, increase sensitivity */
3327		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
3328		    "%s: OFDM low false alarm count: %u\n", __func__, fa);
3329		dec_clip(calib->corr_ofdm_x1,     1, 105);
3330		dec_clip(calib->corr_ofdm_mrc_x1, 1, 220);
3331		dec_clip(calib->corr_ofdm_x4,     1,  85);
3332		dec_clip(calib->corr_ofdm_mrc_x4, 1, 170);
3333	}
3334
3335	/* compute maximum noise among 3 antennas */
3336	for (i = 0; i < 3; i++)
3337		noise[i] = (le32toh(stats->general.noise[i]) >> 8) & 0xff;
3338	val = max(noise[0], noise[1]);
3339	val = max(noise[2], val);
3340	/* insert it into our samples table */
3341	calib->noise_samples[calib->cur_noise_sample] = val;
3342	calib->cur_noise_sample = (calib->cur_noise_sample + 1) % 20;
3343
3344	/* compute maximum noise among last 20 samples */
3345	noise_ref = calib->noise_samples[0];
3346	for (i = 1; i < 20; i++)
3347		noise_ref = max(noise_ref, calib->noise_samples[i]);
3348
3349	/* compute maximum energy among 3 antennas */
3350	for (i = 0; i < 3; i++)
3351		energy[i] = le32toh(stats->general.energy[i]);
3352	val = min(energy[0], energy[1]);
3353	val = min(energy[2], val);
3354	/* insert it into our samples table */
3355	calib->energy_samples[calib->cur_energy_sample] = val;
3356	calib->cur_energy_sample = (calib->cur_energy_sample + 1) % 10;
3357
3358	/* compute minimum energy among last 10 samples */
3359	energy_min = calib->energy_samples[0];
3360	for (i = 1; i < 10; i++)
3361		energy_min = max(energy_min, calib->energy_samples[i]);
3362	energy_min += 6;
3363
3364	/* compute number of false alarms since last call for CCK */
3365	fa  = le32toh(stats->cck.bad_plcp) - calib->bad_plcp_cck;
3366	fa += le32toh(stats->cck.fa) - calib->fa_cck;
3367	fa *= 200 * 1024;	/* 200TU */
3368
3369	/* save counters values for next call */
3370	calib->bad_plcp_cck = le32toh(stats->cck.bad_plcp);
3371	calib->fa_cck = le32toh(stats->cck.fa);
3372
3373	if (fa > 50 * rxena) {
3374		/* high false alarm count, decrease sensitivity */
3375		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
3376		    "%s: CCK high false alarm count: %u\n", __func__, fa);
3377		calib->cck_state = IWN_CCK_STATE_HIFA;
3378		calib->low_fa = 0;
3379
3380		if (calib->corr_cck_x4 > 160) {
3381			calib->noise_ref = noise_ref;
3382			if (calib->energy_cck > 2)
3383				dec_clip(calib->energy_cck, 2, energy_min);
3384		}
3385		if (calib->corr_cck_x4 < 160) {
3386			calib->corr_cck_x4 = 161;
3387			needs_update = 1;
3388		} else
3389			inc_clip(calib->corr_cck_x4, 3, 200);
3390
3391		inc_clip(calib->corr_cck_mrc_x4, 3, 400);
3392
3393	} else if (fa < 5 * rxena) {
3394		/* low false alarm count, increase sensitivity */
3395		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
3396		    "%s: CCK low false alarm count: %u\n", __func__, fa);
3397		calib->cck_state = IWN_CCK_STATE_LOFA;
3398		calib->low_fa++;
3399
3400		if (calib->cck_state != 0 &&
3401		    ((calib->noise_ref - noise_ref) > 2 ||
3402		     calib->low_fa > 100)) {
3403			inc_clip(calib->energy_cck,      2,  97);
3404			dec_clip(calib->corr_cck_x4,     3, 125);
3405			dec_clip(calib->corr_cck_mrc_x4, 3, 200);
3406		}
3407	} else {
3408		/* not worth to increase or decrease sensitivity */
3409		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
3410		    "%s: CCK normal false alarm count: %u\n", __func__, fa);
3411		calib->low_fa = 0;
3412		calib->noise_ref = noise_ref;
3413
3414		if (calib->cck_state == IWN_CCK_STATE_HIFA) {
3415			/* previous interval had many false alarms */
3416			dec_clip(calib->energy_cck, 8, energy_min);
3417		}
3418		calib->cck_state = IWN_CCK_STATE_INIT;
3419	}
3420
3421	if (needs_update)
3422		(void)iwn_send_sensitivity(sc);
3423#undef dec_clip
3424#undef inc_clip
3425}
3426
3427int
3428iwn_send_sensitivity(struct iwn_softc *sc)
3429{
3430	struct iwn_calib_state *calib = &sc->calib;
3431	struct iwn_sensitivity_cmd cmd;
3432
3433	memset(&cmd, 0, sizeof cmd);
3434	cmd.which = IWN_SENSITIVITY_WORKTBL;
3435	/* OFDM modulation */
3436	cmd.corr_ofdm_x1     = htole16(calib->corr_ofdm_x1);
3437	cmd.corr_ofdm_mrc_x1 = htole16(calib->corr_ofdm_mrc_x1);
3438	cmd.corr_ofdm_x4     = htole16(calib->corr_ofdm_x4);
3439	cmd.corr_ofdm_mrc_x4 = htole16(calib->corr_ofdm_mrc_x4);
3440	cmd.energy_ofdm      = htole16(100);
3441	cmd.energy_ofdm_th   = htole16(62);
3442	/* CCK modulation */
3443	cmd.corr_cck_x4      = htole16(calib->corr_cck_x4);
3444	cmd.corr_cck_mrc_x4  = htole16(calib->corr_cck_mrc_x4);
3445	cmd.energy_cck       = htole16(calib->energy_cck);
3446	/* Barker modulation: use default values */
3447	cmd.corr_barker      = htole16(190);
3448	cmd.corr_barker_mrc  = htole16(390);
3449
3450	DPRINTF(sc, IWN_DEBUG_RESET,
3451	    "%s: set sensitivity %d/%d/%d/%d/%d/%d/%d\n", __func__,
3452	    calib->corr_ofdm_x1, calib->corr_ofdm_mrc_x1, calib->corr_ofdm_x4,
3453	    calib->corr_ofdm_mrc_x4, calib->corr_cck_x4,
3454	    calib->corr_cck_mrc_x4, calib->energy_cck);
3455	return iwn_cmd(sc, IWN_SENSITIVITY, &cmd, sizeof cmd, 1);
3456}
3457
3458int
3459iwn_auth(struct iwn_softc *sc)
3460{
3461	struct ifnet *ifp = sc->sc_ifp;
3462	struct ieee80211com *ic = ifp->if_l2com;
3463	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);	/*XXX*/
3464	struct ieee80211_node *ni = vap->iv_bss;
3465	struct iwn_node_info node;
3466	int error;
3467
3468	sc->calib.state = IWN_CALIB_STATE_INIT;
3469
3470	/* update adapter's configuration */
3471	sc->config.associd = 0;
3472	IEEE80211_ADDR_COPY(sc->config.bssid, ni->ni_bssid);
3473	sc->config.chan = htole16(ieee80211_chan2ieee(ic, ni->ni_chan));
3474	sc->config.flags = htole32(IWN_CONFIG_TSF);
3475	if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
3476		sc->config.flags |= htole32(IWN_CONFIG_AUTO | IWN_CONFIG_24GHZ);
3477	if (IEEE80211_IS_CHAN_A(ni->ni_chan)) {
3478		sc->config.cck_mask  = 0;
3479		sc->config.ofdm_mask = 0x15;
3480	} else if (IEEE80211_IS_CHAN_B(ni->ni_chan)) {
3481		sc->config.cck_mask  = 0x03;
3482		sc->config.ofdm_mask = 0;
3483	} else {
3484		/* XXX assume 802.11b/g */
3485		sc->config.cck_mask  = 0x0f;
3486		sc->config.ofdm_mask = 0x15;
3487	}
3488	if (ic->ic_flags & IEEE80211_F_SHSLOT)
3489		sc->config.flags |= htole32(IWN_CONFIG_SHSLOT);
3490	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
3491		sc->config.flags |= htole32(IWN_CONFIG_SHPREAMBLE);
3492	sc->config.filter &= ~htole32(IWN_FILTER_BSS);
3493
3494	DPRINTF(sc, IWN_DEBUG_STATE,
3495	   "%s: config chan %d mode %d flags 0x%x cck 0x%x ofdm 0x%x "
3496	   "ht_single 0x%x ht_dual 0x%x rxchain 0x%x "
3497	   "myaddr %6D wlap %6D bssid %6D associd %d filter 0x%x\n",
3498	   __func__,
3499	   le16toh(sc->config.chan), sc->config.mode, le32toh(sc->config.flags),
3500	   sc->config.cck_mask, sc->config.ofdm_mask,
3501	   sc->config.ht_single_mask, sc->config.ht_dual_mask,
3502	   le16toh(sc->config.rxchain),
3503	   sc->config.myaddr, ":", sc->config.wlap, ":", sc->config.bssid, ":",
3504	   le16toh(sc->config.associd), le32toh(sc->config.filter));
3505	error = iwn_cmd(sc, IWN_CMD_CONFIGURE, &sc->config,
3506	    sizeof (struct iwn_config), 1);
3507	if (error != 0) {
3508		device_printf(sc->sc_dev,
3509		    "%s: could not configure, error %d\n", __func__, error);
3510		return error;
3511	}
3512	sc->sc_curchan = ic->ic_curchan;
3513
3514	/* configuration has changed, set Tx power accordingly */
3515	error = iwn_set_txpower(sc, ni->ni_chan, 1);
3516	if (error != 0) {
3517		device_printf(sc->sc_dev,
3518		    "%s: could not set Tx power, error %d\n", __func__, error);
3519		return error;
3520	}
3521
3522	/*
3523	 * Reconfiguring clears the adapter's nodes table so we must
3524	 * add the broadcast node again.
3525	 */
3526	memset(&node, 0, sizeof node);
3527	IEEE80211_ADDR_COPY(node.macaddr, ifp->if_broadcastaddr);
3528	node.id = IWN_ID_BROADCAST;
3529	DPRINTF(sc, IWN_DEBUG_STATE, "%s: add broadcast node\n", __func__);
3530	error = iwn_cmd(sc, IWN_CMD_ADD_NODE, &node, sizeof node, 1);
3531	if (error != 0) {
3532		device_printf(sc->sc_dev,
3533		    "%s: could not add broadcast node, error %d\n",
3534		    __func__, error);
3535		return error;
3536	}
3537	error = iwn_set_link_quality(sc, node.id, ic->ic_curchan, 1);
3538	if (error != 0) {
3539		device_printf(sc->sc_dev,
3540		    "%s: could not setup MRR for broadcast node, error %d\n",
3541		    __func__, error);
3542		return error;
3543	}
3544
3545	return 0;
3546}
3547
3548/*
3549 * Configure the adapter for associated state.
3550 */
3551int
3552iwn_run(struct iwn_softc *sc)
3553{
3554#define	MS(v,x)	(((v) & x) >> x##_S)
3555	struct ifnet *ifp = sc->sc_ifp;
3556	struct ieee80211com *ic = ifp->if_l2com;
3557	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);	/*XXX*/
3558	struct ieee80211_node *ni = vap->iv_bss;
3559	struct iwn_node_info node;
3560	int error, maxrxampdu, ampdudensity;
3561
3562	sc->calib.state = IWN_CALIB_STATE_INIT;
3563
3564	if (ic->ic_opmode == IEEE80211_M_MONITOR) {
3565		/* link LED blinks while monitoring */
3566		iwn_set_led(sc, IWN_LED_LINK, 5, 5);
3567		return 0;
3568	}
3569
3570	iwn_enable_tsf(sc, ni);
3571
3572	/* update adapter's configuration */
3573	sc->config.associd = htole16(IEEE80211_AID(ni->ni_associd));
3574	/* short preamble/slot time are negotiated when associating */
3575	sc->config.flags &= ~htole32(IWN_CONFIG_SHPREAMBLE | IWN_CONFIG_SHSLOT);
3576	if (ic->ic_flags & IEEE80211_F_SHSLOT)
3577		sc->config.flags |= htole32(IWN_CONFIG_SHSLOT);
3578	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
3579		sc->config.flags |= htole32(IWN_CONFIG_SHPREAMBLE);
3580	if (IEEE80211_IS_CHAN_HT(ni->ni_chan)) {
3581		sc->config.flags &= ~htole32(IWN_CONFIG_HT);
3582		if (IEEE80211_IS_CHAN_HT40U(ni->ni_chan))
3583			sc->config.flags |= htole32(IWN_CONFIG_HT40U);
3584		else if (IEEE80211_IS_CHAN_HT40D(ni->ni_chan))
3585			sc->config.flags |= htole32(IWN_CONFIG_HT40D);
3586		else
3587			sc->config.flags |= htole32(IWN_CONFIG_HT20);
3588		sc->config.rxchain = htole16(
3589			  (3 << IWN_RXCHAIN_VALID_S)
3590			| (3 << IWN_RXCHAIN_MIMO_CNT_S)
3591			| (1 << IWN_RXCHAIN_CNT_S)
3592			| IWN_RXCHAIN_MIMO_FORCE);
3593
3594		maxrxampdu = MS(ni->ni_htparam, IEEE80211_HTCAP_MAXRXAMPDU);
3595		ampdudensity = MS(ni->ni_htparam, IEEE80211_HTCAP_MPDUDENSITY);
3596	} else
3597		maxrxampdu = ampdudensity = 0;
3598	sc->config.filter |= htole32(IWN_FILTER_BSS);
3599
3600	DPRINTF(sc, IWN_DEBUG_STATE,
3601	   "%s: config chan %d mode %d flags 0x%x cck 0x%x ofdm 0x%x "
3602	   "ht_single 0x%x ht_dual 0x%x rxchain 0x%x "
3603	   "myaddr %6D wlap %6D bssid %6D associd %d filter 0x%x\n",
3604	   __func__,
3605	   le16toh(sc->config.chan), sc->config.mode, le32toh(sc->config.flags),
3606	   sc->config.cck_mask, sc->config.ofdm_mask,
3607	   sc->config.ht_single_mask, sc->config.ht_dual_mask,
3608	   le16toh(sc->config.rxchain),
3609	   sc->config.myaddr, ":", sc->config.wlap, ":", sc->config.bssid, ":",
3610	   le16toh(sc->config.associd), le32toh(sc->config.filter));
3611	error = iwn_cmd(sc, IWN_CMD_CONFIGURE, &sc->config,
3612	    sizeof (struct iwn_config), 1);
3613	if (error != 0) {
3614		device_printf(sc->sc_dev,
3615		    "%s: could not update configuration, error %d\n",
3616		    __func__, error);
3617		return error;
3618	}
3619	sc->sc_curchan = ni->ni_chan;
3620
3621	/* configuration has changed, set Tx power accordingly */
3622	error = iwn_set_txpower(sc, ni->ni_chan, 1);
3623	if (error != 0) {
3624		device_printf(sc->sc_dev,
3625		    "%s: could not set Tx power, error %d\n", __func__, error);
3626		return error;
3627	}
3628
3629	/* add BSS node */
3630	memset(&node, 0, sizeof node);
3631	IEEE80211_ADDR_COPY(node.macaddr, ni->ni_macaddr);
3632	node.id = IWN_ID_BSS;
3633	node.htflags = htole32(
3634	    (maxrxampdu << IWN_MAXRXAMPDU_S) |
3635	    (ampdudensity << IWN_MPDUDENSITY_S));
3636	DPRINTF(sc, IWN_DEBUG_STATE, "%s: add BSS node, id %d htflags 0x%x\n",
3637	    __func__, node.id, le32toh(node.htflags));
3638	error = iwn_cmd(sc, IWN_CMD_ADD_NODE, &node, sizeof node, 1);
3639	if (error != 0) {
3640		device_printf(sc->sc_dev,"could not add BSS node\n");
3641		return error;
3642	}
3643	error = iwn_set_link_quality(sc, node.id, ni->ni_chan, 1);
3644	if (error != 0) {
3645		device_printf(sc->sc_dev,
3646		    "%s: could not setup MRR for node %d, error %d\n",
3647		    __func__, node.id, error);
3648		return error;
3649	}
3650
3651	if (ic->ic_opmode == IEEE80211_M_STA) {
3652		/* fake a join to init the tx rate */
3653		iwn_newassoc(ni, 1);
3654	}
3655
3656	error = iwn_init_sensitivity(sc);
3657	if (error != 0) {
3658		device_printf(sc->sc_dev,
3659		    "%s: could not set sensitivity, error %d\n",
3660		    __func__, error);
3661		return error;
3662	}
3663
3664	/* start/restart periodic calibration timer */
3665	sc->calib.state = IWN_CALIB_STATE_ASSOC;
3666	iwn_calib_reset(sc);
3667
3668	/* link LED always on while associated */
3669	iwn_set_led(sc, IWN_LED_LINK, 0, 1);
3670
3671	return 0;
3672#undef MS
3673}
3674
3675/*
3676 * Send a scan request to the firmware.  Since this command is huge, we map it
3677 * into a mbuf instead of using the pre-allocated set of commands.
3678 */
3679int
3680iwn_scan(struct iwn_softc *sc)
3681{
3682	struct ifnet *ifp = sc->sc_ifp;
3683	struct ieee80211com *ic = ifp->if_l2com;
3684	struct ieee80211_scan_state *ss = ic->ic_scan;	/*XXX*/
3685	struct iwn_tx_ring *ring = &sc->txq[4];
3686	struct iwn_tx_desc *desc;
3687	struct iwn_tx_data *data;
3688	struct iwn_tx_cmd *cmd;
3689	struct iwn_cmd_data *tx;
3690	struct iwn_scan_hdr *hdr;
3691	struct iwn_scan_essid *essid;
3692	struct iwn_scan_chan *chan;
3693	struct ieee80211_frame *wh;
3694	struct ieee80211_rateset *rs;
3695	struct ieee80211_channel *c;
3696	enum ieee80211_phymode mode;
3697	uint8_t *frm;
3698	int pktlen, error, nrates;
3699	bus_addr_t physaddr;
3700
3701	desc = &ring->desc[ring->cur];
3702	data = &ring->data[ring->cur];
3703
3704	/* XXX malloc */
3705	data->m = m_getcl(M_DONTWAIT, MT_DATA, 0);
3706	if (data->m == NULL) {
3707		device_printf(sc->sc_dev,
3708		    "%s: could not allocate mbuf for scan command\n", __func__);
3709		return ENOMEM;
3710	}
3711
3712	cmd = mtod(data->m, struct iwn_tx_cmd *);
3713	cmd->code = IWN_CMD_SCAN;
3714	cmd->flags = 0;
3715	cmd->qid = ring->qid;
3716	cmd->idx = ring->cur;
3717
3718	hdr = (struct iwn_scan_hdr *)cmd->data;
3719	memset(hdr, 0, sizeof (struct iwn_scan_hdr));
3720
3721	/* XXX use scan state */
3722	/*
3723	 * Move to the next channel if no packets are received within 5 msecs
3724	 * after sending the probe request (this helps to reduce the duration
3725	 * of active scans).
3726	 */
3727	hdr->quiet = htole16(5);	/* timeout in milliseconds */
3728	hdr->plcp_threshold = htole16(1);	/* min # of packets */
3729
3730	/* select Ant B and Ant C for scanning */
3731	hdr->rxchain = htole16(0x3e1 | (7 << IWN_RXCHAIN_VALID_S));
3732
3733	tx = (struct iwn_cmd_data *)(hdr + 1);
3734	memset(tx, 0, sizeof (struct iwn_cmd_data));
3735	tx->flags = htole32(IWN_TX_AUTO_SEQ | 0x200);	/* XXX */
3736	tx->id = IWN_ID_BROADCAST;
3737	tx->lifetime = htole32(IWN_LIFETIME_INFINITE);
3738	tx->rflags = IWN_RFLAG_ANT_B;
3739
3740	if (IEEE80211_IS_CHAN_A(ic->ic_curchan)) {
3741		hdr->crc_threshold = htole16(1);
3742		/* send probe requests at 6Mbps */
3743		tx->rate = iwn_ridx_to_plcp[IWN_RATE_OFDM6];
3744	} else {
3745		hdr->flags = htole32(IWN_CONFIG_24GHZ | IWN_CONFIG_AUTO);
3746		/* send probe requests at 1Mbps */
3747		tx->rate = iwn_ridx_to_plcp[IWN_RATE_CCK1];
3748		tx->rflags |= IWN_RFLAG_CCK;
3749	}
3750
3751	essid = (struct iwn_scan_essid *)(tx + 1);
3752	memset(essid, 0, 4 * sizeof (struct iwn_scan_essid));
3753	essid[0].id  = IEEE80211_ELEMID_SSID;
3754	essid[0].len = ss->ss_ssid[0].len;
3755	memcpy(essid[0].data, ss->ss_ssid[0].ssid, ss->ss_ssid[0].len);
3756
3757	/*
3758	 * Build a probe request frame.  Most of the following code is a
3759	 * copy & paste of what is done in net80211.
3760	 */
3761	wh = (struct ieee80211_frame *)&essid[4];
3762	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
3763	    IEEE80211_FC0_SUBTYPE_PROBE_REQ;
3764	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
3765	IEEE80211_ADDR_COPY(wh->i_addr1, ifp->if_broadcastaddr);
3766	IEEE80211_ADDR_COPY(wh->i_addr2, ic->ic_myaddr);
3767	IEEE80211_ADDR_COPY(wh->i_addr3, ifp->if_broadcastaddr);
3768	*(u_int16_t *)&wh->i_dur[0] = 0;	/* filled by h/w */
3769	*(u_int16_t *)&wh->i_seq[0] = 0;	/* filled by h/w */
3770
3771	frm = (uint8_t *)(wh + 1);
3772
3773	/* add SSID IE */
3774        *frm++ = IEEE80211_ELEMID_SSID;
3775        *frm++ = ss->ss_ssid[0].len;
3776        memcpy(frm, ss->ss_ssid[0].ssid, ss->ss_ssid[0].len);
3777	frm += ss->ss_ssid[0].len;
3778
3779	mode = ieee80211_chan2mode(ic->ic_curchan);
3780	rs = &ic->ic_sup_rates[mode];
3781
3782	/* add supported rates IE */
3783	*frm++ = IEEE80211_ELEMID_RATES;
3784	nrates = rs->rs_nrates;
3785	if (nrates > IEEE80211_RATE_SIZE)
3786		nrates = IEEE80211_RATE_SIZE;
3787	*frm++ = nrates;
3788	memcpy(frm, rs->rs_rates, nrates);
3789	frm += nrates;
3790
3791	/* add supported xrates IE */
3792	if (rs->rs_nrates > IEEE80211_RATE_SIZE) {
3793		nrates = rs->rs_nrates - IEEE80211_RATE_SIZE;
3794		*frm++ = IEEE80211_ELEMID_XRATES;
3795		*frm++ = (uint8_t)nrates;
3796		memcpy(frm, rs->rs_rates + IEEE80211_RATE_SIZE, nrates);
3797		frm += nrates;
3798	}
3799
3800	/* setup length of probe request */
3801	tx->len = htole16(frm - (uint8_t *)wh);
3802
3803	c = ic->ic_curchan;
3804	chan = (struct iwn_scan_chan *)frm;
3805	chan->chan = ieee80211_chan2ieee(ic, c);
3806	chan->flags = 0;
3807	if ((c->ic_flags & IEEE80211_CHAN_PASSIVE) == 0) {
3808		chan->flags |= IWN_CHAN_ACTIVE;
3809		if (ss->ss_nssid > 0)
3810			chan->flags |= IWN_CHAN_DIRECT;
3811	}
3812	chan->dsp_gain = 0x6e;
3813	if (IEEE80211_IS_CHAN_5GHZ(c)) {
3814		chan->rf_gain = 0x3b;
3815		chan->active  = htole16(10);
3816		chan->passive = htole16(110);
3817	} else {
3818		chan->rf_gain = 0x28;
3819		chan->active  = htole16(20);
3820		chan->passive = htole16(120);
3821	}
3822
3823	DPRINTF(sc, IWN_DEBUG_STATE, "%s: chan %u flags 0x%x rf_gain 0x%x "
3824	    "dsp_gain 0x%x active 0x%x passive 0x%x\n", __func__,
3825	    chan->chan, chan->flags, chan->rf_gain, chan->dsp_gain,
3826	    chan->active, chan->passive);
3827	hdr->nchan++;
3828	chan++;
3829
3830	frm += sizeof (struct iwn_scan_chan);
3831
3832	hdr->len = htole16(frm - (uint8_t *)hdr);
3833	pktlen = frm - (uint8_t *)cmd;
3834
3835	error = bus_dmamap_load(ring->data_dmat, data->map, cmd, pktlen,
3836	    iwn_dma_map_addr, &physaddr, BUS_DMA_NOWAIT);
3837	if (error != 0) {
3838		device_printf(sc->sc_dev,
3839		    "%s: could not map scan command, error %d\n",
3840		    __func__, error);
3841		m_freem(data->m);
3842		data->m = NULL;
3843		return error;
3844	}
3845
3846	IWN_SET_DESC_NSEGS(desc, 1);
3847	IWN_SET_DESC_SEG(desc, 0, physaddr, pktlen);
3848	sc->shared->len[ring->qid][ring->cur] = htole16(8);
3849	if (ring->cur < IWN_TX_WINDOW)
3850		sc->shared->len[ring->qid][ring->cur + IWN_TX_RING_COUNT] =
3851		    htole16(8);
3852
3853	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
3854	    BUS_DMASYNC_PREWRITE);
3855	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
3856
3857	/* kick cmd ring */
3858	ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT;
3859	IWN_WRITE(sc, IWN_TX_WIDX, ring->qid << 8 | ring->cur);
3860
3861	return 0;	/* will be notified async. of failure/success */
3862}
3863
3864int
3865iwn_config(struct iwn_softc *sc)
3866{
3867	struct ifnet *ifp = sc->sc_ifp;
3868	struct ieee80211com *ic = ifp->if_l2com;
3869	struct iwn_power power;
3870	struct iwn_bluetooth bluetooth;
3871	struct iwn_node_info node;
3872	int error;
3873
3874	/* set power mode */
3875	memset(&power, 0, sizeof power);
3876	power.flags = htole16(IWN_POWER_CAM | 0x8);
3877	DPRINTF(sc, IWN_DEBUG_RESET, "%s: set power mode\n", __func__);
3878	error = iwn_cmd(sc, IWN_CMD_SET_POWER_MODE, &power, sizeof power, 0);
3879	if (error != 0) {
3880		device_printf(sc->sc_dev,
3881		    "%s: could not set power mode, error %d\n",
3882		    __func__, error);
3883		return error;
3884	}
3885
3886	/* configure bluetooth coexistence */
3887	memset(&bluetooth, 0, sizeof bluetooth);
3888	bluetooth.flags = 3;
3889	bluetooth.lead = 0xaa;
3890	bluetooth.kill = 1;
3891	DPRINTF(sc, IWN_DEBUG_RESET, "%s: config bluetooth coexistence\n",
3892	    __func__);
3893	error = iwn_cmd(sc, IWN_CMD_BLUETOOTH, &bluetooth, sizeof bluetooth,
3894	    0);
3895	if (error != 0) {
3896		device_printf(sc->sc_dev,
3897		    "%s: could not configure bluetooth coexistence, error %d\n",
3898		    __func__, error);
3899		return error;
3900	}
3901
3902	/* configure adapter */
3903	memset(&sc->config, 0, sizeof (struct iwn_config));
3904	IEEE80211_ADDR_COPY(sc->config.myaddr, ic->ic_myaddr);
3905	IEEE80211_ADDR_COPY(sc->config.wlap, ic->ic_myaddr);
3906	/* set default channel */
3907	sc->config.chan = htole16(ieee80211_chan2ieee(ic, ic->ic_curchan));
3908	sc->config.flags = htole32(IWN_CONFIG_TSF);
3909	if (IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan))
3910		sc->config.flags |= htole32(IWN_CONFIG_AUTO | IWN_CONFIG_24GHZ);
3911	sc->config.filter = 0;
3912	switch (ic->ic_opmode) {
3913	case IEEE80211_M_STA:
3914		sc->config.mode = IWN_MODE_STA;
3915		sc->config.filter |= htole32(IWN_FILTER_MULTICAST);
3916		break;
3917	case IEEE80211_M_IBSS:
3918	case IEEE80211_M_AHDEMO:
3919		sc->config.mode = IWN_MODE_IBSS;
3920		break;
3921	case IEEE80211_M_HOSTAP:
3922		sc->config.mode = IWN_MODE_HOSTAP;
3923		break;
3924	case IEEE80211_M_MONITOR:
3925		sc->config.mode = IWN_MODE_MONITOR;
3926		sc->config.filter |= htole32(IWN_FILTER_MULTICAST |
3927		    IWN_FILTER_CTL | IWN_FILTER_PROMISC);
3928		break;
3929	default:
3930		break;
3931	}
3932	sc->config.cck_mask  = 0x0f;	/* not yet negotiated */
3933	sc->config.ofdm_mask = 0xff;	/* not yet negotiated */
3934	sc->config.ht_single_mask = 0xff;
3935	sc->config.ht_dual_mask = 0xff;
3936	sc->config.rxchain = htole16(0x2800 | (7 << IWN_RXCHAIN_VALID_S));
3937
3938	DPRINTF(sc, IWN_DEBUG_STATE,
3939	   "%s: config chan %d mode %d flags 0x%x cck 0x%x ofdm 0x%x "
3940	   "ht_single 0x%x ht_dual 0x%x rxchain 0x%x "
3941	   "myaddr %6D wlap %6D bssid %6D associd %d filter 0x%x\n",
3942	   __func__,
3943	   le16toh(sc->config.chan), sc->config.mode, le32toh(sc->config.flags),
3944	   sc->config.cck_mask, sc->config.ofdm_mask,
3945	   sc->config.ht_single_mask, sc->config.ht_dual_mask,
3946	   le16toh(sc->config.rxchain),
3947	   sc->config.myaddr, ":", sc->config.wlap, ":", sc->config.bssid, ":",
3948	   le16toh(sc->config.associd), le32toh(sc->config.filter));
3949	error = iwn_cmd(sc, IWN_CMD_CONFIGURE, &sc->config,
3950	    sizeof (struct iwn_config), 0);
3951	if (error != 0) {
3952		device_printf(sc->sc_dev,
3953		    "%s: configure command failed, error %d\n",
3954		    __func__, error);
3955		return error;
3956	}
3957	sc->sc_curchan = ic->ic_curchan;
3958
3959	/* configuration has changed, set Tx power accordingly */
3960	error = iwn_set_txpower(sc, ic->ic_curchan, 0);
3961	if (error != 0) {
3962		device_printf(sc->sc_dev,
3963		    "%s: could not set Tx power, error %d\n", __func__, error);
3964		return error;
3965	}
3966
3967	/* add broadcast node */
3968	memset(&node, 0, sizeof node);
3969	IEEE80211_ADDR_COPY(node.macaddr, ic->ic_ifp->if_broadcastaddr);
3970	node.id = IWN_ID_BROADCAST;
3971	node.rate = iwn_plcp_signal(2);
3972	DPRINTF(sc, IWN_DEBUG_RESET, "%s: add broadcast node\n", __func__);
3973	error = iwn_cmd(sc, IWN_CMD_ADD_NODE, &node, sizeof node, 0);
3974	if (error != 0) {
3975		device_printf(sc->sc_dev,
3976		    "%s: could not add broadcast node, error %d\n",
3977		    __func__, error);
3978		return error;
3979	}
3980	error = iwn_set_link_quality(sc, node.id, ic->ic_curchan, 0);
3981	if (error != 0) {
3982		device_printf(sc->sc_dev,
3983		    "%s: could not setup MRR for node %d, error %d\n",
3984		    __func__, node.id, error);
3985		return error;
3986	}
3987
3988	error = iwn_set_critical_temp(sc);
3989	if (error != 0) {
3990		device_printf(sc->sc_dev,
3991		    "%s: could not set critical temperature, error %d\n",
3992		    __func__, error);
3993		return error;
3994	}
3995	return 0;
3996}
3997
3998/*
3999 * Do post-alive initialization of the NIC (after firmware upload).
4000 */
4001void
4002iwn_post_alive(struct iwn_softc *sc)
4003{
4004	uint32_t base;
4005	uint16_t offset;
4006	int qid;
4007
4008	iwn_mem_lock(sc);
4009
4010	/* clear SRAM */
4011	base = iwn_mem_read(sc, IWN_SRAM_BASE);
4012	for (offset = 0x380; offset < 0x520; offset += 4) {
4013		IWN_WRITE(sc, IWN_MEM_WADDR, base + offset);
4014		IWN_WRITE(sc, IWN_MEM_WDATA, 0);
4015	}
4016
4017	/* shared area is aligned on a 1K boundary */
4018	iwn_mem_write(sc, IWN_SRAM_BASE, sc->shared_dma.paddr >> 10);
4019	iwn_mem_write(sc, IWN_SELECT_QCHAIN, 0);
4020
4021	for (qid = 0; qid < IWN_NTXQUEUES; qid++) {
4022		iwn_mem_write(sc, IWN_QUEUE_RIDX(qid), 0);
4023		IWN_WRITE(sc, IWN_TX_WIDX, qid << 8 | 0);
4024
4025		/* set sched. window size */
4026		IWN_WRITE(sc, IWN_MEM_WADDR, base + IWN_QUEUE_OFFSET(qid));
4027		IWN_WRITE(sc, IWN_MEM_WDATA, 64);
4028		/* set sched. frame limit */
4029		IWN_WRITE(sc, IWN_MEM_WADDR, base + IWN_QUEUE_OFFSET(qid) + 4);
4030		IWN_WRITE(sc, IWN_MEM_WDATA, 10 << 16);
4031	}
4032
4033	/* enable interrupts for all 16 queues */
4034	iwn_mem_write(sc, IWN_QUEUE_INTR_MASK, 0xffff);
4035
4036	/* identify active Tx rings (0-7) */
4037	iwn_mem_write(sc, IWN_TX_ACTIVE, 0xff);
4038
4039	/* mark Tx rings (4 EDCA + cmd + 2 HCCA) as active */
4040	for (qid = 0; qid < 7; qid++) {
4041		iwn_mem_write(sc, IWN_TXQ_STATUS(qid),
4042		    IWN_TXQ_STATUS_ACTIVE | qid << 1);
4043	}
4044
4045	iwn_mem_unlock(sc);
4046}
4047
4048void
4049iwn_stop_master(struct iwn_softc *sc)
4050{
4051	uint32_t tmp;
4052	int ntries;
4053
4054	tmp = IWN_READ(sc, IWN_RESET);
4055	IWN_WRITE(sc, IWN_RESET, tmp | IWN_STOP_MASTER);
4056
4057	tmp = IWN_READ(sc, IWN_GPIO_CTL);
4058	if ((tmp & IWN_GPIO_PWR_STATUS) == IWN_GPIO_PWR_SLEEP)
4059		return;	/* already asleep */
4060
4061	for (ntries = 0; ntries < 100; ntries++) {
4062		if (IWN_READ(sc, IWN_RESET) & IWN_MASTER_DISABLED)
4063			break;
4064		DELAY(10);
4065	}
4066	if (ntries == 100)
4067		device_printf(sc->sc_dev,
4068		    "%s: timeout waiting for master\n", __func__);
4069}
4070
4071int
4072iwn_reset(struct iwn_softc *sc)
4073{
4074	uint32_t tmp;
4075	int ntries;
4076
4077	/* clear any pending interrupts */
4078	IWN_WRITE(sc, IWN_INTR, 0xffffffff);
4079
4080	tmp = IWN_READ(sc, IWN_CHICKEN);
4081	IWN_WRITE(sc, IWN_CHICKEN, tmp | IWN_CHICKEN_DISLOS);
4082
4083	tmp = IWN_READ(sc, IWN_GPIO_CTL);
4084	IWN_WRITE(sc, IWN_GPIO_CTL, tmp | IWN_GPIO_INIT);
4085
4086	/* wait for clock stabilization */
4087	for (ntries = 0; ntries < 1000; ntries++) {
4088		if (IWN_READ(sc, IWN_GPIO_CTL) & IWN_GPIO_CLOCK)
4089			break;
4090		DELAY(10);
4091	}
4092	if (ntries == 1000) {
4093		device_printf(sc->sc_dev,
4094		    "%s: timeout waiting for clock stabilization\n", __func__);
4095		return ETIMEDOUT;
4096	}
4097	return 0;
4098}
4099
4100void
4101iwn_hw_config(struct iwn_softc *sc)
4102{
4103	uint32_t tmp, hw;
4104
4105	/* enable interrupts mitigation */
4106	IWN_WRITE(sc, IWN_INTR_MIT, 512 / 32);
4107
4108	/* voodoo from the reference driver */
4109	tmp = pci_read_config(sc->sc_dev, PCIR_REVID,1);
4110	if ((tmp & 0x80) && (tmp & 0x7f) < 8) {
4111		/* enable "no snoop" field */
4112		tmp = pci_read_config(sc->sc_dev, 0xe8, 1);
4113		tmp &= ~IWN_DIS_NOSNOOP;
4114		/* clear device specific PCI configuration register 0x41 */
4115		pci_write_config(sc->sc_dev, 0xe8, tmp, 1);
4116	}
4117
4118	/* disable L1 entry to work around a hardware bug */
4119	tmp = pci_read_config(sc->sc_dev, 0xf0, 1);
4120	tmp &= ~IWN_ENA_L1;
4121	pci_write_config(sc->sc_dev, 0xf0, tmp, 1 );
4122
4123	hw = IWN_READ(sc, IWN_HWCONFIG);
4124	IWN_WRITE(sc, IWN_HWCONFIG, hw | 0x310);
4125
4126	iwn_mem_lock(sc);
4127	tmp = iwn_mem_read(sc, IWN_MEM_POWER);
4128	iwn_mem_write(sc, IWN_MEM_POWER, tmp | IWN_POWER_RESET);
4129	DELAY(5);
4130	tmp = iwn_mem_read(sc, IWN_MEM_POWER);
4131	iwn_mem_write(sc, IWN_MEM_POWER, tmp & ~IWN_POWER_RESET);
4132	iwn_mem_unlock(sc);
4133}
4134
4135void
4136iwn_init_locked(struct iwn_softc *sc)
4137{
4138	struct ifnet *ifp = sc->sc_ifp;
4139	uint32_t tmp;
4140	int error, qid;
4141
4142	IWN_LOCK_ASSERT(sc);
4143
4144	/* load the firmware */
4145	if (sc->fw_fp == NULL && (error = iwn_load_firmware(sc)) != 0) {
4146		device_printf(sc->sc_dev,
4147		    "%s: could not load firmware, error %d\n", __func__, error);
4148		return;
4149	}
4150
4151	error = iwn_reset(sc);
4152	if (error != 0) {
4153		device_printf(sc->sc_dev,
4154		    "%s: could not reset adapter, error %d\n", __func__, error);
4155		return;
4156	}
4157
4158	iwn_mem_lock(sc);
4159	iwn_mem_read(sc, IWN_CLOCK_CTL);
4160	iwn_mem_write(sc, IWN_CLOCK_CTL, 0xa00);
4161	iwn_mem_read(sc, IWN_CLOCK_CTL);
4162	iwn_mem_unlock(sc);
4163
4164	DELAY(20);
4165
4166	iwn_mem_lock(sc);
4167	tmp = iwn_mem_read(sc, IWN_MEM_PCIDEV);
4168	iwn_mem_write(sc, IWN_MEM_PCIDEV, tmp | 0x800);
4169	iwn_mem_unlock(sc);
4170
4171	iwn_mem_lock(sc);
4172	tmp = iwn_mem_read(sc, IWN_MEM_POWER);
4173	iwn_mem_write(sc, IWN_MEM_POWER, tmp & ~0x03000000);
4174	iwn_mem_unlock(sc);
4175
4176	iwn_hw_config(sc);
4177
4178	/* init Rx ring */
4179	iwn_mem_lock(sc);
4180	IWN_WRITE(sc, IWN_RX_CONFIG, 0);
4181	IWN_WRITE(sc, IWN_RX_WIDX, 0);
4182	/* Rx ring is aligned on a 256-byte boundary */
4183	IWN_WRITE(sc, IWN_RX_BASE, sc->rxq.desc_dma.paddr >> 8);
4184	/* shared area is aligned on a 16-byte boundary */
4185	IWN_WRITE(sc, IWN_RW_WIDX_PTR, (sc->shared_dma.paddr +
4186	    offsetof(struct iwn_shared, closed_count)) >> 4);
4187	IWN_WRITE(sc, IWN_RX_CONFIG, 0x80601000);
4188	iwn_mem_unlock(sc);
4189
4190	IWN_WRITE(sc, IWN_RX_WIDX, (IWN_RX_RING_COUNT - 1) & ~7);
4191
4192	iwn_mem_lock(sc);
4193	iwn_mem_write(sc, IWN_TX_ACTIVE, 0);
4194
4195	/* set physical address of "keep warm" page */
4196	IWN_WRITE(sc, IWN_KW_BASE, sc->kw_dma.paddr >> 4);
4197
4198	/* init Tx rings */
4199	for (qid = 0; qid < IWN_NTXQUEUES; qid++) {
4200		struct iwn_tx_ring *txq = &sc->txq[qid];
4201		IWN_WRITE(sc, IWN_TX_BASE(qid), txq->desc_dma.paddr >> 8);
4202		IWN_WRITE(sc, IWN_TX_CONFIG(qid), 0x80000008);
4203	}
4204	iwn_mem_unlock(sc);
4205
4206	/* clear "radio off" and "disable command" bits (reversed logic) */
4207	IWN_WRITE(sc, IWN_UCODE_CLR, IWN_RADIO_OFF);
4208	IWN_WRITE(sc, IWN_UCODE_CLR, IWN_DISABLE_CMD);
4209
4210	/* clear any pending interrupts */
4211	IWN_WRITE(sc, IWN_INTR, 0xffffffff);
4212	/* enable interrupts */
4213	IWN_WRITE(sc, IWN_MASK, IWN_INTR_MASK);
4214
4215	/* not sure why/if this is necessary... */
4216	IWN_WRITE(sc, IWN_UCODE_CLR, IWN_RADIO_OFF);
4217	IWN_WRITE(sc, IWN_UCODE_CLR, IWN_RADIO_OFF);
4218
4219	/* check that the radio is not disabled by RF switch */
4220	if (!(IWN_READ(sc, IWN_GPIO_CTL) & IWN_GPIO_RF_ENABLED)) {
4221		device_printf(sc->sc_dev,
4222		    "radio is disabled by hardware switch\n");
4223		return;
4224	}
4225
4226	error = iwn_transfer_firmware(sc);
4227	if (error != 0) {
4228		device_printf(sc->sc_dev,
4229		    "%s: could not load firmware, error %d\n", __func__, error);
4230		return;
4231	}
4232
4233	/* firmware has notified us that it is alive.. */
4234	iwn_post_alive(sc);	/* ..do post alive initialization */
4235
4236	sc->rawtemp = sc->ucode_info.temp[3].chan20MHz;
4237	sc->temp = iwn_get_temperature(sc);
4238	DPRINTF(sc, IWN_DEBUG_RESET, "%s: temperature=%d\n",
4239	   __func__, sc->temp);
4240
4241	error = iwn_config(sc);
4242	if (error != 0) {
4243		device_printf(sc->sc_dev,
4244		    "%s: could not configure device, error %d\n",
4245		    __func__, error);
4246		return;
4247	}
4248
4249	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4250	ifp->if_drv_flags |= IFF_DRV_RUNNING;
4251}
4252
4253void
4254iwn_init(void *arg)
4255{
4256	struct iwn_softc *sc = arg;
4257	struct ifnet *ifp = sc->sc_ifp;
4258	struct ieee80211com *ic = ifp->if_l2com;
4259
4260	IWN_LOCK(sc);
4261	iwn_init_locked(sc);
4262	IWN_UNLOCK(sc);
4263
4264	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
4265		ieee80211_start_all(ic);
4266}
4267
4268void
4269iwn_stop_locked(struct iwn_softc *sc)
4270{
4271	struct ifnet *ifp = sc->sc_ifp;
4272	uint32_t tmp;
4273	int i;
4274
4275	IWN_LOCK_ASSERT(sc);
4276
4277	IWN_WRITE(sc, IWN_RESET, IWN_NEVO_RESET);
4278
4279	sc->sc_tx_timer = 0;
4280	callout_stop(&sc->sc_timer_to);
4281	ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
4282
4283	/* disable interrupts */
4284	IWN_WRITE(sc, IWN_MASK, 0);
4285	IWN_WRITE(sc, IWN_INTR, 0xffffffff);
4286	IWN_WRITE(sc, IWN_INTR_STATUS, 0xffffffff);
4287
4288	/* Clear any commands left in the taskq command buffer */
4289	memset(sc->sc_cmd, 0, sizeof(sc->sc_cmd));
4290
4291	/* reset all Tx rings */
4292	for (i = 0; i < IWN_NTXQUEUES; i++)
4293		iwn_reset_tx_ring(sc, &sc->txq[i]);
4294
4295	/* reset Rx ring */
4296	iwn_reset_rx_ring(sc, &sc->rxq);
4297
4298	iwn_mem_lock(sc);
4299	iwn_mem_write(sc, IWN_MEM_CLOCK2, 0x200);
4300	iwn_mem_unlock(sc);
4301
4302	DELAY(5);
4303	iwn_stop_master(sc);
4304
4305	tmp = IWN_READ(sc, IWN_RESET);
4306	IWN_WRITE(sc, IWN_RESET, tmp | IWN_SW_RESET);
4307}
4308
4309void
4310iwn_stop(struct iwn_softc *sc)
4311{
4312	IWN_LOCK(sc);
4313	iwn_stop_locked(sc);
4314	IWN_UNLOCK(sc);
4315}
4316
4317/*
4318 * Callback from net80211 to start a scan.
4319 */
4320static void
4321iwn_scan_start(struct ieee80211com *ic)
4322{
4323	struct ifnet *ifp = ic->ic_ifp;
4324	struct iwn_softc *sc = ifp->if_softc;
4325
4326	iwn_queue_cmd(sc, IWN_SCAN_START, 0, IWN_QUEUE_NORMAL);
4327}
4328
4329/*
4330 * Callback from net80211 to terminate a scan.
4331 */
4332static void
4333iwn_scan_end(struct ieee80211com *ic)
4334{
4335	struct ifnet *ifp = ic->ic_ifp;
4336	struct iwn_softc *sc = ifp->if_softc;
4337
4338	iwn_queue_cmd(sc, IWN_SCAN_STOP, 0, IWN_QUEUE_NORMAL);
4339}
4340
4341/*
4342 * Callback from net80211 to force a channel change.
4343 */
4344static void
4345iwn_set_channel(struct ieee80211com *ic)
4346{
4347	struct ifnet *ifp = ic->ic_ifp;
4348	struct iwn_softc *sc = ifp->if_softc;
4349	const struct ieee80211_channel *c = ic->ic_curchan;
4350
4351	if (c != sc->sc_curchan) {
4352		sc->sc_rxtap.wr_chan_freq = htole16(c->ic_freq);
4353		sc->sc_rxtap.wr_chan_flags = htole16(c->ic_flags);
4354		sc->sc_txtap.wt_chan_freq = htole16(c->ic_freq);
4355		sc->sc_txtap.wt_chan_flags = htole16(c->ic_flags);
4356		iwn_queue_cmd(sc, IWN_SET_CHAN, 0, IWN_QUEUE_NORMAL);
4357	}
4358}
4359
4360/*
4361 * Callback from net80211 to start scanning of the current channel.
4362 */
4363static void
4364iwn_scan_curchan(struct ieee80211_scan_state *ss, unsigned long maxdwell)
4365{
4366	struct ieee80211vap *vap = ss->ss_vap;
4367	struct iwn_softc *sc = vap->iv_ic->ic_ifp->if_softc;
4368
4369	iwn_queue_cmd(sc, IWN_SCAN_CURCHAN, 0, IWN_QUEUE_NORMAL);
4370}
4371
4372/*
4373 * Callback from net80211 to handle the minimum dwell time being met.
4374 * The intent is to terminate the scan but we just let the firmware
4375 * notify us when it's finished as we have no safe way to abort it.
4376 */
4377static void
4378iwn_scan_mindwell(struct ieee80211_scan_state *ss)
4379{
4380	/* NB: don't try to abort scan; wait for firmware to finish */
4381}
4382
4383/*
4384 * Carry out work in the taskq context.
4385 */
4386static void
4387iwn_ops(void *arg0, int pending)
4388{
4389	struct iwn_softc *sc = arg0;
4390	struct ifnet *ifp = sc->sc_ifp;
4391	struct ieee80211com *ic = ifp->if_l2com;
4392	struct ieee80211vap *vap;
4393	int cmd, arg, error;
4394	enum ieee80211_state nstate;
4395
4396	for (;;) {
4397		IWN_CMD_LOCK(sc);
4398		cmd = sc->sc_cmd[sc->sc_cmd_cur];
4399		if (cmd == 0) {
4400			/* No more commands to process */
4401			IWN_CMD_UNLOCK(sc);
4402			return;
4403		}
4404		if ((sc->sc_ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 &&
4405		    cmd != IWN_RADIO_ENABLE ) {
4406			IWN_CMD_UNLOCK(sc);
4407			return;
4408		}
4409		arg = sc->sc_cmd_arg[sc->sc_cmd_cur];
4410		sc->sc_cmd[sc->sc_cmd_cur] = 0;		/* free the slot */
4411		sc->sc_cmd_cur = (sc->sc_cmd_cur + 1) % IWN_CMD_MAXOPS;
4412		IWN_CMD_UNLOCK(sc);
4413
4414		IWN_LOCK(sc);		/* NB: sync debug printfs on smp */
4415		DPRINTF(sc, IWN_DEBUG_OPS, "%s: %s (cmd 0x%x)\n",
4416		    __func__, iwn_ops_str(cmd), cmd);
4417
4418		vap = TAILQ_FIRST(&ic->ic_vaps);	/* XXX */
4419		switch (cmd) {
4420		case IWN_SCAN_START:
4421			/* make the link LED blink while we're scanning */
4422			iwn_set_led(sc, IWN_LED_LINK, 20, 2);
4423			break;
4424		case IWN_SCAN_STOP:
4425			break;
4426		case IWN_SCAN_NEXT:
4427			ieee80211_scan_next(vap);
4428			break;
4429		case IWN_SCAN_CURCHAN:
4430			error = iwn_scan(sc);
4431			if (error != 0) {
4432				IWN_UNLOCK(sc);
4433				ieee80211_cancel_scan(vap);
4434				IWN_LOCK(sc);
4435				return;
4436			}
4437			break;
4438		case IWN_SET_CHAN:
4439			error = iwn_config(sc);
4440			if (error != 0) {
4441				DPRINTF(sc, IWN_DEBUG_STATE,
4442				    "%s: set chan failed, cancel scan\n",
4443				    __func__);
4444				IWN_UNLOCK(sc);
4445				//XXX Handle failed scan correctly
4446				ieee80211_cancel_scan(vap);
4447				return;
4448			}
4449			break;
4450		case IWN_AUTH:
4451		case IWN_RUN:
4452			if (cmd == IWN_AUTH) {
4453				error = iwn_auth(sc);
4454				nstate = IEEE80211_S_AUTH;
4455			} else {
4456				error = iwn_run(sc);
4457				nstate = IEEE80211_S_RUN;
4458			}
4459			if (error == 0) {
4460				IWN_UNLOCK(sc);
4461				IEEE80211_LOCK(ic);
4462				IWN_VAP(vap)->iv_newstate(vap, nstate, arg);
4463				if (vap->iv_newstate_cb != NULL)
4464					vap->iv_newstate_cb(vap, nstate, arg);
4465				IEEE80211_UNLOCK(ic);
4466				IWN_LOCK(sc);
4467			} else {
4468				device_printf(sc->sc_dev,
4469				    "%s: %s state change failed, error %d\n",
4470				    __func__, ieee80211_state_name[nstate],
4471				    error);
4472			}
4473			break;
4474		case IWN_REINIT:
4475			IWN_UNLOCK(sc);
4476			iwn_init(sc);
4477			IWN_LOCK(sc);
4478			ieee80211_notify_radio(ic, 1);
4479			break;
4480		case IWN_RADIO_ENABLE:
4481			KASSERT(sc->fw_fp != NULL,
4482			    ("Fware Not Loaded, can't load from tq"));
4483			IWN_UNLOCK(sc);
4484			iwn_init(sc);
4485			IWN_LOCK(sc);
4486			break;
4487		case IWN_RADIO_DISABLE:
4488			ieee80211_notify_radio(ic, 0);
4489			iwn_stop_locked(sc);
4490			break;
4491		}
4492		IWN_UNLOCK(sc);
4493	}
4494}
4495
4496/*
4497 * Queue a command for execution in the taskq thread.
4498 * This is needed as the net80211 callbacks do not allow
4499 * sleeping, since we need to sleep to confirm commands have
4500 * been processed by the firmware, we must defer execution to
4501 * a sleep enabled thread.
4502 */
4503static int
4504iwn_queue_cmd(struct iwn_softc *sc, int cmd, int arg, int clear)
4505{
4506	IWN_CMD_LOCK(sc);
4507	if (clear) {
4508		sc->sc_cmd[0] = cmd;
4509		sc->sc_cmd_arg[0] = arg;
4510		sc->sc_cmd_cur = 0;
4511		sc->sc_cmd_next = 1;
4512	} else {
4513		if (sc->sc_cmd[sc->sc_cmd_next] != 0) {
4514			IWN_CMD_UNLOCK(sc);
4515			DPRINTF(sc, IWN_DEBUG_ANY, "%s: command %d dropped\n",
4516			    __func__, cmd);
4517			return EBUSY;
4518		}
4519		sc->sc_cmd[sc->sc_cmd_next] = cmd;
4520		sc->sc_cmd_arg[sc->sc_cmd_next] = arg;
4521		sc->sc_cmd_next = (sc->sc_cmd_next + 1) % IWN_CMD_MAXOPS;
4522	}
4523	taskqueue_enqueue(sc->sc_tq, &sc->sc_ops_task);
4524	IWN_CMD_UNLOCK(sc);
4525	return 0;
4526}
4527
4528static void
4529iwn_bpfattach(struct iwn_softc *sc)
4530{
4531	struct ifnet *ifp = sc->sc_ifp;
4532
4533        bpfattach(ifp, DLT_IEEE802_11_RADIO,
4534            sizeof (struct ieee80211_frame) + sizeof (sc->sc_txtap));
4535
4536        sc->sc_rxtap_len = sizeof sc->sc_rxtap;
4537        sc->sc_rxtap.wr_ihdr.it_len = htole16(sc->sc_rxtap_len);
4538        sc->sc_rxtap.wr_ihdr.it_present = htole32(IWN_RX_RADIOTAP_PRESENT);
4539
4540        sc->sc_txtap_len = sizeof sc->sc_txtap;
4541        sc->sc_txtap.wt_ihdr.it_len = htole16(sc->sc_txtap_len);
4542        sc->sc_txtap.wt_ihdr.it_present = htole32(IWN_TX_RADIOTAP_PRESENT);
4543}
4544
4545static void
4546iwn_sysctlattach(struct iwn_softc *sc)
4547{
4548	struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->sc_dev);
4549	struct sysctl_oid *tree = device_get_sysctl_tree(sc->sc_dev);
4550
4551#ifdef IWN_DEBUG
4552	sc->sc_debug = 0;
4553	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
4554	    "debug", CTLFLAG_RW, &sc->sc_debug, 0, "control debugging printfs");
4555#endif
4556}
4557
4558#ifdef IWN_DEBUG
4559static const char *
4560iwn_ops_str(int cmd)
4561{
4562	switch (cmd) {
4563	case IWN_SCAN_START:	return "SCAN_START";
4564	case IWN_SCAN_CURCHAN:	return "SCAN_CURCHAN";
4565	case IWN_SCAN_STOP:	return "SCAN_STOP";
4566	case IWN_SET_CHAN:	return "SET_CHAN";
4567	case IWN_AUTH:		return "AUTH";
4568	case IWN_SCAN_NEXT:	return "SCAN_NEXT";
4569	case IWN_RUN:		return "RUN";
4570	case IWN_RADIO_ENABLE:	return "RADIO_ENABLE";
4571	case IWN_RADIO_DISABLE:	return "RADIO_DISABLE";
4572	case IWN_REINIT:	return "REINIT";
4573	}
4574	return "UNKNOWN COMMAND";
4575}
4576
4577static const char *
4578iwn_intr_str(uint8_t cmd)
4579{
4580	switch (cmd) {
4581	/* Notifications */
4582	case IWN_UC_READY:		return "UC_READY";
4583	case IWN_ADD_NODE_DONE:		return "ADD_NODE_DONE";
4584	case IWN_TX_DONE:		return "TX_DONE";
4585	case IWN_START_SCAN:		return "START_SCAN";
4586	case IWN_STOP_SCAN:		return "STOP_SCAN";
4587	case IWN_RX_STATISTICS:		return "RX_STATS";
4588	case IWN_BEACON_STATISTICS:	return "BEACON_STATS";
4589	case IWN_STATE_CHANGED:		return "STATE_CHANGED";
4590	case IWN_BEACON_MISSED:		return "BEACON_MISSED";
4591	case IWN_AMPDU_RX_START:	return "AMPDU_RX_START";
4592	case IWN_AMPDU_RX_DONE:		return "AMPDU_RX_DONE";
4593	case IWN_RX_DONE:		return "RX_DONE";
4594
4595	/* Command Notifications */
4596	case IWN_CMD_CONFIGURE:		return "IWN_CMD_CONFIGURE";
4597	case IWN_CMD_ASSOCIATE:		return "IWN_CMD_ASSOCIATE";
4598	case IWN_CMD_EDCA_PARAMS:	return "IWN_CMD_EDCA_PARAMS";
4599	case IWN_CMD_TSF:		return "IWN_CMD_TSF";
4600	case IWN_CMD_TX_LINK_QUALITY:	return "IWN_CMD_TX_LINK_QUALITY";
4601	case IWN_CMD_SET_LED:		return "IWN_CMD_SET_LED";
4602	case IWN_CMD_SET_POWER_MODE:	return "IWN_CMD_SET_POWER_MODE";
4603	case IWN_CMD_SCAN:		return "IWN_CMD_SCAN";
4604	case IWN_CMD_TXPOWER:		return "IWN_CMD_TXPOWER";
4605	case IWN_CMD_BLUETOOTH:		return "IWN_CMD_BLUETOOTH";
4606	case IWN_CMD_SET_CRITICAL_TEMP:	return "IWN_CMD_SET_CRITICAL_TEMP";
4607	case IWN_SENSITIVITY:		return "IWN_SENSITIVITY";
4608	case IWN_PHY_CALIB:		return "IWN_PHY_CALIB";
4609	}
4610	return "UNKNOWN INTR NOTIF/CMD";
4611}
4612#endif /* IWN_DEBUG */
4613
4614static device_method_t iwn_methods[] = {
4615        /* Device interface */
4616        DEVMETHOD(device_probe,         iwn_probe),
4617        DEVMETHOD(device_attach,        iwn_attach),
4618        DEVMETHOD(device_detach,        iwn_detach),
4619        DEVMETHOD(device_shutdown,      iwn_shutdown),
4620        DEVMETHOD(device_suspend,       iwn_suspend),
4621        DEVMETHOD(device_resume,        iwn_resume),
4622
4623        { 0, 0 }
4624};
4625
4626static driver_t iwn_driver = {
4627        "iwn",
4628        iwn_methods,
4629        sizeof (struct iwn_softc)
4630};
4631static devclass_t iwn_devclass;
4632DRIVER_MODULE(iwn, pci, iwn_driver, iwn_devclass, 0, 0);
4633MODULE_DEPEND(iwn, pci, 1, 1, 1);
4634MODULE_DEPEND(iwn, firmware, 1, 1, 1);
4635MODULE_DEPEND(iwn, wlan, 1, 1, 1);
4636MODULE_DEPEND(iwn, wlan_amrr, 1, 1, 1);
4637