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