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