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