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