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