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