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