1 /******************************************************************************
2  *
3  *  Copyright 2009-2012 Broadcom Corporation
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at:
8  *
9  *  http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  ******************************************************************************/
18 
19 #include <base/logging.h>
20 #include <ctype.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <linux/uhid.h>
24 #include <pthread.h>
25 #include <stdint.h>
26 #include <stdio.h>
27 #include <string.h>
28 #include <sys/poll.h>
29 #include <unistd.h>
30 
31 #include "bta_api.h"
32 #include "bta_hh_api.h"
33 #include "bta_hh_co.h"
34 #include "btif_hh.h"
35 #include "btif_util.h"
36 #include "osi/include/osi.h"
37 
38 const char* dev_path = "/dev/uhid";
39 
40 #include "btif_config.h"
41 #define BTA_HH_NV_LOAD_MAX 16
42 static tBTA_HH_RPT_CACHE_ENTRY sReportCache[BTA_HH_NV_LOAD_MAX];
43 #define GET_RPT_RSP_OFFSET 9
44 #define BTA_HH_CACHE_REPORT_VERSION 1
45 #define THREAD_NORMAL_PRIORITY 0
46 #define BT_HH_THREAD "bt_hh_thread"
47 
uhid_set_non_blocking(int fd)48 void uhid_set_non_blocking(int fd) {
49   int opts = fcntl(fd, F_GETFL);
50   if (opts < 0)
51     APPL_TRACE_ERROR("%s() Getting flags failed (%s)", __func__,
52                      strerror(errno));
53 
54   opts |= O_NONBLOCK;
55 
56   if (fcntl(fd, F_SETFL, opts) < 0)
57     APPL_TRACE_EVENT("%s() Setting non-blocking flag failed (%s)", __func__,
58                      strerror(errno));
59 }
60 
61 /*Internal function to perform UHID write and error checking*/
uhid_write(int fd,const struct uhid_event * ev)62 static int uhid_write(int fd, const struct uhid_event* ev) {
63   ssize_t ret;
64   OSI_NO_INTR(ret = write(fd, ev, sizeof(*ev)));
65 
66   if (ret < 0) {
67     int rtn = -errno;
68     APPL_TRACE_ERROR("%s: Cannot write to uhid:%s", __func__, strerror(errno));
69     return rtn;
70   } else if (ret != (ssize_t)sizeof(*ev)) {
71     APPL_TRACE_ERROR("%s: Wrong size written to uhid: %zd != %zu", __func__,
72                      ret, sizeof(*ev));
73     return -EFAULT;
74   }
75 
76   return 0;
77 }
78 
79 /* Internal function to parse the events received from UHID driver*/
uhid_read_event(btif_hh_device_t * p_dev)80 static int uhid_read_event(btif_hh_device_t* p_dev) {
81   CHECK(p_dev);
82 
83   struct uhid_event ev;
84   memset(&ev, 0, sizeof(ev));
85 
86   ssize_t ret;
87   OSI_NO_INTR(ret = read(p_dev->fd, &ev, sizeof(ev)));
88 
89   if (ret == 0) {
90     APPL_TRACE_ERROR("%s: Read HUP on uhid-cdev %s", __func__, strerror(errno));
91     return -EFAULT;
92   } else if (ret < 0) {
93     APPL_TRACE_ERROR("%s: Cannot read uhid-cdev: %s", __func__,
94                      strerror(errno));
95     return -errno;
96   }
97 
98   switch (ev.type) {
99     case UHID_START:
100       APPL_TRACE_DEBUG("UHID_START from uhid-dev\n");
101       p_dev->ready_for_data = true;
102       break;
103     case UHID_STOP:
104       APPL_TRACE_DEBUG("UHID_STOP from uhid-dev\n");
105       p_dev->ready_for_data = false;
106       break;
107     case UHID_OPEN:
108       APPL_TRACE_DEBUG("UHID_OPEN from uhid-dev\n");
109       p_dev->ready_for_data = true;
110       break;
111     case UHID_CLOSE:
112       APPL_TRACE_DEBUG("UHID_CLOSE from uhid-dev\n");
113       p_dev->ready_for_data = false;
114       break;
115     case UHID_OUTPUT:
116       if (ret < (ssize_t)(sizeof(ev.type) + sizeof(ev.u.output))) {
117         APPL_TRACE_ERROR("%s: Invalid size read from uhid-dev: %zd < %zu",
118                          __func__, ret, sizeof(ev.type) + sizeof(ev.u.output));
119         return -EFAULT;
120       }
121 
122       APPL_TRACE_DEBUG("UHID_OUTPUT: Report type = %d, report_size = %d",
123                        ev.u.output.rtype, ev.u.output.size);
124       // Send SET_REPORT with feature report if the report type in output event
125       // is FEATURE
126       if (ev.u.output.rtype == UHID_FEATURE_REPORT)
127         btif_hh_setreport(p_dev, BTHH_FEATURE_REPORT, ev.u.output.size,
128                           ev.u.output.data);
129       else if (ev.u.output.rtype == UHID_OUTPUT_REPORT)
130         btif_hh_senddata(p_dev, ev.u.output.size, ev.u.output.data);
131       else
132         APPL_TRACE_ERROR("%s: UHID_OUTPUT: Invalid report type = %d", __func__,
133                          ev.u.output.rtype);
134       break;
135     case UHID_OUTPUT_EV:
136       if (ret < (ssize_t)(sizeof(ev.type) + sizeof(ev.u.output_ev))) {
137         APPL_TRACE_ERROR("%s: Invalid size read from uhid-dev: %zd < %zu",
138                          __func__, ret,
139                          sizeof(ev.type) + sizeof(ev.u.output_ev));
140         return -EFAULT;
141       }
142       APPL_TRACE_DEBUG("UHID_OUTPUT_EV from uhid-dev\n");
143       break;
144     case UHID_FEATURE:
145       if (ret < (ssize_t)(sizeof(ev.type) + sizeof(ev.u.feature))) {
146         APPL_TRACE_ERROR(
147             "%s: UHID_FEATURE: Invalid size read from uhid-dev: %zd < %zu",
148             __func__, ret, sizeof(ev.type) + sizeof(ev.u.feature));
149         return -EFAULT;
150       }
151       APPL_TRACE_DEBUG("UHID_FEATURE: Report type = %d", ev.u.feature.rtype);
152       p_dev->get_rpt_snt++;
153       if (p_dev->get_rpt_id_queue) {
154         uint32_t* get_rpt_id = (uint32_t*)osi_malloc(sizeof(uint32_t));
155         *get_rpt_id = ev.u.feature.id;
156         fixed_queue_enqueue(p_dev->get_rpt_id_queue, (void*)get_rpt_id);
157       }
158       if (ev.u.feature.rtype == UHID_FEATURE_REPORT)
159         btif_hh_getreport(p_dev, BTHH_FEATURE_REPORT, ev.u.feature.rnum, 0);
160       else
161         APPL_TRACE_ERROR("%s: UHID_FEATURE: Invalid report type = %d", __func__,
162                          ev.u.feature.rtype);
163       break;
164 #ifdef OS_ANDROID  // Host kernel does not support UHID_SET_REPORT
165     case UHID_SET_REPORT:
166       if (ret < (ssize_t)(sizeof(ev.type) + sizeof(ev.u.set_report))) {
167           APPL_TRACE_ERROR("%s: Invalid size read from uhid-dev: %zd < %zu",
168                            __func__, ret, sizeof(ev.type) + sizeof(ev.u.set_report));
169             return -EFAULT;
170         }
171 
172         APPL_TRACE_DEBUG("UHID_SET_REPORT: Report type = %d, report_size = %d"
173                           , ev.u.set_report.rtype, ev.u.set_report.size);
174 
175         if (ev.u.set_report.rtype == UHID_FEATURE_REPORT)
176             btif_hh_setreport(p_dev, BTHH_FEATURE_REPORT,
177                               ev.u.set_report.size, ev.u.set_report.data);
178         else if (ev.u.set_report.rtype == UHID_OUTPUT_REPORT)
179             btif_hh_setreport(p_dev, BTHH_OUTPUT_REPORT,
180                               ev.u.set_report.size, ev.u.set_report.data);
181         else if(ev.u.set_report.rtype == UHID_INPUT_REPORT)
182             btif_hh_setreport(p_dev, BTHH_INPUT_REPORT,
183                               ev.u.set_report.size, ev.u.set_report.data);
184         else
185             APPL_TRACE_ERROR("%s:UHID_SET_REPORT: Invalid Report type = %d"
186                           , __func__, ev.u.set_report.rtype);
187         break;
188 #endif  // ifdef OS_ANDROID
189     default:
190       APPL_TRACE_DEBUG("Invalid event from uhid-dev: %u\n", ev.type);
191   }
192 
193   return 0;
194 }
195 
196 /*******************************************************************************
197  *
198  * Function create_thread
199  *
200  * Description creat a select loop
201  *
202  * Returns pthread_t
203  *
204  ******************************************************************************/
create_thread(void * (* start_routine)(void *),void * arg)205 static inline pthread_t create_thread(void* (*start_routine)(void*),
206                                       void* arg) {
207   APPL_TRACE_DEBUG("create_thread: entered");
208   pthread_attr_t thread_attr;
209 
210   pthread_attr_init(&thread_attr);
211   pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_JOINABLE);
212   pthread_t thread_id = -1;
213   if (pthread_create(&thread_id, &thread_attr, start_routine, arg) != 0) {
214     APPL_TRACE_ERROR("pthread_create : %s", strerror(errno));
215     return -1;
216   }
217   APPL_TRACE_DEBUG("create_thread: thread created successfully");
218   return thread_id;
219 }
220 
221 /*******************************************************************************
222  *
223  * Function btif_hh_poll_event_thread
224  *
225  * Description the polling thread which polls for event from UHID driver
226  *
227  * Returns void
228  *
229  ******************************************************************************/
btif_hh_poll_event_thread(void * arg)230 static void* btif_hh_poll_event_thread(void* arg) {
231   btif_hh_device_t* p_dev = (btif_hh_device_t*)arg;
232   struct pollfd pfds[1];
233 
234   // This thread is created by bt_main_thread with RT priority. Lower the thread
235   // priority here since the tasks in this thread is not timing critical.
236   struct sched_param sched_params;
237   sched_params.sched_priority = THREAD_NORMAL_PRIORITY;
238   if (sched_setscheduler(gettid(), SCHED_OTHER, &sched_params)) {
239     APPL_TRACE_ERROR("%s: Failed to set thread priority to normal", __func__);
240     p_dev->hh_poll_thread_id = -1;
241     return 0;
242   }
243   p_dev->pid = gettid();
244   pthread_setname_np(pthread_self(), BT_HH_THREAD);
245   LOG_DEBUG("Host hid polling thread created name:%s pid:%d fd:%d",
246             BT_HH_THREAD, p_dev->pid, p_dev->fd);
247 
248   pfds[0].fd = p_dev->fd;
249   pfds[0].events = POLLIN;
250 
251   // Set the uhid fd as non-blocking to ensure we never block the BTU thread
252   uhid_set_non_blocking(p_dev->fd);
253 
254   while (p_dev->hh_keep_polling) {
255     int ret;
256     OSI_NO_INTR(ret = poll(pfds, 1, 50));
257     if (ret < 0) {
258       APPL_TRACE_ERROR("%s: Cannot poll for fds: %s\n", __func__,
259                        strerror(errno));
260       break;
261     }
262     if (pfds[0].revents & POLLIN) {
263       APPL_TRACE_DEBUG("%s: POLLIN", __func__);
264       ret = uhid_read_event(p_dev);
265       if (ret != 0) break;
266     }
267   }
268 
269   p_dev->hh_poll_thread_id = -1;
270   p_dev->pid = -1;
271   return 0;
272 }
273 
btif_hh_close_poll_thread(btif_hh_device_t * p_dev)274 static inline void btif_hh_close_poll_thread(btif_hh_device_t* p_dev) {
275   APPL_TRACE_DEBUG("%s", __func__);
276   p_dev->hh_keep_polling = 0;
277   if (p_dev->hh_poll_thread_id > 0)
278     pthread_join(p_dev->hh_poll_thread_id, NULL);
279 
280   return;
281 }
282 
bta_hh_co_destroy(int fd)283 void bta_hh_co_destroy(int fd) {
284   struct uhid_event ev;
285   memset(&ev, 0, sizeof(ev));
286   ev.type = UHID_DESTROY;
287   uhid_write(fd, &ev);
288   APPL_TRACE_DEBUG("%s: Closing fd=%d", __func__, fd);
289   close(fd);
290 }
291 
bta_hh_co_write(int fd,uint8_t * rpt,uint16_t len)292 int bta_hh_co_write(int fd, uint8_t* rpt, uint16_t len) {
293   APPL_TRACE_VERBOSE("%s: UHID write %d", __func__, len);
294 
295   struct uhid_event ev;
296   memset(&ev, 0, sizeof(ev));
297   ev.type = UHID_INPUT;
298   ev.u.input.size = len;
299   if (len > sizeof(ev.u.input.data)) {
300     APPL_TRACE_WARNING("%s: Report size greater than allowed size", __func__);
301     return -1;
302   }
303   memcpy(ev.u.input.data, rpt, len);
304 
305   return uhid_write(fd, &ev);
306 }
307 
308 /*******************************************************************************
309  *
310  * Function      bta_hh_co_open
311  *
312  * Description   When connection is opened, this call-out function is executed
313  *               by HH to do platform specific initialization.
314  *
315  * Returns       void.
316  ******************************************************************************/
bta_hh_co_open(uint8_t dev_handle,uint8_t sub_class,tBTA_HH_ATTR_MASK attr_mask,uint8_t app_id)317 void bta_hh_co_open(uint8_t dev_handle, uint8_t sub_class,
318                     tBTA_HH_ATTR_MASK attr_mask, uint8_t app_id) {
319   uint32_t i;
320   btif_hh_device_t* p_dev = NULL;
321 
322   if (dev_handle == BTA_HH_INVALID_HANDLE) {
323     APPL_TRACE_WARNING("%s: Oops, dev_handle (%d) is invalid...", __func__,
324                        dev_handle);
325     return;
326   }
327 
328   for (i = 0; i < BTIF_HH_MAX_HID; i++) {
329     p_dev = &btif_hh_cb.devices[i];
330     if (p_dev->dev_status != BTHH_CONN_STATE_UNKNOWN &&
331         p_dev->dev_handle == dev_handle) {
332       // We found a device with the same handle. Must be a device reconnected.
333       APPL_TRACE_WARNING(
334           "%s: Found an existing device with the same handle dev_status=%d, "
335           "address=%s, attr_mask=0x%04x, sub_class=0x%02x, app_id=%d",
336           __func__, p_dev->dev_status, p_dev->bd_addr.ToString().c_str(),
337           p_dev->attr_mask, p_dev->sub_class, p_dev->app_id);
338 
339       if (p_dev->fd < 0) {
340         p_dev->fd = open(dev_path, O_RDWR | O_CLOEXEC);
341         if (p_dev->fd < 0) {
342           APPL_TRACE_ERROR("%s: Error: failed to open uhid, err:%s", __func__,
343                            strerror(errno));
344           return;
345         } else
346           APPL_TRACE_DEBUG("%s: uhid fd = %d", __func__, p_dev->fd);
347       }
348 
349       p_dev->hh_keep_polling = 1;
350       p_dev->hh_poll_thread_id =
351           create_thread(btif_hh_poll_event_thread, p_dev);
352       break;
353     }
354     p_dev = NULL;
355   }
356 
357   if (p_dev == NULL) {
358     // Did not find a device reconnection case. Find an empty slot now.
359     for (i = 0; i < BTIF_HH_MAX_HID; i++) {
360       if (btif_hh_cb.devices[i].dev_status == BTHH_CONN_STATE_UNKNOWN) {
361         p_dev = &btif_hh_cb.devices[i];
362         p_dev->dev_handle = dev_handle;
363         p_dev->attr_mask = attr_mask;
364         p_dev->sub_class = sub_class;
365         p_dev->app_id = app_id;
366         p_dev->local_vup = false;
367 
368         btif_hh_cb.device_num++;
369         // This is a new device,open the uhid driver now.
370         p_dev->fd = open(dev_path, O_RDWR | O_CLOEXEC);
371         if (p_dev->fd < 0) {
372           APPL_TRACE_ERROR("%s: Error: failed to open uhid, err:%s", __func__,
373                            strerror(errno));
374           return;
375         } else {
376           APPL_TRACE_DEBUG("%s: uhid fd = %d", __func__, p_dev->fd);
377           p_dev->hh_keep_polling = 1;
378           p_dev->hh_poll_thread_id =
379               create_thread(btif_hh_poll_event_thread, p_dev);
380         }
381 
382         break;
383       }
384     }
385   }
386 
387   if (p_dev == NULL) {
388     APPL_TRACE_ERROR("%s: Error: too many HID devices are connected", __func__);
389     return;
390   }
391 
392   p_dev->dev_status = BTHH_CONN_STATE_CONNECTED;
393   p_dev->get_rpt_id_queue = fixed_queue_new(SIZE_MAX);
394   CHECK(p_dev->get_rpt_id_queue);
395 
396   APPL_TRACE_DEBUG("%s: Return device status %d", __func__, p_dev->dev_status);
397 }
398 
399 /*******************************************************************************
400  *
401  * Function      bta_hh_co_close
402  *
403  * Description   When connection is closed, this call-out function is executed
404  *               by HH to do platform specific finalization.
405  *
406  * Parameters    dev_handle  - device handle
407  *                  app_id      - application id
408  *
409  * Returns          void.
410  ******************************************************************************/
bta_hh_co_close(uint8_t dev_handle,uint8_t app_id)411 void bta_hh_co_close(uint8_t dev_handle, uint8_t app_id) {
412   uint32_t i;
413   btif_hh_device_t* p_dev = NULL;
414 
415   APPL_TRACE_WARNING("%s: dev_handle = %d, app_id = %d", __func__, dev_handle,
416                      app_id);
417   if (dev_handle == BTA_HH_INVALID_HANDLE) {
418     APPL_TRACE_WARNING("%s: Oops, dev_handle (%d) is invalid...", __func__,
419                        dev_handle);
420     return;
421   }
422 
423   for (i = 0; i < BTIF_HH_MAX_HID; i++) {
424     p_dev = &btif_hh_cb.devices[i];
425     fixed_queue_flush(p_dev->get_rpt_id_queue, osi_free);
426     fixed_queue_free(p_dev->get_rpt_id_queue, NULL);
427     p_dev->get_rpt_id_queue = NULL;
428     if (p_dev->dev_status != BTHH_CONN_STATE_UNKNOWN &&
429         p_dev->dev_handle == dev_handle) {
430       APPL_TRACE_WARNING(
431           "%s: Found an existing device with the same handle "
432           "dev_status = %d, dev_handle =%d",
433           __func__, p_dev->dev_status, p_dev->dev_handle);
434       btif_hh_close_poll_thread(p_dev);
435       break;
436     }
437   }
438 }
439 
440 /*******************************************************************************
441  *
442  * Function         bta_hh_co_data
443  *
444  * Description      This function is executed by BTA when HID host receive a
445  *                  data report.
446  *
447  * Parameters       dev_handle  - device handle
448  *                  *p_rpt      - pointer to the report data
449  *                  len         - length of report data
450  *                  mode        - Hid host Protocol Mode
451  *                  sub_clas    - Device Subclass
452  *                  app_id      - application id
453  *
454  * Returns          void
455  ******************************************************************************/
bta_hh_co_data(uint8_t dev_handle,uint8_t * p_rpt,uint16_t len,tBTA_HH_PROTO_MODE mode,uint8_t sub_class,uint8_t ctry_code,UNUSED_ATTR const RawAddress & peer_addr,uint8_t app_id)456 void bta_hh_co_data(uint8_t dev_handle, uint8_t* p_rpt, uint16_t len,
457                     tBTA_HH_PROTO_MODE mode, uint8_t sub_class,
458                     uint8_t ctry_code, UNUSED_ATTR const RawAddress& peer_addr,
459                     uint8_t app_id) {
460   btif_hh_device_t* p_dev;
461 
462   APPL_TRACE_DEBUG(
463       "%s: dev_handle = %d, subclass = 0x%02X, mode = %d, "
464       "ctry_code = %d, app_id = %d",
465       __func__, dev_handle, sub_class, mode, ctry_code, app_id);
466 
467   p_dev = btif_hh_find_connected_dev_by_handle(dev_handle);
468   if (p_dev == NULL) {
469     APPL_TRACE_WARNING("%s: Error: unknown HID device handle %d", __func__,
470                        dev_handle);
471     return;
472   }
473 
474   // Wait a maximum of MAX_POLLING_ATTEMPTS x POLLING_SLEEP_DURATION in case
475   // device creation is pending.
476   if (p_dev->fd >= 0) {
477     uint32_t polling_attempts = 0;
478     while (!p_dev->ready_for_data &&
479            polling_attempts++ < BTIF_HH_MAX_POLLING_ATTEMPTS) {
480       usleep(BTIF_HH_POLLING_SLEEP_DURATION_US);
481     }
482   }
483 
484   // Send the HID data to the kernel.
485   if ((p_dev->fd >= 0) && p_dev->ready_for_data) {
486     bta_hh_co_write(p_dev->fd, p_rpt, len);
487   } else {
488     APPL_TRACE_WARNING("%s: Error: fd = %d, ready %d, len = %d", __func__,
489                        p_dev->fd, p_dev->ready_for_data, len);
490   }
491 }
492 
493 /*******************************************************************************
494  *
495  * Function         bta_hh_co_send_hid_info
496  *
497  * Description      This function is called in btif_hh.c to process DSCP
498  *                  received.
499  *
500  * Parameters       dev_handle  - device handle
501  *                  dscp_len    - report descriptor length
502  *                  *p_dscp     - report descriptor
503  *
504  * Returns          void
505  ******************************************************************************/
bta_hh_co_send_hid_info(btif_hh_device_t * p_dev,const char * dev_name,uint16_t vendor_id,uint16_t product_id,uint16_t version,uint8_t ctry_code,int dscp_len,uint8_t * p_dscp)506 void bta_hh_co_send_hid_info(btif_hh_device_t* p_dev, const char* dev_name,
507                              uint16_t vendor_id, uint16_t product_id,
508                              uint16_t version, uint8_t ctry_code, int dscp_len,
509                              uint8_t* p_dscp) {
510   int result;
511   struct uhid_event ev;
512 
513   if (p_dev->fd < 0) {
514     APPL_TRACE_WARNING("%s: Error: fd = %d, dscp_len = %d", __func__, p_dev->fd,
515                        dscp_len);
516     return;
517   }
518 
519   APPL_TRACE_WARNING("%s: fd = %d, name = [%s], dscp_len = %d", __func__,
520                      p_dev->fd, dev_name, dscp_len);
521   APPL_TRACE_WARNING(
522       "%s: vendor_id = 0x%04x, product_id = 0x%04x, version= 0x%04x,"
523       "ctry_code=0x%02x",
524       __func__, vendor_id, product_id, version, ctry_code);
525 
526   // Create and send hid descriptor to kernel
527   memset(&ev, 0, sizeof(ev));
528   ev.type = UHID_CREATE;
529   strlcpy((char*)ev.u.create.name, dev_name, sizeof(ev.u.create.name));
530   snprintf((char*)ev.u.create.uniq, sizeof(ev.u.create.uniq), "%s",
531            p_dev->bd_addr.ToString().c_str());
532   ev.u.create.rd_size = dscp_len;
533   ev.u.create.rd_data = p_dscp;
534   ev.u.create.bus = BUS_BLUETOOTH;
535   ev.u.create.vendor = vendor_id;
536   ev.u.create.product = product_id;
537   ev.u.create.version = version;
538   ev.u.create.country = ctry_code;
539   result = uhid_write(p_dev->fd, &ev);
540 
541   APPL_TRACE_WARNING(
542       "%s: wrote descriptor to fd = %d, dscp_len = %d, result = %d", __func__,
543       p_dev->fd, dscp_len, result);
544 
545   if (result) {
546     APPL_TRACE_WARNING("%s: Error: failed to send DSCP, result = %d", __func__,
547                        result);
548 
549     /* The HID report descriptor is corrupted. Close the driver. */
550     close(p_dev->fd);
551     p_dev->fd = -1;
552   }
553 }
554 
555 /*******************************************************************************
556  *
557  * Function         bta_hh_co_set_rpt_rsp
558  *
559  * Description      This callout function is executed by HH when Set Report
560  *                  Response is received on Control Channel.
561  *
562  * Returns          void.
563  *
564  ******************************************************************************/
bta_hh_co_set_rpt_rsp(uint8_t dev_handle,uint8_t status)565 void bta_hh_co_set_rpt_rsp(uint8_t dev_handle, uint8_t status) {
566   APPL_TRACE_ERROR("%s: Error: UHID_SET_REPORT_REPLY not supported", __func__);
567 }
568 
569 /*******************************************************************************
570  *
571  * Function         bta_hh_co_get_rpt_rsp
572  *
573  * Description      This callout function is executed by HH when Get Report
574  *                  Response is received on Control Channel.
575  *
576  * Returns          void.
577  *
578  ******************************************************************************/
bta_hh_co_get_rpt_rsp(uint8_t dev_handle,uint8_t status,uint8_t * p_rpt,uint16_t len)579 void bta_hh_co_get_rpt_rsp(uint8_t dev_handle, uint8_t status, uint8_t* p_rpt,
580                            uint16_t len) {
581   struct uhid_event ev;
582   btif_hh_device_t* p_dev;
583 
584   APPL_TRACE_VERBOSE("%s: dev_handle = %d", __func__, dev_handle);
585 
586   p_dev = btif_hh_find_connected_dev_by_handle(dev_handle);
587   if (p_dev == NULL) {
588     APPL_TRACE_WARNING("%s: Error: unknown HID device handle %d", __func__,
589                        dev_handle);
590     return;
591   }
592 
593   if (!p_dev->get_rpt_id_queue) {
594     APPL_TRACE_WARNING("%s: Error: missing UHID_GET_REPORT id queue", __func__);
595     return;
596   }
597 
598   // Send the HID report to the kernel.
599   if (p_dev->fd >= 0 && p_dev->get_rpt_snt > 0 && p_dev->get_rpt_snt--) {
600     uint32_t* get_rpt_id =
601         (uint32_t*)fixed_queue_dequeue(p_dev->get_rpt_id_queue);
602     memset(&ev, 0, sizeof(ev));
603     ev.type = UHID_FEATURE_ANSWER;
604     ev.u.feature_answer.id = *get_rpt_id;
605     ev.u.feature_answer.err = status;
606     ev.u.feature_answer.size = len;
607     osi_free(get_rpt_id);
608     if (len > 0) {
609       if (len > UHID_DATA_MAX) {
610         APPL_TRACE_WARNING("%s: Report size greater than allowed size",
611                            __func__);
612         return;
613       }
614       memcpy(ev.u.feature_answer.data, p_rpt + GET_RPT_RSP_OFFSET, len);
615       uhid_write(p_dev->fd, &ev);
616     }
617   }
618 }
619 
620 /*******************************************************************************
621  *
622  * Function         bta_hh_le_co_rpt_info
623  *
624  * Description      This callout function is to convey the report information on
625  *                  a HOGP device to the application. Application can save this
626  *                  information in NV if device is bonded and load it back when
627  *                  stack reboot.
628  *
629  * Parameters       remote_bda  - remote device address
630  *                  p_entry     - report entry pointer
631  *                  app_id      - application id
632  *
633  * Returns          void.
634  *
635  ******************************************************************************/
bta_hh_le_co_rpt_info(const RawAddress & remote_bda,tBTA_HH_RPT_CACHE_ENTRY * p_entry,UNUSED_ATTR uint8_t app_id)636 void bta_hh_le_co_rpt_info(const RawAddress& remote_bda,
637                            tBTA_HH_RPT_CACHE_ENTRY* p_entry,
638                            UNUSED_ATTR uint8_t app_id) {
639   unsigned idx = 0;
640 
641   std::string addrstr = remote_bda.ToString();
642   const char* bdstr = addrstr.c_str();
643 
644   size_t len = btif_config_get_bin_length(bdstr, "HidReport");
645   if (len >= sizeof(tBTA_HH_RPT_CACHE_ENTRY) && len <= sizeof(sReportCache)) {
646     btif_config_get_bin(bdstr, "HidReport", (uint8_t*)sReportCache, &len);
647     idx = len / sizeof(tBTA_HH_RPT_CACHE_ENTRY);
648   }
649 
650   if (idx < BTA_HH_NV_LOAD_MAX) {
651     memcpy(&sReportCache[idx++], p_entry, sizeof(tBTA_HH_RPT_CACHE_ENTRY));
652     btif_config_set_bin(bdstr, "HidReport", (const uint8_t*)sReportCache,
653                         idx * sizeof(tBTA_HH_RPT_CACHE_ENTRY));
654     btif_config_set_int(bdstr, "HidReportVersion", BTA_HH_CACHE_REPORT_VERSION);
655     BTIF_TRACE_DEBUG("%s() - Saving report; dev=%s, idx=%d", __func__, bdstr,
656                      idx);
657   }
658 }
659 
660 /*******************************************************************************
661  *
662  * Function         bta_hh_le_co_cache_load
663  *
664  * Description      This callout function is to request the application to load
665  *                  the cached HOGP report if there is any. When cache reading
666  *                  is completed, bta_hh_le_co_cache_load() is called by the
667  *                  application.
668  *
669  * Parameters       remote_bda  - remote device address
670  *                  p_num_rpt   - number of cached report
671  *                  app_id      - application id
672  *
673  * Returns          the cached report array
674  *
675  ******************************************************************************/
bta_hh_le_co_cache_load(const RawAddress & remote_bda,uint8_t * p_num_rpt,UNUSED_ATTR uint8_t app_id)676 tBTA_HH_RPT_CACHE_ENTRY* bta_hh_le_co_cache_load(const RawAddress& remote_bda,
677                                                  uint8_t* p_num_rpt,
678                                                  UNUSED_ATTR uint8_t app_id) {
679   std::string addrstr = remote_bda.ToString();
680   const char* bdstr = addrstr.c_str();
681 
682   size_t len = btif_config_get_bin_length(bdstr, "HidReport");
683   if (!p_num_rpt || len < sizeof(tBTA_HH_RPT_CACHE_ENTRY)) return NULL;
684 
685   if (len > sizeof(sReportCache)) len = sizeof(sReportCache);
686   btif_config_get_bin(bdstr, "HidReport", (uint8_t*)sReportCache, &len);
687 
688   int cache_version = -1;
689   btif_config_get_int(bdstr, "HidReportVersion", &cache_version);
690 
691   if (cache_version != BTA_HH_CACHE_REPORT_VERSION) {
692     bta_hh_le_co_reset_rpt_cache(remote_bda, app_id);
693     return NULL;
694   }
695 
696   *p_num_rpt = len / sizeof(tBTA_HH_RPT_CACHE_ENTRY);
697 
698   BTIF_TRACE_DEBUG("%s() - Loaded %d reports; dev=%s", __func__, *p_num_rpt,
699                    bdstr);
700 
701   return sReportCache;
702 }
703 
704 /*******************************************************************************
705  *
706  * Function         bta_hh_le_co_reset_rpt_cache
707  *
708  * Description      This callout function is to reset the HOGP device cache.
709  *
710  * Parameters       remote_bda  - remote device address
711  *
712  * Returns          none
713  *
714  ******************************************************************************/
bta_hh_le_co_reset_rpt_cache(const RawAddress & remote_bda,UNUSED_ATTR uint8_t app_id)715 void bta_hh_le_co_reset_rpt_cache(const RawAddress& remote_bda,
716                                   UNUSED_ATTR uint8_t app_id) {
717   std::string addrstr = remote_bda.ToString();
718   const char* bdstr = addrstr.c_str();
719 
720   btif_config_remove(bdstr, "HidReport");
721   btif_config_remove(bdstr, "HidReportVersion");
722   BTIF_TRACE_DEBUG("%s() - Reset cache for bda %s", __func__, bdstr);
723 }
724