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