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