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