1 /*
2  * Copyright 2002-2005, Instant802 Networks, Inc.
3  * Copyright 2005-2006, Devicescape Software, Inc.
4  * Copyright 2007	Johannes Berg <johannes@sipsolutions.net>
5  * Copyright 2008-2011	Luis R. Rodriguez <mcgrof@qca.qualcomm.com>
6  * Copyright 2013-2014  Intel Mobile Communications GmbH
7  * Copyright      2017  Intel Deutschland GmbH
8  * Copyright (C) 2018 - 2025 Intel Corporation
9  *
10  * Permission to use, copy, modify, and/or distribute this software for any
11  * purpose with or without fee is hereby granted, provided that the above
12  * copyright notice and this permission notice appear in all copies.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
15  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
16  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
17  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
18  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
19  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
20  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
21  */
22 
23 
24 /**
25  * DOC: Wireless regulatory infrastructure
26  *
27  * The usual implementation is for a driver to read a device EEPROM to
28  * determine which regulatory domain it should be operating under, then
29  * looking up the allowable channels in a driver-local table and finally
30  * registering those channels in the wiphy structure.
31  *
32  * Another set of compliance enforcement is for drivers to use their
33  * own compliance limits which can be stored on the EEPROM. The host
34  * driver or firmware may ensure these are used.
35  *
36  * In addition to all this we provide an extra layer of regulatory
37  * conformance. For drivers which do not have any regulatory
38  * information CRDA provides the complete regulatory solution.
39  * For others it provides a community effort on further restrictions
40  * to enhance compliance.
41  *
42  * Note: When number of rules --> infinity we will not be able to
43  * index on alpha2 any more, instead we'll probably have to
44  * rely on some SHA1 checksum of the regdomain for example.
45  *
46  */
47 
48 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
49 
50 #include <linux/kernel.h>
51 #include <linux/export.h>
52 #include <linux/slab.h>
53 #include <linux/list.h>
54 #include <linux/ctype.h>
55 #include <linux/nl80211.h>
56 #include <linux/platform_device.h>
57 #include <linux/verification.h>
58 #include <linux/moduleparam.h>
59 #include <linux/firmware.h>
60 #include <linux/units.h>
61 
62 #include <net/cfg80211.h>
63 #include "core.h"
64 #include "reg.h"
65 #include "rdev-ops.h"
66 #include "nl80211.h"
67 
68 /*
69  * Grace period we give before making sure all current interfaces reside on
70  * channels allowed by the current regulatory domain.
71  */
72 #define REG_ENFORCE_GRACE_MS 60000
73 
74 /**
75  * enum reg_request_treatment - regulatory request treatment
76  *
77  * @REG_REQ_OK: continue processing the regulatory request
78  * @REG_REQ_IGNORE: ignore the regulatory request
79  * @REG_REQ_INTERSECT: the regulatory domain resulting from this request should
80  *	be intersected with the current one.
81  * @REG_REQ_ALREADY_SET: the regulatory request will not change the current
82  *	regulatory settings, and no further processing is required.
83  */
84 enum reg_request_treatment {
85 	REG_REQ_OK,
86 	REG_REQ_IGNORE,
87 	REG_REQ_INTERSECT,
88 	REG_REQ_ALREADY_SET,
89 };
90 
91 static struct regulatory_request core_request_world = {
92 	.initiator = NL80211_REGDOM_SET_BY_CORE,
93 	.alpha2[0] = '0',
94 	.alpha2[1] = '0',
95 	.intersect = false,
96 	.processed = true,
97 	.country_ie_env = ENVIRON_ANY,
98 };
99 
100 /*
101  * Receipt of information from last regulatory request,
102  * protected by RTNL (and can be accessed with RCU protection)
103  */
104 static struct regulatory_request __rcu *last_request =
105 	(void __force __rcu *)&core_request_world;
106 
107 /* To trigger userspace events and load firmware */
108 static struct platform_device *reg_pdev;
109 
110 /*
111  * Central wireless core regulatory domains, we only need two,
112  * the current one and a world regulatory domain in case we have no
113  * information to give us an alpha2.
114  * (protected by RTNL, can be read under RCU)
115  */
116 const struct ieee80211_regdomain __rcu *cfg80211_regdomain;
117 
118 /*
119  * Number of devices that registered to the core
120  * that support cellular base station regulatory hints
121  * (protected by RTNL)
122  */
123 static int reg_num_devs_support_basehint;
124 
125 /*
126  * State variable indicating if the platform on which the devices
127  * are attached is operating in an indoor environment. The state variable
128  * is relevant for all registered devices.
129  */
130 static bool reg_is_indoor;
131 static DEFINE_SPINLOCK(reg_indoor_lock);
132 
133 /* Used to track the userspace process controlling the indoor setting */
134 static u32 reg_is_indoor_portid;
135 
136 static void restore_regulatory_settings(bool reset_user, bool cached);
137 static void print_regdomain(const struct ieee80211_regdomain *rd);
138 static void reg_process_hint(struct regulatory_request *reg_request);
139 
get_cfg80211_regdom(void)140 static const struct ieee80211_regdomain *get_cfg80211_regdom(void)
141 {
142 	return rcu_dereference_rtnl(cfg80211_regdomain);
143 }
144 
145 /*
146  * Returns the regulatory domain associated with the wiphy.
147  *
148  * Requires any of RTNL, wiphy mutex or RCU protection.
149  */
get_wiphy_regdom(struct wiphy * wiphy)150 const struct ieee80211_regdomain *get_wiphy_regdom(struct wiphy *wiphy)
151 {
152 	return rcu_dereference_check(wiphy->regd,
153 				     lockdep_is_held(&wiphy->mtx) ||
154 				     lockdep_rtnl_is_held());
155 }
156 EXPORT_SYMBOL(get_wiphy_regdom);
157 
reg_dfs_region_str(enum nl80211_dfs_regions dfs_region)158 static const char *reg_dfs_region_str(enum nl80211_dfs_regions dfs_region)
159 {
160 	switch (dfs_region) {
161 	case NL80211_DFS_UNSET:
162 		return "unset";
163 	case NL80211_DFS_FCC:
164 		return "FCC";
165 	case NL80211_DFS_ETSI:
166 		return "ETSI";
167 	case NL80211_DFS_JP:
168 		return "JP";
169 	}
170 	return "Unknown";
171 }
172 
reg_get_dfs_region(struct wiphy * wiphy)173 enum nl80211_dfs_regions reg_get_dfs_region(struct wiphy *wiphy)
174 {
175 	const struct ieee80211_regdomain *regd = NULL;
176 	const struct ieee80211_regdomain *wiphy_regd = NULL;
177 	enum nl80211_dfs_regions dfs_region;
178 
179 	rcu_read_lock();
180 	regd = get_cfg80211_regdom();
181 	dfs_region = regd->dfs_region;
182 
183 	if (!wiphy)
184 		goto out;
185 
186 	wiphy_regd = get_wiphy_regdom(wiphy);
187 	if (!wiphy_regd)
188 		goto out;
189 
190 	if (wiphy->regulatory_flags & REGULATORY_WIPHY_SELF_MANAGED) {
191 		dfs_region = wiphy_regd->dfs_region;
192 		goto out;
193 	}
194 
195 	if (wiphy_regd->dfs_region == regd->dfs_region)
196 		goto out;
197 
198 	pr_debug("%s: device specific dfs_region (%s) disagrees with cfg80211's central dfs_region (%s)\n",
199 		 dev_name(&wiphy->dev),
200 		 reg_dfs_region_str(wiphy_regd->dfs_region),
201 		 reg_dfs_region_str(regd->dfs_region));
202 
203 out:
204 	rcu_read_unlock();
205 
206 	return dfs_region;
207 }
208 
rcu_free_regdom(const struct ieee80211_regdomain * r)209 static void rcu_free_regdom(const struct ieee80211_regdomain *r)
210 {
211 	if (!r)
212 		return;
213 	kfree_rcu((struct ieee80211_regdomain *)r, rcu_head);
214 }
215 
get_last_request(void)216 static struct regulatory_request *get_last_request(void)
217 {
218 	return rcu_dereference_rtnl(last_request);
219 }
220 
221 /* Used to queue up regulatory hints */
222 static LIST_HEAD(reg_requests_list);
223 static DEFINE_SPINLOCK(reg_requests_lock);
224 
225 /* Used to queue up beacon hints for review */
226 static LIST_HEAD(reg_pending_beacons);
227 static DEFINE_SPINLOCK(reg_pending_beacons_lock);
228 
229 /* Used to keep track of processed beacon hints */
230 static LIST_HEAD(reg_beacon_list);
231 
232 struct reg_beacon {
233 	struct list_head list;
234 	struct ieee80211_channel chan;
235 };
236 
237 static void reg_check_chans_work(struct work_struct *work);
238 static DECLARE_DELAYED_WORK(reg_check_chans, reg_check_chans_work);
239 
240 static void reg_todo(struct work_struct *work);
241 static DECLARE_WORK(reg_work, reg_todo);
242 
243 /* We keep a static world regulatory domain in case of the absence of CRDA */
244 static const struct ieee80211_regdomain world_regdom = {
245 	.n_reg_rules = 8,
246 	.alpha2 =  "00",
247 	.reg_rules = {
248 		/* IEEE 802.11b/g, channels 1..11 */
249 		REG_RULE(2412-10, 2462+10, 40, 6, 20, 0),
250 		/* IEEE 802.11b/g, channels 12..13. */
251 		REG_RULE(2467-10, 2472+10, 20, 6, 20,
252 			NL80211_RRF_NO_IR | NL80211_RRF_AUTO_BW),
253 		/* IEEE 802.11 channel 14 - Only JP enables
254 		 * this and for 802.11b only */
255 		REG_RULE(2484-10, 2484+10, 20, 6, 20,
256 			NL80211_RRF_NO_IR |
257 			NL80211_RRF_NO_OFDM),
258 		/* IEEE 802.11a, channel 36..48 */
259 		REG_RULE(5180-10, 5240+10, 80, 6, 20,
260                         NL80211_RRF_NO_IR |
261                         NL80211_RRF_AUTO_BW),
262 
263 		/* IEEE 802.11a, channel 52..64 - DFS required */
264 		REG_RULE(5260-10, 5320+10, 80, 6, 20,
265 			NL80211_RRF_NO_IR |
266 			NL80211_RRF_AUTO_BW |
267 			NL80211_RRF_DFS),
268 
269 		/* IEEE 802.11a, channel 100..144 - DFS required */
270 		REG_RULE(5500-10, 5720+10, 160, 6, 20,
271 			NL80211_RRF_NO_IR |
272 			NL80211_RRF_DFS),
273 
274 		/* IEEE 802.11a, channel 149..165 */
275 		REG_RULE(5745-10, 5825+10, 80, 6, 20,
276 			NL80211_RRF_NO_IR),
277 
278 		/* IEEE 802.11ad (60GHz), channels 1..3 */
279 		REG_RULE(56160+2160*1-1080, 56160+2160*3+1080, 2160, 0, 0, 0),
280 	}
281 };
282 
283 /* protected by RTNL */
284 static const struct ieee80211_regdomain *cfg80211_world_regdom =
285 	&world_regdom;
286 
287 static char *ieee80211_regdom = "00";
288 static char user_alpha2[2];
289 static const struct ieee80211_regdomain *cfg80211_user_regdom;
290 
291 module_param(ieee80211_regdom, charp, 0444);
292 MODULE_PARM_DESC(ieee80211_regdom, "IEEE 802.11 regulatory domain code");
293 
reg_free_request(struct regulatory_request * request)294 static void reg_free_request(struct regulatory_request *request)
295 {
296 	if (request == &core_request_world)
297 		return;
298 
299 	if (request != get_last_request())
300 		kfree(request);
301 }
302 
reg_free_last_request(void)303 static void reg_free_last_request(void)
304 {
305 	struct regulatory_request *lr = get_last_request();
306 
307 	if (lr != &core_request_world && lr)
308 		kfree_rcu(lr, rcu_head);
309 }
310 
reg_update_last_request(struct regulatory_request * request)311 static void reg_update_last_request(struct regulatory_request *request)
312 {
313 	struct regulatory_request *lr;
314 
315 	lr = get_last_request();
316 	if (lr == request)
317 		return;
318 
319 	reg_free_last_request();
320 	rcu_assign_pointer(last_request, request);
321 }
322 
reset_regdomains(bool full_reset,const struct ieee80211_regdomain * new_regdom)323 static void reset_regdomains(bool full_reset,
324 			     const struct ieee80211_regdomain *new_regdom)
325 {
326 	const struct ieee80211_regdomain *r;
327 
328 	ASSERT_RTNL();
329 
330 	r = get_cfg80211_regdom();
331 
332 	/* avoid freeing static information or freeing something twice */
333 	if (r == cfg80211_world_regdom)
334 		r = NULL;
335 	if (cfg80211_world_regdom == &world_regdom)
336 		cfg80211_world_regdom = NULL;
337 	if (r == &world_regdom)
338 		r = NULL;
339 
340 	rcu_free_regdom(r);
341 	rcu_free_regdom(cfg80211_world_regdom);
342 
343 	cfg80211_world_regdom = &world_regdom;
344 	rcu_assign_pointer(cfg80211_regdomain, new_regdom);
345 
346 	if (!full_reset)
347 		return;
348 
349 	reg_update_last_request(&core_request_world);
350 }
351 
352 /*
353  * Dynamic world regulatory domain requested by the wireless
354  * core upon initialization
355  */
update_world_regdomain(const struct ieee80211_regdomain * rd)356 static void update_world_regdomain(const struct ieee80211_regdomain *rd)
357 {
358 	struct regulatory_request *lr;
359 
360 	lr = get_last_request();
361 
362 	WARN_ON(!lr);
363 
364 	reset_regdomains(false, rd);
365 
366 	cfg80211_world_regdom = rd;
367 }
368 
is_world_regdom(const char * alpha2)369 bool is_world_regdom(const char *alpha2)
370 {
371 	if (!alpha2)
372 		return false;
373 	return alpha2[0] == '0' && alpha2[1] == '0';
374 }
375 
is_alpha2_set(const char * alpha2)376 static bool is_alpha2_set(const char *alpha2)
377 {
378 	if (!alpha2)
379 		return false;
380 	return alpha2[0] && alpha2[1];
381 }
382 
is_unknown_alpha2(const char * alpha2)383 static bool is_unknown_alpha2(const char *alpha2)
384 {
385 	if (!alpha2)
386 		return false;
387 	/*
388 	 * Special case where regulatory domain was built by driver
389 	 * but a specific alpha2 cannot be determined
390 	 */
391 	return alpha2[0] == '9' && alpha2[1] == '9';
392 }
393 
is_intersected_alpha2(const char * alpha2)394 static bool is_intersected_alpha2(const char *alpha2)
395 {
396 	if (!alpha2)
397 		return false;
398 	/*
399 	 * Special case where regulatory domain is the
400 	 * result of an intersection between two regulatory domain
401 	 * structures
402 	 */
403 	return alpha2[0] == '9' && alpha2[1] == '8';
404 }
405 
is_an_alpha2(const char * alpha2)406 static bool is_an_alpha2(const char *alpha2)
407 {
408 	if (!alpha2)
409 		return false;
410 	return isascii(alpha2[0]) && isalpha(alpha2[0]) &&
411 	       isascii(alpha2[1]) && isalpha(alpha2[1]);
412 }
413 
alpha2_equal(const char * alpha2_x,const char * alpha2_y)414 static bool alpha2_equal(const char *alpha2_x, const char *alpha2_y)
415 {
416 	if (!alpha2_x || !alpha2_y)
417 		return false;
418 	return alpha2_x[0] == alpha2_y[0] && alpha2_x[1] == alpha2_y[1];
419 }
420 
regdom_changes(const char * alpha2)421 static bool regdom_changes(const char *alpha2)
422 {
423 	const struct ieee80211_regdomain *r = get_cfg80211_regdom();
424 
425 	if (!r)
426 		return true;
427 	return !alpha2_equal(r->alpha2, alpha2);
428 }
429 
430 /*
431  * The NL80211_REGDOM_SET_BY_USER regdom alpha2 is cached, this lets
432  * you know if a valid regulatory hint with NL80211_REGDOM_SET_BY_USER
433  * has ever been issued.
434  */
is_user_regdom_saved(void)435 static bool is_user_regdom_saved(void)
436 {
437 	if (user_alpha2[0] == '9' && user_alpha2[1] == '7')
438 		return false;
439 
440 	/* This would indicate a mistake on the design */
441 	if (WARN(!is_world_regdom(user_alpha2) && !is_an_alpha2(user_alpha2),
442 		 "Unexpected user alpha2: %c%c\n",
443 		 user_alpha2[0], user_alpha2[1]))
444 		return false;
445 
446 	return true;
447 }
448 
449 static const struct ieee80211_regdomain *
reg_copy_regd(const struct ieee80211_regdomain * src_regd)450 reg_copy_regd(const struct ieee80211_regdomain *src_regd)
451 {
452 	struct ieee80211_regdomain *regd;
453 	unsigned int i;
454 
455 	regd = kzalloc(struct_size(regd, reg_rules, src_regd->n_reg_rules),
456 		       GFP_KERNEL);
457 	if (!regd)
458 		return ERR_PTR(-ENOMEM);
459 
460 	memcpy(regd, src_regd, sizeof(struct ieee80211_regdomain));
461 
462 	for (i = 0; i < src_regd->n_reg_rules; i++)
463 		memcpy(®d->reg_rules[i], &src_regd->reg_rules[i],
464 		       sizeof(struct ieee80211_reg_rule));
465 
466 	return regd;
467 }
468 
cfg80211_save_user_regdom(const struct ieee80211_regdomain * rd)469 static void cfg80211_save_user_regdom(const struct ieee80211_regdomain *rd)
470 {
471 	ASSERT_RTNL();
472 
473 	if (!IS_ERR(cfg80211_user_regdom))
474 		kfree(cfg80211_user_regdom);
475 	cfg80211_user_regdom = reg_copy_regd(rd);
476 }
477 
478 struct reg_regdb_apply_request {
479 	struct list_head list;
480 	const struct ieee80211_regdomain *regdom;
481 };
482 
483 static LIST_HEAD(reg_regdb_apply_list);
484 static DEFINE_MUTEX(reg_regdb_apply_mutex);
485 
reg_regdb_apply(struct work_struct * work)486 static void reg_regdb_apply(struct work_struct *work)
487 {
488 	struct reg_regdb_apply_request *request;
489 
490 	rtnl_lock();
491 
492 	mutex_lock(®_regdb_apply_mutex);
493 	while (!list_empty(®_regdb_apply_list)) {
494 		request = list_first_entry(®_regdb_apply_list,
495 					   struct reg_regdb_apply_request,
496 					   list);
497 		list_del(&request->list);
498 
499 		set_regdom(request->regdom, REGD_SOURCE_INTERNAL_DB);
500 		kfree(request);
501 	}
502 	mutex_unlock(®_regdb_apply_mutex);
503 
504 	rtnl_unlock();
505 }
506 
507 static DECLARE_WORK(reg_regdb_work, reg_regdb_apply);
508 
reg_schedule_apply(const struct ieee80211_regdomain * regdom)509 static int reg_schedule_apply(const struct ieee80211_regdomain *regdom)
510 {
511 	struct reg_regdb_apply_request *request;
512 
513 	request = kzalloc(sizeof(struct reg_regdb_apply_request), GFP_KERNEL);
514 	if (!request) {
515 		kfree(regdom);
516 		return -ENOMEM;
517 	}
518 
519 	request->regdom = regdom;
520 
521 	mutex_lock(®_regdb_apply_mutex);
522 	list_add_tail(&request->list, ®_regdb_apply_list);
523 	mutex_unlock(®_regdb_apply_mutex);
524 
525 	schedule_work(®_regdb_work);
526 	return 0;
527 }
528 
529 #ifdef CONFIG_CFG80211_CRDA_SUPPORT
530 /* Max number of consecutive attempts to communicate with CRDA  */
531 #define REG_MAX_CRDA_TIMEOUTS 10
532 
533 static u32 reg_crda_timeouts;
534 
535 static void crda_timeout_work(struct work_struct *work);
536 static DECLARE_DELAYED_WORK(crda_timeout, crda_timeout_work);
537 
crda_timeout_work(struct work_struct * work)538 static void crda_timeout_work(struct work_struct *work)
539 {
540 	pr_debug("Timeout while waiting for CRDA to reply, restoring regulatory settings\n");
541 	rtnl_lock();
542 	reg_crda_timeouts++;
543 	restore_regulatory_settings(true, false);
544 	rtnl_unlock();
545 }
546 
cancel_crda_timeout(void)547 static void cancel_crda_timeout(void)
548 {
549 	cancel_delayed_work(&crda_timeout);
550 }
551 
cancel_crda_timeout_sync(void)552 static void cancel_crda_timeout_sync(void)
553 {
554 	cancel_delayed_work_sync(&crda_timeout);
555 }
556 
reset_crda_timeouts(void)557 static void reset_crda_timeouts(void)
558 {
559 	reg_crda_timeouts = 0;
560 }
561 
562 /*
563  * This lets us keep regulatory code which is updated on a regulatory
564  * basis in userspace.
565  */
call_crda(const char * alpha2)566 static int call_crda(const char *alpha2)
567 {
568 	char country[12];
569 	char *env[] = { country, NULL };
570 	int ret;
571 
572 	snprintf(country, sizeof(country), "COUNTRY=%c%c",
573 		 alpha2[0], alpha2[1]);
574 
575 	if (reg_crda_timeouts > REG_MAX_CRDA_TIMEOUTS) {
576 		pr_debug("Exceeded CRDA call max attempts. Not calling CRDA\n");
577 		return -EINVAL;
578 	}
579 
580 	if (!is_world_regdom((char *) alpha2))
581 		pr_debug("Calling CRDA for country: %c%c\n",
582 			 alpha2[0], alpha2[1]);
583 	else
584 		pr_debug("Calling CRDA to update world regulatory domain\n");
585 
586 	ret = kobject_uevent_env(®_pdev->dev.kobj, KOBJ_CHANGE, env);
587 	if (ret)
588 		return ret;
589 
590 	queue_delayed_work(system_power_efficient_wq,
591 			   &crda_timeout, msecs_to_jiffies(3142));
592 	return 0;
593 }
594 #else
cancel_crda_timeout(void)595 static inline void cancel_crda_timeout(void) {}
cancel_crda_timeout_sync(void)596 static inline void cancel_crda_timeout_sync(void) {}
reset_crda_timeouts(void)597 static inline void reset_crda_timeouts(void) {}
call_crda(const char * alpha2)598 static inline int call_crda(const char *alpha2)
599 {
600 	return -ENODATA;
601 }
602 #endif /* CONFIG_CFG80211_CRDA_SUPPORT */
603 
604 /* code to directly load a firmware database through request_firmware */
605 static const struct fwdb_header *regdb;
606 
607 struct fwdb_country {
608 	u8 alpha2[2];
609 	__be16 coll_ptr;
610 	/* this struct cannot be extended */
611 } __packed __aligned(4);
612 
613 struct fwdb_collection {
614 	u8 len;
615 	u8 n_rules;
616 	u8 dfs_region;
617 	/* no optional data yet */
618 	/* aligned to 2, then followed by __be16 array of rule pointers */
619 } __packed __aligned(4);
620 
621 enum fwdb_flags {
622 	FWDB_FLAG_NO_OFDM	= BIT(0),
623 	FWDB_FLAG_NO_OUTDOOR	= BIT(1),
624 	FWDB_FLAG_DFS		= BIT(2),
625 	FWDB_FLAG_NO_IR		= BIT(3),
626 	FWDB_FLAG_AUTO_BW	= BIT(4),
627 };
628 
629 struct fwdb_wmm_ac {
630 	u8 ecw;
631 	u8 aifsn;
632 	__be16 cot;
633 } __packed;
634 
635 struct fwdb_wmm_rule {
636 	struct fwdb_wmm_ac client[IEEE80211_NUM_ACS];
637 	struct fwdb_wmm_ac ap[IEEE80211_NUM_ACS];
638 } __packed;
639 
640 struct fwdb_rule {
641 	u8 len;
642 	u8 flags;
643 	__be16 max_eirp;
644 	__be32 start, end, max_bw;
645 	/* start of optional data */
646 	__be16 cac_timeout;
647 	__be16 wmm_ptr;
648 } __packed __aligned(4);
649 
650 #define FWDB_MAGIC 0x52474442
651 #define FWDB_VERSION 20
652 
653 struct fwdb_header {
654 	__be32 magic;
655 	__be32 version;
656 	struct fwdb_country country[];
657 } __packed __aligned(4);
658 
ecw2cw(int ecw)659 static int ecw2cw(int ecw)
660 {
661 	return (1 << ecw) - 1;
662 }
663 
valid_wmm(struct fwdb_wmm_rule * rule)664 static bool valid_wmm(struct fwdb_wmm_rule *rule)
665 {
666 	struct fwdb_wmm_ac *ac = (struct fwdb_wmm_ac *)rule;
667 	int i;
668 
669 	for (i = 0; i < IEEE80211_NUM_ACS * 2; i++) {
670 		u16 cw_min = ecw2cw((ac[i].ecw & 0xf0) >> 4);
671 		u16 cw_max = ecw2cw(ac[i].ecw & 0x0f);
672 		u8 aifsn = ac[i].aifsn;
673 
674 		if (cw_min >= cw_max)
675 			return false;
676 
677 		if (aifsn < 1)
678 			return false;
679 	}
680 
681 	return true;
682 }
683 
valid_rule(const u8 * data,unsigned int size,u16 rule_ptr)684 static bool valid_rule(const u8 *data, unsigned int size, u16 rule_ptr)
685 {
686 	struct fwdb_rule *rule = (void *)(data + (rule_ptr << 2));
687 
688 	if ((u8 *)rule + sizeof(rule->len) > data + size)
689 		return false;
690 
691 	/* mandatory fields */
692 	if (rule->len < offsetofend(struct fwdb_rule, max_bw))
693 		return false;
694 	if (rule->len >= offsetofend(struct fwdb_rule, wmm_ptr)) {
695 		u32 wmm_ptr = be16_to_cpu(rule->wmm_ptr) << 2;
696 		struct fwdb_wmm_rule *wmm;
697 
698 		if (wmm_ptr + sizeof(struct fwdb_wmm_rule) > size)
699 			return false;
700 
701 		wmm = (void *)(data + wmm_ptr);
702 
703 		if (!valid_wmm(wmm))
704 			return false;
705 	}
706 	return true;
707 }
708 
valid_country(const u8 * data,unsigned int size,const struct fwdb_country * country)709 static bool valid_country(const u8 *data, unsigned int size,
710 			  const struct fwdb_country *country)
711 {
712 	unsigned int ptr = be16_to_cpu(country->coll_ptr) << 2;
713 	struct fwdb_collection *coll = (void *)(data + ptr);
714 	__be16 *rules_ptr;
715 	unsigned int i;
716 
717 	/* make sure we can read len/n_rules */
718 	if ((u8 *)coll + offsetofend(typeof(*coll), n_rules) > data + size)
719 		return false;
720 
721 	/* make sure base struct and all rules fit */
722 	if ((u8 *)coll + ALIGN(coll->len, 2) +
723 	    (coll->n_rules * 2) > data + size)
724 		return false;
725 
726 	/* mandatory fields must exist */
727 	if (coll->len < offsetofend(struct fwdb_collection, dfs_region))
728 		return false;
729 
730 	rules_ptr = (void *)((u8 *)coll + ALIGN(coll->len, 2));
731 
732 	for (i = 0; i < coll->n_rules; i++) {
733 		u16 rule_ptr = be16_to_cpu(rules_ptr[i]);
734 
735 		if (!valid_rule(data, size, rule_ptr))
736 			return false;
737 	}
738 
739 	return true;
740 }
741 
742 #ifdef CONFIG_CFG80211_REQUIRE_SIGNED_REGDB
743 #include <keys/asymmetric-type.h>
744 
745 static struct key *builtin_regdb_keys;
746 
load_builtin_regdb_keys(void)747 static int __init load_builtin_regdb_keys(void)
748 {
749 	builtin_regdb_keys =
750 		keyring_alloc(".builtin_regdb_keys",
751 			      KUIDT_INIT(0), KGIDT_INIT(0), current_cred(),
752 			      ((KEY_POS_ALL & ~KEY_POS_SETATTR) |
753 			      KEY_USR_VIEW | KEY_USR_READ | KEY_USR_SEARCH),
754 			      KEY_ALLOC_NOT_IN_QUOTA, NULL, NULL);
755 	if (IS_ERR(builtin_regdb_keys))
756 		return PTR_ERR(builtin_regdb_keys);
757 
758 	pr_notice("Loading compiled-in X.509 certificates for regulatory database\n");
759 
760 #ifdef CONFIG_CFG80211_USE_KERNEL_REGDB_KEYS
761 	x509_load_certificate_list(shipped_regdb_certs,
762 				   shipped_regdb_certs_len,
763 				   builtin_regdb_keys);
764 #endif
765 #ifdef CONFIG_CFG80211_EXTRA_REGDB_KEYDIR
766 	if (CONFIG_CFG80211_EXTRA_REGDB_KEYDIR[0] != '\0')
767 		x509_load_certificate_list(extra_regdb_certs,
768 					   extra_regdb_certs_len,
769 					   builtin_regdb_keys);
770 #endif
771 
772 	return 0;
773 }
774 
775 MODULE_FIRMWARE("regulatory.db.p7s");
776 
regdb_has_valid_signature(const u8 * data,unsigned int size)777 static bool regdb_has_valid_signature(const u8 *data, unsigned int size)
778 {
779 	const struct firmware *sig;
780 	bool result;
781 
782 	if (request_firmware(&sig, "regulatory.db.p7s", ®_pdev->dev))
783 		return false;
784 
785 	result = verify_pkcs7_signature(data, size, sig->data, sig->size,
786 					builtin_regdb_keys,
787 					VERIFYING_UNSPECIFIED_SIGNATURE,
788 					NULL, NULL) == 0;
789 
790 	release_firmware(sig);
791 
792 	return result;
793 }
794 
free_regdb_keyring(void)795 static void free_regdb_keyring(void)
796 {
797 	key_put(builtin_regdb_keys);
798 }
799 #else
load_builtin_regdb_keys(void)800 static int load_builtin_regdb_keys(void)
801 {
802 	return 0;
803 }
804 
regdb_has_valid_signature(const u8 * data,unsigned int size)805 static bool regdb_has_valid_signature(const u8 *data, unsigned int size)
806 {
807 	return true;
808 }
809 
free_regdb_keyring(void)810 static void free_regdb_keyring(void)
811 {
812 }
813 #endif /* CONFIG_CFG80211_REQUIRE_SIGNED_REGDB */
814 
valid_regdb(const u8 * data,unsigned int size)815 static bool valid_regdb(const u8 *data, unsigned int size)
816 {
817 	const struct fwdb_header *hdr = (void *)data;
818 	const struct fwdb_country *country;
819 
820 	if (size < sizeof(*hdr))
821 		return false;
822 
823 	if (hdr->magic != cpu_to_be32(FWDB_MAGIC))
824 		return false;
825 
826 	if (hdr->version != cpu_to_be32(FWDB_VERSION))
827 		return false;
828 
829 	if (!regdb_has_valid_signature(data, size))
830 		return false;
831 
832 	country = &hdr->country[0];
833 	while ((u8 *)(country + 1) <= data + size) {
834 		if (!country->coll_ptr)
835 			break;
836 		if (!valid_country(data, size, country))
837 			return false;
838 		country++;
839 	}
840 
841 	return true;
842 }
843 
set_wmm_rule(const struct fwdb_header * db,const struct fwdb_country * country,const struct fwdb_rule * rule,struct ieee80211_reg_rule * rrule)844 static void set_wmm_rule(const struct fwdb_header *db,
845 			 const struct fwdb_country *country,
846 			 const struct fwdb_rule *rule,
847 			 struct ieee80211_reg_rule *rrule)
848 {
849 	struct ieee80211_wmm_rule *wmm_rule = &rrule->wmm_rule;
850 	struct fwdb_wmm_rule *wmm;
851 	unsigned int i, wmm_ptr;
852 
853 	wmm_ptr = be16_to_cpu(rule->wmm_ptr) << 2;
854 	wmm = (void *)((u8 *)db + wmm_ptr);
855 
856 	if (!valid_wmm(wmm)) {
857 		pr_err("Invalid regulatory WMM rule %u-%u in domain %c%c\n",
858 		       be32_to_cpu(rule->start), be32_to_cpu(rule->end),
859 		       country->alpha2[0], country->alpha2[1]);
860 		return;
861 	}
862 
863 	for (i = 0; i < IEEE80211_NUM_ACS; i++) {
864 		wmm_rule->client[i].cw_min =
865 			ecw2cw((wmm->client[i].ecw & 0xf0) >> 4);
866 		wmm_rule->client[i].cw_max = ecw2cw(wmm->client[i].ecw & 0x0f);
867 		wmm_rule->client[i].aifsn =  wmm->client[i].aifsn;
868 		wmm_rule->client[i].cot =
869 			1000 * be16_to_cpu(wmm->client[i].cot);
870 		wmm_rule->ap[i].cw_min = ecw2cw((wmm->ap[i].ecw & 0xf0) >> 4);
871 		wmm_rule->ap[i].cw_max = ecw2cw(wmm->ap[i].ecw & 0x0f);
872 		wmm_rule->ap[i].aifsn = wmm->ap[i].aifsn;
873 		wmm_rule->ap[i].cot = 1000 * be16_to_cpu(wmm->ap[i].cot);
874 	}
875 
876 	rrule->has_wmm = true;
877 }
878 
__regdb_query_wmm(const struct fwdb_header * db,const struct fwdb_country * country,int freq,struct ieee80211_reg_rule * rrule)879 static int __regdb_query_wmm(const struct fwdb_header *db,
880 			     const struct fwdb_country *country, int freq,
881 			     struct ieee80211_reg_rule *rrule)
882 {
883 	unsigned int ptr = be16_to_cpu(country->coll_ptr) << 2;
884 	struct fwdb_collection *coll = (void *)((u8 *)db + ptr);
885 	int i;
886 
887 	for (i = 0; i < coll->n_rules; i++) {
888 		__be16 *rules_ptr = (void *)((u8 *)coll + ALIGN(coll->len, 2));
889 		unsigned int rule_ptr = be16_to_cpu(rules_ptr[i]) << 2;
890 		struct fwdb_rule *rule = (void *)((u8 *)db + rule_ptr);
891 
892 		if (rule->len < offsetofend(struct fwdb_rule, wmm_ptr))
893 			continue;
894 
895 		if (freq >= KHZ_TO_MHZ(be32_to_cpu(rule->start)) &&
896 		    freq <= KHZ_TO_MHZ(be32_to_cpu(rule->end))) {
897 			set_wmm_rule(db, country, rule, rrule);
898 			return 0;
899 		}
900 	}
901 
902 	return -ENODATA;
903 }
904 
reg_query_regdb_wmm(char * alpha2,int freq,struct ieee80211_reg_rule * rule)905 int reg_query_regdb_wmm(char *alpha2, int freq, struct ieee80211_reg_rule *rule)
906 {
907 	const struct fwdb_header *hdr = regdb;
908 	const struct fwdb_country *country;
909 
910 	if (!regdb)
911 		return -ENODATA;
912 
913 	if (IS_ERR(regdb))
914 		return PTR_ERR(regdb);
915 
916 	country = &hdr->country[0];
917 	while (country->coll_ptr) {
918 		if (alpha2_equal(alpha2, country->alpha2))
919 			return __regdb_query_wmm(regdb, country, freq, rule);
920 
921 		country++;
922 	}
923 
924 	return -ENODATA;
925 }
926 EXPORT_SYMBOL(reg_query_regdb_wmm);
927 
regdb_query_country(const struct fwdb_header * db,const struct fwdb_country * country)928 static int regdb_query_country(const struct fwdb_header *db,
929 			       const struct fwdb_country *country)
930 {
931 	unsigned int ptr = be16_to_cpu(country->coll_ptr) << 2;
932 	struct fwdb_collection *coll = (void *)((u8 *)db + ptr);
933 	struct ieee80211_regdomain *regdom;
934 	unsigned int i;
935 
936 	regdom = kzalloc(struct_size(regdom, reg_rules, coll->n_rules),
937 			 GFP_KERNEL);
938 	if (!regdom)
939 		return -ENOMEM;
940 
941 	regdom->n_reg_rules = coll->n_rules;
942 	regdom->alpha2[0] = country->alpha2[0];
943 	regdom->alpha2[1] = country->alpha2[1];
944 	regdom->dfs_region = coll->dfs_region;
945 
946 	for (i = 0; i < regdom->n_reg_rules; i++) {
947 		__be16 *rules_ptr = (void *)((u8 *)coll + ALIGN(coll->len, 2));
948 		unsigned int rule_ptr = be16_to_cpu(rules_ptr[i]) << 2;
949 		struct fwdb_rule *rule = (void *)((u8 *)db + rule_ptr);
950 		struct ieee80211_reg_rule *rrule = ®dom->reg_rules[i];
951 
952 		rrule->freq_range.start_freq_khz = be32_to_cpu(rule->start);
953 		rrule->freq_range.end_freq_khz = be32_to_cpu(rule->end);
954 		rrule->freq_range.max_bandwidth_khz = be32_to_cpu(rule->max_bw);
955 
956 		rrule->power_rule.max_antenna_gain = 0;
957 		rrule->power_rule.max_eirp = be16_to_cpu(rule->max_eirp);
958 
959 		rrule->flags = 0;
960 		if (rule->flags & FWDB_FLAG_NO_OFDM)
961 			rrule->flags |= NL80211_RRF_NO_OFDM;
962 		if (rule->flags & FWDB_FLAG_NO_OUTDOOR)
963 			rrule->flags |= NL80211_RRF_NO_OUTDOOR;
964 		if (rule->flags & FWDB_FLAG_DFS)
965 			rrule->flags |= NL80211_RRF_DFS;
966 		if (rule->flags & FWDB_FLAG_NO_IR)
967 			rrule->flags |= NL80211_RRF_NO_IR;
968 		if (rule->flags & FWDB_FLAG_AUTO_BW)
969 			rrule->flags |= NL80211_RRF_AUTO_BW;
970 
971 		rrule->dfs_cac_ms = 0;
972 
973 		/* handle optional data */
974 		if (rule->len >= offsetofend(struct fwdb_rule, cac_timeout))
975 			rrule->dfs_cac_ms =
976 				1000 * be16_to_cpu(rule->cac_timeout);
977 		if (rule->len >= offsetofend(struct fwdb_rule, wmm_ptr))
978 			set_wmm_rule(db, country, rule, rrule);
979 	}
980 
981 	return reg_schedule_apply(regdom);
982 }
983 
query_regdb(const char * alpha2)984 static int query_regdb(const char *alpha2)
985 {
986 	const struct fwdb_header *hdr = regdb;
987 	const struct fwdb_country *country;
988 
989 	ASSERT_RTNL();
990 
991 	if (IS_ERR(regdb))
992 		return PTR_ERR(regdb);
993 
994 	country = &hdr->country[0];
995 	while (country->coll_ptr) {
996 		if (alpha2_equal(alpha2, country->alpha2))
997 			return regdb_query_country(regdb, country);
998 		country++;
999 	}
1000 
1001 	return -ENODATA;
1002 }
1003 
regdb_fw_cb(const struct firmware * fw,void * context)1004 static void regdb_fw_cb(const struct firmware *fw, void *context)
1005 {
1006 	int set_error = 0;
1007 	bool restore = true;
1008 	void *db;
1009 
1010 	if (!fw) {
1011 		pr_info("failed to load regulatory.db\n");
1012 		set_error = -ENODATA;
1013 	} else if (!valid_regdb(fw->data, fw->size)) {
1014 		pr_info("loaded regulatory.db is malformed or signature is missing/invalid\n");
1015 		set_error = -EINVAL;
1016 	}
1017 
1018 	rtnl_lock();
1019 	if (regdb && !IS_ERR(regdb)) {
1020 		/* negative case - a bug
1021 		 * positive case - can happen due to race in case of multiple cb's in
1022 		 * queue, due to usage of asynchronous callback
1023 		 *
1024 		 * Either case, just restore and free new db.
1025 		 */
1026 	} else if (set_error) {
1027 		regdb = ERR_PTR(set_error);
1028 	} else if (fw) {
1029 		db = kmemdup(fw->data, fw->size, GFP_KERNEL);
1030 		if (db) {
1031 			regdb = db;
1032 			restore = context && query_regdb(context);
1033 		} else {
1034 			restore = true;
1035 		}
1036 	}
1037 
1038 	if (restore)
1039 		restore_regulatory_settings(true, false);
1040 
1041 	rtnl_unlock();
1042 
1043 	kfree(context);
1044 
1045 	release_firmware(fw);
1046 }
1047 
1048 MODULE_FIRMWARE("regulatory.db");
1049 
query_regdb_file(const char * alpha2)1050 static int query_regdb_file(const char *alpha2)
1051 {
1052 	int err;
1053 
1054 	ASSERT_RTNL();
1055 
1056 	if (regdb)
1057 		return query_regdb(alpha2);
1058 
1059 	alpha2 = kmemdup(alpha2, 2, GFP_KERNEL);
1060 	if (!alpha2)
1061 		return -ENOMEM;
1062 
1063 	err = request_firmware_nowait(THIS_MODULE, true, "regulatory.db",
1064 				      ®_pdev->dev, GFP_KERNEL,
1065 				      (void *)alpha2, regdb_fw_cb);
1066 	if (err)
1067 		kfree(alpha2);
1068 
1069 	return err;
1070 }
1071 
reg_reload_regdb(void)1072 int reg_reload_regdb(void)
1073 {
1074 	const struct firmware *fw;
1075 	void *db;
1076 	int err;
1077 	const struct ieee80211_regdomain *current_regdomain;
1078 	struct regulatory_request *request;
1079 
1080 	err = request_firmware(&fw, "regulatory.db", ®_pdev->dev);
1081 	if (err)
1082 		return err;
1083 
1084 	if (!valid_regdb(fw->data, fw->size)) {
1085 		err = -ENODATA;
1086 		goto out;
1087 	}
1088 
1089 	db = kmemdup(fw->data, fw->size, GFP_KERNEL);
1090 	if (!db) {
1091 		err = -ENOMEM;
1092 		goto out;
1093 	}
1094 
1095 	rtnl_lock();
1096 	if (!IS_ERR_OR_NULL(regdb))
1097 		kfree(regdb);
1098 	regdb = db;
1099 
1100 	/* reset regulatory domain */
1101 	current_regdomain = get_cfg80211_regdom();
1102 
1103 	request = kzalloc(sizeof(*request), GFP_KERNEL);
1104 	if (!request) {
1105 		err = -ENOMEM;
1106 		goto out_unlock;
1107 	}
1108 
1109 	request->wiphy_idx = WIPHY_IDX_INVALID;
1110 	request->alpha2[0] = current_regdomain->alpha2[0];
1111 	request->alpha2[1] = current_regdomain->alpha2[1];
1112 	request->initiator = NL80211_REGDOM_SET_BY_CORE;
1113 	request->user_reg_hint_type = NL80211_USER_REG_HINT_USER;
1114 
1115 	reg_process_hint(request);
1116 
1117 out_unlock:
1118 	rtnl_unlock();
1119  out:
1120 	release_firmware(fw);
1121 	return err;
1122 }
1123 
reg_query_database(struct regulatory_request * request)1124 static bool reg_query_database(struct regulatory_request *request)
1125 {
1126 	if (query_regdb_file(request->alpha2) == 0)
1127 		return true;
1128 
1129 	if (call_crda(request->alpha2) == 0)
1130 		return true;
1131 
1132 	return false;
1133 }
1134 
reg_is_valid_request(const char * alpha2)1135 bool reg_is_valid_request(const char *alpha2)
1136 {
1137 	struct regulatory_request *lr = get_last_request();
1138 
1139 	if (!lr || lr->processed)
1140 		return false;
1141 
1142 	return alpha2_equal(lr->alpha2, alpha2);
1143 }
1144 
reg_get_regdomain(struct wiphy * wiphy)1145 static const struct ieee80211_regdomain *reg_get_regdomain(struct wiphy *wiphy)
1146 {
1147 	struct regulatory_request *lr = get_last_request();
1148 
1149 	/*
1150 	 * Follow the driver's regulatory domain, if present, unless a country
1151 	 * IE has been processed or a user wants to help complaince further
1152 	 */
1153 	if (lr->initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE &&
1154 	    lr->initiator != NL80211_REGDOM_SET_BY_USER &&
1155 	    wiphy->regd)
1156 		return get_wiphy_regdom(wiphy);
1157 
1158 	return get_cfg80211_regdom();
1159 }
1160 
1161 static unsigned int
reg_get_max_bandwidth_from_range(const struct ieee80211_regdomain * rd,const struct ieee80211_reg_rule * rule)1162 reg_get_max_bandwidth_from_range(const struct ieee80211_regdomain *rd,
1163 				 const struct ieee80211_reg_rule *rule)
1164 {
1165 	const struct ieee80211_freq_range *freq_range = &rule->freq_range;
1166 	const struct ieee80211_freq_range *freq_range_tmp;
1167 	const struct ieee80211_reg_rule *tmp;
1168 	u32 start_freq, end_freq, idx, no;
1169 
1170 	for (idx = 0; idx < rd->n_reg_rules; idx++)
1171 		if (rule == &rd->reg_rules[idx])
1172 			break;
1173 
1174 	if (idx == rd->n_reg_rules)
1175 		return 0;
1176 
1177 	/* get start_freq */
1178 	no = idx;
1179 
1180 	while (no) {
1181 		tmp = &rd->reg_rules[--no];
1182 		freq_range_tmp = &tmp->freq_range;
1183 
1184 		if (freq_range_tmp->end_freq_khz < freq_range->start_freq_khz)
1185 			break;
1186 
1187 		freq_range = freq_range_tmp;
1188 	}
1189 
1190 	start_freq = freq_range->start_freq_khz;
1191 
1192 	/* get end_freq */
1193 	freq_range = &rule->freq_range;
1194 	no = idx;
1195 
1196 	while (no < rd->n_reg_rules - 1) {
1197 		tmp = &rd->reg_rules[++no];
1198 		freq_range_tmp = &tmp->freq_range;
1199 
1200 		if (freq_range_tmp->start_freq_khz > freq_range->end_freq_khz)
1201 			break;
1202 
1203 		freq_range = freq_range_tmp;
1204 	}
1205 
1206 	end_freq = freq_range->end_freq_khz;
1207 
1208 	return end_freq - start_freq;
1209 }
1210 
reg_get_max_bandwidth(const struct ieee80211_regdomain * rd,const struct ieee80211_reg_rule * rule)1211 unsigned int reg_get_max_bandwidth(const struct ieee80211_regdomain *rd,
1212 				   const struct ieee80211_reg_rule *rule)
1213 {
1214 	unsigned int bw = reg_get_max_bandwidth_from_range(rd, rule);
1215 
1216 	if (rule->flags & NL80211_RRF_NO_320MHZ)
1217 		bw = min_t(unsigned int, bw, MHZ_TO_KHZ(160));
1218 	if (rule->flags & NL80211_RRF_NO_160MHZ)
1219 		bw = min_t(unsigned int, bw, MHZ_TO_KHZ(80));
1220 	if (rule->flags & NL80211_RRF_NO_80MHZ)
1221 		bw = min_t(unsigned int, bw, MHZ_TO_KHZ(40));
1222 
1223 	/*
1224 	 * HT40+/HT40- limits are handled per-channel. Only limit BW if both
1225 	 * are not allowed.
1226 	 */
1227 	if (rule->flags & NL80211_RRF_NO_HT40MINUS &&
1228 	    rule->flags & NL80211_RRF_NO_HT40PLUS)
1229 		bw = min_t(unsigned int, bw, MHZ_TO_KHZ(20));
1230 
1231 	return bw;
1232 }
1233 
1234 /* Sanity check on a regulatory rule */
is_valid_reg_rule(const struct ieee80211_reg_rule * rule)1235 static bool is_valid_reg_rule(const struct ieee80211_reg_rule *rule)
1236 {
1237 	const struct ieee80211_freq_range *freq_range = &rule->freq_range;
1238 	u32 freq_diff;
1239 
1240 	if (freq_range->start_freq_khz <= 0 || freq_range->end_freq_khz <= 0)
1241 		return false;
1242 
1243 	if (freq_range->start_freq_khz > freq_range->end_freq_khz)
1244 		return false;
1245 
1246 	freq_diff = freq_range->end_freq_khz - freq_range->start_freq_khz;
1247 
1248 	if (freq_range->end_freq_khz <= freq_range->start_freq_khz ||
1249 	    freq_range->max_bandwidth_khz > freq_diff)
1250 		return false;
1251 
1252 	return true;
1253 }
1254 
is_valid_rd(const struct ieee80211_regdomain * rd)1255 static bool is_valid_rd(const struct ieee80211_regdomain *rd)
1256 {
1257 	const struct ieee80211_reg_rule *reg_rule = NULL;
1258 	unsigned int i;
1259 
1260 	if (!rd->n_reg_rules)
1261 		return false;
1262 
1263 	if (WARN_ON(rd->n_reg_rules > NL80211_MAX_SUPP_REG_RULES))
1264 		return false;
1265 
1266 	for (i = 0; i < rd->n_reg_rules; i++) {
1267 		reg_rule = &rd->reg_rules[i];
1268 		if (!is_valid_reg_rule(reg_rule))
1269 			return false;
1270 	}
1271 
1272 	return true;
1273 }
1274 
1275 /**
1276  * freq_in_rule_band - tells us if a frequency is in a frequency band
1277  * @freq_range: frequency rule we want to query
1278  * @freq_khz: frequency we are inquiring about
1279  *
1280  * This lets us know if a specific frequency rule is or is not relevant to
1281  * a specific frequency's band. Bands are device specific and artificial
1282  * definitions (the "2.4 GHz band", the "5 GHz band" and the "60GHz band"),
1283  * however it is safe for now to assume that a frequency rule should not be
1284  * part of a frequency's band if the start freq or end freq are off by more
1285  * than 2 GHz for the 2.4 and 5 GHz bands, and by more than 20 GHz for the
1286  * 60 GHz band.
1287  * This resolution can be lowered and should be considered as we add
1288  * regulatory rule support for other "bands".
1289  *
1290  * Returns: whether or not the frequency is in the range
1291  */
freq_in_rule_band(const struct ieee80211_freq_range * freq_range,u32 freq_khz)1292 static bool freq_in_rule_band(const struct ieee80211_freq_range *freq_range,
1293 			      u32 freq_khz)
1294 {
1295 	/*
1296 	 * From 802.11ad: directional multi-gigabit (DMG):
1297 	 * Pertaining to operation in a frequency band containing a channel
1298 	 * with the Channel starting frequency above 45 GHz.
1299 	 */
1300 	u32 limit = freq_khz > 45 * KHZ_PER_GHZ ? 20 * KHZ_PER_GHZ : 2 * KHZ_PER_GHZ;
1301 	if (abs(freq_khz - freq_range->start_freq_khz) <= limit)
1302 		return true;
1303 	if (abs(freq_khz - freq_range->end_freq_khz) <= limit)
1304 		return true;
1305 	return false;
1306 }
1307 
1308 /*
1309  * Later on we can perhaps use the more restrictive DFS
1310  * region but we don't have information for that yet so
1311  * for now simply disallow conflicts.
1312  */
1313 static enum nl80211_dfs_regions
reg_intersect_dfs_region(const enum nl80211_dfs_regions dfs_region1,const enum nl80211_dfs_regions dfs_region2)1314 reg_intersect_dfs_region(const enum nl80211_dfs_regions dfs_region1,
1315 			 const enum nl80211_dfs_regions dfs_region2)
1316 {
1317 	if (dfs_region1 != dfs_region2)
1318 		return NL80211_DFS_UNSET;
1319 	return dfs_region1;
1320 }
1321 
reg_wmm_rules_intersect(const struct ieee80211_wmm_ac * wmm_ac1,const struct ieee80211_wmm_ac * wmm_ac2,struct ieee80211_wmm_ac * intersect)1322 static void reg_wmm_rules_intersect(const struct ieee80211_wmm_ac *wmm_ac1,
1323 				    const struct ieee80211_wmm_ac *wmm_ac2,
1324 				    struct ieee80211_wmm_ac *intersect)
1325 {
1326 	intersect->cw_min = max_t(u16, wmm_ac1->cw_min, wmm_ac2->cw_min);
1327 	intersect->cw_max = max_t(u16, wmm_ac1->cw_max, wmm_ac2->cw_max);
1328 	intersect->cot = min_t(u16, wmm_ac1->cot, wmm_ac2->cot);
1329 	intersect->aifsn = max_t(u8, wmm_ac1->aifsn, wmm_ac2->aifsn);
1330 }
1331 
1332 /*
1333  * Helper for regdom_intersect(), this does the real
1334  * mathematical intersection fun
1335  */
reg_rules_intersect(const struct ieee80211_regdomain * rd1,const struct ieee80211_regdomain * rd2,const struct ieee80211_reg_rule * rule1,const struct ieee80211_reg_rule * rule2,struct ieee80211_reg_rule * intersected_rule)1336 static int reg_rules_intersect(const struct ieee80211_regdomain *rd1,
1337 			       const struct ieee80211_regdomain *rd2,
1338 			       const struct ieee80211_reg_rule *rule1,
1339 			       const struct ieee80211_reg_rule *rule2,
1340 			       struct ieee80211_reg_rule *intersected_rule)
1341 {
1342 	const struct ieee80211_freq_range *freq_range1, *freq_range2;
1343 	struct ieee80211_freq_range *freq_range;
1344 	const struct ieee80211_power_rule *power_rule1, *power_rule2;
1345 	struct ieee80211_power_rule *power_rule;
1346 	const struct ieee80211_wmm_rule *wmm_rule1, *wmm_rule2;
1347 	struct ieee80211_wmm_rule *wmm_rule;
1348 	u32 freq_diff, max_bandwidth1, max_bandwidth2;
1349 
1350 	freq_range1 = &rule1->freq_range;
1351 	freq_range2 = &rule2->freq_range;
1352 	freq_range = &intersected_rule->freq_range;
1353 
1354 	power_rule1 = &rule1->power_rule;
1355 	power_rule2 = &rule2->power_rule;
1356 	power_rule = &intersected_rule->power_rule;
1357 
1358 	wmm_rule1 = &rule1->wmm_rule;
1359 	wmm_rule2 = &rule2->wmm_rule;
1360 	wmm_rule = &intersected_rule->wmm_rule;
1361 
1362 	freq_range->start_freq_khz = max(freq_range1->start_freq_khz,
1363 					 freq_range2->start_freq_khz);
1364 	freq_range->end_freq_khz = min(freq_range1->end_freq_khz,
1365 				       freq_range2->end_freq_khz);
1366 
1367 	max_bandwidth1 = freq_range1->max_bandwidth_khz;
1368 	max_bandwidth2 = freq_range2->max_bandwidth_khz;
1369 
1370 	if (rule1->flags & NL80211_RRF_AUTO_BW)
1371 		max_bandwidth1 = reg_get_max_bandwidth(rd1, rule1);
1372 	if (rule2->flags & NL80211_RRF_AUTO_BW)
1373 		max_bandwidth2 = reg_get_max_bandwidth(rd2, rule2);
1374 
1375 	freq_range->max_bandwidth_khz = min(max_bandwidth1, max_bandwidth2);
1376 
1377 	intersected_rule->flags = rule1->flags | rule2->flags;
1378 
1379 	/*
1380 	 * In case NL80211_RRF_AUTO_BW requested for both rules
1381 	 * set AUTO_BW in intersected rule also. Next we will
1382 	 * calculate BW correctly in handle_channel function.
1383 	 * In other case remove AUTO_BW flag while we calculate
1384 	 * maximum bandwidth correctly and auto calculation is
1385 	 * not required.
1386 	 */
1387 	if ((rule1->flags & NL80211_RRF_AUTO_BW) &&
1388 	    (rule2->flags & NL80211_RRF_AUTO_BW))
1389 		intersected_rule->flags |= NL80211_RRF_AUTO_BW;
1390 	else
1391 		intersected_rule->flags &= ~NL80211_RRF_AUTO_BW;
1392 
1393 	freq_diff = freq_range->end_freq_khz - freq_range->start_freq_khz;
1394 	if (freq_range->max_bandwidth_khz > freq_diff)
1395 		freq_range->max_bandwidth_khz = freq_diff;
1396 
1397 	power_rule->max_eirp = min(power_rule1->max_eirp,
1398 		power_rule2->max_eirp);
1399 	power_rule->max_antenna_gain = min(power_rule1->max_antenna_gain,
1400 		power_rule2->max_antenna_gain);
1401 
1402 	intersected_rule->dfs_cac_ms = max(rule1->dfs_cac_ms,
1403 					   rule2->dfs_cac_ms);
1404 
1405 	if (rule1->has_wmm && rule2->has_wmm) {
1406 		u8 ac;
1407 
1408 		for (ac = 0; ac < IEEE80211_NUM_ACS; ac++) {
1409 			reg_wmm_rules_intersect(&wmm_rule1->client[ac],
1410 						&wmm_rule2->client[ac],
1411 						&wmm_rule->client[ac]);
1412 			reg_wmm_rules_intersect(&wmm_rule1->ap[ac],
1413 						&wmm_rule2->ap[ac],
1414 						&wmm_rule->ap[ac]);
1415 		}
1416 
1417 		intersected_rule->has_wmm = true;
1418 	} else if (rule1->has_wmm) {
1419 		*wmm_rule = *wmm_rule1;
1420 		intersected_rule->has_wmm = true;
1421 	} else if (rule2->has_wmm) {
1422 		*wmm_rule = *wmm_rule2;
1423 		intersected_rule->has_wmm = true;
1424 	} else {
1425 		intersected_rule->has_wmm = false;
1426 	}
1427 
1428 	if (!is_valid_reg_rule(intersected_rule))
1429 		return -EINVAL;
1430 
1431 	return 0;
1432 }
1433 
1434 /* check whether old rule contains new rule */
rule_contains(struct ieee80211_reg_rule * r1,struct ieee80211_reg_rule * r2)1435 static bool rule_contains(struct ieee80211_reg_rule *r1,
1436 			  struct ieee80211_reg_rule *r2)
1437 {
1438 	/* for simplicity, currently consider only same flags */
1439 	if (r1->flags != r2->flags)
1440 		return false;
1441 
1442 	/* verify r1 is more restrictive */
1443 	if ((r1->power_rule.max_antenna_gain >
1444 	     r2->power_rule.max_antenna_gain) ||
1445 	    r1->power_rule.max_eirp > r2->power_rule.max_eirp)
1446 		return false;
1447 
1448 	/* make sure r2's range is contained within r1 */
1449 	if (r1->freq_range.start_freq_khz > r2->freq_range.start_freq_khz ||
1450 	    r1->freq_range.end_freq_khz < r2->freq_range.end_freq_khz)
1451 		return false;
1452 
1453 	/* and finally verify that r1.max_bw >= r2.max_bw */
1454 	if (r1->freq_range.max_bandwidth_khz <
1455 	    r2->freq_range.max_bandwidth_khz)
1456 		return false;
1457 
1458 	return true;
1459 }
1460 
1461 /* add or extend current rules. do nothing if rule is already contained */
add_rule(struct ieee80211_reg_rule * rule,struct ieee80211_reg_rule * reg_rules,u32 * n_rules)1462 static void add_rule(struct ieee80211_reg_rule *rule,
1463 		     struct ieee80211_reg_rule *reg_rules, u32 *n_rules)
1464 {
1465 	struct ieee80211_reg_rule *tmp_rule;
1466 	int i;
1467 
1468 	for (i = 0; i < *n_rules; i++) {
1469 		tmp_rule = ®_rules[i];
1470 		/* rule is already contained - do nothing */
1471 		if (rule_contains(tmp_rule, rule))
1472 			return;
1473 
1474 		/* extend rule if possible */
1475 		if (rule_contains(rule, tmp_rule)) {
1476 			memcpy(tmp_rule, rule, sizeof(*rule));
1477 			return;
1478 		}
1479 	}
1480 
1481 	memcpy(®_rules[*n_rules], rule, sizeof(*rule));
1482 	(*n_rules)++;
1483 }
1484 
1485 /**
1486  * regdom_intersect - do the intersection between two regulatory domains
1487  * @rd1: first regulatory domain
1488  * @rd2: second regulatory domain
1489  *
1490  * Use this function to get the intersection between two regulatory domains.
1491  * Once completed we will mark the alpha2 for the rd as intersected, "98",
1492  * as no one single alpha2 can represent this regulatory domain.
1493  *
1494  * Returns a pointer to the regulatory domain structure which will hold the
1495  * resulting intersection of rules between rd1 and rd2. We will
1496  * kzalloc() this structure for you.
1497  *
1498  * Returns: the intersected regdomain
1499  */
1500 static struct ieee80211_regdomain *
regdom_intersect(const struct ieee80211_regdomain * rd1,const struct ieee80211_regdomain * rd2)1501 regdom_intersect(const struct ieee80211_regdomain *rd1,
1502 		 const struct ieee80211_regdomain *rd2)
1503 {
1504 	int r;
1505 	unsigned int x, y;
1506 	unsigned int num_rules = 0;
1507 	const struct ieee80211_reg_rule *rule1, *rule2;
1508 	struct ieee80211_reg_rule intersected_rule;
1509 	struct ieee80211_regdomain *rd;
1510 
1511 	if (!rd1 || !rd2)
1512 		return NULL;
1513 
1514 	/*
1515 	 * First we get a count of the rules we'll need, then we actually
1516 	 * build them. This is to so we can malloc() and free() a
1517 	 * regdomain once. The reason we use reg_rules_intersect() here
1518 	 * is it will return -EINVAL if the rule computed makes no sense.
1519 	 * All rules that do check out OK are valid.
1520 	 */
1521 
1522 	for (x = 0; x < rd1->n_reg_rules; x++) {
1523 		rule1 = &rd1->reg_rules[x];
1524 		for (y = 0; y < rd2->n_reg_rules; y++) {
1525 			rule2 = &rd2->reg_rules[y];
1526 			if (!reg_rules_intersect(rd1, rd2, rule1, rule2,
1527 						 &intersected_rule))
1528 				num_rules++;
1529 		}
1530 	}
1531 
1532 	if (!num_rules)
1533 		return NULL;
1534 
1535 	rd = kzalloc(struct_size(rd, reg_rules, num_rules), GFP_KERNEL);
1536 	if (!rd)
1537 		return NULL;
1538 
1539 	for (x = 0; x < rd1->n_reg_rules; x++) {
1540 		rule1 = &rd1->reg_rules[x];
1541 		for (y = 0; y < rd2->n_reg_rules; y++) {
1542 			rule2 = &rd2->reg_rules[y];
1543 			r = reg_rules_intersect(rd1, rd2, rule1, rule2,
1544 						&intersected_rule);
1545 			/*
1546 			 * No need to memset here the intersected rule here as
1547 			 * we're not using the stack anymore
1548 			 */
1549 			if (r)
1550 				continue;
1551 
1552 			add_rule(&intersected_rule, rd->reg_rules,
1553 				 &rd->n_reg_rules);
1554 		}
1555 	}
1556 
1557 	rd->alpha2[0] = '9';
1558 	rd->alpha2[1] = '8';
1559 	rd->dfs_region = reg_intersect_dfs_region(rd1->dfs_region,
1560 						  rd2->dfs_region);
1561 
1562 	return rd;
1563 }
1564 
1565 /*
1566  * XXX: add support for the rest of enum nl80211_reg_rule_flags, we may
1567  * want to just have the channel structure use these
1568  */
map_regdom_flags(u32 rd_flags)1569 static u32 map_regdom_flags(u32 rd_flags)
1570 {
1571 	u32 channel_flags = 0;
1572 	if (rd_flags & NL80211_RRF_NO_IR_ALL)
1573 		channel_flags |= IEEE80211_CHAN_NO_IR;
1574 	if (rd_flags & NL80211_RRF_DFS)
1575 		channel_flags |= IEEE80211_CHAN_RADAR;
1576 	if (rd_flags & NL80211_RRF_NO_OFDM)
1577 		channel_flags |= IEEE80211_CHAN_NO_OFDM;
1578 	if (rd_flags & NL80211_RRF_NO_OUTDOOR)
1579 		channel_flags |= IEEE80211_CHAN_INDOOR_ONLY;
1580 	if (rd_flags & NL80211_RRF_IR_CONCURRENT)
1581 		channel_flags |= IEEE80211_CHAN_IR_CONCURRENT;
1582 	if (rd_flags & NL80211_RRF_NO_HT40MINUS)
1583 		channel_flags |= IEEE80211_CHAN_NO_HT40MINUS;
1584 	if (rd_flags & NL80211_RRF_NO_HT40PLUS)
1585 		channel_flags |= IEEE80211_CHAN_NO_HT40PLUS;
1586 	if (rd_flags & NL80211_RRF_NO_80MHZ)
1587 		channel_flags |= IEEE80211_CHAN_NO_80MHZ;
1588 	if (rd_flags & NL80211_RRF_NO_160MHZ)
1589 		channel_flags |= IEEE80211_CHAN_NO_160MHZ;
1590 	if (rd_flags & NL80211_RRF_NO_HE)
1591 		channel_flags |= IEEE80211_CHAN_NO_HE;
1592 	if (rd_flags & NL80211_RRF_NO_320MHZ)
1593 		channel_flags |= IEEE80211_CHAN_NO_320MHZ;
1594 	if (rd_flags & NL80211_RRF_NO_EHT)
1595 		channel_flags |= IEEE80211_CHAN_NO_EHT;
1596 	if (rd_flags & NL80211_RRF_DFS_CONCURRENT)
1597 		channel_flags |= IEEE80211_CHAN_DFS_CONCURRENT;
1598 	if (rd_flags & NL80211_RRF_NO_6GHZ_VLP_CLIENT)
1599 		channel_flags |= IEEE80211_CHAN_NO_6GHZ_VLP_CLIENT;
1600 	if (rd_flags & NL80211_RRF_NO_6GHZ_AFC_CLIENT)
1601 		channel_flags |= IEEE80211_CHAN_NO_6GHZ_AFC_CLIENT;
1602 	if (rd_flags & NL80211_RRF_PSD)
1603 		channel_flags |= IEEE80211_CHAN_PSD;
1604 	if (rd_flags & NL80211_RRF_ALLOW_6GHZ_VLP_AP)
1605 		channel_flags |= IEEE80211_CHAN_ALLOW_6GHZ_VLP_AP;
1606 	if (rd_flags & NL80211_RRF_ALLOW_20MHZ_ACTIVITY)
1607 		channel_flags |= IEEE80211_CHAN_ALLOW_20MHZ_ACTIVITY;
1608 	return channel_flags;
1609 }
1610 
1611 static const struct ieee80211_reg_rule *
freq_reg_info_regd(u32 center_freq,const struct ieee80211_regdomain * regd,u32 bw)1612 freq_reg_info_regd(u32 center_freq,
1613 		   const struct ieee80211_regdomain *regd, u32 bw)
1614 {
1615 	int i;
1616 	bool band_rule_found = false;
1617 	bool bw_fits = false;
1618 
1619 	if (!regd)
1620 		return ERR_PTR(-EINVAL);
1621 
1622 	for (i = 0; i < regd->n_reg_rules; i++) {
1623 		const struct ieee80211_reg_rule *rr;
1624 		const struct ieee80211_freq_range *fr = NULL;
1625 
1626 		rr = ®d->reg_rules[i];
1627 		fr = &rr->freq_range;
1628 
1629 		/*
1630 		 * We only need to know if one frequency rule was
1631 		 * in center_freq's band, that's enough, so let's
1632 		 * not overwrite it once found
1633 		 */
1634 		if (!band_rule_found)
1635 			band_rule_found = freq_in_rule_band(fr, center_freq);
1636 
1637 		bw_fits = cfg80211_does_bw_fit_range(fr, center_freq, bw);
1638 
1639 		if (band_rule_found && bw_fits)
1640 			return rr;
1641 	}
1642 
1643 	if (!band_rule_found)
1644 		return ERR_PTR(-ERANGE);
1645 
1646 	return ERR_PTR(-EINVAL);
1647 }
1648 
1649 static const struct ieee80211_reg_rule *
__freq_reg_info(struct wiphy * wiphy,u32 center_freq,u32 min_bw)1650 __freq_reg_info(struct wiphy *wiphy, u32 center_freq, u32 min_bw)
1651 {
1652 	const struct ieee80211_regdomain *regd = reg_get_regdomain(wiphy);
1653 	static const u32 bws[] = {0, 1, 2, 4, 5, 8, 10, 16, 20};
1654 	const struct ieee80211_reg_rule *reg_rule = ERR_PTR(-ERANGE);
1655 	int i = ARRAY_SIZE(bws) - 1;
1656 	u32 bw;
1657 
1658 	for (bw = MHZ_TO_KHZ(bws[i]); bw >= min_bw; bw = MHZ_TO_KHZ(bws[i--])) {
1659 		reg_rule = freq_reg_info_regd(center_freq, regd, bw);
1660 		if (!IS_ERR(reg_rule))
1661 			return reg_rule;
1662 	}
1663 
1664 	return reg_rule;
1665 }
1666 
freq_reg_info(struct wiphy * wiphy,u32 center_freq)1667 const struct ieee80211_reg_rule *freq_reg_info(struct wiphy *wiphy,
1668 					       u32 center_freq)
1669 {
1670 	u32 min_bw = center_freq < MHZ_TO_KHZ(1000) ? 1 : 20;
1671 
1672 	return __freq_reg_info(wiphy, center_freq, MHZ_TO_KHZ(min_bw));
1673 }
1674 EXPORT_SYMBOL(freq_reg_info);
1675 
reg_initiator_name(enum nl80211_reg_initiator initiator)1676 const char *reg_initiator_name(enum nl80211_reg_initiator initiator)
1677 {
1678 	switch (initiator) {
1679 	case NL80211_REGDOM_SET_BY_CORE:
1680 		return "core";
1681 	case NL80211_REGDOM_SET_BY_USER:
1682 		return "user";
1683 	case NL80211_REGDOM_SET_BY_DRIVER:
1684 		return "driver";
1685 	case NL80211_REGDOM_SET_BY_COUNTRY_IE:
1686 		return "country element";
1687 	default:
1688 		WARN_ON(1);
1689 		return "bug";
1690 	}
1691 }
1692 EXPORT_SYMBOL(reg_initiator_name);
1693 
reg_rule_to_chan_bw_flags(const struct ieee80211_regdomain * regd,const struct ieee80211_reg_rule * reg_rule,const struct ieee80211_channel * chan)1694 static uint32_t reg_rule_to_chan_bw_flags(const struct ieee80211_regdomain *regd,
1695 					  const struct ieee80211_reg_rule *reg_rule,
1696 					  const struct ieee80211_channel *chan)
1697 {
1698 	const struct ieee80211_freq_range *freq_range = NULL;
1699 	u32 max_bandwidth_khz, center_freq_khz, bw_flags = 0;
1700 	bool is_s1g = chan->band == NL80211_BAND_S1GHZ;
1701 
1702 	freq_range = ®_rule->freq_range;
1703 
1704 	max_bandwidth_khz = freq_range->max_bandwidth_khz;
1705 	center_freq_khz = ieee80211_channel_to_khz(chan);
1706 	/* Check if auto calculation requested */
1707 	if (reg_rule->flags & NL80211_RRF_AUTO_BW)
1708 		max_bandwidth_khz = reg_get_max_bandwidth(regd, reg_rule);
1709 
1710 	/* If we get a reg_rule we can assume that at least 5Mhz fit */
1711 	if (!cfg80211_does_bw_fit_range(freq_range,
1712 					center_freq_khz,
1713 					MHZ_TO_KHZ(10)))
1714 		bw_flags |= IEEE80211_CHAN_NO_10MHZ;
1715 	if (!cfg80211_does_bw_fit_range(freq_range,
1716 					center_freq_khz,
1717 					MHZ_TO_KHZ(20)))
1718 		bw_flags |= IEEE80211_CHAN_NO_20MHZ;
1719 
1720 	if (is_s1g) {
1721 		/* S1G is strict about non overlapping channels. We can
1722 		 * calculate which bandwidth is allowed per channel by finding
1723 		 * the largest bandwidth which cleanly divides the freq_range.
1724 		 */
1725 		int edge_offset;
1726 		int ch_bw = max_bandwidth_khz;
1727 
1728 		while (ch_bw) {
1729 			edge_offset = (center_freq_khz - ch_bw / 2) -
1730 				      freq_range->start_freq_khz;
1731 			if (edge_offset % ch_bw == 0) {
1732 				switch (KHZ_TO_MHZ(ch_bw)) {
1733 				case 1:
1734 					bw_flags |= IEEE80211_CHAN_1MHZ;
1735 					break;
1736 				case 2:
1737 					bw_flags |= IEEE80211_CHAN_2MHZ;
1738 					break;
1739 				case 4:
1740 					bw_flags |= IEEE80211_CHAN_4MHZ;
1741 					break;
1742 				case 8:
1743 					bw_flags |= IEEE80211_CHAN_8MHZ;
1744 					break;
1745 				case 16:
1746 					bw_flags |= IEEE80211_CHAN_16MHZ;
1747 					break;
1748 				default:
1749 					/* If we got here, no bandwidths fit on
1750 					 * this frequency, ie. band edge.
1751 					 */
1752 					bw_flags |= IEEE80211_CHAN_DISABLED;
1753 					break;
1754 				}
1755 				break;
1756 			}
1757 			ch_bw /= 2;
1758 		}
1759 	} else {
1760 		if (max_bandwidth_khz < MHZ_TO_KHZ(10))
1761 			bw_flags |= IEEE80211_CHAN_NO_10MHZ;
1762 		if (max_bandwidth_khz < MHZ_TO_KHZ(20))
1763 			bw_flags |= IEEE80211_CHAN_NO_20MHZ;
1764 		if (max_bandwidth_khz < MHZ_TO_KHZ(40))
1765 			bw_flags |= IEEE80211_CHAN_NO_HT40;
1766 		if (max_bandwidth_khz < MHZ_TO_KHZ(80))
1767 			bw_flags |= IEEE80211_CHAN_NO_80MHZ;
1768 		if (max_bandwidth_khz < MHZ_TO_KHZ(160))
1769 			bw_flags |= IEEE80211_CHAN_NO_160MHZ;
1770 		if (max_bandwidth_khz < MHZ_TO_KHZ(320))
1771 			bw_flags |= IEEE80211_CHAN_NO_320MHZ;
1772 	}
1773 	return bw_flags;
1774 }
1775 
handle_channel_single_rule(struct wiphy * wiphy,enum nl80211_reg_initiator initiator,struct ieee80211_channel * chan,u32 flags,struct regulatory_request * lr,struct wiphy * request_wiphy,const struct ieee80211_reg_rule * reg_rule)1776 static void handle_channel_single_rule(struct wiphy *wiphy,
1777 				       enum nl80211_reg_initiator initiator,
1778 				       struct ieee80211_channel *chan,
1779 				       u32 flags,
1780 				       struct regulatory_request *lr,
1781 				       struct wiphy *request_wiphy,
1782 				       const struct ieee80211_reg_rule *reg_rule)
1783 {
1784 	u32 bw_flags = 0;
1785 	const struct ieee80211_power_rule *power_rule = NULL;
1786 	const struct ieee80211_regdomain *regd;
1787 
1788 	regd = reg_get_regdomain(wiphy);
1789 
1790 	power_rule = ®_rule->power_rule;
1791 	bw_flags = reg_rule_to_chan_bw_flags(regd, reg_rule, chan);
1792 
1793 	if (lr->initiator == NL80211_REGDOM_SET_BY_DRIVER &&
1794 	    request_wiphy && request_wiphy == wiphy &&
1795 	    request_wiphy->regulatory_flags & REGULATORY_STRICT_REG) {
1796 		/*
1797 		 * This guarantees the driver's requested regulatory domain
1798 		 * will always be used as a base for further regulatory
1799 		 * settings
1800 		 */
1801 		chan->flags = chan->orig_flags =
1802 			map_regdom_flags(reg_rule->flags) | bw_flags;
1803 		chan->max_antenna_gain = chan->orig_mag =
1804 			(int) MBI_TO_DBI(power_rule->max_antenna_gain);
1805 		chan->max_reg_power = chan->max_power = chan->orig_mpwr =
1806 			(int) MBM_TO_DBM(power_rule->max_eirp);
1807 
1808 		if (chan->flags & IEEE80211_CHAN_RADAR) {
1809 			chan->dfs_cac_ms = IEEE80211_DFS_MIN_CAC_TIME_MS;
1810 			if (reg_rule->dfs_cac_ms)
1811 				chan->dfs_cac_ms = reg_rule->dfs_cac_ms;
1812 		}
1813 
1814 		if (chan->flags & IEEE80211_CHAN_PSD)
1815 			chan->psd = reg_rule->psd;
1816 
1817 		return;
1818 	}
1819 
1820 	chan->dfs_state = NL80211_DFS_USABLE;
1821 	chan->dfs_state_entered = jiffies;
1822 
1823 	chan->beacon_found = false;
1824 	chan->flags = flags | bw_flags | map_regdom_flags(reg_rule->flags);
1825 	chan->max_antenna_gain =
1826 		min_t(int, chan->orig_mag,
1827 		      MBI_TO_DBI(power_rule->max_antenna_gain));
1828 	chan->max_reg_power = (int) MBM_TO_DBM(power_rule->max_eirp);
1829 
1830 	if (chan->flags & IEEE80211_CHAN_RADAR) {
1831 		if (reg_rule->dfs_cac_ms)
1832 			chan->dfs_cac_ms = reg_rule->dfs_cac_ms;
1833 		else
1834 			chan->dfs_cac_ms = IEEE80211_DFS_MIN_CAC_TIME_MS;
1835 	}
1836 
1837 	if (chan->flags & IEEE80211_CHAN_PSD)
1838 		chan->psd = reg_rule->psd;
1839 
1840 	if (chan->orig_mpwr) {
1841 		/*
1842 		 * Devices that use REGULATORY_COUNTRY_IE_FOLLOW_POWER
1843 		 * will always follow the passed country IE power settings.
1844 		 */
1845 		if (initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE &&
1846 		    wiphy->regulatory_flags & REGULATORY_COUNTRY_IE_FOLLOW_POWER)
1847 			chan->max_power = chan->max_reg_power;
1848 		else
1849 			chan->max_power = min(chan->orig_mpwr,
1850 					      chan->max_reg_power);
1851 	} else
1852 		chan->max_power = chan->max_reg_power;
1853 }
1854 
handle_channel_adjacent_rules(struct wiphy * wiphy,enum nl80211_reg_initiator initiator,struct ieee80211_channel * chan,u32 flags,struct regulatory_request * lr,struct wiphy * request_wiphy,const struct ieee80211_reg_rule * rrule1,const struct ieee80211_reg_rule * rrule2,struct ieee80211_freq_range * comb_range)1855 static void handle_channel_adjacent_rules(struct wiphy *wiphy,
1856 					  enum nl80211_reg_initiator initiator,
1857 					  struct ieee80211_channel *chan,
1858 					  u32 flags,
1859 					  struct regulatory_request *lr,
1860 					  struct wiphy *request_wiphy,
1861 					  const struct ieee80211_reg_rule *rrule1,
1862 					  const struct ieee80211_reg_rule *rrule2,
1863 					  struct ieee80211_freq_range *comb_range)
1864 {
1865 	u32 bw_flags1 = 0;
1866 	u32 bw_flags2 = 0;
1867 	const struct ieee80211_power_rule *power_rule1 = NULL;
1868 	const struct ieee80211_power_rule *power_rule2 = NULL;
1869 	const struct ieee80211_regdomain *regd;
1870 
1871 	regd = reg_get_regdomain(wiphy);
1872 
1873 	power_rule1 = &rrule1->power_rule;
1874 	power_rule2 = &rrule2->power_rule;
1875 	bw_flags1 = reg_rule_to_chan_bw_flags(regd, rrule1, chan);
1876 	bw_flags2 = reg_rule_to_chan_bw_flags(regd, rrule2, chan);
1877 
1878 	if (lr->initiator == NL80211_REGDOM_SET_BY_DRIVER &&
1879 	    request_wiphy && request_wiphy == wiphy &&
1880 	    request_wiphy->regulatory_flags & REGULATORY_STRICT_REG) {
1881 		/* This guarantees the driver's requested regulatory domain
1882 		 * will always be used as a base for further regulatory
1883 		 * settings
1884 		 */
1885 		chan->flags =
1886 			map_regdom_flags(rrule1->flags) |
1887 			map_regdom_flags(rrule2->flags) |
1888 			bw_flags1 |
1889 			bw_flags2;
1890 		chan->orig_flags = chan->flags;
1891 		chan->max_antenna_gain =
1892 			min_t(int, MBI_TO_DBI(power_rule1->max_antenna_gain),
1893 			      MBI_TO_DBI(power_rule2->max_antenna_gain));
1894 		chan->orig_mag = chan->max_antenna_gain;
1895 		chan->max_reg_power =
1896 			min_t(int, MBM_TO_DBM(power_rule1->max_eirp),
1897 			      MBM_TO_DBM(power_rule2->max_eirp));
1898 		chan->max_power = chan->max_reg_power;
1899 		chan->orig_mpwr = chan->max_reg_power;
1900 
1901 		if (chan->flags & IEEE80211_CHAN_RADAR) {
1902 			chan->dfs_cac_ms = IEEE80211_DFS_MIN_CAC_TIME_MS;
1903 			if (rrule1->dfs_cac_ms || rrule2->dfs_cac_ms)
1904 				chan->dfs_cac_ms = max_t(unsigned int,
1905 							 rrule1->dfs_cac_ms,
1906 							 rrule2->dfs_cac_ms);
1907 		}
1908 
1909 		if ((rrule1->flags & NL80211_RRF_PSD) &&
1910 		    (rrule2->flags & NL80211_RRF_PSD))
1911 			chan->psd = min_t(s8, rrule1->psd, rrule2->psd);
1912 		else
1913 			chan->flags &= ~NL80211_RRF_PSD;
1914 
1915 		return;
1916 	}
1917 
1918 	chan->dfs_state = NL80211_DFS_USABLE;
1919 	chan->dfs_state_entered = jiffies;
1920 
1921 	chan->beacon_found = false;
1922 	chan->flags = flags | bw_flags1 | bw_flags2 |
1923 		      map_regdom_flags(rrule1->flags) |
1924 		      map_regdom_flags(rrule2->flags);
1925 
1926 	/* reg_rule_to_chan_bw_flags may forbids 10 and forbids 20 MHz
1927 	 * (otherwise no adj. rule case), recheck therefore
1928 	 */
1929 	if (cfg80211_does_bw_fit_range(comb_range,
1930 				       ieee80211_channel_to_khz(chan),
1931 				       MHZ_TO_KHZ(10)))
1932 		chan->flags &= ~IEEE80211_CHAN_NO_10MHZ;
1933 	if (cfg80211_does_bw_fit_range(comb_range,
1934 				       ieee80211_channel_to_khz(chan),
1935 				       MHZ_TO_KHZ(20)))
1936 		chan->flags &= ~IEEE80211_CHAN_NO_20MHZ;
1937 
1938 	chan->max_antenna_gain =
1939 		min_t(int, chan->orig_mag,
1940 		      min_t(int,
1941 			    MBI_TO_DBI(power_rule1->max_antenna_gain),
1942 			    MBI_TO_DBI(power_rule2->max_antenna_gain)));
1943 	chan->max_reg_power = min_t(int,
1944 				    MBM_TO_DBM(power_rule1->max_eirp),
1945 				    MBM_TO_DBM(power_rule2->max_eirp));
1946 
1947 	if (chan->flags & IEEE80211_CHAN_RADAR) {
1948 		if (rrule1->dfs_cac_ms || rrule2->dfs_cac_ms)
1949 			chan->dfs_cac_ms = max_t(unsigned int,
1950 						 rrule1->dfs_cac_ms,
1951 						 rrule2->dfs_cac_ms);
1952 		else
1953 			chan->dfs_cac_ms = IEEE80211_DFS_MIN_CAC_TIME_MS;
1954 	}
1955 
1956 	if (chan->orig_mpwr) {
1957 		/* Devices that use REGULATORY_COUNTRY_IE_FOLLOW_POWER
1958 		 * will always follow the passed country IE power settings.
1959 		 */
1960 		if (initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE &&
1961 		    wiphy->regulatory_flags & REGULATORY_COUNTRY_IE_FOLLOW_POWER)
1962 			chan->max_power = chan->max_reg_power;
1963 		else
1964 			chan->max_power = min(chan->orig_mpwr,
1965 					      chan->max_reg_power);
1966 	} else {
1967 		chan->max_power = chan->max_reg_power;
1968 	}
1969 }
1970 
1971 /* Note that right now we assume the desired channel bandwidth
1972  * is always 20 MHz for each individual channel (HT40 uses 20 MHz
1973  * per channel, the primary and the extension channel).
1974  */
handle_channel(struct wiphy * wiphy,enum nl80211_reg_initiator initiator,struct ieee80211_channel * chan)1975 static void handle_channel(struct wiphy *wiphy,
1976 			   enum nl80211_reg_initiator initiator,
1977 			   struct ieee80211_channel *chan)
1978 {
1979 	const u32 orig_chan_freq = ieee80211_channel_to_khz(chan);
1980 	struct regulatory_request *lr = get_last_request();
1981 	struct wiphy *request_wiphy = wiphy_idx_to_wiphy(lr->wiphy_idx);
1982 	const struct ieee80211_reg_rule *rrule = NULL;
1983 	const struct ieee80211_reg_rule *rrule1 = NULL;
1984 	const struct ieee80211_reg_rule *rrule2 = NULL;
1985 
1986 	u32 flags = chan->orig_flags;
1987 
1988 	rrule = freq_reg_info(wiphy, orig_chan_freq);
1989 	if (IS_ERR(rrule)) {
1990 		/* check for adjacent match, therefore get rules for
1991 		 * chan - 20 MHz and chan + 20 MHz and test
1992 		 * if reg rules are adjacent
1993 		 */
1994 		rrule1 = freq_reg_info(wiphy,
1995 				       orig_chan_freq - MHZ_TO_KHZ(20));
1996 		rrule2 = freq_reg_info(wiphy,
1997 				       orig_chan_freq + MHZ_TO_KHZ(20));
1998 		if (!IS_ERR(rrule1) && !IS_ERR(rrule2)) {
1999 			struct ieee80211_freq_range comb_range;
2000 
2001 			if (rrule1->freq_range.end_freq_khz !=
2002 			    rrule2->freq_range.start_freq_khz)
2003 				goto disable_chan;
2004 
2005 			comb_range.start_freq_khz =
2006 				rrule1->freq_range.start_freq_khz;
2007 			comb_range.end_freq_khz =
2008 				rrule2->freq_range.end_freq_khz;
2009 			comb_range.max_bandwidth_khz =
2010 				min_t(u32,
2011 				      rrule1->freq_range.max_bandwidth_khz,
2012 				      rrule2->freq_range.max_bandwidth_khz);
2013 
2014 			if (!cfg80211_does_bw_fit_range(&comb_range,
2015 							orig_chan_freq,
2016 							MHZ_TO_KHZ(20)))
2017 				goto disable_chan;
2018 
2019 			handle_channel_adjacent_rules(wiphy, initiator, chan,
2020 						      flags, lr, request_wiphy,
2021 						      rrule1, rrule2,
2022 						      &comb_range);
2023 			return;
2024 		}
2025 
2026 disable_chan:
2027 		/* We will disable all channels that do not match our
2028 		 * received regulatory rule unless the hint is coming
2029 		 * from a Country IE and the Country IE had no information
2030 		 * about a band. The IEEE 802.11 spec allows for an AP
2031 		 * to send only a subset of the regulatory rules allowed,
2032 		 * so an AP in the US that only supports 2.4 GHz may only send
2033 		 * a country IE with information for the 2.4 GHz band
2034 		 * while 5 GHz is still supported.
2035 		 */
2036 		if (initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE &&
2037 		    PTR_ERR(rrule) == -ERANGE)
2038 			return;
2039 
2040 		if (lr->initiator == NL80211_REGDOM_SET_BY_DRIVER &&
2041 		    request_wiphy && request_wiphy == wiphy &&
2042 		    request_wiphy->regulatory_flags & REGULATORY_STRICT_REG) {
2043 			pr_debug("Disabling freq %d.%03d MHz for good\n",
2044 				 chan->center_freq, chan->freq_offset);
2045 			chan->orig_flags |= IEEE80211_CHAN_DISABLED;
2046 			chan->flags = chan->orig_flags;
2047 		} else {
2048 			pr_debug("Disabling freq %d.%03d MHz\n",
2049 				 chan->center_freq, chan->freq_offset);
2050 			chan->flags |= IEEE80211_CHAN_DISABLED;
2051 		}
2052 		return;
2053 	}
2054 
2055 	handle_channel_single_rule(wiphy, initiator, chan, flags, lr,
2056 				   request_wiphy, rrule);
2057 }
2058 
handle_band(struct wiphy * wiphy,enum nl80211_reg_initiator initiator,struct ieee80211_supported_band * sband)2059 static void handle_band(struct wiphy *wiphy,
2060 			enum nl80211_reg_initiator initiator,
2061 			struct ieee80211_supported_band *sband)
2062 {
2063 	unsigned int i;
2064 
2065 	if (!sband)
2066 		return;
2067 
2068 	for (i = 0; i < sband->n_channels; i++)
2069 		handle_channel(wiphy, initiator, &sband->channels[i]);
2070 }
2071 
reg_request_cell_base(struct regulatory_request * request)2072 static bool reg_request_cell_base(struct regulatory_request *request)
2073 {
2074 	if (request->initiator != NL80211_REGDOM_SET_BY_USER)
2075 		return false;
2076 	return request->user_reg_hint_type == NL80211_USER_REG_HINT_CELL_BASE;
2077 }
2078 
reg_last_request_cell_base(void)2079 bool reg_last_request_cell_base(void)
2080 {
2081 	return reg_request_cell_base(get_last_request());
2082 }
2083 
2084 #ifdef CONFIG_CFG80211_REG_CELLULAR_HINTS
2085 /* Core specific check */
2086 static enum reg_request_treatment
reg_ignore_cell_hint(struct regulatory_request * pending_request)2087 reg_ignore_cell_hint(struct regulatory_request *pending_request)
2088 {
2089 	struct regulatory_request *lr = get_last_request();
2090 
2091 	if (!reg_num_devs_support_basehint)
2092 		return REG_REQ_IGNORE;
2093 
2094 	if (reg_request_cell_base(lr) &&
2095 	    !regdom_changes(pending_request->alpha2))
2096 		return REG_REQ_ALREADY_SET;
2097 
2098 	return REG_REQ_OK;
2099 }
2100 
2101 /* Device specific check */
reg_dev_ignore_cell_hint(struct wiphy * wiphy)2102 static bool reg_dev_ignore_cell_hint(struct wiphy *wiphy)
2103 {
2104 	return !(wiphy->features & NL80211_FEATURE_CELL_BASE_REG_HINTS);
2105 }
2106 #else
2107 static enum reg_request_treatment
reg_ignore_cell_hint(struct regulatory_request * pending_request)2108 reg_ignore_cell_hint(struct regulatory_request *pending_request)
2109 {
2110 	return REG_REQ_IGNORE;
2111 }
2112 
reg_dev_ignore_cell_hint(struct wiphy * wiphy)2113 static bool reg_dev_ignore_cell_hint(struct wiphy *wiphy)
2114 {
2115 	return true;
2116 }
2117 #endif
2118 
wiphy_strict_alpha2_regd(struct wiphy * wiphy)2119 static bool wiphy_strict_alpha2_regd(struct wiphy *wiphy)
2120 {
2121 	if (wiphy->regulatory_flags & REGULATORY_STRICT_REG &&
2122 	    !(wiphy->regulatory_flags & REGULATORY_CUSTOM_REG))
2123 		return true;
2124 	return false;
2125 }
2126 
ignore_reg_update(struct wiphy * wiphy,enum nl80211_reg_initiator initiator)2127 static bool ignore_reg_update(struct wiphy *wiphy,
2128 			      enum nl80211_reg_initiator initiator)
2129 {
2130 	struct regulatory_request *lr = get_last_request();
2131 
2132 	if (wiphy->regulatory_flags & REGULATORY_WIPHY_SELF_MANAGED)
2133 		return true;
2134 
2135 	if (!lr) {
2136 		pr_debug("Ignoring regulatory request set by %s since last_request is not set\n",
2137 			 reg_initiator_name(initiator));
2138 		return true;
2139 	}
2140 
2141 	if (initiator == NL80211_REGDOM_SET_BY_CORE &&
2142 	    wiphy->regulatory_flags & REGULATORY_CUSTOM_REG) {
2143 		pr_debug("Ignoring regulatory request set by %s since the driver uses its own custom regulatory domain\n",
2144 			 reg_initiator_name(initiator));
2145 		return true;
2146 	}
2147 
2148 	/*
2149 	 * wiphy->regd will be set once the device has its own
2150 	 * desired regulatory domain set
2151 	 */
2152 	if (wiphy_strict_alpha2_regd(wiphy) && !wiphy->regd &&
2153 	    initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE &&
2154 	    !is_world_regdom(lr->alpha2)) {
2155 		pr_debug("Ignoring regulatory request set by %s since the driver requires its own regulatory domain to be set first\n",
2156 			 reg_initiator_name(initiator));
2157 		return true;
2158 	}
2159 
2160 	if (reg_request_cell_base(lr))
2161 		return reg_dev_ignore_cell_hint(wiphy);
2162 
2163 	return false;
2164 }
2165 
reg_is_world_roaming(struct wiphy * wiphy)2166 static bool reg_is_world_roaming(struct wiphy *wiphy)
2167 {
2168 	const struct ieee80211_regdomain *cr = get_cfg80211_regdom();
2169 	const struct ieee80211_regdomain *wr = get_wiphy_regdom(wiphy);
2170 	struct regulatory_request *lr = get_last_request();
2171 
2172 	if (is_world_regdom(cr->alpha2) || (wr && is_world_regdom(wr->alpha2)))
2173 		return true;
2174 
2175 	if (lr && lr->initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE &&
2176 	    wiphy->regulatory_flags & REGULATORY_CUSTOM_REG)
2177 		return true;
2178 
2179 	return false;
2180 }
2181 
reg_call_notifier(struct wiphy * wiphy,struct regulatory_request * request)2182 static void reg_call_notifier(struct wiphy *wiphy,
2183 			      struct regulatory_request *request)
2184 {
2185 	if (wiphy->reg_notifier)
2186 		wiphy->reg_notifier(wiphy, request);
2187 }
2188 
handle_reg_beacon(struct wiphy * wiphy,unsigned int chan_idx,struct reg_beacon * reg_beacon)2189 static void handle_reg_beacon(struct wiphy *wiphy, unsigned int chan_idx,
2190 			      struct reg_beacon *reg_beacon)
2191 {
2192 	struct ieee80211_supported_band *sband;
2193 	struct ieee80211_channel *chan;
2194 	bool channel_changed = false;
2195 	struct ieee80211_channel chan_before;
2196 	struct regulatory_request *lr = get_last_request();
2197 
2198 	sband = wiphy->bands[reg_beacon->chan.band];
2199 	chan = &sband->channels[chan_idx];
2200 
2201 	if (likely(!ieee80211_channel_equal(chan, ®_beacon->chan)))
2202 		return;
2203 
2204 	if (chan->beacon_found)
2205 		return;
2206 
2207 	chan->beacon_found = true;
2208 
2209 	if (!reg_is_world_roaming(wiphy))
2210 		return;
2211 
2212 	if (wiphy->regulatory_flags & REGULATORY_DISABLE_BEACON_HINTS)
2213 		return;
2214 
2215 	chan_before = *chan;
2216 
2217 	if (chan->flags & IEEE80211_CHAN_NO_IR) {
2218 		chan->flags &= ~IEEE80211_CHAN_NO_IR;
2219 		channel_changed = true;
2220 	}
2221 
2222 	if (channel_changed) {
2223 		nl80211_send_beacon_hint_event(wiphy, &chan_before, chan);
2224 		if (wiphy->flags & WIPHY_FLAG_CHANNEL_CHANGE_ON_BEACON)
2225 			reg_call_notifier(wiphy, lr);
2226 	}
2227 }
2228 
2229 /*
2230  * Called when a scan on a wiphy finds a beacon on
2231  * new channel
2232  */
wiphy_update_new_beacon(struct wiphy * wiphy,struct reg_beacon * reg_beacon)2233 static void wiphy_update_new_beacon(struct wiphy *wiphy,
2234 				    struct reg_beacon *reg_beacon)
2235 {
2236 	unsigned int i;
2237 	struct ieee80211_supported_band *sband;
2238 
2239 	if (!wiphy->bands[reg_beacon->chan.band])
2240 		return;
2241 
2242 	sband = wiphy->bands[reg_beacon->chan.band];
2243 
2244 	for (i = 0; i < sband->n_channels; i++)
2245 		handle_reg_beacon(wiphy, i, reg_beacon);
2246 }
2247 
2248 /*
2249  * Called upon reg changes or a new wiphy is added
2250  */
wiphy_update_beacon_reg(struct wiphy * wiphy)2251 static void wiphy_update_beacon_reg(struct wiphy *wiphy)
2252 {
2253 	unsigned int i;
2254 	struct ieee80211_supported_band *sband;
2255 	struct reg_beacon *reg_beacon;
2256 
2257 	list_for_each_entry(reg_beacon, ®_beacon_list, list) {
2258 		if (!wiphy->bands[reg_beacon->chan.band])
2259 			continue;
2260 		sband = wiphy->bands[reg_beacon->chan.band];
2261 		for (i = 0; i < sband->n_channels; i++)
2262 			handle_reg_beacon(wiphy, i, reg_beacon);
2263 	}
2264 }
2265 
2266 /* Reap the advantages of previously found beacons */
reg_process_beacons(struct wiphy * wiphy)2267 static void reg_process_beacons(struct wiphy *wiphy)
2268 {
2269 	/*
2270 	 * Means we are just firing up cfg80211, so no beacons would
2271 	 * have been processed yet.
2272 	 */
2273 	if (!last_request)
2274 		return;
2275 	wiphy_update_beacon_reg(wiphy);
2276 }
2277 
is_ht40_allowed(struct ieee80211_channel * chan)2278 static bool is_ht40_allowed(struct ieee80211_channel *chan)
2279 {
2280 	if (!chan)
2281 		return false;
2282 	if (chan->flags & IEEE80211_CHAN_DISABLED)
2283 		return false;
2284 	/* This would happen when regulatory rules disallow HT40 completely */
2285 	if ((chan->flags & IEEE80211_CHAN_NO_HT40) == IEEE80211_CHAN_NO_HT40)
2286 		return false;
2287 	return true;
2288 }
2289 
reg_process_ht_flags_channel(struct wiphy * wiphy,struct ieee80211_channel * channel)2290 static void reg_process_ht_flags_channel(struct wiphy *wiphy,
2291 					 struct ieee80211_channel *channel)
2292 {
2293 	struct ieee80211_supported_band *sband = wiphy->bands[channel->band];
2294 	struct ieee80211_channel *channel_before = NULL, *channel_after = NULL;
2295 	const struct ieee80211_regdomain *regd;
2296 	unsigned int i;
2297 	u32 flags;
2298 
2299 	if (!is_ht40_allowed(channel)) {
2300 		channel->flags |= IEEE80211_CHAN_NO_HT40;
2301 		return;
2302 	}
2303 
2304 	/*
2305 	 * We need to ensure the extension channels exist to
2306 	 * be able to use HT40- or HT40+, this finds them (or not)
2307 	 */
2308 	for (i = 0; i < sband->n_channels; i++) {
2309 		struct ieee80211_channel *c = &sband->channels[i];
2310 
2311 		if (c->center_freq == (channel->center_freq - 20))
2312 			channel_before = c;
2313 		if (c->center_freq == (channel->center_freq + 20))
2314 			channel_after = c;
2315 	}
2316 
2317 	flags = 0;
2318 	regd = get_wiphy_regdom(wiphy);
2319 	if (regd) {
2320 		const struct ieee80211_reg_rule *reg_rule =
2321 			freq_reg_info_regd(MHZ_TO_KHZ(channel->center_freq),
2322 					   regd, MHZ_TO_KHZ(20));
2323 
2324 		if (!IS_ERR(reg_rule))
2325 			flags = reg_rule->flags;
2326 	}
2327 
2328 	/*
2329 	 * Please note that this assumes target bandwidth is 20 MHz,
2330 	 * if that ever changes we also need to change the below logic
2331 	 * to include that as well.
2332 	 */
2333 	if (!is_ht40_allowed(channel_before) ||
2334 	    flags & NL80211_RRF_NO_HT40MINUS)
2335 		channel->flags |= IEEE80211_CHAN_NO_HT40MINUS;
2336 	else
2337 		channel->flags &= ~IEEE80211_CHAN_NO_HT40MINUS;
2338 
2339 	if (!is_ht40_allowed(channel_after) ||
2340 	    flags & NL80211_RRF_NO_HT40PLUS)
2341 		channel->flags |= IEEE80211_CHAN_NO_HT40PLUS;
2342 	else
2343 		channel->flags &= ~IEEE80211_CHAN_NO_HT40PLUS;
2344 }
2345 
reg_process_ht_flags_band(struct wiphy * wiphy,struct ieee80211_supported_band * sband)2346 static void reg_process_ht_flags_band(struct wiphy *wiphy,
2347 				      struct ieee80211_supported_band *sband)
2348 {
2349 	unsigned int i;
2350 
2351 	if (!sband)
2352 		return;
2353 
2354 	for (i = 0; i < sband->n_channels; i++)
2355 		reg_process_ht_flags_channel(wiphy, &sband->channels[i]);
2356 }
2357 
reg_process_ht_flags(struct wiphy * wiphy)2358 static void reg_process_ht_flags(struct wiphy *wiphy)
2359 {
2360 	enum nl80211_band band;
2361 
2362 	if (!wiphy)
2363 		return;
2364 
2365 	for (band = 0; band < NUM_NL80211_BANDS; band++)
2366 		reg_process_ht_flags_band(wiphy, wiphy->bands[band]);
2367 }
2368 
reg_wdev_chan_valid(struct wiphy * wiphy,struct wireless_dev * wdev)2369 static bool reg_wdev_chan_valid(struct wiphy *wiphy, struct wireless_dev *wdev)
2370 {
2371 	struct cfg80211_chan_def chandef = {};
2372 	struct cfg80211_registered_device *rdev = wiphy_to_rdev(wiphy);
2373 	enum nl80211_iftype iftype;
2374 	bool ret;
2375 	int link;
2376 
2377 	iftype = wdev->iftype;
2378 
2379 	/* make sure the interface is active */
2380 	if (!wdev->netdev || !netif_running(wdev->netdev))
2381 		return true;
2382 
2383 	for (link = 0; link < ARRAY_SIZE(wdev->links); link++) {
2384 		struct ieee80211_channel *chan;
2385 
2386 		if (!wdev->valid_links && link > 0)
2387 			break;
2388 		if (wdev->valid_links && !(wdev->valid_links & BIT(link)))
2389 			continue;
2390 		switch (iftype) {
2391 		case NL80211_IFTYPE_AP:
2392 		case NL80211_IFTYPE_P2P_GO:
2393 			if (!wdev->links[link].ap.beacon_interval)
2394 				continue;
2395 			chandef = wdev->links[link].ap.chandef;
2396 			break;
2397 		case NL80211_IFTYPE_MESH_POINT:
2398 			if (!wdev->u.mesh.beacon_interval)
2399 				continue;
2400 			chandef = wdev->u.mesh.chandef;
2401 			break;
2402 		case NL80211_IFTYPE_ADHOC:
2403 			if (!wdev->u.ibss.ssid_len)
2404 				continue;
2405 			chandef = wdev->u.ibss.chandef;
2406 			break;
2407 		case NL80211_IFTYPE_STATION:
2408 		case NL80211_IFTYPE_P2P_CLIENT:
2409 			/* Maybe we could consider disabling that link only? */
2410 			if (!wdev->links[link].client.current_bss)
2411 				continue;
2412 
2413 			chan = wdev->links[link].client.current_bss->pub.channel;
2414 			if (!chan)
2415 				continue;
2416 
2417 			if (!rdev->ops->get_channel ||
2418 			    rdev_get_channel(rdev, wdev, link, &chandef))
2419 				cfg80211_chandef_create(&chandef, chan,
2420 							NL80211_CHAN_NO_HT);
2421 			break;
2422 		case NL80211_IFTYPE_MONITOR:
2423 		case NL80211_IFTYPE_AP_VLAN:
2424 		case NL80211_IFTYPE_P2P_DEVICE:
2425 			/* no enforcement required */
2426 			break;
2427 		case NL80211_IFTYPE_OCB:
2428 			if (!wdev->u.ocb.chandef.chan)
2429 				continue;
2430 			chandef = wdev->u.ocb.chandef;
2431 			break;
2432 		case NL80211_IFTYPE_NAN:
2433 			/* we have no info, but NAN is also pretty universal */
2434 			continue;
2435 		default:
2436 			/* others not implemented for now */
2437 			WARN_ON_ONCE(1);
2438 			break;
2439 		}
2440 
2441 		switch (iftype) {
2442 		case NL80211_IFTYPE_AP:
2443 		case NL80211_IFTYPE_P2P_GO:
2444 		case NL80211_IFTYPE_ADHOC:
2445 		case NL80211_IFTYPE_MESH_POINT:
2446 			ret = cfg80211_reg_can_beacon_relax(wiphy, &chandef,
2447 							    iftype);
2448 			if (!ret)
2449 				return ret;
2450 			break;
2451 		case NL80211_IFTYPE_STATION:
2452 		case NL80211_IFTYPE_P2P_CLIENT:
2453 			ret = cfg80211_chandef_usable(wiphy, &chandef,
2454 						      IEEE80211_CHAN_DISABLED);
2455 			if (!ret)
2456 				return ret;
2457 			break;
2458 		default:
2459 			break;
2460 		}
2461 	}
2462 
2463 	return true;
2464 }
2465 
reg_leave_invalid_chans(struct wiphy * wiphy)2466 static void reg_leave_invalid_chans(struct wiphy *wiphy)
2467 {
2468 	struct wireless_dev *wdev;
2469 	struct cfg80211_registered_device *rdev = wiphy_to_rdev(wiphy);
2470 
2471 	wiphy_lock(wiphy);
2472 	list_for_each_entry(wdev, &rdev->wiphy.wdev_list, list)
2473 		if (!reg_wdev_chan_valid(wiphy, wdev))
2474 			cfg80211_leave(rdev, wdev);
2475 	wiphy_unlock(wiphy);
2476 }
2477 
reg_check_chans_work(struct work_struct * work)2478 static void reg_check_chans_work(struct work_struct *work)
2479 {
2480 	struct cfg80211_registered_device *rdev;
2481 
2482 	pr_debug("Verifying active interfaces after reg change\n");
2483 	rtnl_lock();
2484 
2485 	for_each_rdev(rdev)
2486 		reg_leave_invalid_chans(&rdev->wiphy);
2487 
2488 	rtnl_unlock();
2489 }
2490 
reg_check_channels(void)2491 void reg_check_channels(void)
2492 {
2493 	/*
2494 	 * Give usermode a chance to do something nicer (move to another
2495 	 * channel, orderly disconnection), before forcing a disconnection.
2496 	 */
2497 	mod_delayed_work(system_power_efficient_wq,
2498 			 ®_check_chans,
2499 			 msecs_to_jiffies(REG_ENFORCE_GRACE_MS));
2500 }
2501 
wiphy_update_regulatory(struct wiphy * wiphy,enum nl80211_reg_initiator initiator)2502 static void wiphy_update_regulatory(struct wiphy *wiphy,
2503 				    enum nl80211_reg_initiator initiator)
2504 {
2505 	enum nl80211_band band;
2506 	struct regulatory_request *lr = get_last_request();
2507 
2508 	if (ignore_reg_update(wiphy, initiator)) {
2509 		/*
2510 		 * Regulatory updates set by CORE are ignored for custom
2511 		 * regulatory cards. Let us notify the changes to the driver,
2512 		 * as some drivers used this to restore its orig_* reg domain.
2513 		 */
2514 		if (initiator == NL80211_REGDOM_SET_BY_CORE &&
2515 		    wiphy->regulatory_flags & REGULATORY_CUSTOM_REG &&
2516 		    !(wiphy->regulatory_flags &
2517 		      REGULATORY_WIPHY_SELF_MANAGED))
2518 			reg_call_notifier(wiphy, lr);
2519 		return;
2520 	}
2521 
2522 	lr->dfs_region = get_cfg80211_regdom()->dfs_region;
2523 
2524 	for (band = 0; band < NUM_NL80211_BANDS; band++)
2525 		handle_band(wiphy, initiator, wiphy->bands[band]);
2526 
2527 	reg_process_beacons(wiphy);
2528 	reg_process_ht_flags(wiphy);
2529 	reg_call_notifier(wiphy, lr);
2530 }
2531 
update_all_wiphy_regulatory(enum nl80211_reg_initiator initiator)2532 static void update_all_wiphy_regulatory(enum nl80211_reg_initiator initiator)
2533 {
2534 	struct cfg80211_registered_device *rdev;
2535 	struct wiphy *wiphy;
2536 
2537 	ASSERT_RTNL();
2538 
2539 	for_each_rdev(rdev) {
2540 		wiphy = &rdev->wiphy;
2541 		wiphy_update_regulatory(wiphy, initiator);
2542 	}
2543 
2544 	reg_check_channels();
2545 }
2546 
handle_channel_custom(struct wiphy * wiphy,struct ieee80211_channel * chan,const struct ieee80211_regdomain * regd,u32 min_bw)2547 static void handle_channel_custom(struct wiphy *wiphy,
2548 				  struct ieee80211_channel *chan,
2549 				  const struct ieee80211_regdomain *regd,
2550 				  u32 min_bw)
2551 {
2552 	u32 bw_flags = 0;
2553 	const struct ieee80211_reg_rule *reg_rule = NULL;
2554 	const struct ieee80211_power_rule *power_rule = NULL;
2555 	u32 bw, center_freq_khz;
2556 
2557 	center_freq_khz = ieee80211_channel_to_khz(chan);
2558 	for (bw = MHZ_TO_KHZ(20); bw >= min_bw; bw = bw / 2) {
2559 		reg_rule = freq_reg_info_regd(center_freq_khz, regd, bw);
2560 		if (!IS_ERR(reg_rule))
2561 			break;
2562 	}
2563 
2564 	if (IS_ERR_OR_NULL(reg_rule)) {
2565 		pr_debug("Disabling freq %d.%03d MHz as custom regd has no rule that fits it\n",
2566 			 chan->center_freq, chan->freq_offset);
2567 		if (wiphy->regulatory_flags & REGULATORY_WIPHY_SELF_MANAGED) {
2568 			chan->flags |= IEEE80211_CHAN_DISABLED;
2569 		} else {
2570 			chan->orig_flags |= IEEE80211_CHAN_DISABLED;
2571 			chan->flags = chan->orig_flags;
2572 		}
2573 		return;
2574 	}
2575 
2576 	power_rule = ®_rule->power_rule;
2577 	bw_flags = reg_rule_to_chan_bw_flags(regd, reg_rule, chan);
2578 
2579 	chan->dfs_state_entered = jiffies;
2580 	chan->dfs_state = NL80211_DFS_USABLE;
2581 
2582 	chan->beacon_found = false;
2583 
2584 	if (wiphy->regulatory_flags & REGULATORY_WIPHY_SELF_MANAGED)
2585 		chan->flags = chan->orig_flags | bw_flags |
2586 			      map_regdom_flags(reg_rule->flags);
2587 	else
2588 		chan->flags |= map_regdom_flags(reg_rule->flags) | bw_flags;
2589 
2590 	chan->max_antenna_gain = (int) MBI_TO_DBI(power_rule->max_antenna_gain);
2591 	chan->max_reg_power = chan->max_power =
2592 		(int) MBM_TO_DBM(power_rule->max_eirp);
2593 
2594 	if (chan->flags & IEEE80211_CHAN_RADAR) {
2595 		if (reg_rule->dfs_cac_ms)
2596 			chan->dfs_cac_ms = reg_rule->dfs_cac_ms;
2597 		else
2598 			chan->dfs_cac_ms = IEEE80211_DFS_MIN_CAC_TIME_MS;
2599 	}
2600 
2601 	if (chan->flags & IEEE80211_CHAN_PSD)
2602 		chan->psd = reg_rule->psd;
2603 
2604 	chan->max_power = chan->max_reg_power;
2605 }
2606 
handle_band_custom(struct wiphy * wiphy,struct ieee80211_supported_band * sband,const struct ieee80211_regdomain * regd)2607 static void handle_band_custom(struct wiphy *wiphy,
2608 			       struct ieee80211_supported_band *sband,
2609 			       const struct ieee80211_regdomain *regd)
2610 {
2611 	unsigned int i;
2612 
2613 	if (!sband)
2614 		return;
2615 
2616 	/*
2617 	 * We currently assume that you always want at least 20 MHz,
2618 	 * otherwise channel 12 might get enabled if this rule is
2619 	 * compatible to US, which permits 2402 - 2472 MHz.
2620 	 */
2621 	for (i = 0; i < sband->n_channels; i++)
2622 		handle_channel_custom(wiphy, &sband->channels[i], regd,
2623 				      MHZ_TO_KHZ(20));
2624 }
2625 
2626 /* Used by drivers prior to wiphy registration */
wiphy_apply_custom_regulatory(struct wiphy * wiphy,const struct ieee80211_regdomain * regd)2627 void wiphy_apply_custom_regulatory(struct wiphy *wiphy,
2628 				   const struct ieee80211_regdomain *regd)
2629 {
2630 	const struct ieee80211_regdomain *new_regd, *tmp;
2631 	enum nl80211_band band;
2632 	unsigned int bands_set = 0;
2633 
2634 	WARN(!(wiphy->regulatory_flags & REGULATORY_CUSTOM_REG),
2635 	     "wiphy should have REGULATORY_CUSTOM_REG\n");
2636 	wiphy->regulatory_flags |= REGULATORY_CUSTOM_REG;
2637 
2638 	for (band = 0; band < NUM_NL80211_BANDS; band++) {
2639 		if (!wiphy->bands[band])
2640 			continue;
2641 		handle_band_custom(wiphy, wiphy->bands[band], regd);
2642 		bands_set++;
2643 	}
2644 
2645 	/*
2646 	 * no point in calling this if it won't have any effect
2647 	 * on your device's supported bands.
2648 	 */
2649 	WARN_ON(!bands_set);
2650 	new_regd = reg_copy_regd(regd);
2651 	if (IS_ERR(new_regd))
2652 		return;
2653 
2654 	rtnl_lock();
2655 	wiphy_lock(wiphy);
2656 
2657 	tmp = get_wiphy_regdom(wiphy);
2658 	rcu_assign_pointer(wiphy->regd, new_regd);
2659 	rcu_free_regdom(tmp);
2660 
2661 	wiphy_unlock(wiphy);
2662 	rtnl_unlock();
2663 }
2664 EXPORT_SYMBOL(wiphy_apply_custom_regulatory);
2665 
reg_set_request_processed(void)2666 static void reg_set_request_processed(void)
2667 {
2668 	bool need_more_processing = false;
2669 	struct regulatory_request *lr = get_last_request();
2670 
2671 	lr->processed = true;
2672 
2673 	spin_lock(®_requests_lock);
2674 	if (!list_empty(®_requests_list))
2675 		need_more_processing = true;
2676 	spin_unlock(®_requests_lock);
2677 
2678 	cancel_crda_timeout();
2679 
2680 	if (need_more_processing)
2681 		schedule_work(®_work);
2682 }
2683 
2684 /**
2685  * reg_process_hint_core - process core regulatory requests
2686  * @core_request: a pending core regulatory request
2687  *
2688  * The wireless subsystem can use this function to process
2689  * a regulatory request issued by the regulatory core.
2690  *
2691  * Returns: %REG_REQ_OK or %REG_REQ_IGNORE, indicating if the
2692  *	hint was processed or ignored
2693  */
2694 static enum reg_request_treatment
reg_process_hint_core(struct regulatory_request * core_request)2695 reg_process_hint_core(struct regulatory_request *core_request)
2696 {
2697 	if (reg_query_database(core_request)) {
2698 		core_request->intersect = false;
2699 		core_request->processed = false;
2700 		reg_update_last_request(core_request);
2701 		return REG_REQ_OK;
2702 	}
2703 
2704 	return REG_REQ_IGNORE;
2705 }
2706 
2707 static enum reg_request_treatment
__reg_process_hint_user(struct regulatory_request * user_request)2708 __reg_process_hint_user(struct regulatory_request *user_request)
2709 {
2710 	struct regulatory_request *lr = get_last_request();
2711 
2712 	if (reg_request_cell_base(user_request))
2713 		return reg_ignore_cell_hint(user_request);
2714 
2715 	if (reg_request_cell_base(lr))
2716 		return REG_REQ_IGNORE;
2717 
2718 	if (lr->initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE)
2719 		return REG_REQ_INTERSECT;
2720 	/*
2721 	 * If the user knows better the user should set the regdom
2722 	 * to their country before the IE is picked up
2723 	 */
2724 	if (lr->initiator == NL80211_REGDOM_SET_BY_USER &&
2725 	    lr->intersect)
2726 		return REG_REQ_IGNORE;
2727 	/*
2728 	 * Process user requests only after previous user/driver/core
2729 	 * requests have been processed
2730 	 */
2731 	if ((lr->initiator == NL80211_REGDOM_SET_BY_CORE ||
2732 	     lr->initiator == NL80211_REGDOM_SET_BY_DRIVER ||
2733 	     lr->initiator == NL80211_REGDOM_SET_BY_USER) &&
2734 	    regdom_changes(lr->alpha2))
2735 		return REG_REQ_IGNORE;
2736 
2737 	if (!regdom_changes(user_request->alpha2))
2738 		return REG_REQ_ALREADY_SET;
2739 
2740 	return REG_REQ_OK;
2741 }
2742 
2743 /**
2744  * reg_process_hint_user - process user regulatory requests
2745  * @user_request: a pending user regulatory request
2746  *
2747  * The wireless subsystem can use this function to process
2748  * a regulatory request initiated by userspace.
2749  *
2750  * Returns: %REG_REQ_OK or %REG_REQ_IGNORE, indicating if the
2751  *	hint was processed or ignored
2752  */
2753 static enum reg_request_treatment
reg_process_hint_user(struct regulatory_request * user_request)2754 reg_process_hint_user(struct regulatory_request *user_request)
2755 {
2756 	enum reg_request_treatment treatment;
2757 
2758 	treatment = __reg_process_hint_user(user_request);
2759 	if (treatment == REG_REQ_IGNORE ||
2760 	    treatment == REG_REQ_ALREADY_SET)
2761 		return REG_REQ_IGNORE;
2762 
2763 	user_request->intersect = treatment == REG_REQ_INTERSECT;
2764 	user_request->processed = false;
2765 
2766 	if (reg_query_database(user_request)) {
2767 		reg_update_last_request(user_request);
2768 		user_alpha2[0] = user_request->alpha2[0];
2769 		user_alpha2[1] = user_request->alpha2[1];
2770 		return REG_REQ_OK;
2771 	}
2772 
2773 	return REG_REQ_IGNORE;
2774 }
2775 
2776 static enum reg_request_treatment
__reg_process_hint_driver(struct regulatory_request * driver_request)2777 __reg_process_hint_driver(struct regulatory_request *driver_request)
2778 {
2779 	struct regulatory_request *lr = get_last_request();
2780 
2781 	if (lr->initiator == NL80211_REGDOM_SET_BY_CORE) {
2782 		if (regdom_changes(driver_request->alpha2))
2783 			return REG_REQ_OK;
2784 		return REG_REQ_ALREADY_SET;
2785 	}
2786 
2787 	/*
2788 	 * This would happen if you unplug and plug your card
2789 	 * back in or if you add a new device for which the previously
2790 	 * loaded card also agrees on the regulatory domain.
2791 	 */
2792 	if (lr->initiator == NL80211_REGDOM_SET_BY_DRIVER &&
2793 	    !regdom_changes(driver_request->alpha2))
2794 		return REG_REQ_ALREADY_SET;
2795 
2796 	return REG_REQ_INTERSECT;
2797 }
2798 
2799 /**
2800  * reg_process_hint_driver - process driver regulatory requests
2801  * @wiphy: the wireless device for the regulatory request
2802  * @driver_request: a pending driver regulatory request
2803  *
2804  * The wireless subsystem can use this function to process
2805  * a regulatory request issued by an 802.11 driver.
2806  *
2807  * Returns: one of the different reg request treatment values.
2808  */
2809 static enum reg_request_treatment
reg_process_hint_driver(struct wiphy * wiphy,struct regulatory_request * driver_request)2810 reg_process_hint_driver(struct wiphy *wiphy,
2811 			struct regulatory_request *driver_request)
2812 {
2813 	const struct ieee80211_regdomain *regd, *tmp;
2814 	enum reg_request_treatment treatment;
2815 
2816 	treatment = __reg_process_hint_driver(driver_request);
2817 
2818 	switch (treatment) {
2819 	case REG_REQ_OK:
2820 		break;
2821 	case REG_REQ_IGNORE:
2822 		return REG_REQ_IGNORE;
2823 	case REG_REQ_INTERSECT:
2824 	case REG_REQ_ALREADY_SET:
2825 		regd = reg_copy_regd(get_cfg80211_regdom());
2826 		if (IS_ERR(regd))
2827 			return REG_REQ_IGNORE;
2828 
2829 		tmp = get_wiphy_regdom(wiphy);
2830 		ASSERT_RTNL();
2831 		wiphy_lock(wiphy);
2832 		rcu_assign_pointer(wiphy->regd, regd);
2833 		wiphy_unlock(wiphy);
2834 		rcu_free_regdom(tmp);
2835 	}
2836 
2837 
2838 	driver_request->intersect = treatment == REG_REQ_INTERSECT;
2839 	driver_request->processed = false;
2840 
2841 	/*
2842 	 * Since CRDA will not be called in this case as we already
2843 	 * have applied the requested regulatory domain before we just
2844 	 * inform userspace we have processed the request
2845 	 */
2846 	if (treatment == REG_REQ_ALREADY_SET) {
2847 		nl80211_send_reg_change_event(driver_request);
2848 		reg_update_last_request(driver_request);
2849 		reg_set_request_processed();
2850 		return REG_REQ_ALREADY_SET;
2851 	}
2852 
2853 	if (reg_query_database(driver_request)) {
2854 		reg_update_last_request(driver_request);
2855 		return REG_REQ_OK;
2856 	}
2857 
2858 	return REG_REQ_IGNORE;
2859 }
2860 
2861 static enum reg_request_treatment
__reg_process_hint_country_ie(struct wiphy * wiphy,struct regulatory_request * country_ie_request)2862 __reg_process_hint_country_ie(struct wiphy *wiphy,
2863 			      struct regulatory_request *country_ie_request)
2864 {
2865 	struct wiphy *last_wiphy = NULL;
2866 	struct regulatory_request *lr = get_last_request();
2867 
2868 	if (reg_request_cell_base(lr)) {
2869 		/* Trust a Cell base station over the AP's country IE */
2870 		if (regdom_changes(country_ie_request->alpha2))
2871 			return REG_REQ_IGNORE;
2872 		return REG_REQ_ALREADY_SET;
2873 	} else {
2874 		if (wiphy->regulatory_flags & REGULATORY_COUNTRY_IE_IGNORE)
2875 			return REG_REQ_IGNORE;
2876 	}
2877 
2878 	if (unlikely(!is_an_alpha2(country_ie_request->alpha2)))
2879 		return -EINVAL;
2880 
2881 	if (lr->initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE)
2882 		return REG_REQ_OK;
2883 
2884 	last_wiphy = wiphy_idx_to_wiphy(lr->wiphy_idx);
2885 
2886 	if (last_wiphy != wiphy) {
2887 		/*
2888 		 * Two cards with two APs claiming different
2889 		 * Country IE alpha2s. We could
2890 		 * intersect them, but that seems unlikely
2891 		 * to be correct. Reject second one for now.
2892 		 */
2893 		if (regdom_changes(country_ie_request->alpha2))
2894 			return REG_REQ_IGNORE;
2895 		return REG_REQ_ALREADY_SET;
2896 	}
2897 
2898 	if (regdom_changes(country_ie_request->alpha2))
2899 		return REG_REQ_OK;
2900 	return REG_REQ_ALREADY_SET;
2901 }
2902 
2903 /**
2904  * reg_process_hint_country_ie - process regulatory requests from country IEs
2905  * @wiphy: the wireless device for the regulatory request
2906  * @country_ie_request: a regulatory request from a country IE
2907  *
2908  * The wireless subsystem can use this function to process
2909  * a regulatory request issued by a country Information Element.
2910  *
2911  * Returns: one of the different reg request treatment values.
2912  */
2913 static enum reg_request_treatment
reg_process_hint_country_ie(struct wiphy * wiphy,struct regulatory_request * country_ie_request)2914 reg_process_hint_country_ie(struct wiphy *wiphy,
2915 			    struct regulatory_request *country_ie_request)
2916 {
2917 	enum reg_request_treatment treatment;
2918 
2919 	treatment = __reg_process_hint_country_ie(wiphy, country_ie_request);
2920 
2921 	switch (treatment) {
2922 	case REG_REQ_OK:
2923 		break;
2924 	case REG_REQ_IGNORE:
2925 		return REG_REQ_IGNORE;
2926 	case REG_REQ_ALREADY_SET:
2927 		reg_free_request(country_ie_request);
2928 		return REG_REQ_ALREADY_SET;
2929 	case REG_REQ_INTERSECT:
2930 		/*
2931 		 * This doesn't happen yet, not sure we
2932 		 * ever want to support it for this case.
2933 		 */
2934 		WARN_ONCE(1, "Unexpected intersection for country elements");
2935 		return REG_REQ_IGNORE;
2936 	}
2937 
2938 	country_ie_request->intersect = false;
2939 	country_ie_request->processed = false;
2940 
2941 	if (reg_query_database(country_ie_request)) {
2942 		reg_update_last_request(country_ie_request);
2943 		return REG_REQ_OK;
2944 	}
2945 
2946 	return REG_REQ_IGNORE;
2947 }
2948 
reg_dfs_domain_same(struct wiphy * wiphy1,struct wiphy * wiphy2)2949 bool reg_dfs_domain_same(struct wiphy *wiphy1, struct wiphy *wiphy2)
2950 {
2951 	const struct ieee80211_regdomain *wiphy1_regd = NULL;
2952 	const struct ieee80211_regdomain *wiphy2_regd = NULL;
2953 	const struct ieee80211_regdomain *cfg80211_regd = NULL;
2954 	bool dfs_domain_same;
2955 
2956 	rcu_read_lock();
2957 
2958 	cfg80211_regd = rcu_dereference(cfg80211_regdomain);
2959 	wiphy1_regd = rcu_dereference(wiphy1->regd);
2960 	if (!wiphy1_regd)
2961 		wiphy1_regd = cfg80211_regd;
2962 
2963 	wiphy2_regd = rcu_dereference(wiphy2->regd);
2964 	if (!wiphy2_regd)
2965 		wiphy2_regd = cfg80211_regd;
2966 
2967 	dfs_domain_same = wiphy1_regd->dfs_region == wiphy2_regd->dfs_region;
2968 
2969 	rcu_read_unlock();
2970 
2971 	return dfs_domain_same;
2972 }
2973 
reg_copy_dfs_chan_state(struct ieee80211_channel * dst_chan,struct ieee80211_channel * src_chan)2974 static void reg_copy_dfs_chan_state(struct ieee80211_channel *dst_chan,
2975 				    struct ieee80211_channel *src_chan)
2976 {
2977 	if (!(dst_chan->flags & IEEE80211_CHAN_RADAR) ||
2978 	    !(src_chan->flags & IEEE80211_CHAN_RADAR))
2979 		return;
2980 
2981 	if (dst_chan->flags & IEEE80211_CHAN_DISABLED ||
2982 	    src_chan->flags & IEEE80211_CHAN_DISABLED)
2983 		return;
2984 
2985 	if (src_chan->center_freq == dst_chan->center_freq &&
2986 	    dst_chan->dfs_state == NL80211_DFS_USABLE) {
2987 		dst_chan->dfs_state = src_chan->dfs_state;
2988 		dst_chan->dfs_state_entered = src_chan->dfs_state_entered;
2989 	}
2990 }
2991 
wiphy_share_dfs_chan_state(struct wiphy * dst_wiphy,struct wiphy * src_wiphy)2992 static void wiphy_share_dfs_chan_state(struct wiphy *dst_wiphy,
2993 				       struct wiphy *src_wiphy)
2994 {
2995 	struct ieee80211_supported_band *src_sband, *dst_sband;
2996 	struct ieee80211_channel *src_chan, *dst_chan;
2997 	int i, j, band;
2998 
2999 	if (!reg_dfs_domain_same(dst_wiphy, src_wiphy))
3000 		return;
3001 
3002 	for (band = 0; band < NUM_NL80211_BANDS; band++) {
3003 		dst_sband = dst_wiphy->bands[band];
3004 		src_sband = src_wiphy->bands[band];
3005 		if (!dst_sband || !src_sband)
3006 			continue;
3007 
3008 		for (i = 0; i < dst_sband->n_channels; i++) {
3009 			dst_chan = &dst_sband->channels[i];
3010 			for (j = 0; j < src_sband->n_channels; j++) {
3011 				src_chan = &src_sband->channels[j];
3012 				reg_copy_dfs_chan_state(dst_chan, src_chan);
3013 			}
3014 		}
3015 	}
3016 }
3017 
wiphy_all_share_dfs_chan_state(struct wiphy * wiphy)3018 static void wiphy_all_share_dfs_chan_state(struct wiphy *wiphy)
3019 {
3020 	struct cfg80211_registered_device *rdev;
3021 
3022 	ASSERT_RTNL();
3023 
3024 	for_each_rdev(rdev) {
3025 		if (wiphy == &rdev->wiphy)
3026 			continue;
3027 		wiphy_share_dfs_chan_state(wiphy, &rdev->wiphy);
3028 	}
3029 }
3030 
3031 /* This processes *all* regulatory hints */
reg_process_hint(struct regulatory_request * reg_request)3032 static void reg_process_hint(struct regulatory_request *reg_request)
3033 {
3034 	struct wiphy *wiphy = NULL;
3035 	enum reg_request_treatment treatment;
3036 	enum nl80211_reg_initiator initiator = reg_request->initiator;
3037 
3038 	if (reg_request->wiphy_idx != WIPHY_IDX_INVALID)
3039 		wiphy = wiphy_idx_to_wiphy(reg_request->wiphy_idx);
3040 
3041 	switch (initiator) {
3042 	case NL80211_REGDOM_SET_BY_CORE:
3043 		treatment = reg_process_hint_core(reg_request);
3044 		break;
3045 	case NL80211_REGDOM_SET_BY_USER:
3046 		treatment = reg_process_hint_user(reg_request);
3047 		break;
3048 	case NL80211_REGDOM_SET_BY_DRIVER:
3049 		if (!wiphy)
3050 			goto out_free;
3051 		treatment = reg_process_hint_driver(wiphy, reg_request);
3052 		break;
3053 	case NL80211_REGDOM_SET_BY_COUNTRY_IE:
3054 		if (!wiphy)
3055 			goto out_free;
3056 		treatment = reg_process_hint_country_ie(wiphy, reg_request);
3057 		break;
3058 	default:
3059 		WARN(1, "invalid initiator %d\n", initiator);
3060 		goto out_free;
3061 	}
3062 
3063 	if (treatment == REG_REQ_IGNORE)
3064 		goto out_free;
3065 
3066 	WARN(treatment != REG_REQ_OK && treatment != REG_REQ_ALREADY_SET,
3067 	     "unexpected treatment value %d\n", treatment);
3068 
3069 	/* This is required so that the orig_* parameters are saved.
3070 	 * NOTE: treatment must be set for any case that reaches here!
3071 	 */
3072 	if (treatment == REG_REQ_ALREADY_SET && wiphy &&
3073 	    wiphy->regulatory_flags & REGULATORY_STRICT_REG) {
3074 		wiphy_update_regulatory(wiphy, initiator);
3075 		wiphy_all_share_dfs_chan_state(wiphy);
3076 		reg_check_channels();
3077 	}
3078 
3079 	return;
3080 
3081 out_free:
3082 	reg_free_request(reg_request);
3083 }
3084 
notify_self_managed_wiphys(struct regulatory_request * request)3085 static void notify_self_managed_wiphys(struct regulatory_request *request)
3086 {
3087 	struct cfg80211_registered_device *rdev;
3088 	struct wiphy *wiphy;
3089 
3090 	for_each_rdev(rdev) {
3091 		wiphy = &rdev->wiphy;
3092 		if (wiphy->regulatory_flags & REGULATORY_WIPHY_SELF_MANAGED &&
3093 		    request->initiator == NL80211_REGDOM_SET_BY_USER)
3094 			reg_call_notifier(wiphy, request);
3095 	}
3096 }
3097 
3098 /*
3099  * Processes regulatory hints, this is all the NL80211_REGDOM_SET_BY_*
3100  * Regulatory hints come on a first come first serve basis and we
3101  * must process each one atomically.
3102  */
reg_process_pending_hints(void)3103 static void reg_process_pending_hints(void)
3104 {
3105 	struct regulatory_request *reg_request, *lr;
3106 
3107 	lr = get_last_request();
3108 
3109 	/* When last_request->processed becomes true this will be rescheduled */
3110 	if (lr && !lr->processed) {
3111 		pr_debug("Pending regulatory request, waiting for it to be processed...\n");
3112 		return;
3113 	}
3114 
3115 	spin_lock(®_requests_lock);
3116 
3117 	if (list_empty(®_requests_list)) {
3118 		spin_unlock(®_requests_lock);
3119 		return;
3120 	}
3121 
3122 	reg_request = list_first_entry(®_requests_list,
3123 				       struct regulatory_request,
3124 				       list);
3125 	list_del_init(®_request->list);
3126 
3127 	spin_unlock(®_requests_lock);
3128 
3129 	notify_self_managed_wiphys(reg_request);
3130 
3131 	reg_process_hint(reg_request);
3132 
3133 	lr = get_last_request();
3134 
3135 	spin_lock(®_requests_lock);
3136 	if (!list_empty(®_requests_list) && lr && lr->processed)
3137 		schedule_work(®_work);
3138 	spin_unlock(®_requests_lock);
3139 }
3140 
3141 /* Processes beacon hints -- this has nothing to do with country IEs */
reg_process_pending_beacon_hints(void)3142 static void reg_process_pending_beacon_hints(void)
3143 {
3144 	struct cfg80211_registered_device *rdev;
3145 	struct reg_beacon *pending_beacon, *tmp;
3146 
3147 	/* This goes through the _pending_ beacon list */
3148 	spin_lock_bh(®_pending_beacons_lock);
3149 
3150 	list_for_each_entry_safe(pending_beacon, tmp,
3151 				 ®_pending_beacons, list) {
3152 		list_del_init(&pending_beacon->list);
3153 
3154 		/* Applies the beacon hint to current wiphys */
3155 		for_each_rdev(rdev)
3156 			wiphy_update_new_beacon(&rdev->wiphy, pending_beacon);
3157 
3158 		/* Remembers the beacon hint for new wiphys or reg changes */
3159 		list_add_tail(&pending_beacon->list, ®_beacon_list);
3160 	}
3161 
3162 	spin_unlock_bh(®_pending_beacons_lock);
3163 }
3164 
reg_process_self_managed_hint(struct wiphy * wiphy)3165 static void reg_process_self_managed_hint(struct wiphy *wiphy)
3166 {
3167 	struct cfg80211_registered_device *rdev = wiphy_to_rdev(wiphy);
3168 	const struct ieee80211_regdomain *tmp;
3169 	const struct ieee80211_regdomain *regd;
3170 	enum nl80211_band band;
3171 	struct regulatory_request request = {};
3172 
3173 	ASSERT_RTNL();
3174 	lockdep_assert_wiphy(wiphy);
3175 
3176 	spin_lock(®_requests_lock);
3177 	regd = rdev->requested_regd;
3178 	rdev->requested_regd = NULL;
3179 	spin_unlock(®_requests_lock);
3180 
3181 	if (!regd)
3182 		return;
3183 
3184 	tmp = get_wiphy_regdom(wiphy);
3185 	rcu_assign_pointer(wiphy->regd, regd);
3186 	rcu_free_regdom(tmp);
3187 
3188 	for (band = 0; band < NUM_NL80211_BANDS; band++)
3189 		handle_band_custom(wiphy, wiphy->bands[band], regd);
3190 
3191 	reg_process_ht_flags(wiphy);
3192 
3193 	request.wiphy_idx = get_wiphy_idx(wiphy);
3194 	request.alpha2[0] = regd->alpha2[0];
3195 	request.alpha2[1] = regd->alpha2[1];
3196 	request.initiator = NL80211_REGDOM_SET_BY_DRIVER;
3197 
3198 	if (wiphy->flags & WIPHY_FLAG_NOTIFY_REGDOM_BY_DRIVER)
3199 		reg_call_notifier(wiphy, &request);
3200 
3201 	nl80211_send_wiphy_reg_change_event(&request);
3202 }
3203 
reg_process_self_managed_hints(void)3204 static void reg_process_self_managed_hints(void)
3205 {
3206 	struct cfg80211_registered_device *rdev;
3207 
3208 	ASSERT_RTNL();
3209 
3210 	for_each_rdev(rdev) {
3211 		wiphy_lock(&rdev->wiphy);
3212 		reg_process_self_managed_hint(&rdev->wiphy);
3213 		wiphy_unlock(&rdev->wiphy);
3214 	}
3215 
3216 	reg_check_channels();
3217 }
3218 
reg_todo(struct work_struct * work)3219 static void reg_todo(struct work_struct *work)
3220 {
3221 	rtnl_lock();
3222 	reg_process_pending_hints();
3223 	reg_process_pending_beacon_hints();
3224 	reg_process_self_managed_hints();
3225 	rtnl_unlock();
3226 }
3227 
queue_regulatory_request(struct regulatory_request * request)3228 static void queue_regulatory_request(struct regulatory_request *request)
3229 {
3230 	request->alpha2[0] = toupper(request->alpha2[0]);
3231 	request->alpha2[1] = toupper(request->alpha2[1]);
3232 
3233 	spin_lock(®_requests_lock);
3234 	list_add_tail(&request->list, ®_requests_list);
3235 	spin_unlock(®_requests_lock);
3236 
3237 	schedule_work(®_work);
3238 }
3239 
3240 /*
3241  * Core regulatory hint -- happens during cfg80211_init()
3242  * and when we restore regulatory settings.
3243  */
regulatory_hint_core(const char * alpha2)3244 static int regulatory_hint_core(const char *alpha2)
3245 {
3246 	struct regulatory_request *request;
3247 
3248 	request = kzalloc(sizeof(struct regulatory_request), GFP_KERNEL);
3249 	if (!request)
3250 		return -ENOMEM;
3251 
3252 	request->alpha2[0] = alpha2[0];
3253 	request->alpha2[1] = alpha2[1];
3254 	request->initiator = NL80211_REGDOM_SET_BY_CORE;
3255 	request->wiphy_idx = WIPHY_IDX_INVALID;
3256 
3257 	queue_regulatory_request(request);
3258 
3259 	return 0;
3260 }
3261 
3262 /* User hints */
regulatory_hint_user(const char * alpha2,enum nl80211_user_reg_hint_type user_reg_hint_type)3263 int regulatory_hint_user(const char *alpha2,
3264 			 enum nl80211_user_reg_hint_type user_reg_hint_type)
3265 {
3266 	struct regulatory_request *request;
3267 
3268 	if (WARN_ON(!alpha2))
3269 		return -EINVAL;
3270 
3271 	if (!is_world_regdom(alpha2) && !is_an_alpha2(alpha2))
3272 		return -EINVAL;
3273 
3274 	request = kzalloc(sizeof(struct regulatory_request), GFP_KERNEL);
3275 	if (!request)
3276 		return -ENOMEM;
3277 
3278 	request->wiphy_idx = WIPHY_IDX_INVALID;
3279 	request->alpha2[0] = alpha2[0];
3280 	request->alpha2[1] = alpha2[1];
3281 	request->initiator = NL80211_REGDOM_SET_BY_USER;
3282 	request->user_reg_hint_type = user_reg_hint_type;
3283 
3284 	/* Allow calling CRDA again */
3285 	reset_crda_timeouts();
3286 
3287 	queue_regulatory_request(request);
3288 
3289 	return 0;
3290 }
3291 
regulatory_hint_indoor(bool is_indoor,u32 portid)3292 void regulatory_hint_indoor(bool is_indoor, u32 portid)
3293 {
3294 	spin_lock(®_indoor_lock);
3295 
3296 	/* It is possible that more than one user space process is trying to
3297 	 * configure the indoor setting. To handle such cases, clear the indoor
3298 	 * setting in case that some process does not think that the device
3299 	 * is operating in an indoor environment. In addition, if a user space
3300 	 * process indicates that it is controlling the indoor setting, save its
3301 	 * portid, i.e., make it the owner.
3302 	 */
3303 	reg_is_indoor = is_indoor;
3304 	if (reg_is_indoor) {
3305 		if (!reg_is_indoor_portid)
3306 			reg_is_indoor_portid = portid;
3307 	} else {
3308 		reg_is_indoor_portid = 0;
3309 	}
3310 
3311 	spin_unlock(®_indoor_lock);
3312 
3313 	if (!is_indoor)
3314 		reg_check_channels();
3315 }
3316 
regulatory_netlink_notify(u32 portid)3317 void regulatory_netlink_notify(u32 portid)
3318 {
3319 	spin_lock(®_indoor_lock);
3320 
3321 	if (reg_is_indoor_portid != portid) {
3322 		spin_unlock(®_indoor_lock);
3323 		return;
3324 	}
3325 
3326 	reg_is_indoor = false;
3327 	reg_is_indoor_portid = 0;
3328 
3329 	spin_unlock(®_indoor_lock);
3330 
3331 	reg_check_channels();
3332 }
3333 
3334 /* Driver hints */
regulatory_hint(struct wiphy * wiphy,const char * alpha2)3335 int regulatory_hint(struct wiphy *wiphy, const char *alpha2)
3336 {
3337 	struct regulatory_request *request;
3338 
3339 	if (WARN_ON(!alpha2 || !wiphy))
3340 		return -EINVAL;
3341 
3342 	wiphy->regulatory_flags &= ~REGULATORY_CUSTOM_REG;
3343 
3344 	request = kzalloc(sizeof(struct regulatory_request), GFP_KERNEL);
3345 	if (!request)
3346 		return -ENOMEM;
3347 
3348 	request->wiphy_idx = get_wiphy_idx(wiphy);
3349 
3350 	request->alpha2[0] = alpha2[0];
3351 	request->alpha2[1] = alpha2[1];
3352 	request->initiator = NL80211_REGDOM_SET_BY_DRIVER;
3353 
3354 	/* Allow calling CRDA again */
3355 	reset_crda_timeouts();
3356 
3357 	queue_regulatory_request(request);
3358 
3359 	return 0;
3360 }
3361 EXPORT_SYMBOL(regulatory_hint);
3362 
regulatory_hint_country_ie(struct wiphy * wiphy,enum nl80211_band band,const u8 * country_ie,u8 country_ie_len)3363 void regulatory_hint_country_ie(struct wiphy *wiphy, enum nl80211_band band,
3364 				const u8 *country_ie, u8 country_ie_len)
3365 {
3366 	char alpha2[2];
3367 	enum environment_cap env = ENVIRON_ANY;
3368 	struct regulatory_request *request = NULL, *lr;
3369 
3370 	/* IE len must be evenly divisible by 2 */
3371 	if (country_ie_len & 0x01)
3372 		return;
3373 
3374 	if (country_ie_len < IEEE80211_COUNTRY_IE_MIN_LEN)
3375 		return;
3376 
3377 	request = kzalloc(sizeof(*request), GFP_KERNEL);
3378 	if (!request)
3379 		return;
3380 
3381 	alpha2[0] = country_ie[0];
3382 	alpha2[1] = country_ie[1];
3383 
3384 	if (country_ie[2] == 'I')
3385 		env = ENVIRON_INDOOR;
3386 	else if (country_ie[2] == 'O')
3387 		env = ENVIRON_OUTDOOR;
3388 
3389 	rcu_read_lock();
3390 	lr = get_last_request();
3391 
3392 	if (unlikely(!lr))
3393 		goto out;
3394 
3395 	/*
3396 	 * We will run this only upon a successful connection on cfg80211.
3397 	 * We leave conflict resolution to the workqueue, where can hold
3398 	 * the RTNL.
3399 	 */
3400 	if (lr->initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE &&
3401 	    lr->wiphy_idx != WIPHY_IDX_INVALID)
3402 		goto out;
3403 
3404 	request->wiphy_idx = get_wiphy_idx(wiphy);
3405 	request->alpha2[0] = alpha2[0];
3406 	request->alpha2[1] = alpha2[1];
3407 	request->initiator = NL80211_REGDOM_SET_BY_COUNTRY_IE;
3408 	request->country_ie_env = env;
3409 
3410 	/* Allow calling CRDA again */
3411 	reset_crda_timeouts();
3412 
3413 	queue_regulatory_request(request);
3414 	request = NULL;
3415 out:
3416 	kfree(request);
3417 	rcu_read_unlock();
3418 }
3419 
restore_alpha2(char * alpha2,bool reset_user)3420 static void restore_alpha2(char *alpha2, bool reset_user)
3421 {
3422 	/* indicates there is no alpha2 to consider for restoration */
3423 	alpha2[0] = '9';
3424 	alpha2[1] = '7';
3425 
3426 	/* The user setting has precedence over the module parameter */
3427 	if (is_user_regdom_saved()) {
3428 		/* Unless we're asked to ignore it and reset it */
3429 		if (reset_user) {
3430 			pr_debug("Restoring regulatory settings including user preference\n");
3431 			user_alpha2[0] = '9';
3432 			user_alpha2[1] = '7';
3433 
3434 			/*
3435 			 * If we're ignoring user settings, we still need to
3436 			 * check the module parameter to ensure we put things
3437 			 * back as they were for a full restore.
3438 			 */
3439 			if (!is_world_regdom(ieee80211_regdom)) {
3440 				pr_debug("Keeping preference on module parameter ieee80211_regdom: %c%c\n",
3441 					 ieee80211_regdom[0], ieee80211_regdom[1]);
3442 				alpha2[0] = ieee80211_regdom[0];
3443 				alpha2[1] = ieee80211_regdom[1];
3444 			}
3445 		} else {
3446 			pr_debug("Restoring regulatory settings while preserving user preference for: %c%c\n",
3447 				 user_alpha2[0], user_alpha2[1]);
3448 			alpha2[0] = user_alpha2[0];
3449 			alpha2[1] = user_alpha2[1];
3450 		}
3451 	} else if (!is_world_regdom(ieee80211_regdom)) {
3452 		pr_debug("Keeping preference on module parameter ieee80211_regdom: %c%c\n",
3453 			 ieee80211_regdom[0], ieee80211_regdom[1]);
3454 		alpha2[0] = ieee80211_regdom[0];
3455 		alpha2[1] = ieee80211_regdom[1];
3456 	} else
3457 		pr_debug("Restoring regulatory settings\n");
3458 }
3459 
restore_custom_reg_settings(struct wiphy * wiphy)3460 static void restore_custom_reg_settings(struct wiphy *wiphy)
3461 {
3462 	struct ieee80211_supported_band *sband;
3463 	enum nl80211_band band;
3464 	struct ieee80211_channel *chan;
3465 	int i;
3466 
3467 	for (band = 0; band < NUM_NL80211_BANDS; band++) {
3468 		sband = wiphy->bands[band];
3469 		if (!sband)
3470 			continue;
3471 		for (i = 0; i < sband->n_channels; i++) {
3472 			chan = &sband->channels[i];
3473 			chan->flags = chan->orig_flags;
3474 			chan->max_antenna_gain = chan->orig_mag;
3475 			chan->max_power = chan->orig_mpwr;
3476 			chan->beacon_found = false;
3477 		}
3478 	}
3479 }
3480 
3481 /*
3482  * Restoring regulatory settings involves ignoring any
3483  * possibly stale country IE information and user regulatory
3484  * settings if so desired, this includes any beacon hints
3485  * learned as we could have traveled outside to another country
3486  * after disconnection. To restore regulatory settings we do
3487  * exactly what we did at bootup:
3488  *
3489  *   - send a core regulatory hint
3490  *   - send a user regulatory hint if applicable
3491  *
3492  * Device drivers that send a regulatory hint for a specific country
3493  * keep their own regulatory domain on wiphy->regd so that does
3494  * not need to be remembered.
3495  */
restore_regulatory_settings(bool reset_user,bool cached)3496 static void restore_regulatory_settings(bool reset_user, bool cached)
3497 {
3498 	char alpha2[2];
3499 	char world_alpha2[2];
3500 	struct reg_beacon *reg_beacon, *btmp;
3501 	LIST_HEAD(tmp_reg_req_list);
3502 	struct cfg80211_registered_device *rdev;
3503 
3504 	ASSERT_RTNL();
3505 
3506 	/*
3507 	 * Clear the indoor setting in case that it is not controlled by user
3508 	 * space, as otherwise there is no guarantee that the device is still
3509 	 * operating in an indoor environment.
3510 	 */
3511 	spin_lock(®_indoor_lock);
3512 	if (reg_is_indoor && !reg_is_indoor_portid) {
3513 		reg_is_indoor = false;
3514 		reg_check_channels();
3515 	}
3516 	spin_unlock(®_indoor_lock);
3517 
3518 	reset_regdomains(true, &world_regdom);
3519 	restore_alpha2(alpha2, reset_user);
3520 
3521 	/*
3522 	 * If there's any pending requests we simply
3523 	 * stash them to a temporary pending queue and
3524 	 * add then after we've restored regulatory
3525 	 * settings.
3526 	 */
3527 	spin_lock(®_requests_lock);
3528 	list_splice_tail_init(®_requests_list, &tmp_reg_req_list);
3529 	spin_unlock(®_requests_lock);
3530 
3531 	/* Clear beacon hints */
3532 	spin_lock_bh(®_pending_beacons_lock);
3533 	list_for_each_entry_safe(reg_beacon, btmp, ®_pending_beacons, list) {
3534 		list_del(®_beacon->list);
3535 		kfree(reg_beacon);
3536 	}
3537 	spin_unlock_bh(®_pending_beacons_lock);
3538 
3539 	list_for_each_entry_safe(reg_beacon, btmp, ®_beacon_list, list) {
3540 		list_del(®_beacon->list);
3541 		kfree(reg_beacon);
3542 	}
3543 
3544 	/* First restore to the basic regulatory settings */
3545 	world_alpha2[0] = cfg80211_world_regdom->alpha2[0];
3546 	world_alpha2[1] = cfg80211_world_regdom->alpha2[1];
3547 
3548 	for_each_rdev(rdev) {
3549 		if (rdev->wiphy.regulatory_flags & REGULATORY_WIPHY_SELF_MANAGED)
3550 			continue;
3551 		if (rdev->wiphy.regulatory_flags & REGULATORY_CUSTOM_REG)
3552 			restore_custom_reg_settings(&rdev->wiphy);
3553 	}
3554 
3555 	if (cached && (!is_an_alpha2(alpha2) ||
3556 		       !IS_ERR_OR_NULL(cfg80211_user_regdom))) {
3557 		reset_regdomains(false, cfg80211_world_regdom);
3558 		update_all_wiphy_regulatory(NL80211_REGDOM_SET_BY_CORE);
3559 		print_regdomain(get_cfg80211_regdom());
3560 		nl80211_send_reg_change_event(&core_request_world);
3561 		reg_set_request_processed();
3562 
3563 		if (is_an_alpha2(alpha2) &&
3564 		    !regulatory_hint_user(alpha2, NL80211_USER_REG_HINT_USER)) {
3565 			struct regulatory_request *ureq;
3566 
3567 			spin_lock(®_requests_lock);
3568 			ureq = list_last_entry(®_requests_list,
3569 					       struct regulatory_request,
3570 					       list);
3571 			list_del(&ureq->list);
3572 			spin_unlock(®_requests_lock);
3573 
3574 			notify_self_managed_wiphys(ureq);
3575 			reg_update_last_request(ureq);
3576 			set_regdom(reg_copy_regd(cfg80211_user_regdom),
3577 				   REGD_SOURCE_CACHED);
3578 		}
3579 	} else {
3580 		regulatory_hint_core(world_alpha2);
3581 
3582 		/*
3583 		 * This restores the ieee80211_regdom module parameter
3584 		 * preference or the last user requested regulatory
3585 		 * settings, user regulatory settings takes precedence.
3586 		 */
3587 		if (is_an_alpha2(alpha2))
3588 			regulatory_hint_user(alpha2, NL80211_USER_REG_HINT_USER);
3589 	}
3590 
3591 	spin_lock(®_requests_lock);
3592 	list_splice_tail_init(&tmp_reg_req_list, ®_requests_list);
3593 	spin_unlock(®_requests_lock);
3594 
3595 	pr_debug("Kicking the queue\n");
3596 
3597 	schedule_work(®_work);
3598 }
3599 
is_wiphy_all_set_reg_flag(enum ieee80211_regulatory_flags flag)3600 static bool is_wiphy_all_set_reg_flag(enum ieee80211_regulatory_flags flag)
3601 {
3602 	struct cfg80211_registered_device *rdev;
3603 	struct wireless_dev *wdev;
3604 
3605 	for_each_rdev(rdev) {
3606 		wiphy_lock(&rdev->wiphy);
3607 		list_for_each_entry(wdev, &rdev->wiphy.wdev_list, list) {
3608 			if (!(wdev->wiphy->regulatory_flags & flag)) {
3609 				wiphy_unlock(&rdev->wiphy);
3610 				return false;
3611 			}
3612 		}
3613 		wiphy_unlock(&rdev->wiphy);
3614 	}
3615 
3616 	return true;
3617 }
3618 
regulatory_hint_disconnect(void)3619 void regulatory_hint_disconnect(void)
3620 {
3621 	/* Restore of regulatory settings is not required when wiphy(s)
3622 	 * ignore IE from connected access point but clearance of beacon hints
3623 	 * is required when wiphy(s) supports beacon hints.
3624 	 */
3625 	if (is_wiphy_all_set_reg_flag(REGULATORY_COUNTRY_IE_IGNORE)) {
3626 		struct reg_beacon *reg_beacon, *btmp;
3627 
3628 		if (is_wiphy_all_set_reg_flag(REGULATORY_DISABLE_BEACON_HINTS))
3629 			return;
3630 
3631 		spin_lock_bh(®_pending_beacons_lock);
3632 		list_for_each_entry_safe(reg_beacon, btmp,
3633 					 ®_pending_beacons, list) {
3634 			list_del(®_beacon->list);
3635 			kfree(reg_beacon);
3636 		}
3637 		spin_unlock_bh(®_pending_beacons_lock);
3638 
3639 		list_for_each_entry_safe(reg_beacon, btmp,
3640 					 ®_beacon_list, list) {
3641 			list_del(®_beacon->list);
3642 			kfree(reg_beacon);
3643 		}
3644 
3645 		return;
3646 	}
3647 
3648 	pr_debug("All devices are disconnected, going to restore regulatory settings\n");
3649 	restore_regulatory_settings(false, true);
3650 }
3651 
freq_is_chan_12_13_14(u32 freq)3652 static bool freq_is_chan_12_13_14(u32 freq)
3653 {
3654 	if (freq == ieee80211_channel_to_frequency(12, NL80211_BAND_2GHZ) ||
3655 	    freq == ieee80211_channel_to_frequency(13, NL80211_BAND_2GHZ) ||
3656 	    freq == ieee80211_channel_to_frequency(14, NL80211_BAND_2GHZ))
3657 		return true;
3658 	return false;
3659 }
3660 
pending_reg_beacon(struct ieee80211_channel * beacon_chan)3661 static bool pending_reg_beacon(struct ieee80211_channel *beacon_chan)
3662 {
3663 	struct reg_beacon *pending_beacon;
3664 
3665 	list_for_each_entry(pending_beacon, ®_pending_beacons, list)
3666 		if (ieee80211_channel_equal(beacon_chan,
3667 					    &pending_beacon->chan))
3668 			return true;
3669 	return false;
3670 }
3671 
regulatory_hint_found_beacon(struct wiphy * wiphy,struct ieee80211_channel * beacon_chan,gfp_t gfp)3672 void regulatory_hint_found_beacon(struct wiphy *wiphy,
3673 				  struct ieee80211_channel *beacon_chan,
3674 				  gfp_t gfp)
3675 {
3676 	struct reg_beacon *reg_beacon;
3677 	bool processing;
3678 
3679 	if (beacon_chan->beacon_found ||
3680 	    beacon_chan->flags & IEEE80211_CHAN_RADAR ||
3681 	    (beacon_chan->band == NL80211_BAND_2GHZ &&
3682 	     !freq_is_chan_12_13_14(beacon_chan->center_freq)))
3683 		return;
3684 
3685 	spin_lock_bh(®_pending_beacons_lock);
3686 	processing = pending_reg_beacon(beacon_chan);
3687 	spin_unlock_bh(®_pending_beacons_lock);
3688 
3689 	if (processing)
3690 		return;
3691 
3692 	reg_beacon = kzalloc(sizeof(struct reg_beacon), gfp);
3693 	if (!reg_beacon)
3694 		return;
3695 
3696 	pr_debug("Found new beacon on frequency: %d.%03d MHz (Ch %d) on %s\n",
3697 		 beacon_chan->center_freq, beacon_chan->freq_offset,
3698 		 ieee80211_freq_khz_to_channel(
3699 			 ieee80211_channel_to_khz(beacon_chan)),
3700 		 wiphy_name(wiphy));
3701 
3702 	memcpy(®_beacon->chan, beacon_chan,
3703 	       sizeof(struct ieee80211_channel));
3704 
3705 	/*
3706 	 * Since we can be called from BH or and non-BH context
3707 	 * we must use spin_lock_bh()
3708 	 */
3709 	spin_lock_bh(®_pending_beacons_lock);
3710 	list_add_tail(®_beacon->list, ®_pending_beacons);
3711 	spin_unlock_bh(®_pending_beacons_lock);
3712 
3713 	schedule_work(®_work);
3714 }
3715 
print_rd_rules(const struct ieee80211_regdomain * rd)3716 static void print_rd_rules(const struct ieee80211_regdomain *rd)
3717 {
3718 	unsigned int i;
3719 	const struct ieee80211_reg_rule *reg_rule = NULL;
3720 	const struct ieee80211_freq_range *freq_range = NULL;
3721 	const struct ieee80211_power_rule *power_rule = NULL;
3722 	char bw[32], cac_time[32];
3723 
3724 	pr_debug("  (start_freq - end_freq @ bandwidth), (max_antenna_gain, max_eirp), (dfs_cac_time)\n");
3725 
3726 	for (i = 0; i < rd->n_reg_rules; i++) {
3727 		reg_rule = &rd->reg_rules[i];
3728 		freq_range = ®_rule->freq_range;
3729 		power_rule = ®_rule->power_rule;
3730 
3731 		if (reg_rule->flags & NL80211_RRF_AUTO_BW)
3732 			snprintf(bw, sizeof(bw), "%d KHz, %u KHz AUTO",
3733 				 freq_range->max_bandwidth_khz,
3734 				 reg_get_max_bandwidth(rd, reg_rule));
3735 		else
3736 			snprintf(bw, sizeof(bw), "%d KHz",
3737 				 freq_range->max_bandwidth_khz);
3738 
3739 		if (reg_rule->flags & NL80211_RRF_DFS)
3740 			scnprintf(cac_time, sizeof(cac_time), "%u s",
3741 				  reg_rule->dfs_cac_ms/1000);
3742 		else
3743 			scnprintf(cac_time, sizeof(cac_time), "N/A");
3744 
3745 
3746 		/*
3747 		 * There may not be documentation for max antenna gain
3748 		 * in certain regions
3749 		 */
3750 		if (power_rule->max_antenna_gain)
3751 			pr_debug("  (%d KHz - %d KHz @ %s), (%d mBi, %d mBm), (%s)\n",
3752 				freq_range->start_freq_khz,
3753 				freq_range->end_freq_khz,
3754 				bw,
3755 				power_rule->max_antenna_gain,
3756 				power_rule->max_eirp,
3757 				cac_time);
3758 		else
3759 			pr_debug("  (%d KHz - %d KHz @ %s), (N/A, %d mBm), (%s)\n",
3760 				freq_range->start_freq_khz,
3761 				freq_range->end_freq_khz,
3762 				bw,
3763 				power_rule->max_eirp,
3764 				cac_time);
3765 	}
3766 }
3767 
reg_supported_dfs_region(enum nl80211_dfs_regions dfs_region)3768 bool reg_supported_dfs_region(enum nl80211_dfs_regions dfs_region)
3769 {
3770 	switch (dfs_region) {
3771 	case NL80211_DFS_UNSET:
3772 	case NL80211_DFS_FCC:
3773 	case NL80211_DFS_ETSI:
3774 	case NL80211_DFS_JP:
3775 		return true;
3776 	default:
3777 		pr_debug("Ignoring unknown DFS master region: %d\n", dfs_region);
3778 		return false;
3779 	}
3780 }
3781 
print_regdomain(const struct ieee80211_regdomain * rd)3782 static void print_regdomain(const struct ieee80211_regdomain *rd)
3783 {
3784 	struct regulatory_request *lr = get_last_request();
3785 
3786 	if (is_intersected_alpha2(rd->alpha2)) {
3787 		if (lr->initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE) {
3788 			struct cfg80211_registered_device *rdev;
3789 			rdev = cfg80211_rdev_by_wiphy_idx(lr->wiphy_idx);
3790 			if (rdev) {
3791 				pr_debug("Current regulatory domain updated by AP to: %c%c\n",
3792 					rdev->country_ie_alpha2[0],
3793 					rdev->country_ie_alpha2[1]);
3794 			} else
3795 				pr_debug("Current regulatory domain intersected:\n");
3796 		} else
3797 			pr_debug("Current regulatory domain intersected:\n");
3798 	} else if (is_world_regdom(rd->alpha2)) {
3799 		pr_debug("World regulatory domain updated:\n");
3800 	} else {
3801 		if (is_unknown_alpha2(rd->alpha2))
3802 			pr_debug("Regulatory domain changed to driver built-in settings (unknown country)\n");
3803 		else {
3804 			if (reg_request_cell_base(lr))
3805 				pr_debug("Regulatory domain changed to country: %c%c by Cell Station\n",
3806 					rd->alpha2[0], rd->alpha2[1]);
3807 			else
3808 				pr_debug("Regulatory domain changed to country: %c%c\n",
3809 					rd->alpha2[0], rd->alpha2[1]);
3810 		}
3811 	}
3812 
3813 	pr_debug(" DFS Master region: %s", reg_dfs_region_str(rd->dfs_region));
3814 	print_rd_rules(rd);
3815 }
3816 
print_regdomain_info(const struct ieee80211_regdomain * rd)3817 static void print_regdomain_info(const struct ieee80211_regdomain *rd)
3818 {
3819 	pr_debug("Regulatory domain: %c%c\n", rd->alpha2[0], rd->alpha2[1]);
3820 	print_rd_rules(rd);
3821 }
3822 
reg_set_rd_core(const struct ieee80211_regdomain * rd)3823 static int reg_set_rd_core(const struct ieee80211_regdomain *rd)
3824 {
3825 	if (!is_world_regdom(rd->alpha2))
3826 		return -EINVAL;
3827 	update_world_regdomain(rd);
3828 	return 0;
3829 }
3830 
reg_set_rd_user(const struct ieee80211_regdomain * rd,struct regulatory_request * user_request)3831 static int reg_set_rd_user(const struct ieee80211_regdomain *rd,
3832 			   struct regulatory_request *user_request)
3833 {
3834 	const struct ieee80211_regdomain *intersected_rd = NULL;
3835 
3836 	if (!regdom_changes(rd->alpha2))
3837 		return -EALREADY;
3838 
3839 	if (!is_valid_rd(rd)) {
3840 		pr_err("Invalid regulatory domain detected: %c%c\n",
3841 		       rd->alpha2[0], rd->alpha2[1]);
3842 		print_regdomain_info(rd);
3843 		return -EINVAL;
3844 	}
3845 
3846 	if (!user_request->intersect) {
3847 		reset_regdomains(false, rd);
3848 		return 0;
3849 	}
3850 
3851 	intersected_rd = regdom_intersect(rd, get_cfg80211_regdom());
3852 	if (!intersected_rd)
3853 		return -EINVAL;
3854 
3855 	kfree(rd);
3856 	rd = NULL;
3857 	reset_regdomains(false, intersected_rd);
3858 
3859 	return 0;
3860 }
3861 
reg_set_rd_driver(const struct ieee80211_regdomain * rd,struct regulatory_request * driver_request)3862 static int reg_set_rd_driver(const struct ieee80211_regdomain *rd,
3863 			     struct regulatory_request *driver_request)
3864 {
3865 	const struct ieee80211_regdomain *regd;
3866 	const struct ieee80211_regdomain *intersected_rd = NULL;
3867 	const struct ieee80211_regdomain *tmp = NULL;
3868 	struct wiphy *request_wiphy;
3869 
3870 	if (is_world_regdom(rd->alpha2))
3871 		return -EINVAL;
3872 
3873 	if (!regdom_changes(rd->alpha2))
3874 		return -EALREADY;
3875 
3876 	if (!is_valid_rd(rd)) {
3877 		pr_err("Invalid regulatory domain detected: %c%c\n",
3878 		       rd->alpha2[0], rd->alpha2[1]);
3879 		print_regdomain_info(rd);
3880 		return -EINVAL;
3881 	}
3882 
3883 	request_wiphy = wiphy_idx_to_wiphy(driver_request->wiphy_idx);
3884 	if (!request_wiphy)
3885 		return -ENODEV;
3886 
3887 	if (!driver_request->intersect) {
3888 		ASSERT_RTNL();
3889 		wiphy_lock(request_wiphy);
3890 		if (request_wiphy->regd)
3891 			tmp = get_wiphy_regdom(request_wiphy);
3892 
3893 		regd = reg_copy_regd(rd);
3894 		if (IS_ERR(regd)) {
3895 			wiphy_unlock(request_wiphy);
3896 			return PTR_ERR(regd);
3897 		}
3898 
3899 		rcu_assign_pointer(request_wiphy->regd, regd);
3900 		rcu_free_regdom(tmp);
3901 		wiphy_unlock(request_wiphy);
3902 		reset_regdomains(false, rd);
3903 		return 0;
3904 	}
3905 
3906 	intersected_rd = regdom_intersect(rd, get_cfg80211_regdom());
3907 	if (!intersected_rd)
3908 		return -EINVAL;
3909 
3910 	/*
3911 	 * We can trash what CRDA provided now.
3912 	 * However if a driver requested this specific regulatory
3913 	 * domain we keep it for its private use
3914 	 */
3915 	tmp = get_wiphy_regdom(request_wiphy);
3916 	rcu_assign_pointer(request_wiphy->regd, rd);
3917 	rcu_free_regdom(tmp);
3918 
3919 	rd = NULL;
3920 
3921 	reset_regdomains(false, intersected_rd);
3922 
3923 	return 0;
3924 }
3925 
reg_set_rd_country_ie(const struct ieee80211_regdomain * rd,struct regulatory_request * country_ie_request)3926 static int reg_set_rd_country_ie(const struct ieee80211_regdomain *rd,
3927 				 struct regulatory_request *country_ie_request)
3928 {
3929 	struct wiphy *request_wiphy;
3930 
3931 	if (!is_alpha2_set(rd->alpha2) && !is_an_alpha2(rd->alpha2) &&
3932 	    !is_unknown_alpha2(rd->alpha2))
3933 		return -EINVAL;
3934 
3935 	/*
3936 	 * Lets only bother proceeding on the same alpha2 if the current
3937 	 * rd is non static (it means CRDA was present and was used last)
3938 	 * and the pending request came in from a country IE
3939 	 */
3940 
3941 	if (!is_valid_rd(rd)) {
3942 		pr_err("Invalid regulatory domain detected: %c%c\n",
3943 		       rd->alpha2[0], rd->alpha2[1]);
3944 		print_regdomain_info(rd);
3945 		return -EINVAL;
3946 	}
3947 
3948 	request_wiphy = wiphy_idx_to_wiphy(country_ie_request->wiphy_idx);
3949 	if (!request_wiphy)
3950 		return -ENODEV;
3951 
3952 	if (country_ie_request->intersect)
3953 		return -EINVAL;
3954 
3955 	reset_regdomains(false, rd);
3956 	return 0;
3957 }
3958 
3959 /*
3960  * Use this call to set the current regulatory domain. Conflicts with
3961  * multiple drivers can be ironed out later. Caller must've already
3962  * kmalloc'd the rd structure.
3963  */
set_regdom(const struct ieee80211_regdomain * rd,enum ieee80211_regd_source regd_src)3964 int set_regdom(const struct ieee80211_regdomain *rd,
3965 	       enum ieee80211_regd_source regd_src)
3966 {
3967 	struct regulatory_request *lr;
3968 	bool user_reset = false;
3969 	int r;
3970 
3971 	if (IS_ERR_OR_NULL(rd))
3972 		return -ENODATA;
3973 
3974 	if (!reg_is_valid_request(rd->alpha2)) {
3975 		kfree(rd);
3976 		return -EINVAL;
3977 	}
3978 
3979 	if (regd_src == REGD_SOURCE_CRDA)
3980 		reset_crda_timeouts();
3981 
3982 	lr = get_last_request();
3983 
3984 	/* Note that this doesn't update the wiphys, this is done below */
3985 	switch (lr->initiator) {
3986 	case NL80211_REGDOM_SET_BY_CORE:
3987 		r = reg_set_rd_core(rd);
3988 		break;
3989 	case NL80211_REGDOM_SET_BY_USER:
3990 		cfg80211_save_user_regdom(rd);
3991 		r = reg_set_rd_user(rd, lr);
3992 		user_reset = true;
3993 		break;
3994 	case NL80211_REGDOM_SET_BY_DRIVER:
3995 		r = reg_set_rd_driver(rd, lr);
3996 		break;
3997 	case NL80211_REGDOM_SET_BY_COUNTRY_IE:
3998 		r = reg_set_rd_country_ie(rd, lr);
3999 		break;
4000 	default:
4001 		WARN(1, "invalid initiator %d\n", lr->initiator);
4002 		kfree(rd);
4003 		return -EINVAL;
4004 	}
4005 
4006 	if (r) {
4007 		switch (r) {
4008 		case -EALREADY:
4009 			reg_set_request_processed();
4010 			break;
4011 		default:
4012 			/* Back to world regulatory in case of errors */
4013 			restore_regulatory_settings(user_reset, false);
4014 		}
4015 
4016 		kfree(rd);
4017 		return r;
4018 	}
4019 
4020 	/* This would make this whole thing pointless */
4021 	if (WARN_ON(!lr->intersect && rd != get_cfg80211_regdom()))
4022 		return -EINVAL;
4023 
4024 	/* update all wiphys now with the new established regulatory domain */
4025 	update_all_wiphy_regulatory(lr->initiator);
4026 
4027 	print_regdomain(get_cfg80211_regdom());
4028 
4029 	nl80211_send_reg_change_event(lr);
4030 
4031 	reg_set_request_processed();
4032 
4033 	return 0;
4034 }
4035 
__regulatory_set_wiphy_regd(struct wiphy * wiphy,struct ieee80211_regdomain * rd)4036 static int __regulatory_set_wiphy_regd(struct wiphy *wiphy,
4037 				       struct ieee80211_regdomain *rd)
4038 {
4039 	const struct ieee80211_regdomain *regd;
4040 	const struct ieee80211_regdomain *prev_regd;
4041 	struct cfg80211_registered_device *rdev;
4042 
4043 	if (WARN_ON(!wiphy || !rd))
4044 		return -EINVAL;
4045 
4046 	if (WARN(!(wiphy->regulatory_flags & REGULATORY_WIPHY_SELF_MANAGED),
4047 		 "wiphy should have REGULATORY_WIPHY_SELF_MANAGED\n"))
4048 		return -EPERM;
4049 
4050 	if (WARN(!is_valid_rd(rd),
4051 		 "Invalid regulatory domain detected: %c%c\n",
4052 		 rd->alpha2[0], rd->alpha2[1])) {
4053 		print_regdomain_info(rd);
4054 		return -EINVAL;
4055 	}
4056 
4057 	regd = reg_copy_regd(rd);
4058 	if (IS_ERR(regd))
4059 		return PTR_ERR(regd);
4060 
4061 	rdev = wiphy_to_rdev(wiphy);
4062 
4063 	spin_lock(®_requests_lock);
4064 	prev_regd = rdev->requested_regd;
4065 	rdev->requested_regd = regd;
4066 	spin_unlock(®_requests_lock);
4067 
4068 	kfree(prev_regd);
4069 	return 0;
4070 }
4071 
regulatory_set_wiphy_regd(struct wiphy * wiphy,struct ieee80211_regdomain * rd)4072 int regulatory_set_wiphy_regd(struct wiphy *wiphy,
4073 			      struct ieee80211_regdomain *rd)
4074 {
4075 	int ret = __regulatory_set_wiphy_regd(wiphy, rd);
4076 
4077 	if (ret)
4078 		return ret;
4079 
4080 	schedule_work(®_work);
4081 	return 0;
4082 }
4083 EXPORT_SYMBOL(regulatory_set_wiphy_regd);
4084 
regulatory_set_wiphy_regd_sync(struct wiphy * wiphy,struct ieee80211_regdomain * rd)4085 int regulatory_set_wiphy_regd_sync(struct wiphy *wiphy,
4086 				   struct ieee80211_regdomain *rd)
4087 {
4088 	int ret;
4089 
4090 	ASSERT_RTNL();
4091 
4092 	ret = __regulatory_set_wiphy_regd(wiphy, rd);
4093 	if (ret)
4094 		return ret;
4095 
4096 	/* process the request immediately */
4097 	reg_process_self_managed_hint(wiphy);
4098 	reg_check_channels();
4099 	return 0;
4100 }
4101 EXPORT_SYMBOL(regulatory_set_wiphy_regd_sync);
4102 
wiphy_regulatory_register(struct wiphy * wiphy)4103 void wiphy_regulatory_register(struct wiphy *wiphy)
4104 {
4105 	struct regulatory_request *lr = get_last_request();
4106 
4107 	/* self-managed devices ignore beacon hints and country IE */
4108 	if (wiphy->regulatory_flags & REGULATORY_WIPHY_SELF_MANAGED) {
4109 		wiphy->regulatory_flags |= REGULATORY_DISABLE_BEACON_HINTS |
4110 					   REGULATORY_COUNTRY_IE_IGNORE;
4111 
4112 		/*
4113 		 * The last request may have been received before this
4114 		 * registration call. Call the driver notifier if
4115 		 * initiator is USER.
4116 		 */
4117 		if (lr->initiator == NL80211_REGDOM_SET_BY_USER)
4118 			reg_call_notifier(wiphy, lr);
4119 	}
4120 
4121 	if (!reg_dev_ignore_cell_hint(wiphy))
4122 		reg_num_devs_support_basehint++;
4123 
4124 	wiphy_update_regulatory(wiphy, lr->initiator);
4125 	wiphy_all_share_dfs_chan_state(wiphy);
4126 	reg_process_self_managed_hints();
4127 }
4128 
wiphy_regulatory_deregister(struct wiphy * wiphy)4129 void wiphy_regulatory_deregister(struct wiphy *wiphy)
4130 {
4131 	struct wiphy *request_wiphy = NULL;
4132 	struct regulatory_request *lr;
4133 
4134 	lr = get_last_request();
4135 
4136 	if (!reg_dev_ignore_cell_hint(wiphy))
4137 		reg_num_devs_support_basehint--;
4138 
4139 	rcu_free_regdom(get_wiphy_regdom(wiphy));
4140 	RCU_INIT_POINTER(wiphy->regd, NULL);
4141 
4142 	if (lr)
4143 		request_wiphy = wiphy_idx_to_wiphy(lr->wiphy_idx);
4144 
4145 	if (!request_wiphy || request_wiphy != wiphy)
4146 		return;
4147 
4148 	lr->wiphy_idx = WIPHY_IDX_INVALID;
4149 	lr->country_ie_env = ENVIRON_ANY;
4150 }
4151 
4152 /*
4153  * See FCC notices for UNII band definitions
4154  *  5GHz: https://www.fcc.gov/document/5-ghz-unlicensed-spectrum-unii
4155  *  6GHz: https://www.fcc.gov/document/fcc-proposes-more-spectrum-unlicensed-use-0
4156  */
cfg80211_get_unii(int freq)4157 int cfg80211_get_unii(int freq)
4158 {
4159 	/* UNII-1 */
4160 	if (freq >= 5150 && freq <= 5250)
4161 		return 0;
4162 
4163 	/* UNII-2A */
4164 	if (freq > 5250 && freq <= 5350)
4165 		return 1;
4166 
4167 	/* UNII-2B */
4168 	if (freq > 5350 && freq <= 5470)
4169 		return 2;
4170 
4171 	/* UNII-2C */
4172 	if (freq > 5470 && freq <= 5725)
4173 		return 3;
4174 
4175 	/* UNII-3 */
4176 	if (freq > 5725 && freq <= 5825)
4177 		return 4;
4178 
4179 	/* UNII-5 */
4180 	if (freq > 5925 && freq <= 6425)
4181 		return 5;
4182 
4183 	/* UNII-6 */
4184 	if (freq > 6425 && freq <= 6525)
4185 		return 6;
4186 
4187 	/* UNII-7 */
4188 	if (freq > 6525 && freq <= 6875)
4189 		return 7;
4190 
4191 	/* UNII-8 */
4192 	if (freq > 6875 && freq <= 7125)
4193 		return 8;
4194 
4195 	return -EINVAL;
4196 }
4197 
regulatory_indoor_allowed(void)4198 bool regulatory_indoor_allowed(void)
4199 {
4200 	return reg_is_indoor;
4201 }
4202 
regulatory_pre_cac_allowed(struct wiphy * wiphy)4203 bool regulatory_pre_cac_allowed(struct wiphy *wiphy)
4204 {
4205 	const struct ieee80211_regdomain *regd = NULL;
4206 	const struct ieee80211_regdomain *wiphy_regd = NULL;
4207 	bool pre_cac_allowed = false;
4208 
4209 	rcu_read_lock();
4210 
4211 	regd = rcu_dereference(cfg80211_regdomain);
4212 	wiphy_regd = rcu_dereference(wiphy->regd);
4213 	if (!wiphy_regd) {
4214 		if (regd->dfs_region == NL80211_DFS_ETSI)
4215 			pre_cac_allowed = true;
4216 
4217 		rcu_read_unlock();
4218 
4219 		return pre_cac_allowed;
4220 	}
4221 
4222 	if (regd->dfs_region == wiphy_regd->dfs_region &&
4223 	    wiphy_regd->dfs_region == NL80211_DFS_ETSI)
4224 		pre_cac_allowed = true;
4225 
4226 	rcu_read_unlock();
4227 
4228 	return pre_cac_allowed;
4229 }
4230 EXPORT_SYMBOL(regulatory_pre_cac_allowed);
4231 
cfg80211_check_and_end_cac(struct cfg80211_registered_device * rdev)4232 static void cfg80211_check_and_end_cac(struct cfg80211_registered_device *rdev)
4233 {
4234 	struct wireless_dev *wdev;
4235 	unsigned int link_id;
4236 
4237 	/* If we finished CAC or received radar, we should end any
4238 	 * CAC running on the same channels.
4239 	 * the check !cfg80211_chandef_dfs_usable contain 2 options:
4240 	 * either all channels are available - those the CAC_FINISHED
4241 	 * event has effected another wdev state, or there is a channel
4242 	 * in unavailable state in wdev chandef - those the RADAR_DETECTED
4243 	 * event has effected another wdev state.
4244 	 * In both cases we should end the CAC on the wdev.
4245 	 */
4246 	list_for_each_entry(wdev, &rdev->wiphy.wdev_list, list) {
4247 		struct cfg80211_chan_def *chandef;
4248 
4249 		for_each_valid_link(wdev, link_id) {
4250 			if (!wdev->links[link_id].cac_started)
4251 				continue;
4252 
4253 			chandef = wdev_chandef(wdev, link_id);
4254 			if (!chandef)
4255 				continue;
4256 
4257 			if (!cfg80211_chandef_dfs_usable(&rdev->wiphy, chandef))
4258 				rdev_end_cac(rdev, wdev->netdev, link_id);
4259 		}
4260 	}
4261 }
4262 
regulatory_propagate_dfs_state(struct wiphy * wiphy,struct cfg80211_chan_def * chandef,enum nl80211_dfs_state dfs_state,enum nl80211_radar_event event)4263 void regulatory_propagate_dfs_state(struct wiphy *wiphy,
4264 				    struct cfg80211_chan_def *chandef,
4265 				    enum nl80211_dfs_state dfs_state,
4266 				    enum nl80211_radar_event event)
4267 {
4268 	struct cfg80211_registered_device *rdev;
4269 
4270 	ASSERT_RTNL();
4271 
4272 	if (WARN_ON(!cfg80211_chandef_valid(chandef)))
4273 		return;
4274 
4275 	for_each_rdev(rdev) {
4276 		if (wiphy == &rdev->wiphy)
4277 			continue;
4278 
4279 		if (!reg_dfs_domain_same(wiphy, &rdev->wiphy))
4280 			continue;
4281 
4282 		if (!ieee80211_get_channel(&rdev->wiphy,
4283 					   chandef->chan->center_freq))
4284 			continue;
4285 
4286 		cfg80211_set_dfs_state(&rdev->wiphy, chandef, dfs_state);
4287 
4288 		if (event == NL80211_RADAR_DETECTED ||
4289 		    event == NL80211_RADAR_CAC_FINISHED) {
4290 			cfg80211_sched_dfs_chan_update(rdev);
4291 			cfg80211_check_and_end_cac(rdev);
4292 		}
4293 
4294 		nl80211_radar_notify(rdev, chandef, event, NULL, GFP_KERNEL);
4295 	}
4296 }
4297 
regulatory_init_db(void)4298 static int __init regulatory_init_db(void)
4299 {
4300 	int err;
4301 
4302 	/*
4303 	 * It's possible that - due to other bugs/issues - cfg80211
4304 	 * never called regulatory_init() below, or that it failed;
4305 	 * in that case, don't try to do any further work here as
4306 	 * it's doomed to lead to crashes.
4307 	 */
4308 	if (IS_ERR_OR_NULL(reg_pdev))
4309 		return -EINVAL;
4310 
4311 	err = load_builtin_regdb_keys();
4312 	if (err) {
4313 		platform_device_unregister(reg_pdev);
4314 		return err;
4315 	}
4316 
4317 	/* We always try to get an update for the static regdomain */
4318 	err = regulatory_hint_core(cfg80211_world_regdom->alpha2);
4319 	if (err) {
4320 		if (err == -ENOMEM) {
4321 			platform_device_unregister(reg_pdev);
4322 			return err;
4323 		}
4324 		/*
4325 		 * N.B. kobject_uevent_env() can fail mainly for when we're out
4326 		 * memory which is handled and propagated appropriately above
4327 		 * but it can also fail during a netlink_broadcast() or during
4328 		 * early boot for call_usermodehelper(). For now treat these
4329 		 * errors as non-fatal.
4330 		 */
4331 		pr_err("kobject_uevent_env() was unable to call CRDA during init\n");
4332 	}
4333 
4334 	/*
4335 	 * Finally, if the user set the module parameter treat it
4336 	 * as a user hint.
4337 	 */
4338 	if (!is_world_regdom(ieee80211_regdom))
4339 		regulatory_hint_user(ieee80211_regdom,
4340 				     NL80211_USER_REG_HINT_USER);
4341 
4342 	return 0;
4343 }
4344 #ifndef MODULE
4345 late_initcall(regulatory_init_db);
4346 #endif
4347 
regulatory_init(void)4348 int __init regulatory_init(void)
4349 {
4350 	reg_pdev = platform_device_register_simple("regulatory", 0, NULL, 0);
4351 	if (IS_ERR(reg_pdev))
4352 		return PTR_ERR(reg_pdev);
4353 
4354 	rcu_assign_pointer(cfg80211_regdomain, cfg80211_world_regdom);
4355 
4356 	user_alpha2[0] = '9';
4357 	user_alpha2[1] = '7';
4358 
4359 #ifdef MODULE
4360 	return regulatory_init_db();
4361 #else
4362 	return 0;
4363 #endif
4364 }
4365 
regulatory_exit(void)4366 void regulatory_exit(void)
4367 {
4368 	struct regulatory_request *reg_request, *tmp;
4369 	struct reg_beacon *reg_beacon, *btmp;
4370 
4371 	cancel_work_sync(®_work);
4372 	cancel_crda_timeout_sync();
4373 	cancel_delayed_work_sync(®_check_chans);
4374 
4375 	/* Lock to suppress warnings */
4376 	rtnl_lock();
4377 	reset_regdomains(true, NULL);
4378 	rtnl_unlock();
4379 
4380 	dev_set_uevent_suppress(®_pdev->dev, true);
4381 
4382 	platform_device_unregister(reg_pdev);
4383 
4384 	list_for_each_entry_safe(reg_beacon, btmp, ®_pending_beacons, list) {
4385 		list_del(®_beacon->list);
4386 		kfree(reg_beacon);
4387 	}
4388 
4389 	list_for_each_entry_safe(reg_beacon, btmp, ®_beacon_list, list) {
4390 		list_del(®_beacon->list);
4391 		kfree(reg_beacon);
4392 	}
4393 
4394 	list_for_each_entry_safe(reg_request, tmp, ®_requests_list, list) {
4395 		list_del(®_request->list);
4396 		kfree(reg_request);
4397 	}
4398 
4399 	if (!IS_ERR_OR_NULL(regdb))
4400 		kfree(regdb);
4401 	if (!IS_ERR_OR_NULL(cfg80211_user_regdom))
4402 		kfree(cfg80211_user_regdom);
4403 
4404 	free_regdb_keyring();
4405 }
4406