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