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