xref: /freebsd/sys/dev/iwn/if_iwn.c (revision db3cb3640f547c063293e9fdc4db69e9dc120951)
1 /*-
2  * Copyright (c) 2007-2009 Damien Bergamini <damien.bergamini@free.fr>
3  * Copyright (c) 2008 Benjamin Close <benjsc@FreeBSD.org>
4  * Copyright (c) 2008 Sam Leffler, Errno Consulting
5  * Copyright (c) 2011 Intel Corporation
6  * Copyright (c) 2013 Cedric GROSS <c.gross@kreiz-it.fr>
7  * Copyright (c) 2013 Adrian Chadd <adrian@FreeBSD.org>
8  *
9  * Permission to use, copy, modify, and distribute this software for any
10  * purpose with or without fee is hereby granted, provided that the above
11  * copyright notice and this permission notice appear in all copies.
12  *
13  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
14  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
15  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
16  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
17  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
18  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
19  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20  */
21 
22 /*
23  * Driver for Intel WiFi Link 4965 and 1000/5000/6000 Series 802.11 network
24  * adapters.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include "opt_wlan.h"
31 #include "opt_iwn.h"
32 
33 #include <sys/param.h>
34 #include <sys/sockio.h>
35 #include <sys/sysctl.h>
36 #include <sys/mbuf.h>
37 #include <sys/kernel.h>
38 #include <sys/socket.h>
39 #include <sys/systm.h>
40 #include <sys/malloc.h>
41 #include <sys/bus.h>
42 #include <sys/rman.h>
43 #include <sys/endian.h>
44 #include <sys/firmware.h>
45 #include <sys/limits.h>
46 #include <sys/module.h>
47 #include <sys/queue.h>
48 #include <sys/taskqueue.h>
49 
50 #include <machine/bus.h>
51 #include <machine/resource.h>
52 #include <machine/clock.h>
53 
54 #include <dev/pci/pcireg.h>
55 #include <dev/pci/pcivar.h>
56 
57 #include <net/bpf.h>
58 #include <net/if.h>
59 #include <net/if_var.h>
60 #include <net/if_arp.h>
61 #include <net/ethernet.h>
62 #include <net/if_dl.h>
63 #include <net/if_media.h>
64 #include <net/if_types.h>
65 
66 #include <netinet/in.h>
67 #include <netinet/in_systm.h>
68 #include <netinet/in_var.h>
69 #include <netinet/if_ether.h>
70 #include <netinet/ip.h>
71 
72 #include <net80211/ieee80211_var.h>
73 #include <net80211/ieee80211_radiotap.h>
74 #include <net80211/ieee80211_regdomain.h>
75 #include <net80211/ieee80211_ratectl.h>
76 
77 #include <dev/iwn/if_iwnreg.h>
78 #include <dev/iwn/if_iwnvar.h>
79 #include <dev/iwn/if_iwn_devid.h>
80 #include <dev/iwn/if_iwn_chip_cfg.h>
81 #include <dev/iwn/if_iwn_debug.h>
82 #include <dev/iwn/if_iwn_ioctl.h>
83 
84 struct iwn_ident {
85 	uint16_t	vendor;
86 	uint16_t	device;
87 	const char	*name;
88 };
89 
90 static const struct iwn_ident iwn_ident_table[] = {
91 	{ 0x8086, IWN_DID_6x05_1, "Intel Centrino Advanced-N 6205"		},
92 	{ 0x8086, IWN_DID_1000_1, "Intel Centrino Wireless-N 1000"		},
93 	{ 0x8086, IWN_DID_1000_2, "Intel Centrino Wireless-N 1000"		},
94 	{ 0x8086, IWN_DID_6x05_2, "Intel Centrino Advanced-N 6205"		},
95 	{ 0x8086, IWN_DID_6050_1, "Intel Centrino Advanced-N + WiMAX 6250"	},
96 	{ 0x8086, IWN_DID_6050_2, "Intel Centrino Advanced-N + WiMAX 6250"	},
97 	{ 0x8086, IWN_DID_x030_1, "Intel Centrino Wireless-N 1030"		},
98 	{ 0x8086, IWN_DID_x030_2, "Intel Centrino Wireless-N 1030"		},
99 	{ 0x8086, IWN_DID_x030_3, "Intel Centrino Advanced-N 6230"		},
100 	{ 0x8086, IWN_DID_x030_4, "Intel Centrino Advanced-N 6230"		},
101 	{ 0x8086, IWN_DID_6150_1, "Intel Centrino Wireless-N + WiMAX 6150"	},
102 	{ 0x8086, IWN_DID_6150_2, "Intel Centrino Wireless-N + WiMAX 6150"	},
103 	{ 0x8086, IWN_DID_2x00_1, "Intel(R) Centrino(R) Wireless-N 2200 BGN"	},
104 	{ 0x8086, IWN_DID_2x00_2, "Intel(R) Centrino(R) Wireless-N 2200 BGN"	},
105 	/* XXX 2200D is IWN_SDID_2x00_4; there's no way to express this here! */
106 	{ 0x8086, IWN_DID_2x30_1, "Intel Centrino Wireless-N 2230"		},
107 	{ 0x8086, IWN_DID_2x30_2, "Intel Centrino Wireless-N 2230"		},
108 	{ 0x8086, IWN_DID_130_1, "Intel Centrino Wireless-N 130"		},
109 	{ 0x8086, IWN_DID_130_2, "Intel Centrino Wireless-N 130"		},
110 	{ 0x8086, IWN_DID_100_1, "Intel Centrino Wireless-N 100"		},
111 	{ 0x8086, IWN_DID_100_2, "Intel Centrino Wireless-N 100"		},
112 	{ 0x8086, IWN_DID_105_1, "Intel Centrino Wireless-N 105"		},
113 	{ 0x8086, IWN_DID_105_2, "Intel Centrino Wireless-N 105"		},
114 	{ 0x8086, IWN_DID_135_1, "Intel Centrino Wireless-N 135"		},
115 	{ 0x8086, IWN_DID_135_2, "Intel Centrino Wireless-N 135"		},
116 	{ 0x8086, IWN_DID_4965_1, "Intel Wireless WiFi Link 4965"		},
117 	{ 0x8086, IWN_DID_6x00_1, "Intel Centrino Ultimate-N 6300"		},
118 	{ 0x8086, IWN_DID_6x00_2, "Intel Centrino Advanced-N 6200"		},
119 	{ 0x8086, IWN_DID_4965_2, "Intel Wireless WiFi Link 4965"		},
120 	{ 0x8086, IWN_DID_4965_3, "Intel Wireless WiFi Link 4965"		},
121 	{ 0x8086, IWN_DID_5x00_1, "Intel WiFi Link 5100"			},
122 	{ 0x8086, IWN_DID_4965_4, "Intel Wireless WiFi Link 4965"		},
123 	{ 0x8086, IWN_DID_5x00_3, "Intel Ultimate N WiFi Link 5300"		},
124 	{ 0x8086, IWN_DID_5x00_4, "Intel Ultimate N WiFi Link 5300"		},
125 	{ 0x8086, IWN_DID_5x00_2, "Intel WiFi Link 5100"			},
126 	{ 0x8086, IWN_DID_6x00_3, "Intel Centrino Ultimate-N 6300"		},
127 	{ 0x8086, IWN_DID_6x00_4, "Intel Centrino Advanced-N 6200"		},
128 	{ 0x8086, IWN_DID_5x50_1, "Intel WiMAX/WiFi Link 5350"			},
129 	{ 0x8086, IWN_DID_5x50_2, "Intel WiMAX/WiFi Link 5350"			},
130 	{ 0x8086, IWN_DID_5x50_3, "Intel WiMAX/WiFi Link 5150"			},
131 	{ 0x8086, IWN_DID_5x50_4, "Intel WiMAX/WiFi Link 5150"			},
132 	{ 0x8086, IWN_DID_6035_1, "Intel Centrino Advanced 6235"		},
133 	{ 0x8086, IWN_DID_6035_2, "Intel Centrino Advanced 6235"		},
134 	{ 0, 0, NULL }
135 };
136 
137 static int	iwn_probe(device_t);
138 static int	iwn_attach(device_t);
139 static int	iwn4965_attach(struct iwn_softc *, uint16_t);
140 static int	iwn5000_attach(struct iwn_softc *, uint16_t);
141 static int	iwn_config_specific(struct iwn_softc *, uint16_t);
142 static void	iwn_radiotap_attach(struct iwn_softc *);
143 static void	iwn_sysctlattach(struct iwn_softc *);
144 static struct ieee80211vap *iwn_vap_create(struct ieee80211com *,
145 		    const char [IFNAMSIZ], int, enum ieee80211_opmode, int,
146 		    const uint8_t [IEEE80211_ADDR_LEN],
147 		    const uint8_t [IEEE80211_ADDR_LEN]);
148 static void	iwn_vap_delete(struct ieee80211vap *);
149 static int	iwn_detach(device_t);
150 static int	iwn_shutdown(device_t);
151 static int	iwn_suspend(device_t);
152 static int	iwn_resume(device_t);
153 static int	iwn_nic_lock(struct iwn_softc *);
154 static int	iwn_eeprom_lock(struct iwn_softc *);
155 static int	iwn_init_otprom(struct iwn_softc *);
156 static int	iwn_read_prom_data(struct iwn_softc *, uint32_t, void *, int);
157 static void	iwn_dma_map_addr(void *, bus_dma_segment_t *, int, int);
158 static int	iwn_dma_contig_alloc(struct iwn_softc *, struct iwn_dma_info *,
159 		    void **, bus_size_t, bus_size_t);
160 static void	iwn_dma_contig_free(struct iwn_dma_info *);
161 static int	iwn_alloc_sched(struct iwn_softc *);
162 static void	iwn_free_sched(struct iwn_softc *);
163 static int	iwn_alloc_kw(struct iwn_softc *);
164 static void	iwn_free_kw(struct iwn_softc *);
165 static int	iwn_alloc_ict(struct iwn_softc *);
166 static void	iwn_free_ict(struct iwn_softc *);
167 static int	iwn_alloc_fwmem(struct iwn_softc *);
168 static void	iwn_free_fwmem(struct iwn_softc *);
169 static int	iwn_alloc_rx_ring(struct iwn_softc *, struct iwn_rx_ring *);
170 static void	iwn_reset_rx_ring(struct iwn_softc *, struct iwn_rx_ring *);
171 static void	iwn_free_rx_ring(struct iwn_softc *, struct iwn_rx_ring *);
172 static int	iwn_alloc_tx_ring(struct iwn_softc *, struct iwn_tx_ring *,
173 		    int);
174 static void	iwn_reset_tx_ring(struct iwn_softc *, struct iwn_tx_ring *);
175 static void	iwn_free_tx_ring(struct iwn_softc *, struct iwn_tx_ring *);
176 static void	iwn5000_ict_reset(struct iwn_softc *);
177 static int	iwn_read_eeprom(struct iwn_softc *,
178 		    uint8_t macaddr[IEEE80211_ADDR_LEN]);
179 static void	iwn4965_read_eeprom(struct iwn_softc *);
180 #ifdef	IWN_DEBUG
181 static void	iwn4965_print_power_group(struct iwn_softc *, int);
182 #endif
183 static void	iwn5000_read_eeprom(struct iwn_softc *);
184 static uint32_t	iwn_eeprom_channel_flags(struct iwn_eeprom_chan *);
185 static void	iwn_read_eeprom_band(struct iwn_softc *, int);
186 static void	iwn_read_eeprom_ht40(struct iwn_softc *, int);
187 static void	iwn_read_eeprom_channels(struct iwn_softc *, int, uint32_t);
188 static struct iwn_eeprom_chan *iwn_find_eeprom_channel(struct iwn_softc *,
189 		    struct ieee80211_channel *);
190 static int	iwn_setregdomain(struct ieee80211com *,
191 		    struct ieee80211_regdomain *, int,
192 		    struct ieee80211_channel[]);
193 static void	iwn_read_eeprom_enhinfo(struct iwn_softc *);
194 static struct ieee80211_node *iwn_node_alloc(struct ieee80211vap *,
195 		    const uint8_t mac[IEEE80211_ADDR_LEN]);
196 static void	iwn_newassoc(struct ieee80211_node *, int);
197 static int	iwn_media_change(struct ifnet *);
198 static int	iwn_newstate(struct ieee80211vap *, enum ieee80211_state, int);
199 static void	iwn_calib_timeout(void *);
200 static void	iwn_rx_phy(struct iwn_softc *, struct iwn_rx_desc *,
201 		    struct iwn_rx_data *);
202 static void	iwn_rx_done(struct iwn_softc *, struct iwn_rx_desc *,
203 		    struct iwn_rx_data *);
204 static void	iwn_rx_compressed_ba(struct iwn_softc *, struct iwn_rx_desc *,
205 		    struct iwn_rx_data *);
206 static void	iwn5000_rx_calib_results(struct iwn_softc *,
207 		    struct iwn_rx_desc *, struct iwn_rx_data *);
208 static void	iwn_rx_statistics(struct iwn_softc *, struct iwn_rx_desc *,
209 		    struct iwn_rx_data *);
210 static void	iwn4965_tx_done(struct iwn_softc *, struct iwn_rx_desc *,
211 		    struct iwn_rx_data *);
212 static void	iwn5000_tx_done(struct iwn_softc *, struct iwn_rx_desc *,
213 		    struct iwn_rx_data *);
214 static void	iwn_tx_done(struct iwn_softc *, struct iwn_rx_desc *, int,
215 		    uint8_t);
216 static void	iwn_ampdu_tx_done(struct iwn_softc *, int, int, int, int, void *);
217 static void	iwn_cmd_done(struct iwn_softc *, struct iwn_rx_desc *);
218 static void	iwn_notif_intr(struct iwn_softc *);
219 static void	iwn_wakeup_intr(struct iwn_softc *);
220 static void	iwn_rftoggle_intr(struct iwn_softc *);
221 static void	iwn_fatal_intr(struct iwn_softc *);
222 static void	iwn_intr(void *);
223 static void	iwn4965_update_sched(struct iwn_softc *, int, int, uint8_t,
224 		    uint16_t);
225 static void	iwn5000_update_sched(struct iwn_softc *, int, int, uint8_t,
226 		    uint16_t);
227 #ifdef notyet
228 static void	iwn5000_reset_sched(struct iwn_softc *, int, int);
229 #endif
230 static int	iwn_tx_data(struct iwn_softc *, struct mbuf *,
231 		    struct ieee80211_node *);
232 static int	iwn_tx_data_raw(struct iwn_softc *, struct mbuf *,
233 		    struct ieee80211_node *,
234 		    const struct ieee80211_bpf_params *params);
235 static int	iwn_raw_xmit(struct ieee80211_node *, struct mbuf *,
236 		    const struct ieee80211_bpf_params *);
237 static void	iwn_start(struct ifnet *);
238 static void	iwn_start_locked(struct ifnet *);
239 static void	iwn_watchdog(void *);
240 static int	iwn_ioctl(struct ifnet *, u_long, caddr_t);
241 static int	iwn_cmd(struct iwn_softc *, int, const void *, int, int);
242 static int	iwn4965_add_node(struct iwn_softc *, struct iwn_node_info *,
243 		    int);
244 static int	iwn5000_add_node(struct iwn_softc *, struct iwn_node_info *,
245 		    int);
246 static int	iwn_set_link_quality(struct iwn_softc *,
247 		    struct ieee80211_node *);
248 static int	iwn_add_broadcast_node(struct iwn_softc *, int);
249 static int	iwn_updateedca(struct ieee80211com *);
250 static void	iwn_update_mcast(struct ifnet *);
251 static void	iwn_set_led(struct iwn_softc *, uint8_t, uint8_t, uint8_t);
252 static int	iwn_set_critical_temp(struct iwn_softc *);
253 static int	iwn_set_timing(struct iwn_softc *, struct ieee80211_node *);
254 static void	iwn4965_power_calibration(struct iwn_softc *, int);
255 static int	iwn4965_set_txpower(struct iwn_softc *,
256 		    struct ieee80211_channel *, int);
257 static int	iwn5000_set_txpower(struct iwn_softc *,
258 		    struct ieee80211_channel *, int);
259 static int	iwn4965_get_rssi(struct iwn_softc *, struct iwn_rx_stat *);
260 static int	iwn5000_get_rssi(struct iwn_softc *, struct iwn_rx_stat *);
261 static int	iwn_get_noise(const struct iwn_rx_general_stats *);
262 static int	iwn4965_get_temperature(struct iwn_softc *);
263 static int	iwn5000_get_temperature(struct iwn_softc *);
264 static int	iwn_init_sensitivity(struct iwn_softc *);
265 static void	iwn_collect_noise(struct iwn_softc *,
266 		    const struct iwn_rx_general_stats *);
267 static int	iwn4965_init_gains(struct iwn_softc *);
268 static int	iwn5000_init_gains(struct iwn_softc *);
269 static int	iwn4965_set_gains(struct iwn_softc *);
270 static int	iwn5000_set_gains(struct iwn_softc *);
271 static void	iwn_tune_sensitivity(struct iwn_softc *,
272 		    const struct iwn_rx_stats *);
273 static void	iwn_save_stats_counters(struct iwn_softc *,
274 		    const struct iwn_stats *);
275 static int	iwn_send_sensitivity(struct iwn_softc *);
276 static void	iwn_check_rx_recovery(struct iwn_softc *, struct iwn_stats *);
277 static int	iwn_set_pslevel(struct iwn_softc *, int, int, int);
278 static int	iwn_send_btcoex(struct iwn_softc *);
279 static int	iwn_send_advanced_btcoex(struct iwn_softc *);
280 static int	iwn5000_runtime_calib(struct iwn_softc *);
281 static int	iwn_config(struct iwn_softc *);
282 static int	iwn_scan(struct iwn_softc *, struct ieee80211vap *,
283 		    struct ieee80211_scan_state *, struct ieee80211_channel *);
284 static int	iwn_auth(struct iwn_softc *, struct ieee80211vap *vap);
285 static int	iwn_run(struct iwn_softc *, struct ieee80211vap *vap);
286 static int	iwn_ampdu_rx_start(struct ieee80211_node *,
287 		    struct ieee80211_rx_ampdu *, int, int, int);
288 static void	iwn_ampdu_rx_stop(struct ieee80211_node *,
289 		    struct ieee80211_rx_ampdu *);
290 static int	iwn_addba_request(struct ieee80211_node *,
291 		    struct ieee80211_tx_ampdu *, int, int, int);
292 static int	iwn_addba_response(struct ieee80211_node *,
293 		    struct ieee80211_tx_ampdu *, int, int, int);
294 static int	iwn_ampdu_tx_start(struct ieee80211com *,
295 		    struct ieee80211_node *, uint8_t);
296 static void	iwn_ampdu_tx_stop(struct ieee80211_node *,
297 		    struct ieee80211_tx_ampdu *);
298 static void	iwn4965_ampdu_tx_start(struct iwn_softc *,
299 		    struct ieee80211_node *, int, uint8_t, uint16_t);
300 static void	iwn4965_ampdu_tx_stop(struct iwn_softc *, int,
301 		    uint8_t, uint16_t);
302 static void	iwn5000_ampdu_tx_start(struct iwn_softc *,
303 		    struct ieee80211_node *, int, uint8_t, uint16_t);
304 static void	iwn5000_ampdu_tx_stop(struct iwn_softc *, int,
305 		    uint8_t, uint16_t);
306 static int	iwn5000_query_calibration(struct iwn_softc *);
307 static int	iwn5000_send_calibration(struct iwn_softc *);
308 static int	iwn5000_send_wimax_coex(struct iwn_softc *);
309 static int	iwn5000_crystal_calib(struct iwn_softc *);
310 static int	iwn5000_temp_offset_calib(struct iwn_softc *);
311 static int	iwn5000_temp_offset_calibv2(struct iwn_softc *);
312 static int	iwn4965_post_alive(struct iwn_softc *);
313 static int	iwn5000_post_alive(struct iwn_softc *);
314 static int	iwn4965_load_bootcode(struct iwn_softc *, const uint8_t *,
315 		    int);
316 static int	iwn4965_load_firmware(struct iwn_softc *);
317 static int	iwn5000_load_firmware_section(struct iwn_softc *, uint32_t,
318 		    const uint8_t *, int);
319 static int	iwn5000_load_firmware(struct iwn_softc *);
320 static int	iwn_read_firmware_leg(struct iwn_softc *,
321 		    struct iwn_fw_info *);
322 static int	iwn_read_firmware_tlv(struct iwn_softc *,
323 		    struct iwn_fw_info *, uint16_t);
324 static int	iwn_read_firmware(struct iwn_softc *);
325 static int	iwn_clock_wait(struct iwn_softc *);
326 static int	iwn_apm_init(struct iwn_softc *);
327 static void	iwn_apm_stop_master(struct iwn_softc *);
328 static void	iwn_apm_stop(struct iwn_softc *);
329 static int	iwn4965_nic_config(struct iwn_softc *);
330 static int	iwn5000_nic_config(struct iwn_softc *);
331 static int	iwn_hw_prepare(struct iwn_softc *);
332 static int	iwn_hw_init(struct iwn_softc *);
333 static void	iwn_hw_stop(struct iwn_softc *);
334 static void	iwn_radio_on(void *, int);
335 static void	iwn_radio_off(void *, int);
336 static void	iwn_panicked(void *, int);
337 static void	iwn_init_locked(struct iwn_softc *);
338 static void	iwn_init(void *);
339 static void	iwn_stop_locked(struct iwn_softc *);
340 static void	iwn_stop(struct iwn_softc *);
341 static void	iwn_scan_start(struct ieee80211com *);
342 static void	iwn_scan_end(struct ieee80211com *);
343 static void	iwn_set_channel(struct ieee80211com *);
344 static void	iwn_scan_curchan(struct ieee80211_scan_state *, unsigned long);
345 static void	iwn_scan_mindwell(struct ieee80211_scan_state *);
346 static void	iwn_hw_reset(void *, int);
347 #ifdef	IWN_DEBUG
348 static char	*iwn_get_csr_string(int);
349 static void	iwn_debug_register(struct iwn_softc *);
350 #endif
351 
352 static device_method_t iwn_methods[] = {
353 	/* Device interface */
354 	DEVMETHOD(device_probe,		iwn_probe),
355 	DEVMETHOD(device_attach,	iwn_attach),
356 	DEVMETHOD(device_detach,	iwn_detach),
357 	DEVMETHOD(device_shutdown,	iwn_shutdown),
358 	DEVMETHOD(device_suspend,	iwn_suspend),
359 	DEVMETHOD(device_resume,	iwn_resume),
360 
361 	DEVMETHOD_END
362 };
363 
364 static driver_t iwn_driver = {
365 	"iwn",
366 	iwn_methods,
367 	sizeof(struct iwn_softc)
368 };
369 static devclass_t iwn_devclass;
370 
371 DRIVER_MODULE(iwn, pci, iwn_driver, iwn_devclass, NULL, NULL);
372 
373 MODULE_VERSION(iwn, 1);
374 
375 MODULE_DEPEND(iwn, firmware, 1, 1, 1);
376 MODULE_DEPEND(iwn, pci, 1, 1, 1);
377 MODULE_DEPEND(iwn, wlan, 1, 1, 1);
378 
379 static int
380 iwn_probe(device_t dev)
381 {
382 	const struct iwn_ident *ident;
383 
384 	for (ident = iwn_ident_table; ident->name != NULL; ident++) {
385 		if (pci_get_vendor(dev) == ident->vendor &&
386 		    pci_get_device(dev) == ident->device) {
387 			device_set_desc(dev, ident->name);
388 			return (BUS_PROBE_DEFAULT);
389 		}
390 	}
391 	return ENXIO;
392 }
393 
394 static int
395 iwn_is_3stream_device(struct iwn_softc *sc)
396 {
397 	/* XXX for now only 5300, until the 5350 can be tested */
398 	if (sc->hw_type == IWN_HW_REV_TYPE_5300)
399 		return (1);
400 	return (0);
401 }
402 
403 static int
404 iwn_attach(device_t dev)
405 {
406 	struct iwn_softc *sc = (struct iwn_softc *)device_get_softc(dev);
407 	struct ieee80211com *ic;
408 	struct ifnet *ifp;
409 	int i, error, rid;
410 	uint8_t macaddr[IEEE80211_ADDR_LEN];
411 
412 	sc->sc_dev = dev;
413 
414 #ifdef	IWN_DEBUG
415 	error = resource_int_value(device_get_name(sc->sc_dev),
416 	    device_get_unit(sc->sc_dev), "debug", &(sc->sc_debug));
417 	if (error != 0)
418 		sc->sc_debug = 0;
419 #else
420 	sc->sc_debug = 0;
421 #endif
422 
423 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: begin\n",__func__);
424 
425 	/*
426 	 * Get the offset of the PCI Express Capability Structure in PCI
427 	 * Configuration Space.
428 	 */
429 	error = pci_find_cap(dev, PCIY_EXPRESS, &sc->sc_cap_off);
430 	if (error != 0) {
431 		device_printf(dev, "PCIe capability structure not found!\n");
432 		return error;
433 	}
434 
435 	/* Clear device-specific "PCI retry timeout" register (41h). */
436 	pci_write_config(dev, 0x41, 0, 1);
437 
438 	/* Enable bus-mastering. */
439 	pci_enable_busmaster(dev);
440 
441 	rid = PCIR_BAR(0);
442 	sc->mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid,
443 	    RF_ACTIVE);
444 	if (sc->mem == NULL) {
445 		device_printf(dev, "can't map mem space\n");
446 		error = ENOMEM;
447 		return error;
448 	}
449 	sc->sc_st = rman_get_bustag(sc->mem);
450 	sc->sc_sh = rman_get_bushandle(sc->mem);
451 
452 	i = 1;
453 	rid = 0;
454 	if (pci_alloc_msi(dev, &i) == 0)
455 		rid = 1;
456 	/* Install interrupt handler. */
457 	sc->irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, RF_ACTIVE |
458 	    (rid != 0 ? 0 : RF_SHAREABLE));
459 	if (sc->irq == NULL) {
460 		device_printf(dev, "can't map interrupt\n");
461 		error = ENOMEM;
462 		goto fail;
463 	}
464 
465 	IWN_LOCK_INIT(sc);
466 
467 	/* Read hardware revision and attach. */
468 	sc->hw_type = (IWN_READ(sc, IWN_HW_REV) >> IWN_HW_REV_TYPE_SHIFT)
469 	    & IWN_HW_REV_TYPE_MASK;
470 	sc->subdevice_id = pci_get_subdevice(dev);
471 
472 	/*
473 	 * 4965 versus 5000 and later have different methods.
474 	 * Let's set those up first.
475 	 */
476 	if (sc->hw_type == IWN_HW_REV_TYPE_4965)
477 		error = iwn4965_attach(sc, pci_get_device(dev));
478 	else
479 		error = iwn5000_attach(sc, pci_get_device(dev));
480 	if (error != 0) {
481 		device_printf(dev, "could not attach device, error %d\n",
482 		    error);
483 		goto fail;
484 	}
485 
486 	/*
487 	 * Next, let's setup the various parameters of each NIC.
488 	 */
489 	error = iwn_config_specific(sc, pci_get_device(dev));
490 	if (error != 0) {
491 		device_printf(dev, "could not attach device, error %d\n",
492 		    error);
493 		goto fail;
494 	}
495 
496 	if ((error = iwn_hw_prepare(sc)) != 0) {
497 		device_printf(dev, "hardware not ready, error %d\n", error);
498 		goto fail;
499 	}
500 
501 	/* Allocate DMA memory for firmware transfers. */
502 	if ((error = iwn_alloc_fwmem(sc)) != 0) {
503 		device_printf(dev,
504 		    "could not allocate memory for firmware, error %d\n",
505 		    error);
506 		goto fail;
507 	}
508 
509 	/* Allocate "Keep Warm" page. */
510 	if ((error = iwn_alloc_kw(sc)) != 0) {
511 		device_printf(dev,
512 		    "could not allocate keep warm page, error %d\n", error);
513 		goto fail;
514 	}
515 
516 	/* Allocate ICT table for 5000 Series. */
517 	if (sc->hw_type != IWN_HW_REV_TYPE_4965 &&
518 	    (error = iwn_alloc_ict(sc)) != 0) {
519 		device_printf(dev, "could not allocate ICT table, error %d\n",
520 		    error);
521 		goto fail;
522 	}
523 
524 	/* Allocate TX scheduler "rings". */
525 	if ((error = iwn_alloc_sched(sc)) != 0) {
526 		device_printf(dev,
527 		    "could not allocate TX scheduler rings, error %d\n", error);
528 		goto fail;
529 	}
530 
531 	/* Allocate TX rings (16 on 4965AGN, 20 on >=5000). */
532 	for (i = 0; i < sc->ntxqs; i++) {
533 		if ((error = iwn_alloc_tx_ring(sc, &sc->txq[i], i)) != 0) {
534 			device_printf(dev,
535 			    "could not allocate TX ring %d, error %d\n", i,
536 			    error);
537 			goto fail;
538 		}
539 	}
540 
541 	/* Allocate RX ring. */
542 	if ((error = iwn_alloc_rx_ring(sc, &sc->rxq)) != 0) {
543 		device_printf(dev, "could not allocate RX ring, error %d\n",
544 		    error);
545 		goto fail;
546 	}
547 
548 	/* Clear pending interrupts. */
549 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
550 
551 	ifp = sc->sc_ifp = if_alloc(IFT_IEEE80211);
552 	if (ifp == NULL) {
553 		device_printf(dev, "can not allocate ifnet structure\n");
554 		goto fail;
555 	}
556 
557 	ic = ifp->if_l2com;
558 	ic->ic_ifp = ifp;
559 	ic->ic_phytype = IEEE80211_T_OFDM;	/* not only, but not used */
560 	ic->ic_opmode = IEEE80211_M_STA;	/* default to BSS mode */
561 
562 	/* Set device capabilities. */
563 	ic->ic_caps =
564 		  IEEE80211_C_STA		/* station mode supported */
565 		| IEEE80211_C_MONITOR		/* monitor mode supported */
566 		| IEEE80211_C_BGSCAN		/* background scanning */
567 		| IEEE80211_C_TXPMGT		/* tx power management */
568 		| IEEE80211_C_SHSLOT		/* short slot time supported */
569 		| IEEE80211_C_WPA
570 		| IEEE80211_C_SHPREAMBLE	/* short preamble supported */
571 #if 0
572 		| IEEE80211_C_IBSS		/* ibss/adhoc mode */
573 #endif
574 		| IEEE80211_C_WME		/* WME */
575 		| IEEE80211_C_PMGT		/* Station-side power mgmt */
576 		;
577 
578 	/* Read MAC address, channels, etc from EEPROM. */
579 	if ((error = iwn_read_eeprom(sc, macaddr)) != 0) {
580 		device_printf(dev, "could not read EEPROM, error %d\n",
581 		    error);
582 		goto fail;
583 	}
584 
585 	/* Count the number of available chains. */
586 	sc->ntxchains =
587 	    ((sc->txchainmask >> 2) & 1) +
588 	    ((sc->txchainmask >> 1) & 1) +
589 	    ((sc->txchainmask >> 0) & 1);
590 	sc->nrxchains =
591 	    ((sc->rxchainmask >> 2) & 1) +
592 	    ((sc->rxchainmask >> 1) & 1) +
593 	    ((sc->rxchainmask >> 0) & 1);
594 	if (bootverbose) {
595 		device_printf(dev, "MIMO %dT%dR, %.4s, address %6D\n",
596 		    sc->ntxchains, sc->nrxchains, sc->eeprom_domain,
597 		    macaddr, ":");
598 	}
599 
600 	if (sc->sc_flags & IWN_FLAG_HAS_11N) {
601 		ic->ic_rxstream = sc->nrxchains;
602 		ic->ic_txstream = sc->ntxchains;
603 
604 		/*
605 		 * Some of the 3 antenna devices (ie, the 4965) only supports
606 		 * 2x2 operation.  So correct the number of streams if
607 		 * it's not a 3-stream device.
608 		 */
609 		if (! iwn_is_3stream_device(sc)) {
610 			if (ic->ic_rxstream > 2)
611 				ic->ic_rxstream = 2;
612 			if (ic->ic_txstream > 2)
613 				ic->ic_txstream = 2;
614 		}
615 
616 		ic->ic_htcaps =
617 			  IEEE80211_HTCAP_SMPS_OFF	/* SMPS mode disabled */
618 			| IEEE80211_HTCAP_SHORTGI20	/* short GI in 20MHz */
619 			| IEEE80211_HTCAP_CHWIDTH40	/* 40MHz channel width*/
620 			| IEEE80211_HTCAP_SHORTGI40	/* short GI in 40MHz */
621 #ifdef notyet
622 			| IEEE80211_HTCAP_GREENFIELD
623 #if IWN_RBUF_SIZE == 8192
624 			| IEEE80211_HTCAP_MAXAMSDU_7935	/* max A-MSDU length */
625 #else
626 			| IEEE80211_HTCAP_MAXAMSDU_3839	/* max A-MSDU length */
627 #endif
628 #endif
629 			/* s/w capabilities */
630 			| IEEE80211_HTC_HT		/* HT operation */
631 			| IEEE80211_HTC_AMPDU		/* tx A-MPDU */
632 #ifdef notyet
633 			| IEEE80211_HTC_AMSDU		/* tx A-MSDU */
634 #endif
635 			;
636 	}
637 
638 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
639 	ifp->if_softc = sc;
640 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
641 	ifp->if_init = iwn_init;
642 	ifp->if_ioctl = iwn_ioctl;
643 	ifp->if_start = iwn_start;
644 	IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
645 	ifp->if_snd.ifq_drv_maxlen = ifqmaxlen;
646 	IFQ_SET_READY(&ifp->if_snd);
647 
648 	ieee80211_ifattach(ic, macaddr);
649 	ic->ic_vap_create = iwn_vap_create;
650 	ic->ic_vap_delete = iwn_vap_delete;
651 	ic->ic_raw_xmit = iwn_raw_xmit;
652 	ic->ic_node_alloc = iwn_node_alloc;
653 	sc->sc_ampdu_rx_start = ic->ic_ampdu_rx_start;
654 	ic->ic_ampdu_rx_start = iwn_ampdu_rx_start;
655 	sc->sc_ampdu_rx_stop = ic->ic_ampdu_rx_stop;
656 	ic->ic_ampdu_rx_stop = iwn_ampdu_rx_stop;
657 	sc->sc_addba_request = ic->ic_addba_request;
658 	ic->ic_addba_request = iwn_addba_request;
659 	sc->sc_addba_response = ic->ic_addba_response;
660 	ic->ic_addba_response = iwn_addba_response;
661 	sc->sc_addba_stop = ic->ic_addba_stop;
662 	ic->ic_addba_stop = iwn_ampdu_tx_stop;
663 	ic->ic_newassoc = iwn_newassoc;
664 	ic->ic_wme.wme_update = iwn_updateedca;
665 	ic->ic_update_mcast = iwn_update_mcast;
666 	ic->ic_scan_start = iwn_scan_start;
667 	ic->ic_scan_end = iwn_scan_end;
668 	ic->ic_set_channel = iwn_set_channel;
669 	ic->ic_scan_curchan = iwn_scan_curchan;
670 	ic->ic_scan_mindwell = iwn_scan_mindwell;
671 	ic->ic_setregdomain = iwn_setregdomain;
672 
673 	iwn_radiotap_attach(sc);
674 
675 	callout_init_mtx(&sc->calib_to, &sc->sc_mtx, 0);
676 	callout_init_mtx(&sc->watchdog_to, &sc->sc_mtx, 0);
677 	TASK_INIT(&sc->sc_reinit_task, 0, iwn_hw_reset, sc);
678 	TASK_INIT(&sc->sc_radioon_task, 0, iwn_radio_on, sc);
679 	TASK_INIT(&sc->sc_radiooff_task, 0, iwn_radio_off, sc);
680 	TASK_INIT(&sc->sc_panic_task, 0, iwn_panicked, sc);
681 
682 	sc->sc_tq = taskqueue_create("iwn_taskq", M_WAITOK,
683 	    taskqueue_thread_enqueue, &sc->sc_tq);
684 	error = taskqueue_start_threads(&sc->sc_tq, 1, 0, "iwn_taskq");
685 	if (error != 0) {
686 		device_printf(dev, "can't start threads, error %d\n", error);
687 		goto fail;
688 	}
689 
690 	iwn_sysctlattach(sc);
691 
692 	/*
693 	 * Hook our interrupt after all initialization is complete.
694 	 */
695 	error = bus_setup_intr(dev, sc->irq, INTR_TYPE_NET | INTR_MPSAFE,
696 	    NULL, iwn_intr, sc, &sc->sc_ih);
697 	if (error != 0) {
698 		device_printf(dev, "can't establish interrupt, error %d\n",
699 		    error);
700 		goto fail;
701 	}
702 
703 #if 0
704 	device_printf(sc->sc_dev, "%s: rx_stats=%d, rx_stats_bt=%d\n",
705 	    __func__,
706 	    sizeof(struct iwn_stats),
707 	    sizeof(struct iwn_stats_bt));
708 #endif
709 
710 	if (bootverbose)
711 		ieee80211_announce(ic);
712 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
713 	return 0;
714 fail:
715 	iwn_detach(dev);
716 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end in error\n",__func__);
717 	return error;
718 }
719 
720 /*
721  * Define specific configuration based on device id and subdevice id
722  * pid : PCI device id
723  */
724 static int
725 iwn_config_specific(struct iwn_softc *sc, uint16_t pid)
726 {
727 
728 	switch (pid) {
729 /* 4965 series */
730 	case IWN_DID_4965_1:
731 	case IWN_DID_4965_2:
732 	case IWN_DID_4965_3:
733 	case IWN_DID_4965_4:
734 		sc->base_params = &iwn4965_base_params;
735 		sc->limits = &iwn4965_sensitivity_limits;
736 		sc->fwname = "iwn4965fw";
737 		/* Override chains masks, ROM is known to be broken. */
738 		sc->txchainmask = IWN_ANT_AB;
739 		sc->rxchainmask = IWN_ANT_ABC;
740 		/* Enable normal btcoex */
741 		sc->sc_flags |= IWN_FLAG_BTCOEX;
742 		break;
743 /* 1000 Series */
744 	case IWN_DID_1000_1:
745 	case IWN_DID_1000_2:
746 		switch(sc->subdevice_id) {
747 			case	IWN_SDID_1000_1:
748 			case	IWN_SDID_1000_2:
749 			case	IWN_SDID_1000_3:
750 			case	IWN_SDID_1000_4:
751 			case	IWN_SDID_1000_5:
752 			case	IWN_SDID_1000_6:
753 			case	IWN_SDID_1000_7:
754 			case	IWN_SDID_1000_8:
755 			case	IWN_SDID_1000_9:
756 			case	IWN_SDID_1000_10:
757 			case	IWN_SDID_1000_11:
758 			case	IWN_SDID_1000_12:
759 				sc->limits = &iwn1000_sensitivity_limits;
760 				sc->base_params = &iwn1000_base_params;
761 				sc->fwname = "iwn1000fw";
762 				break;
763 			default:
764 				device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
765 				    "0x%04x rev %d not supported (subdevice)\n", pid,
766 				    sc->subdevice_id,sc->hw_type);
767 				return ENOTSUP;
768 		}
769 		break;
770 /* 6x00 Series */
771 	case IWN_DID_6x00_2:
772 	case IWN_DID_6x00_4:
773 	case IWN_DID_6x00_1:
774 	case IWN_DID_6x00_3:
775 		sc->fwname = "iwn6000fw";
776 		sc->limits = &iwn6000_sensitivity_limits;
777 		switch(sc->subdevice_id) {
778 			case IWN_SDID_6x00_1:
779 			case IWN_SDID_6x00_2:
780 			case IWN_SDID_6x00_8:
781 				//iwl6000_3agn_cfg
782 				sc->base_params = &iwn_6000_base_params;
783 				break;
784 			case IWN_SDID_6x00_3:
785 			case IWN_SDID_6x00_6:
786 			case IWN_SDID_6x00_9:
787 				////iwl6000i_2agn
788 			case IWN_SDID_6x00_4:
789 			case IWN_SDID_6x00_7:
790 			case IWN_SDID_6x00_10:
791 				//iwl6000i_2abg_cfg
792 			case IWN_SDID_6x00_5:
793 				//iwl6000i_2bg_cfg
794 				sc->base_params = &iwn_6000i_base_params;
795 				sc->sc_flags |= IWN_FLAG_INTERNAL_PA;
796 				sc->txchainmask = IWN_ANT_BC;
797 				sc->rxchainmask = IWN_ANT_BC;
798 				break;
799 			default:
800 				device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
801 				    "0x%04x rev %d not supported (subdevice)\n", pid,
802 				    sc->subdevice_id,sc->hw_type);
803 				return ENOTSUP;
804 		}
805 		break;
806 /* 6x05 Series */
807 	case IWN_DID_6x05_1:
808 	case IWN_DID_6x05_2:
809 		switch(sc->subdevice_id) {
810 			case IWN_SDID_6x05_1:
811 			case IWN_SDID_6x05_4:
812 			case IWN_SDID_6x05_6:
813 				//iwl6005_2agn_cfg
814 			case IWN_SDID_6x05_2:
815 			case IWN_SDID_6x05_5:
816 			case IWN_SDID_6x05_7:
817 				//iwl6005_2abg_cfg
818 			case IWN_SDID_6x05_3:
819 				//iwl6005_2bg_cfg
820 			case IWN_SDID_6x05_8:
821 			case IWN_SDID_6x05_9:
822 				//iwl6005_2agn_sff_cfg
823 			case IWN_SDID_6x05_10:
824 				//iwl6005_2agn_d_cfg
825 			case IWN_SDID_6x05_11:
826 				//iwl6005_2agn_mow1_cfg
827 			case IWN_SDID_6x05_12:
828 				//iwl6005_2agn_mow2_cfg
829 				sc->fwname = "iwn6000g2afw";
830 				sc->limits = &iwn6000_sensitivity_limits;
831 				sc->base_params = &iwn_6000g2_base_params;
832 				break;
833 			default:
834 				device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
835 				    "0x%04x rev %d not supported (subdevice)\n", pid,
836 				    sc->subdevice_id,sc->hw_type);
837 				return ENOTSUP;
838 		}
839 		break;
840 /* 6x35 Series */
841 	case IWN_DID_6035_1:
842 	case IWN_DID_6035_2:
843 		switch(sc->subdevice_id) {
844 			case IWN_SDID_6035_1:
845 			case IWN_SDID_6035_2:
846 			case IWN_SDID_6035_3:
847 			case IWN_SDID_6035_4:
848 				sc->fwname = "iwn6000g2bfw";
849 				sc->limits = &iwn6235_sensitivity_limits;
850 				sc->base_params = &iwn_6235_base_params;
851 				break;
852 			default:
853 				device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
854 				    "0x%04x rev %d not supported (subdevice)\n", pid,
855 				    sc->subdevice_id,sc->hw_type);
856 				return ENOTSUP;
857 		}
858 		break;
859 /* 6x50 WiFi/WiMax Series */
860 	case IWN_DID_6050_1:
861 	case IWN_DID_6050_2:
862 		switch(sc->subdevice_id) {
863 			case IWN_SDID_6050_1:
864 			case IWN_SDID_6050_3:
865 			case IWN_SDID_6050_5:
866 				//iwl6050_2agn_cfg
867 			case IWN_SDID_6050_2:
868 			case IWN_SDID_6050_4:
869 			case IWN_SDID_6050_6:
870 				//iwl6050_2abg_cfg
871 				sc->fwname = "iwn6050fw";
872 				sc->txchainmask = IWN_ANT_AB;
873 				sc->rxchainmask = IWN_ANT_AB;
874 				sc->limits = &iwn6000_sensitivity_limits;
875 				sc->base_params = &iwn_6050_base_params;
876 				break;
877 			default:
878 				device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
879 				    "0x%04x rev %d not supported (subdevice)\n", pid,
880 				    sc->subdevice_id,sc->hw_type);
881 				return ENOTSUP;
882 		}
883 		break;
884 /* 6150 WiFi/WiMax Series */
885 	case IWN_DID_6150_1:
886 	case IWN_DID_6150_2:
887 		switch(sc->subdevice_id) {
888 			case IWN_SDID_6150_1:
889 			case IWN_SDID_6150_3:
890 			case IWN_SDID_6150_5:
891 				// iwl6150_bgn_cfg
892 			case IWN_SDID_6150_2:
893 			case IWN_SDID_6150_4:
894 			case IWN_SDID_6150_6:
895 				//iwl6150_bg_cfg
896 				sc->fwname = "iwn6050fw";
897 				sc->limits = &iwn6000_sensitivity_limits;
898 				sc->base_params = &iwn_6150_base_params;
899 				break;
900 			default:
901 				device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
902 				    "0x%04x rev %d not supported (subdevice)\n", pid,
903 				    sc->subdevice_id,sc->hw_type);
904 				return ENOTSUP;
905 		}
906 		break;
907 /* 6030 Series and 1030 Series */
908 	case IWN_DID_x030_1:
909 	case IWN_DID_x030_2:
910 	case IWN_DID_x030_3:
911 	case IWN_DID_x030_4:
912 		switch(sc->subdevice_id) {
913 			case IWN_SDID_x030_1:
914 			case IWN_SDID_x030_3:
915 			case IWN_SDID_x030_5:
916 			// iwl1030_bgn_cfg
917 			case IWN_SDID_x030_2:
918 			case IWN_SDID_x030_4:
919 			case IWN_SDID_x030_6:
920 			//iwl1030_bg_cfg
921 			case IWN_SDID_x030_7:
922 			case IWN_SDID_x030_10:
923 			case IWN_SDID_x030_14:
924 			//iwl6030_2agn_cfg
925 			case IWN_SDID_x030_8:
926 			case IWN_SDID_x030_11:
927 			case IWN_SDID_x030_15:
928 			// iwl6030_2bgn_cfg
929 			case IWN_SDID_x030_9:
930 			case IWN_SDID_x030_12:
931 			case IWN_SDID_x030_16:
932 			// iwl6030_2abg_cfg
933 			case IWN_SDID_x030_13:
934 			//iwl6030_2bg_cfg
935 				sc->fwname = "iwn6000g2bfw";
936 				sc->limits = &iwn6000_sensitivity_limits;
937 				sc->base_params = &iwn_6000g2b_base_params;
938 				break;
939 			default:
940 				device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
941 				    "0x%04x rev %d not supported (subdevice)\n", pid,
942 				    sc->subdevice_id,sc->hw_type);
943 				return ENOTSUP;
944 		}
945 		break;
946 /* 130 Series WiFi */
947 /* XXX: This series will need adjustment for rate.
948  * see rx_with_siso_diversity in linux kernel
949  */
950 	case IWN_DID_130_1:
951 	case IWN_DID_130_2:
952 		switch(sc->subdevice_id) {
953 			case IWN_SDID_130_1:
954 			case IWN_SDID_130_3:
955 			case IWN_SDID_130_5:
956 			//iwl130_bgn_cfg
957 			case IWN_SDID_130_2:
958 			case IWN_SDID_130_4:
959 			case IWN_SDID_130_6:
960 			//iwl130_bg_cfg
961 				sc->fwname = "iwn6000g2bfw";
962 				sc->limits = &iwn6000_sensitivity_limits;
963 				sc->base_params = &iwn_6000g2b_base_params;
964 				break;
965 			default:
966 				device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
967 				    "0x%04x rev %d not supported (subdevice)\n", pid,
968 				    sc->subdevice_id,sc->hw_type);
969 				return ENOTSUP;
970 		}
971 		break;
972 /* 100 Series WiFi */
973 	case IWN_DID_100_1:
974 	case IWN_DID_100_2:
975 		switch(sc->subdevice_id) {
976 			case IWN_SDID_100_1:
977 			case IWN_SDID_100_2:
978 			case IWN_SDID_100_3:
979 			case IWN_SDID_100_4:
980 			case IWN_SDID_100_5:
981 			case IWN_SDID_100_6:
982 				sc->limits = &iwn1000_sensitivity_limits;
983 				sc->base_params = &iwn1000_base_params;
984 				sc->fwname = "iwn100fw";
985 				break;
986 			default:
987 				device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
988 				    "0x%04x rev %d not supported (subdevice)\n", pid,
989 				    sc->subdevice_id,sc->hw_type);
990 				return ENOTSUP;
991 		}
992 		break;
993 
994 /* 105 Series */
995 /* XXX: This series will need adjustment for rate.
996  * see rx_with_siso_diversity in linux kernel
997  */
998 	case IWN_DID_105_1:
999 	case IWN_DID_105_2:
1000 		switch(sc->subdevice_id) {
1001 			case IWN_SDID_105_1:
1002 			case IWN_SDID_105_2:
1003 			case IWN_SDID_105_3:
1004 			//iwl105_bgn_cfg
1005 			case IWN_SDID_105_4:
1006 			//iwl105_bgn_d_cfg
1007 				sc->limits = &iwn2030_sensitivity_limits;
1008 				sc->base_params = &iwn2000_base_params;
1009 				sc->fwname = "iwn105fw";
1010 				break;
1011 			default:
1012 				device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
1013 				    "0x%04x rev %d not supported (subdevice)\n", pid,
1014 				    sc->subdevice_id,sc->hw_type);
1015 				return ENOTSUP;
1016 		}
1017 		break;
1018 
1019 /* 135 Series */
1020 /* XXX: This series will need adjustment for rate.
1021  * see rx_with_siso_diversity in linux kernel
1022  */
1023 	case IWN_DID_135_1:
1024 	case IWN_DID_135_2:
1025 		switch(sc->subdevice_id) {
1026 			case IWN_SDID_135_1:
1027 			case IWN_SDID_135_2:
1028 			case IWN_SDID_135_3:
1029 				sc->limits = &iwn2030_sensitivity_limits;
1030 				sc->base_params = &iwn2030_base_params;
1031 				sc->fwname = "iwn135fw";
1032 				break;
1033 			default:
1034 				device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
1035 				    "0x%04x rev %d not supported (subdevice)\n", pid,
1036 				    sc->subdevice_id,sc->hw_type);
1037 				return ENOTSUP;
1038 		}
1039 		break;
1040 
1041 /* 2x00 Series */
1042 	case IWN_DID_2x00_1:
1043 	case IWN_DID_2x00_2:
1044 		switch(sc->subdevice_id) {
1045 			case IWN_SDID_2x00_1:
1046 			case IWN_SDID_2x00_2:
1047 			case IWN_SDID_2x00_3:
1048 			//iwl2000_2bgn_cfg
1049 			case IWN_SDID_2x00_4:
1050 			//iwl2000_2bgn_d_cfg
1051 				sc->limits = &iwn2030_sensitivity_limits;
1052 				sc->base_params = &iwn2000_base_params;
1053 				sc->fwname = "iwn2000fw";
1054 				break;
1055 			default:
1056 				device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
1057 				    "0x%04x rev %d not supported (subdevice) \n",
1058 				    pid, sc->subdevice_id, sc->hw_type);
1059 				return ENOTSUP;
1060 		}
1061 		break;
1062 /* 2x30 Series */
1063 	case IWN_DID_2x30_1:
1064 	case IWN_DID_2x30_2:
1065 		switch(sc->subdevice_id) {
1066 			case IWN_SDID_2x30_1:
1067 			case IWN_SDID_2x30_3:
1068 			case IWN_SDID_2x30_5:
1069 			//iwl100_bgn_cfg
1070 			case IWN_SDID_2x30_2:
1071 			case IWN_SDID_2x30_4:
1072 			case IWN_SDID_2x30_6:
1073 			//iwl100_bg_cfg
1074 				sc->limits = &iwn2030_sensitivity_limits;
1075 				sc->base_params = &iwn2030_base_params;
1076 				sc->fwname = "iwn2030fw";
1077 				break;
1078 			default:
1079 				device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
1080 				    "0x%04x rev %d not supported (subdevice)\n", pid,
1081 				    sc->subdevice_id,sc->hw_type);
1082 				return ENOTSUP;
1083 		}
1084 		break;
1085 /* 5x00 Series */
1086 	case IWN_DID_5x00_1:
1087 	case IWN_DID_5x00_2:
1088 	case IWN_DID_5x00_3:
1089 	case IWN_DID_5x00_4:
1090 		sc->limits = &iwn5000_sensitivity_limits;
1091 		sc->base_params = &iwn5000_base_params;
1092 		sc->fwname = "iwn5000fw";
1093 		switch(sc->subdevice_id) {
1094 			case IWN_SDID_5x00_1:
1095 			case IWN_SDID_5x00_2:
1096 			case IWN_SDID_5x00_3:
1097 			case IWN_SDID_5x00_4:
1098 			case IWN_SDID_5x00_9:
1099 			case IWN_SDID_5x00_10:
1100 			case IWN_SDID_5x00_11:
1101 			case IWN_SDID_5x00_12:
1102 			case IWN_SDID_5x00_17:
1103 			case IWN_SDID_5x00_18:
1104 			case IWN_SDID_5x00_19:
1105 			case IWN_SDID_5x00_20:
1106 			//iwl5100_agn_cfg
1107 				sc->txchainmask = IWN_ANT_B;
1108 				sc->rxchainmask = IWN_ANT_AB;
1109 				break;
1110 			case IWN_SDID_5x00_5:
1111 			case IWN_SDID_5x00_6:
1112 			case IWN_SDID_5x00_13:
1113 			case IWN_SDID_5x00_14:
1114 			case IWN_SDID_5x00_21:
1115 			case IWN_SDID_5x00_22:
1116 			//iwl5100_bgn_cfg
1117 				sc->txchainmask = IWN_ANT_B;
1118 				sc->rxchainmask = IWN_ANT_AB;
1119 				break;
1120 			case IWN_SDID_5x00_7:
1121 			case IWN_SDID_5x00_8:
1122 			case IWN_SDID_5x00_15:
1123 			case IWN_SDID_5x00_16:
1124 			case IWN_SDID_5x00_23:
1125 			case IWN_SDID_5x00_24:
1126 			//iwl5100_abg_cfg
1127 				sc->txchainmask = IWN_ANT_B;
1128 				sc->rxchainmask = IWN_ANT_AB;
1129 				break;
1130 			case IWN_SDID_5x00_25:
1131 			case IWN_SDID_5x00_26:
1132 			case IWN_SDID_5x00_27:
1133 			case IWN_SDID_5x00_28:
1134 			case IWN_SDID_5x00_29:
1135 			case IWN_SDID_5x00_30:
1136 			case IWN_SDID_5x00_31:
1137 			case IWN_SDID_5x00_32:
1138 			case IWN_SDID_5x00_33:
1139 			case IWN_SDID_5x00_34:
1140 			case IWN_SDID_5x00_35:
1141 			case IWN_SDID_5x00_36:
1142 			//iwl5300_agn_cfg
1143 				sc->txchainmask = IWN_ANT_ABC;
1144 				sc->rxchainmask = IWN_ANT_ABC;
1145 				break;
1146 			default:
1147 				device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
1148 				    "0x%04x rev %d not supported (subdevice)\n", pid,
1149 				    sc->subdevice_id,sc->hw_type);
1150 				return ENOTSUP;
1151 		}
1152 		break;
1153 /* 5x50 Series */
1154 	case IWN_DID_5x50_1:
1155 	case IWN_DID_5x50_2:
1156 	case IWN_DID_5x50_3:
1157 	case IWN_DID_5x50_4:
1158 		sc->limits = &iwn5000_sensitivity_limits;
1159 		sc->base_params = &iwn5000_base_params;
1160 		sc->fwname = "iwn5000fw";
1161 		switch(sc->subdevice_id) {
1162 			case IWN_SDID_5x50_1:
1163 			case IWN_SDID_5x50_2:
1164 			case IWN_SDID_5x50_3:
1165 			//iwl5350_agn_cfg
1166 				sc->limits = &iwn5000_sensitivity_limits;
1167 				sc->base_params = &iwn5000_base_params;
1168 				sc->fwname = "iwn5000fw";
1169 				break;
1170 			case IWN_SDID_5x50_4:
1171 			case IWN_SDID_5x50_5:
1172 			case IWN_SDID_5x50_8:
1173 			case IWN_SDID_5x50_9:
1174 			case IWN_SDID_5x50_10:
1175 			case IWN_SDID_5x50_11:
1176 			//iwl5150_agn_cfg
1177 			case IWN_SDID_5x50_6:
1178 			case IWN_SDID_5x50_7:
1179 			case IWN_SDID_5x50_12:
1180 			case IWN_SDID_5x50_13:
1181 			//iwl5150_abg_cfg
1182 				sc->limits = &iwn5000_sensitivity_limits;
1183 				sc->fwname = "iwn5150fw";
1184 				sc->base_params = &iwn_5x50_base_params;
1185 				break;
1186 			default:
1187 				device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id :"
1188 				    "0x%04x rev %d not supported (subdevice)\n", pid,
1189 				    sc->subdevice_id,sc->hw_type);
1190 				return ENOTSUP;
1191 		}
1192 		break;
1193 	default:
1194 		device_printf(sc->sc_dev, "adapter type id : 0x%04x sub id : 0x%04x"
1195 		    "rev 0x%08x not supported (device)\n", pid, sc->subdevice_id,
1196 		     sc->hw_type);
1197 		return ENOTSUP;
1198 	}
1199 	return 0;
1200 }
1201 
1202 static int
1203 iwn4965_attach(struct iwn_softc *sc, uint16_t pid)
1204 {
1205 	struct iwn_ops *ops = &sc->ops;
1206 
1207 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
1208 	ops->load_firmware = iwn4965_load_firmware;
1209 	ops->read_eeprom = iwn4965_read_eeprom;
1210 	ops->post_alive = iwn4965_post_alive;
1211 	ops->nic_config = iwn4965_nic_config;
1212 	ops->update_sched = iwn4965_update_sched;
1213 	ops->get_temperature = iwn4965_get_temperature;
1214 	ops->get_rssi = iwn4965_get_rssi;
1215 	ops->set_txpower = iwn4965_set_txpower;
1216 	ops->init_gains = iwn4965_init_gains;
1217 	ops->set_gains = iwn4965_set_gains;
1218 	ops->add_node = iwn4965_add_node;
1219 	ops->tx_done = iwn4965_tx_done;
1220 	ops->ampdu_tx_start = iwn4965_ampdu_tx_start;
1221 	ops->ampdu_tx_stop = iwn4965_ampdu_tx_stop;
1222 	sc->ntxqs = IWN4965_NTXQUEUES;
1223 	sc->firstaggqueue = IWN4965_FIRSTAGGQUEUE;
1224 	sc->ndmachnls = IWN4965_NDMACHNLS;
1225 	sc->broadcast_id = IWN4965_ID_BROADCAST;
1226 	sc->rxonsz = IWN4965_RXONSZ;
1227 	sc->schedsz = IWN4965_SCHEDSZ;
1228 	sc->fw_text_maxsz = IWN4965_FW_TEXT_MAXSZ;
1229 	sc->fw_data_maxsz = IWN4965_FW_DATA_MAXSZ;
1230 	sc->fwsz = IWN4965_FWSZ;
1231 	sc->sched_txfact_addr = IWN4965_SCHED_TXFACT;
1232 	sc->limits = &iwn4965_sensitivity_limits;
1233 	sc->fwname = "iwn4965fw";
1234 	/* Override chains masks, ROM is known to be broken. */
1235 	sc->txchainmask = IWN_ANT_AB;
1236 	sc->rxchainmask = IWN_ANT_ABC;
1237 	/* Enable normal btcoex */
1238 	sc->sc_flags |= IWN_FLAG_BTCOEX;
1239 
1240 	DPRINTF(sc, IWN_DEBUG_TRACE, "%s: end\n",__func__);
1241 
1242 	return 0;
1243 }
1244 
1245 static int
1246 iwn5000_attach(struct iwn_softc *sc, uint16_t pid)
1247 {
1248 	struct iwn_ops *ops = &sc->ops;
1249 
1250 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
1251 
1252 	ops->load_firmware = iwn5000_load_firmware;
1253 	ops->read_eeprom = iwn5000_read_eeprom;
1254 	ops->post_alive = iwn5000_post_alive;
1255 	ops->nic_config = iwn5000_nic_config;
1256 	ops->update_sched = iwn5000_update_sched;
1257 	ops->get_temperature = iwn5000_get_temperature;
1258 	ops->get_rssi = iwn5000_get_rssi;
1259 	ops->set_txpower = iwn5000_set_txpower;
1260 	ops->init_gains = iwn5000_init_gains;
1261 	ops->set_gains = iwn5000_set_gains;
1262 	ops->add_node = iwn5000_add_node;
1263 	ops->tx_done = iwn5000_tx_done;
1264 	ops->ampdu_tx_start = iwn5000_ampdu_tx_start;
1265 	ops->ampdu_tx_stop = iwn5000_ampdu_tx_stop;
1266 	sc->ntxqs = IWN5000_NTXQUEUES;
1267 	sc->firstaggqueue = IWN5000_FIRSTAGGQUEUE;
1268 	sc->ndmachnls = IWN5000_NDMACHNLS;
1269 	sc->broadcast_id = IWN5000_ID_BROADCAST;
1270 	sc->rxonsz = IWN5000_RXONSZ;
1271 	sc->schedsz = IWN5000_SCHEDSZ;
1272 	sc->fw_text_maxsz = IWN5000_FW_TEXT_MAXSZ;
1273 	sc->fw_data_maxsz = IWN5000_FW_DATA_MAXSZ;
1274 	sc->fwsz = IWN5000_FWSZ;
1275 	sc->sched_txfact_addr = IWN5000_SCHED_TXFACT;
1276 	sc->reset_noise_gain = IWN5000_PHY_CALIB_RESET_NOISE_GAIN;
1277 	sc->noise_gain = IWN5000_PHY_CALIB_NOISE_GAIN;
1278 
1279 	return 0;
1280 }
1281 
1282 /*
1283  * Attach the interface to 802.11 radiotap.
1284  */
1285 static void
1286 iwn_radiotap_attach(struct iwn_softc *sc)
1287 {
1288 	struct ifnet *ifp = sc->sc_ifp;
1289 	struct ieee80211com *ic = ifp->if_l2com;
1290 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
1291 	ieee80211_radiotap_attach(ic,
1292 	    &sc->sc_txtap.wt_ihdr, sizeof(sc->sc_txtap),
1293 		IWN_TX_RADIOTAP_PRESENT,
1294 	    &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap),
1295 		IWN_RX_RADIOTAP_PRESENT);
1296 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
1297 }
1298 
1299 static void
1300 iwn_sysctlattach(struct iwn_softc *sc)
1301 {
1302 #ifdef	IWN_DEBUG
1303 	struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->sc_dev);
1304 	struct sysctl_oid *tree = device_get_sysctl_tree(sc->sc_dev);
1305 
1306 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
1307 	    "debug", CTLFLAG_RW, &sc->sc_debug, sc->sc_debug,
1308 		"control debugging printfs");
1309 #endif
1310 }
1311 
1312 static struct ieee80211vap *
1313 iwn_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
1314     enum ieee80211_opmode opmode, int flags,
1315     const uint8_t bssid[IEEE80211_ADDR_LEN],
1316     const uint8_t mac[IEEE80211_ADDR_LEN])
1317 {
1318 	struct iwn_vap *ivp;
1319 	struct ieee80211vap *vap;
1320 	uint8_t mac1[IEEE80211_ADDR_LEN];
1321 	struct iwn_softc *sc = ic->ic_ifp->if_softc;
1322 
1323 	if (!TAILQ_EMPTY(&ic->ic_vaps))		/* only one at a time */
1324 		return NULL;
1325 
1326 	IEEE80211_ADDR_COPY(mac1, mac);
1327 
1328 	ivp = (struct iwn_vap *) malloc(sizeof(struct iwn_vap),
1329 	    M_80211_VAP, M_NOWAIT | M_ZERO);
1330 	if (ivp == NULL)
1331 		return NULL;
1332 	vap = &ivp->iv_vap;
1333 	ieee80211_vap_setup(ic, vap, name, unit, opmode, flags, bssid, mac1);
1334 	ivp->ctx = IWN_RXON_BSS_CTX;
1335 	IEEE80211_ADDR_COPY(ivp->macaddr, mac1);
1336 	vap->iv_bmissthreshold = 10;		/* override default */
1337 	/* Override with driver methods. */
1338 	ivp->iv_newstate = vap->iv_newstate;
1339 	vap->iv_newstate = iwn_newstate;
1340 	sc->ivap[IWN_RXON_BSS_CTX] = vap;
1341 
1342 	ieee80211_ratectl_init(vap);
1343 	/* Complete setup. */
1344 	ieee80211_vap_attach(vap, iwn_media_change, ieee80211_media_status);
1345 	ic->ic_opmode = opmode;
1346 	return vap;
1347 }
1348 
1349 static void
1350 iwn_vap_delete(struct ieee80211vap *vap)
1351 {
1352 	struct iwn_vap *ivp = IWN_VAP(vap);
1353 
1354 	ieee80211_ratectl_deinit(vap);
1355 	ieee80211_vap_detach(vap);
1356 	free(ivp, M_80211_VAP);
1357 }
1358 
1359 static int
1360 iwn_detach(device_t dev)
1361 {
1362 	struct iwn_softc *sc = device_get_softc(dev);
1363 	struct ifnet *ifp = sc->sc_ifp;
1364 	struct ieee80211com *ic;
1365 	int qid;
1366 
1367 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
1368 
1369 	if (ifp != NULL) {
1370 		ic = ifp->if_l2com;
1371 
1372 		ieee80211_draintask(ic, &sc->sc_reinit_task);
1373 		ieee80211_draintask(ic, &sc->sc_radioon_task);
1374 		ieee80211_draintask(ic, &sc->sc_radiooff_task);
1375 
1376 		iwn_stop(sc);
1377 
1378 		taskqueue_drain_all(sc->sc_tq);
1379 		taskqueue_free(sc->sc_tq);
1380 
1381 		callout_drain(&sc->watchdog_to);
1382 		callout_drain(&sc->calib_to);
1383 		ieee80211_ifdetach(ic);
1384 	}
1385 
1386 	/* Uninstall interrupt handler. */
1387 	if (sc->irq != NULL) {
1388 		bus_teardown_intr(dev, sc->irq, sc->sc_ih);
1389 		bus_release_resource(dev, SYS_RES_IRQ, rman_get_rid(sc->irq),
1390 		    sc->irq);
1391 		pci_release_msi(dev);
1392 	}
1393 
1394 	/* Free DMA resources. */
1395 	iwn_free_rx_ring(sc, &sc->rxq);
1396 	for (qid = 0; qid < sc->ntxqs; qid++)
1397 		iwn_free_tx_ring(sc, &sc->txq[qid]);
1398 	iwn_free_sched(sc);
1399 	iwn_free_kw(sc);
1400 	if (sc->ict != NULL)
1401 		iwn_free_ict(sc);
1402 	iwn_free_fwmem(sc);
1403 
1404 	if (sc->mem != NULL)
1405 		bus_release_resource(dev, SYS_RES_MEMORY,
1406 		    rman_get_rid(sc->mem), sc->mem);
1407 
1408 	if (ifp != NULL)
1409 		if_free(ifp);
1410 
1411 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n", __func__);
1412 	IWN_LOCK_DESTROY(sc);
1413 	return 0;
1414 }
1415 
1416 static int
1417 iwn_shutdown(device_t dev)
1418 {
1419 	struct iwn_softc *sc = device_get_softc(dev);
1420 
1421 	iwn_stop(sc);
1422 	return 0;
1423 }
1424 
1425 static int
1426 iwn_suspend(device_t dev)
1427 {
1428 	struct iwn_softc *sc = device_get_softc(dev);
1429 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
1430 
1431 	ieee80211_suspend_all(ic);
1432 	return 0;
1433 }
1434 
1435 static int
1436 iwn_resume(device_t dev)
1437 {
1438 	struct iwn_softc *sc = device_get_softc(dev);
1439 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
1440 
1441 	/* Clear device-specific "PCI retry timeout" register (41h). */
1442 	pci_write_config(dev, 0x41, 0, 1);
1443 
1444 	ieee80211_resume_all(ic);
1445 	return 0;
1446 }
1447 
1448 static int
1449 iwn_nic_lock(struct iwn_softc *sc)
1450 {
1451 	int ntries;
1452 
1453 	/* Request exclusive access to NIC. */
1454 	IWN_SETBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_MAC_ACCESS_REQ);
1455 
1456 	/* Spin until we actually get the lock. */
1457 	for (ntries = 0; ntries < 1000; ntries++) {
1458 		if ((IWN_READ(sc, IWN_GP_CNTRL) &
1459 		     (IWN_GP_CNTRL_MAC_ACCESS_ENA | IWN_GP_CNTRL_SLEEP)) ==
1460 		    IWN_GP_CNTRL_MAC_ACCESS_ENA)
1461 			return 0;
1462 		DELAY(10);
1463 	}
1464 	return ETIMEDOUT;
1465 }
1466 
1467 static __inline void
1468 iwn_nic_unlock(struct iwn_softc *sc)
1469 {
1470 	IWN_CLRBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_MAC_ACCESS_REQ);
1471 }
1472 
1473 static __inline uint32_t
1474 iwn_prph_read(struct iwn_softc *sc, uint32_t addr)
1475 {
1476 	IWN_WRITE(sc, IWN_PRPH_RADDR, IWN_PRPH_DWORD | addr);
1477 	IWN_BARRIER_READ_WRITE(sc);
1478 	return IWN_READ(sc, IWN_PRPH_RDATA);
1479 }
1480 
1481 static __inline void
1482 iwn_prph_write(struct iwn_softc *sc, uint32_t addr, uint32_t data)
1483 {
1484 	IWN_WRITE(sc, IWN_PRPH_WADDR, IWN_PRPH_DWORD | addr);
1485 	IWN_BARRIER_WRITE(sc);
1486 	IWN_WRITE(sc, IWN_PRPH_WDATA, data);
1487 }
1488 
1489 static __inline void
1490 iwn_prph_setbits(struct iwn_softc *sc, uint32_t addr, uint32_t mask)
1491 {
1492 	iwn_prph_write(sc, addr, iwn_prph_read(sc, addr) | mask);
1493 }
1494 
1495 static __inline void
1496 iwn_prph_clrbits(struct iwn_softc *sc, uint32_t addr, uint32_t mask)
1497 {
1498 	iwn_prph_write(sc, addr, iwn_prph_read(sc, addr) & ~mask);
1499 }
1500 
1501 static __inline void
1502 iwn_prph_write_region_4(struct iwn_softc *sc, uint32_t addr,
1503     const uint32_t *data, int count)
1504 {
1505 	for (; count > 0; count--, data++, addr += 4)
1506 		iwn_prph_write(sc, addr, *data);
1507 }
1508 
1509 static __inline uint32_t
1510 iwn_mem_read(struct iwn_softc *sc, uint32_t addr)
1511 {
1512 	IWN_WRITE(sc, IWN_MEM_RADDR, addr);
1513 	IWN_BARRIER_READ_WRITE(sc);
1514 	return IWN_READ(sc, IWN_MEM_RDATA);
1515 }
1516 
1517 static __inline void
1518 iwn_mem_write(struct iwn_softc *sc, uint32_t addr, uint32_t data)
1519 {
1520 	IWN_WRITE(sc, IWN_MEM_WADDR, addr);
1521 	IWN_BARRIER_WRITE(sc);
1522 	IWN_WRITE(sc, IWN_MEM_WDATA, data);
1523 }
1524 
1525 static __inline void
1526 iwn_mem_write_2(struct iwn_softc *sc, uint32_t addr, uint16_t data)
1527 {
1528 	uint32_t tmp;
1529 
1530 	tmp = iwn_mem_read(sc, addr & ~3);
1531 	if (addr & 3)
1532 		tmp = (tmp & 0x0000ffff) | data << 16;
1533 	else
1534 		tmp = (tmp & 0xffff0000) | data;
1535 	iwn_mem_write(sc, addr & ~3, tmp);
1536 }
1537 
1538 static __inline void
1539 iwn_mem_read_region_4(struct iwn_softc *sc, uint32_t addr, uint32_t *data,
1540     int count)
1541 {
1542 	for (; count > 0; count--, addr += 4)
1543 		*data++ = iwn_mem_read(sc, addr);
1544 }
1545 
1546 static __inline void
1547 iwn_mem_set_region_4(struct iwn_softc *sc, uint32_t addr, uint32_t val,
1548     int count)
1549 {
1550 	for (; count > 0; count--, addr += 4)
1551 		iwn_mem_write(sc, addr, val);
1552 }
1553 
1554 static int
1555 iwn_eeprom_lock(struct iwn_softc *sc)
1556 {
1557 	int i, ntries;
1558 
1559 	for (i = 0; i < 100; i++) {
1560 		/* Request exclusive access to EEPROM. */
1561 		IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
1562 		    IWN_HW_IF_CONFIG_EEPROM_LOCKED);
1563 
1564 		/* Spin until we actually get the lock. */
1565 		for (ntries = 0; ntries < 100; ntries++) {
1566 			if (IWN_READ(sc, IWN_HW_IF_CONFIG) &
1567 			    IWN_HW_IF_CONFIG_EEPROM_LOCKED)
1568 				return 0;
1569 			DELAY(10);
1570 		}
1571 	}
1572 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end timeout\n", __func__);
1573 	return ETIMEDOUT;
1574 }
1575 
1576 static __inline void
1577 iwn_eeprom_unlock(struct iwn_softc *sc)
1578 {
1579 	IWN_CLRBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_EEPROM_LOCKED);
1580 }
1581 
1582 /*
1583  * Initialize access by host to One Time Programmable ROM.
1584  * NB: This kind of ROM can be found on 1000 or 6000 Series only.
1585  */
1586 static int
1587 iwn_init_otprom(struct iwn_softc *sc)
1588 {
1589 	uint16_t prev, base, next;
1590 	int count, error;
1591 
1592 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
1593 
1594 	/* Wait for clock stabilization before accessing prph. */
1595 	if ((error = iwn_clock_wait(sc)) != 0)
1596 		return error;
1597 
1598 	if ((error = iwn_nic_lock(sc)) != 0)
1599 		return error;
1600 	iwn_prph_setbits(sc, IWN_APMG_PS, IWN_APMG_PS_RESET_REQ);
1601 	DELAY(5);
1602 	iwn_prph_clrbits(sc, IWN_APMG_PS, IWN_APMG_PS_RESET_REQ);
1603 	iwn_nic_unlock(sc);
1604 
1605 	/* Set auto clock gate disable bit for HW with OTP shadow RAM. */
1606 	if (sc->base_params->shadow_ram_support) {
1607 		IWN_SETBITS(sc, IWN_DBG_LINK_PWR_MGMT,
1608 		    IWN_RESET_LINK_PWR_MGMT_DIS);
1609 	}
1610 	IWN_CLRBITS(sc, IWN_EEPROM_GP, IWN_EEPROM_GP_IF_OWNER);
1611 	/* Clear ECC status. */
1612 	IWN_SETBITS(sc, IWN_OTP_GP,
1613 	    IWN_OTP_GP_ECC_CORR_STTS | IWN_OTP_GP_ECC_UNCORR_STTS);
1614 
1615 	/*
1616 	 * Find the block before last block (contains the EEPROM image)
1617 	 * for HW without OTP shadow RAM.
1618 	 */
1619 	if (! sc->base_params->shadow_ram_support) {
1620 		/* Switch to absolute addressing mode. */
1621 		IWN_CLRBITS(sc, IWN_OTP_GP, IWN_OTP_GP_RELATIVE_ACCESS);
1622 		base = prev = 0;
1623 		for (count = 0; count < sc->base_params->max_ll_items;
1624 		    count++) {
1625 			error = iwn_read_prom_data(sc, base, &next, 2);
1626 			if (error != 0)
1627 				return error;
1628 			if (next == 0)	/* End of linked-list. */
1629 				break;
1630 			prev = base;
1631 			base = le16toh(next);
1632 		}
1633 		if (count == 0 || count == sc->base_params->max_ll_items)
1634 			return EIO;
1635 		/* Skip "next" word. */
1636 		sc->prom_base = prev + 1;
1637 	}
1638 
1639 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
1640 
1641 	return 0;
1642 }
1643 
1644 static int
1645 iwn_read_prom_data(struct iwn_softc *sc, uint32_t addr, void *data, int count)
1646 {
1647 	uint8_t *out = data;
1648 	uint32_t val, tmp;
1649 	int ntries;
1650 
1651 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
1652 
1653 	addr += sc->prom_base;
1654 	for (; count > 0; count -= 2, addr++) {
1655 		IWN_WRITE(sc, IWN_EEPROM, addr << 2);
1656 		for (ntries = 0; ntries < 10; ntries++) {
1657 			val = IWN_READ(sc, IWN_EEPROM);
1658 			if (val & IWN_EEPROM_READ_VALID)
1659 				break;
1660 			DELAY(5);
1661 		}
1662 		if (ntries == 10) {
1663 			device_printf(sc->sc_dev,
1664 			    "timeout reading ROM at 0x%x\n", addr);
1665 			return ETIMEDOUT;
1666 		}
1667 		if (sc->sc_flags & IWN_FLAG_HAS_OTPROM) {
1668 			/* OTPROM, check for ECC errors. */
1669 			tmp = IWN_READ(sc, IWN_OTP_GP);
1670 			if (tmp & IWN_OTP_GP_ECC_UNCORR_STTS) {
1671 				device_printf(sc->sc_dev,
1672 				    "OTPROM ECC error at 0x%x\n", addr);
1673 				return EIO;
1674 			}
1675 			if (tmp & IWN_OTP_GP_ECC_CORR_STTS) {
1676 				/* Correctable ECC error, clear bit. */
1677 				IWN_SETBITS(sc, IWN_OTP_GP,
1678 				    IWN_OTP_GP_ECC_CORR_STTS);
1679 			}
1680 		}
1681 		*out++ = val >> 16;
1682 		if (count > 1)
1683 			*out++ = val >> 24;
1684 	}
1685 
1686 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
1687 
1688 	return 0;
1689 }
1690 
1691 static void
1692 iwn_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
1693 {
1694 	if (error != 0)
1695 		return;
1696 	KASSERT(nsegs == 1, ("too many DMA segments, %d should be 1", nsegs));
1697 	*(bus_addr_t *)arg = segs[0].ds_addr;
1698 }
1699 
1700 static int
1701 iwn_dma_contig_alloc(struct iwn_softc *sc, struct iwn_dma_info *dma,
1702     void **kvap, bus_size_t size, bus_size_t alignment)
1703 {
1704 	int error;
1705 
1706 	dma->tag = NULL;
1707 	dma->size = size;
1708 
1709 	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), alignment,
1710 	    0, BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, size,
1711 	    1, size, BUS_DMA_NOWAIT, NULL, NULL, &dma->tag);
1712 	if (error != 0)
1713 		goto fail;
1714 
1715 	error = bus_dmamem_alloc(dma->tag, (void **)&dma->vaddr,
1716 	    BUS_DMA_NOWAIT | BUS_DMA_ZERO | BUS_DMA_COHERENT, &dma->map);
1717 	if (error != 0)
1718 		goto fail;
1719 
1720 	error = bus_dmamap_load(dma->tag, dma->map, dma->vaddr, size,
1721 	    iwn_dma_map_addr, &dma->paddr, BUS_DMA_NOWAIT);
1722 	if (error != 0)
1723 		goto fail;
1724 
1725 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
1726 
1727 	if (kvap != NULL)
1728 		*kvap = dma->vaddr;
1729 
1730 	return 0;
1731 
1732 fail:	iwn_dma_contig_free(dma);
1733 	return error;
1734 }
1735 
1736 static void
1737 iwn_dma_contig_free(struct iwn_dma_info *dma)
1738 {
1739 	if (dma->vaddr != NULL) {
1740 		bus_dmamap_sync(dma->tag, dma->map,
1741 		    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
1742 		bus_dmamap_unload(dma->tag, dma->map);
1743 		bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
1744 		dma->vaddr = NULL;
1745 	}
1746 	if (dma->tag != NULL) {
1747 		bus_dma_tag_destroy(dma->tag);
1748 		dma->tag = NULL;
1749 	}
1750 }
1751 
1752 static int
1753 iwn_alloc_sched(struct iwn_softc *sc)
1754 {
1755 	/* TX scheduler rings must be aligned on a 1KB boundary. */
1756 	return iwn_dma_contig_alloc(sc, &sc->sched_dma, (void **)&sc->sched,
1757 	    sc->schedsz, 1024);
1758 }
1759 
1760 static void
1761 iwn_free_sched(struct iwn_softc *sc)
1762 {
1763 	iwn_dma_contig_free(&sc->sched_dma);
1764 }
1765 
1766 static int
1767 iwn_alloc_kw(struct iwn_softc *sc)
1768 {
1769 	/* "Keep Warm" page must be aligned on a 4KB boundary. */
1770 	return iwn_dma_contig_alloc(sc, &sc->kw_dma, NULL, 4096, 4096);
1771 }
1772 
1773 static void
1774 iwn_free_kw(struct iwn_softc *sc)
1775 {
1776 	iwn_dma_contig_free(&sc->kw_dma);
1777 }
1778 
1779 static int
1780 iwn_alloc_ict(struct iwn_softc *sc)
1781 {
1782 	/* ICT table must be aligned on a 4KB boundary. */
1783 	return iwn_dma_contig_alloc(sc, &sc->ict_dma, (void **)&sc->ict,
1784 	    IWN_ICT_SIZE, 4096);
1785 }
1786 
1787 static void
1788 iwn_free_ict(struct iwn_softc *sc)
1789 {
1790 	iwn_dma_contig_free(&sc->ict_dma);
1791 }
1792 
1793 static int
1794 iwn_alloc_fwmem(struct iwn_softc *sc)
1795 {
1796 	/* Must be aligned on a 16-byte boundary. */
1797 	return iwn_dma_contig_alloc(sc, &sc->fw_dma, NULL, sc->fwsz, 16);
1798 }
1799 
1800 static void
1801 iwn_free_fwmem(struct iwn_softc *sc)
1802 {
1803 	iwn_dma_contig_free(&sc->fw_dma);
1804 }
1805 
1806 static int
1807 iwn_alloc_rx_ring(struct iwn_softc *sc, struct iwn_rx_ring *ring)
1808 {
1809 	bus_size_t size;
1810 	int i, error;
1811 
1812 	ring->cur = 0;
1813 
1814 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
1815 
1816 	/* Allocate RX descriptors (256-byte aligned). */
1817 	size = IWN_RX_RING_COUNT * sizeof (uint32_t);
1818 	error = iwn_dma_contig_alloc(sc, &ring->desc_dma, (void **)&ring->desc,
1819 	    size, 256);
1820 	if (error != 0) {
1821 		device_printf(sc->sc_dev,
1822 		    "%s: could not allocate RX ring DMA memory, error %d\n",
1823 		    __func__, error);
1824 		goto fail;
1825 	}
1826 
1827 	/* Allocate RX status area (16-byte aligned). */
1828 	error = iwn_dma_contig_alloc(sc, &ring->stat_dma, (void **)&ring->stat,
1829 	    sizeof (struct iwn_rx_status), 16);
1830 	if (error != 0) {
1831 		device_printf(sc->sc_dev,
1832 		    "%s: could not allocate RX status DMA memory, error %d\n",
1833 		    __func__, error);
1834 		goto fail;
1835 	}
1836 
1837 	/* Create RX buffer DMA tag. */
1838 	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 1, 0,
1839 	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
1840 	    IWN_RBUF_SIZE, 1, IWN_RBUF_SIZE, BUS_DMA_NOWAIT, NULL, NULL,
1841 	    &ring->data_dmat);
1842 	if (error != 0) {
1843 		device_printf(sc->sc_dev,
1844 		    "%s: could not create RX buf DMA tag, error %d\n",
1845 		    __func__, error);
1846 		goto fail;
1847 	}
1848 
1849 	/*
1850 	 * Allocate and map RX buffers.
1851 	 */
1852 	for (i = 0; i < IWN_RX_RING_COUNT; i++) {
1853 		struct iwn_rx_data *data = &ring->data[i];
1854 		bus_addr_t paddr;
1855 
1856 		error = bus_dmamap_create(ring->data_dmat, 0, &data->map);
1857 		if (error != 0) {
1858 			device_printf(sc->sc_dev,
1859 			    "%s: could not create RX buf DMA map, error %d\n",
1860 			    __func__, error);
1861 			goto fail;
1862 		}
1863 
1864 		data->m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR,
1865 		    IWN_RBUF_SIZE);
1866 		if (data->m == NULL) {
1867 			device_printf(sc->sc_dev,
1868 			    "%s: could not allocate RX mbuf\n", __func__);
1869 			error = ENOBUFS;
1870 			goto fail;
1871 		}
1872 
1873 		error = bus_dmamap_load(ring->data_dmat, data->map,
1874 		    mtod(data->m, void *), IWN_RBUF_SIZE, iwn_dma_map_addr,
1875 		    &paddr, BUS_DMA_NOWAIT);
1876 		if (error != 0 && error != EFBIG) {
1877 			device_printf(sc->sc_dev,
1878 			    "%s: can't not map mbuf, error %d\n", __func__,
1879 			    error);
1880 			goto fail;
1881 		}
1882 
1883 		/* Set physical address of RX buffer (256-byte aligned). */
1884 		ring->desc[i] = htole32(paddr >> 8);
1885 	}
1886 
1887 	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
1888 	    BUS_DMASYNC_PREWRITE);
1889 
1890 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
1891 
1892 	return 0;
1893 
1894 fail:	iwn_free_rx_ring(sc, ring);
1895 
1896 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end in error\n",__func__);
1897 
1898 	return error;
1899 }
1900 
1901 static void
1902 iwn_reset_rx_ring(struct iwn_softc *sc, struct iwn_rx_ring *ring)
1903 {
1904 	int ntries;
1905 
1906 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
1907 
1908 	if (iwn_nic_lock(sc) == 0) {
1909 		IWN_WRITE(sc, IWN_FH_RX_CONFIG, 0);
1910 		for (ntries = 0; ntries < 1000; ntries++) {
1911 			if (IWN_READ(sc, IWN_FH_RX_STATUS) &
1912 			    IWN_FH_RX_STATUS_IDLE)
1913 				break;
1914 			DELAY(10);
1915 		}
1916 		iwn_nic_unlock(sc);
1917 	}
1918 	ring->cur = 0;
1919 	sc->last_rx_valid = 0;
1920 }
1921 
1922 static void
1923 iwn_free_rx_ring(struct iwn_softc *sc, struct iwn_rx_ring *ring)
1924 {
1925 	int i;
1926 
1927 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s \n", __func__);
1928 
1929 	iwn_dma_contig_free(&ring->desc_dma);
1930 	iwn_dma_contig_free(&ring->stat_dma);
1931 
1932 	for (i = 0; i < IWN_RX_RING_COUNT; i++) {
1933 		struct iwn_rx_data *data = &ring->data[i];
1934 
1935 		if (data->m != NULL) {
1936 			bus_dmamap_sync(ring->data_dmat, data->map,
1937 			    BUS_DMASYNC_POSTREAD);
1938 			bus_dmamap_unload(ring->data_dmat, data->map);
1939 			m_freem(data->m);
1940 			data->m = NULL;
1941 		}
1942 		if (data->map != NULL)
1943 			bus_dmamap_destroy(ring->data_dmat, data->map);
1944 	}
1945 	if (ring->data_dmat != NULL) {
1946 		bus_dma_tag_destroy(ring->data_dmat);
1947 		ring->data_dmat = NULL;
1948 	}
1949 }
1950 
1951 static int
1952 iwn_alloc_tx_ring(struct iwn_softc *sc, struct iwn_tx_ring *ring, int qid)
1953 {
1954 	bus_addr_t paddr;
1955 	bus_size_t size;
1956 	int i, error;
1957 
1958 	ring->qid = qid;
1959 	ring->queued = 0;
1960 	ring->cur = 0;
1961 
1962 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
1963 
1964 	/* Allocate TX descriptors (256-byte aligned). */
1965 	size = IWN_TX_RING_COUNT * sizeof (struct iwn_tx_desc);
1966 	error = iwn_dma_contig_alloc(sc, &ring->desc_dma, (void **)&ring->desc,
1967 	    size, 256);
1968 	if (error != 0) {
1969 		device_printf(sc->sc_dev,
1970 		    "%s: could not allocate TX ring DMA memory, error %d\n",
1971 		    __func__, error);
1972 		goto fail;
1973 	}
1974 
1975 	size = IWN_TX_RING_COUNT * sizeof (struct iwn_tx_cmd);
1976 	error = iwn_dma_contig_alloc(sc, &ring->cmd_dma, (void **)&ring->cmd,
1977 	    size, 4);
1978 	if (error != 0) {
1979 		device_printf(sc->sc_dev,
1980 		    "%s: could not allocate TX cmd DMA memory, error %d\n",
1981 		    __func__, error);
1982 		goto fail;
1983 	}
1984 
1985 	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 1, 0,
1986 	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES,
1987 	    IWN_MAX_SCATTER - 1, MCLBYTES, BUS_DMA_NOWAIT, NULL, NULL,
1988 	    &ring->data_dmat);
1989 	if (error != 0) {
1990 		device_printf(sc->sc_dev,
1991 		    "%s: could not create TX buf DMA tag, error %d\n",
1992 		    __func__, error);
1993 		goto fail;
1994 	}
1995 
1996 	paddr = ring->cmd_dma.paddr;
1997 	for (i = 0; i < IWN_TX_RING_COUNT; i++) {
1998 		struct iwn_tx_data *data = &ring->data[i];
1999 
2000 		data->cmd_paddr = paddr;
2001 		data->scratch_paddr = paddr + 12;
2002 		paddr += sizeof (struct iwn_tx_cmd);
2003 
2004 		error = bus_dmamap_create(ring->data_dmat, 0, &data->map);
2005 		if (error != 0) {
2006 			device_printf(sc->sc_dev,
2007 			    "%s: could not create TX buf DMA map, error %d\n",
2008 			    __func__, error);
2009 			goto fail;
2010 		}
2011 	}
2012 
2013 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
2014 
2015 	return 0;
2016 
2017 fail:	iwn_free_tx_ring(sc, ring);
2018 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end in error\n", __func__);
2019 	return error;
2020 }
2021 
2022 static void
2023 iwn_reset_tx_ring(struct iwn_softc *sc, struct iwn_tx_ring *ring)
2024 {
2025 	int i;
2026 
2027 	DPRINTF(sc, IWN_DEBUG_TRACE, "->doing %s \n", __func__);
2028 
2029 	for (i = 0; i < IWN_TX_RING_COUNT; i++) {
2030 		struct iwn_tx_data *data = &ring->data[i];
2031 
2032 		if (data->m != NULL) {
2033 			bus_dmamap_sync(ring->data_dmat, data->map,
2034 			    BUS_DMASYNC_POSTWRITE);
2035 			bus_dmamap_unload(ring->data_dmat, data->map);
2036 			m_freem(data->m);
2037 			data->m = NULL;
2038 		}
2039 	}
2040 	/* Clear TX descriptors. */
2041 	memset(ring->desc, 0, ring->desc_dma.size);
2042 	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
2043 	    BUS_DMASYNC_PREWRITE);
2044 	sc->qfullmsk &= ~(1 << ring->qid);
2045 	ring->queued = 0;
2046 	ring->cur = 0;
2047 }
2048 
2049 static void
2050 iwn_free_tx_ring(struct iwn_softc *sc, struct iwn_tx_ring *ring)
2051 {
2052 	int i;
2053 
2054 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s \n", __func__);
2055 
2056 	iwn_dma_contig_free(&ring->desc_dma);
2057 	iwn_dma_contig_free(&ring->cmd_dma);
2058 
2059 	for (i = 0; i < IWN_TX_RING_COUNT; i++) {
2060 		struct iwn_tx_data *data = &ring->data[i];
2061 
2062 		if (data->m != NULL) {
2063 			bus_dmamap_sync(ring->data_dmat, data->map,
2064 			    BUS_DMASYNC_POSTWRITE);
2065 			bus_dmamap_unload(ring->data_dmat, data->map);
2066 			m_freem(data->m);
2067 		}
2068 		if (data->map != NULL)
2069 			bus_dmamap_destroy(ring->data_dmat, data->map);
2070 	}
2071 	if (ring->data_dmat != NULL) {
2072 		bus_dma_tag_destroy(ring->data_dmat);
2073 		ring->data_dmat = NULL;
2074 	}
2075 }
2076 
2077 static void
2078 iwn5000_ict_reset(struct iwn_softc *sc)
2079 {
2080 	/* Disable interrupts. */
2081 	IWN_WRITE(sc, IWN_INT_MASK, 0);
2082 
2083 	/* Reset ICT table. */
2084 	memset(sc->ict, 0, IWN_ICT_SIZE);
2085 	sc->ict_cur = 0;
2086 
2087 	/* Set physical address of ICT table (4KB aligned). */
2088 	DPRINTF(sc, IWN_DEBUG_RESET, "%s: enabling ICT\n", __func__);
2089 	IWN_WRITE(sc, IWN_DRAM_INT_TBL, IWN_DRAM_INT_TBL_ENABLE |
2090 	    IWN_DRAM_INT_TBL_WRAP_CHECK | sc->ict_dma.paddr >> 12);
2091 
2092 	/* Enable periodic RX interrupt. */
2093 	sc->int_mask |= IWN_INT_RX_PERIODIC;
2094 	/* Switch to ICT interrupt mode in driver. */
2095 	sc->sc_flags |= IWN_FLAG_USE_ICT;
2096 
2097 	/* Re-enable interrupts. */
2098 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
2099 	IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
2100 }
2101 
2102 static int
2103 iwn_read_eeprom(struct iwn_softc *sc, uint8_t macaddr[IEEE80211_ADDR_LEN])
2104 {
2105 	struct iwn_ops *ops = &sc->ops;
2106 	uint16_t val;
2107 	int error;
2108 
2109 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
2110 
2111 	/* Check whether adapter has an EEPROM or an OTPROM. */
2112 	if (sc->hw_type >= IWN_HW_REV_TYPE_1000 &&
2113 	    (IWN_READ(sc, IWN_OTP_GP) & IWN_OTP_GP_DEV_SEL_OTP))
2114 		sc->sc_flags |= IWN_FLAG_HAS_OTPROM;
2115 	DPRINTF(sc, IWN_DEBUG_RESET, "%s found\n",
2116 	    (sc->sc_flags & IWN_FLAG_HAS_OTPROM) ? "OTPROM" : "EEPROM");
2117 
2118 	/* Adapter has to be powered on for EEPROM access to work. */
2119 	if ((error = iwn_apm_init(sc)) != 0) {
2120 		device_printf(sc->sc_dev,
2121 		    "%s: could not power ON adapter, error %d\n", __func__,
2122 		    error);
2123 		return error;
2124 	}
2125 
2126 	if ((IWN_READ(sc, IWN_EEPROM_GP) & 0x7) == 0) {
2127 		device_printf(sc->sc_dev, "%s: bad ROM signature\n", __func__);
2128 		return EIO;
2129 	}
2130 	if ((error = iwn_eeprom_lock(sc)) != 0) {
2131 		device_printf(sc->sc_dev, "%s: could not lock ROM, error %d\n",
2132 		    __func__, error);
2133 		return error;
2134 	}
2135 	if (sc->sc_flags & IWN_FLAG_HAS_OTPROM) {
2136 		if ((error = iwn_init_otprom(sc)) != 0) {
2137 			device_printf(sc->sc_dev,
2138 			    "%s: could not initialize OTPROM, error %d\n",
2139 			    __func__, error);
2140 			return error;
2141 		}
2142 	}
2143 
2144 	iwn_read_prom_data(sc, IWN_EEPROM_SKU_CAP, &val, 2);
2145 	DPRINTF(sc, IWN_DEBUG_RESET, "SKU capabilities=0x%04x\n", le16toh(val));
2146 	/* Check if HT support is bonded out. */
2147 	if (val & htole16(IWN_EEPROM_SKU_CAP_11N))
2148 		sc->sc_flags |= IWN_FLAG_HAS_11N;
2149 
2150 	iwn_read_prom_data(sc, IWN_EEPROM_RFCFG, &val, 2);
2151 	sc->rfcfg = le16toh(val);
2152 	DPRINTF(sc, IWN_DEBUG_RESET, "radio config=0x%04x\n", sc->rfcfg);
2153 	/* Read Tx/Rx chains from ROM unless it's known to be broken. */
2154 	if (sc->txchainmask == 0)
2155 		sc->txchainmask = IWN_RFCFG_TXANTMSK(sc->rfcfg);
2156 	if (sc->rxchainmask == 0)
2157 		sc->rxchainmask = IWN_RFCFG_RXANTMSK(sc->rfcfg);
2158 
2159 	/* Read MAC address. */
2160 	iwn_read_prom_data(sc, IWN_EEPROM_MAC, macaddr, 6);
2161 
2162 	/* Read adapter-specific information from EEPROM. */
2163 	ops->read_eeprom(sc);
2164 
2165 	iwn_apm_stop(sc);	/* Power OFF adapter. */
2166 
2167 	iwn_eeprom_unlock(sc);
2168 
2169 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
2170 
2171 	return 0;
2172 }
2173 
2174 static void
2175 iwn4965_read_eeprom(struct iwn_softc *sc)
2176 {
2177 	uint32_t addr;
2178 	uint16_t val;
2179 	int i;
2180 
2181 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
2182 
2183 	/* Read regulatory domain (4 ASCII characters). */
2184 	iwn_read_prom_data(sc, IWN4965_EEPROM_DOMAIN, sc->eeprom_domain, 4);
2185 
2186 	/* Read the list of authorized channels (20MHz ones only). */
2187 	for (i = 0; i < IWN_NBANDS - 1; i++) {
2188 		addr = iwn4965_regulatory_bands[i];
2189 		iwn_read_eeprom_channels(sc, i, addr);
2190 	}
2191 
2192 	/* Read maximum allowed TX power for 2GHz and 5GHz bands. */
2193 	iwn_read_prom_data(sc, IWN4965_EEPROM_MAXPOW, &val, 2);
2194 	sc->maxpwr2GHz = val & 0xff;
2195 	sc->maxpwr5GHz = val >> 8;
2196 	/* Check that EEPROM values are within valid range. */
2197 	if (sc->maxpwr5GHz < 20 || sc->maxpwr5GHz > 50)
2198 		sc->maxpwr5GHz = 38;
2199 	if (sc->maxpwr2GHz < 20 || sc->maxpwr2GHz > 50)
2200 		sc->maxpwr2GHz = 38;
2201 	DPRINTF(sc, IWN_DEBUG_RESET, "maxpwr 2GHz=%d 5GHz=%d\n",
2202 	    sc->maxpwr2GHz, sc->maxpwr5GHz);
2203 
2204 	/* Read samples for each TX power group. */
2205 	iwn_read_prom_data(sc, IWN4965_EEPROM_BANDS, sc->bands,
2206 	    sizeof sc->bands);
2207 
2208 	/* Read voltage at which samples were taken. */
2209 	iwn_read_prom_data(sc, IWN4965_EEPROM_VOLTAGE, &val, 2);
2210 	sc->eeprom_voltage = (int16_t)le16toh(val);
2211 	DPRINTF(sc, IWN_DEBUG_RESET, "voltage=%d (in 0.3V)\n",
2212 	    sc->eeprom_voltage);
2213 
2214 #ifdef IWN_DEBUG
2215 	/* Print samples. */
2216 	if (sc->sc_debug & IWN_DEBUG_ANY) {
2217 		for (i = 0; i < IWN_NBANDS - 1; i++)
2218 			iwn4965_print_power_group(sc, i);
2219 	}
2220 #endif
2221 
2222 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
2223 }
2224 
2225 #ifdef IWN_DEBUG
2226 static void
2227 iwn4965_print_power_group(struct iwn_softc *sc, int i)
2228 {
2229 	struct iwn4965_eeprom_band *band = &sc->bands[i];
2230 	struct iwn4965_eeprom_chan_samples *chans = band->chans;
2231 	int j, c;
2232 
2233 	printf("===band %d===\n", i);
2234 	printf("chan lo=%d, chan hi=%d\n", band->lo, band->hi);
2235 	printf("chan1 num=%d\n", chans[0].num);
2236 	for (c = 0; c < 2; c++) {
2237 		for (j = 0; j < IWN_NSAMPLES; j++) {
2238 			printf("chain %d, sample %d: temp=%d gain=%d "
2239 			    "power=%d pa_det=%d\n", c, j,
2240 			    chans[0].samples[c][j].temp,
2241 			    chans[0].samples[c][j].gain,
2242 			    chans[0].samples[c][j].power,
2243 			    chans[0].samples[c][j].pa_det);
2244 		}
2245 	}
2246 	printf("chan2 num=%d\n", chans[1].num);
2247 	for (c = 0; c < 2; c++) {
2248 		for (j = 0; j < IWN_NSAMPLES; j++) {
2249 			printf("chain %d, sample %d: temp=%d gain=%d "
2250 			    "power=%d pa_det=%d\n", c, j,
2251 			    chans[1].samples[c][j].temp,
2252 			    chans[1].samples[c][j].gain,
2253 			    chans[1].samples[c][j].power,
2254 			    chans[1].samples[c][j].pa_det);
2255 		}
2256 	}
2257 }
2258 #endif
2259 
2260 static void
2261 iwn5000_read_eeprom(struct iwn_softc *sc)
2262 {
2263 	struct iwn5000_eeprom_calib_hdr hdr;
2264 	int32_t volt;
2265 	uint32_t base, addr;
2266 	uint16_t val;
2267 	int i;
2268 
2269 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
2270 
2271 	/* Read regulatory domain (4 ASCII characters). */
2272 	iwn_read_prom_data(sc, IWN5000_EEPROM_REG, &val, 2);
2273 	base = le16toh(val);
2274 	iwn_read_prom_data(sc, base + IWN5000_EEPROM_DOMAIN,
2275 	    sc->eeprom_domain, 4);
2276 
2277 	/* Read the list of authorized channels (20MHz ones only). */
2278 	for (i = 0; i < IWN_NBANDS - 1; i++) {
2279 		addr =  base + sc->base_params->regulatory_bands[i];
2280 		iwn_read_eeprom_channels(sc, i, addr);
2281 	}
2282 
2283 	/* Read enhanced TX power information for 6000 Series. */
2284 	if (sc->base_params->enhanced_TX_power)
2285 		iwn_read_eeprom_enhinfo(sc);
2286 
2287 	iwn_read_prom_data(sc, IWN5000_EEPROM_CAL, &val, 2);
2288 	base = le16toh(val);
2289 	iwn_read_prom_data(sc, base, &hdr, sizeof hdr);
2290 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
2291 	    "%s: calib version=%u pa type=%u voltage=%u\n", __func__,
2292 	    hdr.version, hdr.pa_type, le16toh(hdr.volt));
2293 	sc->calib_ver = hdr.version;
2294 
2295 	if (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_TEMP_OFFSETv2) {
2296 		sc->eeprom_voltage = le16toh(hdr.volt);
2297 		iwn_read_prom_data(sc, base + IWN5000_EEPROM_TEMP, &val, 2);
2298 		sc->eeprom_temp_high=le16toh(val);
2299 		iwn_read_prom_data(sc, base + IWN5000_EEPROM_VOLT, &val, 2);
2300 		sc->eeprom_temp = le16toh(val);
2301 	}
2302 
2303 	if (sc->hw_type == IWN_HW_REV_TYPE_5150) {
2304 		/* Compute temperature offset. */
2305 		iwn_read_prom_data(sc, base + IWN5000_EEPROM_TEMP, &val, 2);
2306 		sc->eeprom_temp = le16toh(val);
2307 		iwn_read_prom_data(sc, base + IWN5000_EEPROM_VOLT, &val, 2);
2308 		volt = le16toh(val);
2309 		sc->temp_off = sc->eeprom_temp - (volt / -5);
2310 		DPRINTF(sc, IWN_DEBUG_CALIBRATE, "temp=%d volt=%d offset=%dK\n",
2311 		    sc->eeprom_temp, volt, sc->temp_off);
2312 	} else {
2313 		/* Read crystal calibration. */
2314 		iwn_read_prom_data(sc, base + IWN5000_EEPROM_CRYSTAL,
2315 		    &sc->eeprom_crystal, sizeof (uint32_t));
2316 		DPRINTF(sc, IWN_DEBUG_CALIBRATE, "crystal calibration 0x%08x\n",
2317 		    le32toh(sc->eeprom_crystal));
2318 	}
2319 
2320 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
2321 
2322 }
2323 
2324 /*
2325  * Translate EEPROM flags to net80211.
2326  */
2327 static uint32_t
2328 iwn_eeprom_channel_flags(struct iwn_eeprom_chan *channel)
2329 {
2330 	uint32_t nflags;
2331 
2332 	nflags = 0;
2333 	if ((channel->flags & IWN_EEPROM_CHAN_ACTIVE) == 0)
2334 		nflags |= IEEE80211_CHAN_PASSIVE;
2335 	if ((channel->flags & IWN_EEPROM_CHAN_IBSS) == 0)
2336 		nflags |= IEEE80211_CHAN_NOADHOC;
2337 	if (channel->flags & IWN_EEPROM_CHAN_RADAR) {
2338 		nflags |= IEEE80211_CHAN_DFS;
2339 		/* XXX apparently IBSS may still be marked */
2340 		nflags |= IEEE80211_CHAN_NOADHOC;
2341 	}
2342 
2343 	return nflags;
2344 }
2345 
2346 static void
2347 iwn_read_eeprom_band(struct iwn_softc *sc, int n)
2348 {
2349 	struct ifnet *ifp = sc->sc_ifp;
2350 	struct ieee80211com *ic = ifp->if_l2com;
2351 	struct iwn_eeprom_chan *channels = sc->eeprom_channels[n];
2352 	const struct iwn_chan_band *band = &iwn_bands[n];
2353 	struct ieee80211_channel *c;
2354 	uint8_t chan;
2355 	int i, nflags;
2356 
2357 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
2358 
2359 	for (i = 0; i < band->nchan; i++) {
2360 		if (!(channels[i].flags & IWN_EEPROM_CHAN_VALID)) {
2361 			DPRINTF(sc, IWN_DEBUG_RESET,
2362 			    "skip chan %d flags 0x%x maxpwr %d\n",
2363 			    band->chan[i], channels[i].flags,
2364 			    channels[i].maxpwr);
2365 			continue;
2366 		}
2367 		chan = band->chan[i];
2368 		nflags = iwn_eeprom_channel_flags(&channels[i]);
2369 
2370 		c = &ic->ic_channels[ic->ic_nchans++];
2371 		c->ic_ieee = chan;
2372 		c->ic_maxregpower = channels[i].maxpwr;
2373 		c->ic_maxpower = 2*c->ic_maxregpower;
2374 
2375 		if (n == 0) {	/* 2GHz band */
2376 			c->ic_freq = ieee80211_ieee2mhz(chan, IEEE80211_CHAN_G);
2377 			/* G =>'s B is supported */
2378 			c->ic_flags = IEEE80211_CHAN_B | nflags;
2379 			c = &ic->ic_channels[ic->ic_nchans++];
2380 			c[0] = c[-1];
2381 			c->ic_flags = IEEE80211_CHAN_G | nflags;
2382 		} else {	/* 5GHz band */
2383 			c->ic_freq = ieee80211_ieee2mhz(chan, IEEE80211_CHAN_A);
2384 			c->ic_flags = IEEE80211_CHAN_A | nflags;
2385 		}
2386 
2387 		/* Save maximum allowed TX power for this channel. */
2388 		sc->maxpwr[chan] = channels[i].maxpwr;
2389 
2390 		DPRINTF(sc, IWN_DEBUG_RESET,
2391 		    "add chan %d flags 0x%x maxpwr %d\n", chan,
2392 		    channels[i].flags, channels[i].maxpwr);
2393 
2394 		if (sc->sc_flags & IWN_FLAG_HAS_11N) {
2395 			/* add HT20, HT40 added separately */
2396 			c = &ic->ic_channels[ic->ic_nchans++];
2397 			c[0] = c[-1];
2398 			c->ic_flags |= IEEE80211_CHAN_HT20;
2399 		}
2400 	}
2401 
2402 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
2403 
2404 }
2405 
2406 static void
2407 iwn_read_eeprom_ht40(struct iwn_softc *sc, int n)
2408 {
2409 	struct ifnet *ifp = sc->sc_ifp;
2410 	struct ieee80211com *ic = ifp->if_l2com;
2411 	struct iwn_eeprom_chan *channels = sc->eeprom_channels[n];
2412 	const struct iwn_chan_band *band = &iwn_bands[n];
2413 	struct ieee80211_channel *c, *cent, *extc;
2414 	uint8_t chan;
2415 	int i, nflags;
2416 
2417 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s start\n", __func__);
2418 
2419 	if (!(sc->sc_flags & IWN_FLAG_HAS_11N)) {
2420 		DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end no 11n\n", __func__);
2421 		return;
2422 	}
2423 
2424 	for (i = 0; i < band->nchan; i++) {
2425 		if (!(channels[i].flags & IWN_EEPROM_CHAN_VALID)) {
2426 			DPRINTF(sc, IWN_DEBUG_RESET,
2427 			    "skip chan %d flags 0x%x maxpwr %d\n",
2428 			    band->chan[i], channels[i].flags,
2429 			    channels[i].maxpwr);
2430 			continue;
2431 		}
2432 		chan = band->chan[i];
2433 		nflags = iwn_eeprom_channel_flags(&channels[i]);
2434 
2435 		/*
2436 		 * Each entry defines an HT40 channel pair; find the
2437 		 * center channel, then the extension channel above.
2438 		 */
2439 		cent = ieee80211_find_channel_byieee(ic, chan,
2440 		    (n == 5 ? IEEE80211_CHAN_G : IEEE80211_CHAN_A));
2441 		if (cent == NULL) {	/* XXX shouldn't happen */
2442 			device_printf(sc->sc_dev,
2443 			    "%s: no entry for channel %d\n", __func__, chan);
2444 			continue;
2445 		}
2446 		extc = ieee80211_find_channel(ic, cent->ic_freq+20,
2447 		    (n == 5 ? IEEE80211_CHAN_G : IEEE80211_CHAN_A));
2448 		if (extc == NULL) {
2449 			DPRINTF(sc, IWN_DEBUG_RESET,
2450 			    "%s: skip chan %d, extension channel not found\n",
2451 			    __func__, chan);
2452 			continue;
2453 		}
2454 
2455 		DPRINTF(sc, IWN_DEBUG_RESET,
2456 		    "add ht40 chan %d flags 0x%x maxpwr %d\n",
2457 		    chan, channels[i].flags, channels[i].maxpwr);
2458 
2459 		c = &ic->ic_channels[ic->ic_nchans++];
2460 		c[0] = cent[0];
2461 		c->ic_extieee = extc->ic_ieee;
2462 		c->ic_flags &= ~IEEE80211_CHAN_HT;
2463 		c->ic_flags |= IEEE80211_CHAN_HT40U | nflags;
2464 		c = &ic->ic_channels[ic->ic_nchans++];
2465 		c[0] = extc[0];
2466 		c->ic_extieee = cent->ic_ieee;
2467 		c->ic_flags &= ~IEEE80211_CHAN_HT;
2468 		c->ic_flags |= IEEE80211_CHAN_HT40D | nflags;
2469 	}
2470 
2471 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
2472 
2473 }
2474 
2475 static void
2476 iwn_read_eeprom_channels(struct iwn_softc *sc, int n, uint32_t addr)
2477 {
2478 	struct ifnet *ifp = sc->sc_ifp;
2479 	struct ieee80211com *ic = ifp->if_l2com;
2480 
2481 	iwn_read_prom_data(sc, addr, &sc->eeprom_channels[n],
2482 	    iwn_bands[n].nchan * sizeof (struct iwn_eeprom_chan));
2483 
2484 	if (n < 5)
2485 		iwn_read_eeprom_band(sc, n);
2486 	else
2487 		iwn_read_eeprom_ht40(sc, n);
2488 	ieee80211_sort_channels(ic->ic_channels, ic->ic_nchans);
2489 }
2490 
2491 static struct iwn_eeprom_chan *
2492 iwn_find_eeprom_channel(struct iwn_softc *sc, struct ieee80211_channel *c)
2493 {
2494 	int band, chan, i, j;
2495 
2496 	if (IEEE80211_IS_CHAN_HT40(c)) {
2497 		band = IEEE80211_IS_CHAN_5GHZ(c) ? 6 : 5;
2498 		if (IEEE80211_IS_CHAN_HT40D(c))
2499 			chan = c->ic_extieee;
2500 		else
2501 			chan = c->ic_ieee;
2502 		for (i = 0; i < iwn_bands[band].nchan; i++) {
2503 			if (iwn_bands[band].chan[i] == chan)
2504 				return &sc->eeprom_channels[band][i];
2505 		}
2506 	} else {
2507 		for (j = 0; j < 5; j++) {
2508 			for (i = 0; i < iwn_bands[j].nchan; i++) {
2509 				if (iwn_bands[j].chan[i] == c->ic_ieee)
2510 					return &sc->eeprom_channels[j][i];
2511 			}
2512 		}
2513 	}
2514 	return NULL;
2515 }
2516 
2517 /*
2518  * Enforce flags read from EEPROM.
2519  */
2520 static int
2521 iwn_setregdomain(struct ieee80211com *ic, struct ieee80211_regdomain *rd,
2522     int nchan, struct ieee80211_channel chans[])
2523 {
2524 	struct iwn_softc *sc = ic->ic_ifp->if_softc;
2525 	int i;
2526 
2527 	for (i = 0; i < nchan; i++) {
2528 		struct ieee80211_channel *c = &chans[i];
2529 		struct iwn_eeprom_chan *channel;
2530 
2531 		channel = iwn_find_eeprom_channel(sc, c);
2532 		if (channel == NULL) {
2533 			if_printf(ic->ic_ifp,
2534 			    "%s: invalid channel %u freq %u/0x%x\n",
2535 			    __func__, c->ic_ieee, c->ic_freq, c->ic_flags);
2536 			return EINVAL;
2537 		}
2538 		c->ic_flags |= iwn_eeprom_channel_flags(channel);
2539 	}
2540 
2541 	return 0;
2542 }
2543 
2544 static void
2545 iwn_read_eeprom_enhinfo(struct iwn_softc *sc)
2546 {
2547 	struct iwn_eeprom_enhinfo enhinfo[35];
2548 	struct ifnet *ifp = sc->sc_ifp;
2549 	struct ieee80211com *ic = ifp->if_l2com;
2550 	struct ieee80211_channel *c;
2551 	uint16_t val, base;
2552 	int8_t maxpwr;
2553 	uint8_t flags;
2554 	int i, j;
2555 
2556 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
2557 
2558 	iwn_read_prom_data(sc, IWN5000_EEPROM_REG, &val, 2);
2559 	base = le16toh(val);
2560 	iwn_read_prom_data(sc, base + IWN6000_EEPROM_ENHINFO,
2561 	    enhinfo, sizeof enhinfo);
2562 
2563 	for (i = 0; i < nitems(enhinfo); i++) {
2564 		flags = enhinfo[i].flags;
2565 		if (!(flags & IWN_ENHINFO_VALID))
2566 			continue;	/* Skip invalid entries. */
2567 
2568 		maxpwr = 0;
2569 		if (sc->txchainmask & IWN_ANT_A)
2570 			maxpwr = MAX(maxpwr, enhinfo[i].chain[0]);
2571 		if (sc->txchainmask & IWN_ANT_B)
2572 			maxpwr = MAX(maxpwr, enhinfo[i].chain[1]);
2573 		if (sc->txchainmask & IWN_ANT_C)
2574 			maxpwr = MAX(maxpwr, enhinfo[i].chain[2]);
2575 		if (sc->ntxchains == 2)
2576 			maxpwr = MAX(maxpwr, enhinfo[i].mimo2);
2577 		else if (sc->ntxchains == 3)
2578 			maxpwr = MAX(maxpwr, enhinfo[i].mimo3);
2579 
2580 		for (j = 0; j < ic->ic_nchans; j++) {
2581 			c = &ic->ic_channels[j];
2582 			if ((flags & IWN_ENHINFO_5GHZ)) {
2583 				if (!IEEE80211_IS_CHAN_A(c))
2584 					continue;
2585 			} else if ((flags & IWN_ENHINFO_OFDM)) {
2586 				if (!IEEE80211_IS_CHAN_G(c))
2587 					continue;
2588 			} else if (!IEEE80211_IS_CHAN_B(c))
2589 				continue;
2590 			if ((flags & IWN_ENHINFO_HT40)) {
2591 				if (!IEEE80211_IS_CHAN_HT40(c))
2592 					continue;
2593 			} else {
2594 				if (IEEE80211_IS_CHAN_HT40(c))
2595 					continue;
2596 			}
2597 			if (enhinfo[i].chan != 0 &&
2598 			    enhinfo[i].chan != c->ic_ieee)
2599 				continue;
2600 
2601 			DPRINTF(sc, IWN_DEBUG_RESET,
2602 			    "channel %d(%x), maxpwr %d\n", c->ic_ieee,
2603 			    c->ic_flags, maxpwr / 2);
2604 			c->ic_maxregpower = maxpwr / 2;
2605 			c->ic_maxpower = maxpwr;
2606 		}
2607 	}
2608 
2609 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
2610 
2611 }
2612 
2613 static struct ieee80211_node *
2614 iwn_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
2615 {
2616 	return malloc(sizeof (struct iwn_node), M_80211_NODE,M_NOWAIT | M_ZERO);
2617 }
2618 
2619 static __inline int
2620 rate2plcp(int rate)
2621 {
2622 	switch (rate & 0xff) {
2623 	case 12:	return 0xd;
2624 	case 18:	return 0xf;
2625 	case 24:	return 0x5;
2626 	case 36:	return 0x7;
2627 	case 48:	return 0x9;
2628 	case 72:	return 0xb;
2629 	case 96:	return 0x1;
2630 	case 108:	return 0x3;
2631 	case 2:		return 10;
2632 	case 4:		return 20;
2633 	case 11:	return 55;
2634 	case 22:	return 110;
2635 	}
2636 	return 0;
2637 }
2638 
2639 static int
2640 iwn_get_1stream_tx_antmask(struct iwn_softc *sc)
2641 {
2642 
2643 	return IWN_LSB(sc->txchainmask);
2644 }
2645 
2646 static int
2647 iwn_get_2stream_tx_antmask(struct iwn_softc *sc)
2648 {
2649 	int tx;
2650 
2651 	/*
2652 	 * The '2 stream' setup is a bit .. odd.
2653 	 *
2654 	 * For NICs that support only 1 antenna, default to IWN_ANT_AB or
2655 	 * the firmware panics (eg Intel 5100.)
2656 	 *
2657 	 * For NICs that support two antennas, we use ANT_AB.
2658 	 *
2659 	 * For NICs that support three antennas, we use the two that
2660 	 * wasn't the default one.
2661 	 *
2662 	 * XXX TODO: if bluetooth (full concurrent) is enabled, restrict
2663 	 * this to only one antenna.
2664 	 */
2665 
2666 	/* Default - transmit on the other antennas */
2667 	tx = (sc->txchainmask & ~IWN_LSB(sc->txchainmask));
2668 
2669 	/* Now, if it's zero, set it to IWN_ANT_AB, so to not panic firmware */
2670 	if (tx == 0)
2671 		tx = IWN_ANT_AB;
2672 
2673 	/*
2674 	 * If the NIC is a two-stream TX NIC, configure the TX mask to
2675 	 * the default chainmask
2676 	 */
2677 	else if (sc->ntxchains == 2)
2678 		tx = sc->txchainmask;
2679 
2680 	return (tx);
2681 }
2682 
2683 
2684 
2685 /*
2686  * Calculate the required PLCP value from the given rate,
2687  * to the given node.
2688  *
2689  * This will take the node configuration (eg 11n, rate table
2690  * setup, etc) into consideration.
2691  */
2692 static uint32_t
2693 iwn_rate_to_plcp(struct iwn_softc *sc, struct ieee80211_node *ni,
2694     uint8_t rate)
2695 {
2696 #define	RV(v)	((v) & IEEE80211_RATE_VAL)
2697 	struct ieee80211com *ic = ni->ni_ic;
2698 	uint32_t plcp = 0;
2699 	int ridx;
2700 
2701 	/*
2702 	 * If it's an MCS rate, let's set the plcp correctly
2703 	 * and set the relevant flags based on the node config.
2704 	 */
2705 	if (rate & IEEE80211_RATE_MCS) {
2706 		/*
2707 		 * Set the initial PLCP value to be between 0->31 for
2708 		 * MCS 0 -> MCS 31, then set the "I'm an MCS rate!"
2709 		 * flag.
2710 		 */
2711 		plcp = RV(rate) | IWN_RFLAG_MCS;
2712 
2713 		/*
2714 		 * XXX the following should only occur if both
2715 		 * the local configuration _and_ the remote node
2716 		 * advertise these capabilities.  Thus this code
2717 		 * may need fixing!
2718 		 */
2719 
2720 		/*
2721 		 * Set the channel width and guard interval.
2722 		 */
2723 		if (IEEE80211_IS_CHAN_HT40(ni->ni_chan)) {
2724 			plcp |= IWN_RFLAG_HT40;
2725 			if (ni->ni_htcap & IEEE80211_HTCAP_SHORTGI40)
2726 				plcp |= IWN_RFLAG_SGI;
2727 		} else if (ni->ni_htcap & IEEE80211_HTCAP_SHORTGI20) {
2728 			plcp |= IWN_RFLAG_SGI;
2729 		}
2730 
2731 		/*
2732 		 * Ensure the selected rate matches the link quality
2733 		 * table entries being used.
2734 		 */
2735 		if (rate > 0x8f)
2736 			plcp |= IWN_RFLAG_ANT(sc->txchainmask);
2737 		else if (rate > 0x87)
2738 			plcp |= IWN_RFLAG_ANT(iwn_get_2stream_tx_antmask(sc));
2739 		else
2740 			plcp |= IWN_RFLAG_ANT(iwn_get_1stream_tx_antmask(sc));
2741 	} else {
2742 		/*
2743 		 * Set the initial PLCP - fine for both
2744 		 * OFDM and CCK rates.
2745 		 */
2746 		plcp = rate2plcp(rate);
2747 
2748 		/* Set CCK flag if it's CCK */
2749 
2750 		/* XXX It would be nice to have a method
2751 		 * to map the ridx -> phy table entry
2752 		 * so we could just query that, rather than
2753 		 * this hack to check against IWN_RIDX_OFDM6.
2754 		 */
2755 		ridx = ieee80211_legacy_rate_lookup(ic->ic_rt,
2756 		    rate & IEEE80211_RATE_VAL);
2757 		if (ridx < IWN_RIDX_OFDM6 &&
2758 		    IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
2759 			plcp |= IWN_RFLAG_CCK;
2760 
2761 		/* Set antenna configuration */
2762 		/* XXX TODO: is this the right antenna to use for legacy? */
2763 		plcp |= IWN_RFLAG_ANT(iwn_get_1stream_tx_antmask(sc));
2764 	}
2765 
2766 	DPRINTF(sc, IWN_DEBUG_TXRATE, "%s: rate=0x%02x, plcp=0x%08x\n",
2767 	    __func__,
2768 	    rate,
2769 	    plcp);
2770 
2771 	return (htole32(plcp));
2772 #undef	RV
2773 }
2774 
2775 static void
2776 iwn_newassoc(struct ieee80211_node *ni, int isnew)
2777 {
2778 	/* Doesn't do anything at the moment */
2779 }
2780 
2781 static int
2782 iwn_media_change(struct ifnet *ifp)
2783 {
2784 	int error;
2785 
2786 	error = ieee80211_media_change(ifp);
2787 	/* NB: only the fixed rate can change and that doesn't need a reset */
2788 	return (error == ENETRESET ? 0 : error);
2789 }
2790 
2791 static int
2792 iwn_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
2793 {
2794 	struct iwn_vap *ivp = IWN_VAP(vap);
2795 	struct ieee80211com *ic = vap->iv_ic;
2796 	struct iwn_softc *sc = ic->ic_ifp->if_softc;
2797 	int error = 0;
2798 
2799 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
2800 
2801 	DPRINTF(sc, IWN_DEBUG_STATE, "%s: %s -> %s\n", __func__,
2802 	    ieee80211_state_name[vap->iv_state], ieee80211_state_name[nstate]);
2803 
2804 	IEEE80211_UNLOCK(ic);
2805 	IWN_LOCK(sc);
2806 	callout_stop(&sc->calib_to);
2807 
2808 	sc->rxon = &sc->rx_on[IWN_RXON_BSS_CTX];
2809 
2810 	switch (nstate) {
2811 	case IEEE80211_S_ASSOC:
2812 		if (vap->iv_state != IEEE80211_S_RUN)
2813 			break;
2814 		/* FALLTHROUGH */
2815 	case IEEE80211_S_AUTH:
2816 		if (vap->iv_state == IEEE80211_S_AUTH)
2817 			break;
2818 
2819 		/*
2820 		 * !AUTH -> AUTH transition requires state reset to handle
2821 		 * reassociations correctly.
2822 		 */
2823 		sc->rxon->associd = 0;
2824 		sc->rxon->filter &= ~htole32(IWN_FILTER_BSS);
2825 		sc->calib.state = IWN_CALIB_STATE_INIT;
2826 
2827 		if ((error = iwn_auth(sc, vap)) != 0) {
2828 			device_printf(sc->sc_dev,
2829 			    "%s: could not move to auth state\n", __func__);
2830 		}
2831 		break;
2832 
2833 	case IEEE80211_S_RUN:
2834 		/*
2835 		 * RUN -> RUN transition; Just restart the timers.
2836 		 */
2837 		if (vap->iv_state == IEEE80211_S_RUN) {
2838 			sc->calib_cnt = 0;
2839 			break;
2840 		}
2841 
2842 		/*
2843 		 * !RUN -> RUN requires setting the association id
2844 		 * which is done with a firmware cmd.  We also defer
2845 		 * starting the timers until that work is done.
2846 		 */
2847 		if ((error = iwn_run(sc, vap)) != 0) {
2848 			device_printf(sc->sc_dev,
2849 			    "%s: could not move to run state\n", __func__);
2850 		}
2851 		break;
2852 
2853 	case IEEE80211_S_INIT:
2854 		sc->calib.state = IWN_CALIB_STATE_INIT;
2855 		break;
2856 
2857 	default:
2858 		break;
2859 	}
2860 	IWN_UNLOCK(sc);
2861 	IEEE80211_LOCK(ic);
2862 	if (error != 0){
2863 		DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end in error\n", __func__);
2864 		return error;
2865 	}
2866 
2867 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
2868 
2869 	return ivp->iv_newstate(vap, nstate, arg);
2870 }
2871 
2872 static void
2873 iwn_calib_timeout(void *arg)
2874 {
2875 	struct iwn_softc *sc = arg;
2876 
2877 	IWN_LOCK_ASSERT(sc);
2878 
2879 	/* Force automatic TX power calibration every 60 secs. */
2880 	if (++sc->calib_cnt >= 120) {
2881 		uint32_t flags = 0;
2882 
2883 		DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s\n",
2884 		    "sending request for statistics");
2885 		(void)iwn_cmd(sc, IWN_CMD_GET_STATISTICS, &flags,
2886 		    sizeof flags, 1);
2887 		sc->calib_cnt = 0;
2888 	}
2889 	callout_reset(&sc->calib_to, msecs_to_ticks(500), iwn_calib_timeout,
2890 	    sc);
2891 }
2892 
2893 /*
2894  * Process an RX_PHY firmware notification.  This is usually immediately
2895  * followed by an MPDU_RX_DONE notification.
2896  */
2897 static void
2898 iwn_rx_phy(struct iwn_softc *sc, struct iwn_rx_desc *desc,
2899     struct iwn_rx_data *data)
2900 {
2901 	struct iwn_rx_stat *stat = (struct iwn_rx_stat *)(desc + 1);
2902 
2903 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: received PHY stats\n", __func__);
2904 	bus_dmamap_sync(sc->rxq.data_dmat, data->map, BUS_DMASYNC_POSTREAD);
2905 
2906 	/* Save RX statistics, they will be used on MPDU_RX_DONE. */
2907 	memcpy(&sc->last_rx_stat, stat, sizeof (*stat));
2908 	sc->last_rx_valid = 1;
2909 }
2910 
2911 /*
2912  * Process an RX_DONE (4965AGN only) or MPDU_RX_DONE firmware notification.
2913  * Each MPDU_RX_DONE notification must be preceded by an RX_PHY one.
2914  */
2915 static void
2916 iwn_rx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc,
2917     struct iwn_rx_data *data)
2918 {
2919 	struct iwn_ops *ops = &sc->ops;
2920 	struct ifnet *ifp = sc->sc_ifp;
2921 	struct ieee80211com *ic = ifp->if_l2com;
2922 	struct iwn_rx_ring *ring = &sc->rxq;
2923 	struct ieee80211_frame *wh;
2924 	struct ieee80211_node *ni;
2925 	struct mbuf *m, *m1;
2926 	struct iwn_rx_stat *stat;
2927 	caddr_t head;
2928 	bus_addr_t paddr;
2929 	uint32_t flags;
2930 	int error, len, rssi, nf;
2931 
2932 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
2933 
2934 	if (desc->type == IWN_MPDU_RX_DONE) {
2935 		/* Check for prior RX_PHY notification. */
2936 		if (!sc->last_rx_valid) {
2937 			DPRINTF(sc, IWN_DEBUG_ANY,
2938 			    "%s: missing RX_PHY\n", __func__);
2939 			return;
2940 		}
2941 		stat = &sc->last_rx_stat;
2942 	} else
2943 		stat = (struct iwn_rx_stat *)(desc + 1);
2944 
2945 	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTREAD);
2946 
2947 	if (stat->cfg_phy_len > IWN_STAT_MAXLEN) {
2948 		device_printf(sc->sc_dev,
2949 		    "%s: invalid RX statistic header, len %d\n", __func__,
2950 		    stat->cfg_phy_len);
2951 		return;
2952 	}
2953 	if (desc->type == IWN_MPDU_RX_DONE) {
2954 		struct iwn_rx_mpdu *mpdu = (struct iwn_rx_mpdu *)(desc + 1);
2955 		head = (caddr_t)(mpdu + 1);
2956 		len = le16toh(mpdu->len);
2957 	} else {
2958 		head = (caddr_t)(stat + 1) + stat->cfg_phy_len;
2959 		len = le16toh(stat->len);
2960 	}
2961 
2962 	flags = le32toh(*(uint32_t *)(head + len));
2963 
2964 	/* Discard frames with a bad FCS early. */
2965 	if ((flags & IWN_RX_NOERROR) != IWN_RX_NOERROR) {
2966 		DPRINTF(sc, IWN_DEBUG_RECV, "%s: RX flags error %x\n",
2967 		    __func__, flags);
2968 		if_inc_counter(ifp, IFCOUNTER_IERRORS, 1);
2969 		return;
2970 	}
2971 	/* Discard frames that are too short. */
2972 	if (len < sizeof (*wh)) {
2973 		DPRINTF(sc, IWN_DEBUG_RECV, "%s: frame too short: %d\n",
2974 		    __func__, len);
2975 		if_inc_counter(ifp, IFCOUNTER_IERRORS, 1);
2976 		return;
2977 	}
2978 
2979 	m1 = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, IWN_RBUF_SIZE);
2980 	if (m1 == NULL) {
2981 		DPRINTF(sc, IWN_DEBUG_ANY, "%s: no mbuf to restock ring\n",
2982 		    __func__);
2983 		if_inc_counter(ifp, IFCOUNTER_IERRORS, 1);
2984 		return;
2985 	}
2986 	bus_dmamap_unload(ring->data_dmat, data->map);
2987 
2988 	error = bus_dmamap_load(ring->data_dmat, data->map, mtod(m1, void *),
2989 	    IWN_RBUF_SIZE, iwn_dma_map_addr, &paddr, BUS_DMA_NOWAIT);
2990 	if (error != 0 && error != EFBIG) {
2991 		device_printf(sc->sc_dev,
2992 		    "%s: bus_dmamap_load failed, error %d\n", __func__, error);
2993 		m_freem(m1);
2994 
2995 		/* Try to reload the old mbuf. */
2996 		error = bus_dmamap_load(ring->data_dmat, data->map,
2997 		    mtod(data->m, void *), IWN_RBUF_SIZE, iwn_dma_map_addr,
2998 		    &paddr, BUS_DMA_NOWAIT);
2999 		if (error != 0 && error != EFBIG) {
3000 			panic("%s: could not load old RX mbuf", __func__);
3001 		}
3002 		/* Physical address may have changed. */
3003 		ring->desc[ring->cur] = htole32(paddr >> 8);
3004 		bus_dmamap_sync(ring->data_dmat, ring->desc_dma.map,
3005 		    BUS_DMASYNC_PREWRITE);
3006 		if_inc_counter(ifp, IFCOUNTER_IERRORS, 1);
3007 		return;
3008 	}
3009 
3010 	m = data->m;
3011 	data->m = m1;
3012 	/* Update RX descriptor. */
3013 	ring->desc[ring->cur] = htole32(paddr >> 8);
3014 	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
3015 	    BUS_DMASYNC_PREWRITE);
3016 
3017 	/* Finalize mbuf. */
3018 	m->m_pkthdr.rcvif = ifp;
3019 	m->m_data = head;
3020 	m->m_pkthdr.len = m->m_len = len;
3021 
3022 	/* Grab a reference to the source node. */
3023 	wh = mtod(m, struct ieee80211_frame *);
3024 	ni = ieee80211_find_rxnode(ic, (struct ieee80211_frame_min *)wh);
3025 	nf = (ni != NULL && ni->ni_vap->iv_state == IEEE80211_S_RUN &&
3026 	    (ic->ic_flags & IEEE80211_F_SCAN) == 0) ? sc->noise : -95;
3027 
3028 	rssi = ops->get_rssi(sc, stat);
3029 
3030 	if (ieee80211_radiotap_active(ic)) {
3031 		struct iwn_rx_radiotap_header *tap = &sc->sc_rxtap;
3032 
3033 		tap->wr_flags = 0;
3034 		if (stat->flags & htole16(IWN_STAT_FLAG_SHPREAMBLE))
3035 			tap->wr_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
3036 		tap->wr_dbm_antsignal = (int8_t)rssi;
3037 		tap->wr_dbm_antnoise = (int8_t)nf;
3038 		tap->wr_tsft = stat->tstamp;
3039 		switch (stat->rate) {
3040 		/* CCK rates. */
3041 		case  10: tap->wr_rate =   2; break;
3042 		case  20: tap->wr_rate =   4; break;
3043 		case  55: tap->wr_rate =  11; break;
3044 		case 110: tap->wr_rate =  22; break;
3045 		/* OFDM rates. */
3046 		case 0xd: tap->wr_rate =  12; break;
3047 		case 0xf: tap->wr_rate =  18; break;
3048 		case 0x5: tap->wr_rate =  24; break;
3049 		case 0x7: tap->wr_rate =  36; break;
3050 		case 0x9: tap->wr_rate =  48; break;
3051 		case 0xb: tap->wr_rate =  72; break;
3052 		case 0x1: tap->wr_rate =  96; break;
3053 		case 0x3: tap->wr_rate = 108; break;
3054 		/* Unknown rate: should not happen. */
3055 		default:  tap->wr_rate =   0;
3056 		}
3057 	}
3058 
3059 	IWN_UNLOCK(sc);
3060 
3061 	/* Send the frame to the 802.11 layer. */
3062 	if (ni != NULL) {
3063 		if (ni->ni_flags & IEEE80211_NODE_HT)
3064 			m->m_flags |= M_AMPDU;
3065 		(void)ieee80211_input(ni, m, rssi - nf, nf);
3066 		/* Node is no longer needed. */
3067 		ieee80211_free_node(ni);
3068 	} else
3069 		(void)ieee80211_input_all(ic, m, rssi - nf, nf);
3070 
3071 	IWN_LOCK(sc);
3072 
3073 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
3074 
3075 }
3076 
3077 /* Process an incoming Compressed BlockAck. */
3078 static void
3079 iwn_rx_compressed_ba(struct iwn_softc *sc, struct iwn_rx_desc *desc,
3080     struct iwn_rx_data *data)
3081 {
3082 	struct iwn_ops *ops = &sc->ops;
3083 	struct ifnet *ifp = sc->sc_ifp;
3084 	struct iwn_node *wn;
3085 	struct ieee80211_node *ni;
3086 	struct iwn_compressed_ba *ba = (struct iwn_compressed_ba *)(desc + 1);
3087 	struct iwn_tx_ring *txq;
3088 	struct iwn_tx_data *txdata;
3089 	struct ieee80211_tx_ampdu *tap;
3090 	struct mbuf *m;
3091 	uint64_t bitmap;
3092 	uint16_t ssn;
3093 	uint8_t tid;
3094 	int ackfailcnt = 0, i, lastidx, qid, *res, shift;
3095 	int tx_ok = 0, tx_err = 0;
3096 
3097 	DPRINTF(sc, IWN_DEBUG_TRACE | IWN_DEBUG_XMIT, "->%s begin\n", __func__);
3098 
3099 	bus_dmamap_sync(sc->rxq.data_dmat, data->map, BUS_DMASYNC_POSTREAD);
3100 
3101 	qid = le16toh(ba->qid);
3102 	txq = &sc->txq[ba->qid];
3103 	tap = sc->qid2tap[ba->qid];
3104 	tid = tap->txa_tid;
3105 	wn = (void *)tap->txa_ni;
3106 
3107 	res = NULL;
3108 	ssn = 0;
3109 	if (!IEEE80211_AMPDU_RUNNING(tap)) {
3110 		res = tap->txa_private;
3111 		ssn = tap->txa_start & 0xfff;
3112 	}
3113 
3114 	for (lastidx = le16toh(ba->ssn) & 0xff; txq->read != lastidx;) {
3115 		txdata = &txq->data[txq->read];
3116 
3117 		/* Unmap and free mbuf. */
3118 		bus_dmamap_sync(txq->data_dmat, txdata->map,
3119 		    BUS_DMASYNC_POSTWRITE);
3120 		bus_dmamap_unload(txq->data_dmat, txdata->map);
3121 		m = txdata->m, txdata->m = NULL;
3122 		ni = txdata->ni, txdata->ni = NULL;
3123 
3124 		KASSERT(ni != NULL, ("no node"));
3125 		KASSERT(m != NULL, ("no mbuf"));
3126 
3127 		DPRINTF(sc, IWN_DEBUG_XMIT, "%s: freeing m=%p\n", __func__, m);
3128 		ieee80211_tx_complete(ni, m, 1);
3129 
3130 		txq->queued--;
3131 		txq->read = (txq->read + 1) % IWN_TX_RING_COUNT;
3132 	}
3133 
3134 	if (txq->queued == 0 && res != NULL) {
3135 		iwn_nic_lock(sc);
3136 		ops->ampdu_tx_stop(sc, qid, tid, ssn);
3137 		iwn_nic_unlock(sc);
3138 		sc->qid2tap[qid] = NULL;
3139 		free(res, M_DEVBUF);
3140 		return;
3141 	}
3142 
3143 	if (wn->agg[tid].bitmap == 0)
3144 		return;
3145 
3146 	shift = wn->agg[tid].startidx - ((le16toh(ba->seq) >> 4) & 0xff);
3147 	if (shift < 0)
3148 		shift += 0x100;
3149 
3150 	if (wn->agg[tid].nframes > (64 - shift))
3151 		return;
3152 
3153 	/*
3154 	 * Walk the bitmap and calculate how many successful and failed
3155 	 * attempts are made.
3156 	 *
3157 	 * Yes, the rate control code doesn't know these are A-MPDU
3158 	 * subframes and that it's okay to fail some of these.
3159 	 */
3160 	ni = tap->txa_ni;
3161 	bitmap = (le64toh(ba->bitmap) >> shift) & wn->agg[tid].bitmap;
3162 	for (i = 0; bitmap; i++) {
3163 		if ((bitmap & 1) == 0) {
3164 			if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
3165 			tx_err ++;
3166 			ieee80211_ratectl_tx_complete(ni->ni_vap, ni,
3167 			    IEEE80211_RATECTL_TX_FAILURE, &ackfailcnt, NULL);
3168 		} else {
3169 			if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
3170 			tx_ok ++;
3171 			ieee80211_ratectl_tx_complete(ni->ni_vap, ni,
3172 			    IEEE80211_RATECTL_TX_SUCCESS, &ackfailcnt, NULL);
3173 		}
3174 		bitmap >>= 1;
3175 	}
3176 
3177 	DPRINTF(sc, IWN_DEBUG_TRACE | IWN_DEBUG_XMIT,
3178 	    "->%s: end; %d ok; %d err\n",__func__, tx_ok, tx_err);
3179 
3180 }
3181 
3182 /*
3183  * Process a CALIBRATION_RESULT notification sent by the initialization
3184  * firmware on response to a CMD_CALIB_CONFIG command (5000 only).
3185  */
3186 static void
3187 iwn5000_rx_calib_results(struct iwn_softc *sc, struct iwn_rx_desc *desc,
3188     struct iwn_rx_data *data)
3189 {
3190 	struct iwn_phy_calib *calib = (struct iwn_phy_calib *)(desc + 1);
3191 	int len, idx = -1;
3192 
3193 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
3194 
3195 	/* Runtime firmware should not send such a notification. */
3196 	if (sc->sc_flags & IWN_FLAG_CALIB_DONE){
3197 		DPRINTF(sc, IWN_DEBUG_TRACE, "->%s received after clib done\n",
3198 	    __func__);
3199 		return;
3200 	}
3201 	len = (le32toh(desc->len) & 0x3fff) - 4;
3202 	bus_dmamap_sync(sc->rxq.data_dmat, data->map, BUS_DMASYNC_POSTREAD);
3203 
3204 	switch (calib->code) {
3205 	case IWN5000_PHY_CALIB_DC:
3206 		if (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_DC)
3207 			idx = 0;
3208 		break;
3209 	case IWN5000_PHY_CALIB_LO:
3210 		if (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_LO)
3211 			idx = 1;
3212 		break;
3213 	case IWN5000_PHY_CALIB_TX_IQ:
3214 		if (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_TX_IQ)
3215 			idx = 2;
3216 		break;
3217 	case IWN5000_PHY_CALIB_TX_IQ_PERIODIC:
3218 		if (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_TX_IQ_PERIODIC)
3219 			idx = 3;
3220 		break;
3221 	case IWN5000_PHY_CALIB_BASE_BAND:
3222 		if (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_BASE_BAND)
3223 			idx = 4;
3224 		break;
3225 	}
3226 	if (idx == -1)	/* Ignore other results. */
3227 		return;
3228 
3229 	/* Save calibration result. */
3230 	if (sc->calibcmd[idx].buf != NULL)
3231 		free(sc->calibcmd[idx].buf, M_DEVBUF);
3232 	sc->calibcmd[idx].buf = malloc(len, M_DEVBUF, M_NOWAIT);
3233 	if (sc->calibcmd[idx].buf == NULL) {
3234 		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
3235 		    "not enough memory for calibration result %d\n",
3236 		    calib->code);
3237 		return;
3238 	}
3239 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
3240 	    "saving calibration result idx=%d, code=%d len=%d\n", idx, calib->code, len);
3241 	sc->calibcmd[idx].len = len;
3242 	memcpy(sc->calibcmd[idx].buf, calib, len);
3243 }
3244 
3245 static void
3246 iwn_stats_update(struct iwn_softc *sc, struct iwn_calib_state *calib,
3247     struct iwn_stats *stats, int len)
3248 {
3249 	struct iwn_stats_bt *stats_bt;
3250 	struct iwn_stats *lstats;
3251 
3252 	/*
3253 	 * First - check whether the length is the bluetooth or normal.
3254 	 *
3255 	 * If it's normal - just copy it and bump out.
3256 	 * Otherwise we have to convert things.
3257 	 */
3258 
3259 	if (len == sizeof(struct iwn_stats) + 4) {
3260 		memcpy(&sc->last_stat, stats, sizeof(struct iwn_stats));
3261 		sc->last_stat_valid = 1;
3262 		return;
3263 	}
3264 
3265 	/*
3266 	 * If it's not the bluetooth size - log, then just copy.
3267 	 */
3268 	if (len != sizeof(struct iwn_stats_bt) + 4) {
3269 		DPRINTF(sc, IWN_DEBUG_STATS,
3270 		    "%s: size of rx statistics (%d) not an expected size!\n",
3271 		    __func__,
3272 		    len);
3273 		memcpy(&sc->last_stat, stats, sizeof(struct iwn_stats));
3274 		sc->last_stat_valid = 1;
3275 		return;
3276 	}
3277 
3278 	/*
3279 	 * Ok. Time to copy.
3280 	 */
3281 	stats_bt = (struct iwn_stats_bt *) stats;
3282 	lstats = &sc->last_stat;
3283 
3284 	/* flags */
3285 	lstats->flags = stats_bt->flags;
3286 	/* rx_bt */
3287 	memcpy(&lstats->rx.ofdm, &stats_bt->rx_bt.ofdm,
3288 	    sizeof(struct iwn_rx_phy_stats));
3289 	memcpy(&lstats->rx.cck, &stats_bt->rx_bt.cck,
3290 	    sizeof(struct iwn_rx_phy_stats));
3291 	memcpy(&lstats->rx.general, &stats_bt->rx_bt.general_bt.common,
3292 	    sizeof(struct iwn_rx_general_stats));
3293 	memcpy(&lstats->rx.ht, &stats_bt->rx_bt.ht,
3294 	    sizeof(struct iwn_rx_ht_phy_stats));
3295 	/* tx */
3296 	memcpy(&lstats->tx, &stats_bt->tx,
3297 	    sizeof(struct iwn_tx_stats));
3298 	/* general */
3299 	memcpy(&lstats->general, &stats_bt->general,
3300 	    sizeof(struct iwn_general_stats));
3301 
3302 	/* XXX TODO: Squirrel away the extra bluetooth stats somewhere */
3303 	sc->last_stat_valid = 1;
3304 }
3305 
3306 /*
3307  * Process an RX_STATISTICS or BEACON_STATISTICS firmware notification.
3308  * The latter is sent by the firmware after each received beacon.
3309  */
3310 static void
3311 iwn_rx_statistics(struct iwn_softc *sc, struct iwn_rx_desc *desc,
3312     struct iwn_rx_data *data)
3313 {
3314 	struct iwn_ops *ops = &sc->ops;
3315 	struct ifnet *ifp = sc->sc_ifp;
3316 	struct ieee80211com *ic = ifp->if_l2com;
3317 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3318 	struct iwn_calib_state *calib = &sc->calib;
3319 	struct iwn_stats *stats = (struct iwn_stats *)(desc + 1);
3320 	struct iwn_stats *lstats;
3321 	int temp;
3322 
3323 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
3324 
3325 	/* Ignore statistics received during a scan. */
3326 	if (vap->iv_state != IEEE80211_S_RUN ||
3327 	    (ic->ic_flags & IEEE80211_F_SCAN)){
3328 		DPRINTF(sc, IWN_DEBUG_TRACE, "->%s received during calib\n",
3329 	    __func__);
3330 		return;
3331 	}
3332 
3333 	bus_dmamap_sync(sc->rxq.data_dmat, data->map, BUS_DMASYNC_POSTREAD);
3334 
3335 	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_STATS,
3336 	    "%s: received statistics, cmd %d, len %d\n",
3337 	    __func__, desc->type, le16toh(desc->len));
3338 	sc->calib_cnt = 0;	/* Reset TX power calibration timeout. */
3339 
3340 	/*
3341 	 * Collect/track general statistics for reporting.
3342 	 *
3343 	 * This takes care of ensuring that the bluetooth sized message
3344 	 * will be correctly converted to the legacy sized message.
3345 	 */
3346 	iwn_stats_update(sc, calib, stats, le16toh(desc->len));
3347 
3348 	/*
3349 	 * And now, let's take a reference of it to use!
3350 	 */
3351 	lstats = &sc->last_stat;
3352 
3353 	/* Test if temperature has changed. */
3354 	if (lstats->general.temp != sc->rawtemp) {
3355 		/* Convert "raw" temperature to degC. */
3356 		sc->rawtemp = stats->general.temp;
3357 		temp = ops->get_temperature(sc);
3358 		DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: temperature %d\n",
3359 		    __func__, temp);
3360 
3361 		/* Update TX power if need be (4965AGN only). */
3362 		if (sc->hw_type == IWN_HW_REV_TYPE_4965)
3363 			iwn4965_power_calibration(sc, temp);
3364 	}
3365 
3366 	if (desc->type != IWN_BEACON_STATISTICS)
3367 		return;	/* Reply to a statistics request. */
3368 
3369 	sc->noise = iwn_get_noise(&lstats->rx.general);
3370 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: noise %d\n", __func__, sc->noise);
3371 
3372 	/* Test that RSSI and noise are present in stats report. */
3373 	if (le32toh(lstats->rx.general.flags) != 1) {
3374 		DPRINTF(sc, IWN_DEBUG_ANY, "%s\n",
3375 		    "received statistics without RSSI");
3376 		return;
3377 	}
3378 
3379 	if (calib->state == IWN_CALIB_STATE_ASSOC)
3380 		iwn_collect_noise(sc, &lstats->rx.general);
3381 	else if (calib->state == IWN_CALIB_STATE_RUN) {
3382 		iwn_tune_sensitivity(sc, &lstats->rx);
3383 		/*
3384 		 * XXX TODO: Only run the RX recovery if we're associated!
3385 		 */
3386 		iwn_check_rx_recovery(sc, lstats);
3387 		iwn_save_stats_counters(sc, lstats);
3388 	}
3389 
3390 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
3391 }
3392 
3393 /*
3394  * Save the relevant statistic counters for the next calibration
3395  * pass.
3396  */
3397 static void
3398 iwn_save_stats_counters(struct iwn_softc *sc, const struct iwn_stats *rs)
3399 {
3400 	struct iwn_calib_state *calib = &sc->calib;
3401 
3402 	/* Save counters values for next call. */
3403 	calib->bad_plcp_cck = le32toh(rs->rx.cck.bad_plcp);
3404 	calib->fa_cck = le32toh(rs->rx.cck.fa);
3405 	calib->bad_plcp_ht = le32toh(rs->rx.ht.bad_plcp);
3406 	calib->bad_plcp_ofdm = le32toh(rs->rx.ofdm.bad_plcp);
3407 	calib->fa_ofdm = le32toh(rs->rx.ofdm.fa);
3408 
3409 	/* Last time we received these tick values */
3410 	sc->last_calib_ticks = ticks;
3411 }
3412 
3413 /*
3414  * Process a TX_DONE firmware notification.  Unfortunately, the 4965AGN
3415  * and 5000 adapters have different incompatible TX status formats.
3416  */
3417 static void
3418 iwn4965_tx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc,
3419     struct iwn_rx_data *data)
3420 {
3421 	struct iwn4965_tx_stat *stat = (struct iwn4965_tx_stat *)(desc + 1);
3422 	struct iwn_tx_ring *ring;
3423 	int qid;
3424 
3425 	qid = desc->qid & 0xf;
3426 	ring = &sc->txq[qid];
3427 
3428 	DPRINTF(sc, IWN_DEBUG_XMIT, "%s: "
3429 	    "qid %d idx %d RTS retries %d ACK retries %d nkill %d rate %x duration %d status %x\n",
3430 	    __func__, desc->qid, desc->idx,
3431 	    stat->rtsfailcnt,
3432 	    stat->ackfailcnt,
3433 	    stat->btkillcnt,
3434 	    stat->rate, le16toh(stat->duration),
3435 	    le32toh(stat->status));
3436 
3437 	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTREAD);
3438 	if (qid >= sc->firstaggqueue) {
3439 		iwn_ampdu_tx_done(sc, qid, desc->idx, stat->nframes,
3440 		    stat->ackfailcnt, &stat->status);
3441 	} else {
3442 		iwn_tx_done(sc, desc, stat->ackfailcnt,
3443 		    le32toh(stat->status) & 0xff);
3444 	}
3445 }
3446 
3447 static void
3448 iwn5000_tx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc,
3449     struct iwn_rx_data *data)
3450 {
3451 	struct iwn5000_tx_stat *stat = (struct iwn5000_tx_stat *)(desc + 1);
3452 	struct iwn_tx_ring *ring;
3453 	int qid;
3454 
3455 	qid = desc->qid & 0xf;
3456 	ring = &sc->txq[qid];
3457 
3458 	DPRINTF(sc, IWN_DEBUG_XMIT, "%s: "
3459 	    "qid %d idx %d RTS retries %d ACK retries %d nkill %d rate %x duration %d status %x\n",
3460 	    __func__, desc->qid, desc->idx,
3461 	    stat->rtsfailcnt,
3462 	    stat->ackfailcnt,
3463 	    stat->btkillcnt,
3464 	    stat->rate, le16toh(stat->duration),
3465 	    le32toh(stat->status));
3466 
3467 #ifdef notyet
3468 	/* Reset TX scheduler slot. */
3469 	iwn5000_reset_sched(sc, desc->qid & 0xf, desc->idx);
3470 #endif
3471 
3472 	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTREAD);
3473 	if (qid >= sc->firstaggqueue) {
3474 		iwn_ampdu_tx_done(sc, qid, desc->idx, stat->nframes,
3475 		    stat->ackfailcnt, &stat->status);
3476 	} else {
3477 		iwn_tx_done(sc, desc, stat->ackfailcnt,
3478 		    le16toh(stat->status) & 0xff);
3479 	}
3480 }
3481 
3482 /*
3483  * Adapter-independent backend for TX_DONE firmware notifications.
3484  */
3485 static void
3486 iwn_tx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc, int ackfailcnt,
3487     uint8_t status)
3488 {
3489 	struct ifnet *ifp = sc->sc_ifp;
3490 	struct iwn_tx_ring *ring = &sc->txq[desc->qid & 0xf];
3491 	struct iwn_tx_data *data = &ring->data[desc->idx];
3492 	struct mbuf *m;
3493 	struct ieee80211_node *ni;
3494 	struct ieee80211vap *vap;
3495 
3496 	KASSERT(data->ni != NULL, ("no node"));
3497 
3498 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
3499 
3500 	/* Unmap and free mbuf. */
3501 	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTWRITE);
3502 	bus_dmamap_unload(ring->data_dmat, data->map);
3503 	m = data->m, data->m = NULL;
3504 	ni = data->ni, data->ni = NULL;
3505 	vap = ni->ni_vap;
3506 
3507 	/*
3508 	 * Update rate control statistics for the node.
3509 	 */
3510 	if (status & IWN_TX_FAIL) {
3511 		if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
3512 		ieee80211_ratectl_tx_complete(vap, ni,
3513 		    IEEE80211_RATECTL_TX_FAILURE, &ackfailcnt, NULL);
3514 	} else {
3515 		if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
3516 		ieee80211_ratectl_tx_complete(vap, ni,
3517 		    IEEE80211_RATECTL_TX_SUCCESS, &ackfailcnt, NULL);
3518 	}
3519 
3520 	/*
3521 	 * Channels marked for "radar" require traffic to be received
3522 	 * to unlock before we can transmit.  Until traffic is seen
3523 	 * any attempt to transmit is returned immediately with status
3524 	 * set to IWN_TX_FAIL_TX_LOCKED.  Unfortunately this can easily
3525 	 * happen on first authenticate after scanning.  To workaround
3526 	 * this we ignore a failure of this sort in AUTH state so the
3527 	 * 802.11 layer will fall back to using a timeout to wait for
3528 	 * the AUTH reply.  This allows the firmware time to see
3529 	 * traffic so a subsequent retry of AUTH succeeds.  It's
3530 	 * unclear why the firmware does not maintain state for
3531 	 * channels recently visited as this would allow immediate
3532 	 * use of the channel after a scan (where we see traffic).
3533 	 */
3534 	if (status == IWN_TX_FAIL_TX_LOCKED &&
3535 	    ni->ni_vap->iv_state == IEEE80211_S_AUTH)
3536 		ieee80211_tx_complete(ni, m, 0);
3537 	else
3538 		ieee80211_tx_complete(ni, m,
3539 		    (status & IWN_TX_FAIL) != 0);
3540 
3541 	sc->sc_tx_timer = 0;
3542 	if (--ring->queued < IWN_TX_RING_LOMARK) {
3543 		sc->qfullmsk &= ~(1 << ring->qid);
3544 		if (sc->qfullmsk == 0 &&
3545 		    (ifp->if_drv_flags & IFF_DRV_OACTIVE)) {
3546 			ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3547 			iwn_start_locked(ifp);
3548 		}
3549 	}
3550 
3551 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
3552 
3553 }
3554 
3555 /*
3556  * Process a "command done" firmware notification.  This is where we wakeup
3557  * processes waiting for a synchronous command completion.
3558  */
3559 static void
3560 iwn_cmd_done(struct iwn_softc *sc, struct iwn_rx_desc *desc)
3561 {
3562 	struct iwn_tx_ring *ring;
3563 	struct iwn_tx_data *data;
3564 	int cmd_queue_num;
3565 
3566 	if (sc->sc_flags & IWN_FLAG_PAN_SUPPORT)
3567 		cmd_queue_num = IWN_PAN_CMD_QUEUE;
3568 	else
3569 		cmd_queue_num = IWN_CMD_QUEUE_NUM;
3570 
3571 	if ((desc->qid & IWN_RX_DESC_QID_MSK) != cmd_queue_num)
3572 		return;	/* Not a command ack. */
3573 
3574 	ring = &sc->txq[cmd_queue_num];
3575 	data = &ring->data[desc->idx];
3576 
3577 	/* If the command was mapped in an mbuf, free it. */
3578 	if (data->m != NULL) {
3579 		bus_dmamap_sync(ring->data_dmat, data->map,
3580 		    BUS_DMASYNC_POSTWRITE);
3581 		bus_dmamap_unload(ring->data_dmat, data->map);
3582 		m_freem(data->m);
3583 		data->m = NULL;
3584 	}
3585 	wakeup(&ring->desc[desc->idx]);
3586 }
3587 
3588 static void
3589 iwn_ampdu_tx_done(struct iwn_softc *sc, int qid, int idx, int nframes,
3590     int ackfailcnt, void *stat)
3591 {
3592 	struct iwn_ops *ops = &sc->ops;
3593 	struct ifnet *ifp = sc->sc_ifp;
3594 	struct iwn_tx_ring *ring = &sc->txq[qid];
3595 	struct iwn_tx_data *data;
3596 	struct mbuf *m;
3597 	struct iwn_node *wn;
3598 	struct ieee80211_node *ni;
3599 	struct ieee80211_tx_ampdu *tap;
3600 	uint64_t bitmap;
3601 	uint32_t *status = stat;
3602 	uint16_t *aggstatus = stat;
3603 	uint16_t ssn;
3604 	uint8_t tid;
3605 	int bit, i, lastidx, *res, seqno, shift, start;
3606 
3607 	/* XXX TODO: status is le16 field! Grr */
3608 
3609 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
3610 	DPRINTF(sc, IWN_DEBUG_XMIT, "%s: nframes=%d, status=0x%08x\n",
3611 	    __func__,
3612 	    nframes,
3613 	    *status);
3614 
3615 	tap = sc->qid2tap[qid];
3616 	tid = tap->txa_tid;
3617 	wn = (void *)tap->txa_ni;
3618 	ni = tap->txa_ni;
3619 
3620 	/*
3621 	 * XXX TODO: ACK and RTS failures would be nice here!
3622 	 */
3623 
3624 	/*
3625 	 * A-MPDU single frame status - if we failed to transmit it
3626 	 * in A-MPDU, then it may be a permanent failure.
3627 	 *
3628 	 * XXX TODO: check what the Linux iwlwifi driver does here;
3629 	 * there's some permanent and temporary failures that may be
3630 	 * handled differently.
3631 	 */
3632 	if (nframes == 1) {
3633 		if ((*status & 0xff) != 1 && (*status & 0xff) != 2) {
3634 #ifdef	NOT_YET
3635 			printf("ieee80211_send_bar()\n");
3636 #endif
3637 			/*
3638 			 * If we completely fail a transmit, make sure a
3639 			 * notification is pushed up to the rate control
3640 			 * layer.
3641 			 */
3642 			ieee80211_ratectl_tx_complete(ni->ni_vap,
3643 			    ni,
3644 			    IEEE80211_RATECTL_TX_FAILURE,
3645 			    &ackfailcnt,
3646 			    NULL);
3647 		} else {
3648 			/*
3649 			 * If nframes=1, then we won't be getting a BA for
3650 			 * this frame.  Ensure that we correctly update the
3651 			 * rate control code with how many retries were
3652 			 * needed to send it.
3653 			 */
3654 			ieee80211_ratectl_tx_complete(ni->ni_vap,
3655 			    ni,
3656 			    IEEE80211_RATECTL_TX_SUCCESS,
3657 			    &ackfailcnt,
3658 			    NULL);
3659 		}
3660 	}
3661 
3662 	bitmap = 0;
3663 	start = idx;
3664 	for (i = 0; i < nframes; i++) {
3665 		if (le16toh(aggstatus[i * 2]) & 0xc)
3666 			continue;
3667 
3668 		idx = le16toh(aggstatus[2*i + 1]) & 0xff;
3669 		bit = idx - start;
3670 		shift = 0;
3671 		if (bit >= 64) {
3672 			shift = 0x100 - idx + start;
3673 			bit = 0;
3674 			start = idx;
3675 		} else if (bit <= -64)
3676 			bit = 0x100 - start + idx;
3677 		else if (bit < 0) {
3678 			shift = start - idx;
3679 			start = idx;
3680 			bit = 0;
3681 		}
3682 		bitmap = bitmap << shift;
3683 		bitmap |= 1ULL << bit;
3684 	}
3685 	tap = sc->qid2tap[qid];
3686 	tid = tap->txa_tid;
3687 	wn = (void *)tap->txa_ni;
3688 	wn->agg[tid].bitmap = bitmap;
3689 	wn->agg[tid].startidx = start;
3690 	wn->agg[tid].nframes = nframes;
3691 
3692 	res = NULL;
3693 	ssn = 0;
3694 	if (!IEEE80211_AMPDU_RUNNING(tap)) {
3695 		res = tap->txa_private;
3696 		ssn = tap->txa_start & 0xfff;
3697 	}
3698 
3699 	/* This is going nframes DWORDS into the descriptor? */
3700 	seqno = le32toh(*(status + nframes)) & 0xfff;
3701 	for (lastidx = (seqno & 0xff); ring->read != lastidx;) {
3702 		data = &ring->data[ring->read];
3703 
3704 		/* Unmap and free mbuf. */
3705 		bus_dmamap_sync(ring->data_dmat, data->map,
3706 		    BUS_DMASYNC_POSTWRITE);
3707 		bus_dmamap_unload(ring->data_dmat, data->map);
3708 		m = data->m, data->m = NULL;
3709 		ni = data->ni, data->ni = NULL;
3710 
3711 		KASSERT(ni != NULL, ("no node"));
3712 		KASSERT(m != NULL, ("no mbuf"));
3713 		DPRINTF(sc, IWN_DEBUG_XMIT, "%s: freeing m=%p\n", __func__, m);
3714 		ieee80211_tx_complete(ni, m, 1);
3715 
3716 		ring->queued--;
3717 		ring->read = (ring->read + 1) % IWN_TX_RING_COUNT;
3718 	}
3719 
3720 	if (ring->queued == 0 && res != NULL) {
3721 		iwn_nic_lock(sc);
3722 		ops->ampdu_tx_stop(sc, qid, tid, ssn);
3723 		iwn_nic_unlock(sc);
3724 		sc->qid2tap[qid] = NULL;
3725 		free(res, M_DEVBUF);
3726 		return;
3727 	}
3728 
3729 	sc->sc_tx_timer = 0;
3730 	if (ring->queued < IWN_TX_RING_LOMARK) {
3731 		sc->qfullmsk &= ~(1 << ring->qid);
3732 		if (sc->qfullmsk == 0 &&
3733 		    (ifp->if_drv_flags & IFF_DRV_OACTIVE)) {
3734 			ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3735 			iwn_start_locked(ifp);
3736 		}
3737 	}
3738 
3739 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
3740 
3741 }
3742 
3743 /*
3744  * Process an INT_FH_RX or INT_SW_RX interrupt.
3745  */
3746 static void
3747 iwn_notif_intr(struct iwn_softc *sc)
3748 {
3749 	struct iwn_ops *ops = &sc->ops;
3750 	struct ifnet *ifp = sc->sc_ifp;
3751 	struct ieee80211com *ic = ifp->if_l2com;
3752 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3753 	uint16_t hw;
3754 
3755 	bus_dmamap_sync(sc->rxq.stat_dma.tag, sc->rxq.stat_dma.map,
3756 	    BUS_DMASYNC_POSTREAD);
3757 
3758 	hw = le16toh(sc->rxq.stat->closed_count) & 0xfff;
3759 	while (sc->rxq.cur != hw) {
3760 		struct iwn_rx_data *data = &sc->rxq.data[sc->rxq.cur];
3761 		struct iwn_rx_desc *desc;
3762 
3763 		bus_dmamap_sync(sc->rxq.data_dmat, data->map,
3764 		    BUS_DMASYNC_POSTREAD);
3765 		desc = mtod(data->m, struct iwn_rx_desc *);
3766 
3767 		DPRINTF(sc, IWN_DEBUG_RECV,
3768 		    "%s: cur=%d; qid %x idx %d flags %x type %d(%s) len %d\n",
3769 		    __func__, sc->rxq.cur, desc->qid & 0xf, desc->idx, desc->flags,
3770 		    desc->type, iwn_intr_str(desc->type),
3771 		    le16toh(desc->len));
3772 
3773 		if (!(desc->qid & IWN_UNSOLICITED_RX_NOTIF))	/* Reply to a command. */
3774 			iwn_cmd_done(sc, desc);
3775 
3776 		switch (desc->type) {
3777 		case IWN_RX_PHY:
3778 			iwn_rx_phy(sc, desc, data);
3779 			break;
3780 
3781 		case IWN_RX_DONE:		/* 4965AGN only. */
3782 		case IWN_MPDU_RX_DONE:
3783 			/* An 802.11 frame has been received. */
3784 			iwn_rx_done(sc, desc, data);
3785 			break;
3786 
3787 		case IWN_RX_COMPRESSED_BA:
3788 			/* A Compressed BlockAck has been received. */
3789 			iwn_rx_compressed_ba(sc, desc, data);
3790 			break;
3791 
3792 		case IWN_TX_DONE:
3793 			/* An 802.11 frame has been transmitted. */
3794 			ops->tx_done(sc, desc, data);
3795 			break;
3796 
3797 		case IWN_RX_STATISTICS:
3798 		case IWN_BEACON_STATISTICS:
3799 			iwn_rx_statistics(sc, desc, data);
3800 			break;
3801 
3802 		case IWN_BEACON_MISSED:
3803 		{
3804 			struct iwn_beacon_missed *miss =
3805 			    (struct iwn_beacon_missed *)(desc + 1);
3806 			int misses;
3807 
3808 			bus_dmamap_sync(sc->rxq.data_dmat, data->map,
3809 			    BUS_DMASYNC_POSTREAD);
3810 			misses = le32toh(miss->consecutive);
3811 
3812 			DPRINTF(sc, IWN_DEBUG_STATE,
3813 			    "%s: beacons missed %d/%d\n", __func__,
3814 			    misses, le32toh(miss->total));
3815 			/*
3816 			 * If more than 5 consecutive beacons are missed,
3817 			 * reinitialize the sensitivity state machine.
3818 			 */
3819 			if (vap->iv_state == IEEE80211_S_RUN &&
3820 			    (ic->ic_flags & IEEE80211_F_SCAN) == 0) {
3821 				if (misses > 5)
3822 					(void)iwn_init_sensitivity(sc);
3823 				if (misses >= vap->iv_bmissthreshold) {
3824 					IWN_UNLOCK(sc);
3825 					ieee80211_beacon_miss(ic);
3826 					IWN_LOCK(sc);
3827 				}
3828 			}
3829 			break;
3830 		}
3831 		case IWN_UC_READY:
3832 		{
3833 			struct iwn_ucode_info *uc =
3834 			    (struct iwn_ucode_info *)(desc + 1);
3835 
3836 			/* The microcontroller is ready. */
3837 			bus_dmamap_sync(sc->rxq.data_dmat, data->map,
3838 			    BUS_DMASYNC_POSTREAD);
3839 			DPRINTF(sc, IWN_DEBUG_RESET,
3840 			    "microcode alive notification version=%d.%d "
3841 			    "subtype=%x alive=%x\n", uc->major, uc->minor,
3842 			    uc->subtype, le32toh(uc->valid));
3843 
3844 			if (le32toh(uc->valid) != 1) {
3845 				device_printf(sc->sc_dev,
3846 				    "microcontroller initialization failed");
3847 				break;
3848 			}
3849 			if (uc->subtype == IWN_UCODE_INIT) {
3850 				/* Save microcontroller report. */
3851 				memcpy(&sc->ucode_info, uc, sizeof (*uc));
3852 			}
3853 			/* Save the address of the error log in SRAM. */
3854 			sc->errptr = le32toh(uc->errptr);
3855 			break;
3856 		}
3857 		case IWN_STATE_CHANGED:
3858 		{
3859 			/*
3860 			 * State change allows hardware switch change to be
3861 			 * noted. However, we handle this in iwn_intr as we
3862 			 * get both the enable/disble intr.
3863 			 */
3864 			bus_dmamap_sync(sc->rxq.data_dmat, data->map,
3865 			    BUS_DMASYNC_POSTREAD);
3866 #ifdef	IWN_DEBUG
3867 			uint32_t *status = (uint32_t *)(desc + 1);
3868 			DPRINTF(sc, IWN_DEBUG_INTR | IWN_DEBUG_STATE,
3869 			    "state changed to %x\n",
3870 			    le32toh(*status));
3871 #endif
3872 			break;
3873 		}
3874 		case IWN_START_SCAN:
3875 		{
3876 			bus_dmamap_sync(sc->rxq.data_dmat, data->map,
3877 			    BUS_DMASYNC_POSTREAD);
3878 #ifdef	IWN_DEBUG
3879 			struct iwn_start_scan *scan =
3880 			    (struct iwn_start_scan *)(desc + 1);
3881 			DPRINTF(sc, IWN_DEBUG_ANY,
3882 			    "%s: scanning channel %d status %x\n",
3883 			    __func__, scan->chan, le32toh(scan->status));
3884 #endif
3885 			break;
3886 		}
3887 		case IWN_STOP_SCAN:
3888 		{
3889 			bus_dmamap_sync(sc->rxq.data_dmat, data->map,
3890 			    BUS_DMASYNC_POSTREAD);
3891 #ifdef	IWN_DEBUG
3892 			struct iwn_stop_scan *scan =
3893 			    (struct iwn_stop_scan *)(desc + 1);
3894 			DPRINTF(sc, IWN_DEBUG_STATE | IWN_DEBUG_SCAN,
3895 			    "scan finished nchan=%d status=%d chan=%d\n",
3896 			    scan->nchan, scan->status, scan->chan);
3897 #endif
3898 			sc->sc_is_scanning = 0;
3899 			IWN_UNLOCK(sc);
3900 			ieee80211_scan_next(vap);
3901 			IWN_LOCK(sc);
3902 			break;
3903 		}
3904 		case IWN5000_CALIBRATION_RESULT:
3905 			iwn5000_rx_calib_results(sc, desc, data);
3906 			break;
3907 
3908 		case IWN5000_CALIBRATION_DONE:
3909 			sc->sc_flags |= IWN_FLAG_CALIB_DONE;
3910 			wakeup(sc);
3911 			break;
3912 		}
3913 
3914 		sc->rxq.cur = (sc->rxq.cur + 1) % IWN_RX_RING_COUNT;
3915 	}
3916 
3917 	/* Tell the firmware what we have processed. */
3918 	hw = (hw == 0) ? IWN_RX_RING_COUNT - 1 : hw - 1;
3919 	IWN_WRITE(sc, IWN_FH_RX_WPTR, hw & ~7);
3920 }
3921 
3922 /*
3923  * Process an INT_WAKEUP interrupt raised when the microcontroller wakes up
3924  * from power-down sleep mode.
3925  */
3926 static void
3927 iwn_wakeup_intr(struct iwn_softc *sc)
3928 {
3929 	int qid;
3930 
3931 	DPRINTF(sc, IWN_DEBUG_RESET, "%s: ucode wakeup from power-down sleep\n",
3932 	    __func__);
3933 
3934 	/* Wakeup RX and TX rings. */
3935 	IWN_WRITE(sc, IWN_FH_RX_WPTR, sc->rxq.cur & ~7);
3936 	for (qid = 0; qid < sc->ntxqs; qid++) {
3937 		struct iwn_tx_ring *ring = &sc->txq[qid];
3938 		IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | ring->cur);
3939 	}
3940 }
3941 
3942 static void
3943 iwn_rftoggle_intr(struct iwn_softc *sc)
3944 {
3945 	struct ifnet *ifp = sc->sc_ifp;
3946 	struct ieee80211com *ic = ifp->if_l2com;
3947 	uint32_t tmp = IWN_READ(sc, IWN_GP_CNTRL);
3948 
3949 	IWN_LOCK_ASSERT(sc);
3950 
3951 	device_printf(sc->sc_dev, "RF switch: radio %s\n",
3952 	    (tmp & IWN_GP_CNTRL_RFKILL) ? "enabled" : "disabled");
3953 	if (tmp & IWN_GP_CNTRL_RFKILL)
3954 		ieee80211_runtask(ic, &sc->sc_radioon_task);
3955 	else
3956 		ieee80211_runtask(ic, &sc->sc_radiooff_task);
3957 }
3958 
3959 /*
3960  * Dump the error log of the firmware when a firmware panic occurs.  Although
3961  * we can't debug the firmware because it is neither open source nor free, it
3962  * can help us to identify certain classes of problems.
3963  */
3964 static void
3965 iwn_fatal_intr(struct iwn_softc *sc)
3966 {
3967 	struct iwn_fw_dump dump;
3968 	int i;
3969 
3970 	IWN_LOCK_ASSERT(sc);
3971 
3972 	/* Force a complete recalibration on next init. */
3973 	sc->sc_flags &= ~IWN_FLAG_CALIB_DONE;
3974 
3975 	/* Check that the error log address is valid. */
3976 	if (sc->errptr < IWN_FW_DATA_BASE ||
3977 	    sc->errptr + sizeof (dump) >
3978 	    IWN_FW_DATA_BASE + sc->fw_data_maxsz) {
3979 		printf("%s: bad firmware error log address 0x%08x\n", __func__,
3980 		    sc->errptr);
3981 		return;
3982 	}
3983 	if (iwn_nic_lock(sc) != 0) {
3984 		printf("%s: could not read firmware error log\n", __func__);
3985 		return;
3986 	}
3987 	/* Read firmware error log from SRAM. */
3988 	iwn_mem_read_region_4(sc, sc->errptr, (uint32_t *)&dump,
3989 	    sizeof (dump) / sizeof (uint32_t));
3990 	iwn_nic_unlock(sc);
3991 
3992 	if (dump.valid == 0) {
3993 		printf("%s: firmware error log is empty\n", __func__);
3994 		return;
3995 	}
3996 	printf("firmware error log:\n");
3997 	printf("  error type      = \"%s\" (0x%08X)\n",
3998 	    (dump.id < nitems(iwn_fw_errmsg)) ?
3999 		iwn_fw_errmsg[dump.id] : "UNKNOWN",
4000 	    dump.id);
4001 	printf("  program counter = 0x%08X\n", dump.pc);
4002 	printf("  source line     = 0x%08X\n", dump.src_line);
4003 	printf("  error data      = 0x%08X%08X\n",
4004 	    dump.error_data[0], dump.error_data[1]);
4005 	printf("  branch link     = 0x%08X%08X\n",
4006 	    dump.branch_link[0], dump.branch_link[1]);
4007 	printf("  interrupt link  = 0x%08X%08X\n",
4008 	    dump.interrupt_link[0], dump.interrupt_link[1]);
4009 	printf("  time            = %u\n", dump.time[0]);
4010 
4011 	/* Dump driver status (TX and RX rings) while we're here. */
4012 	printf("driver status:\n");
4013 	for (i = 0; i < sc->ntxqs; i++) {
4014 		struct iwn_tx_ring *ring = &sc->txq[i];
4015 		printf("  tx ring %2d: qid=%-2d cur=%-3d queued=%-3d\n",
4016 		    i, ring->qid, ring->cur, ring->queued);
4017 	}
4018 	printf("  rx ring: cur=%d\n", sc->rxq.cur);
4019 }
4020 
4021 static void
4022 iwn_intr(void *arg)
4023 {
4024 	struct iwn_softc *sc = arg;
4025 	struct ifnet *ifp = sc->sc_ifp;
4026 	uint32_t r1, r2, tmp;
4027 
4028 	IWN_LOCK(sc);
4029 
4030 	/* Disable interrupts. */
4031 	IWN_WRITE(sc, IWN_INT_MASK, 0);
4032 
4033 	/* Read interrupts from ICT (fast) or from registers (slow). */
4034 	if (sc->sc_flags & IWN_FLAG_USE_ICT) {
4035 		tmp = 0;
4036 		while (sc->ict[sc->ict_cur] != 0) {
4037 			tmp |= sc->ict[sc->ict_cur];
4038 			sc->ict[sc->ict_cur] = 0;	/* Acknowledge. */
4039 			sc->ict_cur = (sc->ict_cur + 1) % IWN_ICT_COUNT;
4040 		}
4041 		tmp = le32toh(tmp);
4042 		if (tmp == 0xffffffff)	/* Shouldn't happen. */
4043 			tmp = 0;
4044 		else if (tmp & 0xc0000)	/* Workaround a HW bug. */
4045 			tmp |= 0x8000;
4046 		r1 = (tmp & 0xff00) << 16 | (tmp & 0xff);
4047 		r2 = 0;	/* Unused. */
4048 	} else {
4049 		r1 = IWN_READ(sc, IWN_INT);
4050 		if (r1 == 0xffffffff || (r1 & 0xfffffff0) == 0xa5a5a5a0)
4051 			return;	/* Hardware gone! */
4052 		r2 = IWN_READ(sc, IWN_FH_INT);
4053 	}
4054 
4055 	DPRINTF(sc, IWN_DEBUG_INTR, "interrupt reg1=0x%08x reg2=0x%08x\n"
4056     , r1, r2);
4057 
4058 	if (r1 == 0 && r2 == 0)
4059 		goto done;	/* Interrupt not for us. */
4060 
4061 	/* Acknowledge interrupts. */
4062 	IWN_WRITE(sc, IWN_INT, r1);
4063 	if (!(sc->sc_flags & IWN_FLAG_USE_ICT))
4064 		IWN_WRITE(sc, IWN_FH_INT, r2);
4065 
4066 	if (r1 & IWN_INT_RF_TOGGLED) {
4067 		iwn_rftoggle_intr(sc);
4068 		goto done;
4069 	}
4070 	if (r1 & IWN_INT_CT_REACHED) {
4071 		device_printf(sc->sc_dev, "%s: critical temperature reached!\n",
4072 		    __func__);
4073 	}
4074 	if (r1 & (IWN_INT_SW_ERR | IWN_INT_HW_ERR)) {
4075 		device_printf(sc->sc_dev, "%s: fatal firmware error\n",
4076 		    __func__);
4077 #ifdef	IWN_DEBUG
4078 		iwn_debug_register(sc);
4079 #endif
4080 		/* Dump firmware error log and stop. */
4081 		iwn_fatal_intr(sc);
4082 
4083 		taskqueue_enqueue(sc->sc_tq, &sc->sc_panic_task);
4084 		goto done;
4085 	}
4086 	if ((r1 & (IWN_INT_FH_RX | IWN_INT_SW_RX | IWN_INT_RX_PERIODIC)) ||
4087 	    (r2 & IWN_FH_INT_RX)) {
4088 		if (sc->sc_flags & IWN_FLAG_USE_ICT) {
4089 			if (r1 & (IWN_INT_FH_RX | IWN_INT_SW_RX))
4090 				IWN_WRITE(sc, IWN_FH_INT, IWN_FH_INT_RX);
4091 			IWN_WRITE_1(sc, IWN_INT_PERIODIC,
4092 			    IWN_INT_PERIODIC_DIS);
4093 			iwn_notif_intr(sc);
4094 			if (r1 & (IWN_INT_FH_RX | IWN_INT_SW_RX)) {
4095 				IWN_WRITE_1(sc, IWN_INT_PERIODIC,
4096 				    IWN_INT_PERIODIC_ENA);
4097 			}
4098 		} else
4099 			iwn_notif_intr(sc);
4100 	}
4101 
4102 	if ((r1 & IWN_INT_FH_TX) || (r2 & IWN_FH_INT_TX)) {
4103 		if (sc->sc_flags & IWN_FLAG_USE_ICT)
4104 			IWN_WRITE(sc, IWN_FH_INT, IWN_FH_INT_TX);
4105 		wakeup(sc);	/* FH DMA transfer completed. */
4106 	}
4107 
4108 	if (r1 & IWN_INT_ALIVE)
4109 		wakeup(sc);	/* Firmware is alive. */
4110 
4111 	if (r1 & IWN_INT_WAKEUP)
4112 		iwn_wakeup_intr(sc);
4113 
4114 done:
4115 	/* Re-enable interrupts. */
4116 	if (ifp->if_flags & IFF_UP)
4117 		IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
4118 
4119 	IWN_UNLOCK(sc);
4120 }
4121 
4122 /*
4123  * Update TX scheduler ring when transmitting an 802.11 frame (4965AGN and
4124  * 5000 adapters use a slightly different format).
4125  */
4126 static void
4127 iwn4965_update_sched(struct iwn_softc *sc, int qid, int idx, uint8_t id,
4128     uint16_t len)
4129 {
4130 	uint16_t *w = &sc->sched[qid * IWN4965_SCHED_COUNT + idx];
4131 
4132 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
4133 
4134 	*w = htole16(len + 8);
4135 	bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
4136 	    BUS_DMASYNC_PREWRITE);
4137 	if (idx < IWN_SCHED_WINSZ) {
4138 		*(w + IWN_TX_RING_COUNT) = *w;
4139 		bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
4140 		    BUS_DMASYNC_PREWRITE);
4141 	}
4142 }
4143 
4144 static void
4145 iwn5000_update_sched(struct iwn_softc *sc, int qid, int idx, uint8_t id,
4146     uint16_t len)
4147 {
4148 	uint16_t *w = &sc->sched[qid * IWN5000_SCHED_COUNT + idx];
4149 
4150 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
4151 
4152 	*w = htole16(id << 12 | (len + 8));
4153 	bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
4154 	    BUS_DMASYNC_PREWRITE);
4155 	if (idx < IWN_SCHED_WINSZ) {
4156 		*(w + IWN_TX_RING_COUNT) = *w;
4157 		bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
4158 		    BUS_DMASYNC_PREWRITE);
4159 	}
4160 }
4161 
4162 #ifdef notyet
4163 static void
4164 iwn5000_reset_sched(struct iwn_softc *sc, int qid, int idx)
4165 {
4166 	uint16_t *w = &sc->sched[qid * IWN5000_SCHED_COUNT + idx];
4167 
4168 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
4169 
4170 	*w = (*w & htole16(0xf000)) | htole16(1);
4171 	bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
4172 	    BUS_DMASYNC_PREWRITE);
4173 	if (idx < IWN_SCHED_WINSZ) {
4174 		*(w + IWN_TX_RING_COUNT) = *w;
4175 		bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
4176 		    BUS_DMASYNC_PREWRITE);
4177 	}
4178 }
4179 #endif
4180 
4181 /*
4182  * Check whether OFDM 11g protection will be enabled for the given rate.
4183  *
4184  * The original driver code only enabled protection for OFDM rates.
4185  * It didn't check to see whether it was operating in 11a or 11bg mode.
4186  */
4187 static int
4188 iwn_check_rate_needs_protection(struct iwn_softc *sc,
4189     struct ieee80211vap *vap, uint8_t rate)
4190 {
4191 	struct ieee80211com *ic = vap->iv_ic;
4192 
4193 	/*
4194 	 * Not in 2GHz mode? Then there's no need to enable OFDM
4195 	 * 11bg protection.
4196 	 */
4197 	if (! IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan)) {
4198 		return (0);
4199 	}
4200 
4201 	/*
4202 	 * 11bg protection not enabled? Then don't use it.
4203 	 */
4204 	if ((ic->ic_flags & IEEE80211_F_USEPROT) == 0)
4205 		return (0);
4206 
4207 	/*
4208 	 * If it's an 11n rate - no protection.
4209 	 * We'll do it via a specific 11n check.
4210 	 */
4211 	if (rate & IEEE80211_RATE_MCS) {
4212 		return (0);
4213 	}
4214 
4215 	/*
4216 	 * Do a rate table lookup.  If the PHY is CCK,
4217 	 * don't do protection.
4218 	 */
4219 	if (ieee80211_rate2phytype(ic->ic_rt, rate) == IEEE80211_T_CCK)
4220 		return (0);
4221 
4222 	/*
4223 	 * Yup, enable protection.
4224 	 */
4225 	return (1);
4226 }
4227 
4228 /*
4229  * return a value between 0 and IWN_MAX_TX_RETRIES-1 as an index into
4230  * the link quality table that reflects this particular entry.
4231  */
4232 static int
4233 iwn_tx_rate_to_linkq_offset(struct iwn_softc *sc, struct ieee80211_node *ni,
4234     uint8_t rate)
4235 {
4236 	struct ieee80211_rateset *rs;
4237 	int is_11n;
4238 	int nr;
4239 	int i;
4240 	uint8_t cmp_rate;
4241 
4242 	/*
4243 	 * Figure out if we're using 11n or not here.
4244 	 */
4245 	if (IEEE80211_IS_CHAN_HT(ni->ni_chan) && ni->ni_htrates.rs_nrates > 0)
4246 		is_11n = 1;
4247 	else
4248 		is_11n = 0;
4249 
4250 	/*
4251 	 * Use the correct rate table.
4252 	 */
4253 	if (is_11n) {
4254 		rs = (struct ieee80211_rateset *) &ni->ni_htrates;
4255 		nr = ni->ni_htrates.rs_nrates;
4256 	} else {
4257 		rs = &ni->ni_rates;
4258 		nr = rs->rs_nrates;
4259 	}
4260 
4261 	/*
4262 	 * Find the relevant link quality entry in the table.
4263 	 */
4264 	for (i = 0; i < nr && i < IWN_MAX_TX_RETRIES - 1 ; i++) {
4265 		/*
4266 		 * The link quality table index starts at 0 == highest
4267 		 * rate, so we walk the rate table backwards.
4268 		 */
4269 		cmp_rate = rs->rs_rates[(nr - 1) - i];
4270 		if (rate & IEEE80211_RATE_MCS)
4271 			cmp_rate |= IEEE80211_RATE_MCS;
4272 
4273 #if 0
4274 		DPRINTF(sc, IWN_DEBUG_XMIT, "%s: idx %d: nr=%d, rate=0x%02x, rateentry=0x%02x\n",
4275 		    __func__,
4276 		    i,
4277 		    nr,
4278 		    rate,
4279 		    cmp_rate);
4280 #endif
4281 
4282 		if (cmp_rate == rate)
4283 			return (i);
4284 	}
4285 
4286 	/* Failed? Start at the end */
4287 	return (IWN_MAX_TX_RETRIES - 1);
4288 }
4289 
4290 static int
4291 iwn_tx_data(struct iwn_softc *sc, struct mbuf *m, struct ieee80211_node *ni)
4292 {
4293 	struct iwn_ops *ops = &sc->ops;
4294 	const struct ieee80211_txparam *tp;
4295 	struct ieee80211vap *vap = ni->ni_vap;
4296 	struct ieee80211com *ic = ni->ni_ic;
4297 	struct iwn_node *wn = (void *)ni;
4298 	struct iwn_tx_ring *ring;
4299 	struct iwn_tx_desc *desc;
4300 	struct iwn_tx_data *data;
4301 	struct iwn_tx_cmd *cmd;
4302 	struct iwn_cmd_data *tx;
4303 	struct ieee80211_frame *wh;
4304 	struct ieee80211_key *k = NULL;
4305 	struct mbuf *m1;
4306 	uint32_t flags;
4307 	uint16_t qos;
4308 	u_int hdrlen;
4309 	bus_dma_segment_t *seg, segs[IWN_MAX_SCATTER];
4310 	uint8_t tid, type;
4311 	int ac, i, totlen, error, pad, nsegs = 0, rate;
4312 
4313 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
4314 
4315 	IWN_LOCK_ASSERT(sc);
4316 
4317 	wh = mtod(m, struct ieee80211_frame *);
4318 	hdrlen = ieee80211_anyhdrsize(wh);
4319 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
4320 
4321 	/* Select EDCA Access Category and TX ring for this frame. */
4322 	if (IEEE80211_QOS_HAS_SEQ(wh)) {
4323 		qos = ((const struct ieee80211_qosframe *)wh)->i_qos[0];
4324 		tid = qos & IEEE80211_QOS_TID;
4325 	} else {
4326 		qos = 0;
4327 		tid = 0;
4328 	}
4329 	ac = M_WME_GETAC(m);
4330 	if (m->m_flags & M_AMPDU_MPDU) {
4331 		uint16_t seqno;
4332 		struct ieee80211_tx_ampdu *tap = &ni->ni_tx_ampdu[ac];
4333 
4334 		if (!IEEE80211_AMPDU_RUNNING(tap)) {
4335 			m_freem(m);
4336 			return EINVAL;
4337 		}
4338 
4339 		/*
4340 		 * Queue this frame to the hardware ring that we've
4341 		 * negotiated AMPDU TX on.
4342 		 *
4343 		 * Note that the sequence number must match the TX slot
4344 		 * being used!
4345 		 */
4346 		ac = *(int *)tap->txa_private;
4347 		seqno = ni->ni_txseqs[tid];
4348 		*(uint16_t *)wh->i_seq =
4349 		    htole16(seqno << IEEE80211_SEQ_SEQ_SHIFT);
4350 		ring = &sc->txq[ac];
4351 		if ((seqno % 256) != ring->cur) {
4352 			device_printf(sc->sc_dev,
4353 			    "%s: m=%p: seqno (%d) (%d) != ring index (%d) !\n",
4354 			    __func__,
4355 			    m,
4356 			    seqno,
4357 			    seqno % 256,
4358 			    ring->cur);
4359 		}
4360 		ni->ni_txseqs[tid]++;
4361 	}
4362 	ring = &sc->txq[ac];
4363 	desc = &ring->desc[ring->cur];
4364 	data = &ring->data[ring->cur];
4365 
4366 	/* Choose a TX rate index. */
4367 	tp = &vap->iv_txparms[ieee80211_chan2mode(ni->ni_chan)];
4368 	if (type == IEEE80211_FC0_TYPE_MGT)
4369 		rate = tp->mgmtrate;
4370 	else if (IEEE80211_IS_MULTICAST(wh->i_addr1))
4371 		rate = tp->mcastrate;
4372 	else if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE)
4373 		rate = tp->ucastrate;
4374 	else if (m->m_flags & M_EAPOL)
4375 		rate = tp->mgmtrate;
4376 	else {
4377 		/* XXX pass pktlen */
4378 		(void) ieee80211_ratectl_rate(ni, NULL, 0);
4379 		rate = ni->ni_txrate;
4380 	}
4381 
4382 	/* Encrypt the frame if need be. */
4383 	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
4384 		/* Retrieve key for TX. */
4385 		k = ieee80211_crypto_encap(ni, m);
4386 		if (k == NULL) {
4387 			m_freem(m);
4388 			return ENOBUFS;
4389 		}
4390 		/* 802.11 header may have moved. */
4391 		wh = mtod(m, struct ieee80211_frame *);
4392 	}
4393 	totlen = m->m_pkthdr.len;
4394 
4395 	if (ieee80211_radiotap_active_vap(vap)) {
4396 		struct iwn_tx_radiotap_header *tap = &sc->sc_txtap;
4397 
4398 		tap->wt_flags = 0;
4399 		tap->wt_rate = rate;
4400 		if (k != NULL)
4401 			tap->wt_flags |= IEEE80211_RADIOTAP_F_WEP;
4402 
4403 		ieee80211_radiotap_tx(vap, m);
4404 	}
4405 
4406 	/* Prepare TX firmware command. */
4407 	cmd = &ring->cmd[ring->cur];
4408 	cmd->code = IWN_CMD_TX_DATA;
4409 	cmd->flags = 0;
4410 	cmd->qid = ring->qid;
4411 	cmd->idx = ring->cur;
4412 
4413 	tx = (struct iwn_cmd_data *)cmd->data;
4414 	/* NB: No need to clear tx, all fields are reinitialized here. */
4415 	tx->scratch = 0;	/* clear "scratch" area */
4416 
4417 	flags = 0;
4418 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
4419 		/* Unicast frame, check if an ACK is expected. */
4420 		if (!qos || (qos & IEEE80211_QOS_ACKPOLICY) !=
4421 		    IEEE80211_QOS_ACKPOLICY_NOACK)
4422 			flags |= IWN_TX_NEED_ACK;
4423 	}
4424 	if ((wh->i_fc[0] &
4425 	    (IEEE80211_FC0_TYPE_MASK | IEEE80211_FC0_SUBTYPE_MASK)) ==
4426 	    (IEEE80211_FC0_TYPE_CTL | IEEE80211_FC0_SUBTYPE_BAR))
4427 		flags |= IWN_TX_IMM_BA;		/* Cannot happen yet. */
4428 
4429 	if (wh->i_fc[1] & IEEE80211_FC1_MORE_FRAG)
4430 		flags |= IWN_TX_MORE_FRAG;	/* Cannot happen yet. */
4431 
4432 	/* Check if frame must be protected using RTS/CTS or CTS-to-self. */
4433 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
4434 		/* NB: Group frames are sent using CCK in 802.11b/g. */
4435 		if (totlen + IEEE80211_CRC_LEN > vap->iv_rtsthreshold) {
4436 			flags |= IWN_TX_NEED_RTS;
4437 		} else if (iwn_check_rate_needs_protection(sc, vap, rate)) {
4438 			if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
4439 				flags |= IWN_TX_NEED_CTS;
4440 			else if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
4441 				flags |= IWN_TX_NEED_RTS;
4442 		} else if ((rate & IEEE80211_RATE_MCS) &&
4443 			(ic->ic_htprotmode == IEEE80211_PROT_RTSCTS)) {
4444 			flags |= IWN_TX_NEED_RTS;
4445 		}
4446 
4447 		/* XXX HT protection? */
4448 
4449 		if (flags & (IWN_TX_NEED_RTS | IWN_TX_NEED_CTS)) {
4450 			if (sc->hw_type != IWN_HW_REV_TYPE_4965) {
4451 				/* 5000 autoselects RTS/CTS or CTS-to-self. */
4452 				flags &= ~(IWN_TX_NEED_RTS | IWN_TX_NEED_CTS);
4453 				flags |= IWN_TX_NEED_PROTECTION;
4454 			} else
4455 				flags |= IWN_TX_FULL_TXOP;
4456 		}
4457 	}
4458 
4459 	if (IEEE80211_IS_MULTICAST(wh->i_addr1) ||
4460 	    type != IEEE80211_FC0_TYPE_DATA)
4461 		tx->id = sc->broadcast_id;
4462 	else
4463 		tx->id = wn->id;
4464 
4465 	if (type == IEEE80211_FC0_TYPE_MGT) {
4466 		uint8_t subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
4467 
4468 		/* Tell HW to set timestamp in probe responses. */
4469 		if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
4470 			flags |= IWN_TX_INSERT_TSTAMP;
4471 		if (subtype == IEEE80211_FC0_SUBTYPE_ASSOC_REQ ||
4472 		    subtype == IEEE80211_FC0_SUBTYPE_REASSOC_REQ)
4473 			tx->timeout = htole16(3);
4474 		else
4475 			tx->timeout = htole16(2);
4476 	} else
4477 		tx->timeout = htole16(0);
4478 
4479 	if (hdrlen & 3) {
4480 		/* First segment length must be a multiple of 4. */
4481 		flags |= IWN_TX_NEED_PADDING;
4482 		pad = 4 - (hdrlen & 3);
4483 	} else
4484 		pad = 0;
4485 
4486 	tx->len = htole16(totlen);
4487 	tx->tid = tid;
4488 	tx->rts_ntries = 60;
4489 	tx->data_ntries = 15;
4490 	tx->lifetime = htole32(IWN_LIFETIME_INFINITE);
4491 	tx->rate = iwn_rate_to_plcp(sc, ni, rate);
4492 	if (tx->id == sc->broadcast_id) {
4493 		/* Group or management frame. */
4494 		tx->linkq = 0;
4495 	} else {
4496 		tx->linkq = iwn_tx_rate_to_linkq_offset(sc, ni, rate);
4497 		flags |= IWN_TX_LINKQ;	/* enable MRR */
4498 	}
4499 
4500 	/* Set physical address of "scratch area". */
4501 	tx->loaddr = htole32(IWN_LOADDR(data->scratch_paddr));
4502 	tx->hiaddr = IWN_HIADDR(data->scratch_paddr);
4503 
4504 	/* Copy 802.11 header in TX command. */
4505 	memcpy((uint8_t *)(tx + 1), wh, hdrlen);
4506 
4507 	/* Trim 802.11 header. */
4508 	m_adj(m, hdrlen);
4509 	tx->security = 0;
4510 	tx->flags = htole32(flags);
4511 
4512 	error = bus_dmamap_load_mbuf_sg(ring->data_dmat, data->map, m, segs,
4513 	    &nsegs, BUS_DMA_NOWAIT);
4514 	if (error != 0) {
4515 		if (error != EFBIG) {
4516 			device_printf(sc->sc_dev,
4517 			    "%s: can't map mbuf (error %d)\n", __func__, error);
4518 			m_freem(m);
4519 			return error;
4520 		}
4521 		/* Too many DMA segments, linearize mbuf. */
4522 		m1 = m_collapse(m, M_NOWAIT, IWN_MAX_SCATTER);
4523 		if (m1 == NULL) {
4524 			device_printf(sc->sc_dev,
4525 			    "%s: could not defrag mbuf\n", __func__);
4526 			m_freem(m);
4527 			return ENOBUFS;
4528 		}
4529 		m = m1;
4530 
4531 		error = bus_dmamap_load_mbuf_sg(ring->data_dmat, data->map, m,
4532 		    segs, &nsegs, BUS_DMA_NOWAIT);
4533 		if (error != 0) {
4534 			device_printf(sc->sc_dev,
4535 			    "%s: can't map mbuf (error %d)\n", __func__, error);
4536 			m_freem(m);
4537 			return error;
4538 		}
4539 	}
4540 
4541 	data->m = m;
4542 	data->ni = ni;
4543 
4544 	DPRINTF(sc, IWN_DEBUG_XMIT,
4545 	    "%s: qid %d idx %d len %d nsegs %d flags 0x%08x rate 0x%04x plcp 0x%08x\n",
4546 	    __func__,
4547 	    ring->qid,
4548 	    ring->cur,
4549 	    m->m_pkthdr.len,
4550 	    nsegs,
4551 	    flags,
4552 	    rate,
4553 	    tx->rate);
4554 
4555 	/* Fill TX descriptor. */
4556 	desc->nsegs = 1;
4557 	if (m->m_len != 0)
4558 		desc->nsegs += nsegs;
4559 	/* First DMA segment is used by the TX command. */
4560 	desc->segs[0].addr = htole32(IWN_LOADDR(data->cmd_paddr));
4561 	desc->segs[0].len  = htole16(IWN_HIADDR(data->cmd_paddr) |
4562 	    (4 + sizeof (*tx) + hdrlen + pad) << 4);
4563 	/* Other DMA segments are for data payload. */
4564 	seg = &segs[0];
4565 	for (i = 1; i <= nsegs; i++) {
4566 		desc->segs[i].addr = htole32(IWN_LOADDR(seg->ds_addr));
4567 		desc->segs[i].len  = htole16(IWN_HIADDR(seg->ds_addr) |
4568 		    seg->ds_len << 4);
4569 		seg++;
4570 	}
4571 
4572 	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
4573 	bus_dmamap_sync(ring->data_dmat, ring->cmd_dma.map,
4574 	    BUS_DMASYNC_PREWRITE);
4575 	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
4576 	    BUS_DMASYNC_PREWRITE);
4577 
4578 	/* Update TX scheduler. */
4579 	if (ring->qid >= sc->firstaggqueue)
4580 		ops->update_sched(sc, ring->qid, ring->cur, tx->id, totlen);
4581 
4582 	/* Kick TX ring. */
4583 	ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT;
4584 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, ring->qid << 8 | ring->cur);
4585 
4586 	/* Mark TX ring as full if we reach a certain threshold. */
4587 	if (++ring->queued > IWN_TX_RING_HIMARK)
4588 		sc->qfullmsk |= 1 << ring->qid;
4589 
4590 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
4591 
4592 	return 0;
4593 }
4594 
4595 static int
4596 iwn_tx_data_raw(struct iwn_softc *sc, struct mbuf *m,
4597     struct ieee80211_node *ni, const struct ieee80211_bpf_params *params)
4598 {
4599 	struct iwn_ops *ops = &sc->ops;
4600 //	struct ifnet *ifp = sc->sc_ifp;
4601 	struct ieee80211vap *vap = ni->ni_vap;
4602 //	struct ieee80211com *ic = ifp->if_l2com;
4603 	struct iwn_tx_cmd *cmd;
4604 	struct iwn_cmd_data *tx;
4605 	struct ieee80211_frame *wh;
4606 	struct iwn_tx_ring *ring;
4607 	struct iwn_tx_desc *desc;
4608 	struct iwn_tx_data *data;
4609 	struct mbuf *m1;
4610 	bus_dma_segment_t *seg, segs[IWN_MAX_SCATTER];
4611 	uint32_t flags;
4612 	u_int hdrlen;
4613 	int ac, totlen, error, pad, nsegs = 0, i, rate;
4614 	uint8_t type;
4615 
4616 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
4617 
4618 	IWN_LOCK_ASSERT(sc);
4619 
4620 	wh = mtod(m, struct ieee80211_frame *);
4621 	hdrlen = ieee80211_anyhdrsize(wh);
4622 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
4623 
4624 	ac = params->ibp_pri & 3;
4625 
4626 	ring = &sc->txq[ac];
4627 	desc = &ring->desc[ring->cur];
4628 	data = &ring->data[ring->cur];
4629 
4630 	/* Choose a TX rate. */
4631 	rate = params->ibp_rate0;
4632 	totlen = m->m_pkthdr.len;
4633 
4634 	/* Prepare TX firmware command. */
4635 	cmd = &ring->cmd[ring->cur];
4636 	cmd->code = IWN_CMD_TX_DATA;
4637 	cmd->flags = 0;
4638 	cmd->qid = ring->qid;
4639 	cmd->idx = ring->cur;
4640 
4641 	tx = (struct iwn_cmd_data *)cmd->data;
4642 	/* NB: No need to clear tx, all fields are reinitialized here. */
4643 	tx->scratch = 0;	/* clear "scratch" area */
4644 
4645 	flags = 0;
4646 	if ((params->ibp_flags & IEEE80211_BPF_NOACK) == 0)
4647 		flags |= IWN_TX_NEED_ACK;
4648 	if (params->ibp_flags & IEEE80211_BPF_RTS) {
4649 		if (sc->hw_type != IWN_HW_REV_TYPE_4965) {
4650 			/* 5000 autoselects RTS/CTS or CTS-to-self. */
4651 			flags &= ~IWN_TX_NEED_RTS;
4652 			flags |= IWN_TX_NEED_PROTECTION;
4653 		} else
4654 			flags |= IWN_TX_NEED_RTS | IWN_TX_FULL_TXOP;
4655 	}
4656 	if (params->ibp_flags & IEEE80211_BPF_CTS) {
4657 		if (sc->hw_type != IWN_HW_REV_TYPE_4965) {
4658 			/* 5000 autoselects RTS/CTS or CTS-to-self. */
4659 			flags &= ~IWN_TX_NEED_CTS;
4660 			flags |= IWN_TX_NEED_PROTECTION;
4661 		} else
4662 			flags |= IWN_TX_NEED_CTS | IWN_TX_FULL_TXOP;
4663 	}
4664 	if (type == IEEE80211_FC0_TYPE_MGT) {
4665 		uint8_t subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
4666 
4667 		/* Tell HW to set timestamp in probe responses. */
4668 		if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
4669 			flags |= IWN_TX_INSERT_TSTAMP;
4670 
4671 		if (subtype == IEEE80211_FC0_SUBTYPE_ASSOC_REQ ||
4672 		    subtype == IEEE80211_FC0_SUBTYPE_REASSOC_REQ)
4673 			tx->timeout = htole16(3);
4674 		else
4675 			tx->timeout = htole16(2);
4676 	} else
4677 		tx->timeout = htole16(0);
4678 
4679 	if (hdrlen & 3) {
4680 		/* First segment length must be a multiple of 4. */
4681 		flags |= IWN_TX_NEED_PADDING;
4682 		pad = 4 - (hdrlen & 3);
4683 	} else
4684 		pad = 0;
4685 
4686 	if (ieee80211_radiotap_active_vap(vap)) {
4687 		struct iwn_tx_radiotap_header *tap = &sc->sc_txtap;
4688 
4689 		tap->wt_flags = 0;
4690 		tap->wt_rate = rate;
4691 
4692 		ieee80211_radiotap_tx(vap, m);
4693 	}
4694 
4695 	tx->len = htole16(totlen);
4696 	tx->tid = 0;
4697 	tx->id = sc->broadcast_id;
4698 	tx->rts_ntries = params->ibp_try1;
4699 	tx->data_ntries = params->ibp_try0;
4700 	tx->lifetime = htole32(IWN_LIFETIME_INFINITE);
4701 	tx->rate = iwn_rate_to_plcp(sc, ni, rate);
4702 
4703 	/* Group or management frame. */
4704 	tx->linkq = 0;
4705 
4706 	/* Set physical address of "scratch area". */
4707 	tx->loaddr = htole32(IWN_LOADDR(data->scratch_paddr));
4708 	tx->hiaddr = IWN_HIADDR(data->scratch_paddr);
4709 
4710 	/* Copy 802.11 header in TX command. */
4711 	memcpy((uint8_t *)(tx + 1), wh, hdrlen);
4712 
4713 	/* Trim 802.11 header. */
4714 	m_adj(m, hdrlen);
4715 	tx->security = 0;
4716 	tx->flags = htole32(flags);
4717 
4718 	error = bus_dmamap_load_mbuf_sg(ring->data_dmat, data->map, m, segs,
4719 	    &nsegs, BUS_DMA_NOWAIT);
4720 	if (error != 0) {
4721 		if (error != EFBIG) {
4722 			device_printf(sc->sc_dev,
4723 			    "%s: can't map mbuf (error %d)\n", __func__, error);
4724 			m_freem(m);
4725 			return error;
4726 		}
4727 		/* Too many DMA segments, linearize mbuf. */
4728 		m1 = m_collapse(m, M_NOWAIT, IWN_MAX_SCATTER);
4729 		if (m1 == NULL) {
4730 			device_printf(sc->sc_dev,
4731 			    "%s: could not defrag mbuf\n", __func__);
4732 			m_freem(m);
4733 			return ENOBUFS;
4734 		}
4735 		m = m1;
4736 
4737 		error = bus_dmamap_load_mbuf_sg(ring->data_dmat, data->map, m,
4738 		    segs, &nsegs, BUS_DMA_NOWAIT);
4739 		if (error != 0) {
4740 			device_printf(sc->sc_dev,
4741 			    "%s: can't map mbuf (error %d)\n", __func__, error);
4742 			m_freem(m);
4743 			return error;
4744 		}
4745 	}
4746 
4747 	data->m = m;
4748 	data->ni = ni;
4749 
4750 	DPRINTF(sc, IWN_DEBUG_XMIT, "%s: qid %d idx %d len %d nsegs %d\n",
4751 	    __func__, ring->qid, ring->cur, m->m_pkthdr.len, nsegs);
4752 
4753 	/* Fill TX descriptor. */
4754 	desc->nsegs = 1;
4755 	if (m->m_len != 0)
4756 		desc->nsegs += nsegs;
4757 	/* First DMA segment is used by the TX command. */
4758 	desc->segs[0].addr = htole32(IWN_LOADDR(data->cmd_paddr));
4759 	desc->segs[0].len  = htole16(IWN_HIADDR(data->cmd_paddr) |
4760 	    (4 + sizeof (*tx) + hdrlen + pad) << 4);
4761 	/* Other DMA segments are for data payload. */
4762 	seg = &segs[0];
4763 	for (i = 1; i <= nsegs; i++) {
4764 		desc->segs[i].addr = htole32(IWN_LOADDR(seg->ds_addr));
4765 		desc->segs[i].len  = htole16(IWN_HIADDR(seg->ds_addr) |
4766 		    seg->ds_len << 4);
4767 		seg++;
4768 	}
4769 
4770 	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
4771 	bus_dmamap_sync(ring->data_dmat, ring->cmd_dma.map,
4772 	    BUS_DMASYNC_PREWRITE);
4773 	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
4774 	    BUS_DMASYNC_PREWRITE);
4775 
4776 	/* Update TX scheduler. */
4777 	if (ring->qid >= sc->firstaggqueue)
4778 		ops->update_sched(sc, ring->qid, ring->cur, tx->id, totlen);
4779 
4780 	/* Kick TX ring. */
4781 	ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT;
4782 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, ring->qid << 8 | ring->cur);
4783 
4784 	/* Mark TX ring as full if we reach a certain threshold. */
4785 	if (++ring->queued > IWN_TX_RING_HIMARK)
4786 		sc->qfullmsk |= 1 << ring->qid;
4787 
4788 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
4789 
4790 	return 0;
4791 }
4792 
4793 static int
4794 iwn_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
4795     const struct ieee80211_bpf_params *params)
4796 {
4797 	struct ieee80211com *ic = ni->ni_ic;
4798 	struct ifnet *ifp = ic->ic_ifp;
4799 	struct iwn_softc *sc = ifp->if_softc;
4800 	int error = 0;
4801 
4802 	DPRINTF(sc, IWN_DEBUG_XMIT | IWN_DEBUG_TRACE, "->%s begin\n", __func__);
4803 
4804 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
4805 		ieee80211_free_node(ni);
4806 		m_freem(m);
4807 		return ENETDOWN;
4808 	}
4809 
4810 	IWN_LOCK(sc);
4811 	if (params == NULL) {
4812 		/*
4813 		 * Legacy path; interpret frame contents to decide
4814 		 * precisely how to send the frame.
4815 		 */
4816 		error = iwn_tx_data(sc, m, ni);
4817 	} else {
4818 		/*
4819 		 * Caller supplied explicit parameters to use in
4820 		 * sending the frame.
4821 		 */
4822 		error = iwn_tx_data_raw(sc, m, ni, params);
4823 	}
4824 	if (error != 0) {
4825 		/* NB: m is reclaimed on tx failure */
4826 		ieee80211_free_node(ni);
4827 		if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
4828 	}
4829 	sc->sc_tx_timer = 5;
4830 
4831 	IWN_UNLOCK(sc);
4832 
4833 	DPRINTF(sc, IWN_DEBUG_TRACE | IWN_DEBUG_XMIT, "->%s: end\n",__func__);
4834 
4835 	return error;
4836 }
4837 
4838 static void
4839 iwn_start(struct ifnet *ifp)
4840 {
4841 	struct iwn_softc *sc = ifp->if_softc;
4842 
4843 	IWN_LOCK(sc);
4844 	iwn_start_locked(ifp);
4845 	IWN_UNLOCK(sc);
4846 }
4847 
4848 static void
4849 iwn_start_locked(struct ifnet *ifp)
4850 {
4851 	struct iwn_softc *sc = ifp->if_softc;
4852 	struct ieee80211_node *ni;
4853 	struct mbuf *m;
4854 
4855 	IWN_LOCK_ASSERT(sc);
4856 
4857 	DPRINTF(sc, IWN_DEBUG_XMIT, "%s: called\n", __func__);
4858 
4859 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 ||
4860 	    (ifp->if_drv_flags & IFF_DRV_OACTIVE))
4861 		return;
4862 
4863 	for (;;) {
4864 		if (sc->qfullmsk != 0) {
4865 			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
4866 			break;
4867 		}
4868 		IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
4869 		if (m == NULL)
4870 			break;
4871 		ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
4872 		if (iwn_tx_data(sc, m, ni) != 0) {
4873 			ieee80211_free_node(ni);
4874 			if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
4875 			continue;
4876 		}
4877 		sc->sc_tx_timer = 5;
4878 	}
4879 
4880 	DPRINTF(sc, IWN_DEBUG_XMIT, "%s: done\n", __func__);
4881 }
4882 
4883 static void
4884 iwn_watchdog(void *arg)
4885 {
4886 	struct iwn_softc *sc = arg;
4887 	struct ifnet *ifp = sc->sc_ifp;
4888 	struct ieee80211com *ic = ifp->if_l2com;
4889 
4890 	IWN_LOCK_ASSERT(sc);
4891 
4892 	KASSERT(ifp->if_drv_flags & IFF_DRV_RUNNING, ("not running"));
4893 
4894 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
4895 
4896 	if (sc->sc_tx_timer > 0) {
4897 		if (--sc->sc_tx_timer == 0) {
4898 			if_printf(ifp, "device timeout\n");
4899 			ieee80211_runtask(ic, &sc->sc_reinit_task);
4900 			return;
4901 		}
4902 	}
4903 	callout_reset(&sc->watchdog_to, hz, iwn_watchdog, sc);
4904 }
4905 
4906 static int
4907 iwn_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
4908 {
4909 	struct iwn_softc *sc = ifp->if_softc;
4910 	struct ieee80211com *ic = ifp->if_l2com;
4911 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
4912 	struct ifreq *ifr = (struct ifreq *) data;
4913 	int error = 0, startall = 0, stop = 0;
4914 
4915 	switch (cmd) {
4916 	case SIOCGIFADDR:
4917 		error = ether_ioctl(ifp, cmd, data);
4918 		break;
4919 	case SIOCSIFFLAGS:
4920 		IWN_LOCK(sc);
4921 		if (ifp->if_flags & IFF_UP) {
4922 			if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
4923 				iwn_init_locked(sc);
4924 				if (IWN_READ(sc, IWN_GP_CNTRL) & IWN_GP_CNTRL_RFKILL)
4925 					startall = 1;
4926 				else
4927 					stop = 1;
4928 			}
4929 		} else {
4930 			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
4931 				iwn_stop_locked(sc);
4932 		}
4933 		IWN_UNLOCK(sc);
4934 		if (startall)
4935 			ieee80211_start_all(ic);
4936 		else if (vap != NULL && stop)
4937 			ieee80211_stop(vap);
4938 		break;
4939 	case SIOCGIFMEDIA:
4940 		error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
4941 		break;
4942 	case SIOCGIWNSTATS:
4943 		IWN_LOCK(sc);
4944 		/* XXX validate permissions/memory/etc? */
4945 		error = copyout(&sc->last_stat, ifr->ifr_data,
4946 		    sizeof(struct iwn_stats));
4947 		IWN_UNLOCK(sc);
4948 		break;
4949 	case SIOCZIWNSTATS:
4950 		IWN_LOCK(sc);
4951 		memset(&sc->last_stat, 0, sizeof(struct iwn_stats));
4952 		IWN_UNLOCK(sc);
4953 		error = 0;
4954 		break;
4955 	default:
4956 		error = EINVAL;
4957 		break;
4958 	}
4959 	return error;
4960 }
4961 
4962 /*
4963  * Send a command to the firmware.
4964  */
4965 static int
4966 iwn_cmd(struct iwn_softc *sc, int code, const void *buf, int size, int async)
4967 {
4968 	struct iwn_tx_ring *ring;
4969 	struct iwn_tx_desc *desc;
4970 	struct iwn_tx_data *data;
4971 	struct iwn_tx_cmd *cmd;
4972 	struct mbuf *m;
4973 	bus_addr_t paddr;
4974 	int totlen, error;
4975 	int cmd_queue_num;
4976 
4977 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
4978 
4979 	if (async == 0)
4980 		IWN_LOCK_ASSERT(sc);
4981 
4982 	if (sc->sc_flags & IWN_FLAG_PAN_SUPPORT)
4983 		cmd_queue_num = IWN_PAN_CMD_QUEUE;
4984 	else
4985 		cmd_queue_num = IWN_CMD_QUEUE_NUM;
4986 
4987 	ring = &sc->txq[cmd_queue_num];
4988 	desc = &ring->desc[ring->cur];
4989 	data = &ring->data[ring->cur];
4990 	totlen = 4 + size;
4991 
4992 	if (size > sizeof cmd->data) {
4993 		/* Command is too large to fit in a descriptor. */
4994 		if (totlen > MCLBYTES)
4995 			return EINVAL;
4996 		m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, MJUMPAGESIZE);
4997 		if (m == NULL)
4998 			return ENOMEM;
4999 		cmd = mtod(m, struct iwn_tx_cmd *);
5000 		error = bus_dmamap_load(ring->data_dmat, data->map, cmd,
5001 		    totlen, iwn_dma_map_addr, &paddr, BUS_DMA_NOWAIT);
5002 		if (error != 0) {
5003 			m_freem(m);
5004 			return error;
5005 		}
5006 		data->m = m;
5007 	} else {
5008 		cmd = &ring->cmd[ring->cur];
5009 		paddr = data->cmd_paddr;
5010 	}
5011 
5012 	cmd->code = code;
5013 	cmd->flags = 0;
5014 	cmd->qid = ring->qid;
5015 	cmd->idx = ring->cur;
5016 	memcpy(cmd->data, buf, size);
5017 
5018 	desc->nsegs = 1;
5019 	desc->segs[0].addr = htole32(IWN_LOADDR(paddr));
5020 	desc->segs[0].len  = htole16(IWN_HIADDR(paddr) | totlen << 4);
5021 
5022 	DPRINTF(sc, IWN_DEBUG_CMD, "%s: %s (0x%x) flags %d qid %d idx %d\n",
5023 	    __func__, iwn_intr_str(cmd->code), cmd->code,
5024 	    cmd->flags, cmd->qid, cmd->idx);
5025 
5026 	if (size > sizeof cmd->data) {
5027 		bus_dmamap_sync(ring->data_dmat, data->map,
5028 		    BUS_DMASYNC_PREWRITE);
5029 	} else {
5030 		bus_dmamap_sync(ring->data_dmat, ring->cmd_dma.map,
5031 		    BUS_DMASYNC_PREWRITE);
5032 	}
5033 	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
5034 	    BUS_DMASYNC_PREWRITE);
5035 
5036 	/* Kick command ring. */
5037 	ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT;
5038 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, ring->qid << 8 | ring->cur);
5039 
5040 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
5041 
5042 	return async ? 0 : msleep(desc, &sc->sc_mtx, PCATCH, "iwncmd", hz);
5043 }
5044 
5045 static int
5046 iwn4965_add_node(struct iwn_softc *sc, struct iwn_node_info *node, int async)
5047 {
5048 	struct iwn4965_node_info hnode;
5049 	caddr_t src, dst;
5050 
5051 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5052 
5053 	/*
5054 	 * We use the node structure for 5000 Series internally (it is
5055 	 * a superset of the one for 4965AGN). We thus copy the common
5056 	 * fields before sending the command.
5057 	 */
5058 	src = (caddr_t)node;
5059 	dst = (caddr_t)&hnode;
5060 	memcpy(dst, src, 48);
5061 	/* Skip TSC, RX MIC and TX MIC fields from ``src''. */
5062 	memcpy(dst + 48, src + 72, 20);
5063 	return iwn_cmd(sc, IWN_CMD_ADD_NODE, &hnode, sizeof hnode, async);
5064 }
5065 
5066 static int
5067 iwn5000_add_node(struct iwn_softc *sc, struct iwn_node_info *node, int async)
5068 {
5069 
5070 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5071 
5072 	/* Direct mapping. */
5073 	return iwn_cmd(sc, IWN_CMD_ADD_NODE, node, sizeof (*node), async);
5074 }
5075 
5076 static int
5077 iwn_set_link_quality(struct iwn_softc *sc, struct ieee80211_node *ni)
5078 {
5079 #define	RV(v)	((v) & IEEE80211_RATE_VAL)
5080 	struct iwn_node *wn = (void *)ni;
5081 	struct ieee80211_rateset *rs;
5082 	struct iwn_cmd_link_quality linkq;
5083 	int i, rate, txrate;
5084 	int is_11n;
5085 
5086 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
5087 
5088 	memset(&linkq, 0, sizeof linkq);
5089 	linkq.id = wn->id;
5090 	linkq.antmsk_1stream = iwn_get_1stream_tx_antmask(sc);
5091 	linkq.antmsk_2stream = iwn_get_2stream_tx_antmask(sc);
5092 
5093 	linkq.ampdu_max = 32;		/* XXX negotiated? */
5094 	linkq.ampdu_threshold = 3;
5095 	linkq.ampdu_limit = htole16(4000);	/* 4ms */
5096 
5097 	DPRINTF(sc, IWN_DEBUG_XMIT,
5098 	    "%s: 1stream antenna=0x%02x, 2stream antenna=0x%02x, ntxstreams=%d\n",
5099 	    __func__,
5100 	    linkq.antmsk_1stream,
5101 	    linkq.antmsk_2stream,
5102 	    sc->ntxchains);
5103 
5104 	/*
5105 	 * Are we using 11n rates? Ensure the channel is
5106 	 * 11n _and_ we have some 11n rates, or don't
5107 	 * try.
5108 	 */
5109 	if (IEEE80211_IS_CHAN_HT(ni->ni_chan) && ni->ni_htrates.rs_nrates > 0) {
5110 		rs = (struct ieee80211_rateset *) &ni->ni_htrates;
5111 		is_11n = 1;
5112 	} else {
5113 		rs = &ni->ni_rates;
5114 		is_11n = 0;
5115 	}
5116 
5117 	/* Start at highest available bit-rate. */
5118 	/*
5119 	 * XXX this is all very dirty!
5120 	 */
5121 	if (is_11n)
5122 		txrate = ni->ni_htrates.rs_nrates - 1;
5123 	else
5124 		txrate = rs->rs_nrates - 1;
5125 	for (i = 0; i < IWN_MAX_TX_RETRIES; i++) {
5126 		uint32_t plcp;
5127 
5128 		/*
5129 		 * XXX TODO: ensure the last two slots are the two lowest
5130 		 * rate entries, just for now.
5131 		 */
5132 		if (i == 14 || i == 15)
5133 			txrate = 0;
5134 
5135 		if (is_11n)
5136 			rate = IEEE80211_RATE_MCS | rs->rs_rates[txrate];
5137 		else
5138 			rate = RV(rs->rs_rates[txrate]);
5139 
5140 		/* Do rate -> PLCP config mapping */
5141 		plcp = iwn_rate_to_plcp(sc, ni, rate);
5142 		linkq.retry[i] = plcp;
5143 		DPRINTF(sc, IWN_DEBUG_XMIT,
5144 		    "%s: i=%d, txrate=%d, rate=0x%02x, plcp=0x%08x\n",
5145 		    __func__,
5146 		    i,
5147 		    txrate,
5148 		    rate,
5149 		    le32toh(plcp));
5150 
5151 		/*
5152 		 * The mimo field is an index into the table which
5153 		 * indicates the first index where it and subsequent entries
5154 		 * will not be using MIMO.
5155 		 *
5156 		 * Since we're filling linkq from 0..15 and we're filling
5157 		 * from the higest MCS rates to the lowest rates, if we
5158 		 * _are_ doing a dual-stream rate, set mimo to idx+1 (ie,
5159 		 * the next entry.)  That way if the next entry is a non-MIMO
5160 		 * entry, we're already pointing at it.
5161 		 */
5162 		if ((le32toh(plcp) & IWN_RFLAG_MCS) &&
5163 		    RV(le32toh(plcp)) > 7)
5164 			linkq.mimo = i + 1;
5165 
5166 		/* Next retry at immediate lower bit-rate. */
5167 		if (txrate > 0)
5168 			txrate--;
5169 	}
5170 	/*
5171 	 * If we reached the end of the list and indeed we hit
5172 	 * all MIMO rates (eg 5300 doing MCS23-15) then yes,
5173 	 * set mimo to 15.  Setting it to 16 panics the firmware.
5174 	 */
5175 	if (linkq.mimo > 15)
5176 		linkq.mimo = 15;
5177 
5178 	DPRINTF(sc, IWN_DEBUG_XMIT, "%s: mimo = %d\n", __func__, linkq.mimo);
5179 
5180 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
5181 
5182 	return iwn_cmd(sc, IWN_CMD_LINK_QUALITY, &linkq, sizeof linkq, 1);
5183 #undef	RV
5184 }
5185 
5186 /*
5187  * Broadcast node is used to send group-addressed and management frames.
5188  */
5189 static int
5190 iwn_add_broadcast_node(struct iwn_softc *sc, int async)
5191 {
5192 	struct iwn_ops *ops = &sc->ops;
5193 	struct ifnet *ifp = sc->sc_ifp;
5194 	struct ieee80211com *ic = ifp->if_l2com;
5195 	struct iwn_node_info node;
5196 	struct iwn_cmd_link_quality linkq;
5197 	uint8_t txant;
5198 	int i, error;
5199 
5200 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
5201 
5202 	sc->rxon = &sc->rx_on[IWN_RXON_BSS_CTX];
5203 
5204 	memset(&node, 0, sizeof node);
5205 	IEEE80211_ADDR_COPY(node.macaddr, ifp->if_broadcastaddr);
5206 	node.id = sc->broadcast_id;
5207 	DPRINTF(sc, IWN_DEBUG_RESET, "%s: adding broadcast node\n", __func__);
5208 	if ((error = ops->add_node(sc, &node, async)) != 0)
5209 		return error;
5210 
5211 	/* Use the first valid TX antenna. */
5212 	txant = IWN_LSB(sc->txchainmask);
5213 
5214 	memset(&linkq, 0, sizeof linkq);
5215 	linkq.id = sc->broadcast_id;
5216 	linkq.antmsk_1stream = iwn_get_1stream_tx_antmask(sc);
5217 	linkq.antmsk_2stream = iwn_get_2stream_tx_antmask(sc);
5218 	linkq.ampdu_max = 64;
5219 	linkq.ampdu_threshold = 3;
5220 	linkq.ampdu_limit = htole16(4000);	/* 4ms */
5221 
5222 	/* Use lowest mandatory bit-rate. */
5223 	/* XXX rate table lookup? */
5224 	if (IEEE80211_IS_CHAN_5GHZ(ic->ic_curchan))
5225 		linkq.retry[0] = htole32(0xd);
5226 	else
5227 		linkq.retry[0] = htole32(10 | IWN_RFLAG_CCK);
5228 	linkq.retry[0] |= htole32(IWN_RFLAG_ANT(txant));
5229 	/* Use same bit-rate for all TX retries. */
5230 	for (i = 1; i < IWN_MAX_TX_RETRIES; i++) {
5231 		linkq.retry[i] = linkq.retry[0];
5232 	}
5233 
5234 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
5235 
5236 	return iwn_cmd(sc, IWN_CMD_LINK_QUALITY, &linkq, sizeof linkq, async);
5237 }
5238 
5239 static int
5240 iwn_updateedca(struct ieee80211com *ic)
5241 {
5242 #define IWN_EXP2(x)	((1 << (x)) - 1)	/* CWmin = 2^ECWmin - 1 */
5243 	struct iwn_softc *sc = ic->ic_ifp->if_softc;
5244 	struct iwn_edca_params cmd;
5245 	int aci;
5246 
5247 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
5248 
5249 	memset(&cmd, 0, sizeof cmd);
5250 	cmd.flags = htole32(IWN_EDCA_UPDATE);
5251 	for (aci = 0; aci < WME_NUM_AC; aci++) {
5252 		const struct wmeParams *ac =
5253 		    &ic->ic_wme.wme_chanParams.cap_wmeParams[aci];
5254 		cmd.ac[aci].aifsn = ac->wmep_aifsn;
5255 		cmd.ac[aci].cwmin = htole16(IWN_EXP2(ac->wmep_logcwmin));
5256 		cmd.ac[aci].cwmax = htole16(IWN_EXP2(ac->wmep_logcwmax));
5257 		cmd.ac[aci].txoplimit =
5258 		    htole16(IEEE80211_TXOP_TO_US(ac->wmep_txopLimit));
5259 	}
5260 	IEEE80211_UNLOCK(ic);
5261 	IWN_LOCK(sc);
5262 	(void)iwn_cmd(sc, IWN_CMD_EDCA_PARAMS, &cmd, sizeof cmd, 1);
5263 	IWN_UNLOCK(sc);
5264 	IEEE80211_LOCK(ic);
5265 
5266 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
5267 
5268 	return 0;
5269 #undef IWN_EXP2
5270 }
5271 
5272 static void
5273 iwn_update_mcast(struct ifnet *ifp)
5274 {
5275 	/* Ignore */
5276 }
5277 
5278 static void
5279 iwn_set_led(struct iwn_softc *sc, uint8_t which, uint8_t off, uint8_t on)
5280 {
5281 	struct iwn_cmd_led led;
5282 
5283 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5284 
5285 #if 0
5286 	/* XXX don't set LEDs during scan? */
5287 	if (sc->sc_is_scanning)
5288 		return;
5289 #endif
5290 
5291 	/* Clear microcode LED ownership. */
5292 	IWN_CLRBITS(sc, IWN_LED, IWN_LED_BSM_CTRL);
5293 
5294 	led.which = which;
5295 	led.unit = htole32(10000);	/* on/off in unit of 100ms */
5296 	led.off = off;
5297 	led.on = on;
5298 	(void)iwn_cmd(sc, IWN_CMD_SET_LED, &led, sizeof led, 1);
5299 }
5300 
5301 /*
5302  * Set the critical temperature at which the firmware will stop the radio
5303  * and notify us.
5304  */
5305 static int
5306 iwn_set_critical_temp(struct iwn_softc *sc)
5307 {
5308 	struct iwn_critical_temp crit;
5309 	int32_t temp;
5310 
5311 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5312 
5313 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_CTEMP_STOP_RF);
5314 
5315 	if (sc->hw_type == IWN_HW_REV_TYPE_5150)
5316 		temp = (IWN_CTOK(110) - sc->temp_off) * -5;
5317 	else if (sc->hw_type == IWN_HW_REV_TYPE_4965)
5318 		temp = IWN_CTOK(110);
5319 	else
5320 		temp = 110;
5321 	memset(&crit, 0, sizeof crit);
5322 	crit.tempR = htole32(temp);
5323 	DPRINTF(sc, IWN_DEBUG_RESET, "setting critical temp to %d\n", temp);
5324 	return iwn_cmd(sc, IWN_CMD_SET_CRITICAL_TEMP, &crit, sizeof crit, 0);
5325 }
5326 
5327 static int
5328 iwn_set_timing(struct iwn_softc *sc, struct ieee80211_node *ni)
5329 {
5330 	struct iwn_cmd_timing cmd;
5331 	uint64_t val, mod;
5332 
5333 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5334 
5335 	memset(&cmd, 0, sizeof cmd);
5336 	memcpy(&cmd.tstamp, ni->ni_tstamp.data, sizeof (uint64_t));
5337 	cmd.bintval = htole16(ni->ni_intval);
5338 	cmd.lintval = htole16(10);
5339 
5340 	/* Compute remaining time until next beacon. */
5341 	val = (uint64_t)ni->ni_intval * IEEE80211_DUR_TU;
5342 	mod = le64toh(cmd.tstamp) % val;
5343 	cmd.binitval = htole32((uint32_t)(val - mod));
5344 
5345 	DPRINTF(sc, IWN_DEBUG_RESET, "timing bintval=%u tstamp=%ju, init=%u\n",
5346 	    ni->ni_intval, le64toh(cmd.tstamp), (uint32_t)(val - mod));
5347 
5348 	return iwn_cmd(sc, IWN_CMD_TIMING, &cmd, sizeof cmd, 1);
5349 }
5350 
5351 static void
5352 iwn4965_power_calibration(struct iwn_softc *sc, int temp)
5353 {
5354 	struct ifnet *ifp = sc->sc_ifp;
5355 	struct ieee80211com *ic = ifp->if_l2com;
5356 
5357 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5358 
5359 	/* Adjust TX power if need be (delta >= 3 degC). */
5360 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: temperature %d->%d\n",
5361 	    __func__, sc->temp, temp);
5362 	if (abs(temp - sc->temp) >= 3) {
5363 		/* Record temperature of last calibration. */
5364 		sc->temp = temp;
5365 		(void)iwn4965_set_txpower(sc, ic->ic_bsschan, 1);
5366 	}
5367 }
5368 
5369 /*
5370  * Set TX power for current channel (each rate has its own power settings).
5371  * This function takes into account the regulatory information from EEPROM,
5372  * the current temperature and the current voltage.
5373  */
5374 static int
5375 iwn4965_set_txpower(struct iwn_softc *sc, struct ieee80211_channel *ch,
5376     int async)
5377 {
5378 /* Fixed-point arithmetic division using a n-bit fractional part. */
5379 #define fdivround(a, b, n)	\
5380 	((((1 << n) * (a)) / (b) + (1 << n) / 2) / (1 << n))
5381 /* Linear interpolation. */
5382 #define interpolate(x, x1, y1, x2, y2, n)	\
5383 	((y1) + fdivround(((int)(x) - (x1)) * ((y2) - (y1)), (x2) - (x1), n))
5384 
5385 	static const int tdiv[IWN_NATTEN_GROUPS] = { 9, 8, 8, 8, 6 };
5386 	struct iwn_ucode_info *uc = &sc->ucode_info;
5387 	struct iwn4965_cmd_txpower cmd;
5388 	struct iwn4965_eeprom_chan_samples *chans;
5389 	const uint8_t *rf_gain, *dsp_gain;
5390 	int32_t vdiff, tdiff;
5391 	int i, c, grp, maxpwr;
5392 	uint8_t chan;
5393 
5394 	sc->rxon = &sc->rx_on[IWN_RXON_BSS_CTX];
5395 	/* Retrieve current channel from last RXON. */
5396 	chan = sc->rxon->chan;
5397 	DPRINTF(sc, IWN_DEBUG_RESET, "setting TX power for channel %d\n",
5398 	    chan);
5399 
5400 	memset(&cmd, 0, sizeof cmd);
5401 	cmd.band = IEEE80211_IS_CHAN_5GHZ(ch) ? 0 : 1;
5402 	cmd.chan = chan;
5403 
5404 	if (IEEE80211_IS_CHAN_5GHZ(ch)) {
5405 		maxpwr   = sc->maxpwr5GHz;
5406 		rf_gain  = iwn4965_rf_gain_5ghz;
5407 		dsp_gain = iwn4965_dsp_gain_5ghz;
5408 	} else {
5409 		maxpwr   = sc->maxpwr2GHz;
5410 		rf_gain  = iwn4965_rf_gain_2ghz;
5411 		dsp_gain = iwn4965_dsp_gain_2ghz;
5412 	}
5413 
5414 	/* Compute voltage compensation. */
5415 	vdiff = ((int32_t)le32toh(uc->volt) - sc->eeprom_voltage) / 7;
5416 	if (vdiff > 0)
5417 		vdiff *= 2;
5418 	if (abs(vdiff) > 2)
5419 		vdiff = 0;
5420 	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
5421 	    "%s: voltage compensation=%d (UCODE=%d, EEPROM=%d)\n",
5422 	    __func__, vdiff, le32toh(uc->volt), sc->eeprom_voltage);
5423 
5424 	/* Get channel attenuation group. */
5425 	if (chan <= 20)		/* 1-20 */
5426 		grp = 4;
5427 	else if (chan <= 43)	/* 34-43 */
5428 		grp = 0;
5429 	else if (chan <= 70)	/* 44-70 */
5430 		grp = 1;
5431 	else if (chan <= 124)	/* 71-124 */
5432 		grp = 2;
5433 	else			/* 125-200 */
5434 		grp = 3;
5435 	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
5436 	    "%s: chan %d, attenuation group=%d\n", __func__, chan, grp);
5437 
5438 	/* Get channel sub-band. */
5439 	for (i = 0; i < IWN_NBANDS; i++)
5440 		if (sc->bands[i].lo != 0 &&
5441 		    sc->bands[i].lo <= chan && chan <= sc->bands[i].hi)
5442 			break;
5443 	if (i == IWN_NBANDS)	/* Can't happen in real-life. */
5444 		return EINVAL;
5445 	chans = sc->bands[i].chans;
5446 	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
5447 	    "%s: chan %d sub-band=%d\n", __func__, chan, i);
5448 
5449 	for (c = 0; c < 2; c++) {
5450 		uint8_t power, gain, temp;
5451 		int maxchpwr, pwr, ridx, idx;
5452 
5453 		power = interpolate(chan,
5454 		    chans[0].num, chans[0].samples[c][1].power,
5455 		    chans[1].num, chans[1].samples[c][1].power, 1);
5456 		gain  = interpolate(chan,
5457 		    chans[0].num, chans[0].samples[c][1].gain,
5458 		    chans[1].num, chans[1].samples[c][1].gain, 1);
5459 		temp  = interpolate(chan,
5460 		    chans[0].num, chans[0].samples[c][1].temp,
5461 		    chans[1].num, chans[1].samples[c][1].temp, 1);
5462 		DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
5463 		    "%s: Tx chain %d: power=%d gain=%d temp=%d\n",
5464 		    __func__, c, power, gain, temp);
5465 
5466 		/* Compute temperature compensation. */
5467 		tdiff = ((sc->temp - temp) * 2) / tdiv[grp];
5468 		DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
5469 		    "%s: temperature compensation=%d (current=%d, EEPROM=%d)\n",
5470 		    __func__, tdiff, sc->temp, temp);
5471 
5472 		for (ridx = 0; ridx <= IWN_RIDX_MAX; ridx++) {
5473 			/* Convert dBm to half-dBm. */
5474 			maxchpwr = sc->maxpwr[chan] * 2;
5475 			if ((ridx / 8) & 1)
5476 				maxchpwr -= 6;	/* MIMO 2T: -3dB */
5477 
5478 			pwr = maxpwr;
5479 
5480 			/* Adjust TX power based on rate. */
5481 			if ((ridx % 8) == 5)
5482 				pwr -= 15;	/* OFDM48: -7.5dB */
5483 			else if ((ridx % 8) == 6)
5484 				pwr -= 17;	/* OFDM54: -8.5dB */
5485 			else if ((ridx % 8) == 7)
5486 				pwr -= 20;	/* OFDM60: -10dB */
5487 			else
5488 				pwr -= 10;	/* Others: -5dB */
5489 
5490 			/* Do not exceed channel max TX power. */
5491 			if (pwr > maxchpwr)
5492 				pwr = maxchpwr;
5493 
5494 			idx = gain - (pwr - power) - tdiff - vdiff;
5495 			if ((ridx / 8) & 1)	/* MIMO */
5496 				idx += (int32_t)le32toh(uc->atten[grp][c]);
5497 
5498 			if (cmd.band == 0)
5499 				idx += 9;	/* 5GHz */
5500 			if (ridx == IWN_RIDX_MAX)
5501 				idx += 5;	/* CCK */
5502 
5503 			/* Make sure idx stays in a valid range. */
5504 			if (idx < 0)
5505 				idx = 0;
5506 			else if (idx > IWN4965_MAX_PWR_INDEX)
5507 				idx = IWN4965_MAX_PWR_INDEX;
5508 
5509 			DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
5510 			    "%s: Tx chain %d, rate idx %d: power=%d\n",
5511 			    __func__, c, ridx, idx);
5512 			cmd.power[ridx].rf_gain[c] = rf_gain[idx];
5513 			cmd.power[ridx].dsp_gain[c] = dsp_gain[idx];
5514 		}
5515 	}
5516 
5517 	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
5518 	    "%s: set tx power for chan %d\n", __func__, chan);
5519 	return iwn_cmd(sc, IWN_CMD_TXPOWER, &cmd, sizeof cmd, async);
5520 
5521 #undef interpolate
5522 #undef fdivround
5523 }
5524 
5525 static int
5526 iwn5000_set_txpower(struct iwn_softc *sc, struct ieee80211_channel *ch,
5527     int async)
5528 {
5529 	struct iwn5000_cmd_txpower cmd;
5530 	int cmdid;
5531 
5532 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5533 
5534 	/*
5535 	 * TX power calibration is handled automatically by the firmware
5536 	 * for 5000 Series.
5537 	 */
5538 	memset(&cmd, 0, sizeof cmd);
5539 	cmd.global_limit = 2 * IWN5000_TXPOWER_MAX_DBM;	/* 16 dBm */
5540 	cmd.flags = IWN5000_TXPOWER_NO_CLOSED;
5541 	cmd.srv_limit = IWN5000_TXPOWER_AUTO;
5542 	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_XMIT,
5543 	    "%s: setting TX power; rev=%d\n",
5544 	    __func__,
5545 	    IWN_UCODE_API(sc->ucode_rev));
5546 	if (IWN_UCODE_API(sc->ucode_rev) == 1)
5547 		cmdid = IWN_CMD_TXPOWER_DBM_V1;
5548 	else
5549 		cmdid = IWN_CMD_TXPOWER_DBM;
5550 	return iwn_cmd(sc, cmdid, &cmd, sizeof cmd, async);
5551 }
5552 
5553 /*
5554  * Retrieve the maximum RSSI (in dBm) among receivers.
5555  */
5556 static int
5557 iwn4965_get_rssi(struct iwn_softc *sc, struct iwn_rx_stat *stat)
5558 {
5559 	struct iwn4965_rx_phystat *phy = (void *)stat->phybuf;
5560 	uint8_t mask, agc;
5561 	int rssi;
5562 
5563 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5564 
5565 	mask = (le16toh(phy->antenna) >> 4) & IWN_ANT_ABC;
5566 	agc  = (le16toh(phy->agc) >> 7) & 0x7f;
5567 
5568 	rssi = 0;
5569 	if (mask & IWN_ANT_A)
5570 		rssi = MAX(rssi, phy->rssi[0]);
5571 	if (mask & IWN_ANT_B)
5572 		rssi = MAX(rssi, phy->rssi[2]);
5573 	if (mask & IWN_ANT_C)
5574 		rssi = MAX(rssi, phy->rssi[4]);
5575 
5576 	DPRINTF(sc, IWN_DEBUG_RECV,
5577 	    "%s: agc %d mask 0x%x rssi %d %d %d result %d\n", __func__, agc,
5578 	    mask, phy->rssi[0], phy->rssi[2], phy->rssi[4],
5579 	    rssi - agc - IWN_RSSI_TO_DBM);
5580 	return rssi - agc - IWN_RSSI_TO_DBM;
5581 }
5582 
5583 static int
5584 iwn5000_get_rssi(struct iwn_softc *sc, struct iwn_rx_stat *stat)
5585 {
5586 	struct iwn5000_rx_phystat *phy = (void *)stat->phybuf;
5587 	uint8_t agc;
5588 	int rssi;
5589 
5590 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5591 
5592 	agc = (le32toh(phy->agc) >> 9) & 0x7f;
5593 
5594 	rssi = MAX(le16toh(phy->rssi[0]) & 0xff,
5595 		   le16toh(phy->rssi[1]) & 0xff);
5596 	rssi = MAX(le16toh(phy->rssi[2]) & 0xff, rssi);
5597 
5598 	DPRINTF(sc, IWN_DEBUG_RECV,
5599 	    "%s: agc %d rssi %d %d %d result %d\n", __func__, agc,
5600 	    phy->rssi[0], phy->rssi[1], phy->rssi[2],
5601 	    rssi - agc - IWN_RSSI_TO_DBM);
5602 	return rssi - agc - IWN_RSSI_TO_DBM;
5603 }
5604 
5605 /*
5606  * Retrieve the average noise (in dBm) among receivers.
5607  */
5608 static int
5609 iwn_get_noise(const struct iwn_rx_general_stats *stats)
5610 {
5611 	int i, total, nbant, noise;
5612 
5613 	total = nbant = 0;
5614 	for (i = 0; i < 3; i++) {
5615 		if ((noise = le32toh(stats->noise[i]) & 0xff) == 0)
5616 			continue;
5617 		total += noise;
5618 		nbant++;
5619 	}
5620 	/* There should be at least one antenna but check anyway. */
5621 	return (nbant == 0) ? -127 : (total / nbant) - 107;
5622 }
5623 
5624 /*
5625  * Compute temperature (in degC) from last received statistics.
5626  */
5627 static int
5628 iwn4965_get_temperature(struct iwn_softc *sc)
5629 {
5630 	struct iwn_ucode_info *uc = &sc->ucode_info;
5631 	int32_t r1, r2, r3, r4, temp;
5632 
5633 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5634 
5635 	r1 = le32toh(uc->temp[0].chan20MHz);
5636 	r2 = le32toh(uc->temp[1].chan20MHz);
5637 	r3 = le32toh(uc->temp[2].chan20MHz);
5638 	r4 = le32toh(sc->rawtemp);
5639 
5640 	if (r1 == r3)	/* Prevents division by 0 (should not happen). */
5641 		return 0;
5642 
5643 	/* Sign-extend 23-bit R4 value to 32-bit. */
5644 	r4 = ((r4 & 0xffffff) ^ 0x800000) - 0x800000;
5645 	/* Compute temperature in Kelvin. */
5646 	temp = (259 * (r4 - r2)) / (r3 - r1);
5647 	temp = (temp * 97) / 100 + 8;
5648 
5649 	DPRINTF(sc, IWN_DEBUG_ANY, "temperature %dK/%dC\n", temp,
5650 	    IWN_KTOC(temp));
5651 	return IWN_KTOC(temp);
5652 }
5653 
5654 static int
5655 iwn5000_get_temperature(struct iwn_softc *sc)
5656 {
5657 	int32_t temp;
5658 
5659 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5660 
5661 	/*
5662 	 * Temperature is not used by the driver for 5000 Series because
5663 	 * TX power calibration is handled by firmware.
5664 	 */
5665 	temp = le32toh(sc->rawtemp);
5666 	if (sc->hw_type == IWN_HW_REV_TYPE_5150) {
5667 		temp = (temp / -5) + sc->temp_off;
5668 		temp = IWN_KTOC(temp);
5669 	}
5670 	return temp;
5671 }
5672 
5673 /*
5674  * Initialize sensitivity calibration state machine.
5675  */
5676 static int
5677 iwn_init_sensitivity(struct iwn_softc *sc)
5678 {
5679 	struct iwn_ops *ops = &sc->ops;
5680 	struct iwn_calib_state *calib = &sc->calib;
5681 	uint32_t flags;
5682 	int error;
5683 
5684 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5685 
5686 	/* Reset calibration state machine. */
5687 	memset(calib, 0, sizeof (*calib));
5688 	calib->state = IWN_CALIB_STATE_INIT;
5689 	calib->cck_state = IWN_CCK_STATE_HIFA;
5690 	/* Set initial correlation values. */
5691 	calib->ofdm_x1     = sc->limits->min_ofdm_x1;
5692 	calib->ofdm_mrc_x1 = sc->limits->min_ofdm_mrc_x1;
5693 	calib->ofdm_x4     = sc->limits->min_ofdm_x4;
5694 	calib->ofdm_mrc_x4 = sc->limits->min_ofdm_mrc_x4;
5695 	calib->cck_x4      = 125;
5696 	calib->cck_mrc_x4  = sc->limits->min_cck_mrc_x4;
5697 	calib->energy_cck  = sc->limits->energy_cck;
5698 
5699 	/* Write initial sensitivity. */
5700 	if ((error = iwn_send_sensitivity(sc)) != 0)
5701 		return error;
5702 
5703 	/* Write initial gains. */
5704 	if ((error = ops->init_gains(sc)) != 0)
5705 		return error;
5706 
5707 	/* Request statistics at each beacon interval. */
5708 	flags = 0;
5709 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: sending request for statistics\n",
5710 	    __func__);
5711 	return iwn_cmd(sc, IWN_CMD_GET_STATISTICS, &flags, sizeof flags, 1);
5712 }
5713 
5714 /*
5715  * Collect noise and RSSI statistics for the first 20 beacons received
5716  * after association and use them to determine connected antennas and
5717  * to set differential gains.
5718  */
5719 static void
5720 iwn_collect_noise(struct iwn_softc *sc,
5721     const struct iwn_rx_general_stats *stats)
5722 {
5723 	struct iwn_ops *ops = &sc->ops;
5724 	struct iwn_calib_state *calib = &sc->calib;
5725 	struct ifnet *ifp = sc->sc_ifp;
5726 	struct ieee80211com *ic = ifp->if_l2com;
5727 	uint32_t val;
5728 	int i;
5729 
5730 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
5731 
5732 	/* Accumulate RSSI and noise for all 3 antennas. */
5733 	for (i = 0; i < 3; i++) {
5734 		calib->rssi[i] += le32toh(stats->rssi[i]) & 0xff;
5735 		calib->noise[i] += le32toh(stats->noise[i]) & 0xff;
5736 	}
5737 	/* NB: We update differential gains only once after 20 beacons. */
5738 	if (++calib->nbeacons < 20)
5739 		return;
5740 
5741 	/* Determine highest average RSSI. */
5742 	val = MAX(calib->rssi[0], calib->rssi[1]);
5743 	val = MAX(calib->rssi[2], val);
5744 
5745 	/* Determine which antennas are connected. */
5746 	sc->chainmask = sc->rxchainmask;
5747 	for (i = 0; i < 3; i++)
5748 		if (val - calib->rssi[i] > 15 * 20)
5749 			sc->chainmask &= ~(1 << i);
5750 	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_XMIT,
5751 	    "%s: RX chains mask: theoretical=0x%x, actual=0x%x\n",
5752 	    __func__, sc->rxchainmask, sc->chainmask);
5753 
5754 	/* If none of the TX antennas are connected, keep at least one. */
5755 	if ((sc->chainmask & sc->txchainmask) == 0)
5756 		sc->chainmask |= IWN_LSB(sc->txchainmask);
5757 
5758 	(void)ops->set_gains(sc);
5759 	calib->state = IWN_CALIB_STATE_RUN;
5760 
5761 #ifdef notyet
5762 	/* XXX Disable RX chains with no antennas connected. */
5763 	sc->rxon->rxchain = htole16(IWN_RXCHAIN_SEL(sc->chainmask));
5764 	if (sc->sc_is_scanning)
5765 		device_printf(sc->sc_dev,
5766 		    "%s: is_scanning set, before RXON\n",
5767 		    __func__);
5768 	(void)iwn_cmd(sc, IWN_CMD_RXON, sc->rxon, sc->rxonsz, 1);
5769 #endif
5770 
5771 	/* Enable power-saving mode if requested by user. */
5772 	if (ic->ic_flags & IEEE80211_F_PMGTON)
5773 		(void)iwn_set_pslevel(sc, 0, 3, 1);
5774 
5775 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
5776 
5777 }
5778 
5779 static int
5780 iwn4965_init_gains(struct iwn_softc *sc)
5781 {
5782 	struct iwn_phy_calib_gain cmd;
5783 
5784 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5785 
5786 	memset(&cmd, 0, sizeof cmd);
5787 	cmd.code = IWN4965_PHY_CALIB_DIFF_GAIN;
5788 	/* Differential gains initially set to 0 for all 3 antennas. */
5789 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
5790 	    "%s: setting initial differential gains\n", __func__);
5791 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
5792 }
5793 
5794 static int
5795 iwn5000_init_gains(struct iwn_softc *sc)
5796 {
5797 	struct iwn_phy_calib cmd;
5798 
5799 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5800 
5801 	memset(&cmd, 0, sizeof cmd);
5802 	cmd.code = sc->reset_noise_gain;
5803 	cmd.ngroups = 1;
5804 	cmd.isvalid = 1;
5805 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
5806 	    "%s: setting initial differential gains\n", __func__);
5807 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
5808 }
5809 
5810 static int
5811 iwn4965_set_gains(struct iwn_softc *sc)
5812 {
5813 	struct iwn_calib_state *calib = &sc->calib;
5814 	struct iwn_phy_calib_gain cmd;
5815 	int i, delta, noise;
5816 
5817 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5818 
5819 	/* Get minimal noise among connected antennas. */
5820 	noise = INT_MAX;	/* NB: There's at least one antenna. */
5821 	for (i = 0; i < 3; i++)
5822 		if (sc->chainmask & (1 << i))
5823 			noise = MIN(calib->noise[i], noise);
5824 
5825 	memset(&cmd, 0, sizeof cmd);
5826 	cmd.code = IWN4965_PHY_CALIB_DIFF_GAIN;
5827 	/* Set differential gains for connected antennas. */
5828 	for (i = 0; i < 3; i++) {
5829 		if (sc->chainmask & (1 << i)) {
5830 			/* Compute attenuation (in unit of 1.5dB). */
5831 			delta = (noise - (int32_t)calib->noise[i]) / 30;
5832 			/* NB: delta <= 0 */
5833 			/* Limit to [-4.5dB,0]. */
5834 			cmd.gain[i] = MIN(abs(delta), 3);
5835 			if (delta < 0)
5836 				cmd.gain[i] |= 1 << 2;	/* sign bit */
5837 		}
5838 	}
5839 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
5840 	    "setting differential gains Ant A/B/C: %x/%x/%x (%x)\n",
5841 	    cmd.gain[0], cmd.gain[1], cmd.gain[2], sc->chainmask);
5842 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
5843 }
5844 
5845 static int
5846 iwn5000_set_gains(struct iwn_softc *sc)
5847 {
5848 	struct iwn_calib_state *calib = &sc->calib;
5849 	struct iwn_phy_calib_gain cmd;
5850 	int i, ant, div, delta;
5851 
5852 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5853 
5854 	/* We collected 20 beacons and !=6050 need a 1.5 factor. */
5855 	div = (sc->hw_type == IWN_HW_REV_TYPE_6050) ? 20 : 30;
5856 
5857 	memset(&cmd, 0, sizeof cmd);
5858 	cmd.code = sc->noise_gain;
5859 	cmd.ngroups = 1;
5860 	cmd.isvalid = 1;
5861 	/* Get first available RX antenna as referential. */
5862 	ant = IWN_LSB(sc->rxchainmask);
5863 	/* Set differential gains for other antennas. */
5864 	for (i = ant + 1; i < 3; i++) {
5865 		if (sc->chainmask & (1 << i)) {
5866 			/* The delta is relative to antenna "ant". */
5867 			delta = ((int32_t)calib->noise[ant] -
5868 			    (int32_t)calib->noise[i]) / div;
5869 			/* Limit to [-4.5dB,+4.5dB]. */
5870 			cmd.gain[i - 1] = MIN(abs(delta), 3);
5871 			if (delta < 0)
5872 				cmd.gain[i - 1] |= 1 << 2;	/* sign bit */
5873 		}
5874 	}
5875 	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_XMIT,
5876 	    "setting differential gains Ant B/C: %x/%x (%x)\n",
5877 	    cmd.gain[0], cmd.gain[1], sc->chainmask);
5878 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
5879 }
5880 
5881 /*
5882  * Tune RF RX sensitivity based on the number of false alarms detected
5883  * during the last beacon period.
5884  */
5885 static void
5886 iwn_tune_sensitivity(struct iwn_softc *sc, const struct iwn_rx_stats *stats)
5887 {
5888 #define inc(val, inc, max)			\
5889 	if ((val) < (max)) {			\
5890 		if ((val) < (max) - (inc))	\
5891 			(val) += (inc);		\
5892 		else				\
5893 			(val) = (max);		\
5894 		needs_update = 1;		\
5895 	}
5896 #define dec(val, dec, min)			\
5897 	if ((val) > (min)) {			\
5898 		if ((val) > (min) + (dec))	\
5899 			(val) -= (dec);		\
5900 		else				\
5901 			(val) = (min);		\
5902 		needs_update = 1;		\
5903 	}
5904 
5905 	const struct iwn_sensitivity_limits *limits = sc->limits;
5906 	struct iwn_calib_state *calib = &sc->calib;
5907 	uint32_t val, rxena, fa;
5908 	uint32_t energy[3], energy_min;
5909 	uint8_t noise[3], noise_ref;
5910 	int i, needs_update = 0;
5911 
5912 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
5913 
5914 	/* Check that we've been enabled long enough. */
5915 	if ((rxena = le32toh(stats->general.load)) == 0){
5916 		DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end not so long\n", __func__);
5917 		return;
5918 	}
5919 
5920 	/* Compute number of false alarms since last call for OFDM. */
5921 	fa  = le32toh(stats->ofdm.bad_plcp) - calib->bad_plcp_ofdm;
5922 	fa += le32toh(stats->ofdm.fa) - calib->fa_ofdm;
5923 	fa *= 200 * IEEE80211_DUR_TU;	/* 200TU */
5924 
5925 	if (fa > 50 * rxena) {
5926 		/* High false alarm count, decrease sensitivity. */
5927 		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
5928 		    "%s: OFDM high false alarm count: %u\n", __func__, fa);
5929 		inc(calib->ofdm_x1,     1, limits->max_ofdm_x1);
5930 		inc(calib->ofdm_mrc_x1, 1, limits->max_ofdm_mrc_x1);
5931 		inc(calib->ofdm_x4,     1, limits->max_ofdm_x4);
5932 		inc(calib->ofdm_mrc_x4, 1, limits->max_ofdm_mrc_x4);
5933 
5934 	} else if (fa < 5 * rxena) {
5935 		/* Low false alarm count, increase sensitivity. */
5936 		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
5937 		    "%s: OFDM low false alarm count: %u\n", __func__, fa);
5938 		dec(calib->ofdm_x1,     1, limits->min_ofdm_x1);
5939 		dec(calib->ofdm_mrc_x1, 1, limits->min_ofdm_mrc_x1);
5940 		dec(calib->ofdm_x4,     1, limits->min_ofdm_x4);
5941 		dec(calib->ofdm_mrc_x4, 1, limits->min_ofdm_mrc_x4);
5942 	}
5943 
5944 	/* Compute maximum noise among 3 receivers. */
5945 	for (i = 0; i < 3; i++)
5946 		noise[i] = (le32toh(stats->general.noise[i]) >> 8) & 0xff;
5947 	val = MAX(noise[0], noise[1]);
5948 	val = MAX(noise[2], val);
5949 	/* Insert it into our samples table. */
5950 	calib->noise_samples[calib->cur_noise_sample] = val;
5951 	calib->cur_noise_sample = (calib->cur_noise_sample + 1) % 20;
5952 
5953 	/* Compute maximum noise among last 20 samples. */
5954 	noise_ref = calib->noise_samples[0];
5955 	for (i = 1; i < 20; i++)
5956 		noise_ref = MAX(noise_ref, calib->noise_samples[i]);
5957 
5958 	/* Compute maximum energy among 3 receivers. */
5959 	for (i = 0; i < 3; i++)
5960 		energy[i] = le32toh(stats->general.energy[i]);
5961 	val = MIN(energy[0], energy[1]);
5962 	val = MIN(energy[2], val);
5963 	/* Insert it into our samples table. */
5964 	calib->energy_samples[calib->cur_energy_sample] = val;
5965 	calib->cur_energy_sample = (calib->cur_energy_sample + 1) % 10;
5966 
5967 	/* Compute minimum energy among last 10 samples. */
5968 	energy_min = calib->energy_samples[0];
5969 	for (i = 1; i < 10; i++)
5970 		energy_min = MAX(energy_min, calib->energy_samples[i]);
5971 	energy_min += 6;
5972 
5973 	/* Compute number of false alarms since last call for CCK. */
5974 	fa  = le32toh(stats->cck.bad_plcp) - calib->bad_plcp_cck;
5975 	fa += le32toh(stats->cck.fa) - calib->fa_cck;
5976 	fa *= 200 * IEEE80211_DUR_TU;	/* 200TU */
5977 
5978 	if (fa > 50 * rxena) {
5979 		/* High false alarm count, decrease sensitivity. */
5980 		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
5981 		    "%s: CCK high false alarm count: %u\n", __func__, fa);
5982 		calib->cck_state = IWN_CCK_STATE_HIFA;
5983 		calib->low_fa = 0;
5984 
5985 		if (calib->cck_x4 > 160) {
5986 			calib->noise_ref = noise_ref;
5987 			if (calib->energy_cck > 2)
5988 				dec(calib->energy_cck, 2, energy_min);
5989 		}
5990 		if (calib->cck_x4 < 160) {
5991 			calib->cck_x4 = 161;
5992 			needs_update = 1;
5993 		} else
5994 			inc(calib->cck_x4, 3, limits->max_cck_x4);
5995 
5996 		inc(calib->cck_mrc_x4, 3, limits->max_cck_mrc_x4);
5997 
5998 	} else if (fa < 5 * rxena) {
5999 		/* Low false alarm count, increase sensitivity. */
6000 		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
6001 		    "%s: CCK low false alarm count: %u\n", __func__, fa);
6002 		calib->cck_state = IWN_CCK_STATE_LOFA;
6003 		calib->low_fa++;
6004 
6005 		if (calib->cck_state != IWN_CCK_STATE_INIT &&
6006 		    (((int32_t)calib->noise_ref - (int32_t)noise_ref) > 2 ||
6007 		     calib->low_fa > 100)) {
6008 			inc(calib->energy_cck, 2, limits->min_energy_cck);
6009 			dec(calib->cck_x4,     3, limits->min_cck_x4);
6010 			dec(calib->cck_mrc_x4, 3, limits->min_cck_mrc_x4);
6011 		}
6012 	} else {
6013 		/* Not worth to increase or decrease sensitivity. */
6014 		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
6015 		    "%s: CCK normal false alarm count: %u\n", __func__, fa);
6016 		calib->low_fa = 0;
6017 		calib->noise_ref = noise_ref;
6018 
6019 		if (calib->cck_state == IWN_CCK_STATE_HIFA) {
6020 			/* Previous interval had many false alarms. */
6021 			dec(calib->energy_cck, 8, energy_min);
6022 		}
6023 		calib->cck_state = IWN_CCK_STATE_INIT;
6024 	}
6025 
6026 	if (needs_update)
6027 		(void)iwn_send_sensitivity(sc);
6028 
6029 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
6030 
6031 #undef dec
6032 #undef inc
6033 }
6034 
6035 static int
6036 iwn_send_sensitivity(struct iwn_softc *sc)
6037 {
6038 	struct iwn_calib_state *calib = &sc->calib;
6039 	struct iwn_enhanced_sensitivity_cmd cmd;
6040 	int len;
6041 
6042 	memset(&cmd, 0, sizeof cmd);
6043 	len = sizeof (struct iwn_sensitivity_cmd);
6044 	cmd.which = IWN_SENSITIVITY_WORKTBL;
6045 	/* OFDM modulation. */
6046 	cmd.corr_ofdm_x1       = htole16(calib->ofdm_x1);
6047 	cmd.corr_ofdm_mrc_x1   = htole16(calib->ofdm_mrc_x1);
6048 	cmd.corr_ofdm_x4       = htole16(calib->ofdm_x4);
6049 	cmd.corr_ofdm_mrc_x4   = htole16(calib->ofdm_mrc_x4);
6050 	cmd.energy_ofdm        = htole16(sc->limits->energy_ofdm);
6051 	cmd.energy_ofdm_th     = htole16(62);
6052 	/* CCK modulation. */
6053 	cmd.corr_cck_x4        = htole16(calib->cck_x4);
6054 	cmd.corr_cck_mrc_x4    = htole16(calib->cck_mrc_x4);
6055 	cmd.energy_cck         = htole16(calib->energy_cck);
6056 	/* Barker modulation: use default values. */
6057 	cmd.corr_barker        = htole16(190);
6058 	cmd.corr_barker_mrc    = htole16(sc->limits->barker_mrc);
6059 
6060 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
6061 	    "%s: set sensitivity %d/%d/%d/%d/%d/%d/%d\n", __func__,
6062 	    calib->ofdm_x1, calib->ofdm_mrc_x1, calib->ofdm_x4,
6063 	    calib->ofdm_mrc_x4, calib->cck_x4,
6064 	    calib->cck_mrc_x4, calib->energy_cck);
6065 
6066 	if (!(sc->sc_flags & IWN_FLAG_ENH_SENS))
6067 		goto send;
6068 	/* Enhanced sensitivity settings. */
6069 	len = sizeof (struct iwn_enhanced_sensitivity_cmd);
6070 	cmd.ofdm_det_slope_mrc = htole16(668);
6071 	cmd.ofdm_det_icept_mrc = htole16(4);
6072 	cmd.ofdm_det_slope     = htole16(486);
6073 	cmd.ofdm_det_icept     = htole16(37);
6074 	cmd.cck_det_slope_mrc  = htole16(853);
6075 	cmd.cck_det_icept_mrc  = htole16(4);
6076 	cmd.cck_det_slope      = htole16(476);
6077 	cmd.cck_det_icept      = htole16(99);
6078 send:
6079 	return iwn_cmd(sc, IWN_CMD_SET_SENSITIVITY, &cmd, len, 1);
6080 }
6081 
6082 /*
6083  * Look at the increase of PLCP errors over time; if it exceeds
6084  * a programmed threshold then trigger an RF retune.
6085  */
6086 static void
6087 iwn_check_rx_recovery(struct iwn_softc *sc, struct iwn_stats *rs)
6088 {
6089 	int32_t delta_ofdm, delta_ht, delta_cck;
6090 	struct iwn_calib_state *calib = &sc->calib;
6091 	int delta_ticks, cur_ticks;
6092 	int delta_msec;
6093 	int thresh;
6094 
6095 	/*
6096 	 * Calculate the difference between the current and
6097 	 * previous statistics.
6098 	 */
6099 	delta_cck = le32toh(rs->rx.cck.bad_plcp) - calib->bad_plcp_cck;
6100 	delta_ofdm = le32toh(rs->rx.ofdm.bad_plcp) - calib->bad_plcp_ofdm;
6101 	delta_ht = le32toh(rs->rx.ht.bad_plcp) - calib->bad_plcp_ht;
6102 
6103 	/*
6104 	 * Calculate the delta in time between successive statistics
6105 	 * messages.  Yes, it can roll over; so we make sure that
6106 	 * this doesn't happen.
6107 	 *
6108 	 * XXX go figure out what to do about rollover
6109 	 * XXX go figure out what to do if ticks rolls over to -ve instead!
6110 	 * XXX go stab signed integer overflow undefined-ness in the face.
6111 	 */
6112 	cur_ticks = ticks;
6113 	delta_ticks = cur_ticks - sc->last_calib_ticks;
6114 
6115 	/*
6116 	 * If any are negative, then the firmware likely reset; so just
6117 	 * bail.  We'll pick this up next time.
6118 	 */
6119 	if (delta_cck < 0 || delta_ofdm < 0 || delta_ht < 0 || delta_ticks < 0)
6120 		return;
6121 
6122 	/*
6123 	 * delta_ticks is in ticks; we need to convert it up to milliseconds
6124 	 * so we can do some useful math with it.
6125 	 */
6126 	delta_msec = ticks_to_msecs(delta_ticks);
6127 
6128 	/*
6129 	 * Calculate what our threshold is given the current delta_msec.
6130 	 */
6131 	thresh = sc->base_params->plcp_err_threshold * delta_msec;
6132 
6133 	DPRINTF(sc, IWN_DEBUG_STATE,
6134 	    "%s: time delta: %d; cck=%d, ofdm=%d, ht=%d, total=%d, thresh=%d\n",
6135 	    __func__,
6136 	    delta_msec,
6137 	    delta_cck,
6138 	    delta_ofdm,
6139 	    delta_ht,
6140 	    (delta_msec + delta_cck + delta_ofdm + delta_ht),
6141 	    thresh);
6142 
6143 	/*
6144 	 * If we need a retune, then schedule a single channel scan
6145 	 * to a channel that isn't the currently active one!
6146 	 *
6147 	 * The math from linux iwlwifi:
6148 	 *
6149 	 * if ((delta * 100 / msecs) > threshold)
6150 	 */
6151 	if (thresh > 0 && (delta_cck + delta_ofdm + delta_ht) * 100 > thresh) {
6152 		DPRINTF(sc, IWN_DEBUG_ANY,
6153 		    "%s: PLCP error threshold raw (%d) comparison (%d) "
6154 		    "over limit (%d); retune!\n",
6155 		    __func__,
6156 		    (delta_cck + delta_ofdm + delta_ht),
6157 		    (delta_cck + delta_ofdm + delta_ht) * 100,
6158 		    thresh);
6159 	}
6160 }
6161 
6162 /*
6163  * Set STA mode power saving level (between 0 and 5).
6164  * Level 0 is CAM (Continuously Aware Mode), 5 is for maximum power saving.
6165  */
6166 static int
6167 iwn_set_pslevel(struct iwn_softc *sc, int dtim, int level, int async)
6168 {
6169 	struct iwn_pmgt_cmd cmd;
6170 	const struct iwn_pmgt *pmgt;
6171 	uint32_t max, skip_dtim;
6172 	uint32_t reg;
6173 	int i;
6174 
6175 	DPRINTF(sc, IWN_DEBUG_PWRSAVE,
6176 	    "%s: dtim=%d, level=%d, async=%d\n",
6177 	    __func__,
6178 	    dtim,
6179 	    level,
6180 	    async);
6181 
6182 	/* Select which PS parameters to use. */
6183 	if (dtim <= 2)
6184 		pmgt = &iwn_pmgt[0][level];
6185 	else if (dtim <= 10)
6186 		pmgt = &iwn_pmgt[1][level];
6187 	else
6188 		pmgt = &iwn_pmgt[2][level];
6189 
6190 	memset(&cmd, 0, sizeof cmd);
6191 	if (level != 0)	/* not CAM */
6192 		cmd.flags |= htole16(IWN_PS_ALLOW_SLEEP);
6193 	if (level == 5)
6194 		cmd.flags |= htole16(IWN_PS_FAST_PD);
6195 	/* Retrieve PCIe Active State Power Management (ASPM). */
6196 	reg = pci_read_config(sc->sc_dev, sc->sc_cap_off + 0x10, 1);
6197 	if (!(reg & 0x1))	/* L0s Entry disabled. */
6198 		cmd.flags |= htole16(IWN_PS_PCI_PMGT);
6199 	cmd.rxtimeout = htole32(pmgt->rxtimeout * 1024);
6200 	cmd.txtimeout = htole32(pmgt->txtimeout * 1024);
6201 
6202 	if (dtim == 0) {
6203 		dtim = 1;
6204 		skip_dtim = 0;
6205 	} else
6206 		skip_dtim = pmgt->skip_dtim;
6207 	if (skip_dtim != 0) {
6208 		cmd.flags |= htole16(IWN_PS_SLEEP_OVER_DTIM);
6209 		max = pmgt->intval[4];
6210 		if (max == (uint32_t)-1)
6211 			max = dtim * (skip_dtim + 1);
6212 		else if (max > dtim)
6213 			max = (max / dtim) * dtim;
6214 	} else
6215 		max = dtim;
6216 	for (i = 0; i < 5; i++)
6217 		cmd.intval[i] = htole32(MIN(max, pmgt->intval[i]));
6218 
6219 	DPRINTF(sc, IWN_DEBUG_RESET, "setting power saving level to %d\n",
6220 	    level);
6221 	return iwn_cmd(sc, IWN_CMD_SET_POWER_MODE, &cmd, sizeof cmd, async);
6222 }
6223 
6224 static int
6225 iwn_send_btcoex(struct iwn_softc *sc)
6226 {
6227 	struct iwn_bluetooth cmd;
6228 
6229 	memset(&cmd, 0, sizeof cmd);
6230 	cmd.flags = IWN_BT_COEX_CHAN_ANN | IWN_BT_COEX_BT_PRIO;
6231 	cmd.lead_time = IWN_BT_LEAD_TIME_DEF;
6232 	cmd.max_kill = IWN_BT_MAX_KILL_DEF;
6233 	DPRINTF(sc, IWN_DEBUG_RESET, "%s: configuring bluetooth coexistence\n",
6234 	    __func__);
6235 	return iwn_cmd(sc, IWN_CMD_BT_COEX, &cmd, sizeof(cmd), 0);
6236 }
6237 
6238 static int
6239 iwn_send_advanced_btcoex(struct iwn_softc *sc)
6240 {
6241 	static const uint32_t btcoex_3wire[12] = {
6242 		0xaaaaaaaa, 0xaaaaaaaa, 0xaeaaaaaa, 0xaaaaaaaa,
6243 		0xcc00ff28, 0x0000aaaa, 0xcc00aaaa, 0x0000aaaa,
6244 		0xc0004000, 0x00004000, 0xf0005000, 0xf0005000,
6245 	};
6246 	struct iwn6000_btcoex_config btconfig;
6247 	struct iwn2000_btcoex_config btconfig2k;
6248 	struct iwn_btcoex_priotable btprio;
6249 	struct iwn_btcoex_prot btprot;
6250 	int error, i;
6251 	uint8_t flags;
6252 
6253 	memset(&btconfig, 0, sizeof btconfig);
6254 	memset(&btconfig2k, 0, sizeof btconfig2k);
6255 
6256 	flags = IWN_BT_FLAG_COEX6000_MODE_3W <<
6257 	    IWN_BT_FLAG_COEX6000_MODE_SHIFT; // Done as is in linux kernel 3.2
6258 
6259 	if (sc->base_params->bt_sco_disable)
6260 		flags &= ~IWN_BT_FLAG_SYNC_2_BT_DISABLE;
6261 	else
6262 		flags |= IWN_BT_FLAG_SYNC_2_BT_DISABLE;
6263 
6264 	flags |= IWN_BT_FLAG_COEX6000_CHAN_INHIBITION;
6265 
6266 	/* Default flags result is 145 as old value */
6267 
6268 	/*
6269 	 * Flags value has to be review. Values must change if we
6270 	 * which to disable it
6271 	 */
6272 	if (sc->base_params->bt_session_2) {
6273 		btconfig2k.flags = flags;
6274 		btconfig2k.max_kill = 5;
6275 		btconfig2k.bt3_t7_timer = 1;
6276 		btconfig2k.kill_ack = htole32(0xffff0000);
6277 		btconfig2k.kill_cts = htole32(0xffff0000);
6278 		btconfig2k.sample_time = 2;
6279 		btconfig2k.bt3_t2_timer = 0xc;
6280 
6281 		for (i = 0; i < 12; i++)
6282 			btconfig2k.lookup_table[i] = htole32(btcoex_3wire[i]);
6283 		btconfig2k.valid = htole16(0xff);
6284 		btconfig2k.prio_boost = htole32(0xf0);
6285 		DPRINTF(sc, IWN_DEBUG_RESET,
6286 		    "%s: configuring advanced bluetooth coexistence"
6287 		    " session 2, flags : 0x%x\n",
6288 		    __func__,
6289 		    flags);
6290 		error = iwn_cmd(sc, IWN_CMD_BT_COEX, &btconfig2k,
6291 		    sizeof(btconfig2k), 1);
6292 	} else {
6293 		btconfig.flags = flags;
6294 		btconfig.max_kill = 5;
6295 		btconfig.bt3_t7_timer = 1;
6296 		btconfig.kill_ack = htole32(0xffff0000);
6297 		btconfig.kill_cts = htole32(0xffff0000);
6298 		btconfig.sample_time = 2;
6299 		btconfig.bt3_t2_timer = 0xc;
6300 
6301 		for (i = 0; i < 12; i++)
6302 			btconfig.lookup_table[i] = htole32(btcoex_3wire[i]);
6303 		btconfig.valid = htole16(0xff);
6304 		btconfig.prio_boost = 0xf0;
6305 		DPRINTF(sc, IWN_DEBUG_RESET,
6306 		    "%s: configuring advanced bluetooth coexistence,"
6307 		    " flags : 0x%x\n",
6308 		    __func__,
6309 		    flags);
6310 		error = iwn_cmd(sc, IWN_CMD_BT_COEX, &btconfig,
6311 		    sizeof(btconfig), 1);
6312 	}
6313 
6314 	if (error != 0)
6315 		return error;
6316 
6317 	memset(&btprio, 0, sizeof btprio);
6318 	btprio.calib_init1 = 0x6;
6319 	btprio.calib_init2 = 0x7;
6320 	btprio.calib_periodic_low1 = 0x2;
6321 	btprio.calib_periodic_low2 = 0x3;
6322 	btprio.calib_periodic_high1 = 0x4;
6323 	btprio.calib_periodic_high2 = 0x5;
6324 	btprio.dtim = 0x6;
6325 	btprio.scan52 = 0x8;
6326 	btprio.scan24 = 0xa;
6327 	error = iwn_cmd(sc, IWN_CMD_BT_COEX_PRIOTABLE, &btprio, sizeof(btprio),
6328 	    1);
6329 	if (error != 0)
6330 		return error;
6331 
6332 	/* Force BT state machine change. */
6333 	memset(&btprot, 0, sizeof btprot);
6334 	btprot.open = 1;
6335 	btprot.type = 1;
6336 	error = iwn_cmd(sc, IWN_CMD_BT_COEX_PROT, &btprot, sizeof(btprot), 1);
6337 	if (error != 0)
6338 		return error;
6339 	btprot.open = 0;
6340 	return iwn_cmd(sc, IWN_CMD_BT_COEX_PROT, &btprot, sizeof(btprot), 1);
6341 }
6342 
6343 static int
6344 iwn5000_runtime_calib(struct iwn_softc *sc)
6345 {
6346 	struct iwn5000_calib_config cmd;
6347 
6348 	memset(&cmd, 0, sizeof cmd);
6349 	cmd.ucode.once.enable = 0xffffffff;
6350 	cmd.ucode.once.start = IWN5000_CALIB_DC;
6351 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
6352 	    "%s: configuring runtime calibration\n", __func__);
6353 	return iwn_cmd(sc, IWN5000_CMD_CALIB_CONFIG, &cmd, sizeof(cmd), 0);
6354 }
6355 
6356 static int
6357 iwn_config(struct iwn_softc *sc)
6358 {
6359 	struct iwn_ops *ops = &sc->ops;
6360 	struct ifnet *ifp = sc->sc_ifp;
6361 	struct ieee80211com *ic = ifp->if_l2com;
6362 	uint32_t txmask;
6363 	uint16_t rxchain;
6364 	int error;
6365 
6366 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
6367 
6368 	if ((sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_TEMP_OFFSET)
6369 	    && (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_TEMP_OFFSETv2)) {
6370 		device_printf(sc->sc_dev,"%s: temp_offset and temp_offsetv2 are"
6371 		    " exclusive each together. Review NIC config file. Conf"
6372 		    " :  0x%08x Flags :  0x%08x  \n", __func__,
6373 		    sc->base_params->calib_need,
6374 		    (IWN_FLG_NEED_PHY_CALIB_TEMP_OFFSET |
6375 		    IWN_FLG_NEED_PHY_CALIB_TEMP_OFFSETv2));
6376 		return (EINVAL);
6377 	}
6378 
6379 	/* Compute temperature calib if needed. Will be send by send calib */
6380 	if (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_TEMP_OFFSET) {
6381 		error = iwn5000_temp_offset_calib(sc);
6382 		if (error != 0) {
6383 			device_printf(sc->sc_dev,
6384 			    "%s: could not set temperature offset\n", __func__);
6385 			return (error);
6386 		}
6387 	} else if (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_TEMP_OFFSETv2) {
6388 		error = iwn5000_temp_offset_calibv2(sc);
6389 		if (error != 0) {
6390 			device_printf(sc->sc_dev,
6391 			    "%s: could not compute temperature offset v2\n",
6392 			    __func__);
6393 			return (error);
6394 		}
6395 	}
6396 
6397 	if (sc->hw_type == IWN_HW_REV_TYPE_6050) {
6398 		/* Configure runtime DC calibration. */
6399 		error = iwn5000_runtime_calib(sc);
6400 		if (error != 0) {
6401 			device_printf(sc->sc_dev,
6402 			    "%s: could not configure runtime calibration\n",
6403 			    __func__);
6404 			return error;
6405 		}
6406 	}
6407 
6408 	/* Configure valid TX chains for >=5000 Series. */
6409 	if (sc->hw_type != IWN_HW_REV_TYPE_4965 &&
6410 	    IWN_UCODE_API(sc->ucode_rev) > 1) {
6411 		txmask = htole32(sc->txchainmask);
6412 		DPRINTF(sc, IWN_DEBUG_RESET | IWN_DEBUG_XMIT,
6413 		    "%s: configuring valid TX chains 0x%x\n", __func__, txmask);
6414 		error = iwn_cmd(sc, IWN5000_CMD_TX_ANT_CONFIG, &txmask,
6415 		    sizeof txmask, 0);
6416 		if (error != 0) {
6417 			device_printf(sc->sc_dev,
6418 			    "%s: could not configure valid TX chains, "
6419 			    "error %d\n", __func__, error);
6420 			return error;
6421 		}
6422 	}
6423 
6424 	/* Configure bluetooth coexistence. */
6425 	error = 0;
6426 
6427 	/* Configure bluetooth coexistence if needed. */
6428 	if (sc->base_params->bt_mode == IWN_BT_ADVANCED)
6429 		error = iwn_send_advanced_btcoex(sc);
6430 	if (sc->base_params->bt_mode == IWN_BT_SIMPLE)
6431 		error = iwn_send_btcoex(sc);
6432 
6433 	if (error != 0) {
6434 		device_printf(sc->sc_dev,
6435 		    "%s: could not configure bluetooth coexistence, error %d\n",
6436 		    __func__, error);
6437 		return error;
6438 	}
6439 
6440 	/* Set mode, channel, RX filter and enable RX. */
6441 	sc->rxon = &sc->rx_on[IWN_RXON_BSS_CTX];
6442 	memset(sc->rxon, 0, sizeof (struct iwn_rxon));
6443 	IEEE80211_ADDR_COPY(sc->rxon->myaddr, IF_LLADDR(ifp));
6444 	IEEE80211_ADDR_COPY(sc->rxon->wlap, IF_LLADDR(ifp));
6445 	sc->rxon->chan = ieee80211_chan2ieee(ic, ic->ic_curchan);
6446 	sc->rxon->flags = htole32(IWN_RXON_TSF | IWN_RXON_CTS_TO_SELF);
6447 	if (IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan))
6448 		sc->rxon->flags |= htole32(IWN_RXON_AUTO | IWN_RXON_24GHZ);
6449 	switch (ic->ic_opmode) {
6450 	case IEEE80211_M_STA:
6451 		sc->rxon->mode = IWN_MODE_STA;
6452 		sc->rxon->filter = htole32(IWN_FILTER_MULTICAST);
6453 		break;
6454 	case IEEE80211_M_MONITOR:
6455 		sc->rxon->mode = IWN_MODE_MONITOR;
6456 		sc->rxon->filter = htole32(IWN_FILTER_MULTICAST |
6457 		    IWN_FILTER_CTL | IWN_FILTER_PROMISC);
6458 		break;
6459 	default:
6460 		/* Should not get there. */
6461 		break;
6462 	}
6463 	sc->rxon->cck_mask  = 0x0f;	/* not yet negotiated */
6464 	sc->rxon->ofdm_mask = 0xff;	/* not yet negotiated */
6465 	sc->rxon->ht_single_mask = 0xff;
6466 	sc->rxon->ht_dual_mask = 0xff;
6467 	sc->rxon->ht_triple_mask = 0xff;
6468 	/*
6469 	 * In active association mode, ensure that
6470 	 * all the receive chains are enabled.
6471 	 *
6472 	 * Since we're not yet doing SMPS, don't allow the
6473 	 * number of idle RX chains to be less than the active
6474 	 * number.
6475 	 */
6476 	rxchain =
6477 	    IWN_RXCHAIN_VALID(sc->rxchainmask) |
6478 	    IWN_RXCHAIN_MIMO_COUNT(sc->nrxchains) |
6479 	    IWN_RXCHAIN_IDLE_COUNT(sc->nrxchains);
6480 	sc->rxon->rxchain = htole16(rxchain);
6481 	DPRINTF(sc, IWN_DEBUG_RESET | IWN_DEBUG_XMIT,
6482 	    "%s: rxchainmask=0x%x, nrxchains=%d\n",
6483 	    __func__,
6484 	    sc->rxchainmask,
6485 	    sc->nrxchains);
6486 	DPRINTF(sc, IWN_DEBUG_RESET, "%s: setting configuration\n", __func__);
6487 	if (sc->sc_is_scanning)
6488 		device_printf(sc->sc_dev,
6489 		    "%s: is_scanning set, before RXON\n",
6490 		    __func__);
6491 	error = iwn_cmd(sc, IWN_CMD_RXON, sc->rxon, sc->rxonsz, 0);
6492 	if (error != 0) {
6493 		device_printf(sc->sc_dev, "%s: RXON command failed\n",
6494 		    __func__);
6495 		return error;
6496 	}
6497 
6498 	if ((error = iwn_add_broadcast_node(sc, 0)) != 0) {
6499 		device_printf(sc->sc_dev, "%s: could not add broadcast node\n",
6500 		    __func__);
6501 		return error;
6502 	}
6503 
6504 	/* Configuration has changed, set TX power accordingly. */
6505 	if ((error = ops->set_txpower(sc, ic->ic_curchan, 0)) != 0) {
6506 		device_printf(sc->sc_dev, "%s: could not set TX power\n",
6507 		    __func__);
6508 		return error;
6509 	}
6510 
6511 	if ((error = iwn_set_critical_temp(sc)) != 0) {
6512 		device_printf(sc->sc_dev,
6513 		    "%s: could not set critical temperature\n", __func__);
6514 		return error;
6515 	}
6516 
6517 	/* Set power saving level to CAM during initialization. */
6518 	if ((error = iwn_set_pslevel(sc, 0, 0, 0)) != 0) {
6519 		device_printf(sc->sc_dev,
6520 		    "%s: could not set power saving level\n", __func__);
6521 		return error;
6522 	}
6523 
6524 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
6525 
6526 	return 0;
6527 }
6528 
6529 static uint16_t
6530 iwn_get_active_dwell_time(struct iwn_softc *sc,
6531     struct ieee80211_channel *c, uint8_t n_probes)
6532 {
6533 	/* No channel? Default to 2GHz settings */
6534 	if (c == NULL || IEEE80211_IS_CHAN_2GHZ(c)) {
6535 		return (IWN_ACTIVE_DWELL_TIME_2GHZ +
6536 		IWN_ACTIVE_DWELL_FACTOR_2GHZ * (n_probes + 1));
6537 	}
6538 
6539 	/* 5GHz dwell time */
6540 	return (IWN_ACTIVE_DWELL_TIME_5GHZ +
6541 	    IWN_ACTIVE_DWELL_FACTOR_5GHZ * (n_probes + 1));
6542 }
6543 
6544 /*
6545  * Limit the total dwell time to 85% of the beacon interval.
6546  *
6547  * Returns the dwell time in milliseconds.
6548  */
6549 static uint16_t
6550 iwn_limit_dwell(struct iwn_softc *sc, uint16_t dwell_time)
6551 {
6552 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
6553 	struct ieee80211vap *vap = NULL;
6554 	int bintval = 0;
6555 
6556 	/* bintval is in TU (1.024mS) */
6557 	if (! TAILQ_EMPTY(&ic->ic_vaps)) {
6558 		vap = TAILQ_FIRST(&ic->ic_vaps);
6559 		bintval = vap->iv_bss->ni_intval;
6560 	}
6561 
6562 	/*
6563 	 * If it's non-zero, we should calculate the minimum of
6564 	 * it and the DWELL_BASE.
6565 	 *
6566 	 * XXX Yes, the math should take into account that bintval
6567 	 * is 1.024mS, not 1mS..
6568 	 */
6569 	if (bintval > 0) {
6570 		DPRINTF(sc, IWN_DEBUG_SCAN,
6571 		    "%s: bintval=%d\n",
6572 		    __func__,
6573 		    bintval);
6574 		return (MIN(IWN_PASSIVE_DWELL_BASE, ((bintval * 85) / 100)));
6575 	}
6576 
6577 	/* No association context? Default */
6578 	return (IWN_PASSIVE_DWELL_BASE);
6579 }
6580 
6581 static uint16_t
6582 iwn_get_passive_dwell_time(struct iwn_softc *sc, struct ieee80211_channel *c)
6583 {
6584 	uint16_t passive;
6585 
6586 	if (c == NULL || IEEE80211_IS_CHAN_2GHZ(c)) {
6587 		passive = IWN_PASSIVE_DWELL_BASE + IWN_PASSIVE_DWELL_TIME_2GHZ;
6588 	} else {
6589 		passive = IWN_PASSIVE_DWELL_BASE + IWN_PASSIVE_DWELL_TIME_5GHZ;
6590 	}
6591 
6592 	/* Clamp to the beacon interval if we're associated */
6593 	return (iwn_limit_dwell(sc, passive));
6594 }
6595 
6596 static int
6597 iwn_scan(struct iwn_softc *sc, struct ieee80211vap *vap,
6598     struct ieee80211_scan_state *ss, struct ieee80211_channel *c)
6599 {
6600 	struct ifnet *ifp = sc->sc_ifp;
6601 	struct ieee80211com *ic = ifp->if_l2com;
6602 	struct ieee80211_node *ni = vap->iv_bss;
6603 	struct iwn_scan_hdr *hdr;
6604 	struct iwn_cmd_data *tx;
6605 	struct iwn_scan_essid *essid;
6606 	struct iwn_scan_chan *chan;
6607 	struct ieee80211_frame *wh;
6608 	struct ieee80211_rateset *rs;
6609 	uint8_t *buf, *frm;
6610 	uint16_t rxchain;
6611 	uint8_t txant;
6612 	int buflen, error;
6613 	int is_active;
6614 	uint16_t dwell_active, dwell_passive;
6615 	uint32_t extra, scan_service_time;
6616 
6617 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
6618 
6619 	/*
6620 	 * We are absolutely not allowed to send a scan command when another
6621 	 * scan command is pending.
6622 	 */
6623 	if (sc->sc_is_scanning) {
6624 		device_printf(sc->sc_dev, "%s: called whilst scanning!\n",
6625 		    __func__);
6626 		return (EAGAIN);
6627 	}
6628 
6629 	/* Assign the scan channel */
6630 	c = ic->ic_curchan;
6631 
6632 	sc->rxon = &sc->rx_on[IWN_RXON_BSS_CTX];
6633 	buf = malloc(IWN_SCAN_MAXSZ, M_DEVBUF, M_NOWAIT | M_ZERO);
6634 	if (buf == NULL) {
6635 		device_printf(sc->sc_dev,
6636 		    "%s: could not allocate buffer for scan command\n",
6637 		    __func__);
6638 		return ENOMEM;
6639 	}
6640 	hdr = (struct iwn_scan_hdr *)buf;
6641 	/*
6642 	 * Move to the next channel if no frames are received within 10ms
6643 	 * after sending the probe request.
6644 	 */
6645 	hdr->quiet_time = htole16(10);		/* timeout in milliseconds */
6646 	hdr->quiet_threshold = htole16(1);	/* min # of packets */
6647 	/*
6648 	 * Max needs to be greater than active and passive and quiet!
6649 	 * It's also in microseconds!
6650 	 */
6651 	hdr->max_svc = htole32(250 * 1024);
6652 
6653 	/*
6654 	 * Reset scan: interval=100
6655 	 * Normal scan: interval=becaon interval
6656 	 * suspend_time: 100 (TU)
6657 	 *
6658 	 */
6659 	extra = (100 /* suspend_time */ / 100 /* beacon interval */) << 22;
6660 	//scan_service_time = extra | ((100 /* susp */ % 100 /* int */) * 1024);
6661 	scan_service_time = (4 << 22) | (100 * 1024);	/* Hardcode for now! */
6662 	hdr->pause_svc = htole32(scan_service_time);
6663 
6664 	/* Select antennas for scanning. */
6665 	rxchain =
6666 	    IWN_RXCHAIN_VALID(sc->rxchainmask) |
6667 	    IWN_RXCHAIN_FORCE_MIMO_SEL(sc->rxchainmask) |
6668 	    IWN_RXCHAIN_DRIVER_FORCE;
6669 	if (IEEE80211_IS_CHAN_A(c) &&
6670 	    sc->hw_type == IWN_HW_REV_TYPE_4965) {
6671 		/* Ant A must be avoided in 5GHz because of an HW bug. */
6672 		rxchain |= IWN_RXCHAIN_FORCE_SEL(IWN_ANT_B);
6673 	} else	/* Use all available RX antennas. */
6674 		rxchain |= IWN_RXCHAIN_FORCE_SEL(sc->rxchainmask);
6675 	hdr->rxchain = htole16(rxchain);
6676 	hdr->filter = htole32(IWN_FILTER_MULTICAST | IWN_FILTER_BEACON);
6677 
6678 	tx = (struct iwn_cmd_data *)(hdr + 1);
6679 	tx->flags = htole32(IWN_TX_AUTO_SEQ);
6680 	tx->id = sc->broadcast_id;
6681 	tx->lifetime = htole32(IWN_LIFETIME_INFINITE);
6682 
6683 	if (IEEE80211_IS_CHAN_5GHZ(c)) {
6684 		/* Send probe requests at 6Mbps. */
6685 		tx->rate = htole32(0xd);
6686 		rs = &ic->ic_sup_rates[IEEE80211_MODE_11A];
6687 	} else {
6688 		hdr->flags = htole32(IWN_RXON_24GHZ | IWN_RXON_AUTO);
6689 		if (sc->hw_type == IWN_HW_REV_TYPE_4965 &&
6690 		    sc->rxon->associd && sc->rxon->chan > 14)
6691 			tx->rate = htole32(0xd);
6692 		else {
6693 			/* Send probe requests at 1Mbps. */
6694 			tx->rate = htole32(10 | IWN_RFLAG_CCK);
6695 		}
6696 		rs = &ic->ic_sup_rates[IEEE80211_MODE_11G];
6697 	}
6698 	/* Use the first valid TX antenna. */
6699 	txant = IWN_LSB(sc->txchainmask);
6700 	tx->rate |= htole32(IWN_RFLAG_ANT(txant));
6701 
6702 	/*
6703 	 * Only do active scanning if we're announcing a probe request
6704 	 * for a given SSID (or more, if we ever add it to the driver.)
6705 	 */
6706 	is_active = 0;
6707 
6708 	/*
6709 	 * If we're scanning for a specific SSID, add it to the command.
6710 	 *
6711 	 * XXX maybe look at adding support for scanning multiple SSIDs?
6712 	 */
6713 	essid = (struct iwn_scan_essid *)(tx + 1);
6714 	if (ss != NULL) {
6715 		if (ss->ss_ssid[0].len != 0) {
6716 			essid[0].id = IEEE80211_ELEMID_SSID;
6717 			essid[0].len = ss->ss_ssid[0].len;
6718 			memcpy(essid[0].data, ss->ss_ssid[0].ssid, ss->ss_ssid[0].len);
6719 		}
6720 
6721 		DPRINTF(sc, IWN_DEBUG_SCAN, "%s: ssid_len=%d, ssid=%*s\n",
6722 		    __func__,
6723 		    ss->ss_ssid[0].len,
6724 		    ss->ss_ssid[0].len,
6725 		    ss->ss_ssid[0].ssid);
6726 
6727 		if (ss->ss_nssid > 0)
6728 			is_active = 1;
6729 	}
6730 
6731 	/*
6732 	 * Build a probe request frame.  Most of the following code is a
6733 	 * copy & paste of what is done in net80211.
6734 	 */
6735 	wh = (struct ieee80211_frame *)(essid + 20);
6736 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
6737 	    IEEE80211_FC0_SUBTYPE_PROBE_REQ;
6738 	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
6739 	IEEE80211_ADDR_COPY(wh->i_addr1, ifp->if_broadcastaddr);
6740 	IEEE80211_ADDR_COPY(wh->i_addr2, IF_LLADDR(ifp));
6741 	IEEE80211_ADDR_COPY(wh->i_addr3, ifp->if_broadcastaddr);
6742 	*(uint16_t *)&wh->i_dur[0] = 0;	/* filled by HW */
6743 	*(uint16_t *)&wh->i_seq[0] = 0;	/* filled by HW */
6744 
6745 	frm = (uint8_t *)(wh + 1);
6746 	frm = ieee80211_add_ssid(frm, NULL, 0);
6747 	frm = ieee80211_add_rates(frm, rs);
6748 	if (rs->rs_nrates > IEEE80211_RATE_SIZE)
6749 		frm = ieee80211_add_xrates(frm, rs);
6750 	if (ic->ic_htcaps & IEEE80211_HTC_HT)
6751 		frm = ieee80211_add_htcap(frm, ni);
6752 
6753 	/* Set length of probe request. */
6754 	tx->len = htole16(frm - (uint8_t *)wh);
6755 
6756 	/*
6757 	 * If active scanning is requested but a certain channel is
6758 	 * marked passive, we can do active scanning if we detect
6759 	 * transmissions.
6760 	 *
6761 	 * There is an issue with some firmware versions that triggers
6762 	 * a sysassert on a "good CRC threshold" of zero (== disabled),
6763 	 * on a radar channel even though this means that we should NOT
6764 	 * send probes.
6765 	 *
6766 	 * The "good CRC threshold" is the number of frames that we
6767 	 * need to receive during our dwell time on a channel before
6768 	 * sending out probes -- setting this to a huge value will
6769 	 * mean we never reach it, but at the same time work around
6770 	 * the aforementioned issue. Thus use IWL_GOOD_CRC_TH_NEVER
6771 	 * here instead of IWL_GOOD_CRC_TH_DISABLED.
6772 	 *
6773 	 * This was fixed in later versions along with some other
6774 	 * scan changes, and the threshold behaves as a flag in those
6775 	 * versions.
6776 	 */
6777 
6778 	/*
6779 	 * If we're doing active scanning, set the crc_threshold
6780 	 * to a suitable value.  This is different to active veruss
6781 	 * passive scanning depending upon the channel flags; the
6782 	 * firmware will obey that particular check for us.
6783 	 */
6784 	if (sc->tlv_feature_flags & IWN_UCODE_TLV_FLAGS_NEWSCAN)
6785 		hdr->crc_threshold = is_active ?
6786 		    IWN_GOOD_CRC_TH_DEFAULT : IWN_GOOD_CRC_TH_DISABLED;
6787 	else
6788 		hdr->crc_threshold = is_active ?
6789 		    IWN_GOOD_CRC_TH_DEFAULT : IWN_GOOD_CRC_TH_NEVER;
6790 
6791 	chan = (struct iwn_scan_chan *)frm;
6792 	chan->chan = htole16(ieee80211_chan2ieee(ic, c));
6793 	chan->flags = 0;
6794 	if (ss->ss_nssid > 0)
6795 		chan->flags |= htole32(IWN_CHAN_NPBREQS(1));
6796 	chan->dsp_gain = 0x6e;
6797 
6798 	/*
6799 	 * Set the passive/active flag depending upon the channel mode.
6800 	 * XXX TODO: take the is_active flag into account as well?
6801 	 */
6802 	if (c->ic_flags & IEEE80211_CHAN_PASSIVE)
6803 		chan->flags |= htole32(IWN_CHAN_PASSIVE);
6804 	else
6805 		chan->flags |= htole32(IWN_CHAN_ACTIVE);
6806 
6807 	/*
6808 	 * Calculate the active/passive dwell times.
6809 	 */
6810 
6811 	dwell_active = iwn_get_active_dwell_time(sc, c, ss->ss_nssid);
6812 	dwell_passive = iwn_get_passive_dwell_time(sc, c);
6813 
6814 	/* Make sure they're valid */
6815 	if (dwell_passive <= dwell_active)
6816 		dwell_passive = dwell_active + 1;
6817 
6818 	chan->active = htole16(dwell_active);
6819 	chan->passive = htole16(dwell_passive);
6820 
6821 	if (IEEE80211_IS_CHAN_5GHZ(c) &&
6822 	    !(c->ic_flags & IEEE80211_CHAN_PASSIVE)) {
6823 		chan->rf_gain = 0x3b;
6824 	} else if (IEEE80211_IS_CHAN_5GHZ(c)) {
6825 		chan->rf_gain = 0x3b;
6826 	} else if (!(c->ic_flags & IEEE80211_CHAN_PASSIVE)) {
6827 		chan->rf_gain = 0x28;
6828 	} else {
6829 		chan->rf_gain = 0x28;
6830 	}
6831 
6832 	DPRINTF(sc, IWN_DEBUG_STATE,
6833 	    "%s: chan %u flags 0x%x rf_gain 0x%x "
6834 	    "dsp_gain 0x%x active %d passive %d scan_svc_time %d crc 0x%x "
6835 	    "isactive=%d numssid=%d\n", __func__,
6836 	    chan->chan, chan->flags, chan->rf_gain, chan->dsp_gain,
6837 	    dwell_active, dwell_passive, scan_service_time,
6838 	    hdr->crc_threshold, is_active, ss->ss_nssid);
6839 
6840 	hdr->nchan++;
6841 	chan++;
6842 	buflen = (uint8_t *)chan - buf;
6843 	hdr->len = htole16(buflen);
6844 
6845 	if (sc->sc_is_scanning) {
6846 		device_printf(sc->sc_dev,
6847 		    "%s: called with is_scanning set!\n",
6848 		    __func__);
6849 	}
6850 	sc->sc_is_scanning = 1;
6851 
6852 	DPRINTF(sc, IWN_DEBUG_STATE, "sending scan command nchan=%d\n",
6853 	    hdr->nchan);
6854 	error = iwn_cmd(sc, IWN_CMD_SCAN, buf, buflen, 1);
6855 	free(buf, M_DEVBUF);
6856 
6857 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
6858 
6859 	return error;
6860 }
6861 
6862 static int
6863 iwn_auth(struct iwn_softc *sc, struct ieee80211vap *vap)
6864 {
6865 	struct iwn_ops *ops = &sc->ops;
6866 	struct ifnet *ifp = sc->sc_ifp;
6867 	struct ieee80211com *ic = ifp->if_l2com;
6868 	struct ieee80211_node *ni = vap->iv_bss;
6869 	int error;
6870 
6871 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
6872 
6873 	sc->rxon = &sc->rx_on[IWN_RXON_BSS_CTX];
6874 	/* Update adapter configuration. */
6875 	IEEE80211_ADDR_COPY(sc->rxon->bssid, ni->ni_bssid);
6876 	sc->rxon->chan = ieee80211_chan2ieee(ic, ni->ni_chan);
6877 	sc->rxon->flags = htole32(IWN_RXON_TSF | IWN_RXON_CTS_TO_SELF);
6878 	if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
6879 		sc->rxon->flags |= htole32(IWN_RXON_AUTO | IWN_RXON_24GHZ);
6880 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
6881 		sc->rxon->flags |= htole32(IWN_RXON_SHSLOT);
6882 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
6883 		sc->rxon->flags |= htole32(IWN_RXON_SHPREAMBLE);
6884 	if (IEEE80211_IS_CHAN_A(ni->ni_chan)) {
6885 		sc->rxon->cck_mask  = 0;
6886 		sc->rxon->ofdm_mask = 0x15;
6887 	} else if (IEEE80211_IS_CHAN_B(ni->ni_chan)) {
6888 		sc->rxon->cck_mask  = 0x03;
6889 		sc->rxon->ofdm_mask = 0;
6890 	} else {
6891 		/* Assume 802.11b/g. */
6892 		sc->rxon->cck_mask  = 0x03;
6893 		sc->rxon->ofdm_mask = 0x15;
6894 	}
6895 	DPRINTF(sc, IWN_DEBUG_STATE, "rxon chan %d flags %x cck %x ofdm %x\n",
6896 	    sc->rxon->chan, sc->rxon->flags, sc->rxon->cck_mask,
6897 	    sc->rxon->ofdm_mask);
6898 	if (sc->sc_is_scanning)
6899 		device_printf(sc->sc_dev,
6900 		    "%s: is_scanning set, before RXON\n",
6901 		    __func__);
6902 	error = iwn_cmd(sc, IWN_CMD_RXON, sc->rxon, sc->rxonsz, 1);
6903 	if (error != 0) {
6904 		device_printf(sc->sc_dev, "%s: RXON command failed, error %d\n",
6905 		    __func__, error);
6906 		return error;
6907 	}
6908 
6909 	/* Configuration has changed, set TX power accordingly. */
6910 	if ((error = ops->set_txpower(sc, ni->ni_chan, 1)) != 0) {
6911 		device_printf(sc->sc_dev,
6912 		    "%s: could not set TX power, error %d\n", __func__, error);
6913 		return error;
6914 	}
6915 	/*
6916 	 * Reconfiguring RXON clears the firmware nodes table so we must
6917 	 * add the broadcast node again.
6918 	 */
6919 	if ((error = iwn_add_broadcast_node(sc, 1)) != 0) {
6920 		device_printf(sc->sc_dev,
6921 		    "%s: could not add broadcast node, error %d\n", __func__,
6922 		    error);
6923 		return error;
6924 	}
6925 
6926 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
6927 
6928 	return 0;
6929 }
6930 
6931 static int
6932 iwn_run(struct iwn_softc *sc, struct ieee80211vap *vap)
6933 {
6934 	struct iwn_ops *ops = &sc->ops;
6935 	struct ifnet *ifp = sc->sc_ifp;
6936 	struct ieee80211com *ic = ifp->if_l2com;
6937 	struct ieee80211_node *ni = vap->iv_bss;
6938 	struct iwn_node_info node;
6939 	uint32_t htflags = 0;
6940 	int error;
6941 
6942 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
6943 
6944 	sc->rxon = &sc->rx_on[IWN_RXON_BSS_CTX];
6945 	if (ic->ic_opmode == IEEE80211_M_MONITOR) {
6946 		/* Link LED blinks while monitoring. */
6947 		iwn_set_led(sc, IWN_LED_LINK, 5, 5);
6948 		return 0;
6949 	}
6950 	if ((error = iwn_set_timing(sc, ni)) != 0) {
6951 		device_printf(sc->sc_dev,
6952 		    "%s: could not set timing, error %d\n", __func__, error);
6953 		return error;
6954 	}
6955 
6956 	/* Update adapter configuration. */
6957 	IEEE80211_ADDR_COPY(sc->rxon->bssid, ni->ni_bssid);
6958 	sc->rxon->associd = htole16(IEEE80211_AID(ni->ni_associd));
6959 	sc->rxon->chan = ieee80211_chan2ieee(ic, ni->ni_chan);
6960 	sc->rxon->flags = htole32(IWN_RXON_TSF | IWN_RXON_CTS_TO_SELF);
6961 	if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
6962 		sc->rxon->flags |= htole32(IWN_RXON_AUTO | IWN_RXON_24GHZ);
6963 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
6964 		sc->rxon->flags |= htole32(IWN_RXON_SHSLOT);
6965 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
6966 		sc->rxon->flags |= htole32(IWN_RXON_SHPREAMBLE);
6967 	if (IEEE80211_IS_CHAN_A(ni->ni_chan)) {
6968 		sc->rxon->cck_mask  = 0;
6969 		sc->rxon->ofdm_mask = 0x15;
6970 	} else if (IEEE80211_IS_CHAN_B(ni->ni_chan)) {
6971 		sc->rxon->cck_mask  = 0x03;
6972 		sc->rxon->ofdm_mask = 0;
6973 	} else {
6974 		/* Assume 802.11b/g. */
6975 		sc->rxon->cck_mask  = 0x0f;
6976 		sc->rxon->ofdm_mask = 0x15;
6977 	}
6978 	if (IEEE80211_IS_CHAN_HT(ni->ni_chan)) {
6979 		htflags |= IWN_RXON_HT_PROTMODE(ic->ic_curhtprotmode);
6980 		if (IEEE80211_IS_CHAN_HT40(ni->ni_chan)) {
6981 			switch (ic->ic_curhtprotmode) {
6982 			case IEEE80211_HTINFO_OPMODE_HT20PR:
6983 				htflags |= IWN_RXON_HT_MODEPURE40;
6984 				break;
6985 			default:
6986 				htflags |= IWN_RXON_HT_MODEMIXED;
6987 				break;
6988 			}
6989 		}
6990 		if (IEEE80211_IS_CHAN_HT40D(ni->ni_chan))
6991 			htflags |= IWN_RXON_HT_HT40MINUS;
6992 	}
6993 	sc->rxon->flags |= htole32(htflags);
6994 	sc->rxon->filter |= htole32(IWN_FILTER_BSS);
6995 	DPRINTF(sc, IWN_DEBUG_STATE, "rxon chan %d flags %x\n",
6996 	    sc->rxon->chan, sc->rxon->flags);
6997 	if (sc->sc_is_scanning)
6998 		device_printf(sc->sc_dev,
6999 		    "%s: is_scanning set, before RXON\n",
7000 		    __func__);
7001 	error = iwn_cmd(sc, IWN_CMD_RXON, sc->rxon, sc->rxonsz, 1);
7002 	if (error != 0) {
7003 		device_printf(sc->sc_dev,
7004 		    "%s: could not update configuration, error %d\n", __func__,
7005 		    error);
7006 		return error;
7007 	}
7008 
7009 	/* Configuration has changed, set TX power accordingly. */
7010 	if ((error = ops->set_txpower(sc, ni->ni_chan, 1)) != 0) {
7011 		device_printf(sc->sc_dev,
7012 		    "%s: could not set TX power, error %d\n", __func__, error);
7013 		return error;
7014 	}
7015 
7016 	/* Fake a join to initialize the TX rate. */
7017 	((struct iwn_node *)ni)->id = IWN_ID_BSS;
7018 	iwn_newassoc(ni, 1);
7019 
7020 	/* Add BSS node. */
7021 	memset(&node, 0, sizeof node);
7022 	IEEE80211_ADDR_COPY(node.macaddr, ni->ni_macaddr);
7023 	node.id = IWN_ID_BSS;
7024 	if (IEEE80211_IS_CHAN_HT(ni->ni_chan)) {
7025 		switch (ni->ni_htcap & IEEE80211_HTCAP_SMPS) {
7026 		case IEEE80211_HTCAP_SMPS_ENA:
7027 			node.htflags |= htole32(IWN_SMPS_MIMO_DIS);
7028 			break;
7029 		case IEEE80211_HTCAP_SMPS_DYNAMIC:
7030 			node.htflags |= htole32(IWN_SMPS_MIMO_PROT);
7031 			break;
7032 		}
7033 		node.htflags |= htole32(IWN_AMDPU_SIZE_FACTOR(3) |
7034 		    IWN_AMDPU_DENSITY(5));	/* 4us */
7035 		if (IEEE80211_IS_CHAN_HT40(ni->ni_chan))
7036 			node.htflags |= htole32(IWN_NODE_HT40);
7037 	}
7038 	DPRINTF(sc, IWN_DEBUG_STATE, "%s: adding BSS node\n", __func__);
7039 	error = ops->add_node(sc, &node, 1);
7040 	if (error != 0) {
7041 		device_printf(sc->sc_dev,
7042 		    "%s: could not add BSS node, error %d\n", __func__, error);
7043 		return error;
7044 	}
7045 	DPRINTF(sc, IWN_DEBUG_STATE, "%s: setting link quality for node %d\n",
7046 	    __func__, node.id);
7047 	if ((error = iwn_set_link_quality(sc, ni)) != 0) {
7048 		device_printf(sc->sc_dev,
7049 		    "%s: could not setup link quality for node %d, error %d\n",
7050 		    __func__, node.id, error);
7051 		return error;
7052 	}
7053 
7054 	if ((error = iwn_init_sensitivity(sc)) != 0) {
7055 		device_printf(sc->sc_dev,
7056 		    "%s: could not set sensitivity, error %d\n", __func__,
7057 		    error);
7058 		return error;
7059 	}
7060 	/* Start periodic calibration timer. */
7061 	sc->calib.state = IWN_CALIB_STATE_ASSOC;
7062 	sc->calib_cnt = 0;
7063 	callout_reset(&sc->calib_to, msecs_to_ticks(500), iwn_calib_timeout,
7064 	    sc);
7065 
7066 	/* Link LED always on while associated. */
7067 	iwn_set_led(sc, IWN_LED_LINK, 0, 1);
7068 
7069 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
7070 
7071 	return 0;
7072 }
7073 
7074 /*
7075  * This function is called by upper layer when an ADDBA request is received
7076  * from another STA and before the ADDBA response is sent.
7077  */
7078 static int
7079 iwn_ampdu_rx_start(struct ieee80211_node *ni, struct ieee80211_rx_ampdu *rap,
7080     int baparamset, int batimeout, int baseqctl)
7081 {
7082 #define MS(_v, _f)	(((_v) & _f) >> _f##_S)
7083 	struct iwn_softc *sc = ni->ni_ic->ic_ifp->if_softc;
7084 	struct iwn_ops *ops = &sc->ops;
7085 	struct iwn_node *wn = (void *)ni;
7086 	struct iwn_node_info node;
7087 	uint16_t ssn;
7088 	uint8_t tid;
7089 	int error;
7090 
7091 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7092 
7093 	tid = MS(le16toh(baparamset), IEEE80211_BAPS_TID);
7094 	ssn = MS(le16toh(baseqctl), IEEE80211_BASEQ_START);
7095 
7096 	memset(&node, 0, sizeof node);
7097 	node.id = wn->id;
7098 	node.control = IWN_NODE_UPDATE;
7099 	node.flags = IWN_FLAG_SET_ADDBA;
7100 	node.addba_tid = tid;
7101 	node.addba_ssn = htole16(ssn);
7102 	DPRINTF(sc, IWN_DEBUG_RECV, "ADDBA RA=%d TID=%d SSN=%d\n",
7103 	    wn->id, tid, ssn);
7104 	error = ops->add_node(sc, &node, 1);
7105 	if (error != 0)
7106 		return error;
7107 	return sc->sc_ampdu_rx_start(ni, rap, baparamset, batimeout, baseqctl);
7108 #undef MS
7109 }
7110 
7111 /*
7112  * This function is called by upper layer on teardown of an HT-immediate
7113  * Block Ack agreement (eg. uppon receipt of a DELBA frame).
7114  */
7115 static void
7116 iwn_ampdu_rx_stop(struct ieee80211_node *ni, struct ieee80211_rx_ampdu *rap)
7117 {
7118 	struct ieee80211com *ic = ni->ni_ic;
7119 	struct iwn_softc *sc = ic->ic_ifp->if_softc;
7120 	struct iwn_ops *ops = &sc->ops;
7121 	struct iwn_node *wn = (void *)ni;
7122 	struct iwn_node_info node;
7123 	uint8_t tid;
7124 
7125 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7126 
7127 	/* XXX: tid as an argument */
7128 	for (tid = 0; tid < WME_NUM_TID; tid++) {
7129 		if (&ni->ni_rx_ampdu[tid] == rap)
7130 			break;
7131 	}
7132 
7133 	memset(&node, 0, sizeof node);
7134 	node.id = wn->id;
7135 	node.control = IWN_NODE_UPDATE;
7136 	node.flags = IWN_FLAG_SET_DELBA;
7137 	node.delba_tid = tid;
7138 	DPRINTF(sc, IWN_DEBUG_RECV, "DELBA RA=%d TID=%d\n", wn->id, tid);
7139 	(void)ops->add_node(sc, &node, 1);
7140 	sc->sc_ampdu_rx_stop(ni, rap);
7141 }
7142 
7143 static int
7144 iwn_addba_request(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap,
7145     int dialogtoken, int baparamset, int batimeout)
7146 {
7147 	struct iwn_softc *sc = ni->ni_ic->ic_ifp->if_softc;
7148 	int qid;
7149 
7150 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7151 
7152 	for (qid = sc->firstaggqueue; qid < sc->ntxqs; qid++) {
7153 		if (sc->qid2tap[qid] == NULL)
7154 			break;
7155 	}
7156 	if (qid == sc->ntxqs) {
7157 		DPRINTF(sc, IWN_DEBUG_XMIT, "%s: not free aggregation queue\n",
7158 		    __func__);
7159 		return 0;
7160 	}
7161 	tap->txa_private = malloc(sizeof(int), M_DEVBUF, M_NOWAIT);
7162 	if (tap->txa_private == NULL) {
7163 		device_printf(sc->sc_dev,
7164 		    "%s: failed to alloc TX aggregation structure\n", __func__);
7165 		return 0;
7166 	}
7167 	sc->qid2tap[qid] = tap;
7168 	*(int *)tap->txa_private = qid;
7169 	return sc->sc_addba_request(ni, tap, dialogtoken, baparamset,
7170 	    batimeout);
7171 }
7172 
7173 static int
7174 iwn_addba_response(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap,
7175     int code, int baparamset, int batimeout)
7176 {
7177 	struct iwn_softc *sc = ni->ni_ic->ic_ifp->if_softc;
7178 	int qid = *(int *)tap->txa_private;
7179 	uint8_t tid = tap->txa_tid;
7180 	int ret;
7181 
7182 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7183 
7184 	if (code == IEEE80211_STATUS_SUCCESS) {
7185 		ni->ni_txseqs[tid] = tap->txa_start & 0xfff;
7186 		ret = iwn_ampdu_tx_start(ni->ni_ic, ni, tid);
7187 		if (ret != 1)
7188 			return ret;
7189 	} else {
7190 		sc->qid2tap[qid] = NULL;
7191 		free(tap->txa_private, M_DEVBUF);
7192 		tap->txa_private = NULL;
7193 	}
7194 	return sc->sc_addba_response(ni, tap, code, baparamset, batimeout);
7195 }
7196 
7197 /*
7198  * This function is called by upper layer when an ADDBA response is received
7199  * from another STA.
7200  */
7201 static int
7202 iwn_ampdu_tx_start(struct ieee80211com *ic, struct ieee80211_node *ni,
7203     uint8_t tid)
7204 {
7205 	struct ieee80211_tx_ampdu *tap = &ni->ni_tx_ampdu[tid];
7206 	struct iwn_softc *sc = ni->ni_ic->ic_ifp->if_softc;
7207 	struct iwn_ops *ops = &sc->ops;
7208 	struct iwn_node *wn = (void *)ni;
7209 	struct iwn_node_info node;
7210 	int error, qid;
7211 
7212 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7213 
7214 	/* Enable TX for the specified RA/TID. */
7215 	wn->disable_tid &= ~(1 << tid);
7216 	memset(&node, 0, sizeof node);
7217 	node.id = wn->id;
7218 	node.control = IWN_NODE_UPDATE;
7219 	node.flags = IWN_FLAG_SET_DISABLE_TID;
7220 	node.disable_tid = htole16(wn->disable_tid);
7221 	error = ops->add_node(sc, &node, 1);
7222 	if (error != 0)
7223 		return 0;
7224 
7225 	if ((error = iwn_nic_lock(sc)) != 0)
7226 		return 0;
7227 	qid = *(int *)tap->txa_private;
7228 	DPRINTF(sc, IWN_DEBUG_XMIT, "%s: ra=%d tid=%d ssn=%d qid=%d\n",
7229 	    __func__, wn->id, tid, tap->txa_start, qid);
7230 	ops->ampdu_tx_start(sc, ni, qid, tid, tap->txa_start & 0xfff);
7231 	iwn_nic_unlock(sc);
7232 
7233 	iwn_set_link_quality(sc, ni);
7234 	return 1;
7235 }
7236 
7237 static void
7238 iwn_ampdu_tx_stop(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap)
7239 {
7240 	struct iwn_softc *sc = ni->ni_ic->ic_ifp->if_softc;
7241 	struct iwn_ops *ops = &sc->ops;
7242 	uint8_t tid = tap->txa_tid;
7243 	int qid;
7244 
7245 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7246 
7247 	sc->sc_addba_stop(ni, tap);
7248 
7249 	if (tap->txa_private == NULL)
7250 		return;
7251 
7252 	qid = *(int *)tap->txa_private;
7253 	if (sc->txq[qid].queued != 0)
7254 		return;
7255 	if (iwn_nic_lock(sc) != 0)
7256 		return;
7257 	ops->ampdu_tx_stop(sc, qid, tid, tap->txa_start & 0xfff);
7258 	iwn_nic_unlock(sc);
7259 	sc->qid2tap[qid] = NULL;
7260 	free(tap->txa_private, M_DEVBUF);
7261 	tap->txa_private = NULL;
7262 }
7263 
7264 static void
7265 iwn4965_ampdu_tx_start(struct iwn_softc *sc, struct ieee80211_node *ni,
7266     int qid, uint8_t tid, uint16_t ssn)
7267 {
7268 	struct iwn_node *wn = (void *)ni;
7269 
7270 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7271 
7272 	/* Stop TX scheduler while we're changing its configuration. */
7273 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
7274 	    IWN4965_TXQ_STATUS_CHGACT);
7275 
7276 	/* Assign RA/TID translation to the queue. */
7277 	iwn_mem_write_2(sc, sc->sched_base + IWN4965_SCHED_TRANS_TBL(qid),
7278 	    wn->id << 4 | tid);
7279 
7280 	/* Enable chain-building mode for the queue. */
7281 	iwn_prph_setbits(sc, IWN4965_SCHED_QCHAIN_SEL, 1 << qid);
7282 
7283 	/* Set starting sequence number from the ADDBA request. */
7284 	sc->txq[qid].cur = sc->txq[qid].read = (ssn & 0xff);
7285 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | (ssn & 0xff));
7286 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_RDPTR(qid), ssn);
7287 
7288 	/* Set scheduler window size. */
7289 	iwn_mem_write(sc, sc->sched_base + IWN4965_SCHED_QUEUE_OFFSET(qid),
7290 	    IWN_SCHED_WINSZ);
7291 	/* Set scheduler frame limit. */
7292 	iwn_mem_write(sc, sc->sched_base + IWN4965_SCHED_QUEUE_OFFSET(qid) + 4,
7293 	    IWN_SCHED_LIMIT << 16);
7294 
7295 	/* Enable interrupts for the queue. */
7296 	iwn_prph_setbits(sc, IWN4965_SCHED_INTR_MASK, 1 << qid);
7297 
7298 	/* Mark the queue as active. */
7299 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
7300 	    IWN4965_TXQ_STATUS_ACTIVE | IWN4965_TXQ_STATUS_AGGR_ENA |
7301 	    iwn_tid2fifo[tid] << 1);
7302 }
7303 
7304 static void
7305 iwn4965_ampdu_tx_stop(struct iwn_softc *sc, int qid, uint8_t tid, uint16_t ssn)
7306 {
7307 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7308 
7309 	/* Stop TX scheduler while we're changing its configuration. */
7310 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
7311 	    IWN4965_TXQ_STATUS_CHGACT);
7312 
7313 	/* Set starting sequence number from the ADDBA request. */
7314 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | (ssn & 0xff));
7315 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_RDPTR(qid), ssn);
7316 
7317 	/* Disable interrupts for the queue. */
7318 	iwn_prph_clrbits(sc, IWN4965_SCHED_INTR_MASK, 1 << qid);
7319 
7320 	/* Mark the queue as inactive. */
7321 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
7322 	    IWN4965_TXQ_STATUS_INACTIVE | iwn_tid2fifo[tid] << 1);
7323 }
7324 
7325 static void
7326 iwn5000_ampdu_tx_start(struct iwn_softc *sc, struct ieee80211_node *ni,
7327     int qid, uint8_t tid, uint16_t ssn)
7328 {
7329 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7330 
7331 	struct iwn_node *wn = (void *)ni;
7332 
7333 	/* Stop TX scheduler while we're changing its configuration. */
7334 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
7335 	    IWN5000_TXQ_STATUS_CHGACT);
7336 
7337 	/* Assign RA/TID translation to the queue. */
7338 	iwn_mem_write_2(sc, sc->sched_base + IWN5000_SCHED_TRANS_TBL(qid),
7339 	    wn->id << 4 | tid);
7340 
7341 	/* Enable chain-building mode for the queue. */
7342 	iwn_prph_setbits(sc, IWN5000_SCHED_QCHAIN_SEL, 1 << qid);
7343 
7344 	/* Enable aggregation for the queue. */
7345 	iwn_prph_setbits(sc, IWN5000_SCHED_AGGR_SEL, 1 << qid);
7346 
7347 	/* Set starting sequence number from the ADDBA request. */
7348 	sc->txq[qid].cur = sc->txq[qid].read = (ssn & 0xff);
7349 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | (ssn & 0xff));
7350 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_RDPTR(qid), ssn);
7351 
7352 	/* Set scheduler window size and frame limit. */
7353 	iwn_mem_write(sc, sc->sched_base + IWN5000_SCHED_QUEUE_OFFSET(qid) + 4,
7354 	    IWN_SCHED_LIMIT << 16 | IWN_SCHED_WINSZ);
7355 
7356 	/* Enable interrupts for the queue. */
7357 	iwn_prph_setbits(sc, IWN5000_SCHED_INTR_MASK, 1 << qid);
7358 
7359 	/* Mark the queue as active. */
7360 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
7361 	    IWN5000_TXQ_STATUS_ACTIVE | iwn_tid2fifo[tid]);
7362 }
7363 
7364 static void
7365 iwn5000_ampdu_tx_stop(struct iwn_softc *sc, int qid, uint8_t tid, uint16_t ssn)
7366 {
7367 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7368 
7369 	/* Stop TX scheduler while we're changing its configuration. */
7370 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
7371 	    IWN5000_TXQ_STATUS_CHGACT);
7372 
7373 	/* Disable aggregation for the queue. */
7374 	iwn_prph_clrbits(sc, IWN5000_SCHED_AGGR_SEL, 1 << qid);
7375 
7376 	/* Set starting sequence number from the ADDBA request. */
7377 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | (ssn & 0xff));
7378 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_RDPTR(qid), ssn);
7379 
7380 	/* Disable interrupts for the queue. */
7381 	iwn_prph_clrbits(sc, IWN5000_SCHED_INTR_MASK, 1 << qid);
7382 
7383 	/* Mark the queue as inactive. */
7384 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
7385 	    IWN5000_TXQ_STATUS_INACTIVE | iwn_tid2fifo[tid]);
7386 }
7387 
7388 /*
7389  * Query calibration tables from the initialization firmware.  We do this
7390  * only once at first boot.  Called from a process context.
7391  */
7392 static int
7393 iwn5000_query_calibration(struct iwn_softc *sc)
7394 {
7395 	struct iwn5000_calib_config cmd;
7396 	int error;
7397 
7398 	memset(&cmd, 0, sizeof cmd);
7399 	cmd.ucode.once.enable = htole32(0xffffffff);
7400 	cmd.ucode.once.start  = htole32(0xffffffff);
7401 	cmd.ucode.once.send   = htole32(0xffffffff);
7402 	cmd.ucode.flags       = htole32(0xffffffff);
7403 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: sending calibration query\n",
7404 	    __func__);
7405 	error = iwn_cmd(sc, IWN5000_CMD_CALIB_CONFIG, &cmd, sizeof cmd, 0);
7406 	if (error != 0)
7407 		return error;
7408 
7409 	/* Wait at most two seconds for calibration to complete. */
7410 	if (!(sc->sc_flags & IWN_FLAG_CALIB_DONE))
7411 		error = msleep(sc, &sc->sc_mtx, PCATCH, "iwncal", 2 * hz);
7412 	return error;
7413 }
7414 
7415 /*
7416  * Send calibration results to the runtime firmware.  These results were
7417  * obtained on first boot from the initialization firmware.
7418  */
7419 static int
7420 iwn5000_send_calibration(struct iwn_softc *sc)
7421 {
7422 	int idx, error;
7423 
7424 	for (idx = 0; idx < IWN5000_PHY_CALIB_MAX_RESULT; idx++) {
7425 		if (!(sc->base_params->calib_need & (1<<idx))) {
7426 			DPRINTF(sc, IWN_DEBUG_CALIBRATE,
7427 			    "No need of calib %d\n",
7428 			    idx);
7429 			continue; /* no need for this calib */
7430 		}
7431 		if (sc->calibcmd[idx].buf == NULL) {
7432 			DPRINTF(sc, IWN_DEBUG_CALIBRATE,
7433 			    "Need calib idx : %d but no available data\n",
7434 			    idx);
7435 			continue;
7436 		}
7437 
7438 		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
7439 		    "send calibration result idx=%d len=%d\n", idx,
7440 		    sc->calibcmd[idx].len);
7441 		error = iwn_cmd(sc, IWN_CMD_PHY_CALIB, sc->calibcmd[idx].buf,
7442 		    sc->calibcmd[idx].len, 0);
7443 		if (error != 0) {
7444 			device_printf(sc->sc_dev,
7445 			    "%s: could not send calibration result, error %d\n",
7446 			    __func__, error);
7447 			return error;
7448 		}
7449 	}
7450 	return 0;
7451 }
7452 
7453 static int
7454 iwn5000_send_wimax_coex(struct iwn_softc *sc)
7455 {
7456 	struct iwn5000_wimax_coex wimax;
7457 
7458 #if 0
7459 	if (sc->hw_type == IWN_HW_REV_TYPE_6050) {
7460 		/* Enable WiMAX coexistence for combo adapters. */
7461 		wimax.flags =
7462 		    IWN_WIMAX_COEX_ASSOC_WA_UNMASK |
7463 		    IWN_WIMAX_COEX_UNASSOC_WA_UNMASK |
7464 		    IWN_WIMAX_COEX_STA_TABLE_VALID |
7465 		    IWN_WIMAX_COEX_ENABLE;
7466 		memcpy(wimax.events, iwn6050_wimax_events,
7467 		    sizeof iwn6050_wimax_events);
7468 	} else
7469 #endif
7470 	{
7471 		/* Disable WiMAX coexistence. */
7472 		wimax.flags = 0;
7473 		memset(wimax.events, 0, sizeof wimax.events);
7474 	}
7475 	DPRINTF(sc, IWN_DEBUG_RESET, "%s: Configuring WiMAX coexistence\n",
7476 	    __func__);
7477 	return iwn_cmd(sc, IWN5000_CMD_WIMAX_COEX, &wimax, sizeof wimax, 0);
7478 }
7479 
7480 static int
7481 iwn5000_crystal_calib(struct iwn_softc *sc)
7482 {
7483 	struct iwn5000_phy_calib_crystal cmd;
7484 
7485 	memset(&cmd, 0, sizeof cmd);
7486 	cmd.code = IWN5000_PHY_CALIB_CRYSTAL;
7487 	cmd.ngroups = 1;
7488 	cmd.isvalid = 1;
7489 	cmd.cap_pin[0] = le32toh(sc->eeprom_crystal) & 0xff;
7490 	cmd.cap_pin[1] = (le32toh(sc->eeprom_crystal) >> 16) & 0xff;
7491 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "sending crystal calibration %d, %d\n",
7492 	    cmd.cap_pin[0], cmd.cap_pin[1]);
7493 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 0);
7494 }
7495 
7496 static int
7497 iwn5000_temp_offset_calib(struct iwn_softc *sc)
7498 {
7499 	struct iwn5000_phy_calib_temp_offset cmd;
7500 
7501 	memset(&cmd, 0, sizeof cmd);
7502 	cmd.code = IWN5000_PHY_CALIB_TEMP_OFFSET;
7503 	cmd.ngroups = 1;
7504 	cmd.isvalid = 1;
7505 	if (sc->eeprom_temp != 0)
7506 		cmd.offset = htole16(sc->eeprom_temp);
7507 	else
7508 		cmd.offset = htole16(IWN_DEFAULT_TEMP_OFFSET);
7509 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "setting radio sensor offset to %d\n",
7510 	    le16toh(cmd.offset));
7511 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 0);
7512 }
7513 
7514 static int
7515 iwn5000_temp_offset_calibv2(struct iwn_softc *sc)
7516 {
7517 	struct iwn5000_phy_calib_temp_offsetv2 cmd;
7518 
7519 	memset(&cmd, 0, sizeof cmd);
7520 	cmd.code = IWN5000_PHY_CALIB_TEMP_OFFSET;
7521 	cmd.ngroups = 1;
7522 	cmd.isvalid = 1;
7523 	if (sc->eeprom_temp != 0) {
7524 		cmd.offset_low = htole16(sc->eeprom_temp);
7525 		cmd.offset_high = htole16(sc->eeprom_temp_high);
7526 	} else {
7527 		cmd.offset_low = htole16(IWN_DEFAULT_TEMP_OFFSET);
7528 		cmd.offset_high = htole16(IWN_DEFAULT_TEMP_OFFSET);
7529 	}
7530 	cmd.burnt_voltage_ref = htole16(sc->eeprom_voltage);
7531 
7532 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
7533 	    "setting radio sensor low offset to %d, high offset to %d, voltage to %d\n",
7534 	    le16toh(cmd.offset_low),
7535 	    le16toh(cmd.offset_high),
7536 	    le16toh(cmd.burnt_voltage_ref));
7537 
7538 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 0);
7539 }
7540 
7541 /*
7542  * This function is called after the runtime firmware notifies us of its
7543  * readiness (called in a process context).
7544  */
7545 static int
7546 iwn4965_post_alive(struct iwn_softc *sc)
7547 {
7548 	int error, qid;
7549 
7550 	if ((error = iwn_nic_lock(sc)) != 0)
7551 		return error;
7552 
7553 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7554 
7555 	/* Clear TX scheduler state in SRAM. */
7556 	sc->sched_base = iwn_prph_read(sc, IWN_SCHED_SRAM_ADDR);
7557 	iwn_mem_set_region_4(sc, sc->sched_base + IWN4965_SCHED_CTX_OFF, 0,
7558 	    IWN4965_SCHED_CTX_LEN / sizeof (uint32_t));
7559 
7560 	/* Set physical address of TX scheduler rings (1KB aligned). */
7561 	iwn_prph_write(sc, IWN4965_SCHED_DRAM_ADDR, sc->sched_dma.paddr >> 10);
7562 
7563 	IWN_SETBITS(sc, IWN_FH_TX_CHICKEN, IWN_FH_TX_CHICKEN_SCHED_RETRY);
7564 
7565 	/* Disable chain mode for all our 16 queues. */
7566 	iwn_prph_write(sc, IWN4965_SCHED_QCHAIN_SEL, 0);
7567 
7568 	for (qid = 0; qid < IWN4965_NTXQUEUES; qid++) {
7569 		iwn_prph_write(sc, IWN4965_SCHED_QUEUE_RDPTR(qid), 0);
7570 		IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | 0);
7571 
7572 		/* Set scheduler window size. */
7573 		iwn_mem_write(sc, sc->sched_base +
7574 		    IWN4965_SCHED_QUEUE_OFFSET(qid), IWN_SCHED_WINSZ);
7575 		/* Set scheduler frame limit. */
7576 		iwn_mem_write(sc, sc->sched_base +
7577 		    IWN4965_SCHED_QUEUE_OFFSET(qid) + 4,
7578 		    IWN_SCHED_LIMIT << 16);
7579 	}
7580 
7581 	/* Enable interrupts for all our 16 queues. */
7582 	iwn_prph_write(sc, IWN4965_SCHED_INTR_MASK, 0xffff);
7583 	/* Identify TX FIFO rings (0-7). */
7584 	iwn_prph_write(sc, IWN4965_SCHED_TXFACT, 0xff);
7585 
7586 	/* Mark TX rings (4 EDCA + cmd + 2 HCCA) as active. */
7587 	for (qid = 0; qid < 7; qid++) {
7588 		static uint8_t qid2fifo[] = { 3, 2, 1, 0, 4, 5, 6 };
7589 		iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
7590 		    IWN4965_TXQ_STATUS_ACTIVE | qid2fifo[qid] << 1);
7591 	}
7592 	iwn_nic_unlock(sc);
7593 	return 0;
7594 }
7595 
7596 /*
7597  * This function is called after the initialization or runtime firmware
7598  * notifies us of its readiness (called in a process context).
7599  */
7600 static int
7601 iwn5000_post_alive(struct iwn_softc *sc)
7602 {
7603 	int error, qid;
7604 
7605 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
7606 
7607 	/* Switch to using ICT interrupt mode. */
7608 	iwn5000_ict_reset(sc);
7609 
7610 	if ((error = iwn_nic_lock(sc)) != 0){
7611 		DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end in error\n", __func__);
7612 		return error;
7613 	}
7614 
7615 	/* Clear TX scheduler state in SRAM. */
7616 	sc->sched_base = iwn_prph_read(sc, IWN_SCHED_SRAM_ADDR);
7617 	iwn_mem_set_region_4(sc, sc->sched_base + IWN5000_SCHED_CTX_OFF, 0,
7618 	    IWN5000_SCHED_CTX_LEN / sizeof (uint32_t));
7619 
7620 	/* Set physical address of TX scheduler rings (1KB aligned). */
7621 	iwn_prph_write(sc, IWN5000_SCHED_DRAM_ADDR, sc->sched_dma.paddr >> 10);
7622 
7623 	IWN_SETBITS(sc, IWN_FH_TX_CHICKEN, IWN_FH_TX_CHICKEN_SCHED_RETRY);
7624 
7625 	/* Enable chain mode for all queues, except command queue. */
7626 	if (sc->sc_flags & IWN_FLAG_PAN_SUPPORT)
7627 		iwn_prph_write(sc, IWN5000_SCHED_QCHAIN_SEL, 0xfffdf);
7628 	else
7629 		iwn_prph_write(sc, IWN5000_SCHED_QCHAIN_SEL, 0xfffef);
7630 	iwn_prph_write(sc, IWN5000_SCHED_AGGR_SEL, 0);
7631 
7632 	for (qid = 0; qid < IWN5000_NTXQUEUES; qid++) {
7633 		iwn_prph_write(sc, IWN5000_SCHED_QUEUE_RDPTR(qid), 0);
7634 		IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | 0);
7635 
7636 		iwn_mem_write(sc, sc->sched_base +
7637 		    IWN5000_SCHED_QUEUE_OFFSET(qid), 0);
7638 		/* Set scheduler window size and frame limit. */
7639 		iwn_mem_write(sc, sc->sched_base +
7640 		    IWN5000_SCHED_QUEUE_OFFSET(qid) + 4,
7641 		    IWN_SCHED_LIMIT << 16 | IWN_SCHED_WINSZ);
7642 	}
7643 
7644 	/* Enable interrupts for all our 20 queues. */
7645 	iwn_prph_write(sc, IWN5000_SCHED_INTR_MASK, 0xfffff);
7646 	/* Identify TX FIFO rings (0-7). */
7647 	iwn_prph_write(sc, IWN5000_SCHED_TXFACT, 0xff);
7648 
7649 	/* Mark TX rings (4 EDCA + cmd + 2 HCCA) as active. */
7650 	if (sc->sc_flags & IWN_FLAG_PAN_SUPPORT) {
7651 		/* Mark TX rings as active. */
7652 		for (qid = 0; qid < 11; qid++) {
7653 			static uint8_t qid2fifo[] = { 3, 2, 1, 0, 0, 4, 2, 5, 4, 7, 5 };
7654 			iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
7655 			    IWN5000_TXQ_STATUS_ACTIVE | qid2fifo[qid]);
7656 		}
7657 	} else {
7658 		/* Mark TX rings (4 EDCA + cmd + 2 HCCA) as active. */
7659 		for (qid = 0; qid < 7; qid++) {
7660 			static uint8_t qid2fifo[] = { 3, 2, 1, 0, 7, 5, 6 };
7661 			iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
7662 			    IWN5000_TXQ_STATUS_ACTIVE | qid2fifo[qid]);
7663 		}
7664 	}
7665 	iwn_nic_unlock(sc);
7666 
7667 	/* Configure WiMAX coexistence for combo adapters. */
7668 	error = iwn5000_send_wimax_coex(sc);
7669 	if (error != 0) {
7670 		device_printf(sc->sc_dev,
7671 		    "%s: could not configure WiMAX coexistence, error %d\n",
7672 		    __func__, error);
7673 		return error;
7674 	}
7675 	if (sc->hw_type != IWN_HW_REV_TYPE_5150) {
7676 		/* Perform crystal calibration. */
7677 		error = iwn5000_crystal_calib(sc);
7678 		if (error != 0) {
7679 			device_printf(sc->sc_dev,
7680 			    "%s: crystal calibration failed, error %d\n",
7681 			    __func__, error);
7682 			return error;
7683 		}
7684 	}
7685 	if (!(sc->sc_flags & IWN_FLAG_CALIB_DONE)) {
7686 		/* Query calibration from the initialization firmware. */
7687 		if ((error = iwn5000_query_calibration(sc)) != 0) {
7688 			device_printf(sc->sc_dev,
7689 			    "%s: could not query calibration, error %d\n",
7690 			    __func__, error);
7691 			return error;
7692 		}
7693 		/*
7694 		 * We have the calibration results now, reboot with the
7695 		 * runtime firmware (call ourselves recursively!)
7696 		 */
7697 		iwn_hw_stop(sc);
7698 		error = iwn_hw_init(sc);
7699 	} else {
7700 		/* Send calibration results to runtime firmware. */
7701 		error = iwn5000_send_calibration(sc);
7702 	}
7703 
7704 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
7705 
7706 	return error;
7707 }
7708 
7709 /*
7710  * The firmware boot code is small and is intended to be copied directly into
7711  * the NIC internal memory (no DMA transfer).
7712  */
7713 static int
7714 iwn4965_load_bootcode(struct iwn_softc *sc, const uint8_t *ucode, int size)
7715 {
7716 	int error, ntries;
7717 
7718 	size /= sizeof (uint32_t);
7719 
7720 	if ((error = iwn_nic_lock(sc)) != 0)
7721 		return error;
7722 
7723 	/* Copy microcode image into NIC memory. */
7724 	iwn_prph_write_region_4(sc, IWN_BSM_SRAM_BASE,
7725 	    (const uint32_t *)ucode, size);
7726 
7727 	iwn_prph_write(sc, IWN_BSM_WR_MEM_SRC, 0);
7728 	iwn_prph_write(sc, IWN_BSM_WR_MEM_DST, IWN_FW_TEXT_BASE);
7729 	iwn_prph_write(sc, IWN_BSM_WR_DWCOUNT, size);
7730 
7731 	/* Start boot load now. */
7732 	iwn_prph_write(sc, IWN_BSM_WR_CTRL, IWN_BSM_WR_CTRL_START);
7733 
7734 	/* Wait for transfer to complete. */
7735 	for (ntries = 0; ntries < 1000; ntries++) {
7736 		if (!(iwn_prph_read(sc, IWN_BSM_WR_CTRL) &
7737 		    IWN_BSM_WR_CTRL_START))
7738 			break;
7739 		DELAY(10);
7740 	}
7741 	if (ntries == 1000) {
7742 		device_printf(sc->sc_dev, "%s: could not load boot firmware\n",
7743 		    __func__);
7744 		iwn_nic_unlock(sc);
7745 		return ETIMEDOUT;
7746 	}
7747 
7748 	/* Enable boot after power up. */
7749 	iwn_prph_write(sc, IWN_BSM_WR_CTRL, IWN_BSM_WR_CTRL_START_EN);
7750 
7751 	iwn_nic_unlock(sc);
7752 	return 0;
7753 }
7754 
7755 static int
7756 iwn4965_load_firmware(struct iwn_softc *sc)
7757 {
7758 	struct iwn_fw_info *fw = &sc->fw;
7759 	struct iwn_dma_info *dma = &sc->fw_dma;
7760 	int error;
7761 
7762 	/* Copy initialization sections into pre-allocated DMA-safe memory. */
7763 	memcpy(dma->vaddr, fw->init.data, fw->init.datasz);
7764 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
7765 	memcpy(dma->vaddr + IWN4965_FW_DATA_MAXSZ,
7766 	    fw->init.text, fw->init.textsz);
7767 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
7768 
7769 	/* Tell adapter where to find initialization sections. */
7770 	if ((error = iwn_nic_lock(sc)) != 0)
7771 		return error;
7772 	iwn_prph_write(sc, IWN_BSM_DRAM_DATA_ADDR, dma->paddr >> 4);
7773 	iwn_prph_write(sc, IWN_BSM_DRAM_DATA_SIZE, fw->init.datasz);
7774 	iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_ADDR,
7775 	    (dma->paddr + IWN4965_FW_DATA_MAXSZ) >> 4);
7776 	iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_SIZE, fw->init.textsz);
7777 	iwn_nic_unlock(sc);
7778 
7779 	/* Load firmware boot code. */
7780 	error = iwn4965_load_bootcode(sc, fw->boot.text, fw->boot.textsz);
7781 	if (error != 0) {
7782 		device_printf(sc->sc_dev, "%s: could not load boot firmware\n",
7783 		    __func__);
7784 		return error;
7785 	}
7786 	/* Now press "execute". */
7787 	IWN_WRITE(sc, IWN_RESET, 0);
7788 
7789 	/* Wait at most one second for first alive notification. */
7790 	if ((error = msleep(sc, &sc->sc_mtx, PCATCH, "iwninit", hz)) != 0) {
7791 		device_printf(sc->sc_dev,
7792 		    "%s: timeout waiting for adapter to initialize, error %d\n",
7793 		    __func__, error);
7794 		return error;
7795 	}
7796 
7797 	/* Retrieve current temperature for initial TX power calibration. */
7798 	sc->rawtemp = sc->ucode_info.temp[3].chan20MHz;
7799 	sc->temp = iwn4965_get_temperature(sc);
7800 
7801 	/* Copy runtime sections into pre-allocated DMA-safe memory. */
7802 	memcpy(dma->vaddr, fw->main.data, fw->main.datasz);
7803 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
7804 	memcpy(dma->vaddr + IWN4965_FW_DATA_MAXSZ,
7805 	    fw->main.text, fw->main.textsz);
7806 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
7807 
7808 	/* Tell adapter where to find runtime sections. */
7809 	if ((error = iwn_nic_lock(sc)) != 0)
7810 		return error;
7811 	iwn_prph_write(sc, IWN_BSM_DRAM_DATA_ADDR, dma->paddr >> 4);
7812 	iwn_prph_write(sc, IWN_BSM_DRAM_DATA_SIZE, fw->main.datasz);
7813 	iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_ADDR,
7814 	    (dma->paddr + IWN4965_FW_DATA_MAXSZ) >> 4);
7815 	iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_SIZE,
7816 	    IWN_FW_UPDATED | fw->main.textsz);
7817 	iwn_nic_unlock(sc);
7818 
7819 	return 0;
7820 }
7821 
7822 static int
7823 iwn5000_load_firmware_section(struct iwn_softc *sc, uint32_t dst,
7824     const uint8_t *section, int size)
7825 {
7826 	struct iwn_dma_info *dma = &sc->fw_dma;
7827 	int error;
7828 
7829 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7830 
7831 	/* Copy firmware section into pre-allocated DMA-safe memory. */
7832 	memcpy(dma->vaddr, section, size);
7833 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
7834 
7835 	if ((error = iwn_nic_lock(sc)) != 0)
7836 		return error;
7837 
7838 	IWN_WRITE(sc, IWN_FH_TX_CONFIG(IWN_SRVC_DMACHNL),
7839 	    IWN_FH_TX_CONFIG_DMA_PAUSE);
7840 
7841 	IWN_WRITE(sc, IWN_FH_SRAM_ADDR(IWN_SRVC_DMACHNL), dst);
7842 	IWN_WRITE(sc, IWN_FH_TFBD_CTRL0(IWN_SRVC_DMACHNL),
7843 	    IWN_LOADDR(dma->paddr));
7844 	IWN_WRITE(sc, IWN_FH_TFBD_CTRL1(IWN_SRVC_DMACHNL),
7845 	    IWN_HIADDR(dma->paddr) << 28 | size);
7846 	IWN_WRITE(sc, IWN_FH_TXBUF_STATUS(IWN_SRVC_DMACHNL),
7847 	    IWN_FH_TXBUF_STATUS_TBNUM(1) |
7848 	    IWN_FH_TXBUF_STATUS_TBIDX(1) |
7849 	    IWN_FH_TXBUF_STATUS_TFBD_VALID);
7850 
7851 	/* Kick Flow Handler to start DMA transfer. */
7852 	IWN_WRITE(sc, IWN_FH_TX_CONFIG(IWN_SRVC_DMACHNL),
7853 	    IWN_FH_TX_CONFIG_DMA_ENA | IWN_FH_TX_CONFIG_CIRQ_HOST_ENDTFD);
7854 
7855 	iwn_nic_unlock(sc);
7856 
7857 	/* Wait at most five seconds for FH DMA transfer to complete. */
7858 	return msleep(sc, &sc->sc_mtx, PCATCH, "iwninit", 5 * hz);
7859 }
7860 
7861 static int
7862 iwn5000_load_firmware(struct iwn_softc *sc)
7863 {
7864 	struct iwn_fw_part *fw;
7865 	int error;
7866 
7867 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7868 
7869 	/* Load the initialization firmware on first boot only. */
7870 	fw = (sc->sc_flags & IWN_FLAG_CALIB_DONE) ?
7871 	    &sc->fw.main : &sc->fw.init;
7872 
7873 	error = iwn5000_load_firmware_section(sc, IWN_FW_TEXT_BASE,
7874 	    fw->text, fw->textsz);
7875 	if (error != 0) {
7876 		device_printf(sc->sc_dev,
7877 		    "%s: could not load firmware %s section, error %d\n",
7878 		    __func__, ".text", error);
7879 		return error;
7880 	}
7881 	error = iwn5000_load_firmware_section(sc, IWN_FW_DATA_BASE,
7882 	    fw->data, fw->datasz);
7883 	if (error != 0) {
7884 		device_printf(sc->sc_dev,
7885 		    "%s: could not load firmware %s section, error %d\n",
7886 		    __func__, ".data", error);
7887 		return error;
7888 	}
7889 
7890 	/* Now press "execute". */
7891 	IWN_WRITE(sc, IWN_RESET, 0);
7892 	return 0;
7893 }
7894 
7895 /*
7896  * Extract text and data sections from a legacy firmware image.
7897  */
7898 static int
7899 iwn_read_firmware_leg(struct iwn_softc *sc, struct iwn_fw_info *fw)
7900 {
7901 	const uint32_t *ptr;
7902 	size_t hdrlen = 24;
7903 	uint32_t rev;
7904 
7905 	ptr = (const uint32_t *)fw->data;
7906 	rev = le32toh(*ptr++);
7907 
7908 	sc->ucode_rev = rev;
7909 
7910 	/* Check firmware API version. */
7911 	if (IWN_FW_API(rev) <= 1) {
7912 		device_printf(sc->sc_dev,
7913 		    "%s: bad firmware, need API version >=2\n", __func__);
7914 		return EINVAL;
7915 	}
7916 	if (IWN_FW_API(rev) >= 3) {
7917 		/* Skip build number (version 2 header). */
7918 		hdrlen += 4;
7919 		ptr++;
7920 	}
7921 	if (fw->size < hdrlen) {
7922 		device_printf(sc->sc_dev, "%s: firmware too short: %zu bytes\n",
7923 		    __func__, fw->size);
7924 		return EINVAL;
7925 	}
7926 	fw->main.textsz = le32toh(*ptr++);
7927 	fw->main.datasz = le32toh(*ptr++);
7928 	fw->init.textsz = le32toh(*ptr++);
7929 	fw->init.datasz = le32toh(*ptr++);
7930 	fw->boot.textsz = le32toh(*ptr++);
7931 
7932 	/* Check that all firmware sections fit. */
7933 	if (fw->size < hdrlen + fw->main.textsz + fw->main.datasz +
7934 	    fw->init.textsz + fw->init.datasz + fw->boot.textsz) {
7935 		device_printf(sc->sc_dev, "%s: firmware too short: %zu bytes\n",
7936 		    __func__, fw->size);
7937 		return EINVAL;
7938 	}
7939 
7940 	/* Get pointers to firmware sections. */
7941 	fw->main.text = (const uint8_t *)ptr;
7942 	fw->main.data = fw->main.text + fw->main.textsz;
7943 	fw->init.text = fw->main.data + fw->main.datasz;
7944 	fw->init.data = fw->init.text + fw->init.textsz;
7945 	fw->boot.text = fw->init.data + fw->init.datasz;
7946 	return 0;
7947 }
7948 
7949 /*
7950  * Extract text and data sections from a TLV firmware image.
7951  */
7952 static int
7953 iwn_read_firmware_tlv(struct iwn_softc *sc, struct iwn_fw_info *fw,
7954     uint16_t alt)
7955 {
7956 	const struct iwn_fw_tlv_hdr *hdr;
7957 	const struct iwn_fw_tlv *tlv;
7958 	const uint8_t *ptr, *end;
7959 	uint64_t altmask;
7960 	uint32_t len, tmp;
7961 
7962 	if (fw->size < sizeof (*hdr)) {
7963 		device_printf(sc->sc_dev, "%s: firmware too short: %zu bytes\n",
7964 		    __func__, fw->size);
7965 		return EINVAL;
7966 	}
7967 	hdr = (const struct iwn_fw_tlv_hdr *)fw->data;
7968 	if (hdr->signature != htole32(IWN_FW_SIGNATURE)) {
7969 		device_printf(sc->sc_dev, "%s: bad firmware signature 0x%08x\n",
7970 		    __func__, le32toh(hdr->signature));
7971 		return EINVAL;
7972 	}
7973 	DPRINTF(sc, IWN_DEBUG_RESET, "FW: \"%.64s\", build 0x%x\n", hdr->descr,
7974 	    le32toh(hdr->build));
7975 	sc->ucode_rev = le32toh(hdr->rev);
7976 
7977 	/*
7978 	 * Select the closest supported alternative that is less than
7979 	 * or equal to the specified one.
7980 	 */
7981 	altmask = le64toh(hdr->altmask);
7982 	while (alt > 0 && !(altmask & (1ULL << alt)))
7983 		alt--;	/* Downgrade. */
7984 	DPRINTF(sc, IWN_DEBUG_RESET, "using alternative %d\n", alt);
7985 
7986 	ptr = (const uint8_t *)(hdr + 1);
7987 	end = (const uint8_t *)(fw->data + fw->size);
7988 
7989 	/* Parse type-length-value fields. */
7990 	while (ptr + sizeof (*tlv) <= end) {
7991 		tlv = (const struct iwn_fw_tlv *)ptr;
7992 		len = le32toh(tlv->len);
7993 
7994 		ptr += sizeof (*tlv);
7995 		if (ptr + len > end) {
7996 			device_printf(sc->sc_dev,
7997 			    "%s: firmware too short: %zu bytes\n", __func__,
7998 			    fw->size);
7999 			return EINVAL;
8000 		}
8001 		/* Skip other alternatives. */
8002 		if (tlv->alt != 0 && tlv->alt != htole16(alt))
8003 			goto next;
8004 
8005 		switch (le16toh(tlv->type)) {
8006 		case IWN_FW_TLV_MAIN_TEXT:
8007 			fw->main.text = ptr;
8008 			fw->main.textsz = len;
8009 			break;
8010 		case IWN_FW_TLV_MAIN_DATA:
8011 			fw->main.data = ptr;
8012 			fw->main.datasz = len;
8013 			break;
8014 		case IWN_FW_TLV_INIT_TEXT:
8015 			fw->init.text = ptr;
8016 			fw->init.textsz = len;
8017 			break;
8018 		case IWN_FW_TLV_INIT_DATA:
8019 			fw->init.data = ptr;
8020 			fw->init.datasz = len;
8021 			break;
8022 		case IWN_FW_TLV_BOOT_TEXT:
8023 			fw->boot.text = ptr;
8024 			fw->boot.textsz = len;
8025 			break;
8026 		case IWN_FW_TLV_ENH_SENS:
8027 			if (!len)
8028 				sc->sc_flags |= IWN_FLAG_ENH_SENS;
8029 			break;
8030 		case IWN_FW_TLV_PHY_CALIB:
8031 			tmp = le32toh(*ptr);
8032 			if (tmp < 253) {
8033 				sc->reset_noise_gain = tmp;
8034 				sc->noise_gain = tmp + 1;
8035 			}
8036 			break;
8037 		case IWN_FW_TLV_PAN:
8038 			sc->sc_flags |= IWN_FLAG_PAN_SUPPORT;
8039 			DPRINTF(sc, IWN_DEBUG_RESET,
8040 			    "PAN Support found: %d\n", 1);
8041 			break;
8042 		case IWN_FW_TLV_FLAGS:
8043 			if (len < sizeof(uint32_t))
8044 				break;
8045 			if (len % sizeof(uint32_t))
8046 				break;
8047 			sc->tlv_feature_flags = le32toh(*ptr);
8048 			DPRINTF(sc, IWN_DEBUG_RESET,
8049 			    "%s: feature: 0x%08x\n",
8050 			    __func__,
8051 			    sc->tlv_feature_flags);
8052 			break;
8053 		case IWN_FW_TLV_PBREQ_MAXLEN:
8054 		case IWN_FW_TLV_RUNT_EVTLOG_PTR:
8055 		case IWN_FW_TLV_RUNT_EVTLOG_SIZE:
8056 		case IWN_FW_TLV_RUNT_ERRLOG_PTR:
8057 		case IWN_FW_TLV_INIT_EVTLOG_PTR:
8058 		case IWN_FW_TLV_INIT_EVTLOG_SIZE:
8059 		case IWN_FW_TLV_INIT_ERRLOG_PTR:
8060 		case IWN_FW_TLV_WOWLAN_INST:
8061 		case IWN_FW_TLV_WOWLAN_DATA:
8062 			DPRINTF(sc, IWN_DEBUG_RESET,
8063 			    "TLV type %d reconized but not handled\n",
8064 			    le16toh(tlv->type));
8065 			break;
8066 		default:
8067 			DPRINTF(sc, IWN_DEBUG_RESET,
8068 			    "TLV type %d not handled\n", le16toh(tlv->type));
8069 			break;
8070 		}
8071  next:		/* TLV fields are 32-bit aligned. */
8072 		ptr += (len + 3) & ~3;
8073 	}
8074 	return 0;
8075 }
8076 
8077 static int
8078 iwn_read_firmware(struct iwn_softc *sc)
8079 {
8080 	struct iwn_fw_info *fw = &sc->fw;
8081 	int error;
8082 
8083 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
8084 
8085 	IWN_UNLOCK(sc);
8086 
8087 	memset(fw, 0, sizeof (*fw));
8088 
8089 	/* Read firmware image from filesystem. */
8090 	sc->fw_fp = firmware_get(sc->fwname);
8091 	if (sc->fw_fp == NULL) {
8092 		device_printf(sc->sc_dev, "%s: could not read firmware %s\n",
8093 		    __func__, sc->fwname);
8094 		IWN_LOCK(sc);
8095 		return EINVAL;
8096 	}
8097 	IWN_LOCK(sc);
8098 
8099 	fw->size = sc->fw_fp->datasize;
8100 	fw->data = (const uint8_t *)sc->fw_fp->data;
8101 	if (fw->size < sizeof (uint32_t)) {
8102 		device_printf(sc->sc_dev, "%s: firmware too short: %zu bytes\n",
8103 		    __func__, fw->size);
8104 		firmware_put(sc->fw_fp, FIRMWARE_UNLOAD);
8105 		sc->fw_fp = NULL;
8106 		return EINVAL;
8107 	}
8108 
8109 	/* Retrieve text and data sections. */
8110 	if (*(const uint32_t *)fw->data != 0)	/* Legacy image. */
8111 		error = iwn_read_firmware_leg(sc, fw);
8112 	else
8113 		error = iwn_read_firmware_tlv(sc, fw, 1);
8114 	if (error != 0) {
8115 		device_printf(sc->sc_dev,
8116 		    "%s: could not read firmware sections, error %d\n",
8117 		    __func__, error);
8118 		firmware_put(sc->fw_fp, FIRMWARE_UNLOAD);
8119 		sc->fw_fp = NULL;
8120 		return error;
8121 	}
8122 
8123 	device_printf(sc->sc_dev, "%s: ucode rev=0x%08x\n", __func__, sc->ucode_rev);
8124 
8125 	/* Make sure text and data sections fit in hardware memory. */
8126 	if (fw->main.textsz > sc->fw_text_maxsz ||
8127 	    fw->main.datasz > sc->fw_data_maxsz ||
8128 	    fw->init.textsz > sc->fw_text_maxsz ||
8129 	    fw->init.datasz > sc->fw_data_maxsz ||
8130 	    fw->boot.textsz > IWN_FW_BOOT_TEXT_MAXSZ ||
8131 	    (fw->boot.textsz & 3) != 0) {
8132 		device_printf(sc->sc_dev, "%s: firmware sections too large\n",
8133 		    __func__);
8134 		firmware_put(sc->fw_fp, FIRMWARE_UNLOAD);
8135 		sc->fw_fp = NULL;
8136 		return EINVAL;
8137 	}
8138 
8139 	/* We can proceed with loading the firmware. */
8140 	return 0;
8141 }
8142 
8143 static int
8144 iwn_clock_wait(struct iwn_softc *sc)
8145 {
8146 	int ntries;
8147 
8148 	/* Set "initialization complete" bit. */
8149 	IWN_SETBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_INIT_DONE);
8150 
8151 	/* Wait for clock stabilization. */
8152 	for (ntries = 0; ntries < 2500; ntries++) {
8153 		if (IWN_READ(sc, IWN_GP_CNTRL) & IWN_GP_CNTRL_MAC_CLOCK_READY)
8154 			return 0;
8155 		DELAY(10);
8156 	}
8157 	device_printf(sc->sc_dev,
8158 	    "%s: timeout waiting for clock stabilization\n", __func__);
8159 	return ETIMEDOUT;
8160 }
8161 
8162 static int
8163 iwn_apm_init(struct iwn_softc *sc)
8164 {
8165 	uint32_t reg;
8166 	int error;
8167 
8168 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
8169 
8170 	/* Disable L0s exit timer (NMI bug workaround). */
8171 	IWN_SETBITS(sc, IWN_GIO_CHICKEN, IWN_GIO_CHICKEN_DIS_L0S_TIMER);
8172 	/* Don't wait for ICH L0s (ICH bug workaround). */
8173 	IWN_SETBITS(sc, IWN_GIO_CHICKEN, IWN_GIO_CHICKEN_L1A_NO_L0S_RX);
8174 
8175 	/* Set FH wait threshold to max (HW bug under stress workaround). */
8176 	IWN_SETBITS(sc, IWN_DBG_HPET_MEM, 0xffff0000);
8177 
8178 	/* Enable HAP INTA to move adapter from L1a to L0s. */
8179 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_HAP_WAKE_L1A);
8180 
8181 	/* Retrieve PCIe Active State Power Management (ASPM). */
8182 	reg = pci_read_config(sc->sc_dev, sc->sc_cap_off + 0x10, 1);
8183 	/* Workaround for HW instability in PCIe L0->L0s->L1 transition. */
8184 	if (reg & 0x02)	/* L1 Entry enabled. */
8185 		IWN_SETBITS(sc, IWN_GIO, IWN_GIO_L0S_ENA);
8186 	else
8187 		IWN_CLRBITS(sc, IWN_GIO, IWN_GIO_L0S_ENA);
8188 
8189 	if (sc->base_params->pll_cfg_val)
8190 		IWN_SETBITS(sc, IWN_ANA_PLL, sc->base_params->pll_cfg_val);
8191 
8192 	/* Wait for clock stabilization before accessing prph. */
8193 	if ((error = iwn_clock_wait(sc)) != 0)
8194 		return error;
8195 
8196 	if ((error = iwn_nic_lock(sc)) != 0)
8197 		return error;
8198 	if (sc->hw_type == IWN_HW_REV_TYPE_4965) {
8199 		/* Enable DMA and BSM (Bootstrap State Machine). */
8200 		iwn_prph_write(sc, IWN_APMG_CLK_EN,
8201 		    IWN_APMG_CLK_CTRL_DMA_CLK_RQT |
8202 		    IWN_APMG_CLK_CTRL_BSM_CLK_RQT);
8203 	} else {
8204 		/* Enable DMA. */
8205 		iwn_prph_write(sc, IWN_APMG_CLK_EN,
8206 		    IWN_APMG_CLK_CTRL_DMA_CLK_RQT);
8207 	}
8208 	DELAY(20);
8209 	/* Disable L1-Active. */
8210 	iwn_prph_setbits(sc, IWN_APMG_PCI_STT, IWN_APMG_PCI_STT_L1A_DIS);
8211 	iwn_nic_unlock(sc);
8212 
8213 	return 0;
8214 }
8215 
8216 static void
8217 iwn_apm_stop_master(struct iwn_softc *sc)
8218 {
8219 	int ntries;
8220 
8221 	/* Stop busmaster DMA activity. */
8222 	IWN_SETBITS(sc, IWN_RESET, IWN_RESET_STOP_MASTER);
8223 	for (ntries = 0; ntries < 100; ntries++) {
8224 		if (IWN_READ(sc, IWN_RESET) & IWN_RESET_MASTER_DISABLED)
8225 			return;
8226 		DELAY(10);
8227 	}
8228 	device_printf(sc->sc_dev, "%s: timeout waiting for master\n", __func__);
8229 }
8230 
8231 static void
8232 iwn_apm_stop(struct iwn_softc *sc)
8233 {
8234 	iwn_apm_stop_master(sc);
8235 
8236 	/* Reset the entire device. */
8237 	IWN_SETBITS(sc, IWN_RESET, IWN_RESET_SW);
8238 	DELAY(10);
8239 	/* Clear "initialization complete" bit. */
8240 	IWN_CLRBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_INIT_DONE);
8241 }
8242 
8243 static int
8244 iwn4965_nic_config(struct iwn_softc *sc)
8245 {
8246 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
8247 
8248 	if (IWN_RFCFG_TYPE(sc->rfcfg) == 1) {
8249 		/*
8250 		 * I don't believe this to be correct but this is what the
8251 		 * vendor driver is doing. Probably the bits should not be
8252 		 * shifted in IWN_RFCFG_*.
8253 		 */
8254 		IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
8255 		    IWN_RFCFG_TYPE(sc->rfcfg) |
8256 		    IWN_RFCFG_STEP(sc->rfcfg) |
8257 		    IWN_RFCFG_DASH(sc->rfcfg));
8258 	}
8259 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
8260 	    IWN_HW_IF_CONFIG_RADIO_SI | IWN_HW_IF_CONFIG_MAC_SI);
8261 	return 0;
8262 }
8263 
8264 static int
8265 iwn5000_nic_config(struct iwn_softc *sc)
8266 {
8267 	uint32_t tmp;
8268 	int error;
8269 
8270 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
8271 
8272 	if (IWN_RFCFG_TYPE(sc->rfcfg) < 3) {
8273 		IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
8274 		    IWN_RFCFG_TYPE(sc->rfcfg) |
8275 		    IWN_RFCFG_STEP(sc->rfcfg) |
8276 		    IWN_RFCFG_DASH(sc->rfcfg));
8277 	}
8278 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
8279 	    IWN_HW_IF_CONFIG_RADIO_SI | IWN_HW_IF_CONFIG_MAC_SI);
8280 
8281 	if ((error = iwn_nic_lock(sc)) != 0)
8282 		return error;
8283 	iwn_prph_setbits(sc, IWN_APMG_PS, IWN_APMG_PS_EARLY_PWROFF_DIS);
8284 
8285 	if (sc->hw_type == IWN_HW_REV_TYPE_1000) {
8286 		/*
8287 		 * Select first Switching Voltage Regulator (1.32V) to
8288 		 * solve a stability issue related to noisy DC2DC line
8289 		 * in the silicon of 1000 Series.
8290 		 */
8291 		tmp = iwn_prph_read(sc, IWN_APMG_DIGITAL_SVR);
8292 		tmp &= ~IWN_APMG_DIGITAL_SVR_VOLTAGE_MASK;
8293 		tmp |= IWN_APMG_DIGITAL_SVR_VOLTAGE_1_32;
8294 		iwn_prph_write(sc, IWN_APMG_DIGITAL_SVR, tmp);
8295 	}
8296 	iwn_nic_unlock(sc);
8297 
8298 	if (sc->sc_flags & IWN_FLAG_INTERNAL_PA) {
8299 		/* Use internal power amplifier only. */
8300 		IWN_WRITE(sc, IWN_GP_DRIVER, IWN_GP_DRIVER_RADIO_2X2_IPA);
8301 	}
8302 	if (sc->base_params->additional_nic_config && sc->calib_ver >= 6) {
8303 		/* Indicate that ROM calibration version is >=6. */
8304 		IWN_SETBITS(sc, IWN_GP_DRIVER, IWN_GP_DRIVER_CALIB_VER6);
8305 	}
8306 	if (sc->base_params->additional_gp_drv_bit)
8307 		IWN_SETBITS(sc, IWN_GP_DRIVER,
8308 		    sc->base_params->additional_gp_drv_bit);
8309 	return 0;
8310 }
8311 
8312 /*
8313  * Take NIC ownership over Intel Active Management Technology (AMT).
8314  */
8315 static int
8316 iwn_hw_prepare(struct iwn_softc *sc)
8317 {
8318 	int ntries;
8319 
8320 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
8321 
8322 	/* Check if hardware is ready. */
8323 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_NIC_READY);
8324 	for (ntries = 0; ntries < 5; ntries++) {
8325 		if (IWN_READ(sc, IWN_HW_IF_CONFIG) &
8326 		    IWN_HW_IF_CONFIG_NIC_READY)
8327 			return 0;
8328 		DELAY(10);
8329 	}
8330 
8331 	/* Hardware not ready, force into ready state. */
8332 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_PREPARE);
8333 	for (ntries = 0; ntries < 15000; ntries++) {
8334 		if (!(IWN_READ(sc, IWN_HW_IF_CONFIG) &
8335 		    IWN_HW_IF_CONFIG_PREPARE_DONE))
8336 			break;
8337 		DELAY(10);
8338 	}
8339 	if (ntries == 15000)
8340 		return ETIMEDOUT;
8341 
8342 	/* Hardware should be ready now. */
8343 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_NIC_READY);
8344 	for (ntries = 0; ntries < 5; ntries++) {
8345 		if (IWN_READ(sc, IWN_HW_IF_CONFIG) &
8346 		    IWN_HW_IF_CONFIG_NIC_READY)
8347 			return 0;
8348 		DELAY(10);
8349 	}
8350 	return ETIMEDOUT;
8351 }
8352 
8353 static int
8354 iwn_hw_init(struct iwn_softc *sc)
8355 {
8356 	struct iwn_ops *ops = &sc->ops;
8357 	int error, chnl, qid;
8358 
8359 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
8360 
8361 	/* Clear pending interrupts. */
8362 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
8363 
8364 	if ((error = iwn_apm_init(sc)) != 0) {
8365 		device_printf(sc->sc_dev,
8366 		    "%s: could not power ON adapter, error %d\n", __func__,
8367 		    error);
8368 		return error;
8369 	}
8370 
8371 	/* Select VMAIN power source. */
8372 	if ((error = iwn_nic_lock(sc)) != 0)
8373 		return error;
8374 	iwn_prph_clrbits(sc, IWN_APMG_PS, IWN_APMG_PS_PWR_SRC_MASK);
8375 	iwn_nic_unlock(sc);
8376 
8377 	/* Perform adapter-specific initialization. */
8378 	if ((error = ops->nic_config(sc)) != 0)
8379 		return error;
8380 
8381 	/* Initialize RX ring. */
8382 	if ((error = iwn_nic_lock(sc)) != 0)
8383 		return error;
8384 	IWN_WRITE(sc, IWN_FH_RX_CONFIG, 0);
8385 	IWN_WRITE(sc, IWN_FH_RX_WPTR, 0);
8386 	/* Set physical address of RX ring (256-byte aligned). */
8387 	IWN_WRITE(sc, IWN_FH_RX_BASE, sc->rxq.desc_dma.paddr >> 8);
8388 	/* Set physical address of RX status (16-byte aligned). */
8389 	IWN_WRITE(sc, IWN_FH_STATUS_WPTR, sc->rxq.stat_dma.paddr >> 4);
8390 	/* Enable RX. */
8391 	IWN_WRITE(sc, IWN_FH_RX_CONFIG,
8392 	    IWN_FH_RX_CONFIG_ENA           |
8393 	    IWN_FH_RX_CONFIG_IGN_RXF_EMPTY |	/* HW bug workaround */
8394 	    IWN_FH_RX_CONFIG_IRQ_DST_HOST  |
8395 	    IWN_FH_RX_CONFIG_SINGLE_FRAME  |
8396 	    IWN_FH_RX_CONFIG_RB_TIMEOUT(0) |
8397 	    IWN_FH_RX_CONFIG_NRBD(IWN_RX_RING_COUNT_LOG));
8398 	iwn_nic_unlock(sc);
8399 	IWN_WRITE(sc, IWN_FH_RX_WPTR, (IWN_RX_RING_COUNT - 1) & ~7);
8400 
8401 	if ((error = iwn_nic_lock(sc)) != 0)
8402 		return error;
8403 
8404 	/* Initialize TX scheduler. */
8405 	iwn_prph_write(sc, sc->sched_txfact_addr, 0);
8406 
8407 	/* Set physical address of "keep warm" page (16-byte aligned). */
8408 	IWN_WRITE(sc, IWN_FH_KW_ADDR, sc->kw_dma.paddr >> 4);
8409 
8410 	/* Initialize TX rings. */
8411 	for (qid = 0; qid < sc->ntxqs; qid++) {
8412 		struct iwn_tx_ring *txq = &sc->txq[qid];
8413 
8414 		/* Set physical address of TX ring (256-byte aligned). */
8415 		IWN_WRITE(sc, IWN_FH_CBBC_QUEUE(qid),
8416 		    txq->desc_dma.paddr >> 8);
8417 	}
8418 	iwn_nic_unlock(sc);
8419 
8420 	/* Enable DMA channels. */
8421 	for (chnl = 0; chnl < sc->ndmachnls; chnl++) {
8422 		IWN_WRITE(sc, IWN_FH_TX_CONFIG(chnl),
8423 		    IWN_FH_TX_CONFIG_DMA_ENA |
8424 		    IWN_FH_TX_CONFIG_DMA_CREDIT_ENA);
8425 	}
8426 
8427 	/* Clear "radio off" and "commands blocked" bits. */
8428 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_RFKILL);
8429 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_CMD_BLOCKED);
8430 
8431 	/* Clear pending interrupts. */
8432 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
8433 	/* Enable interrupt coalescing. */
8434 	IWN_WRITE(sc, IWN_INT_COALESCING, 512 / 8);
8435 	/* Enable interrupts. */
8436 	IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
8437 
8438 	/* _Really_ make sure "radio off" bit is cleared! */
8439 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_RFKILL);
8440 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_RFKILL);
8441 
8442 	/* Enable shadow registers. */
8443 	if (sc->base_params->shadow_reg_enable)
8444 		IWN_SETBITS(sc, IWN_SHADOW_REG_CTRL, 0x800fffff);
8445 
8446 	if ((error = ops->load_firmware(sc)) != 0) {
8447 		device_printf(sc->sc_dev,
8448 		    "%s: could not load firmware, error %d\n", __func__,
8449 		    error);
8450 		return error;
8451 	}
8452 	/* Wait at most one second for firmware alive notification. */
8453 	if ((error = msleep(sc, &sc->sc_mtx, PCATCH, "iwninit", hz)) != 0) {
8454 		device_printf(sc->sc_dev,
8455 		    "%s: timeout waiting for adapter to initialize, error %d\n",
8456 		    __func__, error);
8457 		return error;
8458 	}
8459 	/* Do post-firmware initialization. */
8460 
8461 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
8462 
8463 	return ops->post_alive(sc);
8464 }
8465 
8466 static void
8467 iwn_hw_stop(struct iwn_softc *sc)
8468 {
8469 	int chnl, qid, ntries;
8470 
8471 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
8472 
8473 	IWN_WRITE(sc, IWN_RESET, IWN_RESET_NEVO);
8474 
8475 	/* Disable interrupts. */
8476 	IWN_WRITE(sc, IWN_INT_MASK, 0);
8477 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
8478 	IWN_WRITE(sc, IWN_FH_INT, 0xffffffff);
8479 	sc->sc_flags &= ~IWN_FLAG_USE_ICT;
8480 
8481 	/* Make sure we no longer hold the NIC lock. */
8482 	iwn_nic_unlock(sc);
8483 
8484 	/* Stop TX scheduler. */
8485 	iwn_prph_write(sc, sc->sched_txfact_addr, 0);
8486 
8487 	/* Stop all DMA channels. */
8488 	if (iwn_nic_lock(sc) == 0) {
8489 		for (chnl = 0; chnl < sc->ndmachnls; chnl++) {
8490 			IWN_WRITE(sc, IWN_FH_TX_CONFIG(chnl), 0);
8491 			for (ntries = 0; ntries < 200; ntries++) {
8492 				if (IWN_READ(sc, IWN_FH_TX_STATUS) &
8493 				    IWN_FH_TX_STATUS_IDLE(chnl))
8494 					break;
8495 				DELAY(10);
8496 			}
8497 		}
8498 		iwn_nic_unlock(sc);
8499 	}
8500 
8501 	/* Stop RX ring. */
8502 	iwn_reset_rx_ring(sc, &sc->rxq);
8503 
8504 	/* Reset all TX rings. */
8505 	for (qid = 0; qid < sc->ntxqs; qid++)
8506 		iwn_reset_tx_ring(sc, &sc->txq[qid]);
8507 
8508 	if (iwn_nic_lock(sc) == 0) {
8509 		iwn_prph_write(sc, IWN_APMG_CLK_DIS,
8510 		    IWN_APMG_CLK_CTRL_DMA_CLK_RQT);
8511 		iwn_nic_unlock(sc);
8512 	}
8513 	DELAY(5);
8514 	/* Power OFF adapter. */
8515 	iwn_apm_stop(sc);
8516 }
8517 
8518 static void
8519 iwn_radio_on(void *arg0, int pending)
8520 {
8521 	struct iwn_softc *sc = arg0;
8522 	struct ifnet *ifp = sc->sc_ifp;
8523 	struct ieee80211com *ic = ifp->if_l2com;
8524 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
8525 
8526 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
8527 
8528 	if (vap != NULL) {
8529 		iwn_init(sc);
8530 		ieee80211_init(vap);
8531 	}
8532 }
8533 
8534 static void
8535 iwn_radio_off(void *arg0, int pending)
8536 {
8537 	struct iwn_softc *sc = arg0;
8538 	struct ifnet *ifp = sc->sc_ifp;
8539 	struct ieee80211com *ic = ifp->if_l2com;
8540 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
8541 
8542 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
8543 
8544 	iwn_stop(sc);
8545 	if (vap != NULL)
8546 		ieee80211_stop(vap);
8547 
8548 	/* Enable interrupts to get RF toggle notification. */
8549 	IWN_LOCK(sc);
8550 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
8551 	IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
8552 	IWN_UNLOCK(sc);
8553 }
8554 
8555 static void
8556 iwn_panicked(void *arg0, int pending)
8557 {
8558 	struct iwn_softc *sc = arg0;
8559 	struct ifnet *ifp = sc->sc_ifp;
8560 	struct ieee80211com *ic = ifp->if_l2com;
8561 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
8562 	int error;
8563 
8564 	if (vap == NULL) {
8565 		printf("%s: null vap\n", __func__);
8566 		return;
8567 	}
8568 
8569 	device_printf(sc->sc_dev, "%s: controller panicked, iv_state = %d; "
8570 	    "resetting...\n", __func__, vap->iv_state);
8571 
8572 	IWN_LOCK(sc);
8573 
8574 	iwn_stop_locked(sc);
8575 	iwn_init_locked(sc);
8576 	if (vap->iv_state >= IEEE80211_S_AUTH &&
8577 	    (error = iwn_auth(sc, vap)) != 0) {
8578 		device_printf(sc->sc_dev,
8579 		    "%s: could not move to auth state\n", __func__);
8580 	}
8581 	if (vap->iv_state >= IEEE80211_S_RUN &&
8582 	    (error = iwn_run(sc, vap)) != 0) {
8583 		device_printf(sc->sc_dev,
8584 		    "%s: could not move to run state\n", __func__);
8585 	}
8586 
8587 	/* Only run start once the NIC is in a useful state, like associated */
8588 	iwn_start_locked(sc->sc_ifp);
8589 
8590 	IWN_UNLOCK(sc);
8591 }
8592 
8593 static void
8594 iwn_init_locked(struct iwn_softc *sc)
8595 {
8596 	struct ifnet *ifp = sc->sc_ifp;
8597 	int error;
8598 
8599 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
8600 
8601 	IWN_LOCK_ASSERT(sc);
8602 
8603 	if ((error = iwn_hw_prepare(sc)) != 0) {
8604 		device_printf(sc->sc_dev, "%s: hardware not ready, error %d\n",
8605 		    __func__, error);
8606 		goto fail;
8607 	}
8608 
8609 	/* Initialize interrupt mask to default value. */
8610 	sc->int_mask = IWN_INT_MASK_DEF;
8611 	sc->sc_flags &= ~IWN_FLAG_USE_ICT;
8612 
8613 	/* Check that the radio is not disabled by hardware switch. */
8614 	if (!(IWN_READ(sc, IWN_GP_CNTRL) & IWN_GP_CNTRL_RFKILL)) {
8615 		device_printf(sc->sc_dev,
8616 		    "radio is disabled by hardware switch\n");
8617 		/* Enable interrupts to get RF toggle notifications. */
8618 		IWN_WRITE(sc, IWN_INT, 0xffffffff);
8619 		IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
8620 		return;
8621 	}
8622 
8623 	/* Read firmware images from the filesystem. */
8624 	if ((error = iwn_read_firmware(sc)) != 0) {
8625 		device_printf(sc->sc_dev,
8626 		    "%s: could not read firmware, error %d\n", __func__,
8627 		    error);
8628 		goto fail;
8629 	}
8630 
8631 	/* Initialize hardware and upload firmware. */
8632 	error = iwn_hw_init(sc);
8633 	firmware_put(sc->fw_fp, FIRMWARE_UNLOAD);
8634 	sc->fw_fp = NULL;
8635 	if (error != 0) {
8636 		device_printf(sc->sc_dev,
8637 		    "%s: could not initialize hardware, error %d\n", __func__,
8638 		    error);
8639 		goto fail;
8640 	}
8641 
8642 	/* Configure adapter now that it is ready. */
8643 	if ((error = iwn_config(sc)) != 0) {
8644 		device_printf(sc->sc_dev,
8645 		    "%s: could not configure device, error %d\n", __func__,
8646 		    error);
8647 		goto fail;
8648 	}
8649 
8650 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
8651 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
8652 
8653 	callout_reset(&sc->watchdog_to, hz, iwn_watchdog, sc);
8654 
8655 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
8656 
8657 	return;
8658 
8659 fail:	iwn_stop_locked(sc);
8660 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end in error\n",__func__);
8661 }
8662 
8663 static void
8664 iwn_init(void *arg)
8665 {
8666 	struct iwn_softc *sc = arg;
8667 	struct ifnet *ifp = sc->sc_ifp;
8668 	struct ieee80211com *ic = ifp->if_l2com;
8669 
8670 	IWN_LOCK(sc);
8671 	iwn_init_locked(sc);
8672 	IWN_UNLOCK(sc);
8673 
8674 	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
8675 		ieee80211_start_all(ic);
8676 }
8677 
8678 static void
8679 iwn_stop_locked(struct iwn_softc *sc)
8680 {
8681 	struct ifnet *ifp = sc->sc_ifp;
8682 
8683 	IWN_LOCK_ASSERT(sc);
8684 
8685 	sc->sc_is_scanning = 0;
8686 	sc->sc_tx_timer = 0;
8687 	callout_stop(&sc->watchdog_to);
8688 	callout_stop(&sc->calib_to);
8689 	ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
8690 
8691 	/* Power OFF hardware. */
8692 	iwn_hw_stop(sc);
8693 }
8694 
8695 static void
8696 iwn_stop(struct iwn_softc *sc)
8697 {
8698 	IWN_LOCK(sc);
8699 	iwn_stop_locked(sc);
8700 	IWN_UNLOCK(sc);
8701 }
8702 
8703 /*
8704  * Callback from net80211 to start a scan.
8705  */
8706 static void
8707 iwn_scan_start(struct ieee80211com *ic)
8708 {
8709 	struct ifnet *ifp = ic->ic_ifp;
8710 	struct iwn_softc *sc = ifp->if_softc;
8711 
8712 	IWN_LOCK(sc);
8713 	/* make the link LED blink while we're scanning */
8714 	iwn_set_led(sc, IWN_LED_LINK, 20, 2);
8715 	IWN_UNLOCK(sc);
8716 }
8717 
8718 /*
8719  * Callback from net80211 to terminate a scan.
8720  */
8721 static void
8722 iwn_scan_end(struct ieee80211com *ic)
8723 {
8724 	struct ifnet *ifp = ic->ic_ifp;
8725 	struct iwn_softc *sc = ifp->if_softc;
8726 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
8727 
8728 	IWN_LOCK(sc);
8729 	if (vap->iv_state == IEEE80211_S_RUN) {
8730 		/* Set link LED to ON status if we are associated */
8731 		iwn_set_led(sc, IWN_LED_LINK, 0, 1);
8732 	}
8733 	IWN_UNLOCK(sc);
8734 }
8735 
8736 /*
8737  * Callback from net80211 to force a channel change.
8738  */
8739 static void
8740 iwn_set_channel(struct ieee80211com *ic)
8741 {
8742 	const struct ieee80211_channel *c = ic->ic_curchan;
8743 	struct ifnet *ifp = ic->ic_ifp;
8744 	struct iwn_softc *sc = ifp->if_softc;
8745 	int error;
8746 
8747 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
8748 
8749 	IWN_LOCK(sc);
8750 	sc->sc_rxtap.wr_chan_freq = htole16(c->ic_freq);
8751 	sc->sc_rxtap.wr_chan_flags = htole16(c->ic_flags);
8752 	sc->sc_txtap.wt_chan_freq = htole16(c->ic_freq);
8753 	sc->sc_txtap.wt_chan_flags = htole16(c->ic_flags);
8754 
8755 	/*
8756 	 * Only need to set the channel in Monitor mode. AP scanning and auth
8757 	 * are already taken care of by their respective firmware commands.
8758 	 */
8759 	if (ic->ic_opmode == IEEE80211_M_MONITOR) {
8760 		error = iwn_config(sc);
8761 		if (error != 0)
8762 		device_printf(sc->sc_dev,
8763 		    "%s: error %d settting channel\n", __func__, error);
8764 	}
8765 	IWN_UNLOCK(sc);
8766 }
8767 
8768 /*
8769  * Callback from net80211 to start scanning of the current channel.
8770  */
8771 static void
8772 iwn_scan_curchan(struct ieee80211_scan_state *ss, unsigned long maxdwell)
8773 {
8774 	struct ieee80211vap *vap = ss->ss_vap;
8775 	struct iwn_softc *sc = vap->iv_ic->ic_ifp->if_softc;
8776 	struct ieee80211com *ic = vap->iv_ic;
8777 	int error;
8778 
8779 	IWN_LOCK(sc);
8780 	error = iwn_scan(sc, vap, ss, ic->ic_curchan);
8781 	IWN_UNLOCK(sc);
8782 	if (error != 0)
8783 		ieee80211_cancel_scan(vap);
8784 }
8785 
8786 /*
8787  * Callback from net80211 to handle the minimum dwell time being met.
8788  * The intent is to terminate the scan but we just let the firmware
8789  * notify us when it's finished as we have no safe way to abort it.
8790  */
8791 static void
8792 iwn_scan_mindwell(struct ieee80211_scan_state *ss)
8793 {
8794 	/* NB: don't try to abort scan; wait for firmware to finish */
8795 }
8796 
8797 static void
8798 iwn_hw_reset(void *arg0, int pending)
8799 {
8800 	struct iwn_softc *sc = arg0;
8801 	struct ifnet *ifp = sc->sc_ifp;
8802 	struct ieee80211com *ic = ifp->if_l2com;
8803 
8804 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
8805 
8806 	iwn_stop(sc);
8807 	iwn_init(sc);
8808 	ieee80211_notify_radio(ic, 1);
8809 }
8810 #ifdef	IWN_DEBUG
8811 #define	IWN_DESC(x) case x:	return #x
8812 #define	COUNTOF(array) (sizeof(array) / sizeof(array[0]))
8813 
8814 /*
8815  * Translate CSR code to string
8816  */
8817 static char *iwn_get_csr_string(int csr)
8818 {
8819 	switch (csr) {
8820 		IWN_DESC(IWN_HW_IF_CONFIG);
8821 		IWN_DESC(IWN_INT_COALESCING);
8822 		IWN_DESC(IWN_INT);
8823 		IWN_DESC(IWN_INT_MASK);
8824 		IWN_DESC(IWN_FH_INT);
8825 		IWN_DESC(IWN_GPIO_IN);
8826 		IWN_DESC(IWN_RESET);
8827 		IWN_DESC(IWN_GP_CNTRL);
8828 		IWN_DESC(IWN_HW_REV);
8829 		IWN_DESC(IWN_EEPROM);
8830 		IWN_DESC(IWN_EEPROM_GP);
8831 		IWN_DESC(IWN_OTP_GP);
8832 		IWN_DESC(IWN_GIO);
8833 		IWN_DESC(IWN_GP_UCODE);
8834 		IWN_DESC(IWN_GP_DRIVER);
8835 		IWN_DESC(IWN_UCODE_GP1);
8836 		IWN_DESC(IWN_UCODE_GP2);
8837 		IWN_DESC(IWN_LED);
8838 		IWN_DESC(IWN_DRAM_INT_TBL);
8839 		IWN_DESC(IWN_GIO_CHICKEN);
8840 		IWN_DESC(IWN_ANA_PLL);
8841 		IWN_DESC(IWN_HW_REV_WA);
8842 		IWN_DESC(IWN_DBG_HPET_MEM);
8843 	default:
8844 		return "UNKNOWN CSR";
8845 	}
8846 }
8847 
8848 /*
8849  * This function print firmware register
8850  */
8851 static void
8852 iwn_debug_register(struct iwn_softc *sc)
8853 {
8854 	int i;
8855 	static const uint32_t csr_tbl[] = {
8856 		IWN_HW_IF_CONFIG,
8857 		IWN_INT_COALESCING,
8858 		IWN_INT,
8859 		IWN_INT_MASK,
8860 		IWN_FH_INT,
8861 		IWN_GPIO_IN,
8862 		IWN_RESET,
8863 		IWN_GP_CNTRL,
8864 		IWN_HW_REV,
8865 		IWN_EEPROM,
8866 		IWN_EEPROM_GP,
8867 		IWN_OTP_GP,
8868 		IWN_GIO,
8869 		IWN_GP_UCODE,
8870 		IWN_GP_DRIVER,
8871 		IWN_UCODE_GP1,
8872 		IWN_UCODE_GP2,
8873 		IWN_LED,
8874 		IWN_DRAM_INT_TBL,
8875 		IWN_GIO_CHICKEN,
8876 		IWN_ANA_PLL,
8877 		IWN_HW_REV_WA,
8878 		IWN_DBG_HPET_MEM,
8879 	};
8880 	DPRINTF(sc, IWN_DEBUG_REGISTER,
8881 	    "CSR values: (2nd byte of IWN_INT_COALESCING is IWN_INT_PERIODIC)%s",
8882 	    "\n");
8883 	for (i = 0; i <  COUNTOF(csr_tbl); i++){
8884 		DPRINTF(sc, IWN_DEBUG_REGISTER,"  %10s: 0x%08x ",
8885 			iwn_get_csr_string(csr_tbl[i]), IWN_READ(sc, csr_tbl[i]));
8886 		if ((i+1) % 3 == 0)
8887 			DPRINTF(sc, IWN_DEBUG_REGISTER,"%s","\n");
8888 	}
8889 	DPRINTF(sc, IWN_DEBUG_REGISTER,"%s","\n");
8890 }
8891 #endif
8892