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