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