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