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