xref: /linux/net/wireless/reg.c (revision 9e8ba5f3ec35cba4fd8a8bebda548c4db2651e40)
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	Luis R. Rodriguez <lrodriguz@atheros.com>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License version 2 as
9  * published by the Free Software Foundation.
10  */
11 
12 /**
13  * DOC: Wireless regulatory infrastructure
14  *
15  * The usual implementation is for a driver to read a device EEPROM to
16  * determine which regulatory domain it should be operating under, then
17  * looking up the allowable channels in a driver-local table and finally
18  * registering those channels in the wiphy structure.
19  *
20  * Another set of compliance enforcement is for drivers to use their
21  * own compliance limits which can be stored on the EEPROM. The host
22  * driver or firmware may ensure these are used.
23  *
24  * In addition to all this we provide an extra layer of regulatory
25  * conformance. For drivers which do not have any regulatory
26  * information CRDA provides the complete regulatory solution.
27  * For others it provides a community effort on further restrictions
28  * to enhance compliance.
29  *
30  * Note: When number of rules --> infinity we will not be able to
31  * index on alpha2 any more, instead we'll probably have to
32  * rely on some SHA1 checksum of the regdomain for example.
33  *
34  */
35 
36 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
37 
38 #include <linux/kernel.h>
39 #include <linux/export.h>
40 #include <linux/slab.h>
41 #include <linux/list.h>
42 #include <linux/random.h>
43 #include <linux/ctype.h>
44 #include <linux/nl80211.h>
45 #include <linux/platform_device.h>
46 #include <linux/moduleparam.h>
47 #include <net/cfg80211.h>
48 #include "core.h"
49 #include "reg.h"
50 #include "regdb.h"
51 #include "nl80211.h"
52 
53 #ifdef CONFIG_CFG80211_REG_DEBUG
54 #define REG_DBG_PRINT(format, args...)			\
55 	printk(KERN_DEBUG pr_fmt(format), ##args)
56 #else
57 #define REG_DBG_PRINT(args...)
58 #endif
59 
60 static struct regulatory_request core_request_world = {
61 	.initiator = NL80211_REGDOM_SET_BY_CORE,
62 	.alpha2[0] = '0',
63 	.alpha2[1] = '0',
64 	.intersect = false,
65 	.processed = true,
66 	.country_ie_env = ENVIRON_ANY,
67 };
68 
69 /* Receipt of information from last regulatory request */
70 static struct regulatory_request *last_request = &core_request_world;
71 
72 /* To trigger userspace events */
73 static struct platform_device *reg_pdev;
74 
75 static struct device_type reg_device_type = {
76 	.uevent = reg_device_uevent,
77 };
78 
79 /*
80  * Central wireless core regulatory domains, we only need two,
81  * the current one and a world regulatory domain in case we have no
82  * information to give us an alpha2
83  */
84 const struct ieee80211_regdomain *cfg80211_regdomain;
85 
86 /*
87  * Protects static reg.c components:
88  *     - cfg80211_world_regdom
89  *     - cfg80211_regdom
90  *     - last_request
91  */
92 static DEFINE_MUTEX(reg_mutex);
93 
94 static inline void assert_reg_lock(void)
95 {
96 	lockdep_assert_held(&reg_mutex);
97 }
98 
99 /* Used to queue up regulatory hints */
100 static LIST_HEAD(reg_requests_list);
101 static spinlock_t reg_requests_lock;
102 
103 /* Used to queue up beacon hints for review */
104 static LIST_HEAD(reg_pending_beacons);
105 static spinlock_t reg_pending_beacons_lock;
106 
107 /* Used to keep track of processed beacon hints */
108 static LIST_HEAD(reg_beacon_list);
109 
110 struct reg_beacon {
111 	struct list_head list;
112 	struct ieee80211_channel chan;
113 };
114 
115 static void reg_todo(struct work_struct *work);
116 static DECLARE_WORK(reg_work, reg_todo);
117 
118 static void reg_timeout_work(struct work_struct *work);
119 static DECLARE_DELAYED_WORK(reg_timeout, reg_timeout_work);
120 
121 /* We keep a static world regulatory domain in case of the absence of CRDA */
122 static const struct ieee80211_regdomain world_regdom = {
123 	.n_reg_rules = 5,
124 	.alpha2 =  "00",
125 	.reg_rules = {
126 		/* IEEE 802.11b/g, channels 1..11 */
127 		REG_RULE(2412-10, 2462+10, 40, 6, 20, 0),
128 		/* IEEE 802.11b/g, channels 12..13. No HT40
129 		 * channel fits here. */
130 		REG_RULE(2467-10, 2472+10, 20, 6, 20,
131 			NL80211_RRF_PASSIVE_SCAN |
132 			NL80211_RRF_NO_IBSS),
133 		/* IEEE 802.11 channel 14 - Only JP enables
134 		 * this and for 802.11b only */
135 		REG_RULE(2484-10, 2484+10, 20, 6, 20,
136 			NL80211_RRF_PASSIVE_SCAN |
137 			NL80211_RRF_NO_IBSS |
138 			NL80211_RRF_NO_OFDM),
139 		/* IEEE 802.11a, channel 36..48 */
140 		REG_RULE(5180-10, 5240+10, 40, 6, 20,
141                         NL80211_RRF_PASSIVE_SCAN |
142                         NL80211_RRF_NO_IBSS),
143 
144 		/* NB: 5260 MHz - 5700 MHz requies DFS */
145 
146 		/* IEEE 802.11a, channel 149..165 */
147 		REG_RULE(5745-10, 5825+10, 40, 6, 20,
148 			NL80211_RRF_PASSIVE_SCAN |
149 			NL80211_RRF_NO_IBSS),
150 	}
151 };
152 
153 static const struct ieee80211_regdomain *cfg80211_world_regdom =
154 	&world_regdom;
155 
156 static char *ieee80211_regdom = "00";
157 static char user_alpha2[2];
158 
159 module_param(ieee80211_regdom, charp, 0444);
160 MODULE_PARM_DESC(ieee80211_regdom, "IEEE 802.11 regulatory domain code");
161 
162 static void reset_regdomains(bool full_reset)
163 {
164 	/* avoid freeing static information or freeing something twice */
165 	if (cfg80211_regdomain == cfg80211_world_regdom)
166 		cfg80211_regdomain = NULL;
167 	if (cfg80211_world_regdom == &world_regdom)
168 		cfg80211_world_regdom = NULL;
169 	if (cfg80211_regdomain == &world_regdom)
170 		cfg80211_regdomain = NULL;
171 
172 	kfree(cfg80211_regdomain);
173 	kfree(cfg80211_world_regdom);
174 
175 	cfg80211_world_regdom = &world_regdom;
176 	cfg80211_regdomain = NULL;
177 
178 	if (!full_reset)
179 		return;
180 
181 	if (last_request != &core_request_world)
182 		kfree(last_request);
183 	last_request = &core_request_world;
184 }
185 
186 /*
187  * Dynamic world regulatory domain requested by the wireless
188  * core upon initialization
189  */
190 static void update_world_regdomain(const struct ieee80211_regdomain *rd)
191 {
192 	BUG_ON(!last_request);
193 
194 	reset_regdomains(false);
195 
196 	cfg80211_world_regdom = rd;
197 	cfg80211_regdomain = rd;
198 }
199 
200 bool is_world_regdom(const char *alpha2)
201 {
202 	if (!alpha2)
203 		return false;
204 	if (alpha2[0] == '0' && alpha2[1] == '0')
205 		return true;
206 	return false;
207 }
208 
209 static bool is_alpha2_set(const char *alpha2)
210 {
211 	if (!alpha2)
212 		return false;
213 	if (alpha2[0] != 0 && alpha2[1] != 0)
214 		return true;
215 	return false;
216 }
217 
218 static bool is_unknown_alpha2(const char *alpha2)
219 {
220 	if (!alpha2)
221 		return false;
222 	/*
223 	 * Special case where regulatory domain was built by driver
224 	 * but a specific alpha2 cannot be determined
225 	 */
226 	if (alpha2[0] == '9' && alpha2[1] == '9')
227 		return true;
228 	return false;
229 }
230 
231 static bool is_intersected_alpha2(const char *alpha2)
232 {
233 	if (!alpha2)
234 		return false;
235 	/*
236 	 * Special case where regulatory domain is the
237 	 * result of an intersection between two regulatory domain
238 	 * structures
239 	 */
240 	if (alpha2[0] == '9' && alpha2[1] == '8')
241 		return true;
242 	return false;
243 }
244 
245 static bool is_an_alpha2(const char *alpha2)
246 {
247 	if (!alpha2)
248 		return false;
249 	if (isalpha(alpha2[0]) && isalpha(alpha2[1]))
250 		return true;
251 	return false;
252 }
253 
254 static bool alpha2_equal(const char *alpha2_x, const char *alpha2_y)
255 {
256 	if (!alpha2_x || !alpha2_y)
257 		return false;
258 	if (alpha2_x[0] == alpha2_y[0] &&
259 		alpha2_x[1] == alpha2_y[1])
260 		return true;
261 	return false;
262 }
263 
264 static bool regdom_changes(const char *alpha2)
265 {
266 	assert_cfg80211_lock();
267 
268 	if (!cfg80211_regdomain)
269 		return true;
270 	if (alpha2_equal(cfg80211_regdomain->alpha2, alpha2))
271 		return false;
272 	return true;
273 }
274 
275 /*
276  * The NL80211_REGDOM_SET_BY_USER regdom alpha2 is cached, this lets
277  * you know if a valid regulatory hint with NL80211_REGDOM_SET_BY_USER
278  * has ever been issued.
279  */
280 static bool is_user_regdom_saved(void)
281 {
282 	if (user_alpha2[0] == '9' && user_alpha2[1] == '7')
283 		return false;
284 
285 	/* This would indicate a mistake on the design */
286 	if (WARN((!is_world_regdom(user_alpha2) &&
287 		  !is_an_alpha2(user_alpha2)),
288 		 "Unexpected user alpha2: %c%c\n",
289 		 user_alpha2[0],
290 	         user_alpha2[1]))
291 		return false;
292 
293 	return true;
294 }
295 
296 static int reg_copy_regd(const struct ieee80211_regdomain **dst_regd,
297 			 const struct ieee80211_regdomain *src_regd)
298 {
299 	struct ieee80211_regdomain *regd;
300 	int size_of_regd = 0;
301 	unsigned int i;
302 
303 	size_of_regd = sizeof(struct ieee80211_regdomain) +
304 	  ((src_regd->n_reg_rules + 1) * sizeof(struct ieee80211_reg_rule));
305 
306 	regd = kzalloc(size_of_regd, GFP_KERNEL);
307 	if (!regd)
308 		return -ENOMEM;
309 
310 	memcpy(regd, src_regd, sizeof(struct ieee80211_regdomain));
311 
312 	for (i = 0; i < src_regd->n_reg_rules; i++)
313 		memcpy(&regd->reg_rules[i], &src_regd->reg_rules[i],
314 			sizeof(struct ieee80211_reg_rule));
315 
316 	*dst_regd = regd;
317 	return 0;
318 }
319 
320 #ifdef CONFIG_CFG80211_INTERNAL_REGDB
321 struct reg_regdb_search_request {
322 	char alpha2[2];
323 	struct list_head list;
324 };
325 
326 static LIST_HEAD(reg_regdb_search_list);
327 static DEFINE_MUTEX(reg_regdb_search_mutex);
328 
329 static void reg_regdb_search(struct work_struct *work)
330 {
331 	struct reg_regdb_search_request *request;
332 	const struct ieee80211_regdomain *curdom, *regdom;
333 	int i, r;
334 
335 	mutex_lock(&reg_regdb_search_mutex);
336 	while (!list_empty(&reg_regdb_search_list)) {
337 		request = list_first_entry(&reg_regdb_search_list,
338 					   struct reg_regdb_search_request,
339 					   list);
340 		list_del(&request->list);
341 
342 		for (i=0; i<reg_regdb_size; i++) {
343 			curdom = reg_regdb[i];
344 
345 			if (!memcmp(request->alpha2, curdom->alpha2, 2)) {
346 				r = reg_copy_regd(&regdom, curdom);
347 				if (r)
348 					break;
349 				mutex_lock(&cfg80211_mutex);
350 				set_regdom(regdom);
351 				mutex_unlock(&cfg80211_mutex);
352 				break;
353 			}
354 		}
355 
356 		kfree(request);
357 	}
358 	mutex_unlock(&reg_regdb_search_mutex);
359 }
360 
361 static DECLARE_WORK(reg_regdb_work, reg_regdb_search);
362 
363 static void reg_regdb_query(const char *alpha2)
364 {
365 	struct reg_regdb_search_request *request;
366 
367 	if (!alpha2)
368 		return;
369 
370 	request = kzalloc(sizeof(struct reg_regdb_search_request), GFP_KERNEL);
371 	if (!request)
372 		return;
373 
374 	memcpy(request->alpha2, alpha2, 2);
375 
376 	mutex_lock(&reg_regdb_search_mutex);
377 	list_add_tail(&request->list, &reg_regdb_search_list);
378 	mutex_unlock(&reg_regdb_search_mutex);
379 
380 	schedule_work(&reg_regdb_work);
381 }
382 #else
383 static inline void reg_regdb_query(const char *alpha2) {}
384 #endif /* CONFIG_CFG80211_INTERNAL_REGDB */
385 
386 /*
387  * This lets us keep regulatory code which is updated on a regulatory
388  * basis in userspace. Country information is filled in by
389  * reg_device_uevent
390  */
391 static int call_crda(const char *alpha2)
392 {
393 	if (!is_world_regdom((char *) alpha2))
394 		pr_info("Calling CRDA for country: %c%c\n",
395 			alpha2[0], alpha2[1]);
396 	else
397 		pr_info("Calling CRDA to update world regulatory domain\n");
398 
399 	/* query internal regulatory database (if it exists) */
400 	reg_regdb_query(alpha2);
401 
402 	return kobject_uevent(&reg_pdev->dev.kobj, KOBJ_CHANGE);
403 }
404 
405 /* Used by nl80211 before kmalloc'ing our regulatory domain */
406 bool reg_is_valid_request(const char *alpha2)
407 {
408 	assert_cfg80211_lock();
409 
410 	if (!last_request)
411 		return false;
412 
413 	return alpha2_equal(last_request->alpha2, alpha2);
414 }
415 
416 /* Sanity check on a regulatory rule */
417 static bool is_valid_reg_rule(const struct ieee80211_reg_rule *rule)
418 {
419 	const struct ieee80211_freq_range *freq_range = &rule->freq_range;
420 	u32 freq_diff;
421 
422 	if (freq_range->start_freq_khz <= 0 || freq_range->end_freq_khz <= 0)
423 		return false;
424 
425 	if (freq_range->start_freq_khz > freq_range->end_freq_khz)
426 		return false;
427 
428 	freq_diff = freq_range->end_freq_khz - freq_range->start_freq_khz;
429 
430 	if (freq_range->end_freq_khz <= freq_range->start_freq_khz ||
431 			freq_range->max_bandwidth_khz > freq_diff)
432 		return false;
433 
434 	return true;
435 }
436 
437 static bool is_valid_rd(const struct ieee80211_regdomain *rd)
438 {
439 	const struct ieee80211_reg_rule *reg_rule = NULL;
440 	unsigned int i;
441 
442 	if (!rd->n_reg_rules)
443 		return false;
444 
445 	if (WARN_ON(rd->n_reg_rules > NL80211_MAX_SUPP_REG_RULES))
446 		return false;
447 
448 	for (i = 0; i < rd->n_reg_rules; i++) {
449 		reg_rule = &rd->reg_rules[i];
450 		if (!is_valid_reg_rule(reg_rule))
451 			return false;
452 	}
453 
454 	return true;
455 }
456 
457 static bool reg_does_bw_fit(const struct ieee80211_freq_range *freq_range,
458 			    u32 center_freq_khz,
459 			    u32 bw_khz)
460 {
461 	u32 start_freq_khz, end_freq_khz;
462 
463 	start_freq_khz = center_freq_khz - (bw_khz/2);
464 	end_freq_khz = center_freq_khz + (bw_khz/2);
465 
466 	if (start_freq_khz >= freq_range->start_freq_khz &&
467 	    end_freq_khz <= freq_range->end_freq_khz)
468 		return true;
469 
470 	return false;
471 }
472 
473 /**
474  * freq_in_rule_band - tells us if a frequency is in a frequency band
475  * @freq_range: frequency rule we want to query
476  * @freq_khz: frequency we are inquiring about
477  *
478  * This lets us know if a specific frequency rule is or is not relevant to
479  * a specific frequency's band. Bands are device specific and artificial
480  * definitions (the "2.4 GHz band" and the "5 GHz band"), however it is
481  * safe for now to assume that a frequency rule should not be part of a
482  * frequency's band if the start freq or end freq are off by more than 2 GHz.
483  * This resolution can be lowered and should be considered as we add
484  * regulatory rule support for other "bands".
485  **/
486 static bool freq_in_rule_band(const struct ieee80211_freq_range *freq_range,
487 	u32 freq_khz)
488 {
489 #define ONE_GHZ_IN_KHZ	1000000
490 	if (abs(freq_khz - freq_range->start_freq_khz) <= (2 * ONE_GHZ_IN_KHZ))
491 		return true;
492 	if (abs(freq_khz - freq_range->end_freq_khz) <= (2 * ONE_GHZ_IN_KHZ))
493 		return true;
494 	return false;
495 #undef ONE_GHZ_IN_KHZ
496 }
497 
498 /*
499  * Helper for regdom_intersect(), this does the real
500  * mathematical intersection fun
501  */
502 static int reg_rules_intersect(
503 	const struct ieee80211_reg_rule *rule1,
504 	const struct ieee80211_reg_rule *rule2,
505 	struct ieee80211_reg_rule *intersected_rule)
506 {
507 	const struct ieee80211_freq_range *freq_range1, *freq_range2;
508 	struct ieee80211_freq_range *freq_range;
509 	const struct ieee80211_power_rule *power_rule1, *power_rule2;
510 	struct ieee80211_power_rule *power_rule;
511 	u32 freq_diff;
512 
513 	freq_range1 = &rule1->freq_range;
514 	freq_range2 = &rule2->freq_range;
515 	freq_range = &intersected_rule->freq_range;
516 
517 	power_rule1 = &rule1->power_rule;
518 	power_rule2 = &rule2->power_rule;
519 	power_rule = &intersected_rule->power_rule;
520 
521 	freq_range->start_freq_khz = max(freq_range1->start_freq_khz,
522 		freq_range2->start_freq_khz);
523 	freq_range->end_freq_khz = min(freq_range1->end_freq_khz,
524 		freq_range2->end_freq_khz);
525 	freq_range->max_bandwidth_khz = min(freq_range1->max_bandwidth_khz,
526 		freq_range2->max_bandwidth_khz);
527 
528 	freq_diff = freq_range->end_freq_khz - freq_range->start_freq_khz;
529 	if (freq_range->max_bandwidth_khz > freq_diff)
530 		freq_range->max_bandwidth_khz = freq_diff;
531 
532 	power_rule->max_eirp = min(power_rule1->max_eirp,
533 		power_rule2->max_eirp);
534 	power_rule->max_antenna_gain = min(power_rule1->max_antenna_gain,
535 		power_rule2->max_antenna_gain);
536 
537 	intersected_rule->flags = (rule1->flags | rule2->flags);
538 
539 	if (!is_valid_reg_rule(intersected_rule))
540 		return -EINVAL;
541 
542 	return 0;
543 }
544 
545 /**
546  * regdom_intersect - do the intersection between two regulatory domains
547  * @rd1: first regulatory domain
548  * @rd2: second regulatory domain
549  *
550  * Use this function to get the intersection between two regulatory domains.
551  * Once completed we will mark the alpha2 for the rd as intersected, "98",
552  * as no one single alpha2 can represent this regulatory domain.
553  *
554  * Returns a pointer to the regulatory domain structure which will hold the
555  * resulting intersection of rules between rd1 and rd2. We will
556  * kzalloc() this structure for you.
557  */
558 static struct ieee80211_regdomain *regdom_intersect(
559 	const struct ieee80211_regdomain *rd1,
560 	const struct ieee80211_regdomain *rd2)
561 {
562 	int r, size_of_regd;
563 	unsigned int x, y;
564 	unsigned int num_rules = 0, rule_idx = 0;
565 	const struct ieee80211_reg_rule *rule1, *rule2;
566 	struct ieee80211_reg_rule *intersected_rule;
567 	struct ieee80211_regdomain *rd;
568 	/* This is just a dummy holder to help us count */
569 	struct ieee80211_reg_rule irule;
570 
571 	/* Uses the stack temporarily for counter arithmetic */
572 	intersected_rule = &irule;
573 
574 	memset(intersected_rule, 0, sizeof(struct ieee80211_reg_rule));
575 
576 	if (!rd1 || !rd2)
577 		return NULL;
578 
579 	/*
580 	 * First we get a count of the rules we'll need, then we actually
581 	 * build them. This is to so we can malloc() and free() a
582 	 * regdomain once. The reason we use reg_rules_intersect() here
583 	 * is it will return -EINVAL if the rule computed makes no sense.
584 	 * All rules that do check out OK are valid.
585 	 */
586 
587 	for (x = 0; x < rd1->n_reg_rules; x++) {
588 		rule1 = &rd1->reg_rules[x];
589 		for (y = 0; y < rd2->n_reg_rules; y++) {
590 			rule2 = &rd2->reg_rules[y];
591 			if (!reg_rules_intersect(rule1, rule2,
592 					intersected_rule))
593 				num_rules++;
594 			memset(intersected_rule, 0,
595 					sizeof(struct ieee80211_reg_rule));
596 		}
597 	}
598 
599 	if (!num_rules)
600 		return NULL;
601 
602 	size_of_regd = sizeof(struct ieee80211_regdomain) +
603 		((num_rules + 1) * sizeof(struct ieee80211_reg_rule));
604 
605 	rd = kzalloc(size_of_regd, GFP_KERNEL);
606 	if (!rd)
607 		return NULL;
608 
609 	for (x = 0; x < rd1->n_reg_rules; x++) {
610 		rule1 = &rd1->reg_rules[x];
611 		for (y = 0; y < rd2->n_reg_rules; y++) {
612 			rule2 = &rd2->reg_rules[y];
613 			/*
614 			 * This time around instead of using the stack lets
615 			 * write to the target rule directly saving ourselves
616 			 * a memcpy()
617 			 */
618 			intersected_rule = &rd->reg_rules[rule_idx];
619 			r = reg_rules_intersect(rule1, rule2,
620 				intersected_rule);
621 			/*
622 			 * No need to memset here the intersected rule here as
623 			 * we're not using the stack anymore
624 			 */
625 			if (r)
626 				continue;
627 			rule_idx++;
628 		}
629 	}
630 
631 	if (rule_idx != num_rules) {
632 		kfree(rd);
633 		return NULL;
634 	}
635 
636 	rd->n_reg_rules = num_rules;
637 	rd->alpha2[0] = '9';
638 	rd->alpha2[1] = '8';
639 
640 	return rd;
641 }
642 
643 /*
644  * XXX: add support for the rest of enum nl80211_reg_rule_flags, we may
645  * want to just have the channel structure use these
646  */
647 static u32 map_regdom_flags(u32 rd_flags)
648 {
649 	u32 channel_flags = 0;
650 	if (rd_flags & NL80211_RRF_PASSIVE_SCAN)
651 		channel_flags |= IEEE80211_CHAN_PASSIVE_SCAN;
652 	if (rd_flags & NL80211_RRF_NO_IBSS)
653 		channel_flags |= IEEE80211_CHAN_NO_IBSS;
654 	if (rd_flags & NL80211_RRF_DFS)
655 		channel_flags |= IEEE80211_CHAN_RADAR;
656 	return channel_flags;
657 }
658 
659 static int freq_reg_info_regd(struct wiphy *wiphy,
660 			      u32 center_freq,
661 			      u32 desired_bw_khz,
662 			      const struct ieee80211_reg_rule **reg_rule,
663 			      const struct ieee80211_regdomain *custom_regd)
664 {
665 	int i;
666 	bool band_rule_found = false;
667 	const struct ieee80211_regdomain *regd;
668 	bool bw_fits = false;
669 
670 	if (!desired_bw_khz)
671 		desired_bw_khz = MHZ_TO_KHZ(20);
672 
673 	regd = custom_regd ? custom_regd : cfg80211_regdomain;
674 
675 	/*
676 	 * Follow the driver's regulatory domain, if present, unless a country
677 	 * IE has been processed or a user wants to help complaince further
678 	 */
679 	if (!custom_regd &&
680 	    last_request->initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE &&
681 	    last_request->initiator != NL80211_REGDOM_SET_BY_USER &&
682 	    wiphy->regd)
683 		regd = wiphy->regd;
684 
685 	if (!regd)
686 		return -EINVAL;
687 
688 	for (i = 0; i < regd->n_reg_rules; i++) {
689 		const struct ieee80211_reg_rule *rr;
690 		const struct ieee80211_freq_range *fr = NULL;
691 
692 		rr = &regd->reg_rules[i];
693 		fr = &rr->freq_range;
694 
695 		/*
696 		 * We only need to know if one frequency rule was
697 		 * was in center_freq's band, that's enough, so lets
698 		 * not overwrite it once found
699 		 */
700 		if (!band_rule_found)
701 			band_rule_found = freq_in_rule_band(fr, center_freq);
702 
703 		bw_fits = reg_does_bw_fit(fr,
704 					  center_freq,
705 					  desired_bw_khz);
706 
707 		if (band_rule_found && bw_fits) {
708 			*reg_rule = rr;
709 			return 0;
710 		}
711 	}
712 
713 	if (!band_rule_found)
714 		return -ERANGE;
715 
716 	return -EINVAL;
717 }
718 
719 int freq_reg_info(struct wiphy *wiphy,
720 		  u32 center_freq,
721 		  u32 desired_bw_khz,
722 		  const struct ieee80211_reg_rule **reg_rule)
723 {
724 	assert_cfg80211_lock();
725 	return freq_reg_info_regd(wiphy,
726 				  center_freq,
727 				  desired_bw_khz,
728 				  reg_rule,
729 				  NULL);
730 }
731 EXPORT_SYMBOL(freq_reg_info);
732 
733 #ifdef CONFIG_CFG80211_REG_DEBUG
734 static const char *reg_initiator_name(enum nl80211_reg_initiator initiator)
735 {
736 	switch (initiator) {
737 	case NL80211_REGDOM_SET_BY_CORE:
738 		return "Set by core";
739 	case NL80211_REGDOM_SET_BY_USER:
740 		return "Set by user";
741 	case NL80211_REGDOM_SET_BY_DRIVER:
742 		return "Set by driver";
743 	case NL80211_REGDOM_SET_BY_COUNTRY_IE:
744 		return "Set by country IE";
745 	default:
746 		WARN_ON(1);
747 		return "Set by bug";
748 	}
749 }
750 
751 static void chan_reg_rule_print_dbg(struct ieee80211_channel *chan,
752 				    u32 desired_bw_khz,
753 				    const struct ieee80211_reg_rule *reg_rule)
754 {
755 	const struct ieee80211_power_rule *power_rule;
756 	const struct ieee80211_freq_range *freq_range;
757 	char max_antenna_gain[32];
758 
759 	power_rule = &reg_rule->power_rule;
760 	freq_range = &reg_rule->freq_range;
761 
762 	if (!power_rule->max_antenna_gain)
763 		snprintf(max_antenna_gain, 32, "N/A");
764 	else
765 		snprintf(max_antenna_gain, 32, "%d", power_rule->max_antenna_gain);
766 
767 	REG_DBG_PRINT("Updating information on frequency %d MHz "
768 		      "for a %d MHz width channel with regulatory rule:\n",
769 		      chan->center_freq,
770 		      KHZ_TO_MHZ(desired_bw_khz));
771 
772 	REG_DBG_PRINT("%d KHz - %d KHz @ %d KHz), (%s mBi, %d mBm)\n",
773 		      freq_range->start_freq_khz,
774 		      freq_range->end_freq_khz,
775 		      freq_range->max_bandwidth_khz,
776 		      max_antenna_gain,
777 		      power_rule->max_eirp);
778 }
779 #else
780 static void chan_reg_rule_print_dbg(struct ieee80211_channel *chan,
781 				    u32 desired_bw_khz,
782 				    const struct ieee80211_reg_rule *reg_rule)
783 {
784 	return;
785 }
786 #endif
787 
788 /*
789  * Note that right now we assume the desired channel bandwidth
790  * is always 20 MHz for each individual channel (HT40 uses 20 MHz
791  * per channel, the primary and the extension channel). To support
792  * smaller custom bandwidths such as 5 MHz or 10 MHz we'll need a
793  * new ieee80211_channel.target_bw and re run the regulatory check
794  * on the wiphy with the target_bw specified. Then we can simply use
795  * that below for the desired_bw_khz below.
796  */
797 static void handle_channel(struct wiphy *wiphy,
798 			   enum nl80211_reg_initiator initiator,
799 			   enum ieee80211_band band,
800 			   unsigned int chan_idx)
801 {
802 	int r;
803 	u32 flags, bw_flags = 0;
804 	u32 desired_bw_khz = MHZ_TO_KHZ(20);
805 	const struct ieee80211_reg_rule *reg_rule = NULL;
806 	const struct ieee80211_power_rule *power_rule = NULL;
807 	const struct ieee80211_freq_range *freq_range = NULL;
808 	struct ieee80211_supported_band *sband;
809 	struct ieee80211_channel *chan;
810 	struct wiphy *request_wiphy = NULL;
811 
812 	assert_cfg80211_lock();
813 
814 	request_wiphy = wiphy_idx_to_wiphy(last_request->wiphy_idx);
815 
816 	sband = wiphy->bands[band];
817 	BUG_ON(chan_idx >= sband->n_channels);
818 	chan = &sband->channels[chan_idx];
819 
820 	flags = chan->orig_flags;
821 
822 	r = freq_reg_info(wiphy,
823 			  MHZ_TO_KHZ(chan->center_freq),
824 			  desired_bw_khz,
825 			  &reg_rule);
826 
827 	if (r) {
828 		/*
829 		 * We will disable all channels that do not match our
830 		 * received regulatory rule unless the hint is coming
831 		 * from a Country IE and the Country IE had no information
832 		 * about a band. The IEEE 802.11 spec allows for an AP
833 		 * to send only a subset of the regulatory rules allowed,
834 		 * so an AP in the US that only supports 2.4 GHz may only send
835 		 * a country IE with information for the 2.4 GHz band
836 		 * while 5 GHz is still supported.
837 		 */
838 		if (initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE &&
839 		    r == -ERANGE)
840 			return;
841 
842 		REG_DBG_PRINT("Disabling freq %d MHz\n", chan->center_freq);
843 		chan->flags = IEEE80211_CHAN_DISABLED;
844 		return;
845 	}
846 
847 	chan_reg_rule_print_dbg(chan, desired_bw_khz, reg_rule);
848 
849 	power_rule = &reg_rule->power_rule;
850 	freq_range = &reg_rule->freq_range;
851 
852 	if (freq_range->max_bandwidth_khz < MHZ_TO_KHZ(40))
853 		bw_flags = IEEE80211_CHAN_NO_HT40;
854 
855 	if (last_request->initiator == NL80211_REGDOM_SET_BY_DRIVER &&
856 	    request_wiphy && request_wiphy == wiphy &&
857 	    request_wiphy->flags & WIPHY_FLAG_STRICT_REGULATORY) {
858 		/*
859 		 * This guarantees the driver's requested regulatory domain
860 		 * will always be used as a base for further regulatory
861 		 * settings
862 		 */
863 		chan->flags = chan->orig_flags =
864 			map_regdom_flags(reg_rule->flags) | bw_flags;
865 		chan->max_antenna_gain = chan->orig_mag =
866 			(int) MBI_TO_DBI(power_rule->max_antenna_gain);
867 		chan->max_power = chan->orig_mpwr =
868 			(int) MBM_TO_DBM(power_rule->max_eirp);
869 		return;
870 	}
871 
872 	chan->beacon_found = false;
873 	chan->flags = flags | bw_flags | map_regdom_flags(reg_rule->flags);
874 	chan->max_antenna_gain = min(chan->orig_mag,
875 		(int) MBI_TO_DBI(power_rule->max_antenna_gain));
876 	if (chan->orig_mpwr) {
877 		/*
878 		 * Devices that have their own custom regulatory domain
879 		 * but also use WIPHY_FLAG_STRICT_REGULATORY will follow the
880 		 * passed country IE power settings.
881 		 */
882 		if (initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE &&
883 		    wiphy->flags & WIPHY_FLAG_CUSTOM_REGULATORY &&
884 		    wiphy->flags & WIPHY_FLAG_STRICT_REGULATORY) {
885 			chan->max_power =
886 				MBM_TO_DBM(power_rule->max_eirp);
887 		} else {
888 			chan->max_power = min(chan->orig_mpwr,
889 				(int) MBM_TO_DBM(power_rule->max_eirp));
890 		}
891 	} else
892 		chan->max_power = (int) MBM_TO_DBM(power_rule->max_eirp);
893 }
894 
895 static void handle_band(struct wiphy *wiphy,
896 			enum ieee80211_band band,
897 			enum nl80211_reg_initiator initiator)
898 {
899 	unsigned int i;
900 	struct ieee80211_supported_band *sband;
901 
902 	BUG_ON(!wiphy->bands[band]);
903 	sband = wiphy->bands[band];
904 
905 	for (i = 0; i < sband->n_channels; i++)
906 		handle_channel(wiphy, initiator, band, i);
907 }
908 
909 static bool ignore_reg_update(struct wiphy *wiphy,
910 			      enum nl80211_reg_initiator initiator)
911 {
912 	if (!last_request) {
913 		REG_DBG_PRINT("Ignoring regulatory request %s since "
914 			      "last_request is not set\n",
915 			      reg_initiator_name(initiator));
916 		return true;
917 	}
918 
919 	if (initiator == NL80211_REGDOM_SET_BY_CORE &&
920 	    wiphy->flags & WIPHY_FLAG_CUSTOM_REGULATORY) {
921 		REG_DBG_PRINT("Ignoring regulatory request %s "
922 			      "since the driver uses its own custom "
923 			      "regulatory domain\n",
924 			      reg_initiator_name(initiator));
925 		return true;
926 	}
927 
928 	/*
929 	 * wiphy->regd will be set once the device has its own
930 	 * desired regulatory domain set
931 	 */
932 	if (wiphy->flags & WIPHY_FLAG_STRICT_REGULATORY && !wiphy->regd &&
933 	    initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE &&
934 	    !is_world_regdom(last_request->alpha2)) {
935 		REG_DBG_PRINT("Ignoring regulatory request %s "
936 			      "since the driver requires its own regulatory "
937 			      "domain to be set first\n",
938 			      reg_initiator_name(initiator));
939 		return true;
940 	}
941 
942 	return false;
943 }
944 
945 static void handle_reg_beacon(struct wiphy *wiphy,
946 			      unsigned int chan_idx,
947 			      struct reg_beacon *reg_beacon)
948 {
949 	struct ieee80211_supported_band *sband;
950 	struct ieee80211_channel *chan;
951 	bool channel_changed = false;
952 	struct ieee80211_channel chan_before;
953 
954 	assert_cfg80211_lock();
955 
956 	sband = wiphy->bands[reg_beacon->chan.band];
957 	chan = &sband->channels[chan_idx];
958 
959 	if (likely(chan->center_freq != reg_beacon->chan.center_freq))
960 		return;
961 
962 	if (chan->beacon_found)
963 		return;
964 
965 	chan->beacon_found = true;
966 
967 	if (wiphy->flags & WIPHY_FLAG_DISABLE_BEACON_HINTS)
968 		return;
969 
970 	chan_before.center_freq = chan->center_freq;
971 	chan_before.flags = chan->flags;
972 
973 	if (chan->flags & IEEE80211_CHAN_PASSIVE_SCAN) {
974 		chan->flags &= ~IEEE80211_CHAN_PASSIVE_SCAN;
975 		channel_changed = true;
976 	}
977 
978 	if (chan->flags & IEEE80211_CHAN_NO_IBSS) {
979 		chan->flags &= ~IEEE80211_CHAN_NO_IBSS;
980 		channel_changed = true;
981 	}
982 
983 	if (channel_changed)
984 		nl80211_send_beacon_hint_event(wiphy, &chan_before, chan);
985 }
986 
987 /*
988  * Called when a scan on a wiphy finds a beacon on
989  * new channel
990  */
991 static void wiphy_update_new_beacon(struct wiphy *wiphy,
992 				    struct reg_beacon *reg_beacon)
993 {
994 	unsigned int i;
995 	struct ieee80211_supported_band *sband;
996 
997 	assert_cfg80211_lock();
998 
999 	if (!wiphy->bands[reg_beacon->chan.band])
1000 		return;
1001 
1002 	sband = wiphy->bands[reg_beacon->chan.band];
1003 
1004 	for (i = 0; i < sband->n_channels; i++)
1005 		handle_reg_beacon(wiphy, i, reg_beacon);
1006 }
1007 
1008 /*
1009  * Called upon reg changes or a new wiphy is added
1010  */
1011 static void wiphy_update_beacon_reg(struct wiphy *wiphy)
1012 {
1013 	unsigned int i;
1014 	struct ieee80211_supported_band *sband;
1015 	struct reg_beacon *reg_beacon;
1016 
1017 	assert_cfg80211_lock();
1018 
1019 	if (list_empty(&reg_beacon_list))
1020 		return;
1021 
1022 	list_for_each_entry(reg_beacon, &reg_beacon_list, list) {
1023 		if (!wiphy->bands[reg_beacon->chan.band])
1024 			continue;
1025 		sband = wiphy->bands[reg_beacon->chan.band];
1026 		for (i = 0; i < sband->n_channels; i++)
1027 			handle_reg_beacon(wiphy, i, reg_beacon);
1028 	}
1029 }
1030 
1031 static bool reg_is_world_roaming(struct wiphy *wiphy)
1032 {
1033 	if (is_world_regdom(cfg80211_regdomain->alpha2) ||
1034 	    (wiphy->regd && is_world_regdom(wiphy->regd->alpha2)))
1035 		return true;
1036 	if (last_request &&
1037 	    last_request->initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE &&
1038 	    wiphy->flags & WIPHY_FLAG_CUSTOM_REGULATORY)
1039 		return true;
1040 	return false;
1041 }
1042 
1043 /* Reap the advantages of previously found beacons */
1044 static void reg_process_beacons(struct wiphy *wiphy)
1045 {
1046 	/*
1047 	 * Means we are just firing up cfg80211, so no beacons would
1048 	 * have been processed yet.
1049 	 */
1050 	if (!last_request)
1051 		return;
1052 	if (!reg_is_world_roaming(wiphy))
1053 		return;
1054 	wiphy_update_beacon_reg(wiphy);
1055 }
1056 
1057 static bool is_ht40_not_allowed(struct ieee80211_channel *chan)
1058 {
1059 	if (!chan)
1060 		return true;
1061 	if (chan->flags & IEEE80211_CHAN_DISABLED)
1062 		return true;
1063 	/* This would happen when regulatory rules disallow HT40 completely */
1064 	if (IEEE80211_CHAN_NO_HT40 == (chan->flags & (IEEE80211_CHAN_NO_HT40)))
1065 		return true;
1066 	return false;
1067 }
1068 
1069 static void reg_process_ht_flags_channel(struct wiphy *wiphy,
1070 					 enum ieee80211_band band,
1071 					 unsigned int chan_idx)
1072 {
1073 	struct ieee80211_supported_band *sband;
1074 	struct ieee80211_channel *channel;
1075 	struct ieee80211_channel *channel_before = NULL, *channel_after = NULL;
1076 	unsigned int i;
1077 
1078 	assert_cfg80211_lock();
1079 
1080 	sband = wiphy->bands[band];
1081 	BUG_ON(chan_idx >= sband->n_channels);
1082 	channel = &sband->channels[chan_idx];
1083 
1084 	if (is_ht40_not_allowed(channel)) {
1085 		channel->flags |= IEEE80211_CHAN_NO_HT40;
1086 		return;
1087 	}
1088 
1089 	/*
1090 	 * We need to ensure the extension channels exist to
1091 	 * be able to use HT40- or HT40+, this finds them (or not)
1092 	 */
1093 	for (i = 0; i < sband->n_channels; i++) {
1094 		struct ieee80211_channel *c = &sband->channels[i];
1095 		if (c->center_freq == (channel->center_freq - 20))
1096 			channel_before = c;
1097 		if (c->center_freq == (channel->center_freq + 20))
1098 			channel_after = c;
1099 	}
1100 
1101 	/*
1102 	 * Please note that this assumes target bandwidth is 20 MHz,
1103 	 * if that ever changes we also need to change the below logic
1104 	 * to include that as well.
1105 	 */
1106 	if (is_ht40_not_allowed(channel_before))
1107 		channel->flags |= IEEE80211_CHAN_NO_HT40MINUS;
1108 	else
1109 		channel->flags &= ~IEEE80211_CHAN_NO_HT40MINUS;
1110 
1111 	if (is_ht40_not_allowed(channel_after))
1112 		channel->flags |= IEEE80211_CHAN_NO_HT40PLUS;
1113 	else
1114 		channel->flags &= ~IEEE80211_CHAN_NO_HT40PLUS;
1115 }
1116 
1117 static void reg_process_ht_flags_band(struct wiphy *wiphy,
1118 				      enum ieee80211_band band)
1119 {
1120 	unsigned int i;
1121 	struct ieee80211_supported_band *sband;
1122 
1123 	BUG_ON(!wiphy->bands[band]);
1124 	sband = wiphy->bands[band];
1125 
1126 	for (i = 0; i < sband->n_channels; i++)
1127 		reg_process_ht_flags_channel(wiphy, band, i);
1128 }
1129 
1130 static void reg_process_ht_flags(struct wiphy *wiphy)
1131 {
1132 	enum ieee80211_band band;
1133 
1134 	if (!wiphy)
1135 		return;
1136 
1137 	for (band = 0; band < IEEE80211_NUM_BANDS; band++) {
1138 		if (wiphy->bands[band])
1139 			reg_process_ht_flags_band(wiphy, band);
1140 	}
1141 
1142 }
1143 
1144 static void wiphy_update_regulatory(struct wiphy *wiphy,
1145 				    enum nl80211_reg_initiator initiator)
1146 {
1147 	enum ieee80211_band band;
1148 
1149 	assert_reg_lock();
1150 
1151 	if (ignore_reg_update(wiphy, initiator))
1152 		return;
1153 
1154 	last_request->dfs_region = cfg80211_regdomain->dfs_region;
1155 
1156 	for (band = 0; band < IEEE80211_NUM_BANDS; band++) {
1157 		if (wiphy->bands[band])
1158 			handle_band(wiphy, band, initiator);
1159 	}
1160 
1161 	reg_process_beacons(wiphy);
1162 	reg_process_ht_flags(wiphy);
1163 	if (wiphy->reg_notifier)
1164 		wiphy->reg_notifier(wiphy, last_request);
1165 }
1166 
1167 void regulatory_update(struct wiphy *wiphy,
1168 		       enum nl80211_reg_initiator setby)
1169 {
1170 	mutex_lock(&reg_mutex);
1171 	wiphy_update_regulatory(wiphy, setby);
1172 	mutex_unlock(&reg_mutex);
1173 }
1174 
1175 static void update_all_wiphy_regulatory(enum nl80211_reg_initiator initiator)
1176 {
1177 	struct cfg80211_registered_device *rdev;
1178 	struct wiphy *wiphy;
1179 
1180 	list_for_each_entry(rdev, &cfg80211_rdev_list, list) {
1181 		wiphy = &rdev->wiphy;
1182 		wiphy_update_regulatory(wiphy, initiator);
1183 		/*
1184 		 * Regulatory updates set by CORE are ignored for custom
1185 		 * regulatory cards. Let us notify the changes to the driver,
1186 		 * as some drivers used this to restore its orig_* reg domain.
1187 		 */
1188 		if (initiator == NL80211_REGDOM_SET_BY_CORE &&
1189 		    wiphy->flags & WIPHY_FLAG_CUSTOM_REGULATORY &&
1190 		    wiphy->reg_notifier)
1191 			wiphy->reg_notifier(wiphy, last_request);
1192 	}
1193 }
1194 
1195 static void handle_channel_custom(struct wiphy *wiphy,
1196 				  enum ieee80211_band band,
1197 				  unsigned int chan_idx,
1198 				  const struct ieee80211_regdomain *regd)
1199 {
1200 	int r;
1201 	u32 desired_bw_khz = MHZ_TO_KHZ(20);
1202 	u32 bw_flags = 0;
1203 	const struct ieee80211_reg_rule *reg_rule = NULL;
1204 	const struct ieee80211_power_rule *power_rule = NULL;
1205 	const struct ieee80211_freq_range *freq_range = NULL;
1206 	struct ieee80211_supported_band *sband;
1207 	struct ieee80211_channel *chan;
1208 
1209 	assert_reg_lock();
1210 
1211 	sband = wiphy->bands[band];
1212 	BUG_ON(chan_idx >= sband->n_channels);
1213 	chan = &sband->channels[chan_idx];
1214 
1215 	r = freq_reg_info_regd(wiphy,
1216 			       MHZ_TO_KHZ(chan->center_freq),
1217 			       desired_bw_khz,
1218 			       &reg_rule,
1219 			       regd);
1220 
1221 	if (r) {
1222 		REG_DBG_PRINT("Disabling freq %d MHz as custom "
1223 			      "regd has no rule that fits a %d MHz "
1224 			      "wide channel\n",
1225 			      chan->center_freq,
1226 			      KHZ_TO_MHZ(desired_bw_khz));
1227 		chan->flags = IEEE80211_CHAN_DISABLED;
1228 		return;
1229 	}
1230 
1231 	chan_reg_rule_print_dbg(chan, desired_bw_khz, reg_rule);
1232 
1233 	power_rule = &reg_rule->power_rule;
1234 	freq_range = &reg_rule->freq_range;
1235 
1236 	if (freq_range->max_bandwidth_khz < MHZ_TO_KHZ(40))
1237 		bw_flags = IEEE80211_CHAN_NO_HT40;
1238 
1239 	chan->flags |= map_regdom_flags(reg_rule->flags) | bw_flags;
1240 	chan->max_antenna_gain = (int) MBI_TO_DBI(power_rule->max_antenna_gain);
1241 	chan->max_power = (int) MBM_TO_DBM(power_rule->max_eirp);
1242 }
1243 
1244 static void handle_band_custom(struct wiphy *wiphy, enum ieee80211_band band,
1245 			       const struct ieee80211_regdomain *regd)
1246 {
1247 	unsigned int i;
1248 	struct ieee80211_supported_band *sband;
1249 
1250 	BUG_ON(!wiphy->bands[band]);
1251 	sband = wiphy->bands[band];
1252 
1253 	for (i = 0; i < sband->n_channels; i++)
1254 		handle_channel_custom(wiphy, band, i, regd);
1255 }
1256 
1257 /* Used by drivers prior to wiphy registration */
1258 void wiphy_apply_custom_regulatory(struct wiphy *wiphy,
1259 				   const struct ieee80211_regdomain *regd)
1260 {
1261 	enum ieee80211_band band;
1262 	unsigned int bands_set = 0;
1263 
1264 	mutex_lock(&reg_mutex);
1265 	for (band = 0; band < IEEE80211_NUM_BANDS; band++) {
1266 		if (!wiphy->bands[band])
1267 			continue;
1268 		handle_band_custom(wiphy, band, regd);
1269 		bands_set++;
1270 	}
1271 	mutex_unlock(&reg_mutex);
1272 
1273 	/*
1274 	 * no point in calling this if it won't have any effect
1275 	 * on your device's supportd bands.
1276 	 */
1277 	WARN_ON(!bands_set);
1278 }
1279 EXPORT_SYMBOL(wiphy_apply_custom_regulatory);
1280 
1281 /*
1282  * Return value which can be used by ignore_request() to indicate
1283  * it has been determined we should intersect two regulatory domains
1284  */
1285 #define REG_INTERSECT	1
1286 
1287 /* This has the logic which determines when a new request
1288  * should be ignored. */
1289 static int ignore_request(struct wiphy *wiphy,
1290 			  struct regulatory_request *pending_request)
1291 {
1292 	struct wiphy *last_wiphy = NULL;
1293 
1294 	assert_cfg80211_lock();
1295 
1296 	/* All initial requests are respected */
1297 	if (!last_request)
1298 		return 0;
1299 
1300 	switch (pending_request->initiator) {
1301 	case NL80211_REGDOM_SET_BY_CORE:
1302 		return 0;
1303 	case NL80211_REGDOM_SET_BY_COUNTRY_IE:
1304 
1305 		last_wiphy = wiphy_idx_to_wiphy(last_request->wiphy_idx);
1306 
1307 		if (unlikely(!is_an_alpha2(pending_request->alpha2)))
1308 			return -EINVAL;
1309 		if (last_request->initiator ==
1310 		    NL80211_REGDOM_SET_BY_COUNTRY_IE) {
1311 			if (last_wiphy != wiphy) {
1312 				/*
1313 				 * Two cards with two APs claiming different
1314 				 * Country IE alpha2s. We could
1315 				 * intersect them, but that seems unlikely
1316 				 * to be correct. Reject second one for now.
1317 				 */
1318 				if (regdom_changes(pending_request->alpha2))
1319 					return -EOPNOTSUPP;
1320 				return -EALREADY;
1321 			}
1322 			/*
1323 			 * Two consecutive Country IE hints on the same wiphy.
1324 			 * This should be picked up early by the driver/stack
1325 			 */
1326 			if (WARN_ON(regdom_changes(pending_request->alpha2)))
1327 				return 0;
1328 			return -EALREADY;
1329 		}
1330 		return 0;
1331 	case NL80211_REGDOM_SET_BY_DRIVER:
1332 		if (last_request->initiator == NL80211_REGDOM_SET_BY_CORE) {
1333 			if (regdom_changes(pending_request->alpha2))
1334 				return 0;
1335 			return -EALREADY;
1336 		}
1337 
1338 		/*
1339 		 * This would happen if you unplug and plug your card
1340 		 * back in or if you add a new device for which the previously
1341 		 * loaded card also agrees on the regulatory domain.
1342 		 */
1343 		if (last_request->initiator == NL80211_REGDOM_SET_BY_DRIVER &&
1344 		    !regdom_changes(pending_request->alpha2))
1345 			return -EALREADY;
1346 
1347 		return REG_INTERSECT;
1348 	case NL80211_REGDOM_SET_BY_USER:
1349 		if (last_request->initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE)
1350 			return REG_INTERSECT;
1351 		/*
1352 		 * If the user knows better the user should set the regdom
1353 		 * to their country before the IE is picked up
1354 		 */
1355 		if (last_request->initiator == NL80211_REGDOM_SET_BY_USER &&
1356 			  last_request->intersect)
1357 			return -EOPNOTSUPP;
1358 		/*
1359 		 * Process user requests only after previous user/driver/core
1360 		 * requests have been processed
1361 		 */
1362 		if (last_request->initiator == NL80211_REGDOM_SET_BY_CORE ||
1363 		    last_request->initiator == NL80211_REGDOM_SET_BY_DRIVER ||
1364 		    last_request->initiator == NL80211_REGDOM_SET_BY_USER) {
1365 			if (regdom_changes(last_request->alpha2))
1366 				return -EAGAIN;
1367 		}
1368 
1369 		if (!regdom_changes(pending_request->alpha2))
1370 			return -EALREADY;
1371 
1372 		return 0;
1373 	}
1374 
1375 	return -EINVAL;
1376 }
1377 
1378 static void reg_set_request_processed(void)
1379 {
1380 	bool need_more_processing = false;
1381 
1382 	last_request->processed = true;
1383 
1384 	spin_lock(&reg_requests_lock);
1385 	if (!list_empty(&reg_requests_list))
1386 		need_more_processing = true;
1387 	spin_unlock(&reg_requests_lock);
1388 
1389 	if (last_request->initiator == NL80211_REGDOM_SET_BY_USER)
1390 		cancel_delayed_work_sync(&reg_timeout);
1391 
1392 	if (need_more_processing)
1393 		schedule_work(&reg_work);
1394 }
1395 
1396 /**
1397  * __regulatory_hint - hint to the wireless core a regulatory domain
1398  * @wiphy: if the hint comes from country information from an AP, this
1399  *	is required to be set to the wiphy that received the information
1400  * @pending_request: the regulatory request currently being processed
1401  *
1402  * The Wireless subsystem can use this function to hint to the wireless core
1403  * what it believes should be the current regulatory domain.
1404  *
1405  * Returns zero if all went fine, %-EALREADY if a regulatory domain had
1406  * already been set or other standard error codes.
1407  *
1408  * Caller must hold &cfg80211_mutex and &reg_mutex
1409  */
1410 static int __regulatory_hint(struct wiphy *wiphy,
1411 			     struct regulatory_request *pending_request)
1412 {
1413 	bool intersect = false;
1414 	int r = 0;
1415 
1416 	assert_cfg80211_lock();
1417 
1418 	r = ignore_request(wiphy, pending_request);
1419 
1420 	if (r == REG_INTERSECT) {
1421 		if (pending_request->initiator ==
1422 		    NL80211_REGDOM_SET_BY_DRIVER) {
1423 			r = reg_copy_regd(&wiphy->regd, cfg80211_regdomain);
1424 			if (r) {
1425 				kfree(pending_request);
1426 				return r;
1427 			}
1428 		}
1429 		intersect = true;
1430 	} else if (r) {
1431 		/*
1432 		 * If the regulatory domain being requested by the
1433 		 * driver has already been set just copy it to the
1434 		 * wiphy
1435 		 */
1436 		if (r == -EALREADY &&
1437 		    pending_request->initiator ==
1438 		    NL80211_REGDOM_SET_BY_DRIVER) {
1439 			r = reg_copy_regd(&wiphy->regd, cfg80211_regdomain);
1440 			if (r) {
1441 				kfree(pending_request);
1442 				return r;
1443 			}
1444 			r = -EALREADY;
1445 			goto new_request;
1446 		}
1447 		kfree(pending_request);
1448 		return r;
1449 	}
1450 
1451 new_request:
1452 	if (last_request != &core_request_world)
1453 		kfree(last_request);
1454 
1455 	last_request = pending_request;
1456 	last_request->intersect = intersect;
1457 
1458 	pending_request = NULL;
1459 
1460 	if (last_request->initiator == NL80211_REGDOM_SET_BY_USER) {
1461 		user_alpha2[0] = last_request->alpha2[0];
1462 		user_alpha2[1] = last_request->alpha2[1];
1463 	}
1464 
1465 	/* When r == REG_INTERSECT we do need to call CRDA */
1466 	if (r < 0) {
1467 		/*
1468 		 * Since CRDA will not be called in this case as we already
1469 		 * have applied the requested regulatory domain before we just
1470 		 * inform userspace we have processed the request
1471 		 */
1472 		if (r == -EALREADY) {
1473 			nl80211_send_reg_change_event(last_request);
1474 			reg_set_request_processed();
1475 		}
1476 		return r;
1477 	}
1478 
1479 	return call_crda(last_request->alpha2);
1480 }
1481 
1482 /* This processes *all* regulatory hints */
1483 static void reg_process_hint(struct regulatory_request *reg_request)
1484 {
1485 	int r = 0;
1486 	struct wiphy *wiphy = NULL;
1487 	enum nl80211_reg_initiator initiator = reg_request->initiator;
1488 
1489 	BUG_ON(!reg_request->alpha2);
1490 
1491 	if (wiphy_idx_valid(reg_request->wiphy_idx))
1492 		wiphy = wiphy_idx_to_wiphy(reg_request->wiphy_idx);
1493 
1494 	if (reg_request->initiator == NL80211_REGDOM_SET_BY_DRIVER &&
1495 	    !wiphy) {
1496 		kfree(reg_request);
1497 		return;
1498 	}
1499 
1500 	r = __regulatory_hint(wiphy, reg_request);
1501 	/* This is required so that the orig_* parameters are saved */
1502 	if (r == -EALREADY && wiphy &&
1503 	    wiphy->flags & WIPHY_FLAG_STRICT_REGULATORY) {
1504 		wiphy_update_regulatory(wiphy, initiator);
1505 		return;
1506 	}
1507 
1508 	/*
1509 	 * We only time out user hints, given that they should be the only
1510 	 * source of bogus requests.
1511 	 */
1512 	if (r != -EALREADY &&
1513 	    reg_request->initiator == NL80211_REGDOM_SET_BY_USER)
1514 		schedule_delayed_work(&reg_timeout, msecs_to_jiffies(3142));
1515 }
1516 
1517 /*
1518  * Processes regulatory hints, this is all the NL80211_REGDOM_SET_BY_*
1519  * Regulatory hints come on a first come first serve basis and we
1520  * must process each one atomically.
1521  */
1522 static void reg_process_pending_hints(void)
1523 {
1524 	struct regulatory_request *reg_request;
1525 
1526 	mutex_lock(&cfg80211_mutex);
1527 	mutex_lock(&reg_mutex);
1528 
1529 	/* When last_request->processed becomes true this will be rescheduled */
1530 	if (last_request && !last_request->processed) {
1531 		REG_DBG_PRINT("Pending regulatory request, waiting "
1532 			      "for it to be processed...\n");
1533 		goto out;
1534 	}
1535 
1536 	spin_lock(&reg_requests_lock);
1537 
1538 	if (list_empty(&reg_requests_list)) {
1539 		spin_unlock(&reg_requests_lock);
1540 		goto out;
1541 	}
1542 
1543 	reg_request = list_first_entry(&reg_requests_list,
1544 				       struct regulatory_request,
1545 				       list);
1546 	list_del_init(&reg_request->list);
1547 
1548 	spin_unlock(&reg_requests_lock);
1549 
1550 	reg_process_hint(reg_request);
1551 
1552 out:
1553 	mutex_unlock(&reg_mutex);
1554 	mutex_unlock(&cfg80211_mutex);
1555 }
1556 
1557 /* Processes beacon hints -- this has nothing to do with country IEs */
1558 static void reg_process_pending_beacon_hints(void)
1559 {
1560 	struct cfg80211_registered_device *rdev;
1561 	struct reg_beacon *pending_beacon, *tmp;
1562 
1563 	/*
1564 	 * No need to hold the reg_mutex here as we just touch wiphys
1565 	 * and do not read or access regulatory variables.
1566 	 */
1567 	mutex_lock(&cfg80211_mutex);
1568 
1569 	/* This goes through the _pending_ beacon list */
1570 	spin_lock_bh(&reg_pending_beacons_lock);
1571 
1572 	if (list_empty(&reg_pending_beacons)) {
1573 		spin_unlock_bh(&reg_pending_beacons_lock);
1574 		goto out;
1575 	}
1576 
1577 	list_for_each_entry_safe(pending_beacon, tmp,
1578 				 &reg_pending_beacons, list) {
1579 
1580 		list_del_init(&pending_beacon->list);
1581 
1582 		/* Applies the beacon hint to current wiphys */
1583 		list_for_each_entry(rdev, &cfg80211_rdev_list, list)
1584 			wiphy_update_new_beacon(&rdev->wiphy, pending_beacon);
1585 
1586 		/* Remembers the beacon hint for new wiphys or reg changes */
1587 		list_add_tail(&pending_beacon->list, &reg_beacon_list);
1588 	}
1589 
1590 	spin_unlock_bh(&reg_pending_beacons_lock);
1591 out:
1592 	mutex_unlock(&cfg80211_mutex);
1593 }
1594 
1595 static void reg_todo(struct work_struct *work)
1596 {
1597 	reg_process_pending_hints();
1598 	reg_process_pending_beacon_hints();
1599 }
1600 
1601 static void queue_regulatory_request(struct regulatory_request *request)
1602 {
1603 	if (isalpha(request->alpha2[0]))
1604 		request->alpha2[0] = toupper(request->alpha2[0]);
1605 	if (isalpha(request->alpha2[1]))
1606 		request->alpha2[1] = toupper(request->alpha2[1]);
1607 
1608 	spin_lock(&reg_requests_lock);
1609 	list_add_tail(&request->list, &reg_requests_list);
1610 	spin_unlock(&reg_requests_lock);
1611 
1612 	schedule_work(&reg_work);
1613 }
1614 
1615 /*
1616  * Core regulatory hint -- happens during cfg80211_init()
1617  * and when we restore regulatory settings.
1618  */
1619 static int regulatory_hint_core(const char *alpha2)
1620 {
1621 	struct regulatory_request *request;
1622 
1623 	request = kzalloc(sizeof(struct regulatory_request),
1624 			  GFP_KERNEL);
1625 	if (!request)
1626 		return -ENOMEM;
1627 
1628 	request->alpha2[0] = alpha2[0];
1629 	request->alpha2[1] = alpha2[1];
1630 	request->initiator = NL80211_REGDOM_SET_BY_CORE;
1631 
1632 	queue_regulatory_request(request);
1633 
1634 	return 0;
1635 }
1636 
1637 /* User hints */
1638 int regulatory_hint_user(const char *alpha2)
1639 {
1640 	struct regulatory_request *request;
1641 
1642 	BUG_ON(!alpha2);
1643 
1644 	request = kzalloc(sizeof(struct regulatory_request), GFP_KERNEL);
1645 	if (!request)
1646 		return -ENOMEM;
1647 
1648 	request->wiphy_idx = WIPHY_IDX_STALE;
1649 	request->alpha2[0] = alpha2[0];
1650 	request->alpha2[1] = alpha2[1];
1651 	request->initiator = NL80211_REGDOM_SET_BY_USER;
1652 
1653 	queue_regulatory_request(request);
1654 
1655 	return 0;
1656 }
1657 
1658 /* Driver hints */
1659 int regulatory_hint(struct wiphy *wiphy, const char *alpha2)
1660 {
1661 	struct regulatory_request *request;
1662 
1663 	BUG_ON(!alpha2);
1664 	BUG_ON(!wiphy);
1665 
1666 	request = kzalloc(sizeof(struct regulatory_request), GFP_KERNEL);
1667 	if (!request)
1668 		return -ENOMEM;
1669 
1670 	request->wiphy_idx = get_wiphy_idx(wiphy);
1671 
1672 	/* Must have registered wiphy first */
1673 	BUG_ON(!wiphy_idx_valid(request->wiphy_idx));
1674 
1675 	request->alpha2[0] = alpha2[0];
1676 	request->alpha2[1] = alpha2[1];
1677 	request->initiator = NL80211_REGDOM_SET_BY_DRIVER;
1678 
1679 	queue_regulatory_request(request);
1680 
1681 	return 0;
1682 }
1683 EXPORT_SYMBOL(regulatory_hint);
1684 
1685 /*
1686  * We hold wdev_lock() here so we cannot hold cfg80211_mutex() and
1687  * therefore cannot iterate over the rdev list here.
1688  */
1689 void regulatory_hint_11d(struct wiphy *wiphy,
1690 			 enum ieee80211_band band,
1691 			 u8 *country_ie,
1692 			 u8 country_ie_len)
1693 {
1694 	char alpha2[2];
1695 	enum environment_cap env = ENVIRON_ANY;
1696 	struct regulatory_request *request;
1697 
1698 	mutex_lock(&reg_mutex);
1699 
1700 	if (unlikely(!last_request))
1701 		goto out;
1702 
1703 	/* IE len must be evenly divisible by 2 */
1704 	if (country_ie_len & 0x01)
1705 		goto out;
1706 
1707 	if (country_ie_len < IEEE80211_COUNTRY_IE_MIN_LEN)
1708 		goto out;
1709 
1710 	alpha2[0] = country_ie[0];
1711 	alpha2[1] = country_ie[1];
1712 
1713 	if (country_ie[2] == 'I')
1714 		env = ENVIRON_INDOOR;
1715 	else if (country_ie[2] == 'O')
1716 		env = ENVIRON_OUTDOOR;
1717 
1718 	/*
1719 	 * We will run this only upon a successful connection on cfg80211.
1720 	 * We leave conflict resolution to the workqueue, where can hold
1721 	 * cfg80211_mutex.
1722 	 */
1723 	if (likely(last_request->initiator ==
1724 	    NL80211_REGDOM_SET_BY_COUNTRY_IE &&
1725 	    wiphy_idx_valid(last_request->wiphy_idx)))
1726 		goto out;
1727 
1728 	request = kzalloc(sizeof(struct regulatory_request), GFP_KERNEL);
1729 	if (!request)
1730 		goto out;
1731 
1732 	request->wiphy_idx = get_wiphy_idx(wiphy);
1733 	request->alpha2[0] = alpha2[0];
1734 	request->alpha2[1] = alpha2[1];
1735 	request->initiator = NL80211_REGDOM_SET_BY_COUNTRY_IE;
1736 	request->country_ie_env = env;
1737 
1738 	mutex_unlock(&reg_mutex);
1739 
1740 	queue_regulatory_request(request);
1741 
1742 	return;
1743 
1744 out:
1745 	mutex_unlock(&reg_mutex);
1746 }
1747 
1748 static void restore_alpha2(char *alpha2, bool reset_user)
1749 {
1750 	/* indicates there is no alpha2 to consider for restoration */
1751 	alpha2[0] = '9';
1752 	alpha2[1] = '7';
1753 
1754 	/* The user setting has precedence over the module parameter */
1755 	if (is_user_regdom_saved()) {
1756 		/* Unless we're asked to ignore it and reset it */
1757 		if (reset_user) {
1758 			REG_DBG_PRINT("Restoring regulatory settings "
1759 			       "including user preference\n");
1760 			user_alpha2[0] = '9';
1761 			user_alpha2[1] = '7';
1762 
1763 			/*
1764 			 * If we're ignoring user settings, we still need to
1765 			 * check the module parameter to ensure we put things
1766 			 * back as they were for a full restore.
1767 			 */
1768 			if (!is_world_regdom(ieee80211_regdom)) {
1769 				REG_DBG_PRINT("Keeping preference on "
1770 				       "module parameter ieee80211_regdom: %c%c\n",
1771 				       ieee80211_regdom[0],
1772 				       ieee80211_regdom[1]);
1773 				alpha2[0] = ieee80211_regdom[0];
1774 				alpha2[1] = ieee80211_regdom[1];
1775 			}
1776 		} else {
1777 			REG_DBG_PRINT("Restoring regulatory settings "
1778 			       "while preserving user preference for: %c%c\n",
1779 			       user_alpha2[0],
1780 			       user_alpha2[1]);
1781 			alpha2[0] = user_alpha2[0];
1782 			alpha2[1] = user_alpha2[1];
1783 		}
1784 	} else if (!is_world_regdom(ieee80211_regdom)) {
1785 		REG_DBG_PRINT("Keeping preference on "
1786 		       "module parameter ieee80211_regdom: %c%c\n",
1787 		       ieee80211_regdom[0],
1788 		       ieee80211_regdom[1]);
1789 		alpha2[0] = ieee80211_regdom[0];
1790 		alpha2[1] = ieee80211_regdom[1];
1791 	} else
1792 		REG_DBG_PRINT("Restoring regulatory settings\n");
1793 }
1794 
1795 static void restore_custom_reg_settings(struct wiphy *wiphy)
1796 {
1797 	struct ieee80211_supported_band *sband;
1798 	enum ieee80211_band band;
1799 	struct ieee80211_channel *chan;
1800 	int i;
1801 
1802 	for (band = 0; band < IEEE80211_NUM_BANDS; band++) {
1803 		sband = wiphy->bands[band];
1804 		if (!sband)
1805 			continue;
1806 		for (i = 0; i < sband->n_channels; i++) {
1807 			chan = &sband->channels[i];
1808 			chan->flags = chan->orig_flags;
1809 			chan->max_antenna_gain = chan->orig_mag;
1810 			chan->max_power = chan->orig_mpwr;
1811 		}
1812 	}
1813 }
1814 
1815 /*
1816  * Restoring regulatory settings involves ingoring any
1817  * possibly stale country IE information and user regulatory
1818  * settings if so desired, this includes any beacon hints
1819  * learned as we could have traveled outside to another country
1820  * after disconnection. To restore regulatory settings we do
1821  * exactly what we did at bootup:
1822  *
1823  *   - send a core regulatory hint
1824  *   - send a user regulatory hint if applicable
1825  *
1826  * Device drivers that send a regulatory hint for a specific country
1827  * keep their own regulatory domain on wiphy->regd so that does does
1828  * not need to be remembered.
1829  */
1830 static void restore_regulatory_settings(bool reset_user)
1831 {
1832 	char alpha2[2];
1833 	struct reg_beacon *reg_beacon, *btmp;
1834 	struct regulatory_request *reg_request, *tmp;
1835 	LIST_HEAD(tmp_reg_req_list);
1836 	struct cfg80211_registered_device *rdev;
1837 
1838 	mutex_lock(&cfg80211_mutex);
1839 	mutex_lock(&reg_mutex);
1840 
1841 	reset_regdomains(true);
1842 	restore_alpha2(alpha2, reset_user);
1843 
1844 	/*
1845 	 * If there's any pending requests we simply
1846 	 * stash them to a temporary pending queue and
1847 	 * add then after we've restored regulatory
1848 	 * settings.
1849 	 */
1850 	spin_lock(&reg_requests_lock);
1851 	if (!list_empty(&reg_requests_list)) {
1852 		list_for_each_entry_safe(reg_request, tmp,
1853 					 &reg_requests_list, list) {
1854 			if (reg_request->initiator !=
1855 			    NL80211_REGDOM_SET_BY_USER)
1856 				continue;
1857 			list_del(&reg_request->list);
1858 			list_add_tail(&reg_request->list, &tmp_reg_req_list);
1859 		}
1860 	}
1861 	spin_unlock(&reg_requests_lock);
1862 
1863 	/* Clear beacon hints */
1864 	spin_lock_bh(&reg_pending_beacons_lock);
1865 	if (!list_empty(&reg_pending_beacons)) {
1866 		list_for_each_entry_safe(reg_beacon, btmp,
1867 					 &reg_pending_beacons, list) {
1868 			list_del(&reg_beacon->list);
1869 			kfree(reg_beacon);
1870 		}
1871 	}
1872 	spin_unlock_bh(&reg_pending_beacons_lock);
1873 
1874 	if (!list_empty(&reg_beacon_list)) {
1875 		list_for_each_entry_safe(reg_beacon, btmp,
1876 					 &reg_beacon_list, list) {
1877 			list_del(&reg_beacon->list);
1878 			kfree(reg_beacon);
1879 		}
1880 	}
1881 
1882 	/* First restore to the basic regulatory settings */
1883 	cfg80211_regdomain = cfg80211_world_regdom;
1884 
1885 	list_for_each_entry(rdev, &cfg80211_rdev_list, list) {
1886 		if (rdev->wiphy.flags & WIPHY_FLAG_CUSTOM_REGULATORY)
1887 			restore_custom_reg_settings(&rdev->wiphy);
1888 	}
1889 
1890 	mutex_unlock(&reg_mutex);
1891 	mutex_unlock(&cfg80211_mutex);
1892 
1893 	regulatory_hint_core(cfg80211_regdomain->alpha2);
1894 
1895 	/*
1896 	 * This restores the ieee80211_regdom module parameter
1897 	 * preference or the last user requested regulatory
1898 	 * settings, user regulatory settings takes precedence.
1899 	 */
1900 	if (is_an_alpha2(alpha2))
1901 		regulatory_hint_user(user_alpha2);
1902 
1903 	if (list_empty(&tmp_reg_req_list))
1904 		return;
1905 
1906 	mutex_lock(&cfg80211_mutex);
1907 	mutex_lock(&reg_mutex);
1908 
1909 	spin_lock(&reg_requests_lock);
1910 	list_for_each_entry_safe(reg_request, tmp, &tmp_reg_req_list, list) {
1911 		REG_DBG_PRINT("Adding request for country %c%c back "
1912 			      "into the queue\n",
1913 			      reg_request->alpha2[0],
1914 			      reg_request->alpha2[1]);
1915 		list_del(&reg_request->list);
1916 		list_add_tail(&reg_request->list, &reg_requests_list);
1917 	}
1918 	spin_unlock(&reg_requests_lock);
1919 
1920 	mutex_unlock(&reg_mutex);
1921 	mutex_unlock(&cfg80211_mutex);
1922 
1923 	REG_DBG_PRINT("Kicking the queue\n");
1924 
1925 	schedule_work(&reg_work);
1926 }
1927 
1928 void regulatory_hint_disconnect(void)
1929 {
1930 	REG_DBG_PRINT("All devices are disconnected, going to "
1931 		      "restore regulatory settings\n");
1932 	restore_regulatory_settings(false);
1933 }
1934 
1935 static bool freq_is_chan_12_13_14(u16 freq)
1936 {
1937 	if (freq == ieee80211_channel_to_frequency(12, IEEE80211_BAND_2GHZ) ||
1938 	    freq == ieee80211_channel_to_frequency(13, IEEE80211_BAND_2GHZ) ||
1939 	    freq == ieee80211_channel_to_frequency(14, IEEE80211_BAND_2GHZ))
1940 		return true;
1941 	return false;
1942 }
1943 
1944 int regulatory_hint_found_beacon(struct wiphy *wiphy,
1945 				 struct ieee80211_channel *beacon_chan,
1946 				 gfp_t gfp)
1947 {
1948 	struct reg_beacon *reg_beacon;
1949 
1950 	if (likely((beacon_chan->beacon_found ||
1951 	    (beacon_chan->flags & IEEE80211_CHAN_RADAR) ||
1952 	    (beacon_chan->band == IEEE80211_BAND_2GHZ &&
1953 	     !freq_is_chan_12_13_14(beacon_chan->center_freq)))))
1954 		return 0;
1955 
1956 	reg_beacon = kzalloc(sizeof(struct reg_beacon), gfp);
1957 	if (!reg_beacon)
1958 		return -ENOMEM;
1959 
1960 	REG_DBG_PRINT("Found new beacon on "
1961 		      "frequency: %d MHz (Ch %d) on %s\n",
1962 		      beacon_chan->center_freq,
1963 		      ieee80211_frequency_to_channel(beacon_chan->center_freq),
1964 		      wiphy_name(wiphy));
1965 
1966 	memcpy(&reg_beacon->chan, beacon_chan,
1967 		sizeof(struct ieee80211_channel));
1968 
1969 
1970 	/*
1971 	 * Since we can be called from BH or and non-BH context
1972 	 * we must use spin_lock_bh()
1973 	 */
1974 	spin_lock_bh(&reg_pending_beacons_lock);
1975 	list_add_tail(&reg_beacon->list, &reg_pending_beacons);
1976 	spin_unlock_bh(&reg_pending_beacons_lock);
1977 
1978 	schedule_work(&reg_work);
1979 
1980 	return 0;
1981 }
1982 
1983 static void print_rd_rules(const struct ieee80211_regdomain *rd)
1984 {
1985 	unsigned int i;
1986 	const struct ieee80211_reg_rule *reg_rule = NULL;
1987 	const struct ieee80211_freq_range *freq_range = NULL;
1988 	const struct ieee80211_power_rule *power_rule = NULL;
1989 
1990 	pr_info("    (start_freq - end_freq @ bandwidth), (max_antenna_gain, max_eirp)\n");
1991 
1992 	for (i = 0; i < rd->n_reg_rules; i++) {
1993 		reg_rule = &rd->reg_rules[i];
1994 		freq_range = &reg_rule->freq_range;
1995 		power_rule = &reg_rule->power_rule;
1996 
1997 		/*
1998 		 * There may not be documentation for max antenna gain
1999 		 * in certain regions
2000 		 */
2001 		if (power_rule->max_antenna_gain)
2002 			pr_info("    (%d KHz - %d KHz @ %d KHz), (%d mBi, %d mBm)\n",
2003 				freq_range->start_freq_khz,
2004 				freq_range->end_freq_khz,
2005 				freq_range->max_bandwidth_khz,
2006 				power_rule->max_antenna_gain,
2007 				power_rule->max_eirp);
2008 		else
2009 			pr_info("    (%d KHz - %d KHz @ %d KHz), (N/A, %d mBm)\n",
2010 				freq_range->start_freq_khz,
2011 				freq_range->end_freq_khz,
2012 				freq_range->max_bandwidth_khz,
2013 				power_rule->max_eirp);
2014 	}
2015 }
2016 
2017 bool reg_supported_dfs_region(u8 dfs_region)
2018 {
2019 	switch (dfs_region) {
2020 	case NL80211_DFS_UNSET:
2021 	case NL80211_DFS_FCC:
2022 	case NL80211_DFS_ETSI:
2023 	case NL80211_DFS_JP:
2024 		return true;
2025 	default:
2026 		REG_DBG_PRINT("Ignoring uknown DFS master region: %d\n",
2027 			      dfs_region);
2028 		return false;
2029 	}
2030 }
2031 
2032 static void print_dfs_region(u8 dfs_region)
2033 {
2034 	if (!dfs_region)
2035 		return;
2036 
2037 	switch (dfs_region) {
2038 	case NL80211_DFS_FCC:
2039 		pr_info(" DFS Master region FCC");
2040 		break;
2041 	case NL80211_DFS_ETSI:
2042 		pr_info(" DFS Master region ETSI");
2043 		break;
2044 	case NL80211_DFS_JP:
2045 		pr_info(" DFS Master region JP");
2046 		break;
2047 	default:
2048 		pr_info(" DFS Master region Uknown");
2049 		break;
2050 	}
2051 }
2052 
2053 static void print_regdomain(const struct ieee80211_regdomain *rd)
2054 {
2055 
2056 	if (is_intersected_alpha2(rd->alpha2)) {
2057 
2058 		if (last_request->initiator ==
2059 		    NL80211_REGDOM_SET_BY_COUNTRY_IE) {
2060 			struct cfg80211_registered_device *rdev;
2061 			rdev = cfg80211_rdev_by_wiphy_idx(
2062 				last_request->wiphy_idx);
2063 			if (rdev) {
2064 				pr_info("Current regulatory domain updated by AP to: %c%c\n",
2065 					rdev->country_ie_alpha2[0],
2066 					rdev->country_ie_alpha2[1]);
2067 			} else
2068 				pr_info("Current regulatory domain intersected:\n");
2069 		} else
2070 			pr_info("Current regulatory domain intersected:\n");
2071 	} else if (is_world_regdom(rd->alpha2))
2072 		pr_info("World regulatory domain updated:\n");
2073 	else {
2074 		if (is_unknown_alpha2(rd->alpha2))
2075 			pr_info("Regulatory domain changed to driver built-in settings (unknown country)\n");
2076 		else
2077 			pr_info("Regulatory domain changed to country: %c%c\n",
2078 				rd->alpha2[0], rd->alpha2[1]);
2079 	}
2080 	print_dfs_region(rd->dfs_region);
2081 	print_rd_rules(rd);
2082 }
2083 
2084 static void print_regdomain_info(const struct ieee80211_regdomain *rd)
2085 {
2086 	pr_info("Regulatory domain: %c%c\n", rd->alpha2[0], rd->alpha2[1]);
2087 	print_rd_rules(rd);
2088 }
2089 
2090 /* Takes ownership of rd only if it doesn't fail */
2091 static int __set_regdom(const struct ieee80211_regdomain *rd)
2092 {
2093 	const struct ieee80211_regdomain *intersected_rd = NULL;
2094 	struct cfg80211_registered_device *rdev = NULL;
2095 	struct wiphy *request_wiphy;
2096 	/* Some basic sanity checks first */
2097 
2098 	if (is_world_regdom(rd->alpha2)) {
2099 		if (WARN_ON(!reg_is_valid_request(rd->alpha2)))
2100 			return -EINVAL;
2101 		update_world_regdomain(rd);
2102 		return 0;
2103 	}
2104 
2105 	if (!is_alpha2_set(rd->alpha2) && !is_an_alpha2(rd->alpha2) &&
2106 			!is_unknown_alpha2(rd->alpha2))
2107 		return -EINVAL;
2108 
2109 	if (!last_request)
2110 		return -EINVAL;
2111 
2112 	/*
2113 	 * Lets only bother proceeding on the same alpha2 if the current
2114 	 * rd is non static (it means CRDA was present and was used last)
2115 	 * and the pending request came in from a country IE
2116 	 */
2117 	if (last_request->initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE) {
2118 		/*
2119 		 * If someone else asked us to change the rd lets only bother
2120 		 * checking if the alpha2 changes if CRDA was already called
2121 		 */
2122 		if (!regdom_changes(rd->alpha2))
2123 			return -EINVAL;
2124 	}
2125 
2126 	/*
2127 	 * Now lets set the regulatory domain, update all driver channels
2128 	 * and finally inform them of what we have done, in case they want
2129 	 * to review or adjust their own settings based on their own
2130 	 * internal EEPROM data
2131 	 */
2132 
2133 	if (WARN_ON(!reg_is_valid_request(rd->alpha2)))
2134 		return -EINVAL;
2135 
2136 	if (!is_valid_rd(rd)) {
2137 		pr_err("Invalid regulatory domain detected:\n");
2138 		print_regdomain_info(rd);
2139 		return -EINVAL;
2140 	}
2141 
2142 	request_wiphy = wiphy_idx_to_wiphy(last_request->wiphy_idx);
2143 	if (!request_wiphy &&
2144 	    (last_request->initiator == NL80211_REGDOM_SET_BY_DRIVER ||
2145 	     last_request->initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE)) {
2146 		schedule_delayed_work(&reg_timeout, 0);
2147 		return -ENODEV;
2148 	}
2149 
2150 	if (!last_request->intersect) {
2151 		int r;
2152 
2153 		if (last_request->initiator != NL80211_REGDOM_SET_BY_DRIVER) {
2154 			reset_regdomains(false);
2155 			cfg80211_regdomain = rd;
2156 			return 0;
2157 		}
2158 
2159 		/*
2160 		 * For a driver hint, lets copy the regulatory domain the
2161 		 * driver wanted to the wiphy to deal with conflicts
2162 		 */
2163 
2164 		/*
2165 		 * Userspace could have sent two replies with only
2166 		 * one kernel request.
2167 		 */
2168 		if (request_wiphy->regd)
2169 			return -EALREADY;
2170 
2171 		r = reg_copy_regd(&request_wiphy->regd, rd);
2172 		if (r)
2173 			return r;
2174 
2175 		reset_regdomains(false);
2176 		cfg80211_regdomain = rd;
2177 		return 0;
2178 	}
2179 
2180 	/* Intersection requires a bit more work */
2181 
2182 	if (last_request->initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE) {
2183 
2184 		intersected_rd = regdom_intersect(rd, cfg80211_regdomain);
2185 		if (!intersected_rd)
2186 			return -EINVAL;
2187 
2188 		/*
2189 		 * We can trash what CRDA provided now.
2190 		 * However if a driver requested this specific regulatory
2191 		 * domain we keep it for its private use
2192 		 */
2193 		if (last_request->initiator == NL80211_REGDOM_SET_BY_DRIVER)
2194 			request_wiphy->regd = rd;
2195 		else
2196 			kfree(rd);
2197 
2198 		rd = NULL;
2199 
2200 		reset_regdomains(false);
2201 		cfg80211_regdomain = intersected_rd;
2202 
2203 		return 0;
2204 	}
2205 
2206 	if (!intersected_rd)
2207 		return -EINVAL;
2208 
2209 	rdev = wiphy_to_dev(request_wiphy);
2210 
2211 	rdev->country_ie_alpha2[0] = rd->alpha2[0];
2212 	rdev->country_ie_alpha2[1] = rd->alpha2[1];
2213 	rdev->env = last_request->country_ie_env;
2214 
2215 	BUG_ON(intersected_rd == rd);
2216 
2217 	kfree(rd);
2218 	rd = NULL;
2219 
2220 	reset_regdomains(false);
2221 	cfg80211_regdomain = intersected_rd;
2222 
2223 	return 0;
2224 }
2225 
2226 
2227 /*
2228  * Use this call to set the current regulatory domain. Conflicts with
2229  * multiple drivers can be ironed out later. Caller must've already
2230  * kmalloc'd the rd structure. Caller must hold cfg80211_mutex
2231  */
2232 int set_regdom(const struct ieee80211_regdomain *rd)
2233 {
2234 	int r;
2235 
2236 	assert_cfg80211_lock();
2237 
2238 	mutex_lock(&reg_mutex);
2239 
2240 	/* Note that this doesn't update the wiphys, this is done below */
2241 	r = __set_regdom(rd);
2242 	if (r) {
2243 		kfree(rd);
2244 		mutex_unlock(&reg_mutex);
2245 		return r;
2246 	}
2247 
2248 	/* This would make this whole thing pointless */
2249 	if (!last_request->intersect)
2250 		BUG_ON(rd != cfg80211_regdomain);
2251 
2252 	/* update all wiphys now with the new established regulatory domain */
2253 	update_all_wiphy_regulatory(last_request->initiator);
2254 
2255 	print_regdomain(cfg80211_regdomain);
2256 
2257 	nl80211_send_reg_change_event(last_request);
2258 
2259 	reg_set_request_processed();
2260 
2261 	mutex_unlock(&reg_mutex);
2262 
2263 	return r;
2264 }
2265 
2266 #ifdef CONFIG_HOTPLUG
2267 int reg_device_uevent(struct device *dev, struct kobj_uevent_env *env)
2268 {
2269 	if (last_request && !last_request->processed) {
2270 		if (add_uevent_var(env, "COUNTRY=%c%c",
2271 				   last_request->alpha2[0],
2272 				   last_request->alpha2[1]))
2273 			return -ENOMEM;
2274 	}
2275 
2276 	return 0;
2277 }
2278 #else
2279 int reg_device_uevent(struct device *dev, struct kobj_uevent_env *env)
2280 {
2281 	return -ENODEV;
2282 }
2283 #endif /* CONFIG_HOTPLUG */
2284 
2285 /* Caller must hold cfg80211_mutex */
2286 void reg_device_remove(struct wiphy *wiphy)
2287 {
2288 	struct wiphy *request_wiphy = NULL;
2289 
2290 	assert_cfg80211_lock();
2291 
2292 	mutex_lock(&reg_mutex);
2293 
2294 	kfree(wiphy->regd);
2295 
2296 	if (last_request)
2297 		request_wiphy = wiphy_idx_to_wiphy(last_request->wiphy_idx);
2298 
2299 	if (!request_wiphy || request_wiphy != wiphy)
2300 		goto out;
2301 
2302 	last_request->wiphy_idx = WIPHY_IDX_STALE;
2303 	last_request->country_ie_env = ENVIRON_ANY;
2304 out:
2305 	mutex_unlock(&reg_mutex);
2306 }
2307 
2308 static void reg_timeout_work(struct work_struct *work)
2309 {
2310 	REG_DBG_PRINT("Timeout while waiting for CRDA to reply, "
2311 		      "restoring regulatory settings\n");
2312 	restore_regulatory_settings(true);
2313 }
2314 
2315 int __init regulatory_init(void)
2316 {
2317 	int err = 0;
2318 
2319 	reg_pdev = platform_device_register_simple("regulatory", 0, NULL, 0);
2320 	if (IS_ERR(reg_pdev))
2321 		return PTR_ERR(reg_pdev);
2322 
2323 	reg_pdev->dev.type = &reg_device_type;
2324 
2325 	spin_lock_init(&reg_requests_lock);
2326 	spin_lock_init(&reg_pending_beacons_lock);
2327 
2328 	cfg80211_regdomain = cfg80211_world_regdom;
2329 
2330 	user_alpha2[0] = '9';
2331 	user_alpha2[1] = '7';
2332 
2333 	/* We always try to get an update for the static regdomain */
2334 	err = regulatory_hint_core(cfg80211_regdomain->alpha2);
2335 	if (err) {
2336 		if (err == -ENOMEM)
2337 			return err;
2338 		/*
2339 		 * N.B. kobject_uevent_env() can fail mainly for when we're out
2340 		 * memory which is handled and propagated appropriately above
2341 		 * but it can also fail during a netlink_broadcast() or during
2342 		 * early boot for call_usermodehelper(). For now treat these
2343 		 * errors as non-fatal.
2344 		 */
2345 		pr_err("kobject_uevent_env() was unable to call CRDA during init\n");
2346 #ifdef CONFIG_CFG80211_REG_DEBUG
2347 		/* We want to find out exactly why when debugging */
2348 		WARN_ON(err);
2349 #endif
2350 	}
2351 
2352 	/*
2353 	 * Finally, if the user set the module parameter treat it
2354 	 * as a user hint.
2355 	 */
2356 	if (!is_world_regdom(ieee80211_regdom))
2357 		regulatory_hint_user(ieee80211_regdom);
2358 
2359 	return 0;
2360 }
2361 
2362 void /* __init_or_exit */ regulatory_exit(void)
2363 {
2364 	struct regulatory_request *reg_request, *tmp;
2365 	struct reg_beacon *reg_beacon, *btmp;
2366 
2367 	cancel_work_sync(&reg_work);
2368 	cancel_delayed_work_sync(&reg_timeout);
2369 
2370 	mutex_lock(&cfg80211_mutex);
2371 	mutex_lock(&reg_mutex);
2372 
2373 	reset_regdomains(true);
2374 
2375 	dev_set_uevent_suppress(&reg_pdev->dev, true);
2376 
2377 	platform_device_unregister(reg_pdev);
2378 
2379 	spin_lock_bh(&reg_pending_beacons_lock);
2380 	if (!list_empty(&reg_pending_beacons)) {
2381 		list_for_each_entry_safe(reg_beacon, btmp,
2382 					 &reg_pending_beacons, list) {
2383 			list_del(&reg_beacon->list);
2384 			kfree(reg_beacon);
2385 		}
2386 	}
2387 	spin_unlock_bh(&reg_pending_beacons_lock);
2388 
2389 	if (!list_empty(&reg_beacon_list)) {
2390 		list_for_each_entry_safe(reg_beacon, btmp,
2391 					 &reg_beacon_list, list) {
2392 			list_del(&reg_beacon->list);
2393 			kfree(reg_beacon);
2394 		}
2395 	}
2396 
2397 	spin_lock(&reg_requests_lock);
2398 	if (!list_empty(&reg_requests_list)) {
2399 		list_for_each_entry_safe(reg_request, tmp,
2400 					 &reg_requests_list, list) {
2401 			list_del(&reg_request->list);
2402 			kfree(reg_request);
2403 		}
2404 	}
2405 	spin_unlock(&reg_requests_lock);
2406 
2407 	mutex_unlock(&reg_mutex);
2408 	mutex_unlock(&cfg80211_mutex);
2409 }
2410