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