xref: /openbsd-src/sys/dev/pci/if_iwn.c (revision 2b0358df1d88d06ef4139321dd05bd5e05d91eaf)
1 /*	$OpenBSD: if_iwn.c,v 1.49 2009/03/29 21:53:52 sthen Exp $	*/
2 
3 /*-
4  * Copyright (c) 2007, 2008
5  *	Damien Bergamini <damien.bergamini@free.fr>
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 /*
21  * Driver for Intel Wireless WiFi Link 4965 and Intel WiFi Link 5000 Series
22  * 802.11 network adapters.
23  */
24 
25 #include "bpfilter.h"
26 
27 #include <sys/param.h>
28 #include <sys/sockio.h>
29 #include <sys/sysctl.h>
30 #include <sys/mbuf.h>
31 #include <sys/kernel.h>
32 #include <sys/socket.h>
33 #include <sys/systm.h>
34 #include <sys/malloc.h>
35 #include <sys/conf.h>
36 #include <sys/device.h>
37 #include <sys/sensors.h>
38 
39 #include <machine/bus.h>
40 #include <machine/endian.h>
41 #include <machine/intr.h>
42 
43 #include <dev/pci/pcireg.h>
44 #include <dev/pci/pcivar.h>
45 #include <dev/pci/pcidevs.h>
46 
47 #if NBPFILTER > 0
48 #include <net/bpf.h>
49 #endif
50 #include <net/if.h>
51 #include <net/if_arp.h>
52 #include <net/if_dl.h>
53 #include <net/if_media.h>
54 #include <net/if_types.h>
55 
56 #include <netinet/in.h>
57 #include <netinet/in_systm.h>
58 #include <netinet/in_var.h>
59 #include <netinet/if_ether.h>
60 #include <netinet/ip.h>
61 
62 #include <net80211/ieee80211_var.h>
63 #include <net80211/ieee80211_amrr.h>
64 #include <net80211/ieee80211_radiotap.h>
65 
66 #include <dev/pci/if_iwnreg.h>
67 #include <dev/pci/if_iwnvar.h>
68 
69 static const struct pci_matchid iwn_devices[] = {
70 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WIFI_LINK_4965_1 },
71 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WIFI_LINK_4965_2 },
72 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WIFI_LINK_5100_1 },
73 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WIFI_LINK_5100_2 },
74 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WIFI_LINK_5150_1 },
75 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WIFI_LINK_5150_2 },
76 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WIFI_LINK_5300_1 },
77 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WIFI_LINK_5300_2 },
78 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WIFI_LINK_5350_1 },
79 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WIFI_LINK_5350_2 },
80 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WIFI_LINK_6000_1 },
81 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WIFI_LINK_6000_2 },
82 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WIFI_LINK_6000_3 },
83 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WIFI_LINK_6000_4 },
84 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WIFI_LINK_6050_1 },
85 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WIFI_LINK_6050_2 },
86 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WIFI_LINK_6050_3 },
87 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WIFI_LINK_6050_4 },
88 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WIFI_LINK_1000_1 },
89 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WIFI_LINK_1000_2 }
90 };
91 
92 int		iwn_match(struct device *, void *, void *);
93 void		iwn_attach(struct device *, struct device *, void *);
94 const struct	iwn_hal *iwn_hal_attach(struct iwn_softc *);
95 #ifndef SMALL_KERNEL
96 void		iwn_sensor_attach(struct iwn_softc *);
97 #endif
98 #if NBPFILTER > 0
99 void		iwn_radiotap_attach(struct iwn_softc *);
100 #endif
101 void		iwn_power(int, void *);
102 int		iwn_nic_lock(struct iwn_softc *);
103 int		iwn_eeprom_lock(struct iwn_softc *);
104 int		iwn_read_prom_data(struct iwn_softc *, uint32_t, void *, int);
105 int		iwn_dma_contig_alloc(bus_dma_tag_t, struct iwn_dma_info *,
106 		    void **, bus_size_t, bus_size_t, int);
107 void		iwn_dma_contig_free(struct iwn_dma_info *);
108 int		iwn_alloc_sched(struct iwn_softc *);
109 void		iwn_free_sched(struct iwn_softc *);
110 int		iwn_alloc_kw(struct iwn_softc *);
111 void		iwn_free_kw(struct iwn_softc *);
112 int		iwn_alloc_fwmem(struct iwn_softc *);
113 void		iwn_free_fwmem(struct iwn_softc *);
114 struct		iwn_rbuf *iwn_alloc_rbuf(struct iwn_softc *);
115 void		iwn_free_rbuf(caddr_t, u_int, void *);
116 int		iwn_alloc_rpool(struct iwn_softc *);
117 void		iwn_free_rpool(struct iwn_softc *);
118 int		iwn_alloc_rx_ring(struct iwn_softc *, struct iwn_rx_ring *);
119 void		iwn_reset_rx_ring(struct iwn_softc *, struct iwn_rx_ring *);
120 void		iwn_free_rx_ring(struct iwn_softc *, struct iwn_rx_ring *);
121 int		iwn_alloc_tx_ring(struct iwn_softc *, struct iwn_tx_ring *,
122 		    int);
123 void		iwn_reset_tx_ring(struct iwn_softc *, struct iwn_tx_ring *);
124 void		iwn_free_tx_ring(struct iwn_softc *, struct iwn_tx_ring *);
125 int		iwn_read_eeprom(struct iwn_softc *);
126 void		iwn4965_read_eeprom(struct iwn_softc *);
127 void		iwn4965_print_power_group(struct iwn_softc *, int);
128 void		iwn5000_read_eeprom(struct iwn_softc *);
129 void		iwn_read_eeprom_channels(struct iwn_softc *, int, uint32_t);
130 struct		ieee80211_node *iwn_node_alloc(struct ieee80211com *);
131 void		iwn_newassoc(struct ieee80211com *, struct ieee80211_node *,
132 		    int);
133 int		iwn_media_change(struct ifnet *);
134 int		iwn_newstate(struct ieee80211com *, enum ieee80211_state, int);
135 void		iwn_iter_func(void *, struct ieee80211_node *);
136 void		iwn_calib_timeout(void *);
137 int		iwn_ccmp_decap(struct iwn_softc *, struct mbuf *,
138 		    struct ieee80211_key *);
139 void		iwn_rx_phy(struct iwn_softc *, struct iwn_rx_desc *);
140 void		iwn_rx_done(struct iwn_softc *, struct iwn_rx_desc *,
141 		    struct iwn_rx_data *);
142 void		iwn5000_rx_calib_results(struct iwn_softc *,
143 		    struct iwn_rx_desc *);
144 void		iwn_rx_statistics(struct iwn_softc *, struct iwn_rx_desc *);
145 void		iwn4965_tx_done(struct iwn_softc *, struct iwn_rx_desc *);
146 void		iwn5000_tx_done(struct iwn_softc *, struct iwn_rx_desc *);
147 void		iwn_tx_done(struct iwn_softc *, struct iwn_rx_desc *, int,
148 		    uint8_t);
149 void		iwn_cmd_done(struct iwn_softc *, struct iwn_rx_desc *);
150 void		iwn_notif_intr(struct iwn_softc *);
151 void		iwn_wakeup_intr(struct iwn_softc *);
152 void		iwn_fatal_intr(struct iwn_softc *);
153 int		iwn_intr(void *);
154 void		iwn4965_update_sched(struct iwn_softc *, int, int, uint8_t,
155 		    uint16_t);
156 void		iwn5000_update_sched(struct iwn_softc *, int, int, uint8_t,
157 		    uint16_t);
158 void		iwn5000_reset_sched(struct iwn_softc *, int, int);
159 int		iwn_tx(struct iwn_softc *, struct mbuf *,
160 		    struct ieee80211_node *);
161 void		iwn_start(struct ifnet *);
162 void		iwn_watchdog(struct ifnet *);
163 int		iwn_ioctl(struct ifnet *, u_long, caddr_t);
164 int		iwn_cmd(struct iwn_softc *, int, const void *, int, int);
165 int		iwn4965_add_node(struct iwn_softc *, struct iwn_node_info *,
166 		    int);
167 int		iwn5000_add_node(struct iwn_softc *, struct iwn_node_info *,
168 		    int);
169 int		iwn_set_link_quality(struct iwn_softc *,
170 		    struct ieee80211_node *);
171 int		iwn_add_broadcast_node(struct iwn_softc *, int);
172 void		iwn_updateedca(struct ieee80211com *);
173 void		iwn_set_led(struct iwn_softc *, uint8_t, uint8_t, uint8_t);
174 int		iwn_set_critical_temp(struct iwn_softc *);
175 int		iwn_set_timing(struct iwn_softc *, struct ieee80211_node *);
176 void		iwn4965_power_calibration(struct iwn_softc *, int);
177 int		iwn4965_set_txpower(struct iwn_softc *, int);
178 int		iwn5000_set_txpower(struct iwn_softc *, int);
179 int		iwn4965_get_rssi(const struct iwn_rx_stat *);
180 int		iwn5000_get_rssi(const struct iwn_rx_stat *);
181 int		iwn_get_noise(const struct iwn_rx_general_stats *);
182 int		iwn4965_get_temperature(struct iwn_softc *);
183 int		iwn5000_get_temperature(struct iwn_softc *);
184 int		iwn_init_sensitivity(struct iwn_softc *);
185 void		iwn_collect_noise(struct iwn_softc *,
186 		    const struct iwn_rx_general_stats *);
187 int		iwn4965_init_gains(struct iwn_softc *);
188 int		iwn5000_init_gains(struct iwn_softc *);
189 int		iwn4965_set_gains(struct iwn_softc *);
190 int		iwn5000_set_gains(struct iwn_softc *);
191 void		iwn_tune_sensitivity(struct iwn_softc *,
192 		    const struct iwn_rx_stats *);
193 int		iwn_send_sensitivity(struct iwn_softc *);
194 int		iwn_set_pslevel(struct iwn_softc *, int, int, int);
195 int		iwn_config(struct iwn_softc *);
196 int		iwn_scan(struct iwn_softc *, uint16_t);
197 int		iwn_auth(struct iwn_softc *);
198 int		iwn_run(struct iwn_softc *);
199 int		iwn_set_key(struct ieee80211com *, struct ieee80211_node *,
200 		    struct ieee80211_key *);
201 void		iwn_delete_key(struct ieee80211com *, struct ieee80211_node *,
202 		    struct ieee80211_key *);
203 #ifndef IEEE80211_NO_HT
204 int		iwn_ampdu_rx_start(struct ieee80211com *,
205 		    struct ieee80211_node *, uint8_t);
206 void		iwn_ampdu_rx_stop(struct ieee80211com *,
207 		    struct ieee80211_node *, uint8_t);
208 int		iwn_ampdu_tx_start(struct ieee80211com *,
209 		    struct ieee80211_node *, uint8_t);
210 void		iwn_ampdu_tx_stop(struct ieee80211com *,
211 		    struct ieee80211_node *, uint8_t);
212 void		iwn4965_ampdu_tx_start(struct iwn_softc *,
213 		    struct ieee80211_node *, uint8_t, uint16_t);
214 void		iwn4965_ampdu_tx_stop(struct iwn_softc *,
215 		    uint8_t, uint16_t);
216 void		iwn5000_ampdu_tx_start(struct iwn_softc *,
217 		    struct ieee80211_node *, uint8_t, uint16_t);
218 void		iwn5000_ampdu_tx_stop(struct iwn_softc *,
219 		    uint8_t, uint16_t);
220 #endif
221 int		iwn5000_query_calibration(struct iwn_softc *);
222 int		iwn5000_send_calibration(struct iwn_softc *);
223 int		iwn4965_post_alive(struct iwn_softc *);
224 int		iwn5000_post_alive(struct iwn_softc *);
225 int		iwn4965_load_bootcode(struct iwn_softc *, const uint8_t *,
226 		    int);
227 int		iwn4965_load_firmware(struct iwn_softc *);
228 int		iwn5000_load_firmware_section(struct iwn_softc *, uint32_t,
229 		    const uint8_t *, int);
230 int		iwn5000_load_firmware(struct iwn_softc *);
231 int		iwn_read_firmware(struct iwn_softc *);
232 int		iwn_clock_wait(struct iwn_softc *);
233 int		iwn4965_apm_init(struct iwn_softc *);
234 int		iwn5000_apm_init(struct iwn_softc *);
235 void		iwn_apm_stop_master(struct iwn_softc *);
236 void		iwn_apm_stop(struct iwn_softc *);
237 int		iwn4965_nic_config(struct iwn_softc *);
238 int		iwn5000_nic_config(struct iwn_softc *);
239 int		iwn_hw_init(struct iwn_softc *);
240 void		iwn_hw_stop(struct iwn_softc *);
241 int		iwn_init(struct ifnet *);
242 void		iwn_stop(struct ifnet *, int);
243 
244 #ifdef IWN_DEBUG
245 #define DPRINTF(x)	do { if (iwn_debug > 0) printf x; } while (0)
246 #define DPRINTFN(n, x)	do { if (iwn_debug >= (n)) printf x; } while (0)
247 int iwn_debug = 0;
248 #else
249 #define DPRINTF(x)
250 #define DPRINTFN(n, x)
251 #endif
252 
253 static const struct iwn_hal iwn4965_hal = {
254 	iwn4965_load_firmware,
255 	iwn4965_read_eeprom,
256 	iwn4965_post_alive,
257 	iwn4965_apm_init,
258 	iwn4965_nic_config,
259 	iwn4965_update_sched,
260 	iwn4965_get_temperature,
261 	iwn4965_get_rssi,
262 	iwn4965_set_txpower,
263 	iwn4965_init_gains,
264 	iwn4965_set_gains,
265 	iwn4965_add_node,
266 	iwn4965_tx_done,
267 #ifndef IEEE80211_NO_HT
268 	iwn4965_ampdu_tx_start,
269 	iwn4965_ampdu_tx_stop,
270 #endif
271 	&iwn4965_sensitivity_limits,
272 	IWN4965_NTXQUEUES,
273 	IWN4965_ID_BROADCAST,
274 	IWN4965_RXONSZ,
275 	IWN4965_SCHEDSZ,
276 	IWN4965_FW_TEXT_MAXSZ,
277 	IWN4965_FW_DATA_MAXSZ,
278 	IWN4965_FWSZ,
279 	IWN4965_SCHED_TXFACT
280 };
281 
282 static const struct iwn_hal iwn5000_hal = {
283 	iwn5000_load_firmware,
284 	iwn5000_read_eeprom,
285 	iwn5000_post_alive,
286 	iwn5000_apm_init,
287 	iwn5000_nic_config,
288 	iwn5000_update_sched,
289 	iwn5000_get_temperature,
290 	iwn5000_get_rssi,
291 	iwn5000_set_txpower,
292 	iwn5000_init_gains,
293 	iwn5000_set_gains,
294 	iwn5000_add_node,
295 	iwn5000_tx_done,
296 #ifndef IEEE80211_NO_HT
297 	iwn5000_ampdu_tx_start,
298 	iwn5000_ampdu_tx_stop,
299 #endif
300 	&iwn5000_sensitivity_limits,
301 	IWN5000_NTXQUEUES,
302 	IWN5000_ID_BROADCAST,
303 	IWN5000_RXONSZ,
304 	IWN5000_SCHEDSZ,
305 	IWN5000_FW_TEXT_MAXSZ,
306 	IWN5000_FW_DATA_MAXSZ,
307 	IWN5000_FWSZ,
308 	IWN5000_SCHED_TXFACT
309 };
310 
311 struct cfdriver iwn_cd = {
312 	NULL, "iwn", DV_IFNET
313 };
314 
315 struct cfattach iwn_ca = {
316 	sizeof (struct iwn_softc), iwn_match, iwn_attach
317 };
318 
319 int
320 iwn_match(struct device *parent, void *match, void *aux)
321 {
322 	return pci_matchbyid((struct pci_attach_args *)aux, iwn_devices,
323 	    nitems(iwn_devices));
324 }
325 
326 void
327 iwn_attach(struct device *parent, struct device *self, void *aux)
328 {
329 	struct iwn_softc *sc = (struct iwn_softc *)self;
330 	struct ieee80211com *ic = &sc->sc_ic;
331 	struct ifnet *ifp = &ic->ic_if;
332 	struct pci_attach_args *pa = aux;
333 	const struct iwn_hal *hal;
334 	const char *intrstr;
335 	pci_intr_handle_t ih;
336 	pcireg_t memtype, reg;
337 	int i, error;
338 
339 	sc->sc_pct = pa->pa_pc;
340 	sc->sc_pcitag = pa->pa_tag;
341 	sc->sc_dmat = pa->pa_dmat;
342 
343 	/*
344 	 * Get the offset of the PCI Express Capability Structure in PCI
345 	 * Configuration Space (the vendor driver hard-codes it as E0h.)
346 	 */
347 	error = pci_get_capability(sc->sc_pct, sc->sc_pcitag,
348 	    PCI_CAP_PCIEXPRESS, &sc->sc_cap_off, NULL);
349 	if (error == 0) {
350 		printf(": PCIe capability structure not found!\n");
351 		return;
352 	}
353 
354 	/* Clear device-specific "PCI retry timeout" register (41h). */
355 	reg = pci_conf_read(sc->sc_pct, sc->sc_pcitag, 0x40);
356 	reg &= ~0xff00;
357 	pci_conf_write(sc->sc_pct, sc->sc_pcitag, 0x40, reg);
358 
359 	memtype = pci_mapreg_type(pa->pa_pc, pa->pa_tag, IWN_PCI_BAR0);
360 	error = pci_mapreg_map(pa, IWN_PCI_BAR0, memtype, 0, &sc->sc_st,
361 	    &sc->sc_sh, NULL, &sc->sc_sz, 0);
362 	if (error != 0) {
363 		printf(": can't map mem space\n");
364 		return;
365 	}
366 
367 	/* Install interrupt handler. */
368 	if (pci_intr_map(pa, &ih) != 0) {
369 		printf(": can't map interrupt\n");
370 		return;
371 	}
372 	intrstr = pci_intr_string(sc->sc_pct, ih);
373 	sc->sc_ih = pci_intr_establish(sc->sc_pct, ih, IPL_NET, iwn_intr, sc,
374 	    sc->sc_dev.dv_xname);
375 	if (sc->sc_ih == NULL) {
376 		printf(": can't establish interrupt");
377 		if (intrstr != NULL)
378 			printf(" at %s", intrstr);
379 		printf("\n");
380 		return;
381 	}
382 	printf(": %s", intrstr);
383 
384 	/* Attach Hardware Abstraction Layer. */
385 	if ((hal = iwn_hal_attach(sc)) == NULL)
386 		return;
387 
388 	/* Power ON adapter. */
389 	if ((error = hal->apm_init(sc)) != 0) {
390 		printf(": could not power ON adapter\n");
391 		return;
392 	}
393 
394 	/* Read MAC address, channels, etc from EEPROM. */
395 	if ((error = iwn_read_eeprom(sc)) != 0) {
396 		printf(": could not read EEPROM\n");
397 		return;
398 	}
399 
400 	/* Allocate DMA memory for firmware transfers. */
401 	if ((error = iwn_alloc_fwmem(sc)) != 0) {
402 		printf(": could not allocate memory for firmware\n");
403 		return;
404 	}
405 
406 	/* Allocate "Keep Warm" page. */
407 	if ((error = iwn_alloc_kw(sc)) != 0) {
408 		printf(": could not allocate keep warm page\n");
409 		goto fail1;
410 	}
411 
412 	/* Allocate TX scheduler "rings". */
413 	if ((error = iwn_alloc_sched(sc)) != 0) {
414 		printf(": could not allocate TX scheduler rings\n");
415 		goto fail2;
416 	}
417 
418 	/* Allocate RX buffers. */
419 	if ((error = iwn_alloc_rpool(sc)) != 0) {
420 		printf(": could not allocate RX buffers\n");
421 		goto fail3;
422 	}
423 
424 	/* Allocate TX rings (16 on 4965AGN, 20 on 5000.) */
425 	for (i = 0; i < hal->ntxqs; i++) {
426 		if ((error = iwn_alloc_tx_ring(sc, &sc->txq[i], i)) != 0) {
427 			printf(": could not allocate TX ring %d\n", i);
428 			goto fail4;
429 		}
430 	}
431 
432 	/* Allocate RX ring. */
433 	if ((error = iwn_alloc_rx_ring(sc, &sc->rxq)) != 0) {
434 		printf(": could not allocate RX ring\n");
435 		goto fail4;
436 	}
437 
438 	/* Power OFF adapter. */
439 	iwn_apm_stop(sc);
440 	/* Clear pending interrupts. */
441 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
442 
443 	printf(", MIMO %dT%dR, %.4s, address %s\n", sc->ntxchains,
444 	    sc->nrxchains, sc->eeprom_domain, ether_sprintf(ic->ic_myaddr));
445 
446 	/* Initialization firmware has not been loaded yet. */
447 	sc->sc_flags |= IWN_FLAG_FIRST_BOOT;
448 
449 	ic->ic_phytype = IEEE80211_T_OFDM;	/* not only, but not used */
450 	ic->ic_opmode = IEEE80211_M_STA;	/* default to BSS mode */
451 	ic->ic_state = IEEE80211_S_INIT;
452 
453 	/* Set device capabilities. */
454 	ic->ic_caps =
455 	    IEEE80211_C_WEP |		/* WEP */
456 	    IEEE80211_C_RSN |		/* WPA/RSN */
457 	    IEEE80211_C_MONITOR |	/* monitor mode supported */
458 	    IEEE80211_C_SHSLOT |	/* short slot time supported */
459 	    IEEE80211_C_SHPREAMBLE |	/* short preamble supported */
460 	    IEEE80211_C_PMGT;		/* power saving supported */
461 
462 	/* Set supported rates. */
463 	ic->ic_sup_rates[IEEE80211_MODE_11B] = ieee80211_std_rateset_11b;
464 	ic->ic_sup_rates[IEEE80211_MODE_11G] = ieee80211_std_rateset_11g;
465 	if (sc->sc_flags & IWN_FLAG_HAS_5GHZ) {
466 		ic->ic_sup_rates[IEEE80211_MODE_11A] =
467 		    ieee80211_std_rateset_11a;
468 	}
469 
470 	/* IBSS channel undefined for now. */
471 	ic->ic_ibss_chan = &ic->ic_channels[0];
472 
473 	ifp->if_softc = sc;
474 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
475 	ifp->if_init = iwn_init;
476 	ifp->if_ioctl = iwn_ioctl;
477 	ifp->if_start = iwn_start;
478 	ifp->if_watchdog = iwn_watchdog;
479 	IFQ_SET_READY(&ifp->if_snd);
480 	memcpy(ifp->if_xname, sc->sc_dev.dv_xname, IFNAMSIZ);
481 
482 	if_attach(ifp);
483 	ieee80211_ifattach(ifp);
484 	ic->ic_node_alloc = iwn_node_alloc;
485 	ic->ic_newassoc = iwn_newassoc;
486 	ic->ic_updateedca = iwn_updateedca;
487 	ic->ic_set_key = iwn_set_key;
488 	ic->ic_delete_key = iwn_delete_key;
489 #ifndef IEEE80211_NO_HT
490 	ic->ic_ampdu_rx_start = iwn_ampdu_rx_start;
491 	ic->ic_ampdu_rx_stop = iwn_ampdu_rx_stop;
492 	ic->ic_ampdu_tx_start = iwn_ampdu_tx_start;
493 	ic->ic_ampdu_tx_stop = iwn_ampdu_tx_stop;
494 #endif
495 
496 	/* Override 802.11 state transition machine. */
497 	sc->sc_newstate = ic->ic_newstate;
498 	ic->ic_newstate = iwn_newstate;
499 	ieee80211_media_init(ifp, iwn_media_change, ieee80211_media_status);
500 
501 	sc->amrr.amrr_min_success_threshold =  1;
502 	sc->amrr.amrr_max_success_threshold = 15;
503 
504 #ifndef SMALL_KERNEL
505 	iwn_sensor_attach(sc);
506 #endif
507 #if NBPFILTER > 0
508 	iwn_radiotap_attach(sc);
509 #endif
510 	timeout_set(&sc->calib_to, iwn_calib_timeout, sc);
511 
512 	sc->powerhook = powerhook_establish(iwn_power, sc);
513 
514 	return;
515 
516 	/* Free allocated memory if something failed during attachment. */
517 fail4:	while (--i >= 0)
518 		iwn_free_tx_ring(sc, &sc->txq[i]);
519 	iwn_free_rpool(sc);
520 fail3:	iwn_free_sched(sc);
521 fail2:	iwn_free_kw(sc);
522 fail1:	iwn_free_fwmem(sc);
523 }
524 
525 const struct iwn_hal *
526 iwn_hal_attach(struct iwn_softc *sc)
527 {
528 	sc->hw_type = (IWN_READ(sc, IWN_HW_REV) >> 4) & 0xf;
529 
530 	switch (sc->hw_type) {
531 	case IWN_HW_REV_TYPE_4965:
532 		sc->sc_hal = &iwn4965_hal;
533 		sc->fwname = "iwn-4965";
534 		sc->critical_temp = IWN_CTOK(110);
535 		sc->txantmsk = IWN_ANT_A | IWN_ANT_B;
536 		sc->rxantmsk = IWN_ANT_ABC;
537 		sc->ntxchains = 2;
538 		sc->nrxchains = 3;
539 		break;
540 	case IWN_HW_REV_TYPE_5100:
541 		sc->sc_hal = &iwn5000_hal;
542 		sc->fwname = "iwn-5000";
543 		sc->critical_temp = 110;
544 		sc->txantmsk = IWN_ANT_B;
545 		sc->rxantmsk = IWN_ANT_A | IWN_ANT_B;
546 		sc->ntxchains = 1;
547 		sc->nrxchains = 2;
548 		break;
549 	case IWN_HW_REV_TYPE_5150:
550 		sc->sc_hal = &iwn5000_hal;
551 		sc->fwname = "iwn-5150";
552 		/* NB: critical temperature will be read from EEPROM. */
553 		sc->txantmsk = IWN_ANT_A;
554 		sc->rxantmsk = IWN_ANT_A | IWN_ANT_B;
555 		sc->ntxchains = 1;
556 		sc->nrxchains = 2;
557 		break;
558 	case IWN_HW_REV_TYPE_5300:
559 	case IWN_HW_REV_TYPE_5350:
560 		sc->sc_hal = &iwn5000_hal;
561 		sc->fwname = "iwn-5000";
562 		sc->critical_temp = 110;
563 		sc->txantmsk = sc->rxantmsk = IWN_ANT_ABC;
564 		sc->ntxchains = sc->nrxchains = 3;
565 		break;
566 	case IWN_HW_REV_TYPE_1000:
567 		sc->sc_hal = &iwn5000_hal;
568 		sc->fwname = "iwn-1000";
569 		sc->critical_temp = 110;
570 		sc->txantmsk = IWN_ANT_A;
571 		sc->rxantmsk = IWN_ANT_A | IWN_ANT_B;
572 		sc->ntxchains = 1;
573 		sc->nrxchains = 2;
574 		break;
575 	case IWN_HW_REV_TYPE_6000:
576 		sc->sc_hal = &iwn5000_hal;
577 		sc->fwname = "iwn-6000";
578 		sc->critical_temp = 110;
579 		sc->txantmsk = IWN_ANT_ABC;
580 		sc->rxantmsk = IWN_ANT_ABC;
581 		sc->ntxchains = 3;
582 		sc->nrxchains = 3;
583 		break;
584 	case IWN_HW_REV_TYPE_6050:
585 		sc->sc_hal = &iwn5000_hal;
586 		sc->fwname = "iwn-6050";
587 		sc->critical_temp = 110;
588 		sc->txantmsk = IWN_ANT_ABC;
589 		sc->rxantmsk = IWN_ANT_ABC;
590 		sc->ntxchains = 3;
591 		sc->nrxchains = 3;
592 		break;
593 	default:
594 		printf(": adapter type %d not supported\n", sc->hw_type);
595 		return NULL;
596 	}
597 	return sc->sc_hal;
598 }
599 
600 #ifndef SMALL_KERNEL
601 /*
602  * Attach the adapter's on-board thermal sensor to the sensors framework.
603  */
604 void
605 iwn_sensor_attach(struct iwn_softc *sc)
606 {
607 	strlcpy(sc->sensordev.xname, sc->sc_dev.dv_xname,
608 	    sizeof sc->sensordev.xname);
609 	sc->sensor.type = SENSOR_TEMP;
610 	/* Temperature is not valid unless interface is up. */
611 	sc->sensor.value = 0;
612 	sc->sensor.flags = SENSOR_FINVALID;
613 	sensor_attach(&sc->sensordev, &sc->sensor);
614 	sensordev_install(&sc->sensordev);
615 }
616 #endif
617 
618 #if NBPFILTER > 0
619 /*
620  * Attach the interface to 802.11 radiotap.
621  */
622 void
623 iwn_radiotap_attach(struct iwn_softc *sc)
624 {
625 	bpfattach(&sc->sc_drvbpf, &sc->sc_ic.ic_if, DLT_IEEE802_11_RADIO,
626 	    sizeof (struct ieee80211_frame) + IEEE80211_RADIOTAP_HDRLEN);
627 
628 	sc->sc_rxtap_len = sizeof sc->sc_rxtapu;
629 	sc->sc_rxtap.wr_ihdr.it_len = htole16(sc->sc_rxtap_len);
630 	sc->sc_rxtap.wr_ihdr.it_present = htole32(IWN_RX_RADIOTAP_PRESENT);
631 
632 	sc->sc_txtap_len = sizeof sc->sc_txtapu;
633 	sc->sc_txtap.wt_ihdr.it_len = htole16(sc->sc_txtap_len);
634 	sc->sc_txtap.wt_ihdr.it_present = htole32(IWN_TX_RADIOTAP_PRESENT);
635 }
636 #endif
637 
638 void
639 iwn_power(int why, void *arg)
640 {
641 	struct iwn_softc *sc = arg;
642 	struct ifnet *ifp;
643 	pcireg_t reg;
644 	int s;
645 
646 	if (why != PWR_RESUME)
647 		return;
648 
649 	/* Clear device-specific "PCI retry timeout" register (41h). */
650 	reg = pci_conf_read(sc->sc_pct, sc->sc_pcitag, 0x40);
651 	reg &= ~0xff00;
652 	pci_conf_write(sc->sc_pct, sc->sc_pcitag, 0x40, reg);
653 
654 	s = splnet();
655 	ifp = &sc->sc_ic.ic_if;
656 	if (ifp->if_flags & IFF_UP) {
657 		ifp->if_init(ifp);
658 		if (ifp->if_flags & IFF_RUNNING)
659 			ifp->if_start(ifp);
660 	}
661 	splx(s);
662 }
663 
664 int
665 iwn_nic_lock(struct iwn_softc *sc)
666 {
667 	int ntries;
668 
669 	/* Request exclusive access to NIC. */
670 	IWN_SETBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_MAC_ACCESS_REQ);
671 
672 	/* Spin until we actually get the lock. */
673 	for (ntries = 0; ntries < 1000; ntries++) {
674 		if ((IWN_READ(sc, IWN_GP_CNTRL) &
675 		     (IWN_GP_CNTRL_MAC_ACCESS_ENA | IWN_GP_CNTRL_SLEEP)) ==
676 		    IWN_GP_CNTRL_MAC_ACCESS_ENA)
677 			return 0;
678 		DELAY(10);
679 	}
680 	return ETIMEDOUT;
681 }
682 
683 static __inline void
684 iwn_nic_unlock(struct iwn_softc *sc)
685 {
686 	IWN_CLRBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_MAC_ACCESS_REQ);
687 }
688 
689 static __inline uint32_t
690 iwn_prph_read(struct iwn_softc *sc, uint32_t addr)
691 {
692 	IWN_WRITE(sc, IWN_PRPH_RADDR, IWN_PRPH_DWORD | addr);
693 	return IWN_READ(sc, IWN_PRPH_RDATA);
694 }
695 
696 static __inline void
697 iwn_prph_write(struct iwn_softc *sc, uint32_t addr, uint32_t data)
698 {
699 	IWN_WRITE(sc, IWN_PRPH_WADDR, IWN_PRPH_DWORD | addr);
700 	IWN_WRITE(sc, IWN_PRPH_WDATA, data);
701 }
702 
703 static __inline void
704 iwn_prph_setbits(struct iwn_softc *sc, uint32_t addr, uint32_t mask)
705 {
706 	iwn_prph_write(sc, addr, iwn_prph_read(sc, addr) | mask);
707 }
708 
709 static __inline void
710 iwn_prph_clrbits(struct iwn_softc *sc, uint32_t addr, uint32_t mask)
711 {
712 	iwn_prph_write(sc, addr, iwn_prph_read(sc, addr) & ~mask);
713 }
714 
715 static __inline void
716 iwn_prph_write_region_4(struct iwn_softc *sc, uint32_t addr,
717     const uint32_t *data, int count)
718 {
719 	for (; count > 0; count--, data++, addr += 4)
720 		iwn_prph_write(sc, addr, *data);
721 }
722 
723 static __inline uint32_t
724 iwn_mem_read(struct iwn_softc *sc, uint32_t addr)
725 {
726 	IWN_WRITE(sc, IWN_MEM_RADDR, addr);
727 	return IWN_READ(sc, IWN_MEM_RDATA);
728 }
729 
730 static __inline void
731 iwn_mem_write(struct iwn_softc *sc, uint32_t addr, uint32_t data)
732 {
733 	IWN_WRITE(sc, IWN_MEM_WADDR, addr);
734 	IWN_WRITE(sc, IWN_MEM_WDATA, data);
735 }
736 
737 static __inline void
738 iwn_mem_write_2(struct iwn_softc *sc, uint32_t addr, uint16_t data)
739 {
740 	uint32_t tmp;
741 
742 	tmp = iwn_mem_read(sc, addr & ~3);
743 	if (addr & 3)
744 		tmp = (tmp & 0x0000ffff) | data << 16;
745 	else
746 		tmp = (tmp & 0xffff0000) | data;
747 	iwn_mem_write(sc, addr & ~3, tmp);
748 }
749 
750 static __inline void
751 iwn_mem_read_region_4(struct iwn_softc *sc, uint32_t addr, uint32_t *data,
752     int count)
753 {
754 	for (; count > 0; count--, addr += 4)
755 		*data++ = iwn_mem_read(sc, addr);
756 }
757 
758 static __inline void
759 iwn_mem_set_region_4(struct iwn_softc *sc, uint32_t addr, uint32_t val,
760     int count)
761 {
762 	for (; count > 0; count--, addr += 4)
763 		iwn_mem_write(sc, addr, val);
764 }
765 
766 int
767 iwn_eeprom_lock(struct iwn_softc *sc)
768 {
769 	int i, ntries;
770 
771 	for (i = 0; i < 100; i++) {
772 		/* Request exclusive access to EEPROM. */
773 		IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
774 		    IWN_HW_IF_CONFIG_EEPROM_LOCKED);
775 
776 		/* Spin until we actually get the lock. */
777 		for (ntries = 0; ntries < 100; ntries++) {
778 			if (IWN_READ(sc, IWN_HW_IF_CONFIG) &
779 			    IWN_HW_IF_CONFIG_EEPROM_LOCKED)
780 				return 0;
781 			DELAY(10);
782 		}
783 	}
784 	return ETIMEDOUT;
785 }
786 
787 static __inline void
788 iwn_eeprom_unlock(struct iwn_softc *sc)
789 {
790 	IWN_CLRBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_EEPROM_LOCKED);
791 }
792 
793 int
794 iwn_read_prom_data(struct iwn_softc *sc, uint32_t addr, void *data, int count)
795 {
796 	uint8_t *out = data;
797 	uint32_t val;
798 	int ntries;
799 
800 	for (; count > 0; count -= 2, addr++) {
801 		IWN_WRITE(sc, IWN_EEPROM, addr << 2);
802 		IWN_CLRBITS(sc, IWN_EEPROM, IWN_EEPROM_CMD);
803 
804 		for (ntries = 0; ntries < 10; ntries++) {
805 			val = IWN_READ(sc, IWN_EEPROM);
806 			if (val & IWN_EEPROM_READ_VALID)
807 				break;
808 			DELAY(5);
809 		}
810 		if (ntries == 10) {
811 			printf("%s: could not read EEPROM\n",
812 			    sc->sc_dev.dv_xname);
813 			return ETIMEDOUT;
814 		}
815 		*out++ = val >> 16;
816 		if (count > 1)
817 			*out++ = val >> 24;
818 	}
819 	return 0;
820 }
821 
822 int
823 iwn_dma_contig_alloc(bus_dma_tag_t tag, struct iwn_dma_info *dma, void **kvap,
824     bus_size_t size, bus_size_t alignment, int flags)
825 {
826 	int nsegs, error;
827 
828 	dma->tag = tag;
829 	dma->size = size;
830 
831 	error = bus_dmamap_create(tag, size, 1, size, 0, flags, &dma->map);
832 	if (error != 0)
833 		goto fail;
834 
835 	error = bus_dmamem_alloc(tag, size, alignment, 0, &dma->seg, 1, &nsegs,
836 	    flags);
837 	if (error != 0)
838 		goto fail;
839 
840 	error = bus_dmamem_map(tag, &dma->seg, 1, size, &dma->vaddr, flags);
841 	if (error != 0)
842 		goto fail;
843 
844 	error = bus_dmamap_load_raw(tag, dma->map, &dma->seg, 1, size, flags);
845 	if (error != 0)
846 		goto fail;
847 
848 	memset(dma->vaddr, 0, size);
849 	bus_dmamap_sync(tag, dma->map, 0, size, BUS_DMASYNC_PREWRITE);
850 
851 	dma->paddr = dma->map->dm_segs[0].ds_addr;
852 	if (kvap != NULL)
853 		*kvap = dma->vaddr;
854 
855 	return 0;
856 
857 fail:	iwn_dma_contig_free(dma);
858 	return error;
859 }
860 
861 void
862 iwn_dma_contig_free(struct iwn_dma_info *dma)
863 {
864 	if (dma->map != NULL) {
865 		if (dma->vaddr != NULL) {
866 			bus_dmamap_sync(dma->tag, dma->map, 0, dma->size,
867 			    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
868 			bus_dmamap_unload(dma->tag, dma->map);
869 			bus_dmamem_unmap(dma->tag, dma->vaddr, dma->size);
870 			bus_dmamem_free(dma->tag, &dma->seg, 1);
871 			dma->vaddr = NULL;
872 		}
873 		bus_dmamap_destroy(dma->tag, dma->map);
874 		dma->map = NULL;
875 	}
876 }
877 
878 int
879 iwn_alloc_sched(struct iwn_softc *sc)
880 {
881 	/* TX scheduler rings must be aligned on a 1KB boundary. */
882 	return iwn_dma_contig_alloc(sc->sc_dmat, &sc->sched_dma,
883 	    (void **)&sc->sched, sc->sc_hal->schedsz, 1024, BUS_DMA_NOWAIT);
884 }
885 
886 void
887 iwn_free_sched(struct iwn_softc *sc)
888 {
889 	iwn_dma_contig_free(&sc->sched_dma);
890 }
891 
892 int
893 iwn_alloc_kw(struct iwn_softc *sc)
894 {
895 	/* "Keep Warm" page must be aligned on a 4KB boundary. */
896 	return iwn_dma_contig_alloc(sc->sc_dmat, &sc->kw_dma, NULL, 4096,
897 	    4096, BUS_DMA_NOWAIT);
898 }
899 
900 void
901 iwn_free_kw(struct iwn_softc *sc)
902 {
903 	iwn_dma_contig_free(&sc->kw_dma);
904 }
905 
906 int
907 iwn_alloc_fwmem(struct iwn_softc *sc)
908 {
909 	/* Must be aligned on a 16-byte boundary. */
910 	return iwn_dma_contig_alloc(sc->sc_dmat, &sc->fw_dma, NULL,
911 	    sc->sc_hal->fwsz, 16, BUS_DMA_NOWAIT);
912 }
913 
914 void
915 iwn_free_fwmem(struct iwn_softc *sc)
916 {
917 	iwn_dma_contig_free(&sc->fw_dma);
918 }
919 
920 struct iwn_rbuf *
921 iwn_alloc_rbuf(struct iwn_softc *sc)
922 {
923 	struct iwn_rbuf *rbuf;
924 
925 	rbuf = SLIST_FIRST(&sc->rxq.freelist);
926 	if (rbuf == NULL)
927 		return NULL;
928 	SLIST_REMOVE_HEAD(&sc->rxq.freelist, next);
929 	return rbuf;
930 }
931 
932 /*
933  * This is called automatically by the network stack when the mbuf to which
934  * our RX buffer is attached is freed.
935  */
936 void
937 iwn_free_rbuf(caddr_t buf, u_int size, void *arg)
938 {
939 	struct iwn_rbuf *rbuf = arg;
940 	struct iwn_softc *sc = rbuf->sc;
941 
942 	/* Put the RX buffer back in the free list. */
943 	SLIST_INSERT_HEAD(&sc->rxq.freelist, rbuf, next);
944 }
945 
946 int
947 iwn_alloc_rpool(struct iwn_softc *sc)
948 {
949 	struct iwn_rx_ring *ring = &sc->rxq;
950 	int i, error;
951 
952 	/* Allocate a big chunk of DMA'able memory... */
953 	error = iwn_dma_contig_alloc(sc->sc_dmat, &ring->buf_dma, NULL,
954 	    IWN_RBUF_COUNT * IWN_RBUF_SIZE, 4096, BUS_DMA_NOWAIT);
955 	if (error != 0) {
956 		printf("%s: could not allocate RX buffers DMA memory\n",
957 		    sc->sc_dev.dv_xname);
958 		return error;
959 	}
960 	/* ...and split it into chunks of IWN_RBUF_SIZE bytes. */
961 	SLIST_INIT(&ring->freelist);
962 	for (i = 0; i < IWN_RBUF_COUNT; i++) {
963 		struct iwn_rbuf *rbuf = &ring->rbuf[i];
964 
965 		rbuf->sc = sc;	/* Backpointer for callbacks. */
966 		rbuf->vaddr = ring->buf_dma.vaddr + i * IWN_RBUF_SIZE;
967 		rbuf->paddr = ring->buf_dma.paddr + i * IWN_RBUF_SIZE;
968 
969 		SLIST_INSERT_HEAD(&ring->freelist, rbuf, next);
970 	}
971 	return 0;
972 }
973 
974 void
975 iwn_free_rpool(struct iwn_softc *sc)
976 {
977 	iwn_dma_contig_free(&sc->rxq.buf_dma);
978 }
979 
980 int
981 iwn_alloc_rx_ring(struct iwn_softc *sc, struct iwn_rx_ring *ring)
982 {
983 	bus_size_t size;
984 	int i, error;
985 
986 	ring->cur = 0;
987 
988 	/* Allocate RX descriptors (256-byte aligned.) */
989 	size = IWN_RX_RING_COUNT * sizeof (uint32_t);
990 	error = iwn_dma_contig_alloc(sc->sc_dmat, &ring->desc_dma,
991 	    (void **)&ring->desc, size, 256, BUS_DMA_NOWAIT);
992 	if (error != 0) {
993 		printf("%s: could not allocate RX ring DMA memory\n",
994 		    sc->sc_dev.dv_xname);
995 		goto fail;
996 	}
997 
998 	/* Allocate RX status area (16-byte aligned.) */
999 	error = iwn_dma_contig_alloc(sc->sc_dmat, &ring->stat_dma,
1000 	    (void **)&ring->stat, sizeof (struct iwn_rx_status), 16,
1001 	    BUS_DMA_NOWAIT);
1002 	if (error != 0) {
1003 		printf("%s: could not allocate RX status DMA memory\n",
1004 		    sc->sc_dev.dv_xname);
1005 		goto fail;
1006 	}
1007 
1008 	/*
1009 	 * Allocate RX buffers.
1010 	 */
1011 	for (i = 0; i < IWN_RX_RING_COUNT; i++) {
1012 		struct iwn_rx_data *data = &ring->data[i];
1013 		struct iwn_rbuf *rbuf;
1014 
1015 		MGETHDR(data->m, M_DONTWAIT, MT_DATA);
1016 		if (data->m == NULL) {
1017 			printf("%s: could not allocate RX mbuf\n",
1018 			    sc->sc_dev.dv_xname);
1019 			error = ENOMEM;
1020 			goto fail;
1021 		}
1022 		if ((rbuf = iwn_alloc_rbuf(sc)) == NULL) {
1023 			m_freem(data->m);
1024 			data->m = NULL;
1025 			printf("%s: could not allocate RX buffer\n",
1026 			    sc->sc_dev.dv_xname);
1027 			error = ENOMEM;
1028 			goto fail;
1029 		}
1030 		/* Attach RX buffer to mbuf header. */
1031 		MEXTADD(data->m, rbuf->vaddr, IWN_RBUF_SIZE, 0, iwn_free_rbuf,
1032 		    rbuf);
1033 
1034 		/* Set physical address of RX buffer (256-byte aligned.) */
1035 		ring->desc[i] = htole32(rbuf->paddr >> 8);
1036 	}
1037 
1038 	bus_dmamap_sync(sc->sc_dmat, ring->desc_dma.map,
1039 	    0, ring->desc_dma.size, BUS_DMASYNC_PREWRITE);
1040 
1041 	return 0;
1042 
1043 fail:	iwn_free_rx_ring(sc, ring);
1044 	return error;
1045 }
1046 
1047 void
1048 iwn_reset_rx_ring(struct iwn_softc *sc, struct iwn_rx_ring *ring)
1049 {
1050 	int ntries;
1051 
1052 	if (iwn_nic_lock(sc) == 0) {
1053 		IWN_WRITE(sc, IWN_FH_RX_CONFIG, 0);
1054 		for (ntries = 0; ntries < 1000; ntries++) {
1055 			if (IWN_READ(sc, IWN_FH_RX_STATUS) &
1056 			    IWN_FH_RX_STATUS_IDLE)
1057 				break;
1058 			DELAY(10);
1059 		}
1060 		iwn_nic_unlock(sc);
1061 	}
1062 	ring->cur = 0;
1063 	sc->last_rx_valid = 0;
1064 }
1065 
1066 void
1067 iwn_free_rx_ring(struct iwn_softc *sc, struct iwn_rx_ring *ring)
1068 {
1069 	int i;
1070 
1071 	iwn_dma_contig_free(&ring->desc_dma);
1072 	iwn_dma_contig_free(&ring->stat_dma);
1073 
1074 	for (i = 0; i < IWN_RX_RING_COUNT; i++) {
1075 		if (ring->data[i].m != NULL)
1076 			m_freem(ring->data[i].m);
1077 	}
1078 }
1079 
1080 int
1081 iwn_alloc_tx_ring(struct iwn_softc *sc, struct iwn_tx_ring *ring, int qid)
1082 {
1083 	bus_addr_t paddr;
1084 	bus_size_t size;
1085 	int i, error;
1086 
1087 	ring->qid = qid;
1088 	ring->queued = 0;
1089 	ring->cur = 0;
1090 
1091 	/* Allocate TX descriptors (256-byte aligned.) */
1092 	size = IWN_TX_RING_COUNT * sizeof (struct iwn_tx_desc);
1093 	error = iwn_dma_contig_alloc(sc->sc_dmat, &ring->desc_dma,
1094 	    (void **)&ring->desc, size, 256, BUS_DMA_NOWAIT);
1095 	if (error != 0) {
1096 		printf("%s: could not allocate TX ring DMA memory\n",
1097 		    sc->sc_dev.dv_xname);
1098 		goto fail;
1099 	}
1100 	/*
1101 	 * We only use rings 0 through 4 (4 EDCA + cmd) so there is no need
1102 	 * to allocate commands space for other rings.
1103 	 * XXX Do we really need to allocate descriptors for other rings?
1104 	 */
1105 	if (qid > 4)
1106 		return 0;
1107 
1108 	size = IWN_TX_RING_COUNT * sizeof (struct iwn_tx_cmd);
1109 	error = iwn_dma_contig_alloc(sc->sc_dmat, &ring->cmd_dma,
1110 	    (void **)&ring->cmd, size, 4, BUS_DMA_NOWAIT);
1111 	if (error != 0) {
1112 		printf("%s: could not allocate TX cmd DMA memory\n",
1113 		    sc->sc_dev.dv_xname);
1114 		goto fail;
1115 	}
1116 
1117 	paddr = ring->cmd_dma.paddr;
1118 	for (i = 0; i < IWN_TX_RING_COUNT; i++) {
1119 		struct iwn_tx_data *data = &ring->data[i];
1120 
1121 		data->cmd_paddr = paddr;
1122 		data->scratch_paddr = paddr + 12;
1123 		paddr += sizeof (struct iwn_tx_cmd);
1124 
1125 		error = bus_dmamap_create(sc->sc_dmat, MCLBYTES,
1126 		    IWN_MAX_SCATTER - 1, MCLBYTES, 0, BUS_DMA_NOWAIT,
1127 		    &data->map);
1128 		if (error != 0) {
1129 			printf("%s: could not create TX buf DMA map\n",
1130 			    sc->sc_dev.dv_xname);
1131 			goto fail;
1132 		}
1133 	}
1134 	return 0;
1135 
1136 fail:	iwn_free_tx_ring(sc, ring);
1137 	return error;
1138 }
1139 
1140 void
1141 iwn_reset_tx_ring(struct iwn_softc *sc, struct iwn_tx_ring *ring)
1142 {
1143 	uint32_t tmp;
1144 	int i, ntries;
1145 
1146 	if (iwn_nic_lock(sc) == 0) {
1147 		IWN_WRITE(sc, IWN_FH_TX_CONFIG(ring->qid), 0);
1148 		for (ntries = 0; ntries < 200; ntries++) {
1149 			tmp = IWN_READ(sc, IWN_FH_TX_STATUS);
1150 			if ((tmp & IWN_FH_TX_STATUS_IDLE(ring->qid)) ==
1151 			    IWN_FH_TX_STATUS_IDLE(ring->qid))
1152 				break;
1153 			DELAY(10);
1154 		}
1155 		iwn_nic_unlock(sc);
1156 	}
1157 	for (i = 0; i < IWN_TX_RING_COUNT; i++) {
1158 		struct iwn_tx_data *data = &ring->data[i];
1159 
1160 		if (data->m != NULL) {
1161 			bus_dmamap_sync(sc->sc_dmat, data->map, 0,
1162 			    data->map->dm_mapsize, BUS_DMASYNC_POSTWRITE);
1163 			bus_dmamap_unload(sc->sc_dmat, data->map);
1164 			m_freem(data->m);
1165 			data->m = NULL;
1166 		}
1167 	}
1168 	/* Clear TX descriptors. */
1169 	memset(ring->desc, 0, ring->desc_dma.size);
1170 	bus_dmamap_sync(sc->sc_dmat, ring->desc_dma.map, 0,
1171 	    ring->desc_dma.size, BUS_DMASYNC_PREWRITE);
1172 	sc->qfullmsk &= ~(1 << ring->qid);
1173 	ring->queued = 0;
1174 	ring->cur = 0;
1175 }
1176 
1177 void
1178 iwn_free_tx_ring(struct iwn_softc *sc, struct iwn_tx_ring *ring)
1179 {
1180 	int i;
1181 
1182 	iwn_dma_contig_free(&ring->desc_dma);
1183 	iwn_dma_contig_free(&ring->cmd_dma);
1184 
1185 	for (i = 0; i < IWN_TX_RING_COUNT; i++) {
1186 		struct iwn_tx_data *data = &ring->data[i];
1187 
1188 		if (data->m != NULL) {
1189 			bus_dmamap_sync(sc->sc_dmat, data->map, 0,
1190 			    data->map->dm_mapsize, BUS_DMASYNC_POSTWRITE);
1191 			bus_dmamap_unload(sc->sc_dmat, data->map);
1192 			m_freem(data->m);
1193 		}
1194 		if (data->map != NULL)
1195 			bus_dmamap_destroy(sc->sc_dmat, data->map);
1196 	}
1197 }
1198 
1199 int
1200 iwn_read_eeprom(struct iwn_softc *sc)
1201 {
1202 	const struct iwn_hal *hal = sc->sc_hal;
1203 	struct ieee80211com *ic = &sc->sc_ic;
1204 	uint16_t val;
1205 	int error;
1206 
1207 	if ((IWN_READ(sc, IWN_EEPROM_GP) & 0x6) == 0) {
1208 		printf("%s: bad EEPROM signature\n", sc->sc_dev.dv_xname);
1209 		return EIO;
1210 	}
1211 	if ((error = iwn_eeprom_lock(sc)) != 0) {
1212 		printf("%s: could not lock EEPROM (error=%d)\n",
1213 		    sc->sc_dev.dv_xname, error);
1214 		return error;
1215 	}
1216 
1217 	iwn_read_prom_data(sc, IWN_EEPROM_RFCFG, &val, 2);
1218 	sc->rfcfg = letoh16(val);
1219 	DPRINTF(("radio config=0x%04x\n", sc->rfcfg));
1220 
1221 	/* Read MAC address. */
1222 	iwn_read_prom_data(sc, IWN_EEPROM_MAC, ic->ic_myaddr, 6);
1223 
1224 	/* Read adapter-specific information from EEPROM. */
1225 	hal->read_eeprom(sc);
1226 
1227 	iwn_eeprom_unlock(sc);
1228 	return 0;
1229 }
1230 
1231 void
1232 iwn4965_read_eeprom(struct iwn_softc *sc)
1233 {
1234 	uint32_t addr;
1235 	uint16_t val;
1236 	int i;
1237 
1238 	/* Read regulatory domain (4 ASCII characters.) */
1239 	iwn_read_prom_data(sc, IWN4965_EEPROM_DOMAIN, sc->eeprom_domain, 4);
1240 
1241 	/* Read the list of authorized channels (20MHz ones only.) */
1242 	for (i = 0; i < 5; i++) {
1243 		addr = iwn4965_regulatory_bands[i];
1244 		iwn_read_eeprom_channels(sc, i, addr);
1245 	}
1246 
1247 	/* Read maximum allowed TX power for 2GHz and 5GHz bands. */
1248 	iwn_read_prom_data(sc, IWN4965_EEPROM_MAXPOW, &val, 2);
1249 	sc->maxpwr2GHz = val & 0xff;
1250 	sc->maxpwr5GHz = val >> 8;
1251 	/* Check that EEPROM values are within valid range. */
1252 	if (sc->maxpwr5GHz < 20 || sc->maxpwr5GHz > 50)
1253 		sc->maxpwr5GHz = 38;
1254 	if (sc->maxpwr2GHz < 20 || sc->maxpwr2GHz > 50)
1255 		sc->maxpwr2GHz = 38;
1256 	DPRINTF(("maxpwr 2GHz=%d 5GHz=%d\n", sc->maxpwr2GHz, sc->maxpwr5GHz));
1257 
1258 	/* Read samples for each TX power group. */
1259 	iwn_read_prom_data(sc, IWN4965_EEPROM_BANDS, sc->bands,
1260 	    sizeof sc->bands);
1261 
1262 	/* Read voltage at which samples were taken. */
1263 	iwn_read_prom_data(sc, IWN4965_EEPROM_VOLTAGE, &val, 2);
1264 	sc->eeprom_voltage = (int16_t)letoh16(val);
1265 	DPRINTF(("voltage=%d (in 0.3V)\n", sc->eeprom_voltage));
1266 
1267 #ifdef IWN_DEBUG
1268 	/* Print samples. */
1269 	if (iwn_debug > 0) {
1270 		for (i = 0; i < IWN_NBANDS; i++)
1271 			iwn4965_print_power_group(sc, i);
1272 	}
1273 #endif
1274 }
1275 
1276 #ifdef IWN_DEBUG
1277 void
1278 iwn4965_print_power_group(struct iwn_softc *sc, int i)
1279 {
1280 	struct iwn4965_eeprom_band *band = &sc->bands[i];
1281 	struct iwn4965_eeprom_chan_samples *chans = band->chans;
1282 	int j, c;
1283 
1284 	printf("===band %d===\n", i);
1285 	printf("chan lo=%d, chan hi=%d\n", band->lo, band->hi);
1286 	printf("chan1 num=%d\n", chans[0].num);
1287 	for (c = 0; c < 2; c++) {
1288 		for (j = 0; j < IWN_NSAMPLES; j++) {
1289 			printf("chain %d, sample %d: temp=%d gain=%d "
1290 			    "power=%d pa_det=%d\n", c, j,
1291 			    chans[0].samples[c][j].temp,
1292 			    chans[0].samples[c][j].gain,
1293 			    chans[0].samples[c][j].power,
1294 			    chans[0].samples[c][j].pa_det);
1295 		}
1296 	}
1297 	printf("chan2 num=%d\n", chans[1].num);
1298 	for (c = 0; c < 2; c++) {
1299 		for (j = 0; j < IWN_NSAMPLES; j++) {
1300 			printf("chain %d, sample %d: temp=%d gain=%d "
1301 			    "power=%d pa_det=%d\n", c, j,
1302 			    chans[1].samples[c][j].temp,
1303 			    chans[1].samples[c][j].gain,
1304 			    chans[1].samples[c][j].power,
1305 			    chans[1].samples[c][j].pa_det);
1306 		}
1307 	}
1308 }
1309 #endif
1310 
1311 void
1312 iwn5000_read_eeprom(struct iwn_softc *sc)
1313 {
1314 	int32_t temp, volt, delta;
1315 	uint32_t base, addr;
1316 	uint16_t val;
1317 	int i;
1318 
1319 	/* Read regulatory domain (4 ASCII characters.) */
1320 	iwn_read_prom_data(sc, IWN5000_EEPROM_REG, &val, 2);
1321 	base = letoh16(val);
1322 	iwn_read_prom_data(sc, base + IWN5000_EEPROM_DOMAIN,
1323 	    sc->eeprom_domain, 4);
1324 
1325 	/* Read the list of authorized channels (20MHz ones only.) */
1326 	for (i = 0; i < 5; i++) {
1327 		addr = base + iwn5000_regulatory_bands[i];
1328 		iwn_read_eeprom_channels(sc, i, addr);
1329 	}
1330 
1331 	iwn_read_prom_data(sc, IWN5000_EEPROM_CAL, &val, 2);
1332 	base = letoh16(val);
1333 	if (sc->hw_type == IWN_HW_REV_TYPE_5150) {
1334 		/* Compute critical temperature (in Kelvin.) */
1335 		iwn_read_prom_data(sc, base + IWN5000_EEPROM_TEMP, &val, 2);
1336 		temp = letoh16(val);
1337 		iwn_read_prom_data(sc, base + IWN5000_EEPROM_VOLT, &val, 2);
1338 		volt = letoh16(val);
1339 		delta = temp - (volt / -5);
1340 		sc->critical_temp = (IWN_CTOK(110) - delta) * -5;
1341 		DPRINTF(("temp=%d volt=%d delta=%dK\n",
1342 		    temp, volt, delta));
1343 	} else {
1344 		/* Read crystal calibration. */
1345 		iwn_read_prom_data(sc, base + IWN5000_EEPROM_CRYSTAL,
1346 		    &sc->eeprom_crystal, sizeof (uint32_t));
1347 		DPRINTF(("crystal calibration 0x%08x\n",
1348 		    letoh32(sc->eeprom_crystal)));
1349 	}
1350 }
1351 
1352 void
1353 iwn_read_eeprom_channels(struct iwn_softc *sc, int n, uint32_t addr)
1354 {
1355 	struct ieee80211com *ic = &sc->sc_ic;
1356 	const struct iwn_chan_band *band = &iwn_bands[n];
1357 	struct iwn_eeprom_chan channels[IWN_MAX_CHAN_PER_BAND];
1358 	uint8_t chan;
1359 	int i;
1360 
1361 	iwn_read_prom_data(sc, addr, channels,
1362 	    band->nchan * sizeof (struct iwn_eeprom_chan));
1363 
1364 	for (i = 0; i < band->nchan; i++) {
1365 		if (!(channels[i].flags & IWN_EEPROM_CHAN_VALID))
1366 			continue;
1367 
1368 		chan = band->chan[i];
1369 
1370 		if (n == 0) {	/* 2GHz band */
1371 			ic->ic_channels[chan].ic_freq =
1372 			    ieee80211_ieee2mhz(chan, IEEE80211_CHAN_2GHZ);
1373 			ic->ic_channels[chan].ic_flags =
1374 			    IEEE80211_CHAN_CCK | IEEE80211_CHAN_OFDM |
1375 			    IEEE80211_CHAN_DYN | IEEE80211_CHAN_2GHZ;
1376 
1377 		} else {	/* 5GHz band */
1378 			/*
1379 			 * Some adapters support channels 7, 8, 11 and 12
1380 			 * both in the 2GHz and 4.9GHz bands.
1381 			 * Because of limitations in our net80211 layer,
1382 			 * we don't support them in the 4.9GHz band.
1383 			 */
1384 			if (chan <= 14)
1385 				continue;
1386 
1387 			ic->ic_channels[chan].ic_freq =
1388 			    ieee80211_ieee2mhz(chan, IEEE80211_CHAN_5GHZ);
1389 			ic->ic_channels[chan].ic_flags = IEEE80211_CHAN_A;
1390 			/* We have at least one valid 5GHz channel. */
1391 			sc->sc_flags |= IWN_FLAG_HAS_5GHZ;
1392 		}
1393 
1394 		/* Is active scan allowed on this channel? */
1395 		if (!(channels[i].flags & IWN_EEPROM_CHAN_ACTIVE)) {
1396 			ic->ic_channels[chan].ic_flags |=
1397 			    IEEE80211_CHAN_PASSIVE;
1398 		}
1399 
1400 		/* Save maximum allowed TX power for this channel. */
1401 		sc->maxpwr[chan] = channels[i].maxpwr;
1402 
1403 		DPRINTF(("adding chan %d flags=0x%x maxpwr=%d\n",
1404 		    chan, channels[i].flags, sc->maxpwr[chan]));
1405 	}
1406 }
1407 
1408 struct ieee80211_node *
1409 iwn_node_alloc(struct ieee80211com *ic)
1410 {
1411 	return malloc(sizeof (struct iwn_node), M_DEVBUF, M_NOWAIT | M_ZERO);
1412 }
1413 
1414 void
1415 iwn_newassoc(struct ieee80211com *ic, struct ieee80211_node *ni, int isnew)
1416 {
1417 	struct iwn_softc *sc = ic->ic_if.if_softc;
1418 	struct iwn_node *wn = (void *)ni;
1419 	uint8_t rate;
1420 	int ridx, i;
1421 
1422 	ieee80211_amrr_node_init(&sc->amrr, &wn->amn);
1423 
1424 	for (i = 0; i < ni->ni_rates.rs_nrates; i++) {
1425 		rate = ni->ni_rates.rs_rates[i] & IEEE80211_RATE_VAL;
1426 		/* Map 802.11 rate to HW rate index. */
1427 		for (ridx = 0; ridx <= IWN_RIDX_MAX; ridx++)
1428 			if (iwn_rates[ridx].rate == rate)
1429 				break;
1430 		wn->ridx[i] = ridx;
1431 		/* Initial TX rate <= 24Mbps. */
1432 		if (rate <= 48)
1433 			ni->ni_txrate = i;
1434 	}
1435 }
1436 
1437 int
1438 iwn_media_change(struct ifnet *ifp)
1439 {
1440 	struct iwn_softc *sc = ifp->if_softc;
1441 	struct ieee80211com *ic = &sc->sc_ic;
1442 	uint8_t rate, ridx;
1443 	int error;
1444 
1445 	error = ieee80211_media_change(ifp);
1446 	if (error != ENETRESET)
1447 		return error;
1448 
1449 	if (ic->ic_fixed_rate != -1) {
1450 		rate = ic->ic_sup_rates[ic->ic_curmode].
1451 		    rs_rates[ic->ic_fixed_rate] & IEEE80211_RATE_VAL;
1452 		/* Map 802.11 rate to HW rate index. */
1453 		for (ridx = 0; ridx <= IWN_RIDX_MAX; ridx++)
1454 			if (iwn_rates[ridx].rate == rate)
1455 				break;
1456 		sc->fixed_ridx = ridx;
1457 	}
1458 
1459 	if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
1460 	    (IFF_UP | IFF_RUNNING)) {
1461 		iwn_stop(ifp, 0);
1462 		error = iwn_init(ifp);
1463 	}
1464 	return error;
1465 }
1466 
1467 int
1468 iwn_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
1469 {
1470 	struct ifnet *ifp = &ic->ic_if;
1471 	struct iwn_softc *sc = ifp->if_softc;
1472 	int error;
1473 
1474 	timeout_del(&sc->calib_to);
1475 
1476 	switch (nstate) {
1477 	case IEEE80211_S_SCAN:
1478 		/* Make the link LED blink while we're scanning. */
1479 		iwn_set_led(sc, IWN_LED_LINK, 10, 10);
1480 
1481 		if ((error = iwn_scan(sc, IEEE80211_CHAN_2GHZ)) != 0) {
1482 			printf("%s: could not initiate scan\n",
1483 			    sc->sc_dev.dv_xname);
1484 			return error;
1485 		}
1486 		ic->ic_state = nstate;
1487 		return 0;
1488 
1489 	case IEEE80211_S_ASSOC:
1490 		if (ic->ic_state != IEEE80211_S_RUN)
1491 			break;
1492 		/* FALLTHROUGH */
1493 	case IEEE80211_S_AUTH:
1494 		/* Reset state to handle reassociations correctly. */
1495 		sc->rxon.associd = 0;
1496 		sc->rxon.filter &= ~htole32(IWN_FILTER_BSS);
1497 		sc->calib.state = IWN_CALIB_STATE_INIT;
1498 
1499 		if ((error = iwn_auth(sc)) != 0) {
1500 			printf("%s: could not move to auth state\n",
1501 			    sc->sc_dev.dv_xname);
1502 			return error;
1503 		}
1504 		break;
1505 
1506 	case IEEE80211_S_RUN:
1507 		if ((error = iwn_run(sc)) != 0) {
1508 			printf("%s: could not move to run state\n",
1509 			    sc->sc_dev.dv_xname);
1510 			return error;
1511 		}
1512 		break;
1513 
1514 	case IEEE80211_S_INIT:
1515 		sc->calib.state = IWN_CALIB_STATE_INIT;
1516 		break;
1517 	}
1518 
1519 	return sc->sc_newstate(ic, nstate, arg);
1520 }
1521 
1522 void
1523 iwn_iter_func(void *arg, struct ieee80211_node *ni)
1524 {
1525 	struct iwn_softc *sc = arg;
1526 	struct iwn_node *wn = (struct iwn_node *)ni;
1527 
1528 	ieee80211_amrr_choose(&sc->amrr, ni, &wn->amn);
1529 }
1530 
1531 void
1532 iwn_calib_timeout(void *arg)
1533 {
1534 	struct iwn_softc *sc = arg;
1535 	struct ieee80211com *ic = &sc->sc_ic;
1536 	int s;
1537 
1538 	if (ic->ic_fixed_rate == -1) {
1539 		s = splnet();
1540 		if (ic->ic_opmode == IEEE80211_M_STA)
1541 			iwn_iter_func(sc, ic->ic_bss);
1542 		else
1543 			ieee80211_iterate_nodes(ic, iwn_iter_func, sc);
1544 		splx(s);
1545 	}
1546 	/* Force automatic TX power calibration every 60 secs. */
1547 	if (++sc->calib_cnt >= 120) {
1548 		uint32_t flags = 0;
1549 
1550 		DPRINTF(("sending request for statistics\n"));
1551 		(void)iwn_cmd(sc, IWN_CMD_GET_STATISTICS, &flags,
1552 		    sizeof flags, 1);
1553 		sc->calib_cnt = 0;
1554 	}
1555 	/* Automatic rate control triggered every 500ms. */
1556 	timeout_add(&sc->calib_to, hz / 2);
1557 }
1558 
1559 int
1560 iwn_ccmp_decap(struct iwn_softc *sc, struct mbuf *m, struct ieee80211_key *k)
1561 {
1562 	struct ieee80211_frame *wh;
1563 	uint64_t pn, *prsc;
1564 	uint8_t *ivp;
1565 	uint8_t tid;
1566 	int hdrlen;
1567 
1568 	wh = mtod(m, struct ieee80211_frame *);
1569 	hdrlen = ieee80211_get_hdrlen(wh);
1570 	ivp = (uint8_t *)wh + hdrlen;
1571 
1572 	/* Check that ExtIV bit is be set. */
1573 	if (!(ivp[3] & IEEE80211_WEP_EXTIV)) {
1574 		DPRINTF(("CCMP decap ExtIV not set\n"));
1575 		return 1;
1576 	}
1577 	tid = ieee80211_has_qos(wh) ?
1578 	    ieee80211_get_qos(wh) & IEEE80211_QOS_TID : 0;
1579 	prsc = &k->k_rsc[tid];
1580 
1581 	/* Extract the 48-bit PN from the CCMP header. */
1582 	pn = (uint64_t)ivp[0]       |
1583 	     (uint64_t)ivp[1] <<  8 |
1584 	     (uint64_t)ivp[4] << 16 |
1585 	     (uint64_t)ivp[5] << 24 |
1586 	     (uint64_t)ivp[6] << 32 |
1587 	     (uint64_t)ivp[7] << 40;
1588 	if (pn <= *prsc) {
1589 		/*
1590 		 * Not necessarily a replayed frame since we did not check
1591 		 * the sequence number of the 802.11 header yet.
1592 		 */
1593 		DPRINTF(("CCMP replayed\n"));
1594 		return 1;
1595 	}
1596 	/* Update last seen packet number. */
1597 	*prsc = pn;
1598 
1599 	/* Clear Protected bit and strip IV. */
1600 	wh->i_fc[1] &= ~IEEE80211_FC1_PROTECTED;
1601 	ovbcopy(wh, mtod(m, caddr_t) + IEEE80211_CCMP_HDRLEN, hdrlen);
1602 	m_adj(m, IEEE80211_CCMP_HDRLEN);
1603 	/* Strip MIC. */
1604 	m_adj(m, -IEEE80211_CCMP_MICLEN);
1605 	return 0;
1606 }
1607 
1608 /*
1609  * Process an RX_PHY firmware notification.  This is usually immediately
1610  * followed by an MPDU_RX_DONE notification.
1611  */
1612 void
1613 iwn_rx_phy(struct iwn_softc *sc, struct iwn_rx_desc *desc)
1614 {
1615 	struct iwn_rx_stat *stat = (struct iwn_rx_stat *)(desc + 1);
1616 
1617 	DPRINTFN(2, ("received PHY stats\n"));
1618 	bus_dmamap_sync(sc->sc_dmat, sc->rxq.buf_dma.map,
1619 	    (caddr_t)stat - sc->rxq.buf_dma.vaddr, sizeof (*stat),
1620 	    BUS_DMASYNC_POSTREAD);
1621 
1622 	/* Save RX statistics, they will be used on MPDU_RX_DONE. */
1623 	memcpy(&sc->last_rx_stat, stat, sizeof (*stat));
1624 	sc->last_rx_valid = 1;
1625 }
1626 
1627 /*
1628  * Process an RX_DONE (4965AGN only) or MPDU_RX_DONE firmware notification.
1629  * Each MPDU_RX_DONE notification must be preceded by an RX_PHY one.
1630  */
1631 void
1632 iwn_rx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc,
1633     struct iwn_rx_data *data)
1634 {
1635 	const struct iwn_hal *hal = sc->sc_hal;
1636 	struct ieee80211com *ic = &sc->sc_ic;
1637 	struct ifnet *ifp = &ic->ic_if;
1638 	struct iwn_rx_ring *ring = &sc->rxq;
1639 	struct iwn_rbuf *rbuf;
1640 	struct ieee80211_frame *wh;
1641 	struct ieee80211_rxinfo rxi;
1642 	struct ieee80211_node *ni;
1643 	struct mbuf *m, *m1;
1644 	struct iwn_rx_stat *stat;
1645 	caddr_t head;
1646 	uint32_t flags;
1647 	int len, rssi;
1648 
1649 	if (desc->type == IWN_MPDU_RX_DONE) {
1650 		/* Check for prior RX_PHY notification. */
1651 		if (!sc->last_rx_valid) {
1652 			DPRINTF(("missing RX_PHY\n"));
1653 			ifp->if_ierrors++;
1654 			return;
1655 		}
1656 		sc->last_rx_valid = 0;
1657 		stat = &sc->last_rx_stat;
1658 	} else
1659 		stat = (struct iwn_rx_stat *)(desc + 1);
1660 
1661 	bus_dmamap_sync(sc->sc_dmat, ring->buf_dma.map,
1662 	    (caddr_t)(desc + 1) - ring->buf_dma.vaddr, IWN_RBUF_SIZE,
1663 	    BUS_DMASYNC_POSTREAD);
1664 
1665 	if (stat->cfg_phy_len > IWN_STAT_MAXLEN) {
1666 		printf("%s: invalid RX statistic header\n",
1667 		    sc->sc_dev.dv_xname);
1668 		ifp->if_ierrors++;
1669 		return;
1670 	}
1671 	if (desc->type == IWN_MPDU_RX_DONE) {
1672 		struct iwn_rx_mpdu *mpdu =
1673 		    (struct iwn_rx_mpdu *)(desc + 1);
1674 		head = (caddr_t)(mpdu + 1);
1675 		len = letoh16(mpdu->len);
1676 	} else {
1677 		head = (caddr_t)(stat + 1) + stat->cfg_phy_len;
1678 		len = letoh16(stat->len);
1679 	}
1680 
1681 	flags = letoh32(*(uint32_t *)(head + len));
1682 
1683 	/* Discard frames with a bad FCS early. */
1684 	if ((flags & IWN_RX_NOERROR) != IWN_RX_NOERROR) {
1685 		DPRINTFN(2, ("RX flags error %x\n", flags));
1686 		ifp->if_ierrors++;
1687 		return;
1688 	}
1689 	/* Discard frames that are too short. */
1690 	if (len < sizeof (struct ieee80211_frame)) {
1691 		DPRINTF(("frame too short: %d\n", len));
1692 		ic->ic_stats.is_rx_tooshort++;
1693 		ifp->if_ierrors++;
1694 		return;
1695 	}
1696 
1697 	m = data->m;
1698 
1699 	/* Finalize mbuf. */
1700 	m->m_pkthdr.rcvif = ifp;
1701 	m->m_data = head;
1702 	m->m_pkthdr.len = m->m_len = len;
1703 
1704 	/* Grab a reference to the source node. */
1705 	wh = mtod(m, struct ieee80211_frame *);
1706 	ni = ieee80211_find_rxnode(ic, wh);
1707 
1708 	rxi.rxi_flags = 0;
1709 	if ((wh->i_fc[1] & IEEE80211_FC1_PROTECTED) &&
1710 	    !IEEE80211_IS_MULTICAST(wh->i_addr1) &&
1711 	    (ni->ni_flags & IEEE80211_NODE_RXPROT) &&
1712 	    ni->ni_pairwise_key.k_cipher == IEEE80211_CIPHER_CCMP) {
1713 		if ((flags & IWN_RX_CIPHER_MASK) != IWN_RX_CIPHER_CCMP) {
1714 			ic->ic_stats.is_ccmp_dec_errs++;
1715 			ifp->if_ierrors++;
1716 			return;
1717 		}
1718 		/* Check whether decryption was successful or not. */
1719 		if ((desc->type == IWN_MPDU_RX_DONE &&
1720 		     (flags & (IWN_RX_MPDU_DEC | IWN_RX_MPDU_MIC_OK)) !=
1721 		      (IWN_RX_MPDU_DEC | IWN_RX_MPDU_MIC_OK)) ||
1722 		    (desc->type != IWN_MPDU_RX_DONE &&
1723 		     (flags & IWN_RX_DECRYPT_MASK) != IWN_RX_DECRYPT_OK)) {
1724 			DPRINTF(("CCMP decryption failed 0x%x\n", flags));
1725 			ic->ic_stats.is_ccmp_dec_errs++;
1726 			ifp->if_ierrors++;
1727 			return;
1728 		}
1729 		if (iwn_ccmp_decap(sc, m, &ni->ni_pairwise_key) != 0) {
1730 			ifp->if_ierrors++;
1731 			return;
1732 		}
1733 		rxi.rxi_flags |= IEEE80211_RXI_HWDEC;
1734 	}
1735 
1736 	if ((rbuf = SLIST_FIRST(&sc->rxq.freelist)) != NULL) {
1737 		MGETHDR(m1, M_DONTWAIT, MT_DATA);
1738 		if (m1 == NULL) {
1739 			ic->ic_stats.is_rx_nombuf++;
1740 			ifp->if_ierrors++;
1741 			return;
1742 		}
1743 		/* Attach RX buffer to mbuf header. */
1744 		MEXTADD(m1, rbuf->vaddr, IWN_RBUF_SIZE, 0, iwn_free_rbuf,
1745 		    rbuf);
1746 		SLIST_REMOVE_HEAD(&sc->rxq.freelist, next);
1747 
1748 		data->m = m1;
1749 
1750 		/* Update RX descriptor. */
1751 		ring->desc[ring->cur] = htole32(rbuf->paddr >> 8);
1752 		bus_dmamap_sync(sc->sc_dmat, ring->desc_dma.map,
1753 		    ring->cur * sizeof (uint32_t), sizeof (uint32_t),
1754 		    BUS_DMASYNC_PREWRITE);
1755 	} else {
1756 		/* No free rbufs, copy frame into an mbuf. */
1757 		m = m_copym2(m, 0, M_COPYALL, M_DONTWAIT);
1758 		if (m == NULL) {
1759 			/* No free mbufs either, drop frame. */
1760 			ic->ic_stats.is_rx_nombuf++;
1761 			ifp->if_ierrors++;
1762 			return;
1763 		}
1764 	}
1765 
1766 	rssi = hal->get_rssi(stat);
1767 
1768 #if NBPFILTER > 0
1769 	if (sc->sc_drvbpf != NULL) {
1770 		struct mbuf mb;
1771 		struct iwn_rx_radiotap_header *tap = &sc->sc_rxtap;
1772 
1773 		tap->wr_flags = 0;
1774 		if (stat->flags & htole16(IWN_STAT_FLAG_SHPREAMBLE))
1775 			tap->wr_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
1776 		tap->wr_chan_freq =
1777 		    htole16(ic->ic_channels[stat->chan].ic_freq);
1778 		tap->wr_chan_flags =
1779 		    htole16(ic->ic_channels[stat->chan].ic_flags);
1780 		tap->wr_dbm_antsignal = (int8_t)rssi;
1781 		tap->wr_dbm_antnoise = (int8_t)sc->noise;
1782 		tap->wr_tsft = stat->tstamp;
1783 		switch (stat->rate) {
1784 		/* CCK rates. */
1785 		case  10: tap->wr_rate =   2; break;
1786 		case  20: tap->wr_rate =   4; break;
1787 		case  55: tap->wr_rate =  11; break;
1788 		case 110: tap->wr_rate =  22; break;
1789 		/* OFDM rates. */
1790 		case 0xd: tap->wr_rate =  12; break;
1791 		case 0xf: tap->wr_rate =  18; break;
1792 		case 0x5: tap->wr_rate =  24; break;
1793 		case 0x7: tap->wr_rate =  36; break;
1794 		case 0x9: tap->wr_rate =  48; break;
1795 		case 0xb: tap->wr_rate =  72; break;
1796 		case 0x1: tap->wr_rate =  96; break;
1797 		case 0x3: tap->wr_rate = 108; break;
1798 		/* Unknown rate: should not happen. */
1799 		default:  tap->wr_rate =   0;
1800 		}
1801 
1802 		mb.m_data = (caddr_t)tap;
1803 		mb.m_len = sc->sc_rxtap_len;
1804 		mb.m_next = m;
1805 		mb.m_nextpkt = NULL;
1806 		mb.m_type = 0;
1807 		mb.m_flags = 0;
1808 		bpf_mtap(sc->sc_drvbpf, &mb, BPF_DIRECTION_IN);
1809 	}
1810 #endif
1811 
1812 	/* Send the frame to the 802.11 layer. */
1813 	rxi.rxi_rssi = rssi;
1814 	rxi.rxi_tstamp = 0;	/* unused */
1815 	ieee80211_input(ifp, m, ni, &rxi);
1816 
1817 	/* Node is no longer needed. */
1818 	ieee80211_release_node(ic, ni);
1819 }
1820 
1821 /*
1822  * Process a CALIBRATION_RESULT notification sent by the initialization
1823  * firmware on response to a CMD_CALIB_CONFIG command (5000 only.)
1824  */
1825 void
1826 iwn5000_rx_calib_results(struct iwn_softc *sc, struct iwn_rx_desc *desc)
1827 {
1828 	struct iwn_phy_calib *calib = (struct iwn_phy_calib *)(desc + 1);
1829 	int len, idx = -1;
1830 
1831 	/* Runtime firmware should not send such a notification. */
1832 	if (!(sc->sc_flags & IWN_FLAG_FIRST_BOOT))
1833 		return;
1834 
1835 	len = (letoh32(desc->len) & 0x3fff) - 4;
1836 	bus_dmamap_sync(sc->sc_dmat, sc->rxq.buf_dma.map,
1837 	    (caddr_t)calib - sc->rxq.buf_dma.vaddr, len,
1838 	    BUS_DMASYNC_POSTREAD);
1839 
1840 	switch (calib->code) {
1841 	case IWN5000_PHY_CALIB_DC:
1842 		if (sc->hw_type == IWN_HW_REV_TYPE_5150)
1843 			idx = 0;
1844 		break;
1845 	case IWN5000_PHY_CALIB_LO:
1846 		idx = 1;
1847 		break;
1848 	case IWN5000_PHY_CALIB_TX_IQ:
1849 		idx = 2;
1850 		break;
1851 	case IWN5000_PHY_CALIB_TX_IQ_PERD:
1852 		if (sc->hw_type != IWN_HW_REV_TYPE_5150)
1853 			idx = 3;
1854 		break;
1855 	case IWN5000_PHY_CALIB_BASE_BAND:
1856 		idx = 4;
1857 		break;
1858 	}
1859 	if (idx == -1)	/* Ignore other results. */
1860 		return;
1861 
1862 	/* Save calibration result. */
1863 	if (sc->calibcmd[idx].buf != NULL)
1864 		free(sc->calibcmd[idx].buf, M_DEVBUF);
1865 	sc->calibcmd[idx].buf = malloc(len, M_DEVBUF, M_NOWAIT);
1866 	if (sc->calibcmd[idx].buf == NULL) {
1867 		DPRINTF(("not enough memory for calibration result %d\n",
1868 		    calib->code));
1869 		return;
1870 	}
1871 	DPRINTF(("saving calibration result code=%d len=%d\n",
1872 	    calib->code, len));
1873 	sc->calibcmd[idx].len = len;
1874 	memcpy(sc->calibcmd[idx].buf, calib, len);
1875 }
1876 
1877 /*
1878  * Process an RX_STATISTICS or BEACON_STATISTICS firmware notification.
1879  * The latter is sent by the firmware after each received beacon.
1880  */
1881 void
1882 iwn_rx_statistics(struct iwn_softc *sc, struct iwn_rx_desc *desc)
1883 {
1884 	const struct iwn_hal *hal = sc->sc_hal;
1885 	struct ieee80211com *ic = &sc->sc_ic;
1886 	struct iwn_calib_state *calib = &sc->calib;
1887 	struct iwn_stats *stats = (struct iwn_stats *)(desc + 1);
1888 	int temp;
1889 
1890 	/* Ignore statistics received during a scan. */
1891 	if (ic->ic_state != IEEE80211_S_RUN)
1892 		return;
1893 
1894 	bus_dmamap_sync(sc->sc_dmat, sc->rxq.buf_dma.map,
1895 	    (caddr_t)stats - sc->rxq.buf_dma.vaddr, sizeof (*stats),
1896 	    BUS_DMASYNC_POSTREAD);
1897 
1898 	DPRINTFN(3, ("received statistics (cmd=%d)\n", desc->type));
1899 	sc->calib_cnt = 0;	/* Reset TX power calibration timeout. */
1900 
1901 	/* Test if temperature has changed. */
1902 	if (stats->general.temp != sc->rawtemp) {
1903 		/* Convert "raw" temperature to degC. */
1904 		sc->rawtemp = stats->general.temp;
1905 		temp = hal->get_temperature(sc);
1906 		DPRINTFN(2, ("temperature=%dC\n", temp));
1907 
1908 		/* Update temperature sensor. */
1909 		sc->sensor.value = IWN_CTOMUK(temp);
1910 		sc->sensor.flags &= ~SENSOR_FINVALID;
1911 
1912 		/* Update TX power if need be (4965AGN only.) */
1913 		if (sc->hw_type == IWN_HW_REV_TYPE_4965)
1914 			iwn4965_power_calibration(sc, temp);
1915 	}
1916 
1917 	if (desc->type != IWN_BEACON_STATISTICS)
1918 		return;	/* Reply to a statistics request. */
1919 
1920 	sc->noise = iwn_get_noise(&stats->rx.general);
1921 
1922 	/* Test that RSSI and noise are present in stats report. */
1923 	if (letoh32(stats->rx.general.flags) != 1) {
1924 		DPRINTF(("received statistics without RSSI\n"));
1925 		return;
1926 	}
1927 
1928 	if (calib->state == IWN_CALIB_STATE_ASSOC)
1929 		iwn_collect_noise(sc, &stats->rx.general);
1930 	else if (calib->state == IWN_CALIB_STATE_RUN)
1931 		iwn_tune_sensitivity(sc, &stats->rx);
1932 }
1933 
1934 /*
1935  * Process a TX_DONE firmware notification.  Unfortunately, the 4965AGN
1936  * and 5000 adapters have different incompatible TX status formats.
1937  */
1938 void
1939 iwn4965_tx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc)
1940 {
1941 	struct iwn4965_tx_stat *stat = (struct iwn4965_tx_stat *)(desc + 1);
1942 
1943 	bus_dmamap_sync(sc->sc_dmat, sc->rxq.buf_dma.map,
1944 	    (caddr_t)stat - sc->rxq.buf_dma.vaddr, sizeof (*stat),
1945 	    BUS_DMASYNC_POSTREAD);
1946 	iwn_tx_done(sc, desc, stat->retrycnt, letoh32(stat->status) & 0xff);
1947 }
1948 
1949 void
1950 iwn5000_tx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc)
1951 {
1952 	struct iwn5000_tx_stat *stat = (struct iwn5000_tx_stat *)(desc + 1);
1953 
1954 	/* Reset TX scheduler slot. */
1955 	iwn5000_reset_sched(sc, desc->qid & 0xf, desc->idx);
1956 
1957 	bus_dmamap_sync(sc->sc_dmat, sc->rxq.buf_dma.map,
1958 	    (caddr_t)stat - sc->rxq.buf_dma.vaddr, sizeof (*stat),
1959 	    BUS_DMASYNC_POSTREAD);
1960 	iwn_tx_done(sc, desc, stat->retrycnt, letoh16(stat->status) & 0xff);
1961 }
1962 
1963 /*
1964  * Adapter-independent backend for TX_DONE firmware notifications.
1965  */
1966 void
1967 iwn_tx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc, int retrycnt,
1968     uint8_t status)
1969 {
1970 	struct ieee80211com *ic = &sc->sc_ic;
1971 	struct ifnet *ifp = &ic->ic_if;
1972 	struct iwn_tx_ring *ring = &sc->txq[desc->qid & 0xf];
1973 	struct iwn_tx_data *data = &ring->data[desc->idx];
1974 	struct iwn_node *wn = (struct iwn_node *)data->ni;
1975 
1976 	/* Update rate control statistics. */
1977 	wn->amn.amn_txcnt++;
1978 	if (retrycnt > 0)
1979 		wn->amn.amn_retrycnt++;
1980 
1981 	if (status != 1 && status != 2)
1982 		ifp->if_oerrors++;
1983 	else
1984 		ifp->if_opackets++;
1985 
1986 	/* Unmap and free mbuf. */
1987 	bus_dmamap_sync(sc->sc_dmat, data->map, 0, data->map->dm_mapsize,
1988 	    BUS_DMASYNC_POSTWRITE);
1989 	bus_dmamap_unload(sc->sc_dmat, data->map);
1990 	m_freem(data->m);
1991 	data->m = NULL;
1992 	ieee80211_release_node(ic, data->ni);
1993 	data->ni = NULL;
1994 
1995 	sc->sc_tx_timer = 0;
1996 	if (--ring->queued < IWN_TX_RING_LOMARK) {
1997 		sc->qfullmsk &= ~(1 << ring->qid);
1998 		if (sc->qfullmsk == 0 && (ifp->if_flags & IFF_OACTIVE)) {
1999 			ifp->if_flags &= ~IFF_OACTIVE;
2000 			(*ifp->if_start)(ifp);
2001 		}
2002 	}
2003 }
2004 
2005 /*
2006  * Process a "command done" firmware notification.  This is where we wakeup
2007  * processes waiting for a synchronous command completion.
2008  */
2009 void
2010 iwn_cmd_done(struct iwn_softc *sc, struct iwn_rx_desc *desc)
2011 {
2012 	struct iwn_tx_ring *ring = &sc->txq[4];
2013 	struct iwn_tx_data *data;
2014 
2015 	if ((desc->qid & 0xf) != 4)
2016 		return;	/* Not a command ack. */
2017 
2018 	data = &ring->data[desc->idx];
2019 
2020 	/* If the command was mapped in an mbuf, free it. */
2021 	if (data->m != NULL) {
2022 		bus_dmamap_sync(sc->sc_dmat, data->map, 0,
2023 		    data->map->dm_mapsize, BUS_DMASYNC_POSTWRITE);
2024 		bus_dmamap_unload(sc->sc_dmat, data->map);
2025 		m_freem(data->m);
2026 		data->m = NULL;
2027 	}
2028 	wakeup(&ring->desc[desc->idx]);
2029 }
2030 
2031 /*
2032  * Process an INT_FH_RX or INT_SW_RX interrupt.
2033  */
2034 void
2035 iwn_notif_intr(struct iwn_softc *sc)
2036 {
2037 	struct ieee80211com *ic = &sc->sc_ic;
2038 	struct ifnet *ifp = &ic->ic_if;
2039 	uint16_t hw;
2040 
2041 	bus_dmamap_sync(sc->sc_dmat, sc->rxq.stat_dma.map,
2042 	    0, sc->rxq.stat_dma.size, BUS_DMASYNC_POSTREAD);
2043 
2044 	hw = letoh16(sc->rxq.stat->closed_count) & 0xfff;
2045 	while (sc->rxq.cur != hw) {
2046 		struct iwn_rx_data *data = &sc->rxq.data[sc->rxq.cur];
2047 		struct iwn_rx_desc *desc = (void *)data->m->m_ext.ext_buf;
2048 
2049 		bus_dmamap_sync(sc->sc_dmat, sc->rxq.buf_dma.map,
2050 		    (caddr_t)desc - sc->rxq.buf_dma.vaddr, sizeof (*desc),
2051 		    BUS_DMASYNC_POSTREAD);
2052 
2053 		DPRINTFN(4, ("notification qid=%d idx=%d flags=%x type=%d\n",
2054 		    desc->qid & 0xf, desc->idx, desc->flags, desc->type));
2055 
2056 		if (!(desc->qid & 0x80))	/* Reply to a command. */
2057 			iwn_cmd_done(sc, desc);
2058 
2059 		switch (desc->type) {
2060 		case IWN_RX_PHY:
2061 			iwn_rx_phy(sc, desc);
2062 			break;
2063 
2064 		case IWN_RX_DONE:		/* 4965AGN only. */
2065 		case IWN_MPDU_RX_DONE:
2066 			/* An 802.11 frame has been received. */
2067 			iwn_rx_done(sc, desc, data);
2068 			break;
2069 
2070 		case IWN_TX_DONE:
2071 			/* An 802.11 frame has been transmitted. */
2072 			sc->sc_hal->tx_done(sc, desc);
2073 			break;
2074 
2075 		case IWN_RX_STATISTICS:
2076 		case IWN_BEACON_STATISTICS:
2077 			iwn_rx_statistics(sc, desc);
2078 			break;
2079 
2080 		case IWN_BEACON_MISSED:
2081 		{
2082 			struct iwn_beacon_missed *miss =
2083 			    (struct iwn_beacon_missed *)(desc + 1);
2084 
2085 			bus_dmamap_sync(sc->sc_dmat, sc->rxq.buf_dma.map,
2086 			    (caddr_t)miss - sc->rxq.buf_dma.vaddr,
2087 			    sizeof (*miss), BUS_DMASYNC_POSTREAD);
2088 			/*
2089 			 * If more than 5 consecutive beacons are missed,
2090 			 * reinitialize the sensitivity state machine.
2091 			 */
2092 			DPRINTF(("beacons missed %d/%d\n",
2093 			    letoh32(miss->consecutive), letoh32(miss->total)));
2094 			if (ic->ic_state == IEEE80211_S_RUN &&
2095 			    letoh32(miss->consecutive) > 5)
2096 				(void)iwn_init_sensitivity(sc);
2097 			break;
2098 		}
2099 		case IWN_UC_READY:
2100 		{
2101 			struct iwn_ucode_info *uc =
2102 			    (struct iwn_ucode_info *)(desc + 1);
2103 
2104 			/* The microcontroller is ready. */
2105 			bus_dmamap_sync(sc->sc_dmat, sc->rxq.buf_dma.map,
2106 			    (caddr_t)uc - sc->rxq.buf_dma.vaddr,
2107 			    sizeof (*uc), BUS_DMASYNC_POSTREAD);
2108 			DPRINTF(("microcode alive notification version=%d.%d "
2109 			    "subtype=%x alive=%x\n", uc->major, uc->minor,
2110 			    uc->subtype, letoh32(uc->valid)));
2111 
2112 			if (letoh32(uc->valid) != 1) {
2113 				printf("%s: microcontroller initialization "
2114 				    "failed\n", sc->sc_dev.dv_xname);
2115 				break;
2116 			}
2117 			if (uc->subtype == IWN_UCODE_INIT) {
2118 				/* Save microcontroller's report. */
2119 				memcpy(&sc->ucode_info, uc, sizeof (*uc));
2120 			}
2121 			/* Save the address of the error log in SRAM. */
2122 			sc->errptr = letoh32(uc->errptr);
2123 			break;
2124 		}
2125 		case IWN_STATE_CHANGED:
2126 		{
2127 			uint32_t *status = (uint32_t *)(desc + 1);
2128 
2129 			/* Enabled/disabled notification. */
2130 			bus_dmamap_sync(sc->sc_dmat, sc->rxq.buf_dma.map,
2131 			    (caddr_t)status - sc->rxq.buf_dma.vaddr,
2132 			    sizeof (*status), BUS_DMASYNC_POSTREAD);
2133 			DPRINTF(("state changed to %x\n", letoh32(*status)));
2134 
2135 			if (letoh32(*status) & 1) {
2136 				/* The radio button has to be pushed. */
2137 				printf("%s: Radio transmitter is off\n",
2138 				    sc->sc_dev.dv_xname);
2139 				/* Turn the interface down. */
2140 				ifp->if_flags &= ~IFF_UP;
2141 				iwn_stop(ifp, 1);
2142 				return;	/* No further processing. */
2143 			}
2144 			break;
2145 		}
2146 		case IWN_START_SCAN:
2147 		{
2148 			struct iwn_start_scan *scan =
2149 			    (struct iwn_start_scan *)(desc + 1);
2150 
2151 			bus_dmamap_sync(sc->sc_dmat, sc->rxq.buf_dma.map,
2152 			    (caddr_t)scan - sc->rxq.buf_dma.vaddr,
2153 			    sizeof (*scan), BUS_DMASYNC_POSTREAD);
2154 			DPRINTFN(2, ("scanning channel %d status %x\n",
2155 			    scan->chan, letoh32(scan->status)));
2156 
2157 			/* Fix current channel. */
2158 			ic->ic_bss->ni_chan = &ic->ic_channels[scan->chan];
2159 			break;
2160 		}
2161 		case IWN_STOP_SCAN:
2162 		{
2163 			struct iwn_stop_scan *scan =
2164 			    (struct iwn_stop_scan *)(desc + 1);
2165 
2166 			bus_dmamap_sync(sc->sc_dmat, sc->rxq.buf_dma.map,
2167 			    (caddr_t)scan - sc->rxq.buf_dma.vaddr,
2168 			    sizeof (*scan), BUS_DMASYNC_POSTREAD);
2169 			DPRINTF(("scan finished nchan=%d status=%d chan=%d\n",
2170 			    scan->nchan, scan->status, scan->chan));
2171 
2172 			if (scan->status == 1 && scan->chan <= 14 &&
2173 			    (sc->sc_flags & IWN_FLAG_HAS_5GHZ)) {
2174 				/*
2175 				 * We just finished scanning 2GHz channels,
2176 				 * start scanning 5GHz ones.
2177 				 */
2178 				if (iwn_scan(sc, IEEE80211_CHAN_5GHZ) == 0)
2179 					break;
2180 			}
2181 			ieee80211_end_scan(ifp);
2182 			break;
2183 		}
2184 		case IWN5000_CALIBRATION_RESULT:
2185 			iwn5000_rx_calib_results(sc, desc);
2186 			break;
2187 
2188 		case IWN5000_CALIBRATION_DONE:
2189 			wakeup(sc);
2190 			break;
2191 		}
2192 
2193 		sc->rxq.cur = (sc->rxq.cur + 1) % IWN_RX_RING_COUNT;
2194 	}
2195 
2196 	/* Tell the firmware what we have processed. */
2197 	hw = (hw == 0) ? IWN_RX_RING_COUNT - 1 : hw - 1;
2198 	IWN_WRITE(sc, IWN_FH_RX_WPTR, hw & ~7);
2199 }
2200 
2201 /*
2202  * Process an INT_WAKEUP interrupt raised when the microcontroller wakes up
2203  * from power-down sleep mode.
2204  */
2205 void
2206 iwn_wakeup_intr(struct iwn_softc *sc)
2207 {
2208 	int qid;
2209 
2210 	DPRINTF(("ucode wakeup from power-down sleep\n"));
2211 
2212 	/* Wakeup RX and TX rings. */
2213 	IWN_WRITE(sc, IWN_FH_RX_WPTR, sc->rxq.cur & ~7);
2214 	for (qid = 0; qid < 6; qid++) {
2215 		struct iwn_tx_ring *ring = &sc->txq[qid];
2216 		IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | ring->cur);
2217 	}
2218 }
2219 
2220 /*
2221  * Dump the error log of the firmware when a firmware panic occurs.  Although
2222  * we can't debug the firmware because it is neither open source nor free, it
2223  * can help us to identify certain classes of problems.
2224  */
2225 void
2226 iwn_fatal_intr(struct iwn_softc *sc)
2227 {
2228 	const struct iwn_hal *hal = sc->sc_hal;
2229 	struct iwn_fw_dump dump;
2230 	int i;
2231 
2232 	/* Check that the error log address is valid. */
2233 	if (sc->errptr < IWN_FW_DATA_BASE ||
2234 	    sc->errptr + sizeof (dump) >
2235 	    IWN_FW_DATA_BASE + hal->fw_data_maxsz) {
2236 		printf("%s: bad firmware error log address 0x%08x\n",
2237 		    sc->sc_dev.dv_xname, sc->errptr);
2238 		return;
2239 	}
2240 	if (iwn_nic_lock(sc) != 0) {
2241 		printf("%s: could not read firmware error log\n",
2242 		    sc->sc_dev.dv_xname);
2243 		return;
2244 	}
2245 	/* Read firmware error log from SRAM. */
2246 	iwn_mem_read_region_4(sc, sc->errptr, (uint32_t *)&dump,
2247 	    sizeof (dump) / sizeof (uint32_t));
2248 	iwn_nic_unlock(sc);
2249 
2250 	if (dump.valid == 0) {
2251 		printf("%s: firmware error log is empty\n",
2252 		    sc->sc_dev.dv_xname);
2253 		return;
2254 	}
2255 	printf("firmware error log:\n");
2256 	printf("  error type      = \"%s\" (0x%08X)\n",
2257 	    (dump.id < nitems(iwn_fw_errmsg)) ?
2258 		iwn_fw_errmsg[dump.id] : "UNKNOWN",
2259 	    dump.id);
2260 	printf("  program counter = 0x%08X\n", dump.pc);
2261 	printf("  source line     = 0x%08X\n", dump.src_line);
2262 	printf("  error data      = 0x%08X%08X\n",
2263 	    dump.error_data[0], dump.error_data[1]);
2264 	printf("  branch link     = 0x%08X%08X\n",
2265 	    dump.branch_link[0], dump.branch_link[1]);
2266 	printf("  interrupt link  = 0x%08X%08X\n",
2267 	    dump.interrupt_link[0], dump.interrupt_link[1]);
2268 	printf("  time            = %u\n", dump.time[0]);
2269 
2270 	/* Dump driver status (TX and RX rings) while we're here. */
2271 	printf("driver status:\n");
2272 	for (i = 0; i < hal->ntxqs; i++) {
2273 		struct iwn_tx_ring *ring = &sc->txq[i];
2274 		printf("  tx ring %2d: qid=%-2d cur=%-3d queued=%-3d\n",
2275 		    i, ring->qid, ring->cur, ring->queued);
2276 	}
2277 	printf("  rx ring: cur=%d\n", sc->rxq.cur);
2278 	printf("  802.11 state %d\n", sc->sc_ic.ic_state);
2279 }
2280 
2281 int
2282 iwn_intr(void *arg)
2283 {
2284 	struct iwn_softc *sc = arg;
2285 	struct ifnet *ifp = &sc->sc_ic.ic_if;
2286 	uint32_t r1, r2;
2287 
2288 	/* Disable interrupts. */
2289 	IWN_WRITE(sc, IWN_MASK, 0);
2290 
2291 	r1 = IWN_READ(sc, IWN_INT);
2292 	r2 = IWN_READ(sc, IWN_FH_INT);
2293 
2294 	if (r1 == 0 && r2 == 0) {
2295 		if (ifp->if_flags & IFF_UP)
2296 			IWN_WRITE(sc, IWN_MASK, IWN_INT_MASK);
2297 		return 0;	/* Interrupt not for us. */
2298 	}
2299 	if (r1 == 0xffffffff || (r1 & 0xfffffff0) == 0xa5a5a5a0)
2300 		return 0;	/* Hardware gone! */
2301 
2302 	/* Acknowledge interrupts. */
2303 	IWN_WRITE(sc, IWN_INT, r1);
2304 	IWN_WRITE(sc, IWN_FH_INT, r2);
2305 
2306 	if (r1 & IWN_INT_RF_TOGGLED) {
2307 		uint32_t tmp = IWN_READ(sc, IWN_GP_CNTRL);
2308 		printf("%s: RF switch: radio %s\n", sc->sc_dev.dv_xname,
2309 		    (tmp & IWN_GP_CNTRL_RFKILL) ? "enabled" : "disabled");
2310 	}
2311 	if (r1 & IWN_INT_CT_REACHED) {
2312 		printf("%s: critical temperature reached!\n",
2313 		    sc->sc_dev.dv_xname);
2314 		/* XXX Reduce TX power? */
2315 	}
2316 	if (r1 & (IWN_INT_SW_ERR | IWN_INT_HW_ERR)) {
2317 		printf("%s: fatal firmware error\n", sc->sc_dev.dv_xname);
2318 		/* Dump firmware error log and stop. */
2319 		iwn_fatal_intr(sc);
2320 		ifp->if_flags &= ~IFF_UP;
2321 		iwn_stop(ifp, 1);
2322 		return 1;
2323 	}
2324 	if ((r1 & (IWN_INT_FH_RX | IWN_INT_SW_RX)) ||
2325 	    (r2 & IWN_FH_INT_RX))
2326 		iwn_notif_intr(sc);
2327 
2328 	if ((r1 & IWN_INT_FH_TX) || (r2 & IWN_FH_INT_TX))
2329 		wakeup(sc);	/* FH DMA transfer completed. */
2330 
2331 	if (r1 & IWN_INT_ALIVE)
2332 		wakeup(sc);	/* Firmware is alive. */
2333 
2334 	if (r1 & IWN_INT_WAKEUP)
2335 		iwn_wakeup_intr(sc);
2336 
2337 	/* Re-enable interrupts. */
2338 	if (ifp->if_flags & IFF_UP)
2339 		IWN_WRITE(sc, IWN_MASK, IWN_INT_MASK);
2340 
2341 	return 1;
2342 }
2343 
2344 /*
2345  * Update TX scheduler ring when transmitting an 802.11 frame (4965AGN and
2346  * 5000 adapters use a slightly different format.)
2347  */
2348 void
2349 iwn4965_update_sched(struct iwn_softc *sc, int qid, int idx, uint8_t id,
2350     uint16_t len)
2351 {
2352 	uint16_t *w = &sc->sched[qid * IWN4965_SCHED_COUNT + idx];
2353 
2354 	*w = htole16(len + 8);
2355 	bus_dmamap_sync(sc->sc_dmat, sc->sched_dma.map,
2356 	    (caddr_t)w - sc->sched_dma.vaddr, sizeof (uint16_t),
2357 	    BUS_DMASYNC_PREWRITE);
2358 	if (idx < IWN_SCHED_WINSZ) {
2359 		*(w + IWN_TX_RING_COUNT) = *w;
2360 		bus_dmamap_sync(sc->sc_dmat, sc->sched_dma.map,
2361 		    (caddr_t)(w + IWN_TX_RING_COUNT) - sc->sched_dma.vaddr,
2362 		    sizeof (uint16_t), BUS_DMASYNC_PREWRITE);
2363 	}
2364 }
2365 
2366 void
2367 iwn5000_update_sched(struct iwn_softc *sc, int qid, int idx, uint8_t id,
2368     uint16_t len)
2369 {
2370 	uint16_t *w = &sc->sched[qid * IWN5000_SCHED_COUNT + idx];
2371 
2372 	*w = htole16(id << 12 | (len + 8));
2373 	bus_dmamap_sync(sc->sc_dmat, sc->sched_dma.map,
2374 	    (caddr_t)w - sc->sched_dma.vaddr, sizeof (uint16_t),
2375 	    BUS_DMASYNC_PREWRITE);
2376 	if (idx < IWN_SCHED_WINSZ) {
2377 		*(w + IWN_TX_RING_COUNT) = *w;
2378 		bus_dmamap_sync(sc->sc_dmat, sc->sched_dma.map,
2379 		    (caddr_t)(w + IWN_TX_RING_COUNT) - sc->sched_dma.vaddr,
2380 		    sizeof (uint16_t), BUS_DMASYNC_PREWRITE);
2381 	}
2382 }
2383 
2384 void
2385 iwn5000_reset_sched(struct iwn_softc *sc, int qid, int idx)
2386 {
2387 	uint16_t *w = &sc->sched[qid * IWN5000_SCHED_COUNT + idx];
2388 
2389 	*w = (*w & htole16(0xf000)) | htole16(1);
2390 	bus_dmamap_sync(sc->sc_dmat, sc->sched_dma.map,
2391 	    (caddr_t)w - sc->sched_dma.vaddr, sizeof (uint16_t),
2392 	    BUS_DMASYNC_PREWRITE);
2393 	if (idx < IWN_SCHED_WINSZ) {
2394 		*(w + IWN_TX_RING_COUNT) = *w;
2395 		bus_dmamap_sync(sc->sc_dmat, sc->sched_dma.map,
2396 		    (caddr_t)(w + IWN_TX_RING_COUNT) - sc->sched_dma.vaddr,
2397 		    sizeof (uint16_t), BUS_DMASYNC_PREWRITE);
2398 	}
2399 }
2400 
2401 int
2402 iwn_tx(struct iwn_softc *sc, struct mbuf *m, struct ieee80211_node *ni)
2403 {
2404 	const struct iwn_hal *hal = sc->sc_hal;
2405 	struct ieee80211com *ic = &sc->sc_ic;
2406 	struct iwn_node *wn = (void *)ni;
2407 	struct iwn_tx_ring *ring;
2408 	struct iwn_tx_desc *desc;
2409 	struct iwn_tx_data *data;
2410 	struct iwn_tx_cmd *cmd;
2411 	struct iwn_cmd_data *tx;
2412 	const struct iwn_rate *rinfo;
2413 	struct ieee80211_frame *wh;
2414 	struct ieee80211_key *k = NULL;
2415 	struct mbuf *m1;
2416 	enum ieee80211_edca_ac ac;
2417 	uint32_t flags;
2418 	uint16_t qos;
2419 	u_int hdrlen;
2420 	bus_dma_segment_t *seg;
2421 	uint8_t *ivp, tid, ridx, txant, type;
2422 	int i, totlen, hasqos, error, pad;
2423 
2424 	wh = mtod(m, struct ieee80211_frame *);
2425 	hdrlen = ieee80211_get_hdrlen(wh);
2426 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
2427 
2428 	/* Select EDCA Access Category and TX ring for this frame. */
2429 	if ((hasqos = ieee80211_has_qos(wh))) {
2430 		qos = ieee80211_get_qos(wh);
2431 		tid = qos & IEEE80211_QOS_TID;
2432 		ac = ieee80211_up_to_ac(ic, tid);
2433 	} else {
2434 		tid = 0;
2435 		ac = EDCA_AC_BE;
2436 	}
2437 
2438 	ring = &sc->txq[ac];
2439 	desc = &ring->desc[ring->cur];
2440 	data = &ring->data[ring->cur];
2441 
2442 	/* Choose a TX rate index. */
2443 	if (IEEE80211_IS_MULTICAST(wh->i_addr1) ||
2444 	    type != IEEE80211_FC0_TYPE_DATA) {
2445 		ridx = (ic->ic_curmode == IEEE80211_MODE_11A) ?
2446 		    IWN_RIDX_OFDM6 : IWN_RIDX_CCK1;
2447 	} else if (ic->ic_fixed_rate != -1) {
2448 		ridx = sc->fixed_ridx;
2449 	} else
2450 		ridx = wn->ridx[ni->ni_txrate];
2451 	rinfo = &iwn_rates[ridx];
2452 
2453 #if NBPFILTER > 0
2454 	if (sc->sc_drvbpf != NULL) {
2455 		struct mbuf mb;
2456 		struct iwn_tx_radiotap_header *tap = &sc->sc_txtap;
2457 
2458 		tap->wt_flags = 0;
2459 		tap->wt_chan_freq = htole16(ni->ni_chan->ic_freq);
2460 		tap->wt_chan_flags = htole16(ni->ni_chan->ic_flags);
2461 		tap->wt_rate = rinfo->rate;
2462 		tap->wt_hwqueue = ac;
2463 		if ((ic->ic_flags & IEEE80211_F_WEPON) &&
2464 		    (wh->i_fc[1] & IEEE80211_FC1_PROTECTED))
2465 			tap->wt_flags |= IEEE80211_RADIOTAP_F_WEP;
2466 
2467 		mb.m_data = (caddr_t)tap;
2468 		mb.m_len = sc->sc_txtap_len;
2469 		mb.m_next = m;
2470 		mb.m_nextpkt = NULL;
2471 		mb.m_type = 0;
2472 		mb.m_flags = 0;
2473 		bpf_mtap(sc->sc_drvbpf, &mb, BPF_DIRECTION_OUT);
2474 	}
2475 #endif
2476 
2477 	totlen = m->m_pkthdr.len;
2478 
2479 	/* Encrypt the frame if need be. */
2480 	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
2481 		/* Retrieve key for TX. */
2482 		k = ieee80211_get_txkey(ic, wh, ni);
2483 		if (k->k_cipher != IEEE80211_CIPHER_CCMP) {
2484 			/* Do software encryption. */
2485 			if ((m = ieee80211_encrypt(ic, m, k)) == NULL)
2486 				return ENOBUFS;
2487 			/* 802.11 header may have moved. */
2488 			wh = mtod(m, struct ieee80211_frame *);
2489 			totlen = m->m_pkthdr.len;
2490 
2491 		} else	/* HW appends CCMP MIC. */
2492 			totlen += IEEE80211_CCMP_HDRLEN;
2493 	}
2494 
2495 	/* Prepare TX firmware command. */
2496 	cmd = &ring->cmd[ring->cur];
2497 	cmd->code = IWN_CMD_TX_DATA;
2498 	cmd->flags = 0;
2499 	cmd->qid = ring->qid;
2500 	cmd->idx = ring->cur;
2501 
2502 	tx = (struct iwn_cmd_data *)cmd->data;
2503 	/* NB: No need to clear tx, all fields are reinitialized here. */
2504 	tx->scratch = 0;	/* clear "scratch" area */
2505 
2506 	flags = 0;
2507 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
2508 		/* Unicast frame, check if an ACK is expected. */
2509 		if (!hasqos || (qos & IEEE80211_QOS_ACK_POLICY_MASK) !=
2510 		    IEEE80211_QOS_ACK_POLICY_NOACK)
2511 			flags |= IWN_TX_NEED_ACK;
2512 	}
2513 	if ((wh->i_fc[0] &
2514 	    (IEEE80211_FC0_TYPE_MASK | IEEE80211_FC0_SUBTYPE_MASK)) ==
2515 	    (IEEE80211_FC0_TYPE_CTL | IEEE80211_FC0_SUBTYPE_BAR))
2516 		flags |= IWN_TX_IMM_BA;		/* Cannot happen yet. */
2517 
2518 	if (wh->i_fc[1] & IEEE80211_FC1_MORE_FRAG)
2519 		flags |= IWN_TX_MORE_FRAG;	/* Cannot happen yet. */
2520 
2521 	/* Check if frame must be protected using RTS/CTS or CTS-to-self. */
2522 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
2523 		/* NB: Group frames are sent using CCK in 802.11b/g. */
2524 		if (totlen + IEEE80211_CRC_LEN > ic->ic_rtsthreshold) {
2525 			flags |= IWN_TX_NEED_RTS;
2526 		} else if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
2527 		    ridx >= IWN_RIDX_OFDM6) {
2528 			if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
2529 				flags |= IWN_TX_NEED_CTS;
2530 			else if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
2531 				flags |= IWN_TX_NEED_RTS;
2532 		}
2533 		if (flags & (IWN_TX_NEED_RTS | IWN_TX_NEED_CTS)) {
2534 			if (sc->hw_type != IWN_HW_REV_TYPE_4965) {
2535 				/* 5000 autoselects RTS/CTS or CTS-to-self. */
2536 				flags &= ~(IWN_TX_NEED_RTS | IWN_TX_NEED_CTS);
2537 				flags |= IWN_TX_NEED_PROTECTION;
2538 			} else
2539 				flags |= IWN_TX_FULL_TXOP;
2540 		}
2541 	}
2542 
2543 	if (IEEE80211_IS_MULTICAST(wh->i_addr1) ||
2544 	    type != IEEE80211_FC0_TYPE_DATA)
2545 		tx->id = hal->broadcast_id;
2546 	else
2547 		tx->id = wn->id;
2548 
2549 	if (type == IEEE80211_FC0_TYPE_MGT) {
2550 		uint8_t subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
2551 
2552 #ifndef IEEE80211_STA_ONLY
2553 		/* Tell HW to set timestamp in probe responses. */
2554 		if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
2555 			flags |= IWN_TX_INSERT_TSTAMP;
2556 #endif
2557 		if (subtype == IEEE80211_FC0_SUBTYPE_ASSOC_REQ ||
2558 		    subtype == IEEE80211_FC0_SUBTYPE_REASSOC_REQ)
2559 			tx->timeout = htole16(3);
2560 		else
2561 			tx->timeout = htole16(2);
2562 	} else
2563 		tx->timeout = htole16(0);
2564 
2565 	if (hdrlen & 3) {
2566 		/* First segment's length must be a multiple of 4. */
2567 		flags |= IWN_TX_NEED_PADDING;
2568 		pad = 4 - (hdrlen & 3);
2569 	} else
2570 		pad = 0;
2571 
2572 	tx->len = htole16(totlen);
2573 	tx->tid = tid;
2574 	tx->rts_ntries = 60;
2575 	tx->data_ntries = 15;
2576 	tx->lifetime = htole32(IWN_LIFETIME_INFINITE);
2577 	tx->plcp = rinfo->plcp;
2578 	tx->rflags = rinfo->flags;
2579 	if (tx->id == hal->broadcast_id) {
2580 		/* Group or management frame. */
2581 		tx->linkq = 0;
2582 		/* XXX Alternate between antenna A and B? */
2583 		txant = IWN_LSB(sc->txantmsk);
2584 		tx->rflags |= IWN_RFLAG_ANT(txant);
2585 	} else {
2586 		tx->linkq = ni->ni_rates.rs_nrates - ni->ni_txrate - 1;
2587 		flags |= IWN_TX_LINKQ;	/* enable MRR */
2588 	}
2589 	/* Set physical address of "scratch area". */
2590 	tx->loaddr = htole32(IWN_LOADDR(data->scratch_paddr));
2591 	tx->hiaddr = IWN_HIADDR(data->scratch_paddr);
2592 
2593 	/* Copy 802.11 header in TX command. */
2594 	memcpy((uint8_t *)(tx + 1), wh, hdrlen);
2595 
2596 	if (k != NULL && k->k_cipher == IEEE80211_CIPHER_CCMP) {
2597 		/* Trim 802.11 header and prepend CCMP IV. */
2598 		m_adj(m, hdrlen - IEEE80211_CCMP_HDRLEN);
2599 		ivp = mtod(m, uint8_t *);
2600 		k->k_tsc++;
2601 		ivp[0] = k->k_tsc;
2602 		ivp[1] = k->k_tsc >> 8;
2603 		ivp[2] = 0;
2604 		ivp[3] = k->k_id << 6 | IEEE80211_WEP_EXTIV;
2605 		ivp[4] = k->k_tsc >> 16;
2606 		ivp[5] = k->k_tsc >> 24;
2607 		ivp[6] = k->k_tsc >> 32;
2608 		ivp[7] = k->k_tsc >> 40;
2609 
2610 		tx->security = IWN_CIPHER_CCMP;
2611 		/* XXX flags |= IWN_TX_AMPDU_CCMP; */
2612 		memcpy(tx->key, k->k_key, k->k_len);
2613 
2614 		/* TX scheduler includes CCMP MIC len w/5000 Series. */
2615 		if (sc->hw_type != IWN_HW_REV_TYPE_4965)
2616 			totlen += IEEE80211_CCMP_MICLEN;
2617 	} else {
2618 		/* Trim 802.11 header. */
2619 		m_adj(m, hdrlen);
2620 		tx->security = 0;
2621 	}
2622 	tx->flags = htole32(flags);
2623 
2624 	error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m,
2625 	    BUS_DMA_NOWAIT);
2626 	if (error != 0 && error != EFBIG) {
2627 		printf("%s: can't map mbuf (error %d)\n",
2628 		    sc->sc_dev.dv_xname, error);
2629 		m_freem(m);
2630 		return error;
2631 	}
2632 	if (error != 0) {
2633 		/* Too many DMA segments, linearize mbuf. */
2634 		MGETHDR(m1, M_DONTWAIT, MT_DATA);
2635 		if (m1 == NULL) {
2636 			m_freem(m);
2637 			return ENOBUFS;
2638 		}
2639 		if (m->m_pkthdr.len > MHLEN) {
2640 			MCLGET(m1, M_DONTWAIT);
2641 			if (!(m1->m_flags & M_EXT)) {
2642 				m_freem(m);
2643 				m_freem(m1);
2644 				return ENOBUFS;
2645 			}
2646 		}
2647 		m_copydata(m, 0, m->m_pkthdr.len, mtod(m1, caddr_t));
2648 		m1->m_pkthdr.len = m1->m_len = m->m_pkthdr.len;
2649 		m_freem(m);
2650 		m = m1;
2651 
2652 		error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m,
2653 		    BUS_DMA_NOWAIT);
2654 		if (error != 0) {
2655 			printf("%s: can't map mbuf (error %d)\n",
2656 			    sc->sc_dev.dv_xname, error);
2657 			m_freem(m);
2658 			return error;
2659 		}
2660 	}
2661 
2662 	data->m = m;
2663 	data->ni = ni;
2664 
2665 	DPRINTFN(4, ("sending data: qid=%d idx=%d len=%d nsegs=%d\n",
2666 	    ring->qid, ring->cur, m->m_pkthdr.len, data->map->dm_nsegs));
2667 
2668 	/* Fill TX descriptor. */
2669 	desc->nsegs = 1 + data->map->dm_nsegs;
2670 	/* First DMA segment is used by the TX command. */
2671 	desc->segs[0].addr = htole32(IWN_LOADDR(data->cmd_paddr));
2672 	desc->segs[0].len  = htole16(IWN_HIADDR(data->cmd_paddr) |
2673 	    (4 + sizeof (*tx) + hdrlen + pad) << 4);
2674 	/* Other DMA segments are for data payload. */
2675 	seg = data->map->dm_segs;
2676 	for (i = 1; i <= data->map->dm_nsegs; i++) {
2677 		desc->segs[i].addr = htole32(IWN_LOADDR(seg->ds_addr));
2678 		desc->segs[i].len  = htole16(IWN_HIADDR(seg->ds_addr) |
2679 		    seg->ds_len << 4);
2680 		seg++;
2681 	}
2682 
2683 	bus_dmamap_sync(sc->sc_dmat, data->map, 0, data->map->dm_mapsize,
2684 	    BUS_DMASYNC_PREWRITE);
2685 	bus_dmamap_sync(sc->sc_dmat, ring->cmd_dma.map,
2686 	    (caddr_t)cmd - ring->cmd_dma.vaddr, sizeof (*cmd),
2687 	    BUS_DMASYNC_PREWRITE);
2688 	bus_dmamap_sync(sc->sc_dmat, ring->desc_dma.map,
2689 	    (caddr_t)desc - ring->desc_dma.vaddr, sizeof (*desc),
2690 	    BUS_DMASYNC_PREWRITE);
2691 
2692 	/* Update TX scheduler. */
2693 	hal->update_sched(sc, ring->qid, ring->cur, tx->id, totlen);
2694 
2695 	/* Kick TX ring. */
2696 	ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT;
2697 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, ring->qid << 8 | ring->cur);
2698 
2699 	/* Mark TX ring as full if we reach a certain threshold. */
2700 	if (++ring->queued > IWN_TX_RING_HIMARK)
2701 		sc->qfullmsk |= 1 << ring->qid;
2702 
2703 	return 0;
2704 }
2705 
2706 void
2707 iwn_start(struct ifnet *ifp)
2708 {
2709 	struct iwn_softc *sc = ifp->if_softc;
2710 	struct ieee80211com *ic = &sc->sc_ic;
2711 	struct ieee80211_node *ni;
2712 	struct mbuf *m;
2713 
2714 	if ((ifp->if_flags & (IFF_RUNNING | IFF_OACTIVE)) != IFF_RUNNING)
2715 		return;
2716 
2717 	for (;;) {
2718 		if (sc->qfullmsk != 0) {
2719 			ifp->if_flags |= IFF_OACTIVE;
2720 			break;
2721 		}
2722 		/* Send pending management frames first. */
2723 		IF_DEQUEUE(&ic->ic_mgtq, m);
2724 		if (m != NULL) {
2725 			ni = (void *)m->m_pkthdr.rcvif;
2726 			goto sendit;
2727 		}
2728 		if (ic->ic_state != IEEE80211_S_RUN)
2729 			break;
2730 
2731 		/* Encapsulate and send data frames. */
2732 		IFQ_DEQUEUE(&ifp->if_snd, m);
2733 		if (m == NULL)
2734 			break;
2735 #if NBPFILTER > 0
2736 		if (ifp->if_bpf != NULL)
2737 			bpf_mtap(ifp->if_bpf, m, BPF_DIRECTION_OUT);
2738 #endif
2739 		if ((m = ieee80211_encap(ifp, m, &ni)) == NULL)
2740 			continue;
2741 sendit:
2742 #if NBPFILTER > 0
2743 		if (ic->ic_rawbpf != NULL)
2744 			bpf_mtap(ic->ic_rawbpf, m, BPF_DIRECTION_OUT);
2745 #endif
2746 		if (iwn_tx(sc, m, ni) != 0) {
2747 			ieee80211_release_node(ic, ni);
2748 			ifp->if_oerrors++;
2749 			continue;
2750 		}
2751 
2752 		sc->sc_tx_timer = 5;
2753 		ifp->if_timer = 1;
2754 	}
2755 }
2756 
2757 void
2758 iwn_watchdog(struct ifnet *ifp)
2759 {
2760 	struct iwn_softc *sc = ifp->if_softc;
2761 
2762 	ifp->if_timer = 0;
2763 
2764 	if (sc->sc_tx_timer > 0) {
2765 		if (--sc->sc_tx_timer == 0) {
2766 			printf("%s: device timeout\n", sc->sc_dev.dv_xname);
2767 			ifp->if_flags &= ~IFF_UP;
2768 			iwn_stop(ifp, 1);
2769 			ifp->if_oerrors++;
2770 			return;
2771 		}
2772 		ifp->if_timer = 1;
2773 	}
2774 
2775 	ieee80211_watchdog(ifp);
2776 }
2777 
2778 int
2779 iwn_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
2780 {
2781 	struct iwn_softc *sc = ifp->if_softc;
2782 	struct ieee80211com *ic = &sc->sc_ic;
2783 	struct ifaddr *ifa;
2784 	struct ifreq *ifr;
2785 	int s, error = 0;
2786 
2787 	s = splnet();
2788 
2789 	switch (cmd) {
2790 	case SIOCSIFADDR:
2791 		ifa = (struct ifaddr *)data;
2792 		ifp->if_flags |= IFF_UP;
2793 #ifdef INET
2794 		if (ifa->ifa_addr->sa_family == AF_INET)
2795 			arp_ifinit(&ic->ic_ac, ifa);
2796 #endif
2797 		/* FALLTHROUGH */
2798 	case SIOCSIFFLAGS:
2799 		if (ifp->if_flags & IFF_UP) {
2800 			if (!(ifp->if_flags & IFF_RUNNING))
2801 				error = iwn_init(ifp);
2802 		} else {
2803 			if (ifp->if_flags & IFF_RUNNING)
2804 				iwn_stop(ifp, 1);
2805 		}
2806 		break;
2807 
2808 	case SIOCADDMULTI:
2809 	case SIOCDELMULTI:
2810 		ifr = (struct ifreq *)data;
2811 		error = (cmd == SIOCADDMULTI) ?
2812 		    ether_addmulti(ifr, &ic->ic_ac) :
2813 		    ether_delmulti(ifr, &ic->ic_ac);
2814 
2815 		if (error == ENETRESET)
2816 			error = 0;
2817 		break;
2818 
2819 	case SIOCS80211POWER:
2820 		error = ieee80211_ioctl(ifp, cmd, data);
2821 		if (error != ENETRESET)
2822 			break;
2823 		if (ic->ic_state == IEEE80211_S_RUN &&
2824 		    sc->calib.state == IWN_CALIB_STATE_RUN) {
2825 			if (ic->ic_flags & IEEE80211_F_PMGTON)
2826 				error = iwn_set_pslevel(sc, 0, 3, 0);
2827 			else	/* back to CAM */
2828 				error = iwn_set_pslevel(sc, 0, 0, 0);
2829 		} else {
2830 			/* Defer until transition to IWN_CALIB_STATE_RUN. */
2831 			error = 0;
2832 		}
2833 		break;
2834 
2835 	default:
2836 		error = ieee80211_ioctl(ifp, cmd, data);
2837 	}
2838 
2839 	if (error == ENETRESET) {
2840 		error = 0;
2841 		if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
2842 		    (IFF_UP | IFF_RUNNING)) {
2843 			iwn_stop(ifp, 0);
2844 			error = iwn_init(ifp);
2845 		}
2846 	}
2847 	splx(s);
2848 	return error;
2849 }
2850 
2851 /*
2852  * Send a command to the firmware.
2853  */
2854 int
2855 iwn_cmd(struct iwn_softc *sc, int code, const void *buf, int size, int async)
2856 {
2857 	const struct iwn_hal *hal = sc->sc_hal;
2858 	struct iwn_tx_ring *ring = &sc->txq[4];
2859 	struct iwn_tx_desc *desc;
2860 	struct iwn_tx_data *data;
2861 	struct iwn_tx_cmd *cmd;
2862 	struct mbuf *m;
2863 	bus_addr_t paddr;
2864 	int totlen, error;
2865 
2866 	desc = &ring->desc[ring->cur];
2867 	data = &ring->data[ring->cur];
2868 	totlen = 4 + size;
2869 
2870 	if (size > sizeof cmd->data) {
2871 		/* Command is too large to fit in a descriptor. */
2872 		if (totlen > MCLBYTES)
2873 			return EINVAL;
2874 		MGETHDR(m, M_DONTWAIT, MT_DATA);
2875 		if (m == NULL)
2876 			return ENOMEM;
2877 		if (totlen > MHLEN) {
2878 			MCLGET(m, M_DONTWAIT);
2879 			if (!(m->m_flags & M_EXT)) {
2880 				m_freem(m);
2881 				return ENOMEM;
2882 			}
2883 		}
2884 		cmd = mtod(m, struct iwn_tx_cmd *);
2885 		error = bus_dmamap_load(sc->sc_dmat, data->map, cmd, totlen,
2886 		    NULL, BUS_DMA_NOWAIT);
2887 		if (error != 0) {
2888 			m_freem(m);
2889 			return error;
2890 		}
2891 		data->m = m;
2892 		paddr = data->map->dm_segs[0].ds_addr;
2893 	} else {
2894 		cmd = &ring->cmd[ring->cur];
2895 		paddr = data->cmd_paddr;
2896 	}
2897 
2898 	cmd->code = code;
2899 	cmd->flags = 0;
2900 	cmd->qid = ring->qid;
2901 	cmd->idx = ring->cur;
2902 	memcpy(cmd->data, buf, size);
2903 
2904 	desc->nsegs = 1;
2905 	desc->segs[0].addr = htole32(IWN_LOADDR(paddr));
2906 	desc->segs[0].len  = htole16(IWN_HIADDR(paddr) | totlen << 4);
2907 
2908 	if (size > sizeof cmd->data) {
2909 		bus_dmamap_sync(sc->sc_dmat, data->map, 0, totlen,
2910 		    BUS_DMASYNC_PREWRITE);
2911 	} else {
2912 		bus_dmamap_sync(sc->sc_dmat, ring->cmd_dma.map,
2913 		    (caddr_t)cmd - ring->cmd_dma.vaddr, totlen,
2914 		    BUS_DMASYNC_PREWRITE);
2915 	}
2916 	bus_dmamap_sync(sc->sc_dmat, ring->desc_dma.map,
2917 	    (caddr_t)desc - ring->desc_dma.vaddr, sizeof (*desc),
2918 	    BUS_DMASYNC_PREWRITE);
2919 
2920 	/* Update TX scheduler. */
2921 	hal->update_sched(sc, ring->qid, ring->cur, 0, 0);
2922 
2923 	/* Kick command ring. */
2924 	ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT;
2925 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, ring->qid << 8 | ring->cur);
2926 
2927 	return async ? 0 : tsleep(desc, PCATCH, "iwncmd", hz);
2928 }
2929 
2930 int
2931 iwn4965_add_node(struct iwn_softc *sc, struct iwn_node_info *node, int async)
2932 {
2933 	struct iwn4965_node_info hnode;
2934 	caddr_t src, dst;
2935 
2936 	/*
2937 	 * We use the node structure for 5000 Series internally (it is
2938 	 * a superset of the one for 4965AGN). We thus copy the common
2939 	 * fields before sending the command.
2940 	 */
2941 	src = (caddr_t)node;
2942 	dst = (caddr_t)&hnode;
2943 	memcpy(dst, src, 48);
2944 	/* Skip TSC, RX MIC and TX MIC fields from ``src''. */
2945 	memcpy(dst + 48, src + 72, 20);
2946 	return iwn_cmd(sc, IWN_CMD_ADD_NODE, &hnode, sizeof hnode, async);
2947 }
2948 
2949 int
2950 iwn5000_add_node(struct iwn_softc *sc, struct iwn_node_info *node, int async)
2951 {
2952 	/* Direct mapping. */
2953 	return iwn_cmd(sc, IWN_CMD_ADD_NODE, node, sizeof (*node), async);
2954 }
2955 
2956 int
2957 iwn_set_link_quality(struct iwn_softc *sc, struct ieee80211_node *ni)
2958 {
2959 	struct iwn_node *wn = (void *)ni;
2960 	struct ieee80211_rateset *rs = &ni->ni_rates;
2961 	struct iwn_cmd_link_quality linkq;
2962 	const struct iwn_rate *rinfo;
2963 	uint8_t txant;
2964 	int i, txrate;
2965 
2966 	/* Use the first valid TX antenna. */
2967 	txant = IWN_LSB(sc->txantmsk);
2968 
2969 	memset(&linkq, 0, sizeof linkq);
2970 	linkq.id = wn->id;
2971 	linkq.antmsk_1stream = txant;
2972 	linkq.antmsk_2stream = IWN_ANT_A | IWN_ANT_B;
2973 	linkq.ampdu_max = 64;
2974 	linkq.ampdu_threshold = 3;
2975 	linkq.ampdu_limit = htole16(4000);	/* 4ms */
2976 
2977 	/* Start at highest available bit-rate. */
2978 	txrate = rs->rs_nrates - 1;
2979 	for (i = 0; i < IWN_MAX_TX_RETRIES; i++) {
2980 		rinfo = &iwn_rates[wn->ridx[txrate]];
2981 		linkq.retry[i].plcp = rinfo->plcp;
2982 		linkq.retry[i].rflags = rinfo->flags;
2983 		linkq.retry[i].rflags |= IWN_RFLAG_ANT(txant);
2984 		/* Next retry at immediate lower bit-rate. */
2985 		if (txrate > 0)
2986 			txrate--;
2987 	}
2988 	return iwn_cmd(sc, IWN_CMD_LINK_QUALITY, &linkq, sizeof linkq, 1);
2989 }
2990 
2991 /*
2992  * Broadcast node is used to send group-addressed and management frames.
2993  */
2994 int
2995 iwn_add_broadcast_node(struct iwn_softc *sc, int async)
2996 {
2997 	const struct iwn_hal *hal = sc->sc_hal;
2998 	struct iwn_node_info node;
2999 	struct iwn_cmd_link_quality linkq;
3000 	const struct iwn_rate *rinfo;
3001 	uint8_t txant;
3002 	int i, error;
3003 
3004 	memset(&node, 0, sizeof node);
3005 	IEEE80211_ADDR_COPY(node.macaddr, etherbroadcastaddr);
3006 	node.id = hal->broadcast_id;
3007 	DPRINTF(("adding broadcast node\n"));
3008 	if ((error = hal->add_node(sc, &node, async)) != 0)
3009 		return error;
3010 
3011 	/* Use the first valid TX antenna. */
3012 	txant = IWN_LSB(sc->txantmsk);
3013 
3014 	memset(&linkq, 0, sizeof linkq);
3015 	linkq.id = hal->broadcast_id;
3016 	linkq.antmsk_1stream = txant;
3017 	linkq.antmsk_2stream = IWN_ANT_A | IWN_ANT_B;
3018 	linkq.ampdu_max = 64;
3019 	linkq.ampdu_threshold = 3;
3020 	linkq.ampdu_limit = htole16(4000);	/* 4ms */
3021 
3022 	/* Use lowest mandatory bit-rate. */
3023 	rinfo = (sc->sc_ic.ic_curmode != IEEE80211_MODE_11A) ?
3024 	    &iwn_rates[IWN_RIDX_CCK1] : &iwn_rates[IWN_RIDX_OFDM6];
3025 	linkq.retry[0].plcp = rinfo->plcp;
3026 	linkq.retry[0].rflags = rinfo->flags;
3027 	linkq.retry[0].rflags |= IWN_RFLAG_ANT(txant);
3028 	/* Use same bit-rate for all TX retries. */
3029 	for (i = 1; i < IWN_MAX_TX_RETRIES; i++) {
3030 		linkq.retry[i].plcp = linkq.retry[0].plcp;
3031 		linkq.retry[i].rflags = linkq.retry[0].rflags;
3032 	}
3033 	return iwn_cmd(sc, IWN_CMD_LINK_QUALITY, &linkq, sizeof linkq, async);
3034 }
3035 
3036 void
3037 iwn_updateedca(struct ieee80211com *ic)
3038 {
3039 #define IWN_EXP2(x)	((1 << (x)) - 1)	/* CWmin = 2^ECWmin - 1 */
3040 	struct iwn_softc *sc = ic->ic_softc;
3041 	struct iwn_edca_params cmd;
3042 	int aci;
3043 
3044 	memset(&cmd, 0, sizeof cmd);
3045 	cmd.flags = htole32(IWN_EDCA_UPDATE);
3046 	for (aci = 0; aci < EDCA_NUM_AC; aci++) {
3047 		const struct ieee80211_edca_ac_params *ac =
3048 		    &ic->ic_edca_ac[aci];
3049 		cmd.ac[aci].aifsn = ac->ac_aifsn;
3050 		cmd.ac[aci].cwmin = htole16(IWN_EXP2(ac->ac_ecwmin));
3051 		cmd.ac[aci].cwmax = htole16(IWN_EXP2(ac->ac_ecwmax));
3052 		cmd.ac[aci].txoplimit =
3053 		    htole16(IEEE80211_TXOP_TO_US(ac->ac_txoplimit));
3054 	}
3055 	(void)iwn_cmd(sc, IWN_CMD_EDCA_PARAMS, &cmd, sizeof cmd, 1);
3056 #undef IWN_EXP2
3057 }
3058 
3059 void
3060 iwn_set_led(struct iwn_softc *sc, uint8_t which, uint8_t off, uint8_t on)
3061 {
3062 	struct iwn_cmd_led led;
3063 
3064 	/* Clear microcode LED ownership. */
3065 	IWN_CLRBITS(sc, IWN_LED, IWN_LED_BSM_CTRL);
3066 
3067 	led.which = which;
3068 	led.unit = htole32(10000);	/* on/off in unit of 100ms */
3069 	led.off = off;
3070 	led.on = on;
3071 	(void)iwn_cmd(sc, IWN_CMD_SET_LED, &led, sizeof led, 1);
3072 }
3073 
3074 /*
3075  * Set the critical temperature at which the firmware will notify us.
3076  */
3077 int
3078 iwn_set_critical_temp(struct iwn_softc *sc)
3079 {
3080 	struct iwn_critical_temp crit;
3081 
3082 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_CTEMP_STOP_RF);
3083 
3084 	memset(&crit, 0, sizeof crit);
3085 	crit.tempR = htole32(sc->critical_temp);
3086 	DPRINTF(("setting critical temperature to %u\n", sc->critical_temp));
3087 	return iwn_cmd(sc, IWN_CMD_SET_CRITICAL_TEMP, &crit, sizeof crit, 0);
3088 }
3089 
3090 int
3091 iwn_set_timing(struct iwn_softc *sc, struct ieee80211_node *ni)
3092 {
3093 	struct iwn_cmd_timing cmd;
3094 	uint64_t val, mod;
3095 
3096 	memset(&cmd, 0, sizeof cmd);
3097 	memcpy(&cmd.tstamp, ni->ni_tstamp, sizeof (uint64_t));
3098 	cmd.bintval = htole16(ni->ni_intval);
3099 	cmd.lintval = htole16(10);
3100 
3101 	/* Compute remaining time until next beacon. */
3102 	val = (uint64_t)ni->ni_intval * 1024;	/* msecs -> usecs */
3103 	mod = letoh64(cmd.tstamp) % val;
3104 	cmd.binitval = htole32((uint32_t)(val - mod));
3105 
3106 	DPRINTF(("timing bintval=%u, tstamp=%llu, init=%u\n",
3107 	    ni->ni_intval, letoh64(cmd.tstamp), (uint32_t)(val - mod)));
3108 
3109 	return iwn_cmd(sc, IWN_CMD_TIMING, &cmd, sizeof cmd, 1);
3110 }
3111 
3112 void
3113 iwn4965_power_calibration(struct iwn_softc *sc, int temp)
3114 {
3115 	/* Adjust TX power if need be (delta >= 3 degC.) */
3116 	DPRINTF(("temperature %d->%d\n", sc->temp, temp));
3117 	if (abs(temp - sc->temp) >= 3) {
3118 		/* Record temperature of last calibration. */
3119 		sc->temp = temp;
3120 		(void)iwn4965_set_txpower(sc, 1);
3121 	}
3122 }
3123 
3124 /*
3125  * Set TX power for current channel (each rate has its own power settings).
3126  * This function takes into account the regulatory information from EEPROM,
3127  * the current temperature and the current voltage.
3128  */
3129 int
3130 iwn4965_set_txpower(struct iwn_softc *sc, int async)
3131 {
3132 /* Fixed-point arithmetic division using a n-bit fractional part. */
3133 #define fdivround(a, b, n)	\
3134 	((((1 << n) * (a)) / (b) + (1 << n) / 2) / (1 << n))
3135 /* Linear interpolation. */
3136 #define interpolate(x, x1, y1, x2, y2, n)	\
3137 	((y1) + fdivround(((int)(x) - (x1)) * ((y2) - (y1)), (x2) - (x1), n))
3138 
3139 	static const int tdiv[IWN_NATTEN_GROUPS] = { 9, 8, 8, 8, 6 };
3140 	struct ieee80211com *ic = &sc->sc_ic;
3141 	struct iwn_ucode_info *uc = &sc->ucode_info;
3142 	struct ieee80211_channel *ch;
3143 	struct iwn4965_cmd_txpower cmd;
3144 	struct iwn4965_eeprom_chan_samples *chans;
3145 	const uint8_t *rf_gain, *dsp_gain;
3146 	int32_t vdiff, tdiff;
3147 	int i, c, grp, maxpwr;
3148 	uint8_t chan;
3149 
3150 	/* Retrieve current channel from last RXON. */
3151 	chan = sc->rxon.chan;
3152 	DPRINTF(("setting TX power for channel %d\n", chan));
3153 	ch = &ic->ic_channels[chan];
3154 
3155 	memset(&cmd, 0, sizeof cmd);
3156 	cmd.band = IEEE80211_IS_CHAN_5GHZ(ch) ? 0 : 1;
3157 	cmd.chan = chan;
3158 
3159 	if (IEEE80211_IS_CHAN_5GHZ(ch)) {
3160 		maxpwr   = sc->maxpwr5GHz;
3161 		rf_gain  = iwn4965_rf_gain_5ghz;
3162 		dsp_gain = iwn4965_dsp_gain_5ghz;
3163 	} else {
3164 		maxpwr   = sc->maxpwr2GHz;
3165 		rf_gain  = iwn4965_rf_gain_2ghz;
3166 		dsp_gain = iwn4965_dsp_gain_2ghz;
3167 	}
3168 
3169 	/* Compute voltage compensation. */
3170 	vdiff = ((int32_t)letoh32(uc->volt) - sc->eeprom_voltage) / 7;
3171 	if (vdiff > 0)
3172 		vdiff *= 2;
3173 	if (abs(vdiff) > 2)
3174 		vdiff = 0;
3175 	DPRINTF(("voltage compensation=%d (UCODE=%d, EEPROM=%d)\n",
3176 	    vdiff, letoh32(uc->volt), sc->eeprom_voltage));
3177 
3178 	/* Get channel's attenuation group. */
3179 	if (chan <= 20)		/* 1-20 */
3180 		grp = 4;
3181 	else if (chan <= 43)	/* 34-43 */
3182 		grp = 0;
3183 	else if (chan <= 70)	/* 44-70 */
3184 		grp = 1;
3185 	else if (chan <= 124)	/* 71-124 */
3186 		grp = 2;
3187 	else			/* 125-200 */
3188 		grp = 3;
3189 	DPRINTF(("chan %d, attenuation group=%d\n", chan, grp));
3190 
3191 	/* Get channel's sub-band. */
3192 	for (i = 0; i < IWN_NBANDS; i++)
3193 		if (sc->bands[i].lo != 0 &&
3194 		    sc->bands[i].lo <= chan && chan <= sc->bands[i].hi)
3195 			break;
3196 	chans = sc->bands[i].chans;
3197 	DPRINTF(("chan %d sub-band=%d\n", chan, i));
3198 
3199 	for (c = 0; c < 2; c++) {
3200 		uint8_t power, gain, temp;
3201 		int maxchpwr, pwr, ridx, idx;
3202 
3203 		power = interpolate(chan,
3204 		    chans[0].num, chans[0].samples[c][1].power,
3205 		    chans[1].num, chans[1].samples[c][1].power, 1);
3206 		gain  = interpolate(chan,
3207 		    chans[0].num, chans[0].samples[c][1].gain,
3208 		    chans[1].num, chans[1].samples[c][1].gain, 1);
3209 		temp  = interpolate(chan,
3210 		    chans[0].num, chans[0].samples[c][1].temp,
3211 		    chans[1].num, chans[1].samples[c][1].temp, 1);
3212 		DPRINTF(("TX chain %d: power=%d gain=%d temp=%d\n",
3213 		    c, power, gain, temp));
3214 
3215 		/* Compute temperature compensation. */
3216 		tdiff = ((sc->temp - temp) * 2) / tdiv[grp];
3217 		DPRINTF(("temperature compensation=%d (current=%d, "
3218 		    "EEPROM=%d)\n", tdiff, sc->temp, temp));
3219 
3220 		for (ridx = 0; ridx <= IWN_RIDX_MAX; ridx++) {
3221 			maxchpwr = sc->maxpwr[chan] * 2;
3222 			if ((ridx / 8) & 1)
3223 				maxchpwr -= 6;	/* MIMO 2T: -3dB */
3224 
3225 			pwr = maxpwr;
3226 
3227 			/* Adjust TX power based on rate. */
3228 			if ((ridx % 8) == 5)
3229 				pwr -= 15;	/* OFDM48: -7.5dB */
3230 			else if ((ridx % 8) == 6)
3231 				pwr -= 17;	/* OFDM54: -8.5dB */
3232 			else if ((ridx % 8) == 7)
3233 				pwr -= 20;	/* OFDM60: -10dB */
3234 			else
3235 				pwr -= 10;	/* Others: -5dB */
3236 
3237 			/* Do not exceed channel's max TX power. */
3238 			if (pwr > maxchpwr)
3239 				pwr = maxchpwr;
3240 
3241 			idx = gain - (pwr - power) - tdiff - vdiff;
3242 			if ((ridx / 8) & 1)	/* MIMO */
3243 				idx += (int32_t)letoh32(uc->atten[grp][c]);
3244 
3245 			if (cmd.band == 0)
3246 				idx += 9;	/* 5GHz */
3247 			if (ridx == IWN_RIDX_MAX)
3248 				idx += 5;	/* CCK */
3249 
3250 			/* Make sure idx stays in a valid range. */
3251 			if (idx < 0)
3252 				idx = 0;
3253 			else if (idx > IWN4965_MAX_PWR_INDEX)
3254 				idx = IWN4965_MAX_PWR_INDEX;
3255 
3256 			DPRINTF(("TX chain %d, rate idx %d: power=%d\n",
3257 			    c, ridx, idx));
3258 			cmd.power[ridx].rf_gain[c] = rf_gain[idx];
3259 			cmd.power[ridx].dsp_gain[c] = dsp_gain[idx];
3260 		}
3261 	}
3262 
3263 	DPRINTF(("setting TX power for chan %d\n", chan));
3264 	return iwn_cmd(sc, IWN_CMD_TXPOWER, &cmd, sizeof cmd, async);
3265 
3266 #undef interpolate
3267 #undef fdivround
3268 }
3269 
3270 int
3271 iwn5000_set_txpower(struct iwn_softc *sc, int async)
3272 {
3273 	struct iwn5000_cmd_txpower cmd;
3274 
3275 	/*
3276 	 * TX power calibration is handled automatically by the firmware
3277 	 * for 5000 Series.
3278 	 */
3279 	memset(&cmd, 0, sizeof cmd);
3280 	cmd.global_limit = 2 * IWN5000_TXPOWER_MAX_DBM;	/* 16 dBm */
3281 	cmd.flags = IWN5000_TXPOWER_NO_CLOSED;
3282 	cmd.srv_limit = IWN5000_TXPOWER_AUTO;
3283 	DPRINTF(("setting TX power\n"));
3284 	return iwn_cmd(sc, IWN_CMD_TXPOWER_DBM, &cmd, sizeof cmd, async);
3285 }
3286 
3287 /*
3288  * Retrieve the maximum RSSI (in dBm) among receivers.
3289  */
3290 int
3291 iwn4965_get_rssi(const struct iwn_rx_stat *stat)
3292 {
3293 	struct iwn4965_rx_phystat *phy = (void *)stat->phybuf;
3294 	uint8_t mask, agc;
3295 	int rssi;
3296 
3297 	mask = (letoh16(phy->antenna) >> 4) & 0x7;
3298 	agc  = (letoh16(phy->agc) >> 7) & 0x7f;
3299 
3300 	rssi = 0;
3301 	if (mask & IWN_ANT_A)
3302 		rssi = MAX(rssi, phy->rssi[0]);
3303 	if (mask & IWN_ANT_B)
3304 		rssi = MAX(rssi, phy->rssi[2]);
3305 	if (mask & IWN_ANT_C)
3306 		rssi = MAX(rssi, phy->rssi[4]);
3307 
3308 	return rssi - agc - IWN_RSSI_TO_DBM;
3309 }
3310 
3311 int
3312 iwn5000_get_rssi(const struct iwn_rx_stat *stat)
3313 {
3314 	struct iwn5000_rx_phystat *phy = (void *)stat->phybuf;
3315 	uint8_t agc;
3316 	int rssi;
3317 
3318 	agc = (letoh32(phy->agc) >> 9) & 0x7f;
3319 
3320 	rssi = MAX(letoh16(phy->rssi[0]) & 0xff,
3321 		   letoh16(phy->rssi[1]) & 0xff);
3322 	rssi = MAX(letoh16(phy->rssi[2]) & 0xff, rssi);
3323 
3324 	return rssi - agc - IWN_RSSI_TO_DBM;
3325 }
3326 
3327 /*
3328  * Retrieve the average noise (in dBm) among receivers.
3329  */
3330 int
3331 iwn_get_noise(const struct iwn_rx_general_stats *stats)
3332 {
3333 	int i, total, nbant, noise;
3334 
3335 	total = nbant = 0;
3336 	for (i = 0; i < 3; i++) {
3337 		if ((noise = letoh32(stats->noise[i]) & 0xff) == 0)
3338 			continue;
3339 		total += noise;
3340 		nbant++;
3341 	}
3342 	/* There should be at least one antenna but check anyway. */
3343 	return (nbant == 0) ? -127 : (total / nbant) - 107;
3344 }
3345 
3346 /*
3347  * Compute temperature (in degC) from last received statistics.
3348  */
3349 int
3350 iwn4965_get_temperature(struct iwn_softc *sc)
3351 {
3352 	struct iwn_ucode_info *uc = &sc->ucode_info;
3353 	int32_t r1, r2, r3, r4, temp;
3354 
3355 	r1 = letoh32(uc->temp[0].chan20MHz);
3356 	r2 = letoh32(uc->temp[1].chan20MHz);
3357 	r3 = letoh32(uc->temp[2].chan20MHz);
3358 	r4 = letoh32(sc->rawtemp);
3359 
3360 	if (r1 == r3)	/* Prevents division by 0 (should not happen.) */
3361 		return 0;
3362 
3363 	/* Sign-extend 23-bit R4 value to 32-bit. */
3364 	r4 = (r4 << 8) >> 8;
3365 	/* Compute temperature in Kelvin. */
3366 	temp = (259 * (r4 - r2)) / (r3 - r1);
3367 	temp = (temp * 97) / 100 + 8;
3368 
3369 	DPRINTF(("temperature %dK/%dC\n", temp, IWN_KTOC(temp)));
3370 	return IWN_KTOC(temp);
3371 }
3372 
3373 int
3374 iwn5000_get_temperature(struct iwn_softc *sc)
3375 {
3376 	/*
3377 	 * Temperature is not used by the driver for 5000 Series because
3378 	 * TX power calibration is handled by firmware.  We export it to
3379 	 * users through the sensor framework though.
3380 	 */
3381 	return letoh32(sc->rawtemp);
3382 }
3383 
3384 /*
3385  * Initialize sensitivity calibration state machine.
3386  */
3387 int
3388 iwn_init_sensitivity(struct iwn_softc *sc)
3389 {
3390 	const struct iwn_hal *hal = sc->sc_hal;
3391 	struct iwn_calib_state *calib = &sc->calib;
3392 	uint32_t flags;
3393 	int error;
3394 
3395 	/* Reset calibration state machine. */
3396 	memset(calib, 0, sizeof (*calib));
3397 	calib->state = IWN_CALIB_STATE_INIT;
3398 	calib->cck_state = IWN_CCK_STATE_HIFA;
3399 	/* Set initial correlation values. */
3400 	calib->ofdm_x1     = hal->limits->min_ofdm_x1;
3401 	calib->ofdm_mrc_x1 = hal->limits->min_ofdm_mrc_x1;
3402 	calib->ofdm_x4     = 90;
3403 	calib->ofdm_mrc_x4 = hal->limits->min_ofdm_mrc_x4;
3404 	calib->cck_x4      = 125;
3405 	calib->cck_mrc_x4  = hal->limits->min_cck_mrc_x4;
3406 	calib->energy_cck  = hal->limits->energy_cck;
3407 
3408 	/* Write initial sensitivity. */
3409 	if ((error = iwn_send_sensitivity(sc)) != 0)
3410 		return error;
3411 
3412 	/* Write initial gains. */
3413 	if ((error = hal->init_gains(sc)) != 0)
3414 		return error;
3415 
3416 	/* Request statistics at each beacon interval. */
3417 	flags = 0;
3418 	DPRINTF(("sending request for statistics\n"));
3419 	return iwn_cmd(sc, IWN_CMD_GET_STATISTICS, &flags, sizeof flags, 1);
3420 }
3421 
3422 /*
3423  * Collect noise and RSSI statistics for the first 20 beacons received
3424  * after association and use them to determine connected antennas and
3425  * to set differential gains.
3426  */
3427 void
3428 iwn_collect_noise(struct iwn_softc *sc,
3429     const struct iwn_rx_general_stats *stats)
3430 {
3431 	const struct iwn_hal *hal = sc->sc_hal;
3432 	struct iwn_calib_state *calib = &sc->calib;
3433 	uint32_t val;
3434 	int i;
3435 
3436 	/* Accumulate RSSI and noise for all 3 antennas. */
3437 	for (i = 0; i < 3; i++) {
3438 		calib->rssi[i] += letoh32(stats->rssi[i]) & 0xff;
3439 		calib->noise[i] += letoh32(stats->noise[i]) & 0xff;
3440 	}
3441 	/* NB: We update differential gains only once after 20 beacons. */
3442 	if (++calib->nbeacons < 20)
3443 		return;
3444 
3445 	/* Determine highest average RSSI. */
3446 	val = MAX(calib->rssi[0], calib->rssi[1]);
3447 	val = MAX(calib->rssi[2], val);
3448 
3449 	/* Determine which antennas are connected. */
3450 	sc->antmsk = 0;
3451 	for (i = 0; i < 3; i++)
3452 		if (val - calib->rssi[i] <= 15 * 20)
3453 			sc->antmsk |= 1 << i;
3454 	/* If none of the TX antennas are connected, keep at least one. */
3455 	if ((sc->antmsk & sc->txantmsk) == 0)
3456 		sc->antmsk |= IWN_LSB(sc->txantmsk);
3457 
3458 	(void)hal->set_gains(sc);
3459 	calib->state = IWN_CALIB_STATE_RUN;
3460 
3461 #ifdef notyet
3462 	/* XXX Disable RX chains with no antennas connected. */
3463 	sc->rxon.rxchain = htole16(IWN_RXCHAIN_SEL(sc->antmsk));
3464 	(void)iwn_cmd(sc, IWN_CMD_CONFIGURE, &sc->rxon, hal->rxonsz, 1);
3465 #endif
3466 
3467 	/* Enable power-saving mode if requested by user. */
3468 	if (sc->sc_ic.ic_flags & IEEE80211_F_PMGTON)
3469 		(void)iwn_set_pslevel(sc, 0, 3, 1);
3470 }
3471 
3472 int
3473 iwn4965_init_gains(struct iwn_softc *sc)
3474 {
3475 	struct iwn_phy_calib_gain cmd;
3476 
3477 	memset(&cmd, 0, sizeof cmd);
3478 	cmd.code = IWN4965_PHY_CALIB_DIFF_GAIN;
3479 	/* Differential gains initially set to 0 for all 3 antennas. */
3480 	DPRINTF(("setting initial differential gains\n"));
3481 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
3482 }
3483 
3484 int
3485 iwn5000_init_gains(struct iwn_softc *sc)
3486 {
3487 	struct iwn_phy_calib cmd;
3488 
3489 	if (sc->hw_type == IWN_HW_REV_TYPE_6000 ||
3490 	    sc->hw_type == IWN_HW_REV_TYPE_6050)
3491 		return 0;
3492 
3493 	memset(&cmd, 0, sizeof cmd);
3494 	cmd.code = IWN5000_PHY_CALIB_RESET_NOISE_GAIN;
3495 	cmd.ngroups = 1;
3496 	cmd.isvalid = 1;
3497 	DPRINTF(("setting initial differential gains\n"));
3498 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
3499 }
3500 
3501 int
3502 iwn4965_set_gains(struct iwn_softc *sc)
3503 {
3504 	struct iwn_calib_state *calib = &sc->calib;
3505 	struct iwn_phy_calib_gain cmd;
3506 	int i, delta, noise;
3507 
3508 	/* Get minimal noise among connected antennas. */
3509 	noise = INT_MAX;	/* NB: There's at least one antenna. */
3510 	for (i = 0; i < 3; i++)
3511 		if (sc->antmsk & (1 << i))
3512 			noise = MIN(calib->noise[i], noise);
3513 
3514 	memset(&cmd, 0, sizeof cmd);
3515 	cmd.code = IWN4965_PHY_CALIB_DIFF_GAIN;
3516 	/* Set differential gains for connected antennas. */
3517 	for (i = 0; i < 3; i++) {
3518 		if (sc->antmsk & (1 << i)) {
3519 			/* Compute attenuation (in unit of 1.5dB). */
3520 			delta = (noise - (int32_t)calib->noise[i]) / 30;
3521 			/* NB: delta <= 0 */
3522 			/* Limit to [-4.5dB,0]. */
3523 			cmd.gain[i] = MIN(abs(delta), 3);
3524 			if (delta < 0)
3525 				cmd.gain[i] |= 1 << 2;	/* sign bit */
3526 		}
3527 	}
3528 	DPRINTF(("setting differential gains Ant A/B/C: %x/%x/%x (%x)\n",
3529 	    cmd.gain[0], cmd.gain[1], cmd.gain[2], sc->antmsk));
3530 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
3531 }
3532 
3533 int
3534 iwn5000_set_gains(struct iwn_softc *sc)
3535 {
3536 	struct iwn_calib_state *calib = &sc->calib;
3537 	struct iwn_phy_calib_gain cmd;
3538 	int i, delta;
3539 
3540 	if (sc->hw_type == IWN_HW_REV_TYPE_6000 ||
3541 	    sc->hw_type == IWN_HW_REV_TYPE_6050)
3542 		return 0;
3543 
3544 	memset(&cmd, 0, sizeof cmd);
3545 	cmd.code = IWN5000_PHY_CALIB_NOISE_GAIN;
3546 	cmd.ngroups = 1;
3547 	cmd.isvalid = 1;
3548 	/* Set differential gains for antennas B and C. */
3549 	for (i = 1; i < 3; i++) {
3550 		if (sc->antmsk & (1 << i)) {
3551 			/* The delta is relative to antenna A. */
3552 			delta = ((int32_t)calib->noise[0] -
3553 			    (int32_t)calib->noise[i]) / 30;
3554 			/* Limit to [-4.5dB,+4.5dB]. */
3555 			cmd.gain[i - 1] = MIN(abs(delta), 3);
3556 			if (delta < 0)
3557 				cmd.gain[i - 1] |= 1 << 2;	/* sign bit */
3558 		}
3559 	}
3560 	DPRINTF(("setting differential gains Ant B/C: %x/%x (%x)\n",
3561 	    cmd.gain[0], cmd.gain[1], sc->antmsk));
3562 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
3563 }
3564 
3565 /*
3566  * Tune RF RX sensitivity based on the number of false alarms detected
3567  * during the last beacon period.
3568  */
3569 void
3570 iwn_tune_sensitivity(struct iwn_softc *sc, const struct iwn_rx_stats *stats)
3571 {
3572 #define inc(val, inc, max)			\
3573 	if ((val) < (max)) {			\
3574 		if ((val) < (max) - (inc))	\
3575 			(val) += (inc);		\
3576 		else				\
3577 			(val) = (max);		\
3578 		needs_update = 1;		\
3579 	}
3580 #define dec(val, dec, min)			\
3581 	if ((val) > (min)) {			\
3582 		if ((val) > (min) + (dec))	\
3583 			(val) -= (dec);		\
3584 		else				\
3585 			(val) = (min);		\
3586 		needs_update = 1;		\
3587 	}
3588 
3589 	const struct iwn_hal *hal = sc->sc_hal;
3590 	const struct iwn_sensitivity_limits *limits = hal->limits;
3591 	struct iwn_calib_state *calib = &sc->calib;
3592 	uint32_t val, rxena, fa;
3593 	uint32_t energy[3], energy_min;
3594 	uint8_t noise[3], noise_ref;
3595 	int i, needs_update = 0;
3596 
3597 	/* Check that we've been enabled long enough. */
3598 	if ((rxena = letoh32(stats->general.load)) == 0)
3599 		return;
3600 
3601 	/* Compute number of false alarms since last call for OFDM. */
3602 	fa  = letoh32(stats->ofdm.bad_plcp) - calib->bad_plcp_ofdm;
3603 	fa += letoh32(stats->ofdm.fa) - calib->fa_ofdm;
3604 	fa *= 200 * 1024;	/* 200TU */
3605 
3606 	/* Save counters values for next call. */
3607 	calib->bad_plcp_ofdm = letoh32(stats->ofdm.bad_plcp);
3608 	calib->fa_ofdm = letoh32(stats->ofdm.fa);
3609 
3610 	if (fa > 50 * rxena) {
3611 		/* High false alarm count, decrease sensitivity. */
3612 		DPRINTFN(2, ("OFDM high false alarm count: %u\n", fa));
3613 		inc(calib->ofdm_x1,     1, limits->max_ofdm_x1);
3614 		inc(calib->ofdm_mrc_x1, 1, limits->max_ofdm_mrc_x1);
3615 		inc(calib->ofdm_x4,     1, limits->max_ofdm_x4);
3616 		inc(calib->ofdm_mrc_x4, 1, limits->max_ofdm_mrc_x4);
3617 
3618 	} else if (fa < 5 * rxena) {
3619 		/* Low false alarm count, increase sensitivity. */
3620 		DPRINTFN(2, ("OFDM low false alarm count: %u\n", fa));
3621 		dec(calib->ofdm_x1,     1, limits->min_ofdm_x1);
3622 		dec(calib->ofdm_mrc_x1, 1, limits->min_ofdm_mrc_x1);
3623 		dec(calib->ofdm_x4,     1, limits->min_ofdm_x4);
3624 		dec(calib->ofdm_mrc_x4, 1, limits->min_ofdm_mrc_x4);
3625 	}
3626 
3627 	/* Compute maximum noise among 3 receivers. */
3628 	for (i = 0; i < 3; i++)
3629 		noise[i] = (letoh32(stats->general.noise[i]) >> 8) & 0xff;
3630 	val = MAX(noise[0], noise[1]);
3631 	val = MAX(noise[2], val);
3632 	/* Insert it into our samples table. */
3633 	calib->noise_samples[calib->cur_noise_sample] = val;
3634 	calib->cur_noise_sample = (calib->cur_noise_sample + 1) % 20;
3635 
3636 	/* Compute maximum noise among last 20 samples. */
3637 	noise_ref = calib->noise_samples[0];
3638 	for (i = 1; i < 20; i++)
3639 		noise_ref = MAX(noise_ref, calib->noise_samples[i]);
3640 
3641 	/* Compute maximum energy among 3 receivers. */
3642 	for (i = 0; i < 3; i++)
3643 		energy[i] = letoh32(stats->general.energy[i]);
3644 	val = MIN(energy[0], energy[1]);
3645 	val = MIN(energy[2], val);
3646 	/* Insert it into our samples table. */
3647 	calib->energy_samples[calib->cur_energy_sample] = val;
3648 	calib->cur_energy_sample = (calib->cur_energy_sample + 1) % 10;
3649 
3650 	/* Compute minimum energy among last 10 samples. */
3651 	energy_min = calib->energy_samples[0];
3652 	for (i = 1; i < 10; i++)
3653 		energy_min = MAX(energy_min, calib->energy_samples[i]);
3654 	energy_min += 6;
3655 
3656 	/* Compute number of false alarms since last call for CCK. */
3657 	fa  = letoh32(stats->cck.bad_plcp) - calib->bad_plcp_cck;
3658 	fa += letoh32(stats->cck.fa) - calib->fa_cck;
3659 	fa *= 200 * 1024;	/* 200TU */
3660 
3661 	/* Save counters values for next call. */
3662 	calib->bad_plcp_cck = letoh32(stats->cck.bad_plcp);
3663 	calib->fa_cck = letoh32(stats->cck.fa);
3664 
3665 	if (fa > 50 * rxena) {
3666 		/* High false alarm count, decrease sensitivity. */
3667 		DPRINTFN(2, ("CCK high false alarm count: %u\n", fa));
3668 		calib->cck_state = IWN_CCK_STATE_HIFA;
3669 		calib->low_fa = 0;
3670 
3671 		if (calib->cck_x4 > 160) {
3672 			calib->noise_ref = noise_ref;
3673 			if (calib->energy_cck > 2)
3674 				dec(calib->energy_cck, 2, energy_min);
3675 		}
3676 		if (calib->cck_x4 < 160) {
3677 			calib->cck_x4 = 161;
3678 			needs_update = 1;
3679 		} else
3680 			inc(calib->cck_x4, 3, limits->max_cck_x4);
3681 
3682 		inc(calib->cck_mrc_x4, 3, limits->max_cck_mrc_x4);
3683 
3684 	} else if (fa < 5 * rxena) {
3685 		/* Low false alarm count, increase sensitivity. */
3686 		DPRINTFN(2, ("CCK low false alarm count: %u\n", fa));
3687 		calib->cck_state = IWN_CCK_STATE_LOFA;
3688 		calib->low_fa++;
3689 
3690 		if (calib->cck_state != IWN_CCK_STATE_INIT &&
3691 		    (((int32_t)calib->noise_ref - (int32_t)noise_ref) > 2 ||
3692 		     calib->low_fa > 100)) {
3693 			inc(calib->energy_cck, 2, limits->min_energy_cck);
3694 			dec(calib->cck_x4,     3, limits->min_cck_x4);
3695 			dec(calib->cck_mrc_x4, 3, limits->min_cck_mrc_x4);
3696 		}
3697 	} else {
3698 		/* Not worth to increase or decrease sensitivity. */
3699 		DPRINTFN(2, ("CCK normal false alarm count: %u\n", fa));
3700 		calib->low_fa = 0;
3701 		calib->noise_ref = noise_ref;
3702 
3703 		if (calib->cck_state == IWN_CCK_STATE_HIFA) {
3704 			/* Previous interval had many false alarms. */
3705 			dec(calib->energy_cck, 8, energy_min);
3706 		}
3707 		calib->cck_state = IWN_CCK_STATE_INIT;
3708 	}
3709 
3710 	if (needs_update)
3711 		(void)iwn_send_sensitivity(sc);
3712 #undef dec
3713 #undef inc
3714 }
3715 
3716 int
3717 iwn_send_sensitivity(struct iwn_softc *sc)
3718 {
3719 	const struct iwn_hal *hal = sc->sc_hal;
3720 	struct iwn_calib_state *calib = &sc->calib;
3721 	struct iwn_sensitivity_cmd cmd;
3722 
3723 	memset(&cmd, 0, sizeof cmd);
3724 	cmd.which = IWN_SENSITIVITY_WORKTBL;
3725 	/* OFDM modulation. */
3726 	cmd.corr_ofdm_x1     = htole16(calib->ofdm_x1);
3727 	cmd.corr_ofdm_mrc_x1 = htole16(calib->ofdm_mrc_x1);
3728 	cmd.corr_ofdm_x4     = htole16(calib->ofdm_x4);
3729 	cmd.corr_ofdm_mrc_x4 = htole16(calib->ofdm_mrc_x4);
3730 	cmd.energy_ofdm      = htole16(hal->limits->energy_ofdm);
3731 	cmd.energy_ofdm_th   = htole16(62);
3732 	/* CCK modulation. */
3733 	cmd.corr_cck_x4      = htole16(calib->cck_x4);
3734 	cmd.corr_cck_mrc_x4  = htole16(calib->cck_mrc_x4);
3735 	cmd.energy_cck       = htole16(calib->energy_cck);
3736 	/* Barker modulation: use default values. */
3737 	cmd.corr_barker      = htole16(190);
3738 	cmd.corr_barker_mrc  = htole16(390);
3739 
3740 	DPRINTFN(2, ("setting sensitivity %d/%d/%d/%d/%d/%d/%d\n",
3741 	    calib->ofdm_x1, calib->ofdm_mrc_x1, calib->ofdm_x4,
3742 	    calib->ofdm_mrc_x4, calib->cck_x4, calib->cck_mrc_x4,
3743 	    calib->energy_cck));
3744 	return iwn_cmd(sc, IWN_CMD_SET_SENSITIVITY, &cmd, sizeof cmd, 1);
3745 }
3746 
3747 /*
3748  * Set STA mode power saving level (between 0 and 5).
3749  * Level 0 is CAM (Continuously Aware Mode), 5 is for maximum power saving.
3750  */
3751 int
3752 iwn_set_pslevel(struct iwn_softc *sc, int dtim, int level, int async)
3753 {
3754 	struct iwn_pmgt_cmd cmd;
3755 	const struct iwn_pmgt *pmgt;
3756 	uint32_t max, skip_dtim;
3757 	pcireg_t reg;
3758 	int i;
3759 
3760 	/* Select which PS parameters to use. */
3761 	if (dtim <= 2)
3762 		pmgt = &iwn_pmgt[0][level];
3763 	else if (dtim <= 10)
3764 		pmgt = &iwn_pmgt[1][level];
3765 	else
3766 		pmgt = &iwn_pmgt[2][level];
3767 
3768 	memset(&cmd, 0, sizeof cmd);
3769 	if (level != 0)	/* not CAM */
3770 		cmd.flags |= htole16(IWN_PS_ALLOW_SLEEP);
3771 	if (level == 5)
3772 		cmd.flags |= htole16(IWN_PS_FAST_PD);
3773 	/* Retrieve PCIe Active State Power Management (ASPM). */
3774 	reg = pci_conf_read(sc->sc_pct, sc->sc_pcitag,
3775 	    sc->sc_cap_off + PCI_PCIE_LCSR);
3776 	if (!(reg & PCI_PCIE_LCSR_ASPM_L0S))	/* L0s Entry disabled. */
3777 		cmd.flags |= htole16(IWN_PS_PCI_PMGT);
3778 	cmd.rxtimeout = htole32(pmgt->rxtimeout * 1024);
3779 	cmd.txtimeout = htole32(pmgt->txtimeout * 1024);
3780 
3781 	if (dtim == 0) {
3782 		dtim = 1;
3783 		skip_dtim = 0;
3784 	} else
3785 		skip_dtim = pmgt->skip_dtim;
3786 	if (skip_dtim != 0) {
3787 		cmd.flags |= htole16(IWN_PS_SLEEP_OVER_DTIM);
3788 		max = pmgt->intval[4];
3789 		if (max == (uint32_t)-1)
3790 			max = dtim * (skip_dtim + 1);
3791 		else if (max > dtim)
3792 			max = (max / dtim) * dtim;
3793 	} else
3794 		max = dtim;
3795 	for (i = 0; i < 5; i++)
3796 		cmd.intval[i] = htole32(MIN(max, pmgt->intval[i]));
3797 
3798 	DPRINTF(("setting power saving level to %d\n", level));
3799 	return iwn_cmd(sc, IWN_CMD_SET_POWER_MODE, &cmd, sizeof cmd, async);
3800 }
3801 
3802 int
3803 iwn_config(struct iwn_softc *sc)
3804 {
3805 	const struct iwn_hal *hal = sc->sc_hal;
3806 	struct ieee80211com *ic = &sc->sc_ic;
3807 	struct ifnet *ifp = &ic->ic_if;
3808 	struct iwn_bluetooth bluetooth;
3809 	uint16_t rxchain;
3810 	int error;
3811 
3812 	/* Set power saving level to CAM during initialization. */
3813 	if ((error = iwn_set_pslevel(sc, 0, 0, 0)) != 0) {
3814 		printf("%s: could not set power saving level\n",
3815 		    sc->sc_dev.dv_xname);
3816 		return error;
3817 	}
3818 
3819 	/* Configure bluetooth coexistence. */
3820 	memset(&bluetooth, 0, sizeof bluetooth);
3821 	bluetooth.flags = 3;
3822 	bluetooth.lead = 0xaa;
3823 	bluetooth.kill = 1;
3824 	DPRINTF(("configuring bluetooth coexistence\n"));
3825 	error = iwn_cmd(sc, IWN_CMD_BT_COEX, &bluetooth, sizeof bluetooth, 0);
3826 	if (error != 0) {
3827 		printf("%s: could not configure bluetooth coexistence\n",
3828 		    sc->sc_dev.dv_xname);
3829 		return error;
3830 	}
3831 
3832 	/* Configure adapter. */
3833 	memset(&sc->rxon, 0, sizeof (struct iwn_rxon));
3834 	IEEE80211_ADDR_COPY(ic->ic_myaddr, LLADDR(ifp->if_sadl));
3835 	IEEE80211_ADDR_COPY(sc->rxon.myaddr, ic->ic_myaddr);
3836 	IEEE80211_ADDR_COPY(sc->rxon.wlap, ic->ic_myaddr);
3837 	/* Set default channel. */
3838 	sc->rxon.chan = ieee80211_chan2ieee(ic, ic->ic_ibss_chan);
3839 	sc->rxon.flags = htole32(IWN_RXON_TSF | IWN_RXON_CTS_TO_SELF);
3840 	if (IEEE80211_IS_CHAN_2GHZ(ic->ic_ibss_chan))
3841 		sc->rxon.flags |= htole32(IWN_RXON_AUTO | IWN_RXON_24GHZ);
3842 	switch (ic->ic_opmode) {
3843 	case IEEE80211_M_STA:
3844 		sc->rxon.mode = IWN_MODE_STA;
3845 		sc->rxon.filter = htole32(IWN_FILTER_MULTICAST);
3846 		break;
3847 	case IEEE80211_M_MONITOR:
3848 		sc->rxon.mode = IWN_MODE_MONITOR;
3849 		sc->rxon.filter = htole32(IWN_FILTER_MULTICAST |
3850 		    IWN_FILTER_CTL | IWN_FILTER_PROMISC);
3851 		break;
3852 	default:
3853 		/* Should not get there. */
3854 		break;
3855 	}
3856 	sc->rxon.cck_mask  = 0x0f;	/* not yet negotiated */
3857 	sc->rxon.ofdm_mask = 0xff;	/* not yet negotiated */
3858 	sc->rxon.ht_single_mask = 0xff;
3859 	sc->rxon.ht_dual_mask = 0xff;
3860 	rxchain = IWN_RXCHAIN_VALID(IWN_ANT_ABC) | IWN_RXCHAIN_IDLE_COUNT(2) |
3861 	    IWN_RXCHAIN_MIMO_COUNT(2);
3862 	sc->rxon.rxchain = htole16(rxchain);
3863 	DPRINTF(("setting configuration\n"));
3864 	error = iwn_cmd(sc, IWN_CMD_CONFIGURE, &sc->rxon, hal->rxonsz, 0);
3865 	if (error != 0) {
3866 		printf("%s: configure command failed\n", sc->sc_dev.dv_xname);
3867 		return error;
3868 	}
3869 
3870 	/* Configuration has changed, set TX power accordingly. */
3871 	if ((error = hal->set_txpower(sc, 0)) != 0) {
3872 		printf("%s: could not set TX power\n", sc->sc_dev.dv_xname);
3873 		return error;
3874 	}
3875 
3876 	if ((error = iwn_add_broadcast_node(sc, 0)) != 0) {
3877 		printf("%s: could not add broadcast node\n",
3878 		    sc->sc_dev.dv_xname);
3879 		return error;
3880 	}
3881 
3882 	if ((error = iwn_set_critical_temp(sc)) != 0) {
3883 		printf("%s: could not set critical temperature\n",
3884 		    sc->sc_dev.dv_xname);
3885 		return error;
3886 	}
3887 	return 0;
3888 }
3889 
3890 int
3891 iwn_scan(struct iwn_softc *sc, uint16_t flags)
3892 {
3893 	struct ieee80211com *ic = &sc->sc_ic;
3894 	struct iwn_scan_hdr *hdr;
3895 	struct iwn_cmd_data *tx;
3896 	struct iwn_scan_essid *essid;
3897 	struct iwn_scan_chan *chan;
3898 	struct ieee80211_frame *wh;
3899 	struct ieee80211_rateset *rs;
3900 	struct ieee80211_channel *c;
3901 	uint8_t *buf, *frm;
3902 	uint16_t rxchain;
3903 	uint8_t txant;
3904 	int buflen, error;
3905 
3906 	buf = malloc(IWN_SCAN_MAXSZ, M_DEVBUF, M_NOWAIT | M_ZERO);
3907 	if (buf == NULL) {
3908 		printf("%s: could not allocate buffer for scan command\n",
3909 		    sc->sc_dev.dv_xname);
3910 		return ENOMEM;
3911 	}
3912 	hdr = (struct iwn_scan_hdr *)buf;
3913 	/*
3914 	 * Move to the next channel if no frames are received within 10ms
3915 	 * after sending the probe request.
3916 	 */
3917 	hdr->quiet_time = htole16(10);		/* timeout in milliseconds */
3918 	hdr->quiet_threshold = htole16(1);	/* min # of packets */
3919 
3920 	/* Select antennas for scanning. */
3921 	rxchain = IWN_RXCHAIN_FORCE | IWN_RXCHAIN_VALID(IWN_ANT_ABC) |
3922 	    IWN_RXCHAIN_MIMO(IWN_ANT_ABC);
3923 	if ((flags & IEEE80211_CHAN_5GHZ) &&
3924 	    sc->hw_type == IWN_HW_REV_TYPE_4965) {
3925 		/* Ant A must be avoided in 5GHz because of an HW bug. */
3926 		rxchain |= IWN_RXCHAIN_SEL(IWN_ANT_B | IWN_ANT_C);
3927 	} else	/* Use all available RX antennas. */
3928 		rxchain |= IWN_RXCHAIN_SEL(IWN_ANT_ABC);
3929 	hdr->rxchain = htole16(rxchain);
3930 	hdr->filter = htole32(IWN_FILTER_MULTICAST | IWN_FILTER_BEACON);
3931 
3932 	tx = (struct iwn_cmd_data *)(hdr + 1);
3933 	tx->flags = htole32(IWN_TX_AUTO_SEQ);
3934 	tx->id = sc->sc_hal->broadcast_id;
3935 	tx->lifetime = htole32(IWN_LIFETIME_INFINITE);
3936 
3937 	if (flags & IEEE80211_CHAN_5GHZ) {
3938 		hdr->crc_threshold = htole16(1);
3939 		/* Send probe requests at 6Mbps. */
3940 		tx->plcp = iwn_rates[IWN_RIDX_OFDM6].plcp;
3941 		rs = &ic->ic_sup_rates[IEEE80211_MODE_11A];
3942 	} else {
3943 		hdr->flags = htole32(IWN_RXON_24GHZ | IWN_RXON_AUTO);
3944 		/* Send probe requests at 1Mbps. */
3945 		tx->plcp = iwn_rates[IWN_RIDX_CCK1].plcp;
3946 		tx->rflags = IWN_RFLAG_CCK;
3947 		rs = &ic->ic_sup_rates[IEEE80211_MODE_11G];
3948 	}
3949 	/* Use the first valid TX antenna. */
3950 	txant = IWN_LSB(sc->txantmsk);
3951 	tx->rflags |= IWN_RFLAG_ANT(txant);
3952 
3953 	essid = (struct iwn_scan_essid *)(tx + 1);
3954 	if (ic->ic_des_esslen != 0) {
3955 		essid[0].id = IEEE80211_ELEMID_SSID;
3956 		essid[0].len = ic->ic_des_esslen;
3957 		memcpy(essid[0].data, ic->ic_des_essid, ic->ic_des_esslen);
3958 	}
3959 	/*
3960 	 * Build a probe request frame.  Most of the following code is a
3961 	 * copy & paste of what is done in net80211.
3962 	 */
3963 	wh = (struct ieee80211_frame *)(essid + 20);
3964 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
3965 	    IEEE80211_FC0_SUBTYPE_PROBE_REQ;
3966 	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
3967 	IEEE80211_ADDR_COPY(wh->i_addr1, etherbroadcastaddr);
3968 	IEEE80211_ADDR_COPY(wh->i_addr2, ic->ic_myaddr);
3969 	IEEE80211_ADDR_COPY(wh->i_addr3, etherbroadcastaddr);
3970 	*(uint16_t *)&wh->i_dur[0] = 0;	/* filled by HW */
3971 	*(uint16_t *)&wh->i_seq[0] = 0;	/* filled by HW */
3972 
3973 	frm = (uint8_t *)(wh + 1);
3974 	frm = ieee80211_add_ssid(frm, NULL, 0);
3975 	frm = ieee80211_add_rates(frm, rs);
3976 	if (rs->rs_nrates > IEEE80211_RATE_SIZE)
3977 		frm = ieee80211_add_xrates(frm, rs);
3978 
3979 	/* Set length of probe request. */
3980 	tx->len = htole16(frm - (uint8_t *)wh);
3981 
3982 	chan = (struct iwn_scan_chan *)frm;
3983 	for (c  = &ic->ic_channels[1];
3984 	     c <= &ic->ic_channels[IEEE80211_CHAN_MAX]; c++) {
3985 		if ((c->ic_flags & flags) != flags)
3986 			continue;
3987 
3988 		chan->chan = htole16(ieee80211_chan2ieee(ic, c));
3989 		DPRINTFN(2, ("adding channel %d\n", chan->chan));
3990 		chan->flags = 0;
3991 		if (!(c->ic_flags & IEEE80211_CHAN_PASSIVE))
3992 			chan->flags |= htole32(IWN_CHAN_ACTIVE);
3993 		if (ic->ic_des_esslen != 0)
3994 			chan->flags |= htole32(IWN_CHAN_NPBREQS(1));
3995 		chan->dsp_gain = 0x6e;
3996 		if (IEEE80211_IS_CHAN_5GHZ(c)) {
3997 			chan->rf_gain = 0x3b;
3998 			chan->active  = htole16(24);
3999 			chan->passive = htole16(110);
4000 		} else {
4001 			chan->rf_gain = 0x28;
4002 			chan->active  = htole16(36);
4003 			chan->passive = htole16(120);
4004 		}
4005 		hdr->nchan++;
4006 		chan++;
4007 	}
4008 
4009 	buflen = (uint8_t *)chan - buf;
4010 	hdr->len = htole16(buflen);
4011 
4012 	DPRINTF(("sending scan command nchan=%d\n", hdr->nchan));
4013 	error = iwn_cmd(sc, IWN_CMD_SCAN, buf, buflen, 1);
4014 	free(buf, M_DEVBUF);
4015 	return error;
4016 }
4017 
4018 int
4019 iwn_auth(struct iwn_softc *sc)
4020 {
4021 	const struct iwn_hal *hal = sc->sc_hal;
4022 	struct ieee80211com *ic = &sc->sc_ic;
4023 	struct ieee80211_node *ni = ic->ic_bss;
4024 	int error;
4025 
4026 	/* Update adapter's configuration. */
4027 	IEEE80211_ADDR_COPY(sc->rxon.bssid, ni->ni_bssid);
4028 	sc->rxon.chan = ieee80211_chan2ieee(ic, ni->ni_chan);
4029 	sc->rxon.flags = htole32(IWN_RXON_TSF | IWN_RXON_CTS_TO_SELF);
4030 	if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
4031 		sc->rxon.flags |= htole32(IWN_RXON_AUTO | IWN_RXON_24GHZ);
4032 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
4033 		sc->rxon.flags |= htole32(IWN_RXON_SHSLOT);
4034 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
4035 		sc->rxon.flags |= htole32(IWN_RXON_SHPREAMBLE);
4036 	switch (ic->ic_curmode) {
4037 	case IEEE80211_MODE_11A:
4038 		sc->rxon.cck_mask  = 0;
4039 		sc->rxon.ofdm_mask = 0x15;
4040 		break;
4041 	case IEEE80211_MODE_11B:
4042 		sc->rxon.cck_mask  = 0x03;
4043 		sc->rxon.ofdm_mask = 0;
4044 		break;
4045 	default:	/* Assume 802.11b/g. */
4046 		sc->rxon.cck_mask  = 0x0f;
4047 		sc->rxon.ofdm_mask = 0x15;
4048 	}
4049 	DPRINTF(("rxon chan %d flags %x cck %x ofdm %x\n", sc->rxon.chan,
4050 	    sc->rxon.flags, sc->rxon.cck_mask, sc->rxon.ofdm_mask));
4051 	error = iwn_cmd(sc, IWN_CMD_CONFIGURE, &sc->rxon, hal->rxonsz, 1);
4052 	if (error != 0) {
4053 		printf("%s: could not configure\n", sc->sc_dev.dv_xname);
4054 		return error;
4055 	}
4056 
4057 	/* Configuration has changed, set TX power accordingly. */
4058 	if ((error = hal->set_txpower(sc, 1)) != 0) {
4059 		printf("%s: could not set TX power\n", sc->sc_dev.dv_xname);
4060 		return error;
4061 	}
4062 	/*
4063 	 * Reconfiguring RXON clears the firmware's nodes table so we must
4064 	 * add the broadcast node again.
4065 	 */
4066 	if ((error = iwn_add_broadcast_node(sc, 1)) != 0) {
4067 		printf("%s: could not add broadcast node\n",
4068 		    sc->sc_dev.dv_xname);
4069 		return error;
4070 	}
4071 	return 0;
4072 }
4073 
4074 int
4075 iwn_run(struct iwn_softc *sc)
4076 {
4077 	const struct iwn_hal *hal = sc->sc_hal;
4078 	struct ieee80211com *ic = &sc->sc_ic;
4079 	struct ieee80211_node *ni = ic->ic_bss;
4080 	struct iwn_node_info node;
4081 	int error;
4082 
4083 	if (ic->ic_opmode == IEEE80211_M_MONITOR) {
4084 		/* Link LED blinks while monitoring. */
4085 		iwn_set_led(sc, IWN_LED_LINK, 5, 5);
4086 		return 0;
4087 	}
4088 	if ((error = iwn_set_timing(sc, ni)) != 0) {
4089 		printf("%s: could not set timing\n", sc->sc_dev.dv_xname);
4090 		return error;
4091 	}
4092 
4093 	/* Update adapter's configuration. */
4094 	sc->rxon.associd = htole16(IEEE80211_AID(ni->ni_associd));
4095 	/* Short preamble and slot time are negotiated when associating. */
4096 	sc->rxon.flags &= ~htole32(IWN_RXON_SHPREAMBLE | IWN_RXON_SHSLOT);
4097 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
4098 		sc->rxon.flags |= htole32(IWN_RXON_SHSLOT);
4099 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
4100 		sc->rxon.flags |= htole32(IWN_RXON_SHPREAMBLE);
4101 	sc->rxon.filter |= htole32(IWN_FILTER_BSS);
4102 	DPRINTF(("rxon chan %d flags %x\n", sc->rxon.chan, sc->rxon.flags));
4103 	error = iwn_cmd(sc, IWN_CMD_CONFIGURE, &sc->rxon, hal->rxonsz, 1);
4104 	if (error != 0) {
4105 		printf("%s: could not update configuration\n",
4106 		    sc->sc_dev.dv_xname);
4107 		return error;
4108 	}
4109 
4110 	/* Configuration has changed, set TX power accordingly. */
4111 	if ((error = hal->set_txpower(sc, 1)) != 0) {
4112 		printf("%s: could not set TX power\n", sc->sc_dev.dv_xname);
4113 		return error;
4114 	}
4115 
4116 	/* Fake a join to initialize the TX rate. */
4117 	((struct iwn_node *)ni)->id = IWN_ID_BSS;
4118 	iwn_newassoc(ic, ni, 1);
4119 
4120 	/* Add BSS node. */
4121 	memset(&node, 0, sizeof node);
4122 	IEEE80211_ADDR_COPY(node.macaddr, ni->ni_macaddr);
4123 	node.id = IWN_ID_BSS;
4124 #ifdef notyet
4125 	node.htflags = htole32(IWN_AMDPU_SIZE_FACTOR(3) |
4126 	    IWN_AMDPU_DENSITY(5));	/* 2us */
4127 #endif
4128 	DPRINTF(("adding BSS node\n"));
4129 	error = hal->add_node(sc, &node, 1);
4130 	if (error != 0) {
4131 		printf("%s: could not add BSS node\n", sc->sc_dev.dv_xname);
4132 		return error;
4133 	}
4134 	DPRINTF(("setting link quality for node %d\n", node.id));
4135 	if ((error = iwn_set_link_quality(sc, ni)) != 0) {
4136 		printf("%s: could not setup link quality for node %d\n",
4137 		    sc->sc_dev.dv_xname, node.id);
4138 		return error;
4139 	}
4140 
4141 	if ((error = iwn_init_sensitivity(sc)) != 0) {
4142 		printf("%s: could not set sensitivity\n",
4143 		    sc->sc_dev.dv_xname);
4144 		return error;
4145 	}
4146 	/* Start periodic calibration timer. */
4147 	sc->calib.state = IWN_CALIB_STATE_ASSOC;
4148 	sc->calib_cnt = 0;
4149 	timeout_add(&sc->calib_to, hz / 2);
4150 
4151 	/* Link LED always on while associated. */
4152 	iwn_set_led(sc, IWN_LED_LINK, 0, 1);
4153 	return 0;
4154 }
4155 
4156 /*
4157  * We support CCMP hardware encryption/decryption of unicast frames only.
4158  * HW support for TKIP really sucks.  We should let TKIP die anyway.
4159  */
4160 int
4161 iwn_set_key(struct ieee80211com *ic, struct ieee80211_node *ni,
4162     struct ieee80211_key *k)
4163 {
4164 	struct iwn_softc *sc = ic->ic_softc;
4165 	const struct iwn_hal *hal = sc->sc_hal;
4166 	struct iwn_node *wn = (void *)ni;
4167 	struct iwn_node_info node;
4168 	uint16_t kflags;
4169 
4170 	if ((k->k_flags & IEEE80211_KEY_GROUP) ||
4171 	    k->k_cipher != IEEE80211_CIPHER_CCMP)
4172 		return ieee80211_set_key(ic, ni, k);
4173 
4174 	kflags = IWN_KFLAG_CCMP | IWN_KFLAG_MAP | IWN_KFLAG_KID(k->k_id);
4175 	if (k->k_flags & IEEE80211_KEY_GROUP)
4176 		kflags |= IWN_KFLAG_GROUP;
4177 
4178 	memset(&node, 0, sizeof node);
4179 	node.id = (k->k_flags & IEEE80211_KEY_GROUP) ?
4180 	    hal->broadcast_id : wn->id;
4181 	node.control = IWN_NODE_UPDATE;
4182 	node.flags = IWN_FLAG_SET_KEY;
4183 	node.kflags = htole16(kflags);
4184 	node.kid = k->k_id;
4185 	memcpy(node.key, k->k_key, k->k_len);
4186 	DPRINTF(("set key id=%d for node %d\n", k->k_id, node.id));
4187 	return hal->add_node(sc, &node, 1);
4188 }
4189 
4190 void
4191 iwn_delete_key(struct ieee80211com *ic, struct ieee80211_node *ni,
4192     struct ieee80211_key *k)
4193 {
4194 	struct iwn_softc *sc = ic->ic_softc;
4195 	const struct iwn_hal *hal = sc->sc_hal;
4196 	struct iwn_node *wn = (void *)ni;
4197 	struct iwn_node_info node;
4198 
4199 	if ((k->k_flags & IEEE80211_KEY_GROUP) ||
4200 	    k->k_cipher != IEEE80211_CIPHER_CCMP) {
4201 		/* See comment about other ciphers above. */
4202 		ieee80211_delete_key(ic, ni, k);
4203 		return;
4204 	}
4205 	if (ic->ic_state != IEEE80211_S_RUN)
4206 		return;	/* Nothing to do. */
4207 	memset(&node, 0, sizeof node);
4208 	node.id = (k->k_flags & IEEE80211_KEY_GROUP) ?
4209 	    hal->broadcast_id : wn->id;
4210 	node.control = IWN_NODE_UPDATE;
4211 	node.flags = IWN_FLAG_SET_KEY;
4212 	node.kflags = htole16(IWN_KFLAG_INVALID);
4213 	node.kid = 0xff;
4214 	DPRINTF(("delete keys for node %d\n", node.id));
4215 	(void)hal->add_node(sc, &node, 1);
4216 }
4217 
4218 #ifndef IEEE80211_NO_HT
4219 /*
4220  * This function is called by upper layer when an ADDBA request is received
4221  * from another STA and before the ADDBA response is sent.
4222  */
4223 int
4224 iwn_ampdu_rx_start(struct ieee80211com *ic, struct ieee80211_node *ni,
4225     uint8_t tid)
4226 {
4227 	struct ieee80211_rx_ba *ba = &ni->ni_rx_ba[tid];
4228 	struct iwn_softc *sc = ic->ic_softc;
4229 	struct iwn_node *wn = (void *)ni;
4230 	struct iwn_node_info node;
4231 
4232 	memset(&node, 0, sizeof node);
4233 	node.id = wn->id;
4234 	node.control = IWN_NODE_UPDATE;
4235 	node.flags = IWN_FLAG_SET_ADDBA;
4236 	node.addba_tid = tid;
4237 	node.addba_ssn = htole16(ba->ba_winstart);
4238 	DPRINTFN(2, ("ADDBA RA=%d TID=%d SSN=%d\n", wn->id, tid,
4239 	    ba->ba_winstart));
4240 	return sc->sc_hal->add_node(sc, &node, 1);
4241 }
4242 
4243 /*
4244  * This function is called by upper layer on teardown of an HT-immediate
4245  * Block Ack agreement (eg. uppon receipt of a DELBA frame.)
4246  */
4247 void
4248 iwn_ampdu_rx_stop(struct ieee80211com *ic, struct ieee80211_node *ni,
4249     uint8_t tid)
4250 {
4251 	struct iwn_softc *sc = ic->ic_softc;
4252 	struct iwn_node *wn = (void *)ni;
4253 	struct iwn_node_info node;
4254 
4255 	memset(&node, 0, sizeof node);
4256 	node.id = wn->id;
4257 	node.control = IWN_NODE_UPDATE;
4258 	node.flags = IWN_FLAG_SET_DELBA;
4259 	node.delba_tid = tid;
4260 	DPRINTFN(2, ("DELBA RA=%d TID=%d\n", wn->id, tid));
4261 	(void)sc->sc_hal->add_node(sc, &node, 1);
4262 }
4263 
4264 /*
4265  * This function is called by upper layer when an ADDBA response is received
4266  * from another STA.
4267  */
4268 int
4269 iwn_ampdu_tx_start(struct ieee80211com *ic, struct ieee80211_node *ni,
4270     uint8_t tid)
4271 {
4272 	struct ieee80211_tx_ba *ba = &ni->ni_tx_ba[tid];
4273 	struct iwn_softc *sc = ic->ic_softc;
4274 	const struct iwn_hal *hal = sc->sc_hal;
4275 	struct iwn_node *wn = (void *)ni;
4276 	struct iwn_node_info node;
4277 	int error;
4278 
4279 	/* Enable TX for the specified RA/TID. */
4280 	wn->disable_tid &= ~(1 << tid);
4281 	memset(&node, 0, sizeof node);
4282 	node.id = wn->id;
4283 	node.control = IWN_NODE_UPDATE;
4284 	node.flags = IWN_FLAG_SET_DISABLE_TID;
4285 	node.disable_tid = htole16(wn->disable_tid);
4286 	error = hal->add_node(sc, &node, 1);
4287 	if (error != 0)
4288 		return error;
4289 
4290 	if ((error = iwn_nic_lock(sc)) != 0)
4291 		return error;
4292 	hal->ampdu_tx_start(sc, ni, tid, ba->ba_winstart);
4293 	iwn_nic_unlock(sc);
4294 	return 0;
4295 }
4296 
4297 void
4298 iwn_ampdu_tx_stop(struct ieee80211com *ic, struct ieee80211_node *ni,
4299     uint8_t tid)
4300 {
4301 	struct ieee80211_tx_ba *ba = &ni->ni_tx_ba[tid];
4302 	struct iwn_softc *sc = ic->ic_softc;
4303 
4304 	if (iwn_nic_lock(sc) != 0)
4305 		return;
4306 	sc->sc_hal->ampdu_tx_stop(sc, tid, ba->ba_winstart);
4307 	iwn_nic_unlock(sc);
4308 }
4309 
4310 void
4311 iwn4965_ampdu_tx_start(struct iwn_softc *sc, struct ieee80211_node *ni,
4312     uint8_t tid, uint16_t ssn)
4313 {
4314 	struct iwn_node *wn = (void *)ni;
4315 	int qid = 7 + tid;
4316 
4317 	/* Stop TX scheduler while we're changing its configuration. */
4318 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
4319 	    IWN4965_TXQ_STATUS_CHGACT);
4320 
4321 	/* Assign RA/TID translation to the queue. */
4322 	iwn_mem_write_2(sc, sc->sched_base + IWN4965_SCHED_TRANS_TBL(qid),
4323 	    wn->id << 4 | tid);
4324 
4325 	/* Enable chain mode for the queue. */
4326 	iwn_prph_setbits(sc, IWN4965_SCHED_QCHAIN_SEL, 1 << qid);
4327 
4328 	/* Set starting sequence number from the ADDBA request. */
4329 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, ssn);
4330 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_RDPTR(qid), ssn);
4331 
4332 	/* Set scheduler window size. */
4333 	iwn_mem_write(sc, sc->sched_base + IWN4965_SCHED_QUEUE_OFFSET(qid),
4334 	    IWN_SCHED_WINSZ);
4335 	/* Set scheduler frame limit. */
4336 	iwn_mem_write(sc, sc->sched_base + IWN4965_SCHED_QUEUE_OFFSET(qid) + 4,
4337 	    IWN_SCHED_LIMIT << 16);
4338 
4339 	/* Enable interrupts for the queue. */
4340 	iwn_prph_setbits(sc, IWN4965_SCHED_INTR_MASK, 1 << qid);
4341 
4342 	/* Mark the queue as active. */
4343 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
4344 	    IWN4965_TXQ_STATUS_ACTIVE | IWN4965_TXQ_STATUS_AGGR_ENA |
4345 	    iwn_tid2fifo[tid] << 1);
4346 }
4347 
4348 void
4349 iwn4965_ampdu_tx_stop(struct iwn_softc *sc, uint8_t tid, uint16_t ssn)
4350 {
4351 	int qid = 7 + tid;
4352 
4353 	/* Stop TX scheduler while we're changing its configuration. */
4354 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
4355 	    IWN4965_TXQ_STATUS_CHGACT);
4356 
4357 	/* Set starting sequence number from the ADDBA request. */
4358 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, ssn);
4359 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_RDPTR(qid), ssn);
4360 
4361 	/* Disable interrupts for the queue. */
4362 	iwn_prph_clrbits(sc, IWN4965_SCHED_INTR_MASK, 1 << qid);
4363 
4364 	/* Mark the queue as inactive. */
4365 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
4366 	    IWN4965_TXQ_STATUS_INACTIVE | iwn_tid2fifo[tid] << 1);
4367 }
4368 
4369 void
4370 iwn5000_ampdu_tx_start(struct iwn_softc *sc, struct ieee80211_node *ni,
4371     uint8_t tid, uint16_t ssn)
4372 {
4373 	struct iwn_node *wn = (void *)ni;
4374 	int qid = 10 + tid;
4375 
4376 	/* Stop TX scheduler while we're changing its configuration. */
4377 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
4378 	    IWN5000_TXQ_STATUS_CHGACT);
4379 
4380 	/* Assign RA/TID translation to the queue. */
4381 	iwn_mem_write_2(sc, sc->sched_base + IWN5000_SCHED_TRANS_TBL(qid),
4382 	    wn->id << 4 | tid);
4383 
4384 	/* Enable chain mode for the queue. */
4385 	iwn_prph_setbits(sc, IWN5000_SCHED_QCHAIN_SEL, 1 << qid);
4386 
4387 	/* Enable aggregation for the queue. */
4388 	iwn_prph_setbits(sc, IWN5000_SCHED_AGGR_SEL, 1 << qid);
4389 
4390 	/* Set starting sequence number from the ADDBA request. */
4391 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, ssn);
4392 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_RDPTR(qid), ssn);
4393 
4394 	/* Set scheduler window size and frame limit. */
4395 	iwn_mem_write(sc, sc->sched_base + IWN5000_SCHED_QUEUE_OFFSET(qid) + 4,
4396 	    IWN_SCHED_LIMIT << 16 | IWN_SCHED_WINSZ);
4397 
4398 	/* Enable interrupts for the queue. */
4399 	iwn_prph_setbits(sc, IWN5000_SCHED_INTR_MASK, 1 << qid);
4400 
4401 	/* Mark the queue as active. */
4402 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
4403 	    IWN5000_TXQ_STATUS_ACTIVE | iwn_tid2fifo[tid]);
4404 }
4405 
4406 void
4407 iwn5000_ampdu_tx_stop(struct iwn_softc *sc, uint8_t tid, uint16_t ssn)
4408 {
4409 	int qid = 10 + tid;
4410 
4411 	/* Stop TX scheduler while we're changing its configuration. */
4412 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
4413 	    IWN5000_TXQ_STATUS_CHGACT);
4414 
4415 	/* Disable aggregation for the queue. */
4416 	iwn_prph_clrbits(sc, IWN5000_SCHED_AGGR_SEL, 1 << qid);
4417 
4418 	/* Set starting sequence number from the ADDBA request. */
4419 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, ssn);
4420 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_RDPTR(qid), ssn);
4421 
4422 	/* Disable interrupts for the queue. */
4423 	iwn_prph_clrbits(sc, IWN5000_SCHED_INTR_MASK, 1 << qid);
4424 
4425 	/* Mark the queue as inactive. */
4426 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
4427 	    IWN5000_TXQ_STATUS_INACTIVE | iwn_tid2fifo[tid]);
4428 }
4429 #endif	/* !IEEE80211_NO_HT */
4430 
4431 /*
4432  * Query calibration tables from the initialization firmware.  We do this
4433  * only once at first boot.  Called from a process context.
4434  */
4435 int
4436 iwn5000_query_calibration(struct iwn_softc *sc)
4437 {
4438 	struct iwn5000_calib_config cmd;
4439 	int error;
4440 
4441 	memset(&cmd, 0, sizeof cmd);
4442 	cmd.ucode.once.enable = 0xffffffff;
4443 	cmd.ucode.once.start  = 0xffffffff;
4444 	cmd.ucode.once.send   = 0xffffffff;
4445 	cmd.ucode.flags       = 0xffffffff;
4446 	DPRINTF(("sending calibration query\n"));
4447 	error = iwn_cmd(sc, IWN5000_CMD_CALIB_CONFIG, &cmd, sizeof cmd, 0);
4448 	if (error != 0)
4449 		return error;
4450 
4451 	/* Wait at most two seconds for calibration to complete. */
4452 	return tsleep(sc, PCATCH, "iwncal", 2 * hz);
4453 }
4454 
4455 /*
4456  * Send calibration results to the runtime firmware.  These results were
4457  * obtained on first boot from the initialization firmware.
4458  */
4459 int
4460 iwn5000_send_calibration(struct iwn_softc *sc)
4461 {
4462 	int idx, error;
4463 
4464 	for (idx = 0; idx < 5; idx++) {
4465 		if (sc->calibcmd[idx].buf == NULL)
4466 			continue;	/* No results available. */
4467 		DPRINTF(("send calibration result idx=%d len=%d\n",
4468 		    idx, sc->calibcmd[idx].len));
4469 		error = iwn_cmd(sc, IWN_CMD_PHY_CALIB, sc->calibcmd[idx].buf,
4470 		    sc->calibcmd[idx].len, 0);
4471 		if (error != 0) {
4472 			printf("%s: could not send calibration result\n",
4473 			    sc->sc_dev.dv_xname);
4474 			return error;
4475 		}
4476 	}
4477 	return 0;
4478 }
4479 
4480 /*
4481  * This function is called after the runtime firmware notifies us of its
4482  * readiness (called in a process context.)
4483  */
4484 int
4485 iwn4965_post_alive(struct iwn_softc *sc)
4486 {
4487 	int error, qid;
4488 
4489 	if ((error = iwn_nic_lock(sc)) != 0)
4490 		return error;
4491 
4492 	/* Clear TX scheduler's state in SRAM. */
4493 	sc->sched_base = iwn_prph_read(sc, IWN_SCHED_SRAM_ADDR);
4494 	iwn_mem_set_region_4(sc, sc->sched_base + IWN4965_SCHED_CTX_OFF, 0,
4495 	    IWN4965_SCHED_CTX_LEN);
4496 
4497 	/* Set physical address of TX scheduler rings (1KB aligned.) */
4498 	iwn_prph_write(sc, IWN4965_SCHED_DRAM_ADDR, sc->sched_dma.paddr >> 10);
4499 
4500 	IWN_SETBITS(sc, IWN_FH_TX_CHICKEN, IWN_FH_TX_CHICKEN_SCHED_RETRY);
4501 
4502 	/* Disable chain mode for all our 16 queues. */
4503 	iwn_prph_write(sc, IWN4965_SCHED_QCHAIN_SEL, 0);
4504 
4505 	for (qid = 0; qid < IWN4965_NTXQUEUES; qid++) {
4506 		iwn_prph_write(sc, IWN4965_SCHED_QUEUE_RDPTR(qid), 0);
4507 		IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | 0);
4508 
4509 		/* Set scheduler window size. */
4510 		iwn_mem_write(sc, sc->sched_base +
4511 		    IWN4965_SCHED_QUEUE_OFFSET(qid), IWN_SCHED_WINSZ);
4512 		/* Set scheduler frame limit. */
4513 		iwn_mem_write(sc, sc->sched_base +
4514 		    IWN4965_SCHED_QUEUE_OFFSET(qid) + 4,
4515 		    IWN_SCHED_LIMIT << 16);
4516 	}
4517 
4518 	/* Enable interrupts for all our 16 queues. */
4519 	iwn_prph_write(sc, IWN4965_SCHED_INTR_MASK, 0xffff);
4520 	/* Identify TX FIFO rings (0-7). */
4521 	iwn_prph_write(sc, IWN4965_SCHED_TXFACT, 0xff);
4522 
4523 	/* Mark TX rings (4 EDCA + cmd + 2 HCCA) as active. */
4524 	for (qid = 0; qid < 7; qid++) {
4525 		static uint8_t qid2fifo[] = { 3, 2, 1, 0, 4, 5, 6 };
4526 		iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
4527 		    IWN4965_TXQ_STATUS_ACTIVE | qid2fifo[qid] << 1);
4528 	}
4529 	iwn_nic_unlock(sc);
4530 	return 0;
4531 }
4532 
4533 /*
4534  * This function is called after the initialization or runtime firmware
4535  * notifies us of its readiness (called in a process context.)
4536  */
4537 int
4538 iwn5000_post_alive(struct iwn_softc *sc)
4539 {
4540 	struct iwn5000_wimax_coex wimax;
4541 	int error, qid;
4542 
4543 	if ((error = iwn_nic_lock(sc)) != 0)
4544 		return error;
4545 
4546 	/* Clear TX scheduler's state in SRAM. */
4547 	sc->sched_base = iwn_prph_read(sc, IWN_SCHED_SRAM_ADDR);
4548 	iwn_mem_set_region_4(sc, sc->sched_base + IWN5000_SCHED_CTX_OFF, 0,
4549 	    IWN5000_SCHED_CTX_LEN);
4550 
4551 	/* Set physical address of TX scheduler rings (1KB aligned.) */
4552 	iwn_prph_write(sc, IWN5000_SCHED_DRAM_ADDR, sc->sched_dma.paddr >> 10);
4553 
4554 	IWN_SETBITS(sc, IWN_FH_TX_CHICKEN, IWN_FH_TX_CHICKEN_SCHED_RETRY);
4555 
4556 	/* Enable chain mode for all our 20 queues. */
4557 	iwn_prph_write(sc, IWN5000_SCHED_QCHAIN_SEL, 0xfffff);
4558 	iwn_prph_write(sc, IWN5000_SCHED_AGGR_SEL, 0);
4559 
4560 	for (qid = 0; qid < IWN5000_NTXQUEUES; qid++) {
4561 		iwn_prph_write(sc, IWN5000_SCHED_QUEUE_RDPTR(qid), 0);
4562 		IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | 0);
4563 
4564 		iwn_mem_write(sc, sc->sched_base +
4565 		    IWN5000_SCHED_QUEUE_OFFSET(qid), 0);
4566 		/* Set scheduler window size and frame limit. */
4567 		iwn_mem_write(sc, sc->sched_base +
4568 		    IWN5000_SCHED_QUEUE_OFFSET(qid) + 4,
4569 		    IWN_SCHED_LIMIT << 16 | IWN_SCHED_WINSZ);
4570 	}
4571 
4572 	/* Enable interrupts for all our 20 queues. */
4573 	iwn_prph_write(sc, IWN5000_SCHED_INTR_MASK, 0xfffff);
4574 	/* Identify TX FIFO rings (0-7). */
4575 	iwn_prph_write(sc, IWN5000_SCHED_TXFACT, 0xff);
4576 
4577 	/* Mark TX rings (4 EDCA + cmd + 2 HCCA) as active. */
4578 	for (qid = 0; qid < 7; qid++) {
4579 		static uint8_t qid2fifo[] = { 3, 2, 1, 0, 7, 5, 6 };
4580 		iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
4581 		    IWN5000_TXQ_STATUS_ACTIVE | qid2fifo[qid]);
4582 	}
4583 	iwn_nic_unlock(sc);
4584 
4585 	/* Configure WiMAX (IEEE 802.16e) coexistence. */
4586 	memset(&wimax, 0, sizeof wimax);
4587 	DPRINTF(("Configuring WiMAX coexistence\n"));
4588 	error = iwn_cmd(sc, IWN5000_CMD_WIMAX_COEX, &wimax, sizeof wimax, 0);
4589 	if (error != 0) {
4590 		printf("%s: could not configure WiMAX coexistence\n",
4591 		    sc->sc_dev.dv_xname);
4592 		return error;
4593 	}
4594 
4595 	if (sc->hw_type != IWN_HW_REV_TYPE_5150) {
4596 		struct iwn5000_phy_calib_crystal cmd;
4597 
4598 		/* Perform crystal calibration. */
4599 		memset(&cmd, 0, sizeof cmd);
4600 		cmd.code = IWN5000_PHY_CALIB_CRYSTAL;
4601 		cmd.ngroups = 1;
4602 		cmd.isvalid = 1;
4603 		cmd.cap_pin[0] = letoh32(sc->eeprom_crystal) & 0xff;
4604 		cmd.cap_pin[1] = (letoh32(sc->eeprom_crystal) >> 16) & 0xff;
4605 		DPRINTF(("sending crystal calibration %d, %d\n",
4606 		    cmd.cap_pin[0], cmd.cap_pin[1]));
4607 		error = iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 0);
4608 		if (error != 0) {
4609 			printf("%s: crystal calibration failed\n",
4610 			    sc->sc_dev.dv_xname);
4611 			return error;
4612 		}
4613 	}
4614 	if (sc->sc_flags & IWN_FLAG_FIRST_BOOT) {
4615 		/* Query calibration from the initialization firmware. */
4616 		if ((error = iwn5000_query_calibration(sc)) != 0) {
4617 			printf("%s: could not query calibration\n",
4618 			    sc->sc_dev.dv_xname);
4619 			return error;
4620 		}
4621 		/*
4622 		 * We have the calibration results now so we can skip
4623 		 * loading the initialization firmware next time.
4624 		 */
4625 		sc->sc_flags &= ~IWN_FLAG_FIRST_BOOT;
4626 
4627 		/* Reboot (call ourselves recursively!) */
4628 		iwn_hw_stop(sc);
4629 		error = iwn_hw_init(sc);
4630 	} else {
4631 		/* Send calibration results to runtime firmware. */
4632 		error = iwn5000_send_calibration(sc);
4633 	}
4634 	return error;
4635 }
4636 
4637 /*
4638  * The firmware boot code is small and is intended to be copied directly into
4639  * the NIC internal memory (no DMA transfer.)
4640  */
4641 int
4642 iwn4965_load_bootcode(struct iwn_softc *sc, const uint8_t *ucode, int size)
4643 {
4644 	int error, ntries;
4645 
4646 	size /= sizeof (uint32_t);
4647 
4648 	if ((error = iwn_nic_lock(sc)) != 0)
4649 		return error;
4650 
4651 	/* Copy microcode image into NIC memory. */
4652 	iwn_prph_write_region_4(sc, IWN_BSM_SRAM_BASE,
4653 	    (const uint32_t *)ucode, size);
4654 
4655 	iwn_prph_write(sc, IWN_BSM_WR_MEM_SRC, 0);
4656 	iwn_prph_write(sc, IWN_BSM_WR_MEM_DST, IWN_FW_TEXT_BASE);
4657 	iwn_prph_write(sc, IWN_BSM_WR_DWCOUNT, size);
4658 
4659 	/* Start boot load now. */
4660 	iwn_prph_write(sc, IWN_BSM_WR_CTRL, IWN_BSM_WR_CTRL_START);
4661 
4662 	/* Wait for transfer to complete. */
4663 	for (ntries = 0; ntries < 1000; ntries++) {
4664 		if (!(iwn_prph_read(sc, IWN_BSM_WR_CTRL) &
4665 		    IWN_BSM_WR_CTRL_START))
4666 			break;
4667 		DELAY(10);
4668 	}
4669 	if (ntries == 1000) {
4670 		printf("%s: could not load boot firmware\n",
4671 		    sc->sc_dev.dv_xname);
4672 		iwn_nic_unlock(sc);
4673 		return ETIMEDOUT;
4674 	}
4675 
4676 	/* Enable boot after power up. */
4677 	iwn_prph_write(sc, IWN_BSM_WR_CTRL, IWN_BSM_WR_CTRL_START_EN);
4678 
4679 	iwn_nic_unlock(sc);
4680 	return 0;
4681 }
4682 
4683 int
4684 iwn4965_load_firmware(struct iwn_softc *sc)
4685 {
4686 	struct iwn_fw_info *fw = &sc->fw;
4687 	struct iwn_dma_info *dma = &sc->fw_dma;
4688 	int error;
4689 
4690 	/* Copy initialization sections into pre-allocated DMA-safe memory. */
4691 	memcpy(dma->vaddr, fw->init.data, fw->init.datasz);
4692 	bus_dmamap_sync(sc->sc_dmat, dma->map, 0, fw->init.datasz,
4693 	    BUS_DMASYNC_PREWRITE);
4694 	memcpy(dma->vaddr + IWN4965_FW_DATA_MAXSZ,
4695 	    fw->init.text, fw->init.textsz);
4696 	bus_dmamap_sync(sc->sc_dmat, dma->map, IWN4965_FW_DATA_MAXSZ,
4697 	    fw->init.textsz, BUS_DMASYNC_PREWRITE);
4698 
4699 	/* Tell adapter where to find initialization sections. */
4700 	if ((error = iwn_nic_lock(sc)) != 0)
4701 		return error;
4702 	iwn_prph_write(sc, IWN_BSM_DRAM_DATA_ADDR, dma->paddr >> 4);
4703 	iwn_prph_write(sc, IWN_BSM_DRAM_DATA_SIZE, fw->init.datasz);
4704 	iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_ADDR,
4705 	    (dma->paddr + IWN4965_FW_DATA_MAXSZ) >> 4);
4706 	iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_SIZE, fw->init.textsz);
4707 	iwn_nic_unlock(sc);
4708 
4709 	/* Load firmware boot code. */
4710 	error = iwn4965_load_bootcode(sc, fw->boot.text, fw->boot.textsz);
4711 	if (error != 0) {
4712 		printf("%s: could not load boot firmware\n",
4713 		    sc->sc_dev.dv_xname);
4714 		return error;
4715 	}
4716 	/* Now press "execute". */
4717 	IWN_WRITE(sc, IWN_RESET, 0);
4718 
4719 	/* Wait at most one second for first alive notification. */
4720 	if ((error = tsleep(sc, PCATCH, "iwninit", hz)) != 0) {
4721 		printf("%s: timeout waiting for adapter to initialize\n",
4722 		    sc->sc_dev.dv_xname);
4723 		return error;
4724 	}
4725 
4726 	/* Retrieve current temperature for initial TX power calibration. */
4727 	sc->rawtemp = sc->ucode_info.temp[3].chan20MHz;
4728 	sc->temp = iwn4965_get_temperature(sc);
4729 
4730 	/* Copy runtime sections into pre-allocated DMA-safe memory. */
4731 	memcpy(dma->vaddr, fw->main.data, fw->main.datasz);
4732 	bus_dmamap_sync(sc->sc_dmat, dma->map, 0, fw->main.datasz,
4733 	    BUS_DMASYNC_PREWRITE);
4734 	memcpy(dma->vaddr + IWN4965_FW_DATA_MAXSZ,
4735 	    fw->main.text, fw->main.textsz);
4736 	bus_dmamap_sync(sc->sc_dmat, dma->map, IWN4965_FW_DATA_MAXSZ,
4737 	    fw->main.textsz, BUS_DMASYNC_PREWRITE);
4738 
4739 	/* Tell adapter where to find runtime sections. */
4740 	if ((error = iwn_nic_lock(sc)) != 0)
4741 		return error;
4742 	iwn_prph_write(sc, IWN_BSM_DRAM_DATA_ADDR, dma->paddr >> 4);
4743 	iwn_prph_write(sc, IWN_BSM_DRAM_DATA_SIZE, fw->main.datasz);
4744 	iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_ADDR,
4745 	    (dma->paddr + IWN4965_FW_DATA_MAXSZ) >> 4);
4746 	iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_SIZE,
4747 	    IWN_FW_UPDATED | fw->main.textsz);
4748 	iwn_nic_unlock(sc);
4749 
4750 	return 0;
4751 }
4752 
4753 int
4754 iwn5000_load_firmware_section(struct iwn_softc *sc, uint32_t dst,
4755     const uint8_t *section, int size)
4756 {
4757 	struct iwn_dma_info *dma = &sc->fw_dma;
4758 	int error;
4759 
4760 	/* Copy firmware section into pre-allocated DMA-safe memory. */
4761 	memcpy(dma->vaddr, section, size);
4762 	bus_dmamap_sync(sc->sc_dmat, dma->map, 0, size, BUS_DMASYNC_PREWRITE);
4763 
4764 	if ((error = iwn_nic_lock(sc)) != 0)
4765 		return error;
4766 
4767 	IWN_WRITE(sc, IWN_FH_TX_CONFIG(IWN_SRVC_CHNL),
4768 	    IWN_FH_TX_CONFIG_DMA_PAUSE);
4769 
4770 	IWN_WRITE(sc, IWN_FH_SRAM_ADDR(IWN_SRVC_CHNL), dst);
4771 	IWN_WRITE(sc, IWN_FH_TFBD_CTRL0(IWN_SRVC_CHNL),
4772 	    IWN_LOADDR(dma->paddr));
4773 	IWN_WRITE(sc, IWN_FH_TFBD_CTRL1(IWN_SRVC_CHNL),
4774 	    IWN_HIADDR(dma->paddr) << 28 | size);
4775 	IWN_WRITE(sc, IWN_FH_TXBUF_STATUS(IWN_SRVC_CHNL),
4776 	    IWN_FH_TXBUF_STATUS_TBNUM(1) |
4777 	    IWN_FH_TXBUF_STATUS_TBIDX(1) |
4778 	    IWN_FH_TXBUF_STATUS_TFBD_VALID);
4779 
4780 	/* Kick Flow Handler to start DMA transfer. */
4781 	IWN_WRITE(sc, IWN_FH_TX_CONFIG(IWN_SRVC_CHNL),
4782 	    IWN_FH_TX_CONFIG_DMA_ENA | IWN_FH_TX_CONFIG_CIRQ_HOST_ENDTFD);
4783 
4784 	iwn_nic_unlock(sc);
4785 
4786 	/* Wait at most five seconds for FH DMA transfer to complete. */
4787 	return tsleep(sc, PCATCH, "iwninit", 5 * hz);
4788 }
4789 
4790 int
4791 iwn5000_load_firmware(struct iwn_softc *sc)
4792 {
4793 	struct iwn_fw_part *fw;
4794 	int error;
4795 
4796 	/* Load the initialization firmware on first boot only. */
4797 	fw = (sc->sc_flags & IWN_FLAG_FIRST_BOOT) ?
4798 	    &sc->fw.init : &sc->fw.main;
4799 
4800 	error = iwn5000_load_firmware_section(sc, IWN_FW_TEXT_BASE,
4801 	    fw->text, fw->textsz);
4802 	if (error != 0) {
4803 		printf("%s: could not load firmware %s section\n",
4804 		    sc->sc_dev.dv_xname, ".text");
4805 		return error;
4806 	}
4807 	error = iwn5000_load_firmware_section(sc, IWN_FW_DATA_BASE,
4808 	    fw->data, fw->datasz);
4809 	if (error != 0) {
4810 		printf("%s: could not load firmware %s section\n",
4811 		    sc->sc_dev.dv_xname, ".data");
4812 		return error;
4813 	}
4814 
4815 	/* Now press "execute". */
4816 	IWN_WRITE(sc, IWN_RESET, 0);
4817 	return 0;
4818 }
4819 
4820 int
4821 iwn_read_firmware(struct iwn_softc *sc)
4822 {
4823 	const struct iwn_hal *hal = sc->sc_hal;
4824 	struct iwn_fw_info *fw = &sc->fw;
4825 	const struct iwn_firmware_hdr *hdr;
4826 	size_t size;
4827 	int error;
4828 
4829 	/* Read firmware image from filesystem. */
4830 	if ((error = loadfirmware(sc->fwname, &fw->data, &size)) != 0) {
4831 		printf("%s: error, %d, could not read firmware %s\n",
4832 		    sc->sc_dev.dv_xname, error, sc->fwname);
4833 		return error;
4834 	}
4835 	if (size < sizeof (*hdr)) {
4836 		printf("%s: truncated firmware header: %d bytes\n",
4837 		    sc->sc_dev.dv_xname, size);
4838 		free(fw->data, M_DEVBUF);
4839 		return EINVAL;
4840 	}
4841 	/* Extract firmware header information. */
4842 	hdr = (struct iwn_firmware_hdr *)fw->data;
4843 	fw->main.textsz = letoh32(hdr->main_textsz);
4844 	fw->main.datasz = letoh32(hdr->main_datasz);
4845 	fw->init.textsz = letoh32(hdr->init_textsz);
4846 	fw->init.datasz = letoh32(hdr->init_datasz);
4847 	fw->boot.textsz = letoh32(hdr->boot_textsz);
4848 	fw->boot.datasz = 0;
4849 
4850 	/* Sanity-check firmware header. */
4851 	if (fw->main.textsz > hal->fw_text_maxsz ||
4852 	    fw->main.datasz > hal->fw_data_maxsz ||
4853 	    fw->init.textsz > hal->fw_text_maxsz ||
4854 	    fw->init.datasz > hal->fw_data_maxsz ||
4855 	    fw->boot.textsz > IWN_FW_BOOT_TEXT_MAXSZ ||
4856 	    (fw->boot.textsz & 3) != 0) {
4857 		printf("%s: invalid firmware header\n", sc->sc_dev.dv_xname);
4858 		free(fw->data, M_DEVBUF);
4859 		return EINVAL;
4860 	}
4861 
4862 	/* Check that all firmware sections fit. */
4863 	if (size < sizeof (*hdr) + fw->main.textsz + fw->main.datasz +
4864 	    fw->init.textsz + fw->init.datasz + fw->boot.textsz) {
4865 		printf("%s: firmware file too short: %d bytes\n",
4866 		    sc->sc_dev.dv_xname, size);
4867 		free(fw->data, M_DEVBUF);
4868 		return EINVAL;
4869 	}
4870 
4871 	/* Get pointers to firmware sections. */
4872 	fw->main.text = (const uint8_t *)(hdr + 1);
4873 	fw->main.data = fw->main.text + fw->main.textsz;
4874 	fw->init.text = fw->main.data + fw->main.datasz;
4875 	fw->init.data = fw->init.text + fw->init.textsz;
4876 	fw->boot.text = fw->init.data + fw->init.datasz;
4877 
4878 	return 0;
4879 }
4880 
4881 int
4882 iwn_clock_wait(struct iwn_softc *sc)
4883 {
4884 	int ntries;
4885 
4886 	/* Set "initialization complete" bit. */
4887 	IWN_SETBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_INIT_DONE);
4888 
4889 	/* Wait for clock stabilization. */
4890 	for (ntries = 0; ntries < 25000; ntries++) {
4891 		if (IWN_READ(sc, IWN_GP_CNTRL) & IWN_GP_CNTRL_MAC_CLOCK_READY)
4892 			return 0;
4893 		DELAY(100);
4894 	}
4895 	printf("%s: timeout waiting for clock stabilization\n",
4896 	    sc->sc_dev.dv_xname);
4897 	return ETIMEDOUT;
4898 }
4899 
4900 int
4901 iwn4965_apm_init(struct iwn_softc *sc)
4902 {
4903 	int error;
4904 
4905 	/* Disable L0s. */
4906 	IWN_SETBITS(sc, IWN_GIO_CHICKEN, IWN_GIO_CHICKEN_DIS_L0S_TIMER);
4907 	IWN_SETBITS(sc, IWN_GIO_CHICKEN, IWN_GIO_CHICKEN_L1A_NO_L0S_RX);
4908 
4909 	if ((error = iwn_clock_wait(sc)) != 0)
4910 		return error;
4911 
4912 	if ((error = iwn_nic_lock(sc)) != 0)
4913 		return error;
4914 	/* Enable DMA. */
4915 	iwn_prph_write(sc, IWN_APMG_CLK_CTRL,
4916 	    IWN_APMG_CLK_CTRL_DMA_CLK_RQT | IWN_APMG_CLK_CTRL_BSM_CLK_RQT);
4917 	DELAY(20);
4918 	/* Disable L1. */
4919 	iwn_prph_setbits(sc, IWN_APMG_PCI_STT, IWN_APMG_PCI_STT_L1A_DIS);
4920 	iwn_nic_unlock(sc);
4921 
4922 	return 0;
4923 }
4924 
4925 int
4926 iwn5000_apm_init(struct iwn_softc *sc)
4927 {
4928 	int error;
4929 
4930 	/* Disable L0s. */
4931 	IWN_SETBITS(sc, IWN_GIO_CHICKEN, IWN_GIO_CHICKEN_DIS_L0S_TIMER);
4932 	IWN_SETBITS(sc, IWN_GIO_CHICKEN, IWN_GIO_CHICKEN_L1A_NO_L0S_RX);
4933 
4934 	/* Set Flow Handler wait threshold to the maximum. */
4935 	IWN_SETBITS(sc, IWN_DBG_HPET_MEM, 0xffff0000);
4936 
4937 	/* Enable HAP to move adapter from L1a to L0s. */
4938 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_HAP_WAKE_L1A);
4939 
4940 	if (sc->hw_type != IWN_HW_REV_TYPE_6000 &&
4941 	    sc->hw_type != IWN_HW_REV_TYPE_6050)
4942 		IWN_SETBITS(sc, IWN_ANA_PLL, IWN_ANA_PLL_INIT);
4943 
4944 	if ((error = iwn_clock_wait(sc)) != 0)
4945 		return error;
4946 
4947 	if ((error = iwn_nic_lock(sc)) != 0)
4948 		return error;
4949 	/* Enable DMA. */
4950 	iwn_prph_write(sc, IWN_APMG_CLK_CTRL, IWN_APMG_CLK_CTRL_DMA_CLK_RQT);
4951 	DELAY(20);
4952 	/* Disable L1. */
4953 	iwn_prph_setbits(sc, IWN_APMG_PCI_STT, IWN_APMG_PCI_STT_L1A_DIS);
4954 	iwn_nic_unlock(sc);
4955 
4956 	return 0;
4957 }
4958 
4959 void
4960 iwn_apm_stop_master(struct iwn_softc *sc)
4961 {
4962 	int ntries;
4963 
4964 	IWN_SETBITS(sc, IWN_RESET, IWN_RESET_STOP_MASTER);
4965 	for (ntries = 0; ntries < 100; ntries++) {
4966 		if (IWN_READ(sc, IWN_RESET) & IWN_RESET_MASTER_DISABLED)
4967 			return;
4968 		DELAY(10);
4969 	}
4970 	printf("%s: timeout waiting for master\n", sc->sc_dev.dv_xname);
4971 }
4972 
4973 void
4974 iwn_apm_stop(struct iwn_softc *sc)
4975 {
4976 	iwn_apm_stop_master(sc);
4977 
4978 	IWN_SETBITS(sc, IWN_RESET, IWN_RESET_SW);
4979 	DELAY(10);
4980 	/* Clear "initialization complete" bit. */
4981 	IWN_CLRBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_INIT_DONE);
4982 }
4983 
4984 int
4985 iwn4965_nic_config(struct iwn_softc *sc)
4986 {
4987 	pcireg_t reg;
4988 
4989 	/* Retrieve PCIe Active State Power Management (ASPM). */
4990 	reg = pci_conf_read(sc->sc_pct, sc->sc_pcitag,
4991 	    sc->sc_cap_off + PCI_PCIE_LCSR);
4992 	if (reg & PCI_PCIE_LCSR_ASPM_L1)	/* L1 Entry enabled. */
4993 		IWN_SETBITS(sc, IWN_GIO, IWN_GIO_L0S_ENA);
4994 	else
4995 		IWN_CLRBITS(sc, IWN_GIO, IWN_GIO_L0S_ENA);
4996 
4997 	if (IWN_RFCFG_TYPE(sc->rfcfg) == 1) {
4998 		/*
4999 		 * I don't believe this to be correct but this is what the
5000 		 * vendor driver is doing. Probably the bits should not be
5001 		 * shifted in IWN_RFCFG_*.
5002 		 */
5003 		IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
5004 		    IWN_RFCFG_TYPE(sc->rfcfg) |
5005 		    IWN_RFCFG_STEP(sc->rfcfg) |
5006 		    IWN_RFCFG_DASH(sc->rfcfg));
5007 	}
5008 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
5009 	    IWN_HW_IF_CONFIG_RADIO_SI | IWN_HW_IF_CONFIG_MAC_SI);
5010 	return 0;
5011 }
5012 
5013 int
5014 iwn5000_nic_config(struct iwn_softc *sc)
5015 {
5016 	pcireg_t reg;
5017 	int error;
5018 
5019 	/* Retrieve PCIe Active State Power Management (ASPM). */
5020 	reg = pci_conf_read(sc->sc_pct, sc->sc_pcitag,
5021 	    sc->sc_cap_off + PCI_PCIE_LCSR);
5022 	if (reg & PCI_PCIE_LCSR_ASPM_L1)	/* L1 Entry enabled. */
5023 		IWN_SETBITS(sc, IWN_GIO, IWN_GIO_L0S_ENA);
5024 	else
5025 		IWN_CLRBITS(sc, IWN_GIO, IWN_GIO_L0S_ENA);
5026 
5027 	if (IWN_RFCFG_TYPE(sc->rfcfg) < 3) {
5028 		IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
5029 		    IWN_RFCFG_TYPE(sc->rfcfg) |
5030 		    IWN_RFCFG_STEP(sc->rfcfg) |
5031 		    IWN_RFCFG_DASH(sc->rfcfg));
5032 	}
5033 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
5034 	    IWN_HW_IF_CONFIG_RADIO_SI | IWN_HW_IF_CONFIG_MAC_SI);
5035 
5036 	if ((error = iwn_nic_lock(sc)) != 0)
5037 		return error;
5038 	iwn_prph_setbits(sc, IWN_APMG_PS, IWN_APMG_PS_EARLY_PWROFF_DIS);
5039 	iwn_nic_unlock(sc);
5040 	return 0;
5041 }
5042 
5043 int
5044 iwn_hw_init(struct iwn_softc *sc)
5045 {
5046 	const struct iwn_hal *hal = sc->sc_hal;
5047 	int error, qid;
5048 
5049 	/* Clear pending interrupts. */
5050 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
5051 
5052 	if ((error = hal->apm_init(sc)) != 0) {
5053 		printf("%s: could not power ON adapter\n",
5054 		    sc->sc_dev.dv_xname);
5055 		return error;
5056 	}
5057 
5058 	/* Select VMAIN power source. */
5059 	if ((error = iwn_nic_lock(sc)) != 0)
5060 		return error;
5061 	iwn_prph_clrbits(sc, IWN_APMG_PS, IWN_APMG_PS_PWR_SRC_MASK);
5062 	iwn_nic_unlock(sc);
5063 
5064 	/* Perform adapter-specific initialization. */
5065 	if ((error = hal->nic_config(sc)) != 0)
5066 		return error;
5067 
5068 	/* Initialize RX ring. */
5069 	if ((error = iwn_nic_lock(sc)) != 0)
5070 		return error;
5071 	IWN_WRITE(sc, IWN_FH_RX_CONFIG, 0);
5072 	IWN_WRITE(sc, IWN_FH_RX_WPTR, 0);
5073 	/* Set physical address of RX ring (256-byte aligned.) */
5074 	IWN_WRITE(sc, IWN_FH_RX_BASE, sc->rxq.desc_dma.paddr >> 8);
5075 	/* Set physical address of RX status (16-byte aligned.) */
5076 	IWN_WRITE(sc, IWN_FH_STATUS_WPTR, sc->rxq.stat_dma.paddr >> 4);
5077 	/* Enable RX. */
5078 	IWN_WRITE(sc, IWN_FH_RX_CONFIG,
5079 	    IWN_FH_RX_CONFIG_ENA           |
5080 	    IWN_FH_RX_CONFIG_IGN_RXF_EMPTY |	/* HW bug workaround */
5081 	    IWN_FH_RX_CONFIG_IRQ_DST_HOST  |
5082 	    IWN_FH_RX_CONFIG_SINGLE_FRAME  |
5083 	    IWN_FH_RX_CONFIG_RB_TIMEOUT(0) |
5084 	    IWN_FH_RX_CONFIG_NRBD(IWN_RX_RING_COUNT_LOG));
5085 	iwn_nic_unlock(sc);
5086 	IWN_WRITE(sc, IWN_FH_RX_WPTR, (IWN_RX_RING_COUNT - 1) & ~7);
5087 
5088 	if ((error = iwn_nic_lock(sc)) != 0)
5089 		return error;
5090 
5091 	/* Initialize TX scheduler. */
5092 	iwn_prph_write(sc, hal->sched_txfact_addr, 0);
5093 
5094 	/* Set physical address of "keep warm" page (16-byte aligned.) */
5095 	IWN_WRITE(sc, IWN_FH_KW_ADDR, sc->kw_dma.paddr >> 4);
5096 
5097 	/* Initialize TX rings. */
5098 	for (qid = 0; qid < hal->ntxqs; qid++) {
5099 		struct iwn_tx_ring *txq = &sc->txq[qid];
5100 
5101 		/* Set physical address of TX ring (256-byte aligned.) */
5102 		IWN_WRITE(sc, IWN_FH_CBBC_QUEUE(qid),
5103 		    txq->desc_dma.paddr >> 8);
5104 		/* Enable TX for this ring. */
5105 		IWN_WRITE(sc, IWN_FH_TX_CONFIG(qid),
5106 		    IWN_FH_TX_CONFIG_DMA_ENA |
5107 		    IWN_FH_TX_CONFIG_DMA_CREDIT_ENA);
5108 	}
5109 	iwn_nic_unlock(sc);
5110 
5111 	/* Clear "radio off" and "commands blocked" bits. */
5112 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_RFKILL);
5113 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_CMD_BLOCKED);
5114 
5115 	/* Clear pending interrupts. */
5116 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
5117 	/* Enable interrupt coalescing. */
5118 	IWN_WRITE(sc, IWN_INT_COALESCING, 512 / 8);
5119 	/* Enable interrupts. */
5120 	IWN_WRITE(sc, IWN_MASK, IWN_INT_MASK);
5121 
5122 	/* _Really_ make sure "radio off" bit is cleared! */
5123 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_RFKILL);
5124 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_RFKILL);
5125 
5126 	if ((error = hal->load_firmware(sc)) != 0) {
5127 		printf("%s: could not load firmware\n", sc->sc_dev.dv_xname);
5128 		return error;
5129 	}
5130 	/* Wait at most one second for firmware alive notification. */
5131 	if ((error = tsleep(sc, PCATCH, "iwninit", hz)) != 0) {
5132 		printf("%s: timeout waiting for adapter to initialize\n",
5133 		    sc->sc_dev.dv_xname);
5134 		return error;
5135 	}
5136 	/* Do post-firmware initialization. */
5137 	return hal->post_alive(sc);
5138 }
5139 
5140 void
5141 iwn_hw_stop(struct iwn_softc *sc)
5142 {
5143 	const struct iwn_hal *hal = sc->sc_hal;
5144 	int qid;
5145 
5146 	IWN_WRITE(sc, IWN_RESET, IWN_RESET_NEVO);
5147 
5148 	/* Disable interrupts. */
5149 	IWN_WRITE(sc, IWN_MASK, 0);
5150 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
5151 	IWN_WRITE(sc, IWN_FH_INT, 0xffffffff);
5152 
5153 	/* Make sure we no longer hold the NIC lock. */
5154 	iwn_nic_unlock(sc);
5155 
5156 	/* Stop TX scheduler. */
5157 	iwn_prph_write(sc, hal->sched_txfact_addr, 0);
5158 
5159 	/* Stop all TX rings. */
5160 	for (qid = 0; qid < hal->ntxqs; qid++)
5161 		iwn_reset_tx_ring(sc, &sc->txq[qid]);
5162 
5163 	/* Stop RX ring. */
5164 	iwn_reset_rx_ring(sc, &sc->rxq);
5165 
5166 	if (iwn_nic_lock(sc) == 0) {
5167 		iwn_prph_write(sc, IWN_APMG_CLK_DIS, IWN_APMG_CLK_DMA_RQT);
5168 		iwn_nic_unlock(sc);
5169 	}
5170 	DELAY(5);
5171 	/* Power OFF adapter. */
5172 	iwn_apm_stop(sc);
5173 }
5174 
5175 int
5176 iwn_init(struct ifnet *ifp)
5177 {
5178 	struct iwn_softc *sc = ifp->if_softc;
5179 	struct ieee80211com *ic = &sc->sc_ic;
5180 	int error;
5181 
5182 	/* Check that the radio is not disabled by hardware switch. */
5183 	if (!(IWN_READ(sc, IWN_GP_CNTRL) & IWN_GP_CNTRL_RFKILL)) {
5184 		printf("%s: radio is disabled by hardware switch\n",
5185 		    sc->sc_dev.dv_xname);
5186 		error = EPERM;	/* :-) */
5187 		goto fail;
5188 	}
5189 
5190 	/* Read firmware images from the filesystem. */
5191 	if ((error = iwn_read_firmware(sc)) != 0) {
5192 		printf("%s: could not read firmware\n", sc->sc_dev.dv_xname);
5193 		goto fail;
5194 	}
5195 
5196 	/* Initialize hardware and upload firmware. */
5197 	error = iwn_hw_init(sc);
5198 	free(sc->fw.data, M_DEVBUF);
5199 	if (error != 0) {
5200 		printf("%s: could not initialize hardware\n",
5201 		    sc->sc_dev.dv_xname);
5202 		goto fail;
5203 	}
5204 
5205 	/* Configure adapter now that it is ready. */
5206 	if ((error = iwn_config(sc)) != 0) {
5207 		printf("%s: could not configure device\n",
5208 		    sc->sc_dev.dv_xname);
5209 		goto fail;
5210 	}
5211 
5212 	ifp->if_flags &= ~IFF_OACTIVE;
5213 	ifp->if_flags |= IFF_RUNNING;
5214 
5215 	if (ic->ic_opmode != IEEE80211_M_MONITOR)
5216 		ieee80211_begin_scan(ifp);
5217 	else
5218 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
5219 
5220 	return 0;
5221 
5222 fail:	iwn_stop(ifp, 1);
5223 	return error;
5224 }
5225 
5226 void
5227 iwn_stop(struct ifnet *ifp, int disable)
5228 {
5229 	struct iwn_softc *sc = ifp->if_softc;
5230 	struct ieee80211com *ic = &sc->sc_ic;
5231 
5232 	ifp->if_timer = sc->sc_tx_timer = 0;
5233 	ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
5234 
5235 	/* In case we were scanning, release the scan "lock". */
5236 	ic->ic_scan_lock = IEEE80211_SCAN_UNLOCKED;
5237 
5238 	ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
5239 
5240 	/* Power OFF hardware. */
5241 	iwn_hw_stop(sc);
5242 
5243 	/* Temperature sensor is no longer valid. */
5244 	sc->sensor.value = 0;
5245 	sc->sensor.flags |= SENSOR_FINVALID;
5246 }
5247