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