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