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