xref: /openbsd-src/sys/dev/pci/if_iwn.c (revision 24bb5fcea3ed904bc467217bdaadb5dfc618d5bf)
1 /*	$OpenBSD: if_iwn.c,v 1.248 2021/04/29 21:43:47 stsp Exp $	*/
2 
3 /*-
4  * Copyright (c) 2007-2010 Damien Bergamini <damien.bergamini@free.fr>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 /*
20  * Driver for Intel WiFi Link 4965 and 1000/5000/6000 Series 802.11 network
21  * adapters.
22  */
23 
24 #include "bpfilter.h"
25 
26 #include <sys/param.h>
27 #include <sys/sockio.h>
28 #include <sys/mbuf.h>
29 #include <sys/kernel.h>
30 #include <sys/rwlock.h>
31 #include <sys/socket.h>
32 #include <sys/systm.h>
33 #include <sys/malloc.h>
34 #include <sys/conf.h>
35 #include <sys/device.h>
36 #include <sys/task.h>
37 #include <sys/endian.h>
38 
39 #include <machine/bus.h>
40 #include <machine/intr.h>
41 
42 #include <dev/pci/pcireg.h>
43 #include <dev/pci/pcivar.h>
44 #include <dev/pci/pcidevs.h>
45 
46 #if NBPFILTER > 0
47 #include <net/bpf.h>
48 #endif
49 #include <net/if.h>
50 #include <net/if_dl.h>
51 #include <net/if_media.h>
52 
53 #include <netinet/in.h>
54 #include <netinet/if_ether.h>
55 
56 #include <net80211/ieee80211_var.h>
57 #include <net80211/ieee80211_amrr.h>
58 #include <net80211/ieee80211_ra.h>
59 #include <net80211/ieee80211_radiotap.h>
60 #include <net80211/ieee80211_priv.h> /* for SEQ_LT */
61 #undef DPRINTF /* defined in ieee80211_priv.h */
62 
63 #include <dev/pci/if_iwnreg.h>
64 #include <dev/pci/if_iwnvar.h>
65 
66 static const struct pci_matchid iwn_devices[] = {
67 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_4965_1 },
68 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_4965_2 },
69 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_5100_1 },
70 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_5100_2 },
71 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_5150_1 },
72 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_5150_2 },
73 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_5300_1 },
74 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_5300_2 },
75 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_5350_1 },
76 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_5350_2 },
77 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_1000_1 },
78 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_1000_2 },
79 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_6300_1 },
80 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_6300_2 },
81 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_6200_1 },
82 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_6200_2 },
83 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_6050_1 },
84 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_6050_2 },
85 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_6005_1 },
86 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_6005_2 },
87 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_6030_1 },
88 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_6030_2 },
89 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_1030_1 },
90 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_1030_2 },
91 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_100_1 },
92 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_100_2 },
93 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_130_1 },
94 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_130_2 },
95 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_6235_1 },
96 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_6235_2 },
97 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_2230_1 },
98 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_2230_2 },
99 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_2200_1 },
100 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_2200_2 },
101 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_135_1 },
102 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_135_2 },
103 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_105_1 },
104 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_WL_105_2 },
105 };
106 
107 int		iwn_match(struct device *, void *, void *);
108 void		iwn_attach(struct device *, struct device *, void *);
109 int		iwn4965_attach(struct iwn_softc *, pci_product_id_t);
110 int		iwn5000_attach(struct iwn_softc *, pci_product_id_t);
111 #if NBPFILTER > 0
112 void		iwn_radiotap_attach(struct iwn_softc *);
113 #endif
114 int		iwn_detach(struct device *, int);
115 int		iwn_activate(struct device *, int);
116 void		iwn_wakeup(struct iwn_softc *);
117 void		iwn_init_task(void *);
118 int		iwn_nic_lock(struct iwn_softc *);
119 int		iwn_eeprom_lock(struct iwn_softc *);
120 int		iwn_init_otprom(struct iwn_softc *);
121 int		iwn_read_prom_data(struct iwn_softc *, uint32_t, void *, int);
122 int		iwn_dma_contig_alloc(bus_dma_tag_t, struct iwn_dma_info *,
123 		    void **, bus_size_t, bus_size_t);
124 void		iwn_dma_contig_free(struct iwn_dma_info *);
125 int		iwn_alloc_sched(struct iwn_softc *);
126 void		iwn_free_sched(struct iwn_softc *);
127 int		iwn_alloc_kw(struct iwn_softc *);
128 void		iwn_free_kw(struct iwn_softc *);
129 int		iwn_alloc_ict(struct iwn_softc *);
130 void		iwn_free_ict(struct iwn_softc *);
131 int		iwn_alloc_fwmem(struct iwn_softc *);
132 void		iwn_free_fwmem(struct iwn_softc *);
133 int		iwn_alloc_rx_ring(struct iwn_softc *, struct iwn_rx_ring *);
134 void		iwn_reset_rx_ring(struct iwn_softc *, struct iwn_rx_ring *);
135 void		iwn_free_rx_ring(struct iwn_softc *, struct iwn_rx_ring *);
136 int		iwn_alloc_tx_ring(struct iwn_softc *, struct iwn_tx_ring *,
137 		    int);
138 void		iwn_reset_tx_ring(struct iwn_softc *, struct iwn_tx_ring *);
139 void		iwn_free_tx_ring(struct iwn_softc *, struct iwn_tx_ring *);
140 void		iwn5000_ict_reset(struct iwn_softc *);
141 int		iwn_read_eeprom(struct iwn_softc *);
142 void		iwn4965_read_eeprom(struct iwn_softc *);
143 void		iwn4965_print_power_group(struct iwn_softc *, int);
144 void		iwn5000_read_eeprom(struct iwn_softc *);
145 void		iwn_read_eeprom_channels(struct iwn_softc *, int, uint32_t);
146 void		iwn_read_eeprom_enhinfo(struct iwn_softc *);
147 struct		ieee80211_node *iwn_node_alloc(struct ieee80211com *);
148 void		iwn_newassoc(struct ieee80211com *, struct ieee80211_node *,
149 		    int);
150 int		iwn_media_change(struct ifnet *);
151 int		iwn_newstate(struct ieee80211com *, enum ieee80211_state, int);
152 void		iwn_iter_func(void *, struct ieee80211_node *);
153 void		iwn_calib_timeout(void *);
154 int		iwn_ccmp_decap(struct iwn_softc *, struct mbuf *,
155 		    struct ieee80211_node *);
156 void		iwn_rx_phy(struct iwn_softc *, struct iwn_rx_desc *,
157 		    struct iwn_rx_data *);
158 void		iwn_rx_done(struct iwn_softc *, struct iwn_rx_desc *,
159 		    struct iwn_rx_data *, struct mbuf_list *);
160 void		iwn_ra_choose(struct iwn_softc *, struct ieee80211_node *);
161 void		iwn_ampdu_rate_control(struct iwn_softc *, struct ieee80211_node *,
162 		    struct iwn_tx_ring *, uint16_t, uint16_t);
163 void		iwn_ht_single_rate_control(struct iwn_softc *,
164 		    struct ieee80211_node *, uint8_t, uint8_t, uint8_t, int);
165 void		iwn_rx_compressed_ba(struct iwn_softc *, struct iwn_rx_desc *,
166 		    struct iwn_rx_data *);
167 void		iwn5000_rx_calib_results(struct iwn_softc *,
168 		    struct iwn_rx_desc *, struct iwn_rx_data *);
169 void		iwn_rx_statistics(struct iwn_softc *, struct iwn_rx_desc *,
170 		    struct iwn_rx_data *);
171 void		iwn_ampdu_txq_advance(struct iwn_softc *, struct iwn_tx_ring *,
172 		    int, int);
173 void		iwn_ampdu_tx_done(struct iwn_softc *, struct iwn_tx_ring *,
174 		    struct iwn_rx_desc *, uint16_t, uint8_t, uint8_t, uint8_t,
175 		    int, uint32_t, struct iwn_txagg_status *);
176 void		iwn4965_tx_done(struct iwn_softc *, struct iwn_rx_desc *,
177 		    struct iwn_rx_data *);
178 void		iwn5000_tx_done(struct iwn_softc *, struct iwn_rx_desc *,
179 		    struct iwn_rx_data *);
180 void		iwn_tx_done_free_txdata(struct iwn_softc *,
181 		    struct iwn_tx_data *);
182 void		iwn_clear_oactive(struct iwn_softc *, struct iwn_tx_ring *);
183 void		iwn_tx_done(struct iwn_softc *, struct iwn_rx_desc *,
184 		    uint8_t, uint8_t, uint8_t, int, int, uint16_t);
185 void		iwn_cmd_done(struct iwn_softc *, struct iwn_rx_desc *);
186 void		iwn_notif_intr(struct iwn_softc *);
187 void		iwn_wakeup_intr(struct iwn_softc *);
188 void		iwn_fatal_intr(struct iwn_softc *);
189 int		iwn_intr(void *);
190 void		iwn4965_update_sched(struct iwn_softc *, int, int, uint8_t,
191 		    uint16_t);
192 void		iwn4965_reset_sched(struct iwn_softc *, int, int);
193 void		iwn5000_update_sched(struct iwn_softc *, int, int, uint8_t,
194 		    uint16_t);
195 void		iwn5000_reset_sched(struct iwn_softc *, int, int);
196 int		iwn_tx(struct iwn_softc *, struct mbuf *,
197 		    struct ieee80211_node *);
198 int		iwn_rval2ridx(int);
199 void		iwn_start(struct ifnet *);
200 void		iwn_watchdog(struct ifnet *);
201 int		iwn_ioctl(struct ifnet *, u_long, caddr_t);
202 int		iwn_cmd(struct iwn_softc *, int, const void *, int, int);
203 int		iwn4965_add_node(struct iwn_softc *, struct iwn_node_info *,
204 		    int);
205 int		iwn5000_add_node(struct iwn_softc *, struct iwn_node_info *,
206 		    int);
207 int		iwn_set_link_quality(struct iwn_softc *,
208 		    struct ieee80211_node *);
209 int		iwn_add_broadcast_node(struct iwn_softc *, int, int);
210 void		iwn_updateedca(struct ieee80211com *);
211 void		iwn_set_led(struct iwn_softc *, uint8_t, uint8_t, uint8_t);
212 int		iwn_set_critical_temp(struct iwn_softc *);
213 int		iwn_set_timing(struct iwn_softc *, struct ieee80211_node *);
214 void		iwn4965_power_calibration(struct iwn_softc *, int);
215 int		iwn4965_set_txpower(struct iwn_softc *, int);
216 int		iwn5000_set_txpower(struct iwn_softc *, int);
217 int		iwn4965_get_rssi(const struct iwn_rx_stat *);
218 int		iwn5000_get_rssi(const struct iwn_rx_stat *);
219 int		iwn_get_noise(const struct iwn_rx_general_stats *);
220 int		iwn4965_get_temperature(struct iwn_softc *);
221 int		iwn5000_get_temperature(struct iwn_softc *);
222 int		iwn_init_sensitivity(struct iwn_softc *);
223 void		iwn_collect_noise(struct iwn_softc *,
224 		    const struct iwn_rx_general_stats *);
225 int		iwn4965_init_gains(struct iwn_softc *);
226 int		iwn5000_init_gains(struct iwn_softc *);
227 int		iwn4965_set_gains(struct iwn_softc *);
228 int		iwn5000_set_gains(struct iwn_softc *);
229 void		iwn_tune_sensitivity(struct iwn_softc *,
230 		    const struct iwn_rx_stats *);
231 int		iwn_send_sensitivity(struct iwn_softc *);
232 int		iwn_set_pslevel(struct iwn_softc *, int, int, int);
233 int		iwn_send_temperature_offset(struct iwn_softc *);
234 int		iwn_send_btcoex(struct iwn_softc *);
235 int		iwn_send_advanced_btcoex(struct iwn_softc *);
236 int		iwn5000_runtime_calib(struct iwn_softc *);
237 int		iwn_config(struct iwn_softc *);
238 uint16_t	iwn_get_active_dwell_time(struct iwn_softc *, uint16_t, uint8_t);
239 uint16_t	iwn_limit_dwell(struct iwn_softc *, uint16_t);
240 uint16_t	iwn_get_passive_dwell_time(struct iwn_softc *, uint16_t);
241 int		iwn_scan(struct iwn_softc *, uint16_t, int);
242 void		iwn_scan_abort(struct iwn_softc *);
243 int		iwn_bgscan(struct ieee80211com *);
244 int		iwn_auth(struct iwn_softc *, int);
245 int		iwn_run(struct iwn_softc *);
246 int		iwn_set_key(struct ieee80211com *, struct ieee80211_node *,
247 		    struct ieee80211_key *);
248 void		iwn_delete_key(struct ieee80211com *, struct ieee80211_node *,
249 		    struct ieee80211_key *);
250 void		iwn_updateprot(struct ieee80211com *);
251 void		iwn_updateslot(struct ieee80211com *);
252 void		iwn_update_rxon(struct iwn_softc *);
253 int		iwn_ampdu_rx_start(struct ieee80211com *,
254 		    struct ieee80211_node *, uint8_t);
255 void		iwn_ampdu_rx_stop(struct ieee80211com *,
256 		    struct ieee80211_node *, uint8_t);
257 int		iwn_ampdu_tx_start(struct ieee80211com *,
258 		    struct ieee80211_node *, uint8_t);
259 void		iwn_ampdu_tx_stop(struct ieee80211com *,
260 		    struct ieee80211_node *, uint8_t);
261 void		iwn4965_ampdu_tx_start(struct iwn_softc *,
262 		    struct ieee80211_node *, uint8_t, uint16_t);
263 void		iwn4965_ampdu_tx_stop(struct iwn_softc *,
264 		    uint8_t, uint16_t);
265 void		iwn5000_ampdu_tx_start(struct iwn_softc *,
266 		    struct ieee80211_node *, uint8_t, uint16_t);
267 void		iwn5000_ampdu_tx_stop(struct iwn_softc *,
268 		    uint8_t, uint16_t);
269 int		iwn5000_query_calibration(struct iwn_softc *);
270 int		iwn5000_send_calibration(struct iwn_softc *);
271 int		iwn5000_send_wimax_coex(struct iwn_softc *);
272 int		iwn5000_crystal_calib(struct iwn_softc *);
273 int		iwn6000_temp_offset_calib(struct iwn_softc *);
274 int		iwn2000_temp_offset_calib(struct iwn_softc *);
275 int		iwn4965_post_alive(struct iwn_softc *);
276 int		iwn5000_post_alive(struct iwn_softc *);
277 int		iwn4965_load_bootcode(struct iwn_softc *, const uint8_t *,
278 		    int);
279 int		iwn4965_load_firmware(struct iwn_softc *);
280 int		iwn5000_load_firmware_section(struct iwn_softc *, uint32_t,
281 		    const uint8_t *, int);
282 int		iwn5000_load_firmware(struct iwn_softc *);
283 int		iwn_read_firmware_leg(struct iwn_softc *,
284 		    struct iwn_fw_info *);
285 int		iwn_read_firmware_tlv(struct iwn_softc *,
286 		    struct iwn_fw_info *, uint16_t);
287 int		iwn_read_firmware(struct iwn_softc *);
288 int		iwn_clock_wait(struct iwn_softc *);
289 int		iwn_apm_init(struct iwn_softc *);
290 void		iwn_apm_stop_master(struct iwn_softc *);
291 void		iwn_apm_stop(struct iwn_softc *);
292 int		iwn4965_nic_config(struct iwn_softc *);
293 int		iwn5000_nic_config(struct iwn_softc *);
294 int		iwn_hw_prepare(struct iwn_softc *);
295 int		iwn_hw_init(struct iwn_softc *);
296 void		iwn_hw_stop(struct iwn_softc *);
297 int		iwn_init(struct ifnet *);
298 void		iwn_stop(struct ifnet *);
299 
300 #ifdef IWN_DEBUG
301 #define DPRINTF(x)	do { if (iwn_debug > 0) printf x; } while (0)
302 #define DPRINTFN(n, x)	do { if (iwn_debug >= (n)) printf x; } while (0)
303 int iwn_debug = 1;
304 #else
305 #define DPRINTF(x)
306 #define DPRINTFN(n, x)
307 #endif
308 
309 struct cfdriver iwn_cd = {
310 	NULL, "iwn", DV_IFNET
311 };
312 
313 struct cfattach iwn_ca = {
314 	sizeof (struct iwn_softc), iwn_match, iwn_attach, iwn_detach,
315 	iwn_activate
316 };
317 
318 int
319 iwn_match(struct device *parent, void *match, void *aux)
320 {
321 	return pci_matchbyid((struct pci_attach_args *)aux, iwn_devices,
322 	    nitems(iwn_devices));
323 }
324 
325 void
326 iwn_attach(struct device *parent, struct device *self, void *aux)
327 {
328 	struct iwn_softc *sc = (struct iwn_softc *)self;
329 	struct ieee80211com *ic = &sc->sc_ic;
330 	struct ifnet *ifp = &ic->ic_if;
331 	struct pci_attach_args *pa = aux;
332 	const char *intrstr;
333 	pci_intr_handle_t ih;
334 	pcireg_t memtype, reg;
335 	int i, error;
336 
337 	sc->sc_pct = pa->pa_pc;
338 	sc->sc_pcitag = pa->pa_tag;
339 	sc->sc_dmat = pa->pa_dmat;
340 
341 	/*
342 	 * Get the offset of the PCI Express Capability Structure in PCI
343 	 * Configuration Space.
344 	 */
345 	error = pci_get_capability(sc->sc_pct, sc->sc_pcitag,
346 	    PCI_CAP_PCIEXPRESS, &sc->sc_cap_off, NULL);
347 	if (error == 0) {
348 		printf(": PCIe capability structure not found!\n");
349 		return;
350 	}
351 
352 	/* Clear device-specific "PCI retry timeout" register (41h). */
353 	reg = pci_conf_read(sc->sc_pct, sc->sc_pcitag, 0x40);
354 	if (reg & 0xff00)
355 		pci_conf_write(sc->sc_pct, sc->sc_pcitag, 0x40, reg & ~0xff00);
356 
357 	/* Hardware bug workaround. */
358 	reg = pci_conf_read(sc->sc_pct, sc->sc_pcitag, PCI_COMMAND_STATUS_REG);
359 	if (reg & PCI_COMMAND_INTERRUPT_DISABLE) {
360 		DPRINTF(("PCIe INTx Disable set\n"));
361 		reg &= ~PCI_COMMAND_INTERRUPT_DISABLE;
362 		pci_conf_write(sc->sc_pct, sc->sc_pcitag,
363 		    PCI_COMMAND_STATUS_REG, reg);
364 	}
365 
366 	memtype = pci_mapreg_type(pa->pa_pc, pa->pa_tag, IWN_PCI_BAR0);
367 	error = pci_mapreg_map(pa, IWN_PCI_BAR0, memtype, 0, &sc->sc_st,
368 	    &sc->sc_sh, NULL, &sc->sc_sz, 0);
369 	if (error != 0) {
370 		printf(": can't map mem space\n");
371 		return;
372 	}
373 
374 	/* Install interrupt handler. */
375 	if (pci_intr_map_msi(pa, &ih) != 0 && pci_intr_map(pa, &ih) != 0) {
376 		printf(": can't map interrupt\n");
377 		return;
378 	}
379 	intrstr = pci_intr_string(sc->sc_pct, ih);
380 	sc->sc_ih = pci_intr_establish(sc->sc_pct, ih, IPL_NET, iwn_intr, sc,
381 	    sc->sc_dev.dv_xname);
382 	if (sc->sc_ih == NULL) {
383 		printf(": can't establish interrupt");
384 		if (intrstr != NULL)
385 			printf(" at %s", intrstr);
386 		printf("\n");
387 		return;
388 	}
389 	printf(": %s", intrstr);
390 
391 	/* Read hardware revision and attach. */
392 	sc->hw_type = (IWN_READ(sc, IWN_HW_REV) >> 4) & 0x1f;
393 	if (sc->hw_type == IWN_HW_REV_TYPE_4965)
394 		error = iwn4965_attach(sc, PCI_PRODUCT(pa->pa_id));
395 	else
396 		error = iwn5000_attach(sc, PCI_PRODUCT(pa->pa_id));
397 	if (error != 0) {
398 		printf(": could not attach device\n");
399 		return;
400 	}
401 
402 	if ((error = iwn_hw_prepare(sc)) != 0) {
403 		printf(": hardware not ready\n");
404 		return;
405 	}
406 
407 	/* Read MAC address, channels, etc from EEPROM. */
408 	if ((error = iwn_read_eeprom(sc)) != 0) {
409 		printf(": could not read EEPROM\n");
410 		return;
411 	}
412 
413 	/* Allocate DMA memory for firmware transfers. */
414 	if ((error = iwn_alloc_fwmem(sc)) != 0) {
415 		printf(": could not allocate memory for firmware\n");
416 		return;
417 	}
418 
419 	/* Allocate "Keep Warm" page. */
420 	if ((error = iwn_alloc_kw(sc)) != 0) {
421 		printf(": could not allocate keep warm page\n");
422 		goto fail1;
423 	}
424 
425 	/* Allocate ICT table for 5000 Series. */
426 	if (sc->hw_type != IWN_HW_REV_TYPE_4965 &&
427 	    (error = iwn_alloc_ict(sc)) != 0) {
428 		printf(": could not allocate ICT table\n");
429 		goto fail2;
430 	}
431 
432 	/* Allocate TX scheduler "rings". */
433 	if ((error = iwn_alloc_sched(sc)) != 0) {
434 		printf(": could not allocate TX scheduler rings\n");
435 		goto fail3;
436 	}
437 
438 	/* Allocate TX rings (16 on 4965AGN, 20 on >=5000). */
439 	for (i = 0; i < sc->ntxqs; i++) {
440 		if ((error = iwn_alloc_tx_ring(sc, &sc->txq[i], i)) != 0) {
441 			printf(": could not allocate TX ring %d\n", i);
442 			goto fail4;
443 		}
444 	}
445 
446 	/* Allocate RX ring. */
447 	if ((error = iwn_alloc_rx_ring(sc, &sc->rxq)) != 0) {
448 		printf(": could not allocate RX ring\n");
449 		goto fail4;
450 	}
451 
452 	/* Clear pending interrupts. */
453 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
454 
455 	/* Count the number of available chains. */
456 	sc->ntxchains =
457 	    ((sc->txchainmask >> 2) & 1) +
458 	    ((sc->txchainmask >> 1) & 1) +
459 	    ((sc->txchainmask >> 0) & 1);
460 	sc->nrxchains =
461 	    ((sc->rxchainmask >> 2) & 1) +
462 	    ((sc->rxchainmask >> 1) & 1) +
463 	    ((sc->rxchainmask >> 0) & 1);
464 	printf(", MIMO %dT%dR, %.4s, address %s\n", sc->ntxchains,
465 	    sc->nrxchains, sc->eeprom_domain, ether_sprintf(ic->ic_myaddr));
466 
467 	ic->ic_phytype = IEEE80211_T_OFDM;	/* not only, but not used */
468 	ic->ic_opmode = IEEE80211_M_STA;	/* default to BSS mode */
469 	ic->ic_state = IEEE80211_S_INIT;
470 
471 	/* Set device capabilities. */
472 	ic->ic_caps =
473 	    IEEE80211_C_WEP |		/* WEP */
474 	    IEEE80211_C_RSN |		/* WPA/RSN */
475 	    IEEE80211_C_SCANALL |	/* device scans all channels at once */
476 	    IEEE80211_C_SCANALLBAND |	/* driver scans all bands at once */
477 	    IEEE80211_C_MONITOR |	/* monitor mode supported */
478 	    IEEE80211_C_SHSLOT |	/* short slot time supported */
479 	    IEEE80211_C_SHPREAMBLE |	/* short preamble supported */
480 	    IEEE80211_C_PMGT;		/* power saving supported */
481 
482 	/* No optional HT features supported for now, */
483 	ic->ic_htcaps = 0;
484 	ic->ic_htxcaps = 0;
485 	ic->ic_txbfcaps = 0;
486 	ic->ic_aselcaps = 0;
487 	ic->ic_ampdu_params = (IEEE80211_AMPDU_PARAM_SS_4 | 0x3 /* 64k */);
488 	if (sc->sc_flags & IWN_FLAG_HAS_11N) {
489 		ic->ic_caps |= (IEEE80211_C_QOS | IEEE80211_C_TX_AMPDU);
490 		/* Set HT capabilities. */
491 		ic->ic_htcaps = IEEE80211_HTCAP_SGI20;
492 #ifdef notyet
493 		ic->ic_htcaps |=
494 #if IWN_RBUF_SIZE == 8192
495 		    IEEE80211_HTCAP_AMSDU7935 |
496 #endif
497 		    IEEE80211_HTCAP_CBW20_40 |
498 		    IEEE80211_HTCAP_SGI40;
499 		if (sc->hw_type != IWN_HW_REV_TYPE_4965)
500 			ic->ic_htcaps |= IEEE80211_HTCAP_GF;
501 		if (sc->hw_type == IWN_HW_REV_TYPE_6050)
502 			ic->ic_htcaps |= IEEE80211_HTCAP_SMPS_DYN;
503 		else
504 			ic->ic_htcaps |= IEEE80211_HTCAP_SMPS_DIS;
505 #endif	/* notyet */
506 	}
507 
508 	/* Set supported legacy rates. */
509 	ic->ic_sup_rates[IEEE80211_MODE_11B] = ieee80211_std_rateset_11b;
510 	ic->ic_sup_rates[IEEE80211_MODE_11G] = ieee80211_std_rateset_11g;
511 	if (sc->sc_flags & IWN_FLAG_HAS_5GHZ) {
512 		ic->ic_sup_rates[IEEE80211_MODE_11A] =
513 		    ieee80211_std_rateset_11a;
514 	}
515 	if (sc->sc_flags & IWN_FLAG_HAS_11N) {
516 		/* Set supported HT rates. */
517 		ic->ic_sup_mcs[0] = 0xff;		/* MCS 0-7 */
518 #ifdef notyet
519 		if (sc->nrxchains > 1)
520 			ic->ic_sup_mcs[1] = 0xff;	/* MCS 8-15 */
521 		if (sc->nrxchains > 2)
522 			ic->ic_sup_mcs[2] = 0xff;	/* MCS 16-23 */
523 #endif
524 	}
525 
526 	/* IBSS channel undefined for now. */
527 	ic->ic_ibss_chan = &ic->ic_channels[0];
528 
529 	ifp->if_softc = sc;
530 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
531 	ifp->if_ioctl = iwn_ioctl;
532 	ifp->if_start = iwn_start;
533 	ifp->if_watchdog = iwn_watchdog;
534 	memcpy(ifp->if_xname, sc->sc_dev.dv_xname, IFNAMSIZ);
535 
536 	if_attach(ifp);
537 	ieee80211_ifattach(ifp);
538 	ic->ic_node_alloc = iwn_node_alloc;
539 	ic->ic_bgscan_start = iwn_bgscan;
540 	ic->ic_newassoc = iwn_newassoc;
541 	ic->ic_updateedca = iwn_updateedca;
542 	ic->ic_set_key = iwn_set_key;
543 	ic->ic_delete_key = iwn_delete_key;
544 	ic->ic_updateprot = iwn_updateprot;
545 	ic->ic_updateslot = iwn_updateslot;
546 	ic->ic_ampdu_rx_start = iwn_ampdu_rx_start;
547 	ic->ic_ampdu_rx_stop = iwn_ampdu_rx_stop;
548 	ic->ic_ampdu_tx_start = iwn_ampdu_tx_start;
549 	ic->ic_ampdu_tx_stop = iwn_ampdu_tx_stop;
550 
551 	/* Override 802.11 state transition machine. */
552 	sc->sc_newstate = ic->ic_newstate;
553 	ic->ic_newstate = iwn_newstate;
554 	ieee80211_media_init(ifp, iwn_media_change, ieee80211_media_status);
555 
556 	sc->amrr.amrr_min_success_threshold =  1;
557 	sc->amrr.amrr_max_success_threshold = 15;
558 
559 #if NBPFILTER > 0
560 	iwn_radiotap_attach(sc);
561 #endif
562 	timeout_set(&sc->calib_to, iwn_calib_timeout, sc);
563 	rw_init(&sc->sc_rwlock, "iwnlock");
564 	task_set(&sc->init_task, iwn_init_task, sc);
565 	return;
566 
567 	/* Free allocated memory if something failed during attachment. */
568 fail4:	while (--i >= 0)
569 		iwn_free_tx_ring(sc, &sc->txq[i]);
570 	iwn_free_sched(sc);
571 fail3:	if (sc->ict != NULL)
572 		iwn_free_ict(sc);
573 fail2:	iwn_free_kw(sc);
574 fail1:	iwn_free_fwmem(sc);
575 }
576 
577 int
578 iwn4965_attach(struct iwn_softc *sc, pci_product_id_t pid)
579 {
580 	struct iwn_ops *ops = &sc->ops;
581 
582 	ops->load_firmware = iwn4965_load_firmware;
583 	ops->read_eeprom = iwn4965_read_eeprom;
584 	ops->post_alive = iwn4965_post_alive;
585 	ops->nic_config = iwn4965_nic_config;
586 	ops->reset_sched = iwn4965_reset_sched;
587 	ops->update_sched = iwn4965_update_sched;
588 	ops->get_temperature = iwn4965_get_temperature;
589 	ops->get_rssi = iwn4965_get_rssi;
590 	ops->set_txpower = iwn4965_set_txpower;
591 	ops->init_gains = iwn4965_init_gains;
592 	ops->set_gains = iwn4965_set_gains;
593 	ops->add_node = iwn4965_add_node;
594 	ops->tx_done = iwn4965_tx_done;
595 	ops->ampdu_tx_start = iwn4965_ampdu_tx_start;
596 	ops->ampdu_tx_stop = iwn4965_ampdu_tx_stop;
597 	sc->ntxqs = IWN4965_NTXQUEUES;
598 	sc->first_agg_txq = IWN4965_FIRST_AGG_TXQUEUE;
599 	sc->ndmachnls = IWN4965_NDMACHNLS;
600 	sc->broadcast_id = IWN4965_ID_BROADCAST;
601 	sc->rxonsz = IWN4965_RXONSZ;
602 	sc->schedsz = IWN4965_SCHEDSZ;
603 	sc->fw_text_maxsz = IWN4965_FW_TEXT_MAXSZ;
604 	sc->fw_data_maxsz = IWN4965_FW_DATA_MAXSZ;
605 	sc->fwsz = IWN4965_FWSZ;
606 	sc->sched_txfact_addr = IWN4965_SCHED_TXFACT;
607 	sc->limits = &iwn4965_sensitivity_limits;
608 	sc->fwname = "iwn-4965";
609 	/* Override chains masks, ROM is known to be broken. */
610 	sc->txchainmask = IWN_ANT_AB;
611 	sc->rxchainmask = IWN_ANT_ABC;
612 
613 	return 0;
614 }
615 
616 int
617 iwn5000_attach(struct iwn_softc *sc, pci_product_id_t pid)
618 {
619 	struct iwn_ops *ops = &sc->ops;
620 
621 	ops->load_firmware = iwn5000_load_firmware;
622 	ops->read_eeprom = iwn5000_read_eeprom;
623 	ops->post_alive = iwn5000_post_alive;
624 	ops->nic_config = iwn5000_nic_config;
625 	ops->reset_sched = iwn5000_reset_sched;
626 	ops->update_sched = iwn5000_update_sched;
627 	ops->get_temperature = iwn5000_get_temperature;
628 	ops->get_rssi = iwn5000_get_rssi;
629 	ops->set_txpower = iwn5000_set_txpower;
630 	ops->init_gains = iwn5000_init_gains;
631 	ops->set_gains = iwn5000_set_gains;
632 	ops->add_node = iwn5000_add_node;
633 	ops->tx_done = iwn5000_tx_done;
634 	ops->ampdu_tx_start = iwn5000_ampdu_tx_start;
635 	ops->ampdu_tx_stop = iwn5000_ampdu_tx_stop;
636 	sc->ntxqs = IWN5000_NTXQUEUES;
637 	sc->first_agg_txq = IWN5000_FIRST_AGG_TXQUEUE;
638 	sc->ndmachnls = IWN5000_NDMACHNLS;
639 	sc->broadcast_id = IWN5000_ID_BROADCAST;
640 	sc->rxonsz = IWN5000_RXONSZ;
641 	sc->schedsz = IWN5000_SCHEDSZ;
642 	sc->fw_text_maxsz = IWN5000_FW_TEXT_MAXSZ;
643 	sc->fw_data_maxsz = IWN5000_FW_DATA_MAXSZ;
644 	sc->fwsz = IWN5000_FWSZ;
645 	sc->sched_txfact_addr = IWN5000_SCHED_TXFACT;
646 
647 	switch (sc->hw_type) {
648 	case IWN_HW_REV_TYPE_5100:
649 		sc->limits = &iwn5000_sensitivity_limits;
650 		sc->fwname = "iwn-5000";
651 		/* Override chains masks, ROM is known to be broken. */
652 		sc->txchainmask = IWN_ANT_B;
653 		sc->rxchainmask = IWN_ANT_AB;
654 		break;
655 	case IWN_HW_REV_TYPE_5150:
656 		sc->limits = &iwn5150_sensitivity_limits;
657 		sc->fwname = "iwn-5150";
658 		break;
659 	case IWN_HW_REV_TYPE_5300:
660 	case IWN_HW_REV_TYPE_5350:
661 		sc->limits = &iwn5000_sensitivity_limits;
662 		sc->fwname = "iwn-5000";
663 		break;
664 	case IWN_HW_REV_TYPE_1000:
665 		sc->limits = &iwn1000_sensitivity_limits;
666 		sc->fwname = "iwn-1000";
667 		break;
668 	case IWN_HW_REV_TYPE_6000:
669 		sc->limits = &iwn6000_sensitivity_limits;
670 		sc->fwname = "iwn-6000";
671 		if (pid == PCI_PRODUCT_INTEL_WL_6200_1 ||
672 		    pid == PCI_PRODUCT_INTEL_WL_6200_2) {
673 			sc->sc_flags |= IWN_FLAG_INTERNAL_PA;
674 			/* Override chains masks, ROM is known to be broken. */
675 			sc->txchainmask = IWN_ANT_BC;
676 			sc->rxchainmask = IWN_ANT_BC;
677 		}
678 		break;
679 	case IWN_HW_REV_TYPE_6050:
680 		sc->limits = &iwn6000_sensitivity_limits;
681 		sc->fwname = "iwn-6050";
682 		break;
683 	case IWN_HW_REV_TYPE_6005:
684 		sc->limits = &iwn6000_sensitivity_limits;
685 		if (pid != PCI_PRODUCT_INTEL_WL_6005_1 &&
686 		    pid != PCI_PRODUCT_INTEL_WL_6005_2) {
687 			sc->fwname = "iwn-6030";
688 			sc->sc_flags |= IWN_FLAG_ADV_BT_COEX;
689 		} else
690 			sc->fwname = "iwn-6005";
691 		break;
692 	case IWN_HW_REV_TYPE_2030:
693 		sc->limits = &iwn2000_sensitivity_limits;
694 		sc->fwname = "iwn-2030";
695 		sc->sc_flags |= IWN_FLAG_ADV_BT_COEX;
696 		break;
697 	case IWN_HW_REV_TYPE_2000:
698 		sc->limits = &iwn2000_sensitivity_limits;
699 		sc->fwname = "iwn-2000";
700 		break;
701 	case IWN_HW_REV_TYPE_135:
702 		sc->limits = &iwn2000_sensitivity_limits;
703 		sc->fwname = "iwn-135";
704 		sc->sc_flags |= IWN_FLAG_ADV_BT_COEX;
705 		break;
706 	case IWN_HW_REV_TYPE_105:
707 		sc->limits = &iwn2000_sensitivity_limits;
708 		sc->fwname = "iwn-105";
709 		break;
710 	default:
711 		printf(": adapter type %d not supported\n", sc->hw_type);
712 		return ENOTSUP;
713 	}
714 	return 0;
715 }
716 
717 #if NBPFILTER > 0
718 /*
719  * Attach the interface to 802.11 radiotap.
720  */
721 void
722 iwn_radiotap_attach(struct iwn_softc *sc)
723 {
724 	bpfattach(&sc->sc_drvbpf, &sc->sc_ic.ic_if, DLT_IEEE802_11_RADIO,
725 	    sizeof (struct ieee80211_frame) + IEEE80211_RADIOTAP_HDRLEN);
726 
727 	sc->sc_rxtap_len = sizeof sc->sc_rxtapu;
728 	sc->sc_rxtap.wr_ihdr.it_len = htole16(sc->sc_rxtap_len);
729 	sc->sc_rxtap.wr_ihdr.it_present = htole32(IWN_RX_RADIOTAP_PRESENT);
730 
731 	sc->sc_txtap_len = sizeof sc->sc_txtapu;
732 	sc->sc_txtap.wt_ihdr.it_len = htole16(sc->sc_txtap_len);
733 	sc->sc_txtap.wt_ihdr.it_present = htole32(IWN_TX_RADIOTAP_PRESENT);
734 }
735 #endif
736 
737 int
738 iwn_detach(struct device *self, int flags)
739 {
740 	struct iwn_softc *sc = (struct iwn_softc *)self;
741 	struct ifnet *ifp = &sc->sc_ic.ic_if;
742 	int qid;
743 
744 	timeout_del(&sc->calib_to);
745 	task_del(systq, &sc->init_task);
746 
747 	/* Uninstall interrupt handler. */
748 	if (sc->sc_ih != NULL)
749 		pci_intr_disestablish(sc->sc_pct, sc->sc_ih);
750 
751 	/* Free DMA resources. */
752 	iwn_free_rx_ring(sc, &sc->rxq);
753 	for (qid = 0; qid < sc->ntxqs; qid++)
754 		iwn_free_tx_ring(sc, &sc->txq[qid]);
755 	iwn_free_sched(sc);
756 	iwn_free_kw(sc);
757 	if (sc->ict != NULL)
758 		iwn_free_ict(sc);
759 	iwn_free_fwmem(sc);
760 
761 	bus_space_unmap(sc->sc_st, sc->sc_sh, sc->sc_sz);
762 
763 	ieee80211_ifdetach(ifp);
764 	if_detach(ifp);
765 
766 	return 0;
767 }
768 
769 int
770 iwn_activate(struct device *self, int act)
771 {
772 	struct iwn_softc *sc = (struct iwn_softc *)self;
773 	struct ifnet *ifp = &sc->sc_ic.ic_if;
774 
775 	switch (act) {
776 	case DVACT_SUSPEND:
777 		if (ifp->if_flags & IFF_RUNNING)
778 			iwn_stop(ifp);
779 		break;
780 	case DVACT_WAKEUP:
781 		iwn_wakeup(sc);
782 		break;
783 	}
784 
785 	return 0;
786 }
787 
788 void
789 iwn_wakeup(struct iwn_softc *sc)
790 {
791 	pcireg_t reg;
792 
793 	/* Clear device-specific "PCI retry timeout" register (41h). */
794 	reg = pci_conf_read(sc->sc_pct, sc->sc_pcitag, 0x40);
795 	if (reg & 0xff00)
796 		pci_conf_write(sc->sc_pct, sc->sc_pcitag, 0x40, reg & ~0xff00);
797 	iwn_init_task(sc);
798 }
799 
800 void
801 iwn_init_task(void *arg1)
802 {
803 	struct iwn_softc *sc = arg1;
804 	struct ifnet *ifp = &sc->sc_ic.ic_if;
805 	int s;
806 
807 	rw_enter_write(&sc->sc_rwlock);
808 	s = splnet();
809 
810 	if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) == IFF_UP)
811 		iwn_init(ifp);
812 
813 	splx(s);
814 	rw_exit_write(&sc->sc_rwlock);
815 }
816 
817 int
818 iwn_nic_lock(struct iwn_softc *sc)
819 {
820 	int ntries;
821 
822 	/* Request exclusive access to NIC. */
823 	IWN_SETBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_MAC_ACCESS_REQ);
824 
825 	/* Spin until we actually get the lock. */
826 	for (ntries = 0; ntries < 1000; ntries++) {
827 		if ((IWN_READ(sc, IWN_GP_CNTRL) &
828 		     (IWN_GP_CNTRL_MAC_ACCESS_ENA | IWN_GP_CNTRL_SLEEP)) ==
829 		    IWN_GP_CNTRL_MAC_ACCESS_ENA)
830 			return 0;
831 		DELAY(10);
832 	}
833 	return ETIMEDOUT;
834 }
835 
836 static __inline void
837 iwn_nic_unlock(struct iwn_softc *sc)
838 {
839 	IWN_CLRBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_MAC_ACCESS_REQ);
840 }
841 
842 static __inline uint32_t
843 iwn_prph_read(struct iwn_softc *sc, uint32_t addr)
844 {
845 	IWN_WRITE(sc, IWN_PRPH_RADDR, IWN_PRPH_DWORD | addr);
846 	IWN_BARRIER_READ_WRITE(sc);
847 	return IWN_READ(sc, IWN_PRPH_RDATA);
848 }
849 
850 static __inline void
851 iwn_prph_write(struct iwn_softc *sc, uint32_t addr, uint32_t data)
852 {
853 	IWN_WRITE(sc, IWN_PRPH_WADDR, IWN_PRPH_DWORD | addr);
854 	IWN_BARRIER_WRITE(sc);
855 	IWN_WRITE(sc, IWN_PRPH_WDATA, data);
856 }
857 
858 static __inline void
859 iwn_prph_setbits(struct iwn_softc *sc, uint32_t addr, uint32_t mask)
860 {
861 	iwn_prph_write(sc, addr, iwn_prph_read(sc, addr) | mask);
862 }
863 
864 static __inline void
865 iwn_prph_clrbits(struct iwn_softc *sc, uint32_t addr, uint32_t mask)
866 {
867 	iwn_prph_write(sc, addr, iwn_prph_read(sc, addr) & ~mask);
868 }
869 
870 static __inline void
871 iwn_prph_write_region_4(struct iwn_softc *sc, uint32_t addr,
872     const uint32_t *data, int count)
873 {
874 	for (; count > 0; count--, data++, addr += 4)
875 		iwn_prph_write(sc, addr, *data);
876 }
877 
878 static __inline uint32_t
879 iwn_mem_read(struct iwn_softc *sc, uint32_t addr)
880 {
881 	IWN_WRITE(sc, IWN_MEM_RADDR, addr);
882 	IWN_BARRIER_READ_WRITE(sc);
883 	return IWN_READ(sc, IWN_MEM_RDATA);
884 }
885 
886 static __inline void
887 iwn_mem_write(struct iwn_softc *sc, uint32_t addr, uint32_t data)
888 {
889 	IWN_WRITE(sc, IWN_MEM_WADDR, addr);
890 	IWN_BARRIER_WRITE(sc);
891 	IWN_WRITE(sc, IWN_MEM_WDATA, data);
892 }
893 
894 static __inline void
895 iwn_mem_write_2(struct iwn_softc *sc, uint32_t addr, uint16_t data)
896 {
897 	uint32_t tmp;
898 
899 	tmp = iwn_mem_read(sc, addr & ~3);
900 	if (addr & 3)
901 		tmp = (tmp & 0x0000ffff) | data << 16;
902 	else
903 		tmp = (tmp & 0xffff0000) | data;
904 	iwn_mem_write(sc, addr & ~3, tmp);
905 }
906 
907 #ifdef IWN_DEBUG
908 
909 static __inline void
910 iwn_mem_read_region_4(struct iwn_softc *sc, uint32_t addr, uint32_t *data,
911     int count)
912 {
913 	for (; count > 0; count--, addr += 4)
914 		*data++ = iwn_mem_read(sc, addr);
915 }
916 
917 #endif
918 
919 static __inline void
920 iwn_mem_set_region_4(struct iwn_softc *sc, uint32_t addr, uint32_t val,
921     int count)
922 {
923 	for (; count > 0; count--, addr += 4)
924 		iwn_mem_write(sc, addr, val);
925 }
926 
927 int
928 iwn_eeprom_lock(struct iwn_softc *sc)
929 {
930 	int i, ntries;
931 
932 	for (i = 0; i < 100; i++) {
933 		/* Request exclusive access to EEPROM. */
934 		IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
935 		    IWN_HW_IF_CONFIG_EEPROM_LOCKED);
936 
937 		/* Spin until we actually get the lock. */
938 		for (ntries = 0; ntries < 100; ntries++) {
939 			if (IWN_READ(sc, IWN_HW_IF_CONFIG) &
940 			    IWN_HW_IF_CONFIG_EEPROM_LOCKED)
941 				return 0;
942 			DELAY(10);
943 		}
944 	}
945 	return ETIMEDOUT;
946 }
947 
948 static __inline void
949 iwn_eeprom_unlock(struct iwn_softc *sc)
950 {
951 	IWN_CLRBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_EEPROM_LOCKED);
952 }
953 
954 /*
955  * Initialize access by host to One Time Programmable ROM.
956  * NB: This kind of ROM can be found on 1000 or 6000 Series only.
957  */
958 int
959 iwn_init_otprom(struct iwn_softc *sc)
960 {
961 	uint16_t prev, base, next;
962 	int count, error;
963 
964 	/* Wait for clock stabilization before accessing prph. */
965 	if ((error = iwn_clock_wait(sc)) != 0)
966 		return error;
967 
968 	if ((error = iwn_nic_lock(sc)) != 0)
969 		return error;
970 	iwn_prph_setbits(sc, IWN_APMG_PS, IWN_APMG_PS_RESET_REQ);
971 	DELAY(5);
972 	iwn_prph_clrbits(sc, IWN_APMG_PS, IWN_APMG_PS_RESET_REQ);
973 	iwn_nic_unlock(sc);
974 
975 	/* Set auto clock gate disable bit for HW with OTP shadow RAM. */
976 	if (sc->hw_type != IWN_HW_REV_TYPE_1000) {
977 		IWN_SETBITS(sc, IWN_DBG_LINK_PWR_MGMT,
978 		    IWN_RESET_LINK_PWR_MGMT_DIS);
979 	}
980 	IWN_CLRBITS(sc, IWN_EEPROM_GP, IWN_EEPROM_GP_IF_OWNER);
981 	/* Clear ECC status. */
982 	IWN_SETBITS(sc, IWN_OTP_GP,
983 	    IWN_OTP_GP_ECC_CORR_STTS | IWN_OTP_GP_ECC_UNCORR_STTS);
984 
985 	/*
986 	 * Find the block before last block (contains the EEPROM image)
987 	 * for HW without OTP shadow RAM.
988 	 */
989 	if (sc->hw_type == IWN_HW_REV_TYPE_1000) {
990 		/* Switch to absolute addressing mode. */
991 		IWN_CLRBITS(sc, IWN_OTP_GP, IWN_OTP_GP_RELATIVE_ACCESS);
992 		base = 0;
993 		for (count = 0; count < IWN1000_OTP_NBLOCKS; count++) {
994 			error = iwn_read_prom_data(sc, base, &next, 2);
995 			if (error != 0)
996 				return error;
997 			if (next == 0)	/* End of linked-list. */
998 				break;
999 			prev = base;
1000 			base = letoh16(next);
1001 		}
1002 		if (count == 0 || count == IWN1000_OTP_NBLOCKS)
1003 			return EIO;
1004 		/* Skip "next" word. */
1005 		sc->prom_base = prev + 1;
1006 	}
1007 	return 0;
1008 }
1009 
1010 int
1011 iwn_read_prom_data(struct iwn_softc *sc, uint32_t addr, void *data, int count)
1012 {
1013 	uint8_t *out = data;
1014 	uint32_t val, tmp;
1015 	int ntries;
1016 
1017 	addr += sc->prom_base;
1018 	for (; count > 0; count -= 2, addr++) {
1019 		IWN_WRITE(sc, IWN_EEPROM, addr << 2);
1020 		for (ntries = 0; ntries < 10; ntries++) {
1021 			val = IWN_READ(sc, IWN_EEPROM);
1022 			if (val & IWN_EEPROM_READ_VALID)
1023 				break;
1024 			DELAY(5);
1025 		}
1026 		if (ntries == 10) {
1027 			printf("%s: timeout reading ROM at 0x%x\n",
1028 			    sc->sc_dev.dv_xname, addr);
1029 			return ETIMEDOUT;
1030 		}
1031 		if (sc->sc_flags & IWN_FLAG_HAS_OTPROM) {
1032 			/* OTPROM, check for ECC errors. */
1033 			tmp = IWN_READ(sc, IWN_OTP_GP);
1034 			if (tmp & IWN_OTP_GP_ECC_UNCORR_STTS) {
1035 				printf("%s: OTPROM ECC error at 0x%x\n",
1036 				    sc->sc_dev.dv_xname, addr);
1037 				return EIO;
1038 			}
1039 			if (tmp & IWN_OTP_GP_ECC_CORR_STTS) {
1040 				/* Correctable ECC error, clear bit. */
1041 				IWN_SETBITS(sc, IWN_OTP_GP,
1042 				    IWN_OTP_GP_ECC_CORR_STTS);
1043 			}
1044 		}
1045 		*out++ = val >> 16;
1046 		if (count > 1)
1047 			*out++ = val >> 24;
1048 	}
1049 	return 0;
1050 }
1051 
1052 int
1053 iwn_dma_contig_alloc(bus_dma_tag_t tag, struct iwn_dma_info *dma, void **kvap,
1054     bus_size_t size, bus_size_t alignment)
1055 {
1056 	int nsegs, error;
1057 
1058 	dma->tag = tag;
1059 	dma->size = size;
1060 
1061 	error = bus_dmamap_create(tag, size, 1, size, 0, BUS_DMA_NOWAIT,
1062 	    &dma->map);
1063 	if (error != 0)
1064 		goto fail;
1065 
1066 	error = bus_dmamem_alloc(tag, size, alignment, 0, &dma->seg, 1, &nsegs,
1067 	    BUS_DMA_NOWAIT | BUS_DMA_ZERO);
1068 	if (error != 0)
1069 		goto fail;
1070 
1071 	error = bus_dmamem_map(tag, &dma->seg, 1, size, &dma->vaddr,
1072 	    BUS_DMA_NOWAIT | BUS_DMA_COHERENT);
1073 	if (error != 0)
1074 		goto fail;
1075 
1076 	error = bus_dmamap_load_raw(tag, dma->map, &dma->seg, 1, size,
1077 	    BUS_DMA_NOWAIT);
1078 	if (error != 0)
1079 		goto fail;
1080 
1081 	bus_dmamap_sync(tag, dma->map, 0, size, BUS_DMASYNC_PREWRITE);
1082 
1083 	dma->paddr = dma->map->dm_segs[0].ds_addr;
1084 	if (kvap != NULL)
1085 		*kvap = dma->vaddr;
1086 
1087 	return 0;
1088 
1089 fail:	iwn_dma_contig_free(dma);
1090 	return error;
1091 }
1092 
1093 void
1094 iwn_dma_contig_free(struct iwn_dma_info *dma)
1095 {
1096 	if (dma->map != NULL) {
1097 		if (dma->vaddr != NULL) {
1098 			bus_dmamap_sync(dma->tag, dma->map, 0, dma->size,
1099 			    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
1100 			bus_dmamap_unload(dma->tag, dma->map);
1101 			bus_dmamem_unmap(dma->tag, dma->vaddr, dma->size);
1102 			bus_dmamem_free(dma->tag, &dma->seg, 1);
1103 			dma->vaddr = NULL;
1104 		}
1105 		bus_dmamap_destroy(dma->tag, dma->map);
1106 		dma->map = NULL;
1107 	}
1108 }
1109 
1110 int
1111 iwn_alloc_sched(struct iwn_softc *sc)
1112 {
1113 	/* TX scheduler rings must be aligned on a 1KB boundary. */
1114 	return iwn_dma_contig_alloc(sc->sc_dmat, &sc->sched_dma,
1115 	    (void **)&sc->sched, sc->schedsz, 1024);
1116 }
1117 
1118 void
1119 iwn_free_sched(struct iwn_softc *sc)
1120 {
1121 	iwn_dma_contig_free(&sc->sched_dma);
1122 }
1123 
1124 int
1125 iwn_alloc_kw(struct iwn_softc *sc)
1126 {
1127 	/* "Keep Warm" page must be aligned on a 4KB boundary. */
1128 	return iwn_dma_contig_alloc(sc->sc_dmat, &sc->kw_dma, NULL, 4096,
1129 	    4096);
1130 }
1131 
1132 void
1133 iwn_free_kw(struct iwn_softc *sc)
1134 {
1135 	iwn_dma_contig_free(&sc->kw_dma);
1136 }
1137 
1138 int
1139 iwn_alloc_ict(struct iwn_softc *sc)
1140 {
1141 	/* ICT table must be aligned on a 4KB boundary. */
1142 	return iwn_dma_contig_alloc(sc->sc_dmat, &sc->ict_dma,
1143 	    (void **)&sc->ict, IWN_ICT_SIZE, 4096);
1144 }
1145 
1146 void
1147 iwn_free_ict(struct iwn_softc *sc)
1148 {
1149 	iwn_dma_contig_free(&sc->ict_dma);
1150 }
1151 
1152 int
1153 iwn_alloc_fwmem(struct iwn_softc *sc)
1154 {
1155 	/* Must be aligned on a 16-byte boundary. */
1156 	return iwn_dma_contig_alloc(sc->sc_dmat, &sc->fw_dma, NULL,
1157 	    sc->fwsz, 16);
1158 }
1159 
1160 void
1161 iwn_free_fwmem(struct iwn_softc *sc)
1162 {
1163 	iwn_dma_contig_free(&sc->fw_dma);
1164 }
1165 
1166 int
1167 iwn_alloc_rx_ring(struct iwn_softc *sc, struct iwn_rx_ring *ring)
1168 {
1169 	bus_size_t size;
1170 	int i, error;
1171 
1172 	ring->cur = 0;
1173 
1174 	/* Allocate RX descriptors (256-byte aligned). */
1175 	size = IWN_RX_RING_COUNT * sizeof (uint32_t);
1176 	error = iwn_dma_contig_alloc(sc->sc_dmat, &ring->desc_dma,
1177 	    (void **)&ring->desc, size, 256);
1178 	if (error != 0) {
1179 		printf("%s: could not allocate RX ring DMA memory\n",
1180 		    sc->sc_dev.dv_xname);
1181 		goto fail;
1182 	}
1183 
1184 	/* Allocate RX status area (16-byte aligned). */
1185 	error = iwn_dma_contig_alloc(sc->sc_dmat, &ring->stat_dma,
1186 	    (void **)&ring->stat, sizeof (struct iwn_rx_status), 16);
1187 	if (error != 0) {
1188 		printf("%s: could not allocate RX status DMA memory\n",
1189 		    sc->sc_dev.dv_xname);
1190 		goto fail;
1191 	}
1192 
1193 	/*
1194 	 * Allocate and map RX buffers.
1195 	 */
1196 	for (i = 0; i < IWN_RX_RING_COUNT; i++) {
1197 		struct iwn_rx_data *data = &ring->data[i];
1198 
1199 		error = bus_dmamap_create(sc->sc_dmat, IWN_RBUF_SIZE, 1,
1200 		    IWN_RBUF_SIZE, 0, BUS_DMA_NOWAIT | BUS_DMA_ALLOCNOW,
1201 		    &data->map);
1202 		if (error != 0) {
1203 			printf("%s: could not create RX buf DMA map\n",
1204 			    sc->sc_dev.dv_xname);
1205 			goto fail;
1206 		}
1207 
1208 		data->m = MCLGETL(NULL, M_DONTWAIT, IWN_RBUF_SIZE);
1209 		if (data->m == NULL) {
1210 			printf("%s: could not allocate RX mbuf\n",
1211 			    sc->sc_dev.dv_xname);
1212 			error = ENOBUFS;
1213 			goto fail;
1214 		}
1215 
1216 		error = bus_dmamap_load(sc->sc_dmat, data->map,
1217 		    mtod(data->m, void *), IWN_RBUF_SIZE, NULL,
1218 		    BUS_DMA_NOWAIT | BUS_DMA_READ);
1219 		if (error != 0) {
1220 			printf("%s: can't map mbuf (error %d)\n",
1221 			    sc->sc_dev.dv_xname, error);
1222 			goto fail;
1223 		}
1224 
1225 		/* Set physical address of RX buffer (256-byte aligned). */
1226 		ring->desc[i] = htole32(data->map->dm_segs[0].ds_addr >> 8);
1227 	}
1228 
1229 	bus_dmamap_sync(sc->sc_dmat, ring->desc_dma.map, 0, size,
1230 	    BUS_DMASYNC_PREWRITE);
1231 
1232 	return 0;
1233 
1234 fail:	iwn_free_rx_ring(sc, ring);
1235 	return error;
1236 }
1237 
1238 void
1239 iwn_reset_rx_ring(struct iwn_softc *sc, struct iwn_rx_ring *ring)
1240 {
1241 	int ntries;
1242 
1243 	if (iwn_nic_lock(sc) == 0) {
1244 		IWN_WRITE(sc, IWN_FH_RX_CONFIG, 0);
1245 		for (ntries = 0; ntries < 1000; ntries++) {
1246 			if (IWN_READ(sc, IWN_FH_RX_STATUS) &
1247 			    IWN_FH_RX_STATUS_IDLE)
1248 				break;
1249 			DELAY(10);
1250 		}
1251 		iwn_nic_unlock(sc);
1252 	}
1253 	ring->cur = 0;
1254 	sc->last_rx_valid = 0;
1255 }
1256 
1257 void
1258 iwn_free_rx_ring(struct iwn_softc *sc, struct iwn_rx_ring *ring)
1259 {
1260 	int i;
1261 
1262 	iwn_dma_contig_free(&ring->desc_dma);
1263 	iwn_dma_contig_free(&ring->stat_dma);
1264 
1265 	for (i = 0; i < IWN_RX_RING_COUNT; i++) {
1266 		struct iwn_rx_data *data = &ring->data[i];
1267 
1268 		if (data->m != NULL) {
1269 			bus_dmamap_sync(sc->sc_dmat, data->map, 0,
1270 			    data->map->dm_mapsize, BUS_DMASYNC_POSTREAD);
1271 			bus_dmamap_unload(sc->sc_dmat, data->map);
1272 			m_freem(data->m);
1273 		}
1274 		if (data->map != NULL)
1275 			bus_dmamap_destroy(sc->sc_dmat, data->map);
1276 	}
1277 }
1278 
1279 int
1280 iwn_alloc_tx_ring(struct iwn_softc *sc, struct iwn_tx_ring *ring, int qid)
1281 {
1282 	bus_addr_t paddr;
1283 	bus_size_t size;
1284 	int i, error;
1285 
1286 	ring->qid = qid;
1287 	ring->queued = 0;
1288 	ring->cur = 0;
1289 
1290 	/* Allocate TX descriptors (256-byte aligned). */
1291 	size = IWN_TX_RING_COUNT * sizeof (struct iwn_tx_desc);
1292 	error = iwn_dma_contig_alloc(sc->sc_dmat, &ring->desc_dma,
1293 	    (void **)&ring->desc, size, 256);
1294 	if (error != 0) {
1295 		printf("%s: could not allocate TX ring DMA memory\n",
1296 		    sc->sc_dev.dv_xname);
1297 		goto fail;
1298 	}
1299 
1300 	size = IWN_TX_RING_COUNT * sizeof (struct iwn_tx_cmd);
1301 	error = iwn_dma_contig_alloc(sc->sc_dmat, &ring->cmd_dma,
1302 	    (void **)&ring->cmd, size, 4);
1303 	if (error != 0) {
1304 		printf("%s: could not allocate TX cmd DMA memory\n",
1305 		    sc->sc_dev.dv_xname);
1306 		goto fail;
1307 	}
1308 
1309 	paddr = ring->cmd_dma.paddr;
1310 	for (i = 0; i < IWN_TX_RING_COUNT; i++) {
1311 		struct iwn_tx_data *data = &ring->data[i];
1312 
1313 		data->cmd_paddr = paddr;
1314 		data->scratch_paddr = paddr + 12;
1315 		paddr += sizeof (struct iwn_tx_cmd);
1316 
1317 		error = bus_dmamap_create(sc->sc_dmat, MCLBYTES,
1318 		    IWN_MAX_SCATTER - 1, MCLBYTES, 0, BUS_DMA_NOWAIT,
1319 		    &data->map);
1320 		if (error != 0) {
1321 			printf("%s: could not create TX buf DMA map\n",
1322 			    sc->sc_dev.dv_xname);
1323 			goto fail;
1324 		}
1325 	}
1326 	return 0;
1327 
1328 fail:	iwn_free_tx_ring(sc, ring);
1329 	return error;
1330 }
1331 
1332 void
1333 iwn_reset_tx_ring(struct iwn_softc *sc, struct iwn_tx_ring *ring)
1334 {
1335 	int i;
1336 
1337 	for (i = 0; i < IWN_TX_RING_COUNT; i++) {
1338 		struct iwn_tx_data *data = &ring->data[i];
1339 
1340 		if (data->m != NULL) {
1341 			bus_dmamap_sync(sc->sc_dmat, data->map, 0,
1342 			    data->map->dm_mapsize, BUS_DMASYNC_POSTWRITE);
1343 			bus_dmamap_unload(sc->sc_dmat, data->map);
1344 			m_freem(data->m);
1345 			data->m = NULL;
1346 		}
1347 	}
1348 	/* Clear TX descriptors. */
1349 	memset(ring->desc, 0, ring->desc_dma.size);
1350 	bus_dmamap_sync(sc->sc_dmat, ring->desc_dma.map, 0,
1351 	    ring->desc_dma.size, BUS_DMASYNC_PREWRITE);
1352 	sc->qfullmsk &= ~(1 << ring->qid);
1353 	ring->queued = 0;
1354 	ring->cur = 0;
1355 }
1356 
1357 void
1358 iwn_free_tx_ring(struct iwn_softc *sc, struct iwn_tx_ring *ring)
1359 {
1360 	int i;
1361 
1362 	iwn_dma_contig_free(&ring->desc_dma);
1363 	iwn_dma_contig_free(&ring->cmd_dma);
1364 
1365 	for (i = 0; i < IWN_TX_RING_COUNT; i++) {
1366 		struct iwn_tx_data *data = &ring->data[i];
1367 
1368 		if (data->m != NULL) {
1369 			bus_dmamap_sync(sc->sc_dmat, data->map, 0,
1370 			    data->map->dm_mapsize, BUS_DMASYNC_POSTWRITE);
1371 			bus_dmamap_unload(sc->sc_dmat, data->map);
1372 			m_freem(data->m);
1373 		}
1374 		if (data->map != NULL)
1375 			bus_dmamap_destroy(sc->sc_dmat, data->map);
1376 	}
1377 }
1378 
1379 void
1380 iwn5000_ict_reset(struct iwn_softc *sc)
1381 {
1382 	/* Disable interrupts. */
1383 	IWN_WRITE(sc, IWN_INT_MASK, 0);
1384 
1385 	/* Reset ICT table. */
1386 	memset(sc->ict, 0, IWN_ICT_SIZE);
1387 	sc->ict_cur = 0;
1388 
1389 	/* Set physical address of ICT table (4KB aligned). */
1390 	DPRINTF(("enabling ICT\n"));
1391 	IWN_WRITE(sc, IWN_DRAM_INT_TBL, IWN_DRAM_INT_TBL_ENABLE |
1392 	    IWN_DRAM_INT_TBL_WRAP_CHECK | sc->ict_dma.paddr >> 12);
1393 
1394 	/* Enable periodic RX interrupt. */
1395 	sc->int_mask |= IWN_INT_RX_PERIODIC;
1396 	/* Switch to ICT interrupt mode in driver. */
1397 	sc->sc_flags |= IWN_FLAG_USE_ICT;
1398 
1399 	/* Re-enable interrupts. */
1400 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
1401 	IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
1402 }
1403 
1404 int
1405 iwn_read_eeprom(struct iwn_softc *sc)
1406 {
1407 	struct iwn_ops *ops = &sc->ops;
1408 	struct ieee80211com *ic = &sc->sc_ic;
1409 	uint16_t val;
1410 	int error;
1411 
1412 	/* Check whether adapter has an EEPROM or an OTPROM. */
1413 	if (sc->hw_type >= IWN_HW_REV_TYPE_1000 &&
1414 	    (IWN_READ(sc, IWN_OTP_GP) & IWN_OTP_GP_DEV_SEL_OTP))
1415 		sc->sc_flags |= IWN_FLAG_HAS_OTPROM;
1416 	DPRINTF(("%s found\n", (sc->sc_flags & IWN_FLAG_HAS_OTPROM) ?
1417 	    "OTPROM" : "EEPROM"));
1418 
1419 	/* Adapter has to be powered on for EEPROM access to work. */
1420 	if ((error = iwn_apm_init(sc)) != 0) {
1421 		printf("%s: could not power ON adapter\n",
1422 		    sc->sc_dev.dv_xname);
1423 		return error;
1424 	}
1425 
1426 	if ((IWN_READ(sc, IWN_EEPROM_GP) & 0x7) == 0) {
1427 		printf("%s: bad ROM signature\n", sc->sc_dev.dv_xname);
1428 		return EIO;
1429 	}
1430 	if ((error = iwn_eeprom_lock(sc)) != 0) {
1431 		printf("%s: could not lock ROM (error=%d)\n",
1432 		    sc->sc_dev.dv_xname, error);
1433 		return error;
1434 	}
1435 	if (sc->sc_flags & IWN_FLAG_HAS_OTPROM) {
1436 		if ((error = iwn_init_otprom(sc)) != 0) {
1437 			printf("%s: could not initialize OTPROM\n",
1438 			    sc->sc_dev.dv_xname);
1439 			return error;
1440 		}
1441 	}
1442 
1443 	iwn_read_prom_data(sc, IWN_EEPROM_SKU_CAP, &val, 2);
1444 	DPRINTF(("SKU capabilities=0x%04x\n", letoh16(val)));
1445 	/* Check if HT support is bonded out. */
1446 	if (val & htole16(IWN_EEPROM_SKU_CAP_11N))
1447 		sc->sc_flags |= IWN_FLAG_HAS_11N;
1448 
1449 	iwn_read_prom_data(sc, IWN_EEPROM_RFCFG, &val, 2);
1450 	sc->rfcfg = letoh16(val);
1451 	DPRINTF(("radio config=0x%04x\n", sc->rfcfg));
1452 	/* Read Tx/Rx chains from ROM unless it's known to be broken. */
1453 	if (sc->txchainmask == 0)
1454 		sc->txchainmask = IWN_RFCFG_TXANTMSK(sc->rfcfg);
1455 	if (sc->rxchainmask == 0)
1456 		sc->rxchainmask = IWN_RFCFG_RXANTMSK(sc->rfcfg);
1457 
1458 	/* Read MAC address. */
1459 	iwn_read_prom_data(sc, IWN_EEPROM_MAC, ic->ic_myaddr, 6);
1460 
1461 	/* Read adapter-specific information from EEPROM. */
1462 	ops->read_eeprom(sc);
1463 
1464 	iwn_apm_stop(sc);	/* Power OFF adapter. */
1465 
1466 	iwn_eeprom_unlock(sc);
1467 	return 0;
1468 }
1469 
1470 void
1471 iwn4965_read_eeprom(struct iwn_softc *sc)
1472 {
1473 	uint32_t addr;
1474 	uint16_t val;
1475 	int i;
1476 
1477 	/* Read regulatory domain (4 ASCII characters). */
1478 	iwn_read_prom_data(sc, IWN4965_EEPROM_DOMAIN, sc->eeprom_domain, 4);
1479 
1480 	/* Read the list of authorized channels (20MHz ones only). */
1481 	for (i = 0; i < 5; i++) {
1482 		addr = iwn4965_regulatory_bands[i];
1483 		iwn_read_eeprom_channels(sc, i, addr);
1484 	}
1485 
1486 	/* Read maximum allowed TX power for 2GHz and 5GHz bands. */
1487 	iwn_read_prom_data(sc, IWN4965_EEPROM_MAXPOW, &val, 2);
1488 	sc->maxpwr2GHz = val & 0xff;
1489 	sc->maxpwr5GHz = val >> 8;
1490 	/* Check that EEPROM values are within valid range. */
1491 	if (sc->maxpwr5GHz < 20 || sc->maxpwr5GHz > 50)
1492 		sc->maxpwr5GHz = 38;
1493 	if (sc->maxpwr2GHz < 20 || sc->maxpwr2GHz > 50)
1494 		sc->maxpwr2GHz = 38;
1495 	DPRINTF(("maxpwr 2GHz=%d 5GHz=%d\n", sc->maxpwr2GHz, sc->maxpwr5GHz));
1496 
1497 	/* Read samples for each TX power group. */
1498 	iwn_read_prom_data(sc, IWN4965_EEPROM_BANDS, sc->bands,
1499 	    sizeof sc->bands);
1500 
1501 	/* Read voltage at which samples were taken. */
1502 	iwn_read_prom_data(sc, IWN4965_EEPROM_VOLTAGE, &val, 2);
1503 	sc->eeprom_voltage = (int16_t)letoh16(val);
1504 	DPRINTF(("voltage=%d (in 0.3V)\n", sc->eeprom_voltage));
1505 
1506 #ifdef IWN_DEBUG
1507 	/* Print samples. */
1508 	if (iwn_debug > 0) {
1509 		for (i = 0; i < IWN_NBANDS; i++)
1510 			iwn4965_print_power_group(sc, i);
1511 	}
1512 #endif
1513 }
1514 
1515 #ifdef IWN_DEBUG
1516 void
1517 iwn4965_print_power_group(struct iwn_softc *sc, int i)
1518 {
1519 	struct iwn4965_eeprom_band *band = &sc->bands[i];
1520 	struct iwn4965_eeprom_chan_samples *chans = band->chans;
1521 	int j, c;
1522 
1523 	printf("===band %d===\n", i);
1524 	printf("chan lo=%d, chan hi=%d\n", band->lo, band->hi);
1525 	printf("chan1 num=%d\n", chans[0].num);
1526 	for (c = 0; c < 2; c++) {
1527 		for (j = 0; j < IWN_NSAMPLES; j++) {
1528 			printf("chain %d, sample %d: temp=%d gain=%d "
1529 			    "power=%d pa_det=%d\n", c, j,
1530 			    chans[0].samples[c][j].temp,
1531 			    chans[0].samples[c][j].gain,
1532 			    chans[0].samples[c][j].power,
1533 			    chans[0].samples[c][j].pa_det);
1534 		}
1535 	}
1536 	printf("chan2 num=%d\n", chans[1].num);
1537 	for (c = 0; c < 2; c++) {
1538 		for (j = 0; j < IWN_NSAMPLES; j++) {
1539 			printf("chain %d, sample %d: temp=%d gain=%d "
1540 			    "power=%d pa_det=%d\n", c, j,
1541 			    chans[1].samples[c][j].temp,
1542 			    chans[1].samples[c][j].gain,
1543 			    chans[1].samples[c][j].power,
1544 			    chans[1].samples[c][j].pa_det);
1545 		}
1546 	}
1547 }
1548 #endif
1549 
1550 void
1551 iwn5000_read_eeprom(struct iwn_softc *sc)
1552 {
1553 	struct iwn5000_eeprom_calib_hdr hdr;
1554 	int32_t volt;
1555 	uint32_t base, addr;
1556 	uint16_t val;
1557 	int i;
1558 
1559 	/* Read regulatory domain (4 ASCII characters). */
1560 	iwn_read_prom_data(sc, IWN5000_EEPROM_REG, &val, 2);
1561 	base = letoh16(val);
1562 	iwn_read_prom_data(sc, base + IWN5000_EEPROM_DOMAIN,
1563 	    sc->eeprom_domain, 4);
1564 
1565 	/* Read the list of authorized channels (20MHz ones only). */
1566 	for (i = 0; i < 5; i++) {
1567 		addr = base + iwn5000_regulatory_bands[i];
1568 		iwn_read_eeprom_channels(sc, i, addr);
1569 	}
1570 
1571 	/* Read enhanced TX power information for 6000 Series. */
1572 	if (sc->hw_type >= IWN_HW_REV_TYPE_6000)
1573 		iwn_read_eeprom_enhinfo(sc);
1574 
1575 	iwn_read_prom_data(sc, IWN5000_EEPROM_CAL, &val, 2);
1576 	base = letoh16(val);
1577 	iwn_read_prom_data(sc, base, &hdr, sizeof hdr);
1578 	DPRINTF(("calib version=%u pa type=%u voltage=%u\n",
1579 	    hdr.version, hdr.pa_type, letoh16(hdr.volt)));
1580 	sc->calib_ver = hdr.version;
1581 
1582 	if (sc->hw_type == IWN_HW_REV_TYPE_2030 ||
1583 	    sc->hw_type == IWN_HW_REV_TYPE_2000 ||
1584 	    sc->hw_type == IWN_HW_REV_TYPE_135 ||
1585 	    sc->hw_type == IWN_HW_REV_TYPE_105) {
1586 		sc->eeprom_voltage = letoh16(hdr.volt);
1587 		iwn_read_prom_data(sc, base + IWN5000_EEPROM_TEMP, &val, 2);
1588 		sc->eeprom_temp = letoh16(val);
1589 		iwn_read_prom_data(sc, base + IWN2000_EEPROM_RAWTEMP, &val, 2);
1590 		sc->eeprom_rawtemp = letoh16(val);
1591 	}
1592 
1593 	if (sc->hw_type == IWN_HW_REV_TYPE_5150) {
1594 		/* Compute temperature offset. */
1595 		iwn_read_prom_data(sc, base + IWN5000_EEPROM_TEMP, &val, 2);
1596 		sc->eeprom_temp = letoh16(val);
1597 		iwn_read_prom_data(sc, base + IWN5000_EEPROM_VOLT, &val, 2);
1598 		volt = letoh16(val);
1599 		sc->temp_off = sc->eeprom_temp - (volt / -5);
1600 		DPRINTF(("temp=%d volt=%d offset=%dK\n",
1601 		    sc->eeprom_temp, volt, sc->temp_off));
1602 	} else {
1603 		/* Read crystal calibration. */
1604 		iwn_read_prom_data(sc, base + IWN5000_EEPROM_CRYSTAL,
1605 		    &sc->eeprom_crystal, sizeof (uint32_t));
1606 		DPRINTF(("crystal calibration 0x%08x\n",
1607 		    letoh32(sc->eeprom_crystal)));
1608 	}
1609 }
1610 
1611 void
1612 iwn_read_eeprom_channels(struct iwn_softc *sc, int n, uint32_t addr)
1613 {
1614 	struct ieee80211com *ic = &sc->sc_ic;
1615 	const struct iwn_chan_band *band = &iwn_bands[n];
1616 	struct iwn_eeprom_chan channels[IWN_MAX_CHAN_PER_BAND];
1617 	uint8_t chan;
1618 	int i;
1619 
1620 	iwn_read_prom_data(sc, addr, channels,
1621 	    band->nchan * sizeof (struct iwn_eeprom_chan));
1622 
1623 	for (i = 0; i < band->nchan; i++) {
1624 		if (!(channels[i].flags & IWN_EEPROM_CHAN_VALID))
1625 			continue;
1626 
1627 		chan = band->chan[i];
1628 
1629 		if (n == 0) {	/* 2GHz band */
1630 			ic->ic_channels[chan].ic_freq =
1631 			    ieee80211_ieee2mhz(chan, IEEE80211_CHAN_2GHZ);
1632 			ic->ic_channels[chan].ic_flags =
1633 			    IEEE80211_CHAN_CCK | IEEE80211_CHAN_OFDM |
1634 			    IEEE80211_CHAN_DYN | IEEE80211_CHAN_2GHZ;
1635 
1636 		} else {	/* 5GHz band */
1637 			/*
1638 			 * Some adapters support channels 7, 8, 11 and 12
1639 			 * both in the 2GHz and 4.9GHz bands.
1640 			 * Because of limitations in our net80211 layer,
1641 			 * we don't support them in the 4.9GHz band.
1642 			 */
1643 			if (chan <= 14)
1644 				continue;
1645 
1646 			ic->ic_channels[chan].ic_freq =
1647 			    ieee80211_ieee2mhz(chan, IEEE80211_CHAN_5GHZ);
1648 			ic->ic_channels[chan].ic_flags = IEEE80211_CHAN_A;
1649 			/* We have at least one valid 5GHz channel. */
1650 			sc->sc_flags |= IWN_FLAG_HAS_5GHZ;
1651 		}
1652 
1653 		/* Is active scan allowed on this channel? */
1654 		if (!(channels[i].flags & IWN_EEPROM_CHAN_ACTIVE)) {
1655 			ic->ic_channels[chan].ic_flags |=
1656 			    IEEE80211_CHAN_PASSIVE;
1657 		}
1658 
1659 		/* Save maximum allowed TX power for this channel. */
1660 		sc->maxpwr[chan] = channels[i].maxpwr;
1661 
1662 		if (sc->sc_flags & IWN_FLAG_HAS_11N)
1663 			ic->ic_channels[chan].ic_flags |= IEEE80211_CHAN_HT;
1664 
1665 		DPRINTF(("adding chan %d flags=0x%x maxpwr=%d\n",
1666 		    chan, channels[i].flags, sc->maxpwr[chan]));
1667 	}
1668 }
1669 
1670 void
1671 iwn_read_eeprom_enhinfo(struct iwn_softc *sc)
1672 {
1673 	struct iwn_eeprom_enhinfo enhinfo[35];
1674 	uint16_t val, base;
1675 	int8_t maxpwr;
1676 	int i;
1677 
1678 	iwn_read_prom_data(sc, IWN5000_EEPROM_REG, &val, 2);
1679 	base = letoh16(val);
1680 	iwn_read_prom_data(sc, base + IWN6000_EEPROM_ENHINFO,
1681 	    enhinfo, sizeof enhinfo);
1682 
1683 	memset(sc->enh_maxpwr, 0, sizeof sc->enh_maxpwr);
1684 	for (i = 0; i < nitems(enhinfo); i++) {
1685 		if (enhinfo[i].chan == 0 || enhinfo[i].reserved != 0)
1686 			continue;	/* Skip invalid entries. */
1687 
1688 		maxpwr = 0;
1689 		if (sc->txchainmask & IWN_ANT_A)
1690 			maxpwr = MAX(maxpwr, enhinfo[i].chain[0]);
1691 		if (sc->txchainmask & IWN_ANT_B)
1692 			maxpwr = MAX(maxpwr, enhinfo[i].chain[1]);
1693 		if (sc->txchainmask & IWN_ANT_C)
1694 			maxpwr = MAX(maxpwr, enhinfo[i].chain[2]);
1695 		if (sc->ntxchains == 2)
1696 			maxpwr = MAX(maxpwr, enhinfo[i].mimo2);
1697 		else if (sc->ntxchains == 3)
1698 			maxpwr = MAX(maxpwr, enhinfo[i].mimo3);
1699 		maxpwr /= 2;	/* Convert half-dBm to dBm. */
1700 
1701 		DPRINTF(("enhinfo %d, maxpwr=%d\n", i, maxpwr));
1702 		sc->enh_maxpwr[i] = maxpwr;
1703 	}
1704 }
1705 
1706 struct ieee80211_node *
1707 iwn_node_alloc(struct ieee80211com *ic)
1708 {
1709 	return malloc(sizeof (struct iwn_node), M_DEVBUF, M_NOWAIT | M_ZERO);
1710 }
1711 
1712 void
1713 iwn_newassoc(struct ieee80211com *ic, struct ieee80211_node *ni, int isnew)
1714 {
1715 	struct iwn_softc *sc = ic->ic_if.if_softc;
1716 	struct iwn_node *wn = (void *)ni;
1717 	uint8_t rate;
1718 	int ridx, i;
1719 
1720 	if ((ni->ni_flags & IEEE80211_NODE_HT) == 0)
1721 		ieee80211_amrr_node_init(&sc->amrr, &wn->amn);
1722 
1723 	/* Start at lowest available bit-rate, AMRR/MiRA will raise. */
1724 	ni->ni_txrate = 0;
1725 	ni->ni_txmcs = 0;
1726 
1727 	for (i = 0; i < ni->ni_rates.rs_nrates; i++) {
1728 		rate = ni->ni_rates.rs_rates[i] & IEEE80211_RATE_VAL;
1729 		/* Map 802.11 rate to HW rate index. */
1730 		for (ridx = 0; ridx <= IWN_RIDX_MAX; ridx++) {
1731 			if (iwn_rates[ridx].plcp != IWN_PLCP_INVALID &&
1732 			    iwn_rates[ridx].rate == rate)
1733 				break;
1734 		}
1735 		wn->ridx[i] = ridx;
1736 	}
1737 }
1738 
1739 int
1740 iwn_media_change(struct ifnet *ifp)
1741 {
1742 	struct iwn_softc *sc = ifp->if_softc;
1743 	struct ieee80211com *ic = &sc->sc_ic;
1744 	uint8_t rate, ridx;
1745 	int error;
1746 
1747 	error = ieee80211_media_change(ifp);
1748 	if (error != ENETRESET)
1749 		return error;
1750 
1751 	if (ic->ic_fixed_mcs != -1)
1752 		sc->fixed_ridx = iwn_mcs2ridx[ic->ic_fixed_mcs];
1753 	if (ic->ic_fixed_rate != -1) {
1754 		rate = ic->ic_sup_rates[ic->ic_curmode].
1755 		    rs_rates[ic->ic_fixed_rate] & IEEE80211_RATE_VAL;
1756 		/* Map 802.11 rate to HW rate index. */
1757 		for (ridx = 0; ridx <= IWN_RIDX_MAX; ridx++)
1758 			if (iwn_rates[ridx].plcp != IWN_PLCP_INVALID &&
1759 			    iwn_rates[ridx].rate == rate)
1760 				break;
1761 		sc->fixed_ridx = ridx;
1762 	}
1763 
1764 	if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
1765 	    (IFF_UP | IFF_RUNNING)) {
1766 		iwn_stop(ifp);
1767 		error = iwn_init(ifp);
1768 	}
1769 	return error;
1770 }
1771 
1772 int
1773 iwn_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
1774 {
1775 	struct ifnet *ifp = &ic->ic_if;
1776 	struct iwn_softc *sc = ifp->if_softc;
1777 	struct ieee80211_node *ni = ic->ic_bss;
1778 	int error;
1779 
1780 	if (ic->ic_state == IEEE80211_S_RUN) {
1781 		if (nstate == IEEE80211_S_SCAN) {
1782 			/*
1783 			 * During RUN->SCAN we don't call sc_newstate() so
1784 			 * we must stop A-MPDU Tx ourselves in this case.
1785 			 */
1786 			ieee80211_stop_ampdu_tx(ic, ni, -1);
1787 			ieee80211_ba_del(ni);
1788 		}
1789 		timeout_del(&sc->calib_to);
1790 		sc->calib.state = IWN_CALIB_STATE_INIT;
1791 		if (sc->sc_flags & IWN_FLAG_BGSCAN)
1792 			iwn_scan_abort(sc);
1793 	}
1794 
1795 	if (ic->ic_state == IEEE80211_S_SCAN) {
1796 		if (nstate == IEEE80211_S_SCAN) {
1797 			if (sc->sc_flags & IWN_FLAG_SCANNING)
1798 				return 0;
1799 		} else
1800 			sc->sc_flags &= ~IWN_FLAG_SCANNING;
1801 		/* Turn LED off when leaving scan state. */
1802 		iwn_set_led(sc, IWN_LED_LINK, 1, 0);
1803 	}
1804 
1805 	if (ic->ic_state >= IEEE80211_S_ASSOC &&
1806 	    nstate <= IEEE80211_S_ASSOC) {
1807 		/* Reset state to handle re- and disassociations. */
1808 		sc->rxon.associd = 0;
1809 		sc->rxon.filter &= ~htole32(IWN_FILTER_BSS);
1810 		sc->calib.state = IWN_CALIB_STATE_INIT;
1811 		error = iwn_cmd(sc, IWN_CMD_RXON, &sc->rxon, sc->rxonsz, 1);
1812 		if (error != 0)
1813 			printf("%s: RXON command failed\n",
1814 			    sc->sc_dev.dv_xname);
1815 	}
1816 
1817 	switch (nstate) {
1818 	case IEEE80211_S_SCAN:
1819 		/* Make the link LED blink while we're scanning. */
1820 		iwn_set_led(sc, IWN_LED_LINK, 10, 10);
1821 
1822 		if ((error = iwn_scan(sc, IEEE80211_CHAN_2GHZ, 0)) != 0) {
1823 			printf("%s: could not initiate scan\n",
1824 			    sc->sc_dev.dv_xname);
1825 			return error;
1826 		}
1827 		if (ifp->if_flags & IFF_DEBUG)
1828 			printf("%s: %s -> %s\n", ifp->if_xname,
1829 			    ieee80211_state_name[ic->ic_state],
1830 			    ieee80211_state_name[nstate]);
1831 		if ((sc->sc_flags & IWN_FLAG_BGSCAN) == 0) {
1832 			ieee80211_set_link_state(ic, LINK_STATE_DOWN);
1833 			ieee80211_node_cleanup(ic, ic->ic_bss);
1834 		}
1835 		ic->ic_state = nstate;
1836 		return 0;
1837 
1838 	case IEEE80211_S_ASSOC:
1839 		if (ic->ic_state != IEEE80211_S_RUN)
1840 			break;
1841 		/* FALLTHROUGH */
1842 	case IEEE80211_S_AUTH:
1843 		if ((error = iwn_auth(sc, arg)) != 0) {
1844 			printf("%s: could not move to auth state\n",
1845 			    sc->sc_dev.dv_xname);
1846 			return error;
1847 		}
1848 		break;
1849 
1850 	case IEEE80211_S_RUN:
1851 		if ((error = iwn_run(sc)) != 0) {
1852 			printf("%s: could not move to run state\n",
1853 			    sc->sc_dev.dv_xname);
1854 			return error;
1855 		}
1856 		break;
1857 
1858 	case IEEE80211_S_INIT:
1859 		sc->calib.state = IWN_CALIB_STATE_INIT;
1860 		break;
1861 	}
1862 
1863 	return sc->sc_newstate(ic, nstate, arg);
1864 }
1865 
1866 void
1867 iwn_iter_func(void *arg, struct ieee80211_node *ni)
1868 {
1869 	struct iwn_softc *sc = arg;
1870 	struct iwn_node *wn = (void *)ni;
1871 
1872 	if ((ni->ni_flags & IEEE80211_NODE_HT) == 0) {
1873 		int old_txrate = ni->ni_txrate;
1874 		ieee80211_amrr_choose(&sc->amrr, ni, &wn->amn);
1875 		if (old_txrate != ni->ni_txrate)
1876 			iwn_set_link_quality(sc, ni);
1877 	}
1878 }
1879 
1880 void
1881 iwn_calib_timeout(void *arg)
1882 {
1883 	struct iwn_softc *sc = arg;
1884 	struct ieee80211com *ic = &sc->sc_ic;
1885 	int s;
1886 
1887 	s = splnet();
1888 	if (ic->ic_fixed_rate == -1) {
1889 		if (ic->ic_opmode == IEEE80211_M_STA)
1890 			iwn_iter_func(sc, ic->ic_bss);
1891 		else
1892 			ieee80211_iterate_nodes(ic, iwn_iter_func, sc);
1893 	}
1894 	/* Force automatic TX power calibration every 60 secs. */
1895 	if (++sc->calib_cnt >= 120) {
1896 		uint32_t flags = 0;
1897 
1898 		DPRINTFN(2, ("sending request for statistics\n"));
1899 		(void)iwn_cmd(sc, IWN_CMD_GET_STATISTICS, &flags,
1900 		    sizeof flags, 1);
1901 		sc->calib_cnt = 0;
1902 	}
1903 	splx(s);
1904 
1905 	/* Automatic rate control triggered every 500ms. */
1906 	timeout_add_msec(&sc->calib_to, 500);
1907 }
1908 
1909 int
1910 iwn_ccmp_decap(struct iwn_softc *sc, struct mbuf *m, struct ieee80211_node *ni)
1911 {
1912 	struct ieee80211com *ic = &sc->sc_ic;
1913 	struct ieee80211_key *k = &ni->ni_pairwise_key;
1914 	struct ieee80211_frame *wh;
1915 	uint64_t pn, *prsc;
1916 	uint8_t *ivp;
1917 	uint8_t tid;
1918 	int hdrlen, hasqos;
1919 
1920 	wh = mtod(m, struct ieee80211_frame *);
1921 	hdrlen = ieee80211_get_hdrlen(wh);
1922 	ivp = (uint8_t *)wh + hdrlen;
1923 
1924 	/* Check that ExtIV bit is set. */
1925 	if (!(ivp[3] & IEEE80211_WEP_EXTIV)) {
1926 		DPRINTF(("CCMP decap ExtIV not set\n"));
1927 		return 1;
1928 	}
1929 	hasqos = ieee80211_has_qos(wh);
1930 	tid = hasqos ? ieee80211_get_qos(wh) & IEEE80211_QOS_TID : 0;
1931 	prsc = &k->k_rsc[tid];
1932 
1933 	/* Extract the 48-bit PN from the CCMP header. */
1934 	pn = (uint64_t)ivp[0]       |
1935 	     (uint64_t)ivp[1] <<  8 |
1936 	     (uint64_t)ivp[4] << 16 |
1937 	     (uint64_t)ivp[5] << 24 |
1938 	     (uint64_t)ivp[6] << 32 |
1939 	     (uint64_t)ivp[7] << 40;
1940 	if (pn <= *prsc) {
1941 		DPRINTF(("CCMP replayed\n"));
1942 		ic->ic_stats.is_ccmp_replays++;
1943 		return 1;
1944 	}
1945 	/* Last seen packet number is updated in ieee80211_inputm(). */
1946 
1947 	/* Strip MIC. IV will be stripped by ieee80211_inputm(). */
1948 	m_adj(m, -IEEE80211_CCMP_MICLEN);
1949 	return 0;
1950 }
1951 
1952 /*
1953  * Process an RX_PHY firmware notification.  This is usually immediately
1954  * followed by an MPDU_RX_DONE notification.
1955  */
1956 void
1957 iwn_rx_phy(struct iwn_softc *sc, struct iwn_rx_desc *desc,
1958     struct iwn_rx_data *data)
1959 {
1960 	struct iwn_rx_stat *stat = (struct iwn_rx_stat *)(desc + 1);
1961 
1962 	DPRINTFN(2, ("received PHY stats\n"));
1963 	bus_dmamap_sync(sc->sc_dmat, data->map, sizeof (*desc),
1964 	    sizeof (*stat), BUS_DMASYNC_POSTREAD);
1965 
1966 	/* Save RX statistics, they will be used on MPDU_RX_DONE. */
1967 	memcpy(&sc->last_rx_stat, stat, sizeof (*stat));
1968 	sc->last_rx_valid = IWN_LAST_RX_VALID;
1969 	/*
1970 	 * The firmware does not send separate RX_PHY
1971 	 * notifications for A-MPDU subframes.
1972 	 */
1973 	if (stat->flags & htole16(IWN_STAT_FLAG_AGG))
1974 		sc->last_rx_valid |= IWN_LAST_RX_AMPDU;
1975 }
1976 
1977 /*
1978  * Process an RX_DONE (4965AGN only) or MPDU_RX_DONE firmware notification.
1979  * Each MPDU_RX_DONE notification must be preceded by an RX_PHY one.
1980  */
1981 void
1982 iwn_rx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc,
1983     struct iwn_rx_data *data, struct mbuf_list *ml)
1984 {
1985 	struct iwn_ops *ops = &sc->ops;
1986 	struct ieee80211com *ic = &sc->sc_ic;
1987 	struct ifnet *ifp = &ic->ic_if;
1988 	struct iwn_rx_ring *ring = &sc->rxq;
1989 	struct ieee80211_frame *wh;
1990 	struct ieee80211_rxinfo rxi;
1991 	struct ieee80211_node *ni;
1992 	struct ieee80211_channel *bss_chan = NULL;
1993 	uint8_t saved_bssid[IEEE80211_ADDR_LEN] = { 0 };
1994 	struct mbuf *m, *m1;
1995 	struct iwn_rx_stat *stat;
1996 	caddr_t head;
1997 	uint32_t flags;
1998 	int error, len, rssi;
1999 	uint16_t chan;
2000 
2001 	if (desc->type == IWN_MPDU_RX_DONE) {
2002 		/* Check for prior RX_PHY notification. */
2003 		if (!sc->last_rx_valid) {
2004 			DPRINTF(("missing RX_PHY\n"));
2005 			return;
2006 		}
2007 		sc->last_rx_valid &= ~IWN_LAST_RX_VALID;
2008 		stat = &sc->last_rx_stat;
2009 		if ((sc->last_rx_valid & IWN_LAST_RX_AMPDU) &&
2010 		    (stat->flags & htole16(IWN_STAT_FLAG_AGG)) == 0) {
2011 			DPRINTF(("missing RX_PHY (expecting A-MPDU)\n"));
2012 			return;
2013 		}
2014 		if ((sc->last_rx_valid & IWN_LAST_RX_AMPDU) == 0 &&
2015 		    (stat->flags & htole16(IWN_STAT_FLAG_AGG))) {
2016 			DPRINTF(("missing RX_PHY (unexpected A-MPDU)\n"));
2017 			return;
2018 		}
2019 	} else
2020 		stat = (struct iwn_rx_stat *)(desc + 1);
2021 
2022 	bus_dmamap_sync(sc->sc_dmat, data->map, 0, IWN_RBUF_SIZE,
2023 	    BUS_DMASYNC_POSTREAD);
2024 
2025 	if (stat->cfg_phy_len > IWN_STAT_MAXLEN) {
2026 		printf("%s: invalid RX statistic header\n",
2027 		    sc->sc_dev.dv_xname);
2028 		return;
2029 	}
2030 	if (desc->type == IWN_MPDU_RX_DONE) {
2031 		struct iwn_rx_mpdu *mpdu = (struct iwn_rx_mpdu *)(desc + 1);
2032 		head = (caddr_t)(mpdu + 1);
2033 		len = letoh16(mpdu->len);
2034 	} else {
2035 		head = (caddr_t)(stat + 1) + stat->cfg_phy_len;
2036 		len = letoh16(stat->len);
2037 	}
2038 
2039 	flags = letoh32(*(uint32_t *)(head + len));
2040 
2041 	/* Discard frames with a bad FCS early. */
2042 	if ((flags & IWN_RX_NOERROR) != IWN_RX_NOERROR) {
2043 		DPRINTFN(2, ("RX flags error %x\n", flags));
2044 		ifp->if_ierrors++;
2045 		return;
2046 	}
2047 	/* Discard frames that are too short. */
2048 	if (ic->ic_opmode == IEEE80211_M_MONITOR) {
2049 		/* Allow control frames in monitor mode. */
2050 		if (len < sizeof (struct ieee80211_frame_cts)) {
2051 			DPRINTF(("frame too short: %d\n", len));
2052 			ic->ic_stats.is_rx_tooshort++;
2053 			ifp->if_ierrors++;
2054 			return;
2055 		}
2056 	} else if (len < sizeof (*wh)) {
2057 		DPRINTF(("frame too short: %d\n", len));
2058 		ic->ic_stats.is_rx_tooshort++;
2059 		ifp->if_ierrors++;
2060 		return;
2061 	}
2062 
2063 	m1 = MCLGETL(NULL, M_DONTWAIT, IWN_RBUF_SIZE);
2064 	if (m1 == NULL) {
2065 		ic->ic_stats.is_rx_nombuf++;
2066 		ifp->if_ierrors++;
2067 		return;
2068 	}
2069 	bus_dmamap_unload(sc->sc_dmat, data->map);
2070 
2071 	error = bus_dmamap_load(sc->sc_dmat, data->map, mtod(m1, void *),
2072 	    IWN_RBUF_SIZE, NULL, BUS_DMA_NOWAIT | BUS_DMA_READ);
2073 	if (error != 0) {
2074 		m_freem(m1);
2075 
2076 		/* Try to reload the old mbuf. */
2077 		error = bus_dmamap_load(sc->sc_dmat, data->map,
2078 		    mtod(data->m, void *), IWN_RBUF_SIZE, NULL,
2079 		    BUS_DMA_NOWAIT | BUS_DMA_READ);
2080 		if (error != 0) {
2081 			panic("%s: could not load old RX mbuf",
2082 			    sc->sc_dev.dv_xname);
2083 		}
2084 		/* Physical address may have changed. */
2085 		ring->desc[ring->cur] =
2086 		    htole32(data->map->dm_segs[0].ds_addr >> 8);
2087 		bus_dmamap_sync(sc->sc_dmat, ring->desc_dma.map,
2088 		    ring->cur * sizeof (uint32_t), sizeof (uint32_t),
2089 		    BUS_DMASYNC_PREWRITE);
2090 		ifp->if_ierrors++;
2091 		return;
2092 	}
2093 
2094 	m = data->m;
2095 	data->m = m1;
2096 	/* Update RX descriptor. */
2097 	ring->desc[ring->cur] = htole32(data->map->dm_segs[0].ds_addr >> 8);
2098 	bus_dmamap_sync(sc->sc_dmat, ring->desc_dma.map,
2099 	    ring->cur * sizeof (uint32_t), sizeof (uint32_t),
2100 	    BUS_DMASYNC_PREWRITE);
2101 
2102 	/* Finalize mbuf. */
2103 	m->m_data = head;
2104 	m->m_pkthdr.len = m->m_len = len;
2105 
2106 	/*
2107 	 * Grab a reference to the source node. Note that control frames are
2108 	 * shorter than struct ieee80211_frame but ieee80211_find_rxnode()
2109 	 * is being careful about control frames.
2110 	 */
2111 	wh = mtod(m, struct ieee80211_frame *);
2112 	if (len < sizeof (*wh) &&
2113 	   (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) != IEEE80211_FC0_TYPE_CTL) {
2114 		ic->ic_stats.is_rx_tooshort++;
2115 		ifp->if_ierrors++;
2116 		m_freem(m);
2117 		return;
2118 	}
2119 	ni = ieee80211_find_rxnode(ic, wh);
2120 
2121 	rxi.rxi_flags = 0;
2122 	if (((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) != IEEE80211_FC0_TYPE_CTL)
2123 	    && (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) &&
2124 	    !IEEE80211_IS_MULTICAST(wh->i_addr1) &&
2125 	    (ni->ni_flags & IEEE80211_NODE_RXPROT) &&
2126 	    ni->ni_pairwise_key.k_cipher == IEEE80211_CIPHER_CCMP) {
2127 		if ((flags & IWN_RX_CIPHER_MASK) != IWN_RX_CIPHER_CCMP) {
2128 			ic->ic_stats.is_ccmp_dec_errs++;
2129 			ifp->if_ierrors++;
2130 			m_freem(m);
2131 			ieee80211_release_node(ic, ni);
2132 			return;
2133 		}
2134 		/* Check whether decryption was successful or not. */
2135 		if ((desc->type == IWN_MPDU_RX_DONE &&
2136 		     (flags & (IWN_RX_MPDU_DEC | IWN_RX_MPDU_MIC_OK)) !=
2137 		      (IWN_RX_MPDU_DEC | IWN_RX_MPDU_MIC_OK)) ||
2138 		    (desc->type != IWN_MPDU_RX_DONE &&
2139 		     (flags & IWN_RX_DECRYPT_MASK) != IWN_RX_DECRYPT_OK)) {
2140 			DPRINTF(("CCMP decryption failed 0x%x\n", flags));
2141 			ic->ic_stats.is_ccmp_dec_errs++;
2142 			ifp->if_ierrors++;
2143 			m_freem(m);
2144 			ieee80211_release_node(ic, ni);
2145 			return;
2146 		}
2147 		if (iwn_ccmp_decap(sc, m, ni) != 0) {
2148 			ifp->if_ierrors++;
2149 			m_freem(m);
2150 			ieee80211_release_node(ic, ni);
2151 			return;
2152 		}
2153 		rxi.rxi_flags |= IEEE80211_RXI_HWDEC;
2154 	}
2155 
2156 	rssi = ops->get_rssi(stat);
2157 
2158 	chan = stat->chan;
2159 	if (chan > IEEE80211_CHAN_MAX)
2160 		chan = IEEE80211_CHAN_MAX;
2161 
2162 	/* Fix current channel. */
2163 	if (ni == ic->ic_bss) {
2164 		/*
2165 		 * We may switch ic_bss's channel during scans.
2166 		 * Record the current channel so we can restore it later.
2167 		 */
2168 		bss_chan = ni->ni_chan;
2169 		IEEE80211_ADDR_COPY(&saved_bssid, ni->ni_macaddr);
2170 	}
2171 	ni->ni_chan = &ic->ic_channels[chan];
2172 
2173 #if NBPFILTER > 0
2174 	if (sc->sc_drvbpf != NULL) {
2175 		struct iwn_rx_radiotap_header *tap = &sc->sc_rxtap;
2176 		uint16_t chan_flags;
2177 
2178 		tap->wr_flags = 0;
2179 		if (stat->flags & htole16(IWN_STAT_FLAG_SHPREAMBLE))
2180 			tap->wr_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
2181 		tap->wr_chan_freq = htole16(ic->ic_channels[chan].ic_freq);
2182 		chan_flags = ic->ic_channels[chan].ic_flags;
2183 		if (ic->ic_curmode != IEEE80211_MODE_11N)
2184 			chan_flags &= ~IEEE80211_CHAN_HT;
2185 		tap->wr_chan_flags = htole16(chan_flags);
2186 		tap->wr_dbm_antsignal = (int8_t)rssi;
2187 		tap->wr_dbm_antnoise = (int8_t)sc->noise;
2188 		tap->wr_tsft = stat->tstamp;
2189 		if (stat->rflags & IWN_RFLAG_MCS) {
2190 			tap->wr_rate = (0x80 | stat->rate); /* HT MCS index */
2191 		} else {
2192 			switch (stat->rate) {
2193 			/* CCK rates. */
2194 			case  10: tap->wr_rate =   2; break;
2195 			case  20: tap->wr_rate =   4; break;
2196 			case  55: tap->wr_rate =  11; break;
2197 			case 110: tap->wr_rate =  22; break;
2198 			/* OFDM rates. */
2199 			case 0xd: tap->wr_rate =  12; break;
2200 			case 0xf: tap->wr_rate =  18; break;
2201 			case 0x5: tap->wr_rate =  24; break;
2202 			case 0x7: tap->wr_rate =  36; break;
2203 			case 0x9: tap->wr_rate =  48; break;
2204 			case 0xb: tap->wr_rate =  72; break;
2205 			case 0x1: tap->wr_rate =  96; break;
2206 			case 0x3: tap->wr_rate = 108; break;
2207 			/* Unknown rate: should not happen. */
2208 			default:  tap->wr_rate =  0;
2209 			}
2210 		}
2211 
2212 		bpf_mtap_hdr(sc->sc_drvbpf, tap, sc->sc_rxtap_len,
2213 		    m, BPF_DIRECTION_IN);
2214 	}
2215 #endif
2216 
2217 	/* Send the frame to the 802.11 layer. */
2218 	rxi.rxi_rssi = rssi;
2219 	rxi.rxi_tstamp = 0;	/* unused */
2220 	ieee80211_inputm(ifp, m, ni, &rxi, ml);
2221 
2222 	/*
2223 	 * ieee80211_inputm() might have changed our BSS.
2224 	 * Restore ic_bss's channel if we are still in the same BSS.
2225 	 */
2226 	if (ni == ic->ic_bss && IEEE80211_ADDR_EQ(saved_bssid, ni->ni_macaddr))
2227 		ni->ni_chan = bss_chan;
2228 
2229 	/* Node is no longer needed. */
2230 	ieee80211_release_node(ic, ni);
2231 }
2232 
2233 void
2234 iwn_ra_choose(struct iwn_softc *sc, struct ieee80211_node *ni)
2235 {
2236 	struct ieee80211com *ic = &sc->sc_ic;
2237 	struct iwn_node *wn = (void *)ni;
2238 	int old_txmcs = ni->ni_txmcs;
2239 
2240 	ieee80211_ra_choose(&wn->rn, ic, ni);
2241 
2242 	/* Update firmware's LQ retry table if RA has chosen a new MCS. */
2243 	if (ni->ni_txmcs != old_txmcs)
2244 		iwn_set_link_quality(sc, ni);
2245 }
2246 
2247 void
2248 iwn_ampdu_rate_control(struct iwn_softc *sc, struct ieee80211_node *ni,
2249     struct iwn_tx_ring *txq, uint16_t seq, uint16_t ssn)
2250 {
2251 	struct ieee80211com *ic = &sc->sc_ic;
2252 	struct iwn_node *wn = (void *)ni;
2253 	int idx, end_idx;
2254 
2255 	/*
2256 	 * Update Tx rate statistics for A-MPDUs before firmware's BA window.
2257 	 */
2258 	idx = IWN_AGG_SSN_TO_TXQ_IDX(seq);
2259 	end_idx = IWN_AGG_SSN_TO_TXQ_IDX(ssn);
2260 	while (idx != end_idx) {
2261 		struct iwn_tx_data *txdata = &txq->data[idx];
2262 		if (txdata->m != NULL && txdata->ampdu_nframes > 1) {
2263 			/*
2264 			 * We can assume that this subframe has been ACKed
2265 			 * because ACK failures come as single frames and
2266 			 * before failing an A-MPDU subframe the firmware
2267 			 * sends it as a single frame at least once.
2268 			 */
2269 			ieee80211_ra_add_stats_ht(&wn->rn, ic, ni,
2270 			    txdata->ampdu_txmcs, 1, 0);
2271 
2272 			/* Report this frame only once. */
2273 			txdata->ampdu_nframes = 0;
2274 		}
2275 
2276 		idx = (idx + 1) % IWN_TX_RING_COUNT;
2277 	}
2278 
2279 	iwn_ra_choose(sc, ni);
2280 }
2281 
2282 void
2283 iwn_ht_single_rate_control(struct iwn_softc *sc, struct ieee80211_node *ni,
2284     uint8_t rate, uint8_t rflags, uint8_t ackfailcnt, int txfail)
2285 {
2286 	struct ieee80211com *ic = &sc->sc_ic;
2287 	struct iwn_node *wn = (void *)ni;
2288 	int mcs = rate;
2289 	const struct ieee80211_ht_rateset *rs =
2290 	    ieee80211_ra_get_ht_rateset(rate,
2291 	    ieee80211_node_supports_ht_sgi20(ni));
2292 	unsigned int retries = 0, i;
2293 
2294 	/*
2295 	 * Ignore Tx reports which don't match our last LQ command.
2296 	 */
2297 	if (rate != ni->ni_txmcs) {
2298 		if (++wn->lq_rate_mismatch > 15) {
2299 			/* Try to sync firmware with driver. */
2300 			iwn_set_link_quality(sc, ni);
2301 			wn->lq_rate_mismatch = 0;
2302 		}
2303 		return;
2304 	}
2305 
2306 	wn->lq_rate_mismatch = 0;
2307 
2308 	/*
2309 	 * Firmware has attempted rates in this rate set in sequence.
2310 	 * Retries at a basic rate are counted against the minimum MCS.
2311 	 */
2312 	for (i = 0; i < ackfailcnt; i++) {
2313 		if (mcs > rs->min_mcs) {
2314 			ieee80211_ra_add_stats_ht(&wn->rn, ic, ni, mcs, 1, 1);
2315 			mcs--;
2316 		} else
2317 			retries++;
2318 	}
2319 
2320 	if (txfail && ackfailcnt == 0)
2321 		ieee80211_ra_add_stats_ht(&wn->rn, ic, ni, mcs, 1, 1);
2322 	else
2323 		ieee80211_ra_add_stats_ht(&wn->rn, ic, ni, mcs, retries + 1, retries);
2324 
2325 	iwn_ra_choose(sc, ni);
2326 }
2327 
2328 /*
2329  * Process an incoming Compressed BlockAck.
2330  * Note that these block ack notifications are generated by firmware and do
2331  * not necessarily correspond to contents of block ack frames seen on the air.
2332  */
2333 void
2334 iwn_rx_compressed_ba(struct iwn_softc *sc, struct iwn_rx_desc *desc,
2335     struct iwn_rx_data *data)
2336 {
2337 	struct iwn_compressed_ba *cba = (struct iwn_compressed_ba *)(desc + 1);
2338 	struct ieee80211com *ic = &sc->sc_ic;
2339 	struct ieee80211_node *ni;
2340 	struct ieee80211_tx_ba *ba;
2341 	struct iwn_tx_ring *txq;
2342 	uint16_t seq, ssn;
2343 	int qid;
2344 
2345 	if (ic->ic_state != IEEE80211_S_RUN)
2346 		return;
2347 
2348 	bus_dmamap_sync(sc->sc_dmat, data->map, sizeof (*desc), sizeof (*cba),
2349 	    BUS_DMASYNC_POSTREAD);
2350 
2351 	if (!IEEE80211_ADDR_EQ(ic->ic_bss->ni_macaddr, cba->macaddr))
2352 		return;
2353 
2354 	ni = ic->ic_bss;
2355 
2356 	qid = le16toh(cba->qid);
2357 	if (qid < sc->first_agg_txq || qid >= sc->ntxqs)
2358 		return;
2359 
2360 	txq = &sc->txq[qid];
2361 
2362 	/* Protect against a firmware bug where the queue/TID are off. */
2363 	if (qid != sc->first_agg_txq + cba->tid)
2364 		return;
2365 
2366 	ba = &ni->ni_tx_ba[cba->tid];
2367 	if (ba->ba_state != IEEE80211_BA_AGREED)
2368 		return;
2369 
2370 	/*
2371 	 * The first bit in cba->bitmap corresponds to the sequence number
2372 	 * stored in the sequence control field cba->seq.
2373 	 * Multiple BA notifications in a row may be using this number, with
2374 	 * additional bits being set in cba->bitmap. It is unclear how the
2375 	 * firmware decides to shift this window forward.
2376 	 * We rely on ba->ba_winstart instead.
2377 	 */
2378 	seq = le16toh(cba->seq) >> IEEE80211_SEQ_SEQ_SHIFT;
2379 
2380 	/*
2381 	 * The firmware's new BA window starting sequence number
2382 	 * corresponds to the first hole in cba->bitmap, implying
2383 	 * that all frames between 'seq' and 'ssn' (non-inclusive)
2384 	 * have been acked.
2385 	 */
2386 	ssn = le16toh(cba->ssn);
2387 
2388 	if (SEQ_LT(ssn, ba->ba_winstart))
2389 		return;
2390 
2391 	/* Skip rate control if our Tx rate is fixed. */
2392 	if (ic->ic_fixed_mcs == -1)
2393 		iwn_ampdu_rate_control(sc, ni, txq, ba->ba_winstart, ssn);
2394 
2395 	/*
2396 	 * SSN corresponds to the first (perhaps not yet transmitted) frame
2397 	 * in firmware's BA window. Firmware is not going to retransmit any
2398 	 * frames before its BA window so mark them all as done.
2399 	 */
2400 	ieee80211_output_ba_move_window(ic, ni, cba->tid, ssn);
2401 	iwn_ampdu_txq_advance(sc, txq, qid,
2402 	    IWN_AGG_SSN_TO_TXQ_IDX(ssn));
2403 	iwn_clear_oactive(sc, txq);
2404 }
2405 
2406 /*
2407  * Process a CALIBRATION_RESULT notification sent by the initialization
2408  * firmware on response to a CMD_CALIB_CONFIG command (5000 only).
2409  */
2410 void
2411 iwn5000_rx_calib_results(struct iwn_softc *sc, struct iwn_rx_desc *desc,
2412     struct iwn_rx_data *data)
2413 {
2414 	struct iwn_phy_calib *calib = (struct iwn_phy_calib *)(desc + 1);
2415 	int len, idx = -1;
2416 
2417 	/* Runtime firmware should not send such a notification. */
2418 	if (sc->sc_flags & IWN_FLAG_CALIB_DONE)
2419 		return;
2420 
2421 	len = (letoh32(desc->len) & IWN_RX_DESC_LEN_MASK) - 4;
2422 	bus_dmamap_sync(sc->sc_dmat, data->map, sizeof (*desc), len,
2423 	    BUS_DMASYNC_POSTREAD);
2424 
2425 	switch (calib->code) {
2426 	case IWN5000_PHY_CALIB_DC:
2427 		if (sc->hw_type == IWN_HW_REV_TYPE_5150 ||
2428 		    sc->hw_type == IWN_HW_REV_TYPE_2030 ||
2429 		    sc->hw_type == IWN_HW_REV_TYPE_2000 ||
2430 		    sc->hw_type == IWN_HW_REV_TYPE_135 ||
2431 		    sc->hw_type == IWN_HW_REV_TYPE_105)
2432 			idx = 0;
2433 		break;
2434 	case IWN5000_PHY_CALIB_LO:
2435 		idx = 1;
2436 		break;
2437 	case IWN5000_PHY_CALIB_TX_IQ:
2438 		idx = 2;
2439 		break;
2440 	case IWN5000_PHY_CALIB_TX_IQ_PERIODIC:
2441 		if (sc->hw_type < IWN_HW_REV_TYPE_6000 &&
2442 		    sc->hw_type != IWN_HW_REV_TYPE_5150)
2443 			idx = 3;
2444 		break;
2445 	case IWN5000_PHY_CALIB_BASE_BAND:
2446 		idx = 4;
2447 		break;
2448 	}
2449 	if (idx == -1)	/* Ignore other results. */
2450 		return;
2451 
2452 	/* Save calibration result. */
2453 	if (sc->calibcmd[idx].buf != NULL)
2454 		free(sc->calibcmd[idx].buf, M_DEVBUF, 0);
2455 	sc->calibcmd[idx].buf = malloc(len, M_DEVBUF, M_NOWAIT);
2456 	if (sc->calibcmd[idx].buf == NULL) {
2457 		DPRINTF(("not enough memory for calibration result %d\n",
2458 		    calib->code));
2459 		return;
2460 	}
2461 	DPRINTF(("saving calibration result code=%d len=%d\n",
2462 	    calib->code, len));
2463 	sc->calibcmd[idx].len = len;
2464 	memcpy(sc->calibcmd[idx].buf, calib, len);
2465 }
2466 
2467 /*
2468  * Process an RX_STATISTICS or BEACON_STATISTICS firmware notification.
2469  * The latter is sent by the firmware after each received beacon.
2470  */
2471 void
2472 iwn_rx_statistics(struct iwn_softc *sc, struct iwn_rx_desc *desc,
2473     struct iwn_rx_data *data)
2474 {
2475 	struct iwn_ops *ops = &sc->ops;
2476 	struct ieee80211com *ic = &sc->sc_ic;
2477 	struct iwn_calib_state *calib = &sc->calib;
2478 	struct iwn_stats *stats = (struct iwn_stats *)(desc + 1);
2479 	int temp;
2480 
2481 	/* Ignore statistics received during a scan. */
2482 	if (ic->ic_state != IEEE80211_S_RUN)
2483 		return;
2484 
2485 	bus_dmamap_sync(sc->sc_dmat, data->map, sizeof (*desc),
2486 	    sizeof (*stats), BUS_DMASYNC_POSTREAD);
2487 
2488 	DPRINTFN(3, ("received statistics (cmd=%d)\n", desc->type));
2489 	sc->calib_cnt = 0;	/* Reset TX power calibration timeout. */
2490 
2491 	/* Test if temperature has changed. */
2492 	if (stats->general.temp != sc->rawtemp) {
2493 		/* Convert "raw" temperature to degC. */
2494 		sc->rawtemp = stats->general.temp;
2495 		temp = ops->get_temperature(sc);
2496 		DPRINTFN(2, ("temperature=%dC\n", temp));
2497 
2498 		/* Update TX power if need be (4965AGN only). */
2499 		if (sc->hw_type == IWN_HW_REV_TYPE_4965)
2500 			iwn4965_power_calibration(sc, temp);
2501 	}
2502 
2503 	if (desc->type != IWN_BEACON_STATISTICS)
2504 		return;	/* Reply to a statistics request. */
2505 
2506 	sc->noise = iwn_get_noise(&stats->rx.general);
2507 
2508 	/* Test that RSSI and noise are present in stats report. */
2509 	if (sc->noise == -127)
2510 		return;
2511 
2512 	if (letoh32(stats->rx.general.flags) != 1) {
2513 		DPRINTF(("received statistics without RSSI\n"));
2514 		return;
2515 	}
2516 
2517 	/*
2518 	 * XXX Differential gain calibration makes the 6005 firmware
2519 	 * crap out, so skip it for now.  This effectively disables
2520 	 * sensitivity tuning as well.
2521 	 */
2522 	if (sc->hw_type == IWN_HW_REV_TYPE_6005)
2523 		return;
2524 
2525 	if (calib->state == IWN_CALIB_STATE_ASSOC)
2526 		iwn_collect_noise(sc, &stats->rx.general);
2527 	else if (calib->state == IWN_CALIB_STATE_RUN)
2528 		iwn_tune_sensitivity(sc, &stats->rx);
2529 }
2530 
2531 void
2532 iwn_ampdu_txq_advance(struct iwn_softc *sc, struct iwn_tx_ring *txq, int qid,
2533     int idx)
2534 {
2535 	struct iwn_ops *ops = &sc->ops;
2536 
2537 	DPRINTFN(3, ("%s: txq->cur=%d txq->read=%d txq->queued=%d qid=%d "
2538 	    "idx=%d\n", __func__, txq->cur, txq->read, txq->queued, qid, idx));
2539 
2540 	while (txq->read != idx) {
2541 		struct iwn_tx_data *txdata = &txq->data[txq->read];
2542 		if (txdata->m != NULL) {
2543 			ops->reset_sched(sc, qid, txq->read);
2544 			iwn_tx_done_free_txdata(sc, txdata);
2545 			txq->queued--;
2546 		}
2547 		txq->read = (txq->read + 1) % IWN_TX_RING_COUNT;
2548 	}
2549 }
2550 
2551 /*
2552  * Handle A-MPDU Tx queue status report.
2553  * Tx failures come as single frames (perhaps out of order), and before failing
2554  * an A-MPDU subframe the firmware transmits it as a single frame at least once.
2555  * Frames successfully transmitted in an A-MPDU are completed when a compressed
2556  * block ack notification is received.
2557  */
2558 void
2559 iwn_ampdu_tx_done(struct iwn_softc *sc, struct iwn_tx_ring *txq,
2560     struct iwn_rx_desc *desc, uint16_t status, uint8_t ackfailcnt,
2561     uint8_t rate, uint8_t rflags, int nframes, uint32_t ssn,
2562     struct iwn_txagg_status *agg_status)
2563 {
2564 	struct ieee80211com *ic = &sc->sc_ic;
2565 	int tid = desc->qid - sc->first_agg_txq;
2566 	struct iwn_tx_data *txdata = &txq->data[desc->idx];
2567 	struct ieee80211_node *ni = txdata->ni;
2568 	int txfail = (status != IWN_TX_STATUS_SUCCESS &&
2569 	    status != IWN_TX_STATUS_DIRECT_DONE);
2570 	struct ieee80211_tx_ba *ba;
2571 	uint16_t seq;
2572 
2573 	sc->sc_tx_timer = 0;
2574 
2575 	if (ic->ic_state != IEEE80211_S_RUN)
2576 		return;
2577 
2578 	if (nframes > 1) {
2579 		int i;
2580 
2581  		/*
2582 		 * Collect information about this A-MPDU.
2583 		 */
2584 		for (i = 0; i < nframes; i++) {
2585 			uint8_t qid = agg_status[i].qid;
2586 			uint8_t idx = agg_status[i].idx;
2587 			uint16_t txstatus = (le16toh(agg_status[i].status) &
2588 			    IWN_AGG_TX_STATUS_MASK);
2589 
2590 			if (txstatus != IWN_AGG_TX_STATE_TRANSMITTED)
2591 				continue;
2592 
2593 			if (qid != desc->qid)
2594 				continue;
2595 
2596 			txdata = &txq->data[idx];
2597 			if (txdata->ni == NULL)
2598 				continue;
2599 
2600 			/* The Tx rate was the same for all subframes. */
2601 			txdata->ampdu_txmcs = rate;
2602 			txdata->ampdu_nframes = nframes;
2603 		}
2604 		return;
2605 	}
2606 
2607 	if (ni == NULL)
2608 		return;
2609 
2610 	ba = &ni->ni_tx_ba[tid];
2611 	if (ba->ba_state != IEEE80211_BA_AGREED)
2612 		return;
2613 	if (SEQ_LT(ssn, ba->ba_winstart))
2614 		return;
2615 
2616 	/* This was a final single-frame Tx attempt for frame SSN-1. */
2617 	seq = (ssn - 1) & 0xfff;
2618 
2619 	/*
2620 	 * Skip rate control if our Tx rate is fixed.
2621 	 */
2622 	if (ic->ic_fixed_mcs == -1) {
2623 		if (txdata->ampdu_nframes > 1) {
2624 			struct iwn_node *wn = (void *)ni;
2625 			/*
2626 			 * This frame was once part of an A-MPDU.
2627 			 * Report one failed A-MPDU Tx attempt.
2628 			 * The firmware might have made several such
2629 			 * attempts but we don't keep track of this.
2630 			 */
2631 			ieee80211_ra_add_stats_ht(&wn->rn, ic, ni,
2632 			    txdata->ampdu_txmcs, 1, 1);
2633 		}
2634 
2635 		/* Report the final single-frame Tx attempt. */
2636 		if (rflags & IWN_RFLAG_MCS)
2637 			iwn_ht_single_rate_control(sc, ni, rate, rflags,
2638 			    ackfailcnt, txfail);
2639 	}
2640 
2641 	if (txfail)
2642 		ieee80211_tx_compressed_bar(ic, ni, tid, ssn);
2643 
2644 	/*
2645 	 * SSN corresponds to the first (perhaps not yet transmitted) frame
2646 	 * in firmware's BA window. Firmware is not going to retransmit any
2647 	 * frames before its BA window so mark them all as done.
2648 	 */
2649 	ieee80211_output_ba_move_window(ic, ni, tid, ssn);
2650 	iwn_ampdu_txq_advance(sc, txq, desc->qid, IWN_AGG_SSN_TO_TXQ_IDX(ssn));
2651 	iwn_clear_oactive(sc, txq);
2652 }
2653 
2654 /*
2655  * Process a TX_DONE firmware notification.  Unfortunately, the 4965AGN
2656  * and 5000 adapters have different incompatible TX status formats.
2657  */
2658 void
2659 iwn4965_tx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc,
2660     struct iwn_rx_data *data)
2661 {
2662 	struct iwn4965_tx_stat *stat = (struct iwn4965_tx_stat *)(desc + 1);
2663 	struct iwn_tx_ring *ring;
2664 	size_t len = (letoh32(desc->len) & IWN_RX_DESC_LEN_MASK);
2665 	uint16_t status = letoh32(stat->stat.status) & 0xff;
2666 	uint32_t ssn;
2667 
2668 	if (desc->qid > IWN4965_NTXQUEUES)
2669 		return;
2670 
2671 	ring = &sc->txq[desc->qid];
2672 
2673 	bus_dmamap_sync(sc->sc_dmat, data->map, sizeof (*desc),
2674 	    len, BUS_DMASYNC_POSTREAD);
2675 
2676 	/* Sanity checks. */
2677 	if (sizeof(*stat) > len)
2678 		return;
2679 	if (stat->nframes < 1 || stat->nframes > IWN_AMPDU_MAX)
2680 		return;
2681 	if (desc->qid < sc->first_agg_txq && stat->nframes > 1)
2682 		return;
2683 	if (desc->qid >= sc->first_agg_txq && sizeof(*stat) + sizeof(ssn) +
2684 	    stat->nframes * sizeof(stat->stat) > len)
2685 		return;
2686 
2687 	if (desc->qid < sc->first_agg_txq) {
2688 		/* XXX 4965 does not report byte count */
2689 		struct iwn_tx_data *txdata = &ring->data[desc->idx];
2690 		uint16_t framelen = txdata->totlen + IEEE80211_CRC_LEN;
2691 		int txfail = (status != IWN_TX_STATUS_SUCCESS &&
2692 		    status != IWN_TX_STATUS_DIRECT_DONE);
2693 
2694 		iwn_tx_done(sc, desc, stat->ackfailcnt, stat->rate,
2695 		    stat->rflags, txfail, desc->qid, framelen);
2696 	} else {
2697 		memcpy(&ssn, &stat->stat.status + stat->nframes, sizeof(ssn));
2698 		ssn = le32toh(ssn) & 0xfff;
2699 		iwn_ampdu_tx_done(sc, ring, desc, status, stat->ackfailcnt,
2700 		    stat->rate, stat->rflags, stat->nframes, ssn,
2701 		    stat->stat.agg_status);
2702 	}
2703 }
2704 
2705 void
2706 iwn5000_tx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc,
2707     struct iwn_rx_data *data)
2708 {
2709 	struct iwn5000_tx_stat *stat = (struct iwn5000_tx_stat *)(desc + 1);
2710 	struct iwn_tx_ring *ring;
2711 	size_t len = (letoh32(desc->len) & IWN_RX_DESC_LEN_MASK);
2712 	uint16_t status = letoh32(stat->stat.status) & 0xff;
2713 	uint32_t ssn;
2714 
2715 	if (desc->qid > IWN5000_NTXQUEUES)
2716 		return;
2717 
2718 	ring = &sc->txq[desc->qid];
2719 
2720 	bus_dmamap_sync(sc->sc_dmat, data->map, sizeof (*desc),
2721 	    sizeof (*stat), BUS_DMASYNC_POSTREAD);
2722 
2723 	/* Sanity checks. */
2724 	if (sizeof(*stat) > len)
2725 		return;
2726 	if (stat->nframes < 1 || stat->nframes > IWN_AMPDU_MAX)
2727 		return;
2728 	if (desc->qid < sc->first_agg_txq && stat->nframes > 1)
2729 		return;
2730 	if (desc->qid >= sc->first_agg_txq && sizeof(*stat) + sizeof(ssn) +
2731 	    stat->nframes * sizeof(stat->stat) > len)
2732 		return;
2733 
2734 	/* If this was not an aggregated frame, complete it now. */
2735 	if (desc->qid < sc->first_agg_txq) {
2736 		int txfail = (status != IWN_TX_STATUS_SUCCESS &&
2737 		    status != IWN_TX_STATUS_DIRECT_DONE);
2738 
2739 		/* Reset TX scheduler slot. */
2740 		iwn5000_reset_sched(sc, desc->qid, desc->idx);
2741 
2742 		iwn_tx_done(sc, desc, stat->ackfailcnt, stat->rate,
2743 		    stat->rflags, txfail, desc->qid, letoh16(stat->len));
2744 	} else {
2745 		memcpy(&ssn, &stat->stat.status + stat->nframes, sizeof(ssn));
2746 		ssn = le32toh(ssn) & 0xfff;
2747 		iwn_ampdu_tx_done(sc, ring, desc, status, stat->ackfailcnt,
2748 		    stat->rate, stat->rflags, stat->nframes, ssn,
2749 		    stat->stat.agg_status);
2750 	}
2751 }
2752 
2753 void
2754 iwn_tx_done_free_txdata(struct iwn_softc *sc, struct iwn_tx_data *data)
2755 {
2756 	struct ieee80211com *ic = &sc->sc_ic;
2757 
2758 	bus_dmamap_sync(sc->sc_dmat, data->map, 0, data->map->dm_mapsize,
2759 	    BUS_DMASYNC_POSTWRITE);
2760 	bus_dmamap_unload(sc->sc_dmat, data->map);
2761 	m_freem(data->m);
2762 	data->m = NULL;
2763 	ieee80211_release_node(ic, data->ni);
2764 	data->ni = NULL;
2765 	data->totlen = 0;
2766 	data->ampdu_nframes = 0;
2767 	data->ampdu_txmcs = 0;
2768 }
2769 
2770 void
2771 iwn_clear_oactive(struct iwn_softc *sc, struct iwn_tx_ring *ring)
2772 {
2773 	struct ieee80211com *ic = &sc->sc_ic;
2774 	struct ifnet *ifp = &ic->ic_if;
2775 
2776 	if (ring->queued < IWN_TX_RING_LOMARK) {
2777 		sc->qfullmsk &= ~(1 << ring->qid);
2778 		if (sc->qfullmsk == 0 && ifq_is_oactive(&ifp->if_snd)) {
2779 			ifq_clr_oactive(&ifp->if_snd);
2780 			(*ifp->if_start)(ifp);
2781 		}
2782 	}
2783 }
2784 
2785 /*
2786  * Adapter-independent backend for TX_DONE firmware notifications.
2787  * This handles Tx status for non-aggregation queues.
2788  */
2789 void
2790 iwn_tx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc,
2791     uint8_t ackfailcnt, uint8_t rate, uint8_t rflags, int txfail,
2792     int qid, uint16_t len)
2793 {
2794 	struct ieee80211com *ic = &sc->sc_ic;
2795 	struct ifnet *ifp = &ic->ic_if;
2796 	struct iwn_tx_ring *ring = &sc->txq[qid];
2797 	struct iwn_tx_data *data = &ring->data[desc->idx];
2798 	struct iwn_node *wn = (void *)data->ni;
2799 
2800 	if (data->ni == NULL)
2801 		return;
2802 
2803 	if (data->ni->ni_flags & IEEE80211_NODE_HT) {
2804 		if (ic->ic_state == IEEE80211_S_RUN &&
2805 		    ic->ic_fixed_mcs == -1 && (rflags & IWN_RFLAG_MCS)) {
2806 			iwn_ht_single_rate_control(sc, data->ni, rate, rflags,
2807 			    ackfailcnt, txfail);
2808 		}
2809 	} else {
2810 		if (rate != data->ni->ni_txrate) {
2811 			if (++wn->lq_rate_mismatch > 15) {
2812 				/* Try to sync firmware with driver. */
2813 				iwn_set_link_quality(sc, data->ni);
2814 				wn->lq_rate_mismatch = 0;
2815 			}
2816 		} else {
2817 			wn->lq_rate_mismatch = 0;
2818 
2819 			wn->amn.amn_txcnt++;
2820 			if (ackfailcnt > 0)
2821 				wn->amn.amn_retrycnt++;
2822 			if (txfail)
2823 				wn->amn.amn_retrycnt++;
2824 		}
2825 	}
2826 	if (txfail)
2827 		ifp->if_oerrors++;
2828 
2829 	iwn_tx_done_free_txdata(sc, data);
2830 
2831 	sc->sc_tx_timer = 0;
2832 	ring->queued--;
2833 	iwn_clear_oactive(sc, ring);
2834 }
2835 
2836 /*
2837  * Process a "command done" firmware notification.  This is where we wakeup
2838  * processes waiting for a synchronous command completion.
2839  */
2840 void
2841 iwn_cmd_done(struct iwn_softc *sc, struct iwn_rx_desc *desc)
2842 {
2843 	struct iwn_tx_ring *ring = &sc->txq[4];
2844 	struct iwn_tx_data *data;
2845 
2846 	if ((desc->qid & 0xf) != 4)
2847 		return;	/* Not a command ack. */
2848 
2849 	data = &ring->data[desc->idx];
2850 
2851 	/* If the command was mapped in an mbuf, free it. */
2852 	if (data->m != NULL) {
2853 		bus_dmamap_sync(sc->sc_dmat, data->map, 0,
2854 		    data->map->dm_mapsize, BUS_DMASYNC_POSTWRITE);
2855 		bus_dmamap_unload(sc->sc_dmat, data->map);
2856 		m_freem(data->m);
2857 		data->m = NULL;
2858 	}
2859 	wakeup(&ring->desc[desc->idx]);
2860 }
2861 
2862 /*
2863  * Process an INT_FH_RX or INT_SW_RX interrupt.
2864  */
2865 void
2866 iwn_notif_intr(struct iwn_softc *sc)
2867 {
2868 	struct mbuf_list ml = MBUF_LIST_INITIALIZER();
2869 	struct iwn_ops *ops = &sc->ops;
2870 	struct ieee80211com *ic = &sc->sc_ic;
2871 	struct ifnet *ifp = &ic->ic_if;
2872 	uint16_t hw;
2873 
2874 	bus_dmamap_sync(sc->sc_dmat, sc->rxq.stat_dma.map,
2875 	    0, sc->rxq.stat_dma.size, BUS_DMASYNC_POSTREAD);
2876 
2877 	hw = letoh16(sc->rxq.stat->closed_count) & 0xfff;
2878 	while (sc->rxq.cur != hw) {
2879 		struct iwn_rx_data *data = &sc->rxq.data[sc->rxq.cur];
2880 		struct iwn_rx_desc *desc;
2881 
2882 		bus_dmamap_sync(sc->sc_dmat, data->map, 0, sizeof (*desc),
2883 		    BUS_DMASYNC_POSTREAD);
2884 		desc = mtod(data->m, struct iwn_rx_desc *);
2885 
2886 		DPRINTFN(4, ("notification qid=%d idx=%d flags=%x type=%d\n",
2887 		    desc->qid & 0xf, desc->idx, desc->flags, desc->type));
2888 
2889 		if (!(desc->qid & 0x80))	/* Reply to a command. */
2890 			iwn_cmd_done(sc, desc);
2891 
2892 		switch (desc->type) {
2893 		case IWN_RX_PHY:
2894 			iwn_rx_phy(sc, desc, data);
2895 			break;
2896 
2897 		case IWN_RX_DONE:		/* 4965AGN only. */
2898 		case IWN_MPDU_RX_DONE:
2899 			/* An 802.11 frame has been received. */
2900 			iwn_rx_done(sc, desc, data, &ml);
2901 			break;
2902 		case IWN_RX_COMPRESSED_BA:
2903 			/* A Compressed BlockAck has been received. */
2904 			iwn_rx_compressed_ba(sc, desc, data);
2905 			break;
2906 		case IWN_TX_DONE:
2907 			/* An 802.11 frame has been transmitted. */
2908 			ops->tx_done(sc, desc, data);
2909 			break;
2910 
2911 		case IWN_RX_STATISTICS:
2912 		case IWN_BEACON_STATISTICS:
2913 			iwn_rx_statistics(sc, desc, data);
2914 			break;
2915 
2916 		case IWN_BEACON_MISSED:
2917 		{
2918 			struct iwn_beacon_missed *miss =
2919 			    (struct iwn_beacon_missed *)(desc + 1);
2920 			uint32_t missed;
2921 
2922 			if ((ic->ic_opmode != IEEE80211_M_STA) ||
2923 			    (ic->ic_state != IEEE80211_S_RUN))
2924 				break;
2925 
2926 			bus_dmamap_sync(sc->sc_dmat, data->map, sizeof (*desc),
2927 			    sizeof (*miss), BUS_DMASYNC_POSTREAD);
2928 			missed = letoh32(miss->consecutive);
2929 
2930 			/*
2931 			 * If more than 5 consecutive beacons are missed,
2932 			 * reinitialize the sensitivity state machine.
2933 			 */
2934 			if (missed > 5)
2935 				(void)iwn_init_sensitivity(sc);
2936 
2937 			/*
2938 			 * Rather than go directly to scan state, try to send a
2939 			 * directed probe request first. If that fails then the
2940 			 * state machine will drop us into scanning after timing
2941 			 * out waiting for a probe response.
2942 			 */
2943 			if (missed > ic->ic_bmissthres && !ic->ic_mgt_timer) {
2944 				if (ic->ic_if.if_flags & IFF_DEBUG)
2945 					printf("%s: receiving no beacons from "
2946 					    "%s; checking if this AP is still "
2947 					    "responding to probe requests\n",
2948 					    sc->sc_dev.dv_xname, ether_sprintf(
2949 					    ic->ic_bss->ni_macaddr));
2950 				IEEE80211_SEND_MGMT(ic, ic->ic_bss,
2951 				    IEEE80211_FC0_SUBTYPE_PROBE_REQ, 0);
2952 			}
2953 			break;
2954 		}
2955 		case IWN_UC_READY:
2956 		{
2957 			struct iwn_ucode_info *uc =
2958 			    (struct iwn_ucode_info *)(desc + 1);
2959 
2960 			/* The microcontroller is ready. */
2961 			bus_dmamap_sync(sc->sc_dmat, data->map, sizeof (*desc),
2962 			    sizeof (*uc), BUS_DMASYNC_POSTREAD);
2963 			DPRINTF(("microcode alive notification version=%d.%d "
2964 			    "subtype=%x alive=%x\n", uc->major, uc->minor,
2965 			    uc->subtype, letoh32(uc->valid)));
2966 
2967 			if (letoh32(uc->valid) != 1) {
2968 				printf("%s: microcontroller initialization "
2969 				    "failed\n", sc->sc_dev.dv_xname);
2970 				break;
2971 			}
2972 			if (uc->subtype == IWN_UCODE_INIT) {
2973 				/* Save microcontroller report. */
2974 				memcpy(&sc->ucode_info, uc, sizeof (*uc));
2975 			}
2976 			/* Save the address of the error log in SRAM. */
2977 			sc->errptr = letoh32(uc->errptr);
2978 			break;
2979 		}
2980 		case IWN_STATE_CHANGED:
2981 		{
2982 			uint32_t *status = (uint32_t *)(desc + 1);
2983 
2984 			/* Enabled/disabled notification. */
2985 			bus_dmamap_sync(sc->sc_dmat, data->map, sizeof (*desc),
2986 			    sizeof (*status), BUS_DMASYNC_POSTREAD);
2987 			DPRINTF(("state changed to %x\n", letoh32(*status)));
2988 
2989 			if (letoh32(*status) & 1) {
2990 				/* Radio transmitter is off, power down. */
2991 				iwn_stop(ifp);
2992 				return;	/* No further processing. */
2993 			}
2994 			break;
2995 		}
2996 		case IWN_START_SCAN:
2997 		{
2998 			struct iwn_start_scan *scan =
2999 			    (struct iwn_start_scan *)(desc + 1);
3000 
3001 			bus_dmamap_sync(sc->sc_dmat, data->map, sizeof (*desc),
3002 			    sizeof (*scan), BUS_DMASYNC_POSTREAD);
3003 			DPRINTFN(2, ("scan start: chan %d status %x\n",
3004 			    scan->chan, letoh32(scan->status)));
3005 
3006 			if (sc->sc_flags & IWN_FLAG_BGSCAN)
3007 				break;
3008 
3009 			/* Fix current channel. */
3010 			ic->ic_bss->ni_chan = &ic->ic_channels[scan->chan];
3011 			break;
3012 		}
3013 		case IWN_STOP_SCAN:
3014 		{
3015 			struct iwn_stop_scan *scan =
3016 			    (struct iwn_stop_scan *)(desc + 1);
3017 
3018 			bus_dmamap_sync(sc->sc_dmat, data->map, sizeof (*desc),
3019 			    sizeof (*scan), BUS_DMASYNC_POSTREAD);
3020 			DPRINTFN(2, ("scan stop: nchan=%d status=%d chan=%d\n",
3021 			    scan->nchan, scan->status, scan->chan));
3022 
3023 			if (scan->status == 1 && scan->chan <= 14 &&
3024 			    (sc->sc_flags & IWN_FLAG_HAS_5GHZ)) {
3025 			    	int error;
3026 				/*
3027 				 * We just finished scanning 2GHz channels,
3028 				 * start scanning 5GHz ones.
3029 				 */
3030 				error = iwn_scan(sc, IEEE80211_CHAN_5GHZ,
3031 				    (sc->sc_flags & IWN_FLAG_BGSCAN) ? 1 : 0);
3032 				if (error == 0)
3033 					break;
3034 			}
3035 			sc->sc_flags &= ~IWN_FLAG_SCANNING;
3036 			sc->sc_flags &= ~IWN_FLAG_BGSCAN;
3037 			ieee80211_end_scan(ifp);
3038 			break;
3039 		}
3040 		case IWN5000_CALIBRATION_RESULT:
3041 			iwn5000_rx_calib_results(sc, desc, data);
3042 			break;
3043 
3044 		case IWN5000_CALIBRATION_DONE:
3045 			sc->sc_flags |= IWN_FLAG_CALIB_DONE;
3046 			wakeup(sc);
3047 			break;
3048 		}
3049 
3050 		sc->rxq.cur = (sc->rxq.cur + 1) % IWN_RX_RING_COUNT;
3051 	}
3052 	if_input(&sc->sc_ic.ic_if, &ml);
3053 
3054 	/* Tell the firmware what we have processed. */
3055 	hw = (hw == 0) ? IWN_RX_RING_COUNT - 1 : hw - 1;
3056 	IWN_WRITE(sc, IWN_FH_RX_WPTR, hw & ~7);
3057 }
3058 
3059 /*
3060  * Process an INT_WAKEUP interrupt raised when the microcontroller wakes up
3061  * from power-down sleep mode.
3062  */
3063 void
3064 iwn_wakeup_intr(struct iwn_softc *sc)
3065 {
3066 	int qid;
3067 
3068 	DPRINTF(("ucode wakeup from power-down sleep\n"));
3069 
3070 	/* Wakeup RX and TX rings. */
3071 	IWN_WRITE(sc, IWN_FH_RX_WPTR, sc->rxq.cur & ~7);
3072 	for (qid = 0; qid < sc->ntxqs; qid++) {
3073 		struct iwn_tx_ring *ring = &sc->txq[qid];
3074 		IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | ring->cur);
3075 	}
3076 }
3077 
3078 #ifdef IWN_DEBUG
3079 /*
3080  * Dump the error log of the firmware when a firmware panic occurs.  Although
3081  * we can't debug the firmware because it is neither open source nor free, it
3082  * can help us to identify certain classes of problems.
3083  */
3084 void
3085 iwn_fatal_intr(struct iwn_softc *sc)
3086 {
3087 	struct iwn_fw_dump dump;
3088 	int i;
3089 
3090 	/* Check that the error log address is valid. */
3091 	if (sc->errptr < IWN_FW_DATA_BASE ||
3092 	    sc->errptr + sizeof (dump) >
3093 	    IWN_FW_DATA_BASE + sc->fw_data_maxsz) {
3094 		printf("%s: bad firmware error log address 0x%08x\n",
3095 		    sc->sc_dev.dv_xname, sc->errptr);
3096 		return;
3097 	}
3098 	if (iwn_nic_lock(sc) != 0) {
3099 		printf("%s: could not read firmware error log\n",
3100 		    sc->sc_dev.dv_xname);
3101 		return;
3102 	}
3103 	/* Read firmware error log from SRAM. */
3104 	iwn_mem_read_region_4(sc, sc->errptr, (uint32_t *)&dump,
3105 	    sizeof (dump) / sizeof (uint32_t));
3106 	iwn_nic_unlock(sc);
3107 
3108 	if (dump.valid == 0) {
3109 		printf("%s: firmware error log is empty\n",
3110 		    sc->sc_dev.dv_xname);
3111 		return;
3112 	}
3113 	printf("firmware error log:\n");
3114 	printf("  error type      = \"%s\" (0x%08X)\n",
3115 	    (dump.id < nitems(iwn_fw_errmsg)) ?
3116 		iwn_fw_errmsg[dump.id] : "UNKNOWN",
3117 	    dump.id);
3118 	printf("  program counter = 0x%08X\n", dump.pc);
3119 	printf("  source line     = 0x%08X\n", dump.src_line);
3120 	printf("  error data      = 0x%08X%08X\n",
3121 	    dump.error_data[0], dump.error_data[1]);
3122 	printf("  branch link     = 0x%08X%08X\n",
3123 	    dump.branch_link[0], dump.branch_link[1]);
3124 	printf("  interrupt link  = 0x%08X%08X\n",
3125 	    dump.interrupt_link[0], dump.interrupt_link[1]);
3126 	printf("  time            = %u\n", dump.time[0]);
3127 
3128 	/* Dump driver status (TX and RX rings) while we're here. */
3129 	printf("driver status:\n");
3130 	for (i = 0; i < sc->ntxqs; i++) {
3131 		struct iwn_tx_ring *ring = &sc->txq[i];
3132 		printf("  tx ring %2d: qid=%-2d cur=%-3d queued=%-3d\n",
3133 		    i, ring->qid, ring->cur, ring->queued);
3134 	}
3135 	printf("  rx ring: cur=%d\n", sc->rxq.cur);
3136 	printf("  802.11 state %d\n", sc->sc_ic.ic_state);
3137 }
3138 #endif
3139 
3140 int
3141 iwn_intr(void *arg)
3142 {
3143 	struct iwn_softc *sc = arg;
3144 	struct ifnet *ifp = &sc->sc_ic.ic_if;
3145 	uint32_t r1, r2, tmp;
3146 
3147 	/* Disable interrupts. */
3148 	IWN_WRITE(sc, IWN_INT_MASK, 0);
3149 
3150 	/* Read interrupts from ICT (fast) or from registers (slow). */
3151 	if (sc->sc_flags & IWN_FLAG_USE_ICT) {
3152 		tmp = 0;
3153 		while (sc->ict[sc->ict_cur] != 0) {
3154 			tmp |= sc->ict[sc->ict_cur];
3155 			sc->ict[sc->ict_cur] = 0;	/* Acknowledge. */
3156 			sc->ict_cur = (sc->ict_cur + 1) % IWN_ICT_COUNT;
3157 		}
3158 		tmp = letoh32(tmp);
3159 		if (tmp == 0xffffffff)	/* Shouldn't happen. */
3160 			tmp = 0;
3161 		else if (tmp & 0xc0000)	/* Workaround a HW bug. */
3162 			tmp |= 0x8000;
3163 		r1 = (tmp & 0xff00) << 16 | (tmp & 0xff);
3164 		r2 = 0;	/* Unused. */
3165 	} else {
3166 		r1 = IWN_READ(sc, IWN_INT);
3167 		if (r1 == 0xffffffff || (r1 & 0xfffffff0) == 0xa5a5a5a0)
3168 			return 0;	/* Hardware gone! */
3169 		r2 = IWN_READ(sc, IWN_FH_INT);
3170 	}
3171 	if (r1 == 0 && r2 == 0) {
3172 		if (ifp->if_flags & IFF_UP)
3173 			IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
3174 		return 0;	/* Interrupt not for us. */
3175 	}
3176 
3177 	/* Acknowledge interrupts. */
3178 	IWN_WRITE(sc, IWN_INT, r1);
3179 	if (!(sc->sc_flags & IWN_FLAG_USE_ICT))
3180 		IWN_WRITE(sc, IWN_FH_INT, r2);
3181 
3182 	if (r1 & IWN_INT_RF_TOGGLED) {
3183 		tmp = IWN_READ(sc, IWN_GP_CNTRL) & IWN_GP_CNTRL_RFKILL;
3184 		printf("%s: RF switch: radio %s\n", sc->sc_dev.dv_xname,
3185 		    tmp ? "enabled" : "disabled");
3186 		if (tmp)
3187 			task_add(systq, &sc->init_task);
3188 	}
3189 	if (r1 & IWN_INT_CT_REACHED) {
3190 		printf("%s: critical temperature reached!\n",
3191 		    sc->sc_dev.dv_xname);
3192 	}
3193 	if (r1 & (IWN_INT_SW_ERR | IWN_INT_HW_ERR)) {
3194 		printf("%s: fatal firmware error\n", sc->sc_dev.dv_xname);
3195 
3196 		/* Force a complete recalibration on next init. */
3197 		sc->sc_flags &= ~IWN_FLAG_CALIB_DONE;
3198 
3199 		/* Dump firmware error log and stop. */
3200 #ifdef IWN_DEBUG
3201 		iwn_fatal_intr(sc);
3202 #endif
3203 		iwn_stop(ifp);
3204 		task_add(systq, &sc->init_task);
3205 		return 1;
3206 	}
3207 	if ((r1 & (IWN_INT_FH_RX | IWN_INT_SW_RX | IWN_INT_RX_PERIODIC)) ||
3208 	    (r2 & IWN_FH_INT_RX)) {
3209 		if (sc->sc_flags & IWN_FLAG_USE_ICT) {
3210 			if (r1 & (IWN_INT_FH_RX | IWN_INT_SW_RX))
3211 				IWN_WRITE(sc, IWN_FH_INT, IWN_FH_INT_RX);
3212 			IWN_WRITE_1(sc, IWN_INT_PERIODIC,
3213 			    IWN_INT_PERIODIC_DIS);
3214 			iwn_notif_intr(sc);
3215 			if (r1 & (IWN_INT_FH_RX | IWN_INT_SW_RX)) {
3216 				IWN_WRITE_1(sc, IWN_INT_PERIODIC,
3217 				    IWN_INT_PERIODIC_ENA);
3218 			}
3219 		} else
3220 			iwn_notif_intr(sc);
3221 	}
3222 
3223 	if ((r1 & IWN_INT_FH_TX) || (r2 & IWN_FH_INT_TX)) {
3224 		if (sc->sc_flags & IWN_FLAG_USE_ICT)
3225 			IWN_WRITE(sc, IWN_FH_INT, IWN_FH_INT_TX);
3226 		wakeup(sc);	/* FH DMA transfer completed. */
3227 	}
3228 
3229 	if (r1 & IWN_INT_ALIVE)
3230 		wakeup(sc);	/* Firmware is alive. */
3231 
3232 	if (r1 & IWN_INT_WAKEUP)
3233 		iwn_wakeup_intr(sc);
3234 
3235 	/* Re-enable interrupts. */
3236 	if (ifp->if_flags & IFF_UP)
3237 		IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
3238 
3239 	return 1;
3240 }
3241 
3242 /*
3243  * Update TX scheduler ring when transmitting an 802.11 frame (4965AGN and
3244  * 5000 adapters use a slightly different format).
3245  */
3246 void
3247 iwn4965_update_sched(struct iwn_softc *sc, int qid, int idx, uint8_t id,
3248     uint16_t len)
3249 {
3250 	uint16_t *w = &sc->sched[qid * IWN4965_SCHED_COUNT + idx];
3251 
3252 	*w = htole16(len + 8);
3253 	bus_dmamap_sync(sc->sc_dmat, sc->sched_dma.map,
3254 	    (caddr_t)w - sc->sched_dma.vaddr, sizeof (uint16_t),
3255 	    BUS_DMASYNC_PREWRITE);
3256 	if (idx < IWN_SCHED_WINSZ) {
3257 		*(w + IWN_TX_RING_COUNT) = *w;
3258 		bus_dmamap_sync(sc->sc_dmat, sc->sched_dma.map,
3259 		    (caddr_t)(w + IWN_TX_RING_COUNT) - sc->sched_dma.vaddr,
3260 		    sizeof (uint16_t), BUS_DMASYNC_PREWRITE);
3261 	}
3262 }
3263 
3264 void
3265 iwn4965_reset_sched(struct iwn_softc *sc, int qid, int idx)
3266 {
3267 	/* TBD */
3268 }
3269 
3270 void
3271 iwn5000_update_sched(struct iwn_softc *sc, int qid, int idx, uint8_t id,
3272     uint16_t len)
3273 {
3274 	uint16_t *w = &sc->sched[qid * IWN5000_SCHED_COUNT + idx];
3275 
3276 	*w = htole16(id << 12 | (len + 8));
3277 	bus_dmamap_sync(sc->sc_dmat, sc->sched_dma.map,
3278 	    (caddr_t)w - sc->sched_dma.vaddr, sizeof (uint16_t),
3279 	    BUS_DMASYNC_PREWRITE);
3280 	if (idx < IWN_SCHED_WINSZ) {
3281 		*(w + IWN_TX_RING_COUNT) = *w;
3282 		bus_dmamap_sync(sc->sc_dmat, sc->sched_dma.map,
3283 		    (caddr_t)(w + IWN_TX_RING_COUNT) - sc->sched_dma.vaddr,
3284 		    sizeof (uint16_t), BUS_DMASYNC_PREWRITE);
3285 	}
3286 }
3287 
3288 void
3289 iwn5000_reset_sched(struct iwn_softc *sc, int qid, int idx)
3290 {
3291 	uint16_t *w = &sc->sched[qid * IWN5000_SCHED_COUNT + idx];
3292 
3293 	*w = (*w & htole16(0xf000)) | htole16(1);
3294 	bus_dmamap_sync(sc->sc_dmat, sc->sched_dma.map,
3295 	    (caddr_t)w - sc->sched_dma.vaddr, sizeof (uint16_t),
3296 	    BUS_DMASYNC_PREWRITE);
3297 	if (idx < IWN_SCHED_WINSZ) {
3298 		*(w + IWN_TX_RING_COUNT) = *w;
3299 		bus_dmamap_sync(sc->sc_dmat, sc->sched_dma.map,
3300 		    (caddr_t)(w + IWN_TX_RING_COUNT) - sc->sched_dma.vaddr,
3301 		    sizeof (uint16_t), BUS_DMASYNC_PREWRITE);
3302 	}
3303 }
3304 
3305 int
3306 iwn_rval2ridx(int rval)
3307 {
3308 	int ridx;
3309 
3310 	for (ridx = 0; ridx < nitems(iwn_rates); ridx++) {
3311 		if (rval == iwn_rates[ridx].rate)
3312 			break;
3313 	}
3314 
3315 	return ridx;
3316 }
3317 
3318 int
3319 iwn_tx(struct iwn_softc *sc, struct mbuf *m, struct ieee80211_node *ni)
3320 {
3321 	struct iwn_ops *ops = &sc->ops;
3322 	struct ieee80211com *ic = &sc->sc_ic;
3323 	struct iwn_node *wn = (void *)ni;
3324 	struct iwn_tx_ring *ring;
3325 	struct iwn_tx_desc *desc;
3326 	struct iwn_tx_data *data;
3327 	struct iwn_tx_cmd *cmd;
3328 	struct iwn_cmd_data *tx;
3329 	const struct iwn_rate *rinfo;
3330 	struct ieee80211_frame *wh;
3331 	struct ieee80211_key *k = NULL;
3332 	enum ieee80211_edca_ac ac;
3333 	int qid;
3334 	uint32_t flags;
3335 	uint16_t qos;
3336 	u_int hdrlen;
3337 	bus_dma_segment_t *seg;
3338 	uint8_t *ivp, tid, ridx, txant, type, subtype;
3339 	int i, totlen, hasqos, error, pad;
3340 
3341 	wh = mtod(m, struct ieee80211_frame *);
3342 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
3343 	subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
3344 	if (type == IEEE80211_FC0_TYPE_CTL)
3345 		hdrlen = sizeof(struct ieee80211_frame_min);
3346 	else
3347 		hdrlen = ieee80211_get_hdrlen(wh);
3348 
3349 	if ((hasqos = ieee80211_has_qos(wh))) {
3350 		/* Select EDCA Access Category and TX ring for this frame. */
3351 		struct ieee80211_tx_ba *ba;
3352 		qos = ieee80211_get_qos(wh);
3353 		tid = qos & IEEE80211_QOS_TID;
3354 		ac = ieee80211_up_to_ac(ic, tid);
3355 		qid = ac;
3356 
3357 		/* If possible, put this frame on an aggregation queue. */
3358 		if (sc->sc_tx_ba[tid].wn == wn) {
3359 			ba = &ni->ni_tx_ba[tid];
3360 			if (!IEEE80211_IS_MULTICAST(wh->i_addr1) &&
3361 			    ba->ba_state == IEEE80211_BA_AGREED) {
3362 				qid = sc->first_agg_txq + tid;
3363 				if (sc->qfullmsk & (1 << qid)) {
3364 					m_freem(m);
3365 					return ENOBUFS;
3366 				}
3367 			}
3368 		}
3369 	} else {
3370 		qos = 0;
3371 		tid = IWN_NONQOS_TID;
3372 		ac = EDCA_AC_BE;
3373 		qid = ac;
3374 	}
3375 
3376 	ring = &sc->txq[qid];
3377 	desc = &ring->desc[ring->cur];
3378 	data = &ring->data[ring->cur];
3379 
3380 	/* Choose a TX rate index. */
3381 	if (IEEE80211_IS_MULTICAST(wh->i_addr1) ||
3382 	    type != IEEE80211_FC0_TYPE_DATA)
3383 		ridx = iwn_rval2ridx(ieee80211_min_basic_rate(ic));
3384 	else if (ic->ic_fixed_mcs != -1)
3385 		ridx = sc->fixed_ridx;
3386 	else if (ic->ic_fixed_rate != -1)
3387 		ridx = sc->fixed_ridx;
3388 	else {
3389 		if (ni->ni_flags & IEEE80211_NODE_HT)
3390 			ridx = iwn_mcs2ridx[ni->ni_txmcs];
3391 		else
3392 			ridx = wn->ridx[ni->ni_txrate];
3393 	}
3394 	rinfo = &iwn_rates[ridx];
3395 #if NBPFILTER > 0
3396 	if (sc->sc_drvbpf != NULL) {
3397 		struct iwn_tx_radiotap_header *tap = &sc->sc_txtap;
3398 		uint16_t chan_flags;
3399 
3400 		tap->wt_flags = 0;
3401 		tap->wt_chan_freq = htole16(ni->ni_chan->ic_freq);
3402 		chan_flags = ni->ni_chan->ic_flags;
3403 		if (ic->ic_curmode != IEEE80211_MODE_11N)
3404 			chan_flags &= ~IEEE80211_CHAN_HT;
3405 		tap->wt_chan_flags = htole16(chan_flags);
3406 		if ((ni->ni_flags & IEEE80211_NODE_HT) &&
3407 		    !IEEE80211_IS_MULTICAST(wh->i_addr1) &&
3408 		    type == IEEE80211_FC0_TYPE_DATA) {
3409 			tap->wt_rate = (0x80 | ni->ni_txmcs);
3410 		} else
3411 			tap->wt_rate = rinfo->rate;
3412 		if ((ic->ic_flags & IEEE80211_F_WEPON) &&
3413 		    (wh->i_fc[1] & IEEE80211_FC1_PROTECTED))
3414 			tap->wt_flags |= IEEE80211_RADIOTAP_F_WEP;
3415 
3416 		bpf_mtap_hdr(sc->sc_drvbpf, tap, sc->sc_txtap_len,
3417 		    m, BPF_DIRECTION_OUT);
3418 	}
3419 #endif
3420 
3421 	totlen = m->m_pkthdr.len;
3422 
3423 	/* Encrypt the frame if need be. */
3424 	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
3425 		/* Retrieve key for TX. */
3426 		k = ieee80211_get_txkey(ic, wh, ni);
3427 		if (k->k_cipher != IEEE80211_CIPHER_CCMP) {
3428 			/* Do software encryption. */
3429 			if ((m = ieee80211_encrypt(ic, m, k)) == NULL)
3430 				return ENOBUFS;
3431 			/* 802.11 header may have moved. */
3432 			wh = mtod(m, struct ieee80211_frame *);
3433 			totlen = m->m_pkthdr.len;
3434 
3435 		} else	/* HW appends CCMP MIC. */
3436 			totlen += IEEE80211_CCMP_HDRLEN;
3437 	}
3438 
3439 	data->totlen = totlen;
3440 
3441 	/* Prepare TX firmware command. */
3442 	cmd = &ring->cmd[ring->cur];
3443 	cmd->code = IWN_CMD_TX_DATA;
3444 	cmd->flags = 0;
3445 	cmd->qid = ring->qid;
3446 	cmd->idx = ring->cur;
3447 
3448 	tx = (struct iwn_cmd_data *)cmd->data;
3449 	/* NB: No need to clear tx, all fields are reinitialized here. */
3450 	tx->scratch = 0;	/* clear "scratch" area */
3451 
3452 	flags = 0;
3453 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
3454 		/* Unicast frame, check if an ACK is expected. */
3455 		if (!hasqos || (qos & IEEE80211_QOS_ACK_POLICY_MASK) !=
3456 		    IEEE80211_QOS_ACK_POLICY_NOACK)
3457 			flags |= IWN_TX_NEED_ACK;
3458 	}
3459 	if (type == IEEE80211_FC0_TYPE_CTL &&
3460 	    subtype == IEEE80211_FC0_SUBTYPE_BAR) {
3461 		struct ieee80211_frame_min *mwh;
3462 		uint8_t *barfrm;
3463 		uint16_t ctl;
3464 		mwh = mtod(m, struct ieee80211_frame_min *);
3465 		barfrm = (uint8_t *)&mwh[1];
3466 		ctl = LE_READ_2(barfrm);
3467 		tid = (ctl & IEEE80211_BA_TID_INFO_MASK) >>
3468 		    IEEE80211_BA_TID_INFO_SHIFT;
3469 		flags |= (IWN_TX_NEED_ACK | IWN_TX_IMM_BA);
3470 	}
3471 
3472 	if (wh->i_fc[1] & IEEE80211_FC1_MORE_FRAG)
3473 		flags |= IWN_TX_MORE_FRAG;	/* Cannot happen yet. */
3474 
3475 	/* Check if frame must be protected using RTS/CTS or CTS-to-self. */
3476 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
3477 		/* NB: Group frames are sent using CCK in 802.11b/g/n (2GHz). */
3478 		if (totlen + IEEE80211_CRC_LEN > ic->ic_rtsthreshold) {
3479 			flags |= IWN_TX_NEED_RTS;
3480 		} else if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
3481 		    ridx >= IWN_RIDX_OFDM6) {
3482 			if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
3483 				flags |= IWN_TX_NEED_CTS;
3484 			else if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
3485 				flags |= IWN_TX_NEED_RTS;
3486 		}
3487 
3488 		if (flags & (IWN_TX_NEED_RTS | IWN_TX_NEED_CTS)) {
3489 			if (sc->hw_type != IWN_HW_REV_TYPE_4965) {
3490 				/* 5000 autoselects RTS/CTS or CTS-to-self. */
3491 				flags &= ~(IWN_TX_NEED_RTS | IWN_TX_NEED_CTS);
3492 				flags |= IWN_TX_NEED_PROTECTION;
3493 			} else
3494 				flags |= IWN_TX_FULL_TXOP;
3495 		}
3496 	}
3497 
3498 	if (type == IEEE80211_FC0_TYPE_CTL &&
3499 	    subtype == IEEE80211_FC0_SUBTYPE_BAR)
3500 		tx->id = wn->id;
3501 	else if (IEEE80211_IS_MULTICAST(wh->i_addr1) ||
3502 	    type != IEEE80211_FC0_TYPE_DATA)
3503 		tx->id = sc->broadcast_id;
3504 	else
3505 		tx->id = wn->id;
3506 
3507 	if (type == IEEE80211_FC0_TYPE_MGT) {
3508 #ifndef IEEE80211_STA_ONLY
3509 		/* Tell HW to set timestamp in probe responses. */
3510 		if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
3511 			flags |= IWN_TX_INSERT_TSTAMP;
3512 #endif
3513 		if (subtype == IEEE80211_FC0_SUBTYPE_ASSOC_REQ ||
3514 		    subtype == IEEE80211_FC0_SUBTYPE_REASSOC_REQ)
3515 			tx->timeout = htole16(3);
3516 		else
3517 			tx->timeout = htole16(2);
3518 	} else
3519 		tx->timeout = htole16(0);
3520 
3521 	if (hdrlen & 3) {
3522 		/* First segment length must be a multiple of 4. */
3523 		flags |= IWN_TX_NEED_PADDING;
3524 		pad = 4 - (hdrlen & 3);
3525 	} else
3526 		pad = 0;
3527 
3528 	tx->len = htole16(totlen);
3529 	tx->tid = tid;
3530 	tx->rts_ntries = 60;
3531 	tx->data_ntries = 15;
3532 	tx->lifetime = htole32(IWN_LIFETIME_INFINITE);
3533 
3534 	if ((ni->ni_flags & IEEE80211_NODE_HT) &&
3535 	    tx->id != sc->broadcast_id)
3536 		tx->plcp = rinfo->ht_plcp;
3537 	else
3538 		tx->plcp = rinfo->plcp;
3539 
3540 	if ((ni->ni_flags & IEEE80211_NODE_HT) &&
3541 	    tx->id != sc->broadcast_id) {
3542 		tx->rflags = rinfo->ht_flags;
3543 		if (ni->ni_htcaps & IEEE80211_HTCAP_SGI20)
3544 			tx->rflags |= IWN_RFLAG_SGI;
3545 	}
3546 	else
3547 		tx->rflags = rinfo->flags;
3548 	if (tx->id == sc->broadcast_id || ic->ic_fixed_mcs != -1 ||
3549 	    ic->ic_fixed_rate != -1) {
3550 		/* Group or management frame, or fixed Tx rate. */
3551 		tx->linkq = 0;
3552 		/* XXX Alternate between antenna A and B? */
3553 		txant = IWN_LSB(sc->txchainmask);
3554 		tx->rflags |= IWN_RFLAG_ANT(txant);
3555 	} else {
3556 		tx->linkq = 0; /* initial index into firmware LQ retry table */
3557 		flags |= IWN_TX_LINKQ;	/* enable multi-rate retry */
3558 	}
3559 	/* Set physical address of "scratch area". */
3560 	tx->loaddr = htole32(IWN_LOADDR(data->scratch_paddr));
3561 	tx->hiaddr = IWN_HIADDR(data->scratch_paddr);
3562 
3563 	/* Copy 802.11 header in TX command. */
3564 	memcpy((uint8_t *)(tx + 1), wh, hdrlen);
3565 
3566 	if (k != NULL && k->k_cipher == IEEE80211_CIPHER_CCMP) {
3567 		/* Trim 802.11 header and prepend CCMP IV. */
3568 		m_adj(m, hdrlen - IEEE80211_CCMP_HDRLEN);
3569 		ivp = mtod(m, uint8_t *);
3570 		k->k_tsc++;
3571 		ivp[0] = k->k_tsc;
3572 		ivp[1] = k->k_tsc >> 8;
3573 		ivp[2] = 0;
3574 		ivp[3] = k->k_id << 6 | IEEE80211_WEP_EXTIV;
3575 		ivp[4] = k->k_tsc >> 16;
3576 		ivp[5] = k->k_tsc >> 24;
3577 		ivp[6] = k->k_tsc >> 32;
3578 		ivp[7] = k->k_tsc >> 40;
3579 
3580 		tx->security = IWN_CIPHER_CCMP;
3581 		if (qid >= sc->first_agg_txq)
3582 			flags |= IWN_TX_AMPDU_CCMP;
3583 		memcpy(tx->key, k->k_key, k->k_len);
3584 
3585 		/* TX scheduler includes CCMP MIC len w/5000 Series. */
3586 		if (sc->hw_type != IWN_HW_REV_TYPE_4965)
3587 			totlen += IEEE80211_CCMP_MICLEN;
3588 	} else {
3589 		/* Trim 802.11 header. */
3590 		m_adj(m, hdrlen);
3591 		tx->security = 0;
3592 	}
3593 	tx->flags = htole32(flags);
3594 
3595 	error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m,
3596 	    BUS_DMA_NOWAIT | BUS_DMA_WRITE);
3597 	if (error != 0 && error != EFBIG) {
3598 		printf("%s: can't map mbuf (error %d)\n",
3599 		    sc->sc_dev.dv_xname, error);
3600 		m_freem(m);
3601 		return error;
3602 	}
3603 	if (error != 0) {
3604 		/* Too many DMA segments, linearize mbuf. */
3605 		if (m_defrag(m, M_DONTWAIT)) {
3606 			m_freem(m);
3607 			return ENOBUFS;
3608 		}
3609 		error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m,
3610 		    BUS_DMA_NOWAIT | BUS_DMA_WRITE);
3611 		if (error != 0) {
3612 			printf("%s: can't map mbuf (error %d)\n",
3613 			    sc->sc_dev.dv_xname, error);
3614 			m_freem(m);
3615 			return error;
3616 		}
3617 	}
3618 
3619 	data->m = m;
3620 	data->ni = ni;
3621 	data->ampdu_txmcs = ni->ni_txmcs; /* updated upon Tx interrupt */
3622 
3623 	DPRINTFN(4, ("sending data: qid=%d idx=%d len=%d nsegs=%d\n",
3624 	    ring->qid, ring->cur, m->m_pkthdr.len, data->map->dm_nsegs));
3625 
3626 	/* Fill TX descriptor. */
3627 	desc->nsegs = 1 + data->map->dm_nsegs;
3628 	/* First DMA segment is used by the TX command. */
3629 	desc->segs[0].addr = htole32(IWN_LOADDR(data->cmd_paddr));
3630 	desc->segs[0].len  = htole16(IWN_HIADDR(data->cmd_paddr) |
3631 	    (4 + sizeof (*tx) + hdrlen + pad) << 4);
3632 	/* Other DMA segments are for data payload. */
3633 	seg = data->map->dm_segs;
3634 	for (i = 1; i <= data->map->dm_nsegs; i++) {
3635 		desc->segs[i].addr = htole32(IWN_LOADDR(seg->ds_addr));
3636 		desc->segs[i].len  = htole16(IWN_HIADDR(seg->ds_addr) |
3637 		    seg->ds_len << 4);
3638 		seg++;
3639 	}
3640 
3641 	bus_dmamap_sync(sc->sc_dmat, data->map, 0, data->map->dm_mapsize,
3642 	    BUS_DMASYNC_PREWRITE);
3643 	bus_dmamap_sync(sc->sc_dmat, ring->cmd_dma.map,
3644 	    (caddr_t)cmd - ring->cmd_dma.vaddr, sizeof (*cmd),
3645 	    BUS_DMASYNC_PREWRITE);
3646 	bus_dmamap_sync(sc->sc_dmat, ring->desc_dma.map,
3647 	    (caddr_t)desc - ring->desc_dma.vaddr, sizeof (*desc),
3648 	    BUS_DMASYNC_PREWRITE);
3649 
3650 	/* Update TX scheduler. */
3651 	ops->update_sched(sc, ring->qid, ring->cur, tx->id, totlen);
3652 
3653 	/* Kick TX ring. */
3654 	ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT;
3655 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, ring->qid << 8 | ring->cur);
3656 
3657 	/* Mark TX ring as full if we reach a certain threshold. */
3658 	if (++ring->queued > IWN_TX_RING_HIMARK)
3659 		sc->qfullmsk |= 1 << ring->qid;
3660 
3661 	return 0;
3662 }
3663 
3664 void
3665 iwn_start(struct ifnet *ifp)
3666 {
3667 	struct iwn_softc *sc = ifp->if_softc;
3668 	struct ieee80211com *ic = &sc->sc_ic;
3669 	struct ieee80211_node *ni;
3670 	struct mbuf *m;
3671 
3672 	if (!(ifp->if_flags & IFF_RUNNING) || ifq_is_oactive(&ifp->if_snd))
3673 		return;
3674 
3675 	for (;;) {
3676 		if (sc->qfullmsk != 0) {
3677 			ifq_set_oactive(&ifp->if_snd);
3678 			break;
3679 		}
3680 
3681 		/* Send pending management frames first. */
3682 		m = mq_dequeue(&ic->ic_mgtq);
3683 		if (m != NULL) {
3684 			ni = m->m_pkthdr.ph_cookie;
3685 			goto sendit;
3686 		}
3687 		if (ic->ic_state != IEEE80211_S_RUN ||
3688 		    (ic->ic_xflags & IEEE80211_F_TX_MGMT_ONLY))
3689 			break;
3690 
3691 		/* Encapsulate and send data frames. */
3692 		m = ifq_dequeue(&ifp->if_snd);
3693 		if (m == NULL)
3694 			break;
3695 #if NBPFILTER > 0
3696 		if (ifp->if_bpf != NULL)
3697 			bpf_mtap(ifp->if_bpf, m, BPF_DIRECTION_OUT);
3698 #endif
3699 		if ((m = ieee80211_encap(ifp, m, &ni)) == NULL)
3700 			continue;
3701 sendit:
3702 #if NBPFILTER > 0
3703 		if (ic->ic_rawbpf != NULL)
3704 			bpf_mtap(ic->ic_rawbpf, m, BPF_DIRECTION_OUT);
3705 #endif
3706 		if (iwn_tx(sc, m, ni) != 0) {
3707 			ieee80211_release_node(ic, ni);
3708 			ifp->if_oerrors++;
3709 			continue;
3710 		}
3711 
3712 		sc->sc_tx_timer = 5;
3713 		ifp->if_timer = 1;
3714 	}
3715 }
3716 
3717 void
3718 iwn_watchdog(struct ifnet *ifp)
3719 {
3720 	struct iwn_softc *sc = ifp->if_softc;
3721 
3722 	ifp->if_timer = 0;
3723 
3724 	if (sc->sc_tx_timer > 0) {
3725 		if (--sc->sc_tx_timer == 0) {
3726 			printf("%s: device timeout\n", sc->sc_dev.dv_xname);
3727 			iwn_stop(ifp);
3728 			ifp->if_oerrors++;
3729 			return;
3730 		}
3731 		ifp->if_timer = 1;
3732 	}
3733 
3734 	ieee80211_watchdog(ifp);
3735 }
3736 
3737 int
3738 iwn_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
3739 {
3740 	struct iwn_softc *sc = ifp->if_softc;
3741 	struct ieee80211com *ic = &sc->sc_ic;
3742 	int s, error = 0;
3743 
3744 	error = rw_enter(&sc->sc_rwlock, RW_WRITE | RW_INTR);
3745 	if (error)
3746 		return error;
3747 	s = splnet();
3748 
3749 	switch (cmd) {
3750 	case SIOCSIFADDR:
3751 		ifp->if_flags |= IFF_UP;
3752 		/* FALLTHROUGH */
3753 	case SIOCSIFFLAGS:
3754 		if (ifp->if_flags & IFF_UP) {
3755 			if (!(ifp->if_flags & IFF_RUNNING))
3756 				error = iwn_init(ifp);
3757 		} else {
3758 			if (ifp->if_flags & IFF_RUNNING)
3759 				iwn_stop(ifp);
3760 		}
3761 		break;
3762 
3763 	case SIOCS80211POWER:
3764 		error = ieee80211_ioctl(ifp, cmd, data);
3765 		if (error != ENETRESET)
3766 			break;
3767 		if (ic->ic_state == IEEE80211_S_RUN &&
3768 		    sc->calib.state == IWN_CALIB_STATE_RUN) {
3769 			if (ic->ic_flags & IEEE80211_F_PMGTON)
3770 				error = iwn_set_pslevel(sc, 0, 3, 0);
3771 			else	/* back to CAM */
3772 				error = iwn_set_pslevel(sc, 0, 0, 0);
3773 		} else {
3774 			/* Defer until transition to IWN_CALIB_STATE_RUN. */
3775 			error = 0;
3776 		}
3777 		break;
3778 
3779 	default:
3780 		error = ieee80211_ioctl(ifp, cmd, data);
3781 	}
3782 
3783 	if (error == ENETRESET) {
3784 		error = 0;
3785 		if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
3786 		    (IFF_UP | IFF_RUNNING)) {
3787 			iwn_stop(ifp);
3788 			error = iwn_init(ifp);
3789 		}
3790 	}
3791 
3792 	splx(s);
3793 	rw_exit_write(&sc->sc_rwlock);
3794 	return error;
3795 }
3796 
3797 /*
3798  * Send a command to the firmware.
3799  */
3800 int
3801 iwn_cmd(struct iwn_softc *sc, int code, const void *buf, int size, int async)
3802 {
3803 	struct iwn_ops *ops = &sc->ops;
3804 	struct iwn_tx_ring *ring = &sc->txq[4];
3805 	struct iwn_tx_desc *desc;
3806 	struct iwn_tx_data *data;
3807 	struct iwn_tx_cmd *cmd;
3808 	struct mbuf *m;
3809 	bus_addr_t paddr;
3810 	int totlen, error;
3811 
3812 	desc = &ring->desc[ring->cur];
3813 	data = &ring->data[ring->cur];
3814 	totlen = 4 + size;
3815 
3816 	if (size > sizeof cmd->data) {
3817 		/* Command is too large to fit in a descriptor. */
3818 		if (totlen > MCLBYTES)
3819 			return EINVAL;
3820 		MGETHDR(m, M_DONTWAIT, MT_DATA);
3821 		if (m == NULL)
3822 			return ENOMEM;
3823 		if (totlen > MHLEN) {
3824 			MCLGET(m, M_DONTWAIT);
3825 			if (!(m->m_flags & M_EXT)) {
3826 				m_freem(m);
3827 				return ENOMEM;
3828 			}
3829 		}
3830 		cmd = mtod(m, struct iwn_tx_cmd *);
3831 		error = bus_dmamap_load(sc->sc_dmat, data->map, cmd, totlen,
3832 		    NULL, BUS_DMA_NOWAIT | BUS_DMA_WRITE);
3833 		if (error != 0) {
3834 			m_freem(m);
3835 			return error;
3836 		}
3837 		data->m = m;
3838 		paddr = data->map->dm_segs[0].ds_addr;
3839 	} else {
3840 		cmd = &ring->cmd[ring->cur];
3841 		paddr = data->cmd_paddr;
3842 	}
3843 
3844 	cmd->code = code;
3845 	cmd->flags = 0;
3846 	cmd->qid = ring->qid;
3847 	cmd->idx = ring->cur;
3848 	memcpy(cmd->data, buf, size);
3849 
3850 	desc->nsegs = 1;
3851 	desc->segs[0].addr = htole32(IWN_LOADDR(paddr));
3852 	desc->segs[0].len  = htole16(IWN_HIADDR(paddr) | totlen << 4);
3853 
3854 	if (size > sizeof cmd->data) {
3855 		bus_dmamap_sync(sc->sc_dmat, data->map, 0, totlen,
3856 		    BUS_DMASYNC_PREWRITE);
3857 	} else {
3858 		bus_dmamap_sync(sc->sc_dmat, ring->cmd_dma.map,
3859 		    (caddr_t)cmd - ring->cmd_dma.vaddr, totlen,
3860 		    BUS_DMASYNC_PREWRITE);
3861 	}
3862 	bus_dmamap_sync(sc->sc_dmat, ring->desc_dma.map,
3863 	    (caddr_t)desc - ring->desc_dma.vaddr, sizeof (*desc),
3864 	    BUS_DMASYNC_PREWRITE);
3865 
3866 	/* Update TX scheduler. */
3867 	ops->update_sched(sc, ring->qid, ring->cur, 0, 0);
3868 
3869 	/* Kick command ring. */
3870 	ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT;
3871 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, ring->qid << 8 | ring->cur);
3872 
3873 	return async ? 0 : tsleep_nsec(desc, PCATCH, "iwncmd", SEC_TO_NSEC(1));
3874 }
3875 
3876 int
3877 iwn4965_add_node(struct iwn_softc *sc, struct iwn_node_info *node, int async)
3878 {
3879 	struct iwn4965_node_info hnode;
3880 	caddr_t src, dst;
3881 
3882 	/*
3883 	 * We use the node structure for 5000 Series internally (it is
3884 	 * a superset of the one for 4965AGN). We thus copy the common
3885 	 * fields before sending the command.
3886 	 */
3887 	src = (caddr_t)node;
3888 	dst = (caddr_t)&hnode;
3889 	memcpy(dst, src, 48);
3890 	/* Skip TSC, RX MIC and TX MIC fields from ``src''. */
3891 	memcpy(dst + 48, src + 72, 20);
3892 	return iwn_cmd(sc, IWN_CMD_ADD_NODE, &hnode, sizeof hnode, async);
3893 }
3894 
3895 int
3896 iwn5000_add_node(struct iwn_softc *sc, struct iwn_node_info *node, int async)
3897 {
3898 	/* Direct mapping. */
3899 	return iwn_cmd(sc, IWN_CMD_ADD_NODE, node, sizeof (*node), async);
3900 }
3901 
3902 int
3903 iwn_set_link_quality(struct iwn_softc *sc, struct ieee80211_node *ni)
3904 {
3905 	struct ieee80211com *ic = &sc->sc_ic;
3906 	struct iwn_node *wn = (void *)ni;
3907 	struct iwn_cmd_link_quality linkq;
3908 	const struct iwn_rate *rinfo;
3909 	uint8_t txant;
3910 	int i;
3911 
3912 	/* Use the first valid TX antenna. */
3913 	txant = IWN_LSB(sc->txchainmask);
3914 
3915 	memset(&linkq, 0, sizeof linkq);
3916 	linkq.id = wn->id;
3917 	linkq.antmsk_1stream = txant;
3918 	linkq.antmsk_2stream = IWN_ANT_AB;
3919 	linkq.ampdu_max = IWN_AMPDU_MAX;
3920 	linkq.ampdu_threshold = 3;
3921 	linkq.ampdu_limit = htole16(4000);	/* 4ms */
3922 
3923 	i = 0;
3924 	if (ni->ni_flags & IEEE80211_NODE_HT) {
3925 		int txmcs;
3926 		for (txmcs = ni->ni_txmcs; txmcs >= 0; txmcs--) {
3927 			rinfo = &iwn_rates[iwn_mcs2ridx[txmcs]];
3928 			linkq.retry[i].plcp = rinfo->ht_plcp;
3929 			linkq.retry[i].rflags = rinfo->ht_flags;
3930 
3931 			if (ni->ni_htcaps & IEEE80211_HTCAP_SGI20)
3932 				linkq.retry[i].rflags |= IWN_RFLAG_SGI;
3933 
3934 			/* XXX set correct ant mask for MIMO rates here */
3935 			linkq.retry[i].rflags |= IWN_RFLAG_ANT(txant);
3936 
3937 			if (++i >= IWN_MAX_TX_RETRIES)
3938 				break;
3939 		}
3940 	} else {
3941 		int txrate;
3942 		for (txrate = ni->ni_txrate; txrate >= 0; txrate--) {
3943 			rinfo = &iwn_rates[wn->ridx[txrate]];
3944 			linkq.retry[i].plcp = rinfo->plcp;
3945 			linkq.retry[i].rflags = rinfo->flags;
3946 			linkq.retry[i].rflags |= IWN_RFLAG_ANT(txant);
3947 			if (++i >= IWN_MAX_TX_RETRIES)
3948 				break;
3949 		}
3950 	}
3951 
3952 	/* Fill the rest with the lowest basic rate. */
3953 	rinfo = &iwn_rates[iwn_rval2ridx(ieee80211_min_basic_rate(ic))];
3954 	while (i < IWN_MAX_TX_RETRIES) {
3955 		linkq.retry[i].plcp = rinfo->plcp;
3956 		linkq.retry[i].rflags = rinfo->flags;
3957 		linkq.retry[i].rflags |= IWN_RFLAG_ANT(txant);
3958 		i++;
3959 	}
3960 
3961 	return iwn_cmd(sc, IWN_CMD_LINK_QUALITY, &linkq, sizeof linkq, 1);
3962 }
3963 
3964 /*
3965  * Broadcast node is used to send group-addressed and management frames.
3966  */
3967 int
3968 iwn_add_broadcast_node(struct iwn_softc *sc, int async, int ridx)
3969 {
3970 	struct iwn_ops *ops = &sc->ops;
3971 	struct iwn_node_info node;
3972 	struct iwn_cmd_link_quality linkq;
3973 	const struct iwn_rate *rinfo;
3974 	uint8_t txant;
3975 	int i, error;
3976 
3977 	memset(&node, 0, sizeof node);
3978 	IEEE80211_ADDR_COPY(node.macaddr, etherbroadcastaddr);
3979 	node.id = sc->broadcast_id;
3980 	DPRINTF(("adding broadcast node\n"));
3981 	if ((error = ops->add_node(sc, &node, async)) != 0)
3982 		return error;
3983 
3984 	/* Use the first valid TX antenna. */
3985 	txant = IWN_LSB(sc->txchainmask);
3986 
3987 	memset(&linkq, 0, sizeof linkq);
3988 	linkq.id = sc->broadcast_id;
3989 	linkq.antmsk_1stream = txant;
3990 	linkq.antmsk_2stream = IWN_ANT_AB;
3991 	linkq.ampdu_max = IWN_AMPDU_MAX_NO_AGG;
3992 	linkq.ampdu_threshold = 3;
3993 	linkq.ampdu_limit = htole16(4000);	/* 4ms */
3994 
3995 	/* Use lowest mandatory bit-rate. */
3996 	rinfo = &iwn_rates[ridx];
3997 	linkq.retry[0].plcp = rinfo->plcp;
3998 	linkq.retry[0].rflags = rinfo->flags;
3999 	linkq.retry[0].rflags |= IWN_RFLAG_ANT(txant);
4000 	/* Use same bit-rate for all TX retries. */
4001 	for (i = 1; i < IWN_MAX_TX_RETRIES; i++) {
4002 		linkq.retry[i].plcp = linkq.retry[0].plcp;
4003 		linkq.retry[i].rflags = linkq.retry[0].rflags;
4004 	}
4005 	return iwn_cmd(sc, IWN_CMD_LINK_QUALITY, &linkq, sizeof linkq, async);
4006 }
4007 
4008 void
4009 iwn_updateedca(struct ieee80211com *ic)
4010 {
4011 #define IWN_EXP2(x)	((1 << (x)) - 1)	/* CWmin = 2^ECWmin - 1 */
4012 	struct iwn_softc *sc = ic->ic_softc;
4013 	struct iwn_edca_params cmd;
4014 	int aci;
4015 
4016 	memset(&cmd, 0, sizeof cmd);
4017 	cmd.flags = htole32(IWN_EDCA_UPDATE);
4018 	for (aci = 0; aci < EDCA_NUM_AC; aci++) {
4019 		const struct ieee80211_edca_ac_params *ac =
4020 		    &ic->ic_edca_ac[aci];
4021 		cmd.ac[aci].aifsn = ac->ac_aifsn;
4022 		cmd.ac[aci].cwmin = htole16(IWN_EXP2(ac->ac_ecwmin));
4023 		cmd.ac[aci].cwmax = htole16(IWN_EXP2(ac->ac_ecwmax));
4024 		cmd.ac[aci].txoplimit =
4025 		    htole16(IEEE80211_TXOP_TO_US(ac->ac_txoplimit));
4026 	}
4027 	(void)iwn_cmd(sc, IWN_CMD_EDCA_PARAMS, &cmd, sizeof cmd, 1);
4028 #undef IWN_EXP2
4029 }
4030 
4031 void
4032 iwn_set_led(struct iwn_softc *sc, uint8_t which, uint8_t off, uint8_t on)
4033 {
4034 	struct iwn_cmd_led led;
4035 
4036 	/* Clear microcode LED ownership. */
4037 	IWN_CLRBITS(sc, IWN_LED, IWN_LED_BSM_CTRL);
4038 
4039 	led.which = which;
4040 	led.unit = htole32(10000);	/* on/off in unit of 100ms */
4041 	led.off = off;
4042 	led.on = on;
4043 	(void)iwn_cmd(sc, IWN_CMD_SET_LED, &led, sizeof led, 1);
4044 }
4045 
4046 /*
4047  * Set the critical temperature at which the firmware will stop the radio
4048  * and notify us.
4049  */
4050 int
4051 iwn_set_critical_temp(struct iwn_softc *sc)
4052 {
4053 	struct iwn_critical_temp crit;
4054 	int32_t temp;
4055 
4056 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_CTEMP_STOP_RF);
4057 
4058 	if (sc->hw_type == IWN_HW_REV_TYPE_5150)
4059 		temp = (IWN_CTOK(110) - sc->temp_off) * -5;
4060 	else if (sc->hw_type == IWN_HW_REV_TYPE_4965)
4061 		temp = IWN_CTOK(110);
4062 	else
4063 		temp = 110;
4064 	memset(&crit, 0, sizeof crit);
4065 	crit.tempR = htole32(temp);
4066 	DPRINTF(("setting critical temperature to %d\n", temp));
4067 	return iwn_cmd(sc, IWN_CMD_SET_CRITICAL_TEMP, &crit, sizeof crit, 0);
4068 }
4069 
4070 int
4071 iwn_set_timing(struct iwn_softc *sc, struct ieee80211_node *ni)
4072 {
4073 	struct iwn_cmd_timing cmd;
4074 	uint64_t val, mod;
4075 
4076 	memset(&cmd, 0, sizeof cmd);
4077 	memcpy(&cmd.tstamp, ni->ni_tstamp, sizeof (uint64_t));
4078 	cmd.bintval = htole16(ni->ni_intval);
4079 	cmd.lintval = htole16(10);
4080 
4081 	/* Compute remaining time until next beacon. */
4082 	val = (uint64_t)ni->ni_intval * IEEE80211_DUR_TU;
4083 	mod = letoh64(cmd.tstamp) % val;
4084 	cmd.binitval = htole32((uint32_t)(val - mod));
4085 
4086 	DPRINTF(("timing bintval=%u, tstamp=%llu, init=%u\n",
4087 	    ni->ni_intval, letoh64(cmd.tstamp), (uint32_t)(val - mod)));
4088 
4089 	return iwn_cmd(sc, IWN_CMD_TIMING, &cmd, sizeof cmd, 1);
4090 }
4091 
4092 void
4093 iwn4965_power_calibration(struct iwn_softc *sc, int temp)
4094 {
4095 	/* Adjust TX power if need be (delta >= 3 degC). */
4096 	DPRINTF(("temperature %d->%d\n", sc->temp, temp));
4097 	if (abs(temp - sc->temp) >= 3) {
4098 		/* Record temperature of last calibration. */
4099 		sc->temp = temp;
4100 		(void)iwn4965_set_txpower(sc, 1);
4101 	}
4102 }
4103 
4104 /*
4105  * Set TX power for current channel (each rate has its own power settings).
4106  * This function takes into account the regulatory information from EEPROM,
4107  * the current temperature and the current voltage.
4108  */
4109 int
4110 iwn4965_set_txpower(struct iwn_softc *sc, int async)
4111 {
4112 /* Fixed-point arithmetic division using a n-bit fractional part. */
4113 #define fdivround(a, b, n)	\
4114 	((((1 << n) * (a)) / (b) + (1 << n) / 2) / (1 << n))
4115 /* Linear interpolation. */
4116 #define interpolate(x, x1, y1, x2, y2, n)	\
4117 	((y1) + fdivround(((int)(x) - (x1)) * ((y2) - (y1)), (x2) - (x1), n))
4118 
4119 	static const int tdiv[IWN_NATTEN_GROUPS] = { 9, 8, 8, 8, 6 };
4120 	struct ieee80211com *ic = &sc->sc_ic;
4121 	struct iwn_ucode_info *uc = &sc->ucode_info;
4122 	struct ieee80211_channel *ch;
4123 	struct iwn4965_cmd_txpower cmd;
4124 	struct iwn4965_eeprom_chan_samples *chans;
4125 	const uint8_t *rf_gain, *dsp_gain;
4126 	int32_t vdiff, tdiff;
4127 	int i, c, grp, maxpwr;
4128 	uint8_t chan;
4129 
4130 	/* Retrieve current channel from last RXON. */
4131 	chan = sc->rxon.chan;
4132 	DPRINTF(("setting TX power for channel %d\n", chan));
4133 	ch = &ic->ic_channels[chan];
4134 
4135 	memset(&cmd, 0, sizeof cmd);
4136 	cmd.band = IEEE80211_IS_CHAN_5GHZ(ch) ? 0 : 1;
4137 	cmd.chan = chan;
4138 
4139 	if (IEEE80211_IS_CHAN_5GHZ(ch)) {
4140 		maxpwr   = sc->maxpwr5GHz;
4141 		rf_gain  = iwn4965_rf_gain_5ghz;
4142 		dsp_gain = iwn4965_dsp_gain_5ghz;
4143 	} else {
4144 		maxpwr   = sc->maxpwr2GHz;
4145 		rf_gain  = iwn4965_rf_gain_2ghz;
4146 		dsp_gain = iwn4965_dsp_gain_2ghz;
4147 	}
4148 
4149 	/* Compute voltage compensation. */
4150 	vdiff = ((int32_t)letoh32(uc->volt) - sc->eeprom_voltage) / 7;
4151 	if (vdiff > 0)
4152 		vdiff *= 2;
4153 	if (abs(vdiff) > 2)
4154 		vdiff = 0;
4155 	DPRINTF(("voltage compensation=%d (UCODE=%d, EEPROM=%d)\n",
4156 	    vdiff, letoh32(uc->volt), sc->eeprom_voltage));
4157 
4158 	/* Get channel attenuation group. */
4159 	if (chan <= 20)		/* 1-20 */
4160 		grp = 4;
4161 	else if (chan <= 43)	/* 34-43 */
4162 		grp = 0;
4163 	else if (chan <= 70)	/* 44-70 */
4164 		grp = 1;
4165 	else if (chan <= 124)	/* 71-124 */
4166 		grp = 2;
4167 	else			/* 125-200 */
4168 		grp = 3;
4169 	DPRINTF(("chan %d, attenuation group=%d\n", chan, grp));
4170 
4171 	/* Get channel sub-band. */
4172 	for (i = 0; i < IWN_NBANDS; i++)
4173 		if (sc->bands[i].lo != 0 &&
4174 		    sc->bands[i].lo <= chan && chan <= sc->bands[i].hi)
4175 			break;
4176 	if (i == IWN_NBANDS)	/* Can't happen in real-life. */
4177 		return EINVAL;
4178 	chans = sc->bands[i].chans;
4179 	DPRINTF(("chan %d sub-band=%d\n", chan, i));
4180 
4181 	for (c = 0; c < 2; c++) {
4182 		uint8_t power, gain, temp;
4183 		int maxchpwr, pwr, ridx, idx;
4184 
4185 		power = interpolate(chan,
4186 		    chans[0].num, chans[0].samples[c][1].power,
4187 		    chans[1].num, chans[1].samples[c][1].power, 1);
4188 		gain  = interpolate(chan,
4189 		    chans[0].num, chans[0].samples[c][1].gain,
4190 		    chans[1].num, chans[1].samples[c][1].gain, 1);
4191 		temp  = interpolate(chan,
4192 		    chans[0].num, chans[0].samples[c][1].temp,
4193 		    chans[1].num, chans[1].samples[c][1].temp, 1);
4194 		DPRINTF(("TX chain %d: power=%d gain=%d temp=%d\n",
4195 		    c, power, gain, temp));
4196 
4197 		/* Compute temperature compensation. */
4198 		tdiff = ((sc->temp - temp) * 2) / tdiv[grp];
4199 		DPRINTF(("temperature compensation=%d (current=%d, "
4200 		    "EEPROM=%d)\n", tdiff, sc->temp, temp));
4201 
4202 		for (ridx = 0; ridx <= IWN_RIDX_MAX; ridx++) {
4203 			/* Convert dBm to half-dBm. */
4204 			maxchpwr = sc->maxpwr[chan] * 2;
4205 #ifdef notyet
4206 			if (ridx > iwn_mcs2ridx[7] && ridx < iwn_mcs2ridx[16])
4207 				maxchpwr -= 6;	/* MIMO 2T: -3dB */
4208 #endif
4209 
4210 			pwr = maxpwr;
4211 
4212 			/* Adjust TX power based on rate. */
4213 			if ((ridx % 8) == 5)
4214 				pwr -= 15;	/* OFDM48: -7.5dB */
4215 			else if ((ridx % 8) == 6)
4216 				pwr -= 17;	/* OFDM54: -8.5dB */
4217 			else if ((ridx % 8) == 7)
4218 				pwr -= 20;	/* OFDM60: -10dB */
4219 			else
4220 				pwr -= 10;	/* Others: -5dB */
4221 
4222 			/* Do not exceed channel max TX power. */
4223 			if (pwr > maxchpwr)
4224 				pwr = maxchpwr;
4225 
4226 			idx = gain - (pwr - power) - tdiff - vdiff;
4227 			if (ridx > iwn_mcs2ridx[7]) /* MIMO */
4228 				idx += (int32_t)letoh32(uc->atten[grp][c]);
4229 
4230 			if (cmd.band == 0)
4231 				idx += 9;	/* 5GHz */
4232 			if (ridx == IWN_RIDX_MAX)
4233 				idx += 5;	/* CCK */
4234 
4235 			/* Make sure idx stays in a valid range. */
4236 			if (idx < 0)
4237 				idx = 0;
4238 			else if (idx > IWN4965_MAX_PWR_INDEX)
4239 				idx = IWN4965_MAX_PWR_INDEX;
4240 
4241 			DPRINTF(("TX chain %d, rate idx %d: power=%d\n",
4242 			    c, ridx, idx));
4243 			cmd.power[ridx].rf_gain[c] = rf_gain[idx];
4244 			cmd.power[ridx].dsp_gain[c] = dsp_gain[idx];
4245 		}
4246 	}
4247 
4248 	DPRINTF(("setting TX power for chan %d\n", chan));
4249 	return iwn_cmd(sc, IWN_CMD_TXPOWER, &cmd, sizeof cmd, async);
4250 
4251 #undef interpolate
4252 #undef fdivround
4253 }
4254 
4255 int
4256 iwn5000_set_txpower(struct iwn_softc *sc, int async)
4257 {
4258 	struct iwn5000_cmd_txpower cmd;
4259 
4260 	/*
4261 	 * TX power calibration is handled automatically by the firmware
4262 	 * for 5000 Series.
4263 	 */
4264 	memset(&cmd, 0, sizeof cmd);
4265 	cmd.global_limit = 2 * IWN5000_TXPOWER_MAX_DBM;	/* 16 dBm */
4266 	cmd.flags = IWN5000_TXPOWER_NO_CLOSED;
4267 	cmd.srv_limit = IWN5000_TXPOWER_AUTO;
4268 	DPRINTF(("setting TX power\n"));
4269 	return iwn_cmd(sc, IWN_CMD_TXPOWER_DBM, &cmd, sizeof cmd, async);
4270 }
4271 
4272 /*
4273  * Retrieve the maximum RSSI (in dBm) among receivers.
4274  */
4275 int
4276 iwn4965_get_rssi(const struct iwn_rx_stat *stat)
4277 {
4278 	struct iwn4965_rx_phystat *phy = (void *)stat->phybuf;
4279 	uint8_t mask, agc;
4280 	int rssi;
4281 
4282 	mask = (letoh16(phy->antenna) >> 4) & IWN_ANT_ABC;
4283 	agc  = (letoh16(phy->agc) >> 7) & 0x7f;
4284 
4285 	rssi = 0;
4286 	if (mask & IWN_ANT_A)
4287 		rssi = MAX(rssi, phy->rssi[0]);
4288 	if (mask & IWN_ANT_B)
4289 		rssi = MAX(rssi, phy->rssi[2]);
4290 	if (mask & IWN_ANT_C)
4291 		rssi = MAX(rssi, phy->rssi[4]);
4292 
4293 	return rssi - agc - IWN_RSSI_TO_DBM;
4294 }
4295 
4296 int
4297 iwn5000_get_rssi(const struct iwn_rx_stat *stat)
4298 {
4299 	struct iwn5000_rx_phystat *phy = (void *)stat->phybuf;
4300 	uint8_t agc;
4301 	int rssi;
4302 
4303 	agc = (letoh32(phy->agc) >> 9) & 0x7f;
4304 
4305 	rssi = MAX(letoh16(phy->rssi[0]) & 0xff,
4306 		   letoh16(phy->rssi[1]) & 0xff);
4307 	rssi = MAX(letoh16(phy->rssi[2]) & 0xff, rssi);
4308 
4309 	return rssi - agc - IWN_RSSI_TO_DBM;
4310 }
4311 
4312 /*
4313  * Retrieve the average noise (in dBm) among receivers.
4314  */
4315 int
4316 iwn_get_noise(const struct iwn_rx_general_stats *stats)
4317 {
4318 	int i, total, nbant, noise;
4319 
4320 	total = nbant = 0;
4321 	for (i = 0; i < 3; i++) {
4322 		if ((noise = letoh32(stats->noise[i]) & 0xff) == 0)
4323 			continue;
4324 		total += noise;
4325 		nbant++;
4326 	}
4327 	/* There should be at least one antenna but check anyway. */
4328 	return (nbant == 0) ? -127 : (total / nbant) - 107;
4329 }
4330 
4331 /*
4332  * Compute temperature (in degC) from last received statistics.
4333  */
4334 int
4335 iwn4965_get_temperature(struct iwn_softc *sc)
4336 {
4337 	struct iwn_ucode_info *uc = &sc->ucode_info;
4338 	int32_t r1, r2, r3, r4, temp;
4339 
4340 	r1 = letoh32(uc->temp[0].chan20MHz);
4341 	r2 = letoh32(uc->temp[1].chan20MHz);
4342 	r3 = letoh32(uc->temp[2].chan20MHz);
4343 	r4 = letoh32(sc->rawtemp);
4344 
4345 	if (r1 == r3)	/* Prevents division by 0 (should not happen). */
4346 		return 0;
4347 
4348 	/* Sign-extend 23-bit R4 value to 32-bit. */
4349 	r4 = ((r4 & 0xffffff) ^ 0x800000) - 0x800000;
4350 	/* Compute temperature in Kelvin. */
4351 	temp = (259 * (r4 - r2)) / (r3 - r1);
4352 	temp = (temp * 97) / 100 + 8;
4353 
4354 	DPRINTF(("temperature %dK/%dC\n", temp, IWN_KTOC(temp)));
4355 	return IWN_KTOC(temp);
4356 }
4357 
4358 int
4359 iwn5000_get_temperature(struct iwn_softc *sc)
4360 {
4361 	int32_t temp;
4362 
4363 	/*
4364 	 * Temperature is not used by the driver for 5000 Series because
4365 	 * TX power calibration is handled by firmware.
4366 	 */
4367 	temp = letoh32(sc->rawtemp);
4368 	if (sc->hw_type == IWN_HW_REV_TYPE_5150) {
4369 		temp = (temp / -5) + sc->temp_off;
4370 		temp = IWN_KTOC(temp);
4371 	}
4372 	return temp;
4373 }
4374 
4375 /*
4376  * Initialize sensitivity calibration state machine.
4377  */
4378 int
4379 iwn_init_sensitivity(struct iwn_softc *sc)
4380 {
4381 	struct iwn_ops *ops = &sc->ops;
4382 	struct iwn_calib_state *calib = &sc->calib;
4383 	uint32_t flags;
4384 	int error;
4385 
4386 	/* Reset calibration state machine. */
4387 	memset(calib, 0, sizeof (*calib));
4388 	calib->state = IWN_CALIB_STATE_INIT;
4389 	calib->cck_state = IWN_CCK_STATE_HIFA;
4390 	/* Set initial correlation values. */
4391 	calib->ofdm_x1     = sc->limits->min_ofdm_x1;
4392 	calib->ofdm_mrc_x1 = sc->limits->min_ofdm_mrc_x1;
4393 	calib->ofdm_x4     = sc->limits->min_ofdm_x4;
4394 	calib->ofdm_mrc_x4 = sc->limits->min_ofdm_mrc_x4;
4395 	calib->cck_x4      = 125;
4396 	calib->cck_mrc_x4  = sc->limits->min_cck_mrc_x4;
4397 	calib->energy_cck  = sc->limits->energy_cck;
4398 
4399 	/* Write initial sensitivity. */
4400 	if ((error = iwn_send_sensitivity(sc)) != 0)
4401 		return error;
4402 
4403 	/* Write initial gains. */
4404 	if ((error = ops->init_gains(sc)) != 0)
4405 		return error;
4406 
4407 	/* Request statistics at each beacon interval. */
4408 	flags = 0;
4409 	DPRINTFN(2, ("sending request for statistics\n"));
4410 	return iwn_cmd(sc, IWN_CMD_GET_STATISTICS, &flags, sizeof flags, 1);
4411 }
4412 
4413 /*
4414  * Collect noise and RSSI statistics for the first 20 beacons received
4415  * after association and use them to determine connected antennas and
4416  * to set differential gains.
4417  */
4418 void
4419 iwn_collect_noise(struct iwn_softc *sc,
4420     const struct iwn_rx_general_stats *stats)
4421 {
4422 	struct iwn_ops *ops = &sc->ops;
4423 	struct iwn_calib_state *calib = &sc->calib;
4424 	uint32_t val;
4425 	int i;
4426 
4427 	/* Accumulate RSSI and noise for all 3 antennas. */
4428 	for (i = 0; i < 3; i++) {
4429 		calib->rssi[i] += letoh32(stats->rssi[i]) & 0xff;
4430 		calib->noise[i] += letoh32(stats->noise[i]) & 0xff;
4431 	}
4432 	/* NB: We update differential gains only once after 20 beacons. */
4433 	if (++calib->nbeacons < 20)
4434 		return;
4435 
4436 	/* Determine highest average RSSI. */
4437 	val = MAX(calib->rssi[0], calib->rssi[1]);
4438 	val = MAX(calib->rssi[2], val);
4439 
4440 	/* Determine which antennas are connected. */
4441 	sc->chainmask = sc->rxchainmask;
4442 	for (i = 0; i < 3; i++)
4443 		if (val - calib->rssi[i] > 15 * 20)
4444 			sc->chainmask &= ~(1 << i);
4445 	DPRINTF(("RX chains mask: theoretical=0x%x, actual=0x%x\n",
4446 	    sc->rxchainmask, sc->chainmask));
4447 
4448 	/* If none of the TX antennas are connected, keep at least one. */
4449 	if ((sc->chainmask & sc->txchainmask) == 0)
4450 		sc->chainmask |= IWN_LSB(sc->txchainmask);
4451 
4452 	(void)ops->set_gains(sc);
4453 	calib->state = IWN_CALIB_STATE_RUN;
4454 
4455 #ifdef notyet
4456 	/* XXX Disable RX chains with no antennas connected. */
4457 	sc->rxon.rxchain = htole16(IWN_RXCHAIN_SEL(sc->chainmask));
4458 	(void)iwn_cmd(sc, IWN_CMD_RXON, &sc->rxon, sc->rxonsz, 1);
4459 #endif
4460 
4461 	/* Enable power-saving mode if requested by user. */
4462 	if (sc->sc_ic.ic_flags & IEEE80211_F_PMGTON)
4463 		(void)iwn_set_pslevel(sc, 0, 3, 1);
4464 }
4465 
4466 int
4467 iwn4965_init_gains(struct iwn_softc *sc)
4468 {
4469 	struct iwn_phy_calib_gain cmd;
4470 
4471 	memset(&cmd, 0, sizeof cmd);
4472 	cmd.code = IWN4965_PHY_CALIB_DIFF_GAIN;
4473 	/* Differential gains initially set to 0 for all 3 antennas. */
4474 	DPRINTF(("setting initial differential gains\n"));
4475 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
4476 }
4477 
4478 int
4479 iwn5000_init_gains(struct iwn_softc *sc)
4480 {
4481 	struct iwn_phy_calib cmd;
4482 
4483 	memset(&cmd, 0, sizeof cmd);
4484 	cmd.code = sc->reset_noise_gain;
4485 	cmd.ngroups = 1;
4486 	cmd.isvalid = 1;
4487 	DPRINTF(("setting initial differential gains\n"));
4488 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
4489 }
4490 
4491 int
4492 iwn4965_set_gains(struct iwn_softc *sc)
4493 {
4494 	struct iwn_calib_state *calib = &sc->calib;
4495 	struct iwn_phy_calib_gain cmd;
4496 	int i, delta, noise;
4497 
4498 	/* Get minimal noise among connected antennas. */
4499 	noise = INT_MAX;	/* NB: There's at least one antenna. */
4500 	for (i = 0; i < 3; i++)
4501 		if (sc->chainmask & (1 << i))
4502 			noise = MIN(calib->noise[i], noise);
4503 
4504 	memset(&cmd, 0, sizeof cmd);
4505 	cmd.code = IWN4965_PHY_CALIB_DIFF_GAIN;
4506 	/* Set differential gains for connected antennas. */
4507 	for (i = 0; i < 3; i++) {
4508 		if (sc->chainmask & (1 << i)) {
4509 			/* Compute attenuation (in unit of 1.5dB). */
4510 			delta = (noise - (int32_t)calib->noise[i]) / 30;
4511 			/* NB: delta <= 0 */
4512 			/* Limit to [-4.5dB,0]. */
4513 			cmd.gain[i] = MIN(abs(delta), 3);
4514 			if (delta < 0)
4515 				cmd.gain[i] |= 1 << 2;	/* sign bit */
4516 		}
4517 	}
4518 	DPRINTF(("setting differential gains Ant A/B/C: %x/%x/%x (%x)\n",
4519 	    cmd.gain[0], cmd.gain[1], cmd.gain[2], sc->chainmask));
4520 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
4521 }
4522 
4523 int
4524 iwn5000_set_gains(struct iwn_softc *sc)
4525 {
4526 	struct iwn_calib_state *calib = &sc->calib;
4527 	struct iwn_phy_calib_gain cmd;
4528 	int i, ant, div, delta;
4529 
4530 	/* We collected 20 beacons and !=6050 need a 1.5 factor. */
4531 	div = (sc->hw_type == IWN_HW_REV_TYPE_6050) ? 20 : 30;
4532 
4533 	memset(&cmd, 0, sizeof cmd);
4534 	cmd.code = sc->noise_gain;
4535 	cmd.ngroups = 1;
4536 	cmd.isvalid = 1;
4537 	/*
4538 	 * Get first available RX antenna as referential.
4539 	 * IWN_LSB() return values start with 1, but antenna gain array
4540 	 * cmd.gain[] and noise array calib->noise[] start with 0.
4541 	 */
4542 	ant = IWN_LSB(sc->rxchainmask) - 1;
4543 
4544 	/* Set differential gains for other antennas. */
4545 	for (i = ant + 1; i < 3; i++) {
4546 		if (sc->chainmask & (1 << i)) {
4547 			/* The delta is relative to antenna "ant". */
4548 			delta = ((int32_t)calib->noise[ant] -
4549 			    (int32_t)calib->noise[i]) / div;
4550 			DPRINTF(("Ant[%d] vs. Ant[%d]: delta %d\n", ant, i, delta));
4551 			/* Limit to [-4.5dB,+4.5dB]. */
4552 			cmd.gain[i] = MIN(abs(delta), 3);
4553 			if (delta < 0)
4554 				cmd.gain[i] |= 1 << 2;	/* sign bit */
4555 			DPRINTF(("Setting differential gains for antenna %d: %x\n",
4556 				i, cmd.gain[i]));
4557 		}
4558 	}
4559 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
4560 }
4561 
4562 /*
4563  * Tune RF RX sensitivity based on the number of false alarms detected
4564  * during the last beacon period.
4565  */
4566 void
4567 iwn_tune_sensitivity(struct iwn_softc *sc, const struct iwn_rx_stats *stats)
4568 {
4569 #define inc(val, inc, max)			\
4570 	if ((val) < (max)) {			\
4571 		if ((val) < (max) - (inc))	\
4572 			(val) += (inc);		\
4573 		else				\
4574 			(val) = (max);		\
4575 		needs_update = 1;		\
4576 	}
4577 #define dec(val, dec, min)			\
4578 	if ((val) > (min)) {			\
4579 		if ((val) > (min) + (dec))	\
4580 			(val) -= (dec);		\
4581 		else				\
4582 			(val) = (min);		\
4583 		needs_update = 1;		\
4584 	}
4585 
4586 	const struct iwn_sensitivity_limits *limits = sc->limits;
4587 	struct iwn_calib_state *calib = &sc->calib;
4588 	uint32_t val, rxena, fa;
4589 	uint32_t energy[3], energy_min;
4590 	uint8_t noise[3], noise_ref;
4591 	int i, needs_update = 0;
4592 
4593 	/* Check that we've been enabled long enough. */
4594 	if ((rxena = letoh32(stats->general.load)) == 0)
4595 		return;
4596 
4597 	/* Compute number of false alarms since last call for OFDM. */
4598 	fa  = letoh32(stats->ofdm.bad_plcp) - calib->bad_plcp_ofdm;
4599 	fa += letoh32(stats->ofdm.fa) - calib->fa_ofdm;
4600 	fa *= 200 * IEEE80211_DUR_TU;	/* 200TU */
4601 
4602 	/* Save counters values for next call. */
4603 	calib->bad_plcp_ofdm = letoh32(stats->ofdm.bad_plcp);
4604 	calib->fa_ofdm = letoh32(stats->ofdm.fa);
4605 
4606 	if (fa > 50 * rxena) {
4607 		/* High false alarm count, decrease sensitivity. */
4608 		DPRINTFN(2, ("OFDM high false alarm count: %u\n", fa));
4609 		inc(calib->ofdm_x1,     1, limits->max_ofdm_x1);
4610 		inc(calib->ofdm_mrc_x1, 1, limits->max_ofdm_mrc_x1);
4611 		inc(calib->ofdm_x4,     1, limits->max_ofdm_x4);
4612 		inc(calib->ofdm_mrc_x4, 1, limits->max_ofdm_mrc_x4);
4613 
4614 	} else if (fa < 5 * rxena) {
4615 		/* Low false alarm count, increase sensitivity. */
4616 		DPRINTFN(2, ("OFDM low false alarm count: %u\n", fa));
4617 		dec(calib->ofdm_x1,     1, limits->min_ofdm_x1);
4618 		dec(calib->ofdm_mrc_x1, 1, limits->min_ofdm_mrc_x1);
4619 		dec(calib->ofdm_x4,     1, limits->min_ofdm_x4);
4620 		dec(calib->ofdm_mrc_x4, 1, limits->min_ofdm_mrc_x4);
4621 	}
4622 
4623 	/* Compute maximum noise among 3 receivers. */
4624 	for (i = 0; i < 3; i++)
4625 		noise[i] = (letoh32(stats->general.noise[i]) >> 8) & 0xff;
4626 	val = MAX(noise[0], noise[1]);
4627 	val = MAX(noise[2], val);
4628 	/* Insert it into our samples table. */
4629 	calib->noise_samples[calib->cur_noise_sample] = val;
4630 	calib->cur_noise_sample = (calib->cur_noise_sample + 1) % 20;
4631 
4632 	/* Compute maximum noise among last 20 samples. */
4633 	noise_ref = calib->noise_samples[0];
4634 	for (i = 1; i < 20; i++)
4635 		noise_ref = MAX(noise_ref, calib->noise_samples[i]);
4636 
4637 	/* Compute maximum energy among 3 receivers. */
4638 	for (i = 0; i < 3; i++)
4639 		energy[i] = letoh32(stats->general.energy[i]);
4640 	val = MIN(energy[0], energy[1]);
4641 	val = MIN(energy[2], val);
4642 	/* Insert it into our samples table. */
4643 	calib->energy_samples[calib->cur_energy_sample] = val;
4644 	calib->cur_energy_sample = (calib->cur_energy_sample + 1) % 10;
4645 
4646 	/* Compute minimum energy among last 10 samples. */
4647 	energy_min = calib->energy_samples[0];
4648 	for (i = 1; i < 10; i++)
4649 		energy_min = MAX(energy_min, calib->energy_samples[i]);
4650 	energy_min += 6;
4651 
4652 	/* Compute number of false alarms since last call for CCK. */
4653 	fa  = letoh32(stats->cck.bad_plcp) - calib->bad_plcp_cck;
4654 	fa += letoh32(stats->cck.fa) - calib->fa_cck;
4655 	fa *= 200 * IEEE80211_DUR_TU;	/* 200TU */
4656 
4657 	/* Save counters values for next call. */
4658 	calib->bad_plcp_cck = letoh32(stats->cck.bad_plcp);
4659 	calib->fa_cck = letoh32(stats->cck.fa);
4660 
4661 	if (fa > 50 * rxena) {
4662 		/* High false alarm count, decrease sensitivity. */
4663 		DPRINTFN(2, ("CCK high false alarm count: %u\n", fa));
4664 		calib->cck_state = IWN_CCK_STATE_HIFA;
4665 		calib->low_fa = 0;
4666 
4667 		if (calib->cck_x4 > 160) {
4668 			calib->noise_ref = noise_ref;
4669 			if (calib->energy_cck > 2)
4670 				dec(calib->energy_cck, 2, energy_min);
4671 		}
4672 		if (calib->cck_x4 < 160) {
4673 			calib->cck_x4 = 161;
4674 			needs_update = 1;
4675 		} else
4676 			inc(calib->cck_x4, 3, limits->max_cck_x4);
4677 
4678 		inc(calib->cck_mrc_x4, 3, limits->max_cck_mrc_x4);
4679 
4680 	} else if (fa < 5 * rxena) {
4681 		/* Low false alarm count, increase sensitivity. */
4682 		DPRINTFN(2, ("CCK low false alarm count: %u\n", fa));
4683 		calib->cck_state = IWN_CCK_STATE_LOFA;
4684 		calib->low_fa++;
4685 
4686 		if (calib->cck_state != IWN_CCK_STATE_INIT &&
4687 		    (((int32_t)calib->noise_ref - (int32_t)noise_ref) > 2 ||
4688 		     calib->low_fa > 100)) {
4689 			inc(calib->energy_cck, 2, limits->min_energy_cck);
4690 			dec(calib->cck_x4,     3, limits->min_cck_x4);
4691 			dec(calib->cck_mrc_x4, 3, limits->min_cck_mrc_x4);
4692 		}
4693 	} else {
4694 		/* Not worth to increase or decrease sensitivity. */
4695 		DPRINTFN(2, ("CCK normal false alarm count: %u\n", fa));
4696 		calib->low_fa = 0;
4697 		calib->noise_ref = noise_ref;
4698 
4699 		if (calib->cck_state == IWN_CCK_STATE_HIFA) {
4700 			/* Previous interval had many false alarms. */
4701 			dec(calib->energy_cck, 8, energy_min);
4702 		}
4703 		calib->cck_state = IWN_CCK_STATE_INIT;
4704 	}
4705 
4706 	if (needs_update)
4707 		(void)iwn_send_sensitivity(sc);
4708 #undef dec
4709 #undef inc
4710 }
4711 
4712 int
4713 iwn_send_sensitivity(struct iwn_softc *sc)
4714 {
4715 	struct iwn_calib_state *calib = &sc->calib;
4716 	struct iwn_enhanced_sensitivity_cmd cmd;
4717 	int len;
4718 
4719 	memset(&cmd, 0, sizeof cmd);
4720 	len = sizeof (struct iwn_sensitivity_cmd);
4721 	cmd.which = IWN_SENSITIVITY_WORKTBL;
4722 	/* OFDM modulation. */
4723 	cmd.corr_ofdm_x1       = htole16(calib->ofdm_x1);
4724 	cmd.corr_ofdm_mrc_x1   = htole16(calib->ofdm_mrc_x1);
4725 	cmd.corr_ofdm_x4       = htole16(calib->ofdm_x4);
4726 	cmd.corr_ofdm_mrc_x4   = htole16(calib->ofdm_mrc_x4);
4727 	cmd.energy_ofdm        = htole16(sc->limits->energy_ofdm);
4728 	cmd.energy_ofdm_th     = htole16(62);
4729 	/* CCK modulation. */
4730 	cmd.corr_cck_x4        = htole16(calib->cck_x4);
4731 	cmd.corr_cck_mrc_x4    = htole16(calib->cck_mrc_x4);
4732 	cmd.energy_cck         = htole16(calib->energy_cck);
4733 	/* Barker modulation: use default values. */
4734 	cmd.corr_barker        = htole16(190);
4735 	cmd.corr_barker_mrc    = htole16(390);
4736 	if (!(sc->sc_flags & IWN_FLAG_ENH_SENS))
4737 		goto send;
4738 	/* Enhanced sensitivity settings. */
4739 	len = sizeof (struct iwn_enhanced_sensitivity_cmd);
4740 	cmd.ofdm_det_slope_mrc = htole16(668);
4741 	cmd.ofdm_det_icept_mrc = htole16(4);
4742 	cmd.ofdm_det_slope     = htole16(486);
4743 	cmd.ofdm_det_icept     = htole16(37);
4744 	cmd.cck_det_slope_mrc  = htole16(853);
4745 	cmd.cck_det_icept_mrc  = htole16(4);
4746 	cmd.cck_det_slope      = htole16(476);
4747 	cmd.cck_det_icept      = htole16(99);
4748 send:
4749 	return iwn_cmd(sc, IWN_CMD_SET_SENSITIVITY, &cmd, len, 1);
4750 }
4751 
4752 /*
4753  * Set STA mode power saving level (between 0 and 5).
4754  * Level 0 is CAM (Continuously Aware Mode), 5 is for maximum power saving.
4755  */
4756 int
4757 iwn_set_pslevel(struct iwn_softc *sc, int dtim, int level, int async)
4758 {
4759 	struct iwn_pmgt_cmd cmd;
4760 	const struct iwn_pmgt *pmgt;
4761 	uint32_t max, skip_dtim;
4762 	pcireg_t reg;
4763 	int i;
4764 
4765 	/* Select which PS parameters to use. */
4766 	if (dtim <= 2)
4767 		pmgt = &iwn_pmgt[0][level];
4768 	else if (dtim <= 10)
4769 		pmgt = &iwn_pmgt[1][level];
4770 	else
4771 		pmgt = &iwn_pmgt[2][level];
4772 
4773 	memset(&cmd, 0, sizeof cmd);
4774 	if (level != 0)	/* not CAM */
4775 		cmd.flags |= htole16(IWN_PS_ALLOW_SLEEP);
4776 	if (level == 5)
4777 		cmd.flags |= htole16(IWN_PS_FAST_PD);
4778 	/* Retrieve PCIe Active State Power Management (ASPM). */
4779 	reg = pci_conf_read(sc->sc_pct, sc->sc_pcitag,
4780 	    sc->sc_cap_off + PCI_PCIE_LCSR);
4781 	if (!(reg & PCI_PCIE_LCSR_ASPM_L0S))	/* L0s Entry disabled. */
4782 		cmd.flags |= htole16(IWN_PS_PCI_PMGT);
4783 	cmd.rxtimeout = htole32(pmgt->rxtimeout * 1024);
4784 	cmd.txtimeout = htole32(pmgt->txtimeout * 1024);
4785 
4786 	if (dtim == 0) {
4787 		dtim = 1;
4788 		skip_dtim = 0;
4789 	} else
4790 		skip_dtim = pmgt->skip_dtim;
4791 	if (skip_dtim != 0) {
4792 		cmd.flags |= htole16(IWN_PS_SLEEP_OVER_DTIM);
4793 		max = pmgt->intval[4];
4794 		if (max == (uint32_t)-1)
4795 			max = dtim * (skip_dtim + 1);
4796 		else if (max > dtim)
4797 			max = (max / dtim) * dtim;
4798 	} else
4799 		max = dtim;
4800 	for (i = 0; i < 5; i++)
4801 		cmd.intval[i] = htole32(MIN(max, pmgt->intval[i]));
4802 
4803 	DPRINTF(("setting power saving level to %d\n", level));
4804 	return iwn_cmd(sc, IWN_CMD_SET_POWER_MODE, &cmd, sizeof cmd, async);
4805 }
4806 
4807 int
4808 iwn_send_btcoex(struct iwn_softc *sc)
4809 {
4810 	struct iwn_bluetooth cmd;
4811 
4812 	memset(&cmd, 0, sizeof cmd);
4813 	cmd.flags = IWN_BT_COEX_CHAN_ANN | IWN_BT_COEX_BT_PRIO;
4814 	cmd.lead_time = IWN_BT_LEAD_TIME_DEF;
4815 	cmd.max_kill = IWN_BT_MAX_KILL_DEF;
4816 	DPRINTF(("configuring bluetooth coexistence\n"));
4817 	return iwn_cmd(sc, IWN_CMD_BT_COEX, &cmd, sizeof(cmd), 0);
4818 }
4819 
4820 int
4821 iwn_send_advanced_btcoex(struct iwn_softc *sc)
4822 {
4823 	static const uint32_t btcoex_3wire[12] = {
4824 		0xaaaaaaaa, 0xaaaaaaaa, 0xaeaaaaaa, 0xaaaaaaaa,
4825 		0xcc00ff28, 0x0000aaaa, 0xcc00aaaa, 0x0000aaaa,
4826 		0xc0004000, 0x00004000, 0xf0005000, 0xf0005000,
4827 	};
4828 	struct iwn_btcoex_priotable btprio;
4829 	struct iwn_btcoex_prot btprot;
4830 	int error, i;
4831 
4832 	if (sc->hw_type == IWN_HW_REV_TYPE_2030 ||
4833 	    sc->hw_type == IWN_HW_REV_TYPE_135) {
4834 		struct iwn2000_btcoex_config btconfig;
4835 
4836 		memset(&btconfig, 0, sizeof btconfig);
4837 		btconfig.flags = IWN_BT_COEX6000_CHAN_INHIBITION |
4838 		    (IWN_BT_COEX6000_MODE_3W << IWN_BT_COEX6000_MODE_SHIFT) |
4839 		    IWN_BT_SYNC_2_BT_DISABLE;
4840 		btconfig.max_kill = 5;
4841 		btconfig.bt3_t7_timer = 1;
4842 		btconfig.kill_ack = htole32(0xffff0000);
4843 		btconfig.kill_cts = htole32(0xffff0000);
4844 		btconfig.sample_time = 2;
4845 		btconfig.bt3_t2_timer = 0xc;
4846 		for (i = 0; i < 12; i++)
4847 			btconfig.lookup_table[i] = htole32(btcoex_3wire[i]);
4848 		btconfig.valid = htole16(0xff);
4849 		btconfig.prio_boost = htole32(0xf0);
4850 		DPRINTF(("configuring advanced bluetooth coexistence\n"));
4851 		error = iwn_cmd(sc, IWN_CMD_BT_COEX, &btconfig,
4852 		    sizeof(btconfig), 1);
4853 		if (error != 0)
4854 			return (error);
4855 	} else {
4856 		struct iwn6000_btcoex_config btconfig;
4857 
4858 		memset(&btconfig, 0, sizeof btconfig);
4859 		btconfig.flags = IWN_BT_COEX6000_CHAN_INHIBITION |
4860 		    (IWN_BT_COEX6000_MODE_3W << IWN_BT_COEX6000_MODE_SHIFT) |
4861 		    IWN_BT_SYNC_2_BT_DISABLE;
4862 		btconfig.max_kill = 5;
4863 		btconfig.bt3_t7_timer = 1;
4864 		btconfig.kill_ack = htole32(0xffff0000);
4865 		btconfig.kill_cts = htole32(0xffff0000);
4866 		btconfig.sample_time = 2;
4867 		btconfig.bt3_t2_timer = 0xc;
4868 		for (i = 0; i < 12; i++)
4869 			btconfig.lookup_table[i] = htole32(btcoex_3wire[i]);
4870 		btconfig.valid = htole16(0xff);
4871 		btconfig.prio_boost = 0xf0;
4872 		DPRINTF(("configuring advanced bluetooth coexistence\n"));
4873 		error = iwn_cmd(sc, IWN_CMD_BT_COEX, &btconfig,
4874 		    sizeof(btconfig), 1);
4875 		if (error != 0)
4876 			return (error);
4877 	}
4878 
4879 	memset(&btprio, 0, sizeof btprio);
4880 	btprio.calib_init1 = 0x6;
4881 	btprio.calib_init2 = 0x7;
4882 	btprio.calib_periodic_low1 = 0x2;
4883 	btprio.calib_periodic_low2 = 0x3;
4884 	btprio.calib_periodic_high1 = 0x4;
4885 	btprio.calib_periodic_high2 = 0x5;
4886 	btprio.dtim = 0x6;
4887 	btprio.scan52 = 0x8;
4888 	btprio.scan24 = 0xa;
4889 	error = iwn_cmd(sc, IWN_CMD_BT_COEX_PRIOTABLE, &btprio, sizeof(btprio),
4890 	    1);
4891 	if (error != 0)
4892 		return (error);
4893 
4894 	/* Force BT state machine change */
4895 	memset(&btprot, 0, sizeof btprot);
4896 	btprot.open = 1;
4897 	btprot.type = 1;
4898 	error = iwn_cmd(sc, IWN_CMD_BT_COEX_PROT, &btprot, sizeof(btprot), 1);
4899 	if (error != 0)
4900 		return (error);
4901 
4902 	btprot.open = 0;
4903 	return (iwn_cmd(sc, IWN_CMD_BT_COEX_PROT, &btprot, sizeof(btprot), 1));
4904 }
4905 
4906 int
4907 iwn5000_runtime_calib(struct iwn_softc *sc)
4908 {
4909 	struct iwn5000_calib_config cmd;
4910 
4911 	memset(&cmd, 0, sizeof cmd);
4912 	cmd.ucode.once.enable = 0xffffffff;
4913 	cmd.ucode.once.start = IWN5000_CALIB_DC;
4914 	DPRINTF(("configuring runtime calibration\n"));
4915 	return iwn_cmd(sc, IWN5000_CMD_CALIB_CONFIG, &cmd, sizeof(cmd), 0);
4916 }
4917 
4918 int
4919 iwn_config(struct iwn_softc *sc)
4920 {
4921 	struct iwn_ops *ops = &sc->ops;
4922 	struct ieee80211com *ic = &sc->sc_ic;
4923 	struct ifnet *ifp = &ic->ic_if;
4924 	uint32_t txmask;
4925 	uint16_t rxchain;
4926 	int error, ridx;
4927 
4928 	/* Set radio temperature sensor offset. */
4929 	if (sc->hw_type == IWN_HW_REV_TYPE_6005) {
4930 		error = iwn6000_temp_offset_calib(sc);
4931 		if (error != 0) {
4932 			printf("%s: could not set temperature offset\n",
4933 			    sc->sc_dev.dv_xname);
4934 			return error;
4935 		}
4936 	}
4937 
4938 	if (sc->hw_type == IWN_HW_REV_TYPE_2030 ||
4939 	    sc->hw_type == IWN_HW_REV_TYPE_2000 ||
4940 	    sc->hw_type == IWN_HW_REV_TYPE_135 ||
4941 	    sc->hw_type == IWN_HW_REV_TYPE_105) {
4942 		error = iwn2000_temp_offset_calib(sc);
4943 		if (error != 0) {
4944 			printf("%s: could not set temperature offset\n",
4945 			    sc->sc_dev.dv_xname);
4946 			return error;
4947 		}
4948 	}
4949 
4950 	if (sc->hw_type == IWN_HW_REV_TYPE_6050 ||
4951 	    sc->hw_type == IWN_HW_REV_TYPE_6005) {
4952 		/* Configure runtime DC calibration. */
4953 		error = iwn5000_runtime_calib(sc);
4954 		if (error != 0) {
4955 			printf("%s: could not configure runtime calibration\n",
4956 			    sc->sc_dev.dv_xname);
4957 			return error;
4958 		}
4959 	}
4960 
4961 	/* Configure valid TX chains for >=5000 Series. */
4962 	if (sc->hw_type != IWN_HW_REV_TYPE_4965) {
4963 		txmask = htole32(sc->txchainmask);
4964 		DPRINTF(("configuring valid TX chains 0x%x\n", txmask));
4965 		error = iwn_cmd(sc, IWN5000_CMD_TX_ANT_CONFIG, &txmask,
4966 		    sizeof txmask, 0);
4967 		if (error != 0) {
4968 			printf("%s: could not configure valid TX chains\n",
4969 			    sc->sc_dev.dv_xname);
4970 			return error;
4971 		}
4972 	}
4973 
4974 	/* Configure bluetooth coexistence. */
4975 	if (sc->sc_flags & IWN_FLAG_ADV_BT_COEX)
4976 		error = iwn_send_advanced_btcoex(sc);
4977 	else
4978 		error = iwn_send_btcoex(sc);
4979 	if (error != 0) {
4980 		printf("%s: could not configure bluetooth coexistence\n",
4981 		    sc->sc_dev.dv_xname);
4982 		return error;
4983 	}
4984 
4985 	/* Set mode, channel, RX filter and enable RX. */
4986 	memset(&sc->rxon, 0, sizeof (struct iwn_rxon));
4987 	IEEE80211_ADDR_COPY(ic->ic_myaddr, LLADDR(ifp->if_sadl));
4988 	IEEE80211_ADDR_COPY(sc->rxon.myaddr, ic->ic_myaddr);
4989 	IEEE80211_ADDR_COPY(sc->rxon.wlap, ic->ic_myaddr);
4990 	sc->rxon.chan = ieee80211_chan2ieee(ic, ic->ic_ibss_chan);
4991 	sc->rxon.flags = htole32(IWN_RXON_TSF | IWN_RXON_CTS_TO_SELF);
4992 	if (IEEE80211_IS_CHAN_2GHZ(ic->ic_ibss_chan)) {
4993 		sc->rxon.flags |= htole32(IWN_RXON_AUTO | IWN_RXON_24GHZ);
4994 		if (ic->ic_flags & IEEE80211_F_USEPROT)
4995 			sc->rxon.flags |= htole32(IWN_RXON_TGG_PROT);
4996 		DPRINTF(("%s: 2ghz prot 0x%x\n", __func__,
4997 		    le32toh(sc->rxon.flags)));
4998 	}
4999 	switch (ic->ic_opmode) {
5000 	case IEEE80211_M_STA:
5001 		sc->rxon.mode = IWN_MODE_STA;
5002 		sc->rxon.filter = htole32(IWN_FILTER_MULTICAST);
5003 		break;
5004 	case IEEE80211_M_MONITOR:
5005 		sc->rxon.mode = IWN_MODE_MONITOR;
5006 		sc->rxon.filter = htole32(IWN_FILTER_MULTICAST |
5007 		    IWN_FILTER_CTL | IWN_FILTER_PROMISC);
5008 		break;
5009 	default:
5010 		/* Should not get there. */
5011 		break;
5012 	}
5013 	sc->rxon.cck_mask  = 0x0f;	/* not yet negotiated */
5014 	sc->rxon.ofdm_mask = 0xff;	/* not yet negotiated */
5015 	sc->rxon.ht_single_mask = 0xff;
5016 	sc->rxon.ht_dual_mask = 0xff;
5017 	sc->rxon.ht_triple_mask = 0xff;
5018 	rxchain =
5019 	    IWN_RXCHAIN_VALID(sc->rxchainmask) |
5020 	    IWN_RXCHAIN_MIMO_COUNT(sc->nrxchains) |
5021 	    IWN_RXCHAIN_IDLE_COUNT(sc->nrxchains);
5022 	if (ic->ic_opmode == IEEE80211_M_MONITOR) {
5023 		rxchain |= IWN_RXCHAIN_FORCE_SEL(sc->rxchainmask);
5024 		rxchain |= IWN_RXCHAIN_FORCE_MIMO_SEL(sc->rxchainmask);
5025 	    	rxchain |= (IWN_RXCHAIN_DRIVER_FORCE | IWN_RXCHAIN_MIMO_FORCE);
5026 	}
5027 	sc->rxon.rxchain = htole16(rxchain);
5028 	DPRINTF(("setting configuration\n"));
5029 	DPRINTF(("%s: rxon chan %d flags %x cck %x ofdm %x rxchain %x\n",
5030 	    __func__, sc->rxon.chan, le32toh(sc->rxon.flags), sc->rxon.cck_mask,
5031 	    sc->rxon.ofdm_mask, sc->rxon.rxchain));
5032 	error = iwn_cmd(sc, IWN_CMD_RXON, &sc->rxon, sc->rxonsz, 0);
5033 	if (error != 0) {
5034 		printf("%s: RXON command failed\n", sc->sc_dev.dv_xname);
5035 		return error;
5036 	}
5037 
5038 	ridx = (sc->sc_ic.ic_curmode == IEEE80211_MODE_11A) ?
5039 	    IWN_RIDX_OFDM6 : IWN_RIDX_CCK1;
5040 	if ((error = iwn_add_broadcast_node(sc, 0, ridx)) != 0) {
5041 		printf("%s: could not add broadcast node\n",
5042 		    sc->sc_dev.dv_xname);
5043 		return error;
5044 	}
5045 
5046 	/* Configuration has changed, set TX power accordingly. */
5047 	if ((error = ops->set_txpower(sc, 0)) != 0) {
5048 		printf("%s: could not set TX power\n", sc->sc_dev.dv_xname);
5049 		return error;
5050 	}
5051 
5052 	if ((error = iwn_set_critical_temp(sc)) != 0) {
5053 		printf("%s: could not set critical temperature\n",
5054 		    sc->sc_dev.dv_xname);
5055 		return error;
5056 	}
5057 
5058 	/* Set power saving level to CAM during initialization. */
5059 	if ((error = iwn_set_pslevel(sc, 0, 0, 0)) != 0) {
5060 		printf("%s: could not set power saving level\n",
5061 		    sc->sc_dev.dv_xname);
5062 		return error;
5063 	}
5064 	return 0;
5065 }
5066 
5067 uint16_t
5068 iwn_get_active_dwell_time(struct iwn_softc *sc,
5069     uint16_t flags, uint8_t n_probes)
5070 {
5071 	/* No channel? Default to 2GHz settings */
5072 	if (flags & IEEE80211_CHAN_2GHZ) {
5073 		return (IWN_ACTIVE_DWELL_TIME_2GHZ +
5074 		IWN_ACTIVE_DWELL_FACTOR_2GHZ * (n_probes + 1));
5075 	}
5076 
5077 	/* 5GHz dwell time */
5078 	return (IWN_ACTIVE_DWELL_TIME_5GHZ +
5079 	    IWN_ACTIVE_DWELL_FACTOR_5GHZ * (n_probes + 1));
5080 }
5081 
5082 /*
5083  * Limit the total dwell time to 85% of the beacon interval.
5084  *
5085  * Returns the dwell time in milliseconds.
5086  */
5087 uint16_t
5088 iwn_limit_dwell(struct iwn_softc *sc, uint16_t dwell_time)
5089 {
5090 	struct ieee80211com *ic = &sc->sc_ic;
5091 	struct ieee80211_node *ni = ic->ic_bss;
5092 	int bintval = 0;
5093 
5094 	/* bintval is in TU (1.024mS) */
5095 	if (ni != NULL)
5096 		bintval = ni->ni_intval;
5097 
5098 	/*
5099 	 * If it's non-zero, we should calculate the minimum of
5100 	 * it and the DWELL_BASE.
5101 	 *
5102 	 * XXX Yes, the math should take into account that bintval
5103 	 * is 1.024mS, not 1mS..
5104 	 */
5105 	if (ic->ic_state == IEEE80211_S_RUN && bintval > 0)
5106 		return (MIN(IWN_PASSIVE_DWELL_BASE, ((bintval * 85) / 100)));
5107 
5108 	/* No association context? Default */
5109 	return dwell_time;
5110 }
5111 
5112 uint16_t
5113 iwn_get_passive_dwell_time(struct iwn_softc *sc, uint16_t flags)
5114 {
5115 	uint16_t passive;
5116 	if (flags & IEEE80211_CHAN_2GHZ) {
5117 		passive = IWN_PASSIVE_DWELL_BASE + IWN_PASSIVE_DWELL_TIME_2GHZ;
5118 	} else {
5119 		passive = IWN_PASSIVE_DWELL_BASE + IWN_PASSIVE_DWELL_TIME_5GHZ;
5120 	}
5121 
5122 	/* Clamp to the beacon interval if we're associated */
5123 	return (iwn_limit_dwell(sc, passive));
5124 }
5125 
5126 int
5127 iwn_scan(struct iwn_softc *sc, uint16_t flags, int bgscan)
5128 {
5129 	struct ieee80211com *ic = &sc->sc_ic;
5130 	struct iwn_scan_hdr *hdr;
5131 	struct iwn_cmd_data *tx;
5132 	struct iwn_scan_essid *essid;
5133 	struct iwn_scan_chan *chan;
5134 	struct ieee80211_frame *wh;
5135 	struct ieee80211_rateset *rs;
5136 	struct ieee80211_channel *c;
5137 	uint8_t *buf, *frm;
5138 	uint16_t rxchain, dwell_active, dwell_passive;
5139 	uint8_t txant;
5140 	int buflen, error, is_active;
5141 
5142 	buf = malloc(IWN_SCAN_MAXSZ, M_DEVBUF, M_NOWAIT | M_ZERO);
5143 	if (buf == NULL) {
5144 		printf("%s: could not allocate buffer for scan command\n",
5145 		    sc->sc_dev.dv_xname);
5146 		return ENOMEM;
5147 	}
5148 	hdr = (struct iwn_scan_hdr *)buf;
5149 	/*
5150 	 * Move to the next channel if no frames are received within 10ms
5151 	 * after sending the probe request.
5152 	 */
5153 	hdr->quiet_time = htole16(10);		/* timeout in milliseconds */
5154 	hdr->quiet_threshold = htole16(1);	/* min # of packets */
5155 
5156 	if (bgscan) {
5157 		int bintval;
5158 
5159 		/* Set maximum off-channel time. */
5160 		hdr->max_out = htole32(200 * 1024);
5161 
5162 		/* Configure scan pauses which service on-channel traffic. */
5163 		bintval = ic->ic_bss->ni_intval ? ic->ic_bss->ni_intval : 100;
5164 		hdr->pause_scan = htole32(((100 / bintval) << 22) |
5165 		    ((100 % bintval) * 1024));
5166 	}
5167 
5168 	/* Select antennas for scanning. */
5169 	rxchain =
5170 	    IWN_RXCHAIN_VALID(sc->rxchainmask) |
5171 	    IWN_RXCHAIN_FORCE_MIMO_SEL(sc->rxchainmask) |
5172 	    IWN_RXCHAIN_DRIVER_FORCE;
5173 	if ((flags & IEEE80211_CHAN_5GHZ) &&
5174 	    sc->hw_type == IWN_HW_REV_TYPE_4965) {
5175 		/*
5176 		 * On 4965 ant A and C must be avoided in 5GHz because of a
5177 		 * HW bug which causes very weak RSSI values being reported.
5178 		 */
5179 		rxchain |= IWN_RXCHAIN_FORCE_SEL(IWN_ANT_B);
5180 	} else	/* Use all available RX antennas. */
5181 		rxchain |= IWN_RXCHAIN_FORCE_SEL(sc->rxchainmask);
5182 	hdr->rxchain = htole16(rxchain);
5183 	hdr->filter = htole32(IWN_FILTER_MULTICAST | IWN_FILTER_BEACON);
5184 
5185 	tx = (struct iwn_cmd_data *)(hdr + 1);
5186 	tx->flags = htole32(IWN_TX_AUTO_SEQ);
5187 	tx->id = sc->broadcast_id;
5188 	tx->lifetime = htole32(IWN_LIFETIME_INFINITE);
5189 
5190 	if (flags & IEEE80211_CHAN_5GHZ) {
5191 		/* Send probe requests at 6Mbps. */
5192 		tx->plcp = iwn_rates[IWN_RIDX_OFDM6].plcp;
5193 		rs = &ic->ic_sup_rates[IEEE80211_MODE_11A];
5194 	} else {
5195 		hdr->flags = htole32(IWN_RXON_24GHZ | IWN_RXON_AUTO);
5196 		if (bgscan && sc->hw_type == IWN_HW_REV_TYPE_4965 &&
5197 		    sc->rxon.chan > 14) {
5198 			/*
5199 			 * 4965 firmware can crash when sending probe requests
5200 			 * with CCK rates while associated to a 5GHz AP.
5201 			 * Send probe requests at 6Mbps OFDM as a workaround.
5202 			 */
5203 			tx->plcp = iwn_rates[IWN_RIDX_OFDM6].plcp;
5204 		} else {
5205 			/* Send probe requests at 1Mbps. */
5206 			tx->plcp = iwn_rates[IWN_RIDX_CCK1].plcp;
5207 			tx->rflags = IWN_RFLAG_CCK;
5208 		}
5209 		rs = &ic->ic_sup_rates[IEEE80211_MODE_11G];
5210 	}
5211 	/* Use the first valid TX antenna. */
5212 	txant = IWN_LSB(sc->txchainmask);
5213 	tx->rflags |= IWN_RFLAG_ANT(txant);
5214 
5215 	/*
5216 	 * Only do active scanning if we're announcing a probe request
5217 	 * for a given SSID (or more, if we ever add it to the driver.)
5218 	 */
5219 	is_active = 0;
5220 
5221 	/*
5222 	 * If we're scanning for a specific SSID, add it to the command.
5223 	 */
5224 	essid = (struct iwn_scan_essid *)(tx + 1);
5225 	if (ic->ic_des_esslen != 0) {
5226 		essid[0].id = IEEE80211_ELEMID_SSID;
5227 		essid[0].len = ic->ic_des_esslen;
5228 		memcpy(essid[0].data, ic->ic_des_essid, ic->ic_des_esslen);
5229 
5230 		is_active = 1;
5231 	}
5232 	/*
5233 	 * Build a probe request frame.  Most of the following code is a
5234 	 * copy & paste of what is done in net80211.
5235 	 */
5236 	wh = (struct ieee80211_frame *)(essid + 20);
5237 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
5238 	    IEEE80211_FC0_SUBTYPE_PROBE_REQ;
5239 	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
5240 	IEEE80211_ADDR_COPY(wh->i_addr1, etherbroadcastaddr);
5241 	IEEE80211_ADDR_COPY(wh->i_addr2, ic->ic_myaddr);
5242 	IEEE80211_ADDR_COPY(wh->i_addr3, etherbroadcastaddr);
5243 	*(uint16_t *)&wh->i_dur[0] = 0;	/* filled by HW */
5244 	*(uint16_t *)&wh->i_seq[0] = 0;	/* filled by HW */
5245 
5246 	frm = (uint8_t *)(wh + 1);
5247 	frm = ieee80211_add_ssid(frm, NULL, 0);
5248 	frm = ieee80211_add_rates(frm, rs);
5249 	if (rs->rs_nrates > IEEE80211_RATE_SIZE)
5250 		frm = ieee80211_add_xrates(frm, rs);
5251 	if (ic->ic_flags & IEEE80211_F_HTON)
5252 		frm = ieee80211_add_htcaps(frm, ic);
5253 
5254 	/* Set length of probe request. */
5255 	tx->len = htole16(frm - (uint8_t *)wh);
5256 
5257 	/*
5258 	 * If active scanning is requested but a certain channel is
5259 	 * marked passive, we can do active scanning if we detect
5260 	 * transmissions.
5261 	 *
5262 	 * There is an issue with some firmware versions that triggers
5263 	 * a sysassert on a "good CRC threshold" of zero (== disabled),
5264 	 * on a radar channel even though this means that we should NOT
5265 	 * send probes.
5266 	 *
5267 	 * The "good CRC threshold" is the number of frames that we
5268 	 * need to receive during our dwell time on a channel before
5269 	 * sending out probes -- setting this to a huge value will
5270 	 * mean we never reach it, but at the same time work around
5271 	 * the aforementioned issue. Thus use IWN_GOOD_CRC_TH_NEVER
5272 	 * here instead of IWN_GOOD_CRC_TH_DISABLED.
5273 	 *
5274 	 * This was fixed in later versions along with some other
5275 	 * scan changes, and the threshold behaves as a flag in those
5276 	 * versions.
5277 	 */
5278 
5279 	/*
5280 	 * If we're doing active scanning, set the crc_threshold
5281 	 * to a suitable value.  This is different to active veruss
5282 	 * passive scanning depending upon the channel flags; the
5283 	 * firmware will obey that particular check for us.
5284 	 */
5285 	if (sc->tlv_feature_flags & IWN_UCODE_TLV_FLAGS_NEWSCAN)
5286 		hdr->crc_threshold = is_active ?
5287 		    IWN_GOOD_CRC_TH_DEFAULT : IWN_GOOD_CRC_TH_DISABLED;
5288 	else
5289 		hdr->crc_threshold = is_active ?
5290 		    IWN_GOOD_CRC_TH_DEFAULT : IWN_GOOD_CRC_TH_NEVER;
5291 
5292 	chan = (struct iwn_scan_chan *)frm;
5293 	for (c  = &ic->ic_channels[1];
5294 	     c <= &ic->ic_channels[IEEE80211_CHAN_MAX]; c++) {
5295 		if ((c->ic_flags & flags) != flags)
5296 			continue;
5297 
5298 		chan->chan = htole16(ieee80211_chan2ieee(ic, c));
5299 		DPRINTFN(2, ("adding channel %d\n", chan->chan));
5300 		chan->flags = 0;
5301 		if (ic->ic_des_esslen != 0)
5302 			chan->flags |= htole32(IWN_CHAN_NPBREQS(1));
5303 
5304 		if (c->ic_flags & IEEE80211_CHAN_PASSIVE)
5305 			chan->flags |= htole32(IWN_CHAN_PASSIVE);
5306 		else
5307 			chan->flags |= htole32(IWN_CHAN_ACTIVE);
5308 
5309 		/*
5310 		 * Calculate the active/passive dwell times.
5311 		 */
5312 
5313 		dwell_active = iwn_get_active_dwell_time(sc, flags, is_active);
5314 		dwell_passive = iwn_get_passive_dwell_time(sc, flags);
5315 
5316 		/* Make sure they're valid */
5317 		if (dwell_passive <= dwell_active)
5318 			dwell_passive = dwell_active + 1;
5319 
5320 		chan->active = htole16(dwell_active);
5321 		chan->passive = htole16(dwell_passive);
5322 
5323 		chan->dsp_gain = 0x6e;
5324 		if (IEEE80211_IS_CHAN_5GHZ(c)) {
5325 			chan->rf_gain = 0x3b;
5326 		} else {
5327 			chan->rf_gain = 0x28;
5328 		}
5329 		hdr->nchan++;
5330 		chan++;
5331 	}
5332 
5333 	buflen = (uint8_t *)chan - buf;
5334 	hdr->len = htole16(buflen);
5335 
5336 	error = iwn_cmd(sc, IWN_CMD_SCAN, buf, buflen, 1);
5337 	if (error == 0) {
5338 		/*
5339 		 * The current mode might have been fixed during association.
5340 		 * Ensure all channels get scanned.
5341 		 */
5342 		if (IFM_MODE(ic->ic_media.ifm_cur->ifm_media) == IFM_AUTO)
5343 			ieee80211_setmode(ic, IEEE80211_MODE_AUTO);
5344 
5345 		sc->sc_flags |= IWN_FLAG_SCANNING;
5346 		if (bgscan)
5347 			sc->sc_flags |= IWN_FLAG_BGSCAN;
5348 	}
5349 	free(buf, M_DEVBUF, IWN_SCAN_MAXSZ);
5350 	return error;
5351 }
5352 
5353 void
5354 iwn_scan_abort(struct iwn_softc *sc)
5355 {
5356 	iwn_cmd(sc, IWN_CMD_SCAN_ABORT, NULL, 0, 1);
5357 
5358 	/* XXX Cannot wait for status response in interrupt context. */
5359 	DELAY(100);
5360 
5361 	sc->sc_flags &= ~IWN_FLAG_SCANNING;
5362 	sc->sc_flags &= ~IWN_FLAG_BGSCAN;
5363 }
5364 
5365 int
5366 iwn_bgscan(struct ieee80211com *ic)
5367 {
5368 	struct iwn_softc *sc = ic->ic_softc;
5369 	int error;
5370 
5371 	if (sc->sc_flags & IWN_FLAG_SCANNING)
5372 		return 0;
5373 
5374 	error = iwn_scan(sc, IEEE80211_CHAN_2GHZ, 1);
5375 	if (error)
5376 		printf("%s: could not initiate background scan\n",
5377 		    sc->sc_dev.dv_xname);
5378 	return error;
5379 }
5380 
5381 int
5382 iwn_auth(struct iwn_softc *sc, int arg)
5383 {
5384 	struct iwn_ops *ops = &sc->ops;
5385 	struct ieee80211com *ic = &sc->sc_ic;
5386 	struct ieee80211_node *ni = ic->ic_bss;
5387 	int error, ridx;
5388 	int bss_switch =
5389 	    (!IEEE80211_ADDR_EQ(sc->bss_node_addr, etheranyaddr) &&
5390 	    !IEEE80211_ADDR_EQ(sc->bss_node_addr, ni->ni_macaddr));
5391 
5392 	/* Update adapter configuration. */
5393 	IEEE80211_ADDR_COPY(sc->rxon.bssid, ni->ni_bssid);
5394 	sc->rxon.chan = ieee80211_chan2ieee(ic, ni->ni_chan);
5395 	sc->rxon.flags = htole32(IWN_RXON_TSF | IWN_RXON_CTS_TO_SELF);
5396 	if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan)) {
5397 		sc->rxon.flags |= htole32(IWN_RXON_AUTO | IWN_RXON_24GHZ);
5398 		if (ic->ic_flags & IEEE80211_F_USEPROT)
5399 			sc->rxon.flags |= htole32(IWN_RXON_TGG_PROT);
5400 		DPRINTF(("%s: 2ghz prot 0x%x\n", __func__,
5401 		    le32toh(sc->rxon.flags)));
5402 	}
5403 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
5404 		sc->rxon.flags |= htole32(IWN_RXON_SHSLOT);
5405 	else
5406 		sc->rxon.flags &= ~htole32(IWN_RXON_SHSLOT);
5407 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
5408 		sc->rxon.flags |= htole32(IWN_RXON_SHPREAMBLE);
5409 	else
5410 		sc->rxon.flags &= ~htole32(IWN_RXON_SHPREAMBLE);
5411 	switch (ic->ic_curmode) {
5412 	case IEEE80211_MODE_11A:
5413 		sc->rxon.cck_mask  = 0;
5414 		sc->rxon.ofdm_mask = 0x15;
5415 		break;
5416 	case IEEE80211_MODE_11B:
5417 		sc->rxon.cck_mask  = 0x03;
5418 		sc->rxon.ofdm_mask = 0;
5419 		break;
5420 	default:	/* Assume 802.11b/g/n. */
5421 		sc->rxon.cck_mask  = 0x0f;
5422 		sc->rxon.ofdm_mask = 0x15;
5423 	}
5424 	DPRINTF(("%s: rxon chan %d flags %x cck %x ofdm %x\n", __func__,
5425 	    sc->rxon.chan, le32toh(sc->rxon.flags), sc->rxon.cck_mask,
5426 	    sc->rxon.ofdm_mask));
5427 	error = iwn_cmd(sc, IWN_CMD_RXON, &sc->rxon, sc->rxonsz, 1);
5428 	if (error != 0) {
5429 		printf("%s: RXON command failed\n", sc->sc_dev.dv_xname);
5430 		return error;
5431 	}
5432 
5433 	/* Configuration has changed, set TX power accordingly. */
5434 	if ((error = ops->set_txpower(sc, 1)) != 0) {
5435 		printf("%s: could not set TX power\n", sc->sc_dev.dv_xname);
5436 		return error;
5437 	}
5438 	/*
5439 	 * Reconfiguring RXON clears the firmware nodes table so we must
5440 	 * add the broadcast node again.
5441 	 */
5442 	ridx = IEEE80211_IS_CHAN_5GHZ(ni->ni_chan) ?
5443 	    IWN_RIDX_OFDM6 : IWN_RIDX_CCK1;
5444 	if ((error = iwn_add_broadcast_node(sc, 1, ridx)) != 0) {
5445 		printf("%s: could not add broadcast node\n",
5446 		    sc->sc_dev.dv_xname);
5447 		return error;
5448 	}
5449 
5450 	/*
5451 	 * Make sure the firmware gets to see a beacon before we send
5452 	 * the auth request. Otherwise the Tx attempt can fail due to
5453 	 * the firmware's built-in regulatory domain enforcement.
5454 	 * Delaying here for every incoming deauth frame can result in a DoS.
5455 	 * Don't delay if we're here because of an incoming frame (arg != -1)
5456 	 * or if we're already waiting for a response (ic_mgt_timer != 0).
5457 	 * If we are switching APs after a background scan then net80211 has
5458 	 * just faked the reception of a deauth frame from our old AP, so it
5459 	 * is safe to delay in that case.
5460 	 */
5461 	if ((arg == -1 || bss_switch) && ic->ic_mgt_timer == 0)
5462 		DELAY(ni->ni_intval * 3 * IEEE80211_DUR_TU);
5463 
5464 	/* We can now clear the cached address of our previous AP. */
5465 	memset(sc->bss_node_addr, 0, sizeof(sc->bss_node_addr));
5466 
5467 	return 0;
5468 }
5469 
5470 int
5471 iwn_run(struct iwn_softc *sc)
5472 {
5473 	struct iwn_ops *ops = &sc->ops;
5474 	struct ieee80211com *ic = &sc->sc_ic;
5475 	struct ieee80211_node *ni = ic->ic_bss;
5476 	struct iwn_node *wn = (void *)ni;
5477 	struct iwn_node_info node;
5478 	int error;
5479 
5480 	if (ic->ic_opmode == IEEE80211_M_MONITOR) {
5481 		/* Link LED blinks while monitoring. */
5482 		iwn_set_led(sc, IWN_LED_LINK, 50, 50);
5483 		return 0;
5484 	}
5485 	if ((error = iwn_set_timing(sc, ni)) != 0) {
5486 		printf("%s: could not set timing\n", sc->sc_dev.dv_xname);
5487 		return error;
5488 	}
5489 
5490 	/* Update adapter configuration. */
5491 	sc->rxon.associd = htole16(IEEE80211_AID(ni->ni_associd));
5492 	/* Short preamble and slot time are negotiated when associating. */
5493 	sc->rxon.flags &= ~htole32(IWN_RXON_SHPREAMBLE | IWN_RXON_SHSLOT);
5494 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
5495 		sc->rxon.flags |= htole32(IWN_RXON_SHSLOT);
5496 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
5497 		sc->rxon.flags |= htole32(IWN_RXON_SHPREAMBLE);
5498 	sc->rxon.filter |= htole32(IWN_FILTER_BSS);
5499 
5500 	/* HT is negotiated when associating. */
5501 	if (ni->ni_flags & IEEE80211_NODE_HT) {
5502 		enum ieee80211_htprot htprot =
5503 		    (ni->ni_htop1 & IEEE80211_HTOP1_PROT_MASK);
5504 		DPRINTF(("%s: htprot = %d\n", __func__, htprot));
5505 		sc->rxon.flags |= htole32(IWN_RXON_HT_PROTMODE(htprot));
5506 	} else
5507 		sc->rxon.flags &= ~htole32(IWN_RXON_HT_PROTMODE(3));
5508 
5509 	if (IEEE80211_IS_CHAN_5GHZ(ni->ni_chan)) {
5510 		/* 11a or 11n 5GHz */
5511 		sc->rxon.cck_mask  = 0;
5512 		sc->rxon.ofdm_mask = 0x15;
5513 	} else if (ni->ni_flags & IEEE80211_NODE_HT) {
5514 		/* 11n 2GHz */
5515 		sc->rxon.cck_mask  = 0x0f;
5516 		sc->rxon.ofdm_mask = 0x15;
5517 	} else {
5518 		if (ni->ni_rates.rs_nrates == 4) {
5519 			/* 11b */
5520 			sc->rxon.cck_mask  = 0x03;
5521 			sc->rxon.ofdm_mask = 0;
5522 		} else {
5523 			/* assume 11g */
5524 			sc->rxon.cck_mask  = 0x0f;
5525 			sc->rxon.ofdm_mask = 0x15;
5526 		}
5527 	}
5528 	DPRINTF(("%s: rxon chan %d flags %x cck %x ofdm %x\n", __func__,
5529 	    sc->rxon.chan, le32toh(sc->rxon.flags), sc->rxon.cck_mask,
5530 	    sc->rxon.ofdm_mask));
5531 	error = iwn_cmd(sc, IWN_CMD_RXON, &sc->rxon, sc->rxonsz, 1);
5532 	if (error != 0) {
5533 		printf("%s: could not update configuration\n",
5534 		    sc->sc_dev.dv_xname);
5535 		return error;
5536 	}
5537 
5538 	/* Configuration has changed, set TX power accordingly. */
5539 	if ((error = ops->set_txpower(sc, 1)) != 0) {
5540 		printf("%s: could not set TX power\n", sc->sc_dev.dv_xname);
5541 		return error;
5542 	}
5543 
5544 	/* Fake a join to initialize the TX rate. */
5545 	((struct iwn_node *)ni)->id = IWN_ID_BSS;
5546 	iwn_newassoc(ic, ni, 1);
5547 
5548 	/* Add BSS node. */
5549 	memset(&node, 0, sizeof node);
5550 	IEEE80211_ADDR_COPY(node.macaddr, ni->ni_macaddr);
5551 	node.id = IWN_ID_BSS;
5552 	if (ni->ni_flags & IEEE80211_NODE_HT) {
5553 		node.htmask = (IWN_AMDPU_SIZE_FACTOR_MASK |
5554 		    IWN_AMDPU_DENSITY_MASK);
5555 		node.htflags = htole32(
5556 		    IWN_AMDPU_SIZE_FACTOR(
5557 			(ic->ic_ampdu_params & IEEE80211_AMPDU_PARAM_LE)) |
5558 		    IWN_AMDPU_DENSITY(
5559 			(ic->ic_ampdu_params & IEEE80211_AMPDU_PARAM_SS) >> 2));
5560 	}
5561 	DPRINTF(("adding BSS node\n"));
5562 	error = ops->add_node(sc, &node, 1);
5563 	if (error != 0) {
5564 		printf("%s: could not add BSS node\n", sc->sc_dev.dv_xname);
5565 		return error;
5566 	}
5567 
5568 	/* Cache address of AP in case it changes after a background scan. */
5569 	IEEE80211_ADDR_COPY(sc->bss_node_addr, ni->ni_macaddr);
5570 
5571 	DPRINTF(("setting link quality for node %d\n", node.id));
5572 	if ((error = iwn_set_link_quality(sc, ni)) != 0) {
5573 		printf("%s: could not setup link quality for node %d\n",
5574 		    sc->sc_dev.dv_xname, node.id);
5575 		return error;
5576 	}
5577 
5578 	if ((error = iwn_init_sensitivity(sc)) != 0) {
5579 		printf("%s: could not set sensitivity\n",
5580 		    sc->sc_dev.dv_xname);
5581 		return error;
5582 	}
5583 	/* Start periodic calibration timer. */
5584 	sc->calib.state = IWN_CALIB_STATE_ASSOC;
5585 	sc->calib_cnt = 0;
5586 	timeout_add_msec(&sc->calib_to, 500);
5587 
5588 	ieee80211_ra_node_init(&wn->rn);
5589 
5590 	/* Link LED always on while associated. */
5591 	iwn_set_led(sc, IWN_LED_LINK, 0, 1);
5592 	return 0;
5593 }
5594 
5595 /*
5596  * We support CCMP hardware encryption/decryption of unicast frames only.
5597  * HW support for TKIP really sucks.  We should let TKIP die anyway.
5598  */
5599 int
5600 iwn_set_key(struct ieee80211com *ic, struct ieee80211_node *ni,
5601     struct ieee80211_key *k)
5602 {
5603 	struct iwn_softc *sc = ic->ic_softc;
5604 	struct iwn_ops *ops = &sc->ops;
5605 	struct iwn_node *wn = (void *)ni;
5606 	struct iwn_node_info node;
5607 	uint16_t kflags;
5608 
5609 	if ((k->k_flags & IEEE80211_KEY_GROUP) ||
5610 	    k->k_cipher != IEEE80211_CIPHER_CCMP)
5611 		return ieee80211_set_key(ic, ni, k);
5612 
5613 	kflags = IWN_KFLAG_CCMP | IWN_KFLAG_MAP | IWN_KFLAG_KID(k->k_id);
5614 	if (k->k_flags & IEEE80211_KEY_GROUP)
5615 		kflags |= IWN_KFLAG_GROUP;
5616 
5617 	memset(&node, 0, sizeof node);
5618 	node.id = (k->k_flags & IEEE80211_KEY_GROUP) ?
5619 	    sc->broadcast_id : wn->id;
5620 	node.control = IWN_NODE_UPDATE;
5621 	node.flags = IWN_FLAG_SET_KEY;
5622 	node.kflags = htole16(kflags);
5623 	node.kid = k->k_id;
5624 	memcpy(node.key, k->k_key, k->k_len);
5625 	DPRINTF(("set key id=%d for node %d\n", k->k_id, node.id));
5626 	return ops->add_node(sc, &node, 1);
5627 }
5628 
5629 void
5630 iwn_delete_key(struct ieee80211com *ic, struct ieee80211_node *ni,
5631     struct ieee80211_key *k)
5632 {
5633 	struct iwn_softc *sc = ic->ic_softc;
5634 	struct iwn_ops *ops = &sc->ops;
5635 	struct iwn_node *wn = (void *)ni;
5636 	struct iwn_node_info node;
5637 
5638 	if ((k->k_flags & IEEE80211_KEY_GROUP) ||
5639 	    k->k_cipher != IEEE80211_CIPHER_CCMP) {
5640 		/* See comment about other ciphers above. */
5641 		ieee80211_delete_key(ic, ni, k);
5642 		return;
5643 	}
5644 	if (ic->ic_state != IEEE80211_S_RUN)
5645 		return;	/* Nothing to do. */
5646 	memset(&node, 0, sizeof node);
5647 	node.id = (k->k_flags & IEEE80211_KEY_GROUP) ?
5648 	    sc->broadcast_id : wn->id;
5649 	node.control = IWN_NODE_UPDATE;
5650 	node.flags = IWN_FLAG_SET_KEY;
5651 	node.kflags = htole16(IWN_KFLAG_INVALID);
5652 	node.kid = 0xff;
5653 	DPRINTF(("delete keys for node %d\n", node.id));
5654 	(void)ops->add_node(sc, &node, 1);
5655 }
5656 
5657 void
5658 iwn_updateprot(struct ieee80211com *ic)
5659 {
5660 	struct iwn_softc *sc = ic->ic_softc;
5661 	enum ieee80211_htprot htprot;
5662 
5663 	if (ic->ic_state != IEEE80211_S_RUN)
5664 		return;
5665 
5666 	/* Update ERP protection setting. */
5667 	if (ic->ic_flags & IEEE80211_F_USEPROT)
5668 		sc->rxon.flags |= htole32(IWN_RXON_TGG_PROT);
5669 	else
5670 		sc->rxon.flags &= ~htole32(IWN_RXON_TGG_PROT);
5671 
5672 	/* Update HT protection mode setting. */
5673 	htprot = (ic->ic_bss->ni_htop1 & IEEE80211_HTOP1_PROT_MASK) >>
5674 	    IEEE80211_HTOP1_PROT_SHIFT;
5675 	sc->rxon.flags &= ~htole32(IWN_RXON_HT_PROTMODE(3));
5676 	sc->rxon.flags |= htole32(IWN_RXON_HT_PROTMODE(htprot));
5677 
5678 	iwn_update_rxon(sc);
5679 }
5680 
5681 void
5682 iwn_updateslot(struct ieee80211com *ic)
5683 {
5684 	struct iwn_softc *sc = ic->ic_softc;
5685 
5686 	if (ic->ic_state != IEEE80211_S_RUN)
5687 		return;
5688 
5689 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
5690 		sc->rxon.flags |= htole32(IWN_RXON_SHSLOT);
5691 	else
5692 		sc->rxon.flags &= ~htole32(IWN_RXON_SHSLOT);
5693 
5694 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
5695 		sc->rxon.flags |= htole32(IWN_RXON_SHPREAMBLE);
5696 	else
5697 		sc->rxon.flags &= ~htole32(IWN_RXON_SHPREAMBLE);
5698 
5699 	iwn_update_rxon(sc);
5700 }
5701 void
5702 iwn_update_rxon(struct iwn_softc *sc)
5703 {
5704 	struct ieee80211com *ic = &sc->sc_ic;
5705 	struct iwn_ops *ops = &sc->ops;
5706 	struct iwn_rxon_assoc rxon_assoc;
5707 	int s, error;
5708 
5709 	/* Update RXON config. */
5710 	memset(&rxon_assoc, 0, sizeof(rxon_assoc));
5711 	rxon_assoc.flags = sc->rxon.flags;
5712 	rxon_assoc.filter = sc->rxon.filter;
5713 	rxon_assoc.ofdm_mask = sc->rxon.ofdm_mask;
5714 	rxon_assoc.cck_mask = sc->rxon.cck_mask;
5715 	rxon_assoc.ht_single_mask = sc->rxon.ht_single_mask;
5716 	rxon_assoc.ht_dual_mask = sc->rxon.ht_dual_mask;
5717 	rxon_assoc.ht_triple_mask = sc->rxon.ht_triple_mask;
5718 	rxon_assoc.rxchain = sc->rxon.rxchain;
5719 	rxon_assoc.acquisition = sc->rxon.acquisition;
5720 
5721 	s = splnet();
5722 
5723 	error = iwn_cmd(sc, IWN_CMD_RXON_ASSOC, &rxon_assoc,
5724 	    sizeof(rxon_assoc), 1);
5725 	if (error != 0)
5726 		printf("%s: RXON_ASSOC command failed\n", sc->sc_dev.dv_xname);
5727 
5728 	DELAY(100);
5729 
5730 	/* All RXONs wipe the firmware's txpower table. Restore it. */
5731 	error = ops->set_txpower(sc, 1);
5732 	if (error != 0)
5733 		printf("%s: could not set TX power\n", sc->sc_dev.dv_xname);
5734 
5735 	DELAY(100);
5736 
5737 	/* Restore power saving level */
5738 	if (ic->ic_flags & IEEE80211_F_PMGTON)
5739 		error = iwn_set_pslevel(sc, 0, 3, 1);
5740 	else
5741 		error = iwn_set_pslevel(sc, 0, 0, 1);
5742 	if (error != 0)
5743 		printf("%s: could not set PS level\n", sc->sc_dev.dv_xname);
5744 
5745 	splx(s);
5746 }
5747 
5748 /*
5749  * This function is called by upper layer when an ADDBA request is received
5750  * from another STA and before the ADDBA response is sent.
5751  */
5752 int
5753 iwn_ampdu_rx_start(struct ieee80211com *ic, struct ieee80211_node *ni,
5754     uint8_t tid)
5755 {
5756 	struct ieee80211_rx_ba *ba = &ni->ni_rx_ba[tid];
5757 	struct iwn_softc *sc = ic->ic_softc;
5758 	struct iwn_ops *ops = &sc->ops;
5759 	struct iwn_node *wn = (void *)ni;
5760 	struct iwn_node_info node;
5761 
5762 	memset(&node, 0, sizeof node);
5763 	node.id = wn->id;
5764 	node.control = IWN_NODE_UPDATE;
5765 	node.flags = IWN_FLAG_SET_ADDBA;
5766 	node.addba_tid = tid;
5767 	node.addba_ssn = htole16(ba->ba_winstart);
5768 	DPRINTF(("ADDBA RA=%d TID=%d SSN=%d\n", wn->id, tid,
5769 	    ba->ba_winstart));
5770 	/* XXX async command, so firmware may still fail to add BA agreement */
5771 	return ops->add_node(sc, &node, 1);
5772 }
5773 
5774 /*
5775  * This function is called by upper layer on teardown of an HT-immediate
5776  * Block Ack agreement (eg. uppon receipt of a DELBA frame).
5777  */
5778 void
5779 iwn_ampdu_rx_stop(struct ieee80211com *ic, struct ieee80211_node *ni,
5780     uint8_t tid)
5781 {
5782 	struct iwn_softc *sc = ic->ic_softc;
5783 	struct iwn_ops *ops = &sc->ops;
5784 	struct iwn_node *wn = (void *)ni;
5785 	struct iwn_node_info node;
5786 
5787 	memset(&node, 0, sizeof node);
5788 	node.id = wn->id;
5789 	node.control = IWN_NODE_UPDATE;
5790 	node.flags = IWN_FLAG_SET_DELBA;
5791 	node.delba_tid = tid;
5792 	DPRINTF(("DELBA RA=%d TID=%d\n", wn->id, tid));
5793 	(void)ops->add_node(sc, &node, 1);
5794 }
5795 
5796 /*
5797  * This function is called by upper layer when an ADDBA response is received
5798  * from another STA.
5799  */
5800 int
5801 iwn_ampdu_tx_start(struct ieee80211com *ic, struct ieee80211_node *ni,
5802     uint8_t tid)
5803 {
5804 	struct ieee80211_tx_ba *ba = &ni->ni_tx_ba[tid];
5805 	struct iwn_softc *sc = ic->ic_softc;
5806 	struct iwn_ops *ops = &sc->ops;
5807 	struct iwn_node *wn = (void *)ni;
5808 	struct iwn_node_info node;
5809 	int qid = sc->first_agg_txq + tid;
5810 	int error;
5811 
5812 	/* Ensure we can map this TID to an aggregation queue. */
5813 	if (tid >= IWN_NUM_AMPDU_TID || ba->ba_winsize > IWN_SCHED_WINSZ ||
5814 	    qid > sc->ntxqs || (sc->agg_queue_mask & (1 << qid)))
5815 		return ENOSPC;
5816 
5817 	/* Enable TX for the specified RA/TID. */
5818 	wn->disable_tid &= ~(1 << tid);
5819 	memset(&node, 0, sizeof node);
5820 	node.id = wn->id;
5821 	node.control = IWN_NODE_UPDATE;
5822 	node.flags = IWN_FLAG_SET_DISABLE_TID;
5823 	node.disable_tid = htole16(wn->disable_tid);
5824 	error = ops->add_node(sc, &node, 1);
5825 	if (error != 0)
5826 		return error;
5827 
5828 	if ((error = iwn_nic_lock(sc)) != 0)
5829 		return error;
5830 	ops->ampdu_tx_start(sc, ni, tid, ba->ba_winstart);
5831 	iwn_nic_unlock(sc);
5832 
5833 	sc->agg_queue_mask |= (1 << qid);
5834 	sc->sc_tx_ba[tid].wn = wn;
5835 	ba->ba_bitmap = 0;
5836 
5837 	return 0;
5838 }
5839 
5840 void
5841 iwn_ampdu_tx_stop(struct ieee80211com *ic, struct ieee80211_node *ni,
5842     uint8_t tid)
5843 {
5844 	struct ieee80211_tx_ba *ba = &ni->ni_tx_ba[tid];
5845 	struct iwn_softc *sc = ic->ic_softc;
5846 	struct iwn_ops *ops = &sc->ops;
5847 	int qid = sc->first_agg_txq + tid;
5848 	struct iwn_node *wn = (void *)ni;
5849 	struct iwn_node_info node;
5850 
5851 	/* Discard all frames in the current window. */
5852 	iwn_ampdu_txq_advance(sc, &sc->txq[qid], qid,
5853 	    IWN_AGG_SSN_TO_TXQ_IDX(ba->ba_winend));
5854 
5855 	if (iwn_nic_lock(sc) != 0)
5856 		return;
5857 	ops->ampdu_tx_stop(sc, tid, ba->ba_winstart);
5858 	iwn_nic_unlock(sc);
5859 
5860 	sc->agg_queue_mask &= ~(1 << qid);
5861 	sc->sc_tx_ba[tid].wn = NULL;
5862 	ba->ba_bitmap = 0;
5863 
5864 	/* Disable TX for the specified RA/TID. */
5865 	wn->disable_tid |= (1 << tid);
5866 	memset(&node, 0, sizeof node);
5867 	node.id = wn->id;
5868 	node.control = IWN_NODE_UPDATE;
5869 	node.flags = IWN_FLAG_SET_DISABLE_TID;
5870 	node.disable_tid = htole16(wn->disable_tid);
5871 	ops->add_node(sc, &node, 1);
5872 }
5873 
5874 void
5875 iwn4965_ampdu_tx_start(struct iwn_softc *sc, struct ieee80211_node *ni,
5876     uint8_t tid, uint16_t ssn)
5877 {
5878 	struct iwn_node *wn = (void *)ni;
5879 	int qid = IWN4965_FIRST_AGG_TXQUEUE + tid;
5880 	uint16_t idx = IWN_AGG_SSN_TO_TXQ_IDX(ssn);
5881 
5882 	/* Stop TX scheduler while we're changing its configuration. */
5883 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
5884 	    IWN4965_TXQ_STATUS_CHGACT);
5885 
5886 	/* Assign RA/TID translation to the queue. */
5887 	iwn_mem_write_2(sc, sc->sched_base + IWN4965_SCHED_TRANS_TBL(qid),
5888 	    wn->id << 4 | tid);
5889 
5890 	/* Enable chain-building mode for the queue. */
5891 	iwn_prph_setbits(sc, IWN4965_SCHED_QCHAIN_SEL, 1 << qid);
5892 
5893 	/* Set starting sequence number from the ADDBA request. */
5894 	sc->txq[qid].cur = sc->txq[qid].read = idx;
5895 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | idx);
5896 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_RDPTR(qid), ssn);
5897 
5898 	/* Set scheduler window size. */
5899 	iwn_mem_write(sc, sc->sched_base + IWN4965_SCHED_QUEUE_OFFSET(qid),
5900 	    IWN_SCHED_WINSZ);
5901 	/* Set scheduler frame limit. */
5902 	iwn_mem_write(sc, sc->sched_base + IWN4965_SCHED_QUEUE_OFFSET(qid) + 4,
5903 	    IWN_SCHED_LIMIT << 16);
5904 
5905 	/* Enable interrupts for the queue. */
5906 	iwn_prph_setbits(sc, IWN4965_SCHED_INTR_MASK, 1 << qid);
5907 
5908 	/* Mark the queue as active. */
5909 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
5910 	    IWN4965_TXQ_STATUS_ACTIVE | IWN4965_TXQ_STATUS_AGGR_ENA |
5911 	    iwn_tid2fifo[tid] << 1);
5912 }
5913 
5914 void
5915 iwn4965_ampdu_tx_stop(struct iwn_softc *sc, uint8_t tid, uint16_t ssn)
5916 {
5917 	int qid = IWN4965_FIRST_AGG_TXQUEUE + tid;
5918 	uint16_t idx = IWN_AGG_SSN_TO_TXQ_IDX(ssn);
5919 
5920 	/* Stop TX scheduler while we're changing its configuration. */
5921 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
5922 	    IWN4965_TXQ_STATUS_CHGACT);
5923 
5924 	/* Set starting sequence number from the ADDBA request. */
5925 	sc->txq[qid].cur = sc->txq[qid].read = idx;
5926 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | idx);
5927 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_RDPTR(qid), ssn);
5928 
5929 	/* Disable interrupts for the queue. */
5930 	iwn_prph_clrbits(sc, IWN4965_SCHED_INTR_MASK, 1 << qid);
5931 
5932 	/* Mark the queue as inactive. */
5933 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
5934 	    IWN4965_TXQ_STATUS_INACTIVE | iwn_tid2fifo[tid] << 1);
5935 }
5936 
5937 void
5938 iwn5000_ampdu_tx_start(struct iwn_softc *sc, struct ieee80211_node *ni,
5939     uint8_t tid, uint16_t ssn)
5940 {
5941 	int qid = IWN5000_FIRST_AGG_TXQUEUE + tid;
5942 	int idx = IWN_AGG_SSN_TO_TXQ_IDX(ssn);
5943 	struct iwn_node *wn = (void *)ni;
5944 
5945 	/* Stop TX scheduler while we're changing its configuration. */
5946 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
5947 	    IWN5000_TXQ_STATUS_CHGACT);
5948 
5949 	/* Assign RA/TID translation to the queue. */
5950 	iwn_mem_write_2(sc, sc->sched_base + IWN5000_SCHED_TRANS_TBL(qid),
5951 	    wn->id << 4 | tid);
5952 
5953 	/* Enable chain-building mode for the queue. */
5954 	iwn_prph_setbits(sc, IWN5000_SCHED_QCHAIN_SEL, 1 << qid);
5955 
5956 	/* Enable aggregation for the queue. */
5957 	iwn_prph_setbits(sc, IWN5000_SCHED_AGGR_SEL, 1 << qid);
5958 
5959 	/* Set starting sequence number from the ADDBA request. */
5960 	sc->txq[qid].cur = sc->txq[qid].read = idx;
5961 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | idx);
5962 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_RDPTR(qid), ssn);
5963 
5964 	/* Set scheduler window size and frame limit. */
5965 	iwn_mem_write(sc, sc->sched_base + IWN5000_SCHED_QUEUE_OFFSET(qid) + 4,
5966 	    IWN_SCHED_LIMIT << 16 | IWN_SCHED_WINSZ);
5967 
5968 	/* Enable interrupts for the queue. */
5969 	iwn_prph_setbits(sc, IWN5000_SCHED_INTR_MASK, 1 << qid);
5970 
5971 	/* Mark the queue as active. */
5972 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
5973 	    IWN5000_TXQ_STATUS_ACTIVE | iwn_tid2fifo[tid]);
5974 }
5975 
5976 void
5977 iwn5000_ampdu_tx_stop(struct iwn_softc *sc, uint8_t tid, uint16_t ssn)
5978 {
5979 	int qid = IWN5000_FIRST_AGG_TXQUEUE + tid;
5980 	int idx = IWN_AGG_SSN_TO_TXQ_IDX(ssn);
5981 
5982 	/* Stop TX scheduler while we're changing its configuration. */
5983 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
5984 	    IWN5000_TXQ_STATUS_CHGACT);
5985 
5986 	/* Disable aggregation for the queue. */
5987 	iwn_prph_clrbits(sc, IWN5000_SCHED_AGGR_SEL, 1 << qid);
5988 
5989 	/* Set starting sequence number from the ADDBA request. */
5990 	sc->txq[qid].cur = sc->txq[qid].read = idx;
5991 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | idx);
5992 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_RDPTR(qid), ssn);
5993 
5994 	/* Disable interrupts for the queue. */
5995 	iwn_prph_clrbits(sc, IWN5000_SCHED_INTR_MASK, 1 << qid);
5996 
5997 	/* Mark the queue as inactive. */
5998 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
5999 	    IWN5000_TXQ_STATUS_INACTIVE | iwn_tid2fifo[tid]);
6000 }
6001 
6002 /*
6003  * Query calibration tables from the initialization firmware.  We do this
6004  * only once at first boot.  Called from a process context.
6005  */
6006 int
6007 iwn5000_query_calibration(struct iwn_softc *sc)
6008 {
6009 	struct iwn5000_calib_config cmd;
6010 	int error;
6011 
6012 	memset(&cmd, 0, sizeof cmd);
6013 	cmd.ucode.once.enable = 0xffffffff;
6014 	cmd.ucode.once.start  = 0xffffffff;
6015 	cmd.ucode.once.send   = 0xffffffff;
6016 	cmd.ucode.flags       = 0xffffffff;
6017 	DPRINTF(("sending calibration query\n"));
6018 	error = iwn_cmd(sc, IWN5000_CMD_CALIB_CONFIG, &cmd, sizeof cmd, 0);
6019 	if (error != 0)
6020 		return error;
6021 
6022 	/* Wait at most two seconds for calibration to complete. */
6023 	if (!(sc->sc_flags & IWN_FLAG_CALIB_DONE))
6024 		error = tsleep_nsec(sc, PCATCH, "iwncal", SEC_TO_NSEC(2));
6025 	return error;
6026 }
6027 
6028 /*
6029  * Send calibration results to the runtime firmware.  These results were
6030  * obtained on first boot from the initialization firmware.
6031  */
6032 int
6033 iwn5000_send_calibration(struct iwn_softc *sc)
6034 {
6035 	int idx, error;
6036 
6037 	for (idx = 0; idx < 5; idx++) {
6038 		if (sc->calibcmd[idx].buf == NULL)
6039 			continue;	/* No results available. */
6040 		DPRINTF(("send calibration result idx=%d len=%d\n",
6041 		    idx, sc->calibcmd[idx].len));
6042 		error = iwn_cmd(sc, IWN_CMD_PHY_CALIB, sc->calibcmd[idx].buf,
6043 		    sc->calibcmd[idx].len, 0);
6044 		if (error != 0) {
6045 			printf("%s: could not send calibration result\n",
6046 			    sc->sc_dev.dv_xname);
6047 			return error;
6048 		}
6049 	}
6050 	return 0;
6051 }
6052 
6053 int
6054 iwn5000_send_wimax_coex(struct iwn_softc *sc)
6055 {
6056 	struct iwn5000_wimax_coex wimax;
6057 
6058 #ifdef notyet
6059 	if (sc->hw_type == IWN_HW_REV_TYPE_6050) {
6060 		/* Enable WiMAX coexistence for combo adapters. */
6061 		wimax.flags =
6062 		    IWN_WIMAX_COEX_ASSOC_WA_UNMASK |
6063 		    IWN_WIMAX_COEX_UNASSOC_WA_UNMASK |
6064 		    IWN_WIMAX_COEX_STA_TABLE_VALID |
6065 		    IWN_WIMAX_COEX_ENABLE;
6066 		memcpy(wimax.events, iwn6050_wimax_events,
6067 		    sizeof iwn6050_wimax_events);
6068 	} else
6069 #endif
6070 	{
6071 		/* Disable WiMAX coexistence. */
6072 		wimax.flags = 0;
6073 		memset(wimax.events, 0, sizeof wimax.events);
6074 	}
6075 	DPRINTF(("Configuring WiMAX coexistence\n"));
6076 	return iwn_cmd(sc, IWN5000_CMD_WIMAX_COEX, &wimax, sizeof wimax, 0);
6077 }
6078 
6079 int
6080 iwn5000_crystal_calib(struct iwn_softc *sc)
6081 {
6082 	struct iwn5000_phy_calib_crystal cmd;
6083 
6084 	memset(&cmd, 0, sizeof cmd);
6085 	cmd.code = IWN5000_PHY_CALIB_CRYSTAL;
6086 	cmd.ngroups = 1;
6087 	cmd.isvalid = 1;
6088 	cmd.cap_pin[0] = letoh32(sc->eeprom_crystal) & 0xff;
6089 	cmd.cap_pin[1] = (letoh32(sc->eeprom_crystal) >> 16) & 0xff;
6090 	DPRINTF(("sending crystal calibration %d, %d\n",
6091 	    cmd.cap_pin[0], cmd.cap_pin[1]));
6092 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 0);
6093 }
6094 
6095 int
6096 iwn6000_temp_offset_calib(struct iwn_softc *sc)
6097 {
6098 	struct iwn6000_phy_calib_temp_offset cmd;
6099 
6100 	memset(&cmd, 0, sizeof cmd);
6101 	cmd.code = IWN6000_PHY_CALIB_TEMP_OFFSET;
6102 	cmd.ngroups = 1;
6103 	cmd.isvalid = 1;
6104 	if (sc->eeprom_temp != 0)
6105 		cmd.offset = htole16(sc->eeprom_temp);
6106 	else
6107 		cmd.offset = htole16(IWN_DEFAULT_TEMP_OFFSET);
6108 	DPRINTF(("setting radio sensor offset to %d\n", letoh16(cmd.offset)));
6109 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 0);
6110 }
6111 
6112 int
6113 iwn2000_temp_offset_calib(struct iwn_softc *sc)
6114 {
6115 	struct iwn2000_phy_calib_temp_offset cmd;
6116 
6117 	memset(&cmd, 0, sizeof cmd);
6118 	cmd.code = IWN2000_PHY_CALIB_TEMP_OFFSET;
6119 	cmd.ngroups = 1;
6120 	cmd.isvalid = 1;
6121 	if (sc->eeprom_rawtemp != 0) {
6122 		cmd.offset_low = htole16(sc->eeprom_rawtemp);
6123 		cmd.offset_high = htole16(sc->eeprom_temp);
6124 	} else {
6125 		cmd.offset_low = htole16(IWN_DEFAULT_TEMP_OFFSET);
6126 		cmd.offset_high = htole16(IWN_DEFAULT_TEMP_OFFSET);
6127 	}
6128 	cmd.burnt_voltage_ref = htole16(sc->eeprom_voltage);
6129 	DPRINTF(("setting radio sensor offset to %d:%d, voltage to %d\n",
6130 	    letoh16(cmd.offset_low), letoh16(cmd.offset_high),
6131 	    letoh16(cmd.burnt_voltage_ref)));
6132 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 0);
6133 }
6134 
6135 /*
6136  * This function is called after the runtime firmware notifies us of its
6137  * readiness (called in a process context).
6138  */
6139 int
6140 iwn4965_post_alive(struct iwn_softc *sc)
6141 {
6142 	int error, qid;
6143 
6144 	if ((error = iwn_nic_lock(sc)) != 0)
6145 		return error;
6146 
6147 	/* Clear TX scheduler state in SRAM. */
6148 	sc->sched_base = iwn_prph_read(sc, IWN_SCHED_SRAM_ADDR);
6149 	iwn_mem_set_region_4(sc, sc->sched_base + IWN4965_SCHED_CTX_OFF, 0,
6150 	    IWN4965_SCHED_CTX_LEN / sizeof (uint32_t));
6151 
6152 	/* Set physical address of TX scheduler rings (1KB aligned). */
6153 	iwn_prph_write(sc, IWN4965_SCHED_DRAM_ADDR, sc->sched_dma.paddr >> 10);
6154 
6155 	IWN_SETBITS(sc, IWN_FH_TX_CHICKEN, IWN_FH_TX_CHICKEN_SCHED_RETRY);
6156 
6157 	/* Disable chain mode for all our 16 queues. */
6158 	iwn_prph_write(sc, IWN4965_SCHED_QCHAIN_SEL, 0);
6159 
6160 	for (qid = 0; qid < IWN4965_NTXQUEUES; qid++) {
6161 		iwn_prph_write(sc, IWN4965_SCHED_QUEUE_RDPTR(qid), 0);
6162 		IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | 0);
6163 
6164 		/* Set scheduler window size. */
6165 		iwn_mem_write(sc, sc->sched_base +
6166 		    IWN4965_SCHED_QUEUE_OFFSET(qid), IWN_SCHED_WINSZ);
6167 		/* Set scheduler frame limit. */
6168 		iwn_mem_write(sc, sc->sched_base +
6169 		    IWN4965_SCHED_QUEUE_OFFSET(qid) + 4,
6170 		    IWN_SCHED_LIMIT << 16);
6171 	}
6172 
6173 	/* Enable interrupts for all our 16 queues. */
6174 	iwn_prph_write(sc, IWN4965_SCHED_INTR_MASK, 0xffff);
6175 	/* Identify TX FIFO rings (0-7). */
6176 	iwn_prph_write(sc, IWN4965_SCHED_TXFACT, 0xff);
6177 
6178 	/* Mark TX rings (4 EDCA + cmd + 2 HCCA) as active. */
6179 	for (qid = 0; qid < 7; qid++) {
6180 		static uint8_t qid2fifo[] = { 3, 2, 1, 0, 4, 5, 6 };
6181 		iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
6182 		    IWN4965_TXQ_STATUS_ACTIVE | qid2fifo[qid] << 1);
6183 	}
6184 	iwn_nic_unlock(sc);
6185 	return 0;
6186 }
6187 
6188 /*
6189  * This function is called after the initialization or runtime firmware
6190  * notifies us of its readiness (called in a process context).
6191  */
6192 int
6193 iwn5000_post_alive(struct iwn_softc *sc)
6194 {
6195 	int error, qid;
6196 
6197 	/* Switch to using ICT interrupt mode. */
6198 	iwn5000_ict_reset(sc);
6199 
6200 	if ((error = iwn_nic_lock(sc)) != 0)
6201 		return error;
6202 
6203 	/* Clear TX scheduler state in SRAM. */
6204 	sc->sched_base = iwn_prph_read(sc, IWN_SCHED_SRAM_ADDR);
6205 	iwn_mem_set_region_4(sc, sc->sched_base + IWN5000_SCHED_CTX_OFF, 0,
6206 	    IWN5000_SCHED_CTX_LEN / sizeof (uint32_t));
6207 
6208 	/* Set physical address of TX scheduler rings (1KB aligned). */
6209 	iwn_prph_write(sc, IWN5000_SCHED_DRAM_ADDR, sc->sched_dma.paddr >> 10);
6210 
6211 	/* Disable scheduler chain extension (enabled by default in HW). */
6212 	iwn_prph_write(sc, IWN5000_SCHED_CHAINEXT_EN, 0);
6213 
6214 	IWN_SETBITS(sc, IWN_FH_TX_CHICKEN, IWN_FH_TX_CHICKEN_SCHED_RETRY);
6215 
6216 	/* Enable chain mode for all queues, except command queue. */
6217 	iwn_prph_write(sc, IWN5000_SCHED_QCHAIN_SEL, 0xfffef);
6218 	iwn_prph_write(sc, IWN5000_SCHED_AGGR_SEL, 0);
6219 
6220 	for (qid = 0; qid < IWN5000_NTXQUEUES; qid++) {
6221 		iwn_prph_write(sc, IWN5000_SCHED_QUEUE_RDPTR(qid), 0);
6222 		IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | 0);
6223 
6224 		iwn_mem_write(sc, sc->sched_base +
6225 		    IWN5000_SCHED_QUEUE_OFFSET(qid), 0);
6226 		/* Set scheduler window size and frame limit. */
6227 		iwn_mem_write(sc, sc->sched_base +
6228 		    IWN5000_SCHED_QUEUE_OFFSET(qid) + 4,
6229 		    IWN_SCHED_LIMIT << 16 | IWN_SCHED_WINSZ);
6230 	}
6231 
6232 	/* Enable interrupts for all our 20 queues. */
6233 	iwn_prph_write(sc, IWN5000_SCHED_INTR_MASK, 0xfffff);
6234 	/* Identify TX FIFO rings (0-7). */
6235 	iwn_prph_write(sc, IWN5000_SCHED_TXFACT, 0xff);
6236 
6237 	/* Mark TX rings (4 EDCA + cmd + 2 HCCA) as active. */
6238 	for (qid = 0; qid < 7; qid++) {
6239 		static uint8_t qid2fifo[] = { 3, 2, 1, 0, 7, 5, 6 };
6240 		iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
6241 		    IWN5000_TXQ_STATUS_ACTIVE | qid2fifo[qid]);
6242 	}
6243 	iwn_nic_unlock(sc);
6244 
6245 	/* Configure WiMAX coexistence for combo adapters. */
6246 	error = iwn5000_send_wimax_coex(sc);
6247 	if (error != 0) {
6248 		printf("%s: could not configure WiMAX coexistence\n",
6249 		    sc->sc_dev.dv_xname);
6250 		return error;
6251 	}
6252 	if (sc->hw_type != IWN_HW_REV_TYPE_5150) {
6253 		/* Perform crystal calibration. */
6254 		error = iwn5000_crystal_calib(sc);
6255 		if (error != 0) {
6256 			printf("%s: crystal calibration failed\n",
6257 			    sc->sc_dev.dv_xname);
6258 			return error;
6259 		}
6260 	}
6261 	if (!(sc->sc_flags & IWN_FLAG_CALIB_DONE)) {
6262 		/* Query calibration from the initialization firmware. */
6263 		if ((error = iwn5000_query_calibration(sc)) != 0) {
6264 			printf("%s: could not query calibration\n",
6265 			    sc->sc_dev.dv_xname);
6266 			return error;
6267 		}
6268 		/*
6269 		 * We have the calibration results now, reboot with the
6270 		 * runtime firmware (call ourselves recursively!)
6271 		 */
6272 		iwn_hw_stop(sc);
6273 		error = iwn_hw_init(sc);
6274 	} else {
6275 		/* Send calibration results to runtime firmware. */
6276 		error = iwn5000_send_calibration(sc);
6277 	}
6278 	return error;
6279 }
6280 
6281 /*
6282  * The firmware boot code is small and is intended to be copied directly into
6283  * the NIC internal memory (no DMA transfer).
6284  */
6285 int
6286 iwn4965_load_bootcode(struct iwn_softc *sc, const uint8_t *ucode, int size)
6287 {
6288 	int error, ntries;
6289 
6290 	size /= sizeof (uint32_t);
6291 
6292 	if ((error = iwn_nic_lock(sc)) != 0)
6293 		return error;
6294 
6295 	/* Copy microcode image into NIC memory. */
6296 	iwn_prph_write_region_4(sc, IWN_BSM_SRAM_BASE,
6297 	    (const uint32_t *)ucode, size);
6298 
6299 	iwn_prph_write(sc, IWN_BSM_WR_MEM_SRC, 0);
6300 	iwn_prph_write(sc, IWN_BSM_WR_MEM_DST, IWN_FW_TEXT_BASE);
6301 	iwn_prph_write(sc, IWN_BSM_WR_DWCOUNT, size);
6302 
6303 	/* Start boot load now. */
6304 	iwn_prph_write(sc, IWN_BSM_WR_CTRL, IWN_BSM_WR_CTRL_START);
6305 
6306 	/* Wait for transfer to complete. */
6307 	for (ntries = 0; ntries < 1000; ntries++) {
6308 		if (!(iwn_prph_read(sc, IWN_BSM_WR_CTRL) &
6309 		    IWN_BSM_WR_CTRL_START))
6310 			break;
6311 		DELAY(10);
6312 	}
6313 	if (ntries == 1000) {
6314 		printf("%s: could not load boot firmware\n",
6315 		    sc->sc_dev.dv_xname);
6316 		iwn_nic_unlock(sc);
6317 		return ETIMEDOUT;
6318 	}
6319 
6320 	/* Enable boot after power up. */
6321 	iwn_prph_write(sc, IWN_BSM_WR_CTRL, IWN_BSM_WR_CTRL_START_EN);
6322 
6323 	iwn_nic_unlock(sc);
6324 	return 0;
6325 }
6326 
6327 int
6328 iwn4965_load_firmware(struct iwn_softc *sc)
6329 {
6330 	struct iwn_fw_info *fw = &sc->fw;
6331 	struct iwn_dma_info *dma = &sc->fw_dma;
6332 	int error;
6333 
6334 	/* Copy initialization sections into pre-allocated DMA-safe memory. */
6335 	memcpy(dma->vaddr, fw->init.data, fw->init.datasz);
6336 	bus_dmamap_sync(sc->sc_dmat, dma->map, 0, fw->init.datasz,
6337 	    BUS_DMASYNC_PREWRITE);
6338 	memcpy(dma->vaddr + IWN4965_FW_DATA_MAXSZ,
6339 	    fw->init.text, fw->init.textsz);
6340 	bus_dmamap_sync(sc->sc_dmat, dma->map, IWN4965_FW_DATA_MAXSZ,
6341 	    fw->init.textsz, BUS_DMASYNC_PREWRITE);
6342 
6343 	/* Tell adapter where to find initialization sections. */
6344 	if ((error = iwn_nic_lock(sc)) != 0)
6345 		return error;
6346 	iwn_prph_write(sc, IWN_BSM_DRAM_DATA_ADDR, dma->paddr >> 4);
6347 	iwn_prph_write(sc, IWN_BSM_DRAM_DATA_SIZE, fw->init.datasz);
6348 	iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_ADDR,
6349 	    (dma->paddr + IWN4965_FW_DATA_MAXSZ) >> 4);
6350 	iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_SIZE, fw->init.textsz);
6351 	iwn_nic_unlock(sc);
6352 
6353 	/* Load firmware boot code. */
6354 	error = iwn4965_load_bootcode(sc, fw->boot.text, fw->boot.textsz);
6355 	if (error != 0) {
6356 		printf("%s: could not load boot firmware\n",
6357 		    sc->sc_dev.dv_xname);
6358 		return error;
6359 	}
6360 	/* Now press "execute". */
6361 	IWN_WRITE(sc, IWN_RESET, 0);
6362 
6363 	/* Wait at most one second for first alive notification. */
6364 	if ((error = tsleep_nsec(sc, PCATCH, "iwninit", SEC_TO_NSEC(1))) != 0) {
6365 		printf("%s: timeout waiting for adapter to initialize\n",
6366 		    sc->sc_dev.dv_xname);
6367 		return error;
6368 	}
6369 
6370 	/* Retrieve current temperature for initial TX power calibration. */
6371 	sc->rawtemp = sc->ucode_info.temp[3].chan20MHz;
6372 	sc->temp = iwn4965_get_temperature(sc);
6373 
6374 	/* Copy runtime sections into pre-allocated DMA-safe memory. */
6375 	memcpy(dma->vaddr, fw->main.data, fw->main.datasz);
6376 	bus_dmamap_sync(sc->sc_dmat, dma->map, 0, fw->main.datasz,
6377 	    BUS_DMASYNC_PREWRITE);
6378 	memcpy(dma->vaddr + IWN4965_FW_DATA_MAXSZ,
6379 	    fw->main.text, fw->main.textsz);
6380 	bus_dmamap_sync(sc->sc_dmat, dma->map, IWN4965_FW_DATA_MAXSZ,
6381 	    fw->main.textsz, BUS_DMASYNC_PREWRITE);
6382 
6383 	/* Tell adapter where to find runtime sections. */
6384 	if ((error = iwn_nic_lock(sc)) != 0)
6385 		return error;
6386 	iwn_prph_write(sc, IWN_BSM_DRAM_DATA_ADDR, dma->paddr >> 4);
6387 	iwn_prph_write(sc, IWN_BSM_DRAM_DATA_SIZE, fw->main.datasz);
6388 	iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_ADDR,
6389 	    (dma->paddr + IWN4965_FW_DATA_MAXSZ) >> 4);
6390 	iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_SIZE,
6391 	    IWN_FW_UPDATED | fw->main.textsz);
6392 	iwn_nic_unlock(sc);
6393 
6394 	return 0;
6395 }
6396 
6397 int
6398 iwn5000_load_firmware_section(struct iwn_softc *sc, uint32_t dst,
6399     const uint8_t *section, int size)
6400 {
6401 	struct iwn_dma_info *dma = &sc->fw_dma;
6402 	int error;
6403 
6404 	/* Copy firmware section into pre-allocated DMA-safe memory. */
6405 	memcpy(dma->vaddr, section, size);
6406 	bus_dmamap_sync(sc->sc_dmat, dma->map, 0, size, BUS_DMASYNC_PREWRITE);
6407 
6408 	if ((error = iwn_nic_lock(sc)) != 0)
6409 		return error;
6410 
6411 	IWN_WRITE(sc, IWN_FH_TX_CONFIG(IWN_SRVC_DMACHNL),
6412 	    IWN_FH_TX_CONFIG_DMA_PAUSE);
6413 
6414 	IWN_WRITE(sc, IWN_FH_SRAM_ADDR(IWN_SRVC_DMACHNL), dst);
6415 	IWN_WRITE(sc, IWN_FH_TFBD_CTRL0(IWN_SRVC_DMACHNL),
6416 	    IWN_LOADDR(dma->paddr));
6417 	IWN_WRITE(sc, IWN_FH_TFBD_CTRL1(IWN_SRVC_DMACHNL),
6418 	    IWN_HIADDR(dma->paddr) << 28 | size);
6419 	IWN_WRITE(sc, IWN_FH_TXBUF_STATUS(IWN_SRVC_DMACHNL),
6420 	    IWN_FH_TXBUF_STATUS_TBNUM(1) |
6421 	    IWN_FH_TXBUF_STATUS_TBIDX(1) |
6422 	    IWN_FH_TXBUF_STATUS_TFBD_VALID);
6423 
6424 	/* Kick Flow Handler to start DMA transfer. */
6425 	IWN_WRITE(sc, IWN_FH_TX_CONFIG(IWN_SRVC_DMACHNL),
6426 	    IWN_FH_TX_CONFIG_DMA_ENA | IWN_FH_TX_CONFIG_CIRQ_HOST_ENDTFD);
6427 
6428 	iwn_nic_unlock(sc);
6429 
6430 	/* Wait at most five seconds for FH DMA transfer to complete. */
6431 	return tsleep_nsec(sc, PCATCH, "iwninit", SEC_TO_NSEC(5));
6432 }
6433 
6434 int
6435 iwn5000_load_firmware(struct iwn_softc *sc)
6436 {
6437 	struct iwn_fw_part *fw;
6438 	int error;
6439 
6440 	/* Load the initialization firmware on first boot only. */
6441 	fw = (sc->sc_flags & IWN_FLAG_CALIB_DONE) ?
6442 	    &sc->fw.main : &sc->fw.init;
6443 
6444 	error = iwn5000_load_firmware_section(sc, IWN_FW_TEXT_BASE,
6445 	    fw->text, fw->textsz);
6446 	if (error != 0) {
6447 		printf("%s: could not load firmware %s section\n",
6448 		    sc->sc_dev.dv_xname, ".text");
6449 		return error;
6450 	}
6451 	error = iwn5000_load_firmware_section(sc, IWN_FW_DATA_BASE,
6452 	    fw->data, fw->datasz);
6453 	if (error != 0) {
6454 		printf("%s: could not load firmware %s section\n",
6455 		    sc->sc_dev.dv_xname, ".data");
6456 		return error;
6457 	}
6458 
6459 	/* Now press "execute". */
6460 	IWN_WRITE(sc, IWN_RESET, 0);
6461 	return 0;
6462 }
6463 
6464 /*
6465  * Extract text and data sections from a legacy firmware image.
6466  */
6467 int
6468 iwn_read_firmware_leg(struct iwn_softc *sc, struct iwn_fw_info *fw)
6469 {
6470 	const uint32_t *ptr;
6471 	size_t hdrlen = 24;
6472 	uint32_t rev;
6473 
6474 	ptr = (const uint32_t *)fw->data;
6475 	rev = letoh32(*ptr++);
6476 
6477 	/* Check firmware API version. */
6478 	if (IWN_FW_API(rev) <= 1) {
6479 		printf("%s: bad firmware, need API version >=2\n",
6480 		    sc->sc_dev.dv_xname);
6481 		return EINVAL;
6482 	}
6483 	if (IWN_FW_API(rev) >= 3) {
6484 		/* Skip build number (version 2 header). */
6485 		hdrlen += 4;
6486 		ptr++;
6487 	}
6488 	if (fw->size < hdrlen) {
6489 		printf("%s: firmware too short: %zu bytes\n",
6490 		    sc->sc_dev.dv_xname, fw->size);
6491 		return EINVAL;
6492 	}
6493 	fw->main.textsz = letoh32(*ptr++);
6494 	fw->main.datasz = letoh32(*ptr++);
6495 	fw->init.textsz = letoh32(*ptr++);
6496 	fw->init.datasz = letoh32(*ptr++);
6497 	fw->boot.textsz = letoh32(*ptr++);
6498 
6499 	/* Check that all firmware sections fit. */
6500 	if (fw->size < hdrlen + fw->main.textsz + fw->main.datasz +
6501 	    fw->init.textsz + fw->init.datasz + fw->boot.textsz) {
6502 		printf("%s: firmware too short: %zu bytes\n",
6503 		    sc->sc_dev.dv_xname, fw->size);
6504 		return EINVAL;
6505 	}
6506 
6507 	/* Get pointers to firmware sections. */
6508 	fw->main.text = (const uint8_t *)ptr;
6509 	fw->main.data = fw->main.text + fw->main.textsz;
6510 	fw->init.text = fw->main.data + fw->main.datasz;
6511 	fw->init.data = fw->init.text + fw->init.textsz;
6512 	fw->boot.text = fw->init.data + fw->init.datasz;
6513 	return 0;
6514 }
6515 
6516 /*
6517  * Extract text and data sections from a TLV firmware image.
6518  */
6519 int
6520 iwn_read_firmware_tlv(struct iwn_softc *sc, struct iwn_fw_info *fw,
6521     uint16_t alt)
6522 {
6523 	const struct iwn_fw_tlv_hdr *hdr;
6524 	const struct iwn_fw_tlv *tlv;
6525 	const uint8_t *ptr, *end;
6526 	uint64_t altmask;
6527 	uint32_t len;
6528 
6529 	if (fw->size < sizeof (*hdr)) {
6530 		printf("%s: firmware too short: %zu bytes\n",
6531 		    sc->sc_dev.dv_xname, fw->size);
6532 		return EINVAL;
6533 	}
6534 	hdr = (const struct iwn_fw_tlv_hdr *)fw->data;
6535 	if (hdr->signature != htole32(IWN_FW_SIGNATURE)) {
6536 		printf("%s: bad firmware signature 0x%08x\n",
6537 		    sc->sc_dev.dv_xname, letoh32(hdr->signature));
6538 		return EINVAL;
6539 	}
6540 	DPRINTF(("FW: \"%.64s\", build 0x%x\n", hdr->descr,
6541 	    letoh32(hdr->build)));
6542 
6543 	/*
6544 	 * Select the closest supported alternative that is less than
6545 	 * or equal to the specified one.
6546 	 */
6547 	altmask = letoh64(hdr->altmask);
6548 	while (alt > 0 && !(altmask & (1ULL << alt)))
6549 		alt--;	/* Downgrade. */
6550 	DPRINTF(("using alternative %d\n", alt));
6551 
6552 	ptr = (const uint8_t *)(hdr + 1);
6553 	end = (const uint8_t *)(fw->data + fw->size);
6554 
6555 	/* Parse type-length-value fields. */
6556 	while (ptr + sizeof (*tlv) <= end) {
6557 		tlv = (const struct iwn_fw_tlv *)ptr;
6558 		len = letoh32(tlv->len);
6559 
6560 		ptr += sizeof (*tlv);
6561 		if (ptr + len > end) {
6562 			printf("%s: firmware too short: %zu bytes\n",
6563 			    sc->sc_dev.dv_xname, fw->size);
6564 			return EINVAL;
6565 		}
6566 		/* Skip other alternatives. */
6567 		if (tlv->alt != 0 && tlv->alt != htole16(alt))
6568 			goto next;
6569 
6570 		switch (letoh16(tlv->type)) {
6571 		case IWN_FW_TLV_MAIN_TEXT:
6572 			fw->main.text = ptr;
6573 			fw->main.textsz = len;
6574 			break;
6575 		case IWN_FW_TLV_MAIN_DATA:
6576 			fw->main.data = ptr;
6577 			fw->main.datasz = len;
6578 			break;
6579 		case IWN_FW_TLV_INIT_TEXT:
6580 			fw->init.text = ptr;
6581 			fw->init.textsz = len;
6582 			break;
6583 		case IWN_FW_TLV_INIT_DATA:
6584 			fw->init.data = ptr;
6585 			fw->init.datasz = len;
6586 			break;
6587 		case IWN_FW_TLV_BOOT_TEXT:
6588 			fw->boot.text = ptr;
6589 			fw->boot.textsz = len;
6590 			break;
6591 		case IWN_FW_TLV_ENH_SENS:
6592 			if (len !=  0) {
6593 				printf("%s: TLV type %d has invalid size %u\n",
6594 				    sc->sc_dev.dv_xname, letoh16(tlv->type),
6595 				    len);
6596 				goto next;
6597 			}
6598 			sc->sc_flags |= IWN_FLAG_ENH_SENS;
6599 			break;
6600 		case IWN_FW_TLV_PHY_CALIB:
6601 			if (len != sizeof(uint32_t)) {
6602 				printf("%s: TLV type %d has invalid size %u\n",
6603 				    sc->sc_dev.dv_xname, letoh16(tlv->type),
6604 				    len);
6605 				goto next;
6606 			}
6607 			if (letoh32(*ptr) <= IWN5000_PHY_CALIB_MAX) {
6608 				sc->reset_noise_gain = letoh32(*ptr);
6609 				sc->noise_gain = letoh32(*ptr) + 1;
6610 			}
6611 			break;
6612 		case IWN_FW_TLV_FLAGS:
6613 			if (len < sizeof(uint32_t))
6614 				break;
6615 			if (len % sizeof(uint32_t))
6616 				break;
6617 			sc->tlv_feature_flags = letoh32(*ptr);
6618 			DPRINTF(("feature: 0x%08x\n", sc->tlv_feature_flags));
6619 			break;
6620 		default:
6621 			DPRINTF(("TLV type %d not handled\n",
6622 			    letoh16(tlv->type)));
6623 			break;
6624 		}
6625  next:		/* TLV fields are 32-bit aligned. */
6626 		ptr += (len + 3) & ~3;
6627 	}
6628 	return 0;
6629 }
6630 
6631 int
6632 iwn_read_firmware(struct iwn_softc *sc)
6633 {
6634 	struct iwn_fw_info *fw = &sc->fw;
6635 	int error;
6636 
6637 	/*
6638 	 * Some PHY calibration commands are firmware-dependent; these
6639 	 * are the default values that will be overridden if
6640 	 * necessary.
6641 	 */
6642 	sc->reset_noise_gain = IWN5000_PHY_CALIB_RESET_NOISE_GAIN;
6643 	sc->noise_gain = IWN5000_PHY_CALIB_NOISE_GAIN;
6644 
6645 	memset(fw, 0, sizeof (*fw));
6646 
6647 	/* Read firmware image from filesystem. */
6648 	if ((error = loadfirmware(sc->fwname, &fw->data, &fw->size)) != 0) {
6649 		printf("%s: could not read firmware %s (error %d)\n",
6650 		    sc->sc_dev.dv_xname, sc->fwname, error);
6651 		return error;
6652 	}
6653 	if (fw->size < sizeof (uint32_t)) {
6654 		printf("%s: firmware too short: %zu bytes\n",
6655 		    sc->sc_dev.dv_xname, fw->size);
6656 		free(fw->data, M_DEVBUF, fw->size);
6657 		return EINVAL;
6658 	}
6659 
6660 	/* Retrieve text and data sections. */
6661 	if (*(const uint32_t *)fw->data != 0)	/* Legacy image. */
6662 		error = iwn_read_firmware_leg(sc, fw);
6663 	else
6664 		error = iwn_read_firmware_tlv(sc, fw, 1);
6665 	if (error != 0) {
6666 		printf("%s: could not read firmware sections\n",
6667 		    sc->sc_dev.dv_xname);
6668 		free(fw->data, M_DEVBUF, fw->size);
6669 		return error;
6670 	}
6671 
6672 	/* Make sure text and data sections fit in hardware memory. */
6673 	if (fw->main.textsz > sc->fw_text_maxsz ||
6674 	    fw->main.datasz > sc->fw_data_maxsz ||
6675 	    fw->init.textsz > sc->fw_text_maxsz ||
6676 	    fw->init.datasz > sc->fw_data_maxsz ||
6677 	    fw->boot.textsz > IWN_FW_BOOT_TEXT_MAXSZ ||
6678 	    (fw->boot.textsz & 3) != 0) {
6679 		printf("%s: firmware sections too large\n",
6680 		    sc->sc_dev.dv_xname);
6681 		free(fw->data, M_DEVBUF, fw->size);
6682 		return EINVAL;
6683 	}
6684 
6685 	/* We can proceed with loading the firmware. */
6686 	return 0;
6687 }
6688 
6689 int
6690 iwn_clock_wait(struct iwn_softc *sc)
6691 {
6692 	int ntries;
6693 
6694 	/* Set "initialization complete" bit. */
6695 	IWN_SETBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_INIT_DONE);
6696 
6697 	/* Wait for clock stabilization. */
6698 	for (ntries = 0; ntries < 2500; ntries++) {
6699 		if (IWN_READ(sc, IWN_GP_CNTRL) & IWN_GP_CNTRL_MAC_CLOCK_READY)
6700 			return 0;
6701 		DELAY(10);
6702 	}
6703 	printf("%s: timeout waiting for clock stabilization\n",
6704 	    sc->sc_dev.dv_xname);
6705 	return ETIMEDOUT;
6706 }
6707 
6708 int
6709 iwn_apm_init(struct iwn_softc *sc)
6710 {
6711 	pcireg_t reg;
6712 	int error;
6713 
6714 	/* Disable L0s exit timer (NMI bug workaround). */
6715 	IWN_SETBITS(sc, IWN_GIO_CHICKEN, IWN_GIO_CHICKEN_DIS_L0S_TIMER);
6716 	/* Don't wait for ICH L0s (ICH bug workaround). */
6717 	IWN_SETBITS(sc, IWN_GIO_CHICKEN, IWN_GIO_CHICKEN_L1A_NO_L0S_RX);
6718 
6719 	/* Set FH wait threshold to max (HW bug under stress workaround). */
6720 	IWN_SETBITS(sc, IWN_DBG_HPET_MEM, 0xffff0000);
6721 
6722 	/* Enable HAP INTA to move adapter from L1a to L0s. */
6723 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_HAP_WAKE_L1A);
6724 
6725 	/* Retrieve PCIe Active State Power Management (ASPM). */
6726 	reg = pci_conf_read(sc->sc_pct, sc->sc_pcitag,
6727 	    sc->sc_cap_off + PCI_PCIE_LCSR);
6728 	/* Workaround for HW instability in PCIe L0->L0s->L1 transition. */
6729 	if (reg & PCI_PCIE_LCSR_ASPM_L1)	/* L1 Entry enabled. */
6730 		IWN_SETBITS(sc, IWN_GIO, IWN_GIO_L0S_ENA);
6731 	else
6732 		IWN_CLRBITS(sc, IWN_GIO, IWN_GIO_L0S_ENA);
6733 
6734 	if (sc->hw_type != IWN_HW_REV_TYPE_4965 &&
6735 	    sc->hw_type <= IWN_HW_REV_TYPE_1000)
6736 		IWN_SETBITS(sc, IWN_ANA_PLL, IWN_ANA_PLL_INIT);
6737 
6738 	/* Wait for clock stabilization before accessing prph. */
6739 	if ((error = iwn_clock_wait(sc)) != 0)
6740 		return error;
6741 
6742 	if ((error = iwn_nic_lock(sc)) != 0)
6743 		return error;
6744 	if (sc->hw_type == IWN_HW_REV_TYPE_4965) {
6745 		/* Enable DMA and BSM (Bootstrap State Machine). */
6746 		iwn_prph_write(sc, IWN_APMG_CLK_EN,
6747 		    IWN_APMG_CLK_CTRL_DMA_CLK_RQT |
6748 		    IWN_APMG_CLK_CTRL_BSM_CLK_RQT);
6749 	} else {
6750 		/* Enable DMA. */
6751 		iwn_prph_write(sc, IWN_APMG_CLK_EN,
6752 		    IWN_APMG_CLK_CTRL_DMA_CLK_RQT);
6753 	}
6754 	DELAY(20);
6755 	/* Disable L1-Active. */
6756 	iwn_prph_setbits(sc, IWN_APMG_PCI_STT, IWN_APMG_PCI_STT_L1A_DIS);
6757 	iwn_nic_unlock(sc);
6758 
6759 	return 0;
6760 }
6761 
6762 void
6763 iwn_apm_stop_master(struct iwn_softc *sc)
6764 {
6765 	int ntries;
6766 
6767 	/* Stop busmaster DMA activity. */
6768 	IWN_SETBITS(sc, IWN_RESET, IWN_RESET_STOP_MASTER);
6769 	for (ntries = 0; ntries < 100; ntries++) {
6770 		if (IWN_READ(sc, IWN_RESET) & IWN_RESET_MASTER_DISABLED)
6771 			return;
6772 		DELAY(10);
6773 	}
6774 	printf("%s: timeout waiting for master\n", sc->sc_dev.dv_xname);
6775 }
6776 
6777 void
6778 iwn_apm_stop(struct iwn_softc *sc)
6779 {
6780 	iwn_apm_stop_master(sc);
6781 
6782 	/* Reset the entire device. */
6783 	IWN_SETBITS(sc, IWN_RESET, IWN_RESET_SW);
6784 	DELAY(10);
6785 	/* Clear "initialization complete" bit. */
6786 	IWN_CLRBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_INIT_DONE);
6787 }
6788 
6789 int
6790 iwn4965_nic_config(struct iwn_softc *sc)
6791 {
6792 	if (IWN_RFCFG_TYPE(sc->rfcfg) == 1) {
6793 		/*
6794 		 * I don't believe this to be correct but this is what the
6795 		 * vendor driver is doing. Probably the bits should not be
6796 		 * shifted in IWN_RFCFG_*.
6797 		 */
6798 		IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
6799 		    IWN_RFCFG_TYPE(sc->rfcfg) |
6800 		    IWN_RFCFG_STEP(sc->rfcfg) |
6801 		    IWN_RFCFG_DASH(sc->rfcfg));
6802 	}
6803 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
6804 	    IWN_HW_IF_CONFIG_RADIO_SI | IWN_HW_IF_CONFIG_MAC_SI);
6805 	return 0;
6806 }
6807 
6808 int
6809 iwn5000_nic_config(struct iwn_softc *sc)
6810 {
6811 	uint32_t tmp;
6812 	int error;
6813 
6814 	if (IWN_RFCFG_TYPE(sc->rfcfg) < 3) {
6815 		IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
6816 		    IWN_RFCFG_TYPE(sc->rfcfg) |
6817 		    IWN_RFCFG_STEP(sc->rfcfg) |
6818 		    IWN_RFCFG_DASH(sc->rfcfg));
6819 	}
6820 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
6821 	    IWN_HW_IF_CONFIG_RADIO_SI | IWN_HW_IF_CONFIG_MAC_SI);
6822 
6823 	if ((error = iwn_nic_lock(sc)) != 0)
6824 		return error;
6825 	iwn_prph_setbits(sc, IWN_APMG_PS, IWN_APMG_PS_EARLY_PWROFF_DIS);
6826 
6827 	if (sc->hw_type == IWN_HW_REV_TYPE_1000) {
6828 		/*
6829 		 * Select first Switching Voltage Regulator (1.32V) to
6830 		 * solve a stability issue related to noisy DC2DC line
6831 		 * in the silicon of 1000 Series.
6832 		 */
6833 		tmp = iwn_prph_read(sc, IWN_APMG_DIGITAL_SVR);
6834 		tmp &= ~IWN_APMG_DIGITAL_SVR_VOLTAGE_MASK;
6835 		tmp |= IWN_APMG_DIGITAL_SVR_VOLTAGE_1_32;
6836 		iwn_prph_write(sc, IWN_APMG_DIGITAL_SVR, tmp);
6837 	}
6838 	iwn_nic_unlock(sc);
6839 
6840 	if (sc->sc_flags & IWN_FLAG_INTERNAL_PA) {
6841 		/* Use internal power amplifier only. */
6842 		IWN_WRITE(sc, IWN_GP_DRIVER, IWN_GP_DRIVER_RADIO_2X2_IPA);
6843 	}
6844 	if ((sc->hw_type == IWN_HW_REV_TYPE_6050 ||
6845 	     sc->hw_type == IWN_HW_REV_TYPE_6005) && sc->calib_ver >= 6) {
6846 		/* Indicate that ROM calibration version is >=6. */
6847 		IWN_SETBITS(sc, IWN_GP_DRIVER, IWN_GP_DRIVER_CALIB_VER6);
6848 	}
6849 	if (sc->hw_type == IWN_HW_REV_TYPE_6005)
6850 		IWN_SETBITS(sc, IWN_GP_DRIVER, IWN_GP_DRIVER_6050_1X2);
6851 	if (sc->hw_type == IWN_HW_REV_TYPE_2030 ||
6852 	    sc->hw_type == IWN_HW_REV_TYPE_2000 ||
6853 	    sc->hw_type == IWN_HW_REV_TYPE_135 ||
6854 	    sc->hw_type == IWN_HW_REV_TYPE_105)
6855 		IWN_SETBITS(sc, IWN_GP_DRIVER, IWN_GP_DRIVER_RADIO_IQ_INVERT);
6856 	return 0;
6857 }
6858 
6859 /*
6860  * Take NIC ownership over Intel Active Management Technology (AMT).
6861  */
6862 int
6863 iwn_hw_prepare(struct iwn_softc *sc)
6864 {
6865 	int ntries;
6866 
6867 	/* Check if hardware is ready. */
6868 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_NIC_READY);
6869 	for (ntries = 0; ntries < 5; ntries++) {
6870 		if (IWN_READ(sc, IWN_HW_IF_CONFIG) &
6871 		    IWN_HW_IF_CONFIG_NIC_READY)
6872 			return 0;
6873 		DELAY(10);
6874 	}
6875 
6876 	/* Hardware not ready, force into ready state. */
6877 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_PREPARE);
6878 	for (ntries = 0; ntries < 15000; ntries++) {
6879 		if (!(IWN_READ(sc, IWN_HW_IF_CONFIG) &
6880 		    IWN_HW_IF_CONFIG_PREPARE_DONE))
6881 			break;
6882 		DELAY(10);
6883 	}
6884 	if (ntries == 15000)
6885 		return ETIMEDOUT;
6886 
6887 	/* Hardware should be ready now. */
6888 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_NIC_READY);
6889 	for (ntries = 0; ntries < 5; ntries++) {
6890 		if (IWN_READ(sc, IWN_HW_IF_CONFIG) &
6891 		    IWN_HW_IF_CONFIG_NIC_READY)
6892 			return 0;
6893 		DELAY(10);
6894 	}
6895 	return ETIMEDOUT;
6896 }
6897 
6898 int
6899 iwn_hw_init(struct iwn_softc *sc)
6900 {
6901 	struct iwn_ops *ops = &sc->ops;
6902 	int error, chnl, qid;
6903 
6904 	/* Clear pending interrupts. */
6905 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
6906 
6907 	if ((error = iwn_apm_init(sc)) != 0) {
6908 		printf("%s: could not power on adapter\n",
6909 		    sc->sc_dev.dv_xname);
6910 		return error;
6911 	}
6912 
6913 	/* Select VMAIN power source. */
6914 	if ((error = iwn_nic_lock(sc)) != 0)
6915 		return error;
6916 	iwn_prph_clrbits(sc, IWN_APMG_PS, IWN_APMG_PS_PWR_SRC_MASK);
6917 	iwn_nic_unlock(sc);
6918 
6919 	/* Perform adapter-specific initialization. */
6920 	if ((error = ops->nic_config(sc)) != 0)
6921 		return error;
6922 
6923 	/* Initialize RX ring. */
6924 	if ((error = iwn_nic_lock(sc)) != 0)
6925 		return error;
6926 	IWN_WRITE(sc, IWN_FH_RX_CONFIG, 0);
6927 	IWN_WRITE(sc, IWN_FH_RX_WPTR, 0);
6928 	/* Set physical address of RX ring (256-byte aligned). */
6929 	IWN_WRITE(sc, IWN_FH_RX_BASE, sc->rxq.desc_dma.paddr >> 8);
6930 	/* Set physical address of RX status (16-byte aligned). */
6931 	IWN_WRITE(sc, IWN_FH_STATUS_WPTR, sc->rxq.stat_dma.paddr >> 4);
6932 	/* Enable RX. */
6933 	IWN_WRITE(sc, IWN_FH_RX_CONFIG,
6934 	    IWN_FH_RX_CONFIG_ENA           |
6935 	    IWN_FH_RX_CONFIG_IGN_RXF_EMPTY |	/* HW bug workaround */
6936 	    IWN_FH_RX_CONFIG_IRQ_DST_HOST  |
6937 	    IWN_FH_RX_CONFIG_SINGLE_FRAME  |
6938 	    IWN_FH_RX_CONFIG_RB_TIMEOUT(0x11) | /* about 1/2 msec */
6939 	    IWN_FH_RX_CONFIG_NRBD(IWN_RX_RING_COUNT_LOG));
6940 	iwn_nic_unlock(sc);
6941 	IWN_WRITE(sc, IWN_FH_RX_WPTR, (IWN_RX_RING_COUNT - 1) & ~7);
6942 
6943 	if ((error = iwn_nic_lock(sc)) != 0)
6944 		return error;
6945 
6946 	/* Initialize TX scheduler. */
6947 	iwn_prph_write(sc, sc->sched_txfact_addr, 0);
6948 
6949 	/* Set physical address of "keep warm" page (16-byte aligned). */
6950 	IWN_WRITE(sc, IWN_FH_KW_ADDR, sc->kw_dma.paddr >> 4);
6951 
6952 	/* Initialize TX rings. */
6953 	for (qid = 0; qid < sc->ntxqs; qid++) {
6954 		struct iwn_tx_ring *txq = &sc->txq[qid];
6955 
6956 		/* Set physical address of TX ring (256-byte aligned). */
6957 		IWN_WRITE(sc, IWN_FH_CBBC_QUEUE(qid),
6958 		    txq->desc_dma.paddr >> 8);
6959 	}
6960 	iwn_nic_unlock(sc);
6961 
6962 	/* Enable DMA channels. */
6963 	for (chnl = 0; chnl < sc->ndmachnls; chnl++) {
6964 		IWN_WRITE(sc, IWN_FH_TX_CONFIG(chnl),
6965 		    IWN_FH_TX_CONFIG_DMA_ENA |
6966 		    IWN_FH_TX_CONFIG_DMA_CREDIT_ENA);
6967 	}
6968 
6969 	/* Clear "radio off" and "commands blocked" bits. */
6970 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_RFKILL);
6971 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_CMD_BLOCKED);
6972 
6973 	/* Clear pending interrupts. */
6974 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
6975 	/* Enable interrupt coalescing. */
6976 	IWN_WRITE(sc, IWN_INT_COALESCING, 512 / 8);
6977 	/* Enable interrupts. */
6978 	IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
6979 
6980 	/* _Really_ make sure "radio off" bit is cleared! */
6981 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_RFKILL);
6982 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_RFKILL);
6983 
6984 	/* Enable shadow registers. */
6985 	if (sc->hw_type >= IWN_HW_REV_TYPE_6000)
6986 		IWN_SETBITS(sc, IWN_SHADOW_REG_CTRL, 0x800fffff);
6987 
6988 	if ((error = ops->load_firmware(sc)) != 0) {
6989 		printf("%s: could not load firmware\n", sc->sc_dev.dv_xname);
6990 		return error;
6991 	}
6992 	/* Wait at most one second for firmware alive notification. */
6993 	if ((error = tsleep_nsec(sc, PCATCH, "iwninit", SEC_TO_NSEC(1))) != 0) {
6994 		printf("%s: timeout waiting for adapter to initialize\n",
6995 		    sc->sc_dev.dv_xname);
6996 		return error;
6997 	}
6998 	/* Do post-firmware initialization. */
6999 	return ops->post_alive(sc);
7000 }
7001 
7002 void
7003 iwn_hw_stop(struct iwn_softc *sc)
7004 {
7005 	int chnl, qid, ntries;
7006 
7007 	IWN_WRITE(sc, IWN_RESET, IWN_RESET_NEVO);
7008 
7009 	/* Disable interrupts. */
7010 	IWN_WRITE(sc, IWN_INT_MASK, 0);
7011 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
7012 	IWN_WRITE(sc, IWN_FH_INT, 0xffffffff);
7013 	sc->sc_flags &= ~IWN_FLAG_USE_ICT;
7014 
7015 	/* Make sure we no longer hold the NIC lock. */
7016 	iwn_nic_unlock(sc);
7017 
7018 	/* Stop TX scheduler. */
7019 	iwn_prph_write(sc, sc->sched_txfact_addr, 0);
7020 
7021 	/* Stop all DMA channels. */
7022 	if (iwn_nic_lock(sc) == 0) {
7023 		for (chnl = 0; chnl < sc->ndmachnls; chnl++) {
7024 			IWN_WRITE(sc, IWN_FH_TX_CONFIG(chnl), 0);
7025 			for (ntries = 0; ntries < 200; ntries++) {
7026 				if (IWN_READ(sc, IWN_FH_TX_STATUS) &
7027 				    IWN_FH_TX_STATUS_IDLE(chnl))
7028 					break;
7029 				DELAY(10);
7030 			}
7031 		}
7032 		iwn_nic_unlock(sc);
7033 	}
7034 
7035 	/* Stop RX ring. */
7036 	iwn_reset_rx_ring(sc, &sc->rxq);
7037 
7038 	/* Reset all TX rings. */
7039 	for (qid = 0; qid < sc->ntxqs; qid++)
7040 		iwn_reset_tx_ring(sc, &sc->txq[qid]);
7041 
7042 	if (iwn_nic_lock(sc) == 0) {
7043 		iwn_prph_write(sc, IWN_APMG_CLK_DIS,
7044 		    IWN_APMG_CLK_CTRL_DMA_CLK_RQT);
7045 		iwn_nic_unlock(sc);
7046 	}
7047 	DELAY(5);
7048 	/* Power OFF adapter. */
7049 	iwn_apm_stop(sc);
7050 }
7051 
7052 int
7053 iwn_init(struct ifnet *ifp)
7054 {
7055 	struct iwn_softc *sc = ifp->if_softc;
7056 	struct ieee80211com *ic = &sc->sc_ic;
7057 	int error;
7058 
7059 	memset(sc->bss_node_addr, 0, sizeof(sc->bss_node_addr));
7060 	sc->agg_queue_mask = 0;
7061 	memset(sc->sc_tx_ba, 0, sizeof(sc->sc_tx_ba));
7062 
7063 	if ((error = iwn_hw_prepare(sc)) != 0) {
7064 		printf("%s: hardware not ready\n", sc->sc_dev.dv_xname);
7065 		goto fail;
7066 	}
7067 
7068 	/* Initialize interrupt mask to default value. */
7069 	sc->int_mask = IWN_INT_MASK_DEF;
7070 	sc->sc_flags &= ~IWN_FLAG_USE_ICT;
7071 
7072 	/* Check that the radio is not disabled by hardware switch. */
7073 	if (!(IWN_READ(sc, IWN_GP_CNTRL) & IWN_GP_CNTRL_RFKILL)) {
7074 		printf("%s: radio is disabled by hardware switch\n",
7075 		    sc->sc_dev.dv_xname);
7076 		error = EPERM;	/* :-) */
7077 		/* Re-enable interrupts. */
7078 		IWN_WRITE(sc, IWN_INT, 0xffffffff);
7079 		IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
7080 		return error;
7081 	}
7082 
7083 	/* Read firmware images from the filesystem. */
7084 	if ((error = iwn_read_firmware(sc)) != 0) {
7085 		printf("%s: could not read firmware\n", sc->sc_dev.dv_xname);
7086 		goto fail;
7087 	}
7088 
7089 	/* Initialize hardware and upload firmware. */
7090 	error = iwn_hw_init(sc);
7091 	free(sc->fw.data, M_DEVBUF, sc->fw.size);
7092 	if (error != 0) {
7093 		printf("%s: could not initialize hardware\n",
7094 		    sc->sc_dev.dv_xname);
7095 		goto fail;
7096 	}
7097 
7098 	/* Configure adapter now that it is ready. */
7099 	if ((error = iwn_config(sc)) != 0) {
7100 		printf("%s: could not configure device\n",
7101 		    sc->sc_dev.dv_xname);
7102 		goto fail;
7103 	}
7104 
7105 	ifq_clr_oactive(&ifp->if_snd);
7106 	ifp->if_flags |= IFF_RUNNING;
7107 
7108 	if (ic->ic_opmode != IEEE80211_M_MONITOR)
7109 		ieee80211_begin_scan(ifp);
7110 	else
7111 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
7112 
7113 	return 0;
7114 
7115 fail:	iwn_stop(ifp);
7116 	return error;
7117 }
7118 
7119 void
7120 iwn_stop(struct ifnet *ifp)
7121 {
7122 	struct iwn_softc *sc = ifp->if_softc;
7123 	struct ieee80211com *ic = &sc->sc_ic;
7124 
7125 	timeout_del(&sc->calib_to);
7126 	ifp->if_timer = sc->sc_tx_timer = 0;
7127 	ifp->if_flags &= ~IFF_RUNNING;
7128 	ifq_clr_oactive(&ifp->if_snd);
7129 
7130 	ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
7131 
7132 	/* Power OFF hardware. */
7133 	iwn_hw_stop(sc);
7134 }
7135