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