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