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