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