eiwd

no dbus iwd with iwctl functionality
git clone https://git.daat.foo/repos/eiwd.git
Log | Files | Refs | Submodules | README | LICENSE

scan.c (66374B)


      1 /*
      2  *
      3  *  Wireless daemon for Linux
      4  *
      5  *  Copyright (C) 2015-2019  Intel Corporation. All rights reserved.
      6  *
      7  *  This library is free software; you can redistribute it and/or
      8  *  modify it under the terms of the GNU Lesser General Public
      9  *  License as published by the Free Software Foundation; either
     10  *  version 2.1 of the License, or (at your option) any later version.
     11  *
     12  *  This library is distributed in the hope that it will be useful,
     13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
     14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     15  *  Lesser General Public License for more details.
     16  *
     17  *  You should have received a copy of the GNU Lesser General Public
     18  *  License along with this library; if not, write to the Free Software
     19  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
     20  *
     21  */
     22 
     23 #ifdef HAVE_CONFIG_H
     24 #include <config.h>
     25 #endif
     26 
     27 #define _GNU_SOURCE
     28 #include <stdlib.h>
     29 #include <stdio.h>
     30 #include <errno.h>
     31 #include <time.h>
     32 #include <sys/socket.h>
     33 #include <limits.h>
     34 #include <linux/if.h>
     35 #include <linux/if_ether.h>
     36 #include <ell/ell.h>
     37 
     38 #include "ell/useful.h"
     39 #include "linux/nl80211.h"
     40 #include "src/iwd.h"
     41 #include "src/module.h"
     42 #include "src/wiphy.h"
     43 #include "src/ie.h"
     44 #include "src/common.h"
     45 #include "src/network.h"
     46 #include "src/knownnetworks.h"
     47 #include "src/nl80211cmd.h"
     48 #include "src/nl80211util.h"
     49 #include "src/util.h"
     50 #include "src/p2putil.h"
     51 #include "src/mpdu.h"
     52 #include "src/band.h"
     53 #include "src/scan.h"
     54 #include "src/vendor_quirks.h"
     55 
     56 /* User configurable options */
     57 static double RANK_2G_FACTOR;
     58 static double RANK_5G_FACTOR;
     59 static double RANK_6G_FACTOR;
     60 static uint32_t RANK_HIGH_UTILIZATION;
     61 static uint32_t RANK_HIGH_STATION_COUNT;
     62 static uint32_t SCAN_MAX_INTERVAL;
     63 static uint32_t SCAN_INIT_INTERVAL;
     64 
     65 static struct l_queue *scan_contexts;
     66 
     67 static struct l_genl_family *nl80211;
     68 
     69 struct scan_context;
     70 
     71 struct scan_periodic {
     72 	struct l_timeout *timeout;
     73 	uint16_t interval;
     74 	scan_trigger_func_t trigger;
     75 	scan_notify_func_t callback;
     76 	void *userdata;
     77 	uint32_t id;
     78 	bool needs_active_scan:1;
     79 };
     80 
     81 struct scan_request {
     82 	struct scan_context *sc;
     83 	scan_trigger_func_t trigger;
     84 	scan_notify_func_t callback;
     85 	void *userdata;
     86 	scan_destroy_func_t destroy;
     87 	bool canceled : 1; /* Is scan_cancel being called on this request? */
     88 	bool passive:1; /* Active or Passive scan? */
     89 	bool started : 1; /* Has TRIGGER_SCAN succeeded at least once? */
     90 	/*
     91 	 * Set to true if the TRIGGER_SCAN command at the head of the 'cmds'
     92 	 * queue was acked by the kernel indicating that the scan request was
     93 	 * successful.  May be set and cleared multiple times during a
     94 	 * the scan_request lifetime (as each command in the 'cmds' queue is
     95 	 * issued to the kernel).  Will be false if the current request
     96 	 * was not started due to an -EBUSY error from the kernel.  Also will
     97 	 * be false when the scan is complete and GET_SCAN is pending.
     98 	 */
     99 	bool triggered : 1;
    100 	bool in_callback : 1; /* Scan request complete, re-entrancy guard */
    101 	/* The request was split anticipating 6GHz will become available */
    102 	bool split : 1;
    103 	struct l_queue *cmds;
    104 	/* The time the current scan was started. Reported in TRIGGER_SCAN */
    105 	uint64_t start_time_tsf;
    106 	struct wiphy_radio_work_item work;
    107 	/*
    108 	 * List of frequencies scanned so far. Since the NEW_SCAN_RESULTS event
    109 	 * contains frequencies of only the last CMD_TRIGGER we need to parse
    110 	 * and save these since there may be additional scan commands to run.
    111 	 */
    112 	struct scan_freq_set *freqs_scanned;
    113 	/* Entire list of frequencies to scan */
    114 	struct scan_freq_set *scan_freqs;
    115 };
    116 
    117 struct scan_context {
    118 	uint64_t wdev_id;
    119 	uint32_t wiphy_watch_id;
    120 	/*
    121 	 * Tells us whether a scan, our own or external, is running.
    122 	 * Set when scan gets triggered, cleared when scan done and
    123 	 * before actual results are queried.
    124 	 */
    125 	enum scan_state state;
    126 	struct scan_periodic sp;
    127 	struct l_queue *requests;
    128 	/* Non-zero if SCAN_TRIGGER is still running */
    129 	unsigned int start_cmd_id;
    130 	/* Non-zero if GET_SCAN is still running */
    131 	unsigned int get_scan_cmd_id;
    132 	/*
    133 	 * Special request used for getting scan results after the firmware
    134 	 * roamed automatically.
    135 	 */
    136 	unsigned int get_fw_scan_cmd_id;
    137 	struct wiphy *wiphy;
    138 
    139 	unsigned int get_survey_cmd_id;
    140 };
    141 
    142 struct scan_survey {
    143 	int8_t noise;
    144 };
    145 
    146 struct scan_survey_results {
    147 	struct scan_survey survey_2_4[15];
    148 	struct scan_survey survey_5[197];
    149 	struct scan_survey survey_6[234];
    150 };
    151 
    152 struct scan_results {
    153 	struct scan_context *sc;
    154 	struct l_queue *bss_list;
    155 	uint64_t time_stamp;
    156 	struct scan_request *sr;
    157 	struct scan_freq_set *freqs;
    158 	struct scan_survey_results survey;
    159 
    160 	bool survey_parsed : 1;
    161 };
    162 
    163 static bool start_next_scan_request(struct wiphy_radio_work_item *item);
    164 static void scan_periodic_rearm(struct scan_context *sc);
    165 
    166 static bool scan_context_match(const void *a, const void *b)
    167 {
    168 	const struct scan_context *sc = a;
    169 	const uint64_t *wdev_id = b;
    170 
    171 	return sc->wdev_id == *wdev_id;
    172 }
    173 
    174 static bool scan_request_match(const void *a, const void *b)
    175 {
    176 	const struct scan_request *sr = a;
    177 	uint32_t id = L_PTR_TO_UINT(b);
    178 
    179 	return sr->work.id == id;
    180 }
    181 
    182 static void scan_request_free(struct wiphy_radio_work_item *item)
    183 {
    184 	struct scan_request *sr = l_container_of(item, struct scan_request,
    185 							work);
    186 
    187 	if (sr->destroy)
    188 		sr->destroy(sr->userdata);
    189 
    190 	l_queue_destroy(sr->cmds, (l_queue_destroy_func_t) l_genl_msg_unref);
    191 
    192 	scan_freq_set_free(sr->freqs_scanned);
    193 	scan_freq_set_free(sr->scan_freqs);
    194 
    195 	l_free(sr);
    196 }
    197 
    198 static void scan_request_failed(struct scan_context *sc,
    199 				struct scan_request *sr, int err)
    200 {
    201 	sr->in_callback = true;
    202 
    203 	if (sr->trigger)
    204 		sr->trigger(err, sr->userdata);
    205 	else if (sr->callback)
    206 		sr->callback(err, NULL, NULL, sr->userdata);
    207 
    208 	sr->in_callback = false;
    209 	l_queue_remove(sc->requests, sr);
    210 	wiphy_radio_work_done(sc->wiphy, sr->work.id);
    211 }
    212 
    213 static void scan_request_cancel(void *data)
    214 {
    215 	struct scan_request *sr = data;
    216 
    217 	wiphy_radio_work_done(sr->sc->wiphy, sr->work.id);
    218 }
    219 
    220 static void scan_context_free(struct scan_context *sc)
    221 {
    222 	l_debug("sc: %p", sc);
    223 
    224 	l_queue_destroy(sc->requests, scan_request_cancel);
    225 
    226 	if (sc->sp.timeout)
    227 		l_timeout_remove(sc->sp.timeout);
    228 
    229 	if (sc->start_cmd_id && nl80211)
    230 		l_genl_family_cancel(nl80211, sc->start_cmd_id);
    231 
    232 	if (sc->get_scan_cmd_id && nl80211)
    233 		l_genl_family_cancel(nl80211, sc->get_scan_cmd_id);
    234 
    235 	if (sc->get_fw_scan_cmd_id && nl80211)
    236 		l_genl_family_cancel(nl80211, sc->get_fw_scan_cmd_id);
    237 
    238 	if (sc->get_survey_cmd_id && nl80211)
    239 		l_genl_family_cancel(nl80211, sc->get_survey_cmd_id);
    240 
    241 	wiphy_state_watch_remove(sc->wiphy, sc->wiphy_watch_id);
    242 
    243 	l_free(sc);
    244 }
    245 
    246 static void scan_request_triggered(struct l_genl_msg *msg, void *userdata)
    247 {
    248 	struct scan_context *sc = userdata;
    249 	struct scan_request *sr = l_queue_peek_head(sc->requests);
    250 	int err;
    251 
    252 	sc->start_cmd_id = 0;
    253 
    254 	err = l_genl_msg_get_error(msg);
    255 	if (err < 0) {
    256 		/* Scan in progress, assume another scan is running */
    257 		if (err == -EBUSY) {
    258 			sc->state = SCAN_STATE_PASSIVE;
    259 			return;
    260 		}
    261 
    262 		scan_request_failed(sc, sr, err);
    263 
    264 		l_error("Received error during CMD_TRIGGER_SCAN: %s (%d)",
    265 			strerror(-err), -err);
    266 
    267 		return;
    268 	}
    269 
    270 	sc->state = sr->passive ? SCAN_STATE_PASSIVE : SCAN_STATE_ACTIVE;
    271 	l_debug("%s scan triggered for wdev %" PRIx64,
    272 		sr->passive ? "Passive" : "Active", sc->wdev_id);
    273 
    274 	sr->triggered = true;
    275 	sr->started = true;
    276 	l_genl_msg_unref(l_queue_pop_head(sr->cmds));
    277 
    278 	if (sr->trigger) {
    279 		sr->trigger(0, sr->userdata);
    280 
    281 		/*
    282 		 * Reset callback for the consequent scan triggerings of the
    283 		 * multi-segmented scans.
    284 		 */
    285 		sr->trigger = NULL;
    286 	}
    287 }
    288 
    289 struct scan_freq_append_data {
    290 	struct l_genl_msg *msg;
    291 	int count;
    292 };
    293 
    294 static void scan_freq_append(uint32_t freq, void *user_data)
    295 {
    296 	struct scan_freq_append_data *data = user_data;
    297 
    298 	l_genl_msg_append_attr(data->msg, data->count++, 4, &freq);
    299 }
    300 
    301 static void scan_build_attr_scan_frequencies(struct l_genl_msg *msg,
    302 					const struct scan_freq_set *freqs)
    303 {
    304 	struct scan_freq_append_data append_data = { msg, 0 };
    305 
    306 	l_genl_msg_enter_nested(msg, NL80211_ATTR_SCAN_FREQUENCIES);
    307 
    308 	scan_freq_set_foreach(freqs, scan_freq_append, &append_data);
    309 
    310 	l_genl_msg_leave_nested(msg);
    311 }
    312 
    313 static void scan_build_attr_ie(struct l_genl_msg *msg,
    314 					struct scan_context *sc,
    315 					const struct scan_parameters *params)
    316 {
    317 	struct iovec iov[3];
    318 	unsigned int iov_elems = 0;
    319 	const uint8_t *ext_capa;
    320 	uint8_t interworking[3];
    321 
    322 	ext_capa = wiphy_get_extended_capabilities(sc->wiphy,
    323 							NL80211_IFTYPE_STATION);
    324 	/*
    325 	 * If adding IE's here ensure that ordering is not broken for
    326 	 * probe requests (IEEE Std 802.11-2016 Table 9-33).
    327 	 */
    328 	/* Order 9 - Extended Capabilities */
    329 	iov[iov_elems].iov_base = (void *) ext_capa;
    330 	iov[iov_elems].iov_len = ext_capa[1] + 2;
    331 	iov_elems++;
    332 
    333 	if (test_bit(&ext_capa[2 + 3], 7)) {
    334 		/* Order 12 - Interworking */
    335 		interworking[0] = IE_TYPE_INTERWORKING;
    336 		interworking[1] = 1;
    337 		/* Private network, INet=0,ASRA=0,ESR=0,UESA=0 */
    338 		interworking[2] = 0;
    339 
    340 		iov[iov_elems].iov_base = interworking;
    341 		iov[iov_elems].iov_len = 3;
    342 		iov_elems++;
    343 	}
    344 
    345 	/* Order Last (assuming WSC vendor specific) */
    346 	if (params->extra_ie && params->extra_ie_size) {
    347 		iov[iov_elems].iov_base = (void *) params->extra_ie;
    348 		iov[iov_elems].iov_len = params->extra_ie_size;
    349 		iov_elems++;
    350 	}
    351 
    352 	l_genl_msg_append_attrv(msg, NL80211_ATTR_IE, iov, iov_elems);
    353 }
    354 
    355 static bool scan_mac_address_randomization_is_disabled(void)
    356 {
    357 	const struct l_settings *config = iwd_get_config();
    358 	bool disabled;
    359 
    360 	if (!l_settings_get_bool(config, "Scan",
    361 					"DisableMacAddressRandomization",
    362 					&disabled))
    363 		return false;
    364 
    365 	return disabled;
    366 }
    367 
    368 static struct l_genl_msg *scan_build_cmd(struct scan_context *sc,
    369 					bool ignore_flush_flag, bool is_passive,
    370 					const struct scan_parameters *params,
    371 					const struct scan_freq_set *freqs)
    372 {
    373 	struct l_genl_msg *msg;
    374 	uint32_t flags = 0;
    375 
    376 	msg = l_genl_msg_new(NL80211_CMD_TRIGGER_SCAN);
    377 
    378 	l_genl_msg_append_attr(msg, NL80211_ATTR_WDEV, 8, &sc->wdev_id);
    379 
    380 	if (wiphy_get_max_scan_ie_len(sc->wiphy))
    381 		scan_build_attr_ie(msg, sc, params);
    382 
    383 	if (freqs)
    384 		scan_build_attr_scan_frequencies(msg, freqs);
    385 
    386 	if (params->flush && !ignore_flush_flag && wiphy_has_feature(sc->wiphy,
    387 						NL80211_FEATURE_SCAN_FLUSH))
    388 		flags |= NL80211_SCAN_FLAG_FLUSH;
    389 
    390 	if (!is_passive && params->randomize_mac_addr_hint &&
    391 			wiphy_can_randomize_mac_addr(sc->wiphy) &&
    392 				!scan_mac_address_randomization_is_disabled())
    393 		/*
    394 		 * Randomizing 46 bits (locally administered 1 and multicast 0
    395 		 * is assumed).
    396 		 */
    397 		flags |= NL80211_SCAN_FLAG_RANDOM_ADDR;
    398 
    399 	if (!is_passive && params->source_mac &&
    400 			wiphy_can_randomize_mac_addr(sc->wiphy)) {
    401 		static const uint8_t mask[6] =	/* No random bits */
    402 			{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
    403 
    404 		flags |= NL80211_SCAN_FLAG_RANDOM_ADDR;
    405 		l_genl_msg_append_attr(msg, NL80211_ATTR_MAC, 6,
    406 					params->source_mac);
    407 		l_genl_msg_append_attr(msg, NL80211_ATTR_MAC_MASK, 6,
    408 					mask);
    409 	}
    410 
    411 	if (!is_passive && wiphy_has_ext_feature(sc->wiphy,
    412 					NL80211_EXT_FEATURE_SCAN_RANDOM_SN))
    413 		flags |= NL80211_SCAN_FLAG_RANDOM_SN;
    414 
    415 	if (params->ap_scan)
    416 		flags |= NL80211_SCAN_FLAG_AP;
    417 
    418 	if (wiphy_supports_colocated_flag(sc->wiphy))
    419 		flags |= NL80211_SCAN_FLAG_COLOCATED_6GHZ;
    420 
    421 	if (flags)
    422 		l_genl_msg_append_attr(msg, NL80211_ATTR_SCAN_FLAGS, 4, &flags);
    423 
    424 	if (params->no_cck_rates) {
    425 		static const uint8_t b_rates[] = { 2, 4, 11, 22 };
    426 		uint8_t *scan_rates;
    427 		const uint8_t *supported;
    428 		unsigned int num_supported;
    429 		unsigned int count;
    430 		unsigned int i;
    431 
    432 		l_genl_msg_append_attr(msg, NL80211_ATTR_TX_NO_CCK_RATE, 0,
    433 					NULL);
    434 
    435 		/*
    436 		 * Assume if we're sending the probe requests at OFDM bit
    437 		 * rates we don't want to advertise support for 802.11b rates.
    438 		 */
    439 		if (L_WARN_ON(!(supported = wiphy_get_supported_rates(sc->wiphy,
    440 							BAND_FREQ_2_4_GHZ,
    441 							&num_supported))))
    442 			goto done;
    443 
    444 		scan_rates = l_malloc(num_supported);
    445 
    446 		for (count = 0, i = 0; i < num_supported; i++)
    447 			if (!memchr(b_rates, supported[i],
    448 						L_ARRAY_SIZE(b_rates)))
    449 				scan_rates[count++] = supported[i];
    450 
    451 		if (L_WARN_ON(!count)) {
    452 			l_free(scan_rates);
    453 			goto done;
    454 		}
    455 
    456 		l_genl_msg_enter_nested(msg, NL80211_ATTR_SCAN_SUPP_RATES);
    457 		l_genl_msg_append_attr(msg, NL80211_BAND_2GHZ,
    458 							count, scan_rates);
    459 		l_genl_msg_leave_nested(msg);
    460 		l_free(scan_rates);
    461 	}
    462 
    463 	if (wiphy_has_ext_feature(sc->wiphy,
    464 					NL80211_EXT_FEATURE_SET_SCAN_DWELL)) {
    465 		if (params->duration)
    466 			l_genl_msg_append_attr(msg,
    467 					NL80211_ATTR_MEASUREMENT_DURATION,
    468 					2, &params->duration);
    469 
    470 		if (params->duration_mandatory)
    471 			l_genl_msg_append_attr(msg,
    472 				NL80211_ATTR_MEASUREMENT_DURATION_MANDATORY,
    473 				0, NULL);
    474 	}
    475 
    476 done:
    477 	return msg;
    478 }
    479 
    480 struct l_genl_msg *scan_build_trigger_scan_bss(uint32_t ifindex,
    481 						struct wiphy *wiphy,
    482 						uint32_t frequency,
    483 						const uint8_t *ssid,
    484 						uint32_t ssid_len)
    485 {
    486 	struct l_genl_msg *msg = l_genl_msg_new(NL80211_CMD_TRIGGER_SCAN);
    487 	uint32_t flags = 0;
    488 
    489 	l_genl_msg_append_attr(msg, NL80211_ATTR_IFINDEX, 4, &ifindex);
    490 
    491 	l_genl_msg_enter_nested(msg, NL80211_ATTR_SCAN_FREQUENCIES);
    492 	l_genl_msg_append_attr(msg, 0, 4, &frequency);
    493 	l_genl_msg_leave_nested(msg);
    494 
    495 	if (wiphy_has_ext_feature(wiphy, NL80211_EXT_FEATURE_SCAN_RANDOM_SN))
    496 		flags |= NL80211_SCAN_FLAG_RANDOM_SN;
    497 
    498 	if (flags)
    499 		l_genl_msg_append_attr(msg, NL80211_ATTR_SCAN_FLAGS, 4, &flags);
    500 
    501 	/* direct probe request scan */
    502 	l_genl_msg_enter_nested(msg, NL80211_ATTR_SCAN_SSIDS);
    503 	l_genl_msg_append_attr(msg, 0, ssid_len, ssid);
    504 	l_genl_msg_leave_nested(msg);
    505 
    506 	return msg;
    507 }
    508 
    509 struct scan_cmds_add_data {
    510 	struct scan_context *sc;
    511 	const struct scan_parameters *params;
    512 	struct l_queue *cmds;
    513 	struct l_genl_msg **cmd;
    514 	uint8_t max_ssids_per_scan;
    515 	uint8_t num_ssids_can_append;
    516 };
    517 
    518 static bool scan_cmds_add_hidden(const struct network_info *network,
    519 					void *user_data)
    520 {
    521 	struct scan_cmds_add_data *data = user_data;
    522 
    523 	if (!network->config.is_hidden)
    524 		return true;
    525 
    526 	l_genl_msg_append_attr(*data->cmd, NL80211_ATTR_SSID,
    527 				strlen(network->ssid), network->ssid);
    528 	data->num_ssids_can_append--;
    529 
    530 	if (!data->num_ssids_can_append) {
    531 		l_genl_msg_leave_nested(*data->cmd);
    532 		l_queue_push_tail(data->cmds, *data->cmd);
    533 
    534 		data->num_ssids_can_append = data->max_ssids_per_scan;
    535 
    536 		/*
    537 		 * Create a consecutive scan trigger in the batch of scans.
    538 		 * The 'flush' flag is ignored, this allows to get the results
    539 		 * of all scans in the batch after the last scan is finished.
    540 		 */
    541 		*data->cmd = scan_build_cmd(data->sc, true, false,
    542 							data->params,
    543 							data->params->freqs);
    544 		l_genl_msg_enter_nested(*data->cmd, NL80211_ATTR_SCAN_SSIDS);
    545 	}
    546 
    547 	return true;
    548 }
    549 
    550 static void scan_build_next_cmd(struct l_queue *cmds, struct scan_context *sc,
    551 				bool passive,
    552 				const struct scan_parameters *params,
    553 				const struct scan_freq_set *freqs)
    554 {
    555 	struct l_genl_msg *cmd;
    556 	struct scan_cmds_add_data data = {
    557 		sc,
    558 		params,
    559 		cmds,
    560 		&cmd,
    561 		wiphy_get_max_num_ssids_per_scan(sc->wiphy),
    562 	};
    563 
    564 	cmd = scan_build_cmd(sc, false, passive, params, freqs);
    565 
    566 	if (passive) {
    567 		/* passive scan */
    568 		l_queue_push_tail(cmds, cmd);
    569 		return;
    570 	}
    571 
    572 	l_genl_msg_enter_nested(cmd, NL80211_ATTR_SCAN_SSIDS);
    573 
    574 	if (params->ssid) {
    575 		/* direct probe request scan */
    576 		l_genl_msg_append_attr(cmd, NL80211_ATTR_SSID,
    577 					params->ssid_len, params->ssid);
    578 		l_genl_msg_leave_nested(cmd);
    579 
    580 		l_queue_push_tail(cmds, cmd);
    581 		return;
    582 	}
    583 
    584 	data.num_ssids_can_append = data.max_ssids_per_scan;
    585 	known_networks_foreach(scan_cmds_add_hidden, &data);
    586 
    587 	l_genl_msg_append_attr(cmd, NL80211_ATTR_SSID, 0, NULL);
    588 	l_genl_msg_leave_nested(cmd);
    589 	l_queue_push_tail(cmds, cmd);
    590 }
    591 
    592 static void scan_cmds_add(struct scan_request *sr, struct scan_context *sc,
    593 				bool passive,
    594 				const struct scan_parameters *params)
    595 {
    596 	uint32_t bands = BAND_FREQ_2_4_GHZ | BAND_FREQ_5_GHZ | BAND_FREQ_6_GHZ;
    597 	unsigned int i;
    598 	struct scan_freq_set *subsets[2] = { 0 };
    599 	const struct scan_freq_set *supported =
    600 					wiphy_get_supported_freqs(sc->wiphy);
    601 
    602 	/*
    603 	 * No frequencies, just include the entire supported list and let the
    604 	 * kernel filter out any disabled frequencies
    605 	 */
    606 	if (!params->freqs)
    607 		sr->scan_freqs = scan_freq_set_clone(supported, bands);
    608 	else
    609 		sr->scan_freqs = scan_freq_set_clone(params->freqs, bands);
    610 
    611 	/* If 6GHz is not possible or already allowed don't split the request */
    612 	if (wiphy_band_is_disabled(sc->wiphy, BAND_FREQ_6_GHZ) != 1) {
    613 		scan_build_next_cmd(sr->cmds, sc, passive,
    614 						params, sr->scan_freqs);
    615 		return;
    616 	}
    617 
    618 	/*
    619 	 * Otherwise a full spectrum scan will likely open up the 6GHz
    620 	 * band. The problem is the regdom update occurs after an
    621 	 * individual scan request so a single request isn't going to
    622 	 * include potential 6GHz results.
    623 	 *
    624 	 * Instead we can break this full scan up into individual bands
    625 	 * and increase our chances of the regdom updating after one of
    626 	 * the earlier requests. If it does update to allow 6GHz an
    627 	 * extra 6GHz-only passive scan can be appended to this request
    628 	 * at that time.
    629 	 */
    630 	subsets[0] = scan_freq_set_clone(sr->scan_freqs, BAND_FREQ_2_4_GHZ);
    631 	subsets[1] = scan_freq_set_clone(sr->scan_freqs, BAND_FREQ_5_GHZ);
    632 
    633 	for(i = 0; i < L_ARRAY_SIZE(subsets); i++) {
    634 		if (!scan_freq_set_isempty(subsets[i]))
    635 			scan_build_next_cmd(sr->cmds, sc, passive, params,
    636 								subsets[i]);
    637 
    638 		scan_freq_set_free(subsets[i]);
    639 	}
    640 
    641 	sr->split = true;
    642 }
    643 
    644 static int scan_request_send_trigger(struct scan_context *sc,
    645 					struct scan_request *sr)
    646 {
    647 	struct l_genl_msg *cmd = l_queue_peek_head(sr->cmds);
    648 
    649 	if (!cmd)
    650 		return -ENOMSG;
    651 
    652 	sc->start_cmd_id = l_genl_family_send(nl80211, cmd,
    653 						scan_request_triggered, sc,
    654 									NULL);
    655 	if (sc->start_cmd_id) {
    656 		l_genl_msg_ref(cmd);
    657 
    658 		return 0;
    659 	}
    660 
    661 	l_error("Scan request: failed to trigger scan.");
    662 
    663 	return -EIO;
    664 }
    665 
    666 static const struct wiphy_radio_work_item_ops work_ops = {
    667 	.do_work = start_next_scan_request,
    668 	.destroy = scan_request_free,
    669 };
    670 
    671 static struct scan_request *scan_request_new(struct scan_context *sc,
    672 						bool passive,
    673 						scan_trigger_func_t trigger,
    674 						scan_notify_func_t notify,
    675 						void *userdata,
    676 						scan_destroy_func_t destroy)
    677 {
    678 	struct scan_request *sr;
    679 
    680 	sr = l_new(struct scan_request, 1);
    681 	sr->sc = sc;
    682 	sr->trigger = trigger;
    683 	sr->callback = notify;
    684 	sr->userdata = userdata;
    685 	sr->destroy = destroy;
    686 	sr->passive = passive;
    687 	sr->cmds = l_queue_new();
    688 	sr->freqs_scanned = scan_freq_set_new();
    689 
    690 	return sr;
    691 }
    692 
    693 static int insert_by_priority(const void *a, const void *b, void *user_data)
    694 {
    695 	const struct scan_request *cur = b;
    696 	int priority = L_PTR_TO_INT(user_data);
    697 
    698 	if (cur->work.priority <= priority)
    699 		return 1;
    700 
    701 	return -1;
    702 }
    703 
    704 static uint32_t scan_common(uint64_t wdev_id, bool passive,
    705 				const struct scan_parameters *params,
    706 				int priority,
    707 				scan_trigger_func_t trigger,
    708 				scan_notify_func_t notify, void *userdata,
    709 				scan_destroy_func_t destroy)
    710 {
    711 	struct scan_context *sc;
    712 	struct scan_request *sr;
    713 
    714 	sc = l_queue_find(scan_contexts, scan_context_match, &wdev_id);
    715 
    716 	if (!sc)
    717 		return 0;
    718 
    719 	sr = scan_request_new(sc, passive, trigger, notify, userdata, destroy);
    720 
    721 	scan_cmds_add(sr, sc, passive, params);
    722 
    723 	/*
    724 	 * sr->work isn't initialized yet, it will be done by
    725 	 * wiphy_radio_work_insert().  Pass the priority as user_data instead
    726 	 */
    727 	l_queue_insert(sc->requests, sr, insert_by_priority,
    728 						L_INT_TO_PTR(priority));
    729 
    730 	return wiphy_radio_work_insert(sc->wiphy, &sr->work,
    731 					priority, &work_ops);
    732 }
    733 
    734 uint32_t scan_passive(uint64_t wdev_id, const struct scan_freq_set *freqs,
    735 			scan_trigger_func_t trigger, scan_notify_func_t notify,
    736 			void *userdata, scan_destroy_func_t destroy)
    737 {
    738 	struct scan_parameters params = { .freqs = freqs };
    739 
    740 	return scan_common(wdev_id, true, &params, WIPHY_WORK_PRIORITY_SCAN,
    741 				trigger, notify, userdata, destroy);
    742 }
    743 
    744 uint32_t scan_passive_full(uint64_t wdev_id,
    745 			const struct scan_parameters *params,
    746 			scan_trigger_func_t trigger,
    747 			scan_notify_func_t notify, void *userdata,
    748 			scan_destroy_func_t destroy)
    749 {
    750 	return scan_common(wdev_id, true, params, WIPHY_WORK_PRIORITY_SCAN,
    751 				trigger, notify, userdata, destroy);
    752 }
    753 
    754 uint32_t scan_active(uint64_t wdev_id, uint8_t *extra_ie, size_t extra_ie_size,
    755 			scan_trigger_func_t trigger,
    756 			scan_notify_func_t notify, void *userdata,
    757 			scan_destroy_func_t destroy)
    758 {
    759 	struct scan_parameters params = {};
    760 
    761 	params.extra_ie = extra_ie;
    762 	params.extra_ie_size = extra_ie_size;
    763 
    764 	return scan_common(wdev_id, false, &params, WIPHY_WORK_PRIORITY_SCAN,
    765 					trigger, notify, userdata, destroy);
    766 }
    767 
    768 uint32_t scan_active_full(uint64_t wdev_id,
    769 			const struct scan_parameters *params,
    770 			scan_trigger_func_t trigger, scan_notify_func_t notify,
    771 			void *userdata, scan_destroy_func_t destroy)
    772 {
    773 	return scan_common(wdev_id, false, params, WIPHY_WORK_PRIORITY_SCAN,
    774 					trigger, notify, userdata, destroy);
    775 }
    776 
    777 static void scan_add_owe_freq(struct scan_freq_set *freqs,
    778 				const struct scan_bss *bss)
    779 {
    780 	int freq;
    781 
    782 	if (bss->owe_trans->oper_class)
    783 		freq = oci_to_frequency(bss->owe_trans->oper_class,
    784 					bss->owe_trans->channel);
    785 	else
    786 		freq = bss->frequency;
    787 
    788 	L_WARN_ON(freq < 0);
    789 
    790 	scan_freq_set_add(freqs, freq);
    791 }
    792 
    793 static void add_owe_scan_cmd(struct scan_context *sc, struct scan_request *sr,
    794 				bool ignore_flush,
    795 				struct scan_freq_set *freqs,
    796 				const struct scan_bss *bss)
    797 {
    798 	struct l_genl_msg *cmd;
    799 	struct scan_parameters params = {};
    800 	struct scan_freq_set *tmp;
    801 
    802 	if (!freqs) {
    803 		tmp = scan_freq_set_new();
    804 
    805 		scan_add_owe_freq(tmp, bss);
    806 
    807 		params.freqs = tmp;
    808 	} else
    809 		params.freqs = freqs;
    810 
    811 	params.ssid = bss->owe_trans->ssid;
    812 	params.ssid_len = bss->owe_trans->ssid_len;
    813 	params.flush = true;
    814 
    815 	cmd = scan_build_cmd(sc, ignore_flush, false, &params, params.freqs);
    816 
    817 	l_genl_msg_enter_nested(cmd, NL80211_ATTR_SCAN_SSIDS);
    818 	l_genl_msg_append_attr(cmd, 0, params.ssid_len, params.ssid);
    819 	l_genl_msg_leave_nested(cmd);
    820 
    821 	l_queue_push_tail(sr->cmds, cmd);
    822 
    823 	if (!freqs)
    824 		scan_freq_set_free(tmp);
    825 }
    826 
    827 uint32_t scan_owe_hidden(uint64_t wdev_id, struct l_queue *list,
    828 			scan_trigger_func_t trigger, scan_notify_func_t notify,
    829 			void *userdata, scan_destroy_func_t destroy)
    830 {
    831 	struct scan_context *sc;
    832 	struct scan_request *sr;
    833 	struct scan_freq_set *freqs;
    834 	const struct l_queue_entry *entry;
    835 	const uint8_t *ssid = NULL;
    836 	size_t ssid_len;
    837 	bool same_ssid = true;
    838 	struct scan_bss *bss;
    839 	bool ignore_flush = false;
    840 
    841 	sc = l_queue_find(scan_contexts, scan_context_match, &wdev_id);
    842 
    843 	if (!sc)
    844 		return 0;
    845 
    846 	sr = scan_request_new(sc, false, trigger, notify, userdata, destroy);
    847 
    848 	freqs = scan_freq_set_new();
    849 
    850 	/*
    851 	 * Start building up a frequency list if all SSIDs are the same. This
    852 	 * is hopefully the common case and will allow a single scan command.
    853 	 */
    854 	for (entry = l_queue_get_entries(list); entry; entry = entry->next) {
    855 		bss = entry->data;
    856 
    857 		scan_add_owe_freq(freqs, bss);
    858 
    859 		/* First */
    860 		if (!ssid) {
    861 			ssid = bss->owe_trans->ssid;
    862 			ssid_len = bss->owe_trans->ssid_len;
    863 			continue;
    864 		}
    865 
    866 		if (ssid_len == bss->owe_trans->ssid_len &&
    867 				!memcmp(ssid, bss->owe_trans->ssid,
    868 				bss->owe_trans->ssid_len))
    869 			continue;
    870 
    871 		same_ssid = false;
    872 		break;
    873 	}
    874 
    875 	if (same_ssid) {
    876 		bss = l_queue_peek_head(list);
    877 
    878 		add_owe_scan_cmd(sc, sr, ignore_flush, freqs, bss);
    879 
    880 		scan_freq_set_free(freqs);
    881 
    882 		goto done;
    883 	}
    884 
    885 	scan_freq_set_free(freqs);
    886 
    887 	/* SSIDs differed, use separate scan commands. */
    888 	for (entry = l_queue_get_entries(list); entry; entry = entry->next) {
    889 		bss = entry->data;
    890 
    891 		add_owe_scan_cmd(sc, sr, ignore_flush, NULL, bss);
    892 
    893 		/* Ignore flush on all subsequent commands */
    894 		if (!ignore_flush)
    895 			ignore_flush = true;
    896 	}
    897 
    898 done:
    899 	l_queue_insert(sc->requests, sr, insert_by_priority,
    900 				L_INT_TO_PTR(WIPHY_WORK_PRIORITY_SCAN));
    901 
    902 	return wiphy_radio_work_insert(sc->wiphy, &sr->work,
    903 					WIPHY_WORK_PRIORITY_SCAN, &work_ops);
    904 }
    905 
    906 bool scan_cancel(uint64_t wdev_id, uint32_t id)
    907 {
    908 	struct scan_context *sc;
    909 	struct scan_request *sr;
    910 
    911 	l_debug("Trying to cancel scan id %u for wdev %" PRIx64, id, wdev_id);
    912 
    913 	sc = l_queue_find(scan_contexts, scan_context_match, &wdev_id);
    914 	if (!sc)
    915 		return false;
    916 
    917 	sr = l_queue_find(sc->requests, scan_request_match, L_UINT_TO_PTR(id));
    918 	if (!sr)
    919 		return false;
    920 
    921 	/* We're in the callback and about to be removed, invoke destroy now */
    922 	if (sr->in_callback)
    923 		goto call_destroy;
    924 
    925 	/* If already triggered, just zero out the callback */
    926 	if (sr->triggered) {
    927 		l_debug("Scan has been triggered, wait for it to complete");
    928 
    929 		sr->callback = NULL;
    930 		goto call_destroy;
    931 	}
    932 
    933 	/*
    934 	 * Takes care of the following cases:
    935 	 * 1. If TRIGGER_SCAN is in flight
    936 	 * 2. TRIGGER_SCAN sent but bounced with -EBUSY
    937 	 * 3. Scan request is done but GET_SCAN/GET_SURVEY is still pending
    938 	 *
    939 	 * For case 3, we can easily cancel the command and proceed with the
    940 	 * other pending requests.  For case 1 & 2, the subsequent pending
    941 	 * request might bounce off with an -EBUSY.
    942 	 */
    943 	if (wiphy_radio_work_is_running(sc->wiphy, sr->work.id)) {
    944 		l_debug("Scan is already started");
    945 
    946 		/* l_genl_family_cancel will trigger destroy callbacks */
    947 		sr->canceled = true;
    948 
    949 		if (sc->start_cmd_id)
    950 			l_genl_family_cancel(nl80211, sc->start_cmd_id);
    951 
    952 		if (sc->get_survey_cmd_id)
    953 			l_genl_family_cancel(nl80211, sc->get_survey_cmd_id);
    954 
    955 		if (sc->get_scan_cmd_id)
    956 			l_genl_family_cancel(nl80211, sc->get_scan_cmd_id);
    957 
    958 		sc->start_cmd_id = 0;
    959 		sc->get_scan_cmd_id = 0;
    960 	}
    961 
    962 	l_queue_remove(sc->requests, sr);
    963 	wiphy_radio_work_done(sc->wiphy, sr->work.id);
    964 
    965 	return true;
    966 
    967 call_destroy:
    968 	if (sr->destroy) {
    969 		sr->destroy(sr->userdata);
    970 		sr->destroy = NULL;
    971 	}
    972 
    973 	return true;
    974 }
    975 
    976 static void scan_periodic_triggered(int err, void *user_data)
    977 {
    978 	struct scan_context *sc = user_data;
    979 
    980 	if (err) {
    981 		scan_periodic_rearm(sc);
    982 		return;
    983 	}
    984 
    985 	l_debug("Periodic scan triggered for wdev %" PRIx64, sc->wdev_id);
    986 
    987 	if (sc->sp.trigger)
    988 		sc->sp.trigger(0, sc->sp.userdata);
    989 }
    990 
    991 static bool scan_periodic_notify(int err, struct l_queue *bss_list,
    992 					const struct scan_freq_set *freqs,
    993 					void *user_data)
    994 {
    995 	struct scan_context *sc = user_data;
    996 
    997 	scan_periodic_rearm(sc);
    998 
    999 	if (sc->sp.callback)
   1000 		return sc->sp.callback(err, bss_list, freqs, sc->sp.userdata);
   1001 
   1002 	return false;
   1003 }
   1004 
   1005 static void scan_periodic_destroy(void *user_data)
   1006 {
   1007 	struct scan_context *sc = user_data;
   1008 
   1009 	sc->sp.id = 0;
   1010 }
   1011 
   1012 static struct scan_freq_set *scan_periodic_get_freqs(struct scan_context *sc)
   1013 {
   1014 	uint32_t band_mask = 0;
   1015 	struct scan_freq_set *freqs;
   1016 	const struct scan_freq_set *supported =
   1017 					wiphy_get_supported_freqs(sc->wiphy);
   1018 
   1019 	if (RANK_2G_FACTOR)
   1020 		band_mask |= BAND_FREQ_2_4_GHZ;
   1021 	if (RANK_5G_FACTOR)
   1022 		band_mask |= BAND_FREQ_5_GHZ;
   1023 	if (RANK_6G_FACTOR)
   1024 		band_mask |= BAND_FREQ_6_GHZ;
   1025 
   1026 	freqs = scan_freq_set_clone(supported, band_mask);
   1027 	if (scan_freq_set_isempty(freqs)) {
   1028 		scan_freq_set_free(freqs);
   1029 		freqs = NULL;
   1030 	}
   1031 
   1032 	return freqs;
   1033 }
   1034 
   1035 static bool scan_periodic_queue(struct scan_context *sc)
   1036 {
   1037 	struct scan_parameters params = {};
   1038 	struct scan_freq_set *freqs = scan_periodic_get_freqs(sc);
   1039 
   1040 	/*
   1041 	 * If this happens its due to the user disabling all bands. This will
   1042 	 * cause IWD to never issue another periodic scan so warn the user of
   1043 	 * this.
   1044 	 */
   1045 	if (L_WARN_ON(!freqs))
   1046 		return false;
   1047 
   1048 	params.freqs = freqs;
   1049 
   1050 	if (sc->sp.needs_active_scan && known_networks_has_hidden()) {
   1051 		params.randomize_mac_addr_hint = true;
   1052 
   1053 		sc->sp.needs_active_scan = false;
   1054 		sc->sp.id = scan_common(sc->wdev_id, false, &params,
   1055 					WIPHY_WORK_PRIORITY_PERIODIC_SCAN,
   1056 					scan_periodic_triggered,
   1057 					scan_periodic_notify, sc,
   1058 					scan_periodic_destroy);
   1059 	} else
   1060 		sc->sp.id = scan_common(sc->wdev_id, true, &params,
   1061 					WIPHY_WORK_PRIORITY_PERIODIC_SCAN,
   1062 					scan_periodic_triggered,
   1063 					scan_periodic_notify, sc,
   1064 					scan_periodic_destroy);
   1065 
   1066 	scan_freq_set_free(freqs);
   1067 
   1068 	return sc->sp.id != 0;
   1069 }
   1070 
   1071 static bool scan_periodic_is_disabled(void)
   1072 {
   1073 	const struct l_settings *config = iwd_get_config();
   1074 	bool disabled;
   1075 
   1076 	if (!l_settings_get_bool(config, "Scan", "DisablePeriodicScan",
   1077 								&disabled))
   1078 		return false;
   1079 
   1080 	return disabled;
   1081 }
   1082 
   1083 void scan_periodic_start(uint64_t wdev_id, scan_trigger_func_t trigger,
   1084 				scan_notify_func_t func, void *userdata)
   1085 {
   1086 	struct scan_context *sc;
   1087 
   1088 	if (scan_periodic_is_disabled())
   1089 		return;
   1090 
   1091 	sc = l_queue_find(scan_contexts, scan_context_match, &wdev_id);
   1092 
   1093 	if (!sc) {
   1094 		l_error("%s called without scan_wdev_add", __func__);
   1095 		return;
   1096 	}
   1097 
   1098 	if (sc->sp.interval)
   1099 		return;
   1100 
   1101 	l_debug("Starting periodic scan for wdev %" PRIx64, wdev_id);
   1102 
   1103 	sc->sp.interval = SCAN_INIT_INTERVAL;
   1104 	sc->sp.trigger = trigger;
   1105 	sc->sp.callback = func;
   1106 	sc->sp.userdata = userdata;
   1107 
   1108 	/* If nothing queued, start the first periodic scan */
   1109 	scan_periodic_queue(sc);
   1110 }
   1111 
   1112 bool scan_periodic_stop(uint64_t wdev_id)
   1113 {
   1114 	struct scan_context *sc;
   1115 
   1116 	sc = l_queue_find(scan_contexts, scan_context_match, &wdev_id);
   1117 
   1118 	if (!sc)
   1119 		return false;
   1120 
   1121 	if (!sc->sp.interval)
   1122 		return false;
   1123 
   1124 	l_debug("Stopping periodic scan for wdev %" PRIx64, wdev_id);
   1125 
   1126 	if (sc->sp.timeout)
   1127 		l_timeout_remove(sc->sp.timeout);
   1128 
   1129 	if (sc->sp.id) {
   1130 		scan_cancel(wdev_id, sc->sp.id);
   1131 		sc->sp.id = 0;
   1132 	}
   1133 
   1134 	sc->sp.interval = 0;
   1135 	sc->sp.trigger = NULL;
   1136 	sc->sp.callback = NULL;
   1137 	sc->sp.userdata = NULL;
   1138 	sc->sp.needs_active_scan = false;
   1139 
   1140 	return true;
   1141 }
   1142 
   1143 uint64_t scan_get_triggered_time(uint64_t wdev_id, uint32_t id)
   1144 {
   1145 	struct scan_context *sc;
   1146 	struct scan_request *sr;
   1147 
   1148 	sc = l_queue_find(scan_contexts, scan_context_match, &wdev_id);
   1149 	if (!sc)
   1150 		return 0;
   1151 
   1152 	sr = l_queue_find(sc->requests, scan_request_match, L_UINT_TO_PTR(id));
   1153 	if (!sr || !sr->triggered)
   1154 		return 0;
   1155 
   1156 	return sr->start_time_tsf;
   1157 }
   1158 
   1159 static void scan_periodic_timeout(struct l_timeout *timeout, void *user_data)
   1160 {
   1161 	struct scan_context *sc = user_data;
   1162 
   1163 	l_debug("%" PRIx64, sc->wdev_id);
   1164 
   1165 	/*
   1166 	 * Timeout triggered before periodic scan could even start, just rearm
   1167 	 * with the same interval.
   1168 	 */
   1169 	if (sc->sp.id) {
   1170 		l_debug("Periodic scan timer called before scan could start!");
   1171 		scan_periodic_rearm(sc);
   1172 		return;
   1173 	}
   1174 
   1175 	sc->sp.interval *= 2;
   1176 	if (sc->sp.interval > SCAN_MAX_INTERVAL)
   1177 		sc->sp.interval = SCAN_MAX_INTERVAL;
   1178 
   1179 	scan_periodic_queue(sc);
   1180 }
   1181 
   1182 static void scan_periodic_timeout_destroy(void *user_data)
   1183 {
   1184 	struct scan_context *sc = user_data;
   1185 
   1186 	sc->sp.timeout = NULL;
   1187 }
   1188 
   1189 static void scan_periodic_rearm(struct scan_context *sc)
   1190 {
   1191 	l_debug("Arming periodic scan timer: %u", sc->sp.interval);
   1192 
   1193 	if (sc->sp.timeout)
   1194 		l_timeout_modify(sc->sp.timeout, sc->sp.interval);
   1195 	else
   1196 		sc->sp.timeout = l_timeout_create(sc->sp.interval,
   1197 						scan_periodic_timeout, sc,
   1198 						scan_periodic_timeout_destroy);
   1199 }
   1200 
   1201 static bool start_next_scan_request(struct wiphy_radio_work_item *item)
   1202 {
   1203 	struct scan_request *sr = l_container_of(item,
   1204 						struct scan_request, work);
   1205 	struct scan_context *sc = sr->sc;
   1206 
   1207 	if (sc->state != SCAN_STATE_NOT_RUNNING)
   1208 		return false;
   1209 
   1210 	if (!scan_request_send_trigger(sc, sr))
   1211 		return false;
   1212 
   1213 	scan_request_failed(sc, sr, -EIO);
   1214 
   1215 	return true;
   1216 }
   1217 
   1218 static void scan_parse_vendor_specific(struct scan_bss *bss, const void *data,
   1219 					uint16_t len)
   1220 {
   1221 	uint16_t cost_level;
   1222 	uint16_t cost_flags;
   1223 	bool dgaf_disable;
   1224 
   1225 	if (L_WARN_ON(len < 3))
   1226 		return;
   1227 
   1228 	vendor_quirks_append_for_oui(data, &bss->vendor_quirks);
   1229 
   1230 	if (!bss->wpa && is_ie_wpa_ie(data, len)) {
   1231 		bss->wpa = l_memdup(data - 2, len + 2);
   1232 		return;
   1233 	}
   1234 
   1235 	if (!bss->osen && is_ie_wfa_ie(data, len, IE_WFA_OI_OSEN)) {
   1236 		bss->osen = l_memdup(data - 2, len + 2);
   1237 		return;
   1238 	}
   1239 
   1240 	if (is_ie_wfa_ie(data, len, IE_WFA_OI_HS20_INDICATION)) {
   1241 		if (ie_parse_hs20_indication_from_data(data - 2, len + 2,
   1242 					&bss->hs20_version, NULL, NULL,
   1243 					&dgaf_disable) < 0)
   1244 			return;
   1245 
   1246 		bss->hs20_dgaf_disable = dgaf_disable;
   1247 		bss->hs20_capable = true;
   1248 		return;
   1249 	}
   1250 
   1251 	if (is_ie_wfa_ie(data, len, IE_WFA_OI_OWE_TRANSITION)) {
   1252 		_auto_(l_free) struct ie_owe_transition_info *owe_trans =
   1253 				l_new(struct ie_owe_transition_info, 1);
   1254 
   1255 		if (ie_parse_owe_transition(data - 2, len + 2, owe_trans) < 0)
   1256 			return;
   1257 
   1258 		if (owe_trans->oper_class &&
   1259 				oci_to_frequency(owe_trans->oper_class,
   1260 						owe_trans->channel) < 0)
   1261 			return;
   1262 
   1263 		bss->owe_trans = l_steal_ptr(owe_trans);
   1264 		return;
   1265 	}
   1266 
   1267 	if (is_ie_wfa_ie(data, len, IE_WFA_OI_CONFIGURATOR_CONNECTIVITY))
   1268 		bss->dpp_configurator = true;
   1269 
   1270 	if (!ie_parse_network_cost(data, len, &cost_level, &cost_flags)) {
   1271 		bss->cost_level = cost_level;
   1272 		bss->cost_flags = cost_flags;
   1273 		return;
   1274 	}
   1275 }
   1276 
   1277 /*
   1278  * Fully parses the Advertisement Protocol Element. The only thing being looked
   1279  * for is the ANQP protocol ID, but this could be buried behind several other
   1280  * advertisement tuples so the entire IE may need to be parsed.
   1281  */
   1282 static bool scan_parse_advertisement_protocol(struct scan_bss *bss,
   1283 						const void *data, uint16_t len)
   1284 {
   1285 	const uint8_t *ptr = data;
   1286 
   1287 	while (len) {
   1288 		/*
   1289 		 * TODO: Store query info for GAS response length verification
   1290 		 */
   1291 		uint8_t id = ptr[1];
   1292 
   1293 		switch (id) {
   1294 		/*
   1295 		 * IEEE 802.11-2016 Section 11.25.3.3.1
   1296 		 *
   1297 		 * "A non-AP STA shall not transmit an ANQP request to
   1298 		 * an AP for any ANQP-element unless the ANQP
   1299 		 * Advertisement Protocol ID is included..."
   1300 		 */
   1301 		case IE_ADVERTISEMENT_ANQP:
   1302 			bss->anqp_capable = true;
   1303 			return true;
   1304 		case IE_ADVERTISEMENT_MIH_SERVICE:
   1305 		case IE_ADVERTISEMENT_MIH_DISCOVERY:
   1306 		case IE_ADVERTISEMENT_EAS:
   1307 		case IE_ADVERTISEMENT_RLQP:
   1308 			len -= 2;
   1309 			ptr += 2;
   1310 			break;
   1311 		case IE_ADVERTISEMENT_VENDOR_SPECIFIC:
   1312 			/* IEEE 802.11-2016 Section 9.4.2.26 */
   1313 			len -= ptr[3];
   1314 			ptr += ptr[3];
   1315 			break;
   1316 		default:
   1317 			return false;
   1318 		}
   1319 	}
   1320 
   1321 	return true;
   1322 }
   1323 
   1324 static bool scan_parse_bss_information_elements(struct scan_bss *bss,
   1325 					const void *data, uint16_t len)
   1326 {
   1327 	struct ie_tlv_iter iter;
   1328 	bool have_ssid = false;
   1329 
   1330 	ie_tlv_iter_init(&iter, data, len);
   1331 
   1332 	while (ie_tlv_iter_next(&iter)) {
   1333 		uint8_t tag = ie_tlv_iter_get_tag(&iter);
   1334 
   1335 		switch (tag) {
   1336 		case IE_TYPE_SSID:
   1337 			if (iter.len > SSID_MAX_SIZE)
   1338 				return false;
   1339 
   1340 			memcpy(bss->ssid, iter.data, iter.len);
   1341 			bss->ssid_len = iter.len;
   1342 			have_ssid = true;
   1343 			break;
   1344 		case IE_TYPE_RSN:
   1345 			if (!bss->rsne)
   1346 				bss->rsne = l_memdup(iter.data - 2,
   1347 								iter.len + 2);
   1348 			break;
   1349 		case IE_TYPE_RSNX:
   1350 			if (!bss->rsnxe)
   1351 				bss->rsnxe = l_memdup(iter.data - 2,
   1352 								iter.len + 2);
   1353 			break;
   1354 		case IE_TYPE_BSS_LOAD:
   1355 			if (ie_parse_bss_load(&iter, &bss->sta_count,
   1356 						&bss->utilization, NULL) < 0)
   1357 				l_warn("Unable to parse BSS Load IE for "
   1358 					MAC, MAC_STR(bss->addr));
   1359 			else
   1360 				bss->have_utilization = true;
   1361 
   1362 			break;
   1363 		case IE_TYPE_VENDOR_SPECIFIC:
   1364 			scan_parse_vendor_specific(bss, iter.data, iter.len);
   1365 			break;
   1366 		case IE_TYPE_MOBILITY_DOMAIN:
   1367 			if (!bss->mde_present && iter.len == 3) {
   1368 				memcpy(bss->mde, iter.data, iter.len);
   1369 				bss->mde_present = true;
   1370 			}
   1371 
   1372 			break;
   1373 		case IE_TYPE_RM_ENABLED_CAPABILITIES:
   1374 			if (iter.len != 5)
   1375 				break;
   1376 
   1377 			/* Only interested in Neighbor Reports */
   1378 
   1379 			bss->cap_rm_neighbor_report =
   1380 				(iter.data[0] & IE_RM_CAP_NEIGHBOR_REPORT) > 0;
   1381 			break;
   1382 		case IE_TYPE_COUNTRY:
   1383 			if (bss->cc_present || iter.len < 6)
   1384 				break;
   1385 
   1386 			bss->cc[0] = iter.data[0];
   1387 			bss->cc[1] = iter.data[1];
   1388 			bss->cc[2] = iter.data[2];
   1389 			bss->cc_present = true;
   1390 
   1391 			break;
   1392 		case IE_TYPE_HT_CAPABILITIES:
   1393 			bss->ht_capable = true;
   1394 			break;
   1395 		case IE_TYPE_VHT_CAPABILITIES:
   1396 			bss->vht_capable = true;
   1397 			break;
   1398 		case IE_TYPE_ADVERTISEMENT_PROTOCOL:
   1399 			if (iter.len < 2)
   1400 				return false;
   1401 
   1402 			scan_parse_advertisement_protocol(bss, iter.data,
   1403 								iter.len);
   1404 			break;
   1405 		case IE_TYPE_INTERWORKING:
   1406 			/*
   1407 			 * No bits indicate if venue/HESSID is included, so the
   1408 			 * length is the only way to know.
   1409 			 * (IEEE 802.11-2016 - Figure 9-439)
   1410 			 */
   1411 			if (iter.len == 9)
   1412 				memcpy(bss->hessid, iter.data + 3, 6);
   1413 			else if (iter.len == 7)
   1414 				memcpy(bss->hessid, iter.data + 1, 6);
   1415 			break;
   1416 		case IE_TYPE_ROAMING_CONSORTIUM:
   1417 			if (iter.len < 2)
   1418 				return false;
   1419 
   1420 			bss->rc_ie = l_memdup(iter.data - 2, iter.len + 2);
   1421 
   1422 			break;
   1423 
   1424 		case IE_TYPE_EXTENDED_CAPABILITIES:
   1425 			/* 802.11-2020 9.4.2.26
   1426 			 *
   1427 			 * "The length of the Extended Capabilities field is
   1428 			 * variable. If fewer bits are received in an Extended
   1429 			 * Capabilities field than shown in Table 9-153, the
   1430 			 * rest of the Extended Capabilities field bits are
   1431 			 * assumed to be zero"
   1432 			 *
   1433 			 * Currently only Proxy ARP bit (12) is checked, and if
   1434 			 * not found, this is not a fatal error.
   1435 			 */
   1436 			if (iter.len >= 2)
   1437 				bss->proxy_arp = test_bit(iter.data, 12);
   1438 
   1439 			/*
   1440 			 * 802.11-2020 Table 9-153
   1441 			 *
   1442 			 * The spec merely mentions the "exclusive" bit and
   1443 			 * doesn't enforce a requirement to check it anywhere.
   1444 			 * But if set it would indicate the AP will only accept
   1445 			 * auths when a password ID is used so store this in
   1446 			 * order to fail early if no ID is set.
   1447 			 */
   1448 			if (iter.len >= 11) {
   1449 				bss->sae_pw_id_used = test_bit(iter.data, 81);
   1450 				bss->sae_pw_id_exclusive =
   1451 							test_bit(iter.data, 82);
   1452 			}
   1453 
   1454 		}
   1455 	}
   1456 
   1457 	bss->wsc = ie_tlv_extract_wsc_payload(data, len, &bss->wsc_size);
   1458 
   1459 	switch (bss->source_frame) {
   1460 	case SCAN_BSS_PROBE_RESP:
   1461 		bss->p2p_probe_resp_info = l_new(struct p2p_probe_resp, 1);
   1462 
   1463 		if (p2p_parse_probe_resp(data, len, bss->p2p_probe_resp_info) ==
   1464 				0)
   1465 			break;
   1466 
   1467 		l_free(bss->p2p_probe_resp_info);
   1468 		bss->p2p_probe_resp_info = NULL;
   1469 		break;
   1470 	case SCAN_BSS_PROBE_REQ:
   1471 		bss->p2p_probe_req_info = l_new(struct p2p_probe_req, 1);
   1472 
   1473 		if (p2p_parse_probe_req(data, len, bss->p2p_probe_req_info) ==
   1474 				0)
   1475 			break;
   1476 
   1477 		l_free(bss->p2p_probe_req_info);
   1478 		bss->p2p_probe_req_info = NULL;
   1479 		break;
   1480 	case SCAN_BSS_BEACON:
   1481 	{
   1482 		/*
   1483 		 * Beacon and Probe Response P2P IE subelement formats are
   1484 		 * mutually incompatible and can help us distinguish one frame
   1485 		 * subtype from the other if the driver is not exposing enough
   1486 		 * information.  As a result of trusting the frame contents on
   1487 		 * this, no critical code should depend on the
   1488 		 * bss->source_frame information being right.
   1489 		 */
   1490 		struct p2p_beacon info;
   1491 		int r;
   1492 
   1493 		r = p2p_parse_beacon(data, len, &info);
   1494 		if (r == 0) {
   1495 			bss->p2p_beacon_info = l_memdup(&info, sizeof(info));
   1496 			break;
   1497 		}
   1498 
   1499 		if (r == -ENOENT)
   1500 			break;
   1501 
   1502 		bss->p2p_probe_resp_info = l_new(struct p2p_probe_resp, 1);
   1503 
   1504 		if (p2p_parse_probe_resp(data, len, bss->p2p_probe_resp_info) ==
   1505 				0) {
   1506 			bss->source_frame = SCAN_BSS_PROBE_RESP;
   1507 			break;
   1508 		}
   1509 
   1510 		l_free(bss->p2p_probe_resp_info);
   1511 		bss->p2p_probe_resp_info = NULL;
   1512 		break;
   1513 	}
   1514 	}
   1515 
   1516 	bss->wfd = ie_tlv_extract_wfd_payload(data, len, &bss->wfd_size);
   1517 
   1518 	return have_ssid;
   1519 }
   1520 
   1521 /*
   1522  * Maps 0..100 values to -10000..0
   1523  *
   1524  * This isn't really mapping to mBm since the input is unit-less and we have no
   1525  * idea what the driver itself does to come up with this 'strength' value but
   1526  * this is really the best that can be done for these drivers (its only 4 in
   1527  * tree drivers after all).
   1528  */
   1529 static int32_t signal_unspec_to_mbm(uint8_t strength)
   1530 {
   1531 	if (L_WARN_ON(strength > 100))
   1532 		return 0;
   1533 
   1534 	return ((int32_t)strength * 100) - 10000;
   1535 }
   1536 
   1537 static struct scan_bss *scan_parse_attr_bss(struct l_genl_attr *attr,
   1538 						struct wiphy *wiphy,
   1539 						uint32_t *out_seen_ms_ago)
   1540 {
   1541 	uint16_t type, len;
   1542 	const void *data;
   1543 	struct scan_bss *bss;
   1544 	const uint8_t *ies = NULL;
   1545 	size_t ies_len;
   1546 	const uint8_t *beacon_ies = NULL;
   1547 	size_t beacon_ies_len;
   1548 
   1549 	bss = l_new(struct scan_bss, 1);
   1550 	bss->source_frame = SCAN_BSS_BEACON;
   1551 
   1552 	while (l_genl_attr_next(attr, &type, &len, &data)) {
   1553 		switch (type) {
   1554 		case NL80211_BSS_BSSID:
   1555 			if (len != sizeof(bss->addr))
   1556 				goto fail;
   1557 
   1558 			memcpy(bss->addr, data, len);
   1559 			break;
   1560 		case NL80211_BSS_CAPABILITY:
   1561 			if (len != sizeof(uint16_t))
   1562 				goto fail;
   1563 
   1564 			bss->capability = *((uint16_t *) data);
   1565 			break;
   1566 		case NL80211_BSS_FREQUENCY:
   1567 			if (len != sizeof(uint32_t))
   1568 				goto fail;
   1569 
   1570 			bss->frequency = *((uint32_t *) data);
   1571 			break;
   1572 		case NL80211_BSS_SIGNAL_MBM:
   1573 			if (len != sizeof(int32_t))
   1574 				goto fail;
   1575 
   1576 			bss->signal_strength = *((int32_t *) data);
   1577 			break;
   1578 		case NL80211_BSS_SIGNAL_UNSPEC:
   1579 			if (len != 1)
   1580 				goto fail;
   1581 
   1582 			bss->signal_strength =
   1583 					signal_unspec_to_mbm(l_get_u8(data));
   1584 			break;
   1585 		case NL80211_BSS_INFORMATION_ELEMENTS:
   1586 			ies = data;
   1587 			ies_len = len;
   1588 			break;
   1589 		case NL80211_BSS_PARENT_TSF:
   1590 			if (len != sizeof(uint64_t))
   1591 				goto fail;
   1592 
   1593 			bss->parent_tsf = l_get_u64(data);
   1594 			break;
   1595 		case NL80211_BSS_PRESP_DATA:
   1596 			bss->source_frame = SCAN_BSS_PROBE_RESP;
   1597 			break;
   1598 		case NL80211_BSS_BEACON_IES:
   1599 			beacon_ies = data;
   1600 			beacon_ies_len = len;
   1601 			break;
   1602 		case NL80211_BSS_SEEN_MS_AGO:
   1603 			if (L_WARN_ON(len != sizeof(uint32_t)))
   1604 				break;
   1605 
   1606 			*out_seen_ms_ago = l_get_u32(data);
   1607 			break;
   1608 		case NL80211_BSS_LAST_SEEN_BOOTTIME:
   1609 			if (L_WARN_ON(len != sizeof(uint64_t)))
   1610 				break;
   1611 
   1612 			bss->time_stamp = l_get_u64(data) / L_NSEC_PER_USEC;
   1613 			break;
   1614 		}
   1615 	}
   1616 
   1617 	/*
   1618 	 * Try our best at deciding whether the IEs come from a Probe
   1619 	 * Response based on the hints explained in nl80211.h
   1620 	 * (enum nl80211_bss).
   1621 	 */
   1622 	if (bss->source_frame == SCAN_BSS_BEACON && ies && (
   1623 				!beacon_ies ||
   1624 				ies_len != beacon_ies_len ||
   1625 				memcmp(ies, beacon_ies, ies_len)))
   1626 		bss->source_frame = SCAN_BSS_PROBE_RESP;
   1627 
   1628 	/* Set data rate to something low, just in case estimation fails */
   1629 	bss->data_rate = 2000000;
   1630 
   1631 	if (ies) {
   1632 		int ret;
   1633 
   1634 		if (!scan_parse_bss_information_elements(bss, ies, ies_len))
   1635 			goto fail;
   1636 
   1637 		ret = wiphy_estimate_data_rate(wiphy, ies, ies_len, bss,
   1638 						&bss->data_rate);
   1639 		if (ret < 0 && ret != -ENETUNREACH)
   1640 			l_warn("wiphy_estimate_data_rate() failed");
   1641 	}
   1642 
   1643 	return bss;
   1644 
   1645 fail:
   1646 	scan_bss_free(bss);
   1647 	return NULL;
   1648 }
   1649 
   1650 static void scan_parse_attr_scan_frequencies(struct l_genl_attr *attr,
   1651 						struct scan_freq_set *set)
   1652 {
   1653 	uint16_t type, len;
   1654 	const void *data;
   1655 
   1656 	while (l_genl_attr_next(attr, &type, &len, &data)) {
   1657 		uint32_t freq;
   1658 
   1659 		if (len != sizeof(uint32_t))
   1660 			continue;
   1661 
   1662 		freq = *((uint32_t *) data);
   1663 		scan_freq_set_add(set, freq);
   1664 	}
   1665 }
   1666 
   1667 static struct scan_bss *scan_parse_result(struct l_genl_msg *msg,
   1668 						struct wiphy *wiphy,
   1669 						uint32_t *out_seen_ms_ago)
   1670 {
   1671 	struct l_genl_attr attr, nested;
   1672 	uint16_t type;
   1673 	struct scan_bss *bss = NULL;
   1674 
   1675 	if (!l_genl_attr_init(&attr, msg))
   1676 		return NULL;
   1677 
   1678 	while (l_genl_attr_next(&attr, &type, NULL, NULL)) {
   1679 		switch (type) {
   1680 		case NL80211_ATTR_BSS:
   1681 			if (!l_genl_attr_recurse(&attr, &nested))
   1682 				return NULL;
   1683 
   1684 			bss = scan_parse_attr_bss(&nested, wiphy,
   1685 							out_seen_ms_ago);
   1686 			break;
   1687 		}
   1688 	}
   1689 
   1690 	return bss;
   1691 }
   1692 
   1693 static double scan_legacy_utilization_factor(uint8_t utilization)
   1694 {
   1695 	static const double RANK_HIGH_UTILIZATION_FACTOR = 0.8;
   1696 	static const double RANK_LOW_UTILIZATION_FACTOR = 1.2;
   1697 
   1698 	if (utilization >= 192)
   1699 		return RANK_HIGH_UTILIZATION_FACTOR;
   1700 	else if (utilization <= 63)
   1701 		return RANK_LOW_UTILIZATION_FACTOR;
   1702 
   1703 	return 1.0;
   1704 }
   1705 
   1706 static double scan_get_load_factors(uint8_t utilization, uint16_t sta_count)
   1707 {
   1708 	double n;
   1709 	double factor = 1.0;
   1710 	/*
   1711 	 * The exponential decay table has 64 entries (0 <= n <= 63) which range
   1712 	 * from 1.0 to 0.28. For the utilization and station count factors we
   1713 	 * likely don't want to adjust the rank so drastically (potentially a
   1714 	 * 78% reduction in the worse case) so cap the index at 30 which equates
   1715 	 * to ~64% at the worst case.
   1716 	 */
   1717 	static const uint8_t LOAD_DECAY_OFFSET = 30;
   1718 
   1719 	if (!RANK_HIGH_UTILIZATION) {
   1720 		/*
   1721 		 * To maintain existing behavior, if the utilization factor is
   1722 		 * unset (default) fall back to the static thresholds and
   1723 		 * factor weights.
   1724 		 */
   1725 		factor = scan_legacy_utilization_factor(utilization);
   1726 		goto sta_count;
   1727 	} else if (utilization < RANK_HIGH_UTILIZATION)
   1728 		goto sta_count;
   1729 
   1730 	/* Map the utilization threshold -> 255 to rankmod_table indexes */
   1731 	if (L_WARN_ON(!util_linear_map(utilization, RANK_HIGH_UTILIZATION,
   1732 					255, 0, LOAD_DECAY_OFFSET, &n)))
   1733 		goto sta_count;
   1734 
   1735 	factor = util_exponential_decay(n);
   1736 
   1737 sta_count:
   1738 	if (!RANK_HIGH_STATION_COUNT || sta_count < RANK_HIGH_STATION_COUNT)
   1739 		return factor;
   1740 
   1741 	/*
   1742 	 * The station count is a uint16 so in theory it could be excessively
   1743 	 * large. In practice APs generally can't handle anywhere near this so
   1744 	 * put a cap at 255. If at some time in the future APs begin to handle
   1745 	 * this level of capacity we could increase this.
   1746 	 *
   1747 	 * TODO: A warning is used here to make this visible. If we see cases
   1748 	 * where this is happening we may need to give this another look.
   1749 	 */
   1750 	if (L_WARN_ON(sta_count > 255))
   1751 		sta_count = 255;
   1752 
   1753 	if (L_WARN_ON(!util_linear_map(sta_count, RANK_HIGH_STATION_COUNT,
   1754 					255, 0, LOAD_DECAY_OFFSET, &n)))
   1755 		return factor;
   1756 
   1757 	factor *= util_exponential_decay(n);
   1758 
   1759 	return factor;
   1760 }
   1761 
   1762 static void scan_bss_compute_rank(struct scan_bss *bss)
   1763 {
   1764 	static const double RANK_HIGH_SNR_FACTOR = 1.2;
   1765 	static const double RANK_LOW_SNR_FACTOR = 0.8;
   1766 	double rank;
   1767 	uint32_t irank;
   1768 	/*
   1769 	 * Maximum rate is 9607.8Mbps (HE)
   1770 	 */
   1771 	double max_rate = 9607800000;
   1772 
   1773 	rank = (double)bss->data_rate / max_rate * USHRT_MAX;
   1774 
   1775 	if (bss->frequency < 3000)
   1776 		rank *= RANK_2G_FACTOR;
   1777 
   1778 	/* Prefer 5G networks over 2.4G and 6G */
   1779 	if (bss->frequency >= 4900 && bss->frequency < 5900)
   1780 		rank *= RANK_5G_FACTOR;
   1781 
   1782 	/* Prefer 6G networks over 2.4G and 5G */
   1783 	if (bss->frequency >= 5900 && bss->frequency < 7200)
   1784 		rank *= RANK_6G_FACTOR;
   1785 
   1786 	/* Rank loaded APs lower and lightly loaded APs higher */
   1787 	if (bss->have_utilization)
   1788 		rank *= scan_get_load_factors(bss->utilization, bss->sta_count);
   1789 
   1790 	if (bss->have_snr) {
   1791 		if (bss->snr <= 15)
   1792 			rank *= RANK_LOW_SNR_FACTOR;
   1793 		else if (bss->snr >= 30)
   1794 			rank *= RANK_HIGH_SNR_FACTOR;
   1795 	}
   1796 
   1797 	irank = rank;
   1798 
   1799 	if (irank > USHRT_MAX)
   1800 		bss->rank = USHRT_MAX;
   1801 	else
   1802 		bss->rank = irank;
   1803 }
   1804 
   1805 struct scan_bss *scan_bss_new_from_probe_req(const struct mmpdu_header *mpdu,
   1806 						const uint8_t *body,
   1807 						size_t body_len,
   1808 						uint32_t frequency, int rssi)
   1809 
   1810 {
   1811 	struct scan_bss *bss;
   1812 
   1813 	bss = l_new(struct scan_bss, 1);
   1814 	memcpy(bss->addr, mpdu->address_2, 6);
   1815 	bss->source_frame = SCAN_BSS_PROBE_REQ;
   1816 	bss->frequency = frequency;
   1817 	bss->signal_strength = rssi;
   1818 
   1819 	if (!scan_parse_bss_information_elements(bss, body, body_len))
   1820 		goto fail;
   1821 
   1822 	return bss;
   1823 
   1824 fail:
   1825 	scan_bss_free(bss);
   1826 	return NULL;
   1827 }
   1828 
   1829 void scan_bss_free(struct scan_bss *bss)
   1830 {
   1831 	l_free(bss->rsne);
   1832 	l_free(bss->rsnxe);
   1833 	l_free(bss->wpa);
   1834 	l_free(bss->wsc);
   1835 	l_free(bss->osen);
   1836 	l_free(bss->rc_ie);
   1837 	l_free(bss->wfd);
   1838 	l_free(bss->owe_trans);
   1839 
   1840 	switch (bss->source_frame) {
   1841 	case SCAN_BSS_PROBE_RESP:
   1842 		if (!bss->p2p_probe_resp_info)
   1843 			break;
   1844 
   1845 		p2p_clear_probe_resp(bss->p2p_probe_resp_info);
   1846 		l_free(bss->p2p_probe_resp_info);
   1847 		break;
   1848 	case SCAN_BSS_PROBE_REQ:
   1849 		if (!bss->p2p_probe_req_info)
   1850 			break;
   1851 
   1852 		p2p_clear_probe_req(bss->p2p_probe_req_info);
   1853 		l_free(bss->p2p_probe_req_info);
   1854 		break;
   1855 	case SCAN_BSS_BEACON:
   1856 		if (!bss->p2p_beacon_info)
   1857 			break;
   1858 
   1859 		p2p_clear_beacon(bss->p2p_beacon_info);
   1860 		l_free(bss->p2p_beacon_info);
   1861 		break;
   1862 	}
   1863 
   1864 	l_free(bss);
   1865 }
   1866 
   1867 int scan_bss_get_rsn_info(const struct scan_bss *bss, struct ie_rsn_info *info)
   1868 {
   1869 	/*
   1870 	 * If both an RSN and a WPA elements are present currently
   1871 	 * RSN takes priority and the WPA IE is ignored.
   1872 	 */
   1873 	if (bss->rsne) {
   1874 		int res = ie_parse_rsne_from_data(bss->rsne, bss->rsne[1] + 2,
   1875 							info);
   1876 		if (res < 0) {
   1877 			l_debug("Cannot parse RSN field (%d, %s)",
   1878 					res, strerror(-res));
   1879 			return res;
   1880 		}
   1881 	} else if (bss->wpa) {
   1882 		int res = ie_parse_wpa_from_data(bss->wpa, bss->wpa[1] + 2,
   1883 							info);
   1884 		if (res < 0) {
   1885 			l_debug("Cannot parse WPA IE (%d, %s)",
   1886 					res, strerror(-res));
   1887 			return res;
   1888 		}
   1889 	} else if (bss->osen) {
   1890 		int res = ie_parse_osen_from_data(bss->osen, bss->osen[1] + 2,
   1891 							info);
   1892 		if (res < 0) {
   1893 			l_debug("Cannot parse OSEN IE (%d, %s)",
   1894 					res, strerror(-res));
   1895 			return res;
   1896 		}
   1897 	} else
   1898 		return -ENOENT;
   1899 
   1900 	return 0;
   1901 }
   1902 
   1903 int scan_bss_get_security(const struct scan_bss *bss, enum security *security)
   1904 {
   1905 	int ret;
   1906 	struct ie_rsn_info info;
   1907 
   1908 	ret = scan_bss_get_rsn_info(bss, &info);
   1909 	if (ret < 0) {
   1910 		if (ret != -ENOENT)
   1911 			return ret;
   1912 
   1913 		*security = security_determine(bss->capability, NULL);
   1914 	} else
   1915 		*security = security_determine(bss->capability, &info);
   1916 
   1917 	return 0;
   1918 }
   1919 
   1920 int scan_bss_rank_compare(const void *a, const void *b, void *user_data)
   1921 {
   1922 	const struct scan_bss *new_bss = a, *bss = b;
   1923 
   1924 	if (bss->rank == new_bss->rank)
   1925 		return (bss->signal_strength >
   1926 					new_bss->signal_strength) ? 1 : -1;
   1927 
   1928 	return (bss->rank > new_bss->rank) ? 1 : -1;
   1929 }
   1930 
   1931 static bool scan_survey_get_snr(struct scan_results *results,
   1932 					uint32_t freq, int32_t signal,
   1933 					int8_t *snr)
   1934 {
   1935 	uint8_t channel;
   1936 	enum band_freq band;
   1937 	int8_t noise = 0;
   1938 
   1939 	if (!results->survey_parsed)
   1940 		return false;
   1941 
   1942 	channel = band_freq_to_channel(freq, &band);
   1943 	if (L_WARN_ON(!channel))
   1944 		return false;
   1945 
   1946 	switch (band) {
   1947 	case BAND_FREQ_2_4_GHZ:
   1948 		noise = results->survey.survey_2_4[channel].noise;
   1949 		break;
   1950 	case BAND_FREQ_5_GHZ:
   1951 		noise = results->survey.survey_5[channel].noise;
   1952 		break;
   1953 	case BAND_FREQ_6_GHZ:
   1954 		noise = results->survey.survey_6[channel].noise;
   1955 		break;
   1956 	}
   1957 
   1958 	if (noise) {
   1959 		*snr = signal - noise;
   1960 		return true;
   1961 	}
   1962 
   1963 	return false;
   1964 }
   1965 
   1966 static void get_scan_callback(struct l_genl_msg *msg, void *user_data)
   1967 {
   1968 	struct scan_results *results = user_data;
   1969 	struct scan_context *sc = results->sc;
   1970 	struct scan_bss *bss;
   1971 	uint64_t wdev_id;
   1972 	uint32_t seen_ms_ago = 0;
   1973 
   1974 	if (nl80211_parse_attrs(msg, NL80211_ATTR_WDEV, &wdev_id,
   1975 					NL80211_ATTR_UNSPEC) < 0)
   1976 		return;
   1977 
   1978 	if (wdev_id != sc->wdev_id) {
   1979 		l_warn("wdev mismatch in get_scan_callback");
   1980 		return;
   1981 	}
   1982 
   1983 	bss = scan_parse_result(msg, sc->wiphy, &seen_ms_ago);
   1984 	if (!bss)
   1985 		return;
   1986 
   1987 	if (!bss->time_stamp)
   1988 		bss->time_stamp = results->time_stamp -
   1989 					seen_ms_ago * L_USEC_PER_MSEC;
   1990 
   1991 	bss->have_snr = scan_survey_get_snr(results, bss->frequency,
   1992 						bss->signal_strength / 100,
   1993 						&bss->snr);
   1994 
   1995 	scan_bss_compute_rank(bss);
   1996 	l_queue_insert(results->bss_list, bss, scan_bss_rank_compare, NULL);
   1997 }
   1998 
   1999 static void discover_hidden_network_bsses(struct scan_context *sc,
   2000 						struct l_queue *bss_list)
   2001 {
   2002 	const struct l_queue_entry *bss_entry;
   2003 
   2004 	for (bss_entry = l_queue_get_entries(bss_list); bss_entry;
   2005 						bss_entry = bss_entry->next) {
   2006 		struct scan_bss *bss = bss_entry->data;
   2007 
   2008 		if (!util_ssid_is_hidden(bss->ssid_len, bss->ssid))
   2009 			continue;
   2010 
   2011 		sc->sp.needs_active_scan = true;
   2012 	}
   2013 }
   2014 
   2015 static void scan_finished(struct scan_context *sc,
   2016 				int err, struct l_queue *bss_list,
   2017 				const struct scan_freq_set *freqs,
   2018 				struct scan_request *sr)
   2019 {
   2020 	bool new_owner = false;
   2021 	scan_notify_func_t callback = sr ? sr->callback : sc->sp.callback;
   2022 	void *userdata = sr ? sr->userdata : sc->sp.userdata;
   2023 
   2024 	if (bss_list)
   2025 		discover_hidden_network_bsses(sc, bss_list);
   2026 
   2027 	if (sr)
   2028 		sr->in_callback = true;
   2029 
   2030 	if (callback)
   2031 		new_owner = callback(err, bss_list, freqs, userdata);
   2032 
   2033 	if (bss_list && !new_owner)
   2034 		l_queue_destroy(bss_list,
   2035 				(l_queue_destroy_func_t) scan_bss_free);
   2036 
   2037 	if (!sr)
   2038 		return;
   2039 
   2040 	/*
   2041 	 * Can start a new scan now that we've removed this one from the
   2042 	 * queue.  If this were an external scan request (sr NULL) then the
   2043 	 * SCAN_FINISHED or SCAN_ABORTED handler would have taken care of
   2044 	 * sending the next command for a new or ongoing scan.
   2045 	 */
   2046 	sr->in_callback = false;
   2047 	l_queue_remove(sc->requests, sr);
   2048 	wiphy_radio_work_done(sc->wiphy, sr->work.id);
   2049 }
   2050 
   2051 static void get_scan_done(void *user)
   2052 {
   2053 	struct scan_results *results = user;
   2054 	struct scan_context *sc = results->sc;
   2055 
   2056 	sc->get_scan_cmd_id = 0;
   2057 
   2058 	if (!results->sr || !results->sr->canceled)
   2059 		scan_finished(sc, 0, results->bss_list,
   2060 						results->freqs, results->sr);
   2061 	else
   2062 		l_queue_destroy(results->bss_list,
   2063 				(l_queue_destroy_func_t) scan_bss_free);
   2064 
   2065 	if (!results->sr)
   2066 		scan_freq_set_free(results->freqs);
   2067 
   2068 	l_free(results);
   2069 }
   2070 
   2071 static void get_survey_callback(struct l_genl_msg *msg, void *user_data)
   2072 {
   2073 	struct scan_results *results = user_data;
   2074 	struct scan_survey_results *survey = &results->survey;
   2075 	struct l_genl_attr attr;
   2076 	uint32_t freq;
   2077 	int8_t noise;
   2078 	uint8_t channel;
   2079 	enum band_freq band;
   2080 
   2081 	if (nl80211_parse_attrs(msg, NL80211_ATTR_SURVEY_INFO, &attr,
   2082 				NL80211_ATTR_UNSPEC) < 0)
   2083 		return;
   2084 
   2085 	if (nl80211_parse_nested(&attr, NL80211_ATTR_SURVEY_INFO,
   2086 					NL80211_SURVEY_INFO_FREQUENCY, &freq,
   2087 					NL80211_SURVEY_INFO_NOISE, &noise,
   2088 					NL80211_ATTR_UNSPEC) < 0)
   2089 		return;
   2090 
   2091 	channel = band_freq_to_channel(freq, &band);
   2092 	if (!channel)
   2093 		return;
   2094 
   2095 	/* At least one frequency was surveyed */
   2096 	results->survey_parsed = true;
   2097 
   2098 	switch (band) {
   2099 	case BAND_FREQ_2_4_GHZ:
   2100 		survey->survey_2_4[channel].noise = noise;
   2101 		break;
   2102 	case BAND_FREQ_5_GHZ:
   2103 		survey->survey_5[channel].noise = noise;
   2104 		break;
   2105 	case BAND_FREQ_6_GHZ:
   2106 		survey->survey_6[channel].noise = noise;
   2107 		break;
   2108 	}
   2109 }
   2110 
   2111 static void get_results(struct scan_results *results)
   2112 {
   2113 	struct l_genl_msg *scan_msg;
   2114 
   2115 	scan_msg = l_genl_msg_new_sized(NL80211_CMD_GET_SCAN, 8);
   2116 
   2117 	l_genl_msg_append_attr(scan_msg, NL80211_ATTR_WDEV, 8,
   2118 					&results->sc->wdev_id);
   2119 	results->sc->get_scan_cmd_id = l_genl_family_dump(nl80211, scan_msg,
   2120 						get_scan_callback,
   2121 						results, get_scan_done);
   2122 }
   2123 
   2124 static void get_survey_done(void *user_data)
   2125 {
   2126 	struct scan_results *results = user_data;
   2127 	struct scan_context *sc = results->sc;
   2128 
   2129 	sc->get_survey_cmd_id = 0;
   2130 
   2131 	if (!results->sr->canceled)
   2132 		get_results(results);
   2133 	else
   2134 		get_scan_done(user_data);
   2135 }
   2136 
   2137 static bool scan_survey(struct scan_results *results)
   2138 {
   2139 	struct scan_context *sc = results->sc;
   2140 	struct l_genl_msg *survey_msg;
   2141 
   2142 	survey_msg = l_genl_msg_new(NL80211_CMD_GET_SURVEY);
   2143 	l_genl_msg_append_attr(survey_msg, NL80211_ATTR_WDEV, 8,
   2144 				&sc->wdev_id);
   2145 	sc->get_survey_cmd_id = l_genl_family_dump(nl80211, survey_msg,
   2146 						get_survey_callback, results,
   2147 						get_survey_done);
   2148 
   2149 	return sc->get_survey_cmd_id != 0;
   2150 }
   2151 
   2152 static void scan_get_results(struct scan_context *sc, struct scan_request *sr,
   2153 				struct scan_freq_set *freqs)
   2154 {
   2155 	struct scan_results *results;
   2156 
   2157 	results = l_new(struct scan_results, 1);
   2158 	results->sc = sc;
   2159 	results->time_stamp = l_time_now();
   2160 	results->sr = sr;
   2161 	results->bss_list = l_queue_new();
   2162 	results->freqs = freqs;
   2163 
   2164 	/* If there is no scan request (external scan), just get the results */
   2165 	if (sr && scan_survey(results))
   2166 		return;
   2167 	else if (sr)
   2168 		l_warn("failed to start a scan survey");
   2169 
   2170 	get_results(results);
   2171 }
   2172 
   2173 static void scan_wiphy_watch(struct wiphy *wiphy,
   2174 				enum wiphy_state_watch_event event,
   2175 				void *user_data)
   2176 {
   2177 	struct scan_context *sc = user_data;
   2178 	struct scan_request *sr = NULL;
   2179 	struct l_genl_msg *msg = NULL;
   2180 	struct scan_parameters params = { 0 };
   2181 	_auto_(scan_freq_set_free) struct scan_freq_set *freqs_6ghz = NULL;
   2182 	int disabled;
   2183 
   2184 	/* Only care about completed regulatory dumps */
   2185 	if (event != WIPHY_STATE_WATCH_EVENT_REGDOM_DONE)
   2186 		return;
   2187 
   2188 	if (!sc->sp.id)
   2189 		return;
   2190 
   2191 	sr = l_queue_find(sc->requests, scan_request_match,
   2192 						L_UINT_TO_PTR(sc->sp.id));
   2193 	if (!sr)
   2194 		return;
   2195 
   2196 	/*
   2197 	 * If the regdom update finished with GET_SCAN/GET_SURVEY in flight
   2198 	 * don't try and get the results again and allow those calls to finish.
   2199 	 * For the non-6ghz case this has no downside as the results should not
   2200 	 * differ.
   2201 	 *
   2202 	 * If 6ghz was enabled by this regdom update there is still not much we
   2203 	 * can do since the scan itself is already completed. Appending to the
   2204 	 * command list won't do anything.
   2205 	 *
   2206 	 * TODO: Handle the 6ghz case by checking for this case in get_scan_done
   2207 	 *       and continuing to iterate the sr->cmds array.
   2208 	 */
   2209 	if (sc->get_scan_cmd_id || sc->get_survey_cmd_id)
   2210 		return;
   2211 
   2212 	/*
   2213 	 * This update did not allow 6GHz, or the original request was
   2214 	 * not expecting 6GHz. The periodic scan should now be ended.
   2215 	 */
   2216 	disabled = wiphy_band_is_disabled(wiphy, BAND_FREQ_6_GHZ);
   2217 	if (scan_freq_set_get_bands(sr->freqs_scanned) & BAND_FREQ_6_GHZ ||
   2218 			disabled == 1 || !sr->split) {
   2219 		scan_get_results(sc, sr, sr->freqs_scanned);
   2220 		return;
   2221 	}
   2222 
   2223 	freqs_6ghz = scan_freq_set_clone(sr->scan_freqs, BAND_FREQ_6_GHZ);
   2224 
   2225 	/*
   2226 	 * At this point we know there is an ongoing periodic scan.
   2227 	 * Create a new 6GHz passive scan request and append to the
   2228 	 * command list
   2229 	 */
   2230 	msg = scan_build_cmd(sc, false, true, &params, freqs_6ghz);
   2231 	l_queue_push_tail(sr->cmds, msg);
   2232 
   2233 	/*
   2234 	 * If this periodic scan is at the top of the queue, continue
   2235 	 * running it.
   2236 	 */
   2237 	if (l_queue_peek_head(sc->requests) == sr)
   2238 		start_next_scan_request(&sr->work);
   2239 }
   2240 
   2241 static struct scan_context *scan_context_new(uint64_t wdev_id)
   2242 {
   2243 	struct wiphy *wiphy = wiphy_find_by_wdev(wdev_id);
   2244 	struct scan_context *sc;
   2245 
   2246 	if (!wiphy)
   2247 		return NULL;
   2248 
   2249 	sc = l_new(struct scan_context, 1);
   2250 
   2251 	sc->wdev_id = wdev_id;
   2252 	sc->wiphy = wiphy;
   2253 	sc->state = SCAN_STATE_NOT_RUNNING;
   2254 	sc->requests = l_queue_new();
   2255 	sc->wiphy_watch_id = wiphy_state_watch_add(wiphy, scan_wiphy_watch,
   2256 							sc, NULL);
   2257 
   2258 	return sc;
   2259 }
   2260 
   2261 static bool scan_parse_flush_flag_from_msg(struct l_genl_msg *msg)
   2262 {
   2263 	uint32_t flags;
   2264 
   2265 	if (nl80211_parse_attrs(msg, NL80211_ATTR_SCAN_FLAGS, &flags,
   2266 					NL80211_ATTR_UNSPEC) < 0)
   2267 		return false;
   2268 
   2269 	if (flags & NL80211_SCAN_FLAG_FLUSH)
   2270 		return true;
   2271 
   2272 	return false;
   2273 }
   2274 
   2275 static void scan_parse_result_frequencies(struct l_genl_msg *msg,
   2276 					struct scan_freq_set *freqs)
   2277 {
   2278 	struct l_genl_attr attr, nested;
   2279 	uint16_t type, len;
   2280 	const void *data;
   2281 
   2282 	if (!l_genl_attr_init(&attr, msg))
   2283 		return;
   2284 
   2285 	while (l_genl_attr_next(&attr, &type, &len, &data)) {
   2286 		switch (type) {
   2287 		case NL80211_ATTR_SCAN_FREQUENCIES:
   2288 			if (!l_genl_attr_recurse(&attr, &nested)) {
   2289 				l_warn("Failed to parse ATTR_SCAN_FREQUENCIES");
   2290 				break;
   2291 			}
   2292 
   2293 			scan_parse_attr_scan_frequencies(&nested, freqs);
   2294 			break;
   2295 		}
   2296 	}
   2297 }
   2298 
   2299 static void scan_retry_pending(uint32_t wiphy_id)
   2300 {
   2301 	const struct l_queue_entry *entry;
   2302 
   2303 	l_debug("");
   2304 
   2305 	for (entry = l_queue_get_entries(scan_contexts); entry;
   2306 						entry = entry->next) {
   2307 		struct scan_context *sc = entry->data;
   2308 		struct scan_request *sr = l_queue_peek_head(sc->requests);
   2309 
   2310 		if (wiphy_get_id(sc->wiphy) != wiphy_id)
   2311 			continue;
   2312 
   2313 		if (!sr)
   2314 			continue;
   2315 
   2316 		if (!wiphy_radio_work_is_running(sc->wiphy, sr->work.id))
   2317 			continue;
   2318 
   2319 		sc->state = SCAN_STATE_NOT_RUNNING;
   2320 		start_next_scan_request(&sr->work);
   2321 
   2322 		return;
   2323 	}
   2324 }
   2325 
   2326 static void scan_notify(struct l_genl_msg *msg, void *user_data)
   2327 {
   2328 	struct l_genl_attr attr;
   2329 	uint16_t type, len;
   2330 	const void *data;
   2331 	uint8_t cmd;
   2332 	uint64_t wdev_id;
   2333 	uint32_t wiphy_id;
   2334 	struct scan_context *sc;
   2335 	bool active_scan = false;
   2336 	uint64_t start_time_tsf = 0;
   2337 	struct scan_request *sr;
   2338 
   2339 	cmd = l_genl_msg_get_command(msg);
   2340 
   2341 	if (nl80211_parse_attrs(msg, NL80211_ATTR_WDEV, &wdev_id,
   2342 					NL80211_ATTR_WIPHY, &wiphy_id,
   2343 					NL80211_ATTR_UNSPEC) < 0)
   2344 		return;
   2345 
   2346 	sc = l_queue_find(scan_contexts, scan_context_match, &wdev_id);
   2347 	if (!sc) {
   2348 		/*
   2349 		 * If the event is for an unmanaged device, retry pending scan
   2350 		 * requests on the same wiphy.
   2351 		 */
   2352 		if (cmd == NL80211_CMD_NEW_SCAN_RESULTS ||
   2353 		    cmd == NL80211_CMD_SCAN_ABORTED)
   2354 			scan_retry_pending(wiphy_id);
   2355 
   2356 		return;
   2357 	}
   2358 
   2359 	l_debug("Scan notification %s(%u)", nl80211cmd_to_string(cmd), cmd);
   2360 
   2361 	if (!l_genl_attr_init(&attr, msg))
   2362 		return;
   2363 
   2364 	while (l_genl_attr_next(&attr, &type, &len, &data)) {
   2365 		switch (type) {
   2366 		case NL80211_ATTR_SCAN_SSIDS:
   2367 			active_scan = true;
   2368 			break;
   2369 		case NL80211_ATTR_SCAN_START_TIME_TSF:
   2370 			if (len != sizeof(uint64_t))
   2371 				return;
   2372 
   2373 			start_time_tsf = l_get_u64(data);
   2374 			break;
   2375 		}
   2376 	}
   2377 
   2378 	sr = l_queue_peek_head(sc->requests);
   2379 
   2380 	switch (cmd) {
   2381 	case NL80211_CMD_NEW_SCAN_RESULTS:
   2382 	{
   2383 		struct scan_freq_set *freqs;
   2384 		bool send_next = false;
   2385 		bool retry = false;
   2386 		bool get_results = false;
   2387 
   2388 		sc->state = SCAN_STATE_NOT_RUNNING;
   2389 
   2390 		/* Was this our own scan or an external scan */
   2391 		if (sr && sr->triggered) {
   2392 			sr->triggered = false;
   2393 
   2394 			if (!sr->callback) {
   2395 				scan_finished(sc, -ECANCELED, NULL, NULL, sr);
   2396 				break;
   2397 			}
   2398 
   2399 			/* Regdom changed during a periodic scan */
   2400 			if (sc->sp.id == sr->work.id &&
   2401 					wiphy_regdom_is_updating(sc->wiphy)) {
   2402 				scan_parse_result_frequencies(msg,
   2403 							sr->freqs_scanned);
   2404 				return;
   2405 			}
   2406 
   2407 			/*
   2408 			 * If this was the last command for the current request
   2409 			 * avoid starting the next request until the GET_SCAN
   2410 			 * dump callback so that any current request is always
   2411 			 * at the top of the queue and handling is simpler.
   2412 			 */
   2413 			if (l_queue_isempty(sr->cmds))
   2414 				get_results = true;
   2415 			else {
   2416 				scan_parse_result_frequencies(msg,
   2417 							sr->freqs_scanned);
   2418 				send_next = true;
   2419 			}
   2420 		} else {
   2421 			if (sc->get_scan_cmd_id)
   2422 				break;
   2423 
   2424 			if (sc->sp.callback)
   2425 				get_results = true;
   2426 
   2427 			/*
   2428 			 * Drop the ongoing scan if an external scan flushed
   2429 			 * our results.  Otherwise, try to retry the trigger
   2430 			 * request if it failed with an -EBUSY.
   2431 			 */
   2432 			if (sr && sr->started &&
   2433 					scan_parse_flush_flag_from_msg(msg))
   2434 				scan_finished(sc, -EAGAIN, NULL, NULL, sr);
   2435 			else
   2436 				retry = true;
   2437 
   2438 			sr = NULL;
   2439 		}
   2440 
   2441 		/*
   2442 		 * Send the next command of an ongoing request, or continue
   2443 		 * with a previously busy scan attempt due to an external
   2444 		 * scan.
   2445 		 */
   2446 		if (send_next || retry) {
   2447 			struct scan_request *next = l_queue_peek_head(
   2448 								sc->requests);
   2449 
   2450 			if (next && wiphy_radio_work_is_running(sc->wiphy,
   2451 								next->work.id))
   2452 				start_next_scan_request(&next->work);
   2453 		}
   2454 
   2455 		if (!get_results)
   2456 			break;
   2457 
   2458 		/*
   2459 		 * In case this was an external scan, setup a new, temporary
   2460 		 * frequency set to report the results to the periodic callback
   2461 		 */
   2462 		if (!sr)
   2463 			freqs = scan_freq_set_new();
   2464 		else
   2465 			freqs = sr->freqs_scanned;
   2466 
   2467 		scan_parse_result_frequencies(msg, freqs);
   2468 
   2469 		scan_get_results(sc, sr, freqs);
   2470 
   2471 		break;
   2472 	}
   2473 
   2474 	case NL80211_CMD_TRIGGER_SCAN:
   2475 		if (active_scan)
   2476 			sc->state = SCAN_STATE_ACTIVE;
   2477 		else
   2478 			sc->state = SCAN_STATE_PASSIVE;
   2479 
   2480 		if (sr)
   2481 			sr->start_time_tsf = start_time_tsf;
   2482 
   2483 		break;
   2484 
   2485 	case NL80211_CMD_SCAN_ABORTED:
   2486 		sc->state = SCAN_STATE_NOT_RUNNING;
   2487 
   2488 		/*
   2489 		 * If there's nothing pending, then most likely an external
   2490 		 * scan got aborted.  We don't care, ignore.
   2491 		 */
   2492 		if (!sr)
   2493 			break;
   2494 
   2495 		if (sr->triggered) {
   2496 			sr->triggered = false;
   2497 			scan_finished(sc, -ECANCELED, NULL, NULL, sr);
   2498 		} else if (wiphy_radio_work_is_running(sc->wiphy,
   2499 							sr->work.id)) {
   2500 			/*
   2501 			 * If this was an external scan that got aborted
   2502 			 * we may be able to now queue our own scan although
   2503 			 * the abort could also have been triggered by the
   2504 			 * hardware or the driver because of another activity
   2505 			 * starting in which case we should just get an EBUSY.
   2506 			 */
   2507 			start_next_scan_request(&sr->work);
   2508 		}
   2509 
   2510 		break;
   2511 	}
   2512 }
   2513 
   2514 static void get_fw_scan_done(void *userdata)
   2515 {
   2516 	struct scan_results *results = userdata;
   2517 	struct scan_request *sr = results->sr;
   2518 	struct scan_context *sc = results->sc;
   2519 	int err = l_queue_length(results->bss_list) == 0 ? -ENOENT : 0;
   2520 	bool new_owner = false;
   2521 
   2522 	sc->get_fw_scan_cmd_id = 0;
   2523 
   2524 	if (sr->callback)
   2525 		new_owner = sr->callback(err, results->bss_list, NULL,
   2526 						sr->userdata);
   2527 
   2528 	if (!new_owner)
   2529 		l_queue_destroy(results->bss_list,
   2530 				(l_queue_destroy_func_t) scan_bss_free);
   2531 
   2532 	if (sr->destroy)
   2533 		sr->destroy(sr->userdata);
   2534 
   2535 	l_free(sr);
   2536 	l_free(results);
   2537 }
   2538 
   2539 bool scan_get_firmware_scan(uint64_t wdev_id, scan_notify_func_t notify,
   2540 				void *userdata, scan_destroy_func_t destroy)
   2541 {
   2542 	struct l_genl_msg *scan_msg;
   2543 	struct scan_results *results;
   2544 	struct scan_request *sr;
   2545 	struct scan_context *sc = l_queue_find(scan_contexts,
   2546 						scan_context_match, &wdev_id);
   2547 
   2548 	if (!sc)
   2549 		return false;
   2550 
   2551 	sr = l_new(struct scan_request, 1);
   2552 	sr->callback = notify;
   2553 	sr->destroy = destroy;
   2554 	sr->userdata = userdata;
   2555 
   2556 	results = l_new(struct scan_results, 1);
   2557 	results->sc = sc;
   2558 	results->time_stamp = l_time_now();
   2559 	results->bss_list = l_queue_new();
   2560 	results->sr = sr;
   2561 
   2562 	scan_msg = l_genl_msg_new_sized(NL80211_CMD_GET_SCAN, 8);
   2563 	l_genl_msg_append_attr(scan_msg, NL80211_ATTR_WDEV, 8, &sc->wdev_id);
   2564 
   2565 	sc->get_fw_scan_cmd_id = l_genl_family_dump(nl80211, scan_msg,
   2566 							get_scan_callback,
   2567 							results,
   2568 							get_fw_scan_done);
   2569 	if (!sc->get_fw_scan_cmd_id) {
   2570 		l_queue_destroy(results->bss_list,
   2571 				(l_queue_destroy_func_t) scan_bss_free);
   2572 		l_free(results);
   2573 		l_free(sr);
   2574 		return false;
   2575 	}
   2576 
   2577 	return true;
   2578 }
   2579 
   2580 double scan_get_band_rank_modifier(enum band_freq band)
   2581 {
   2582 	const struct l_settings *config = iwd_get_config();
   2583 	double modifier;
   2584 	char *str;
   2585 
   2586 	switch (band) {
   2587 	case BAND_FREQ_2_4_GHZ:
   2588 		str = "BandModifier2_4GHz";
   2589 		break;
   2590 	case BAND_FREQ_5_GHZ:
   2591 		str = "BandModifier5GHz";
   2592 		break;
   2593 	case BAND_FREQ_6_GHZ:
   2594 		str = "BandModifier6GHz";
   2595 		break;
   2596 	default:
   2597 		l_warn("Unhandled band %u", band);
   2598 		return 0.0;
   2599 	}
   2600 
   2601 	if (!l_settings_get_double(config, "Rank", str, &modifier))
   2602 		modifier = 1.0;
   2603 
   2604 	return modifier;
   2605 }
   2606 
   2607 bool scan_wdev_add(uint64_t wdev_id)
   2608 {
   2609 	struct scan_context *sc;
   2610 
   2611 	if (l_queue_find(scan_contexts, scan_context_match, &wdev_id))
   2612 		return false;
   2613 
   2614 	sc = scan_context_new(wdev_id);
   2615 	if (!sc)
   2616 		return false;
   2617 
   2618 	l_queue_push_head(scan_contexts, sc);
   2619 
   2620 	if (l_queue_length(scan_contexts) > 1)
   2621 		goto done;
   2622 
   2623 	nl80211 = l_genl_family_new(iwd_get_genl(), NL80211_GENL_NAME);
   2624 	l_genl_family_register(nl80211, "scan", scan_notify, NULL, NULL);
   2625 
   2626 done:
   2627 	return true;
   2628 }
   2629 
   2630 bool scan_wdev_remove(uint64_t wdev_id)
   2631 {
   2632 	struct scan_context *sc;
   2633 
   2634 	sc = l_queue_remove_if(scan_contexts, scan_context_match, &wdev_id);
   2635 
   2636 	if (!sc)
   2637 		return false;
   2638 
   2639 	l_info("Removing scan context for wdev %" PRIx64, wdev_id);
   2640 	scan_context_free(sc);
   2641 
   2642 	if (l_queue_isempty(scan_contexts)) {
   2643 		l_genl_family_free(nl80211);
   2644 		nl80211 = NULL;
   2645 	}
   2646 
   2647 	return true;
   2648 }
   2649 
   2650 static int scan_init(void)
   2651 {
   2652 	const struct l_settings *config = iwd_get_config();
   2653 
   2654 	scan_contexts = l_queue_new();
   2655 
   2656 	RANK_2G_FACTOR = scan_get_band_rank_modifier(BAND_FREQ_2_4_GHZ);
   2657 	RANK_5G_FACTOR = scan_get_band_rank_modifier(BAND_FREQ_5_GHZ);
   2658 	RANK_6G_FACTOR = scan_get_band_rank_modifier(BAND_FREQ_6_GHZ);
   2659 
   2660 	if (!l_settings_get_uint(config, "Scan", "InitialPeriodicScanInterval",
   2661 					&SCAN_INIT_INTERVAL))
   2662 		SCAN_INIT_INTERVAL = 10;
   2663 
   2664 	if (SCAN_INIT_INTERVAL > UINT16_MAX)
   2665 		SCAN_INIT_INTERVAL = UINT16_MAX;
   2666 
   2667 	if (!l_settings_get_uint(config, "Scan", "MaximumPeriodicScanInterval",
   2668 					&SCAN_MAX_INTERVAL))
   2669 		SCAN_MAX_INTERVAL = 300;
   2670 
   2671 	if (SCAN_MAX_INTERVAL > UINT16_MAX)
   2672 		SCAN_MAX_INTERVAL = UINT16_MAX;
   2673 
   2674 	if (!l_settings_get_uint(config, "Rank", "HighUtilizationThreshold",
   2675 					&RANK_HIGH_UTILIZATION))
   2676 		RANK_HIGH_UTILIZATION = 0;
   2677 
   2678 	if (L_WARN_ON(RANK_HIGH_UTILIZATION > 255))
   2679 		RANK_HIGH_UTILIZATION = 255;
   2680 
   2681 	if (!l_settings_get_uint(config, "Rank", "HighStationCountThreshold",
   2682 					&RANK_HIGH_STATION_COUNT))
   2683 		RANK_HIGH_STATION_COUNT = 0;
   2684 
   2685 	if (L_WARN_ON(RANK_HIGH_STATION_COUNT > 255))
   2686 		RANK_HIGH_STATION_COUNT = 255;
   2687 
   2688 	return 0;
   2689 }
   2690 
   2691 static void scan_exit(void)
   2692 {
   2693 	l_queue_destroy(scan_contexts,
   2694 				(l_queue_destroy_func_t) scan_context_free);
   2695 	scan_contexts = NULL;
   2696 	l_genl_family_free(nl80211);
   2697 	nl80211 = NULL;
   2698 }
   2699 
   2700 IWD_MODULE(scan, scan_init, scan_exit)
   2701 IWD_MODULE_DEPENDS(scan, wiphy)