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 <array>
18 #include <chrono>
19 
20 #include <android-base/logging.h>
21 #include <cutils/properties.h>
22 
23 #include "hidl_sync_util.h"
24 #include "wifi_legacy_hal.h"
25 #include "wifi_legacy_hal_stubs.h"
26 
27 namespace {
28 // Constants ported over from the legacy HAL calling code
29 // (com_android_server_wifi_WifiNative.cpp). This will all be thrown
30 // away when this shim layer is replaced by the real vendor
31 // implementation.
32 static constexpr uint32_t kMaxVersionStringLength = 256;
33 static constexpr uint32_t kMaxCachedGscanResults = 64;
34 static constexpr uint32_t kMaxGscanFrequenciesForBand = 64;
35 static constexpr uint32_t kLinkLayerStatsDataMpduSizeThreshold = 128;
36 static constexpr uint32_t kMaxWakeReasonStatsArraySize = 32;
37 static constexpr uint32_t kMaxRingBuffers = 10;
38 static constexpr uint32_t kMaxStopCompleteWaitMs = 100;
39 static constexpr char kDriverPropName[] = "wlan.driver.status";
40 
41 // Helper function to create a non-const char* for legacy Hal API's.
makeCharVec(const std::string & str)42 std::vector<char> makeCharVec(const std::string& str) {
43     std::vector<char> vec(str.size() + 1);
44     vec.assign(str.begin(), str.end());
45     vec.push_back('\0');
46     return vec;
47 }
48 }  // namespace
49 
50 namespace android {
51 namespace hardware {
52 namespace wifi {
53 namespace V1_3 {
54 namespace implementation {
55 namespace legacy_hal {
56 // Legacy HAL functions accept "C" style function pointers, so use global
57 // functions to pass to the legacy HAL function and store the corresponding
58 // std::function methods to be invoked.
59 //
60 // Callback to be invoked once |stop| is complete
61 std::function<void(wifi_handle handle)> on_stop_complete_internal_callback;
onAsyncStopComplete(wifi_handle handle)62 void onAsyncStopComplete(wifi_handle handle) {
63     const auto lock = hidl_sync_util::acquireGlobalLock();
64     if (on_stop_complete_internal_callback) {
65         on_stop_complete_internal_callback(handle);
66         // Invalidate this callback since we don't want this firing again.
67         on_stop_complete_internal_callback = nullptr;
68     }
69 }
70 
71 // Callback to be invoked for driver dump.
72 std::function<void(char*, int)> on_driver_memory_dump_internal_callback;
onSyncDriverMemoryDump(char * buffer,int buffer_size)73 void onSyncDriverMemoryDump(char* buffer, int buffer_size) {
74     if (on_driver_memory_dump_internal_callback) {
75         on_driver_memory_dump_internal_callback(buffer, buffer_size);
76     }
77 }
78 
79 // Callback to be invoked for firmware dump.
80 std::function<void(char*, int)> on_firmware_memory_dump_internal_callback;
onSyncFirmwareMemoryDump(char * buffer,int buffer_size)81 void onSyncFirmwareMemoryDump(char* buffer, int buffer_size) {
82     if (on_firmware_memory_dump_internal_callback) {
83         on_firmware_memory_dump_internal_callback(buffer, buffer_size);
84     }
85 }
86 
87 // Callback to be invoked for Gscan events.
88 std::function<void(wifi_request_id, wifi_scan_event)>
89     on_gscan_event_internal_callback;
onAsyncGscanEvent(wifi_request_id id,wifi_scan_event event)90 void onAsyncGscanEvent(wifi_request_id id, wifi_scan_event event) {
91     const auto lock = hidl_sync_util::acquireGlobalLock();
92     if (on_gscan_event_internal_callback) {
93         on_gscan_event_internal_callback(id, event);
94     }
95 }
96 
97 // Callback to be invoked for Gscan full results.
98 std::function<void(wifi_request_id, wifi_scan_result*, uint32_t)>
99     on_gscan_full_result_internal_callback;
onAsyncGscanFullResult(wifi_request_id id,wifi_scan_result * result,uint32_t buckets_scanned)100 void onAsyncGscanFullResult(wifi_request_id id, wifi_scan_result* result,
101                             uint32_t buckets_scanned) {
102     const auto lock = hidl_sync_util::acquireGlobalLock();
103     if (on_gscan_full_result_internal_callback) {
104         on_gscan_full_result_internal_callback(id, result, buckets_scanned);
105     }
106 }
107 
108 // Callback to be invoked for link layer stats results.
109 std::function<void((wifi_request_id, wifi_iface_stat*, int, wifi_radio_stat*))>
110     on_link_layer_stats_result_internal_callback;
onSyncLinkLayerStatsResult(wifi_request_id id,wifi_iface_stat * iface_stat,int num_radios,wifi_radio_stat * radio_stat)111 void onSyncLinkLayerStatsResult(wifi_request_id id, wifi_iface_stat* iface_stat,
112                                 int num_radios, wifi_radio_stat* radio_stat) {
113     if (on_link_layer_stats_result_internal_callback) {
114         on_link_layer_stats_result_internal_callback(id, iface_stat, num_radios,
115                                                      radio_stat);
116     }
117 }
118 
119 // Callback to be invoked for rssi threshold breach.
120 std::function<void((wifi_request_id, uint8_t*, int8_t))>
121     on_rssi_threshold_breached_internal_callback;
onAsyncRssiThresholdBreached(wifi_request_id id,uint8_t * bssid,int8_t rssi)122 void onAsyncRssiThresholdBreached(wifi_request_id id, uint8_t* bssid,
123                                   int8_t rssi) {
124     const auto lock = hidl_sync_util::acquireGlobalLock();
125     if (on_rssi_threshold_breached_internal_callback) {
126         on_rssi_threshold_breached_internal_callback(id, bssid, rssi);
127     }
128 }
129 
130 // Callback to be invoked for ring buffer data indication.
131 std::function<void(char*, char*, int, wifi_ring_buffer_status*)>
132     on_ring_buffer_data_internal_callback;
onAsyncRingBufferData(char * ring_name,char * buffer,int buffer_size,wifi_ring_buffer_status * status)133 void onAsyncRingBufferData(char* ring_name, char* buffer, int buffer_size,
134                            wifi_ring_buffer_status* status) {
135     const auto lock = hidl_sync_util::acquireGlobalLock();
136     if (on_ring_buffer_data_internal_callback) {
137         on_ring_buffer_data_internal_callback(ring_name, buffer, buffer_size,
138                                               status);
139     }
140 }
141 
142 // Callback to be invoked for error alert indication.
143 std::function<void(wifi_request_id, char*, int, int)>
144     on_error_alert_internal_callback;
onAsyncErrorAlert(wifi_request_id id,char * buffer,int buffer_size,int err_code)145 void onAsyncErrorAlert(wifi_request_id id, char* buffer, int buffer_size,
146                        int err_code) {
147     const auto lock = hidl_sync_util::acquireGlobalLock();
148     if (on_error_alert_internal_callback) {
149         on_error_alert_internal_callback(id, buffer, buffer_size, err_code);
150     }
151 }
152 
153 // Callback to be invoked for radio mode change indication.
154 std::function<void(wifi_request_id, uint32_t, wifi_mac_info*)>
155     on_radio_mode_change_internal_callback;
onAsyncRadioModeChange(wifi_request_id id,uint32_t num_macs,wifi_mac_info * mac_infos)156 void onAsyncRadioModeChange(wifi_request_id id, uint32_t num_macs,
157                             wifi_mac_info* mac_infos) {
158     const auto lock = hidl_sync_util::acquireGlobalLock();
159     if (on_radio_mode_change_internal_callback) {
160         on_radio_mode_change_internal_callback(id, num_macs, mac_infos);
161     }
162 }
163 
164 // Callback to be invoked for rtt results results.
165 std::function<void(wifi_request_id, unsigned num_results,
166                    wifi_rtt_result* rtt_results[])>
167     on_rtt_results_internal_callback;
onAsyncRttResults(wifi_request_id id,unsigned num_results,wifi_rtt_result * rtt_results[])168 void onAsyncRttResults(wifi_request_id id, unsigned num_results,
169                        wifi_rtt_result* rtt_results[]) {
170     const auto lock = hidl_sync_util::acquireGlobalLock();
171     if (on_rtt_results_internal_callback) {
172         on_rtt_results_internal_callback(id, num_results, rtt_results);
173         on_rtt_results_internal_callback = nullptr;
174     }
175 }
176 
177 // Callbacks for the various NAN operations.
178 // NOTE: These have very little conversions to perform before invoking the user
179 // callbacks.
180 // So, handle all of them here directly to avoid adding an unnecessary layer.
181 std::function<void(transaction_id, const NanResponseMsg&)>
182     on_nan_notify_response_user_callback;
onAysncNanNotifyResponse(transaction_id id,NanResponseMsg * msg)183 void onAysncNanNotifyResponse(transaction_id id, NanResponseMsg* msg) {
184     const auto lock = hidl_sync_util::acquireGlobalLock();
185     if (on_nan_notify_response_user_callback && msg) {
186         on_nan_notify_response_user_callback(id, *msg);
187     }
188 }
189 
190 std::function<void(const NanPublishRepliedInd&)>
191     on_nan_event_publish_replied_user_callback;
onAysncNanEventPublishReplied(NanPublishRepliedInd *)192 void onAysncNanEventPublishReplied(NanPublishRepliedInd* /* event */) {
193     LOG(ERROR) << "onAysncNanEventPublishReplied triggered";
194 }
195 
196 std::function<void(const NanPublishTerminatedInd&)>
197     on_nan_event_publish_terminated_user_callback;
onAysncNanEventPublishTerminated(NanPublishTerminatedInd * event)198 void onAysncNanEventPublishTerminated(NanPublishTerminatedInd* event) {
199     const auto lock = hidl_sync_util::acquireGlobalLock();
200     if (on_nan_event_publish_terminated_user_callback && event) {
201         on_nan_event_publish_terminated_user_callback(*event);
202     }
203 }
204 
205 std::function<void(const NanMatchInd&)> on_nan_event_match_user_callback;
onAysncNanEventMatch(NanMatchInd * event)206 void onAysncNanEventMatch(NanMatchInd* event) {
207     const auto lock = hidl_sync_util::acquireGlobalLock();
208     if (on_nan_event_match_user_callback && event) {
209         on_nan_event_match_user_callback(*event);
210     }
211 }
212 
213 std::function<void(const NanMatchExpiredInd&)>
214     on_nan_event_match_expired_user_callback;
onAysncNanEventMatchExpired(NanMatchExpiredInd * event)215 void onAysncNanEventMatchExpired(NanMatchExpiredInd* event) {
216     const auto lock = hidl_sync_util::acquireGlobalLock();
217     if (on_nan_event_match_expired_user_callback && event) {
218         on_nan_event_match_expired_user_callback(*event);
219     }
220 }
221 
222 std::function<void(const NanSubscribeTerminatedInd&)>
223     on_nan_event_subscribe_terminated_user_callback;
onAysncNanEventSubscribeTerminated(NanSubscribeTerminatedInd * event)224 void onAysncNanEventSubscribeTerminated(NanSubscribeTerminatedInd* event) {
225     const auto lock = hidl_sync_util::acquireGlobalLock();
226     if (on_nan_event_subscribe_terminated_user_callback && event) {
227         on_nan_event_subscribe_terminated_user_callback(*event);
228     }
229 }
230 
231 std::function<void(const NanFollowupInd&)> on_nan_event_followup_user_callback;
onAysncNanEventFollowup(NanFollowupInd * event)232 void onAysncNanEventFollowup(NanFollowupInd* event) {
233     const auto lock = hidl_sync_util::acquireGlobalLock();
234     if (on_nan_event_followup_user_callback && event) {
235         on_nan_event_followup_user_callback(*event);
236     }
237 }
238 
239 std::function<void(const NanDiscEngEventInd&)>
240     on_nan_event_disc_eng_event_user_callback;
onAysncNanEventDiscEngEvent(NanDiscEngEventInd * event)241 void onAysncNanEventDiscEngEvent(NanDiscEngEventInd* event) {
242     const auto lock = hidl_sync_util::acquireGlobalLock();
243     if (on_nan_event_disc_eng_event_user_callback && event) {
244         on_nan_event_disc_eng_event_user_callback(*event);
245     }
246 }
247 
248 std::function<void(const NanDisabledInd&)> on_nan_event_disabled_user_callback;
onAysncNanEventDisabled(NanDisabledInd * event)249 void onAysncNanEventDisabled(NanDisabledInd* event) {
250     const auto lock = hidl_sync_util::acquireGlobalLock();
251     if (on_nan_event_disabled_user_callback && event) {
252         on_nan_event_disabled_user_callback(*event);
253     }
254 }
255 
256 std::function<void(const NanTCAInd&)> on_nan_event_tca_user_callback;
onAysncNanEventTca(NanTCAInd * event)257 void onAysncNanEventTca(NanTCAInd* event) {
258     const auto lock = hidl_sync_util::acquireGlobalLock();
259     if (on_nan_event_tca_user_callback && event) {
260         on_nan_event_tca_user_callback(*event);
261     }
262 }
263 
264 std::function<void(const NanBeaconSdfPayloadInd&)>
265     on_nan_event_beacon_sdf_payload_user_callback;
onAysncNanEventBeaconSdfPayload(NanBeaconSdfPayloadInd * event)266 void onAysncNanEventBeaconSdfPayload(NanBeaconSdfPayloadInd* event) {
267     const auto lock = hidl_sync_util::acquireGlobalLock();
268     if (on_nan_event_beacon_sdf_payload_user_callback && event) {
269         on_nan_event_beacon_sdf_payload_user_callback(*event);
270     }
271 }
272 
273 std::function<void(const NanDataPathRequestInd&)>
274     on_nan_event_data_path_request_user_callback;
onAysncNanEventDataPathRequest(NanDataPathRequestInd * event)275 void onAysncNanEventDataPathRequest(NanDataPathRequestInd* event) {
276     const auto lock = hidl_sync_util::acquireGlobalLock();
277     if (on_nan_event_data_path_request_user_callback && event) {
278         on_nan_event_data_path_request_user_callback(*event);
279     }
280 }
281 std::function<void(const NanDataPathConfirmInd&)>
282     on_nan_event_data_path_confirm_user_callback;
onAysncNanEventDataPathConfirm(NanDataPathConfirmInd * event)283 void onAysncNanEventDataPathConfirm(NanDataPathConfirmInd* event) {
284     const auto lock = hidl_sync_util::acquireGlobalLock();
285     if (on_nan_event_data_path_confirm_user_callback && event) {
286         on_nan_event_data_path_confirm_user_callback(*event);
287     }
288 }
289 
290 std::function<void(const NanDataPathEndInd&)>
291     on_nan_event_data_path_end_user_callback;
onAysncNanEventDataPathEnd(NanDataPathEndInd * event)292 void onAysncNanEventDataPathEnd(NanDataPathEndInd* event) {
293     const auto lock = hidl_sync_util::acquireGlobalLock();
294     if (on_nan_event_data_path_end_user_callback && event) {
295         on_nan_event_data_path_end_user_callback(*event);
296     }
297 }
298 
299 std::function<void(const NanTransmitFollowupInd&)>
300     on_nan_event_transmit_follow_up_user_callback;
onAysncNanEventTransmitFollowUp(NanTransmitFollowupInd * event)301 void onAysncNanEventTransmitFollowUp(NanTransmitFollowupInd* event) {
302     const auto lock = hidl_sync_util::acquireGlobalLock();
303     if (on_nan_event_transmit_follow_up_user_callback && event) {
304         on_nan_event_transmit_follow_up_user_callback(*event);
305     }
306 }
307 
308 std::function<void(const NanRangeRequestInd&)>
309     on_nan_event_range_request_user_callback;
onAysncNanEventRangeRequest(NanRangeRequestInd * event)310 void onAysncNanEventRangeRequest(NanRangeRequestInd* event) {
311     const auto lock = hidl_sync_util::acquireGlobalLock();
312     if (on_nan_event_range_request_user_callback && event) {
313         on_nan_event_range_request_user_callback(*event);
314     }
315 }
316 
317 std::function<void(const NanRangeReportInd&)>
318     on_nan_event_range_report_user_callback;
onAysncNanEventRangeReport(NanRangeReportInd * event)319 void onAysncNanEventRangeReport(NanRangeReportInd* event) {
320     const auto lock = hidl_sync_util::acquireGlobalLock();
321     if (on_nan_event_range_report_user_callback && event) {
322         on_nan_event_range_report_user_callback(*event);
323     }
324 }
325 
326 std::function<void(const NanDataPathScheduleUpdateInd&)>
327     on_nan_event_schedule_update_user_callback;
onAsyncNanEventScheduleUpdate(NanDataPathScheduleUpdateInd * event)328 void onAsyncNanEventScheduleUpdate(NanDataPathScheduleUpdateInd* event) {
329     const auto lock = hidl_sync_util::acquireGlobalLock();
330     if (on_nan_event_schedule_update_user_callback && event) {
331         on_nan_event_schedule_update_user_callback(*event);
332     }
333 }
334 // End of the free-standing "C" style callbacks.
335 
WifiLegacyHal(const std::weak_ptr<wifi_system::InterfaceTool> iface_tool)336 WifiLegacyHal::WifiLegacyHal(
337     const std::weak_ptr<wifi_system::InterfaceTool> iface_tool)
338     : global_handle_(nullptr),
339       awaiting_event_loop_termination_(false),
340       is_started_(false),
341       iface_tool_(iface_tool) {}
342 
initialize()343 wifi_error WifiLegacyHal::initialize() {
344     LOG(DEBUG) << "Initialize legacy HAL";
345     // TODO: Add back the HAL Tool if we need to. All we need from the HAL tool
346     // for now is this function call which we can directly call.
347     if (!initHalFuncTableWithStubs(&global_func_table_)) {
348         LOG(ERROR)
349             << "Failed to initialize legacy hal function table with stubs";
350         return WIFI_ERROR_UNKNOWN;
351     }
352     wifi_error status = init_wifi_vendor_hal_func_table(&global_func_table_);
353     if (status != WIFI_SUCCESS) {
354         LOG(ERROR) << "Failed to initialize legacy hal function table";
355     }
356     return status;
357 }
358 
start()359 wifi_error WifiLegacyHal::start() {
360     // Ensure that we're starting in a good state.
361     CHECK(global_func_table_.wifi_initialize && !global_handle_ &&
362           iface_name_to_handle_.empty() && !awaiting_event_loop_termination_);
363     if (is_started_) {
364         LOG(DEBUG) << "Legacy HAL already started";
365         return WIFI_SUCCESS;
366     }
367     LOG(DEBUG) << "Waiting for the driver ready";
368     wifi_error status = global_func_table_.wifi_wait_for_driver_ready();
369     if (status == WIFI_ERROR_TIMED_OUT) {
370         LOG(ERROR) << "Timed out awaiting driver ready";
371         return status;
372     }
373     property_set(kDriverPropName, "ok");
374 
375     LOG(DEBUG) << "Starting legacy HAL";
376     if (!iface_tool_.lock()->SetWifiUpState(true)) {
377         LOG(ERROR) << "Failed to set WiFi interface up";
378         return WIFI_ERROR_UNKNOWN;
379     }
380     status = global_func_table_.wifi_initialize(&global_handle_);
381     if (status != WIFI_SUCCESS || !global_handle_) {
382         LOG(ERROR) << "Failed to retrieve global handle";
383         return status;
384     }
385     std::thread(&WifiLegacyHal::runEventLoop, this).detach();
386     status = retrieveIfaceHandles();
387     if (status != WIFI_SUCCESS || iface_name_to_handle_.empty()) {
388         LOG(ERROR) << "Failed to retrieve wlan interface handle";
389         return status;
390     }
391     LOG(DEBUG) << "Legacy HAL start complete";
392     is_started_ = true;
393     return WIFI_SUCCESS;
394 }
395 
stop(std::unique_lock<std::recursive_mutex> * lock,const std::function<void ()> & on_stop_complete_user_callback)396 wifi_error WifiLegacyHal::stop(
397     /* NONNULL */ std::unique_lock<std::recursive_mutex>* lock,
398     const std::function<void()>& on_stop_complete_user_callback) {
399     if (!is_started_) {
400         LOG(DEBUG) << "Legacy HAL already stopped";
401         on_stop_complete_user_callback();
402         return WIFI_SUCCESS;
403     }
404     LOG(DEBUG) << "Stopping legacy HAL";
405     on_stop_complete_internal_callback = [on_stop_complete_user_callback,
406                                           this](wifi_handle handle) {
407         CHECK_EQ(global_handle_, handle) << "Handle mismatch";
408         LOG(INFO) << "Legacy HAL stop complete callback received";
409         // Invalidate all the internal pointers now that the HAL is
410         // stopped.
411         invalidate();
412         iface_tool_.lock()->SetWifiUpState(false);
413         on_stop_complete_user_callback();
414         is_started_ = false;
415     };
416     awaiting_event_loop_termination_ = true;
417     global_func_table_.wifi_cleanup(global_handle_, onAsyncStopComplete);
418     const auto status = stop_wait_cv_.wait_for(
419         *lock, std::chrono::milliseconds(kMaxStopCompleteWaitMs),
420         [this] { return !awaiting_event_loop_termination_; });
421     if (!status) {
422         LOG(ERROR) << "Legacy HAL stop failed or timed out";
423         return WIFI_ERROR_UNKNOWN;
424     }
425     LOG(DEBUG) << "Legacy HAL stop complete";
426     return WIFI_SUCCESS;
427 }
428 
isStarted()429 bool WifiLegacyHal::isStarted() { return is_started_; }
430 
getDriverVersion(const std::string & iface_name)431 std::pair<wifi_error, std::string> WifiLegacyHal::getDriverVersion(
432     const std::string& iface_name) {
433     std::array<char, kMaxVersionStringLength> buffer;
434     buffer.fill(0);
435     wifi_error status = global_func_table_.wifi_get_driver_version(
436         getIfaceHandle(iface_name), buffer.data(), buffer.size());
437     return {status, buffer.data()};
438 }
439 
getFirmwareVersion(const std::string & iface_name)440 std::pair<wifi_error, std::string> WifiLegacyHal::getFirmwareVersion(
441     const std::string& iface_name) {
442     std::array<char, kMaxVersionStringLength> buffer;
443     buffer.fill(0);
444     wifi_error status = global_func_table_.wifi_get_firmware_version(
445         getIfaceHandle(iface_name), buffer.data(), buffer.size());
446     return {status, buffer.data()};
447 }
448 
449 std::pair<wifi_error, std::vector<uint8_t>>
requestDriverMemoryDump(const std::string & iface_name)450 WifiLegacyHal::requestDriverMemoryDump(const std::string& iface_name) {
451     std::vector<uint8_t> driver_dump;
452     on_driver_memory_dump_internal_callback = [&driver_dump](char* buffer,
453                                                              int buffer_size) {
454         driver_dump.insert(driver_dump.end(),
455                            reinterpret_cast<uint8_t*>(buffer),
456                            reinterpret_cast<uint8_t*>(buffer) + buffer_size);
457     };
458     wifi_error status = global_func_table_.wifi_get_driver_memory_dump(
459         getIfaceHandle(iface_name), {onSyncDriverMemoryDump});
460     on_driver_memory_dump_internal_callback = nullptr;
461     return {status, std::move(driver_dump)};
462 }
463 
464 std::pair<wifi_error, std::vector<uint8_t>>
requestFirmwareMemoryDump(const std::string & iface_name)465 WifiLegacyHal::requestFirmwareMemoryDump(const std::string& iface_name) {
466     std::vector<uint8_t> firmware_dump;
467     on_firmware_memory_dump_internal_callback =
468         [&firmware_dump](char* buffer, int buffer_size) {
469             firmware_dump.insert(
470                 firmware_dump.end(), reinterpret_cast<uint8_t*>(buffer),
471                 reinterpret_cast<uint8_t*>(buffer) + buffer_size);
472         };
473     wifi_error status = global_func_table_.wifi_get_firmware_memory_dump(
474         getIfaceHandle(iface_name), {onSyncFirmwareMemoryDump});
475     on_firmware_memory_dump_internal_callback = nullptr;
476     return {status, std::move(firmware_dump)};
477 }
478 
getSupportedFeatureSet(const std::string & iface_name)479 std::pair<wifi_error, uint32_t> WifiLegacyHal::getSupportedFeatureSet(
480     const std::string& iface_name) {
481     feature_set set;
482     static_assert(sizeof(set) == sizeof(uint32_t),
483                   "Some feature_flags can not be represented in output");
484     wifi_error status = global_func_table_.wifi_get_supported_feature_set(
485         getIfaceHandle(iface_name), &set);
486     return {status, static_cast<uint32_t>(set)};
487 }
488 
489 std::pair<wifi_error, PacketFilterCapabilities>
getPacketFilterCapabilities(const std::string & iface_name)490 WifiLegacyHal::getPacketFilterCapabilities(const std::string& iface_name) {
491     PacketFilterCapabilities caps;
492     wifi_error status = global_func_table_.wifi_get_packet_filter_capabilities(
493         getIfaceHandle(iface_name), &caps.version, &caps.max_len);
494     return {status, caps};
495 }
496 
setPacketFilter(const std::string & iface_name,const std::vector<uint8_t> & program)497 wifi_error WifiLegacyHal::setPacketFilter(const std::string& iface_name,
498                                           const std::vector<uint8_t>& program) {
499     return global_func_table_.wifi_set_packet_filter(
500         getIfaceHandle(iface_name), program.data(), program.size());
501 }
502 
503 std::pair<wifi_error, std::vector<uint8_t>>
readApfPacketFilterData(const std::string & iface_name)504 WifiLegacyHal::readApfPacketFilterData(const std::string& iface_name) {
505     PacketFilterCapabilities caps;
506     wifi_error status = global_func_table_.wifi_get_packet_filter_capabilities(
507         getIfaceHandle(iface_name), &caps.version, &caps.max_len);
508     if (status != WIFI_SUCCESS) {
509         return {status, {}};
510     }
511 
512     // Size the buffer to read the entire program & work memory.
513     std::vector<uint8_t> buffer(caps.max_len);
514 
515     status = global_func_table_.wifi_read_packet_filter(
516         getIfaceHandle(iface_name), /*src_offset=*/0, buffer.data(),
517         buffer.size());
518     return {status, move(buffer)};
519 }
520 
521 std::pair<wifi_error, wifi_gscan_capabilities>
getGscanCapabilities(const std::string & iface_name)522 WifiLegacyHal::getGscanCapabilities(const std::string& iface_name) {
523     wifi_gscan_capabilities caps;
524     wifi_error status = global_func_table_.wifi_get_gscan_capabilities(
525         getIfaceHandle(iface_name), &caps);
526     return {status, caps};
527 }
528 
startGscan(const std::string & iface_name,wifi_request_id id,const wifi_scan_cmd_params & params,const std::function<void (wifi_request_id)> & on_failure_user_callback,const on_gscan_results_callback & on_results_user_callback,const on_gscan_full_result_callback & on_full_result_user_callback)529 wifi_error WifiLegacyHal::startGscan(
530     const std::string& iface_name, wifi_request_id id,
531     const wifi_scan_cmd_params& params,
532     const std::function<void(wifi_request_id)>& on_failure_user_callback,
533     const on_gscan_results_callback& on_results_user_callback,
534     const on_gscan_full_result_callback& on_full_result_user_callback) {
535     // If there is already an ongoing background scan, reject new scan requests.
536     if (on_gscan_event_internal_callback ||
537         on_gscan_full_result_internal_callback) {
538         return WIFI_ERROR_NOT_AVAILABLE;
539     }
540 
541     // This callback will be used to either trigger |on_results_user_callback|
542     // or |on_failure_user_callback|.
543     on_gscan_event_internal_callback =
544         [iface_name, on_failure_user_callback, on_results_user_callback, this](
545             wifi_request_id id, wifi_scan_event event) {
546             switch (event) {
547                 case WIFI_SCAN_RESULTS_AVAILABLE:
548                 case WIFI_SCAN_THRESHOLD_NUM_SCANS:
549                 case WIFI_SCAN_THRESHOLD_PERCENT: {
550                     wifi_error status;
551                     std::vector<wifi_cached_scan_results> cached_scan_results;
552                     std::tie(status, cached_scan_results) =
553                         getGscanCachedResults(iface_name);
554                     if (status == WIFI_SUCCESS) {
555                         on_results_user_callback(id, cached_scan_results);
556                         return;
557                     }
558                     FALLTHROUGH_INTENDED;
559                 }
560                 // Fall through if failed. Failure to retrieve cached scan
561                 // results should trigger a background scan failure.
562                 case WIFI_SCAN_FAILED:
563                     on_failure_user_callback(id);
564                     on_gscan_event_internal_callback = nullptr;
565                     on_gscan_full_result_internal_callback = nullptr;
566                     return;
567             }
568             LOG(FATAL) << "Unexpected gscan event received: " << event;
569         };
570 
571     on_gscan_full_result_internal_callback = [on_full_result_user_callback](
572                                                  wifi_request_id id,
573                                                  wifi_scan_result* result,
574                                                  uint32_t buckets_scanned) {
575         if (result) {
576             on_full_result_user_callback(id, result, buckets_scanned);
577         }
578     };
579 
580     wifi_scan_result_handler handler = {onAsyncGscanFullResult,
581                                         onAsyncGscanEvent};
582     wifi_error status = global_func_table_.wifi_start_gscan(
583         id, getIfaceHandle(iface_name), params, handler);
584     if (status != WIFI_SUCCESS) {
585         on_gscan_event_internal_callback = nullptr;
586         on_gscan_full_result_internal_callback = nullptr;
587     }
588     return status;
589 }
590 
stopGscan(const std::string & iface_name,wifi_request_id id)591 wifi_error WifiLegacyHal::stopGscan(const std::string& iface_name,
592                                     wifi_request_id id) {
593     // If there is no an ongoing background scan, reject stop requests.
594     // TODO(b/32337212): This needs to be handled by the HIDL object because we
595     // need to return the NOT_STARTED error code.
596     if (!on_gscan_event_internal_callback &&
597         !on_gscan_full_result_internal_callback) {
598         return WIFI_ERROR_NOT_AVAILABLE;
599     }
600     wifi_error status =
601         global_func_table_.wifi_stop_gscan(id, getIfaceHandle(iface_name));
602     // If the request Id is wrong, don't stop the ongoing background scan. Any
603     // other error should be treated as the end of background scan.
604     if (status != WIFI_ERROR_INVALID_REQUEST_ID) {
605         on_gscan_event_internal_callback = nullptr;
606         on_gscan_full_result_internal_callback = nullptr;
607     }
608     return status;
609 }
610 
611 std::pair<wifi_error, std::vector<uint32_t>>
getValidFrequenciesForBand(const std::string & iface_name,wifi_band band)612 WifiLegacyHal::getValidFrequenciesForBand(const std::string& iface_name,
613                                           wifi_band band) {
614     static_assert(sizeof(uint32_t) >= sizeof(wifi_channel),
615                   "Wifi Channel cannot be represented in output");
616     std::vector<uint32_t> freqs;
617     freqs.resize(kMaxGscanFrequenciesForBand);
618     int32_t num_freqs = 0;
619     wifi_error status = global_func_table_.wifi_get_valid_channels(
620         getIfaceHandle(iface_name), band, freqs.size(),
621         reinterpret_cast<wifi_channel*>(freqs.data()), &num_freqs);
622     CHECK(num_freqs >= 0 &&
623           static_cast<uint32_t>(num_freqs) <= kMaxGscanFrequenciesForBand);
624     freqs.resize(num_freqs);
625     return {status, std::move(freqs)};
626 }
627 
setDfsFlag(const std::string & iface_name,bool dfs_on)628 wifi_error WifiLegacyHal::setDfsFlag(const std::string& iface_name,
629                                      bool dfs_on) {
630     return global_func_table_.wifi_set_nodfs_flag(getIfaceHandle(iface_name),
631                                                   dfs_on ? 0 : 1);
632 }
633 
enableLinkLayerStats(const std::string & iface_name,bool debug)634 wifi_error WifiLegacyHal::enableLinkLayerStats(const std::string& iface_name,
635                                                bool debug) {
636     wifi_link_layer_params params;
637     params.mpdu_size_threshold = kLinkLayerStatsDataMpduSizeThreshold;
638     params.aggressive_statistics_gathering = debug;
639     return global_func_table_.wifi_set_link_stats(getIfaceHandle(iface_name),
640                                                   params);
641 }
642 
disableLinkLayerStats(const std::string & iface_name)643 wifi_error WifiLegacyHal::disableLinkLayerStats(const std::string& iface_name) {
644     // TODO: Do we care about these responses?
645     uint32_t clear_mask_rsp;
646     uint8_t stop_rsp;
647     return global_func_table_.wifi_clear_link_stats(
648         getIfaceHandle(iface_name), 0xFFFFFFFF, &clear_mask_rsp, 1, &stop_rsp);
649 }
650 
getLinkLayerStats(const std::string & iface_name)651 std::pair<wifi_error, LinkLayerStats> WifiLegacyHal::getLinkLayerStats(
652     const std::string& iface_name) {
653     LinkLayerStats link_stats{};
654     LinkLayerStats* link_stats_ptr = &link_stats;
655 
656     on_link_layer_stats_result_internal_callback =
657         [&link_stats_ptr](wifi_request_id /* id */,
658                           wifi_iface_stat* iface_stats_ptr, int num_radios,
659                           wifi_radio_stat* radio_stats_ptr) {
660             wifi_radio_stat* l_radio_stats_ptr;
661 
662             if (iface_stats_ptr != nullptr) {
663                 link_stats_ptr->iface = *iface_stats_ptr;
664                 link_stats_ptr->iface.num_peers = 0;
665             } else {
666                 LOG(ERROR) << "Invalid iface stats in link layer stats";
667             }
668             if (num_radios <= 0 || radio_stats_ptr == nullptr) {
669                 LOG(ERROR) << "Invalid radio stats in link layer stats";
670                 return;
671             }
672             l_radio_stats_ptr = radio_stats_ptr;
673             for (int i = 0; i < num_radios; i++) {
674                 LinkLayerRadioStats radio;
675 
676                 radio.stats = *l_radio_stats_ptr;
677                 // Copy over the tx level array to the separate vector.
678                 if (l_radio_stats_ptr->num_tx_levels > 0 &&
679                     l_radio_stats_ptr->tx_time_per_levels != nullptr) {
680                     radio.tx_time_per_levels.assign(
681                         l_radio_stats_ptr->tx_time_per_levels,
682                         l_radio_stats_ptr->tx_time_per_levels +
683                             l_radio_stats_ptr->num_tx_levels);
684                 }
685                 radio.stats.num_tx_levels = 0;
686                 radio.stats.tx_time_per_levels = nullptr;
687                 /* Copy over the channel stat to separate vector */
688                 if (l_radio_stats_ptr->num_channels > 0) {
689                     /* Copy the channel stats */
690                     radio.channel_stats.assign(
691                         l_radio_stats_ptr->channels,
692                         l_radio_stats_ptr->channels +
693                             l_radio_stats_ptr->num_channels);
694                 }
695                 link_stats_ptr->radios.push_back(radio);
696                 l_radio_stats_ptr =
697                     (wifi_radio_stat*)((u8*)l_radio_stats_ptr +
698                                        sizeof(wifi_radio_stat) +
699                                        (sizeof(wifi_channel_stat) *
700                                         l_radio_stats_ptr->num_channels));
701             }
702         };
703 
704     wifi_error status = global_func_table_.wifi_get_link_stats(
705         0, getIfaceHandle(iface_name), {onSyncLinkLayerStatsResult});
706     on_link_layer_stats_result_internal_callback = nullptr;
707     return {status, link_stats};
708 }
709 
startRssiMonitoring(const std::string & iface_name,wifi_request_id id,int8_t max_rssi,int8_t min_rssi,const on_rssi_threshold_breached_callback & on_threshold_breached_user_callback)710 wifi_error WifiLegacyHal::startRssiMonitoring(
711     const std::string& iface_name, wifi_request_id id, int8_t max_rssi,
712     int8_t min_rssi,
713     const on_rssi_threshold_breached_callback&
714         on_threshold_breached_user_callback) {
715     if (on_rssi_threshold_breached_internal_callback) {
716         return WIFI_ERROR_NOT_AVAILABLE;
717     }
718     on_rssi_threshold_breached_internal_callback =
719         [on_threshold_breached_user_callback](wifi_request_id id,
720                                               uint8_t* bssid_ptr, int8_t rssi) {
721             if (!bssid_ptr) {
722                 return;
723             }
724             std::array<uint8_t, 6> bssid_arr;
725             // |bssid_ptr| pointer is assumed to have 6 bytes for the mac
726             // address.
727             std::copy(bssid_ptr, bssid_ptr + 6, std::begin(bssid_arr));
728             on_threshold_breached_user_callback(id, bssid_arr, rssi);
729         };
730     wifi_error status = global_func_table_.wifi_start_rssi_monitoring(
731         id, getIfaceHandle(iface_name), max_rssi, min_rssi,
732         {onAsyncRssiThresholdBreached});
733     if (status != WIFI_SUCCESS) {
734         on_rssi_threshold_breached_internal_callback = nullptr;
735     }
736     return status;
737 }
738 
stopRssiMonitoring(const std::string & iface_name,wifi_request_id id)739 wifi_error WifiLegacyHal::stopRssiMonitoring(const std::string& iface_name,
740                                              wifi_request_id id) {
741     if (!on_rssi_threshold_breached_internal_callback) {
742         return WIFI_ERROR_NOT_AVAILABLE;
743     }
744     wifi_error status = global_func_table_.wifi_stop_rssi_monitoring(
745         id, getIfaceHandle(iface_name));
746     // If the request Id is wrong, don't stop the ongoing rssi monitoring. Any
747     // other error should be treated as the end of background scan.
748     if (status != WIFI_ERROR_INVALID_REQUEST_ID) {
749         on_rssi_threshold_breached_internal_callback = nullptr;
750     }
751     return status;
752 }
753 
754 std::pair<wifi_error, wifi_roaming_capabilities>
getRoamingCapabilities(const std::string & iface_name)755 WifiLegacyHal::getRoamingCapabilities(const std::string& iface_name) {
756     wifi_roaming_capabilities caps;
757     wifi_error status = global_func_table_.wifi_get_roaming_capabilities(
758         getIfaceHandle(iface_name), &caps);
759     return {status, caps};
760 }
761 
configureRoaming(const std::string & iface_name,const wifi_roaming_config & config)762 wifi_error WifiLegacyHal::configureRoaming(const std::string& iface_name,
763                                            const wifi_roaming_config& config) {
764     wifi_roaming_config config_internal = config;
765     return global_func_table_.wifi_configure_roaming(getIfaceHandle(iface_name),
766                                                      &config_internal);
767 }
768 
enableFirmwareRoaming(const std::string & iface_name,fw_roaming_state_t state)769 wifi_error WifiLegacyHal::enableFirmwareRoaming(const std::string& iface_name,
770                                                 fw_roaming_state_t state) {
771     return global_func_table_.wifi_enable_firmware_roaming(
772         getIfaceHandle(iface_name), state);
773 }
774 
configureNdOffload(const std::string & iface_name,bool enable)775 wifi_error WifiLegacyHal::configureNdOffload(const std::string& iface_name,
776                                              bool enable) {
777     return global_func_table_.wifi_configure_nd_offload(
778         getIfaceHandle(iface_name), enable);
779 }
780 
startSendingOffloadedPacket(const std::string & iface_name,uint32_t cmd_id,uint16_t ether_type,const std::vector<uint8_t> & ip_packet_data,const std::array<uint8_t,6> & src_address,const std::array<uint8_t,6> & dst_address,uint32_t period_in_ms)781 wifi_error WifiLegacyHal::startSendingOffloadedPacket(
782     const std::string& iface_name, uint32_t cmd_id, uint16_t ether_type,
783     const std::vector<uint8_t>& ip_packet_data,
784     const std::array<uint8_t, 6>& src_address,
785     const std::array<uint8_t, 6>& dst_address, uint32_t period_in_ms) {
786     std::vector<uint8_t> ip_packet_data_internal(ip_packet_data);
787     std::vector<uint8_t> src_address_internal(
788         src_address.data(), src_address.data() + src_address.size());
789     std::vector<uint8_t> dst_address_internal(
790         dst_address.data(), dst_address.data() + dst_address.size());
791     return global_func_table_.wifi_start_sending_offloaded_packet(
792         cmd_id, getIfaceHandle(iface_name), ether_type,
793         ip_packet_data_internal.data(), ip_packet_data_internal.size(),
794         src_address_internal.data(), dst_address_internal.data(), period_in_ms);
795 }
796 
stopSendingOffloadedPacket(const std::string & iface_name,uint32_t cmd_id)797 wifi_error WifiLegacyHal::stopSendingOffloadedPacket(
798     const std::string& iface_name, uint32_t cmd_id) {
799     return global_func_table_.wifi_stop_sending_offloaded_packet(
800         cmd_id, getIfaceHandle(iface_name));
801 }
802 
setScanningMacOui(const std::string & iface_name,const std::array<uint8_t,3> & oui)803 wifi_error WifiLegacyHal::setScanningMacOui(const std::string& iface_name,
804                                             const std::array<uint8_t, 3>& oui) {
805     std::vector<uint8_t> oui_internal(oui.data(), oui.data() + oui.size());
806     return global_func_table_.wifi_set_scanning_mac_oui(
807         getIfaceHandle(iface_name), oui_internal.data());
808 }
809 
selectTxPowerScenario(const std::string & iface_name,wifi_power_scenario scenario)810 wifi_error WifiLegacyHal::selectTxPowerScenario(const std::string& iface_name,
811                                                 wifi_power_scenario scenario) {
812     return global_func_table_.wifi_select_tx_power_scenario(
813         getIfaceHandle(iface_name), scenario);
814 }
815 
resetTxPowerScenario(const std::string & iface_name)816 wifi_error WifiLegacyHal::resetTxPowerScenario(const std::string& iface_name) {
817     return global_func_table_.wifi_reset_tx_power_scenario(
818         getIfaceHandle(iface_name));
819 }
820 
setLatencyMode(const std::string & iface_name,wifi_latency_mode mode)821 wifi_error WifiLegacyHal::setLatencyMode(const std::string& iface_name,
822                                          wifi_latency_mode mode) {
823     return global_func_table_.wifi_set_latency_mode(getIfaceHandle(iface_name),
824                                                     mode);
825 }
826 
getLoggerSupportedFeatureSet(const std::string & iface_name)827 std::pair<wifi_error, uint32_t> WifiLegacyHal::getLoggerSupportedFeatureSet(
828     const std::string& iface_name) {
829     uint32_t supported_feature_flags;
830     wifi_error status =
831         global_func_table_.wifi_get_logger_supported_feature_set(
832             getIfaceHandle(iface_name), &supported_feature_flags);
833     return {status, supported_feature_flags};
834 }
835 
startPktFateMonitoring(const std::string & iface_name)836 wifi_error WifiLegacyHal::startPktFateMonitoring(
837     const std::string& iface_name) {
838     return global_func_table_.wifi_start_pkt_fate_monitoring(
839         getIfaceHandle(iface_name));
840 }
841 
getTxPktFates(const std::string & iface_name)842 std::pair<wifi_error, std::vector<wifi_tx_report>> WifiLegacyHal::getTxPktFates(
843     const std::string& iface_name) {
844     std::vector<wifi_tx_report> tx_pkt_fates;
845     tx_pkt_fates.resize(MAX_FATE_LOG_LEN);
846     size_t num_fates = 0;
847     wifi_error status = global_func_table_.wifi_get_tx_pkt_fates(
848         getIfaceHandle(iface_name), tx_pkt_fates.data(), tx_pkt_fates.size(),
849         &num_fates);
850     CHECK(num_fates <= MAX_FATE_LOG_LEN);
851     tx_pkt_fates.resize(num_fates);
852     return {status, std::move(tx_pkt_fates)};
853 }
854 
getRxPktFates(const std::string & iface_name)855 std::pair<wifi_error, std::vector<wifi_rx_report>> WifiLegacyHal::getRxPktFates(
856     const std::string& iface_name) {
857     std::vector<wifi_rx_report> rx_pkt_fates;
858     rx_pkt_fates.resize(MAX_FATE_LOG_LEN);
859     size_t num_fates = 0;
860     wifi_error status = global_func_table_.wifi_get_rx_pkt_fates(
861         getIfaceHandle(iface_name), rx_pkt_fates.data(), rx_pkt_fates.size(),
862         &num_fates);
863     CHECK(num_fates <= MAX_FATE_LOG_LEN);
864     rx_pkt_fates.resize(num_fates);
865     return {status, std::move(rx_pkt_fates)};
866 }
867 
getWakeReasonStats(const std::string & iface_name)868 std::pair<wifi_error, WakeReasonStats> WifiLegacyHal::getWakeReasonStats(
869     const std::string& iface_name) {
870     WakeReasonStats stats;
871     stats.cmd_event_wake_cnt.resize(kMaxWakeReasonStatsArraySize);
872     stats.driver_fw_local_wake_cnt.resize(kMaxWakeReasonStatsArraySize);
873 
874     // This legacy struct needs separate memory to store the variable sized wake
875     // reason types.
876     stats.wake_reason_cnt.cmd_event_wake_cnt =
877         reinterpret_cast<int32_t*>(stats.cmd_event_wake_cnt.data());
878     stats.wake_reason_cnt.cmd_event_wake_cnt_sz =
879         stats.cmd_event_wake_cnt.size();
880     stats.wake_reason_cnt.cmd_event_wake_cnt_used = 0;
881     stats.wake_reason_cnt.driver_fw_local_wake_cnt =
882         reinterpret_cast<int32_t*>(stats.driver_fw_local_wake_cnt.data());
883     stats.wake_reason_cnt.driver_fw_local_wake_cnt_sz =
884         stats.driver_fw_local_wake_cnt.size();
885     stats.wake_reason_cnt.driver_fw_local_wake_cnt_used = 0;
886 
887     wifi_error status = global_func_table_.wifi_get_wake_reason_stats(
888         getIfaceHandle(iface_name), &stats.wake_reason_cnt);
889 
890     CHECK(
891         stats.wake_reason_cnt.cmd_event_wake_cnt_used >= 0 &&
892         static_cast<uint32_t>(stats.wake_reason_cnt.cmd_event_wake_cnt_used) <=
893             kMaxWakeReasonStatsArraySize);
894     stats.cmd_event_wake_cnt.resize(
895         stats.wake_reason_cnt.cmd_event_wake_cnt_used);
896     stats.wake_reason_cnt.cmd_event_wake_cnt = nullptr;
897 
898     CHECK(stats.wake_reason_cnt.driver_fw_local_wake_cnt_used >= 0 &&
899           static_cast<uint32_t>(
900               stats.wake_reason_cnt.driver_fw_local_wake_cnt_used) <=
901               kMaxWakeReasonStatsArraySize);
902     stats.driver_fw_local_wake_cnt.resize(
903         stats.wake_reason_cnt.driver_fw_local_wake_cnt_used);
904     stats.wake_reason_cnt.driver_fw_local_wake_cnt = nullptr;
905 
906     return {status, stats};
907 }
908 
registerRingBufferCallbackHandler(const std::string & iface_name,const on_ring_buffer_data_callback & on_user_data_callback)909 wifi_error WifiLegacyHal::registerRingBufferCallbackHandler(
910     const std::string& iface_name,
911     const on_ring_buffer_data_callback& on_user_data_callback) {
912     if (on_ring_buffer_data_internal_callback) {
913         return WIFI_ERROR_NOT_AVAILABLE;
914     }
915     on_ring_buffer_data_internal_callback =
916         [on_user_data_callback](char* ring_name, char* buffer, int buffer_size,
917                                 wifi_ring_buffer_status* status) {
918             if (status && buffer) {
919                 std::vector<uint8_t> buffer_vector(
920                     reinterpret_cast<uint8_t*>(buffer),
921                     reinterpret_cast<uint8_t*>(buffer) + buffer_size);
922                 on_user_data_callback(ring_name, buffer_vector, *status);
923             }
924         };
925     wifi_error status = global_func_table_.wifi_set_log_handler(
926         0, getIfaceHandle(iface_name), {onAsyncRingBufferData});
927     if (status != WIFI_SUCCESS) {
928         on_ring_buffer_data_internal_callback = nullptr;
929     }
930     return status;
931 }
932 
deregisterRingBufferCallbackHandler(const std::string & iface_name)933 wifi_error WifiLegacyHal::deregisterRingBufferCallbackHandler(
934     const std::string& iface_name) {
935     if (!on_ring_buffer_data_internal_callback) {
936         return WIFI_ERROR_NOT_AVAILABLE;
937     }
938     on_ring_buffer_data_internal_callback = nullptr;
939     return global_func_table_.wifi_reset_log_handler(
940         0, getIfaceHandle(iface_name));
941 }
942 
943 std::pair<wifi_error, std::vector<wifi_ring_buffer_status>>
getRingBuffersStatus(const std::string & iface_name)944 WifiLegacyHal::getRingBuffersStatus(const std::string& iface_name) {
945     std::vector<wifi_ring_buffer_status> ring_buffers_status;
946     ring_buffers_status.resize(kMaxRingBuffers);
947     uint32_t num_rings = kMaxRingBuffers;
948     wifi_error status = global_func_table_.wifi_get_ring_buffers_status(
949         getIfaceHandle(iface_name), &num_rings, ring_buffers_status.data());
950     CHECK(num_rings <= kMaxRingBuffers);
951     ring_buffers_status.resize(num_rings);
952     return {status, std::move(ring_buffers_status)};
953 }
954 
startRingBufferLogging(const std::string & iface_name,const std::string & ring_name,uint32_t verbose_level,uint32_t max_interval_sec,uint32_t min_data_size)955 wifi_error WifiLegacyHal::startRingBufferLogging(const std::string& iface_name,
956                                                  const std::string& ring_name,
957                                                  uint32_t verbose_level,
958                                                  uint32_t max_interval_sec,
959                                                  uint32_t min_data_size) {
960     return global_func_table_.wifi_start_logging(
961         getIfaceHandle(iface_name), verbose_level, 0, max_interval_sec,
962         min_data_size, makeCharVec(ring_name).data());
963 }
964 
getRingBufferData(const std::string & iface_name,const std::string & ring_name)965 wifi_error WifiLegacyHal::getRingBufferData(const std::string& iface_name,
966                                             const std::string& ring_name) {
967     return global_func_table_.wifi_get_ring_data(getIfaceHandle(iface_name),
968                                                  makeCharVec(ring_name).data());
969 }
970 
registerErrorAlertCallbackHandler(const std::string & iface_name,const on_error_alert_callback & on_user_alert_callback)971 wifi_error WifiLegacyHal::registerErrorAlertCallbackHandler(
972     const std::string& iface_name,
973     const on_error_alert_callback& on_user_alert_callback) {
974     if (on_error_alert_internal_callback) {
975         return WIFI_ERROR_NOT_AVAILABLE;
976     }
977     on_error_alert_internal_callback = [on_user_alert_callback](
978                                            wifi_request_id id, char* buffer,
979                                            int buffer_size, int err_code) {
980         if (buffer) {
981             CHECK(id == 0);
982             on_user_alert_callback(
983                 err_code,
984                 std::vector<uint8_t>(
985                     reinterpret_cast<uint8_t*>(buffer),
986                     reinterpret_cast<uint8_t*>(buffer) + buffer_size));
987         }
988     };
989     wifi_error status = global_func_table_.wifi_set_alert_handler(
990         0, getIfaceHandle(iface_name), {onAsyncErrorAlert});
991     if (status != WIFI_SUCCESS) {
992         on_error_alert_internal_callback = nullptr;
993     }
994     return status;
995 }
996 
deregisterErrorAlertCallbackHandler(const std::string & iface_name)997 wifi_error WifiLegacyHal::deregisterErrorAlertCallbackHandler(
998     const std::string& iface_name) {
999     if (!on_error_alert_internal_callback) {
1000         return WIFI_ERROR_NOT_AVAILABLE;
1001     }
1002     on_error_alert_internal_callback = nullptr;
1003     return global_func_table_.wifi_reset_alert_handler(
1004         0, getIfaceHandle(iface_name));
1005 }
1006 
registerRadioModeChangeCallbackHandler(const std::string & iface_name,const on_radio_mode_change_callback & on_user_change_callback)1007 wifi_error WifiLegacyHal::registerRadioModeChangeCallbackHandler(
1008     const std::string& iface_name,
1009     const on_radio_mode_change_callback& on_user_change_callback) {
1010     if (on_radio_mode_change_internal_callback) {
1011         return WIFI_ERROR_NOT_AVAILABLE;
1012     }
1013     on_radio_mode_change_internal_callback = [on_user_change_callback](
1014                                                  wifi_request_id /* id */,
1015                                                  uint32_t num_macs,
1016                                                  wifi_mac_info* mac_infos_arr) {
1017         if (num_macs > 0 && mac_infos_arr) {
1018             std::vector<WifiMacInfo> mac_infos_vec;
1019             for (uint32_t i = 0; i < num_macs; i++) {
1020                 WifiMacInfo mac_info;
1021                 mac_info.wlan_mac_id = mac_infos_arr[i].wlan_mac_id;
1022                 mac_info.mac_band = mac_infos_arr[i].mac_band;
1023                 for (int32_t j = 0; j < mac_infos_arr[i].num_iface; j++) {
1024                     WifiIfaceInfo iface_info;
1025                     iface_info.name = mac_infos_arr[i].iface_info[j].iface_name;
1026                     iface_info.channel = mac_infos_arr[i].iface_info[j].channel;
1027                     mac_info.iface_infos.push_back(iface_info);
1028                 }
1029                 mac_infos_vec.push_back(mac_info);
1030             }
1031             on_user_change_callback(mac_infos_vec);
1032         }
1033     };
1034     wifi_error status = global_func_table_.wifi_set_radio_mode_change_handler(
1035         0, getIfaceHandle(iface_name), {onAsyncRadioModeChange});
1036     if (status != WIFI_SUCCESS) {
1037         on_radio_mode_change_internal_callback = nullptr;
1038     }
1039     return status;
1040 }
1041 
startRttRangeRequest(const std::string & iface_name,wifi_request_id id,const std::vector<wifi_rtt_config> & rtt_configs,const on_rtt_results_callback & on_results_user_callback)1042 wifi_error WifiLegacyHal::startRttRangeRequest(
1043     const std::string& iface_name, wifi_request_id id,
1044     const std::vector<wifi_rtt_config>& rtt_configs,
1045     const on_rtt_results_callback& on_results_user_callback) {
1046     if (on_rtt_results_internal_callback) {
1047         return WIFI_ERROR_NOT_AVAILABLE;
1048     }
1049 
1050     on_rtt_results_internal_callback =
1051         [on_results_user_callback](wifi_request_id id, unsigned num_results,
1052                                    wifi_rtt_result* rtt_results[]) {
1053             if (num_results > 0 && !rtt_results) {
1054                 LOG(ERROR) << "Unexpected nullptr in RTT results";
1055                 return;
1056             }
1057             std::vector<const wifi_rtt_result*> rtt_results_vec;
1058             std::copy_if(rtt_results, rtt_results + num_results,
1059                          back_inserter(rtt_results_vec),
1060                          [](wifi_rtt_result* rtt_result) {
1061                              return rtt_result != nullptr;
1062                          });
1063             on_results_user_callback(id, rtt_results_vec);
1064         };
1065 
1066     std::vector<wifi_rtt_config> rtt_configs_internal(rtt_configs);
1067     wifi_error status = global_func_table_.wifi_rtt_range_request(
1068         id, getIfaceHandle(iface_name), rtt_configs.size(),
1069         rtt_configs_internal.data(), {onAsyncRttResults});
1070     if (status != WIFI_SUCCESS) {
1071         on_rtt_results_internal_callback = nullptr;
1072     }
1073     return status;
1074 }
1075 
cancelRttRangeRequest(const std::string & iface_name,wifi_request_id id,const std::vector<std::array<uint8_t,6>> & mac_addrs)1076 wifi_error WifiLegacyHal::cancelRttRangeRequest(
1077     const std::string& iface_name, wifi_request_id id,
1078     const std::vector<std::array<uint8_t, 6>>& mac_addrs) {
1079     if (!on_rtt_results_internal_callback) {
1080         return WIFI_ERROR_NOT_AVAILABLE;
1081     }
1082     static_assert(sizeof(mac_addr) == sizeof(std::array<uint8_t, 6>),
1083                   "MAC address size mismatch");
1084     // TODO: How do we handle partial cancels (i.e only a subset of enabled mac
1085     // addressed are cancelled).
1086     std::vector<std::array<uint8_t, 6>> mac_addrs_internal(mac_addrs);
1087     wifi_error status = global_func_table_.wifi_rtt_range_cancel(
1088         id, getIfaceHandle(iface_name), mac_addrs.size(),
1089         reinterpret_cast<mac_addr*>(mac_addrs_internal.data()));
1090     // If the request Id is wrong, don't stop the ongoing range request. Any
1091     // other error should be treated as the end of rtt ranging.
1092     if (status != WIFI_ERROR_INVALID_REQUEST_ID) {
1093         on_rtt_results_internal_callback = nullptr;
1094     }
1095     return status;
1096 }
1097 
getRttCapabilities(const std::string & iface_name)1098 std::pair<wifi_error, wifi_rtt_capabilities> WifiLegacyHal::getRttCapabilities(
1099     const std::string& iface_name) {
1100     wifi_rtt_capabilities rtt_caps;
1101     wifi_error status = global_func_table_.wifi_get_rtt_capabilities(
1102         getIfaceHandle(iface_name), &rtt_caps);
1103     return {status, rtt_caps};
1104 }
1105 
getRttResponderInfo(const std::string & iface_name)1106 std::pair<wifi_error, wifi_rtt_responder> WifiLegacyHal::getRttResponderInfo(
1107     const std::string& iface_name) {
1108     wifi_rtt_responder rtt_responder;
1109     wifi_error status = global_func_table_.wifi_rtt_get_responder_info(
1110         getIfaceHandle(iface_name), &rtt_responder);
1111     return {status, rtt_responder};
1112 }
1113 
enableRttResponder(const std::string & iface_name,wifi_request_id id,const wifi_channel_info & channel_hint,uint32_t max_duration_secs,const wifi_rtt_responder & info)1114 wifi_error WifiLegacyHal::enableRttResponder(
1115     const std::string& iface_name, wifi_request_id id,
1116     const wifi_channel_info& channel_hint, uint32_t max_duration_secs,
1117     const wifi_rtt_responder& info) {
1118     wifi_rtt_responder info_internal(info);
1119     return global_func_table_.wifi_enable_responder(
1120         id, getIfaceHandle(iface_name), channel_hint, max_duration_secs,
1121         &info_internal);
1122 }
1123 
disableRttResponder(const std::string & iface_name,wifi_request_id id)1124 wifi_error WifiLegacyHal::disableRttResponder(const std::string& iface_name,
1125                                               wifi_request_id id) {
1126     return global_func_table_.wifi_disable_responder(
1127         id, getIfaceHandle(iface_name));
1128 }
1129 
setRttLci(const std::string & iface_name,wifi_request_id id,const wifi_lci_information & info)1130 wifi_error WifiLegacyHal::setRttLci(const std::string& iface_name,
1131                                     wifi_request_id id,
1132                                     const wifi_lci_information& info) {
1133     wifi_lci_information info_internal(info);
1134     return global_func_table_.wifi_set_lci(id, getIfaceHandle(iface_name),
1135                                            &info_internal);
1136 }
1137 
setRttLcr(const std::string & iface_name,wifi_request_id id,const wifi_lcr_information & info)1138 wifi_error WifiLegacyHal::setRttLcr(const std::string& iface_name,
1139                                     wifi_request_id id,
1140                                     const wifi_lcr_information& info) {
1141     wifi_lcr_information info_internal(info);
1142     return global_func_table_.wifi_set_lcr(id, getIfaceHandle(iface_name),
1143                                            &info_internal);
1144 }
1145 
nanRegisterCallbackHandlers(const std::string & iface_name,const NanCallbackHandlers & user_callbacks)1146 wifi_error WifiLegacyHal::nanRegisterCallbackHandlers(
1147     const std::string& iface_name, const NanCallbackHandlers& user_callbacks) {
1148     on_nan_notify_response_user_callback = user_callbacks.on_notify_response;
1149     on_nan_event_publish_terminated_user_callback =
1150         user_callbacks.on_event_publish_terminated;
1151     on_nan_event_match_user_callback = user_callbacks.on_event_match;
1152     on_nan_event_match_expired_user_callback =
1153         user_callbacks.on_event_match_expired;
1154     on_nan_event_subscribe_terminated_user_callback =
1155         user_callbacks.on_event_subscribe_terminated;
1156     on_nan_event_followup_user_callback = user_callbacks.on_event_followup;
1157     on_nan_event_disc_eng_event_user_callback =
1158         user_callbacks.on_event_disc_eng_event;
1159     on_nan_event_disabled_user_callback = user_callbacks.on_event_disabled;
1160     on_nan_event_tca_user_callback = user_callbacks.on_event_tca;
1161     on_nan_event_beacon_sdf_payload_user_callback =
1162         user_callbacks.on_event_beacon_sdf_payload;
1163     on_nan_event_data_path_request_user_callback =
1164         user_callbacks.on_event_data_path_request;
1165     on_nan_event_data_path_confirm_user_callback =
1166         user_callbacks.on_event_data_path_confirm;
1167     on_nan_event_data_path_end_user_callback =
1168         user_callbacks.on_event_data_path_end;
1169     on_nan_event_transmit_follow_up_user_callback =
1170         user_callbacks.on_event_transmit_follow_up;
1171     on_nan_event_range_request_user_callback =
1172         user_callbacks.on_event_range_request;
1173     on_nan_event_range_report_user_callback =
1174         user_callbacks.on_event_range_report;
1175     on_nan_event_schedule_update_user_callback =
1176         user_callbacks.on_event_schedule_update;
1177 
1178     return global_func_table_.wifi_nan_register_handler(
1179         getIfaceHandle(iface_name),
1180         {onAysncNanNotifyResponse, onAysncNanEventPublishReplied,
1181          onAysncNanEventPublishTerminated, onAysncNanEventMatch,
1182          onAysncNanEventMatchExpired, onAysncNanEventSubscribeTerminated,
1183          onAysncNanEventFollowup, onAysncNanEventDiscEngEvent,
1184          onAysncNanEventDisabled, onAysncNanEventTca,
1185          onAysncNanEventBeaconSdfPayload, onAysncNanEventDataPathRequest,
1186          onAysncNanEventDataPathConfirm, onAysncNanEventDataPathEnd,
1187          onAysncNanEventTransmitFollowUp, onAysncNanEventRangeRequest,
1188          onAysncNanEventRangeReport, onAsyncNanEventScheduleUpdate});
1189 }
1190 
nanEnableRequest(const std::string & iface_name,transaction_id id,const NanEnableRequest & msg)1191 wifi_error WifiLegacyHal::nanEnableRequest(const std::string& iface_name,
1192                                            transaction_id id,
1193                                            const NanEnableRequest& msg) {
1194     NanEnableRequest msg_internal(msg);
1195     return global_func_table_.wifi_nan_enable_request(
1196         id, getIfaceHandle(iface_name), &msg_internal);
1197 }
1198 
nanDisableRequest(const std::string & iface_name,transaction_id id)1199 wifi_error WifiLegacyHal::nanDisableRequest(const std::string& iface_name,
1200                                             transaction_id id) {
1201     return global_func_table_.wifi_nan_disable_request(
1202         id, getIfaceHandle(iface_name));
1203 }
1204 
nanPublishRequest(const std::string & iface_name,transaction_id id,const NanPublishRequest & msg)1205 wifi_error WifiLegacyHal::nanPublishRequest(const std::string& iface_name,
1206                                             transaction_id id,
1207                                             const NanPublishRequest& msg) {
1208     NanPublishRequest msg_internal(msg);
1209     return global_func_table_.wifi_nan_publish_request(
1210         id, getIfaceHandle(iface_name), &msg_internal);
1211 }
1212 
nanPublishCancelRequest(const std::string & iface_name,transaction_id id,const NanPublishCancelRequest & msg)1213 wifi_error WifiLegacyHal::nanPublishCancelRequest(
1214     const std::string& iface_name, transaction_id id,
1215     const NanPublishCancelRequest& msg) {
1216     NanPublishCancelRequest msg_internal(msg);
1217     return global_func_table_.wifi_nan_publish_cancel_request(
1218         id, getIfaceHandle(iface_name), &msg_internal);
1219 }
1220 
nanSubscribeRequest(const std::string & iface_name,transaction_id id,const NanSubscribeRequest & msg)1221 wifi_error WifiLegacyHal::nanSubscribeRequest(const std::string& iface_name,
1222                                               transaction_id id,
1223                                               const NanSubscribeRequest& msg) {
1224     NanSubscribeRequest msg_internal(msg);
1225     return global_func_table_.wifi_nan_subscribe_request(
1226         id, getIfaceHandle(iface_name), &msg_internal);
1227 }
1228 
nanSubscribeCancelRequest(const std::string & iface_name,transaction_id id,const NanSubscribeCancelRequest & msg)1229 wifi_error WifiLegacyHal::nanSubscribeCancelRequest(
1230     const std::string& iface_name, transaction_id id,
1231     const NanSubscribeCancelRequest& msg) {
1232     NanSubscribeCancelRequest msg_internal(msg);
1233     return global_func_table_.wifi_nan_subscribe_cancel_request(
1234         id, getIfaceHandle(iface_name), &msg_internal);
1235 }
1236 
nanTransmitFollowupRequest(const std::string & iface_name,transaction_id id,const NanTransmitFollowupRequest & msg)1237 wifi_error WifiLegacyHal::nanTransmitFollowupRequest(
1238     const std::string& iface_name, transaction_id id,
1239     const NanTransmitFollowupRequest& msg) {
1240     NanTransmitFollowupRequest msg_internal(msg);
1241     return global_func_table_.wifi_nan_transmit_followup_request(
1242         id, getIfaceHandle(iface_name), &msg_internal);
1243 }
1244 
nanStatsRequest(const std::string & iface_name,transaction_id id,const NanStatsRequest & msg)1245 wifi_error WifiLegacyHal::nanStatsRequest(const std::string& iface_name,
1246                                           transaction_id id,
1247                                           const NanStatsRequest& msg) {
1248     NanStatsRequest msg_internal(msg);
1249     return global_func_table_.wifi_nan_stats_request(
1250         id, getIfaceHandle(iface_name), &msg_internal);
1251 }
1252 
nanConfigRequest(const std::string & iface_name,transaction_id id,const NanConfigRequest & msg)1253 wifi_error WifiLegacyHal::nanConfigRequest(const std::string& iface_name,
1254                                            transaction_id id,
1255                                            const NanConfigRequest& msg) {
1256     NanConfigRequest msg_internal(msg);
1257     return global_func_table_.wifi_nan_config_request(
1258         id, getIfaceHandle(iface_name), &msg_internal);
1259 }
1260 
nanTcaRequest(const std::string & iface_name,transaction_id id,const NanTCARequest & msg)1261 wifi_error WifiLegacyHal::nanTcaRequest(const std::string& iface_name,
1262                                         transaction_id id,
1263                                         const NanTCARequest& msg) {
1264     NanTCARequest msg_internal(msg);
1265     return global_func_table_.wifi_nan_tca_request(
1266         id, getIfaceHandle(iface_name), &msg_internal);
1267 }
1268 
nanBeaconSdfPayloadRequest(const std::string & iface_name,transaction_id id,const NanBeaconSdfPayloadRequest & msg)1269 wifi_error WifiLegacyHal::nanBeaconSdfPayloadRequest(
1270     const std::string& iface_name, transaction_id id,
1271     const NanBeaconSdfPayloadRequest& msg) {
1272     NanBeaconSdfPayloadRequest msg_internal(msg);
1273     return global_func_table_.wifi_nan_beacon_sdf_payload_request(
1274         id, getIfaceHandle(iface_name), &msg_internal);
1275 }
1276 
nanGetVersion()1277 std::pair<wifi_error, NanVersion> WifiLegacyHal::nanGetVersion() {
1278     NanVersion version;
1279     wifi_error status =
1280         global_func_table_.wifi_nan_get_version(global_handle_, &version);
1281     return {status, version};
1282 }
1283 
nanGetCapabilities(const std::string & iface_name,transaction_id id)1284 wifi_error WifiLegacyHal::nanGetCapabilities(const std::string& iface_name,
1285                                              transaction_id id) {
1286     return global_func_table_.wifi_nan_get_capabilities(
1287         id, getIfaceHandle(iface_name));
1288 }
1289 
nanDataInterfaceCreate(const std::string & iface_name,transaction_id id,const std::string & data_iface_name)1290 wifi_error WifiLegacyHal::nanDataInterfaceCreate(
1291     const std::string& iface_name, transaction_id id,
1292     const std::string& data_iface_name) {
1293     return global_func_table_.wifi_nan_data_interface_create(
1294         id, getIfaceHandle(iface_name), makeCharVec(data_iface_name).data());
1295 }
1296 
nanDataInterfaceDelete(const std::string & iface_name,transaction_id id,const std::string & data_iface_name)1297 wifi_error WifiLegacyHal::nanDataInterfaceDelete(
1298     const std::string& iface_name, transaction_id id,
1299     const std::string& data_iface_name) {
1300     return global_func_table_.wifi_nan_data_interface_delete(
1301         id, getIfaceHandle(iface_name), makeCharVec(data_iface_name).data());
1302 }
1303 
nanDataRequestInitiator(const std::string & iface_name,transaction_id id,const NanDataPathInitiatorRequest & msg)1304 wifi_error WifiLegacyHal::nanDataRequestInitiator(
1305     const std::string& iface_name, transaction_id id,
1306     const NanDataPathInitiatorRequest& msg) {
1307     NanDataPathInitiatorRequest msg_internal(msg);
1308     return global_func_table_.wifi_nan_data_request_initiator(
1309         id, getIfaceHandle(iface_name), &msg_internal);
1310 }
1311 
nanDataIndicationResponse(const std::string & iface_name,transaction_id id,const NanDataPathIndicationResponse & msg)1312 wifi_error WifiLegacyHal::nanDataIndicationResponse(
1313     const std::string& iface_name, transaction_id id,
1314     const NanDataPathIndicationResponse& msg) {
1315     NanDataPathIndicationResponse msg_internal(msg);
1316     return global_func_table_.wifi_nan_data_indication_response(
1317         id, getIfaceHandle(iface_name), &msg_internal);
1318 }
1319 
1320 typedef struct {
1321     u8 num_ndp_instances;
1322     NanDataPathId ndp_instance_id;
1323 } NanDataPathEndSingleNdpIdRequest;
1324 
nanDataEnd(const std::string & iface_name,transaction_id id,uint32_t ndpInstanceId)1325 wifi_error WifiLegacyHal::nanDataEnd(const std::string& iface_name,
1326                                      transaction_id id,
1327                                      uint32_t ndpInstanceId) {
1328     NanDataPathEndSingleNdpIdRequest msg;
1329     msg.num_ndp_instances = 1;
1330     msg.ndp_instance_id = ndpInstanceId;
1331     wifi_error status = global_func_table_.wifi_nan_data_end(
1332         id, getIfaceHandle(iface_name), (NanDataPathEndRequest*)&msg);
1333     return status;
1334 }
1335 
setCountryCode(const std::string & iface_name,std::array<int8_t,2> code)1336 wifi_error WifiLegacyHal::setCountryCode(const std::string& iface_name,
1337                                          std::array<int8_t, 2> code) {
1338     std::string code_str(code.data(), code.data() + code.size());
1339     return global_func_table_.wifi_set_country_code(getIfaceHandle(iface_name),
1340                                                     code_str.c_str());
1341 }
1342 
retrieveIfaceHandles()1343 wifi_error WifiLegacyHal::retrieveIfaceHandles() {
1344     wifi_interface_handle* iface_handles = nullptr;
1345     int num_iface_handles = 0;
1346     wifi_error status = global_func_table_.wifi_get_ifaces(
1347         global_handle_, &num_iface_handles, &iface_handles);
1348     if (status != WIFI_SUCCESS) {
1349         LOG(ERROR) << "Failed to enumerate interface handles";
1350         return status;
1351     }
1352     for (int i = 0; i < num_iface_handles; ++i) {
1353         std::array<char, IFNAMSIZ> iface_name_arr = {};
1354         status = global_func_table_.wifi_get_iface_name(
1355             iface_handles[i], iface_name_arr.data(), iface_name_arr.size());
1356         if (status != WIFI_SUCCESS) {
1357             LOG(WARNING) << "Failed to get interface handle name";
1358             continue;
1359         }
1360         // Assuming the interface name is null terminated since the legacy HAL
1361         // API does not return a size.
1362         std::string iface_name(iface_name_arr.data());
1363         LOG(INFO) << "Adding interface handle for " << iface_name;
1364         iface_name_to_handle_[iface_name] = iface_handles[i];
1365     }
1366     return WIFI_SUCCESS;
1367 }
1368 
getIfaceHandle(const std::string & iface_name)1369 wifi_interface_handle WifiLegacyHal::getIfaceHandle(
1370     const std::string& iface_name) {
1371     const auto iface_handle_iter = iface_name_to_handle_.find(iface_name);
1372     if (iface_handle_iter == iface_name_to_handle_.end()) {
1373         LOG(ERROR) << "Unknown iface name: " << iface_name;
1374         return nullptr;
1375     }
1376     return iface_handle_iter->second;
1377 }
1378 
runEventLoop()1379 void WifiLegacyHal::runEventLoop() {
1380     LOG(DEBUG) << "Starting legacy HAL event loop";
1381     global_func_table_.wifi_event_loop(global_handle_);
1382     const auto lock = hidl_sync_util::acquireGlobalLock();
1383     if (!awaiting_event_loop_termination_) {
1384         LOG(FATAL)
1385             << "Legacy HAL event loop terminated, but HAL was not stopping";
1386     }
1387     LOG(DEBUG) << "Legacy HAL event loop terminated";
1388     awaiting_event_loop_termination_ = false;
1389     stop_wait_cv_.notify_one();
1390 }
1391 
1392 std::pair<wifi_error, std::vector<wifi_cached_scan_results>>
getGscanCachedResults(const std::string & iface_name)1393 WifiLegacyHal::getGscanCachedResults(const std::string& iface_name) {
1394     std::vector<wifi_cached_scan_results> cached_scan_results;
1395     cached_scan_results.resize(kMaxCachedGscanResults);
1396     int32_t num_results = 0;
1397     wifi_error status = global_func_table_.wifi_get_cached_gscan_results(
1398         getIfaceHandle(iface_name), true /* always flush */,
1399         cached_scan_results.size(), cached_scan_results.data(), &num_results);
1400     CHECK(num_results >= 0 &&
1401           static_cast<uint32_t>(num_results) <= kMaxCachedGscanResults);
1402     cached_scan_results.resize(num_results);
1403     // Check for invalid IE lengths in these cached scan results and correct it.
1404     for (auto& cached_scan_result : cached_scan_results) {
1405         int num_scan_results = cached_scan_result.num_results;
1406         for (int i = 0; i < num_scan_results; i++) {
1407             auto& scan_result = cached_scan_result.results[i];
1408             if (scan_result.ie_length > 0) {
1409                 LOG(DEBUG) << "Cached scan result has non-zero IE length "
1410                            << scan_result.ie_length;
1411                 scan_result.ie_length = 0;
1412             }
1413         }
1414     }
1415     return {status, std::move(cached_scan_results)};
1416 }
1417 
invalidate()1418 void WifiLegacyHal::invalidate() {
1419     global_handle_ = nullptr;
1420     iface_name_to_handle_.clear();
1421     on_driver_memory_dump_internal_callback = nullptr;
1422     on_firmware_memory_dump_internal_callback = nullptr;
1423     on_gscan_event_internal_callback = nullptr;
1424     on_gscan_full_result_internal_callback = nullptr;
1425     on_link_layer_stats_result_internal_callback = nullptr;
1426     on_rssi_threshold_breached_internal_callback = nullptr;
1427     on_ring_buffer_data_internal_callback = nullptr;
1428     on_error_alert_internal_callback = nullptr;
1429     on_radio_mode_change_internal_callback = nullptr;
1430     on_rtt_results_internal_callback = nullptr;
1431     on_nan_notify_response_user_callback = nullptr;
1432     on_nan_event_publish_terminated_user_callback = nullptr;
1433     on_nan_event_match_user_callback = nullptr;
1434     on_nan_event_match_expired_user_callback = nullptr;
1435     on_nan_event_subscribe_terminated_user_callback = nullptr;
1436     on_nan_event_followup_user_callback = nullptr;
1437     on_nan_event_disc_eng_event_user_callback = nullptr;
1438     on_nan_event_disabled_user_callback = nullptr;
1439     on_nan_event_tca_user_callback = nullptr;
1440     on_nan_event_beacon_sdf_payload_user_callback = nullptr;
1441     on_nan_event_data_path_request_user_callback = nullptr;
1442     on_nan_event_data_path_confirm_user_callback = nullptr;
1443     on_nan_event_data_path_end_user_callback = nullptr;
1444     on_nan_event_transmit_follow_up_user_callback = nullptr;
1445     on_nan_event_range_request_user_callback = nullptr;
1446     on_nan_event_range_report_user_callback = nullptr;
1447     on_nan_event_schedule_update_user_callback = nullptr;
1448 }
1449 
1450 }  // namespace legacy_hal
1451 }  // namespace implementation
1452 }  // namespace V1_3
1453 }  // namespace wifi
1454 }  // namespace hardware
1455 }  // namespace android
1456