xref: /freebsd/sys/dev/iwn/if_iwn.c (revision 7afb8adff33d47f10a11368ff54bb2eec5b30165)
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 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 		if (data->ni != NULL) {
2040 			ieee80211_free_node(data->ni);
2041 			data->ni = NULL;
2042 		}
2043 	}
2044 	/* Clear TX descriptors. */
2045 	memset(ring->desc, 0, ring->desc_dma.size);
2046 	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
2047 	    BUS_DMASYNC_PREWRITE);
2048 	sc->qfullmsk &= ~(1 << ring->qid);
2049 	ring->queued = 0;
2050 	ring->cur = 0;
2051 }
2052 
2053 static void
2054 iwn_free_tx_ring(struct iwn_softc *sc, struct iwn_tx_ring *ring)
2055 {
2056 	int i;
2057 
2058 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s \n", __func__);
2059 
2060 	iwn_dma_contig_free(&ring->desc_dma);
2061 	iwn_dma_contig_free(&ring->cmd_dma);
2062 
2063 	for (i = 0; i < IWN_TX_RING_COUNT; i++) {
2064 		struct iwn_tx_data *data = &ring->data[i];
2065 
2066 		if (data->m != NULL) {
2067 			bus_dmamap_sync(ring->data_dmat, data->map,
2068 			    BUS_DMASYNC_POSTWRITE);
2069 			bus_dmamap_unload(ring->data_dmat, data->map);
2070 			m_freem(data->m);
2071 		}
2072 		if (data->map != NULL)
2073 			bus_dmamap_destroy(ring->data_dmat, data->map);
2074 	}
2075 	if (ring->data_dmat != NULL) {
2076 		bus_dma_tag_destroy(ring->data_dmat);
2077 		ring->data_dmat = NULL;
2078 	}
2079 }
2080 
2081 static void
2082 iwn5000_ict_reset(struct iwn_softc *sc)
2083 {
2084 	/* Disable interrupts. */
2085 	IWN_WRITE(sc, IWN_INT_MASK, 0);
2086 
2087 	/* Reset ICT table. */
2088 	memset(sc->ict, 0, IWN_ICT_SIZE);
2089 	sc->ict_cur = 0;
2090 
2091 	/* Set physical address of ICT table (4KB aligned). */
2092 	DPRINTF(sc, IWN_DEBUG_RESET, "%s: enabling ICT\n", __func__);
2093 	IWN_WRITE(sc, IWN_DRAM_INT_TBL, IWN_DRAM_INT_TBL_ENABLE |
2094 	    IWN_DRAM_INT_TBL_WRAP_CHECK | sc->ict_dma.paddr >> 12);
2095 
2096 	/* Enable periodic RX interrupt. */
2097 	sc->int_mask |= IWN_INT_RX_PERIODIC;
2098 	/* Switch to ICT interrupt mode in driver. */
2099 	sc->sc_flags |= IWN_FLAG_USE_ICT;
2100 
2101 	/* Re-enable interrupts. */
2102 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
2103 	IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
2104 }
2105 
2106 static int
2107 iwn_read_eeprom(struct iwn_softc *sc, uint8_t macaddr[IEEE80211_ADDR_LEN])
2108 {
2109 	struct iwn_ops *ops = &sc->ops;
2110 	uint16_t val;
2111 	int error;
2112 
2113 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
2114 
2115 	/* Check whether adapter has an EEPROM or an OTPROM. */
2116 	if (sc->hw_type >= IWN_HW_REV_TYPE_1000 &&
2117 	    (IWN_READ(sc, IWN_OTP_GP) & IWN_OTP_GP_DEV_SEL_OTP))
2118 		sc->sc_flags |= IWN_FLAG_HAS_OTPROM;
2119 	DPRINTF(sc, IWN_DEBUG_RESET, "%s found\n",
2120 	    (sc->sc_flags & IWN_FLAG_HAS_OTPROM) ? "OTPROM" : "EEPROM");
2121 
2122 	/* Adapter has to be powered on for EEPROM access to work. */
2123 	if ((error = iwn_apm_init(sc)) != 0) {
2124 		device_printf(sc->sc_dev,
2125 		    "%s: could not power ON adapter, error %d\n", __func__,
2126 		    error);
2127 		return error;
2128 	}
2129 
2130 	if ((IWN_READ(sc, IWN_EEPROM_GP) & 0x7) == 0) {
2131 		device_printf(sc->sc_dev, "%s: bad ROM signature\n", __func__);
2132 		return EIO;
2133 	}
2134 	if ((error = iwn_eeprom_lock(sc)) != 0) {
2135 		device_printf(sc->sc_dev, "%s: could not lock ROM, error %d\n",
2136 		    __func__, error);
2137 		return error;
2138 	}
2139 	if (sc->sc_flags & IWN_FLAG_HAS_OTPROM) {
2140 		if ((error = iwn_init_otprom(sc)) != 0) {
2141 			device_printf(sc->sc_dev,
2142 			    "%s: could not initialize OTPROM, error %d\n",
2143 			    __func__, error);
2144 			return error;
2145 		}
2146 	}
2147 
2148 	iwn_read_prom_data(sc, IWN_EEPROM_SKU_CAP, &val, 2);
2149 	DPRINTF(sc, IWN_DEBUG_RESET, "SKU capabilities=0x%04x\n", le16toh(val));
2150 	/* Check if HT support is bonded out. */
2151 	if (val & htole16(IWN_EEPROM_SKU_CAP_11N))
2152 		sc->sc_flags |= IWN_FLAG_HAS_11N;
2153 
2154 	iwn_read_prom_data(sc, IWN_EEPROM_RFCFG, &val, 2);
2155 	sc->rfcfg = le16toh(val);
2156 	DPRINTF(sc, IWN_DEBUG_RESET, "radio config=0x%04x\n", sc->rfcfg);
2157 	/* Read Tx/Rx chains from ROM unless it's known to be broken. */
2158 	if (sc->txchainmask == 0)
2159 		sc->txchainmask = IWN_RFCFG_TXANTMSK(sc->rfcfg);
2160 	if (sc->rxchainmask == 0)
2161 		sc->rxchainmask = IWN_RFCFG_RXANTMSK(sc->rfcfg);
2162 
2163 	/* Read MAC address. */
2164 	iwn_read_prom_data(sc, IWN_EEPROM_MAC, macaddr, 6);
2165 
2166 	/* Read adapter-specific information from EEPROM. */
2167 	ops->read_eeprom(sc);
2168 
2169 	iwn_apm_stop(sc);	/* Power OFF adapter. */
2170 
2171 	iwn_eeprom_unlock(sc);
2172 
2173 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
2174 
2175 	return 0;
2176 }
2177 
2178 static void
2179 iwn4965_read_eeprom(struct iwn_softc *sc)
2180 {
2181 	uint32_t addr;
2182 	uint16_t val;
2183 	int i;
2184 
2185 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
2186 
2187 	/* Read regulatory domain (4 ASCII characters). */
2188 	iwn_read_prom_data(sc, IWN4965_EEPROM_DOMAIN, sc->eeprom_domain, 4);
2189 
2190 	/* Read the list of authorized channels (20MHz ones only). */
2191 	for (i = 0; i < IWN_NBANDS - 1; i++) {
2192 		addr = iwn4965_regulatory_bands[i];
2193 		iwn_read_eeprom_channels(sc, i, addr);
2194 	}
2195 
2196 	/* Read maximum allowed TX power for 2GHz and 5GHz bands. */
2197 	iwn_read_prom_data(sc, IWN4965_EEPROM_MAXPOW, &val, 2);
2198 	sc->maxpwr2GHz = val & 0xff;
2199 	sc->maxpwr5GHz = val >> 8;
2200 	/* Check that EEPROM values are within valid range. */
2201 	if (sc->maxpwr5GHz < 20 || sc->maxpwr5GHz > 50)
2202 		sc->maxpwr5GHz = 38;
2203 	if (sc->maxpwr2GHz < 20 || sc->maxpwr2GHz > 50)
2204 		sc->maxpwr2GHz = 38;
2205 	DPRINTF(sc, IWN_DEBUG_RESET, "maxpwr 2GHz=%d 5GHz=%d\n",
2206 	    sc->maxpwr2GHz, sc->maxpwr5GHz);
2207 
2208 	/* Read samples for each TX power group. */
2209 	iwn_read_prom_data(sc, IWN4965_EEPROM_BANDS, sc->bands,
2210 	    sizeof sc->bands);
2211 
2212 	/* Read voltage at which samples were taken. */
2213 	iwn_read_prom_data(sc, IWN4965_EEPROM_VOLTAGE, &val, 2);
2214 	sc->eeprom_voltage = (int16_t)le16toh(val);
2215 	DPRINTF(sc, IWN_DEBUG_RESET, "voltage=%d (in 0.3V)\n",
2216 	    sc->eeprom_voltage);
2217 
2218 #ifdef IWN_DEBUG
2219 	/* Print samples. */
2220 	if (sc->sc_debug & IWN_DEBUG_ANY) {
2221 		for (i = 0; i < IWN_NBANDS - 1; i++)
2222 			iwn4965_print_power_group(sc, i);
2223 	}
2224 #endif
2225 
2226 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
2227 }
2228 
2229 #ifdef IWN_DEBUG
2230 static void
2231 iwn4965_print_power_group(struct iwn_softc *sc, int i)
2232 {
2233 	struct iwn4965_eeprom_band *band = &sc->bands[i];
2234 	struct iwn4965_eeprom_chan_samples *chans = band->chans;
2235 	int j, c;
2236 
2237 	printf("===band %d===\n", i);
2238 	printf("chan lo=%d, chan hi=%d\n", band->lo, band->hi);
2239 	printf("chan1 num=%d\n", chans[0].num);
2240 	for (c = 0; c < 2; c++) {
2241 		for (j = 0; j < IWN_NSAMPLES; j++) {
2242 			printf("chain %d, sample %d: temp=%d gain=%d "
2243 			    "power=%d pa_det=%d\n", c, j,
2244 			    chans[0].samples[c][j].temp,
2245 			    chans[0].samples[c][j].gain,
2246 			    chans[0].samples[c][j].power,
2247 			    chans[0].samples[c][j].pa_det);
2248 		}
2249 	}
2250 	printf("chan2 num=%d\n", chans[1].num);
2251 	for (c = 0; c < 2; c++) {
2252 		for (j = 0; j < IWN_NSAMPLES; j++) {
2253 			printf("chain %d, sample %d: temp=%d gain=%d "
2254 			    "power=%d pa_det=%d\n", c, j,
2255 			    chans[1].samples[c][j].temp,
2256 			    chans[1].samples[c][j].gain,
2257 			    chans[1].samples[c][j].power,
2258 			    chans[1].samples[c][j].pa_det);
2259 		}
2260 	}
2261 }
2262 #endif
2263 
2264 static void
2265 iwn5000_read_eeprom(struct iwn_softc *sc)
2266 {
2267 	struct iwn5000_eeprom_calib_hdr hdr;
2268 	int32_t volt;
2269 	uint32_t base, addr;
2270 	uint16_t val;
2271 	int i;
2272 
2273 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
2274 
2275 	/* Read regulatory domain (4 ASCII characters). */
2276 	iwn_read_prom_data(sc, IWN5000_EEPROM_REG, &val, 2);
2277 	base = le16toh(val);
2278 	iwn_read_prom_data(sc, base + IWN5000_EEPROM_DOMAIN,
2279 	    sc->eeprom_domain, 4);
2280 
2281 	/* Read the list of authorized channels (20MHz ones only). */
2282 	for (i = 0; i < IWN_NBANDS - 1; i++) {
2283 		addr =  base + sc->base_params->regulatory_bands[i];
2284 		iwn_read_eeprom_channels(sc, i, addr);
2285 	}
2286 
2287 	/* Read enhanced TX power information for 6000 Series. */
2288 	if (sc->base_params->enhanced_TX_power)
2289 		iwn_read_eeprom_enhinfo(sc);
2290 
2291 	iwn_read_prom_data(sc, IWN5000_EEPROM_CAL, &val, 2);
2292 	base = le16toh(val);
2293 	iwn_read_prom_data(sc, base, &hdr, sizeof hdr);
2294 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
2295 	    "%s: calib version=%u pa type=%u voltage=%u\n", __func__,
2296 	    hdr.version, hdr.pa_type, le16toh(hdr.volt));
2297 	sc->calib_ver = hdr.version;
2298 
2299 	if (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_TEMP_OFFSETv2) {
2300 		sc->eeprom_voltage = le16toh(hdr.volt);
2301 		iwn_read_prom_data(sc, base + IWN5000_EEPROM_TEMP, &val, 2);
2302 		sc->eeprom_temp_high=le16toh(val);
2303 		iwn_read_prom_data(sc, base + IWN5000_EEPROM_VOLT, &val, 2);
2304 		sc->eeprom_temp = le16toh(val);
2305 	}
2306 
2307 	if (sc->hw_type == IWN_HW_REV_TYPE_5150) {
2308 		/* Compute temperature offset. */
2309 		iwn_read_prom_data(sc, base + IWN5000_EEPROM_TEMP, &val, 2);
2310 		sc->eeprom_temp = le16toh(val);
2311 		iwn_read_prom_data(sc, base + IWN5000_EEPROM_VOLT, &val, 2);
2312 		volt = le16toh(val);
2313 		sc->temp_off = sc->eeprom_temp - (volt / -5);
2314 		DPRINTF(sc, IWN_DEBUG_CALIBRATE, "temp=%d volt=%d offset=%dK\n",
2315 		    sc->eeprom_temp, volt, sc->temp_off);
2316 	} else {
2317 		/* Read crystal calibration. */
2318 		iwn_read_prom_data(sc, base + IWN5000_EEPROM_CRYSTAL,
2319 		    &sc->eeprom_crystal, sizeof (uint32_t));
2320 		DPRINTF(sc, IWN_DEBUG_CALIBRATE, "crystal calibration 0x%08x\n",
2321 		    le32toh(sc->eeprom_crystal));
2322 	}
2323 
2324 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
2325 
2326 }
2327 
2328 /*
2329  * Translate EEPROM flags to net80211.
2330  */
2331 static uint32_t
2332 iwn_eeprom_channel_flags(struct iwn_eeprom_chan *channel)
2333 {
2334 	uint32_t nflags;
2335 
2336 	nflags = 0;
2337 	if ((channel->flags & IWN_EEPROM_CHAN_ACTIVE) == 0)
2338 		nflags |= IEEE80211_CHAN_PASSIVE;
2339 	if ((channel->flags & IWN_EEPROM_CHAN_IBSS) == 0)
2340 		nflags |= IEEE80211_CHAN_NOADHOC;
2341 	if (channel->flags & IWN_EEPROM_CHAN_RADAR) {
2342 		nflags |= IEEE80211_CHAN_DFS;
2343 		/* XXX apparently IBSS may still be marked */
2344 		nflags |= IEEE80211_CHAN_NOADHOC;
2345 	}
2346 
2347 	return nflags;
2348 }
2349 
2350 static void
2351 iwn_read_eeprom_band(struct iwn_softc *sc, int n)
2352 {
2353 	struct ifnet *ifp = sc->sc_ifp;
2354 	struct ieee80211com *ic = ifp->if_l2com;
2355 	struct iwn_eeprom_chan *channels = sc->eeprom_channels[n];
2356 	const struct iwn_chan_band *band = &iwn_bands[n];
2357 	struct ieee80211_channel *c;
2358 	uint8_t chan;
2359 	int i, nflags;
2360 
2361 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
2362 
2363 	for (i = 0; i < band->nchan; i++) {
2364 		if (!(channels[i].flags & IWN_EEPROM_CHAN_VALID)) {
2365 			DPRINTF(sc, IWN_DEBUG_RESET,
2366 			    "skip chan %d flags 0x%x maxpwr %d\n",
2367 			    band->chan[i], channels[i].flags,
2368 			    channels[i].maxpwr);
2369 			continue;
2370 		}
2371 		chan = band->chan[i];
2372 		nflags = iwn_eeprom_channel_flags(&channels[i]);
2373 
2374 		c = &ic->ic_channels[ic->ic_nchans++];
2375 		c->ic_ieee = chan;
2376 		c->ic_maxregpower = channels[i].maxpwr;
2377 		c->ic_maxpower = 2*c->ic_maxregpower;
2378 
2379 		if (n == 0) {	/* 2GHz band */
2380 			c->ic_freq = ieee80211_ieee2mhz(chan, IEEE80211_CHAN_G);
2381 			/* G =>'s B is supported */
2382 			c->ic_flags = IEEE80211_CHAN_B | nflags;
2383 			c = &ic->ic_channels[ic->ic_nchans++];
2384 			c[0] = c[-1];
2385 			c->ic_flags = IEEE80211_CHAN_G | nflags;
2386 		} else {	/* 5GHz band */
2387 			c->ic_freq = ieee80211_ieee2mhz(chan, IEEE80211_CHAN_A);
2388 			c->ic_flags = IEEE80211_CHAN_A | nflags;
2389 		}
2390 
2391 		/* Save maximum allowed TX power for this channel. */
2392 		sc->maxpwr[chan] = channels[i].maxpwr;
2393 
2394 		DPRINTF(sc, IWN_DEBUG_RESET,
2395 		    "add chan %d flags 0x%x maxpwr %d\n", chan,
2396 		    channels[i].flags, channels[i].maxpwr);
2397 
2398 		if (sc->sc_flags & IWN_FLAG_HAS_11N) {
2399 			/* add HT20, HT40 added separately */
2400 			c = &ic->ic_channels[ic->ic_nchans++];
2401 			c[0] = c[-1];
2402 			c->ic_flags |= IEEE80211_CHAN_HT20;
2403 		}
2404 	}
2405 
2406 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
2407 
2408 }
2409 
2410 static void
2411 iwn_read_eeprom_ht40(struct iwn_softc *sc, int n)
2412 {
2413 	struct ifnet *ifp = sc->sc_ifp;
2414 	struct ieee80211com *ic = ifp->if_l2com;
2415 	struct iwn_eeprom_chan *channels = sc->eeprom_channels[n];
2416 	const struct iwn_chan_band *band = &iwn_bands[n];
2417 	struct ieee80211_channel *c, *cent, *extc;
2418 	uint8_t chan;
2419 	int i, nflags;
2420 
2421 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s start\n", __func__);
2422 
2423 	if (!(sc->sc_flags & IWN_FLAG_HAS_11N)) {
2424 		DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end no 11n\n", __func__);
2425 		return;
2426 	}
2427 
2428 	for (i = 0; i < band->nchan; i++) {
2429 		if (!(channels[i].flags & IWN_EEPROM_CHAN_VALID)) {
2430 			DPRINTF(sc, IWN_DEBUG_RESET,
2431 			    "skip chan %d flags 0x%x maxpwr %d\n",
2432 			    band->chan[i], channels[i].flags,
2433 			    channels[i].maxpwr);
2434 			continue;
2435 		}
2436 		chan = band->chan[i];
2437 		nflags = iwn_eeprom_channel_flags(&channels[i]);
2438 
2439 		/*
2440 		 * Each entry defines an HT40 channel pair; find the
2441 		 * center channel, then the extension channel above.
2442 		 */
2443 		cent = ieee80211_find_channel_byieee(ic, chan,
2444 		    (n == 5 ? IEEE80211_CHAN_G : IEEE80211_CHAN_A));
2445 		if (cent == NULL) {	/* XXX shouldn't happen */
2446 			device_printf(sc->sc_dev,
2447 			    "%s: no entry for channel %d\n", __func__, chan);
2448 			continue;
2449 		}
2450 		extc = ieee80211_find_channel(ic, cent->ic_freq+20,
2451 		    (n == 5 ? IEEE80211_CHAN_G : IEEE80211_CHAN_A));
2452 		if (extc == NULL) {
2453 			DPRINTF(sc, IWN_DEBUG_RESET,
2454 			    "%s: skip chan %d, extension channel not found\n",
2455 			    __func__, chan);
2456 			continue;
2457 		}
2458 
2459 		DPRINTF(sc, IWN_DEBUG_RESET,
2460 		    "add ht40 chan %d flags 0x%x maxpwr %d\n",
2461 		    chan, channels[i].flags, channels[i].maxpwr);
2462 
2463 		c = &ic->ic_channels[ic->ic_nchans++];
2464 		c[0] = cent[0];
2465 		c->ic_extieee = extc->ic_ieee;
2466 		c->ic_flags &= ~IEEE80211_CHAN_HT;
2467 		c->ic_flags |= IEEE80211_CHAN_HT40U | nflags;
2468 		c = &ic->ic_channels[ic->ic_nchans++];
2469 		c[0] = extc[0];
2470 		c->ic_extieee = cent->ic_ieee;
2471 		c->ic_flags &= ~IEEE80211_CHAN_HT;
2472 		c->ic_flags |= IEEE80211_CHAN_HT40D | nflags;
2473 	}
2474 
2475 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
2476 
2477 }
2478 
2479 static void
2480 iwn_read_eeprom_channels(struct iwn_softc *sc, int n, uint32_t addr)
2481 {
2482 	struct ifnet *ifp = sc->sc_ifp;
2483 	struct ieee80211com *ic = ifp->if_l2com;
2484 
2485 	iwn_read_prom_data(sc, addr, &sc->eeprom_channels[n],
2486 	    iwn_bands[n].nchan * sizeof (struct iwn_eeprom_chan));
2487 
2488 	if (n < 5)
2489 		iwn_read_eeprom_band(sc, n);
2490 	else
2491 		iwn_read_eeprom_ht40(sc, n);
2492 	ieee80211_sort_channels(ic->ic_channels, ic->ic_nchans);
2493 }
2494 
2495 static struct iwn_eeprom_chan *
2496 iwn_find_eeprom_channel(struct iwn_softc *sc, struct ieee80211_channel *c)
2497 {
2498 	int band, chan, i, j;
2499 
2500 	if (IEEE80211_IS_CHAN_HT40(c)) {
2501 		band = IEEE80211_IS_CHAN_5GHZ(c) ? 6 : 5;
2502 		if (IEEE80211_IS_CHAN_HT40D(c))
2503 			chan = c->ic_extieee;
2504 		else
2505 			chan = c->ic_ieee;
2506 		for (i = 0; i < iwn_bands[band].nchan; i++) {
2507 			if (iwn_bands[band].chan[i] == chan)
2508 				return &sc->eeprom_channels[band][i];
2509 		}
2510 	} else {
2511 		for (j = 0; j < 5; j++) {
2512 			for (i = 0; i < iwn_bands[j].nchan; i++) {
2513 				if (iwn_bands[j].chan[i] == c->ic_ieee)
2514 					return &sc->eeprom_channels[j][i];
2515 			}
2516 		}
2517 	}
2518 	return NULL;
2519 }
2520 
2521 /*
2522  * Enforce flags read from EEPROM.
2523  */
2524 static int
2525 iwn_setregdomain(struct ieee80211com *ic, struct ieee80211_regdomain *rd,
2526     int nchan, struct ieee80211_channel chans[])
2527 {
2528 	struct iwn_softc *sc = ic->ic_ifp->if_softc;
2529 	int i;
2530 
2531 	for (i = 0; i < nchan; i++) {
2532 		struct ieee80211_channel *c = &chans[i];
2533 		struct iwn_eeprom_chan *channel;
2534 
2535 		channel = iwn_find_eeprom_channel(sc, c);
2536 		if (channel == NULL) {
2537 			if_printf(ic->ic_ifp,
2538 			    "%s: invalid channel %u freq %u/0x%x\n",
2539 			    __func__, c->ic_ieee, c->ic_freq, c->ic_flags);
2540 			return EINVAL;
2541 		}
2542 		c->ic_flags |= iwn_eeprom_channel_flags(channel);
2543 	}
2544 
2545 	return 0;
2546 }
2547 
2548 static void
2549 iwn_read_eeprom_enhinfo(struct iwn_softc *sc)
2550 {
2551 	struct iwn_eeprom_enhinfo enhinfo[35];
2552 	struct ifnet *ifp = sc->sc_ifp;
2553 	struct ieee80211com *ic = ifp->if_l2com;
2554 	struct ieee80211_channel *c;
2555 	uint16_t val, base;
2556 	int8_t maxpwr;
2557 	uint8_t flags;
2558 	int i, j;
2559 
2560 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
2561 
2562 	iwn_read_prom_data(sc, IWN5000_EEPROM_REG, &val, 2);
2563 	base = le16toh(val);
2564 	iwn_read_prom_data(sc, base + IWN6000_EEPROM_ENHINFO,
2565 	    enhinfo, sizeof enhinfo);
2566 
2567 	for (i = 0; i < nitems(enhinfo); i++) {
2568 		flags = enhinfo[i].flags;
2569 		if (!(flags & IWN_ENHINFO_VALID))
2570 			continue;	/* Skip invalid entries. */
2571 
2572 		maxpwr = 0;
2573 		if (sc->txchainmask & IWN_ANT_A)
2574 			maxpwr = MAX(maxpwr, enhinfo[i].chain[0]);
2575 		if (sc->txchainmask & IWN_ANT_B)
2576 			maxpwr = MAX(maxpwr, enhinfo[i].chain[1]);
2577 		if (sc->txchainmask & IWN_ANT_C)
2578 			maxpwr = MAX(maxpwr, enhinfo[i].chain[2]);
2579 		if (sc->ntxchains == 2)
2580 			maxpwr = MAX(maxpwr, enhinfo[i].mimo2);
2581 		else if (sc->ntxchains == 3)
2582 			maxpwr = MAX(maxpwr, enhinfo[i].mimo3);
2583 
2584 		for (j = 0; j < ic->ic_nchans; j++) {
2585 			c = &ic->ic_channels[j];
2586 			if ((flags & IWN_ENHINFO_5GHZ)) {
2587 				if (!IEEE80211_IS_CHAN_A(c))
2588 					continue;
2589 			} else if ((flags & IWN_ENHINFO_OFDM)) {
2590 				if (!IEEE80211_IS_CHAN_G(c))
2591 					continue;
2592 			} else if (!IEEE80211_IS_CHAN_B(c))
2593 				continue;
2594 			if ((flags & IWN_ENHINFO_HT40)) {
2595 				if (!IEEE80211_IS_CHAN_HT40(c))
2596 					continue;
2597 			} else {
2598 				if (IEEE80211_IS_CHAN_HT40(c))
2599 					continue;
2600 			}
2601 			if (enhinfo[i].chan != 0 &&
2602 			    enhinfo[i].chan != c->ic_ieee)
2603 				continue;
2604 
2605 			DPRINTF(sc, IWN_DEBUG_RESET,
2606 			    "channel %d(%x), maxpwr %d\n", c->ic_ieee,
2607 			    c->ic_flags, maxpwr / 2);
2608 			c->ic_maxregpower = maxpwr / 2;
2609 			c->ic_maxpower = maxpwr;
2610 		}
2611 	}
2612 
2613 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end\n", __func__);
2614 
2615 }
2616 
2617 static struct ieee80211_node *
2618 iwn_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
2619 {
2620 	return malloc(sizeof (struct iwn_node), M_80211_NODE,M_NOWAIT | M_ZERO);
2621 }
2622 
2623 static __inline int
2624 rate2plcp(int rate)
2625 {
2626 	switch (rate & 0xff) {
2627 	case 12:	return 0xd;
2628 	case 18:	return 0xf;
2629 	case 24:	return 0x5;
2630 	case 36:	return 0x7;
2631 	case 48:	return 0x9;
2632 	case 72:	return 0xb;
2633 	case 96:	return 0x1;
2634 	case 108:	return 0x3;
2635 	case 2:		return 10;
2636 	case 4:		return 20;
2637 	case 11:	return 55;
2638 	case 22:	return 110;
2639 	}
2640 	return 0;
2641 }
2642 
2643 static int
2644 iwn_get_1stream_tx_antmask(struct iwn_softc *sc)
2645 {
2646 
2647 	return IWN_LSB(sc->txchainmask);
2648 }
2649 
2650 static int
2651 iwn_get_2stream_tx_antmask(struct iwn_softc *sc)
2652 {
2653 	int tx;
2654 
2655 	/*
2656 	 * The '2 stream' setup is a bit .. odd.
2657 	 *
2658 	 * For NICs that support only 1 antenna, default to IWN_ANT_AB or
2659 	 * the firmware panics (eg Intel 5100.)
2660 	 *
2661 	 * For NICs that support two antennas, we use ANT_AB.
2662 	 *
2663 	 * For NICs that support three antennas, we use the two that
2664 	 * wasn't the default one.
2665 	 *
2666 	 * XXX TODO: if bluetooth (full concurrent) is enabled, restrict
2667 	 * this to only one antenna.
2668 	 */
2669 
2670 	/* Default - transmit on the other antennas */
2671 	tx = (sc->txchainmask & ~IWN_LSB(sc->txchainmask));
2672 
2673 	/* Now, if it's zero, set it to IWN_ANT_AB, so to not panic firmware */
2674 	if (tx == 0)
2675 		tx = IWN_ANT_AB;
2676 
2677 	/*
2678 	 * If the NIC is a two-stream TX NIC, configure the TX mask to
2679 	 * the default chainmask
2680 	 */
2681 	else if (sc->ntxchains == 2)
2682 		tx = sc->txchainmask;
2683 
2684 	return (tx);
2685 }
2686 
2687 
2688 
2689 /*
2690  * Calculate the required PLCP value from the given rate,
2691  * to the given node.
2692  *
2693  * This will take the node configuration (eg 11n, rate table
2694  * setup, etc) into consideration.
2695  */
2696 static uint32_t
2697 iwn_rate_to_plcp(struct iwn_softc *sc, struct ieee80211_node *ni,
2698     uint8_t rate)
2699 {
2700 #define	RV(v)	((v) & IEEE80211_RATE_VAL)
2701 	struct ieee80211com *ic = ni->ni_ic;
2702 	uint32_t plcp = 0;
2703 	int ridx;
2704 
2705 	/*
2706 	 * If it's an MCS rate, let's set the plcp correctly
2707 	 * and set the relevant flags based on the node config.
2708 	 */
2709 	if (rate & IEEE80211_RATE_MCS) {
2710 		/*
2711 		 * Set the initial PLCP value to be between 0->31 for
2712 		 * MCS 0 -> MCS 31, then set the "I'm an MCS rate!"
2713 		 * flag.
2714 		 */
2715 		plcp = RV(rate) | IWN_RFLAG_MCS;
2716 
2717 		/*
2718 		 * XXX the following should only occur if both
2719 		 * the local configuration _and_ the remote node
2720 		 * advertise these capabilities.  Thus this code
2721 		 * may need fixing!
2722 		 */
2723 
2724 		/*
2725 		 * Set the channel width and guard interval.
2726 		 */
2727 		if (IEEE80211_IS_CHAN_HT40(ni->ni_chan)) {
2728 			plcp |= IWN_RFLAG_HT40;
2729 			if (ni->ni_htcap & IEEE80211_HTCAP_SHORTGI40)
2730 				plcp |= IWN_RFLAG_SGI;
2731 		} else if (ni->ni_htcap & IEEE80211_HTCAP_SHORTGI20) {
2732 			plcp |= IWN_RFLAG_SGI;
2733 		}
2734 
2735 		/*
2736 		 * Ensure the selected rate matches the link quality
2737 		 * table entries being used.
2738 		 */
2739 		if (rate > 0x8f)
2740 			plcp |= IWN_RFLAG_ANT(sc->txchainmask);
2741 		else if (rate > 0x87)
2742 			plcp |= IWN_RFLAG_ANT(iwn_get_2stream_tx_antmask(sc));
2743 		else
2744 			plcp |= IWN_RFLAG_ANT(iwn_get_1stream_tx_antmask(sc));
2745 	} else {
2746 		/*
2747 		 * Set the initial PLCP - fine for both
2748 		 * OFDM and CCK rates.
2749 		 */
2750 		plcp = rate2plcp(rate);
2751 
2752 		/* Set CCK flag if it's CCK */
2753 
2754 		/* XXX It would be nice to have a method
2755 		 * to map the ridx -> phy table entry
2756 		 * so we could just query that, rather than
2757 		 * this hack to check against IWN_RIDX_OFDM6.
2758 		 */
2759 		ridx = ieee80211_legacy_rate_lookup(ic->ic_rt,
2760 		    rate & IEEE80211_RATE_VAL);
2761 		if (ridx < IWN_RIDX_OFDM6 &&
2762 		    IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
2763 			plcp |= IWN_RFLAG_CCK;
2764 
2765 		/* Set antenna configuration */
2766 		/* XXX TODO: is this the right antenna to use for legacy? */
2767 		plcp |= IWN_RFLAG_ANT(iwn_get_1stream_tx_antmask(sc));
2768 	}
2769 
2770 	DPRINTF(sc, IWN_DEBUG_TXRATE, "%s: rate=0x%02x, plcp=0x%08x\n",
2771 	    __func__,
2772 	    rate,
2773 	    plcp);
2774 
2775 	return (htole32(plcp));
2776 #undef	RV
2777 }
2778 
2779 static void
2780 iwn_newassoc(struct ieee80211_node *ni, int isnew)
2781 {
2782 	/* Doesn't do anything at the moment */
2783 }
2784 
2785 static int
2786 iwn_media_change(struct ifnet *ifp)
2787 {
2788 	int error;
2789 
2790 	error = ieee80211_media_change(ifp);
2791 	/* NB: only the fixed rate can change and that doesn't need a reset */
2792 	return (error == ENETRESET ? 0 : error);
2793 }
2794 
2795 static int
2796 iwn_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
2797 {
2798 	struct iwn_vap *ivp = IWN_VAP(vap);
2799 	struct ieee80211com *ic = vap->iv_ic;
2800 	struct iwn_softc *sc = ic->ic_ifp->if_softc;
2801 	int error = 0;
2802 
2803 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
2804 
2805 	DPRINTF(sc, IWN_DEBUG_STATE, "%s: %s -> %s\n", __func__,
2806 	    ieee80211_state_name[vap->iv_state], ieee80211_state_name[nstate]);
2807 
2808 	IEEE80211_UNLOCK(ic);
2809 	IWN_LOCK(sc);
2810 	callout_stop(&sc->calib_to);
2811 
2812 	sc->rxon = &sc->rx_on[IWN_RXON_BSS_CTX];
2813 
2814 	switch (nstate) {
2815 	case IEEE80211_S_ASSOC:
2816 		if (vap->iv_state != IEEE80211_S_RUN)
2817 			break;
2818 		/* FALLTHROUGH */
2819 	case IEEE80211_S_AUTH:
2820 		if (vap->iv_state == IEEE80211_S_AUTH)
2821 			break;
2822 
2823 		/*
2824 		 * !AUTH -> AUTH transition requires state reset to handle
2825 		 * reassociations correctly.
2826 		 */
2827 		sc->rxon->associd = 0;
2828 		sc->rxon->filter &= ~htole32(IWN_FILTER_BSS);
2829 		sc->calib.state = IWN_CALIB_STATE_INIT;
2830 
2831 		if ((error = iwn_auth(sc, vap)) != 0) {
2832 			device_printf(sc->sc_dev,
2833 			    "%s: could not move to auth state\n", __func__);
2834 		}
2835 		break;
2836 
2837 	case IEEE80211_S_RUN:
2838 		/*
2839 		 * RUN -> RUN transition; Just restart the timers.
2840 		 */
2841 		if (vap->iv_state == IEEE80211_S_RUN) {
2842 			sc->calib_cnt = 0;
2843 			break;
2844 		}
2845 
2846 		/*
2847 		 * !RUN -> RUN requires setting the association id
2848 		 * which is done with a firmware cmd.  We also defer
2849 		 * starting the timers until that work is done.
2850 		 */
2851 		if ((error = iwn_run(sc, vap)) != 0) {
2852 			device_printf(sc->sc_dev,
2853 			    "%s: could not move to run state\n", __func__);
2854 		}
2855 		break;
2856 
2857 	case IEEE80211_S_INIT:
2858 		sc->calib.state = IWN_CALIB_STATE_INIT;
2859 		break;
2860 
2861 	default:
2862 		break;
2863 	}
2864 	IWN_UNLOCK(sc);
2865 	IEEE80211_LOCK(ic);
2866 	if (error != 0){
2867 		DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end in error\n", __func__);
2868 		return error;
2869 	}
2870 
2871 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
2872 
2873 	return ivp->iv_newstate(vap, nstate, arg);
2874 }
2875 
2876 static void
2877 iwn_calib_timeout(void *arg)
2878 {
2879 	struct iwn_softc *sc = arg;
2880 
2881 	IWN_LOCK_ASSERT(sc);
2882 
2883 	/* Force automatic TX power calibration every 60 secs. */
2884 	if (++sc->calib_cnt >= 120) {
2885 		uint32_t flags = 0;
2886 
2887 		DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s\n",
2888 		    "sending request for statistics");
2889 		(void)iwn_cmd(sc, IWN_CMD_GET_STATISTICS, &flags,
2890 		    sizeof flags, 1);
2891 		sc->calib_cnt = 0;
2892 	}
2893 	callout_reset(&sc->calib_to, msecs_to_ticks(500), iwn_calib_timeout,
2894 	    sc);
2895 }
2896 
2897 /*
2898  * Process an RX_PHY firmware notification.  This is usually immediately
2899  * followed by an MPDU_RX_DONE notification.
2900  */
2901 static void
2902 iwn_rx_phy(struct iwn_softc *sc, struct iwn_rx_desc *desc,
2903     struct iwn_rx_data *data)
2904 {
2905 	struct iwn_rx_stat *stat = (struct iwn_rx_stat *)(desc + 1);
2906 
2907 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: received PHY stats\n", __func__);
2908 	bus_dmamap_sync(sc->rxq.data_dmat, data->map, BUS_DMASYNC_POSTREAD);
2909 
2910 	/* Save RX statistics, they will be used on MPDU_RX_DONE. */
2911 	memcpy(&sc->last_rx_stat, stat, sizeof (*stat));
2912 	sc->last_rx_valid = 1;
2913 }
2914 
2915 /*
2916  * Process an RX_DONE (4965AGN only) or MPDU_RX_DONE firmware notification.
2917  * Each MPDU_RX_DONE notification must be preceded by an RX_PHY one.
2918  */
2919 static void
2920 iwn_rx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc,
2921     struct iwn_rx_data *data)
2922 {
2923 	struct iwn_ops *ops = &sc->ops;
2924 	struct ifnet *ifp = sc->sc_ifp;
2925 	struct ieee80211com *ic = ifp->if_l2com;
2926 	struct iwn_rx_ring *ring = &sc->rxq;
2927 	struct ieee80211_frame *wh;
2928 	struct ieee80211_node *ni;
2929 	struct mbuf *m, *m1;
2930 	struct iwn_rx_stat *stat;
2931 	caddr_t head;
2932 	bus_addr_t paddr;
2933 	uint32_t flags;
2934 	int error, len, rssi, nf;
2935 
2936 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
2937 
2938 	if (desc->type == IWN_MPDU_RX_DONE) {
2939 		/* Check for prior RX_PHY notification. */
2940 		if (!sc->last_rx_valid) {
2941 			DPRINTF(sc, IWN_DEBUG_ANY,
2942 			    "%s: missing RX_PHY\n", __func__);
2943 			return;
2944 		}
2945 		stat = &sc->last_rx_stat;
2946 	} else
2947 		stat = (struct iwn_rx_stat *)(desc + 1);
2948 
2949 	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTREAD);
2950 
2951 	if (stat->cfg_phy_len > IWN_STAT_MAXLEN) {
2952 		device_printf(sc->sc_dev,
2953 		    "%s: invalid RX statistic header, len %d\n", __func__,
2954 		    stat->cfg_phy_len);
2955 		return;
2956 	}
2957 	if (desc->type == IWN_MPDU_RX_DONE) {
2958 		struct iwn_rx_mpdu *mpdu = (struct iwn_rx_mpdu *)(desc + 1);
2959 		head = (caddr_t)(mpdu + 1);
2960 		len = le16toh(mpdu->len);
2961 	} else {
2962 		head = (caddr_t)(stat + 1) + stat->cfg_phy_len;
2963 		len = le16toh(stat->len);
2964 	}
2965 
2966 	flags = le32toh(*(uint32_t *)(head + len));
2967 
2968 	/* Discard frames with a bad FCS early. */
2969 	if ((flags & IWN_RX_NOERROR) != IWN_RX_NOERROR) {
2970 		DPRINTF(sc, IWN_DEBUG_RECV, "%s: RX flags error %x\n",
2971 		    __func__, flags);
2972 		if_inc_counter(ifp, IFCOUNTER_IERRORS, 1);
2973 		return;
2974 	}
2975 	/* Discard frames that are too short. */
2976 	if (len < sizeof (struct ieee80211_frame_ack)) {
2977 		DPRINTF(sc, IWN_DEBUG_RECV, "%s: frame too short: %d\n",
2978 		    __func__, len);
2979 		if_inc_counter(ifp, IFCOUNTER_IERRORS, 1);
2980 		return;
2981 	}
2982 
2983 	m1 = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, IWN_RBUF_SIZE);
2984 	if (m1 == NULL) {
2985 		DPRINTF(sc, IWN_DEBUG_ANY, "%s: no mbuf to restock ring\n",
2986 		    __func__);
2987 		if_inc_counter(ifp, IFCOUNTER_IERRORS, 1);
2988 		return;
2989 	}
2990 	bus_dmamap_unload(ring->data_dmat, data->map);
2991 
2992 	error = bus_dmamap_load(ring->data_dmat, data->map, mtod(m1, void *),
2993 	    IWN_RBUF_SIZE, iwn_dma_map_addr, &paddr, BUS_DMA_NOWAIT);
2994 	if (error != 0 && error != EFBIG) {
2995 		device_printf(sc->sc_dev,
2996 		    "%s: bus_dmamap_load failed, error %d\n", __func__, error);
2997 		m_freem(m1);
2998 
2999 		/* Try to reload the old mbuf. */
3000 		error = bus_dmamap_load(ring->data_dmat, data->map,
3001 		    mtod(data->m, void *), IWN_RBUF_SIZE, iwn_dma_map_addr,
3002 		    &paddr, BUS_DMA_NOWAIT);
3003 		if (error != 0 && error != EFBIG) {
3004 			panic("%s: could not load old RX mbuf", __func__);
3005 		}
3006 		/* Physical address may have changed. */
3007 		ring->desc[ring->cur] = htole32(paddr >> 8);
3008 		bus_dmamap_sync(ring->data_dmat, ring->desc_dma.map,
3009 		    BUS_DMASYNC_PREWRITE);
3010 		if_inc_counter(ifp, IFCOUNTER_IERRORS, 1);
3011 		return;
3012 	}
3013 
3014 	m = data->m;
3015 	data->m = m1;
3016 	/* Update RX descriptor. */
3017 	ring->desc[ring->cur] = htole32(paddr >> 8);
3018 	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
3019 	    BUS_DMASYNC_PREWRITE);
3020 
3021 	/* Finalize mbuf. */
3022 	m->m_pkthdr.rcvif = ifp;
3023 	m->m_data = head;
3024 	m->m_pkthdr.len = m->m_len = len;
3025 
3026 	/* Grab a reference to the source node. */
3027 	wh = mtod(m, struct ieee80211_frame *);
3028 	if (len >= sizeof(struct ieee80211_frame_min))
3029 		ni = ieee80211_find_rxnode(ic, (struct ieee80211_frame_min *)wh);
3030 	else
3031 		ni = NULL;
3032 	nf = (ni != NULL && ni->ni_vap->iv_state == IEEE80211_S_RUN &&
3033 	    (ic->ic_flags & IEEE80211_F_SCAN) == 0) ? sc->noise : -95;
3034 
3035 	rssi = ops->get_rssi(sc, stat);
3036 
3037 	if (ieee80211_radiotap_active(ic)) {
3038 		struct iwn_rx_radiotap_header *tap = &sc->sc_rxtap;
3039 
3040 		tap->wr_flags = 0;
3041 		if (stat->flags & htole16(IWN_STAT_FLAG_SHPREAMBLE))
3042 			tap->wr_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
3043 		tap->wr_dbm_antsignal = (int8_t)rssi;
3044 		tap->wr_dbm_antnoise = (int8_t)nf;
3045 		tap->wr_tsft = stat->tstamp;
3046 		switch (stat->rate) {
3047 		/* CCK rates. */
3048 		case  10: tap->wr_rate =   2; break;
3049 		case  20: tap->wr_rate =   4; break;
3050 		case  55: tap->wr_rate =  11; break;
3051 		case 110: tap->wr_rate =  22; break;
3052 		/* OFDM rates. */
3053 		case 0xd: tap->wr_rate =  12; break;
3054 		case 0xf: tap->wr_rate =  18; break;
3055 		case 0x5: tap->wr_rate =  24; break;
3056 		case 0x7: tap->wr_rate =  36; break;
3057 		case 0x9: tap->wr_rate =  48; break;
3058 		case 0xb: tap->wr_rate =  72; break;
3059 		case 0x1: tap->wr_rate =  96; break;
3060 		case 0x3: tap->wr_rate = 108; break;
3061 		/* Unknown rate: should not happen. */
3062 		default:  tap->wr_rate =   0;
3063 		}
3064 	}
3065 
3066 	IWN_UNLOCK(sc);
3067 
3068 	/* Send the frame to the 802.11 layer. */
3069 	if (ni != NULL) {
3070 		if (ni->ni_flags & IEEE80211_NODE_HT)
3071 			m->m_flags |= M_AMPDU;
3072 		(void)ieee80211_input(ni, m, rssi - nf, nf);
3073 		/* Node is no longer needed. */
3074 		ieee80211_free_node(ni);
3075 	} else
3076 		(void)ieee80211_input_all(ic, m, rssi - nf, nf);
3077 
3078 	IWN_LOCK(sc);
3079 
3080 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
3081 
3082 }
3083 
3084 /* Process an incoming Compressed BlockAck. */
3085 static void
3086 iwn_rx_compressed_ba(struct iwn_softc *sc, struct iwn_rx_desc *desc,
3087     struct iwn_rx_data *data)
3088 {
3089 	struct iwn_ops *ops = &sc->ops;
3090 	struct ifnet *ifp = sc->sc_ifp;
3091 	struct iwn_node *wn;
3092 	struct ieee80211_node *ni;
3093 	struct iwn_compressed_ba *ba = (struct iwn_compressed_ba *)(desc + 1);
3094 	struct iwn_tx_ring *txq;
3095 	struct iwn_tx_data *txdata;
3096 	struct ieee80211_tx_ampdu *tap;
3097 	struct mbuf *m;
3098 	uint64_t bitmap;
3099 	uint16_t ssn;
3100 	uint8_t tid;
3101 	int ackfailcnt = 0, i, lastidx, qid, *res, shift;
3102 	int tx_ok = 0, tx_err = 0;
3103 
3104 	DPRINTF(sc, IWN_DEBUG_TRACE | IWN_DEBUG_XMIT, "->%s begin\n", __func__);
3105 
3106 	bus_dmamap_sync(sc->rxq.data_dmat, data->map, BUS_DMASYNC_POSTREAD);
3107 
3108 	qid = le16toh(ba->qid);
3109 	txq = &sc->txq[ba->qid];
3110 	tap = sc->qid2tap[ba->qid];
3111 	tid = tap->txa_tid;
3112 	wn = (void *)tap->txa_ni;
3113 
3114 	res = NULL;
3115 	ssn = 0;
3116 	if (!IEEE80211_AMPDU_RUNNING(tap)) {
3117 		res = tap->txa_private;
3118 		ssn = tap->txa_start & 0xfff;
3119 	}
3120 
3121 	for (lastidx = le16toh(ba->ssn) & 0xff; txq->read != lastidx;) {
3122 		txdata = &txq->data[txq->read];
3123 
3124 		/* Unmap and free mbuf. */
3125 		bus_dmamap_sync(txq->data_dmat, txdata->map,
3126 		    BUS_DMASYNC_POSTWRITE);
3127 		bus_dmamap_unload(txq->data_dmat, txdata->map);
3128 		m = txdata->m, txdata->m = NULL;
3129 		ni = txdata->ni, txdata->ni = NULL;
3130 
3131 		KASSERT(ni != NULL, ("no node"));
3132 		KASSERT(m != NULL, ("no mbuf"));
3133 
3134 		DPRINTF(sc, IWN_DEBUG_XMIT, "%s: freeing m=%p\n", __func__, m);
3135 		ieee80211_tx_complete(ni, m, 1);
3136 
3137 		txq->queued--;
3138 		txq->read = (txq->read + 1) % IWN_TX_RING_COUNT;
3139 	}
3140 
3141 	if (txq->queued == 0 && res != NULL) {
3142 		iwn_nic_lock(sc);
3143 		ops->ampdu_tx_stop(sc, qid, tid, ssn);
3144 		iwn_nic_unlock(sc);
3145 		sc->qid2tap[qid] = NULL;
3146 		free(res, M_DEVBUF);
3147 		return;
3148 	}
3149 
3150 	if (wn->agg[tid].bitmap == 0)
3151 		return;
3152 
3153 	shift = wn->agg[tid].startidx - ((le16toh(ba->seq) >> 4) & 0xff);
3154 	if (shift < 0)
3155 		shift += 0x100;
3156 
3157 	if (wn->agg[tid].nframes > (64 - shift))
3158 		return;
3159 
3160 	/*
3161 	 * Walk the bitmap and calculate how many successful and failed
3162 	 * attempts are made.
3163 	 *
3164 	 * Yes, the rate control code doesn't know these are A-MPDU
3165 	 * subframes and that it's okay to fail some of these.
3166 	 */
3167 	ni = tap->txa_ni;
3168 	bitmap = (le64toh(ba->bitmap) >> shift) & wn->agg[tid].bitmap;
3169 	for (i = 0; bitmap; i++) {
3170 		if ((bitmap & 1) == 0) {
3171 			if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
3172 			tx_err ++;
3173 			ieee80211_ratectl_tx_complete(ni->ni_vap, ni,
3174 			    IEEE80211_RATECTL_TX_FAILURE, &ackfailcnt, NULL);
3175 		} else {
3176 			if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
3177 			tx_ok ++;
3178 			ieee80211_ratectl_tx_complete(ni->ni_vap, ni,
3179 			    IEEE80211_RATECTL_TX_SUCCESS, &ackfailcnt, NULL);
3180 		}
3181 		bitmap >>= 1;
3182 	}
3183 
3184 	DPRINTF(sc, IWN_DEBUG_TRACE | IWN_DEBUG_XMIT,
3185 	    "->%s: end; %d ok; %d err\n",__func__, tx_ok, tx_err);
3186 
3187 }
3188 
3189 /*
3190  * Process a CALIBRATION_RESULT notification sent by the initialization
3191  * firmware on response to a CMD_CALIB_CONFIG command (5000 only).
3192  */
3193 static void
3194 iwn5000_rx_calib_results(struct iwn_softc *sc, struct iwn_rx_desc *desc,
3195     struct iwn_rx_data *data)
3196 {
3197 	struct iwn_phy_calib *calib = (struct iwn_phy_calib *)(desc + 1);
3198 	int len, idx = -1;
3199 
3200 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
3201 
3202 	/* Runtime firmware should not send such a notification. */
3203 	if (sc->sc_flags & IWN_FLAG_CALIB_DONE){
3204 		DPRINTF(sc, IWN_DEBUG_TRACE, "->%s received after clib done\n",
3205 	    __func__);
3206 		return;
3207 	}
3208 	len = (le32toh(desc->len) & 0x3fff) - 4;
3209 	bus_dmamap_sync(sc->rxq.data_dmat, data->map, BUS_DMASYNC_POSTREAD);
3210 
3211 	switch (calib->code) {
3212 	case IWN5000_PHY_CALIB_DC:
3213 		if (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_DC)
3214 			idx = 0;
3215 		break;
3216 	case IWN5000_PHY_CALIB_LO:
3217 		if (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_LO)
3218 			idx = 1;
3219 		break;
3220 	case IWN5000_PHY_CALIB_TX_IQ:
3221 		if (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_TX_IQ)
3222 			idx = 2;
3223 		break;
3224 	case IWN5000_PHY_CALIB_TX_IQ_PERIODIC:
3225 		if (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_TX_IQ_PERIODIC)
3226 			idx = 3;
3227 		break;
3228 	case IWN5000_PHY_CALIB_BASE_BAND:
3229 		if (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_BASE_BAND)
3230 			idx = 4;
3231 		break;
3232 	}
3233 	if (idx == -1)	/* Ignore other results. */
3234 		return;
3235 
3236 	/* Save calibration result. */
3237 	if (sc->calibcmd[idx].buf != NULL)
3238 		free(sc->calibcmd[idx].buf, M_DEVBUF);
3239 	sc->calibcmd[idx].buf = malloc(len, M_DEVBUF, M_NOWAIT);
3240 	if (sc->calibcmd[idx].buf == NULL) {
3241 		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
3242 		    "not enough memory for calibration result %d\n",
3243 		    calib->code);
3244 		return;
3245 	}
3246 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
3247 	    "saving calibration result idx=%d, code=%d len=%d\n", idx, calib->code, len);
3248 	sc->calibcmd[idx].len = len;
3249 	memcpy(sc->calibcmd[idx].buf, calib, len);
3250 }
3251 
3252 static void
3253 iwn_stats_update(struct iwn_softc *sc, struct iwn_calib_state *calib,
3254     struct iwn_stats *stats, int len)
3255 {
3256 	struct iwn_stats_bt *stats_bt;
3257 	struct iwn_stats *lstats;
3258 
3259 	/*
3260 	 * First - check whether the length is the bluetooth or normal.
3261 	 *
3262 	 * If it's normal - just copy it and bump out.
3263 	 * Otherwise we have to convert things.
3264 	 */
3265 
3266 	if (len == sizeof(struct iwn_stats) + 4) {
3267 		memcpy(&sc->last_stat, stats, sizeof(struct iwn_stats));
3268 		sc->last_stat_valid = 1;
3269 		return;
3270 	}
3271 
3272 	/*
3273 	 * If it's not the bluetooth size - log, then just copy.
3274 	 */
3275 	if (len != sizeof(struct iwn_stats_bt) + 4) {
3276 		DPRINTF(sc, IWN_DEBUG_STATS,
3277 		    "%s: size of rx statistics (%d) not an expected size!\n",
3278 		    __func__,
3279 		    len);
3280 		memcpy(&sc->last_stat, stats, sizeof(struct iwn_stats));
3281 		sc->last_stat_valid = 1;
3282 		return;
3283 	}
3284 
3285 	/*
3286 	 * Ok. Time to copy.
3287 	 */
3288 	stats_bt = (struct iwn_stats_bt *) stats;
3289 	lstats = &sc->last_stat;
3290 
3291 	/* flags */
3292 	lstats->flags = stats_bt->flags;
3293 	/* rx_bt */
3294 	memcpy(&lstats->rx.ofdm, &stats_bt->rx_bt.ofdm,
3295 	    sizeof(struct iwn_rx_phy_stats));
3296 	memcpy(&lstats->rx.cck, &stats_bt->rx_bt.cck,
3297 	    sizeof(struct iwn_rx_phy_stats));
3298 	memcpy(&lstats->rx.general, &stats_bt->rx_bt.general_bt.common,
3299 	    sizeof(struct iwn_rx_general_stats));
3300 	memcpy(&lstats->rx.ht, &stats_bt->rx_bt.ht,
3301 	    sizeof(struct iwn_rx_ht_phy_stats));
3302 	/* tx */
3303 	memcpy(&lstats->tx, &stats_bt->tx,
3304 	    sizeof(struct iwn_tx_stats));
3305 	/* general */
3306 	memcpy(&lstats->general, &stats_bt->general,
3307 	    sizeof(struct iwn_general_stats));
3308 
3309 	/* XXX TODO: Squirrel away the extra bluetooth stats somewhere */
3310 	sc->last_stat_valid = 1;
3311 }
3312 
3313 /*
3314  * Process an RX_STATISTICS or BEACON_STATISTICS firmware notification.
3315  * The latter is sent by the firmware after each received beacon.
3316  */
3317 static void
3318 iwn_rx_statistics(struct iwn_softc *sc, struct iwn_rx_desc *desc,
3319     struct iwn_rx_data *data)
3320 {
3321 	struct iwn_ops *ops = &sc->ops;
3322 	struct ifnet *ifp = sc->sc_ifp;
3323 	struct ieee80211com *ic = ifp->if_l2com;
3324 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3325 	struct iwn_calib_state *calib = &sc->calib;
3326 	struct iwn_stats *stats = (struct iwn_stats *)(desc + 1);
3327 	struct iwn_stats *lstats;
3328 	int temp;
3329 
3330 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
3331 
3332 	/* Ignore statistics received during a scan. */
3333 	if (vap->iv_state != IEEE80211_S_RUN ||
3334 	    (ic->ic_flags & IEEE80211_F_SCAN)){
3335 		DPRINTF(sc, IWN_DEBUG_TRACE, "->%s received during calib\n",
3336 	    __func__);
3337 		return;
3338 	}
3339 
3340 	bus_dmamap_sync(sc->rxq.data_dmat, data->map, BUS_DMASYNC_POSTREAD);
3341 
3342 	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_STATS,
3343 	    "%s: received statistics, cmd %d, len %d\n",
3344 	    __func__, desc->type, le16toh(desc->len));
3345 	sc->calib_cnt = 0;	/* Reset TX power calibration timeout. */
3346 
3347 	/*
3348 	 * Collect/track general statistics for reporting.
3349 	 *
3350 	 * This takes care of ensuring that the bluetooth sized message
3351 	 * will be correctly converted to the legacy sized message.
3352 	 */
3353 	iwn_stats_update(sc, calib, stats, le16toh(desc->len));
3354 
3355 	/*
3356 	 * And now, let's take a reference of it to use!
3357 	 */
3358 	lstats = &sc->last_stat;
3359 
3360 	/* Test if temperature has changed. */
3361 	if (lstats->general.temp != sc->rawtemp) {
3362 		/* Convert "raw" temperature to degC. */
3363 		sc->rawtemp = stats->general.temp;
3364 		temp = ops->get_temperature(sc);
3365 		DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: temperature %d\n",
3366 		    __func__, temp);
3367 
3368 		/* Update TX power if need be (4965AGN only). */
3369 		if (sc->hw_type == IWN_HW_REV_TYPE_4965)
3370 			iwn4965_power_calibration(sc, temp);
3371 	}
3372 
3373 	if (desc->type != IWN_BEACON_STATISTICS)
3374 		return;	/* Reply to a statistics request. */
3375 
3376 	sc->noise = iwn_get_noise(&lstats->rx.general);
3377 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: noise %d\n", __func__, sc->noise);
3378 
3379 	/* Test that RSSI and noise are present in stats report. */
3380 	if (le32toh(lstats->rx.general.flags) != 1) {
3381 		DPRINTF(sc, IWN_DEBUG_ANY, "%s\n",
3382 		    "received statistics without RSSI");
3383 		return;
3384 	}
3385 
3386 	if (calib->state == IWN_CALIB_STATE_ASSOC)
3387 		iwn_collect_noise(sc, &lstats->rx.general);
3388 	else if (calib->state == IWN_CALIB_STATE_RUN) {
3389 		iwn_tune_sensitivity(sc, &lstats->rx);
3390 		/*
3391 		 * XXX TODO: Only run the RX recovery if we're associated!
3392 		 */
3393 		iwn_check_rx_recovery(sc, lstats);
3394 		iwn_save_stats_counters(sc, lstats);
3395 	}
3396 
3397 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
3398 }
3399 
3400 /*
3401  * Save the relevant statistic counters for the next calibration
3402  * pass.
3403  */
3404 static void
3405 iwn_save_stats_counters(struct iwn_softc *sc, const struct iwn_stats *rs)
3406 {
3407 	struct iwn_calib_state *calib = &sc->calib;
3408 
3409 	/* Save counters values for next call. */
3410 	calib->bad_plcp_cck = le32toh(rs->rx.cck.bad_plcp);
3411 	calib->fa_cck = le32toh(rs->rx.cck.fa);
3412 	calib->bad_plcp_ht = le32toh(rs->rx.ht.bad_plcp);
3413 	calib->bad_plcp_ofdm = le32toh(rs->rx.ofdm.bad_plcp);
3414 	calib->fa_ofdm = le32toh(rs->rx.ofdm.fa);
3415 
3416 	/* Last time we received these tick values */
3417 	sc->last_calib_ticks = ticks;
3418 }
3419 
3420 /*
3421  * Process a TX_DONE firmware notification.  Unfortunately, the 4965AGN
3422  * and 5000 adapters have different incompatible TX status formats.
3423  */
3424 static void
3425 iwn4965_tx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc,
3426     struct iwn_rx_data *data)
3427 {
3428 	struct iwn4965_tx_stat *stat = (struct iwn4965_tx_stat *)(desc + 1);
3429 	struct iwn_tx_ring *ring;
3430 	int qid;
3431 
3432 	qid = desc->qid & 0xf;
3433 	ring = &sc->txq[qid];
3434 
3435 	DPRINTF(sc, IWN_DEBUG_XMIT, "%s: "
3436 	    "qid %d idx %d RTS retries %d ACK retries %d nkill %d rate %x duration %d status %x\n",
3437 	    __func__, desc->qid, desc->idx,
3438 	    stat->rtsfailcnt,
3439 	    stat->ackfailcnt,
3440 	    stat->btkillcnt,
3441 	    stat->rate, le16toh(stat->duration),
3442 	    le32toh(stat->status));
3443 
3444 	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTREAD);
3445 	if (qid >= sc->firstaggqueue) {
3446 		iwn_ampdu_tx_done(sc, qid, desc->idx, stat->nframes,
3447 		    stat->ackfailcnt, &stat->status);
3448 	} else {
3449 		iwn_tx_done(sc, desc, stat->ackfailcnt,
3450 		    le32toh(stat->status) & 0xff);
3451 	}
3452 }
3453 
3454 static void
3455 iwn5000_tx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc,
3456     struct iwn_rx_data *data)
3457 {
3458 	struct iwn5000_tx_stat *stat = (struct iwn5000_tx_stat *)(desc + 1);
3459 	struct iwn_tx_ring *ring;
3460 	int qid;
3461 
3462 	qid = desc->qid & 0xf;
3463 	ring = &sc->txq[qid];
3464 
3465 	DPRINTF(sc, IWN_DEBUG_XMIT, "%s: "
3466 	    "qid %d idx %d RTS retries %d ACK retries %d nkill %d rate %x duration %d status %x\n",
3467 	    __func__, desc->qid, desc->idx,
3468 	    stat->rtsfailcnt,
3469 	    stat->ackfailcnt,
3470 	    stat->btkillcnt,
3471 	    stat->rate, le16toh(stat->duration),
3472 	    le32toh(stat->status));
3473 
3474 #ifdef notyet
3475 	/* Reset TX scheduler slot. */
3476 	iwn5000_reset_sched(sc, desc->qid & 0xf, desc->idx);
3477 #endif
3478 
3479 	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTREAD);
3480 	if (qid >= sc->firstaggqueue) {
3481 		iwn_ampdu_tx_done(sc, qid, desc->idx, stat->nframes,
3482 		    stat->ackfailcnt, &stat->status);
3483 	} else {
3484 		iwn_tx_done(sc, desc, stat->ackfailcnt,
3485 		    le16toh(stat->status) & 0xff);
3486 	}
3487 }
3488 
3489 /*
3490  * Adapter-independent backend for TX_DONE firmware notifications.
3491  */
3492 static void
3493 iwn_tx_done(struct iwn_softc *sc, struct iwn_rx_desc *desc, int ackfailcnt,
3494     uint8_t status)
3495 {
3496 	struct ifnet *ifp = sc->sc_ifp;
3497 	struct iwn_tx_ring *ring = &sc->txq[desc->qid & 0xf];
3498 	struct iwn_tx_data *data = &ring->data[desc->idx];
3499 	struct mbuf *m;
3500 	struct ieee80211_node *ni;
3501 	struct ieee80211vap *vap;
3502 
3503 	KASSERT(data->ni != NULL, ("no node"));
3504 
3505 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
3506 
3507 	/* Unmap and free mbuf. */
3508 	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTWRITE);
3509 	bus_dmamap_unload(ring->data_dmat, data->map);
3510 	m = data->m, data->m = NULL;
3511 	ni = data->ni, data->ni = NULL;
3512 	vap = ni->ni_vap;
3513 
3514 	/*
3515 	 * Update rate control statistics for the node.
3516 	 */
3517 	if (status & IWN_TX_FAIL) {
3518 		if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
3519 		ieee80211_ratectl_tx_complete(vap, ni,
3520 		    IEEE80211_RATECTL_TX_FAILURE, &ackfailcnt, NULL);
3521 	} else {
3522 		if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
3523 		ieee80211_ratectl_tx_complete(vap, ni,
3524 		    IEEE80211_RATECTL_TX_SUCCESS, &ackfailcnt, NULL);
3525 	}
3526 
3527 	/*
3528 	 * Channels marked for "radar" require traffic to be received
3529 	 * to unlock before we can transmit.  Until traffic is seen
3530 	 * any attempt to transmit is returned immediately with status
3531 	 * set to IWN_TX_FAIL_TX_LOCKED.  Unfortunately this can easily
3532 	 * happen on first authenticate after scanning.  To workaround
3533 	 * this we ignore a failure of this sort in AUTH state so the
3534 	 * 802.11 layer will fall back to using a timeout to wait for
3535 	 * the AUTH reply.  This allows the firmware time to see
3536 	 * traffic so a subsequent retry of AUTH succeeds.  It's
3537 	 * unclear why the firmware does not maintain state for
3538 	 * channels recently visited as this would allow immediate
3539 	 * use of the channel after a scan (where we see traffic).
3540 	 */
3541 	if (status == IWN_TX_FAIL_TX_LOCKED &&
3542 	    ni->ni_vap->iv_state == IEEE80211_S_AUTH)
3543 		ieee80211_tx_complete(ni, m, 0);
3544 	else
3545 		ieee80211_tx_complete(ni, m,
3546 		    (status & IWN_TX_FAIL) != 0);
3547 
3548 	sc->sc_tx_timer = 0;
3549 	if (--ring->queued < IWN_TX_RING_LOMARK) {
3550 		sc->qfullmsk &= ~(1 << ring->qid);
3551 		if (sc->qfullmsk == 0 &&
3552 		    (ifp->if_drv_flags & IFF_DRV_OACTIVE)) {
3553 			ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3554 			iwn_start_locked(ifp);
3555 		}
3556 	}
3557 
3558 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
3559 
3560 }
3561 
3562 /*
3563  * Process a "command done" firmware notification.  This is where we wakeup
3564  * processes waiting for a synchronous command completion.
3565  */
3566 static void
3567 iwn_cmd_done(struct iwn_softc *sc, struct iwn_rx_desc *desc)
3568 {
3569 	struct iwn_tx_ring *ring;
3570 	struct iwn_tx_data *data;
3571 	int cmd_queue_num;
3572 
3573 	if (sc->sc_flags & IWN_FLAG_PAN_SUPPORT)
3574 		cmd_queue_num = IWN_PAN_CMD_QUEUE;
3575 	else
3576 		cmd_queue_num = IWN_CMD_QUEUE_NUM;
3577 
3578 	if ((desc->qid & IWN_RX_DESC_QID_MSK) != cmd_queue_num)
3579 		return;	/* Not a command ack. */
3580 
3581 	ring = &sc->txq[cmd_queue_num];
3582 	data = &ring->data[desc->idx];
3583 
3584 	/* If the command was mapped in an mbuf, free it. */
3585 	if (data->m != NULL) {
3586 		bus_dmamap_sync(ring->data_dmat, data->map,
3587 		    BUS_DMASYNC_POSTWRITE);
3588 		bus_dmamap_unload(ring->data_dmat, data->map);
3589 		m_freem(data->m);
3590 		data->m = NULL;
3591 	}
3592 	wakeup(&ring->desc[desc->idx]);
3593 }
3594 
3595 static void
3596 iwn_ampdu_tx_done(struct iwn_softc *sc, int qid, int idx, int nframes,
3597     int ackfailcnt, void *stat)
3598 {
3599 	struct iwn_ops *ops = &sc->ops;
3600 	struct ifnet *ifp = sc->sc_ifp;
3601 	struct iwn_tx_ring *ring = &sc->txq[qid];
3602 	struct iwn_tx_data *data;
3603 	struct mbuf *m;
3604 	struct iwn_node *wn;
3605 	struct ieee80211_node *ni;
3606 	struct ieee80211_tx_ampdu *tap;
3607 	uint64_t bitmap;
3608 	uint32_t *status = stat;
3609 	uint16_t *aggstatus = stat;
3610 	uint16_t ssn;
3611 	uint8_t tid;
3612 	int bit, i, lastidx, *res, seqno, shift, start;
3613 
3614 	/* XXX TODO: status is le16 field! Grr */
3615 
3616 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
3617 	DPRINTF(sc, IWN_DEBUG_XMIT, "%s: nframes=%d, status=0x%08x\n",
3618 	    __func__,
3619 	    nframes,
3620 	    *status);
3621 
3622 	tap = sc->qid2tap[qid];
3623 	tid = tap->txa_tid;
3624 	wn = (void *)tap->txa_ni;
3625 	ni = tap->txa_ni;
3626 
3627 	/*
3628 	 * XXX TODO: ACK and RTS failures would be nice here!
3629 	 */
3630 
3631 	/*
3632 	 * A-MPDU single frame status - if we failed to transmit it
3633 	 * in A-MPDU, then it may be a permanent failure.
3634 	 *
3635 	 * XXX TODO: check what the Linux iwlwifi driver does here;
3636 	 * there's some permanent and temporary failures that may be
3637 	 * handled differently.
3638 	 */
3639 	if (nframes == 1) {
3640 		if ((*status & 0xff) != 1 && (*status & 0xff) != 2) {
3641 #ifdef	NOT_YET
3642 			printf("ieee80211_send_bar()\n");
3643 #endif
3644 			/*
3645 			 * If we completely fail a transmit, make sure a
3646 			 * notification is pushed up to the rate control
3647 			 * layer.
3648 			 */
3649 			ieee80211_ratectl_tx_complete(ni->ni_vap,
3650 			    ni,
3651 			    IEEE80211_RATECTL_TX_FAILURE,
3652 			    &ackfailcnt,
3653 			    NULL);
3654 		} else {
3655 			/*
3656 			 * If nframes=1, then we won't be getting a BA for
3657 			 * this frame.  Ensure that we correctly update the
3658 			 * rate control code with how many retries were
3659 			 * needed to send it.
3660 			 */
3661 			ieee80211_ratectl_tx_complete(ni->ni_vap,
3662 			    ni,
3663 			    IEEE80211_RATECTL_TX_SUCCESS,
3664 			    &ackfailcnt,
3665 			    NULL);
3666 		}
3667 	}
3668 
3669 	bitmap = 0;
3670 	start = idx;
3671 	for (i = 0; i < nframes; i++) {
3672 		if (le16toh(aggstatus[i * 2]) & 0xc)
3673 			continue;
3674 
3675 		idx = le16toh(aggstatus[2*i + 1]) & 0xff;
3676 		bit = idx - start;
3677 		shift = 0;
3678 		if (bit >= 64) {
3679 			shift = 0x100 - idx + start;
3680 			bit = 0;
3681 			start = idx;
3682 		} else if (bit <= -64)
3683 			bit = 0x100 - start + idx;
3684 		else if (bit < 0) {
3685 			shift = start - idx;
3686 			start = idx;
3687 			bit = 0;
3688 		}
3689 		bitmap = bitmap << shift;
3690 		bitmap |= 1ULL << bit;
3691 	}
3692 	tap = sc->qid2tap[qid];
3693 	tid = tap->txa_tid;
3694 	wn = (void *)tap->txa_ni;
3695 	wn->agg[tid].bitmap = bitmap;
3696 	wn->agg[tid].startidx = start;
3697 	wn->agg[tid].nframes = nframes;
3698 
3699 	res = NULL;
3700 	ssn = 0;
3701 	if (!IEEE80211_AMPDU_RUNNING(tap)) {
3702 		res = tap->txa_private;
3703 		ssn = tap->txa_start & 0xfff;
3704 	}
3705 
3706 	/* This is going nframes DWORDS into the descriptor? */
3707 	seqno = le32toh(*(status + nframes)) & 0xfff;
3708 	for (lastidx = (seqno & 0xff); ring->read != lastidx;) {
3709 		data = &ring->data[ring->read];
3710 
3711 		/* Unmap and free mbuf. */
3712 		bus_dmamap_sync(ring->data_dmat, data->map,
3713 		    BUS_DMASYNC_POSTWRITE);
3714 		bus_dmamap_unload(ring->data_dmat, data->map);
3715 		m = data->m, data->m = NULL;
3716 		ni = data->ni, data->ni = NULL;
3717 
3718 		KASSERT(ni != NULL, ("no node"));
3719 		KASSERT(m != NULL, ("no mbuf"));
3720 		DPRINTF(sc, IWN_DEBUG_XMIT, "%s: freeing m=%p\n", __func__, m);
3721 		ieee80211_tx_complete(ni, m, 1);
3722 
3723 		ring->queued--;
3724 		ring->read = (ring->read + 1) % IWN_TX_RING_COUNT;
3725 	}
3726 
3727 	if (ring->queued == 0 && res != NULL) {
3728 		iwn_nic_lock(sc);
3729 		ops->ampdu_tx_stop(sc, qid, tid, ssn);
3730 		iwn_nic_unlock(sc);
3731 		sc->qid2tap[qid] = NULL;
3732 		free(res, M_DEVBUF);
3733 		return;
3734 	}
3735 
3736 	sc->sc_tx_timer = 0;
3737 	if (ring->queued < IWN_TX_RING_LOMARK) {
3738 		sc->qfullmsk &= ~(1 << ring->qid);
3739 		if (sc->qfullmsk == 0 &&
3740 		    (ifp->if_drv_flags & IFF_DRV_OACTIVE)) {
3741 			ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3742 			iwn_start_locked(ifp);
3743 		}
3744 	}
3745 
3746 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
3747 
3748 }
3749 
3750 /*
3751  * Process an INT_FH_RX or INT_SW_RX interrupt.
3752  */
3753 static void
3754 iwn_notif_intr(struct iwn_softc *sc)
3755 {
3756 	struct iwn_ops *ops = &sc->ops;
3757 	struct ifnet *ifp = sc->sc_ifp;
3758 	struct ieee80211com *ic = ifp->if_l2com;
3759 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3760 	uint16_t hw;
3761 
3762 	bus_dmamap_sync(sc->rxq.stat_dma.tag, sc->rxq.stat_dma.map,
3763 	    BUS_DMASYNC_POSTREAD);
3764 
3765 	hw = le16toh(sc->rxq.stat->closed_count) & 0xfff;
3766 	while (sc->rxq.cur != hw) {
3767 		struct iwn_rx_data *data = &sc->rxq.data[sc->rxq.cur];
3768 		struct iwn_rx_desc *desc;
3769 
3770 		bus_dmamap_sync(sc->rxq.data_dmat, data->map,
3771 		    BUS_DMASYNC_POSTREAD);
3772 		desc = mtod(data->m, struct iwn_rx_desc *);
3773 
3774 		DPRINTF(sc, IWN_DEBUG_RECV,
3775 		    "%s: cur=%d; qid %x idx %d flags %x type %d(%s) len %d\n",
3776 		    __func__, sc->rxq.cur, desc->qid & 0xf, desc->idx, desc->flags,
3777 		    desc->type, iwn_intr_str(desc->type),
3778 		    le16toh(desc->len));
3779 
3780 		if (!(desc->qid & IWN_UNSOLICITED_RX_NOTIF))	/* Reply to a command. */
3781 			iwn_cmd_done(sc, desc);
3782 
3783 		switch (desc->type) {
3784 		case IWN_RX_PHY:
3785 			iwn_rx_phy(sc, desc, data);
3786 			break;
3787 
3788 		case IWN_RX_DONE:		/* 4965AGN only. */
3789 		case IWN_MPDU_RX_DONE:
3790 			/* An 802.11 frame has been received. */
3791 			iwn_rx_done(sc, desc, data);
3792 			break;
3793 
3794 		case IWN_RX_COMPRESSED_BA:
3795 			/* A Compressed BlockAck has been received. */
3796 			iwn_rx_compressed_ba(sc, desc, data);
3797 			break;
3798 
3799 		case IWN_TX_DONE:
3800 			/* An 802.11 frame has been transmitted. */
3801 			ops->tx_done(sc, desc, data);
3802 			break;
3803 
3804 		case IWN_RX_STATISTICS:
3805 		case IWN_BEACON_STATISTICS:
3806 			iwn_rx_statistics(sc, desc, data);
3807 			break;
3808 
3809 		case IWN_BEACON_MISSED:
3810 		{
3811 			struct iwn_beacon_missed *miss =
3812 			    (struct iwn_beacon_missed *)(desc + 1);
3813 			int misses;
3814 
3815 			bus_dmamap_sync(sc->rxq.data_dmat, data->map,
3816 			    BUS_DMASYNC_POSTREAD);
3817 			misses = le32toh(miss->consecutive);
3818 
3819 			DPRINTF(sc, IWN_DEBUG_STATE,
3820 			    "%s: beacons missed %d/%d\n", __func__,
3821 			    misses, le32toh(miss->total));
3822 			/*
3823 			 * If more than 5 consecutive beacons are missed,
3824 			 * reinitialize the sensitivity state machine.
3825 			 */
3826 			if (vap->iv_state == IEEE80211_S_RUN &&
3827 			    (ic->ic_flags & IEEE80211_F_SCAN) == 0) {
3828 				if (misses > 5)
3829 					(void)iwn_init_sensitivity(sc);
3830 				if (misses >= vap->iv_bmissthreshold) {
3831 					IWN_UNLOCK(sc);
3832 					ieee80211_beacon_miss(ic);
3833 					IWN_LOCK(sc);
3834 				}
3835 			}
3836 			break;
3837 		}
3838 		case IWN_UC_READY:
3839 		{
3840 			struct iwn_ucode_info *uc =
3841 			    (struct iwn_ucode_info *)(desc + 1);
3842 
3843 			/* The microcontroller is ready. */
3844 			bus_dmamap_sync(sc->rxq.data_dmat, data->map,
3845 			    BUS_DMASYNC_POSTREAD);
3846 			DPRINTF(sc, IWN_DEBUG_RESET,
3847 			    "microcode alive notification version=%d.%d "
3848 			    "subtype=%x alive=%x\n", uc->major, uc->minor,
3849 			    uc->subtype, le32toh(uc->valid));
3850 
3851 			if (le32toh(uc->valid) != 1) {
3852 				device_printf(sc->sc_dev,
3853 				    "microcontroller initialization failed");
3854 				break;
3855 			}
3856 			if (uc->subtype == IWN_UCODE_INIT) {
3857 				/* Save microcontroller report. */
3858 				memcpy(&sc->ucode_info, uc, sizeof (*uc));
3859 			}
3860 			/* Save the address of the error log in SRAM. */
3861 			sc->errptr = le32toh(uc->errptr);
3862 			break;
3863 		}
3864 		case IWN_STATE_CHANGED:
3865 		{
3866 			/*
3867 			 * State change allows hardware switch change to be
3868 			 * noted. However, we handle this in iwn_intr as we
3869 			 * get both the enable/disble intr.
3870 			 */
3871 			bus_dmamap_sync(sc->rxq.data_dmat, data->map,
3872 			    BUS_DMASYNC_POSTREAD);
3873 #ifdef	IWN_DEBUG
3874 			uint32_t *status = (uint32_t *)(desc + 1);
3875 			DPRINTF(sc, IWN_DEBUG_INTR | IWN_DEBUG_STATE,
3876 			    "state changed to %x\n",
3877 			    le32toh(*status));
3878 #endif
3879 			break;
3880 		}
3881 		case IWN_START_SCAN:
3882 		{
3883 			bus_dmamap_sync(sc->rxq.data_dmat, data->map,
3884 			    BUS_DMASYNC_POSTREAD);
3885 #ifdef	IWN_DEBUG
3886 			struct iwn_start_scan *scan =
3887 			    (struct iwn_start_scan *)(desc + 1);
3888 			DPRINTF(sc, IWN_DEBUG_ANY,
3889 			    "%s: scanning channel %d status %x\n",
3890 			    __func__, scan->chan, le32toh(scan->status));
3891 #endif
3892 			break;
3893 		}
3894 		case IWN_STOP_SCAN:
3895 		{
3896 			bus_dmamap_sync(sc->rxq.data_dmat, data->map,
3897 			    BUS_DMASYNC_POSTREAD);
3898 #ifdef	IWN_DEBUG
3899 			struct iwn_stop_scan *scan =
3900 			    (struct iwn_stop_scan *)(desc + 1);
3901 			DPRINTF(sc, IWN_DEBUG_STATE | IWN_DEBUG_SCAN,
3902 			    "scan finished nchan=%d status=%d chan=%d\n",
3903 			    scan->nchan, scan->status, scan->chan);
3904 #endif
3905 			sc->sc_is_scanning = 0;
3906 			IWN_UNLOCK(sc);
3907 			ieee80211_scan_next(vap);
3908 			IWN_LOCK(sc);
3909 			break;
3910 		}
3911 		case IWN5000_CALIBRATION_RESULT:
3912 			iwn5000_rx_calib_results(sc, desc, data);
3913 			break;
3914 
3915 		case IWN5000_CALIBRATION_DONE:
3916 			sc->sc_flags |= IWN_FLAG_CALIB_DONE;
3917 			wakeup(sc);
3918 			break;
3919 		}
3920 
3921 		sc->rxq.cur = (sc->rxq.cur + 1) % IWN_RX_RING_COUNT;
3922 	}
3923 
3924 	/* Tell the firmware what we have processed. */
3925 	hw = (hw == 0) ? IWN_RX_RING_COUNT - 1 : hw - 1;
3926 	IWN_WRITE(sc, IWN_FH_RX_WPTR, hw & ~7);
3927 }
3928 
3929 /*
3930  * Process an INT_WAKEUP interrupt raised when the microcontroller wakes up
3931  * from power-down sleep mode.
3932  */
3933 static void
3934 iwn_wakeup_intr(struct iwn_softc *sc)
3935 {
3936 	int qid;
3937 
3938 	DPRINTF(sc, IWN_DEBUG_RESET, "%s: ucode wakeup from power-down sleep\n",
3939 	    __func__);
3940 
3941 	/* Wakeup RX and TX rings. */
3942 	IWN_WRITE(sc, IWN_FH_RX_WPTR, sc->rxq.cur & ~7);
3943 	for (qid = 0; qid < sc->ntxqs; qid++) {
3944 		struct iwn_tx_ring *ring = &sc->txq[qid];
3945 		IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | ring->cur);
3946 	}
3947 }
3948 
3949 static void
3950 iwn_rftoggle_intr(struct iwn_softc *sc)
3951 {
3952 	struct ifnet *ifp = sc->sc_ifp;
3953 	struct ieee80211com *ic = ifp->if_l2com;
3954 	uint32_t tmp = IWN_READ(sc, IWN_GP_CNTRL);
3955 
3956 	IWN_LOCK_ASSERT(sc);
3957 
3958 	device_printf(sc->sc_dev, "RF switch: radio %s\n",
3959 	    (tmp & IWN_GP_CNTRL_RFKILL) ? "enabled" : "disabled");
3960 	if (tmp & IWN_GP_CNTRL_RFKILL)
3961 		ieee80211_runtask(ic, &sc->sc_radioon_task);
3962 	else
3963 		ieee80211_runtask(ic, &sc->sc_radiooff_task);
3964 }
3965 
3966 /*
3967  * Dump the error log of the firmware when a firmware panic occurs.  Although
3968  * we can't debug the firmware because it is neither open source nor free, it
3969  * can help us to identify certain classes of problems.
3970  */
3971 static void
3972 iwn_fatal_intr(struct iwn_softc *sc)
3973 {
3974 	struct iwn_fw_dump dump;
3975 	int i;
3976 
3977 	IWN_LOCK_ASSERT(sc);
3978 
3979 	/* Force a complete recalibration on next init. */
3980 	sc->sc_flags &= ~IWN_FLAG_CALIB_DONE;
3981 
3982 	/* Check that the error log address is valid. */
3983 	if (sc->errptr < IWN_FW_DATA_BASE ||
3984 	    sc->errptr + sizeof (dump) >
3985 	    IWN_FW_DATA_BASE + sc->fw_data_maxsz) {
3986 		printf("%s: bad firmware error log address 0x%08x\n", __func__,
3987 		    sc->errptr);
3988 		return;
3989 	}
3990 	if (iwn_nic_lock(sc) != 0) {
3991 		printf("%s: could not read firmware error log\n", __func__);
3992 		return;
3993 	}
3994 	/* Read firmware error log from SRAM. */
3995 	iwn_mem_read_region_4(sc, sc->errptr, (uint32_t *)&dump,
3996 	    sizeof (dump) / sizeof (uint32_t));
3997 	iwn_nic_unlock(sc);
3998 
3999 	if (dump.valid == 0) {
4000 		printf("%s: firmware error log is empty\n", __func__);
4001 		return;
4002 	}
4003 	printf("firmware error log:\n");
4004 	printf("  error type      = \"%s\" (0x%08X)\n",
4005 	    (dump.id < nitems(iwn_fw_errmsg)) ?
4006 		iwn_fw_errmsg[dump.id] : "UNKNOWN",
4007 	    dump.id);
4008 	printf("  program counter = 0x%08X\n", dump.pc);
4009 	printf("  source line     = 0x%08X\n", dump.src_line);
4010 	printf("  error data      = 0x%08X%08X\n",
4011 	    dump.error_data[0], dump.error_data[1]);
4012 	printf("  branch link     = 0x%08X%08X\n",
4013 	    dump.branch_link[0], dump.branch_link[1]);
4014 	printf("  interrupt link  = 0x%08X%08X\n",
4015 	    dump.interrupt_link[0], dump.interrupt_link[1]);
4016 	printf("  time            = %u\n", dump.time[0]);
4017 
4018 	/* Dump driver status (TX and RX rings) while we're here. */
4019 	printf("driver status:\n");
4020 	for (i = 0; i < sc->ntxqs; i++) {
4021 		struct iwn_tx_ring *ring = &sc->txq[i];
4022 		printf("  tx ring %2d: qid=%-2d cur=%-3d queued=%-3d\n",
4023 		    i, ring->qid, ring->cur, ring->queued);
4024 	}
4025 	printf("  rx ring: cur=%d\n", sc->rxq.cur);
4026 }
4027 
4028 static void
4029 iwn_intr(void *arg)
4030 {
4031 	struct iwn_softc *sc = arg;
4032 	struct ifnet *ifp = sc->sc_ifp;
4033 	uint32_t r1, r2, tmp;
4034 
4035 	IWN_LOCK(sc);
4036 
4037 	/* Disable interrupts. */
4038 	IWN_WRITE(sc, IWN_INT_MASK, 0);
4039 
4040 	/* Read interrupts from ICT (fast) or from registers (slow). */
4041 	if (sc->sc_flags & IWN_FLAG_USE_ICT) {
4042 		tmp = 0;
4043 		while (sc->ict[sc->ict_cur] != 0) {
4044 			tmp |= sc->ict[sc->ict_cur];
4045 			sc->ict[sc->ict_cur] = 0;	/* Acknowledge. */
4046 			sc->ict_cur = (sc->ict_cur + 1) % IWN_ICT_COUNT;
4047 		}
4048 		tmp = le32toh(tmp);
4049 		if (tmp == 0xffffffff)	/* Shouldn't happen. */
4050 			tmp = 0;
4051 		else if (tmp & 0xc0000)	/* Workaround a HW bug. */
4052 			tmp |= 0x8000;
4053 		r1 = (tmp & 0xff00) << 16 | (tmp & 0xff);
4054 		r2 = 0;	/* Unused. */
4055 	} else {
4056 		r1 = IWN_READ(sc, IWN_INT);
4057 		if (r1 == 0xffffffff || (r1 & 0xfffffff0) == 0xa5a5a5a0) {
4058 			IWN_UNLOCK(sc);
4059 			return;	/* Hardware gone! */
4060 		}
4061 		r2 = IWN_READ(sc, IWN_FH_INT);
4062 	}
4063 
4064 	DPRINTF(sc, IWN_DEBUG_INTR, "interrupt reg1=0x%08x reg2=0x%08x\n"
4065     , r1, r2);
4066 
4067 	if (r1 == 0 && r2 == 0)
4068 		goto done;	/* Interrupt not for us. */
4069 
4070 	/* Acknowledge interrupts. */
4071 	IWN_WRITE(sc, IWN_INT, r1);
4072 	if (!(sc->sc_flags & IWN_FLAG_USE_ICT))
4073 		IWN_WRITE(sc, IWN_FH_INT, r2);
4074 
4075 	if (r1 & IWN_INT_RF_TOGGLED) {
4076 		iwn_rftoggle_intr(sc);
4077 		goto done;
4078 	}
4079 	if (r1 & IWN_INT_CT_REACHED) {
4080 		device_printf(sc->sc_dev, "%s: critical temperature reached!\n",
4081 		    __func__);
4082 	}
4083 	if (r1 & (IWN_INT_SW_ERR | IWN_INT_HW_ERR)) {
4084 		device_printf(sc->sc_dev, "%s: fatal firmware error\n",
4085 		    __func__);
4086 #ifdef	IWN_DEBUG
4087 		iwn_debug_register(sc);
4088 #endif
4089 		/* Dump firmware error log and stop. */
4090 		iwn_fatal_intr(sc);
4091 
4092 		taskqueue_enqueue(sc->sc_tq, &sc->sc_panic_task);
4093 		goto done;
4094 	}
4095 	if ((r1 & (IWN_INT_FH_RX | IWN_INT_SW_RX | IWN_INT_RX_PERIODIC)) ||
4096 	    (r2 & IWN_FH_INT_RX)) {
4097 		if (sc->sc_flags & IWN_FLAG_USE_ICT) {
4098 			if (r1 & (IWN_INT_FH_RX | IWN_INT_SW_RX))
4099 				IWN_WRITE(sc, IWN_FH_INT, IWN_FH_INT_RX);
4100 			IWN_WRITE_1(sc, IWN_INT_PERIODIC,
4101 			    IWN_INT_PERIODIC_DIS);
4102 			iwn_notif_intr(sc);
4103 			if (r1 & (IWN_INT_FH_RX | IWN_INT_SW_RX)) {
4104 				IWN_WRITE_1(sc, IWN_INT_PERIODIC,
4105 				    IWN_INT_PERIODIC_ENA);
4106 			}
4107 		} else
4108 			iwn_notif_intr(sc);
4109 	}
4110 
4111 	if ((r1 & IWN_INT_FH_TX) || (r2 & IWN_FH_INT_TX)) {
4112 		if (sc->sc_flags & IWN_FLAG_USE_ICT)
4113 			IWN_WRITE(sc, IWN_FH_INT, IWN_FH_INT_TX);
4114 		wakeup(sc);	/* FH DMA transfer completed. */
4115 	}
4116 
4117 	if (r1 & IWN_INT_ALIVE)
4118 		wakeup(sc);	/* Firmware is alive. */
4119 
4120 	if (r1 & IWN_INT_WAKEUP)
4121 		iwn_wakeup_intr(sc);
4122 
4123 done:
4124 	/* Re-enable interrupts. */
4125 	if (ifp->if_flags & IFF_UP)
4126 		IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
4127 
4128 	IWN_UNLOCK(sc);
4129 }
4130 
4131 /*
4132  * Update TX scheduler ring when transmitting an 802.11 frame (4965AGN and
4133  * 5000 adapters use a slightly different format).
4134  */
4135 static void
4136 iwn4965_update_sched(struct iwn_softc *sc, int qid, int idx, uint8_t id,
4137     uint16_t len)
4138 {
4139 	uint16_t *w = &sc->sched[qid * IWN4965_SCHED_COUNT + idx];
4140 
4141 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
4142 
4143 	*w = htole16(len + 8);
4144 	bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
4145 	    BUS_DMASYNC_PREWRITE);
4146 	if (idx < IWN_SCHED_WINSZ) {
4147 		*(w + IWN_TX_RING_COUNT) = *w;
4148 		bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
4149 		    BUS_DMASYNC_PREWRITE);
4150 	}
4151 }
4152 
4153 static void
4154 iwn5000_update_sched(struct iwn_softc *sc, int qid, int idx, uint8_t id,
4155     uint16_t len)
4156 {
4157 	uint16_t *w = &sc->sched[qid * IWN5000_SCHED_COUNT + idx];
4158 
4159 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
4160 
4161 	*w = htole16(id << 12 | (len + 8));
4162 	bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
4163 	    BUS_DMASYNC_PREWRITE);
4164 	if (idx < IWN_SCHED_WINSZ) {
4165 		*(w + IWN_TX_RING_COUNT) = *w;
4166 		bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
4167 		    BUS_DMASYNC_PREWRITE);
4168 	}
4169 }
4170 
4171 #ifdef notyet
4172 static void
4173 iwn5000_reset_sched(struct iwn_softc *sc, int qid, int idx)
4174 {
4175 	uint16_t *w = &sc->sched[qid * IWN5000_SCHED_COUNT + idx];
4176 
4177 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
4178 
4179 	*w = (*w & htole16(0xf000)) | htole16(1);
4180 	bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
4181 	    BUS_DMASYNC_PREWRITE);
4182 	if (idx < IWN_SCHED_WINSZ) {
4183 		*(w + IWN_TX_RING_COUNT) = *w;
4184 		bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
4185 		    BUS_DMASYNC_PREWRITE);
4186 	}
4187 }
4188 #endif
4189 
4190 /*
4191  * Check whether OFDM 11g protection will be enabled for the given rate.
4192  *
4193  * The original driver code only enabled protection for OFDM rates.
4194  * It didn't check to see whether it was operating in 11a or 11bg mode.
4195  */
4196 static int
4197 iwn_check_rate_needs_protection(struct iwn_softc *sc,
4198     struct ieee80211vap *vap, uint8_t rate)
4199 {
4200 	struct ieee80211com *ic = vap->iv_ic;
4201 
4202 	/*
4203 	 * Not in 2GHz mode? Then there's no need to enable OFDM
4204 	 * 11bg protection.
4205 	 */
4206 	if (! IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan)) {
4207 		return (0);
4208 	}
4209 
4210 	/*
4211 	 * 11bg protection not enabled? Then don't use it.
4212 	 */
4213 	if ((ic->ic_flags & IEEE80211_F_USEPROT) == 0)
4214 		return (0);
4215 
4216 	/*
4217 	 * If it's an 11n rate - no protection.
4218 	 * We'll do it via a specific 11n check.
4219 	 */
4220 	if (rate & IEEE80211_RATE_MCS) {
4221 		return (0);
4222 	}
4223 
4224 	/*
4225 	 * Do a rate table lookup.  If the PHY is CCK,
4226 	 * don't do protection.
4227 	 */
4228 	if (ieee80211_rate2phytype(ic->ic_rt, rate) == IEEE80211_T_CCK)
4229 		return (0);
4230 
4231 	/*
4232 	 * Yup, enable protection.
4233 	 */
4234 	return (1);
4235 }
4236 
4237 /*
4238  * return a value between 0 and IWN_MAX_TX_RETRIES-1 as an index into
4239  * the link quality table that reflects this particular entry.
4240  */
4241 static int
4242 iwn_tx_rate_to_linkq_offset(struct iwn_softc *sc, struct ieee80211_node *ni,
4243     uint8_t rate)
4244 {
4245 	struct ieee80211_rateset *rs;
4246 	int is_11n;
4247 	int nr;
4248 	int i;
4249 	uint8_t cmp_rate;
4250 
4251 	/*
4252 	 * Figure out if we're using 11n or not here.
4253 	 */
4254 	if (IEEE80211_IS_CHAN_HT(ni->ni_chan) && ni->ni_htrates.rs_nrates > 0)
4255 		is_11n = 1;
4256 	else
4257 		is_11n = 0;
4258 
4259 	/*
4260 	 * Use the correct rate table.
4261 	 */
4262 	if (is_11n) {
4263 		rs = (struct ieee80211_rateset *) &ni->ni_htrates;
4264 		nr = ni->ni_htrates.rs_nrates;
4265 	} else {
4266 		rs = &ni->ni_rates;
4267 		nr = rs->rs_nrates;
4268 	}
4269 
4270 	/*
4271 	 * Find the relevant link quality entry in the table.
4272 	 */
4273 	for (i = 0; i < nr && i < IWN_MAX_TX_RETRIES - 1 ; i++) {
4274 		/*
4275 		 * The link quality table index starts at 0 == highest
4276 		 * rate, so we walk the rate table backwards.
4277 		 */
4278 		cmp_rate = rs->rs_rates[(nr - 1) - i];
4279 		if (rate & IEEE80211_RATE_MCS)
4280 			cmp_rate |= IEEE80211_RATE_MCS;
4281 
4282 #if 0
4283 		DPRINTF(sc, IWN_DEBUG_XMIT, "%s: idx %d: nr=%d, rate=0x%02x, rateentry=0x%02x\n",
4284 		    __func__,
4285 		    i,
4286 		    nr,
4287 		    rate,
4288 		    cmp_rate);
4289 #endif
4290 
4291 		if (cmp_rate == rate)
4292 			return (i);
4293 	}
4294 
4295 	/* Failed? Start at the end */
4296 	return (IWN_MAX_TX_RETRIES - 1);
4297 }
4298 
4299 static int
4300 iwn_tx_data(struct iwn_softc *sc, struct mbuf *m, struct ieee80211_node *ni)
4301 {
4302 	struct iwn_ops *ops = &sc->ops;
4303 	const struct ieee80211_txparam *tp;
4304 	struct ieee80211vap *vap = ni->ni_vap;
4305 	struct ieee80211com *ic = ni->ni_ic;
4306 	struct iwn_node *wn = (void *)ni;
4307 	struct iwn_tx_ring *ring;
4308 	struct iwn_tx_desc *desc;
4309 	struct iwn_tx_data *data;
4310 	struct iwn_tx_cmd *cmd;
4311 	struct iwn_cmd_data *tx;
4312 	struct ieee80211_frame *wh;
4313 	struct ieee80211_key *k = NULL;
4314 	struct mbuf *m1;
4315 	uint32_t flags;
4316 	uint16_t qos;
4317 	u_int hdrlen;
4318 	bus_dma_segment_t *seg, segs[IWN_MAX_SCATTER];
4319 	uint8_t tid, type;
4320 	int ac, i, totlen, error, pad, nsegs = 0, rate;
4321 
4322 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
4323 
4324 	IWN_LOCK_ASSERT(sc);
4325 
4326 	wh = mtod(m, struct ieee80211_frame *);
4327 	hdrlen = ieee80211_anyhdrsize(wh);
4328 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
4329 
4330 	/* Select EDCA Access Category and TX ring for this frame. */
4331 	if (IEEE80211_QOS_HAS_SEQ(wh)) {
4332 		qos = ((const struct ieee80211_qosframe *)wh)->i_qos[0];
4333 		tid = qos & IEEE80211_QOS_TID;
4334 	} else {
4335 		qos = 0;
4336 		tid = 0;
4337 	}
4338 	ac = M_WME_GETAC(m);
4339 	if (m->m_flags & M_AMPDU_MPDU) {
4340 		uint16_t seqno;
4341 		struct ieee80211_tx_ampdu *tap = &ni->ni_tx_ampdu[ac];
4342 
4343 		if (!IEEE80211_AMPDU_RUNNING(tap)) {
4344 			m_freem(m);
4345 			return EINVAL;
4346 		}
4347 
4348 		/*
4349 		 * Queue this frame to the hardware ring that we've
4350 		 * negotiated AMPDU TX on.
4351 		 *
4352 		 * Note that the sequence number must match the TX slot
4353 		 * being used!
4354 		 */
4355 		ac = *(int *)tap->txa_private;
4356 		seqno = ni->ni_txseqs[tid];
4357 		*(uint16_t *)wh->i_seq =
4358 		    htole16(seqno << IEEE80211_SEQ_SEQ_SHIFT);
4359 		ring = &sc->txq[ac];
4360 		if ((seqno % 256) != ring->cur) {
4361 			device_printf(sc->sc_dev,
4362 			    "%s: m=%p: seqno (%d) (%d) != ring index (%d) !\n",
4363 			    __func__,
4364 			    m,
4365 			    seqno,
4366 			    seqno % 256,
4367 			    ring->cur);
4368 		}
4369 		ni->ni_txseqs[tid]++;
4370 	}
4371 	ring = &sc->txq[ac];
4372 	desc = &ring->desc[ring->cur];
4373 	data = &ring->data[ring->cur];
4374 
4375 	/* Choose a TX rate index. */
4376 	tp = &vap->iv_txparms[ieee80211_chan2mode(ni->ni_chan)];
4377 	if (type == IEEE80211_FC0_TYPE_MGT)
4378 		rate = tp->mgmtrate;
4379 	else if (IEEE80211_IS_MULTICAST(wh->i_addr1))
4380 		rate = tp->mcastrate;
4381 	else if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE)
4382 		rate = tp->ucastrate;
4383 	else if (m->m_flags & M_EAPOL)
4384 		rate = tp->mgmtrate;
4385 	else {
4386 		/* XXX pass pktlen */
4387 		(void) ieee80211_ratectl_rate(ni, NULL, 0);
4388 		rate = ni->ni_txrate;
4389 	}
4390 
4391 	/* Encrypt the frame if need be. */
4392 	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
4393 		/* Retrieve key for TX. */
4394 		k = ieee80211_crypto_encap(ni, m);
4395 		if (k == NULL) {
4396 			m_freem(m);
4397 			return ENOBUFS;
4398 		}
4399 		/* 802.11 header may have moved. */
4400 		wh = mtod(m, struct ieee80211_frame *);
4401 	}
4402 	totlen = m->m_pkthdr.len;
4403 
4404 	if (ieee80211_radiotap_active_vap(vap)) {
4405 		struct iwn_tx_radiotap_header *tap = &sc->sc_txtap;
4406 
4407 		tap->wt_flags = 0;
4408 		tap->wt_rate = rate;
4409 		if (k != NULL)
4410 			tap->wt_flags |= IEEE80211_RADIOTAP_F_WEP;
4411 
4412 		ieee80211_radiotap_tx(vap, m);
4413 	}
4414 
4415 	/* Prepare TX firmware command. */
4416 	cmd = &ring->cmd[ring->cur];
4417 	cmd->code = IWN_CMD_TX_DATA;
4418 	cmd->flags = 0;
4419 	cmd->qid = ring->qid;
4420 	cmd->idx = ring->cur;
4421 
4422 	tx = (struct iwn_cmd_data *)cmd->data;
4423 	/* NB: No need to clear tx, all fields are reinitialized here. */
4424 	tx->scratch = 0;	/* clear "scratch" area */
4425 
4426 	flags = 0;
4427 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
4428 		/* Unicast frame, check if an ACK is expected. */
4429 		if (!qos || (qos & IEEE80211_QOS_ACKPOLICY) !=
4430 		    IEEE80211_QOS_ACKPOLICY_NOACK)
4431 			flags |= IWN_TX_NEED_ACK;
4432 	}
4433 	if ((wh->i_fc[0] &
4434 	    (IEEE80211_FC0_TYPE_MASK | IEEE80211_FC0_SUBTYPE_MASK)) ==
4435 	    (IEEE80211_FC0_TYPE_CTL | IEEE80211_FC0_SUBTYPE_BAR))
4436 		flags |= IWN_TX_IMM_BA;		/* Cannot happen yet. */
4437 
4438 	if (wh->i_fc[1] & IEEE80211_FC1_MORE_FRAG)
4439 		flags |= IWN_TX_MORE_FRAG;	/* Cannot happen yet. */
4440 
4441 	/* Check if frame must be protected using RTS/CTS or CTS-to-self. */
4442 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
4443 		/* NB: Group frames are sent using CCK in 802.11b/g. */
4444 		if (totlen + IEEE80211_CRC_LEN > vap->iv_rtsthreshold) {
4445 			flags |= IWN_TX_NEED_RTS;
4446 		} else if (iwn_check_rate_needs_protection(sc, vap, rate)) {
4447 			if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
4448 				flags |= IWN_TX_NEED_CTS;
4449 			else if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
4450 				flags |= IWN_TX_NEED_RTS;
4451 		} else if ((rate & IEEE80211_RATE_MCS) &&
4452 			(ic->ic_htprotmode == IEEE80211_PROT_RTSCTS)) {
4453 			flags |= IWN_TX_NEED_RTS;
4454 		}
4455 
4456 		/* XXX HT protection? */
4457 
4458 		if (flags & (IWN_TX_NEED_RTS | IWN_TX_NEED_CTS)) {
4459 			if (sc->hw_type != IWN_HW_REV_TYPE_4965) {
4460 				/* 5000 autoselects RTS/CTS or CTS-to-self. */
4461 				flags &= ~(IWN_TX_NEED_RTS | IWN_TX_NEED_CTS);
4462 				flags |= IWN_TX_NEED_PROTECTION;
4463 			} else
4464 				flags |= IWN_TX_FULL_TXOP;
4465 		}
4466 	}
4467 
4468 	if (IEEE80211_IS_MULTICAST(wh->i_addr1) ||
4469 	    type != IEEE80211_FC0_TYPE_DATA)
4470 		tx->id = sc->broadcast_id;
4471 	else
4472 		tx->id = wn->id;
4473 
4474 	if (type == IEEE80211_FC0_TYPE_MGT) {
4475 		uint8_t subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
4476 
4477 		/* Tell HW to set timestamp in probe responses. */
4478 		if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
4479 			flags |= IWN_TX_INSERT_TSTAMP;
4480 		if (subtype == IEEE80211_FC0_SUBTYPE_ASSOC_REQ ||
4481 		    subtype == IEEE80211_FC0_SUBTYPE_REASSOC_REQ)
4482 			tx->timeout = htole16(3);
4483 		else
4484 			tx->timeout = htole16(2);
4485 	} else
4486 		tx->timeout = htole16(0);
4487 
4488 	if (hdrlen & 3) {
4489 		/* First segment length must be a multiple of 4. */
4490 		flags |= IWN_TX_NEED_PADDING;
4491 		pad = 4 - (hdrlen & 3);
4492 	} else
4493 		pad = 0;
4494 
4495 	tx->len = htole16(totlen);
4496 	tx->tid = tid;
4497 	tx->rts_ntries = 60;
4498 	tx->data_ntries = 15;
4499 	tx->lifetime = htole32(IWN_LIFETIME_INFINITE);
4500 	tx->rate = iwn_rate_to_plcp(sc, ni, rate);
4501 	if (tx->id == sc->broadcast_id) {
4502 		/* Group or management frame. */
4503 		tx->linkq = 0;
4504 	} else {
4505 		tx->linkq = iwn_tx_rate_to_linkq_offset(sc, ni, rate);
4506 		flags |= IWN_TX_LINKQ;	/* enable MRR */
4507 	}
4508 
4509 	/* Set physical address of "scratch area". */
4510 	tx->loaddr = htole32(IWN_LOADDR(data->scratch_paddr));
4511 	tx->hiaddr = IWN_HIADDR(data->scratch_paddr);
4512 
4513 	/* Copy 802.11 header in TX command. */
4514 	memcpy((uint8_t *)(tx + 1), wh, hdrlen);
4515 
4516 	/* Trim 802.11 header. */
4517 	m_adj(m, hdrlen);
4518 	tx->security = 0;
4519 	tx->flags = htole32(flags);
4520 
4521 	error = bus_dmamap_load_mbuf_sg(ring->data_dmat, data->map, m, segs,
4522 	    &nsegs, BUS_DMA_NOWAIT);
4523 	if (error != 0) {
4524 		if (error != EFBIG) {
4525 			device_printf(sc->sc_dev,
4526 			    "%s: can't map mbuf (error %d)\n", __func__, error);
4527 			m_freem(m);
4528 			return error;
4529 		}
4530 		/* Too many DMA segments, linearize mbuf. */
4531 		m1 = m_collapse(m, M_NOWAIT, IWN_MAX_SCATTER - 1);
4532 		if (m1 == NULL) {
4533 			device_printf(sc->sc_dev,
4534 			    "%s: could not defrag mbuf\n", __func__);
4535 			m_freem(m);
4536 			return ENOBUFS;
4537 		}
4538 		m = m1;
4539 
4540 		error = bus_dmamap_load_mbuf_sg(ring->data_dmat, data->map, m,
4541 		    segs, &nsegs, BUS_DMA_NOWAIT);
4542 		if (error != 0) {
4543 			device_printf(sc->sc_dev,
4544 			    "%s: can't map mbuf (error %d)\n", __func__, error);
4545 			m_freem(m);
4546 			return error;
4547 		}
4548 	}
4549 
4550 	data->m = m;
4551 	data->ni = ni;
4552 
4553 	DPRINTF(sc, IWN_DEBUG_XMIT,
4554 	    "%s: qid %d idx %d len %d nsegs %d flags 0x%08x rate 0x%04x plcp 0x%08x\n",
4555 	    __func__,
4556 	    ring->qid,
4557 	    ring->cur,
4558 	    m->m_pkthdr.len,
4559 	    nsegs,
4560 	    flags,
4561 	    rate,
4562 	    tx->rate);
4563 
4564 	/* Fill TX descriptor. */
4565 	desc->nsegs = 1;
4566 	if (m->m_len != 0)
4567 		desc->nsegs += nsegs;
4568 	/* First DMA segment is used by the TX command. */
4569 	desc->segs[0].addr = htole32(IWN_LOADDR(data->cmd_paddr));
4570 	desc->segs[0].len  = htole16(IWN_HIADDR(data->cmd_paddr) |
4571 	    (4 + sizeof (*tx) + hdrlen + pad) << 4);
4572 	/* Other DMA segments are for data payload. */
4573 	seg = &segs[0];
4574 	for (i = 1; i <= nsegs; i++) {
4575 		desc->segs[i].addr = htole32(IWN_LOADDR(seg->ds_addr));
4576 		desc->segs[i].len  = htole16(IWN_HIADDR(seg->ds_addr) |
4577 		    seg->ds_len << 4);
4578 		seg++;
4579 	}
4580 
4581 	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
4582 	bus_dmamap_sync(ring->data_dmat, ring->cmd_dma.map,
4583 	    BUS_DMASYNC_PREWRITE);
4584 	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
4585 	    BUS_DMASYNC_PREWRITE);
4586 
4587 	/* Update TX scheduler. */
4588 	if (ring->qid >= sc->firstaggqueue)
4589 		ops->update_sched(sc, ring->qid, ring->cur, tx->id, totlen);
4590 
4591 	/* Kick TX ring. */
4592 	ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT;
4593 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, ring->qid << 8 | ring->cur);
4594 
4595 	/* Mark TX ring as full if we reach a certain threshold. */
4596 	if (++ring->queued > IWN_TX_RING_HIMARK)
4597 		sc->qfullmsk |= 1 << ring->qid;
4598 
4599 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
4600 
4601 	return 0;
4602 }
4603 
4604 static int
4605 iwn_tx_data_raw(struct iwn_softc *sc, struct mbuf *m,
4606     struct ieee80211_node *ni, const struct ieee80211_bpf_params *params)
4607 {
4608 	struct iwn_ops *ops = &sc->ops;
4609 //	struct ifnet *ifp = sc->sc_ifp;
4610 	struct ieee80211vap *vap = ni->ni_vap;
4611 //	struct ieee80211com *ic = ifp->if_l2com;
4612 	struct iwn_tx_cmd *cmd;
4613 	struct iwn_cmd_data *tx;
4614 	struct ieee80211_frame *wh;
4615 	struct iwn_tx_ring *ring;
4616 	struct iwn_tx_desc *desc;
4617 	struct iwn_tx_data *data;
4618 	struct mbuf *m1;
4619 	bus_dma_segment_t *seg, segs[IWN_MAX_SCATTER];
4620 	uint32_t flags;
4621 	u_int hdrlen;
4622 	int ac, totlen, error, pad, nsegs = 0, i, rate;
4623 	uint8_t type;
4624 
4625 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
4626 
4627 	IWN_LOCK_ASSERT(sc);
4628 
4629 	wh = mtod(m, struct ieee80211_frame *);
4630 	hdrlen = ieee80211_anyhdrsize(wh);
4631 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
4632 
4633 	ac = params->ibp_pri & 3;
4634 
4635 	ring = &sc->txq[ac];
4636 	desc = &ring->desc[ring->cur];
4637 	data = &ring->data[ring->cur];
4638 
4639 	/* Choose a TX rate. */
4640 	rate = params->ibp_rate0;
4641 	totlen = m->m_pkthdr.len;
4642 
4643 	/* Prepare TX firmware command. */
4644 	cmd = &ring->cmd[ring->cur];
4645 	cmd->code = IWN_CMD_TX_DATA;
4646 	cmd->flags = 0;
4647 	cmd->qid = ring->qid;
4648 	cmd->idx = ring->cur;
4649 
4650 	tx = (struct iwn_cmd_data *)cmd->data;
4651 	/* NB: No need to clear tx, all fields are reinitialized here. */
4652 	tx->scratch = 0;	/* clear "scratch" area */
4653 
4654 	flags = 0;
4655 	if ((params->ibp_flags & IEEE80211_BPF_NOACK) == 0)
4656 		flags |= IWN_TX_NEED_ACK;
4657 	if (params->ibp_flags & IEEE80211_BPF_RTS) {
4658 		if (sc->hw_type != IWN_HW_REV_TYPE_4965) {
4659 			/* 5000 autoselects RTS/CTS or CTS-to-self. */
4660 			flags &= ~IWN_TX_NEED_RTS;
4661 			flags |= IWN_TX_NEED_PROTECTION;
4662 		} else
4663 			flags |= IWN_TX_NEED_RTS | IWN_TX_FULL_TXOP;
4664 	}
4665 	if (params->ibp_flags & IEEE80211_BPF_CTS) {
4666 		if (sc->hw_type != IWN_HW_REV_TYPE_4965) {
4667 			/* 5000 autoselects RTS/CTS or CTS-to-self. */
4668 			flags &= ~IWN_TX_NEED_CTS;
4669 			flags |= IWN_TX_NEED_PROTECTION;
4670 		} else
4671 			flags |= IWN_TX_NEED_CTS | IWN_TX_FULL_TXOP;
4672 	}
4673 	if (type == IEEE80211_FC0_TYPE_MGT) {
4674 		uint8_t subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
4675 
4676 		/* Tell HW to set timestamp in probe responses. */
4677 		if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
4678 			flags |= IWN_TX_INSERT_TSTAMP;
4679 
4680 		if (subtype == IEEE80211_FC0_SUBTYPE_ASSOC_REQ ||
4681 		    subtype == IEEE80211_FC0_SUBTYPE_REASSOC_REQ)
4682 			tx->timeout = htole16(3);
4683 		else
4684 			tx->timeout = htole16(2);
4685 	} else
4686 		tx->timeout = htole16(0);
4687 
4688 	if (hdrlen & 3) {
4689 		/* First segment length must be a multiple of 4. */
4690 		flags |= IWN_TX_NEED_PADDING;
4691 		pad = 4 - (hdrlen & 3);
4692 	} else
4693 		pad = 0;
4694 
4695 	if (ieee80211_radiotap_active_vap(vap)) {
4696 		struct iwn_tx_radiotap_header *tap = &sc->sc_txtap;
4697 
4698 		tap->wt_flags = 0;
4699 		tap->wt_rate = rate;
4700 
4701 		ieee80211_radiotap_tx(vap, m);
4702 	}
4703 
4704 	tx->len = htole16(totlen);
4705 	tx->tid = 0;
4706 	tx->id = sc->broadcast_id;
4707 	tx->rts_ntries = params->ibp_try1;
4708 	tx->data_ntries = params->ibp_try0;
4709 	tx->lifetime = htole32(IWN_LIFETIME_INFINITE);
4710 	tx->rate = iwn_rate_to_plcp(sc, ni, rate);
4711 
4712 	/* Group or management frame. */
4713 	tx->linkq = 0;
4714 
4715 	/* Set physical address of "scratch area". */
4716 	tx->loaddr = htole32(IWN_LOADDR(data->scratch_paddr));
4717 	tx->hiaddr = IWN_HIADDR(data->scratch_paddr);
4718 
4719 	/* Copy 802.11 header in TX command. */
4720 	memcpy((uint8_t *)(tx + 1), wh, hdrlen);
4721 
4722 	/* Trim 802.11 header. */
4723 	m_adj(m, hdrlen);
4724 	tx->security = 0;
4725 	tx->flags = htole32(flags);
4726 
4727 	error = bus_dmamap_load_mbuf_sg(ring->data_dmat, data->map, m, segs,
4728 	    &nsegs, BUS_DMA_NOWAIT);
4729 	if (error != 0) {
4730 		if (error != EFBIG) {
4731 			device_printf(sc->sc_dev,
4732 			    "%s: can't map mbuf (error %d)\n", __func__, error);
4733 			m_freem(m);
4734 			return error;
4735 		}
4736 		/* Too many DMA segments, linearize mbuf. */
4737 		m1 = m_collapse(m, M_NOWAIT, IWN_MAX_SCATTER - 1);
4738 		if (m1 == NULL) {
4739 			device_printf(sc->sc_dev,
4740 			    "%s: could not defrag mbuf\n", __func__);
4741 			m_freem(m);
4742 			return ENOBUFS;
4743 		}
4744 		m = m1;
4745 
4746 		error = bus_dmamap_load_mbuf_sg(ring->data_dmat, data->map, m,
4747 		    segs, &nsegs, BUS_DMA_NOWAIT);
4748 		if (error != 0) {
4749 			device_printf(sc->sc_dev,
4750 			    "%s: can't map mbuf (error %d)\n", __func__, error);
4751 			m_freem(m);
4752 			return error;
4753 		}
4754 	}
4755 
4756 	data->m = m;
4757 	data->ni = ni;
4758 
4759 	DPRINTF(sc, IWN_DEBUG_XMIT, "%s: qid %d idx %d len %d nsegs %d\n",
4760 	    __func__, ring->qid, ring->cur, m->m_pkthdr.len, nsegs);
4761 
4762 	/* Fill TX descriptor. */
4763 	desc->nsegs = 1;
4764 	if (m->m_len != 0)
4765 		desc->nsegs += nsegs;
4766 	/* First DMA segment is used by the TX command. */
4767 	desc->segs[0].addr = htole32(IWN_LOADDR(data->cmd_paddr));
4768 	desc->segs[0].len  = htole16(IWN_HIADDR(data->cmd_paddr) |
4769 	    (4 + sizeof (*tx) + hdrlen + pad) << 4);
4770 	/* Other DMA segments are for data payload. */
4771 	seg = &segs[0];
4772 	for (i = 1; i <= nsegs; i++) {
4773 		desc->segs[i].addr = htole32(IWN_LOADDR(seg->ds_addr));
4774 		desc->segs[i].len  = htole16(IWN_HIADDR(seg->ds_addr) |
4775 		    seg->ds_len << 4);
4776 		seg++;
4777 	}
4778 
4779 	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
4780 	bus_dmamap_sync(ring->data_dmat, ring->cmd_dma.map,
4781 	    BUS_DMASYNC_PREWRITE);
4782 	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
4783 	    BUS_DMASYNC_PREWRITE);
4784 
4785 	/* Update TX scheduler. */
4786 	if (ring->qid >= sc->firstaggqueue)
4787 		ops->update_sched(sc, ring->qid, ring->cur, tx->id, totlen);
4788 
4789 	/* Kick TX ring. */
4790 	ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT;
4791 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, ring->qid << 8 | ring->cur);
4792 
4793 	/* Mark TX ring as full if we reach a certain threshold. */
4794 	if (++ring->queued > IWN_TX_RING_HIMARK)
4795 		sc->qfullmsk |= 1 << ring->qid;
4796 
4797 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
4798 
4799 	return 0;
4800 }
4801 
4802 static int
4803 iwn_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
4804     const struct ieee80211_bpf_params *params)
4805 {
4806 	struct ieee80211com *ic = ni->ni_ic;
4807 	struct ifnet *ifp = ic->ic_ifp;
4808 	struct iwn_softc *sc = ifp->if_softc;
4809 	int error = 0;
4810 
4811 	DPRINTF(sc, IWN_DEBUG_XMIT | IWN_DEBUG_TRACE, "->%s begin\n", __func__);
4812 
4813 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
4814 		ieee80211_free_node(ni);
4815 		m_freem(m);
4816 		return ENETDOWN;
4817 	}
4818 
4819 	IWN_LOCK(sc);
4820 	if (params == NULL) {
4821 		/*
4822 		 * Legacy path; interpret frame contents to decide
4823 		 * precisely how to send the frame.
4824 		 */
4825 		error = iwn_tx_data(sc, m, ni);
4826 	} else {
4827 		/*
4828 		 * Caller supplied explicit parameters to use in
4829 		 * sending the frame.
4830 		 */
4831 		error = iwn_tx_data_raw(sc, m, ni, params);
4832 	}
4833 	if (error != 0) {
4834 		/* NB: m is reclaimed on tx failure */
4835 		ieee80211_free_node(ni);
4836 		if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
4837 	} else
4838 		sc->sc_tx_timer = 5;
4839 
4840 	IWN_UNLOCK(sc);
4841 
4842 	DPRINTF(sc, IWN_DEBUG_TRACE | IWN_DEBUG_XMIT, "->%s: end\n",__func__);
4843 
4844 	return error;
4845 }
4846 
4847 static void
4848 iwn_start(struct ifnet *ifp)
4849 {
4850 	struct iwn_softc *sc = ifp->if_softc;
4851 
4852 	IWN_LOCK(sc);
4853 	iwn_start_locked(ifp);
4854 	IWN_UNLOCK(sc);
4855 }
4856 
4857 static void
4858 iwn_start_locked(struct ifnet *ifp)
4859 {
4860 	struct iwn_softc *sc = ifp->if_softc;
4861 	struct ieee80211_node *ni;
4862 	struct mbuf *m;
4863 
4864 	IWN_LOCK_ASSERT(sc);
4865 
4866 	DPRINTF(sc, IWN_DEBUG_XMIT, "%s: called\n", __func__);
4867 
4868 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 ||
4869 	    (ifp->if_drv_flags & IFF_DRV_OACTIVE))
4870 		return;
4871 
4872 	for (;;) {
4873 		if (sc->qfullmsk != 0) {
4874 			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
4875 			break;
4876 		}
4877 		IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
4878 		if (m == NULL)
4879 			break;
4880 		ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
4881 		if (iwn_tx_data(sc, m, ni) != 0) {
4882 			ieee80211_free_node(ni);
4883 			if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
4884 		} else
4885 			sc->sc_tx_timer = 5;
4886 	}
4887 
4888 	DPRINTF(sc, IWN_DEBUG_XMIT, "%s: done\n", __func__);
4889 }
4890 
4891 static void
4892 iwn_watchdog(void *arg)
4893 {
4894 	struct iwn_softc *sc = arg;
4895 	struct ifnet *ifp = sc->sc_ifp;
4896 	struct ieee80211com *ic = ifp->if_l2com;
4897 
4898 	IWN_LOCK_ASSERT(sc);
4899 
4900 	KASSERT(ifp->if_drv_flags & IFF_DRV_RUNNING, ("not running"));
4901 
4902 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
4903 
4904 	if (sc->sc_tx_timer > 0) {
4905 		if (--sc->sc_tx_timer == 0) {
4906 			if_printf(ifp, "device timeout\n");
4907 			ieee80211_runtask(ic, &sc->sc_reinit_task);
4908 			return;
4909 		}
4910 	}
4911 	callout_reset(&sc->watchdog_to, hz, iwn_watchdog, sc);
4912 }
4913 
4914 static int
4915 iwn_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
4916 {
4917 	struct iwn_softc *sc = ifp->if_softc;
4918 	struct ieee80211com *ic = ifp->if_l2com;
4919 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
4920 	struct ifreq *ifr = (struct ifreq *) data;
4921 	int error = 0, startall = 0, stop = 0;
4922 
4923 	switch (cmd) {
4924 	case SIOCGIFADDR:
4925 		error = ether_ioctl(ifp, cmd, data);
4926 		break;
4927 	case SIOCSIFFLAGS:
4928 		IWN_LOCK(sc);
4929 		if (ifp->if_flags & IFF_UP) {
4930 			if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
4931 				iwn_init_locked(sc);
4932 				if (IWN_READ(sc, IWN_GP_CNTRL) & IWN_GP_CNTRL_RFKILL)
4933 					startall = 1;
4934 				else
4935 					stop = 1;
4936 			}
4937 		} else {
4938 			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
4939 				iwn_stop_locked(sc);
4940 		}
4941 		IWN_UNLOCK(sc);
4942 		if (startall)
4943 			ieee80211_start_all(ic);
4944 		else if (vap != NULL && stop)
4945 			ieee80211_stop(vap);
4946 		break;
4947 	case SIOCGIFMEDIA:
4948 		error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
4949 		break;
4950 	case SIOCGIWNSTATS:
4951 		IWN_LOCK(sc);
4952 		/* XXX validate permissions/memory/etc? */
4953 		error = copyout(&sc->last_stat, ifr->ifr_data,
4954 		    sizeof(struct iwn_stats));
4955 		IWN_UNLOCK(sc);
4956 		break;
4957 	case SIOCZIWNSTATS:
4958 		IWN_LOCK(sc);
4959 		memset(&sc->last_stat, 0, sizeof(struct iwn_stats));
4960 		IWN_UNLOCK(sc);
4961 		break;
4962 	default:
4963 		error = EINVAL;
4964 		break;
4965 	}
4966 	return error;
4967 }
4968 
4969 /*
4970  * Send a command to the firmware.
4971  */
4972 static int
4973 iwn_cmd(struct iwn_softc *sc, int code, const void *buf, int size, int async)
4974 {
4975 	struct iwn_tx_ring *ring;
4976 	struct iwn_tx_desc *desc;
4977 	struct iwn_tx_data *data;
4978 	struct iwn_tx_cmd *cmd;
4979 	struct mbuf *m;
4980 	bus_addr_t paddr;
4981 	int totlen, error;
4982 	int cmd_queue_num;
4983 
4984 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
4985 
4986 	if (async == 0)
4987 		IWN_LOCK_ASSERT(sc);
4988 
4989 	if (sc->sc_flags & IWN_FLAG_PAN_SUPPORT)
4990 		cmd_queue_num = IWN_PAN_CMD_QUEUE;
4991 	else
4992 		cmd_queue_num = IWN_CMD_QUEUE_NUM;
4993 
4994 	ring = &sc->txq[cmd_queue_num];
4995 	desc = &ring->desc[ring->cur];
4996 	data = &ring->data[ring->cur];
4997 	totlen = 4 + size;
4998 
4999 	if (size > sizeof cmd->data) {
5000 		/* Command is too large to fit in a descriptor. */
5001 		if (totlen > MCLBYTES)
5002 			return EINVAL;
5003 		m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, MJUMPAGESIZE);
5004 		if (m == NULL)
5005 			return ENOMEM;
5006 		cmd = mtod(m, struct iwn_tx_cmd *);
5007 		error = bus_dmamap_load(ring->data_dmat, data->map, cmd,
5008 		    totlen, iwn_dma_map_addr, &paddr, BUS_DMA_NOWAIT);
5009 		if (error != 0) {
5010 			m_freem(m);
5011 			return error;
5012 		}
5013 		data->m = m;
5014 	} else {
5015 		cmd = &ring->cmd[ring->cur];
5016 		paddr = data->cmd_paddr;
5017 	}
5018 
5019 	cmd->code = code;
5020 	cmd->flags = 0;
5021 	cmd->qid = ring->qid;
5022 	cmd->idx = ring->cur;
5023 	memcpy(cmd->data, buf, size);
5024 
5025 	desc->nsegs = 1;
5026 	desc->segs[0].addr = htole32(IWN_LOADDR(paddr));
5027 	desc->segs[0].len  = htole16(IWN_HIADDR(paddr) | totlen << 4);
5028 
5029 	DPRINTF(sc, IWN_DEBUG_CMD, "%s: %s (0x%x) flags %d qid %d idx %d\n",
5030 	    __func__, iwn_intr_str(cmd->code), cmd->code,
5031 	    cmd->flags, cmd->qid, cmd->idx);
5032 
5033 	if (size > sizeof cmd->data) {
5034 		bus_dmamap_sync(ring->data_dmat, data->map,
5035 		    BUS_DMASYNC_PREWRITE);
5036 	} else {
5037 		bus_dmamap_sync(ring->data_dmat, ring->cmd_dma.map,
5038 		    BUS_DMASYNC_PREWRITE);
5039 	}
5040 	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
5041 	    BUS_DMASYNC_PREWRITE);
5042 
5043 	/* Kick command ring. */
5044 	ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT;
5045 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, ring->qid << 8 | ring->cur);
5046 
5047 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
5048 
5049 	return async ? 0 : msleep(desc, &sc->sc_mtx, PCATCH, "iwncmd", hz);
5050 }
5051 
5052 static int
5053 iwn4965_add_node(struct iwn_softc *sc, struct iwn_node_info *node, int async)
5054 {
5055 	struct iwn4965_node_info hnode;
5056 	caddr_t src, dst;
5057 
5058 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5059 
5060 	/*
5061 	 * We use the node structure for 5000 Series internally (it is
5062 	 * a superset of the one for 4965AGN). We thus copy the common
5063 	 * fields before sending the command.
5064 	 */
5065 	src = (caddr_t)node;
5066 	dst = (caddr_t)&hnode;
5067 	memcpy(dst, src, 48);
5068 	/* Skip TSC, RX MIC and TX MIC fields from ``src''. */
5069 	memcpy(dst + 48, src + 72, 20);
5070 	return iwn_cmd(sc, IWN_CMD_ADD_NODE, &hnode, sizeof hnode, async);
5071 }
5072 
5073 static int
5074 iwn5000_add_node(struct iwn_softc *sc, struct iwn_node_info *node, int async)
5075 {
5076 
5077 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5078 
5079 	/* Direct mapping. */
5080 	return iwn_cmd(sc, IWN_CMD_ADD_NODE, node, sizeof (*node), async);
5081 }
5082 
5083 static int
5084 iwn_set_link_quality(struct iwn_softc *sc, struct ieee80211_node *ni)
5085 {
5086 #define	RV(v)	((v) & IEEE80211_RATE_VAL)
5087 	struct iwn_node *wn = (void *)ni;
5088 	struct ieee80211_rateset *rs;
5089 	struct iwn_cmd_link_quality linkq;
5090 	int i, rate, txrate;
5091 	int is_11n;
5092 
5093 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
5094 
5095 	memset(&linkq, 0, sizeof linkq);
5096 	linkq.id = wn->id;
5097 	linkq.antmsk_1stream = iwn_get_1stream_tx_antmask(sc);
5098 	linkq.antmsk_2stream = iwn_get_2stream_tx_antmask(sc);
5099 
5100 	linkq.ampdu_max = 32;		/* XXX negotiated? */
5101 	linkq.ampdu_threshold = 3;
5102 	linkq.ampdu_limit = htole16(4000);	/* 4ms */
5103 
5104 	DPRINTF(sc, IWN_DEBUG_XMIT,
5105 	    "%s: 1stream antenna=0x%02x, 2stream antenna=0x%02x, ntxstreams=%d\n",
5106 	    __func__,
5107 	    linkq.antmsk_1stream,
5108 	    linkq.antmsk_2stream,
5109 	    sc->ntxchains);
5110 
5111 	/*
5112 	 * Are we using 11n rates? Ensure the channel is
5113 	 * 11n _and_ we have some 11n rates, or don't
5114 	 * try.
5115 	 */
5116 	if (IEEE80211_IS_CHAN_HT(ni->ni_chan) && ni->ni_htrates.rs_nrates > 0) {
5117 		rs = (struct ieee80211_rateset *) &ni->ni_htrates;
5118 		is_11n = 1;
5119 	} else {
5120 		rs = &ni->ni_rates;
5121 		is_11n = 0;
5122 	}
5123 
5124 	/* Start at highest available bit-rate. */
5125 	/*
5126 	 * XXX this is all very dirty!
5127 	 */
5128 	if (is_11n)
5129 		txrate = ni->ni_htrates.rs_nrates - 1;
5130 	else
5131 		txrate = rs->rs_nrates - 1;
5132 	for (i = 0; i < IWN_MAX_TX_RETRIES; i++) {
5133 		uint32_t plcp;
5134 
5135 		/*
5136 		 * XXX TODO: ensure the last two slots are the two lowest
5137 		 * rate entries, just for now.
5138 		 */
5139 		if (i == 14 || i == 15)
5140 			txrate = 0;
5141 
5142 		if (is_11n)
5143 			rate = IEEE80211_RATE_MCS | rs->rs_rates[txrate];
5144 		else
5145 			rate = RV(rs->rs_rates[txrate]);
5146 
5147 		/* Do rate -> PLCP config mapping */
5148 		plcp = iwn_rate_to_plcp(sc, ni, rate);
5149 		linkq.retry[i] = plcp;
5150 		DPRINTF(sc, IWN_DEBUG_XMIT,
5151 		    "%s: i=%d, txrate=%d, rate=0x%02x, plcp=0x%08x\n",
5152 		    __func__,
5153 		    i,
5154 		    txrate,
5155 		    rate,
5156 		    le32toh(plcp));
5157 
5158 		/*
5159 		 * The mimo field is an index into the table which
5160 		 * indicates the first index where it and subsequent entries
5161 		 * will not be using MIMO.
5162 		 *
5163 		 * Since we're filling linkq from 0..15 and we're filling
5164 		 * from the higest MCS rates to the lowest rates, if we
5165 		 * _are_ doing a dual-stream rate, set mimo to idx+1 (ie,
5166 		 * the next entry.)  That way if the next entry is a non-MIMO
5167 		 * entry, we're already pointing at it.
5168 		 */
5169 		if ((le32toh(plcp) & IWN_RFLAG_MCS) &&
5170 		    RV(le32toh(plcp)) > 7)
5171 			linkq.mimo = i + 1;
5172 
5173 		/* Next retry at immediate lower bit-rate. */
5174 		if (txrate > 0)
5175 			txrate--;
5176 	}
5177 	/*
5178 	 * If we reached the end of the list and indeed we hit
5179 	 * all MIMO rates (eg 5300 doing MCS23-15) then yes,
5180 	 * set mimo to 15.  Setting it to 16 panics the firmware.
5181 	 */
5182 	if (linkq.mimo > 15)
5183 		linkq.mimo = 15;
5184 
5185 	DPRINTF(sc, IWN_DEBUG_XMIT, "%s: mimo = %d\n", __func__, linkq.mimo);
5186 
5187 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
5188 
5189 	return iwn_cmd(sc, IWN_CMD_LINK_QUALITY, &linkq, sizeof linkq, 1);
5190 #undef	RV
5191 }
5192 
5193 /*
5194  * Broadcast node is used to send group-addressed and management frames.
5195  */
5196 static int
5197 iwn_add_broadcast_node(struct iwn_softc *sc, int async)
5198 {
5199 	struct iwn_ops *ops = &sc->ops;
5200 	struct ifnet *ifp = sc->sc_ifp;
5201 	struct ieee80211com *ic = ifp->if_l2com;
5202 	struct iwn_node_info node;
5203 	struct iwn_cmd_link_quality linkq;
5204 	uint8_t txant;
5205 	int i, error;
5206 
5207 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
5208 
5209 	sc->rxon = &sc->rx_on[IWN_RXON_BSS_CTX];
5210 
5211 	memset(&node, 0, sizeof node);
5212 	IEEE80211_ADDR_COPY(node.macaddr, ifp->if_broadcastaddr);
5213 	node.id = sc->broadcast_id;
5214 	DPRINTF(sc, IWN_DEBUG_RESET, "%s: adding broadcast node\n", __func__);
5215 	if ((error = ops->add_node(sc, &node, async)) != 0)
5216 		return error;
5217 
5218 	/* Use the first valid TX antenna. */
5219 	txant = IWN_LSB(sc->txchainmask);
5220 
5221 	memset(&linkq, 0, sizeof linkq);
5222 	linkq.id = sc->broadcast_id;
5223 	linkq.antmsk_1stream = iwn_get_1stream_tx_antmask(sc);
5224 	linkq.antmsk_2stream = iwn_get_2stream_tx_antmask(sc);
5225 	linkq.ampdu_max = 64;
5226 	linkq.ampdu_threshold = 3;
5227 	linkq.ampdu_limit = htole16(4000);	/* 4ms */
5228 
5229 	/* Use lowest mandatory bit-rate. */
5230 	/* XXX rate table lookup? */
5231 	if (IEEE80211_IS_CHAN_5GHZ(ic->ic_curchan))
5232 		linkq.retry[0] = htole32(0xd);
5233 	else
5234 		linkq.retry[0] = htole32(10 | IWN_RFLAG_CCK);
5235 	linkq.retry[0] |= htole32(IWN_RFLAG_ANT(txant));
5236 	/* Use same bit-rate for all TX retries. */
5237 	for (i = 1; i < IWN_MAX_TX_RETRIES; i++) {
5238 		linkq.retry[i] = linkq.retry[0];
5239 	}
5240 
5241 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
5242 
5243 	return iwn_cmd(sc, IWN_CMD_LINK_QUALITY, &linkq, sizeof linkq, async);
5244 }
5245 
5246 static int
5247 iwn_updateedca(struct ieee80211com *ic)
5248 {
5249 #define IWN_EXP2(x)	((1 << (x)) - 1)	/* CWmin = 2^ECWmin - 1 */
5250 	struct iwn_softc *sc = ic->ic_ifp->if_softc;
5251 	struct iwn_edca_params cmd;
5252 	int aci;
5253 
5254 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
5255 
5256 	memset(&cmd, 0, sizeof cmd);
5257 	cmd.flags = htole32(IWN_EDCA_UPDATE);
5258 	for (aci = 0; aci < WME_NUM_AC; aci++) {
5259 		const struct wmeParams *ac =
5260 		    &ic->ic_wme.wme_chanParams.cap_wmeParams[aci];
5261 		cmd.ac[aci].aifsn = ac->wmep_aifsn;
5262 		cmd.ac[aci].cwmin = htole16(IWN_EXP2(ac->wmep_logcwmin));
5263 		cmd.ac[aci].cwmax = htole16(IWN_EXP2(ac->wmep_logcwmax));
5264 		cmd.ac[aci].txoplimit =
5265 		    htole16(IEEE80211_TXOP_TO_US(ac->wmep_txopLimit));
5266 	}
5267 	IEEE80211_UNLOCK(ic);
5268 	IWN_LOCK(sc);
5269 	(void)iwn_cmd(sc, IWN_CMD_EDCA_PARAMS, &cmd, sizeof cmd, 1);
5270 	IWN_UNLOCK(sc);
5271 	IEEE80211_LOCK(ic);
5272 
5273 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
5274 
5275 	return 0;
5276 #undef IWN_EXP2
5277 }
5278 
5279 static void
5280 iwn_update_mcast(struct ifnet *ifp)
5281 {
5282 	/* Ignore */
5283 }
5284 
5285 static void
5286 iwn_set_led(struct iwn_softc *sc, uint8_t which, uint8_t off, uint8_t on)
5287 {
5288 	struct iwn_cmd_led led;
5289 
5290 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5291 
5292 #if 0
5293 	/* XXX don't set LEDs during scan? */
5294 	if (sc->sc_is_scanning)
5295 		return;
5296 #endif
5297 
5298 	/* Clear microcode LED ownership. */
5299 	IWN_CLRBITS(sc, IWN_LED, IWN_LED_BSM_CTRL);
5300 
5301 	led.which = which;
5302 	led.unit = htole32(10000);	/* on/off in unit of 100ms */
5303 	led.off = off;
5304 	led.on = on;
5305 	(void)iwn_cmd(sc, IWN_CMD_SET_LED, &led, sizeof led, 1);
5306 }
5307 
5308 /*
5309  * Set the critical temperature at which the firmware will stop the radio
5310  * and notify us.
5311  */
5312 static int
5313 iwn_set_critical_temp(struct iwn_softc *sc)
5314 {
5315 	struct iwn_critical_temp crit;
5316 	int32_t temp;
5317 
5318 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5319 
5320 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_CTEMP_STOP_RF);
5321 
5322 	if (sc->hw_type == IWN_HW_REV_TYPE_5150)
5323 		temp = (IWN_CTOK(110) - sc->temp_off) * -5;
5324 	else if (sc->hw_type == IWN_HW_REV_TYPE_4965)
5325 		temp = IWN_CTOK(110);
5326 	else
5327 		temp = 110;
5328 	memset(&crit, 0, sizeof crit);
5329 	crit.tempR = htole32(temp);
5330 	DPRINTF(sc, IWN_DEBUG_RESET, "setting critical temp to %d\n", temp);
5331 	return iwn_cmd(sc, IWN_CMD_SET_CRITICAL_TEMP, &crit, sizeof crit, 0);
5332 }
5333 
5334 static int
5335 iwn_set_timing(struct iwn_softc *sc, struct ieee80211_node *ni)
5336 {
5337 	struct iwn_cmd_timing cmd;
5338 	uint64_t val, mod;
5339 
5340 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5341 
5342 	memset(&cmd, 0, sizeof cmd);
5343 	memcpy(&cmd.tstamp, ni->ni_tstamp.data, sizeof (uint64_t));
5344 	cmd.bintval = htole16(ni->ni_intval);
5345 	cmd.lintval = htole16(10);
5346 
5347 	/* Compute remaining time until next beacon. */
5348 	val = (uint64_t)ni->ni_intval * IEEE80211_DUR_TU;
5349 	mod = le64toh(cmd.tstamp) % val;
5350 	cmd.binitval = htole32((uint32_t)(val - mod));
5351 
5352 	DPRINTF(sc, IWN_DEBUG_RESET, "timing bintval=%u tstamp=%ju, init=%u\n",
5353 	    ni->ni_intval, le64toh(cmd.tstamp), (uint32_t)(val - mod));
5354 
5355 	return iwn_cmd(sc, IWN_CMD_TIMING, &cmd, sizeof cmd, 1);
5356 }
5357 
5358 static void
5359 iwn4965_power_calibration(struct iwn_softc *sc, int temp)
5360 {
5361 	struct ifnet *ifp = sc->sc_ifp;
5362 	struct ieee80211com *ic = ifp->if_l2com;
5363 
5364 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5365 
5366 	/* Adjust TX power if need be (delta >= 3 degC). */
5367 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: temperature %d->%d\n",
5368 	    __func__, sc->temp, temp);
5369 	if (abs(temp - sc->temp) >= 3) {
5370 		/* Record temperature of last calibration. */
5371 		sc->temp = temp;
5372 		(void)iwn4965_set_txpower(sc, ic->ic_bsschan, 1);
5373 	}
5374 }
5375 
5376 /*
5377  * Set TX power for current channel (each rate has its own power settings).
5378  * This function takes into account the regulatory information from EEPROM,
5379  * the current temperature and the current voltage.
5380  */
5381 static int
5382 iwn4965_set_txpower(struct iwn_softc *sc, struct ieee80211_channel *ch,
5383     int async)
5384 {
5385 /* Fixed-point arithmetic division using a n-bit fractional part. */
5386 #define fdivround(a, b, n)	\
5387 	((((1 << n) * (a)) / (b) + (1 << n) / 2) / (1 << n))
5388 /* Linear interpolation. */
5389 #define interpolate(x, x1, y1, x2, y2, n)	\
5390 	((y1) + fdivround(((int)(x) - (x1)) * ((y2) - (y1)), (x2) - (x1), n))
5391 
5392 	static const int tdiv[IWN_NATTEN_GROUPS] = { 9, 8, 8, 8, 6 };
5393 	struct iwn_ucode_info *uc = &sc->ucode_info;
5394 	struct iwn4965_cmd_txpower cmd;
5395 	struct iwn4965_eeprom_chan_samples *chans;
5396 	const uint8_t *rf_gain, *dsp_gain;
5397 	int32_t vdiff, tdiff;
5398 	int i, c, grp, maxpwr;
5399 	uint8_t chan;
5400 
5401 	sc->rxon = &sc->rx_on[IWN_RXON_BSS_CTX];
5402 	/* Retrieve current channel from last RXON. */
5403 	chan = sc->rxon->chan;
5404 	DPRINTF(sc, IWN_DEBUG_RESET, "setting TX power for channel %d\n",
5405 	    chan);
5406 
5407 	memset(&cmd, 0, sizeof cmd);
5408 	cmd.band = IEEE80211_IS_CHAN_5GHZ(ch) ? 0 : 1;
5409 	cmd.chan = chan;
5410 
5411 	if (IEEE80211_IS_CHAN_5GHZ(ch)) {
5412 		maxpwr   = sc->maxpwr5GHz;
5413 		rf_gain  = iwn4965_rf_gain_5ghz;
5414 		dsp_gain = iwn4965_dsp_gain_5ghz;
5415 	} else {
5416 		maxpwr   = sc->maxpwr2GHz;
5417 		rf_gain  = iwn4965_rf_gain_2ghz;
5418 		dsp_gain = iwn4965_dsp_gain_2ghz;
5419 	}
5420 
5421 	/* Compute voltage compensation. */
5422 	vdiff = ((int32_t)le32toh(uc->volt) - sc->eeprom_voltage) / 7;
5423 	if (vdiff > 0)
5424 		vdiff *= 2;
5425 	if (abs(vdiff) > 2)
5426 		vdiff = 0;
5427 	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
5428 	    "%s: voltage compensation=%d (UCODE=%d, EEPROM=%d)\n",
5429 	    __func__, vdiff, le32toh(uc->volt), sc->eeprom_voltage);
5430 
5431 	/* Get channel attenuation group. */
5432 	if (chan <= 20)		/* 1-20 */
5433 		grp = 4;
5434 	else if (chan <= 43)	/* 34-43 */
5435 		grp = 0;
5436 	else if (chan <= 70)	/* 44-70 */
5437 		grp = 1;
5438 	else if (chan <= 124)	/* 71-124 */
5439 		grp = 2;
5440 	else			/* 125-200 */
5441 		grp = 3;
5442 	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
5443 	    "%s: chan %d, attenuation group=%d\n", __func__, chan, grp);
5444 
5445 	/* Get channel sub-band. */
5446 	for (i = 0; i < IWN_NBANDS; i++)
5447 		if (sc->bands[i].lo != 0 &&
5448 		    sc->bands[i].lo <= chan && chan <= sc->bands[i].hi)
5449 			break;
5450 	if (i == IWN_NBANDS)	/* Can't happen in real-life. */
5451 		return EINVAL;
5452 	chans = sc->bands[i].chans;
5453 	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
5454 	    "%s: chan %d sub-band=%d\n", __func__, chan, i);
5455 
5456 	for (c = 0; c < 2; c++) {
5457 		uint8_t power, gain, temp;
5458 		int maxchpwr, pwr, ridx, idx;
5459 
5460 		power = interpolate(chan,
5461 		    chans[0].num, chans[0].samples[c][1].power,
5462 		    chans[1].num, chans[1].samples[c][1].power, 1);
5463 		gain  = interpolate(chan,
5464 		    chans[0].num, chans[0].samples[c][1].gain,
5465 		    chans[1].num, chans[1].samples[c][1].gain, 1);
5466 		temp  = interpolate(chan,
5467 		    chans[0].num, chans[0].samples[c][1].temp,
5468 		    chans[1].num, chans[1].samples[c][1].temp, 1);
5469 		DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
5470 		    "%s: Tx chain %d: power=%d gain=%d temp=%d\n",
5471 		    __func__, c, power, gain, temp);
5472 
5473 		/* Compute temperature compensation. */
5474 		tdiff = ((sc->temp - temp) * 2) / tdiv[grp];
5475 		DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
5476 		    "%s: temperature compensation=%d (current=%d, EEPROM=%d)\n",
5477 		    __func__, tdiff, sc->temp, temp);
5478 
5479 		for (ridx = 0; ridx <= IWN_RIDX_MAX; ridx++) {
5480 			/* Convert dBm to half-dBm. */
5481 			maxchpwr = sc->maxpwr[chan] * 2;
5482 			if ((ridx / 8) & 1)
5483 				maxchpwr -= 6;	/* MIMO 2T: -3dB */
5484 
5485 			pwr = maxpwr;
5486 
5487 			/* Adjust TX power based on rate. */
5488 			if ((ridx % 8) == 5)
5489 				pwr -= 15;	/* OFDM48: -7.5dB */
5490 			else if ((ridx % 8) == 6)
5491 				pwr -= 17;	/* OFDM54: -8.5dB */
5492 			else if ((ridx % 8) == 7)
5493 				pwr -= 20;	/* OFDM60: -10dB */
5494 			else
5495 				pwr -= 10;	/* Others: -5dB */
5496 
5497 			/* Do not exceed channel max TX power. */
5498 			if (pwr > maxchpwr)
5499 				pwr = maxchpwr;
5500 
5501 			idx = gain - (pwr - power) - tdiff - vdiff;
5502 			if ((ridx / 8) & 1)	/* MIMO */
5503 				idx += (int32_t)le32toh(uc->atten[grp][c]);
5504 
5505 			if (cmd.band == 0)
5506 				idx += 9;	/* 5GHz */
5507 			if (ridx == IWN_RIDX_MAX)
5508 				idx += 5;	/* CCK */
5509 
5510 			/* Make sure idx stays in a valid range. */
5511 			if (idx < 0)
5512 				idx = 0;
5513 			else if (idx > IWN4965_MAX_PWR_INDEX)
5514 				idx = IWN4965_MAX_PWR_INDEX;
5515 
5516 			DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
5517 			    "%s: Tx chain %d, rate idx %d: power=%d\n",
5518 			    __func__, c, ridx, idx);
5519 			cmd.power[ridx].rf_gain[c] = rf_gain[idx];
5520 			cmd.power[ridx].dsp_gain[c] = dsp_gain[idx];
5521 		}
5522 	}
5523 
5524 	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_TXPOW,
5525 	    "%s: set tx power for chan %d\n", __func__, chan);
5526 	return iwn_cmd(sc, IWN_CMD_TXPOWER, &cmd, sizeof cmd, async);
5527 
5528 #undef interpolate
5529 #undef fdivround
5530 }
5531 
5532 static int
5533 iwn5000_set_txpower(struct iwn_softc *sc, struct ieee80211_channel *ch,
5534     int async)
5535 {
5536 	struct iwn5000_cmd_txpower cmd;
5537 	int cmdid;
5538 
5539 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5540 
5541 	/*
5542 	 * TX power calibration is handled automatically by the firmware
5543 	 * for 5000 Series.
5544 	 */
5545 	memset(&cmd, 0, sizeof cmd);
5546 	cmd.global_limit = 2 * IWN5000_TXPOWER_MAX_DBM;	/* 16 dBm */
5547 	cmd.flags = IWN5000_TXPOWER_NO_CLOSED;
5548 	cmd.srv_limit = IWN5000_TXPOWER_AUTO;
5549 	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_XMIT,
5550 	    "%s: setting TX power; rev=%d\n",
5551 	    __func__,
5552 	    IWN_UCODE_API(sc->ucode_rev));
5553 	if (IWN_UCODE_API(sc->ucode_rev) == 1)
5554 		cmdid = IWN_CMD_TXPOWER_DBM_V1;
5555 	else
5556 		cmdid = IWN_CMD_TXPOWER_DBM;
5557 	return iwn_cmd(sc, cmdid, &cmd, sizeof cmd, async);
5558 }
5559 
5560 /*
5561  * Retrieve the maximum RSSI (in dBm) among receivers.
5562  */
5563 static int
5564 iwn4965_get_rssi(struct iwn_softc *sc, struct iwn_rx_stat *stat)
5565 {
5566 	struct iwn4965_rx_phystat *phy = (void *)stat->phybuf;
5567 	uint8_t mask, agc;
5568 	int rssi;
5569 
5570 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5571 
5572 	mask = (le16toh(phy->antenna) >> 4) & IWN_ANT_ABC;
5573 	agc  = (le16toh(phy->agc) >> 7) & 0x7f;
5574 
5575 	rssi = 0;
5576 	if (mask & IWN_ANT_A)
5577 		rssi = MAX(rssi, phy->rssi[0]);
5578 	if (mask & IWN_ANT_B)
5579 		rssi = MAX(rssi, phy->rssi[2]);
5580 	if (mask & IWN_ANT_C)
5581 		rssi = MAX(rssi, phy->rssi[4]);
5582 
5583 	DPRINTF(sc, IWN_DEBUG_RECV,
5584 	    "%s: agc %d mask 0x%x rssi %d %d %d result %d\n", __func__, agc,
5585 	    mask, phy->rssi[0], phy->rssi[2], phy->rssi[4],
5586 	    rssi - agc - IWN_RSSI_TO_DBM);
5587 	return rssi - agc - IWN_RSSI_TO_DBM;
5588 }
5589 
5590 static int
5591 iwn5000_get_rssi(struct iwn_softc *sc, struct iwn_rx_stat *stat)
5592 {
5593 	struct iwn5000_rx_phystat *phy = (void *)stat->phybuf;
5594 	uint8_t agc;
5595 	int rssi;
5596 
5597 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5598 
5599 	agc = (le32toh(phy->agc) >> 9) & 0x7f;
5600 
5601 	rssi = MAX(le16toh(phy->rssi[0]) & 0xff,
5602 		   le16toh(phy->rssi[1]) & 0xff);
5603 	rssi = MAX(le16toh(phy->rssi[2]) & 0xff, rssi);
5604 
5605 	DPRINTF(sc, IWN_DEBUG_RECV,
5606 	    "%s: agc %d rssi %d %d %d result %d\n", __func__, agc,
5607 	    phy->rssi[0], phy->rssi[1], phy->rssi[2],
5608 	    rssi - agc - IWN_RSSI_TO_DBM);
5609 	return rssi - agc - IWN_RSSI_TO_DBM;
5610 }
5611 
5612 /*
5613  * Retrieve the average noise (in dBm) among receivers.
5614  */
5615 static int
5616 iwn_get_noise(const struct iwn_rx_general_stats *stats)
5617 {
5618 	int i, total, nbant, noise;
5619 
5620 	total = nbant = 0;
5621 	for (i = 0; i < 3; i++) {
5622 		if ((noise = le32toh(stats->noise[i]) & 0xff) == 0)
5623 			continue;
5624 		total += noise;
5625 		nbant++;
5626 	}
5627 	/* There should be at least one antenna but check anyway. */
5628 	return (nbant == 0) ? -127 : (total / nbant) - 107;
5629 }
5630 
5631 /*
5632  * Compute temperature (in degC) from last received statistics.
5633  */
5634 static int
5635 iwn4965_get_temperature(struct iwn_softc *sc)
5636 {
5637 	struct iwn_ucode_info *uc = &sc->ucode_info;
5638 	int32_t r1, r2, r3, r4, temp;
5639 
5640 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5641 
5642 	r1 = le32toh(uc->temp[0].chan20MHz);
5643 	r2 = le32toh(uc->temp[1].chan20MHz);
5644 	r3 = le32toh(uc->temp[2].chan20MHz);
5645 	r4 = le32toh(sc->rawtemp);
5646 
5647 	if (r1 == r3)	/* Prevents division by 0 (should not happen). */
5648 		return 0;
5649 
5650 	/* Sign-extend 23-bit R4 value to 32-bit. */
5651 	r4 = ((r4 & 0xffffff) ^ 0x800000) - 0x800000;
5652 	/* Compute temperature in Kelvin. */
5653 	temp = (259 * (r4 - r2)) / (r3 - r1);
5654 	temp = (temp * 97) / 100 + 8;
5655 
5656 	DPRINTF(sc, IWN_DEBUG_ANY, "temperature %dK/%dC\n", temp,
5657 	    IWN_KTOC(temp));
5658 	return IWN_KTOC(temp);
5659 }
5660 
5661 static int
5662 iwn5000_get_temperature(struct iwn_softc *sc)
5663 {
5664 	int32_t temp;
5665 
5666 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5667 
5668 	/*
5669 	 * Temperature is not used by the driver for 5000 Series because
5670 	 * TX power calibration is handled by firmware.
5671 	 */
5672 	temp = le32toh(sc->rawtemp);
5673 	if (sc->hw_type == IWN_HW_REV_TYPE_5150) {
5674 		temp = (temp / -5) + sc->temp_off;
5675 		temp = IWN_KTOC(temp);
5676 	}
5677 	return temp;
5678 }
5679 
5680 /*
5681  * Initialize sensitivity calibration state machine.
5682  */
5683 static int
5684 iwn_init_sensitivity(struct iwn_softc *sc)
5685 {
5686 	struct iwn_ops *ops = &sc->ops;
5687 	struct iwn_calib_state *calib = &sc->calib;
5688 	uint32_t flags;
5689 	int error;
5690 
5691 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5692 
5693 	/* Reset calibration state machine. */
5694 	memset(calib, 0, sizeof (*calib));
5695 	calib->state = IWN_CALIB_STATE_INIT;
5696 	calib->cck_state = IWN_CCK_STATE_HIFA;
5697 	/* Set initial correlation values. */
5698 	calib->ofdm_x1     = sc->limits->min_ofdm_x1;
5699 	calib->ofdm_mrc_x1 = sc->limits->min_ofdm_mrc_x1;
5700 	calib->ofdm_x4     = sc->limits->min_ofdm_x4;
5701 	calib->ofdm_mrc_x4 = sc->limits->min_ofdm_mrc_x4;
5702 	calib->cck_x4      = 125;
5703 	calib->cck_mrc_x4  = sc->limits->min_cck_mrc_x4;
5704 	calib->energy_cck  = sc->limits->energy_cck;
5705 
5706 	/* Write initial sensitivity. */
5707 	if ((error = iwn_send_sensitivity(sc)) != 0)
5708 		return error;
5709 
5710 	/* Write initial gains. */
5711 	if ((error = ops->init_gains(sc)) != 0)
5712 		return error;
5713 
5714 	/* Request statistics at each beacon interval. */
5715 	flags = 0;
5716 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: sending request for statistics\n",
5717 	    __func__);
5718 	return iwn_cmd(sc, IWN_CMD_GET_STATISTICS, &flags, sizeof flags, 1);
5719 }
5720 
5721 /*
5722  * Collect noise and RSSI statistics for the first 20 beacons received
5723  * after association and use them to determine connected antennas and
5724  * to set differential gains.
5725  */
5726 static void
5727 iwn_collect_noise(struct iwn_softc *sc,
5728     const struct iwn_rx_general_stats *stats)
5729 {
5730 	struct iwn_ops *ops = &sc->ops;
5731 	struct iwn_calib_state *calib = &sc->calib;
5732 	struct ifnet *ifp = sc->sc_ifp;
5733 	struct ieee80211com *ic = ifp->if_l2com;
5734 	uint32_t val;
5735 	int i;
5736 
5737 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
5738 
5739 	/* Accumulate RSSI and noise for all 3 antennas. */
5740 	for (i = 0; i < 3; i++) {
5741 		calib->rssi[i] += le32toh(stats->rssi[i]) & 0xff;
5742 		calib->noise[i] += le32toh(stats->noise[i]) & 0xff;
5743 	}
5744 	/* NB: We update differential gains only once after 20 beacons. */
5745 	if (++calib->nbeacons < 20)
5746 		return;
5747 
5748 	/* Determine highest average RSSI. */
5749 	val = MAX(calib->rssi[0], calib->rssi[1]);
5750 	val = MAX(calib->rssi[2], val);
5751 
5752 	/* Determine which antennas are connected. */
5753 	sc->chainmask = sc->rxchainmask;
5754 	for (i = 0; i < 3; i++)
5755 		if (val - calib->rssi[i] > 15 * 20)
5756 			sc->chainmask &= ~(1 << i);
5757 	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_XMIT,
5758 	    "%s: RX chains mask: theoretical=0x%x, actual=0x%x\n",
5759 	    __func__, sc->rxchainmask, sc->chainmask);
5760 
5761 	/* If none of the TX antennas are connected, keep at least one. */
5762 	if ((sc->chainmask & sc->txchainmask) == 0)
5763 		sc->chainmask |= IWN_LSB(sc->txchainmask);
5764 
5765 	(void)ops->set_gains(sc);
5766 	calib->state = IWN_CALIB_STATE_RUN;
5767 
5768 #ifdef notyet
5769 	/* XXX Disable RX chains with no antennas connected. */
5770 	sc->rxon->rxchain = htole16(IWN_RXCHAIN_SEL(sc->chainmask));
5771 	if (sc->sc_is_scanning)
5772 		device_printf(sc->sc_dev,
5773 		    "%s: is_scanning set, before RXON\n",
5774 		    __func__);
5775 	(void)iwn_cmd(sc, IWN_CMD_RXON, sc->rxon, sc->rxonsz, 1);
5776 #endif
5777 
5778 	/* Enable power-saving mode if requested by user. */
5779 	if (ic->ic_flags & IEEE80211_F_PMGTON)
5780 		(void)iwn_set_pslevel(sc, 0, 3, 1);
5781 
5782 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
5783 
5784 }
5785 
5786 static int
5787 iwn4965_init_gains(struct iwn_softc *sc)
5788 {
5789 	struct iwn_phy_calib_gain cmd;
5790 
5791 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5792 
5793 	memset(&cmd, 0, sizeof cmd);
5794 	cmd.code = IWN4965_PHY_CALIB_DIFF_GAIN;
5795 	/* Differential gains initially set to 0 for all 3 antennas. */
5796 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
5797 	    "%s: setting initial differential gains\n", __func__);
5798 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
5799 }
5800 
5801 static int
5802 iwn5000_init_gains(struct iwn_softc *sc)
5803 {
5804 	struct iwn_phy_calib cmd;
5805 
5806 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5807 
5808 	memset(&cmd, 0, sizeof cmd);
5809 	cmd.code = sc->reset_noise_gain;
5810 	cmd.ngroups = 1;
5811 	cmd.isvalid = 1;
5812 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
5813 	    "%s: setting initial differential gains\n", __func__);
5814 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
5815 }
5816 
5817 static int
5818 iwn4965_set_gains(struct iwn_softc *sc)
5819 {
5820 	struct iwn_calib_state *calib = &sc->calib;
5821 	struct iwn_phy_calib_gain cmd;
5822 	int i, delta, noise;
5823 
5824 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5825 
5826 	/* Get minimal noise among connected antennas. */
5827 	noise = INT_MAX;	/* NB: There's at least one antenna. */
5828 	for (i = 0; i < 3; i++)
5829 		if (sc->chainmask & (1 << i))
5830 			noise = MIN(calib->noise[i], noise);
5831 
5832 	memset(&cmd, 0, sizeof cmd);
5833 	cmd.code = IWN4965_PHY_CALIB_DIFF_GAIN;
5834 	/* Set differential gains for connected antennas. */
5835 	for (i = 0; i < 3; i++) {
5836 		if (sc->chainmask & (1 << i)) {
5837 			/* Compute attenuation (in unit of 1.5dB). */
5838 			delta = (noise - (int32_t)calib->noise[i]) / 30;
5839 			/* NB: delta <= 0 */
5840 			/* Limit to [-4.5dB,0]. */
5841 			cmd.gain[i] = MIN(abs(delta), 3);
5842 			if (delta < 0)
5843 				cmd.gain[i] |= 1 << 2;	/* sign bit */
5844 		}
5845 	}
5846 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
5847 	    "setting differential gains Ant A/B/C: %x/%x/%x (%x)\n",
5848 	    cmd.gain[0], cmd.gain[1], cmd.gain[2], sc->chainmask);
5849 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
5850 }
5851 
5852 static int
5853 iwn5000_set_gains(struct iwn_softc *sc)
5854 {
5855 	struct iwn_calib_state *calib = &sc->calib;
5856 	struct iwn_phy_calib_gain cmd;
5857 	int i, ant, div, delta;
5858 
5859 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
5860 
5861 	/* We collected 20 beacons and !=6050 need a 1.5 factor. */
5862 	div = (sc->hw_type == IWN_HW_REV_TYPE_6050) ? 20 : 30;
5863 
5864 	memset(&cmd, 0, sizeof cmd);
5865 	cmd.code = sc->noise_gain;
5866 	cmd.ngroups = 1;
5867 	cmd.isvalid = 1;
5868 	/* Get first available RX antenna as referential. */
5869 	ant = IWN_LSB(sc->rxchainmask);
5870 	/* Set differential gains for other antennas. */
5871 	for (i = ant + 1; i < 3; i++) {
5872 		if (sc->chainmask & (1 << i)) {
5873 			/* The delta is relative to antenna "ant". */
5874 			delta = ((int32_t)calib->noise[ant] -
5875 			    (int32_t)calib->noise[i]) / div;
5876 			/* Limit to [-4.5dB,+4.5dB]. */
5877 			cmd.gain[i - 1] = MIN(abs(delta), 3);
5878 			if (delta < 0)
5879 				cmd.gain[i - 1] |= 1 << 2;	/* sign bit */
5880 		}
5881 	}
5882 	DPRINTF(sc, IWN_DEBUG_CALIBRATE | IWN_DEBUG_XMIT,
5883 	    "setting differential gains Ant B/C: %x/%x (%x)\n",
5884 	    cmd.gain[0], cmd.gain[1], sc->chainmask);
5885 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 1);
5886 }
5887 
5888 /*
5889  * Tune RF RX sensitivity based on the number of false alarms detected
5890  * during the last beacon period.
5891  */
5892 static void
5893 iwn_tune_sensitivity(struct iwn_softc *sc, const struct iwn_rx_stats *stats)
5894 {
5895 #define inc(val, inc, max)			\
5896 	if ((val) < (max)) {			\
5897 		if ((val) < (max) - (inc))	\
5898 			(val) += (inc);		\
5899 		else				\
5900 			(val) = (max);		\
5901 		needs_update = 1;		\
5902 	}
5903 #define dec(val, dec, min)			\
5904 	if ((val) > (min)) {			\
5905 		if ((val) > (min) + (dec))	\
5906 			(val) -= (dec);		\
5907 		else				\
5908 			(val) = (min);		\
5909 		needs_update = 1;		\
5910 	}
5911 
5912 	const struct iwn_sensitivity_limits *limits = sc->limits;
5913 	struct iwn_calib_state *calib = &sc->calib;
5914 	uint32_t val, rxena, fa;
5915 	uint32_t energy[3], energy_min;
5916 	uint8_t noise[3], noise_ref;
5917 	int i, needs_update = 0;
5918 
5919 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
5920 
5921 	/* Check that we've been enabled long enough. */
5922 	if ((rxena = le32toh(stats->general.load)) == 0){
5923 		DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end not so long\n", __func__);
5924 		return;
5925 	}
5926 
5927 	/* Compute number of false alarms since last call for OFDM. */
5928 	fa  = le32toh(stats->ofdm.bad_plcp) - calib->bad_plcp_ofdm;
5929 	fa += le32toh(stats->ofdm.fa) - calib->fa_ofdm;
5930 	fa *= 200 * IEEE80211_DUR_TU;	/* 200TU */
5931 
5932 	if (fa > 50 * rxena) {
5933 		/* High false alarm count, decrease sensitivity. */
5934 		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
5935 		    "%s: OFDM high false alarm count: %u\n", __func__, fa);
5936 		inc(calib->ofdm_x1,     1, limits->max_ofdm_x1);
5937 		inc(calib->ofdm_mrc_x1, 1, limits->max_ofdm_mrc_x1);
5938 		inc(calib->ofdm_x4,     1, limits->max_ofdm_x4);
5939 		inc(calib->ofdm_mrc_x4, 1, limits->max_ofdm_mrc_x4);
5940 
5941 	} else if (fa < 5 * rxena) {
5942 		/* Low false alarm count, increase sensitivity. */
5943 		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
5944 		    "%s: OFDM low false alarm count: %u\n", __func__, fa);
5945 		dec(calib->ofdm_x1,     1, limits->min_ofdm_x1);
5946 		dec(calib->ofdm_mrc_x1, 1, limits->min_ofdm_mrc_x1);
5947 		dec(calib->ofdm_x4,     1, limits->min_ofdm_x4);
5948 		dec(calib->ofdm_mrc_x4, 1, limits->min_ofdm_mrc_x4);
5949 	}
5950 
5951 	/* Compute maximum noise among 3 receivers. */
5952 	for (i = 0; i < 3; i++)
5953 		noise[i] = (le32toh(stats->general.noise[i]) >> 8) & 0xff;
5954 	val = MAX(noise[0], noise[1]);
5955 	val = MAX(noise[2], val);
5956 	/* Insert it into our samples table. */
5957 	calib->noise_samples[calib->cur_noise_sample] = val;
5958 	calib->cur_noise_sample = (calib->cur_noise_sample + 1) % 20;
5959 
5960 	/* Compute maximum noise among last 20 samples. */
5961 	noise_ref = calib->noise_samples[0];
5962 	for (i = 1; i < 20; i++)
5963 		noise_ref = MAX(noise_ref, calib->noise_samples[i]);
5964 
5965 	/* Compute maximum energy among 3 receivers. */
5966 	for (i = 0; i < 3; i++)
5967 		energy[i] = le32toh(stats->general.energy[i]);
5968 	val = MIN(energy[0], energy[1]);
5969 	val = MIN(energy[2], val);
5970 	/* Insert it into our samples table. */
5971 	calib->energy_samples[calib->cur_energy_sample] = val;
5972 	calib->cur_energy_sample = (calib->cur_energy_sample + 1) % 10;
5973 
5974 	/* Compute minimum energy among last 10 samples. */
5975 	energy_min = calib->energy_samples[0];
5976 	for (i = 1; i < 10; i++)
5977 		energy_min = MAX(energy_min, calib->energy_samples[i]);
5978 	energy_min += 6;
5979 
5980 	/* Compute number of false alarms since last call for CCK. */
5981 	fa  = le32toh(stats->cck.bad_plcp) - calib->bad_plcp_cck;
5982 	fa += le32toh(stats->cck.fa) - calib->fa_cck;
5983 	fa *= 200 * IEEE80211_DUR_TU;	/* 200TU */
5984 
5985 	if (fa > 50 * rxena) {
5986 		/* High false alarm count, decrease sensitivity. */
5987 		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
5988 		    "%s: CCK high false alarm count: %u\n", __func__, fa);
5989 		calib->cck_state = IWN_CCK_STATE_HIFA;
5990 		calib->low_fa = 0;
5991 
5992 		if (calib->cck_x4 > 160) {
5993 			calib->noise_ref = noise_ref;
5994 			if (calib->energy_cck > 2)
5995 				dec(calib->energy_cck, 2, energy_min);
5996 		}
5997 		if (calib->cck_x4 < 160) {
5998 			calib->cck_x4 = 161;
5999 			needs_update = 1;
6000 		} else
6001 			inc(calib->cck_x4, 3, limits->max_cck_x4);
6002 
6003 		inc(calib->cck_mrc_x4, 3, limits->max_cck_mrc_x4);
6004 
6005 	} else if (fa < 5 * rxena) {
6006 		/* Low false alarm count, increase sensitivity. */
6007 		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
6008 		    "%s: CCK low false alarm count: %u\n", __func__, fa);
6009 		calib->cck_state = IWN_CCK_STATE_LOFA;
6010 		calib->low_fa++;
6011 
6012 		if (calib->cck_state != IWN_CCK_STATE_INIT &&
6013 		    (((int32_t)calib->noise_ref - (int32_t)noise_ref) > 2 ||
6014 		     calib->low_fa > 100)) {
6015 			inc(calib->energy_cck, 2, limits->min_energy_cck);
6016 			dec(calib->cck_x4,     3, limits->min_cck_x4);
6017 			dec(calib->cck_mrc_x4, 3, limits->min_cck_mrc_x4);
6018 		}
6019 	} else {
6020 		/* Not worth to increase or decrease sensitivity. */
6021 		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
6022 		    "%s: CCK normal false alarm count: %u\n", __func__, fa);
6023 		calib->low_fa = 0;
6024 		calib->noise_ref = noise_ref;
6025 
6026 		if (calib->cck_state == IWN_CCK_STATE_HIFA) {
6027 			/* Previous interval had many false alarms. */
6028 			dec(calib->energy_cck, 8, energy_min);
6029 		}
6030 		calib->cck_state = IWN_CCK_STATE_INIT;
6031 	}
6032 
6033 	if (needs_update)
6034 		(void)iwn_send_sensitivity(sc);
6035 
6036 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
6037 
6038 #undef dec
6039 #undef inc
6040 }
6041 
6042 static int
6043 iwn_send_sensitivity(struct iwn_softc *sc)
6044 {
6045 	struct iwn_calib_state *calib = &sc->calib;
6046 	struct iwn_enhanced_sensitivity_cmd cmd;
6047 	int len;
6048 
6049 	memset(&cmd, 0, sizeof cmd);
6050 	len = sizeof (struct iwn_sensitivity_cmd);
6051 	cmd.which = IWN_SENSITIVITY_WORKTBL;
6052 	/* OFDM modulation. */
6053 	cmd.corr_ofdm_x1       = htole16(calib->ofdm_x1);
6054 	cmd.corr_ofdm_mrc_x1   = htole16(calib->ofdm_mrc_x1);
6055 	cmd.corr_ofdm_x4       = htole16(calib->ofdm_x4);
6056 	cmd.corr_ofdm_mrc_x4   = htole16(calib->ofdm_mrc_x4);
6057 	cmd.energy_ofdm        = htole16(sc->limits->energy_ofdm);
6058 	cmd.energy_ofdm_th     = htole16(62);
6059 	/* CCK modulation. */
6060 	cmd.corr_cck_x4        = htole16(calib->cck_x4);
6061 	cmd.corr_cck_mrc_x4    = htole16(calib->cck_mrc_x4);
6062 	cmd.energy_cck         = htole16(calib->energy_cck);
6063 	/* Barker modulation: use default values. */
6064 	cmd.corr_barker        = htole16(190);
6065 	cmd.corr_barker_mrc    = htole16(sc->limits->barker_mrc);
6066 
6067 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
6068 	    "%s: set sensitivity %d/%d/%d/%d/%d/%d/%d\n", __func__,
6069 	    calib->ofdm_x1, calib->ofdm_mrc_x1, calib->ofdm_x4,
6070 	    calib->ofdm_mrc_x4, calib->cck_x4,
6071 	    calib->cck_mrc_x4, calib->energy_cck);
6072 
6073 	if (!(sc->sc_flags & IWN_FLAG_ENH_SENS))
6074 		goto send;
6075 	/* Enhanced sensitivity settings. */
6076 	len = sizeof (struct iwn_enhanced_sensitivity_cmd);
6077 	cmd.ofdm_det_slope_mrc = htole16(668);
6078 	cmd.ofdm_det_icept_mrc = htole16(4);
6079 	cmd.ofdm_det_slope     = htole16(486);
6080 	cmd.ofdm_det_icept     = htole16(37);
6081 	cmd.cck_det_slope_mrc  = htole16(853);
6082 	cmd.cck_det_icept_mrc  = htole16(4);
6083 	cmd.cck_det_slope      = htole16(476);
6084 	cmd.cck_det_icept      = htole16(99);
6085 send:
6086 	return iwn_cmd(sc, IWN_CMD_SET_SENSITIVITY, &cmd, len, 1);
6087 }
6088 
6089 /*
6090  * Look at the increase of PLCP errors over time; if it exceeds
6091  * a programmed threshold then trigger an RF retune.
6092  */
6093 static void
6094 iwn_check_rx_recovery(struct iwn_softc *sc, struct iwn_stats *rs)
6095 {
6096 	int32_t delta_ofdm, delta_ht, delta_cck;
6097 	struct iwn_calib_state *calib = &sc->calib;
6098 	int delta_ticks, cur_ticks;
6099 	int delta_msec;
6100 	int thresh;
6101 
6102 	/*
6103 	 * Calculate the difference between the current and
6104 	 * previous statistics.
6105 	 */
6106 	delta_cck = le32toh(rs->rx.cck.bad_plcp) - calib->bad_plcp_cck;
6107 	delta_ofdm = le32toh(rs->rx.ofdm.bad_plcp) - calib->bad_plcp_ofdm;
6108 	delta_ht = le32toh(rs->rx.ht.bad_plcp) - calib->bad_plcp_ht;
6109 
6110 	/*
6111 	 * Calculate the delta in time between successive statistics
6112 	 * messages.  Yes, it can roll over; so we make sure that
6113 	 * this doesn't happen.
6114 	 *
6115 	 * XXX go figure out what to do about rollover
6116 	 * XXX go figure out what to do if ticks rolls over to -ve instead!
6117 	 * XXX go stab signed integer overflow undefined-ness in the face.
6118 	 */
6119 	cur_ticks = ticks;
6120 	delta_ticks = cur_ticks - sc->last_calib_ticks;
6121 
6122 	/*
6123 	 * If any are negative, then the firmware likely reset; so just
6124 	 * bail.  We'll pick this up next time.
6125 	 */
6126 	if (delta_cck < 0 || delta_ofdm < 0 || delta_ht < 0 || delta_ticks < 0)
6127 		return;
6128 
6129 	/*
6130 	 * delta_ticks is in ticks; we need to convert it up to milliseconds
6131 	 * so we can do some useful math with it.
6132 	 */
6133 	delta_msec = ticks_to_msecs(delta_ticks);
6134 
6135 	/*
6136 	 * Calculate what our threshold is given the current delta_msec.
6137 	 */
6138 	thresh = sc->base_params->plcp_err_threshold * delta_msec;
6139 
6140 	DPRINTF(sc, IWN_DEBUG_STATE,
6141 	    "%s: time delta: %d; cck=%d, ofdm=%d, ht=%d, total=%d, thresh=%d\n",
6142 	    __func__,
6143 	    delta_msec,
6144 	    delta_cck,
6145 	    delta_ofdm,
6146 	    delta_ht,
6147 	    (delta_msec + delta_cck + delta_ofdm + delta_ht),
6148 	    thresh);
6149 
6150 	/*
6151 	 * If we need a retune, then schedule a single channel scan
6152 	 * to a channel that isn't the currently active one!
6153 	 *
6154 	 * The math from linux iwlwifi:
6155 	 *
6156 	 * if ((delta * 100 / msecs) > threshold)
6157 	 */
6158 	if (thresh > 0 && (delta_cck + delta_ofdm + delta_ht) * 100 > thresh) {
6159 		DPRINTF(sc, IWN_DEBUG_ANY,
6160 		    "%s: PLCP error threshold raw (%d) comparison (%d) "
6161 		    "over limit (%d); retune!\n",
6162 		    __func__,
6163 		    (delta_cck + delta_ofdm + delta_ht),
6164 		    (delta_cck + delta_ofdm + delta_ht) * 100,
6165 		    thresh);
6166 	}
6167 }
6168 
6169 /*
6170  * Set STA mode power saving level (between 0 and 5).
6171  * Level 0 is CAM (Continuously Aware Mode), 5 is for maximum power saving.
6172  */
6173 static int
6174 iwn_set_pslevel(struct iwn_softc *sc, int dtim, int level, int async)
6175 {
6176 	struct iwn_pmgt_cmd cmd;
6177 	const struct iwn_pmgt *pmgt;
6178 	uint32_t max, skip_dtim;
6179 	uint32_t reg;
6180 	int i;
6181 
6182 	DPRINTF(sc, IWN_DEBUG_PWRSAVE,
6183 	    "%s: dtim=%d, level=%d, async=%d\n",
6184 	    __func__,
6185 	    dtim,
6186 	    level,
6187 	    async);
6188 
6189 	/* Select which PS parameters to use. */
6190 	if (dtim <= 2)
6191 		pmgt = &iwn_pmgt[0][level];
6192 	else if (dtim <= 10)
6193 		pmgt = &iwn_pmgt[1][level];
6194 	else
6195 		pmgt = &iwn_pmgt[2][level];
6196 
6197 	memset(&cmd, 0, sizeof cmd);
6198 	if (level != 0)	/* not CAM */
6199 		cmd.flags |= htole16(IWN_PS_ALLOW_SLEEP);
6200 	if (level == 5)
6201 		cmd.flags |= htole16(IWN_PS_FAST_PD);
6202 	/* Retrieve PCIe Active State Power Management (ASPM). */
6203 	reg = pci_read_config(sc->sc_dev, sc->sc_cap_off + 0x10, 1);
6204 	if (!(reg & 0x1))	/* L0s Entry disabled. */
6205 		cmd.flags |= htole16(IWN_PS_PCI_PMGT);
6206 	cmd.rxtimeout = htole32(pmgt->rxtimeout * 1024);
6207 	cmd.txtimeout = htole32(pmgt->txtimeout * 1024);
6208 
6209 	if (dtim == 0) {
6210 		dtim = 1;
6211 		skip_dtim = 0;
6212 	} else
6213 		skip_dtim = pmgt->skip_dtim;
6214 	if (skip_dtim != 0) {
6215 		cmd.flags |= htole16(IWN_PS_SLEEP_OVER_DTIM);
6216 		max = pmgt->intval[4];
6217 		if (max == (uint32_t)-1)
6218 			max = dtim * (skip_dtim + 1);
6219 		else if (max > dtim)
6220 			max = (max / dtim) * dtim;
6221 	} else
6222 		max = dtim;
6223 	for (i = 0; i < 5; i++)
6224 		cmd.intval[i] = htole32(MIN(max, pmgt->intval[i]));
6225 
6226 	DPRINTF(sc, IWN_DEBUG_RESET, "setting power saving level to %d\n",
6227 	    level);
6228 	return iwn_cmd(sc, IWN_CMD_SET_POWER_MODE, &cmd, sizeof cmd, async);
6229 }
6230 
6231 static int
6232 iwn_send_btcoex(struct iwn_softc *sc)
6233 {
6234 	struct iwn_bluetooth cmd;
6235 
6236 	memset(&cmd, 0, sizeof cmd);
6237 	cmd.flags = IWN_BT_COEX_CHAN_ANN | IWN_BT_COEX_BT_PRIO;
6238 	cmd.lead_time = IWN_BT_LEAD_TIME_DEF;
6239 	cmd.max_kill = IWN_BT_MAX_KILL_DEF;
6240 	DPRINTF(sc, IWN_DEBUG_RESET, "%s: configuring bluetooth coexistence\n",
6241 	    __func__);
6242 	return iwn_cmd(sc, IWN_CMD_BT_COEX, &cmd, sizeof(cmd), 0);
6243 }
6244 
6245 static int
6246 iwn_send_advanced_btcoex(struct iwn_softc *sc)
6247 {
6248 	static const uint32_t btcoex_3wire[12] = {
6249 		0xaaaaaaaa, 0xaaaaaaaa, 0xaeaaaaaa, 0xaaaaaaaa,
6250 		0xcc00ff28, 0x0000aaaa, 0xcc00aaaa, 0x0000aaaa,
6251 		0xc0004000, 0x00004000, 0xf0005000, 0xf0005000,
6252 	};
6253 	struct iwn6000_btcoex_config btconfig;
6254 	struct iwn2000_btcoex_config btconfig2k;
6255 	struct iwn_btcoex_priotable btprio;
6256 	struct iwn_btcoex_prot btprot;
6257 	int error, i;
6258 	uint8_t flags;
6259 
6260 	memset(&btconfig, 0, sizeof btconfig);
6261 	memset(&btconfig2k, 0, sizeof btconfig2k);
6262 
6263 	flags = IWN_BT_FLAG_COEX6000_MODE_3W <<
6264 	    IWN_BT_FLAG_COEX6000_MODE_SHIFT; // Done as is in linux kernel 3.2
6265 
6266 	if (sc->base_params->bt_sco_disable)
6267 		flags &= ~IWN_BT_FLAG_SYNC_2_BT_DISABLE;
6268 	else
6269 		flags |= IWN_BT_FLAG_SYNC_2_BT_DISABLE;
6270 
6271 	flags |= IWN_BT_FLAG_COEX6000_CHAN_INHIBITION;
6272 
6273 	/* Default flags result is 145 as old value */
6274 
6275 	/*
6276 	 * Flags value has to be review. Values must change if we
6277 	 * which to disable it
6278 	 */
6279 	if (sc->base_params->bt_session_2) {
6280 		btconfig2k.flags = flags;
6281 		btconfig2k.max_kill = 5;
6282 		btconfig2k.bt3_t7_timer = 1;
6283 		btconfig2k.kill_ack = htole32(0xffff0000);
6284 		btconfig2k.kill_cts = htole32(0xffff0000);
6285 		btconfig2k.sample_time = 2;
6286 		btconfig2k.bt3_t2_timer = 0xc;
6287 
6288 		for (i = 0; i < 12; i++)
6289 			btconfig2k.lookup_table[i] = htole32(btcoex_3wire[i]);
6290 		btconfig2k.valid = htole16(0xff);
6291 		btconfig2k.prio_boost = htole32(0xf0);
6292 		DPRINTF(sc, IWN_DEBUG_RESET,
6293 		    "%s: configuring advanced bluetooth coexistence"
6294 		    " session 2, flags : 0x%x\n",
6295 		    __func__,
6296 		    flags);
6297 		error = iwn_cmd(sc, IWN_CMD_BT_COEX, &btconfig2k,
6298 		    sizeof(btconfig2k), 1);
6299 	} else {
6300 		btconfig.flags = flags;
6301 		btconfig.max_kill = 5;
6302 		btconfig.bt3_t7_timer = 1;
6303 		btconfig.kill_ack = htole32(0xffff0000);
6304 		btconfig.kill_cts = htole32(0xffff0000);
6305 		btconfig.sample_time = 2;
6306 		btconfig.bt3_t2_timer = 0xc;
6307 
6308 		for (i = 0; i < 12; i++)
6309 			btconfig.lookup_table[i] = htole32(btcoex_3wire[i]);
6310 		btconfig.valid = htole16(0xff);
6311 		btconfig.prio_boost = 0xf0;
6312 		DPRINTF(sc, IWN_DEBUG_RESET,
6313 		    "%s: configuring advanced bluetooth coexistence,"
6314 		    " flags : 0x%x\n",
6315 		    __func__,
6316 		    flags);
6317 		error = iwn_cmd(sc, IWN_CMD_BT_COEX, &btconfig,
6318 		    sizeof(btconfig), 1);
6319 	}
6320 
6321 	if (error != 0)
6322 		return error;
6323 
6324 	memset(&btprio, 0, sizeof btprio);
6325 	btprio.calib_init1 = 0x6;
6326 	btprio.calib_init2 = 0x7;
6327 	btprio.calib_periodic_low1 = 0x2;
6328 	btprio.calib_periodic_low2 = 0x3;
6329 	btprio.calib_periodic_high1 = 0x4;
6330 	btprio.calib_periodic_high2 = 0x5;
6331 	btprio.dtim = 0x6;
6332 	btprio.scan52 = 0x8;
6333 	btprio.scan24 = 0xa;
6334 	error = iwn_cmd(sc, IWN_CMD_BT_COEX_PRIOTABLE, &btprio, sizeof(btprio),
6335 	    1);
6336 	if (error != 0)
6337 		return error;
6338 
6339 	/* Force BT state machine change. */
6340 	memset(&btprot, 0, sizeof btprot);
6341 	btprot.open = 1;
6342 	btprot.type = 1;
6343 	error = iwn_cmd(sc, IWN_CMD_BT_COEX_PROT, &btprot, sizeof(btprot), 1);
6344 	if (error != 0)
6345 		return error;
6346 	btprot.open = 0;
6347 	return iwn_cmd(sc, IWN_CMD_BT_COEX_PROT, &btprot, sizeof(btprot), 1);
6348 }
6349 
6350 static int
6351 iwn5000_runtime_calib(struct iwn_softc *sc)
6352 {
6353 	struct iwn5000_calib_config cmd;
6354 
6355 	memset(&cmd, 0, sizeof cmd);
6356 	cmd.ucode.once.enable = 0xffffffff;
6357 	cmd.ucode.once.start = IWN5000_CALIB_DC;
6358 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
6359 	    "%s: configuring runtime calibration\n", __func__);
6360 	return iwn_cmd(sc, IWN5000_CMD_CALIB_CONFIG, &cmd, sizeof(cmd), 0);
6361 }
6362 
6363 static int
6364 iwn_config(struct iwn_softc *sc)
6365 {
6366 	struct iwn_ops *ops = &sc->ops;
6367 	struct ifnet *ifp = sc->sc_ifp;
6368 	struct ieee80211com *ic = ifp->if_l2com;
6369 	uint32_t txmask;
6370 	uint16_t rxchain;
6371 	int error;
6372 
6373 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
6374 
6375 	if ((sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_TEMP_OFFSET)
6376 	    && (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_TEMP_OFFSETv2)) {
6377 		device_printf(sc->sc_dev,"%s: temp_offset and temp_offsetv2 are"
6378 		    " exclusive each together. Review NIC config file. Conf"
6379 		    " :  0x%08x Flags :  0x%08x  \n", __func__,
6380 		    sc->base_params->calib_need,
6381 		    (IWN_FLG_NEED_PHY_CALIB_TEMP_OFFSET |
6382 		    IWN_FLG_NEED_PHY_CALIB_TEMP_OFFSETv2));
6383 		return (EINVAL);
6384 	}
6385 
6386 	/* Compute temperature calib if needed. Will be send by send calib */
6387 	if (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_TEMP_OFFSET) {
6388 		error = iwn5000_temp_offset_calib(sc);
6389 		if (error != 0) {
6390 			device_printf(sc->sc_dev,
6391 			    "%s: could not set temperature offset\n", __func__);
6392 			return (error);
6393 		}
6394 	} else if (sc->base_params->calib_need & IWN_FLG_NEED_PHY_CALIB_TEMP_OFFSETv2) {
6395 		error = iwn5000_temp_offset_calibv2(sc);
6396 		if (error != 0) {
6397 			device_printf(sc->sc_dev,
6398 			    "%s: could not compute temperature offset v2\n",
6399 			    __func__);
6400 			return (error);
6401 		}
6402 	}
6403 
6404 	if (sc->hw_type == IWN_HW_REV_TYPE_6050) {
6405 		/* Configure runtime DC calibration. */
6406 		error = iwn5000_runtime_calib(sc);
6407 		if (error != 0) {
6408 			device_printf(sc->sc_dev,
6409 			    "%s: could not configure runtime calibration\n",
6410 			    __func__);
6411 			return error;
6412 		}
6413 	}
6414 
6415 	/* Configure valid TX chains for >=5000 Series. */
6416 	if (sc->hw_type != IWN_HW_REV_TYPE_4965 &&
6417 	    IWN_UCODE_API(sc->ucode_rev) > 1) {
6418 		txmask = htole32(sc->txchainmask);
6419 		DPRINTF(sc, IWN_DEBUG_RESET | IWN_DEBUG_XMIT,
6420 		    "%s: configuring valid TX chains 0x%x\n", __func__, txmask);
6421 		error = iwn_cmd(sc, IWN5000_CMD_TX_ANT_CONFIG, &txmask,
6422 		    sizeof txmask, 0);
6423 		if (error != 0) {
6424 			device_printf(sc->sc_dev,
6425 			    "%s: could not configure valid TX chains, "
6426 			    "error %d\n", __func__, error);
6427 			return error;
6428 		}
6429 	}
6430 
6431 	/* Configure bluetooth coexistence. */
6432 	error = 0;
6433 
6434 	/* Configure bluetooth coexistence if needed. */
6435 	if (sc->base_params->bt_mode == IWN_BT_ADVANCED)
6436 		error = iwn_send_advanced_btcoex(sc);
6437 	if (sc->base_params->bt_mode == IWN_BT_SIMPLE)
6438 		error = iwn_send_btcoex(sc);
6439 
6440 	if (error != 0) {
6441 		device_printf(sc->sc_dev,
6442 		    "%s: could not configure bluetooth coexistence, error %d\n",
6443 		    __func__, error);
6444 		return error;
6445 	}
6446 
6447 	/* Set mode, channel, RX filter and enable RX. */
6448 	sc->rxon = &sc->rx_on[IWN_RXON_BSS_CTX];
6449 	memset(sc->rxon, 0, sizeof (struct iwn_rxon));
6450 	IEEE80211_ADDR_COPY(sc->rxon->myaddr, IF_LLADDR(ifp));
6451 	IEEE80211_ADDR_COPY(sc->rxon->wlap, IF_LLADDR(ifp));
6452 	sc->rxon->chan = ieee80211_chan2ieee(ic, ic->ic_curchan);
6453 	sc->rxon->flags = htole32(IWN_RXON_TSF | IWN_RXON_CTS_TO_SELF);
6454 	if (IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan))
6455 		sc->rxon->flags |= htole32(IWN_RXON_AUTO | IWN_RXON_24GHZ);
6456 	switch (ic->ic_opmode) {
6457 	case IEEE80211_M_STA:
6458 		sc->rxon->mode = IWN_MODE_STA;
6459 		sc->rxon->filter = htole32(IWN_FILTER_MULTICAST);
6460 		break;
6461 	case IEEE80211_M_MONITOR:
6462 		sc->rxon->mode = IWN_MODE_MONITOR;
6463 		sc->rxon->filter = htole32(IWN_FILTER_MULTICAST |
6464 		    IWN_FILTER_CTL | IWN_FILTER_PROMISC);
6465 		break;
6466 	default:
6467 		/* Should not get there. */
6468 		break;
6469 	}
6470 	sc->rxon->cck_mask  = 0x0f;	/* not yet negotiated */
6471 	sc->rxon->ofdm_mask = 0xff;	/* not yet negotiated */
6472 	sc->rxon->ht_single_mask = 0xff;
6473 	sc->rxon->ht_dual_mask = 0xff;
6474 	sc->rxon->ht_triple_mask = 0xff;
6475 	/*
6476 	 * In active association mode, ensure that
6477 	 * all the receive chains are enabled.
6478 	 *
6479 	 * Since we're not yet doing SMPS, don't allow the
6480 	 * number of idle RX chains to be less than the active
6481 	 * number.
6482 	 */
6483 	rxchain =
6484 	    IWN_RXCHAIN_VALID(sc->rxchainmask) |
6485 	    IWN_RXCHAIN_MIMO_COUNT(sc->nrxchains) |
6486 	    IWN_RXCHAIN_IDLE_COUNT(sc->nrxchains);
6487 	sc->rxon->rxchain = htole16(rxchain);
6488 	DPRINTF(sc, IWN_DEBUG_RESET | IWN_DEBUG_XMIT,
6489 	    "%s: rxchainmask=0x%x, nrxchains=%d\n",
6490 	    __func__,
6491 	    sc->rxchainmask,
6492 	    sc->nrxchains);
6493 	DPRINTF(sc, IWN_DEBUG_RESET, "%s: setting configuration\n", __func__);
6494 	if (sc->sc_is_scanning)
6495 		device_printf(sc->sc_dev,
6496 		    "%s: is_scanning set, before RXON\n",
6497 		    __func__);
6498 	error = iwn_cmd(sc, IWN_CMD_RXON, sc->rxon, sc->rxonsz, 0);
6499 	if (error != 0) {
6500 		device_printf(sc->sc_dev, "%s: RXON command failed\n",
6501 		    __func__);
6502 		return error;
6503 	}
6504 
6505 	if ((error = iwn_add_broadcast_node(sc, 0)) != 0) {
6506 		device_printf(sc->sc_dev, "%s: could not add broadcast node\n",
6507 		    __func__);
6508 		return error;
6509 	}
6510 
6511 	/* Configuration has changed, set TX power accordingly. */
6512 	if ((error = ops->set_txpower(sc, ic->ic_curchan, 0)) != 0) {
6513 		device_printf(sc->sc_dev, "%s: could not set TX power\n",
6514 		    __func__);
6515 		return error;
6516 	}
6517 
6518 	if ((error = iwn_set_critical_temp(sc)) != 0) {
6519 		device_printf(sc->sc_dev,
6520 		    "%s: could not set critical temperature\n", __func__);
6521 		return error;
6522 	}
6523 
6524 	/* Set power saving level to CAM during initialization. */
6525 	if ((error = iwn_set_pslevel(sc, 0, 0, 0)) != 0) {
6526 		device_printf(sc->sc_dev,
6527 		    "%s: could not set power saving level\n", __func__);
6528 		return error;
6529 	}
6530 
6531 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
6532 
6533 	return 0;
6534 }
6535 
6536 static uint16_t
6537 iwn_get_active_dwell_time(struct iwn_softc *sc,
6538     struct ieee80211_channel *c, uint8_t n_probes)
6539 {
6540 	/* No channel? Default to 2GHz settings */
6541 	if (c == NULL || IEEE80211_IS_CHAN_2GHZ(c)) {
6542 		return (IWN_ACTIVE_DWELL_TIME_2GHZ +
6543 		IWN_ACTIVE_DWELL_FACTOR_2GHZ * (n_probes + 1));
6544 	}
6545 
6546 	/* 5GHz dwell time */
6547 	return (IWN_ACTIVE_DWELL_TIME_5GHZ +
6548 	    IWN_ACTIVE_DWELL_FACTOR_5GHZ * (n_probes + 1));
6549 }
6550 
6551 /*
6552  * Limit the total dwell time to 85% of the beacon interval.
6553  *
6554  * Returns the dwell time in milliseconds.
6555  */
6556 static uint16_t
6557 iwn_limit_dwell(struct iwn_softc *sc, uint16_t dwell_time)
6558 {
6559 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
6560 	struct ieee80211vap *vap = NULL;
6561 	int bintval = 0;
6562 
6563 	/* bintval is in TU (1.024mS) */
6564 	if (! TAILQ_EMPTY(&ic->ic_vaps)) {
6565 		vap = TAILQ_FIRST(&ic->ic_vaps);
6566 		bintval = vap->iv_bss->ni_intval;
6567 	}
6568 
6569 	/*
6570 	 * If it's non-zero, we should calculate the minimum of
6571 	 * it and the DWELL_BASE.
6572 	 *
6573 	 * XXX Yes, the math should take into account that bintval
6574 	 * is 1.024mS, not 1mS..
6575 	 */
6576 	if (bintval > 0) {
6577 		DPRINTF(sc, IWN_DEBUG_SCAN,
6578 		    "%s: bintval=%d\n",
6579 		    __func__,
6580 		    bintval);
6581 		return (MIN(IWN_PASSIVE_DWELL_BASE, ((bintval * 85) / 100)));
6582 	}
6583 
6584 	/* No association context? Default */
6585 	return (IWN_PASSIVE_DWELL_BASE);
6586 }
6587 
6588 static uint16_t
6589 iwn_get_passive_dwell_time(struct iwn_softc *sc, struct ieee80211_channel *c)
6590 {
6591 	uint16_t passive;
6592 
6593 	if (c == NULL || IEEE80211_IS_CHAN_2GHZ(c)) {
6594 		passive = IWN_PASSIVE_DWELL_BASE + IWN_PASSIVE_DWELL_TIME_2GHZ;
6595 	} else {
6596 		passive = IWN_PASSIVE_DWELL_BASE + IWN_PASSIVE_DWELL_TIME_5GHZ;
6597 	}
6598 
6599 	/* Clamp to the beacon interval if we're associated */
6600 	return (iwn_limit_dwell(sc, passive));
6601 }
6602 
6603 static int
6604 iwn_scan(struct iwn_softc *sc, struct ieee80211vap *vap,
6605     struct ieee80211_scan_state *ss, struct ieee80211_channel *c)
6606 {
6607 	struct ifnet *ifp = sc->sc_ifp;
6608 	struct ieee80211com *ic = ifp->if_l2com;
6609 	struct ieee80211_node *ni = vap->iv_bss;
6610 	struct iwn_scan_hdr *hdr;
6611 	struct iwn_cmd_data *tx;
6612 	struct iwn_scan_essid *essid;
6613 	struct iwn_scan_chan *chan;
6614 	struct ieee80211_frame *wh;
6615 	struct ieee80211_rateset *rs;
6616 	uint8_t *buf, *frm;
6617 	uint16_t rxchain;
6618 	uint8_t txant;
6619 	int buflen, error;
6620 	int is_active;
6621 	uint16_t dwell_active, dwell_passive;
6622 	uint32_t extra, scan_service_time;
6623 
6624 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
6625 
6626 	/*
6627 	 * We are absolutely not allowed to send a scan command when another
6628 	 * scan command is pending.
6629 	 */
6630 	if (sc->sc_is_scanning) {
6631 		device_printf(sc->sc_dev, "%s: called whilst scanning!\n",
6632 		    __func__);
6633 		return (EAGAIN);
6634 	}
6635 
6636 	/* Assign the scan channel */
6637 	c = ic->ic_curchan;
6638 
6639 	sc->rxon = &sc->rx_on[IWN_RXON_BSS_CTX];
6640 	buf = malloc(IWN_SCAN_MAXSZ, M_DEVBUF, M_NOWAIT | M_ZERO);
6641 	if (buf == NULL) {
6642 		device_printf(sc->sc_dev,
6643 		    "%s: could not allocate buffer for scan command\n",
6644 		    __func__);
6645 		return ENOMEM;
6646 	}
6647 	hdr = (struct iwn_scan_hdr *)buf;
6648 	/*
6649 	 * Move to the next channel if no frames are received within 10ms
6650 	 * after sending the probe request.
6651 	 */
6652 	hdr->quiet_time = htole16(10);		/* timeout in milliseconds */
6653 	hdr->quiet_threshold = htole16(1);	/* min # of packets */
6654 	/*
6655 	 * Max needs to be greater than active and passive and quiet!
6656 	 * It's also in microseconds!
6657 	 */
6658 	hdr->max_svc = htole32(250 * 1024);
6659 
6660 	/*
6661 	 * Reset scan: interval=100
6662 	 * Normal scan: interval=becaon interval
6663 	 * suspend_time: 100 (TU)
6664 	 *
6665 	 */
6666 	extra = (100 /* suspend_time */ / 100 /* beacon interval */) << 22;
6667 	//scan_service_time = extra | ((100 /* susp */ % 100 /* int */) * 1024);
6668 	scan_service_time = (4 << 22) | (100 * 1024);	/* Hardcode for now! */
6669 	hdr->pause_svc = htole32(scan_service_time);
6670 
6671 	/* Select antennas for scanning. */
6672 	rxchain =
6673 	    IWN_RXCHAIN_VALID(sc->rxchainmask) |
6674 	    IWN_RXCHAIN_FORCE_MIMO_SEL(sc->rxchainmask) |
6675 	    IWN_RXCHAIN_DRIVER_FORCE;
6676 	if (IEEE80211_IS_CHAN_A(c) &&
6677 	    sc->hw_type == IWN_HW_REV_TYPE_4965) {
6678 		/* Ant A must be avoided in 5GHz because of an HW bug. */
6679 		rxchain |= IWN_RXCHAIN_FORCE_SEL(IWN_ANT_B);
6680 	} else	/* Use all available RX antennas. */
6681 		rxchain |= IWN_RXCHAIN_FORCE_SEL(sc->rxchainmask);
6682 	hdr->rxchain = htole16(rxchain);
6683 	hdr->filter = htole32(IWN_FILTER_MULTICAST | IWN_FILTER_BEACON);
6684 
6685 	tx = (struct iwn_cmd_data *)(hdr + 1);
6686 	tx->flags = htole32(IWN_TX_AUTO_SEQ);
6687 	tx->id = sc->broadcast_id;
6688 	tx->lifetime = htole32(IWN_LIFETIME_INFINITE);
6689 
6690 	if (IEEE80211_IS_CHAN_5GHZ(c)) {
6691 		/* Send probe requests at 6Mbps. */
6692 		tx->rate = htole32(0xd);
6693 		rs = &ic->ic_sup_rates[IEEE80211_MODE_11A];
6694 	} else {
6695 		hdr->flags = htole32(IWN_RXON_24GHZ | IWN_RXON_AUTO);
6696 		if (sc->hw_type == IWN_HW_REV_TYPE_4965 &&
6697 		    sc->rxon->associd && sc->rxon->chan > 14)
6698 			tx->rate = htole32(0xd);
6699 		else {
6700 			/* Send probe requests at 1Mbps. */
6701 			tx->rate = htole32(10 | IWN_RFLAG_CCK);
6702 		}
6703 		rs = &ic->ic_sup_rates[IEEE80211_MODE_11G];
6704 	}
6705 	/* Use the first valid TX antenna. */
6706 	txant = IWN_LSB(sc->txchainmask);
6707 	tx->rate |= htole32(IWN_RFLAG_ANT(txant));
6708 
6709 	/*
6710 	 * Only do active scanning if we're announcing a probe request
6711 	 * for a given SSID (or more, if we ever add it to the driver.)
6712 	 */
6713 	is_active = 0;
6714 
6715 	/*
6716 	 * If we're scanning for a specific SSID, add it to the command.
6717 	 *
6718 	 * XXX maybe look at adding support for scanning multiple SSIDs?
6719 	 */
6720 	essid = (struct iwn_scan_essid *)(tx + 1);
6721 	if (ss != NULL) {
6722 		if (ss->ss_ssid[0].len != 0) {
6723 			essid[0].id = IEEE80211_ELEMID_SSID;
6724 			essid[0].len = ss->ss_ssid[0].len;
6725 			memcpy(essid[0].data, ss->ss_ssid[0].ssid, ss->ss_ssid[0].len);
6726 		}
6727 
6728 		DPRINTF(sc, IWN_DEBUG_SCAN, "%s: ssid_len=%d, ssid=%*s\n",
6729 		    __func__,
6730 		    ss->ss_ssid[0].len,
6731 		    ss->ss_ssid[0].len,
6732 		    ss->ss_ssid[0].ssid);
6733 
6734 		if (ss->ss_nssid > 0)
6735 			is_active = 1;
6736 	}
6737 
6738 	/*
6739 	 * Build a probe request frame.  Most of the following code is a
6740 	 * copy & paste of what is done in net80211.
6741 	 */
6742 	wh = (struct ieee80211_frame *)(essid + 20);
6743 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
6744 	    IEEE80211_FC0_SUBTYPE_PROBE_REQ;
6745 	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
6746 	IEEE80211_ADDR_COPY(wh->i_addr1, ifp->if_broadcastaddr);
6747 	IEEE80211_ADDR_COPY(wh->i_addr2, IF_LLADDR(ifp));
6748 	IEEE80211_ADDR_COPY(wh->i_addr3, ifp->if_broadcastaddr);
6749 	*(uint16_t *)&wh->i_dur[0] = 0;	/* filled by HW */
6750 	*(uint16_t *)&wh->i_seq[0] = 0;	/* filled by HW */
6751 
6752 	frm = (uint8_t *)(wh + 1);
6753 	frm = ieee80211_add_ssid(frm, NULL, 0);
6754 	frm = ieee80211_add_rates(frm, rs);
6755 	if (rs->rs_nrates > IEEE80211_RATE_SIZE)
6756 		frm = ieee80211_add_xrates(frm, rs);
6757 	if (ic->ic_htcaps & IEEE80211_HTC_HT)
6758 		frm = ieee80211_add_htcap(frm, ni);
6759 
6760 	/* Set length of probe request. */
6761 	tx->len = htole16(frm - (uint8_t *)wh);
6762 
6763 	/*
6764 	 * If active scanning is requested but a certain channel is
6765 	 * marked passive, we can do active scanning if we detect
6766 	 * transmissions.
6767 	 *
6768 	 * There is an issue with some firmware versions that triggers
6769 	 * a sysassert on a "good CRC threshold" of zero (== disabled),
6770 	 * on a radar channel even though this means that we should NOT
6771 	 * send probes.
6772 	 *
6773 	 * The "good CRC threshold" is the number of frames that we
6774 	 * need to receive during our dwell time on a channel before
6775 	 * sending out probes -- setting this to a huge value will
6776 	 * mean we never reach it, but at the same time work around
6777 	 * the aforementioned issue. Thus use IWL_GOOD_CRC_TH_NEVER
6778 	 * here instead of IWL_GOOD_CRC_TH_DISABLED.
6779 	 *
6780 	 * This was fixed in later versions along with some other
6781 	 * scan changes, and the threshold behaves as a flag in those
6782 	 * versions.
6783 	 */
6784 
6785 	/*
6786 	 * If we're doing active scanning, set the crc_threshold
6787 	 * to a suitable value.  This is different to active veruss
6788 	 * passive scanning depending upon the channel flags; the
6789 	 * firmware will obey that particular check for us.
6790 	 */
6791 	if (sc->tlv_feature_flags & IWN_UCODE_TLV_FLAGS_NEWSCAN)
6792 		hdr->crc_threshold = is_active ?
6793 		    IWN_GOOD_CRC_TH_DEFAULT : IWN_GOOD_CRC_TH_DISABLED;
6794 	else
6795 		hdr->crc_threshold = is_active ?
6796 		    IWN_GOOD_CRC_TH_DEFAULT : IWN_GOOD_CRC_TH_NEVER;
6797 
6798 	chan = (struct iwn_scan_chan *)frm;
6799 	chan->chan = htole16(ieee80211_chan2ieee(ic, c));
6800 	chan->flags = 0;
6801 	if (ss->ss_nssid > 0)
6802 		chan->flags |= htole32(IWN_CHAN_NPBREQS(1));
6803 	chan->dsp_gain = 0x6e;
6804 
6805 	/*
6806 	 * Set the passive/active flag depending upon the channel mode.
6807 	 * XXX TODO: take the is_active flag into account as well?
6808 	 */
6809 	if (c->ic_flags & IEEE80211_CHAN_PASSIVE)
6810 		chan->flags |= htole32(IWN_CHAN_PASSIVE);
6811 	else
6812 		chan->flags |= htole32(IWN_CHAN_ACTIVE);
6813 
6814 	/*
6815 	 * Calculate the active/passive dwell times.
6816 	 */
6817 
6818 	dwell_active = iwn_get_active_dwell_time(sc, c, ss->ss_nssid);
6819 	dwell_passive = iwn_get_passive_dwell_time(sc, c);
6820 
6821 	/* Make sure they're valid */
6822 	if (dwell_passive <= dwell_active)
6823 		dwell_passive = dwell_active + 1;
6824 
6825 	chan->active = htole16(dwell_active);
6826 	chan->passive = htole16(dwell_passive);
6827 
6828 	if (IEEE80211_IS_CHAN_5GHZ(c))
6829 		chan->rf_gain = 0x3b;
6830 	else
6831 		chan->rf_gain = 0x28;
6832 
6833 	DPRINTF(sc, IWN_DEBUG_STATE,
6834 	    "%s: chan %u flags 0x%x rf_gain 0x%x "
6835 	    "dsp_gain 0x%x active %d passive %d scan_svc_time %d crc 0x%x "
6836 	    "isactive=%d numssid=%d\n", __func__,
6837 	    chan->chan, chan->flags, chan->rf_gain, chan->dsp_gain,
6838 	    dwell_active, dwell_passive, scan_service_time,
6839 	    hdr->crc_threshold, is_active, ss->ss_nssid);
6840 
6841 	hdr->nchan++;
6842 	chan++;
6843 	buflen = (uint8_t *)chan - buf;
6844 	hdr->len = htole16(buflen);
6845 
6846 	if (sc->sc_is_scanning) {
6847 		device_printf(sc->sc_dev,
6848 		    "%s: called with is_scanning set!\n",
6849 		    __func__);
6850 	}
6851 	sc->sc_is_scanning = 1;
6852 
6853 	DPRINTF(sc, IWN_DEBUG_STATE, "sending scan command nchan=%d\n",
6854 	    hdr->nchan);
6855 	error = iwn_cmd(sc, IWN_CMD_SCAN, buf, buflen, 1);
6856 	free(buf, M_DEVBUF);
6857 
6858 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
6859 
6860 	return error;
6861 }
6862 
6863 static int
6864 iwn_auth(struct iwn_softc *sc, struct ieee80211vap *vap)
6865 {
6866 	struct iwn_ops *ops = &sc->ops;
6867 	struct ifnet *ifp = sc->sc_ifp;
6868 	struct ieee80211com *ic = ifp->if_l2com;
6869 	struct ieee80211_node *ni = vap->iv_bss;
6870 	int error;
6871 
6872 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
6873 
6874 	sc->rxon = &sc->rx_on[IWN_RXON_BSS_CTX];
6875 	/* Update adapter configuration. */
6876 	IEEE80211_ADDR_COPY(sc->rxon->bssid, ni->ni_bssid);
6877 	sc->rxon->chan = ieee80211_chan2ieee(ic, ni->ni_chan);
6878 	sc->rxon->flags = htole32(IWN_RXON_TSF | IWN_RXON_CTS_TO_SELF);
6879 	if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
6880 		sc->rxon->flags |= htole32(IWN_RXON_AUTO | IWN_RXON_24GHZ);
6881 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
6882 		sc->rxon->flags |= htole32(IWN_RXON_SHSLOT);
6883 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
6884 		sc->rxon->flags |= htole32(IWN_RXON_SHPREAMBLE);
6885 	if (IEEE80211_IS_CHAN_A(ni->ni_chan)) {
6886 		sc->rxon->cck_mask  = 0;
6887 		sc->rxon->ofdm_mask = 0x15;
6888 	} else if (IEEE80211_IS_CHAN_B(ni->ni_chan)) {
6889 		sc->rxon->cck_mask  = 0x03;
6890 		sc->rxon->ofdm_mask = 0;
6891 	} else {
6892 		/* Assume 802.11b/g. */
6893 		sc->rxon->cck_mask  = 0x03;
6894 		sc->rxon->ofdm_mask = 0x15;
6895 	}
6896 	DPRINTF(sc, IWN_DEBUG_STATE, "rxon chan %d flags %x cck %x ofdm %x\n",
6897 	    sc->rxon->chan, sc->rxon->flags, sc->rxon->cck_mask,
6898 	    sc->rxon->ofdm_mask);
6899 	if (sc->sc_is_scanning)
6900 		device_printf(sc->sc_dev,
6901 		    "%s: is_scanning set, before RXON\n",
6902 		    __func__);
6903 	error = iwn_cmd(sc, IWN_CMD_RXON, sc->rxon, sc->rxonsz, 1);
6904 	if (error != 0) {
6905 		device_printf(sc->sc_dev, "%s: RXON command failed, error %d\n",
6906 		    __func__, error);
6907 		return error;
6908 	}
6909 
6910 	/* Configuration has changed, set TX power accordingly. */
6911 	if ((error = ops->set_txpower(sc, ni->ni_chan, 1)) != 0) {
6912 		device_printf(sc->sc_dev,
6913 		    "%s: could not set TX power, error %d\n", __func__, error);
6914 		return error;
6915 	}
6916 	/*
6917 	 * Reconfiguring RXON clears the firmware nodes table so we must
6918 	 * add the broadcast node again.
6919 	 */
6920 	if ((error = iwn_add_broadcast_node(sc, 1)) != 0) {
6921 		device_printf(sc->sc_dev,
6922 		    "%s: could not add broadcast node, error %d\n", __func__,
6923 		    error);
6924 		return error;
6925 	}
6926 
6927 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
6928 
6929 	return 0;
6930 }
6931 
6932 static int
6933 iwn_run(struct iwn_softc *sc, struct ieee80211vap *vap)
6934 {
6935 	struct iwn_ops *ops = &sc->ops;
6936 	struct ifnet *ifp = sc->sc_ifp;
6937 	struct ieee80211com *ic = ifp->if_l2com;
6938 	struct ieee80211_node *ni = vap->iv_bss;
6939 	struct iwn_node_info node;
6940 	uint32_t htflags = 0;
6941 	int error;
6942 
6943 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
6944 
6945 	sc->rxon = &sc->rx_on[IWN_RXON_BSS_CTX];
6946 	if (ic->ic_opmode == IEEE80211_M_MONITOR) {
6947 		/* Link LED blinks while monitoring. */
6948 		iwn_set_led(sc, IWN_LED_LINK, 5, 5);
6949 		return 0;
6950 	}
6951 	if ((error = iwn_set_timing(sc, ni)) != 0) {
6952 		device_printf(sc->sc_dev,
6953 		    "%s: could not set timing, error %d\n", __func__, error);
6954 		return error;
6955 	}
6956 
6957 	/* Update adapter configuration. */
6958 	IEEE80211_ADDR_COPY(sc->rxon->bssid, ni->ni_bssid);
6959 	sc->rxon->associd = htole16(IEEE80211_AID(ni->ni_associd));
6960 	sc->rxon->chan = ieee80211_chan2ieee(ic, ni->ni_chan);
6961 	sc->rxon->flags = htole32(IWN_RXON_TSF | IWN_RXON_CTS_TO_SELF);
6962 	if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
6963 		sc->rxon->flags |= htole32(IWN_RXON_AUTO | IWN_RXON_24GHZ);
6964 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
6965 		sc->rxon->flags |= htole32(IWN_RXON_SHSLOT);
6966 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
6967 		sc->rxon->flags |= htole32(IWN_RXON_SHPREAMBLE);
6968 	if (IEEE80211_IS_CHAN_A(ni->ni_chan)) {
6969 		sc->rxon->cck_mask  = 0;
6970 		sc->rxon->ofdm_mask = 0x15;
6971 	} else if (IEEE80211_IS_CHAN_B(ni->ni_chan)) {
6972 		sc->rxon->cck_mask  = 0x03;
6973 		sc->rxon->ofdm_mask = 0;
6974 	} else {
6975 		/* Assume 802.11b/g. */
6976 		sc->rxon->cck_mask  = 0x0f;
6977 		sc->rxon->ofdm_mask = 0x15;
6978 	}
6979 	if (IEEE80211_IS_CHAN_HT(ni->ni_chan)) {
6980 		htflags |= IWN_RXON_HT_PROTMODE(ic->ic_curhtprotmode);
6981 		if (IEEE80211_IS_CHAN_HT40(ni->ni_chan)) {
6982 			switch (ic->ic_curhtprotmode) {
6983 			case IEEE80211_HTINFO_OPMODE_HT20PR:
6984 				htflags |= IWN_RXON_HT_MODEPURE40;
6985 				break;
6986 			default:
6987 				htflags |= IWN_RXON_HT_MODEMIXED;
6988 				break;
6989 			}
6990 		}
6991 		if (IEEE80211_IS_CHAN_HT40D(ni->ni_chan))
6992 			htflags |= IWN_RXON_HT_HT40MINUS;
6993 	}
6994 	sc->rxon->flags |= htole32(htflags);
6995 	sc->rxon->filter |= htole32(IWN_FILTER_BSS);
6996 	DPRINTF(sc, IWN_DEBUG_STATE, "rxon chan %d flags %x\n",
6997 	    sc->rxon->chan, sc->rxon->flags);
6998 	if (sc->sc_is_scanning)
6999 		device_printf(sc->sc_dev,
7000 		    "%s: is_scanning set, before RXON\n",
7001 		    __func__);
7002 	error = iwn_cmd(sc, IWN_CMD_RXON, sc->rxon, sc->rxonsz, 1);
7003 	if (error != 0) {
7004 		device_printf(sc->sc_dev,
7005 		    "%s: could not update configuration, error %d\n", __func__,
7006 		    error);
7007 		return error;
7008 	}
7009 
7010 	/* Configuration has changed, set TX power accordingly. */
7011 	if ((error = ops->set_txpower(sc, ni->ni_chan, 1)) != 0) {
7012 		device_printf(sc->sc_dev,
7013 		    "%s: could not set TX power, error %d\n", __func__, error);
7014 		return error;
7015 	}
7016 
7017 	/* Fake a join to initialize the TX rate. */
7018 	((struct iwn_node *)ni)->id = IWN_ID_BSS;
7019 	iwn_newassoc(ni, 1);
7020 
7021 	/* Add BSS node. */
7022 	memset(&node, 0, sizeof node);
7023 	IEEE80211_ADDR_COPY(node.macaddr, ni->ni_macaddr);
7024 	node.id = IWN_ID_BSS;
7025 	if (IEEE80211_IS_CHAN_HT(ni->ni_chan)) {
7026 		switch (ni->ni_htcap & IEEE80211_HTCAP_SMPS) {
7027 		case IEEE80211_HTCAP_SMPS_ENA:
7028 			node.htflags |= htole32(IWN_SMPS_MIMO_DIS);
7029 			break;
7030 		case IEEE80211_HTCAP_SMPS_DYNAMIC:
7031 			node.htflags |= htole32(IWN_SMPS_MIMO_PROT);
7032 			break;
7033 		}
7034 		node.htflags |= htole32(IWN_AMDPU_SIZE_FACTOR(3) |
7035 		    IWN_AMDPU_DENSITY(5));	/* 4us */
7036 		if (IEEE80211_IS_CHAN_HT40(ni->ni_chan))
7037 			node.htflags |= htole32(IWN_NODE_HT40);
7038 	}
7039 	DPRINTF(sc, IWN_DEBUG_STATE, "%s: adding BSS node\n", __func__);
7040 	error = ops->add_node(sc, &node, 1);
7041 	if (error != 0) {
7042 		device_printf(sc->sc_dev,
7043 		    "%s: could not add BSS node, error %d\n", __func__, error);
7044 		return error;
7045 	}
7046 	DPRINTF(sc, IWN_DEBUG_STATE, "%s: setting link quality for node %d\n",
7047 	    __func__, node.id);
7048 	if ((error = iwn_set_link_quality(sc, ni)) != 0) {
7049 		device_printf(sc->sc_dev,
7050 		    "%s: could not setup link quality for node %d, error %d\n",
7051 		    __func__, node.id, error);
7052 		return error;
7053 	}
7054 
7055 	if ((error = iwn_init_sensitivity(sc)) != 0) {
7056 		device_printf(sc->sc_dev,
7057 		    "%s: could not set sensitivity, error %d\n", __func__,
7058 		    error);
7059 		return error;
7060 	}
7061 	/* Start periodic calibration timer. */
7062 	sc->calib.state = IWN_CALIB_STATE_ASSOC;
7063 	sc->calib_cnt = 0;
7064 	callout_reset(&sc->calib_to, msecs_to_ticks(500), iwn_calib_timeout,
7065 	    sc);
7066 
7067 	/* Link LED always on while associated. */
7068 	iwn_set_led(sc, IWN_LED_LINK, 0, 1);
7069 
7070 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
7071 
7072 	return 0;
7073 }
7074 
7075 /*
7076  * This function is called by upper layer when an ADDBA request is received
7077  * from another STA and before the ADDBA response is sent.
7078  */
7079 static int
7080 iwn_ampdu_rx_start(struct ieee80211_node *ni, struct ieee80211_rx_ampdu *rap,
7081     int baparamset, int batimeout, int baseqctl)
7082 {
7083 #define MS(_v, _f)	(((_v) & _f) >> _f##_S)
7084 	struct iwn_softc *sc = ni->ni_ic->ic_ifp->if_softc;
7085 	struct iwn_ops *ops = &sc->ops;
7086 	struct iwn_node *wn = (void *)ni;
7087 	struct iwn_node_info node;
7088 	uint16_t ssn;
7089 	uint8_t tid;
7090 	int error;
7091 
7092 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7093 
7094 	tid = MS(le16toh(baparamset), IEEE80211_BAPS_TID);
7095 	ssn = MS(le16toh(baseqctl), IEEE80211_BASEQ_START);
7096 
7097 	memset(&node, 0, sizeof node);
7098 	node.id = wn->id;
7099 	node.control = IWN_NODE_UPDATE;
7100 	node.flags = IWN_FLAG_SET_ADDBA;
7101 	node.addba_tid = tid;
7102 	node.addba_ssn = htole16(ssn);
7103 	DPRINTF(sc, IWN_DEBUG_RECV, "ADDBA RA=%d TID=%d SSN=%d\n",
7104 	    wn->id, tid, ssn);
7105 	error = ops->add_node(sc, &node, 1);
7106 	if (error != 0)
7107 		return error;
7108 	return sc->sc_ampdu_rx_start(ni, rap, baparamset, batimeout, baseqctl);
7109 #undef MS
7110 }
7111 
7112 /*
7113  * This function is called by upper layer on teardown of an HT-immediate
7114  * Block Ack agreement (eg. uppon receipt of a DELBA frame).
7115  */
7116 static void
7117 iwn_ampdu_rx_stop(struct ieee80211_node *ni, struct ieee80211_rx_ampdu *rap)
7118 {
7119 	struct ieee80211com *ic = ni->ni_ic;
7120 	struct iwn_softc *sc = ic->ic_ifp->if_softc;
7121 	struct iwn_ops *ops = &sc->ops;
7122 	struct iwn_node *wn = (void *)ni;
7123 	struct iwn_node_info node;
7124 	uint8_t tid;
7125 
7126 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7127 
7128 	/* XXX: tid as an argument */
7129 	for (tid = 0; tid < WME_NUM_TID; tid++) {
7130 		if (&ni->ni_rx_ampdu[tid] == rap)
7131 			break;
7132 	}
7133 
7134 	memset(&node, 0, sizeof node);
7135 	node.id = wn->id;
7136 	node.control = IWN_NODE_UPDATE;
7137 	node.flags = IWN_FLAG_SET_DELBA;
7138 	node.delba_tid = tid;
7139 	DPRINTF(sc, IWN_DEBUG_RECV, "DELBA RA=%d TID=%d\n", wn->id, tid);
7140 	(void)ops->add_node(sc, &node, 1);
7141 	sc->sc_ampdu_rx_stop(ni, rap);
7142 }
7143 
7144 static int
7145 iwn_addba_request(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap,
7146     int dialogtoken, int baparamset, int batimeout)
7147 {
7148 	struct iwn_softc *sc = ni->ni_ic->ic_ifp->if_softc;
7149 	int qid;
7150 
7151 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7152 
7153 	for (qid = sc->firstaggqueue; qid < sc->ntxqs; qid++) {
7154 		if (sc->qid2tap[qid] == NULL)
7155 			break;
7156 	}
7157 	if (qid == sc->ntxqs) {
7158 		DPRINTF(sc, IWN_DEBUG_XMIT, "%s: not free aggregation queue\n",
7159 		    __func__);
7160 		return 0;
7161 	}
7162 	tap->txa_private = malloc(sizeof(int), M_DEVBUF, M_NOWAIT);
7163 	if (tap->txa_private == NULL) {
7164 		device_printf(sc->sc_dev,
7165 		    "%s: failed to alloc TX aggregation structure\n", __func__);
7166 		return 0;
7167 	}
7168 	sc->qid2tap[qid] = tap;
7169 	*(int *)tap->txa_private = qid;
7170 	return sc->sc_addba_request(ni, tap, dialogtoken, baparamset,
7171 	    batimeout);
7172 }
7173 
7174 static int
7175 iwn_addba_response(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap,
7176     int code, int baparamset, int batimeout)
7177 {
7178 	struct iwn_softc *sc = ni->ni_ic->ic_ifp->if_softc;
7179 	int qid = *(int *)tap->txa_private;
7180 	uint8_t tid = tap->txa_tid;
7181 	int ret;
7182 
7183 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7184 
7185 	if (code == IEEE80211_STATUS_SUCCESS) {
7186 		ni->ni_txseqs[tid] = tap->txa_start & 0xfff;
7187 		ret = iwn_ampdu_tx_start(ni->ni_ic, ni, tid);
7188 		if (ret != 1)
7189 			return ret;
7190 	} else {
7191 		sc->qid2tap[qid] = NULL;
7192 		free(tap->txa_private, M_DEVBUF);
7193 		tap->txa_private = NULL;
7194 	}
7195 	return sc->sc_addba_response(ni, tap, code, baparamset, batimeout);
7196 }
7197 
7198 /*
7199  * This function is called by upper layer when an ADDBA response is received
7200  * from another STA.
7201  */
7202 static int
7203 iwn_ampdu_tx_start(struct ieee80211com *ic, struct ieee80211_node *ni,
7204     uint8_t tid)
7205 {
7206 	struct ieee80211_tx_ampdu *tap = &ni->ni_tx_ampdu[tid];
7207 	struct iwn_softc *sc = ni->ni_ic->ic_ifp->if_softc;
7208 	struct iwn_ops *ops = &sc->ops;
7209 	struct iwn_node *wn = (void *)ni;
7210 	struct iwn_node_info node;
7211 	int error, qid;
7212 
7213 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7214 
7215 	/* Enable TX for the specified RA/TID. */
7216 	wn->disable_tid &= ~(1 << tid);
7217 	memset(&node, 0, sizeof node);
7218 	node.id = wn->id;
7219 	node.control = IWN_NODE_UPDATE;
7220 	node.flags = IWN_FLAG_SET_DISABLE_TID;
7221 	node.disable_tid = htole16(wn->disable_tid);
7222 	error = ops->add_node(sc, &node, 1);
7223 	if (error != 0)
7224 		return 0;
7225 
7226 	if ((error = iwn_nic_lock(sc)) != 0)
7227 		return 0;
7228 	qid = *(int *)tap->txa_private;
7229 	DPRINTF(sc, IWN_DEBUG_XMIT, "%s: ra=%d tid=%d ssn=%d qid=%d\n",
7230 	    __func__, wn->id, tid, tap->txa_start, qid);
7231 	ops->ampdu_tx_start(sc, ni, qid, tid, tap->txa_start & 0xfff);
7232 	iwn_nic_unlock(sc);
7233 
7234 	iwn_set_link_quality(sc, ni);
7235 	return 1;
7236 }
7237 
7238 static void
7239 iwn_ampdu_tx_stop(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap)
7240 {
7241 	struct iwn_softc *sc = ni->ni_ic->ic_ifp->if_softc;
7242 	struct iwn_ops *ops = &sc->ops;
7243 	uint8_t tid = tap->txa_tid;
7244 	int qid;
7245 
7246 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7247 
7248 	sc->sc_addba_stop(ni, tap);
7249 
7250 	if (tap->txa_private == NULL)
7251 		return;
7252 
7253 	qid = *(int *)tap->txa_private;
7254 	if (sc->txq[qid].queued != 0)
7255 		return;
7256 	if (iwn_nic_lock(sc) != 0)
7257 		return;
7258 	ops->ampdu_tx_stop(sc, qid, tid, tap->txa_start & 0xfff);
7259 	iwn_nic_unlock(sc);
7260 	sc->qid2tap[qid] = NULL;
7261 	free(tap->txa_private, M_DEVBUF);
7262 	tap->txa_private = NULL;
7263 }
7264 
7265 static void
7266 iwn4965_ampdu_tx_start(struct iwn_softc *sc, struct ieee80211_node *ni,
7267     int qid, uint8_t tid, uint16_t ssn)
7268 {
7269 	struct iwn_node *wn = (void *)ni;
7270 
7271 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7272 
7273 	/* Stop TX scheduler while we're changing its configuration. */
7274 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
7275 	    IWN4965_TXQ_STATUS_CHGACT);
7276 
7277 	/* Assign RA/TID translation to the queue. */
7278 	iwn_mem_write_2(sc, sc->sched_base + IWN4965_SCHED_TRANS_TBL(qid),
7279 	    wn->id << 4 | tid);
7280 
7281 	/* Enable chain-building mode for the queue. */
7282 	iwn_prph_setbits(sc, IWN4965_SCHED_QCHAIN_SEL, 1 << qid);
7283 
7284 	/* Set starting sequence number from the ADDBA request. */
7285 	sc->txq[qid].cur = sc->txq[qid].read = (ssn & 0xff);
7286 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | (ssn & 0xff));
7287 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_RDPTR(qid), ssn);
7288 
7289 	/* Set scheduler window size. */
7290 	iwn_mem_write(sc, sc->sched_base + IWN4965_SCHED_QUEUE_OFFSET(qid),
7291 	    IWN_SCHED_WINSZ);
7292 	/* Set scheduler frame limit. */
7293 	iwn_mem_write(sc, sc->sched_base + IWN4965_SCHED_QUEUE_OFFSET(qid) + 4,
7294 	    IWN_SCHED_LIMIT << 16);
7295 
7296 	/* Enable interrupts for the queue. */
7297 	iwn_prph_setbits(sc, IWN4965_SCHED_INTR_MASK, 1 << qid);
7298 
7299 	/* Mark the queue as active. */
7300 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
7301 	    IWN4965_TXQ_STATUS_ACTIVE | IWN4965_TXQ_STATUS_AGGR_ENA |
7302 	    iwn_tid2fifo[tid] << 1);
7303 }
7304 
7305 static void
7306 iwn4965_ampdu_tx_stop(struct iwn_softc *sc, int qid, uint8_t tid, uint16_t ssn)
7307 {
7308 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7309 
7310 	/* Stop TX scheduler while we're changing its configuration. */
7311 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
7312 	    IWN4965_TXQ_STATUS_CHGACT);
7313 
7314 	/* Set starting sequence number from the ADDBA request. */
7315 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | (ssn & 0xff));
7316 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_RDPTR(qid), ssn);
7317 
7318 	/* Disable interrupts for the queue. */
7319 	iwn_prph_clrbits(sc, IWN4965_SCHED_INTR_MASK, 1 << qid);
7320 
7321 	/* Mark the queue as inactive. */
7322 	iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
7323 	    IWN4965_TXQ_STATUS_INACTIVE | iwn_tid2fifo[tid] << 1);
7324 }
7325 
7326 static void
7327 iwn5000_ampdu_tx_start(struct iwn_softc *sc, struct ieee80211_node *ni,
7328     int qid, uint8_t tid, uint16_t ssn)
7329 {
7330 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7331 
7332 	struct iwn_node *wn = (void *)ni;
7333 
7334 	/* Stop TX scheduler while we're changing its configuration. */
7335 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
7336 	    IWN5000_TXQ_STATUS_CHGACT);
7337 
7338 	/* Assign RA/TID translation to the queue. */
7339 	iwn_mem_write_2(sc, sc->sched_base + IWN5000_SCHED_TRANS_TBL(qid),
7340 	    wn->id << 4 | tid);
7341 
7342 	/* Enable chain-building mode for the queue. */
7343 	iwn_prph_setbits(sc, IWN5000_SCHED_QCHAIN_SEL, 1 << qid);
7344 
7345 	/* Enable aggregation for the queue. */
7346 	iwn_prph_setbits(sc, IWN5000_SCHED_AGGR_SEL, 1 << qid);
7347 
7348 	/* Set starting sequence number from the ADDBA request. */
7349 	sc->txq[qid].cur = sc->txq[qid].read = (ssn & 0xff);
7350 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | (ssn & 0xff));
7351 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_RDPTR(qid), ssn);
7352 
7353 	/* Set scheduler window size and frame limit. */
7354 	iwn_mem_write(sc, sc->sched_base + IWN5000_SCHED_QUEUE_OFFSET(qid) + 4,
7355 	    IWN_SCHED_LIMIT << 16 | IWN_SCHED_WINSZ);
7356 
7357 	/* Enable interrupts for the queue. */
7358 	iwn_prph_setbits(sc, IWN5000_SCHED_INTR_MASK, 1 << qid);
7359 
7360 	/* Mark the queue as active. */
7361 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
7362 	    IWN5000_TXQ_STATUS_ACTIVE | iwn_tid2fifo[tid]);
7363 }
7364 
7365 static void
7366 iwn5000_ampdu_tx_stop(struct iwn_softc *sc, int qid, uint8_t tid, uint16_t ssn)
7367 {
7368 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7369 
7370 	/* Stop TX scheduler while we're changing its configuration. */
7371 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
7372 	    IWN5000_TXQ_STATUS_CHGACT);
7373 
7374 	/* Disable aggregation for the queue. */
7375 	iwn_prph_clrbits(sc, IWN5000_SCHED_AGGR_SEL, 1 << qid);
7376 
7377 	/* Set starting sequence number from the ADDBA request. */
7378 	IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | (ssn & 0xff));
7379 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_RDPTR(qid), ssn);
7380 
7381 	/* Disable interrupts for the queue. */
7382 	iwn_prph_clrbits(sc, IWN5000_SCHED_INTR_MASK, 1 << qid);
7383 
7384 	/* Mark the queue as inactive. */
7385 	iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
7386 	    IWN5000_TXQ_STATUS_INACTIVE | iwn_tid2fifo[tid]);
7387 }
7388 
7389 /*
7390  * Query calibration tables from the initialization firmware.  We do this
7391  * only once at first boot.  Called from a process context.
7392  */
7393 static int
7394 iwn5000_query_calibration(struct iwn_softc *sc)
7395 {
7396 	struct iwn5000_calib_config cmd;
7397 	int error;
7398 
7399 	memset(&cmd, 0, sizeof cmd);
7400 	cmd.ucode.once.enable = htole32(0xffffffff);
7401 	cmd.ucode.once.start  = htole32(0xffffffff);
7402 	cmd.ucode.once.send   = htole32(0xffffffff);
7403 	cmd.ucode.flags       = htole32(0xffffffff);
7404 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "%s: sending calibration query\n",
7405 	    __func__);
7406 	error = iwn_cmd(sc, IWN5000_CMD_CALIB_CONFIG, &cmd, sizeof cmd, 0);
7407 	if (error != 0)
7408 		return error;
7409 
7410 	/* Wait at most two seconds for calibration to complete. */
7411 	if (!(sc->sc_flags & IWN_FLAG_CALIB_DONE))
7412 		error = msleep(sc, &sc->sc_mtx, PCATCH, "iwncal", 2 * hz);
7413 	return error;
7414 }
7415 
7416 /*
7417  * Send calibration results to the runtime firmware.  These results were
7418  * obtained on first boot from the initialization firmware.
7419  */
7420 static int
7421 iwn5000_send_calibration(struct iwn_softc *sc)
7422 {
7423 	int idx, error;
7424 
7425 	for (idx = 0; idx < IWN5000_PHY_CALIB_MAX_RESULT; idx++) {
7426 		if (!(sc->base_params->calib_need & (1<<idx))) {
7427 			DPRINTF(sc, IWN_DEBUG_CALIBRATE,
7428 			    "No need of calib %d\n",
7429 			    idx);
7430 			continue; /* no need for this calib */
7431 		}
7432 		if (sc->calibcmd[idx].buf == NULL) {
7433 			DPRINTF(sc, IWN_DEBUG_CALIBRATE,
7434 			    "Need calib idx : %d but no available data\n",
7435 			    idx);
7436 			continue;
7437 		}
7438 
7439 		DPRINTF(sc, IWN_DEBUG_CALIBRATE,
7440 		    "send calibration result idx=%d len=%d\n", idx,
7441 		    sc->calibcmd[idx].len);
7442 		error = iwn_cmd(sc, IWN_CMD_PHY_CALIB, sc->calibcmd[idx].buf,
7443 		    sc->calibcmd[idx].len, 0);
7444 		if (error != 0) {
7445 			device_printf(sc->sc_dev,
7446 			    "%s: could not send calibration result, error %d\n",
7447 			    __func__, error);
7448 			return error;
7449 		}
7450 	}
7451 	return 0;
7452 }
7453 
7454 static int
7455 iwn5000_send_wimax_coex(struct iwn_softc *sc)
7456 {
7457 	struct iwn5000_wimax_coex wimax;
7458 
7459 #if 0
7460 	if (sc->hw_type == IWN_HW_REV_TYPE_6050) {
7461 		/* Enable WiMAX coexistence for combo adapters. */
7462 		wimax.flags =
7463 		    IWN_WIMAX_COEX_ASSOC_WA_UNMASK |
7464 		    IWN_WIMAX_COEX_UNASSOC_WA_UNMASK |
7465 		    IWN_WIMAX_COEX_STA_TABLE_VALID |
7466 		    IWN_WIMAX_COEX_ENABLE;
7467 		memcpy(wimax.events, iwn6050_wimax_events,
7468 		    sizeof iwn6050_wimax_events);
7469 	} else
7470 #endif
7471 	{
7472 		/* Disable WiMAX coexistence. */
7473 		wimax.flags = 0;
7474 		memset(wimax.events, 0, sizeof wimax.events);
7475 	}
7476 	DPRINTF(sc, IWN_DEBUG_RESET, "%s: Configuring WiMAX coexistence\n",
7477 	    __func__);
7478 	return iwn_cmd(sc, IWN5000_CMD_WIMAX_COEX, &wimax, sizeof wimax, 0);
7479 }
7480 
7481 static int
7482 iwn5000_crystal_calib(struct iwn_softc *sc)
7483 {
7484 	struct iwn5000_phy_calib_crystal cmd;
7485 
7486 	memset(&cmd, 0, sizeof cmd);
7487 	cmd.code = IWN5000_PHY_CALIB_CRYSTAL;
7488 	cmd.ngroups = 1;
7489 	cmd.isvalid = 1;
7490 	cmd.cap_pin[0] = le32toh(sc->eeprom_crystal) & 0xff;
7491 	cmd.cap_pin[1] = (le32toh(sc->eeprom_crystal) >> 16) & 0xff;
7492 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "sending crystal calibration %d, %d\n",
7493 	    cmd.cap_pin[0], cmd.cap_pin[1]);
7494 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 0);
7495 }
7496 
7497 static int
7498 iwn5000_temp_offset_calib(struct iwn_softc *sc)
7499 {
7500 	struct iwn5000_phy_calib_temp_offset cmd;
7501 
7502 	memset(&cmd, 0, sizeof cmd);
7503 	cmd.code = IWN5000_PHY_CALIB_TEMP_OFFSET;
7504 	cmd.ngroups = 1;
7505 	cmd.isvalid = 1;
7506 	if (sc->eeprom_temp != 0)
7507 		cmd.offset = htole16(sc->eeprom_temp);
7508 	else
7509 		cmd.offset = htole16(IWN_DEFAULT_TEMP_OFFSET);
7510 	DPRINTF(sc, IWN_DEBUG_CALIBRATE, "setting radio sensor offset to %d\n",
7511 	    le16toh(cmd.offset));
7512 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 0);
7513 }
7514 
7515 static int
7516 iwn5000_temp_offset_calibv2(struct iwn_softc *sc)
7517 {
7518 	struct iwn5000_phy_calib_temp_offsetv2 cmd;
7519 
7520 	memset(&cmd, 0, sizeof cmd);
7521 	cmd.code = IWN5000_PHY_CALIB_TEMP_OFFSET;
7522 	cmd.ngroups = 1;
7523 	cmd.isvalid = 1;
7524 	if (sc->eeprom_temp != 0) {
7525 		cmd.offset_low = htole16(sc->eeprom_temp);
7526 		cmd.offset_high = htole16(sc->eeprom_temp_high);
7527 	} else {
7528 		cmd.offset_low = htole16(IWN_DEFAULT_TEMP_OFFSET);
7529 		cmd.offset_high = htole16(IWN_DEFAULT_TEMP_OFFSET);
7530 	}
7531 	cmd.burnt_voltage_ref = htole16(sc->eeprom_voltage);
7532 
7533 	DPRINTF(sc, IWN_DEBUG_CALIBRATE,
7534 	    "setting radio sensor low offset to %d, high offset to %d, voltage to %d\n",
7535 	    le16toh(cmd.offset_low),
7536 	    le16toh(cmd.offset_high),
7537 	    le16toh(cmd.burnt_voltage_ref));
7538 
7539 	return iwn_cmd(sc, IWN_CMD_PHY_CALIB, &cmd, sizeof cmd, 0);
7540 }
7541 
7542 /*
7543  * This function is called after the runtime firmware notifies us of its
7544  * readiness (called in a process context).
7545  */
7546 static int
7547 iwn4965_post_alive(struct iwn_softc *sc)
7548 {
7549 	int error, qid;
7550 
7551 	if ((error = iwn_nic_lock(sc)) != 0)
7552 		return error;
7553 
7554 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7555 
7556 	/* Clear TX scheduler state in SRAM. */
7557 	sc->sched_base = iwn_prph_read(sc, IWN_SCHED_SRAM_ADDR);
7558 	iwn_mem_set_region_4(sc, sc->sched_base + IWN4965_SCHED_CTX_OFF, 0,
7559 	    IWN4965_SCHED_CTX_LEN / sizeof (uint32_t));
7560 
7561 	/* Set physical address of TX scheduler rings (1KB aligned). */
7562 	iwn_prph_write(sc, IWN4965_SCHED_DRAM_ADDR, sc->sched_dma.paddr >> 10);
7563 
7564 	IWN_SETBITS(sc, IWN_FH_TX_CHICKEN, IWN_FH_TX_CHICKEN_SCHED_RETRY);
7565 
7566 	/* Disable chain mode for all our 16 queues. */
7567 	iwn_prph_write(sc, IWN4965_SCHED_QCHAIN_SEL, 0);
7568 
7569 	for (qid = 0; qid < IWN4965_NTXQUEUES; qid++) {
7570 		iwn_prph_write(sc, IWN4965_SCHED_QUEUE_RDPTR(qid), 0);
7571 		IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | 0);
7572 
7573 		/* Set scheduler window size. */
7574 		iwn_mem_write(sc, sc->sched_base +
7575 		    IWN4965_SCHED_QUEUE_OFFSET(qid), IWN_SCHED_WINSZ);
7576 		/* Set scheduler frame limit. */
7577 		iwn_mem_write(sc, sc->sched_base +
7578 		    IWN4965_SCHED_QUEUE_OFFSET(qid) + 4,
7579 		    IWN_SCHED_LIMIT << 16);
7580 	}
7581 
7582 	/* Enable interrupts for all our 16 queues. */
7583 	iwn_prph_write(sc, IWN4965_SCHED_INTR_MASK, 0xffff);
7584 	/* Identify TX FIFO rings (0-7). */
7585 	iwn_prph_write(sc, IWN4965_SCHED_TXFACT, 0xff);
7586 
7587 	/* Mark TX rings (4 EDCA + cmd + 2 HCCA) as active. */
7588 	for (qid = 0; qid < 7; qid++) {
7589 		static uint8_t qid2fifo[] = { 3, 2, 1, 0, 4, 5, 6 };
7590 		iwn_prph_write(sc, IWN4965_SCHED_QUEUE_STATUS(qid),
7591 		    IWN4965_TXQ_STATUS_ACTIVE | qid2fifo[qid] << 1);
7592 	}
7593 	iwn_nic_unlock(sc);
7594 	return 0;
7595 }
7596 
7597 /*
7598  * This function is called after the initialization or runtime firmware
7599  * notifies us of its readiness (called in a process context).
7600  */
7601 static int
7602 iwn5000_post_alive(struct iwn_softc *sc)
7603 {
7604 	int error, qid;
7605 
7606 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
7607 
7608 	/* Switch to using ICT interrupt mode. */
7609 	iwn5000_ict_reset(sc);
7610 
7611 	if ((error = iwn_nic_lock(sc)) != 0){
7612 		DPRINTF(sc, IWN_DEBUG_TRACE, "->%s end in error\n", __func__);
7613 		return error;
7614 	}
7615 
7616 	/* Clear TX scheduler state in SRAM. */
7617 	sc->sched_base = iwn_prph_read(sc, IWN_SCHED_SRAM_ADDR);
7618 	iwn_mem_set_region_4(sc, sc->sched_base + IWN5000_SCHED_CTX_OFF, 0,
7619 	    IWN5000_SCHED_CTX_LEN / sizeof (uint32_t));
7620 
7621 	/* Set physical address of TX scheduler rings (1KB aligned). */
7622 	iwn_prph_write(sc, IWN5000_SCHED_DRAM_ADDR, sc->sched_dma.paddr >> 10);
7623 
7624 	IWN_SETBITS(sc, IWN_FH_TX_CHICKEN, IWN_FH_TX_CHICKEN_SCHED_RETRY);
7625 
7626 	/* Enable chain mode for all queues, except command queue. */
7627 	if (sc->sc_flags & IWN_FLAG_PAN_SUPPORT)
7628 		iwn_prph_write(sc, IWN5000_SCHED_QCHAIN_SEL, 0xfffdf);
7629 	else
7630 		iwn_prph_write(sc, IWN5000_SCHED_QCHAIN_SEL, 0xfffef);
7631 	iwn_prph_write(sc, IWN5000_SCHED_AGGR_SEL, 0);
7632 
7633 	for (qid = 0; qid < IWN5000_NTXQUEUES; qid++) {
7634 		iwn_prph_write(sc, IWN5000_SCHED_QUEUE_RDPTR(qid), 0);
7635 		IWN_WRITE(sc, IWN_HBUS_TARG_WRPTR, qid << 8 | 0);
7636 
7637 		iwn_mem_write(sc, sc->sched_base +
7638 		    IWN5000_SCHED_QUEUE_OFFSET(qid), 0);
7639 		/* Set scheduler window size and frame limit. */
7640 		iwn_mem_write(sc, sc->sched_base +
7641 		    IWN5000_SCHED_QUEUE_OFFSET(qid) + 4,
7642 		    IWN_SCHED_LIMIT << 16 | IWN_SCHED_WINSZ);
7643 	}
7644 
7645 	/* Enable interrupts for all our 20 queues. */
7646 	iwn_prph_write(sc, IWN5000_SCHED_INTR_MASK, 0xfffff);
7647 	/* Identify TX FIFO rings (0-7). */
7648 	iwn_prph_write(sc, IWN5000_SCHED_TXFACT, 0xff);
7649 
7650 	/* Mark TX rings (4 EDCA + cmd + 2 HCCA) as active. */
7651 	if (sc->sc_flags & IWN_FLAG_PAN_SUPPORT) {
7652 		/* Mark TX rings as active. */
7653 		for (qid = 0; qid < 11; qid++) {
7654 			static uint8_t qid2fifo[] = { 3, 2, 1, 0, 0, 4, 2, 5, 4, 7, 5 };
7655 			iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
7656 			    IWN5000_TXQ_STATUS_ACTIVE | qid2fifo[qid]);
7657 		}
7658 	} else {
7659 		/* Mark TX rings (4 EDCA + cmd + 2 HCCA) as active. */
7660 		for (qid = 0; qid < 7; qid++) {
7661 			static uint8_t qid2fifo[] = { 3, 2, 1, 0, 7, 5, 6 };
7662 			iwn_prph_write(sc, IWN5000_SCHED_QUEUE_STATUS(qid),
7663 			    IWN5000_TXQ_STATUS_ACTIVE | qid2fifo[qid]);
7664 		}
7665 	}
7666 	iwn_nic_unlock(sc);
7667 
7668 	/* Configure WiMAX coexistence for combo adapters. */
7669 	error = iwn5000_send_wimax_coex(sc);
7670 	if (error != 0) {
7671 		device_printf(sc->sc_dev,
7672 		    "%s: could not configure WiMAX coexistence, error %d\n",
7673 		    __func__, error);
7674 		return error;
7675 	}
7676 	if (sc->hw_type != IWN_HW_REV_TYPE_5150) {
7677 		/* Perform crystal calibration. */
7678 		error = iwn5000_crystal_calib(sc);
7679 		if (error != 0) {
7680 			device_printf(sc->sc_dev,
7681 			    "%s: crystal calibration failed, error %d\n",
7682 			    __func__, error);
7683 			return error;
7684 		}
7685 	}
7686 	if (!(sc->sc_flags & IWN_FLAG_CALIB_DONE)) {
7687 		/* Query calibration from the initialization firmware. */
7688 		if ((error = iwn5000_query_calibration(sc)) != 0) {
7689 			device_printf(sc->sc_dev,
7690 			    "%s: could not query calibration, error %d\n",
7691 			    __func__, error);
7692 			return error;
7693 		}
7694 		/*
7695 		 * We have the calibration results now, reboot with the
7696 		 * runtime firmware (call ourselves recursively!)
7697 		 */
7698 		iwn_hw_stop(sc);
7699 		error = iwn_hw_init(sc);
7700 	} else {
7701 		/* Send calibration results to runtime firmware. */
7702 		error = iwn5000_send_calibration(sc);
7703 	}
7704 
7705 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
7706 
7707 	return error;
7708 }
7709 
7710 /*
7711  * The firmware boot code is small and is intended to be copied directly into
7712  * the NIC internal memory (no DMA transfer).
7713  */
7714 static int
7715 iwn4965_load_bootcode(struct iwn_softc *sc, const uint8_t *ucode, int size)
7716 {
7717 	int error, ntries;
7718 
7719 	size /= sizeof (uint32_t);
7720 
7721 	if ((error = iwn_nic_lock(sc)) != 0)
7722 		return error;
7723 
7724 	/* Copy microcode image into NIC memory. */
7725 	iwn_prph_write_region_4(sc, IWN_BSM_SRAM_BASE,
7726 	    (const uint32_t *)ucode, size);
7727 
7728 	iwn_prph_write(sc, IWN_BSM_WR_MEM_SRC, 0);
7729 	iwn_prph_write(sc, IWN_BSM_WR_MEM_DST, IWN_FW_TEXT_BASE);
7730 	iwn_prph_write(sc, IWN_BSM_WR_DWCOUNT, size);
7731 
7732 	/* Start boot load now. */
7733 	iwn_prph_write(sc, IWN_BSM_WR_CTRL, IWN_BSM_WR_CTRL_START);
7734 
7735 	/* Wait for transfer to complete. */
7736 	for (ntries = 0; ntries < 1000; ntries++) {
7737 		if (!(iwn_prph_read(sc, IWN_BSM_WR_CTRL) &
7738 		    IWN_BSM_WR_CTRL_START))
7739 			break;
7740 		DELAY(10);
7741 	}
7742 	if (ntries == 1000) {
7743 		device_printf(sc->sc_dev, "%s: could not load boot firmware\n",
7744 		    __func__);
7745 		iwn_nic_unlock(sc);
7746 		return ETIMEDOUT;
7747 	}
7748 
7749 	/* Enable boot after power up. */
7750 	iwn_prph_write(sc, IWN_BSM_WR_CTRL, IWN_BSM_WR_CTRL_START_EN);
7751 
7752 	iwn_nic_unlock(sc);
7753 	return 0;
7754 }
7755 
7756 static int
7757 iwn4965_load_firmware(struct iwn_softc *sc)
7758 {
7759 	struct iwn_fw_info *fw = &sc->fw;
7760 	struct iwn_dma_info *dma = &sc->fw_dma;
7761 	int error;
7762 
7763 	/* Copy initialization sections into pre-allocated DMA-safe memory. */
7764 	memcpy(dma->vaddr, fw->init.data, fw->init.datasz);
7765 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
7766 	memcpy(dma->vaddr + IWN4965_FW_DATA_MAXSZ,
7767 	    fw->init.text, fw->init.textsz);
7768 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
7769 
7770 	/* Tell adapter where to find initialization sections. */
7771 	if ((error = iwn_nic_lock(sc)) != 0)
7772 		return error;
7773 	iwn_prph_write(sc, IWN_BSM_DRAM_DATA_ADDR, dma->paddr >> 4);
7774 	iwn_prph_write(sc, IWN_BSM_DRAM_DATA_SIZE, fw->init.datasz);
7775 	iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_ADDR,
7776 	    (dma->paddr + IWN4965_FW_DATA_MAXSZ) >> 4);
7777 	iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_SIZE, fw->init.textsz);
7778 	iwn_nic_unlock(sc);
7779 
7780 	/* Load firmware boot code. */
7781 	error = iwn4965_load_bootcode(sc, fw->boot.text, fw->boot.textsz);
7782 	if (error != 0) {
7783 		device_printf(sc->sc_dev, "%s: could not load boot firmware\n",
7784 		    __func__);
7785 		return error;
7786 	}
7787 	/* Now press "execute". */
7788 	IWN_WRITE(sc, IWN_RESET, 0);
7789 
7790 	/* Wait at most one second for first alive notification. */
7791 	if ((error = msleep(sc, &sc->sc_mtx, PCATCH, "iwninit", hz)) != 0) {
7792 		device_printf(sc->sc_dev,
7793 		    "%s: timeout waiting for adapter to initialize, error %d\n",
7794 		    __func__, error);
7795 		return error;
7796 	}
7797 
7798 	/* Retrieve current temperature for initial TX power calibration. */
7799 	sc->rawtemp = sc->ucode_info.temp[3].chan20MHz;
7800 	sc->temp = iwn4965_get_temperature(sc);
7801 
7802 	/* Copy runtime sections into pre-allocated DMA-safe memory. */
7803 	memcpy(dma->vaddr, fw->main.data, fw->main.datasz);
7804 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
7805 	memcpy(dma->vaddr + IWN4965_FW_DATA_MAXSZ,
7806 	    fw->main.text, fw->main.textsz);
7807 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
7808 
7809 	/* Tell adapter where to find runtime sections. */
7810 	if ((error = iwn_nic_lock(sc)) != 0)
7811 		return error;
7812 	iwn_prph_write(sc, IWN_BSM_DRAM_DATA_ADDR, dma->paddr >> 4);
7813 	iwn_prph_write(sc, IWN_BSM_DRAM_DATA_SIZE, fw->main.datasz);
7814 	iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_ADDR,
7815 	    (dma->paddr + IWN4965_FW_DATA_MAXSZ) >> 4);
7816 	iwn_prph_write(sc, IWN_BSM_DRAM_TEXT_SIZE,
7817 	    IWN_FW_UPDATED | fw->main.textsz);
7818 	iwn_nic_unlock(sc);
7819 
7820 	return 0;
7821 }
7822 
7823 static int
7824 iwn5000_load_firmware_section(struct iwn_softc *sc, uint32_t dst,
7825     const uint8_t *section, int size)
7826 {
7827 	struct iwn_dma_info *dma = &sc->fw_dma;
7828 	int error;
7829 
7830 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7831 
7832 	/* Copy firmware section into pre-allocated DMA-safe memory. */
7833 	memcpy(dma->vaddr, section, size);
7834 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
7835 
7836 	if ((error = iwn_nic_lock(sc)) != 0)
7837 		return error;
7838 
7839 	IWN_WRITE(sc, IWN_FH_TX_CONFIG(IWN_SRVC_DMACHNL),
7840 	    IWN_FH_TX_CONFIG_DMA_PAUSE);
7841 
7842 	IWN_WRITE(sc, IWN_FH_SRAM_ADDR(IWN_SRVC_DMACHNL), dst);
7843 	IWN_WRITE(sc, IWN_FH_TFBD_CTRL0(IWN_SRVC_DMACHNL),
7844 	    IWN_LOADDR(dma->paddr));
7845 	IWN_WRITE(sc, IWN_FH_TFBD_CTRL1(IWN_SRVC_DMACHNL),
7846 	    IWN_HIADDR(dma->paddr) << 28 | size);
7847 	IWN_WRITE(sc, IWN_FH_TXBUF_STATUS(IWN_SRVC_DMACHNL),
7848 	    IWN_FH_TXBUF_STATUS_TBNUM(1) |
7849 	    IWN_FH_TXBUF_STATUS_TBIDX(1) |
7850 	    IWN_FH_TXBUF_STATUS_TFBD_VALID);
7851 
7852 	/* Kick Flow Handler to start DMA transfer. */
7853 	IWN_WRITE(sc, IWN_FH_TX_CONFIG(IWN_SRVC_DMACHNL),
7854 	    IWN_FH_TX_CONFIG_DMA_ENA | IWN_FH_TX_CONFIG_CIRQ_HOST_ENDTFD);
7855 
7856 	iwn_nic_unlock(sc);
7857 
7858 	/* Wait at most five seconds for FH DMA transfer to complete. */
7859 	return msleep(sc, &sc->sc_mtx, PCATCH, "iwninit", 5 * hz);
7860 }
7861 
7862 static int
7863 iwn5000_load_firmware(struct iwn_softc *sc)
7864 {
7865 	struct iwn_fw_part *fw;
7866 	int error;
7867 
7868 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
7869 
7870 	/* Load the initialization firmware on first boot only. */
7871 	fw = (sc->sc_flags & IWN_FLAG_CALIB_DONE) ?
7872 	    &sc->fw.main : &sc->fw.init;
7873 
7874 	error = iwn5000_load_firmware_section(sc, IWN_FW_TEXT_BASE,
7875 	    fw->text, fw->textsz);
7876 	if (error != 0) {
7877 		device_printf(sc->sc_dev,
7878 		    "%s: could not load firmware %s section, error %d\n",
7879 		    __func__, ".text", error);
7880 		return error;
7881 	}
7882 	error = iwn5000_load_firmware_section(sc, IWN_FW_DATA_BASE,
7883 	    fw->data, fw->datasz);
7884 	if (error != 0) {
7885 		device_printf(sc->sc_dev,
7886 		    "%s: could not load firmware %s section, error %d\n",
7887 		    __func__, ".data", error);
7888 		return error;
7889 	}
7890 
7891 	/* Now press "execute". */
7892 	IWN_WRITE(sc, IWN_RESET, 0);
7893 	return 0;
7894 }
7895 
7896 /*
7897  * Extract text and data sections from a legacy firmware image.
7898  */
7899 static int
7900 iwn_read_firmware_leg(struct iwn_softc *sc, struct iwn_fw_info *fw)
7901 {
7902 	const uint32_t *ptr;
7903 	size_t hdrlen = 24;
7904 	uint32_t rev;
7905 
7906 	ptr = (const uint32_t *)fw->data;
7907 	rev = le32toh(*ptr++);
7908 
7909 	sc->ucode_rev = rev;
7910 
7911 	/* Check firmware API version. */
7912 	if (IWN_FW_API(rev) <= 1) {
7913 		device_printf(sc->sc_dev,
7914 		    "%s: bad firmware, need API version >=2\n", __func__);
7915 		return EINVAL;
7916 	}
7917 	if (IWN_FW_API(rev) >= 3) {
7918 		/* Skip build number (version 2 header). */
7919 		hdrlen += 4;
7920 		ptr++;
7921 	}
7922 	if (fw->size < hdrlen) {
7923 		device_printf(sc->sc_dev, "%s: firmware too short: %zu bytes\n",
7924 		    __func__, fw->size);
7925 		return EINVAL;
7926 	}
7927 	fw->main.textsz = le32toh(*ptr++);
7928 	fw->main.datasz = le32toh(*ptr++);
7929 	fw->init.textsz = le32toh(*ptr++);
7930 	fw->init.datasz = le32toh(*ptr++);
7931 	fw->boot.textsz = le32toh(*ptr++);
7932 
7933 	/* Check that all firmware sections fit. */
7934 	if (fw->size < hdrlen + fw->main.textsz + fw->main.datasz +
7935 	    fw->init.textsz + fw->init.datasz + fw->boot.textsz) {
7936 		device_printf(sc->sc_dev, "%s: firmware too short: %zu bytes\n",
7937 		    __func__, fw->size);
7938 		return EINVAL;
7939 	}
7940 
7941 	/* Get pointers to firmware sections. */
7942 	fw->main.text = (const uint8_t *)ptr;
7943 	fw->main.data = fw->main.text + fw->main.textsz;
7944 	fw->init.text = fw->main.data + fw->main.datasz;
7945 	fw->init.data = fw->init.text + fw->init.textsz;
7946 	fw->boot.text = fw->init.data + fw->init.datasz;
7947 	return 0;
7948 }
7949 
7950 /*
7951  * Extract text and data sections from a TLV firmware image.
7952  */
7953 static int
7954 iwn_read_firmware_tlv(struct iwn_softc *sc, struct iwn_fw_info *fw,
7955     uint16_t alt)
7956 {
7957 	const struct iwn_fw_tlv_hdr *hdr;
7958 	const struct iwn_fw_tlv *tlv;
7959 	const uint8_t *ptr, *end;
7960 	uint64_t altmask;
7961 	uint32_t len, tmp;
7962 
7963 	if (fw->size < sizeof (*hdr)) {
7964 		device_printf(sc->sc_dev, "%s: firmware too short: %zu bytes\n",
7965 		    __func__, fw->size);
7966 		return EINVAL;
7967 	}
7968 	hdr = (const struct iwn_fw_tlv_hdr *)fw->data;
7969 	if (hdr->signature != htole32(IWN_FW_SIGNATURE)) {
7970 		device_printf(sc->sc_dev, "%s: bad firmware signature 0x%08x\n",
7971 		    __func__, le32toh(hdr->signature));
7972 		return EINVAL;
7973 	}
7974 	DPRINTF(sc, IWN_DEBUG_RESET, "FW: \"%.64s\", build 0x%x\n", hdr->descr,
7975 	    le32toh(hdr->build));
7976 	sc->ucode_rev = le32toh(hdr->rev);
7977 
7978 	/*
7979 	 * Select the closest supported alternative that is less than
7980 	 * or equal to the specified one.
7981 	 */
7982 	altmask = le64toh(hdr->altmask);
7983 	while (alt > 0 && !(altmask & (1ULL << alt)))
7984 		alt--;	/* Downgrade. */
7985 	DPRINTF(sc, IWN_DEBUG_RESET, "using alternative %d\n", alt);
7986 
7987 	ptr = (const uint8_t *)(hdr + 1);
7988 	end = (const uint8_t *)(fw->data + fw->size);
7989 
7990 	/* Parse type-length-value fields. */
7991 	while (ptr + sizeof (*tlv) <= end) {
7992 		tlv = (const struct iwn_fw_tlv *)ptr;
7993 		len = le32toh(tlv->len);
7994 
7995 		ptr += sizeof (*tlv);
7996 		if (ptr + len > end) {
7997 			device_printf(sc->sc_dev,
7998 			    "%s: firmware too short: %zu bytes\n", __func__,
7999 			    fw->size);
8000 			return EINVAL;
8001 		}
8002 		/* Skip other alternatives. */
8003 		if (tlv->alt != 0 && tlv->alt != htole16(alt))
8004 			goto next;
8005 
8006 		switch (le16toh(tlv->type)) {
8007 		case IWN_FW_TLV_MAIN_TEXT:
8008 			fw->main.text = ptr;
8009 			fw->main.textsz = len;
8010 			break;
8011 		case IWN_FW_TLV_MAIN_DATA:
8012 			fw->main.data = ptr;
8013 			fw->main.datasz = len;
8014 			break;
8015 		case IWN_FW_TLV_INIT_TEXT:
8016 			fw->init.text = ptr;
8017 			fw->init.textsz = len;
8018 			break;
8019 		case IWN_FW_TLV_INIT_DATA:
8020 			fw->init.data = ptr;
8021 			fw->init.datasz = len;
8022 			break;
8023 		case IWN_FW_TLV_BOOT_TEXT:
8024 			fw->boot.text = ptr;
8025 			fw->boot.textsz = len;
8026 			break;
8027 		case IWN_FW_TLV_ENH_SENS:
8028 			if (!len)
8029 				sc->sc_flags |= IWN_FLAG_ENH_SENS;
8030 			break;
8031 		case IWN_FW_TLV_PHY_CALIB:
8032 			tmp = le32toh(*ptr);
8033 			if (tmp < 253) {
8034 				sc->reset_noise_gain = tmp;
8035 				sc->noise_gain = tmp + 1;
8036 			}
8037 			break;
8038 		case IWN_FW_TLV_PAN:
8039 			sc->sc_flags |= IWN_FLAG_PAN_SUPPORT;
8040 			DPRINTF(sc, IWN_DEBUG_RESET,
8041 			    "PAN Support found: %d\n", 1);
8042 			break;
8043 		case IWN_FW_TLV_FLAGS:
8044 			if (len < sizeof(uint32_t))
8045 				break;
8046 			if (len % sizeof(uint32_t))
8047 				break;
8048 			sc->tlv_feature_flags = le32toh(*ptr);
8049 			DPRINTF(sc, IWN_DEBUG_RESET,
8050 			    "%s: feature: 0x%08x\n",
8051 			    __func__,
8052 			    sc->tlv_feature_flags);
8053 			break;
8054 		case IWN_FW_TLV_PBREQ_MAXLEN:
8055 		case IWN_FW_TLV_RUNT_EVTLOG_PTR:
8056 		case IWN_FW_TLV_RUNT_EVTLOG_SIZE:
8057 		case IWN_FW_TLV_RUNT_ERRLOG_PTR:
8058 		case IWN_FW_TLV_INIT_EVTLOG_PTR:
8059 		case IWN_FW_TLV_INIT_EVTLOG_SIZE:
8060 		case IWN_FW_TLV_INIT_ERRLOG_PTR:
8061 		case IWN_FW_TLV_WOWLAN_INST:
8062 		case IWN_FW_TLV_WOWLAN_DATA:
8063 			DPRINTF(sc, IWN_DEBUG_RESET,
8064 			    "TLV type %d recognized but not handled\n",
8065 			    le16toh(tlv->type));
8066 			break;
8067 		default:
8068 			DPRINTF(sc, IWN_DEBUG_RESET,
8069 			    "TLV type %d not handled\n", le16toh(tlv->type));
8070 			break;
8071 		}
8072  next:		/* TLV fields are 32-bit aligned. */
8073 		ptr += (len + 3) & ~3;
8074 	}
8075 	return 0;
8076 }
8077 
8078 static int
8079 iwn_read_firmware(struct iwn_softc *sc)
8080 {
8081 	struct iwn_fw_info *fw = &sc->fw;
8082 	int error;
8083 
8084 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
8085 
8086 	IWN_UNLOCK(sc);
8087 
8088 	memset(fw, 0, sizeof (*fw));
8089 
8090 	/* Read firmware image from filesystem. */
8091 	sc->fw_fp = firmware_get(sc->fwname);
8092 	if (sc->fw_fp == NULL) {
8093 		device_printf(sc->sc_dev, "%s: could not read firmware %s\n",
8094 		    __func__, sc->fwname);
8095 		IWN_LOCK(sc);
8096 		return EINVAL;
8097 	}
8098 	IWN_LOCK(sc);
8099 
8100 	fw->size = sc->fw_fp->datasize;
8101 	fw->data = (const uint8_t *)sc->fw_fp->data;
8102 	if (fw->size < sizeof (uint32_t)) {
8103 		device_printf(sc->sc_dev, "%s: firmware too short: %zu bytes\n",
8104 		    __func__, fw->size);
8105 		firmware_put(sc->fw_fp, FIRMWARE_UNLOAD);
8106 		sc->fw_fp = NULL;
8107 		return EINVAL;
8108 	}
8109 
8110 	/* Retrieve text and data sections. */
8111 	if (*(const uint32_t *)fw->data != 0)	/* Legacy image. */
8112 		error = iwn_read_firmware_leg(sc, fw);
8113 	else
8114 		error = iwn_read_firmware_tlv(sc, fw, 1);
8115 	if (error != 0) {
8116 		device_printf(sc->sc_dev,
8117 		    "%s: could not read firmware sections, error %d\n",
8118 		    __func__, error);
8119 		firmware_put(sc->fw_fp, FIRMWARE_UNLOAD);
8120 		sc->fw_fp = NULL;
8121 		return error;
8122 	}
8123 
8124 	device_printf(sc->sc_dev, "%s: ucode rev=0x%08x\n", __func__, sc->ucode_rev);
8125 
8126 	/* Make sure text and data sections fit in hardware memory. */
8127 	if (fw->main.textsz > sc->fw_text_maxsz ||
8128 	    fw->main.datasz > sc->fw_data_maxsz ||
8129 	    fw->init.textsz > sc->fw_text_maxsz ||
8130 	    fw->init.datasz > sc->fw_data_maxsz ||
8131 	    fw->boot.textsz > IWN_FW_BOOT_TEXT_MAXSZ ||
8132 	    (fw->boot.textsz & 3) != 0) {
8133 		device_printf(sc->sc_dev, "%s: firmware sections too large\n",
8134 		    __func__);
8135 		firmware_put(sc->fw_fp, FIRMWARE_UNLOAD);
8136 		sc->fw_fp = NULL;
8137 		return EINVAL;
8138 	}
8139 
8140 	/* We can proceed with loading the firmware. */
8141 	return 0;
8142 }
8143 
8144 static int
8145 iwn_clock_wait(struct iwn_softc *sc)
8146 {
8147 	int ntries;
8148 
8149 	/* Set "initialization complete" bit. */
8150 	IWN_SETBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_INIT_DONE);
8151 
8152 	/* Wait for clock stabilization. */
8153 	for (ntries = 0; ntries < 2500; ntries++) {
8154 		if (IWN_READ(sc, IWN_GP_CNTRL) & IWN_GP_CNTRL_MAC_CLOCK_READY)
8155 			return 0;
8156 		DELAY(10);
8157 	}
8158 	device_printf(sc->sc_dev,
8159 	    "%s: timeout waiting for clock stabilization\n", __func__);
8160 	return ETIMEDOUT;
8161 }
8162 
8163 static int
8164 iwn_apm_init(struct iwn_softc *sc)
8165 {
8166 	uint32_t reg;
8167 	int error;
8168 
8169 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
8170 
8171 	/* Disable L0s exit timer (NMI bug workaround). */
8172 	IWN_SETBITS(sc, IWN_GIO_CHICKEN, IWN_GIO_CHICKEN_DIS_L0S_TIMER);
8173 	/* Don't wait for ICH L0s (ICH bug workaround). */
8174 	IWN_SETBITS(sc, IWN_GIO_CHICKEN, IWN_GIO_CHICKEN_L1A_NO_L0S_RX);
8175 
8176 	/* Set FH wait threshold to max (HW bug under stress workaround). */
8177 	IWN_SETBITS(sc, IWN_DBG_HPET_MEM, 0xffff0000);
8178 
8179 	/* Enable HAP INTA to move adapter from L1a to L0s. */
8180 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_HAP_WAKE_L1A);
8181 
8182 	/* Retrieve PCIe Active State Power Management (ASPM). */
8183 	reg = pci_read_config(sc->sc_dev, sc->sc_cap_off + 0x10, 1);
8184 	/* Workaround for HW instability in PCIe L0->L0s->L1 transition. */
8185 	if (reg & 0x02)	/* L1 Entry enabled. */
8186 		IWN_SETBITS(sc, IWN_GIO, IWN_GIO_L0S_ENA);
8187 	else
8188 		IWN_CLRBITS(sc, IWN_GIO, IWN_GIO_L0S_ENA);
8189 
8190 	if (sc->base_params->pll_cfg_val)
8191 		IWN_SETBITS(sc, IWN_ANA_PLL, sc->base_params->pll_cfg_val);
8192 
8193 	/* Wait for clock stabilization before accessing prph. */
8194 	if ((error = iwn_clock_wait(sc)) != 0)
8195 		return error;
8196 
8197 	if ((error = iwn_nic_lock(sc)) != 0)
8198 		return error;
8199 	if (sc->hw_type == IWN_HW_REV_TYPE_4965) {
8200 		/* Enable DMA and BSM (Bootstrap State Machine). */
8201 		iwn_prph_write(sc, IWN_APMG_CLK_EN,
8202 		    IWN_APMG_CLK_CTRL_DMA_CLK_RQT |
8203 		    IWN_APMG_CLK_CTRL_BSM_CLK_RQT);
8204 	} else {
8205 		/* Enable DMA. */
8206 		iwn_prph_write(sc, IWN_APMG_CLK_EN,
8207 		    IWN_APMG_CLK_CTRL_DMA_CLK_RQT);
8208 	}
8209 	DELAY(20);
8210 	/* Disable L1-Active. */
8211 	iwn_prph_setbits(sc, IWN_APMG_PCI_STT, IWN_APMG_PCI_STT_L1A_DIS);
8212 	iwn_nic_unlock(sc);
8213 
8214 	return 0;
8215 }
8216 
8217 static void
8218 iwn_apm_stop_master(struct iwn_softc *sc)
8219 {
8220 	int ntries;
8221 
8222 	/* Stop busmaster DMA activity. */
8223 	IWN_SETBITS(sc, IWN_RESET, IWN_RESET_STOP_MASTER);
8224 	for (ntries = 0; ntries < 100; ntries++) {
8225 		if (IWN_READ(sc, IWN_RESET) & IWN_RESET_MASTER_DISABLED)
8226 			return;
8227 		DELAY(10);
8228 	}
8229 	device_printf(sc->sc_dev, "%s: timeout waiting for master\n", __func__);
8230 }
8231 
8232 static void
8233 iwn_apm_stop(struct iwn_softc *sc)
8234 {
8235 	iwn_apm_stop_master(sc);
8236 
8237 	/* Reset the entire device. */
8238 	IWN_SETBITS(sc, IWN_RESET, IWN_RESET_SW);
8239 	DELAY(10);
8240 	/* Clear "initialization complete" bit. */
8241 	IWN_CLRBITS(sc, IWN_GP_CNTRL, IWN_GP_CNTRL_INIT_DONE);
8242 }
8243 
8244 static int
8245 iwn4965_nic_config(struct iwn_softc *sc)
8246 {
8247 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
8248 
8249 	if (IWN_RFCFG_TYPE(sc->rfcfg) == 1) {
8250 		/*
8251 		 * I don't believe this to be correct but this is what the
8252 		 * vendor driver is doing. Probably the bits should not be
8253 		 * shifted in IWN_RFCFG_*.
8254 		 */
8255 		IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
8256 		    IWN_RFCFG_TYPE(sc->rfcfg) |
8257 		    IWN_RFCFG_STEP(sc->rfcfg) |
8258 		    IWN_RFCFG_DASH(sc->rfcfg));
8259 	}
8260 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
8261 	    IWN_HW_IF_CONFIG_RADIO_SI | IWN_HW_IF_CONFIG_MAC_SI);
8262 	return 0;
8263 }
8264 
8265 static int
8266 iwn5000_nic_config(struct iwn_softc *sc)
8267 {
8268 	uint32_t tmp;
8269 	int error;
8270 
8271 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
8272 
8273 	if (IWN_RFCFG_TYPE(sc->rfcfg) < 3) {
8274 		IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
8275 		    IWN_RFCFG_TYPE(sc->rfcfg) |
8276 		    IWN_RFCFG_STEP(sc->rfcfg) |
8277 		    IWN_RFCFG_DASH(sc->rfcfg));
8278 	}
8279 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG,
8280 	    IWN_HW_IF_CONFIG_RADIO_SI | IWN_HW_IF_CONFIG_MAC_SI);
8281 
8282 	if ((error = iwn_nic_lock(sc)) != 0)
8283 		return error;
8284 	iwn_prph_setbits(sc, IWN_APMG_PS, IWN_APMG_PS_EARLY_PWROFF_DIS);
8285 
8286 	if (sc->hw_type == IWN_HW_REV_TYPE_1000) {
8287 		/*
8288 		 * Select first Switching Voltage Regulator (1.32V) to
8289 		 * solve a stability issue related to noisy DC2DC line
8290 		 * in the silicon of 1000 Series.
8291 		 */
8292 		tmp = iwn_prph_read(sc, IWN_APMG_DIGITAL_SVR);
8293 		tmp &= ~IWN_APMG_DIGITAL_SVR_VOLTAGE_MASK;
8294 		tmp |= IWN_APMG_DIGITAL_SVR_VOLTAGE_1_32;
8295 		iwn_prph_write(sc, IWN_APMG_DIGITAL_SVR, tmp);
8296 	}
8297 	iwn_nic_unlock(sc);
8298 
8299 	if (sc->sc_flags & IWN_FLAG_INTERNAL_PA) {
8300 		/* Use internal power amplifier only. */
8301 		IWN_WRITE(sc, IWN_GP_DRIVER, IWN_GP_DRIVER_RADIO_2X2_IPA);
8302 	}
8303 	if (sc->base_params->additional_nic_config && sc->calib_ver >= 6) {
8304 		/* Indicate that ROM calibration version is >=6. */
8305 		IWN_SETBITS(sc, IWN_GP_DRIVER, IWN_GP_DRIVER_CALIB_VER6);
8306 	}
8307 	if (sc->base_params->additional_gp_drv_bit)
8308 		IWN_SETBITS(sc, IWN_GP_DRIVER,
8309 		    sc->base_params->additional_gp_drv_bit);
8310 	return 0;
8311 }
8312 
8313 /*
8314  * Take NIC ownership over Intel Active Management Technology (AMT).
8315  */
8316 static int
8317 iwn_hw_prepare(struct iwn_softc *sc)
8318 {
8319 	int ntries;
8320 
8321 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
8322 
8323 	/* Check if hardware is ready. */
8324 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_NIC_READY);
8325 	for (ntries = 0; ntries < 5; ntries++) {
8326 		if (IWN_READ(sc, IWN_HW_IF_CONFIG) &
8327 		    IWN_HW_IF_CONFIG_NIC_READY)
8328 			return 0;
8329 		DELAY(10);
8330 	}
8331 
8332 	/* Hardware not ready, force into ready state. */
8333 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_PREPARE);
8334 	for (ntries = 0; ntries < 15000; ntries++) {
8335 		if (!(IWN_READ(sc, IWN_HW_IF_CONFIG) &
8336 		    IWN_HW_IF_CONFIG_PREPARE_DONE))
8337 			break;
8338 		DELAY(10);
8339 	}
8340 	if (ntries == 15000)
8341 		return ETIMEDOUT;
8342 
8343 	/* Hardware should be ready now. */
8344 	IWN_SETBITS(sc, IWN_HW_IF_CONFIG, IWN_HW_IF_CONFIG_NIC_READY);
8345 	for (ntries = 0; ntries < 5; ntries++) {
8346 		if (IWN_READ(sc, IWN_HW_IF_CONFIG) &
8347 		    IWN_HW_IF_CONFIG_NIC_READY)
8348 			return 0;
8349 		DELAY(10);
8350 	}
8351 	return ETIMEDOUT;
8352 }
8353 
8354 static int
8355 iwn_hw_init(struct iwn_softc *sc)
8356 {
8357 	struct iwn_ops *ops = &sc->ops;
8358 	int error, chnl, qid;
8359 
8360 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
8361 
8362 	/* Clear pending interrupts. */
8363 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
8364 
8365 	if ((error = iwn_apm_init(sc)) != 0) {
8366 		device_printf(sc->sc_dev,
8367 		    "%s: could not power ON adapter, error %d\n", __func__,
8368 		    error);
8369 		return error;
8370 	}
8371 
8372 	/* Select VMAIN power source. */
8373 	if ((error = iwn_nic_lock(sc)) != 0)
8374 		return error;
8375 	iwn_prph_clrbits(sc, IWN_APMG_PS, IWN_APMG_PS_PWR_SRC_MASK);
8376 	iwn_nic_unlock(sc);
8377 
8378 	/* Perform adapter-specific initialization. */
8379 	if ((error = ops->nic_config(sc)) != 0)
8380 		return error;
8381 
8382 	/* Initialize RX ring. */
8383 	if ((error = iwn_nic_lock(sc)) != 0)
8384 		return error;
8385 	IWN_WRITE(sc, IWN_FH_RX_CONFIG, 0);
8386 	IWN_WRITE(sc, IWN_FH_RX_WPTR, 0);
8387 	/* Set physical address of RX ring (256-byte aligned). */
8388 	IWN_WRITE(sc, IWN_FH_RX_BASE, sc->rxq.desc_dma.paddr >> 8);
8389 	/* Set physical address of RX status (16-byte aligned). */
8390 	IWN_WRITE(sc, IWN_FH_STATUS_WPTR, sc->rxq.stat_dma.paddr >> 4);
8391 	/* Enable RX. */
8392 	IWN_WRITE(sc, IWN_FH_RX_CONFIG,
8393 	    IWN_FH_RX_CONFIG_ENA           |
8394 	    IWN_FH_RX_CONFIG_IGN_RXF_EMPTY |	/* HW bug workaround */
8395 	    IWN_FH_RX_CONFIG_IRQ_DST_HOST  |
8396 	    IWN_FH_RX_CONFIG_SINGLE_FRAME  |
8397 	    IWN_FH_RX_CONFIG_RB_TIMEOUT(0) |
8398 	    IWN_FH_RX_CONFIG_NRBD(IWN_RX_RING_COUNT_LOG));
8399 	iwn_nic_unlock(sc);
8400 	IWN_WRITE(sc, IWN_FH_RX_WPTR, (IWN_RX_RING_COUNT - 1) & ~7);
8401 
8402 	if ((error = iwn_nic_lock(sc)) != 0)
8403 		return error;
8404 
8405 	/* Initialize TX scheduler. */
8406 	iwn_prph_write(sc, sc->sched_txfact_addr, 0);
8407 
8408 	/* Set physical address of "keep warm" page (16-byte aligned). */
8409 	IWN_WRITE(sc, IWN_FH_KW_ADDR, sc->kw_dma.paddr >> 4);
8410 
8411 	/* Initialize TX rings. */
8412 	for (qid = 0; qid < sc->ntxqs; qid++) {
8413 		struct iwn_tx_ring *txq = &sc->txq[qid];
8414 
8415 		/* Set physical address of TX ring (256-byte aligned). */
8416 		IWN_WRITE(sc, IWN_FH_CBBC_QUEUE(qid),
8417 		    txq->desc_dma.paddr >> 8);
8418 	}
8419 	iwn_nic_unlock(sc);
8420 
8421 	/* Enable DMA channels. */
8422 	for (chnl = 0; chnl < sc->ndmachnls; chnl++) {
8423 		IWN_WRITE(sc, IWN_FH_TX_CONFIG(chnl),
8424 		    IWN_FH_TX_CONFIG_DMA_ENA |
8425 		    IWN_FH_TX_CONFIG_DMA_CREDIT_ENA);
8426 	}
8427 
8428 	/* Clear "radio off" and "commands blocked" bits. */
8429 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_RFKILL);
8430 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_CMD_BLOCKED);
8431 
8432 	/* Clear pending interrupts. */
8433 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
8434 	/* Enable interrupt coalescing. */
8435 	IWN_WRITE(sc, IWN_INT_COALESCING, 512 / 8);
8436 	/* Enable interrupts. */
8437 	IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
8438 
8439 	/* _Really_ make sure "radio off" bit is cleared! */
8440 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_RFKILL);
8441 	IWN_WRITE(sc, IWN_UCODE_GP1_CLR, IWN_UCODE_GP1_RFKILL);
8442 
8443 	/* Enable shadow registers. */
8444 	if (sc->base_params->shadow_reg_enable)
8445 		IWN_SETBITS(sc, IWN_SHADOW_REG_CTRL, 0x800fffff);
8446 
8447 	if ((error = ops->load_firmware(sc)) != 0) {
8448 		device_printf(sc->sc_dev,
8449 		    "%s: could not load firmware, error %d\n", __func__,
8450 		    error);
8451 		return error;
8452 	}
8453 	/* Wait at most one second for firmware alive notification. */
8454 	if ((error = msleep(sc, &sc->sc_mtx, PCATCH, "iwninit", hz)) != 0) {
8455 		device_printf(sc->sc_dev,
8456 		    "%s: timeout waiting for adapter to initialize, error %d\n",
8457 		    __func__, error);
8458 		return error;
8459 	}
8460 	/* Do post-firmware initialization. */
8461 
8462 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
8463 
8464 	return ops->post_alive(sc);
8465 }
8466 
8467 static void
8468 iwn_hw_stop(struct iwn_softc *sc)
8469 {
8470 	int chnl, qid, ntries;
8471 
8472 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
8473 
8474 	IWN_WRITE(sc, IWN_RESET, IWN_RESET_NEVO);
8475 
8476 	/* Disable interrupts. */
8477 	IWN_WRITE(sc, IWN_INT_MASK, 0);
8478 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
8479 	IWN_WRITE(sc, IWN_FH_INT, 0xffffffff);
8480 	sc->sc_flags &= ~IWN_FLAG_USE_ICT;
8481 
8482 	/* Make sure we no longer hold the NIC lock. */
8483 	iwn_nic_unlock(sc);
8484 
8485 	/* Stop TX scheduler. */
8486 	iwn_prph_write(sc, sc->sched_txfact_addr, 0);
8487 
8488 	/* Stop all DMA channels. */
8489 	if (iwn_nic_lock(sc) == 0) {
8490 		for (chnl = 0; chnl < sc->ndmachnls; chnl++) {
8491 			IWN_WRITE(sc, IWN_FH_TX_CONFIG(chnl), 0);
8492 			for (ntries = 0; ntries < 200; ntries++) {
8493 				if (IWN_READ(sc, IWN_FH_TX_STATUS) &
8494 				    IWN_FH_TX_STATUS_IDLE(chnl))
8495 					break;
8496 				DELAY(10);
8497 			}
8498 		}
8499 		iwn_nic_unlock(sc);
8500 	}
8501 
8502 	/* Stop RX ring. */
8503 	iwn_reset_rx_ring(sc, &sc->rxq);
8504 
8505 	/* Reset all TX rings. */
8506 	for (qid = 0; qid < sc->ntxqs; qid++)
8507 		iwn_reset_tx_ring(sc, &sc->txq[qid]);
8508 
8509 	if (iwn_nic_lock(sc) == 0) {
8510 		iwn_prph_write(sc, IWN_APMG_CLK_DIS,
8511 		    IWN_APMG_CLK_CTRL_DMA_CLK_RQT);
8512 		iwn_nic_unlock(sc);
8513 	}
8514 	DELAY(5);
8515 	/* Power OFF adapter. */
8516 	iwn_apm_stop(sc);
8517 }
8518 
8519 static void
8520 iwn_radio_on(void *arg0, int pending)
8521 {
8522 	struct iwn_softc *sc = arg0;
8523 	struct ifnet *ifp = sc->sc_ifp;
8524 	struct ieee80211com *ic = ifp->if_l2com;
8525 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
8526 
8527 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
8528 
8529 	if (vap != NULL) {
8530 		iwn_init(sc);
8531 		ieee80211_init(vap);
8532 	}
8533 }
8534 
8535 static void
8536 iwn_radio_off(void *arg0, int pending)
8537 {
8538 	struct iwn_softc *sc = arg0;
8539 	struct ifnet *ifp = sc->sc_ifp;
8540 	struct ieee80211com *ic = ifp->if_l2com;
8541 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
8542 
8543 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
8544 
8545 	iwn_stop(sc);
8546 	if (vap != NULL)
8547 		ieee80211_stop(vap);
8548 
8549 	/* Enable interrupts to get RF toggle notification. */
8550 	IWN_LOCK(sc);
8551 	IWN_WRITE(sc, IWN_INT, 0xffffffff);
8552 	IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
8553 	IWN_UNLOCK(sc);
8554 }
8555 
8556 static void
8557 iwn_panicked(void *arg0, int pending)
8558 {
8559 	struct iwn_softc *sc = arg0;
8560 	struct ifnet *ifp = sc->sc_ifp;
8561 	struct ieee80211com *ic = ifp->if_l2com;
8562 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
8563 	int error;
8564 
8565 	if (vap == NULL) {
8566 		printf("%s: null vap\n", __func__);
8567 		return;
8568 	}
8569 
8570 	device_printf(sc->sc_dev, "%s: controller panicked, iv_state = %d; "
8571 	    "resetting...\n", __func__, vap->iv_state);
8572 
8573 	IWN_LOCK(sc);
8574 
8575 	iwn_stop_locked(sc);
8576 	iwn_init_locked(sc);
8577 	if (vap->iv_state >= IEEE80211_S_AUTH &&
8578 	    (error = iwn_auth(sc, vap)) != 0) {
8579 		device_printf(sc->sc_dev,
8580 		    "%s: could not move to auth state\n", __func__);
8581 	}
8582 	if (vap->iv_state >= IEEE80211_S_RUN &&
8583 	    (error = iwn_run(sc, vap)) != 0) {
8584 		device_printf(sc->sc_dev,
8585 		    "%s: could not move to run state\n", __func__);
8586 	}
8587 
8588 	/* Only run start once the NIC is in a useful state, like associated */
8589 	iwn_start_locked(sc->sc_ifp);
8590 
8591 	IWN_UNLOCK(sc);
8592 }
8593 
8594 static void
8595 iwn_init_locked(struct iwn_softc *sc)
8596 {
8597 	struct ifnet *ifp = sc->sc_ifp;
8598 	int error;
8599 
8600 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s begin\n", __func__);
8601 
8602 	IWN_LOCK_ASSERT(sc);
8603 
8604 	if ((error = iwn_hw_prepare(sc)) != 0) {
8605 		device_printf(sc->sc_dev, "%s: hardware not ready, error %d\n",
8606 		    __func__, error);
8607 		goto fail;
8608 	}
8609 
8610 	/* Initialize interrupt mask to default value. */
8611 	sc->int_mask = IWN_INT_MASK_DEF;
8612 	sc->sc_flags &= ~IWN_FLAG_USE_ICT;
8613 
8614 	/* Check that the radio is not disabled by hardware switch. */
8615 	if (!(IWN_READ(sc, IWN_GP_CNTRL) & IWN_GP_CNTRL_RFKILL)) {
8616 		device_printf(sc->sc_dev,
8617 		    "radio is disabled by hardware switch\n");
8618 		/* Enable interrupts to get RF toggle notifications. */
8619 		IWN_WRITE(sc, IWN_INT, 0xffffffff);
8620 		IWN_WRITE(sc, IWN_INT_MASK, sc->int_mask);
8621 		return;
8622 	}
8623 
8624 	/* Read firmware images from the filesystem. */
8625 	if ((error = iwn_read_firmware(sc)) != 0) {
8626 		device_printf(sc->sc_dev,
8627 		    "%s: could not read firmware, error %d\n", __func__,
8628 		    error);
8629 		goto fail;
8630 	}
8631 
8632 	/* Initialize hardware and upload firmware. */
8633 	error = iwn_hw_init(sc);
8634 	firmware_put(sc->fw_fp, FIRMWARE_UNLOAD);
8635 	sc->fw_fp = NULL;
8636 	if (error != 0) {
8637 		device_printf(sc->sc_dev,
8638 		    "%s: could not initialize hardware, error %d\n", __func__,
8639 		    error);
8640 		goto fail;
8641 	}
8642 
8643 	/* Configure adapter now that it is ready. */
8644 	if ((error = iwn_config(sc)) != 0) {
8645 		device_printf(sc->sc_dev,
8646 		    "%s: could not configure device, error %d\n", __func__,
8647 		    error);
8648 		goto fail;
8649 	}
8650 
8651 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
8652 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
8653 
8654 	callout_reset(&sc->watchdog_to, hz, iwn_watchdog, sc);
8655 
8656 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end\n",__func__);
8657 
8658 	return;
8659 
8660 fail:	iwn_stop_locked(sc);
8661 	DPRINTF(sc, IWN_DEBUG_TRACE, "->%s: end in error\n",__func__);
8662 }
8663 
8664 static void
8665 iwn_init(void *arg)
8666 {
8667 	struct iwn_softc *sc = arg;
8668 	struct ifnet *ifp = sc->sc_ifp;
8669 	struct ieee80211com *ic = ifp->if_l2com;
8670 
8671 	IWN_LOCK(sc);
8672 	iwn_init_locked(sc);
8673 	IWN_UNLOCK(sc);
8674 
8675 	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
8676 		ieee80211_start_all(ic);
8677 }
8678 
8679 static void
8680 iwn_stop_locked(struct iwn_softc *sc)
8681 {
8682 	struct ifnet *ifp = sc->sc_ifp;
8683 
8684 	IWN_LOCK_ASSERT(sc);
8685 
8686 	sc->sc_is_scanning = 0;
8687 	sc->sc_tx_timer = 0;
8688 	callout_stop(&sc->watchdog_to);
8689 	callout_stop(&sc->calib_to);
8690 	ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
8691 
8692 	/* Power OFF hardware. */
8693 	iwn_hw_stop(sc);
8694 }
8695 
8696 static void
8697 iwn_stop(struct iwn_softc *sc)
8698 {
8699 	IWN_LOCK(sc);
8700 	iwn_stop_locked(sc);
8701 	IWN_UNLOCK(sc);
8702 }
8703 
8704 /*
8705  * Callback from net80211 to start a scan.
8706  */
8707 static void
8708 iwn_scan_start(struct ieee80211com *ic)
8709 {
8710 	struct ifnet *ifp = ic->ic_ifp;
8711 	struct iwn_softc *sc = ifp->if_softc;
8712 
8713 	IWN_LOCK(sc);
8714 	/* make the link LED blink while we're scanning */
8715 	iwn_set_led(sc, IWN_LED_LINK, 20, 2);
8716 	IWN_UNLOCK(sc);
8717 }
8718 
8719 /*
8720  * Callback from net80211 to terminate a scan.
8721  */
8722 static void
8723 iwn_scan_end(struct ieee80211com *ic)
8724 {
8725 	struct ifnet *ifp = ic->ic_ifp;
8726 	struct iwn_softc *sc = ifp->if_softc;
8727 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
8728 
8729 	IWN_LOCK(sc);
8730 	if (vap->iv_state == IEEE80211_S_RUN) {
8731 		/* Set link LED to ON status if we are associated */
8732 		iwn_set_led(sc, IWN_LED_LINK, 0, 1);
8733 	}
8734 	IWN_UNLOCK(sc);
8735 }
8736 
8737 /*
8738  * Callback from net80211 to force a channel change.
8739  */
8740 static void
8741 iwn_set_channel(struct ieee80211com *ic)
8742 {
8743 	const struct ieee80211_channel *c = ic->ic_curchan;
8744 	struct ifnet *ifp = ic->ic_ifp;
8745 	struct iwn_softc *sc = ifp->if_softc;
8746 	int error;
8747 
8748 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
8749 
8750 	IWN_LOCK(sc);
8751 	sc->sc_rxtap.wr_chan_freq = htole16(c->ic_freq);
8752 	sc->sc_rxtap.wr_chan_flags = htole16(c->ic_flags);
8753 	sc->sc_txtap.wt_chan_freq = htole16(c->ic_freq);
8754 	sc->sc_txtap.wt_chan_flags = htole16(c->ic_flags);
8755 
8756 	/*
8757 	 * Only need to set the channel in Monitor mode. AP scanning and auth
8758 	 * are already taken care of by their respective firmware commands.
8759 	 */
8760 	if (ic->ic_opmode == IEEE80211_M_MONITOR) {
8761 		error = iwn_config(sc);
8762 		if (error != 0)
8763 		device_printf(sc->sc_dev,
8764 		    "%s: error %d settting channel\n", __func__, error);
8765 	}
8766 	IWN_UNLOCK(sc);
8767 }
8768 
8769 /*
8770  * Callback from net80211 to start scanning of the current channel.
8771  */
8772 static void
8773 iwn_scan_curchan(struct ieee80211_scan_state *ss, unsigned long maxdwell)
8774 {
8775 	struct ieee80211vap *vap = ss->ss_vap;
8776 	struct iwn_softc *sc = vap->iv_ic->ic_ifp->if_softc;
8777 	struct ieee80211com *ic = vap->iv_ic;
8778 	int error;
8779 
8780 	IWN_LOCK(sc);
8781 	error = iwn_scan(sc, vap, ss, ic->ic_curchan);
8782 	IWN_UNLOCK(sc);
8783 	if (error != 0)
8784 		ieee80211_cancel_scan(vap);
8785 }
8786 
8787 /*
8788  * Callback from net80211 to handle the minimum dwell time being met.
8789  * The intent is to terminate the scan but we just let the firmware
8790  * notify us when it's finished as we have no safe way to abort it.
8791  */
8792 static void
8793 iwn_scan_mindwell(struct ieee80211_scan_state *ss)
8794 {
8795 	/* NB: don't try to abort scan; wait for firmware to finish */
8796 }
8797 
8798 static void
8799 iwn_hw_reset(void *arg0, int pending)
8800 {
8801 	struct iwn_softc *sc = arg0;
8802 	struct ifnet *ifp = sc->sc_ifp;
8803 	struct ieee80211com *ic = ifp->if_l2com;
8804 
8805 	DPRINTF(sc, IWN_DEBUG_TRACE, "->Doing %s\n", __func__);
8806 
8807 	iwn_stop(sc);
8808 	iwn_init(sc);
8809 	ieee80211_notify_radio(ic, 1);
8810 }
8811 #ifdef	IWN_DEBUG
8812 #define	IWN_DESC(x) case x:	return #x
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 <  nitems(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