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