xref: /linux/drivers/net/wireless/intel/iwlwifi/mvm/utils.c (revision dc52fac37c874cfb909caf6bef34edf69503b979)
1 // SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
2 /*
3  * Copyright (C) 2012-2014, 2018-2021 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 int iwl_mvm_legacy_hw_idx_to_mac80211_idx(u32 rate_n_flags,
139 					  enum nl80211_band band)
140 {
141 	int format = rate_n_flags & RATE_MCS_MOD_TYPE_MSK;
142 	int rate = rate_n_flags & RATE_LEGACY_RATE_MSK;
143 	bool is_LB = band == NL80211_BAND_2GHZ;
144 
145 	if (format == RATE_MCS_LEGACY_OFDM_MSK)
146 		return is_LB ? rate + IWL_FIRST_OFDM_RATE :
147 			rate;
148 
149 	/* CCK is not allowed in HB */
150 	return is_LB ? rate : -1;
151 }
152 
153 int iwl_mvm_legacy_rate_to_mac80211_idx(u32 rate_n_flags,
154 					enum nl80211_band band)
155 {
156 	int rate = rate_n_flags & RATE_LEGACY_RATE_MSK_V1;
157 	int idx;
158 	int band_offset = 0;
159 
160 	/* Legacy rate format, search for match in table */
161 	if (band != NL80211_BAND_2GHZ)
162 		band_offset = IWL_FIRST_OFDM_RATE;
163 	for (idx = band_offset; idx < IWL_RATE_COUNT_LEGACY; idx++)
164 		if (iwl_fw_rate_idx_to_plcp(idx) == rate)
165 			return idx - band_offset;
166 
167 	return -1;
168 }
169 
170 u8 iwl_mvm_mac80211_idx_to_hwrate(const struct iwl_fw *fw, int rate_idx)
171 {
172 	if (iwl_fw_lookup_cmd_ver(fw, LONG_GROUP,
173 				  TX_CMD, 0) > 8)
174 		/* In the new rate legacy rates are indexed:
175 		 * 0 - 3 for CCK and 0 - 7 for OFDM.
176 		 */
177 		return (rate_idx >= IWL_FIRST_OFDM_RATE ?
178 			rate_idx - IWL_FIRST_OFDM_RATE :
179 			rate_idx);
180 
181 	return iwl_fw_rate_idx_to_plcp(rate_idx);
182 }
183 
184 u8 iwl_mvm_mac80211_ac_to_ucode_ac(enum ieee80211_ac_numbers ac)
185 {
186 	static const u8 mac80211_ac_to_ucode_ac[] = {
187 		AC_VO,
188 		AC_VI,
189 		AC_BE,
190 		AC_BK
191 	};
192 
193 	return mac80211_ac_to_ucode_ac[ac];
194 }
195 
196 void iwl_mvm_rx_fw_error(struct iwl_mvm *mvm, struct iwl_rx_cmd_buffer *rxb)
197 {
198 	struct iwl_rx_packet *pkt = rxb_addr(rxb);
199 	struct iwl_error_resp *err_resp = (void *)pkt->data;
200 
201 	IWL_ERR(mvm, "FW Error notification: type 0x%08X cmd_id 0x%02X\n",
202 		le32_to_cpu(err_resp->error_type), err_resp->cmd_id);
203 	IWL_ERR(mvm, "FW Error notification: seq 0x%04X service 0x%08X\n",
204 		le16_to_cpu(err_resp->bad_cmd_seq_num),
205 		le32_to_cpu(err_resp->error_service));
206 	IWL_ERR(mvm, "FW Error notification: timestamp 0x%016llX\n",
207 		le64_to_cpu(err_resp->timestamp));
208 }
209 
210 /*
211  * Returns the first antenna as ANT_[ABC], as defined in iwl-config.h.
212  * The parameter should also be a combination of ANT_[ABC].
213  */
214 u8 first_antenna(u8 mask)
215 {
216 	BUILD_BUG_ON(ANT_A != BIT(0)); /* using ffs is wrong if not */
217 	if (WARN_ON_ONCE(!mask)) /* ffs will return 0 if mask is zeroed */
218 		return BIT(0);
219 	return BIT(ffs(mask) - 1);
220 }
221 
222 #define MAX_ANT_NUM 2
223 /*
224  * Toggles between TX antennas to send the probe request on.
225  * Receives the bitmask of valid TX antennas and the *index* used
226  * for the last TX, and returns the next valid *index* to use.
227  * In order to set it in the tx_cmd, must do BIT(idx).
228  */
229 u8 iwl_mvm_next_antenna(struct iwl_mvm *mvm, u8 valid, u8 last_idx)
230 {
231 	u8 ind = last_idx;
232 	int i;
233 
234 	for (i = 0; i < MAX_ANT_NUM; i++) {
235 		ind = (ind + 1) % MAX_ANT_NUM;
236 		if (valid & BIT(ind))
237 			return ind;
238 	}
239 
240 	WARN_ONCE(1, "Failed to toggle between antennas 0x%x", valid);
241 	return last_idx;
242 }
243 
244 int iwl_mvm_reconfig_scd(struct iwl_mvm *mvm, int queue, int fifo, int sta_id,
245 			 int tid, int frame_limit, u16 ssn)
246 {
247 	struct iwl_scd_txq_cfg_cmd cmd = {
248 		.scd_queue = queue,
249 		.action = SCD_CFG_ENABLE_QUEUE,
250 		.window = frame_limit,
251 		.sta_id = sta_id,
252 		.ssn = cpu_to_le16(ssn),
253 		.tx_fifo = fifo,
254 		.aggregate = (queue >= IWL_MVM_DQA_MIN_DATA_QUEUE ||
255 			      queue == IWL_MVM_DQA_BSS_CLIENT_QUEUE),
256 		.tid = tid,
257 	};
258 	int ret;
259 
260 	if (WARN_ON(iwl_mvm_has_new_tx_api(mvm)))
261 		return -EINVAL;
262 
263 	if (WARN(mvm->queue_info[queue].tid_bitmap == 0,
264 		 "Trying to reconfig unallocated queue %d\n", queue))
265 		return -ENXIO;
266 
267 	IWL_DEBUG_TX_QUEUES(mvm, "Reconfig SCD for TXQ #%d\n", queue);
268 
269 	ret = iwl_mvm_send_cmd_pdu(mvm, SCD_QUEUE_CFG, 0, sizeof(cmd), &cmd);
270 	WARN_ONCE(ret, "Failed to re-configure queue %d on FIFO %d, ret=%d\n",
271 		  queue, fifo, ret);
272 
273 	return ret;
274 }
275 
276 /**
277  * iwl_mvm_send_lq_cmd() - Send link quality command
278  * @mvm: Driver data.
279  * @lq: Link quality command to send.
280  *
281  * The link quality command is sent as the last step of station creation.
282  * This is the special case in which init is set and we call a callback in
283  * this case to clear the state indicating that station creation is in
284  * progress.
285  */
286 int iwl_mvm_send_lq_cmd(struct iwl_mvm *mvm, struct iwl_lq_cmd *lq)
287 {
288 	struct iwl_host_cmd cmd = {
289 		.id = LQ_CMD,
290 		.len = { sizeof(struct iwl_lq_cmd), },
291 		.flags = CMD_ASYNC,
292 		.data = { lq, },
293 	};
294 
295 	if (WARN_ON(lq->sta_id == IWL_MVM_INVALID_STA ||
296 		    iwl_mvm_has_tlc_offload(mvm)))
297 		return -EINVAL;
298 
299 	return iwl_mvm_send_cmd(mvm, &cmd);
300 }
301 
302 /**
303  * iwl_mvm_update_smps - Get a request to change the SMPS mode
304  * @mvm: Driver data.
305  * @vif: Pointer to the ieee80211_vif structure
306  * @req_type: The part of the driver who call for a change.
307  * @smps_request: The request to change the SMPS mode.
308  *
309  * Get a requst to change the SMPS mode,
310  * and change it according to all other requests in the driver.
311  */
312 void iwl_mvm_update_smps(struct iwl_mvm *mvm, struct ieee80211_vif *vif,
313 			 enum iwl_mvm_smps_type_request req_type,
314 			 enum ieee80211_smps_mode smps_request)
315 {
316 	struct iwl_mvm_vif *mvmvif;
317 	enum ieee80211_smps_mode smps_mode = IEEE80211_SMPS_AUTOMATIC;
318 	int i;
319 
320 	lockdep_assert_held(&mvm->mutex);
321 
322 	/* SMPS is irrelevant for NICs that don't have at least 2 RX antenna */
323 	if (num_of_ant(iwl_mvm_get_valid_rx_ant(mvm)) == 1)
324 		return;
325 
326 	if (vif->type != NL80211_IFTYPE_STATION)
327 		return;
328 
329 	mvmvif = iwl_mvm_vif_from_mac80211(vif);
330 	mvmvif->smps_requests[req_type] = smps_request;
331 	for (i = 0; i < NUM_IWL_MVM_SMPS_REQ; i++) {
332 		if (mvmvif->smps_requests[i] == IEEE80211_SMPS_STATIC) {
333 			smps_mode = IEEE80211_SMPS_STATIC;
334 			break;
335 		}
336 		if (mvmvif->smps_requests[i] == IEEE80211_SMPS_DYNAMIC)
337 			smps_mode = IEEE80211_SMPS_DYNAMIC;
338 	}
339 
340 	ieee80211_request_smps(vif, smps_mode);
341 }
342 
343 int iwl_mvm_request_statistics(struct iwl_mvm *mvm, bool clear)
344 {
345 	struct iwl_statistics_cmd scmd = {
346 		.flags = clear ? cpu_to_le32(IWL_STATISTICS_FLG_CLEAR) : 0,
347 	};
348 	struct iwl_host_cmd cmd = {
349 		.id = STATISTICS_CMD,
350 		.len[0] = sizeof(scmd),
351 		.data[0] = &scmd,
352 		.flags = CMD_WANT_SKB,
353 	};
354 	int ret;
355 
356 	ret = iwl_mvm_send_cmd(mvm, &cmd);
357 	if (ret)
358 		return ret;
359 
360 	iwl_mvm_handle_rx_statistics(mvm, cmd.resp_pkt);
361 	iwl_free_resp(&cmd);
362 
363 	if (clear)
364 		iwl_mvm_accu_radio_stats(mvm);
365 
366 	return 0;
367 }
368 
369 void iwl_mvm_accu_radio_stats(struct iwl_mvm *mvm)
370 {
371 	mvm->accu_radio_stats.rx_time += mvm->radio_stats.rx_time;
372 	mvm->accu_radio_stats.tx_time += mvm->radio_stats.tx_time;
373 	mvm->accu_radio_stats.on_time_rf += mvm->radio_stats.on_time_rf;
374 	mvm->accu_radio_stats.on_time_scan += mvm->radio_stats.on_time_scan;
375 }
376 
377 struct iwl_mvm_diversity_iter_data {
378 	struct iwl_mvm_phy_ctxt *ctxt;
379 	bool result;
380 };
381 
382 static void iwl_mvm_diversity_iter(void *_data, u8 *mac,
383 				   struct ieee80211_vif *vif)
384 {
385 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
386 	struct iwl_mvm_diversity_iter_data *data = _data;
387 	int i;
388 
389 	if (mvmvif->phy_ctxt != data->ctxt)
390 		return;
391 
392 	for (i = 0; i < NUM_IWL_MVM_SMPS_REQ; i++) {
393 		if (mvmvif->smps_requests[i] == IEEE80211_SMPS_STATIC ||
394 		    mvmvif->smps_requests[i] == IEEE80211_SMPS_DYNAMIC) {
395 			data->result = false;
396 			break;
397 		}
398 	}
399 }
400 
401 bool iwl_mvm_rx_diversity_allowed(struct iwl_mvm *mvm,
402 				  struct iwl_mvm_phy_ctxt *ctxt)
403 {
404 	struct iwl_mvm_diversity_iter_data data = {
405 		.ctxt = ctxt,
406 		.result = true,
407 	};
408 
409 	lockdep_assert_held(&mvm->mutex);
410 
411 	if (iwlmvm_mod_params.power_scheme != IWL_POWER_SCHEME_CAM)
412 		return false;
413 
414 	if (num_of_ant(iwl_mvm_get_valid_rx_ant(mvm)) == 1)
415 		return false;
416 
417 	if (mvm->cfg->rx_with_siso_diversity)
418 		return false;
419 
420 	ieee80211_iterate_active_interfaces_atomic(
421 			mvm->hw, IEEE80211_IFACE_ITER_NORMAL,
422 			iwl_mvm_diversity_iter, &data);
423 
424 	return data.result;
425 }
426 
427 void iwl_mvm_send_low_latency_cmd(struct iwl_mvm *mvm,
428 				  bool low_latency, u16 mac_id)
429 {
430 	struct iwl_mac_low_latency_cmd cmd = {
431 		.mac_id = cpu_to_le32(mac_id)
432 	};
433 
434 	if (!fw_has_capa(&mvm->fw->ucode_capa,
435 			 IWL_UCODE_TLV_CAPA_DYNAMIC_QUOTA))
436 		return;
437 
438 	if (low_latency) {
439 		/* currently we don't care about the direction */
440 		cmd.low_latency_rx = 1;
441 		cmd.low_latency_tx = 1;
442 	}
443 
444 	if (iwl_mvm_send_cmd_pdu(mvm, iwl_cmd_id(LOW_LATENCY_CMD,
445 						 MAC_CONF_GROUP, 0),
446 				 0, sizeof(cmd), &cmd))
447 		IWL_ERR(mvm, "Failed to send low latency command\n");
448 }
449 
450 int iwl_mvm_update_low_latency(struct iwl_mvm *mvm, struct ieee80211_vif *vif,
451 			       bool low_latency,
452 			       enum iwl_mvm_low_latency_cause cause)
453 {
454 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
455 	int res;
456 	bool prev;
457 
458 	lockdep_assert_held(&mvm->mutex);
459 
460 	prev = iwl_mvm_vif_low_latency(mvmvif);
461 	iwl_mvm_vif_set_low_latency(mvmvif, low_latency, cause);
462 
463 	low_latency = iwl_mvm_vif_low_latency(mvmvif);
464 
465 	if (low_latency == prev)
466 		return 0;
467 
468 	iwl_mvm_send_low_latency_cmd(mvm, low_latency, mvmvif->id);
469 
470 	res = iwl_mvm_update_quotas(mvm, false, NULL);
471 	if (res)
472 		return res;
473 
474 	iwl_mvm_bt_coex_vif_change(mvm);
475 
476 	return iwl_mvm_power_update_mac(mvm);
477 }
478 
479 struct iwl_mvm_low_latency_iter {
480 	bool result;
481 	bool result_per_band[NUM_NL80211_BANDS];
482 };
483 
484 static void iwl_mvm_ll_iter(void *_data, u8 *mac, struct ieee80211_vif *vif)
485 {
486 	struct iwl_mvm_low_latency_iter *result = _data;
487 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
488 	enum nl80211_band band;
489 
490 	if (iwl_mvm_vif_low_latency(mvmvif)) {
491 		result->result = true;
492 
493 		if (!mvmvif->phy_ctxt)
494 			return;
495 
496 		band = mvmvif->phy_ctxt->channel->band;
497 		result->result_per_band[band] = true;
498 	}
499 }
500 
501 bool iwl_mvm_low_latency(struct iwl_mvm *mvm)
502 {
503 	struct iwl_mvm_low_latency_iter data = {};
504 
505 	ieee80211_iterate_active_interfaces_atomic(
506 			mvm->hw, IEEE80211_IFACE_ITER_NORMAL,
507 			iwl_mvm_ll_iter, &data);
508 
509 	return data.result;
510 }
511 
512 bool iwl_mvm_low_latency_band(struct iwl_mvm *mvm, enum nl80211_band band)
513 {
514 	struct iwl_mvm_low_latency_iter data = {};
515 
516 	ieee80211_iterate_active_interfaces_atomic(
517 			mvm->hw, IEEE80211_IFACE_ITER_NORMAL,
518 			iwl_mvm_ll_iter, &data);
519 
520 	return data.result_per_band[band];
521 }
522 
523 struct iwl_bss_iter_data {
524 	struct ieee80211_vif *vif;
525 	bool error;
526 };
527 
528 static void iwl_mvm_bss_iface_iterator(void *_data, u8 *mac,
529 				       struct ieee80211_vif *vif)
530 {
531 	struct iwl_bss_iter_data *data = _data;
532 
533 	if (vif->type != NL80211_IFTYPE_STATION || vif->p2p)
534 		return;
535 
536 	if (data->vif) {
537 		data->error = true;
538 		return;
539 	}
540 
541 	data->vif = vif;
542 }
543 
544 struct ieee80211_vif *iwl_mvm_get_bss_vif(struct iwl_mvm *mvm)
545 {
546 	struct iwl_bss_iter_data bss_iter_data = {};
547 
548 	ieee80211_iterate_active_interfaces_atomic(
549 		mvm->hw, IEEE80211_IFACE_ITER_NORMAL,
550 		iwl_mvm_bss_iface_iterator, &bss_iter_data);
551 
552 	if (bss_iter_data.error) {
553 		IWL_ERR(mvm, "More than one managed interface active!\n");
554 		return ERR_PTR(-EINVAL);
555 	}
556 
557 	return bss_iter_data.vif;
558 }
559 
560 struct iwl_bss_find_iter_data {
561 	struct ieee80211_vif *vif;
562 	u32 macid;
563 };
564 
565 static void iwl_mvm_bss_find_iface_iterator(void *_data, u8 *mac,
566 					    struct ieee80211_vif *vif)
567 {
568 	struct iwl_bss_find_iter_data *data = _data;
569 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
570 
571 	if (mvmvif->id == data->macid)
572 		data->vif = vif;
573 }
574 
575 struct ieee80211_vif *iwl_mvm_get_vif_by_macid(struct iwl_mvm *mvm, u32 macid)
576 {
577 	struct iwl_bss_find_iter_data data = {
578 		.macid = macid,
579 	};
580 
581 	lockdep_assert_held(&mvm->mutex);
582 
583 	ieee80211_iterate_active_interfaces_atomic(
584 		mvm->hw, IEEE80211_IFACE_ITER_NORMAL,
585 		iwl_mvm_bss_find_iface_iterator, &data);
586 
587 	return data.vif;
588 }
589 
590 struct iwl_sta_iter_data {
591 	bool assoc;
592 };
593 
594 static void iwl_mvm_sta_iface_iterator(void *_data, u8 *mac,
595 				       struct ieee80211_vif *vif)
596 {
597 	struct iwl_sta_iter_data *data = _data;
598 
599 	if (vif->type != NL80211_IFTYPE_STATION)
600 		return;
601 
602 	if (vif->bss_conf.assoc)
603 		data->assoc = true;
604 }
605 
606 bool iwl_mvm_is_vif_assoc(struct iwl_mvm *mvm)
607 {
608 	struct iwl_sta_iter_data data = {
609 		.assoc = false,
610 	};
611 
612 	ieee80211_iterate_active_interfaces_atomic(mvm->hw,
613 						   IEEE80211_IFACE_ITER_NORMAL,
614 						   iwl_mvm_sta_iface_iterator,
615 						   &data);
616 	return data.assoc;
617 }
618 
619 unsigned int iwl_mvm_get_wd_timeout(struct iwl_mvm *mvm,
620 				    struct ieee80211_vif *vif,
621 				    bool tdls, bool cmd_q)
622 {
623 	struct iwl_fw_dbg_trigger_tlv *trigger;
624 	struct iwl_fw_dbg_trigger_txq_timer *txq_timer;
625 	unsigned int default_timeout = cmd_q ?
626 		IWL_DEF_WD_TIMEOUT :
627 		mvm->trans->trans_cfg->base_params->wd_timeout;
628 
629 	if (!iwl_fw_dbg_trigger_enabled(mvm->fw, FW_DBG_TRIGGER_TXQ_TIMERS)) {
630 		/*
631 		 * We can't know when the station is asleep or awake, so we
632 		 * must disable the queue hang detection.
633 		 */
634 		if (fw_has_capa(&mvm->fw->ucode_capa,
635 				IWL_UCODE_TLV_CAPA_STA_PM_NOTIF) &&
636 		    vif && vif->type == NL80211_IFTYPE_AP)
637 			return IWL_WATCHDOG_DISABLED;
638 		return default_timeout;
639 	}
640 
641 	trigger = iwl_fw_dbg_get_trigger(mvm->fw, FW_DBG_TRIGGER_TXQ_TIMERS);
642 	txq_timer = (void *)trigger->data;
643 
644 	if (tdls)
645 		return le32_to_cpu(txq_timer->tdls);
646 
647 	if (cmd_q)
648 		return le32_to_cpu(txq_timer->command_queue);
649 
650 	if (WARN_ON(!vif))
651 		return default_timeout;
652 
653 	switch (ieee80211_vif_type_p2p(vif)) {
654 	case NL80211_IFTYPE_ADHOC:
655 		return le32_to_cpu(txq_timer->ibss);
656 	case NL80211_IFTYPE_STATION:
657 		return le32_to_cpu(txq_timer->bss);
658 	case NL80211_IFTYPE_AP:
659 		return le32_to_cpu(txq_timer->softap);
660 	case NL80211_IFTYPE_P2P_CLIENT:
661 		return le32_to_cpu(txq_timer->p2p_client);
662 	case NL80211_IFTYPE_P2P_GO:
663 		return le32_to_cpu(txq_timer->p2p_go);
664 	case NL80211_IFTYPE_P2P_DEVICE:
665 		return le32_to_cpu(txq_timer->p2p_device);
666 	case NL80211_IFTYPE_MONITOR:
667 		return default_timeout;
668 	default:
669 		WARN_ON(1);
670 		return mvm->trans->trans_cfg->base_params->wd_timeout;
671 	}
672 }
673 
674 void iwl_mvm_connection_loss(struct iwl_mvm *mvm, struct ieee80211_vif *vif,
675 			     const char *errmsg)
676 {
677 	struct iwl_fw_dbg_trigger_tlv *trig;
678 	struct iwl_fw_dbg_trigger_mlme *trig_mlme;
679 
680 	trig = iwl_fw_dbg_trigger_on(&mvm->fwrt, ieee80211_vif_to_wdev(vif),
681 				     FW_DBG_TRIGGER_MLME);
682 	if (!trig)
683 		goto out;
684 
685 	trig_mlme = (void *)trig->data;
686 
687 	if (trig_mlme->stop_connection_loss &&
688 	    --trig_mlme->stop_connection_loss)
689 		goto out;
690 
691 	iwl_fw_dbg_collect_trig(&mvm->fwrt, trig, "%s", errmsg);
692 
693 out:
694 	ieee80211_connection_loss(vif);
695 }
696 
697 void iwl_mvm_event_frame_timeout_callback(struct iwl_mvm *mvm,
698 					  struct ieee80211_vif *vif,
699 					  const struct ieee80211_sta *sta,
700 					  u16 tid)
701 {
702 	struct iwl_fw_dbg_trigger_tlv *trig;
703 	struct iwl_fw_dbg_trigger_ba *ba_trig;
704 
705 	trig = iwl_fw_dbg_trigger_on(&mvm->fwrt, ieee80211_vif_to_wdev(vif),
706 				     FW_DBG_TRIGGER_BA);
707 	if (!trig)
708 		return;
709 
710 	ba_trig = (void *)trig->data;
711 
712 	if (!(le16_to_cpu(ba_trig->frame_timeout) & BIT(tid)))
713 		return;
714 
715 	iwl_fw_dbg_collect_trig(&mvm->fwrt, trig,
716 				"Frame from %pM timed out, tid %d",
717 				sta->addr, tid);
718 }
719 
720 u8 iwl_mvm_tcm_load_percentage(u32 airtime, u32 elapsed)
721 {
722 	if (!elapsed)
723 		return 0;
724 
725 	return (100 * airtime / elapsed) / USEC_PER_MSEC;
726 }
727 
728 static enum iwl_mvm_traffic_load
729 iwl_mvm_tcm_load(struct iwl_mvm *mvm, u32 airtime, unsigned long elapsed)
730 {
731 	u8 load = iwl_mvm_tcm_load_percentage(airtime, elapsed);
732 
733 	if (load > IWL_MVM_TCM_LOAD_HIGH_THRESH)
734 		return IWL_MVM_TRAFFIC_HIGH;
735 	if (load > IWL_MVM_TCM_LOAD_MEDIUM_THRESH)
736 		return IWL_MVM_TRAFFIC_MEDIUM;
737 
738 	return IWL_MVM_TRAFFIC_LOW;
739 }
740 
741 static void iwl_mvm_tcm_iter(void *_data, u8 *mac, struct ieee80211_vif *vif)
742 {
743 	struct iwl_mvm *mvm = _data;
744 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
745 	bool low_latency, prev = mvmvif->low_latency & LOW_LATENCY_TRAFFIC;
746 
747 	if (mvmvif->id >= NUM_MAC_INDEX_DRIVER)
748 		return;
749 
750 	low_latency = mvm->tcm.result.low_latency[mvmvif->id];
751 
752 	if (!mvm->tcm.result.change[mvmvif->id] &&
753 	    prev == low_latency) {
754 		iwl_mvm_update_quotas(mvm, false, NULL);
755 		return;
756 	}
757 
758 	if (prev != low_latency) {
759 		/* this sends traffic load and updates quota as well */
760 		iwl_mvm_update_low_latency(mvm, vif, low_latency,
761 					   LOW_LATENCY_TRAFFIC);
762 	} else {
763 		iwl_mvm_update_quotas(mvm, false, NULL);
764 	}
765 }
766 
767 static void iwl_mvm_tcm_results(struct iwl_mvm *mvm)
768 {
769 	mutex_lock(&mvm->mutex);
770 
771 	ieee80211_iterate_active_interfaces(
772 		mvm->hw, IEEE80211_IFACE_ITER_NORMAL,
773 		iwl_mvm_tcm_iter, mvm);
774 
775 	if (fw_has_capa(&mvm->fw->ucode_capa, IWL_UCODE_TLV_CAPA_UMAC_SCAN))
776 		iwl_mvm_config_scan(mvm);
777 
778 	mutex_unlock(&mvm->mutex);
779 }
780 
781 static void iwl_mvm_tcm_uapsd_nonagg_detected_wk(struct work_struct *wk)
782 {
783 	struct iwl_mvm *mvm;
784 	struct iwl_mvm_vif *mvmvif;
785 	struct ieee80211_vif *vif;
786 
787 	mvmvif = container_of(wk, struct iwl_mvm_vif,
788 			      uapsd_nonagg_detected_wk.work);
789 	vif = container_of((void *)mvmvif, struct ieee80211_vif, drv_priv);
790 	mvm = mvmvif->mvm;
791 
792 	if (mvm->tcm.data[mvmvif->id].opened_rx_ba_sessions)
793 		return;
794 
795 	/* remember that this AP is broken */
796 	memcpy(mvm->uapsd_noagg_bssids[mvm->uapsd_noagg_bssid_write_idx].addr,
797 	       vif->bss_conf.bssid, ETH_ALEN);
798 	mvm->uapsd_noagg_bssid_write_idx++;
799 	if (mvm->uapsd_noagg_bssid_write_idx >= IWL_MVM_UAPSD_NOAGG_LIST_LEN)
800 		mvm->uapsd_noagg_bssid_write_idx = 0;
801 
802 	iwl_mvm_connection_loss(mvm, vif,
803 				"AP isn't using AMPDU with uAPSD enabled");
804 }
805 
806 static void iwl_mvm_uapsd_agg_disconnect(struct iwl_mvm *mvm,
807 					 struct ieee80211_vif *vif)
808 {
809 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
810 
811 	if (vif->type != NL80211_IFTYPE_STATION)
812 		return;
813 
814 	if (!vif->bss_conf.assoc)
815 		return;
816 
817 	if (!mvmvif->queue_params[IEEE80211_AC_VO].uapsd &&
818 	    !mvmvif->queue_params[IEEE80211_AC_VI].uapsd &&
819 	    !mvmvif->queue_params[IEEE80211_AC_BE].uapsd &&
820 	    !mvmvif->queue_params[IEEE80211_AC_BK].uapsd)
821 		return;
822 
823 	if (mvm->tcm.data[mvmvif->id].uapsd_nonagg_detect.detected)
824 		return;
825 
826 	mvm->tcm.data[mvmvif->id].uapsd_nonagg_detect.detected = true;
827 	IWL_INFO(mvm,
828 		 "detected AP should do aggregation but isn't, likely due to U-APSD\n");
829 	schedule_delayed_work(&mvmvif->uapsd_nonagg_detected_wk, 15 * HZ);
830 }
831 
832 static void iwl_mvm_check_uapsd_agg_expected_tpt(struct iwl_mvm *mvm,
833 						 unsigned int elapsed,
834 						 int mac)
835 {
836 	u64 bytes = mvm->tcm.data[mac].uapsd_nonagg_detect.rx_bytes;
837 	u64 tpt;
838 	unsigned long rate;
839 	struct ieee80211_vif *vif;
840 
841 	rate = ewma_rate_read(&mvm->tcm.data[mac].uapsd_nonagg_detect.rate);
842 
843 	if (!rate || mvm->tcm.data[mac].opened_rx_ba_sessions ||
844 	    mvm->tcm.data[mac].uapsd_nonagg_detect.detected)
845 		return;
846 
847 	if (iwl_mvm_has_new_rx_api(mvm)) {
848 		tpt = 8 * bytes; /* kbps */
849 		do_div(tpt, elapsed);
850 		rate *= 1000; /* kbps */
851 		if (tpt < 22 * rate / 100)
852 			return;
853 	} else {
854 		/*
855 		 * the rate here is actually the threshold, in 100Kbps units,
856 		 * so do the needed conversion from bytes to 100Kbps:
857 		 * 100kb = bits / (100 * 1000),
858 		 * 100kbps = 100kb / (msecs / 1000) ==
859 		 *           (bits / (100 * 1000)) / (msecs / 1000) ==
860 		 *           bits / (100 * msecs)
861 		 */
862 		tpt = (8 * bytes);
863 		do_div(tpt, elapsed * 100);
864 		if (tpt < rate)
865 			return;
866 	}
867 
868 	rcu_read_lock();
869 	vif = rcu_dereference(mvm->vif_id_to_mac[mac]);
870 	if (vif)
871 		iwl_mvm_uapsd_agg_disconnect(mvm, vif);
872 	rcu_read_unlock();
873 }
874 
875 static void iwl_mvm_tcm_iterator(void *_data, u8 *mac,
876 				 struct ieee80211_vif *vif)
877 {
878 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
879 	u32 *band = _data;
880 
881 	if (!mvmvif->phy_ctxt)
882 		return;
883 
884 	band[mvmvif->id] = mvmvif->phy_ctxt->channel->band;
885 }
886 
887 static unsigned long iwl_mvm_calc_tcm_stats(struct iwl_mvm *mvm,
888 					    unsigned long ts,
889 					    bool handle_uapsd)
890 {
891 	unsigned int elapsed = jiffies_to_msecs(ts - mvm->tcm.ts);
892 	unsigned int uapsd_elapsed =
893 		jiffies_to_msecs(ts - mvm->tcm.uapsd_nonagg_ts);
894 	u32 total_airtime = 0;
895 	u32 band_airtime[NUM_NL80211_BANDS] = {0};
896 	u32 band[NUM_MAC_INDEX_DRIVER] = {0};
897 	int ac, mac, i;
898 	bool low_latency = false;
899 	enum iwl_mvm_traffic_load load, band_load;
900 	bool handle_ll = time_after(ts, mvm->tcm.ll_ts + MVM_LL_PERIOD);
901 
902 	if (handle_ll)
903 		mvm->tcm.ll_ts = ts;
904 	if (handle_uapsd)
905 		mvm->tcm.uapsd_nonagg_ts = ts;
906 
907 	mvm->tcm.result.elapsed = elapsed;
908 
909 	ieee80211_iterate_active_interfaces_atomic(mvm->hw,
910 						   IEEE80211_IFACE_ITER_NORMAL,
911 						   iwl_mvm_tcm_iterator,
912 						   &band);
913 
914 	for (mac = 0; mac < NUM_MAC_INDEX_DRIVER; mac++) {
915 		struct iwl_mvm_tcm_mac *mdata = &mvm->tcm.data[mac];
916 		u32 vo_vi_pkts = 0;
917 		u32 airtime = mdata->rx.airtime + mdata->tx.airtime;
918 
919 		total_airtime += airtime;
920 		band_airtime[band[mac]] += airtime;
921 
922 		load = iwl_mvm_tcm_load(mvm, airtime, elapsed);
923 		mvm->tcm.result.change[mac] = load != mvm->tcm.result.load[mac];
924 		mvm->tcm.result.load[mac] = load;
925 		mvm->tcm.result.airtime[mac] = airtime;
926 
927 		for (ac = IEEE80211_AC_VO; ac <= IEEE80211_AC_VI; ac++)
928 			vo_vi_pkts += mdata->rx.pkts[ac] +
929 				      mdata->tx.pkts[ac];
930 
931 		/* enable immediately with enough packets but defer disabling */
932 		if (vo_vi_pkts > IWL_MVM_TCM_LOWLAT_ENABLE_THRESH)
933 			mvm->tcm.result.low_latency[mac] = true;
934 		else if (handle_ll)
935 			mvm->tcm.result.low_latency[mac] = false;
936 
937 		if (handle_ll) {
938 			/* clear old data */
939 			memset(&mdata->rx.pkts, 0, sizeof(mdata->rx.pkts));
940 			memset(&mdata->tx.pkts, 0, sizeof(mdata->tx.pkts));
941 		}
942 		low_latency |= mvm->tcm.result.low_latency[mac];
943 
944 		if (!mvm->tcm.result.low_latency[mac] && handle_uapsd)
945 			iwl_mvm_check_uapsd_agg_expected_tpt(mvm, uapsd_elapsed,
946 							     mac);
947 		/* clear old data */
948 		if (handle_uapsd)
949 			mdata->uapsd_nonagg_detect.rx_bytes = 0;
950 		memset(&mdata->rx.airtime, 0, sizeof(mdata->rx.airtime));
951 		memset(&mdata->tx.airtime, 0, sizeof(mdata->tx.airtime));
952 	}
953 
954 	load = iwl_mvm_tcm_load(mvm, total_airtime, elapsed);
955 	mvm->tcm.result.global_load = load;
956 
957 	for (i = 0; i < NUM_NL80211_BANDS; i++) {
958 		band_load = iwl_mvm_tcm_load(mvm, band_airtime[i], elapsed);
959 		mvm->tcm.result.band_load[i] = band_load;
960 	}
961 
962 	/*
963 	 * If the current load isn't low we need to force re-evaluation
964 	 * in the TCM period, so that we can return to low load if there
965 	 * was no traffic at all (and thus iwl_mvm_recalc_tcm didn't get
966 	 * triggered by traffic).
967 	 */
968 	if (load != IWL_MVM_TRAFFIC_LOW)
969 		return MVM_TCM_PERIOD;
970 	/*
971 	 * If low-latency is active we need to force re-evaluation after
972 	 * (the longer) MVM_LL_PERIOD, so that we can disable low-latency
973 	 * when there's no traffic at all.
974 	 */
975 	if (low_latency)
976 		return MVM_LL_PERIOD;
977 	/*
978 	 * Otherwise, we don't need to run the work struct because we're
979 	 * in the default "idle" state - traffic indication is low (which
980 	 * also covers the "no traffic" case) and low-latency is disabled
981 	 * so there's no state that may need to be disabled when there's
982 	 * no traffic at all.
983 	 *
984 	 * Note that this has no impact on the regular scheduling of the
985 	 * updates triggered by traffic - those happen whenever one of the
986 	 * two timeouts expire (if there's traffic at all.)
987 	 */
988 	return 0;
989 }
990 
991 void iwl_mvm_recalc_tcm(struct iwl_mvm *mvm)
992 {
993 	unsigned long ts = jiffies;
994 	bool handle_uapsd =
995 		time_after(ts, mvm->tcm.uapsd_nonagg_ts +
996 			       msecs_to_jiffies(IWL_MVM_UAPSD_NONAGG_PERIOD));
997 
998 	spin_lock(&mvm->tcm.lock);
999 	if (mvm->tcm.paused || !time_after(ts, mvm->tcm.ts + MVM_TCM_PERIOD)) {
1000 		spin_unlock(&mvm->tcm.lock);
1001 		return;
1002 	}
1003 	spin_unlock(&mvm->tcm.lock);
1004 
1005 	if (handle_uapsd && iwl_mvm_has_new_rx_api(mvm)) {
1006 		mutex_lock(&mvm->mutex);
1007 		if (iwl_mvm_request_statistics(mvm, true))
1008 			handle_uapsd = false;
1009 		mutex_unlock(&mvm->mutex);
1010 	}
1011 
1012 	spin_lock(&mvm->tcm.lock);
1013 	/* re-check if somebody else won the recheck race */
1014 	if (!mvm->tcm.paused && time_after(ts, mvm->tcm.ts + MVM_TCM_PERIOD)) {
1015 		/* calculate statistics */
1016 		unsigned long work_delay = iwl_mvm_calc_tcm_stats(mvm, ts,
1017 								  handle_uapsd);
1018 
1019 		/* the memset needs to be visible before the timestamp */
1020 		smp_mb();
1021 		mvm->tcm.ts = ts;
1022 		if (work_delay)
1023 			schedule_delayed_work(&mvm->tcm.work, work_delay);
1024 	}
1025 	spin_unlock(&mvm->tcm.lock);
1026 
1027 	iwl_mvm_tcm_results(mvm);
1028 }
1029 
1030 void iwl_mvm_tcm_work(struct work_struct *work)
1031 {
1032 	struct delayed_work *delayed_work = to_delayed_work(work);
1033 	struct iwl_mvm *mvm = container_of(delayed_work, struct iwl_mvm,
1034 					   tcm.work);
1035 
1036 	iwl_mvm_recalc_tcm(mvm);
1037 }
1038 
1039 void iwl_mvm_pause_tcm(struct iwl_mvm *mvm, bool with_cancel)
1040 {
1041 	spin_lock_bh(&mvm->tcm.lock);
1042 	mvm->tcm.paused = true;
1043 	spin_unlock_bh(&mvm->tcm.lock);
1044 	if (with_cancel)
1045 		cancel_delayed_work_sync(&mvm->tcm.work);
1046 }
1047 
1048 void iwl_mvm_resume_tcm(struct iwl_mvm *mvm)
1049 {
1050 	int mac;
1051 	bool low_latency = false;
1052 
1053 	spin_lock_bh(&mvm->tcm.lock);
1054 	mvm->tcm.ts = jiffies;
1055 	mvm->tcm.ll_ts = jiffies;
1056 	for (mac = 0; mac < NUM_MAC_INDEX_DRIVER; mac++) {
1057 		struct iwl_mvm_tcm_mac *mdata = &mvm->tcm.data[mac];
1058 
1059 		memset(&mdata->rx.pkts, 0, sizeof(mdata->rx.pkts));
1060 		memset(&mdata->tx.pkts, 0, sizeof(mdata->tx.pkts));
1061 		memset(&mdata->rx.airtime, 0, sizeof(mdata->rx.airtime));
1062 		memset(&mdata->tx.airtime, 0, sizeof(mdata->tx.airtime));
1063 
1064 		if (mvm->tcm.result.low_latency[mac])
1065 			low_latency = true;
1066 	}
1067 	/* The TCM data needs to be reset before "paused" flag changes */
1068 	smp_mb();
1069 	mvm->tcm.paused = false;
1070 
1071 	/*
1072 	 * if the current load is not low or low latency is active, force
1073 	 * re-evaluation to cover the case of no traffic.
1074 	 */
1075 	if (mvm->tcm.result.global_load > IWL_MVM_TRAFFIC_LOW)
1076 		schedule_delayed_work(&mvm->tcm.work, MVM_TCM_PERIOD);
1077 	else if (low_latency)
1078 		schedule_delayed_work(&mvm->tcm.work, MVM_LL_PERIOD);
1079 
1080 	spin_unlock_bh(&mvm->tcm.lock);
1081 }
1082 
1083 void iwl_mvm_tcm_add_vif(struct iwl_mvm *mvm, struct ieee80211_vif *vif)
1084 {
1085 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
1086 
1087 	INIT_DELAYED_WORK(&mvmvif->uapsd_nonagg_detected_wk,
1088 			  iwl_mvm_tcm_uapsd_nonagg_detected_wk);
1089 }
1090 
1091 void iwl_mvm_tcm_rm_vif(struct iwl_mvm *mvm, struct ieee80211_vif *vif)
1092 {
1093 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
1094 
1095 	cancel_delayed_work_sync(&mvmvif->uapsd_nonagg_detected_wk);
1096 }
1097 
1098 u32 iwl_mvm_get_systime(struct iwl_mvm *mvm)
1099 {
1100 	u32 reg_addr = DEVICE_SYSTEM_TIME_REG;
1101 
1102 	if (mvm->trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_22000 &&
1103 	    mvm->trans->cfg->gp2_reg_addr)
1104 		reg_addr = mvm->trans->cfg->gp2_reg_addr;
1105 
1106 	return iwl_read_prph(mvm->trans, reg_addr);
1107 }
1108 
1109 void iwl_mvm_get_sync_time(struct iwl_mvm *mvm, int clock_type,
1110 			   u32 *gp2, u64 *boottime, ktime_t *realtime)
1111 {
1112 	bool ps_disabled;
1113 
1114 	lockdep_assert_held(&mvm->mutex);
1115 
1116 	/* Disable power save when reading GP2 */
1117 	ps_disabled = mvm->ps_disabled;
1118 	if (!ps_disabled) {
1119 		mvm->ps_disabled = true;
1120 		iwl_mvm_power_update_device(mvm);
1121 	}
1122 
1123 	*gp2 = iwl_mvm_get_systime(mvm);
1124 
1125 	if (clock_type == CLOCK_BOOTTIME && boottime)
1126 		*boottime = ktime_get_boottime_ns();
1127 	else if (clock_type == CLOCK_REALTIME && realtime)
1128 		*realtime = ktime_get_real();
1129 
1130 	if (!ps_disabled) {
1131 		mvm->ps_disabled = ps_disabled;
1132 		iwl_mvm_power_update_device(mvm);
1133 	}
1134 }
1135