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