wifi: mac80211: Support multi link in ieee80211_recalc_min_chandef()
[linux-block.git] / net / mac80211 / sta_info.c
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-2021 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/codel.h>
22 #include <net/mac80211.h>
23 #include "ieee80211_i.h"
24 #include "driver-ops.h"
25 #include "rate.h"
26 #include "sta_info.h"
27 #include "debugfs_sta.h"
28 #include "mesh.h"
29 #include "wme.h"
30
31 /**
32  * DOC: STA information lifetime rules
33  *
34  * STA info structures (&struct sta_info) are managed in a hash table
35  * for faster lookup and a list for iteration. They are managed using
36  * RCU, i.e. access to the list and hash table is protected by RCU.
37  *
38  * Upon allocating a STA info structure with sta_info_alloc(), the caller
39  * owns that structure. It must then insert it into the hash table using
40  * either sta_info_insert() or sta_info_insert_rcu(); only in the latter
41  * case (which acquires an rcu read section but must not be called from
42  * within one) will the pointer still be valid after the call. Note that
43  * the caller may not do much with the STA info before inserting it, in
44  * particular, it may not start any mesh peer link management or add
45  * encryption keys.
46  *
47  * When the insertion fails (sta_info_insert()) returns non-zero), the
48  * structure will have been freed by sta_info_insert()!
49  *
50  * Station entries are added by mac80211 when you establish a link with a
51  * peer. This means different things for the different type of interfaces
52  * we support. For a regular station this mean we add the AP sta when we
53  * receive an association response from the AP. For IBSS this occurs when
54  * get to know about a peer on the same IBSS. For WDS we add the sta for
55  * the peer immediately upon device open. When using AP mode we add stations
56  * for each respective station upon request from userspace through nl80211.
57  *
58  * In order to remove a STA info structure, various sta_info_destroy_*()
59  * calls are available.
60  *
61  * There is no concept of ownership on a STA entry, each structure is
62  * owned by the global hash table/list until it is removed. All users of
63  * the structure need to be RCU protected so that the structure won't be
64  * freed before they are done using it.
65  */
66
67 struct sta_link_alloc {
68         struct link_sta_info info;
69         struct ieee80211_link_sta sta;
70         struct rcu_head rcu_head;
71 };
72
73 static const struct rhashtable_params sta_rht_params = {
74         .nelem_hint = 3, /* start small */
75         .automatic_shrinking = true,
76         .head_offset = offsetof(struct sta_info, hash_node),
77         .key_offset = offsetof(struct sta_info, addr),
78         .key_len = ETH_ALEN,
79         .max_size = CONFIG_MAC80211_STA_HASH_MAX_SIZE,
80 };
81
82 static const struct rhashtable_params link_sta_rht_params = {
83         .nelem_hint = 3, /* start small */
84         .automatic_shrinking = true,
85         .head_offset = offsetof(struct link_sta_info, link_hash_node),
86         .key_offset = offsetof(struct link_sta_info, addr),
87         .key_len = ETH_ALEN,
88         .max_size = CONFIG_MAC80211_STA_HASH_MAX_SIZE,
89 };
90
91 /* Caller must hold local->sta_mtx */
92 static int sta_info_hash_del(struct ieee80211_local *local,
93                              struct sta_info *sta)
94 {
95         return rhltable_remove(&local->sta_hash, &sta->hash_node,
96                                sta_rht_params);
97 }
98
99 static int link_sta_info_hash_del(struct ieee80211_local *local,
100                                   struct link_sta_info *link_sta)
101 {
102         return rhltable_remove(&local->link_sta_hash,
103                                &link_sta->link_hash_node,
104                                link_sta_rht_params);
105 }
106
107 static void __cleanup_single_sta(struct sta_info *sta)
108 {
109         int ac, i;
110         struct tid_ampdu_tx *tid_tx;
111         struct ieee80211_sub_if_data *sdata = sta->sdata;
112         struct ieee80211_local *local = sdata->local;
113         struct ps_data *ps;
114
115         if (test_sta_flag(sta, WLAN_STA_PS_STA) ||
116             test_sta_flag(sta, WLAN_STA_PS_DRIVER) ||
117             test_sta_flag(sta, WLAN_STA_PS_DELIVER)) {
118                 if (sta->sdata->vif.type == NL80211_IFTYPE_AP ||
119                     sta->sdata->vif.type == NL80211_IFTYPE_AP_VLAN)
120                         ps = &sdata->bss->ps;
121                 else if (ieee80211_vif_is_mesh(&sdata->vif))
122                         ps = &sdata->u.mesh.ps;
123                 else
124                         return;
125
126                 clear_sta_flag(sta, WLAN_STA_PS_STA);
127                 clear_sta_flag(sta, WLAN_STA_PS_DRIVER);
128                 clear_sta_flag(sta, WLAN_STA_PS_DELIVER);
129
130                 atomic_dec(&ps->num_sta_ps);
131         }
132
133         if (sta->sta.txq[0]) {
134                 for (i = 0; i < ARRAY_SIZE(sta->sta.txq); i++) {
135                         struct txq_info *txqi;
136
137                         if (!sta->sta.txq[i])
138                                 continue;
139
140                         txqi = to_txq_info(sta->sta.txq[i]);
141
142                         ieee80211_txq_purge(local, txqi);
143                 }
144         }
145
146         for (ac = 0; ac < IEEE80211_NUM_ACS; ac++) {
147                 local->total_ps_buffered -= skb_queue_len(&sta->ps_tx_buf[ac]);
148                 ieee80211_purge_tx_queue(&local->hw, &sta->ps_tx_buf[ac]);
149                 ieee80211_purge_tx_queue(&local->hw, &sta->tx_filtered[ac]);
150         }
151
152         if (ieee80211_vif_is_mesh(&sdata->vif))
153                 mesh_sta_cleanup(sta);
154
155         cancel_work_sync(&sta->drv_deliver_wk);
156
157         /*
158          * Destroy aggregation state here. It would be nice to wait for the
159          * driver to finish aggregation stop and then clean up, but for now
160          * drivers have to handle aggregation stop being requested, followed
161          * directly by station destruction.
162          */
163         for (i = 0; i < IEEE80211_NUM_TIDS; i++) {
164                 kfree(sta->ampdu_mlme.tid_start_tx[i]);
165                 tid_tx = rcu_dereference_raw(sta->ampdu_mlme.tid_tx[i]);
166                 if (!tid_tx)
167                         continue;
168                 ieee80211_purge_tx_queue(&local->hw, &tid_tx->pending);
169                 kfree(tid_tx);
170         }
171 }
172
173 static void cleanup_single_sta(struct sta_info *sta)
174 {
175         struct ieee80211_sub_if_data *sdata = sta->sdata;
176         struct ieee80211_local *local = sdata->local;
177
178         __cleanup_single_sta(sta);
179         sta_info_free(local, sta);
180 }
181
182 struct rhlist_head *sta_info_hash_lookup(struct ieee80211_local *local,
183                                          const u8 *addr)
184 {
185         return rhltable_lookup(&local->sta_hash, addr, sta_rht_params);
186 }
187
188 /* protected by RCU */
189 struct sta_info *sta_info_get(struct ieee80211_sub_if_data *sdata,
190                               const u8 *addr)
191 {
192         struct ieee80211_local *local = sdata->local;
193         struct rhlist_head *tmp;
194         struct sta_info *sta;
195
196         rcu_read_lock();
197         for_each_sta_info(local, addr, sta, tmp) {
198                 if (sta->sdata == sdata) {
199                         rcu_read_unlock();
200                         /* this is safe as the caller must already hold
201                          * another rcu read section or the mutex
202                          */
203                         return sta;
204                 }
205         }
206         rcu_read_unlock();
207         return NULL;
208 }
209
210 /*
211  * Get sta info either from the specified interface
212  * or from one of its vlans
213  */
214 struct sta_info *sta_info_get_bss(struct ieee80211_sub_if_data *sdata,
215                                   const u8 *addr)
216 {
217         struct ieee80211_local *local = sdata->local;
218         struct rhlist_head *tmp;
219         struct sta_info *sta;
220
221         rcu_read_lock();
222         for_each_sta_info(local, addr, sta, tmp) {
223                 if (sta->sdata == sdata ||
224                     (sta->sdata->bss && sta->sdata->bss == sdata->bss)) {
225                         rcu_read_unlock();
226                         /* this is safe as the caller must already hold
227                          * another rcu read section or the mutex
228                          */
229                         return sta;
230                 }
231         }
232         rcu_read_unlock();
233         return NULL;
234 }
235
236 struct rhlist_head *link_sta_info_hash_lookup(struct ieee80211_local *local,
237                                               const u8 *addr)
238 {
239         return rhltable_lookup(&local->link_sta_hash, addr,
240                                link_sta_rht_params);
241 }
242
243 struct link_sta_info *
244 link_sta_info_get_bss(struct ieee80211_sub_if_data *sdata, const u8 *addr)
245 {
246         struct ieee80211_local *local = sdata->local;
247         struct rhlist_head *tmp;
248         struct link_sta_info *link_sta;
249
250         rcu_read_lock();
251         for_each_link_sta_info(local, addr, link_sta, tmp) {
252                 struct sta_info *sta = link_sta->sta;
253
254                 if (sta->sdata == sdata ||
255                     (sta->sdata->bss && sta->sdata->bss == sdata->bss)) {
256                         rcu_read_unlock();
257                         /* this is safe as the caller must already hold
258                          * another rcu read section or the mutex
259                          */
260                         return link_sta;
261                 }
262         }
263         rcu_read_unlock();
264         return NULL;
265 }
266
267 struct sta_info *sta_info_get_by_addrs(struct ieee80211_local *local,
268                                        const u8 *sta_addr, const u8 *vif_addr)
269 {
270         struct rhlist_head *tmp;
271         struct sta_info *sta;
272
273         for_each_sta_info(local, sta_addr, sta, tmp) {
274                 if (ether_addr_equal(vif_addr, sta->sdata->vif.addr))
275                         return sta;
276         }
277
278         return NULL;
279 }
280
281 struct sta_info *sta_info_get_by_idx(struct ieee80211_sub_if_data *sdata,
282                                      int idx)
283 {
284         struct ieee80211_local *local = sdata->local;
285         struct sta_info *sta;
286         int i = 0;
287
288         list_for_each_entry_rcu(sta, &local->sta_list, list,
289                                 lockdep_is_held(&local->sta_mtx)) {
290                 if (sdata != sta->sdata)
291                         continue;
292                 if (i < idx) {
293                         ++i;
294                         continue;
295                 }
296                 return sta;
297         }
298
299         return NULL;
300 }
301
302 static void sta_info_free_link(struct link_sta_info *link_sta)
303 {
304         free_percpu(link_sta->pcpu_rx_stats);
305 }
306
307 static void sta_remove_link(struct sta_info *sta, unsigned int link_id,
308                             bool unhash)
309 {
310         struct sta_link_alloc *alloc = NULL;
311         struct link_sta_info *link_sta;
312
313         link_sta = rcu_dereference_protected(sta->link[link_id],
314                                              lockdep_is_held(&sta->local->sta_mtx));
315
316         if (WARN_ON(!link_sta))
317                 return;
318
319         if (unhash)
320                 link_sta_info_hash_del(sta->local, link_sta);
321
322         if (link_sta != &sta->deflink)
323                 alloc = container_of(link_sta, typeof(*alloc), info);
324
325         sta->sta.valid_links &= ~BIT(link_id);
326         RCU_INIT_POINTER(sta->link[link_id], NULL);
327         RCU_INIT_POINTER(sta->sta.link[link_id], NULL);
328         if (alloc) {
329                 sta_info_free_link(&alloc->info);
330                 kfree_rcu(alloc, rcu_head);
331         }
332 }
333
334 /**
335  * sta_info_free - free STA
336  *
337  * @local: pointer to the global information
338  * @sta: STA info to free
339  *
340  * This function must undo everything done by sta_info_alloc()
341  * that may happen before sta_info_insert(). It may only be
342  * called when sta_info_insert() has not been attempted (and
343  * if that fails, the station is freed anyway.)
344  */
345 void sta_info_free(struct ieee80211_local *local, struct sta_info *sta)
346 {
347         int i;
348
349         for (i = 0; i < ARRAY_SIZE(sta->link); i++) {
350                 if (!(sta->sta.valid_links & BIT(i)))
351                         continue;
352
353                 sta_remove_link(sta, i, true);
354         }
355
356         /*
357          * If we had used sta_info_pre_move_state() then we might not
358          * have gone through the state transitions down again, so do
359          * it here now (and warn if it's inserted).
360          *
361          * This will clear state such as fast TX/RX that may have been
362          * allocated during state transitions.
363          */
364         while (sta->sta_state > IEEE80211_STA_NONE) {
365                 int ret;
366
367                 WARN_ON_ONCE(test_sta_flag(sta, WLAN_STA_INSERTED));
368
369                 ret = sta_info_move_state(sta, sta->sta_state - 1);
370                 if (WARN_ONCE(ret, "sta_info_move_state() returned %d\n", ret))
371                         break;
372         }
373
374         if (sta->rate_ctrl)
375                 rate_control_free_sta(sta);
376
377         sta_dbg(sta->sdata, "Destroyed STA %pM\n", sta->sta.addr);
378
379         if (sta->sta.txq[0])
380                 kfree(to_txq_info(sta->sta.txq[0]));
381         kfree(rcu_dereference_raw(sta->sta.rates));
382 #ifdef CONFIG_MAC80211_MESH
383         kfree(sta->mesh);
384 #endif
385
386         sta_info_free_link(&sta->deflink);
387         kfree(sta);
388 }
389
390 /* Caller must hold local->sta_mtx */
391 static int sta_info_hash_add(struct ieee80211_local *local,
392                              struct sta_info *sta)
393 {
394         return rhltable_insert(&local->sta_hash, &sta->hash_node,
395                                sta_rht_params);
396 }
397
398 static void sta_deliver_ps_frames(struct work_struct *wk)
399 {
400         struct sta_info *sta;
401
402         sta = container_of(wk, struct sta_info, drv_deliver_wk);
403
404         if (sta->dead)
405                 return;
406
407         local_bh_disable();
408         if (!test_sta_flag(sta, WLAN_STA_PS_STA))
409                 ieee80211_sta_ps_deliver_wakeup(sta);
410         else if (test_and_clear_sta_flag(sta, WLAN_STA_PSPOLL))
411                 ieee80211_sta_ps_deliver_poll_response(sta);
412         else if (test_and_clear_sta_flag(sta, WLAN_STA_UAPSD))
413                 ieee80211_sta_ps_deliver_uapsd(sta);
414         local_bh_enable();
415 }
416
417 static int sta_prepare_rate_control(struct ieee80211_local *local,
418                                     struct sta_info *sta, gfp_t gfp)
419 {
420         if (ieee80211_hw_check(&local->hw, HAS_RATE_CONTROL))
421                 return 0;
422
423         sta->rate_ctrl = local->rate_ctrl;
424         sta->rate_ctrl_priv = rate_control_alloc_sta(sta->rate_ctrl,
425                                                      sta, gfp);
426         if (!sta->rate_ctrl_priv)
427                 return -ENOMEM;
428
429         return 0;
430 }
431
432 static int sta_info_alloc_link(struct ieee80211_local *local,
433                                struct link_sta_info *link_info,
434                                gfp_t gfp)
435 {
436         struct ieee80211_hw *hw = &local->hw;
437         int i;
438
439         if (ieee80211_hw_check(hw, USES_RSS)) {
440                 link_info->pcpu_rx_stats =
441                         alloc_percpu_gfp(struct ieee80211_sta_rx_stats, gfp);
442                 if (!link_info->pcpu_rx_stats)
443                         return -ENOMEM;
444         }
445
446         link_info->rx_stats.last_rx = jiffies;
447         u64_stats_init(&link_info->rx_stats.syncp);
448
449         ewma_signal_init(&link_info->rx_stats_avg.signal);
450         ewma_avg_signal_init(&link_info->status_stats.avg_ack_signal);
451         for (i = 0; i < ARRAY_SIZE(link_info->rx_stats_avg.chain_signal); i++)
452                 ewma_signal_init(&link_info->rx_stats_avg.chain_signal[i]);
453
454         return 0;
455 }
456
457 static void sta_info_add_link(struct sta_info *sta,
458                               unsigned int link_id,
459                               struct link_sta_info *link_info,
460                               struct ieee80211_link_sta *link_sta)
461 {
462         link_info->sta = sta;
463         link_info->link_id = link_id;
464         link_info->pub = link_sta;
465         rcu_assign_pointer(sta->link[link_id], link_info);
466         rcu_assign_pointer(sta->sta.link[link_id], link_sta);
467 }
468
469 struct sta_info *sta_info_alloc(struct ieee80211_sub_if_data *sdata,
470                                 const u8 *addr, int link_id, gfp_t gfp)
471 {
472         struct ieee80211_local *local = sdata->local;
473         struct ieee80211_hw *hw = &local->hw;
474         struct sta_info *sta;
475         int i;
476
477         sta = kzalloc(sizeof(*sta) + hw->sta_data_size, gfp);
478         if (!sta)
479                 return NULL;
480
481         sta->local = local;
482         sta->sdata = sdata;
483
484         if (sta_info_alloc_link(local, &sta->deflink, gfp))
485                 return NULL;
486
487         if (link_id >= 0) {
488                 sta_info_add_link(sta, link_id, &sta->deflink,
489                                   &sta->sta.deflink);
490                 sta->sta.valid_links = BIT(link_id);
491         } else {
492                 sta_info_add_link(sta, 0, &sta->deflink, &sta->sta.deflink);
493         }
494
495         spin_lock_init(&sta->lock);
496         spin_lock_init(&sta->ps_lock);
497         INIT_WORK(&sta->drv_deliver_wk, sta_deliver_ps_frames);
498         INIT_WORK(&sta->ampdu_mlme.work, ieee80211_ba_session_work);
499         mutex_init(&sta->ampdu_mlme.mtx);
500 #ifdef CONFIG_MAC80211_MESH
501         if (ieee80211_vif_is_mesh(&sdata->vif)) {
502                 sta->mesh = kzalloc(sizeof(*sta->mesh), gfp);
503                 if (!sta->mesh)
504                         goto free;
505                 sta->mesh->plink_sta = sta;
506                 spin_lock_init(&sta->mesh->plink_lock);
507                 if (!sdata->u.mesh.user_mpm)
508                         timer_setup(&sta->mesh->plink_timer, mesh_plink_timer,
509                                     0);
510                 sta->mesh->nonpeer_pm = NL80211_MESH_POWER_ACTIVE;
511         }
512 #endif
513
514         memcpy(sta->addr, addr, ETH_ALEN);
515         memcpy(sta->sta.addr, addr, ETH_ALEN);
516         memcpy(sta->deflink.addr, addr, ETH_ALEN);
517         memcpy(sta->sta.deflink.addr, addr, ETH_ALEN);
518         sta->sta.max_rx_aggregation_subframes =
519                 local->hw.max_rx_aggregation_subframes;
520
521         /* TODO link specific alloc and assignments for MLO Link STA */
522
523         /* Extended Key ID needs to install keys for keyid 0 and 1 Rx-only.
524          * The Tx path starts to use a key as soon as the key slot ptk_idx
525          * references to is not NULL. To not use the initial Rx-only key
526          * prematurely for Tx initialize ptk_idx to an impossible PTK keyid
527          * which always will refer to a NULL key.
528          */
529         BUILD_BUG_ON(ARRAY_SIZE(sta->ptk) <= INVALID_PTK_KEYIDX);
530         sta->ptk_idx = INVALID_PTK_KEYIDX;
531
532
533         ieee80211_init_frag_cache(&sta->frags);
534
535         sta->sta_state = IEEE80211_STA_NONE;
536
537         /* Mark TID as unreserved */
538         sta->reserved_tid = IEEE80211_TID_UNRESERVED;
539
540         sta->last_connected = ktime_get_seconds();
541
542         if (local->ops->wake_tx_queue) {
543                 void *txq_data;
544                 int size = sizeof(struct txq_info) +
545                            ALIGN(hw->txq_data_size, sizeof(void *));
546
547                 txq_data = kcalloc(ARRAY_SIZE(sta->sta.txq), size, gfp);
548                 if (!txq_data)
549                         goto free;
550
551                 for (i = 0; i < ARRAY_SIZE(sta->sta.txq); i++) {
552                         struct txq_info *txq = txq_data + i * size;
553
554                         /* might not do anything for the bufferable MMPDU TXQ */
555                         ieee80211_txq_init(sdata, sta, txq, i);
556                 }
557         }
558
559         if (sta_prepare_rate_control(local, sta, gfp))
560                 goto free_txq;
561
562         sta->airtime_weight = IEEE80211_DEFAULT_AIRTIME_WEIGHT;
563
564         for (i = 0; i < IEEE80211_NUM_ACS; i++) {
565                 skb_queue_head_init(&sta->ps_tx_buf[i]);
566                 skb_queue_head_init(&sta->tx_filtered[i]);
567                 sta->airtime[i].deficit = sta->airtime_weight;
568                 atomic_set(&sta->airtime[i].aql_tx_pending, 0);
569                 sta->airtime[i].aql_limit_low = local->aql_txq_limit_low[i];
570                 sta->airtime[i].aql_limit_high = local->aql_txq_limit_high[i];
571         }
572
573         for (i = 0; i < IEEE80211_NUM_TIDS; i++)
574                 sta->last_seq_ctrl[i] = cpu_to_le16(USHRT_MAX);
575
576         for (i = 0; i < NUM_NL80211_BANDS; i++) {
577                 u32 mandatory = 0;
578                 int r;
579
580                 if (!hw->wiphy->bands[i])
581                         continue;
582
583                 switch (i) {
584                 case NL80211_BAND_2GHZ:
585                 case NL80211_BAND_LC:
586                         /*
587                          * We use both here, even if we cannot really know for
588                          * sure the station will support both, but the only use
589                          * for this is when we don't know anything yet and send
590                          * management frames, and then we'll pick the lowest
591                          * possible rate anyway.
592                          * If we don't include _G here, we cannot find a rate
593                          * in P2P, and thus trigger the WARN_ONCE() in rate.c
594                          */
595                         mandatory = IEEE80211_RATE_MANDATORY_B |
596                                     IEEE80211_RATE_MANDATORY_G;
597                         break;
598                 case NL80211_BAND_5GHZ:
599                         mandatory = IEEE80211_RATE_MANDATORY_A;
600                         break;
601                 case NL80211_BAND_60GHZ:
602                         WARN_ON(1);
603                         mandatory = 0;
604                         break;
605                 }
606
607                 for (r = 0; r < hw->wiphy->bands[i]->n_bitrates; r++) {
608                         struct ieee80211_rate *rate;
609
610                         rate = &hw->wiphy->bands[i]->bitrates[r];
611
612                         if (!(rate->flags & mandatory))
613                                 continue;
614                         sta->sta.deflink.supp_rates[i] |= BIT(r);
615                 }
616         }
617
618         sta->sta.smps_mode = IEEE80211_SMPS_OFF;
619         sta->sta.max_rc_amsdu_len = IEEE80211_MAX_MPDU_LEN_HT_BA;
620
621         sta->cparams.ce_threshold = CODEL_DISABLED_THRESHOLD;
622         sta->cparams.target = MS2TIME(20);
623         sta->cparams.interval = MS2TIME(100);
624         sta->cparams.ecn = true;
625         sta->cparams.ce_threshold_selector = 0;
626         sta->cparams.ce_threshold_mask = 0;
627
628         sta_dbg(sdata, "Allocated STA %pM\n", sta->sta.addr);
629
630         return sta;
631
632 free_txq:
633         if (sta->sta.txq[0])
634                 kfree(to_txq_info(sta->sta.txq[0]));
635 free:
636         sta_info_free_link(&sta->deflink);
637 #ifdef CONFIG_MAC80211_MESH
638         kfree(sta->mesh);
639 #endif
640         kfree(sta);
641         return NULL;
642 }
643
644 static int sta_info_insert_check(struct sta_info *sta)
645 {
646         struct ieee80211_sub_if_data *sdata = sta->sdata;
647
648         /*
649          * Can't be a WARN_ON because it can be triggered through a race:
650          * something inserts a STA (on one CPU) without holding the RTNL
651          * and another CPU turns off the net device.
652          */
653         if (unlikely(!ieee80211_sdata_running(sdata)))
654                 return -ENETDOWN;
655
656         if (WARN_ON(ether_addr_equal(sta->sta.addr, sdata->vif.addr) ||
657                     !is_valid_ether_addr(sta->sta.addr)))
658                 return -EINVAL;
659
660         /* The RCU read lock is required by rhashtable due to
661          * asynchronous resize/rehash.  We also require the mutex
662          * for correctness.
663          */
664         rcu_read_lock();
665         lockdep_assert_held(&sdata->local->sta_mtx);
666         if (ieee80211_hw_check(&sdata->local->hw, NEEDS_UNIQUE_STA_ADDR) &&
667             ieee80211_find_sta_by_ifaddr(&sdata->local->hw, sta->addr, NULL)) {
668                 rcu_read_unlock();
669                 return -ENOTUNIQ;
670         }
671         rcu_read_unlock();
672
673         return 0;
674 }
675
676 static int sta_info_insert_drv_state(struct ieee80211_local *local,
677                                      struct ieee80211_sub_if_data *sdata,
678                                      struct sta_info *sta)
679 {
680         enum ieee80211_sta_state state;
681         int err = 0;
682
683         for (state = IEEE80211_STA_NOTEXIST; state < sta->sta_state; state++) {
684                 err = drv_sta_state(local, sdata, sta, state, state + 1);
685                 if (err)
686                         break;
687         }
688
689         if (!err) {
690                 /*
691                  * Drivers using legacy sta_add/sta_remove callbacks only
692                  * get uploaded set to true after sta_add is called.
693                  */
694                 if (!local->ops->sta_add)
695                         sta->uploaded = true;
696                 return 0;
697         }
698
699         if (sdata->vif.type == NL80211_IFTYPE_ADHOC) {
700                 sdata_info(sdata,
701                            "failed to move IBSS STA %pM to state %d (%d) - keeping it anyway\n",
702                            sta->sta.addr, state + 1, err);
703                 err = 0;
704         }
705
706         /* unwind on error */
707         for (; state > IEEE80211_STA_NOTEXIST; state--)
708                 WARN_ON(drv_sta_state(local, sdata, sta, state, state - 1));
709
710         return err;
711 }
712
713 static void
714 ieee80211_recalc_p2p_go_ps_allowed(struct ieee80211_sub_if_data *sdata)
715 {
716         struct ieee80211_local *local = sdata->local;
717         bool allow_p2p_go_ps = sdata->vif.p2p;
718         struct sta_info *sta;
719
720         rcu_read_lock();
721         list_for_each_entry_rcu(sta, &local->sta_list, list) {
722                 if (sdata != sta->sdata ||
723                     !test_sta_flag(sta, WLAN_STA_ASSOC))
724                         continue;
725                 if (!sta->sta.support_p2p_ps) {
726                         allow_p2p_go_ps = false;
727                         break;
728                 }
729         }
730         rcu_read_unlock();
731
732         if (allow_p2p_go_ps != sdata->vif.bss_conf.allow_p2p_go_ps) {
733                 sdata->vif.bss_conf.allow_p2p_go_ps = allow_p2p_go_ps;
734                 ieee80211_link_info_change_notify(sdata, &sdata->deflink,
735                                                   BSS_CHANGED_P2P_PS);
736         }
737 }
738
739 /*
740  * should be called with sta_mtx locked
741  * this function replaces the mutex lock
742  * with a RCU lock
743  */
744 static int sta_info_insert_finish(struct sta_info *sta) __acquires(RCU)
745 {
746         struct ieee80211_local *local = sta->local;
747         struct ieee80211_sub_if_data *sdata = sta->sdata;
748         struct station_info *sinfo = NULL;
749         int err = 0;
750
751         lockdep_assert_held(&local->sta_mtx);
752
753         /* check if STA exists already */
754         if (sta_info_get_bss(sdata, sta->sta.addr)) {
755                 err = -EEXIST;
756                 goto out_cleanup;
757         }
758
759         sinfo = kzalloc(sizeof(struct station_info), GFP_KERNEL);
760         if (!sinfo) {
761                 err = -ENOMEM;
762                 goto out_cleanup;
763         }
764
765         local->num_sta++;
766         local->sta_generation++;
767         smp_mb();
768
769         /* simplify things and don't accept BA sessions yet */
770         set_sta_flag(sta, WLAN_STA_BLOCK_BA);
771
772         /* make the station visible */
773         err = sta_info_hash_add(local, sta);
774         if (err)
775                 goto out_drop_sta;
776
777         list_add_tail_rcu(&sta->list, &local->sta_list);
778
779         /* update channel context before notifying the driver about state
780          * change, this enables driver using the updated channel context right away.
781          */
782         if (sta->sta_state >= IEEE80211_STA_ASSOC) {
783                 ieee80211_recalc_min_chandef(sta->sdata, -1);
784                 if (!sta->sta.support_p2p_ps)
785                         ieee80211_recalc_p2p_go_ps_allowed(sta->sdata);
786         }
787
788         /* notify driver */
789         err = sta_info_insert_drv_state(local, sdata, sta);
790         if (err)
791                 goto out_remove;
792
793         set_sta_flag(sta, WLAN_STA_INSERTED);
794
795         /* accept BA sessions now */
796         clear_sta_flag(sta, WLAN_STA_BLOCK_BA);
797
798         ieee80211_sta_debugfs_add(sta);
799         rate_control_add_sta_debugfs(sta);
800
801         sinfo->generation = local->sta_generation;
802         cfg80211_new_sta(sdata->dev, sta->sta.addr, sinfo, GFP_KERNEL);
803         kfree(sinfo);
804
805         sta_dbg(sdata, "Inserted STA %pM\n", sta->sta.addr);
806
807         /* move reference to rcu-protected */
808         rcu_read_lock();
809         mutex_unlock(&local->sta_mtx);
810
811         if (ieee80211_vif_is_mesh(&sdata->vif))
812                 mesh_accept_plinks_update(sdata);
813
814         return 0;
815  out_remove:
816         sta_info_hash_del(local, sta);
817         list_del_rcu(&sta->list);
818  out_drop_sta:
819         local->num_sta--;
820         synchronize_net();
821  out_cleanup:
822         cleanup_single_sta(sta);
823         mutex_unlock(&local->sta_mtx);
824         kfree(sinfo);
825         rcu_read_lock();
826         return err;
827 }
828
829 int sta_info_insert_rcu(struct sta_info *sta) __acquires(RCU)
830 {
831         struct ieee80211_local *local = sta->local;
832         int err;
833
834         might_sleep();
835
836         mutex_lock(&local->sta_mtx);
837
838         err = sta_info_insert_check(sta);
839         if (err) {
840                 sta_info_free(local, sta);
841                 mutex_unlock(&local->sta_mtx);
842                 rcu_read_lock();
843                 return err;
844         }
845
846         return sta_info_insert_finish(sta);
847 }
848
849 int sta_info_insert(struct sta_info *sta)
850 {
851         int err = sta_info_insert_rcu(sta);
852
853         rcu_read_unlock();
854
855         return err;
856 }
857
858 static inline void __bss_tim_set(u8 *tim, u16 id)
859 {
860         /*
861          * This format has been mandated by the IEEE specifications,
862          * so this line may not be changed to use the __set_bit() format.
863          */
864         tim[id / 8] |= (1 << (id % 8));
865 }
866
867 static inline void __bss_tim_clear(u8 *tim, u16 id)
868 {
869         /*
870          * This format has been mandated by the IEEE specifications,
871          * so this line may not be changed to use the __clear_bit() format.
872          */
873         tim[id / 8] &= ~(1 << (id % 8));
874 }
875
876 static inline bool __bss_tim_get(u8 *tim, u16 id)
877 {
878         /*
879          * This format has been mandated by the IEEE specifications,
880          * so this line may not be changed to use the test_bit() format.
881          */
882         return tim[id / 8] & (1 << (id % 8));
883 }
884
885 static unsigned long ieee80211_tids_for_ac(int ac)
886 {
887         /* If we ever support TIDs > 7, this obviously needs to be adjusted */
888         switch (ac) {
889         case IEEE80211_AC_VO:
890                 return BIT(6) | BIT(7);
891         case IEEE80211_AC_VI:
892                 return BIT(4) | BIT(5);
893         case IEEE80211_AC_BE:
894                 return BIT(0) | BIT(3);
895         case IEEE80211_AC_BK:
896                 return BIT(1) | BIT(2);
897         default:
898                 WARN_ON(1);
899                 return 0;
900         }
901 }
902
903 static void __sta_info_recalc_tim(struct sta_info *sta, bool ignore_pending)
904 {
905         struct ieee80211_local *local = sta->local;
906         struct ps_data *ps;
907         bool indicate_tim = false;
908         u8 ignore_for_tim = sta->sta.uapsd_queues;
909         int ac;
910         u16 id = sta->sta.aid;
911
912         if (sta->sdata->vif.type == NL80211_IFTYPE_AP ||
913             sta->sdata->vif.type == NL80211_IFTYPE_AP_VLAN) {
914                 if (WARN_ON_ONCE(!sta->sdata->bss))
915                         return;
916
917                 ps = &sta->sdata->bss->ps;
918 #ifdef CONFIG_MAC80211_MESH
919         } else if (ieee80211_vif_is_mesh(&sta->sdata->vif)) {
920                 ps = &sta->sdata->u.mesh.ps;
921 #endif
922         } else {
923                 return;
924         }
925
926         /* No need to do anything if the driver does all */
927         if (ieee80211_hw_check(&local->hw, AP_LINK_PS) && !local->ops->set_tim)
928                 return;
929
930         if (sta->dead)
931                 goto done;
932
933         /*
934          * If all ACs are delivery-enabled then we should build
935          * the TIM bit for all ACs anyway; if only some are then
936          * we ignore those and build the TIM bit using only the
937          * non-enabled ones.
938          */
939         if (ignore_for_tim == BIT(IEEE80211_NUM_ACS) - 1)
940                 ignore_for_tim = 0;
941
942         if (ignore_pending)
943                 ignore_for_tim = BIT(IEEE80211_NUM_ACS) - 1;
944
945         for (ac = 0; ac < IEEE80211_NUM_ACS; ac++) {
946                 unsigned long tids;
947
948                 if (ignore_for_tim & ieee80211_ac_to_qos_mask[ac])
949                         continue;
950
951                 indicate_tim |= !skb_queue_empty(&sta->tx_filtered[ac]) ||
952                                 !skb_queue_empty(&sta->ps_tx_buf[ac]);
953                 if (indicate_tim)
954                         break;
955
956                 tids = ieee80211_tids_for_ac(ac);
957
958                 indicate_tim |=
959                         sta->driver_buffered_tids & tids;
960                 indicate_tim |=
961                         sta->txq_buffered_tids & tids;
962         }
963
964  done:
965         spin_lock_bh(&local->tim_lock);
966
967         if (indicate_tim == __bss_tim_get(ps->tim, id))
968                 goto out_unlock;
969
970         if (indicate_tim)
971                 __bss_tim_set(ps->tim, id);
972         else
973                 __bss_tim_clear(ps->tim, id);
974
975         if (local->ops->set_tim && !WARN_ON(sta->dead)) {
976                 local->tim_in_locked_section = true;
977                 drv_set_tim(local, &sta->sta, indicate_tim);
978                 local->tim_in_locked_section = false;
979         }
980
981 out_unlock:
982         spin_unlock_bh(&local->tim_lock);
983 }
984
985 void sta_info_recalc_tim(struct sta_info *sta)
986 {
987         __sta_info_recalc_tim(sta, false);
988 }
989
990 static bool sta_info_buffer_expired(struct sta_info *sta, struct sk_buff *skb)
991 {
992         struct ieee80211_tx_info *info;
993         int timeout;
994
995         if (!skb)
996                 return false;
997
998         info = IEEE80211_SKB_CB(skb);
999
1000         /* Timeout: (2 * listen_interval * beacon_int * 1024 / 1000000) sec */
1001         timeout = (sta->listen_interval *
1002                    sta->sdata->vif.bss_conf.beacon_int *
1003                    32 / 15625) * HZ;
1004         if (timeout < STA_TX_BUFFER_EXPIRE)
1005                 timeout = STA_TX_BUFFER_EXPIRE;
1006         return time_after(jiffies, info->control.jiffies + timeout);
1007 }
1008
1009
1010 static bool sta_info_cleanup_expire_buffered_ac(struct ieee80211_local *local,
1011                                                 struct sta_info *sta, int ac)
1012 {
1013         unsigned long flags;
1014         struct sk_buff *skb;
1015
1016         /*
1017          * First check for frames that should expire on the filtered
1018          * queue. Frames here were rejected by the driver and are on
1019          * a separate queue to avoid reordering with normal PS-buffered
1020          * frames. They also aren't accounted for right now in the
1021          * total_ps_buffered counter.
1022          */
1023         for (;;) {
1024                 spin_lock_irqsave(&sta->tx_filtered[ac].lock, flags);
1025                 skb = skb_peek(&sta->tx_filtered[ac]);
1026                 if (sta_info_buffer_expired(sta, skb))
1027                         skb = __skb_dequeue(&sta->tx_filtered[ac]);
1028                 else
1029                         skb = NULL;
1030                 spin_unlock_irqrestore(&sta->tx_filtered[ac].lock, flags);
1031
1032                 /*
1033                  * Frames are queued in order, so if this one
1034                  * hasn't expired yet we can stop testing. If
1035                  * we actually reached the end of the queue we
1036                  * also need to stop, of course.
1037                  */
1038                 if (!skb)
1039                         break;
1040                 ieee80211_free_txskb(&local->hw, skb);
1041         }
1042
1043         /*
1044          * Now also check the normal PS-buffered queue, this will
1045          * only find something if the filtered queue was emptied
1046          * since the filtered frames are all before the normal PS
1047          * buffered frames.
1048          */
1049         for (;;) {
1050                 spin_lock_irqsave(&sta->ps_tx_buf[ac].lock, flags);
1051                 skb = skb_peek(&sta->ps_tx_buf[ac]);
1052                 if (sta_info_buffer_expired(sta, skb))
1053                         skb = __skb_dequeue(&sta->ps_tx_buf[ac]);
1054                 else
1055                         skb = NULL;
1056                 spin_unlock_irqrestore(&sta->ps_tx_buf[ac].lock, flags);
1057
1058                 /*
1059                  * frames are queued in order, so if this one
1060                  * hasn't expired yet (or we reached the end of
1061                  * the queue) we can stop testing
1062                  */
1063                 if (!skb)
1064                         break;
1065
1066                 local->total_ps_buffered--;
1067                 ps_dbg(sta->sdata, "Buffered frame expired (STA %pM)\n",
1068                        sta->sta.addr);
1069                 ieee80211_free_txskb(&local->hw, skb);
1070         }
1071
1072         /*
1073          * Finally, recalculate the TIM bit for this station -- it might
1074          * now be clear because the station was too slow to retrieve its
1075          * frames.
1076          */
1077         sta_info_recalc_tim(sta);
1078
1079         /*
1080          * Return whether there are any frames still buffered, this is
1081          * used to check whether the cleanup timer still needs to run,
1082          * if there are no frames we don't need to rearm the timer.
1083          */
1084         return !(skb_queue_empty(&sta->ps_tx_buf[ac]) &&
1085                  skb_queue_empty(&sta->tx_filtered[ac]));
1086 }
1087
1088 static bool sta_info_cleanup_expire_buffered(struct ieee80211_local *local,
1089                                              struct sta_info *sta)
1090 {
1091         bool have_buffered = false;
1092         int ac;
1093
1094         /* This is only necessary for stations on BSS/MBSS interfaces */
1095         if (!sta->sdata->bss &&
1096             !ieee80211_vif_is_mesh(&sta->sdata->vif))
1097                 return false;
1098
1099         for (ac = 0; ac < IEEE80211_NUM_ACS; ac++)
1100                 have_buffered |=
1101                         sta_info_cleanup_expire_buffered_ac(local, sta, ac);
1102
1103         return have_buffered;
1104 }
1105
1106 static int __must_check __sta_info_destroy_part1(struct sta_info *sta)
1107 {
1108         struct ieee80211_local *local;
1109         struct ieee80211_sub_if_data *sdata;
1110         int ret;
1111
1112         might_sleep();
1113
1114         if (!sta)
1115                 return -ENOENT;
1116
1117         local = sta->local;
1118         sdata = sta->sdata;
1119
1120         lockdep_assert_held(&local->sta_mtx);
1121
1122         /*
1123          * Before removing the station from the driver and
1124          * rate control, it might still start new aggregation
1125          * sessions -- block that to make sure the tear-down
1126          * will be sufficient.
1127          */
1128         set_sta_flag(sta, WLAN_STA_BLOCK_BA);
1129         ieee80211_sta_tear_down_BA_sessions(sta, AGG_STOP_DESTROY_STA);
1130
1131         /*
1132          * Before removing the station from the driver there might be pending
1133          * rx frames on RSS queues sent prior to the disassociation - wait for
1134          * all such frames to be processed.
1135          */
1136         drv_sync_rx_queues(local, sta);
1137
1138         ret = sta_info_hash_del(local, sta);
1139         if (WARN_ON(ret))
1140                 return ret;
1141
1142         /*
1143          * for TDLS peers, make sure to return to the base channel before
1144          * removal.
1145          */
1146         if (test_sta_flag(sta, WLAN_STA_TDLS_OFF_CHANNEL)) {
1147                 drv_tdls_cancel_channel_switch(local, sdata, &sta->sta);
1148                 clear_sta_flag(sta, WLAN_STA_TDLS_OFF_CHANNEL);
1149         }
1150
1151         list_del_rcu(&sta->list);
1152         sta->removed = true;
1153
1154         drv_sta_pre_rcu_remove(local, sta->sdata, sta);
1155
1156         if (sdata->vif.type == NL80211_IFTYPE_AP_VLAN &&
1157             rcu_access_pointer(sdata->u.vlan.sta) == sta)
1158                 RCU_INIT_POINTER(sdata->u.vlan.sta, NULL);
1159
1160         return 0;
1161 }
1162
1163 static void __sta_info_destroy_part2(struct sta_info *sta)
1164 {
1165         struct ieee80211_local *local = sta->local;
1166         struct ieee80211_sub_if_data *sdata = sta->sdata;
1167         struct station_info *sinfo;
1168         int ret;
1169
1170         /*
1171          * NOTE: This assumes at least synchronize_net() was done
1172          *       after _part1 and before _part2!
1173          */
1174
1175         might_sleep();
1176         lockdep_assert_held(&local->sta_mtx);
1177
1178         if (sta->sta_state == IEEE80211_STA_AUTHORIZED) {
1179                 ret = sta_info_move_state(sta, IEEE80211_STA_ASSOC);
1180                 WARN_ON_ONCE(ret);
1181         }
1182
1183         /* now keys can no longer be reached */
1184         ieee80211_free_sta_keys(local, sta);
1185
1186         /* disable TIM bit - last chance to tell driver */
1187         __sta_info_recalc_tim(sta, true);
1188
1189         sta->dead = true;
1190
1191         local->num_sta--;
1192         local->sta_generation++;
1193
1194         while (sta->sta_state > IEEE80211_STA_NONE) {
1195                 ret = sta_info_move_state(sta, sta->sta_state - 1);
1196                 if (ret) {
1197                         WARN_ON_ONCE(1);
1198                         break;
1199                 }
1200         }
1201
1202         if (sta->uploaded) {
1203                 ret = drv_sta_state(local, sdata, sta, IEEE80211_STA_NONE,
1204                                     IEEE80211_STA_NOTEXIST);
1205                 WARN_ON_ONCE(ret != 0);
1206         }
1207
1208         sta_dbg(sdata, "Removed STA %pM\n", sta->sta.addr);
1209
1210         sinfo = kzalloc(sizeof(*sinfo), GFP_KERNEL);
1211         if (sinfo)
1212                 sta_set_sinfo(sta, sinfo, true);
1213         cfg80211_del_sta_sinfo(sdata->dev, sta->sta.addr, sinfo, GFP_KERNEL);
1214         kfree(sinfo);
1215
1216         ieee80211_sta_debugfs_remove(sta);
1217
1218         ieee80211_destroy_frag_cache(&sta->frags);
1219
1220         cleanup_single_sta(sta);
1221 }
1222
1223 int __must_check __sta_info_destroy(struct sta_info *sta)
1224 {
1225         int err = __sta_info_destroy_part1(sta);
1226
1227         if (err)
1228                 return err;
1229
1230         synchronize_net();
1231
1232         __sta_info_destroy_part2(sta);
1233
1234         return 0;
1235 }
1236
1237 int sta_info_destroy_addr(struct ieee80211_sub_if_data *sdata, const u8 *addr)
1238 {
1239         struct sta_info *sta;
1240         int ret;
1241
1242         mutex_lock(&sdata->local->sta_mtx);
1243         sta = sta_info_get(sdata, addr);
1244         ret = __sta_info_destroy(sta);
1245         mutex_unlock(&sdata->local->sta_mtx);
1246
1247         return ret;
1248 }
1249
1250 int sta_info_destroy_addr_bss(struct ieee80211_sub_if_data *sdata,
1251                               const u8 *addr)
1252 {
1253         struct sta_info *sta;
1254         int ret;
1255
1256         mutex_lock(&sdata->local->sta_mtx);
1257         sta = sta_info_get_bss(sdata, addr);
1258         ret = __sta_info_destroy(sta);
1259         mutex_unlock(&sdata->local->sta_mtx);
1260
1261         return ret;
1262 }
1263
1264 static void sta_info_cleanup(struct timer_list *t)
1265 {
1266         struct ieee80211_local *local = from_timer(local, t, sta_cleanup);
1267         struct sta_info *sta;
1268         bool timer_needed = false;
1269
1270         rcu_read_lock();
1271         list_for_each_entry_rcu(sta, &local->sta_list, list)
1272                 if (sta_info_cleanup_expire_buffered(local, sta))
1273                         timer_needed = true;
1274         rcu_read_unlock();
1275
1276         if (local->quiescing)
1277                 return;
1278
1279         if (!timer_needed)
1280                 return;
1281
1282         mod_timer(&local->sta_cleanup,
1283                   round_jiffies(jiffies + STA_INFO_CLEANUP_INTERVAL));
1284 }
1285
1286 int sta_info_init(struct ieee80211_local *local)
1287 {
1288         int err;
1289
1290         err = rhltable_init(&local->sta_hash, &sta_rht_params);
1291         if (err)
1292                 return err;
1293
1294         err = rhltable_init(&local->link_sta_hash, &link_sta_rht_params);
1295         if (err) {
1296                 rhltable_destroy(&local->sta_hash);
1297                 return err;
1298         }
1299
1300         spin_lock_init(&local->tim_lock);
1301         mutex_init(&local->sta_mtx);
1302         INIT_LIST_HEAD(&local->sta_list);
1303
1304         timer_setup(&local->sta_cleanup, sta_info_cleanup, 0);
1305         return 0;
1306 }
1307
1308 void sta_info_stop(struct ieee80211_local *local)
1309 {
1310         del_timer_sync(&local->sta_cleanup);
1311         rhltable_destroy(&local->sta_hash);
1312         rhltable_destroy(&local->link_sta_hash);
1313 }
1314
1315
1316 int __sta_info_flush(struct ieee80211_sub_if_data *sdata, bool vlans)
1317 {
1318         struct ieee80211_local *local = sdata->local;
1319         struct sta_info *sta, *tmp;
1320         LIST_HEAD(free_list);
1321         int ret = 0;
1322
1323         might_sleep();
1324
1325         WARN_ON(vlans && sdata->vif.type != NL80211_IFTYPE_AP);
1326         WARN_ON(vlans && !sdata->bss);
1327
1328         mutex_lock(&local->sta_mtx);
1329         list_for_each_entry_safe(sta, tmp, &local->sta_list, list) {
1330                 if (sdata == sta->sdata ||
1331                     (vlans && sdata->bss == sta->sdata->bss)) {
1332                         if (!WARN_ON(__sta_info_destroy_part1(sta)))
1333                                 list_add(&sta->free_list, &free_list);
1334                         ret++;
1335                 }
1336         }
1337
1338         if (!list_empty(&free_list)) {
1339                 synchronize_net();
1340                 list_for_each_entry_safe(sta, tmp, &free_list, free_list)
1341                         __sta_info_destroy_part2(sta);
1342         }
1343         mutex_unlock(&local->sta_mtx);
1344
1345         return ret;
1346 }
1347
1348 void ieee80211_sta_expire(struct ieee80211_sub_if_data *sdata,
1349                           unsigned long exp_time)
1350 {
1351         struct ieee80211_local *local = sdata->local;
1352         struct sta_info *sta, *tmp;
1353
1354         mutex_lock(&local->sta_mtx);
1355
1356         list_for_each_entry_safe(sta, tmp, &local->sta_list, list) {
1357                 unsigned long last_active = ieee80211_sta_last_active(sta);
1358
1359                 if (sdata != sta->sdata)
1360                         continue;
1361
1362                 if (time_is_before_jiffies(last_active + exp_time)) {
1363                         sta_dbg(sta->sdata, "expiring inactive STA %pM\n",
1364                                 sta->sta.addr);
1365
1366                         if (ieee80211_vif_is_mesh(&sdata->vif) &&
1367                             test_sta_flag(sta, WLAN_STA_PS_STA))
1368                                 atomic_dec(&sdata->u.mesh.ps.num_sta_ps);
1369
1370                         WARN_ON(__sta_info_destroy(sta));
1371                 }
1372         }
1373
1374         mutex_unlock(&local->sta_mtx);
1375 }
1376
1377 struct ieee80211_sta *ieee80211_find_sta_by_ifaddr(struct ieee80211_hw *hw,
1378                                                    const u8 *addr,
1379                                                    const u8 *localaddr)
1380 {
1381         struct ieee80211_local *local = hw_to_local(hw);
1382         struct rhlist_head *tmp;
1383         struct sta_info *sta;
1384
1385         /*
1386          * Just return a random station if localaddr is NULL
1387          * ... first in list.
1388          */
1389         for_each_sta_info(local, addr, sta, tmp) {
1390                 if (localaddr &&
1391                     !ether_addr_equal(sta->sdata->vif.addr, localaddr))
1392                         continue;
1393                 if (!sta->uploaded)
1394                         return NULL;
1395                 return &sta->sta;
1396         }
1397
1398         return NULL;
1399 }
1400 EXPORT_SYMBOL_GPL(ieee80211_find_sta_by_ifaddr);
1401
1402 struct ieee80211_sta *ieee80211_find_sta(struct ieee80211_vif *vif,
1403                                          const u8 *addr)
1404 {
1405         struct sta_info *sta;
1406
1407         if (!vif)
1408                 return NULL;
1409
1410         sta = sta_info_get_bss(vif_to_sdata(vif), addr);
1411         if (!sta)
1412                 return NULL;
1413
1414         if (!sta->uploaded)
1415                 return NULL;
1416
1417         return &sta->sta;
1418 }
1419 EXPORT_SYMBOL(ieee80211_find_sta);
1420
1421 /* powersave support code */
1422 void ieee80211_sta_ps_deliver_wakeup(struct sta_info *sta)
1423 {
1424         struct ieee80211_sub_if_data *sdata = sta->sdata;
1425         struct ieee80211_local *local = sdata->local;
1426         struct sk_buff_head pending;
1427         int filtered = 0, buffered = 0, ac, i;
1428         unsigned long flags;
1429         struct ps_data *ps;
1430
1431         if (sdata->vif.type == NL80211_IFTYPE_AP_VLAN)
1432                 sdata = container_of(sdata->bss, struct ieee80211_sub_if_data,
1433                                      u.ap);
1434
1435         if (sdata->vif.type == NL80211_IFTYPE_AP)
1436                 ps = &sdata->bss->ps;
1437         else if (ieee80211_vif_is_mesh(&sdata->vif))
1438                 ps = &sdata->u.mesh.ps;
1439         else
1440                 return;
1441
1442         clear_sta_flag(sta, WLAN_STA_SP);
1443
1444         BUILD_BUG_ON(BITS_TO_LONGS(IEEE80211_NUM_TIDS) > 1);
1445         sta->driver_buffered_tids = 0;
1446         sta->txq_buffered_tids = 0;
1447
1448         if (!ieee80211_hw_check(&local->hw, AP_LINK_PS))
1449                 drv_sta_notify(local, sdata, STA_NOTIFY_AWAKE, &sta->sta);
1450
1451         for (i = 0; i < ARRAY_SIZE(sta->sta.txq); i++) {
1452                 if (!sta->sta.txq[i] || !txq_has_queue(sta->sta.txq[i]))
1453                         continue;
1454
1455                 schedule_and_wake_txq(local, to_txq_info(sta->sta.txq[i]));
1456         }
1457
1458         skb_queue_head_init(&pending);
1459
1460         /* sync with ieee80211_tx_h_unicast_ps_buf */
1461         spin_lock(&sta->ps_lock);
1462         /* Send all buffered frames to the station */
1463         for (ac = 0; ac < IEEE80211_NUM_ACS; ac++) {
1464                 int count = skb_queue_len(&pending), tmp;
1465
1466                 spin_lock_irqsave(&sta->tx_filtered[ac].lock, flags);
1467                 skb_queue_splice_tail_init(&sta->tx_filtered[ac], &pending);
1468                 spin_unlock_irqrestore(&sta->tx_filtered[ac].lock, flags);
1469                 tmp = skb_queue_len(&pending);
1470                 filtered += tmp - count;
1471                 count = tmp;
1472
1473                 spin_lock_irqsave(&sta->ps_tx_buf[ac].lock, flags);
1474                 skb_queue_splice_tail_init(&sta->ps_tx_buf[ac], &pending);
1475                 spin_unlock_irqrestore(&sta->ps_tx_buf[ac].lock, flags);
1476                 tmp = skb_queue_len(&pending);
1477                 buffered += tmp - count;
1478         }
1479
1480         ieee80211_add_pending_skbs(local, &pending);
1481
1482         /* now we're no longer in the deliver code */
1483         clear_sta_flag(sta, WLAN_STA_PS_DELIVER);
1484
1485         /* The station might have polled and then woken up before we responded,
1486          * so clear these flags now to avoid them sticking around.
1487          */
1488         clear_sta_flag(sta, WLAN_STA_PSPOLL);
1489         clear_sta_flag(sta, WLAN_STA_UAPSD);
1490         spin_unlock(&sta->ps_lock);
1491
1492         atomic_dec(&ps->num_sta_ps);
1493
1494         local->total_ps_buffered -= buffered;
1495
1496         sta_info_recalc_tim(sta);
1497
1498         ps_dbg(sdata,
1499                "STA %pM aid %d sending %d filtered/%d PS frames since STA woke up\n",
1500                sta->sta.addr, sta->sta.aid, filtered, buffered);
1501
1502         ieee80211_check_fast_xmit(sta);
1503 }
1504
1505 static void ieee80211_send_null_response(struct sta_info *sta, int tid,
1506                                          enum ieee80211_frame_release_type reason,
1507                                          bool call_driver, bool more_data)
1508 {
1509         struct ieee80211_sub_if_data *sdata = sta->sdata;
1510         struct ieee80211_local *local = sdata->local;
1511         struct ieee80211_qos_hdr *nullfunc;
1512         struct sk_buff *skb;
1513         int size = sizeof(*nullfunc);
1514         __le16 fc;
1515         bool qos = sta->sta.wme;
1516         struct ieee80211_tx_info *info;
1517         struct ieee80211_chanctx_conf *chanctx_conf;
1518
1519         if (qos) {
1520                 fc = cpu_to_le16(IEEE80211_FTYPE_DATA |
1521                                  IEEE80211_STYPE_QOS_NULLFUNC |
1522                                  IEEE80211_FCTL_FROMDS);
1523         } else {
1524                 size -= 2;
1525                 fc = cpu_to_le16(IEEE80211_FTYPE_DATA |
1526                                  IEEE80211_STYPE_NULLFUNC |
1527                                  IEEE80211_FCTL_FROMDS);
1528         }
1529
1530         skb = dev_alloc_skb(local->hw.extra_tx_headroom + size);
1531         if (!skb)
1532                 return;
1533
1534         skb_reserve(skb, local->hw.extra_tx_headroom);
1535
1536         nullfunc = skb_put(skb, size);
1537         nullfunc->frame_control = fc;
1538         nullfunc->duration_id = 0;
1539         memcpy(nullfunc->addr1, sta->sta.addr, ETH_ALEN);
1540         memcpy(nullfunc->addr2, sdata->vif.addr, ETH_ALEN);
1541         memcpy(nullfunc->addr3, sdata->vif.addr, ETH_ALEN);
1542         nullfunc->seq_ctrl = 0;
1543
1544         skb->priority = tid;
1545         skb_set_queue_mapping(skb, ieee802_1d_to_ac[tid]);
1546         if (qos) {
1547                 nullfunc->qos_ctrl = cpu_to_le16(tid);
1548
1549                 if (reason == IEEE80211_FRAME_RELEASE_UAPSD) {
1550                         nullfunc->qos_ctrl |=
1551                                 cpu_to_le16(IEEE80211_QOS_CTL_EOSP);
1552                         if (more_data)
1553                                 nullfunc->frame_control |=
1554                                         cpu_to_le16(IEEE80211_FCTL_MOREDATA);
1555                 }
1556         }
1557
1558         info = IEEE80211_SKB_CB(skb);
1559
1560         /*
1561          * Tell TX path to send this frame even though the
1562          * STA may still remain is PS mode after this frame
1563          * exchange. Also set EOSP to indicate this packet
1564          * ends the poll/service period.
1565          */
1566         info->flags |= IEEE80211_TX_CTL_NO_PS_BUFFER |
1567                        IEEE80211_TX_STATUS_EOSP |
1568                        IEEE80211_TX_CTL_REQ_TX_STATUS;
1569
1570         info->control.flags |= IEEE80211_TX_CTRL_PS_RESPONSE;
1571
1572         if (call_driver)
1573                 drv_allow_buffered_frames(local, sta, BIT(tid), 1,
1574                                           reason, false);
1575
1576         skb->dev = sdata->dev;
1577
1578         rcu_read_lock();
1579         chanctx_conf = rcu_dereference(sdata->vif.bss_conf.chanctx_conf);
1580         if (WARN_ON(!chanctx_conf)) {
1581                 rcu_read_unlock();
1582                 kfree_skb(skb);
1583                 return;
1584         }
1585
1586         info->band = chanctx_conf->def.chan->band;
1587         ieee80211_xmit(sdata, sta, skb);
1588         rcu_read_unlock();
1589 }
1590
1591 static int find_highest_prio_tid(unsigned long tids)
1592 {
1593         /* lower 3 TIDs aren't ordered perfectly */
1594         if (tids & 0xF8)
1595                 return fls(tids) - 1;
1596         /* TID 0 is BE just like TID 3 */
1597         if (tids & BIT(0))
1598                 return 0;
1599         return fls(tids) - 1;
1600 }
1601
1602 /* Indicates if the MORE_DATA bit should be set in the last
1603  * frame obtained by ieee80211_sta_ps_get_frames.
1604  * Note that driver_release_tids is relevant only if
1605  * reason = IEEE80211_FRAME_RELEASE_PSPOLL
1606  */
1607 static bool
1608 ieee80211_sta_ps_more_data(struct sta_info *sta, u8 ignored_acs,
1609                            enum ieee80211_frame_release_type reason,
1610                            unsigned long driver_release_tids)
1611 {
1612         int ac;
1613
1614         /* If the driver has data on more than one TID then
1615          * certainly there's more data if we release just a
1616          * single frame now (from a single TID). This will
1617          * only happen for PS-Poll.
1618          */
1619         if (reason == IEEE80211_FRAME_RELEASE_PSPOLL &&
1620             hweight16(driver_release_tids) > 1)
1621                 return true;
1622
1623         for (ac = 0; ac < IEEE80211_NUM_ACS; ac++) {
1624                 if (ignored_acs & ieee80211_ac_to_qos_mask[ac])
1625                         continue;
1626
1627                 if (!skb_queue_empty(&sta->tx_filtered[ac]) ||
1628                     !skb_queue_empty(&sta->ps_tx_buf[ac]))
1629                         return true;
1630         }
1631
1632         return false;
1633 }
1634
1635 static void
1636 ieee80211_sta_ps_get_frames(struct sta_info *sta, int n_frames, u8 ignored_acs,
1637                             enum ieee80211_frame_release_type reason,
1638                             struct sk_buff_head *frames,
1639                             unsigned long *driver_release_tids)
1640 {
1641         struct ieee80211_sub_if_data *sdata = sta->sdata;
1642         struct ieee80211_local *local = sdata->local;
1643         int ac;
1644
1645         /* Get response frame(s) and more data bit for the last one. */
1646         for (ac = 0; ac < IEEE80211_NUM_ACS; ac++) {
1647                 unsigned long tids;
1648
1649                 if (ignored_acs & ieee80211_ac_to_qos_mask[ac])
1650                         continue;
1651
1652                 tids = ieee80211_tids_for_ac(ac);
1653
1654                 /* if we already have frames from software, then we can't also
1655                  * release from hardware queues
1656                  */
1657                 if (skb_queue_empty(frames)) {
1658                         *driver_release_tids |=
1659                                 sta->driver_buffered_tids & tids;
1660                         *driver_release_tids |= sta->txq_buffered_tids & tids;
1661                 }
1662
1663                 if (!*driver_release_tids) {
1664                         struct sk_buff *skb;
1665
1666                         while (n_frames > 0) {
1667                                 skb = skb_dequeue(&sta->tx_filtered[ac]);
1668                                 if (!skb) {
1669                                         skb = skb_dequeue(
1670                                                 &sta->ps_tx_buf[ac]);
1671                                         if (skb)
1672                                                 local->total_ps_buffered--;
1673                                 }
1674                                 if (!skb)
1675                                         break;
1676                                 n_frames--;
1677                                 __skb_queue_tail(frames, skb);
1678                         }
1679                 }
1680
1681                 /* If we have more frames buffered on this AC, then abort the
1682                  * loop since we can't send more data from other ACs before
1683                  * the buffered frames from this.
1684                  */
1685                 if (!skb_queue_empty(&sta->tx_filtered[ac]) ||
1686                     !skb_queue_empty(&sta->ps_tx_buf[ac]))
1687                         break;
1688         }
1689 }
1690
1691 static void
1692 ieee80211_sta_ps_deliver_response(struct sta_info *sta,
1693                                   int n_frames, u8 ignored_acs,
1694                                   enum ieee80211_frame_release_type reason)
1695 {
1696         struct ieee80211_sub_if_data *sdata = sta->sdata;
1697         struct ieee80211_local *local = sdata->local;
1698         unsigned long driver_release_tids = 0;
1699         struct sk_buff_head frames;
1700         bool more_data;
1701
1702         /* Service or PS-Poll period starts */
1703         set_sta_flag(sta, WLAN_STA_SP);
1704
1705         __skb_queue_head_init(&frames);
1706
1707         ieee80211_sta_ps_get_frames(sta, n_frames, ignored_acs, reason,
1708                                     &frames, &driver_release_tids);
1709
1710         more_data = ieee80211_sta_ps_more_data(sta, ignored_acs, reason, driver_release_tids);
1711
1712         if (driver_release_tids && reason == IEEE80211_FRAME_RELEASE_PSPOLL)
1713                 driver_release_tids =
1714                         BIT(find_highest_prio_tid(driver_release_tids));
1715
1716         if (skb_queue_empty(&frames) && !driver_release_tids) {
1717                 int tid, ac;
1718
1719                 /*
1720                  * For PS-Poll, this can only happen due to a race condition
1721                  * when we set the TIM bit and the station notices it, but
1722                  * before it can poll for the frame we expire it.
1723                  *
1724                  * For uAPSD, this is said in the standard (11.2.1.5 h):
1725                  *      At each unscheduled SP for a non-AP STA, the AP shall
1726                  *      attempt to transmit at least one MSDU or MMPDU, but no
1727                  *      more than the value specified in the Max SP Length field
1728                  *      in the QoS Capability element from delivery-enabled ACs,
1729                  *      that are destined for the non-AP STA.
1730                  *
1731                  * Since we have no other MSDU/MMPDU, transmit a QoS null frame.
1732                  */
1733
1734                 /* This will evaluate to 1, 3, 5 or 7. */
1735                 for (ac = IEEE80211_AC_VO; ac < IEEE80211_NUM_ACS; ac++)
1736                         if (!(ignored_acs & ieee80211_ac_to_qos_mask[ac]))
1737                                 break;
1738                 tid = 7 - 2 * ac;
1739
1740                 ieee80211_send_null_response(sta, tid, reason, true, false);
1741         } else if (!driver_release_tids) {
1742                 struct sk_buff_head pending;
1743                 struct sk_buff *skb;
1744                 int num = 0;
1745                 u16 tids = 0;
1746                 bool need_null = false;
1747
1748                 skb_queue_head_init(&pending);
1749
1750                 while ((skb = __skb_dequeue(&frames))) {
1751                         struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
1752                         struct ieee80211_hdr *hdr = (void *) skb->data;
1753                         u8 *qoshdr = NULL;
1754
1755                         num++;
1756
1757                         /*
1758                          * Tell TX path to send this frame even though the
1759                          * STA may still remain is PS mode after this frame
1760                          * exchange.
1761                          */
1762                         info->flags |= IEEE80211_TX_CTL_NO_PS_BUFFER;
1763                         info->control.flags |= IEEE80211_TX_CTRL_PS_RESPONSE;
1764
1765                         /*
1766                          * Use MoreData flag to indicate whether there are
1767                          * more buffered frames for this STA
1768                          */
1769                         if (more_data || !skb_queue_empty(&frames))
1770                                 hdr->frame_control |=
1771                                         cpu_to_le16(IEEE80211_FCTL_MOREDATA);
1772                         else
1773                                 hdr->frame_control &=
1774                                         cpu_to_le16(~IEEE80211_FCTL_MOREDATA);
1775
1776                         if (ieee80211_is_data_qos(hdr->frame_control) ||
1777                             ieee80211_is_qos_nullfunc(hdr->frame_control))
1778                                 qoshdr = ieee80211_get_qos_ctl(hdr);
1779
1780                         tids |= BIT(skb->priority);
1781
1782                         __skb_queue_tail(&pending, skb);
1783
1784                         /* end service period after last frame or add one */
1785                         if (!skb_queue_empty(&frames))
1786                                 continue;
1787
1788                         if (reason != IEEE80211_FRAME_RELEASE_UAPSD) {
1789                                 /* for PS-Poll, there's only one frame */
1790                                 info->flags |= IEEE80211_TX_STATUS_EOSP |
1791                                                IEEE80211_TX_CTL_REQ_TX_STATUS;
1792                                 break;
1793                         }
1794
1795                         /* For uAPSD, things are a bit more complicated. If the
1796                          * last frame has a QoS header (i.e. is a QoS-data or
1797                          * QoS-nulldata frame) then just set the EOSP bit there
1798                          * and be done.
1799                          * If the frame doesn't have a QoS header (which means
1800                          * it should be a bufferable MMPDU) then we can't set
1801                          * the EOSP bit in the QoS header; add a QoS-nulldata
1802                          * frame to the list to send it after the MMPDU.
1803                          *
1804                          * Note that this code is only in the mac80211-release
1805                          * code path, we assume that the driver will not buffer
1806                          * anything but QoS-data frames, or if it does, will
1807                          * create the QoS-nulldata frame by itself if needed.
1808                          *
1809                          * Cf. 802.11-2012 10.2.1.10 (c).
1810                          */
1811                         if (qoshdr) {
1812                                 *qoshdr |= IEEE80211_QOS_CTL_EOSP;
1813
1814                                 info->flags |= IEEE80211_TX_STATUS_EOSP |
1815                                                IEEE80211_TX_CTL_REQ_TX_STATUS;
1816                         } else {
1817                                 /* The standard isn't completely clear on this
1818                                  * as it says the more-data bit should be set
1819                                  * if there are more BUs. The QoS-Null frame
1820                                  * we're about to send isn't buffered yet, we
1821                                  * only create it below, but let's pretend it
1822                                  * was buffered just in case some clients only
1823                                  * expect more-data=0 when eosp=1.
1824                                  */
1825                                 hdr->frame_control |=
1826                                         cpu_to_le16(IEEE80211_FCTL_MOREDATA);
1827                                 need_null = true;
1828                                 num++;
1829                         }
1830                         break;
1831                 }
1832
1833                 drv_allow_buffered_frames(local, sta, tids, num,
1834                                           reason, more_data);
1835
1836                 ieee80211_add_pending_skbs(local, &pending);
1837
1838                 if (need_null)
1839                         ieee80211_send_null_response(
1840                                 sta, find_highest_prio_tid(tids),
1841                                 reason, false, false);
1842
1843                 sta_info_recalc_tim(sta);
1844         } else {
1845                 int tid;
1846
1847                 /*
1848                  * We need to release a frame that is buffered somewhere in the
1849                  * driver ... it'll have to handle that.
1850                  * Note that the driver also has to check the number of frames
1851                  * on the TIDs we're releasing from - if there are more than
1852                  * n_frames it has to set the more-data bit (if we didn't ask
1853                  * it to set it anyway due to other buffered frames); if there
1854                  * are fewer than n_frames it has to make sure to adjust that
1855                  * to allow the service period to end properly.
1856                  */
1857                 drv_release_buffered_frames(local, sta, driver_release_tids,
1858                                             n_frames, reason, more_data);
1859
1860                 /*
1861                  * Note that we don't recalculate the TIM bit here as it would
1862                  * most likely have no effect at all unless the driver told us
1863                  * that the TID(s) became empty before returning here from the
1864                  * release function.
1865                  * Either way, however, when the driver tells us that the TID(s)
1866                  * became empty or we find that a txq became empty, we'll do the
1867                  * TIM recalculation.
1868                  */
1869
1870                 if (!sta->sta.txq[0])
1871                         return;
1872
1873                 for (tid = 0; tid < ARRAY_SIZE(sta->sta.txq); tid++) {
1874                         if (!sta->sta.txq[tid] ||
1875                             !(driver_release_tids & BIT(tid)) ||
1876                             txq_has_queue(sta->sta.txq[tid]))
1877                                 continue;
1878
1879                         sta_info_recalc_tim(sta);
1880                         break;
1881                 }
1882         }
1883 }
1884
1885 void ieee80211_sta_ps_deliver_poll_response(struct sta_info *sta)
1886 {
1887         u8 ignore_for_response = sta->sta.uapsd_queues;
1888
1889         /*
1890          * If all ACs are delivery-enabled then we should reply
1891          * from any of them, if only some are enabled we reply
1892          * only from the non-enabled ones.
1893          */
1894         if (ignore_for_response == BIT(IEEE80211_NUM_ACS) - 1)
1895                 ignore_for_response = 0;
1896
1897         ieee80211_sta_ps_deliver_response(sta, 1, ignore_for_response,
1898                                           IEEE80211_FRAME_RELEASE_PSPOLL);
1899 }
1900
1901 void ieee80211_sta_ps_deliver_uapsd(struct sta_info *sta)
1902 {
1903         int n_frames = sta->sta.max_sp;
1904         u8 delivery_enabled = sta->sta.uapsd_queues;
1905
1906         /*
1907          * If we ever grow support for TSPEC this might happen if
1908          * the TSPEC update from hostapd comes in between a trigger
1909          * frame setting WLAN_STA_UAPSD in the RX path and this
1910          * actually getting called.
1911          */
1912         if (!delivery_enabled)
1913                 return;
1914
1915         switch (sta->sta.max_sp) {
1916         case 1:
1917                 n_frames = 2;
1918                 break;
1919         case 2:
1920                 n_frames = 4;
1921                 break;
1922         case 3:
1923                 n_frames = 6;
1924                 break;
1925         case 0:
1926                 /* XXX: what is a good value? */
1927                 n_frames = 128;
1928                 break;
1929         }
1930
1931         ieee80211_sta_ps_deliver_response(sta, n_frames, ~delivery_enabled,
1932                                           IEEE80211_FRAME_RELEASE_UAPSD);
1933 }
1934
1935 void ieee80211_sta_block_awake(struct ieee80211_hw *hw,
1936                                struct ieee80211_sta *pubsta, bool block)
1937 {
1938         struct sta_info *sta = container_of(pubsta, struct sta_info, sta);
1939
1940         trace_api_sta_block_awake(sta->local, pubsta, block);
1941
1942         if (block) {
1943                 set_sta_flag(sta, WLAN_STA_PS_DRIVER);
1944                 ieee80211_clear_fast_xmit(sta);
1945                 return;
1946         }
1947
1948         if (!test_sta_flag(sta, WLAN_STA_PS_DRIVER))
1949                 return;
1950
1951         if (!test_sta_flag(sta, WLAN_STA_PS_STA)) {
1952                 set_sta_flag(sta, WLAN_STA_PS_DELIVER);
1953                 clear_sta_flag(sta, WLAN_STA_PS_DRIVER);
1954                 ieee80211_queue_work(hw, &sta->drv_deliver_wk);
1955         } else if (test_sta_flag(sta, WLAN_STA_PSPOLL) ||
1956                    test_sta_flag(sta, WLAN_STA_UAPSD)) {
1957                 /* must be asleep in this case */
1958                 clear_sta_flag(sta, WLAN_STA_PS_DRIVER);
1959                 ieee80211_queue_work(hw, &sta->drv_deliver_wk);
1960         } else {
1961                 clear_sta_flag(sta, WLAN_STA_PS_DRIVER);
1962                 ieee80211_check_fast_xmit(sta);
1963         }
1964 }
1965 EXPORT_SYMBOL(ieee80211_sta_block_awake);
1966
1967 void ieee80211_sta_eosp(struct ieee80211_sta *pubsta)
1968 {
1969         struct sta_info *sta = container_of(pubsta, struct sta_info, sta);
1970         struct ieee80211_local *local = sta->local;
1971
1972         trace_api_eosp(local, pubsta);
1973
1974         clear_sta_flag(sta, WLAN_STA_SP);
1975 }
1976 EXPORT_SYMBOL(ieee80211_sta_eosp);
1977
1978 void ieee80211_send_eosp_nullfunc(struct ieee80211_sta *pubsta, int tid)
1979 {
1980         struct sta_info *sta = container_of(pubsta, struct sta_info, sta);
1981         enum ieee80211_frame_release_type reason;
1982         bool more_data;
1983
1984         trace_api_send_eosp_nullfunc(sta->local, pubsta, tid);
1985
1986         reason = IEEE80211_FRAME_RELEASE_UAPSD;
1987         more_data = ieee80211_sta_ps_more_data(sta, ~sta->sta.uapsd_queues,
1988                                                reason, 0);
1989
1990         ieee80211_send_null_response(sta, tid, reason, false, more_data);
1991 }
1992 EXPORT_SYMBOL(ieee80211_send_eosp_nullfunc);
1993
1994 void ieee80211_sta_set_buffered(struct ieee80211_sta *pubsta,
1995                                 u8 tid, bool buffered)
1996 {
1997         struct sta_info *sta = container_of(pubsta, struct sta_info, sta);
1998
1999         if (WARN_ON(tid >= IEEE80211_NUM_TIDS))
2000                 return;
2001
2002         trace_api_sta_set_buffered(sta->local, pubsta, tid, buffered);
2003
2004         if (buffered)
2005                 set_bit(tid, &sta->driver_buffered_tids);
2006         else
2007                 clear_bit(tid, &sta->driver_buffered_tids);
2008
2009         sta_info_recalc_tim(sta);
2010 }
2011 EXPORT_SYMBOL(ieee80211_sta_set_buffered);
2012
2013 void ieee80211_sta_register_airtime(struct ieee80211_sta *pubsta, u8 tid,
2014                                     u32 tx_airtime, u32 rx_airtime)
2015 {
2016         struct sta_info *sta = container_of(pubsta, struct sta_info, sta);
2017         struct ieee80211_local *local = sta->sdata->local;
2018         u8 ac = ieee80211_ac_from_tid(tid);
2019         u32 airtime = 0;
2020         u32 diff;
2021
2022         if (sta->local->airtime_flags & AIRTIME_USE_TX)
2023                 airtime += tx_airtime;
2024         if (sta->local->airtime_flags & AIRTIME_USE_RX)
2025                 airtime += rx_airtime;
2026
2027         spin_lock_bh(&local->active_txq_lock[ac]);
2028         sta->airtime[ac].tx_airtime += tx_airtime;
2029         sta->airtime[ac].rx_airtime += rx_airtime;
2030
2031         diff = (u32)jiffies - sta->airtime[ac].last_active;
2032         if (diff <= AIRTIME_ACTIVE_DURATION)
2033                 sta->airtime[ac].deficit -= airtime;
2034
2035         spin_unlock_bh(&local->active_txq_lock[ac]);
2036 }
2037 EXPORT_SYMBOL(ieee80211_sta_register_airtime);
2038
2039 void ieee80211_sta_update_pending_airtime(struct ieee80211_local *local,
2040                                           struct sta_info *sta, u8 ac,
2041                                           u16 tx_airtime, bool tx_completed)
2042 {
2043         int tx_pending;
2044
2045         if (!wiphy_ext_feature_isset(local->hw.wiphy, NL80211_EXT_FEATURE_AQL))
2046                 return;
2047
2048         if (!tx_completed) {
2049                 if (sta)
2050                         atomic_add(tx_airtime,
2051                                    &sta->airtime[ac].aql_tx_pending);
2052
2053                 atomic_add(tx_airtime, &local->aql_total_pending_airtime);
2054                 atomic_add(tx_airtime, &local->aql_ac_pending_airtime[ac]);
2055                 return;
2056         }
2057
2058         if (sta) {
2059                 tx_pending = atomic_sub_return(tx_airtime,
2060                                                &sta->airtime[ac].aql_tx_pending);
2061                 if (tx_pending < 0)
2062                         atomic_cmpxchg(&sta->airtime[ac].aql_tx_pending,
2063                                        tx_pending, 0);
2064         }
2065
2066         atomic_sub(tx_airtime, &local->aql_total_pending_airtime);
2067         tx_pending = atomic_sub_return(tx_airtime,
2068                                        &local->aql_ac_pending_airtime[ac]);
2069         if (WARN_ONCE(tx_pending < 0,
2070                       "Device %s AC %d pending airtime underflow: %u, %u",
2071                       wiphy_name(local->hw.wiphy), ac, tx_pending,
2072                       tx_airtime)) {
2073                 atomic_cmpxchg(&local->aql_ac_pending_airtime[ac],
2074                                tx_pending, 0);
2075                 atomic_sub(tx_pending, &local->aql_total_pending_airtime);
2076         }
2077 }
2078
2079 int sta_info_move_state(struct sta_info *sta,
2080                         enum ieee80211_sta_state new_state)
2081 {
2082         might_sleep();
2083
2084         if (sta->sta_state == new_state)
2085                 return 0;
2086
2087         /* check allowed transitions first */
2088
2089         switch (new_state) {
2090         case IEEE80211_STA_NONE:
2091                 if (sta->sta_state != IEEE80211_STA_AUTH)
2092                         return -EINVAL;
2093                 break;
2094         case IEEE80211_STA_AUTH:
2095                 if (sta->sta_state != IEEE80211_STA_NONE &&
2096                     sta->sta_state != IEEE80211_STA_ASSOC)
2097                         return -EINVAL;
2098                 break;
2099         case IEEE80211_STA_ASSOC:
2100                 if (sta->sta_state != IEEE80211_STA_AUTH &&
2101                     sta->sta_state != IEEE80211_STA_AUTHORIZED)
2102                         return -EINVAL;
2103                 break;
2104         case IEEE80211_STA_AUTHORIZED:
2105                 if (sta->sta_state != IEEE80211_STA_ASSOC)
2106                         return -EINVAL;
2107                 break;
2108         default:
2109                 WARN(1, "invalid state %d", new_state);
2110                 return -EINVAL;
2111         }
2112
2113         sta_dbg(sta->sdata, "moving STA %pM to state %d\n",
2114                 sta->sta.addr, new_state);
2115
2116         /*
2117          * notify the driver before the actual changes so it can
2118          * fail the transition
2119          */
2120         if (test_sta_flag(sta, WLAN_STA_INSERTED)) {
2121                 int err = drv_sta_state(sta->local, sta->sdata, sta,
2122                                         sta->sta_state, new_state);
2123                 if (err)
2124                         return err;
2125         }
2126
2127         /* reflect the change in all state variables */
2128
2129         switch (new_state) {
2130         case IEEE80211_STA_NONE:
2131                 if (sta->sta_state == IEEE80211_STA_AUTH)
2132                         clear_bit(WLAN_STA_AUTH, &sta->_flags);
2133                 break;
2134         case IEEE80211_STA_AUTH:
2135                 if (sta->sta_state == IEEE80211_STA_NONE) {
2136                         set_bit(WLAN_STA_AUTH, &sta->_flags);
2137                 } else if (sta->sta_state == IEEE80211_STA_ASSOC) {
2138                         clear_bit(WLAN_STA_ASSOC, &sta->_flags);
2139                         ieee80211_recalc_min_chandef(sta->sdata, -1);
2140                         if (!sta->sta.support_p2p_ps)
2141                                 ieee80211_recalc_p2p_go_ps_allowed(sta->sdata);
2142                 }
2143                 break;
2144         case IEEE80211_STA_ASSOC:
2145                 if (sta->sta_state == IEEE80211_STA_AUTH) {
2146                         set_bit(WLAN_STA_ASSOC, &sta->_flags);
2147                         sta->assoc_at = ktime_get_boottime_ns();
2148                         ieee80211_recalc_min_chandef(sta->sdata, -1);
2149                         if (!sta->sta.support_p2p_ps)
2150                                 ieee80211_recalc_p2p_go_ps_allowed(sta->sdata);
2151                 } else if (sta->sta_state == IEEE80211_STA_AUTHORIZED) {
2152                         ieee80211_vif_dec_num_mcast(sta->sdata);
2153                         clear_bit(WLAN_STA_AUTHORIZED, &sta->_flags);
2154                         ieee80211_clear_fast_xmit(sta);
2155                         ieee80211_clear_fast_rx(sta);
2156                 }
2157                 break;
2158         case IEEE80211_STA_AUTHORIZED:
2159                 if (sta->sta_state == IEEE80211_STA_ASSOC) {
2160                         ieee80211_vif_inc_num_mcast(sta->sdata);
2161                         set_bit(WLAN_STA_AUTHORIZED, &sta->_flags);
2162                         ieee80211_check_fast_xmit(sta);
2163                         ieee80211_check_fast_rx(sta);
2164                 }
2165                 if (sta->sdata->vif.type == NL80211_IFTYPE_AP_VLAN ||
2166                     sta->sdata->vif.type == NL80211_IFTYPE_AP)
2167                         cfg80211_send_layer2_update(sta->sdata->dev,
2168                                                     sta->sta.addr);
2169                 break;
2170         default:
2171                 break;
2172         }
2173
2174         sta->sta_state = new_state;
2175
2176         return 0;
2177 }
2178
2179 static struct ieee80211_sta_rx_stats *
2180 sta_get_last_rx_stats(struct sta_info *sta)
2181 {
2182         struct ieee80211_sta_rx_stats *stats = &sta->deflink.rx_stats;
2183         int cpu;
2184
2185         if (!sta->deflink.pcpu_rx_stats)
2186                 return stats;
2187
2188         for_each_possible_cpu(cpu) {
2189                 struct ieee80211_sta_rx_stats *cpustats;
2190
2191                 cpustats = per_cpu_ptr(sta->deflink.pcpu_rx_stats, cpu);
2192
2193                 if (time_after(cpustats->last_rx, stats->last_rx))
2194                         stats = cpustats;
2195         }
2196
2197         return stats;
2198 }
2199
2200 static void sta_stats_decode_rate(struct ieee80211_local *local, u32 rate,
2201                                   struct rate_info *rinfo)
2202 {
2203         rinfo->bw = STA_STATS_GET(BW, rate);
2204
2205         switch (STA_STATS_GET(TYPE, rate)) {
2206         case STA_STATS_RATE_TYPE_VHT:
2207                 rinfo->flags = RATE_INFO_FLAGS_VHT_MCS;
2208                 rinfo->mcs = STA_STATS_GET(VHT_MCS, rate);
2209                 rinfo->nss = STA_STATS_GET(VHT_NSS, rate);
2210                 if (STA_STATS_GET(SGI, rate))
2211                         rinfo->flags |= RATE_INFO_FLAGS_SHORT_GI;
2212                 break;
2213         case STA_STATS_RATE_TYPE_HT:
2214                 rinfo->flags = RATE_INFO_FLAGS_MCS;
2215                 rinfo->mcs = STA_STATS_GET(HT_MCS, rate);
2216                 if (STA_STATS_GET(SGI, rate))
2217                         rinfo->flags |= RATE_INFO_FLAGS_SHORT_GI;
2218                 break;
2219         case STA_STATS_RATE_TYPE_LEGACY: {
2220                 struct ieee80211_supported_band *sband;
2221                 u16 brate;
2222                 unsigned int shift;
2223                 int band = STA_STATS_GET(LEGACY_BAND, rate);
2224                 int rate_idx = STA_STATS_GET(LEGACY_IDX, rate);
2225
2226                 sband = local->hw.wiphy->bands[band];
2227
2228                 if (WARN_ON_ONCE(!sband->bitrates))
2229                         break;
2230
2231                 brate = sband->bitrates[rate_idx].bitrate;
2232                 if (rinfo->bw == RATE_INFO_BW_5)
2233                         shift = 2;
2234                 else if (rinfo->bw == RATE_INFO_BW_10)
2235                         shift = 1;
2236                 else
2237                         shift = 0;
2238                 rinfo->legacy = DIV_ROUND_UP(brate, 1 << shift);
2239                 break;
2240                 }
2241         case STA_STATS_RATE_TYPE_HE:
2242                 rinfo->flags = RATE_INFO_FLAGS_HE_MCS;
2243                 rinfo->mcs = STA_STATS_GET(HE_MCS, rate);
2244                 rinfo->nss = STA_STATS_GET(HE_NSS, rate);
2245                 rinfo->he_gi = STA_STATS_GET(HE_GI, rate);
2246                 rinfo->he_ru_alloc = STA_STATS_GET(HE_RU, rate);
2247                 rinfo->he_dcm = STA_STATS_GET(HE_DCM, rate);
2248                 break;
2249         }
2250 }
2251
2252 static int sta_set_rate_info_rx(struct sta_info *sta, struct rate_info *rinfo)
2253 {
2254         u16 rate = READ_ONCE(sta_get_last_rx_stats(sta)->last_rate);
2255
2256         if (rate == STA_STATS_RATE_INVALID)
2257                 return -EINVAL;
2258
2259         sta_stats_decode_rate(sta->local, rate, rinfo);
2260         return 0;
2261 }
2262
2263 static inline u64 sta_get_tidstats_msdu(struct ieee80211_sta_rx_stats *rxstats,
2264                                         int tid)
2265 {
2266         unsigned int start;
2267         u64 value;
2268
2269         do {
2270                 start = u64_stats_fetch_begin(&rxstats->syncp);
2271                 value = rxstats->msdu[tid];
2272         } while (u64_stats_fetch_retry(&rxstats->syncp, start));
2273
2274         return value;
2275 }
2276
2277 static void sta_set_tidstats(struct sta_info *sta,
2278                              struct cfg80211_tid_stats *tidstats,
2279                              int tid)
2280 {
2281         struct ieee80211_local *local = sta->local;
2282         int cpu;
2283
2284         if (!(tidstats->filled & BIT(NL80211_TID_STATS_RX_MSDU))) {
2285                 tidstats->rx_msdu += sta_get_tidstats_msdu(&sta->deflink.rx_stats,
2286                                                            tid);
2287
2288                 if (sta->deflink.pcpu_rx_stats) {
2289                         for_each_possible_cpu(cpu) {
2290                                 struct ieee80211_sta_rx_stats *cpurxs;
2291
2292                                 cpurxs = per_cpu_ptr(sta->deflink.pcpu_rx_stats,
2293                                                      cpu);
2294                                 tidstats->rx_msdu +=
2295                                         sta_get_tidstats_msdu(cpurxs, tid);
2296                         }
2297                 }
2298
2299                 tidstats->filled |= BIT(NL80211_TID_STATS_RX_MSDU);
2300         }
2301
2302         if (!(tidstats->filled & BIT(NL80211_TID_STATS_TX_MSDU))) {
2303                 tidstats->filled |= BIT(NL80211_TID_STATS_TX_MSDU);
2304                 tidstats->tx_msdu = sta->deflink.tx_stats.msdu[tid];
2305         }
2306
2307         if (!(tidstats->filled & BIT(NL80211_TID_STATS_TX_MSDU_RETRIES)) &&
2308             ieee80211_hw_check(&local->hw, REPORTS_TX_ACK_STATUS)) {
2309                 tidstats->filled |= BIT(NL80211_TID_STATS_TX_MSDU_RETRIES);
2310                 tidstats->tx_msdu_retries = sta->deflink.status_stats.msdu_retries[tid];
2311         }
2312
2313         if (!(tidstats->filled & BIT(NL80211_TID_STATS_TX_MSDU_FAILED)) &&
2314             ieee80211_hw_check(&local->hw, REPORTS_TX_ACK_STATUS)) {
2315                 tidstats->filled |= BIT(NL80211_TID_STATS_TX_MSDU_FAILED);
2316                 tidstats->tx_msdu_failed = sta->deflink.status_stats.msdu_failed[tid];
2317         }
2318
2319         if (local->ops->wake_tx_queue && tid < IEEE80211_NUM_TIDS) {
2320                 spin_lock_bh(&local->fq.lock);
2321                 rcu_read_lock();
2322
2323                 tidstats->filled |= BIT(NL80211_TID_STATS_TXQ_STATS);
2324                 ieee80211_fill_txq_stats(&tidstats->txq_stats,
2325                                          to_txq_info(sta->sta.txq[tid]));
2326
2327                 rcu_read_unlock();
2328                 spin_unlock_bh(&local->fq.lock);
2329         }
2330 }
2331
2332 static inline u64 sta_get_stats_bytes(struct ieee80211_sta_rx_stats *rxstats)
2333 {
2334         unsigned int start;
2335         u64 value;
2336
2337         do {
2338                 start = u64_stats_fetch_begin(&rxstats->syncp);
2339                 value = rxstats->bytes;
2340         } while (u64_stats_fetch_retry(&rxstats->syncp, start));
2341
2342         return value;
2343 }
2344
2345 void sta_set_sinfo(struct sta_info *sta, struct station_info *sinfo,
2346                    bool tidstats)
2347 {
2348         struct ieee80211_sub_if_data *sdata = sta->sdata;
2349         struct ieee80211_local *local = sdata->local;
2350         u32 thr = 0;
2351         int i, ac, cpu;
2352         struct ieee80211_sta_rx_stats *last_rxstats;
2353
2354         last_rxstats = sta_get_last_rx_stats(sta);
2355
2356         sinfo->generation = sdata->local->sta_generation;
2357
2358         /* do before driver, so beacon filtering drivers have a
2359          * chance to e.g. just add the number of filtered beacons
2360          * (or just modify the value entirely, of course)
2361          */
2362         if (sdata->vif.type == NL80211_IFTYPE_STATION)
2363                 sinfo->rx_beacon = sdata->deflink.u.mgd.count_beacon_signal;
2364
2365         drv_sta_statistics(local, sdata, &sta->sta, sinfo);
2366         sinfo->filled |= BIT_ULL(NL80211_STA_INFO_INACTIVE_TIME) |
2367                          BIT_ULL(NL80211_STA_INFO_STA_FLAGS) |
2368                          BIT_ULL(NL80211_STA_INFO_BSS_PARAM) |
2369                          BIT_ULL(NL80211_STA_INFO_CONNECTED_TIME) |
2370                          BIT_ULL(NL80211_STA_INFO_ASSOC_AT_BOOTTIME) |
2371                          BIT_ULL(NL80211_STA_INFO_RX_DROP_MISC);
2372
2373         if (sdata->vif.type == NL80211_IFTYPE_STATION) {
2374                 sinfo->beacon_loss_count =
2375                         sdata->deflink.u.mgd.beacon_loss_count;
2376                 sinfo->filled |= BIT_ULL(NL80211_STA_INFO_BEACON_LOSS);
2377         }
2378
2379         sinfo->connected_time = ktime_get_seconds() - sta->last_connected;
2380         sinfo->assoc_at = sta->assoc_at;
2381         sinfo->inactive_time =
2382                 jiffies_to_msecs(jiffies - ieee80211_sta_last_active(sta));
2383
2384         if (!(sinfo->filled & (BIT_ULL(NL80211_STA_INFO_TX_BYTES64) |
2385                                BIT_ULL(NL80211_STA_INFO_TX_BYTES)))) {
2386                 sinfo->tx_bytes = 0;
2387                 for (ac = 0; ac < IEEE80211_NUM_ACS; ac++)
2388                         sinfo->tx_bytes += sta->deflink.tx_stats.bytes[ac];
2389                 sinfo->filled |= BIT_ULL(NL80211_STA_INFO_TX_BYTES64);
2390         }
2391
2392         if (!(sinfo->filled & BIT_ULL(NL80211_STA_INFO_TX_PACKETS))) {
2393                 sinfo->tx_packets = 0;
2394                 for (ac = 0; ac < IEEE80211_NUM_ACS; ac++)
2395                         sinfo->tx_packets += sta->deflink.tx_stats.packets[ac];
2396                 sinfo->filled |= BIT_ULL(NL80211_STA_INFO_TX_PACKETS);
2397         }
2398
2399         if (!(sinfo->filled & (BIT_ULL(NL80211_STA_INFO_RX_BYTES64) |
2400                                BIT_ULL(NL80211_STA_INFO_RX_BYTES)))) {
2401                 sinfo->rx_bytes += sta_get_stats_bytes(&sta->deflink.rx_stats);
2402
2403                 if (sta->deflink.pcpu_rx_stats) {
2404                         for_each_possible_cpu(cpu) {
2405                                 struct ieee80211_sta_rx_stats *cpurxs;
2406
2407                                 cpurxs = per_cpu_ptr(sta->deflink.pcpu_rx_stats,
2408                                                      cpu);
2409                                 sinfo->rx_bytes += sta_get_stats_bytes(cpurxs);
2410                         }
2411                 }
2412
2413                 sinfo->filled |= BIT_ULL(NL80211_STA_INFO_RX_BYTES64);
2414         }
2415
2416         if (!(sinfo->filled & BIT_ULL(NL80211_STA_INFO_RX_PACKETS))) {
2417                 sinfo->rx_packets = sta->deflink.rx_stats.packets;
2418                 if (sta->deflink.pcpu_rx_stats) {
2419                         for_each_possible_cpu(cpu) {
2420                                 struct ieee80211_sta_rx_stats *cpurxs;
2421
2422                                 cpurxs = per_cpu_ptr(sta->deflink.pcpu_rx_stats,
2423                                                      cpu);
2424                                 sinfo->rx_packets += cpurxs->packets;
2425                         }
2426                 }
2427                 sinfo->filled |= BIT_ULL(NL80211_STA_INFO_RX_PACKETS);
2428         }
2429
2430         if (!(sinfo->filled & BIT_ULL(NL80211_STA_INFO_TX_RETRIES))) {
2431                 sinfo->tx_retries = sta->deflink.status_stats.retry_count;
2432                 sinfo->filled |= BIT_ULL(NL80211_STA_INFO_TX_RETRIES);
2433         }
2434
2435         if (!(sinfo->filled & BIT_ULL(NL80211_STA_INFO_TX_FAILED))) {
2436                 sinfo->tx_failed = sta->deflink.status_stats.retry_failed;
2437                 sinfo->filled |= BIT_ULL(NL80211_STA_INFO_TX_FAILED);
2438         }
2439
2440         if (!(sinfo->filled & BIT_ULL(NL80211_STA_INFO_RX_DURATION))) {
2441                 for (ac = 0; ac < IEEE80211_NUM_ACS; ac++)
2442                         sinfo->rx_duration += sta->airtime[ac].rx_airtime;
2443                 sinfo->filled |= BIT_ULL(NL80211_STA_INFO_RX_DURATION);
2444         }
2445
2446         if (!(sinfo->filled & BIT_ULL(NL80211_STA_INFO_TX_DURATION))) {
2447                 for (ac = 0; ac < IEEE80211_NUM_ACS; ac++)
2448                         sinfo->tx_duration += sta->airtime[ac].tx_airtime;
2449                 sinfo->filled |= BIT_ULL(NL80211_STA_INFO_TX_DURATION);
2450         }
2451
2452         if (!(sinfo->filled & BIT_ULL(NL80211_STA_INFO_AIRTIME_WEIGHT))) {
2453                 sinfo->airtime_weight = sta->airtime_weight;
2454                 sinfo->filled |= BIT_ULL(NL80211_STA_INFO_AIRTIME_WEIGHT);
2455         }
2456
2457         sinfo->rx_dropped_misc = sta->deflink.rx_stats.dropped;
2458         if (sta->deflink.pcpu_rx_stats) {
2459                 for_each_possible_cpu(cpu) {
2460                         struct ieee80211_sta_rx_stats *cpurxs;
2461
2462                         cpurxs = per_cpu_ptr(sta->deflink.pcpu_rx_stats, cpu);
2463                         sinfo->rx_dropped_misc += cpurxs->dropped;
2464                 }
2465         }
2466
2467         if (sdata->vif.type == NL80211_IFTYPE_STATION &&
2468             !(sdata->vif.driver_flags & IEEE80211_VIF_BEACON_FILTER)) {
2469                 sinfo->filled |= BIT_ULL(NL80211_STA_INFO_BEACON_RX) |
2470                                  BIT_ULL(NL80211_STA_INFO_BEACON_SIGNAL_AVG);
2471                 sinfo->rx_beacon_signal_avg = ieee80211_ave_rssi(&sdata->vif);
2472         }
2473
2474         if (ieee80211_hw_check(&sta->local->hw, SIGNAL_DBM) ||
2475             ieee80211_hw_check(&sta->local->hw, SIGNAL_UNSPEC)) {
2476                 if (!(sinfo->filled & BIT_ULL(NL80211_STA_INFO_SIGNAL))) {
2477                         sinfo->signal = (s8)last_rxstats->last_signal;
2478                         sinfo->filled |= BIT_ULL(NL80211_STA_INFO_SIGNAL);
2479                 }
2480
2481                 if (!sta->deflink.pcpu_rx_stats &&
2482                     !(sinfo->filled & BIT_ULL(NL80211_STA_INFO_SIGNAL_AVG))) {
2483                         sinfo->signal_avg =
2484                                 -ewma_signal_read(&sta->deflink.rx_stats_avg.signal);
2485                         sinfo->filled |= BIT_ULL(NL80211_STA_INFO_SIGNAL_AVG);
2486                 }
2487         }
2488
2489         /* for the average - if pcpu_rx_stats isn't set - rxstats must point to
2490          * the sta->rx_stats struct, so the check here is fine with and without
2491          * pcpu statistics
2492          */
2493         if (last_rxstats->chains &&
2494             !(sinfo->filled & (BIT_ULL(NL80211_STA_INFO_CHAIN_SIGNAL) |
2495                                BIT_ULL(NL80211_STA_INFO_CHAIN_SIGNAL_AVG)))) {
2496                 sinfo->filled |= BIT_ULL(NL80211_STA_INFO_CHAIN_SIGNAL);
2497                 if (!sta->deflink.pcpu_rx_stats)
2498                         sinfo->filled |= BIT_ULL(NL80211_STA_INFO_CHAIN_SIGNAL_AVG);
2499
2500                 sinfo->chains = last_rxstats->chains;
2501
2502                 for (i = 0; i < ARRAY_SIZE(sinfo->chain_signal); i++) {
2503                         sinfo->chain_signal[i] =
2504                                 last_rxstats->chain_signal_last[i];
2505                         sinfo->chain_signal_avg[i] =
2506                                 -ewma_signal_read(&sta->deflink.rx_stats_avg.chain_signal[i]);
2507                 }
2508         }
2509
2510         if (!(sinfo->filled & BIT_ULL(NL80211_STA_INFO_TX_BITRATE)) &&
2511             !sta->sta.valid_links) {
2512                 sta_set_rate_info_tx(sta, &sta->deflink.tx_stats.last_rate,
2513                                      &sinfo->txrate);
2514                 sinfo->filled |= BIT_ULL(NL80211_STA_INFO_TX_BITRATE);
2515         }
2516
2517         if (!(sinfo->filled & BIT_ULL(NL80211_STA_INFO_RX_BITRATE)) &&
2518             !sta->sta.valid_links) {
2519                 if (sta_set_rate_info_rx(sta, &sinfo->rxrate) == 0)
2520                         sinfo->filled |= BIT_ULL(NL80211_STA_INFO_RX_BITRATE);
2521         }
2522
2523         if (tidstats && !cfg80211_sinfo_alloc_tid_stats(sinfo, GFP_KERNEL)) {
2524                 for (i = 0; i < IEEE80211_NUM_TIDS + 1; i++)
2525                         sta_set_tidstats(sta, &sinfo->pertid[i], i);
2526         }
2527
2528         if (ieee80211_vif_is_mesh(&sdata->vif)) {
2529 #ifdef CONFIG_MAC80211_MESH
2530                 sinfo->filled |= BIT_ULL(NL80211_STA_INFO_LLID) |
2531                                  BIT_ULL(NL80211_STA_INFO_PLID) |
2532                                  BIT_ULL(NL80211_STA_INFO_PLINK_STATE) |
2533                                  BIT_ULL(NL80211_STA_INFO_LOCAL_PM) |
2534                                  BIT_ULL(NL80211_STA_INFO_PEER_PM) |
2535                                  BIT_ULL(NL80211_STA_INFO_NONPEER_PM) |
2536                                  BIT_ULL(NL80211_STA_INFO_CONNECTED_TO_GATE) |
2537                                  BIT_ULL(NL80211_STA_INFO_CONNECTED_TO_AS);
2538
2539                 sinfo->llid = sta->mesh->llid;
2540                 sinfo->plid = sta->mesh->plid;
2541                 sinfo->plink_state = sta->mesh->plink_state;
2542                 if (test_sta_flag(sta, WLAN_STA_TOFFSET_KNOWN)) {
2543                         sinfo->filled |= BIT_ULL(NL80211_STA_INFO_T_OFFSET);
2544                         sinfo->t_offset = sta->mesh->t_offset;
2545                 }
2546                 sinfo->local_pm = sta->mesh->local_pm;
2547                 sinfo->peer_pm = sta->mesh->peer_pm;
2548                 sinfo->nonpeer_pm = sta->mesh->nonpeer_pm;
2549                 sinfo->connected_to_gate = sta->mesh->connected_to_gate;
2550                 sinfo->connected_to_as = sta->mesh->connected_to_as;
2551 #endif
2552         }
2553
2554         sinfo->bss_param.flags = 0;
2555         if (sdata->vif.bss_conf.use_cts_prot)
2556                 sinfo->bss_param.flags |= BSS_PARAM_FLAGS_CTS_PROT;
2557         if (sdata->vif.bss_conf.use_short_preamble)
2558                 sinfo->bss_param.flags |= BSS_PARAM_FLAGS_SHORT_PREAMBLE;
2559         if (sdata->vif.bss_conf.use_short_slot)
2560                 sinfo->bss_param.flags |= BSS_PARAM_FLAGS_SHORT_SLOT_TIME;
2561         sinfo->bss_param.dtim_period = sdata->vif.bss_conf.dtim_period;
2562         sinfo->bss_param.beacon_interval = sdata->vif.bss_conf.beacon_int;
2563
2564         sinfo->sta_flags.set = 0;
2565         sinfo->sta_flags.mask = BIT(NL80211_STA_FLAG_AUTHORIZED) |
2566                                 BIT(NL80211_STA_FLAG_SHORT_PREAMBLE) |
2567                                 BIT(NL80211_STA_FLAG_WME) |
2568                                 BIT(NL80211_STA_FLAG_MFP) |
2569                                 BIT(NL80211_STA_FLAG_AUTHENTICATED) |
2570                                 BIT(NL80211_STA_FLAG_ASSOCIATED) |
2571                                 BIT(NL80211_STA_FLAG_TDLS_PEER);
2572         if (test_sta_flag(sta, WLAN_STA_AUTHORIZED))
2573                 sinfo->sta_flags.set |= BIT(NL80211_STA_FLAG_AUTHORIZED);
2574         if (test_sta_flag(sta, WLAN_STA_SHORT_PREAMBLE))
2575                 sinfo->sta_flags.set |= BIT(NL80211_STA_FLAG_SHORT_PREAMBLE);
2576         if (sta->sta.wme)
2577                 sinfo->sta_flags.set |= BIT(NL80211_STA_FLAG_WME);
2578         if (test_sta_flag(sta, WLAN_STA_MFP))
2579                 sinfo->sta_flags.set |= BIT(NL80211_STA_FLAG_MFP);
2580         if (test_sta_flag(sta, WLAN_STA_AUTH))
2581                 sinfo->sta_flags.set |= BIT(NL80211_STA_FLAG_AUTHENTICATED);
2582         if (test_sta_flag(sta, WLAN_STA_ASSOC))
2583                 sinfo->sta_flags.set |= BIT(NL80211_STA_FLAG_ASSOCIATED);
2584         if (test_sta_flag(sta, WLAN_STA_TDLS_PEER))
2585                 sinfo->sta_flags.set |= BIT(NL80211_STA_FLAG_TDLS_PEER);
2586
2587         thr = sta_get_expected_throughput(sta);
2588
2589         if (thr != 0) {
2590                 sinfo->filled |= BIT_ULL(NL80211_STA_INFO_EXPECTED_THROUGHPUT);
2591                 sinfo->expected_throughput = thr;
2592         }
2593
2594         if (!(sinfo->filled & BIT_ULL(NL80211_STA_INFO_ACK_SIGNAL)) &&
2595             sta->deflink.status_stats.ack_signal_filled) {
2596                 sinfo->ack_signal = sta->deflink.status_stats.last_ack_signal;
2597                 sinfo->filled |= BIT_ULL(NL80211_STA_INFO_ACK_SIGNAL);
2598         }
2599
2600         if (!(sinfo->filled & BIT_ULL(NL80211_STA_INFO_ACK_SIGNAL_AVG)) &&
2601             sta->deflink.status_stats.ack_signal_filled) {
2602                 sinfo->avg_ack_signal =
2603                         -(s8)ewma_avg_signal_read(
2604                                 &sta->deflink.status_stats.avg_ack_signal);
2605                 sinfo->filled |=
2606                         BIT_ULL(NL80211_STA_INFO_ACK_SIGNAL_AVG);
2607         }
2608
2609         if (ieee80211_vif_is_mesh(&sdata->vif)) {
2610                 sinfo->filled |= BIT_ULL(NL80211_STA_INFO_AIRTIME_LINK_METRIC);
2611                 sinfo->airtime_link_metric =
2612                         airtime_link_metric_get(local, sta);
2613         }
2614 }
2615
2616 u32 sta_get_expected_throughput(struct sta_info *sta)
2617 {
2618         struct ieee80211_sub_if_data *sdata = sta->sdata;
2619         struct ieee80211_local *local = sdata->local;
2620         struct rate_control_ref *ref = NULL;
2621         u32 thr = 0;
2622
2623         if (test_sta_flag(sta, WLAN_STA_RATE_CONTROL))
2624                 ref = local->rate_ctrl;
2625
2626         /* check if the driver has a SW RC implementation */
2627         if (ref && ref->ops->get_expected_throughput)
2628                 thr = ref->ops->get_expected_throughput(sta->rate_ctrl_priv);
2629         else
2630                 thr = drv_get_expected_throughput(local, sta);
2631
2632         return thr;
2633 }
2634
2635 unsigned long ieee80211_sta_last_active(struct sta_info *sta)
2636 {
2637         struct ieee80211_sta_rx_stats *stats = sta_get_last_rx_stats(sta);
2638
2639         if (!sta->deflink.status_stats.last_ack ||
2640             time_after(stats->last_rx, sta->deflink.status_stats.last_ack))
2641                 return stats->last_rx;
2642         return sta->deflink.status_stats.last_ack;
2643 }
2644
2645 static void sta_update_codel_params(struct sta_info *sta, u32 thr)
2646 {
2647         if (!sta->sdata->local->ops->wake_tx_queue)
2648                 return;
2649
2650         if (thr && thr < STA_SLOW_THRESHOLD * sta->local->num_sta) {
2651                 sta->cparams.target = MS2TIME(50);
2652                 sta->cparams.interval = MS2TIME(300);
2653                 sta->cparams.ecn = false;
2654         } else {
2655                 sta->cparams.target = MS2TIME(20);
2656                 sta->cparams.interval = MS2TIME(100);
2657                 sta->cparams.ecn = true;
2658         }
2659 }
2660
2661 void ieee80211_sta_set_expected_throughput(struct ieee80211_sta *pubsta,
2662                                            u32 thr)
2663 {
2664         struct sta_info *sta = container_of(pubsta, struct sta_info, sta);
2665
2666         sta_update_codel_params(sta, thr);
2667 }
2668
2669 int ieee80211_sta_allocate_link(struct sta_info *sta, unsigned int link_id)
2670 {
2671         struct ieee80211_sub_if_data *sdata = sta->sdata;
2672         struct sta_link_alloc *alloc;
2673         int ret;
2674
2675         lockdep_assert_held(&sdata->local->sta_mtx);
2676
2677         /* must represent an MLD from the start */
2678         if (WARN_ON(!sta->sta.valid_links))
2679                 return -EINVAL;
2680
2681         if (WARN_ON(sta->sta.valid_links & BIT(link_id) ||
2682                     sta->link[link_id]))
2683                 return -EBUSY;
2684
2685         alloc = kzalloc(sizeof(*alloc), GFP_KERNEL);
2686         if (!alloc)
2687                 return -ENOMEM;
2688
2689         ret = sta_info_alloc_link(sdata->local, &alloc->info, GFP_KERNEL);
2690         if (ret) {
2691                 kfree(alloc);
2692                 return ret;
2693         }
2694
2695         sta_info_add_link(sta, link_id, &alloc->info, &alloc->sta);
2696
2697         return 0;
2698 }
2699
2700 static int link_sta_info_hash_add(struct ieee80211_local *local,
2701                                   struct link_sta_info *link_sta)
2702 {
2703         return rhltable_insert(&local->link_sta_hash,
2704                                &link_sta->link_hash_node,
2705                                link_sta_rht_params);
2706 }
2707
2708 void ieee80211_sta_free_link(struct sta_info *sta, unsigned int link_id)
2709 {
2710         lockdep_assert_held(&sta->sdata->local->sta_mtx);
2711
2712         sta_remove_link(sta, link_id, false);
2713 }
2714
2715 int ieee80211_sta_activate_link(struct sta_info *sta, unsigned int link_id)
2716 {
2717         struct ieee80211_sub_if_data *sdata = sta->sdata;
2718         struct link_sta_info *link_sta;
2719         u16 old_links = sta->sta.valid_links;
2720         u16 new_links = old_links | BIT(link_id);
2721         int ret;
2722
2723         link_sta = rcu_dereference_protected(sta->link[link_id],
2724                                              lockdep_is_held(&sdata->local->sta_mtx));
2725
2726         if (WARN_ON(old_links == new_links || !link_sta))
2727                 return -EINVAL;
2728
2729         sta->sta.valid_links = new_links;
2730
2731         if (!test_sta_flag(sta, WLAN_STA_INSERTED)) {
2732                 ret = 0;
2733                 goto hash;
2734         }
2735
2736         ret = drv_change_sta_links(sdata->local, sdata, &sta->sta,
2737                                    old_links, new_links);
2738         if (ret) {
2739                 sta->sta.valid_links = old_links;
2740                 sta_remove_link(sta, link_id, false);
2741         }
2742
2743 hash:
2744         link_sta_info_hash_add(sdata->local, link_sta);
2745
2746         return ret;
2747 }
2748
2749 void ieee80211_sta_remove_link(struct sta_info *sta, unsigned int link_id)
2750 {
2751         struct ieee80211_sub_if_data *sdata = sta->sdata;
2752
2753         lockdep_assert_held(&sdata->local->sta_mtx);
2754
2755         sta->sta.valid_links &= ~BIT(link_id);
2756
2757         if (test_sta_flag(sta, WLAN_STA_INSERTED))
2758                 drv_change_sta_links(sdata->local, sdata, &sta->sta,
2759                                      sta->sta.valid_links,
2760                                      sta->sta.valid_links & ~BIT(link_id));
2761
2762         sta_remove_link(sta, link_id, true);
2763 }