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