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