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