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