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