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