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