OSDN Git Service

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