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