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