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