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