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