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