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