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