xref: /linux/drivers/net/wireless/intel/iwlwifi/mvm/utils.c (revision a5d9265e017f081f0dc133c0e2f45103d027b874)
1 /******************************************************************************
2  *
3  * This file is provided under a dual BSD/GPLv2 license.  When using or
4  * redistributing this file, you may do so under either license.
5  *
6  * GPL LICENSE SUMMARY
7  *
8  * Copyright(c) 2012 - 2014 Intel Corporation. All rights reserved.
9  * Copyright(c) 2013 - 2014 Intel Mobile Communications GmbH
10  * Copyright (C) 2015 - 2017 Intel Deutschland GmbH
11  * Copyright(c) 2018 Intel Corporation
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of version 2 of the GNU General Public License as
15  * published by the Free Software Foundation.
16  *
17  * This program is distributed in the hope that it will be useful, but
18  * WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * General Public License for more details.
21  *
22  * The full GNU General Public License is included in this distribution
23  * in the file called COPYING.
24  *
25  * Contact Information:
26  *  Intel Linux Wireless <linuxwifi@intel.com>
27  * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
28  *
29  * BSD LICENSE
30  *
31  * Copyright(c) 2012 - 2014 Intel Corporation. All rights reserved.
32  * Copyright(c) 2013 - 2014 Intel Mobile Communications GmbH
33  * Copyright (C) 2015 - 2017 Intel Deutschland GmbH
34  * Copyright(c) 2018 Intel Corporation
35  * All rights reserved.
36  *
37  * Redistribution and use in source and binary forms, with or without
38  * modification, are permitted provided that the following conditions
39  * are met:
40  *
41  *  * Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  *  * Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in
45  *    the documentation and/or other materials provided with the
46  *    distribution.
47  *  * Neither the name Intel Corporation nor the names of its
48  *    contributors may be used to endorse or promote products derived
49  *    from this software without specific prior written permission.
50  *
51  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
52  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
53  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
54  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
55  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
56  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
57  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
58  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
59  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
60  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
61  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
62  *
63  *****************************************************************************/
64 #include <net/mac80211.h>
65 
66 #include "iwl-debug.h"
67 #include "iwl-io.h"
68 #include "iwl-prph.h"
69 #include "iwl-csr.h"
70 #include "mvm.h"
71 #include "fw/api/rs.h"
72 
73 /*
74  * Will return 0 even if the cmd failed when RFKILL is asserted unless
75  * CMD_WANT_SKB is set in cmd->flags.
76  */
77 int iwl_mvm_send_cmd(struct iwl_mvm *mvm, struct iwl_host_cmd *cmd)
78 {
79 	int ret;
80 
81 #if defined(CONFIG_IWLWIFI_DEBUGFS) && defined(CONFIG_PM_SLEEP)
82 	if (WARN_ON(mvm->d3_test_active))
83 		return -EIO;
84 #endif
85 
86 	/*
87 	 * Synchronous commands from this op-mode must hold
88 	 * the mutex, this ensures we don't try to send two
89 	 * (or more) synchronous commands at a time.
90 	 */
91 	if (!(cmd->flags & CMD_ASYNC)) {
92 		lockdep_assert_held(&mvm->mutex);
93 		if (!(cmd->flags & CMD_SEND_IN_IDLE))
94 			iwl_mvm_ref(mvm, IWL_MVM_REF_SENDING_CMD);
95 	}
96 
97 	ret = iwl_trans_send_cmd(mvm->trans, cmd);
98 
99 	if (!(cmd->flags & (CMD_ASYNC | CMD_SEND_IN_IDLE)))
100 		iwl_mvm_unref(mvm, IWL_MVM_REF_SENDING_CMD);
101 
102 	/*
103 	 * If the caller wants the SKB, then don't hide any problems, the
104 	 * caller might access the response buffer which will be NULL if
105 	 * the command failed.
106 	 */
107 	if (cmd->flags & CMD_WANT_SKB)
108 		return ret;
109 
110 	/* Silently ignore failures if RFKILL is asserted */
111 	if (!ret || ret == -ERFKILL)
112 		return 0;
113 	return ret;
114 }
115 
116 int iwl_mvm_send_cmd_pdu(struct iwl_mvm *mvm, u32 id,
117 			 u32 flags, u16 len, const void *data)
118 {
119 	struct iwl_host_cmd cmd = {
120 		.id = id,
121 		.len = { len, },
122 		.data = { data, },
123 		.flags = flags,
124 	};
125 
126 	return iwl_mvm_send_cmd(mvm, &cmd);
127 }
128 
129 /*
130  * We assume that the caller set the status to the success value
131  */
132 int iwl_mvm_send_cmd_status(struct iwl_mvm *mvm, struct iwl_host_cmd *cmd,
133 			    u32 *status)
134 {
135 	struct iwl_rx_packet *pkt;
136 	struct iwl_cmd_response *resp;
137 	int ret, resp_len;
138 
139 	lockdep_assert_held(&mvm->mutex);
140 
141 #if defined(CONFIG_IWLWIFI_DEBUGFS) && defined(CONFIG_PM_SLEEP)
142 	if (WARN_ON(mvm->d3_test_active))
143 		return -EIO;
144 #endif
145 
146 	/*
147 	 * Only synchronous commands can wait for status,
148 	 * we use WANT_SKB so the caller can't.
149 	 */
150 	if (WARN_ONCE(cmd->flags & (CMD_ASYNC | CMD_WANT_SKB),
151 		      "cmd flags %x", cmd->flags))
152 		return -EINVAL;
153 
154 	cmd->flags |= CMD_WANT_SKB;
155 
156 	ret = iwl_trans_send_cmd(mvm->trans, cmd);
157 	if (ret == -ERFKILL) {
158 		/*
159 		 * The command failed because of RFKILL, don't update
160 		 * the status, leave it as success and return 0.
161 		 */
162 		return 0;
163 	} else if (ret) {
164 		return ret;
165 	}
166 
167 	pkt = cmd->resp_pkt;
168 
169 	resp_len = iwl_rx_packet_payload_len(pkt);
170 	if (WARN_ON_ONCE(resp_len != sizeof(*resp))) {
171 		ret = -EIO;
172 		goto out_free_resp;
173 	}
174 
175 	resp = (void *)pkt->data;
176 	*status = le32_to_cpu(resp->status);
177  out_free_resp:
178 	iwl_free_resp(cmd);
179 	return ret;
180 }
181 
182 /*
183  * We assume that the caller set the status to the sucess value
184  */
185 int iwl_mvm_send_cmd_pdu_status(struct iwl_mvm *mvm, u32 id, u16 len,
186 				const void *data, u32 *status)
187 {
188 	struct iwl_host_cmd cmd = {
189 		.id = id,
190 		.len = { len, },
191 		.data = { data, },
192 	};
193 
194 	return iwl_mvm_send_cmd_status(mvm, &cmd, status);
195 }
196 
197 #define IWL_DECLARE_RATE_INFO(r) \
198 	[IWL_RATE_##r##M_INDEX] = IWL_RATE_##r##M_PLCP
199 
200 /*
201  * Translate from fw_rate_index (IWL_RATE_XXM_INDEX) to PLCP
202  */
203 static const u8 fw_rate_idx_to_plcp[IWL_RATE_COUNT] = {
204 	IWL_DECLARE_RATE_INFO(1),
205 	IWL_DECLARE_RATE_INFO(2),
206 	IWL_DECLARE_RATE_INFO(5),
207 	IWL_DECLARE_RATE_INFO(11),
208 	IWL_DECLARE_RATE_INFO(6),
209 	IWL_DECLARE_RATE_INFO(9),
210 	IWL_DECLARE_RATE_INFO(12),
211 	IWL_DECLARE_RATE_INFO(18),
212 	IWL_DECLARE_RATE_INFO(24),
213 	IWL_DECLARE_RATE_INFO(36),
214 	IWL_DECLARE_RATE_INFO(48),
215 	IWL_DECLARE_RATE_INFO(54),
216 };
217 
218 int iwl_mvm_legacy_rate_to_mac80211_idx(u32 rate_n_flags,
219 					enum nl80211_band band)
220 {
221 	int rate = rate_n_flags & RATE_LEGACY_RATE_MSK;
222 	int idx;
223 	int band_offset = 0;
224 
225 	/* Legacy rate format, search for match in table */
226 	if (band == NL80211_BAND_5GHZ)
227 		band_offset = IWL_FIRST_OFDM_RATE;
228 	for (idx = band_offset; idx < IWL_RATE_COUNT_LEGACY; idx++)
229 		if (fw_rate_idx_to_plcp[idx] == rate)
230 			return idx - band_offset;
231 
232 	return -1;
233 }
234 
235 u8 iwl_mvm_mac80211_idx_to_hwrate(int rate_idx)
236 {
237 	/* Get PLCP rate for tx_cmd->rate_n_flags */
238 	return fw_rate_idx_to_plcp[rate_idx];
239 }
240 
241 void iwl_mvm_rx_fw_error(struct iwl_mvm *mvm, struct iwl_rx_cmd_buffer *rxb)
242 {
243 	struct iwl_rx_packet *pkt = rxb_addr(rxb);
244 	struct iwl_error_resp *err_resp = (void *)pkt->data;
245 
246 	IWL_ERR(mvm, "FW Error notification: type 0x%08X cmd_id 0x%02X\n",
247 		le32_to_cpu(err_resp->error_type), err_resp->cmd_id);
248 	IWL_ERR(mvm, "FW Error notification: seq 0x%04X service 0x%08X\n",
249 		le16_to_cpu(err_resp->bad_cmd_seq_num),
250 		le32_to_cpu(err_resp->error_service));
251 	IWL_ERR(mvm, "FW Error notification: timestamp 0x%016llX\n",
252 		le64_to_cpu(err_resp->timestamp));
253 }
254 
255 /*
256  * Returns the first antenna as ANT_[ABC], as defined in iwl-config.h.
257  * The parameter should also be a combination of ANT_[ABC].
258  */
259 u8 first_antenna(u8 mask)
260 {
261 	BUILD_BUG_ON(ANT_A != BIT(0)); /* using ffs is wrong if not */
262 	if (WARN_ON_ONCE(!mask)) /* ffs will return 0 if mask is zeroed */
263 		return BIT(0);
264 	return BIT(ffs(mask) - 1);
265 }
266 
267 /*
268  * Toggles between TX antennas to send the probe request on.
269  * Receives the bitmask of valid TX antennas and the *index* used
270  * for the last TX, and returns the next valid *index* to use.
271  * In order to set it in the tx_cmd, must do BIT(idx).
272  */
273 u8 iwl_mvm_next_antenna(struct iwl_mvm *mvm, u8 valid, u8 last_idx)
274 {
275 	u8 ind = last_idx;
276 	int i;
277 
278 	for (i = 0; i < MAX_ANT_NUM; i++) {
279 		ind = (ind + 1) % MAX_ANT_NUM;
280 		if (valid & BIT(ind))
281 			return ind;
282 	}
283 
284 	WARN_ONCE(1, "Failed to toggle between antennas 0x%x", valid);
285 	return last_idx;
286 }
287 
288 #define FW_SYSASSERT_CPU_MASK 0xf0000000
289 static const struct {
290 	const char *name;
291 	u8 num;
292 } advanced_lookup[] = {
293 	{ "NMI_INTERRUPT_WDG", 0x34 },
294 	{ "SYSASSERT", 0x35 },
295 	{ "UCODE_VERSION_MISMATCH", 0x37 },
296 	{ "BAD_COMMAND", 0x38 },
297 	{ "NMI_INTERRUPT_DATA_ACTION_PT", 0x3C },
298 	{ "FATAL_ERROR", 0x3D },
299 	{ "NMI_TRM_HW_ERR", 0x46 },
300 	{ "NMI_INTERRUPT_TRM", 0x4C },
301 	{ "NMI_INTERRUPT_BREAK_POINT", 0x54 },
302 	{ "NMI_INTERRUPT_WDG_RXF_FULL", 0x5C },
303 	{ "NMI_INTERRUPT_WDG_NO_RBD_RXF_FULL", 0x64 },
304 	{ "NMI_INTERRUPT_HOST", 0x66 },
305 	{ "NMI_INTERRUPT_LMAC_FATAL", 0x70 },
306 	{ "NMI_INTERRUPT_UMAC_FATAL", 0x71 },
307 	{ "NMI_INTERRUPT_OTHER_LMAC_FATAL", 0x73 },
308 	{ "NMI_INTERRUPT_ACTION_PT", 0x7C },
309 	{ "NMI_INTERRUPT_UNKNOWN", 0x84 },
310 	{ "NMI_INTERRUPT_INST_ACTION_PT", 0x86 },
311 	{ "ADVANCED_SYSASSERT", 0 },
312 };
313 
314 static const char *desc_lookup(u32 num)
315 {
316 	int i;
317 
318 	for (i = 0; i < ARRAY_SIZE(advanced_lookup) - 1; i++)
319 		if (advanced_lookup[i].num == (num & ~FW_SYSASSERT_CPU_MASK))
320 			return advanced_lookup[i].name;
321 
322 	/* No entry matches 'num', so it is the last: ADVANCED_SYSASSERT */
323 	return advanced_lookup[i].name;
324 }
325 
326 /*
327  * Note: This structure is read from the device with IO accesses,
328  * and the reading already does the endian conversion. As it is
329  * read with u32-sized accesses, any members with a different size
330  * need to be ordered correctly though!
331  */
332 struct iwl_error_event_table_v1 {
333 	u32 valid;		/* (nonzero) valid, (0) log is empty */
334 	u32 error_id;		/* type of error */
335 	u32 pc;			/* program counter */
336 	u32 blink1;		/* branch link */
337 	u32 blink2;		/* branch link */
338 	u32 ilink1;		/* interrupt link */
339 	u32 ilink2;		/* interrupt link */
340 	u32 data1;		/* error-specific data */
341 	u32 data2;		/* error-specific data */
342 	u32 data3;		/* error-specific data */
343 	u32 bcon_time;		/* beacon timer */
344 	u32 tsf_low;		/* network timestamp function timer */
345 	u32 tsf_hi;		/* network timestamp function timer */
346 	u32 gp1;		/* GP1 timer register */
347 	u32 gp2;		/* GP2 timer register */
348 	u32 gp3;		/* GP3 timer register */
349 	u32 ucode_ver;		/* uCode version */
350 	u32 hw_ver;		/* HW Silicon version */
351 	u32 brd_ver;		/* HW board version */
352 	u32 log_pc;		/* log program counter */
353 	u32 frame_ptr;		/* frame pointer */
354 	u32 stack_ptr;		/* stack pointer */
355 	u32 hcmd;		/* last host command header */
356 	u32 isr0;		/* isr status register LMPM_NIC_ISR0:
357 				 * rxtx_flag */
358 	u32 isr1;		/* isr status register LMPM_NIC_ISR1:
359 				 * host_flag */
360 	u32 isr2;		/* isr status register LMPM_NIC_ISR2:
361 				 * enc_flag */
362 	u32 isr3;		/* isr status register LMPM_NIC_ISR3:
363 				 * time_flag */
364 	u32 isr4;		/* isr status register LMPM_NIC_ISR4:
365 				 * wico interrupt */
366 	u32 isr_pref;		/* isr status register LMPM_NIC_PREF_STAT */
367 	u32 wait_event;		/* wait event() caller address */
368 	u32 l2p_control;	/* L2pControlField */
369 	u32 l2p_duration;	/* L2pDurationField */
370 	u32 l2p_mhvalid;	/* L2pMhValidBits */
371 	u32 l2p_addr_match;	/* L2pAddrMatchStat */
372 	u32 lmpm_pmg_sel;	/* indicate which clocks are turned on
373 				 * (LMPM_PMG_SEL) */
374 	u32 u_timestamp;	/* indicate when the date and time of the
375 				 * compilation */
376 	u32 flow_handler;	/* FH read/write pointers, RX credit */
377 } __packed /* LOG_ERROR_TABLE_API_S_VER_1 */;
378 
379 struct iwl_error_event_table {
380 	u32 valid;		/* (nonzero) valid, (0) log is empty */
381 	u32 error_id;		/* type of error */
382 	u32 trm_hw_status0;	/* TRM HW status */
383 	u32 trm_hw_status1;	/* TRM HW status */
384 	u32 blink2;		/* branch link */
385 	u32 ilink1;		/* interrupt link */
386 	u32 ilink2;		/* interrupt link */
387 	u32 data1;		/* error-specific data */
388 	u32 data2;		/* error-specific data */
389 	u32 data3;		/* error-specific data */
390 	u32 bcon_time;		/* beacon timer */
391 	u32 tsf_low;		/* network timestamp function timer */
392 	u32 tsf_hi;		/* network timestamp function timer */
393 	u32 gp1;		/* GP1 timer register */
394 	u32 gp2;		/* GP2 timer register */
395 	u32 fw_rev_type;	/* firmware revision type */
396 	u32 major;		/* uCode version major */
397 	u32 minor;		/* uCode version minor */
398 	u32 hw_ver;		/* HW Silicon version */
399 	u32 brd_ver;		/* HW board version */
400 	u32 log_pc;		/* log program counter */
401 	u32 frame_ptr;		/* frame pointer */
402 	u32 stack_ptr;		/* stack pointer */
403 	u32 hcmd;		/* last host command header */
404 	u32 isr0;		/* isr status register LMPM_NIC_ISR0:
405 				 * rxtx_flag */
406 	u32 isr1;		/* isr status register LMPM_NIC_ISR1:
407 				 * host_flag */
408 	u32 isr2;		/* isr status register LMPM_NIC_ISR2:
409 				 * enc_flag */
410 	u32 isr3;		/* isr status register LMPM_NIC_ISR3:
411 				 * time_flag */
412 	u32 isr4;		/* isr status register LMPM_NIC_ISR4:
413 				 * wico interrupt */
414 	u32 last_cmd_id;	/* last HCMD id handled by the firmware */
415 	u32 wait_event;		/* wait event() caller address */
416 	u32 l2p_control;	/* L2pControlField */
417 	u32 l2p_duration;	/* L2pDurationField */
418 	u32 l2p_mhvalid;	/* L2pMhValidBits */
419 	u32 l2p_addr_match;	/* L2pAddrMatchStat */
420 	u32 lmpm_pmg_sel;	/* indicate which clocks are turned on
421 				 * (LMPM_PMG_SEL) */
422 	u32 u_timestamp;	/* indicate when the date and time of the
423 				 * compilation */
424 	u32 flow_handler;	/* FH read/write pointers, RX credit */
425 } __packed /* LOG_ERROR_TABLE_API_S_VER_3 */;
426 
427 /*
428  * UMAC error struct - relevant starting from family 8000 chip.
429  * Note: This structure is read from the device with IO accesses,
430  * and the reading already does the endian conversion. As it is
431  * read with u32-sized accesses, any members with a different size
432  * need to be ordered correctly though!
433  */
434 struct iwl_umac_error_event_table {
435 	u32 valid;		/* (nonzero) valid, (0) log is empty */
436 	u32 error_id;		/* type of error */
437 	u32 blink1;		/* branch link */
438 	u32 blink2;		/* branch link */
439 	u32 ilink1;		/* interrupt link */
440 	u32 ilink2;		/* interrupt link */
441 	u32 data1;		/* error-specific data */
442 	u32 data2;		/* error-specific data */
443 	u32 data3;		/* error-specific data */
444 	u32 umac_major;
445 	u32 umac_minor;
446 	u32 frame_pointer;	/* core register 27*/
447 	u32 stack_pointer;	/* core register 28 */
448 	u32 cmd_header;		/* latest host cmd sent to UMAC */
449 	u32 nic_isr_pref;	/* ISR status register */
450 } __packed;
451 
452 #define ERROR_START_OFFSET  (1 * sizeof(u32))
453 #define ERROR_ELEM_SIZE     (7 * sizeof(u32))
454 
455 static void iwl_mvm_dump_umac_error_log(struct iwl_mvm *mvm)
456 {
457 	struct iwl_trans *trans = mvm->trans;
458 	struct iwl_umac_error_event_table table;
459 
460 	if (!mvm->support_umac_log)
461 		return;
462 
463 	iwl_trans_read_mem_bytes(trans, mvm->umac_error_event_table, &table,
464 				 sizeof(table));
465 
466 	if (table.valid)
467 		mvm->fwrt.dump.umac_err_id = table.error_id;
468 
469 	if (ERROR_START_OFFSET <= table.valid * ERROR_ELEM_SIZE) {
470 		IWL_ERR(trans, "Start IWL Error Log Dump:\n");
471 		IWL_ERR(trans, "Status: 0x%08lX, count: %d\n",
472 			mvm->status, table.valid);
473 	}
474 
475 	IWL_ERR(mvm, "0x%08X | %s\n", table.error_id,
476 		desc_lookup(table.error_id));
477 	IWL_ERR(mvm, "0x%08X | umac branchlink1\n", table.blink1);
478 	IWL_ERR(mvm, "0x%08X | umac branchlink2\n", table.blink2);
479 	IWL_ERR(mvm, "0x%08X | umac interruptlink1\n", table.ilink1);
480 	IWL_ERR(mvm, "0x%08X | umac interruptlink2\n", table.ilink2);
481 	IWL_ERR(mvm, "0x%08X | umac data1\n", table.data1);
482 	IWL_ERR(mvm, "0x%08X | umac data2\n", table.data2);
483 	IWL_ERR(mvm, "0x%08X | umac data3\n", table.data3);
484 	IWL_ERR(mvm, "0x%08X | umac major\n", table.umac_major);
485 	IWL_ERR(mvm, "0x%08X | umac minor\n", table.umac_minor);
486 	IWL_ERR(mvm, "0x%08X | frame pointer\n", table.frame_pointer);
487 	IWL_ERR(mvm, "0x%08X | stack pointer\n", table.stack_pointer);
488 	IWL_ERR(mvm, "0x%08X | last host cmd\n", table.cmd_header);
489 	IWL_ERR(mvm, "0x%08X | isr status reg\n", table.nic_isr_pref);
490 }
491 
492 static void iwl_mvm_dump_lmac_error_log(struct iwl_mvm *mvm, u8 lmac_num)
493 {
494 	struct iwl_trans *trans = mvm->trans;
495 	struct iwl_error_event_table table;
496 	u32 val, base = mvm->error_event_table[lmac_num];
497 
498 	if (mvm->fwrt.cur_fw_img == IWL_UCODE_INIT) {
499 		if (!base)
500 			base = mvm->fw->init_errlog_ptr;
501 	} else {
502 		if (!base)
503 			base = mvm->fw->inst_errlog_ptr;
504 	}
505 
506 	if (base < 0x400000) {
507 		IWL_ERR(mvm,
508 			"Not valid error log pointer 0x%08X for %s uCode\n",
509 			base,
510 			(mvm->fwrt.cur_fw_img == IWL_UCODE_INIT)
511 			? "Init" : "RT");
512 		return;
513 	}
514 
515 	/* check if there is a HW error */
516 	val = iwl_trans_read_mem32(trans, base);
517 	if (((val & ~0xf) == 0xa5a5a5a0) || ((val & ~0xf) == 0x5a5a5a50)) {
518 		int err;
519 
520 		IWL_ERR(trans, "HW error, resetting before reading\n");
521 
522 		/* reset the device */
523 		iwl_trans_sw_reset(trans);
524 
525 		/* set INIT_DONE flag */
526 		iwl_set_bit(trans, CSR_GP_CNTRL,
527 			    BIT(trans->cfg->csr->flag_init_done));
528 
529 		/* and wait for clock stabilization */
530 		if (trans->cfg->device_family == IWL_DEVICE_FAMILY_8000)
531 			udelay(2);
532 
533 		err = iwl_poll_bit(trans, CSR_GP_CNTRL,
534 				   BIT(trans->cfg->csr->flag_mac_clock_ready),
535 				   BIT(trans->cfg->csr->flag_mac_clock_ready),
536 				   25000);
537 		if (err < 0) {
538 			IWL_DEBUG_INFO(trans,
539 				       "Failed to reset the card for the dump\n");
540 			return;
541 		}
542 	}
543 
544 	iwl_trans_read_mem_bytes(trans, base, &table, sizeof(table));
545 
546 	if (table.valid)
547 		mvm->fwrt.dump.lmac_err_id[lmac_num] = table.error_id;
548 
549 	if (ERROR_START_OFFSET <= table.valid * ERROR_ELEM_SIZE) {
550 		IWL_ERR(trans, "Start IWL Error Log Dump:\n");
551 		IWL_ERR(trans, "Status: 0x%08lX, count: %d\n",
552 			mvm->status, table.valid);
553 	}
554 
555 	/* Do not change this output - scripts rely on it */
556 
557 	IWL_ERR(mvm, "Loaded firmware version: %s\n", mvm->fw->fw_version);
558 
559 	IWL_ERR(mvm, "0x%08X | %-28s\n", table.error_id,
560 		desc_lookup(table.error_id));
561 	IWL_ERR(mvm, "0x%08X | trm_hw_status0\n", table.trm_hw_status0);
562 	IWL_ERR(mvm, "0x%08X | trm_hw_status1\n", table.trm_hw_status1);
563 	IWL_ERR(mvm, "0x%08X | branchlink2\n", table.blink2);
564 	IWL_ERR(mvm, "0x%08X | interruptlink1\n", table.ilink1);
565 	IWL_ERR(mvm, "0x%08X | interruptlink2\n", table.ilink2);
566 	IWL_ERR(mvm, "0x%08X | data1\n", table.data1);
567 	IWL_ERR(mvm, "0x%08X | data2\n", table.data2);
568 	IWL_ERR(mvm, "0x%08X | data3\n", table.data3);
569 	IWL_ERR(mvm, "0x%08X | beacon time\n", table.bcon_time);
570 	IWL_ERR(mvm, "0x%08X | tsf low\n", table.tsf_low);
571 	IWL_ERR(mvm, "0x%08X | tsf hi\n", table.tsf_hi);
572 	IWL_ERR(mvm, "0x%08X | time gp1\n", table.gp1);
573 	IWL_ERR(mvm, "0x%08X | time gp2\n", table.gp2);
574 	IWL_ERR(mvm, "0x%08X | uCode revision type\n", table.fw_rev_type);
575 	IWL_ERR(mvm, "0x%08X | uCode version major\n", table.major);
576 	IWL_ERR(mvm, "0x%08X | uCode version minor\n", table.minor);
577 	IWL_ERR(mvm, "0x%08X | hw version\n", table.hw_ver);
578 	IWL_ERR(mvm, "0x%08X | board version\n", table.brd_ver);
579 	IWL_ERR(mvm, "0x%08X | hcmd\n", table.hcmd);
580 	IWL_ERR(mvm, "0x%08X | isr0\n", table.isr0);
581 	IWL_ERR(mvm, "0x%08X | isr1\n", table.isr1);
582 	IWL_ERR(mvm, "0x%08X | isr2\n", table.isr2);
583 	IWL_ERR(mvm, "0x%08X | isr3\n", table.isr3);
584 	IWL_ERR(mvm, "0x%08X | isr4\n", table.isr4);
585 	IWL_ERR(mvm, "0x%08X | last cmd Id\n", table.last_cmd_id);
586 	IWL_ERR(mvm, "0x%08X | wait_event\n", table.wait_event);
587 	IWL_ERR(mvm, "0x%08X | l2p_control\n", table.l2p_control);
588 	IWL_ERR(mvm, "0x%08X | l2p_duration\n", table.l2p_duration);
589 	IWL_ERR(mvm, "0x%08X | l2p_mhvalid\n", table.l2p_mhvalid);
590 	IWL_ERR(mvm, "0x%08X | l2p_addr_match\n", table.l2p_addr_match);
591 	IWL_ERR(mvm, "0x%08X | lmpm_pmg_sel\n", table.lmpm_pmg_sel);
592 	IWL_ERR(mvm, "0x%08X | timestamp\n", table.u_timestamp);
593 	IWL_ERR(mvm, "0x%08X | flow_handler\n", table.flow_handler);
594 }
595 
596 void iwl_mvm_dump_nic_error_log(struct iwl_mvm *mvm)
597 {
598 	if (!test_bit(STATUS_DEVICE_ENABLED, &mvm->trans->status)) {
599 		IWL_ERR(mvm,
600 			"DEVICE_ENABLED bit is not set. Aborting dump.\n");
601 		return;
602 	}
603 
604 	iwl_mvm_dump_lmac_error_log(mvm, 0);
605 
606 	if (mvm->error_event_table[1])
607 		iwl_mvm_dump_lmac_error_log(mvm, 1);
608 
609 	iwl_mvm_dump_umac_error_log(mvm);
610 }
611 
612 int iwl_mvm_reconfig_scd(struct iwl_mvm *mvm, int queue, int fifo, int sta_id,
613 			 int tid, int frame_limit, u16 ssn)
614 {
615 	struct iwl_scd_txq_cfg_cmd cmd = {
616 		.scd_queue = queue,
617 		.action = SCD_CFG_ENABLE_QUEUE,
618 		.window = frame_limit,
619 		.sta_id = sta_id,
620 		.ssn = cpu_to_le16(ssn),
621 		.tx_fifo = fifo,
622 		.aggregate = (queue >= IWL_MVM_DQA_MIN_DATA_QUEUE ||
623 			      queue == IWL_MVM_DQA_BSS_CLIENT_QUEUE),
624 		.tid = tid,
625 	};
626 	int ret;
627 
628 	if (WARN_ON(iwl_mvm_has_new_tx_api(mvm)))
629 		return -EINVAL;
630 
631 	if (WARN(mvm->queue_info[queue].tid_bitmap == 0,
632 		 "Trying to reconfig unallocated queue %d\n", queue))
633 		return -ENXIO;
634 
635 	IWL_DEBUG_TX_QUEUES(mvm, "Reconfig SCD for TXQ #%d\n", queue);
636 
637 	ret = iwl_mvm_send_cmd_pdu(mvm, SCD_QUEUE_CFG, 0, sizeof(cmd), &cmd);
638 	WARN_ONCE(ret, "Failed to re-configure queue %d on FIFO %d, ret=%d\n",
639 		  queue, fifo, ret);
640 
641 	return ret;
642 }
643 
644 /**
645  * iwl_mvm_send_lq_cmd() - Send link quality command
646  * @sync: This command can be sent synchronously.
647  *
648  * The link quality command is sent as the last step of station creation.
649  * This is the special case in which init is set and we call a callback in
650  * this case to clear the state indicating that station creation is in
651  * progress.
652  */
653 int iwl_mvm_send_lq_cmd(struct iwl_mvm *mvm, struct iwl_lq_cmd *lq, bool sync)
654 {
655 	struct iwl_host_cmd cmd = {
656 		.id = LQ_CMD,
657 		.len = { sizeof(struct iwl_lq_cmd), },
658 		.flags = sync ? 0 : CMD_ASYNC,
659 		.data = { lq, },
660 	};
661 
662 	if (WARN_ON(lq->sta_id == IWL_MVM_INVALID_STA ||
663 		    iwl_mvm_has_tlc_offload(mvm)))
664 		return -EINVAL;
665 
666 	return iwl_mvm_send_cmd(mvm, &cmd);
667 }
668 
669 /**
670  * iwl_mvm_update_smps - Get a request to change the SMPS mode
671  * @req_type: The part of the driver who call for a change.
672  * @smps_requests: The request to change the SMPS mode.
673  *
674  * Get a requst to change the SMPS mode,
675  * and change it according to all other requests in the driver.
676  */
677 void iwl_mvm_update_smps(struct iwl_mvm *mvm, struct ieee80211_vif *vif,
678 			 enum iwl_mvm_smps_type_request req_type,
679 			 enum ieee80211_smps_mode smps_request)
680 {
681 	struct iwl_mvm_vif *mvmvif;
682 	enum ieee80211_smps_mode smps_mode;
683 	int i;
684 
685 	lockdep_assert_held(&mvm->mutex);
686 
687 	/* SMPS is irrelevant for NICs that don't have at least 2 RX antenna */
688 	if (num_of_ant(iwl_mvm_get_valid_rx_ant(mvm)) == 1)
689 		return;
690 
691 	if (vif->type == NL80211_IFTYPE_AP)
692 		smps_mode = IEEE80211_SMPS_OFF;
693 	else
694 		smps_mode = IEEE80211_SMPS_AUTOMATIC;
695 
696 	mvmvif = iwl_mvm_vif_from_mac80211(vif);
697 	mvmvif->smps_requests[req_type] = smps_request;
698 	for (i = 0; i < NUM_IWL_MVM_SMPS_REQ; i++) {
699 		if (mvmvif->smps_requests[i] == IEEE80211_SMPS_STATIC) {
700 			smps_mode = IEEE80211_SMPS_STATIC;
701 			break;
702 		}
703 		if (mvmvif->smps_requests[i] == IEEE80211_SMPS_DYNAMIC)
704 			smps_mode = IEEE80211_SMPS_DYNAMIC;
705 	}
706 
707 	ieee80211_request_smps(vif, smps_mode);
708 }
709 
710 int iwl_mvm_request_statistics(struct iwl_mvm *mvm, bool clear)
711 {
712 	struct iwl_statistics_cmd scmd = {
713 		.flags = clear ? cpu_to_le32(IWL_STATISTICS_FLG_CLEAR) : 0,
714 	};
715 	struct iwl_host_cmd cmd = {
716 		.id = STATISTICS_CMD,
717 		.len[0] = sizeof(scmd),
718 		.data[0] = &scmd,
719 		.flags = CMD_WANT_SKB,
720 	};
721 	int ret;
722 
723 	ret = iwl_mvm_send_cmd(mvm, &cmd);
724 	if (ret)
725 		return ret;
726 
727 	iwl_mvm_handle_rx_statistics(mvm, cmd.resp_pkt);
728 	iwl_free_resp(&cmd);
729 
730 	if (clear)
731 		iwl_mvm_accu_radio_stats(mvm);
732 
733 	return 0;
734 }
735 
736 void iwl_mvm_accu_radio_stats(struct iwl_mvm *mvm)
737 {
738 	mvm->accu_radio_stats.rx_time += mvm->radio_stats.rx_time;
739 	mvm->accu_radio_stats.tx_time += mvm->radio_stats.tx_time;
740 	mvm->accu_radio_stats.on_time_rf += mvm->radio_stats.on_time_rf;
741 	mvm->accu_radio_stats.on_time_scan += mvm->radio_stats.on_time_scan;
742 }
743 
744 static void iwl_mvm_diversity_iter(void *_data, u8 *mac,
745 				   struct ieee80211_vif *vif)
746 {
747 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
748 	bool *result = _data;
749 	int i;
750 
751 	for (i = 0; i < NUM_IWL_MVM_SMPS_REQ; i++) {
752 		if (mvmvif->smps_requests[i] == IEEE80211_SMPS_STATIC ||
753 		    mvmvif->smps_requests[i] == IEEE80211_SMPS_DYNAMIC)
754 			*result = false;
755 	}
756 }
757 
758 bool iwl_mvm_rx_diversity_allowed(struct iwl_mvm *mvm)
759 {
760 	bool result = true;
761 
762 	lockdep_assert_held(&mvm->mutex);
763 
764 	if (num_of_ant(iwl_mvm_get_valid_rx_ant(mvm)) == 1)
765 		return false;
766 
767 	if (mvm->cfg->rx_with_siso_diversity)
768 		return false;
769 
770 	ieee80211_iterate_active_interfaces_atomic(
771 			mvm->hw, IEEE80211_IFACE_ITER_NORMAL,
772 			iwl_mvm_diversity_iter, &result);
773 
774 	return result;
775 }
776 
777 void iwl_mvm_send_low_latency_cmd(struct iwl_mvm *mvm,
778 				  bool low_latency, u16 mac_id)
779 {
780 	struct iwl_mac_low_latency_cmd cmd = {
781 		.mac_id = cpu_to_le32(mac_id)
782 	};
783 
784 	if (!fw_has_capa(&mvm->fw->ucode_capa,
785 			 IWL_UCODE_TLV_CAPA_DYNAMIC_QUOTA))
786 		return;
787 
788 	if (low_latency) {
789 		/* currently we don't care about the direction */
790 		cmd.low_latency_rx = 1;
791 		cmd.low_latency_tx = 1;
792 	}
793 
794 	if (iwl_mvm_send_cmd_pdu(mvm, iwl_cmd_id(LOW_LATENCY_CMD,
795 						 MAC_CONF_GROUP, 0),
796 				 0, sizeof(cmd), &cmd))
797 		IWL_ERR(mvm, "Failed to send low latency command\n");
798 }
799 
800 int iwl_mvm_update_low_latency(struct iwl_mvm *mvm, struct ieee80211_vif *vif,
801 			       bool low_latency,
802 			       enum iwl_mvm_low_latency_cause cause)
803 {
804 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
805 	int res;
806 	bool prev;
807 
808 	lockdep_assert_held(&mvm->mutex);
809 
810 	prev = iwl_mvm_vif_low_latency(mvmvif);
811 	iwl_mvm_vif_set_low_latency(mvmvif, low_latency, cause);
812 
813 	low_latency = iwl_mvm_vif_low_latency(mvmvif);
814 
815 	if (low_latency == prev)
816 		return 0;
817 
818 	iwl_mvm_send_low_latency_cmd(mvm, low_latency, mvmvif->id);
819 
820 	res = iwl_mvm_update_quotas(mvm, false, NULL);
821 	if (res)
822 		return res;
823 
824 	iwl_mvm_bt_coex_vif_change(mvm);
825 
826 	return iwl_mvm_power_update_mac(mvm);
827 }
828 
829 struct iwl_mvm_low_latency_iter {
830 	bool result;
831 	bool result_per_band[NUM_NL80211_BANDS];
832 };
833 
834 static void iwl_mvm_ll_iter(void *_data, u8 *mac, struct ieee80211_vif *vif)
835 {
836 	struct iwl_mvm_low_latency_iter *result = _data;
837 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
838 	enum nl80211_band band;
839 
840 	if (iwl_mvm_vif_low_latency(mvmvif)) {
841 		result->result = true;
842 
843 		if (!mvmvif->phy_ctxt)
844 			return;
845 
846 		band = mvmvif->phy_ctxt->channel->band;
847 		result->result_per_band[band] = true;
848 	}
849 }
850 
851 bool iwl_mvm_low_latency(struct iwl_mvm *mvm)
852 {
853 	struct iwl_mvm_low_latency_iter data = {};
854 
855 	ieee80211_iterate_active_interfaces_atomic(
856 			mvm->hw, IEEE80211_IFACE_ITER_NORMAL,
857 			iwl_mvm_ll_iter, &data);
858 
859 	return data.result;
860 }
861 
862 bool iwl_mvm_low_latency_band(struct iwl_mvm *mvm, enum nl80211_band band)
863 {
864 	struct iwl_mvm_low_latency_iter data = {};
865 
866 	ieee80211_iterate_active_interfaces_atomic(
867 			mvm->hw, IEEE80211_IFACE_ITER_NORMAL,
868 			iwl_mvm_ll_iter, &data);
869 
870 	return data.result_per_band[band];
871 }
872 
873 struct iwl_bss_iter_data {
874 	struct ieee80211_vif *vif;
875 	bool error;
876 };
877 
878 static void iwl_mvm_bss_iface_iterator(void *_data, u8 *mac,
879 				       struct ieee80211_vif *vif)
880 {
881 	struct iwl_bss_iter_data *data = _data;
882 
883 	if (vif->type != NL80211_IFTYPE_STATION || vif->p2p)
884 		return;
885 
886 	if (data->vif) {
887 		data->error = true;
888 		return;
889 	}
890 
891 	data->vif = vif;
892 }
893 
894 struct ieee80211_vif *iwl_mvm_get_bss_vif(struct iwl_mvm *mvm)
895 {
896 	struct iwl_bss_iter_data bss_iter_data = {};
897 
898 	ieee80211_iterate_active_interfaces_atomic(
899 		mvm->hw, IEEE80211_IFACE_ITER_NORMAL,
900 		iwl_mvm_bss_iface_iterator, &bss_iter_data);
901 
902 	if (bss_iter_data.error) {
903 		IWL_ERR(mvm, "More than one managed interface active!\n");
904 		return ERR_PTR(-EINVAL);
905 	}
906 
907 	return bss_iter_data.vif;
908 }
909 
910 struct iwl_sta_iter_data {
911 	bool assoc;
912 };
913 
914 static void iwl_mvm_sta_iface_iterator(void *_data, u8 *mac,
915 				       struct ieee80211_vif *vif)
916 {
917 	struct iwl_sta_iter_data *data = _data;
918 
919 	if (vif->type != NL80211_IFTYPE_STATION)
920 		return;
921 
922 	if (vif->bss_conf.assoc)
923 		data->assoc = true;
924 }
925 
926 bool iwl_mvm_is_vif_assoc(struct iwl_mvm *mvm)
927 {
928 	struct iwl_sta_iter_data data = {
929 		.assoc = false,
930 	};
931 
932 	ieee80211_iterate_active_interfaces_atomic(mvm->hw,
933 						   IEEE80211_IFACE_ITER_NORMAL,
934 						   iwl_mvm_sta_iface_iterator,
935 						   &data);
936 	return data.assoc;
937 }
938 
939 unsigned int iwl_mvm_get_wd_timeout(struct iwl_mvm *mvm,
940 				    struct ieee80211_vif *vif,
941 				    bool tdls, bool cmd_q)
942 {
943 	struct iwl_fw_dbg_trigger_tlv *trigger;
944 	struct iwl_fw_dbg_trigger_txq_timer *txq_timer;
945 	unsigned int default_timeout =
946 		cmd_q ? IWL_DEF_WD_TIMEOUT : mvm->cfg->base_params->wd_timeout;
947 
948 	if (!iwl_fw_dbg_trigger_enabled(mvm->fw, FW_DBG_TRIGGER_TXQ_TIMERS)) {
949 		/*
950 		 * We can't know when the station is asleep or awake, so we
951 		 * must disable the queue hang detection.
952 		 */
953 		if (fw_has_capa(&mvm->fw->ucode_capa,
954 				IWL_UCODE_TLV_CAPA_STA_PM_NOTIF) &&
955 		    vif && vif->type == NL80211_IFTYPE_AP)
956 			return IWL_WATCHDOG_DISABLED;
957 		return iwlmvm_mod_params.tfd_q_hang_detect ?
958 			default_timeout : IWL_WATCHDOG_DISABLED;
959 	}
960 
961 	trigger = iwl_fw_dbg_get_trigger(mvm->fw, FW_DBG_TRIGGER_TXQ_TIMERS);
962 	txq_timer = (void *)trigger->data;
963 
964 	if (tdls)
965 		return le32_to_cpu(txq_timer->tdls);
966 
967 	if (cmd_q)
968 		return le32_to_cpu(txq_timer->command_queue);
969 
970 	if (WARN_ON(!vif))
971 		return default_timeout;
972 
973 	switch (ieee80211_vif_type_p2p(vif)) {
974 	case NL80211_IFTYPE_ADHOC:
975 		return le32_to_cpu(txq_timer->ibss);
976 	case NL80211_IFTYPE_STATION:
977 		return le32_to_cpu(txq_timer->bss);
978 	case NL80211_IFTYPE_AP:
979 		return le32_to_cpu(txq_timer->softap);
980 	case NL80211_IFTYPE_P2P_CLIENT:
981 		return le32_to_cpu(txq_timer->p2p_client);
982 	case NL80211_IFTYPE_P2P_GO:
983 		return le32_to_cpu(txq_timer->p2p_go);
984 	case NL80211_IFTYPE_P2P_DEVICE:
985 		return le32_to_cpu(txq_timer->p2p_device);
986 	case NL80211_IFTYPE_MONITOR:
987 		return default_timeout;
988 	default:
989 		WARN_ON(1);
990 		return mvm->cfg->base_params->wd_timeout;
991 	}
992 }
993 
994 void iwl_mvm_connection_loss(struct iwl_mvm *mvm, struct ieee80211_vif *vif,
995 			     const char *errmsg)
996 {
997 	struct iwl_fw_dbg_trigger_tlv *trig;
998 	struct iwl_fw_dbg_trigger_mlme *trig_mlme;
999 
1000 	trig = iwl_fw_dbg_trigger_on(&mvm->fwrt, ieee80211_vif_to_wdev(vif),
1001 				     FW_DBG_TRIGGER_MLME);
1002 	if (!trig)
1003 		goto out;
1004 
1005 	trig_mlme = (void *)trig->data;
1006 
1007 	if (trig_mlme->stop_connection_loss &&
1008 	    --trig_mlme->stop_connection_loss)
1009 		goto out;
1010 
1011 	iwl_fw_dbg_collect_trig(&mvm->fwrt, trig, "%s", errmsg);
1012 
1013 out:
1014 	ieee80211_connection_loss(vif);
1015 }
1016 
1017 void iwl_mvm_event_frame_timeout_callback(struct iwl_mvm *mvm,
1018 					  struct ieee80211_vif *vif,
1019 					  const struct ieee80211_sta *sta,
1020 					  u16 tid)
1021 {
1022 	struct iwl_fw_dbg_trigger_tlv *trig;
1023 	struct iwl_fw_dbg_trigger_ba *ba_trig;
1024 
1025 	trig = iwl_fw_dbg_trigger_on(&mvm->fwrt, ieee80211_vif_to_wdev(vif),
1026 				     FW_DBG_TRIGGER_BA);
1027 	if (!trig)
1028 		return;
1029 
1030 	ba_trig = (void *)trig->data;
1031 
1032 	if (!(le16_to_cpu(ba_trig->frame_timeout) & BIT(tid)))
1033 		return;
1034 
1035 	iwl_fw_dbg_collect_trig(&mvm->fwrt, trig,
1036 				"Frame from %pM timed out, tid %d",
1037 				sta->addr, tid);
1038 }
1039 
1040 u8 iwl_mvm_tcm_load_percentage(u32 airtime, u32 elapsed)
1041 {
1042 	if (!elapsed)
1043 		return 0;
1044 
1045 	return (100 * airtime / elapsed) / USEC_PER_MSEC;
1046 }
1047 
1048 static enum iwl_mvm_traffic_load
1049 iwl_mvm_tcm_load(struct iwl_mvm *mvm, u32 airtime, unsigned long elapsed)
1050 {
1051 	u8 load = iwl_mvm_tcm_load_percentage(airtime, elapsed);
1052 
1053 	if (load > IWL_MVM_TCM_LOAD_HIGH_THRESH)
1054 		return IWL_MVM_TRAFFIC_HIGH;
1055 	if (load > IWL_MVM_TCM_LOAD_MEDIUM_THRESH)
1056 		return IWL_MVM_TRAFFIC_MEDIUM;
1057 
1058 	return IWL_MVM_TRAFFIC_LOW;
1059 }
1060 
1061 struct iwl_mvm_tcm_iter_data {
1062 	struct iwl_mvm *mvm;
1063 	bool any_sent;
1064 };
1065 
1066 static void iwl_mvm_tcm_iter(void *_data, u8 *mac, struct ieee80211_vif *vif)
1067 {
1068 	struct iwl_mvm_tcm_iter_data *data = _data;
1069 	struct iwl_mvm *mvm = data->mvm;
1070 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
1071 	bool low_latency, prev = mvmvif->low_latency & LOW_LATENCY_TRAFFIC;
1072 
1073 	if (mvmvif->id >= NUM_MAC_INDEX_DRIVER)
1074 		return;
1075 
1076 	low_latency = mvm->tcm.result.low_latency[mvmvif->id];
1077 
1078 	if (!mvm->tcm.result.change[mvmvif->id] &&
1079 	    prev == low_latency) {
1080 		iwl_mvm_update_quotas(mvm, false, NULL);
1081 		return;
1082 	}
1083 
1084 	if (prev != low_latency) {
1085 		/* this sends traffic load and updates quota as well */
1086 		iwl_mvm_update_low_latency(mvm, vif, low_latency,
1087 					   LOW_LATENCY_TRAFFIC);
1088 	} else {
1089 		iwl_mvm_update_quotas(mvm, false, NULL);
1090 	}
1091 
1092 	data->any_sent = true;
1093 }
1094 
1095 static void iwl_mvm_tcm_results(struct iwl_mvm *mvm)
1096 {
1097 	struct iwl_mvm_tcm_iter_data data = {
1098 		.mvm = mvm,
1099 		.any_sent = false,
1100 	};
1101 
1102 	mutex_lock(&mvm->mutex);
1103 
1104 	ieee80211_iterate_active_interfaces(
1105 		mvm->hw, IEEE80211_IFACE_ITER_NORMAL,
1106 		iwl_mvm_tcm_iter, &data);
1107 
1108 	if (fw_has_capa(&mvm->fw->ucode_capa, IWL_UCODE_TLV_CAPA_UMAC_SCAN))
1109 		iwl_mvm_config_scan(mvm);
1110 
1111 	mutex_unlock(&mvm->mutex);
1112 }
1113 
1114 static void iwl_mvm_tcm_uapsd_nonagg_detected_wk(struct work_struct *wk)
1115 {
1116 	struct iwl_mvm *mvm;
1117 	struct iwl_mvm_vif *mvmvif;
1118 	struct ieee80211_vif *vif;
1119 
1120 	mvmvif = container_of(wk, struct iwl_mvm_vif,
1121 			      uapsd_nonagg_detected_wk.work);
1122 	vif = container_of((void *)mvmvif, struct ieee80211_vif, drv_priv);
1123 	mvm = mvmvif->mvm;
1124 
1125 	if (mvm->tcm.data[mvmvif->id].opened_rx_ba_sessions)
1126 		return;
1127 
1128 	/* remember that this AP is broken */
1129 	memcpy(mvm->uapsd_noagg_bssids[mvm->uapsd_noagg_bssid_write_idx].addr,
1130 	       vif->bss_conf.bssid, ETH_ALEN);
1131 	mvm->uapsd_noagg_bssid_write_idx++;
1132 	if (mvm->uapsd_noagg_bssid_write_idx >= IWL_MVM_UAPSD_NOAGG_LIST_LEN)
1133 		mvm->uapsd_noagg_bssid_write_idx = 0;
1134 
1135 	iwl_mvm_connection_loss(mvm, vif,
1136 				"AP isn't using AMPDU with uAPSD enabled");
1137 }
1138 
1139 static void iwl_mvm_uapsd_agg_disconnect(struct iwl_mvm *mvm,
1140 					 struct ieee80211_vif *vif)
1141 {
1142 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
1143 
1144 	if (vif->type != NL80211_IFTYPE_STATION)
1145 		return;
1146 
1147 	if (!vif->bss_conf.assoc)
1148 		return;
1149 
1150 	if (!mvmvif->queue_params[IEEE80211_AC_VO].uapsd &&
1151 	    !mvmvif->queue_params[IEEE80211_AC_VI].uapsd &&
1152 	    !mvmvif->queue_params[IEEE80211_AC_BE].uapsd &&
1153 	    !mvmvif->queue_params[IEEE80211_AC_BK].uapsd)
1154 		return;
1155 
1156 	if (mvm->tcm.data[mvmvif->id].uapsd_nonagg_detect.detected)
1157 		return;
1158 
1159 	mvm->tcm.data[mvmvif->id].uapsd_nonagg_detect.detected = true;
1160 	IWL_INFO(mvm,
1161 		 "detected AP should do aggregation but isn't, likely due to U-APSD\n");
1162 	schedule_delayed_work(&mvmvif->uapsd_nonagg_detected_wk, 15 * HZ);
1163 }
1164 
1165 static void iwl_mvm_check_uapsd_agg_expected_tpt(struct iwl_mvm *mvm,
1166 						 unsigned int elapsed,
1167 						 int mac)
1168 {
1169 	u64 bytes = mvm->tcm.data[mac].uapsd_nonagg_detect.rx_bytes;
1170 	u64 tpt;
1171 	unsigned long rate;
1172 	struct ieee80211_vif *vif;
1173 
1174 	rate = ewma_rate_read(&mvm->tcm.data[mac].uapsd_nonagg_detect.rate);
1175 
1176 	if (!rate || mvm->tcm.data[mac].opened_rx_ba_sessions ||
1177 	    mvm->tcm.data[mac].uapsd_nonagg_detect.detected)
1178 		return;
1179 
1180 	if (iwl_mvm_has_new_rx_api(mvm)) {
1181 		tpt = 8 * bytes; /* kbps */
1182 		do_div(tpt, elapsed);
1183 		rate *= 1000; /* kbps */
1184 		if (tpt < 22 * rate / 100)
1185 			return;
1186 	} else {
1187 		/*
1188 		 * the rate here is actually the threshold, in 100Kbps units,
1189 		 * so do the needed conversion from bytes to 100Kbps:
1190 		 * 100kb = bits / (100 * 1000),
1191 		 * 100kbps = 100kb / (msecs / 1000) ==
1192 		 *           (bits / (100 * 1000)) / (msecs / 1000) ==
1193 		 *           bits / (100 * msecs)
1194 		 */
1195 		tpt = (8 * bytes);
1196 		do_div(tpt, elapsed * 100);
1197 		if (tpt < rate)
1198 			return;
1199 	}
1200 
1201 	rcu_read_lock();
1202 	vif = rcu_dereference(mvm->vif_id_to_mac[mac]);
1203 	if (vif)
1204 		iwl_mvm_uapsd_agg_disconnect(mvm, vif);
1205 	rcu_read_unlock();
1206 }
1207 
1208 static void iwl_mvm_tcm_iterator(void *_data, u8 *mac,
1209 				 struct ieee80211_vif *vif)
1210 {
1211 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
1212 	u32 *band = _data;
1213 
1214 	if (!mvmvif->phy_ctxt)
1215 		return;
1216 
1217 	band[mvmvif->id] = mvmvif->phy_ctxt->channel->band;
1218 }
1219 
1220 static unsigned long iwl_mvm_calc_tcm_stats(struct iwl_mvm *mvm,
1221 					    unsigned long ts,
1222 					    bool handle_uapsd)
1223 {
1224 	unsigned int elapsed = jiffies_to_msecs(ts - mvm->tcm.ts);
1225 	unsigned int uapsd_elapsed =
1226 		jiffies_to_msecs(ts - mvm->tcm.uapsd_nonagg_ts);
1227 	u32 total_airtime = 0;
1228 	u32 band_airtime[NUM_NL80211_BANDS] = {0};
1229 	u32 band[NUM_MAC_INDEX_DRIVER] = {0};
1230 	int ac, mac, i;
1231 	bool low_latency = false;
1232 	enum iwl_mvm_traffic_load load, band_load;
1233 	bool handle_ll = time_after(ts, mvm->tcm.ll_ts + MVM_LL_PERIOD);
1234 
1235 	if (handle_ll)
1236 		mvm->tcm.ll_ts = ts;
1237 	if (handle_uapsd)
1238 		mvm->tcm.uapsd_nonagg_ts = ts;
1239 
1240 	mvm->tcm.result.elapsed = elapsed;
1241 
1242 	ieee80211_iterate_active_interfaces_atomic(mvm->hw,
1243 						   IEEE80211_IFACE_ITER_NORMAL,
1244 						   iwl_mvm_tcm_iterator,
1245 						   &band);
1246 
1247 	for (mac = 0; mac < NUM_MAC_INDEX_DRIVER; mac++) {
1248 		struct iwl_mvm_tcm_mac *mdata = &mvm->tcm.data[mac];
1249 		u32 vo_vi_pkts = 0;
1250 		u32 airtime = mdata->rx.airtime + mdata->tx.airtime;
1251 
1252 		total_airtime += airtime;
1253 		band_airtime[band[mac]] += airtime;
1254 
1255 		load = iwl_mvm_tcm_load(mvm, airtime, elapsed);
1256 		mvm->tcm.result.change[mac] = load != mvm->tcm.result.load[mac];
1257 		mvm->tcm.result.load[mac] = load;
1258 		mvm->tcm.result.airtime[mac] = airtime;
1259 
1260 		for (ac = IEEE80211_AC_VO; ac <= IEEE80211_AC_VI; ac++)
1261 			vo_vi_pkts += mdata->rx.pkts[ac] +
1262 				      mdata->tx.pkts[ac];
1263 
1264 		/* enable immediately with enough packets but defer disabling */
1265 		if (vo_vi_pkts > IWL_MVM_TCM_LOWLAT_ENABLE_THRESH)
1266 			mvm->tcm.result.low_latency[mac] = true;
1267 		else if (handle_ll)
1268 			mvm->tcm.result.low_latency[mac] = false;
1269 
1270 		if (handle_ll) {
1271 			/* clear old data */
1272 			memset(&mdata->rx.pkts, 0, sizeof(mdata->rx.pkts));
1273 			memset(&mdata->tx.pkts, 0, sizeof(mdata->tx.pkts));
1274 		}
1275 		low_latency |= mvm->tcm.result.low_latency[mac];
1276 
1277 		if (!mvm->tcm.result.low_latency[mac] && handle_uapsd)
1278 			iwl_mvm_check_uapsd_agg_expected_tpt(mvm, uapsd_elapsed,
1279 							     mac);
1280 		/* clear old data */
1281 		if (handle_uapsd)
1282 			mdata->uapsd_nonagg_detect.rx_bytes = 0;
1283 		memset(&mdata->rx.airtime, 0, sizeof(mdata->rx.airtime));
1284 		memset(&mdata->tx.airtime, 0, sizeof(mdata->tx.airtime));
1285 	}
1286 
1287 	load = iwl_mvm_tcm_load(mvm, total_airtime, elapsed);
1288 	mvm->tcm.result.global_change = load != mvm->tcm.result.global_load;
1289 	mvm->tcm.result.global_load = load;
1290 
1291 	for (i = 0; i < NUM_NL80211_BANDS; i++) {
1292 		band_load = iwl_mvm_tcm_load(mvm, band_airtime[i], elapsed);
1293 		mvm->tcm.result.band_load[i] = band_load;
1294 	}
1295 
1296 	/*
1297 	 * If the current load isn't low we need to force re-evaluation
1298 	 * in the TCM period, so that we can return to low load if there
1299 	 * was no traffic at all (and thus iwl_mvm_recalc_tcm didn't get
1300 	 * triggered by traffic).
1301 	 */
1302 	if (load != IWL_MVM_TRAFFIC_LOW)
1303 		return MVM_TCM_PERIOD;
1304 	/*
1305 	 * If low-latency is active we need to force re-evaluation after
1306 	 * (the longer) MVM_LL_PERIOD, so that we can disable low-latency
1307 	 * when there's no traffic at all.
1308 	 */
1309 	if (low_latency)
1310 		return MVM_LL_PERIOD;
1311 	/*
1312 	 * Otherwise, we don't need to run the work struct because we're
1313 	 * in the default "idle" state - traffic indication is low (which
1314 	 * also covers the "no traffic" case) and low-latency is disabled
1315 	 * so there's no state that may need to be disabled when there's
1316 	 * no traffic at all.
1317 	 *
1318 	 * Note that this has no impact on the regular scheduling of the
1319 	 * updates triggered by traffic - those happen whenever one of the
1320 	 * two timeouts expire (if there's traffic at all.)
1321 	 */
1322 	return 0;
1323 }
1324 
1325 void iwl_mvm_recalc_tcm(struct iwl_mvm *mvm)
1326 {
1327 	unsigned long ts = jiffies;
1328 	bool handle_uapsd =
1329 		time_after(ts, mvm->tcm.uapsd_nonagg_ts +
1330 			       msecs_to_jiffies(IWL_MVM_UAPSD_NONAGG_PERIOD));
1331 
1332 	spin_lock(&mvm->tcm.lock);
1333 	if (mvm->tcm.paused || !time_after(ts, mvm->tcm.ts + MVM_TCM_PERIOD)) {
1334 		spin_unlock(&mvm->tcm.lock);
1335 		return;
1336 	}
1337 	spin_unlock(&mvm->tcm.lock);
1338 
1339 	if (handle_uapsd && iwl_mvm_has_new_rx_api(mvm)) {
1340 		mutex_lock(&mvm->mutex);
1341 		if (iwl_mvm_request_statistics(mvm, true))
1342 			handle_uapsd = false;
1343 		mutex_unlock(&mvm->mutex);
1344 	}
1345 
1346 	spin_lock(&mvm->tcm.lock);
1347 	/* re-check if somebody else won the recheck race */
1348 	if (!mvm->tcm.paused && time_after(ts, mvm->tcm.ts + MVM_TCM_PERIOD)) {
1349 		/* calculate statistics */
1350 		unsigned long work_delay = iwl_mvm_calc_tcm_stats(mvm, ts,
1351 								  handle_uapsd);
1352 
1353 		/* the memset needs to be visible before the timestamp */
1354 		smp_mb();
1355 		mvm->tcm.ts = ts;
1356 		if (work_delay)
1357 			schedule_delayed_work(&mvm->tcm.work, work_delay);
1358 	}
1359 	spin_unlock(&mvm->tcm.lock);
1360 
1361 	iwl_mvm_tcm_results(mvm);
1362 }
1363 
1364 void iwl_mvm_tcm_work(struct work_struct *work)
1365 {
1366 	struct delayed_work *delayed_work = to_delayed_work(work);
1367 	struct iwl_mvm *mvm = container_of(delayed_work, struct iwl_mvm,
1368 					   tcm.work);
1369 
1370 	iwl_mvm_recalc_tcm(mvm);
1371 }
1372 
1373 void iwl_mvm_pause_tcm(struct iwl_mvm *mvm, bool with_cancel)
1374 {
1375 	spin_lock_bh(&mvm->tcm.lock);
1376 	mvm->tcm.paused = true;
1377 	spin_unlock_bh(&mvm->tcm.lock);
1378 	if (with_cancel)
1379 		cancel_delayed_work_sync(&mvm->tcm.work);
1380 }
1381 
1382 void iwl_mvm_resume_tcm(struct iwl_mvm *mvm)
1383 {
1384 	int mac;
1385 	bool low_latency = false;
1386 
1387 	spin_lock_bh(&mvm->tcm.lock);
1388 	mvm->tcm.ts = jiffies;
1389 	mvm->tcm.ll_ts = jiffies;
1390 	for (mac = 0; mac < NUM_MAC_INDEX_DRIVER; mac++) {
1391 		struct iwl_mvm_tcm_mac *mdata = &mvm->tcm.data[mac];
1392 
1393 		memset(&mdata->rx.pkts, 0, sizeof(mdata->rx.pkts));
1394 		memset(&mdata->tx.pkts, 0, sizeof(mdata->tx.pkts));
1395 		memset(&mdata->rx.airtime, 0, sizeof(mdata->rx.airtime));
1396 		memset(&mdata->tx.airtime, 0, sizeof(mdata->tx.airtime));
1397 
1398 		if (mvm->tcm.result.low_latency[mac])
1399 			low_latency = true;
1400 	}
1401 	/* The TCM data needs to be reset before "paused" flag changes */
1402 	smp_mb();
1403 	mvm->tcm.paused = false;
1404 
1405 	/*
1406 	 * if the current load is not low or low latency is active, force
1407 	 * re-evaluation to cover the case of no traffic.
1408 	 */
1409 	if (mvm->tcm.result.global_load > IWL_MVM_TRAFFIC_LOW)
1410 		schedule_delayed_work(&mvm->tcm.work, MVM_TCM_PERIOD);
1411 	else if (low_latency)
1412 		schedule_delayed_work(&mvm->tcm.work, MVM_LL_PERIOD);
1413 
1414 	spin_unlock_bh(&mvm->tcm.lock);
1415 }
1416 
1417 void iwl_mvm_tcm_add_vif(struct iwl_mvm *mvm, struct ieee80211_vif *vif)
1418 {
1419 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
1420 
1421 	INIT_DELAYED_WORK(&mvmvif->uapsd_nonagg_detected_wk,
1422 			  iwl_mvm_tcm_uapsd_nonagg_detected_wk);
1423 }
1424 
1425 void iwl_mvm_tcm_rm_vif(struct iwl_mvm *mvm, struct ieee80211_vif *vif)
1426 {
1427 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
1428 
1429 	cancel_delayed_work_sync(&mvmvif->uapsd_nonagg_detected_wk);
1430 }
1431 
1432 
1433 void iwl_mvm_get_sync_time(struct iwl_mvm *mvm, u32 *gp2, u64 *boottime)
1434 {
1435 	bool ps_disabled;
1436 
1437 	lockdep_assert_held(&mvm->mutex);
1438 
1439 	/* Disable power save when reading GP2 */
1440 	ps_disabled = mvm->ps_disabled;
1441 	if (!ps_disabled) {
1442 		mvm->ps_disabled = true;
1443 		iwl_mvm_power_update_device(mvm);
1444 	}
1445 
1446 	*gp2 = iwl_read_prph(mvm->trans, DEVICE_SYSTEM_TIME_REG);
1447 	*boottime = ktime_get_boot_ns();
1448 
1449 	if (!ps_disabled) {
1450 		mvm->ps_disabled = ps_disabled;
1451 		iwl_mvm_power_update_device(mvm);
1452 	}
1453 }
1454