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