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