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