Mention branches and keyring.
[releases.git] / 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-2011  Luis R. Rodriguez <mcgrof@qca.qualcomm.com>
6  * Copyright 2013-2014  Intel Mobile Communications GmbH
7  * Copyright      2017  Intel Deutschland GmbH
8  * Copyright (C) 2018 - 2021 Intel Corporation
9  *
10  * Permission to use, copy, modify, and/or distribute this software for any
11  * purpose with or without fee is hereby granted, provided that the above
12  * copyright notice and this permission notice appear in all copies.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
15  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
16  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
17  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
18  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
19  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
20  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
21  */
22
23
24 /**
25  * DOC: Wireless regulatory infrastructure
26  *
27  * The usual implementation is for a driver to read a device EEPROM to
28  * determine which regulatory domain it should be operating under, then
29  * looking up the allowable channels in a driver-local table and finally
30  * registering those channels in the wiphy structure.
31  *
32  * Another set of compliance enforcement is for drivers to use their
33  * own compliance limits which can be stored on the EEPROM. The host
34  * driver or firmware may ensure these are used.
35  *
36  * In addition to all this we provide an extra layer of regulatory
37  * conformance. For drivers which do not have any regulatory
38  * information CRDA provides the complete regulatory solution.
39  * For others it provides a community effort on further restrictions
40  * to enhance compliance.
41  *
42  * Note: When number of rules --> infinity we will not be able to
43  * index on alpha2 any more, instead we'll probably have to
44  * rely on some SHA1 checksum of the regdomain for example.
45  *
46  */
47
48 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
49
50 #include <linux/kernel.h>
51 #include <linux/export.h>
52 #include <linux/slab.h>
53 #include <linux/list.h>
54 #include <linux/ctype.h>
55 #include <linux/nl80211.h>
56 #include <linux/platform_device.h>
57 #include <linux/verification.h>
58 #include <linux/moduleparam.h>
59 #include <linux/firmware.h>
60 #include <net/cfg80211.h>
61 #include "core.h"
62 #include "reg.h"
63 #include "rdev-ops.h"
64 #include "nl80211.h"
65
66 /*
67  * Grace period we give before making sure all current interfaces reside on
68  * channels allowed by the current regulatory domain.
69  */
70 #define REG_ENFORCE_GRACE_MS 60000
71
72 /**
73  * enum reg_request_treatment - regulatory request treatment
74  *
75  * @REG_REQ_OK: continue processing the regulatory request
76  * @REG_REQ_IGNORE: ignore the regulatory request
77  * @REG_REQ_INTERSECT: the regulatory domain resulting from this request should
78  *      be intersected with the current one.
79  * @REG_REQ_ALREADY_SET: the regulatory request will not change the current
80  *      regulatory settings, and no further processing is required.
81  */
82 enum reg_request_treatment {
83         REG_REQ_OK,
84         REG_REQ_IGNORE,
85         REG_REQ_INTERSECT,
86         REG_REQ_ALREADY_SET,
87 };
88
89 static struct regulatory_request core_request_world = {
90         .initiator = NL80211_REGDOM_SET_BY_CORE,
91         .alpha2[0] = '0',
92         .alpha2[1] = '0',
93         .intersect = false,
94         .processed = true,
95         .country_ie_env = ENVIRON_ANY,
96 };
97
98 /*
99  * Receipt of information from last regulatory request,
100  * protected by RTNL (and can be accessed with RCU protection)
101  */
102 static struct regulatory_request __rcu *last_request =
103         (void __force __rcu *)&core_request_world;
104
105 /* To trigger userspace events and load firmware */
106 static struct platform_device *reg_pdev;
107
108 /*
109  * Central wireless core regulatory domains, we only need two,
110  * the current one and a world regulatory domain in case we have no
111  * information to give us an alpha2.
112  * (protected by RTNL, can be read under RCU)
113  */
114 const struct ieee80211_regdomain __rcu *cfg80211_regdomain;
115
116 /*
117  * Number of devices that registered to the core
118  * that support cellular base station regulatory hints
119  * (protected by RTNL)
120  */
121 static int reg_num_devs_support_basehint;
122
123 /*
124  * State variable indicating if the platform on which the devices
125  * are attached is operating in an indoor environment. The state variable
126  * is relevant for all registered devices.
127  */
128 static bool reg_is_indoor;
129 static DEFINE_SPINLOCK(reg_indoor_lock);
130
131 /* Used to track the userspace process controlling the indoor setting */
132 static u32 reg_is_indoor_portid;
133
134 static void restore_regulatory_settings(bool reset_user, bool cached);
135 static void print_regdomain(const struct ieee80211_regdomain *rd);
136
137 static const struct ieee80211_regdomain *get_cfg80211_regdom(void)
138 {
139         return rcu_dereference_rtnl(cfg80211_regdomain);
140 }
141
142 /*
143  * Returns the regulatory domain associated with the wiphy.
144  *
145  * Requires any of RTNL, wiphy mutex or RCU protection.
146  */
147 const struct ieee80211_regdomain *get_wiphy_regdom(struct wiphy *wiphy)
148 {
149         return rcu_dereference_check(wiphy->regd,
150                                      lockdep_is_held(&wiphy->mtx) ||
151                                      lockdep_rtnl_is_held());
152 }
153 EXPORT_SYMBOL(get_wiphy_regdom);
154
155 static const char *reg_dfs_region_str(enum nl80211_dfs_regions dfs_region)
156 {
157         switch (dfs_region) {
158         case NL80211_DFS_UNSET:
159                 return "unset";
160         case NL80211_DFS_FCC:
161                 return "FCC";
162         case NL80211_DFS_ETSI:
163                 return "ETSI";
164         case NL80211_DFS_JP:
165                 return "JP";
166         }
167         return "Unknown";
168 }
169
170 enum nl80211_dfs_regions reg_get_dfs_region(struct wiphy *wiphy)
171 {
172         const struct ieee80211_regdomain *regd = NULL;
173         const struct ieee80211_regdomain *wiphy_regd = NULL;
174         enum nl80211_dfs_regions dfs_region;
175
176         rcu_read_lock();
177         regd = get_cfg80211_regdom();
178         dfs_region = regd->dfs_region;
179
180         if (!wiphy)
181                 goto out;
182
183         wiphy_regd = get_wiphy_regdom(wiphy);
184         if (!wiphy_regd)
185                 goto out;
186
187         if (wiphy->regulatory_flags & REGULATORY_WIPHY_SELF_MANAGED) {
188                 dfs_region = wiphy_regd->dfs_region;
189                 goto out;
190         }
191
192         if (wiphy_regd->dfs_region == regd->dfs_region)
193                 goto out;
194
195         pr_debug("%s: device specific dfs_region (%s) disagrees with cfg80211's central dfs_region (%s)\n",
196                  dev_name(&wiphy->dev),
197                  reg_dfs_region_str(wiphy_regd->dfs_region),
198                  reg_dfs_region_str(regd->dfs_region));
199
200 out:
201         rcu_read_unlock();
202
203         return dfs_region;
204 }
205
206 static void rcu_free_regdom(const struct ieee80211_regdomain *r)
207 {
208         if (!r)
209                 return;
210         kfree_rcu((struct ieee80211_regdomain *)r, rcu_head);
211 }
212
213 static struct regulatory_request *get_last_request(void)
214 {
215         return rcu_dereference_rtnl(last_request);
216 }
217
218 /* Used to queue up regulatory hints */
219 static LIST_HEAD(reg_requests_list);
220 static DEFINE_SPINLOCK(reg_requests_lock);
221
222 /* Used to queue up beacon hints for review */
223 static LIST_HEAD(reg_pending_beacons);
224 static DEFINE_SPINLOCK(reg_pending_beacons_lock);
225
226 /* Used to keep track of processed beacon hints */
227 static LIST_HEAD(reg_beacon_list);
228
229 struct reg_beacon {
230         struct list_head list;
231         struct ieee80211_channel chan;
232 };
233
234 static void reg_check_chans_work(struct work_struct *work);
235 static DECLARE_DELAYED_WORK(reg_check_chans, reg_check_chans_work);
236
237 static void reg_todo(struct work_struct *work);
238 static DECLARE_WORK(reg_work, reg_todo);
239
240 /* We keep a static world regulatory domain in case of the absence of CRDA */
241 static const struct ieee80211_regdomain world_regdom = {
242         .n_reg_rules = 8,
243         .alpha2 =  "00",
244         .reg_rules = {
245                 /* IEEE 802.11b/g, channels 1..11 */
246                 REG_RULE(2412-10, 2462+10, 40, 6, 20, 0),
247                 /* IEEE 802.11b/g, channels 12..13. */
248                 REG_RULE(2467-10, 2472+10, 20, 6, 20,
249                         NL80211_RRF_NO_IR | NL80211_RRF_AUTO_BW),
250                 /* IEEE 802.11 channel 14 - Only JP enables
251                  * this and for 802.11b only */
252                 REG_RULE(2484-10, 2484+10, 20, 6, 20,
253                         NL80211_RRF_NO_IR |
254                         NL80211_RRF_NO_OFDM),
255                 /* IEEE 802.11a, channel 36..48 */
256                 REG_RULE(5180-10, 5240+10, 80, 6, 20,
257                         NL80211_RRF_NO_IR |
258                         NL80211_RRF_AUTO_BW),
259
260                 /* IEEE 802.11a, channel 52..64 - DFS required */
261                 REG_RULE(5260-10, 5320+10, 80, 6, 20,
262                         NL80211_RRF_NO_IR |
263                         NL80211_RRF_AUTO_BW |
264                         NL80211_RRF_DFS),
265
266                 /* IEEE 802.11a, channel 100..144 - DFS required */
267                 REG_RULE(5500-10, 5720+10, 160, 6, 20,
268                         NL80211_RRF_NO_IR |
269                         NL80211_RRF_DFS),
270
271                 /* IEEE 802.11a, channel 149..165 */
272                 REG_RULE(5745-10, 5825+10, 80, 6, 20,
273                         NL80211_RRF_NO_IR),
274
275                 /* IEEE 802.11ad (60GHz), channels 1..3 */
276                 REG_RULE(56160+2160*1-1080, 56160+2160*3+1080, 2160, 0, 0, 0),
277         }
278 };
279
280 /* protected by RTNL */
281 static const struct ieee80211_regdomain *cfg80211_world_regdom =
282         &world_regdom;
283
284 static char *ieee80211_regdom = "00";
285 static char user_alpha2[2];
286 static const struct ieee80211_regdomain *cfg80211_user_regdom;
287
288 module_param(ieee80211_regdom, charp, 0444);
289 MODULE_PARM_DESC(ieee80211_regdom, "IEEE 802.11 regulatory domain code");
290
291 static void reg_free_request(struct regulatory_request *request)
292 {
293         if (request == &core_request_world)
294                 return;
295
296         if (request != get_last_request())
297                 kfree(request);
298 }
299
300 static void reg_free_last_request(void)
301 {
302         struct regulatory_request *lr = get_last_request();
303
304         if (lr != &core_request_world && lr)
305                 kfree_rcu(lr, rcu_head);
306 }
307
308 static void reg_update_last_request(struct regulatory_request *request)
309 {
310         struct regulatory_request *lr;
311
312         lr = get_last_request();
313         if (lr == request)
314                 return;
315
316         reg_free_last_request();
317         rcu_assign_pointer(last_request, request);
318 }
319
320 static void reset_regdomains(bool full_reset,
321                              const struct ieee80211_regdomain *new_regdom)
322 {
323         const struct ieee80211_regdomain *r;
324
325         ASSERT_RTNL();
326
327         r = get_cfg80211_regdom();
328
329         /* avoid freeing static information or freeing something twice */
330         if (r == cfg80211_world_regdom)
331                 r = NULL;
332         if (cfg80211_world_regdom == &world_regdom)
333                 cfg80211_world_regdom = NULL;
334         if (r == &world_regdom)
335                 r = NULL;
336
337         rcu_free_regdom(r);
338         rcu_free_regdom(cfg80211_world_regdom);
339
340         cfg80211_world_regdom = &world_regdom;
341         rcu_assign_pointer(cfg80211_regdomain, new_regdom);
342
343         if (!full_reset)
344                 return;
345
346         reg_update_last_request(&core_request_world);
347 }
348
349 /*
350  * Dynamic world regulatory domain requested by the wireless
351  * core upon initialization
352  */
353 static void update_world_regdomain(const struct ieee80211_regdomain *rd)
354 {
355         struct regulatory_request *lr;
356
357         lr = get_last_request();
358
359         WARN_ON(!lr);
360
361         reset_regdomains(false, rd);
362
363         cfg80211_world_regdom = rd;
364 }
365
366 bool is_world_regdom(const char *alpha2)
367 {
368         if (!alpha2)
369                 return false;
370         return alpha2[0] == '0' && alpha2[1] == '0';
371 }
372
373 static bool is_alpha2_set(const char *alpha2)
374 {
375         if (!alpha2)
376                 return false;
377         return alpha2[0] && alpha2[1];
378 }
379
380 static bool is_unknown_alpha2(const char *alpha2)
381 {
382         if (!alpha2)
383                 return false;
384         /*
385          * Special case where regulatory domain was built by driver
386          * but a specific alpha2 cannot be determined
387          */
388         return alpha2[0] == '9' && alpha2[1] == '9';
389 }
390
391 static bool is_intersected_alpha2(const char *alpha2)
392 {
393         if (!alpha2)
394                 return false;
395         /*
396          * Special case where regulatory domain is the
397          * result of an intersection between two regulatory domain
398          * structures
399          */
400         return alpha2[0] == '9' && alpha2[1] == '8';
401 }
402
403 static bool is_an_alpha2(const char *alpha2)
404 {
405         if (!alpha2)
406                 return false;
407         return isalpha(alpha2[0]) && isalpha(alpha2[1]);
408 }
409
410 static bool alpha2_equal(const char *alpha2_x, const char *alpha2_y)
411 {
412         if (!alpha2_x || !alpha2_y)
413                 return false;
414         return alpha2_x[0] == alpha2_y[0] && alpha2_x[1] == alpha2_y[1];
415 }
416
417 static bool regdom_changes(const char *alpha2)
418 {
419         const struct ieee80211_regdomain *r = get_cfg80211_regdom();
420
421         if (!r)
422                 return true;
423         return !alpha2_equal(r->alpha2, alpha2);
424 }
425
426 /*
427  * The NL80211_REGDOM_SET_BY_USER regdom alpha2 is cached, this lets
428  * you know if a valid regulatory hint with NL80211_REGDOM_SET_BY_USER
429  * has ever been issued.
430  */
431 static bool is_user_regdom_saved(void)
432 {
433         if (user_alpha2[0] == '9' && user_alpha2[1] == '7')
434                 return false;
435
436         /* This would indicate a mistake on the design */
437         if (WARN(!is_world_regdom(user_alpha2) && !is_an_alpha2(user_alpha2),
438                  "Unexpected user alpha2: %c%c\n",
439                  user_alpha2[0], user_alpha2[1]))
440                 return false;
441
442         return true;
443 }
444
445 static const struct ieee80211_regdomain *
446 reg_copy_regd(const struct ieee80211_regdomain *src_regd)
447 {
448         struct ieee80211_regdomain *regd;
449         unsigned int i;
450
451         regd = kzalloc(struct_size(regd, reg_rules, src_regd->n_reg_rules),
452                        GFP_KERNEL);
453         if (!regd)
454                 return ERR_PTR(-ENOMEM);
455
456         memcpy(regd, src_regd, sizeof(struct ieee80211_regdomain));
457
458         for (i = 0; i < src_regd->n_reg_rules; i++)
459                 memcpy(&regd->reg_rules[i], &src_regd->reg_rules[i],
460                        sizeof(struct ieee80211_reg_rule));
461
462         return regd;
463 }
464
465 static void cfg80211_save_user_regdom(const struct ieee80211_regdomain *rd)
466 {
467         ASSERT_RTNL();
468
469         if (!IS_ERR(cfg80211_user_regdom))
470                 kfree(cfg80211_user_regdom);
471         cfg80211_user_regdom = reg_copy_regd(rd);
472 }
473
474 struct reg_regdb_apply_request {
475         struct list_head list;
476         const struct ieee80211_regdomain *regdom;
477 };
478
479 static LIST_HEAD(reg_regdb_apply_list);
480 static DEFINE_MUTEX(reg_regdb_apply_mutex);
481
482 static void reg_regdb_apply(struct work_struct *work)
483 {
484         struct reg_regdb_apply_request *request;
485
486         rtnl_lock();
487
488         mutex_lock(&reg_regdb_apply_mutex);
489         while (!list_empty(&reg_regdb_apply_list)) {
490                 request = list_first_entry(&reg_regdb_apply_list,
491                                            struct reg_regdb_apply_request,
492                                            list);
493                 list_del(&request->list);
494
495                 set_regdom(request->regdom, REGD_SOURCE_INTERNAL_DB);
496                 kfree(request);
497         }
498         mutex_unlock(&reg_regdb_apply_mutex);
499
500         rtnl_unlock();
501 }
502
503 static DECLARE_WORK(reg_regdb_work, reg_regdb_apply);
504
505 static int reg_schedule_apply(const struct ieee80211_regdomain *regdom)
506 {
507         struct reg_regdb_apply_request *request;
508
509         request = kzalloc(sizeof(struct reg_regdb_apply_request), GFP_KERNEL);
510         if (!request) {
511                 kfree(regdom);
512                 return -ENOMEM;
513         }
514
515         request->regdom = regdom;
516
517         mutex_lock(&reg_regdb_apply_mutex);
518         list_add_tail(&request->list, &reg_regdb_apply_list);
519         mutex_unlock(&reg_regdb_apply_mutex);
520
521         schedule_work(&reg_regdb_work);
522         return 0;
523 }
524
525 #ifdef CONFIG_CFG80211_CRDA_SUPPORT
526 /* Max number of consecutive attempts to communicate with CRDA  */
527 #define REG_MAX_CRDA_TIMEOUTS 10
528
529 static u32 reg_crda_timeouts;
530
531 static void crda_timeout_work(struct work_struct *work);
532 static DECLARE_DELAYED_WORK(crda_timeout, crda_timeout_work);
533
534 static void crda_timeout_work(struct work_struct *work)
535 {
536         pr_debug("Timeout while waiting for CRDA to reply, restoring regulatory settings\n");
537         rtnl_lock();
538         reg_crda_timeouts++;
539         restore_regulatory_settings(true, false);
540         rtnl_unlock();
541 }
542
543 static void cancel_crda_timeout(void)
544 {
545         cancel_delayed_work(&crda_timeout);
546 }
547
548 static void cancel_crda_timeout_sync(void)
549 {
550         cancel_delayed_work_sync(&crda_timeout);
551 }
552
553 static void reset_crda_timeouts(void)
554 {
555         reg_crda_timeouts = 0;
556 }
557
558 /*
559  * This lets us keep regulatory code which is updated on a regulatory
560  * basis in userspace.
561  */
562 static int call_crda(const char *alpha2)
563 {
564         char country[12];
565         char *env[] = { country, NULL };
566         int ret;
567
568         snprintf(country, sizeof(country), "COUNTRY=%c%c",
569                  alpha2[0], alpha2[1]);
570
571         if (reg_crda_timeouts > REG_MAX_CRDA_TIMEOUTS) {
572                 pr_debug("Exceeded CRDA call max attempts. Not calling CRDA\n");
573                 return -EINVAL;
574         }
575
576         if (!is_world_regdom((char *) alpha2))
577                 pr_debug("Calling CRDA for country: %c%c\n",
578                          alpha2[0], alpha2[1]);
579         else
580                 pr_debug("Calling CRDA to update world regulatory domain\n");
581
582         ret = kobject_uevent_env(&reg_pdev->dev.kobj, KOBJ_CHANGE, env);
583         if (ret)
584                 return ret;
585
586         queue_delayed_work(system_power_efficient_wq,
587                            &crda_timeout, msecs_to_jiffies(3142));
588         return 0;
589 }
590 #else
591 static inline void cancel_crda_timeout(void) {}
592 static inline void cancel_crda_timeout_sync(void) {}
593 static inline void reset_crda_timeouts(void) {}
594 static inline int call_crda(const char *alpha2)
595 {
596         return -ENODATA;
597 }
598 #endif /* CONFIG_CFG80211_CRDA_SUPPORT */
599
600 /* code to directly load a firmware database through request_firmware */
601 static const struct fwdb_header *regdb;
602
603 struct fwdb_country {
604         u8 alpha2[2];
605         __be16 coll_ptr;
606         /* this struct cannot be extended */
607 } __packed __aligned(4);
608
609 struct fwdb_collection {
610         u8 len;
611         u8 n_rules;
612         u8 dfs_region;
613         /* no optional data yet */
614         /* aligned to 2, then followed by __be16 array of rule pointers */
615 } __packed __aligned(4);
616
617 enum fwdb_flags {
618         FWDB_FLAG_NO_OFDM       = BIT(0),
619         FWDB_FLAG_NO_OUTDOOR    = BIT(1),
620         FWDB_FLAG_DFS           = BIT(2),
621         FWDB_FLAG_NO_IR         = BIT(3),
622         FWDB_FLAG_AUTO_BW       = BIT(4),
623 };
624
625 struct fwdb_wmm_ac {
626         u8 ecw;
627         u8 aifsn;
628         __be16 cot;
629 } __packed;
630
631 struct fwdb_wmm_rule {
632         struct fwdb_wmm_ac client[IEEE80211_NUM_ACS];
633         struct fwdb_wmm_ac ap[IEEE80211_NUM_ACS];
634 } __packed;
635
636 struct fwdb_rule {
637         u8 len;
638         u8 flags;
639         __be16 max_eirp;
640         __be32 start, end, max_bw;
641         /* start of optional data */
642         __be16 cac_timeout;
643         __be16 wmm_ptr;
644 } __packed __aligned(4);
645
646 #define FWDB_MAGIC 0x52474442
647 #define FWDB_VERSION 20
648
649 struct fwdb_header {
650         __be32 magic;
651         __be32 version;
652         struct fwdb_country country[];
653 } __packed __aligned(4);
654
655 static int ecw2cw(int ecw)
656 {
657         return (1 << ecw) - 1;
658 }
659
660 static bool valid_wmm(struct fwdb_wmm_rule *rule)
661 {
662         struct fwdb_wmm_ac *ac = (struct fwdb_wmm_ac *)rule;
663         int i;
664
665         for (i = 0; i < IEEE80211_NUM_ACS * 2; i++) {
666                 u16 cw_min = ecw2cw((ac[i].ecw & 0xf0) >> 4);
667                 u16 cw_max = ecw2cw(ac[i].ecw & 0x0f);
668                 u8 aifsn = ac[i].aifsn;
669
670                 if (cw_min >= cw_max)
671                         return false;
672
673                 if (aifsn < 1)
674                         return false;
675         }
676
677         return true;
678 }
679
680 static bool valid_rule(const u8 *data, unsigned int size, u16 rule_ptr)
681 {
682         struct fwdb_rule *rule = (void *)(data + (rule_ptr << 2));
683
684         if ((u8 *)rule + sizeof(rule->len) > data + size)
685                 return false;
686
687         /* mandatory fields */
688         if (rule->len < offsetofend(struct fwdb_rule, max_bw))
689                 return false;
690         if (rule->len >= offsetofend(struct fwdb_rule, wmm_ptr)) {
691                 u32 wmm_ptr = be16_to_cpu(rule->wmm_ptr) << 2;
692                 struct fwdb_wmm_rule *wmm;
693
694                 if (wmm_ptr + sizeof(struct fwdb_wmm_rule) > size)
695                         return false;
696
697                 wmm = (void *)(data + wmm_ptr);
698
699                 if (!valid_wmm(wmm))
700                         return false;
701         }
702         return true;
703 }
704
705 static bool valid_country(const u8 *data, unsigned int size,
706                           const struct fwdb_country *country)
707 {
708         unsigned int ptr = be16_to_cpu(country->coll_ptr) << 2;
709         struct fwdb_collection *coll = (void *)(data + ptr);
710         __be16 *rules_ptr;
711         unsigned int i;
712
713         /* make sure we can read len/n_rules */
714         if ((u8 *)coll + offsetofend(typeof(*coll), n_rules) > data + size)
715                 return false;
716
717         /* make sure base struct and all rules fit */
718         if ((u8 *)coll + ALIGN(coll->len, 2) +
719             (coll->n_rules * 2) > data + size)
720                 return false;
721
722         /* mandatory fields must exist */
723         if (coll->len < offsetofend(struct fwdb_collection, dfs_region))
724                 return false;
725
726         rules_ptr = (void *)((u8 *)coll + ALIGN(coll->len, 2));
727
728         for (i = 0; i < coll->n_rules; i++) {
729                 u16 rule_ptr = be16_to_cpu(rules_ptr[i]);
730
731                 if (!valid_rule(data, size, rule_ptr))
732                         return false;
733         }
734
735         return true;
736 }
737
738 #ifdef CONFIG_CFG80211_REQUIRE_SIGNED_REGDB
739 static struct key *builtin_regdb_keys;
740
741 static void __init load_keys_from_buffer(const u8 *p, unsigned int buflen)
742 {
743         const u8 *end = p + buflen;
744         size_t plen;
745         key_ref_t key;
746
747         while (p < end) {
748                 /* Each cert begins with an ASN.1 SEQUENCE tag and must be more
749                  * than 256 bytes in size.
750                  */
751                 if (end - p < 4)
752                         goto dodgy_cert;
753                 if (p[0] != 0x30 &&
754                     p[1] != 0x82)
755                         goto dodgy_cert;
756                 plen = (p[2] << 8) | p[3];
757                 plen += 4;
758                 if (plen > end - p)
759                         goto dodgy_cert;
760
761                 key = key_create_or_update(make_key_ref(builtin_regdb_keys, 1),
762                                            "asymmetric", NULL, p, plen,
763                                            ((KEY_POS_ALL & ~KEY_POS_SETATTR) |
764                                             KEY_USR_VIEW | KEY_USR_READ),
765                                            KEY_ALLOC_NOT_IN_QUOTA |
766                                            KEY_ALLOC_BUILT_IN |
767                                            KEY_ALLOC_BYPASS_RESTRICTION);
768                 if (IS_ERR(key)) {
769                         pr_err("Problem loading in-kernel X.509 certificate (%ld)\n",
770                                PTR_ERR(key));
771                 } else {
772                         pr_notice("Loaded X.509 cert '%s'\n",
773                                   key_ref_to_ptr(key)->description);
774                         key_ref_put(key);
775                 }
776                 p += plen;
777         }
778
779         return;
780
781 dodgy_cert:
782         pr_err("Problem parsing in-kernel X.509 certificate list\n");
783 }
784
785 static int __init load_builtin_regdb_keys(void)
786 {
787         builtin_regdb_keys =
788                 keyring_alloc(".builtin_regdb_keys",
789                               KUIDT_INIT(0), KGIDT_INIT(0), current_cred(),
790                               ((KEY_POS_ALL & ~KEY_POS_SETATTR) |
791                               KEY_USR_VIEW | KEY_USR_READ | KEY_USR_SEARCH),
792                               KEY_ALLOC_NOT_IN_QUOTA, NULL, NULL);
793         if (IS_ERR(builtin_regdb_keys))
794                 return PTR_ERR(builtin_regdb_keys);
795
796         pr_notice("Loading compiled-in X.509 certificates for regulatory database\n");
797
798 #ifdef CONFIG_CFG80211_USE_KERNEL_REGDB_KEYS
799         load_keys_from_buffer(shipped_regdb_certs, shipped_regdb_certs_len);
800 #endif
801 #ifdef CONFIG_CFG80211_EXTRA_REGDB_KEYDIR
802         if (CONFIG_CFG80211_EXTRA_REGDB_KEYDIR[0] != '\0')
803                 load_keys_from_buffer(extra_regdb_certs, extra_regdb_certs_len);
804 #endif
805
806         return 0;
807 }
808
809 MODULE_FIRMWARE("regulatory.db.p7s");
810
811 static bool regdb_has_valid_signature(const u8 *data, unsigned int size)
812 {
813         const struct firmware *sig;
814         bool result;
815
816         if (request_firmware(&sig, "regulatory.db.p7s", &reg_pdev->dev))
817                 return false;
818
819         result = verify_pkcs7_signature(data, size, sig->data, sig->size,
820                                         builtin_regdb_keys,
821                                         VERIFYING_UNSPECIFIED_SIGNATURE,
822                                         NULL, NULL) == 0;
823
824         release_firmware(sig);
825
826         return result;
827 }
828
829 static void free_regdb_keyring(void)
830 {
831         key_put(builtin_regdb_keys);
832 }
833 #else
834 static int load_builtin_regdb_keys(void)
835 {
836         return 0;
837 }
838
839 static bool regdb_has_valid_signature(const u8 *data, unsigned int size)
840 {
841         return true;
842 }
843
844 static void free_regdb_keyring(void)
845 {
846 }
847 #endif /* CONFIG_CFG80211_REQUIRE_SIGNED_REGDB */
848
849 static bool valid_regdb(const u8 *data, unsigned int size)
850 {
851         const struct fwdb_header *hdr = (void *)data;
852         const struct fwdb_country *country;
853
854         if (size < sizeof(*hdr))
855                 return false;
856
857         if (hdr->magic != cpu_to_be32(FWDB_MAGIC))
858                 return false;
859
860         if (hdr->version != cpu_to_be32(FWDB_VERSION))
861                 return false;
862
863         if (!regdb_has_valid_signature(data, size))
864                 return false;
865
866         country = &hdr->country[0];
867         while ((u8 *)(country + 1) <= data + size) {
868                 if (!country->coll_ptr)
869                         break;
870                 if (!valid_country(data, size, country))
871                         return false;
872                 country++;
873         }
874
875         return true;
876 }
877
878 static void set_wmm_rule(const struct fwdb_header *db,
879                          const struct fwdb_country *country,
880                          const struct fwdb_rule *rule,
881                          struct ieee80211_reg_rule *rrule)
882 {
883         struct ieee80211_wmm_rule *wmm_rule = &rrule->wmm_rule;
884         struct fwdb_wmm_rule *wmm;
885         unsigned int i, wmm_ptr;
886
887         wmm_ptr = be16_to_cpu(rule->wmm_ptr) << 2;
888         wmm = (void *)((u8 *)db + wmm_ptr);
889
890         if (!valid_wmm(wmm)) {
891                 pr_err("Invalid regulatory WMM rule %u-%u in domain %c%c\n",
892                        be32_to_cpu(rule->start), be32_to_cpu(rule->end),
893                        country->alpha2[0], country->alpha2[1]);
894                 return;
895         }
896
897         for (i = 0; i < IEEE80211_NUM_ACS; i++) {
898                 wmm_rule->client[i].cw_min =
899                         ecw2cw((wmm->client[i].ecw & 0xf0) >> 4);
900                 wmm_rule->client[i].cw_max = ecw2cw(wmm->client[i].ecw & 0x0f);
901                 wmm_rule->client[i].aifsn =  wmm->client[i].aifsn;
902                 wmm_rule->client[i].cot =
903                         1000 * be16_to_cpu(wmm->client[i].cot);
904                 wmm_rule->ap[i].cw_min = ecw2cw((wmm->ap[i].ecw & 0xf0) >> 4);
905                 wmm_rule->ap[i].cw_max = ecw2cw(wmm->ap[i].ecw & 0x0f);
906                 wmm_rule->ap[i].aifsn = wmm->ap[i].aifsn;
907                 wmm_rule->ap[i].cot = 1000 * be16_to_cpu(wmm->ap[i].cot);
908         }
909
910         rrule->has_wmm = true;
911 }
912
913 static int __regdb_query_wmm(const struct fwdb_header *db,
914                              const struct fwdb_country *country, int freq,
915                              struct ieee80211_reg_rule *rrule)
916 {
917         unsigned int ptr = be16_to_cpu(country->coll_ptr) << 2;
918         struct fwdb_collection *coll = (void *)((u8 *)db + ptr);
919         int i;
920
921         for (i = 0; i < coll->n_rules; i++) {
922                 __be16 *rules_ptr = (void *)((u8 *)coll + ALIGN(coll->len, 2));
923                 unsigned int rule_ptr = be16_to_cpu(rules_ptr[i]) << 2;
924                 struct fwdb_rule *rule = (void *)((u8 *)db + rule_ptr);
925
926                 if (rule->len < offsetofend(struct fwdb_rule, wmm_ptr))
927                         continue;
928
929                 if (freq >= KHZ_TO_MHZ(be32_to_cpu(rule->start)) &&
930                     freq <= KHZ_TO_MHZ(be32_to_cpu(rule->end))) {
931                         set_wmm_rule(db, country, rule, rrule);
932                         return 0;
933                 }
934         }
935
936         return -ENODATA;
937 }
938
939 int reg_query_regdb_wmm(char *alpha2, int freq, struct ieee80211_reg_rule *rule)
940 {
941         const struct fwdb_header *hdr = regdb;
942         const struct fwdb_country *country;
943
944         if (!regdb)
945                 return -ENODATA;
946
947         if (IS_ERR(regdb))
948                 return PTR_ERR(regdb);
949
950         country = &hdr->country[0];
951         while (country->coll_ptr) {
952                 if (alpha2_equal(alpha2, country->alpha2))
953                         return __regdb_query_wmm(regdb, country, freq, rule);
954
955                 country++;
956         }
957
958         return -ENODATA;
959 }
960 EXPORT_SYMBOL(reg_query_regdb_wmm);
961
962 static int regdb_query_country(const struct fwdb_header *db,
963                                const struct fwdb_country *country)
964 {
965         unsigned int ptr = be16_to_cpu(country->coll_ptr) << 2;
966         struct fwdb_collection *coll = (void *)((u8 *)db + ptr);
967         struct ieee80211_regdomain *regdom;
968         unsigned int i;
969
970         regdom = kzalloc(struct_size(regdom, reg_rules, coll->n_rules),
971                          GFP_KERNEL);
972         if (!regdom)
973                 return -ENOMEM;
974
975         regdom->n_reg_rules = coll->n_rules;
976         regdom->alpha2[0] = country->alpha2[0];
977         regdom->alpha2[1] = country->alpha2[1];
978         regdom->dfs_region = coll->dfs_region;
979
980         for (i = 0; i < regdom->n_reg_rules; i++) {
981                 __be16 *rules_ptr = (void *)((u8 *)coll + ALIGN(coll->len, 2));
982                 unsigned int rule_ptr = be16_to_cpu(rules_ptr[i]) << 2;
983                 struct fwdb_rule *rule = (void *)((u8 *)db + rule_ptr);
984                 struct ieee80211_reg_rule *rrule = &regdom->reg_rules[i];
985
986                 rrule->freq_range.start_freq_khz = be32_to_cpu(rule->start);
987                 rrule->freq_range.end_freq_khz = be32_to_cpu(rule->end);
988                 rrule->freq_range.max_bandwidth_khz = be32_to_cpu(rule->max_bw);
989
990                 rrule->power_rule.max_antenna_gain = 0;
991                 rrule->power_rule.max_eirp = be16_to_cpu(rule->max_eirp);
992
993                 rrule->flags = 0;
994                 if (rule->flags & FWDB_FLAG_NO_OFDM)
995                         rrule->flags |= NL80211_RRF_NO_OFDM;
996                 if (rule->flags & FWDB_FLAG_NO_OUTDOOR)
997                         rrule->flags |= NL80211_RRF_NO_OUTDOOR;
998                 if (rule->flags & FWDB_FLAG_DFS)
999                         rrule->flags |= NL80211_RRF_DFS;
1000                 if (rule->flags & FWDB_FLAG_NO_IR)
1001                         rrule->flags |= NL80211_RRF_NO_IR;
1002                 if (rule->flags & FWDB_FLAG_AUTO_BW)
1003                         rrule->flags |= NL80211_RRF_AUTO_BW;
1004
1005                 rrule->dfs_cac_ms = 0;
1006
1007                 /* handle optional data */
1008                 if (rule->len >= offsetofend(struct fwdb_rule, cac_timeout))
1009                         rrule->dfs_cac_ms =
1010                                 1000 * be16_to_cpu(rule->cac_timeout);
1011                 if (rule->len >= offsetofend(struct fwdb_rule, wmm_ptr))
1012                         set_wmm_rule(db, country, rule, rrule);
1013         }
1014
1015         return reg_schedule_apply(regdom);
1016 }
1017
1018 static int query_regdb(const char *alpha2)
1019 {
1020         const struct fwdb_header *hdr = regdb;
1021         const struct fwdb_country *country;
1022
1023         ASSERT_RTNL();
1024
1025         if (IS_ERR(regdb))
1026                 return PTR_ERR(regdb);
1027
1028         country = &hdr->country[0];
1029         while (country->coll_ptr) {
1030                 if (alpha2_equal(alpha2, country->alpha2))
1031                         return regdb_query_country(regdb, country);
1032                 country++;
1033         }
1034
1035         return -ENODATA;
1036 }
1037
1038 static void regdb_fw_cb(const struct firmware *fw, void *context)
1039 {
1040         int set_error = 0;
1041         bool restore = true;
1042         void *db;
1043
1044         if (!fw) {
1045                 pr_info("failed to load regulatory.db\n");
1046                 set_error = -ENODATA;
1047         } else if (!valid_regdb(fw->data, fw->size)) {
1048                 pr_info("loaded regulatory.db is malformed or signature is missing/invalid\n");
1049                 set_error = -EINVAL;
1050         }
1051
1052         rtnl_lock();
1053         if (regdb && !IS_ERR(regdb)) {
1054                 /* negative case - a bug
1055                  * positive case - can happen due to race in case of multiple cb's in
1056                  * queue, due to usage of asynchronous callback
1057                  *
1058                  * Either case, just restore and free new db.
1059                  */
1060         } else if (set_error) {
1061                 regdb = ERR_PTR(set_error);
1062         } else if (fw) {
1063                 db = kmemdup(fw->data, fw->size, GFP_KERNEL);
1064                 if (db) {
1065                         regdb = db;
1066                         restore = context && query_regdb(context);
1067                 } else {
1068                         restore = true;
1069                 }
1070         }
1071
1072         if (restore)
1073                 restore_regulatory_settings(true, false);
1074
1075         rtnl_unlock();
1076
1077         kfree(context);
1078
1079         release_firmware(fw);
1080 }
1081
1082 MODULE_FIRMWARE("regulatory.db");
1083
1084 static int query_regdb_file(const char *alpha2)
1085 {
1086         ASSERT_RTNL();
1087
1088         if (regdb)
1089                 return query_regdb(alpha2);
1090
1091         alpha2 = kmemdup(alpha2, 2, GFP_KERNEL);
1092         if (!alpha2)
1093                 return -ENOMEM;
1094
1095         return request_firmware_nowait(THIS_MODULE, true, "regulatory.db",
1096                                        &reg_pdev->dev, GFP_KERNEL,
1097                                        (void *)alpha2, regdb_fw_cb);
1098 }
1099
1100 int reg_reload_regdb(void)
1101 {
1102         const struct firmware *fw;
1103         void *db;
1104         int err;
1105
1106         err = request_firmware(&fw, "regulatory.db", &reg_pdev->dev);
1107         if (err)
1108                 return err;
1109
1110         if (!valid_regdb(fw->data, fw->size)) {
1111                 err = -ENODATA;
1112                 goto out;
1113         }
1114
1115         db = kmemdup(fw->data, fw->size, GFP_KERNEL);
1116         if (!db) {
1117                 err = -ENOMEM;
1118                 goto out;
1119         }
1120
1121         rtnl_lock();
1122         if (!IS_ERR_OR_NULL(regdb))
1123                 kfree(regdb);
1124         regdb = db;
1125         rtnl_unlock();
1126
1127  out:
1128         release_firmware(fw);
1129         return err;
1130 }
1131
1132 static bool reg_query_database(struct regulatory_request *request)
1133 {
1134         if (query_regdb_file(request->alpha2) == 0)
1135                 return true;
1136
1137         if (call_crda(request->alpha2) == 0)
1138                 return true;
1139
1140         return false;
1141 }
1142
1143 bool reg_is_valid_request(const char *alpha2)
1144 {
1145         struct regulatory_request *lr = get_last_request();
1146
1147         if (!lr || lr->processed)
1148                 return false;
1149
1150         return alpha2_equal(lr->alpha2, alpha2);
1151 }
1152
1153 static const struct ieee80211_regdomain *reg_get_regdomain(struct wiphy *wiphy)
1154 {
1155         struct regulatory_request *lr = get_last_request();
1156
1157         /*
1158          * Follow the driver's regulatory domain, if present, unless a country
1159          * IE has been processed or a user wants to help complaince further
1160          */
1161         if (lr->initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE &&
1162             lr->initiator != NL80211_REGDOM_SET_BY_USER &&
1163             wiphy->regd)
1164                 return get_wiphy_regdom(wiphy);
1165
1166         return get_cfg80211_regdom();
1167 }
1168
1169 static unsigned int
1170 reg_get_max_bandwidth_from_range(const struct ieee80211_regdomain *rd,
1171                                  const struct ieee80211_reg_rule *rule)
1172 {
1173         const struct ieee80211_freq_range *freq_range = &rule->freq_range;
1174         const struct ieee80211_freq_range *freq_range_tmp;
1175         const struct ieee80211_reg_rule *tmp;
1176         u32 start_freq, end_freq, idx, no;
1177
1178         for (idx = 0; idx < rd->n_reg_rules; idx++)
1179                 if (rule == &rd->reg_rules[idx])
1180                         break;
1181
1182         if (idx == rd->n_reg_rules)
1183                 return 0;
1184
1185         /* get start_freq */
1186         no = idx;
1187
1188         while (no) {
1189                 tmp = &rd->reg_rules[--no];
1190                 freq_range_tmp = &tmp->freq_range;
1191
1192                 if (freq_range_tmp->end_freq_khz < freq_range->start_freq_khz)
1193                         break;
1194
1195                 freq_range = freq_range_tmp;
1196         }
1197
1198         start_freq = freq_range->start_freq_khz;
1199
1200         /* get end_freq */
1201         freq_range = &rule->freq_range;
1202         no = idx;
1203
1204         while (no < rd->n_reg_rules - 1) {
1205                 tmp = &rd->reg_rules[++no];
1206                 freq_range_tmp = &tmp->freq_range;
1207
1208                 if (freq_range_tmp->start_freq_khz > freq_range->end_freq_khz)
1209                         break;
1210
1211                 freq_range = freq_range_tmp;
1212         }
1213
1214         end_freq = freq_range->end_freq_khz;
1215
1216         return end_freq - start_freq;
1217 }
1218
1219 unsigned int reg_get_max_bandwidth(const struct ieee80211_regdomain *rd,
1220                                    const struct ieee80211_reg_rule *rule)
1221 {
1222         unsigned int bw = reg_get_max_bandwidth_from_range(rd, rule);
1223
1224         if (rule->flags & NL80211_RRF_NO_160MHZ)
1225                 bw = min_t(unsigned int, bw, MHZ_TO_KHZ(80));
1226         if (rule->flags & NL80211_RRF_NO_80MHZ)
1227                 bw = min_t(unsigned int, bw, MHZ_TO_KHZ(40));
1228
1229         /*
1230          * HT40+/HT40- limits are handled per-channel. Only limit BW if both
1231          * are not allowed.
1232          */
1233         if (rule->flags & NL80211_RRF_NO_HT40MINUS &&
1234             rule->flags & NL80211_RRF_NO_HT40PLUS)
1235                 bw = min_t(unsigned int, bw, MHZ_TO_KHZ(20));
1236
1237         return bw;
1238 }
1239
1240 /* Sanity check on a regulatory rule */
1241 static bool is_valid_reg_rule(const struct ieee80211_reg_rule *rule)
1242 {
1243         const struct ieee80211_freq_range *freq_range = &rule->freq_range;
1244         u32 freq_diff;
1245
1246         if (freq_range->start_freq_khz <= 0 || freq_range->end_freq_khz <= 0)
1247                 return false;
1248
1249         if (freq_range->start_freq_khz > freq_range->end_freq_khz)
1250                 return false;
1251
1252         freq_diff = freq_range->end_freq_khz - freq_range->start_freq_khz;
1253
1254         if (freq_range->end_freq_khz <= freq_range->start_freq_khz ||
1255             freq_range->max_bandwidth_khz > freq_diff)
1256                 return false;
1257
1258         return true;
1259 }
1260
1261 static bool is_valid_rd(const struct ieee80211_regdomain *rd)
1262 {
1263         const struct ieee80211_reg_rule *reg_rule = NULL;
1264         unsigned int i;
1265
1266         if (!rd->n_reg_rules)
1267                 return false;
1268
1269         if (WARN_ON(rd->n_reg_rules > NL80211_MAX_SUPP_REG_RULES))
1270                 return false;
1271
1272         for (i = 0; i < rd->n_reg_rules; i++) {
1273                 reg_rule = &rd->reg_rules[i];
1274                 if (!is_valid_reg_rule(reg_rule))
1275                         return false;
1276         }
1277
1278         return true;
1279 }
1280
1281 /**
1282  * freq_in_rule_band - tells us if a frequency is in a frequency band
1283  * @freq_range: frequency rule we want to query
1284  * @freq_khz: frequency we are inquiring about
1285  *
1286  * This lets us know if a specific frequency rule is or is not relevant to
1287  * a specific frequency's band. Bands are device specific and artificial
1288  * definitions (the "2.4 GHz band", the "5 GHz band" and the "60GHz band"),
1289  * however it is safe for now to assume that a frequency rule should not be
1290  * part of a frequency's band if the start freq or end freq are off by more
1291  * than 2 GHz for the 2.4 and 5 GHz bands, and by more than 20 GHz for the
1292  * 60 GHz band.
1293  * This resolution can be lowered and should be considered as we add
1294  * regulatory rule support for other "bands".
1295  **/
1296 static bool freq_in_rule_band(const struct ieee80211_freq_range *freq_range,
1297                               u32 freq_khz)
1298 {
1299 #define ONE_GHZ_IN_KHZ  1000000
1300         /*
1301          * From 802.11ad: directional multi-gigabit (DMG):
1302          * Pertaining to operation in a frequency band containing a channel
1303          * with the Channel starting frequency above 45 GHz.
1304          */
1305         u32 limit = freq_khz > 45 * ONE_GHZ_IN_KHZ ?
1306                         20 * ONE_GHZ_IN_KHZ : 2 * ONE_GHZ_IN_KHZ;
1307         if (abs(freq_khz - freq_range->start_freq_khz) <= limit)
1308                 return true;
1309         if (abs(freq_khz - freq_range->end_freq_khz) <= limit)
1310                 return true;
1311         return false;
1312 #undef ONE_GHZ_IN_KHZ
1313 }
1314
1315 /*
1316  * Later on we can perhaps use the more restrictive DFS
1317  * region but we don't have information for that yet so
1318  * for now simply disallow conflicts.
1319  */
1320 static enum nl80211_dfs_regions
1321 reg_intersect_dfs_region(const enum nl80211_dfs_regions dfs_region1,
1322                          const enum nl80211_dfs_regions dfs_region2)
1323 {
1324         if (dfs_region1 != dfs_region2)
1325                 return NL80211_DFS_UNSET;
1326         return dfs_region1;
1327 }
1328
1329 static void reg_wmm_rules_intersect(const struct ieee80211_wmm_ac *wmm_ac1,
1330                                     const struct ieee80211_wmm_ac *wmm_ac2,
1331                                     struct ieee80211_wmm_ac *intersect)
1332 {
1333         intersect->cw_min = max_t(u16, wmm_ac1->cw_min, wmm_ac2->cw_min);
1334         intersect->cw_max = max_t(u16, wmm_ac1->cw_max, wmm_ac2->cw_max);
1335         intersect->cot = min_t(u16, wmm_ac1->cot, wmm_ac2->cot);
1336         intersect->aifsn = max_t(u8, wmm_ac1->aifsn, wmm_ac2->aifsn);
1337 }
1338
1339 /*
1340  * Helper for regdom_intersect(), this does the real
1341  * mathematical intersection fun
1342  */
1343 static int reg_rules_intersect(const struct ieee80211_regdomain *rd1,
1344                                const struct ieee80211_regdomain *rd2,
1345                                const struct ieee80211_reg_rule *rule1,
1346                                const struct ieee80211_reg_rule *rule2,
1347                                struct ieee80211_reg_rule *intersected_rule)
1348 {
1349         const struct ieee80211_freq_range *freq_range1, *freq_range2;
1350         struct ieee80211_freq_range *freq_range;
1351         const struct ieee80211_power_rule *power_rule1, *power_rule2;
1352         struct ieee80211_power_rule *power_rule;
1353         const struct ieee80211_wmm_rule *wmm_rule1, *wmm_rule2;
1354         struct ieee80211_wmm_rule *wmm_rule;
1355         u32 freq_diff, max_bandwidth1, max_bandwidth2;
1356
1357         freq_range1 = &rule1->freq_range;
1358         freq_range2 = &rule2->freq_range;
1359         freq_range = &intersected_rule->freq_range;
1360
1361         power_rule1 = &rule1->power_rule;
1362         power_rule2 = &rule2->power_rule;
1363         power_rule = &intersected_rule->power_rule;
1364
1365         wmm_rule1 = &rule1->wmm_rule;
1366         wmm_rule2 = &rule2->wmm_rule;
1367         wmm_rule = &intersected_rule->wmm_rule;
1368
1369         freq_range->start_freq_khz = max(freq_range1->start_freq_khz,
1370                                          freq_range2->start_freq_khz);
1371         freq_range->end_freq_khz = min(freq_range1->end_freq_khz,
1372                                        freq_range2->end_freq_khz);
1373
1374         max_bandwidth1 = freq_range1->max_bandwidth_khz;
1375         max_bandwidth2 = freq_range2->max_bandwidth_khz;
1376
1377         if (rule1->flags & NL80211_RRF_AUTO_BW)
1378                 max_bandwidth1 = reg_get_max_bandwidth(rd1, rule1);
1379         if (rule2->flags & NL80211_RRF_AUTO_BW)
1380                 max_bandwidth2 = reg_get_max_bandwidth(rd2, rule2);
1381
1382         freq_range->max_bandwidth_khz = min(max_bandwidth1, max_bandwidth2);
1383
1384         intersected_rule->flags = rule1->flags | rule2->flags;
1385
1386         /*
1387          * In case NL80211_RRF_AUTO_BW requested for both rules
1388          * set AUTO_BW in intersected rule also. Next we will
1389          * calculate BW correctly in handle_channel function.
1390          * In other case remove AUTO_BW flag while we calculate
1391          * maximum bandwidth correctly and auto calculation is
1392          * not required.
1393          */
1394         if ((rule1->flags & NL80211_RRF_AUTO_BW) &&
1395             (rule2->flags & NL80211_RRF_AUTO_BW))
1396                 intersected_rule->flags |= NL80211_RRF_AUTO_BW;
1397         else
1398                 intersected_rule->flags &= ~NL80211_RRF_AUTO_BW;
1399
1400         freq_diff = freq_range->end_freq_khz - freq_range->start_freq_khz;
1401         if (freq_range->max_bandwidth_khz > freq_diff)
1402                 freq_range->max_bandwidth_khz = freq_diff;
1403
1404         power_rule->max_eirp = min(power_rule1->max_eirp,
1405                 power_rule2->max_eirp);
1406         power_rule->max_antenna_gain = min(power_rule1->max_antenna_gain,
1407                 power_rule2->max_antenna_gain);
1408
1409         intersected_rule->dfs_cac_ms = max(rule1->dfs_cac_ms,
1410                                            rule2->dfs_cac_ms);
1411
1412         if (rule1->has_wmm && rule2->has_wmm) {
1413                 u8 ac;
1414
1415                 for (ac = 0; ac < IEEE80211_NUM_ACS; ac++) {
1416                         reg_wmm_rules_intersect(&wmm_rule1->client[ac],
1417                                                 &wmm_rule2->client[ac],
1418                                                 &wmm_rule->client[ac]);
1419                         reg_wmm_rules_intersect(&wmm_rule1->ap[ac],
1420                                                 &wmm_rule2->ap[ac],
1421                                                 &wmm_rule->ap[ac]);
1422                 }
1423
1424                 intersected_rule->has_wmm = true;
1425         } else if (rule1->has_wmm) {
1426                 *wmm_rule = *wmm_rule1;
1427                 intersected_rule->has_wmm = true;
1428         } else if (rule2->has_wmm) {
1429                 *wmm_rule = *wmm_rule2;
1430                 intersected_rule->has_wmm = true;
1431         } else {
1432                 intersected_rule->has_wmm = false;
1433         }
1434
1435         if (!is_valid_reg_rule(intersected_rule))
1436                 return -EINVAL;
1437
1438         return 0;
1439 }
1440
1441 /* check whether old rule contains new rule */
1442 static bool rule_contains(struct ieee80211_reg_rule *r1,
1443                           struct ieee80211_reg_rule *r2)
1444 {
1445         /* for simplicity, currently consider only same flags */
1446         if (r1->flags != r2->flags)
1447                 return false;
1448
1449         /* verify r1 is more restrictive */
1450         if ((r1->power_rule.max_antenna_gain >
1451              r2->power_rule.max_antenna_gain) ||
1452             r1->power_rule.max_eirp > r2->power_rule.max_eirp)
1453                 return false;
1454
1455         /* make sure r2's range is contained within r1 */
1456         if (r1->freq_range.start_freq_khz > r2->freq_range.start_freq_khz ||
1457             r1->freq_range.end_freq_khz < r2->freq_range.end_freq_khz)
1458                 return false;
1459
1460         /* and finally verify that r1.max_bw >= r2.max_bw */
1461         if (r1->freq_range.max_bandwidth_khz <
1462             r2->freq_range.max_bandwidth_khz)
1463                 return false;
1464
1465         return true;
1466 }
1467
1468 /* add or extend current rules. do nothing if rule is already contained */
1469 static void add_rule(struct ieee80211_reg_rule *rule,
1470                      struct ieee80211_reg_rule *reg_rules, u32 *n_rules)
1471 {
1472         struct ieee80211_reg_rule *tmp_rule;
1473         int i;
1474
1475         for (i = 0; i < *n_rules; i++) {
1476                 tmp_rule = &reg_rules[i];
1477                 /* rule is already contained - do nothing */
1478                 if (rule_contains(tmp_rule, rule))
1479                         return;
1480
1481                 /* extend rule if possible */
1482                 if (rule_contains(rule, tmp_rule)) {
1483                         memcpy(tmp_rule, rule, sizeof(*rule));
1484                         return;
1485                 }
1486         }
1487
1488         memcpy(&reg_rules[*n_rules], rule, sizeof(*rule));
1489         (*n_rules)++;
1490 }
1491
1492 /**
1493  * regdom_intersect - do the intersection between two regulatory domains
1494  * @rd1: first regulatory domain
1495  * @rd2: second regulatory domain
1496  *
1497  * Use this function to get the intersection between two regulatory domains.
1498  * Once completed we will mark the alpha2 for the rd as intersected, "98",
1499  * as no one single alpha2 can represent this regulatory domain.
1500  *
1501  * Returns a pointer to the regulatory domain structure which will hold the
1502  * resulting intersection of rules between rd1 and rd2. We will
1503  * kzalloc() this structure for you.
1504  */
1505 static struct ieee80211_regdomain *
1506 regdom_intersect(const struct ieee80211_regdomain *rd1,
1507                  const struct ieee80211_regdomain *rd2)
1508 {
1509         int r;
1510         unsigned int x, y;
1511         unsigned int num_rules = 0;
1512         const struct ieee80211_reg_rule *rule1, *rule2;
1513         struct ieee80211_reg_rule intersected_rule;
1514         struct ieee80211_regdomain *rd;
1515
1516         if (!rd1 || !rd2)
1517                 return NULL;
1518
1519         /*
1520          * First we get a count of the rules we'll need, then we actually
1521          * build them. This is to so we can malloc() and free() a
1522          * regdomain once. The reason we use reg_rules_intersect() here
1523          * is it will return -EINVAL if the rule computed makes no sense.
1524          * All rules that do check out OK are valid.
1525          */
1526
1527         for (x = 0; x < rd1->n_reg_rules; x++) {
1528                 rule1 = &rd1->reg_rules[x];
1529                 for (y = 0; y < rd2->n_reg_rules; y++) {
1530                         rule2 = &rd2->reg_rules[y];
1531                         if (!reg_rules_intersect(rd1, rd2, rule1, rule2,
1532                                                  &intersected_rule))
1533                                 num_rules++;
1534                 }
1535         }
1536
1537         if (!num_rules)
1538                 return NULL;
1539
1540         rd = kzalloc(struct_size(rd, reg_rules, num_rules), GFP_KERNEL);
1541         if (!rd)
1542                 return NULL;
1543
1544         for (x = 0; x < rd1->n_reg_rules; x++) {
1545                 rule1 = &rd1->reg_rules[x];
1546                 for (y = 0; y < rd2->n_reg_rules; y++) {
1547                         rule2 = &rd2->reg_rules[y];
1548                         r = reg_rules_intersect(rd1, rd2, rule1, rule2,
1549                                                 &intersected_rule);
1550                         /*
1551                          * No need to memset here the intersected rule here as
1552                          * we're not using the stack anymore
1553                          */
1554                         if (r)
1555                                 continue;
1556
1557                         add_rule(&intersected_rule, rd->reg_rules,
1558                                  &rd->n_reg_rules);
1559                 }
1560         }
1561
1562         rd->alpha2[0] = '9';
1563         rd->alpha2[1] = '8';
1564         rd->dfs_region = reg_intersect_dfs_region(rd1->dfs_region,
1565                                                   rd2->dfs_region);
1566
1567         return rd;
1568 }
1569
1570 /*
1571  * XXX: add support for the rest of enum nl80211_reg_rule_flags, we may
1572  * want to just have the channel structure use these
1573  */
1574 static u32 map_regdom_flags(u32 rd_flags)
1575 {
1576         u32 channel_flags = 0;
1577         if (rd_flags & NL80211_RRF_NO_IR_ALL)
1578                 channel_flags |= IEEE80211_CHAN_NO_IR;
1579         if (rd_flags & NL80211_RRF_DFS)
1580                 channel_flags |= IEEE80211_CHAN_RADAR;
1581         if (rd_flags & NL80211_RRF_NO_OFDM)
1582                 channel_flags |= IEEE80211_CHAN_NO_OFDM;
1583         if (rd_flags & NL80211_RRF_NO_OUTDOOR)
1584                 channel_flags |= IEEE80211_CHAN_INDOOR_ONLY;
1585         if (rd_flags & NL80211_RRF_IR_CONCURRENT)
1586                 channel_flags |= IEEE80211_CHAN_IR_CONCURRENT;
1587         if (rd_flags & NL80211_RRF_NO_HT40MINUS)
1588                 channel_flags |= IEEE80211_CHAN_NO_HT40MINUS;
1589         if (rd_flags & NL80211_RRF_NO_HT40PLUS)
1590                 channel_flags |= IEEE80211_CHAN_NO_HT40PLUS;
1591         if (rd_flags & NL80211_RRF_NO_80MHZ)
1592                 channel_flags |= IEEE80211_CHAN_NO_80MHZ;
1593         if (rd_flags & NL80211_RRF_NO_160MHZ)
1594                 channel_flags |= IEEE80211_CHAN_NO_160MHZ;
1595         if (rd_flags & NL80211_RRF_NO_HE)
1596                 channel_flags |= IEEE80211_CHAN_NO_HE;
1597         return channel_flags;
1598 }
1599
1600 static const struct ieee80211_reg_rule *
1601 freq_reg_info_regd(u32 center_freq,
1602                    const struct ieee80211_regdomain *regd, u32 bw)
1603 {
1604         int i;
1605         bool band_rule_found = false;
1606         bool bw_fits = false;
1607
1608         if (!regd)
1609                 return ERR_PTR(-EINVAL);
1610
1611         for (i = 0; i < regd->n_reg_rules; i++) {
1612                 const struct ieee80211_reg_rule *rr;
1613                 const struct ieee80211_freq_range *fr = NULL;
1614
1615                 rr = &regd->reg_rules[i];
1616                 fr = &rr->freq_range;
1617
1618                 /*
1619                  * We only need to know if one frequency rule was
1620                  * in center_freq's band, that's enough, so let's
1621                  * not overwrite it once found
1622                  */
1623                 if (!band_rule_found)
1624                         band_rule_found = freq_in_rule_band(fr, center_freq);
1625
1626                 bw_fits = cfg80211_does_bw_fit_range(fr, center_freq, bw);
1627
1628                 if (band_rule_found && bw_fits)
1629                         return rr;
1630         }
1631
1632         if (!band_rule_found)
1633                 return ERR_PTR(-ERANGE);
1634
1635         return ERR_PTR(-EINVAL);
1636 }
1637
1638 static const struct ieee80211_reg_rule *
1639 __freq_reg_info(struct wiphy *wiphy, u32 center_freq, u32 min_bw)
1640 {
1641         const struct ieee80211_regdomain *regd = reg_get_regdomain(wiphy);
1642         static const u32 bws[] = {0, 1, 2, 4, 5, 8, 10, 16, 20};
1643         const struct ieee80211_reg_rule *reg_rule = ERR_PTR(-ERANGE);
1644         int i = ARRAY_SIZE(bws) - 1;
1645         u32 bw;
1646
1647         for (bw = MHZ_TO_KHZ(bws[i]); bw >= min_bw; bw = MHZ_TO_KHZ(bws[i--])) {
1648                 reg_rule = freq_reg_info_regd(center_freq, regd, bw);
1649                 if (!IS_ERR(reg_rule))
1650                         return reg_rule;
1651         }
1652
1653         return reg_rule;
1654 }
1655
1656 const struct ieee80211_reg_rule *freq_reg_info(struct wiphy *wiphy,
1657                                                u32 center_freq)
1658 {
1659         u32 min_bw = center_freq < MHZ_TO_KHZ(1000) ? 1 : 20;
1660
1661         return __freq_reg_info(wiphy, center_freq, MHZ_TO_KHZ(min_bw));
1662 }
1663 EXPORT_SYMBOL(freq_reg_info);
1664
1665 const char *reg_initiator_name(enum nl80211_reg_initiator initiator)
1666 {
1667         switch (initiator) {
1668         case NL80211_REGDOM_SET_BY_CORE:
1669                 return "core";
1670         case NL80211_REGDOM_SET_BY_USER:
1671                 return "user";
1672         case NL80211_REGDOM_SET_BY_DRIVER:
1673                 return "driver";
1674         case NL80211_REGDOM_SET_BY_COUNTRY_IE:
1675                 return "country element";
1676         default:
1677                 WARN_ON(1);
1678                 return "bug";
1679         }
1680 }
1681 EXPORT_SYMBOL(reg_initiator_name);
1682
1683 static uint32_t reg_rule_to_chan_bw_flags(const struct ieee80211_regdomain *regd,
1684                                           const struct ieee80211_reg_rule *reg_rule,
1685                                           const struct ieee80211_channel *chan)
1686 {
1687         const struct ieee80211_freq_range *freq_range = NULL;
1688         u32 max_bandwidth_khz, center_freq_khz, bw_flags = 0;
1689         bool is_s1g = chan->band == NL80211_BAND_S1GHZ;
1690
1691         freq_range = &reg_rule->freq_range;
1692
1693         max_bandwidth_khz = freq_range->max_bandwidth_khz;
1694         center_freq_khz = ieee80211_channel_to_khz(chan);
1695         /* Check if auto calculation requested */
1696         if (reg_rule->flags & NL80211_RRF_AUTO_BW)
1697                 max_bandwidth_khz = reg_get_max_bandwidth(regd, reg_rule);
1698
1699         /* If we get a reg_rule we can assume that at least 5Mhz fit */
1700         if (!cfg80211_does_bw_fit_range(freq_range,
1701                                         center_freq_khz,
1702                                         MHZ_TO_KHZ(10)))
1703                 bw_flags |= IEEE80211_CHAN_NO_10MHZ;
1704         if (!cfg80211_does_bw_fit_range(freq_range,
1705                                         center_freq_khz,
1706                                         MHZ_TO_KHZ(20)))
1707                 bw_flags |= IEEE80211_CHAN_NO_20MHZ;
1708
1709         if (is_s1g) {
1710                 /* S1G is strict about non overlapping channels. We can
1711                  * calculate which bandwidth is allowed per channel by finding
1712                  * the largest bandwidth which cleanly divides the freq_range.
1713                  */
1714                 int edge_offset;
1715                 int ch_bw = max_bandwidth_khz;
1716
1717                 while (ch_bw) {
1718                         edge_offset = (center_freq_khz - ch_bw / 2) -
1719                                       freq_range->start_freq_khz;
1720                         if (edge_offset % ch_bw == 0) {
1721                                 switch (KHZ_TO_MHZ(ch_bw)) {
1722                                 case 1:
1723                                         bw_flags |= IEEE80211_CHAN_1MHZ;
1724                                         break;
1725                                 case 2:
1726                                         bw_flags |= IEEE80211_CHAN_2MHZ;
1727                                         break;
1728                                 case 4:
1729                                         bw_flags |= IEEE80211_CHAN_4MHZ;
1730                                         break;
1731                                 case 8:
1732                                         bw_flags |= IEEE80211_CHAN_8MHZ;
1733                                         break;
1734                                 case 16:
1735                                         bw_flags |= IEEE80211_CHAN_16MHZ;
1736                                         break;
1737                                 default:
1738                                         /* If we got here, no bandwidths fit on
1739                                          * this frequency, ie. band edge.
1740                                          */
1741                                         bw_flags |= IEEE80211_CHAN_DISABLED;
1742                                         break;
1743                                 }
1744                                 break;
1745                         }
1746                         ch_bw /= 2;
1747                 }
1748         } else {
1749                 if (max_bandwidth_khz < MHZ_TO_KHZ(10))
1750                         bw_flags |= IEEE80211_CHAN_NO_10MHZ;
1751                 if (max_bandwidth_khz < MHZ_TO_KHZ(20))
1752                         bw_flags |= IEEE80211_CHAN_NO_20MHZ;
1753                 if (max_bandwidth_khz < MHZ_TO_KHZ(40))
1754                         bw_flags |= IEEE80211_CHAN_NO_HT40;
1755                 if (max_bandwidth_khz < MHZ_TO_KHZ(80))
1756                         bw_flags |= IEEE80211_CHAN_NO_80MHZ;
1757                 if (max_bandwidth_khz < MHZ_TO_KHZ(160))
1758                         bw_flags |= IEEE80211_CHAN_NO_160MHZ;
1759         }
1760         return bw_flags;
1761 }
1762
1763 static void handle_channel_single_rule(struct wiphy *wiphy,
1764                                        enum nl80211_reg_initiator initiator,
1765                                        struct ieee80211_channel *chan,
1766                                        u32 flags,
1767                                        struct regulatory_request *lr,
1768                                        struct wiphy *request_wiphy,
1769                                        const struct ieee80211_reg_rule *reg_rule)
1770 {
1771         u32 bw_flags = 0;
1772         const struct ieee80211_power_rule *power_rule = NULL;
1773         const struct ieee80211_regdomain *regd;
1774
1775         regd = reg_get_regdomain(wiphy);
1776
1777         power_rule = &reg_rule->power_rule;
1778         bw_flags = reg_rule_to_chan_bw_flags(regd, reg_rule, chan);
1779
1780         if (lr->initiator == NL80211_REGDOM_SET_BY_DRIVER &&
1781             request_wiphy && request_wiphy == wiphy &&
1782             request_wiphy->regulatory_flags & REGULATORY_STRICT_REG) {
1783                 /*
1784                  * This guarantees the driver's requested regulatory domain
1785                  * will always be used as a base for further regulatory
1786                  * settings
1787                  */
1788                 chan->flags = chan->orig_flags =
1789                         map_regdom_flags(reg_rule->flags) | bw_flags;
1790                 chan->max_antenna_gain = chan->orig_mag =
1791                         (int) MBI_TO_DBI(power_rule->max_antenna_gain);
1792                 chan->max_reg_power = chan->max_power = chan->orig_mpwr =
1793                         (int) MBM_TO_DBM(power_rule->max_eirp);
1794
1795                 if (chan->flags & IEEE80211_CHAN_RADAR) {
1796                         chan->dfs_cac_ms = IEEE80211_DFS_MIN_CAC_TIME_MS;
1797                         if (reg_rule->dfs_cac_ms)
1798                                 chan->dfs_cac_ms = reg_rule->dfs_cac_ms;
1799                 }
1800
1801                 return;
1802         }
1803
1804         chan->dfs_state = NL80211_DFS_USABLE;
1805         chan->dfs_state_entered = jiffies;
1806
1807         chan->beacon_found = false;
1808         chan->flags = flags | bw_flags | map_regdom_flags(reg_rule->flags);
1809         chan->max_antenna_gain =
1810                 min_t(int, chan->orig_mag,
1811                       MBI_TO_DBI(power_rule->max_antenna_gain));
1812         chan->max_reg_power = (int) MBM_TO_DBM(power_rule->max_eirp);
1813
1814         if (chan->flags & IEEE80211_CHAN_RADAR) {
1815                 if (reg_rule->dfs_cac_ms)
1816                         chan->dfs_cac_ms = reg_rule->dfs_cac_ms;
1817                 else
1818                         chan->dfs_cac_ms = IEEE80211_DFS_MIN_CAC_TIME_MS;
1819         }
1820
1821         if (chan->orig_mpwr) {
1822                 /*
1823                  * Devices that use REGULATORY_COUNTRY_IE_FOLLOW_POWER
1824                  * will always follow the passed country IE power settings.
1825                  */
1826                 if (initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE &&
1827                     wiphy->regulatory_flags & REGULATORY_COUNTRY_IE_FOLLOW_POWER)
1828                         chan->max_power = chan->max_reg_power;
1829                 else
1830                         chan->max_power = min(chan->orig_mpwr,
1831                                               chan->max_reg_power);
1832         } else
1833                 chan->max_power = chan->max_reg_power;
1834 }
1835
1836 static void handle_channel_adjacent_rules(struct wiphy *wiphy,
1837                                           enum nl80211_reg_initiator initiator,
1838                                           struct ieee80211_channel *chan,
1839                                           u32 flags,
1840                                           struct regulatory_request *lr,
1841                                           struct wiphy *request_wiphy,
1842                                           const struct ieee80211_reg_rule *rrule1,
1843                                           const struct ieee80211_reg_rule *rrule2,
1844                                           struct ieee80211_freq_range *comb_range)
1845 {
1846         u32 bw_flags1 = 0;
1847         u32 bw_flags2 = 0;
1848         const struct ieee80211_power_rule *power_rule1 = NULL;
1849         const struct ieee80211_power_rule *power_rule2 = NULL;
1850         const struct ieee80211_regdomain *regd;
1851
1852         regd = reg_get_regdomain(wiphy);
1853
1854         power_rule1 = &rrule1->power_rule;
1855         power_rule2 = &rrule2->power_rule;
1856         bw_flags1 = reg_rule_to_chan_bw_flags(regd, rrule1, chan);
1857         bw_flags2 = reg_rule_to_chan_bw_flags(regd, rrule2, chan);
1858
1859         if (lr->initiator == NL80211_REGDOM_SET_BY_DRIVER &&
1860             request_wiphy && request_wiphy == wiphy &&
1861             request_wiphy->regulatory_flags & REGULATORY_STRICT_REG) {
1862                 /* This guarantees the driver's requested regulatory domain
1863                  * will always be used as a base for further regulatory
1864                  * settings
1865                  */
1866                 chan->flags =
1867                         map_regdom_flags(rrule1->flags) |
1868                         map_regdom_flags(rrule2->flags) |
1869                         bw_flags1 |
1870                         bw_flags2;
1871                 chan->orig_flags = chan->flags;
1872                 chan->max_antenna_gain =
1873                         min_t(int, MBI_TO_DBI(power_rule1->max_antenna_gain),
1874                               MBI_TO_DBI(power_rule2->max_antenna_gain));
1875                 chan->orig_mag = chan->max_antenna_gain;
1876                 chan->max_reg_power =
1877                         min_t(int, MBM_TO_DBM(power_rule1->max_eirp),
1878                               MBM_TO_DBM(power_rule2->max_eirp));
1879                 chan->max_power = chan->max_reg_power;
1880                 chan->orig_mpwr = chan->max_reg_power;
1881
1882                 if (chan->flags & IEEE80211_CHAN_RADAR) {
1883                         chan->dfs_cac_ms = IEEE80211_DFS_MIN_CAC_TIME_MS;
1884                         if (rrule1->dfs_cac_ms || rrule2->dfs_cac_ms)
1885                                 chan->dfs_cac_ms = max_t(unsigned int,
1886                                                          rrule1->dfs_cac_ms,
1887                                                          rrule2->dfs_cac_ms);
1888                 }
1889
1890                 return;
1891         }
1892
1893         chan->dfs_state = NL80211_DFS_USABLE;
1894         chan->dfs_state_entered = jiffies;
1895
1896         chan->beacon_found = false;
1897         chan->flags = flags | bw_flags1 | bw_flags2 |
1898                       map_regdom_flags(rrule1->flags) |
1899                       map_regdom_flags(rrule2->flags);
1900
1901         /* reg_rule_to_chan_bw_flags may forbids 10 and forbids 20 MHz
1902          * (otherwise no adj. rule case), recheck therefore
1903          */
1904         if (cfg80211_does_bw_fit_range(comb_range,
1905                                        ieee80211_channel_to_khz(chan),
1906                                        MHZ_TO_KHZ(10)))
1907                 chan->flags &= ~IEEE80211_CHAN_NO_10MHZ;
1908         if (cfg80211_does_bw_fit_range(comb_range,
1909                                        ieee80211_channel_to_khz(chan),
1910                                        MHZ_TO_KHZ(20)))
1911                 chan->flags &= ~IEEE80211_CHAN_NO_20MHZ;
1912
1913         chan->max_antenna_gain =
1914                 min_t(int, chan->orig_mag,
1915                       min_t(int,
1916                             MBI_TO_DBI(power_rule1->max_antenna_gain),
1917                             MBI_TO_DBI(power_rule2->max_antenna_gain)));
1918         chan->max_reg_power = min_t(int,
1919                                     MBM_TO_DBM(power_rule1->max_eirp),
1920                                     MBM_TO_DBM(power_rule2->max_eirp));
1921
1922         if (chan->flags & IEEE80211_CHAN_RADAR) {
1923                 if (rrule1->dfs_cac_ms || rrule2->dfs_cac_ms)
1924                         chan->dfs_cac_ms = max_t(unsigned int,
1925                                                  rrule1->dfs_cac_ms,
1926                                                  rrule2->dfs_cac_ms);
1927                 else
1928                         chan->dfs_cac_ms = IEEE80211_DFS_MIN_CAC_TIME_MS;
1929         }
1930
1931         if (chan->orig_mpwr) {
1932                 /* Devices that use REGULATORY_COUNTRY_IE_FOLLOW_POWER
1933                  * will always follow the passed country IE power settings.
1934                  */
1935                 if (initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE &&
1936                     wiphy->regulatory_flags & REGULATORY_COUNTRY_IE_FOLLOW_POWER)
1937                         chan->max_power = chan->max_reg_power;
1938                 else
1939                         chan->max_power = min(chan->orig_mpwr,
1940                                               chan->max_reg_power);
1941         } else {
1942                 chan->max_power = chan->max_reg_power;
1943         }
1944 }
1945
1946 /* Note that right now we assume the desired channel bandwidth
1947  * is always 20 MHz for each individual channel (HT40 uses 20 MHz
1948  * per channel, the primary and the extension channel).
1949  */
1950 static void handle_channel(struct wiphy *wiphy,
1951                            enum nl80211_reg_initiator initiator,
1952                            struct ieee80211_channel *chan)
1953 {
1954         const u32 orig_chan_freq = ieee80211_channel_to_khz(chan);
1955         struct regulatory_request *lr = get_last_request();
1956         struct wiphy *request_wiphy = wiphy_idx_to_wiphy(lr->wiphy_idx);
1957         const struct ieee80211_reg_rule *rrule = NULL;
1958         const struct ieee80211_reg_rule *rrule1 = NULL;
1959         const struct ieee80211_reg_rule *rrule2 = NULL;
1960
1961         u32 flags = chan->orig_flags;
1962
1963         rrule = freq_reg_info(wiphy, orig_chan_freq);
1964         if (IS_ERR(rrule)) {
1965                 /* check for adjacent match, therefore get rules for
1966                  * chan - 20 MHz and chan + 20 MHz and test
1967                  * if reg rules are adjacent
1968                  */
1969                 rrule1 = freq_reg_info(wiphy,
1970                                        orig_chan_freq - MHZ_TO_KHZ(20));
1971                 rrule2 = freq_reg_info(wiphy,
1972                                        orig_chan_freq + MHZ_TO_KHZ(20));
1973                 if (!IS_ERR(rrule1) && !IS_ERR(rrule2)) {
1974                         struct ieee80211_freq_range comb_range;
1975
1976                         if (rrule1->freq_range.end_freq_khz !=
1977                             rrule2->freq_range.start_freq_khz)
1978                                 goto disable_chan;
1979
1980                         comb_range.start_freq_khz =
1981                                 rrule1->freq_range.start_freq_khz;
1982                         comb_range.end_freq_khz =
1983                                 rrule2->freq_range.end_freq_khz;
1984                         comb_range.max_bandwidth_khz =
1985                                 min_t(u32,
1986                                       rrule1->freq_range.max_bandwidth_khz,
1987                                       rrule2->freq_range.max_bandwidth_khz);
1988
1989                         if (!cfg80211_does_bw_fit_range(&comb_range,
1990                                                         orig_chan_freq,
1991                                                         MHZ_TO_KHZ(20)))
1992                                 goto disable_chan;
1993
1994                         handle_channel_adjacent_rules(wiphy, initiator, chan,
1995                                                       flags, lr, request_wiphy,
1996                                                       rrule1, rrule2,
1997                                                       &comb_range);
1998                         return;
1999                 }
2000
2001 disable_chan:
2002                 /* We will disable all channels that do not match our
2003                  * received regulatory rule unless the hint is coming
2004                  * from a Country IE and the Country IE had no information
2005                  * about a band. The IEEE 802.11 spec allows for an AP
2006                  * to send only a subset of the regulatory rules allowed,
2007                  * so an AP in the US that only supports 2.4 GHz may only send
2008                  * a country IE with information for the 2.4 GHz band
2009                  * while 5 GHz is still supported.
2010                  */
2011                 if (initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE &&
2012                     PTR_ERR(rrule) == -ERANGE)
2013                         return;
2014
2015                 if (lr->initiator == NL80211_REGDOM_SET_BY_DRIVER &&
2016                     request_wiphy && request_wiphy == wiphy &&
2017                     request_wiphy->regulatory_flags & REGULATORY_STRICT_REG) {
2018                         pr_debug("Disabling freq %d.%03d MHz for good\n",
2019                                  chan->center_freq, chan->freq_offset);
2020                         chan->orig_flags |= IEEE80211_CHAN_DISABLED;
2021                         chan->flags = chan->orig_flags;
2022                 } else {
2023                         pr_debug("Disabling freq %d.%03d MHz\n",
2024                                  chan->center_freq, chan->freq_offset);
2025                         chan->flags |= IEEE80211_CHAN_DISABLED;
2026                 }
2027                 return;
2028         }
2029
2030         handle_channel_single_rule(wiphy, initiator, chan, flags, lr,
2031                                    request_wiphy, rrule);
2032 }
2033
2034 static void handle_band(struct wiphy *wiphy,
2035                         enum nl80211_reg_initiator initiator,
2036                         struct ieee80211_supported_band *sband)
2037 {
2038         unsigned int i;
2039
2040         if (!sband)
2041                 return;
2042
2043         for (i = 0; i < sband->n_channels; i++)
2044                 handle_channel(wiphy, initiator, &sband->channels[i]);
2045 }
2046
2047 static bool reg_request_cell_base(struct regulatory_request *request)
2048 {
2049         if (request->initiator != NL80211_REGDOM_SET_BY_USER)
2050                 return false;
2051         return request->user_reg_hint_type == NL80211_USER_REG_HINT_CELL_BASE;
2052 }
2053
2054 bool reg_last_request_cell_base(void)
2055 {
2056         return reg_request_cell_base(get_last_request());
2057 }
2058
2059 #ifdef CONFIG_CFG80211_REG_CELLULAR_HINTS
2060 /* Core specific check */
2061 static enum reg_request_treatment
2062 reg_ignore_cell_hint(struct regulatory_request *pending_request)
2063 {
2064         struct regulatory_request *lr = get_last_request();
2065
2066         if (!reg_num_devs_support_basehint)
2067                 return REG_REQ_IGNORE;
2068
2069         if (reg_request_cell_base(lr) &&
2070             !regdom_changes(pending_request->alpha2))
2071                 return REG_REQ_ALREADY_SET;
2072
2073         return REG_REQ_OK;
2074 }
2075
2076 /* Device specific check */
2077 static bool reg_dev_ignore_cell_hint(struct wiphy *wiphy)
2078 {
2079         return !(wiphy->features & NL80211_FEATURE_CELL_BASE_REG_HINTS);
2080 }
2081 #else
2082 static enum reg_request_treatment
2083 reg_ignore_cell_hint(struct regulatory_request *pending_request)
2084 {
2085         return REG_REQ_IGNORE;
2086 }
2087
2088 static bool reg_dev_ignore_cell_hint(struct wiphy *wiphy)
2089 {
2090         return true;
2091 }
2092 #endif
2093
2094 static bool wiphy_strict_alpha2_regd(struct wiphy *wiphy)
2095 {
2096         if (wiphy->regulatory_flags & REGULATORY_STRICT_REG &&
2097             !(wiphy->regulatory_flags & REGULATORY_CUSTOM_REG))
2098                 return true;
2099         return false;
2100 }
2101
2102 static bool ignore_reg_update(struct wiphy *wiphy,
2103                               enum nl80211_reg_initiator initiator)
2104 {
2105         struct regulatory_request *lr = get_last_request();
2106
2107         if (wiphy->regulatory_flags & REGULATORY_WIPHY_SELF_MANAGED)
2108                 return true;
2109
2110         if (!lr) {
2111                 pr_debug("Ignoring regulatory request set by %s since last_request is not set\n",
2112                          reg_initiator_name(initiator));
2113                 return true;
2114         }
2115
2116         if (initiator == NL80211_REGDOM_SET_BY_CORE &&
2117             wiphy->regulatory_flags & REGULATORY_CUSTOM_REG) {
2118                 pr_debug("Ignoring regulatory request set by %s since the driver uses its own custom regulatory domain\n",
2119                          reg_initiator_name(initiator));
2120                 return true;
2121         }
2122
2123         /*
2124          * wiphy->regd will be set once the device has its own
2125          * desired regulatory domain set
2126          */
2127         if (wiphy_strict_alpha2_regd(wiphy) && !wiphy->regd &&
2128             initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE &&
2129             !is_world_regdom(lr->alpha2)) {
2130                 pr_debug("Ignoring regulatory request set by %s since the driver requires its own regulatory domain to be set first\n",
2131                          reg_initiator_name(initiator));
2132                 return true;
2133         }
2134
2135         if (reg_request_cell_base(lr))
2136                 return reg_dev_ignore_cell_hint(wiphy);
2137
2138         return false;
2139 }
2140
2141 static bool reg_is_world_roaming(struct wiphy *wiphy)
2142 {
2143         const struct ieee80211_regdomain *cr = get_cfg80211_regdom();
2144         const struct ieee80211_regdomain *wr = get_wiphy_regdom(wiphy);
2145         struct regulatory_request *lr = get_last_request();
2146
2147         if (is_world_regdom(cr->alpha2) || (wr && is_world_regdom(wr->alpha2)))
2148                 return true;
2149
2150         if (lr && lr->initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE &&
2151             wiphy->regulatory_flags & REGULATORY_CUSTOM_REG)
2152                 return true;
2153
2154         return false;
2155 }
2156
2157 static void handle_reg_beacon(struct wiphy *wiphy, unsigned int chan_idx,
2158                               struct reg_beacon *reg_beacon)
2159 {
2160         struct ieee80211_supported_band *sband;
2161         struct ieee80211_channel *chan;
2162         bool channel_changed = false;
2163         struct ieee80211_channel chan_before;
2164
2165         sband = wiphy->bands[reg_beacon->chan.band];
2166         chan = &sband->channels[chan_idx];
2167
2168         if (likely(!ieee80211_channel_equal(chan, &reg_beacon->chan)))
2169                 return;
2170
2171         if (chan->beacon_found)
2172                 return;
2173
2174         chan->beacon_found = true;
2175
2176         if (!reg_is_world_roaming(wiphy))
2177                 return;
2178
2179         if (wiphy->regulatory_flags & REGULATORY_DISABLE_BEACON_HINTS)
2180                 return;
2181
2182         chan_before = *chan;
2183
2184         if (chan->flags & IEEE80211_CHAN_NO_IR) {
2185                 chan->flags &= ~IEEE80211_CHAN_NO_IR;
2186                 channel_changed = true;
2187         }
2188
2189         if (channel_changed)
2190                 nl80211_send_beacon_hint_event(wiphy, &chan_before, chan);
2191 }
2192
2193 /*
2194  * Called when a scan on a wiphy finds a beacon on
2195  * new channel
2196  */
2197 static void wiphy_update_new_beacon(struct wiphy *wiphy,
2198                                     struct reg_beacon *reg_beacon)
2199 {
2200         unsigned int i;
2201         struct ieee80211_supported_band *sband;
2202
2203         if (!wiphy->bands[reg_beacon->chan.band])
2204                 return;
2205
2206         sband = wiphy->bands[reg_beacon->chan.band];
2207
2208         for (i = 0; i < sband->n_channels; i++)
2209                 handle_reg_beacon(wiphy, i, reg_beacon);
2210 }
2211
2212 /*
2213  * Called upon reg changes or a new wiphy is added
2214  */
2215 static void wiphy_update_beacon_reg(struct wiphy *wiphy)
2216 {
2217         unsigned int i;
2218         struct ieee80211_supported_band *sband;
2219         struct reg_beacon *reg_beacon;
2220
2221         list_for_each_entry(reg_beacon, &reg_beacon_list, list) {
2222                 if (!wiphy->bands[reg_beacon->chan.band])
2223                         continue;
2224                 sband = wiphy->bands[reg_beacon->chan.band];
2225                 for (i = 0; i < sband->n_channels; i++)
2226                         handle_reg_beacon(wiphy, i, reg_beacon);
2227         }
2228 }
2229
2230 /* Reap the advantages of previously found beacons */
2231 static void reg_process_beacons(struct wiphy *wiphy)
2232 {
2233         /*
2234          * Means we are just firing up cfg80211, so no beacons would
2235          * have been processed yet.
2236          */
2237         if (!last_request)
2238                 return;
2239         wiphy_update_beacon_reg(wiphy);
2240 }
2241
2242 static bool is_ht40_allowed(struct ieee80211_channel *chan)
2243 {
2244         if (!chan)
2245                 return false;
2246         if (chan->flags & IEEE80211_CHAN_DISABLED)
2247                 return false;
2248         /* This would happen when regulatory rules disallow HT40 completely */
2249         if ((chan->flags & IEEE80211_CHAN_NO_HT40) == IEEE80211_CHAN_NO_HT40)
2250                 return false;
2251         return true;
2252 }
2253
2254 static void reg_process_ht_flags_channel(struct wiphy *wiphy,
2255                                          struct ieee80211_channel *channel)
2256 {
2257         struct ieee80211_supported_band *sband = wiphy->bands[channel->band];
2258         struct ieee80211_channel *channel_before = NULL, *channel_after = NULL;
2259         const struct ieee80211_regdomain *regd;
2260         unsigned int i;
2261         u32 flags;
2262
2263         if (!is_ht40_allowed(channel)) {
2264                 channel->flags |= IEEE80211_CHAN_NO_HT40;
2265                 return;
2266         }
2267
2268         /*
2269          * We need to ensure the extension channels exist to
2270          * be able to use HT40- or HT40+, this finds them (or not)
2271          */
2272         for (i = 0; i < sband->n_channels; i++) {
2273                 struct ieee80211_channel *c = &sband->channels[i];
2274
2275                 if (c->center_freq == (channel->center_freq - 20))
2276                         channel_before = c;
2277                 if (c->center_freq == (channel->center_freq + 20))
2278                         channel_after = c;
2279         }
2280
2281         flags = 0;
2282         regd = get_wiphy_regdom(wiphy);
2283         if (regd) {
2284                 const struct ieee80211_reg_rule *reg_rule =
2285                         freq_reg_info_regd(MHZ_TO_KHZ(channel->center_freq),
2286                                            regd, MHZ_TO_KHZ(20));
2287
2288                 if (!IS_ERR(reg_rule))
2289                         flags = reg_rule->flags;
2290         }
2291
2292         /*
2293          * Please note that this assumes target bandwidth is 20 MHz,
2294          * if that ever changes we also need to change the below logic
2295          * to include that as well.
2296          */
2297         if (!is_ht40_allowed(channel_before) ||
2298             flags & NL80211_RRF_NO_HT40MINUS)
2299                 channel->flags |= IEEE80211_CHAN_NO_HT40MINUS;
2300         else
2301                 channel->flags &= ~IEEE80211_CHAN_NO_HT40MINUS;
2302
2303         if (!is_ht40_allowed(channel_after) ||
2304             flags & NL80211_RRF_NO_HT40PLUS)
2305                 channel->flags |= IEEE80211_CHAN_NO_HT40PLUS;
2306         else
2307                 channel->flags &= ~IEEE80211_CHAN_NO_HT40PLUS;
2308 }
2309
2310 static void reg_process_ht_flags_band(struct wiphy *wiphy,
2311                                       struct ieee80211_supported_band *sband)
2312 {
2313         unsigned int i;
2314
2315         if (!sband)
2316                 return;
2317
2318         for (i = 0; i < sband->n_channels; i++)
2319                 reg_process_ht_flags_channel(wiphy, &sband->channels[i]);
2320 }
2321
2322 static void reg_process_ht_flags(struct wiphy *wiphy)
2323 {
2324         enum nl80211_band band;
2325
2326         if (!wiphy)
2327                 return;
2328
2329         for (band = 0; band < NUM_NL80211_BANDS; band++)
2330                 reg_process_ht_flags_band(wiphy, wiphy->bands[band]);
2331 }
2332
2333 static void reg_call_notifier(struct wiphy *wiphy,
2334                               struct regulatory_request *request)
2335 {
2336         if (wiphy->reg_notifier)
2337                 wiphy->reg_notifier(wiphy, request);
2338 }
2339
2340 static bool reg_wdev_chan_valid(struct wiphy *wiphy, struct wireless_dev *wdev)
2341 {
2342         struct cfg80211_chan_def chandef = {};
2343         struct cfg80211_registered_device *rdev = wiphy_to_rdev(wiphy);
2344         enum nl80211_iftype iftype;
2345         bool ret;
2346
2347         wdev_lock(wdev);
2348         iftype = wdev->iftype;
2349
2350         /* make sure the interface is active */
2351         if (!wdev->netdev || !netif_running(wdev->netdev))
2352                 goto wdev_inactive_unlock;
2353
2354         switch (iftype) {
2355         case NL80211_IFTYPE_AP:
2356         case NL80211_IFTYPE_P2P_GO:
2357                 if (!wdev->beacon_interval)
2358                         goto wdev_inactive_unlock;
2359                 chandef = wdev->chandef;
2360                 break;
2361         case NL80211_IFTYPE_ADHOC:
2362                 if (!wdev->ssid_len)
2363                         goto wdev_inactive_unlock;
2364                 chandef = wdev->chandef;
2365                 break;
2366         case NL80211_IFTYPE_STATION:
2367         case NL80211_IFTYPE_P2P_CLIENT:
2368                 if (!wdev->current_bss ||
2369                     !wdev->current_bss->pub.channel)
2370                         goto wdev_inactive_unlock;
2371
2372                 if (!rdev->ops->get_channel ||
2373                     rdev_get_channel(rdev, wdev, &chandef))
2374                         cfg80211_chandef_create(&chandef,
2375                                                 wdev->current_bss->pub.channel,
2376                                                 NL80211_CHAN_NO_HT);
2377                 break;
2378         case NL80211_IFTYPE_MONITOR:
2379         case NL80211_IFTYPE_AP_VLAN:
2380         case NL80211_IFTYPE_P2P_DEVICE:
2381                 /* no enforcement required */
2382                 break;
2383         default:
2384                 /* others not implemented for now */
2385                 WARN_ON(1);
2386                 break;
2387         }
2388
2389         wdev_unlock(wdev);
2390
2391         switch (iftype) {
2392         case NL80211_IFTYPE_AP:
2393         case NL80211_IFTYPE_P2P_GO:
2394         case NL80211_IFTYPE_ADHOC:
2395                 wiphy_lock(wiphy);
2396                 ret = cfg80211_reg_can_beacon_relax(wiphy, &chandef, iftype);
2397                 wiphy_unlock(wiphy);
2398
2399                 return ret;
2400         case NL80211_IFTYPE_STATION:
2401         case NL80211_IFTYPE_P2P_CLIENT:
2402                 return cfg80211_chandef_usable(wiphy, &chandef,
2403                                                IEEE80211_CHAN_DISABLED);
2404         default:
2405                 break;
2406         }
2407
2408         return true;
2409
2410 wdev_inactive_unlock:
2411         wdev_unlock(wdev);
2412         return true;
2413 }
2414
2415 static void reg_leave_invalid_chans(struct wiphy *wiphy)
2416 {
2417         struct wireless_dev *wdev;
2418         struct cfg80211_registered_device *rdev = wiphy_to_rdev(wiphy);
2419
2420         ASSERT_RTNL();
2421
2422         list_for_each_entry(wdev, &rdev->wiphy.wdev_list, list)
2423                 if (!reg_wdev_chan_valid(wiphy, wdev))
2424                         cfg80211_leave(rdev, wdev);
2425 }
2426
2427 static void reg_check_chans_work(struct work_struct *work)
2428 {
2429         struct cfg80211_registered_device *rdev;
2430
2431         pr_debug("Verifying active interfaces after reg change\n");
2432         rtnl_lock();
2433
2434         list_for_each_entry(rdev, &cfg80211_rdev_list, list)
2435                 if (!(rdev->wiphy.regulatory_flags &
2436                       REGULATORY_IGNORE_STALE_KICKOFF))
2437                         reg_leave_invalid_chans(&rdev->wiphy);
2438
2439         rtnl_unlock();
2440 }
2441
2442 static void reg_check_channels(void)
2443 {
2444         /*
2445          * Give usermode a chance to do something nicer (move to another
2446          * channel, orderly disconnection), before forcing a disconnection.
2447          */
2448         mod_delayed_work(system_power_efficient_wq,
2449                          &reg_check_chans,
2450                          msecs_to_jiffies(REG_ENFORCE_GRACE_MS));
2451 }
2452
2453 static void wiphy_update_regulatory(struct wiphy *wiphy,
2454                                     enum nl80211_reg_initiator initiator)
2455 {
2456         enum nl80211_band band;
2457         struct regulatory_request *lr = get_last_request();
2458
2459         if (ignore_reg_update(wiphy, initiator)) {
2460                 /*
2461                  * Regulatory updates set by CORE are ignored for custom
2462                  * regulatory cards. Let us notify the changes to the driver,
2463                  * as some drivers used this to restore its orig_* reg domain.
2464                  */
2465                 if (initiator == NL80211_REGDOM_SET_BY_CORE &&
2466                     wiphy->regulatory_flags & REGULATORY_CUSTOM_REG &&
2467                     !(wiphy->regulatory_flags &
2468                       REGULATORY_WIPHY_SELF_MANAGED))
2469                         reg_call_notifier(wiphy, lr);
2470                 return;
2471         }
2472
2473         lr->dfs_region = get_cfg80211_regdom()->dfs_region;
2474
2475         for (band = 0; band < NUM_NL80211_BANDS; band++)
2476                 handle_band(wiphy, initiator, wiphy->bands[band]);
2477
2478         reg_process_beacons(wiphy);
2479         reg_process_ht_flags(wiphy);
2480         reg_call_notifier(wiphy, lr);
2481 }
2482
2483 static void update_all_wiphy_regulatory(enum nl80211_reg_initiator initiator)
2484 {
2485         struct cfg80211_registered_device *rdev;
2486         struct wiphy *wiphy;
2487
2488         ASSERT_RTNL();
2489
2490         list_for_each_entry(rdev, &cfg80211_rdev_list, list) {
2491                 wiphy = &rdev->wiphy;
2492                 wiphy_update_regulatory(wiphy, initiator);
2493         }
2494
2495         reg_check_channels();
2496 }
2497
2498 static void handle_channel_custom(struct wiphy *wiphy,
2499                                   struct ieee80211_channel *chan,
2500                                   const struct ieee80211_regdomain *regd,
2501                                   u32 min_bw)
2502 {
2503         u32 bw_flags = 0;
2504         const struct ieee80211_reg_rule *reg_rule = NULL;
2505         const struct ieee80211_power_rule *power_rule = NULL;
2506         u32 bw, center_freq_khz;
2507
2508         center_freq_khz = ieee80211_channel_to_khz(chan);
2509         for (bw = MHZ_TO_KHZ(20); bw >= min_bw; bw = bw / 2) {
2510                 reg_rule = freq_reg_info_regd(center_freq_khz, regd, bw);
2511                 if (!IS_ERR(reg_rule))
2512                         break;
2513         }
2514
2515         if (IS_ERR_OR_NULL(reg_rule)) {
2516                 pr_debug("Disabling freq %d.%03d MHz as custom regd has no rule that fits it\n",
2517                          chan->center_freq, chan->freq_offset);
2518                 if (wiphy->regulatory_flags & REGULATORY_WIPHY_SELF_MANAGED) {
2519                         chan->flags |= IEEE80211_CHAN_DISABLED;
2520                 } else {
2521                         chan->orig_flags |= IEEE80211_CHAN_DISABLED;
2522                         chan->flags = chan->orig_flags;
2523                 }
2524                 return;
2525         }
2526
2527         power_rule = &reg_rule->power_rule;
2528         bw_flags = reg_rule_to_chan_bw_flags(regd, reg_rule, chan);
2529
2530         chan->dfs_state_entered = jiffies;
2531         chan->dfs_state = NL80211_DFS_USABLE;
2532
2533         chan->beacon_found = false;
2534
2535         if (wiphy->regulatory_flags & REGULATORY_WIPHY_SELF_MANAGED)
2536                 chan->flags = chan->orig_flags | bw_flags |
2537                               map_regdom_flags(reg_rule->flags);
2538         else
2539                 chan->flags |= map_regdom_flags(reg_rule->flags) | bw_flags;
2540
2541         chan->max_antenna_gain = (int) MBI_TO_DBI(power_rule->max_antenna_gain);
2542         chan->max_reg_power = chan->max_power =
2543                 (int) MBM_TO_DBM(power_rule->max_eirp);
2544
2545         if (chan->flags & IEEE80211_CHAN_RADAR) {
2546                 if (reg_rule->dfs_cac_ms)
2547                         chan->dfs_cac_ms = reg_rule->dfs_cac_ms;
2548                 else
2549                         chan->dfs_cac_ms = IEEE80211_DFS_MIN_CAC_TIME_MS;
2550         }
2551
2552         chan->max_power = chan->max_reg_power;
2553 }
2554
2555 static void handle_band_custom(struct wiphy *wiphy,
2556                                struct ieee80211_supported_band *sband,
2557                                const struct ieee80211_regdomain *regd)
2558 {
2559         unsigned int i;
2560
2561         if (!sband)
2562                 return;
2563
2564         /*
2565          * We currently assume that you always want at least 20 MHz,
2566          * otherwise channel 12 might get enabled if this rule is
2567          * compatible to US, which permits 2402 - 2472 MHz.
2568          */
2569         for (i = 0; i < sband->n_channels; i++)
2570                 handle_channel_custom(wiphy, &sband->channels[i], regd,
2571                                       MHZ_TO_KHZ(20));
2572 }
2573
2574 /* Used by drivers prior to wiphy registration */
2575 void wiphy_apply_custom_regulatory(struct wiphy *wiphy,
2576                                    const struct ieee80211_regdomain *regd)
2577 {
2578         const struct ieee80211_regdomain *new_regd, *tmp;
2579         enum nl80211_band band;
2580         unsigned int bands_set = 0;
2581
2582         WARN(!(wiphy->regulatory_flags & REGULATORY_CUSTOM_REG),
2583              "wiphy should have REGULATORY_CUSTOM_REG\n");
2584         wiphy->regulatory_flags |= REGULATORY_CUSTOM_REG;
2585
2586         for (band = 0; band < NUM_NL80211_BANDS; band++) {
2587                 if (!wiphy->bands[band])
2588                         continue;
2589                 handle_band_custom(wiphy, wiphy->bands[band], regd);
2590                 bands_set++;
2591         }
2592
2593         /*
2594          * no point in calling this if it won't have any effect
2595          * on your device's supported bands.
2596          */
2597         WARN_ON(!bands_set);
2598         new_regd = reg_copy_regd(regd);
2599         if (IS_ERR(new_regd))
2600                 return;
2601
2602         rtnl_lock();
2603         wiphy_lock(wiphy);
2604
2605         tmp = get_wiphy_regdom(wiphy);
2606         rcu_assign_pointer(wiphy->regd, new_regd);
2607         rcu_free_regdom(tmp);
2608
2609         wiphy_unlock(wiphy);
2610         rtnl_unlock();
2611 }
2612 EXPORT_SYMBOL(wiphy_apply_custom_regulatory);
2613
2614 static void reg_set_request_processed(void)
2615 {
2616         bool need_more_processing = false;
2617         struct regulatory_request *lr = get_last_request();
2618
2619         lr->processed = true;
2620
2621         spin_lock(&reg_requests_lock);
2622         if (!list_empty(&reg_requests_list))
2623                 need_more_processing = true;
2624         spin_unlock(&reg_requests_lock);
2625
2626         cancel_crda_timeout();
2627
2628         if (need_more_processing)
2629                 schedule_work(&reg_work);
2630 }
2631
2632 /**
2633  * reg_process_hint_core - process core regulatory requests
2634  * @core_request: a pending core regulatory request
2635  *
2636  * The wireless subsystem can use this function to process
2637  * a regulatory request issued by the regulatory core.
2638  */
2639 static enum reg_request_treatment
2640 reg_process_hint_core(struct regulatory_request *core_request)
2641 {
2642         if (reg_query_database(core_request)) {
2643                 core_request->intersect = false;
2644                 core_request->processed = false;
2645                 reg_update_last_request(core_request);
2646                 return REG_REQ_OK;
2647         }
2648
2649         return REG_REQ_IGNORE;
2650 }
2651
2652 static enum reg_request_treatment
2653 __reg_process_hint_user(struct regulatory_request *user_request)
2654 {
2655         struct regulatory_request *lr = get_last_request();
2656
2657         if (reg_request_cell_base(user_request))
2658                 return reg_ignore_cell_hint(user_request);
2659
2660         if (reg_request_cell_base(lr))
2661                 return REG_REQ_IGNORE;
2662
2663         if (lr->initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE)
2664                 return REG_REQ_INTERSECT;
2665         /*
2666          * If the user knows better the user should set the regdom
2667          * to their country before the IE is picked up
2668          */
2669         if (lr->initiator == NL80211_REGDOM_SET_BY_USER &&
2670             lr->intersect)
2671                 return REG_REQ_IGNORE;
2672         /*
2673          * Process user requests only after previous user/driver/core
2674          * requests have been processed
2675          */
2676         if ((lr->initiator == NL80211_REGDOM_SET_BY_CORE ||
2677              lr->initiator == NL80211_REGDOM_SET_BY_DRIVER ||
2678              lr->initiator == NL80211_REGDOM_SET_BY_USER) &&
2679             regdom_changes(lr->alpha2))
2680                 return REG_REQ_IGNORE;
2681
2682         if (!regdom_changes(user_request->alpha2))
2683                 return REG_REQ_ALREADY_SET;
2684
2685         return REG_REQ_OK;
2686 }
2687
2688 /**
2689  * reg_process_hint_user - process user regulatory requests
2690  * @user_request: a pending user regulatory request
2691  *
2692  * The wireless subsystem can use this function to process
2693  * a regulatory request initiated by userspace.
2694  */
2695 static enum reg_request_treatment
2696 reg_process_hint_user(struct regulatory_request *user_request)
2697 {
2698         enum reg_request_treatment treatment;
2699
2700         treatment = __reg_process_hint_user(user_request);
2701         if (treatment == REG_REQ_IGNORE ||
2702             treatment == REG_REQ_ALREADY_SET)
2703                 return REG_REQ_IGNORE;
2704
2705         user_request->intersect = treatment == REG_REQ_INTERSECT;
2706         user_request->processed = false;
2707
2708         if (reg_query_database(user_request)) {
2709                 reg_update_last_request(user_request);
2710                 user_alpha2[0] = user_request->alpha2[0];
2711                 user_alpha2[1] = user_request->alpha2[1];
2712                 return REG_REQ_OK;
2713         }
2714
2715         return REG_REQ_IGNORE;
2716 }
2717
2718 static enum reg_request_treatment
2719 __reg_process_hint_driver(struct regulatory_request *driver_request)
2720 {
2721         struct regulatory_request *lr = get_last_request();
2722
2723         if (lr->initiator == NL80211_REGDOM_SET_BY_CORE) {
2724                 if (regdom_changes(driver_request->alpha2))
2725                         return REG_REQ_OK;
2726                 return REG_REQ_ALREADY_SET;
2727         }
2728
2729         /*
2730          * This would happen if you unplug and plug your card
2731          * back in or if you add a new device for which the previously
2732          * loaded card also agrees on the regulatory domain.
2733          */
2734         if (lr->initiator == NL80211_REGDOM_SET_BY_DRIVER &&
2735             !regdom_changes(driver_request->alpha2))
2736                 return REG_REQ_ALREADY_SET;
2737
2738         return REG_REQ_INTERSECT;
2739 }
2740
2741 /**
2742  * reg_process_hint_driver - process driver regulatory requests
2743  * @wiphy: the wireless device for the regulatory request
2744  * @driver_request: a pending driver regulatory request
2745  *
2746  * The wireless subsystem can use this function to process
2747  * a regulatory request issued by an 802.11 driver.
2748  *
2749  * Returns one of the different reg request treatment values.
2750  */
2751 static enum reg_request_treatment
2752 reg_process_hint_driver(struct wiphy *wiphy,
2753                         struct regulatory_request *driver_request)
2754 {
2755         const struct ieee80211_regdomain *regd, *tmp;
2756         enum reg_request_treatment treatment;
2757
2758         treatment = __reg_process_hint_driver(driver_request);
2759
2760         switch (treatment) {
2761         case REG_REQ_OK:
2762                 break;
2763         case REG_REQ_IGNORE:
2764                 return REG_REQ_IGNORE;
2765         case REG_REQ_INTERSECT:
2766         case REG_REQ_ALREADY_SET:
2767                 regd = reg_copy_regd(get_cfg80211_regdom());
2768                 if (IS_ERR(regd))
2769                         return REG_REQ_IGNORE;
2770
2771                 tmp = get_wiphy_regdom(wiphy);
2772                 ASSERT_RTNL();
2773                 wiphy_lock(wiphy);
2774                 rcu_assign_pointer(wiphy->regd, regd);
2775                 wiphy_unlock(wiphy);
2776                 rcu_free_regdom(tmp);
2777         }
2778
2779
2780         driver_request->intersect = treatment == REG_REQ_INTERSECT;
2781         driver_request->processed = false;
2782
2783         /*
2784          * Since CRDA will not be called in this case as we already
2785          * have applied the requested regulatory domain before we just
2786          * inform userspace we have processed the request
2787          */
2788         if (treatment == REG_REQ_ALREADY_SET) {
2789                 nl80211_send_reg_change_event(driver_request);
2790                 reg_update_last_request(driver_request);
2791                 reg_set_request_processed();
2792                 return REG_REQ_ALREADY_SET;
2793         }
2794
2795         if (reg_query_database(driver_request)) {
2796                 reg_update_last_request(driver_request);
2797                 return REG_REQ_OK;
2798         }
2799
2800         return REG_REQ_IGNORE;
2801 }
2802
2803 static enum reg_request_treatment
2804 __reg_process_hint_country_ie(struct wiphy *wiphy,
2805                               struct regulatory_request *country_ie_request)
2806 {
2807         struct wiphy *last_wiphy = NULL;
2808         struct regulatory_request *lr = get_last_request();
2809
2810         if (reg_request_cell_base(lr)) {
2811                 /* Trust a Cell base station over the AP's country IE */
2812                 if (regdom_changes(country_ie_request->alpha2))
2813                         return REG_REQ_IGNORE;
2814                 return REG_REQ_ALREADY_SET;
2815         } else {
2816                 if (wiphy->regulatory_flags & REGULATORY_COUNTRY_IE_IGNORE)
2817                         return REG_REQ_IGNORE;
2818         }
2819
2820         if (unlikely(!is_an_alpha2(country_ie_request->alpha2)))
2821                 return -EINVAL;
2822
2823         if (lr->initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE)
2824                 return REG_REQ_OK;
2825
2826         last_wiphy = wiphy_idx_to_wiphy(lr->wiphy_idx);
2827
2828         if (last_wiphy != wiphy) {
2829                 /*
2830                  * Two cards with two APs claiming different
2831                  * Country IE alpha2s. We could
2832                  * intersect them, but that seems unlikely
2833                  * to be correct. Reject second one for now.
2834                  */
2835                 if (regdom_changes(country_ie_request->alpha2))
2836                         return REG_REQ_IGNORE;
2837                 return REG_REQ_ALREADY_SET;
2838         }
2839
2840         if (regdom_changes(country_ie_request->alpha2))
2841                 return REG_REQ_OK;
2842         return REG_REQ_ALREADY_SET;
2843 }
2844
2845 /**
2846  * reg_process_hint_country_ie - process regulatory requests from country IEs
2847  * @wiphy: the wireless device for the regulatory request
2848  * @country_ie_request: a regulatory request from a country IE
2849  *
2850  * The wireless subsystem can use this function to process
2851  * a regulatory request issued by a country Information Element.
2852  *
2853  * Returns one of the different reg request treatment values.
2854  */
2855 static enum reg_request_treatment
2856 reg_process_hint_country_ie(struct wiphy *wiphy,
2857                             struct regulatory_request *country_ie_request)
2858 {
2859         enum reg_request_treatment treatment;
2860
2861         treatment = __reg_process_hint_country_ie(wiphy, country_ie_request);
2862
2863         switch (treatment) {
2864         case REG_REQ_OK:
2865                 break;
2866         case REG_REQ_IGNORE:
2867                 return REG_REQ_IGNORE;
2868         case REG_REQ_ALREADY_SET:
2869                 reg_free_request(country_ie_request);
2870                 return REG_REQ_ALREADY_SET;
2871         case REG_REQ_INTERSECT:
2872                 /*
2873                  * This doesn't happen yet, not sure we
2874                  * ever want to support it for this case.
2875                  */
2876                 WARN_ONCE(1, "Unexpected intersection for country elements");
2877                 return REG_REQ_IGNORE;
2878         }
2879
2880         country_ie_request->intersect = false;
2881         country_ie_request->processed = false;
2882
2883         if (reg_query_database(country_ie_request)) {
2884                 reg_update_last_request(country_ie_request);
2885                 return REG_REQ_OK;
2886         }
2887
2888         return REG_REQ_IGNORE;
2889 }
2890
2891 bool reg_dfs_domain_same(struct wiphy *wiphy1, struct wiphy *wiphy2)
2892 {
2893         const struct ieee80211_regdomain *wiphy1_regd = NULL;
2894         const struct ieee80211_regdomain *wiphy2_regd = NULL;
2895         const struct ieee80211_regdomain *cfg80211_regd = NULL;
2896         bool dfs_domain_same;
2897
2898         rcu_read_lock();
2899
2900         cfg80211_regd = rcu_dereference(cfg80211_regdomain);
2901         wiphy1_regd = rcu_dereference(wiphy1->regd);
2902         if (!wiphy1_regd)
2903                 wiphy1_regd = cfg80211_regd;
2904
2905         wiphy2_regd = rcu_dereference(wiphy2->regd);
2906         if (!wiphy2_regd)
2907                 wiphy2_regd = cfg80211_regd;
2908
2909         dfs_domain_same = wiphy1_regd->dfs_region == wiphy2_regd->dfs_region;
2910
2911         rcu_read_unlock();
2912
2913         return dfs_domain_same;
2914 }
2915
2916 static void reg_copy_dfs_chan_state(struct ieee80211_channel *dst_chan,
2917                                     struct ieee80211_channel *src_chan)
2918 {
2919         if (!(dst_chan->flags & IEEE80211_CHAN_RADAR) ||
2920             !(src_chan->flags & IEEE80211_CHAN_RADAR))
2921                 return;
2922
2923         if (dst_chan->flags & IEEE80211_CHAN_DISABLED ||
2924             src_chan->flags & IEEE80211_CHAN_DISABLED)
2925                 return;
2926
2927         if (src_chan->center_freq == dst_chan->center_freq &&
2928             dst_chan->dfs_state == NL80211_DFS_USABLE) {
2929                 dst_chan->dfs_state = src_chan->dfs_state;
2930                 dst_chan->dfs_state_entered = src_chan->dfs_state_entered;
2931         }
2932 }
2933
2934 static void wiphy_share_dfs_chan_state(struct wiphy *dst_wiphy,
2935                                        struct wiphy *src_wiphy)
2936 {
2937         struct ieee80211_supported_band *src_sband, *dst_sband;
2938         struct ieee80211_channel *src_chan, *dst_chan;
2939         int i, j, band;
2940
2941         if (!reg_dfs_domain_same(dst_wiphy, src_wiphy))
2942                 return;
2943
2944         for (band = 0; band < NUM_NL80211_BANDS; band++) {
2945                 dst_sband = dst_wiphy->bands[band];
2946                 src_sband = src_wiphy->bands[band];
2947                 if (!dst_sband || !src_sband)
2948                         continue;
2949
2950                 for (i = 0; i < dst_sband->n_channels; i++) {
2951                         dst_chan = &dst_sband->channels[i];
2952                         for (j = 0; j < src_sband->n_channels; j++) {
2953                                 src_chan = &src_sband->channels[j];
2954                                 reg_copy_dfs_chan_state(dst_chan, src_chan);
2955                         }
2956                 }
2957         }
2958 }
2959
2960 static void wiphy_all_share_dfs_chan_state(struct wiphy *wiphy)
2961 {
2962         struct cfg80211_registered_device *rdev;
2963
2964         ASSERT_RTNL();
2965
2966         list_for_each_entry(rdev, &cfg80211_rdev_list, list) {
2967                 if (wiphy == &rdev->wiphy)
2968                         continue;
2969                 wiphy_share_dfs_chan_state(wiphy, &rdev->wiphy);
2970         }
2971 }
2972
2973 /* This processes *all* regulatory hints */
2974 static void reg_process_hint(struct regulatory_request *reg_request)
2975 {
2976         struct wiphy *wiphy = NULL;
2977         enum reg_request_treatment treatment;
2978         enum nl80211_reg_initiator initiator = reg_request->initiator;
2979
2980         if (reg_request->wiphy_idx != WIPHY_IDX_INVALID)
2981                 wiphy = wiphy_idx_to_wiphy(reg_request->wiphy_idx);
2982
2983         switch (initiator) {
2984         case NL80211_REGDOM_SET_BY_CORE:
2985                 treatment = reg_process_hint_core(reg_request);
2986                 break;
2987         case NL80211_REGDOM_SET_BY_USER:
2988                 treatment = reg_process_hint_user(reg_request);
2989                 break;
2990         case NL80211_REGDOM_SET_BY_DRIVER:
2991                 if (!wiphy)
2992                         goto out_free;
2993                 treatment = reg_process_hint_driver(wiphy, reg_request);
2994                 break;
2995         case NL80211_REGDOM_SET_BY_COUNTRY_IE:
2996                 if (!wiphy)
2997                         goto out_free;
2998                 treatment = reg_process_hint_country_ie(wiphy, reg_request);
2999                 break;
3000         default:
3001                 WARN(1, "invalid initiator %d\n", initiator);
3002                 goto out_free;
3003         }
3004
3005         if (treatment == REG_REQ_IGNORE)
3006                 goto out_free;
3007
3008         WARN(treatment != REG_REQ_OK && treatment != REG_REQ_ALREADY_SET,
3009              "unexpected treatment value %d\n", treatment);
3010
3011         /* This is required so that the orig_* parameters are saved.
3012          * NOTE: treatment must be set for any case that reaches here!
3013          */
3014         if (treatment == REG_REQ_ALREADY_SET && wiphy &&
3015             wiphy->regulatory_flags & REGULATORY_STRICT_REG) {
3016                 wiphy_update_regulatory(wiphy, initiator);
3017                 wiphy_all_share_dfs_chan_state(wiphy);
3018                 reg_check_channels();
3019         }
3020
3021         return;
3022
3023 out_free:
3024         reg_free_request(reg_request);
3025 }
3026
3027 static void notify_self_managed_wiphys(struct regulatory_request *request)
3028 {
3029         struct cfg80211_registered_device *rdev;
3030         struct wiphy *wiphy;
3031
3032         list_for_each_entry(rdev, &cfg80211_rdev_list, list) {
3033                 wiphy = &rdev->wiphy;
3034                 if (wiphy->regulatory_flags & REGULATORY_WIPHY_SELF_MANAGED &&
3035                     request->initiator == NL80211_REGDOM_SET_BY_USER)
3036                         reg_call_notifier(wiphy, request);
3037         }
3038 }
3039
3040 /*
3041  * Processes regulatory hints, this is all the NL80211_REGDOM_SET_BY_*
3042  * Regulatory hints come on a first come first serve basis and we
3043  * must process each one atomically.
3044  */
3045 static void reg_process_pending_hints(void)
3046 {
3047         struct regulatory_request *reg_request, *lr;
3048
3049         lr = get_last_request();
3050
3051         /* When last_request->processed becomes true this will be rescheduled */
3052         if (lr && !lr->processed) {
3053                 pr_debug("Pending regulatory request, waiting for it to be processed...\n");
3054                 return;
3055         }
3056
3057         spin_lock(&reg_requests_lock);
3058
3059         if (list_empty(&reg_requests_list)) {
3060                 spin_unlock(&reg_requests_lock);
3061                 return;
3062         }
3063
3064         reg_request = list_first_entry(&reg_requests_list,
3065                                        struct regulatory_request,
3066                                        list);
3067         list_del_init(&reg_request->list);
3068
3069         spin_unlock(&reg_requests_lock);
3070
3071         notify_self_managed_wiphys(reg_request);
3072
3073         reg_process_hint(reg_request);
3074
3075         lr = get_last_request();
3076
3077         spin_lock(&reg_requests_lock);
3078         if (!list_empty(&reg_requests_list) && lr && lr->processed)
3079                 schedule_work(&reg_work);
3080         spin_unlock(&reg_requests_lock);
3081 }
3082
3083 /* Processes beacon hints -- this has nothing to do with country IEs */
3084 static void reg_process_pending_beacon_hints(void)
3085 {
3086         struct cfg80211_registered_device *rdev;
3087         struct reg_beacon *pending_beacon, *tmp;
3088
3089         /* This goes through the _pending_ beacon list */
3090         spin_lock_bh(&reg_pending_beacons_lock);
3091
3092         list_for_each_entry_safe(pending_beacon, tmp,
3093                                  &reg_pending_beacons, list) {
3094                 list_del_init(&pending_beacon->list);
3095
3096                 /* Applies the beacon hint to current wiphys */
3097                 list_for_each_entry(rdev, &cfg80211_rdev_list, list)
3098                         wiphy_update_new_beacon(&rdev->wiphy, pending_beacon);
3099
3100                 /* Remembers the beacon hint for new wiphys or reg changes */
3101                 list_add_tail(&pending_beacon->list, &reg_beacon_list);
3102         }
3103
3104         spin_unlock_bh(&reg_pending_beacons_lock);
3105 }
3106
3107 static void reg_process_self_managed_hint(struct wiphy *wiphy)
3108 {
3109         struct cfg80211_registered_device *rdev = wiphy_to_rdev(wiphy);
3110         const struct ieee80211_regdomain *tmp;
3111         const struct ieee80211_regdomain *regd;
3112         enum nl80211_band band;
3113         struct regulatory_request request = {};
3114
3115         ASSERT_RTNL();
3116         lockdep_assert_wiphy(wiphy);
3117
3118         spin_lock(&reg_requests_lock);
3119         regd = rdev->requested_regd;
3120         rdev->requested_regd = NULL;
3121         spin_unlock(&reg_requests_lock);
3122
3123         if (!regd)
3124                 return;
3125
3126         tmp = get_wiphy_regdom(wiphy);
3127         rcu_assign_pointer(wiphy->regd, regd);
3128         rcu_free_regdom(tmp);
3129
3130         for (band = 0; band < NUM_NL80211_BANDS; band++)
3131                 handle_band_custom(wiphy, wiphy->bands[band], regd);
3132
3133         reg_process_ht_flags(wiphy);
3134
3135         request.wiphy_idx = get_wiphy_idx(wiphy);
3136         request.alpha2[0] = regd->alpha2[0];
3137         request.alpha2[1] = regd->alpha2[1];
3138         request.initiator = NL80211_REGDOM_SET_BY_DRIVER;
3139
3140         nl80211_send_wiphy_reg_change_event(&request);
3141 }
3142
3143 static void reg_process_self_managed_hints(void)
3144 {
3145         struct cfg80211_registered_device *rdev;
3146
3147         ASSERT_RTNL();
3148
3149         list_for_each_entry(rdev, &cfg80211_rdev_list, list) {
3150                 wiphy_lock(&rdev->wiphy);
3151                 reg_process_self_managed_hint(&rdev->wiphy);
3152                 wiphy_unlock(&rdev->wiphy);
3153         }
3154
3155         reg_check_channels();
3156 }
3157
3158 static void reg_todo(struct work_struct *work)
3159 {
3160         rtnl_lock();
3161         reg_process_pending_hints();
3162         reg_process_pending_beacon_hints();
3163         reg_process_self_managed_hints();
3164         rtnl_unlock();
3165 }
3166
3167 static void queue_regulatory_request(struct regulatory_request *request)
3168 {
3169         request->alpha2[0] = toupper(request->alpha2[0]);
3170         request->alpha2[1] = toupper(request->alpha2[1]);
3171
3172         spin_lock(&reg_requests_lock);
3173         list_add_tail(&request->list, &reg_requests_list);
3174         spin_unlock(&reg_requests_lock);
3175
3176         schedule_work(&reg_work);
3177 }
3178
3179 /*
3180  * Core regulatory hint -- happens during cfg80211_init()
3181  * and when we restore regulatory settings.
3182  */
3183 static int regulatory_hint_core(const char *alpha2)
3184 {
3185         struct regulatory_request *request;
3186
3187         request = kzalloc(sizeof(struct regulatory_request), GFP_KERNEL);
3188         if (!request)
3189                 return -ENOMEM;
3190
3191         request->alpha2[0] = alpha2[0];
3192         request->alpha2[1] = alpha2[1];
3193         request->initiator = NL80211_REGDOM_SET_BY_CORE;
3194         request->wiphy_idx = WIPHY_IDX_INVALID;
3195
3196         queue_regulatory_request(request);
3197
3198         return 0;
3199 }
3200
3201 /* User hints */
3202 int regulatory_hint_user(const char *alpha2,
3203                          enum nl80211_user_reg_hint_type user_reg_hint_type)
3204 {
3205         struct regulatory_request *request;
3206
3207         if (WARN_ON(!alpha2))
3208                 return -EINVAL;
3209
3210         if (!is_world_regdom(alpha2) && !is_an_alpha2(alpha2))
3211                 return -EINVAL;
3212
3213         request = kzalloc(sizeof(struct regulatory_request), GFP_KERNEL);
3214         if (!request)
3215                 return -ENOMEM;
3216
3217         request->wiphy_idx = WIPHY_IDX_INVALID;
3218         request->alpha2[0] = alpha2[0];
3219         request->alpha2[1] = alpha2[1];
3220         request->initiator = NL80211_REGDOM_SET_BY_USER;
3221         request->user_reg_hint_type = user_reg_hint_type;
3222
3223         /* Allow calling CRDA again */
3224         reset_crda_timeouts();
3225
3226         queue_regulatory_request(request);
3227
3228         return 0;
3229 }
3230
3231 int regulatory_hint_indoor(bool is_indoor, u32 portid)
3232 {
3233         spin_lock(&reg_indoor_lock);
3234
3235         /* It is possible that more than one user space process is trying to
3236          * configure the indoor setting. To handle such cases, clear the indoor
3237          * setting in case that some process does not think that the device
3238          * is operating in an indoor environment. In addition, if a user space
3239          * process indicates that it is controlling the indoor setting, save its
3240          * portid, i.e., make it the owner.
3241          */
3242         reg_is_indoor = is_indoor;
3243         if (reg_is_indoor) {
3244                 if (!reg_is_indoor_portid)
3245                         reg_is_indoor_portid = portid;
3246         } else {
3247                 reg_is_indoor_portid = 0;
3248         }
3249
3250         spin_unlock(&reg_indoor_lock);
3251
3252         if (!is_indoor)
3253                 reg_check_channels();
3254
3255         return 0;
3256 }
3257
3258 void regulatory_netlink_notify(u32 portid)
3259 {
3260         spin_lock(&reg_indoor_lock);
3261
3262         if (reg_is_indoor_portid != portid) {
3263                 spin_unlock(&reg_indoor_lock);
3264                 return;
3265         }
3266
3267         reg_is_indoor = false;
3268         reg_is_indoor_portid = 0;
3269
3270         spin_unlock(&reg_indoor_lock);
3271
3272         reg_check_channels();
3273 }
3274
3275 /* Driver hints */
3276 int regulatory_hint(struct wiphy *wiphy, const char *alpha2)
3277 {
3278         struct regulatory_request *request;
3279
3280         if (WARN_ON(!alpha2 || !wiphy))
3281                 return -EINVAL;
3282
3283         wiphy->regulatory_flags &= ~REGULATORY_CUSTOM_REG;
3284
3285         request = kzalloc(sizeof(struct regulatory_request), GFP_KERNEL);
3286         if (!request)
3287                 return -ENOMEM;
3288
3289         request->wiphy_idx = get_wiphy_idx(wiphy);
3290
3291         request->alpha2[0] = alpha2[0];
3292         request->alpha2[1] = alpha2[1];
3293         request->initiator = NL80211_REGDOM_SET_BY_DRIVER;
3294
3295         /* Allow calling CRDA again */
3296         reset_crda_timeouts();
3297
3298         queue_regulatory_request(request);
3299
3300         return 0;
3301 }
3302 EXPORT_SYMBOL(regulatory_hint);
3303
3304 void regulatory_hint_country_ie(struct wiphy *wiphy, enum nl80211_band band,
3305                                 const u8 *country_ie, u8 country_ie_len)
3306 {
3307         char alpha2[2];
3308         enum environment_cap env = ENVIRON_ANY;
3309         struct regulatory_request *request = NULL, *lr;
3310
3311         /* IE len must be evenly divisible by 2 */
3312         if (country_ie_len & 0x01)
3313                 return;
3314
3315         if (country_ie_len < IEEE80211_COUNTRY_IE_MIN_LEN)
3316                 return;
3317
3318         request = kzalloc(sizeof(*request), GFP_KERNEL);
3319         if (!request)
3320                 return;
3321
3322         alpha2[0] = country_ie[0];
3323         alpha2[1] = country_ie[1];
3324
3325         if (country_ie[2] == 'I')
3326                 env = ENVIRON_INDOOR;
3327         else if (country_ie[2] == 'O')
3328                 env = ENVIRON_OUTDOOR;
3329
3330         rcu_read_lock();
3331         lr = get_last_request();
3332
3333         if (unlikely(!lr))
3334                 goto out;
3335
3336         /*
3337          * We will run this only upon a successful connection on cfg80211.
3338          * We leave conflict resolution to the workqueue, where can hold
3339          * the RTNL.
3340          */
3341         if (lr->initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE &&
3342             lr->wiphy_idx != WIPHY_IDX_INVALID)
3343                 goto out;
3344
3345         request->wiphy_idx = get_wiphy_idx(wiphy);
3346         request->alpha2[0] = alpha2[0];
3347         request->alpha2[1] = alpha2[1];
3348         request->initiator = NL80211_REGDOM_SET_BY_COUNTRY_IE;
3349         request->country_ie_env = env;
3350
3351         /* Allow calling CRDA again */
3352         reset_crda_timeouts();
3353
3354         queue_regulatory_request(request);
3355         request = NULL;
3356 out:
3357         kfree(request);
3358         rcu_read_unlock();
3359 }
3360
3361 static void restore_alpha2(char *alpha2, bool reset_user)
3362 {
3363         /* indicates there is no alpha2 to consider for restoration */
3364         alpha2[0] = '9';
3365         alpha2[1] = '7';
3366
3367         /* The user setting has precedence over the module parameter */
3368         if (is_user_regdom_saved()) {
3369                 /* Unless we're asked to ignore it and reset it */
3370                 if (reset_user) {
3371                         pr_debug("Restoring regulatory settings including user preference\n");
3372                         user_alpha2[0] = '9';
3373                         user_alpha2[1] = '7';
3374
3375                         /*
3376                          * If we're ignoring user settings, we still need to
3377                          * check the module parameter to ensure we put things
3378                          * back as they were for a full restore.
3379                          */
3380                         if (!is_world_regdom(ieee80211_regdom)) {
3381                                 pr_debug("Keeping preference on module parameter ieee80211_regdom: %c%c\n",
3382                                          ieee80211_regdom[0], ieee80211_regdom[1]);
3383                                 alpha2[0] = ieee80211_regdom[0];
3384                                 alpha2[1] = ieee80211_regdom[1];
3385                         }
3386                 } else {
3387                         pr_debug("Restoring regulatory settings while preserving user preference for: %c%c\n",
3388                                  user_alpha2[0], user_alpha2[1]);
3389                         alpha2[0] = user_alpha2[0];
3390                         alpha2[1] = user_alpha2[1];
3391                 }
3392         } else if (!is_world_regdom(ieee80211_regdom)) {
3393                 pr_debug("Keeping preference on module parameter ieee80211_regdom: %c%c\n",
3394                          ieee80211_regdom[0], ieee80211_regdom[1]);
3395                 alpha2[0] = ieee80211_regdom[0];
3396                 alpha2[1] = ieee80211_regdom[1];
3397         } else
3398                 pr_debug("Restoring regulatory settings\n");
3399 }
3400
3401 static void restore_custom_reg_settings(struct wiphy *wiphy)
3402 {
3403         struct ieee80211_supported_band *sband;
3404         enum nl80211_band band;
3405         struct ieee80211_channel *chan;
3406         int i;
3407
3408         for (band = 0; band < NUM_NL80211_BANDS; band++) {
3409                 sband = wiphy->bands[band];
3410                 if (!sband)
3411                         continue;
3412                 for (i = 0; i < sband->n_channels; i++) {
3413                         chan = &sband->channels[i];
3414                         chan->flags = chan->orig_flags;
3415                         chan->max_antenna_gain = chan->orig_mag;
3416                         chan->max_power = chan->orig_mpwr;
3417                         chan->beacon_found = false;
3418                 }
3419         }
3420 }
3421
3422 /*
3423  * Restoring regulatory settings involves ignoring any
3424  * possibly stale country IE information and user regulatory
3425  * settings if so desired, this includes any beacon hints
3426  * learned as we could have traveled outside to another country
3427  * after disconnection. To restore regulatory settings we do
3428  * exactly what we did at bootup:
3429  *
3430  *   - send a core regulatory hint
3431  *   - send a user regulatory hint if applicable
3432  *
3433  * Device drivers that send a regulatory hint for a specific country
3434  * keep their own regulatory domain on wiphy->regd so that does
3435  * not need to be remembered.
3436  */
3437 static void restore_regulatory_settings(bool reset_user, bool cached)
3438 {
3439         char alpha2[2];
3440         char world_alpha2[2];
3441         struct reg_beacon *reg_beacon, *btmp;
3442         LIST_HEAD(tmp_reg_req_list);
3443         struct cfg80211_registered_device *rdev;
3444
3445         ASSERT_RTNL();
3446
3447         /*
3448          * Clear the indoor setting in case that it is not controlled by user
3449          * space, as otherwise there is no guarantee that the device is still
3450          * operating in an indoor environment.
3451          */
3452         spin_lock(&reg_indoor_lock);
3453         if (reg_is_indoor && !reg_is_indoor_portid) {
3454                 reg_is_indoor = false;
3455                 reg_check_channels();
3456         }
3457         spin_unlock(&reg_indoor_lock);
3458
3459         reset_regdomains(true, &world_regdom);
3460         restore_alpha2(alpha2, reset_user);
3461
3462         /*
3463          * If there's any pending requests we simply
3464          * stash them to a temporary pending queue and
3465          * add then after we've restored regulatory
3466          * settings.
3467          */
3468         spin_lock(&reg_requests_lock);
3469         list_splice_tail_init(&reg_requests_list, &tmp_reg_req_list);
3470         spin_unlock(&reg_requests_lock);
3471
3472         /* Clear beacon hints */
3473         spin_lock_bh(&reg_pending_beacons_lock);
3474         list_for_each_entry_safe(reg_beacon, btmp, &reg_pending_beacons, list) {
3475                 list_del(&reg_beacon->list);
3476                 kfree(reg_beacon);
3477         }
3478         spin_unlock_bh(&reg_pending_beacons_lock);
3479
3480         list_for_each_entry_safe(reg_beacon, btmp, &reg_beacon_list, list) {
3481                 list_del(&reg_beacon->list);
3482                 kfree(reg_beacon);
3483         }
3484
3485         /* First restore to the basic regulatory settings */
3486         world_alpha2[0] = cfg80211_world_regdom->alpha2[0];
3487         world_alpha2[1] = cfg80211_world_regdom->alpha2[1];
3488
3489         list_for_each_entry(rdev, &cfg80211_rdev_list, list) {
3490                 if (rdev->wiphy.regulatory_flags & REGULATORY_WIPHY_SELF_MANAGED)
3491                         continue;
3492                 if (rdev->wiphy.regulatory_flags & REGULATORY_CUSTOM_REG)
3493                         restore_custom_reg_settings(&rdev->wiphy);
3494         }
3495
3496         if (cached && (!is_an_alpha2(alpha2) ||
3497                        !IS_ERR_OR_NULL(cfg80211_user_regdom))) {
3498                 reset_regdomains(false, cfg80211_world_regdom);
3499                 update_all_wiphy_regulatory(NL80211_REGDOM_SET_BY_CORE);
3500                 print_regdomain(get_cfg80211_regdom());
3501                 nl80211_send_reg_change_event(&core_request_world);
3502                 reg_set_request_processed();
3503
3504                 if (is_an_alpha2(alpha2) &&
3505                     !regulatory_hint_user(alpha2, NL80211_USER_REG_HINT_USER)) {
3506                         struct regulatory_request *ureq;
3507
3508                         spin_lock(&reg_requests_lock);
3509                         ureq = list_last_entry(&reg_requests_list,
3510                                                struct regulatory_request,
3511                                                list);
3512                         list_del(&ureq->list);
3513                         spin_unlock(&reg_requests_lock);
3514
3515                         notify_self_managed_wiphys(ureq);
3516                         reg_update_last_request(ureq);
3517                         set_regdom(reg_copy_regd(cfg80211_user_regdom),
3518                                    REGD_SOURCE_CACHED);
3519                 }
3520         } else {
3521                 regulatory_hint_core(world_alpha2);
3522
3523                 /*
3524                  * This restores the ieee80211_regdom module parameter
3525                  * preference or the last user requested regulatory
3526                  * settings, user regulatory settings takes precedence.
3527                  */
3528                 if (is_an_alpha2(alpha2))
3529                         regulatory_hint_user(alpha2, NL80211_USER_REG_HINT_USER);
3530         }
3531
3532         spin_lock(&reg_requests_lock);
3533         list_splice_tail_init(&tmp_reg_req_list, &reg_requests_list);
3534         spin_unlock(&reg_requests_lock);
3535
3536         pr_debug("Kicking the queue\n");
3537
3538         schedule_work(&reg_work);
3539 }
3540
3541 static bool is_wiphy_all_set_reg_flag(enum ieee80211_regulatory_flags flag)
3542 {
3543         struct cfg80211_registered_device *rdev;
3544         struct wireless_dev *wdev;
3545
3546         list_for_each_entry(rdev, &cfg80211_rdev_list, list) {
3547                 list_for_each_entry(wdev, &rdev->wiphy.wdev_list, list) {
3548                         wdev_lock(wdev);
3549                         if (!(wdev->wiphy->regulatory_flags & flag)) {
3550                                 wdev_unlock(wdev);
3551                                 return false;
3552                         }
3553                         wdev_unlock(wdev);
3554                 }
3555         }
3556
3557         return true;
3558 }
3559
3560 void regulatory_hint_disconnect(void)
3561 {
3562         /* Restore of regulatory settings is not required when wiphy(s)
3563          * ignore IE from connected access point but clearance of beacon hints
3564          * is required when wiphy(s) supports beacon hints.
3565          */
3566         if (is_wiphy_all_set_reg_flag(REGULATORY_COUNTRY_IE_IGNORE)) {
3567                 struct reg_beacon *reg_beacon, *btmp;
3568
3569                 if (is_wiphy_all_set_reg_flag(REGULATORY_DISABLE_BEACON_HINTS))
3570                         return;
3571
3572                 spin_lock_bh(&reg_pending_beacons_lock);
3573                 list_for_each_entry_safe(reg_beacon, btmp,
3574                                          &reg_pending_beacons, list) {
3575                         list_del(&reg_beacon->list);
3576                         kfree(reg_beacon);
3577                 }
3578                 spin_unlock_bh(&reg_pending_beacons_lock);
3579
3580                 list_for_each_entry_safe(reg_beacon, btmp,
3581                                          &reg_beacon_list, list) {
3582                         list_del(&reg_beacon->list);
3583                         kfree(reg_beacon);
3584                 }
3585
3586                 return;
3587         }
3588
3589         pr_debug("All devices are disconnected, going to restore regulatory settings\n");
3590         restore_regulatory_settings(false, true);
3591 }
3592
3593 static bool freq_is_chan_12_13_14(u32 freq)
3594 {
3595         if (freq == ieee80211_channel_to_frequency(12, NL80211_BAND_2GHZ) ||
3596             freq == ieee80211_channel_to_frequency(13, NL80211_BAND_2GHZ) ||
3597             freq == ieee80211_channel_to_frequency(14, NL80211_BAND_2GHZ))
3598                 return true;
3599         return false;
3600 }
3601
3602 static bool pending_reg_beacon(struct ieee80211_channel *beacon_chan)
3603 {
3604         struct reg_beacon *pending_beacon;
3605
3606         list_for_each_entry(pending_beacon, &reg_pending_beacons, list)
3607                 if (ieee80211_channel_equal(beacon_chan,
3608                                             &pending_beacon->chan))
3609                         return true;
3610         return false;
3611 }
3612
3613 int regulatory_hint_found_beacon(struct wiphy *wiphy,
3614                                  struct ieee80211_channel *beacon_chan,
3615                                  gfp_t gfp)
3616 {
3617         struct reg_beacon *reg_beacon;
3618         bool processing;
3619
3620         if (beacon_chan->beacon_found ||
3621             beacon_chan->flags & IEEE80211_CHAN_RADAR ||
3622             (beacon_chan->band == NL80211_BAND_2GHZ &&
3623              !freq_is_chan_12_13_14(beacon_chan->center_freq)))
3624                 return 0;
3625
3626         spin_lock_bh(&reg_pending_beacons_lock);
3627         processing = pending_reg_beacon(beacon_chan);
3628         spin_unlock_bh(&reg_pending_beacons_lock);
3629
3630         if (processing)
3631                 return 0;
3632
3633         reg_beacon = kzalloc(sizeof(struct reg_beacon), gfp);
3634         if (!reg_beacon)
3635                 return -ENOMEM;
3636
3637         pr_debug("Found new beacon on frequency: %d.%03d MHz (Ch %d) on %s\n",
3638                  beacon_chan->center_freq, beacon_chan->freq_offset,
3639                  ieee80211_freq_khz_to_channel(
3640                          ieee80211_channel_to_khz(beacon_chan)),
3641                  wiphy_name(wiphy));
3642
3643         memcpy(&reg_beacon->chan, beacon_chan,
3644                sizeof(struct ieee80211_channel));
3645
3646         /*
3647          * Since we can be called from BH or and non-BH context
3648          * we must use spin_lock_bh()
3649          */
3650         spin_lock_bh(&reg_pending_beacons_lock);
3651         list_add_tail(&reg_beacon->list, &reg_pending_beacons);
3652         spin_unlock_bh(&reg_pending_beacons_lock);
3653
3654         schedule_work(&reg_work);
3655
3656         return 0;
3657 }
3658
3659 static void print_rd_rules(const struct ieee80211_regdomain *rd)
3660 {
3661         unsigned int i;
3662         const struct ieee80211_reg_rule *reg_rule = NULL;
3663         const struct ieee80211_freq_range *freq_range = NULL;
3664         const struct ieee80211_power_rule *power_rule = NULL;
3665         char bw[32], cac_time[32];
3666
3667         pr_debug("  (start_freq - end_freq @ bandwidth), (max_antenna_gain, max_eirp), (dfs_cac_time)\n");
3668
3669         for (i = 0; i < rd->n_reg_rules; i++) {
3670                 reg_rule = &rd->reg_rules[i];
3671                 freq_range = &reg_rule->freq_range;
3672                 power_rule = &reg_rule->power_rule;
3673
3674                 if (reg_rule->flags & NL80211_RRF_AUTO_BW)
3675                         snprintf(bw, sizeof(bw), "%d KHz, %u KHz AUTO",
3676                                  freq_range->max_bandwidth_khz,
3677                                  reg_get_max_bandwidth(rd, reg_rule));
3678                 else
3679                         snprintf(bw, sizeof(bw), "%d KHz",
3680                                  freq_range->max_bandwidth_khz);
3681
3682                 if (reg_rule->flags & NL80211_RRF_DFS)
3683                         scnprintf(cac_time, sizeof(cac_time), "%u s",
3684                                   reg_rule->dfs_cac_ms/1000);
3685                 else
3686                         scnprintf(cac_time, sizeof(cac_time), "N/A");
3687
3688
3689                 /*
3690                  * There may not be documentation for max antenna gain
3691                  * in certain regions
3692                  */
3693                 if (power_rule->max_antenna_gain)
3694                         pr_debug("  (%d KHz - %d KHz @ %s), (%d mBi, %d mBm), (%s)\n",
3695                                 freq_range->start_freq_khz,
3696                                 freq_range->end_freq_khz,
3697                                 bw,
3698                                 power_rule->max_antenna_gain,
3699                                 power_rule->max_eirp,
3700                                 cac_time);
3701                 else
3702                         pr_debug("  (%d KHz - %d KHz @ %s), (N/A, %d mBm), (%s)\n",
3703                                 freq_range->start_freq_khz,
3704                                 freq_range->end_freq_khz,
3705                                 bw,
3706                                 power_rule->max_eirp,
3707                                 cac_time);
3708         }
3709 }
3710
3711 bool reg_supported_dfs_region(enum nl80211_dfs_regions dfs_region)
3712 {
3713         switch (dfs_region) {
3714         case NL80211_DFS_UNSET:
3715         case NL80211_DFS_FCC:
3716         case NL80211_DFS_ETSI:
3717         case NL80211_DFS_JP:
3718                 return true;
3719         default:
3720                 pr_debug("Ignoring unknown DFS master region: %d\n", dfs_region);
3721                 return false;
3722         }
3723 }
3724
3725 static void print_regdomain(const struct ieee80211_regdomain *rd)
3726 {
3727         struct regulatory_request *lr = get_last_request();
3728
3729         if (is_intersected_alpha2(rd->alpha2)) {
3730                 if (lr->initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE) {
3731                         struct cfg80211_registered_device *rdev;
3732                         rdev = cfg80211_rdev_by_wiphy_idx(lr->wiphy_idx);
3733                         if (rdev) {
3734                                 pr_debug("Current regulatory domain updated by AP to: %c%c\n",
3735                                         rdev->country_ie_alpha2[0],
3736                                         rdev->country_ie_alpha2[1]);
3737                         } else
3738                                 pr_debug("Current regulatory domain intersected:\n");
3739                 } else
3740                         pr_debug("Current regulatory domain intersected:\n");
3741         } else if (is_world_regdom(rd->alpha2)) {
3742                 pr_debug("World regulatory domain updated:\n");
3743         } else {
3744                 if (is_unknown_alpha2(rd->alpha2))
3745                         pr_debug("Regulatory domain changed to driver built-in settings (unknown country)\n");
3746                 else {
3747                         if (reg_request_cell_base(lr))
3748                                 pr_debug("Regulatory domain changed to country: %c%c by Cell Station\n",
3749                                         rd->alpha2[0], rd->alpha2[1]);
3750                         else
3751                                 pr_debug("Regulatory domain changed to country: %c%c\n",
3752                                         rd->alpha2[0], rd->alpha2[1]);
3753                 }
3754         }
3755
3756         pr_debug(" DFS Master region: %s", reg_dfs_region_str(rd->dfs_region));
3757         print_rd_rules(rd);
3758 }
3759
3760 static void print_regdomain_info(const struct ieee80211_regdomain *rd)
3761 {
3762         pr_debug("Regulatory domain: %c%c\n", rd->alpha2[0], rd->alpha2[1]);
3763         print_rd_rules(rd);
3764 }
3765
3766 static int reg_set_rd_core(const struct ieee80211_regdomain *rd)
3767 {
3768         if (!is_world_regdom(rd->alpha2))
3769                 return -EINVAL;
3770         update_world_regdomain(rd);
3771         return 0;
3772 }
3773
3774 static int reg_set_rd_user(const struct ieee80211_regdomain *rd,
3775                            struct regulatory_request *user_request)
3776 {
3777         const struct ieee80211_regdomain *intersected_rd = NULL;
3778
3779         if (!regdom_changes(rd->alpha2))
3780                 return -EALREADY;
3781
3782         if (!is_valid_rd(rd)) {
3783                 pr_err("Invalid regulatory domain detected: %c%c\n",
3784                        rd->alpha2[0], rd->alpha2[1]);
3785                 print_regdomain_info(rd);
3786                 return -EINVAL;
3787         }
3788
3789         if (!user_request->intersect) {
3790                 reset_regdomains(false, rd);
3791                 return 0;
3792         }
3793
3794         intersected_rd = regdom_intersect(rd, get_cfg80211_regdom());
3795         if (!intersected_rd)
3796                 return -EINVAL;
3797
3798         kfree(rd);
3799         rd = NULL;
3800         reset_regdomains(false, intersected_rd);
3801
3802         return 0;
3803 }
3804
3805 static int reg_set_rd_driver(const struct ieee80211_regdomain *rd,
3806                              struct regulatory_request *driver_request)
3807 {
3808         const struct ieee80211_regdomain *regd;
3809         const struct ieee80211_regdomain *intersected_rd = NULL;
3810         const struct ieee80211_regdomain *tmp;
3811         struct wiphy *request_wiphy;
3812
3813         if (is_world_regdom(rd->alpha2))
3814                 return -EINVAL;
3815
3816         if (!regdom_changes(rd->alpha2))
3817                 return -EALREADY;
3818
3819         if (!is_valid_rd(rd)) {
3820                 pr_err("Invalid regulatory domain detected: %c%c\n",
3821                        rd->alpha2[0], rd->alpha2[1]);
3822                 print_regdomain_info(rd);
3823                 return -EINVAL;
3824         }
3825
3826         request_wiphy = wiphy_idx_to_wiphy(driver_request->wiphy_idx);
3827         if (!request_wiphy)
3828                 return -ENODEV;
3829
3830         if (!driver_request->intersect) {
3831                 ASSERT_RTNL();
3832                 wiphy_lock(request_wiphy);
3833                 if (request_wiphy->regd) {
3834                         wiphy_unlock(request_wiphy);
3835                         return -EALREADY;
3836                 }
3837
3838                 regd = reg_copy_regd(rd);
3839                 if (IS_ERR(regd)) {
3840                         wiphy_unlock(request_wiphy);
3841                         return PTR_ERR(regd);
3842                 }
3843
3844                 rcu_assign_pointer(request_wiphy->regd, regd);
3845                 wiphy_unlock(request_wiphy);
3846                 reset_regdomains(false, rd);
3847                 return 0;
3848         }
3849
3850         intersected_rd = regdom_intersect(rd, get_cfg80211_regdom());
3851         if (!intersected_rd)
3852                 return -EINVAL;
3853
3854         /*
3855          * We can trash what CRDA provided now.
3856          * However if a driver requested this specific regulatory
3857          * domain we keep it for its private use
3858          */
3859         tmp = get_wiphy_regdom(request_wiphy);
3860         rcu_assign_pointer(request_wiphy->regd, rd);
3861         rcu_free_regdom(tmp);
3862
3863         rd = NULL;
3864
3865         reset_regdomains(false, intersected_rd);
3866
3867         return 0;
3868 }
3869
3870 static int reg_set_rd_country_ie(const struct ieee80211_regdomain *rd,
3871                                  struct regulatory_request *country_ie_request)
3872 {
3873         struct wiphy *request_wiphy;
3874
3875         if (!is_alpha2_set(rd->alpha2) && !is_an_alpha2(rd->alpha2) &&
3876             !is_unknown_alpha2(rd->alpha2))
3877                 return -EINVAL;
3878
3879         /*
3880          * Lets only bother proceeding on the same alpha2 if the current
3881          * rd is non static (it means CRDA was present and was used last)
3882          * and the pending request came in from a country IE
3883          */
3884
3885         if (!is_valid_rd(rd)) {
3886                 pr_err("Invalid regulatory domain detected: %c%c\n",
3887                        rd->alpha2[0], rd->alpha2[1]);
3888                 print_regdomain_info(rd);
3889                 return -EINVAL;
3890         }
3891
3892         request_wiphy = wiphy_idx_to_wiphy(country_ie_request->wiphy_idx);
3893         if (!request_wiphy)
3894                 return -ENODEV;
3895
3896         if (country_ie_request->intersect)
3897                 return -EINVAL;
3898
3899         reset_regdomains(false, rd);
3900         return 0;
3901 }
3902
3903 /*
3904  * Use this call to set the current regulatory domain. Conflicts with
3905  * multiple drivers can be ironed out later. Caller must've already
3906  * kmalloc'd the rd structure.
3907  */
3908 int set_regdom(const struct ieee80211_regdomain *rd,
3909                enum ieee80211_regd_source regd_src)
3910 {
3911         struct regulatory_request *lr;
3912         bool user_reset = false;
3913         int r;
3914
3915         if (IS_ERR_OR_NULL(rd))
3916                 return -ENODATA;
3917
3918         if (!reg_is_valid_request(rd->alpha2)) {
3919                 kfree(rd);
3920                 return -EINVAL;
3921         }
3922
3923         if (regd_src == REGD_SOURCE_CRDA)
3924                 reset_crda_timeouts();
3925
3926         lr = get_last_request();
3927
3928         /* Note that this doesn't update the wiphys, this is done below */
3929         switch (lr->initiator) {
3930         case NL80211_REGDOM_SET_BY_CORE:
3931                 r = reg_set_rd_core(rd);
3932                 break;
3933         case NL80211_REGDOM_SET_BY_USER:
3934                 cfg80211_save_user_regdom(rd);
3935                 r = reg_set_rd_user(rd, lr);
3936                 user_reset = true;
3937                 break;
3938         case NL80211_REGDOM_SET_BY_DRIVER:
3939                 r = reg_set_rd_driver(rd, lr);
3940                 break;
3941         case NL80211_REGDOM_SET_BY_COUNTRY_IE:
3942                 r = reg_set_rd_country_ie(rd, lr);
3943                 break;
3944         default:
3945                 WARN(1, "invalid initiator %d\n", lr->initiator);
3946                 kfree(rd);
3947                 return -EINVAL;
3948         }
3949
3950         if (r) {
3951                 switch (r) {
3952                 case -EALREADY:
3953                         reg_set_request_processed();
3954                         break;
3955                 default:
3956                         /* Back to world regulatory in case of errors */
3957                         restore_regulatory_settings(user_reset, false);
3958                 }
3959
3960                 kfree(rd);
3961                 return r;
3962         }
3963
3964         /* This would make this whole thing pointless */
3965         if (WARN_ON(!lr->intersect && rd != get_cfg80211_regdom()))
3966                 return -EINVAL;
3967
3968         /* update all wiphys now with the new established regulatory domain */
3969         update_all_wiphy_regulatory(lr->initiator);
3970
3971         print_regdomain(get_cfg80211_regdom());
3972
3973         nl80211_send_reg_change_event(lr);
3974
3975         reg_set_request_processed();
3976
3977         return 0;
3978 }
3979
3980 static int __regulatory_set_wiphy_regd(struct wiphy *wiphy,
3981                                        struct ieee80211_regdomain *rd)
3982 {
3983         const struct ieee80211_regdomain *regd;
3984         const struct ieee80211_regdomain *prev_regd;
3985         struct cfg80211_registered_device *rdev;
3986
3987         if (WARN_ON(!wiphy || !rd))
3988                 return -EINVAL;
3989
3990         if (WARN(!(wiphy->regulatory_flags & REGULATORY_WIPHY_SELF_MANAGED),
3991                  "wiphy should have REGULATORY_WIPHY_SELF_MANAGED\n"))
3992                 return -EPERM;
3993
3994         if (WARN(!is_valid_rd(rd),
3995                  "Invalid regulatory domain detected: %c%c\n",
3996                  rd->alpha2[0], rd->alpha2[1])) {
3997                 print_regdomain_info(rd);
3998                 return -EINVAL;
3999         }
4000
4001         regd = reg_copy_regd(rd);
4002         if (IS_ERR(regd))
4003                 return PTR_ERR(regd);
4004
4005         rdev = wiphy_to_rdev(wiphy);
4006
4007         spin_lock(&reg_requests_lock);
4008         prev_regd = rdev->requested_regd;
4009         rdev->requested_regd = regd;
4010         spin_unlock(&reg_requests_lock);
4011
4012         kfree(prev_regd);
4013         return 0;
4014 }
4015
4016 int regulatory_set_wiphy_regd(struct wiphy *wiphy,
4017                               struct ieee80211_regdomain *rd)
4018 {
4019         int ret = __regulatory_set_wiphy_regd(wiphy, rd);
4020
4021         if (ret)
4022                 return ret;
4023
4024         schedule_work(&reg_work);
4025         return 0;
4026 }
4027 EXPORT_SYMBOL(regulatory_set_wiphy_regd);
4028
4029 int regulatory_set_wiphy_regd_sync(struct wiphy *wiphy,
4030                                    struct ieee80211_regdomain *rd)
4031 {
4032         int ret;
4033
4034         ASSERT_RTNL();
4035
4036         ret = __regulatory_set_wiphy_regd(wiphy, rd);
4037         if (ret)
4038                 return ret;
4039
4040         /* process the request immediately */
4041         reg_process_self_managed_hint(wiphy);
4042         reg_check_channels();
4043         return 0;
4044 }
4045 EXPORT_SYMBOL(regulatory_set_wiphy_regd_sync);
4046
4047 void wiphy_regulatory_register(struct wiphy *wiphy)
4048 {
4049         struct regulatory_request *lr = get_last_request();
4050
4051         /* self-managed devices ignore beacon hints and country IE */
4052         if (wiphy->regulatory_flags & REGULATORY_WIPHY_SELF_MANAGED) {
4053                 wiphy->regulatory_flags |= REGULATORY_DISABLE_BEACON_HINTS |
4054                                            REGULATORY_COUNTRY_IE_IGNORE;
4055
4056                 /*
4057                  * The last request may have been received before this
4058                  * registration call. Call the driver notifier if
4059                  * initiator is USER.
4060                  */
4061                 if (lr->initiator == NL80211_REGDOM_SET_BY_USER)
4062                         reg_call_notifier(wiphy, lr);
4063         }
4064
4065         if (!reg_dev_ignore_cell_hint(wiphy))
4066                 reg_num_devs_support_basehint++;
4067
4068         wiphy_update_regulatory(wiphy, lr->initiator);
4069         wiphy_all_share_dfs_chan_state(wiphy);
4070         reg_process_self_managed_hints();
4071 }
4072
4073 void wiphy_regulatory_deregister(struct wiphy *wiphy)
4074 {
4075         struct wiphy *request_wiphy = NULL;
4076         struct regulatory_request *lr;
4077
4078         lr = get_last_request();
4079
4080         if (!reg_dev_ignore_cell_hint(wiphy))
4081                 reg_num_devs_support_basehint--;
4082
4083         rcu_free_regdom(get_wiphy_regdom(wiphy));
4084         RCU_INIT_POINTER(wiphy->regd, NULL);
4085
4086         if (lr)
4087                 request_wiphy = wiphy_idx_to_wiphy(lr->wiphy_idx);
4088
4089         if (!request_wiphy || request_wiphy != wiphy)
4090                 return;
4091
4092         lr->wiphy_idx = WIPHY_IDX_INVALID;
4093         lr->country_ie_env = ENVIRON_ANY;
4094 }
4095
4096 /*
4097  * See FCC notices for UNII band definitions
4098  *  5GHz: https://www.fcc.gov/document/5-ghz-unlicensed-spectrum-unii
4099  *  6GHz: https://www.fcc.gov/document/fcc-proposes-more-spectrum-unlicensed-use-0
4100  */
4101 int cfg80211_get_unii(int freq)
4102 {
4103         /* UNII-1 */
4104         if (freq >= 5150 && freq <= 5250)
4105                 return 0;
4106
4107         /* UNII-2A */
4108         if (freq > 5250 && freq <= 5350)
4109                 return 1;
4110
4111         /* UNII-2B */
4112         if (freq > 5350 && freq <= 5470)
4113                 return 2;
4114
4115         /* UNII-2C */
4116         if (freq > 5470 && freq <= 5725)
4117                 return 3;
4118
4119         /* UNII-3 */
4120         if (freq > 5725 && freq <= 5825)
4121                 return 4;
4122
4123         /* UNII-5 */
4124         if (freq > 5925 && freq <= 6425)
4125                 return 5;
4126
4127         /* UNII-6 */
4128         if (freq > 6425 && freq <= 6525)
4129                 return 6;
4130
4131         /* UNII-7 */
4132         if (freq > 6525 && freq <= 6875)
4133                 return 7;
4134
4135         /* UNII-8 */
4136         if (freq > 6875 && freq <= 7125)
4137                 return 8;
4138
4139         return -EINVAL;
4140 }
4141
4142 bool regulatory_indoor_allowed(void)
4143 {
4144         return reg_is_indoor;
4145 }
4146
4147 bool regulatory_pre_cac_allowed(struct wiphy *wiphy)
4148 {
4149         const struct ieee80211_regdomain *regd = NULL;
4150         const struct ieee80211_regdomain *wiphy_regd = NULL;
4151         bool pre_cac_allowed = false;
4152
4153         rcu_read_lock();
4154
4155         regd = rcu_dereference(cfg80211_regdomain);
4156         wiphy_regd = rcu_dereference(wiphy->regd);
4157         if (!wiphy_regd) {
4158                 if (regd->dfs_region == NL80211_DFS_ETSI)
4159                         pre_cac_allowed = true;
4160
4161                 rcu_read_unlock();
4162
4163                 return pre_cac_allowed;
4164         }
4165
4166         if (regd->dfs_region == wiphy_regd->dfs_region &&
4167             wiphy_regd->dfs_region == NL80211_DFS_ETSI)
4168                 pre_cac_allowed = true;
4169
4170         rcu_read_unlock();
4171
4172         return pre_cac_allowed;
4173 }
4174 EXPORT_SYMBOL(regulatory_pre_cac_allowed);
4175
4176 static void cfg80211_check_and_end_cac(struct cfg80211_registered_device *rdev)
4177 {
4178         struct wireless_dev *wdev;
4179         /* If we finished CAC or received radar, we should end any
4180          * CAC running on the same channels.
4181          * the check !cfg80211_chandef_dfs_usable contain 2 options:
4182          * either all channels are available - those the CAC_FINISHED
4183          * event has effected another wdev state, or there is a channel
4184          * in unavailable state in wdev chandef - those the RADAR_DETECTED
4185          * event has effected another wdev state.
4186          * In both cases we should end the CAC on the wdev.
4187          */
4188         list_for_each_entry(wdev, &rdev->wiphy.wdev_list, list) {
4189                 if (wdev->cac_started &&
4190                     !cfg80211_chandef_dfs_usable(&rdev->wiphy, &wdev->chandef))
4191                         rdev_end_cac(rdev, wdev->netdev);
4192         }
4193 }
4194
4195 void regulatory_propagate_dfs_state(struct wiphy *wiphy,
4196                                     struct cfg80211_chan_def *chandef,
4197                                     enum nl80211_dfs_state dfs_state,
4198                                     enum nl80211_radar_event event)
4199 {
4200         struct cfg80211_registered_device *rdev;
4201
4202         ASSERT_RTNL();
4203
4204         if (WARN_ON(!cfg80211_chandef_valid(chandef)))
4205                 return;
4206
4207         list_for_each_entry(rdev, &cfg80211_rdev_list, list) {
4208                 if (wiphy == &rdev->wiphy)
4209                         continue;
4210
4211                 if (!reg_dfs_domain_same(wiphy, &rdev->wiphy))
4212                         continue;
4213
4214                 if (!ieee80211_get_channel(&rdev->wiphy,
4215                                            chandef->chan->center_freq))
4216                         continue;
4217
4218                 cfg80211_set_dfs_state(&rdev->wiphy, chandef, dfs_state);
4219
4220                 if (event == NL80211_RADAR_DETECTED ||
4221                     event == NL80211_RADAR_CAC_FINISHED) {
4222                         cfg80211_sched_dfs_chan_update(rdev);
4223                         cfg80211_check_and_end_cac(rdev);
4224                 }
4225
4226                 nl80211_radar_notify(rdev, chandef, event, NULL, GFP_KERNEL);
4227         }
4228 }
4229
4230 static int __init regulatory_init_db(void)
4231 {
4232         int err;
4233
4234         /*
4235          * It's possible that - due to other bugs/issues - cfg80211
4236          * never called regulatory_init() below, or that it failed;
4237          * in that case, don't try to do any further work here as
4238          * it's doomed to lead to crashes.
4239          */
4240         if (IS_ERR_OR_NULL(reg_pdev))
4241                 return -EINVAL;
4242
4243         err = load_builtin_regdb_keys();
4244         if (err)
4245                 return err;
4246
4247         /* We always try to get an update for the static regdomain */
4248         err = regulatory_hint_core(cfg80211_world_regdom->alpha2);
4249         if (err) {
4250                 if (err == -ENOMEM) {
4251                         platform_device_unregister(reg_pdev);
4252                         return err;
4253                 }
4254                 /*
4255                  * N.B. kobject_uevent_env() can fail mainly for when we're out
4256                  * memory which is handled and propagated appropriately above
4257                  * but it can also fail during a netlink_broadcast() or during
4258                  * early boot for call_usermodehelper(). For now treat these
4259                  * errors as non-fatal.
4260                  */
4261                 pr_err("kobject_uevent_env() was unable to call CRDA during init\n");
4262         }
4263
4264         /*
4265          * Finally, if the user set the module parameter treat it
4266          * as a user hint.
4267          */
4268         if (!is_world_regdom(ieee80211_regdom))
4269                 regulatory_hint_user(ieee80211_regdom,
4270                                      NL80211_USER_REG_HINT_USER);
4271
4272         return 0;
4273 }
4274 #ifndef MODULE
4275 late_initcall(regulatory_init_db);
4276 #endif
4277
4278 int __init regulatory_init(void)
4279 {
4280         reg_pdev = platform_device_register_simple("regulatory", 0, NULL, 0);
4281         if (IS_ERR(reg_pdev))
4282                 return PTR_ERR(reg_pdev);
4283
4284         rcu_assign_pointer(cfg80211_regdomain, cfg80211_world_regdom);
4285
4286         user_alpha2[0] = '9';
4287         user_alpha2[1] = '7';
4288
4289 #ifdef MODULE
4290         return regulatory_init_db();
4291 #else
4292         return 0;
4293 #endif
4294 }
4295
4296 void regulatory_exit(void)
4297 {
4298         struct regulatory_request *reg_request, *tmp;
4299         struct reg_beacon *reg_beacon, *btmp;
4300
4301         cancel_work_sync(&reg_work);
4302         cancel_crda_timeout_sync();
4303         cancel_delayed_work_sync(&reg_check_chans);
4304
4305         /* Lock to suppress warnings */
4306         rtnl_lock();
4307         reset_regdomains(true, NULL);
4308         rtnl_unlock();
4309
4310         dev_set_uevent_suppress(&reg_pdev->dev, true);
4311
4312         platform_device_unregister(reg_pdev);
4313
4314         list_for_each_entry_safe(reg_beacon, btmp, &reg_pending_beacons, list) {
4315                 list_del(&reg_beacon->list);
4316                 kfree(reg_beacon);
4317         }
4318
4319         list_for_each_entry_safe(reg_beacon, btmp, &reg_beacon_list, list) {
4320                 list_del(&reg_beacon->list);
4321                 kfree(reg_beacon);
4322         }
4323
4324         list_for_each_entry_safe(reg_request, tmp, &reg_requests_list, list) {
4325                 list_del(&reg_request->list);
4326                 kfree(reg_request);
4327         }
4328
4329         if (!IS_ERR_OR_NULL(regdb))
4330                 kfree(regdb);
4331         if (!IS_ERR_OR_NULL(cfg80211_user_regdom))
4332                 kfree(cfg80211_user_regdom);
4333
4334         free_regdb_keyring();
4335 }