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