xref: /openbsd-src/sys/dev/pci/if_iwn.c (revision 850e275390052b330d93020bf619a739a3c277ac)
1 /*	$OpenBSD: if_iwn.c,v 1.23 2008/08/27 09:05:03 damien Exp $	*/
2 
3 /*-
4  * Copyright (c) 2007,2008
5  *	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 Wireless WiFi Link 4965AGN 802.11 network adapters.
22  */
23 
24 #include "bpfilter.h"
25 
26 #include <sys/param.h>
27 #include <sys/sockio.h>
28 #include <sys/sysctl.h>
29 #include <sys/mbuf.h>
30 #include <sys/kernel.h>
31 #include <sys/socket.h>
32 #include <sys/systm.h>
33 #include <sys/malloc.h>
34 #include <sys/conf.h>
35 #include <sys/device.h>
36 #include <sys/sensors.h>
37 
38 #include <machine/bus.h>
39 #include <machine/endian.h>
40 #include <machine/intr.h>
41 
42 #include <dev/pci/pcireg.h>
43 #include <dev/pci/pcivar.h>
44 #include <dev/pci/pcidevs.h>
45 
46 #if NBPFILTER > 0
47 #include <net/bpf.h>
48 #endif
49 #include <net/if.h>
50 #include <net/if_arp.h>
51 #include <net/if_dl.h>
52 #include <net/if_media.h>
53 #include <net/if_types.h>
54 
55 #include <netinet/in.h>
56 #include <netinet/in_systm.h>
57 #include <netinet/in_var.h>
58 #include <netinet/if_ether.h>
59 #include <netinet/ip.h>
60 
61 #include <net80211/ieee80211_var.h>
62 #include <net80211/ieee80211_amrr.h>
63 #include <net80211/ieee80211_radiotap.h>
64 
65 #include <dev/pci/if_iwnreg.h>
66 #include <dev/pci/if_iwnvar.h>
67 
68 static const struct pci_matchid iwn_devices[] = {
69 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_PRO_WL_4965AGN_1 },
70 	{ PCI_VENDOR_INTEL, PCI_PRODUCT_INTEL_PRO_WL_4965AGN_2 }
71 };
72 
73 int		iwn_match(struct device *, void *, void *);
74 void		iwn_attach(struct device *, struct device *, void *);
75 #ifndef SMALL_KERNEL
76 void		iwn_sensor_attach(struct iwn_softc *);
77 #endif
78 void		iwn_radiotap_attach(struct iwn_softc *);
79 void		iwn_power(int, void *);
80 int		iwn_dma_contig_alloc(bus_dma_tag_t, struct iwn_dma_info *,
81 		    void **, bus_size_t, bus_size_t, int);
82 void		iwn_dma_contig_free(struct iwn_dma_info *);
83 int		iwn_alloc_shared(struct iwn_softc *);
84 void		iwn_free_shared(struct iwn_softc *);
85 int		iwn_alloc_kw(struct iwn_softc *);
86 void		iwn_free_kw(struct iwn_softc *);
87 int		iwn_alloc_fwmem(struct iwn_softc *);
88 void		iwn_free_fwmem(struct iwn_softc *);
89 struct		iwn_rbuf *iwn_alloc_rbuf(struct iwn_softc *);
90 void		iwn_free_rbuf(caddr_t, u_int, void *);
91 int		iwn_alloc_rpool(struct iwn_softc *);
92 void		iwn_free_rpool(struct iwn_softc *);
93 int		iwn_alloc_rx_ring(struct iwn_softc *, struct iwn_rx_ring *);
94 void		iwn_reset_rx_ring(struct iwn_softc *, struct iwn_rx_ring *);
95 void		iwn_free_rx_ring(struct iwn_softc *, struct iwn_rx_ring *);
96 int		iwn_alloc_tx_ring(struct iwn_softc *, struct iwn_tx_ring *,
97 		    int);
98 void		iwn_reset_tx_ring(struct iwn_softc *, struct iwn_tx_ring *);
99 void		iwn_free_tx_ring(struct iwn_softc *, struct iwn_tx_ring *);
100 struct		ieee80211_node *iwn_node_alloc(struct ieee80211com *);
101 void		iwn_newassoc(struct ieee80211com *, struct ieee80211_node *,
102 		    int);
103 int		iwn_media_change(struct ifnet *);
104 int		iwn_newstate(struct ieee80211com *, enum ieee80211_state, int);
105 void		iwn_mem_lock(struct iwn_softc *);
106 void		iwn_mem_unlock(struct iwn_softc *);
107 uint32_t	iwn_mem_read(struct iwn_softc *, uint32_t);
108 void		iwn_mem_write(struct iwn_softc *, uint32_t, uint32_t);
109 void		iwn_mem_write_region_4(struct iwn_softc *, uint32_t,
110 		    const uint32_t *, int);
111 int		iwn_eeprom_lock(struct iwn_softc *);
112 void		iwn_eeprom_unlock(struct iwn_softc *);
113 int		iwn_read_prom_data(struct iwn_softc *, uint32_t, void *, int);
114 int		iwn_load_microcode(struct iwn_softc *, const uint8_t *, int);
115 int		iwn_load_firmware(struct iwn_softc *);
116 void		iwn_calib_timeout(void *);
117 void		iwn_iter_func(void *, struct ieee80211_node *);
118 void		iwn_ampdu_rx_start(struct iwn_softc *, struct iwn_rx_desc *);
119 void		iwn_rx_intr(struct iwn_softc *, struct iwn_rx_desc *,
120 		    struct iwn_rx_data *);
121 void		iwn_rx_statistics(struct iwn_softc *, struct iwn_rx_desc *);
122 void		iwn_tx_intr(struct iwn_softc *, struct iwn_rx_desc *);
123 void		iwn_cmd_intr(struct iwn_softc *, struct iwn_rx_desc *);
124 void		iwn_notif_intr(struct iwn_softc *);
125 int		iwn_intr(void *);
126 void		iwn_read_eeprom(struct iwn_softc *);
127 void		iwn_read_eeprom_channels(struct iwn_softc *, int);
128 void		iwn_print_power_group(struct iwn_softc *, int);
129 uint8_t		iwn_plcp_signal(int);
130 int		iwn_tx_data(struct iwn_softc *, struct mbuf *,
131 		    struct ieee80211_node *, int);
132 void		iwn_start(struct ifnet *);
133 void		iwn_watchdog(struct ifnet *);
134 int		iwn_ioctl(struct ifnet *, u_long, caddr_t);
135 int		iwn_cmd(struct iwn_softc *, int, const void *, int, int);
136 int		iwn_setup_node_mrr(struct iwn_softc *,
137 		    const struct ieee80211_node *, uint8_t);
138 int		iwn_set_fixed_rate(struct iwn_softc *, uint8_t, uint8_t, int);
139 int		iwn_set_key(struct ieee80211com *, struct ieee80211_node *,
140 		    struct ieee80211_key *);
141 void		iwn_updateedca(struct ieee80211com *);
142 void		iwn_set_led(struct iwn_softc *, uint8_t, uint8_t, uint8_t);
143 int		iwn_set_critical_temp(struct iwn_softc *);
144 void		iwn_enable_tsf(struct iwn_softc *, struct ieee80211_node *);
145 void		iwn_power_calibration(struct iwn_softc *, int);
146 int		iwn_set_txpower(struct iwn_softc *,
147 		    struct ieee80211_channel *, int);
148 int		iwn_get_rssi(const struct iwn_rx_stat *);
149 int		iwn_get_noise(const struct iwn_rx_general_stats *);
150 int		iwn_get_temperature(struct iwn_softc *);
151 int		iwn_init_sensitivity(struct iwn_softc *);
152 void		iwn_compute_differential_gain(struct iwn_softc *,
153 		    const struct iwn_rx_general_stats *);
154 void		iwn_tune_sensitivity(struct iwn_softc *,
155 		    const struct iwn_rx_stats *);
156 int		iwn_send_sensitivity(struct iwn_softc *);
157 int		iwn_auth(struct iwn_softc *);
158 int		iwn_run(struct iwn_softc *);
159 int		iwn_scan(struct iwn_softc *, uint16_t);
160 int		iwn_config(struct iwn_softc *);
161 void		iwn_post_alive(struct iwn_softc *);
162 void		iwn_stop_master(struct iwn_softc *);
163 int		iwn_reset(struct iwn_softc *);
164 void		iwn_hw_config(struct iwn_softc *);
165 int		iwn_init(struct ifnet *);
166 void		iwn_stop(struct ifnet *, int);
167 
168 #define IWN_DEBUG
169 
170 #ifdef IWN_DEBUG
171 #define DPRINTF(x)	do { if (iwn_debug > 0) printf x; } while (0)
172 #define DPRINTFN(n, x)	do { if (iwn_debug >= (n)) printf x; } while (0)
173 int iwn_debug = 0;
174 #else
175 #define DPRINTF(x)
176 #define DPRINTFN(n, x)
177 #endif
178 
179 struct cfattach iwn_ca = {
180 	sizeof (struct iwn_softc), iwn_match, iwn_attach
181 };
182 
183 int
184 iwn_match(struct device *parent, void *match, void *aux)
185 {
186 	return pci_matchbyid((struct pci_attach_args *)aux, iwn_devices,
187 	    sizeof (iwn_devices) / sizeof (iwn_devices[0]));
188 }
189 
190 /* Base Address Register */
191 #define IWN_PCI_BAR0	0x10
192 
193 void
194 iwn_attach(struct device *parent, struct device *self, void *aux)
195 {
196 	struct iwn_softc *sc = (struct iwn_softc *)self;
197 	struct ieee80211com *ic = &sc->sc_ic;
198 	struct ifnet *ifp = &ic->ic_if;
199 	struct pci_attach_args *pa = aux;
200 	const char *intrstr;
201 	pci_intr_handle_t ih;
202 	pcireg_t memtype, data;
203 	int i, error;
204 
205 	sc->sc_pct = pa->pa_pc;
206 	sc->sc_pcitag = pa->pa_tag;
207 	sc->sc_dmat = pa->pa_dmat;
208 
209 	/* clear device specific PCI configuration register 0x41 */
210 	data = pci_conf_read(sc->sc_pct, sc->sc_pcitag, 0x40);
211 	data &= ~0x0000ff00;
212 	pci_conf_write(sc->sc_pct, sc->sc_pcitag, 0x40, data);
213 
214 	memtype = pci_mapreg_type(pa->pa_pc, pa->pa_tag, IWN_PCI_BAR0);
215 	error = pci_mapreg_map(pa, IWN_PCI_BAR0, memtype, 0, &sc->sc_st,
216 	    &sc->sc_sh, NULL, &sc->sc_sz, 0);
217 	if (error != 0) {
218 		printf(": could not map memory space\n");
219 		return;
220 	}
221 
222 	if (pci_intr_map(pa, &ih) != 0) {
223 		printf(": could not map interrupt\n");
224 		return;
225 	}
226 
227 	intrstr = pci_intr_string(sc->sc_pct, ih);
228 	sc->sc_ih = pci_intr_establish(sc->sc_pct, ih, IPL_NET, iwn_intr, sc,
229 	    sc->sc_dev.dv_xname);
230 	if (sc->sc_ih == NULL) {
231 		printf(": could not establish interrupt");
232 		if (intrstr != NULL)
233 			printf(" at %s", intrstr);
234 		printf("\n");
235 		return;
236 	}
237 	printf(": %s", intrstr);
238 
239 	/*
240 	 * Put adapter into a known state.
241 	 */
242 	if ((error = iwn_reset(sc)) != 0) {
243 		printf(": could not reset adapter\n");
244 		return;
245 	}
246 
247 	/*
248 	 * Allocate DMA memory for firmware transfers.
249 	 */
250 	if ((error = iwn_alloc_fwmem(sc)) != 0) {
251 		printf(": could not allocate firmware memory\n");
252 		return;
253 	}
254 
255 	/*
256 	 * Allocate a "keep warm" page.
257 	 */
258 	if ((error = iwn_alloc_kw(sc)) != 0) {
259 		printf(": could not allocate keep warm page\n");
260 		goto fail1;
261 	}
262 
263 	/*
264 	 * Allocate shared area (communication area).
265 	 */
266 	if ((error = iwn_alloc_shared(sc)) != 0) {
267 		printf(": could not allocate shared area\n");
268 		goto fail2;
269 	}
270 
271 	/*
272 	 * Allocate Rx buffers and Tx/Rx rings.
273 	 */
274 	if ((error = iwn_alloc_rpool(sc)) != 0) {
275 		printf(": could not allocate Rx buffers\n");
276 		goto fail3;
277 	}
278 
279 	for (i = 0; i < IWN_NTXQUEUES; i++) {
280 		if ((error = iwn_alloc_tx_ring(sc, &sc->txq[i], i)) != 0) {
281 			printf(": could not allocate Tx ring %d\n", i);
282 			goto fail4;
283 		}
284 	}
285 
286 	if ((error = iwn_alloc_rx_ring(sc, &sc->rxq)) != 0) {
287 		printf(": could not allocate Rx ring\n");
288 		goto fail4;
289 	}
290 
291 	ic->ic_phytype = IEEE80211_T_OFDM;	/* not only, but not used */
292 	ic->ic_opmode = IEEE80211_M_STA;	/* default to BSS mode */
293 	ic->ic_state = IEEE80211_S_INIT;
294 
295 	/* set device capabilities */
296 	ic->ic_caps =
297 	    IEEE80211_C_WEP |		/* s/w WEP */
298 	    IEEE80211_C_RSN |		/* WPA/RSN */
299 	    IEEE80211_C_MONITOR |	/* monitor mode supported */
300 	    IEEE80211_C_TXPMGT |	/* tx power management */
301 	    IEEE80211_C_SHSLOT |	/* short slot time supported */
302 	    IEEE80211_C_SHPREAMBLE;	/* short preamble supported */
303 
304 	/* read supported channels and MAC address from EEPROM */
305 	iwn_read_eeprom(sc);
306 
307 	/* set supported .11a, .11b and .11g rates */
308 	ic->ic_sup_rates[IEEE80211_MODE_11A] = ieee80211_std_rateset_11a;
309 	ic->ic_sup_rates[IEEE80211_MODE_11B] = ieee80211_std_rateset_11b;
310 	ic->ic_sup_rates[IEEE80211_MODE_11G] = ieee80211_std_rateset_11g;
311 
312 	/* IBSS channel undefined for now */
313 	ic->ic_ibss_chan = &ic->ic_channels[0];
314 
315 	ifp->if_softc = sc;
316 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
317 	ifp->if_init = iwn_init;
318 	ifp->if_ioctl = iwn_ioctl;
319 	ifp->if_start = iwn_start;
320 	ifp->if_watchdog = iwn_watchdog;
321 	IFQ_SET_READY(&ifp->if_snd);
322 	memcpy(ifp->if_xname, sc->sc_dev.dv_xname, IFNAMSIZ);
323 
324 	if_attach(ifp);
325 	ieee80211_ifattach(ifp);
326 	ic->ic_node_alloc = iwn_node_alloc;
327 	ic->ic_newassoc = iwn_newassoc;
328 #ifdef notyet
329 	ic->ic_set_key = iwn_set_key;
330 #endif
331 	ic->ic_updateedca = iwn_updateedca;
332 
333 	/* override state transition machine */
334 	sc->sc_newstate = ic->ic_newstate;
335 	ic->ic_newstate = iwn_newstate;
336 	ieee80211_media_init(ifp, iwn_media_change, ieee80211_media_status);
337 
338 	sc->amrr.amrr_min_success_threshold =  1;
339 	sc->amrr.amrr_max_success_threshold = 15;
340 
341 #ifndef SMALL_KERNEL
342 	iwn_sensor_attach(sc);
343 #endif
344 	iwn_radiotap_attach(sc);
345 
346 	timeout_set(&sc->calib_to, iwn_calib_timeout, sc);
347 
348 	sc->powerhook = powerhook_establish(iwn_power, sc);
349 
350 	return;
351 
352 	/* free allocated memory if something failed during attachment */
353 fail4:	while (--i >= 0)
354 		iwn_free_tx_ring(sc, &sc->txq[i]);
355 	iwn_free_rpool(sc);
356 fail3:	iwn_free_shared(sc);
357 fail2:	iwn_free_kw(sc);
358 fail1:	iwn_free_fwmem(sc);
359 }
360 
361 #ifndef SMALL_KERNEL
362 /*
363  * Attach the adapter's on-board thermal sensor to the sensors framework.
364  */
365 void
366 iwn_sensor_attach(struct iwn_softc *sc)
367 {
368 	strlcpy(sc->sensordev.xname, sc->sc_dev.dv_xname,
369 	    sizeof sc->sensordev.xname);
370 	sc->sensor.type = SENSOR_TEMP;
371 	/* temperature invalid until interface is up */
372 	sc->sensor.value = 0;
373 	sc->sensor.flags = SENSOR_FINVALID;
374 	sensor_attach(&sc->sensordev, &sc->sensor);
375 	sensordev_install(&sc->sensordev);
376 }
377 #endif
378 
379 /*
380  * Attach the interface to 802.11 radiotap.
381  */
382 void
383 iwn_radiotap_attach(struct iwn_softc *sc)
384 {
385 #if NBPFILTER > 0
386 	bpfattach(&sc->sc_drvbpf, &sc->sc_ic.ic_if, DLT_IEEE802_11_RADIO,
387 	    sizeof (struct ieee80211_frame) + IEEE80211_RADIOTAP_HDRLEN);
388 
389 	sc->sc_rxtap_len = sizeof sc->sc_rxtapu;
390 	sc->sc_rxtap.wr_ihdr.it_len = htole16(sc->sc_rxtap_len);
391 	sc->sc_rxtap.wr_ihdr.it_present = htole32(IWN_RX_RADIOTAP_PRESENT);
392 
393 	sc->sc_txtap_len = sizeof sc->sc_txtapu;
394 	sc->sc_txtap.wt_ihdr.it_len = htole16(sc->sc_txtap_len);
395 	sc->sc_txtap.wt_ihdr.it_present = htole32(IWN_TX_RADIOTAP_PRESENT);
396 #endif
397 }
398 
399 void
400 iwn_power(int why, void *arg)
401 {
402 	struct iwn_softc *sc = arg;
403 	struct ifnet *ifp;
404 	pcireg_t data;
405 	int s;
406 
407 	if (why != PWR_RESUME)
408 		return;
409 
410 	/* clear device specific PCI configuration register 0x41 */
411 	data = pci_conf_read(sc->sc_pct, sc->sc_pcitag, 0x40);
412 	data &= ~0x0000ff00;
413 	pci_conf_write(sc->sc_pct, sc->sc_pcitag, 0x40, data);
414 
415 	s = splnet();
416 	ifp = &sc->sc_ic.ic_if;
417 	if (ifp->if_flags & IFF_UP) {
418 		ifp->if_init(ifp);
419 		if (ifp->if_flags & IFF_RUNNING)
420 			ifp->if_start(ifp);
421 	}
422 	splx(s);
423 }
424 
425 int
426 iwn_dma_contig_alloc(bus_dma_tag_t tag, struct iwn_dma_info *dma, void **kvap,
427     bus_size_t size, bus_size_t alignment, int flags)
428 {
429 	int nsegs, error;
430 
431 	dma->tag = tag;
432 	dma->size = size;
433 
434 	error = bus_dmamap_create(tag, size, 1, size, 0, flags, &dma->map);
435 	if (error != 0)
436 		goto fail;
437 
438 	error = bus_dmamem_alloc(tag, size, alignment, 0, &dma->seg, 1, &nsegs,
439 	    flags);
440 	if (error != 0)
441 		goto fail;
442 
443 	error = bus_dmamem_map(tag, &dma->seg, 1, size, &dma->vaddr, flags);
444 	if (error != 0)
445 		goto fail;
446 
447 	error = bus_dmamap_load_raw(tag, dma->map, &dma->seg, 1, size, flags);
448 	if (error != 0)
449 		goto fail;
450 
451 	memset(dma->vaddr, 0, size);
452 
453 	dma->paddr = dma->map->dm_segs[0].ds_addr;
454 	if (kvap != NULL)
455 		*kvap = dma->vaddr;
456 
457 	return 0;
458 
459 fail:	iwn_dma_contig_free(dma);
460 	return error;
461 }
462 
463 void
464 iwn_dma_contig_free(struct iwn_dma_info *dma)
465 {
466 	if (dma->map != NULL) {
467 		if (dma->vaddr != NULL) {
468 			bus_dmamap_unload(dma->tag, dma->map);
469 			bus_dmamem_unmap(dma->tag, dma->vaddr, dma->size);
470 			bus_dmamem_free(dma->tag, &dma->seg, 1);
471 			dma->vaddr = NULL;
472 		}
473 		bus_dmamap_destroy(dma->tag, dma->map);
474 		dma->map = NULL;
475 	}
476 }
477 
478 int
479 iwn_alloc_shared(struct iwn_softc *sc)
480 {
481 	/* must be aligned on a 1KB boundary */
482 	return iwn_dma_contig_alloc(sc->sc_dmat, &sc->shared_dma,
483 	    (void **)&sc->shared, sizeof (struct iwn_shared), 1024,
484 	    BUS_DMA_NOWAIT);
485 }
486 
487 void
488 iwn_free_shared(struct iwn_softc *sc)
489 {
490 	iwn_dma_contig_free(&sc->shared_dma);
491 }
492 
493 int
494 iwn_alloc_kw(struct iwn_softc *sc)
495 {
496 	/* must be aligned on a 4KB boundary */
497 	return iwn_dma_contig_alloc(sc->sc_dmat, &sc->kw_dma, NULL,
498 	    PAGE_SIZE, PAGE_SIZE, BUS_DMA_NOWAIT);
499 }
500 
501 void
502 iwn_free_kw(struct iwn_softc *sc)
503 {
504 	iwn_dma_contig_free(&sc->kw_dma);
505 }
506 
507 int
508 iwn_alloc_fwmem(struct iwn_softc *sc)
509 {
510 	/* allocate enough contiguous space to store text and data */
511 	return iwn_dma_contig_alloc(sc->sc_dmat, &sc->fw_dma, NULL,
512 	    IWN_FW_MAIN_TEXT_MAXSZ + IWN_FW_MAIN_DATA_MAXSZ, 16,
513 	    BUS_DMA_NOWAIT);
514 }
515 
516 void
517 iwn_free_fwmem(struct iwn_softc *sc)
518 {
519 	iwn_dma_contig_free(&sc->fw_dma);
520 }
521 
522 struct iwn_rbuf *
523 iwn_alloc_rbuf(struct iwn_softc *sc)
524 {
525 	struct iwn_rbuf *rbuf;
526 
527 	rbuf = SLIST_FIRST(&sc->rxq.freelist);
528 	if (rbuf == NULL)
529 		return NULL;
530 	SLIST_REMOVE_HEAD(&sc->rxq.freelist, next);
531 	return rbuf;
532 }
533 
534 /*
535  * This is called automatically by the network stack when the mbuf to which
536  * our Rx buffer is attached is freed.
537  */
538 void
539 iwn_free_rbuf(caddr_t buf, u_int size, void *arg)
540 {
541 	struct iwn_rbuf *rbuf = arg;
542 	struct iwn_softc *sc = rbuf->sc;
543 
544 	/* put the buffer back in the free list */
545 	SLIST_INSERT_HEAD(&sc->rxq.freelist, rbuf, next);
546 }
547 
548 int
549 iwn_alloc_rpool(struct iwn_softc *sc)
550 {
551 	struct iwn_rx_ring *ring = &sc->rxq;
552 	int i, error;
553 
554 	/* allocate a big chunk of DMA'able memory.. */
555 	error = iwn_dma_contig_alloc(sc->sc_dmat, &ring->buf_dma, NULL,
556 	    IWN_RBUF_COUNT * IWN_RBUF_SIZE, PAGE_SIZE, BUS_DMA_NOWAIT);
557 	if (error != 0) {
558 		printf("%s: could not allocate Rx buffers DMA memory\n",
559 		    sc->sc_dev.dv_xname);
560 		return error;
561 	}
562 
563 	/* ..and split it into chunks of "rbufsz" bytes */
564 	SLIST_INIT(&ring->freelist);
565 	for (i = 0; i < IWN_RBUF_COUNT; i++) {
566 		struct iwn_rbuf *rbuf = &ring->rbuf[i];
567 
568 		rbuf->sc = sc;	/* backpointer for callbacks */
569 		rbuf->vaddr = ring->buf_dma.vaddr + i * IWN_RBUF_SIZE;
570 		rbuf->paddr = ring->buf_dma.paddr + i * IWN_RBUF_SIZE;
571 
572 		SLIST_INSERT_HEAD(&ring->freelist, rbuf, next);
573 	}
574 	return 0;
575 }
576 
577 void
578 iwn_free_rpool(struct iwn_softc *sc)
579 {
580 	iwn_dma_contig_free(&sc->rxq.buf_dma);
581 }
582 
583 int
584 iwn_alloc_rx_ring(struct iwn_softc *sc, struct iwn_rx_ring *ring)
585 {
586 	int i, error;
587 
588 	ring->cur = 0;
589 
590 	error = iwn_dma_contig_alloc(sc->sc_dmat, &ring->desc_dma,
591 	    (void **)&ring->desc, IWN_RX_RING_COUNT * sizeof (uint32_t),
592 	    IWN_RING_DMA_ALIGN, BUS_DMA_NOWAIT);
593 	if (error != 0) {
594 		printf("%s: could not allocate rx ring DMA memory\n",
595 		    sc->sc_dev.dv_xname);
596 		goto fail;
597 	}
598 
599 	/*
600 	 * Setup Rx buffers.
601 	 */
602 	for (i = 0; i < IWN_RX_RING_COUNT; i++) {
603 		struct iwn_rx_data *data = &ring->data[i];
604 		struct iwn_rbuf *rbuf;
605 
606 		MGETHDR(data->m, M_DONTWAIT, MT_DATA);
607 		if (data->m == NULL) {
608 			printf("%s: could not allocate rx mbuf\n",
609 			    sc->sc_dev.dv_xname);
610 			error = ENOMEM;
611 			goto fail;
612 		}
613 		if ((rbuf = iwn_alloc_rbuf(sc)) == NULL) {
614 			m_freem(data->m);
615 			data->m = NULL;
616 			printf("%s: could not allocate rx buffer\n",
617 			    sc->sc_dev.dv_xname);
618 			error = ENOMEM;
619 			goto fail;
620 		}
621 		/* attach Rx buffer to mbuf */
622 		MEXTADD(data->m, rbuf->vaddr, IWN_RBUF_SIZE, 0, iwn_free_rbuf,
623 		    rbuf);
624 
625 		/* Rx buffers are aligned on a 256-byte boundary */
626 		ring->desc[i] = htole32(rbuf->paddr >> 8);
627 	}
628 
629 	return 0;
630 
631 fail:	iwn_free_rx_ring(sc, ring);
632 	return error;
633 }
634 
635 void
636 iwn_reset_rx_ring(struct iwn_softc *sc, struct iwn_rx_ring *ring)
637 {
638 	int ntries;
639 
640 	iwn_mem_lock(sc);
641 
642 	IWN_WRITE(sc, IWN_RX_CONFIG, 0);
643 	for (ntries = 0; ntries < 100; ntries++) {
644 		if (IWN_READ(sc, IWN_RX_STATUS) & IWN_RX_IDLE)
645 			break;
646 		DELAY(10);
647 	}
648 #ifdef IWN_DEBUG
649 	if (ntries == 100 && iwn_debug > 0)
650 		printf("%s: timeout resetting Rx ring\n", sc->sc_dev.dv_xname);
651 #endif
652 	iwn_mem_unlock(sc);
653 
654 	ring->cur = 0;
655 }
656 
657 void
658 iwn_free_rx_ring(struct iwn_softc *sc, struct iwn_rx_ring *ring)
659 {
660 	int i;
661 
662 	iwn_dma_contig_free(&ring->desc_dma);
663 
664 	for (i = 0; i < IWN_RX_RING_COUNT; i++) {
665 		if (ring->data[i].m != NULL)
666 			m_freem(ring->data[i].m);
667 	}
668 }
669 
670 int
671 iwn_alloc_tx_ring(struct iwn_softc *sc, struct iwn_tx_ring *ring, int qid)
672 {
673 	bus_size_t size;
674 	int i, error;
675 
676 	ring->qid = qid;
677 	ring->queued = 0;
678 	ring->cur = 0;
679 
680 	size = IWN_TX_RING_COUNT * sizeof (struct iwn_tx_desc);
681 	error = iwn_dma_contig_alloc(sc->sc_dmat, &ring->desc_dma,
682 	    (void **)&ring->desc, size, IWN_RING_DMA_ALIGN, BUS_DMA_NOWAIT);
683 	if (error != 0) {
684 		printf("%s: could not allocate tx ring DMA memory\n",
685 		    sc->sc_dev.dv_xname);
686 		goto fail;
687 	}
688 
689 	size = IWN_TX_RING_COUNT * sizeof (struct iwn_tx_cmd);
690 	error = iwn_dma_contig_alloc(sc->sc_dmat, &ring->cmd_dma,
691 	    (void **)&ring->cmd, size, 4, BUS_DMA_NOWAIT);
692 	if (error != 0) {
693 		printf("%s: could not allocate tx cmd DMA memory\n",
694 		    sc->sc_dev.dv_xname);
695 		goto fail;
696 	}
697 
698 	for (i = 0; i < IWN_TX_RING_COUNT; i++) {
699 		struct iwn_tx_data *data = &ring->data[i];
700 
701 		error = bus_dmamap_create(sc->sc_dmat, MCLBYTES,
702 		    IWN_MAX_SCATTER - 1, MCLBYTES, 0, BUS_DMA_NOWAIT,
703 		    &data->map);
704 		if (error != 0) {
705 			printf("%s: could not create tx buf DMA map\n",
706 			    sc->sc_dev.dv_xname);
707 			goto fail;
708 		}
709 	}
710 
711 	return 0;
712 
713 fail:	iwn_free_tx_ring(sc, ring);
714 	return error;
715 }
716 
717 void
718 iwn_reset_tx_ring(struct iwn_softc *sc, struct iwn_tx_ring *ring)
719 {
720 	uint32_t tmp;
721 	int i, ntries;
722 
723 	iwn_mem_lock(sc);
724 
725 	IWN_WRITE(sc, IWN_TX_CONFIG(ring->qid), 0);
726 	for (ntries = 0; ntries < 100; ntries++) {
727 		tmp = IWN_READ(sc, IWN_TX_STATUS);
728 		if ((tmp & IWN_TX_IDLE(ring->qid)) == IWN_TX_IDLE(ring->qid))
729 			break;
730 		DELAY(10);
731 	}
732 #ifdef IWN_DEBUG
733 	if (ntries == 100 && iwn_debug > 1) {
734 		printf("%s: timeout resetting Tx ring %d\n",
735 		    sc->sc_dev.dv_xname, ring->qid);
736 	}
737 #endif
738 	iwn_mem_unlock(sc);
739 
740 	for (i = 0; i < IWN_TX_RING_COUNT; i++) {
741 		struct iwn_tx_data *data = &ring->data[i];
742 
743 		if (data->m != NULL) {
744 			bus_dmamap_unload(sc->sc_dmat, data->map);
745 			m_freem(data->m);
746 			data->m = NULL;
747 		}
748 	}
749 
750 	ring->queued = 0;
751 	ring->cur = 0;
752 }
753 
754 void
755 iwn_free_tx_ring(struct iwn_softc *sc, struct iwn_tx_ring *ring)
756 {
757 	int i;
758 
759 	iwn_dma_contig_free(&ring->desc_dma);
760 	iwn_dma_contig_free(&ring->cmd_dma);
761 
762 	for (i = 0; i < IWN_TX_RING_COUNT; i++) {
763 		struct iwn_tx_data *data = &ring->data[i];
764 
765 		if (data->m != NULL) {
766 			bus_dmamap_unload(sc->sc_dmat, data->map);
767 			m_freem(data->m);
768 		}
769 	}
770 }
771 
772 struct ieee80211_node *
773 iwn_node_alloc(struct ieee80211com *ic)
774 {
775 	return malloc(sizeof (struct iwn_node), M_DEVBUF, M_NOWAIT | M_ZERO);
776 }
777 
778 void
779 iwn_newassoc(struct ieee80211com *ic, struct ieee80211_node *ni, int isnew)
780 {
781 	struct iwn_softc *sc = ic->ic_if.if_softc;
782 	int i;
783 
784 	ieee80211_amrr_node_init(&sc->amrr, &((struct iwn_node *)ni)->amn);
785 
786 	/* set rate to some reasonable initial value */
787 	for (i = ni->ni_rates.rs_nrates - 1;
788 	     i > 0 && (ni->ni_rates.rs_rates[i] & IEEE80211_RATE_VAL) > 72;
789 	     i--);
790 	ni->ni_txrate = i;
791 }
792 
793 int
794 iwn_media_change(struct ifnet *ifp)
795 {
796 	int error;
797 
798 	error = ieee80211_media_change(ifp);
799 	if (error != ENETRESET)
800 		return error;
801 
802 	if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
803 	    (IFF_UP | IFF_RUNNING)) {
804 		iwn_stop(ifp, 0);
805 		iwn_init(ifp);
806 	}
807 	return 0;
808 }
809 
810 int
811 iwn_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
812 {
813 	struct ifnet *ifp = &ic->ic_if;
814 	struct iwn_softc *sc = ifp->if_softc;
815 	int error;
816 
817 	timeout_del(&sc->calib_to);
818 
819 	switch (nstate) {
820 	case IEEE80211_S_SCAN:
821 		/* make the link LED blink while we're scanning */
822 		iwn_set_led(sc, IWN_LED_LINK, 20, 2);
823 
824 		if ((error = iwn_scan(sc, IEEE80211_CHAN_G)) != 0) {
825 			printf("%s: could not initiate scan\n",
826 			    sc->sc_dev.dv_xname);
827 			return error;
828 		}
829 		ic->ic_state = nstate;
830 		return 0;
831 
832 	case IEEE80211_S_ASSOC:
833 		if (ic->ic_state != IEEE80211_S_RUN)
834 			break;
835 		/* FALLTHROUGH */
836 	case IEEE80211_S_AUTH:
837 		/* reset state to handle reassociations correctly */
838 		sc->config.associd = 0;
839 		sc->config.filter &= ~htole32(IWN_FILTER_BSS);
840 		sc->calib.state = IWN_CALIB_STATE_INIT;
841 
842 		if ((error = iwn_auth(sc)) != 0) {
843 			printf("%s: could not move to auth state\n",
844 			    sc->sc_dev.dv_xname);
845 			return error;
846 		}
847 		break;
848 
849 	case IEEE80211_S_RUN:
850 		if ((error = iwn_run(sc)) != 0) {
851 			printf("%s: could not move to run state\n",
852 			    sc->sc_dev.dv_xname);
853 			return error;
854 		}
855 		break;
856 
857 	case IEEE80211_S_INIT:
858 		sc->calib.state = IWN_CALIB_STATE_INIT;
859 		break;
860 	}
861 
862 	return sc->sc_newstate(ic, nstate, arg);
863 }
864 
865 /*
866  * Grab exclusive access to NIC memory.
867  */
868 void
869 iwn_mem_lock(struct iwn_softc *sc)
870 {
871 	uint32_t tmp;
872 	int ntries;
873 
874 	tmp = IWN_READ(sc, IWN_GPIO_CTL);
875 	IWN_WRITE(sc, IWN_GPIO_CTL, tmp | IWN_GPIO_MAC);
876 
877 	/* spin until we actually get the lock */
878 	for (ntries = 0; ntries < 1000; ntries++) {
879 		if ((IWN_READ(sc, IWN_GPIO_CTL) &
880 		    (IWN_GPIO_CLOCK | IWN_GPIO_SLEEP)) == IWN_GPIO_CLOCK)
881 			break;
882 		DELAY(10);
883 	}
884 	if (ntries == 1000)
885 		printf("%s: could not lock memory\n", sc->sc_dev.dv_xname);
886 }
887 
888 /*
889  * Release lock on NIC memory.
890  */
891 void
892 iwn_mem_unlock(struct iwn_softc *sc)
893 {
894 	uint32_t tmp = IWN_READ(sc, IWN_GPIO_CTL);
895 	IWN_WRITE(sc, IWN_GPIO_CTL, tmp & ~IWN_GPIO_MAC);
896 }
897 
898 uint32_t
899 iwn_mem_read(struct iwn_softc *sc, uint32_t addr)
900 {
901 	IWN_WRITE(sc, IWN_READ_MEM_ADDR, IWN_MEM_4 | addr);
902 	return IWN_READ(sc, IWN_READ_MEM_DATA);
903 }
904 
905 void
906 iwn_mem_write(struct iwn_softc *sc, uint32_t addr, uint32_t data)
907 {
908 	IWN_WRITE(sc, IWN_WRITE_MEM_ADDR, IWN_MEM_4 | addr);
909 	IWN_WRITE(sc, IWN_WRITE_MEM_DATA, data);
910 }
911 
912 void
913 iwn_mem_write_region_4(struct iwn_softc *sc, uint32_t addr,
914     const uint32_t *data, int wlen)
915 {
916 	for (; wlen > 0; wlen--, data++, addr += 4)
917 		iwn_mem_write(sc, addr, *data);
918 }
919 
920 int
921 iwn_eeprom_lock(struct iwn_softc *sc)
922 {
923 	uint32_t tmp;
924 	int ntries;
925 
926 	tmp = IWN_READ(sc, IWN_HWCONFIG);
927 	IWN_WRITE(sc, IWN_HWCONFIG, tmp | IWN_HW_EEPROM_LOCKED);
928 
929 	/* spin until we actually get the lock */
930 	for (ntries = 0; ntries < 100; ntries++) {
931 		if (IWN_READ(sc, IWN_HWCONFIG) & IWN_HW_EEPROM_LOCKED)
932 			return 0;
933 		DELAY(10);
934 	}
935 	return ETIMEDOUT;
936 }
937 
938 void
939 iwn_eeprom_unlock(struct iwn_softc *sc)
940 {
941 	uint32_t tmp = IWN_READ(sc, IWN_HWCONFIG);
942 	IWN_WRITE(sc, IWN_HWCONFIG, tmp & ~IWN_HW_EEPROM_LOCKED);
943 }
944 
945 /*
946  * Read `len' bytes from the EEPROM.  We access the EEPROM through the MAC
947  * instead of using the traditional bit-bang method.
948  */
949 int
950 iwn_read_prom_data(struct iwn_softc *sc, uint32_t addr, void *data, int len)
951 {
952 	uint8_t *out = data;
953 	uint32_t val;
954 	int ntries;
955 
956 	iwn_mem_lock(sc);
957 	for (; len > 0; len -= 2, addr++) {
958 		IWN_WRITE(sc, IWN_EEPROM_CTL, addr << 2);
959 		IWN_WRITE(sc, IWN_EEPROM_CTL,
960 		    IWN_READ(sc, IWN_EEPROM_CTL) & ~IWN_EEPROM_CMD);
961 
962 		for (ntries = 0; ntries < 10; ntries++) {
963 			if ((val = IWN_READ(sc, IWN_EEPROM_CTL)) &
964 			    IWN_EEPROM_READY)
965 				break;
966 			DELAY(5);
967 		}
968 		if (ntries == 10) {
969 			printf("%s: could not read EEPROM\n",
970 			    sc->sc_dev.dv_xname);
971 			return ETIMEDOUT;
972 		}
973 		*out++ = val >> 16;
974 		if (len > 1)
975 			*out++ = val >> 24;
976 	}
977 	iwn_mem_unlock(sc);
978 
979 	return 0;
980 }
981 
982 /*
983  * The firmware boot code is small and is intended to be copied directly into
984  * the NIC internal memory.
985  */
986 int
987 iwn_load_microcode(struct iwn_softc *sc, const uint8_t *ucode, int size)
988 {
989 	int ntries;
990 
991 	size /= sizeof (uint32_t);
992 
993 	iwn_mem_lock(sc);
994 
995 	/* copy microcode image into NIC memory */
996 	iwn_mem_write_region_4(sc, IWN_MEM_UCODE_BASE,
997 	    (const uint32_t *)ucode, size);
998 
999 	iwn_mem_write(sc, IWN_MEM_UCODE_SRC, 0);
1000 	iwn_mem_write(sc, IWN_MEM_UCODE_DST, IWN_FW_TEXT);
1001 	iwn_mem_write(sc, IWN_MEM_UCODE_SIZE, size);
1002 
1003 	/* run microcode */
1004 	iwn_mem_write(sc, IWN_MEM_UCODE_CTL, IWN_UC_RUN);
1005 
1006 	/* wait for transfer to complete */
1007 	for (ntries = 0; ntries < 1000; ntries++) {
1008 		if (!(iwn_mem_read(sc, IWN_MEM_UCODE_CTL) & IWN_UC_RUN))
1009 			break;
1010 		DELAY(10);
1011 	}
1012 	if (ntries == 1000) {
1013 		iwn_mem_unlock(sc);
1014 		printf("%s: could not load boot firmware\n",
1015 		    sc->sc_dev.dv_xname);
1016 		return ETIMEDOUT;
1017 	}
1018 	iwn_mem_write(sc, IWN_MEM_UCODE_CTL, IWN_UC_ENABLE);
1019 
1020 	iwn_mem_unlock(sc);
1021 
1022 	return 0;
1023 }
1024 
1025 int
1026 iwn_load_firmware(struct iwn_softc *sc)
1027 {
1028 	struct iwn_dma_info *dma = &sc->fw_dma;
1029 	const struct iwn_firmware_hdr *hdr;
1030 	const uint8_t *init_text, *init_data, *main_text, *main_data;
1031 	const uint8_t *boot_text;
1032 	uint32_t init_textsz, init_datasz, main_textsz, main_datasz;
1033 	uint32_t boot_textsz;
1034 	u_char *fw;
1035 	size_t size;
1036 	int error;
1037 
1038 	/* load firmware image from disk */
1039 	if ((error = loadfirmware("iwn-4965agn", &fw, &size)) != 0) {
1040 		printf("%s: error, %d, could not read firmware %s\n",
1041 		    sc->sc_dev.dv_xname, error, "iwn-4965agn");
1042 		goto fail1;
1043 	}
1044 
1045 	/* extract firmware header information */
1046 	if (size < sizeof (struct iwn_firmware_hdr)) {
1047 		printf("%s: truncated firmware header: %d bytes\n",
1048 		    sc->sc_dev.dv_xname, size);
1049 		error = EINVAL;
1050 		goto fail2;
1051 	}
1052 	hdr = (const struct iwn_firmware_hdr *)fw;
1053 	main_textsz = letoh32(hdr->main_textsz);
1054 	main_datasz = letoh32(hdr->main_datasz);
1055 	init_textsz = letoh32(hdr->init_textsz);
1056 	init_datasz = letoh32(hdr->init_datasz);
1057 	boot_textsz = letoh32(hdr->boot_textsz);
1058 
1059 	/* sanity-check firmware segments sizes */
1060 	if (main_textsz > IWN_FW_MAIN_TEXT_MAXSZ ||
1061 	    main_datasz > IWN_FW_MAIN_DATA_MAXSZ ||
1062 	    init_textsz > IWN_FW_INIT_TEXT_MAXSZ ||
1063 	    init_datasz > IWN_FW_INIT_DATA_MAXSZ ||
1064 	    boot_textsz > IWN_FW_BOOT_TEXT_MAXSZ ||
1065 	    (boot_textsz & 3) != 0) {
1066 		printf("%s: invalid firmware header\n", sc->sc_dev.dv_xname);
1067 		error = EINVAL;
1068 		goto fail2;
1069 	}
1070 
1071 	/* check that all firmware segments are present */
1072 	if (size < sizeof (struct iwn_firmware_hdr) + main_textsz +
1073 	    main_datasz + init_textsz + init_datasz + boot_textsz) {
1074 		printf("%s: firmware file too short: %d bytes\n",
1075 		    sc->sc_dev.dv_xname, size);
1076 		error = EINVAL;
1077 		goto fail2;
1078 	}
1079 
1080 	/* get pointers to firmware segments */
1081 	main_text = (const uint8_t *)(hdr + 1);
1082 	main_data = main_text + main_textsz;
1083 	init_text = main_data + main_datasz;
1084 	init_data = init_text + init_textsz;
1085 	boot_text = init_data + init_datasz;
1086 
1087 	/* copy initialization images into pre-allocated DMA-safe memory */
1088 	memcpy(dma->vaddr, init_data, init_datasz);
1089 	memcpy(dma->vaddr + IWN_FW_INIT_DATA_MAXSZ, init_text, init_textsz);
1090 
1091 	/* tell adapter where to find initialization images */
1092 	iwn_mem_lock(sc);
1093 	iwn_mem_write(sc, IWN_MEM_DATA_BASE, dma->paddr >> 4);
1094 	iwn_mem_write(sc, IWN_MEM_DATA_SIZE, init_datasz);
1095 	iwn_mem_write(sc, IWN_MEM_TEXT_BASE,
1096 	    (dma->paddr + IWN_FW_INIT_DATA_MAXSZ) >> 4);
1097 	iwn_mem_write(sc, IWN_MEM_TEXT_SIZE, init_textsz);
1098 	iwn_mem_unlock(sc);
1099 
1100 	/* load firmware boot code */
1101 	if ((error = iwn_load_microcode(sc, boot_text, boot_textsz)) != 0) {
1102 		printf("%s: could not load boot firmware\n",
1103 		    sc->sc_dev.dv_xname);
1104 		goto fail2;
1105 	}
1106 
1107 	/* now press "execute" ;-) */
1108 	IWN_WRITE(sc, IWN_RESET, 0);
1109 
1110 	/* wait at most one second for first alive notification */
1111 	if ((error = tsleep(sc, PCATCH, "iwninit", hz)) != 0) {
1112 		/* this isn't what was supposed to happen.. */
1113 		printf("%s: timeout waiting for adapter to initialize\n",
1114 		    sc->sc_dev.dv_xname);
1115 		goto fail2;
1116 	}
1117 
1118 	/* copy runtime images into pre-allocated DMA-safe memory */
1119 	memcpy(dma->vaddr, main_data, main_datasz);
1120 	memcpy(dma->vaddr + IWN_FW_MAIN_DATA_MAXSZ, main_text, main_textsz);
1121 
1122 	/* tell adapter where to find runtime images */
1123 	iwn_mem_lock(sc);
1124 	iwn_mem_write(sc, IWN_MEM_DATA_BASE, dma->paddr >> 4);
1125 	iwn_mem_write(sc, IWN_MEM_DATA_SIZE, main_datasz);
1126 	iwn_mem_write(sc, IWN_MEM_TEXT_BASE,
1127 	    (dma->paddr + IWN_FW_MAIN_DATA_MAXSZ) >> 4);
1128 	iwn_mem_write(sc, IWN_MEM_TEXT_SIZE, IWN_FW_UPDATED | main_textsz);
1129 	iwn_mem_unlock(sc);
1130 
1131 	/* wait at most one second for second alive notification */
1132 	if ((error = tsleep(sc, PCATCH, "iwninit", hz)) != 0) {
1133 		/* this isn't what was supposed to happen.. */
1134 		printf("%s: timeout waiting for adapter to initialize\n",
1135 		    sc->sc_dev.dv_xname);
1136 	}
1137 
1138 fail2:	free(fw, M_DEVBUF);
1139 fail1:	return error;
1140 }
1141 
1142 void
1143 iwn_calib_timeout(void *arg)
1144 {
1145 	struct iwn_softc *sc = arg;
1146 	struct ieee80211com *ic = &sc->sc_ic;
1147 	int s;
1148 
1149 	/* automatic rate control triggered every 500ms */
1150 	if (ic->ic_fixed_rate == -1) {
1151 		s = splnet();
1152 		if (ic->ic_opmode == IEEE80211_M_STA)
1153 			iwn_iter_func(sc, ic->ic_bss);
1154 		else
1155 			ieee80211_iterate_nodes(ic, iwn_iter_func, sc);
1156 		splx(s);
1157 	}
1158 
1159 	/* automatic calibration every 60s */
1160 	if (++sc->calib_cnt >= 120) {
1161 		DPRINTF(("sending request for statistics\n"));
1162 		(void)iwn_cmd(sc, IWN_CMD_GET_STATISTICS, NULL, 0, 1);
1163 		sc->calib_cnt = 0;
1164 	}
1165 
1166 	timeout_add(&sc->calib_to, hz / 2);
1167 }
1168 
1169 void
1170 iwn_iter_func(void *arg, struct ieee80211_node *ni)
1171 {
1172 	struct iwn_softc *sc = arg;
1173 	struct iwn_node *wn = (struct iwn_node *)ni;
1174 
1175 	ieee80211_amrr_choose(&sc->amrr, ni, &wn->amn);
1176 }
1177 
1178 void
1179 iwn_ampdu_rx_start(struct iwn_softc *sc, struct iwn_rx_desc *desc)
1180 {
1181 	struct iwn_rx_stat *stat;
1182 
1183 	DPRINTFN(2, ("received AMPDU stats\n"));
1184 	/* save Rx statistics, they will be used on IWN_AMPDU_RX_DONE */
1185 	stat = (struct iwn_rx_stat *)(desc + 1);
1186 	memcpy(&sc->last_rx_stat, stat, sizeof (*stat));
1187 	sc->last_rx_valid = 1;
1188 }
1189 
1190 void
1191 iwn_rx_intr(struct iwn_softc *sc, struct iwn_rx_desc *desc,
1192     struct iwn_rx_data *data)
1193 {
1194 	struct ieee80211com *ic = &sc->sc_ic;
1195 	struct ifnet *ifp = &ic->ic_if;
1196 	struct iwn_rx_ring *ring = &sc->rxq;
1197 	struct iwn_rbuf *rbuf;
1198 	struct ieee80211_frame *wh;
1199 	struct ieee80211_rxinfo rxi;
1200 	struct ieee80211_node *ni;
1201 	struct mbuf *m, *mnew;
1202 	struct iwn_rx_stat *stat;
1203 	caddr_t head;
1204 	uint32_t *tail;
1205 	int len, rssi;
1206 
1207 	if (desc->type == IWN_AMPDU_RX_DONE) {
1208 		/* check for prior AMPDU_RX_START */
1209 		if (!sc->last_rx_valid) {
1210 			DPRINTF(("missing AMPDU_RX_START\n"));
1211 			ifp->if_ierrors++;
1212 			return;
1213 		}
1214 		sc->last_rx_valid = 0;
1215 		stat = &sc->last_rx_stat;
1216 	} else
1217 		stat = (struct iwn_rx_stat *)(desc + 1);
1218 
1219 	if (stat->cfg_phy_len > IWN_STAT_MAXLEN) {
1220 		printf("%s: invalid rx statistic header\n",
1221 		    sc->sc_dev.dv_xname);
1222 		ifp->if_ierrors++;
1223 		return;
1224 	}
1225 	if (desc->type == IWN_AMPDU_RX_DONE) {
1226 		struct iwn_rx_ampdu *ampdu =
1227 		    (struct iwn_rx_ampdu *)(desc + 1);
1228 		head = (caddr_t)(ampdu + 1);
1229 		len = letoh16(ampdu->len);
1230 	} else {
1231 		head = (caddr_t)(stat + 1) + stat->cfg_phy_len;
1232 		len = letoh16(stat->len);
1233 	}
1234 
1235 	/* discard Rx frames with bad CRC early */
1236 	tail = (uint32_t *)(head + len);
1237 	if ((letoh32(*tail) & IWN_RX_NOERROR) != IWN_RX_NOERROR) {
1238 		DPRINTFN(2, ("rx flags error %x\n", letoh32(*tail)));
1239 		ifp->if_ierrors++;
1240 		return;
1241 	}
1242 	/* XXX for ieee80211_find_rxnode() */
1243 	if (len < sizeof (struct ieee80211_frame)) {
1244 		DPRINTF(("frame too short: %d\n", len));
1245 		ic->ic_stats.is_rx_tooshort++;
1246 		ifp->if_ierrors++;
1247 		return;
1248 	}
1249 
1250 	m = data->m;
1251 
1252 	/* finalize mbuf */
1253 	m->m_pkthdr.rcvif = ifp;
1254 	m->m_data = head;
1255 	m->m_pkthdr.len = m->m_len = len;
1256 
1257 	if ((rbuf = SLIST_FIRST(&sc->rxq.freelist)) != NULL) {
1258 		MGETHDR(mnew, M_DONTWAIT, MT_DATA);
1259 		if (mnew == NULL) {
1260 			ic->ic_stats.is_rx_nombuf++;
1261 			ifp->if_ierrors++;
1262 			return;
1263 		}
1264 
1265 		/* attach Rx buffer to mbuf */
1266 		MEXTADD(mnew, rbuf->vaddr, IWN_RBUF_SIZE, 0, iwn_free_rbuf,
1267 		    rbuf);
1268 		SLIST_REMOVE_HEAD(&sc->rxq.freelist, next);
1269 
1270 		data->m = mnew;
1271 
1272 		/* update Rx descriptor */
1273 		ring->desc[ring->cur] = htole32(rbuf->paddr >> 8);
1274 	} else {
1275 		/* no free rbufs, copy frame */
1276 		m = m_copym2(m, 0, M_COPYALL, M_DONTWAIT);
1277 		if (m == NULL) {
1278 			/* no free mbufs either, drop frame */
1279 			ic->ic_stats.is_rx_nombuf++;
1280 			ifp->if_ierrors++;
1281 			return;
1282 		}
1283 	}
1284 
1285 	rssi = iwn_get_rssi(stat);
1286 
1287 #if NBPFILTER > 0
1288 	if (sc->sc_drvbpf != NULL) {
1289 		struct mbuf mb;
1290 		struct iwn_rx_radiotap_header *tap = &sc->sc_rxtap;
1291 
1292 		tap->wr_flags = 0;
1293 		tap->wr_chan_freq =
1294 		    htole16(ic->ic_channels[stat->chan].ic_freq);
1295 		tap->wr_chan_flags =
1296 		    htole16(ic->ic_channels[stat->chan].ic_flags);
1297 		tap->wr_dbm_antsignal = (int8_t)rssi;
1298 		tap->wr_dbm_antnoise = (int8_t)sc->noise;
1299 		tap->wr_tsft = stat->tstamp;
1300 		switch (stat->rate) {
1301 		/* CCK rates */
1302 		case  10: tap->wr_rate =   2; break;
1303 		case  20: tap->wr_rate =   4; break;
1304 		case  55: tap->wr_rate =  11; break;
1305 		case 110: tap->wr_rate =  22; break;
1306 		/* OFDM rates */
1307 		case 0xd: tap->wr_rate =  12; break;
1308 		case 0xf: tap->wr_rate =  18; break;
1309 		case 0x5: tap->wr_rate =  24; break;
1310 		case 0x7: tap->wr_rate =  36; break;
1311 		case 0x9: tap->wr_rate =  48; break;
1312 		case 0xb: tap->wr_rate =  72; break;
1313 		case 0x1: tap->wr_rate =  96; break;
1314 		case 0x3: tap->wr_rate = 108; break;
1315 		/* unknown rate: should not happen */
1316 		default:  tap->wr_rate =   0;
1317 		}
1318 
1319 		mb.m_data = (caddr_t)tap;
1320 		mb.m_len = sc->sc_rxtap_len;
1321 		mb.m_next = m;
1322 		mb.m_nextpkt = NULL;
1323 		mb.m_type = 0;
1324 		mb.m_flags = 0;
1325 		bpf_mtap(sc->sc_drvbpf, &mb, BPF_DIRECTION_IN);
1326 	}
1327 #endif
1328 
1329 	/* grab a reference to the source node */
1330 	wh = mtod(m, struct ieee80211_frame *);
1331 	ni = ieee80211_find_rxnode(ic, wh);
1332 
1333 	/* send the frame to the 802.11 layer */
1334 	rxi.rxi_flags = 0;
1335 	rxi.rxi_rssi = rssi;
1336 	rxi.rxi_tstamp = 0;	/* unused */
1337 	ieee80211_input(ifp, m, ni, &rxi);
1338 
1339 	/* node is no longer needed */
1340 	ieee80211_release_node(ic, ni);
1341 }
1342 
1343 void
1344 iwn_rx_statistics(struct iwn_softc *sc, struct iwn_rx_desc *desc)
1345 {
1346 	struct ieee80211com *ic = &sc->sc_ic;
1347 	struct iwn_calib_state *calib = &sc->calib;
1348 	struct iwn_stats *stats = (struct iwn_stats *)(desc + 1);
1349 
1350 	/* ignore beacon statistics received during a scan */
1351 	if (ic->ic_state != IEEE80211_S_RUN)
1352 		return;
1353 
1354 	DPRINTFN(3, ("received statistics (cmd=%d)\n", desc->type));
1355 	sc->calib_cnt = 0;	/* reset timeout */
1356 
1357 	/* test if temperature has changed */
1358 	if (stats->general.temp != sc->rawtemp) {
1359 		int temp;
1360 
1361 		sc->rawtemp = stats->general.temp;
1362 		temp = iwn_get_temperature(sc);
1363 		DPRINTFN(2, ("temperature=%d\n", temp));
1364 
1365 		/* update temperature sensor */
1366 		sc->sensor.value = IWN_CTOMUK(temp);
1367 
1368 		/* update Tx power if need be */
1369 		iwn_power_calibration(sc, temp);
1370 	}
1371 
1372 	if (desc->type != IWN_BEACON_STATISTICS)
1373 		return;	/* reply to a statistics request */
1374 
1375 	sc->noise = iwn_get_noise(&stats->rx.general);
1376 	DPRINTFN(3, ("noise=%d\n", sc->noise));
1377 
1378 	/* test that RSSI and noise are present in stats report */
1379 	if (letoh32(stats->rx.general.flags) != 1) {
1380 		DPRINTF(("received statistics without RSSI\n"));
1381 		return;
1382 	}
1383 
1384 	if (calib->state == IWN_CALIB_STATE_ASSOC)
1385 		iwn_compute_differential_gain(sc, &stats->rx.general);
1386 	else if (calib->state == IWN_CALIB_STATE_RUN)
1387 		iwn_tune_sensitivity(sc, &stats->rx);
1388 }
1389 
1390 void
1391 iwn_tx_intr(struct iwn_softc *sc, struct iwn_rx_desc *desc)
1392 {
1393 	struct ieee80211com *ic = &sc->sc_ic;
1394 	struct ifnet *ifp = &ic->ic_if;
1395 	struct iwn_tx_ring *ring = &sc->txq[desc->qid & 0xf];
1396 	struct iwn_tx_data *data = &ring->data[desc->idx];
1397 	struct iwn_tx_stat *stat = (struct iwn_tx_stat *)(desc + 1);
1398 	struct iwn_node *wn = (struct iwn_node *)data->ni;
1399 	uint32_t status;
1400 
1401 	DPRINTFN(4, ("tx done: qid=%d idx=%d retries=%d nkill=%d rate=%x "
1402 	    "duration=%d status=%x\n", desc->qid, desc->idx, stat->ntries,
1403 	    stat->nkill, stat->rate, letoh16(stat->duration),
1404 	    letoh32(stat->status)));
1405 
1406 	/*
1407 	 * Update rate control statistics for the node.
1408 	 */
1409 	wn->amn.amn_txcnt++;
1410 	if (stat->ntries > 0) {
1411 		DPRINTFN(3, ("tx intr ntries %d\n", stat->ntries));
1412 		wn->amn.amn_retrycnt++;
1413 	}
1414 
1415 	status = letoh32(stat->status) & 0xff;
1416 	if (status != 1 && status != 2)
1417 		ifp->if_oerrors++;
1418 	else
1419 		ifp->if_opackets++;
1420 
1421 	bus_dmamap_unload(sc->sc_dmat, data->map);
1422 	m_freem(data->m);
1423 	data->m = NULL;
1424 	ieee80211_release_node(ic, data->ni);
1425 	data->ni = NULL;
1426 
1427 	ring->queued--;
1428 
1429 	sc->sc_tx_timer = 0;
1430 	ifp->if_flags &= ~IFF_OACTIVE;
1431 	(*ifp->if_start)(ifp);
1432 }
1433 
1434 void
1435 iwn_cmd_intr(struct iwn_softc *sc, struct iwn_rx_desc *desc)
1436 {
1437 	struct iwn_tx_ring *ring = &sc->txq[4];
1438 	struct iwn_tx_data *data;
1439 
1440 	if ((desc->qid & 0xf) != 4)
1441 		return;	/* not a command ack */
1442 
1443 	data = &ring->data[desc->idx];
1444 
1445 	/* if the command was mapped in a mbuf, free it */
1446 	if (data->m != NULL) {
1447 		bus_dmamap_unload(sc->sc_dmat, data->map);
1448 		m_freem(data->m);
1449 		data->m = NULL;
1450 	}
1451 
1452 	wakeup(&ring->cmd[desc->idx]);
1453 }
1454 
1455 void
1456 iwn_notif_intr(struct iwn_softc *sc)
1457 {
1458 	struct ieee80211com *ic = &sc->sc_ic;
1459 	struct ifnet *ifp = &ic->ic_if;
1460 	uint16_t hw;
1461 
1462 	hw = letoh16(sc->shared->closed_count);
1463 	while (sc->rxq.cur != hw) {
1464 		struct iwn_rx_data *data = &sc->rxq.data[sc->rxq.cur];
1465 		struct iwn_rx_desc *desc = (void *)data->m->m_ext.ext_buf;
1466 
1467 		DPRINTFN(4,("rx notification qid=%x idx=%d flags=%x type=%d "
1468 		    "len=%d\n", desc->qid, desc->idx, desc->flags, desc->type,
1469 		    letoh16(desc->len)));
1470 
1471 		if (!(desc->qid & 0x80))	/* reply to a command */
1472 			iwn_cmd_intr(sc, desc);
1473 
1474 		switch (desc->type) {
1475 		case IWN_RX_DONE:
1476 		case IWN_AMPDU_RX_DONE:
1477 			iwn_rx_intr(sc, desc, data);
1478 			break;
1479 
1480 		case IWN_AMPDU_RX_START:
1481 			iwn_ampdu_rx_start(sc, desc);
1482 			break;
1483 
1484 		case IWN_TX_DONE:
1485 			/* a 802.11 frame has been transmitted */
1486 			iwn_tx_intr(sc, desc);
1487 			break;
1488 
1489 		case IWN_RX_STATISTICS:
1490 		case IWN_BEACON_STATISTICS:
1491 			iwn_rx_statistics(sc, desc);
1492 			break;
1493 
1494 		case IWN_BEACON_MISSED:
1495 		{
1496 			struct iwn_beacon_missed *miss =
1497 			    (struct iwn_beacon_missed *)(desc + 1);
1498 			/*
1499 			 * If more than 5 consecutive beacons are missed,
1500 			 * reinitialize the sensitivity state machine.
1501 			 */
1502 			DPRINTFN(2, ("beacons missed %d/%d\n",
1503 			    letoh32(miss->consecutive), letoh32(miss->total)));
1504 			if (ic->ic_state == IEEE80211_S_RUN &&
1505 			    letoh32(miss->consecutive) > 5)
1506 				(void)iwn_init_sensitivity(sc);
1507 			break;
1508 		}
1509 		case IWN_UC_READY:
1510 		{
1511 			struct iwn_ucode_info *uc =
1512 			    (struct iwn_ucode_info *)(desc + 1);
1513 
1514 			/* the microcontroller is ready */
1515 			DPRINTF(("microcode alive notification version=%d.%d "
1516 			    "subtype=%x alive=%x\n", uc->major, uc->minor,
1517 			    uc->subtype, letoh32(uc->valid)));
1518 
1519 			if (letoh32(uc->valid) != 1) {
1520 				printf("%s: microcontroller initialization "
1521 				    "failed\n", sc->sc_dev.dv_xname);
1522 				break;
1523 			}
1524 			if (uc->subtype == IWN_UCODE_INIT) {
1525 				/* save microcontroller's report */
1526 				memcpy(&sc->ucode_info, uc, sizeof (*uc));
1527 			}
1528 			break;
1529 		}
1530 		case IWN_STATE_CHANGED:
1531 		{
1532 			uint32_t *status = (uint32_t *)(desc + 1);
1533 
1534 			/* enabled/disabled notification */
1535 			DPRINTF(("state changed to %x\n", letoh32(*status)));
1536 
1537 			if (letoh32(*status) & 1) {
1538 				/* the radio button has to be pushed */
1539 				printf("%s: Radio transmitter is off\n",
1540 				    sc->sc_dev.dv_xname);
1541 				/* turn the interface down */
1542 				ifp->if_flags &= ~IFF_UP;
1543 				iwn_stop(ifp, 1);
1544 				return;	/* no further processing */
1545 			}
1546 			break;
1547 		}
1548 		case IWN_START_SCAN:
1549 		{
1550 			struct iwn_start_scan *scan =
1551 			    (struct iwn_start_scan *)(desc + 1);
1552 
1553 			DPRINTFN(2, ("scanning channel %d status %x\n",
1554 			    scan->chan, letoh32(scan->status)));
1555 
1556 			/* fix current channel */
1557 			ic->ic_bss->ni_chan = &ic->ic_channels[scan->chan];
1558 			break;
1559 		}
1560 		case IWN_STOP_SCAN:
1561 		{
1562 			struct iwn_stop_scan *scan =
1563 			    (struct iwn_stop_scan *)(desc + 1);
1564 
1565 			DPRINTF(("scan finished nchan=%d status=%d chan=%d\n",
1566 			    scan->nchan, scan->status, scan->chan));
1567 
1568 			if (scan->status == 1 && scan->chan <= 14) {
1569 				/*
1570 				 * We just finished scanning 802.11g channels,
1571 				 * start scanning 802.11a ones.
1572 				 */
1573 				if (iwn_scan(sc, IEEE80211_CHAN_A) == 0)
1574 					break;
1575 			}
1576 			ieee80211_end_scan(ifp);
1577 			break;
1578 		}
1579 		}
1580 
1581 		sc->rxq.cur = (sc->rxq.cur + 1) % IWN_RX_RING_COUNT;
1582 	}
1583 
1584 	/* tell the firmware what we have processed */
1585 	hw = (hw == 0) ? IWN_RX_RING_COUNT - 1 : hw - 1;
1586 	IWN_WRITE(sc, IWN_RX_WIDX, hw & ~7);
1587 }
1588 
1589 int
1590 iwn_intr(void *arg)
1591 {
1592 	struct iwn_softc *sc = arg;
1593 	struct ifnet *ifp = &sc->sc_ic.ic_if;
1594 	uint32_t r1, r2;
1595 
1596 	/* disable interrupts */
1597 	IWN_WRITE(sc, IWN_MASK, 0);
1598 
1599 	r1 = IWN_READ(sc, IWN_INTR);
1600 	r2 = IWN_READ(sc, IWN_INTR_STATUS);
1601 
1602 	if (r1 == 0 && r2 == 0) {
1603 		if (ifp->if_flags & IFF_UP)
1604 			IWN_WRITE(sc, IWN_MASK, IWN_INTR_MASK);
1605 		return 0;	/* not for us */
1606 	}
1607 
1608 	if (r1 == 0xffffffff)
1609 		return 0;	/* hardware gone */
1610 
1611 	/* ack interrupts */
1612 	IWN_WRITE(sc, IWN_INTR, r1);
1613 	IWN_WRITE(sc, IWN_INTR_STATUS, r2);
1614 
1615 	DPRINTFN(6, ("interrupt reg1=%x reg2=%x\n", r1, r2));
1616 
1617 	if (r1 & IWN_RF_TOGGLED) {
1618 		uint32_t tmp = IWN_READ(sc, IWN_GPIO_CTL);
1619 		printf("%s: RF switch: radio %s\n", sc->sc_dev.dv_xname,
1620 		    (tmp & IWN_GPIO_RF_ENABLED) ? "enabled" : "disabled");
1621 	}
1622 	if (r1 & IWN_CT_REACHED) {
1623 		printf("%s: critical temperature reached!\n",
1624 		    sc->sc_dev.dv_xname);
1625 	}
1626 	if (r1 & (IWN_SW_ERROR | IWN_HW_ERROR)) {
1627 		printf("%s: fatal firmware error\n", sc->sc_dev.dv_xname);
1628 		ifp->if_flags &= ~IFF_UP;
1629 		iwn_stop(ifp, 1);
1630 		return 1;
1631 	}
1632 	if ((r1 & (IWN_RX_INTR | IWN_SW_RX_INTR)) ||
1633 	    (r2 & IWN_RX_STATUS_INTR))
1634 		iwn_notif_intr(sc);
1635 
1636 	if (r1 & IWN_ALIVE_INTR)
1637 		wakeup(sc);
1638 
1639 	/* re-enable interrupts */
1640 	if (ifp->if_flags & IFF_UP)
1641 		IWN_WRITE(sc, IWN_MASK, IWN_INTR_MASK);
1642 
1643 	return 1;
1644 }
1645 
1646 uint8_t
1647 iwn_plcp_signal(int rate)
1648 {
1649 	switch (rate) {
1650 	/* CCK rates (returned values are device-dependent) */
1651 	case 2:		return 10;
1652 	case 4:		return 20;
1653 	case 11:	return 55;
1654 	case 22:	return 110;
1655 
1656 	/* OFDM rates (cf IEEE Std 802.11a-1999, pp. 14 Table 80) */
1657 	/* R1-R4, (u)ral is R4-R1 */
1658 	case 12:	return 0xd;
1659 	case 18:	return 0xf;
1660 	case 24:	return 0x5;
1661 	case 36:	return 0x7;
1662 	case 48:	return 0x9;
1663 	case 72:	return 0xb;
1664 	case 96:	return 0x1;
1665 	case 108:	return 0x3;
1666 	case 120:	return 0x3;
1667 	}
1668 	/* unknown rate (should not get there) */
1669 	return 0;
1670 }
1671 
1672 /* determine if a given rate is CCK or OFDM */
1673 #define IWN_RATE_IS_OFDM(rate) ((rate) >= 12 && (rate) != 22)
1674 
1675 int
1676 iwn_tx_data(struct iwn_softc *sc, struct mbuf *m0, struct ieee80211_node *ni,
1677     int ac)
1678 {
1679 	struct ieee80211com *ic = &sc->sc_ic;
1680 	struct iwn_tx_ring *ring = &sc->txq[ac];
1681 	struct iwn_tx_desc *desc;
1682 	struct iwn_tx_data *data;
1683 	struct iwn_tx_cmd *cmd;
1684 	struct iwn_cmd_data *tx;
1685 	struct ieee80211_frame *wh;
1686 	struct ieee80211_key *k;
1687 	struct mbuf *mnew;
1688 	bus_addr_t paddr;
1689 	uint32_t flags;
1690 	uint8_t type;
1691 	u_int hdrlen;
1692 	int i, rate, error, pad;
1693 
1694 	desc = &ring->desc[ring->cur];
1695 	data = &ring->data[ring->cur];
1696 
1697 	wh = mtod(m0, struct ieee80211_frame *);
1698 	hdrlen = ieee80211_get_hdrlen(wh);
1699 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
1700 
1701 	/* pickup a rate */
1702 	if (IEEE80211_IS_MULTICAST(wh->i_addr1) ||
1703 	    type != IEEE80211_FC0_TYPE_DATA) {
1704 		/* mgmt/multicast frames are sent at the lowest avail. rate */
1705 		rate = ni->ni_rates.rs_rates[0];
1706 	} else if (ic->ic_fixed_rate != -1) {
1707 		rate = ic->ic_sup_rates[ic->ic_curmode].
1708 		    rs_rates[ic->ic_fixed_rate];
1709 	} else
1710 		rate = ni->ni_rates.rs_rates[ni->ni_txrate];
1711 	rate &= IEEE80211_RATE_VAL;
1712 
1713 #if NBPFILTER > 0
1714 	if (sc->sc_drvbpf != NULL) {
1715 		struct mbuf mb;
1716 		struct iwn_tx_radiotap_header *tap = &sc->sc_txtap;
1717 
1718 		tap->wt_flags = 0;
1719 		tap->wt_chan_freq = htole16(ni->ni_chan->ic_freq);
1720 		tap->wt_chan_flags = htole16(ni->ni_chan->ic_flags);
1721 		tap->wt_rate = rate;
1722 		tap->wt_hwqueue = ac;
1723 		if (wh->i_fc[1] & IEEE80211_FC1_WEP)
1724 			tap->wt_flags |= IEEE80211_RADIOTAP_F_WEP;
1725 
1726 		mb.m_data = (caddr_t)tap;
1727 		mb.m_len = sc->sc_txtap_len;
1728 		mb.m_next = m0;
1729 		mb.m_nextpkt = NULL;
1730 		mb.m_type = 0;
1731 		mb.m_flags = 0;
1732 		bpf_mtap(sc->sc_drvbpf, &mb, BPF_DIRECTION_OUT);
1733 	}
1734 #endif
1735 
1736 	cmd = &ring->cmd[ring->cur];
1737 	cmd->code = IWN_CMD_TX_DATA;
1738 	cmd->flags = 0;
1739 	cmd->qid = ring->qid;
1740 	cmd->idx = ring->cur;
1741 
1742 	tx = (struct iwn_cmd_data *)cmd->data;
1743 	/* no need to bzero tx, all fields are reinitialized here */
1744 
1745 	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
1746 		k = ieee80211_get_txkey(ic, wh, ni);
1747 
1748 		if ((m0 = ieee80211_encrypt(ic, m0, k)) == NULL)
1749 			return ENOBUFS;
1750 
1751 		wh = mtod(m0, struct ieee80211_frame *);
1752 	}
1753 
1754 	flags = IWN_TX_AUTO_SEQ;
1755 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1))
1756 		flags |= IWN_TX_NEED_ACK;
1757 
1758 	if (IEEE80211_IS_MULTICAST(wh->i_addr1) ||
1759 	    type != IEEE80211_FC0_TYPE_DATA)
1760 		tx->id = IWN_ID_BROADCAST;
1761 	else
1762 		tx->id = IWN_ID_BSS;
1763 
1764 	/* check if RTS/CTS or CTS-to-self protection must be used */
1765 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1766 		/* multicast frames are not sent at OFDM rates in 802.11b/g */
1767 		if (m0->m_pkthdr.len + IEEE80211_CRC_LEN >
1768 		    ic->ic_rtsthreshold) {
1769 			flags |= IWN_TX_NEED_RTS | IWN_TX_FULL_TXOP;
1770 		} else if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
1771 		    IWN_RATE_IS_OFDM(rate)) {
1772 			if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
1773 				flags |= IWN_TX_NEED_CTS | IWN_TX_FULL_TXOP;
1774 			else if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
1775 				flags |= IWN_TX_NEED_RTS | IWN_TX_FULL_TXOP;
1776 		}
1777 	}
1778 
1779 	if (type == IEEE80211_FC0_TYPE_MGT) {
1780 		uint8_t subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
1781 
1782 		/* tell h/w to set timestamp in probe responses */
1783 		if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
1784 			flags |= IWN_TX_INSERT_TSTAMP;
1785 
1786 		if (subtype == IEEE80211_FC0_SUBTYPE_ASSOC_REQ ||
1787 		    subtype == IEEE80211_FC0_SUBTYPE_REASSOC_REQ)
1788 			tx->timeout = htole16(3);
1789 		else
1790 			tx->timeout = htole16(2);
1791 	} else
1792 		tx->timeout = htole16(0);
1793 
1794 	if (hdrlen & 3) {
1795 		/* first segment's length must be a multiple of 4 */
1796 		flags |= IWN_TX_NEED_PADDING;
1797 		pad = 4 - (hdrlen & 3);
1798 	} else
1799 		pad = 0;
1800 
1801 	tx->flags = htole32(flags);
1802 	tx->len = htole16(m0->m_pkthdr.len);
1803 	tx->rate = iwn_plcp_signal(rate);
1804 	tx->rts_ntries = 60;
1805 	tx->data_ntries = 15;
1806 	tx->lifetime = htole32(IWN_LIFETIME_INFINITE);
1807 
1808 	/* XXX alternate between Ant A and Ant B ? */
1809 	tx->rflags = IWN_RFLAG_ANT_B;
1810 	if (tx->id == IWN_ID_BROADCAST) {
1811 		tx->ridx = IWN_MAX_TX_RETRIES - 1;
1812 		if (!IWN_RATE_IS_OFDM(rate))
1813 			tx->rflags |= IWN_RFLAG_CCK;
1814 	} else {
1815 		tx->ridx = ni->ni_rates.rs_nrates - ni->ni_txrate - 1;
1816 		/* tell adapter to ignore rflags */
1817 		tx->flags |= htole32(IWN_TX_MRR_INDEX);
1818 	}
1819 
1820 	/* copy and trim IEEE802.11 header */
1821 	memcpy((uint8_t *)(tx + 1), wh, hdrlen);
1822 	m_adj(m0, hdrlen);
1823 
1824 	error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m0,
1825 	    BUS_DMA_NOWAIT);
1826 	if (error != 0 && error != EFBIG) {
1827 		printf("%s: could not map mbuf (error %d)\n",
1828 		    sc->sc_dev.dv_xname, error);
1829 		m_freem(m0);
1830 		return error;
1831 	}
1832 	if (error != 0) {
1833 		/* too many fragments, linearize */
1834 
1835 		MGETHDR(mnew, M_DONTWAIT, MT_DATA);
1836 		if (mnew == NULL) {
1837 			m_freem(m0);
1838 			return ENOMEM;
1839 		}
1840 		M_DUP_PKTHDR(mnew, m0);
1841 		if (m0->m_pkthdr.len > MHLEN) {
1842 			MCLGET(mnew, M_DONTWAIT);
1843 			if (!(mnew->m_flags & M_EXT)) {
1844 				m_freem(m0);
1845 				m_freem(mnew);
1846 				return ENOMEM;
1847 			}
1848 		}
1849 
1850 		m_copydata(m0, 0, m0->m_pkthdr.len, mtod(mnew, caddr_t));
1851 		m_freem(m0);
1852 		mnew->m_len = mnew->m_pkthdr.len;
1853 		m0 = mnew;
1854 
1855 		error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m0,
1856 		    BUS_DMA_NOWAIT);
1857 		if (error != 0) {
1858 			printf("%s: could not map mbuf (error %d)\n",
1859 			    sc->sc_dev.dv_xname, error);
1860 			m_freem(m0);
1861 			return error;
1862 		}
1863 	}
1864 
1865 	data->m = m0;
1866 	data->ni = ni;
1867 
1868 	DPRINTFN(4, ("sending data: qid=%d idx=%d len=%d nsegs=%d\n",
1869 	    ring->qid, ring->cur, m0->m_pkthdr.len, data->map->dm_nsegs));
1870 
1871 	paddr = ring->cmd_dma.paddr + ring->cur * sizeof (struct iwn_tx_cmd);
1872 	tx->loaddr = htole32(paddr + 4 +
1873 	    offsetof(struct iwn_cmd_data, ntries));
1874 	tx->hiaddr = 0;	/* limit to 32-bit physical addresses */
1875 
1876 	/* first scatter/gather segment is used by the tx data command */
1877 	IWN_SET_DESC_NSEGS(desc, 1 + data->map->dm_nsegs);
1878 	IWN_SET_DESC_SEG(desc, 0, paddr, 4 + sizeof (*tx) + hdrlen + pad);
1879 	for (i = 1; i <= data->map->dm_nsegs; i++) {
1880 		IWN_SET_DESC_SEG(desc, i, data->map->dm_segs[i - 1].ds_addr,
1881 		     data->map->dm_segs[i - 1].ds_len);
1882 	}
1883 	sc->shared->len[ring->qid][ring->cur] =
1884 	    htole16(hdrlen + m0->m_pkthdr.len + 8);
1885 	if (ring->cur < IWN_TX_WINDOW) {
1886 		sc->shared->len[ring->qid][ring->cur + IWN_TX_RING_COUNT] =
1887 		    htole16(hdrlen + m0->m_pkthdr.len + 8);
1888 	}
1889 	ring->queued++;
1890 
1891 	/* kick Tx ring */
1892 	ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT;
1893 	IWN_WRITE(sc, IWN_TX_WIDX, ring->qid << 8 | ring->cur);
1894 
1895 	return 0;
1896 }
1897 
1898 void
1899 iwn_start(struct ifnet *ifp)
1900 {
1901 	struct iwn_softc *sc = ifp->if_softc;
1902 	struct ieee80211com *ic = &sc->sc_ic;
1903 	struct ieee80211_node *ni;
1904 	struct mbuf *m0;
1905 
1906 	/*
1907 	 * net80211 may still try to send management frames even if the
1908 	 * IFF_RUNNING flag is not set...
1909 	 */
1910 	if ((ifp->if_flags & (IFF_RUNNING | IFF_OACTIVE)) != IFF_RUNNING)
1911 		return;
1912 
1913 	for (;;) {
1914 		IF_POLL(&ic->ic_mgtq, m0);
1915 		if (m0 != NULL) {
1916 			/* management frames go into ring 0 */
1917 			if (sc->txq[0].queued >= IWN_TX_RING_COUNT - 8) {
1918 				ifp->if_flags |= IFF_OACTIVE;
1919 				break;
1920 			}
1921 			IF_DEQUEUE(&ic->ic_mgtq, m0);
1922 
1923 			ni = (struct ieee80211_node *)m0->m_pkthdr.rcvif;
1924 			m0->m_pkthdr.rcvif = NULL;
1925 #if NBPFILTER > 0
1926 			if (ic->ic_rawbpf != NULL)
1927 				bpf_mtap(ic->ic_rawbpf, m0, BPF_DIRECTION_OUT);
1928 #endif
1929 			if (iwn_tx_data(sc, m0, ni, 0) != 0)
1930 				break;
1931 
1932 		} else {
1933 			if (ic->ic_state != IEEE80211_S_RUN)
1934 				break;
1935 			IFQ_POLL(&ifp->if_snd, m0);
1936 			if (m0 == NULL)
1937 				break;
1938 			if (sc->txq[0].queued >= IWN_TX_RING_COUNT - 8) {
1939 				/* there is no place left in this ring */
1940 				ifp->if_flags |= IFF_OACTIVE;
1941 				break;
1942 			}
1943 			IFQ_DEQUEUE(&ifp->if_snd, m0);
1944 #if NBPFILTER > 0
1945 			if (ifp->if_bpf != NULL)
1946 				bpf_mtap(ifp->if_bpf, m0, BPF_DIRECTION_OUT);
1947 #endif
1948 			m0 = ieee80211_encap(ifp, m0, &ni);
1949 			if (m0 == NULL)
1950 				continue;
1951 #if NBPFILTER > 0
1952 			if (ic->ic_rawbpf != NULL)
1953 				bpf_mtap(ic->ic_rawbpf, m0, BPF_DIRECTION_OUT);
1954 #endif
1955 			if (iwn_tx_data(sc, m0, ni, 0) != 0) {
1956 				if (ni != NULL)
1957 					ieee80211_release_node(ic, ni);
1958 				ifp->if_oerrors++;
1959 				break;
1960 			}
1961 		}
1962 
1963 		sc->sc_tx_timer = 5;
1964 		ifp->if_timer = 1;
1965 	}
1966 }
1967 
1968 void
1969 iwn_watchdog(struct ifnet *ifp)
1970 {
1971 	struct iwn_softc *sc = ifp->if_softc;
1972 
1973 	ifp->if_timer = 0;
1974 
1975 	if (sc->sc_tx_timer > 0) {
1976 		if (--sc->sc_tx_timer == 0) {
1977 			printf("%s: device timeout\n", sc->sc_dev.dv_xname);
1978 			ifp->if_flags &= ~IFF_UP;
1979 			iwn_stop(ifp, 1);
1980 			ifp->if_oerrors++;
1981 			return;
1982 		}
1983 		ifp->if_timer = 1;
1984 	}
1985 
1986 	ieee80211_watchdog(ifp);
1987 }
1988 
1989 int
1990 iwn_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1991 {
1992 	struct iwn_softc *sc = ifp->if_softc;
1993 	struct ieee80211com *ic = &sc->sc_ic;
1994 	struct ifaddr *ifa;
1995 	struct ifreq *ifr;
1996 	int s, error = 0;
1997 
1998 	s = splnet();
1999 
2000 	switch (cmd) {
2001 	case SIOCSIFADDR:
2002 		ifa = (struct ifaddr *)data;
2003 		ifp->if_flags |= IFF_UP;
2004 #ifdef INET
2005 		if (ifa->ifa_addr->sa_family == AF_INET)
2006 			arp_ifinit(&ic->ic_ac, ifa);
2007 #endif
2008 		/* FALLTHROUGH */
2009 	case SIOCSIFFLAGS:
2010 		if (ifp->if_flags & IFF_UP) {
2011 			if (!(ifp->if_flags & IFF_RUNNING))
2012 				iwn_init(ifp);
2013 		} else {
2014 			if (ifp->if_flags & IFF_RUNNING)
2015 				iwn_stop(ifp, 1);
2016 		}
2017 		break;
2018 
2019 	case SIOCADDMULTI:
2020 	case SIOCDELMULTI:
2021 		ifr = (struct ifreq *)data;
2022 		error = (cmd == SIOCADDMULTI) ?
2023 		    ether_addmulti(ifr, &ic->ic_ac) :
2024 		    ether_delmulti(ifr, &ic->ic_ac);
2025 
2026 		if (error == ENETRESET)
2027 			error = 0;
2028 		break;
2029 
2030 	default:
2031 		error = ieee80211_ioctl(ifp, cmd, data);
2032 	}
2033 
2034 	if (error == ENETRESET) {
2035 		if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
2036 		    (IFF_UP | IFF_RUNNING)) {
2037 			iwn_stop(ifp, 0);
2038 			iwn_init(ifp);
2039 		}
2040 		error = 0;
2041 	}
2042 
2043 	splx(s);
2044 	return error;
2045 }
2046 
2047 void
2048 iwn_read_eeprom(struct iwn_softc *sc)
2049 {
2050 	struct ieee80211com *ic = &sc->sc_ic;
2051 	char domain[4];
2052 	uint16_t val;
2053 	int i, error;
2054 
2055 	if ((error = iwn_eeprom_lock(sc)) != 0) {
2056 		printf("%s: could not lock EEPROM (error=%d)\n",
2057 		    sc->sc_dev.dv_xname, error);
2058 		return;
2059 	}
2060 	/* read and print regulatory domain */
2061 	iwn_read_prom_data(sc, IWN_EEPROM_DOMAIN, domain, 4);
2062 	printf(", %.4s", domain);
2063 
2064 	/* read and print MAC address */
2065 	iwn_read_prom_data(sc, IWN_EEPROM_MAC, ic->ic_myaddr, 6);
2066 	printf(", address %s\n", ether_sprintf(ic->ic_myaddr));
2067 
2068 	/* read the list of authorized channels */
2069 	for (i = 0; i < IWN_CHAN_BANDS_COUNT; i++)
2070 		iwn_read_eeprom_channels(sc, i);
2071 
2072 	/* read maximum allowed Tx power for 2GHz and 5GHz bands */
2073 	iwn_read_prom_data(sc, IWN_EEPROM_MAXPOW, &val, 2);
2074 	sc->maxpwr2GHz = val & 0xff;
2075 	sc->maxpwr5GHz = val >> 8;
2076 	/* check that EEPROM values are correct */
2077 	if (sc->maxpwr5GHz < 20 || sc->maxpwr5GHz > 50)
2078 		sc->maxpwr5GHz = 38;
2079 	if (sc->maxpwr2GHz < 20 || sc->maxpwr2GHz > 50)
2080 		sc->maxpwr2GHz = 38;
2081 	DPRINTF(("maxpwr 2GHz=%d 5GHz=%d\n", sc->maxpwr2GHz, sc->maxpwr5GHz));
2082 
2083 	/* read voltage at which samples were taken */
2084 	iwn_read_prom_data(sc, IWN_EEPROM_VOLTAGE, &val, 2);
2085 	sc->eeprom_voltage = (int16_t)letoh16(val);
2086 	DPRINTF(("voltage=%d (in 0.3V)\n", sc->eeprom_voltage));
2087 
2088 	/* read power groups */
2089 	iwn_read_prom_data(sc, IWN_EEPROM_BANDS, sc->bands, sizeof sc->bands);
2090 #ifdef IWN_DEBUG
2091 	if (iwn_debug > 0) {
2092 		for (i = 0; i < IWN_NBANDS; i++)
2093 			iwn_print_power_group(sc, i);
2094 	}
2095 #endif
2096 	iwn_eeprom_unlock(sc);
2097 }
2098 
2099 void
2100 iwn_read_eeprom_channels(struct iwn_softc *sc, int n)
2101 {
2102 	struct ieee80211com *ic = &sc->sc_ic;
2103 	const struct iwn_chan_band *band = &iwn_bands[n];
2104 	struct iwn_eeprom_chan channels[IWN_MAX_CHAN_PER_BAND];
2105 	int chan, i;
2106 
2107 	iwn_read_prom_data(sc, band->addr, channels,
2108 	    band->nchan * sizeof (struct iwn_eeprom_chan));
2109 
2110 	for (i = 0; i < band->nchan; i++) {
2111 		if (!(channels[i].flags & IWN_EEPROM_CHAN_VALID))
2112 			continue;
2113 
2114 		chan = band->chan[i];
2115 
2116 		if (n == 0) {	/* 2GHz band */
2117 			ic->ic_channels[chan].ic_freq =
2118 			    ieee80211_ieee2mhz(chan, IEEE80211_CHAN_2GHZ);
2119 			ic->ic_channels[chan].ic_flags =
2120 			    IEEE80211_CHAN_CCK | IEEE80211_CHAN_OFDM |
2121 			    IEEE80211_CHAN_DYN | IEEE80211_CHAN_2GHZ;
2122 
2123 		} else {	/* 5GHz band */
2124 			/*
2125 			 * Some adapters support channels 7, 8, 11 and 12
2126 			 * both in the 2GHz *and* 5GHz bands.
2127 			 * Because of limitations in our net80211(9) stack,
2128 			 * we can't support these channels in 5GHz band.
2129 			 */
2130 			if (chan <= 14)
2131 				continue;
2132 
2133 			ic->ic_channels[chan].ic_freq =
2134 			    ieee80211_ieee2mhz(chan, IEEE80211_CHAN_5GHZ);
2135 			ic->ic_channels[chan].ic_flags = IEEE80211_CHAN_A;
2136 		}
2137 
2138 		/* is active scan allowed on this channel? */
2139 		if (!(channels[i].flags & IWN_EEPROM_CHAN_ACTIVE)) {
2140 			ic->ic_channels[chan].ic_flags |=
2141 			    IEEE80211_CHAN_PASSIVE;
2142 		}
2143 
2144 		/* save maximum allowed power for this channel */
2145 		sc->maxpwr[chan] = channels[i].maxpwr;
2146 
2147 		DPRINTF(("adding chan %d flags=0x%x maxpwr=%d\n",
2148 		    chan, channels[i].flags, sc->maxpwr[chan]));
2149 	}
2150 }
2151 
2152 #ifdef IWN_DEBUG
2153 void
2154 iwn_print_power_group(struct iwn_softc *sc, int i)
2155 {
2156 	struct iwn_eeprom_band *band = &sc->bands[i];
2157 	struct iwn_eeprom_chan_samples *chans = band->chans;
2158 	int j, c;
2159 
2160 	printf("===band %d===\n", i);
2161 	printf("chan lo=%d, chan hi=%d\n", band->lo, band->hi);
2162 	printf("chan1 num=%d\n", chans[0].num);
2163 	for (c = 0; c < IWN_NTXCHAINS; c++) {
2164 		for (j = 0; j < IWN_NSAMPLES; j++) {
2165 			printf("chain %d, sample %d: temp=%d gain=%d "
2166 			    "power=%d pa_det=%d\n", c, j,
2167 			    chans[0].samples[c][j].temp,
2168 			    chans[0].samples[c][j].gain,
2169 			    chans[0].samples[c][j].power,
2170 			    chans[0].samples[c][j].pa_det);
2171 		}
2172 	}
2173 	printf("chan2 num=%d\n", chans[1].num);
2174 	for (c = 0; c < IWN_NTXCHAINS; c++) {
2175 		for (j = 0; j < IWN_NSAMPLES; j++) {
2176 			printf("chain %d, sample %d: temp=%d gain=%d "
2177 			    "power=%d pa_det=%d\n", c, j,
2178 			    chans[1].samples[c][j].temp,
2179 			    chans[1].samples[c][j].gain,
2180 			    chans[1].samples[c][j].power,
2181 			    chans[1].samples[c][j].pa_det);
2182 		}
2183 	}
2184 }
2185 #endif
2186 
2187 /*
2188  * Send a command to the firmware.
2189  */
2190 int
2191 iwn_cmd(struct iwn_softc *sc, int code, const void *buf, int size, int async)
2192 {
2193 	struct iwn_tx_ring *ring = &sc->txq[4];
2194 	struct iwn_tx_desc *desc;
2195 	struct iwn_tx_cmd *cmd;
2196 	bus_addr_t paddr;
2197 
2198 	KASSERT(size <= sizeof cmd->data);
2199 
2200 	desc = &ring->desc[ring->cur];
2201 	cmd = &ring->cmd[ring->cur];
2202 
2203 	cmd->code = code;
2204 	cmd->flags = 0;
2205 	cmd->qid = ring->qid;
2206 	cmd->idx = ring->cur;
2207 	memcpy(cmd->data, buf, size);
2208 
2209 	paddr = ring->cmd_dma.paddr + ring->cur * sizeof (struct iwn_tx_cmd);
2210 
2211 	IWN_SET_DESC_NSEGS(desc, 1);
2212 	IWN_SET_DESC_SEG(desc, 0, paddr, 4 + size);
2213 	sc->shared->len[ring->qid][ring->cur] = htole16(8);
2214 	if (ring->cur < IWN_TX_WINDOW) {
2215 		sc->shared->len[ring->qid][ring->cur + IWN_TX_RING_COUNT] =
2216 		    htole16(8);
2217 	}
2218 
2219 	/* kick cmd ring */
2220 	ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT;
2221 	IWN_WRITE(sc, IWN_TX_WIDX, ring->qid << 8 | ring->cur);
2222 
2223 	return async ? 0 : tsleep(cmd, PCATCH, "iwncmd", hz);
2224 }
2225 
2226 /*
2227  * Configure hardware multi-rate retries for one node.
2228  */
2229 int
2230 iwn_setup_node_mrr(struct iwn_softc *sc, const struct ieee80211_node *ni,
2231     uint8_t id)
2232 {
2233 	const struct ieee80211_rateset *rs = &ni->ni_rates;
2234 	struct iwn_cmd_mrr mrr;
2235 	uint8_t rate;
2236 	int i, r;
2237 
2238 	memset(&mrr, 0, sizeof mrr);
2239 	mrr.id = id;
2240 	mrr.ssmask = 2;
2241 	mrr.dsmask = 3;
2242 	mrr.ampdu_disable = 3;
2243 	mrr.ampdu_limit = 4000;
2244 
2245 	r = rs->rs_nrates - 1;
2246 	for (i = 0; i < IWN_MAX_TX_RETRIES && r >= 0; i++, r--) {
2247 		rate = rs->rs_rates[r] & IEEE80211_RATE_VAL;
2248 		DPRINTF(("retry #%d: rate %d\n", i, rate));
2249 		mrr.table[i].rate = iwn_plcp_signal(rate);
2250 		mrr.table[i].rflags = IWN_RFLAG_ANT_B;
2251 		if (!IWN_RATE_IS_OFDM(rate))
2252 			mrr.table[i].rflags |= IWN_RFLAG_CCK;
2253 	}
2254 	/* pad with the lowest available bit-rate */
2255 	for (; i < IWN_MAX_TX_RETRIES; i++) {
2256 		rate = rs->rs_rates[0] & IEEE80211_RATE_VAL;
2257 		DPRINTF(("retry #%d: rate %d\n", i, rate));
2258 		mrr.table[i].rate = iwn_plcp_signal(rate);
2259 		mrr.table[i].rflags = IWN_RFLAG_ANT_B;
2260 		if (!IWN_RATE_IS_OFDM(rate))
2261 			mrr.table[i].rflags |= IWN_RFLAG_CCK;
2262 	}
2263 	return iwn_cmd(sc, IWN_CMD_NODE_MRR_SETUP, &mrr, sizeof mrr, 1);
2264 }
2265 
2266 int
2267 iwn_set_fixed_rate(struct iwn_softc *sc, uint8_t id, uint8_t rate, int async)
2268 {
2269 	struct iwn_cmd_mrr mrr;
2270 	int i;
2271 
2272 	memset(&mrr, 0, sizeof mrr);
2273 	mrr.id = id;
2274 	mrr.ssmask = 2;
2275 	mrr.dsmask = 3;
2276 	mrr.ampdu_disable = 3;
2277 	mrr.ampdu_limit = 4000;
2278 
2279 	/* to setup a fixed rate, make all retries use the same rate.. */
2280 	mrr.table[0].rate = iwn_plcp_signal(rate);
2281 	mrr.table[0].rflags = IWN_RFLAG_ANT_B;
2282 	if (!IWN_RATE_IS_OFDM(rate))
2283 		mrr.table[0].rflags |= IWN_RFLAG_CCK;
2284 	for (i = 1; i < IWN_MAX_TX_RETRIES; i++) {
2285 		mrr.table[i].rate = mrr.table[0].rate;
2286 		mrr.table[i].rflags = mrr.table[0].rflags;
2287 	}
2288 	return iwn_cmd(sc, IWN_CMD_NODE_MRR_SETUP, &mrr, sizeof mrr, async);
2289 }
2290 
2291 /*
2292  * Install a pairwise key into the hardware.
2293  */
2294 int
2295 iwn_set_key(struct ieee80211com *ic, struct ieee80211_node *ni,
2296     struct ieee80211_key *k)
2297 {
2298 	struct iwn_softc *sc = ic->ic_softc;
2299 	struct iwn_node_info node;
2300 
2301 	if (k->k_flags & IEEE80211_KEY_GROUP)
2302 		return 0;
2303 
2304 	memset(&node, 0, sizeof node);
2305 
2306 	switch (k->k_cipher) {
2307 	case IEEE80211_CIPHER_CCMP:
2308 		node.security = htole16(IWN_CIPHER_CCMP);
2309 		memcpy(node.key, k->k_key, k->k_len);
2310 		break;
2311 	default:
2312 		return 0;
2313 	}
2314 
2315 	node.id = IWN_ID_BSS;
2316 	IEEE80211_ADDR_COPY(node.macaddr, ni->ni_macaddr);
2317 	node.control = IWN_NODE_UPDATE;
2318 	node.flags = IWN_FLAG_SET_KEY;
2319 
2320 	return iwn_cmd(sc, IWN_CMD_ADD_NODE, &node, sizeof node, 1);
2321 }
2322 
2323 void
2324 iwn_updateedca(struct ieee80211com *ic)
2325 {
2326 #define IWN_EXP2(x)	((1 << (x)) - 1)	/* CWmin = 2^ECWmin - 1 */
2327 	struct iwn_softc *sc = ic->ic_softc;
2328 	struct iwn_edca_params cmd;
2329 	int aci;
2330 
2331 	memset(&cmd, 0, sizeof cmd);
2332 	cmd.flags = htole32(IWN_EDCA_UPDATE);
2333 	for (aci = 0; aci < EDCA_NUM_AC; aci++) {
2334 		const struct ieee80211_edca_ac_params *ac =
2335 		    &ic->ic_edca_ac[aci];
2336 		cmd.ac[aci].aifsn = ac->ac_aifsn;
2337 		cmd.ac[aci].cwmin = htole16(IWN_EXP2(ac->ac_ecwmin));
2338 		cmd.ac[aci].cwmax = htole16(IWN_EXP2(ac->ac_ecwmax));
2339 		cmd.ac[aci].txoplimit =
2340 		    htole16(IEEE80211_TXOP_TO_US(ac->ac_txoplimit));
2341 	}
2342 	(void)iwn_cmd(sc, IWN_CMD_EDCA_PARAMS, &cmd, sizeof cmd, 1);
2343 #undef IWN_EXP2
2344 }
2345 
2346 void
2347 iwn_set_led(struct iwn_softc *sc, uint8_t which, uint8_t off, uint8_t on)
2348 {
2349 	struct iwn_cmd_led led;
2350 
2351 	led.which = which;
2352 	led.unit = htole32(100000);	/* on/off in unit of 100ms */
2353 	led.off = off;
2354 	led.on = on;
2355 
2356 	(void)iwn_cmd(sc, IWN_CMD_SET_LED, &led, sizeof led, 1);
2357 }
2358 
2359 /*
2360  * Set the critical temperature at which the firmware will automatically stop
2361  * the radio transmitter.
2362  */
2363 int
2364 iwn_set_critical_temp(struct iwn_softc *sc)
2365 {
2366 	struct iwn_ucode_info *uc = &sc->ucode_info;
2367 	struct iwn_critical_temp crit;
2368 	uint32_t r1, r2, r3, temp;
2369 
2370 	r1 = letoh32(uc->temp[0].chan20MHz);
2371 	r2 = letoh32(uc->temp[1].chan20MHz);
2372 	r3 = letoh32(uc->temp[2].chan20MHz);
2373 	/* inverse function of iwn_get_temperature() */
2374 	temp = r2 + (IWN_CTOK(110) * (r3 - r1)) / 259;
2375 
2376 	IWN_WRITE(sc, IWN_UCODE_CLR, IWN_CTEMP_STOP_RF);
2377 
2378 	memset(&crit, 0, sizeof crit);
2379 	crit.tempR = htole32(temp);
2380 	DPRINTF(("setting critical temperature to %u\n", temp));
2381 	return iwn_cmd(sc, IWN_CMD_SET_CRITICAL_TEMP, &crit, sizeof crit, 0);
2382 }
2383 
2384 void
2385 iwn_enable_tsf(struct iwn_softc *sc, struct ieee80211_node *ni)
2386 {
2387 	struct iwn_cmd_tsf tsf;
2388 	uint64_t val, mod;
2389 
2390 	memset(&tsf, 0, sizeof tsf);
2391 	memcpy(&tsf.tstamp, ni->ni_tstamp, sizeof (uint64_t));
2392 	tsf.bintval = htole16(ni->ni_intval);
2393 	tsf.lintval = htole16(10);
2394 
2395 	/* compute remaining time until next beacon */
2396 	val = (uint64_t)ni->ni_intval * 1024;	/* msecs -> usecs */
2397 	mod = letoh64(tsf.tstamp) % val;
2398 	tsf.binitval = htole32((uint32_t)(val - mod));
2399 
2400 	DPRINTF(("TSF bintval=%u tstamp=%llu, init=%u\n",
2401 	    ni->ni_intval, letoh64(tsf.tstamp), (uint32_t)(val - mod)));
2402 
2403 	if (iwn_cmd(sc, IWN_CMD_TSF, &tsf, sizeof tsf, 1) != 0)
2404 		printf("%s: could not enable TSF\n", sc->sc_dev.dv_xname);
2405 }
2406 
2407 void
2408 iwn_power_calibration(struct iwn_softc *sc, int temp)
2409 {
2410 	struct ieee80211com *ic = &sc->sc_ic;
2411 
2412 	DPRINTF(("temperature %d->%d\n", sc->temp, temp));
2413 
2414 	/* adjust Tx power if need be (delta >= 3�C) */
2415 	if (abs(temp - sc->temp) < 3)
2416 		return;
2417 
2418 	sc->temp = temp;
2419 
2420 	DPRINTF(("setting Tx power for channel %d\n",
2421 	    ieee80211_chan2ieee(ic, ic->ic_bss->ni_chan)));
2422 	if (iwn_set_txpower(sc, ic->ic_bss->ni_chan, 1) != 0) {
2423 		/* just warn, too bad for the automatic calibration... */
2424 		printf("%s: could not adjust Tx power\n", sc->sc_dev.dv_xname);
2425 	}
2426 }
2427 
2428 /*
2429  * Set Tx power for a given channel (each rate has its own power settings).
2430  * This function takes into account the regulatory information from EEPROM,
2431  * the current temperature and the current voltage.
2432  */
2433 int
2434 iwn_set_txpower(struct iwn_softc *sc, struct ieee80211_channel *ch, int async)
2435 {
2436 /* fixed-point arithmetic division using a n-bit fractional part */
2437 #define fdivround(a, b, n)	\
2438 	((((1 << n) * (a)) / (b) + (1 << n) / 2) / (1 << n))
2439 /* linear interpolation */
2440 #define interpolate(x, x1, y1, x2, y2, n)	\
2441 	((y1) + fdivround(((int)(x) - (x1)) * ((y2) - (y1)), (x2) - (x1), n))
2442 
2443 	static const int tdiv[IWN_NATTEN_GROUPS] = { 9, 8, 8, 8, 6 };
2444 	struct ieee80211com *ic = &sc->sc_ic;
2445 	struct iwn_ucode_info *uc = &sc->ucode_info;
2446 	struct iwn_cmd_txpower cmd;
2447 	struct iwn_eeprom_chan_samples *chans;
2448 	const uint8_t *rf_gain, *dsp_gain;
2449 	int32_t vdiff, tdiff;
2450 	int i, c, grp, maxpwr;
2451 	u_int chan;
2452 
2453 	/* get channel number */
2454 	chan = ieee80211_chan2ieee(ic, ch);
2455 
2456 	memset(&cmd, 0, sizeof cmd);
2457 	cmd.band = IEEE80211_IS_CHAN_5GHZ(ch) ? 0 : 1;
2458 	cmd.chan = chan;
2459 
2460 	if (IEEE80211_IS_CHAN_5GHZ(ch)) {
2461 		maxpwr   = sc->maxpwr5GHz;
2462 		rf_gain  = iwn_rf_gain_5ghz;
2463 		dsp_gain = iwn_dsp_gain_5ghz;
2464 	} else {
2465 		maxpwr   = sc->maxpwr2GHz;
2466 		rf_gain  = iwn_rf_gain_2ghz;
2467 		dsp_gain = iwn_dsp_gain_2ghz;
2468 	}
2469 
2470 	/* compute voltage compensation */
2471 	vdiff = ((int32_t)letoh32(uc->volt) - sc->eeprom_voltage) / 7;
2472 	if (vdiff > 0)
2473 		vdiff *= 2;
2474 	if (abs(vdiff) > 2)
2475 		vdiff = 0;
2476 	DPRINTF(("voltage compensation=%d (UCODE=%d, EEPROM=%d)\n",
2477 	    vdiff, letoh32(uc->volt), sc->eeprom_voltage));
2478 
2479 	/* get channel's attenuation group */
2480 	if (chan <= 20)		/* 1-20 */
2481 		grp = 4;
2482 	else if (chan <= 43)	/* 34-43 */
2483 		grp = 0;
2484 	else if (chan <= 70)	/* 44-70 */
2485 		grp = 1;
2486 	else if (chan <= 124)	/* 71-124 */
2487 		grp = 2;
2488 	else			/* 125-200 */
2489 		grp = 3;
2490 	DPRINTF(("chan %d, attenuation group=%d\n", chan, grp));
2491 
2492 	/* get channel's sub-band */
2493 	for (i = 0; i < IWN_NBANDS; i++)
2494 		if (sc->bands[i].lo != 0 &&
2495 		    sc->bands[i].lo <= chan && chan <= sc->bands[i].hi)
2496 			break;
2497 	chans = sc->bands[i].chans;
2498 	DPRINTF(("chan %d sub-band=%d\n", chan, i));
2499 
2500 	for (c = 0; c < IWN_NTXCHAINS; c++) {
2501 		uint8_t power, gain, temp;
2502 		int maxchpwr, pwr, ridx, idx;
2503 
2504 		power = interpolate(chan,
2505 		    chans[0].num, chans[0].samples[c][1].power,
2506 		    chans[1].num, chans[1].samples[c][1].power, 1);
2507 		gain  = interpolate(chan,
2508 		    chans[0].num, chans[0].samples[c][1].gain,
2509 		    chans[1].num, chans[1].samples[c][1].gain, 1);
2510 		temp  = interpolate(chan,
2511 		    chans[0].num, chans[0].samples[c][1].temp,
2512 		    chans[1].num, chans[1].samples[c][1].temp, 1);
2513 		DPRINTF(("Tx chain %d: power=%d gain=%d temp=%d\n",
2514 		    c, power, gain, temp));
2515 
2516 		/* compute temperature compensation */
2517 		tdiff = ((sc->temp - temp) * 2) / tdiv[grp];
2518 		DPRINTF(("temperature compensation=%d (current=%d, "
2519 		    "EEPROM=%d)\n", tdiff, sc->temp, temp));
2520 
2521 		for (ridx = 0; ridx <= IWN_RIDX_MAX; ridx++) {
2522 			maxchpwr = sc->maxpwr[chan] * 2;
2523 			if ((ridx / 8) & 1) {
2524 				/* MIMO: decrease Tx power (-3dB) */
2525 				maxchpwr -= 6;
2526 			}
2527 
2528 			pwr = maxpwr - 10;
2529 
2530 			/* decrease power for highest OFDM rates */
2531 			if ((ridx % 8) == 5)		/* 48Mbit/s */
2532 				pwr -= 5;
2533 			else if ((ridx % 8) == 6)	/* 54Mbit/s */
2534 				pwr -= 7;
2535 			else if ((ridx % 8) == 7)	/* 60Mbit/s */
2536 				pwr -= 10;
2537 
2538 			if (pwr > maxchpwr)
2539 				pwr = maxchpwr;
2540 
2541 			idx = gain - (pwr - power) - tdiff - vdiff;
2542 			if ((ridx / 8) & 1)	/* MIMO */
2543 				idx += (int32_t)letoh32(uc->atten[grp][c]);
2544 
2545 			if (cmd.band == 0)
2546 				idx += 9;	/* 5GHz */
2547 			if (ridx == IWN_RIDX_MAX)
2548 				idx += 5;	/* CCK */
2549 
2550 			/* make sure idx stays in a valid range */
2551 			if (idx < 0)
2552 				idx = 0;
2553 			else if (idx > IWN_MAX_PWR_INDEX)
2554 				idx = IWN_MAX_PWR_INDEX;
2555 
2556 			DPRINTF(("Tx chain %d, rate idx %d: power=%d\n",
2557 			    c, ridx, idx));
2558 			cmd.power[ridx].rf_gain[c] = rf_gain[idx];
2559 			cmd.power[ridx].dsp_gain[c] = dsp_gain[idx];
2560 		}
2561 	}
2562 
2563 	DPRINTF(("setting tx power for chan %d\n", chan));
2564 	return iwn_cmd(sc, IWN_CMD_TXPOWER, &cmd, sizeof cmd, async);
2565 
2566 #undef interpolate
2567 #undef fdivround
2568 }
2569 
2570 /*
2571  * Get the best (maximum) RSSI among Rx antennas (in dBm).
2572  */
2573 int
2574 iwn_get_rssi(const struct iwn_rx_stat *stat)
2575 {
2576 	uint8_t mask, agc;
2577 	int rssi;
2578 
2579 	mask = (letoh16(stat->antenna) >> 4) & 0x7;
2580 	agc  = (letoh16(stat->agc) >> 7) & 0x7f;
2581 
2582 	rssi = 0;
2583 	if (mask & (1 << 0))	/* Ant A */
2584 		rssi = MAX(rssi, stat->rssi[0]);
2585 	if (mask & (1 << 1))	/* Ant B */
2586 		rssi = MAX(rssi, stat->rssi[2]);
2587 	if (mask & (1 << 2))	/* Ant C */
2588 		rssi = MAX(rssi, stat->rssi[4]);
2589 
2590 	return rssi - agc - IWN_RSSI_TO_DBM;
2591 }
2592 
2593 /*
2594  * Get the average noise among Rx antennas (in dBm).
2595  */
2596 int
2597 iwn_get_noise(const struct iwn_rx_general_stats *stats)
2598 {
2599 	int i, total, nbant, noise;
2600 
2601 	total = nbant = 0;
2602 	for (i = 0; i < 3; i++) {
2603 		if ((noise = letoh32(stats->noise[i]) & 0xff) == 0)
2604 			continue;
2605 		total += noise;
2606 		nbant++;
2607 	}
2608 	/* there should be at least one antenna but check anyway */
2609 	return (nbant == 0) ? -127 : (total / nbant) - 107;
2610 }
2611 
2612 /*
2613  * Read temperature (in degC) from the on-board thermal sensor.
2614  */
2615 int
2616 iwn_get_temperature(struct iwn_softc *sc)
2617 {
2618 	struct iwn_ucode_info *uc = &sc->ucode_info;
2619 	int32_t r1, r2, r3, r4, temp;
2620 
2621 	r1 = letoh32(uc->temp[0].chan20MHz);
2622 	r2 = letoh32(uc->temp[1].chan20MHz);
2623 	r3 = letoh32(uc->temp[2].chan20MHz);
2624 	r4 = letoh32(sc->rawtemp);
2625 
2626 	if (r1 == r3)	/* prevents division by 0 (should not happen) */
2627 		return 0;
2628 
2629 	/* sign-extend 23-bit R4 value to 32-bit */
2630 	r4 = (r4 << 8) >> 8;
2631 	/* compute temperature */
2632 	temp = (259 * (r4 - r2)) / (r3 - r1);
2633 	temp = (temp * 97) / 100 + 8;
2634 
2635 	DPRINTF(("temperature %dK/%dC\n", temp, IWN_KTOC(temp)));
2636 	return IWN_KTOC(temp);
2637 }
2638 
2639 /*
2640  * Initialize sensitivity calibration state machine.
2641  */
2642 int
2643 iwn_init_sensitivity(struct iwn_softc *sc)
2644 {
2645 	struct iwn_calib_state *calib = &sc->calib;
2646 	struct iwn_phy_calib_cmd cmd;
2647 	int error;
2648 
2649 	/* reset calibration state */
2650 	memset(calib, 0, sizeof (*calib));
2651 	calib->state = IWN_CALIB_STATE_INIT;
2652 	calib->cck_state = IWN_CCK_STATE_HIFA;
2653 	/* initial values taken from the reference driver */
2654 	calib->corr_ofdm_x1     = 105;
2655 	calib->corr_ofdm_mrc_x1 = 220;
2656 	calib->corr_ofdm_x4     =  90;
2657 	calib->corr_ofdm_mrc_x4 = 170;
2658 	calib->corr_cck_x4      = 125;
2659 	calib->corr_cck_mrc_x4  = 200;
2660 	calib->energy_cck       = 100;
2661 
2662 	/* write initial sensitivity values */
2663 	if ((error = iwn_send_sensitivity(sc)) != 0)
2664 		return error;
2665 
2666 	memset(&cmd, 0, sizeof cmd);
2667 	cmd.code = IWN_SET_DIFF_GAIN;
2668 	/* differential gains initially set to 0 for all 3 antennas */
2669 	DPRINTF(("setting differential gains\n"));
2670 	return iwn_cmd(sc, IWN_PHY_CALIB, &cmd, sizeof cmd, 1);
2671 }
2672 
2673 /*
2674  * Collect noise and RSSI statistics for the first 20 beacons received
2675  * after association and use them to determine connected antennas and
2676  * set differential gains.
2677  */
2678 void
2679 iwn_compute_differential_gain(struct iwn_softc *sc,
2680     const struct iwn_rx_general_stats *stats)
2681 {
2682 	struct iwn_calib_state *calib = &sc->calib;
2683 	struct iwn_phy_calib_cmd cmd;
2684 	int i, val;
2685 
2686 	/* accumulate RSSI and noise for all 3 antennas */
2687 	for (i = 0; i < 3; i++) {
2688 		calib->rssi[i] += letoh32(stats->rssi[i]) & 0xff;
2689 		calib->noise[i] += letoh32(stats->noise[i]) & 0xff;
2690 	}
2691 
2692 	/* we update differential gain only once after 20 beacons */
2693 	if (++calib->nbeacons < 20)
2694 		return;
2695 
2696 	/* determine antenna with highest average RSSI */
2697 	val = MAX(calib->rssi[0], calib->rssi[1]);
2698 	val = MAX(calib->rssi[2], val);
2699 
2700 	/* determine which antennas are connected */
2701 	sc->antmsk = 0;
2702 	for (i = 0; i < 3; i++)
2703 		if (val - calib->rssi[i] <= 15 * 20)
2704 			sc->antmsk |= 1 << i;
2705 	/* if neither Ant A and Ant B are connected.. */
2706 	if ((sc->antmsk & (1 << 0 | 1 << 1)) == 0)
2707 		sc->antmsk |= 1 << 1;	/* ..mark Ant B as connected! */
2708 
2709 	/* get minimal noise among connected antennas */
2710 	val = INT_MAX;	/* ok, there's at least one */
2711 	for (i = 0; i < 3; i++)
2712 		if (sc->antmsk & (1 << i))
2713 			val = MIN(calib->noise[i], val);
2714 
2715 	memset(&cmd, 0, sizeof cmd);
2716 	cmd.code = IWN_SET_DIFF_GAIN;
2717 	/* set differential gains for connected antennas */
2718 	for (i = 0; i < 3; i++) {
2719 		if (sc->antmsk & (1 << i)) {
2720 			cmd.gain[i] = (calib->noise[i] - val) / 30;
2721 			/* limit differential gain to 3 */
2722 			cmd.gain[i] = MIN(cmd.gain[i], 3);
2723 			cmd.gain[i] |= IWN_GAIN_SET;
2724 		}
2725 	}
2726 	DPRINTF(("setting differential gains Ant A/B/C: %x/%x/%x (%x)\n",
2727 	    cmd.gain[0], cmd.gain[1], cmd.gain[2], sc->antmsk));
2728 	if (iwn_cmd(sc, IWN_PHY_CALIB, &cmd, sizeof cmd, 1) == 0)
2729 		calib->state = IWN_CALIB_STATE_RUN;
2730 }
2731 
2732 /*
2733  * Tune RF Rx sensitivity based on the number of false alarms detected
2734  * during the last beacon period.
2735  */
2736 void
2737 iwn_tune_sensitivity(struct iwn_softc *sc, const struct iwn_rx_stats *stats)
2738 {
2739 #define inc_clip(val, inc, max)			\
2740 	if ((val) < (max)) {			\
2741 		if ((val) < (max) - (inc))	\
2742 			(val) += (inc);		\
2743 		else				\
2744 			(val) = (max);		\
2745 		needs_update = 1;		\
2746 	}
2747 #define dec_clip(val, dec, min)			\
2748 	if ((val) > (min)) {			\
2749 		if ((val) > (min) + (dec))	\
2750 			(val) -= (dec);		\
2751 		else				\
2752 			(val) = (min);		\
2753 		needs_update = 1;		\
2754 	}
2755 
2756 	struct iwn_calib_state *calib = &sc->calib;
2757 	uint32_t val, rxena, fa;
2758 	uint32_t energy[3], energy_min;
2759 	uint8_t noise[3], noise_ref;
2760 	int i, needs_update = 0;
2761 
2762 	/* check that we've been enabled long enough */
2763 	if ((rxena = letoh32(stats->general.load)) == 0)
2764 		return;
2765 
2766 	/* compute number of false alarms since last call for OFDM */
2767 	fa  = letoh32(stats->ofdm.bad_plcp) - calib->bad_plcp_ofdm;
2768 	fa += letoh32(stats->ofdm.fa) - calib->fa_ofdm;
2769 	fa *= 200 * 1024;	/* 200TU */
2770 
2771 	/* save counters values for next call */
2772 	calib->bad_plcp_ofdm = letoh32(stats->ofdm.bad_plcp);
2773 	calib->fa_ofdm = letoh32(stats->ofdm.fa);
2774 
2775 	if (fa > 50 * rxena) {
2776 		/* high false alarm count, decrease sensitivity */
2777 		DPRINTFN(2, ("OFDM high false alarm count: %u\n", fa));
2778 		inc_clip(calib->corr_ofdm_x1,     1, 140);
2779 		inc_clip(calib->corr_ofdm_mrc_x1, 1, 270);
2780 		inc_clip(calib->corr_ofdm_x4,     1, 120);
2781 		inc_clip(calib->corr_ofdm_mrc_x4, 1, 210);
2782 
2783 	} else if (fa < 5 * rxena) {
2784 		/* low false alarm count, increase sensitivity */
2785 		DPRINTFN(2, ("OFDM low false alarm count: %u\n", fa));
2786 		dec_clip(calib->corr_ofdm_x1,     1, 105);
2787 		dec_clip(calib->corr_ofdm_mrc_x1, 1, 220);
2788 		dec_clip(calib->corr_ofdm_x4,     1,  85);
2789 		dec_clip(calib->corr_ofdm_mrc_x4, 1, 170);
2790 	}
2791 
2792 	/* compute maximum noise among 3 antennas */
2793 	for (i = 0; i < 3; i++)
2794 		noise[i] = (letoh32(stats->general.noise[i]) >> 8) & 0xff;
2795 	val = MAX(noise[0], noise[1]);
2796 	val = MAX(noise[2], val);
2797 	/* insert it into our samples table */
2798 	calib->noise_samples[calib->cur_noise_sample] = val;
2799 	calib->cur_noise_sample = (calib->cur_noise_sample + 1) % 20;
2800 
2801 	/* compute maximum noise among last 20 samples */
2802 	noise_ref = calib->noise_samples[0];
2803 	for (i = 1; i < 20; i++)
2804 		noise_ref = MAX(noise_ref, calib->noise_samples[i]);
2805 
2806 	/* compute maximum energy among 3 antennas */
2807 	for (i = 0; i < 3; i++)
2808 		energy[i] = letoh32(stats->general.energy[i]);
2809 	val = MIN(energy[0], energy[1]);
2810 	val = MIN(energy[2], val);
2811 	/* insert it into our samples table */
2812 	calib->energy_samples[calib->cur_energy_sample] = val;
2813 	calib->cur_energy_sample = (calib->cur_energy_sample + 1) % 10;
2814 
2815 	/* compute minimum energy among last 10 samples */
2816 	energy_min = calib->energy_samples[0];
2817 	for (i = 1; i < 10; i++)
2818 		energy_min = MAX(energy_min, calib->energy_samples[i]);
2819 	energy_min += 6;
2820 
2821 	/* compute number of false alarms since last call for CCK */
2822 	fa  = letoh32(stats->cck.bad_plcp) - calib->bad_plcp_cck;
2823 	fa += letoh32(stats->cck.fa) - calib->fa_cck;
2824 	fa *= 200 * 1024;	/* 200TU */
2825 
2826 	/* save counters values for next call */
2827 	calib->bad_plcp_cck = letoh32(stats->cck.bad_plcp);
2828 	calib->fa_cck = letoh32(stats->cck.fa);
2829 
2830 	if (fa > 50 * rxena) {
2831 		/* high false alarm count, decrease sensitivity */
2832 		DPRINTFN(2, ("CCK high false alarm count: %u\n", fa));
2833 		calib->cck_state = IWN_CCK_STATE_HIFA;
2834 		calib->low_fa = 0;
2835 
2836 		if (calib->corr_cck_x4 > 160) {
2837 			calib->noise_ref = noise_ref;
2838 			if (calib->energy_cck > 2)
2839 				dec_clip(calib->energy_cck, 2, energy_min);
2840 		}
2841 		if (calib->corr_cck_x4 < 160) {
2842 			calib->corr_cck_x4 = 161;
2843 			needs_update = 1;
2844 		} else
2845 			inc_clip(calib->corr_cck_x4, 3, 200);
2846 
2847 		inc_clip(calib->corr_cck_mrc_x4, 3, 400);
2848 
2849 	} else if (fa < 5 * rxena) {
2850 		/* low false alarm count, increase sensitivity */
2851 		DPRINTFN(2, ("CCK low false alarm count: %u\n", fa));
2852 		calib->cck_state = IWN_CCK_STATE_LOFA;
2853 		calib->low_fa++;
2854 
2855 		if (calib->cck_state != 0 &&
2856 		    ((calib->noise_ref - noise_ref) > 2 ||
2857 		     calib->low_fa > 100)) {
2858 			inc_clip(calib->energy_cck,      2,  97);
2859 			dec_clip(calib->corr_cck_x4,     3, 125);
2860 			dec_clip(calib->corr_cck_mrc_x4, 3, 200);
2861 		}
2862 	} else {
2863 		/* not worth to increase or decrease sensitivity */
2864 		DPRINTFN(2, ("CCK normal false alarm count: %u\n", fa));
2865 		calib->low_fa = 0;
2866 		calib->noise_ref = noise_ref;
2867 
2868 		if (calib->cck_state == IWN_CCK_STATE_HIFA) {
2869 			/* previous interval had many false alarms */
2870 			dec_clip(calib->energy_cck, 8, energy_min);
2871 		}
2872 		calib->cck_state = IWN_CCK_STATE_INIT;
2873 	}
2874 
2875 	if (needs_update)
2876 		(void)iwn_send_sensitivity(sc);
2877 #undef dec_clip
2878 #undef inc_clip
2879 }
2880 
2881 int
2882 iwn_send_sensitivity(struct iwn_softc *sc)
2883 {
2884 	struct iwn_calib_state *calib = &sc->calib;
2885 	struct iwn_sensitivity_cmd cmd;
2886 
2887 	memset(&cmd, 0, sizeof cmd);
2888 	cmd.which = IWN_SENSITIVITY_WORKTBL;
2889 	/* OFDM modulation */
2890 	cmd.corr_ofdm_x1     = htole16(calib->corr_ofdm_x1);
2891 	cmd.corr_ofdm_mrc_x1 = htole16(calib->corr_ofdm_mrc_x1);
2892 	cmd.corr_ofdm_x4     = htole16(calib->corr_ofdm_x4);
2893 	cmd.corr_ofdm_mrc_x4 = htole16(calib->corr_ofdm_mrc_x4);
2894 	cmd.energy_ofdm      = htole16(100);
2895 	cmd.energy_ofdm_th   = htole16(62);
2896 	/* CCK modulation */
2897 	cmd.corr_cck_x4      = htole16(calib->corr_cck_x4);
2898 	cmd.corr_cck_mrc_x4  = htole16(calib->corr_cck_mrc_x4);
2899 	cmd.energy_cck       = htole16(calib->energy_cck);
2900 	/* Barker modulation: use default values */
2901 	cmd.corr_barker      = htole16(190);
2902 	cmd.corr_barker_mrc  = htole16(390);
2903 
2904 	DPRINTFN(2, ("setting sensitivity %d/%d/%d/%d/%d/%d/%d\n",
2905 	    calib->corr_ofdm_x1, calib->corr_ofdm_mrc_x1, calib->corr_ofdm_x4,
2906 	    calib->corr_ofdm_mrc_x4, calib->corr_cck_x4,
2907 	    calib->corr_cck_mrc_x4, calib->energy_cck));
2908 	return iwn_cmd(sc, IWN_SENSITIVITY, &cmd, sizeof cmd, 1);
2909 }
2910 
2911 int
2912 iwn_auth(struct iwn_softc *sc)
2913 {
2914 	struct ieee80211com *ic = &sc->sc_ic;
2915 	struct ieee80211_node *ni = ic->ic_bss;
2916 	struct iwn_node_info node;
2917 	uint8_t rate;
2918 	int error;
2919 
2920 	/* update adapter's configuration */
2921 	IEEE80211_ADDR_COPY(sc->config.bssid, ni->ni_bssid);
2922 	sc->config.chan = ieee80211_chan2ieee(ic, ni->ni_chan);
2923 	sc->config.flags = htole32(IWN_CONFIG_TSF);
2924 	if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan)) {
2925 		sc->config.flags |= htole32(IWN_CONFIG_AUTO |
2926 		    IWN_CONFIG_24GHZ);
2927 	}
2928 	switch (ic->ic_curmode) {
2929 	case IEEE80211_MODE_11A:
2930 		sc->config.cck_mask  = 0;
2931 		sc->config.ofdm_mask = 0x15;
2932 		break;
2933 	case IEEE80211_MODE_11B:
2934 		sc->config.cck_mask  = 0x03;
2935 		sc->config.ofdm_mask = 0;
2936 		break;
2937 	default:	/* assume 802.11b/g */
2938 		sc->config.cck_mask  = 0x0f;
2939 		sc->config.ofdm_mask = 0x15;
2940 	}
2941 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
2942 		sc->config.flags |= htole32(IWN_CONFIG_SHSLOT);
2943 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
2944 		sc->config.flags |= htole32(IWN_CONFIG_SHPREAMBLE);
2945 	DPRINTF(("config chan %d flags %x cck %x ofdm %x\n", sc->config.chan,
2946 	    sc->config.flags, sc->config.cck_mask, sc->config.ofdm_mask));
2947 	error = iwn_cmd(sc, IWN_CMD_CONFIGURE, &sc->config,
2948 	    sizeof (struct iwn_config), 1);
2949 	if (error != 0) {
2950 		printf("%s: could not configure\n", sc->sc_dev.dv_xname);
2951 		return error;
2952 	}
2953 
2954 	/* configuration has changed, set Tx power accordingly */
2955 	if ((error = iwn_set_txpower(sc, ni->ni_chan, 1)) != 0) {
2956 		printf("%s: could not set Tx power\n", sc->sc_dev.dv_xname);
2957 		return error;
2958 	}
2959 
2960 	/*
2961 	 * Reconfiguring clears the adapter's nodes table so we must
2962 	 * add the broadcast node again.
2963 	 */
2964 	memset(&node, 0, sizeof node);
2965 	IEEE80211_ADDR_COPY(node.macaddr, etherbroadcastaddr);
2966 	node.id = IWN_ID_BROADCAST;
2967 	DPRINTF(("adding broadcast node\n"));
2968 	error = iwn_cmd(sc, IWN_CMD_ADD_NODE, &node, sizeof node, 1);
2969 	if (error != 0) {
2970 		printf("%s: could not add broadcast node\n",
2971 		    sc->sc_dev.dv_xname);
2972 		return error;
2973 	}
2974 	DPRINTF(("setting fixed rate for node %d\n", node.id));
2975 	rate = (ic->ic_curmode == IEEE80211_MODE_11A) ? 12 : 2;
2976 	if ((error = iwn_set_fixed_rate(sc, node.id, rate, 1)) != 0) {
2977 		printf("%s: could not setup MRR for broadcast node\n",
2978 		    sc->sc_dev.dv_xname, node.id);
2979 		return error;
2980 	}
2981 
2982 	return 0;
2983 }
2984 
2985 /*
2986  * Configure the adapter for associated state.
2987  */
2988 int
2989 iwn_run(struct iwn_softc *sc)
2990 {
2991 	struct ieee80211com *ic = &sc->sc_ic;
2992 	struct ieee80211_node *ni = ic->ic_bss;
2993 	struct iwn_node_info node;
2994 	int error;
2995 
2996 	if (ic->ic_opmode == IEEE80211_M_MONITOR) {
2997 		/* link LED blinks while monitoring */
2998 		iwn_set_led(sc, IWN_LED_LINK, 5, 5);
2999 		return 0;
3000 	}
3001 
3002 	iwn_enable_tsf(sc, ni);
3003 
3004 	/* update adapter's configuration */
3005 	sc->config.associd = htole16(ni->ni_associd & ~0xc000);
3006 	/* short preamble/slot time are negotiated when associating */
3007 	sc->config.flags &= ~htole32(IWN_CONFIG_SHPREAMBLE |
3008 	    IWN_CONFIG_SHSLOT);
3009 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
3010 		sc->config.flags |= htole32(IWN_CONFIG_SHSLOT);
3011 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
3012 		sc->config.flags |= htole32(IWN_CONFIG_SHPREAMBLE);
3013 	sc->config.filter |= htole32(IWN_FILTER_BSS);
3014 
3015 	DPRINTF(("config chan %d flags %x\n", sc->config.chan,
3016 	    sc->config.flags));
3017 	error = iwn_cmd(sc, IWN_CMD_CONFIGURE, &sc->config,
3018 	    sizeof (struct iwn_config), 1);
3019 	if (error != 0) {
3020 		printf("%s: could not update configuration\n",
3021 		    sc->sc_dev.dv_xname);
3022 		return error;
3023 	}
3024 
3025 	/* configuration has changed, set Tx power accordingly */
3026 	if ((error = iwn_set_txpower(sc, ni->ni_chan, 1)) != 0) {
3027 		printf("%s: could not set Tx power\n",
3028 		    sc->sc_dev.dv_xname);
3029 		return error;
3030 	}
3031 
3032 	/* add BSS node */
3033 	memset(&node, 0, sizeof node);
3034 	IEEE80211_ADDR_COPY(node.macaddr, ni->ni_macaddr);
3035 	node.id = IWN_ID_BSS;
3036 	node.htflags = htole32(3 << IWN_AMDPU_SIZE_FACTOR_SHIFT |
3037 	    5 << IWN_AMDPU_DENSITY_SHIFT);
3038 	DPRINTF(("adding BSS node\n"));
3039 	error = iwn_cmd(sc, IWN_CMD_ADD_NODE, &node, sizeof node, 1);
3040 	if (error != 0) {
3041 		printf("%s: could not add BSS node\n", sc->sc_dev.dv_xname);
3042 		return error;
3043 	}
3044 	DPRINTF(("setting MRR for node %d\n", node.id));
3045 	if ((error = iwn_setup_node_mrr(sc, ni, node.id)) != 0) {
3046 		printf("%s: could not setup MRR for node %d\n",
3047 		    sc->sc_dev.dv_xname, node.id);
3048 		return error;
3049 	}
3050 
3051 	if (ic->ic_opmode == IEEE80211_M_STA) {
3052 		/* fake a join to init the tx rate */
3053 		iwn_newassoc(ic, ni, 1);
3054 	}
3055 
3056 	if ((error = iwn_init_sensitivity(sc)) != 0) {
3057 		printf("%s: could not set sensitivity\n",
3058 		    sc->sc_dev.dv_xname);
3059 		return error;
3060 	}
3061 
3062 	/* start periodic calibration timer */
3063 	sc->calib.state = IWN_CALIB_STATE_ASSOC;
3064 	sc->calib_cnt = 0;
3065 	timeout_add(&sc->calib_to, hz / 2);
3066 
3067 	/* link LED always on while associated */
3068 	iwn_set_led(sc, IWN_LED_LINK, 0, 1);
3069 
3070 	return 0;
3071 }
3072 
3073 /*
3074  * Send a scan request to the firmware.  Since this command is huge, we map it
3075  * into a mbuf instead of using the pre-allocated set of commands.
3076  */
3077 int
3078 iwn_scan(struct iwn_softc *sc, uint16_t flags)
3079 {
3080 	struct ieee80211com *ic = &sc->sc_ic;
3081 	struct iwn_tx_ring *ring = &sc->txq[4];
3082 	struct iwn_tx_desc *desc;
3083 	struct iwn_tx_data *data;
3084 	struct iwn_tx_cmd *cmd;
3085 	struct iwn_cmd_data *tx;
3086 	struct iwn_scan_hdr *hdr;
3087 	struct iwn_scan_essid *essid;
3088 	struct iwn_scan_chan *chan;
3089 	struct ieee80211_frame *wh;
3090 	struct ieee80211_rateset *rs;
3091 	struct ieee80211_channel *c;
3092 	enum ieee80211_phymode mode;
3093 	uint8_t *frm;
3094 	int pktlen, error;
3095 
3096 	desc = &ring->desc[ring->cur];
3097 	data = &ring->data[ring->cur];
3098 
3099 	MGETHDR(data->m, M_DONTWAIT, MT_DATA);
3100 	if (data->m == NULL) {
3101 		printf("%s: could not allocate mbuf for scan command\n",
3102 		    sc->sc_dev.dv_xname);
3103 		return ENOMEM;
3104 	}
3105 	MCLGET(data->m, M_DONTWAIT);
3106 	if (!(data->m->m_flags & M_EXT)) {
3107 		m_freem(data->m);
3108 		data->m = NULL;
3109 		printf("%s: could not allocate mbuf for scan command\n",
3110 		    sc->sc_dev.dv_xname);
3111 		return ENOMEM;
3112 	}
3113 
3114 	cmd = mtod(data->m, struct iwn_tx_cmd *);
3115 	cmd->code = IWN_CMD_SCAN;
3116 	cmd->flags = 0;
3117 	cmd->qid = ring->qid;
3118 	cmd->idx = ring->cur;
3119 
3120 	hdr = (struct iwn_scan_hdr *)cmd->data;
3121 	memset(hdr, 0, sizeof (struct iwn_scan_hdr));
3122 	/*
3123 	 * Move to the next channel if no packets are received within 5 msecs
3124 	 * after sending the probe request (this helps to reduce the duration
3125 	 * of active scans).
3126 	 */
3127 	hdr->quiet = htole16(5);	/* timeout in milliseconds */
3128 	hdr->plcp_threshold = htole16(1);	/* min # of packets */
3129 
3130 	/* select Ant B and Ant C for scanning */
3131 	hdr->rxchain = htole16(0x3e1 | 7 << IWN_RXCHAIN_ANTMSK_SHIFT);
3132 
3133 	tx = (struct iwn_cmd_data *)(hdr + 1);
3134 	memset(tx, 0, sizeof (struct iwn_cmd_data));
3135 	tx->flags = htole32(IWN_TX_AUTO_SEQ | 0x200);	/* XXX */
3136 	tx->id = IWN_ID_BROADCAST;
3137 	tx->lifetime = htole32(IWN_LIFETIME_INFINITE);
3138 	tx->rflags = IWN_RFLAG_ANT_B;
3139 
3140 	if (flags & IEEE80211_CHAN_A) {
3141 		hdr->crc_threshold = htole16(1);
3142 		/* send probe requests at 6Mbps */
3143 		tx->rate = iwn_ridx_to_plcp[IWN_OFDM6];
3144 	} else {
3145 		hdr->flags = htole32(IWN_CONFIG_24GHZ | IWN_CONFIG_AUTO);
3146 		/* send probe requests at 1Mbps */
3147 		tx->rate = iwn_ridx_to_plcp[IWN_CCK1];
3148 		tx->rflags |= IWN_RFLAG_CCK;
3149 	}
3150 
3151 	essid = (struct iwn_scan_essid *)(tx + 1);
3152 	memset(essid, 0, 4 * sizeof (struct iwn_scan_essid));
3153 	essid[0].id  = IEEE80211_ELEMID_SSID;
3154 	essid[0].len = ic->ic_des_esslen;
3155 	memcpy(essid[0].data, ic->ic_des_essid, ic->ic_des_esslen);
3156 
3157 	/*
3158 	 * Build a probe request frame.  Most of the following code is a
3159 	 * copy & paste of what is done in net80211.
3160 	 */
3161 	wh = (struct ieee80211_frame *)&essid[4];
3162 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
3163 	    IEEE80211_FC0_SUBTYPE_PROBE_REQ;
3164 	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
3165 	IEEE80211_ADDR_COPY(wh->i_addr1, etherbroadcastaddr);
3166 	IEEE80211_ADDR_COPY(wh->i_addr2, ic->ic_myaddr);
3167 	IEEE80211_ADDR_COPY(wh->i_addr3, etherbroadcastaddr);
3168 	*(u_int16_t *)&wh->i_dur[0] = 0;	/* filled by h/w */
3169 	*(u_int16_t *)&wh->i_seq[0] = 0;	/* filled by h/w */
3170 
3171 	frm = (uint8_t *)(wh + 1);
3172 
3173 	/* add SSID IE */
3174 	frm = ieee80211_add_ssid(frm, ic->ic_des_essid, ic->ic_des_esslen);
3175 
3176 	mode = ieee80211_chan2mode(ic, ic->ic_ibss_chan);
3177 	rs = &ic->ic_sup_rates[mode];
3178 
3179 	/* add supported rates IE */
3180 	frm = ieee80211_add_rates(frm, rs);
3181 
3182 	/* add supported xrates IE */
3183 	if (rs->rs_nrates > IEEE80211_RATE_SIZE)
3184 		frm = ieee80211_add_xrates(frm, rs);
3185 
3186 	/* setup length of probe request */
3187 	tx->len = htole16(frm - (uint8_t *)wh);
3188 
3189 	chan = (struct iwn_scan_chan *)frm;
3190 	for (c  = &ic->ic_channels[1];
3191 	     c <= &ic->ic_channels[IEEE80211_CHAN_MAX]; c++) {
3192 		if ((c->ic_flags & flags) != flags)
3193 			continue;
3194 
3195 		chan->chan = ieee80211_chan2ieee(ic, c);
3196 		chan->flags = 0;
3197 		if (!(c->ic_flags & IEEE80211_CHAN_PASSIVE)) {
3198 			chan->flags |= IWN_CHAN_ACTIVE;
3199 			if (ic->ic_des_esslen != 0)
3200 				chan->flags |= IWN_CHAN_DIRECT;
3201 		}
3202 		chan->dsp_gain = 0x6e;
3203 		if (IEEE80211_IS_CHAN_5GHZ(c)) {
3204 			chan->rf_gain = 0x3b;
3205 			chan->active  = htole16(10);
3206 			chan->passive = htole16(110);
3207 		} else {
3208 			chan->rf_gain = 0x28;
3209 			chan->active  = htole16(20);
3210 			chan->passive = htole16(120);
3211 		}
3212 		hdr->nchan++;
3213 		chan++;
3214 
3215 		frm += sizeof (struct iwn_scan_chan);
3216 	}
3217 
3218 	hdr->len = htole16(frm - (uint8_t *)hdr);
3219 	pktlen = frm - (uint8_t *)cmd;
3220 
3221 	error = bus_dmamap_load(sc->sc_dmat, data->map, cmd, pktlen, NULL,
3222 	    BUS_DMA_NOWAIT);
3223 	if (error != 0) {
3224 		printf("%s: could not map scan command\n",
3225 		    sc->sc_dev.dv_xname);
3226 		m_freem(data->m);
3227 		data->m = NULL;
3228 		return error;
3229 	}
3230 
3231 	IWN_SET_DESC_NSEGS(desc, 1);
3232 	IWN_SET_DESC_SEG(desc, 0, data->map->dm_segs[0].ds_addr,
3233 	    data->map->dm_segs[0].ds_len);
3234 	sc->shared->len[ring->qid][ring->cur] = htole16(8);
3235 	if (ring->cur < IWN_TX_WINDOW) {
3236 		sc->shared->len[ring->qid][ring->cur + IWN_TX_RING_COUNT] =
3237 		    htole16(8);
3238 	}
3239 
3240 	/* kick cmd ring */
3241 	ring->cur = (ring->cur + 1) % IWN_TX_RING_COUNT;
3242 	IWN_WRITE(sc, IWN_TX_WIDX, ring->qid << 8 | ring->cur);
3243 
3244 	return 0;	/* will be notified async. of failure/success */
3245 }
3246 
3247 int
3248 iwn_config(struct iwn_softc *sc)
3249 {
3250 	struct ieee80211com *ic = &sc->sc_ic;
3251 	struct ifnet *ifp = &ic->ic_if;
3252 	struct iwn_power power;
3253 	struct iwn_bluetooth bluetooth;
3254 	struct iwn_node_info node;
3255 	uint8_t rate;
3256 	int error;
3257 
3258 	/* set power mode */
3259 	memset(&power, 0, sizeof power);
3260 	power.flags = htole16(IWN_POWER_CAM | 0x8);
3261 	DPRINTF(("setting power mode\n"));
3262 	error = iwn_cmd(sc, IWN_CMD_SET_POWER_MODE, &power, sizeof power, 0);
3263 	if (error != 0) {
3264 		printf("%s: could not set power mode\n", sc->sc_dev.dv_xname);
3265 		return error;
3266 	}
3267 
3268 	/* configure bluetooth coexistence */
3269 	memset(&bluetooth, 0, sizeof bluetooth);
3270 	bluetooth.flags = 3;
3271 	bluetooth.lead = 0xaa;
3272 	bluetooth.kill = 1;
3273 	DPRINTF(("configuring bluetooth coexistence\n"));
3274 	error = iwn_cmd(sc, IWN_CMD_BLUETOOTH, &bluetooth, sizeof bluetooth,
3275 	    0);
3276 	if (error != 0) {
3277 		printf("%s: could not configure bluetooth coexistence\n",
3278 		    sc->sc_dev.dv_xname);
3279 		return error;
3280 	}
3281 
3282 	/* configure adapter */
3283 	memset(&sc->config, 0, sizeof (struct iwn_config));
3284 	IEEE80211_ADDR_COPY(ic->ic_myaddr, LLADDR(ifp->if_sadl));
3285 	IEEE80211_ADDR_COPY(sc->config.myaddr, ic->ic_myaddr);
3286 	IEEE80211_ADDR_COPY(sc->config.wlap, ic->ic_myaddr);
3287 	/* set default channel */
3288 	sc->config.chan = ieee80211_chan2ieee(ic, ic->ic_ibss_chan);
3289 	sc->config.flags = htole32(IWN_CONFIG_TSF);
3290 	if (IEEE80211_IS_CHAN_2GHZ(ic->ic_ibss_chan)) {
3291 		sc->config.flags |= htole32(IWN_CONFIG_AUTO |
3292 		    IWN_CONFIG_24GHZ);
3293 	}
3294 	sc->config.filter = 0;
3295 	switch (ic->ic_opmode) {
3296 	case IEEE80211_M_STA:
3297 		sc->config.mode = IWN_MODE_STA;
3298 		sc->config.filter |= htole32(IWN_FILTER_MULTICAST);
3299 		break;
3300 #ifndef IEEE80211_STA_ONLY
3301 #ifdef notyet
3302 	case IEEE80211_M_IBSS:
3303 	case IEEE80211_M_AHDEMO:
3304 		sc->config.mode = IWN_MODE_IBSS;
3305 		break;
3306 	case IEEE80211_M_HOSTAP:
3307 		sc->config.mode = IWN_MODE_HOSTAP;
3308 		break;
3309 #endif
3310 #endif
3311 	case IEEE80211_M_MONITOR:
3312 		sc->config.mode = IWN_MODE_MONITOR;
3313 		sc->config.filter |= htole32(IWN_FILTER_MULTICAST |
3314 		    IWN_FILTER_CTL | IWN_FILTER_PROMISC);
3315 		break;
3316 	default:
3317 		/* should not get there */
3318 		break;
3319 	}
3320 	sc->config.cck_mask  = 0x0f;	/* not yet negotiated */
3321 	sc->config.ofdm_mask = 0xff;	/* not yet negotiated */
3322 	sc->config.ht_single_mask = 0xff;
3323 	sc->config.ht_dual_mask = 0xff;
3324 	sc->config.rxchain = htole16(0x2800 | 7 << IWN_RXCHAIN_ANTMSK_SHIFT);
3325 	DPRINTF(("setting configuration\n"));
3326 	error = iwn_cmd(sc, IWN_CMD_CONFIGURE, &sc->config,
3327 	    sizeof (struct iwn_config), 0);
3328 	if (error != 0) {
3329 		printf("%s: configure command failed\n", sc->sc_dev.dv_xname);
3330 		return error;
3331 	}
3332 
3333 	/* configuration has changed, set Tx power accordingly */
3334 	if ((error = iwn_set_txpower(sc, ic->ic_ibss_chan, 0)) != 0) {
3335 		printf("%s: could not set Tx power\n", sc->sc_dev.dv_xname);
3336 		return error;
3337 	}
3338 
3339 	/* add broadcast node */
3340 	memset(&node, 0, sizeof node);
3341 	IEEE80211_ADDR_COPY(node.macaddr, etherbroadcastaddr);
3342 	node.id = IWN_ID_BROADCAST;
3343 	DPRINTF(("adding broadcast node\n"));
3344 	error = iwn_cmd(sc, IWN_CMD_ADD_NODE, &node, sizeof node, 0);
3345 	if (error != 0) {
3346 		printf("%s: could not add broadcast node\n",
3347 		    sc->sc_dev.dv_xname);
3348 		return error;
3349 	}
3350 	DPRINTF(("setting fixed rate for node %d\n", node.id));
3351 	rate = (ic->ic_curmode == IEEE80211_MODE_11A) ? 12 : 2;
3352 	if ((error = iwn_set_fixed_rate(sc, node.id, rate, 0)) != 0) {
3353 		printf("%s: could not setup MRR for node %d\n",
3354 		    sc->sc_dev.dv_xname, node.id);
3355 		return error;
3356 	}
3357 
3358 	if ((error = iwn_set_critical_temp(sc)) != 0) {
3359 		printf("%s: could not set critical temperature\n",
3360 		    sc->sc_dev.dv_xname);
3361 		return error;
3362 	}
3363 
3364 	return 0;
3365 }
3366 
3367 /*
3368  * Do post-alive initialization of the NIC (after firmware upload).
3369  */
3370 void
3371 iwn_post_alive(struct iwn_softc *sc)
3372 {
3373 	uint32_t base;
3374 	uint16_t offset;
3375 	int qid;
3376 
3377 	iwn_mem_lock(sc);
3378 
3379 	/* clear SRAM */
3380 	base = iwn_mem_read(sc, IWN_SRAM_BASE);
3381 	for (offset = 0x380; offset < 0x520; offset += 4) {
3382 		IWN_WRITE(sc, IWN_MEM_WADDR, base + offset);
3383 		IWN_WRITE(sc, IWN_MEM_WDATA, 0);
3384 	}
3385 
3386 	/* shared area is aligned on a 1K boundary */
3387 	iwn_mem_write(sc, IWN_SRAM_BASE, sc->shared_dma.paddr >> 10);
3388 	iwn_mem_write(sc, IWN_SELECT_QCHAIN, 0);
3389 
3390 	for (qid = 0; qid < IWN_NTXQUEUES; qid++) {
3391 		iwn_mem_write(sc, IWN_QUEUE_RIDX(qid), 0);
3392 		IWN_WRITE(sc, IWN_TX_WIDX, qid << 8 | 0);
3393 
3394 		/* set sched. window size */
3395 		IWN_WRITE(sc, IWN_MEM_WADDR, base + IWN_QUEUE_OFFSET(qid));
3396 		IWN_WRITE(sc, IWN_MEM_WDATA, 64);
3397 		/* set sched. frame limit */
3398 		IWN_WRITE(sc, IWN_MEM_WADDR, base + IWN_QUEUE_OFFSET(qid) + 4);
3399 		IWN_WRITE(sc, IWN_MEM_WDATA, 64 << 16);
3400 	}
3401 
3402 	/* enable interrupts for all 16 queues */
3403 	iwn_mem_write(sc, IWN_QUEUE_INTR_MASK, 0xffff);
3404 
3405 	/* identify active Tx rings (0-7) */
3406 	iwn_mem_write(sc, IWN_TX_ACTIVE, 0xff);
3407 
3408 	/* mark Tx rings (4 EDCA + cmd + 2 HCCA) as active */
3409 	for (qid = 0; qid < 7; qid++) {
3410 		iwn_mem_write(sc, IWN_TXQ_STATUS(qid),
3411 		    IWN_TXQ_STATUS_ACTIVE | qid << 1);
3412 	}
3413 
3414 	iwn_mem_unlock(sc);
3415 }
3416 
3417 void
3418 iwn_stop_master(struct iwn_softc *sc)
3419 {
3420 	uint32_t tmp;
3421 	int ntries;
3422 
3423 	tmp = IWN_READ(sc, IWN_RESET);
3424 	IWN_WRITE(sc, IWN_RESET, tmp | IWN_STOP_MASTER);
3425 
3426 	tmp = IWN_READ(sc, IWN_GPIO_CTL);
3427 	if ((tmp & IWN_GPIO_PWR_STATUS) == IWN_GPIO_PWR_SLEEP)
3428 		return;	/* already asleep */
3429 
3430 	for (ntries = 0; ntries < 100; ntries++) {
3431 		if (IWN_READ(sc, IWN_RESET) & IWN_MASTER_DISABLED)
3432 			break;
3433 		DELAY(10);
3434 	}
3435 	if (ntries == 100) {
3436 		printf("%s: timeout waiting for master\n",
3437 		    sc->sc_dev.dv_xname);
3438 	}
3439 }
3440 
3441 int
3442 iwn_reset(struct iwn_softc *sc)
3443 {
3444 	uint32_t tmp;
3445 	int ntries;
3446 
3447 	/* clear any pending interrupts */
3448 	IWN_WRITE(sc, IWN_INTR, 0xffffffff);
3449 
3450 	tmp = IWN_READ(sc, IWN_CHICKEN);
3451 	IWN_WRITE(sc, IWN_CHICKEN, tmp | IWN_CHICKEN_DISLOS);
3452 
3453 	tmp = IWN_READ(sc, IWN_GPIO_CTL);
3454 	IWN_WRITE(sc, IWN_GPIO_CTL, tmp | IWN_GPIO_INIT);
3455 
3456 	/* wait for clock stabilization */
3457 	for (ntries = 0; ntries < 25000; ntries++) {
3458 		if (IWN_READ(sc, IWN_GPIO_CTL) & IWN_GPIO_CLOCK)
3459 			break;
3460 		DELAY(100);
3461 	}
3462 	if (ntries == 25000) {
3463 		printf("%s: timeout waiting for clock stabilization\n",
3464 		    sc->sc_dev.dv_xname);
3465 		return ETIMEDOUT;
3466 	}
3467 	return 0;
3468 }
3469 
3470 void
3471 iwn_hw_config(struct iwn_softc *sc)
3472 {
3473 	uint32_t tmp, hw;
3474 
3475 	/* enable interrupts mitigation */
3476 	IWN_WRITE(sc, IWN_INTR_MIT, 512 / 32);
3477 
3478 	/* voodoo from the reference driver */
3479 	tmp = pci_conf_read(sc->sc_pct, sc->sc_pcitag, PCI_CLASS_REG);
3480 	tmp = PCI_REVISION(tmp);
3481 	if ((tmp & 0x80) && (tmp & 0x7f) < 8) {
3482 		/* enable "no snoop" field */
3483 		tmp = pci_conf_read(sc->sc_pct, sc->sc_pcitag, 0xe8);
3484 		tmp &= ~IWN_DIS_NOSNOOP;
3485 		pci_conf_write(sc->sc_pct, sc->sc_pcitag, 0xe8, tmp);
3486 	}
3487 
3488 	/* disable L1 entry to work around a hardware bug */
3489 	tmp = pci_conf_read(sc->sc_pct, sc->sc_pcitag, 0xf0);
3490 	tmp &= ~IWN_ENA_L1;
3491 	pci_conf_write(sc->sc_pct, sc->sc_pcitag, 0xf0, tmp);
3492 
3493 	hw = IWN_READ(sc, IWN_HWCONFIG);
3494 	IWN_WRITE(sc, IWN_HWCONFIG, hw | 0x310);
3495 
3496 	iwn_mem_lock(sc);
3497 	tmp = iwn_mem_read(sc, IWN_MEM_POWER);
3498 	iwn_mem_write(sc, IWN_MEM_POWER, tmp | IWN_POWER_RESET);
3499 	DELAY(5);
3500 	tmp = iwn_mem_read(sc, IWN_MEM_POWER);
3501 	iwn_mem_write(sc, IWN_MEM_POWER, tmp & ~IWN_POWER_RESET);
3502 	iwn_mem_unlock(sc);
3503 }
3504 
3505 int
3506 iwn_init(struct ifnet *ifp)
3507 {
3508 	struct iwn_softc *sc = ifp->if_softc;
3509 	struct ieee80211com *ic = &sc->sc_ic;
3510 	uint32_t tmp;
3511 	int error, qid;
3512 
3513 	if ((error = iwn_reset(sc)) != 0) {
3514 		printf("%s: could not reset adapter\n", sc->sc_dev.dv_xname);
3515 		goto fail1;
3516 	}
3517 
3518 	iwn_mem_lock(sc);
3519 	iwn_mem_read(sc, IWN_CLOCK_CTL);
3520 	iwn_mem_write(sc, IWN_CLOCK_CTL, 0xa00);
3521 	iwn_mem_read(sc, IWN_CLOCK_CTL);
3522 	iwn_mem_unlock(sc);
3523 
3524 	DELAY(20);
3525 
3526 	iwn_mem_lock(sc);
3527 	tmp = iwn_mem_read(sc, IWN_MEM_PCIDEV);
3528 	iwn_mem_write(sc, IWN_MEM_PCIDEV, tmp | 0x800);
3529 	iwn_mem_unlock(sc);
3530 
3531 	iwn_mem_lock(sc);
3532 	tmp = iwn_mem_read(sc, IWN_MEM_POWER);
3533 	iwn_mem_write(sc, IWN_MEM_POWER, tmp & ~0x03000000);
3534 	iwn_mem_unlock(sc);
3535 
3536 	iwn_hw_config(sc);
3537 
3538 	/* init Rx ring */
3539 	iwn_mem_lock(sc);
3540 	IWN_WRITE(sc, IWN_RX_CONFIG, 0);
3541 	IWN_WRITE(sc, IWN_RX_WIDX, 0);
3542 	/* Rx ring is aligned on a 256-byte boundary */
3543 	IWN_WRITE(sc, IWN_RX_BASE, sc->rxq.desc_dma.paddr >> 8);
3544 	/* shared area is aligned on a 16-byte boundary */
3545 	IWN_WRITE(sc, IWN_RW_WIDX_PTR, (sc->shared_dma.paddr +
3546 	    offsetof(struct iwn_shared, closed_count)) >> 4);
3547 	IWN_WRITE(sc, IWN_RX_CONFIG, 0x80601000);
3548 	iwn_mem_unlock(sc);
3549 
3550 	IWN_WRITE(sc, IWN_RX_WIDX, (IWN_RX_RING_COUNT - 1) & ~7);
3551 
3552 	iwn_mem_lock(sc);
3553 	iwn_mem_write(sc, IWN_TX_ACTIVE, 0);
3554 
3555 	/* set physical address of "keep warm" page */
3556 	IWN_WRITE(sc, IWN_KW_BASE, sc->kw_dma.paddr >> 4);
3557 
3558 	/* init Tx rings */
3559 	for (qid = 0; qid < IWN_NTXQUEUES; qid++) {
3560 		struct iwn_tx_ring *txq = &sc->txq[qid];
3561 		IWN_WRITE(sc, IWN_TX_BASE(qid), txq->desc_dma.paddr >> 8);
3562 		IWN_WRITE(sc, IWN_TX_CONFIG(qid), 0x80000008);
3563 	}
3564 	iwn_mem_unlock(sc);
3565 
3566 	/* clear "radio off" and "disable command" bits (reversed logic) */
3567 	IWN_WRITE(sc, IWN_UCODE_CLR, IWN_RADIO_OFF);
3568 	IWN_WRITE(sc, IWN_UCODE_CLR, IWN_DISABLE_CMD);
3569 
3570 	/* clear any pending interrupts */
3571 	IWN_WRITE(sc, IWN_INTR, 0xffffffff);
3572 	/* enable interrupts */
3573 	IWN_WRITE(sc, IWN_MASK, IWN_INTR_MASK);
3574 
3575 	/* not sure why/if this is necessary... */
3576 	IWN_WRITE(sc, IWN_UCODE_CLR, IWN_RADIO_OFF);
3577 	IWN_WRITE(sc, IWN_UCODE_CLR, IWN_RADIO_OFF);
3578 
3579 	/* check that the radio is not disabled by RF switch */
3580 	if (!(IWN_READ(sc, IWN_GPIO_CTL) & IWN_GPIO_RF_ENABLED)) {
3581 		printf("%s: radio is disabled by hardware switch\n",
3582 		    sc->sc_dev.dv_xname);
3583 		error = EPERM;	/* XXX ;-) */
3584 		goto fail1;
3585 	}
3586 
3587 	if ((error = iwn_load_firmware(sc)) != 0) {
3588 		printf("%s: could not load firmware\n", sc->sc_dev.dv_xname);
3589 		goto fail1;
3590 	}
3591 
3592 	/* firmware has notified us that it is alive.. */
3593 	iwn_post_alive(sc);	/* ..do post alive initialization */
3594 
3595 	sc->rawtemp = sc->ucode_info.temp[3].chan20MHz;
3596 	sc->temp = iwn_get_temperature(sc);
3597 	DPRINTF(("temperature=%d\n", sc->temp));
3598 	sc->sensor.value = IWN_CTOMUK(sc->temp);
3599 	sc->sensor.flags &= ~SENSOR_FINVALID;
3600 
3601 	if ((error = iwn_config(sc)) != 0) {
3602 		printf("%s: could not configure device\n",
3603 		    sc->sc_dev.dv_xname);
3604 		goto fail1;
3605 	}
3606 
3607 	ifp->if_flags &= ~IFF_OACTIVE;
3608 	ifp->if_flags |= IFF_RUNNING;
3609 
3610 	if (ic->ic_opmode != IEEE80211_M_MONITOR)
3611 		ieee80211_begin_scan(ifp);
3612 	else
3613 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
3614 
3615 	return 0;
3616 
3617 fail1:	iwn_stop(ifp, 1);
3618 	return error;
3619 }
3620 
3621 void
3622 iwn_stop(struct ifnet *ifp, int disable)
3623 {
3624 	struct iwn_softc *sc = ifp->if_softc;
3625 	struct ieee80211com *ic = &sc->sc_ic;
3626 	uint32_t tmp;
3627 	int i;
3628 
3629 	ifp->if_timer = sc->sc_tx_timer = 0;
3630 	ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
3631 
3632 	/* in case we were scanning, release the scan "lock" */
3633 	ic->ic_scan_lock = IEEE80211_SCAN_UNLOCKED;
3634 
3635 	ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
3636 
3637 	IWN_WRITE(sc, IWN_RESET, IWN_NEVO_RESET);
3638 
3639 	/* disable interrupts */
3640 	IWN_WRITE(sc, IWN_MASK, 0);
3641 	IWN_WRITE(sc, IWN_INTR, 0xffffffff);
3642 	IWN_WRITE(sc, IWN_INTR_STATUS, 0xffffffff);
3643 
3644 	/* make sure we no longer hold the memory lock */
3645 	iwn_mem_unlock(sc);
3646 
3647 	/* reset all Tx rings */
3648 	for (i = 0; i < IWN_NTXQUEUES; i++)
3649 		iwn_reset_tx_ring(sc, &sc->txq[i]);
3650 
3651 	/* reset Rx ring */
3652 	iwn_reset_rx_ring(sc, &sc->rxq);
3653 
3654 	/* temperature is no longer valid */
3655 	sc->sensor.value = 0;
3656 	sc->sensor.flags |= SENSOR_FINVALID;
3657 
3658 	iwn_mem_lock(sc);
3659 	iwn_mem_write(sc, IWN_MEM_CLOCK2, 0x200);
3660 	iwn_mem_unlock(sc);
3661 
3662 	DELAY(5);
3663 
3664 	iwn_stop_master(sc);
3665 	tmp = IWN_READ(sc, IWN_RESET);
3666 	IWN_WRITE(sc, IWN_RESET, tmp | IWN_SW_RESET);
3667 }
3668 
3669 struct cfdriver iwn_cd = {
3670 	NULL, "iwn", DV_IFNET
3671 };
3672