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