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