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