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 #ifndef WIFI_LEGACY_HAL_H_
18 #define WIFI_LEGACY_HAL_H_
19 
20 #include <condition_variable>
21 #include <functional>
22 #include <map>
23 #include <thread>
24 #include <vector>
25 
26 #include <wifi_system/interface_tool.h>
27 
28 namespace android {
29 namespace hardware {
30 namespace wifi {
31 namespace V1_2 {
32 namespace implementation {
33 // This is in a separate namespace to prevent typename conflicts between
34 // the legacy HAL types and the HIDL interface types.
35 namespace legacy_hal {
36 // Wrap all the types defined inside the legacy HAL header files inside this
37 // namespace.
38 #include <hardware_legacy/wifi_hal.h>
39 
40 // APF capabilities supported by the iface.
41 struct PacketFilterCapabilities {
42     uint32_t version;
43     uint32_t max_len;
44 };
45 
46 // WARNING: We don't care about the variable sized members of either
47 // |wifi_iface_stat|, |wifi_radio_stat| structures. So, using the pragma
48 // to escape the compiler warnings regarding this.
49 #pragma GCC diagnostic push
50 #pragma GCC diagnostic ignored "-Wgnu-variable-sized-type-not-at-end"
51 // The |wifi_radio_stat.tx_time_per_levels| stats is provided as a pointer in
52 // |wifi_radio_stat| structure in the legacy HAL API. Separate that out
53 // into a separate return element to avoid passing pointers around.
54 struct LinkLayerRadioStats {
55     wifi_radio_stat stats;
56     std::vector<uint32_t> tx_time_per_levels;
57 };
58 
59 struct LinkLayerStats {
60     wifi_iface_stat iface;
61     std::vector<LinkLayerRadioStats> radios;
62 };
63 #pragma GCC diagnostic pop
64 
65 // The |WLAN_DRIVER_WAKE_REASON_CNT.cmd_event_wake_cnt| and
66 // |WLAN_DRIVER_WAKE_REASON_CNT.driver_fw_local_wake_cnt| stats is provided
67 // as a pointer in |WLAN_DRIVER_WAKE_REASON_CNT| structure in the legacy HAL
68 // API. Separate that out into a separate return elements to avoid passing
69 // pointers around.
70 struct WakeReasonStats {
71     WLAN_DRIVER_WAKE_REASON_CNT wake_reason_cnt;
72     std::vector<uint32_t> cmd_event_wake_cnt;
73     std::vector<uint32_t> driver_fw_local_wake_cnt;
74 };
75 
76 // NAN response and event callbacks struct.
77 struct NanCallbackHandlers {
78     // NotifyResponse invoked to notify the status of the Request.
79     std::function<void(transaction_id, const NanResponseMsg&)>
80         on_notify_response;
81     // Various event callbacks.
82     std::function<void(const NanPublishTerminatedInd&)>
83         on_event_publish_terminated;
84     std::function<void(const NanMatchInd&)> on_event_match;
85     std::function<void(const NanMatchExpiredInd&)> on_event_match_expired;
86     std::function<void(const NanSubscribeTerminatedInd&)>
87         on_event_subscribe_terminated;
88     std::function<void(const NanFollowupInd&)> on_event_followup;
89     std::function<void(const NanDiscEngEventInd&)> on_event_disc_eng_event;
90     std::function<void(const NanDisabledInd&)> on_event_disabled;
91     std::function<void(const NanTCAInd&)> on_event_tca;
92     std::function<void(const NanBeaconSdfPayloadInd&)>
93         on_event_beacon_sdf_payload;
94     std::function<void(const NanDataPathRequestInd&)>
95         on_event_data_path_request;
96     std::function<void(const NanDataPathConfirmInd&)>
97         on_event_data_path_confirm;
98     std::function<void(const NanDataPathEndInd&)> on_event_data_path_end;
99     std::function<void(const NanTransmitFollowupInd&)>
100         on_event_transmit_follow_up;
101     std::function<void(const NanRangeRequestInd&)> on_event_range_request;
102     std::function<void(const NanRangeReportInd&)> on_event_range_report;
103     std::function<void(const NanDataPathScheduleUpdateInd&)> on_event_schedule_update;
104 };
105 
106 // Full scan results contain IE info and are hence passed by reference, to
107 // preserve the variable length array member |ie_data|. Callee must not retain
108 // the pointer.
109 using on_gscan_full_result_callback =
110     std::function<void(wifi_request_id, const wifi_scan_result*, uint32_t)>;
111 // These scan results don't contain any IE info, so no need to pass by
112 // reference.
113 using on_gscan_results_callback = std::function<void(
114     wifi_request_id, const std::vector<wifi_cached_scan_results>&)>;
115 
116 // Invoked when the rssi value breaches the thresholds set.
117 using on_rssi_threshold_breached_callback =
118     std::function<void(wifi_request_id, std::array<uint8_t, 6>, int8_t)>;
119 
120 // Callback for RTT range request results.
121 // Rtt results contain IE info and are hence passed by reference, to
122 // preserve the |LCI| and |LCR| pointers. Callee must not retain
123 // the pointer.
124 using on_rtt_results_callback = std::function<void(
125     wifi_request_id, const std::vector<const wifi_rtt_result*>&)>;
126 
127 // Callback for ring buffer data.
128 using on_ring_buffer_data_callback =
129     std::function<void(const std::string&, const std::vector<uint8_t>&,
130                        const wifi_ring_buffer_status&)>;
131 
132 // Callback for alerts.
133 using on_error_alert_callback =
134     std::function<void(int32_t, const std::vector<uint8_t>&)>;
135 
136 // Struct for the mac info from the legacy HAL. This is a cleaner version
137 // of the |wifi_mac_info| & |wifi_iface_info|.
138 typedef struct {
139     std::string name;
140     wifi_channel channel;
141 } WifiIfaceInfo;
142 
143 typedef struct {
144     uint32_t wlan_mac_id;
145     /* BIT MASK of BIT(WLAN_MAC*) as represented by wlan_mac_band */
146     uint32_t mac_band;
147     /* Represents the connected Wi-Fi interfaces associated with each MAC */
148     std::vector<WifiIfaceInfo> iface_infos;
149 } WifiMacInfo;
150 
151 // Callback for radio mode change
152 using on_radio_mode_change_callback =
153     std::function<void(const std::vector<WifiMacInfo>&)>;
154 
155 /**
156  * Class that encapsulates all legacy HAL interactions.
157  * This class manages the lifetime of the event loop thread used by legacy HAL.
158  *
159  * Note: There will only be a single instance of this class created in the Wifi
160  * object and will be valid for the lifetime of the process.
161  */
162 class WifiLegacyHal {
163    public:
164     WifiLegacyHal();
165     virtual ~WifiLegacyHal() = default;
166 
167     // Initialize the legacy HAL function table.
168     virtual wifi_error initialize();
169     // Start the legacy HAL and the event looper thread.
170     virtual wifi_error start();
171     // Deinitialize the legacy HAL and wait for the event loop thread to exit
172     // using a predefined timeout.
173     virtual wifi_error stop(std::unique_lock<std::recursive_mutex>* lock,
174                             const std::function<void()>& on_complete_callback);
175     // Wrappers for all the functions in the legacy HAL function table.
176     std::pair<wifi_error, std::string> getDriverVersion(
177         const std::string& iface_name);
178     std::pair<wifi_error, std::string> getFirmwareVersion(
179         const std::string& iface_name);
180     std::pair<wifi_error, std::vector<uint8_t>> requestDriverMemoryDump(
181         const std::string& iface_name);
182     std::pair<wifi_error, std::vector<uint8_t>> requestFirmwareMemoryDump(
183         const std::string& iface_name);
184     std::pair<wifi_error, uint32_t> getSupportedFeatureSet(
185         const std::string& iface_name);
186     // APF functions.
187     std::pair<wifi_error, PacketFilterCapabilities> getPacketFilterCapabilities(
188         const std::string& iface_name);
189     wifi_error setPacketFilter(const std::string& iface_name,
190                                const std::vector<uint8_t>& program);
191     std::pair<wifi_error, std::vector<uint8_t>> readApfPacketFilterData(
192         const std::string& iface_name);
193     // Gscan functions.
194     std::pair<wifi_error, wifi_gscan_capabilities> getGscanCapabilities(
195         const std::string& iface_name);
196     // These API's provides a simplified interface over the legacy Gscan API's:
197     // a) All scan events from the legacy HAL API other than the
198     //    |WIFI_SCAN_FAILED| are treated as notification of results.
199     //    This method then retrieves the cached scan results from the legacy
200     //    HAL API and triggers the externally provided
201     //    |on_results_user_callback| on success.
202     // b) |WIFI_SCAN_FAILED| scan event or failure to retrieve cached scan
203     // results
204     //    triggers the externally provided |on_failure_user_callback|.
205     // c) Full scan result event triggers the externally provided
206     //    |on_full_result_user_callback|.
207     wifi_error startGscan(
208         const std::string& iface_name, wifi_request_id id,
209         const wifi_scan_cmd_params& params,
210         const std::function<void(wifi_request_id)>& on_failure_callback,
211         const on_gscan_results_callback& on_results_callback,
212         const on_gscan_full_result_callback& on_full_result_callback);
213     wifi_error stopGscan(const std::string& iface_name, wifi_request_id id);
214     std::pair<wifi_error, std::vector<uint32_t>> getValidFrequenciesForBand(
215         const std::string& iface_name, wifi_band band);
216     virtual wifi_error setDfsFlag(const std::string& iface_name, bool dfs_on);
217     // Link layer stats functions.
218     wifi_error enableLinkLayerStats(const std::string& iface_name, bool debug);
219     wifi_error disableLinkLayerStats(const std::string& iface_name);
220     std::pair<wifi_error, LinkLayerStats> getLinkLayerStats(
221         const std::string& iface_name);
222     // RSSI monitor functions.
223     wifi_error startRssiMonitoring(const std::string& iface_name,
224                                    wifi_request_id id, int8_t max_rssi,
225                                    int8_t min_rssi,
226                                    const on_rssi_threshold_breached_callback&
227                                        on_threshold_breached_callback);
228     wifi_error stopRssiMonitoring(const std::string& iface_name,
229                                   wifi_request_id id);
230     std::pair<wifi_error, wifi_roaming_capabilities> getRoamingCapabilities(
231         const std::string& iface_name);
232     wifi_error configureRoaming(const std::string& iface_name,
233                                 const wifi_roaming_config& config);
234     wifi_error enableFirmwareRoaming(const std::string& iface_name,
235                                      fw_roaming_state_t state);
236     wifi_error configureNdOffload(const std::string& iface_name, bool enable);
237     wifi_error startSendingOffloadedPacket(
238         const std::string& iface_name, uint32_t cmd_id,
239         const std::vector<uint8_t>& ip_packet_data,
240         const std::array<uint8_t, 6>& src_address,
241         const std::array<uint8_t, 6>& dst_address, uint32_t period_in_ms);
242     wifi_error stopSendingOffloadedPacket(const std::string& iface_name,
243                                           uint32_t cmd_id);
244     wifi_error setScanningMacOui(const std::string& iface_name,
245                                  const std::array<uint8_t, 3>& oui);
246     wifi_error selectTxPowerScenario(const std::string& iface_name,
247                                      wifi_power_scenario scenario);
248     wifi_error resetTxPowerScenario(const std::string& iface_name);
249     // Logger/debug functions.
250     std::pair<wifi_error, uint32_t> getLoggerSupportedFeatureSet(
251         const std::string& iface_name);
252     wifi_error startPktFateMonitoring(const std::string& iface_name);
253     std::pair<wifi_error, std::vector<wifi_tx_report>> getTxPktFates(
254         const std::string& iface_name);
255     std::pair<wifi_error, std::vector<wifi_rx_report>> getRxPktFates(
256         const std::string& iface_name);
257     std::pair<wifi_error, WakeReasonStats> getWakeReasonStats(
258         const std::string& iface_name);
259     wifi_error registerRingBufferCallbackHandler(
260         const std::string& iface_name,
261         const on_ring_buffer_data_callback& on_data_callback);
262     wifi_error deregisterRingBufferCallbackHandler(
263         const std::string& iface_name);
264     std::pair<wifi_error, std::vector<wifi_ring_buffer_status>>
265     getRingBuffersStatus(const std::string& iface_name);
266     wifi_error startRingBufferLogging(const std::string& iface_name,
267                                       const std::string& ring_name,
268                                       uint32_t verbose_level,
269                                       uint32_t max_interval_sec,
270                                       uint32_t min_data_size);
271     wifi_error getRingBufferData(const std::string& iface_name,
272                                  const std::string& ring_name);
273     wifi_error registerErrorAlertCallbackHandler(
274         const std::string& iface_name,
275         const on_error_alert_callback& on_alert_callback);
276     wifi_error deregisterErrorAlertCallbackHandler(
277         const std::string& iface_name);
278     // Radio mode functions.
279     virtual wifi_error registerRadioModeChangeCallbackHandler(
280         const std::string& iface_name,
281         const on_radio_mode_change_callback& on_user_change_callback);
282     // RTT functions.
283     wifi_error startRttRangeRequest(
284         const std::string& iface_name, wifi_request_id id,
285         const std::vector<wifi_rtt_config>& rtt_configs,
286         const on_rtt_results_callback& on_results_callback);
287     wifi_error cancelRttRangeRequest(
288         const std::string& iface_name, wifi_request_id id,
289         const std::vector<std::array<uint8_t, 6>>& mac_addrs);
290     std::pair<wifi_error, wifi_rtt_capabilities> getRttCapabilities(
291         const std::string& iface_name);
292     std::pair<wifi_error, wifi_rtt_responder> getRttResponderInfo(
293         const std::string& iface_name);
294     wifi_error enableRttResponder(const std::string& iface_name,
295                                   wifi_request_id id,
296                                   const wifi_channel_info& channel_hint,
297                                   uint32_t max_duration_secs,
298                                   const wifi_rtt_responder& info);
299     wifi_error disableRttResponder(const std::string& iface_name,
300                                    wifi_request_id id);
301     wifi_error setRttLci(const std::string& iface_name, wifi_request_id id,
302                          const wifi_lci_information& info);
303     wifi_error setRttLcr(const std::string& iface_name, wifi_request_id id,
304                          const wifi_lcr_information& info);
305     // NAN functions.
306     virtual wifi_error nanRegisterCallbackHandlers(
307         const std::string& iface_name, const NanCallbackHandlers& callbacks);
308     wifi_error nanEnableRequest(const std::string& iface_name,
309                                 transaction_id id, const NanEnableRequest& msg);
310     virtual wifi_error nanDisableRequest(const std::string& iface_name,
311                                          transaction_id id);
312     wifi_error nanPublishRequest(const std::string& iface_name,
313                                  transaction_id id,
314                                  const NanPublishRequest& msg);
315     wifi_error nanPublishCancelRequest(const std::string& iface_name,
316                                        transaction_id id,
317                                        const NanPublishCancelRequest& msg);
318     wifi_error nanSubscribeRequest(const std::string& iface_name,
319                                    transaction_id id,
320                                    const NanSubscribeRequest& msg);
321     wifi_error nanSubscribeCancelRequest(const std::string& iface_name,
322                                          transaction_id id,
323                                          const NanSubscribeCancelRequest& msg);
324     wifi_error nanTransmitFollowupRequest(
325         const std::string& iface_name, transaction_id id,
326         const NanTransmitFollowupRequest& msg);
327     wifi_error nanStatsRequest(const std::string& iface_name, transaction_id id,
328                                const NanStatsRequest& msg);
329     wifi_error nanConfigRequest(const std::string& iface_name,
330                                 transaction_id id, const NanConfigRequest& msg);
331     wifi_error nanTcaRequest(const std::string& iface_name, transaction_id id,
332                              const NanTCARequest& msg);
333     wifi_error nanBeaconSdfPayloadRequest(
334         const std::string& iface_name, transaction_id id,
335         const NanBeaconSdfPayloadRequest& msg);
336     std::pair<wifi_error, NanVersion> nanGetVersion();
337     wifi_error nanGetCapabilities(const std::string& iface_name,
338                                   transaction_id id);
339     wifi_error nanDataInterfaceCreate(const std::string& iface_name,
340                                       transaction_id id,
341                                       const std::string& data_iface_name);
342     virtual wifi_error nanDataInterfaceDelete(
343         const std::string& iface_name, transaction_id id,
344         const std::string& data_iface_name);
345     wifi_error nanDataRequestInitiator(const std::string& iface_name,
346                                        transaction_id id,
347                                        const NanDataPathInitiatorRequest& msg);
348     wifi_error nanDataIndicationResponse(
349         const std::string& iface_name, transaction_id id,
350         const NanDataPathIndicationResponse& msg);
351     wifi_error nanDataEnd(const std::string& iface_name, transaction_id id,
352                           uint32_t ndpInstanceId);
353     // AP functions.
354     wifi_error setCountryCode(const std::string& iface_name,
355                               std::array<int8_t, 2> code);
356 
357    private:
358     // Retrieve interface handles for all the available interfaces.
359     wifi_error retrieveIfaceHandles();
360     wifi_interface_handle getIfaceHandle(const std::string& iface_name);
361     // Run the legacy HAL event loop thread.
362     void runEventLoop();
363     // Retrieve the cached gscan results to pass the results back to the
364     // external callbacks.
365     std::pair<wifi_error, std::vector<wifi_cached_scan_results>>
366     getGscanCachedResults(const std::string& iface_name);
367     void invalidate();
368 
369     // Global function table of legacy HAL.
370     wifi_hal_fn global_func_table_;
371     // Opaque handle to be used for all global operations.
372     wifi_handle global_handle_;
373     // Map of interface name to handle that is to be used for all interface
374     // specific operations.
375     std::map<std::string, wifi_interface_handle> iface_name_to_handle_;
376     // Flag to indicate if we have initiated the cleanup of legacy HAL.
377     std::atomic<bool> awaiting_event_loop_termination_;
378     std::condition_variable_any stop_wait_cv_;
379     // Flag to indicate if the legacy HAL has been started.
380     bool is_started_;
381     wifi_system::InterfaceTool iface_tool_;
382 };
383 
384 }  // namespace legacy_hal
385 }  // namespace implementation
386 }  // namespace V1_2
387 }  // namespace wifi
388 }  // namespace hardware
389 }  // namespace android
390 
391 #endif  // WIFI_LEGACY_HAL_H_
392