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