1// SPDX-License-Identifier: GPL-2.0-only
2/*
3 * mac80211_hwsim - software simulator of 802.11 radio(s) for mac80211
4 * Copyright (c) 2008, Jouni Malinen <j@w1.fi>
5 * Copyright (c) 2011, Javier Lopez <jlopex@gmail.com>
6 * Copyright (c) 2016 - 2017 Intel Deutschland GmbH
7 * Copyright (C) 2018 - 2020 Intel Corporation
8 */
9
10/*
11 * TODO:
12 * - Add TSF sync and fix IBSS beacon transmission by adding
13 *   competition for "air time" at TBTT
14 * - RX filtering based on filter configuration (data->rx_filter)
15 */
16
17#include <linux/list.h>
18#include <linux/slab.h>
19#include <linux/spinlock.h>
20#include <net/dst.h>
21#include <net/xfrm.h>
22#include <net/mac80211.h>
23#include <net/ieee80211_radiotap.h>
24#include <linux/if_arp.h>
25#include <linux/rtnetlink.h>
26#include <linux/etherdevice.h>
27#include <linux/platform_device.h>
28#include <linux/debugfs.h>
29#include <linux/module.h>
30#include <linux/ktime.h>
31#include <net/genetlink.h>
32#include <net/net_namespace.h>
33#include <net/netns/generic.h>
34#include <linux/rhashtable.h>
35#include <linux/nospec.h>
36#include <linux/virtio.h>
37#include <linux/virtio_ids.h>
38#include <linux/virtio_config.h>
39#include "mac80211_hwsim.h"
40
41#define WARN_QUEUE 100
42#define MAX_QUEUE 200
43
44MODULE_AUTHOR("Jouni Malinen");
45MODULE_DESCRIPTION("Software simulator of 802.11 radio(s) for mac80211");
46MODULE_LICENSE("GPL");
47
48static int radios = 2;
49module_param(radios, int, 0444);
50MODULE_PARM_DESC(radios, "Number of simulated radios");
51
52static int channels = 1;
53module_param(channels, int, 0444);
54MODULE_PARM_DESC(channels, "Number of concurrent channels");
55
56static bool paged_rx = false;
57module_param(paged_rx, bool, 0644);
58MODULE_PARM_DESC(paged_rx, "Use paged SKBs for RX instead of linear ones");
59
60static bool rctbl = false;
61module_param(rctbl, bool, 0444);
62MODULE_PARM_DESC(rctbl, "Handle rate control table");
63
64static bool support_p2p_device = true;
65module_param(support_p2p_device, bool, 0444);
66MODULE_PARM_DESC(support_p2p_device, "Support P2P-Device interface type");
67
68/**
69 * enum hwsim_regtest - the type of regulatory tests we offer
70 *
71 * These are the different values you can use for the regtest
72 * module parameter. This is useful to help test world roaming
73 * and the driver regulatory_hint() call and combinations of these.
74 * If you want to do specific alpha2 regulatory domain tests simply
75 * use the userspace regulatory request as that will be respected as
76 * well without the need of this module parameter. This is designed
77 * only for testing the driver regulatory request, world roaming
78 * and all possible combinations.
79 *
80 * @HWSIM_REGTEST_DISABLED: No regulatory tests are performed,
81 * 	this is the default value.
82 * @HWSIM_REGTEST_DRIVER_REG_FOLLOW: Used for testing the driver regulatory
83 *	hint, only one driver regulatory hint will be sent as such the
84 * 	secondary radios are expected to follow.
85 * @HWSIM_REGTEST_DRIVER_REG_ALL: Used for testing the driver regulatory
86 * 	request with all radios reporting the same regulatory domain.
87 * @HWSIM_REGTEST_DIFF_COUNTRY: Used for testing the drivers calling
88 * 	different regulatory domains requests. Expected behaviour is for
89 * 	an intersection to occur but each device will still use their
90 * 	respective regulatory requested domains. Subsequent radios will
91 * 	use the resulting intersection.
92 * @HWSIM_REGTEST_WORLD_ROAM: Used for testing the world roaming. We accomplish
93 *	this by using a custom beacon-capable regulatory domain for the first
94 *	radio. All other device world roam.
95 * @HWSIM_REGTEST_CUSTOM_WORLD: Used for testing the custom world regulatory
96 * 	domain requests. All radios will adhere to this custom world regulatory
97 * 	domain.
98 * @HWSIM_REGTEST_CUSTOM_WORLD_2: Used for testing 2 custom world regulatory
99 * 	domain requests. The first radio will adhere to the first custom world
100 * 	regulatory domain, the second one to the second custom world regulatory
101 * 	domain. All other devices will world roam.
102 * @HWSIM_REGTEST_STRICT_FOLLOW: Used for testing strict regulatory domain
103 *	settings, only the first radio will send a regulatory domain request
104 *	and use strict settings. The rest of the radios are expected to follow.
105 * @HWSIM_REGTEST_STRICT_ALL: Used for testing strict regulatory domain
106 *	settings. All radios will adhere to this.
107 * @HWSIM_REGTEST_STRICT_AND_DRIVER_REG: Used for testing strict regulatory
108 *	domain settings, combined with secondary driver regulatory domain
109 *	settings. The first radio will get a strict regulatory domain setting
110 *	using the first driver regulatory request and the second radio will use
111 *	non-strict settings using the second driver regulatory request. All
112 *	other devices should follow the intersection created between the
113 *	first two.
114 * @HWSIM_REGTEST_ALL: Used for testing every possible mix. You will need
115 * 	at least 6 radios for a complete test. We will test in this order:
116 * 	1 - driver custom world regulatory domain
117 * 	2 - second custom world regulatory domain
118 * 	3 - first driver regulatory domain request
119 * 	4 - second driver regulatory domain request
120 * 	5 - strict regulatory domain settings using the third driver regulatory
121 * 	    domain request
122 * 	6 and on - should follow the intersection of the 3rd, 4rth and 5th radio
123 * 	           regulatory requests.
124 */
125enum hwsim_regtest {
126	HWSIM_REGTEST_DISABLED = 0,
127	HWSIM_REGTEST_DRIVER_REG_FOLLOW = 1,
128	HWSIM_REGTEST_DRIVER_REG_ALL = 2,
129	HWSIM_REGTEST_DIFF_COUNTRY = 3,
130	HWSIM_REGTEST_WORLD_ROAM = 4,
131	HWSIM_REGTEST_CUSTOM_WORLD = 5,
132	HWSIM_REGTEST_CUSTOM_WORLD_2 = 6,
133	HWSIM_REGTEST_STRICT_FOLLOW = 7,
134	HWSIM_REGTEST_STRICT_ALL = 8,
135	HWSIM_REGTEST_STRICT_AND_DRIVER_REG = 9,
136	HWSIM_REGTEST_ALL = 10,
137};
138
139/* Set to one of the HWSIM_REGTEST_* values above */
140static int regtest = HWSIM_REGTEST_DISABLED;
141module_param(regtest, int, 0444);
142MODULE_PARM_DESC(regtest, "The type of regulatory test we want to run");
143
144static const char *hwsim_alpha2s[] = {
145	"FI",
146	"AL",
147	"US",
148	"DE",
149	"JP",
150	"AL",
151};
152
153static const struct ieee80211_regdomain hwsim_world_regdom_custom_01 = {
154	.n_reg_rules = 5,
155	.alpha2 =  "99",
156	.reg_rules = {
157		REG_RULE(2412-10, 2462+10, 40, 0, 20, 0),
158		REG_RULE(2484-10, 2484+10, 40, 0, 20, 0),
159		REG_RULE(5150-10, 5240+10, 40, 0, 30, 0),
160		REG_RULE(5745-10, 5825+10, 40, 0, 30, 0),
161		REG_RULE(5855-10, 5925+10, 40, 0, 33, 0),
162	}
163};
164
165static const struct ieee80211_regdomain hwsim_world_regdom_custom_02 = {
166	.n_reg_rules = 3,
167	.alpha2 =  "99",
168	.reg_rules = {
169		REG_RULE(2412-10, 2462+10, 40, 0, 20, 0),
170		REG_RULE(5725-10, 5850+10, 40, 0, 30,
171			 NL80211_RRF_NO_IR),
172		REG_RULE(5855-10, 5925+10, 40, 0, 33, 0),
173	}
174};
175
176static const struct ieee80211_regdomain *hwsim_world_regdom_custom[] = {
177	&hwsim_world_regdom_custom_01,
178	&hwsim_world_regdom_custom_02,
179};
180
181struct hwsim_vif_priv {
182	u32 magic;
183	u8 bssid[ETH_ALEN];
184	bool assoc;
185	bool bcn_en;
186	u16 aid;
187};
188
189#define HWSIM_VIF_MAGIC	0x69537748
190
191static inline void hwsim_check_magic(struct ieee80211_vif *vif)
192{
193	struct hwsim_vif_priv *vp = (void *)vif->drv_priv;
194	WARN(vp->magic != HWSIM_VIF_MAGIC,
195	     "Invalid VIF (%p) magic %#x, %pM, %d/%d\n",
196	     vif, vp->magic, vif->addr, vif->type, vif->p2p);
197}
198
199static inline void hwsim_set_magic(struct ieee80211_vif *vif)
200{
201	struct hwsim_vif_priv *vp = (void *)vif->drv_priv;
202	vp->magic = HWSIM_VIF_MAGIC;
203}
204
205static inline void hwsim_clear_magic(struct ieee80211_vif *vif)
206{
207	struct hwsim_vif_priv *vp = (void *)vif->drv_priv;
208	vp->magic = 0;
209}
210
211struct hwsim_sta_priv {
212	u32 magic;
213};
214
215#define HWSIM_STA_MAGIC	0x6d537749
216
217static inline void hwsim_check_sta_magic(struct ieee80211_sta *sta)
218{
219	struct hwsim_sta_priv *sp = (void *)sta->drv_priv;
220	WARN_ON(sp->magic != HWSIM_STA_MAGIC);
221}
222
223static inline void hwsim_set_sta_magic(struct ieee80211_sta *sta)
224{
225	struct hwsim_sta_priv *sp = (void *)sta->drv_priv;
226	sp->magic = HWSIM_STA_MAGIC;
227}
228
229static inline void hwsim_clear_sta_magic(struct ieee80211_sta *sta)
230{
231	struct hwsim_sta_priv *sp = (void *)sta->drv_priv;
232	sp->magic = 0;
233}
234
235struct hwsim_chanctx_priv {
236	u32 magic;
237};
238
239#define HWSIM_CHANCTX_MAGIC 0x6d53774a
240
241static inline void hwsim_check_chanctx_magic(struct ieee80211_chanctx_conf *c)
242{
243	struct hwsim_chanctx_priv *cp = (void *)c->drv_priv;
244	WARN_ON(cp->magic != HWSIM_CHANCTX_MAGIC);
245}
246
247static inline void hwsim_set_chanctx_magic(struct ieee80211_chanctx_conf *c)
248{
249	struct hwsim_chanctx_priv *cp = (void *)c->drv_priv;
250	cp->magic = HWSIM_CHANCTX_MAGIC;
251}
252
253static inline void hwsim_clear_chanctx_magic(struct ieee80211_chanctx_conf *c)
254{
255	struct hwsim_chanctx_priv *cp = (void *)c->drv_priv;
256	cp->magic = 0;
257}
258
259static unsigned int hwsim_net_id;
260
261static DEFINE_IDA(hwsim_netgroup_ida);
262
263struct hwsim_net {
264	int netgroup;
265	u32 wmediumd;
266};
267
268static inline int hwsim_net_get_netgroup(struct net *net)
269{
270	struct hwsim_net *hwsim_net = net_generic(net, hwsim_net_id);
271
272	return hwsim_net->netgroup;
273}
274
275static inline int hwsim_net_set_netgroup(struct net *net)
276{
277	struct hwsim_net *hwsim_net = net_generic(net, hwsim_net_id);
278
279	hwsim_net->netgroup = ida_simple_get(&hwsim_netgroup_ida,
280					     0, 0, GFP_KERNEL);
281	return hwsim_net->netgroup >= 0 ? 0 : -ENOMEM;
282}
283
284static inline u32 hwsim_net_get_wmediumd(struct net *net)
285{
286	struct hwsim_net *hwsim_net = net_generic(net, hwsim_net_id);
287
288	return hwsim_net->wmediumd;
289}
290
291static inline void hwsim_net_set_wmediumd(struct net *net, u32 portid)
292{
293	struct hwsim_net *hwsim_net = net_generic(net, hwsim_net_id);
294
295	hwsim_net->wmediumd = portid;
296}
297
298static struct class *hwsim_class;
299
300static struct net_device *hwsim_mon; /* global monitor netdev */
301
302#define CHAN2G(_freq)  { \
303	.band = NL80211_BAND_2GHZ, \
304	.center_freq = (_freq), \
305	.hw_value = (_freq), \
306}
307
308#define CHAN5G(_freq) { \
309	.band = NL80211_BAND_5GHZ, \
310	.center_freq = (_freq), \
311	.hw_value = (_freq), \
312}
313
314static const struct ieee80211_channel hwsim_channels_2ghz[] = {
315	CHAN2G(2412), /* Channel 1 */
316	CHAN2G(2417), /* Channel 2 */
317	CHAN2G(2422), /* Channel 3 */
318	CHAN2G(2427), /* Channel 4 */
319	CHAN2G(2432), /* Channel 5 */
320	CHAN2G(2437), /* Channel 6 */
321	CHAN2G(2442), /* Channel 7 */
322	CHAN2G(2447), /* Channel 8 */
323	CHAN2G(2452), /* Channel 9 */
324	CHAN2G(2457), /* Channel 10 */
325	CHAN2G(2462), /* Channel 11 */
326	CHAN2G(2467), /* Channel 12 */
327	CHAN2G(2472), /* Channel 13 */
328	CHAN2G(2484), /* Channel 14 */
329};
330
331static const struct ieee80211_channel hwsim_channels_5ghz[] = {
332	CHAN5G(5180), /* Channel 36 */
333	CHAN5G(5200), /* Channel 40 */
334	CHAN5G(5220), /* Channel 44 */
335	CHAN5G(5240), /* Channel 48 */
336
337	CHAN5G(5260), /* Channel 52 */
338	CHAN5G(5280), /* Channel 56 */
339	CHAN5G(5300), /* Channel 60 */
340	CHAN5G(5320), /* Channel 64 */
341
342	CHAN5G(5500), /* Channel 100 */
343	CHAN5G(5520), /* Channel 104 */
344	CHAN5G(5540), /* Channel 108 */
345	CHAN5G(5560), /* Channel 112 */
346	CHAN5G(5580), /* Channel 116 */
347	CHAN5G(5600), /* Channel 120 */
348	CHAN5G(5620), /* Channel 124 */
349	CHAN5G(5640), /* Channel 128 */
350	CHAN5G(5660), /* Channel 132 */
351	CHAN5G(5680), /* Channel 136 */
352	CHAN5G(5700), /* Channel 140 */
353
354	CHAN5G(5745), /* Channel 149 */
355	CHAN5G(5765), /* Channel 153 */
356	CHAN5G(5785), /* Channel 157 */
357	CHAN5G(5805), /* Channel 161 */
358	CHAN5G(5825), /* Channel 165 */
359	CHAN5G(5845), /* Channel 169 */
360
361	CHAN5G(5855), /* Channel 171 */
362	CHAN5G(5860), /* Channel 172 */
363	CHAN5G(5865), /* Channel 173 */
364	CHAN5G(5870), /* Channel 174 */
365
366	CHAN5G(5875), /* Channel 175 */
367	CHAN5G(5880), /* Channel 176 */
368	CHAN5G(5885), /* Channel 177 */
369	CHAN5G(5890), /* Channel 178 */
370	CHAN5G(5895), /* Channel 179 */
371	CHAN5G(5900), /* Channel 180 */
372	CHAN5G(5905), /* Channel 181 */
373
374	CHAN5G(5910), /* Channel 182 */
375	CHAN5G(5915), /* Channel 183 */
376	CHAN5G(5920), /* Channel 184 */
377	CHAN5G(5925), /* Channel 185 */
378};
379
380#define NUM_S1G_CHANS_US 51
381static struct ieee80211_channel hwsim_channels_s1g[NUM_S1G_CHANS_US];
382
383static const struct ieee80211_sta_s1g_cap hwsim_s1g_cap = {
384	.s1g = true,
385	.cap = { S1G_CAP0_SGI_1MHZ | S1G_CAP0_SGI_2MHZ,
386		 0,
387		 0,
388		 S1G_CAP3_MAX_MPDU_LEN,
389		 0,
390		 S1G_CAP5_AMPDU,
391		 0,
392		 S1G_CAP7_DUP_1MHZ,
393		 S1G_CAP8_TWT_RESPOND | S1G_CAP8_TWT_REQUEST,
394		 0},
395	.nss_mcs = { 0xfc | 1, /* MCS 7 for 1 SS */
396	/* RX Highest Supported Long GI Data Rate 0:7 */
397		     0,
398	/* RX Highest Supported Long GI Data Rate 0:7 */
399	/* TX S1G MCS Map 0:6 */
400		     0xfa,
401	/* TX S1G MCS Map :7 */
402	/* TX Highest Supported Long GI Data Rate 0:6 */
403		     0x80,
404	/* TX Highest Supported Long GI Data Rate 7:8 */
405	/* Rx Single spatial stream and S1G-MCS Map for 1MHz */
406	/* Tx Single spatial stream and S1G-MCS Map for 1MHz */
407		     0 },
408};
409
410static void hwsim_init_s1g_channels(struct ieee80211_channel *channels)
411{
412	int ch, freq;
413
414	for (ch = 0; ch < NUM_S1G_CHANS_US; ch++) {
415		freq = 902000 + (ch + 1) * 500;
416		channels[ch].band = NL80211_BAND_S1GHZ;
417		channels[ch].center_freq = KHZ_TO_MHZ(freq);
418		channels[ch].freq_offset = freq % 1000;
419		channels[ch].hw_value = ch + 1;
420	}
421}
422
423static const struct ieee80211_rate hwsim_rates[] = {
424	{ .bitrate = 10 },
425	{ .bitrate = 20, .flags = IEEE80211_RATE_SHORT_PREAMBLE },
426	{ .bitrate = 55, .flags = IEEE80211_RATE_SHORT_PREAMBLE },
427	{ .bitrate = 110, .flags = IEEE80211_RATE_SHORT_PREAMBLE },
428	{ .bitrate = 60 },
429	{ .bitrate = 90 },
430	{ .bitrate = 120 },
431	{ .bitrate = 180 },
432	{ .bitrate = 240 },
433	{ .bitrate = 360 },
434	{ .bitrate = 480 },
435	{ .bitrate = 540 }
436};
437
438static const u32 hwsim_ciphers[] = {
439	WLAN_CIPHER_SUITE_WEP40,
440	WLAN_CIPHER_SUITE_WEP104,
441	WLAN_CIPHER_SUITE_TKIP,
442	WLAN_CIPHER_SUITE_CCMP,
443	WLAN_CIPHER_SUITE_CCMP_256,
444	WLAN_CIPHER_SUITE_GCMP,
445	WLAN_CIPHER_SUITE_GCMP_256,
446	WLAN_CIPHER_SUITE_AES_CMAC,
447	WLAN_CIPHER_SUITE_BIP_CMAC_256,
448	WLAN_CIPHER_SUITE_BIP_GMAC_128,
449	WLAN_CIPHER_SUITE_BIP_GMAC_256,
450};
451
452#define OUI_QCA 0x001374
453#define QCA_NL80211_SUBCMD_TEST 1
454enum qca_nl80211_vendor_subcmds {
455	QCA_WLAN_VENDOR_ATTR_TEST = 8,
456	QCA_WLAN_VENDOR_ATTR_MAX = QCA_WLAN_VENDOR_ATTR_TEST
457};
458
459static const struct nla_policy
460hwsim_vendor_test_policy[QCA_WLAN_VENDOR_ATTR_MAX + 1] = {
461	[QCA_WLAN_VENDOR_ATTR_MAX] = { .type = NLA_U32 },
462};
463
464static int mac80211_hwsim_vendor_cmd_test(struct wiphy *wiphy,
465					  struct wireless_dev *wdev,
466					  const void *data, int data_len)
467{
468	struct sk_buff *skb;
469	struct nlattr *tb[QCA_WLAN_VENDOR_ATTR_MAX + 1];
470	int err;
471	u32 val;
472
473	err = nla_parse_deprecated(tb, QCA_WLAN_VENDOR_ATTR_MAX, data,
474				   data_len, hwsim_vendor_test_policy, NULL);
475	if (err)
476		return err;
477	if (!tb[QCA_WLAN_VENDOR_ATTR_TEST])
478		return -EINVAL;
479	val = nla_get_u32(tb[QCA_WLAN_VENDOR_ATTR_TEST]);
480	wiphy_dbg(wiphy, "%s: test=%u\n", __func__, val);
481
482	/* Send a vendor event as a test. Note that this would not normally be
483	 * done within a command handler, but rather, based on some other
484	 * trigger. For simplicity, this command is used to trigger the event
485	 * here.
486	 *
487	 * event_idx = 0 (index in mac80211_hwsim_vendor_commands)
488	 */
489	skb = cfg80211_vendor_event_alloc(wiphy, wdev, 100, 0, GFP_KERNEL);
490	if (skb) {
491		/* skb_put() or nla_put() will fill up data within
492		 * NL80211_ATTR_VENDOR_DATA.
493		 */
494
495		/* Add vendor data */
496		nla_put_u32(skb, QCA_WLAN_VENDOR_ATTR_TEST, val + 1);
497
498		/* Send the event - this will call nla_nest_end() */
499		cfg80211_vendor_event(skb, GFP_KERNEL);
500	}
501
502	/* Send a response to the command */
503	skb = cfg80211_vendor_cmd_alloc_reply_skb(wiphy, 10);
504	if (!skb)
505		return -ENOMEM;
506
507	/* skb_put() or nla_put() will fill up data within
508	 * NL80211_ATTR_VENDOR_DATA
509	 */
510	nla_put_u32(skb, QCA_WLAN_VENDOR_ATTR_TEST, val + 2);
511
512	return cfg80211_vendor_cmd_reply(skb);
513}
514
515static struct wiphy_vendor_command mac80211_hwsim_vendor_commands[] = {
516	{
517		.info = { .vendor_id = OUI_QCA,
518			  .subcmd = QCA_NL80211_SUBCMD_TEST },
519		.flags = WIPHY_VENDOR_CMD_NEED_NETDEV,
520		.doit = mac80211_hwsim_vendor_cmd_test,
521		.policy = hwsim_vendor_test_policy,
522		.maxattr = QCA_WLAN_VENDOR_ATTR_MAX,
523	}
524};
525
526/* Advertise support vendor specific events */
527static const struct nl80211_vendor_cmd_info mac80211_hwsim_vendor_events[] = {
528	{ .vendor_id = OUI_QCA, .subcmd = 1 },
529};
530
531static spinlock_t hwsim_radio_lock;
532static LIST_HEAD(hwsim_radios);
533static struct rhashtable hwsim_radios_rht;
534static int hwsim_radio_idx;
535static int hwsim_radios_generation = 1;
536
537static struct platform_driver mac80211_hwsim_driver = {
538	.driver = {
539		.name = "mac80211_hwsim",
540	},
541};
542
543struct mac80211_hwsim_data {
544	struct list_head list;
545	struct rhash_head rht;
546	struct ieee80211_hw *hw;
547	struct device *dev;
548	struct ieee80211_supported_band bands[NUM_NL80211_BANDS];
549	struct ieee80211_channel channels_2ghz[ARRAY_SIZE(hwsim_channels_2ghz)];
550	struct ieee80211_channel channels_5ghz[ARRAY_SIZE(hwsim_channels_5ghz)];
551	struct ieee80211_channel channels_s1g[ARRAY_SIZE(hwsim_channels_s1g)];
552	struct ieee80211_rate rates[ARRAY_SIZE(hwsim_rates)];
553	struct ieee80211_iface_combination if_combination;
554	struct ieee80211_iface_limit if_limits[3];
555	int n_if_limits;
556
557	u32 ciphers[ARRAY_SIZE(hwsim_ciphers)];
558
559	struct mac_address addresses[2];
560	struct ieee80211_chanctx_conf *chanctx;
561	int channels, idx;
562	bool use_chanctx;
563	bool destroy_on_close;
564	u32 portid;
565	char alpha2[2];
566	const struct ieee80211_regdomain *regd;
567
568	struct ieee80211_channel *tmp_chan;
569	struct ieee80211_channel *roc_chan;
570	u32 roc_duration;
571	struct delayed_work roc_start;
572	struct delayed_work roc_done;
573	struct delayed_work hw_scan;
574	struct cfg80211_scan_request *hw_scan_request;
575	struct ieee80211_vif *hw_scan_vif;
576	int scan_chan_idx;
577	u8 scan_addr[ETH_ALEN];
578	struct {
579		struct ieee80211_channel *channel;
580		unsigned long next_start, start, end;
581	} survey_data[ARRAY_SIZE(hwsim_channels_2ghz) +
582		      ARRAY_SIZE(hwsim_channels_5ghz)];
583
584	struct ieee80211_channel *channel;
585	u64 beacon_int	/* beacon interval in us */;
586	unsigned int rx_filter;
587	bool started, idle, scanning;
588	struct mutex mutex;
589	struct hrtimer beacon_timer;
590	enum ps_mode {
591		PS_DISABLED, PS_ENABLED, PS_AUTO_POLL, PS_MANUAL_POLL
592	} ps;
593	bool ps_poll_pending;
594	struct dentry *debugfs;
595
596	atomic_t pending_cookie;
597	struct sk_buff_head pending;	/* packets pending */
598	/*
599	 * Only radios in the same group can communicate together (the
600	 * channel has to match too). Each bit represents a group. A
601	 * radio can be in more than one group.
602	 */
603	u64 group;
604
605	/* group shared by radios created in the same netns */
606	int netgroup;
607	/* wmediumd portid responsible for netgroup of this radio */
608	u32 wmediumd;
609
610	/* difference between this hw's clock and the real clock, in usecs */
611	s64 tsf_offset;
612	s64 bcn_delta;
613	/* absolute beacon transmission time. Used to cover up "tx" delay. */
614	u64 abs_bcn_ts;
615
616	/* Stats */
617	u64 tx_pkts;
618	u64 rx_pkts;
619	u64 tx_bytes;
620	u64 rx_bytes;
621	u64 tx_dropped;
622	u64 tx_failed;
623};
624
625static const struct rhashtable_params hwsim_rht_params = {
626	.nelem_hint = 2,
627	.automatic_shrinking = true,
628	.key_len = ETH_ALEN,
629	.key_offset = offsetof(struct mac80211_hwsim_data, addresses[1]),
630	.head_offset = offsetof(struct mac80211_hwsim_data, rht),
631};
632
633struct hwsim_radiotap_hdr {
634	struct ieee80211_radiotap_header hdr;
635	__le64 rt_tsft;
636	u8 rt_flags;
637	u8 rt_rate;
638	__le16 rt_channel;
639	__le16 rt_chbitmask;
640} __packed;
641
642struct hwsim_radiotap_ack_hdr {
643	struct ieee80211_radiotap_header hdr;
644	u8 rt_flags;
645	u8 pad;
646	__le16 rt_channel;
647	__le16 rt_chbitmask;
648} __packed;
649
650/* MAC80211_HWSIM netlink family */
651static struct genl_family hwsim_genl_family;
652
653enum hwsim_multicast_groups {
654	HWSIM_MCGRP_CONFIG,
655};
656
657static const struct genl_multicast_group hwsim_mcgrps[] = {
658	[HWSIM_MCGRP_CONFIG] = { .name = "config", },
659};
660
661/* MAC80211_HWSIM netlink policy */
662
663static const struct nla_policy hwsim_genl_policy[HWSIM_ATTR_MAX + 1] = {
664	[HWSIM_ATTR_ADDR_RECEIVER] = NLA_POLICY_ETH_ADDR_COMPAT,
665	[HWSIM_ATTR_ADDR_TRANSMITTER] = NLA_POLICY_ETH_ADDR_COMPAT,
666	[HWSIM_ATTR_FRAME] = { .type = NLA_BINARY,
667			       .len = IEEE80211_MAX_DATA_LEN },
668	[HWSIM_ATTR_FLAGS] = { .type = NLA_U32 },
669	[HWSIM_ATTR_RX_RATE] = { .type = NLA_U32 },
670	[HWSIM_ATTR_SIGNAL] = { .type = NLA_U32 },
671	[HWSIM_ATTR_TX_INFO] = { .type = NLA_BINARY,
672				 .len = IEEE80211_TX_MAX_RATES *
673					sizeof(struct hwsim_tx_rate)},
674	[HWSIM_ATTR_COOKIE] = { .type = NLA_U64 },
675	[HWSIM_ATTR_CHANNELS] = { .type = NLA_U32 },
676	[HWSIM_ATTR_RADIO_ID] = { .type = NLA_U32 },
677	[HWSIM_ATTR_REG_HINT_ALPHA2] = { .type = NLA_STRING, .len = 2 },
678	[HWSIM_ATTR_REG_CUSTOM_REG] = { .type = NLA_U32 },
679	[HWSIM_ATTR_REG_STRICT_REG] = { .type = NLA_FLAG },
680	[HWSIM_ATTR_SUPPORT_P2P_DEVICE] = { .type = NLA_FLAG },
681	[HWSIM_ATTR_USE_CHANCTX] = { .type = NLA_FLAG },
682	[HWSIM_ATTR_DESTROY_RADIO_ON_CLOSE] = { .type = NLA_FLAG },
683	[HWSIM_ATTR_RADIO_NAME] = { .type = NLA_STRING },
684	[HWSIM_ATTR_NO_VIF] = { .type = NLA_FLAG },
685	[HWSIM_ATTR_FREQ] = { .type = NLA_U32 },
686	[HWSIM_ATTR_TX_INFO_FLAGS] = { .type = NLA_BINARY },
687	[HWSIM_ATTR_PERM_ADDR] = NLA_POLICY_ETH_ADDR_COMPAT,
688	[HWSIM_ATTR_IFTYPE_SUPPORT] = { .type = NLA_U32 },
689	[HWSIM_ATTR_CIPHER_SUPPORT] = { .type = NLA_BINARY },
690};
691
692#if IS_REACHABLE(CONFIG_VIRTIO)
693
694/* MAC80211_HWSIM virtio queues */
695static struct virtqueue *hwsim_vqs[HWSIM_NUM_VQS];
696static bool hwsim_virtio_enabled;
697static spinlock_t hwsim_virtio_lock;
698
699static void hwsim_virtio_rx_work(struct work_struct *work);
700static DECLARE_WORK(hwsim_virtio_rx, hwsim_virtio_rx_work);
701
702static int hwsim_tx_virtio(struct mac80211_hwsim_data *data,
703			   struct sk_buff *skb)
704{
705	struct scatterlist sg[1];
706	unsigned long flags;
707	int err;
708
709	spin_lock_irqsave(&hwsim_virtio_lock, flags);
710	if (!hwsim_virtio_enabled) {
711		err = -ENODEV;
712		goto out_free;
713	}
714
715	sg_init_one(sg, skb->head, skb_end_offset(skb));
716	err = virtqueue_add_outbuf(hwsim_vqs[HWSIM_VQ_TX], sg, 1, skb,
717				   GFP_ATOMIC);
718	if (err)
719		goto out_free;
720	virtqueue_kick(hwsim_vqs[HWSIM_VQ_TX]);
721	spin_unlock_irqrestore(&hwsim_virtio_lock, flags);
722	return 0;
723
724out_free:
725	spin_unlock_irqrestore(&hwsim_virtio_lock, flags);
726	nlmsg_free(skb);
727	return err;
728}
729#else
730/* cause a linker error if this ends up being needed */
731extern int hwsim_tx_virtio(struct mac80211_hwsim_data *data,
732			   struct sk_buff *skb);
733#define hwsim_virtio_enabled false
734#endif
735
736static void mac80211_hwsim_tx_frame(struct ieee80211_hw *hw,
737				    struct sk_buff *skb,
738				    struct ieee80211_channel *chan);
739
740/* sysfs attributes */
741static void hwsim_send_ps_poll(void *dat, u8 *mac, struct ieee80211_vif *vif)
742{
743	struct mac80211_hwsim_data *data = dat;
744	struct hwsim_vif_priv *vp = (void *)vif->drv_priv;
745	struct sk_buff *skb;
746	struct ieee80211_pspoll *pspoll;
747
748	if (!vp->assoc)
749		return;
750
751	wiphy_dbg(data->hw->wiphy,
752		  "%s: send PS-Poll to %pM for aid %d\n",
753		  __func__, vp->bssid, vp->aid);
754
755	skb = dev_alloc_skb(sizeof(*pspoll));
756	if (!skb)
757		return;
758	pspoll = skb_put(skb, sizeof(*pspoll));
759	pspoll->frame_control = cpu_to_le16(IEEE80211_FTYPE_CTL |
760					    IEEE80211_STYPE_PSPOLL |
761					    IEEE80211_FCTL_PM);
762	pspoll->aid = cpu_to_le16(0xc000 | vp->aid);
763	memcpy(pspoll->bssid, vp->bssid, ETH_ALEN);
764	memcpy(pspoll->ta, mac, ETH_ALEN);
765
766	rcu_read_lock();
767	mac80211_hwsim_tx_frame(data->hw, skb,
768				rcu_dereference(vif->chanctx_conf)->def.chan);
769	rcu_read_unlock();
770}
771
772static void hwsim_send_nullfunc(struct mac80211_hwsim_data *data, u8 *mac,
773				struct ieee80211_vif *vif, int ps)
774{
775	struct hwsim_vif_priv *vp = (void *)vif->drv_priv;
776	struct sk_buff *skb;
777	struct ieee80211_hdr *hdr;
778	struct ieee80211_tx_info *cb;
779
780	if (!vp->assoc)
781		return;
782
783	wiphy_dbg(data->hw->wiphy,
784		  "%s: send data::nullfunc to %pM ps=%d\n",
785		  __func__, vp->bssid, ps);
786
787	skb = dev_alloc_skb(sizeof(*hdr));
788	if (!skb)
789		return;
790	hdr = skb_put(skb, sizeof(*hdr) - ETH_ALEN);
791	hdr->frame_control = cpu_to_le16(IEEE80211_FTYPE_DATA |
792					 IEEE80211_STYPE_NULLFUNC |
793					 IEEE80211_FCTL_TODS |
794					 (ps ? IEEE80211_FCTL_PM : 0));
795	hdr->duration_id = cpu_to_le16(0);
796	memcpy(hdr->addr1, vp->bssid, ETH_ALEN);
797	memcpy(hdr->addr2, mac, ETH_ALEN);
798	memcpy(hdr->addr3, vp->bssid, ETH_ALEN);
799
800	cb = IEEE80211_SKB_CB(skb);
801	cb->control.rates[0].count = 1;
802	cb->control.rates[1].idx = -1;
803
804	rcu_read_lock();
805	mac80211_hwsim_tx_frame(data->hw, skb,
806				rcu_dereference(vif->chanctx_conf)->def.chan);
807	rcu_read_unlock();
808}
809
810
811static void hwsim_send_nullfunc_ps(void *dat, u8 *mac,
812				   struct ieee80211_vif *vif)
813{
814	struct mac80211_hwsim_data *data = dat;
815	hwsim_send_nullfunc(data, mac, vif, 1);
816}
817
818static void hwsim_send_nullfunc_no_ps(void *dat, u8 *mac,
819				      struct ieee80211_vif *vif)
820{
821	struct mac80211_hwsim_data *data = dat;
822	hwsim_send_nullfunc(data, mac, vif, 0);
823}
824
825static int hwsim_fops_ps_read(void *dat, u64 *val)
826{
827	struct mac80211_hwsim_data *data = dat;
828	*val = data->ps;
829	return 0;
830}
831
832static int hwsim_fops_ps_write(void *dat, u64 val)
833{
834	struct mac80211_hwsim_data *data = dat;
835	enum ps_mode old_ps;
836
837	if (val != PS_DISABLED && val != PS_ENABLED && val != PS_AUTO_POLL &&
838	    val != PS_MANUAL_POLL)
839		return -EINVAL;
840
841	if (val == PS_MANUAL_POLL) {
842		if (data->ps != PS_ENABLED)
843			return -EINVAL;
844		local_bh_disable();
845		ieee80211_iterate_active_interfaces_atomic(
846			data->hw, IEEE80211_IFACE_ITER_NORMAL,
847			hwsim_send_ps_poll, data);
848		local_bh_enable();
849		return 0;
850	}
851	old_ps = data->ps;
852	data->ps = val;
853
854	local_bh_disable();
855	if (old_ps == PS_DISABLED && val != PS_DISABLED) {
856		ieee80211_iterate_active_interfaces_atomic(
857			data->hw, IEEE80211_IFACE_ITER_NORMAL,
858			hwsim_send_nullfunc_ps, data);
859	} else if (old_ps != PS_DISABLED && val == PS_DISABLED) {
860		ieee80211_iterate_active_interfaces_atomic(
861			data->hw, IEEE80211_IFACE_ITER_NORMAL,
862			hwsim_send_nullfunc_no_ps, data);
863	}
864	local_bh_enable();
865
866	return 0;
867}
868
869DEFINE_DEBUGFS_ATTRIBUTE(hwsim_fops_ps, hwsim_fops_ps_read, hwsim_fops_ps_write,
870			 "%llu\n");
871
872static int hwsim_write_simulate_radar(void *dat, u64 val)
873{
874	struct mac80211_hwsim_data *data = dat;
875
876	ieee80211_radar_detected(data->hw);
877
878	return 0;
879}
880
881DEFINE_DEBUGFS_ATTRIBUTE(hwsim_simulate_radar, NULL,
882			 hwsim_write_simulate_radar, "%llu\n");
883
884static int hwsim_fops_group_read(void *dat, u64 *val)
885{
886	struct mac80211_hwsim_data *data = dat;
887	*val = data->group;
888	return 0;
889}
890
891static int hwsim_fops_group_write(void *dat, u64 val)
892{
893	struct mac80211_hwsim_data *data = dat;
894	data->group = val;
895	return 0;
896}
897
898DEFINE_DEBUGFS_ATTRIBUTE(hwsim_fops_group,
899			 hwsim_fops_group_read, hwsim_fops_group_write,
900			 "%llx\n");
901
902static netdev_tx_t hwsim_mon_xmit(struct sk_buff *skb,
903					struct net_device *dev)
904{
905	/* TODO: allow packet injection */
906	dev_kfree_skb(skb);
907	return NETDEV_TX_OK;
908}
909
910static inline u64 mac80211_hwsim_get_tsf_raw(void)
911{
912	return ktime_to_us(ktime_get_real());
913}
914
915static __le64 __mac80211_hwsim_get_tsf(struct mac80211_hwsim_data *data)
916{
917	u64 now = mac80211_hwsim_get_tsf_raw();
918	return cpu_to_le64(now + data->tsf_offset);
919}
920
921static u64 mac80211_hwsim_get_tsf(struct ieee80211_hw *hw,
922				  struct ieee80211_vif *vif)
923{
924	struct mac80211_hwsim_data *data = hw->priv;
925	return le64_to_cpu(__mac80211_hwsim_get_tsf(data));
926}
927
928static void mac80211_hwsim_set_tsf(struct ieee80211_hw *hw,
929		struct ieee80211_vif *vif, u64 tsf)
930{
931	struct mac80211_hwsim_data *data = hw->priv;
932	u64 now = mac80211_hwsim_get_tsf(hw, vif);
933	u32 bcn_int = data->beacon_int;
934	u64 delta = abs(tsf - now);
935
936	/* adjust after beaconing with new timestamp at old TBTT */
937	if (tsf > now) {
938		data->tsf_offset += delta;
939		data->bcn_delta = do_div(delta, bcn_int);
940	} else {
941		data->tsf_offset -= delta;
942		data->bcn_delta = -(s64)do_div(delta, bcn_int);
943	}
944}
945
946static void mac80211_hwsim_monitor_rx(struct ieee80211_hw *hw,
947				      struct sk_buff *tx_skb,
948				      struct ieee80211_channel *chan)
949{
950	struct mac80211_hwsim_data *data = hw->priv;
951	struct sk_buff *skb;
952	struct hwsim_radiotap_hdr *hdr;
953	u16 flags, bitrate;
954	struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx_skb);
955	struct ieee80211_rate *txrate = ieee80211_get_tx_rate(hw, info);
956
957	if (!txrate)
958		bitrate = 0;
959	else
960		bitrate = txrate->bitrate;
961
962	if (!netif_running(hwsim_mon))
963		return;
964
965	skb = skb_copy_expand(tx_skb, sizeof(*hdr), 0, GFP_ATOMIC);
966	if (skb == NULL)
967		return;
968
969	hdr = skb_push(skb, sizeof(*hdr));
970	hdr->hdr.it_version = PKTHDR_RADIOTAP_VERSION;
971	hdr->hdr.it_pad = 0;
972	hdr->hdr.it_len = cpu_to_le16(sizeof(*hdr));
973	hdr->hdr.it_present = cpu_to_le32((1 << IEEE80211_RADIOTAP_FLAGS) |
974					  (1 << IEEE80211_RADIOTAP_RATE) |
975					  (1 << IEEE80211_RADIOTAP_TSFT) |
976					  (1 << IEEE80211_RADIOTAP_CHANNEL));
977	hdr->rt_tsft = __mac80211_hwsim_get_tsf(data);
978	hdr->rt_flags = 0;
979	hdr->rt_rate = bitrate / 5;
980	hdr->rt_channel = cpu_to_le16(chan->center_freq);
981	flags = IEEE80211_CHAN_2GHZ;
982	if (txrate && txrate->flags & IEEE80211_RATE_ERP_G)
983		flags |= IEEE80211_CHAN_OFDM;
984	else
985		flags |= IEEE80211_CHAN_CCK;
986	hdr->rt_chbitmask = cpu_to_le16(flags);
987
988	skb->dev = hwsim_mon;
989	skb_reset_mac_header(skb);
990	skb->ip_summed = CHECKSUM_UNNECESSARY;
991	skb->pkt_type = PACKET_OTHERHOST;
992	skb->protocol = htons(ETH_P_802_2);
993	memset(skb->cb, 0, sizeof(skb->cb));
994	netif_rx(skb);
995}
996
997
998static void mac80211_hwsim_monitor_ack(struct ieee80211_channel *chan,
999				       const u8 *addr)
1000{
1001	struct sk_buff *skb;
1002	struct hwsim_radiotap_ack_hdr *hdr;
1003	u16 flags;
1004	struct ieee80211_hdr *hdr11;
1005
1006	if (!netif_running(hwsim_mon))
1007		return;
1008
1009	skb = dev_alloc_skb(100);
1010	if (skb == NULL)
1011		return;
1012
1013	hdr = skb_put(skb, sizeof(*hdr));
1014	hdr->hdr.it_version = PKTHDR_RADIOTAP_VERSION;
1015	hdr->hdr.it_pad = 0;
1016	hdr->hdr.it_len = cpu_to_le16(sizeof(*hdr));
1017	hdr->hdr.it_present = cpu_to_le32((1 << IEEE80211_RADIOTAP_FLAGS) |
1018					  (1 << IEEE80211_RADIOTAP_CHANNEL));
1019	hdr->rt_flags = 0;
1020	hdr->pad = 0;
1021	hdr->rt_channel = cpu_to_le16(chan->center_freq);
1022	flags = IEEE80211_CHAN_2GHZ;
1023	hdr->rt_chbitmask = cpu_to_le16(flags);
1024
1025	hdr11 = skb_put(skb, 10);
1026	hdr11->frame_control = cpu_to_le16(IEEE80211_FTYPE_CTL |
1027					   IEEE80211_STYPE_ACK);
1028	hdr11->duration_id = cpu_to_le16(0);
1029	memcpy(hdr11->addr1, addr, ETH_ALEN);
1030
1031	skb->dev = hwsim_mon;
1032	skb_reset_mac_header(skb);
1033	skb->ip_summed = CHECKSUM_UNNECESSARY;
1034	skb->pkt_type = PACKET_OTHERHOST;
1035	skb->protocol = htons(ETH_P_802_2);
1036	memset(skb->cb, 0, sizeof(skb->cb));
1037	netif_rx(skb);
1038}
1039
1040struct mac80211_hwsim_addr_match_data {
1041	u8 addr[ETH_ALEN];
1042	bool ret;
1043};
1044
1045static void mac80211_hwsim_addr_iter(void *data, u8 *mac,
1046				     struct ieee80211_vif *vif)
1047{
1048	struct mac80211_hwsim_addr_match_data *md = data;
1049
1050	if (memcmp(mac, md->addr, ETH_ALEN) == 0)
1051		md->ret = true;
1052}
1053
1054static bool mac80211_hwsim_addr_match(struct mac80211_hwsim_data *data,
1055				      const u8 *addr)
1056{
1057	struct mac80211_hwsim_addr_match_data md = {
1058		.ret = false,
1059	};
1060
1061	if (data->scanning && memcmp(addr, data->scan_addr, ETH_ALEN) == 0)
1062		return true;
1063
1064	memcpy(md.addr, addr, ETH_ALEN);
1065
1066	ieee80211_iterate_active_interfaces_atomic(data->hw,
1067						   IEEE80211_IFACE_ITER_NORMAL,
1068						   mac80211_hwsim_addr_iter,
1069						   &md);
1070
1071	return md.ret;
1072}
1073
1074static bool hwsim_ps_rx_ok(struct mac80211_hwsim_data *data,
1075			   struct sk_buff *skb)
1076{
1077	switch (data->ps) {
1078	case PS_DISABLED:
1079		return true;
1080	case PS_ENABLED:
1081		return false;
1082	case PS_AUTO_POLL:
1083		/* TODO: accept (some) Beacons by default and other frames only
1084		 * if pending PS-Poll has been sent */
1085		return true;
1086	case PS_MANUAL_POLL:
1087		/* Allow unicast frames to own address if there is a pending
1088		 * PS-Poll */
1089		if (data->ps_poll_pending &&
1090		    mac80211_hwsim_addr_match(data, skb->data + 4)) {
1091			data->ps_poll_pending = false;
1092			return true;
1093		}
1094		return false;
1095	}
1096
1097	return true;
1098}
1099
1100static int hwsim_unicast_netgroup(struct mac80211_hwsim_data *data,
1101				  struct sk_buff *skb, int portid)
1102{
1103	struct net *net;
1104	bool found = false;
1105	int res = -ENOENT;
1106
1107	rcu_read_lock();
1108	for_each_net_rcu(net) {
1109		if (data->netgroup == hwsim_net_get_netgroup(net)) {
1110			res = genlmsg_unicast(net, skb, portid);
1111			found = true;
1112			break;
1113		}
1114	}
1115	rcu_read_unlock();
1116
1117	if (!found)
1118		nlmsg_free(skb);
1119
1120	return res;
1121}
1122
1123static void mac80211_hwsim_config_mac_nl(struct ieee80211_hw *hw,
1124					 const u8 *addr, bool add)
1125{
1126	struct mac80211_hwsim_data *data = hw->priv;
1127	u32 _portid = READ_ONCE(data->wmediumd);
1128	struct sk_buff *skb;
1129	void *msg_head;
1130
1131	if (!_portid && !hwsim_virtio_enabled)
1132		return;
1133
1134	skb = genlmsg_new(GENLMSG_DEFAULT_SIZE, GFP_ATOMIC);
1135	if (!skb)
1136		return;
1137
1138	msg_head = genlmsg_put(skb, 0, 0, &hwsim_genl_family, 0,
1139			       add ? HWSIM_CMD_ADD_MAC_ADDR :
1140				     HWSIM_CMD_DEL_MAC_ADDR);
1141	if (!msg_head) {
1142		pr_debug("mac80211_hwsim: problem with msg_head\n");
1143		goto nla_put_failure;
1144	}
1145
1146	if (nla_put(skb, HWSIM_ATTR_ADDR_TRANSMITTER,
1147		    ETH_ALEN, data->addresses[1].addr))
1148		goto nla_put_failure;
1149
1150	if (nla_put(skb, HWSIM_ATTR_ADDR_RECEIVER, ETH_ALEN, addr))
1151		goto nla_put_failure;
1152
1153	genlmsg_end(skb, msg_head);
1154
1155	if (hwsim_virtio_enabled)
1156		hwsim_tx_virtio(data, skb);
1157	else
1158		hwsim_unicast_netgroup(data, skb, _portid);
1159	return;
1160nla_put_failure:
1161	nlmsg_free(skb);
1162}
1163
1164static inline u16 trans_tx_rate_flags_ieee2hwsim(struct ieee80211_tx_rate *rate)
1165{
1166	u16 result = 0;
1167
1168	if (rate->flags & IEEE80211_TX_RC_USE_RTS_CTS)
1169		result |= MAC80211_HWSIM_TX_RC_USE_RTS_CTS;
1170	if (rate->flags & IEEE80211_TX_RC_USE_CTS_PROTECT)
1171		result |= MAC80211_HWSIM_TX_RC_USE_CTS_PROTECT;
1172	if (rate->flags & IEEE80211_TX_RC_USE_SHORT_PREAMBLE)
1173		result |= MAC80211_HWSIM_TX_RC_USE_SHORT_PREAMBLE;
1174	if (rate->flags & IEEE80211_TX_RC_MCS)
1175		result |= MAC80211_HWSIM_TX_RC_MCS;
1176	if (rate->flags & IEEE80211_TX_RC_GREEN_FIELD)
1177		result |= MAC80211_HWSIM_TX_RC_GREEN_FIELD;
1178	if (rate->flags & IEEE80211_TX_RC_40_MHZ_WIDTH)
1179		result |= MAC80211_HWSIM_TX_RC_40_MHZ_WIDTH;
1180	if (rate->flags & IEEE80211_TX_RC_DUP_DATA)
1181		result |= MAC80211_HWSIM_TX_RC_DUP_DATA;
1182	if (rate->flags & IEEE80211_TX_RC_SHORT_GI)
1183		result |= MAC80211_HWSIM_TX_RC_SHORT_GI;
1184	if (rate->flags & IEEE80211_TX_RC_VHT_MCS)
1185		result |= MAC80211_HWSIM_TX_RC_VHT_MCS;
1186	if (rate->flags & IEEE80211_TX_RC_80_MHZ_WIDTH)
1187		result |= MAC80211_HWSIM_TX_RC_80_MHZ_WIDTH;
1188	if (rate->flags & IEEE80211_TX_RC_160_MHZ_WIDTH)
1189		result |= MAC80211_HWSIM_TX_RC_160_MHZ_WIDTH;
1190
1191	return result;
1192}
1193
1194static void mac80211_hwsim_tx_frame_nl(struct ieee80211_hw *hw,
1195				       struct sk_buff *my_skb,
1196				       int dst_portid,
1197				       struct ieee80211_channel *channel)
1198{
1199	struct sk_buff *skb;
1200	struct mac80211_hwsim_data *data = hw->priv;
1201	struct ieee80211_hdr *hdr = (struct ieee80211_hdr *) my_skb->data;
1202	struct ieee80211_tx_info *info = IEEE80211_SKB_CB(my_skb);
1203	void *msg_head;
1204	unsigned int hwsim_flags = 0;
1205	int i;
1206	struct hwsim_tx_rate tx_attempts[IEEE80211_TX_MAX_RATES];
1207	struct hwsim_tx_rate_flag tx_attempts_flags[IEEE80211_TX_MAX_RATES];
1208	uintptr_t cookie;
1209
1210	if (data->ps != PS_DISABLED)
1211		hdr->frame_control |= cpu_to_le16(IEEE80211_FCTL_PM);
1212	/* If the queue contains MAX_QUEUE skb's drop some */
1213	if (skb_queue_len(&data->pending) >= MAX_QUEUE) {
1214		/* Droping until WARN_QUEUE level */
1215		while (skb_queue_len(&data->pending) >= WARN_QUEUE) {
1216			ieee80211_free_txskb(hw, skb_dequeue(&data->pending));
1217			data->tx_dropped++;
1218		}
1219	}
1220
1221	skb = genlmsg_new(GENLMSG_DEFAULT_SIZE, GFP_ATOMIC);
1222	if (skb == NULL)
1223		goto nla_put_failure;
1224
1225	msg_head = genlmsg_put(skb, 0, 0, &hwsim_genl_family, 0,
1226			       HWSIM_CMD_FRAME);
1227	if (msg_head == NULL) {
1228		pr_debug("mac80211_hwsim: problem with msg_head\n");
1229		goto nla_put_failure;
1230	}
1231
1232	if (nla_put(skb, HWSIM_ATTR_ADDR_TRANSMITTER,
1233		    ETH_ALEN, data->addresses[1].addr))
1234		goto nla_put_failure;
1235
1236	/* We get the skb->data */
1237	if (nla_put(skb, HWSIM_ATTR_FRAME, my_skb->len, my_skb->data))
1238		goto nla_put_failure;
1239
1240	/* We get the flags for this transmission, and we translate them to
1241	   wmediumd flags  */
1242
1243	if (info->flags & IEEE80211_TX_CTL_REQ_TX_STATUS)
1244		hwsim_flags |= HWSIM_TX_CTL_REQ_TX_STATUS;
1245
1246	if (info->flags & IEEE80211_TX_CTL_NO_ACK)
1247		hwsim_flags |= HWSIM_TX_CTL_NO_ACK;
1248
1249	if (nla_put_u32(skb, HWSIM_ATTR_FLAGS, hwsim_flags))
1250		goto nla_put_failure;
1251
1252	if (nla_put_u32(skb, HWSIM_ATTR_FREQ, channel->center_freq))
1253		goto nla_put_failure;
1254
1255	/* We get the tx control (rate and retries) info*/
1256
1257	for (i = 0; i < IEEE80211_TX_MAX_RATES; i++) {
1258		tx_attempts[i].idx = info->status.rates[i].idx;
1259		tx_attempts_flags[i].idx = info->status.rates[i].idx;
1260		tx_attempts[i].count = info->status.rates[i].count;
1261		tx_attempts_flags[i].flags =
1262				trans_tx_rate_flags_ieee2hwsim(
1263						&info->status.rates[i]);
1264	}
1265
1266	if (nla_put(skb, HWSIM_ATTR_TX_INFO,
1267		    sizeof(struct hwsim_tx_rate)*IEEE80211_TX_MAX_RATES,
1268		    tx_attempts))
1269		goto nla_put_failure;
1270
1271	if (nla_put(skb, HWSIM_ATTR_TX_INFO_FLAGS,
1272		    sizeof(struct hwsim_tx_rate_flag) * IEEE80211_TX_MAX_RATES,
1273		    tx_attempts_flags))
1274		goto nla_put_failure;
1275
1276	/* We create a cookie to identify this skb */
1277	cookie = atomic_inc_return(&data->pending_cookie);
1278	info->rate_driver_data[0] = (void *)cookie;
1279	if (nla_put_u64_64bit(skb, HWSIM_ATTR_COOKIE, cookie, HWSIM_ATTR_PAD))
1280		goto nla_put_failure;
1281
1282	genlmsg_end(skb, msg_head);
1283
1284	if (hwsim_virtio_enabled) {
1285		if (hwsim_tx_virtio(data, skb))
1286			goto err_free_txskb;
1287	} else {
1288		if (hwsim_unicast_netgroup(data, skb, dst_portid))
1289			goto err_free_txskb;
1290	}
1291
1292	/* Enqueue the packet */
1293	skb_queue_tail(&data->pending, my_skb);
1294	data->tx_pkts++;
1295	data->tx_bytes += my_skb->len;
1296	return;
1297
1298nla_put_failure:
1299	nlmsg_free(skb);
1300err_free_txskb:
1301	pr_debug("mac80211_hwsim: error occurred in %s\n", __func__);
1302	ieee80211_free_txskb(hw, my_skb);
1303	data->tx_failed++;
1304}
1305
1306static bool hwsim_chans_compat(struct ieee80211_channel *c1,
1307			       struct ieee80211_channel *c2)
1308{
1309	if (!c1 || !c2)
1310		return false;
1311
1312	return c1->center_freq == c2->center_freq;
1313}
1314
1315struct tx_iter_data {
1316	struct ieee80211_channel *channel;
1317	bool receive;
1318};
1319
1320static void mac80211_hwsim_tx_iter(void *_data, u8 *addr,
1321				   struct ieee80211_vif *vif)
1322{
1323	struct tx_iter_data *data = _data;
1324
1325	if (!vif->chanctx_conf)
1326		return;
1327
1328	if (!hwsim_chans_compat(data->channel,
1329				rcu_dereference(vif->chanctx_conf)->def.chan))
1330		return;
1331
1332	data->receive = true;
1333}
1334
1335static void mac80211_hwsim_add_vendor_rtap(struct sk_buff *skb)
1336{
1337	/*
1338	 * To enable this code, #define the HWSIM_RADIOTAP_OUI,
1339	 * e.g. like this:
1340	 * #define HWSIM_RADIOTAP_OUI "\x02\x00\x00"
1341	 * (but you should use a valid OUI, not that)
1342	 *
1343	 * If anyone wants to 'donate' a radiotap OUI/subns code
1344	 * please send a patch removing this #ifdef and changing
1345	 * the values accordingly.
1346	 */
1347#ifdef HWSIM_RADIOTAP_OUI
1348	struct ieee80211_vendor_radiotap *rtap;
1349
1350	/*
1351	 * Note that this code requires the headroom in the SKB
1352	 * that was allocated earlier.
1353	 */
1354	rtap = skb_push(skb, sizeof(*rtap) + 8 + 4);
1355	rtap->oui[0] = HWSIM_RADIOTAP_OUI[0];
1356	rtap->oui[1] = HWSIM_RADIOTAP_OUI[1];
1357	rtap->oui[2] = HWSIM_RADIOTAP_OUI[2];
1358	rtap->subns = 127;
1359
1360	/*
1361	 * Radiotap vendor namespaces can (and should) also be
1362	 * split into fields by using the standard radiotap
1363	 * presence bitmap mechanism. Use just BIT(0) here for
1364	 * the presence bitmap.
1365	 */
1366	rtap->present = BIT(0);
1367	/* We have 8 bytes of (dummy) data */
1368	rtap->len = 8;
1369	/* For testing, also require it to be aligned */
1370	rtap->align = 8;
1371	/* And also test that padding works, 4 bytes */
1372	rtap->pad = 4;
1373	/* push the data */
1374	memcpy(rtap->data, "ABCDEFGH", 8);
1375	/* make sure to clear padding, mac80211 doesn't */
1376	memset(rtap->data + 8, 0, 4);
1377
1378	IEEE80211_SKB_RXCB(skb)->flag |= RX_FLAG_RADIOTAP_VENDOR_DATA;
1379#endif
1380}
1381
1382static bool mac80211_hwsim_tx_frame_no_nl(struct ieee80211_hw *hw,
1383					  struct sk_buff *skb,
1384					  struct ieee80211_channel *chan)
1385{
1386	struct mac80211_hwsim_data *data = hw->priv, *data2;
1387	bool ack = false;
1388	struct ieee80211_hdr *hdr = (struct ieee80211_hdr *) skb->data;
1389	struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
1390	struct ieee80211_rx_status rx_status;
1391	u64 now;
1392
1393	memset(&rx_status, 0, sizeof(rx_status));
1394	rx_status.flag |= RX_FLAG_MACTIME_START;
1395	rx_status.freq = chan->center_freq;
1396	rx_status.freq_offset = chan->freq_offset ? 1 : 0;
1397	rx_status.band = chan->band;
1398	if (info->control.rates[0].flags & IEEE80211_TX_RC_VHT_MCS) {
1399		rx_status.rate_idx =
1400			ieee80211_rate_get_vht_mcs(&info->control.rates[0]);
1401		rx_status.nss =
1402			ieee80211_rate_get_vht_nss(&info->control.rates[0]);
1403		rx_status.encoding = RX_ENC_VHT;
1404	} else {
1405		rx_status.rate_idx = info->control.rates[0].idx;
1406		if (info->control.rates[0].flags & IEEE80211_TX_RC_MCS)
1407			rx_status.encoding = RX_ENC_HT;
1408	}
1409	if (info->control.rates[0].flags & IEEE80211_TX_RC_40_MHZ_WIDTH)
1410		rx_status.bw = RATE_INFO_BW_40;
1411	else if (info->control.rates[0].flags & IEEE80211_TX_RC_80_MHZ_WIDTH)
1412		rx_status.bw = RATE_INFO_BW_80;
1413	else if (info->control.rates[0].flags & IEEE80211_TX_RC_160_MHZ_WIDTH)
1414		rx_status.bw = RATE_INFO_BW_160;
1415	else
1416		rx_status.bw = RATE_INFO_BW_20;
1417	if (info->control.rates[0].flags & IEEE80211_TX_RC_SHORT_GI)
1418		rx_status.enc_flags |= RX_ENC_FLAG_SHORT_GI;
1419	/* TODO: simulate real signal strength (and optional packet loss) */
1420	rx_status.signal = -50;
1421	if (info->control.vif)
1422		rx_status.signal += info->control.vif->bss_conf.txpower;
1423
1424	if (data->ps != PS_DISABLED)
1425		hdr->frame_control |= cpu_to_le16(IEEE80211_FCTL_PM);
1426
1427	/* release the skb's source info */
1428	skb_orphan(skb);
1429	skb_dst_drop(skb);
1430	skb->mark = 0;
1431	skb_ext_reset(skb);
1432	nf_reset_ct(skb);
1433
1434	/*
1435	 * Get absolute mactime here so all HWs RX at the "same time", and
1436	 * absolute TX time for beacon mactime so the timestamp matches.
1437	 * Giving beacons a different mactime than non-beacons looks messy, but
1438	 * it helps the Toffset be exact and a ~10us mactime discrepancy
1439	 * probably doesn't really matter.
1440	 */
1441	if (ieee80211_is_beacon(hdr->frame_control) ||
1442	    ieee80211_is_probe_resp(hdr->frame_control)) {
1443		rx_status.boottime_ns = ktime_get_boottime_ns();
1444		now = data->abs_bcn_ts;
1445	} else {
1446		now = mac80211_hwsim_get_tsf_raw();
1447	}
1448
1449	/* Copy skb to all enabled radios that are on the current frequency */
1450	spin_lock(&hwsim_radio_lock);
1451	list_for_each_entry(data2, &hwsim_radios, list) {
1452		struct sk_buff *nskb;
1453		struct tx_iter_data tx_iter_data = {
1454			.receive = false,
1455			.channel = chan,
1456		};
1457
1458		if (data == data2)
1459			continue;
1460
1461		if (!data2->started || (data2->idle && !data2->tmp_chan) ||
1462		    !hwsim_ps_rx_ok(data2, skb))
1463			continue;
1464
1465		if (!(data->group & data2->group))
1466			continue;
1467
1468		if (data->netgroup != data2->netgroup)
1469			continue;
1470
1471		if (!hwsim_chans_compat(chan, data2->tmp_chan) &&
1472		    !hwsim_chans_compat(chan, data2->channel)) {
1473			ieee80211_iterate_active_interfaces_atomic(
1474				data2->hw, IEEE80211_IFACE_ITER_NORMAL,
1475				mac80211_hwsim_tx_iter, &tx_iter_data);
1476			if (!tx_iter_data.receive)
1477				continue;
1478		}
1479
1480		/*
1481		 * reserve some space for our vendor and the normal
1482		 * radiotap header, since we're copying anyway
1483		 */
1484		if (skb->len < PAGE_SIZE && paged_rx) {
1485			struct page *page = alloc_page(GFP_ATOMIC);
1486
1487			if (!page)
1488				continue;
1489
1490			nskb = dev_alloc_skb(128);
1491			if (!nskb) {
1492				__free_page(page);
1493				continue;
1494			}
1495
1496			memcpy(page_address(page), skb->data, skb->len);
1497			skb_add_rx_frag(nskb, 0, page, 0, skb->len, skb->len);
1498		} else {
1499			nskb = skb_copy(skb, GFP_ATOMIC);
1500			if (!nskb)
1501				continue;
1502		}
1503
1504		if (mac80211_hwsim_addr_match(data2, hdr->addr1))
1505			ack = true;
1506
1507		rx_status.mactime = now + data2->tsf_offset;
1508
1509		memcpy(IEEE80211_SKB_RXCB(nskb), &rx_status, sizeof(rx_status));
1510
1511		mac80211_hwsim_add_vendor_rtap(nskb);
1512
1513		data2->rx_pkts++;
1514		data2->rx_bytes += nskb->len;
1515		ieee80211_rx_irqsafe(data2->hw, nskb);
1516	}
1517	spin_unlock(&hwsim_radio_lock);
1518
1519	return ack;
1520}
1521
1522static void mac80211_hwsim_tx(struct ieee80211_hw *hw,
1523			      struct ieee80211_tx_control *control,
1524			      struct sk_buff *skb)
1525{
1526	struct mac80211_hwsim_data *data = hw->priv;
1527	struct ieee80211_tx_info *txi = IEEE80211_SKB_CB(skb);
1528	struct ieee80211_hdr *hdr = (void *)skb->data;
1529	struct ieee80211_chanctx_conf *chanctx_conf;
1530	struct ieee80211_channel *channel;
1531	bool ack;
1532	u32 _portid;
1533
1534	if (WARN_ON(skb->len < 10)) {
1535		/* Should not happen; just a sanity check for addr1 use */
1536		ieee80211_free_txskb(hw, skb);
1537		return;
1538	}
1539
1540	if (!data->use_chanctx) {
1541		channel = data->channel;
1542	} else if (txi->hw_queue == 4) {
1543		channel = data->tmp_chan;
1544	} else {
1545		chanctx_conf = rcu_dereference(txi->control.vif->chanctx_conf);
1546		if (chanctx_conf)
1547			channel = chanctx_conf->def.chan;
1548		else
1549			channel = NULL;
1550	}
1551
1552	if (WARN(!channel, "TX w/o channel - queue = %d\n", txi->hw_queue)) {
1553		ieee80211_free_txskb(hw, skb);
1554		return;
1555	}
1556
1557	if (data->idle && !data->tmp_chan) {
1558		wiphy_dbg(hw->wiphy, "Trying to TX when idle - reject\n");
1559		ieee80211_free_txskb(hw, skb);
1560		return;
1561	}
1562
1563	if (txi->control.vif)
1564		hwsim_check_magic(txi->control.vif);
1565	if (control->sta)
1566		hwsim_check_sta_magic(control->sta);
1567
1568	if (ieee80211_hw_check(hw, SUPPORTS_RC_TABLE))
1569		ieee80211_get_tx_rates(txi->control.vif, control->sta, skb,
1570				       txi->control.rates,
1571				       ARRAY_SIZE(txi->control.rates));
1572
1573	if (skb->len >= 24 + 8 &&
1574	    ieee80211_is_probe_resp(hdr->frame_control)) {
1575		/* fake header transmission time */
1576		struct ieee80211_mgmt *mgmt;
1577		struct ieee80211_rate *txrate;
1578		/* TODO: get MCS */
1579		int bitrate = 100;
1580		u64 ts;
1581
1582		mgmt = (struct ieee80211_mgmt *)skb->data;
1583		txrate = ieee80211_get_tx_rate(hw, txi);
1584		if (txrate)
1585			bitrate = txrate->bitrate;
1586		ts = mac80211_hwsim_get_tsf_raw();
1587		mgmt->u.probe_resp.timestamp =
1588			cpu_to_le64(ts + data->tsf_offset +
1589				    24 * 8 * 10 / bitrate);
1590	}
1591
1592	mac80211_hwsim_monitor_rx(hw, skb, channel);
1593
1594	/* wmediumd mode check */
1595	_portid = READ_ONCE(data->wmediumd);
1596
1597	if (_portid || hwsim_virtio_enabled)
1598		return mac80211_hwsim_tx_frame_nl(hw, skb, _portid, channel);
1599
1600	/* NO wmediumd detected, perfect medium simulation */
1601	data->tx_pkts++;
1602	data->tx_bytes += skb->len;
1603	ack = mac80211_hwsim_tx_frame_no_nl(hw, skb, channel);
1604
1605	if (ack && skb->len >= 16)
1606		mac80211_hwsim_monitor_ack(channel, hdr->addr2);
1607
1608	ieee80211_tx_info_clear_status(txi);
1609
1610	/* frame was transmitted at most favorable rate at first attempt */
1611	txi->control.rates[0].count = 1;
1612	txi->control.rates[1].idx = -1;
1613
1614	if (!(txi->flags & IEEE80211_TX_CTL_NO_ACK) && ack)
1615		txi->flags |= IEEE80211_TX_STAT_ACK;
1616	ieee80211_tx_status_irqsafe(hw, skb);
1617}
1618
1619
1620static int mac80211_hwsim_start(struct ieee80211_hw *hw)
1621{
1622	struct mac80211_hwsim_data *data = hw->priv;
1623	wiphy_dbg(hw->wiphy, "%s\n", __func__);
1624	data->started = true;
1625	return 0;
1626}
1627
1628
1629static void mac80211_hwsim_stop(struct ieee80211_hw *hw)
1630{
1631	struct mac80211_hwsim_data *data = hw->priv;
1632
1633	data->started = false;
1634	hrtimer_cancel(&data->beacon_timer);
1635
1636	while (!skb_queue_empty(&data->pending))
1637		ieee80211_free_txskb(hw, skb_dequeue(&data->pending));
1638
1639	wiphy_dbg(hw->wiphy, "%s\n", __func__);
1640}
1641
1642
1643static int mac80211_hwsim_add_interface(struct ieee80211_hw *hw,
1644					struct ieee80211_vif *vif)
1645{
1646	wiphy_dbg(hw->wiphy, "%s (type=%d mac_addr=%pM)\n",
1647		  __func__, ieee80211_vif_type_p2p(vif),
1648		  vif->addr);
1649	hwsim_set_magic(vif);
1650
1651	if (vif->type != NL80211_IFTYPE_MONITOR)
1652		mac80211_hwsim_config_mac_nl(hw, vif->addr, true);
1653
1654	vif->cab_queue = 0;
1655	vif->hw_queue[IEEE80211_AC_VO] = 0;
1656	vif->hw_queue[IEEE80211_AC_VI] = 1;
1657	vif->hw_queue[IEEE80211_AC_BE] = 2;
1658	vif->hw_queue[IEEE80211_AC_BK] = 3;
1659
1660	return 0;
1661}
1662
1663
1664static int mac80211_hwsim_change_interface(struct ieee80211_hw *hw,
1665					   struct ieee80211_vif *vif,
1666					   enum nl80211_iftype newtype,
1667					   bool newp2p)
1668{
1669	newtype = ieee80211_iftype_p2p(newtype, newp2p);
1670	wiphy_dbg(hw->wiphy,
1671		  "%s (old type=%d, new type=%d, mac_addr=%pM)\n",
1672		  __func__, ieee80211_vif_type_p2p(vif),
1673		    newtype, vif->addr);
1674	hwsim_check_magic(vif);
1675
1676	/*
1677	 * interface may change from non-AP to AP in
1678	 * which case this needs to be set up again
1679	 */
1680	vif->cab_queue = 0;
1681
1682	return 0;
1683}
1684
1685static void mac80211_hwsim_remove_interface(
1686	struct ieee80211_hw *hw, struct ieee80211_vif *vif)
1687{
1688	wiphy_dbg(hw->wiphy, "%s (type=%d mac_addr=%pM)\n",
1689		  __func__, ieee80211_vif_type_p2p(vif),
1690		  vif->addr);
1691	hwsim_check_magic(vif);
1692	hwsim_clear_magic(vif);
1693	if (vif->type != NL80211_IFTYPE_MONITOR)
1694		mac80211_hwsim_config_mac_nl(hw, vif->addr, false);
1695}
1696
1697static void mac80211_hwsim_tx_frame(struct ieee80211_hw *hw,
1698				    struct sk_buff *skb,
1699				    struct ieee80211_channel *chan)
1700{
1701	struct mac80211_hwsim_data *data = hw->priv;
1702	u32 _pid = READ_ONCE(data->wmediumd);
1703
1704	if (ieee80211_hw_check(hw, SUPPORTS_RC_TABLE)) {
1705		struct ieee80211_tx_info *txi = IEEE80211_SKB_CB(skb);
1706		ieee80211_get_tx_rates(txi->control.vif, NULL, skb,
1707				       txi->control.rates,
1708				       ARRAY_SIZE(txi->control.rates));
1709	}
1710
1711	mac80211_hwsim_monitor_rx(hw, skb, chan);
1712
1713	if (_pid || hwsim_virtio_enabled)
1714		return mac80211_hwsim_tx_frame_nl(hw, skb, _pid, chan);
1715
1716	mac80211_hwsim_tx_frame_no_nl(hw, skb, chan);
1717	dev_kfree_skb(skb);
1718}
1719
1720static void mac80211_hwsim_beacon_tx(void *arg, u8 *mac,
1721				     struct ieee80211_vif *vif)
1722{
1723	struct mac80211_hwsim_data *data = arg;
1724	struct ieee80211_hw *hw = data->hw;
1725	struct ieee80211_tx_info *info;
1726	struct ieee80211_rate *txrate;
1727	struct ieee80211_mgmt *mgmt;
1728	struct sk_buff *skb;
1729	/* TODO: get MCS */
1730	int bitrate = 100;
1731
1732	hwsim_check_magic(vif);
1733
1734	if (vif->type != NL80211_IFTYPE_AP &&
1735	    vif->type != NL80211_IFTYPE_MESH_POINT &&
1736	    vif->type != NL80211_IFTYPE_ADHOC &&
1737	    vif->type != NL80211_IFTYPE_OCB)
1738		return;
1739
1740	skb = ieee80211_beacon_get(hw, vif);
1741	if (skb == NULL)
1742		return;
1743	info = IEEE80211_SKB_CB(skb);
1744	if (ieee80211_hw_check(hw, SUPPORTS_RC_TABLE))
1745		ieee80211_get_tx_rates(vif, NULL, skb,
1746				       info->control.rates,
1747				       ARRAY_SIZE(info->control.rates));
1748
1749	txrate = ieee80211_get_tx_rate(hw, info);
1750	if (txrate)
1751		bitrate = txrate->bitrate;
1752
1753	mgmt = (struct ieee80211_mgmt *) skb->data;
1754	/* fake header transmission time */
1755	data->abs_bcn_ts = mac80211_hwsim_get_tsf_raw();
1756	if (ieee80211_is_s1g_beacon(mgmt->frame_control)) {
1757		struct ieee80211_ext *ext = (void *) mgmt;
1758
1759		ext->u.s1g_beacon.timestamp = cpu_to_le32(data->abs_bcn_ts +
1760							  data->tsf_offset +
1761							  10 * 8 * 10 /
1762							  bitrate);
1763	} else {
1764		mgmt->u.beacon.timestamp = cpu_to_le64(data->abs_bcn_ts +
1765						       data->tsf_offset +
1766						       24 * 8 * 10 /
1767						       bitrate);
1768	}
1769
1770	mac80211_hwsim_tx_frame(hw, skb,
1771				rcu_dereference(vif->chanctx_conf)->def.chan);
1772
1773	while ((skb = ieee80211_get_buffered_bc(hw, vif)) != NULL) {
1774		mac80211_hwsim_tx_frame(hw, skb,
1775				rcu_dereference(vif->chanctx_conf)->def.chan);
1776	}
1777
1778	if (vif->csa_active && ieee80211_beacon_cntdwn_is_complete(vif))
1779		ieee80211_csa_finish(vif);
1780}
1781
1782static enum hrtimer_restart
1783mac80211_hwsim_beacon(struct hrtimer *timer)
1784{
1785	struct mac80211_hwsim_data *data =
1786		container_of(timer, struct mac80211_hwsim_data, beacon_timer);
1787	struct ieee80211_hw *hw = data->hw;
1788	u64 bcn_int = data->beacon_int;
1789
1790	if (!data->started)
1791		return HRTIMER_NORESTART;
1792
1793	ieee80211_iterate_active_interfaces_atomic(
1794		hw, IEEE80211_IFACE_ITER_NORMAL,
1795		mac80211_hwsim_beacon_tx, data);
1796
1797	/* beacon at new TBTT + beacon interval */
1798	if (data->bcn_delta) {
1799		bcn_int -= data->bcn_delta;
1800		data->bcn_delta = 0;
1801	}
1802	hrtimer_forward_now(&data->beacon_timer,
1803			    ns_to_ktime(bcn_int * NSEC_PER_USEC));
1804	return HRTIMER_RESTART;
1805}
1806
1807static const char * const hwsim_chanwidths[] = {
1808	[NL80211_CHAN_WIDTH_5] = "ht5",
1809	[NL80211_CHAN_WIDTH_10] = "ht10",
1810	[NL80211_CHAN_WIDTH_20_NOHT] = "noht",
1811	[NL80211_CHAN_WIDTH_20] = "ht20",
1812	[NL80211_CHAN_WIDTH_40] = "ht40",
1813	[NL80211_CHAN_WIDTH_80] = "vht80",
1814	[NL80211_CHAN_WIDTH_80P80] = "vht80p80",
1815	[NL80211_CHAN_WIDTH_160] = "vht160",
1816	[NL80211_CHAN_WIDTH_1] = "1MHz",
1817	[NL80211_CHAN_WIDTH_2] = "2MHz",
1818	[NL80211_CHAN_WIDTH_4] = "4MHz",
1819	[NL80211_CHAN_WIDTH_8] = "8MHz",
1820	[NL80211_CHAN_WIDTH_16] = "16MHz",
1821};
1822
1823static int mac80211_hwsim_config(struct ieee80211_hw *hw, u32 changed)
1824{
1825	struct mac80211_hwsim_data *data = hw->priv;
1826	struct ieee80211_conf *conf = &hw->conf;
1827	static const char *smps_modes[IEEE80211_SMPS_NUM_MODES] = {
1828		[IEEE80211_SMPS_AUTOMATIC] = "auto",
1829		[IEEE80211_SMPS_OFF] = "off",
1830		[IEEE80211_SMPS_STATIC] = "static",
1831		[IEEE80211_SMPS_DYNAMIC] = "dynamic",
1832	};
1833	int idx;
1834
1835	if (conf->chandef.chan)
1836		wiphy_dbg(hw->wiphy,
1837			  "%s (freq=%d(%d - %d)/%s idle=%d ps=%d smps=%s)\n",
1838			  __func__,
1839			  conf->chandef.chan->center_freq,
1840			  conf->chandef.center_freq1,
1841			  conf->chandef.center_freq2,
1842			  hwsim_chanwidths[conf->chandef.width],
1843			  !!(conf->flags & IEEE80211_CONF_IDLE),
1844			  !!(conf->flags & IEEE80211_CONF_PS),
1845			  smps_modes[conf->smps_mode]);
1846	else
1847		wiphy_dbg(hw->wiphy,
1848			  "%s (freq=0 idle=%d ps=%d smps=%s)\n",
1849			  __func__,
1850			  !!(conf->flags & IEEE80211_CONF_IDLE),
1851			  !!(conf->flags & IEEE80211_CONF_PS),
1852			  smps_modes[conf->smps_mode]);
1853
1854	data->idle = !!(conf->flags & IEEE80211_CONF_IDLE);
1855
1856	WARN_ON(conf->chandef.chan && data->use_chanctx);
1857
1858	mutex_lock(&data->mutex);
1859	if (data->scanning && conf->chandef.chan) {
1860		for (idx = 0; idx < ARRAY_SIZE(data->survey_data); idx++) {
1861			if (data->survey_data[idx].channel == data->channel) {
1862				data->survey_data[idx].start =
1863					data->survey_data[idx].next_start;
1864				data->survey_data[idx].end = jiffies;
1865				break;
1866			}
1867		}
1868
1869		data->channel = conf->chandef.chan;
1870
1871		for (idx = 0; idx < ARRAY_SIZE(data->survey_data); idx++) {
1872			if (data->survey_data[idx].channel &&
1873			    data->survey_data[idx].channel != data->channel)
1874				continue;
1875			data->survey_data[idx].channel = data->channel;
1876			data->survey_data[idx].next_start = jiffies;
1877			break;
1878		}
1879	} else {
1880		data->channel = conf->chandef.chan;
1881	}
1882	mutex_unlock(&data->mutex);
1883
1884	if (!data->started || !data->beacon_int)
1885		hrtimer_cancel(&data->beacon_timer);
1886	else if (!hrtimer_is_queued(&data->beacon_timer)) {
1887		u64 tsf = mac80211_hwsim_get_tsf(hw, NULL);
1888		u32 bcn_int = data->beacon_int;
1889		u64 until_tbtt = bcn_int - do_div(tsf, bcn_int);
1890
1891		hrtimer_start(&data->beacon_timer,
1892			      ns_to_ktime(until_tbtt * NSEC_PER_USEC),
1893			      HRTIMER_MODE_REL_SOFT);
1894	}
1895
1896	return 0;
1897}
1898
1899
1900static void mac80211_hwsim_configure_filter(struct ieee80211_hw *hw,
1901					    unsigned int changed_flags,
1902					    unsigned int *total_flags,u64 multicast)
1903{
1904	struct mac80211_hwsim_data *data = hw->priv;
1905
1906	wiphy_dbg(hw->wiphy, "%s\n", __func__);
1907
1908	data->rx_filter = 0;
1909	if (*total_flags & FIF_ALLMULTI)
1910		data->rx_filter |= FIF_ALLMULTI;
1911	if (*total_flags & FIF_MCAST_ACTION)
1912		data->rx_filter |= FIF_MCAST_ACTION;
1913
1914	*total_flags = data->rx_filter;
1915}
1916
1917static void mac80211_hwsim_bcn_en_iter(void *data, u8 *mac,
1918				       struct ieee80211_vif *vif)
1919{
1920	unsigned int *count = data;
1921	struct hwsim_vif_priv *vp = (void *)vif->drv_priv;
1922
1923	if (vp->bcn_en)
1924		(*count)++;
1925}
1926
1927static void mac80211_hwsim_bss_info_changed(struct ieee80211_hw *hw,
1928					    struct ieee80211_vif *vif,
1929					    struct ieee80211_bss_conf *info,
1930					    u32 changed)
1931{
1932	struct hwsim_vif_priv *vp = (void *)vif->drv_priv;
1933	struct mac80211_hwsim_data *data = hw->priv;
1934
1935	hwsim_check_magic(vif);
1936
1937	wiphy_dbg(hw->wiphy, "%s(changed=0x%x vif->addr=%pM)\n",
1938		  __func__, changed, vif->addr);
1939
1940	if (changed & BSS_CHANGED_BSSID) {
1941		wiphy_dbg(hw->wiphy, "%s: BSSID changed: %pM\n",
1942			  __func__, info->bssid);
1943		memcpy(vp->bssid, info->bssid, ETH_ALEN);
1944	}
1945
1946	if (changed & BSS_CHANGED_ASSOC) {
1947		wiphy_dbg(hw->wiphy, "  ASSOC: assoc=%d aid=%d\n",
1948			  info->assoc, info->aid);
1949		vp->assoc = info->assoc;
1950		vp->aid = info->aid;
1951	}
1952
1953	if (changed & BSS_CHANGED_BEACON_ENABLED) {
1954		wiphy_dbg(hw->wiphy, "  BCN EN: %d (BI=%u)\n",
1955			  info->enable_beacon, info->beacon_int);
1956		vp->bcn_en = info->enable_beacon;
1957		if (data->started &&
1958		    !hrtimer_is_queued(&data->beacon_timer) &&
1959		    info->enable_beacon) {
1960			u64 tsf, until_tbtt;
1961			u32 bcn_int;
1962			data->beacon_int = info->beacon_int * 1024;
1963			tsf = mac80211_hwsim_get_tsf(hw, vif);
1964			bcn_int = data->beacon_int;
1965			until_tbtt = bcn_int - do_div(tsf, bcn_int);
1966
1967			hrtimer_start(&data->beacon_timer,
1968				      ns_to_ktime(until_tbtt * NSEC_PER_USEC),
1969				      HRTIMER_MODE_REL_SOFT);
1970		} else if (!info->enable_beacon) {
1971			unsigned int count = 0;
1972			ieee80211_iterate_active_interfaces_atomic(
1973				data->hw, IEEE80211_IFACE_ITER_NORMAL,
1974				mac80211_hwsim_bcn_en_iter, &count);
1975			wiphy_dbg(hw->wiphy, "  beaconing vifs remaining: %u",
1976				  count);
1977			if (count == 0) {
1978				hrtimer_cancel(&data->beacon_timer);
1979				data->beacon_int = 0;
1980			}
1981		}
1982	}
1983
1984	if (changed & BSS_CHANGED_ERP_CTS_PROT) {
1985		wiphy_dbg(hw->wiphy, "  ERP_CTS_PROT: %d\n",
1986			  info->use_cts_prot);
1987	}
1988
1989	if (changed & BSS_CHANGED_ERP_PREAMBLE) {
1990		wiphy_dbg(hw->wiphy, "  ERP_PREAMBLE: %d\n",
1991			  info->use_short_preamble);
1992	}
1993
1994	if (changed & BSS_CHANGED_ERP_SLOT) {
1995		wiphy_dbg(hw->wiphy, "  ERP_SLOT: %d\n", info->use_short_slot);
1996	}
1997
1998	if (changed & BSS_CHANGED_HT) {
1999		wiphy_dbg(hw->wiphy, "  HT: op_mode=0x%x\n",
2000			  info->ht_operation_mode);
2001	}
2002
2003	if (changed & BSS_CHANGED_BASIC_RATES) {
2004		wiphy_dbg(hw->wiphy, "  BASIC_RATES: 0x%llx\n",
2005			  (unsigned long long) info->basic_rates);
2006	}
2007
2008	if (changed & BSS_CHANGED_TXPOWER)
2009		wiphy_dbg(hw->wiphy, "  TX Power: %d dBm\n", info->txpower);
2010}
2011
2012static int mac80211_hwsim_sta_add(struct ieee80211_hw *hw,
2013				  struct ieee80211_vif *vif,
2014				  struct ieee80211_sta *sta)
2015{
2016	hwsim_check_magic(vif);
2017	hwsim_set_sta_magic(sta);
2018
2019	return 0;
2020}
2021
2022static int mac80211_hwsim_sta_remove(struct ieee80211_hw *hw,
2023				     struct ieee80211_vif *vif,
2024				     struct ieee80211_sta *sta)
2025{
2026	hwsim_check_magic(vif);
2027	hwsim_clear_sta_magic(sta);
2028
2029	return 0;
2030}
2031
2032static void mac80211_hwsim_sta_notify(struct ieee80211_hw *hw,
2033				      struct ieee80211_vif *vif,
2034				      enum sta_notify_cmd cmd,
2035				      struct ieee80211_sta *sta)
2036{
2037	hwsim_check_magic(vif);
2038
2039	switch (cmd) {
2040	case STA_NOTIFY_SLEEP:
2041	case STA_NOTIFY_AWAKE:
2042		/* TODO: make good use of these flags */
2043		break;
2044	default:
2045		WARN(1, "Invalid sta notify: %d\n", cmd);
2046		break;
2047	}
2048}
2049
2050static int mac80211_hwsim_set_tim(struct ieee80211_hw *hw,
2051				  struct ieee80211_sta *sta,
2052				  bool set)
2053{
2054	hwsim_check_sta_magic(sta);
2055	return 0;
2056}
2057
2058static int mac80211_hwsim_conf_tx(
2059	struct ieee80211_hw *hw,
2060	struct ieee80211_vif *vif, u16 queue,
2061	const struct ieee80211_tx_queue_params *params)
2062{
2063	wiphy_dbg(hw->wiphy,
2064		  "%s (queue=%d txop=%d cw_min=%d cw_max=%d aifs=%d)\n",
2065		  __func__, queue,
2066		  params->txop, params->cw_min,
2067		  params->cw_max, params->aifs);
2068	return 0;
2069}
2070
2071static int mac80211_hwsim_get_survey(struct ieee80211_hw *hw, int idx,
2072				     struct survey_info *survey)
2073{
2074	struct mac80211_hwsim_data *hwsim = hw->priv;
2075
2076	if (idx < 0 || idx >= ARRAY_SIZE(hwsim->survey_data))
2077		return -ENOENT;
2078
2079	mutex_lock(&hwsim->mutex);
2080	survey->channel = hwsim->survey_data[idx].channel;
2081	if (!survey->channel) {
2082		mutex_unlock(&hwsim->mutex);
2083		return -ENOENT;
2084	}
2085
2086	/*
2087	 * Magically conjured dummy values --- this is only ok for simulated hardware.
2088	 *
2089	 * A real driver which cannot determine real values noise MUST NOT
2090	 * report any, especially not a magically conjured ones :-)
2091	 */
2092	survey->filled = SURVEY_INFO_NOISE_DBM |
2093			 SURVEY_INFO_TIME |
2094			 SURVEY_INFO_TIME_BUSY;
2095	survey->noise = -92;
2096	survey->time =
2097		jiffies_to_msecs(hwsim->survey_data[idx].end -
2098				 hwsim->survey_data[idx].start);
2099	/* report 12.5% of channel time is used */
2100	survey->time_busy = survey->time/8;
2101	mutex_unlock(&hwsim->mutex);
2102
2103	return 0;
2104}
2105
2106#ifdef CONFIG_NL80211_TESTMODE
2107/*
2108 * This section contains example code for using netlink
2109 * attributes with the testmode command in nl80211.
2110 */
2111
2112/* These enums need to be kept in sync with userspace */
2113enum hwsim_testmode_attr {
2114	__HWSIM_TM_ATTR_INVALID	= 0,
2115	HWSIM_TM_ATTR_CMD	= 1,
2116	HWSIM_TM_ATTR_PS	= 2,
2117
2118	/* keep last */
2119	__HWSIM_TM_ATTR_AFTER_LAST,
2120	HWSIM_TM_ATTR_MAX	= __HWSIM_TM_ATTR_AFTER_LAST - 1
2121};
2122
2123enum hwsim_testmode_cmd {
2124	HWSIM_TM_CMD_SET_PS		= 0,
2125	HWSIM_TM_CMD_GET_PS		= 1,
2126	HWSIM_TM_CMD_STOP_QUEUES	= 2,
2127	HWSIM_TM_CMD_WAKE_QUEUES	= 3,
2128};
2129
2130static const struct nla_policy hwsim_testmode_policy[HWSIM_TM_ATTR_MAX + 1] = {
2131	[HWSIM_TM_ATTR_CMD] = { .type = NLA_U32 },
2132	[HWSIM_TM_ATTR_PS] = { .type = NLA_U32 },
2133};
2134
2135static int mac80211_hwsim_testmode_cmd(struct ieee80211_hw *hw,
2136				       struct ieee80211_vif *vif,
2137				       void *data, int len)
2138{
2139	struct mac80211_hwsim_data *hwsim = hw->priv;
2140	struct nlattr *tb[HWSIM_TM_ATTR_MAX + 1];
2141	struct sk_buff *skb;
2142	int err, ps;
2143
2144	err = nla_parse_deprecated(tb, HWSIM_TM_ATTR_MAX, data, len,
2145				   hwsim_testmode_policy, NULL);
2146	if (err)
2147		return err;
2148
2149	if (!tb[HWSIM_TM_ATTR_CMD])
2150		return -EINVAL;
2151
2152	switch (nla_get_u32(tb[HWSIM_TM_ATTR_CMD])) {
2153	case HWSIM_TM_CMD_SET_PS:
2154		if (!tb[HWSIM_TM_ATTR_PS])
2155			return -EINVAL;
2156		ps = nla_get_u32(tb[HWSIM_TM_ATTR_PS]);
2157		return hwsim_fops_ps_write(hwsim, ps);
2158	case HWSIM_TM_CMD_GET_PS:
2159		skb = cfg80211_testmode_alloc_reply_skb(hw->wiphy,
2160						nla_total_size(sizeof(u32)));
2161		if (!skb)
2162			return -ENOMEM;
2163		if (nla_put_u32(skb, HWSIM_TM_ATTR_PS, hwsim->ps))
2164			goto nla_put_failure;
2165		return cfg80211_testmode_reply(skb);
2166	case HWSIM_TM_CMD_STOP_QUEUES:
2167		ieee80211_stop_queues(hw);
2168		return 0;
2169	case HWSIM_TM_CMD_WAKE_QUEUES:
2170		ieee80211_wake_queues(hw);
2171		return 0;
2172	default:
2173		return -EOPNOTSUPP;
2174	}
2175
2176 nla_put_failure:
2177	kfree_skb(skb);
2178	return -ENOBUFS;
2179}
2180#endif
2181
2182static int mac80211_hwsim_ampdu_action(struct ieee80211_hw *hw,
2183				       struct ieee80211_vif *vif,
2184				       struct ieee80211_ampdu_params *params)
2185{
2186	struct ieee80211_sta *sta = params->sta;
2187	enum ieee80211_ampdu_mlme_action action = params->action;
2188	u16 tid = params->tid;
2189
2190	switch (action) {
2191	case IEEE80211_AMPDU_TX_START:
2192		return IEEE80211_AMPDU_TX_START_IMMEDIATE;
2193	case IEEE80211_AMPDU_TX_STOP_CONT:
2194	case IEEE80211_AMPDU_TX_STOP_FLUSH:
2195	case IEEE80211_AMPDU_TX_STOP_FLUSH_CONT:
2196		ieee80211_stop_tx_ba_cb_irqsafe(vif, sta->addr, tid);
2197		break;
2198	case IEEE80211_AMPDU_TX_OPERATIONAL:
2199		break;
2200	case IEEE80211_AMPDU_RX_START:
2201	case IEEE80211_AMPDU_RX_STOP:
2202		break;
2203	default:
2204		return -EOPNOTSUPP;
2205	}
2206
2207	return 0;
2208}
2209
2210static void mac80211_hwsim_flush(struct ieee80211_hw *hw,
2211				 struct ieee80211_vif *vif,
2212				 u32 queues, bool drop)
2213{
2214	/* Not implemented, queues only on kernel side */
2215}
2216
2217static void hw_scan_work(struct work_struct *work)
2218{
2219	struct mac80211_hwsim_data *hwsim =
2220		container_of(work, struct mac80211_hwsim_data, hw_scan.work);
2221	struct cfg80211_scan_request *req = hwsim->hw_scan_request;
2222	int dwell, i;
2223
2224	mutex_lock(&hwsim->mutex);
2225	if (hwsim->scan_chan_idx >= req->n_channels) {
2226		struct cfg80211_scan_info info = {
2227			.aborted = false,
2228		};
2229
2230		wiphy_dbg(hwsim->hw->wiphy, "hw scan complete\n");
2231		ieee80211_scan_completed(hwsim->hw, &info);
2232		hwsim->hw_scan_request = NULL;
2233		hwsim->hw_scan_vif = NULL;
2234		hwsim->tmp_chan = NULL;
2235		mutex_unlock(&hwsim->mutex);
2236		mac80211_hwsim_config_mac_nl(hwsim->hw, hwsim->scan_addr,
2237					     false);
2238		return;
2239	}
2240
2241	wiphy_dbg(hwsim->hw->wiphy, "hw scan %d MHz\n",
2242		  req->channels[hwsim->scan_chan_idx]->center_freq);
2243
2244	hwsim->tmp_chan = req->channels[hwsim->scan_chan_idx];
2245	if (hwsim->tmp_chan->flags & (IEEE80211_CHAN_NO_IR |
2246				      IEEE80211_CHAN_RADAR) ||
2247	    !req->n_ssids) {
2248		dwell = 120;
2249	} else {
2250		dwell = 30;
2251		/* send probes */
2252		for (i = 0; i < req->n_ssids; i++) {
2253			struct sk_buff *probe;
2254			struct ieee80211_mgmt *mgmt;
2255
2256			probe = ieee80211_probereq_get(hwsim->hw,
2257						       hwsim->scan_addr,
2258						       req->ssids[i].ssid,
2259						       req->ssids[i].ssid_len,
2260						       req->ie_len);
2261			if (!probe)
2262				continue;
2263
2264			mgmt = (struct ieee80211_mgmt *) probe->data;
2265			memcpy(mgmt->da, req->bssid, ETH_ALEN);
2266			memcpy(mgmt->bssid, req->bssid, ETH_ALEN);
2267
2268			if (req->ie_len)
2269				skb_put_data(probe, req->ie, req->ie_len);
2270
2271			rcu_read_lock();
2272			if (!ieee80211_tx_prepare_skb(hwsim->hw,
2273						      hwsim->hw_scan_vif,
2274						      probe,
2275						      hwsim->tmp_chan->band,
2276						      NULL)) {
2277				rcu_read_unlock();
2278				kfree_skb(probe);
2279				continue;
2280			}
2281
2282			local_bh_disable();
2283			mac80211_hwsim_tx_frame(hwsim->hw, probe,
2284						hwsim->tmp_chan);
2285			rcu_read_unlock();
2286			local_bh_enable();
2287		}
2288	}
2289	ieee80211_queue_delayed_work(hwsim->hw, &hwsim->hw_scan,
2290				     msecs_to_jiffies(dwell));
2291	hwsim->survey_data[hwsim->scan_chan_idx].channel = hwsim->tmp_chan;
2292	hwsim->survey_data[hwsim->scan_chan_idx].start = jiffies;
2293	hwsim->survey_data[hwsim->scan_chan_idx].end =
2294		jiffies + msecs_to_jiffies(dwell);
2295	hwsim->scan_chan_idx++;
2296	mutex_unlock(&hwsim->mutex);
2297}
2298
2299static int mac80211_hwsim_hw_scan(struct ieee80211_hw *hw,
2300				  struct ieee80211_vif *vif,
2301				  struct ieee80211_scan_request *hw_req)
2302{
2303	struct mac80211_hwsim_data *hwsim = hw->priv;
2304	struct cfg80211_scan_request *req = &hw_req->req;
2305
2306	mutex_lock(&hwsim->mutex);
2307	if (WARN_ON(hwsim->tmp_chan || hwsim->hw_scan_request)) {
2308		mutex_unlock(&hwsim->mutex);
2309		return -EBUSY;
2310	}
2311	hwsim->hw_scan_request = req;
2312	hwsim->hw_scan_vif = vif;
2313	hwsim->scan_chan_idx = 0;
2314	if (req->flags & NL80211_SCAN_FLAG_RANDOM_ADDR)
2315		get_random_mask_addr(hwsim->scan_addr,
2316				     hw_req->req.mac_addr,
2317				     hw_req->req.mac_addr_mask);
2318	else
2319		memcpy(hwsim->scan_addr, vif->addr, ETH_ALEN);
2320	memset(hwsim->survey_data, 0, sizeof(hwsim->survey_data));
2321	mutex_unlock(&hwsim->mutex);
2322
2323	mac80211_hwsim_config_mac_nl(hw, hwsim->scan_addr, true);
2324	wiphy_dbg(hw->wiphy, "hwsim hw_scan request\n");
2325
2326	ieee80211_queue_delayed_work(hwsim->hw, &hwsim->hw_scan, 0);
2327
2328	return 0;
2329}
2330
2331static void mac80211_hwsim_cancel_hw_scan(struct ieee80211_hw *hw,
2332					  struct ieee80211_vif *vif)
2333{
2334	struct mac80211_hwsim_data *hwsim = hw->priv;
2335	struct cfg80211_scan_info info = {
2336		.aborted = true,
2337	};
2338
2339	wiphy_dbg(hw->wiphy, "hwsim cancel_hw_scan\n");
2340
2341	cancel_delayed_work_sync(&hwsim->hw_scan);
2342
2343	mutex_lock(&hwsim->mutex);
2344	ieee80211_scan_completed(hwsim->hw, &info);
2345	hwsim->tmp_chan = NULL;
2346	hwsim->hw_scan_request = NULL;
2347	hwsim->hw_scan_vif = NULL;
2348	mutex_unlock(&hwsim->mutex);
2349}
2350
2351static void mac80211_hwsim_sw_scan(struct ieee80211_hw *hw,
2352				   struct ieee80211_vif *vif,
2353				   const u8 *mac_addr)
2354{
2355	struct mac80211_hwsim_data *hwsim = hw->priv;
2356
2357	mutex_lock(&hwsim->mutex);
2358
2359	if (hwsim->scanning) {
2360		pr_debug("two hwsim sw_scans detected!\n");
2361		goto out;
2362	}
2363
2364	pr_debug("hwsim sw_scan request, prepping stuff\n");
2365
2366	memcpy(hwsim->scan_addr, mac_addr, ETH_ALEN);
2367	mac80211_hwsim_config_mac_nl(hw, hwsim->scan_addr, true);
2368	hwsim->scanning = true;
2369	memset(hwsim->survey_data, 0, sizeof(hwsim->survey_data));
2370
2371out:
2372	mutex_unlock(&hwsim->mutex);
2373}
2374
2375static void mac80211_hwsim_sw_scan_complete(struct ieee80211_hw *hw,
2376					    struct ieee80211_vif *vif)
2377{
2378	struct mac80211_hwsim_data *hwsim = hw->priv;
2379
2380	mutex_lock(&hwsim->mutex);
2381
2382	pr_debug("hwsim sw_scan_complete\n");
2383	hwsim->scanning = false;
2384	mac80211_hwsim_config_mac_nl(hw, hwsim->scan_addr, false);
2385	eth_zero_addr(hwsim->scan_addr);
2386
2387	mutex_unlock(&hwsim->mutex);
2388}
2389
2390static void hw_roc_start(struct work_struct *work)
2391{
2392	struct mac80211_hwsim_data *hwsim =
2393		container_of(work, struct mac80211_hwsim_data, roc_start.work);
2394
2395	mutex_lock(&hwsim->mutex);
2396
2397	wiphy_dbg(hwsim->hw->wiphy, "hwsim ROC begins\n");
2398	hwsim->tmp_chan = hwsim->roc_chan;
2399	ieee80211_ready_on_channel(hwsim->hw);
2400
2401	ieee80211_queue_delayed_work(hwsim->hw, &hwsim->roc_done,
2402				     msecs_to_jiffies(hwsim->roc_duration));
2403
2404	mutex_unlock(&hwsim->mutex);
2405}
2406
2407static void hw_roc_done(struct work_struct *work)
2408{
2409	struct mac80211_hwsim_data *hwsim =
2410		container_of(work, struct mac80211_hwsim_data, roc_done.work);
2411
2412	mutex_lock(&hwsim->mutex);
2413	ieee80211_remain_on_channel_expired(hwsim->hw);
2414	hwsim->tmp_chan = NULL;
2415	mutex_unlock(&hwsim->mutex);
2416
2417	wiphy_dbg(hwsim->hw->wiphy, "hwsim ROC expired\n");
2418}
2419
2420static int mac80211_hwsim_roc(struct ieee80211_hw *hw,
2421			      struct ieee80211_vif *vif,
2422			      struct ieee80211_channel *chan,
2423			      int duration,
2424			      enum ieee80211_roc_type type)
2425{
2426	struct mac80211_hwsim_data *hwsim = hw->priv;
2427
2428	mutex_lock(&hwsim->mutex);
2429	if (WARN_ON(hwsim->tmp_chan || hwsim->hw_scan_request)) {
2430		mutex_unlock(&hwsim->mutex);
2431		return -EBUSY;
2432	}
2433
2434	hwsim->roc_chan = chan;
2435	hwsim->roc_duration = duration;
2436	mutex_unlock(&hwsim->mutex);
2437
2438	wiphy_dbg(hw->wiphy, "hwsim ROC (%d MHz, %d ms)\n",
2439		  chan->center_freq, duration);
2440	ieee80211_queue_delayed_work(hw, &hwsim->roc_start, HZ/50);
2441
2442	return 0;
2443}
2444
2445static int mac80211_hwsim_croc(struct ieee80211_hw *hw,
2446			       struct ieee80211_vif *vif)
2447{
2448	struct mac80211_hwsim_data *hwsim = hw->priv;
2449
2450	cancel_delayed_work_sync(&hwsim->roc_start);
2451	cancel_delayed_work_sync(&hwsim->roc_done);
2452
2453	mutex_lock(&hwsim->mutex);
2454	hwsim->tmp_chan = NULL;
2455	mutex_unlock(&hwsim->mutex);
2456
2457	wiphy_dbg(hw->wiphy, "hwsim ROC canceled\n");
2458
2459	return 0;
2460}
2461
2462static int mac80211_hwsim_add_chanctx(struct ieee80211_hw *hw,
2463				      struct ieee80211_chanctx_conf *ctx)
2464{
2465	struct mac80211_hwsim_data *hwsim = hw->priv;
2466
2467	mutex_lock(&hwsim->mutex);
2468	hwsim->chanctx = ctx;
2469	mutex_unlock(&hwsim->mutex);
2470	hwsim_set_chanctx_magic(ctx);
2471	wiphy_dbg(hw->wiphy,
2472		  "add channel context control: %d MHz/width: %d/cfreqs:%d/%d MHz\n",
2473		  ctx->def.chan->center_freq, ctx->def.width,
2474		  ctx->def.center_freq1, ctx->def.center_freq2);
2475	return 0;
2476}
2477
2478static void mac80211_hwsim_remove_chanctx(struct ieee80211_hw *hw,
2479					  struct ieee80211_chanctx_conf *ctx)
2480{
2481	struct mac80211_hwsim_data *hwsim = hw->priv;
2482
2483	mutex_lock(&hwsim->mutex);
2484	hwsim->chanctx = NULL;
2485	mutex_unlock(&hwsim->mutex);
2486	wiphy_dbg(hw->wiphy,
2487		  "remove channel context control: %d MHz/width: %d/cfreqs:%d/%d MHz\n",
2488		  ctx->def.chan->center_freq, ctx->def.width,
2489		  ctx->def.center_freq1, ctx->def.center_freq2);
2490	hwsim_check_chanctx_magic(ctx);
2491	hwsim_clear_chanctx_magic(ctx);
2492}
2493
2494static void mac80211_hwsim_change_chanctx(struct ieee80211_hw *hw,
2495					  struct ieee80211_chanctx_conf *ctx,
2496					  u32 changed)
2497{
2498	struct mac80211_hwsim_data *hwsim = hw->priv;
2499
2500	mutex_lock(&hwsim->mutex);
2501	hwsim->chanctx = ctx;
2502	mutex_unlock(&hwsim->mutex);
2503	hwsim_check_chanctx_magic(ctx);
2504	wiphy_dbg(hw->wiphy,
2505		  "change channel context control: %d MHz/width: %d/cfreqs:%d/%d MHz\n",
2506		  ctx->def.chan->center_freq, ctx->def.width,
2507		  ctx->def.center_freq1, ctx->def.center_freq2);
2508}
2509
2510static int mac80211_hwsim_assign_vif_chanctx(struct ieee80211_hw *hw,
2511					     struct ieee80211_vif *vif,
2512					     struct ieee80211_chanctx_conf *ctx)
2513{
2514	hwsim_check_magic(vif);
2515	hwsim_check_chanctx_magic(ctx);
2516
2517	return 0;
2518}
2519
2520static void mac80211_hwsim_unassign_vif_chanctx(struct ieee80211_hw *hw,
2521						struct ieee80211_vif *vif,
2522						struct ieee80211_chanctx_conf *ctx)
2523{
2524	hwsim_check_magic(vif);
2525	hwsim_check_chanctx_magic(ctx);
2526}
2527
2528static const char mac80211_hwsim_gstrings_stats[][ETH_GSTRING_LEN] = {
2529	"tx_pkts_nic",
2530	"tx_bytes_nic",
2531	"rx_pkts_nic",
2532	"rx_bytes_nic",
2533	"d_tx_dropped",
2534	"d_tx_failed",
2535	"d_ps_mode",
2536	"d_group",
2537};
2538
2539#define MAC80211_HWSIM_SSTATS_LEN ARRAY_SIZE(mac80211_hwsim_gstrings_stats)
2540
2541static void mac80211_hwsim_get_et_strings(struct ieee80211_hw *hw,
2542					  struct ieee80211_vif *vif,
2543					  u32 sset, u8 *data)
2544{
2545	if (sset == ETH_SS_STATS)
2546		memcpy(data, mac80211_hwsim_gstrings_stats,
2547		       sizeof(mac80211_hwsim_gstrings_stats));
2548}
2549
2550static int mac80211_hwsim_get_et_sset_count(struct ieee80211_hw *hw,
2551					    struct ieee80211_vif *vif, int sset)
2552{
2553	if (sset == ETH_SS_STATS)
2554		return MAC80211_HWSIM_SSTATS_LEN;
2555	return 0;
2556}
2557
2558static void mac80211_hwsim_get_et_stats(struct ieee80211_hw *hw,
2559					struct ieee80211_vif *vif,
2560					struct ethtool_stats *stats, u64 *data)
2561{
2562	struct mac80211_hwsim_data *ar = hw->priv;
2563	int i = 0;
2564
2565	data[i++] = ar->tx_pkts;
2566	data[i++] = ar->tx_bytes;
2567	data[i++] = ar->rx_pkts;
2568	data[i++] = ar->rx_bytes;
2569	data[i++] = ar->tx_dropped;
2570	data[i++] = ar->tx_failed;
2571	data[i++] = ar->ps;
2572	data[i++] = ar->group;
2573
2574	WARN_ON(i != MAC80211_HWSIM_SSTATS_LEN);
2575}
2576
2577static int mac80211_hwsim_tx_last_beacon(struct ieee80211_hw *hw)
2578{
2579	return 1;
2580}
2581
2582#define HWSIM_COMMON_OPS					\
2583	.tx = mac80211_hwsim_tx,				\
2584	.start = mac80211_hwsim_start,				\
2585	.stop = mac80211_hwsim_stop,				\
2586	.add_interface = mac80211_hwsim_add_interface,		\
2587	.change_interface = mac80211_hwsim_change_interface,	\
2588	.remove_interface = mac80211_hwsim_remove_interface,	\
2589	.config = mac80211_hwsim_config,			\
2590	.configure_filter = mac80211_hwsim_configure_filter,	\
2591	.bss_info_changed = mac80211_hwsim_bss_info_changed,	\
2592	.tx_last_beacon = mac80211_hwsim_tx_last_beacon,	\
2593	.sta_add = mac80211_hwsim_sta_add,			\
2594	.sta_remove = mac80211_hwsim_sta_remove,		\
2595	.sta_notify = mac80211_hwsim_sta_notify,		\
2596	.set_tim = mac80211_hwsim_set_tim,			\
2597	.conf_tx = mac80211_hwsim_conf_tx,			\
2598	.get_survey = mac80211_hwsim_get_survey,		\
2599	CFG80211_TESTMODE_CMD(mac80211_hwsim_testmode_cmd)	\
2600	.ampdu_action = mac80211_hwsim_ampdu_action,		\
2601	.flush = mac80211_hwsim_flush,				\
2602	.get_tsf = mac80211_hwsim_get_tsf,			\
2603	.set_tsf = mac80211_hwsim_set_tsf,			\
2604	.get_et_sset_count = mac80211_hwsim_get_et_sset_count,	\
2605	.get_et_stats = mac80211_hwsim_get_et_stats,		\
2606	.get_et_strings = mac80211_hwsim_get_et_strings,
2607
2608static const struct ieee80211_ops mac80211_hwsim_ops = {
2609	HWSIM_COMMON_OPS
2610	.sw_scan_start = mac80211_hwsim_sw_scan,
2611	.sw_scan_complete = mac80211_hwsim_sw_scan_complete,
2612};
2613
2614static const struct ieee80211_ops mac80211_hwsim_mchan_ops = {
2615	HWSIM_COMMON_OPS
2616	.hw_scan = mac80211_hwsim_hw_scan,
2617	.cancel_hw_scan = mac80211_hwsim_cancel_hw_scan,
2618	.sw_scan_start = NULL,
2619	.sw_scan_complete = NULL,
2620	.remain_on_channel = mac80211_hwsim_roc,
2621	.cancel_remain_on_channel = mac80211_hwsim_croc,
2622	.add_chanctx = mac80211_hwsim_add_chanctx,
2623	.remove_chanctx = mac80211_hwsim_remove_chanctx,
2624	.change_chanctx = mac80211_hwsim_change_chanctx,
2625	.assign_vif_chanctx = mac80211_hwsim_assign_vif_chanctx,
2626	.unassign_vif_chanctx = mac80211_hwsim_unassign_vif_chanctx,
2627};
2628
2629struct hwsim_new_radio_params {
2630	unsigned int channels;
2631	const char *reg_alpha2;
2632	const struct ieee80211_regdomain *regd;
2633	bool reg_strict;
2634	bool p2p_device;
2635	bool use_chanctx;
2636	bool destroy_on_close;
2637	const char *hwname;
2638	bool no_vif;
2639	const u8 *perm_addr;
2640	u32 iftypes;
2641	u32 *ciphers;
2642	u8 n_ciphers;
2643};
2644
2645static void hwsim_mcast_config_msg(struct sk_buff *mcast_skb,
2646				   struct genl_info *info)
2647{
2648	if (info)
2649		genl_notify(&hwsim_genl_family, mcast_skb, info,
2650			    HWSIM_MCGRP_CONFIG, GFP_KERNEL);
2651	else
2652		genlmsg_multicast(&hwsim_genl_family, mcast_skb, 0,
2653				  HWSIM_MCGRP_CONFIG, GFP_KERNEL);
2654}
2655
2656static int append_radio_msg(struct sk_buff *skb, int id,
2657			    struct hwsim_new_radio_params *param)
2658{
2659	int ret;
2660
2661	ret = nla_put_u32(skb, HWSIM_ATTR_RADIO_ID, id);
2662	if (ret < 0)
2663		return ret;
2664
2665	if (param->channels) {
2666		ret = nla_put_u32(skb, HWSIM_ATTR_CHANNELS, param->channels);
2667		if (ret < 0)
2668			return ret;
2669	}
2670
2671	if (param->reg_alpha2) {
2672		ret = nla_put(skb, HWSIM_ATTR_REG_HINT_ALPHA2, 2,
2673			      param->reg_alpha2);
2674		if (ret < 0)
2675			return ret;
2676	}
2677
2678	if (param->regd) {
2679		int i;
2680
2681		for (i = 0; i < ARRAY_SIZE(hwsim_world_regdom_custom); i++) {
2682			if (hwsim_world_regdom_custom[i] != param->regd)
2683				continue;
2684
2685			ret = nla_put_u32(skb, HWSIM_ATTR_REG_CUSTOM_REG, i);
2686			if (ret < 0)
2687				return ret;
2688			break;
2689		}
2690	}
2691
2692	if (param->reg_strict) {
2693		ret = nla_put_flag(skb, HWSIM_ATTR_REG_STRICT_REG);
2694		if (ret < 0)
2695			return ret;
2696	}
2697
2698	if (param->p2p_device) {
2699		ret = nla_put_flag(skb, HWSIM_ATTR_SUPPORT_P2P_DEVICE);
2700		if (ret < 0)
2701			return ret;
2702	}
2703
2704	if (param->use_chanctx) {
2705		ret = nla_put_flag(skb, HWSIM_ATTR_USE_CHANCTX);
2706		if (ret < 0)
2707			return ret;
2708	}
2709
2710	if (param->hwname) {
2711		ret = nla_put(skb, HWSIM_ATTR_RADIO_NAME,
2712			      strlen(param->hwname), param->hwname);
2713		if (ret < 0)
2714			return ret;
2715	}
2716
2717	return 0;
2718}
2719
2720static void hwsim_mcast_new_radio(int id, struct genl_info *info,
2721				  struct hwsim_new_radio_params *param)
2722{
2723	struct sk_buff *mcast_skb;
2724	void *data;
2725
2726	mcast_skb = genlmsg_new(GENLMSG_DEFAULT_SIZE, GFP_KERNEL);
2727	if (!mcast_skb)
2728		return;
2729
2730	data = genlmsg_put(mcast_skb, 0, 0, &hwsim_genl_family, 0,
2731			   HWSIM_CMD_NEW_RADIO);
2732	if (!data)
2733		goto out_err;
2734
2735	if (append_radio_msg(mcast_skb, id, param) < 0)
2736		goto out_err;
2737
2738	genlmsg_end(mcast_skb, data);
2739
2740	hwsim_mcast_config_msg(mcast_skb, info);
2741	return;
2742
2743out_err:
2744	nlmsg_free(mcast_skb);
2745}
2746
2747static const struct ieee80211_sband_iftype_data he_capa_2ghz[] = {
2748	{
2749		/* TODO: should we support other types, e.g., P2P?*/
2750		.types_mask = BIT(NL80211_IFTYPE_STATION) |
2751			      BIT(NL80211_IFTYPE_AP),
2752		.he_cap = {
2753			.has_he = true,
2754			.he_cap_elem = {
2755				.mac_cap_info[0] =
2756					IEEE80211_HE_MAC_CAP0_HTC_HE,
2757				.mac_cap_info[1] =
2758					IEEE80211_HE_MAC_CAP1_TF_MAC_PAD_DUR_16US |
2759					IEEE80211_HE_MAC_CAP1_MULTI_TID_AGG_RX_QOS_8,
2760				.mac_cap_info[2] =
2761					IEEE80211_HE_MAC_CAP2_BSR |
2762					IEEE80211_HE_MAC_CAP2_MU_CASCADING |
2763					IEEE80211_HE_MAC_CAP2_ACK_EN,
2764				.mac_cap_info[3] =
2765					IEEE80211_HE_MAC_CAP3_OMI_CONTROL |
2766					IEEE80211_HE_MAC_CAP3_MAX_AMPDU_LEN_EXP_VHT_2,
2767				.mac_cap_info[4] = IEEE80211_HE_MAC_CAP4_AMDSU_IN_AMPDU,
2768				.phy_cap_info[1] =
2769					IEEE80211_HE_PHY_CAP1_PREAMBLE_PUNC_RX_MASK |
2770					IEEE80211_HE_PHY_CAP1_DEVICE_CLASS_A |
2771					IEEE80211_HE_PHY_CAP1_LDPC_CODING_IN_PAYLOAD |
2772					IEEE80211_HE_PHY_CAP1_MIDAMBLE_RX_TX_MAX_NSTS,
2773				.phy_cap_info[2] =
2774					IEEE80211_HE_PHY_CAP2_NDP_4x_LTF_AND_3_2US |
2775					IEEE80211_HE_PHY_CAP2_STBC_TX_UNDER_80MHZ |
2776					IEEE80211_HE_PHY_CAP2_STBC_RX_UNDER_80MHZ |
2777					IEEE80211_HE_PHY_CAP2_UL_MU_FULL_MU_MIMO |
2778					IEEE80211_HE_PHY_CAP2_UL_MU_PARTIAL_MU_MIMO,
2779
2780				/* Leave all the other PHY capability bytes
2781				 * unset, as DCM, beam forming, RU and PPE
2782				 * threshold information are not supported
2783				 */
2784			},
2785			.he_mcs_nss_supp = {
2786				.rx_mcs_80 = cpu_to_le16(0xfffa),
2787				.tx_mcs_80 = cpu_to_le16(0xfffa),
2788				.rx_mcs_160 = cpu_to_le16(0xffff),
2789				.tx_mcs_160 = cpu_to_le16(0xffff),
2790				.rx_mcs_80p80 = cpu_to_le16(0xffff),
2791				.tx_mcs_80p80 = cpu_to_le16(0xffff),
2792			},
2793		},
2794	},
2795#ifdef CONFIG_MAC80211_MESH
2796	{
2797		/* TODO: should we support other types, e.g., IBSS?*/
2798		.types_mask = BIT(NL80211_IFTYPE_MESH_POINT),
2799		.he_cap = {
2800			.has_he = true,
2801			.he_cap_elem = {
2802				.mac_cap_info[0] =
2803					IEEE80211_HE_MAC_CAP0_HTC_HE,
2804				.mac_cap_info[1] =
2805					IEEE80211_HE_MAC_CAP1_MULTI_TID_AGG_RX_QOS_8,
2806				.mac_cap_info[2] =
2807					IEEE80211_HE_MAC_CAP2_ACK_EN,
2808				.mac_cap_info[3] =
2809					IEEE80211_HE_MAC_CAP3_OMI_CONTROL |
2810					IEEE80211_HE_MAC_CAP3_MAX_AMPDU_LEN_EXP_VHT_2,
2811				.mac_cap_info[4] = IEEE80211_HE_MAC_CAP4_AMDSU_IN_AMPDU,
2812				.phy_cap_info[1] =
2813					IEEE80211_HE_PHY_CAP1_PREAMBLE_PUNC_RX_MASK |
2814					IEEE80211_HE_PHY_CAP1_DEVICE_CLASS_A |
2815					IEEE80211_HE_PHY_CAP1_LDPC_CODING_IN_PAYLOAD |
2816					IEEE80211_HE_PHY_CAP1_MIDAMBLE_RX_TX_MAX_NSTS,
2817				.phy_cap_info[2] = 0,
2818
2819				/* Leave all the other PHY capability bytes
2820				 * unset, as DCM, beam forming, RU and PPE
2821				 * threshold information are not supported
2822				 */
2823			},
2824			.he_mcs_nss_supp = {
2825				.rx_mcs_80 = cpu_to_le16(0xfffa),
2826				.tx_mcs_80 = cpu_to_le16(0xfffa),
2827				.rx_mcs_160 = cpu_to_le16(0xffff),
2828				.tx_mcs_160 = cpu_to_le16(0xffff),
2829				.rx_mcs_80p80 = cpu_to_le16(0xffff),
2830				.tx_mcs_80p80 = cpu_to_le16(0xffff),
2831			},
2832		},
2833	},
2834#endif
2835};
2836
2837static const struct ieee80211_sband_iftype_data he_capa_5ghz[] = {
2838	{
2839		/* TODO: should we support other types, e.g., P2P?*/
2840		.types_mask = BIT(NL80211_IFTYPE_STATION) |
2841			      BIT(NL80211_IFTYPE_AP),
2842		.he_cap = {
2843			.has_he = true,
2844			.he_cap_elem = {
2845				.mac_cap_info[0] =
2846					IEEE80211_HE_MAC_CAP0_HTC_HE,
2847				.mac_cap_info[1] =
2848					IEEE80211_HE_MAC_CAP1_TF_MAC_PAD_DUR_16US |
2849					IEEE80211_HE_MAC_CAP1_MULTI_TID_AGG_RX_QOS_8,
2850				.mac_cap_info[2] =
2851					IEEE80211_HE_MAC_CAP2_BSR |
2852					IEEE80211_HE_MAC_CAP2_MU_CASCADING |
2853					IEEE80211_HE_MAC_CAP2_ACK_EN,
2854				.mac_cap_info[3] =
2855					IEEE80211_HE_MAC_CAP3_OMI_CONTROL |
2856					IEEE80211_HE_MAC_CAP3_MAX_AMPDU_LEN_EXP_VHT_2,
2857				.mac_cap_info[4] = IEEE80211_HE_MAC_CAP4_AMDSU_IN_AMPDU,
2858				.phy_cap_info[0] =
2859					IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_40MHZ_80MHZ_IN_5G |
2860					IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_160MHZ_IN_5G |
2861					IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_80PLUS80_MHZ_IN_5G,
2862				.phy_cap_info[1] =
2863					IEEE80211_HE_PHY_CAP1_PREAMBLE_PUNC_RX_MASK |
2864					IEEE80211_HE_PHY_CAP1_DEVICE_CLASS_A |
2865					IEEE80211_HE_PHY_CAP1_LDPC_CODING_IN_PAYLOAD |
2866					IEEE80211_HE_PHY_CAP1_MIDAMBLE_RX_TX_MAX_NSTS,
2867				.phy_cap_info[2] =
2868					IEEE80211_HE_PHY_CAP2_NDP_4x_LTF_AND_3_2US |
2869					IEEE80211_HE_PHY_CAP2_STBC_TX_UNDER_80MHZ |
2870					IEEE80211_HE_PHY_CAP2_STBC_RX_UNDER_80MHZ |
2871					IEEE80211_HE_PHY_CAP2_UL_MU_FULL_MU_MIMO |
2872					IEEE80211_HE_PHY_CAP2_UL_MU_PARTIAL_MU_MIMO,
2873
2874				/* Leave all the other PHY capability bytes
2875				 * unset, as DCM, beam forming, RU and PPE
2876				 * threshold information are not supported
2877				 */
2878			},
2879			.he_mcs_nss_supp = {
2880				.rx_mcs_80 = cpu_to_le16(0xfffa),
2881				.tx_mcs_80 = cpu_to_le16(0xfffa),
2882				.rx_mcs_160 = cpu_to_le16(0xfffa),
2883				.tx_mcs_160 = cpu_to_le16(0xfffa),
2884				.rx_mcs_80p80 = cpu_to_le16(0xfffa),
2885				.tx_mcs_80p80 = cpu_to_le16(0xfffa),
2886			},
2887		},
2888	},
2889#ifdef CONFIG_MAC80211_MESH
2890	{
2891		/* TODO: should we support other types, e.g., IBSS?*/
2892		.types_mask = BIT(NL80211_IFTYPE_MESH_POINT),
2893		.he_cap = {
2894			.has_he = true,
2895			.he_cap_elem = {
2896				.mac_cap_info[0] =
2897					IEEE80211_HE_MAC_CAP0_HTC_HE,
2898				.mac_cap_info[1] =
2899					IEEE80211_HE_MAC_CAP1_MULTI_TID_AGG_RX_QOS_8,
2900				.mac_cap_info[2] =
2901					IEEE80211_HE_MAC_CAP2_ACK_EN,
2902				.mac_cap_info[3] =
2903					IEEE80211_HE_MAC_CAP3_OMI_CONTROL |
2904					IEEE80211_HE_MAC_CAP3_MAX_AMPDU_LEN_EXP_VHT_2,
2905				.mac_cap_info[4] = IEEE80211_HE_MAC_CAP4_AMDSU_IN_AMPDU,
2906				.phy_cap_info[0] =
2907					IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_40MHZ_80MHZ_IN_5G |
2908					IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_160MHZ_IN_5G |
2909					IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_80PLUS80_MHZ_IN_5G,
2910				.phy_cap_info[1] =
2911					IEEE80211_HE_PHY_CAP1_PREAMBLE_PUNC_RX_MASK |
2912					IEEE80211_HE_PHY_CAP1_DEVICE_CLASS_A |
2913					IEEE80211_HE_PHY_CAP1_LDPC_CODING_IN_PAYLOAD |
2914					IEEE80211_HE_PHY_CAP1_MIDAMBLE_RX_TX_MAX_NSTS,
2915				.phy_cap_info[2] = 0,
2916
2917				/* Leave all the other PHY capability bytes
2918				 * unset, as DCM, beam forming, RU and PPE
2919				 * threshold information are not supported
2920				 */
2921			},
2922			.he_mcs_nss_supp = {
2923				.rx_mcs_80 = cpu_to_le16(0xfffa),
2924				.tx_mcs_80 = cpu_to_le16(0xfffa),
2925				.rx_mcs_160 = cpu_to_le16(0xfffa),
2926				.tx_mcs_160 = cpu_to_le16(0xfffa),
2927				.rx_mcs_80p80 = cpu_to_le16(0xfffa),
2928				.tx_mcs_80p80 = cpu_to_le16(0xfffa),
2929			},
2930		},
2931	},
2932#endif
2933};
2934
2935static void mac80211_hwsim_he_capab(struct ieee80211_supported_band *sband)
2936{
2937	u16 n_iftype_data;
2938
2939	if (sband->band == NL80211_BAND_2GHZ) {
2940		n_iftype_data = ARRAY_SIZE(he_capa_2ghz);
2941		sband->iftype_data =
2942			(struct ieee80211_sband_iftype_data *)he_capa_2ghz;
2943	} else if (sband->band == NL80211_BAND_5GHZ) {
2944		n_iftype_data = ARRAY_SIZE(he_capa_5ghz);
2945		sband->iftype_data =
2946			(struct ieee80211_sband_iftype_data *)he_capa_5ghz;
2947	} else {
2948		return;
2949	}
2950
2951	sband->n_iftype_data = n_iftype_data;
2952}
2953
2954#ifdef CONFIG_MAC80211_MESH
2955#define HWSIM_MESH_BIT BIT(NL80211_IFTYPE_MESH_POINT)
2956#else
2957#define HWSIM_MESH_BIT 0
2958#endif
2959
2960#define HWSIM_DEFAULT_IF_LIMIT \
2961	(BIT(NL80211_IFTYPE_STATION) | \
2962	 BIT(NL80211_IFTYPE_P2P_CLIENT) | \
2963	 BIT(NL80211_IFTYPE_AP) | \
2964	 BIT(NL80211_IFTYPE_P2P_GO) | \
2965	 HWSIM_MESH_BIT)
2966
2967#define HWSIM_IFTYPE_SUPPORT_MASK \
2968	(BIT(NL80211_IFTYPE_STATION) | \
2969	 BIT(NL80211_IFTYPE_AP) | \
2970	 BIT(NL80211_IFTYPE_P2P_CLIENT) | \
2971	 BIT(NL80211_IFTYPE_P2P_GO) | \
2972	 BIT(NL80211_IFTYPE_ADHOC) | \
2973	 BIT(NL80211_IFTYPE_MESH_POINT) | \
2974	 BIT(NL80211_IFTYPE_OCB))
2975
2976static int mac80211_hwsim_new_radio(struct genl_info *info,
2977				    struct hwsim_new_radio_params *param)
2978{
2979	int err;
2980	u8 addr[ETH_ALEN];
2981	struct mac80211_hwsim_data *data;
2982	struct ieee80211_hw *hw;
2983	enum nl80211_band band;
2984	const struct ieee80211_ops *ops = &mac80211_hwsim_ops;
2985	struct net *net;
2986	int idx, i;
2987	int n_limits = 0;
2988
2989	if (WARN_ON(param->channels > 1 && !param->use_chanctx))
2990		return -EINVAL;
2991
2992	spin_lock_bh(&hwsim_radio_lock);
2993	idx = hwsim_radio_idx++;
2994	spin_unlock_bh(&hwsim_radio_lock);
2995
2996	if (param->use_chanctx)
2997		ops = &mac80211_hwsim_mchan_ops;
2998	hw = ieee80211_alloc_hw_nm(sizeof(*data), ops, param->hwname);
2999	if (!hw) {
3000		pr_debug("mac80211_hwsim: ieee80211_alloc_hw failed\n");
3001		err = -ENOMEM;
3002		goto failed;
3003	}
3004
3005	/* ieee80211_alloc_hw_nm may have used a default name */
3006	param->hwname = wiphy_name(hw->wiphy);
3007
3008	if (info)
3009		net = genl_info_net(info);
3010	else
3011		net = &init_net;
3012	wiphy_net_set(hw->wiphy, net);
3013
3014	data = hw->priv;
3015	data->hw = hw;
3016
3017	data->dev = device_create(hwsim_class, NULL, 0, hw, "hwsim%d", idx);
3018	if (IS_ERR(data->dev)) {
3019		printk(KERN_DEBUG
3020		       "mac80211_hwsim: device_create failed (%ld)\n",
3021		       PTR_ERR(data->dev));
3022		err = -ENOMEM;
3023		goto failed_drvdata;
3024	}
3025	data->dev->driver = &mac80211_hwsim_driver.driver;
3026	err = device_bind_driver(data->dev);
3027	if (err != 0) {
3028		pr_debug("mac80211_hwsim: device_bind_driver failed (%d)\n",
3029		       err);
3030		goto failed_bind;
3031	}
3032
3033	skb_queue_head_init(&data->pending);
3034
3035	SET_IEEE80211_DEV(hw, data->dev);
3036	if (!param->perm_addr) {
3037		eth_zero_addr(addr);
3038		addr[0] = 0x02;
3039		addr[3] = idx >> 8;
3040		addr[4] = idx;
3041		memcpy(data->addresses[0].addr, addr, ETH_ALEN);
3042		/* Why need here second address ? */
3043		memcpy(data->addresses[1].addr, addr, ETH_ALEN);
3044		data->addresses[1].addr[0] |= 0x40;
3045		hw->wiphy->n_addresses = 2;
3046		hw->wiphy->addresses = data->addresses;
3047		/* possible address clash is checked at hash table insertion */
3048	} else {
3049		memcpy(data->addresses[0].addr, param->perm_addr, ETH_ALEN);
3050		/* compatibility with automatically generated mac addr */
3051		memcpy(data->addresses[1].addr, param->perm_addr, ETH_ALEN);
3052		hw->wiphy->n_addresses = 2;
3053		hw->wiphy->addresses = data->addresses;
3054	}
3055
3056	data->channels = param->channels;
3057	data->use_chanctx = param->use_chanctx;
3058	data->idx = idx;
3059	data->destroy_on_close = param->destroy_on_close;
3060	if (info)
3061		data->portid = info->snd_portid;
3062
3063	/* setup interface limits, only on interface types we support */
3064	if (param->iftypes & BIT(NL80211_IFTYPE_ADHOC)) {
3065		data->if_limits[n_limits].max = 1;
3066		data->if_limits[n_limits].types = BIT(NL80211_IFTYPE_ADHOC);
3067		n_limits++;
3068	}
3069
3070	if (param->iftypes & HWSIM_DEFAULT_IF_LIMIT) {
3071		data->if_limits[n_limits].max = 2048;
3072		/*
3073		 * For this case, we may only support a subset of
3074		 * HWSIM_DEFAULT_IF_LIMIT, therefore we only want to add the
3075		 * bits that both param->iftype & HWSIM_DEFAULT_IF_LIMIT have.
3076		 */
3077		data->if_limits[n_limits].types =
3078					HWSIM_DEFAULT_IF_LIMIT & param->iftypes;
3079		n_limits++;
3080	}
3081
3082	if (param->iftypes & BIT(NL80211_IFTYPE_P2P_DEVICE)) {
3083		data->if_limits[n_limits].max = 1;
3084		data->if_limits[n_limits].types =
3085						BIT(NL80211_IFTYPE_P2P_DEVICE);
3086		n_limits++;
3087	}
3088
3089	if (data->use_chanctx) {
3090		hw->wiphy->max_scan_ssids = 255;
3091		hw->wiphy->max_scan_ie_len = IEEE80211_MAX_DATA_LEN;
3092		hw->wiphy->max_remain_on_channel_duration = 1000;
3093		data->if_combination.radar_detect_widths = 0;
3094		data->if_combination.num_different_channels = data->channels;
3095		data->chanctx = NULL;
3096	} else {
3097		data->if_combination.num_different_channels = 1;
3098		data->if_combination.radar_detect_widths =
3099					BIT(NL80211_CHAN_WIDTH_5) |
3100					BIT(NL80211_CHAN_WIDTH_10) |
3101					BIT(NL80211_CHAN_WIDTH_20_NOHT) |
3102					BIT(NL80211_CHAN_WIDTH_20) |
3103					BIT(NL80211_CHAN_WIDTH_40) |
3104					BIT(NL80211_CHAN_WIDTH_80) |
3105					BIT(NL80211_CHAN_WIDTH_160);
3106	}
3107
3108	if (!n_limits) {
3109		err = -EINVAL;
3110		goto failed_hw;
3111	}
3112
3113	data->if_combination.max_interfaces = 0;
3114	for (i = 0; i < n_limits; i++)
3115		data->if_combination.max_interfaces +=
3116			data->if_limits[i].max;
3117
3118	data->if_combination.n_limits = n_limits;
3119	data->if_combination.limits = data->if_limits;
3120
3121	/*
3122	 * If we actually were asked to support combinations,
3123	 * advertise them - if there's only a single thing like
3124	 * only IBSS then don't advertise it as combinations.
3125	 */
3126	if (data->if_combination.max_interfaces > 1) {
3127		hw->wiphy->iface_combinations = &data->if_combination;
3128		hw->wiphy->n_iface_combinations = 1;
3129	}
3130
3131	if (param->ciphers) {
3132		memcpy(data->ciphers, param->ciphers,
3133		       param->n_ciphers * sizeof(u32));
3134		hw->wiphy->cipher_suites = data->ciphers;
3135		hw->wiphy->n_cipher_suites = param->n_ciphers;
3136	}
3137
3138	INIT_DELAYED_WORK(&data->roc_start, hw_roc_start);
3139	INIT_DELAYED_WORK(&data->roc_done, hw_roc_done);
3140	INIT_DELAYED_WORK(&data->hw_scan, hw_scan_work);
3141
3142	hw->queues = 5;
3143	hw->offchannel_tx_hw_queue = 4;
3144
3145	ieee80211_hw_set(hw, SUPPORT_FAST_XMIT);
3146	ieee80211_hw_set(hw, CHANCTX_STA_CSA);
3147	ieee80211_hw_set(hw, SUPPORTS_HT_CCK_RATES);
3148	ieee80211_hw_set(hw, QUEUE_CONTROL);
3149	ieee80211_hw_set(hw, WANT_MONITOR_VIF);
3150	ieee80211_hw_set(hw, AMPDU_AGGREGATION);
3151	ieee80211_hw_set(hw, MFP_CAPABLE);
3152	ieee80211_hw_set(hw, SIGNAL_DBM);
3153	ieee80211_hw_set(hw, SUPPORTS_PS);
3154	ieee80211_hw_set(hw, REPORTS_TX_ACK_STATUS);
3155	ieee80211_hw_set(hw, HOST_BROADCAST_PS_BUFFERING);
3156	ieee80211_hw_set(hw, PS_NULLFUNC_STACK);
3157	ieee80211_hw_set(hw, TDLS_WIDER_BW);
3158	if (rctbl)
3159		ieee80211_hw_set(hw, SUPPORTS_RC_TABLE);
3160	ieee80211_hw_set(hw, SUPPORTS_MULTI_BSSID);
3161
3162	hw->wiphy->flags &= ~WIPHY_FLAG_PS_ON_BY_DEFAULT;
3163	hw->wiphy->flags |= WIPHY_FLAG_SUPPORTS_TDLS |
3164			    WIPHY_FLAG_HAS_REMAIN_ON_CHANNEL |
3165			    WIPHY_FLAG_AP_UAPSD |
3166			    WIPHY_FLAG_SUPPORTS_5_10_MHZ |
3167			    WIPHY_FLAG_HAS_CHANNEL_SWITCH;
3168	hw->wiphy->features |= NL80211_FEATURE_ACTIVE_MONITOR |
3169			       NL80211_FEATURE_AP_MODE_CHAN_WIDTH_CHANGE |
3170			       NL80211_FEATURE_STATIC_SMPS |
3171			       NL80211_FEATURE_DYNAMIC_SMPS |
3172			       NL80211_FEATURE_SCAN_RANDOM_MAC_ADDR;
3173	wiphy_ext_feature_set(hw->wiphy, NL80211_EXT_FEATURE_VHT_IBSS);
3174	wiphy_ext_feature_set(hw->wiphy, NL80211_EXT_FEATURE_BEACON_PROTECTION);
3175	wiphy_ext_feature_set(hw->wiphy,
3176			      NL80211_EXT_FEATURE_MULTICAST_REGISTRATIONS);
3177	wiphy_ext_feature_set(hw->wiphy,
3178			      NL80211_EXT_FEATURE_BEACON_RATE_LEGACY);
3179
3180	hw->wiphy->interface_modes = param->iftypes;
3181
3182	/* ask mac80211 to reserve space for magic */
3183	hw->vif_data_size = sizeof(struct hwsim_vif_priv);
3184	hw->sta_data_size = sizeof(struct hwsim_sta_priv);
3185	hw->chanctx_data_size = sizeof(struct hwsim_chanctx_priv);
3186
3187	memcpy(data->channels_2ghz, hwsim_channels_2ghz,
3188		sizeof(hwsim_channels_2ghz));
3189	memcpy(data->channels_5ghz, hwsim_channels_5ghz,
3190		sizeof(hwsim_channels_5ghz));
3191	memcpy(data->channels_s1g, hwsim_channels_s1g,
3192	       sizeof(hwsim_channels_s1g));
3193	memcpy(data->rates, hwsim_rates, sizeof(hwsim_rates));
3194
3195	for (band = NL80211_BAND_2GHZ; band < NUM_NL80211_BANDS; band++) {
3196		struct ieee80211_supported_band *sband = &data->bands[band];
3197
3198		sband->band = band;
3199
3200		switch (band) {
3201		case NL80211_BAND_2GHZ:
3202			sband->channels = data->channels_2ghz;
3203			sband->n_channels = ARRAY_SIZE(hwsim_channels_2ghz);
3204			sband->bitrates = data->rates;
3205			sband->n_bitrates = ARRAY_SIZE(hwsim_rates);
3206			break;
3207		case NL80211_BAND_5GHZ:
3208			sband->channels = data->channels_5ghz;
3209			sband->n_channels = ARRAY_SIZE(hwsim_channels_5ghz);
3210			sband->bitrates = data->rates + 4;
3211			sband->n_bitrates = ARRAY_SIZE(hwsim_rates) - 4;
3212
3213			sband->vht_cap.vht_supported = true;
3214			sband->vht_cap.cap =
3215				IEEE80211_VHT_CAP_MAX_MPDU_LENGTH_11454 |
3216				IEEE80211_VHT_CAP_SUPP_CHAN_WIDTH_160_80PLUS80MHZ |
3217				IEEE80211_VHT_CAP_RXLDPC |
3218				IEEE80211_VHT_CAP_SHORT_GI_80 |
3219				IEEE80211_VHT_CAP_SHORT_GI_160 |
3220				IEEE80211_VHT_CAP_TXSTBC |
3221				IEEE80211_VHT_CAP_RXSTBC_4 |
3222				IEEE80211_VHT_CAP_MAX_A_MPDU_LENGTH_EXPONENT_MASK;
3223			sband->vht_cap.vht_mcs.rx_mcs_map =
3224				cpu_to_le16(IEEE80211_VHT_MCS_SUPPORT_0_9 << 0 |
3225					    IEEE80211_VHT_MCS_SUPPORT_0_9 << 2 |
3226					    IEEE80211_VHT_MCS_SUPPORT_0_9 << 4 |
3227					    IEEE80211_VHT_MCS_SUPPORT_0_9 << 6 |
3228					    IEEE80211_VHT_MCS_SUPPORT_0_9 << 8 |
3229					    IEEE80211_VHT_MCS_SUPPORT_0_9 << 10 |
3230					    IEEE80211_VHT_MCS_SUPPORT_0_9 << 12 |
3231					    IEEE80211_VHT_MCS_SUPPORT_0_9 << 14);
3232			sband->vht_cap.vht_mcs.tx_mcs_map =
3233				sband->vht_cap.vht_mcs.rx_mcs_map;
3234			break;
3235		case NL80211_BAND_S1GHZ:
3236			memcpy(&sband->s1g_cap, &hwsim_s1g_cap,
3237			       sizeof(sband->s1g_cap));
3238			sband->channels = data->channels_s1g;
3239			sband->n_channels = ARRAY_SIZE(hwsim_channels_s1g);
3240			break;
3241		default:
3242			continue;
3243		}
3244
3245		sband->ht_cap.ht_supported = true;
3246		sband->ht_cap.cap = IEEE80211_HT_CAP_SUP_WIDTH_20_40 |
3247				    IEEE80211_HT_CAP_GRN_FLD |
3248				    IEEE80211_HT_CAP_SGI_20 |
3249				    IEEE80211_HT_CAP_SGI_40 |
3250				    IEEE80211_HT_CAP_DSSSCCK40;
3251		sband->ht_cap.ampdu_factor = 0x3;
3252		sband->ht_cap.ampdu_density = 0x6;
3253		memset(&sband->ht_cap.mcs, 0,
3254		       sizeof(sband->ht_cap.mcs));
3255		sband->ht_cap.mcs.rx_mask[0] = 0xff;
3256		sband->ht_cap.mcs.rx_mask[1] = 0xff;
3257		sband->ht_cap.mcs.tx_params = IEEE80211_HT_MCS_TX_DEFINED;
3258
3259		mac80211_hwsim_he_capab(sband);
3260
3261		hw->wiphy->bands[band] = sband;
3262	}
3263
3264	/* By default all radios belong to the first group */
3265	data->group = 1;
3266	mutex_init(&data->mutex);
3267
3268	data->netgroup = hwsim_net_get_netgroup(net);
3269	data->wmediumd = hwsim_net_get_wmediumd(net);
3270
3271	/* Enable frame retransmissions for lossy channels */
3272	hw->max_rates = 4;
3273	hw->max_rate_tries = 11;
3274
3275	hw->wiphy->vendor_commands = mac80211_hwsim_vendor_commands;
3276	hw->wiphy->n_vendor_commands =
3277		ARRAY_SIZE(mac80211_hwsim_vendor_commands);
3278	hw->wiphy->vendor_events = mac80211_hwsim_vendor_events;
3279	hw->wiphy->n_vendor_events = ARRAY_SIZE(mac80211_hwsim_vendor_events);
3280
3281	if (param->reg_strict)
3282		hw->wiphy->regulatory_flags |= REGULATORY_STRICT_REG;
3283	if (param->regd) {
3284		data->regd = param->regd;
3285		hw->wiphy->regulatory_flags |= REGULATORY_CUSTOM_REG;
3286		wiphy_apply_custom_regulatory(hw->wiphy, param->regd);
3287		/* give the regulatory workqueue a chance to run */
3288		schedule_timeout_interruptible(1);
3289	}
3290
3291	if (param->no_vif)
3292		ieee80211_hw_set(hw, NO_AUTO_VIF);
3293
3294	wiphy_ext_feature_set(hw->wiphy, NL80211_EXT_FEATURE_CQM_RSSI_LIST);
3295
3296	hrtimer_init(&data->beacon_timer, CLOCK_MONOTONIC,
3297		     HRTIMER_MODE_ABS_SOFT);
3298	data->beacon_timer.function = mac80211_hwsim_beacon;
3299
3300	err = ieee80211_register_hw(hw);
3301	if (err < 0) {
3302		pr_debug("mac80211_hwsim: ieee80211_register_hw failed (%d)\n",
3303		       err);
3304		goto failed_hw;
3305	}
3306
3307	wiphy_dbg(hw->wiphy, "hwaddr %pM registered\n", hw->wiphy->perm_addr);
3308
3309	if (param->reg_alpha2) {
3310		data->alpha2[0] = param->reg_alpha2[0];
3311		data->alpha2[1] = param->reg_alpha2[1];
3312		regulatory_hint(hw->wiphy, param->reg_alpha2);
3313	}
3314
3315	data->debugfs = debugfs_create_dir("hwsim", hw->wiphy->debugfsdir);
3316	debugfs_create_file("ps", 0666, data->debugfs, data, &hwsim_fops_ps);
3317	debugfs_create_file("group", 0666, data->debugfs, data,
3318			    &hwsim_fops_group);
3319	if (!data->use_chanctx)
3320		debugfs_create_file("dfs_simulate_radar", 0222,
3321				    data->debugfs,
3322				    data, &hwsim_simulate_radar);
3323
3324	spin_lock_bh(&hwsim_radio_lock);
3325	err = rhashtable_insert_fast(&hwsim_radios_rht, &data->rht,
3326				     hwsim_rht_params);
3327	if (err < 0) {
3328		if (info) {
3329			GENL_SET_ERR_MSG(info, "perm addr already present");
3330			NL_SET_BAD_ATTR(info->extack,
3331					info->attrs[HWSIM_ATTR_PERM_ADDR]);
3332		}
3333		spin_unlock_bh(&hwsim_radio_lock);
3334		goto failed_final_insert;
3335	}
3336
3337	list_add_tail(&data->list, &hwsim_radios);
3338	hwsim_radios_generation++;
3339	spin_unlock_bh(&hwsim_radio_lock);
3340
3341	hwsim_mcast_new_radio(idx, info, param);
3342
3343	return idx;
3344
3345failed_final_insert:
3346	debugfs_remove_recursive(data->debugfs);
3347	ieee80211_unregister_hw(data->hw);
3348failed_hw:
3349	device_release_driver(data->dev);
3350failed_bind:
3351	device_unregister(data->dev);
3352failed_drvdata:
3353	ieee80211_free_hw(hw);
3354failed:
3355	return err;
3356}
3357
3358static void hwsim_mcast_del_radio(int id, const char *hwname,
3359				  struct genl_info *info)
3360{
3361	struct sk_buff *skb;
3362	void *data;
3363	int ret;
3364
3365	skb = genlmsg_new(GENLMSG_DEFAULT_SIZE, GFP_KERNEL);
3366	if (!skb)
3367		return;
3368
3369	data = genlmsg_put(skb, 0, 0, &hwsim_genl_family, 0,
3370			   HWSIM_CMD_DEL_RADIO);
3371	if (!data)
3372		goto error;
3373
3374	ret = nla_put_u32(skb, HWSIM_ATTR_RADIO_ID, id);
3375	if (ret < 0)
3376		goto error;
3377
3378	ret = nla_put(skb, HWSIM_ATTR_RADIO_NAME, strlen(hwname),
3379		      hwname);
3380	if (ret < 0)
3381		goto error;
3382
3383	genlmsg_end(skb, data);
3384
3385	hwsim_mcast_config_msg(skb, info);
3386
3387	return;
3388
3389error:
3390	nlmsg_free(skb);
3391}
3392
3393static void mac80211_hwsim_del_radio(struct mac80211_hwsim_data *data,
3394				     const char *hwname,
3395				     struct genl_info *info)
3396{
3397	hwsim_mcast_del_radio(data->idx, hwname, info);
3398	debugfs_remove_recursive(data->debugfs);
3399	ieee80211_unregister_hw(data->hw);
3400	device_release_driver(data->dev);
3401	device_unregister(data->dev);
3402	ieee80211_free_hw(data->hw);
3403}
3404
3405static int mac80211_hwsim_get_radio(struct sk_buff *skb,
3406				    struct mac80211_hwsim_data *data,
3407				    u32 portid, u32 seq,
3408				    struct netlink_callback *cb, int flags)
3409{
3410	void *hdr;
3411	struct hwsim_new_radio_params param = { };
3412	int res = -EMSGSIZE;
3413
3414	hdr = genlmsg_put(skb, portid, seq, &hwsim_genl_family, flags,
3415			  HWSIM_CMD_GET_RADIO);
3416	if (!hdr)
3417		return -EMSGSIZE;
3418
3419	if (cb)
3420		genl_dump_check_consistent(cb, hdr);
3421
3422	if (data->alpha2[0] && data->alpha2[1])
3423		param.reg_alpha2 = data->alpha2;
3424
3425	param.reg_strict = !!(data->hw->wiphy->regulatory_flags &
3426					REGULATORY_STRICT_REG);
3427	param.p2p_device = !!(data->hw->wiphy->interface_modes &
3428					BIT(NL80211_IFTYPE_P2P_DEVICE));
3429	param.use_chanctx = data->use_chanctx;
3430	param.regd = data->regd;
3431	param.channels = data->channels;
3432	param.hwname = wiphy_name(data->hw->wiphy);
3433
3434	res = append_radio_msg(skb, data->idx, &param);
3435	if (res < 0)
3436		goto out_err;
3437
3438	genlmsg_end(skb, hdr);
3439	return 0;
3440
3441out_err:
3442	genlmsg_cancel(skb, hdr);
3443	return res;
3444}
3445
3446static void mac80211_hwsim_free(void)
3447{
3448	struct mac80211_hwsim_data *data;
3449
3450	spin_lock_bh(&hwsim_radio_lock);
3451	while ((data = list_first_entry_or_null(&hwsim_radios,
3452						struct mac80211_hwsim_data,
3453						list))) {
3454		list_del(&data->list);
3455		spin_unlock_bh(&hwsim_radio_lock);
3456		mac80211_hwsim_del_radio(data, wiphy_name(data->hw->wiphy),
3457					 NULL);
3458		spin_lock_bh(&hwsim_radio_lock);
3459	}
3460	spin_unlock_bh(&hwsim_radio_lock);
3461	class_destroy(hwsim_class);
3462}
3463
3464static const struct net_device_ops hwsim_netdev_ops = {
3465	.ndo_start_xmit 	= hwsim_mon_xmit,
3466	.ndo_set_mac_address 	= eth_mac_addr,
3467	.ndo_validate_addr	= eth_validate_addr,
3468};
3469
3470static void hwsim_mon_setup(struct net_device *dev)
3471{
3472	dev->netdev_ops = &hwsim_netdev_ops;
3473	dev->needs_free_netdev = true;
3474	ether_setup(dev);
3475	dev->priv_flags |= IFF_NO_QUEUE;
3476	dev->type = ARPHRD_IEEE80211_RADIOTAP;
3477	eth_zero_addr(dev->dev_addr);
3478	dev->dev_addr[0] = 0x12;
3479}
3480
3481static struct mac80211_hwsim_data *get_hwsim_data_ref_from_addr(const u8 *addr)
3482{
3483	return rhashtable_lookup_fast(&hwsim_radios_rht,
3484				      addr,
3485				      hwsim_rht_params);
3486}
3487
3488static void hwsim_register_wmediumd(struct net *net, u32 portid)
3489{
3490	struct mac80211_hwsim_data *data;
3491
3492	hwsim_net_set_wmediumd(net, portid);
3493
3494	spin_lock_bh(&hwsim_radio_lock);
3495	list_for_each_entry(data, &hwsim_radios, list) {
3496		if (data->netgroup == hwsim_net_get_netgroup(net))
3497			data->wmediumd = portid;
3498	}
3499	spin_unlock_bh(&hwsim_radio_lock);
3500}
3501
3502static int hwsim_tx_info_frame_received_nl(struct sk_buff *skb_2,
3503					   struct genl_info *info)
3504{
3505
3506	struct ieee80211_hdr *hdr;
3507	struct mac80211_hwsim_data *data2;
3508	struct ieee80211_tx_info *txi;
3509	struct hwsim_tx_rate *tx_attempts;
3510	u64 ret_skb_cookie;
3511	struct sk_buff *skb, *tmp;
3512	const u8 *src;
3513	unsigned int hwsim_flags;
3514	int i;
3515	unsigned long flags;
3516	bool found = false;
3517
3518	if (!info->attrs[HWSIM_ATTR_ADDR_TRANSMITTER] ||
3519	    !info->attrs[HWSIM_ATTR_FLAGS] ||
3520	    !info->attrs[HWSIM_ATTR_COOKIE] ||
3521	    !info->attrs[HWSIM_ATTR_SIGNAL] ||
3522	    !info->attrs[HWSIM_ATTR_TX_INFO])
3523		goto out;
3524
3525	src = (void *)nla_data(info->attrs[HWSIM_ATTR_ADDR_TRANSMITTER]);
3526	hwsim_flags = nla_get_u32(info->attrs[HWSIM_ATTR_FLAGS]);
3527	ret_skb_cookie = nla_get_u64(info->attrs[HWSIM_ATTR_COOKIE]);
3528
3529	data2 = get_hwsim_data_ref_from_addr(src);
3530	if (!data2)
3531		goto out;
3532
3533	if (!hwsim_virtio_enabled) {
3534		if (hwsim_net_get_netgroup(genl_info_net(info)) !=
3535		    data2->netgroup)
3536			goto out;
3537
3538		if (info->snd_portid != data2->wmediumd)
3539			goto out;
3540	}
3541
3542	/* look for the skb matching the cookie passed back from user */
3543	spin_lock_irqsave(&data2->pending.lock, flags);
3544	skb_queue_walk_safe(&data2->pending, skb, tmp) {
3545		uintptr_t skb_cookie;
3546
3547		txi = IEEE80211_SKB_CB(skb);
3548		skb_cookie = (uintptr_t)txi->rate_driver_data[0];
3549
3550		if (skb_cookie == ret_skb_cookie) {
3551			__skb_unlink(skb, &data2->pending);
3552			found = true;
3553			break;
3554		}
3555	}
3556	spin_unlock_irqrestore(&data2->pending.lock, flags);
3557
3558	/* not found */
3559	if (!found)
3560		goto out;
3561
3562	/* Tx info received because the frame was broadcasted on user space,
3563	 so we get all the necessary info: tx attempts and skb control buff */
3564
3565	tx_attempts = (struct hwsim_tx_rate *)nla_data(
3566		       info->attrs[HWSIM_ATTR_TX_INFO]);
3567
3568	/* now send back TX status */
3569	txi = IEEE80211_SKB_CB(skb);
3570
3571	ieee80211_tx_info_clear_status(txi);
3572
3573	for (i = 0; i < IEEE80211_TX_MAX_RATES; i++) {
3574		txi->status.rates[i].idx = tx_attempts[i].idx;
3575		txi->status.rates[i].count = tx_attempts[i].count;
3576	}
3577
3578	txi->status.ack_signal = nla_get_u32(info->attrs[HWSIM_ATTR_SIGNAL]);
3579
3580	if (!(hwsim_flags & HWSIM_TX_CTL_NO_ACK) &&
3581	   (hwsim_flags & HWSIM_TX_STAT_ACK)) {
3582		if (skb->len >= 16) {
3583			hdr = (struct ieee80211_hdr *) skb->data;
3584			mac80211_hwsim_monitor_ack(data2->channel,
3585						   hdr->addr2);
3586		}
3587		txi->flags |= IEEE80211_TX_STAT_ACK;
3588	}
3589
3590	if (hwsim_flags & HWSIM_TX_CTL_NO_ACK)
3591		txi->flags |= IEEE80211_TX_STAT_NOACK_TRANSMITTED;
3592
3593	ieee80211_tx_status_irqsafe(data2->hw, skb);
3594	return 0;
3595out:
3596	return -EINVAL;
3597
3598}
3599
3600static int hwsim_cloned_frame_received_nl(struct sk_buff *skb_2,
3601					  struct genl_info *info)
3602{
3603	struct mac80211_hwsim_data *data2;
3604	struct ieee80211_rx_status rx_status;
3605	struct ieee80211_hdr *hdr;
3606	const u8 *dst;
3607	int frame_data_len;
3608	void *frame_data;
3609	struct sk_buff *skb = NULL;
3610	struct ieee80211_channel *channel = NULL;
3611
3612	if (!info->attrs[HWSIM_ATTR_ADDR_RECEIVER] ||
3613	    !info->attrs[HWSIM_ATTR_FRAME] ||
3614	    !info->attrs[HWSIM_ATTR_RX_RATE] ||
3615	    !info->attrs[HWSIM_ATTR_SIGNAL])
3616		goto out;
3617
3618	dst = (void *)nla_data(info->attrs[HWSIM_ATTR_ADDR_RECEIVER]);
3619	frame_data_len = nla_len(info->attrs[HWSIM_ATTR_FRAME]);
3620	frame_data = (void *)nla_data(info->attrs[HWSIM_ATTR_FRAME]);
3621
3622	if (frame_data_len < sizeof(struct ieee80211_hdr_3addr) ||
3623	    frame_data_len > IEEE80211_MAX_DATA_LEN)
3624		goto err;
3625
3626	/* Allocate new skb here */
3627	skb = alloc_skb(frame_data_len, GFP_KERNEL);
3628	if (skb == NULL)
3629		goto err;
3630
3631	/* Copy the data */
3632	skb_put_data(skb, frame_data, frame_data_len);
3633
3634	data2 = get_hwsim_data_ref_from_addr(dst);
3635	if (!data2)
3636		goto out;
3637
3638	if (data2->use_chanctx) {
3639		if (data2->tmp_chan)
3640			channel = data2->tmp_chan;
3641		else if (data2->chanctx)
3642			channel = data2->chanctx->def.chan;
3643	} else {
3644		channel = data2->channel;
3645	}
3646	if (!channel)
3647		goto out;
3648
3649	if (!hwsim_virtio_enabled) {
3650		if (hwsim_net_get_netgroup(genl_info_net(info)) !=
3651		    data2->netgroup)
3652			goto out;
3653
3654		if (info->snd_portid != data2->wmediumd)
3655			goto out;
3656	}
3657
3658	/* check if radio is configured properly */
3659
3660	if ((data2->idle && !data2->tmp_chan) || !data2->started)
3661		goto out;
3662
3663	/* A frame is received from user space */
3664	memset(&rx_status, 0, sizeof(rx_status));
3665	if (info->attrs[HWSIM_ATTR_FREQ]) {
3666		/* throw away off-channel packets, but allow both the temporary
3667		 * ("hw" scan/remain-on-channel) and regular channel, since the
3668		 * internal datapath also allows this
3669		 */
3670		mutex_lock(&data2->mutex);
3671		rx_status.freq = nla_get_u32(info->attrs[HWSIM_ATTR_FREQ]);
3672
3673		if (rx_status.freq != channel->center_freq) {
3674			mutex_unlock(&data2->mutex);
3675			goto out;
3676		}
3677		mutex_unlock(&data2->mutex);
3678	} else {
3679		rx_status.freq = channel->center_freq;
3680	}
3681
3682	rx_status.band = channel->band;
3683	rx_status.rate_idx = nla_get_u32(info->attrs[HWSIM_ATTR_RX_RATE]);
3684	if (rx_status.rate_idx >= data2->hw->wiphy->bands[rx_status.band]->n_bitrates)
3685		goto out;
3686	rx_status.signal = nla_get_u32(info->attrs[HWSIM_ATTR_SIGNAL]);
3687
3688	hdr = (void *)skb->data;
3689
3690	if (ieee80211_is_beacon(hdr->frame_control) ||
3691	    ieee80211_is_probe_resp(hdr->frame_control))
3692		rx_status.boottime_ns = ktime_get_boottime_ns();
3693
3694	memcpy(IEEE80211_SKB_RXCB(skb), &rx_status, sizeof(rx_status));
3695	data2->rx_pkts++;
3696	data2->rx_bytes += skb->len;
3697	ieee80211_rx_irqsafe(data2->hw, skb);
3698
3699	return 0;
3700err:
3701	pr_debug("mac80211_hwsim: error occurred in %s\n", __func__);
3702out:
3703	dev_kfree_skb(skb);
3704	return -EINVAL;
3705}
3706
3707static int hwsim_register_received_nl(struct sk_buff *skb_2,
3708				      struct genl_info *info)
3709{
3710	struct net *net = genl_info_net(info);
3711	struct mac80211_hwsim_data *data;
3712	int chans = 1;
3713
3714	spin_lock_bh(&hwsim_radio_lock);
3715	list_for_each_entry(data, &hwsim_radios, list)
3716		chans = max(chans, data->channels);
3717	spin_unlock_bh(&hwsim_radio_lock);
3718
3719	/* In the future we should revise the userspace API and allow it
3720	 * to set a flag that it does support multi-channel, then we can
3721	 * let this pass conditionally on the flag.
3722	 * For current userspace, prohibit it since it won't work right.
3723	 */
3724	if (chans > 1)
3725		return -EOPNOTSUPP;
3726
3727	if (hwsim_net_get_wmediumd(net))
3728		return -EBUSY;
3729
3730	hwsim_register_wmediumd(net, info->snd_portid);
3731
3732	pr_debug("mac80211_hwsim: received a REGISTER, "
3733	       "switching to wmediumd mode with pid %d\n", info->snd_portid);
3734
3735	return 0;
3736}
3737
3738/* ensures ciphers only include ciphers listed in 'hwsim_ciphers' array */
3739static bool hwsim_known_ciphers(const u32 *ciphers, int n_ciphers)
3740{
3741	int i;
3742
3743	for (i = 0; i < n_ciphers; i++) {
3744		int j;
3745		int found = 0;
3746
3747		for (j = 0; j < ARRAY_SIZE(hwsim_ciphers); j++) {
3748			if (ciphers[i] == hwsim_ciphers[j]) {
3749				found = 1;
3750				break;
3751			}
3752		}
3753
3754		if (!found)
3755			return false;
3756	}
3757
3758	return true;
3759}
3760
3761static int hwsim_new_radio_nl(struct sk_buff *msg, struct genl_info *info)
3762{
3763	struct hwsim_new_radio_params param = { 0 };
3764	const char *hwname = NULL;
3765	int ret;
3766
3767	param.reg_strict = info->attrs[HWSIM_ATTR_REG_STRICT_REG];
3768	param.p2p_device = info->attrs[HWSIM_ATTR_SUPPORT_P2P_DEVICE];
3769	param.channels = channels;
3770	param.destroy_on_close =
3771		info->attrs[HWSIM_ATTR_DESTROY_RADIO_ON_CLOSE];
3772
3773	if (info->attrs[HWSIM_ATTR_CHANNELS])
3774		param.channels = nla_get_u32(info->attrs[HWSIM_ATTR_CHANNELS]);
3775
3776	if (param.channels < 1) {
3777		GENL_SET_ERR_MSG(info, "must have at least one channel");
3778		return -EINVAL;
3779	}
3780
3781	if (param.channels > CFG80211_MAX_NUM_DIFFERENT_CHANNELS) {
3782		GENL_SET_ERR_MSG(info, "too many channels specified");
3783		return -EINVAL;
3784	}
3785
3786	if (info->attrs[HWSIM_ATTR_NO_VIF])
3787		param.no_vif = true;
3788
3789	if (info->attrs[HWSIM_ATTR_USE_CHANCTX])
3790		param.use_chanctx = true;
3791	else
3792		param.use_chanctx = (param.channels > 1);
3793
3794	if (info->attrs[HWSIM_ATTR_REG_HINT_ALPHA2])
3795		param.reg_alpha2 =
3796			nla_data(info->attrs[HWSIM_ATTR_REG_HINT_ALPHA2]);
3797
3798	if (info->attrs[HWSIM_ATTR_REG_CUSTOM_REG]) {
3799		u32 idx = nla_get_u32(info->attrs[HWSIM_ATTR_REG_CUSTOM_REG]);
3800
3801		if (idx >= ARRAY_SIZE(hwsim_world_regdom_custom))
3802			return -EINVAL;
3803
3804		idx = array_index_nospec(idx,
3805					 ARRAY_SIZE(hwsim_world_regdom_custom));
3806		param.regd = hwsim_world_regdom_custom[idx];
3807	}
3808
3809	if (info->attrs[HWSIM_ATTR_PERM_ADDR]) {
3810		if (!is_valid_ether_addr(
3811				nla_data(info->attrs[HWSIM_ATTR_PERM_ADDR]))) {
3812			GENL_SET_ERR_MSG(info,"MAC is no valid source addr");
3813			NL_SET_BAD_ATTR(info->extack,
3814					info->attrs[HWSIM_ATTR_PERM_ADDR]);
3815			return -EINVAL;
3816		}
3817
3818		param.perm_addr = nla_data(info->attrs[HWSIM_ATTR_PERM_ADDR]);
3819	}
3820
3821	if (info->attrs[HWSIM_ATTR_IFTYPE_SUPPORT]) {
3822		param.iftypes =
3823			nla_get_u32(info->attrs[HWSIM_ATTR_IFTYPE_SUPPORT]);
3824
3825		if (param.iftypes & ~HWSIM_IFTYPE_SUPPORT_MASK) {
3826			NL_SET_ERR_MSG_ATTR(info->extack,
3827					    info->attrs[HWSIM_ATTR_IFTYPE_SUPPORT],
3828					    "cannot support more iftypes than kernel");
3829			return -EINVAL;
3830		}
3831	} else {
3832		param.iftypes = HWSIM_IFTYPE_SUPPORT_MASK;
3833	}
3834
3835	/* ensure both flag and iftype support is honored */
3836	if (param.p2p_device ||
3837	    param.iftypes & BIT(NL80211_IFTYPE_P2P_DEVICE)) {
3838		param.iftypes |= BIT(NL80211_IFTYPE_P2P_DEVICE);
3839		param.p2p_device = true;
3840	}
3841
3842	if (info->attrs[HWSIM_ATTR_CIPHER_SUPPORT]) {
3843		u32 len = nla_len(info->attrs[HWSIM_ATTR_CIPHER_SUPPORT]);
3844
3845		param.ciphers =
3846			nla_data(info->attrs[HWSIM_ATTR_CIPHER_SUPPORT]);
3847
3848		if (len % sizeof(u32)) {
3849			NL_SET_ERR_MSG_ATTR(info->extack,
3850					    info->attrs[HWSIM_ATTR_CIPHER_SUPPORT],
3851					    "bad cipher list length");
3852			return -EINVAL;
3853		}
3854
3855		param.n_ciphers = len / sizeof(u32);
3856
3857		if (param.n_ciphers > ARRAY_SIZE(hwsim_ciphers)) {
3858			NL_SET_ERR_MSG_ATTR(info->extack,
3859					    info->attrs[HWSIM_ATTR_CIPHER_SUPPORT],
3860					    "too many ciphers specified");
3861			return -EINVAL;
3862		}
3863
3864		if (!hwsim_known_ciphers(param.ciphers, param.n_ciphers)) {
3865			NL_SET_ERR_MSG_ATTR(info->extack,
3866					    info->attrs[HWSIM_ATTR_CIPHER_SUPPORT],
3867					    "unsupported ciphers specified");
3868			return -EINVAL;
3869		}
3870	}
3871
3872	if (info->attrs[HWSIM_ATTR_RADIO_NAME]) {
3873		hwname = kstrndup((char *)nla_data(info->attrs[HWSIM_ATTR_RADIO_NAME]),
3874				  nla_len(info->attrs[HWSIM_ATTR_RADIO_NAME]),
3875				  GFP_KERNEL);
3876		if (!hwname)
3877			return -ENOMEM;
3878		param.hwname = hwname;
3879	}
3880
3881	ret = mac80211_hwsim_new_radio(info, &param);
3882	kfree(hwname);
3883	return ret;
3884}
3885
3886static int hwsim_del_radio_nl(struct sk_buff *msg, struct genl_info *info)
3887{
3888	struct mac80211_hwsim_data *data;
3889	s64 idx = -1;
3890	const char *hwname = NULL;
3891
3892	if (info->attrs[HWSIM_ATTR_RADIO_ID]) {
3893		idx = nla_get_u32(info->attrs[HWSIM_ATTR_RADIO_ID]);
3894	} else if (info->attrs[HWSIM_ATTR_RADIO_NAME]) {
3895		hwname = kstrndup((char *)nla_data(info->attrs[HWSIM_ATTR_RADIO_NAME]),
3896				  nla_len(info->attrs[HWSIM_ATTR_RADIO_NAME]),
3897				  GFP_KERNEL);
3898		if (!hwname)
3899			return -ENOMEM;
3900	} else
3901		return -EINVAL;
3902
3903	spin_lock_bh(&hwsim_radio_lock);
3904	list_for_each_entry(data, &hwsim_radios, list) {
3905		if (idx >= 0) {
3906			if (data->idx != idx)
3907				continue;
3908		} else {
3909			if (!hwname ||
3910			    strcmp(hwname, wiphy_name(data->hw->wiphy)))
3911				continue;
3912		}
3913
3914		if (!net_eq(wiphy_net(data->hw->wiphy), genl_info_net(info)))
3915			continue;
3916
3917		list_del(&data->list);
3918		rhashtable_remove_fast(&hwsim_radios_rht, &data->rht,
3919				       hwsim_rht_params);
3920		hwsim_radios_generation++;
3921		spin_unlock_bh(&hwsim_radio_lock);
3922		mac80211_hwsim_del_radio(data, wiphy_name(data->hw->wiphy),
3923					 info);
3924		kfree(hwname);
3925		return 0;
3926	}
3927	spin_unlock_bh(&hwsim_radio_lock);
3928
3929	kfree(hwname);
3930	return -ENODEV;
3931}
3932
3933static int hwsim_get_radio_nl(struct sk_buff *msg, struct genl_info *info)
3934{
3935	struct mac80211_hwsim_data *data;
3936	struct sk_buff *skb;
3937	int idx, res = -ENODEV;
3938
3939	if (!info->attrs[HWSIM_ATTR_RADIO_ID])
3940		return -EINVAL;
3941	idx = nla_get_u32(info->attrs[HWSIM_ATTR_RADIO_ID]);
3942
3943	spin_lock_bh(&hwsim_radio_lock);
3944	list_for_each_entry(data, &hwsim_radios, list) {
3945		if (data->idx != idx)
3946			continue;
3947
3948		if (!net_eq(wiphy_net(data->hw->wiphy), genl_info_net(info)))
3949			continue;
3950
3951		skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC);
3952		if (!skb) {
3953			res = -ENOMEM;
3954			goto out_err;
3955		}
3956
3957		res = mac80211_hwsim_get_radio(skb, data, info->snd_portid,
3958					       info->snd_seq, NULL, 0);
3959		if (res < 0) {
3960			nlmsg_free(skb);
3961			goto out_err;
3962		}
3963
3964		res = genlmsg_reply(skb, info);
3965		break;
3966	}
3967
3968out_err:
3969	spin_unlock_bh(&hwsim_radio_lock);
3970
3971	return res;
3972}
3973
3974static int hwsim_dump_radio_nl(struct sk_buff *skb,
3975			       struct netlink_callback *cb)
3976{
3977	int last_idx = cb->args[0] - 1;
3978	struct mac80211_hwsim_data *data = NULL;
3979	int res = 0;
3980	void *hdr;
3981
3982	spin_lock_bh(&hwsim_radio_lock);
3983	cb->seq = hwsim_radios_generation;
3984
3985	if (last_idx >= hwsim_radio_idx-1)
3986		goto done;
3987
3988	list_for_each_entry(data, &hwsim_radios, list) {
3989		if (data->idx <= last_idx)
3990			continue;
3991
3992		if (!net_eq(wiphy_net(data->hw->wiphy), sock_net(skb->sk)))
3993			continue;
3994
3995		res = mac80211_hwsim_get_radio(skb, data,
3996					       NETLINK_CB(cb->skb).portid,
3997					       cb->nlh->nlmsg_seq, cb,
3998					       NLM_F_MULTI);
3999		if (res < 0)
4000			break;
4001
4002		last_idx = data->idx;
4003	}
4004
4005	cb->args[0] = last_idx + 1;
4006
4007	/* list changed, but no new element sent, set interrupted flag */
4008	if (skb->len == 0 && cb->prev_seq && cb->seq != cb->prev_seq) {
4009		hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid,
4010				  cb->nlh->nlmsg_seq, &hwsim_genl_family,
4011				  NLM_F_MULTI, HWSIM_CMD_GET_RADIO);
4012		if (hdr) {
4013			genl_dump_check_consistent(cb, hdr);
4014			genlmsg_end(skb, hdr);
4015		} else {
4016			res = -EMSGSIZE;
4017		}
4018	}
4019
4020done:
4021	spin_unlock_bh(&hwsim_radio_lock);
4022	return res ?: skb->len;
4023}
4024
4025/* Generic Netlink operations array */
4026static const struct genl_small_ops hwsim_ops[] = {
4027	{
4028		.cmd = HWSIM_CMD_REGISTER,
4029		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
4030		.doit = hwsim_register_received_nl,
4031		.flags = GENL_UNS_ADMIN_PERM,
4032	},
4033	{
4034		.cmd = HWSIM_CMD_FRAME,
4035		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
4036		.doit = hwsim_cloned_frame_received_nl,
4037	},
4038	{
4039		.cmd = HWSIM_CMD_TX_INFO_FRAME,
4040		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
4041		.doit = hwsim_tx_info_frame_received_nl,
4042	},
4043	{
4044		.cmd = HWSIM_CMD_NEW_RADIO,
4045		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
4046		.doit = hwsim_new_radio_nl,
4047		.flags = GENL_UNS_ADMIN_PERM,
4048	},
4049	{
4050		.cmd = HWSIM_CMD_DEL_RADIO,
4051		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
4052		.doit = hwsim_del_radio_nl,
4053		.flags = GENL_UNS_ADMIN_PERM,
4054	},
4055	{
4056		.cmd = HWSIM_CMD_GET_RADIO,
4057		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
4058		.doit = hwsim_get_radio_nl,
4059		.dumpit = hwsim_dump_radio_nl,
4060	},
4061};
4062
4063static struct genl_family hwsim_genl_family __ro_after_init = {
4064	.name = "MAC80211_HWSIM",
4065	.version = 1,
4066	.maxattr = HWSIM_ATTR_MAX,
4067	.policy = hwsim_genl_policy,
4068	.netnsok = true,
4069	.module = THIS_MODULE,
4070	.small_ops = hwsim_ops,
4071	.n_small_ops = ARRAY_SIZE(hwsim_ops),
4072	.mcgrps = hwsim_mcgrps,
4073	.n_mcgrps = ARRAY_SIZE(hwsim_mcgrps),
4074};
4075
4076static void remove_user_radios(u32 portid)
4077{
4078	struct mac80211_hwsim_data *entry, *tmp;
4079	LIST_HEAD(list);
4080
4081	spin_lock_bh(&hwsim_radio_lock);
4082	list_for_each_entry_safe(entry, tmp, &hwsim_radios, list) {
4083		if (entry->destroy_on_close && entry->portid == portid) {
4084			list_move(&entry->list, &list);
4085			rhashtable_remove_fast(&hwsim_radios_rht, &entry->rht,
4086					       hwsim_rht_params);
4087			hwsim_radios_generation++;
4088		}
4089	}
4090	spin_unlock_bh(&hwsim_radio_lock);
4091
4092	list_for_each_entry_safe(entry, tmp, &list, list) {
4093		list_del(&entry->list);
4094		mac80211_hwsim_del_radio(entry, wiphy_name(entry->hw->wiphy),
4095					 NULL);
4096	}
4097}
4098
4099static int mac80211_hwsim_netlink_notify(struct notifier_block *nb,
4100					 unsigned long state,
4101					 void *_notify)
4102{
4103	struct netlink_notify *notify = _notify;
4104
4105	if (state != NETLINK_URELEASE)
4106		return NOTIFY_DONE;
4107
4108	remove_user_radios(notify->portid);
4109
4110	if (notify->portid == hwsim_net_get_wmediumd(notify->net)) {
4111		printk(KERN_INFO "mac80211_hwsim: wmediumd released netlink"
4112		       " socket, switching to perfect channel medium\n");
4113		hwsim_register_wmediumd(notify->net, 0);
4114	}
4115	return NOTIFY_DONE;
4116
4117}
4118
4119static struct notifier_block hwsim_netlink_notifier = {
4120	.notifier_call = mac80211_hwsim_netlink_notify,
4121};
4122
4123static int __init hwsim_init_netlink(void)
4124{
4125	int rc;
4126
4127	printk(KERN_INFO "mac80211_hwsim: initializing netlink\n");
4128
4129	rc = genl_register_family(&hwsim_genl_family);
4130	if (rc)
4131		goto failure;
4132
4133	rc = netlink_register_notifier(&hwsim_netlink_notifier);
4134	if (rc) {
4135		genl_unregister_family(&hwsim_genl_family);
4136		goto failure;
4137	}
4138
4139	return 0;
4140
4141failure:
4142	pr_debug("mac80211_hwsim: error occurred in %s\n", __func__);
4143	return -EINVAL;
4144}
4145
4146static __net_init int hwsim_init_net(struct net *net)
4147{
4148	return hwsim_net_set_netgroup(net);
4149}
4150
4151static void __net_exit hwsim_exit_net(struct net *net)
4152{
4153	struct mac80211_hwsim_data *data, *tmp;
4154	LIST_HEAD(list);
4155
4156	spin_lock_bh(&hwsim_radio_lock);
4157	list_for_each_entry_safe(data, tmp, &hwsim_radios, list) {
4158		if (!net_eq(wiphy_net(data->hw->wiphy), net))
4159			continue;
4160
4161		/* Radios created in init_net are returned to init_net. */
4162		if (data->netgroup == hwsim_net_get_netgroup(&init_net))
4163			continue;
4164
4165		list_move(&data->list, &list);
4166		rhashtable_remove_fast(&hwsim_radios_rht, &data->rht,
4167				       hwsim_rht_params);
4168		hwsim_radios_generation++;
4169	}
4170	spin_unlock_bh(&hwsim_radio_lock);
4171
4172	list_for_each_entry_safe(data, tmp, &list, list) {
4173		list_del(&data->list);
4174		mac80211_hwsim_del_radio(data,
4175					 wiphy_name(data->hw->wiphy),
4176					 NULL);
4177	}
4178
4179	ida_simple_remove(&hwsim_netgroup_ida, hwsim_net_get_netgroup(net));
4180}
4181
4182static struct pernet_operations hwsim_net_ops = {
4183	.init = hwsim_init_net,
4184	.exit = hwsim_exit_net,
4185	.id   = &hwsim_net_id,
4186	.size = sizeof(struct hwsim_net),
4187};
4188
4189static void hwsim_exit_netlink(void)
4190{
4191	/* unregister the notifier */
4192	netlink_unregister_notifier(&hwsim_netlink_notifier);
4193	/* unregister the family */
4194	genl_unregister_family(&hwsim_genl_family);
4195}
4196
4197#if IS_REACHABLE(CONFIG_VIRTIO)
4198static void hwsim_virtio_tx_done(struct virtqueue *vq)
4199{
4200	unsigned int len;
4201	struct sk_buff *skb;
4202	unsigned long flags;
4203
4204	spin_lock_irqsave(&hwsim_virtio_lock, flags);
4205	while ((skb = virtqueue_get_buf(vq, &len)))
4206		nlmsg_free(skb);
4207	spin_unlock_irqrestore(&hwsim_virtio_lock, flags);
4208}
4209
4210static int hwsim_virtio_handle_cmd(struct sk_buff *skb)
4211{
4212	struct nlmsghdr *nlh;
4213	struct genlmsghdr *gnlh;
4214	struct nlattr *tb[HWSIM_ATTR_MAX + 1];
4215	struct genl_info info = {};
4216	int err;
4217
4218	nlh = nlmsg_hdr(skb);
4219	gnlh = nlmsg_data(nlh);
4220
4221	if (skb->len < nlh->nlmsg_len)
4222		return -EINVAL;
4223
4224	err = genlmsg_parse(nlh, &hwsim_genl_family, tb, HWSIM_ATTR_MAX,
4225			    hwsim_genl_policy, NULL);
4226	if (err) {
4227		pr_err_ratelimited("hwsim: genlmsg_parse returned %d\n", err);
4228		return err;
4229	}
4230
4231	info.attrs = tb;
4232
4233	switch (gnlh->cmd) {
4234	case HWSIM_CMD_FRAME:
4235		hwsim_cloned_frame_received_nl(skb, &info);
4236		break;
4237	case HWSIM_CMD_TX_INFO_FRAME:
4238		hwsim_tx_info_frame_received_nl(skb, &info);
4239		break;
4240	default:
4241		pr_err_ratelimited("hwsim: invalid cmd: %d\n", gnlh->cmd);
4242		return -EPROTO;
4243	}
4244	return 0;
4245}
4246
4247static void hwsim_virtio_rx_work(struct work_struct *work)
4248{
4249	struct virtqueue *vq;
4250	unsigned int len;
4251	struct sk_buff *skb;
4252	struct scatterlist sg[1];
4253	int err;
4254	unsigned long flags;
4255
4256	spin_lock_irqsave(&hwsim_virtio_lock, flags);
4257	if (!hwsim_virtio_enabled)
4258		goto out_unlock;
4259
4260	skb = virtqueue_get_buf(hwsim_vqs[HWSIM_VQ_RX], &len);
4261	if (!skb)
4262		goto out_unlock;
4263	spin_unlock_irqrestore(&hwsim_virtio_lock, flags);
4264
4265	skb->data = skb->head;
4266	skb_reset_tail_pointer(skb);
4267	skb_put(skb, len);
4268	hwsim_virtio_handle_cmd(skb);
4269
4270	spin_lock_irqsave(&hwsim_virtio_lock, flags);
4271	if (!hwsim_virtio_enabled) {
4272		nlmsg_free(skb);
4273		goto out_unlock;
4274	}
4275	vq = hwsim_vqs[HWSIM_VQ_RX];
4276	sg_init_one(sg, skb->head, skb_end_offset(skb));
4277	err = virtqueue_add_inbuf(vq, sg, 1, skb, GFP_ATOMIC);
4278	if (WARN(err, "virtqueue_add_inbuf returned %d\n", err))
4279		nlmsg_free(skb);
4280	else
4281		virtqueue_kick(vq);
4282	schedule_work(&hwsim_virtio_rx);
4283
4284out_unlock:
4285	spin_unlock_irqrestore(&hwsim_virtio_lock, flags);
4286}
4287
4288static void hwsim_virtio_rx_done(struct virtqueue *vq)
4289{
4290	schedule_work(&hwsim_virtio_rx);
4291}
4292
4293static int init_vqs(struct virtio_device *vdev)
4294{
4295	vq_callback_t *callbacks[HWSIM_NUM_VQS] = {
4296		[HWSIM_VQ_TX] = hwsim_virtio_tx_done,
4297		[HWSIM_VQ_RX] = hwsim_virtio_rx_done,
4298	};
4299	const char *names[HWSIM_NUM_VQS] = {
4300		[HWSIM_VQ_TX] = "tx",
4301		[HWSIM_VQ_RX] = "rx",
4302	};
4303
4304	return virtio_find_vqs(vdev, HWSIM_NUM_VQS,
4305			       hwsim_vqs, callbacks, names, NULL);
4306}
4307
4308static int fill_vq(struct virtqueue *vq)
4309{
4310	int i, err;
4311	struct sk_buff *skb;
4312	struct scatterlist sg[1];
4313
4314	for (i = 0; i < virtqueue_get_vring_size(vq); i++) {
4315		skb = genlmsg_new(GENLMSG_DEFAULT_SIZE, GFP_KERNEL);
4316		if (!skb)
4317			return -ENOMEM;
4318
4319		sg_init_one(sg, skb->head, skb_end_offset(skb));
4320		err = virtqueue_add_inbuf(vq, sg, 1, skb, GFP_KERNEL);
4321		if (err) {
4322			nlmsg_free(skb);
4323			return err;
4324		}
4325	}
4326	virtqueue_kick(vq);
4327	return 0;
4328}
4329
4330static void remove_vqs(struct virtio_device *vdev)
4331{
4332	int i;
4333
4334	vdev->config->reset(vdev);
4335
4336	for (i = 0; i < ARRAY_SIZE(hwsim_vqs); i++) {
4337		struct virtqueue *vq = hwsim_vqs[i];
4338		struct sk_buff *skb;
4339
4340		while ((skb = virtqueue_detach_unused_buf(vq)))
4341			nlmsg_free(skb);
4342	}
4343
4344	vdev->config->del_vqs(vdev);
4345}
4346
4347static int hwsim_virtio_probe(struct virtio_device *vdev)
4348{
4349	int err;
4350	unsigned long flags;
4351
4352	spin_lock_irqsave(&hwsim_virtio_lock, flags);
4353	if (hwsim_virtio_enabled) {
4354		spin_unlock_irqrestore(&hwsim_virtio_lock, flags);
4355		return -EEXIST;
4356	}
4357	spin_unlock_irqrestore(&hwsim_virtio_lock, flags);
4358
4359	err = init_vqs(vdev);
4360	if (err)
4361		return err;
4362
4363	err = fill_vq(hwsim_vqs[HWSIM_VQ_RX]);
4364	if (err)
4365		goto out_remove;
4366
4367	spin_lock_irqsave(&hwsim_virtio_lock, flags);
4368	hwsim_virtio_enabled = true;
4369	spin_unlock_irqrestore(&hwsim_virtio_lock, flags);
4370
4371	schedule_work(&hwsim_virtio_rx);
4372	return 0;
4373
4374out_remove:
4375	remove_vqs(vdev);
4376	return err;
4377}
4378
4379static void hwsim_virtio_remove(struct virtio_device *vdev)
4380{
4381	hwsim_virtio_enabled = false;
4382
4383	cancel_work_sync(&hwsim_virtio_rx);
4384
4385	remove_vqs(vdev);
4386}
4387
4388/* MAC80211_HWSIM virtio device id table */
4389static const struct virtio_device_id id_table[] = {
4390	{ VIRTIO_ID_MAC80211_HWSIM, VIRTIO_DEV_ANY_ID },
4391	{ 0 }
4392};
4393MODULE_DEVICE_TABLE(virtio, id_table);
4394
4395static struct virtio_driver virtio_hwsim = {
4396	.driver.name = KBUILD_MODNAME,
4397	.driver.owner = THIS_MODULE,
4398	.id_table = id_table,
4399	.probe = hwsim_virtio_probe,
4400	.remove = hwsim_virtio_remove,
4401};
4402
4403static int hwsim_register_virtio_driver(void)
4404{
4405	spin_lock_init(&hwsim_virtio_lock);
4406
4407	return register_virtio_driver(&virtio_hwsim);
4408}
4409
4410static void hwsim_unregister_virtio_driver(void)
4411{
4412	unregister_virtio_driver(&virtio_hwsim);
4413}
4414#else
4415static inline int hwsim_register_virtio_driver(void)
4416{
4417	return 0;
4418}
4419
4420static inline void hwsim_unregister_virtio_driver(void)
4421{
4422}
4423#endif
4424
4425static int __init init_mac80211_hwsim(void)
4426{
4427	int i, err;
4428
4429	if (radios < 0 || radios > 100)
4430		return -EINVAL;
4431
4432	if (channels < 1)
4433		return -EINVAL;
4434
4435	spin_lock_init(&hwsim_radio_lock);
4436
4437	err = rhashtable_init(&hwsim_radios_rht, &hwsim_rht_params);
4438	if (err)
4439		return err;
4440
4441	err = register_pernet_device(&hwsim_net_ops);
4442	if (err)
4443		goto out_free_rht;
4444
4445	err = platform_driver_register(&mac80211_hwsim_driver);
4446	if (err)
4447		goto out_unregister_pernet;
4448
4449	err = hwsim_init_netlink();
4450	if (err)
4451		goto out_unregister_driver;
4452
4453	err = hwsim_register_virtio_driver();
4454	if (err)
4455		goto out_exit_netlink;
4456
4457	hwsim_class = class_create(THIS_MODULE, "mac80211_hwsim");
4458	if (IS_ERR(hwsim_class)) {
4459		err = PTR_ERR(hwsim_class);
4460		goto out_exit_virtio;
4461	}
4462
4463	hwsim_init_s1g_channels(hwsim_channels_s1g);
4464
4465	for (i = 0; i < radios; i++) {
4466		struct hwsim_new_radio_params param = { 0 };
4467
4468		param.channels = channels;
4469
4470		switch (regtest) {
4471		case HWSIM_REGTEST_DIFF_COUNTRY:
4472			if (i < ARRAY_SIZE(hwsim_alpha2s))
4473				param.reg_alpha2 = hwsim_alpha2s[i];
4474			break;
4475		case HWSIM_REGTEST_DRIVER_REG_FOLLOW:
4476			if (!i)
4477				param.reg_alpha2 = hwsim_alpha2s[0];
4478			break;
4479		case HWSIM_REGTEST_STRICT_ALL:
4480			param.reg_strict = true;
4481			fallthrough;
4482		case HWSIM_REGTEST_DRIVER_REG_ALL:
4483			param.reg_alpha2 = hwsim_alpha2s[0];
4484			break;
4485		case HWSIM_REGTEST_WORLD_ROAM:
4486			if (i == 0)
4487				param.regd = &hwsim_world_regdom_custom_01;
4488			break;
4489		case HWSIM_REGTEST_CUSTOM_WORLD:
4490			param.regd = &hwsim_world_regdom_custom_01;
4491			break;
4492		case HWSIM_REGTEST_CUSTOM_WORLD_2:
4493			if (i == 0)
4494				param.regd = &hwsim_world_regdom_custom_01;
4495			else if (i == 1)
4496				param.regd = &hwsim_world_regdom_custom_02;
4497			break;
4498		case HWSIM_REGTEST_STRICT_FOLLOW:
4499			if (i == 0) {
4500				param.reg_strict = true;
4501				param.reg_alpha2 = hwsim_alpha2s[0];
4502			}
4503			break;
4504		case HWSIM_REGTEST_STRICT_AND_DRIVER_REG:
4505			if (i == 0) {
4506				param.reg_strict = true;
4507				param.reg_alpha2 = hwsim_alpha2s[0];
4508			} else if (i == 1) {
4509				param.reg_alpha2 = hwsim_alpha2s[1];
4510			}
4511			break;
4512		case HWSIM_REGTEST_ALL:
4513			switch (i) {
4514			case 0:
4515				param.regd = &hwsim_world_regdom_custom_01;
4516				break;
4517			case 1:
4518				param.regd = &hwsim_world_regdom_custom_02;
4519				break;
4520			case 2:
4521				param.reg_alpha2 = hwsim_alpha2s[0];
4522				break;
4523			case 3:
4524				param.reg_alpha2 = hwsim_alpha2s[1];
4525				break;
4526			case 4:
4527				param.reg_strict = true;
4528				param.reg_alpha2 = hwsim_alpha2s[2];
4529				break;
4530			}
4531			break;
4532		default:
4533			break;
4534		}
4535
4536		param.p2p_device = support_p2p_device;
4537		param.use_chanctx = channels > 1;
4538		param.iftypes = HWSIM_IFTYPE_SUPPORT_MASK;
4539		if (param.p2p_device)
4540			param.iftypes |= BIT(NL80211_IFTYPE_P2P_DEVICE);
4541
4542		err = mac80211_hwsim_new_radio(NULL, &param);
4543		if (err < 0)
4544			goto out_free_radios;
4545	}
4546
4547	hwsim_mon = alloc_netdev(0, "hwsim%d", NET_NAME_UNKNOWN,
4548				 hwsim_mon_setup);
4549	if (hwsim_mon == NULL) {
4550		err = -ENOMEM;
4551		goto out_free_radios;
4552	}
4553
4554	rtnl_lock();
4555	err = dev_alloc_name(hwsim_mon, hwsim_mon->name);
4556	if (err < 0) {
4557		rtnl_unlock();
4558		goto out_free_mon;
4559	}
4560
4561	err = register_netdevice(hwsim_mon);
4562	if (err < 0) {
4563		rtnl_unlock();
4564		goto out_free_mon;
4565	}
4566	rtnl_unlock();
4567
4568	return 0;
4569
4570out_free_mon:
4571	free_netdev(hwsim_mon);
4572out_free_radios:
4573	mac80211_hwsim_free();
4574out_exit_virtio:
4575	hwsim_unregister_virtio_driver();
4576out_exit_netlink:
4577	hwsim_exit_netlink();
4578out_unregister_driver:
4579	platform_driver_unregister(&mac80211_hwsim_driver);
4580out_unregister_pernet:
4581	unregister_pernet_device(&hwsim_net_ops);
4582out_free_rht:
4583	rhashtable_destroy(&hwsim_radios_rht);
4584	return err;
4585}
4586module_init(init_mac80211_hwsim);
4587
4588static void __exit exit_mac80211_hwsim(void)
4589{
4590	pr_debug("mac80211_hwsim: unregister radios\n");
4591
4592	hwsim_unregister_virtio_driver();
4593	hwsim_exit_netlink();
4594
4595	mac80211_hwsim_free();
4596
4597	rhashtable_destroy(&hwsim_radios_rht);
4598	unregister_netdev(hwsim_mon);
4599	platform_driver_unregister(&mac80211_hwsim_driver);
4600	unregister_pernet_device(&hwsim_net_ops);
4601}
4602module_exit(exit_mac80211_hwsim);
4603