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