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