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 static bool iwl_wait_stats_complete(struct iwl_notif_wait_data *notif_wait,
344 				    struct iwl_rx_packet *pkt, void *data)
345 {
346 	WARN_ON(pkt->hdr.cmd != STATISTICS_NOTIFICATION);
347 
348 	return true;
349 }
350 
351 int iwl_mvm_request_statistics(struct iwl_mvm *mvm, bool clear)
352 {
353 	struct iwl_statistics_cmd scmd = {
354 		.flags = clear ? cpu_to_le32(IWL_STATISTICS_FLG_CLEAR) : 0,
355 	};
356 
357 	struct iwl_host_cmd cmd = {
358 		.id = STATISTICS_CMD,
359 		.len[0] = sizeof(scmd),
360 		.data[0] = &scmd,
361 	};
362 	int ret;
363 
364 	/* From version 15 - STATISTICS_NOTIFICATION, the reply for
365 	 * STATISTICS_CMD is empty, and the response is with
366 	 * STATISTICS_NOTIFICATION notification
367 	 */
368 	if (iwl_fw_lookup_notif_ver(mvm->fw, LEGACY_GROUP,
369 				    STATISTICS_NOTIFICATION, 0) < 15) {
370 		cmd.flags = CMD_WANT_SKB;
371 
372 		ret = iwl_mvm_send_cmd(mvm, &cmd);
373 		if (ret)
374 			return ret;
375 
376 		iwl_mvm_handle_rx_statistics(mvm, cmd.resp_pkt);
377 		iwl_free_resp(&cmd);
378 	} else {
379 		struct iwl_notification_wait stats_wait;
380 		static const u16 stats_complete[] = {
381 			STATISTICS_NOTIFICATION,
382 		};
383 
384 		iwl_init_notification_wait(&mvm->notif_wait, &stats_wait,
385 					   stats_complete, ARRAY_SIZE(stats_complete),
386 					   iwl_wait_stats_complete, NULL);
387 
388 		ret = iwl_mvm_send_cmd(mvm, &cmd);
389 		if (ret) {
390 			iwl_remove_notification(&mvm->notif_wait, &stats_wait);
391 			return ret;
392 		}
393 
394 		/* 200ms should be enough for FW to collect data from all
395 		 * LMACs and send STATISTICS_NOTIFICATION to host
396 		 */
397 		ret = iwl_wait_notification(&mvm->notif_wait, &stats_wait, HZ / 5);
398 		if (ret)
399 			return ret;
400 	}
401 
402 	if (clear)
403 		iwl_mvm_accu_radio_stats(mvm);
404 
405 	return 0;
406 }
407 
408 void iwl_mvm_accu_radio_stats(struct iwl_mvm *mvm)
409 {
410 	mvm->accu_radio_stats.rx_time += mvm->radio_stats.rx_time;
411 	mvm->accu_radio_stats.tx_time += mvm->radio_stats.tx_time;
412 	mvm->accu_radio_stats.on_time_rf += mvm->radio_stats.on_time_rf;
413 	mvm->accu_radio_stats.on_time_scan += mvm->radio_stats.on_time_scan;
414 }
415 
416 struct iwl_mvm_diversity_iter_data {
417 	struct iwl_mvm_phy_ctxt *ctxt;
418 	bool result;
419 };
420 
421 static void iwl_mvm_diversity_iter(void *_data, u8 *mac,
422 				   struct ieee80211_vif *vif)
423 {
424 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
425 	struct iwl_mvm_diversity_iter_data *data = _data;
426 	int i;
427 
428 	if (mvmvif->phy_ctxt != data->ctxt)
429 		return;
430 
431 	for (i = 0; i < NUM_IWL_MVM_SMPS_REQ; i++) {
432 		if (mvmvif->smps_requests[i] == IEEE80211_SMPS_STATIC ||
433 		    mvmvif->smps_requests[i] == IEEE80211_SMPS_DYNAMIC) {
434 			data->result = false;
435 			break;
436 		}
437 	}
438 }
439 
440 bool iwl_mvm_rx_diversity_allowed(struct iwl_mvm *mvm,
441 				  struct iwl_mvm_phy_ctxt *ctxt)
442 {
443 	struct iwl_mvm_diversity_iter_data data = {
444 		.ctxt = ctxt,
445 		.result = true,
446 	};
447 
448 	lockdep_assert_held(&mvm->mutex);
449 
450 	if (iwlmvm_mod_params.power_scheme != IWL_POWER_SCHEME_CAM)
451 		return false;
452 
453 	if (num_of_ant(iwl_mvm_get_valid_rx_ant(mvm)) == 1)
454 		return false;
455 
456 	if (mvm->cfg->rx_with_siso_diversity)
457 		return false;
458 
459 	ieee80211_iterate_active_interfaces_atomic(
460 			mvm->hw, IEEE80211_IFACE_ITER_NORMAL,
461 			iwl_mvm_diversity_iter, &data);
462 
463 	return data.result;
464 }
465 
466 void iwl_mvm_send_low_latency_cmd(struct iwl_mvm *mvm,
467 				  bool low_latency, u16 mac_id)
468 {
469 	struct iwl_mac_low_latency_cmd cmd = {
470 		.mac_id = cpu_to_le32(mac_id)
471 	};
472 
473 	if (!fw_has_capa(&mvm->fw->ucode_capa,
474 			 IWL_UCODE_TLV_CAPA_DYNAMIC_QUOTA))
475 		return;
476 
477 	if (low_latency) {
478 		/* currently we don't care about the direction */
479 		cmd.low_latency_rx = 1;
480 		cmd.low_latency_tx = 1;
481 	}
482 
483 	if (iwl_mvm_send_cmd_pdu(mvm, iwl_cmd_id(LOW_LATENCY_CMD,
484 						 MAC_CONF_GROUP, 0),
485 				 0, sizeof(cmd), &cmd))
486 		IWL_ERR(mvm, "Failed to send low latency command\n");
487 }
488 
489 int iwl_mvm_update_low_latency(struct iwl_mvm *mvm, struct ieee80211_vif *vif,
490 			       bool low_latency,
491 			       enum iwl_mvm_low_latency_cause cause)
492 {
493 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
494 	int res;
495 	bool prev;
496 
497 	lockdep_assert_held(&mvm->mutex);
498 
499 	prev = iwl_mvm_vif_low_latency(mvmvif);
500 	iwl_mvm_vif_set_low_latency(mvmvif, low_latency, cause);
501 
502 	low_latency = iwl_mvm_vif_low_latency(mvmvif);
503 
504 	if (low_latency == prev)
505 		return 0;
506 
507 	iwl_mvm_send_low_latency_cmd(mvm, low_latency, mvmvif->id);
508 
509 	res = iwl_mvm_update_quotas(mvm, false, NULL);
510 	if (res)
511 		return res;
512 
513 	iwl_mvm_bt_coex_vif_change(mvm);
514 
515 	return iwl_mvm_power_update_mac(mvm);
516 }
517 
518 struct iwl_mvm_low_latency_iter {
519 	bool result;
520 	bool result_per_band[NUM_NL80211_BANDS];
521 };
522 
523 static void iwl_mvm_ll_iter(void *_data, u8 *mac, struct ieee80211_vif *vif)
524 {
525 	struct iwl_mvm_low_latency_iter *result = _data;
526 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
527 	enum nl80211_band band;
528 
529 	if (iwl_mvm_vif_low_latency(mvmvif)) {
530 		result->result = true;
531 
532 		if (!mvmvif->phy_ctxt)
533 			return;
534 
535 		band = mvmvif->phy_ctxt->channel->band;
536 		result->result_per_band[band] = true;
537 	}
538 }
539 
540 bool iwl_mvm_low_latency(struct iwl_mvm *mvm)
541 {
542 	struct iwl_mvm_low_latency_iter data = {};
543 
544 	ieee80211_iterate_active_interfaces_atomic(
545 			mvm->hw, IEEE80211_IFACE_ITER_NORMAL,
546 			iwl_mvm_ll_iter, &data);
547 
548 	return data.result;
549 }
550 
551 bool iwl_mvm_low_latency_band(struct iwl_mvm *mvm, enum nl80211_band band)
552 {
553 	struct iwl_mvm_low_latency_iter data = {};
554 
555 	ieee80211_iterate_active_interfaces_atomic(
556 			mvm->hw, IEEE80211_IFACE_ITER_NORMAL,
557 			iwl_mvm_ll_iter, &data);
558 
559 	return data.result_per_band[band];
560 }
561 
562 struct iwl_bss_iter_data {
563 	struct ieee80211_vif *vif;
564 	bool error;
565 };
566 
567 static void iwl_mvm_bss_iface_iterator(void *_data, u8 *mac,
568 				       struct ieee80211_vif *vif)
569 {
570 	struct iwl_bss_iter_data *data = _data;
571 
572 	if (vif->type != NL80211_IFTYPE_STATION || vif->p2p)
573 		return;
574 
575 	if (data->vif) {
576 		data->error = true;
577 		return;
578 	}
579 
580 	data->vif = vif;
581 }
582 
583 struct ieee80211_vif *iwl_mvm_get_bss_vif(struct iwl_mvm *mvm)
584 {
585 	struct iwl_bss_iter_data bss_iter_data = {};
586 
587 	ieee80211_iterate_active_interfaces_atomic(
588 		mvm->hw, IEEE80211_IFACE_ITER_NORMAL,
589 		iwl_mvm_bss_iface_iterator, &bss_iter_data);
590 
591 	if (bss_iter_data.error) {
592 		IWL_ERR(mvm, "More than one managed interface active!\n");
593 		return ERR_PTR(-EINVAL);
594 	}
595 
596 	return bss_iter_data.vif;
597 }
598 
599 struct iwl_bss_find_iter_data {
600 	struct ieee80211_vif *vif;
601 	u32 macid;
602 };
603 
604 static void iwl_mvm_bss_find_iface_iterator(void *_data, u8 *mac,
605 					    struct ieee80211_vif *vif)
606 {
607 	struct iwl_bss_find_iter_data *data = _data;
608 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
609 
610 	if (mvmvif->id == data->macid)
611 		data->vif = vif;
612 }
613 
614 struct ieee80211_vif *iwl_mvm_get_vif_by_macid(struct iwl_mvm *mvm, u32 macid)
615 {
616 	struct iwl_bss_find_iter_data data = {
617 		.macid = macid,
618 	};
619 
620 	lockdep_assert_held(&mvm->mutex);
621 
622 	ieee80211_iterate_active_interfaces_atomic(
623 		mvm->hw, IEEE80211_IFACE_ITER_NORMAL,
624 		iwl_mvm_bss_find_iface_iterator, &data);
625 
626 	return data.vif;
627 }
628 
629 struct iwl_sta_iter_data {
630 	bool assoc;
631 };
632 
633 static void iwl_mvm_sta_iface_iterator(void *_data, u8 *mac,
634 				       struct ieee80211_vif *vif)
635 {
636 	struct iwl_sta_iter_data *data = _data;
637 
638 	if (vif->type != NL80211_IFTYPE_STATION)
639 		return;
640 
641 	if (vif->bss_conf.assoc)
642 		data->assoc = true;
643 }
644 
645 bool iwl_mvm_is_vif_assoc(struct iwl_mvm *mvm)
646 {
647 	struct iwl_sta_iter_data data = {
648 		.assoc = false,
649 	};
650 
651 	ieee80211_iterate_active_interfaces_atomic(mvm->hw,
652 						   IEEE80211_IFACE_ITER_NORMAL,
653 						   iwl_mvm_sta_iface_iterator,
654 						   &data);
655 	return data.assoc;
656 }
657 
658 unsigned int iwl_mvm_get_wd_timeout(struct iwl_mvm *mvm,
659 				    struct ieee80211_vif *vif,
660 				    bool tdls, bool cmd_q)
661 {
662 	struct iwl_fw_dbg_trigger_tlv *trigger;
663 	struct iwl_fw_dbg_trigger_txq_timer *txq_timer;
664 	unsigned int default_timeout = cmd_q ?
665 		IWL_DEF_WD_TIMEOUT :
666 		mvm->trans->trans_cfg->base_params->wd_timeout;
667 
668 	if (!iwl_fw_dbg_trigger_enabled(mvm->fw, FW_DBG_TRIGGER_TXQ_TIMERS)) {
669 		/*
670 		 * We can't know when the station is asleep or awake, so we
671 		 * must disable the queue hang detection.
672 		 */
673 		if (fw_has_capa(&mvm->fw->ucode_capa,
674 				IWL_UCODE_TLV_CAPA_STA_PM_NOTIF) &&
675 		    vif && vif->type == NL80211_IFTYPE_AP)
676 			return IWL_WATCHDOG_DISABLED;
677 		return default_timeout;
678 	}
679 
680 	trigger = iwl_fw_dbg_get_trigger(mvm->fw, FW_DBG_TRIGGER_TXQ_TIMERS);
681 	txq_timer = (void *)trigger->data;
682 
683 	if (tdls)
684 		return le32_to_cpu(txq_timer->tdls);
685 
686 	if (cmd_q)
687 		return le32_to_cpu(txq_timer->command_queue);
688 
689 	if (WARN_ON(!vif))
690 		return default_timeout;
691 
692 	switch (ieee80211_vif_type_p2p(vif)) {
693 	case NL80211_IFTYPE_ADHOC:
694 		return le32_to_cpu(txq_timer->ibss);
695 	case NL80211_IFTYPE_STATION:
696 		return le32_to_cpu(txq_timer->bss);
697 	case NL80211_IFTYPE_AP:
698 		return le32_to_cpu(txq_timer->softap);
699 	case NL80211_IFTYPE_P2P_CLIENT:
700 		return le32_to_cpu(txq_timer->p2p_client);
701 	case NL80211_IFTYPE_P2P_GO:
702 		return le32_to_cpu(txq_timer->p2p_go);
703 	case NL80211_IFTYPE_P2P_DEVICE:
704 		return le32_to_cpu(txq_timer->p2p_device);
705 	case NL80211_IFTYPE_MONITOR:
706 		return default_timeout;
707 	default:
708 		WARN_ON(1);
709 		return mvm->trans->trans_cfg->base_params->wd_timeout;
710 	}
711 }
712 
713 void iwl_mvm_connection_loss(struct iwl_mvm *mvm, struct ieee80211_vif *vif,
714 			     const char *errmsg)
715 {
716 	struct iwl_fw_dbg_trigger_tlv *trig;
717 	struct iwl_fw_dbg_trigger_mlme *trig_mlme;
718 
719 	trig = iwl_fw_dbg_trigger_on(&mvm->fwrt, ieee80211_vif_to_wdev(vif),
720 				     FW_DBG_TRIGGER_MLME);
721 	if (!trig)
722 		goto out;
723 
724 	trig_mlme = (void *)trig->data;
725 
726 	if (trig_mlme->stop_connection_loss &&
727 	    --trig_mlme->stop_connection_loss)
728 		goto out;
729 
730 	iwl_fw_dbg_collect_trig(&mvm->fwrt, trig, "%s", errmsg);
731 
732 out:
733 	ieee80211_connection_loss(vif);
734 }
735 
736 void iwl_mvm_event_frame_timeout_callback(struct iwl_mvm *mvm,
737 					  struct ieee80211_vif *vif,
738 					  const struct ieee80211_sta *sta,
739 					  u16 tid)
740 {
741 	struct iwl_fw_dbg_trigger_tlv *trig;
742 	struct iwl_fw_dbg_trigger_ba *ba_trig;
743 
744 	trig = iwl_fw_dbg_trigger_on(&mvm->fwrt, ieee80211_vif_to_wdev(vif),
745 				     FW_DBG_TRIGGER_BA);
746 	if (!trig)
747 		return;
748 
749 	ba_trig = (void *)trig->data;
750 
751 	if (!(le16_to_cpu(ba_trig->frame_timeout) & BIT(tid)))
752 		return;
753 
754 	iwl_fw_dbg_collect_trig(&mvm->fwrt, trig,
755 				"Frame from %pM timed out, tid %d",
756 				sta->addr, tid);
757 }
758 
759 u8 iwl_mvm_tcm_load_percentage(u32 airtime, u32 elapsed)
760 {
761 	if (!elapsed)
762 		return 0;
763 
764 	return (100 * airtime / elapsed) / USEC_PER_MSEC;
765 }
766 
767 static enum iwl_mvm_traffic_load
768 iwl_mvm_tcm_load(struct iwl_mvm *mvm, u32 airtime, unsigned long elapsed)
769 {
770 	u8 load = iwl_mvm_tcm_load_percentage(airtime, elapsed);
771 
772 	if (load > IWL_MVM_TCM_LOAD_HIGH_THRESH)
773 		return IWL_MVM_TRAFFIC_HIGH;
774 	if (load > IWL_MVM_TCM_LOAD_MEDIUM_THRESH)
775 		return IWL_MVM_TRAFFIC_MEDIUM;
776 
777 	return IWL_MVM_TRAFFIC_LOW;
778 }
779 
780 static void iwl_mvm_tcm_iter(void *_data, u8 *mac, struct ieee80211_vif *vif)
781 {
782 	struct iwl_mvm *mvm = _data;
783 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
784 	bool low_latency, prev = mvmvif->low_latency & LOW_LATENCY_TRAFFIC;
785 
786 	if (mvmvif->id >= NUM_MAC_INDEX_DRIVER)
787 		return;
788 
789 	low_latency = mvm->tcm.result.low_latency[mvmvif->id];
790 
791 	if (!mvm->tcm.result.change[mvmvif->id] &&
792 	    prev == low_latency) {
793 		iwl_mvm_update_quotas(mvm, false, NULL);
794 		return;
795 	}
796 
797 	if (prev != low_latency) {
798 		/* this sends traffic load and updates quota as well */
799 		iwl_mvm_update_low_latency(mvm, vif, low_latency,
800 					   LOW_LATENCY_TRAFFIC);
801 	} else {
802 		iwl_mvm_update_quotas(mvm, false, NULL);
803 	}
804 }
805 
806 static void iwl_mvm_tcm_results(struct iwl_mvm *mvm)
807 {
808 	mutex_lock(&mvm->mutex);
809 
810 	ieee80211_iterate_active_interfaces(
811 		mvm->hw, IEEE80211_IFACE_ITER_NORMAL,
812 		iwl_mvm_tcm_iter, mvm);
813 
814 	if (fw_has_capa(&mvm->fw->ucode_capa, IWL_UCODE_TLV_CAPA_UMAC_SCAN))
815 		iwl_mvm_config_scan(mvm);
816 
817 	mutex_unlock(&mvm->mutex);
818 }
819 
820 static void iwl_mvm_tcm_uapsd_nonagg_detected_wk(struct work_struct *wk)
821 {
822 	struct iwl_mvm *mvm;
823 	struct iwl_mvm_vif *mvmvif;
824 	struct ieee80211_vif *vif;
825 
826 	mvmvif = container_of(wk, struct iwl_mvm_vif,
827 			      uapsd_nonagg_detected_wk.work);
828 	vif = container_of((void *)mvmvif, struct ieee80211_vif, drv_priv);
829 	mvm = mvmvif->mvm;
830 
831 	if (mvm->tcm.data[mvmvif->id].opened_rx_ba_sessions)
832 		return;
833 
834 	/* remember that this AP is broken */
835 	memcpy(mvm->uapsd_noagg_bssids[mvm->uapsd_noagg_bssid_write_idx].addr,
836 	       vif->bss_conf.bssid, ETH_ALEN);
837 	mvm->uapsd_noagg_bssid_write_idx++;
838 	if (mvm->uapsd_noagg_bssid_write_idx >= IWL_MVM_UAPSD_NOAGG_LIST_LEN)
839 		mvm->uapsd_noagg_bssid_write_idx = 0;
840 
841 	iwl_mvm_connection_loss(mvm, vif,
842 				"AP isn't using AMPDU with uAPSD enabled");
843 }
844 
845 static void iwl_mvm_uapsd_agg_disconnect(struct iwl_mvm *mvm,
846 					 struct ieee80211_vif *vif)
847 {
848 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
849 
850 	if (vif->type != NL80211_IFTYPE_STATION)
851 		return;
852 
853 	if (!vif->bss_conf.assoc)
854 		return;
855 
856 	if (!mvmvif->queue_params[IEEE80211_AC_VO].uapsd &&
857 	    !mvmvif->queue_params[IEEE80211_AC_VI].uapsd &&
858 	    !mvmvif->queue_params[IEEE80211_AC_BE].uapsd &&
859 	    !mvmvif->queue_params[IEEE80211_AC_BK].uapsd)
860 		return;
861 
862 	if (mvm->tcm.data[mvmvif->id].uapsd_nonagg_detect.detected)
863 		return;
864 
865 	mvm->tcm.data[mvmvif->id].uapsd_nonagg_detect.detected = true;
866 	IWL_INFO(mvm,
867 		 "detected AP should do aggregation but isn't, likely due to U-APSD\n");
868 	schedule_delayed_work(&mvmvif->uapsd_nonagg_detected_wk, 15 * HZ);
869 }
870 
871 static void iwl_mvm_check_uapsd_agg_expected_tpt(struct iwl_mvm *mvm,
872 						 unsigned int elapsed,
873 						 int mac)
874 {
875 	u64 bytes = mvm->tcm.data[mac].uapsd_nonagg_detect.rx_bytes;
876 	u64 tpt;
877 	unsigned long rate;
878 	struct ieee80211_vif *vif;
879 
880 	rate = ewma_rate_read(&mvm->tcm.data[mac].uapsd_nonagg_detect.rate);
881 
882 	if (!rate || mvm->tcm.data[mac].opened_rx_ba_sessions ||
883 	    mvm->tcm.data[mac].uapsd_nonagg_detect.detected)
884 		return;
885 
886 	if (iwl_mvm_has_new_rx_api(mvm)) {
887 		tpt = 8 * bytes; /* kbps */
888 		do_div(tpt, elapsed);
889 		rate *= 1000; /* kbps */
890 		if (tpt < 22 * rate / 100)
891 			return;
892 	} else {
893 		/*
894 		 * the rate here is actually the threshold, in 100Kbps units,
895 		 * so do the needed conversion from bytes to 100Kbps:
896 		 * 100kb = bits / (100 * 1000),
897 		 * 100kbps = 100kb / (msecs / 1000) ==
898 		 *           (bits / (100 * 1000)) / (msecs / 1000) ==
899 		 *           bits / (100 * msecs)
900 		 */
901 		tpt = (8 * bytes);
902 		do_div(tpt, elapsed * 100);
903 		if (tpt < rate)
904 			return;
905 	}
906 
907 	rcu_read_lock();
908 	vif = rcu_dereference(mvm->vif_id_to_mac[mac]);
909 	if (vif)
910 		iwl_mvm_uapsd_agg_disconnect(mvm, vif);
911 	rcu_read_unlock();
912 }
913 
914 static void iwl_mvm_tcm_iterator(void *_data, u8 *mac,
915 				 struct ieee80211_vif *vif)
916 {
917 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
918 	u32 *band = _data;
919 
920 	if (!mvmvif->phy_ctxt)
921 		return;
922 
923 	band[mvmvif->id] = mvmvif->phy_ctxt->channel->band;
924 }
925 
926 static unsigned long iwl_mvm_calc_tcm_stats(struct iwl_mvm *mvm,
927 					    unsigned long ts,
928 					    bool handle_uapsd)
929 {
930 	unsigned int elapsed = jiffies_to_msecs(ts - mvm->tcm.ts);
931 	unsigned int uapsd_elapsed =
932 		jiffies_to_msecs(ts - mvm->tcm.uapsd_nonagg_ts);
933 	u32 total_airtime = 0;
934 	u32 band_airtime[NUM_NL80211_BANDS] = {0};
935 	u32 band[NUM_MAC_INDEX_DRIVER] = {0};
936 	int ac, mac, i;
937 	bool low_latency = false;
938 	enum iwl_mvm_traffic_load load, band_load;
939 	bool handle_ll = time_after(ts, mvm->tcm.ll_ts + MVM_LL_PERIOD);
940 
941 	if (handle_ll)
942 		mvm->tcm.ll_ts = ts;
943 	if (handle_uapsd)
944 		mvm->tcm.uapsd_nonagg_ts = ts;
945 
946 	mvm->tcm.result.elapsed = elapsed;
947 
948 	ieee80211_iterate_active_interfaces_atomic(mvm->hw,
949 						   IEEE80211_IFACE_ITER_NORMAL,
950 						   iwl_mvm_tcm_iterator,
951 						   &band);
952 
953 	for (mac = 0; mac < NUM_MAC_INDEX_DRIVER; mac++) {
954 		struct iwl_mvm_tcm_mac *mdata = &mvm->tcm.data[mac];
955 		u32 vo_vi_pkts = 0;
956 		u32 airtime = mdata->rx.airtime + mdata->tx.airtime;
957 
958 		total_airtime += airtime;
959 		band_airtime[band[mac]] += airtime;
960 
961 		load = iwl_mvm_tcm_load(mvm, airtime, elapsed);
962 		mvm->tcm.result.change[mac] = load != mvm->tcm.result.load[mac];
963 		mvm->tcm.result.load[mac] = load;
964 		mvm->tcm.result.airtime[mac] = airtime;
965 
966 		for (ac = IEEE80211_AC_VO; ac <= IEEE80211_AC_VI; ac++)
967 			vo_vi_pkts += mdata->rx.pkts[ac] +
968 				      mdata->tx.pkts[ac];
969 
970 		/* enable immediately with enough packets but defer disabling */
971 		if (vo_vi_pkts > IWL_MVM_TCM_LOWLAT_ENABLE_THRESH)
972 			mvm->tcm.result.low_latency[mac] = true;
973 		else if (handle_ll)
974 			mvm->tcm.result.low_latency[mac] = false;
975 
976 		if (handle_ll) {
977 			/* clear old data */
978 			memset(&mdata->rx.pkts, 0, sizeof(mdata->rx.pkts));
979 			memset(&mdata->tx.pkts, 0, sizeof(mdata->tx.pkts));
980 		}
981 		low_latency |= mvm->tcm.result.low_latency[mac];
982 
983 		if (!mvm->tcm.result.low_latency[mac] && handle_uapsd)
984 			iwl_mvm_check_uapsd_agg_expected_tpt(mvm, uapsd_elapsed,
985 							     mac);
986 		/* clear old data */
987 		if (handle_uapsd)
988 			mdata->uapsd_nonagg_detect.rx_bytes = 0;
989 		memset(&mdata->rx.airtime, 0, sizeof(mdata->rx.airtime));
990 		memset(&mdata->tx.airtime, 0, sizeof(mdata->tx.airtime));
991 	}
992 
993 	load = iwl_mvm_tcm_load(mvm, total_airtime, elapsed);
994 	mvm->tcm.result.global_load = load;
995 
996 	for (i = 0; i < NUM_NL80211_BANDS; i++) {
997 		band_load = iwl_mvm_tcm_load(mvm, band_airtime[i], elapsed);
998 		mvm->tcm.result.band_load[i] = band_load;
999 	}
1000 
1001 	/*
1002 	 * If the current load isn't low we need to force re-evaluation
1003 	 * in the TCM period, so that we can return to low load if there
1004 	 * was no traffic at all (and thus iwl_mvm_recalc_tcm didn't get
1005 	 * triggered by traffic).
1006 	 */
1007 	if (load != IWL_MVM_TRAFFIC_LOW)
1008 		return MVM_TCM_PERIOD;
1009 	/*
1010 	 * If low-latency is active we need to force re-evaluation after
1011 	 * (the longer) MVM_LL_PERIOD, so that we can disable low-latency
1012 	 * when there's no traffic at all.
1013 	 */
1014 	if (low_latency)
1015 		return MVM_LL_PERIOD;
1016 	/*
1017 	 * Otherwise, we don't need to run the work struct because we're
1018 	 * in the default "idle" state - traffic indication is low (which
1019 	 * also covers the "no traffic" case) and low-latency is disabled
1020 	 * so there's no state that may need to be disabled when there's
1021 	 * no traffic at all.
1022 	 *
1023 	 * Note that this has no impact on the regular scheduling of the
1024 	 * updates triggered by traffic - those happen whenever one of the
1025 	 * two timeouts expire (if there's traffic at all.)
1026 	 */
1027 	return 0;
1028 }
1029 
1030 void iwl_mvm_recalc_tcm(struct iwl_mvm *mvm)
1031 {
1032 	unsigned long ts = jiffies;
1033 	bool handle_uapsd =
1034 		time_after(ts, mvm->tcm.uapsd_nonagg_ts +
1035 			       msecs_to_jiffies(IWL_MVM_UAPSD_NONAGG_PERIOD));
1036 
1037 	spin_lock(&mvm->tcm.lock);
1038 	if (mvm->tcm.paused || !time_after(ts, mvm->tcm.ts + MVM_TCM_PERIOD)) {
1039 		spin_unlock(&mvm->tcm.lock);
1040 		return;
1041 	}
1042 	spin_unlock(&mvm->tcm.lock);
1043 
1044 	if (handle_uapsd && iwl_mvm_has_new_rx_api(mvm)) {
1045 		mutex_lock(&mvm->mutex);
1046 		if (iwl_mvm_request_statistics(mvm, true))
1047 			handle_uapsd = false;
1048 		mutex_unlock(&mvm->mutex);
1049 	}
1050 
1051 	spin_lock(&mvm->tcm.lock);
1052 	/* re-check if somebody else won the recheck race */
1053 	if (!mvm->tcm.paused && time_after(ts, mvm->tcm.ts + MVM_TCM_PERIOD)) {
1054 		/* calculate statistics */
1055 		unsigned long work_delay = iwl_mvm_calc_tcm_stats(mvm, ts,
1056 								  handle_uapsd);
1057 
1058 		/* the memset needs to be visible before the timestamp */
1059 		smp_mb();
1060 		mvm->tcm.ts = ts;
1061 		if (work_delay)
1062 			schedule_delayed_work(&mvm->tcm.work, work_delay);
1063 	}
1064 	spin_unlock(&mvm->tcm.lock);
1065 
1066 	iwl_mvm_tcm_results(mvm);
1067 }
1068 
1069 void iwl_mvm_tcm_work(struct work_struct *work)
1070 {
1071 	struct delayed_work *delayed_work = to_delayed_work(work);
1072 	struct iwl_mvm *mvm = container_of(delayed_work, struct iwl_mvm,
1073 					   tcm.work);
1074 
1075 	iwl_mvm_recalc_tcm(mvm);
1076 }
1077 
1078 void iwl_mvm_pause_tcm(struct iwl_mvm *mvm, bool with_cancel)
1079 {
1080 	spin_lock_bh(&mvm->tcm.lock);
1081 	mvm->tcm.paused = true;
1082 	spin_unlock_bh(&mvm->tcm.lock);
1083 	if (with_cancel)
1084 		cancel_delayed_work_sync(&mvm->tcm.work);
1085 }
1086 
1087 void iwl_mvm_resume_tcm(struct iwl_mvm *mvm)
1088 {
1089 	int mac;
1090 	bool low_latency = false;
1091 
1092 	spin_lock_bh(&mvm->tcm.lock);
1093 	mvm->tcm.ts = jiffies;
1094 	mvm->tcm.ll_ts = jiffies;
1095 	for (mac = 0; mac < NUM_MAC_INDEX_DRIVER; mac++) {
1096 		struct iwl_mvm_tcm_mac *mdata = &mvm->tcm.data[mac];
1097 
1098 		memset(&mdata->rx.pkts, 0, sizeof(mdata->rx.pkts));
1099 		memset(&mdata->tx.pkts, 0, sizeof(mdata->tx.pkts));
1100 		memset(&mdata->rx.airtime, 0, sizeof(mdata->rx.airtime));
1101 		memset(&mdata->tx.airtime, 0, sizeof(mdata->tx.airtime));
1102 
1103 		if (mvm->tcm.result.low_latency[mac])
1104 			low_latency = true;
1105 	}
1106 	/* The TCM data needs to be reset before "paused" flag changes */
1107 	smp_mb();
1108 	mvm->tcm.paused = false;
1109 
1110 	/*
1111 	 * if the current load is not low or low latency is active, force
1112 	 * re-evaluation to cover the case of no traffic.
1113 	 */
1114 	if (mvm->tcm.result.global_load > IWL_MVM_TRAFFIC_LOW)
1115 		schedule_delayed_work(&mvm->tcm.work, MVM_TCM_PERIOD);
1116 	else if (low_latency)
1117 		schedule_delayed_work(&mvm->tcm.work, MVM_LL_PERIOD);
1118 
1119 	spin_unlock_bh(&mvm->tcm.lock);
1120 }
1121 
1122 void iwl_mvm_tcm_add_vif(struct iwl_mvm *mvm, struct ieee80211_vif *vif)
1123 {
1124 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
1125 
1126 	INIT_DELAYED_WORK(&mvmvif->uapsd_nonagg_detected_wk,
1127 			  iwl_mvm_tcm_uapsd_nonagg_detected_wk);
1128 }
1129 
1130 void iwl_mvm_tcm_rm_vif(struct iwl_mvm *mvm, struct ieee80211_vif *vif)
1131 {
1132 	struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
1133 
1134 	cancel_delayed_work_sync(&mvmvif->uapsd_nonagg_detected_wk);
1135 }
1136 
1137 u32 iwl_mvm_get_systime(struct iwl_mvm *mvm)
1138 {
1139 	u32 reg_addr = DEVICE_SYSTEM_TIME_REG;
1140 
1141 	if (mvm->trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_22000 &&
1142 	    mvm->trans->cfg->gp2_reg_addr)
1143 		reg_addr = mvm->trans->cfg->gp2_reg_addr;
1144 
1145 	return iwl_read_prph(mvm->trans, reg_addr);
1146 }
1147 
1148 void iwl_mvm_get_sync_time(struct iwl_mvm *mvm, int clock_type,
1149 			   u32 *gp2, u64 *boottime, ktime_t *realtime)
1150 {
1151 	bool ps_disabled;
1152 
1153 	lockdep_assert_held(&mvm->mutex);
1154 
1155 	/* Disable power save when reading GP2 */
1156 	ps_disabled = mvm->ps_disabled;
1157 	if (!ps_disabled) {
1158 		mvm->ps_disabled = true;
1159 		iwl_mvm_power_update_device(mvm);
1160 	}
1161 
1162 	*gp2 = iwl_mvm_get_systime(mvm);
1163 
1164 	if (clock_type == CLOCK_BOOTTIME && boottime)
1165 		*boottime = ktime_get_boottime_ns();
1166 	else if (clock_type == CLOCK_REALTIME && realtime)
1167 		*realtime = ktime_get_real();
1168 
1169 	if (!ps_disabled) {
1170 		mvm->ps_disabled = ps_disabled;
1171 		iwl_mvm_power_update_device(mvm);
1172 	}
1173 }
1174