xref: /freebsd/sys/dev/iwm/if_iwm.c (revision fcf596178b5f2be36424ecbc1b6a3224b29c91d2)
1 /*	$OpenBSD: if_iwm.c,v 1.42 2015/05/30 02:49:23 deraadt Exp $	*/
2 
3 /*
4  * Copyright (c) 2014 genua mbh <info@genua.de>
5  * Copyright (c) 2014 Fixup Software Ltd.
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  * Based on BSD-licensed source modules in the Linux iwlwifi driver,
22  * which were used as the reference documentation for this implementation.
23  *
24  * Driver version we are currently based off of is
25  * Linux 3.14.3 (tag id a2df521e42b1d9a23f620ac79dbfe8655a8391dd)
26  *
27  ***********************************************************************
28  *
29  * This file is provided under a dual BSD/GPLv2 license.  When using or
30  * redistributing this file, you may do so under either license.
31  *
32  * GPL LICENSE SUMMARY
33  *
34  * Copyright(c) 2007 - 2013 Intel Corporation. All rights reserved.
35  *
36  * This program is free software; you can redistribute it and/or modify
37  * it under the terms of version 2 of the GNU General Public License as
38  * published by the Free Software Foundation.
39  *
40  * This program is distributed in the hope that it will be useful, but
41  * WITHOUT ANY WARRANTY; without even the implied warranty of
42  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
43  * General Public License for more details.
44  *
45  * You should have received a copy of the GNU General Public License
46  * along with this program; if not, write to the Free Software
47  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110,
48  * USA
49  *
50  * The full GNU General Public License is included in this distribution
51  * in the file called COPYING.
52  *
53  * Contact Information:
54  *  Intel Linux Wireless <ilw@linux.intel.com>
55  * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
56  *
57  *
58  * BSD LICENSE
59  *
60  * Copyright(c) 2005 - 2013 Intel Corporation. All rights reserved.
61  * All rights reserved.
62  *
63  * Redistribution and use in source and binary forms, with or without
64  * modification, are permitted provided that the following conditions
65  * are met:
66  *
67  *  * Redistributions of source code must retain the above copyright
68  *    notice, this list of conditions and the following disclaimer.
69  *  * Redistributions in binary form must reproduce the above copyright
70  *    notice, this list of conditions and the following disclaimer in
71  *    the documentation and/or other materials provided with the
72  *    distribution.
73  *  * Neither the name Intel Corporation nor the names of its
74  *    contributors may be used to endorse or promote products derived
75  *    from this software without specific prior written permission.
76  *
77  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
78  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
79  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
80  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
81  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
82  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
83  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
84  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
85  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
86  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
87  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
88  */
89 
90 /*-
91  * Copyright (c) 2007-2010 Damien Bergamini <damien.bergamini@free.fr>
92  *
93  * Permission to use, copy, modify, and distribute this software for any
94  * purpose with or without fee is hereby granted, provided that the above
95  * copyright notice and this permission notice appear in all copies.
96  *
97  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
98  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
99  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
100  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
101  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
102  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
103  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
104  */
105 #include <sys/cdefs.h>
106 __FBSDID("$FreeBSD$");
107 
108 #include "opt_wlan.h"
109 
110 #include <sys/param.h>
111 #include <sys/bus.h>
112 #include <sys/conf.h>
113 #include <sys/endian.h>
114 #include <sys/firmware.h>
115 #include <sys/kernel.h>
116 #include <sys/malloc.h>
117 #include <sys/mbuf.h>
118 #include <sys/mutex.h>
119 #include <sys/module.h>
120 #include <sys/proc.h>
121 #include <sys/rman.h>
122 #include <sys/socket.h>
123 #include <sys/sockio.h>
124 #include <sys/sysctl.h>
125 #include <sys/linker.h>
126 
127 #include <machine/bus.h>
128 #include <machine/endian.h>
129 #include <machine/resource.h>
130 
131 #include <dev/pci/pcivar.h>
132 #include <dev/pci/pcireg.h>
133 
134 #include <net/bpf.h>
135 
136 #include <net/if.h>
137 #include <net/if_var.h>
138 #include <net/if_arp.h>
139 #include <net/if_dl.h>
140 #include <net/if_media.h>
141 #include <net/if_types.h>
142 
143 #include <netinet/in.h>
144 #include <netinet/in_systm.h>
145 #include <netinet/if_ether.h>
146 #include <netinet/ip.h>
147 
148 #include <net80211/ieee80211_var.h>
149 #include <net80211/ieee80211_regdomain.h>
150 #include <net80211/ieee80211_ratectl.h>
151 #include <net80211/ieee80211_radiotap.h>
152 
153 #include <dev/iwm/if_iwmreg.h>
154 #include <dev/iwm/if_iwmvar.h>
155 #include <dev/iwm/if_iwm_debug.h>
156 #include <dev/iwm/if_iwm_notif_wait.h>
157 #include <dev/iwm/if_iwm_util.h>
158 #include <dev/iwm/if_iwm_binding.h>
159 #include <dev/iwm/if_iwm_phy_db.h>
160 #include <dev/iwm/if_iwm_mac_ctxt.h>
161 #include <dev/iwm/if_iwm_phy_ctxt.h>
162 #include <dev/iwm/if_iwm_time_event.h>
163 #include <dev/iwm/if_iwm_power.h>
164 #include <dev/iwm/if_iwm_scan.h>
165 
166 #include <dev/iwm/if_iwm_pcie_trans.h>
167 #include <dev/iwm/if_iwm_led.h>
168 
169 #define IWM_NVM_HW_SECTION_NUM_FAMILY_7000	0
170 #define IWM_NVM_HW_SECTION_NUM_FAMILY_8000	10
171 
172 /* lower blocks contain EEPROM image and calibration data */
173 #define IWM_OTP_LOW_IMAGE_SIZE_FAMILY_7000	(16 * 512 * sizeof(uint16_t)) /* 16 KB */
174 #define IWM_OTP_LOW_IMAGE_SIZE_FAMILY_8000	(32 * 512 * sizeof(uint16_t)) /* 32 KB */
175 
176 #define IWM7260_FW	"iwm7260fw"
177 #define IWM3160_FW	"iwm3160fw"
178 #define IWM7265_FW	"iwm7265fw"
179 #define IWM7265D_FW	"iwm7265Dfw"
180 #define IWM8000_FW	"iwm8000Cfw"
181 
182 #define IWM_DEVICE_7000_COMMON						\
183 	.device_family = IWM_DEVICE_FAMILY_7000,			\
184 	.eeprom_size = IWM_OTP_LOW_IMAGE_SIZE_FAMILY_7000,		\
185 	.nvm_hw_section_num = IWM_NVM_HW_SECTION_NUM_FAMILY_7000
186 
187 const struct iwm_cfg iwm7260_cfg = {
188 	.fw_name = IWM7260_FW,
189 	IWM_DEVICE_7000_COMMON,
190 	.host_interrupt_operation_mode = 1,
191 };
192 
193 const struct iwm_cfg iwm3160_cfg = {
194 	.fw_name = IWM3160_FW,
195 	IWM_DEVICE_7000_COMMON,
196 	.host_interrupt_operation_mode = 1,
197 };
198 
199 const struct iwm_cfg iwm3165_cfg = {
200 	/* XXX IWM7265D_FW doesn't seem to work properly yet */
201 	.fw_name = IWM7265_FW,
202 	IWM_DEVICE_7000_COMMON,
203 	.host_interrupt_operation_mode = 0,
204 };
205 
206 const struct iwm_cfg iwm7265_cfg = {
207 	.fw_name = IWM7265_FW,
208 	IWM_DEVICE_7000_COMMON,
209 	.host_interrupt_operation_mode = 0,
210 };
211 
212 const struct iwm_cfg iwm7265d_cfg = {
213 	/* XXX IWM7265D_FW doesn't seem to work properly yet */
214 	.fw_name = IWM7265_FW,
215 	IWM_DEVICE_7000_COMMON,
216 	.host_interrupt_operation_mode = 0,
217 };
218 
219 #define IWM_DEVICE_8000_COMMON						\
220 	.device_family = IWM_DEVICE_FAMILY_8000,			\
221 	.eeprom_size = IWM_OTP_LOW_IMAGE_SIZE_FAMILY_8000,		\
222 	.nvm_hw_section_num = IWM_NVM_HW_SECTION_NUM_FAMILY_8000
223 
224 const struct iwm_cfg iwm8260_cfg = {
225 	.fw_name = IWM8000_FW,
226 	IWM_DEVICE_8000_COMMON,
227 	.host_interrupt_operation_mode = 0,
228 };
229 
230 const uint8_t iwm_nvm_channels[] = {
231 	/* 2.4 GHz */
232 	1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
233 	/* 5 GHz */
234 	36, 40, 44, 48, 52, 56, 60, 64,
235 	100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140, 144,
236 	149, 153, 157, 161, 165
237 };
238 _Static_assert(nitems(iwm_nvm_channels) <= IWM_NUM_CHANNELS,
239     "IWM_NUM_CHANNELS is too small");
240 
241 const uint8_t iwm_nvm_channels_8000[] = {
242 	/* 2.4 GHz */
243 	1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
244 	/* 5 GHz */
245 	36, 40, 44, 48, 52, 56, 60, 64, 68, 72, 76, 80, 84, 88, 92,
246 	96, 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140, 144,
247 	149, 153, 157, 161, 165, 169, 173, 177, 181
248 };
249 _Static_assert(nitems(iwm_nvm_channels_8000) <= IWM_NUM_CHANNELS_8000,
250     "IWM_NUM_CHANNELS_8000 is too small");
251 
252 #define IWM_NUM_2GHZ_CHANNELS	14
253 #define IWM_N_HW_ADDR_MASK	0xF
254 
255 /*
256  * XXX For now, there's simply a fixed set of rate table entries
257  * that are populated.
258  */
259 const struct iwm_rate {
260 	uint8_t rate;
261 	uint8_t plcp;
262 } iwm_rates[] = {
263 	{   2,	IWM_RATE_1M_PLCP  },
264 	{   4,	IWM_RATE_2M_PLCP  },
265 	{  11,	IWM_RATE_5M_PLCP  },
266 	{  22,	IWM_RATE_11M_PLCP },
267 	{  12,	IWM_RATE_6M_PLCP  },
268 	{  18,	IWM_RATE_9M_PLCP  },
269 	{  24,	IWM_RATE_12M_PLCP },
270 	{  36,	IWM_RATE_18M_PLCP },
271 	{  48,	IWM_RATE_24M_PLCP },
272 	{  72,	IWM_RATE_36M_PLCP },
273 	{  96,	IWM_RATE_48M_PLCP },
274 	{ 108,	IWM_RATE_54M_PLCP },
275 };
276 #define IWM_RIDX_CCK	0
277 #define IWM_RIDX_OFDM	4
278 #define IWM_RIDX_MAX	(nitems(iwm_rates)-1)
279 #define IWM_RIDX_IS_CCK(_i_) ((_i_) < IWM_RIDX_OFDM)
280 #define IWM_RIDX_IS_OFDM(_i_) ((_i_) >= IWM_RIDX_OFDM)
281 
282 struct iwm_nvm_section {
283 	uint16_t length;
284 	uint8_t *data;
285 };
286 
287 #define IWM_MVM_UCODE_CALIB_TIMEOUT	(2*hz)
288 
289 static int	iwm_store_cscheme(struct iwm_softc *, const uint8_t *, size_t);
290 static int	iwm_firmware_store_section(struct iwm_softc *,
291                                            enum iwm_ucode_type,
292                                            const uint8_t *, size_t);
293 static int	iwm_set_default_calib(struct iwm_softc *, const void *);
294 static void	iwm_fw_info_free(struct iwm_fw_info *);
295 static int	iwm_read_firmware(struct iwm_softc *, enum iwm_ucode_type);
296 static void	iwm_dma_map_addr(void *, bus_dma_segment_t *, int, int);
297 static int	iwm_dma_contig_alloc(bus_dma_tag_t, struct iwm_dma_info *,
298                                      bus_size_t, bus_size_t);
299 static void	iwm_dma_contig_free(struct iwm_dma_info *);
300 static int	iwm_alloc_fwmem(struct iwm_softc *);
301 static int	iwm_alloc_sched(struct iwm_softc *);
302 static int	iwm_alloc_kw(struct iwm_softc *);
303 static int	iwm_alloc_ict(struct iwm_softc *);
304 static int	iwm_alloc_rx_ring(struct iwm_softc *, struct iwm_rx_ring *);
305 static void	iwm_disable_rx_dma(struct iwm_softc *);
306 static void	iwm_reset_rx_ring(struct iwm_softc *, struct iwm_rx_ring *);
307 static void	iwm_free_rx_ring(struct iwm_softc *, struct iwm_rx_ring *);
308 static int	iwm_alloc_tx_ring(struct iwm_softc *, struct iwm_tx_ring *,
309                                   int);
310 static void	iwm_reset_tx_ring(struct iwm_softc *, struct iwm_tx_ring *);
311 static void	iwm_free_tx_ring(struct iwm_softc *, struct iwm_tx_ring *);
312 static void	iwm_enable_interrupts(struct iwm_softc *);
313 static void	iwm_restore_interrupts(struct iwm_softc *);
314 static void	iwm_disable_interrupts(struct iwm_softc *);
315 static void	iwm_ict_reset(struct iwm_softc *);
316 static int	iwm_allow_mcast(struct ieee80211vap *, struct iwm_softc *);
317 static void	iwm_stop_device(struct iwm_softc *);
318 static void	iwm_mvm_nic_config(struct iwm_softc *);
319 static int	iwm_nic_rx_init(struct iwm_softc *);
320 static int	iwm_nic_tx_init(struct iwm_softc *);
321 static int	iwm_nic_init(struct iwm_softc *);
322 static int	iwm_enable_txq(struct iwm_softc *, int, int, int);
323 static int	iwm_post_alive(struct iwm_softc *);
324 static int	iwm_nvm_read_chunk(struct iwm_softc *, uint16_t, uint16_t,
325                                    uint16_t, uint8_t *, uint16_t *);
326 static int	iwm_nvm_read_section(struct iwm_softc *, uint16_t, uint8_t *,
327 				     uint16_t *, uint32_t);
328 static uint32_t	iwm_eeprom_channel_flags(uint16_t);
329 static void	iwm_add_channel_band(struct iwm_softc *,
330 		    struct ieee80211_channel[], int, int *, int, size_t,
331 		    const uint8_t[]);
332 static void	iwm_init_channel_map(struct ieee80211com *, int, int *,
333 		    struct ieee80211_channel[]);
334 static struct iwm_nvm_data *
335 	iwm_parse_nvm_data(struct iwm_softc *, const uint16_t *,
336 			   const uint16_t *, const uint16_t *,
337 			   const uint16_t *, const uint16_t *,
338 			   const uint16_t *);
339 static void	iwm_free_nvm_data(struct iwm_nvm_data *);
340 static void	iwm_set_hw_address_family_8000(struct iwm_softc *,
341 					       struct iwm_nvm_data *,
342 					       const uint16_t *,
343 					       const uint16_t *);
344 static int	iwm_get_sku(const struct iwm_softc *, const uint16_t *,
345 			    const uint16_t *);
346 static int	iwm_get_nvm_version(const struct iwm_softc *, const uint16_t *);
347 static int	iwm_get_radio_cfg(const struct iwm_softc *, const uint16_t *,
348 				  const uint16_t *);
349 static int	iwm_get_n_hw_addrs(const struct iwm_softc *,
350 				   const uint16_t *);
351 static void	iwm_set_radio_cfg(const struct iwm_softc *,
352 				  struct iwm_nvm_data *, uint32_t);
353 static struct iwm_nvm_data *
354 	iwm_parse_nvm_sections(struct iwm_softc *, struct iwm_nvm_section *);
355 static int	iwm_nvm_init(struct iwm_softc *);
356 static int	iwm_firmware_load_sect(struct iwm_softc *, uint32_t,
357                                        const uint8_t *, uint32_t);
358 static int	iwm_firmware_load_chunk(struct iwm_softc *, uint32_t,
359                                         const uint8_t *, uint32_t);
360 static int	iwm_load_firmware_7000(struct iwm_softc *, enum iwm_ucode_type);
361 static int	iwm_load_cpu_sections_8000(struct iwm_softc *,
362 					   struct iwm_fw_sects *, int , int *);
363 static int	iwm_load_firmware_8000(struct iwm_softc *, enum iwm_ucode_type);
364 static int	iwm_load_firmware(struct iwm_softc *, enum iwm_ucode_type);
365 static int	iwm_start_fw(struct iwm_softc *, enum iwm_ucode_type);
366 static int	iwm_send_tx_ant_cfg(struct iwm_softc *, uint8_t);
367 static int	iwm_send_phy_cfg_cmd(struct iwm_softc *);
368 static int	iwm_mvm_load_ucode_wait_alive(struct iwm_softc *,
369                                               enum iwm_ucode_type);
370 static int	iwm_run_init_mvm_ucode(struct iwm_softc *, int);
371 static int	iwm_rx_addbuf(struct iwm_softc *, int, int);
372 static int	iwm_mvm_calc_rssi(struct iwm_softc *, struct iwm_rx_phy_info *);
373 static int	iwm_mvm_get_signal_strength(struct iwm_softc *,
374 					    struct iwm_rx_phy_info *);
375 static void	iwm_mvm_rx_rx_phy_cmd(struct iwm_softc *,
376                                       struct iwm_rx_packet *,
377                                       struct iwm_rx_data *);
378 static int	iwm_get_noise(struct iwm_softc *sc,
379 		    const struct iwm_mvm_statistics_rx_non_phy *);
380 static void	iwm_mvm_rx_rx_mpdu(struct iwm_softc *, struct iwm_rx_packet *,
381                                    struct iwm_rx_data *);
382 static int	iwm_mvm_rx_tx_cmd_single(struct iwm_softc *,
383                                          struct iwm_rx_packet *,
384 				         struct iwm_node *);
385 static void	iwm_mvm_rx_tx_cmd(struct iwm_softc *, struct iwm_rx_packet *,
386                                   struct iwm_rx_data *);
387 static void	iwm_cmd_done(struct iwm_softc *, struct iwm_rx_packet *);
388 #if 0
389 static void	iwm_update_sched(struct iwm_softc *, int, int, uint8_t,
390                                  uint16_t);
391 #endif
392 static const struct iwm_rate *
393 	iwm_tx_fill_cmd(struct iwm_softc *, struct iwm_node *,
394 			struct mbuf *, struct iwm_tx_cmd *);
395 static int	iwm_tx(struct iwm_softc *, struct mbuf *,
396                        struct ieee80211_node *, int);
397 static int	iwm_raw_xmit(struct ieee80211_node *, struct mbuf *,
398 			     const struct ieee80211_bpf_params *);
399 static int	iwm_mvm_flush_tx_path(struct iwm_softc *sc,
400 				      uint32_t tfd_msk, uint32_t flags);
401 static int	iwm_mvm_send_add_sta_cmd_status(struct iwm_softc *,
402 					        struct iwm_mvm_add_sta_cmd_v7 *,
403                                                 int *);
404 static int	iwm_mvm_sta_send_to_fw(struct iwm_softc *, struct iwm_node *,
405                                        int);
406 static int	iwm_mvm_add_sta(struct iwm_softc *, struct iwm_node *);
407 static int	iwm_mvm_update_sta(struct iwm_softc *, struct iwm_node *);
408 static int	iwm_mvm_add_int_sta_common(struct iwm_softc *,
409                                            struct iwm_int_sta *,
410 				           const uint8_t *, uint16_t, uint16_t);
411 static int	iwm_mvm_add_aux_sta(struct iwm_softc *);
412 static int	iwm_mvm_update_quotas(struct iwm_softc *, struct iwm_node *);
413 static int	iwm_auth(struct ieee80211vap *, struct iwm_softc *);
414 static int	iwm_assoc(struct ieee80211vap *, struct iwm_softc *);
415 static int	iwm_release(struct iwm_softc *, struct iwm_node *);
416 static struct ieee80211_node *
417 		iwm_node_alloc(struct ieee80211vap *,
418 		               const uint8_t[IEEE80211_ADDR_LEN]);
419 static void	iwm_setrates(struct iwm_softc *, struct iwm_node *);
420 static int	iwm_media_change(struct ifnet *);
421 static int	iwm_newstate(struct ieee80211vap *, enum ieee80211_state, int);
422 static void	iwm_endscan_cb(void *, int);
423 static void	iwm_mvm_fill_sf_command(struct iwm_softc *,
424 					struct iwm_sf_cfg_cmd *,
425 					struct ieee80211_node *);
426 static int	iwm_mvm_sf_config(struct iwm_softc *, enum iwm_sf_state);
427 static int	iwm_send_bt_init_conf(struct iwm_softc *);
428 static int	iwm_send_update_mcc_cmd(struct iwm_softc *, const char *);
429 static void	iwm_mvm_tt_tx_backoff(struct iwm_softc *, uint32_t);
430 static int	iwm_init_hw(struct iwm_softc *);
431 static void	iwm_init(struct iwm_softc *);
432 static void	iwm_start(struct iwm_softc *);
433 static void	iwm_stop(struct iwm_softc *);
434 static void	iwm_watchdog(void *);
435 static void	iwm_parent(struct ieee80211com *);
436 #ifdef IWM_DEBUG
437 static const char *
438 		iwm_desc_lookup(uint32_t);
439 static void	iwm_nic_error(struct iwm_softc *);
440 static void	iwm_nic_umac_error(struct iwm_softc *);
441 #endif
442 static void	iwm_notif_intr(struct iwm_softc *);
443 static void	iwm_intr(void *);
444 static int	iwm_attach(device_t);
445 static int	iwm_is_valid_ether_addr(uint8_t *);
446 static void	iwm_preinit(void *);
447 static int	iwm_detach_local(struct iwm_softc *sc, int);
448 static void	iwm_init_task(void *);
449 static void	iwm_radiotap_attach(struct iwm_softc *);
450 static struct ieee80211vap *
451 		iwm_vap_create(struct ieee80211com *,
452 		               const char [IFNAMSIZ], int,
453 		               enum ieee80211_opmode, int,
454 		               const uint8_t [IEEE80211_ADDR_LEN],
455 		               const uint8_t [IEEE80211_ADDR_LEN]);
456 static void	iwm_vap_delete(struct ieee80211vap *);
457 static void	iwm_scan_start(struct ieee80211com *);
458 static void	iwm_scan_end(struct ieee80211com *);
459 static void	iwm_update_mcast(struct ieee80211com *);
460 static void	iwm_set_channel(struct ieee80211com *);
461 static void	iwm_scan_curchan(struct ieee80211_scan_state *, unsigned long);
462 static void	iwm_scan_mindwell(struct ieee80211_scan_state *);
463 static int	iwm_detach(device_t);
464 
465 /*
466  * Firmware parser.
467  */
468 
469 static int
470 iwm_store_cscheme(struct iwm_softc *sc, const uint8_t *data, size_t dlen)
471 {
472 	const struct iwm_fw_cscheme_list *l = (const void *)data;
473 
474 	if (dlen < sizeof(*l) ||
475 	    dlen < sizeof(l->size) + l->size * sizeof(*l->cs))
476 		return EINVAL;
477 
478 	/* we don't actually store anything for now, always use s/w crypto */
479 
480 	return 0;
481 }
482 
483 static int
484 iwm_firmware_store_section(struct iwm_softc *sc,
485     enum iwm_ucode_type type, const uint8_t *data, size_t dlen)
486 {
487 	struct iwm_fw_sects *fws;
488 	struct iwm_fw_onesect *fwone;
489 
490 	if (type >= IWM_UCODE_TYPE_MAX)
491 		return EINVAL;
492 	if (dlen < sizeof(uint32_t))
493 		return EINVAL;
494 
495 	fws = &sc->sc_fw.fw_sects[type];
496 	if (fws->fw_count >= IWM_UCODE_SECTION_MAX)
497 		return EINVAL;
498 
499 	fwone = &fws->fw_sect[fws->fw_count];
500 
501 	/* first 32bit are device load offset */
502 	memcpy(&fwone->fws_devoff, data, sizeof(uint32_t));
503 
504 	/* rest is data */
505 	fwone->fws_data = data + sizeof(uint32_t);
506 	fwone->fws_len = dlen - sizeof(uint32_t);
507 
508 	fws->fw_count++;
509 
510 	return 0;
511 }
512 
513 #define IWM_DEFAULT_SCAN_CHANNELS 40
514 
515 /* iwlwifi: iwl-drv.c */
516 struct iwm_tlv_calib_data {
517 	uint32_t ucode_type;
518 	struct iwm_tlv_calib_ctrl calib;
519 } __packed;
520 
521 static int
522 iwm_set_default_calib(struct iwm_softc *sc, const void *data)
523 {
524 	const struct iwm_tlv_calib_data *def_calib = data;
525 	uint32_t ucode_type = le32toh(def_calib->ucode_type);
526 
527 	if (ucode_type >= IWM_UCODE_TYPE_MAX) {
528 		device_printf(sc->sc_dev,
529 		    "Wrong ucode_type %u for default "
530 		    "calibration.\n", ucode_type);
531 		return EINVAL;
532 	}
533 
534 	sc->sc_default_calib[ucode_type].flow_trigger =
535 	    def_calib->calib.flow_trigger;
536 	sc->sc_default_calib[ucode_type].event_trigger =
537 	    def_calib->calib.event_trigger;
538 
539 	return 0;
540 }
541 
542 static void
543 iwm_fw_info_free(struct iwm_fw_info *fw)
544 {
545 	firmware_put(fw->fw_fp, FIRMWARE_UNLOAD);
546 	fw->fw_fp = NULL;
547 	/* don't touch fw->fw_status */
548 	memset(fw->fw_sects, 0, sizeof(fw->fw_sects));
549 }
550 
551 static int
552 iwm_read_firmware(struct iwm_softc *sc, enum iwm_ucode_type ucode_type)
553 {
554 	struct iwm_fw_info *fw = &sc->sc_fw;
555 	const struct iwm_tlv_ucode_header *uhdr;
556 	struct iwm_ucode_tlv tlv;
557 	enum iwm_ucode_tlv_type tlv_type;
558 	const struct firmware *fwp;
559 	const uint8_t *data;
560 	uint32_t usniffer_img;
561 	uint32_t paging_mem_size;
562 	int error = 0;
563 	size_t len;
564 
565 	if (fw->fw_status == IWM_FW_STATUS_DONE &&
566 	    ucode_type != IWM_UCODE_INIT)
567 		return 0;
568 
569 	while (fw->fw_status == IWM_FW_STATUS_INPROGRESS)
570 		msleep(&sc->sc_fw, &sc->sc_mtx, 0, "iwmfwp", 0);
571 	fw->fw_status = IWM_FW_STATUS_INPROGRESS;
572 
573 	if (fw->fw_fp != NULL)
574 		iwm_fw_info_free(fw);
575 
576 	/*
577 	 * Load firmware into driver memory.
578 	 * fw_fp will be set.
579 	 */
580 	IWM_UNLOCK(sc);
581 	fwp = firmware_get(sc->cfg->fw_name);
582 	IWM_LOCK(sc);
583 	if (fwp == NULL) {
584 		device_printf(sc->sc_dev,
585 		    "could not read firmware %s (error %d)\n",
586 		    sc->cfg->fw_name, error);
587 		goto out;
588 	}
589 	fw->fw_fp = fwp;
590 
591 	/* (Re-)Initialize default values. */
592 	sc->sc_capaflags = 0;
593 	sc->sc_capa_n_scan_channels = IWM_DEFAULT_SCAN_CHANNELS;
594 	memset(sc->sc_enabled_capa, 0, sizeof(sc->sc_enabled_capa));
595 	memset(sc->sc_fw_mcc, 0, sizeof(sc->sc_fw_mcc));
596 
597 	/*
598 	 * Parse firmware contents
599 	 */
600 
601 	uhdr = (const void *)fw->fw_fp->data;
602 	if (*(const uint32_t *)fw->fw_fp->data != 0
603 	    || le32toh(uhdr->magic) != IWM_TLV_UCODE_MAGIC) {
604 		device_printf(sc->sc_dev, "invalid firmware %s\n",
605 		    sc->cfg->fw_name);
606 		error = EINVAL;
607 		goto out;
608 	}
609 
610 	snprintf(sc->sc_fwver, sizeof(sc->sc_fwver), "%d.%d (API ver %d)",
611 	    IWM_UCODE_MAJOR(le32toh(uhdr->ver)),
612 	    IWM_UCODE_MINOR(le32toh(uhdr->ver)),
613 	    IWM_UCODE_API(le32toh(uhdr->ver)));
614 	data = uhdr->data;
615 	len = fw->fw_fp->datasize - sizeof(*uhdr);
616 
617 	while (len >= sizeof(tlv)) {
618 		size_t tlv_len;
619 		const void *tlv_data;
620 
621 		memcpy(&tlv, data, sizeof(tlv));
622 		tlv_len = le32toh(tlv.length);
623 		tlv_type = le32toh(tlv.type);
624 
625 		len -= sizeof(tlv);
626 		data += sizeof(tlv);
627 		tlv_data = data;
628 
629 		if (len < tlv_len) {
630 			device_printf(sc->sc_dev,
631 			    "firmware too short: %zu bytes\n",
632 			    len);
633 			error = EINVAL;
634 			goto parse_out;
635 		}
636 
637 		switch ((int)tlv_type) {
638 		case IWM_UCODE_TLV_PROBE_MAX_LEN:
639 			if (tlv_len < sizeof(uint32_t)) {
640 				device_printf(sc->sc_dev,
641 				    "%s: PROBE_MAX_LEN (%d) < sizeof(uint32_t)\n",
642 				    __func__,
643 				    (int) tlv_len);
644 				error = EINVAL;
645 				goto parse_out;
646 			}
647 			sc->sc_capa_max_probe_len
648 			    = le32toh(*(const uint32_t *)tlv_data);
649 			/* limit it to something sensible */
650 			if (sc->sc_capa_max_probe_len >
651 			    IWM_SCAN_OFFLOAD_PROBE_REQ_SIZE) {
652 				IWM_DPRINTF(sc, IWM_DEBUG_FIRMWARE_TLV,
653 				    "%s: IWM_UCODE_TLV_PROBE_MAX_LEN "
654 				    "ridiculous\n", __func__);
655 				error = EINVAL;
656 				goto parse_out;
657 			}
658 			break;
659 		case IWM_UCODE_TLV_PAN:
660 			if (tlv_len) {
661 				device_printf(sc->sc_dev,
662 				    "%s: IWM_UCODE_TLV_PAN: tlv_len (%d) > 0\n",
663 				    __func__,
664 				    (int) tlv_len);
665 				error = EINVAL;
666 				goto parse_out;
667 			}
668 			sc->sc_capaflags |= IWM_UCODE_TLV_FLAGS_PAN;
669 			break;
670 		case IWM_UCODE_TLV_FLAGS:
671 			if (tlv_len < sizeof(uint32_t)) {
672 				device_printf(sc->sc_dev,
673 				    "%s: IWM_UCODE_TLV_FLAGS: tlv_len (%d) < sizeof(uint32_t)\n",
674 				    __func__,
675 				    (int) tlv_len);
676 				error = EINVAL;
677 				goto parse_out;
678 			}
679 			/*
680 			 * Apparently there can be many flags, but Linux driver
681 			 * parses only the first one, and so do we.
682 			 *
683 			 * XXX: why does this override IWM_UCODE_TLV_PAN?
684 			 * Intentional or a bug?  Observations from
685 			 * current firmware file:
686 			 *  1) TLV_PAN is parsed first
687 			 *  2) TLV_FLAGS contains TLV_FLAGS_PAN
688 			 * ==> this resets TLV_PAN to itself... hnnnk
689 			 */
690 			sc->sc_capaflags = le32toh(*(const uint32_t *)tlv_data);
691 			break;
692 		case IWM_UCODE_TLV_CSCHEME:
693 			if ((error = iwm_store_cscheme(sc,
694 			    tlv_data, tlv_len)) != 0) {
695 				device_printf(sc->sc_dev,
696 				    "%s: iwm_store_cscheme(): returned %d\n",
697 				    __func__,
698 				    error);
699 				goto parse_out;
700 			}
701 			break;
702 		case IWM_UCODE_TLV_NUM_OF_CPU: {
703 			uint32_t num_cpu;
704 			if (tlv_len != sizeof(uint32_t)) {
705 				device_printf(sc->sc_dev,
706 				    "%s: IWM_UCODE_TLV_NUM_OF_CPU: tlv_len (%d) < sizeof(uint32_t)\n",
707 				    __func__,
708 				    (int) tlv_len);
709 				error = EINVAL;
710 				goto parse_out;
711 			}
712 			num_cpu = le32toh(*(const uint32_t *)tlv_data);
713 			if (num_cpu < 1 || num_cpu > 2) {
714 				device_printf(sc->sc_dev,
715 				    "%s: Driver supports only 1 or 2 CPUs\n",
716 				    __func__);
717 				error = EINVAL;
718 				goto parse_out;
719 			}
720 			break;
721 		}
722 		case IWM_UCODE_TLV_SEC_RT:
723 			if ((error = iwm_firmware_store_section(sc,
724 			    IWM_UCODE_REGULAR, tlv_data, tlv_len)) != 0) {
725 				device_printf(sc->sc_dev,
726 				    "%s: IWM_UCODE_REGULAR: iwm_firmware_store_section() failed; %d\n",
727 				    __func__,
728 				    error);
729 				goto parse_out;
730 			}
731 			break;
732 		case IWM_UCODE_TLV_SEC_INIT:
733 			if ((error = iwm_firmware_store_section(sc,
734 			    IWM_UCODE_INIT, tlv_data, tlv_len)) != 0) {
735 				device_printf(sc->sc_dev,
736 				    "%s: IWM_UCODE_INIT: iwm_firmware_store_section() failed; %d\n",
737 				    __func__,
738 				    error);
739 				goto parse_out;
740 			}
741 			break;
742 		case IWM_UCODE_TLV_SEC_WOWLAN:
743 			if ((error = iwm_firmware_store_section(sc,
744 			    IWM_UCODE_WOWLAN, tlv_data, tlv_len)) != 0) {
745 				device_printf(sc->sc_dev,
746 				    "%s: IWM_UCODE_WOWLAN: iwm_firmware_store_section() failed; %d\n",
747 				    __func__,
748 				    error);
749 				goto parse_out;
750 			}
751 			break;
752 		case IWM_UCODE_TLV_DEF_CALIB:
753 			if (tlv_len != sizeof(struct iwm_tlv_calib_data)) {
754 				device_printf(sc->sc_dev,
755 				    "%s: IWM_UCODE_TLV_DEV_CALIB: tlv_len (%d) < sizeof(iwm_tlv_calib_data) (%d)\n",
756 				    __func__,
757 				    (int) tlv_len,
758 				    (int) sizeof(struct iwm_tlv_calib_data));
759 				error = EINVAL;
760 				goto parse_out;
761 			}
762 			if ((error = iwm_set_default_calib(sc, tlv_data)) != 0) {
763 				device_printf(sc->sc_dev,
764 				    "%s: iwm_set_default_calib() failed: %d\n",
765 				    __func__,
766 				    error);
767 				goto parse_out;
768 			}
769 			break;
770 		case IWM_UCODE_TLV_PHY_SKU:
771 			if (tlv_len != sizeof(uint32_t)) {
772 				error = EINVAL;
773 				device_printf(sc->sc_dev,
774 				    "%s: IWM_UCODE_TLV_PHY_SKU: tlv_len (%d) < sizeof(uint32_t)\n",
775 				    __func__,
776 				    (int) tlv_len);
777 				goto parse_out;
778 			}
779 			sc->sc_fw.phy_config =
780 			    le32toh(*(const uint32_t *)tlv_data);
781 			sc->sc_fw.valid_tx_ant = (sc->sc_fw.phy_config &
782 						  IWM_FW_PHY_CFG_TX_CHAIN) >>
783 						  IWM_FW_PHY_CFG_TX_CHAIN_POS;
784 			sc->sc_fw.valid_rx_ant = (sc->sc_fw.phy_config &
785 						  IWM_FW_PHY_CFG_RX_CHAIN) >>
786 						  IWM_FW_PHY_CFG_RX_CHAIN_POS;
787 			break;
788 
789 		case IWM_UCODE_TLV_API_CHANGES_SET: {
790 			const struct iwm_ucode_api *api;
791 			if (tlv_len != sizeof(*api)) {
792 				error = EINVAL;
793 				goto parse_out;
794 			}
795 			api = (const struct iwm_ucode_api *)tlv_data;
796 			/* Flags may exceed 32 bits in future firmware. */
797 			if (le32toh(api->api_index) > 0) {
798 				device_printf(sc->sc_dev,
799 				    "unsupported API index %d\n",
800 				    le32toh(api->api_index));
801 				goto parse_out;
802 			}
803 			sc->sc_ucode_api = le32toh(api->api_flags);
804 			break;
805 		}
806 
807 		case IWM_UCODE_TLV_ENABLED_CAPABILITIES: {
808 			const struct iwm_ucode_capa *capa;
809 			int idx, i;
810 			if (tlv_len != sizeof(*capa)) {
811 				error = EINVAL;
812 				goto parse_out;
813 			}
814 			capa = (const struct iwm_ucode_capa *)tlv_data;
815 			idx = le32toh(capa->api_index);
816 			if (idx >= howmany(IWM_NUM_UCODE_TLV_CAPA, 32)) {
817 				device_printf(sc->sc_dev,
818 				    "unsupported API index %d\n", idx);
819 				goto parse_out;
820 			}
821 			for (i = 0; i < 32; i++) {
822 				if ((le32toh(capa->api_capa) & (1U << i)) == 0)
823 					continue;
824 				setbit(sc->sc_enabled_capa, i + (32 * idx));
825 			}
826 			break;
827 		}
828 
829 		case 48: /* undocumented TLV */
830 		case IWM_UCODE_TLV_SDIO_ADMA_ADDR:
831 		case IWM_UCODE_TLV_FW_GSCAN_CAPA:
832 			/* ignore, not used by current driver */
833 			break;
834 
835 		case IWM_UCODE_TLV_SEC_RT_USNIFFER:
836 			if ((error = iwm_firmware_store_section(sc,
837 			    IWM_UCODE_REGULAR_USNIFFER, tlv_data,
838 			    tlv_len)) != 0)
839 				goto parse_out;
840 			break;
841 
842 		case IWM_UCODE_TLV_PAGING:
843 			if (tlv_len != sizeof(uint32_t)) {
844 				error = EINVAL;
845 				goto parse_out;
846 			}
847 			paging_mem_size = le32toh(*(const uint32_t *)tlv_data);
848 
849 			IWM_DPRINTF(sc, IWM_DEBUG_FIRMWARE_TLV,
850 			    "%s: Paging: paging enabled (size = %u bytes)\n",
851 			    __func__, paging_mem_size);
852 			if (paging_mem_size > IWM_MAX_PAGING_IMAGE_SIZE) {
853 				device_printf(sc->sc_dev,
854 					"%s: Paging: driver supports up to %u bytes for paging image\n",
855 					__func__, IWM_MAX_PAGING_IMAGE_SIZE);
856 				error = EINVAL;
857 				goto out;
858 			}
859 			if (paging_mem_size & (IWM_FW_PAGING_SIZE - 1)) {
860 				device_printf(sc->sc_dev,
861 				    "%s: Paging: image isn't multiple %u\n",
862 				    __func__, IWM_FW_PAGING_SIZE);
863 				error = EINVAL;
864 				goto out;
865 			}
866 
867 			sc->sc_fw.fw_sects[IWM_UCODE_REGULAR].paging_mem_size =
868 			    paging_mem_size;
869 			usniffer_img = IWM_UCODE_REGULAR_USNIFFER;
870 			sc->sc_fw.fw_sects[usniffer_img].paging_mem_size =
871 			    paging_mem_size;
872 			break;
873 
874 		case IWM_UCODE_TLV_N_SCAN_CHANNELS:
875 			if (tlv_len != sizeof(uint32_t)) {
876 				error = EINVAL;
877 				goto parse_out;
878 			}
879 			sc->sc_capa_n_scan_channels =
880 			  le32toh(*(const uint32_t *)tlv_data);
881 			break;
882 
883 		case IWM_UCODE_TLV_FW_VERSION:
884 			if (tlv_len != sizeof(uint32_t) * 3) {
885 				error = EINVAL;
886 				goto parse_out;
887 			}
888 			snprintf(sc->sc_fwver, sizeof(sc->sc_fwver),
889 			    "%d.%d.%d",
890 			    le32toh(((const uint32_t *)tlv_data)[0]),
891 			    le32toh(((const uint32_t *)tlv_data)[1]),
892 			    le32toh(((const uint32_t *)tlv_data)[2]));
893 			break;
894 
895 		default:
896 			device_printf(sc->sc_dev,
897 			    "%s: unknown firmware section %d, abort\n",
898 			    __func__, tlv_type);
899 			error = EINVAL;
900 			goto parse_out;
901 		}
902 
903 		len -= roundup(tlv_len, 4);
904 		data += roundup(tlv_len, 4);
905 	}
906 
907 	KASSERT(error == 0, ("unhandled error"));
908 
909  parse_out:
910 	if (error) {
911 		device_printf(sc->sc_dev, "firmware parse error %d, "
912 		    "section type %d\n", error, tlv_type);
913 	}
914 
915 	if (!(sc->sc_capaflags & IWM_UCODE_TLV_FLAGS_PM_CMD_SUPPORT)) {
916 		device_printf(sc->sc_dev,
917 		    "device uses unsupported power ops\n");
918 		error = ENOTSUP;
919 	}
920 
921  out:
922 	if (error) {
923 		fw->fw_status = IWM_FW_STATUS_NONE;
924 		if (fw->fw_fp != NULL)
925 			iwm_fw_info_free(fw);
926 	} else
927 		fw->fw_status = IWM_FW_STATUS_DONE;
928 	wakeup(&sc->sc_fw);
929 
930 	return error;
931 }
932 
933 /*
934  * DMA resource routines
935  */
936 
937 static void
938 iwm_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
939 {
940         if (error != 0)
941                 return;
942 	KASSERT(nsegs == 1, ("too many DMA segments, %d should be 1", nsegs));
943 	*(bus_addr_t *)arg = segs[0].ds_addr;
944 }
945 
946 static int
947 iwm_dma_contig_alloc(bus_dma_tag_t tag, struct iwm_dma_info *dma,
948     bus_size_t size, bus_size_t alignment)
949 {
950 	int error;
951 
952 	dma->tag = NULL;
953 	dma->map = NULL;
954 	dma->size = size;
955 	dma->vaddr = NULL;
956 
957 	error = bus_dma_tag_create(tag, alignment,
958             0, BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, size,
959             1, size, 0, NULL, NULL, &dma->tag);
960         if (error != 0)
961                 goto fail;
962 
963         error = bus_dmamem_alloc(dma->tag, (void **)&dma->vaddr,
964             BUS_DMA_NOWAIT | BUS_DMA_ZERO | BUS_DMA_COHERENT, &dma->map);
965         if (error != 0)
966                 goto fail;
967 
968         error = bus_dmamap_load(dma->tag, dma->map, dma->vaddr, size,
969             iwm_dma_map_addr, &dma->paddr, BUS_DMA_NOWAIT);
970         if (error != 0) {
971 		bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
972 		dma->vaddr = NULL;
973 		goto fail;
974 	}
975 
976 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
977 
978 	return 0;
979 
980 fail:
981 	iwm_dma_contig_free(dma);
982 
983 	return error;
984 }
985 
986 static void
987 iwm_dma_contig_free(struct iwm_dma_info *dma)
988 {
989 	if (dma->vaddr != NULL) {
990 		bus_dmamap_sync(dma->tag, dma->map,
991 		    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
992 		bus_dmamap_unload(dma->tag, dma->map);
993 		bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
994 		dma->vaddr = NULL;
995 	}
996 	if (dma->tag != NULL) {
997 		bus_dma_tag_destroy(dma->tag);
998 		dma->tag = NULL;
999 	}
1000 }
1001 
1002 /* fwmem is used to load firmware onto the card */
1003 static int
1004 iwm_alloc_fwmem(struct iwm_softc *sc)
1005 {
1006 	/* Must be aligned on a 16-byte boundary. */
1007 	return iwm_dma_contig_alloc(sc->sc_dmat, &sc->fw_dma,
1008 	    sc->sc_fwdmasegsz, 16);
1009 }
1010 
1011 /* tx scheduler rings.  not used? */
1012 static int
1013 iwm_alloc_sched(struct iwm_softc *sc)
1014 {
1015 	/* TX scheduler rings must be aligned on a 1KB boundary. */
1016 	return iwm_dma_contig_alloc(sc->sc_dmat, &sc->sched_dma,
1017 	    nitems(sc->txq) * sizeof(struct iwm_agn_scd_bc_tbl), 1024);
1018 }
1019 
1020 /* keep-warm page is used internally by the card.  see iwl-fh.h for more info */
1021 static int
1022 iwm_alloc_kw(struct iwm_softc *sc)
1023 {
1024 	return iwm_dma_contig_alloc(sc->sc_dmat, &sc->kw_dma, 4096, 4096);
1025 }
1026 
1027 /* interrupt cause table */
1028 static int
1029 iwm_alloc_ict(struct iwm_softc *sc)
1030 {
1031 	return iwm_dma_contig_alloc(sc->sc_dmat, &sc->ict_dma,
1032 	    IWM_ICT_SIZE, 1<<IWM_ICT_PADDR_SHIFT);
1033 }
1034 
1035 static int
1036 iwm_alloc_rx_ring(struct iwm_softc *sc, struct iwm_rx_ring *ring)
1037 {
1038 	bus_size_t size;
1039 	int i, error;
1040 
1041 	ring->cur = 0;
1042 
1043 	/* Allocate RX descriptors (256-byte aligned). */
1044 	size = IWM_RX_RING_COUNT * sizeof(uint32_t);
1045 	error = iwm_dma_contig_alloc(sc->sc_dmat, &ring->desc_dma, size, 256);
1046 	if (error != 0) {
1047 		device_printf(sc->sc_dev,
1048 		    "could not allocate RX ring DMA memory\n");
1049 		goto fail;
1050 	}
1051 	ring->desc = ring->desc_dma.vaddr;
1052 
1053 	/* Allocate RX status area (16-byte aligned). */
1054 	error = iwm_dma_contig_alloc(sc->sc_dmat, &ring->stat_dma,
1055 	    sizeof(*ring->stat), 16);
1056 	if (error != 0) {
1057 		device_printf(sc->sc_dev,
1058 		    "could not allocate RX status DMA memory\n");
1059 		goto fail;
1060 	}
1061 	ring->stat = ring->stat_dma.vaddr;
1062 
1063         /* Create RX buffer DMA tag. */
1064         error = bus_dma_tag_create(sc->sc_dmat, 1, 0,
1065             BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
1066             IWM_RBUF_SIZE, 1, IWM_RBUF_SIZE, 0, NULL, NULL, &ring->data_dmat);
1067         if (error != 0) {
1068                 device_printf(sc->sc_dev,
1069                     "%s: could not create RX buf DMA tag, error %d\n",
1070                     __func__, error);
1071                 goto fail;
1072         }
1073 
1074 	/* Allocate spare bus_dmamap_t for iwm_rx_addbuf() */
1075 	error = bus_dmamap_create(ring->data_dmat, 0, &ring->spare_map);
1076 	if (error != 0) {
1077 		device_printf(sc->sc_dev,
1078 		    "%s: could not create RX buf DMA map, error %d\n",
1079 		    __func__, error);
1080 		goto fail;
1081 	}
1082 	/*
1083 	 * Allocate and map RX buffers.
1084 	 */
1085 	for (i = 0; i < IWM_RX_RING_COUNT; i++) {
1086 		struct iwm_rx_data *data = &ring->data[i];
1087 		error = bus_dmamap_create(ring->data_dmat, 0, &data->map);
1088 		if (error != 0) {
1089 			device_printf(sc->sc_dev,
1090 			    "%s: could not create RX buf DMA map, error %d\n",
1091 			    __func__, error);
1092 			goto fail;
1093 		}
1094 		data->m = NULL;
1095 
1096 		if ((error = iwm_rx_addbuf(sc, IWM_RBUF_SIZE, i)) != 0) {
1097 			goto fail;
1098 		}
1099 	}
1100 	return 0;
1101 
1102 fail:	iwm_free_rx_ring(sc, ring);
1103 	return error;
1104 }
1105 
1106 static void
1107 iwm_disable_rx_dma(struct iwm_softc *sc)
1108 {
1109 	/* XXX conditional nic locks are stupid */
1110 	/* XXX print out if we can't lock the NIC? */
1111 	if (iwm_nic_lock(sc)) {
1112 		/* XXX handle if RX stop doesn't finish? */
1113 		(void) iwm_pcie_rx_stop(sc);
1114 		iwm_nic_unlock(sc);
1115 	}
1116 }
1117 
1118 static void
1119 iwm_reset_rx_ring(struct iwm_softc *sc, struct iwm_rx_ring *ring)
1120 {
1121 	/* Reset the ring state */
1122 	ring->cur = 0;
1123 
1124 	/*
1125 	 * The hw rx ring index in shared memory must also be cleared,
1126 	 * otherwise the discrepancy can cause reprocessing chaos.
1127 	 */
1128 	memset(sc->rxq.stat, 0, sizeof(*sc->rxq.stat));
1129 }
1130 
1131 static void
1132 iwm_free_rx_ring(struct iwm_softc *sc, struct iwm_rx_ring *ring)
1133 {
1134 	int i;
1135 
1136 	iwm_dma_contig_free(&ring->desc_dma);
1137 	iwm_dma_contig_free(&ring->stat_dma);
1138 
1139 	for (i = 0; i < IWM_RX_RING_COUNT; i++) {
1140 		struct iwm_rx_data *data = &ring->data[i];
1141 
1142 		if (data->m != NULL) {
1143 			bus_dmamap_sync(ring->data_dmat, data->map,
1144 			    BUS_DMASYNC_POSTREAD);
1145 			bus_dmamap_unload(ring->data_dmat, data->map);
1146 			m_freem(data->m);
1147 			data->m = NULL;
1148 		}
1149 		if (data->map != NULL) {
1150 			bus_dmamap_destroy(ring->data_dmat, data->map);
1151 			data->map = NULL;
1152 		}
1153 	}
1154 	if (ring->spare_map != NULL) {
1155 		bus_dmamap_destroy(ring->data_dmat, ring->spare_map);
1156 		ring->spare_map = NULL;
1157 	}
1158 	if (ring->data_dmat != NULL) {
1159 		bus_dma_tag_destroy(ring->data_dmat);
1160 		ring->data_dmat = NULL;
1161 	}
1162 }
1163 
1164 static int
1165 iwm_alloc_tx_ring(struct iwm_softc *sc, struct iwm_tx_ring *ring, int qid)
1166 {
1167 	bus_addr_t paddr;
1168 	bus_size_t size;
1169 	size_t maxsize;
1170 	int nsegments;
1171 	int i, error;
1172 
1173 	ring->qid = qid;
1174 	ring->queued = 0;
1175 	ring->cur = 0;
1176 
1177 	/* Allocate TX descriptors (256-byte aligned). */
1178 	size = IWM_TX_RING_COUNT * sizeof (struct iwm_tfd);
1179 	error = iwm_dma_contig_alloc(sc->sc_dmat, &ring->desc_dma, size, 256);
1180 	if (error != 0) {
1181 		device_printf(sc->sc_dev,
1182 		    "could not allocate TX ring DMA memory\n");
1183 		goto fail;
1184 	}
1185 	ring->desc = ring->desc_dma.vaddr;
1186 
1187 	/*
1188 	 * We only use rings 0 through 9 (4 EDCA + cmd) so there is no need
1189 	 * to allocate commands space for other rings.
1190 	 */
1191 	if (qid > IWM_MVM_CMD_QUEUE)
1192 		return 0;
1193 
1194 	size = IWM_TX_RING_COUNT * sizeof(struct iwm_device_cmd);
1195 	error = iwm_dma_contig_alloc(sc->sc_dmat, &ring->cmd_dma, size, 4);
1196 	if (error != 0) {
1197 		device_printf(sc->sc_dev,
1198 		    "could not allocate TX cmd DMA memory\n");
1199 		goto fail;
1200 	}
1201 	ring->cmd = ring->cmd_dma.vaddr;
1202 
1203 	/* FW commands may require more mapped space than packets. */
1204 	if (qid == IWM_MVM_CMD_QUEUE) {
1205 		maxsize = IWM_RBUF_SIZE;
1206 		nsegments = 1;
1207 	} else {
1208 		maxsize = MCLBYTES;
1209 		nsegments = IWM_MAX_SCATTER - 2;
1210 	}
1211 
1212 	error = bus_dma_tag_create(sc->sc_dmat, 1, 0,
1213 	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, maxsize,
1214             nsegments, maxsize, 0, NULL, NULL, &ring->data_dmat);
1215 	if (error != 0) {
1216 		device_printf(sc->sc_dev, "could not create TX buf DMA tag\n");
1217 		goto fail;
1218 	}
1219 
1220 	paddr = ring->cmd_dma.paddr;
1221 	for (i = 0; i < IWM_TX_RING_COUNT; i++) {
1222 		struct iwm_tx_data *data = &ring->data[i];
1223 
1224 		data->cmd_paddr = paddr;
1225 		data->scratch_paddr = paddr + sizeof(struct iwm_cmd_header)
1226 		    + offsetof(struct iwm_tx_cmd, scratch);
1227 		paddr += sizeof(struct iwm_device_cmd);
1228 
1229 		error = bus_dmamap_create(ring->data_dmat, 0, &data->map);
1230 		if (error != 0) {
1231 			device_printf(sc->sc_dev,
1232 			    "could not create TX buf DMA map\n");
1233 			goto fail;
1234 		}
1235 	}
1236 	KASSERT(paddr == ring->cmd_dma.paddr + size,
1237 	    ("invalid physical address"));
1238 	return 0;
1239 
1240 fail:	iwm_free_tx_ring(sc, ring);
1241 	return error;
1242 }
1243 
1244 static void
1245 iwm_reset_tx_ring(struct iwm_softc *sc, struct iwm_tx_ring *ring)
1246 {
1247 	int i;
1248 
1249 	for (i = 0; i < IWM_TX_RING_COUNT; i++) {
1250 		struct iwm_tx_data *data = &ring->data[i];
1251 
1252 		if (data->m != NULL) {
1253 			bus_dmamap_sync(ring->data_dmat, data->map,
1254 			    BUS_DMASYNC_POSTWRITE);
1255 			bus_dmamap_unload(ring->data_dmat, data->map);
1256 			m_freem(data->m);
1257 			data->m = NULL;
1258 		}
1259 	}
1260 	/* Clear TX descriptors. */
1261 	memset(ring->desc, 0, ring->desc_dma.size);
1262 	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
1263 	    BUS_DMASYNC_PREWRITE);
1264 	sc->qfullmsk &= ~(1 << ring->qid);
1265 	ring->queued = 0;
1266 	ring->cur = 0;
1267 }
1268 
1269 static void
1270 iwm_free_tx_ring(struct iwm_softc *sc, struct iwm_tx_ring *ring)
1271 {
1272 	int i;
1273 
1274 	iwm_dma_contig_free(&ring->desc_dma);
1275 	iwm_dma_contig_free(&ring->cmd_dma);
1276 
1277 	for (i = 0; i < IWM_TX_RING_COUNT; i++) {
1278 		struct iwm_tx_data *data = &ring->data[i];
1279 
1280 		if (data->m != NULL) {
1281 			bus_dmamap_sync(ring->data_dmat, data->map,
1282 			    BUS_DMASYNC_POSTWRITE);
1283 			bus_dmamap_unload(ring->data_dmat, data->map);
1284 			m_freem(data->m);
1285 			data->m = NULL;
1286 		}
1287 		if (data->map != NULL) {
1288 			bus_dmamap_destroy(ring->data_dmat, data->map);
1289 			data->map = NULL;
1290 		}
1291 	}
1292 	if (ring->data_dmat != NULL) {
1293 		bus_dma_tag_destroy(ring->data_dmat);
1294 		ring->data_dmat = NULL;
1295 	}
1296 }
1297 
1298 /*
1299  * High-level hardware frobbing routines
1300  */
1301 
1302 static void
1303 iwm_enable_interrupts(struct iwm_softc *sc)
1304 {
1305 	sc->sc_intmask = IWM_CSR_INI_SET_MASK;
1306 	IWM_WRITE(sc, IWM_CSR_INT_MASK, sc->sc_intmask);
1307 }
1308 
1309 static void
1310 iwm_restore_interrupts(struct iwm_softc *sc)
1311 {
1312 	IWM_WRITE(sc, IWM_CSR_INT_MASK, sc->sc_intmask);
1313 }
1314 
1315 static void
1316 iwm_disable_interrupts(struct iwm_softc *sc)
1317 {
1318 	/* disable interrupts */
1319 	IWM_WRITE(sc, IWM_CSR_INT_MASK, 0);
1320 
1321 	/* acknowledge all interrupts */
1322 	IWM_WRITE(sc, IWM_CSR_INT, ~0);
1323 	IWM_WRITE(sc, IWM_CSR_FH_INT_STATUS, ~0);
1324 }
1325 
1326 static void
1327 iwm_ict_reset(struct iwm_softc *sc)
1328 {
1329 	iwm_disable_interrupts(sc);
1330 
1331 	/* Reset ICT table. */
1332 	memset(sc->ict_dma.vaddr, 0, IWM_ICT_SIZE);
1333 	sc->ict_cur = 0;
1334 
1335 	/* Set physical address of ICT table (4KB aligned). */
1336 	IWM_WRITE(sc, IWM_CSR_DRAM_INT_TBL_REG,
1337 	    IWM_CSR_DRAM_INT_TBL_ENABLE
1338 	    | IWM_CSR_DRAM_INIT_TBL_WRITE_POINTER
1339 	    | IWM_CSR_DRAM_INIT_TBL_WRAP_CHECK
1340 	    | sc->ict_dma.paddr >> IWM_ICT_PADDR_SHIFT);
1341 
1342 	/* Switch to ICT interrupt mode in driver. */
1343 	sc->sc_flags |= IWM_FLAG_USE_ICT;
1344 
1345 	/* Re-enable interrupts. */
1346 	IWM_WRITE(sc, IWM_CSR_INT, ~0);
1347 	iwm_enable_interrupts(sc);
1348 }
1349 
1350 /* iwlwifi pcie/trans.c */
1351 
1352 /*
1353  * Since this .. hard-resets things, it's time to actually
1354  * mark the first vap (if any) as having no mac context.
1355  * It's annoying, but since the driver is potentially being
1356  * stop/start'ed whilst active (thanks openbsd port!) we
1357  * have to correctly track this.
1358  */
1359 static void
1360 iwm_stop_device(struct iwm_softc *sc)
1361 {
1362 	struct ieee80211com *ic = &sc->sc_ic;
1363 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1364 	int chnl, qid;
1365 	uint32_t mask = 0;
1366 
1367 	/* tell the device to stop sending interrupts */
1368 	iwm_disable_interrupts(sc);
1369 
1370 	/*
1371 	 * FreeBSD-local: mark the first vap as not-uploaded,
1372 	 * so the next transition through auth/assoc
1373 	 * will correctly populate the MAC context.
1374 	 */
1375 	if (vap) {
1376 		struct iwm_vap *iv = IWM_VAP(vap);
1377 		iv->is_uploaded = 0;
1378 	}
1379 
1380 	/* device going down, Stop using ICT table */
1381 	sc->sc_flags &= ~IWM_FLAG_USE_ICT;
1382 
1383 	/* stop tx and rx.  tx and rx bits, as usual, are from if_iwn */
1384 
1385 	iwm_write_prph(sc, IWM_SCD_TXFACT, 0);
1386 
1387 	if (iwm_nic_lock(sc)) {
1388 		/* Stop each Tx DMA channel */
1389 		for (chnl = 0; chnl < IWM_FH_TCSR_CHNL_NUM; chnl++) {
1390 			IWM_WRITE(sc,
1391 			    IWM_FH_TCSR_CHNL_TX_CONFIG_REG(chnl), 0);
1392 			mask |= IWM_FH_TSSR_TX_STATUS_REG_MSK_CHNL_IDLE(chnl);
1393 		}
1394 
1395 		/* Wait for DMA channels to be idle */
1396 		if (!iwm_poll_bit(sc, IWM_FH_TSSR_TX_STATUS_REG, mask, mask,
1397 		    5000)) {
1398 			device_printf(sc->sc_dev,
1399 			    "Failing on timeout while stopping DMA channel: [0x%08x]\n",
1400 			    IWM_READ(sc, IWM_FH_TSSR_TX_STATUS_REG));
1401 		}
1402 		iwm_nic_unlock(sc);
1403 	}
1404 	iwm_disable_rx_dma(sc);
1405 
1406 	/* Stop RX ring. */
1407 	iwm_reset_rx_ring(sc, &sc->rxq);
1408 
1409 	/* Reset all TX rings. */
1410 	for (qid = 0; qid < nitems(sc->txq); qid++)
1411 		iwm_reset_tx_ring(sc, &sc->txq[qid]);
1412 
1413 	/*
1414 	 * Power-down device's busmaster DMA clocks
1415 	 */
1416 	iwm_write_prph(sc, IWM_APMG_CLK_DIS_REG, IWM_APMG_CLK_VAL_DMA_CLK_RQT);
1417 	DELAY(5);
1418 
1419 	/* Make sure (redundant) we've released our request to stay awake */
1420 	IWM_CLRBITS(sc, IWM_CSR_GP_CNTRL,
1421 	    IWM_CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ);
1422 
1423 	/* Stop the device, and put it in low power state */
1424 	iwm_apm_stop(sc);
1425 
1426 	/* Upon stop, the APM issues an interrupt if HW RF kill is set.
1427 	 * Clean again the interrupt here
1428 	 */
1429 	iwm_disable_interrupts(sc);
1430 	/* stop and reset the on-board processor */
1431 	IWM_WRITE(sc, IWM_CSR_RESET, IWM_CSR_RESET_REG_FLAG_SW_RESET);
1432 
1433 	/*
1434 	 * Even if we stop the HW, we still want the RF kill
1435 	 * interrupt
1436 	 */
1437 	iwm_enable_rfkill_int(sc);
1438 	iwm_check_rfkill(sc);
1439 }
1440 
1441 /* iwlwifi: mvm/ops.c */
1442 static void
1443 iwm_mvm_nic_config(struct iwm_softc *sc)
1444 {
1445 	uint8_t radio_cfg_type, radio_cfg_step, radio_cfg_dash;
1446 	uint32_t reg_val = 0;
1447 	uint32_t phy_config = iwm_mvm_get_phy_config(sc);
1448 
1449 	radio_cfg_type = (phy_config & IWM_FW_PHY_CFG_RADIO_TYPE) >>
1450 	    IWM_FW_PHY_CFG_RADIO_TYPE_POS;
1451 	radio_cfg_step = (phy_config & IWM_FW_PHY_CFG_RADIO_STEP) >>
1452 	    IWM_FW_PHY_CFG_RADIO_STEP_POS;
1453 	radio_cfg_dash = (phy_config & IWM_FW_PHY_CFG_RADIO_DASH) >>
1454 	    IWM_FW_PHY_CFG_RADIO_DASH_POS;
1455 
1456 	/* SKU control */
1457 	reg_val |= IWM_CSR_HW_REV_STEP(sc->sc_hw_rev) <<
1458 	    IWM_CSR_HW_IF_CONFIG_REG_POS_MAC_STEP;
1459 	reg_val |= IWM_CSR_HW_REV_DASH(sc->sc_hw_rev) <<
1460 	    IWM_CSR_HW_IF_CONFIG_REG_POS_MAC_DASH;
1461 
1462 	/* radio configuration */
1463 	reg_val |= radio_cfg_type << IWM_CSR_HW_IF_CONFIG_REG_POS_PHY_TYPE;
1464 	reg_val |= radio_cfg_step << IWM_CSR_HW_IF_CONFIG_REG_POS_PHY_STEP;
1465 	reg_val |= radio_cfg_dash << IWM_CSR_HW_IF_CONFIG_REG_POS_PHY_DASH;
1466 
1467 	IWM_WRITE(sc, IWM_CSR_HW_IF_CONFIG_REG, reg_val);
1468 
1469 	IWM_DPRINTF(sc, IWM_DEBUG_RESET,
1470 	    "Radio type=0x%x-0x%x-0x%x\n", radio_cfg_type,
1471 	    radio_cfg_step, radio_cfg_dash);
1472 
1473 	/*
1474 	 * W/A : NIC is stuck in a reset state after Early PCIe power off
1475 	 * (PCIe power is lost before PERST# is asserted), causing ME FW
1476 	 * to lose ownership and not being able to obtain it back.
1477 	 */
1478 	if (sc->cfg->device_family == IWM_DEVICE_FAMILY_7000) {
1479 		iwm_set_bits_mask_prph(sc, IWM_APMG_PS_CTRL_REG,
1480 		    IWM_APMG_PS_CTRL_EARLY_PWR_OFF_RESET_DIS,
1481 		    ~IWM_APMG_PS_CTRL_EARLY_PWR_OFF_RESET_DIS);
1482 	}
1483 }
1484 
1485 static int
1486 iwm_nic_rx_init(struct iwm_softc *sc)
1487 {
1488 	if (!iwm_nic_lock(sc))
1489 		return EBUSY;
1490 
1491 	/*
1492 	 * Initialize RX ring.  This is from the iwn driver.
1493 	 */
1494 	memset(sc->rxq.stat, 0, sizeof(*sc->rxq.stat));
1495 
1496 	/* stop DMA */
1497 	iwm_disable_rx_dma(sc);
1498 	IWM_WRITE(sc, IWM_FH_MEM_RCSR_CHNL0_RBDCB_WPTR, 0);
1499 	IWM_WRITE(sc, IWM_FH_MEM_RCSR_CHNL0_FLUSH_RB_REQ, 0);
1500 	IWM_WRITE(sc, IWM_FH_RSCSR_CHNL0_RDPTR, 0);
1501 	IWM_WRITE(sc, IWM_FH_RSCSR_CHNL0_RBDCB_WPTR_REG, 0);
1502 
1503 	/* Set physical address of RX ring (256-byte aligned). */
1504 	IWM_WRITE(sc,
1505 	    IWM_FH_RSCSR_CHNL0_RBDCB_BASE_REG, sc->rxq.desc_dma.paddr >> 8);
1506 
1507 	/* Set physical address of RX status (16-byte aligned). */
1508 	IWM_WRITE(sc,
1509 	    IWM_FH_RSCSR_CHNL0_STTS_WPTR_REG, sc->rxq.stat_dma.paddr >> 4);
1510 
1511 	/* Enable RX. */
1512 	IWM_WRITE(sc, IWM_FH_MEM_RCSR_CHNL0_CONFIG_REG,
1513 	    IWM_FH_RCSR_RX_CONFIG_CHNL_EN_ENABLE_VAL		|
1514 	    IWM_FH_RCSR_CHNL0_RX_IGNORE_RXF_EMPTY		|  /* HW bug */
1515 	    IWM_FH_RCSR_CHNL0_RX_CONFIG_IRQ_DEST_INT_HOST_VAL	|
1516 	    IWM_FH_RCSR_CHNL0_RX_CONFIG_SINGLE_FRAME_MSK	|
1517 	    (IWM_RX_RB_TIMEOUT << IWM_FH_RCSR_RX_CONFIG_REG_IRQ_RBTH_POS) |
1518 	    IWM_FH_RCSR_RX_CONFIG_REG_VAL_RB_SIZE_4K		|
1519 	    IWM_RX_QUEUE_SIZE_LOG << IWM_FH_RCSR_RX_CONFIG_RBDCB_SIZE_POS);
1520 
1521 	IWM_WRITE_1(sc, IWM_CSR_INT_COALESCING, IWM_HOST_INT_TIMEOUT_DEF);
1522 
1523 	/* W/A for interrupt coalescing bug in 7260 and 3160 */
1524 	if (sc->cfg->host_interrupt_operation_mode)
1525 		IWM_SETBITS(sc, IWM_CSR_INT_COALESCING, IWM_HOST_INT_OPER_MODE);
1526 
1527 	/*
1528 	 * Thus sayeth el jefe (iwlwifi) via a comment:
1529 	 *
1530 	 * This value should initially be 0 (before preparing any
1531 	 * RBs), should be 8 after preparing the first 8 RBs (for example)
1532 	 */
1533 	IWM_WRITE(sc, IWM_FH_RSCSR_CHNL0_WPTR, 8);
1534 
1535 	iwm_nic_unlock(sc);
1536 
1537 	return 0;
1538 }
1539 
1540 static int
1541 iwm_nic_tx_init(struct iwm_softc *sc)
1542 {
1543 	int qid;
1544 
1545 	if (!iwm_nic_lock(sc))
1546 		return EBUSY;
1547 
1548 	/* Deactivate TX scheduler. */
1549 	iwm_write_prph(sc, IWM_SCD_TXFACT, 0);
1550 
1551 	/* Set physical address of "keep warm" page (16-byte aligned). */
1552 	IWM_WRITE(sc, IWM_FH_KW_MEM_ADDR_REG, sc->kw_dma.paddr >> 4);
1553 
1554 	/* Initialize TX rings. */
1555 	for (qid = 0; qid < nitems(sc->txq); qid++) {
1556 		struct iwm_tx_ring *txq = &sc->txq[qid];
1557 
1558 		/* Set physical address of TX ring (256-byte aligned). */
1559 		IWM_WRITE(sc, IWM_FH_MEM_CBBC_QUEUE(qid),
1560 		    txq->desc_dma.paddr >> 8);
1561 		IWM_DPRINTF(sc, IWM_DEBUG_XMIT,
1562 		    "%s: loading ring %d descriptors (%p) at %lx\n",
1563 		    __func__,
1564 		    qid, txq->desc,
1565 		    (unsigned long) (txq->desc_dma.paddr >> 8));
1566 	}
1567 
1568 	iwm_write_prph(sc, IWM_SCD_GP_CTRL, IWM_SCD_GP_CTRL_AUTO_ACTIVE_MODE);
1569 
1570 	iwm_nic_unlock(sc);
1571 
1572 	return 0;
1573 }
1574 
1575 static int
1576 iwm_nic_init(struct iwm_softc *sc)
1577 {
1578 	int error;
1579 
1580 	iwm_apm_init(sc);
1581 	if (sc->cfg->device_family == IWM_DEVICE_FAMILY_7000)
1582 		iwm_set_pwr(sc);
1583 
1584 	iwm_mvm_nic_config(sc);
1585 
1586 	if ((error = iwm_nic_rx_init(sc)) != 0)
1587 		return error;
1588 
1589 	/*
1590 	 * Ditto for TX, from iwn
1591 	 */
1592 	if ((error = iwm_nic_tx_init(sc)) != 0)
1593 		return error;
1594 
1595 	IWM_DPRINTF(sc, IWM_DEBUG_RESET,
1596 	    "%s: shadow registers enabled\n", __func__);
1597 	IWM_SETBITS(sc, IWM_CSR_MAC_SHADOW_REG_CTRL, 0x800fffff);
1598 
1599 	return 0;
1600 }
1601 
1602 const uint8_t iwm_mvm_ac_to_tx_fifo[] = {
1603 	IWM_MVM_TX_FIFO_VO,
1604 	IWM_MVM_TX_FIFO_VI,
1605 	IWM_MVM_TX_FIFO_BE,
1606 	IWM_MVM_TX_FIFO_BK,
1607 };
1608 
1609 static int
1610 iwm_enable_txq(struct iwm_softc *sc, int sta_id, int qid, int fifo)
1611 {
1612 	if (!iwm_nic_lock(sc)) {
1613 		device_printf(sc->sc_dev,
1614 		    "%s: cannot enable txq %d\n",
1615 		    __func__,
1616 		    qid);
1617 		return EBUSY;
1618 	}
1619 
1620 	IWM_WRITE(sc, IWM_HBUS_TARG_WRPTR, qid << 8 | 0);
1621 
1622 	if (qid == IWM_MVM_CMD_QUEUE) {
1623 		/* unactivate before configuration */
1624 		iwm_write_prph(sc, IWM_SCD_QUEUE_STATUS_BITS(qid),
1625 		    (0 << IWM_SCD_QUEUE_STTS_REG_POS_ACTIVE)
1626 		    | (1 << IWM_SCD_QUEUE_STTS_REG_POS_SCD_ACT_EN));
1627 
1628 		iwm_clear_bits_prph(sc, IWM_SCD_AGGR_SEL, (1 << qid));
1629 
1630 		iwm_write_prph(sc, IWM_SCD_QUEUE_RDPTR(qid), 0);
1631 
1632 		iwm_write_mem32(sc, sc->sched_base + IWM_SCD_CONTEXT_QUEUE_OFFSET(qid), 0);
1633 		/* Set scheduler window size and frame limit. */
1634 		iwm_write_mem32(sc,
1635 		    sc->sched_base + IWM_SCD_CONTEXT_QUEUE_OFFSET(qid) +
1636 		    sizeof(uint32_t),
1637 		    ((IWM_FRAME_LIMIT << IWM_SCD_QUEUE_CTX_REG2_WIN_SIZE_POS) &
1638 		    IWM_SCD_QUEUE_CTX_REG2_WIN_SIZE_MSK) |
1639 		    ((IWM_FRAME_LIMIT << IWM_SCD_QUEUE_CTX_REG2_FRAME_LIMIT_POS) &
1640 		    IWM_SCD_QUEUE_CTX_REG2_FRAME_LIMIT_MSK));
1641 
1642 		iwm_write_prph(sc, IWM_SCD_QUEUE_STATUS_BITS(qid),
1643 		    (1 << IWM_SCD_QUEUE_STTS_REG_POS_ACTIVE) |
1644 		    (fifo << IWM_SCD_QUEUE_STTS_REG_POS_TXF) |
1645 		    (1 << IWM_SCD_QUEUE_STTS_REG_POS_WSL) |
1646 		    IWM_SCD_QUEUE_STTS_REG_MSK);
1647 	} else {
1648 		struct iwm_scd_txq_cfg_cmd cmd;
1649 		int error;
1650 
1651 		iwm_nic_unlock(sc);
1652 
1653 		memset(&cmd, 0, sizeof(cmd));
1654 		cmd.scd_queue = qid;
1655 		cmd.enable = 1;
1656 		cmd.sta_id = sta_id;
1657 		cmd.tx_fifo = fifo;
1658 		cmd.aggregate = 0;
1659 		cmd.window = IWM_FRAME_LIMIT;
1660 
1661 		error = iwm_mvm_send_cmd_pdu(sc, IWM_SCD_QUEUE_CFG, IWM_CMD_SYNC,
1662 		    sizeof(cmd), &cmd);
1663 		if (error) {
1664 			device_printf(sc->sc_dev,
1665 			    "cannot enable txq %d\n", qid);
1666 			return error;
1667 		}
1668 
1669 		if (!iwm_nic_lock(sc))
1670 			return EBUSY;
1671 	}
1672 
1673 	iwm_write_prph(sc, IWM_SCD_EN_CTRL,
1674 	    iwm_read_prph(sc, IWM_SCD_EN_CTRL) | qid);
1675 
1676 	iwm_nic_unlock(sc);
1677 
1678 	IWM_DPRINTF(sc, IWM_DEBUG_XMIT, "%s: enabled txq %d FIFO %d\n",
1679 	    __func__, qid, fifo);
1680 
1681 	return 0;
1682 }
1683 
1684 static int
1685 iwm_post_alive(struct iwm_softc *sc)
1686 {
1687 	int nwords;
1688 	int error, chnl;
1689 	uint32_t base;
1690 
1691 	if (!iwm_nic_lock(sc))
1692 		return EBUSY;
1693 
1694 	base = iwm_read_prph(sc, IWM_SCD_SRAM_BASE_ADDR);
1695 	if (sc->sched_base != base) {
1696 		device_printf(sc->sc_dev,
1697 		    "%s: sched addr mismatch: alive: 0x%x prph: 0x%x\n",
1698 		    __func__, sc->sched_base, base);
1699 	}
1700 
1701 	iwm_ict_reset(sc);
1702 
1703 	/* Clear TX scheduler state in SRAM. */
1704 	nwords = (IWM_SCD_TRANS_TBL_MEM_UPPER_BOUND -
1705 	    IWM_SCD_CONTEXT_MEM_LOWER_BOUND)
1706 	    / sizeof(uint32_t);
1707 	error = iwm_write_mem(sc,
1708 	    sc->sched_base + IWM_SCD_CONTEXT_MEM_LOWER_BOUND,
1709 	    NULL, nwords);
1710 	if (error)
1711 		goto out;
1712 
1713 	/* Set physical address of TX scheduler rings (1KB aligned). */
1714 	iwm_write_prph(sc, IWM_SCD_DRAM_BASE_ADDR, sc->sched_dma.paddr >> 10);
1715 
1716 	iwm_write_prph(sc, IWM_SCD_CHAINEXT_EN, 0);
1717 
1718 	iwm_nic_unlock(sc);
1719 
1720 	/* enable command channel */
1721 	error = iwm_enable_txq(sc, 0 /* unused */, IWM_MVM_CMD_QUEUE, 7);
1722 	if (error)
1723 		return error;
1724 
1725 	if (!iwm_nic_lock(sc))
1726 		return EBUSY;
1727 
1728 	iwm_write_prph(sc, IWM_SCD_TXFACT, 0xff);
1729 
1730 	/* Enable DMA channels. */
1731 	for (chnl = 0; chnl < IWM_FH_TCSR_CHNL_NUM; chnl++) {
1732 		IWM_WRITE(sc, IWM_FH_TCSR_CHNL_TX_CONFIG_REG(chnl),
1733 		    IWM_FH_TCSR_TX_CONFIG_REG_VAL_DMA_CHNL_ENABLE |
1734 		    IWM_FH_TCSR_TX_CONFIG_REG_VAL_DMA_CREDIT_ENABLE);
1735 	}
1736 
1737 	IWM_SETBITS(sc, IWM_FH_TX_CHICKEN_BITS_REG,
1738 	    IWM_FH_TX_CHICKEN_BITS_SCD_AUTO_RETRY_EN);
1739 
1740 	/* Enable L1-Active */
1741 	if (sc->cfg->device_family != IWM_DEVICE_FAMILY_8000) {
1742 		iwm_clear_bits_prph(sc, IWM_APMG_PCIDEV_STT_REG,
1743 		    IWM_APMG_PCIDEV_STT_VAL_L1_ACT_DIS);
1744 	}
1745 
1746  out:
1747 	iwm_nic_unlock(sc);
1748 	return error;
1749 }
1750 
1751 /*
1752  * NVM read access and content parsing.  We do not support
1753  * external NVM or writing NVM.
1754  * iwlwifi/mvm/nvm.c
1755  */
1756 
1757 /* Default NVM size to read */
1758 #define IWM_NVM_DEFAULT_CHUNK_SIZE	(2*1024)
1759 
1760 #define IWM_NVM_WRITE_OPCODE 1
1761 #define IWM_NVM_READ_OPCODE 0
1762 
1763 /* load nvm chunk response */
1764 enum {
1765 	IWM_READ_NVM_CHUNK_SUCCEED = 0,
1766 	IWM_READ_NVM_CHUNK_NOT_VALID_ADDRESS = 1
1767 };
1768 
1769 static int
1770 iwm_nvm_read_chunk(struct iwm_softc *sc, uint16_t section,
1771 	uint16_t offset, uint16_t length, uint8_t *data, uint16_t *len)
1772 {
1773 	struct iwm_nvm_access_cmd nvm_access_cmd = {
1774 		.offset = htole16(offset),
1775 		.length = htole16(length),
1776 		.type = htole16(section),
1777 		.op_code = IWM_NVM_READ_OPCODE,
1778 	};
1779 	struct iwm_nvm_access_resp *nvm_resp;
1780 	struct iwm_rx_packet *pkt;
1781 	struct iwm_host_cmd cmd = {
1782 		.id = IWM_NVM_ACCESS_CMD,
1783 		.flags = IWM_CMD_WANT_SKB | IWM_CMD_SEND_IN_RFKILL,
1784 		.data = { &nvm_access_cmd, },
1785 	};
1786 	int ret, bytes_read, offset_read;
1787 	uint8_t *resp_data;
1788 
1789 	cmd.len[0] = sizeof(struct iwm_nvm_access_cmd);
1790 
1791 	ret = iwm_send_cmd(sc, &cmd);
1792 	if (ret) {
1793 		device_printf(sc->sc_dev,
1794 		    "Could not send NVM_ACCESS command (error=%d)\n", ret);
1795 		return ret;
1796 	}
1797 
1798 	pkt = cmd.resp_pkt;
1799 
1800 	/* Extract NVM response */
1801 	nvm_resp = (void *)pkt->data;
1802 	ret = le16toh(nvm_resp->status);
1803 	bytes_read = le16toh(nvm_resp->length);
1804 	offset_read = le16toh(nvm_resp->offset);
1805 	resp_data = nvm_resp->data;
1806 	if (ret) {
1807 		if ((offset != 0) &&
1808 		    (ret == IWM_READ_NVM_CHUNK_NOT_VALID_ADDRESS)) {
1809 			/*
1810 			 * meaning of NOT_VALID_ADDRESS:
1811 			 * driver try to read chunk from address that is
1812 			 * multiple of 2K and got an error since addr is empty.
1813 			 * meaning of (offset != 0): driver already
1814 			 * read valid data from another chunk so this case
1815 			 * is not an error.
1816 			 */
1817 			IWM_DPRINTF(sc, IWM_DEBUG_EEPROM | IWM_DEBUG_RESET,
1818 				    "NVM access command failed on offset 0x%x since that section size is multiple 2K\n",
1819 				    offset);
1820 			*len = 0;
1821 			ret = 0;
1822 		} else {
1823 			IWM_DPRINTF(sc, IWM_DEBUG_EEPROM | IWM_DEBUG_RESET,
1824 				    "NVM access command failed with status %d\n", ret);
1825 			ret = EIO;
1826 		}
1827 		goto exit;
1828 	}
1829 
1830 	if (offset_read != offset) {
1831 		device_printf(sc->sc_dev,
1832 		    "NVM ACCESS response with invalid offset %d\n",
1833 		    offset_read);
1834 		ret = EINVAL;
1835 		goto exit;
1836 	}
1837 
1838 	if (bytes_read > length) {
1839 		device_printf(sc->sc_dev,
1840 		    "NVM ACCESS response with too much data "
1841 		    "(%d bytes requested, %d bytes received)\n",
1842 		    length, bytes_read);
1843 		ret = EINVAL;
1844 		goto exit;
1845 	}
1846 
1847 	/* Write data to NVM */
1848 	memcpy(data + offset, resp_data, bytes_read);
1849 	*len = bytes_read;
1850 
1851  exit:
1852 	iwm_free_resp(sc, &cmd);
1853 	return ret;
1854 }
1855 
1856 /*
1857  * Reads an NVM section completely.
1858  * NICs prior to 7000 family don't have a real NVM, but just read
1859  * section 0 which is the EEPROM. Because the EEPROM reading is unlimited
1860  * by uCode, we need to manually check in this case that we don't
1861  * overflow and try to read more than the EEPROM size.
1862  * For 7000 family NICs, we supply the maximal size we can read, and
1863  * the uCode fills the response with as much data as we can,
1864  * without overflowing, so no check is needed.
1865  */
1866 static int
1867 iwm_nvm_read_section(struct iwm_softc *sc,
1868 	uint16_t section, uint8_t *data, uint16_t *len, uint32_t size_read)
1869 {
1870 	uint16_t seglen, length, offset = 0;
1871 	int ret;
1872 
1873 	/* Set nvm section read length */
1874 	length = IWM_NVM_DEFAULT_CHUNK_SIZE;
1875 
1876 	seglen = length;
1877 
1878 	/* Read the NVM until exhausted (reading less than requested) */
1879 	while (seglen == length) {
1880 		/* Check no memory assumptions fail and cause an overflow */
1881 		if ((size_read + offset + length) >
1882 		    sc->cfg->eeprom_size) {
1883 			device_printf(sc->sc_dev,
1884 			    "EEPROM size is too small for NVM\n");
1885 			return ENOBUFS;
1886 		}
1887 
1888 		ret = iwm_nvm_read_chunk(sc, section, offset, length, data, &seglen);
1889 		if (ret) {
1890 			IWM_DPRINTF(sc, IWM_DEBUG_EEPROM | IWM_DEBUG_RESET,
1891 				    "Cannot read NVM from section %d offset %d, length %d\n",
1892 				    section, offset, length);
1893 			return ret;
1894 		}
1895 		offset += seglen;
1896 	}
1897 
1898 	IWM_DPRINTF(sc, IWM_DEBUG_EEPROM | IWM_DEBUG_RESET,
1899 		    "NVM section %d read completed\n", section);
1900 	*len = offset;
1901 	return 0;
1902 }
1903 
1904 /*
1905  * BEGIN IWM_NVM_PARSE
1906  */
1907 
1908 /* iwlwifi/iwl-nvm-parse.c */
1909 
1910 /* NVM offsets (in words) definitions */
1911 enum iwm_nvm_offsets {
1912 	/* NVM HW-Section offset (in words) definitions */
1913 	IWM_HW_ADDR = 0x15,
1914 
1915 /* NVM SW-Section offset (in words) definitions */
1916 	IWM_NVM_SW_SECTION = 0x1C0,
1917 	IWM_NVM_VERSION = 0,
1918 	IWM_RADIO_CFG = 1,
1919 	IWM_SKU = 2,
1920 	IWM_N_HW_ADDRS = 3,
1921 	IWM_NVM_CHANNELS = 0x1E0 - IWM_NVM_SW_SECTION,
1922 
1923 /* NVM calibration section offset (in words) definitions */
1924 	IWM_NVM_CALIB_SECTION = 0x2B8,
1925 	IWM_XTAL_CALIB = 0x316 - IWM_NVM_CALIB_SECTION
1926 };
1927 
1928 enum iwm_8000_nvm_offsets {
1929 	/* NVM HW-Section offset (in words) definitions */
1930 	IWM_HW_ADDR0_WFPM_8000 = 0x12,
1931 	IWM_HW_ADDR1_WFPM_8000 = 0x16,
1932 	IWM_HW_ADDR0_PCIE_8000 = 0x8A,
1933 	IWM_HW_ADDR1_PCIE_8000 = 0x8E,
1934 	IWM_MAC_ADDRESS_OVERRIDE_8000 = 1,
1935 
1936 	/* NVM SW-Section offset (in words) definitions */
1937 	IWM_NVM_SW_SECTION_8000 = 0x1C0,
1938 	IWM_NVM_VERSION_8000 = 0,
1939 	IWM_RADIO_CFG_8000 = 0,
1940 	IWM_SKU_8000 = 2,
1941 	IWM_N_HW_ADDRS_8000 = 3,
1942 
1943 	/* NVM REGULATORY -Section offset (in words) definitions */
1944 	IWM_NVM_CHANNELS_8000 = 0,
1945 	IWM_NVM_LAR_OFFSET_8000_OLD = 0x4C7,
1946 	IWM_NVM_LAR_OFFSET_8000 = 0x507,
1947 	IWM_NVM_LAR_ENABLED_8000 = 0x7,
1948 
1949 	/* NVM calibration section offset (in words) definitions */
1950 	IWM_NVM_CALIB_SECTION_8000 = 0x2B8,
1951 	IWM_XTAL_CALIB_8000 = 0x316 - IWM_NVM_CALIB_SECTION_8000
1952 };
1953 
1954 /* SKU Capabilities (actual values from NVM definition) */
1955 enum nvm_sku_bits {
1956 	IWM_NVM_SKU_CAP_BAND_24GHZ	= (1 << 0),
1957 	IWM_NVM_SKU_CAP_BAND_52GHZ	= (1 << 1),
1958 	IWM_NVM_SKU_CAP_11N_ENABLE	= (1 << 2),
1959 	IWM_NVM_SKU_CAP_11AC_ENABLE	= (1 << 3),
1960 };
1961 
1962 /* radio config bits (actual values from NVM definition) */
1963 #define IWM_NVM_RF_CFG_DASH_MSK(x)   (x & 0x3)         /* bits 0-1   */
1964 #define IWM_NVM_RF_CFG_STEP_MSK(x)   ((x >> 2)  & 0x3) /* bits 2-3   */
1965 #define IWM_NVM_RF_CFG_TYPE_MSK(x)   ((x >> 4)  & 0x3) /* bits 4-5   */
1966 #define IWM_NVM_RF_CFG_PNUM_MSK(x)   ((x >> 6)  & 0x3) /* bits 6-7   */
1967 #define IWM_NVM_RF_CFG_TX_ANT_MSK(x) ((x >> 8)  & 0xF) /* bits 8-11  */
1968 #define IWM_NVM_RF_CFG_RX_ANT_MSK(x) ((x >> 12) & 0xF) /* bits 12-15 */
1969 
1970 #define IWM_NVM_RF_CFG_FLAVOR_MSK_8000(x)	(x & 0xF)
1971 #define IWM_NVM_RF_CFG_DASH_MSK_8000(x)		((x >> 4) & 0xF)
1972 #define IWM_NVM_RF_CFG_STEP_MSK_8000(x)		((x >> 8) & 0xF)
1973 #define IWM_NVM_RF_CFG_TYPE_MSK_8000(x)		((x >> 12) & 0xFFF)
1974 #define IWM_NVM_RF_CFG_TX_ANT_MSK_8000(x)	((x >> 24) & 0xF)
1975 #define IWM_NVM_RF_CFG_RX_ANT_MSK_8000(x)	((x >> 28) & 0xF)
1976 
1977 #define DEFAULT_MAX_TX_POWER 16
1978 
1979 /**
1980  * enum iwm_nvm_channel_flags - channel flags in NVM
1981  * @IWM_NVM_CHANNEL_VALID: channel is usable for this SKU/geo
1982  * @IWM_NVM_CHANNEL_IBSS: usable as an IBSS channel
1983  * @IWM_NVM_CHANNEL_ACTIVE: active scanning allowed
1984  * @IWM_NVM_CHANNEL_RADAR: radar detection required
1985  * XXX cannot find this (DFS) flag in iwm-nvm-parse.c
1986  * @IWM_NVM_CHANNEL_DFS: dynamic freq selection candidate
1987  * @IWM_NVM_CHANNEL_WIDE: 20 MHz channel okay (?)
1988  * @IWM_NVM_CHANNEL_40MHZ: 40 MHz channel okay (?)
1989  * @IWM_NVM_CHANNEL_80MHZ: 80 MHz channel okay (?)
1990  * @IWM_NVM_CHANNEL_160MHZ: 160 MHz channel okay (?)
1991  */
1992 enum iwm_nvm_channel_flags {
1993 	IWM_NVM_CHANNEL_VALID = (1 << 0),
1994 	IWM_NVM_CHANNEL_IBSS = (1 << 1),
1995 	IWM_NVM_CHANNEL_ACTIVE = (1 << 3),
1996 	IWM_NVM_CHANNEL_RADAR = (1 << 4),
1997 	IWM_NVM_CHANNEL_DFS = (1 << 7),
1998 	IWM_NVM_CHANNEL_WIDE = (1 << 8),
1999 	IWM_NVM_CHANNEL_40MHZ = (1 << 9),
2000 	IWM_NVM_CHANNEL_80MHZ = (1 << 10),
2001 	IWM_NVM_CHANNEL_160MHZ = (1 << 11),
2002 };
2003 
2004 /*
2005  * Translate EEPROM flags to net80211.
2006  */
2007 static uint32_t
2008 iwm_eeprom_channel_flags(uint16_t ch_flags)
2009 {
2010 	uint32_t nflags;
2011 
2012 	nflags = 0;
2013 	if ((ch_flags & IWM_NVM_CHANNEL_ACTIVE) == 0)
2014 		nflags |= IEEE80211_CHAN_PASSIVE;
2015 	if ((ch_flags & IWM_NVM_CHANNEL_IBSS) == 0)
2016 		nflags |= IEEE80211_CHAN_NOADHOC;
2017 	if (ch_flags & IWM_NVM_CHANNEL_RADAR) {
2018 		nflags |= IEEE80211_CHAN_DFS;
2019 		/* Just in case. */
2020 		nflags |= IEEE80211_CHAN_NOADHOC;
2021 	}
2022 
2023 	return (nflags);
2024 }
2025 
2026 static void
2027 iwm_add_channel_band(struct iwm_softc *sc, struct ieee80211_channel chans[],
2028     int maxchans, int *nchans, int ch_idx, size_t ch_num,
2029     const uint8_t bands[])
2030 {
2031 	const uint16_t * const nvm_ch_flags = sc->nvm_data->nvm_ch_flags;
2032 	uint32_t nflags;
2033 	uint16_t ch_flags;
2034 	uint8_t ieee;
2035 	int error;
2036 
2037 	for (; ch_idx < ch_num; ch_idx++) {
2038 		ch_flags = le16_to_cpup(nvm_ch_flags + ch_idx);
2039 		if (sc->cfg->device_family == IWM_DEVICE_FAMILY_7000)
2040 			ieee = iwm_nvm_channels[ch_idx];
2041 		else
2042 			ieee = iwm_nvm_channels_8000[ch_idx];
2043 
2044 		if (!(ch_flags & IWM_NVM_CHANNEL_VALID)) {
2045 			IWM_DPRINTF(sc, IWM_DEBUG_EEPROM,
2046 			    "Ch. %d Flags %x [%sGHz] - No traffic\n",
2047 			    ieee, ch_flags,
2048 			    (ch_idx >= IWM_NUM_2GHZ_CHANNELS) ?
2049 			    "5.2" : "2.4");
2050 			continue;
2051 		}
2052 
2053 		nflags = iwm_eeprom_channel_flags(ch_flags);
2054 		error = ieee80211_add_channel(chans, maxchans, nchans,
2055 		    ieee, 0, 0, nflags, bands);
2056 		if (error != 0)
2057 			break;
2058 
2059 		IWM_DPRINTF(sc, IWM_DEBUG_EEPROM,
2060 		    "Ch. %d Flags %x [%sGHz] - Added\n",
2061 		    ieee, ch_flags,
2062 		    (ch_idx >= IWM_NUM_2GHZ_CHANNELS) ?
2063 		    "5.2" : "2.4");
2064 	}
2065 }
2066 
2067 static void
2068 iwm_init_channel_map(struct ieee80211com *ic, int maxchans, int *nchans,
2069     struct ieee80211_channel chans[])
2070 {
2071 	struct iwm_softc *sc = ic->ic_softc;
2072 	struct iwm_nvm_data *data = sc->nvm_data;
2073 	uint8_t bands[IEEE80211_MODE_BYTES];
2074 	size_t ch_num;
2075 
2076 	memset(bands, 0, sizeof(bands));
2077 	/* 1-13: 11b/g channels. */
2078 	setbit(bands, IEEE80211_MODE_11B);
2079 	setbit(bands, IEEE80211_MODE_11G);
2080 	iwm_add_channel_band(sc, chans, maxchans, nchans, 0,
2081 	    IWM_NUM_2GHZ_CHANNELS - 1, bands);
2082 
2083 	/* 14: 11b channel only. */
2084 	clrbit(bands, IEEE80211_MODE_11G);
2085 	iwm_add_channel_band(sc, chans, maxchans, nchans,
2086 	    IWM_NUM_2GHZ_CHANNELS - 1, IWM_NUM_2GHZ_CHANNELS, bands);
2087 
2088 	if (data->sku_cap_band_52GHz_enable) {
2089 		if (sc->cfg->device_family == IWM_DEVICE_FAMILY_7000)
2090 			ch_num = nitems(iwm_nvm_channels);
2091 		else
2092 			ch_num = nitems(iwm_nvm_channels_8000);
2093 		memset(bands, 0, sizeof(bands));
2094 		setbit(bands, IEEE80211_MODE_11A);
2095 		iwm_add_channel_band(sc, chans, maxchans, nchans,
2096 		    IWM_NUM_2GHZ_CHANNELS, ch_num, bands);
2097 	}
2098 }
2099 
2100 static void
2101 iwm_set_hw_address_family_8000(struct iwm_softc *sc, struct iwm_nvm_data *data,
2102 	const uint16_t *mac_override, const uint16_t *nvm_hw)
2103 {
2104 	const uint8_t *hw_addr;
2105 
2106 	if (mac_override) {
2107 		static const uint8_t reserved_mac[] = {
2108 			0x02, 0xcc, 0xaa, 0xff, 0xee, 0x00
2109 		};
2110 
2111 		hw_addr = (const uint8_t *)(mac_override +
2112 				 IWM_MAC_ADDRESS_OVERRIDE_8000);
2113 
2114 		/*
2115 		 * Store the MAC address from MAO section.
2116 		 * No byte swapping is required in MAO section
2117 		 */
2118 		IEEE80211_ADDR_COPY(data->hw_addr, hw_addr);
2119 
2120 		/*
2121 		 * Force the use of the OTP MAC address in case of reserved MAC
2122 		 * address in the NVM, or if address is given but invalid.
2123 		 */
2124 		if (!IEEE80211_ADDR_EQ(reserved_mac, hw_addr) &&
2125 		    !IEEE80211_ADDR_EQ(ieee80211broadcastaddr, data->hw_addr) &&
2126 		    iwm_is_valid_ether_addr(data->hw_addr) &&
2127 		    !IEEE80211_IS_MULTICAST(data->hw_addr))
2128 			return;
2129 
2130 		IWM_DPRINTF(sc, IWM_DEBUG_RESET,
2131 		    "%s: mac address from nvm override section invalid\n",
2132 		    __func__);
2133 	}
2134 
2135 	if (nvm_hw) {
2136 		/* read the mac address from WFMP registers */
2137 		uint32_t mac_addr0 =
2138 		    htole32(iwm_read_prph(sc, IWM_WFMP_MAC_ADDR_0));
2139 		uint32_t mac_addr1 =
2140 		    htole32(iwm_read_prph(sc, IWM_WFMP_MAC_ADDR_1));
2141 
2142 		hw_addr = (const uint8_t *)&mac_addr0;
2143 		data->hw_addr[0] = hw_addr[3];
2144 		data->hw_addr[1] = hw_addr[2];
2145 		data->hw_addr[2] = hw_addr[1];
2146 		data->hw_addr[3] = hw_addr[0];
2147 
2148 		hw_addr = (const uint8_t *)&mac_addr1;
2149 		data->hw_addr[4] = hw_addr[1];
2150 		data->hw_addr[5] = hw_addr[0];
2151 
2152 		return;
2153 	}
2154 
2155 	device_printf(sc->sc_dev, "%s: mac address not found\n", __func__);
2156 	memset(data->hw_addr, 0, sizeof(data->hw_addr));
2157 }
2158 
2159 static int
2160 iwm_get_sku(const struct iwm_softc *sc, const uint16_t *nvm_sw,
2161 	    const uint16_t *phy_sku)
2162 {
2163 	if (sc->cfg->device_family != IWM_DEVICE_FAMILY_8000)
2164 		return le16_to_cpup(nvm_sw + IWM_SKU);
2165 
2166 	return le32_to_cpup((const uint32_t *)(phy_sku + IWM_SKU_8000));
2167 }
2168 
2169 static int
2170 iwm_get_nvm_version(const struct iwm_softc *sc, const uint16_t *nvm_sw)
2171 {
2172 	if (sc->cfg->device_family != IWM_DEVICE_FAMILY_8000)
2173 		return le16_to_cpup(nvm_sw + IWM_NVM_VERSION);
2174 	else
2175 		return le32_to_cpup((const uint32_t *)(nvm_sw +
2176 						IWM_NVM_VERSION_8000));
2177 }
2178 
2179 static int
2180 iwm_get_radio_cfg(const struct iwm_softc *sc, const uint16_t *nvm_sw,
2181 		  const uint16_t *phy_sku)
2182 {
2183         if (sc->cfg->device_family != IWM_DEVICE_FAMILY_8000)
2184                 return le16_to_cpup(nvm_sw + IWM_RADIO_CFG);
2185 
2186         return le32_to_cpup((const uint32_t *)(phy_sku + IWM_RADIO_CFG_8000));
2187 }
2188 
2189 static int
2190 iwm_get_n_hw_addrs(const struct iwm_softc *sc, const uint16_t *nvm_sw)
2191 {
2192 	int n_hw_addr;
2193 
2194 	if (sc->cfg->device_family != IWM_DEVICE_FAMILY_8000)
2195 		return le16_to_cpup(nvm_sw + IWM_N_HW_ADDRS);
2196 
2197 	n_hw_addr = le32_to_cpup((const uint32_t *)(nvm_sw + IWM_N_HW_ADDRS_8000));
2198 
2199         return n_hw_addr & IWM_N_HW_ADDR_MASK;
2200 }
2201 
2202 static void
2203 iwm_set_radio_cfg(const struct iwm_softc *sc, struct iwm_nvm_data *data,
2204 		  uint32_t radio_cfg)
2205 {
2206 	if (sc->cfg->device_family != IWM_DEVICE_FAMILY_8000) {
2207 		data->radio_cfg_type = IWM_NVM_RF_CFG_TYPE_MSK(radio_cfg);
2208 		data->radio_cfg_step = IWM_NVM_RF_CFG_STEP_MSK(radio_cfg);
2209 		data->radio_cfg_dash = IWM_NVM_RF_CFG_DASH_MSK(radio_cfg);
2210 		data->radio_cfg_pnum = IWM_NVM_RF_CFG_PNUM_MSK(radio_cfg);
2211 		return;
2212 	}
2213 
2214 	/* set the radio configuration for family 8000 */
2215 	data->radio_cfg_type = IWM_NVM_RF_CFG_TYPE_MSK_8000(radio_cfg);
2216 	data->radio_cfg_step = IWM_NVM_RF_CFG_STEP_MSK_8000(radio_cfg);
2217 	data->radio_cfg_dash = IWM_NVM_RF_CFG_DASH_MSK_8000(radio_cfg);
2218 	data->radio_cfg_pnum = IWM_NVM_RF_CFG_FLAVOR_MSK_8000(radio_cfg);
2219 	data->valid_tx_ant = IWM_NVM_RF_CFG_TX_ANT_MSK_8000(radio_cfg);
2220 	data->valid_rx_ant = IWM_NVM_RF_CFG_RX_ANT_MSK_8000(radio_cfg);
2221 }
2222 
2223 static int
2224 iwm_set_hw_address(struct iwm_softc *sc, struct iwm_nvm_data *data,
2225 		   const uint16_t *nvm_hw, const uint16_t *mac_override)
2226 {
2227 #ifdef notyet /* for FAMILY 9000 */
2228 	if (cfg->mac_addr_from_csr) {
2229 		iwm_set_hw_address_from_csr(sc, data);
2230         } else
2231 #endif
2232 	if (sc->cfg->device_family != IWM_DEVICE_FAMILY_8000) {
2233 		const uint8_t *hw_addr = (const uint8_t *)(nvm_hw + IWM_HW_ADDR);
2234 
2235 		/* The byte order is little endian 16 bit, meaning 214365 */
2236 		data->hw_addr[0] = hw_addr[1];
2237 		data->hw_addr[1] = hw_addr[0];
2238 		data->hw_addr[2] = hw_addr[3];
2239 		data->hw_addr[3] = hw_addr[2];
2240 		data->hw_addr[4] = hw_addr[5];
2241 		data->hw_addr[5] = hw_addr[4];
2242 	} else {
2243 		iwm_set_hw_address_family_8000(sc, data, mac_override, nvm_hw);
2244 	}
2245 
2246 	if (!iwm_is_valid_ether_addr(data->hw_addr)) {
2247 		device_printf(sc->sc_dev, "no valid mac address was found\n");
2248 		return EINVAL;
2249 	}
2250 
2251 	return 0;
2252 }
2253 
2254 static struct iwm_nvm_data *
2255 iwm_parse_nvm_data(struct iwm_softc *sc,
2256 		   const uint16_t *nvm_hw, const uint16_t *nvm_sw,
2257 		   const uint16_t *nvm_calib, const uint16_t *mac_override,
2258 		   const uint16_t *phy_sku, const uint16_t *regulatory)
2259 {
2260 	struct iwm_nvm_data *data;
2261 	uint32_t sku, radio_cfg;
2262 
2263 	if (sc->cfg->device_family != IWM_DEVICE_FAMILY_8000) {
2264 		data = malloc(sizeof(*data) +
2265 		    IWM_NUM_CHANNELS * sizeof(uint16_t),
2266 		    M_DEVBUF, M_NOWAIT | M_ZERO);
2267 	} else {
2268 		data = malloc(sizeof(*data) +
2269 		    IWM_NUM_CHANNELS_8000 * sizeof(uint16_t),
2270 		    M_DEVBUF, M_NOWAIT | M_ZERO);
2271 	}
2272 	if (!data)
2273 		return NULL;
2274 
2275 	data->nvm_version = iwm_get_nvm_version(sc, nvm_sw);
2276 
2277 	radio_cfg = iwm_get_radio_cfg(sc, nvm_sw, phy_sku);
2278 	iwm_set_radio_cfg(sc, data, radio_cfg);
2279 
2280 	sku = iwm_get_sku(sc, nvm_sw, phy_sku);
2281 	data->sku_cap_band_24GHz_enable = sku & IWM_NVM_SKU_CAP_BAND_24GHZ;
2282 	data->sku_cap_band_52GHz_enable = sku & IWM_NVM_SKU_CAP_BAND_52GHZ;
2283 	data->sku_cap_11n_enable = 0;
2284 
2285 	data->n_hw_addrs = iwm_get_n_hw_addrs(sc, nvm_sw);
2286 
2287 	/* If no valid mac address was found - bail out */
2288 	if (iwm_set_hw_address(sc, data, nvm_hw, mac_override)) {
2289 		free(data, M_DEVBUF);
2290 		return NULL;
2291 	}
2292 
2293 	if (sc->cfg->device_family == IWM_DEVICE_FAMILY_7000) {
2294 		memcpy(data->nvm_ch_flags, &nvm_sw[IWM_NVM_CHANNELS],
2295 		    IWM_NUM_CHANNELS * sizeof(uint16_t));
2296 	} else {
2297 		memcpy(data->nvm_ch_flags, &regulatory[IWM_NVM_CHANNELS_8000],
2298 		    IWM_NUM_CHANNELS_8000 * sizeof(uint16_t));
2299 	}
2300 
2301 	return data;
2302 }
2303 
2304 static void
2305 iwm_free_nvm_data(struct iwm_nvm_data *data)
2306 {
2307 	if (data != NULL)
2308 		free(data, M_DEVBUF);
2309 }
2310 
2311 static struct iwm_nvm_data *
2312 iwm_parse_nvm_sections(struct iwm_softc *sc, struct iwm_nvm_section *sections)
2313 {
2314 	const uint16_t *hw, *sw, *calib, *regulatory, *mac_override, *phy_sku;
2315 
2316 	/* Checking for required sections */
2317 	if (sc->cfg->device_family == IWM_DEVICE_FAMILY_7000) {
2318 		if (!sections[IWM_NVM_SECTION_TYPE_SW].data ||
2319 		    !sections[sc->cfg->nvm_hw_section_num].data) {
2320 			device_printf(sc->sc_dev,
2321 			    "Can't parse empty OTP/NVM sections\n");
2322 			return NULL;
2323 		}
2324 	} else if (sc->cfg->device_family == IWM_DEVICE_FAMILY_8000) {
2325 		/* SW and REGULATORY sections are mandatory */
2326 		if (!sections[IWM_NVM_SECTION_TYPE_SW].data ||
2327 		    !sections[IWM_NVM_SECTION_TYPE_REGULATORY].data) {
2328 			device_printf(sc->sc_dev,
2329 			    "Can't parse empty OTP/NVM sections\n");
2330 			return NULL;
2331 		}
2332 		/* MAC_OVERRIDE or at least HW section must exist */
2333 		if (!sections[sc->cfg->nvm_hw_section_num].data &&
2334 		    !sections[IWM_NVM_SECTION_TYPE_MAC_OVERRIDE].data) {
2335 			device_printf(sc->sc_dev,
2336 			    "Can't parse mac_address, empty sections\n");
2337 			return NULL;
2338 		}
2339 
2340 		/* PHY_SKU section is mandatory in B0 */
2341 		if (!sections[IWM_NVM_SECTION_TYPE_PHY_SKU].data) {
2342 			device_printf(sc->sc_dev,
2343 			    "Can't parse phy_sku in B0, empty sections\n");
2344 			return NULL;
2345 		}
2346 	} else {
2347 		panic("unknown device family %d\n", sc->cfg->device_family);
2348 	}
2349 
2350 	hw = (const uint16_t *) sections[sc->cfg->nvm_hw_section_num].data;
2351 	sw = (const uint16_t *)sections[IWM_NVM_SECTION_TYPE_SW].data;
2352 	calib = (const uint16_t *)
2353 	    sections[IWM_NVM_SECTION_TYPE_CALIBRATION].data;
2354 	regulatory = (const uint16_t *)
2355 	    sections[IWM_NVM_SECTION_TYPE_REGULATORY].data;
2356 	mac_override = (const uint16_t *)
2357 	    sections[IWM_NVM_SECTION_TYPE_MAC_OVERRIDE].data;
2358 	phy_sku = (const uint16_t *)sections[IWM_NVM_SECTION_TYPE_PHY_SKU].data;
2359 
2360 	return iwm_parse_nvm_data(sc, hw, sw, calib, mac_override,
2361 	    phy_sku, regulatory);
2362 }
2363 
2364 static int
2365 iwm_nvm_init(struct iwm_softc *sc)
2366 {
2367 	struct iwm_nvm_section nvm_sections[IWM_NVM_MAX_NUM_SECTIONS];
2368 	int i, ret, section;
2369 	uint32_t size_read = 0;
2370 	uint8_t *nvm_buffer, *temp;
2371 	uint16_t len;
2372 
2373 	memset(nvm_sections, 0, sizeof(nvm_sections));
2374 
2375 	if (sc->cfg->nvm_hw_section_num >= IWM_NVM_MAX_NUM_SECTIONS)
2376 		return EINVAL;
2377 
2378 	/* load NVM values from nic */
2379 	/* Read From FW NVM */
2380 	IWM_DPRINTF(sc, IWM_DEBUG_EEPROM, "Read from NVM\n");
2381 
2382 	nvm_buffer = malloc(sc->cfg->eeprom_size, M_DEVBUF, M_NOWAIT | M_ZERO);
2383 	if (!nvm_buffer)
2384 		return ENOMEM;
2385 	for (section = 0; section < IWM_NVM_MAX_NUM_SECTIONS; section++) {
2386 		/* we override the constness for initial read */
2387 		ret = iwm_nvm_read_section(sc, section, nvm_buffer,
2388 					   &len, size_read);
2389 		if (ret)
2390 			continue;
2391 		size_read += len;
2392 		temp = malloc(len, M_DEVBUF, M_NOWAIT);
2393 		if (!temp) {
2394 			ret = ENOMEM;
2395 			break;
2396 		}
2397 		memcpy(temp, nvm_buffer, len);
2398 
2399 		nvm_sections[section].data = temp;
2400 		nvm_sections[section].length = len;
2401 	}
2402 	if (!size_read)
2403 		device_printf(sc->sc_dev, "OTP is blank\n");
2404 	free(nvm_buffer, M_DEVBUF);
2405 
2406 	sc->nvm_data = iwm_parse_nvm_sections(sc, nvm_sections);
2407 	if (!sc->nvm_data)
2408 		return EINVAL;
2409 	IWM_DPRINTF(sc, IWM_DEBUG_EEPROM | IWM_DEBUG_RESET,
2410 		    "nvm version = %x\n", sc->nvm_data->nvm_version);
2411 
2412 	for (i = 0; i < IWM_NVM_MAX_NUM_SECTIONS; i++) {
2413 		if (nvm_sections[i].data != NULL)
2414 			free(nvm_sections[i].data, M_DEVBUF);
2415 	}
2416 
2417 	return 0;
2418 }
2419 
2420 /*
2421  * Firmware loading gunk.  This is kind of a weird hybrid between the
2422  * iwn driver and the Linux iwlwifi driver.
2423  */
2424 
2425 static int
2426 iwm_firmware_load_sect(struct iwm_softc *sc, uint32_t dst_addr,
2427 	const uint8_t *section, uint32_t byte_cnt)
2428 {
2429 	int error = EINVAL;
2430 	uint32_t chunk_sz, offset;
2431 
2432 	chunk_sz = MIN(IWM_FH_MEM_TB_MAX_LENGTH, byte_cnt);
2433 
2434 	for (offset = 0; offset < byte_cnt; offset += chunk_sz) {
2435 		uint32_t addr, len;
2436 		const uint8_t *data;
2437 
2438 		addr = dst_addr + offset;
2439 		len = MIN(chunk_sz, byte_cnt - offset);
2440 		data = section + offset;
2441 
2442 		error = iwm_firmware_load_chunk(sc, addr, data, len);
2443 		if (error)
2444 			break;
2445 	}
2446 
2447 	return error;
2448 }
2449 
2450 static int
2451 iwm_firmware_load_chunk(struct iwm_softc *sc, uint32_t dst_addr,
2452 	const uint8_t *chunk, uint32_t byte_cnt)
2453 {
2454 	struct iwm_dma_info *dma = &sc->fw_dma;
2455 	int error;
2456 
2457 	/* Copy firmware chunk into pre-allocated DMA-safe memory. */
2458 	memcpy(dma->vaddr, chunk, byte_cnt);
2459 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
2460 
2461 	if (dst_addr >= IWM_FW_MEM_EXTENDED_START &&
2462 	    dst_addr <= IWM_FW_MEM_EXTENDED_END) {
2463 		iwm_set_bits_prph(sc, IWM_LMPM_CHICK,
2464 		    IWM_LMPM_CHICK_EXTENDED_ADDR_SPACE);
2465 	}
2466 
2467 	sc->sc_fw_chunk_done = 0;
2468 
2469 	if (!iwm_nic_lock(sc))
2470 		return EBUSY;
2471 
2472 	IWM_WRITE(sc, IWM_FH_TCSR_CHNL_TX_CONFIG_REG(IWM_FH_SRVC_CHNL),
2473 	    IWM_FH_TCSR_TX_CONFIG_REG_VAL_DMA_CHNL_PAUSE);
2474 	IWM_WRITE(sc, IWM_FH_SRVC_CHNL_SRAM_ADDR_REG(IWM_FH_SRVC_CHNL),
2475 	    dst_addr);
2476 	IWM_WRITE(sc, IWM_FH_TFDIB_CTRL0_REG(IWM_FH_SRVC_CHNL),
2477 	    dma->paddr & IWM_FH_MEM_TFDIB_DRAM_ADDR_LSB_MSK);
2478 	IWM_WRITE(sc, IWM_FH_TFDIB_CTRL1_REG(IWM_FH_SRVC_CHNL),
2479 	    (iwm_get_dma_hi_addr(dma->paddr)
2480 	      << IWM_FH_MEM_TFDIB_REG1_ADDR_BITSHIFT) | byte_cnt);
2481 	IWM_WRITE(sc, IWM_FH_TCSR_CHNL_TX_BUF_STS_REG(IWM_FH_SRVC_CHNL),
2482 	    1 << IWM_FH_TCSR_CHNL_TX_BUF_STS_REG_POS_TB_NUM |
2483 	    1 << IWM_FH_TCSR_CHNL_TX_BUF_STS_REG_POS_TB_IDX |
2484 	    IWM_FH_TCSR_CHNL_TX_BUF_STS_REG_VAL_TFDB_VALID);
2485 	IWM_WRITE(sc, IWM_FH_TCSR_CHNL_TX_CONFIG_REG(IWM_FH_SRVC_CHNL),
2486 	    IWM_FH_TCSR_TX_CONFIG_REG_VAL_DMA_CHNL_ENABLE    |
2487 	    IWM_FH_TCSR_TX_CONFIG_REG_VAL_DMA_CREDIT_DISABLE |
2488 	    IWM_FH_TCSR_TX_CONFIG_REG_VAL_CIRQ_HOST_ENDTFD);
2489 
2490 	iwm_nic_unlock(sc);
2491 
2492 	/* wait 1s for this segment to load */
2493 	while (!sc->sc_fw_chunk_done)
2494 		if ((error = msleep(&sc->sc_fw, &sc->sc_mtx, 0, "iwmfw", hz)) != 0)
2495 			break;
2496 
2497 	if (!sc->sc_fw_chunk_done) {
2498 		device_printf(sc->sc_dev,
2499 		    "fw chunk addr 0x%x len %d failed to load\n",
2500 		    dst_addr, byte_cnt);
2501 	}
2502 
2503 	if (dst_addr >= IWM_FW_MEM_EXTENDED_START &&
2504 	    dst_addr <= IWM_FW_MEM_EXTENDED_END && iwm_nic_lock(sc)) {
2505 		iwm_clear_bits_prph(sc, IWM_LMPM_CHICK,
2506 		    IWM_LMPM_CHICK_EXTENDED_ADDR_SPACE);
2507 		iwm_nic_unlock(sc);
2508 	}
2509 
2510 	return error;
2511 }
2512 
2513 int
2514 iwm_load_cpu_sections_8000(struct iwm_softc *sc, struct iwm_fw_sects *fws,
2515     int cpu, int *first_ucode_section)
2516 {
2517 	int shift_param;
2518 	int i, error = 0, sec_num = 0x1;
2519 	uint32_t val, last_read_idx = 0;
2520 	const void *data;
2521 	uint32_t dlen;
2522 	uint32_t offset;
2523 
2524 	if (cpu == 1) {
2525 		shift_param = 0;
2526 		*first_ucode_section = 0;
2527 	} else {
2528 		shift_param = 16;
2529 		(*first_ucode_section)++;
2530 	}
2531 
2532 	for (i = *first_ucode_section; i < IWM_UCODE_SECTION_MAX; i++) {
2533 		last_read_idx = i;
2534 		data = fws->fw_sect[i].fws_data;
2535 		dlen = fws->fw_sect[i].fws_len;
2536 		offset = fws->fw_sect[i].fws_devoff;
2537 
2538 		/*
2539 		 * CPU1_CPU2_SEPARATOR_SECTION delimiter - separate between
2540 		 * CPU1 to CPU2.
2541 		 * PAGING_SEPARATOR_SECTION delimiter - separate between
2542 		 * CPU2 non paged to CPU2 paging sec.
2543 		 */
2544 		if (!data || offset == IWM_CPU1_CPU2_SEPARATOR_SECTION ||
2545 		    offset == IWM_PAGING_SEPARATOR_SECTION)
2546 			break;
2547 
2548 		IWM_DPRINTF(sc, IWM_DEBUG_RESET,
2549 		    "LOAD FIRMWARE chunk %d offset 0x%x len %d for cpu %d\n",
2550 		    i, offset, dlen, cpu);
2551 
2552 		if (dlen > sc->sc_fwdmasegsz) {
2553 			IWM_DPRINTF(sc, IWM_DEBUG_RESET,
2554 			    "chunk %d too large (%d bytes)\n", i, dlen);
2555 			error = EFBIG;
2556 		} else {
2557 			error = iwm_firmware_load_sect(sc, offset, data, dlen);
2558 		}
2559 		if (error) {
2560 			device_printf(sc->sc_dev,
2561 			    "could not load firmware chunk %d (error %d)\n",
2562 			    i, error);
2563 			return error;
2564 		}
2565 
2566 		/* Notify the ucode of the loaded section number and status */
2567 		if (iwm_nic_lock(sc)) {
2568 			val = IWM_READ(sc, IWM_FH_UCODE_LOAD_STATUS);
2569 			val = val | (sec_num << shift_param);
2570 			IWM_WRITE(sc, IWM_FH_UCODE_LOAD_STATUS, val);
2571 			sec_num = (sec_num << 1) | 0x1;
2572 			iwm_nic_unlock(sc);
2573 
2574 			/*
2575 			 * The firmware won't load correctly without this delay.
2576 			 */
2577 			DELAY(8000);
2578 		}
2579 	}
2580 
2581 	*first_ucode_section = last_read_idx;
2582 
2583 	if (iwm_nic_lock(sc)) {
2584 		if (cpu == 1)
2585 			IWM_WRITE(sc, IWM_FH_UCODE_LOAD_STATUS, 0xFFFF);
2586 		else
2587 			IWM_WRITE(sc, IWM_FH_UCODE_LOAD_STATUS, 0xFFFFFFFF);
2588 		iwm_nic_unlock(sc);
2589 	}
2590 
2591 	return 0;
2592 }
2593 
2594 int
2595 iwm_load_firmware_8000(struct iwm_softc *sc, enum iwm_ucode_type ucode_type)
2596 {
2597 	struct iwm_fw_sects *fws;
2598 	int error = 0;
2599 	int first_ucode_section;
2600 
2601 	IWM_DPRINTF(sc, IWM_DEBUG_RESET, "loading ucode type %d\n",
2602 	    ucode_type);
2603 
2604 	fws = &sc->sc_fw.fw_sects[ucode_type];
2605 
2606 	/* configure the ucode to be ready to get the secured image */
2607 	/* release CPU reset */
2608 	iwm_write_prph(sc, IWM_RELEASE_CPU_RESET, IWM_RELEASE_CPU_RESET_BIT);
2609 
2610 	/* load to FW the binary Secured sections of CPU1 */
2611 	error = iwm_load_cpu_sections_8000(sc, fws, 1, &first_ucode_section);
2612 	if (error)
2613 		return error;
2614 
2615 	/* load to FW the binary sections of CPU2 */
2616 	return iwm_load_cpu_sections_8000(sc, fws, 2, &first_ucode_section);
2617 }
2618 
2619 static int
2620 iwm_load_firmware_7000(struct iwm_softc *sc, enum iwm_ucode_type ucode_type)
2621 {
2622 	struct iwm_fw_sects *fws;
2623 	int error, i;
2624 	const void *data;
2625 	uint32_t dlen;
2626 	uint32_t offset;
2627 
2628 	sc->sc_uc.uc_intr = 0;
2629 
2630 	fws = &sc->sc_fw.fw_sects[ucode_type];
2631 	for (i = 0; i < fws->fw_count; i++) {
2632 		data = fws->fw_sect[i].fws_data;
2633 		dlen = fws->fw_sect[i].fws_len;
2634 		offset = fws->fw_sect[i].fws_devoff;
2635 		IWM_DPRINTF(sc, IWM_DEBUG_FIRMWARE_TLV,
2636 		    "LOAD FIRMWARE type %d offset %u len %d\n",
2637 		    ucode_type, offset, dlen);
2638 		if (dlen > sc->sc_fwdmasegsz) {
2639 			IWM_DPRINTF(sc, IWM_DEBUG_FIRMWARE_TLV,
2640 			    "chunk %d too large (%d bytes)\n", i, dlen);
2641 			error = EFBIG;
2642 		} else {
2643 			error = iwm_firmware_load_sect(sc, offset, data, dlen);
2644 		}
2645 		if (error) {
2646 			device_printf(sc->sc_dev,
2647 			    "could not load firmware chunk %u of %u "
2648 			    "(error=%d)\n", i, fws->fw_count, error);
2649 			return error;
2650 		}
2651 	}
2652 
2653 	IWM_WRITE(sc, IWM_CSR_RESET, 0);
2654 
2655 	return 0;
2656 }
2657 
2658 static int
2659 iwm_load_firmware(struct iwm_softc *sc, enum iwm_ucode_type ucode_type)
2660 {
2661 	int error, w;
2662 
2663 	if (sc->cfg->device_family == IWM_DEVICE_FAMILY_8000)
2664 		error = iwm_load_firmware_8000(sc, ucode_type);
2665 	else
2666 		error = iwm_load_firmware_7000(sc, ucode_type);
2667 	if (error)
2668 		return error;
2669 
2670 	/* wait for the firmware to load */
2671 	for (w = 0; !sc->sc_uc.uc_intr && w < 10; w++) {
2672 		error = msleep(&sc->sc_uc, &sc->sc_mtx, 0, "iwmuc", hz/10);
2673 	}
2674 	if (error || !sc->sc_uc.uc_ok) {
2675 		device_printf(sc->sc_dev, "could not load firmware\n");
2676 		if (sc->cfg->device_family == IWM_DEVICE_FAMILY_8000) {
2677 			device_printf(sc->sc_dev, "cpu1 status: 0x%x\n",
2678 			    iwm_read_prph(sc, IWM_SB_CPU_1_STATUS));
2679 			device_printf(sc->sc_dev, "cpu2 status: 0x%x\n",
2680 			    iwm_read_prph(sc, IWM_SB_CPU_2_STATUS));
2681 		}
2682 	}
2683 
2684 	/*
2685 	 * Give the firmware some time to initialize.
2686 	 * Accessing it too early causes errors.
2687 	 */
2688 	msleep(&w, &sc->sc_mtx, 0, "iwmfwinit", hz);
2689 
2690 	return error;
2691 }
2692 
2693 /* iwlwifi: pcie/trans.c */
2694 static int
2695 iwm_start_fw(struct iwm_softc *sc, enum iwm_ucode_type ucode_type)
2696 {
2697 	int error;
2698 
2699 	IWM_WRITE(sc, IWM_CSR_INT, ~0);
2700 
2701 	if ((error = iwm_nic_init(sc)) != 0) {
2702 		device_printf(sc->sc_dev, "unable to init nic\n");
2703 		return error;
2704 	}
2705 
2706 	/* make sure rfkill handshake bits are cleared */
2707 	IWM_WRITE(sc, IWM_CSR_UCODE_DRV_GP1_CLR, IWM_CSR_UCODE_SW_BIT_RFKILL);
2708 	IWM_WRITE(sc, IWM_CSR_UCODE_DRV_GP1_CLR,
2709 	    IWM_CSR_UCODE_DRV_GP1_BIT_CMD_BLOCKED);
2710 
2711 	/* clear (again), then enable host interrupts */
2712 	IWM_WRITE(sc, IWM_CSR_INT, ~0);
2713 	iwm_enable_interrupts(sc);
2714 
2715 	/* really make sure rfkill handshake bits are cleared */
2716 	/* maybe we should write a few times more?  just to make sure */
2717 	IWM_WRITE(sc, IWM_CSR_UCODE_DRV_GP1_CLR, IWM_CSR_UCODE_SW_BIT_RFKILL);
2718 	IWM_WRITE(sc, IWM_CSR_UCODE_DRV_GP1_CLR, IWM_CSR_UCODE_SW_BIT_RFKILL);
2719 
2720 	/* Load the given image to the HW */
2721 	return iwm_load_firmware(sc, ucode_type);
2722 }
2723 
2724 static int
2725 iwm_send_tx_ant_cfg(struct iwm_softc *sc, uint8_t valid_tx_ant)
2726 {
2727 	struct iwm_tx_ant_cfg_cmd tx_ant_cmd = {
2728 		.valid = htole32(valid_tx_ant),
2729 	};
2730 
2731 	return iwm_mvm_send_cmd_pdu(sc, IWM_TX_ANT_CONFIGURATION_CMD,
2732 	    IWM_CMD_SYNC, sizeof(tx_ant_cmd), &tx_ant_cmd);
2733 }
2734 
2735 /* iwlwifi: mvm/fw.c */
2736 static int
2737 iwm_send_phy_cfg_cmd(struct iwm_softc *sc)
2738 {
2739 	struct iwm_phy_cfg_cmd phy_cfg_cmd;
2740 	enum iwm_ucode_type ucode_type = sc->sc_uc_current;
2741 
2742 	/* Set parameters */
2743 	phy_cfg_cmd.phy_cfg = htole32(iwm_mvm_get_phy_config(sc));
2744 	phy_cfg_cmd.calib_control.event_trigger =
2745 	    sc->sc_default_calib[ucode_type].event_trigger;
2746 	phy_cfg_cmd.calib_control.flow_trigger =
2747 	    sc->sc_default_calib[ucode_type].flow_trigger;
2748 
2749 	IWM_DPRINTF(sc, IWM_DEBUG_CMD | IWM_DEBUG_RESET,
2750 	    "Sending Phy CFG command: 0x%x\n", phy_cfg_cmd.phy_cfg);
2751 	return iwm_mvm_send_cmd_pdu(sc, IWM_PHY_CONFIGURATION_CMD, IWM_CMD_SYNC,
2752 	    sizeof(phy_cfg_cmd), &phy_cfg_cmd);
2753 }
2754 
2755 static int
2756 iwm_wait_phy_db_entry(struct iwm_softc *sc,
2757 	struct iwm_rx_packet *pkt, void *data)
2758 {
2759 	struct iwm_phy_db *phy_db = data;
2760 
2761 	if (pkt->hdr.code != IWM_CALIB_RES_NOTIF_PHY_DB) {
2762 		if(pkt->hdr.code != IWM_INIT_COMPLETE_NOTIF) {
2763 			device_printf(sc->sc_dev, "%s: Unexpected cmd: %d\n",
2764 			    __func__, pkt->hdr.code);
2765 		}
2766 		return TRUE;
2767 	}
2768 
2769 	if (iwm_phy_db_set_section(phy_db, pkt)) {
2770 		device_printf(sc->sc_dev,
2771 		    "%s: iwm_phy_db_set_section failed\n", __func__);
2772 	}
2773 
2774 	return FALSE;
2775 }
2776 
2777 static int
2778 iwm_mvm_load_ucode_wait_alive(struct iwm_softc *sc,
2779 	enum iwm_ucode_type ucode_type)
2780 {
2781 	enum iwm_ucode_type old_type = sc->sc_uc_current;
2782 	int error;
2783 
2784 	if ((error = iwm_read_firmware(sc, ucode_type)) != 0) {
2785 		device_printf(sc->sc_dev, "iwm_read_firmware: failed %d\n",
2786 			error);
2787 		return error;
2788 	}
2789 
2790 	sc->sc_uc_current = ucode_type;
2791 	error = iwm_start_fw(sc, ucode_type);
2792 	if (error) {
2793 		device_printf(sc->sc_dev, "iwm_start_fw: failed %d\n", error);
2794 		sc->sc_uc_current = old_type;
2795 		return error;
2796 	}
2797 
2798 	error = iwm_post_alive(sc);
2799 	if (error) {
2800 		device_printf(sc->sc_dev, "iwm_fw_alive: failed %d\n", error);
2801 	}
2802 	return error;
2803 }
2804 
2805 /*
2806  * mvm misc bits
2807  */
2808 
2809 /*
2810  * follows iwlwifi/fw.c
2811  */
2812 static int
2813 iwm_run_init_mvm_ucode(struct iwm_softc *sc, int justnvm)
2814 {
2815 	struct iwm_notification_wait calib_wait;
2816 	static const uint16_t init_complete[] = {
2817 		IWM_INIT_COMPLETE_NOTIF,
2818 		IWM_CALIB_RES_NOTIF_PHY_DB
2819 	};
2820 	int ret;
2821 
2822 	/* do not operate with rfkill switch turned on */
2823 	if ((sc->sc_flags & IWM_FLAG_RFKILL) && !justnvm) {
2824 		device_printf(sc->sc_dev,
2825 		    "radio is disabled by hardware switch\n");
2826 		return EPERM;
2827 	}
2828 
2829 	iwm_init_notification_wait(sc->sc_notif_wait,
2830 				   &calib_wait,
2831 				   init_complete,
2832 				   nitems(init_complete),
2833 				   iwm_wait_phy_db_entry,
2834 				   sc->sc_phy_db);
2835 
2836 	/* Will also start the device */
2837 	ret = iwm_mvm_load_ucode_wait_alive(sc, IWM_UCODE_INIT);
2838 	if (ret) {
2839 		device_printf(sc->sc_dev, "Failed to start INIT ucode: %d\n",
2840 		    ret);
2841 		goto error;
2842 	}
2843 
2844 	if (justnvm) {
2845 		/* Read nvm */
2846 		ret = iwm_nvm_init(sc);
2847 		if (ret) {
2848 			device_printf(sc->sc_dev, "failed to read nvm\n");
2849 			goto error;
2850 		}
2851 		IEEE80211_ADDR_COPY(sc->sc_ic.ic_macaddr, sc->nvm_data->hw_addr);
2852 		goto error;
2853 	}
2854 
2855 	ret = iwm_send_bt_init_conf(sc);
2856 	if (ret) {
2857 		device_printf(sc->sc_dev,
2858 		    "failed to send bt coex configuration: %d\n", ret);
2859 		goto error;
2860 	}
2861 
2862 	/* Init Smart FIFO. */
2863 	ret = iwm_mvm_sf_config(sc, IWM_SF_INIT_OFF);
2864 	if (ret)
2865 		goto error;
2866 
2867 	/* Send TX valid antennas before triggering calibrations */
2868 	ret = iwm_send_tx_ant_cfg(sc, iwm_mvm_get_valid_tx_ant(sc));
2869 	if (ret) {
2870 		device_printf(sc->sc_dev,
2871 		    "failed to send antennas before calibration: %d\n", ret);
2872 		goto error;
2873 	}
2874 
2875 	/*
2876 	 * Send phy configurations command to init uCode
2877 	 * to start the 16.0 uCode init image internal calibrations.
2878 	 */
2879 	ret = iwm_send_phy_cfg_cmd(sc);
2880 	if (ret) {
2881 		device_printf(sc->sc_dev,
2882 		    "%s: Failed to run INIT calibrations: %d\n",
2883 		    __func__, ret);
2884 		goto error;
2885 	}
2886 
2887 	/*
2888 	 * Nothing to do but wait for the init complete notification
2889 	 * from the firmware.
2890 	 */
2891 	IWM_UNLOCK(sc);
2892 	ret = iwm_wait_notification(sc->sc_notif_wait, &calib_wait,
2893 	    IWM_MVM_UCODE_CALIB_TIMEOUT);
2894 	IWM_LOCK(sc);
2895 
2896 
2897 	goto out;
2898 
2899 error:
2900 	iwm_remove_notification(sc->sc_notif_wait, &calib_wait);
2901 out:
2902 	return ret;
2903 }
2904 
2905 /*
2906  * receive side
2907  */
2908 
2909 /* (re)stock rx ring, called at init-time and at runtime */
2910 static int
2911 iwm_rx_addbuf(struct iwm_softc *sc, int size, int idx)
2912 {
2913 	struct iwm_rx_ring *ring = &sc->rxq;
2914 	struct iwm_rx_data *data = &ring->data[idx];
2915 	struct mbuf *m;
2916 	bus_dmamap_t dmamap = NULL;
2917 	bus_dma_segment_t seg;
2918 	int nsegs, error;
2919 
2920 	m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, IWM_RBUF_SIZE);
2921 	if (m == NULL)
2922 		return ENOBUFS;
2923 
2924 	m->m_len = m->m_pkthdr.len = m->m_ext.ext_size;
2925 	error = bus_dmamap_load_mbuf_sg(ring->data_dmat, ring->spare_map, m,
2926 	    &seg, &nsegs, BUS_DMA_NOWAIT);
2927 	if (error != 0) {
2928 		device_printf(sc->sc_dev,
2929 		    "%s: can't map mbuf, error %d\n", __func__, error);
2930 		goto fail;
2931 	}
2932 
2933 	if (data->m != NULL)
2934 		bus_dmamap_unload(ring->data_dmat, data->map);
2935 
2936 	/* Swap ring->spare_map with data->map */
2937 	dmamap = data->map;
2938 	data->map = ring->spare_map;
2939 	ring->spare_map = dmamap;
2940 
2941 	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_PREREAD);
2942 	data->m = m;
2943 
2944 	/* Update RX descriptor. */
2945 	KASSERT((seg.ds_addr & 255) == 0, ("seg.ds_addr not aligned"));
2946 	ring->desc[idx] = htole32(seg.ds_addr >> 8);
2947 	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
2948 	    BUS_DMASYNC_PREWRITE);
2949 
2950 	return 0;
2951 fail:
2952 	m_freem(m);
2953 	return error;
2954 }
2955 
2956 /* iwlwifi: mvm/rx.c */
2957 #define IWM_RSSI_OFFSET 50
2958 static int
2959 iwm_mvm_calc_rssi(struct iwm_softc *sc, struct iwm_rx_phy_info *phy_info)
2960 {
2961 	int rssi_a, rssi_b, rssi_a_dbm, rssi_b_dbm, max_rssi_dbm;
2962 	uint32_t agc_a, agc_b;
2963 	uint32_t val;
2964 
2965 	val = le32toh(phy_info->non_cfg_phy[IWM_RX_INFO_AGC_IDX]);
2966 	agc_a = (val & IWM_OFDM_AGC_A_MSK) >> IWM_OFDM_AGC_A_POS;
2967 	agc_b = (val & IWM_OFDM_AGC_B_MSK) >> IWM_OFDM_AGC_B_POS;
2968 
2969 	val = le32toh(phy_info->non_cfg_phy[IWM_RX_INFO_RSSI_AB_IDX]);
2970 	rssi_a = (val & IWM_OFDM_RSSI_INBAND_A_MSK) >> IWM_OFDM_RSSI_A_POS;
2971 	rssi_b = (val & IWM_OFDM_RSSI_INBAND_B_MSK) >> IWM_OFDM_RSSI_B_POS;
2972 
2973 	/*
2974 	 * dBm = rssi dB - agc dB - constant.
2975 	 * Higher AGC (higher radio gain) means lower signal.
2976 	 */
2977 	rssi_a_dbm = rssi_a - IWM_RSSI_OFFSET - agc_a;
2978 	rssi_b_dbm = rssi_b - IWM_RSSI_OFFSET - agc_b;
2979 	max_rssi_dbm = MAX(rssi_a_dbm, rssi_b_dbm);
2980 
2981 	IWM_DPRINTF(sc, IWM_DEBUG_RECV,
2982 	    "Rssi In A %d B %d Max %d AGCA %d AGCB %d\n",
2983 	    rssi_a_dbm, rssi_b_dbm, max_rssi_dbm, agc_a, agc_b);
2984 
2985 	return max_rssi_dbm;
2986 }
2987 
2988 /* iwlwifi: mvm/rx.c */
2989 /*
2990  * iwm_mvm_get_signal_strength - use new rx PHY INFO API
2991  * values are reported by the fw as positive values - need to negate
2992  * to obtain their dBM.  Account for missing antennas by replacing 0
2993  * values by -256dBm: practically 0 power and a non-feasible 8 bit value.
2994  */
2995 static int
2996 iwm_mvm_get_signal_strength(struct iwm_softc *sc, struct iwm_rx_phy_info *phy_info)
2997 {
2998 	int energy_a, energy_b, energy_c, max_energy;
2999 	uint32_t val;
3000 
3001 	val = le32toh(phy_info->non_cfg_phy[IWM_RX_INFO_ENERGY_ANT_ABC_IDX]);
3002 	energy_a = (val & IWM_RX_INFO_ENERGY_ANT_A_MSK) >>
3003 	    IWM_RX_INFO_ENERGY_ANT_A_POS;
3004 	energy_a = energy_a ? -energy_a : -256;
3005 	energy_b = (val & IWM_RX_INFO_ENERGY_ANT_B_MSK) >>
3006 	    IWM_RX_INFO_ENERGY_ANT_B_POS;
3007 	energy_b = energy_b ? -energy_b : -256;
3008 	energy_c = (val & IWM_RX_INFO_ENERGY_ANT_C_MSK) >>
3009 	    IWM_RX_INFO_ENERGY_ANT_C_POS;
3010 	energy_c = energy_c ? -energy_c : -256;
3011 	max_energy = MAX(energy_a, energy_b);
3012 	max_energy = MAX(max_energy, energy_c);
3013 
3014 	IWM_DPRINTF(sc, IWM_DEBUG_RECV,
3015 	    "energy In A %d B %d C %d , and max %d\n",
3016 	    energy_a, energy_b, energy_c, max_energy);
3017 
3018 	return max_energy;
3019 }
3020 
3021 static void
3022 iwm_mvm_rx_rx_phy_cmd(struct iwm_softc *sc,
3023 	struct iwm_rx_packet *pkt, struct iwm_rx_data *data)
3024 {
3025 	struct iwm_rx_phy_info *phy_info = (void *)pkt->data;
3026 
3027 	IWM_DPRINTF(sc, IWM_DEBUG_RECV, "received PHY stats\n");
3028 	bus_dmamap_sync(sc->rxq.data_dmat, data->map, BUS_DMASYNC_POSTREAD);
3029 
3030 	memcpy(&sc->sc_last_phy_info, phy_info, sizeof(sc->sc_last_phy_info));
3031 }
3032 
3033 /*
3034  * Retrieve the average noise (in dBm) among receivers.
3035  */
3036 static int
3037 iwm_get_noise(struct iwm_softc *sc,
3038     const struct iwm_mvm_statistics_rx_non_phy *stats)
3039 {
3040 	int i, total, nbant, noise;
3041 
3042 	total = nbant = noise = 0;
3043 	for (i = 0; i < 3; i++) {
3044 		noise = le32toh(stats->beacon_silence_rssi[i]) & 0xff;
3045 		IWM_DPRINTF(sc, IWM_DEBUG_RECV, "%s: i=%d, noise=%d\n",
3046 		    __func__,
3047 		    i,
3048 		    noise);
3049 
3050 		if (noise) {
3051 			total += noise;
3052 			nbant++;
3053 		}
3054 	}
3055 
3056 	IWM_DPRINTF(sc, IWM_DEBUG_RECV, "%s: nbant=%d, total=%d\n",
3057 	    __func__, nbant, total);
3058 #if 0
3059 	/* There should be at least one antenna but check anyway. */
3060 	return (nbant == 0) ? -127 : (total / nbant) - 107;
3061 #else
3062 	/* For now, just hard-code it to -96 to be safe */
3063 	return (-96);
3064 #endif
3065 }
3066 
3067 /*
3068  * iwm_mvm_rx_rx_mpdu - IWM_REPLY_RX_MPDU_CMD handler
3069  *
3070  * Handles the actual data of the Rx packet from the fw
3071  */
3072 static void
3073 iwm_mvm_rx_rx_mpdu(struct iwm_softc *sc,
3074 	struct iwm_rx_packet *pkt, struct iwm_rx_data *data)
3075 {
3076 	struct ieee80211com *ic = &sc->sc_ic;
3077 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3078 	struct ieee80211_frame *wh;
3079 	struct ieee80211_node *ni;
3080 	struct ieee80211_rx_stats rxs;
3081 	struct mbuf *m;
3082 	struct iwm_rx_phy_info *phy_info;
3083 	struct iwm_rx_mpdu_res_start *rx_res;
3084 	uint32_t len;
3085 	uint32_t rx_pkt_status;
3086 	int rssi;
3087 
3088 	bus_dmamap_sync(sc->rxq.data_dmat, data->map, BUS_DMASYNC_POSTREAD);
3089 
3090 	phy_info = &sc->sc_last_phy_info;
3091 	rx_res = (struct iwm_rx_mpdu_res_start *)pkt->data;
3092 	wh = (struct ieee80211_frame *)(pkt->data + sizeof(*rx_res));
3093 	len = le16toh(rx_res->byte_count);
3094 	rx_pkt_status = le32toh(*(uint32_t *)(pkt->data + sizeof(*rx_res) + len));
3095 
3096 	m = data->m;
3097 	m->m_data = pkt->data + sizeof(*rx_res);
3098 	m->m_pkthdr.len = m->m_len = len;
3099 
3100 	if (__predict_false(phy_info->cfg_phy_cnt > 20)) {
3101 		device_printf(sc->sc_dev,
3102 		    "dsp size out of range [0,20]: %d\n",
3103 		    phy_info->cfg_phy_cnt);
3104 		goto fail;
3105 	}
3106 
3107 	if (!(rx_pkt_status & IWM_RX_MPDU_RES_STATUS_CRC_OK) ||
3108 	    !(rx_pkt_status & IWM_RX_MPDU_RES_STATUS_OVERRUN_OK)) {
3109 		IWM_DPRINTF(sc, IWM_DEBUG_RECV,
3110 		    "Bad CRC or FIFO: 0x%08X.\n", rx_pkt_status);
3111 		goto fail;
3112 	}
3113 
3114 	if (sc->sc_capaflags & IWM_UCODE_TLV_FLAGS_RX_ENERGY_API) {
3115 		rssi = iwm_mvm_get_signal_strength(sc, phy_info);
3116 	} else {
3117 		rssi = iwm_mvm_calc_rssi(sc, phy_info);
3118 	}
3119 
3120 	/* Note: RSSI is absolute (ie a -ve value) */
3121 	if (rssi < IWM_MIN_DBM)
3122 		rssi = IWM_MIN_DBM;
3123 	else if (rssi > IWM_MAX_DBM)
3124 		rssi = IWM_MAX_DBM;
3125 
3126 	/* Map it to relative value */
3127 	rssi = rssi - sc->sc_noise;
3128 
3129 	/* replenish ring for the buffer we're going to feed to the sharks */
3130 	if (iwm_rx_addbuf(sc, IWM_RBUF_SIZE, sc->rxq.cur) != 0) {
3131 		device_printf(sc->sc_dev, "%s: unable to add more buffers\n",
3132 		    __func__);
3133 		goto fail;
3134 	}
3135 
3136 	IWM_DPRINTF(sc, IWM_DEBUG_RECV,
3137 	    "%s: rssi=%d, noise=%d\n", __func__, rssi, sc->sc_noise);
3138 
3139 	ni = ieee80211_find_rxnode(ic, (struct ieee80211_frame_min *)wh);
3140 
3141 	IWM_DPRINTF(sc, IWM_DEBUG_RECV,
3142 	    "%s: phy_info: channel=%d, flags=0x%08x\n",
3143 	    __func__,
3144 	    le16toh(phy_info->channel),
3145 	    le16toh(phy_info->phy_flags));
3146 
3147 	/*
3148 	 * Populate an RX state struct with the provided information.
3149 	 */
3150 	bzero(&rxs, sizeof(rxs));
3151 	rxs.r_flags |= IEEE80211_R_IEEE | IEEE80211_R_FREQ;
3152 	rxs.r_flags |= IEEE80211_R_NF | IEEE80211_R_RSSI;
3153 	rxs.c_ieee = le16toh(phy_info->channel);
3154 	if (le16toh(phy_info->phy_flags & IWM_RX_RES_PHY_FLAGS_BAND_24)) {
3155 		rxs.c_freq = ieee80211_ieee2mhz(rxs.c_ieee, IEEE80211_CHAN_2GHZ);
3156 	} else {
3157 		rxs.c_freq = ieee80211_ieee2mhz(rxs.c_ieee, IEEE80211_CHAN_5GHZ);
3158 	}
3159 
3160 	/* rssi is in 1/2db units */
3161 	rxs.c_rssi = rssi * 2;
3162 	rxs.c_nf = sc->sc_noise;
3163 	if (ieee80211_add_rx_params(m, &rxs) == 0) {
3164 		if (ni)
3165 			ieee80211_free_node(ni);
3166 		goto fail;
3167 	}
3168 
3169 	if (ieee80211_radiotap_active_vap(vap)) {
3170 		struct iwm_rx_radiotap_header *tap = &sc->sc_rxtap;
3171 
3172 		tap->wr_flags = 0;
3173 		if (phy_info->phy_flags & htole16(IWM_PHY_INFO_FLAG_SHPREAMBLE))
3174 			tap->wr_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
3175 		tap->wr_chan_freq = htole16(rxs.c_freq);
3176 		/* XXX only if ic->ic_curchan->ic_ieee == rxs.c_ieee */
3177 		tap->wr_chan_flags = htole16(ic->ic_curchan->ic_flags);
3178 		tap->wr_dbm_antsignal = (int8_t)rssi;
3179 		tap->wr_dbm_antnoise = (int8_t)sc->sc_noise;
3180 		tap->wr_tsft = phy_info->system_timestamp;
3181 		switch (phy_info->rate) {
3182 		/* CCK rates. */
3183 		case  10: tap->wr_rate =   2; break;
3184 		case  20: tap->wr_rate =   4; break;
3185 		case  55: tap->wr_rate =  11; break;
3186 		case 110: tap->wr_rate =  22; break;
3187 		/* OFDM rates. */
3188 		case 0xd: tap->wr_rate =  12; break;
3189 		case 0xf: tap->wr_rate =  18; break;
3190 		case 0x5: tap->wr_rate =  24; break;
3191 		case 0x7: tap->wr_rate =  36; break;
3192 		case 0x9: tap->wr_rate =  48; break;
3193 		case 0xb: tap->wr_rate =  72; break;
3194 		case 0x1: tap->wr_rate =  96; break;
3195 		case 0x3: tap->wr_rate = 108; break;
3196 		/* Unknown rate: should not happen. */
3197 		default:  tap->wr_rate =   0;
3198 		}
3199 	}
3200 
3201 	IWM_UNLOCK(sc);
3202 	if (ni != NULL) {
3203 		IWM_DPRINTF(sc, IWM_DEBUG_RECV, "input m %p\n", m);
3204 		ieee80211_input_mimo(ni, m);
3205 		ieee80211_free_node(ni);
3206 	} else {
3207 		IWM_DPRINTF(sc, IWM_DEBUG_RECV, "inputall m %p\n", m);
3208 		ieee80211_input_mimo_all(ic, m);
3209 	}
3210 	IWM_LOCK(sc);
3211 
3212 	return;
3213 
3214 fail:
3215 	counter_u64_add(ic->ic_ierrors, 1);
3216 }
3217 
3218 static int
3219 iwm_mvm_rx_tx_cmd_single(struct iwm_softc *sc, struct iwm_rx_packet *pkt,
3220 	struct iwm_node *in)
3221 {
3222 	struct iwm_mvm_tx_resp *tx_resp = (void *)pkt->data;
3223 	struct ieee80211_ratectl_tx_status *txs = &sc->sc_txs;
3224 	struct ieee80211_node *ni = &in->in_ni;
3225 	int status = le16toh(tx_resp->status.status) & IWM_TX_STATUS_MSK;
3226 
3227 	KASSERT(tx_resp->frame_count == 1, ("too many frames"));
3228 
3229 	/* Update rate control statistics. */
3230 	IWM_DPRINTF(sc, IWM_DEBUG_XMIT, "%s: status=0x%04x, seq=%d, fc=%d, btc=%d, frts=%d, ff=%d, irate=%08x, wmt=%d\n",
3231 	    __func__,
3232 	    (int) le16toh(tx_resp->status.status),
3233 	    (int) le16toh(tx_resp->status.sequence),
3234 	    tx_resp->frame_count,
3235 	    tx_resp->bt_kill_count,
3236 	    tx_resp->failure_rts,
3237 	    tx_resp->failure_frame,
3238 	    le32toh(tx_resp->initial_rate),
3239 	    (int) le16toh(tx_resp->wireless_media_time));
3240 
3241 	txs->flags = IEEE80211_RATECTL_STATUS_SHORT_RETRY |
3242 		     IEEE80211_RATECTL_STATUS_LONG_RETRY;
3243 	txs->short_retries = tx_resp->failure_rts;
3244 	txs->long_retries = tx_resp->failure_frame;
3245 	if (status != IWM_TX_STATUS_SUCCESS &&
3246 	    status != IWM_TX_STATUS_DIRECT_DONE) {
3247 		switch (status) {
3248 		case IWM_TX_STATUS_FAIL_SHORT_LIMIT:
3249 			txs->status = IEEE80211_RATECTL_TX_FAIL_SHORT;
3250 			break;
3251 		case IWM_TX_STATUS_FAIL_LONG_LIMIT:
3252 			txs->status = IEEE80211_RATECTL_TX_FAIL_LONG;
3253 			break;
3254 		case IWM_TX_STATUS_FAIL_LIFE_EXPIRE:
3255 			txs->status = IEEE80211_RATECTL_TX_FAIL_EXPIRED;
3256 			break;
3257 		default:
3258 			txs->status = IEEE80211_RATECTL_TX_FAIL_UNSPECIFIED;
3259 			break;
3260 		}
3261 	} else {
3262 		txs->status = IEEE80211_RATECTL_TX_SUCCESS;
3263 	}
3264 	ieee80211_ratectl_tx_complete(ni, txs);
3265 
3266 	return (txs->status != IEEE80211_RATECTL_TX_SUCCESS);
3267 }
3268 
3269 static void
3270 iwm_mvm_rx_tx_cmd(struct iwm_softc *sc,
3271 	struct iwm_rx_packet *pkt, struct iwm_rx_data *data)
3272 {
3273 	struct iwm_cmd_header *cmd_hdr = &pkt->hdr;
3274 	int idx = cmd_hdr->idx;
3275 	int qid = cmd_hdr->qid;
3276 	struct iwm_tx_ring *ring = &sc->txq[qid];
3277 	struct iwm_tx_data *txd = &ring->data[idx];
3278 	struct iwm_node *in = txd->in;
3279 	struct mbuf *m = txd->m;
3280 	int status;
3281 
3282 	KASSERT(txd->done == 0, ("txd not done"));
3283 	KASSERT(txd->in != NULL, ("txd without node"));
3284 	KASSERT(txd->m != NULL, ("txd without mbuf"));
3285 
3286 	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTREAD);
3287 
3288 	sc->sc_tx_timer = 0;
3289 
3290 	status = iwm_mvm_rx_tx_cmd_single(sc, pkt, in);
3291 
3292 	/* Unmap and free mbuf. */
3293 	bus_dmamap_sync(ring->data_dmat, txd->map, BUS_DMASYNC_POSTWRITE);
3294 	bus_dmamap_unload(ring->data_dmat, txd->map);
3295 
3296 	IWM_DPRINTF(sc, IWM_DEBUG_XMIT,
3297 	    "free txd %p, in %p\n", txd, txd->in);
3298 	txd->done = 1;
3299 	txd->m = NULL;
3300 	txd->in = NULL;
3301 
3302 	ieee80211_tx_complete(&in->in_ni, m, status);
3303 
3304 	if (--ring->queued < IWM_TX_RING_LOMARK) {
3305 		sc->qfullmsk &= ~(1 << ring->qid);
3306 		if (sc->qfullmsk == 0) {
3307 			/*
3308 			 * Well, we're in interrupt context, but then again
3309 			 * I guess net80211 does all sorts of stunts in
3310 			 * interrupt context, so maybe this is no biggie.
3311 			 */
3312 			iwm_start(sc);
3313 		}
3314 	}
3315 }
3316 
3317 /*
3318  * transmit side
3319  */
3320 
3321 /*
3322  * Process a "command done" firmware notification.  This is where we wakeup
3323  * processes waiting for a synchronous command completion.
3324  * from if_iwn
3325  */
3326 static void
3327 iwm_cmd_done(struct iwm_softc *sc, struct iwm_rx_packet *pkt)
3328 {
3329 	struct iwm_tx_ring *ring = &sc->txq[IWM_MVM_CMD_QUEUE];
3330 	struct iwm_tx_data *data;
3331 
3332 	if (pkt->hdr.qid != IWM_MVM_CMD_QUEUE) {
3333 		return;	/* Not a command ack. */
3334 	}
3335 
3336 	/* XXX wide commands? */
3337 	IWM_DPRINTF(sc, IWM_DEBUG_CMD,
3338 	    "cmd notification type 0x%x qid %d idx %d\n",
3339 	    pkt->hdr.code, pkt->hdr.qid, pkt->hdr.idx);
3340 
3341 	data = &ring->data[pkt->hdr.idx];
3342 
3343 	/* If the command was mapped in an mbuf, free it. */
3344 	if (data->m != NULL) {
3345 		bus_dmamap_sync(ring->data_dmat, data->map,
3346 		    BUS_DMASYNC_POSTWRITE);
3347 		bus_dmamap_unload(ring->data_dmat, data->map);
3348 		m_freem(data->m);
3349 		data->m = NULL;
3350 	}
3351 	wakeup(&ring->desc[pkt->hdr.idx]);
3352 }
3353 
3354 #if 0
3355 /*
3356  * necessary only for block ack mode
3357  */
3358 void
3359 iwm_update_sched(struct iwm_softc *sc, int qid, int idx, uint8_t sta_id,
3360 	uint16_t len)
3361 {
3362 	struct iwm_agn_scd_bc_tbl *scd_bc_tbl;
3363 	uint16_t w_val;
3364 
3365 	scd_bc_tbl = sc->sched_dma.vaddr;
3366 
3367 	len += 8; /* magic numbers came naturally from paris */
3368 	if (sc->sc_capaflags & IWM_UCODE_TLV_FLAGS_DW_BC_TABLE)
3369 		len = roundup(len, 4) / 4;
3370 
3371 	w_val = htole16(sta_id << 12 | len);
3372 
3373 	/* Update TX scheduler. */
3374 	scd_bc_tbl[qid].tfd_offset[idx] = w_val;
3375 	bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
3376 	    BUS_DMASYNC_PREWRITE);
3377 
3378 	/* I really wonder what this is ?!? */
3379 	if (idx < IWM_TFD_QUEUE_SIZE_BC_DUP) {
3380 		scd_bc_tbl[qid].tfd_offset[IWM_TFD_QUEUE_SIZE_MAX + idx] = w_val;
3381 		bus_dmamap_sync(sc->sched_dma.tag, sc->sched_dma.map,
3382 		    BUS_DMASYNC_PREWRITE);
3383 	}
3384 }
3385 #endif
3386 
3387 /*
3388  * Take an 802.11 (non-n) rate, find the relevant rate
3389  * table entry.  return the index into in_ridx[].
3390  *
3391  * The caller then uses that index back into in_ridx
3392  * to figure out the rate index programmed /into/
3393  * the firmware for this given node.
3394  */
3395 static int
3396 iwm_tx_rateidx_lookup(struct iwm_softc *sc, struct iwm_node *in,
3397     uint8_t rate)
3398 {
3399 	int i;
3400 	uint8_t r;
3401 
3402 	for (i = 0; i < nitems(in->in_ridx); i++) {
3403 		r = iwm_rates[in->in_ridx[i]].rate;
3404 		if (rate == r)
3405 			return (i);
3406 	}
3407 
3408 	IWM_DPRINTF(sc, IWM_DEBUG_XMIT | IWM_DEBUG_TXRATE,
3409 	    "%s: couldn't find an entry for rate=%d\n",
3410 	    __func__,
3411 	    rate);
3412 
3413 	/* XXX Return the first */
3414 	/* XXX TODO: have it return the /lowest/ */
3415 	return (0);
3416 }
3417 
3418 static int
3419 iwm_tx_rateidx_global_lookup(struct iwm_softc *sc, uint8_t rate)
3420 {
3421 	int i;
3422 
3423 	for (i = 0; i < nitems(iwm_rates); i++) {
3424 		if (iwm_rates[i].rate == rate)
3425 			return (i);
3426 	}
3427 	/* XXX error? */
3428 	IWM_DPRINTF(sc, IWM_DEBUG_XMIT | IWM_DEBUG_TXRATE,
3429 	    "%s: couldn't find an entry for rate=%d\n",
3430 	    __func__,
3431 	    rate);
3432 	return (0);
3433 }
3434 
3435 /*
3436  * Fill in the rate related information for a transmit command.
3437  */
3438 static const struct iwm_rate *
3439 iwm_tx_fill_cmd(struct iwm_softc *sc, struct iwm_node *in,
3440 	struct mbuf *m, struct iwm_tx_cmd *tx)
3441 {
3442 	struct ieee80211_node *ni = &in->in_ni;
3443 	struct ieee80211_frame *wh;
3444 	const struct ieee80211_txparam *tp = ni->ni_txparms;
3445 	const struct iwm_rate *rinfo;
3446 	int type;
3447 	int ridx, rate_flags;
3448 
3449 	wh = mtod(m, struct ieee80211_frame *);
3450 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
3451 
3452 	tx->rts_retry_limit = IWM_RTS_DFAULT_RETRY_LIMIT;
3453 	tx->data_retry_limit = IWM_DEFAULT_TX_RETRY;
3454 
3455 	if (type == IEEE80211_FC0_TYPE_MGT) {
3456 		ridx = iwm_tx_rateidx_global_lookup(sc, tp->mgmtrate);
3457 		IWM_DPRINTF(sc, IWM_DEBUG_TXRATE,
3458 		    "%s: MGT (%d)\n", __func__, tp->mgmtrate);
3459 	} else if (IEEE80211_IS_MULTICAST(wh->i_addr1)) {
3460 		ridx = iwm_tx_rateidx_global_lookup(sc, tp->mcastrate);
3461 		IWM_DPRINTF(sc, IWM_DEBUG_TXRATE,
3462 		    "%s: MCAST (%d)\n", __func__, tp->mcastrate);
3463 	} else if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE) {
3464 		ridx = iwm_tx_rateidx_global_lookup(sc, tp->ucastrate);
3465 		IWM_DPRINTF(sc, IWM_DEBUG_TXRATE,
3466 		    "%s: FIXED_RATE (%d)\n", __func__, tp->ucastrate);
3467 	} else if (m->m_flags & M_EAPOL) {
3468 		ridx = iwm_tx_rateidx_global_lookup(sc, tp->mgmtrate);
3469 		IWM_DPRINTF(sc, IWM_DEBUG_TXRATE,
3470 		    "%s: EAPOL\n", __func__);
3471 	} else if (type == IEEE80211_FC0_TYPE_DATA) {
3472 		int i;
3473 
3474 		/* for data frames, use RS table */
3475 		IWM_DPRINTF(sc, IWM_DEBUG_TXRATE, "%s: DATA\n", __func__);
3476 		/* XXX pass pktlen */
3477 		(void) ieee80211_ratectl_rate(ni, NULL, 0);
3478 		i = iwm_tx_rateidx_lookup(sc, in, ni->ni_txrate);
3479 		ridx = in->in_ridx[i];
3480 
3481 		/* This is the index into the programmed table */
3482 		tx->initial_rate_index = i;
3483 		tx->tx_flags |= htole32(IWM_TX_CMD_FLG_STA_RATE);
3484 
3485 		IWM_DPRINTF(sc, IWM_DEBUG_XMIT | IWM_DEBUG_TXRATE,
3486 		    "%s: start with i=%d, txrate %d\n",
3487 		    __func__, i, iwm_rates[ridx].rate);
3488 	} else {
3489 		ridx = iwm_tx_rateidx_global_lookup(sc, tp->mgmtrate);
3490 		IWM_DPRINTF(sc, IWM_DEBUG_TXRATE, "%s: DEFAULT (%d)\n",
3491 		    __func__, tp->mgmtrate);
3492 	}
3493 
3494 	IWM_DPRINTF(sc, IWM_DEBUG_XMIT | IWM_DEBUG_TXRATE,
3495 	    "%s: frame type=%d txrate %d\n",
3496 	        __func__, type, iwm_rates[ridx].rate);
3497 
3498 	rinfo = &iwm_rates[ridx];
3499 
3500 	IWM_DPRINTF(sc, IWM_DEBUG_TXRATE, "%s: ridx=%d; rate=%d, CCK=%d\n",
3501 	    __func__, ridx,
3502 	    rinfo->rate,
3503 	    !! (IWM_RIDX_IS_CCK(ridx))
3504 	    );
3505 
3506 	/* XXX TODO: hard-coded TX antenna? */
3507 	rate_flags = 1 << IWM_RATE_MCS_ANT_POS;
3508 	if (IWM_RIDX_IS_CCK(ridx))
3509 		rate_flags |= IWM_RATE_MCS_CCK_MSK;
3510 	tx->rate_n_flags = htole32(rate_flags | rinfo->plcp);
3511 
3512 	return rinfo;
3513 }
3514 
3515 #define TB0_SIZE 16
3516 static int
3517 iwm_tx(struct iwm_softc *sc, struct mbuf *m, struct ieee80211_node *ni, int ac)
3518 {
3519 	struct ieee80211com *ic = &sc->sc_ic;
3520 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3521 	struct iwm_node *in = IWM_NODE(ni);
3522 	struct iwm_tx_ring *ring;
3523 	struct iwm_tx_data *data;
3524 	struct iwm_tfd *desc;
3525 	struct iwm_device_cmd *cmd;
3526 	struct iwm_tx_cmd *tx;
3527 	struct ieee80211_frame *wh;
3528 	struct ieee80211_key *k = NULL;
3529 	struct mbuf *m1;
3530 	const struct iwm_rate *rinfo;
3531 	uint32_t flags;
3532 	u_int hdrlen;
3533 	bus_dma_segment_t *seg, segs[IWM_MAX_SCATTER];
3534 	int nsegs;
3535 	uint8_t tid, type;
3536 	int i, totlen, error, pad;
3537 
3538 	wh = mtod(m, struct ieee80211_frame *);
3539 	hdrlen = ieee80211_anyhdrsize(wh);
3540 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
3541 	tid = 0;
3542 	ring = &sc->txq[ac];
3543 	desc = &ring->desc[ring->cur];
3544 	memset(desc, 0, sizeof(*desc));
3545 	data = &ring->data[ring->cur];
3546 
3547 	/* Fill out iwm_tx_cmd to send to the firmware */
3548 	cmd = &ring->cmd[ring->cur];
3549 	cmd->hdr.code = IWM_TX_CMD;
3550 	cmd->hdr.flags = 0;
3551 	cmd->hdr.qid = ring->qid;
3552 	cmd->hdr.idx = ring->cur;
3553 
3554 	tx = (void *)cmd->data;
3555 	memset(tx, 0, sizeof(*tx));
3556 
3557 	rinfo = iwm_tx_fill_cmd(sc, in, m, tx);
3558 
3559 	/* Encrypt the frame if need be. */
3560 	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
3561 		/* Retrieve key for TX && do software encryption. */
3562 		k = ieee80211_crypto_encap(ni, m);
3563 		if (k == NULL) {
3564 			m_freem(m);
3565 			return (ENOBUFS);
3566 		}
3567 		/* 802.11 header may have moved. */
3568 		wh = mtod(m, struct ieee80211_frame *);
3569 	}
3570 
3571 	if (ieee80211_radiotap_active_vap(vap)) {
3572 		struct iwm_tx_radiotap_header *tap = &sc->sc_txtap;
3573 
3574 		tap->wt_flags = 0;
3575 		tap->wt_chan_freq = htole16(ni->ni_chan->ic_freq);
3576 		tap->wt_chan_flags = htole16(ni->ni_chan->ic_flags);
3577 		tap->wt_rate = rinfo->rate;
3578 		if (k != NULL)
3579 			tap->wt_flags |= IEEE80211_RADIOTAP_F_WEP;
3580 		ieee80211_radiotap_tx(vap, m);
3581 	}
3582 
3583 
3584 	totlen = m->m_pkthdr.len;
3585 
3586 	flags = 0;
3587 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
3588 		flags |= IWM_TX_CMD_FLG_ACK;
3589 	}
3590 
3591 	if (type == IEEE80211_FC0_TYPE_DATA
3592 	    && (totlen + IEEE80211_CRC_LEN > vap->iv_rtsthreshold)
3593 	    && !IEEE80211_IS_MULTICAST(wh->i_addr1)) {
3594 		flags |= IWM_TX_CMD_FLG_PROT_REQUIRE;
3595 	}
3596 
3597 	if (IEEE80211_IS_MULTICAST(wh->i_addr1) ||
3598 	    type != IEEE80211_FC0_TYPE_DATA)
3599 		tx->sta_id = sc->sc_aux_sta.sta_id;
3600 	else
3601 		tx->sta_id = IWM_STATION_ID;
3602 
3603 	if (type == IEEE80211_FC0_TYPE_MGT) {
3604 		uint8_t subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
3605 
3606 		if (subtype == IEEE80211_FC0_SUBTYPE_ASSOC_REQ ||
3607 		    subtype == IEEE80211_FC0_SUBTYPE_REASSOC_REQ) {
3608 			tx->pm_frame_timeout = htole16(IWM_PM_FRAME_ASSOC);
3609 		} else if (subtype == IEEE80211_FC0_SUBTYPE_ACTION) {
3610 			tx->pm_frame_timeout = htole16(IWM_PM_FRAME_NONE);
3611 		} else {
3612 			tx->pm_frame_timeout = htole16(IWM_PM_FRAME_MGMT);
3613 		}
3614 	} else {
3615 		tx->pm_frame_timeout = htole16(IWM_PM_FRAME_NONE);
3616 	}
3617 
3618 	if (hdrlen & 3) {
3619 		/* First segment length must be a multiple of 4. */
3620 		flags |= IWM_TX_CMD_FLG_MH_PAD;
3621 		pad = 4 - (hdrlen & 3);
3622 	} else
3623 		pad = 0;
3624 
3625 	tx->driver_txop = 0;
3626 	tx->next_frame_len = 0;
3627 
3628 	tx->len = htole16(totlen);
3629 	tx->tid_tspec = tid;
3630 	tx->life_time = htole32(IWM_TX_CMD_LIFE_TIME_INFINITE);
3631 
3632 	/* Set physical address of "scratch area". */
3633 	tx->dram_lsb_ptr = htole32(data->scratch_paddr);
3634 	tx->dram_msb_ptr = iwm_get_dma_hi_addr(data->scratch_paddr);
3635 
3636 	/* Copy 802.11 header in TX command. */
3637 	memcpy(((uint8_t *)tx) + sizeof(*tx), wh, hdrlen);
3638 
3639 	flags |= IWM_TX_CMD_FLG_BT_DIS | IWM_TX_CMD_FLG_SEQ_CTL;
3640 
3641 	tx->sec_ctl = 0;
3642 	tx->tx_flags |= htole32(flags);
3643 
3644 	/* Trim 802.11 header. */
3645 	m_adj(m, hdrlen);
3646 	error = bus_dmamap_load_mbuf_sg(ring->data_dmat, data->map, m,
3647 	    segs, &nsegs, BUS_DMA_NOWAIT);
3648 	if (error != 0) {
3649 		if (error != EFBIG) {
3650 			device_printf(sc->sc_dev, "can't map mbuf (error %d)\n",
3651 			    error);
3652 			m_freem(m);
3653 			return error;
3654 		}
3655 		/* Too many DMA segments, linearize mbuf. */
3656 		m1 = m_collapse(m, M_NOWAIT, IWM_MAX_SCATTER - 2);
3657 		if (m1 == NULL) {
3658 			device_printf(sc->sc_dev,
3659 			    "%s: could not defrag mbuf\n", __func__);
3660 			m_freem(m);
3661 			return (ENOBUFS);
3662 		}
3663 		m = m1;
3664 
3665 		error = bus_dmamap_load_mbuf_sg(ring->data_dmat, data->map, m,
3666 		    segs, &nsegs, BUS_DMA_NOWAIT);
3667 		if (error != 0) {
3668 			device_printf(sc->sc_dev, "can't map mbuf (error %d)\n",
3669 			    error);
3670 			m_freem(m);
3671 			return error;
3672 		}
3673 	}
3674 	data->m = m;
3675 	data->in = in;
3676 	data->done = 0;
3677 
3678 	IWM_DPRINTF(sc, IWM_DEBUG_XMIT,
3679 	    "sending txd %p, in %p\n", data, data->in);
3680 	KASSERT(data->in != NULL, ("node is NULL"));
3681 
3682 	IWM_DPRINTF(sc, IWM_DEBUG_XMIT,
3683 	    "sending data: qid=%d idx=%d len=%d nsegs=%d txflags=0x%08x rate_n_flags=0x%08x rateidx=%u\n",
3684 	    ring->qid, ring->cur, totlen, nsegs,
3685 	    le32toh(tx->tx_flags),
3686 	    le32toh(tx->rate_n_flags),
3687 	    tx->initial_rate_index
3688 	    );
3689 
3690 	/* Fill TX descriptor. */
3691 	desc->num_tbs = 2 + nsegs;
3692 
3693 	desc->tbs[0].lo = htole32(data->cmd_paddr);
3694 	desc->tbs[0].hi_n_len = htole16(iwm_get_dma_hi_addr(data->cmd_paddr)) |
3695 	    (TB0_SIZE << 4);
3696 	desc->tbs[1].lo = htole32(data->cmd_paddr + TB0_SIZE);
3697 	desc->tbs[1].hi_n_len = htole16(iwm_get_dma_hi_addr(data->cmd_paddr)) |
3698 	    ((sizeof(struct iwm_cmd_header) + sizeof(*tx)
3699 	      + hdrlen + pad - TB0_SIZE) << 4);
3700 
3701 	/* Other DMA segments are for data payload. */
3702 	for (i = 0; i < nsegs; i++) {
3703 		seg = &segs[i];
3704 		desc->tbs[i+2].lo = htole32(seg->ds_addr);
3705 		desc->tbs[i+2].hi_n_len = \
3706 		    htole16(iwm_get_dma_hi_addr(seg->ds_addr))
3707 		    | ((seg->ds_len) << 4);
3708 	}
3709 
3710 	bus_dmamap_sync(ring->data_dmat, data->map,
3711 	    BUS_DMASYNC_PREWRITE);
3712 	bus_dmamap_sync(ring->cmd_dma.tag, ring->cmd_dma.map,
3713 	    BUS_DMASYNC_PREWRITE);
3714 	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
3715 	    BUS_DMASYNC_PREWRITE);
3716 
3717 #if 0
3718 	iwm_update_sched(sc, ring->qid, ring->cur, tx->sta_id, le16toh(tx->len));
3719 #endif
3720 
3721 	/* Kick TX ring. */
3722 	ring->cur = (ring->cur + 1) % IWM_TX_RING_COUNT;
3723 	IWM_WRITE(sc, IWM_HBUS_TARG_WRPTR, ring->qid << 8 | ring->cur);
3724 
3725 	/* Mark TX ring as full if we reach a certain threshold. */
3726 	if (++ring->queued > IWM_TX_RING_HIMARK) {
3727 		sc->qfullmsk |= 1 << ring->qid;
3728 	}
3729 
3730 	return 0;
3731 }
3732 
3733 static int
3734 iwm_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
3735     const struct ieee80211_bpf_params *params)
3736 {
3737 	struct ieee80211com *ic = ni->ni_ic;
3738 	struct iwm_softc *sc = ic->ic_softc;
3739 	int error = 0;
3740 
3741 	IWM_DPRINTF(sc, IWM_DEBUG_XMIT,
3742 	    "->%s begin\n", __func__);
3743 
3744 	if ((sc->sc_flags & IWM_FLAG_HW_INITED) == 0) {
3745 		m_freem(m);
3746 		IWM_DPRINTF(sc, IWM_DEBUG_XMIT,
3747 		    "<-%s not RUNNING\n", __func__);
3748 		return (ENETDOWN);
3749         }
3750 
3751 	IWM_LOCK(sc);
3752 	/* XXX fix this */
3753         if (params == NULL) {
3754 		error = iwm_tx(sc, m, ni, 0);
3755 	} else {
3756 		error = iwm_tx(sc, m, ni, 0);
3757 	}
3758 	sc->sc_tx_timer = 5;
3759 	IWM_UNLOCK(sc);
3760 
3761         return (error);
3762 }
3763 
3764 /*
3765  * mvm/tx.c
3766  */
3767 
3768 /*
3769  * Note that there are transports that buffer frames before they reach
3770  * the firmware. This means that after flush_tx_path is called, the
3771  * queue might not be empty. The race-free way to handle this is to:
3772  * 1) set the station as draining
3773  * 2) flush the Tx path
3774  * 3) wait for the transport queues to be empty
3775  */
3776 int
3777 iwm_mvm_flush_tx_path(struct iwm_softc *sc, uint32_t tfd_msk, uint32_t flags)
3778 {
3779 	int ret;
3780 	struct iwm_tx_path_flush_cmd flush_cmd = {
3781 		.queues_ctl = htole32(tfd_msk),
3782 		.flush_ctl = htole16(IWM_DUMP_TX_FIFO_FLUSH),
3783 	};
3784 
3785 	ret = iwm_mvm_send_cmd_pdu(sc, IWM_TXPATH_FLUSH, flags,
3786 	    sizeof(flush_cmd), &flush_cmd);
3787 	if (ret)
3788                 device_printf(sc->sc_dev,
3789 		    "Flushing tx queue failed: %d\n", ret);
3790 	return ret;
3791 }
3792 
3793 /*
3794  * BEGIN mvm/sta.c
3795  */
3796 
3797 static int
3798 iwm_mvm_send_add_sta_cmd_status(struct iwm_softc *sc,
3799 	struct iwm_mvm_add_sta_cmd_v7 *cmd, int *status)
3800 {
3801 	return iwm_mvm_send_cmd_pdu_status(sc, IWM_ADD_STA, sizeof(*cmd),
3802 	    cmd, status);
3803 }
3804 
3805 /* send station add/update command to firmware */
3806 static int
3807 iwm_mvm_sta_send_to_fw(struct iwm_softc *sc, struct iwm_node *in, int update)
3808 {
3809 	struct iwm_mvm_add_sta_cmd_v7 add_sta_cmd;
3810 	int ret;
3811 	uint32_t status;
3812 
3813 	memset(&add_sta_cmd, 0, sizeof(add_sta_cmd));
3814 
3815 	add_sta_cmd.sta_id = IWM_STATION_ID;
3816 	add_sta_cmd.mac_id_n_color
3817 	    = htole32(IWM_FW_CMD_ID_AND_COLOR(IWM_DEFAULT_MACID,
3818 	        IWM_DEFAULT_COLOR));
3819 	if (!update) {
3820 		int ac;
3821 		for (ac = 0; ac < WME_NUM_AC; ac++) {
3822 			add_sta_cmd.tfd_queue_msk |=
3823 			    htole32(1 << iwm_mvm_ac_to_tx_fifo[ac]);
3824 		}
3825 		IEEE80211_ADDR_COPY(&add_sta_cmd.addr, in->in_ni.ni_bssid);
3826 	}
3827 	add_sta_cmd.add_modify = update ? 1 : 0;
3828 	add_sta_cmd.station_flags_msk
3829 	    |= htole32(IWM_STA_FLG_FAT_EN_MSK | IWM_STA_FLG_MIMO_EN_MSK);
3830 	add_sta_cmd.tid_disable_tx = htole16(0xffff);
3831 	if (update)
3832 		add_sta_cmd.modify_mask |= (IWM_STA_MODIFY_TID_DISABLE_TX);
3833 
3834 	status = IWM_ADD_STA_SUCCESS;
3835 	ret = iwm_mvm_send_add_sta_cmd_status(sc, &add_sta_cmd, &status);
3836 	if (ret)
3837 		return ret;
3838 
3839 	switch (status) {
3840 	case IWM_ADD_STA_SUCCESS:
3841 		break;
3842 	default:
3843 		ret = EIO;
3844 		device_printf(sc->sc_dev, "IWM_ADD_STA failed\n");
3845 		break;
3846 	}
3847 
3848 	return ret;
3849 }
3850 
3851 static int
3852 iwm_mvm_add_sta(struct iwm_softc *sc, struct iwm_node *in)
3853 {
3854 	return iwm_mvm_sta_send_to_fw(sc, in, 0);
3855 }
3856 
3857 static int
3858 iwm_mvm_update_sta(struct iwm_softc *sc, struct iwm_node *in)
3859 {
3860 	return iwm_mvm_sta_send_to_fw(sc, in, 1);
3861 }
3862 
3863 static int
3864 iwm_mvm_add_int_sta_common(struct iwm_softc *sc, struct iwm_int_sta *sta,
3865 	const uint8_t *addr, uint16_t mac_id, uint16_t color)
3866 {
3867 	struct iwm_mvm_add_sta_cmd_v7 cmd;
3868 	int ret;
3869 	uint32_t status;
3870 
3871 	memset(&cmd, 0, sizeof(cmd));
3872 	cmd.sta_id = sta->sta_id;
3873 	cmd.mac_id_n_color = htole32(IWM_FW_CMD_ID_AND_COLOR(mac_id, color));
3874 
3875 	cmd.tfd_queue_msk = htole32(sta->tfd_queue_msk);
3876 	cmd.tid_disable_tx = htole16(0xffff);
3877 
3878 	if (addr)
3879 		IEEE80211_ADDR_COPY(cmd.addr, addr);
3880 
3881 	ret = iwm_mvm_send_add_sta_cmd_status(sc, &cmd, &status);
3882 	if (ret)
3883 		return ret;
3884 
3885 	switch (status) {
3886 	case IWM_ADD_STA_SUCCESS:
3887 		IWM_DPRINTF(sc, IWM_DEBUG_RESET,
3888 		    "%s: Internal station added.\n", __func__);
3889 		return 0;
3890 	default:
3891 		device_printf(sc->sc_dev,
3892 		    "%s: Add internal station failed, status=0x%x\n",
3893 		    __func__, status);
3894 		ret = EIO;
3895 		break;
3896 	}
3897 	return ret;
3898 }
3899 
3900 static int
3901 iwm_mvm_add_aux_sta(struct iwm_softc *sc)
3902 {
3903 	int ret;
3904 
3905 	sc->sc_aux_sta.sta_id = IWM_AUX_STA_ID;
3906 	sc->sc_aux_sta.tfd_queue_msk = (1 << IWM_MVM_AUX_QUEUE);
3907 
3908 	ret = iwm_enable_txq(sc, 0, IWM_MVM_AUX_QUEUE, IWM_MVM_TX_FIFO_MCAST);
3909 	if (ret)
3910 		return ret;
3911 
3912 	ret = iwm_mvm_add_int_sta_common(sc,
3913 	    &sc->sc_aux_sta, NULL, IWM_MAC_INDEX_AUX, 0);
3914 
3915 	if (ret)
3916 		memset(&sc->sc_aux_sta, 0, sizeof(sc->sc_aux_sta));
3917 	return ret;
3918 }
3919 
3920 /*
3921  * END mvm/sta.c
3922  */
3923 
3924 /*
3925  * BEGIN mvm/quota.c
3926  */
3927 
3928 static int
3929 iwm_mvm_update_quotas(struct iwm_softc *sc, struct iwm_node *in)
3930 {
3931 	struct iwm_time_quota_cmd cmd;
3932 	int i, idx, ret, num_active_macs, quota, quota_rem;
3933 	int colors[IWM_MAX_BINDINGS] = { -1, -1, -1, -1, };
3934 	int n_ifs[IWM_MAX_BINDINGS] = {0, };
3935 	uint16_t id;
3936 
3937 	memset(&cmd, 0, sizeof(cmd));
3938 
3939 	/* currently, PHY ID == binding ID */
3940 	if (in) {
3941 		id = in->in_phyctxt->id;
3942 		KASSERT(id < IWM_MAX_BINDINGS, ("invalid id"));
3943 		colors[id] = in->in_phyctxt->color;
3944 
3945 		if (1)
3946 			n_ifs[id] = 1;
3947 	}
3948 
3949 	/*
3950 	 * The FW's scheduling session consists of
3951 	 * IWM_MVM_MAX_QUOTA fragments. Divide these fragments
3952 	 * equally between all the bindings that require quota
3953 	 */
3954 	num_active_macs = 0;
3955 	for (i = 0; i < IWM_MAX_BINDINGS; i++) {
3956 		cmd.quotas[i].id_and_color = htole32(IWM_FW_CTXT_INVALID);
3957 		num_active_macs += n_ifs[i];
3958 	}
3959 
3960 	quota = 0;
3961 	quota_rem = 0;
3962 	if (num_active_macs) {
3963 		quota = IWM_MVM_MAX_QUOTA / num_active_macs;
3964 		quota_rem = IWM_MVM_MAX_QUOTA % num_active_macs;
3965 	}
3966 
3967 	for (idx = 0, i = 0; i < IWM_MAX_BINDINGS; i++) {
3968 		if (colors[i] < 0)
3969 			continue;
3970 
3971 		cmd.quotas[idx].id_and_color =
3972 			htole32(IWM_FW_CMD_ID_AND_COLOR(i, colors[i]));
3973 
3974 		if (n_ifs[i] <= 0) {
3975 			cmd.quotas[idx].quota = htole32(0);
3976 			cmd.quotas[idx].max_duration = htole32(0);
3977 		} else {
3978 			cmd.quotas[idx].quota = htole32(quota * n_ifs[i]);
3979 			cmd.quotas[idx].max_duration = htole32(0);
3980 		}
3981 		idx++;
3982 	}
3983 
3984 	/* Give the remainder of the session to the first binding */
3985 	cmd.quotas[0].quota = htole32(le32toh(cmd.quotas[0].quota) + quota_rem);
3986 
3987 	ret = iwm_mvm_send_cmd_pdu(sc, IWM_TIME_QUOTA_CMD, IWM_CMD_SYNC,
3988 	    sizeof(cmd), &cmd);
3989 	if (ret)
3990 		device_printf(sc->sc_dev,
3991 		    "%s: Failed to send quota: %d\n", __func__, ret);
3992 	return ret;
3993 }
3994 
3995 /*
3996  * END mvm/quota.c
3997  */
3998 
3999 /*
4000  * ieee80211 routines
4001  */
4002 
4003 /*
4004  * Change to AUTH state in 80211 state machine.  Roughly matches what
4005  * Linux does in bss_info_changed().
4006  */
4007 static int
4008 iwm_auth(struct ieee80211vap *vap, struct iwm_softc *sc)
4009 {
4010 	struct ieee80211_node *ni;
4011 	struct iwm_node *in;
4012 	struct iwm_vap *iv = IWM_VAP(vap);
4013 	uint32_t duration;
4014 	int error;
4015 
4016 	/*
4017 	 * XXX i have a feeling that the vap node is being
4018 	 * freed from underneath us. Grr.
4019 	 */
4020 	ni = ieee80211_ref_node(vap->iv_bss);
4021 	in = IWM_NODE(ni);
4022 	IWM_DPRINTF(sc, IWM_DEBUG_RESET | IWM_DEBUG_STATE,
4023 	    "%s: called; vap=%p, bss ni=%p\n",
4024 	    __func__,
4025 	    vap,
4026 	    ni);
4027 
4028 	in->in_assoc = 0;
4029 
4030 	error = iwm_mvm_sf_config(sc, IWM_SF_FULL_ON);
4031 	if (error != 0)
4032 		return error;
4033 
4034 	error = iwm_allow_mcast(vap, sc);
4035 	if (error) {
4036 		device_printf(sc->sc_dev,
4037 		    "%s: failed to set multicast\n", __func__);
4038 		goto out;
4039 	}
4040 
4041 	/*
4042 	 * This is where it deviates from what Linux does.
4043 	 *
4044 	 * Linux iwlwifi doesn't reset the nic each time, nor does it
4045 	 * call ctxt_add() here.  Instead, it adds it during vap creation,
4046 	 * and always does a mac_ctx_changed().
4047 	 *
4048 	 * The openbsd port doesn't attempt to do that - it reset things
4049 	 * at odd states and does the add here.
4050 	 *
4051 	 * So, until the state handling is fixed (ie, we never reset
4052 	 * the NIC except for a firmware failure, which should drag
4053 	 * the NIC back to IDLE, re-setup and re-add all the mac/phy
4054 	 * contexts that are required), let's do a dirty hack here.
4055 	 */
4056 	if (iv->is_uploaded) {
4057 		if ((error = iwm_mvm_mac_ctxt_changed(sc, vap)) != 0) {
4058 			device_printf(sc->sc_dev,
4059 			    "%s: failed to update MAC\n", __func__);
4060 			goto out;
4061 		}
4062 		if ((error = iwm_mvm_phy_ctxt_changed(sc, &sc->sc_phyctxt[0],
4063 		    in->in_ni.ni_chan, 1, 1)) != 0) {
4064 			device_printf(sc->sc_dev,
4065 			    "%s: failed update phy ctxt\n", __func__);
4066 			goto out;
4067 		}
4068 		in->in_phyctxt = &sc->sc_phyctxt[0];
4069 
4070 		if ((error = iwm_mvm_binding_update(sc, in)) != 0) {
4071 			device_printf(sc->sc_dev,
4072 			    "%s: binding update cmd\n", __func__);
4073 			goto out;
4074 		}
4075 		if ((error = iwm_mvm_update_sta(sc, in)) != 0) {
4076 			device_printf(sc->sc_dev,
4077 			    "%s: failed to update sta\n", __func__);
4078 			goto out;
4079 		}
4080 	} else {
4081 		if ((error = iwm_mvm_mac_ctxt_add(sc, vap)) != 0) {
4082 			device_printf(sc->sc_dev,
4083 			    "%s: failed to add MAC\n", __func__);
4084 			goto out;
4085 		}
4086 		if ((error = iwm_mvm_phy_ctxt_changed(sc, &sc->sc_phyctxt[0],
4087 		    in->in_ni.ni_chan, 1, 1)) != 0) {
4088 			device_printf(sc->sc_dev,
4089 			    "%s: failed add phy ctxt!\n", __func__);
4090 			error = ETIMEDOUT;
4091 			goto out;
4092 		}
4093 		in->in_phyctxt = &sc->sc_phyctxt[0];
4094 
4095 		if ((error = iwm_mvm_binding_add_vif(sc, in)) != 0) {
4096 			device_printf(sc->sc_dev,
4097 			    "%s: binding add cmd\n", __func__);
4098 			goto out;
4099 		}
4100 		if ((error = iwm_mvm_add_sta(sc, in)) != 0) {
4101 			device_printf(sc->sc_dev,
4102 			    "%s: failed to add sta\n", __func__);
4103 			goto out;
4104 		}
4105 	}
4106 
4107 	/*
4108 	 * Prevent the FW from wandering off channel during association
4109 	 * by "protecting" the session with a time event.
4110 	 */
4111 	/* XXX duration is in units of TU, not MS */
4112 	duration = IWM_MVM_TE_SESSION_PROTECTION_MAX_TIME_MS;
4113 	iwm_mvm_protect_session(sc, in, duration, 500 /* XXX magic number */);
4114 	DELAY(100);
4115 
4116 	error = 0;
4117 out:
4118 	ieee80211_free_node(ni);
4119 	return (error);
4120 }
4121 
4122 static int
4123 iwm_assoc(struct ieee80211vap *vap, struct iwm_softc *sc)
4124 {
4125 	struct iwm_node *in = IWM_NODE(vap->iv_bss);
4126 	int error;
4127 
4128 	if ((error = iwm_mvm_update_sta(sc, in)) != 0) {
4129 		device_printf(sc->sc_dev,
4130 		    "%s: failed to update STA\n", __func__);
4131 		return error;
4132 	}
4133 
4134 	in->in_assoc = 1;
4135 	if ((error = iwm_mvm_mac_ctxt_changed(sc, vap)) != 0) {
4136 		device_printf(sc->sc_dev,
4137 		    "%s: failed to update MAC\n", __func__);
4138 		return error;
4139 	}
4140 
4141 	return 0;
4142 }
4143 
4144 static int
4145 iwm_release(struct iwm_softc *sc, struct iwm_node *in)
4146 {
4147 	uint32_t tfd_msk;
4148 
4149 	/*
4150 	 * Ok, so *technically* the proper set of calls for going
4151 	 * from RUN back to SCAN is:
4152 	 *
4153 	 * iwm_mvm_power_mac_disable(sc, in);
4154 	 * iwm_mvm_mac_ctxt_changed(sc, in);
4155 	 * iwm_mvm_rm_sta(sc, in);
4156 	 * iwm_mvm_update_quotas(sc, NULL);
4157 	 * iwm_mvm_mac_ctxt_changed(sc, in);
4158 	 * iwm_mvm_binding_remove_vif(sc, in);
4159 	 * iwm_mvm_mac_ctxt_remove(sc, in);
4160 	 *
4161 	 * However, that freezes the device not matter which permutations
4162 	 * and modifications are attempted.  Obviously, this driver is missing
4163 	 * something since it works in the Linux driver, but figuring out what
4164 	 * is missing is a little more complicated.  Now, since we're going
4165 	 * back to nothing anyway, we'll just do a complete device reset.
4166 	 * Up your's, device!
4167 	 */
4168 	/*
4169 	 * Just using 0xf for the queues mask is fine as long as we only
4170 	 * get here from RUN state.
4171 	 */
4172 	tfd_msk = 0xf;
4173 	mbufq_drain(&sc->sc_snd);
4174 	iwm_mvm_flush_tx_path(sc, tfd_msk, IWM_CMD_SYNC);
4175 	/*
4176 	 * We seem to get away with just synchronously sending the
4177 	 * IWM_TXPATH_FLUSH command.
4178 	 */
4179 //	iwm_trans_wait_tx_queue_empty(sc, tfd_msk);
4180 	iwm_stop_device(sc);
4181 	iwm_init_hw(sc);
4182 	if (in)
4183 		in->in_assoc = 0;
4184 	return 0;
4185 
4186 #if 0
4187 	int error;
4188 
4189 	iwm_mvm_power_mac_disable(sc, in);
4190 
4191 	if ((error = iwm_mvm_mac_ctxt_changed(sc, in)) != 0) {
4192 		device_printf(sc->sc_dev, "mac ctxt change fail 1 %d\n", error);
4193 		return error;
4194 	}
4195 
4196 	if ((error = iwm_mvm_rm_sta(sc, in)) != 0) {
4197 		device_printf(sc->sc_dev, "sta remove fail %d\n", error);
4198 		return error;
4199 	}
4200 	error = iwm_mvm_rm_sta(sc, in);
4201 	in->in_assoc = 0;
4202 	iwm_mvm_update_quotas(sc, NULL);
4203 	if ((error = iwm_mvm_mac_ctxt_changed(sc, in)) != 0) {
4204 		device_printf(sc->sc_dev, "mac ctxt change fail 2 %d\n", error);
4205 		return error;
4206 	}
4207 	iwm_mvm_binding_remove_vif(sc, in);
4208 
4209 	iwm_mvm_mac_ctxt_remove(sc, in);
4210 
4211 	return error;
4212 #endif
4213 }
4214 
4215 static struct ieee80211_node *
4216 iwm_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
4217 {
4218 	return malloc(sizeof (struct iwm_node), M_80211_NODE,
4219 	    M_NOWAIT | M_ZERO);
4220 }
4221 
4222 static void
4223 iwm_setrates(struct iwm_softc *sc, struct iwm_node *in)
4224 {
4225 	struct ieee80211_node *ni = &in->in_ni;
4226 	struct iwm_lq_cmd *lq = &in->in_lq;
4227 	int nrates = ni->ni_rates.rs_nrates;
4228 	int i, ridx, tab = 0;
4229 //	int txant = 0;
4230 
4231 	if (nrates > nitems(lq->rs_table)) {
4232 		device_printf(sc->sc_dev,
4233 		    "%s: node supports %d rates, driver handles "
4234 		    "only %zu\n", __func__, nrates, nitems(lq->rs_table));
4235 		return;
4236 	}
4237 	if (nrates == 0) {
4238 		device_printf(sc->sc_dev,
4239 		    "%s: node supports 0 rates, odd!\n", __func__);
4240 		return;
4241 	}
4242 
4243 	/*
4244 	 * XXX .. and most of iwm_node is not initialised explicitly;
4245 	 * it's all just 0x0 passed to the firmware.
4246 	 */
4247 
4248 	/* first figure out which rates we should support */
4249 	/* XXX TODO: this isn't 11n aware /at all/ */
4250 	memset(&in->in_ridx, -1, sizeof(in->in_ridx));
4251 	IWM_DPRINTF(sc, IWM_DEBUG_TXRATE,
4252 	    "%s: nrates=%d\n", __func__, nrates);
4253 
4254 	/*
4255 	 * Loop over nrates and populate in_ridx from the highest
4256 	 * rate to the lowest rate.  Remember, in_ridx[] has
4257 	 * IEEE80211_RATE_MAXSIZE entries!
4258 	 */
4259 	for (i = 0; i < min(nrates, IEEE80211_RATE_MAXSIZE); i++) {
4260 		int rate = ni->ni_rates.rs_rates[(nrates - 1) - i] & IEEE80211_RATE_VAL;
4261 
4262 		/* Map 802.11 rate to HW rate index. */
4263 		for (ridx = 0; ridx <= IWM_RIDX_MAX; ridx++)
4264 			if (iwm_rates[ridx].rate == rate)
4265 				break;
4266 		if (ridx > IWM_RIDX_MAX) {
4267 			device_printf(sc->sc_dev,
4268 			    "%s: WARNING: device rate for %d not found!\n",
4269 			    __func__, rate);
4270 		} else {
4271 			IWM_DPRINTF(sc, IWM_DEBUG_TXRATE,
4272 			    "%s: rate: i: %d, rate=%d, ridx=%d\n",
4273 			    __func__,
4274 			    i,
4275 			    rate,
4276 			    ridx);
4277 			in->in_ridx[i] = ridx;
4278 		}
4279 	}
4280 
4281 	/* then construct a lq_cmd based on those */
4282 	memset(lq, 0, sizeof(*lq));
4283 	lq->sta_id = IWM_STATION_ID;
4284 
4285 	/* For HT, always enable RTS/CTS to avoid excessive retries. */
4286 	if (ni->ni_flags & IEEE80211_NODE_HT)
4287 		lq->flags |= IWM_LQ_FLAG_USE_RTS_MSK;
4288 
4289 	/*
4290 	 * are these used? (we don't do SISO or MIMO)
4291 	 * need to set them to non-zero, though, or we get an error.
4292 	 */
4293 	lq->single_stream_ant_msk = 1;
4294 	lq->dual_stream_ant_msk = 1;
4295 
4296 	/*
4297 	 * Build the actual rate selection table.
4298 	 * The lowest bits are the rates.  Additionally,
4299 	 * CCK needs bit 9 to be set.  The rest of the bits
4300 	 * we add to the table select the tx antenna
4301 	 * Note that we add the rates in the highest rate first
4302 	 * (opposite of ni_rates).
4303 	 */
4304 	/*
4305 	 * XXX TODO: this should be looping over the min of nrates
4306 	 * and LQ_MAX_RETRY_NUM.  Sigh.
4307 	 */
4308 	for (i = 0; i < nrates; i++) {
4309 		int nextant;
4310 
4311 #if 0
4312 		if (txant == 0)
4313 			txant = iwm_mvm_get_valid_tx_ant(sc);
4314 		nextant = 1<<(ffs(txant)-1);
4315 		txant &= ~nextant;
4316 #else
4317 		nextant = iwm_mvm_get_valid_tx_ant(sc);
4318 #endif
4319 		/*
4320 		 * Map the rate id into a rate index into
4321 		 * our hardware table containing the
4322 		 * configuration to use for this rate.
4323 		 */
4324 		ridx = in->in_ridx[i];
4325 		tab = iwm_rates[ridx].plcp;
4326 		tab |= nextant << IWM_RATE_MCS_ANT_POS;
4327 		if (IWM_RIDX_IS_CCK(ridx))
4328 			tab |= IWM_RATE_MCS_CCK_MSK;
4329 		IWM_DPRINTF(sc, IWM_DEBUG_TXRATE,
4330 		    "station rate i=%d, rate=%d, hw=%x\n",
4331 		    i, iwm_rates[ridx].rate, tab);
4332 		lq->rs_table[i] = htole32(tab);
4333 	}
4334 	/* then fill the rest with the lowest possible rate */
4335 	for (i = nrates; i < nitems(lq->rs_table); i++) {
4336 		KASSERT(tab != 0, ("invalid tab"));
4337 		lq->rs_table[i] = htole32(tab);
4338 	}
4339 }
4340 
4341 static int
4342 iwm_media_change(struct ifnet *ifp)
4343 {
4344 	struct ieee80211vap *vap = ifp->if_softc;
4345 	struct ieee80211com *ic = vap->iv_ic;
4346 	struct iwm_softc *sc = ic->ic_softc;
4347 	int error;
4348 
4349 	error = ieee80211_media_change(ifp);
4350 	if (error != ENETRESET)
4351 		return error;
4352 
4353 	IWM_LOCK(sc);
4354 	if (ic->ic_nrunning > 0) {
4355 		iwm_stop(sc);
4356 		iwm_init(sc);
4357 	}
4358 	IWM_UNLOCK(sc);
4359 	return error;
4360 }
4361 
4362 
4363 static int
4364 iwm_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
4365 {
4366 	struct iwm_vap *ivp = IWM_VAP(vap);
4367 	struct ieee80211com *ic = vap->iv_ic;
4368 	struct iwm_softc *sc = ic->ic_softc;
4369 	struct iwm_node *in;
4370 	int error;
4371 
4372 	IWM_DPRINTF(sc, IWM_DEBUG_STATE,
4373 	    "switching state %s -> %s\n",
4374 	    ieee80211_state_name[vap->iv_state],
4375 	    ieee80211_state_name[nstate]);
4376 	IEEE80211_UNLOCK(ic);
4377 	IWM_LOCK(sc);
4378 
4379 	if (vap->iv_state == IEEE80211_S_SCAN && nstate != vap->iv_state)
4380 		iwm_led_blink_stop(sc);
4381 
4382 	/* disable beacon filtering if we're hopping out of RUN */
4383 	if (vap->iv_state == IEEE80211_S_RUN && nstate != vap->iv_state) {
4384 		iwm_mvm_disable_beacon_filter(sc);
4385 
4386 		if (((in = IWM_NODE(vap->iv_bss)) != NULL))
4387 			in->in_assoc = 0;
4388 
4389 		if (nstate == IEEE80211_S_INIT) {
4390 			IWM_UNLOCK(sc);
4391 			IEEE80211_LOCK(ic);
4392 			error = ivp->iv_newstate(vap, nstate, arg);
4393 			IEEE80211_UNLOCK(ic);
4394 			IWM_LOCK(sc);
4395 			iwm_release(sc, NULL);
4396 			IWM_UNLOCK(sc);
4397 			IEEE80211_LOCK(ic);
4398 			return error;
4399 		}
4400 
4401 		/*
4402 		 * It's impossible to directly go RUN->SCAN. If we iwm_release()
4403 		 * above then the card will be completely reinitialized,
4404 		 * so the driver must do everything necessary to bring the card
4405 		 * from INIT to SCAN.
4406 		 *
4407 		 * Additionally, upon receiving deauth frame from AP,
4408 		 * OpenBSD 802.11 stack puts the driver in IEEE80211_S_AUTH
4409 		 * state. This will also fail with this driver, so bring the FSM
4410 		 * from IEEE80211_S_RUN to IEEE80211_S_SCAN in this case as well.
4411 		 *
4412 		 * XXX TODO: fix this for FreeBSD!
4413 		 */
4414 		if (nstate == IEEE80211_S_SCAN ||
4415 		    nstate == IEEE80211_S_AUTH ||
4416 		    nstate == IEEE80211_S_ASSOC) {
4417 			IWM_DPRINTF(sc, IWM_DEBUG_STATE,
4418 			    "Force transition to INIT; MGT=%d\n", arg);
4419 			IWM_UNLOCK(sc);
4420 			IEEE80211_LOCK(ic);
4421 			/* Always pass arg as -1 since we can't Tx right now. */
4422 			/*
4423 			 * XXX arg is just ignored anyway when transitioning
4424 			 *     to IEEE80211_S_INIT.
4425 			 */
4426 			vap->iv_newstate(vap, IEEE80211_S_INIT, -1);
4427 			IWM_DPRINTF(sc, IWM_DEBUG_STATE,
4428 			    "Going INIT->SCAN\n");
4429 			nstate = IEEE80211_S_SCAN;
4430 			IEEE80211_UNLOCK(ic);
4431 			IWM_LOCK(sc);
4432 		}
4433 	}
4434 
4435 	switch (nstate) {
4436 	case IEEE80211_S_INIT:
4437 		break;
4438 
4439 	case IEEE80211_S_AUTH:
4440 		if ((error = iwm_auth(vap, sc)) != 0) {
4441 			device_printf(sc->sc_dev,
4442 			    "%s: could not move to auth state: %d\n",
4443 			    __func__, error);
4444 			break;
4445 		}
4446 		break;
4447 
4448 	case IEEE80211_S_ASSOC:
4449 		if ((error = iwm_assoc(vap, sc)) != 0) {
4450 			device_printf(sc->sc_dev,
4451 			    "%s: failed to associate: %d\n", __func__,
4452 			    error);
4453 			break;
4454 		}
4455 		break;
4456 
4457 	case IEEE80211_S_RUN:
4458 	{
4459 		struct iwm_host_cmd cmd = {
4460 			.id = IWM_LQ_CMD,
4461 			.len = { sizeof(in->in_lq), },
4462 			.flags = IWM_CMD_SYNC,
4463 		};
4464 
4465 		/* Update the association state, now we have it all */
4466 		/* (eg associd comes in at this point */
4467 		error = iwm_assoc(vap, sc);
4468 		if (error != 0) {
4469 			device_printf(sc->sc_dev,
4470 			    "%s: failed to update association state: %d\n",
4471 			    __func__,
4472 			    error);
4473 			break;
4474 		}
4475 
4476 		in = IWM_NODE(vap->iv_bss);
4477 		iwm_mvm_power_mac_update_mode(sc, in);
4478 		iwm_mvm_enable_beacon_filter(sc, in);
4479 		iwm_mvm_update_quotas(sc, in);
4480 		iwm_setrates(sc, in);
4481 
4482 		cmd.data[0] = &in->in_lq;
4483 		if ((error = iwm_send_cmd(sc, &cmd)) != 0) {
4484 			device_printf(sc->sc_dev,
4485 			    "%s: IWM_LQ_CMD failed\n", __func__);
4486 		}
4487 
4488 		iwm_mvm_led_enable(sc);
4489 		break;
4490 	}
4491 
4492 	default:
4493 		break;
4494 	}
4495 	IWM_UNLOCK(sc);
4496 	IEEE80211_LOCK(ic);
4497 
4498 	return (ivp->iv_newstate(vap, nstate, arg));
4499 }
4500 
4501 void
4502 iwm_endscan_cb(void *arg, int pending)
4503 {
4504 	struct iwm_softc *sc = arg;
4505 	struct ieee80211com *ic = &sc->sc_ic;
4506 
4507 	IWM_DPRINTF(sc, IWM_DEBUG_SCAN | IWM_DEBUG_TRACE,
4508 	    "%s: scan ended\n",
4509 	    __func__);
4510 
4511 	ieee80211_scan_done(TAILQ_FIRST(&ic->ic_vaps));
4512 }
4513 
4514 /*
4515  * Aging and idle timeouts for the different possible scenarios
4516  * in default configuration
4517  */
4518 static const uint32_t
4519 iwm_sf_full_timeout_def[IWM_SF_NUM_SCENARIO][IWM_SF_NUM_TIMEOUT_TYPES] = {
4520 	{
4521 		htole32(IWM_SF_SINGLE_UNICAST_AGING_TIMER_DEF),
4522 		htole32(IWM_SF_SINGLE_UNICAST_IDLE_TIMER_DEF)
4523 	},
4524 	{
4525 		htole32(IWM_SF_AGG_UNICAST_AGING_TIMER_DEF),
4526 		htole32(IWM_SF_AGG_UNICAST_IDLE_TIMER_DEF)
4527 	},
4528 	{
4529 		htole32(IWM_SF_MCAST_AGING_TIMER_DEF),
4530 		htole32(IWM_SF_MCAST_IDLE_TIMER_DEF)
4531 	},
4532 	{
4533 		htole32(IWM_SF_BA_AGING_TIMER_DEF),
4534 		htole32(IWM_SF_BA_IDLE_TIMER_DEF)
4535 	},
4536 	{
4537 		htole32(IWM_SF_TX_RE_AGING_TIMER_DEF),
4538 		htole32(IWM_SF_TX_RE_IDLE_TIMER_DEF)
4539 	},
4540 };
4541 
4542 /*
4543  * Aging and idle timeouts for the different possible scenarios
4544  * in single BSS MAC configuration.
4545  */
4546 static const uint32_t
4547 iwm_sf_full_timeout[IWM_SF_NUM_SCENARIO][IWM_SF_NUM_TIMEOUT_TYPES] = {
4548 	{
4549 		htole32(IWM_SF_SINGLE_UNICAST_AGING_TIMER),
4550 		htole32(IWM_SF_SINGLE_UNICAST_IDLE_TIMER)
4551 	},
4552 	{
4553 		htole32(IWM_SF_AGG_UNICAST_AGING_TIMER),
4554 		htole32(IWM_SF_AGG_UNICAST_IDLE_TIMER)
4555 	},
4556 	{
4557 		htole32(IWM_SF_MCAST_AGING_TIMER),
4558 		htole32(IWM_SF_MCAST_IDLE_TIMER)
4559 	},
4560 	{
4561 		htole32(IWM_SF_BA_AGING_TIMER),
4562 		htole32(IWM_SF_BA_IDLE_TIMER)
4563 	},
4564 	{
4565 		htole32(IWM_SF_TX_RE_AGING_TIMER),
4566 		htole32(IWM_SF_TX_RE_IDLE_TIMER)
4567 	},
4568 };
4569 
4570 static void
4571 iwm_mvm_fill_sf_command(struct iwm_softc *sc, struct iwm_sf_cfg_cmd *sf_cmd,
4572     struct ieee80211_node *ni)
4573 {
4574 	int i, j, watermark;
4575 
4576 	sf_cmd->watermark[IWM_SF_LONG_DELAY_ON] = htole32(IWM_SF_W_MARK_SCAN);
4577 
4578 	/*
4579 	 * If we are in association flow - check antenna configuration
4580 	 * capabilities of the AP station, and choose the watermark accordingly.
4581 	 */
4582 	if (ni) {
4583 		if (ni->ni_flags & IEEE80211_NODE_HT) {
4584 #ifdef notyet
4585 			if (ni->ni_rxmcs[2] != 0)
4586 				watermark = IWM_SF_W_MARK_MIMO3;
4587 			else if (ni->ni_rxmcs[1] != 0)
4588 				watermark = IWM_SF_W_MARK_MIMO2;
4589 			else
4590 #endif
4591 				watermark = IWM_SF_W_MARK_SISO;
4592 		} else {
4593 			watermark = IWM_SF_W_MARK_LEGACY;
4594 		}
4595 	/* default watermark value for unassociated mode. */
4596 	} else {
4597 		watermark = IWM_SF_W_MARK_MIMO2;
4598 	}
4599 	sf_cmd->watermark[IWM_SF_FULL_ON] = htole32(watermark);
4600 
4601 	for (i = 0; i < IWM_SF_NUM_SCENARIO; i++) {
4602 		for (j = 0; j < IWM_SF_NUM_TIMEOUT_TYPES; j++) {
4603 			sf_cmd->long_delay_timeouts[i][j] =
4604 					htole32(IWM_SF_LONG_DELAY_AGING_TIMER);
4605 		}
4606 	}
4607 
4608 	if (ni) {
4609 		memcpy(sf_cmd->full_on_timeouts, iwm_sf_full_timeout,
4610 		       sizeof(iwm_sf_full_timeout));
4611 	} else {
4612 		memcpy(sf_cmd->full_on_timeouts, iwm_sf_full_timeout_def,
4613 		       sizeof(iwm_sf_full_timeout_def));
4614 	}
4615 }
4616 
4617 static int
4618 iwm_mvm_sf_config(struct iwm_softc *sc, enum iwm_sf_state new_state)
4619 {
4620 	struct ieee80211com *ic = &sc->sc_ic;
4621 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
4622 	struct iwm_sf_cfg_cmd sf_cmd = {
4623 		.state = htole32(IWM_SF_FULL_ON),
4624 	};
4625 	int ret = 0;
4626 
4627 	if (sc->cfg->device_family == IWM_DEVICE_FAMILY_8000)
4628 		sf_cmd.state |= htole32(IWM_SF_CFG_DUMMY_NOTIF_OFF);
4629 
4630 	switch (new_state) {
4631 	case IWM_SF_UNINIT:
4632 	case IWM_SF_INIT_OFF:
4633 		iwm_mvm_fill_sf_command(sc, &sf_cmd, NULL);
4634 		break;
4635 	case IWM_SF_FULL_ON:
4636 		iwm_mvm_fill_sf_command(sc, &sf_cmd, vap->iv_bss);
4637 		break;
4638 	default:
4639 		IWM_DPRINTF(sc, IWM_DEBUG_PWRSAVE,
4640 		    "Invalid state: %d. not sending Smart Fifo cmd\n",
4641 			  new_state);
4642 		return EINVAL;
4643 	}
4644 
4645 	ret = iwm_mvm_send_cmd_pdu(sc, IWM_REPLY_SF_CFG_CMD, IWM_CMD_ASYNC,
4646 				   sizeof(sf_cmd), &sf_cmd);
4647 	return ret;
4648 }
4649 
4650 static int
4651 iwm_send_bt_init_conf(struct iwm_softc *sc)
4652 {
4653 	struct iwm_bt_coex_cmd bt_cmd;
4654 
4655 	bt_cmd.mode = htole32(IWM_BT_COEX_WIFI);
4656 	bt_cmd.enabled_modules = htole32(IWM_BT_COEX_HIGH_BAND_RET);
4657 
4658 	return iwm_mvm_send_cmd_pdu(sc, IWM_BT_CONFIG, 0, sizeof(bt_cmd),
4659 	    &bt_cmd);
4660 }
4661 
4662 static int
4663 iwm_send_update_mcc_cmd(struct iwm_softc *sc, const char *alpha2)
4664 {
4665 	struct iwm_mcc_update_cmd mcc_cmd;
4666 	struct iwm_host_cmd hcmd = {
4667 		.id = IWM_MCC_UPDATE_CMD,
4668 		.flags = (IWM_CMD_SYNC | IWM_CMD_WANT_SKB),
4669 		.data = { &mcc_cmd },
4670 	};
4671 	int ret;
4672 #ifdef IWM_DEBUG
4673 	struct iwm_rx_packet *pkt;
4674 	struct iwm_mcc_update_resp_v1 *mcc_resp_v1 = NULL;
4675 	struct iwm_mcc_update_resp *mcc_resp;
4676 	int n_channels;
4677 	uint16_t mcc;
4678 #endif
4679 	int resp_v2 = isset(sc->sc_enabled_capa,
4680 	    IWM_UCODE_TLV_CAPA_LAR_SUPPORT_V2);
4681 
4682 	memset(&mcc_cmd, 0, sizeof(mcc_cmd));
4683 	mcc_cmd.mcc = htole16(alpha2[0] << 8 | alpha2[1]);
4684 	if ((sc->sc_ucode_api & IWM_UCODE_TLV_API_WIFI_MCC_UPDATE) ||
4685 	    isset(sc->sc_enabled_capa, IWM_UCODE_TLV_CAPA_LAR_MULTI_MCC))
4686 		mcc_cmd.source_id = IWM_MCC_SOURCE_GET_CURRENT;
4687 	else
4688 		mcc_cmd.source_id = IWM_MCC_SOURCE_OLD_FW;
4689 
4690 	if (resp_v2)
4691 		hcmd.len[0] = sizeof(struct iwm_mcc_update_cmd);
4692 	else
4693 		hcmd.len[0] = sizeof(struct iwm_mcc_update_cmd_v1);
4694 
4695 	IWM_DPRINTF(sc, IWM_DEBUG_NODE,
4696 	    "send MCC update to FW with '%c%c' src = %d\n",
4697 	    alpha2[0], alpha2[1], mcc_cmd.source_id);
4698 
4699 	ret = iwm_send_cmd(sc, &hcmd);
4700 	if (ret)
4701 		return ret;
4702 
4703 #ifdef IWM_DEBUG
4704 	pkt = hcmd.resp_pkt;
4705 
4706 	/* Extract MCC response */
4707 	if (resp_v2) {
4708 		mcc_resp = (void *)pkt->data;
4709 		mcc = mcc_resp->mcc;
4710 		n_channels =  le32toh(mcc_resp->n_channels);
4711 	} else {
4712 		mcc_resp_v1 = (void *)pkt->data;
4713 		mcc = mcc_resp_v1->mcc;
4714 		n_channels =  le32toh(mcc_resp_v1->n_channels);
4715 	}
4716 
4717 	/* W/A for a FW/NVM issue - returns 0x00 for the world domain */
4718 	if (mcc == 0)
4719 		mcc = 0x3030;  /* "00" - world */
4720 
4721 	IWM_DPRINTF(sc, IWM_DEBUG_NODE,
4722 	    "regulatory domain '%c%c' (%d channels available)\n",
4723 	    mcc >> 8, mcc & 0xff, n_channels);
4724 #endif
4725 	iwm_free_resp(sc, &hcmd);
4726 
4727 	return 0;
4728 }
4729 
4730 static void
4731 iwm_mvm_tt_tx_backoff(struct iwm_softc *sc, uint32_t backoff)
4732 {
4733 	struct iwm_host_cmd cmd = {
4734 		.id = IWM_REPLY_THERMAL_MNG_BACKOFF,
4735 		.len = { sizeof(uint32_t), },
4736 		.data = { &backoff, },
4737 	};
4738 
4739 	if (iwm_send_cmd(sc, &cmd) != 0) {
4740 		device_printf(sc->sc_dev,
4741 		    "failed to change thermal tx backoff\n");
4742 	}
4743 }
4744 
4745 static int
4746 iwm_init_hw(struct iwm_softc *sc)
4747 {
4748 	struct ieee80211com *ic = &sc->sc_ic;
4749 	int error, i, ac;
4750 
4751 	if ((error = iwm_start_hw(sc)) != 0) {
4752 		printf("iwm_start_hw: failed %d\n", error);
4753 		return error;
4754 	}
4755 
4756 	if ((error = iwm_run_init_mvm_ucode(sc, 0)) != 0) {
4757 		printf("iwm_run_init_mvm_ucode: failed %d\n", error);
4758 		return error;
4759 	}
4760 
4761 	/*
4762 	 * should stop and start HW since that INIT
4763 	 * image just loaded
4764 	 */
4765 	iwm_stop_device(sc);
4766 	if ((error = iwm_start_hw(sc)) != 0) {
4767 		device_printf(sc->sc_dev, "could not initialize hardware\n");
4768 		return error;
4769 	}
4770 
4771 	/* omstart, this time with the regular firmware */
4772 	error = iwm_mvm_load_ucode_wait_alive(sc, IWM_UCODE_REGULAR);
4773 	if (error) {
4774 		device_printf(sc->sc_dev, "could not load firmware\n");
4775 		goto error;
4776 	}
4777 
4778 	if ((error = iwm_send_bt_init_conf(sc)) != 0) {
4779 		device_printf(sc->sc_dev, "bt init conf failed\n");
4780 		goto error;
4781 	}
4782 
4783 	error = iwm_send_tx_ant_cfg(sc, iwm_mvm_get_valid_tx_ant(sc));
4784 	if (error != 0) {
4785 		device_printf(sc->sc_dev, "antenna config failed\n");
4786 		goto error;
4787 	}
4788 
4789 	/* Send phy db control command and then phy db calibration */
4790 	if ((error = iwm_send_phy_db_data(sc->sc_phy_db)) != 0)
4791 		goto error;
4792 
4793 	if ((error = iwm_send_phy_cfg_cmd(sc)) != 0) {
4794 		device_printf(sc->sc_dev, "phy_cfg_cmd failed\n");
4795 		goto error;
4796 	}
4797 
4798 	/* Add auxiliary station for scanning */
4799 	if ((error = iwm_mvm_add_aux_sta(sc)) != 0) {
4800 		device_printf(sc->sc_dev, "add_aux_sta failed\n");
4801 		goto error;
4802 	}
4803 
4804 	for (i = 0; i < IWM_NUM_PHY_CTX; i++) {
4805 		/*
4806 		 * The channel used here isn't relevant as it's
4807 		 * going to be overwritten in the other flows.
4808 		 * For now use the first channel we have.
4809 		 */
4810 		if ((error = iwm_mvm_phy_ctxt_add(sc,
4811 		    &sc->sc_phyctxt[i], &ic->ic_channels[1], 1, 1)) != 0)
4812 			goto error;
4813 	}
4814 
4815 	/* Initialize tx backoffs to the minimum. */
4816 	if (sc->cfg->device_family == IWM_DEVICE_FAMILY_7000)
4817 		iwm_mvm_tt_tx_backoff(sc, 0);
4818 
4819 	error = iwm_mvm_power_update_device(sc);
4820 	if (error)
4821 		goto error;
4822 
4823 	if (isset(sc->sc_enabled_capa, IWM_UCODE_TLV_CAPA_LAR_SUPPORT)) {
4824 		if ((error = iwm_send_update_mcc_cmd(sc, "ZZ")) != 0)
4825 			goto error;
4826 	}
4827 
4828 	if (isset(sc->sc_enabled_capa, IWM_UCODE_TLV_CAPA_UMAC_SCAN)) {
4829 		if ((error = iwm_mvm_config_umac_scan(sc)) != 0)
4830 			goto error;
4831 	}
4832 
4833 	/* Enable Tx queues. */
4834 	for (ac = 0; ac < WME_NUM_AC; ac++) {
4835 		error = iwm_enable_txq(sc, IWM_STATION_ID, ac,
4836 		    iwm_mvm_ac_to_tx_fifo[ac]);
4837 		if (error)
4838 			goto error;
4839 	}
4840 
4841 	if ((error = iwm_mvm_disable_beacon_filter(sc)) != 0) {
4842 		device_printf(sc->sc_dev, "failed to disable beacon filter\n");
4843 		goto error;
4844 	}
4845 
4846 	return 0;
4847 
4848  error:
4849 	iwm_stop_device(sc);
4850 	return error;
4851 }
4852 
4853 /* Allow multicast from our BSSID. */
4854 static int
4855 iwm_allow_mcast(struct ieee80211vap *vap, struct iwm_softc *sc)
4856 {
4857 	struct ieee80211_node *ni = vap->iv_bss;
4858 	struct iwm_mcast_filter_cmd *cmd;
4859 	size_t size;
4860 	int error;
4861 
4862 	size = roundup(sizeof(*cmd), 4);
4863 	cmd = malloc(size, M_DEVBUF, M_NOWAIT | M_ZERO);
4864 	if (cmd == NULL)
4865 		return ENOMEM;
4866 	cmd->filter_own = 1;
4867 	cmd->port_id = 0;
4868 	cmd->count = 0;
4869 	cmd->pass_all = 1;
4870 	IEEE80211_ADDR_COPY(cmd->bssid, ni->ni_bssid);
4871 
4872 	error = iwm_mvm_send_cmd_pdu(sc, IWM_MCAST_FILTER_CMD,
4873 	    IWM_CMD_SYNC, size, cmd);
4874 	free(cmd, M_DEVBUF);
4875 
4876 	return (error);
4877 }
4878 
4879 /*
4880  * ifnet interfaces
4881  */
4882 
4883 static void
4884 iwm_init(struct iwm_softc *sc)
4885 {
4886 	int error;
4887 
4888 	if (sc->sc_flags & IWM_FLAG_HW_INITED) {
4889 		return;
4890 	}
4891 	sc->sc_generation++;
4892 	sc->sc_flags &= ~IWM_FLAG_STOPPED;
4893 
4894 	if ((error = iwm_init_hw(sc)) != 0) {
4895 		printf("iwm_init_hw failed %d\n", error);
4896 		iwm_stop(sc);
4897 		return;
4898 	}
4899 
4900 	/*
4901 	 * Ok, firmware loaded and we are jogging
4902 	 */
4903 	sc->sc_flags |= IWM_FLAG_HW_INITED;
4904 	callout_reset(&sc->sc_watchdog_to, hz, iwm_watchdog, sc);
4905 }
4906 
4907 static int
4908 iwm_transmit(struct ieee80211com *ic, struct mbuf *m)
4909 {
4910 	struct iwm_softc *sc;
4911 	int error;
4912 
4913 	sc = ic->ic_softc;
4914 
4915 	IWM_LOCK(sc);
4916 	if ((sc->sc_flags & IWM_FLAG_HW_INITED) == 0) {
4917 		IWM_UNLOCK(sc);
4918 		return (ENXIO);
4919 	}
4920 	error = mbufq_enqueue(&sc->sc_snd, m);
4921 	if (error) {
4922 		IWM_UNLOCK(sc);
4923 		return (error);
4924 	}
4925 	iwm_start(sc);
4926 	IWM_UNLOCK(sc);
4927 	return (0);
4928 }
4929 
4930 /*
4931  * Dequeue packets from sendq and call send.
4932  */
4933 static void
4934 iwm_start(struct iwm_softc *sc)
4935 {
4936 	struct ieee80211_node *ni;
4937 	struct mbuf *m;
4938 	int ac = 0;
4939 
4940 	IWM_DPRINTF(sc, IWM_DEBUG_XMIT | IWM_DEBUG_TRACE, "->%s\n", __func__);
4941 	while (sc->qfullmsk == 0 &&
4942 		(m = mbufq_dequeue(&sc->sc_snd)) != NULL) {
4943 		ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
4944 		if (iwm_tx(sc, m, ni, ac) != 0) {
4945 			if_inc_counter(ni->ni_vap->iv_ifp,
4946 			    IFCOUNTER_OERRORS, 1);
4947 			ieee80211_free_node(ni);
4948 			continue;
4949 		}
4950 		sc->sc_tx_timer = 15;
4951 	}
4952 	IWM_DPRINTF(sc, IWM_DEBUG_XMIT | IWM_DEBUG_TRACE, "<-%s\n", __func__);
4953 }
4954 
4955 static void
4956 iwm_stop(struct iwm_softc *sc)
4957 {
4958 
4959 	sc->sc_flags &= ~IWM_FLAG_HW_INITED;
4960 	sc->sc_flags |= IWM_FLAG_STOPPED;
4961 	sc->sc_generation++;
4962 	iwm_led_blink_stop(sc);
4963 	sc->sc_tx_timer = 0;
4964 	iwm_stop_device(sc);
4965 }
4966 
4967 static void
4968 iwm_watchdog(void *arg)
4969 {
4970 	struct iwm_softc *sc = arg;
4971 	struct ieee80211com *ic = &sc->sc_ic;
4972 
4973 	if (sc->sc_tx_timer > 0) {
4974 		if (--sc->sc_tx_timer == 0) {
4975 			device_printf(sc->sc_dev, "device timeout\n");
4976 #ifdef IWM_DEBUG
4977 			iwm_nic_error(sc);
4978 #endif
4979 			ieee80211_restart_all(ic);
4980 			counter_u64_add(sc->sc_ic.ic_oerrors, 1);
4981 			return;
4982 		}
4983 	}
4984 	callout_reset(&sc->sc_watchdog_to, hz, iwm_watchdog, sc);
4985 }
4986 
4987 static void
4988 iwm_parent(struct ieee80211com *ic)
4989 {
4990 	struct iwm_softc *sc = ic->ic_softc;
4991 	int startall = 0;
4992 
4993 	IWM_LOCK(sc);
4994 	if (ic->ic_nrunning > 0) {
4995 		if (!(sc->sc_flags & IWM_FLAG_HW_INITED)) {
4996 			iwm_init(sc);
4997 			startall = 1;
4998 		}
4999 	} else if (sc->sc_flags & IWM_FLAG_HW_INITED)
5000 		iwm_stop(sc);
5001 	IWM_UNLOCK(sc);
5002 	if (startall)
5003 		ieee80211_start_all(ic);
5004 }
5005 
5006 /*
5007  * The interrupt side of things
5008  */
5009 
5010 /*
5011  * error dumping routines are from iwlwifi/mvm/utils.c
5012  */
5013 
5014 /*
5015  * Note: This structure is read from the device with IO accesses,
5016  * and the reading already does the endian conversion. As it is
5017  * read with uint32_t-sized accesses, any members with a different size
5018  * need to be ordered correctly though!
5019  */
5020 struct iwm_error_event_table {
5021 	uint32_t valid;		/* (nonzero) valid, (0) log is empty */
5022 	uint32_t error_id;		/* type of error */
5023 	uint32_t trm_hw_status0;	/* TRM HW status */
5024 	uint32_t trm_hw_status1;	/* TRM HW status */
5025 	uint32_t blink2;		/* branch link */
5026 	uint32_t ilink1;		/* interrupt link */
5027 	uint32_t ilink2;		/* interrupt link */
5028 	uint32_t data1;		/* error-specific data */
5029 	uint32_t data2;		/* error-specific data */
5030 	uint32_t data3;		/* error-specific data */
5031 	uint32_t bcon_time;		/* beacon timer */
5032 	uint32_t tsf_low;		/* network timestamp function timer */
5033 	uint32_t tsf_hi;		/* network timestamp function timer */
5034 	uint32_t gp1;		/* GP1 timer register */
5035 	uint32_t gp2;		/* GP2 timer register */
5036 	uint32_t fw_rev_type;	/* firmware revision type */
5037 	uint32_t major;		/* uCode version major */
5038 	uint32_t minor;		/* uCode version minor */
5039 	uint32_t hw_ver;		/* HW Silicon version */
5040 	uint32_t brd_ver;		/* HW board version */
5041 	uint32_t log_pc;		/* log program counter */
5042 	uint32_t frame_ptr;		/* frame pointer */
5043 	uint32_t stack_ptr;		/* stack pointer */
5044 	uint32_t hcmd;		/* last host command header */
5045 	uint32_t isr0;		/* isr status register LMPM_NIC_ISR0:
5046 				 * rxtx_flag */
5047 	uint32_t isr1;		/* isr status register LMPM_NIC_ISR1:
5048 				 * host_flag */
5049 	uint32_t isr2;		/* isr status register LMPM_NIC_ISR2:
5050 				 * enc_flag */
5051 	uint32_t isr3;		/* isr status register LMPM_NIC_ISR3:
5052 				 * time_flag */
5053 	uint32_t isr4;		/* isr status register LMPM_NIC_ISR4:
5054 				 * wico interrupt */
5055 	uint32_t last_cmd_id;	/* last HCMD id handled by the firmware */
5056 	uint32_t wait_event;		/* wait event() caller address */
5057 	uint32_t l2p_control;	/* L2pControlField */
5058 	uint32_t l2p_duration;	/* L2pDurationField */
5059 	uint32_t l2p_mhvalid;	/* L2pMhValidBits */
5060 	uint32_t l2p_addr_match;	/* L2pAddrMatchStat */
5061 	uint32_t lmpm_pmg_sel;	/* indicate which clocks are turned on
5062 				 * (LMPM_PMG_SEL) */
5063 	uint32_t u_timestamp;	/* indicate when the date and time of the
5064 				 * compilation */
5065 	uint32_t flow_handler;	/* FH read/write pointers, RX credit */
5066 } __packed /* LOG_ERROR_TABLE_API_S_VER_3 */;
5067 
5068 /*
5069  * UMAC error struct - relevant starting from family 8000 chip.
5070  * Note: This structure is read from the device with IO accesses,
5071  * and the reading already does the endian conversion. As it is
5072  * read with u32-sized accesses, any members with a different size
5073  * need to be ordered correctly though!
5074  */
5075 struct iwm_umac_error_event_table {
5076 	uint32_t valid;		/* (nonzero) valid, (0) log is empty */
5077 	uint32_t error_id;	/* type of error */
5078 	uint32_t blink1;	/* branch link */
5079 	uint32_t blink2;	/* branch link */
5080 	uint32_t ilink1;	/* interrupt link */
5081 	uint32_t ilink2;	/* interrupt link */
5082 	uint32_t data1;		/* error-specific data */
5083 	uint32_t data2;		/* error-specific data */
5084 	uint32_t data3;		/* error-specific data */
5085 	uint32_t umac_major;
5086 	uint32_t umac_minor;
5087 	uint32_t frame_pointer;	/* core register 27*/
5088 	uint32_t stack_pointer;	/* core register 28 */
5089 	uint32_t cmd_header;	/* latest host cmd sent to UMAC */
5090 	uint32_t nic_isr_pref;	/* ISR status register */
5091 } __packed;
5092 
5093 #define ERROR_START_OFFSET  (1 * sizeof(uint32_t))
5094 #define ERROR_ELEM_SIZE     (7 * sizeof(uint32_t))
5095 
5096 #ifdef IWM_DEBUG
5097 struct {
5098 	const char *name;
5099 	uint8_t num;
5100 } advanced_lookup[] = {
5101 	{ "NMI_INTERRUPT_WDG", 0x34 },
5102 	{ "SYSASSERT", 0x35 },
5103 	{ "UCODE_VERSION_MISMATCH", 0x37 },
5104 	{ "BAD_COMMAND", 0x38 },
5105 	{ "NMI_INTERRUPT_DATA_ACTION_PT", 0x3C },
5106 	{ "FATAL_ERROR", 0x3D },
5107 	{ "NMI_TRM_HW_ERR", 0x46 },
5108 	{ "NMI_INTERRUPT_TRM", 0x4C },
5109 	{ "NMI_INTERRUPT_BREAK_POINT", 0x54 },
5110 	{ "NMI_INTERRUPT_WDG_RXF_FULL", 0x5C },
5111 	{ "NMI_INTERRUPT_WDG_NO_RBD_RXF_FULL", 0x64 },
5112 	{ "NMI_INTERRUPT_HOST", 0x66 },
5113 	{ "NMI_INTERRUPT_ACTION_PT", 0x7C },
5114 	{ "NMI_INTERRUPT_UNKNOWN", 0x84 },
5115 	{ "NMI_INTERRUPT_INST_ACTION_PT", 0x86 },
5116 	{ "ADVANCED_SYSASSERT", 0 },
5117 };
5118 
5119 static const char *
5120 iwm_desc_lookup(uint32_t num)
5121 {
5122 	int i;
5123 
5124 	for (i = 0; i < nitems(advanced_lookup) - 1; i++)
5125 		if (advanced_lookup[i].num == num)
5126 			return advanced_lookup[i].name;
5127 
5128 	/* No entry matches 'num', so it is the last: ADVANCED_SYSASSERT */
5129 	return advanced_lookup[i].name;
5130 }
5131 
5132 static void
5133 iwm_nic_umac_error(struct iwm_softc *sc)
5134 {
5135 	struct iwm_umac_error_event_table table;
5136 	uint32_t base;
5137 
5138 	base = sc->sc_uc.uc_umac_error_event_table;
5139 
5140 	if (base < 0x800000) {
5141 		device_printf(sc->sc_dev, "Invalid error log pointer 0x%08x\n",
5142 		    base);
5143 		return;
5144 	}
5145 
5146 	if (iwm_read_mem(sc, base, &table, sizeof(table)/sizeof(uint32_t))) {
5147 		device_printf(sc->sc_dev, "reading errlog failed\n");
5148 		return;
5149 	}
5150 
5151 	if (ERROR_START_OFFSET <= table.valid * ERROR_ELEM_SIZE) {
5152 		device_printf(sc->sc_dev, "Start UMAC Error Log Dump:\n");
5153 		device_printf(sc->sc_dev, "Status: 0x%x, count: %d\n",
5154 		    sc->sc_flags, table.valid);
5155 	}
5156 
5157 	device_printf(sc->sc_dev, "0x%08X | %s\n", table.error_id,
5158 		iwm_desc_lookup(table.error_id));
5159 	device_printf(sc->sc_dev, "0x%08X | umac branchlink1\n", table.blink1);
5160 	device_printf(sc->sc_dev, "0x%08X | umac branchlink2\n", table.blink2);
5161 	device_printf(sc->sc_dev, "0x%08X | umac interruptlink1\n",
5162 	    table.ilink1);
5163 	device_printf(sc->sc_dev, "0x%08X | umac interruptlink2\n",
5164 	    table.ilink2);
5165 	device_printf(sc->sc_dev, "0x%08X | umac data1\n", table.data1);
5166 	device_printf(sc->sc_dev, "0x%08X | umac data2\n", table.data2);
5167 	device_printf(sc->sc_dev, "0x%08X | umac data3\n", table.data3);
5168 	device_printf(sc->sc_dev, "0x%08X | umac major\n", table.umac_major);
5169 	device_printf(sc->sc_dev, "0x%08X | umac minor\n", table.umac_minor);
5170 	device_printf(sc->sc_dev, "0x%08X | frame pointer\n",
5171 	    table.frame_pointer);
5172 	device_printf(sc->sc_dev, "0x%08X | stack pointer\n",
5173 	    table.stack_pointer);
5174 	device_printf(sc->sc_dev, "0x%08X | last host cmd\n", table.cmd_header);
5175 	device_printf(sc->sc_dev, "0x%08X | isr status reg\n",
5176 	    table.nic_isr_pref);
5177 }
5178 
5179 /*
5180  * Support for dumping the error log seemed like a good idea ...
5181  * but it's mostly hex junk and the only sensible thing is the
5182  * hw/ucode revision (which we know anyway).  Since it's here,
5183  * I'll just leave it in, just in case e.g. the Intel guys want to
5184  * help us decipher some "ADVANCED_SYSASSERT" later.
5185  */
5186 static void
5187 iwm_nic_error(struct iwm_softc *sc)
5188 {
5189 	struct iwm_error_event_table table;
5190 	uint32_t base;
5191 
5192 	device_printf(sc->sc_dev, "dumping device error log\n");
5193 	base = sc->sc_uc.uc_error_event_table;
5194 	if (base < 0x800000) {
5195 		device_printf(sc->sc_dev,
5196 		    "Invalid error log pointer 0x%08x\n", base);
5197 		return;
5198 	}
5199 
5200 	if (iwm_read_mem(sc, base, &table, sizeof(table)/sizeof(uint32_t))) {
5201 		device_printf(sc->sc_dev, "reading errlog failed\n");
5202 		return;
5203 	}
5204 
5205 	if (!table.valid) {
5206 		device_printf(sc->sc_dev, "errlog not found, skipping\n");
5207 		return;
5208 	}
5209 
5210 	if (ERROR_START_OFFSET <= table.valid * ERROR_ELEM_SIZE) {
5211 		device_printf(sc->sc_dev, "Start Error Log Dump:\n");
5212 		device_printf(sc->sc_dev, "Status: 0x%x, count: %d\n",
5213 		    sc->sc_flags, table.valid);
5214 	}
5215 
5216 	device_printf(sc->sc_dev, "0x%08X | %-28s\n", table.error_id,
5217 	    iwm_desc_lookup(table.error_id));
5218 	device_printf(sc->sc_dev, "%08X | trm_hw_status0\n",
5219 	    table.trm_hw_status0);
5220 	device_printf(sc->sc_dev, "%08X | trm_hw_status1\n",
5221 	    table.trm_hw_status1);
5222 	device_printf(sc->sc_dev, "%08X | branchlink2\n", table.blink2);
5223 	device_printf(sc->sc_dev, "%08X | interruptlink1\n", table.ilink1);
5224 	device_printf(sc->sc_dev, "%08X | interruptlink2\n", table.ilink2);
5225 	device_printf(sc->sc_dev, "%08X | data1\n", table.data1);
5226 	device_printf(sc->sc_dev, "%08X | data2\n", table.data2);
5227 	device_printf(sc->sc_dev, "%08X | data3\n", table.data3);
5228 	device_printf(sc->sc_dev, "%08X | beacon time\n", table.bcon_time);
5229 	device_printf(sc->sc_dev, "%08X | tsf low\n", table.tsf_low);
5230 	device_printf(sc->sc_dev, "%08X | tsf hi\n", table.tsf_hi);
5231 	device_printf(sc->sc_dev, "%08X | time gp1\n", table.gp1);
5232 	device_printf(sc->sc_dev, "%08X | time gp2\n", table.gp2);
5233 	device_printf(sc->sc_dev, "%08X | uCode revision type\n",
5234 	    table.fw_rev_type);
5235 	device_printf(sc->sc_dev, "%08X | uCode version major\n", table.major);
5236 	device_printf(sc->sc_dev, "%08X | uCode version minor\n", table.minor);
5237 	device_printf(sc->sc_dev, "%08X | hw version\n", table.hw_ver);
5238 	device_printf(sc->sc_dev, "%08X | board version\n", table.brd_ver);
5239 	device_printf(sc->sc_dev, "%08X | hcmd\n", table.hcmd);
5240 	device_printf(sc->sc_dev, "%08X | isr0\n", table.isr0);
5241 	device_printf(sc->sc_dev, "%08X | isr1\n", table.isr1);
5242 	device_printf(sc->sc_dev, "%08X | isr2\n", table.isr2);
5243 	device_printf(sc->sc_dev, "%08X | isr3\n", table.isr3);
5244 	device_printf(sc->sc_dev, "%08X | isr4\n", table.isr4);
5245 	device_printf(sc->sc_dev, "%08X | last cmd Id\n", table.last_cmd_id);
5246 	device_printf(sc->sc_dev, "%08X | wait_event\n", table.wait_event);
5247 	device_printf(sc->sc_dev, "%08X | l2p_control\n", table.l2p_control);
5248 	device_printf(sc->sc_dev, "%08X | l2p_duration\n", table.l2p_duration);
5249 	device_printf(sc->sc_dev, "%08X | l2p_mhvalid\n", table.l2p_mhvalid);
5250 	device_printf(sc->sc_dev, "%08X | l2p_addr_match\n", table.l2p_addr_match);
5251 	device_printf(sc->sc_dev, "%08X | lmpm_pmg_sel\n", table.lmpm_pmg_sel);
5252 	device_printf(sc->sc_dev, "%08X | timestamp\n", table.u_timestamp);
5253 	device_printf(sc->sc_dev, "%08X | flow_handler\n", table.flow_handler);
5254 
5255 	if (sc->sc_uc.uc_umac_error_event_table)
5256 		iwm_nic_umac_error(sc);
5257 }
5258 #endif
5259 
5260 #define ADVANCE_RXQ(sc) (sc->rxq.cur = (sc->rxq.cur + 1) % IWM_RX_RING_COUNT);
5261 
5262 /*
5263  * Process an IWM_CSR_INT_BIT_FH_RX or IWM_CSR_INT_BIT_SW_RX interrupt.
5264  * Basic structure from if_iwn
5265  */
5266 static void
5267 iwm_notif_intr(struct iwm_softc *sc)
5268 {
5269 	struct ieee80211com *ic = &sc->sc_ic;
5270 	uint16_t hw;
5271 
5272 	bus_dmamap_sync(sc->rxq.stat_dma.tag, sc->rxq.stat_dma.map,
5273 	    BUS_DMASYNC_POSTREAD);
5274 
5275 	hw = le16toh(sc->rxq.stat->closed_rb_num) & 0xfff;
5276 
5277 	/*
5278 	 * Process responses
5279 	 */
5280 	while (sc->rxq.cur != hw) {
5281 		struct iwm_rx_ring *ring = &sc->rxq;
5282 		struct iwm_rx_data *data = &ring->data[ring->cur];
5283 		struct iwm_rx_packet *pkt;
5284 		struct iwm_cmd_response *cresp;
5285 		int qid, idx, code;
5286 
5287 		bus_dmamap_sync(ring->data_dmat, data->map,
5288 		    BUS_DMASYNC_POSTREAD);
5289 		pkt = mtod(data->m, struct iwm_rx_packet *);
5290 
5291 		qid = pkt->hdr.qid & ~0x80;
5292 		idx = pkt->hdr.idx;
5293 
5294 		code = IWM_WIDE_ID(pkt->hdr.flags, pkt->hdr.code);
5295 		IWM_DPRINTF(sc, IWM_DEBUG_INTR,
5296 		    "rx packet qid=%d idx=%d type=%x %d %d\n",
5297 		    pkt->hdr.qid & ~0x80, pkt->hdr.idx, code, ring->cur, hw);
5298 
5299 		/*
5300 		 * randomly get these from the firmware, no idea why.
5301 		 * they at least seem harmless, so just ignore them for now
5302 		 */
5303 		if (__predict_false((pkt->hdr.code == 0 && qid == 0 && idx == 0)
5304 		    || pkt->len_n_flags == htole32(0x55550000))) {
5305 			ADVANCE_RXQ(sc);
5306 			continue;
5307 		}
5308 
5309 		iwm_notification_wait_notify(sc->sc_notif_wait, code, pkt);
5310 
5311 		switch (code) {
5312 		case IWM_REPLY_RX_PHY_CMD:
5313 			iwm_mvm_rx_rx_phy_cmd(sc, pkt, data);
5314 			break;
5315 
5316 		case IWM_REPLY_RX_MPDU_CMD:
5317 			iwm_mvm_rx_rx_mpdu(sc, pkt, data);
5318 			break;
5319 
5320 		case IWM_TX_CMD:
5321 			iwm_mvm_rx_tx_cmd(sc, pkt, data);
5322 			break;
5323 
5324 		case IWM_MISSED_BEACONS_NOTIFICATION: {
5325 			struct iwm_missed_beacons_notif *resp;
5326 			int missed;
5327 
5328 			/* XXX look at mac_id to determine interface ID */
5329 			struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
5330 
5331 			resp = (void *)pkt->data;
5332 			missed = le32toh(resp->consec_missed_beacons);
5333 
5334 			IWM_DPRINTF(sc, IWM_DEBUG_BEACON | IWM_DEBUG_STATE,
5335 			    "%s: MISSED_BEACON: mac_id=%d, "
5336 			    "consec_since_last_rx=%d, consec=%d, num_expect=%d "
5337 			    "num_rx=%d\n",
5338 			    __func__,
5339 			    le32toh(resp->mac_id),
5340 			    le32toh(resp->consec_missed_beacons_since_last_rx),
5341 			    le32toh(resp->consec_missed_beacons),
5342 			    le32toh(resp->num_expected_beacons),
5343 			    le32toh(resp->num_recvd_beacons));
5344 
5345 			/* Be paranoid */
5346 			if (vap == NULL)
5347 				break;
5348 
5349 			/* XXX no net80211 locking? */
5350 			if (vap->iv_state == IEEE80211_S_RUN &&
5351 			    (ic->ic_flags & IEEE80211_F_SCAN) == 0) {
5352 				if (missed > vap->iv_bmissthreshold) {
5353 					/* XXX bad locking; turn into task */
5354 					IWM_UNLOCK(sc);
5355 					ieee80211_beacon_miss(ic);
5356 					IWM_LOCK(sc);
5357 				}
5358 			}
5359 
5360 			break; }
5361 
5362 		case IWM_MFUART_LOAD_NOTIFICATION:
5363 			break;
5364 
5365 		case IWM_MVM_ALIVE: {
5366 			struct iwm_mvm_alive_resp_v1 *resp1;
5367 			struct iwm_mvm_alive_resp_v2 *resp2;
5368 			struct iwm_mvm_alive_resp_v3 *resp3;
5369 
5370 			if (iwm_rx_packet_payload_len(pkt) == sizeof(*resp1)) {
5371 				resp1 = (void *)pkt->data;
5372 				sc->sc_uc.uc_error_event_table
5373 				    = le32toh(resp1->error_event_table_ptr);
5374 				sc->sc_uc.uc_log_event_table
5375 				    = le32toh(resp1->log_event_table_ptr);
5376 				sc->sched_base = le32toh(resp1->scd_base_ptr);
5377 				if (resp1->status == IWM_ALIVE_STATUS_OK)
5378 					sc->sc_uc.uc_ok = 1;
5379 				else
5380 					sc->sc_uc.uc_ok = 0;
5381 			}
5382 
5383 			if (iwm_rx_packet_payload_len(pkt) == sizeof(*resp2)) {
5384 				resp2 = (void *)pkt->data;
5385 				sc->sc_uc.uc_error_event_table
5386 				    = le32toh(resp2->error_event_table_ptr);
5387 				sc->sc_uc.uc_log_event_table
5388 				    = le32toh(resp2->log_event_table_ptr);
5389 				sc->sched_base = le32toh(resp2->scd_base_ptr);
5390 				sc->sc_uc.uc_umac_error_event_table
5391 				    = le32toh(resp2->error_info_addr);
5392 				if (resp2->status == IWM_ALIVE_STATUS_OK)
5393 					sc->sc_uc.uc_ok = 1;
5394 				else
5395 					sc->sc_uc.uc_ok = 0;
5396 			}
5397 
5398 			if (iwm_rx_packet_payload_len(pkt) == sizeof(*resp3)) {
5399 				resp3 = (void *)pkt->data;
5400 				sc->sc_uc.uc_error_event_table
5401 				    = le32toh(resp3->error_event_table_ptr);
5402 				sc->sc_uc.uc_log_event_table
5403 				    = le32toh(resp3->log_event_table_ptr);
5404 				sc->sched_base = le32toh(resp3->scd_base_ptr);
5405 				sc->sc_uc.uc_umac_error_event_table
5406 				    = le32toh(resp3->error_info_addr);
5407 				if (resp3->status == IWM_ALIVE_STATUS_OK)
5408 					sc->sc_uc.uc_ok = 1;
5409 				else
5410 					sc->sc_uc.uc_ok = 0;
5411 			}
5412 
5413 			sc->sc_uc.uc_intr = 1;
5414 			wakeup(&sc->sc_uc);
5415 			break; }
5416 
5417 		case IWM_CALIB_RES_NOTIF_PHY_DB:
5418 			break;
5419 
5420 		case IWM_STATISTICS_NOTIFICATION: {
5421 			struct iwm_notif_statistics *stats;
5422 			stats = (void *)pkt->data;
5423 			memcpy(&sc->sc_stats, stats, sizeof(sc->sc_stats));
5424 			sc->sc_noise = iwm_get_noise(sc, &stats->rx.general);
5425 			break; }
5426 
5427 		case IWM_NVM_ACCESS_CMD:
5428 		case IWM_MCC_UPDATE_CMD:
5429 			if (sc->sc_wantresp == ((qid << 16) | idx)) {
5430 				memcpy(sc->sc_cmd_resp,
5431 				    pkt, sizeof(sc->sc_cmd_resp));
5432 			}
5433 			break;
5434 
5435 		case IWM_MCC_CHUB_UPDATE_CMD: {
5436 			struct iwm_mcc_chub_notif *notif;
5437 			notif = (void *)pkt->data;
5438 
5439 			sc->sc_fw_mcc[0] = (notif->mcc & 0xff00) >> 8;
5440 			sc->sc_fw_mcc[1] = notif->mcc & 0xff;
5441 			sc->sc_fw_mcc[2] = '\0';
5442 			IWM_DPRINTF(sc, IWM_DEBUG_RESET,
5443 			    "fw source %d sent CC '%s'\n",
5444 			    notif->source_id, sc->sc_fw_mcc);
5445 			break; }
5446 
5447 		case IWM_DTS_MEASUREMENT_NOTIFICATION:
5448 			break;
5449 
5450 		case IWM_PHY_CONFIGURATION_CMD:
5451 		case IWM_TX_ANT_CONFIGURATION_CMD:
5452 		case IWM_ADD_STA:
5453 		case IWM_MAC_CONTEXT_CMD:
5454 		case IWM_REPLY_SF_CFG_CMD:
5455 		case IWM_POWER_TABLE_CMD:
5456 		case IWM_PHY_CONTEXT_CMD:
5457 		case IWM_BINDING_CONTEXT_CMD:
5458 		case IWM_TIME_EVENT_CMD:
5459 		case IWM_WIDE_ID(IWM_ALWAYS_LONG_GROUP, IWM_SCAN_CFG_CMD):
5460 		case IWM_WIDE_ID(IWM_ALWAYS_LONG_GROUP, IWM_SCAN_REQ_UMAC):
5461 		case IWM_SCAN_OFFLOAD_REQUEST_CMD:
5462 		case IWM_REPLY_BEACON_FILTERING_CMD:
5463 		case IWM_MAC_PM_POWER_TABLE:
5464 		case IWM_TIME_QUOTA_CMD:
5465 		case IWM_REMOVE_STA:
5466 		case IWM_TXPATH_FLUSH:
5467 		case IWM_LQ_CMD:
5468 		case IWM_BT_CONFIG:
5469 		case IWM_REPLY_THERMAL_MNG_BACKOFF:
5470 			cresp = (void *)pkt->data;
5471 			if (sc->sc_wantresp == ((qid << 16) | idx)) {
5472 				memcpy(sc->sc_cmd_resp,
5473 				    pkt, sizeof(*pkt)+sizeof(*cresp));
5474 			}
5475 			break;
5476 
5477 		/* ignore */
5478 		case 0x6c: /* IWM_PHY_DB_CMD, no idea why it's not in fw-api.h */
5479 			break;
5480 
5481 		case IWM_INIT_COMPLETE_NOTIF:
5482 			break;
5483 
5484 		case IWM_SCAN_OFFLOAD_COMPLETE: {
5485 			struct iwm_periodic_scan_complete *notif;
5486 			notif = (void *)pkt->data;
5487 			break;
5488 		}
5489 
5490 		case IWM_SCAN_ITERATION_COMPLETE: {
5491 			struct iwm_lmac_scan_complete_notif *notif;
5492 			notif = (void *)pkt->data;
5493 			ieee80211_runtask(&sc->sc_ic, &sc->sc_es_task);
5494  			break;
5495 		}
5496 
5497 		case IWM_SCAN_COMPLETE_UMAC: {
5498 			struct iwm_umac_scan_complete *notif;
5499 			notif = (void *)pkt->data;
5500 
5501 			IWM_DPRINTF(sc, IWM_DEBUG_SCAN,
5502 			    "UMAC scan complete, status=0x%x\n",
5503 			    notif->status);
5504 #if 0	/* XXX This would be a duplicate scan end call */
5505 			taskqueue_enqueue(sc->sc_tq, &sc->sc_es_task);
5506 #endif
5507 			break;
5508 		}
5509 
5510 		case IWM_SCAN_ITERATION_COMPLETE_UMAC: {
5511 			struct iwm_umac_scan_iter_complete_notif *notif;
5512 			notif = (void *)pkt->data;
5513 
5514 			IWM_DPRINTF(sc, IWM_DEBUG_SCAN, "UMAC scan iteration "
5515 			    "complete, status=0x%x, %d channels scanned\n",
5516 			    notif->status, notif->scanned_channels);
5517 			ieee80211_runtask(&sc->sc_ic, &sc->sc_es_task);
5518 			break;
5519 		}
5520 
5521 		case IWM_REPLY_ERROR: {
5522 			struct iwm_error_resp *resp;
5523 			resp = (void *)pkt->data;
5524 
5525 			device_printf(sc->sc_dev,
5526 			    "firmware error 0x%x, cmd 0x%x\n",
5527 			    le32toh(resp->error_type),
5528 			    resp->cmd_id);
5529 			break;
5530 		}
5531 
5532 		case IWM_TIME_EVENT_NOTIFICATION: {
5533 			struct iwm_time_event_notif *notif;
5534 			notif = (void *)pkt->data;
5535 
5536 			IWM_DPRINTF(sc, IWM_DEBUG_INTR,
5537 			    "TE notif status = 0x%x action = 0x%x\n",
5538 			    notif->status, notif->action);
5539 			break;
5540 		}
5541 
5542 		case IWM_MCAST_FILTER_CMD:
5543 			break;
5544 
5545 		case IWM_SCD_QUEUE_CFG: {
5546 			struct iwm_scd_txq_cfg_rsp *rsp;
5547 			rsp = (void *)pkt->data;
5548 
5549 			IWM_DPRINTF(sc, IWM_DEBUG_CMD,
5550 			    "queue cfg token=0x%x sta_id=%d "
5551 			    "tid=%d scd_queue=%d\n",
5552 			    rsp->token, rsp->sta_id, rsp->tid,
5553 			    rsp->scd_queue);
5554 			break;
5555 		}
5556 
5557 		default:
5558 			device_printf(sc->sc_dev,
5559 			    "frame %d/%d %x UNHANDLED (this should "
5560 			    "not happen)\n", qid, idx,
5561 			    pkt->len_n_flags);
5562 			break;
5563 		}
5564 
5565 		/*
5566 		 * Why test bit 0x80?  The Linux driver:
5567 		 *
5568 		 * There is one exception:  uCode sets bit 15 when it
5569 		 * originates the response/notification, i.e. when the
5570 		 * response/notification is not a direct response to a
5571 		 * command sent by the driver.  For example, uCode issues
5572 		 * IWM_REPLY_RX when it sends a received frame to the driver;
5573 		 * it is not a direct response to any driver command.
5574 		 *
5575 		 * Ok, so since when is 7 == 15?  Well, the Linux driver
5576 		 * uses a slightly different format for pkt->hdr, and "qid"
5577 		 * is actually the upper byte of a two-byte field.
5578 		 */
5579 		if (!(pkt->hdr.qid & (1 << 7))) {
5580 			iwm_cmd_done(sc, pkt);
5581 		}
5582 
5583 		ADVANCE_RXQ(sc);
5584 	}
5585 
5586 	IWM_CLRBITS(sc, IWM_CSR_GP_CNTRL,
5587 	    IWM_CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ);
5588 
5589 	/*
5590 	 * Tell the firmware what we have processed.
5591 	 * Seems like the hardware gets upset unless we align
5592 	 * the write by 8??
5593 	 */
5594 	hw = (hw == 0) ? IWM_RX_RING_COUNT - 1 : hw - 1;
5595 	IWM_WRITE(sc, IWM_FH_RSCSR_CHNL0_WPTR, hw & ~7);
5596 }
5597 
5598 static void
5599 iwm_intr(void *arg)
5600 {
5601 	struct iwm_softc *sc = arg;
5602 	int handled = 0;
5603 	int r1, r2, rv = 0;
5604 	int isperiodic = 0;
5605 
5606 	IWM_LOCK(sc);
5607 	IWM_WRITE(sc, IWM_CSR_INT_MASK, 0);
5608 
5609 	if (sc->sc_flags & IWM_FLAG_USE_ICT) {
5610 		uint32_t *ict = sc->ict_dma.vaddr;
5611 		int tmp;
5612 
5613 		tmp = htole32(ict[sc->ict_cur]);
5614 		if (!tmp)
5615 			goto out_ena;
5616 
5617 		/*
5618 		 * ok, there was something.  keep plowing until we have all.
5619 		 */
5620 		r1 = r2 = 0;
5621 		while (tmp) {
5622 			r1 |= tmp;
5623 			ict[sc->ict_cur] = 0;
5624 			sc->ict_cur = (sc->ict_cur+1) % IWM_ICT_COUNT;
5625 			tmp = htole32(ict[sc->ict_cur]);
5626 		}
5627 
5628 		/* this is where the fun begins.  don't ask */
5629 		if (r1 == 0xffffffff)
5630 			r1 = 0;
5631 
5632 		/* i am not expected to understand this */
5633 		if (r1 & 0xc0000)
5634 			r1 |= 0x8000;
5635 		r1 = (0xff & r1) | ((0xff00 & r1) << 16);
5636 	} else {
5637 		r1 = IWM_READ(sc, IWM_CSR_INT);
5638 		/* "hardware gone" (where, fishing?) */
5639 		if (r1 == 0xffffffff || (r1 & 0xfffffff0) == 0xa5a5a5a0)
5640 			goto out;
5641 		r2 = IWM_READ(sc, IWM_CSR_FH_INT_STATUS);
5642 	}
5643 	if (r1 == 0 && r2 == 0) {
5644 		goto out_ena;
5645 	}
5646 
5647 	IWM_WRITE(sc, IWM_CSR_INT, r1 | ~sc->sc_intmask);
5648 
5649 	/* ignored */
5650 	handled |= (r1 & (IWM_CSR_INT_BIT_ALIVE /*| IWM_CSR_INT_BIT_SCD*/));
5651 
5652 	if (r1 & IWM_CSR_INT_BIT_SW_ERR) {
5653 		int i;
5654 		struct ieee80211com *ic = &sc->sc_ic;
5655 		struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
5656 
5657 #ifdef IWM_DEBUG
5658 		iwm_nic_error(sc);
5659 #endif
5660 		/* Dump driver status (TX and RX rings) while we're here. */
5661 		device_printf(sc->sc_dev, "driver status:\n");
5662 		for (i = 0; i < IWM_MVM_MAX_QUEUES; i++) {
5663 			struct iwm_tx_ring *ring = &sc->txq[i];
5664 			device_printf(sc->sc_dev,
5665 			    "  tx ring %2d: qid=%-2d cur=%-3d "
5666 			    "queued=%-3d\n",
5667 			    i, ring->qid, ring->cur, ring->queued);
5668 		}
5669 		device_printf(sc->sc_dev,
5670 		    "  rx ring: cur=%d\n", sc->rxq.cur);
5671 		device_printf(sc->sc_dev,
5672 		    "  802.11 state %d\n", (vap == NULL) ? -1 : vap->iv_state);
5673 
5674 		/* Don't stop the device; just do a VAP restart */
5675 		IWM_UNLOCK(sc);
5676 
5677 		if (vap == NULL) {
5678 			printf("%s: null vap\n", __func__);
5679 			return;
5680 		}
5681 
5682 		device_printf(sc->sc_dev, "%s: controller panicked, iv_state = %d; "
5683 		    "restarting\n", __func__, vap->iv_state);
5684 
5685 		/* XXX TODO: turn this into a callout/taskqueue */
5686 		ieee80211_restart_all(ic);
5687 		return;
5688 	}
5689 
5690 	if (r1 & IWM_CSR_INT_BIT_HW_ERR) {
5691 		handled |= IWM_CSR_INT_BIT_HW_ERR;
5692 		device_printf(sc->sc_dev, "hardware error, stopping device\n");
5693 		iwm_stop(sc);
5694 		rv = 1;
5695 		goto out;
5696 	}
5697 
5698 	/* firmware chunk loaded */
5699 	if (r1 & IWM_CSR_INT_BIT_FH_TX) {
5700 		IWM_WRITE(sc, IWM_CSR_FH_INT_STATUS, IWM_CSR_FH_INT_TX_MASK);
5701 		handled |= IWM_CSR_INT_BIT_FH_TX;
5702 		sc->sc_fw_chunk_done = 1;
5703 		wakeup(&sc->sc_fw);
5704 	}
5705 
5706 	if (r1 & IWM_CSR_INT_BIT_RF_KILL) {
5707 		handled |= IWM_CSR_INT_BIT_RF_KILL;
5708 		if (iwm_check_rfkill(sc)) {
5709 			device_printf(sc->sc_dev,
5710 			    "%s: rfkill switch, disabling interface\n",
5711 			    __func__);
5712 			iwm_stop(sc);
5713 		}
5714 	}
5715 
5716 	/*
5717 	 * The Linux driver uses periodic interrupts to avoid races.
5718 	 * We cargo-cult like it's going out of fashion.
5719 	 */
5720 	if (r1 & IWM_CSR_INT_BIT_RX_PERIODIC) {
5721 		handled |= IWM_CSR_INT_BIT_RX_PERIODIC;
5722 		IWM_WRITE(sc, IWM_CSR_INT, IWM_CSR_INT_BIT_RX_PERIODIC);
5723 		if ((r1 & (IWM_CSR_INT_BIT_FH_RX | IWM_CSR_INT_BIT_SW_RX)) == 0)
5724 			IWM_WRITE_1(sc,
5725 			    IWM_CSR_INT_PERIODIC_REG, IWM_CSR_INT_PERIODIC_DIS);
5726 		isperiodic = 1;
5727 	}
5728 
5729 	if ((r1 & (IWM_CSR_INT_BIT_FH_RX | IWM_CSR_INT_BIT_SW_RX)) || isperiodic) {
5730 		handled |= (IWM_CSR_INT_BIT_FH_RX | IWM_CSR_INT_BIT_SW_RX);
5731 		IWM_WRITE(sc, IWM_CSR_FH_INT_STATUS, IWM_CSR_FH_INT_RX_MASK);
5732 
5733 		iwm_notif_intr(sc);
5734 
5735 		/* enable periodic interrupt, see above */
5736 		if (r1 & (IWM_CSR_INT_BIT_FH_RX | IWM_CSR_INT_BIT_SW_RX) && !isperiodic)
5737 			IWM_WRITE_1(sc, IWM_CSR_INT_PERIODIC_REG,
5738 			    IWM_CSR_INT_PERIODIC_ENA);
5739 	}
5740 
5741 	if (__predict_false(r1 & ~handled))
5742 		IWM_DPRINTF(sc, IWM_DEBUG_INTR,
5743 		    "%s: unhandled interrupts: %x\n", __func__, r1);
5744 	rv = 1;
5745 
5746  out_ena:
5747 	iwm_restore_interrupts(sc);
5748  out:
5749 	IWM_UNLOCK(sc);
5750 	return;
5751 }
5752 
5753 /*
5754  * Autoconf glue-sniffing
5755  */
5756 #define	PCI_VENDOR_INTEL		0x8086
5757 #define	PCI_PRODUCT_INTEL_WL_3160_1	0x08b3
5758 #define	PCI_PRODUCT_INTEL_WL_3160_2	0x08b4
5759 #define	PCI_PRODUCT_INTEL_WL_3165_1	0x3165
5760 #define	PCI_PRODUCT_INTEL_WL_3165_2	0x3166
5761 #define	PCI_PRODUCT_INTEL_WL_7260_1	0x08b1
5762 #define	PCI_PRODUCT_INTEL_WL_7260_2	0x08b2
5763 #define	PCI_PRODUCT_INTEL_WL_7265_1	0x095a
5764 #define	PCI_PRODUCT_INTEL_WL_7265_2	0x095b
5765 #define	PCI_PRODUCT_INTEL_WL_8260_1	0x24f3
5766 #define	PCI_PRODUCT_INTEL_WL_8260_2	0x24f4
5767 
5768 static const struct iwm_devices {
5769 	uint16_t	device;
5770 	const char	*name;
5771 } iwm_devices[] = {
5772 	{ PCI_PRODUCT_INTEL_WL_3160_1, "Intel Dual Band Wireless AC 3160" },
5773 	{ PCI_PRODUCT_INTEL_WL_3160_2, "Intel Dual Band Wireless AC 3160" },
5774 	{ PCI_PRODUCT_INTEL_WL_3165_1, "Intel Dual Band Wireless AC 3165" },
5775 	{ PCI_PRODUCT_INTEL_WL_3165_2, "Intel Dual Band Wireless AC 3165" },
5776 	{ PCI_PRODUCT_INTEL_WL_7260_1, "Intel Dual Band Wireless AC 7260" },
5777 	{ PCI_PRODUCT_INTEL_WL_7260_2, "Intel Dual Band Wireless AC 7260" },
5778 	{ PCI_PRODUCT_INTEL_WL_7265_1, "Intel Dual Band Wireless AC 7265" },
5779 	{ PCI_PRODUCT_INTEL_WL_7265_2, "Intel Dual Band Wireless AC 7265" },
5780 	{ PCI_PRODUCT_INTEL_WL_8260_1, "Intel Dual Band Wireless AC 8260" },
5781 	{ PCI_PRODUCT_INTEL_WL_8260_2, "Intel Dual Band Wireless AC 8260" },
5782 };
5783 
5784 static int
5785 iwm_probe(device_t dev)
5786 {
5787 	int i;
5788 
5789 	for (i = 0; i < nitems(iwm_devices); i++) {
5790 		if (pci_get_vendor(dev) == PCI_VENDOR_INTEL &&
5791 		    pci_get_device(dev) == iwm_devices[i].device) {
5792 			device_set_desc(dev, iwm_devices[i].name);
5793 			return (BUS_PROBE_DEFAULT);
5794 		}
5795 	}
5796 
5797 	return (ENXIO);
5798 }
5799 
5800 static int
5801 iwm_dev_check(device_t dev)
5802 {
5803 	struct iwm_softc *sc;
5804 
5805 	sc = device_get_softc(dev);
5806 
5807 	switch (pci_get_device(dev)) {
5808 	case PCI_PRODUCT_INTEL_WL_3160_1:
5809 	case PCI_PRODUCT_INTEL_WL_3160_2:
5810 		sc->cfg = &iwm3160_cfg;
5811 		sc->sc_fwdmasegsz = IWM_FWDMASEGSZ;
5812 		return (0);
5813 	case PCI_PRODUCT_INTEL_WL_3165_1:
5814 	case PCI_PRODUCT_INTEL_WL_3165_2:
5815 		sc->cfg = &iwm3165_cfg;
5816 		sc->sc_fwdmasegsz = IWM_FWDMASEGSZ;
5817 		return (0);
5818 	case PCI_PRODUCT_INTEL_WL_7260_1:
5819 	case PCI_PRODUCT_INTEL_WL_7260_2:
5820 		sc->cfg = &iwm7260_cfg;
5821 		sc->sc_fwdmasegsz = IWM_FWDMASEGSZ;
5822 		return (0);
5823 	case PCI_PRODUCT_INTEL_WL_7265_1:
5824 	case PCI_PRODUCT_INTEL_WL_7265_2:
5825 		sc->cfg = &iwm7265_cfg;
5826 		sc->sc_fwdmasegsz = IWM_FWDMASEGSZ;
5827 		return (0);
5828 	case PCI_PRODUCT_INTEL_WL_8260_1:
5829 	case PCI_PRODUCT_INTEL_WL_8260_2:
5830 		sc->cfg = &iwm8260_cfg;
5831 		sc->sc_fwdmasegsz = IWM_FWDMASEGSZ_8000;
5832 		return (0);
5833 	default:
5834 		device_printf(dev, "unknown adapter type\n");
5835 		return ENXIO;
5836 	}
5837 }
5838 
5839 static int
5840 iwm_pci_attach(device_t dev)
5841 {
5842 	struct iwm_softc *sc;
5843 	int count, error, rid;
5844 	uint16_t reg;
5845 
5846 	sc = device_get_softc(dev);
5847 
5848 	/* Clear device-specific "PCI retry timeout" register (41h). */
5849 	reg = pci_read_config(dev, 0x40, sizeof(reg));
5850 	pci_write_config(dev, 0x40, reg & ~0xff00, sizeof(reg));
5851 
5852 	/* Enable bus-mastering and hardware bug workaround. */
5853 	pci_enable_busmaster(dev);
5854 	reg = pci_read_config(dev, PCIR_STATUS, sizeof(reg));
5855 	/* if !MSI */
5856 	if (reg & PCIM_STATUS_INTxSTATE) {
5857 		reg &= ~PCIM_STATUS_INTxSTATE;
5858 	}
5859 	pci_write_config(dev, PCIR_STATUS, reg, sizeof(reg));
5860 
5861 	rid = PCIR_BAR(0);
5862 	sc->sc_mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid,
5863 	    RF_ACTIVE);
5864 	if (sc->sc_mem == NULL) {
5865 		device_printf(sc->sc_dev, "can't map mem space\n");
5866 		return (ENXIO);
5867 	}
5868 	sc->sc_st = rman_get_bustag(sc->sc_mem);
5869 	sc->sc_sh = rman_get_bushandle(sc->sc_mem);
5870 
5871 	/* Install interrupt handler. */
5872 	count = 1;
5873 	rid = 0;
5874 	if (pci_alloc_msi(dev, &count) == 0)
5875 		rid = 1;
5876 	sc->sc_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, RF_ACTIVE |
5877 	    (rid != 0 ? 0 : RF_SHAREABLE));
5878 	if (sc->sc_irq == NULL) {
5879 		device_printf(dev, "can't map interrupt\n");
5880 			return (ENXIO);
5881 	}
5882 	error = bus_setup_intr(dev, sc->sc_irq, INTR_TYPE_NET | INTR_MPSAFE,
5883 	    NULL, iwm_intr, sc, &sc->sc_ih);
5884 	if (sc->sc_ih == NULL) {
5885 		device_printf(dev, "can't establish interrupt");
5886 			return (ENXIO);
5887 	}
5888 	sc->sc_dmat = bus_get_dma_tag(sc->sc_dev);
5889 
5890 	return (0);
5891 }
5892 
5893 static void
5894 iwm_pci_detach(device_t dev)
5895 {
5896 	struct iwm_softc *sc = device_get_softc(dev);
5897 
5898 	if (sc->sc_irq != NULL) {
5899 		bus_teardown_intr(dev, sc->sc_irq, sc->sc_ih);
5900 		bus_release_resource(dev, SYS_RES_IRQ,
5901 		    rman_get_rid(sc->sc_irq), sc->sc_irq);
5902 		pci_release_msi(dev);
5903         }
5904 	if (sc->sc_mem != NULL)
5905 		bus_release_resource(dev, SYS_RES_MEMORY,
5906 		    rman_get_rid(sc->sc_mem), sc->sc_mem);
5907 }
5908 
5909 
5910 
5911 static int
5912 iwm_attach(device_t dev)
5913 {
5914 	struct iwm_softc *sc = device_get_softc(dev);
5915 	struct ieee80211com *ic = &sc->sc_ic;
5916 	int error;
5917 	int txq_i, i;
5918 
5919 	sc->sc_dev = dev;
5920 	sc->sc_attached = 1;
5921 	IWM_LOCK_INIT(sc);
5922 	mbufq_init(&sc->sc_snd, ifqmaxlen);
5923 	callout_init_mtx(&sc->sc_watchdog_to, &sc->sc_mtx, 0);
5924 	callout_init_mtx(&sc->sc_led_blink_to, &sc->sc_mtx, 0);
5925 	TASK_INIT(&sc->sc_es_task, 0, iwm_endscan_cb, sc);
5926 
5927 	sc->sc_notif_wait = iwm_notification_wait_init(sc);
5928 	if (sc->sc_notif_wait == NULL) {
5929 		device_printf(dev, "failed to init notification wait struct\n");
5930 		goto fail;
5931 	}
5932 
5933 	/* Init phy db */
5934 	sc->sc_phy_db = iwm_phy_db_init(sc);
5935 	if (!sc->sc_phy_db) {
5936 		device_printf(dev, "Cannot init phy_db\n");
5937 		goto fail;
5938 	}
5939 
5940 	/* PCI attach */
5941 	error = iwm_pci_attach(dev);
5942 	if (error != 0)
5943 		goto fail;
5944 
5945 	sc->sc_wantresp = -1;
5946 
5947 	/* Check device type */
5948 	error = iwm_dev_check(dev);
5949 	if (error != 0)
5950 		goto fail;
5951 
5952 	sc->sc_hw_rev = IWM_READ(sc, IWM_CSR_HW_REV);
5953 	/*
5954 	 * In the 8000 HW family the format of the 4 bytes of CSR_HW_REV have
5955 	 * changed, and now the revision step also includes bit 0-1 (no more
5956 	 * "dash" value). To keep hw_rev backwards compatible - we'll store it
5957 	 * in the old format.
5958 	 */
5959 	if (sc->cfg->device_family == IWM_DEVICE_FAMILY_8000)
5960 		sc->sc_hw_rev = (sc->sc_hw_rev & 0xfff0) |
5961 				(IWM_CSR_HW_REV_STEP(sc->sc_hw_rev << 2) << 2);
5962 
5963 	if (iwm_prepare_card_hw(sc) != 0) {
5964 		device_printf(dev, "could not initialize hardware\n");
5965 		goto fail;
5966 	}
5967 
5968 	if (sc->cfg->device_family == IWM_DEVICE_FAMILY_8000) {
5969 		int ret;
5970 		uint32_t hw_step;
5971 
5972 		/*
5973 		 * In order to recognize C step the driver should read the
5974 		 * chip version id located at the AUX bus MISC address.
5975 		 */
5976 		IWM_SETBITS(sc, IWM_CSR_GP_CNTRL,
5977 			    IWM_CSR_GP_CNTRL_REG_FLAG_INIT_DONE);
5978 		DELAY(2);
5979 
5980 		ret = iwm_poll_bit(sc, IWM_CSR_GP_CNTRL,
5981 				   IWM_CSR_GP_CNTRL_REG_FLAG_MAC_CLOCK_READY,
5982 				   IWM_CSR_GP_CNTRL_REG_FLAG_MAC_CLOCK_READY,
5983 				   25000);
5984 		if (!ret) {
5985 			device_printf(sc->sc_dev,
5986 			    "Failed to wake up the nic\n");
5987 			goto fail;
5988 		}
5989 
5990 		if (iwm_nic_lock(sc)) {
5991 			hw_step = iwm_read_prph(sc, IWM_WFPM_CTRL_REG);
5992 			hw_step |= IWM_ENABLE_WFPM;
5993 			iwm_write_prph(sc, IWM_WFPM_CTRL_REG, hw_step);
5994 			hw_step = iwm_read_prph(sc, IWM_AUX_MISC_REG);
5995 			hw_step = (hw_step >> IWM_HW_STEP_LOCATION_BITS) & 0xF;
5996 			if (hw_step == 0x3)
5997 				sc->sc_hw_rev = (sc->sc_hw_rev & 0xFFFFFFF3) |
5998 						(IWM_SILICON_C_STEP << 2);
5999 			iwm_nic_unlock(sc);
6000 		} else {
6001 			device_printf(sc->sc_dev, "Failed to lock the nic\n");
6002 			goto fail;
6003 		}
6004 	}
6005 
6006 	/* special-case 7265D, it has the same PCI IDs. */
6007 	if (sc->cfg == &iwm7265_cfg &&
6008 	    (sc->sc_hw_rev & IWM_CSR_HW_REV_TYPE_MSK) == IWM_CSR_HW_REV_TYPE_7265D) {
6009 		sc->cfg = &iwm7265d_cfg;
6010 	}
6011 
6012 	/* Allocate DMA memory for firmware transfers. */
6013 	if ((error = iwm_alloc_fwmem(sc)) != 0) {
6014 		device_printf(dev, "could not allocate memory for firmware\n");
6015 		goto fail;
6016 	}
6017 
6018 	/* Allocate "Keep Warm" page. */
6019 	if ((error = iwm_alloc_kw(sc)) != 0) {
6020 		device_printf(dev, "could not allocate keep warm page\n");
6021 		goto fail;
6022 	}
6023 
6024 	/* We use ICT interrupts */
6025 	if ((error = iwm_alloc_ict(sc)) != 0) {
6026 		device_printf(dev, "could not allocate ICT table\n");
6027 		goto fail;
6028 	}
6029 
6030 	/* Allocate TX scheduler "rings". */
6031 	if ((error = iwm_alloc_sched(sc)) != 0) {
6032 		device_printf(dev, "could not allocate TX scheduler rings\n");
6033 		goto fail;
6034 	}
6035 
6036 	/* Allocate TX rings */
6037 	for (txq_i = 0; txq_i < nitems(sc->txq); txq_i++) {
6038 		if ((error = iwm_alloc_tx_ring(sc,
6039 		    &sc->txq[txq_i], txq_i)) != 0) {
6040 			device_printf(dev,
6041 			    "could not allocate TX ring %d\n",
6042 			    txq_i);
6043 			goto fail;
6044 		}
6045 	}
6046 
6047 	/* Allocate RX ring. */
6048 	if ((error = iwm_alloc_rx_ring(sc, &sc->rxq)) != 0) {
6049 		device_printf(dev, "could not allocate RX ring\n");
6050 		goto fail;
6051 	}
6052 
6053 	/* Clear pending interrupts. */
6054 	IWM_WRITE(sc, IWM_CSR_INT, 0xffffffff);
6055 
6056 	ic->ic_softc = sc;
6057 	ic->ic_name = device_get_nameunit(sc->sc_dev);
6058 	ic->ic_phytype = IEEE80211_T_OFDM;	/* not only, but not used */
6059 	ic->ic_opmode = IEEE80211_M_STA;	/* default to BSS mode */
6060 
6061 	/* Set device capabilities. */
6062 	ic->ic_caps =
6063 	    IEEE80211_C_STA |
6064 	    IEEE80211_C_WPA |		/* WPA/RSN */
6065 	    IEEE80211_C_WME |
6066 	    IEEE80211_C_SHSLOT |	/* short slot time supported */
6067 	    IEEE80211_C_SHPREAMBLE	/* short preamble supported */
6068 //	    IEEE80211_C_BGSCAN		/* capable of bg scanning */
6069 	    ;
6070 	/* Advertise full-offload scanning */
6071 	ic->ic_flags_ext = IEEE80211_FEXT_SCAN_OFFLOAD;
6072 	for (i = 0; i < nitems(sc->sc_phyctxt); i++) {
6073 		sc->sc_phyctxt[i].id = i;
6074 		sc->sc_phyctxt[i].color = 0;
6075 		sc->sc_phyctxt[i].ref = 0;
6076 		sc->sc_phyctxt[i].channel = NULL;
6077 	}
6078 
6079 	/* Default noise floor */
6080 	sc->sc_noise = -96;
6081 
6082 	/* Max RSSI */
6083 	sc->sc_max_rssi = IWM_MAX_DBM - IWM_MIN_DBM;
6084 
6085 	sc->sc_preinit_hook.ich_func = iwm_preinit;
6086 	sc->sc_preinit_hook.ich_arg = sc;
6087 	if (config_intrhook_establish(&sc->sc_preinit_hook) != 0) {
6088 		device_printf(dev, "config_intrhook_establish failed\n");
6089 		goto fail;
6090 	}
6091 
6092 #ifdef IWM_DEBUG
6093 	SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
6094 	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO, "debug",
6095 	    CTLFLAG_RW, &sc->sc_debug, 0, "control debugging");
6096 #endif
6097 
6098 	IWM_DPRINTF(sc, IWM_DEBUG_RESET | IWM_DEBUG_TRACE,
6099 	    "<-%s\n", __func__);
6100 
6101 	return 0;
6102 
6103 	/* Free allocated memory if something failed during attachment. */
6104 fail:
6105 	iwm_detach_local(sc, 0);
6106 
6107 	return ENXIO;
6108 }
6109 
6110 static int
6111 iwm_is_valid_ether_addr(uint8_t *addr)
6112 {
6113 	char zero_addr[IEEE80211_ADDR_LEN] = { 0, 0, 0, 0, 0, 0 };
6114 
6115 	if ((addr[0] & 1) || IEEE80211_ADDR_EQ(zero_addr, addr))
6116 		return (FALSE);
6117 
6118 	return (TRUE);
6119 }
6120 
6121 static int
6122 iwm_update_edca(struct ieee80211com *ic)
6123 {
6124 	struct iwm_softc *sc = ic->ic_softc;
6125 
6126 	device_printf(sc->sc_dev, "%s: called\n", __func__);
6127 	return (0);
6128 }
6129 
6130 static void
6131 iwm_preinit(void *arg)
6132 {
6133 	struct iwm_softc *sc = arg;
6134 	device_t dev = sc->sc_dev;
6135 	struct ieee80211com *ic = &sc->sc_ic;
6136 	int error;
6137 
6138 	IWM_DPRINTF(sc, IWM_DEBUG_RESET | IWM_DEBUG_TRACE,
6139 	    "->%s\n", __func__);
6140 
6141 	IWM_LOCK(sc);
6142 	if ((error = iwm_start_hw(sc)) != 0) {
6143 		device_printf(dev, "could not initialize hardware\n");
6144 		IWM_UNLOCK(sc);
6145 		goto fail;
6146 	}
6147 
6148 	error = iwm_run_init_mvm_ucode(sc, 1);
6149 	iwm_stop_device(sc);
6150 	if (error) {
6151 		IWM_UNLOCK(sc);
6152 		goto fail;
6153 	}
6154 	device_printf(dev,
6155 	    "hw rev 0x%x, fw ver %s, address %s\n",
6156 	    sc->sc_hw_rev & IWM_CSR_HW_REV_TYPE_MSK,
6157 	    sc->sc_fwver, ether_sprintf(sc->nvm_data->hw_addr));
6158 
6159 	/* not all hardware can do 5GHz band */
6160 	if (!sc->nvm_data->sku_cap_band_52GHz_enable)
6161 		memset(&ic->ic_sup_rates[IEEE80211_MODE_11A], 0,
6162 		    sizeof(ic->ic_sup_rates[IEEE80211_MODE_11A]));
6163 	IWM_UNLOCK(sc);
6164 
6165 	iwm_init_channel_map(ic, IEEE80211_CHAN_MAX, &ic->ic_nchans,
6166 	    ic->ic_channels);
6167 
6168 	/*
6169 	 * At this point we've committed - if we fail to do setup,
6170 	 * we now also have to tear down the net80211 state.
6171 	 */
6172 	ieee80211_ifattach(ic);
6173 	ic->ic_vap_create = iwm_vap_create;
6174 	ic->ic_vap_delete = iwm_vap_delete;
6175 	ic->ic_raw_xmit = iwm_raw_xmit;
6176 	ic->ic_node_alloc = iwm_node_alloc;
6177 	ic->ic_scan_start = iwm_scan_start;
6178 	ic->ic_scan_end = iwm_scan_end;
6179 	ic->ic_update_mcast = iwm_update_mcast;
6180 	ic->ic_getradiocaps = iwm_init_channel_map;
6181 	ic->ic_set_channel = iwm_set_channel;
6182 	ic->ic_scan_curchan = iwm_scan_curchan;
6183 	ic->ic_scan_mindwell = iwm_scan_mindwell;
6184 	ic->ic_wme.wme_update = iwm_update_edca;
6185 	ic->ic_parent = iwm_parent;
6186 	ic->ic_transmit = iwm_transmit;
6187 	iwm_radiotap_attach(sc);
6188 	if (bootverbose)
6189 		ieee80211_announce(ic);
6190 
6191 	IWM_DPRINTF(sc, IWM_DEBUG_RESET | IWM_DEBUG_TRACE,
6192 	    "<-%s\n", __func__);
6193 	config_intrhook_disestablish(&sc->sc_preinit_hook);
6194 
6195 	return;
6196 fail:
6197 	config_intrhook_disestablish(&sc->sc_preinit_hook);
6198 	iwm_detach_local(sc, 0);
6199 }
6200 
6201 /*
6202  * Attach the interface to 802.11 radiotap.
6203  */
6204 static void
6205 iwm_radiotap_attach(struct iwm_softc *sc)
6206 {
6207         struct ieee80211com *ic = &sc->sc_ic;
6208 
6209 	IWM_DPRINTF(sc, IWM_DEBUG_RESET | IWM_DEBUG_TRACE,
6210 	    "->%s begin\n", __func__);
6211         ieee80211_radiotap_attach(ic,
6212             &sc->sc_txtap.wt_ihdr, sizeof(sc->sc_txtap),
6213                 IWM_TX_RADIOTAP_PRESENT,
6214             &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap),
6215                 IWM_RX_RADIOTAP_PRESENT);
6216 	IWM_DPRINTF(sc, IWM_DEBUG_RESET | IWM_DEBUG_TRACE,
6217 	    "->%s end\n", __func__);
6218 }
6219 
6220 static struct ieee80211vap *
6221 iwm_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
6222     enum ieee80211_opmode opmode, int flags,
6223     const uint8_t bssid[IEEE80211_ADDR_LEN],
6224     const uint8_t mac[IEEE80211_ADDR_LEN])
6225 {
6226 	struct iwm_vap *ivp;
6227 	struct ieee80211vap *vap;
6228 
6229 	if (!TAILQ_EMPTY(&ic->ic_vaps))         /* only one at a time */
6230 		return NULL;
6231 	ivp = malloc(sizeof(struct iwm_vap), M_80211_VAP, M_WAITOK | M_ZERO);
6232 	vap = &ivp->iv_vap;
6233 	ieee80211_vap_setup(ic, vap, name, unit, opmode, flags, bssid);
6234 	vap->iv_bmissthreshold = 10;            /* override default */
6235 	/* Override with driver methods. */
6236 	ivp->iv_newstate = vap->iv_newstate;
6237 	vap->iv_newstate = iwm_newstate;
6238 
6239 	ieee80211_ratectl_init(vap);
6240 	/* Complete setup. */
6241 	ieee80211_vap_attach(vap, iwm_media_change, ieee80211_media_status,
6242 	    mac);
6243 	ic->ic_opmode = opmode;
6244 
6245 	return vap;
6246 }
6247 
6248 static void
6249 iwm_vap_delete(struct ieee80211vap *vap)
6250 {
6251 	struct iwm_vap *ivp = IWM_VAP(vap);
6252 
6253 	ieee80211_ratectl_deinit(vap);
6254 	ieee80211_vap_detach(vap);
6255 	free(ivp, M_80211_VAP);
6256 }
6257 
6258 static void
6259 iwm_scan_start(struct ieee80211com *ic)
6260 {
6261 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
6262 	struct iwm_softc *sc = ic->ic_softc;
6263 	int error;
6264 
6265 	IWM_LOCK(sc);
6266 	if (isset(sc->sc_enabled_capa, IWM_UCODE_TLV_CAPA_UMAC_SCAN))
6267 		error = iwm_mvm_umac_scan(sc);
6268 	else
6269 		error = iwm_mvm_lmac_scan(sc);
6270 	if (error != 0) {
6271 		device_printf(sc->sc_dev, "could not initiate 2 GHz scan\n");
6272 		IWM_UNLOCK(sc);
6273 		ieee80211_cancel_scan(vap);
6274 	} else {
6275 		iwm_led_blink_start(sc);
6276 		IWM_UNLOCK(sc);
6277 	}
6278 }
6279 
6280 static void
6281 iwm_scan_end(struct ieee80211com *ic)
6282 {
6283 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
6284 	struct iwm_softc *sc = ic->ic_softc;
6285 
6286 	IWM_LOCK(sc);
6287 	iwm_led_blink_stop(sc);
6288 	if (vap->iv_state == IEEE80211_S_RUN)
6289 		iwm_mvm_led_enable(sc);
6290 	IWM_UNLOCK(sc);
6291 }
6292 
6293 static void
6294 iwm_update_mcast(struct ieee80211com *ic)
6295 {
6296 }
6297 
6298 static void
6299 iwm_set_channel(struct ieee80211com *ic)
6300 {
6301 }
6302 
6303 static void
6304 iwm_scan_curchan(struct ieee80211_scan_state *ss, unsigned long maxdwell)
6305 {
6306 }
6307 
6308 static void
6309 iwm_scan_mindwell(struct ieee80211_scan_state *ss)
6310 {
6311 	return;
6312 }
6313 
6314 void
6315 iwm_init_task(void *arg1)
6316 {
6317 	struct iwm_softc *sc = arg1;
6318 
6319 	IWM_LOCK(sc);
6320 	while (sc->sc_flags & IWM_FLAG_BUSY)
6321 		msleep(&sc->sc_flags, &sc->sc_mtx, 0, "iwmpwr", 0);
6322 	sc->sc_flags |= IWM_FLAG_BUSY;
6323 	iwm_stop(sc);
6324 	if (sc->sc_ic.ic_nrunning > 0)
6325 		iwm_init(sc);
6326 	sc->sc_flags &= ~IWM_FLAG_BUSY;
6327 	wakeup(&sc->sc_flags);
6328 	IWM_UNLOCK(sc);
6329 }
6330 
6331 static int
6332 iwm_resume(device_t dev)
6333 {
6334 	struct iwm_softc *sc = device_get_softc(dev);
6335 	int do_reinit = 0;
6336 	uint16_t reg;
6337 
6338 	/* Clear device-specific "PCI retry timeout" register (41h). */
6339 	reg = pci_read_config(dev, 0x40, sizeof(reg));
6340 	pci_write_config(dev, 0x40, reg & ~0xff00, sizeof(reg));
6341 	iwm_init_task(device_get_softc(dev));
6342 
6343 	IWM_LOCK(sc);
6344 	if (sc->sc_flags & IWM_FLAG_SCANNING) {
6345 		sc->sc_flags &= ~IWM_FLAG_SCANNING;
6346 		do_reinit = 1;
6347 	}
6348 	IWM_UNLOCK(sc);
6349 
6350 	if (do_reinit)
6351 		ieee80211_resume_all(&sc->sc_ic);
6352 
6353 	return 0;
6354 }
6355 
6356 static int
6357 iwm_suspend(device_t dev)
6358 {
6359 	int do_stop = 0;
6360 	struct iwm_softc *sc = device_get_softc(dev);
6361 
6362 	do_stop = !! (sc->sc_ic.ic_nrunning > 0);
6363 
6364 	ieee80211_suspend_all(&sc->sc_ic);
6365 
6366 	if (do_stop) {
6367 		IWM_LOCK(sc);
6368 		iwm_stop(sc);
6369 		sc->sc_flags |= IWM_FLAG_SCANNING;
6370 		IWM_UNLOCK(sc);
6371 	}
6372 
6373 	return (0);
6374 }
6375 
6376 static int
6377 iwm_detach_local(struct iwm_softc *sc, int do_net80211)
6378 {
6379 	struct iwm_fw_info *fw = &sc->sc_fw;
6380 	device_t dev = sc->sc_dev;
6381 	int i;
6382 
6383 	if (!sc->sc_attached)
6384 		return 0;
6385 	sc->sc_attached = 0;
6386 
6387 	if (do_net80211)
6388 		ieee80211_draintask(&sc->sc_ic, &sc->sc_es_task);
6389 
6390 	callout_drain(&sc->sc_led_blink_to);
6391 	callout_drain(&sc->sc_watchdog_to);
6392 	iwm_stop_device(sc);
6393 	if (do_net80211) {
6394 		ieee80211_ifdetach(&sc->sc_ic);
6395 	}
6396 
6397 	iwm_phy_db_free(sc->sc_phy_db);
6398 	sc->sc_phy_db = NULL;
6399 
6400 	iwm_free_nvm_data(sc->nvm_data);
6401 
6402 	/* Free descriptor rings */
6403 	iwm_free_rx_ring(sc, &sc->rxq);
6404 	for (i = 0; i < nitems(sc->txq); i++)
6405 		iwm_free_tx_ring(sc, &sc->txq[i]);
6406 
6407 	/* Free firmware */
6408 	if (fw->fw_fp != NULL)
6409 		iwm_fw_info_free(fw);
6410 
6411 	/* Free scheduler */
6412 	iwm_dma_contig_free(&sc->sched_dma);
6413 	iwm_dma_contig_free(&sc->ict_dma);
6414 	iwm_dma_contig_free(&sc->kw_dma);
6415 	iwm_dma_contig_free(&sc->fw_dma);
6416 
6417 	/* Finished with the hardware - detach things */
6418 	iwm_pci_detach(dev);
6419 
6420 	if (sc->sc_notif_wait != NULL) {
6421 		iwm_notification_wait_free(sc->sc_notif_wait);
6422 		sc->sc_notif_wait = NULL;
6423 	}
6424 
6425 	mbufq_drain(&sc->sc_snd);
6426 	IWM_LOCK_DESTROY(sc);
6427 
6428 	return (0);
6429 }
6430 
6431 static int
6432 iwm_detach(device_t dev)
6433 {
6434 	struct iwm_softc *sc = device_get_softc(dev);
6435 
6436 	return (iwm_detach_local(sc, 1));
6437 }
6438 
6439 static device_method_t iwm_pci_methods[] = {
6440         /* Device interface */
6441         DEVMETHOD(device_probe,         iwm_probe),
6442         DEVMETHOD(device_attach,        iwm_attach),
6443         DEVMETHOD(device_detach,        iwm_detach),
6444         DEVMETHOD(device_suspend,       iwm_suspend),
6445         DEVMETHOD(device_resume,        iwm_resume),
6446 
6447         DEVMETHOD_END
6448 };
6449 
6450 static driver_t iwm_pci_driver = {
6451         "iwm",
6452         iwm_pci_methods,
6453         sizeof (struct iwm_softc)
6454 };
6455 
6456 static devclass_t iwm_devclass;
6457 
6458 DRIVER_MODULE(iwm, pci, iwm_pci_driver, iwm_devclass, NULL, NULL);
6459 MODULE_DEPEND(iwm, firmware, 1, 1, 1);
6460 MODULE_DEPEND(iwm, pci, 1, 1, 1);
6461 MODULE_DEPEND(iwm, wlan, 1, 1, 1);
6462