xref: /openbmc/linux/drivers/net/wireless/intel/iwlwifi/mvm/utils.c (revision b68fc09be48edbc47de1a0f3d42ef8adf6c0ac55)
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%16llX\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 static const struct {
289 	const char *name;
290 	u8 num;
291 } advanced_lookup[] = {
292 	{ "NMI_INTERRUPT_WDG", 0x34 },
293 	{ "SYSASSERT", 0x35 },
294 	{ "UCODE_VERSION_MISMATCH", 0x37 },
295 	{ "BAD_COMMAND", 0x38 },
296 	{ "NMI_INTERRUPT_DATA_ACTION_PT", 0x3C },
297 	{ "FATAL_ERROR", 0x3D },
298 	{ "NMI_TRM_HW_ERR", 0x46 },
299 	{ "NMI_INTERRUPT_TRM", 0x4C },
300 	{ "NMI_INTERRUPT_BREAK_POINT", 0x54 },
301 	{ "NMI_INTERRUPT_WDG_RXF_FULL", 0x5C },
302 	{ "NMI_INTERRUPT_WDG_NO_RBD_RXF_FULL", 0x64 },
303 	{ "NMI_INTERRUPT_HOST", 0x66 },
304 	{ "NMI_INTERRUPT_ACTION_PT", 0x7C },
305 	{ "NMI_INTERRUPT_UNKNOWN", 0x84 },
306 	{ "NMI_INTERRUPT_INST_ACTION_PT", 0x86 },
307 	{ "ADVANCED_SYSASSERT", 0 },
308 };
309 
310 static const char *desc_lookup(u32 num)
311 {
312 	int i;
313 
314 	for (i = 0; i < ARRAY_SIZE(advanced_lookup) - 1; i++)
315 		if (advanced_lookup[i].num == num)
316 			return advanced_lookup[i].name;
317 
318 	/* No entry matches 'num', so it is the last: ADVANCED_SYSASSERT */
319 	return advanced_lookup[i].name;
320 }
321 
322 /*
323  * Note: This structure is read from the device with IO accesses,
324  * and the reading already does the endian conversion. As it is
325  * read with u32-sized accesses, any members with a different size
326  * need to be ordered correctly though!
327  */
328 struct iwl_error_event_table_v1 {
329 	u32 valid;		/* (nonzero) valid, (0) log is empty */
330 	u32 error_id;		/* type of error */
331 	u32 pc;			/* program counter */
332 	u32 blink1;		/* branch link */
333 	u32 blink2;		/* branch link */
334 	u32 ilink1;		/* interrupt link */
335 	u32 ilink2;		/* interrupt link */
336 	u32 data1;		/* error-specific data */
337 	u32 data2;		/* error-specific data */
338 	u32 data3;		/* error-specific data */
339 	u32 bcon_time;		/* beacon timer */
340 	u32 tsf_low;		/* network timestamp function timer */
341 	u32 tsf_hi;		/* network timestamp function timer */
342 	u32 gp1;		/* GP1 timer register */
343 	u32 gp2;		/* GP2 timer register */
344 	u32 gp3;		/* GP3 timer register */
345 	u32 ucode_ver;		/* uCode version */
346 	u32 hw_ver;		/* HW Silicon version */
347 	u32 brd_ver;		/* HW board version */
348 	u32 log_pc;		/* log program counter */
349 	u32 frame_ptr;		/* frame pointer */
350 	u32 stack_ptr;		/* stack pointer */
351 	u32 hcmd;		/* last host command header */
352 	u32 isr0;		/* isr status register LMPM_NIC_ISR0:
353 				 * rxtx_flag */
354 	u32 isr1;		/* isr status register LMPM_NIC_ISR1:
355 				 * host_flag */
356 	u32 isr2;		/* isr status register LMPM_NIC_ISR2:
357 				 * enc_flag */
358 	u32 isr3;		/* isr status register LMPM_NIC_ISR3:
359 				 * time_flag */
360 	u32 isr4;		/* isr status register LMPM_NIC_ISR4:
361 				 * wico interrupt */
362 	u32 isr_pref;		/* isr status register LMPM_NIC_PREF_STAT */
363 	u32 wait_event;		/* wait event() caller address */
364 	u32 l2p_control;	/* L2pControlField */
365 	u32 l2p_duration;	/* L2pDurationField */
366 	u32 l2p_mhvalid;	/* L2pMhValidBits */
367 	u32 l2p_addr_match;	/* L2pAddrMatchStat */
368 	u32 lmpm_pmg_sel;	/* indicate which clocks are turned on
369 				 * (LMPM_PMG_SEL) */
370 	u32 u_timestamp;	/* indicate when the date and time of the
371 				 * compilation */
372 	u32 flow_handler;	/* FH read/write pointers, RX credit */
373 } __packed /* LOG_ERROR_TABLE_API_S_VER_1 */;
374 
375 struct iwl_error_event_table {
376 	u32 valid;		/* (nonzero) valid, (0) log is empty */
377 	u32 error_id;		/* type of error */
378 	u32 trm_hw_status0;	/* TRM HW status */
379 	u32 trm_hw_status1;	/* TRM HW status */
380 	u32 blink2;		/* branch link */
381 	u32 ilink1;		/* interrupt link */
382 	u32 ilink2;		/* interrupt link */
383 	u32 data1;		/* error-specific data */
384 	u32 data2;		/* error-specific data */
385 	u32 data3;		/* error-specific data */
386 	u32 bcon_time;		/* beacon timer */
387 	u32 tsf_low;		/* network timestamp function timer */
388 	u32 tsf_hi;		/* network timestamp function timer */
389 	u32 gp1;		/* GP1 timer register */
390 	u32 gp2;		/* GP2 timer register */
391 	u32 fw_rev_type;	/* firmware revision type */
392 	u32 major;		/* uCode version major */
393 	u32 minor;		/* uCode version minor */
394 	u32 hw_ver;		/* HW Silicon version */
395 	u32 brd_ver;		/* HW board version */
396 	u32 log_pc;		/* log program counter */
397 	u32 frame_ptr;		/* frame pointer */
398 	u32 stack_ptr;		/* stack pointer */
399 	u32 hcmd;		/* last host command header */
400 	u32 isr0;		/* isr status register LMPM_NIC_ISR0:
401 				 * rxtx_flag */
402 	u32 isr1;		/* isr status register LMPM_NIC_ISR1:
403 				 * host_flag */
404 	u32 isr2;		/* isr status register LMPM_NIC_ISR2:
405 				 * enc_flag */
406 	u32 isr3;		/* isr status register LMPM_NIC_ISR3:
407 				 * time_flag */
408 	u32 isr4;		/* isr status register LMPM_NIC_ISR4:
409 				 * wico interrupt */
410 	u32 last_cmd_id;	/* last HCMD id handled by the firmware */
411 	u32 wait_event;		/* wait event() caller address */
412 	u32 l2p_control;	/* L2pControlField */
413 	u32 l2p_duration;	/* L2pDurationField */
414 	u32 l2p_mhvalid;	/* L2pMhValidBits */
415 	u32 l2p_addr_match;	/* L2pAddrMatchStat */
416 	u32 lmpm_pmg_sel;	/* indicate which clocks are turned on
417 				 * (LMPM_PMG_SEL) */
418 	u32 u_timestamp;	/* indicate when the date and time of the
419 				 * compilation */
420 	u32 flow_handler;	/* FH read/write pointers, RX credit */
421 } __packed /* LOG_ERROR_TABLE_API_S_VER_3 */;
422 
423 /*
424  * UMAC error struct - relevant starting from family 8000 chip.
425  * Note: This structure is read from the device with IO accesses,
426  * and the reading already does the endian conversion. As it is
427  * read with u32-sized accesses, any members with a different size
428  * need to be ordered correctly though!
429  */
430 struct iwl_umac_error_event_table {
431 	u32 valid;		/* (nonzero) valid, (0) log is empty */
432 	u32 error_id;		/* type of error */
433 	u32 blink1;		/* branch link */
434 	u32 blink2;		/* branch link */
435 	u32 ilink1;		/* interrupt link */
436 	u32 ilink2;		/* interrupt link */
437 	u32 data1;		/* error-specific data */
438 	u32 data2;		/* error-specific data */
439 	u32 data3;		/* error-specific data */
440 	u32 umac_major;
441 	u32 umac_minor;
442 	u32 frame_pointer;	/* core register 27*/
443 	u32 stack_pointer;	/* core register 28 */
444 	u32 cmd_header;		/* latest host cmd sent to UMAC */
445 	u32 nic_isr_pref;	/* ISR status register */
446 } __packed;
447 
448 #define ERROR_START_OFFSET  (1 * sizeof(u32))
449 #define ERROR_ELEM_SIZE     (7 * sizeof(u32))
450 
451 static void iwl_mvm_dump_umac_error_log(struct iwl_mvm *mvm)
452 {
453 	struct iwl_trans *trans = mvm->trans;
454 	struct iwl_umac_error_event_table table;
455 
456 	if (!mvm->support_umac_log)
457 		return;
458 
459 	iwl_trans_read_mem_bytes(trans, mvm->umac_error_event_table, &table,
460 				 sizeof(table));
461 
462 	if (ERROR_START_OFFSET <= table.valid * ERROR_ELEM_SIZE) {
463 		IWL_ERR(trans, "Start IWL Error Log Dump:\n");
464 		IWL_ERR(trans, "Status: 0x%08lX, count: %d\n",
465 			mvm->status, table.valid);
466 	}
467 
468 	IWL_ERR(mvm, "0x%08X | %s\n", table.error_id,
469 		desc_lookup(table.error_id));
470 	IWL_ERR(mvm, "0x%08X | umac branchlink1\n", table.blink1);
471 	IWL_ERR(mvm, "0x%08X | umac branchlink2\n", table.blink2);
472 	IWL_ERR(mvm, "0x%08X | umac interruptlink1\n", table.ilink1);
473 	IWL_ERR(mvm, "0x%08X | umac interruptlink2\n", table.ilink2);
474 	IWL_ERR(mvm, "0x%08X | umac data1\n", table.data1);
475 	IWL_ERR(mvm, "0x%08X | umac data2\n", table.data2);
476 	IWL_ERR(mvm, "0x%08X | umac data3\n", table.data3);
477 	IWL_ERR(mvm, "0x%08X | umac major\n", table.umac_major);
478 	IWL_ERR(mvm, "0x%08X | umac minor\n", table.umac_minor);
479 	IWL_ERR(mvm, "0x%08X | frame pointer\n", table.frame_pointer);
480 	IWL_ERR(mvm, "0x%08X | stack pointer\n", table.stack_pointer);
481 	IWL_ERR(mvm, "0x%08X | last host cmd\n", table.cmd_header);
482 	IWL_ERR(mvm, "0x%08X | isr status reg\n", table.nic_isr_pref);
483 }
484 
485 static void iwl_mvm_dump_lmac_error_log(struct iwl_mvm *mvm, u32 base)
486 {
487 	struct iwl_trans *trans = mvm->trans;
488 	struct iwl_error_event_table table;
489 	u32 val;
490 
491 	if (mvm->fwrt.cur_fw_img == IWL_UCODE_INIT) {
492 		if (!base)
493 			base = mvm->fw->init_errlog_ptr;
494 	} else {
495 		if (!base)
496 			base = mvm->fw->inst_errlog_ptr;
497 	}
498 
499 	if (base < 0x400000) {
500 		IWL_ERR(mvm,
501 			"Not valid error log pointer 0x%08X for %s uCode\n",
502 			base,
503 			(mvm->fwrt.cur_fw_img == IWL_UCODE_INIT)
504 			? "Init" : "RT");
505 		return;
506 	}
507 
508 	/* check if there is a HW error */
509 	val = iwl_trans_read_mem32(trans, base);
510 	if (((val & ~0xf) == 0xa5a5a5a0) || ((val & ~0xf) == 0x5a5a5a50)) {
511 		int err;
512 
513 		IWL_ERR(trans, "HW error, resetting before reading\n");
514 
515 		/* reset the device */
516 		iwl_trans_sw_reset(trans);
517 
518 		/* set INIT_DONE flag */
519 		iwl_set_bit(trans, CSR_GP_CNTRL,
520 			    BIT(trans->cfg->csr->flag_init_done));
521 
522 		/* and wait for clock stabilization */
523 		if (trans->cfg->device_family == IWL_DEVICE_FAMILY_8000)
524 			udelay(2);
525 
526 		err = iwl_poll_bit(trans, CSR_GP_CNTRL,
527 				   BIT(trans->cfg->csr->flag_mac_clock_ready),
528 				   BIT(trans->cfg->csr->flag_mac_clock_ready),
529 				   25000);
530 		if (err < 0) {
531 			IWL_DEBUG_INFO(trans,
532 				       "Failed to reset the card for the dump\n");
533 			return;
534 		}
535 	}
536 
537 	iwl_trans_read_mem_bytes(trans, base, &table, sizeof(table));
538 
539 	if (ERROR_START_OFFSET <= table.valid * ERROR_ELEM_SIZE) {
540 		IWL_ERR(trans, "Start IWL Error Log Dump:\n");
541 		IWL_ERR(trans, "Status: 0x%08lX, count: %d\n",
542 			mvm->status, table.valid);
543 	}
544 
545 	/* Do not change this output - scripts rely on it */
546 
547 	IWL_ERR(mvm, "Loaded firmware version: %s\n", mvm->fw->fw_version);
548 
549 	IWL_ERR(mvm, "0x%08X | %-28s\n", table.error_id,
550 		desc_lookup(table.error_id));
551 	IWL_ERR(mvm, "0x%08X | trm_hw_status0\n", table.trm_hw_status0);
552 	IWL_ERR(mvm, "0x%08X | trm_hw_status1\n", table.trm_hw_status1);
553 	IWL_ERR(mvm, "0x%08X | branchlink2\n", table.blink2);
554 	IWL_ERR(mvm, "0x%08X | interruptlink1\n", table.ilink1);
555 	IWL_ERR(mvm, "0x%08X | interruptlink2\n", table.ilink2);
556 	IWL_ERR(mvm, "0x%08X | data1\n", table.data1);
557 	IWL_ERR(mvm, "0x%08X | data2\n", table.data2);
558 	IWL_ERR(mvm, "0x%08X | data3\n", table.data3);
559 	IWL_ERR(mvm, "0x%08X | beacon time\n", table.bcon_time);
560 	IWL_ERR(mvm, "0x%08X | tsf low\n", table.tsf_low);
561 	IWL_ERR(mvm, "0x%08X | tsf hi\n", table.tsf_hi);
562 	IWL_ERR(mvm, "0x%08X | time gp1\n", table.gp1);
563 	IWL_ERR(mvm, "0x%08X | time gp2\n", table.gp2);
564 	IWL_ERR(mvm, "0x%08X | uCode revision type\n", table.fw_rev_type);
565 	IWL_ERR(mvm, "0x%08X | uCode version major\n", table.major);
566 	IWL_ERR(mvm, "0x%08X | uCode version minor\n", table.minor);
567 	IWL_ERR(mvm, "0x%08X | hw version\n", table.hw_ver);
568 	IWL_ERR(mvm, "0x%08X | board version\n", table.brd_ver);
569 	IWL_ERR(mvm, "0x%08X | hcmd\n", table.hcmd);
570 	IWL_ERR(mvm, "0x%08X | isr0\n", table.isr0);
571 	IWL_ERR(mvm, "0x%08X | isr1\n", table.isr1);
572 	IWL_ERR(mvm, "0x%08X | isr2\n", table.isr2);
573 	IWL_ERR(mvm, "0x%08X | isr3\n", table.isr3);
574 	IWL_ERR(mvm, "0x%08X | isr4\n", table.isr4);
575 	IWL_ERR(mvm, "0x%08X | last cmd Id\n", table.last_cmd_id);
576 	IWL_ERR(mvm, "0x%08X | wait_event\n", table.wait_event);
577 	IWL_ERR(mvm, "0x%08X | l2p_control\n", table.l2p_control);
578 	IWL_ERR(mvm, "0x%08X | l2p_duration\n", table.l2p_duration);
579 	IWL_ERR(mvm, "0x%08X | l2p_mhvalid\n", table.l2p_mhvalid);
580 	IWL_ERR(mvm, "0x%08X | l2p_addr_match\n", table.l2p_addr_match);
581 	IWL_ERR(mvm, "0x%08X | lmpm_pmg_sel\n", table.lmpm_pmg_sel);
582 	IWL_ERR(mvm, "0x%08X | timestamp\n", table.u_timestamp);
583 	IWL_ERR(mvm, "0x%08X | flow_handler\n", table.flow_handler);
584 }
585 
586 void iwl_mvm_dump_nic_error_log(struct iwl_mvm *mvm)
587 {
588 	if (!test_bit(STATUS_DEVICE_ENABLED, &mvm->trans->status)) {
589 		IWL_ERR(mvm,
590 			"DEVICE_ENABLED bit is not set. Aborting dump.\n");
591 		return;
592 	}
593 
594 	iwl_mvm_dump_lmac_error_log(mvm, mvm->error_event_table[0]);
595 
596 	if (mvm->error_event_table[1])
597 		iwl_mvm_dump_lmac_error_log(mvm, mvm->error_event_table[1]);
598 
599 	iwl_mvm_dump_umac_error_log(mvm);
600 }
601 
602 int iwl_mvm_find_free_queue(struct iwl_mvm *mvm, u8 sta_id, u8 minq, u8 maxq)
603 {
604 	int i;
605 
606 	lockdep_assert_held(&mvm->queue_info_lock);
607 
608 	/* This should not be hit with new TX path */
609 	if (WARN_ON(iwl_mvm_has_new_tx_api(mvm)))
610 		return -ENOSPC;
611 
612 	/* Start by looking for a free queue */
613 	for (i = minq; i <= maxq; i++)
614 		if (mvm->queue_info[i].hw_queue_refcount == 0 &&
615 		    mvm->queue_info[i].status == IWL_MVM_QUEUE_FREE)
616 			return i;
617 
618 	/*
619 	 * If no free queue found - settle for an inactive one to reconfigure
620 	 * Make sure that the inactive queue either already belongs to this STA,
621 	 * or that if it belongs to another one - it isn't the reserved queue
622 	 */
623 	for (i = minq; i <= maxq; i++)
624 		if (mvm->queue_info[i].status == IWL_MVM_QUEUE_INACTIVE &&
625 		    (sta_id == mvm->queue_info[i].ra_sta_id ||
626 		     !mvm->queue_info[i].reserved))
627 			return i;
628 
629 	return -ENOSPC;
630 }
631 
632 int iwl_mvm_reconfig_scd(struct iwl_mvm *mvm, int queue, int fifo, int sta_id,
633 			 int tid, int frame_limit, u16 ssn)
634 {
635 	struct iwl_scd_txq_cfg_cmd cmd = {
636 		.scd_queue = queue,
637 		.action = SCD_CFG_ENABLE_QUEUE,
638 		.window = frame_limit,
639 		.sta_id = sta_id,
640 		.ssn = cpu_to_le16(ssn),
641 		.tx_fifo = fifo,
642 		.aggregate = (queue >= IWL_MVM_DQA_MIN_DATA_QUEUE ||
643 			      queue == IWL_MVM_DQA_BSS_CLIENT_QUEUE),
644 		.tid = tid,
645 	};
646 	int ret;
647 
648 	if (WARN_ON(iwl_mvm_has_new_tx_api(mvm)))
649 		return -EINVAL;
650 
651 	spin_lock_bh(&mvm->queue_info_lock);
652 	if (WARN(mvm->queue_info[queue].hw_queue_refcount == 0,
653 		 "Trying to reconfig unallocated queue %d\n", queue)) {
654 		spin_unlock_bh(&mvm->queue_info_lock);
655 		return -ENXIO;
656 	}
657 	spin_unlock_bh(&mvm->queue_info_lock);
658 
659 	IWL_DEBUG_TX_QUEUES(mvm, "Reconfig SCD for TXQ #%d\n", queue);
660 
661 	ret = iwl_mvm_send_cmd_pdu(mvm, SCD_QUEUE_CFG, 0, sizeof(cmd), &cmd);
662 	WARN_ONCE(ret, "Failed to re-configure queue %d on FIFO %d, ret=%d\n",
663 		  queue, fifo, ret);
664 
665 	return ret;
666 }
667 
668 static bool iwl_mvm_update_txq_mapping(struct iwl_mvm *mvm, int queue,
669 				       int mac80211_queue, u8 sta_id, u8 tid)
670 {
671 	bool enable_queue = true;
672 
673 	spin_lock_bh(&mvm->queue_info_lock);
674 
675 	/* Make sure this TID isn't already enabled */
676 	if (mvm->queue_info[queue].tid_bitmap & BIT(tid)) {
677 		spin_unlock_bh(&mvm->queue_info_lock);
678 		IWL_ERR(mvm, "Trying to enable TXQ %d with existing TID %d\n",
679 			queue, tid);
680 		return false;
681 	}
682 
683 	/* Update mappings and refcounts */
684 	if (mvm->queue_info[queue].hw_queue_refcount > 0)
685 		enable_queue = false;
686 
687 	if (mac80211_queue != IEEE80211_INVAL_HW_QUEUE) {
688 		WARN(mac80211_queue >=
689 		     BITS_PER_BYTE * sizeof(mvm->hw_queue_to_mac80211[0]),
690 		     "cannot track mac80211 queue %d (queue %d, sta %d, tid %d)\n",
691 		     mac80211_queue, queue, sta_id, tid);
692 		mvm->hw_queue_to_mac80211[queue] |= BIT(mac80211_queue);
693 	}
694 
695 	mvm->queue_info[queue].hw_queue_refcount++;
696 	mvm->queue_info[queue].tid_bitmap |= BIT(tid);
697 	mvm->queue_info[queue].ra_sta_id = sta_id;
698 
699 	if (enable_queue) {
700 		if (tid != IWL_MAX_TID_COUNT)
701 			mvm->queue_info[queue].mac80211_ac =
702 				tid_to_mac80211_ac[tid];
703 		else
704 			mvm->queue_info[queue].mac80211_ac = IEEE80211_AC_VO;
705 
706 		mvm->queue_info[queue].txq_tid = tid;
707 	}
708 
709 	IWL_DEBUG_TX_QUEUES(mvm,
710 			    "Enabling TXQ #%d refcount=%d (mac80211 map:0x%x)\n",
711 			    queue, mvm->queue_info[queue].hw_queue_refcount,
712 			    mvm->hw_queue_to_mac80211[queue]);
713 
714 	spin_unlock_bh(&mvm->queue_info_lock);
715 
716 	return enable_queue;
717 }
718 
719 int iwl_mvm_tvqm_enable_txq(struct iwl_mvm *mvm, int mac80211_queue,
720 			    u8 sta_id, u8 tid, unsigned int timeout)
721 {
722 	int queue, size = IWL_DEFAULT_QUEUE_SIZE;
723 
724 	if (tid == IWL_MAX_TID_COUNT) {
725 		tid = IWL_MGMT_TID;
726 		size = IWL_MGMT_QUEUE_SIZE;
727 	}
728 	queue = iwl_trans_txq_alloc(mvm->trans,
729 				    cpu_to_le16(TX_QUEUE_CFG_ENABLE_QUEUE),
730 				    sta_id, tid, SCD_QUEUE_CFG, size, timeout);
731 
732 	if (queue < 0) {
733 		IWL_DEBUG_TX_QUEUES(mvm,
734 				    "Failed allocating TXQ for sta %d tid %d, ret: %d\n",
735 				    sta_id, tid, queue);
736 		return queue;
737 	}
738 
739 	IWL_DEBUG_TX_QUEUES(mvm, "Enabling TXQ #%d for sta %d tid %d\n",
740 			    queue, sta_id, tid);
741 
742 	mvm->hw_queue_to_mac80211[queue] |= BIT(mac80211_queue);
743 	IWL_DEBUG_TX_QUEUES(mvm,
744 			    "Enabling TXQ #%d (mac80211 map:0x%x)\n",
745 			    queue, mvm->hw_queue_to_mac80211[queue]);
746 
747 	return queue;
748 }
749 
750 bool iwl_mvm_enable_txq(struct iwl_mvm *mvm, int queue, int mac80211_queue,
751 			u16 ssn, const struct iwl_trans_txq_scd_cfg *cfg,
752 			unsigned int wdg_timeout)
753 {
754 	struct iwl_scd_txq_cfg_cmd cmd = {
755 		.scd_queue = queue,
756 		.action = SCD_CFG_ENABLE_QUEUE,
757 		.window = cfg->frame_limit,
758 		.sta_id = cfg->sta_id,
759 		.ssn = cpu_to_le16(ssn),
760 		.tx_fifo = cfg->fifo,
761 		.aggregate = cfg->aggregate,
762 		.tid = cfg->tid,
763 	};
764 	bool inc_ssn;
765 
766 	if (WARN_ON(iwl_mvm_has_new_tx_api(mvm)))
767 		return false;
768 
769 	/* Send the enabling command if we need to */
770 	if (!iwl_mvm_update_txq_mapping(mvm, queue, mac80211_queue,
771 					cfg->sta_id, cfg->tid))
772 		return false;
773 
774 	inc_ssn = iwl_trans_txq_enable_cfg(mvm->trans, queue, ssn,
775 					   NULL, wdg_timeout);
776 	if (inc_ssn)
777 		le16_add_cpu(&cmd.ssn, 1);
778 
779 	WARN(iwl_mvm_send_cmd_pdu(mvm, SCD_QUEUE_CFG, 0, sizeof(cmd), &cmd),
780 	     "Failed to configure queue %d on FIFO %d\n", queue, cfg->fifo);
781 
782 	return inc_ssn;
783 }
784 
785 int iwl_mvm_disable_txq(struct iwl_mvm *mvm, int queue, int mac80211_queue,
786 			u8 tid, u8 flags)
787 {
788 	struct iwl_scd_txq_cfg_cmd cmd = {
789 		.scd_queue = queue,
790 		.action = SCD_CFG_DISABLE_QUEUE,
791 	};
792 	bool remove_mac_queue = mac80211_queue != IEEE80211_INVAL_HW_QUEUE;
793 	int ret;
794 
795 	if (WARN_ON(remove_mac_queue && mac80211_queue >= IEEE80211_MAX_QUEUES))
796 		return -EINVAL;
797 
798 	if (iwl_mvm_has_new_tx_api(mvm)) {
799 		spin_lock_bh(&mvm->queue_info_lock);
800 
801 		if (remove_mac_queue)
802 			mvm->hw_queue_to_mac80211[queue] &=
803 				~BIT(mac80211_queue);
804 
805 		spin_unlock_bh(&mvm->queue_info_lock);
806 
807 		iwl_trans_txq_free(mvm->trans, queue);
808 
809 		return 0;
810 	}
811 
812 	spin_lock_bh(&mvm->queue_info_lock);
813 
814 	if (WARN_ON(mvm->queue_info[queue].hw_queue_refcount == 0)) {
815 		spin_unlock_bh(&mvm->queue_info_lock);
816 		return 0;
817 	}
818 
819 	mvm->queue_info[queue].tid_bitmap &= ~BIT(tid);
820 
821 	/*
822 	 * If there is another TID with the same AC - don't remove the MAC queue
823 	 * from the mapping
824 	 */
825 	if (tid < IWL_MAX_TID_COUNT) {
826 		unsigned long tid_bitmap =
827 			mvm->queue_info[queue].tid_bitmap;
828 		int ac = tid_to_mac80211_ac[tid];
829 		int i;
830 
831 		for_each_set_bit(i, &tid_bitmap, IWL_MAX_TID_COUNT) {
832 			if (tid_to_mac80211_ac[i] == ac)
833 				remove_mac_queue = false;
834 		}
835 	}
836 
837 	if (remove_mac_queue)
838 		mvm->hw_queue_to_mac80211[queue] &=
839 			~BIT(mac80211_queue);
840 	mvm->queue_info[queue].hw_queue_refcount--;
841 
842 	cmd.action = mvm->queue_info[queue].hw_queue_refcount ?
843 		SCD_CFG_ENABLE_QUEUE : SCD_CFG_DISABLE_QUEUE;
844 	if (cmd.action == SCD_CFG_DISABLE_QUEUE)
845 		mvm->queue_info[queue].status = IWL_MVM_QUEUE_FREE;
846 
847 	IWL_DEBUG_TX_QUEUES(mvm,
848 			    "Disabling TXQ #%d refcount=%d (mac80211 map:0x%x)\n",
849 			    queue,
850 			    mvm->queue_info[queue].hw_queue_refcount,
851 			    mvm->hw_queue_to_mac80211[queue]);
852 
853 	/* If the queue is still enabled - nothing left to do in this func */
854 	if (cmd.action == SCD_CFG_ENABLE_QUEUE) {
855 		spin_unlock_bh(&mvm->queue_info_lock);
856 		return 0;
857 	}
858 
859 	cmd.sta_id = mvm->queue_info[queue].ra_sta_id;
860 	cmd.tid = mvm->queue_info[queue].txq_tid;
861 
862 	/* Make sure queue info is correct even though we overwrite it */
863 	WARN(mvm->queue_info[queue].hw_queue_refcount ||
864 	     mvm->queue_info[queue].tid_bitmap ||
865 	     mvm->hw_queue_to_mac80211[queue],
866 	     "TXQ #%d info out-of-sync - refcount=%d, mac map=0x%x, tid=0x%x\n",
867 	     queue, mvm->queue_info[queue].hw_queue_refcount,
868 	     mvm->hw_queue_to_mac80211[queue],
869 	     mvm->queue_info[queue].tid_bitmap);
870 
871 	/* If we are here - the queue is freed and we can zero out these vals */
872 	mvm->queue_info[queue].hw_queue_refcount = 0;
873 	mvm->queue_info[queue].tid_bitmap = 0;
874 	mvm->hw_queue_to_mac80211[queue] = 0;
875 
876 	/* Regardless if this is a reserved TXQ for a STA - mark it as false */
877 	mvm->queue_info[queue].reserved = false;
878 
879 	spin_unlock_bh(&mvm->queue_info_lock);
880 
881 	iwl_trans_txq_disable(mvm->trans, queue, false);
882 	ret = iwl_mvm_send_cmd_pdu(mvm, SCD_QUEUE_CFG, flags,
883 				   sizeof(struct iwl_scd_txq_cfg_cmd), &cmd);
884 
885 	if (ret)
886 		IWL_ERR(mvm, "Failed to disable queue %d (ret=%d)\n",
887 			queue, ret);
888 	return ret;
889 }
890 
891 /**
892  * iwl_mvm_send_lq_cmd() - Send link quality command
893  * @sync: This command can be sent synchronously.
894  *
895  * The link quality command is sent as the last step of station creation.
896  * This is the special case in which init is set and we call a callback in
897  * this case to clear the state indicating that station creation is in
898  * progress.
899  */
900 int iwl_mvm_send_lq_cmd(struct iwl_mvm *mvm, struct iwl_lq_cmd *lq, bool sync)
901 {
902 	struct iwl_host_cmd cmd = {
903 		.id = LQ_CMD,
904 		.len = { sizeof(struct iwl_lq_cmd), },
905 		.flags = sync ? 0 : CMD_ASYNC,
906 		.data = { lq, },
907 	};
908 
909 	if (WARN_ON(lq->sta_id == IWL_MVM_INVALID_STA ||
910 		    iwl_mvm_has_tlc_offload(mvm)))
911 		return -EINVAL;
912 
913 	return iwl_mvm_send_cmd(mvm, &cmd);
914 }
915 
916 /**
917  * iwl_mvm_update_smps - Get a request to change the SMPS mode
918  * @req_type: The part of the driver who call for a change.
919  * @smps_requests: The request to change the SMPS mode.
920  *
921  * Get a requst to change the SMPS mode,
922  * and change it according to all other requests in the driver.
923  */
924 void iwl_mvm_update_smps(struct iwl_mvm *mvm, struct ieee80211_vif *vif,
925 			 enum iwl_mvm_smps_type_request req_type,
926 			 enum ieee80211_smps_mode smps_request)
927 {
928 	struct iwl_mvm_vif *mvmvif;
929 	enum ieee80211_smps_mode smps_mode;
930 	int i;
931 
932 	lockdep_assert_held(&mvm->mutex);
933 
934 	/* SMPS is irrelevant for NICs that don't have at least 2 RX antenna */
935 	if (num_of_ant(iwl_mvm_get_valid_rx_ant(mvm)) == 1)
936 		return;
937 
938 	if (vif->type == NL80211_IFTYPE_AP)
939 		smps_mode = IEEE80211_SMPS_OFF;
940 	else
941 		smps_mode = IEEE80211_SMPS_AUTOMATIC;
942 
943 	mvmvif = iwl_mvm_vif_from_mac80211(vif);
944 	mvmvif->smps_requests[req_type] = smps_request;
945 	for (i = 0; i < NUM_IWL_MVM_SMPS_REQ; i++) {
946 		if (mvmvif->smps_requests[i] == IEEE80211_SMPS_STATIC) {
947 			smps_mode = IEEE80211_SMPS_STATIC;
948 			break;
949 		}
950 		if (mvmvif->smps_requests[i] == IEEE80211_SMPS_DYNAMIC)
951 			smps_mode = IEEE80211_SMPS_DYNAMIC;
952 	}
953 
954 	ieee80211_request_smps(vif, smps_mode);
955 }
956 
957 int iwl_mvm_request_statistics(struct iwl_mvm *mvm, bool clear)
958 {
959 	struct iwl_statistics_cmd scmd = {
960 		.flags = clear ? cpu_to_le32(IWL_STATISTICS_FLG_CLEAR) : 0,
961 	};
962 	struct iwl_host_cmd cmd = {
963 		.id = STATISTICS_CMD,
964 		.len[0] = sizeof(scmd),
965 		.data[0] = &scmd,
966 		.flags = CMD_WANT_SKB,
967 	};
968 	int ret;
969 
970 	ret = iwl_mvm_send_cmd(mvm, &cmd);
971 	if (ret)
972 		return ret;
973 
974 	iwl_mvm_handle_rx_statistics(mvm, cmd.resp_pkt);
975 	iwl_free_resp(&cmd);
976 
977 	if (clear)
978 		iwl_mvm_accu_radio_stats(mvm);
979 
980 	return 0;
981 }
982 
983 void iwl_mvm_accu_radio_stats(struct iwl_mvm *mvm)
984 {
985 	mvm->accu_radio_stats.rx_time += mvm->radio_stats.rx_time;
986 	mvm->accu_radio_stats.tx_time += mvm->radio_stats.tx_time;
987 	mvm->accu_radio_stats.on_time_rf += mvm->radio_stats.on_time_rf;
988 	mvm->accu_radio_stats.on_time_scan += mvm->radio_stats.on_time_scan;
989 }
990 
991 static void iwl_mvm_diversity_iter(void *_data, u8 *mac,
992 				   struct ieee80211_vif *vif)
993 {
994 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
995 	bool *result = _data;
996 	int i;
997 
998 	for (i = 0; i < NUM_IWL_MVM_SMPS_REQ; i++) {
999 		if (mvmvif->smps_requests[i] == IEEE80211_SMPS_STATIC ||
1000 		    mvmvif->smps_requests[i] == IEEE80211_SMPS_DYNAMIC)
1001 			*result = false;
1002 	}
1003 }
1004 
1005 bool iwl_mvm_rx_diversity_allowed(struct iwl_mvm *mvm)
1006 {
1007 	bool result = true;
1008 
1009 	lockdep_assert_held(&mvm->mutex);
1010 
1011 	if (num_of_ant(iwl_mvm_get_valid_rx_ant(mvm)) == 1)
1012 		return false;
1013 
1014 	if (mvm->cfg->rx_with_siso_diversity)
1015 		return false;
1016 
1017 	ieee80211_iterate_active_interfaces_atomic(
1018 			mvm->hw, IEEE80211_IFACE_ITER_NORMAL,
1019 			iwl_mvm_diversity_iter, &result);
1020 
1021 	return result;
1022 }
1023 
1024 int iwl_mvm_update_low_latency(struct iwl_mvm *mvm, struct ieee80211_vif *vif,
1025 			       bool low_latency,
1026 			       enum iwl_mvm_low_latency_cause cause)
1027 {
1028 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
1029 	int res;
1030 	bool prev;
1031 
1032 	lockdep_assert_held(&mvm->mutex);
1033 
1034 	prev = iwl_mvm_vif_low_latency(mvmvif);
1035 	iwl_mvm_vif_set_low_latency(mvmvif, low_latency, cause);
1036 
1037 	low_latency = iwl_mvm_vif_low_latency(mvmvif);
1038 
1039 	if (low_latency == prev)
1040 		return 0;
1041 
1042 	if (fw_has_capa(&mvm->fw->ucode_capa,
1043 			IWL_UCODE_TLV_CAPA_DYNAMIC_QUOTA)) {
1044 		struct iwl_mac_low_latency_cmd cmd = {
1045 			.mac_id = cpu_to_le32(mvmvif->id)
1046 		};
1047 
1048 		if (low_latency) {
1049 			/* currently we don't care about the direction */
1050 			cmd.low_latency_rx = 1;
1051 			cmd.low_latency_tx = 1;
1052 		}
1053 		res = iwl_mvm_send_cmd_pdu(mvm,
1054 					   iwl_cmd_id(LOW_LATENCY_CMD,
1055 						      MAC_CONF_GROUP, 0),
1056 					   0, sizeof(cmd), &cmd);
1057 		if (res)
1058 			IWL_ERR(mvm, "Failed to send low latency command\n");
1059 	}
1060 
1061 	res = iwl_mvm_update_quotas(mvm, false, NULL);
1062 	if (res)
1063 		return res;
1064 
1065 	iwl_mvm_bt_coex_vif_change(mvm);
1066 
1067 	return iwl_mvm_power_update_mac(mvm);
1068 }
1069 
1070 struct iwl_mvm_low_latency_iter {
1071 	bool result;
1072 	bool result_per_band[NUM_NL80211_BANDS];
1073 };
1074 
1075 static void iwl_mvm_ll_iter(void *_data, u8 *mac, struct ieee80211_vif *vif)
1076 {
1077 	struct iwl_mvm_low_latency_iter *result = _data;
1078 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
1079 	enum nl80211_band band;
1080 
1081 	if (iwl_mvm_vif_low_latency(mvmvif)) {
1082 		result->result = true;
1083 
1084 		if (!mvmvif->phy_ctxt)
1085 			return;
1086 
1087 		band = mvmvif->phy_ctxt->channel->band;
1088 		result->result_per_band[band] = true;
1089 	}
1090 }
1091 
1092 bool iwl_mvm_low_latency(struct iwl_mvm *mvm)
1093 {
1094 	struct iwl_mvm_low_latency_iter data = {};
1095 
1096 	ieee80211_iterate_active_interfaces_atomic(
1097 			mvm->hw, IEEE80211_IFACE_ITER_NORMAL,
1098 			iwl_mvm_ll_iter, &data);
1099 
1100 	return data.result;
1101 }
1102 
1103 bool iwl_mvm_low_latency_band(struct iwl_mvm *mvm, enum nl80211_band band)
1104 {
1105 	struct iwl_mvm_low_latency_iter data = {};
1106 
1107 	ieee80211_iterate_active_interfaces_atomic(
1108 			mvm->hw, IEEE80211_IFACE_ITER_NORMAL,
1109 			iwl_mvm_ll_iter, &data);
1110 
1111 	return data.result_per_band[band];
1112 }
1113 
1114 struct iwl_bss_iter_data {
1115 	struct ieee80211_vif *vif;
1116 	bool error;
1117 };
1118 
1119 static void iwl_mvm_bss_iface_iterator(void *_data, u8 *mac,
1120 				       struct ieee80211_vif *vif)
1121 {
1122 	struct iwl_bss_iter_data *data = _data;
1123 
1124 	if (vif->type != NL80211_IFTYPE_STATION || vif->p2p)
1125 		return;
1126 
1127 	if (data->vif) {
1128 		data->error = true;
1129 		return;
1130 	}
1131 
1132 	data->vif = vif;
1133 }
1134 
1135 struct ieee80211_vif *iwl_mvm_get_bss_vif(struct iwl_mvm *mvm)
1136 {
1137 	struct iwl_bss_iter_data bss_iter_data = {};
1138 
1139 	ieee80211_iterate_active_interfaces_atomic(
1140 		mvm->hw, IEEE80211_IFACE_ITER_NORMAL,
1141 		iwl_mvm_bss_iface_iterator, &bss_iter_data);
1142 
1143 	if (bss_iter_data.error) {
1144 		IWL_ERR(mvm, "More than one managed interface active!\n");
1145 		return ERR_PTR(-EINVAL);
1146 	}
1147 
1148 	return bss_iter_data.vif;
1149 }
1150 
1151 struct iwl_sta_iter_data {
1152 	bool assoc;
1153 };
1154 
1155 static void iwl_mvm_sta_iface_iterator(void *_data, u8 *mac,
1156 				       struct ieee80211_vif *vif)
1157 {
1158 	struct iwl_sta_iter_data *data = _data;
1159 
1160 	if (vif->type != NL80211_IFTYPE_STATION)
1161 		return;
1162 
1163 	if (vif->bss_conf.assoc)
1164 		data->assoc = true;
1165 }
1166 
1167 bool iwl_mvm_is_vif_assoc(struct iwl_mvm *mvm)
1168 {
1169 	struct iwl_sta_iter_data data = {
1170 		.assoc = false,
1171 	};
1172 
1173 	ieee80211_iterate_active_interfaces_atomic(mvm->hw,
1174 						   IEEE80211_IFACE_ITER_NORMAL,
1175 						   iwl_mvm_sta_iface_iterator,
1176 						   &data);
1177 	return data.assoc;
1178 }
1179 
1180 unsigned int iwl_mvm_get_wd_timeout(struct iwl_mvm *mvm,
1181 				    struct ieee80211_vif *vif,
1182 				    bool tdls, bool cmd_q)
1183 {
1184 	struct iwl_fw_dbg_trigger_tlv *trigger;
1185 	struct iwl_fw_dbg_trigger_txq_timer *txq_timer;
1186 	unsigned int default_timeout =
1187 		cmd_q ? IWL_DEF_WD_TIMEOUT : mvm->cfg->base_params->wd_timeout;
1188 
1189 	if (!iwl_fw_dbg_trigger_enabled(mvm->fw, FW_DBG_TRIGGER_TXQ_TIMERS)) {
1190 		/*
1191 		 * We can't know when the station is asleep or awake, so we
1192 		 * must disable the queue hang detection.
1193 		 */
1194 		if (fw_has_capa(&mvm->fw->ucode_capa,
1195 				IWL_UCODE_TLV_CAPA_STA_PM_NOTIF) &&
1196 		    vif && vif->type == NL80211_IFTYPE_AP)
1197 			return IWL_WATCHDOG_DISABLED;
1198 		return iwlmvm_mod_params.tfd_q_hang_detect ?
1199 			default_timeout : IWL_WATCHDOG_DISABLED;
1200 	}
1201 
1202 	trigger = iwl_fw_dbg_get_trigger(mvm->fw, FW_DBG_TRIGGER_TXQ_TIMERS);
1203 	txq_timer = (void *)trigger->data;
1204 
1205 	if (tdls)
1206 		return le32_to_cpu(txq_timer->tdls);
1207 
1208 	if (cmd_q)
1209 		return le32_to_cpu(txq_timer->command_queue);
1210 
1211 	if (WARN_ON(!vif))
1212 		return default_timeout;
1213 
1214 	switch (ieee80211_vif_type_p2p(vif)) {
1215 	case NL80211_IFTYPE_ADHOC:
1216 		return le32_to_cpu(txq_timer->ibss);
1217 	case NL80211_IFTYPE_STATION:
1218 		return le32_to_cpu(txq_timer->bss);
1219 	case NL80211_IFTYPE_AP:
1220 		return le32_to_cpu(txq_timer->softap);
1221 	case NL80211_IFTYPE_P2P_CLIENT:
1222 		return le32_to_cpu(txq_timer->p2p_client);
1223 	case NL80211_IFTYPE_P2P_GO:
1224 		return le32_to_cpu(txq_timer->p2p_go);
1225 	case NL80211_IFTYPE_P2P_DEVICE:
1226 		return le32_to_cpu(txq_timer->p2p_device);
1227 	case NL80211_IFTYPE_MONITOR:
1228 		return default_timeout;
1229 	default:
1230 		WARN_ON(1);
1231 		return mvm->cfg->base_params->wd_timeout;
1232 	}
1233 }
1234 
1235 void iwl_mvm_connection_loss(struct iwl_mvm *mvm, struct ieee80211_vif *vif,
1236 			     const char *errmsg)
1237 {
1238 	struct iwl_fw_dbg_trigger_tlv *trig;
1239 	struct iwl_fw_dbg_trigger_mlme *trig_mlme;
1240 
1241 	if (!iwl_fw_dbg_trigger_enabled(mvm->fw, FW_DBG_TRIGGER_MLME))
1242 		goto out;
1243 
1244 	trig = iwl_fw_dbg_get_trigger(mvm->fw, FW_DBG_TRIGGER_MLME);
1245 	trig_mlme = (void *)trig->data;
1246 	if (!iwl_fw_dbg_trigger_check_stop(&mvm->fwrt,
1247 					   ieee80211_vif_to_wdev(vif), trig))
1248 		goto out;
1249 
1250 	if (trig_mlme->stop_connection_loss &&
1251 	    --trig_mlme->stop_connection_loss)
1252 		goto out;
1253 
1254 	iwl_fw_dbg_collect_trig(&mvm->fwrt, trig, "%s", errmsg);
1255 
1256 out:
1257 	ieee80211_connection_loss(vif);
1258 }
1259 
1260 /*
1261  * Remove inactive TIDs of a given queue.
1262  * If all queue TIDs are inactive - mark the queue as inactive
1263  * If only some the queue TIDs are inactive - unmap them from the queue
1264  */
1265 static void iwl_mvm_remove_inactive_tids(struct iwl_mvm *mvm,
1266 					 struct iwl_mvm_sta *mvmsta, int queue,
1267 					 unsigned long tid_bitmap)
1268 {
1269 	int tid;
1270 
1271 	lockdep_assert_held(&mvmsta->lock);
1272 	lockdep_assert_held(&mvm->queue_info_lock);
1273 
1274 	if (WARN_ON(iwl_mvm_has_new_tx_api(mvm)))
1275 		return;
1276 
1277 	/* Go over all non-active TIDs, incl. IWL_MAX_TID_COUNT (for mgmt) */
1278 	for_each_set_bit(tid, &tid_bitmap, IWL_MAX_TID_COUNT + 1) {
1279 		/* If some TFDs are still queued - don't mark TID as inactive */
1280 		if (iwl_mvm_tid_queued(mvm, &mvmsta->tid_data[tid]))
1281 			tid_bitmap &= ~BIT(tid);
1282 
1283 		/* Don't mark as inactive any TID that has an active BA */
1284 		if (mvmsta->tid_data[tid].state != IWL_AGG_OFF)
1285 			tid_bitmap &= ~BIT(tid);
1286 	}
1287 
1288 	/* If all TIDs in the queue are inactive - mark queue as inactive. */
1289 	if (tid_bitmap == mvm->queue_info[queue].tid_bitmap) {
1290 		mvm->queue_info[queue].status = IWL_MVM_QUEUE_INACTIVE;
1291 
1292 		for_each_set_bit(tid, &tid_bitmap, IWL_MAX_TID_COUNT + 1)
1293 			mvmsta->tid_data[tid].is_tid_active = false;
1294 
1295 		IWL_DEBUG_TX_QUEUES(mvm, "Queue %d marked as inactive\n",
1296 				    queue);
1297 		return;
1298 	}
1299 
1300 	/*
1301 	 * If we are here, this is a shared queue and not all TIDs timed-out.
1302 	 * Remove the ones that did.
1303 	 */
1304 	for_each_set_bit(tid, &tid_bitmap, IWL_MAX_TID_COUNT + 1) {
1305 		int mac_queue = mvmsta->vif->hw_queue[tid_to_mac80211_ac[tid]];
1306 
1307 		mvmsta->tid_data[tid].txq_id = IWL_MVM_INVALID_QUEUE;
1308 		mvm->hw_queue_to_mac80211[queue] &= ~BIT(mac_queue);
1309 		mvm->queue_info[queue].hw_queue_refcount--;
1310 		mvm->queue_info[queue].tid_bitmap &= ~BIT(tid);
1311 		mvmsta->tid_data[tid].is_tid_active = false;
1312 
1313 		IWL_DEBUG_TX_QUEUES(mvm,
1314 				    "Removing inactive TID %d from shared Q:%d\n",
1315 				    tid, queue);
1316 	}
1317 
1318 	IWL_DEBUG_TX_QUEUES(mvm,
1319 			    "TXQ #%d left with tid bitmap 0x%x\n", queue,
1320 			    mvm->queue_info[queue].tid_bitmap);
1321 
1322 	/*
1323 	 * There may be different TIDs with the same mac queues, so make
1324 	 * sure all TIDs have existing corresponding mac queues enabled
1325 	 */
1326 	tid_bitmap = mvm->queue_info[queue].tid_bitmap;
1327 	for_each_set_bit(tid, &tid_bitmap, IWL_MAX_TID_COUNT + 1) {
1328 		mvm->hw_queue_to_mac80211[queue] |=
1329 			BIT(mvmsta->vif->hw_queue[tid_to_mac80211_ac[tid]]);
1330 	}
1331 
1332 	/* If the queue is marked as shared - "unshare" it */
1333 	if (mvm->queue_info[queue].hw_queue_refcount == 1 &&
1334 	    mvm->queue_info[queue].status == IWL_MVM_QUEUE_SHARED) {
1335 		mvm->queue_info[queue].status = IWL_MVM_QUEUE_RECONFIGURING;
1336 		IWL_DEBUG_TX_QUEUES(mvm, "Marking Q:%d for reconfig\n",
1337 				    queue);
1338 	}
1339 }
1340 
1341 void iwl_mvm_inactivity_check(struct iwl_mvm *mvm)
1342 {
1343 	unsigned long timeout_queues_map = 0;
1344 	unsigned long now = jiffies;
1345 	int i;
1346 
1347 	if (iwl_mvm_has_new_tx_api(mvm))
1348 		return;
1349 
1350 	spin_lock_bh(&mvm->queue_info_lock);
1351 	for (i = 0; i < IWL_MAX_HW_QUEUES; i++)
1352 		if (mvm->queue_info[i].hw_queue_refcount > 0)
1353 			timeout_queues_map |= BIT(i);
1354 	spin_unlock_bh(&mvm->queue_info_lock);
1355 
1356 	rcu_read_lock();
1357 
1358 	/*
1359 	 * If a queue time outs - mark it as INACTIVE (don't remove right away
1360 	 * if we don't have to.) This is an optimization in case traffic comes
1361 	 * later, and we don't HAVE to use a currently-inactive queue
1362 	 */
1363 	for_each_set_bit(i, &timeout_queues_map, IWL_MAX_HW_QUEUES) {
1364 		struct ieee80211_sta *sta;
1365 		struct iwl_mvm_sta *mvmsta;
1366 		u8 sta_id;
1367 		int tid;
1368 		unsigned long inactive_tid_bitmap = 0;
1369 		unsigned long queue_tid_bitmap;
1370 
1371 		spin_lock_bh(&mvm->queue_info_lock);
1372 		queue_tid_bitmap = mvm->queue_info[i].tid_bitmap;
1373 
1374 		/* If TXQ isn't in active use anyway - nothing to do here... */
1375 		if (mvm->queue_info[i].status != IWL_MVM_QUEUE_READY &&
1376 		    mvm->queue_info[i].status != IWL_MVM_QUEUE_SHARED) {
1377 			spin_unlock_bh(&mvm->queue_info_lock);
1378 			continue;
1379 		}
1380 
1381 		/* Check to see if there are inactive TIDs on this queue */
1382 		for_each_set_bit(tid, &queue_tid_bitmap,
1383 				 IWL_MAX_TID_COUNT + 1) {
1384 			if (time_after(mvm->queue_info[i].last_frame_time[tid] +
1385 				       IWL_MVM_DQA_QUEUE_TIMEOUT, now))
1386 				continue;
1387 
1388 			inactive_tid_bitmap |= BIT(tid);
1389 		}
1390 		spin_unlock_bh(&mvm->queue_info_lock);
1391 
1392 		/* If all TIDs are active - finish check on this queue */
1393 		if (!inactive_tid_bitmap)
1394 			continue;
1395 
1396 		/*
1397 		 * If we are here - the queue hadn't been served recently and is
1398 		 * in use
1399 		 */
1400 
1401 		sta_id = mvm->queue_info[i].ra_sta_id;
1402 		sta = rcu_dereference(mvm->fw_id_to_mac_id[sta_id]);
1403 
1404 		/*
1405 		 * If the STA doesn't exist anymore, it isn't an error. It could
1406 		 * be that it was removed since getting the queues, and in this
1407 		 * case it should've inactivated its queues anyway.
1408 		 */
1409 		if (IS_ERR_OR_NULL(sta))
1410 			continue;
1411 
1412 		mvmsta = iwl_mvm_sta_from_mac80211(sta);
1413 
1414 		spin_lock_bh(&mvmsta->lock);
1415 		spin_lock(&mvm->queue_info_lock);
1416 		iwl_mvm_remove_inactive_tids(mvm, mvmsta, i,
1417 					     inactive_tid_bitmap);
1418 		spin_unlock(&mvm->queue_info_lock);
1419 		spin_unlock_bh(&mvmsta->lock);
1420 	}
1421 
1422 	rcu_read_unlock();
1423 }
1424 
1425 void iwl_mvm_event_frame_timeout_callback(struct iwl_mvm *mvm,
1426 					  struct ieee80211_vif *vif,
1427 					  const struct ieee80211_sta *sta,
1428 					  u16 tid)
1429 {
1430 	struct iwl_fw_dbg_trigger_tlv *trig;
1431 	struct iwl_fw_dbg_trigger_ba *ba_trig;
1432 
1433 	if (!iwl_fw_dbg_trigger_enabled(mvm->fw, FW_DBG_TRIGGER_BA))
1434 		return;
1435 
1436 	trig = iwl_fw_dbg_get_trigger(mvm->fw, FW_DBG_TRIGGER_BA);
1437 	ba_trig = (void *)trig->data;
1438 	if (!iwl_fw_dbg_trigger_check_stop(&mvm->fwrt,
1439 					   ieee80211_vif_to_wdev(vif), trig))
1440 		return;
1441 
1442 	if (!(le16_to_cpu(ba_trig->frame_timeout) & BIT(tid)))
1443 		return;
1444 
1445 	iwl_fw_dbg_collect_trig(&mvm->fwrt, trig,
1446 				"Frame from %pM timed out, tid %d",
1447 				sta->addr, tid);
1448 }
1449 
1450 u8 iwl_mvm_tcm_load_percentage(u32 airtime, u32 elapsed)
1451 {
1452 	if (!elapsed)
1453 		return 0;
1454 
1455 	return (100 * airtime / elapsed) / USEC_PER_MSEC;
1456 }
1457 
1458 static enum iwl_mvm_traffic_load
1459 iwl_mvm_tcm_load(struct iwl_mvm *mvm, u32 airtime, unsigned long elapsed)
1460 {
1461 	u8 load = iwl_mvm_tcm_load_percentage(airtime, elapsed);
1462 
1463 	if (load > IWL_MVM_TCM_LOAD_HIGH_THRESH)
1464 		return IWL_MVM_TRAFFIC_HIGH;
1465 	if (load > IWL_MVM_TCM_LOAD_MEDIUM_THRESH)
1466 		return IWL_MVM_TRAFFIC_MEDIUM;
1467 
1468 	return IWL_MVM_TRAFFIC_LOW;
1469 }
1470 
1471 struct iwl_mvm_tcm_iter_data {
1472 	struct iwl_mvm *mvm;
1473 	bool any_sent;
1474 };
1475 
1476 static void iwl_mvm_tcm_iter(void *_data, u8 *mac, struct ieee80211_vif *vif)
1477 {
1478 	struct iwl_mvm_tcm_iter_data *data = _data;
1479 	struct iwl_mvm *mvm = data->mvm;
1480 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
1481 	bool low_latency, prev = mvmvif->low_latency & LOW_LATENCY_TRAFFIC;
1482 
1483 	if (mvmvif->id >= NUM_MAC_INDEX_DRIVER)
1484 		return;
1485 
1486 	low_latency = mvm->tcm.result.low_latency[mvmvif->id];
1487 
1488 	if (!mvm->tcm.result.change[mvmvif->id] &&
1489 	    prev == low_latency) {
1490 		iwl_mvm_update_quotas(mvm, false, NULL);
1491 		return;
1492 	}
1493 
1494 	if (prev != low_latency) {
1495 		/* this sends traffic load and updates quota as well */
1496 		iwl_mvm_update_low_latency(mvm, vif, low_latency,
1497 					   LOW_LATENCY_TRAFFIC);
1498 	} else {
1499 		iwl_mvm_update_quotas(mvm, false, NULL);
1500 	}
1501 
1502 	data->any_sent = true;
1503 }
1504 
1505 static void iwl_mvm_tcm_results(struct iwl_mvm *mvm)
1506 {
1507 	struct iwl_mvm_tcm_iter_data data = {
1508 		.mvm = mvm,
1509 		.any_sent = false,
1510 	};
1511 
1512 	mutex_lock(&mvm->mutex);
1513 
1514 	ieee80211_iterate_active_interfaces(
1515 		mvm->hw, IEEE80211_IFACE_ITER_NORMAL,
1516 		iwl_mvm_tcm_iter, &data);
1517 
1518 	if (fw_has_capa(&mvm->fw->ucode_capa, IWL_UCODE_TLV_CAPA_UMAC_SCAN))
1519 		iwl_mvm_config_scan(mvm);
1520 
1521 	mutex_unlock(&mvm->mutex);
1522 }
1523 
1524 static void iwl_mvm_tcm_uapsd_nonagg_detected_wk(struct work_struct *wk)
1525 {
1526 	struct iwl_mvm *mvm;
1527 	struct iwl_mvm_vif *mvmvif;
1528 	struct ieee80211_vif *vif;
1529 
1530 	mvmvif = container_of(wk, struct iwl_mvm_vif,
1531 			      uapsd_nonagg_detected_wk.work);
1532 	vif = container_of((void *)mvmvif, struct ieee80211_vif, drv_priv);
1533 	mvm = mvmvif->mvm;
1534 
1535 	if (mvm->tcm.data[mvmvif->id].opened_rx_ba_sessions)
1536 		return;
1537 
1538 	/* remember that this AP is broken */
1539 	memcpy(mvm->uapsd_noagg_bssids[mvm->uapsd_noagg_bssid_write_idx].addr,
1540 	       vif->bss_conf.bssid, ETH_ALEN);
1541 	mvm->uapsd_noagg_bssid_write_idx++;
1542 	if (mvm->uapsd_noagg_bssid_write_idx >= IWL_MVM_UAPSD_NOAGG_LIST_LEN)
1543 		mvm->uapsd_noagg_bssid_write_idx = 0;
1544 
1545 	iwl_mvm_connection_loss(mvm, vif,
1546 				"AP isn't using AMPDU with uAPSD enabled");
1547 }
1548 
1549 static void iwl_mvm_uapsd_agg_disconnect_iter(void *data, u8 *mac,
1550 					      struct ieee80211_vif *vif)
1551 {
1552 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
1553 	struct iwl_mvm *mvm = mvmvif->mvm;
1554 	int *mac_id = data;
1555 
1556 	if (vif->type != NL80211_IFTYPE_STATION)
1557 		return;
1558 
1559 	if (mvmvif->id != *mac_id)
1560 		return;
1561 
1562 	if (!vif->bss_conf.assoc)
1563 		return;
1564 
1565 	if (!mvmvif->queue_params[IEEE80211_AC_VO].uapsd &&
1566 	    !mvmvif->queue_params[IEEE80211_AC_VI].uapsd &&
1567 	    !mvmvif->queue_params[IEEE80211_AC_BE].uapsd &&
1568 	    !mvmvif->queue_params[IEEE80211_AC_BK].uapsd)
1569 		return;
1570 
1571 	if (mvm->tcm.data[*mac_id].uapsd_nonagg_detect.detected)
1572 		return;
1573 
1574 	mvm->tcm.data[*mac_id].uapsd_nonagg_detect.detected = true;
1575 	IWL_INFO(mvm,
1576 		 "detected AP should do aggregation but isn't, likely due to U-APSD\n");
1577 	schedule_delayed_work(&mvmvif->uapsd_nonagg_detected_wk, 15 * HZ);
1578 }
1579 
1580 static void iwl_mvm_check_uapsd_agg_expected_tpt(struct iwl_mvm *mvm,
1581 						 unsigned int elapsed,
1582 						 int mac)
1583 {
1584 	u64 bytes = mvm->tcm.data[mac].uapsd_nonagg_detect.rx_bytes;
1585 	u64 tpt;
1586 	unsigned long rate;
1587 
1588 	rate = ewma_rate_read(&mvm->tcm.data[mac].uapsd_nonagg_detect.rate);
1589 
1590 	if (!rate || mvm->tcm.data[mac].opened_rx_ba_sessions ||
1591 	    mvm->tcm.data[mac].uapsd_nonagg_detect.detected)
1592 		return;
1593 
1594 	if (iwl_mvm_has_new_rx_api(mvm)) {
1595 		tpt = 8 * bytes; /* kbps */
1596 		do_div(tpt, elapsed);
1597 		rate *= 1000; /* kbps */
1598 		if (tpt < 22 * rate / 100)
1599 			return;
1600 	} else {
1601 		/*
1602 		 * the rate here is actually the threshold, in 100Kbps units,
1603 		 * so do the needed conversion from bytes to 100Kbps:
1604 		 * 100kb = bits / (100 * 1000),
1605 		 * 100kbps = 100kb / (msecs / 1000) ==
1606 		 *           (bits / (100 * 1000)) / (msecs / 1000) ==
1607 		 *           bits / (100 * msecs)
1608 		 */
1609 		tpt = (8 * bytes);
1610 		do_div(tpt, elapsed * 100);
1611 		if (tpt < rate)
1612 			return;
1613 	}
1614 
1615 	ieee80211_iterate_active_interfaces_atomic(
1616 		mvm->hw, IEEE80211_IFACE_ITER_NORMAL,
1617 		iwl_mvm_uapsd_agg_disconnect_iter, &mac);
1618 }
1619 
1620 static void iwl_mvm_tcm_iterator(void *_data, u8 *mac,
1621 				 struct ieee80211_vif *vif)
1622 {
1623 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
1624 	u32 *band = _data;
1625 
1626 	if (!mvmvif->phy_ctxt)
1627 		return;
1628 
1629 	band[mvmvif->id] = mvmvif->phy_ctxt->channel->band;
1630 }
1631 
1632 static unsigned long iwl_mvm_calc_tcm_stats(struct iwl_mvm *mvm,
1633 					    unsigned long ts,
1634 					    bool handle_uapsd)
1635 {
1636 	unsigned int elapsed = jiffies_to_msecs(ts - mvm->tcm.ts);
1637 	unsigned int uapsd_elapsed =
1638 		jiffies_to_msecs(ts - mvm->tcm.uapsd_nonagg_ts);
1639 	u32 total_airtime = 0;
1640 	u32 band_airtime[NUM_NL80211_BANDS] = {0};
1641 	u32 band[NUM_MAC_INDEX_DRIVER] = {0};
1642 	int ac, mac, i;
1643 	bool low_latency = false;
1644 	enum iwl_mvm_traffic_load load, band_load;
1645 	bool handle_ll = time_after(ts, mvm->tcm.ll_ts + MVM_LL_PERIOD);
1646 
1647 	if (handle_ll)
1648 		mvm->tcm.ll_ts = ts;
1649 	if (handle_uapsd)
1650 		mvm->tcm.uapsd_nonagg_ts = ts;
1651 
1652 	mvm->tcm.result.elapsed = elapsed;
1653 
1654 	ieee80211_iterate_active_interfaces_atomic(mvm->hw,
1655 						   IEEE80211_IFACE_ITER_NORMAL,
1656 						   iwl_mvm_tcm_iterator,
1657 						   &band);
1658 
1659 	for (mac = 0; mac < NUM_MAC_INDEX_DRIVER; mac++) {
1660 		struct iwl_mvm_tcm_mac *mdata = &mvm->tcm.data[mac];
1661 		u32 vo_vi_pkts = 0;
1662 		u32 airtime = mdata->rx.airtime + mdata->tx.airtime;
1663 
1664 		total_airtime += airtime;
1665 		band_airtime[band[mac]] += airtime;
1666 
1667 		load = iwl_mvm_tcm_load(mvm, airtime, elapsed);
1668 		mvm->tcm.result.change[mac] = load != mvm->tcm.result.load[mac];
1669 		mvm->tcm.result.load[mac] = load;
1670 		mvm->tcm.result.airtime[mac] = airtime;
1671 
1672 		for (ac = IEEE80211_AC_VO; ac <= IEEE80211_AC_VI; ac++)
1673 			vo_vi_pkts += mdata->rx.pkts[ac] +
1674 				      mdata->tx.pkts[ac];
1675 
1676 		/* enable immediately with enough packets but defer disabling */
1677 		if (vo_vi_pkts > IWL_MVM_TCM_LOWLAT_ENABLE_THRESH)
1678 			mvm->tcm.result.low_latency[mac] = true;
1679 		else if (handle_ll)
1680 			mvm->tcm.result.low_latency[mac] = false;
1681 
1682 		if (handle_ll) {
1683 			/* clear old data */
1684 			memset(&mdata->rx.pkts, 0, sizeof(mdata->rx.pkts));
1685 			memset(&mdata->tx.pkts, 0, sizeof(mdata->tx.pkts));
1686 		}
1687 		low_latency |= mvm->tcm.result.low_latency[mac];
1688 
1689 		if (!mvm->tcm.result.low_latency[mac] && handle_uapsd)
1690 			iwl_mvm_check_uapsd_agg_expected_tpt(mvm, uapsd_elapsed,
1691 							     mac);
1692 		/* clear old data */
1693 		if (handle_uapsd)
1694 			mdata->uapsd_nonagg_detect.rx_bytes = 0;
1695 		memset(&mdata->rx.airtime, 0, sizeof(mdata->rx.airtime));
1696 		memset(&mdata->tx.airtime, 0, sizeof(mdata->tx.airtime));
1697 	}
1698 
1699 	load = iwl_mvm_tcm_load(mvm, total_airtime, elapsed);
1700 	mvm->tcm.result.global_change = load != mvm->tcm.result.global_load;
1701 	mvm->tcm.result.global_load = load;
1702 
1703 	for (i = 0; i < NUM_NL80211_BANDS; i++) {
1704 		band_load = iwl_mvm_tcm_load(mvm, band_airtime[i], elapsed);
1705 		mvm->tcm.result.band_load[i] = band_load;
1706 	}
1707 
1708 	/*
1709 	 * If the current load isn't low we need to force re-evaluation
1710 	 * in the TCM period, so that we can return to low load if there
1711 	 * was no traffic at all (and thus iwl_mvm_recalc_tcm didn't get
1712 	 * triggered by traffic).
1713 	 */
1714 	if (load != IWL_MVM_TRAFFIC_LOW)
1715 		return MVM_TCM_PERIOD;
1716 	/*
1717 	 * If low-latency is active we need to force re-evaluation after
1718 	 * (the longer) MVM_LL_PERIOD, so that we can disable low-latency
1719 	 * when there's no traffic at all.
1720 	 */
1721 	if (low_latency)
1722 		return MVM_LL_PERIOD;
1723 	/*
1724 	 * Otherwise, we don't need to run the work struct because we're
1725 	 * in the default "idle" state - traffic indication is low (which
1726 	 * also covers the "no traffic" case) and low-latency is disabled
1727 	 * so there's no state that may need to be disabled when there's
1728 	 * no traffic at all.
1729 	 *
1730 	 * Note that this has no impact on the regular scheduling of the
1731 	 * updates triggered by traffic - those happen whenever one of the
1732 	 * two timeouts expire (if there's traffic at all.)
1733 	 */
1734 	return 0;
1735 }
1736 
1737 void iwl_mvm_recalc_tcm(struct iwl_mvm *mvm)
1738 {
1739 	unsigned long ts = jiffies;
1740 	bool handle_uapsd =
1741 		time_after(ts, mvm->tcm.uapsd_nonagg_ts +
1742 			       msecs_to_jiffies(IWL_MVM_UAPSD_NONAGG_PERIOD));
1743 
1744 	spin_lock(&mvm->tcm.lock);
1745 	if (mvm->tcm.paused || !time_after(ts, mvm->tcm.ts + MVM_TCM_PERIOD)) {
1746 		spin_unlock(&mvm->tcm.lock);
1747 		return;
1748 	}
1749 	spin_unlock(&mvm->tcm.lock);
1750 
1751 	if (handle_uapsd && iwl_mvm_has_new_rx_api(mvm)) {
1752 		mutex_lock(&mvm->mutex);
1753 		if (iwl_mvm_request_statistics(mvm, true))
1754 			handle_uapsd = false;
1755 		mutex_unlock(&mvm->mutex);
1756 	}
1757 
1758 	spin_lock(&mvm->tcm.lock);
1759 	/* re-check if somebody else won the recheck race */
1760 	if (!mvm->tcm.paused && time_after(ts, mvm->tcm.ts + MVM_TCM_PERIOD)) {
1761 		/* calculate statistics */
1762 		unsigned long work_delay = iwl_mvm_calc_tcm_stats(mvm, ts,
1763 								  handle_uapsd);
1764 
1765 		/* the memset needs to be visible before the timestamp */
1766 		smp_mb();
1767 		mvm->tcm.ts = ts;
1768 		if (work_delay)
1769 			schedule_delayed_work(&mvm->tcm.work, work_delay);
1770 	}
1771 	spin_unlock(&mvm->tcm.lock);
1772 
1773 	iwl_mvm_tcm_results(mvm);
1774 }
1775 
1776 void iwl_mvm_tcm_work(struct work_struct *work)
1777 {
1778 	struct delayed_work *delayed_work = to_delayed_work(work);
1779 	struct iwl_mvm *mvm = container_of(delayed_work, struct iwl_mvm,
1780 					   tcm.work);
1781 
1782 	iwl_mvm_recalc_tcm(mvm);
1783 }
1784 
1785 void iwl_mvm_pause_tcm(struct iwl_mvm *mvm, bool with_cancel)
1786 {
1787 	spin_lock_bh(&mvm->tcm.lock);
1788 	mvm->tcm.paused = true;
1789 	spin_unlock_bh(&mvm->tcm.lock);
1790 	if (with_cancel)
1791 		cancel_delayed_work_sync(&mvm->tcm.work);
1792 }
1793 
1794 void iwl_mvm_resume_tcm(struct iwl_mvm *mvm)
1795 {
1796 	int mac;
1797 
1798 	spin_lock_bh(&mvm->tcm.lock);
1799 	mvm->tcm.ts = jiffies;
1800 	mvm->tcm.ll_ts = jiffies;
1801 	for (mac = 0; mac < NUM_MAC_INDEX_DRIVER; mac++) {
1802 		struct iwl_mvm_tcm_mac *mdata = &mvm->tcm.data[mac];
1803 
1804 		memset(&mdata->rx.pkts, 0, sizeof(mdata->rx.pkts));
1805 		memset(&mdata->tx.pkts, 0, sizeof(mdata->tx.pkts));
1806 		memset(&mdata->rx.airtime, 0, sizeof(mdata->rx.airtime));
1807 		memset(&mdata->tx.airtime, 0, sizeof(mdata->tx.airtime));
1808 	}
1809 	/* The TCM data needs to be reset before "paused" flag changes */
1810 	smp_mb();
1811 	mvm->tcm.paused = false;
1812 	spin_unlock_bh(&mvm->tcm.lock);
1813 }
1814 
1815 void iwl_mvm_tcm_add_vif(struct iwl_mvm *mvm, struct ieee80211_vif *vif)
1816 {
1817 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
1818 
1819 	INIT_DELAYED_WORK(&mvmvif->uapsd_nonagg_detected_wk,
1820 			  iwl_mvm_tcm_uapsd_nonagg_detected_wk);
1821 }
1822 
1823 void iwl_mvm_tcm_rm_vif(struct iwl_mvm *mvm, struct ieee80211_vif *vif)
1824 {
1825 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
1826 
1827 	cancel_delayed_work_sync(&mvmvif->uapsd_nonagg_detected_wk);
1828 }
1829 
1830 
1831 void iwl_mvm_get_sync_time(struct iwl_mvm *mvm, u32 *gp2, u64 *boottime)
1832 {
1833 	bool ps_disabled;
1834 
1835 	lockdep_assert_held(&mvm->mutex);
1836 
1837 	/* Disable power save when reading GP2 */
1838 	ps_disabled = mvm->ps_disabled;
1839 	if (!ps_disabled) {
1840 		mvm->ps_disabled = true;
1841 		iwl_mvm_power_update_device(mvm);
1842 	}
1843 
1844 	*gp2 = iwl_read_prph(mvm->trans, DEVICE_SYSTEM_TIME_REG);
1845 	*boottime = ktime_get_boot_ns();
1846 
1847 	if (!ps_disabled) {
1848 		mvm->ps_disabled = ps_disabled;
1849 		iwl_mvm_power_update_device(mvm);
1850 	}
1851 }
1852