blob: f9f55285df2720e0215690afc6b0172b5e56c16a [file] [log] [blame]
Gabriel Birenf3262f92022-07-15 23:25:39 +00001/*
2 * Copyright (C) 2022 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "wifi_chip.h"
18
19#include <android-base/logging.h>
20#include <android-base/unique_fd.h>
21#include <cutils/properties.h>
22#include <fcntl.h>
23#include <net/if.h>
24#include <sys/stat.h>
25#include <sys/sysmacros.h>
26
27#include "aidl_return_util.h"
28#include "aidl_struct_util.h"
maheshkkva8aba172023-02-13 12:33:26 -080029#include "wifi_legacy_hal.h"
Gabriel Birenf3262f92022-07-15 23:25:39 +000030#include "wifi_status_util.h"
31
32#define P2P_MGMT_DEVICE_PREFIX "p2p-dev-"
33
34namespace {
35using aidl::android::hardware::wifi::IfaceType;
36using aidl::android::hardware::wifi::IWifiChip;
37using CoexRestriction = aidl::android::hardware::wifi::IWifiChip::CoexRestriction;
Shuibing Daie5fbcab2022-12-19 15:37:19 -080038using ChannelCategoryMask = aidl::android::hardware::wifi::IWifiChip::ChannelCategoryMask;
Gabriel Birenf3262f92022-07-15 23:25:39 +000039using android::base::unique_fd;
40
41constexpr char kCpioMagic[] = "070701";
42constexpr size_t kMaxBufferSizeBytes = 1024 * 1024 * 3;
43constexpr uint32_t kMaxRingBufferFileAgeSeconds = 60 * 60 * 10;
44constexpr uint32_t kMaxRingBufferFileNum = 20;
45constexpr char kTombstoneFolderPath[] = "/data/vendor/tombstones/wifi/";
46constexpr char kActiveWlanIfaceNameProperty[] = "wifi.active.interface";
47constexpr char kNoActiveWlanIfaceNamePropertyValue[] = "";
48constexpr unsigned kMaxWlanIfaces = 5;
49constexpr char kApBridgeIfacePrefix[] = "ap_br_";
50
51template <typename Iface>
52void invalidateAndClear(std::vector<std::shared_ptr<Iface>>& ifaces, std::shared_ptr<Iface> iface) {
53 iface->invalidate();
54 ifaces.erase(std::remove(ifaces.begin(), ifaces.end(), iface), ifaces.end());
55}
56
57template <typename Iface>
58void invalidateAndClearAll(std::vector<std::shared_ptr<Iface>>& ifaces) {
59 for (const auto& iface : ifaces) {
60 iface->invalidate();
61 }
62 ifaces.clear();
63}
64
65template <typename Iface>
66std::vector<std::string> getNames(std::vector<std::shared_ptr<Iface>>& ifaces) {
67 std::vector<std::string> names;
68 for (const auto& iface : ifaces) {
69 names.emplace_back(iface->getName());
70 }
71 return names;
72}
73
74template <typename Iface>
75std::shared_ptr<Iface> findUsingName(std::vector<std::shared_ptr<Iface>>& ifaces,
76 const std::string& name) {
77 std::vector<std::string> names;
78 for (const auto& iface : ifaces) {
79 if (name == iface->getName()) {
80 return iface;
81 }
82 }
83 return nullptr;
84}
85
86std::string getWlanIfaceName(unsigned idx) {
87 if (idx >= kMaxWlanIfaces) {
88 CHECK(false) << "Requested interface beyond wlan" << kMaxWlanIfaces;
89 return {};
90 }
91
92 std::array<char, PROPERTY_VALUE_MAX> buffer;
93 if (idx == 0 || idx == 1) {
94 const char* altPropName = (idx == 0) ? "wifi.interface" : "wifi.concurrent.interface";
95 auto res = property_get(altPropName, buffer.data(), nullptr);
96 if (res > 0) return buffer.data();
97 }
98 std::string propName = "wifi.interface." + std::to_string(idx);
99 auto res = property_get(propName.c_str(), buffer.data(), nullptr);
100 if (res > 0) return buffer.data();
101
102 return "wlan" + std::to_string(idx);
103}
104
105// Returns the dedicated iface name if defined.
106// Returns two ifaces in bridged mode.
107std::vector<std::string> getPredefinedApIfaceNames(bool is_bridged) {
108 std::vector<std::string> ifnames;
109 std::array<char, PROPERTY_VALUE_MAX> buffer;
110 buffer.fill(0);
111 if (property_get("ro.vendor.wifi.sap.interface", buffer.data(), nullptr) == 0) {
112 return ifnames;
113 }
114 ifnames.push_back(buffer.data());
115 if (is_bridged) {
116 buffer.fill(0);
117 if (property_get("ro.vendor.wifi.sap.concurrent.iface", buffer.data(), nullptr) == 0) {
118 return ifnames;
119 }
120 ifnames.push_back(buffer.data());
121 }
122 return ifnames;
123}
124
125std::string getPredefinedP2pIfaceName() {
126 std::array<char, PROPERTY_VALUE_MAX> primaryIfaceName;
127 char p2pParentIfname[100];
128 std::string p2pDevIfName = "";
129 std::array<char, PROPERTY_VALUE_MAX> buffer;
130 property_get("wifi.direct.interface", buffer.data(), "p2p0");
131 if (strncmp(buffer.data(), P2P_MGMT_DEVICE_PREFIX, strlen(P2P_MGMT_DEVICE_PREFIX)) == 0) {
132 /* Get the p2p parent interface name from p2p device interface name set
133 * in property */
134 strlcpy(p2pParentIfname, buffer.data() + strlen(P2P_MGMT_DEVICE_PREFIX),
135 strlen(buffer.data()) - strlen(P2P_MGMT_DEVICE_PREFIX));
136 if (property_get(kActiveWlanIfaceNameProperty, primaryIfaceName.data(), nullptr) == 0) {
137 return buffer.data();
138 }
139 /* Check if the parent interface derived from p2p device interface name
140 * is active */
141 if (strncmp(p2pParentIfname, primaryIfaceName.data(),
142 strlen(buffer.data()) - strlen(P2P_MGMT_DEVICE_PREFIX)) != 0) {
143 /*
144 * Update the predefined p2p device interface parent interface name
145 * with current active wlan interface
146 */
147 p2pDevIfName += P2P_MGMT_DEVICE_PREFIX;
148 p2pDevIfName += primaryIfaceName.data();
149 LOG(INFO) << "update the p2p device interface name to " << p2pDevIfName.c_str();
150 return p2pDevIfName;
151 }
152 }
153 return buffer.data();
154}
155
156// Returns the dedicated iface name if one is defined.
157std::string getPredefinedNanIfaceName() {
158 std::array<char, PROPERTY_VALUE_MAX> buffer;
159 if (property_get("wifi.aware.interface", buffer.data(), nullptr) == 0) {
160 return {};
161 }
162 return buffer.data();
163}
164
165void setActiveWlanIfaceNameProperty(const std::string& ifname) {
166 auto res = property_set(kActiveWlanIfaceNameProperty, ifname.data());
167 if (res != 0) {
168 PLOG(ERROR) << "Failed to set active wlan iface name property";
169 }
170}
171
172// Delete files that meet either condition:
173// 1. Older than a predefined time in the wifi tombstone dir.
174// 2. Files in excess to a predefined amount, starting from the oldest ones
175bool removeOldFilesInternal() {
176 time_t now = time(0);
177 const time_t delete_files_before = now - kMaxRingBufferFileAgeSeconds;
178 std::unique_ptr<DIR, decltype(&closedir)> dir_dump(opendir(kTombstoneFolderPath), closedir);
179 if (!dir_dump) {
180 PLOG(ERROR) << "Failed to open directory";
181 return false;
182 }
183 struct dirent* dp;
184 bool success = true;
185 std::list<std::pair<const time_t, std::string>> valid_files;
186 while ((dp = readdir(dir_dump.get()))) {
187 if (dp->d_type != DT_REG) {
188 continue;
189 }
190 std::string cur_file_name(dp->d_name);
191 struct stat cur_file_stat;
192 std::string cur_file_path = kTombstoneFolderPath + cur_file_name;
193 if (stat(cur_file_path.c_str(), &cur_file_stat) == -1) {
194 PLOG(ERROR) << "Failed to get file stat for " << cur_file_path;
195 success = false;
196 continue;
197 }
198 const time_t cur_file_time = cur_file_stat.st_mtime;
199 valid_files.push_back(std::pair<const time_t, std::string>(cur_file_time, cur_file_path));
200 }
201 valid_files.sort(); // sort the list of files by last modified time from
202 // small to big.
203 uint32_t cur_file_count = valid_files.size();
204 for (auto cur_file : valid_files) {
205 if (cur_file_count > kMaxRingBufferFileNum || cur_file.first < delete_files_before) {
206 if (unlink(cur_file.second.c_str()) != 0) {
207 PLOG(ERROR) << "Error deleting file";
208 success = false;
209 }
210 cur_file_count--;
211 } else {
212 break;
213 }
214 }
215 return success;
216}
217
218// Helper function for |cpioArchiveFilesInDir|
219bool cpioWriteHeader(int out_fd, struct stat& st, const char* file_name, size_t file_name_len) {
220 const int buf_size = 32 * 1024;
221 std::array<char, buf_size> read_buf;
222 ssize_t llen = snprintf(
223 read_buf.data(), buf_size, "%s%08X%08X%08X%08X%08X%08X%08X%08X%08X%08X%08X%08X%08X",
224 kCpioMagic, static_cast<int>(st.st_ino), st.st_mode, st.st_uid, st.st_gid,
225 static_cast<int>(st.st_nlink), static_cast<int>(st.st_mtime),
226 static_cast<int>(st.st_size), major(st.st_dev), minor(st.st_dev), major(st.st_rdev),
227 minor(st.st_rdev), static_cast<uint32_t>(file_name_len), 0);
228 if (write(out_fd, read_buf.data(), llen < buf_size ? llen : buf_size - 1) == -1) {
229 PLOG(ERROR) << "Error writing cpio header to file " << file_name;
230 return false;
231 }
232 if (write(out_fd, file_name, file_name_len) == -1) {
233 PLOG(ERROR) << "Error writing filename to file " << file_name;
234 return false;
235 }
236
237 // NUL Pad header up to 4 multiple bytes.
238 llen = (llen + file_name_len) % 4;
239 if (llen != 0) {
240 const uint32_t zero = 0;
241 if (write(out_fd, &zero, 4 - llen) == -1) {
242 PLOG(ERROR) << "Error padding 0s to file " << file_name;
243 return false;
244 }
245 }
246 return true;
247}
248
249// Helper function for |cpioArchiveFilesInDir|
250size_t cpioWriteFileContent(int fd_read, int out_fd, struct stat& st) {
251 // writing content of file
252 std::array<char, 32 * 1024> read_buf;
253 ssize_t llen = st.st_size;
254 size_t n_error = 0;
255 while (llen > 0) {
256 ssize_t bytes_read = read(fd_read, read_buf.data(), read_buf.size());
257 if (bytes_read == -1) {
258 PLOG(ERROR) << "Error reading file";
259 return ++n_error;
260 }
261 llen -= bytes_read;
262 if (write(out_fd, read_buf.data(), bytes_read) == -1) {
263 PLOG(ERROR) << "Error writing data to file";
264 return ++n_error;
265 }
266 if (bytes_read == 0) { // this should never happen, but just in case
267 // to unstuck from while loop
268 PLOG(ERROR) << "Unexpected read result";
269 n_error++;
270 break;
271 }
272 }
273 llen = st.st_size % 4;
274 if (llen != 0) {
275 const uint32_t zero = 0;
276 if (write(out_fd, &zero, 4 - llen) == -1) {
277 PLOG(ERROR) << "Error padding 0s to file";
278 return ++n_error;
279 }
280 }
281 return n_error;
282}
283
284// Helper function for |cpioArchiveFilesInDir|
285bool cpioWriteFileTrailer(int out_fd) {
286 const int buf_size = 4096;
287 std::array<char, buf_size> read_buf;
288 read_buf.fill(0);
289 ssize_t llen = snprintf(read_buf.data(), 4096, "070701%040X%056X%08XTRAILER!!!", 1, 0x0b, 0);
290 if (write(out_fd, read_buf.data(), (llen < buf_size ? llen : buf_size - 1) + 4) == -1) {
291 PLOG(ERROR) << "Error writing trailing bytes";
292 return false;
293 }
294 return true;
295}
296
297// Archives all files in |input_dir| and writes result into |out_fd|
298// Logic obtained from //external/toybox/toys/posix/cpio.c "Output cpio archive"
299// portion
300size_t cpioArchiveFilesInDir(int out_fd, const char* input_dir) {
301 struct dirent* dp;
302 size_t n_error = 0;
303 std::unique_ptr<DIR, decltype(&closedir)> dir_dump(opendir(input_dir), closedir);
304 if (!dir_dump) {
305 PLOG(ERROR) << "Failed to open directory";
306 return ++n_error;
307 }
308 while ((dp = readdir(dir_dump.get()))) {
309 if (dp->d_type != DT_REG) {
310 continue;
311 }
312 std::string cur_file_name(dp->d_name);
313 struct stat st;
314 const std::string cur_file_path = kTombstoneFolderPath + cur_file_name;
315 if (stat(cur_file_path.c_str(), &st) == -1) {
316 PLOG(ERROR) << "Failed to get file stat for " << cur_file_path;
317 n_error++;
318 continue;
319 }
320 const int fd_read = open(cur_file_path.c_str(), O_RDONLY);
321 if (fd_read == -1) {
322 PLOG(ERROR) << "Failed to open file " << cur_file_path;
323 n_error++;
324 continue;
325 }
326 std::string file_name_with_last_modified_time =
327 cur_file_name + "-" + std::to_string(st.st_mtime);
328 // string.size() does not include the null terminator. The cpio FreeBSD
329 // file header expects the null character to be included in the length.
330 const size_t file_name_len = file_name_with_last_modified_time.size() + 1;
331 unique_fd file_auto_closer(fd_read);
332 if (!cpioWriteHeader(out_fd, st, file_name_with_last_modified_time.c_str(),
333 file_name_len)) {
334 return ++n_error;
335 }
336 size_t write_error = cpioWriteFileContent(fd_read, out_fd, st);
337 if (write_error) {
338 return n_error + write_error;
339 }
340 }
341 if (!cpioWriteFileTrailer(out_fd)) {
342 return ++n_error;
343 }
344 return n_error;
345}
346
347// Helper function to create a non-const char*.
348std::vector<char> makeCharVec(const std::string& str) {
349 std::vector<char> vec(str.size() + 1);
350 vec.assign(str.begin(), str.end());
351 vec.push_back('\0');
352 return vec;
353}
354
355} // namespace
356
357namespace aidl {
358namespace android {
359namespace hardware {
360namespace wifi {
361using aidl_return_util::validateAndCall;
362using aidl_return_util::validateAndCallWithLock;
363
364WifiChip::WifiChip(int32_t chip_id, bool is_primary,
365 const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal,
366 const std::weak_ptr<mode_controller::WifiModeController> mode_controller,
367 const std::shared_ptr<iface_util::WifiIfaceUtil> iface_util,
368 const std::weak_ptr<feature_flags::WifiFeatureFlags> feature_flags,
369 const std::function<void(const std::string&)>& handler)
370 : chip_id_(chip_id),
371 legacy_hal_(legacy_hal),
372 mode_controller_(mode_controller),
373 iface_util_(iface_util),
374 is_valid_(true),
375 current_mode_id_(feature_flags::chip_mode_ids::kInvalid),
376 modes_(feature_flags.lock()->getChipModes(is_primary)),
377 debug_ring_buffer_cb_registered_(false),
378 subsystemCallbackHandler_(handler) {
379 setActiveWlanIfaceNameProperty(kNoActiveWlanIfaceNamePropertyValue);
Sunil Ravi2be1f262023-02-15 20:56:56 +0000380 using_dynamic_iface_combination_ = false;
381}
382
383void WifiChip::retrieveDynamicIfaceCombination() {
384 if (using_dynamic_iface_combination_) return;
385
386 legacy_hal::wifi_iface_concurrency_matrix legacy_matrix;
387 legacy_hal::wifi_error legacy_status;
388
389 std::tie(legacy_status, legacy_matrix) =
390 legacy_hal_.lock()->getSupportedIfaceConcurrencyMatrix();
391 if (legacy_status != legacy_hal::WIFI_SUCCESS) {
392 LOG(ERROR) << "Failed to get SupportedIfaceCombinations matrix from legacy HAL: "
393 << legacyErrorToString(legacy_status);
394 return;
395 }
396
397 IWifiChip::ChipMode aidl_chip_mode;
398 if (!aidl_struct_util::convertLegacyIfaceCombinationsMatrixToChipMode(legacy_matrix,
399 &aidl_chip_mode)) {
400 LOG(ERROR) << "Failed convertLegacyIfaceCombinationsMatrixToChipMode() ";
401 return;
402 }
403
404 LOG(INFO) << "Reloading iface concurrency combination from driver";
405 aidl_chip_mode.id = feature_flags::chip_mode_ids::kV3;
406 modes_.clear();
407 modes_.push_back(aidl_chip_mode);
408 using_dynamic_iface_combination_ = true;
Gabriel Birenf3262f92022-07-15 23:25:39 +0000409}
410
411std::shared_ptr<WifiChip> WifiChip::create(
412 int32_t chip_id, bool is_primary, const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal,
413 const std::weak_ptr<mode_controller::WifiModeController> mode_controller,
414 const std::shared_ptr<iface_util::WifiIfaceUtil> iface_util,
415 const std::weak_ptr<feature_flags::WifiFeatureFlags> feature_flags,
416 const std::function<void(const std::string&)>& handler) {
417 std::shared_ptr<WifiChip> ptr = ndk::SharedRefBase::make<WifiChip>(
418 chip_id, is_primary, legacy_hal, mode_controller, iface_util, feature_flags, handler);
419 std::weak_ptr<WifiChip> weak_ptr_this(ptr);
420 ptr->setWeakPtr(weak_ptr_this);
421 return ptr;
422}
423
424void WifiChip::invalidate() {
425 if (!writeRingbufferFilesInternal()) {
426 LOG(ERROR) << "Error writing files to flash";
427 }
428 invalidateAndRemoveAllIfaces();
429 setActiveWlanIfaceNameProperty(kNoActiveWlanIfaceNamePropertyValue);
430 legacy_hal_.reset();
431 event_cb_handler_.invalidate();
432 is_valid_ = false;
433}
434
435void WifiChip::setWeakPtr(std::weak_ptr<WifiChip> ptr) {
436 weak_ptr_this_ = ptr;
437}
438
439bool WifiChip::isValid() {
440 return is_valid_;
441}
442
443std::set<std::shared_ptr<IWifiChipEventCallback>> WifiChip::getEventCallbacks() {
444 return event_cb_handler_.getCallbacks();
445}
446
447ndk::ScopedAStatus WifiChip::getId(int32_t* _aidl_return) {
448 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID, &WifiChip::getIdInternal,
449 _aidl_return);
450}
451
452ndk::ScopedAStatus WifiChip::registerEventCallback(
453 const std::shared_ptr<IWifiChipEventCallback>& event_callback) {
454 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
455 &WifiChip::registerEventCallbackInternal, event_callback);
456}
457
Gabriel Biren2f862492023-03-09 19:13:07 +0000458ndk::ScopedAStatus WifiChip::getFeatureSet(int32_t* _aidl_return) {
Gabriel Birenf3262f92022-07-15 23:25:39 +0000459 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
Gabriel Biren2f862492023-03-09 19:13:07 +0000460 &WifiChip::getFeatureSetInternal, _aidl_return);
Gabriel Birenf3262f92022-07-15 23:25:39 +0000461}
462
463ndk::ScopedAStatus WifiChip::getAvailableModes(std::vector<IWifiChip::ChipMode>* _aidl_return) {
464 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
465 &WifiChip::getAvailableModesInternal, _aidl_return);
466}
467
468ndk::ScopedAStatus WifiChip::configureChip(int32_t in_modeId) {
469 return validateAndCallWithLock(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
470 &WifiChip::configureChipInternal, in_modeId);
471}
472
473ndk::ScopedAStatus WifiChip::getMode(int32_t* _aidl_return) {
474 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
475 &WifiChip::getModeInternal, _aidl_return);
476}
477
478ndk::ScopedAStatus WifiChip::requestChipDebugInfo(IWifiChip::ChipDebugInfo* _aidl_return) {
479 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
480 &WifiChip::requestChipDebugInfoInternal, _aidl_return);
481}
482
483ndk::ScopedAStatus WifiChip::requestDriverDebugDump(std::vector<uint8_t>* _aidl_return) {
484 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
485 &WifiChip::requestDriverDebugDumpInternal, _aidl_return);
486}
487
488ndk::ScopedAStatus WifiChip::requestFirmwareDebugDump(std::vector<uint8_t>* _aidl_return) {
489 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
490 &WifiChip::requestFirmwareDebugDumpInternal, _aidl_return);
491}
492
493ndk::ScopedAStatus WifiChip::createApIface(std::shared_ptr<IWifiApIface>* _aidl_return) {
494 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
495 &WifiChip::createApIfaceInternal, _aidl_return);
496}
497
498ndk::ScopedAStatus WifiChip::createBridgedApIface(std::shared_ptr<IWifiApIface>* _aidl_return) {
499 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
500 &WifiChip::createBridgedApIfaceInternal, _aidl_return);
501}
502
503ndk::ScopedAStatus WifiChip::getApIfaceNames(std::vector<std::string>* _aidl_return) {
504 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
505 &WifiChip::getApIfaceNamesInternal, _aidl_return);
506}
507
508ndk::ScopedAStatus WifiChip::getApIface(const std::string& in_ifname,
509 std::shared_ptr<IWifiApIface>* _aidl_return) {
510 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
511 &WifiChip::getApIfaceInternal, _aidl_return, in_ifname);
512}
513
514ndk::ScopedAStatus WifiChip::removeApIface(const std::string& in_ifname) {
515 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
516 &WifiChip::removeApIfaceInternal, in_ifname);
517}
518
519ndk::ScopedAStatus WifiChip::removeIfaceInstanceFromBridgedApIface(
520 const std::string& in_brIfaceName, const std::string& in_ifaceInstanceName) {
521 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
522 &WifiChip::removeIfaceInstanceFromBridgedApIfaceInternal, in_brIfaceName,
523 in_ifaceInstanceName);
524}
525
526ndk::ScopedAStatus WifiChip::createNanIface(std::shared_ptr<IWifiNanIface>* _aidl_return) {
527 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
528 &WifiChip::createNanIfaceInternal, _aidl_return);
529}
530
531ndk::ScopedAStatus WifiChip::getNanIfaceNames(std::vector<std::string>* _aidl_return) {
532 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
533 &WifiChip::getNanIfaceNamesInternal, _aidl_return);
534}
535
536ndk::ScopedAStatus WifiChip::getNanIface(const std::string& in_ifname,
537 std::shared_ptr<IWifiNanIface>* _aidl_return) {
538 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
539 &WifiChip::getNanIfaceInternal, _aidl_return, in_ifname);
540}
541
542ndk::ScopedAStatus WifiChip::removeNanIface(const std::string& in_ifname) {
543 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
544 &WifiChip::removeNanIfaceInternal, in_ifname);
545}
546
547ndk::ScopedAStatus WifiChip::createP2pIface(std::shared_ptr<IWifiP2pIface>* _aidl_return) {
548 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
549 &WifiChip::createP2pIfaceInternal, _aidl_return);
550}
551
552ndk::ScopedAStatus WifiChip::getP2pIfaceNames(std::vector<std::string>* _aidl_return) {
553 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
554 &WifiChip::getP2pIfaceNamesInternal, _aidl_return);
555}
556
557ndk::ScopedAStatus WifiChip::getP2pIface(const std::string& in_ifname,
558 std::shared_ptr<IWifiP2pIface>* _aidl_return) {
559 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
560 &WifiChip::getP2pIfaceInternal, _aidl_return, in_ifname);
561}
562
563ndk::ScopedAStatus WifiChip::removeP2pIface(const std::string& in_ifname) {
564 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
565 &WifiChip::removeP2pIfaceInternal, in_ifname);
566}
567
568ndk::ScopedAStatus WifiChip::createStaIface(std::shared_ptr<IWifiStaIface>* _aidl_return) {
569 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
570 &WifiChip::createStaIfaceInternal, _aidl_return);
571}
572
573ndk::ScopedAStatus WifiChip::getStaIfaceNames(std::vector<std::string>* _aidl_return) {
574 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
575 &WifiChip::getStaIfaceNamesInternal, _aidl_return);
576}
577
578ndk::ScopedAStatus WifiChip::getStaIface(const std::string& in_ifname,
579 std::shared_ptr<IWifiStaIface>* _aidl_return) {
580 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
581 &WifiChip::getStaIfaceInternal, _aidl_return, in_ifname);
582}
583
584ndk::ScopedAStatus WifiChip::removeStaIface(const std::string& in_ifname) {
585 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
586 &WifiChip::removeStaIfaceInternal, in_ifname);
587}
588
589ndk::ScopedAStatus WifiChip::createRttController(
590 const std::shared_ptr<IWifiStaIface>& in_boundIface,
591 std::shared_ptr<IWifiRttController>* _aidl_return) {
592 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
593 &WifiChip::createRttControllerInternal, _aidl_return, in_boundIface);
594}
595
596ndk::ScopedAStatus WifiChip::getDebugRingBuffersStatus(
597 std::vector<WifiDebugRingBufferStatus>* _aidl_return) {
598 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
599 &WifiChip::getDebugRingBuffersStatusInternal, _aidl_return);
600}
601
602ndk::ScopedAStatus WifiChip::startLoggingToDebugRingBuffer(
603 const std::string& in_ringName, WifiDebugRingBufferVerboseLevel in_verboseLevel,
604 int32_t in_maxIntervalInSec, int32_t in_minDataSizeInBytes) {
605 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
606 &WifiChip::startLoggingToDebugRingBufferInternal, in_ringName,
607 in_verboseLevel, in_maxIntervalInSec, in_minDataSizeInBytes);
608}
609
610ndk::ScopedAStatus WifiChip::forceDumpToDebugRingBuffer(const std::string& in_ringName) {
611 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
612 &WifiChip::forceDumpToDebugRingBufferInternal, in_ringName);
613}
614
615ndk::ScopedAStatus WifiChip::flushRingBufferToFile() {
616 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
617 &WifiChip::flushRingBufferToFileInternal);
618}
619
620ndk::ScopedAStatus WifiChip::stopLoggingToDebugRingBuffer() {
621 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
622 &WifiChip::stopLoggingToDebugRingBufferInternal);
623}
624
625ndk::ScopedAStatus WifiChip::getDebugHostWakeReasonStats(
626 WifiDebugHostWakeReasonStats* _aidl_return) {
627 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
628 &WifiChip::getDebugHostWakeReasonStatsInternal, _aidl_return);
629}
630
631ndk::ScopedAStatus WifiChip::enableDebugErrorAlerts(bool in_enable) {
632 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
633 &WifiChip::enableDebugErrorAlertsInternal, in_enable);
634}
635
636ndk::ScopedAStatus WifiChip::selectTxPowerScenario(IWifiChip::TxPowerScenario in_scenario) {
637 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
638 &WifiChip::selectTxPowerScenarioInternal, in_scenario);
639}
640
641ndk::ScopedAStatus WifiChip::resetTxPowerScenario() {
642 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
643 &WifiChip::resetTxPowerScenarioInternal);
644}
645
646ndk::ScopedAStatus WifiChip::setLatencyMode(IWifiChip::LatencyMode in_mode) {
647 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
648 &WifiChip::setLatencyModeInternal, in_mode);
649}
650
651binder_status_t WifiChip::dump(int fd, const char**, uint32_t) {
652 {
653 std::unique_lock<std::mutex> lk(lock_t);
654 for (const auto& item : ringbuffer_map_) {
655 forceDumpToDebugRingBufferInternal(item.first);
656 }
657 // unique_lock unlocked here
658 }
659 usleep(100 * 1000); // sleep for 100 milliseconds to wait for
660 // ringbuffer updates.
661 if (!writeRingbufferFilesInternal()) {
662 LOG(ERROR) << "Error writing files to flash";
663 }
664 uint32_t n_error = cpioArchiveFilesInDir(fd, kTombstoneFolderPath);
665 if (n_error != 0) {
666 LOG(ERROR) << n_error << " errors occurred in cpio function";
667 }
668 fsync(fd);
669 return STATUS_OK;
670}
671
672ndk::ScopedAStatus WifiChip::setMultiStaPrimaryConnection(const std::string& in_ifName) {
673 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
674 &WifiChip::setMultiStaPrimaryConnectionInternal, in_ifName);
675}
676
677ndk::ScopedAStatus WifiChip::setMultiStaUseCase(IWifiChip::MultiStaUseCase in_useCase) {
678 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
679 &WifiChip::setMultiStaUseCaseInternal, in_useCase);
680}
681
682ndk::ScopedAStatus WifiChip::setCoexUnsafeChannels(
683 const std::vector<IWifiChip::CoexUnsafeChannel>& in_unsafeChannels,
Gabriel Biren3b86a782023-02-04 00:42:53 +0000684 int32_t in_restrictions) {
Gabriel Birenf3262f92022-07-15 23:25:39 +0000685 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
686 &WifiChip::setCoexUnsafeChannelsInternal, in_unsafeChannels,
687 in_restrictions);
688}
689
690ndk::ScopedAStatus WifiChip::setCountryCode(const std::array<uint8_t, 2>& in_code) {
691 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
692 &WifiChip::setCountryCodeInternal, in_code);
693}
694
Gabriel Biren3b86a782023-02-04 00:42:53 +0000695ndk::ScopedAStatus WifiChip::getUsableChannels(WifiBand in_band, int32_t in_ifaceModeMask,
696 int32_t in_filterMask,
Gabriel Birenf3262f92022-07-15 23:25:39 +0000697 std::vector<WifiUsableChannel>* _aidl_return) {
698 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
699 &WifiChip::getUsableChannelsInternal, _aidl_return, in_band,
700 in_ifaceModeMask, in_filterMask);
701}
702
Oscar Shuab8313c2022-12-13 00:55:11 +0000703ndk::ScopedAStatus WifiChip::setAfcChannelAllowance(
Oscar Shu4275c872023-03-08 22:48:09 +0000704 const AfcChannelAllowance& afcChannelAllowance) {
Oscar Shuab8313c2022-12-13 00:55:11 +0000705 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
Oscar Shu4275c872023-03-08 22:48:09 +0000706 &WifiChip::setAfcChannelAllowanceInternal, afcChannelAllowance);
Oscar Shuab8313c2022-12-13 00:55:11 +0000707}
708
Gabriel Birenf3262f92022-07-15 23:25:39 +0000709ndk::ScopedAStatus WifiChip::triggerSubsystemRestart() {
710 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
711 &WifiChip::triggerSubsystemRestartInternal);
712}
713
Gabriel Biren263db452023-02-24 21:07:38 +0000714ndk::ScopedAStatus WifiChip::getSupportedRadioCombinations(
715 std::vector<WifiRadioCombination>* _aidl_return) {
Gabriel Birenf3262f92022-07-15 23:25:39 +0000716 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
Gabriel Biren263db452023-02-24 21:07:38 +0000717 &WifiChip::getSupportedRadioCombinationsInternal, _aidl_return);
Gabriel Birenf3262f92022-07-15 23:25:39 +0000718}
719
Mahesh KKVc84d3772022-12-02 16:53:28 -0800720ndk::ScopedAStatus WifiChip::getWifiChipCapabilities(WifiChipCapabilities* _aidl_return) {
721 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
722 &WifiChip::getWifiChipCapabilitiesInternal, _aidl_return);
723}
724
Gabriel Biren3b86a782023-02-04 00:42:53 +0000725ndk::ScopedAStatus WifiChip::enableStaChannelForPeerNetwork(int32_t in_channelCategoryEnableFlag) {
Shuibing Daie5fbcab2022-12-19 15:37:19 -0800726 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
727 &WifiChip::enableStaChannelForPeerNetworkInternal,
728 in_channelCategoryEnableFlag);
729}
730
maheshkkva8aba172023-02-13 12:33:26 -0800731ndk::ScopedAStatus WifiChip::setMloMode(const ChipMloMode in_mode) {
732 return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
733 &WifiChip::setMloModeInternal, in_mode);
734}
735
Gabriel Birenf3262f92022-07-15 23:25:39 +0000736void WifiChip::invalidateAndRemoveAllIfaces() {
737 invalidateAndClearBridgedApAll();
738 invalidateAndClearAll(ap_ifaces_);
739 invalidateAndClearAll(nan_ifaces_);
740 invalidateAndClearAll(p2p_ifaces_);
741 invalidateAndClearAll(sta_ifaces_);
742 // Since all the ifaces are invalid now, all RTT controller objects
743 // using those ifaces also need to be invalidated.
744 for (const auto& rtt : rtt_controllers_) {
745 rtt->invalidate();
746 }
747 rtt_controllers_.clear();
748}
749
750void WifiChip::invalidateAndRemoveDependencies(const std::string& removed_iface_name) {
751 for (auto it = nan_ifaces_.begin(); it != nan_ifaces_.end();) {
752 auto nan_iface = *it;
753 if (nan_iface->getName() == removed_iface_name) {
754 nan_iface->invalidate();
755 for (const auto& callback : event_cb_handler_.getCallbacks()) {
756 if (!callback->onIfaceRemoved(IfaceType::NAN_IFACE, removed_iface_name).isOk()) {
757 LOG(ERROR) << "Failed to invoke onIfaceRemoved callback";
758 }
759 }
760 it = nan_ifaces_.erase(it);
761 } else {
762 ++it;
763 }
764 }
765
766 for (auto it = rtt_controllers_.begin(); it != rtt_controllers_.end();) {
767 auto rtt = *it;
768 if (rtt->getIfaceName() == removed_iface_name) {
769 rtt->invalidate();
770 it = rtt_controllers_.erase(it);
771 } else {
772 ++it;
773 }
774 }
775}
776
777std::pair<int32_t, ndk::ScopedAStatus> WifiChip::getIdInternal() {
778 return {chip_id_, ndk::ScopedAStatus::ok()};
779}
780
781ndk::ScopedAStatus WifiChip::registerEventCallbackInternal(
782 const std::shared_ptr<IWifiChipEventCallback>& event_callback) {
783 if (!event_cb_handler_.addCallback(event_callback)) {
784 return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN);
785 }
786 return ndk::ScopedAStatus::ok();
787}
788
Gabriel Biren2f862492023-03-09 19:13:07 +0000789std::pair<int32_t, ndk::ScopedAStatus> WifiChip::getFeatureSetInternal() {
Gabriel Birenf3262f92022-07-15 23:25:39 +0000790 legacy_hal::wifi_error legacy_status;
791 uint64_t legacy_feature_set;
792 uint32_t legacy_logger_feature_set;
793 const auto ifname = getFirstActiveWlanIfaceName();
794 std::tie(legacy_status, legacy_feature_set) =
795 legacy_hal_.lock()->getSupportedFeatureSet(ifname);
796 if (legacy_status != legacy_hal::WIFI_SUCCESS) {
Gabriel Biren3b86a782023-02-04 00:42:53 +0000797 return {0, createWifiStatusFromLegacyError(legacy_status)};
Gabriel Birenf3262f92022-07-15 23:25:39 +0000798 }
799 std::tie(legacy_status, legacy_logger_feature_set) =
800 legacy_hal_.lock()->getLoggerSupportedFeatureSet(ifname);
801 if (legacy_status != legacy_hal::WIFI_SUCCESS) {
802 // some devices don't support querying logger feature set
803 legacy_logger_feature_set = 0;
804 }
Gabriel Biren2f862492023-03-09 19:13:07 +0000805 uint32_t aidl_feature_set;
806 if (!aidl_struct_util::convertLegacyChipFeaturesToAidl(legacy_feature_set, &aidl_feature_set)) {
Gabriel Biren3b86a782023-02-04 00:42:53 +0000807 return {0, createWifiStatus(WifiStatusCode::ERROR_UNKNOWN)};
Gabriel Birenf3262f92022-07-15 23:25:39 +0000808 }
Gabriel Biren2f862492023-03-09 19:13:07 +0000809 return {aidl_feature_set, ndk::ScopedAStatus::ok()};
Gabriel Birenf3262f92022-07-15 23:25:39 +0000810}
811
812std::pair<std::vector<IWifiChip::ChipMode>, ndk::ScopedAStatus>
813WifiChip::getAvailableModesInternal() {
814 return {modes_, ndk::ScopedAStatus::ok()};
815}
816
817ndk::ScopedAStatus WifiChip::configureChipInternal(
818 /* NONNULL */ std::unique_lock<std::recursive_mutex>* lock, int32_t mode_id) {
819 if (!isValidModeId(mode_id)) {
820 return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
821 }
822 if (mode_id == current_mode_id_) {
823 LOG(DEBUG) << "Already in the specified mode " << mode_id;
824 return ndk::ScopedAStatus::ok();
825 }
826 ndk::ScopedAStatus status = handleChipConfiguration(lock, mode_id);
827 if (!status.isOk()) {
828 WifiStatusCode errorCode = static_cast<WifiStatusCode>(status.getServiceSpecificError());
829 for (const auto& callback : event_cb_handler_.getCallbacks()) {
830 if (!callback->onChipReconfigureFailure(errorCode).isOk()) {
831 LOG(ERROR) << "Failed to invoke onChipReconfigureFailure callback";
832 }
833 }
834 return status;
835 }
836 for (const auto& callback : event_cb_handler_.getCallbacks()) {
837 if (!callback->onChipReconfigured(mode_id).isOk()) {
838 LOG(ERROR) << "Failed to invoke onChipReconfigured callback";
839 }
840 }
841 current_mode_id_ = mode_id;
842 LOG(INFO) << "Configured chip in mode " << mode_id;
843 setActiveWlanIfaceNameProperty(getFirstActiveWlanIfaceName());
844
845 legacy_hal_.lock()->registerSubsystemRestartCallbackHandler(subsystemCallbackHandler_);
846
847 return status;
848}
849
850std::pair<int32_t, ndk::ScopedAStatus> WifiChip::getModeInternal() {
851 if (!isValidModeId(current_mode_id_)) {
852 return {current_mode_id_, createWifiStatus(WifiStatusCode::ERROR_NOT_AVAILABLE)};
853 }
854 return {current_mode_id_, ndk::ScopedAStatus::ok()};
855}
856
857std::pair<IWifiChip::ChipDebugInfo, ndk::ScopedAStatus> WifiChip::requestChipDebugInfoInternal() {
858 IWifiChip::ChipDebugInfo result;
859 legacy_hal::wifi_error legacy_status;
860 std::string driver_desc;
861 const auto ifname = getFirstActiveWlanIfaceName();
862 std::tie(legacy_status, driver_desc) = legacy_hal_.lock()->getDriverVersion(ifname);
863 if (legacy_status != legacy_hal::WIFI_SUCCESS) {
864 LOG(ERROR) << "Failed to get driver version: " << legacyErrorToString(legacy_status);
865 ndk::ScopedAStatus status =
866 createWifiStatusFromLegacyError(legacy_status, "failed to get driver version");
867 return {std::move(result), std::move(status)};
868 }
869 result.driverDescription = driver_desc.c_str();
870
871 std::string firmware_desc;
872 std::tie(legacy_status, firmware_desc) = legacy_hal_.lock()->getFirmwareVersion(ifname);
873 if (legacy_status != legacy_hal::WIFI_SUCCESS) {
874 LOG(ERROR) << "Failed to get firmware version: " << legacyErrorToString(legacy_status);
875 ndk::ScopedAStatus status =
876 createWifiStatusFromLegacyError(legacy_status, "failed to get firmware version");
877 return {std::move(result), std::move(status)};
878 }
879 result.firmwareDescription = firmware_desc.c_str();
880
881 return {std::move(result), ndk::ScopedAStatus::ok()};
882}
883
884std::pair<std::vector<uint8_t>, ndk::ScopedAStatus> WifiChip::requestDriverDebugDumpInternal() {
885 legacy_hal::wifi_error legacy_status;
886 std::vector<uint8_t> driver_dump;
887 std::tie(legacy_status, driver_dump) =
888 legacy_hal_.lock()->requestDriverMemoryDump(getFirstActiveWlanIfaceName());
889 if (legacy_status != legacy_hal::WIFI_SUCCESS) {
890 LOG(ERROR) << "Failed to get driver debug dump: " << legacyErrorToString(legacy_status);
891 return {std::vector<uint8_t>(), createWifiStatusFromLegacyError(legacy_status)};
892 }
893 return {driver_dump, ndk::ScopedAStatus::ok()};
894}
895
896std::pair<std::vector<uint8_t>, ndk::ScopedAStatus> WifiChip::requestFirmwareDebugDumpInternal() {
897 legacy_hal::wifi_error legacy_status;
898 std::vector<uint8_t> firmware_dump;
899 std::tie(legacy_status, firmware_dump) =
900 legacy_hal_.lock()->requestFirmwareMemoryDump(getFirstActiveWlanIfaceName());
901 if (legacy_status != legacy_hal::WIFI_SUCCESS) {
902 LOG(ERROR) << "Failed to get firmware debug dump: " << legacyErrorToString(legacy_status);
903 return {std::vector<uint8_t>(), createWifiStatusFromLegacyError(legacy_status)};
904 }
905 return {firmware_dump, ndk::ScopedAStatus::ok()};
906}
907
908ndk::ScopedAStatus WifiChip::createVirtualApInterface(const std::string& apVirtIf) {
909 legacy_hal::wifi_error legacy_status;
910 legacy_status = legacy_hal_.lock()->createVirtualInterface(
911 apVirtIf, aidl_struct_util::convertAidlIfaceTypeToLegacy(IfaceType::AP));
912 if (legacy_status != legacy_hal::WIFI_SUCCESS) {
913 LOG(ERROR) << "Failed to add interface: " << apVirtIf << " "
914 << legacyErrorToString(legacy_status);
915 return createWifiStatusFromLegacyError(legacy_status);
916 }
917 return ndk::ScopedAStatus::ok();
918}
919
920std::shared_ptr<WifiApIface> WifiChip::newWifiApIface(std::string& ifname) {
921 std::vector<std::string> ap_instances;
922 for (auto const& it : br_ifaces_ap_instances_) {
923 if (it.first == ifname) {
924 ap_instances = it.second;
925 }
926 }
927 std::shared_ptr<WifiApIface> iface =
928 ndk::SharedRefBase::make<WifiApIface>(ifname, ap_instances, legacy_hal_, iface_util_);
929 ap_ifaces_.push_back(iface);
930 for (const auto& callback : event_cb_handler_.getCallbacks()) {
931 if (!callback->onIfaceAdded(IfaceType::AP, ifname).isOk()) {
932 LOG(ERROR) << "Failed to invoke onIfaceAdded callback";
933 }
934 }
935 setActiveWlanIfaceNameProperty(getFirstActiveWlanIfaceName());
936 return iface;
937}
938
939std::pair<std::shared_ptr<IWifiApIface>, ndk::ScopedAStatus> WifiChip::createApIfaceInternal() {
940 if (!canCurrentModeSupportConcurrencyTypeWithCurrentTypes(IfaceConcurrencyType::AP)) {
941 return {std::shared_ptr<WifiApIface>(),
942 createWifiStatus(WifiStatusCode::ERROR_NOT_AVAILABLE)};
943 }
944 std::string ifname = allocateApIfaceName();
945 ndk::ScopedAStatus status = createVirtualApInterface(ifname);
946 if (!status.isOk()) {
947 return {std::shared_ptr<WifiApIface>(), std::move(status)};
948 }
949 std::shared_ptr<WifiApIface> iface = newWifiApIface(ifname);
950 return {iface, ndk::ScopedAStatus::ok()};
951}
952
953std::pair<std::shared_ptr<IWifiApIface>, ndk::ScopedAStatus>
954WifiChip::createBridgedApIfaceInternal() {
955 if (!canCurrentModeSupportConcurrencyTypeWithCurrentTypes(IfaceConcurrencyType::AP_BRIDGED)) {
956 return {nullptr, createWifiStatus(WifiStatusCode::ERROR_NOT_AVAILABLE)};
957 }
958 std::vector<std::string> ap_instances = allocateBridgedApInstanceNames();
959 if (ap_instances.size() < 2) {
960 LOG(ERROR) << "Fail to allocate two instances";
961 return {nullptr, createWifiStatus(WifiStatusCode::ERROR_NOT_AVAILABLE)};
962 }
963 std::string br_ifname = kApBridgeIfacePrefix + ap_instances[0];
964 for (int i = 0; i < 2; i++) {
965 ndk::ScopedAStatus status = createVirtualApInterface(ap_instances[i]);
966 if (!status.isOk()) {
967 if (i != 0) { // The failure happened when creating second virtual
968 // iface.
969 legacy_hal_.lock()->deleteVirtualInterface(
970 ap_instances.front()); // Remove the first virtual iface.
971 }
972 return {nullptr, std::move(status)};
973 }
974 }
975 br_ifaces_ap_instances_[br_ifname] = ap_instances;
976 if (!iface_util_->createBridge(br_ifname)) {
977 LOG(ERROR) << "Failed createBridge - br_name=" << br_ifname.c_str();
978 invalidateAndClearBridgedAp(br_ifname);
979 return {nullptr, createWifiStatus(WifiStatusCode::ERROR_NOT_AVAILABLE)};
980 }
981 for (auto const& instance : ap_instances) {
982 // Bind ap instance interface to AP bridge
983 if (!iface_util_->addIfaceToBridge(br_ifname, instance)) {
984 LOG(ERROR) << "Failed add if to Bridge - if_name=" << instance.c_str();
985 invalidateAndClearBridgedAp(br_ifname);
986 return {nullptr, createWifiStatus(WifiStatusCode::ERROR_NOT_AVAILABLE)};
987 }
988 }
989 std::shared_ptr<WifiApIface> iface = newWifiApIface(br_ifname);
990 return {iface, ndk::ScopedAStatus::ok()};
991}
992
993std::pair<std::vector<std::string>, ndk::ScopedAStatus> WifiChip::getApIfaceNamesInternal() {
994 if (ap_ifaces_.empty()) {
995 return {std::vector<std::string>(), ndk::ScopedAStatus::ok()};
996 }
997 return {getNames(ap_ifaces_), ndk::ScopedAStatus::ok()};
998}
999
1000std::pair<std::shared_ptr<IWifiApIface>, ndk::ScopedAStatus> WifiChip::getApIfaceInternal(
1001 const std::string& ifname) {
1002 const auto iface = findUsingName(ap_ifaces_, ifname);
1003 if (!iface.get()) {
1004 return {nullptr, createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS)};
1005 }
1006 return {iface, ndk::ScopedAStatus::ok()};
1007}
1008
1009ndk::ScopedAStatus WifiChip::removeApIfaceInternal(const std::string& ifname) {
1010 const auto iface = findUsingName(ap_ifaces_, ifname);
1011 if (!iface.get()) {
1012 return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
1013 }
1014 // Invalidate & remove any dependent objects first.
1015 // Note: This is probably not required because we never create
1016 // nan/rtt objects over AP iface. But, there is no harm to do it
1017 // here and not make that assumption all over the place.
1018 invalidateAndRemoveDependencies(ifname);
1019 // Clear the bridge interface and the iface instance.
1020 invalidateAndClearBridgedAp(ifname);
1021 invalidateAndClear(ap_ifaces_, iface);
1022 for (const auto& callback : event_cb_handler_.getCallbacks()) {
1023 if (!callback->onIfaceRemoved(IfaceType::AP, ifname).isOk()) {
1024 LOG(ERROR) << "Failed to invoke onIfaceRemoved callback";
1025 }
1026 }
1027 setActiveWlanIfaceNameProperty(getFirstActiveWlanIfaceName());
1028 return ndk::ScopedAStatus::ok();
1029}
1030
1031ndk::ScopedAStatus WifiChip::removeIfaceInstanceFromBridgedApIfaceInternal(
1032 const std::string& ifname, const std::string& ifInstanceName) {
1033 const auto iface = findUsingName(ap_ifaces_, ifname);
1034 if (!iface.get() || ifInstanceName.empty()) {
1035 return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
1036 }
1037 // Requires to remove one of the instance in bridge mode
1038 for (auto const& it : br_ifaces_ap_instances_) {
1039 if (it.first == ifname) {
1040 std::vector<std::string> ap_instances = it.second;
1041 for (auto const& iface : ap_instances) {
1042 if (iface == ifInstanceName) {
1043 if (!iface_util_->removeIfaceFromBridge(it.first, iface)) {
1044 LOG(ERROR) << "Failed to remove interface: " << ifInstanceName << " from "
1045 << ifname;
1046 return createWifiStatus(WifiStatusCode::ERROR_NOT_AVAILABLE);
1047 }
1048 legacy_hal::wifi_error legacy_status =
1049 legacy_hal_.lock()->deleteVirtualInterface(iface);
1050 if (legacy_status != legacy_hal::WIFI_SUCCESS) {
1051 LOG(ERROR) << "Failed to del interface: " << iface << " "
1052 << legacyErrorToString(legacy_status);
1053 return createWifiStatusFromLegacyError(legacy_status);
1054 }
1055 ap_instances.erase(
1056 std::remove(ap_instances.begin(), ap_instances.end(), ifInstanceName),
1057 ap_instances.end());
1058 br_ifaces_ap_instances_[ifname] = ap_instances;
1059 break;
1060 }
1061 }
1062 break;
1063 }
1064 }
1065 iface->removeInstance(ifInstanceName);
1066 setActiveWlanIfaceNameProperty(getFirstActiveWlanIfaceName());
1067
1068 return ndk::ScopedAStatus::ok();
1069}
1070
1071std::pair<std::shared_ptr<IWifiNanIface>, ndk::ScopedAStatus> WifiChip::createNanIfaceInternal() {
1072 if (!canCurrentModeSupportConcurrencyTypeWithCurrentTypes(IfaceConcurrencyType::NAN_IFACE)) {
1073 return {nullptr, createWifiStatus(WifiStatusCode::ERROR_NOT_AVAILABLE)};
1074 }
1075 bool is_dedicated_iface = true;
1076 std::string ifname = getPredefinedNanIfaceName();
1077 if (ifname.empty() || !iface_util_->ifNameToIndex(ifname)) {
1078 // Use the first shared STA iface (wlan0) if a dedicated aware iface is
1079 // not defined.
1080 ifname = getFirstActiveWlanIfaceName();
1081 is_dedicated_iface = false;
1082 }
1083 std::shared_ptr<WifiNanIface> iface =
1084 WifiNanIface::create(ifname, is_dedicated_iface, legacy_hal_, iface_util_);
1085 nan_ifaces_.push_back(iface);
1086 for (const auto& callback : event_cb_handler_.getCallbacks()) {
1087 if (!callback->onIfaceAdded(IfaceType::NAN_IFACE, ifname).isOk()) {
1088 LOG(ERROR) << "Failed to invoke onIfaceAdded callback";
1089 }
1090 }
1091 return {iface, ndk::ScopedAStatus::ok()};
1092}
1093
1094std::pair<std::vector<std::string>, ndk::ScopedAStatus> WifiChip::getNanIfaceNamesInternal() {
1095 if (nan_ifaces_.empty()) {
1096 return {std::vector<std::string>(), ndk::ScopedAStatus::ok()};
1097 }
1098 return {getNames(nan_ifaces_), ndk::ScopedAStatus::ok()};
1099}
1100
1101std::pair<std::shared_ptr<IWifiNanIface>, ndk::ScopedAStatus> WifiChip::getNanIfaceInternal(
1102 const std::string& ifname) {
1103 const auto iface = findUsingName(nan_ifaces_, ifname);
1104 if (!iface.get()) {
1105 return {nullptr, createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS)};
1106 }
1107 return {iface, ndk::ScopedAStatus::ok()};
1108}
1109
1110ndk::ScopedAStatus WifiChip::removeNanIfaceInternal(const std::string& ifname) {
1111 const auto iface = findUsingName(nan_ifaces_, ifname);
1112 if (!iface.get()) {
1113 return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
1114 }
1115 invalidateAndClear(nan_ifaces_, iface);
1116 for (const auto& callback : event_cb_handler_.getCallbacks()) {
1117 if (!callback->onIfaceRemoved(IfaceType::NAN_IFACE, ifname).isOk()) {
1118 LOG(ERROR) << "Failed to invoke onIfaceAdded callback";
1119 }
1120 }
1121 return ndk::ScopedAStatus::ok();
1122}
1123
1124std::pair<std::shared_ptr<IWifiP2pIface>, ndk::ScopedAStatus> WifiChip::createP2pIfaceInternal() {
1125 if (!canCurrentModeSupportConcurrencyTypeWithCurrentTypes(IfaceConcurrencyType::P2P)) {
1126 return {nullptr, createWifiStatus(WifiStatusCode::ERROR_NOT_AVAILABLE)};
1127 }
1128 std::string ifname = getPredefinedP2pIfaceName();
1129 std::shared_ptr<WifiP2pIface> iface =
1130 ndk::SharedRefBase::make<WifiP2pIface>(ifname, legacy_hal_);
1131 p2p_ifaces_.push_back(iface);
1132 for (const auto& callback : event_cb_handler_.getCallbacks()) {
1133 if (!callback->onIfaceAdded(IfaceType::P2P, ifname).isOk()) {
1134 LOG(ERROR) << "Failed to invoke onIfaceAdded callback";
1135 }
1136 }
1137 return {iface, ndk::ScopedAStatus::ok()};
1138}
1139
1140std::pair<std::vector<std::string>, ndk::ScopedAStatus> WifiChip::getP2pIfaceNamesInternal() {
1141 if (p2p_ifaces_.empty()) {
1142 return {std::vector<std::string>(), ndk::ScopedAStatus::ok()};
1143 }
1144 return {getNames(p2p_ifaces_), ndk::ScopedAStatus::ok()};
1145}
1146
1147std::pair<std::shared_ptr<IWifiP2pIface>, ndk::ScopedAStatus> WifiChip::getP2pIfaceInternal(
1148 const std::string& ifname) {
1149 const auto iface = findUsingName(p2p_ifaces_, ifname);
1150 if (!iface.get()) {
1151 return {nullptr, createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS)};
1152 }
1153 return {iface, ndk::ScopedAStatus::ok()};
1154}
1155
1156ndk::ScopedAStatus WifiChip::removeP2pIfaceInternal(const std::string& ifname) {
1157 const auto iface = findUsingName(p2p_ifaces_, ifname);
1158 if (!iface.get()) {
1159 return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
1160 }
1161 invalidateAndClear(p2p_ifaces_, iface);
1162 for (const auto& callback : event_cb_handler_.getCallbacks()) {
1163 if (!callback->onIfaceRemoved(IfaceType::P2P, ifname).isOk()) {
1164 LOG(ERROR) << "Failed to invoke onIfaceRemoved callback";
1165 }
1166 }
1167 return ndk::ScopedAStatus::ok();
1168}
1169
1170std::pair<std::shared_ptr<IWifiStaIface>, ndk::ScopedAStatus> WifiChip::createStaIfaceInternal() {
1171 if (!canCurrentModeSupportConcurrencyTypeWithCurrentTypes(IfaceConcurrencyType::STA)) {
1172 return {nullptr, createWifiStatus(WifiStatusCode::ERROR_NOT_AVAILABLE)};
1173 }
1174 std::string ifname = allocateStaIfaceName();
1175 legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->createVirtualInterface(
1176 ifname, aidl_struct_util::convertAidlIfaceTypeToLegacy(IfaceType::STA));
1177 if (legacy_status != legacy_hal::WIFI_SUCCESS) {
1178 LOG(ERROR) << "Failed to add interface: " << ifname << " "
1179 << legacyErrorToString(legacy_status);
1180 return {nullptr, createWifiStatusFromLegacyError(legacy_status)};
1181 }
Gabriel Biren2f7bec812023-01-31 01:07:38 +00001182 std::shared_ptr<WifiStaIface> iface = WifiStaIface::create(ifname, legacy_hal_, iface_util_);
Gabriel Birenf3262f92022-07-15 23:25:39 +00001183 sta_ifaces_.push_back(iface);
1184 for (const auto& callback : event_cb_handler_.getCallbacks()) {
1185 if (!callback->onIfaceAdded(IfaceType::STA, ifname).isOk()) {
1186 LOG(ERROR) << "Failed to invoke onIfaceAdded callback";
1187 }
1188 }
1189 setActiveWlanIfaceNameProperty(getFirstActiveWlanIfaceName());
1190 return {iface, ndk::ScopedAStatus::ok()};
1191}
1192
1193std::pair<std::vector<std::string>, ndk::ScopedAStatus> WifiChip::getStaIfaceNamesInternal() {
1194 if (sta_ifaces_.empty()) {
1195 return {std::vector<std::string>(), ndk::ScopedAStatus::ok()};
1196 }
1197 return {getNames(sta_ifaces_), ndk::ScopedAStatus::ok()};
1198}
1199
1200std::pair<std::shared_ptr<IWifiStaIface>, ndk::ScopedAStatus> WifiChip::getStaIfaceInternal(
1201 const std::string& ifname) {
1202 const auto iface = findUsingName(sta_ifaces_, ifname);
1203 if (!iface.get()) {
1204 return {nullptr, createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS)};
1205 }
1206 return {iface, ndk::ScopedAStatus::ok()};
1207}
1208
1209ndk::ScopedAStatus WifiChip::removeStaIfaceInternal(const std::string& ifname) {
1210 const auto iface = findUsingName(sta_ifaces_, ifname);
1211 if (!iface.get()) {
1212 return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
1213 }
1214 // Invalidate & remove any dependent objects first.
1215 invalidateAndRemoveDependencies(ifname);
1216 legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->deleteVirtualInterface(ifname);
1217 if (legacy_status != legacy_hal::WIFI_SUCCESS) {
1218 LOG(ERROR) << "Failed to remove interface: " << ifname << " "
1219 << legacyErrorToString(legacy_status);
1220 }
1221 invalidateAndClear(sta_ifaces_, iface);
1222 for (const auto& callback : event_cb_handler_.getCallbacks()) {
1223 if (!callback->onIfaceRemoved(IfaceType::STA, ifname).isOk()) {
1224 LOG(ERROR) << "Failed to invoke onIfaceRemoved callback";
1225 }
1226 }
1227 setActiveWlanIfaceNameProperty(getFirstActiveWlanIfaceName());
1228 return ndk::ScopedAStatus::ok();
1229}
1230
1231std::pair<std::shared_ptr<IWifiRttController>, ndk::ScopedAStatus>
1232WifiChip::createRttControllerInternal(const std::shared_ptr<IWifiStaIface>& bound_iface) {
1233 if (sta_ifaces_.size() == 0 &&
1234 !canCurrentModeSupportConcurrencyTypeWithCurrentTypes(IfaceConcurrencyType::STA)) {
1235 LOG(ERROR) << "createRttControllerInternal: Chip cannot support STAs "
1236 "(and RTT by extension)";
1237 return {nullptr, createWifiStatus(WifiStatusCode::ERROR_NOT_AVAILABLE)};
1238 }
1239 std::shared_ptr<WifiRttController> rtt =
1240 WifiRttController::create(getFirstActiveWlanIfaceName(), bound_iface, legacy_hal_);
1241 rtt_controllers_.emplace_back(rtt);
1242 return {rtt, ndk::ScopedAStatus::ok()};
1243}
1244
1245std::pair<std::vector<WifiDebugRingBufferStatus>, ndk::ScopedAStatus>
1246WifiChip::getDebugRingBuffersStatusInternal() {
1247 legacy_hal::wifi_error legacy_status;
1248 std::vector<legacy_hal::wifi_ring_buffer_status> legacy_ring_buffer_status_vec;
1249 std::tie(legacy_status, legacy_ring_buffer_status_vec) =
1250 legacy_hal_.lock()->getRingBuffersStatus(getFirstActiveWlanIfaceName());
1251 if (legacy_status != legacy_hal::WIFI_SUCCESS) {
1252 return {std::vector<WifiDebugRingBufferStatus>(),
1253 createWifiStatusFromLegacyError(legacy_status)};
1254 }
1255 std::vector<WifiDebugRingBufferStatus> aidl_ring_buffer_status_vec;
1256 if (!aidl_struct_util::convertLegacyVectorOfDebugRingBufferStatusToAidl(
1257 legacy_ring_buffer_status_vec, &aidl_ring_buffer_status_vec)) {
1258 return {std::vector<WifiDebugRingBufferStatus>(),
1259 createWifiStatus(WifiStatusCode::ERROR_UNKNOWN)};
1260 }
1261 return {aidl_ring_buffer_status_vec, ndk::ScopedAStatus::ok()};
1262}
1263
1264ndk::ScopedAStatus WifiChip::startLoggingToDebugRingBufferInternal(
1265 const std::string& ring_name, WifiDebugRingBufferVerboseLevel verbose_level,
1266 uint32_t max_interval_in_sec, uint32_t min_data_size_in_bytes) {
1267 ndk::ScopedAStatus status = registerDebugRingBufferCallback();
1268 if (!status.isOk()) {
1269 return status;
1270 }
1271 legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->startRingBufferLogging(
1272 getFirstActiveWlanIfaceName(), ring_name,
1273 static_cast<std::underlying_type<WifiDebugRingBufferVerboseLevel>::type>(verbose_level),
1274 max_interval_in_sec, min_data_size_in_bytes);
1275 ringbuffer_map_.insert(
1276 std::pair<std::string, Ringbuffer>(ring_name, Ringbuffer(kMaxBufferSizeBytes)));
1277 // if verbose logging enabled, turn up HAL daemon logging as well.
1278 if (verbose_level < WifiDebugRingBufferVerboseLevel::VERBOSE) {
1279 ::android::base::SetMinimumLogSeverity(::android::base::DEBUG);
1280 } else {
1281 ::android::base::SetMinimumLogSeverity(::android::base::VERBOSE);
1282 }
1283 return createWifiStatusFromLegacyError(legacy_status);
1284}
1285
1286ndk::ScopedAStatus WifiChip::forceDumpToDebugRingBufferInternal(const std::string& ring_name) {
1287 ndk::ScopedAStatus status = registerDebugRingBufferCallback();
1288 if (!status.isOk()) {
1289 return status;
1290 }
1291 legacy_hal::wifi_error legacy_status =
1292 legacy_hal_.lock()->getRingBufferData(getFirstActiveWlanIfaceName(), ring_name);
1293
1294 return createWifiStatusFromLegacyError(legacy_status);
1295}
1296
1297ndk::ScopedAStatus WifiChip::flushRingBufferToFileInternal() {
1298 if (!writeRingbufferFilesInternal()) {
1299 LOG(ERROR) << "Error writing files to flash";
1300 return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN);
1301 }
1302 return ndk::ScopedAStatus::ok();
1303}
1304
1305ndk::ScopedAStatus WifiChip::stopLoggingToDebugRingBufferInternal() {
1306 legacy_hal::wifi_error legacy_status =
1307 legacy_hal_.lock()->deregisterRingBufferCallbackHandler(getFirstActiveWlanIfaceName());
1308 if (legacy_status == legacy_hal::WIFI_SUCCESS) {
1309 debug_ring_buffer_cb_registered_ = false;
1310 }
1311 return createWifiStatusFromLegacyError(legacy_status);
1312}
1313
1314std::pair<WifiDebugHostWakeReasonStats, ndk::ScopedAStatus>
1315WifiChip::getDebugHostWakeReasonStatsInternal() {
1316 legacy_hal::wifi_error legacy_status;
1317 legacy_hal::WakeReasonStats legacy_stats;
1318 std::tie(legacy_status, legacy_stats) =
1319 legacy_hal_.lock()->getWakeReasonStats(getFirstActiveWlanIfaceName());
1320 if (legacy_status != legacy_hal::WIFI_SUCCESS) {
1321 return {WifiDebugHostWakeReasonStats{}, createWifiStatusFromLegacyError(legacy_status)};
1322 }
1323 WifiDebugHostWakeReasonStats aidl_stats;
1324 if (!aidl_struct_util::convertLegacyWakeReasonStatsToAidl(legacy_stats, &aidl_stats)) {
1325 return {WifiDebugHostWakeReasonStats{}, createWifiStatus(WifiStatusCode::ERROR_UNKNOWN)};
1326 }
1327 return {aidl_stats, ndk::ScopedAStatus::ok()};
1328}
1329
1330ndk::ScopedAStatus WifiChip::enableDebugErrorAlertsInternal(bool enable) {
1331 legacy_hal::wifi_error legacy_status;
1332 if (enable) {
1333 std::weak_ptr<WifiChip> weak_ptr_this = weak_ptr_this_;
1334 const auto& on_alert_callback = [weak_ptr_this](int32_t error_code,
1335 std::vector<uint8_t> debug_data) {
1336 const auto shared_ptr_this = weak_ptr_this.lock();
1337 if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
1338 LOG(ERROR) << "Callback invoked on an invalid object";
1339 return;
1340 }
1341 for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
1342 if (!callback->onDebugErrorAlert(error_code, debug_data).isOk()) {
1343 LOG(ERROR) << "Failed to invoke onDebugErrorAlert callback";
1344 }
1345 }
1346 };
1347 legacy_status = legacy_hal_.lock()->registerErrorAlertCallbackHandler(
1348 getFirstActiveWlanIfaceName(), on_alert_callback);
1349 } else {
1350 legacy_status = legacy_hal_.lock()->deregisterErrorAlertCallbackHandler(
1351 getFirstActiveWlanIfaceName());
1352 }
1353 return createWifiStatusFromLegacyError(legacy_status);
1354}
1355
1356ndk::ScopedAStatus WifiChip::selectTxPowerScenarioInternal(IWifiChip::TxPowerScenario scenario) {
1357 auto legacy_status = legacy_hal_.lock()->selectTxPowerScenario(
1358 getFirstActiveWlanIfaceName(),
1359 aidl_struct_util::convertAidlTxPowerScenarioToLegacy(scenario));
1360 return createWifiStatusFromLegacyError(legacy_status);
1361}
1362
1363ndk::ScopedAStatus WifiChip::resetTxPowerScenarioInternal() {
1364 auto legacy_status = legacy_hal_.lock()->resetTxPowerScenario(getFirstActiveWlanIfaceName());
1365 return createWifiStatusFromLegacyError(legacy_status);
1366}
1367
1368ndk::ScopedAStatus WifiChip::setLatencyModeInternal(IWifiChip::LatencyMode mode) {
1369 auto legacy_status = legacy_hal_.lock()->setLatencyMode(
1370 getFirstActiveWlanIfaceName(), aidl_struct_util::convertAidlLatencyModeToLegacy(mode));
1371 return createWifiStatusFromLegacyError(legacy_status);
1372}
1373
1374ndk::ScopedAStatus WifiChip::setMultiStaPrimaryConnectionInternal(const std::string& ifname) {
1375 auto legacy_status = legacy_hal_.lock()->multiStaSetPrimaryConnection(ifname);
1376 return createWifiStatusFromLegacyError(legacy_status);
1377}
1378
1379ndk::ScopedAStatus WifiChip::setMultiStaUseCaseInternal(IWifiChip::MultiStaUseCase use_case) {
1380 auto legacy_status = legacy_hal_.lock()->multiStaSetUseCase(
1381 aidl_struct_util::convertAidlMultiStaUseCaseToLegacy(use_case));
1382 return createWifiStatusFromLegacyError(legacy_status);
1383}
1384
1385ndk::ScopedAStatus WifiChip::setCoexUnsafeChannelsInternal(
Gabriel Biren3b86a782023-02-04 00:42:53 +00001386 std::vector<IWifiChip::CoexUnsafeChannel> unsafe_channels, int32_t aidl_restrictions) {
Gabriel Birenf3262f92022-07-15 23:25:39 +00001387 std::vector<legacy_hal::wifi_coex_unsafe_channel> legacy_unsafe_channels;
1388 if (!aidl_struct_util::convertAidlVectorOfCoexUnsafeChannelToLegacy(unsafe_channels,
1389 &legacy_unsafe_channels)) {
1390 return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
1391 }
Gabriel Birenf3262f92022-07-15 23:25:39 +00001392 uint32_t legacy_restrictions = 0;
1393 if (aidl_restrictions & static_cast<uint32_t>(CoexRestriction::WIFI_DIRECT)) {
1394 legacy_restrictions |= legacy_hal::wifi_coex_restriction::WIFI_DIRECT;
1395 }
1396 if (aidl_restrictions & static_cast<uint32_t>(CoexRestriction::SOFTAP)) {
1397 legacy_restrictions |= legacy_hal::wifi_coex_restriction::SOFTAP;
1398 }
1399 if (aidl_restrictions & static_cast<uint32_t>(CoexRestriction::WIFI_AWARE)) {
1400 legacy_restrictions |= legacy_hal::wifi_coex_restriction::WIFI_AWARE;
1401 }
1402 auto legacy_status =
1403 legacy_hal_.lock()->setCoexUnsafeChannels(legacy_unsafe_channels, legacy_restrictions);
1404 return createWifiStatusFromLegacyError(legacy_status);
1405}
1406
1407ndk::ScopedAStatus WifiChip::setCountryCodeInternal(const std::array<uint8_t, 2>& code) {
1408 auto legacy_status = legacy_hal_.lock()->setCountryCode(getFirstActiveWlanIfaceName(), code);
1409 return createWifiStatusFromLegacyError(legacy_status);
1410}
1411
1412std::pair<std::vector<WifiUsableChannel>, ndk::ScopedAStatus> WifiChip::getUsableChannelsInternal(
Gabriel Biren3b86a782023-02-04 00:42:53 +00001413 WifiBand band, int32_t ifaceModeMask, int32_t filterMask) {
Gabriel Birenf3262f92022-07-15 23:25:39 +00001414 legacy_hal::wifi_error legacy_status;
1415 std::vector<legacy_hal::wifi_usable_channel> legacy_usable_channels;
1416 std::tie(legacy_status, legacy_usable_channels) = legacy_hal_.lock()->getUsableChannels(
1417 aidl_struct_util::convertAidlWifiBandToLegacyMacBand(band),
Gabriel Biren3b86a782023-02-04 00:42:53 +00001418 aidl_struct_util::convertAidlWifiIfaceModeToLegacy(ifaceModeMask),
1419 aidl_struct_util::convertAidlUsableChannelFilterToLegacy(filterMask));
Gabriel Birenf3262f92022-07-15 23:25:39 +00001420
1421 if (legacy_status != legacy_hal::WIFI_SUCCESS) {
1422 return {std::vector<WifiUsableChannel>(), createWifiStatusFromLegacyError(legacy_status)};
1423 }
1424 std::vector<WifiUsableChannel> aidl_usable_channels;
1425 if (!aidl_struct_util::convertLegacyWifiUsableChannelsToAidl(legacy_usable_channels,
1426 &aidl_usable_channels)) {
1427 return {std::vector<WifiUsableChannel>(), createWifiStatus(WifiStatusCode::ERROR_UNKNOWN)};
1428 }
1429 return {aidl_usable_channels, ndk::ScopedAStatus::ok()};
1430}
1431
Oscar Shuab8313c2022-12-13 00:55:11 +00001432ndk::ScopedAStatus WifiChip::setAfcChannelAllowanceInternal(
Oscar Shu4275c872023-03-08 22:48:09 +00001433 const AfcChannelAllowance& afcChannelAllowance) {
1434 LOG(INFO) << "setAfcChannelAllowance is not yet supported. availableAfcFrequencyInfos size="
1435 << afcChannelAllowance.availableAfcFrequencyInfos.size()
1436 << " availableAfcChannelInfos size="
1437 << afcChannelAllowance.availableAfcChannelInfos.size()
1438 << " availabilityExpireTimeMs=" << afcChannelAllowance.availabilityExpireTimeMs;
Oscar Shuab8313c2022-12-13 00:55:11 +00001439 return createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED);
1440}
1441
Gabriel Biren263db452023-02-24 21:07:38 +00001442std::pair<std::vector<WifiRadioCombination>, ndk::ScopedAStatus>
1443WifiChip::getSupportedRadioCombinationsInternal() {
Gabriel Birenf3262f92022-07-15 23:25:39 +00001444 legacy_hal::wifi_error legacy_status;
1445 legacy_hal::wifi_radio_combination_matrix* legacy_matrix;
Gabriel Biren263db452023-02-24 21:07:38 +00001446 std::vector<WifiRadioCombination> aidl_combinations;
Gabriel Birenf3262f92022-07-15 23:25:39 +00001447
1448 std::tie(legacy_status, legacy_matrix) =
1449 legacy_hal_.lock()->getSupportedRadioCombinationsMatrix();
1450 if (legacy_status != legacy_hal::WIFI_SUCCESS) {
1451 LOG(ERROR) << "Failed to get SupportedRadioCombinations matrix from legacy HAL: "
1452 << legacyErrorToString(legacy_status);
Gabriel Biren263db452023-02-24 21:07:38 +00001453 return {aidl_combinations, createWifiStatusFromLegacyError(legacy_status)};
Gabriel Birenf3262f92022-07-15 23:25:39 +00001454 }
1455
Gabriel Birenf3262f92022-07-15 23:25:39 +00001456 if (!aidl_struct_util::convertLegacyRadioCombinationsMatrixToAidl(legacy_matrix,
Gabriel Biren263db452023-02-24 21:07:38 +00001457 &aidl_combinations)) {
Gabriel Birenf3262f92022-07-15 23:25:39 +00001458 LOG(ERROR) << "Failed convertLegacyRadioCombinationsMatrixToAidl() ";
Gabriel Biren263db452023-02-24 21:07:38 +00001459 return {aidl_combinations, createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS)};
Gabriel Birenf3262f92022-07-15 23:25:39 +00001460 }
Gabriel Biren263db452023-02-24 21:07:38 +00001461 return {aidl_combinations, ndk::ScopedAStatus::ok()};
Gabriel Birenf3262f92022-07-15 23:25:39 +00001462}
1463
Mahesh KKVc84d3772022-12-02 16:53:28 -08001464std::pair<WifiChipCapabilities, ndk::ScopedAStatus> WifiChip::getWifiChipCapabilitiesInternal() {
1465 legacy_hal::wifi_error legacy_status;
1466 legacy_hal::wifi_chip_capabilities legacy_chip_capabilities;
1467 std::tie(legacy_status, legacy_chip_capabilities) =
1468 legacy_hal_.lock()->getWifiChipCapabilities();
1469 if (legacy_status != legacy_hal::WIFI_SUCCESS) {
1470 LOG(ERROR) << "Failed to get chip capabilities from legacy HAL: "
1471 << legacyErrorToString(legacy_status);
1472 return {WifiChipCapabilities(), createWifiStatusFromLegacyError(legacy_status)};
1473 }
1474 WifiChipCapabilities aidl_chip_capabilities;
1475 if (!aidl_struct_util::convertLegacyWifiChipCapabilitiesToAidl(legacy_chip_capabilities,
1476 aidl_chip_capabilities)) {
1477 LOG(ERROR) << "Failed convertLegacyWifiChipCapabilitiesToAidl() ";
1478 return {WifiChipCapabilities(), createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS)};
1479 }
1480
1481 return {aidl_chip_capabilities, ndk::ScopedAStatus::ok()};
1482}
1483
Shuibing Daie5fbcab2022-12-19 15:37:19 -08001484ndk::ScopedAStatus WifiChip::enableStaChannelForPeerNetworkInternal(
Gabriel Biren3b86a782023-02-04 00:42:53 +00001485 int32_t channelCategoryEnableFlag) {
Shuibing Daie5fbcab2022-12-19 15:37:19 -08001486 auto legacy_status = legacy_hal_.lock()->enableStaChannelForPeerNetwork(
Gabriel Biren3b86a782023-02-04 00:42:53 +00001487 aidl_struct_util::convertAidlChannelCategoryToLegacy(channelCategoryEnableFlag));
Shuibing Daie5fbcab2022-12-19 15:37:19 -08001488 return createWifiStatusFromLegacyError(legacy_status);
1489}
1490
Gabriel Birenf3262f92022-07-15 23:25:39 +00001491ndk::ScopedAStatus WifiChip::triggerSubsystemRestartInternal() {
1492 auto legacy_status = legacy_hal_.lock()->triggerSubsystemRestart();
1493 return createWifiStatusFromLegacyError(legacy_status);
1494}
1495
1496ndk::ScopedAStatus WifiChip::handleChipConfiguration(
1497 /* NONNULL */ std::unique_lock<std::recursive_mutex>* lock, int32_t mode_id) {
1498 // If the chip is already configured in a different mode, stop
1499 // the legacy HAL and then start it after firmware mode change.
1500 if (isValidModeId(current_mode_id_)) {
1501 LOG(INFO) << "Reconfiguring chip from mode " << current_mode_id_ << " to mode " << mode_id;
1502 invalidateAndRemoveAllIfaces();
1503 legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->stop(lock, []() {});
1504 if (legacy_status != legacy_hal::WIFI_SUCCESS) {
1505 LOG(ERROR) << "Failed to stop legacy HAL: " << legacyErrorToString(legacy_status);
1506 return createWifiStatusFromLegacyError(legacy_status);
1507 }
1508 }
1509 // Firmware mode change not needed for V2 devices.
1510 bool success = true;
1511 if (mode_id == feature_flags::chip_mode_ids::kV1Sta) {
1512 success = mode_controller_.lock()->changeFirmwareMode(IfaceType::STA);
1513 } else if (mode_id == feature_flags::chip_mode_ids::kV1Ap) {
1514 success = mode_controller_.lock()->changeFirmwareMode(IfaceType::AP);
1515 }
1516 if (!success) {
1517 return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN);
1518 }
1519 legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->start();
1520 if (legacy_status != legacy_hal::WIFI_SUCCESS) {
1521 LOG(ERROR) << "Failed to start legacy HAL: " << legacyErrorToString(legacy_status);
1522 return createWifiStatusFromLegacyError(legacy_status);
1523 }
1524 // Every time the HAL is restarted, we need to register the
1525 // radio mode change callback.
1526 ndk::ScopedAStatus status = registerRadioModeChangeCallback();
1527 if (!status.isOk()) {
1528 // This is probably not a critical failure?
1529 LOG(ERROR) << "Failed to register radio mode change callback";
1530 }
1531 // Extract and save the version information into property.
1532 std::pair<IWifiChip::ChipDebugInfo, ndk::ScopedAStatus> version_info;
1533 version_info = WifiChip::requestChipDebugInfoInternal();
1534 if (version_info.second.isOk()) {
1535 property_set("vendor.wlan.firmware.version",
1536 version_info.first.firmwareDescription.c_str());
1537 property_set("vendor.wlan.driver.version", version_info.first.driverDescription.c_str());
1538 }
Sunil Ravi2be1f262023-02-15 20:56:56 +00001539 // Get the driver supported interface combination.
1540 retrieveDynamicIfaceCombination();
Gabriel Birenf3262f92022-07-15 23:25:39 +00001541
1542 return ndk::ScopedAStatus::ok();
1543}
1544
1545ndk::ScopedAStatus WifiChip::registerDebugRingBufferCallback() {
1546 if (debug_ring_buffer_cb_registered_) {
1547 return ndk::ScopedAStatus::ok();
1548 }
1549
1550 std::weak_ptr<WifiChip> weak_ptr_this = weak_ptr_this_;
1551 const auto& on_ring_buffer_data_callback =
1552 [weak_ptr_this](const std::string& name, const std::vector<uint8_t>& data,
1553 const legacy_hal::wifi_ring_buffer_status& status) {
1554 const auto shared_ptr_this = weak_ptr_this.lock();
1555 if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
1556 LOG(ERROR) << "Callback invoked on an invalid object";
1557 return;
1558 }
1559 WifiDebugRingBufferStatus aidl_status;
1560 Ringbuffer::AppendStatus appendstatus;
1561 if (!aidl_struct_util::convertLegacyDebugRingBufferStatusToAidl(status,
1562 &aidl_status)) {
1563 LOG(ERROR) << "Error converting ring buffer status";
1564 return;
1565 }
1566 {
1567 std::unique_lock<std::mutex> lk(shared_ptr_this->lock_t);
1568 const auto& target = shared_ptr_this->ringbuffer_map_.find(name);
1569 if (target != shared_ptr_this->ringbuffer_map_.end()) {
1570 Ringbuffer& cur_buffer = target->second;
1571 appendstatus = cur_buffer.append(data);
1572 } else {
1573 LOG(ERROR) << "Ringname " << name << " not found";
1574 return;
1575 }
1576 // unique_lock unlocked here
1577 }
1578 if (appendstatus == Ringbuffer::AppendStatus::FAIL_RING_BUFFER_CORRUPTED) {
1579 LOG(ERROR) << "Ringname " << name << " is corrupted. Clear the ring buffer";
1580 shared_ptr_this->writeRingbufferFilesInternal();
1581 return;
1582 }
1583 };
1584 legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->registerRingBufferCallbackHandler(
1585 getFirstActiveWlanIfaceName(), on_ring_buffer_data_callback);
1586
1587 if (legacy_status == legacy_hal::WIFI_SUCCESS) {
1588 debug_ring_buffer_cb_registered_ = true;
1589 }
1590 return createWifiStatusFromLegacyError(legacy_status);
1591}
1592
1593ndk::ScopedAStatus WifiChip::registerRadioModeChangeCallback() {
1594 std::weak_ptr<WifiChip> weak_ptr_this = weak_ptr_this_;
1595 const auto& on_radio_mode_change_callback =
1596 [weak_ptr_this](const std::vector<legacy_hal::WifiMacInfo>& mac_infos) {
1597 const auto shared_ptr_this = weak_ptr_this.lock();
1598 if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
1599 LOG(ERROR) << "Callback invoked on an invalid object";
1600 return;
1601 }
1602 std::vector<IWifiChipEventCallback::RadioModeInfo> aidl_radio_mode_infos;
1603 if (!aidl_struct_util::convertLegacyWifiMacInfosToAidl(mac_infos,
1604 &aidl_radio_mode_infos)) {
1605 LOG(ERROR) << "Error converting wifi mac info";
1606 return;
1607 }
1608 for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
1609 if (!callback->onRadioModeChange(aidl_radio_mode_infos).isOk()) {
1610 LOG(ERROR) << "Failed to invoke onRadioModeChange callback";
1611 }
1612 }
1613 };
1614 legacy_hal::wifi_error legacy_status =
1615 legacy_hal_.lock()->registerRadioModeChangeCallbackHandler(
1616 getFirstActiveWlanIfaceName(), on_radio_mode_change_callback);
1617 return createWifiStatusFromLegacyError(legacy_status);
1618}
1619
1620std::vector<IWifiChip::ChipConcurrencyCombination>
1621WifiChip::getCurrentModeConcurrencyCombinations() {
1622 if (!isValidModeId(current_mode_id_)) {
1623 LOG(ERROR) << "Chip not configured in a mode yet";
1624 return std::vector<IWifiChip::ChipConcurrencyCombination>();
1625 }
1626 for (const auto& mode : modes_) {
1627 if (mode.id == current_mode_id_) {
1628 return mode.availableCombinations;
1629 }
1630 }
1631 CHECK(0) << "Expected to find concurrency combinations for current mode!";
1632 return std::vector<IWifiChip::ChipConcurrencyCombination>();
1633}
1634
1635// Returns a map indexed by IfaceConcurrencyType with the number of ifaces currently
1636// created of the corresponding concurrency type.
1637std::map<IfaceConcurrencyType, size_t> WifiChip::getCurrentConcurrencyCombination() {
1638 std::map<IfaceConcurrencyType, size_t> iface_counts;
1639 uint32_t num_ap = 0;
1640 uint32_t num_ap_bridged = 0;
1641 for (const auto& ap_iface : ap_ifaces_) {
1642 std::string ap_iface_name = ap_iface->getName();
1643 if (br_ifaces_ap_instances_.count(ap_iface_name) > 0 &&
1644 br_ifaces_ap_instances_[ap_iface_name].size() > 1) {
1645 num_ap_bridged++;
1646 } else {
1647 num_ap++;
1648 }
1649 }
1650 iface_counts[IfaceConcurrencyType::AP] = num_ap;
1651 iface_counts[IfaceConcurrencyType::AP_BRIDGED] = num_ap_bridged;
1652 iface_counts[IfaceConcurrencyType::NAN_IFACE] = nan_ifaces_.size();
1653 iface_counts[IfaceConcurrencyType::P2P] = p2p_ifaces_.size();
1654 iface_counts[IfaceConcurrencyType::STA] = sta_ifaces_.size();
1655 return iface_counts;
1656}
1657
1658// This expands the provided concurrency combinations to a more parseable
1659// form. Returns a vector of available combinations possible with the number
1660// of each concurrency type in the combination.
1661// This method is a port of HalDeviceManager.expandConcurrencyCombos() from framework.
1662std::vector<std::map<IfaceConcurrencyType, size_t>> WifiChip::expandConcurrencyCombinations(
1663 const IWifiChip::ChipConcurrencyCombination& combination) {
1664 int32_t num_expanded_combos = 1;
1665 for (const auto& limit : combination.limits) {
1666 for (int32_t i = 0; i < limit.maxIfaces; i++) {
1667 num_expanded_combos *= limit.types.size();
1668 }
1669 }
1670
1671 // Allocate the vector of expanded combos and reset all concurrency type counts to 0
1672 // in each combo.
1673 std::vector<std::map<IfaceConcurrencyType, size_t>> expanded_combos;
1674 expanded_combos.resize(num_expanded_combos);
1675 for (auto& expanded_combo : expanded_combos) {
1676 for (const auto type : {IfaceConcurrencyType::AP, IfaceConcurrencyType::AP_BRIDGED,
1677 IfaceConcurrencyType::NAN_IFACE, IfaceConcurrencyType::P2P,
1678 IfaceConcurrencyType::STA}) {
1679 expanded_combo[type] = 0;
1680 }
1681 }
1682 int32_t span = num_expanded_combos;
1683 for (const auto& limit : combination.limits) {
1684 for (int32_t i = 0; i < limit.maxIfaces; i++) {
1685 span /= limit.types.size();
1686 for (int32_t k = 0; k < num_expanded_combos; ++k) {
1687 const auto iface_type = limit.types[(k / span) % limit.types.size()];
1688 expanded_combos[k][iface_type]++;
1689 }
1690 }
1691 }
1692 return expanded_combos;
1693}
1694
1695bool WifiChip::canExpandedConcurrencyComboSupportConcurrencyTypeWithCurrentTypes(
1696 const std::map<IfaceConcurrencyType, size_t>& expanded_combo,
1697 IfaceConcurrencyType requested_type) {
1698 const auto current_combo = getCurrentConcurrencyCombination();
1699
1700 // Check if we have space for 1 more iface of |type| in this combo
1701 for (const auto type :
1702 {IfaceConcurrencyType::AP, IfaceConcurrencyType::AP_BRIDGED,
1703 IfaceConcurrencyType::NAN_IFACE, IfaceConcurrencyType::P2P, IfaceConcurrencyType::STA}) {
1704 size_t num_ifaces_needed = current_combo.at(type);
1705 if (type == requested_type) {
1706 num_ifaces_needed++;
1707 }
1708 size_t num_ifaces_allowed = expanded_combo.at(type);
1709 if (num_ifaces_needed > num_ifaces_allowed) {
1710 return false;
1711 }
1712 }
1713 return true;
1714}
1715
1716// This method does the following:
1717// a) Enumerate all possible concurrency combos by expanding the current
1718// ChipConcurrencyCombination.
1719// b) Check if the requested concurrency type can be added to the current mode
1720// with the concurrency combination that is already active.
1721bool WifiChip::canCurrentModeSupportConcurrencyTypeWithCurrentTypes(
1722 IfaceConcurrencyType requested_type) {
1723 if (!isValidModeId(current_mode_id_)) {
1724 LOG(ERROR) << "Chip not configured in a mode yet";
1725 return false;
1726 }
1727 const auto combinations = getCurrentModeConcurrencyCombinations();
1728 for (const auto& combination : combinations) {
1729 const auto expanded_combos = expandConcurrencyCombinations(combination);
1730 for (const auto& expanded_combo : expanded_combos) {
1731 if (canExpandedConcurrencyComboSupportConcurrencyTypeWithCurrentTypes(expanded_combo,
1732 requested_type)) {
1733 return true;
1734 }
1735 }
1736 }
1737 return false;
1738}
1739
1740// Note: This does not consider concurrency types already active. It only checks if the
1741// provided expanded concurrency combination can support the requested combo.
1742bool WifiChip::canExpandedConcurrencyComboSupportConcurrencyCombo(
1743 const std::map<IfaceConcurrencyType, size_t>& expanded_combo,
1744 const std::map<IfaceConcurrencyType, size_t>& req_combo) {
1745 // Check if we have space for 1 more |type| in this combo
1746 for (const auto type :
1747 {IfaceConcurrencyType::AP, IfaceConcurrencyType::AP_BRIDGED,
1748 IfaceConcurrencyType::NAN_IFACE, IfaceConcurrencyType::P2P, IfaceConcurrencyType::STA}) {
1749 if (req_combo.count(type) == 0) {
1750 // Concurrency type not in the req_combo.
1751 continue;
1752 }
1753 size_t num_ifaces_needed = req_combo.at(type);
1754 size_t num_ifaces_allowed = expanded_combo.at(type);
1755 if (num_ifaces_needed > num_ifaces_allowed) {
1756 return false;
1757 }
1758 }
1759 return true;
1760}
1761
1762// This method does the following:
1763// a) Enumerate all possible concurrency combos by expanding the current
1764// ChipConcurrencyCombination.
1765// b) Check if the requested concurrency combo can be added to the current mode.
1766// Note: This does not consider concurrency types already active. It only checks if the
1767// current mode can support the requested combo.
1768bool WifiChip::canCurrentModeSupportConcurrencyCombo(
1769 const std::map<IfaceConcurrencyType, size_t>& req_combo) {
1770 if (!isValidModeId(current_mode_id_)) {
1771 LOG(ERROR) << "Chip not configured in a mode yet";
1772 return false;
1773 }
1774 const auto combinations = getCurrentModeConcurrencyCombinations();
1775 for (const auto& combination : combinations) {
1776 const auto expanded_combos = expandConcurrencyCombinations(combination);
1777 for (const auto& expanded_combo : expanded_combos) {
1778 if (canExpandedConcurrencyComboSupportConcurrencyCombo(expanded_combo, req_combo)) {
1779 return true;
1780 }
1781 }
1782 }
1783 return false;
1784}
1785
1786// This method does the following:
1787// a) Enumerate all possible concurrency combos by expanding the current
1788// ChipConcurrencyCombination.
1789// b) Check if the requested concurrency type can be added to the current mode.
1790bool WifiChip::canCurrentModeSupportConcurrencyType(IfaceConcurrencyType requested_type) {
1791 // Check if we can support at least 1 of the requested concurrency type.
1792 std::map<IfaceConcurrencyType, size_t> req_iface_combo;
1793 req_iface_combo[requested_type] = 1;
1794 return canCurrentModeSupportConcurrencyCombo(req_iface_combo);
1795}
1796
1797bool WifiChip::isValidModeId(int32_t mode_id) {
1798 for (const auto& mode : modes_) {
1799 if (mode.id == mode_id) {
1800 return true;
1801 }
1802 }
1803 return false;
1804}
1805
1806bool WifiChip::isStaApConcurrencyAllowedInCurrentMode() {
1807 // Check if we can support at least 1 STA & 1 AP concurrently.
1808 std::map<IfaceConcurrencyType, size_t> req_iface_combo;
1809 req_iface_combo[IfaceConcurrencyType::STA] = 1;
1810 req_iface_combo[IfaceConcurrencyType::AP] = 1;
1811 return canCurrentModeSupportConcurrencyCombo(req_iface_combo);
1812}
1813
1814bool WifiChip::isDualStaConcurrencyAllowedInCurrentMode() {
1815 // Check if we can support at least 2 STA concurrently.
1816 std::map<IfaceConcurrencyType, size_t> req_iface_combo;
1817 req_iface_combo[IfaceConcurrencyType::STA] = 2;
1818 return canCurrentModeSupportConcurrencyCombo(req_iface_combo);
1819}
1820
1821std::string WifiChip::getFirstActiveWlanIfaceName() {
1822 if (sta_ifaces_.size() > 0) return sta_ifaces_[0]->getName();
1823 if (ap_ifaces_.size() > 0) {
1824 // If the first active wlan iface is bridged iface.
1825 // Return first instance name.
1826 for (auto const& it : br_ifaces_ap_instances_) {
1827 if (it.first == ap_ifaces_[0]->getName()) {
1828 return it.second[0];
1829 }
1830 }
1831 return ap_ifaces_[0]->getName();
1832 }
1833 // This could happen if the chip call is made before any STA/AP
1834 // iface is created. Default to wlan0 for such cases.
1835 LOG(WARNING) << "No active wlan interfaces in use! Using default";
1836 return getWlanIfaceNameWithType(IfaceType::STA, 0);
1837}
1838
1839// Return the first wlan (wlan0, wlan1 etc.) starting from |start_idx|
1840// not already in use.
1841// Note: This doesn't check the actual presence of these interfaces.
1842std::string WifiChip::allocateApOrStaIfaceName(IfaceType type, uint32_t start_idx) {
1843 for (unsigned idx = start_idx; idx < kMaxWlanIfaces; idx++) {
1844 const auto ifname = getWlanIfaceNameWithType(type, idx);
1845 if (findUsingNameFromBridgedApInstances(ifname)) continue;
1846 if (findUsingName(ap_ifaces_, ifname)) continue;
1847 if (findUsingName(sta_ifaces_, ifname)) continue;
1848 return ifname;
1849 }
1850 // This should never happen. We screwed up somewhere if it did.
1851 CHECK(false) << "All wlan interfaces in use already!";
1852 return {};
1853}
1854
1855uint32_t WifiChip::startIdxOfApIface() {
1856 if (isDualStaConcurrencyAllowedInCurrentMode()) {
1857 // When the HAL support dual STAs, AP should start with idx 2.
1858 return 2;
1859 } else if (isStaApConcurrencyAllowedInCurrentMode()) {
1860 // When the HAL support STA + AP but it doesn't support dual STAs.
1861 // AP should start with idx 1.
1862 return 1;
1863 }
1864 // No concurrency support.
1865 return 0;
1866}
1867
1868// AP iface names start with idx 1 for modes supporting
1869// concurrent STA and not dual AP, else start with idx 0.
1870std::string WifiChip::allocateApIfaceName() {
1871 // Check if we have a dedicated iface for AP.
1872 std::vector<std::string> ifnames = getPredefinedApIfaceNames(true);
1873 for (auto const& ifname : ifnames) {
1874 if (findUsingName(ap_ifaces_, ifname)) continue;
1875 return ifname;
1876 }
1877 return allocateApOrStaIfaceName(IfaceType::AP, startIdxOfApIface());
1878}
1879
1880std::vector<std::string> WifiChip::allocateBridgedApInstanceNames() {
1881 // Check if we have a dedicated iface for AP.
1882 std::vector<std::string> instances = getPredefinedApIfaceNames(true);
1883 if (instances.size() == 2) {
1884 return instances;
1885 } else {
1886 int num_ifaces_need_to_allocate = 2 - instances.size();
1887 for (int i = 0; i < num_ifaces_need_to_allocate; i++) {
1888 std::string instance_name =
1889 allocateApOrStaIfaceName(IfaceType::AP, startIdxOfApIface() + i);
1890 if (!instance_name.empty()) {
1891 instances.push_back(instance_name);
1892 }
1893 }
1894 }
1895 return instances;
1896}
1897
1898// STA iface names start with idx 0.
1899// Primary STA iface will always be 0.
1900std::string WifiChip::allocateStaIfaceName() {
1901 return allocateApOrStaIfaceName(IfaceType::STA, 0);
1902}
1903
1904bool WifiChip::writeRingbufferFilesInternal() {
1905 if (!removeOldFilesInternal()) {
1906 LOG(ERROR) << "Error occurred while deleting old tombstone files";
1907 return false;
1908 }
1909 // write ringbuffers to file
1910 {
1911 std::unique_lock<std::mutex> lk(lock_t);
1912 for (auto& item : ringbuffer_map_) {
1913 Ringbuffer& cur_buffer = item.second;
1914 if (cur_buffer.getData().empty()) {
1915 continue;
1916 }
1917 const std::string file_path_raw = kTombstoneFolderPath + item.first + "XXXXXXXXXX";
1918 const int dump_fd = mkstemp(makeCharVec(file_path_raw).data());
1919 if (dump_fd == -1) {
1920 PLOG(ERROR) << "create file failed";
1921 return false;
1922 }
1923 unique_fd file_auto_closer(dump_fd);
1924 for (const auto& cur_block : cur_buffer.getData()) {
1925 if (cur_block.size() <= 0 || cur_block.size() > kMaxBufferSizeBytes) {
1926 PLOG(ERROR) << "Ring buffer: " << item.first
1927 << " is corrupted. Invalid block size: " << cur_block.size();
1928 break;
1929 }
1930 if (write(dump_fd, cur_block.data(), sizeof(cur_block[0]) * cur_block.size()) ==
1931 -1) {
1932 PLOG(ERROR) << "Error writing to file";
1933 }
1934 }
1935 cur_buffer.clear();
1936 }
1937 // unique_lock unlocked here
1938 }
1939 return true;
1940}
1941
1942std::string WifiChip::getWlanIfaceNameWithType(IfaceType type, unsigned idx) {
1943 std::string ifname;
1944
1945 // let the legacy hal override the interface name
1946 legacy_hal::wifi_error err = legacy_hal_.lock()->getSupportedIfaceName((uint32_t)type, ifname);
1947 if (err == legacy_hal::WIFI_SUCCESS) return ifname;
1948
1949 return getWlanIfaceName(idx);
1950}
1951
1952void WifiChip::invalidateAndClearBridgedApAll() {
1953 for (auto const& it : br_ifaces_ap_instances_) {
1954 for (auto const& iface : it.second) {
1955 iface_util_->removeIfaceFromBridge(it.first, iface);
1956 legacy_hal_.lock()->deleteVirtualInterface(iface);
1957 }
1958 iface_util_->deleteBridge(it.first);
1959 }
1960 br_ifaces_ap_instances_.clear();
1961}
1962
1963void WifiChip::invalidateAndClearBridgedAp(const std::string& br_name) {
1964 if (br_name.empty()) return;
1965 // delete managed interfaces
1966 for (auto const& it : br_ifaces_ap_instances_) {
1967 if (it.first == br_name) {
1968 for (auto const& iface : it.second) {
1969 iface_util_->removeIfaceFromBridge(br_name, iface);
1970 legacy_hal_.lock()->deleteVirtualInterface(iface);
1971 }
1972 iface_util_->deleteBridge(br_name);
1973 br_ifaces_ap_instances_.erase(br_name);
1974 break;
1975 }
1976 }
1977 return;
1978}
1979
1980bool WifiChip::findUsingNameFromBridgedApInstances(const std::string& name) {
1981 for (auto const& it : br_ifaces_ap_instances_) {
1982 if (it.first == name) {
1983 return true;
1984 }
1985 for (auto const& iface : it.second) {
1986 if (iface == name) {
1987 return true;
1988 }
1989 }
1990 }
1991 return false;
1992}
1993
maheshkkva8aba172023-02-13 12:33:26 -08001994ndk::ScopedAStatus WifiChip::setMloModeInternal(const WifiChip::ChipMloMode in_mode) {
1995 legacy_hal::wifi_mlo_mode mode;
1996 switch (in_mode) {
1997 case WifiChip::ChipMloMode::DEFAULT:
1998 mode = legacy_hal::wifi_mlo_mode::WIFI_MLO_MODE_DEFAULT;
1999 break;
2000 case WifiChip::ChipMloMode::LOW_LATENCY:
2001 mode = legacy_hal::wifi_mlo_mode::WIFI_MLO_MODE_LOW_LATENCY;
2002 break;
2003 case WifiChip::ChipMloMode::HIGH_THROUGHPUT:
2004 mode = legacy_hal::wifi_mlo_mode::WIFI_MLO_MODE_HIGH_THROUGHPUT;
2005 break;
2006 case WifiChip::ChipMloMode::LOW_POWER:
2007 mode = legacy_hal::wifi_mlo_mode::WIFI_MLO_MODE_LOW_POWER;
2008 break;
2009 default:
2010 PLOG(ERROR) << "Error: invalid mode: " << toString(in_mode);
2011 return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
2012 }
2013 return createWifiStatusFromLegacyError(legacy_hal_.lock()->setMloMode(mode));
2014}
2015
Gabriel Birenf3262f92022-07-15 23:25:39 +00002016} // namespace wifi
2017} // namespace hardware
2018} // namespace android
2019} // namespace aidl