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