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