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