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