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