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