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