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