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