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