xref: /linux/net/mac80211/sta_info.c (revision 14b1a85518a17c01a8d52a8d3332596b68b4f201)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright 2002-2005, Instant802 Networks, Inc.
4  * Copyright 2006-2007	Jiri Benc <jbenc@suse.cz>
5  * Copyright 2013-2014  Intel Mobile Communications GmbH
6  * Copyright (C) 2015 - 2017 Intel Deutschland GmbH
7  * Copyright (C) 2018-2026 Intel Corporation
8  */
9 
10 #include <linux/module.h>
11 #include <linux/init.h>
12 #include <linux/etherdevice.h>
13 #include <linux/netdevice.h>
14 #include <linux/types.h>
15 #include <linux/slab.h>
16 #include <linux/skbuff.h>
17 #include <linux/if_arp.h>
18 #include <linux/timer.h>
19 #include <linux/rtnetlink.h>
20 
21 #include <net/mac80211.h>
22 #include "ieee80211_i.h"
23 #include "driver-ops.h"
24 #include "rate.h"
25 #include "sta_info.h"
26 #include "debugfs_sta.h"
27 #include "mesh.h"
28 #include "wme.h"
29 
30 /**
31  * DOC: STA information lifetime rules
32  *
33  * STA info structures (&struct sta_info) are managed in a hash table
34  * for faster lookup and a list for iteration. They are managed using
35  * RCU, i.e. access to the list and hash table is protected by RCU.
36  *
37  * Upon allocating a STA info structure with sta_info_alloc(), the caller
38  * owns that structure. It must then insert it into the hash table using
39  * either sta_info_insert() or sta_info_insert_rcu(); only in the latter
40  * case (which acquires an rcu read section but must not be called from
41  * within one) will the pointer still be valid after the call. Note that
42  * the caller may not do much with the STA info before inserting it; in
43  * particular, it may not start any mesh peer link management or add
44  * encryption keys.
45  *
46  * When the insertion fails (sta_info_insert()) returns non-zero), the
47  * structure will have been freed by sta_info_insert()!
48  *
49  * Station entries are added by mac80211 when you establish a link with a
50  * peer. This means different things for the different type of interfaces
51  * we support. For a regular station this mean we add the AP sta when we
52  * receive an association response from the AP. For IBSS this occurs when
53  * get to know about a peer on the same IBSS. For WDS we add the sta for
54  * the peer immediately upon device open. When using AP mode we add stations
55  * for each respective station upon request from userspace through nl80211.
56  *
57  * In order to remove a STA info structure, various sta_info_destroy_*()
58  * calls are available.
59  *
60  * There is no concept of ownership on a STA entry; each structure is
61  * owned by the global hash table/list until it is removed. All users of
62  * the structure need to be RCU protected so that the structure won't be
63  * freed before they are done using it.
64  */
65 
66 struct sta_link_alloc {
67 	struct link_sta_info info;
68 	struct ieee80211_link_sta sta;
69 	struct rcu_head rcu_head;
70 };
71 
72 static const struct rhashtable_params sta_rht_params = {
73 	.nelem_hint = 3, /* start small */
74 	.automatic_shrinking = true,
75 	.head_offset = offsetof(struct sta_info, hash_node),
76 	.key_offset = offsetof(struct sta_info, addr),
77 	.key_len = ETH_ALEN,
78 	.max_size = CONFIG_MAC80211_STA_HASH_MAX_SIZE,
79 };
80 
81 static const struct rhashtable_params link_sta_rht_params = {
82 	.nelem_hint = 3, /* start small */
83 	.automatic_shrinking = true,
84 	.head_offset = offsetof(struct link_sta_info, link_hash_node),
85 	.key_offset = offsetof(struct link_sta_info, addr),
86 	.key_len = ETH_ALEN,
87 	.max_size = CONFIG_MAC80211_STA_HASH_MAX_SIZE,
88 };
89 
90 static int sta_info_hash_del(struct ieee80211_local *local,
91 			     struct sta_info *sta)
92 {
93 	return rhltable_remove(&local->sta_hash, &sta->hash_node,
94 			       sta_rht_params);
95 }
96 
97 static int link_sta_info_hash_add(struct ieee80211_local *local,
98 				  struct link_sta_info *link_sta)
99 {
100 	lockdep_assert_wiphy(local->hw.wiphy);
101 
102 	return rhltable_insert(&local->link_sta_hash,
103 			       &link_sta->link_hash_node, link_sta_rht_params);
104 }
105 
106 static int link_sta_info_hash_del(struct ieee80211_local *local,
107 				  struct link_sta_info *link_sta)
108 {
109 	lockdep_assert_wiphy(local->hw.wiphy);
110 
111 	return rhltable_remove(&local->link_sta_hash,
112 			       &link_sta->link_hash_node, link_sta_rht_params);
113 }
114 
115 void ieee80211_purge_sta_txqs(struct sta_info *sta)
116 {
117 	struct ieee80211_local *local = sta->sdata->local;
118 	int i;
119 
120 	for (i = 0; i < ARRAY_SIZE(sta->sta.txq); i++) {
121 		struct txq_info *txqi;
122 
123 		if (!sta->sta.txq[i])
124 			continue;
125 
126 		txqi = to_txq_info(sta->sta.txq[i]);
127 
128 		ieee80211_txq_purge(local, txqi);
129 	}
130 }
131 
132 static void __cleanup_single_sta(struct sta_info *sta)
133 {
134 	int ac, i;
135 	struct tid_ampdu_tx *tid_tx;
136 	struct ieee80211_sub_if_data *sdata = sta->sdata;
137 	struct ieee80211_local *local = sdata->local;
138 	struct ps_data *ps;
139 
140 	if (test_sta_flag(sta, WLAN_STA_PS_STA) ||
141 	    test_sta_flag(sta, WLAN_STA_PS_DRIVER) ||
142 	    test_sta_flag(sta, WLAN_STA_PS_DELIVER)) {
143 		if (sta->sdata->vif.type == NL80211_IFTYPE_AP ||
144 		    sta->sdata->vif.type == NL80211_IFTYPE_AP_VLAN)
145 			ps = &sdata->bss->ps;
146 		else if (ieee80211_vif_is_mesh(&sdata->vif))
147 			ps = &sdata->u.mesh.ps;
148 		else
149 			return;
150 
151 		clear_sta_flag(sta, WLAN_STA_PS_STA);
152 		clear_sta_flag(sta, WLAN_STA_PS_DRIVER);
153 		clear_sta_flag(sta, WLAN_STA_PS_DELIVER);
154 
155 		atomic_dec(&ps->num_sta_ps);
156 	}
157 
158 	ieee80211_purge_sta_txqs(sta);
159 
160 	for (ac = 0; ac < IEEE80211_NUM_ACS; ac++) {
161 		local->total_ps_buffered -= skb_queue_len(&sta->ps_tx_buf[ac]);
162 		ieee80211_purge_tx_queue(&local->hw, &sta->ps_tx_buf[ac]);
163 		ieee80211_purge_tx_queue(&local->hw, &sta->tx_filtered[ac]);
164 	}
165 
166 	if (ieee80211_vif_is_mesh(&sdata->vif))
167 		mesh_sta_cleanup(sta);
168 
169 	cancel_work_sync(&sta->drv_deliver_wk);
170 
171 	/*
172 	 * Destroy aggregation state here. It would be nice to wait for the
173 	 * driver to finish aggregation stop and then clean up, but for now
174 	 * drivers have to handle aggregation stop being requested, followed
175 	 * directly by station destruction.
176 	 */
177 	for (i = 0; i < IEEE80211_NUM_TIDS; i++) {
178 		kfree(sta->ampdu_mlme.tid_start_tx[i]);
179 		tid_tx = rcu_dereference_raw(sta->ampdu_mlme.tid_tx[i]);
180 		if (!tid_tx)
181 			continue;
182 		ieee80211_purge_tx_queue(&local->hw, &tid_tx->pending);
183 		kfree(tid_tx);
184 	}
185 }
186 
187 static void cleanup_single_sta(struct sta_info *sta)
188 {
189 	struct ieee80211_sub_if_data *sdata = sta->sdata;
190 	struct ieee80211_local *local = sdata->local;
191 
192 	__cleanup_single_sta(sta);
193 	sta_info_free(local, sta);
194 }
195 
196 struct rhlist_head *sta_info_hash_lookup(struct ieee80211_local *local,
197 					 const u8 *addr)
198 {
199 	return rhltable_lookup(&local->sta_hash, addr, sta_rht_params);
200 }
201 
202 /* protected by RCU */
203 struct sta_info *sta_info_get(struct ieee80211_sub_if_data *sdata,
204 			      const u8 *addr)
205 {
206 	struct ieee80211_local *local = sdata->local;
207 	struct rhlist_head *tmp;
208 	struct sta_info *sta;
209 
210 	rcu_read_lock();
211 	for_each_sta_info(local, addr, sta, tmp) {
212 		if (sta->sdata == sdata) {
213 			rcu_read_unlock();
214 			/* this is safe as the caller must already hold
215 			 * another rcu read section or the mutex
216 			 */
217 			return sta;
218 		}
219 	}
220 	rcu_read_unlock();
221 	return NULL;
222 }
223 
224 /*
225  * Get sta info either from the specified interface
226  * or from one of its vlans
227  */
228 struct sta_info *sta_info_get_bss(struct ieee80211_sub_if_data *sdata,
229 				  const u8 *addr)
230 {
231 	struct ieee80211_local *local = sdata->local;
232 	struct rhlist_head *tmp;
233 	struct sta_info *sta;
234 
235 	rcu_read_lock();
236 	for_each_sta_info(local, addr, sta, tmp) {
237 		if (sta->sdata == sdata ||
238 		    (sta->sdata->bss && sta->sdata->bss == sdata->bss)) {
239 			rcu_read_unlock();
240 			/* this is safe as the caller must already hold
241 			 * another rcu read section or the mutex
242 			 */
243 			return sta;
244 		}
245 	}
246 	rcu_read_unlock();
247 	return NULL;
248 }
249 
250 struct rhlist_head *link_sta_info_hash_lookup(struct ieee80211_local *local,
251 					      const u8 *addr)
252 {
253 	return rhltable_lookup(&local->link_sta_hash, addr,
254 			       link_sta_rht_params);
255 }
256 
257 struct link_sta_info *
258 link_sta_info_get_bss(struct ieee80211_sub_if_data *sdata, const u8 *addr)
259 {
260 	struct ieee80211_local *local = sdata->local;
261 	struct rhlist_head *tmp;
262 	struct link_sta_info *link_sta;
263 
264 	rcu_read_lock();
265 	for_each_link_sta_info(local, addr, link_sta, tmp) {
266 		struct sta_info *sta = link_sta->sta;
267 
268 		if (sta->sdata == sdata ||
269 		    (sta->sdata->bss && sta->sdata->bss == sdata->bss)) {
270 			rcu_read_unlock();
271 			/* this is safe as the caller must already hold
272 			 * another rcu read section or the mutex
273 			 */
274 			return link_sta;
275 		}
276 	}
277 	rcu_read_unlock();
278 	return NULL;
279 }
280 
281 struct ieee80211_sta *
282 ieee80211_find_sta_by_link_addrs(struct ieee80211_hw *hw,
283 				 const u8 *addr,
284 				 const u8 *localaddr,
285 				 unsigned int *link_id)
286 {
287 	struct ieee80211_local *local = hw_to_local(hw);
288 	struct link_sta_info *link_sta;
289 	struct rhlist_head *tmp;
290 
291 	for_each_link_sta_info(local, addr, link_sta, tmp) {
292 		struct sta_info *sta = link_sta->sta;
293 		struct ieee80211_link_data *link;
294 		u8 _link_id = link_sta->link_id;
295 
296 		if (!localaddr) {
297 			if (link_id)
298 				*link_id = _link_id;
299 			return &sta->sta;
300 		}
301 
302 		link = rcu_dereference(sta->sdata->link[_link_id]);
303 		if (!link)
304 			continue;
305 
306 		if (memcmp(link->conf->addr, localaddr, ETH_ALEN))
307 			continue;
308 
309 		if (link_id)
310 			*link_id = _link_id;
311 		return &sta->sta;
312 	}
313 
314 	return NULL;
315 }
316 EXPORT_SYMBOL_GPL(ieee80211_find_sta_by_link_addrs);
317 
318 struct sta_info *sta_info_get_by_addrs(struct ieee80211_local *local,
319 				       const u8 *sta_addr, const u8 *vif_addr)
320 {
321 	struct rhlist_head *tmp;
322 	struct sta_info *sta;
323 
324 	for_each_sta_info(local, sta_addr, sta, tmp) {
325 		if (ether_addr_equal(vif_addr, sta->sdata->vif.addr))
326 			return sta;
327 	}
328 
329 	return NULL;
330 }
331 
332 struct sta_info *sta_info_get_by_idx(struct ieee80211_sub_if_data *sdata,
333 				     int idx)
334 {
335 	struct ieee80211_local *local = sdata->local;
336 	struct sta_info *sta;
337 	int i = 0;
338 
339 	list_for_each_entry_rcu(sta, &local->sta_list, list,
340 				lockdep_is_held(&local->hw.wiphy->mtx)) {
341 		if (sdata != sta->sdata)
342 			continue;
343 		if (i < idx) {
344 			++i;
345 			continue;
346 		}
347 		return sta;
348 	}
349 
350 	return NULL;
351 }
352 
353 static void sta_info_free_link(struct link_sta_info *link_sta)
354 {
355 	free_percpu(link_sta->pcpu_rx_stats);
356 }
357 
358 static void sta_accumulate_removed_link_stats(struct sta_info *sta, int link_id)
359 {
360 	struct link_sta_info *link_sta = wiphy_dereference(sta->local->hw.wiphy,
361 							   sta->link[link_id]);
362 	struct ieee80211_link_data *link;
363 	unsigned int start;
364 	int ac, tid;
365 	u64 value;
366 	u32 thr;
367 
368 	for (ac = 0; ac < IEEE80211_NUM_ACS; ac++) {
369 		sta->rem_link_stats.tx_packets +=
370 			link_sta->tx_stats.packets[ac];
371 		sta->rem_link_stats.tx_bytes += link_sta->tx_stats.bytes[ac];
372 	}
373 
374 	do {
375 		start = u64_stats_fetch_begin(&link_sta->rx_stats.syncp);
376 		value = u64_stats_read(&link_sta->rx_stats.bytes);
377 	} while (u64_stats_fetch_retry(&link_sta->rx_stats.syncp, start));
378 
379 	sta->rem_link_stats.rx_packets += link_sta->rx_stats.packets;
380 	sta->rem_link_stats.rx_bytes += value;
381 	sta->rem_link_stats.tx_retries += link_sta->status_stats.retry_count;
382 	sta->rem_link_stats.tx_failed += link_sta->status_stats.retry_failed;
383 	sta->rem_link_stats.rx_dropped_misc += link_sta->rx_stats.dropped;
384 
385 	thr = sta_get_expected_throughput(sta);
386 	if (thr != 0)
387 		sta->rem_link_stats.expected_throughput += thr;
388 
389 	for (tid = 0; tid < IEEE80211_NUM_TIDS; tid++) {
390 		do {
391 			start = u64_stats_fetch_begin(&link_sta->rx_stats.syncp);
392 			value = u64_stats_read(&link_sta->rx_stats.msdu[tid]);
393 		} while (u64_stats_fetch_retry(&link_sta->rx_stats.syncp,
394 					       start));
395 
396 		sta->rem_link_stats.pertid_stats.rx_msdu += value;
397 		sta->rem_link_stats.pertid_stats.tx_msdu +=
398 			link_sta->tx_stats.msdu[tid];
399 		sta->rem_link_stats.pertid_stats.tx_msdu_retries +=
400 			link_sta->status_stats.msdu_retries[tid];
401 		sta->rem_link_stats.pertid_stats.tx_msdu_failed +=
402 			link_sta->status_stats.msdu_failed[tid];
403 	}
404 
405 	if (sta->sdata->vif.type == NL80211_IFTYPE_STATION) {
406 		link = wiphy_dereference(sta->sdata->local->hw.wiphy,
407 					 sta->sdata->link[link_id]);
408 		if (link)
409 			sta->rem_link_stats.beacon_loss_count +=
410 				link->u.mgd.beacon_loss_count;
411 	}
412 }
413 
414 static void sta_remove_link(struct sta_info *sta, unsigned int link_id,
415 			    bool unhash)
416 {
417 	struct sta_link_alloc *alloc = NULL;
418 	struct link_sta_info *link_sta;
419 
420 	lockdep_assert_wiphy(sta->local->hw.wiphy);
421 
422 	link_sta = rcu_access_pointer(sta->link[link_id]);
423 	if (WARN_ON(!link_sta))
424 		return;
425 
426 	if (unhash)
427 		link_sta_info_hash_del(sta->local, link_sta);
428 
429 	if (test_sta_flag(sta, WLAN_STA_INSERTED))
430 		ieee80211_link_sta_debugfs_remove(link_sta);
431 
432 	if (link_sta != &sta->deflink)
433 		alloc = container_of(link_sta, typeof(*alloc), info);
434 
435 	sta->sta.valid_links &= ~BIT(link_id);
436 
437 	/* store removed link info for accumulated stats consistency */
438 	sta_accumulate_removed_link_stats(sta, link_id);
439 
440 	RCU_INIT_POINTER(sta->link[link_id], NULL);
441 	RCU_INIT_POINTER(sta->sta.link[link_id], NULL);
442 	if (alloc) {
443 		sta_info_free_link(&alloc->info);
444 		kfree_rcu(alloc, rcu_head);
445 	}
446 
447 	ieee80211_sta_recalc_aggregates(&sta->sta);
448 }
449 
450 /**
451  * sta_info_free - free STA
452  *
453  * @local: pointer to the global information
454  * @sta: STA info to free
455  *
456  * This function must undo everything done by sta_info_alloc()
457  * that may happen before sta_info_insert(). It may only be
458  * called when sta_info_insert() has not been attempted (and
459  * if that fails, the station is freed anyway.)
460  */
461 void sta_info_free(struct ieee80211_local *local, struct sta_info *sta)
462 {
463 	int i;
464 
465 	for (i = 0; i < ARRAY_SIZE(sta->link); i++) {
466 		struct link_sta_info *link_sta;
467 
468 		link_sta = rcu_access_pointer(sta->link[i]);
469 		if (!link_sta)
470 			continue;
471 
472 		sta_remove_link(sta, i, false);
473 	}
474 
475 	/*
476 	 * If we had used sta_info_pre_move_state() then we might not
477 	 * have gone through the state transitions down again, so do
478 	 * it here now (and warn if it's inserted).
479 	 *
480 	 * This will clear state such as fast TX/RX that may have been
481 	 * allocated during state transitions.
482 	 */
483 	while (sta->sta_state > IEEE80211_STA_NONE) {
484 		int ret;
485 
486 		WARN_ON_ONCE(test_sta_flag(sta, WLAN_STA_INSERTED));
487 
488 		ret = sta_info_move_state(sta, sta->sta_state - 1);
489 		if (WARN_ONCE(ret, "sta_info_move_state() returned %d\n", ret))
490 			break;
491 	}
492 
493 	if (sta->rate_ctrl)
494 		rate_control_free_sta(sta);
495 
496 	sta_dbg(sta->sdata, "Destroyed STA %pM\n", sta->sta.addr);
497 
498 	kfree(to_txq_info(sta->sta.txq[0]));
499 	kfree(rcu_dereference_raw(sta->sta.rates));
500 #ifdef CONFIG_MAC80211_MESH
501 	kfree(sta->mesh);
502 #endif
503 
504 	sta_info_free_link(&sta->deflink);
505 	kfree(sta);
506 }
507 
508 static int sta_info_hash_add(struct ieee80211_local *local,
509 			     struct sta_info *sta)
510 {
511 	return rhltable_insert(&local->sta_hash, &sta->hash_node,
512 			       sta_rht_params);
513 }
514 
515 static void sta_deliver_ps_frames(struct work_struct *wk)
516 {
517 	struct sta_info *sta;
518 
519 	sta = container_of(wk, struct sta_info, drv_deliver_wk);
520 
521 	if (sta->dead)
522 		return;
523 
524 	local_bh_disable();
525 	if (!test_sta_flag(sta, WLAN_STA_PS_STA))
526 		ieee80211_sta_ps_deliver_wakeup(sta);
527 	else if (test_and_clear_sta_flag(sta, WLAN_STA_PSPOLL))
528 		ieee80211_sta_ps_deliver_poll_response(sta);
529 	else if (test_and_clear_sta_flag(sta, WLAN_STA_UAPSD))
530 		ieee80211_sta_ps_deliver_uapsd(sta);
531 	local_bh_enable();
532 }
533 
534 static int sta_prepare_rate_control(struct ieee80211_local *local,
535 				    struct sta_info *sta, gfp_t gfp)
536 {
537 	if (ieee80211_hw_check(&local->hw, HAS_RATE_CONTROL))
538 		return 0;
539 
540 	sta->rate_ctrl = local->rate_ctrl;
541 	sta->rate_ctrl_priv = rate_control_alloc_sta(sta->rate_ctrl,
542 						     sta, gfp);
543 	if (!sta->rate_ctrl_priv)
544 		return -ENOMEM;
545 
546 	return 0;
547 }
548 
549 static int sta_info_alloc_link(struct ieee80211_local *local,
550 			       struct link_sta_info *link_info,
551 			       gfp_t gfp)
552 {
553 	struct ieee80211_hw *hw = &local->hw;
554 	int i;
555 
556 	if (ieee80211_hw_check(hw, USES_RSS)) {
557 		link_info->pcpu_rx_stats =
558 			alloc_percpu_gfp(struct ieee80211_sta_rx_stats, gfp);
559 		if (!link_info->pcpu_rx_stats)
560 			return -ENOMEM;
561 	}
562 
563 	link_info->rx_stats.last_rx = jiffies;
564 	u64_stats_init(&link_info->rx_stats.syncp);
565 
566 	ewma_signal_init(&link_info->rx_stats_avg.signal);
567 	ewma_avg_signal_init(&link_info->status_stats.avg_ack_signal);
568 	for (i = 0; i < ARRAY_SIZE(link_info->rx_stats_avg.chain_signal); i++)
569 		ewma_signal_init(&link_info->rx_stats_avg.chain_signal[i]);
570 
571 	link_info->rx_omi_bw_rx = IEEE80211_STA_RX_BW_MAX;
572 	link_info->rx_omi_bw_tx = IEEE80211_STA_RX_BW_MAX;
573 	link_info->rx_omi_bw_staging = IEEE80211_STA_RX_BW_MAX;
574 
575 	/*
576 	 * This will always be taken into account, so set to MAX.
577 	 * When mac80211 is the client on a UHR AP, it'll be used
578 	 * for the TX side, to limit the bandwidth to TX to the AP
579 	 * with, to limit to the BSS width during DBE enablement.
580 	 *
581 	 * This is needed since the chanreq, which normally has
582 	 * maximum bandwidth to use with the AP, will already be
583 	 * set to the DBE width during enablement to prepare for
584 	 * RX (and not be racy), but the TX can only use higher
585 	 * bandwidth after enablement finishes.
586 	 */
587 	link_info->uhr_usable_tx_width = IEEE80211_STA_RX_BW_MAX;
588 
589 	link_info->op_mode_bw = IEEE80211_STA_RX_BW_MAX;
590 
591 	/*
592 	 * Cause (a) warning(s) if IEEE80211_STA_RX_BW_MAX != 320
593 	 * or if new values are added to the enum.
594 	 */
595 	switch (link_info->op_mode_bw) {
596 	case IEEE80211_STA_RX_BW_20:
597 	case IEEE80211_STA_RX_BW_40:
598 	case IEEE80211_STA_RX_BW_80:
599 	case IEEE80211_STA_RX_BW_160:
600 	case IEEE80211_STA_RX_BW_MAX:
601 		/* intentionally nothing */
602 		break;
603 	}
604 
605 	return 0;
606 }
607 
608 static void sta_info_add_link(struct sta_info *sta,
609 			      unsigned int link_id,
610 			      struct link_sta_info *link_info,
611 			      struct ieee80211_link_sta *link_sta)
612 {
613 	link_info->sta = sta;
614 	link_info->link_id = link_id;
615 	link_info->pub = link_sta;
616 	link_info->pub->sta = &sta->sta;
617 	link_sta->link_id = link_id;
618 	rcu_assign_pointer(sta->link[link_id], link_info);
619 	rcu_assign_pointer(sta->sta.link[link_id], link_sta);
620 
621 	link_sta->smps_mode = IEEE80211_SMPS_OFF;
622 	link_sta->agg.max_rc_amsdu_len = IEEE80211_MAX_MPDU_LEN_HT_BA;
623 }
624 
625 static struct sta_info *
626 __sta_info_alloc(struct ieee80211_sub_if_data *sdata,
627 		 const u8 *addr, int link_id, const u8 *link_addr,
628 		 gfp_t gfp)
629 {
630 	struct ieee80211_local *local = sdata->local;
631 	struct ieee80211_hw *hw = &local->hw;
632 	struct sta_info *sta;
633 	void *txq_data;
634 	int size;
635 	int i;
636 
637 	sta = kzalloc(sizeof(*sta) + hw->sta_data_size, gfp);
638 	if (!sta)
639 		return NULL;
640 
641 	sta->local = local;
642 	sta->sdata = sdata;
643 
644 	if (sta_info_alloc_link(local, &sta->deflink, gfp))
645 		goto free;
646 
647 	if (link_id >= 0) {
648 		sta_info_add_link(sta, link_id, &sta->deflink,
649 				  &sta->sta.deflink);
650 		sta->sta.valid_links = BIT(link_id);
651 	} else {
652 		sta_info_add_link(sta, 0, &sta->deflink, &sta->sta.deflink);
653 	}
654 
655 	sta->sta.cur = &sta->sta.deflink.agg;
656 
657 	spin_lock_init(&sta->lock);
658 	spin_lock_init(&sta->ps_lock);
659 	INIT_WORK(&sta->drv_deliver_wk, sta_deliver_ps_frames);
660 	wiphy_work_init(&sta->ampdu_mlme.work, ieee80211_ba_session_work);
661 #ifdef CONFIG_MAC80211_MESH
662 	if (ieee80211_vif_is_mesh(&sdata->vif)) {
663 		sta->mesh = kzalloc_obj(*sta->mesh, gfp);
664 		if (!sta->mesh)
665 			goto free;
666 		sta->mesh->plink_sta = sta;
667 		spin_lock_init(&sta->mesh->plink_lock);
668 		if (!sdata->u.mesh.user_mpm)
669 			timer_setup(&sta->mesh->plink_timer, mesh_plink_timer,
670 				    0);
671 		sta->mesh->nonpeer_pm = NL80211_MESH_POWER_ACTIVE;
672 	}
673 #endif
674 
675 	memcpy(sta->addr, addr, ETH_ALEN);
676 	memcpy(sta->sta.addr, addr, ETH_ALEN);
677 	memcpy(sta->deflink.addr, link_addr, ETH_ALEN);
678 	memcpy(sta->sta.deflink.addr, link_addr, ETH_ALEN);
679 	sta->sta.max_rx_aggregation_subframes =
680 		local->hw.max_rx_aggregation_subframes;
681 
682 	/* TODO link specific alloc and assignments for MLO Link STA */
683 
684 	/* Extended Key ID needs to install keys for keyid 0 and 1 Rx-only.
685 	 * The Tx path starts to use a key as soon as the key slot ptk_idx
686 	 * references to is not NULL. To not use the initial Rx-only key
687 	 * prematurely for Tx initialize ptk_idx to an impossible PTK keyid
688 	 * which always will refer to a NULL key.
689 	 */
690 	BUILD_BUG_ON(ARRAY_SIZE(sta->ptk) <= INVALID_PTK_KEYIDX);
691 	sta->ptk_idx = INVALID_PTK_KEYIDX;
692 
693 
694 	ieee80211_init_frag_cache(&sta->frags);
695 
696 	sta->sta_state = IEEE80211_STA_NONE;
697 
698 	if (sdata->vif.type == NL80211_IFTYPE_MESH_POINT)
699 		sta->amsdu_mesh_control = -1;
700 
701 	/* Mark TID as unreserved */
702 	sta->reserved_tid = IEEE80211_TID_UNRESERVED;
703 
704 	sta->last_connected = ktime_get_seconds();
705 
706 	size = sizeof(struct txq_info) +
707 	       ALIGN(hw->txq_data_size, sizeof(void *));
708 
709 	txq_data = kcalloc(ARRAY_SIZE(sta->sta.txq), size, gfp);
710 	if (!txq_data)
711 		goto free;
712 
713 	for (i = 0; i < ARRAY_SIZE(sta->sta.txq); i++) {
714 		struct txq_info *txq = txq_data + i * size;
715 
716 		/* might not do anything for the (bufferable) MMPDU TXQ */
717 		ieee80211_txq_init(sdata, sta, txq, i);
718 	}
719 
720 	if (sta_prepare_rate_control(local, sta, gfp))
721 		goto free_txq;
722 
723 	sta->airtime_weight = IEEE80211_DEFAULT_AIRTIME_WEIGHT;
724 
725 	for (i = 0; i < IEEE80211_NUM_ACS; i++) {
726 		skb_queue_head_init(&sta->ps_tx_buf[i]);
727 		skb_queue_head_init(&sta->tx_filtered[i]);
728 		sta->airtime[i].deficit = sta->airtime_weight;
729 		atomic_set(&sta->airtime[i].aql_tx_pending, 0);
730 		sta->airtime[i].aql_limit_low = local->aql_txq_limit_low[i];
731 		sta->airtime[i].aql_limit_high = local->aql_txq_limit_high[i];
732 	}
733 
734 	for (i = 0; i < IEEE80211_NUM_TIDS; i++)
735 		sta->last_seq_ctrl[i] = cpu_to_le16(USHRT_MAX);
736 
737 	for (i = 0; i < NUM_NL80211_BANDS; i++) {
738 		u32 mandatory = 0;
739 		int r;
740 
741 		if (!hw->wiphy->bands[i])
742 			continue;
743 
744 		switch (i) {
745 		case NL80211_BAND_2GHZ:
746 		case NL80211_BAND_LC:
747 			/*
748 			 * We use both here, even if we cannot really know for
749 			 * sure the station will support both, but the only use
750 			 * for this is when we don't know anything yet and send
751 			 * management frames, and then we'll pick the lowest
752 			 * possible rate anyway.
753 			 * If we don't include _G here, we cannot find a rate
754 			 * in P2P, and thus trigger the WARN_ONCE() in rate.c
755 			 */
756 			mandatory = IEEE80211_RATE_MANDATORY_B |
757 				    IEEE80211_RATE_MANDATORY_G;
758 			break;
759 		case NL80211_BAND_5GHZ:
760 		case NL80211_BAND_6GHZ:
761 			mandatory = IEEE80211_RATE_MANDATORY_A;
762 			break;
763 		case NL80211_BAND_60GHZ:
764 			WARN_ON(1);
765 			mandatory = 0;
766 			break;
767 		}
768 
769 		for (r = 0; r < hw->wiphy->bands[i]->n_bitrates; r++) {
770 			struct ieee80211_rate *rate;
771 
772 			rate = &hw->wiphy->bands[i]->bitrates[r];
773 
774 			if (!(rate->flags & mandatory))
775 				continue;
776 			sta->sta.deflink.supp_rates[i] |= BIT(r);
777 		}
778 	}
779 
780 
781 	sta_dbg(sdata, "Allocated STA %pM\n", sta->sta.addr);
782 
783 	return sta;
784 
785 free_txq:
786 	kfree(to_txq_info(sta->sta.txq[0]));
787 free:
788 	sta_info_free_link(&sta->deflink);
789 #ifdef CONFIG_MAC80211_MESH
790 	kfree(sta->mesh);
791 #endif
792 	kfree(sta);
793 	return NULL;
794 }
795 
796 struct sta_info *sta_info_alloc(struct ieee80211_sub_if_data *sdata,
797 				const u8 *addr, gfp_t gfp)
798 {
799 	return __sta_info_alloc(sdata, addr, -1, addr, gfp);
800 }
801 
802 struct sta_info *sta_info_alloc_with_link(struct ieee80211_sub_if_data *sdata,
803 					  const u8 *mld_addr,
804 					  unsigned int link_id,
805 					  const u8 *link_addr,
806 					  gfp_t gfp)
807 {
808 	return __sta_info_alloc(sdata, mld_addr, link_id, link_addr, gfp);
809 }
810 
811 static int sta_info_insert_check(struct sta_info *sta)
812 {
813 	struct ieee80211_sub_if_data *sdata = sta->sdata;
814 	struct ieee80211_sta *same_addr_sta;
815 
816 	lockdep_assert_wiphy(sdata->local->hw.wiphy);
817 
818 	/*
819 	 * Can't be a WARN_ON because it can be triggered through a race:
820 	 * something inserts a STA (on one CPU) without holding the RTNL
821 	 * and another CPU turns off the net device.
822 	 */
823 	if (unlikely(!ieee80211_sdata_running(sdata)))
824 		return -ENETDOWN;
825 
826 	if (WARN_ON(ether_addr_equal(sta->sta.addr, sdata->vif.addr) ||
827 		    !is_valid_ether_addr(sta->sta.addr)))
828 		return -EINVAL;
829 
830 	if (!ieee80211_hw_check(&sdata->local->hw, NEEDS_UNIQUE_STA_ADDR))
831 		return 0;
832 
833 	/* The RCU read lock is required by rhashtable due to
834 	 * asynchronous resize/rehash.  We also require the mutex
835 	 * for correctness.
836 	 */
837 	rcu_read_lock();
838 	same_addr_sta = ieee80211_find_sta_by_ifaddr(&sdata->local->hw,
839 						     sta->addr, NULL);
840 	/* For NAN, a peer can re-use */
841 	if (same_addr_sta && same_addr_sta != rcu_access_pointer(sta->sta.nmi)) {
842 		rcu_read_unlock();
843 		return -ENOTUNIQ;
844 	}
845 	rcu_read_unlock();
846 
847 	return 0;
848 }
849 
850 static int sta_info_insert_drv_state(struct ieee80211_local *local,
851 				     struct ieee80211_sub_if_data *sdata,
852 				     struct sta_info *sta)
853 {
854 	enum ieee80211_sta_state state;
855 	int err = 0;
856 
857 	for (state = IEEE80211_STA_NOTEXIST; state < sta->sta_state; state++) {
858 		err = drv_sta_state(local, sdata, sta, state, state + 1);
859 		if (err)
860 			break;
861 	}
862 
863 	if (!err) {
864 		/*
865 		 * Drivers using legacy sta_add/sta_remove callbacks only
866 		 * get uploaded set to true after sta_add is called.
867 		 */
868 		if (!local->ops->sta_add)
869 			sta->uploaded = true;
870 		return 0;
871 	}
872 
873 	if (sdata->vif.type == NL80211_IFTYPE_ADHOC) {
874 		sdata_info(sdata,
875 			   "failed to move IBSS STA %pM to state %d (%d) - keeping it anyway\n",
876 			   sta->sta.addr, state + 1, err);
877 		err = 0;
878 	}
879 
880 	/* unwind on error */
881 	for (; state > IEEE80211_STA_NOTEXIST; state--)
882 		WARN_ON(drv_sta_state(local, sdata, sta, state, state - 1));
883 
884 	return err;
885 }
886 
887 static void
888 ieee80211_recalc_p2p_go_ps_allowed(struct ieee80211_sub_if_data *sdata)
889 {
890 	struct ieee80211_local *local = sdata->local;
891 	bool allow_p2p_go_ps = sdata->vif.p2p;
892 	struct sta_info *sta;
893 
894 	rcu_read_lock();
895 	list_for_each_entry_rcu(sta, &local->sta_list, list) {
896 		if (sdata != sta->sdata ||
897 		    !test_sta_flag(sta, WLAN_STA_ASSOC))
898 			continue;
899 		if (!sta->sta.support_p2p_ps) {
900 			allow_p2p_go_ps = false;
901 			break;
902 		}
903 	}
904 	rcu_read_unlock();
905 
906 	if (allow_p2p_go_ps != sdata->vif.bss_conf.allow_p2p_go_ps) {
907 		sdata->vif.bss_conf.allow_p2p_go_ps = allow_p2p_go_ps;
908 		ieee80211_link_info_change_notify(sdata, &sdata->deflink,
909 						  BSS_CHANGED_P2P_PS);
910 	}
911 }
912 
913 static int sta_info_insert_finish(struct sta_info *sta) __acquires(RCU)
914 {
915 	struct ieee80211_local *local = sta->local;
916 	struct ieee80211_sub_if_data *sdata = sta->sdata;
917 	struct station_info *sinfo = NULL;
918 	int err = 0;
919 
920 	lockdep_assert_wiphy(local->hw.wiphy);
921 
922 	/* check if STA exists already */
923 	if (sta_info_get_bss(sdata, sta->sta.addr)) {
924 		err = -EEXIST;
925 		goto out_cleanup;
926 	}
927 
928 	sinfo = kzalloc_obj(struct station_info);
929 	if (!sinfo) {
930 		err = -ENOMEM;
931 		goto out_cleanup;
932 	}
933 
934 	local->num_sta++;
935 	local->sta_generation++;
936 	smp_mb();
937 
938 	/* simplify things and don't accept BA sessions yet */
939 	set_sta_flag(sta, WLAN_STA_BLOCK_BA);
940 
941 	/* make the station visible */
942 	err = sta_info_hash_add(local, sta);
943 	if (err)
944 		goto out_drop_sta;
945 
946 	if (sta->sta.valid_links) {
947 		err = link_sta_info_hash_add(local, &sta->deflink);
948 		if (err) {
949 			sta_info_hash_del(local, sta);
950 			goto out_drop_sta;
951 		}
952 	}
953 
954 	list_add_tail_rcu(&sta->list, &local->sta_list);
955 
956 	/* update channel context before notifying the driver about state
957 	 * change, this enables driver using the updated channel context right away.
958 	 */
959 	if (sta->sta_state >= IEEE80211_STA_ASSOC) {
960 		ieee80211_recalc_min_chandef(sta->sdata, -1);
961 		if (!sta->sta.support_p2p_ps)
962 			ieee80211_recalc_p2p_go_ps_allowed(sta->sdata);
963 	}
964 
965 	/* notify driver */
966 	err = sta_info_insert_drv_state(local, sdata, sta);
967 	if (err)
968 		goto out_remove;
969 
970 	set_sta_flag(sta, WLAN_STA_INSERTED);
971 
972 	/* accept BA sessions now */
973 	clear_sta_flag(sta, WLAN_STA_BLOCK_BA);
974 
975 	ieee80211_sta_debugfs_add(sta);
976 	rate_control_add_sta_debugfs(sta);
977 	if (sta->sta.valid_links) {
978 		int i;
979 
980 		for (i = 0; i < ARRAY_SIZE(sta->link); i++) {
981 			struct link_sta_info *link_sta;
982 
983 			link_sta = rcu_dereference_protected(sta->link[i],
984 							     lockdep_is_held(&local->hw.wiphy->mtx));
985 
986 			if (!link_sta)
987 				continue;
988 
989 			ieee80211_link_sta_debugfs_add(link_sta);
990 			if (sdata->vif.active_links & BIT(i))
991 				ieee80211_link_sta_debugfs_drv_add(link_sta);
992 		}
993 	} else {
994 		ieee80211_link_sta_debugfs_add(&sta->deflink);
995 		ieee80211_link_sta_debugfs_drv_add(&sta->deflink);
996 	}
997 
998 	sinfo->generation = local->sta_generation;
999 	cfg80211_new_sta(&sdata->wdev, sta->sta.addr, sinfo, GFP_KERNEL);
1000 	kfree(sinfo);
1001 
1002 	sta_dbg(sdata, "Inserted STA %pM\n", sta->sta.addr);
1003 
1004 	/* move reference to rcu-protected */
1005 	rcu_read_lock();
1006 
1007 	if (ieee80211_vif_is_mesh(&sdata->vif))
1008 		mesh_accept_plinks_update(sdata);
1009 
1010 	ieee80211_check_fast_xmit(sta);
1011 
1012 	return 0;
1013  out_remove:
1014 	if (sta->sta.valid_links)
1015 		link_sta_info_hash_del(local, &sta->deflink);
1016 	sta_info_hash_del(local, sta);
1017 	list_del_rcu(&sta->list);
1018  out_drop_sta:
1019 	local->num_sta--;
1020 	synchronize_net();
1021  out_cleanup:
1022 	cleanup_single_sta(sta);
1023 	kfree(sinfo);
1024 	rcu_read_lock();
1025 	return err;
1026 }
1027 
1028 int sta_info_insert_rcu(struct sta_info *sta) __acquires(RCU)
1029 {
1030 	struct ieee80211_local *local = sta->local;
1031 	int err;
1032 
1033 	might_sleep();
1034 	lockdep_assert_wiphy(local->hw.wiphy);
1035 
1036 	err = sta_info_insert_check(sta);
1037 	if (err) {
1038 		sta_info_free(local, sta);
1039 		rcu_read_lock();
1040 		return err;
1041 	}
1042 
1043 	return sta_info_insert_finish(sta);
1044 }
1045 
1046 int sta_info_insert(struct sta_info *sta)
1047 {
1048 	int err = sta_info_insert_rcu(sta);
1049 
1050 	rcu_read_unlock();
1051 
1052 	return err;
1053 }
1054 
1055 static inline void __bss_tim_set(u8 *tim, u16 id)
1056 {
1057 	/*
1058 	 * This format has been mandated by the IEEE specifications,
1059 	 * so this line may not be changed to use the __set_bit() format.
1060 	 */
1061 	tim[id / 8] |= (1 << (id % 8));
1062 }
1063 
1064 static inline void __bss_tim_clear(u8 *tim, u16 id)
1065 {
1066 	/*
1067 	 * This format has been mandated by the IEEE specifications,
1068 	 * so this line may not be changed to use the __clear_bit() format.
1069 	 */
1070 	tim[id / 8] &= ~(1 << (id % 8));
1071 }
1072 
1073 static inline bool __bss_tim_get(u8 *tim, u16 id)
1074 {
1075 	/*
1076 	 * This format has been mandated by the IEEE specifications,
1077 	 * so this line may not be changed to use the test_bit() format.
1078 	 */
1079 	return tim[id / 8] & (1 << (id % 8));
1080 }
1081 
1082 static unsigned long ieee80211_tids_for_ac(int ac)
1083 {
1084 	/* If we ever support TIDs > 7, this obviously needs to be adjusted */
1085 	switch (ac) {
1086 	case IEEE80211_AC_VO:
1087 		return BIT(6) | BIT(7);
1088 	case IEEE80211_AC_VI:
1089 		return BIT(4) | BIT(5);
1090 	case IEEE80211_AC_BE:
1091 		return BIT(0) | BIT(3);
1092 	case IEEE80211_AC_BK:
1093 		return BIT(1) | BIT(2);
1094 	default:
1095 		WARN_ON(1);
1096 		return 0;
1097 	}
1098 }
1099 
1100 static void __sta_info_recalc_tim(struct sta_info *sta, bool ignore_pending)
1101 {
1102 	struct ieee80211_local *local = sta->local;
1103 	struct ps_data *ps;
1104 	bool indicate_tim = false;
1105 	u8 ignore_for_tim = sta->sta.uapsd_queues;
1106 	int ac;
1107 	u16 id = sta->sta.aid;
1108 
1109 	if (sta->sdata->vif.type == NL80211_IFTYPE_AP ||
1110 	    sta->sdata->vif.type == NL80211_IFTYPE_AP_VLAN) {
1111 		if (WARN_ON_ONCE(!sta->sdata->bss))
1112 			return;
1113 
1114 		ps = &sta->sdata->bss->ps;
1115 #ifdef CONFIG_MAC80211_MESH
1116 	} else if (ieee80211_vif_is_mesh(&sta->sdata->vif)) {
1117 		ps = &sta->sdata->u.mesh.ps;
1118 #endif
1119 	} else {
1120 		return;
1121 	}
1122 
1123 	/* No need to do anything if the driver does all */
1124 	if (ieee80211_hw_check(&local->hw, AP_LINK_PS) && !local->ops->set_tim)
1125 		return;
1126 
1127 	if (sta->dead)
1128 		goto done;
1129 
1130 	/*
1131 	 * If all ACs are delivery-enabled then we should build
1132 	 * the TIM bit for all ACs anyway; if only some are then
1133 	 * we ignore those and build the TIM bit using only the
1134 	 * non-enabled ones.
1135 	 */
1136 	if (ignore_for_tim == BIT(IEEE80211_NUM_ACS) - 1)
1137 		ignore_for_tim = 0;
1138 
1139 	if (ignore_pending)
1140 		ignore_for_tim = BIT(IEEE80211_NUM_ACS) - 1;
1141 
1142 	for (ac = 0; ac < IEEE80211_NUM_ACS; ac++) {
1143 		unsigned long tids;
1144 
1145 		if (ignore_for_tim & ieee80211_ac_to_qos_mask[ac])
1146 			continue;
1147 
1148 		indicate_tim |= !skb_queue_empty(&sta->tx_filtered[ac]) ||
1149 				!skb_queue_empty(&sta->ps_tx_buf[ac]);
1150 		if (indicate_tim)
1151 			break;
1152 
1153 		tids = ieee80211_tids_for_ac(ac);
1154 
1155 		indicate_tim |=
1156 			sta->driver_buffered_tids & tids;
1157 		indicate_tim |=
1158 			sta->txq_buffered_tids & tids;
1159 	}
1160 
1161  done:
1162 	spin_lock_bh(&local->tim_lock);
1163 
1164 	if (indicate_tim == __bss_tim_get(ps->tim, id))
1165 		goto out_unlock;
1166 
1167 	if (indicate_tim)
1168 		__bss_tim_set(ps->tim, id);
1169 	else
1170 		__bss_tim_clear(ps->tim, id);
1171 
1172 	if (local->ops->set_tim && !WARN_ON(sta->dead)) {
1173 		local->tim_in_locked_section = true;
1174 		drv_set_tim(local, &sta->sta, indicate_tim);
1175 		local->tim_in_locked_section = false;
1176 	}
1177 
1178 out_unlock:
1179 	spin_unlock_bh(&local->tim_lock);
1180 }
1181 
1182 void sta_info_recalc_tim(struct sta_info *sta)
1183 {
1184 	__sta_info_recalc_tim(sta, false);
1185 }
1186 
1187 static bool sta_info_buffer_expired(struct sta_info *sta, struct sk_buff *skb)
1188 {
1189 	struct ieee80211_tx_info *info;
1190 	int timeout;
1191 
1192 	if (!skb)
1193 		return false;
1194 
1195 	info = IEEE80211_SKB_CB(skb);
1196 
1197 	/* Timeout: (2 * listen_interval * beacon_int * 1024 / 1000000) sec */
1198 	timeout = (sta->listen_interval *
1199 		   sta->sdata->vif.bss_conf.beacon_int *
1200 		   32 / 15625) * HZ;
1201 	if (timeout < STA_TX_BUFFER_EXPIRE)
1202 		timeout = STA_TX_BUFFER_EXPIRE;
1203 	return time_after(jiffies, info->control.jiffies + timeout);
1204 }
1205 
1206 
1207 static bool sta_info_cleanup_expire_buffered_ac(struct ieee80211_local *local,
1208 						struct sta_info *sta, int ac)
1209 {
1210 	unsigned long flags;
1211 	struct sk_buff *skb;
1212 
1213 	/*
1214 	 * First check for frames that should expire on the filtered
1215 	 * queue. Frames here were rejected by the driver and are on
1216 	 * a separate queue to avoid reordering with normal PS-buffered
1217 	 * frames. They also aren't accounted for right now in the
1218 	 * total_ps_buffered counter.
1219 	 */
1220 	for (;;) {
1221 		spin_lock_irqsave(&sta->tx_filtered[ac].lock, flags);
1222 		skb = skb_peek(&sta->tx_filtered[ac]);
1223 		if (sta_info_buffer_expired(sta, skb))
1224 			skb = __skb_dequeue(&sta->tx_filtered[ac]);
1225 		else
1226 			skb = NULL;
1227 		spin_unlock_irqrestore(&sta->tx_filtered[ac].lock, flags);
1228 
1229 		/*
1230 		 * Frames are queued in order, so if this one
1231 		 * hasn't expired yet we can stop testing. If
1232 		 * we actually reached the end of the queue we
1233 		 * also need to stop, of course.
1234 		 */
1235 		if (!skb)
1236 			break;
1237 		ieee80211_free_txskb(&local->hw, skb);
1238 	}
1239 
1240 	/*
1241 	 * Now also check the normal PS-buffered queue, this will
1242 	 * only find something if the filtered queue was emptied
1243 	 * since the filtered frames are all before the normal PS
1244 	 * buffered frames.
1245 	 */
1246 	for (;;) {
1247 		spin_lock_irqsave(&sta->ps_tx_buf[ac].lock, flags);
1248 		skb = skb_peek(&sta->ps_tx_buf[ac]);
1249 		if (sta_info_buffer_expired(sta, skb))
1250 			skb = __skb_dequeue(&sta->ps_tx_buf[ac]);
1251 		else
1252 			skb = NULL;
1253 		spin_unlock_irqrestore(&sta->ps_tx_buf[ac].lock, flags);
1254 
1255 		/*
1256 		 * frames are queued in order, so if this one
1257 		 * hasn't expired yet (or we reached the end of
1258 		 * the queue) we can stop testing
1259 		 */
1260 		if (!skb)
1261 			break;
1262 
1263 		local->total_ps_buffered--;
1264 		ps_dbg(sta->sdata, "Buffered frame expired (STA %pM)\n",
1265 		       sta->sta.addr);
1266 		ieee80211_free_txskb(&local->hw, skb);
1267 	}
1268 
1269 	/*
1270 	 * Finally, recalculate the TIM bit for this station -- it might
1271 	 * now be clear because the station was too slow to retrieve its
1272 	 * frames.
1273 	 */
1274 	sta_info_recalc_tim(sta);
1275 
1276 	/*
1277 	 * Return whether there are any frames still buffered, this is
1278 	 * used to check whether the cleanup timer still needs to run,
1279 	 * if there are no frames we don't need to rearm the timer.
1280 	 */
1281 	return !(skb_queue_empty(&sta->ps_tx_buf[ac]) &&
1282 		 skb_queue_empty(&sta->tx_filtered[ac]));
1283 }
1284 
1285 static bool sta_info_cleanup_expire_buffered(struct ieee80211_local *local,
1286 					     struct sta_info *sta)
1287 {
1288 	bool have_buffered = false;
1289 	int ac;
1290 
1291 	/* This is only necessary for stations on BSS/MBSS interfaces */
1292 	if (!sta->sdata->bss &&
1293 	    !ieee80211_vif_is_mesh(&sta->sdata->vif))
1294 		return false;
1295 
1296 	for (ac = 0; ac < IEEE80211_NUM_ACS; ac++)
1297 		have_buffered |=
1298 			sta_info_cleanup_expire_buffered_ac(local, sta, ac);
1299 
1300 	return have_buffered;
1301 }
1302 
1303 static int __must_check __sta_info_destroy_part1(struct sta_info *sta)
1304 {
1305 	struct ieee80211_local *local;
1306 	struct ieee80211_sub_if_data *sdata;
1307 	int ret, i;
1308 
1309 	might_sleep();
1310 
1311 	if (!sta)
1312 		return -ENOENT;
1313 
1314 	local = sta->local;
1315 	sdata = sta->sdata;
1316 
1317 	lockdep_assert_wiphy(local->hw.wiphy);
1318 
1319 	if (sdata->vif.type == NL80211_IFTYPE_NAN) {
1320 		struct sta_info *sta_iter, *tmp;
1321 
1322 		/* Remove all NDI stations associated with this NMI STA */
1323 		list_for_each_entry_safe(sta_iter, tmp, &local->sta_list, list) {
1324 			if (rcu_access_pointer(sta_iter->sta.nmi) != &sta->sta)
1325 				continue;
1326 			sta_info_destroy_addr(sta_iter->sdata, sta_iter->addr);
1327 		}
1328 
1329 		/* Free and clear the local peer schedule */
1330 		ieee80211_nan_free_peer_sched(sta->sta.nan_sched);
1331 		sta->sta.nan_sched = NULL;
1332 	}
1333 
1334 	/*
1335 	 * Before removing the station from the driver and
1336 	 * rate control, it might still start new aggregation
1337 	 * sessions -- block that to make sure the tear-down
1338 	 * will be sufficient.
1339 	 */
1340 	set_sta_flag(sta, WLAN_STA_BLOCK_BA);
1341 	ieee80211_sta_tear_down_BA_sessions(sta, AGG_STOP_DESTROY_STA);
1342 
1343 	/*
1344 	 * Before removing the station from the driver there might be pending
1345 	 * rx frames on RSS queues sent prior to the disassociation - wait for
1346 	 * all such frames to be processed.
1347 	 */
1348 	drv_sync_rx_queues(local, sta);
1349 
1350 	for (i = 0; i < ARRAY_SIZE(sta->link); i++) {
1351 		struct link_sta_info *link_sta;
1352 
1353 		if (!(sta->sta.valid_links & BIT(i)))
1354 			continue;
1355 
1356 		link_sta = rcu_dereference_protected(sta->link[i],
1357 						     lockdep_is_held(&local->hw.wiphy->mtx));
1358 
1359 		link_sta_info_hash_del(local, link_sta);
1360 	}
1361 
1362 	ret = sta_info_hash_del(local, sta);
1363 	if (WARN_ON(ret))
1364 		return ret;
1365 
1366 	/*
1367 	 * for TDLS peers, make sure to return to the base channel before
1368 	 * removal.
1369 	 */
1370 	if (test_sta_flag(sta, WLAN_STA_TDLS_OFF_CHANNEL)) {
1371 		drv_tdls_cancel_channel_switch(local, sdata, &sta->sta);
1372 		clear_sta_flag(sta, WLAN_STA_TDLS_OFF_CHANNEL);
1373 	}
1374 
1375 	list_del_rcu(&sta->list);
1376 	sta->removed = true;
1377 
1378 	if (sta->uploaded)
1379 		drv_sta_pre_rcu_remove(local, sta->sdata, sta);
1380 
1381 	if (sdata->vif.type == NL80211_IFTYPE_AP_VLAN &&
1382 	    rcu_access_pointer(sdata->u.vlan.sta) == sta)
1383 		RCU_INIT_POINTER(sdata->u.vlan.sta, NULL);
1384 
1385 	return 0;
1386 }
1387 
1388 static int _sta_info_move_state(struct sta_info *sta,
1389 				enum ieee80211_sta_state new_state,
1390 				bool recalc)
1391 {
1392 	struct ieee80211_local *local = sta->local;
1393 
1394 	might_sleep();
1395 
1396 	if (sta->sta_state == new_state)
1397 		return 0;
1398 
1399 	/* check allowed transitions first */
1400 
1401 	switch (new_state) {
1402 	case IEEE80211_STA_NONE:
1403 		if (sta->sta_state != IEEE80211_STA_AUTH)
1404 			return -EINVAL;
1405 		break;
1406 	case IEEE80211_STA_AUTH:
1407 		if (sta->sta_state != IEEE80211_STA_NONE &&
1408 		    sta->sta_state != IEEE80211_STA_ASSOC)
1409 			return -EINVAL;
1410 		break;
1411 	case IEEE80211_STA_ASSOC:
1412 		if (sta->sta_state != IEEE80211_STA_AUTH &&
1413 		    sta->sta_state != IEEE80211_STA_AUTHORIZED)
1414 			return -EINVAL;
1415 		break;
1416 	case IEEE80211_STA_AUTHORIZED:
1417 		if (sta->sta_state != IEEE80211_STA_ASSOC)
1418 			return -EINVAL;
1419 		break;
1420 	default:
1421 		WARN(1, "invalid state %d", new_state);
1422 		return -EINVAL;
1423 	}
1424 
1425 	sta_dbg(sta->sdata, "moving STA %pM to state %d\n",
1426 		sta->sta.addr, new_state);
1427 
1428 	/* notify the driver before the actual changes so it can
1429 	 * fail the transition if the state is increasing.
1430 	 * The driver is required not to fail when the transition
1431 	 * is decreasing the state, so first, do all the preparation
1432 	 * work and only then, notify the driver.
1433 	 */
1434 	if (new_state > sta->sta_state &&
1435 	    test_sta_flag(sta, WLAN_STA_INSERTED)) {
1436 		int err = drv_sta_state(sta->local, sta->sdata, sta,
1437 					sta->sta_state, new_state);
1438 		if (err)
1439 			return err;
1440 	}
1441 
1442 	/* reflect the change in all state variables */
1443 
1444 	switch (new_state) {
1445 	case IEEE80211_STA_NONE:
1446 		if (sta->sta_state == IEEE80211_STA_AUTH)
1447 			clear_bit(WLAN_STA_AUTH, &sta->_flags);
1448 		break;
1449 	case IEEE80211_STA_AUTH:
1450 		if (sta->sta_state == IEEE80211_STA_NONE) {
1451 			set_bit(WLAN_STA_AUTH, &sta->_flags);
1452 		} else if (sta->sta_state == IEEE80211_STA_ASSOC) {
1453 			clear_bit(WLAN_STA_ASSOC, &sta->_flags);
1454 			if (recalc) {
1455 				ieee80211_recalc_min_chandef(sta->sdata, -1);
1456 				if (!sta->sta.support_p2p_ps)
1457 					ieee80211_recalc_p2p_go_ps_allowed(sta->sdata);
1458 			}
1459 		}
1460 		break;
1461 	case IEEE80211_STA_ASSOC:
1462 		if (sta->sta_state == IEEE80211_STA_AUTH) {
1463 			set_bit(WLAN_STA_ASSOC, &sta->_flags);
1464 			sta->assoc_at = ktime_get_boottime_ns();
1465 			if (recalc) {
1466 				ieee80211_recalc_min_chandef(sta->sdata, -1);
1467 				if (!sta->sta.support_p2p_ps)
1468 					ieee80211_recalc_p2p_go_ps_allowed(sta->sdata);
1469 			}
1470 		} else if (sta->sta_state == IEEE80211_STA_AUTHORIZED) {
1471 			ieee80211_vif_dec_num_mcast(sta->sdata);
1472 			clear_bit(WLAN_STA_AUTHORIZED, &sta->_flags);
1473 			if (sta->sdata->vif.type == NL80211_IFTYPE_NAN_DATA)
1474 				ieee80211_nan_update_ndi_carrier(sta->sdata);
1475 
1476 			/*
1477 			 * If we have encryption offload, flush (station) queues
1478 			 * (after ensuring concurrent TX completed) so we won't
1479 			 * transmit anything later unencrypted if/when keys are
1480 			 * also removed, which might otherwise happen depending
1481 			 * on how the hardware offload works.
1482 			 */
1483 			if (local->ops->set_key) {
1484 				synchronize_net();
1485 				if (local->ops->flush_sta)
1486 					drv_flush_sta(local, sta->sdata, sta);
1487 				else
1488 					ieee80211_flush_queues(local,
1489 							       sta->sdata,
1490 							       false);
1491 			}
1492 
1493 			ieee80211_clear_fast_xmit(sta);
1494 			ieee80211_clear_fast_rx(sta);
1495 		}
1496 		break;
1497 	case IEEE80211_STA_AUTHORIZED:
1498 		if (sta->sta_state == IEEE80211_STA_ASSOC) {
1499 			ieee80211_vif_inc_num_mcast(sta->sdata);
1500 			set_bit(WLAN_STA_AUTHORIZED, &sta->_flags);
1501 			ieee80211_check_fast_xmit(sta);
1502 			ieee80211_check_fast_rx(sta);
1503 			if (sta->sdata->vif.type == NL80211_IFTYPE_NAN_DATA)
1504 				ieee80211_nan_update_ndi_carrier(sta->sdata);
1505 		}
1506 		if (sta->sdata->vif.type == NL80211_IFTYPE_AP_VLAN ||
1507 		    sta->sdata->vif.type == NL80211_IFTYPE_AP)
1508 			cfg80211_send_layer2_update(sta->sdata->dev,
1509 						    sta->sta.addr);
1510 		break;
1511 	default:
1512 		break;
1513 	}
1514 
1515 	if (new_state < sta->sta_state &&
1516 	    test_sta_flag(sta, WLAN_STA_INSERTED)) {
1517 		int err = drv_sta_state(sta->local, sta->sdata, sta,
1518 					sta->sta_state, new_state);
1519 
1520 		WARN_ONCE(err,
1521 			  "Driver is not allowed to fail if the sta_state is transitioning down the list: %d\n",
1522 			  err);
1523 	}
1524 
1525 	sta->sta_state = new_state;
1526 
1527 	return 0;
1528 }
1529 
1530 int sta_info_move_state(struct sta_info *sta,
1531 			enum ieee80211_sta_state new_state)
1532 {
1533 	return _sta_info_move_state(sta, new_state, true);
1534 }
1535 
1536 static void __sta_info_destroy_part2(struct sta_info *sta, bool recalc)
1537 {
1538 	struct ieee80211_local *local = sta->local;
1539 	struct ieee80211_sub_if_data *sdata = sta->sdata;
1540 	struct station_info *sinfo;
1541 	int ret;
1542 
1543 	/*
1544 	 * NOTE: This assumes at least synchronize_net() was done
1545 	 *	 after _part1 and before _part2!
1546 	 */
1547 
1548 	/*
1549 	 * There's a potential race in _part1 where we set WLAN_STA_BLOCK_BA
1550 	 * but someone might have just gotten past a check, and not yet into
1551 	 * queuing the work/creating the data/etc.
1552 	 *
1553 	 * Do another round of destruction so that the worker is certainly
1554 	 * canceled before we later free the station.
1555 	 *
1556 	 * Since this is after synchronize_rcu()/synchronize_net() we're now
1557 	 * certain that nobody can actually hold a reference to the STA and
1558 	 * be calling e.g. ieee80211_start_tx_ba_session().
1559 	 */
1560 	ieee80211_sta_tear_down_BA_sessions(sta, AGG_STOP_DESTROY_STA);
1561 
1562 	might_sleep();
1563 	lockdep_assert_wiphy(local->hw.wiphy);
1564 
1565 	if (sta->sta_state == IEEE80211_STA_AUTHORIZED) {
1566 		ret = _sta_info_move_state(sta, IEEE80211_STA_ASSOC, recalc);
1567 		WARN_ON_ONCE(ret);
1568 	}
1569 
1570 	/* now keys can no longer be reached */
1571 	ieee80211_free_sta_keys(local, sta);
1572 
1573 	/* disable TIM bit - last chance to tell driver */
1574 	__sta_info_recalc_tim(sta, true);
1575 
1576 	sta->dead = true;
1577 
1578 	local->num_sta--;
1579 	local->sta_generation++;
1580 
1581 	while (sta->sta_state > IEEE80211_STA_NONE) {
1582 		ret = _sta_info_move_state(sta, sta->sta_state - 1, recalc);
1583 		if (ret) {
1584 			WARN_ON_ONCE(1);
1585 			break;
1586 		}
1587 	}
1588 
1589 	sinfo = kzalloc_obj(*sinfo);
1590 	if (sinfo)
1591 		sta_set_sinfo(sta, sinfo, true);
1592 
1593 	if (sta->uploaded) {
1594 		ret = drv_sta_state(local, sdata, sta, IEEE80211_STA_NONE,
1595 				    IEEE80211_STA_NOTEXIST);
1596 		WARN_ON_ONCE(ret != 0);
1597 	}
1598 
1599 	sta_dbg(sdata, "Removed STA %pM\n", sta->sta.addr);
1600 
1601 	cfg80211_del_sta_sinfo(&sdata->wdev, sta->sta.addr, sinfo, GFP_KERNEL);
1602 	kfree(sinfo);
1603 
1604 	ieee80211_sta_debugfs_remove(sta);
1605 
1606 	ieee80211_destroy_frag_cache(&sta->frags);
1607 
1608 	cleanup_single_sta(sta);
1609 }
1610 
1611 int __must_check __sta_info_destroy(struct sta_info *sta)
1612 {
1613 	int err = __sta_info_destroy_part1(sta);
1614 
1615 	if (err)
1616 		return err;
1617 
1618 	synchronize_net();
1619 
1620 	__sta_info_destroy_part2(sta, true);
1621 
1622 	return 0;
1623 }
1624 
1625 int sta_info_destroy_addr(struct ieee80211_sub_if_data *sdata, const u8 *addr)
1626 {
1627 	struct sta_info *sta;
1628 
1629 	lockdep_assert_wiphy(sdata->local->hw.wiphy);
1630 
1631 	sta = sta_info_get(sdata, addr);
1632 	return __sta_info_destroy(sta);
1633 }
1634 
1635 int sta_info_destroy_addr_bss(struct ieee80211_sub_if_data *sdata,
1636 			      const u8 *addr)
1637 {
1638 	struct sta_info *sta;
1639 
1640 	lockdep_assert_wiphy(sdata->local->hw.wiphy);
1641 
1642 	sta = sta_info_get_bss(sdata, addr);
1643 	return __sta_info_destroy(sta);
1644 }
1645 
1646 static void sta_info_cleanup(struct timer_list *t)
1647 {
1648 	struct ieee80211_local *local = timer_container_of(local, t,
1649 							   sta_cleanup);
1650 	struct sta_info *sta;
1651 	bool timer_needed = false;
1652 
1653 	rcu_read_lock();
1654 	list_for_each_entry_rcu(sta, &local->sta_list, list)
1655 		if (sta_info_cleanup_expire_buffered(local, sta))
1656 			timer_needed = true;
1657 	rcu_read_unlock();
1658 
1659 	if (local->quiescing)
1660 		return;
1661 
1662 	if (!timer_needed)
1663 		return;
1664 
1665 	mod_timer(&local->sta_cleanup,
1666 		  round_jiffies(jiffies + STA_INFO_CLEANUP_INTERVAL));
1667 }
1668 
1669 int sta_info_init(struct ieee80211_local *local)
1670 {
1671 	int err;
1672 
1673 	err = rhltable_init(&local->sta_hash, &sta_rht_params);
1674 	if (err)
1675 		return err;
1676 
1677 	err = rhltable_init(&local->link_sta_hash, &link_sta_rht_params);
1678 	if (err) {
1679 		rhltable_destroy(&local->sta_hash);
1680 		return err;
1681 	}
1682 
1683 	spin_lock_init(&local->tim_lock);
1684 	INIT_LIST_HEAD(&local->sta_list);
1685 
1686 	timer_setup(&local->sta_cleanup, sta_info_cleanup, 0);
1687 	return 0;
1688 }
1689 
1690 void sta_info_stop(struct ieee80211_local *local)
1691 {
1692 	timer_delete_sync(&local->sta_cleanup);
1693 	rhltable_destroy(&local->sta_hash);
1694 	rhltable_destroy(&local->link_sta_hash);
1695 }
1696 
1697 
1698 int __sta_info_flush(struct ieee80211_sub_if_data *sdata, bool vlans,
1699 		     int link_id, struct sta_info *do_not_flush_sta)
1700 {
1701 	struct ieee80211_local *local = sdata->local;
1702 	struct sta_info *sta, *tmp;
1703 	LIST_HEAD(free_list);
1704 	int ret = 0;
1705 
1706 	might_sleep();
1707 	lockdep_assert_wiphy(local->hw.wiphy);
1708 
1709 	WARN_ON(vlans && sdata->vif.type != NL80211_IFTYPE_AP);
1710 	WARN_ON(vlans && !sdata->bss);
1711 
1712 	list_for_each_entry_safe(sta, tmp, &local->sta_list, list) {
1713 		if (sdata != sta->sdata &&
1714 		    (!vlans || sdata->bss != sta->sdata->bss))
1715 			continue;
1716 
1717 		if (sta == do_not_flush_sta)
1718 			continue;
1719 
1720 		if (link_id >= 0 && sta->sta.valid_links &&
1721 		    !(sta->sta.valid_links & BIT(link_id)))
1722 			continue;
1723 
1724 		if (!WARN_ON(__sta_info_destroy_part1(sta)))
1725 			list_add(&sta->free_list, &free_list);
1726 
1727 		ret++;
1728 	}
1729 
1730 	if (!list_empty(&free_list)) {
1731 		bool support_p2p_ps = true;
1732 
1733 		synchronize_net();
1734 		list_for_each_entry_safe(sta, tmp, &free_list, free_list) {
1735 			if (!sta->sta.support_p2p_ps)
1736 				support_p2p_ps = false;
1737 			__sta_info_destroy_part2(sta, false);
1738 		}
1739 
1740 		ieee80211_recalc_min_chandef(sdata, -1);
1741 		if (!support_p2p_ps)
1742 			ieee80211_recalc_p2p_go_ps_allowed(sdata);
1743 	}
1744 
1745 	return ret;
1746 }
1747 
1748 void ieee80211_sta_expire(struct ieee80211_sub_if_data *sdata,
1749 			  unsigned long exp_time)
1750 {
1751 	struct ieee80211_local *local = sdata->local;
1752 	struct sta_info *sta, *tmp;
1753 
1754 	lockdep_assert_wiphy(local->hw.wiphy);
1755 
1756 	list_for_each_entry_safe(sta, tmp, &local->sta_list, list) {
1757 		unsigned long last_active = ieee80211_sta_last_active(sta, -1);
1758 
1759 		if (sdata != sta->sdata)
1760 			continue;
1761 
1762 		if (time_is_before_jiffies(last_active + exp_time)) {
1763 			sta_dbg(sta->sdata, "expiring inactive STA %pM\n",
1764 				sta->sta.addr);
1765 
1766 			if (ieee80211_vif_is_mesh(&sdata->vif) &&
1767 			    test_sta_flag(sta, WLAN_STA_PS_STA))
1768 				atomic_dec(&sdata->u.mesh.ps.num_sta_ps);
1769 
1770 			WARN_ON(__sta_info_destroy(sta));
1771 		}
1772 	}
1773 }
1774 
1775 struct ieee80211_sta *ieee80211_find_sta_by_ifaddr(struct ieee80211_hw *hw,
1776 						   const u8 *addr,
1777 						   const u8 *localaddr)
1778 {
1779 	struct ieee80211_local *local = hw_to_local(hw);
1780 	struct rhlist_head *tmp;
1781 	struct sta_info *sta;
1782 
1783 	/*
1784 	 * Just return a random station if localaddr is NULL
1785 	 * ... first in list.
1786 	 */
1787 	for_each_sta_info(local, addr, sta, tmp) {
1788 		if (localaddr &&
1789 		    !ether_addr_equal(sta->sdata->vif.addr, localaddr))
1790 			continue;
1791 		if (!sta->uploaded)
1792 			return NULL;
1793 		return &sta->sta;
1794 	}
1795 
1796 	return NULL;
1797 }
1798 EXPORT_SYMBOL_GPL(ieee80211_find_sta_by_ifaddr);
1799 
1800 struct ieee80211_sta *ieee80211_find_sta(struct ieee80211_vif *vif,
1801 					 const u8 *addr)
1802 {
1803 	struct sta_info *sta;
1804 
1805 	if (!vif)
1806 		return NULL;
1807 
1808 	sta = sta_info_get_bss(vif_to_sdata(vif), addr);
1809 	if (!sta)
1810 		return NULL;
1811 
1812 	if (!sta->uploaded)
1813 		return NULL;
1814 
1815 	return &sta->sta;
1816 }
1817 EXPORT_SYMBOL(ieee80211_find_sta);
1818 
1819 /* powersave support code */
1820 void ieee80211_sta_ps_deliver_wakeup(struct sta_info *sta)
1821 {
1822 	struct ieee80211_sub_if_data *sdata = sta->sdata;
1823 	struct ieee80211_local *local = sdata->local;
1824 	struct sk_buff_head pending;
1825 	int filtered = 0, buffered = 0, ac, i;
1826 	unsigned long flags;
1827 	struct ps_data *ps;
1828 
1829 	if (sdata->vif.type == NL80211_IFTYPE_AP_VLAN)
1830 		sdata = container_of(sdata->bss, struct ieee80211_sub_if_data,
1831 				     u.ap);
1832 
1833 	if (sdata->vif.type == NL80211_IFTYPE_AP)
1834 		ps = &sdata->bss->ps;
1835 	else if (ieee80211_vif_is_mesh(&sdata->vif))
1836 		ps = &sdata->u.mesh.ps;
1837 	else
1838 		return;
1839 
1840 	clear_sta_flag(sta, WLAN_STA_SP);
1841 
1842 	BUILD_BUG_ON(BITS_TO_LONGS(IEEE80211_NUM_TIDS) > 1);
1843 	sta->driver_buffered_tids = 0;
1844 	sta->txq_buffered_tids = 0;
1845 
1846 	if (!ieee80211_hw_check(&local->hw, AP_LINK_PS))
1847 		drv_sta_notify(local, sdata, STA_NOTIFY_AWAKE, &sta->sta);
1848 
1849 	for (i = 0; i < ARRAY_SIZE(sta->sta.txq); i++) {
1850 		if (!sta->sta.txq[i] || !txq_has_queue(sta->sta.txq[i]))
1851 			continue;
1852 
1853 		schedule_and_wake_txq(local, to_txq_info(sta->sta.txq[i]));
1854 	}
1855 
1856 	skb_queue_head_init(&pending);
1857 
1858 	/* sync with ieee80211_tx_h_unicast_ps_buf */
1859 	spin_lock_bh(&sta->ps_lock);
1860 	/* Send all buffered frames to the station */
1861 	for (ac = 0; ac < IEEE80211_NUM_ACS; ac++) {
1862 		int count = skb_queue_len(&pending), tmp;
1863 
1864 		spin_lock_irqsave(&sta->tx_filtered[ac].lock, flags);
1865 		skb_queue_splice_tail_init(&sta->tx_filtered[ac], &pending);
1866 		spin_unlock_irqrestore(&sta->tx_filtered[ac].lock, flags);
1867 		tmp = skb_queue_len(&pending);
1868 		filtered += tmp - count;
1869 		count = tmp;
1870 
1871 		spin_lock_irqsave(&sta->ps_tx_buf[ac].lock, flags);
1872 		skb_queue_splice_tail_init(&sta->ps_tx_buf[ac], &pending);
1873 		spin_unlock_irqrestore(&sta->ps_tx_buf[ac].lock, flags);
1874 		tmp = skb_queue_len(&pending);
1875 		buffered += tmp - count;
1876 	}
1877 
1878 	ieee80211_add_pending_skbs(local, &pending);
1879 
1880 	/* now we're no longer in the deliver code */
1881 	clear_sta_flag(sta, WLAN_STA_PS_DELIVER);
1882 
1883 	/* The station might have polled and then woken up before we responded,
1884 	 * so clear these flags now to avoid them sticking around.
1885 	 */
1886 	clear_sta_flag(sta, WLAN_STA_PSPOLL);
1887 	clear_sta_flag(sta, WLAN_STA_UAPSD);
1888 	spin_unlock_bh(&sta->ps_lock);
1889 
1890 	atomic_dec(&ps->num_sta_ps);
1891 
1892 	local->total_ps_buffered -= buffered;
1893 
1894 	sta_info_recalc_tim(sta);
1895 
1896 	ps_dbg(sdata,
1897 	       "STA %pM aid %d sending %d filtered/%d PS frames since STA woke up\n",
1898 	       sta->sta.addr, sta->sta.aid, filtered, buffered);
1899 
1900 	ieee80211_check_fast_xmit(sta);
1901 }
1902 
1903 static void ieee80211_send_null_response(struct sta_info *sta, int tid,
1904 					 enum ieee80211_frame_release_type reason,
1905 					 bool call_driver, bool more_data)
1906 {
1907 	struct ieee80211_sub_if_data *sdata = sta->sdata;
1908 	struct ieee80211_local *local = sdata->local;
1909 	struct ieee80211_qos_hdr *nullfunc;
1910 	struct sk_buff *skb;
1911 	int size = sizeof(*nullfunc);
1912 	__le16 fc;
1913 	bool qos = sta->sta.wme;
1914 	struct ieee80211_tx_info *info;
1915 	struct ieee80211_chanctx_conf *chanctx_conf;
1916 
1917 	if (qos) {
1918 		fc = cpu_to_le16(IEEE80211_FTYPE_DATA |
1919 				 IEEE80211_STYPE_QOS_NULLFUNC |
1920 				 IEEE80211_FCTL_FROMDS);
1921 	} else {
1922 		size -= 2;
1923 		fc = cpu_to_le16(IEEE80211_FTYPE_DATA |
1924 				 IEEE80211_STYPE_NULLFUNC |
1925 				 IEEE80211_FCTL_FROMDS);
1926 	}
1927 
1928 	skb = dev_alloc_skb(local->hw.extra_tx_headroom + size);
1929 	if (!skb)
1930 		return;
1931 
1932 	skb_reserve(skb, local->hw.extra_tx_headroom);
1933 
1934 	nullfunc = skb_put(skb, size);
1935 	nullfunc->frame_control = fc;
1936 	nullfunc->duration_id = 0;
1937 	memcpy(nullfunc->addr1, sta->sta.addr, ETH_ALEN);
1938 	memcpy(nullfunc->addr2, sdata->vif.addr, ETH_ALEN);
1939 	memcpy(nullfunc->addr3, sdata->vif.addr, ETH_ALEN);
1940 	nullfunc->seq_ctrl = 0;
1941 
1942 	skb->priority = tid;
1943 	skb_set_queue_mapping(skb, ieee802_1d_to_ac[tid]);
1944 	if (qos) {
1945 		nullfunc->qos_ctrl = cpu_to_le16(tid);
1946 
1947 		if (reason == IEEE80211_FRAME_RELEASE_UAPSD) {
1948 			nullfunc->qos_ctrl |=
1949 				cpu_to_le16(IEEE80211_QOS_CTL_EOSP);
1950 			if (more_data)
1951 				nullfunc->frame_control |=
1952 					cpu_to_le16(IEEE80211_FCTL_MOREDATA);
1953 		}
1954 	}
1955 
1956 	info = IEEE80211_SKB_CB(skb);
1957 
1958 	/*
1959 	 * Tell TX path to send this frame even though the
1960 	 * STA may still remain is PS mode after this frame
1961 	 * exchange. Also set EOSP to indicate this packet
1962 	 * ends the poll/service period.
1963 	 */
1964 	info->flags |= IEEE80211_TX_CTL_NO_PS_BUFFER |
1965 		       IEEE80211_TX_STATUS_EOSP |
1966 		       IEEE80211_TX_CTL_REQ_TX_STATUS;
1967 
1968 	info->control.flags |= IEEE80211_TX_CTRL_PS_RESPONSE;
1969 
1970 	if (call_driver)
1971 		drv_allow_buffered_frames(local, sta, BIT(tid), 1,
1972 					  reason, false);
1973 
1974 	skb->dev = sdata->dev;
1975 
1976 	rcu_read_lock();
1977 	chanctx_conf = rcu_dereference(sdata->vif.bss_conf.chanctx_conf);
1978 	if (WARN_ON(!chanctx_conf)) {
1979 		rcu_read_unlock();
1980 		kfree_skb(skb);
1981 		return;
1982 	}
1983 
1984 	info->band = chanctx_conf->def.chan->band;
1985 	ieee80211_xmit(sdata, sta, skb);
1986 	rcu_read_unlock();
1987 }
1988 
1989 static int find_highest_prio_tid(unsigned long tids)
1990 {
1991 	/* lower 3 TIDs aren't ordered perfectly */
1992 	if (tids & 0xF8)
1993 		return fls(tids) - 1;
1994 	/* TID 0 is BE just like TID 3 */
1995 	if (tids & BIT(0))
1996 		return 0;
1997 	return fls(tids) - 1;
1998 }
1999 
2000 /* Indicates if the MORE_DATA bit should be set in the last
2001  * frame obtained by ieee80211_sta_ps_get_frames.
2002  * Note that driver_release_tids is relevant only if
2003  * reason = IEEE80211_FRAME_RELEASE_PSPOLL
2004  */
2005 static bool
2006 ieee80211_sta_ps_more_data(struct sta_info *sta, u8 ignored_acs,
2007 			   enum ieee80211_frame_release_type reason,
2008 			   unsigned long driver_release_tids)
2009 {
2010 	int ac;
2011 
2012 	/* If the driver has data on more than one TID then
2013 	 * certainly there's more data if we release just a
2014 	 * single frame now (from a single TID). This will
2015 	 * only happen for PS-Poll.
2016 	 */
2017 	if (reason == IEEE80211_FRAME_RELEASE_PSPOLL &&
2018 	    hweight16(driver_release_tids) > 1)
2019 		return true;
2020 
2021 	for (ac = 0; ac < IEEE80211_NUM_ACS; ac++) {
2022 		if (ignored_acs & ieee80211_ac_to_qos_mask[ac])
2023 			continue;
2024 
2025 		if (!skb_queue_empty(&sta->tx_filtered[ac]) ||
2026 		    !skb_queue_empty(&sta->ps_tx_buf[ac]))
2027 			return true;
2028 	}
2029 
2030 	return false;
2031 }
2032 
2033 static void
2034 ieee80211_sta_ps_get_frames(struct sta_info *sta, int n_frames, u8 ignored_acs,
2035 			    enum ieee80211_frame_release_type reason,
2036 			    struct sk_buff_head *frames,
2037 			    unsigned long *driver_release_tids)
2038 {
2039 	struct ieee80211_sub_if_data *sdata = sta->sdata;
2040 	struct ieee80211_local *local = sdata->local;
2041 	int ac;
2042 
2043 	/* Get response frame(s) and more data bit for the last one. */
2044 	for (ac = 0; ac < IEEE80211_NUM_ACS; ac++) {
2045 		unsigned long tids;
2046 
2047 		if (ignored_acs & ieee80211_ac_to_qos_mask[ac])
2048 			continue;
2049 
2050 		tids = ieee80211_tids_for_ac(ac);
2051 
2052 		/* if we already have frames from software, then we can't also
2053 		 * release from hardware queues
2054 		 */
2055 		if (skb_queue_empty(frames)) {
2056 			*driver_release_tids |=
2057 				sta->driver_buffered_tids & tids;
2058 			*driver_release_tids |= sta->txq_buffered_tids & tids;
2059 		}
2060 
2061 		if (!*driver_release_tids) {
2062 			struct sk_buff *skb;
2063 
2064 			while (n_frames > 0) {
2065 				skb = skb_dequeue(&sta->tx_filtered[ac]);
2066 				if (!skb) {
2067 					skb = skb_dequeue(
2068 						&sta->ps_tx_buf[ac]);
2069 					if (skb)
2070 						local->total_ps_buffered--;
2071 				}
2072 				if (!skb)
2073 					break;
2074 				n_frames--;
2075 				__skb_queue_tail(frames, skb);
2076 			}
2077 		}
2078 
2079 		/* If we have more frames buffered on this AC, then abort the
2080 		 * loop since we can't send more data from other ACs before
2081 		 * the buffered frames from this.
2082 		 */
2083 		if (!skb_queue_empty(&sta->tx_filtered[ac]) ||
2084 		    !skb_queue_empty(&sta->ps_tx_buf[ac]))
2085 			break;
2086 	}
2087 }
2088 
2089 static void
2090 ieee80211_sta_ps_deliver_response(struct sta_info *sta,
2091 				  int n_frames, u8 ignored_acs,
2092 				  enum ieee80211_frame_release_type reason)
2093 {
2094 	struct ieee80211_sub_if_data *sdata = sta->sdata;
2095 	struct ieee80211_local *local = sdata->local;
2096 	unsigned long driver_release_tids = 0;
2097 	struct sk_buff_head frames;
2098 	bool more_data;
2099 
2100 	/* Service or PS-Poll period starts */
2101 	set_sta_flag(sta, WLAN_STA_SP);
2102 
2103 	__skb_queue_head_init(&frames);
2104 
2105 	ieee80211_sta_ps_get_frames(sta, n_frames, ignored_acs, reason,
2106 				    &frames, &driver_release_tids);
2107 
2108 	more_data = ieee80211_sta_ps_more_data(sta, ignored_acs, reason, driver_release_tids);
2109 
2110 	if (driver_release_tids && reason == IEEE80211_FRAME_RELEASE_PSPOLL)
2111 		driver_release_tids =
2112 			BIT(find_highest_prio_tid(driver_release_tids));
2113 
2114 	if (skb_queue_empty(&frames) && !driver_release_tids) {
2115 		int tid, ac;
2116 
2117 		/*
2118 		 * For PS-Poll, this can only happen due to a race condition
2119 		 * when we set the TIM bit and the station notices it, but
2120 		 * before it can poll for the frame we expire it.
2121 		 *
2122 		 * For uAPSD, this is said in the standard (11.2.1.5 h):
2123 		 *	At each unscheduled SP for a non-AP STA, the AP shall
2124 		 *	attempt to transmit at least one MSDU or MMPDU, but no
2125 		 *	more than the value specified in the Max SP Length field
2126 		 *	in the QoS Capability element from delivery-enabled ACs,
2127 		 *	that are destined for the non-AP STA.
2128 		 *
2129 		 * Since we have no other MSDU/MMPDU, transmit a QoS null frame.
2130 		 */
2131 
2132 		/* This will evaluate to 1, 3, 5 or 7. */
2133 		for (ac = IEEE80211_AC_VO; ac < IEEE80211_NUM_ACS; ac++)
2134 			if (!(ignored_acs & ieee80211_ac_to_qos_mask[ac]))
2135 				break;
2136 		tid = 7 - 2 * ac;
2137 
2138 		ieee80211_send_null_response(sta, tid, reason, true, false);
2139 	} else if (!driver_release_tids) {
2140 		struct sk_buff_head pending;
2141 		struct sk_buff *skb;
2142 		int num = 0;
2143 		u16 tids = 0;
2144 		bool need_null = false;
2145 
2146 		skb_queue_head_init(&pending);
2147 
2148 		while ((skb = __skb_dequeue(&frames))) {
2149 			struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
2150 			struct ieee80211_hdr *hdr = (void *) skb->data;
2151 			u8 *qoshdr = NULL;
2152 
2153 			num++;
2154 
2155 			/*
2156 			 * Tell TX path to send this frame even though the
2157 			 * STA may still remain is PS mode after this frame
2158 			 * exchange.
2159 			 */
2160 			info->flags |= IEEE80211_TX_CTL_NO_PS_BUFFER;
2161 			info->control.flags |= IEEE80211_TX_CTRL_PS_RESPONSE;
2162 
2163 			/*
2164 			 * Use MoreData flag to indicate whether there are
2165 			 * more buffered frames for this STA
2166 			 */
2167 			if (more_data || !skb_queue_empty(&frames))
2168 				hdr->frame_control |=
2169 					cpu_to_le16(IEEE80211_FCTL_MOREDATA);
2170 			else
2171 				hdr->frame_control &=
2172 					cpu_to_le16(~IEEE80211_FCTL_MOREDATA);
2173 
2174 			if (ieee80211_is_data_qos(hdr->frame_control) ||
2175 			    ieee80211_is_qos_nullfunc(hdr->frame_control))
2176 				qoshdr = ieee80211_get_qos_ctl(hdr);
2177 
2178 			tids |= BIT(skb->priority);
2179 
2180 			__skb_queue_tail(&pending, skb);
2181 
2182 			/* end service period after last frame or add one */
2183 			if (!skb_queue_empty(&frames))
2184 				continue;
2185 
2186 			if (reason != IEEE80211_FRAME_RELEASE_UAPSD) {
2187 				/* for PS-Poll, there's only one frame */
2188 				info->flags |= IEEE80211_TX_STATUS_EOSP |
2189 					       IEEE80211_TX_CTL_REQ_TX_STATUS;
2190 				break;
2191 			}
2192 
2193 			/* For uAPSD, things are a bit more complicated. If the
2194 			 * last frame has a QoS header (i.e. is a QoS-data or
2195 			 * QoS-nulldata frame) then just set the EOSP bit there
2196 			 * and be done.
2197 			 * If the frame doesn't have a QoS header (which means
2198 			 * it should be a bufferable MMPDU) then we can't set
2199 			 * the EOSP bit in the QoS header; add a QoS-nulldata
2200 			 * frame to the list to send it after the MMPDU.
2201 			 *
2202 			 * Note that this code is only in the mac80211-release
2203 			 * code path, we assume that the driver will not buffer
2204 			 * anything but QoS-data frames, or if it does, will
2205 			 * create the QoS-nulldata frame by itself if needed.
2206 			 *
2207 			 * Cf. 802.11-2012 10.2.1.10 (c).
2208 			 */
2209 			if (qoshdr) {
2210 				*qoshdr |= IEEE80211_QOS_CTL_EOSP;
2211 
2212 				info->flags |= IEEE80211_TX_STATUS_EOSP |
2213 					       IEEE80211_TX_CTL_REQ_TX_STATUS;
2214 			} else {
2215 				/* The standard isn't completely clear on this
2216 				 * as it says the more-data bit should be set
2217 				 * if there are more BUs. The QoS-Null frame
2218 				 * we're about to send isn't buffered yet, we
2219 				 * only create it below, but let's pretend it
2220 				 * was buffered just in case some clients only
2221 				 * expect more-data=0 when eosp=1.
2222 				 */
2223 				hdr->frame_control |=
2224 					cpu_to_le16(IEEE80211_FCTL_MOREDATA);
2225 				need_null = true;
2226 				num++;
2227 			}
2228 			break;
2229 		}
2230 
2231 		drv_allow_buffered_frames(local, sta, tids, num,
2232 					  reason, more_data);
2233 
2234 		ieee80211_add_pending_skbs(local, &pending);
2235 
2236 		if (need_null)
2237 			ieee80211_send_null_response(
2238 				sta, find_highest_prio_tid(tids),
2239 				reason, false, false);
2240 
2241 		sta_info_recalc_tim(sta);
2242 	} else {
2243 		int tid;
2244 
2245 		/*
2246 		 * We need to release a frame that is buffered somewhere in the
2247 		 * driver ... it'll have to handle that.
2248 		 * Note that the driver also has to check the number of frames
2249 		 * on the TIDs we're releasing from - if there are more than
2250 		 * n_frames it has to set the more-data bit (if we didn't ask
2251 		 * it to set it anyway due to other buffered frames); if there
2252 		 * are fewer than n_frames it has to make sure to adjust that
2253 		 * to allow the service period to end properly.
2254 		 */
2255 		drv_release_buffered_frames(local, sta, driver_release_tids,
2256 					    n_frames, reason, more_data);
2257 
2258 		/*
2259 		 * Note that we don't recalculate the TIM bit here as it would
2260 		 * most likely have no effect at all unless the driver told us
2261 		 * that the TID(s) became empty before returning here from the
2262 		 * release function.
2263 		 * Either way, however, when the driver tells us that the TID(s)
2264 		 * became empty or we find that a txq became empty, we'll do the
2265 		 * TIM recalculation.
2266 		 */
2267 
2268 		for (tid = 0; tid < ARRAY_SIZE(sta->sta.txq); tid++) {
2269 			if (!sta->sta.txq[tid] ||
2270 			    !(driver_release_tids & BIT(tid)) ||
2271 			    txq_has_queue(sta->sta.txq[tid]))
2272 				continue;
2273 
2274 			sta_info_recalc_tim(sta);
2275 			break;
2276 		}
2277 	}
2278 }
2279 
2280 void ieee80211_sta_ps_deliver_poll_response(struct sta_info *sta)
2281 {
2282 	u8 ignore_for_response = sta->sta.uapsd_queues;
2283 
2284 	/*
2285 	 * If all ACs are delivery-enabled then we should reply
2286 	 * from any of them, if only some are enabled we reply
2287 	 * only from the non-enabled ones.
2288 	 */
2289 	if (ignore_for_response == BIT(IEEE80211_NUM_ACS) - 1)
2290 		ignore_for_response = 0;
2291 
2292 	ieee80211_sta_ps_deliver_response(sta, 1, ignore_for_response,
2293 					  IEEE80211_FRAME_RELEASE_PSPOLL);
2294 }
2295 
2296 void ieee80211_sta_ps_deliver_uapsd(struct sta_info *sta)
2297 {
2298 	int n_frames = sta->sta.max_sp;
2299 	u8 delivery_enabled = sta->sta.uapsd_queues;
2300 
2301 	/*
2302 	 * If we ever grow support for TSPEC this might happen if
2303 	 * the TSPEC update from hostapd comes in between a trigger
2304 	 * frame setting WLAN_STA_UAPSD in the RX path and this
2305 	 * actually getting called.
2306 	 */
2307 	if (!delivery_enabled)
2308 		return;
2309 
2310 	switch (sta->sta.max_sp) {
2311 	case 1:
2312 		n_frames = 2;
2313 		break;
2314 	case 2:
2315 		n_frames = 4;
2316 		break;
2317 	case 3:
2318 		n_frames = 6;
2319 		break;
2320 	case 0:
2321 		/* XXX: what is a good value? */
2322 		n_frames = 128;
2323 		break;
2324 	}
2325 
2326 	ieee80211_sta_ps_deliver_response(sta, n_frames, ~delivery_enabled,
2327 					  IEEE80211_FRAME_RELEASE_UAPSD);
2328 }
2329 
2330 void ieee80211_sta_block_awake(struct ieee80211_hw *hw,
2331 			       struct ieee80211_sta *pubsta, bool block)
2332 {
2333 	struct sta_info *sta = container_of(pubsta, struct sta_info, sta);
2334 
2335 	trace_api_sta_block_awake(sta->local, pubsta, block);
2336 
2337 	if (block) {
2338 		set_sta_flag(sta, WLAN_STA_PS_DRIVER);
2339 		ieee80211_clear_fast_xmit(sta);
2340 		return;
2341 	}
2342 
2343 	if (!test_sta_flag(sta, WLAN_STA_PS_DRIVER))
2344 		return;
2345 
2346 	if (!test_sta_flag(sta, WLAN_STA_PS_STA)) {
2347 		set_sta_flag(sta, WLAN_STA_PS_DELIVER);
2348 		clear_sta_flag(sta, WLAN_STA_PS_DRIVER);
2349 		ieee80211_queue_work(hw, &sta->drv_deliver_wk);
2350 	} else if (test_sta_flag(sta, WLAN_STA_PSPOLL) ||
2351 		   test_sta_flag(sta, WLAN_STA_UAPSD)) {
2352 		/* must be asleep in this case */
2353 		clear_sta_flag(sta, WLAN_STA_PS_DRIVER);
2354 		ieee80211_queue_work(hw, &sta->drv_deliver_wk);
2355 	} else {
2356 		clear_sta_flag(sta, WLAN_STA_PS_DRIVER);
2357 		ieee80211_check_fast_xmit(sta);
2358 	}
2359 }
2360 EXPORT_SYMBOL(ieee80211_sta_block_awake);
2361 
2362 void ieee80211_sta_eosp(struct ieee80211_sta *pubsta)
2363 {
2364 	struct sta_info *sta = container_of(pubsta, struct sta_info, sta);
2365 	struct ieee80211_local *local = sta->local;
2366 
2367 	trace_api_eosp(local, pubsta);
2368 
2369 	clear_sta_flag(sta, WLAN_STA_SP);
2370 }
2371 EXPORT_SYMBOL(ieee80211_sta_eosp);
2372 
2373 void ieee80211_send_eosp_nullfunc(struct ieee80211_sta *pubsta, int tid)
2374 {
2375 	struct sta_info *sta = container_of(pubsta, struct sta_info, sta);
2376 	enum ieee80211_frame_release_type reason;
2377 	bool more_data;
2378 
2379 	trace_api_send_eosp_nullfunc(sta->local, pubsta, tid);
2380 
2381 	reason = IEEE80211_FRAME_RELEASE_UAPSD;
2382 	more_data = ieee80211_sta_ps_more_data(sta, ~sta->sta.uapsd_queues,
2383 					       reason, 0);
2384 
2385 	ieee80211_send_null_response(sta, tid, reason, false, more_data);
2386 }
2387 EXPORT_SYMBOL(ieee80211_send_eosp_nullfunc);
2388 
2389 void ieee80211_sta_set_buffered(struct ieee80211_sta *pubsta,
2390 				u8 tid, bool buffered)
2391 {
2392 	struct sta_info *sta = container_of(pubsta, struct sta_info, sta);
2393 
2394 	if (WARN_ON(tid >= IEEE80211_NUM_TIDS))
2395 		return;
2396 
2397 	trace_api_sta_set_buffered(sta->local, pubsta, tid, buffered);
2398 
2399 	if (buffered)
2400 		set_bit(tid, &sta->driver_buffered_tids);
2401 	else
2402 		clear_bit(tid, &sta->driver_buffered_tids);
2403 
2404 	sta_info_recalc_tim(sta);
2405 }
2406 EXPORT_SYMBOL(ieee80211_sta_set_buffered);
2407 
2408 void ieee80211_sta_register_airtime(struct ieee80211_sta *pubsta, u8 tid,
2409 				    u32 tx_airtime, u32 rx_airtime)
2410 {
2411 	struct sta_info *sta = container_of(pubsta, struct sta_info, sta);
2412 	struct ieee80211_local *local = sta->sdata->local;
2413 	u8 ac = ieee80211_ac_from_tid(tid);
2414 	u32 airtime = 0;
2415 
2416 	if (sta->local->airtime_flags & AIRTIME_USE_TX)
2417 		airtime += tx_airtime;
2418 	if (sta->local->airtime_flags & AIRTIME_USE_RX)
2419 		airtime += rx_airtime;
2420 
2421 	spin_lock_bh(&local->active_txq_lock[ac]);
2422 	sta->airtime[ac].tx_airtime += tx_airtime;
2423 	sta->airtime[ac].rx_airtime += rx_airtime;
2424 
2425 	if (ieee80211_sta_keep_active(sta, ac))
2426 		sta->airtime[ac].deficit -= airtime;
2427 
2428 	spin_unlock_bh(&local->active_txq_lock[ac]);
2429 }
2430 EXPORT_SYMBOL(ieee80211_sta_register_airtime);
2431 
2432 void __ieee80211_sta_recalc_aggregates(struct sta_info *sta, u16 active_links)
2433 {
2434 	bool first = true;
2435 	int link_id;
2436 
2437 	if (!sta->sta.valid_links || !sta->sta.mlo) {
2438 		sta->sta.cur = &sta->sta.deflink.agg;
2439 		return;
2440 	}
2441 
2442 	rcu_read_lock();
2443 	for (link_id = 0; link_id < ARRAY_SIZE((sta)->link); link_id++) {
2444 		struct ieee80211_link_sta *link_sta;
2445 		int i;
2446 
2447 		if (!(active_links & BIT(link_id)))
2448 			continue;
2449 
2450 		link_sta = rcu_dereference(sta->sta.link[link_id]);
2451 		if (!link_sta)
2452 			continue;
2453 
2454 		if (first) {
2455 			sta->cur = sta->sta.deflink.agg;
2456 			first = false;
2457 			continue;
2458 		}
2459 
2460 		sta->cur.max_amsdu_len =
2461 			min(sta->cur.max_amsdu_len,
2462 			    link_sta->agg.max_amsdu_len);
2463 		sta->cur.max_rc_amsdu_len =
2464 			min(sta->cur.max_rc_amsdu_len,
2465 			    link_sta->agg.max_rc_amsdu_len);
2466 
2467 		for (i = 0; i < ARRAY_SIZE(sta->cur.max_tid_amsdu_len); i++)
2468 			sta->cur.max_tid_amsdu_len[i] =
2469 				min(sta->cur.max_tid_amsdu_len[i],
2470 				    link_sta->agg.max_tid_amsdu_len[i]);
2471 	}
2472 	rcu_read_unlock();
2473 
2474 	sta->sta.cur = &sta->cur;
2475 }
2476 
2477 void ieee80211_sta_recalc_aggregates(struct ieee80211_sta *pubsta)
2478 {
2479 	struct sta_info *sta = container_of(pubsta, struct sta_info, sta);
2480 
2481 	__ieee80211_sta_recalc_aggregates(sta, sta->sdata->vif.active_links);
2482 }
2483 EXPORT_SYMBOL(ieee80211_sta_recalc_aggregates);
2484 
2485 void ieee80211_sta_update_pending_airtime(struct ieee80211_local *local,
2486 					  struct sta_info *sta, u8 ac,
2487 					  u16 tx_airtime, bool tx_completed)
2488 {
2489 	int tx_pending;
2490 
2491 	if (!wiphy_ext_feature_isset(local->hw.wiphy, NL80211_EXT_FEATURE_AQL))
2492 		return;
2493 
2494 	if (!tx_completed) {
2495 		if (sta)
2496 			atomic_add(tx_airtime,
2497 				   &sta->airtime[ac].aql_tx_pending);
2498 
2499 		atomic_add(tx_airtime, &local->aql_total_pending_airtime);
2500 		atomic_add(tx_airtime, &local->aql_ac_pending_airtime[ac]);
2501 		return;
2502 	}
2503 
2504 	if (sta) {
2505 		tx_pending = atomic_sub_return(tx_airtime,
2506 					       &sta->airtime[ac].aql_tx_pending);
2507 		if (tx_pending < 0)
2508 			atomic_cmpxchg(&sta->airtime[ac].aql_tx_pending,
2509 				       tx_pending, 0);
2510 	}
2511 
2512 	atomic_sub(tx_airtime, &local->aql_total_pending_airtime);
2513 	tx_pending = atomic_sub_return(tx_airtime,
2514 				       &local->aql_ac_pending_airtime[ac]);
2515 	if (WARN_ONCE(tx_pending < 0,
2516 		      "Device %s AC %d pending airtime underflow: %u, %u",
2517 		      wiphy_name(local->hw.wiphy), ac, tx_pending,
2518 		      tx_airtime)) {
2519 		atomic_cmpxchg(&local->aql_ac_pending_airtime[ac],
2520 			       tx_pending, 0);
2521 		atomic_sub(tx_pending, &local->aql_total_pending_airtime);
2522 	}
2523 }
2524 
2525 static struct ieee80211_sta_rx_stats *
2526 sta_get_last_rx_stats(struct sta_info *sta, int link_id)
2527 {
2528 	struct ieee80211_sta_rx_stats *stats;
2529 	struct link_sta_info *link_sta_info;
2530 	int cpu;
2531 
2532 	if (link_id < 0)
2533 		link_sta_info = &sta->deflink;
2534 	else
2535 		link_sta_info = wiphy_dereference(sta->local->hw.wiphy,
2536 						  sta->link[link_id]);
2537 
2538 	stats = &link_sta_info->rx_stats;
2539 
2540 	if (!link_sta_info->pcpu_rx_stats)
2541 		return stats;
2542 
2543 	for_each_possible_cpu(cpu) {
2544 		struct ieee80211_sta_rx_stats *cpustats;
2545 
2546 		cpustats = per_cpu_ptr(link_sta_info->pcpu_rx_stats, cpu);
2547 
2548 		if (time_after(cpustats->last_rx, stats->last_rx))
2549 			stats = cpustats;
2550 	}
2551 
2552 	return stats;
2553 }
2554 
2555 static void sta_stats_decode_rate(struct ieee80211_local *local, u32 rate,
2556 				  struct rate_info *rinfo)
2557 {
2558 	rinfo->bw = STA_STATS_GET(BW, rate);
2559 
2560 	switch (STA_STATS_GET(TYPE, rate)) {
2561 	case STA_STATS_RATE_TYPE_VHT:
2562 		rinfo->flags = RATE_INFO_FLAGS_VHT_MCS;
2563 		rinfo->mcs = STA_STATS_GET(VHT_MCS, rate);
2564 		rinfo->nss = STA_STATS_GET(VHT_NSS, rate);
2565 		if (STA_STATS_GET(SGI, rate))
2566 			rinfo->flags |= RATE_INFO_FLAGS_SHORT_GI;
2567 		break;
2568 	case STA_STATS_RATE_TYPE_HT:
2569 		rinfo->flags = RATE_INFO_FLAGS_MCS;
2570 		rinfo->mcs = STA_STATS_GET(HT_MCS, rate);
2571 		if (STA_STATS_GET(SGI, rate))
2572 			rinfo->flags |= RATE_INFO_FLAGS_SHORT_GI;
2573 		break;
2574 	case STA_STATS_RATE_TYPE_LEGACY: {
2575 		struct ieee80211_supported_band *sband;
2576 		u16 brate;
2577 		unsigned int shift;
2578 		int band = STA_STATS_GET(LEGACY_BAND, rate);
2579 		int rate_idx = STA_STATS_GET(LEGACY_IDX, rate);
2580 
2581 		sband = local->hw.wiphy->bands[band];
2582 
2583 		if (WARN_ON_ONCE(!sband->bitrates))
2584 			break;
2585 
2586 		brate = sband->bitrates[rate_idx].bitrate;
2587 		if (rinfo->bw == RATE_INFO_BW_5)
2588 			shift = 2;
2589 		else if (rinfo->bw == RATE_INFO_BW_10)
2590 			shift = 1;
2591 		else
2592 			shift = 0;
2593 		rinfo->legacy = DIV_ROUND_UP(brate, 1 << shift);
2594 		break;
2595 		}
2596 	case STA_STATS_RATE_TYPE_HE:
2597 		rinfo->flags = RATE_INFO_FLAGS_HE_MCS;
2598 		rinfo->mcs = STA_STATS_GET(HE_MCS, rate);
2599 		rinfo->nss = STA_STATS_GET(HE_NSS, rate);
2600 		rinfo->he_gi = STA_STATS_GET(HE_GI, rate);
2601 		rinfo->he_ru_alloc = STA_STATS_GET(HE_RU, rate);
2602 		rinfo->he_dcm = STA_STATS_GET(HE_DCM, rate);
2603 		break;
2604 	case STA_STATS_RATE_TYPE_EHT:
2605 		rinfo->flags = RATE_INFO_FLAGS_EHT_MCS;
2606 		rinfo->mcs = STA_STATS_GET(EHT_MCS, rate);
2607 		rinfo->nss = STA_STATS_GET(EHT_NSS, rate);
2608 		rinfo->eht_gi = STA_STATS_GET(EHT_GI, rate);
2609 		rinfo->eht_ru_alloc = STA_STATS_GET(EHT_RU, rate);
2610 		break;
2611 	case STA_STATS_RATE_TYPE_UHR:
2612 		rinfo->flags = RATE_INFO_FLAGS_UHR_MCS;
2613 		rinfo->mcs = STA_STATS_GET(UHR_MCS, rate);
2614 		rinfo->nss = STA_STATS_GET(UHR_NSS, rate);
2615 		rinfo->eht_gi = STA_STATS_GET(UHR_GI, rate);
2616 		rinfo->eht_ru_alloc = STA_STATS_GET(UHR_RU, rate);
2617 		if (STA_STATS_GET(UHR_ELR, rate))
2618 			rinfo->flags |= RATE_INFO_FLAGS_UHR_ELR_MCS;
2619 		if (STA_STATS_GET(UHR_IM, rate))
2620 			rinfo->flags |= RATE_INFO_FLAGS_UHR_IM;
2621 		break;
2622 	case STA_STATS_RATE_TYPE_S1G:
2623 		rinfo->flags = RATE_INFO_FLAGS_S1G_MCS;
2624 		rinfo->mcs = STA_STATS_GET(S1G_MCS, rate);
2625 		rinfo->nss = STA_STATS_GET(S1G_NSS, rate);
2626 		if (STA_STATS_GET(SGI, rate))
2627 			rinfo->flags |= RATE_INFO_FLAGS_SHORT_GI;
2628 		break;
2629 	}
2630 }
2631 
2632 static int sta_set_rate_info_rx(struct sta_info *sta, struct rate_info *rinfo,
2633 				int link_id)
2634 {
2635 	u32 rate = READ_ONCE(sta_get_last_rx_stats(sta, link_id)->last_rate);
2636 
2637 	if (rate == STA_STATS_RATE_INVALID)
2638 		return -EINVAL;
2639 
2640 	sta_stats_decode_rate(sta->local, rate, rinfo);
2641 	return 0;
2642 }
2643 
2644 static inline u64 sta_get_tidstats_msdu(struct ieee80211_sta_rx_stats *rxstats,
2645 					int tid)
2646 {
2647 	unsigned int start;
2648 	u64 value;
2649 
2650 	do {
2651 		start = u64_stats_fetch_begin(&rxstats->syncp);
2652 		value = u64_stats_read(&rxstats->msdu[tid]);
2653 	} while (u64_stats_fetch_retry(&rxstats->syncp, start));
2654 
2655 	return value;
2656 }
2657 
2658 static void sta_set_tidstats(struct sta_info *sta,
2659 			     struct cfg80211_tid_stats *tidstats,
2660 			     int tid, int link_id)
2661 {
2662 	struct ieee80211_local *local = sta->local;
2663 	struct link_sta_info *link_sta_info;
2664 	int cpu;
2665 
2666 	if (link_id < 0)
2667 		link_sta_info = &sta->deflink;
2668 	else
2669 		link_sta_info = wiphy_dereference(sta->local->hw.wiphy,
2670 						  sta->link[link_id]);
2671 
2672 	if (!(tidstats->filled & BIT(NL80211_TID_STATS_RX_MSDU))) {
2673 		tidstats->rx_msdu +=
2674 			sta_get_tidstats_msdu(&link_sta_info->rx_stats,
2675 					      tid);
2676 
2677 		if (link_sta_info->pcpu_rx_stats) {
2678 			for_each_possible_cpu(cpu) {
2679 				struct ieee80211_sta_rx_stats *cpurxs;
2680 
2681 				cpurxs = per_cpu_ptr(link_sta_info->pcpu_rx_stats,
2682 						     cpu);
2683 				tidstats->rx_msdu +=
2684 					sta_get_tidstats_msdu(cpurxs, tid);
2685 			}
2686 		}
2687 
2688 		tidstats->filled |= BIT(NL80211_TID_STATS_RX_MSDU);
2689 	}
2690 
2691 	if (!(tidstats->filled & BIT(NL80211_TID_STATS_TX_MSDU))) {
2692 		tidstats->filled |= BIT(NL80211_TID_STATS_TX_MSDU);
2693 		tidstats->tx_msdu = link_sta_info->tx_stats.msdu[tid];
2694 	}
2695 
2696 	if (!(tidstats->filled & BIT(NL80211_TID_STATS_TX_MSDU_RETRIES)) &&
2697 	    ieee80211_hw_check(&local->hw, REPORTS_TX_ACK_STATUS)) {
2698 		tidstats->filled |= BIT(NL80211_TID_STATS_TX_MSDU_RETRIES);
2699 		tidstats->tx_msdu_retries =
2700 			link_sta_info->status_stats.msdu_retries[tid];
2701 	}
2702 
2703 	if (!(tidstats->filled & BIT(NL80211_TID_STATS_TX_MSDU_FAILED)) &&
2704 	    ieee80211_hw_check(&local->hw, REPORTS_TX_ACK_STATUS)) {
2705 		tidstats->filled |= BIT(NL80211_TID_STATS_TX_MSDU_FAILED);
2706 		tidstats->tx_msdu_failed =
2707 			link_sta_info->status_stats.msdu_failed[tid];
2708 	}
2709 
2710 	if (link_id < 0 && tid < IEEE80211_NUM_TIDS) {
2711 		spin_lock_bh(&local->fq.lock);
2712 
2713 		tidstats->filled |= BIT(NL80211_TID_STATS_TXQ_STATS);
2714 		ieee80211_fill_txq_stats(&tidstats->txq_stats,
2715 					 to_txq_info(sta->sta.txq[tid]));
2716 
2717 		spin_unlock_bh(&local->fq.lock);
2718 	}
2719 }
2720 
2721 static inline u64 sta_get_stats_bytes(struct ieee80211_sta_rx_stats *rxstats)
2722 {
2723 	unsigned int start;
2724 	u64 value;
2725 
2726 	do {
2727 		start = u64_stats_fetch_begin(&rxstats->syncp);
2728 		value = u64_stats_read(&rxstats->bytes);
2729 	} while (u64_stats_fetch_retry(&rxstats->syncp, start));
2730 
2731 	return value;
2732 }
2733 
2734 #ifdef CONFIG_MAC80211_MESH
2735 static void sta_set_mesh_sinfo(struct sta_info *sta,
2736 			       struct station_info *sinfo)
2737 {
2738 	struct ieee80211_local *local = sta->sdata->local;
2739 
2740 	sinfo->filled |= BIT_ULL(NL80211_STA_INFO_LLID) |
2741 			 BIT_ULL(NL80211_STA_INFO_PLID) |
2742 			 BIT_ULL(NL80211_STA_INFO_PLINK_STATE) |
2743 			 BIT_ULL(NL80211_STA_INFO_LOCAL_PM) |
2744 			 BIT_ULL(NL80211_STA_INFO_PEER_PM) |
2745 			 BIT_ULL(NL80211_STA_INFO_NONPEER_PM) |
2746 			 BIT_ULL(NL80211_STA_INFO_CONNECTED_TO_GATE) |
2747 			 BIT_ULL(NL80211_STA_INFO_CONNECTED_TO_AS);
2748 
2749 	sinfo->llid = sta->mesh->llid;
2750 	sinfo->plid = sta->mesh->plid;
2751 	sinfo->plink_state = sta->mesh->plink_state;
2752 	if (test_sta_flag(sta, WLAN_STA_TOFFSET_KNOWN)) {
2753 		sinfo->filled |= BIT_ULL(NL80211_STA_INFO_T_OFFSET);
2754 		sinfo->t_offset = sta->mesh->t_offset;
2755 	}
2756 	sinfo->local_pm = sta->mesh->local_pm;
2757 	sinfo->peer_pm = sta->mesh->peer_pm;
2758 	sinfo->nonpeer_pm = sta->mesh->nonpeer_pm;
2759 	sinfo->connected_to_gate = sta->mesh->connected_to_gate;
2760 	sinfo->connected_to_as = sta->mesh->connected_to_as;
2761 
2762 	sinfo->filled |= BIT_ULL(NL80211_STA_INFO_AIRTIME_LINK_METRIC);
2763 	sinfo->airtime_link_metric = airtime_link_metric_get(local, sta);
2764 }
2765 #endif
2766 
2767 void sta_set_accumulated_removed_links_sinfo(struct sta_info *sta,
2768 					     struct station_info *sinfo)
2769 {
2770 	/* Accumulating the removed link statistics. */
2771 	sinfo->tx_packets = sta->rem_link_stats.tx_packets;
2772 	sinfo->rx_packets = sta->rem_link_stats.rx_packets;
2773 	sinfo->tx_bytes = sta->rem_link_stats.tx_bytes;
2774 	sinfo->rx_bytes = sta->rem_link_stats.rx_bytes;
2775 	sinfo->tx_retries = sta->rem_link_stats.tx_retries;
2776 	sinfo->tx_failed = sta->rem_link_stats.tx_failed;
2777 	sinfo->rx_dropped_misc = sta->rem_link_stats.rx_dropped_misc;
2778 	sinfo->beacon_loss_count = sta->rem_link_stats.beacon_loss_count;
2779 	sinfo->expected_throughput = sta->rem_link_stats.expected_throughput;
2780 
2781 	if (sinfo->pertid) {
2782 		sinfo->pertid->rx_msdu =
2783 			sta->rem_link_stats.pertid_stats.rx_msdu;
2784 		sinfo->pertid->tx_msdu =
2785 			sta->rem_link_stats.pertid_stats.tx_msdu;
2786 		sinfo->pertid->tx_msdu_retries =
2787 			sta->rem_link_stats.pertid_stats.tx_msdu_retries;
2788 		sinfo->pertid->tx_msdu_failed =
2789 			sta->rem_link_stats.pertid_stats.tx_msdu_failed;
2790 	}
2791 }
2792 
2793 static void sta_set_link_sinfo(struct sta_info *sta,
2794 			       struct link_station_info *link_sinfo,
2795 			       struct ieee80211_link_data *link,
2796 			       bool tidstats)
2797 {
2798 	struct ieee80211_sub_if_data *sdata = sta->sdata;
2799 	struct ieee80211_sta_rx_stats *last_rxstats;
2800 	int i, ac, cpu, link_id = link->link_id;
2801 	struct link_sta_info *link_sta_info;
2802 	u32 thr = 0;
2803 
2804 	last_rxstats = sta_get_last_rx_stats(sta, link_id);
2805 
2806 	link_sta_info = wiphy_dereference(sta->local->hw.wiphy,
2807 					  sta->link[link_id]);
2808 
2809 	/* do before driver, so beacon filtering drivers have a
2810 	 * chance to e.g. just add the number of filtered beacons
2811 	 * (or just modify the value entirely, of course)
2812 	 */
2813 	if (sdata->vif.type == NL80211_IFTYPE_STATION)
2814 		link_sinfo->rx_beacon = link->u.mgd.count_beacon_signal;
2815 
2816 	ether_addr_copy(link_sinfo->addr, link_sta_info->addr);
2817 
2818 	drv_link_sta_statistics(sta->local, sdata,
2819 				link_sta_info->pub,
2820 				link_sinfo);
2821 
2822 	link_sinfo->filled |= BIT_ULL(NL80211_STA_INFO_INACTIVE_TIME) |
2823 			 BIT_ULL(NL80211_STA_INFO_BSS_PARAM) |
2824 			 BIT_ULL(NL80211_STA_INFO_RX_DROP_MISC);
2825 
2826 	if (sdata->vif.type == NL80211_IFTYPE_STATION) {
2827 		link_sinfo->beacon_loss_count =
2828 			link->u.mgd.beacon_loss_count;
2829 		link_sinfo->filled |= BIT_ULL(NL80211_STA_INFO_BEACON_LOSS);
2830 	}
2831 
2832 	link_sinfo->inactive_time =
2833 		jiffies_delta_to_msecs(jiffies -
2834 				       ieee80211_sta_last_active(sta,
2835 								 link_id));
2836 
2837 	if (!(link_sinfo->filled & (BIT_ULL(NL80211_STA_INFO_TX_BYTES64) |
2838 				    BIT_ULL(NL80211_STA_INFO_TX_BYTES)))) {
2839 		link_sinfo->tx_bytes = 0;
2840 		for (ac = 0; ac < IEEE80211_NUM_ACS; ac++)
2841 			link_sinfo->tx_bytes +=
2842 				link_sta_info->tx_stats.bytes[ac];
2843 		link_sinfo->filled |= BIT_ULL(NL80211_STA_INFO_TX_BYTES64);
2844 	}
2845 
2846 	if (!(link_sinfo->filled & BIT_ULL(NL80211_STA_INFO_TX_PACKETS))) {
2847 		link_sinfo->tx_packets = 0;
2848 		for (ac = 0; ac < IEEE80211_NUM_ACS; ac++)
2849 			link_sinfo->tx_packets +=
2850 				link_sta_info->tx_stats.packets[ac];
2851 		link_sinfo->filled |= BIT_ULL(NL80211_STA_INFO_TX_PACKETS);
2852 	}
2853 
2854 	if (!(link_sinfo->filled & (BIT_ULL(NL80211_STA_INFO_RX_BYTES64) |
2855 			       BIT_ULL(NL80211_STA_INFO_RX_BYTES)))) {
2856 		link_sinfo->rx_bytes +=
2857 			sta_get_stats_bytes(&link_sta_info->rx_stats);
2858 
2859 		if (link_sta_info->pcpu_rx_stats) {
2860 			for_each_possible_cpu(cpu) {
2861 				struct ieee80211_sta_rx_stats *cpurxs;
2862 
2863 				cpurxs = per_cpu_ptr(link_sta_info->pcpu_rx_stats,
2864 						     cpu);
2865 				link_sinfo->rx_bytes +=
2866 					sta_get_stats_bytes(cpurxs);
2867 			}
2868 		}
2869 
2870 		link_sinfo->filled |= BIT_ULL(NL80211_STA_INFO_RX_BYTES64);
2871 	}
2872 
2873 	if (!(link_sinfo->filled & BIT_ULL(NL80211_STA_INFO_RX_PACKETS))) {
2874 		link_sinfo->rx_packets = link_sta_info->rx_stats.packets;
2875 		if (link_sta_info->pcpu_rx_stats) {
2876 			for_each_possible_cpu(cpu) {
2877 				struct ieee80211_sta_rx_stats *cpurxs;
2878 
2879 				cpurxs = per_cpu_ptr(link_sta_info->pcpu_rx_stats,
2880 						     cpu);
2881 				link_sinfo->rx_packets += cpurxs->packets;
2882 			}
2883 		}
2884 		link_sinfo->filled |= BIT_ULL(NL80211_STA_INFO_RX_PACKETS);
2885 	}
2886 
2887 	if (!(link_sinfo->filled & BIT_ULL(NL80211_STA_INFO_TX_RETRIES))) {
2888 		link_sinfo->tx_retries =
2889 			link_sta_info->status_stats.retry_count;
2890 		link_sinfo->filled |= BIT_ULL(NL80211_STA_INFO_TX_RETRIES);
2891 	}
2892 
2893 	if (!(link_sinfo->filled & BIT_ULL(NL80211_STA_INFO_TX_FAILED))) {
2894 		link_sinfo->tx_failed =
2895 			link_sta_info->status_stats.retry_failed;
2896 		link_sinfo->filled |= BIT_ULL(NL80211_STA_INFO_TX_FAILED);
2897 	}
2898 
2899 	if (!(link_sinfo->filled & BIT_ULL(NL80211_STA_INFO_RX_DURATION))) {
2900 		for (ac = 0; ac < IEEE80211_NUM_ACS; ac++)
2901 			link_sinfo->rx_duration += sta->airtime[ac].rx_airtime;
2902 		link_sinfo->filled |= BIT_ULL(NL80211_STA_INFO_RX_DURATION);
2903 	}
2904 
2905 	if (!(link_sinfo->filled & BIT_ULL(NL80211_STA_INFO_TX_DURATION))) {
2906 		for (ac = 0; ac < IEEE80211_NUM_ACS; ac++)
2907 			link_sinfo->tx_duration += sta->airtime[ac].tx_airtime;
2908 		link_sinfo->filled |= BIT_ULL(NL80211_STA_INFO_TX_DURATION);
2909 	}
2910 
2911 	if (!(link_sinfo->filled & BIT_ULL(NL80211_STA_INFO_AIRTIME_WEIGHT))) {
2912 		link_sinfo->airtime_weight = sta->airtime_weight;
2913 		link_sinfo->filled |= BIT_ULL(NL80211_STA_INFO_AIRTIME_WEIGHT);
2914 	}
2915 
2916 	link_sinfo->rx_dropped_misc = link_sta_info->rx_stats.dropped;
2917 	if (link_sta_info->pcpu_rx_stats) {
2918 		for_each_possible_cpu(cpu) {
2919 			struct ieee80211_sta_rx_stats *cpurxs;
2920 
2921 			cpurxs = per_cpu_ptr(link_sta_info->pcpu_rx_stats,
2922 					     cpu);
2923 			link_sinfo->rx_dropped_misc += cpurxs->dropped;
2924 		}
2925 	}
2926 
2927 	if (sdata->vif.type == NL80211_IFTYPE_STATION &&
2928 	    !(sdata->vif.driver_flags & IEEE80211_VIF_BEACON_FILTER)) {
2929 		link_sinfo->filled |= BIT_ULL(NL80211_STA_INFO_BEACON_RX) |
2930 				 BIT_ULL(NL80211_STA_INFO_BEACON_SIGNAL_AVG);
2931 		link_sinfo->rx_beacon_signal_avg =
2932 			ieee80211_ave_rssi(&sdata->vif, -1);
2933 	}
2934 
2935 	if (ieee80211_hw_check(&sta->local->hw, SIGNAL_DBM) ||
2936 	    ieee80211_hw_check(&sta->local->hw, SIGNAL_UNSPEC)) {
2937 		if (!(link_sinfo->filled & BIT_ULL(NL80211_STA_INFO_SIGNAL))) {
2938 			link_sinfo->signal = (s8)last_rxstats->last_signal;
2939 			link_sinfo->filled |= BIT_ULL(NL80211_STA_INFO_SIGNAL);
2940 		}
2941 
2942 		if (!link_sta_info->pcpu_rx_stats &&
2943 		    !(link_sinfo->filled &
2944 		       BIT_ULL(NL80211_STA_INFO_SIGNAL_AVG))) {
2945 			link_sinfo->signal_avg =
2946 				-ewma_signal_read(&link_sta_info->rx_stats_avg.signal);
2947 			link_sinfo->filled |=
2948 				BIT_ULL(NL80211_STA_INFO_SIGNAL_AVG);
2949 		}
2950 	}
2951 
2952 	/* for the average - if pcpu_rx_stats isn't set - rxstats must point to
2953 	 * the sta->rx_stats struct, so the check here is fine with and without
2954 	 * pcpu statistics
2955 	 */
2956 	if (last_rxstats->chains &&
2957 	    !(link_sinfo->filled & (BIT_ULL(NL80211_STA_INFO_CHAIN_SIGNAL) |
2958 			       BIT_ULL(NL80211_STA_INFO_CHAIN_SIGNAL_AVG)))) {
2959 		link_sinfo->filled |= BIT_ULL(NL80211_STA_INFO_CHAIN_SIGNAL);
2960 		if (!link_sta_info->pcpu_rx_stats)
2961 			link_sinfo->filled |=
2962 				BIT_ULL(NL80211_STA_INFO_CHAIN_SIGNAL_AVG);
2963 
2964 		link_sinfo->chains = last_rxstats->chains;
2965 
2966 		for (i = 0; i < ARRAY_SIZE(link_sinfo->chain_signal); i++) {
2967 			link_sinfo->chain_signal[i] =
2968 				last_rxstats->chain_signal_last[i];
2969 			link_sinfo->chain_signal_avg[i] =
2970 				-ewma_signal_read(
2971 					&link_sta_info->rx_stats_avg.chain_signal[i]);
2972 		}
2973 	}
2974 
2975 	if (!(link_sinfo->filled & BIT_ULL(NL80211_STA_INFO_TX_BITRATE)) &&
2976 	    ieee80211_rate_valid(&link_sta_info->tx_stats.last_rate)) {
2977 		sta_set_rate_info_tx(sta, &link_sta_info->tx_stats.last_rate,
2978 				     &link_sinfo->txrate);
2979 		link_sinfo->filled |= BIT_ULL(NL80211_STA_INFO_TX_BITRATE);
2980 	}
2981 
2982 	if (!(link_sinfo->filled & BIT_ULL(NL80211_STA_INFO_RX_BITRATE))) {
2983 		if (sta_set_rate_info_rx(sta, &link_sinfo->rxrate,
2984 					 link_id) == 0)
2985 			link_sinfo->filled |=
2986 				BIT_ULL(NL80211_STA_INFO_RX_BITRATE);
2987 	}
2988 
2989 	if (tidstats && !cfg80211_link_sinfo_alloc_tid_stats(link_sinfo,
2990 							     GFP_KERNEL)) {
2991 		for (i = 0; i < IEEE80211_NUM_TIDS + 1; i++)
2992 			sta_set_tidstats(sta, &link_sinfo->pertid[i], i,
2993 					 link_id);
2994 	}
2995 
2996 	link_sinfo->bss_param.flags = 0;
2997 	if (sdata->vif.bss_conf.use_cts_prot)
2998 		link_sinfo->bss_param.flags |= BSS_PARAM_FLAGS_CTS_PROT;
2999 	if (sdata->vif.bss_conf.use_short_preamble)
3000 		link_sinfo->bss_param.flags |= BSS_PARAM_FLAGS_SHORT_PREAMBLE;
3001 	if (sdata->vif.bss_conf.use_short_slot)
3002 		link_sinfo->bss_param.flags |= BSS_PARAM_FLAGS_SHORT_SLOT_TIME;
3003 	link_sinfo->bss_param.dtim_period = link->conf->dtim_period;
3004 	link_sinfo->bss_param.beacon_interval = link->conf->beacon_int;
3005 
3006 	thr = sta_get_expected_throughput(sta);
3007 
3008 	if (thr != 0) {
3009 		link_sinfo->filled |=
3010 			BIT_ULL(NL80211_STA_INFO_EXPECTED_THROUGHPUT);
3011 		link_sinfo->expected_throughput = thr;
3012 	}
3013 
3014 	if (!(link_sinfo->filled & BIT_ULL(NL80211_STA_INFO_ACK_SIGNAL)) &&
3015 	    link_sta_info->status_stats.ack_signal_filled) {
3016 		link_sinfo->ack_signal =
3017 			link_sta_info->status_stats.last_ack_signal;
3018 		link_sinfo->filled |= BIT_ULL(NL80211_STA_INFO_ACK_SIGNAL);
3019 	}
3020 
3021 	if (!(link_sinfo->filled & BIT_ULL(NL80211_STA_INFO_ACK_SIGNAL_AVG)) &&
3022 	    link_sta_info->status_stats.ack_signal_filled) {
3023 		link_sinfo->avg_ack_signal =
3024 			-(s8)ewma_avg_signal_read(
3025 				&link_sta_info->status_stats.avg_ack_signal);
3026 		link_sinfo->filled |=
3027 			BIT_ULL(NL80211_STA_INFO_ACK_SIGNAL_AVG);
3028 	}
3029 }
3030 
3031 void sta_set_sinfo(struct sta_info *sta, struct station_info *sinfo,
3032 		   bool tidstats)
3033 {
3034 	struct ieee80211_sub_if_data *sdata = sta->sdata;
3035 	struct ieee80211_local *local = sdata->local;
3036 	u32 thr = 0;
3037 	int i, ac, cpu;
3038 	struct ieee80211_sta_rx_stats *last_rxstats;
3039 
3040 	last_rxstats = sta_get_last_rx_stats(sta, -1);
3041 
3042 	sinfo->generation = sdata->local->sta_generation;
3043 
3044 	/* do before driver, so beacon filtering drivers have a
3045 	 * chance to e.g. just add the number of filtered beacons
3046 	 * (or just modify the value entirely, of course)
3047 	 */
3048 	if (sdata->vif.type == NL80211_IFTYPE_STATION)
3049 		sinfo->rx_beacon = sdata->deflink.u.mgd.count_beacon_signal;
3050 
3051 	drv_sta_statistics(local, sdata, &sta->sta, sinfo);
3052 	sinfo->filled |= BIT_ULL(NL80211_STA_INFO_INACTIVE_TIME) |
3053 			 BIT_ULL(NL80211_STA_INFO_STA_FLAGS) |
3054 			 BIT_ULL(NL80211_STA_INFO_BSS_PARAM) |
3055 			 BIT_ULL(NL80211_STA_INFO_CONNECTED_TIME) |
3056 			 BIT_ULL(NL80211_STA_INFO_ASSOC_AT_BOOTTIME) |
3057 			 BIT_ULL(NL80211_STA_INFO_RX_DROP_MISC);
3058 
3059 	if (sdata->vif.type == NL80211_IFTYPE_STATION) {
3060 		sinfo->beacon_loss_count =
3061 			sdata->deflink.u.mgd.beacon_loss_count;
3062 		sinfo->filled |= BIT_ULL(NL80211_STA_INFO_BEACON_LOSS);
3063 	}
3064 
3065 	sinfo->connected_time = ktime_get_seconds() - sta->last_connected;
3066 	sinfo->assoc_at = sta->assoc_at;
3067 	sinfo->inactive_time =
3068 		jiffies_delta_to_msecs(jiffies -
3069 				       ieee80211_sta_last_active(sta, -1));
3070 
3071 	if (!(sinfo->filled & (BIT_ULL(NL80211_STA_INFO_TX_BYTES64) |
3072 			       BIT_ULL(NL80211_STA_INFO_TX_BYTES)))) {
3073 		sinfo->tx_bytes = 0;
3074 		for (ac = 0; ac < IEEE80211_NUM_ACS; ac++)
3075 			sinfo->tx_bytes += sta->deflink.tx_stats.bytes[ac];
3076 		sinfo->filled |= BIT_ULL(NL80211_STA_INFO_TX_BYTES64);
3077 	}
3078 
3079 	if (!(sinfo->filled & BIT_ULL(NL80211_STA_INFO_TX_PACKETS))) {
3080 		sinfo->tx_packets = 0;
3081 		for (ac = 0; ac < IEEE80211_NUM_ACS; ac++)
3082 			sinfo->tx_packets += sta->deflink.tx_stats.packets[ac];
3083 		sinfo->filled |= BIT_ULL(NL80211_STA_INFO_TX_PACKETS);
3084 	}
3085 
3086 	if (!(sinfo->filled & (BIT_ULL(NL80211_STA_INFO_RX_BYTES64) |
3087 			       BIT_ULL(NL80211_STA_INFO_RX_BYTES)))) {
3088 		sinfo->rx_bytes += sta_get_stats_bytes(&sta->deflink.rx_stats);
3089 
3090 		if (sta->deflink.pcpu_rx_stats) {
3091 			for_each_possible_cpu(cpu) {
3092 				struct ieee80211_sta_rx_stats *cpurxs;
3093 
3094 				cpurxs = per_cpu_ptr(sta->deflink.pcpu_rx_stats,
3095 						     cpu);
3096 				sinfo->rx_bytes += sta_get_stats_bytes(cpurxs);
3097 			}
3098 		}
3099 
3100 		sinfo->filled |= BIT_ULL(NL80211_STA_INFO_RX_BYTES64);
3101 	}
3102 
3103 	if (!(sinfo->filled & BIT_ULL(NL80211_STA_INFO_RX_PACKETS))) {
3104 		sinfo->rx_packets = sta->deflink.rx_stats.packets;
3105 		if (sta->deflink.pcpu_rx_stats) {
3106 			for_each_possible_cpu(cpu) {
3107 				struct ieee80211_sta_rx_stats *cpurxs;
3108 
3109 				cpurxs = per_cpu_ptr(sta->deflink.pcpu_rx_stats,
3110 						     cpu);
3111 				sinfo->rx_packets += cpurxs->packets;
3112 			}
3113 		}
3114 		sinfo->filled |= BIT_ULL(NL80211_STA_INFO_RX_PACKETS);
3115 	}
3116 
3117 	if (!(sinfo->filled & BIT_ULL(NL80211_STA_INFO_TX_RETRIES))) {
3118 		sinfo->tx_retries = sta->deflink.status_stats.retry_count;
3119 		sinfo->filled |= BIT_ULL(NL80211_STA_INFO_TX_RETRIES);
3120 	}
3121 
3122 	if (!(sinfo->filled & BIT_ULL(NL80211_STA_INFO_TX_FAILED))) {
3123 		sinfo->tx_failed = sta->deflink.status_stats.retry_failed;
3124 		sinfo->filled |= BIT_ULL(NL80211_STA_INFO_TX_FAILED);
3125 	}
3126 
3127 	if (!(sinfo->filled & BIT_ULL(NL80211_STA_INFO_RX_DURATION))) {
3128 		for (ac = 0; ac < IEEE80211_NUM_ACS; ac++)
3129 			sinfo->rx_duration += sta->airtime[ac].rx_airtime;
3130 		sinfo->filled |= BIT_ULL(NL80211_STA_INFO_RX_DURATION);
3131 	}
3132 
3133 	if (!(sinfo->filled & BIT_ULL(NL80211_STA_INFO_TX_DURATION))) {
3134 		for (ac = 0; ac < IEEE80211_NUM_ACS; ac++)
3135 			sinfo->tx_duration += sta->airtime[ac].tx_airtime;
3136 		sinfo->filled |= BIT_ULL(NL80211_STA_INFO_TX_DURATION);
3137 	}
3138 
3139 	if (!(sinfo->filled & BIT_ULL(NL80211_STA_INFO_AIRTIME_WEIGHT))) {
3140 		sinfo->airtime_weight = sta->airtime_weight;
3141 		sinfo->filled |= BIT_ULL(NL80211_STA_INFO_AIRTIME_WEIGHT);
3142 	}
3143 
3144 	sinfo->rx_dropped_misc = sta->deflink.rx_stats.dropped;
3145 	if (sta->deflink.pcpu_rx_stats) {
3146 		for_each_possible_cpu(cpu) {
3147 			struct ieee80211_sta_rx_stats *cpurxs;
3148 
3149 			cpurxs = per_cpu_ptr(sta->deflink.pcpu_rx_stats, cpu);
3150 			sinfo->rx_dropped_misc += cpurxs->dropped;
3151 		}
3152 	}
3153 
3154 	if (sdata->vif.type == NL80211_IFTYPE_STATION &&
3155 	    !(sdata->vif.driver_flags & IEEE80211_VIF_BEACON_FILTER)) {
3156 		sinfo->filled |= BIT_ULL(NL80211_STA_INFO_BEACON_RX) |
3157 				 BIT_ULL(NL80211_STA_INFO_BEACON_SIGNAL_AVG);
3158 		sinfo->rx_beacon_signal_avg =
3159 			ieee80211_ave_rssi(&sdata->vif, -1);
3160 	}
3161 
3162 	if (ieee80211_hw_check(&sta->local->hw, SIGNAL_DBM) ||
3163 	    ieee80211_hw_check(&sta->local->hw, SIGNAL_UNSPEC)) {
3164 		if (!(sinfo->filled & BIT_ULL(NL80211_STA_INFO_SIGNAL))) {
3165 			sinfo->signal = (s8)last_rxstats->last_signal;
3166 			sinfo->filled |= BIT_ULL(NL80211_STA_INFO_SIGNAL);
3167 		}
3168 
3169 		if (!sta->deflink.pcpu_rx_stats &&
3170 		    !(sinfo->filled & BIT_ULL(NL80211_STA_INFO_SIGNAL_AVG))) {
3171 			sinfo->signal_avg =
3172 				-ewma_signal_read(&sta->deflink.rx_stats_avg.signal);
3173 			sinfo->filled |= BIT_ULL(NL80211_STA_INFO_SIGNAL_AVG);
3174 		}
3175 	}
3176 
3177 	/* for the average - if pcpu_rx_stats isn't set - rxstats must point to
3178 	 * the sta->rx_stats struct, so the check here is fine with and without
3179 	 * pcpu statistics
3180 	 */
3181 	if (last_rxstats->chains &&
3182 	    !(sinfo->filled & (BIT_ULL(NL80211_STA_INFO_CHAIN_SIGNAL) |
3183 			       BIT_ULL(NL80211_STA_INFO_CHAIN_SIGNAL_AVG)))) {
3184 		sinfo->filled |= BIT_ULL(NL80211_STA_INFO_CHAIN_SIGNAL);
3185 		if (!sta->deflink.pcpu_rx_stats)
3186 			sinfo->filled |= BIT_ULL(NL80211_STA_INFO_CHAIN_SIGNAL_AVG);
3187 
3188 		sinfo->chains = last_rxstats->chains;
3189 
3190 		for (i = 0; i < ARRAY_SIZE(sinfo->chain_signal); i++) {
3191 			sinfo->chain_signal[i] =
3192 				last_rxstats->chain_signal_last[i];
3193 			sinfo->chain_signal_avg[i] =
3194 				-ewma_signal_read(&sta->deflink.rx_stats_avg.chain_signal[i]);
3195 		}
3196 	}
3197 
3198 	if (!(sinfo->filled & BIT_ULL(NL80211_STA_INFO_TX_BITRATE)) &&
3199 	    !sta->sta.valid_links &&
3200 	    ieee80211_rate_valid(&sta->deflink.tx_stats.last_rate)) {
3201 		sta_set_rate_info_tx(sta, &sta->deflink.tx_stats.last_rate,
3202 				     &sinfo->txrate);
3203 		sinfo->filled |= BIT_ULL(NL80211_STA_INFO_TX_BITRATE);
3204 	}
3205 
3206 	if (!(sinfo->filled & BIT_ULL(NL80211_STA_INFO_RX_BITRATE)) &&
3207 	    !sta->sta.valid_links) {
3208 		if (sta_set_rate_info_rx(sta, &sinfo->rxrate, -1) == 0)
3209 			sinfo->filled |= BIT_ULL(NL80211_STA_INFO_RX_BITRATE);
3210 	}
3211 
3212 	if (tidstats && !cfg80211_sinfo_alloc_tid_stats(sinfo, GFP_KERNEL)) {
3213 		for (i = 0; i < IEEE80211_NUM_TIDS + 1; i++)
3214 			sta_set_tidstats(sta, &sinfo->pertid[i], i, -1);
3215 	}
3216 
3217 #ifdef CONFIG_MAC80211_MESH
3218 	if (ieee80211_vif_is_mesh(&sdata->vif))
3219 		sta_set_mesh_sinfo(sta, sinfo);
3220 #endif
3221 
3222 	sinfo->bss_param.flags = 0;
3223 	if (sdata->vif.bss_conf.use_cts_prot)
3224 		sinfo->bss_param.flags |= BSS_PARAM_FLAGS_CTS_PROT;
3225 	if (sdata->vif.bss_conf.use_short_preamble)
3226 		sinfo->bss_param.flags |= BSS_PARAM_FLAGS_SHORT_PREAMBLE;
3227 	if (sdata->vif.bss_conf.use_short_slot)
3228 		sinfo->bss_param.flags |= BSS_PARAM_FLAGS_SHORT_SLOT_TIME;
3229 	sinfo->bss_param.dtim_period = sdata->vif.bss_conf.dtim_period;
3230 	sinfo->bss_param.beacon_interval = sdata->vif.bss_conf.beacon_int;
3231 
3232 	sinfo->sta_flags.set = 0;
3233 	sinfo->sta_flags.mask = BIT(NL80211_STA_FLAG_AUTHORIZED) |
3234 				BIT(NL80211_STA_FLAG_SHORT_PREAMBLE) |
3235 				BIT(NL80211_STA_FLAG_WME) |
3236 				BIT(NL80211_STA_FLAG_MFP) |
3237 				BIT(NL80211_STA_FLAG_AUTHENTICATED) |
3238 				BIT(NL80211_STA_FLAG_ASSOCIATED) |
3239 				BIT(NL80211_STA_FLAG_TDLS_PEER);
3240 	if (test_sta_flag(sta, WLAN_STA_AUTHORIZED))
3241 		sinfo->sta_flags.set |= BIT(NL80211_STA_FLAG_AUTHORIZED);
3242 	if (test_sta_flag(sta, WLAN_STA_SHORT_PREAMBLE))
3243 		sinfo->sta_flags.set |= BIT(NL80211_STA_FLAG_SHORT_PREAMBLE);
3244 	if (sta->sta.wme)
3245 		sinfo->sta_flags.set |= BIT(NL80211_STA_FLAG_WME);
3246 	if (test_sta_flag(sta, WLAN_STA_MFP))
3247 		sinfo->sta_flags.set |= BIT(NL80211_STA_FLAG_MFP);
3248 	if (test_sta_flag(sta, WLAN_STA_AUTH))
3249 		sinfo->sta_flags.set |= BIT(NL80211_STA_FLAG_AUTHENTICATED);
3250 	if (test_sta_flag(sta, WLAN_STA_ASSOC))
3251 		sinfo->sta_flags.set |= BIT(NL80211_STA_FLAG_ASSOCIATED);
3252 	if (test_sta_flag(sta, WLAN_STA_TDLS_PEER))
3253 		sinfo->sta_flags.set |= BIT(NL80211_STA_FLAG_TDLS_PEER);
3254 
3255 	thr = sta_get_expected_throughput(sta);
3256 
3257 	if (thr != 0) {
3258 		sinfo->filled |= BIT_ULL(NL80211_STA_INFO_EXPECTED_THROUGHPUT);
3259 		sinfo->expected_throughput = thr;
3260 	}
3261 
3262 	if (!(sinfo->filled & BIT_ULL(NL80211_STA_INFO_ACK_SIGNAL)) &&
3263 	    sta->deflink.status_stats.ack_signal_filled) {
3264 		sinfo->ack_signal = sta->deflink.status_stats.last_ack_signal;
3265 		sinfo->filled |= BIT_ULL(NL80211_STA_INFO_ACK_SIGNAL);
3266 	}
3267 
3268 	if (!(sinfo->filled & BIT_ULL(NL80211_STA_INFO_ACK_SIGNAL_AVG)) &&
3269 	    sta->deflink.status_stats.ack_signal_filled) {
3270 		sinfo->avg_ack_signal =
3271 			-(s8)ewma_avg_signal_read(
3272 				&sta->deflink.status_stats.avg_ack_signal);
3273 		sinfo->filled |=
3274 			BIT_ULL(NL80211_STA_INFO_ACK_SIGNAL_AVG);
3275 	}
3276 
3277 	if (sta->sta.valid_links) {
3278 		struct ieee80211_link_data *link;
3279 		struct link_sta_info *link_sta;
3280 		int link_id;
3281 
3282 		sinfo->mlo_params_valid = true;
3283 		sinfo->assoc_link_id = sta->deflink.link_id;
3284 		if (sta->sta.mlo)
3285 			ether_addr_copy(sinfo->mld_addr, sta->addr);
3286 
3287 		/* assign valid links first for iteration */
3288 		sinfo->valid_links = sta->sta.valid_links;
3289 
3290 		for_each_valid_link(sinfo, link_id) {
3291 			link_sta = wiphy_dereference(sta->local->hw.wiphy,
3292 						     sta->link[link_id]);
3293 			link = wiphy_dereference(sdata->local->hw.wiphy,
3294 						 sdata->link[link_id]);
3295 
3296 			if (!link_sta || !sinfo->links[link_id] || !link) {
3297 				sinfo->valid_links &= ~BIT(link_id);
3298 				continue;
3299 			}
3300 			sta_set_link_sinfo(sta, sinfo->links[link_id],
3301 					   link, tidstats);
3302 		}
3303 	}
3304 }
3305 
3306 u32 sta_get_expected_throughput(struct sta_info *sta)
3307 {
3308 	struct ieee80211_sub_if_data *sdata = sta->sdata;
3309 	struct ieee80211_local *local = sdata->local;
3310 	struct rate_control_ref *ref = NULL;
3311 	u32 thr = 0;
3312 
3313 	if (test_sta_flag(sta, WLAN_STA_RATE_CONTROL))
3314 		ref = local->rate_ctrl;
3315 
3316 	/* check if the driver has a SW RC implementation */
3317 	if (ref && ref->ops->get_expected_throughput)
3318 		thr = ref->ops->get_expected_throughput(sta->rate_ctrl_priv);
3319 	else
3320 		thr = drv_get_expected_throughput(local, sta);
3321 
3322 	return thr;
3323 }
3324 
3325 unsigned long ieee80211_sta_last_active(struct sta_info *sta, int link_id)
3326 {
3327 	struct ieee80211_sta_rx_stats *stats;
3328 	struct link_sta_info *link_sta_info;
3329 
3330 	stats = sta_get_last_rx_stats(sta, link_id);
3331 
3332 	if (link_id < 0)
3333 		link_sta_info = &sta->deflink;
3334 	else
3335 		link_sta_info = wiphy_dereference(sta->local->hw.wiphy,
3336 						  sta->link[link_id]);
3337 
3338 	if (!link_sta_info->status_stats.last_ack ||
3339 	    time_after(stats->last_rx, link_sta_info->status_stats.last_ack))
3340 		return stats->last_rx;
3341 
3342 	return link_sta_info->status_stats.last_ack;
3343 }
3344 
3345 int ieee80211_sta_allocate_link(struct sta_info *sta, unsigned int link_id)
3346 {
3347 	struct ieee80211_sub_if_data *sdata = sta->sdata;
3348 	struct sta_link_alloc *alloc;
3349 	int ret;
3350 
3351 	lockdep_assert_wiphy(sdata->local->hw.wiphy);
3352 
3353 	WARN_ON(!test_sta_flag(sta, WLAN_STA_INSERTED));
3354 
3355 	/* must represent an MLD from the start */
3356 	if (WARN_ON(!sta->sta.valid_links))
3357 		return -EINVAL;
3358 
3359 	if (WARN_ON(sta->sta.valid_links & BIT(link_id) ||
3360 		    sta->link[link_id]))
3361 		return -EBUSY;
3362 
3363 	alloc = kzalloc_obj(*alloc);
3364 	if (!alloc)
3365 		return -ENOMEM;
3366 
3367 	ret = sta_info_alloc_link(sdata->local, &alloc->info, GFP_KERNEL);
3368 	if (ret) {
3369 		kfree(alloc);
3370 		return ret;
3371 	}
3372 
3373 	sta_info_add_link(sta, link_id, &alloc->info, &alloc->sta);
3374 
3375 	ieee80211_link_sta_debugfs_add(&alloc->info);
3376 
3377 	return 0;
3378 }
3379 
3380 void ieee80211_sta_free_link(struct sta_info *sta, unsigned int link_id)
3381 {
3382 	lockdep_assert_wiphy(sta->sdata->local->hw.wiphy);
3383 
3384 	WARN_ON(!test_sta_flag(sta, WLAN_STA_INSERTED));
3385 
3386 	sta_remove_link(sta, link_id, false);
3387 }
3388 
3389 int ieee80211_sta_activate_link(struct sta_info *sta, unsigned int link_id)
3390 {
3391 	struct ieee80211_sub_if_data *sdata = sta->sdata;
3392 	struct link_sta_info *link_sta;
3393 	u16 old_links = sta->sta.valid_links;
3394 	u16 new_links = old_links | BIT(link_id);
3395 	int ret;
3396 
3397 	link_sta = rcu_dereference_protected(sta->link[link_id],
3398 					     lockdep_is_held(&sdata->local->hw.wiphy->mtx));
3399 
3400 	if (WARN_ON(old_links == new_links || !link_sta))
3401 		return -EINVAL;
3402 
3403 	rcu_read_lock();
3404 	if (link_sta_info_hash_lookup(sdata->local, link_sta->addr)) {
3405 		rcu_read_unlock();
3406 		return -EALREADY;
3407 	}
3408 	/* we only modify under the mutex so this is fine */
3409 	rcu_read_unlock();
3410 
3411 	sta->sta.valid_links = new_links;
3412 
3413 	if (WARN_ON(!test_sta_flag(sta, WLAN_STA_INSERTED)))
3414 		goto hash;
3415 
3416 	ieee80211_recalc_min_chandef(sdata, link_id);
3417 
3418 	/* Ensure the values are updated for the driver,
3419 	 * redone by sta_remove_link on failure.
3420 	 */
3421 	ieee80211_sta_recalc_aggregates(&sta->sta);
3422 
3423 	ret = drv_change_sta_links(sdata->local, sdata, &sta->sta,
3424 				   old_links, new_links);
3425 	if (ret) {
3426 		sta->sta.valid_links = old_links;
3427 		sta_remove_link(sta, link_id, false);
3428 		return ret;
3429 	}
3430 
3431 hash:
3432 	ret = link_sta_info_hash_add(sdata->local, link_sta);
3433 	WARN_ON(ret);
3434 	return 0;
3435 }
3436 
3437 void ieee80211_sta_remove_link(struct sta_info *sta, unsigned int link_id)
3438 {
3439 	struct ieee80211_sub_if_data *sdata = sta->sdata;
3440 	u16 old_links = sta->sta.valid_links;
3441 
3442 	lockdep_assert_wiphy(sdata->local->hw.wiphy);
3443 
3444 	sta->sta.valid_links &= ~BIT(link_id);
3445 
3446 	if (!WARN_ON(!test_sta_flag(sta, WLAN_STA_INSERTED)))
3447 		drv_change_sta_links(sdata->local, sdata, &sta->sta,
3448 				     old_links, sta->sta.valid_links);
3449 
3450 	sta_remove_link(sta, link_id, true);
3451 }
3452 
3453 static u8 ieee80211_sta_nss_capability(struct link_sta_info *link_sta)
3454 {
3455 	u8 ht_rx_nss = 0, vht_rx_nss = 0, he_rx_nss = 0, eht_rx_nss = 0, rx_nss;
3456 	bool support_160;
3457 
3458 	if (link_sta->pub->eht_cap.has_eht) {
3459 		int i;
3460 		const u8 *rx_nss_mcs = (void *)&link_sta->pub->eht_cap.eht_mcs_nss_supp;
3461 
3462 		/* get the max nss for EHT over all possible bandwidths and mcs */
3463 		for (i = 0; i < sizeof(struct ieee80211_eht_mcs_nss_supp); i++)
3464 			eht_rx_nss = max_t(u8, eht_rx_nss,
3465 					   u8_get_bits(rx_nss_mcs[i],
3466 						       IEEE80211_EHT_MCS_NSS_RX));
3467 	}
3468 
3469 	if (link_sta->pub->he_cap.has_he) {
3470 		int i;
3471 		u8 rx_mcs_80 = 0, rx_mcs_160 = 0;
3472 		const struct ieee80211_sta_he_cap *he_cap = &link_sta->pub->he_cap;
3473 		u16 mcs_160_map =
3474 			le16_to_cpu(he_cap->he_mcs_nss_supp.rx_mcs_160);
3475 		u16 mcs_80_map = le16_to_cpu(he_cap->he_mcs_nss_supp.rx_mcs_80);
3476 
3477 		for (i = 7; i >= 0; i--) {
3478 			u8 mcs_160 = (mcs_160_map >> (2 * i)) & 3;
3479 
3480 			if (mcs_160 != IEEE80211_HE_MCS_NOT_SUPPORTED) {
3481 				rx_mcs_160 = i + 1;
3482 				break;
3483 			}
3484 		}
3485 		for (i = 7; i >= 0; i--) {
3486 			u8 mcs_80 = (mcs_80_map >> (2 * i)) & 3;
3487 
3488 			if (mcs_80 != IEEE80211_HE_MCS_NOT_SUPPORTED) {
3489 				rx_mcs_80 = i + 1;
3490 				break;
3491 			}
3492 		}
3493 
3494 		support_160 = he_cap->he_cap_elem.phy_cap_info[0] &
3495 			      IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_160MHZ_IN_5G;
3496 
3497 		if (support_160)
3498 			he_rx_nss = min(rx_mcs_80, rx_mcs_160);
3499 		else
3500 			he_rx_nss = rx_mcs_80;
3501 	}
3502 
3503 	if (link_sta->pub->ht_cap.ht_supported) {
3504 		if (link_sta->pub->ht_cap.mcs.rx_mask[0])
3505 			ht_rx_nss++;
3506 		if (link_sta->pub->ht_cap.mcs.rx_mask[1])
3507 			ht_rx_nss++;
3508 		if (link_sta->pub->ht_cap.mcs.rx_mask[2])
3509 			ht_rx_nss++;
3510 		if (link_sta->pub->ht_cap.mcs.rx_mask[3])
3511 			ht_rx_nss++;
3512 		/* FIXME: consider rx_highest? */
3513 	}
3514 
3515 	if (link_sta->pub->vht_cap.vht_supported) {
3516 		int i;
3517 		u16 rx_mcs_map;
3518 
3519 		rx_mcs_map = le16_to_cpu(link_sta->pub->vht_cap.vht_mcs.rx_mcs_map);
3520 
3521 		for (i = 7; i >= 0; i--) {
3522 			u8 mcs = (rx_mcs_map >> (2 * i)) & 3;
3523 
3524 			if (mcs != IEEE80211_VHT_MCS_NOT_SUPPORTED) {
3525 				vht_rx_nss = i + 1;
3526 				break;
3527 			}
3528 		}
3529 		/* FIXME: consider rx_highest? */
3530 	}
3531 
3532 	rx_nss = max(vht_rx_nss, ht_rx_nss);
3533 	rx_nss = max(he_rx_nss, rx_nss);
3534 	rx_nss = max(eht_rx_nss, rx_nss);
3535 	rx_nss = max_t(u8, 1, rx_nss);
3536 
3537 	return rx_nss;
3538 }
3539 
3540 void ieee80211_sta_init_nss_bw_capa(struct link_sta_info *link_sta,
3541 				    struct cfg80211_chan_def *chandef)
3542 {
3543 	/*
3544 	 * TODO: The entirety of the STA Tx/Rx bandwidth handling
3545 	 * assumes 20MHz based widths, so for now don't initialise
3546 	 * pubsta->bandwidth for S1G bands. Since enum
3547 	 * ieee80211_sta_rx_bandwidth is ordered, we will probably
3548 	 * need to introduce ieee80211_s1g_sta_rx_bandwidth with
3549 	 * S1G widths and associated S1G specific code. Additionally,
3550 	 * existing S1G hardware is all 1SS, in the future if hardware
3551 	 * starts supporting >1SS this should be implemented in
3552 	 * ieee80211_sta_nss_capability().
3553 	 */
3554 	if (cfg80211_chandef_is_s1g(chandef)) {
3555 		link_sta->capa_nss = 1;
3556 		link_sta->pub->rx_nss = 1;
3557 		return;
3558 	}
3559 
3560 	link_sta->capa_nss = ieee80211_sta_nss_capability(link_sta);
3561 	link_sta->pub->rx_nss = link_sta->capa_nss;
3562 
3563 	link_sta->pub->bandwidth =
3564 		ieee80211_sta_current_bw(link_sta, chandef,
3565 					 IEEE80211_STA_BW_TX_TO_STA);
3566 }
3567 
3568 void ieee80211_sta_set_max_amsdu_subframes(struct sta_info *sta,
3569 					   const u8 *ext_capab,
3570 					   unsigned int ext_capab_len)
3571 {
3572 	u8 val;
3573 
3574 	sta->sta.max_amsdu_subframes = 0;
3575 
3576 	if (ext_capab_len < 8)
3577 		return;
3578 
3579 	/* The sender might not have sent the last bit, consider it to be 0 */
3580 	val = u8_get_bits(ext_capab[7], WLAN_EXT_CAPA8_MAX_MSDU_IN_AMSDU_LSB);
3581 
3582 	/* we did get all the bits, take the MSB as well */
3583 	if (ext_capab_len >= 9)
3584 		val |= u8_get_bits(ext_capab[8],
3585 				   WLAN_EXT_CAPA9_MAX_MSDU_IN_AMSDU_MSB) << 1;
3586 
3587 	if (val)
3588 		sta->sta.max_amsdu_subframes = 4 << (4 - val);
3589 }
3590 
3591 #ifdef CONFIG_LOCKDEP
3592 bool lockdep_sta_mutex_held(struct ieee80211_sta *pubsta)
3593 {
3594 	struct sta_info *sta = container_of(pubsta, struct sta_info, sta);
3595 
3596 	return lockdep_is_held(&sta->local->hw.wiphy->mtx);
3597 }
3598 EXPORT_SYMBOL(lockdep_sta_mutex_held);
3599 #endif
3600 
3601 /**
3602  * ieee80211_sta_bw_capability - get STA's bandwidth capability
3603  * @link_sta: the (link) STA to get the capability for
3604  * @band: the band to get the capability on
3605  *
3606  * Return: the maximum bandwidth supported by the STA
3607  */
3608 static enum ieee80211_sta_rx_bandwidth
3609 ieee80211_sta_bw_capability(struct link_sta_info *link_sta,
3610 			    enum nl80211_band band)
3611 {
3612 	struct ieee80211_sta_vht_cap *vht_cap = &link_sta->pub->vht_cap;
3613 	struct ieee80211_sta_he_cap *he_cap = &link_sta->pub->he_cap;
3614 	struct ieee80211_sta_eht_cap *eht_cap = &link_sta->pub->eht_cap;
3615 	u32 cap_width;
3616 
3617 	if (he_cap->has_he) {
3618 		u8 info;
3619 
3620 		if (eht_cap->has_eht && band == NL80211_BAND_6GHZ) {
3621 			info = eht_cap->eht_cap_elem.phy_cap_info[0];
3622 
3623 			if (info & IEEE80211_EHT_PHY_CAP0_320MHZ_IN_6GHZ)
3624 				return IEEE80211_STA_RX_BW_320;
3625 		}
3626 
3627 		info = he_cap->he_cap_elem.phy_cap_info[0];
3628 
3629 		if (band == NL80211_BAND_2GHZ) {
3630 			if (info & IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_40MHZ_IN_2G)
3631 				return IEEE80211_STA_RX_BW_40;
3632 			return IEEE80211_STA_RX_BW_20;
3633 		}
3634 
3635 		if (info & IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_160MHZ_IN_5G ||
3636 		    info & IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_80PLUS80_MHZ_IN_5G)
3637 			return IEEE80211_STA_RX_BW_160;
3638 
3639 		if (info & IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_40MHZ_80MHZ_IN_5G)
3640 			return IEEE80211_STA_RX_BW_80;
3641 
3642 		return IEEE80211_STA_RX_BW_20;
3643 	}
3644 
3645 	if (!vht_cap->vht_supported)
3646 		return link_sta->pub->ht_cap.cap & IEEE80211_HT_CAP_SUP_WIDTH_20_40 ?
3647 				IEEE80211_STA_RX_BW_40 :
3648 				IEEE80211_STA_RX_BW_20;
3649 
3650 	cap_width = vht_cap->cap & IEEE80211_VHT_CAP_SUPP_CHAN_WIDTH_MASK;
3651 
3652 	if (cap_width == IEEE80211_VHT_CAP_SUPP_CHAN_WIDTH_160MHZ ||
3653 	    cap_width == IEEE80211_VHT_CAP_SUPP_CHAN_WIDTH_160_80PLUS80MHZ)
3654 		return IEEE80211_STA_RX_BW_160;
3655 
3656 	/*
3657 	 * If this is non-zero, then it does support 160 MHz after all,
3658 	 * in one form or the other. We don't distinguish here (or even
3659 	 * above) between 160 and 80+80 yet.
3660 	 */
3661 	if (vht_cap->cap & IEEE80211_VHT_CAP_EXT_NSS_BW_MASK)
3662 		return IEEE80211_STA_RX_BW_160;
3663 
3664 	return IEEE80211_STA_RX_BW_80;
3665 }
3666 
3667 /**
3668  * ieee80211_sta_usable_bw - get STA's usable bandwidth capability
3669  * @link_sta: the (link) STA to get the capability for
3670  * @band: the band to get the capability on
3671  *
3672  * If the STA is on an AP interface, take into account the AP's
3673  * bandwidth corresponding to this station's PHY capability
3674  *
3675  * Return: the maximum bandwidth supported by the STA on the
3676  *	connection to the interface it's connected to
3677  */
3678 static enum ieee80211_sta_rx_bandwidth
3679 ieee80211_sta_usable_bw(struct link_sta_info *link_sta,
3680 			enum nl80211_band band)
3681 {
3682 	struct ieee80211_sub_if_data *sdata = link_sta->sta->sdata;
3683 	enum ieee80211_sta_rx_bandwidth bw;
3684 	struct ieee80211_link_data *link;
3685 
3686 	bw = ieee80211_sta_bw_capability(link_sta, band);
3687 
3688 	if (sdata->vif.type == NL80211_IFTYPE_AP_VLAN) {
3689 		sdata = get_bss_sdata(sdata);
3690 
3691 		/* for a STA to exist on VLAN, it must have AP */
3692 		if (WARN_ON(!sdata))
3693 			return IEEE80211_STA_RX_BW_20;
3694 	}
3695 
3696 	if (sdata->vif.type != NL80211_IFTYPE_AP)
3697 		return bw;
3698 
3699 	/* for a link STA to exist, vif must have the link */
3700 	link = sdata_dereference(sdata->link[link_sta->link_id], sdata);
3701 	if (WARN_ON(!link))
3702 		return IEEE80211_STA_RX_BW_20;
3703 
3704 	if (!link_sta->pub->eht_cap.has_eht)
3705 		return min(bw, link->bss_bw.he_and_lower);
3706 
3707 	if (!link_sta->pub->uhr_cap.has_uhr ||
3708 	    !link_sta->uhr_dbe_enabled)
3709 		return min(bw, link->bss_bw.eht);
3710 
3711 	return bw;
3712 }
3713 
3714 static enum ieee80211_sta_rx_bandwidth
3715 ieee80211_sta_current_bw_rx_from_sta(struct link_sta_info *link_sta,
3716 				     struct cfg80211_chan_def *chandef)
3717 {
3718 	/*
3719 	 * Take RX OMI into account. The value "rx_omi_bw_rx" is what
3720 	 * we've indicated to the STA we can currently receive.
3721 	 *
3722 	 * This is needed since the RX OMI is done by us to save power,
3723 	 * requiring changing both our TX (rate control) and RX (chanctx),
3724 	 * which in turn needs to be done in the right order (stop TX
3725 	 * at a higher bandwidth first while reducing bandwidth, and
3726 	 * change the chanctx only after the peer accepts, etc.)
3727 	 */
3728 	return min(ieee80211_sta_usable_bw(link_sta, chandef->chan->band),
3729 		   link_sta->rx_omi_bw_rx);
3730 }
3731 
3732 static enum ieee80211_sta_rx_bandwidth
3733 ieee80211_sta_current_bw_tx_to_sta(struct link_sta_info *link_sta,
3734 				   struct cfg80211_chan_def *chandef)
3735 {
3736 	struct sta_info *sta = link_sta->sta;
3737 	enum nl80211_chan_width bss_width;
3738 	enum ieee80211_sta_rx_bandwidth bw;
3739 	enum nl80211_band band;
3740 
3741 	bss_width = chandef->width;
3742 	band = chandef->chan->band;
3743 
3744 	bw = ieee80211_sta_usable_bw(link_sta, band);
3745 	bw = min(bw, link_sta->op_mode_bw);
3746 	/* also limit to RX OMI bandwidth we TX to the STA */
3747 	bw = min(bw, link_sta->rx_omi_bw_tx);
3748 	/* and UHR DBE transition limits */
3749 	bw = min(bw, link_sta->uhr_usable_tx_width);
3750 
3751 	/* Don't consider AP's bandwidth for TDLS peers, section 11.23.1 of
3752 	 * IEEE80211-2016 specification makes higher bandwidth operation
3753 	 * possible on the TDLS link if the peers have wider bandwidth
3754 	 * capability.
3755 	 *
3756 	 * However, in this case, and only if the TDLS peer is authorized,
3757 	 * limit to the tdls_chandef so that the configuration here isn't
3758 	 * wider than what's actually requested on the channel context.
3759 	 */
3760 	if (test_sta_flag(sta, WLAN_STA_TDLS_PEER) &&
3761 	    test_sta_flag(sta, WLAN_STA_TDLS_WIDER_BW) &&
3762 	    test_sta_flag(sta, WLAN_STA_AUTHORIZED) &&
3763 	    sta->tdls_chandef.chan)
3764 		bw = min(bw, ieee80211_chan_width_to_rx_bw(sta->tdls_chandef.width));
3765 	else
3766 		bw = min(bw, ieee80211_chan_width_to_rx_bw(bss_width));
3767 
3768 	return bw;
3769 }
3770 
3771 /**
3772  * ieee80211_sta_current_bw - get STA's current usable bandwidth
3773  * @link_sta: the (link) STA to get the bandwidth for
3774  * @chandef: the chandef for the channel the STA is on
3775  * @direction: the direction (to or from STA)
3776  *
3777  * Return: the maximum bandwidth that the station can/may
3778  *	(currently) use in the given direction
3779  */
3780 enum ieee80211_sta_rx_bandwidth
3781 ieee80211_sta_current_bw(struct link_sta_info *link_sta,
3782 			 struct cfg80211_chan_def *chandef,
3783 			 enum ieee80211_sta_bw_direction direction)
3784 {
3785 	if (WARN_ON(!chandef))
3786 		return IEEE80211_STA_RX_BW_20;
3787 
3788 	switch (direction) {
3789 	case IEEE80211_STA_BW_RX_FROM_STA:
3790 		return ieee80211_sta_current_bw_rx_from_sta(link_sta, chandef);
3791 	case IEEE80211_STA_BW_TX_TO_STA:
3792 		return ieee80211_sta_current_bw_tx_to_sta(link_sta, chandef);
3793 	}
3794 
3795 	/* unreachable */
3796 	return IEEE80211_STA_RX_BW_20;
3797 }
3798 
3799 bool ieee80211_link_sta_update_rc_bw(struct ieee80211_link_data *link,
3800 				     struct link_sta_info *link_sta)
3801 {
3802 	struct ieee80211_sub_if_data *sdata = link->sdata;
3803 	struct ieee80211_supported_band *sband;
3804 	enum ieee80211_sta_rx_bandwidth new_bw;
3805 	enum nl80211_band band;
3806 
3807 	band = link->conf->chanreq.oper.chan->band;
3808 	sband = sdata->local->hw.wiphy->bands[band];
3809 
3810 	new_bw = ieee80211_sta_current_bw(link_sta, &link->conf->chanreq.oper,
3811 					  IEEE80211_STA_BW_TX_TO_STA);
3812 	if (link_sta->pub->bandwidth == new_bw)
3813 		return false;
3814 
3815 	link_sta->pub->bandwidth = new_bw;
3816 	rate_control_rate_update(sdata->local, sband, link_sta,
3817 				 IEEE80211_RC_BW_CHANGED);
3818 
3819 	return true;
3820 }
3821