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