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