1/******************************************************************************
2 *
3 *  Copyright 2003-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/******************************************************************************
20 *
21 *  This file contains the GATT client action functions for the state
22 *  machine.
23 *
24 ******************************************************************************/
25
26#define LOG_TAG "bt_bta_gattc"
27
28#include <string.h>
29
30#include <base/callback.h>
31#include "bt_common.h"
32#include "bt_target.h"
33#include "bta_closure_api.h"
34#include "bta_gattc_int.h"
35#include "bta_sys.h"
36#include "btif/include/btif_debug_conn.h"
37#include "l2c_api.h"
38#include "osi/include/log.h"
39#include "osi/include/osi.h"
40#include "stack/l2cap/l2c_int.h"
41#include "utl.h"
42
43#if (BTA_HH_LE_INCLUDED == TRUE)
44#include "bta_hh_int.h"
45#endif
46
47using base::StringPrintf;
48using bluetooth::Uuid;
49
50/*****************************************************************************
51 *  Constants
52 ****************************************************************************/
53static void bta_gattc_conn_cback(tGATT_IF gattc_if, const RawAddress& bda,
54                                 uint16_t conn_id, bool connected,
55                                 tGATT_DISCONN_REASON reason,
56                                 tBT_TRANSPORT transport);
57
58static void bta_gattc_cmpl_cback(uint16_t conn_id, tGATTC_OPTYPE op,
59                                 tGATT_STATUS status,
60                                 tGATT_CL_COMPLETE* p_data);
61static void bta_gattc_cmpl_sendmsg(uint16_t conn_id, tGATTC_OPTYPE op,
62                                   tGATT_STATUS status,
63                                   tGATT_CL_COMPLETE* p_data);
64
65static void bta_gattc_deregister_cmpl(tBTA_GATTC_RCB* p_clreg);
66static void bta_gattc_enc_cmpl_cback(tGATT_IF gattc_if, const RawAddress& bda);
67static void bta_gattc_cong_cback(uint16_t conn_id, bool congested);
68static void bta_gattc_phy_update_cback(tGATT_IF gatt_if, uint16_t conn_id,
69                                       uint8_t tx_phy, uint8_t rx_phy,
70                                       uint8_t status);
71static void bta_gattc_conn_update_cback(tGATT_IF gatt_if, uint16_t conn_id,
72                                        uint16_t interval, uint16_t latency,
73                                        uint16_t timeout, uint8_t status);
74
75static tGATT_CBACK bta_gattc_cl_cback = {bta_gattc_conn_cback,
76                                         bta_gattc_cmpl_cback,
77                                         bta_gattc_disc_res_cback,
78                                         bta_gattc_disc_cmpl_cback,
79                                         NULL,
80                                         bta_gattc_enc_cmpl_cback,
81                                         bta_gattc_cong_cback,
82                                         bta_gattc_phy_update_cback,
83                                         bta_gattc_conn_update_cback};
84
85/* opcode(tGATTC_OPTYPE) order has to be comply with internal event order */
86static uint16_t bta_gattc_opcode_to_int_evt[] = {
87    /* Skip: GATTC_OPTYPE_NONE */
88    /* Skip: GATTC_OPTYPE_DISCOVERY */
89    BTA_GATTC_API_READ_EVT,   /* GATTC_OPTYPE_READ */
90    BTA_GATTC_API_WRITE_EVT,  /* GATTC_OPTYPE_WRITE */
91    BTA_GATTC_API_EXEC_EVT,   /* GATTC_OPTYPE_EXE_WRITE */
92    BTA_GATTC_API_CFG_MTU_EVT /* GATTC_OPTYPE_CONFIG */
93};
94
95static const char* bta_gattc_op_code_name[] = {
96    "Unknown",      /* GATTC_OPTYPE_NONE */
97    "Discovery",    /* GATTC_OPTYPE_DISCOVERY */
98    "Read",         /* GATTC_OPTYPE_READ */
99    "Write",        /* GATTC_OPTYPE_WRITE */
100    "Exec",         /* GATTC_OPTYPE_EXE_WRITE */
101    "Config",       /* GATTC_OPTYPE_CONFIG */
102    "Notification", /* GATTC_OPTYPE_NOTIFICATION */
103    "Indication"    /* GATTC_OPTYPE_INDICATION */
104};
105
106/*****************************************************************************
107 *  Action Functions
108 ****************************************************************************/
109
110void bta_gattc_reset_discover_st(tBTA_GATTC_SERV* p_srcb, tGATT_STATUS status);
111
112/** Enables GATTC module */
113static void bta_gattc_enable() {
114  VLOG(1) << __func__;
115
116  if (bta_gattc_cb.state == BTA_GATTC_STATE_DISABLED) {
117    /* initialize control block */
118    bta_gattc_cb = tBTA_GATTC_CB();
119    bta_gattc_cb.state = BTA_GATTC_STATE_ENABLED;
120  } else {
121    VLOG(1) << "GATTC is already enabled";
122  }
123}
124
125/** Disable GATTC module by cleaning up all active connections and deregister
126 * all application */
127void bta_gattc_disable() {
128  uint8_t i;
129
130  VLOG(1) << __func__;
131
132  if (bta_gattc_cb.state != BTA_GATTC_STATE_ENABLED) {
133    LOG(ERROR) << "not enabled, or disabled in progress";
134    return;
135  }
136
137  for (i = 0; i < BTA_GATTC_CL_MAX; i++) {
138    if (!bta_gattc_cb.cl_rcb[i].in_use) continue;
139
140    bta_gattc_cb.state = BTA_GATTC_STATE_DISABLING;
141/* don't deregister HH GATT IF */
142/* HH GATT IF will be deregistered by bta_hh_le_deregister when disable HH */
143#if (BTA_HH_LE_INCLUDED == TRUE)
144    if (!bta_hh_le_is_hh_gatt_if(bta_gattc_cb.cl_rcb[i].client_if)) {
145#endif
146      bta_gattc_deregister(&bta_gattc_cb.cl_rcb[i]);
147#if (BTA_HH_LE_INCLUDED == TRUE)
148    }
149#endif
150  }
151
152  /* no registered apps, indicate disable completed */
153  if (bta_gattc_cb.state != BTA_GATTC_STATE_DISABLING) {
154    bta_gattc_cb = tBTA_GATTC_CB();
155    bta_gattc_cb.state = BTA_GATTC_STATE_DISABLED;
156  }
157}
158
159/** start an application interface */
160void bta_gattc_start_if(uint8_t client_if) {
161  if (!bta_gattc_cl_get_regcb(client_if)) {
162    LOG(ERROR) << "Unable to start app.: Unknown client_if=" << +client_if;
163    return;
164  }
165
166  GATT_StartIf(client_if);
167}
168
169/** Register a GATT client application with BTA */
170void bta_gattc_register(const Uuid& app_uuid, tBTA_GATTC_CBACK* p_cback,
171                        BtaAppRegisterCallback cb) {
172  tGATT_STATUS status = GATT_NO_RESOURCES;
173  uint8_t client_if = 0;
174  VLOG(1) << __func__ << ": state:" << +bta_gattc_cb.state;
175
176  /* check if  GATTC module is already enabled . Else enable */
177  if (bta_gattc_cb.state == BTA_GATTC_STATE_DISABLED) {
178    bta_gattc_enable();
179  }
180  /* todo need to check duplicate uuid */
181  for (uint8_t i = 0; i < BTA_GATTC_CL_MAX; i++) {
182    if (!bta_gattc_cb.cl_rcb[i].in_use) {
183      if ((bta_gattc_cb.cl_rcb[i].client_if =
184               GATT_Register(app_uuid, &bta_gattc_cl_cback)) == 0) {
185        LOG(ERROR) << "Register with GATT stack failed.";
186        status = GATT_ERROR;
187      } else {
188        bta_gattc_cb.cl_rcb[i].in_use = true;
189        bta_gattc_cb.cl_rcb[i].p_cback = p_cback;
190        bta_gattc_cb.cl_rcb[i].app_uuid = app_uuid;
191
192        /* BTA use the same client interface as BTE GATT statck */
193        client_if = bta_gattc_cb.cl_rcb[i].client_if;
194
195        do_in_bta_thread(FROM_HERE, base::Bind(&bta_gattc_start_if, client_if));
196
197        status = GATT_SUCCESS;
198        break;
199      }
200    }
201  }
202
203  if (!cb.is_null()) cb.Run(client_if, status);
204}
205
206/** De-Register a GATT client application with BTA */
207void bta_gattc_deregister(tBTA_GATTC_RCB* p_clreg) {
208  if (!p_clreg) {
209    LOG(ERROR) << __func__ << ": Deregister Failed unknown client cif";
210    bta_hh_cleanup_disable(BTA_HH_OK);
211    return;
212  }
213
214  /* remove bg connection associated with this rcb */
215  for (uint8_t i = 0; i < BTA_GATTC_KNOWN_SR_MAX; i++) {
216    if (!bta_gattc_cb.bg_track[i].in_use) continue;
217
218    if (bta_gattc_cb.bg_track[i].cif_mask & (1 << (p_clreg->client_if - 1))) {
219      bta_gattc_mark_bg_conn(p_clreg->client_if,
220                             bta_gattc_cb.bg_track[i].remote_bda, false);
221      GATT_CancelConnect(p_clreg->client_if,
222                         bta_gattc_cb.bg_track[i].remote_bda, false);
223    }
224  }
225
226  if (p_clreg->num_clcb == 0) {
227    bta_gattc_deregister_cmpl(p_clreg);
228    return;
229  }
230
231  /* close all CLCB related to this app */
232  for (uint8_t i = 0; i < BTA_GATTC_CLCB_MAX; i++) {
233    if (!bta_gattc_cb.clcb[i].in_use || (bta_gattc_cb.clcb[i].p_rcb != p_clreg))
234      continue;
235
236    p_clreg->dereg_pending = true;
237
238    BT_HDR buf;
239    buf.event = BTA_GATTC_API_CLOSE_EVT;
240    buf.layer_specific = bta_gattc_cb.clcb[i].bta_conn_id;
241    bta_gattc_close(&bta_gattc_cb.clcb[i], (tBTA_GATTC_DATA*)&buf);
242  }
243}
244
245/** process connect API request */
246void bta_gattc_process_api_open(tBTA_GATTC_DATA* p_msg) {
247  uint16_t event = ((BT_HDR*)p_msg)->event;
248
249  tBTA_GATTC_RCB* p_clreg = bta_gattc_cl_get_regcb(p_msg->api_conn.client_if);
250  if (!p_clreg) {
251    LOG(ERROR) << __func__
252               << ": Failed, unknown client_if=" << +p_msg->api_conn.client_if;
253    return;
254  }
255
256  if (!p_msg->api_conn.is_direct) {
257    bta_gattc_init_bk_conn(&p_msg->api_conn, p_clreg);
258    return;
259  }
260
261  tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_alloc_clcb(
262      p_msg->api_conn.client_if, p_msg->api_conn.remote_bda,
263      p_msg->api_conn.transport);
264  if (p_clcb != NULL) {
265    bta_gattc_sm_execute(p_clcb, event, p_msg);
266  } else {
267    LOG(ERROR) << "No resources to open a new connection.";
268
269    bta_gattc_send_open_cback(p_clreg, GATT_NO_RESOURCES,
270                              p_msg->api_conn.remote_bda, GATT_INVALID_CONN_ID,
271                              p_msg->api_conn.transport, 0);
272  }
273}
274
275/** process connect API request */
276void bta_gattc_process_api_open_cancel(tBTA_GATTC_DATA* p_msg) {
277  uint16_t event = ((BT_HDR*)p_msg)->event;
278
279  if (!p_msg->api_cancel_conn.is_direct) {
280    bta_gattc_cancel_bk_conn(&p_msg->api_cancel_conn);
281    return;
282  }
283
284  tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_cif(
285      p_msg->api_cancel_conn.client_if, p_msg->api_cancel_conn.remote_bda,
286      GATT_TRANSPORT_LE);
287  if (p_clcb != NULL) {
288    bta_gattc_sm_execute(p_clcb, event, p_msg);
289    return;
290  }
291
292  LOG(ERROR) << "No such connection need to be cancelled";
293
294  tBTA_GATTC_RCB* p_clreg =
295      bta_gattc_cl_get_regcb(p_msg->api_cancel_conn.client_if);
296
297  if (p_clreg && p_clreg->p_cback) {
298    tBTA_GATTC cb_data;
299    cb_data.status = GATT_ERROR;
300    (*p_clreg->p_cback)(BTA_GATTC_CANCEL_OPEN_EVT, &cb_data);
301  }
302}
303
304/** process encryption complete message */
305void bta_gattc_process_enc_cmpl(tGATT_IF client_if, const RawAddress& bda) {
306  tBTA_GATTC_RCB* p_clreg = bta_gattc_cl_get_regcb(client_if);
307
308  if (!p_clreg || !p_clreg->p_cback) return;
309
310  tBTA_GATTC cb_data;
311  memset(&cb_data, 0, sizeof(tBTA_GATTC));
312
313  cb_data.enc_cmpl.client_if = client_if;
314  cb_data.enc_cmpl.remote_bda = bda;
315
316  (*p_clreg->p_cback)(BTA_GATTC_ENC_CMPL_CB_EVT, &cb_data);
317}
318
319void bta_gattc_cancel_open_error(tBTA_GATTC_CLCB* p_clcb,
320                                 UNUSED_ATTR tBTA_GATTC_DATA* p_data) {
321  tBTA_GATTC cb_data;
322
323  cb_data.status = GATT_ERROR;
324
325  if (p_clcb && p_clcb->p_rcb && p_clcb->p_rcb->p_cback)
326    (*p_clcb->p_rcb->p_cback)(BTA_GATTC_CANCEL_OPEN_EVT, &cb_data);
327}
328
329void bta_gattc_open_error(tBTA_GATTC_CLCB* p_clcb,
330                          UNUSED_ATTR tBTA_GATTC_DATA* p_data) {
331  LOG(ERROR) << "Connection already opened. wrong state";
332
333  bta_gattc_send_open_cback(p_clcb->p_rcb, GATT_SUCCESS, p_clcb->bda,
334                            p_clcb->bta_conn_id, p_clcb->transport, 0);
335}
336
337void bta_gattc_open_fail(tBTA_GATTC_CLCB* p_clcb,
338                         UNUSED_ATTR tBTA_GATTC_DATA* p_data) {
339  LOG(WARNING) << __func__ << ": Cannot establish Connection. conn_id="
340               << +p_clcb->bta_conn_id << ". Return GATT_ERROR(" << +GATT_ERROR
341               << ")";
342
343  bta_gattc_send_open_cback(p_clcb->p_rcb, GATT_ERROR, p_clcb->bda,
344                            p_clcb->bta_conn_id, p_clcb->transport, 0);
345  /* open failure, remove clcb */
346  bta_gattc_clcb_dealloc(p_clcb);
347}
348
349/** Process API connection function */
350void bta_gattc_open(tBTA_GATTC_CLCB* p_clcb, tBTA_GATTC_DATA* p_data) {
351  tBTA_GATTC_DATA gattc_data;
352
353  /* open/hold a connection */
354  if (!GATT_Connect(p_clcb->p_rcb->client_if, p_data->api_conn.remote_bda, true,
355                    p_data->api_conn.transport, p_data->api_conn.opportunistic,
356                    p_data->api_conn.initiating_phys)) {
357    LOG(ERROR) << "Connection open failure";
358
359    bta_gattc_sm_execute(p_clcb, BTA_GATTC_INT_OPEN_FAIL_EVT, p_data);
360    return;
361  }
362
363  /* a connected remote device */
364  if (GATT_GetConnIdIfConnected(
365          p_clcb->p_rcb->client_if, p_data->api_conn.remote_bda,
366          &p_clcb->bta_conn_id, p_data->api_conn.transport)) {
367    gattc_data.int_conn.hdr.layer_specific = p_clcb->bta_conn_id;
368
369    bta_gattc_sm_execute(p_clcb, BTA_GATTC_INT_CONN_EVT, &gattc_data);
370  }
371  /* else wait for the callback event */
372}
373
374/** Process API Open for a background connection */
375void bta_gattc_init_bk_conn(tBTA_GATTC_API_OPEN* p_data,
376                            tBTA_GATTC_RCB* p_clreg) {
377  if (!bta_gattc_mark_bg_conn(p_data->client_if, p_data->remote_bda, true)) {
378    bta_gattc_send_open_cback(p_clreg, GATT_NO_RESOURCES, p_data->remote_bda,
379                              GATT_INVALID_CONN_ID, GATT_TRANSPORT_LE, 0);
380    return;
381  }
382
383  /* always call open to hold a connection */
384  if (!GATT_Connect(p_data->client_if, p_data->remote_bda, false,
385                    p_data->transport, false)) {
386    LOG(ERROR) << __func__
387               << " unable to connect to remote bd_addr=" << p_data->remote_bda;
388    bta_gattc_send_open_cback(p_clreg, GATT_ERROR, p_data->remote_bda,
389                              GATT_INVALID_CONN_ID, GATT_TRANSPORT_LE, 0);
390    return;
391  }
392
393  uint16_t conn_id;
394  /* if is not a connected remote device */
395  if (!GATT_GetConnIdIfConnected(p_data->client_if, p_data->remote_bda,
396                                 &conn_id, p_data->transport)) {
397    return;
398  }
399
400  tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_alloc_clcb(
401      p_data->client_if, p_data->remote_bda, GATT_TRANSPORT_LE);
402  if (!p_clcb) return;
403
404  tBTA_GATTC_DATA gattc_data;
405  gattc_data.hdr.layer_specific = p_clcb->bta_conn_id = conn_id;
406
407  /* open connection */
408  bta_gattc_sm_execute(p_clcb, BTA_GATTC_INT_CONN_EVT, &gattc_data);
409}
410
411/** Process API Cancel Open for a background connection */
412void bta_gattc_cancel_bk_conn(tBTA_GATTC_API_CANCEL_OPEN* p_data) {
413  tBTA_GATTC_RCB* p_clreg;
414  tBTA_GATTC cb_data;
415  cb_data.status = GATT_ERROR;
416
417  /* remove the device from the bg connection mask */
418  if (bta_gattc_mark_bg_conn(p_data->client_if, p_data->remote_bda, false)) {
419    if (GATT_CancelConnect(p_data->client_if, p_data->remote_bda, false)) {
420      cb_data.status = GATT_SUCCESS;
421    } else {
422      LOG(ERROR) << __func__ << ": failed";
423    }
424  }
425  p_clreg = bta_gattc_cl_get_regcb(p_data->client_if);
426
427  if (p_clreg && p_clreg->p_cback) {
428    (*p_clreg->p_cback)(BTA_GATTC_CANCEL_OPEN_EVT, &cb_data);
429  }
430}
431
432void bta_gattc_cancel_open_ok(tBTA_GATTC_CLCB* p_clcb,
433                              UNUSED_ATTR tBTA_GATTC_DATA* p_data) {
434  tBTA_GATTC cb_data;
435
436  if (p_clcb->p_rcb->p_cback) {
437    cb_data.status = GATT_SUCCESS;
438    (*p_clcb->p_rcb->p_cback)(BTA_GATTC_CANCEL_OPEN_EVT, &cb_data);
439  }
440
441  bta_gattc_clcb_dealloc(p_clcb);
442}
443
444void bta_gattc_cancel_open(tBTA_GATTC_CLCB* p_clcb, tBTA_GATTC_DATA* p_data) {
445  tBTA_GATTC cb_data;
446
447  if (GATT_CancelConnect(p_clcb->p_rcb->client_if,
448                         p_data->api_cancel_conn.remote_bda, true)) {
449    bta_gattc_sm_execute(p_clcb, BTA_GATTC_INT_CANCEL_OPEN_OK_EVT, p_data);
450  } else {
451    if (p_clcb->p_rcb->p_cback) {
452      cb_data.status = GATT_ERROR;
453      (*p_clcb->p_rcb->p_cback)(BTA_GATTC_CANCEL_OPEN_EVT, &cb_data);
454    }
455  }
456}
457
458/** receive connection callback from stack */
459void bta_gattc_conn(tBTA_GATTC_CLCB* p_clcb, tBTA_GATTC_DATA* p_data) {
460  tGATT_IF gatt_if;
461  VLOG(1) << __func__ << ": server cache state=" << +p_clcb->p_srcb->state;
462
463  if (p_data != NULL) {
464    VLOG(1) << __func__ << ": conn_id=" << +p_data->hdr.layer_specific;
465    p_clcb->bta_conn_id = p_data->int_conn.hdr.layer_specific;
466
467    GATT_GetConnectionInfor(p_data->hdr.layer_specific, &gatt_if, p_clcb->bda,
468                            &p_clcb->transport);
469  }
470
471  p_clcb->p_srcb->connected = true;
472
473  if (p_clcb->p_srcb->mtu == 0) p_clcb->p_srcb->mtu = GATT_DEF_BLE_MTU_SIZE;
474
475  /* start database cache if needed */
476  if (p_clcb->p_srcb->srvc_cache.empty() ||
477      p_clcb->p_srcb->state != BTA_GATTC_SERV_IDLE) {
478    if (p_clcb->p_srcb->state == BTA_GATTC_SERV_IDLE) {
479      p_clcb->p_srcb->state = BTA_GATTC_SERV_LOAD;
480      if (bta_gattc_cache_load(p_clcb)) {
481        p_clcb->p_srcb->state = BTA_GATTC_SERV_IDLE;
482        bta_gattc_reset_discover_st(p_clcb->p_srcb, GATT_SUCCESS);
483      } else {
484        p_clcb->p_srcb->state = BTA_GATTC_SERV_DISC;
485        /* cache load failure, start discovery */
486        bta_gattc_start_discover(p_clcb, NULL);
487      }
488    } else /* cache is building */
489      p_clcb->state = BTA_GATTC_DISCOVER_ST;
490  }
491
492  else {
493    /* a pending service handle change indication */
494    if (p_clcb->p_srcb->srvc_hdl_chg) {
495      p_clcb->p_srcb->srvc_hdl_chg = false;
496      /* start discovery */
497      bta_gattc_sm_execute(p_clcb, BTA_GATTC_INT_DISCOVER_EVT, NULL);
498    }
499  }
500
501  if (p_clcb->p_rcb) {
502    /* there is no RM for GATT */
503    if (p_clcb->transport == BTA_TRANSPORT_BR_EDR)
504      bta_sys_conn_open(BTA_ID_GATTC, BTA_ALL_APP_ID, p_clcb->bda);
505
506    bta_gattc_send_open_cback(p_clcb->p_rcb, GATT_SUCCESS, p_clcb->bda,
507                              p_clcb->bta_conn_id, p_clcb->transport,
508                              p_clcb->p_srcb->mtu);
509  }
510}
511
512/** close a  connection */
513void bta_gattc_close_fail(tBTA_GATTC_CLCB* p_clcb, tBTA_GATTC_DATA* p_data) {
514  tBTA_GATTC cb_data;
515
516  if (p_clcb->p_rcb->p_cback) {
517    memset(&cb_data, 0, sizeof(tBTA_GATTC));
518    cb_data.close.client_if = p_clcb->p_rcb->client_if;
519    cb_data.close.conn_id = p_data->hdr.layer_specific;
520    cb_data.close.remote_bda = p_clcb->bda;
521    cb_data.close.status = GATT_ERROR;
522    cb_data.close.reason = BTA_GATT_CONN_NONE;
523
524    LOG(WARNING) << __func__ << ": conn_id=" << loghex(cb_data.close.conn_id)
525                 << ". Returns GATT_ERROR(" << +GATT_ERROR << ").";
526
527    (*p_clcb->p_rcb->p_cback)(BTA_GATTC_CLOSE_EVT, &cb_data);
528  }
529}
530
531/** close a GATTC connection */
532void bta_gattc_close(tBTA_GATTC_CLCB* p_clcb, tBTA_GATTC_DATA* p_data) {
533  tBTA_GATTC_CBACK* p_cback = p_clcb->p_rcb->p_cback;
534  tBTA_GATTC_RCB* p_clreg = p_clcb->p_rcb;
535  tBTA_GATTC cb_data;
536
537  VLOG(1) << __func__ << ": conn_id=" << +p_clcb->bta_conn_id;
538
539  cb_data.close.client_if = p_clcb->p_rcb->client_if;
540  cb_data.close.conn_id = p_clcb->bta_conn_id;
541  cb_data.close.reason = p_clcb->reason;
542  cb_data.close.status = p_clcb->status;
543  cb_data.close.remote_bda = p_clcb->bda;
544
545  if (p_clcb->transport == BTA_TRANSPORT_BR_EDR)
546    bta_sys_conn_close(BTA_ID_GATTC, BTA_ALL_APP_ID, p_clcb->bda);
547
548  bta_gattc_clcb_dealloc(p_clcb);
549
550  if (p_data->hdr.event == BTA_GATTC_API_CLOSE_EVT) {
551    cb_data.close.status = GATT_Disconnect(p_data->hdr.layer_specific);
552  } else if (p_data->hdr.event == BTA_GATTC_INT_DISCONN_EVT) {
553    cb_data.close.status = p_data->int_conn.reason;
554    cb_data.close.reason = p_data->int_conn.reason;
555  }
556
557  if (p_cback) (*p_cback)(BTA_GATTC_CLOSE_EVT, &cb_data);
558
559  if (p_clreg->num_clcb == 0 && p_clreg->dereg_pending) {
560    bta_gattc_deregister_cmpl(p_clreg);
561  }
562}
563
564/** when a SRCB finished discovery, tell all related clcb */
565void bta_gattc_reset_discover_st(tBTA_GATTC_SERV* p_srcb, tGATT_STATUS status) {
566  for (uint8_t i = 0; i < BTA_GATTC_CLCB_MAX; i++) {
567    if (bta_gattc_cb.clcb[i].p_srcb == p_srcb) {
568      bta_gattc_cb.clcb[i].status = status;
569      bta_gattc_sm_execute(&bta_gattc_cb.clcb[i], BTA_GATTC_DISCOVER_CMPL_EVT,
570                           NULL);
571    }
572  }
573}
574
575/** close a GATTC connection while in discovery state */
576void bta_gattc_disc_close(tBTA_GATTC_CLCB* p_clcb, tBTA_GATTC_DATA* p_data) {
577  VLOG(1) << __func__ << ": Discovery cancel conn_id=" << +p_clcb->bta_conn_id;
578
579  if (p_clcb->disc_active)
580    bta_gattc_reset_discover_st(p_clcb->p_srcb, GATT_ERROR);
581  else
582    p_clcb->state = BTA_GATTC_CONN_ST;
583
584  // This function only gets called as the result of a BTA_GATTC_API_CLOSE_EVT
585  // while in the BTA_GATTC_DISCOVER_ST state. Once the state changes, the
586  // connection itself still needs to be closed to resolve the original event.
587  if (p_clcb->state == BTA_GATTC_CONN_ST) {
588    VLOG(1) << "State is back to BTA_GATTC_CONN_ST. Trigger connection close";
589    bta_gattc_close(p_clcb, p_data);
590  }
591}
592
593/** when a SRCB start discovery, tell all related clcb and set the state */
594void bta_gattc_set_discover_st(tBTA_GATTC_SERV* p_srcb) {
595  uint8_t i;
596
597  L2CA_EnableUpdateBleConnParams(p_srcb->server_bda, false);
598  for (i = 0; i < BTA_GATTC_CLCB_MAX; i++) {
599    if (bta_gattc_cb.clcb[i].p_srcb == p_srcb) {
600      bta_gattc_cb.clcb[i].status = GATT_SUCCESS;
601      bta_gattc_cb.clcb[i].state = BTA_GATTC_DISCOVER_ST;
602    }
603  }
604}
605
606/** process service change in discovery state, mark up the auto update flag and
607 * set status to be discovery cancel for current discovery.
608 */
609void bta_gattc_restart_discover(tBTA_GATTC_CLCB* p_clcb,
610                                UNUSED_ATTR tBTA_GATTC_DATA* p_data) {
611  p_clcb->status = GATT_CANCEL;
612  p_clcb->auto_update = BTA_GATTC_DISC_WAITING;
613}
614
615/** Configure MTU size on the GATT connection */
616void bta_gattc_cfg_mtu(tBTA_GATTC_CLCB* p_clcb, tBTA_GATTC_DATA* p_data) {
617  if (!bta_gattc_enqueue(p_clcb, p_data)) return;
618
619  tGATT_STATUS status =
620      GATTC_ConfigureMTU(p_clcb->bta_conn_id, p_data->api_mtu.mtu);
621
622  /* if failed, return callback here */
623  if (status != GATT_SUCCESS && status != GATT_CMD_STARTED) {
624    /* Dequeue the data, if it was enqueued */
625    if (p_clcb->p_q_cmd == p_data) p_clcb->p_q_cmd = NULL;
626
627    bta_gattc_cmpl_sendmsg(p_clcb->bta_conn_id, GATTC_OPTYPE_CONFIG, status,
628                           NULL);
629  }
630}
631
632/** Start a discovery on server */
633void bta_gattc_start_discover(tBTA_GATTC_CLCB* p_clcb,
634                              UNUSED_ATTR tBTA_GATTC_DATA* p_data) {
635  VLOG(1) << __func__ << ": conn_id:" << +p_clcb->bta_conn_id
636          << " p_clcb->p_srcb->state:" << +p_clcb->p_srcb->state;
637
638  if (((p_clcb->p_q_cmd == NULL ||
639        p_clcb->auto_update == BTA_GATTC_REQ_WAITING) &&
640       p_clcb->p_srcb->state == BTA_GATTC_SERV_IDLE) ||
641      p_clcb->p_srcb->state == BTA_GATTC_SERV_DISC)
642  /* no pending operation, start discovery right away */
643  {
644    p_clcb->auto_update = BTA_GATTC_NO_SCHEDULE;
645
646    if (p_clcb->p_srcb != NULL) {
647      /* clear the service change mask */
648      p_clcb->p_srcb->srvc_hdl_chg = false;
649      p_clcb->p_srcb->update_count = 0;
650      p_clcb->p_srcb->state = BTA_GATTC_SERV_DISC_ACT;
651
652      if (p_clcb->transport == BTA_TRANSPORT_LE)
653        L2CA_EnableUpdateBleConnParams(p_clcb->p_srcb->server_bda, false);
654
655      /* set all srcb related clcb into discovery ST */
656      bta_gattc_set_discover_st(p_clcb->p_srcb);
657
658      p_clcb->status = bta_gattc_init_cache(p_clcb->p_srcb);
659      if (p_clcb->status == GATT_SUCCESS) {
660        p_clcb->status = bta_gattc_discover_pri_service(
661            p_clcb->bta_conn_id, p_clcb->p_srcb, GATT_DISC_SRVC_ALL);
662      }
663      if (p_clcb->status != GATT_SUCCESS) {
664        LOG(ERROR) << "discovery on server failed";
665        bta_gattc_reset_discover_st(p_clcb->p_srcb, p_clcb->status);
666      } else
667        p_clcb->disc_active = true;
668    } else {
669      LOG(ERROR) << "unknown device, can not start discovery";
670    }
671  }
672  /* pending operation, wait until it finishes */
673  else {
674    p_clcb->auto_update = BTA_GATTC_DISC_WAITING;
675
676    if (p_clcb->p_srcb->state == BTA_GATTC_SERV_IDLE)
677      p_clcb->state = BTA_GATTC_CONN_ST; /* set clcb state */
678  }
679}
680
681/** discovery on server is finished */
682void bta_gattc_disc_cmpl(tBTA_GATTC_CLCB* p_clcb,
683                         UNUSED_ATTR tBTA_GATTC_DATA* p_data) {
684  tBTA_GATTC_DATA* p_q_cmd = p_clcb->p_q_cmd;
685
686  VLOG(1) << __func__ << ": conn_id=" << +p_clcb->bta_conn_id;
687
688  if (p_clcb->transport == BTA_TRANSPORT_LE)
689    L2CA_EnableUpdateBleConnParams(p_clcb->p_srcb->server_bda, true);
690  p_clcb->p_srcb->state = BTA_GATTC_SERV_IDLE;
691  p_clcb->disc_active = false;
692
693  if (p_clcb->status != GATT_SUCCESS) {
694    /* clean up cache */
695    if (p_clcb->p_srcb) {
696      // clear reallocating
697      std::vector<tBTA_GATTC_SERVICE>().swap(p_clcb->p_srcb->srvc_cache);
698    }
699
700    /* used to reset cache in application */
701    bta_gattc_cache_reset(p_clcb->p_srcb->server_bda);
702  }
703  if (p_clcb->p_srcb) {
704    /* release pending attribute list buffer */
705    p_clcb->p_srcb->pending_discovery.clear();
706  }
707
708  if (p_clcb->auto_update == BTA_GATTC_DISC_WAITING) {
709    /* start discovery again */
710    p_clcb->auto_update = BTA_GATTC_REQ_WAITING;
711    bta_gattc_sm_execute(p_clcb, BTA_GATTC_INT_DISCOVER_EVT, NULL);
712  }
713  /* get any queued command to proceed */
714  else if (p_q_cmd != NULL) {
715    p_clcb->p_q_cmd = NULL;
716    /* execute pending operation of link block still present */
717    if (l2cu_find_lcb_by_bd_addr(p_clcb->p_srcb->server_bda,
718                                 p_clcb->transport)) {
719      bta_gattc_sm_execute(p_clcb, p_q_cmd->hdr.event, p_q_cmd);
720    }
721    /* if the command executed requeued the cmd, we don't
722     * want to free the underlying buffer that's being
723     * referenced by p_clcb->p_q_cmd
724     */
725    if (p_q_cmd != p_clcb->p_q_cmd) osi_free_and_reset((void**)&p_q_cmd);
726  }
727}
728
729/** Read an attribute */
730void bta_gattc_read(tBTA_GATTC_CLCB* p_clcb, tBTA_GATTC_DATA* p_data) {
731  if (!bta_gattc_enqueue(p_clcb, p_data)) return;
732
733  tGATT_STATUS status;
734  if (p_data->api_read.handle != 0) {
735    tGATT_READ_PARAM read_param;
736    memset(&read_param, 0, sizeof(tGATT_READ_PARAM));
737    read_param.by_handle.handle = p_data->api_read.handle;
738    read_param.by_handle.auth_req = p_data->api_read.auth_req;
739    status = GATTC_Read(p_clcb->bta_conn_id, GATT_READ_BY_HANDLE, &read_param);
740  } else {
741    tGATT_READ_PARAM read_param;
742    memset(&read_param, 0, sizeof(tGATT_READ_BY_TYPE));
743
744    read_param.char_type.s_handle = p_data->api_read.s_handle;
745    read_param.char_type.e_handle = p_data->api_read.e_handle;
746    read_param.char_type.uuid = p_data->api_read.uuid;
747    read_param.char_type.auth_req = p_data->api_read.auth_req;
748    status = GATTC_Read(p_clcb->bta_conn_id, GATT_READ_BY_TYPE, &read_param);
749  }
750
751  /* read fail */
752  if (status != GATT_SUCCESS) {
753    /* Dequeue the data, if it was enqueued */
754    if (p_clcb->p_q_cmd == p_data) p_clcb->p_q_cmd = NULL;
755
756    bta_gattc_cmpl_sendmsg(p_clcb->bta_conn_id, GATTC_OPTYPE_READ, status,
757                           NULL);
758  }
759}
760
761/** read multiple */
762void bta_gattc_read_multi(tBTA_GATTC_CLCB* p_clcb, tBTA_GATTC_DATA* p_data) {
763  if (!bta_gattc_enqueue(p_clcb, p_data)) return;
764
765  tGATT_READ_PARAM read_param;
766  memset(&read_param, 0, sizeof(tGATT_READ_PARAM));
767
768  read_param.read_multiple.num_handles = p_data->api_read_multi.num_attr;
769  read_param.read_multiple.auth_req = p_data->api_read_multi.auth_req;
770  memcpy(&read_param.read_multiple.handles, p_data->api_read_multi.handles,
771         sizeof(uint16_t) * p_data->api_read_multi.num_attr);
772
773  tGATT_STATUS status =
774      GATTC_Read(p_clcb->bta_conn_id, GATT_READ_MULTIPLE, &read_param);
775  /* read fail */
776  if (status != GATT_SUCCESS) {
777    /* Dequeue the data, if it was enqueued */
778    if (p_clcb->p_q_cmd == p_data) p_clcb->p_q_cmd = NULL;
779
780    bta_gattc_cmpl_sendmsg(p_clcb->bta_conn_id, GATTC_OPTYPE_READ, status,
781                           NULL);
782  }
783}
784
785/** Write an attribute */
786void bta_gattc_write(tBTA_GATTC_CLCB* p_clcb, tBTA_GATTC_DATA* p_data) {
787  if (!bta_gattc_enqueue(p_clcb, p_data)) return;
788
789  tGATT_STATUS status = GATT_SUCCESS;
790  tGATT_VALUE attr;
791
792  attr.conn_id = p_clcb->bta_conn_id;
793  attr.handle = p_data->api_write.handle;
794  attr.offset = p_data->api_write.offset;
795  attr.len = p_data->api_write.len;
796  attr.auth_req = p_data->api_write.auth_req;
797
798  if (p_data->api_write.p_value)
799    memcpy(attr.value, p_data->api_write.p_value, p_data->api_write.len);
800
801  status =
802      GATTC_Write(p_clcb->bta_conn_id, p_data->api_write.write_type, &attr);
803
804  /* write fail */
805  if (status != GATT_SUCCESS) {
806    /* Dequeue the data, if it was enqueued */
807    if (p_clcb->p_q_cmd == p_data) p_clcb->p_q_cmd = NULL;
808
809    bta_gattc_cmpl_sendmsg(p_clcb->bta_conn_id, GATTC_OPTYPE_WRITE, status,
810                           NULL);
811  }
812}
813
814/** send execute write */
815void bta_gattc_execute(tBTA_GATTC_CLCB* p_clcb, tBTA_GATTC_DATA* p_data) {
816  if (!bta_gattc_enqueue(p_clcb, p_data)) return;
817
818  tGATT_STATUS status =
819      GATTC_ExecuteWrite(p_clcb->bta_conn_id, p_data->api_exec.is_execute);
820  if (status != GATT_SUCCESS) {
821    /* Dequeue the data, if it was enqueued */
822    if (p_clcb->p_q_cmd == p_data) p_clcb->p_q_cmd = NULL;
823
824    bta_gattc_cmpl_sendmsg(p_clcb->bta_conn_id, GATTC_OPTYPE_EXE_WRITE, status,
825                           NULL);
826  }
827}
828
829/** send handle value confirmation */
830void bta_gattc_confirm(tBTA_GATTC_CLCB* p_clcb, tBTA_GATTC_DATA* p_data) {
831  uint16_t handle = p_data->api_confirm.handle;
832
833  if (GATTC_SendHandleValueConfirm(p_data->api_confirm.hdr.layer_specific,
834                                   handle) != GATT_SUCCESS) {
835    LOG(ERROR) << __func__ << ": to handle=" << loghex(handle) << " failed";
836  } else {
837    /* if over BR_EDR, inform PM for mode change */
838    if (p_clcb->transport == BTA_TRANSPORT_BR_EDR) {
839      bta_sys_busy(BTA_ID_GATTC, BTA_ALL_APP_ID, p_clcb->bda);
840      bta_sys_idle(BTA_ID_GATTC, BTA_ALL_APP_ID, p_clcb->bda);
841    }
842  }
843}
844
845/** read complete */
846void bta_gattc_read_cmpl(tBTA_GATTC_CLCB* p_clcb, tBTA_GATTC_OP_CMPL* p_data) {
847  GATT_READ_OP_CB cb = p_clcb->p_q_cmd->api_read.read_cb;
848  void* my_cb_data = p_clcb->p_q_cmd->api_read.read_cb_data;
849
850  /* if it was read by handle, return the handle requested, if read by UUID, use
851   * handle returned from remote
852   */
853  uint16_t handle = p_clcb->p_q_cmd->api_read.handle;
854  if (handle == 0) handle = p_data->p_cmpl->att_value.handle;
855
856  osi_free_and_reset((void**)&p_clcb->p_q_cmd);
857
858  if (cb) {
859    cb(p_clcb->bta_conn_id, p_data->status, handle,
860       p_data->p_cmpl->att_value.len, p_data->p_cmpl->att_value.value,
861       my_cb_data);
862  }
863}
864
865/** write complete */
866void bta_gattc_write_cmpl(tBTA_GATTC_CLCB* p_clcb, tBTA_GATTC_OP_CMPL* p_data) {
867  GATT_WRITE_OP_CB cb = p_clcb->p_q_cmd->api_write.write_cb;
868  void* my_cb_data = p_clcb->p_q_cmd->api_write.write_cb_data;
869
870  osi_free_and_reset((void**)&p_clcb->p_q_cmd);
871
872  if (cb) {
873    cb(p_clcb->bta_conn_id, p_data->status, p_data->p_cmpl->att_value.handle,
874       my_cb_data);
875  }
876}
877
878/** execute write complete */
879void bta_gattc_exec_cmpl(tBTA_GATTC_CLCB* p_clcb, tBTA_GATTC_OP_CMPL* p_data) {
880  tBTA_GATTC cb_data;
881
882  osi_free_and_reset((void**)&p_clcb->p_q_cmd);
883  p_clcb->status = GATT_SUCCESS;
884
885  /* execute complete, callback */
886  cb_data.exec_cmpl.conn_id = p_clcb->bta_conn_id;
887  cb_data.exec_cmpl.status = p_data->status;
888
889  (*p_clcb->p_rcb->p_cback)(BTA_GATTC_EXEC_EVT, &cb_data);
890}
891
892/** configure MTU operation complete */
893void bta_gattc_cfg_mtu_cmpl(tBTA_GATTC_CLCB* p_clcb,
894                            tBTA_GATTC_OP_CMPL* p_data) {
895  tBTA_GATTC cb_data;
896
897  osi_free_and_reset((void**)&p_clcb->p_q_cmd);
898
899  if (p_data->p_cmpl && p_data->status == GATT_SUCCESS)
900    p_clcb->p_srcb->mtu = p_data->p_cmpl->mtu;
901
902  /* configure MTU complete, callback */
903  p_clcb->status = p_data->status;
904  cb_data.cfg_mtu.conn_id = p_clcb->bta_conn_id;
905  cb_data.cfg_mtu.status = p_data->status;
906  cb_data.cfg_mtu.mtu = p_clcb->p_srcb->mtu;
907
908  (*p_clcb->p_rcb->p_cback)(BTA_GATTC_CFG_MTU_EVT, &cb_data);
909}
910
911/** operation completed */
912void bta_gattc_op_cmpl(tBTA_GATTC_CLCB* p_clcb, tBTA_GATTC_DATA* p_data) {
913  uint8_t op = (uint8_t)p_data->op_cmpl.op_code;
914  uint8_t mapped_op = 0;
915
916  VLOG(1) << __func__ << ": op:" << +op;
917
918  if (op == GATTC_OPTYPE_INDICATION || op == GATTC_OPTYPE_NOTIFICATION) {
919    LOG(ERROR) << "unexpected operation, ignored";
920    return;
921  }
922
923  if (op < GATTC_OPTYPE_READ) return;
924
925  if (p_clcb->p_q_cmd == NULL) {
926    LOG(ERROR) << "No pending command";
927    return;
928  }
929
930  if (p_clcb->p_q_cmd->hdr.event !=
931      bta_gattc_opcode_to_int_evt[op - GATTC_OPTYPE_READ]) {
932    mapped_op =
933        p_clcb->p_q_cmd->hdr.event - BTA_GATTC_API_READ_EVT + GATTC_OPTYPE_READ;
934    if (mapped_op > GATTC_OPTYPE_INDICATION) mapped_op = 0;
935
936    LOG(ERROR) << StringPrintf(
937        "expect op:(%s :0x%04x), receive unexpected operation (%s).",
938        bta_gattc_op_code_name[mapped_op], p_clcb->p_q_cmd->hdr.event,
939        bta_gattc_op_code_name[op]);
940    return;
941  }
942
943  /* Except for MTU configuration, discard responses if service change
944   * indication is received before operation completed
945   */
946  if (p_clcb->auto_update == BTA_GATTC_DISC_WAITING &&
947      p_clcb->p_srcb->srvc_hdl_chg && op != GATTC_OPTYPE_CONFIG) {
948    VLOG(1) << "Discard all responses when service change indication is "
949               "received.";
950    p_data->op_cmpl.status = GATT_ERROR;
951  }
952
953  /* service handle change void the response, discard it */
954  if (op == GATTC_OPTYPE_READ)
955    bta_gattc_read_cmpl(p_clcb, &p_data->op_cmpl);
956
957  else if (op == GATTC_OPTYPE_WRITE)
958    bta_gattc_write_cmpl(p_clcb, &p_data->op_cmpl);
959
960  else if (op == GATTC_OPTYPE_EXE_WRITE)
961    bta_gattc_exec_cmpl(p_clcb, &p_data->op_cmpl);
962
963  else if (op == GATTC_OPTYPE_CONFIG)
964    bta_gattc_cfg_mtu_cmpl(p_clcb, &p_data->op_cmpl);
965
966  if (p_clcb->auto_update == BTA_GATTC_DISC_WAITING) {
967    p_clcb->auto_update = BTA_GATTC_REQ_WAITING;
968    bta_gattc_sm_execute(p_clcb, BTA_GATTC_INT_DISCOVER_EVT, NULL);
969  }
970}
971
972/** operation completed */
973void bta_gattc_ignore_op_cmpl(UNUSED_ATTR tBTA_GATTC_CLCB* p_clcb,
974                              tBTA_GATTC_DATA* p_data) {
975  /* receive op complete when discovery is started, ignore the response,
976      and wait for discovery finish and resent */
977  VLOG(1) << __func__ << ": op = " << +p_data->hdr.layer_specific;
978}
979
980/** start a search in the local server cache */
981void bta_gattc_search(tBTA_GATTC_CLCB* p_clcb, tBTA_GATTC_DATA* p_data) {
982  tGATT_STATUS status = GATT_INTERNAL_ERROR;
983  tBTA_GATTC cb_data;
984  VLOG(1) << __func__ << ": conn_id=" << +p_clcb->bta_conn_id;
985  if (p_clcb->p_srcb && !p_clcb->p_srcb->srvc_cache.empty()) {
986    status = GATT_SUCCESS;
987    /* search the local cache of a server device */
988    bta_gattc_search_service(p_clcb, p_data->api_search.p_srvc_uuid);
989  }
990  cb_data.search_cmpl.status = status;
991  cb_data.search_cmpl.conn_id = p_clcb->bta_conn_id;
992
993  /* end of search or no server cache available */
994  (*p_clcb->p_rcb->p_cback)(BTA_GATTC_SEARCH_CMPL_EVT, &cb_data);
995}
996
997/** enqueue a command into control block, usually because discovery operation is
998 * busy */
999void bta_gattc_q_cmd(tBTA_GATTC_CLCB* p_clcb, tBTA_GATTC_DATA* p_data) {
1000  bta_gattc_enqueue(p_clcb, p_data);
1001}
1002
1003/** report API call failure back to apps */
1004void bta_gattc_fail(tBTA_GATTC_CLCB* p_clcb,
1005                    UNUSED_ATTR tBTA_GATTC_DATA* p_data) {
1006  if (p_clcb->status == GATT_SUCCESS) {
1007    LOG(ERROR) << "operation not supported at current state " << +p_clcb->state;
1008  }
1009}
1010
1011/* De-Register a GATT client application with BTA completed */
1012static void bta_gattc_deregister_cmpl(tBTA_GATTC_RCB* p_clreg) {
1013  tGATT_IF client_if = p_clreg->client_if;
1014  tBTA_GATTC cb_data;
1015  tBTA_GATTC_CBACK* p_cback = p_clreg->p_cback;
1016
1017  memset(&cb_data, 0, sizeof(tBTA_GATTC));
1018
1019  GATT_Deregister(p_clreg->client_if);
1020  memset(p_clreg, 0, sizeof(tBTA_GATTC_RCB));
1021
1022  cb_data.reg_oper.client_if = client_if;
1023  cb_data.reg_oper.status = GATT_SUCCESS;
1024
1025  if (p_cback) /* callback with de-register event */
1026    (*p_cback)(BTA_GATTC_DEREG_EVT, &cb_data);
1027
1028  if (bta_gattc_num_reg_app() == 0 &&
1029      bta_gattc_cb.state == BTA_GATTC_STATE_DISABLING) {
1030    bta_gattc_cb.state = BTA_GATTC_STATE_DISABLED;
1031  }
1032}
1033
1034/** callback functions to GATT client stack */
1035static void bta_gattc_conn_cback(tGATT_IF gattc_if, const RawAddress& bdaddr,
1036                                 uint16_t conn_id, bool connected,
1037                                 tGATT_DISCONN_REASON reason,
1038                                 tBT_TRANSPORT transport) {
1039  if (reason != 0) {
1040    LOG(WARNING) << __func__ << ": cif=" << +gattc_if
1041                 << " connected=" << connected << " conn_id=" << loghex(conn_id)
1042                 << " reason=" << loghex(reason);
1043  }
1044
1045  if (connected)
1046    btif_debug_conn_state(bdaddr, BTIF_DEBUG_CONNECTED, GATT_CONN_UNKNOWN);
1047  else
1048    btif_debug_conn_state(bdaddr, BTIF_DEBUG_DISCONNECTED, reason);
1049
1050  tBTA_GATTC_DATA* p_buf =
1051      (tBTA_GATTC_DATA*)osi_calloc(sizeof(tBTA_GATTC_DATA));
1052  p_buf->int_conn.hdr.event =
1053      connected ? BTA_GATTC_INT_CONN_EVT : BTA_GATTC_INT_DISCONN_EVT;
1054  p_buf->int_conn.hdr.layer_specific = conn_id;
1055  p_buf->int_conn.client_if = gattc_if;
1056  p_buf->int_conn.role = L2CA_GetBleConnRole(bdaddr);
1057  p_buf->int_conn.reason = reason;
1058  p_buf->int_conn.transport = transport;
1059  p_buf->int_conn.remote_bda = bdaddr;
1060
1061  bta_sys_sendmsg(p_buf);
1062}
1063
1064/** encryption complete callback function to GATT client stack */
1065static void bta_gattc_enc_cmpl_cback(tGATT_IF gattc_if, const RawAddress& bda) {
1066  tBTA_GATTC_CLCB* p_clcb =
1067      bta_gattc_find_clcb_by_cif(gattc_if, bda, GATT_TRANSPORT_LE);
1068
1069  if (p_clcb == NULL) return;
1070
1071#if (BTA_HH_LE_INCLUDED == TRUE)
1072  /* filter this event just for BTA HH LE GATT client,
1073   * In the future, if we want to enable encryption complete event
1074   * for all GATT clients, we can remove this code
1075   */
1076  if (!bta_hh_le_is_hh_gatt_if(gattc_if)) {
1077    return;
1078  }
1079#endif
1080
1081  VLOG(1) << __func__ << ": cif:" << +gattc_if;
1082
1083  do_in_bta_thread(FROM_HERE,
1084                   base::Bind(&bta_gattc_process_enc_cmpl, gattc_if, bda));
1085}
1086
1087/** process refresh API to delete cache and start a new discovery if currently
1088 * connected */
1089void bta_gattc_process_api_refresh(const RawAddress& remote_bda) {
1090  tBTA_GATTC_SERV* p_srvc_cb = bta_gattc_find_srvr_cache(remote_bda);
1091  if (p_srvc_cb) {
1092    /* try to find a CLCB */
1093    if (p_srvc_cb->connected && p_srvc_cb->num_clcb != 0) {
1094      bool found = false;
1095      tBTA_GATTC_CLCB* p_clcb = &bta_gattc_cb.clcb[0];
1096      for (uint8_t i = 0; i < BTA_GATTC_CLCB_MAX; i++, p_clcb++) {
1097        if (p_clcb->in_use && p_clcb->p_srcb == p_srvc_cb) {
1098          found = true;
1099          break;
1100        }
1101      }
1102      if (found) {
1103        bta_gattc_sm_execute(p_clcb, BTA_GATTC_INT_DISCOVER_EVT, NULL);
1104        return;
1105      }
1106    }
1107    /* in all other cases, mark it and delete the cache */
1108
1109    // clear reallocating
1110    std::vector<tBTA_GATTC_SERVICE>().swap(p_srvc_cb->srvc_cache);
1111  }
1112
1113  /* used to reset cache in application */
1114  bta_gattc_cache_reset(remote_bda);
1115}
1116
1117/** process service change indication */
1118bool bta_gattc_process_srvc_chg_ind(uint16_t conn_id, tBTA_GATTC_RCB* p_clrcb,
1119                                    tBTA_GATTC_SERV* p_srcb,
1120                                    tBTA_GATTC_CLCB* p_clcb,
1121                                    tBTA_GATTC_NOTIFY* p_notify,
1122                                    tGATT_VALUE* att_value) {
1123
1124  Uuid gattp_uuid = Uuid::From16Bit(UUID_SERVCLASS_GATT_SERVER);
1125  Uuid srvc_chg_uuid = Uuid::From16Bit(GATT_UUID_GATT_SRV_CHGD);
1126
1127  const tBTA_GATTC_CHARACTERISTIC* p_char =
1128      bta_gattc_get_characteristic_srcb(p_srcb, p_notify->handle);
1129  if (!p_char) return false;
1130  const tBTA_GATTC_SERVICE* p_svc =
1131      bta_gattc_get_service_for_handle_srcb(p_srcb, p_char->value_handle);
1132  if (!p_svc || p_svc->uuid != gattp_uuid || p_char->uuid != srvc_chg_uuid) {
1133    return false;
1134  }
1135
1136  if (att_value->len != BTA_GATTC_SERVICE_CHANGED_LEN) {
1137    LOG(ERROR) << __func__
1138               << ": received malformed service changed indication, skipping";
1139    return false;
1140  }
1141
1142  uint8_t* p = att_value->value;
1143  uint16_t s_handle = ((uint16_t)(*(p)) + (((uint16_t)(*(p + 1))) << 8));
1144  uint16_t e_handle = ((uint16_t)(*(p + 2)) + (((uint16_t)(*(p + 3))) << 8));
1145
1146  LOG(ERROR) << __func__ << ": service changed s_handle=" << loghex(s_handle)
1147             << ", e_handle=" << loghex(e_handle);
1148
1149  /* mark service handle change pending */
1150  p_srcb->srvc_hdl_chg = true;
1151  /* clear up all notification/indication registration */
1152  bta_gattc_clear_notif_registration(p_srcb, conn_id, s_handle, e_handle);
1153  /* service change indication all received, do discovery update */
1154  if (++p_srcb->update_count == bta_gattc_num_reg_app()) {
1155    /* not an opened connection; or connection busy */
1156    /* search for first available clcb and start discovery */
1157    if (p_clcb == NULL || (p_clcb && p_clcb->p_q_cmd != NULL)) {
1158      for (size_t i = 0; i < BTA_GATTC_CLCB_MAX; i++) {
1159        if (bta_gattc_cb.clcb[i].in_use &&
1160            bta_gattc_cb.clcb[i].p_srcb == p_srcb &&
1161            bta_gattc_cb.clcb[i].p_q_cmd == NULL) {
1162          p_clcb = &bta_gattc_cb.clcb[i];
1163          break;
1164        }
1165      }
1166    }
1167    /* send confirmation here if this is an indication, it should always be */
1168    GATTC_SendHandleValueConfirm(conn_id, att_value->handle);
1169
1170    /* if connection available, refresh cache by doing discovery now */
1171    if (p_clcb) bta_gattc_sm_execute(p_clcb, BTA_GATTC_INT_DISCOVER_EVT, NULL);
1172  }
1173
1174  /* notify applicationf or service change */
1175  if (p_clrcb->p_cback) {
1176    tBTA_GATTC bta_gattc;
1177    bta_gattc.remote_bda = p_srcb->server_bda;
1178    (*p_clrcb->p_cback)(BTA_GATTC_SRVC_CHG_EVT, &bta_gattc);
1179  }
1180
1181  return true;
1182}
1183
1184/** process all non-service change indication/notification */
1185void bta_gattc_proc_other_indication(tBTA_GATTC_CLCB* p_clcb, uint8_t op,
1186                                     tGATT_CL_COMPLETE* p_data,
1187                                     tBTA_GATTC_NOTIFY* p_notify) {
1188  VLOG(1) << __func__
1189          << StringPrintf(
1190                 ": check p_data->att_value.handle=%d p_data->handle=%d",
1191                 p_data->att_value.handle, p_data->handle);
1192  VLOG(1) << "is_notify", p_notify->is_notify;
1193
1194  p_notify->is_notify = (op == GATTC_OPTYPE_INDICATION) ? false : true;
1195  p_notify->len = p_data->att_value.len;
1196  p_notify->bda = p_clcb->bda;
1197  memcpy(p_notify->value, p_data->att_value.value, p_data->att_value.len);
1198  p_notify->conn_id = p_clcb->bta_conn_id;
1199
1200  if (p_clcb->p_rcb->p_cback) {
1201    tBTA_GATTC bta_gattc;
1202    bta_gattc.notify = *p_notify;
1203    (*p_clcb->p_rcb->p_cback)(BTA_GATTC_NOTIF_EVT, &bta_gattc);
1204  }
1205}
1206
1207/** process indication/notification */
1208void bta_gattc_process_indicate(uint16_t conn_id, tGATTC_OPTYPE op,
1209                                tGATT_CL_COMPLETE* p_data) {
1210  uint16_t handle = p_data->att_value.handle;
1211  tBTA_GATTC_NOTIFY notify;
1212  RawAddress remote_bda;
1213  tGATT_IF gatt_if;
1214  tBTA_TRANSPORT transport;
1215
1216  if (!GATT_GetConnectionInfor(conn_id, &gatt_if, remote_bda, &transport)) {
1217    LOG(ERROR) << __func__ << ": indication/notif for unknown app";
1218    if (op == GATTC_OPTYPE_INDICATION)
1219      GATTC_SendHandleValueConfirm(conn_id, handle);
1220    return;
1221  }
1222
1223  tBTA_GATTC_RCB* p_clrcb = bta_gattc_cl_get_regcb(gatt_if);
1224  if (p_clrcb == NULL) {
1225    LOG(ERROR) << __func__ << ": indication/notif for unregistered app";
1226    if (op == GATTC_OPTYPE_INDICATION)
1227      GATTC_SendHandleValueConfirm(conn_id, handle);
1228    return;
1229  }
1230
1231  tBTA_GATTC_SERV* p_srcb = bta_gattc_find_srcb(remote_bda);
1232  if (p_srcb == NULL) {
1233    LOG(ERROR) << __func__ << ": indication/notif for unknown device, ignore";
1234    if (op == GATTC_OPTYPE_INDICATION)
1235      GATTC_SendHandleValueConfirm(conn_id, handle);
1236    return;
1237  }
1238
1239  tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
1240
1241  notify.handle = handle;
1242
1243  /* if service change indication/notification, don't forward to application */
1244  if (bta_gattc_process_srvc_chg_ind(conn_id, p_clrcb, p_srcb, p_clcb, &notify,
1245                                     &p_data->att_value))
1246    return;
1247
1248  /* if app registered for the notification */
1249  if (bta_gattc_check_notif_registry(p_clrcb, p_srcb, &notify)) {
1250    /* connection not open yet */
1251    if (p_clcb == NULL) {
1252      p_clcb = bta_gattc_clcb_alloc(gatt_if, remote_bda, transport);
1253
1254      if (p_clcb == NULL) {
1255        LOG(ERROR) << "No resources";
1256        return;
1257      }
1258
1259      p_clcb->bta_conn_id = conn_id;
1260      p_clcb->transport = transport;
1261
1262      bta_gattc_sm_execute(p_clcb, BTA_GATTC_INT_CONN_EVT, NULL);
1263    }
1264
1265    if (p_clcb != NULL)
1266      bta_gattc_proc_other_indication(p_clcb, op, p_data, &notify);
1267  }
1268  /* no one intersted and need ack? */
1269  else if (op == GATTC_OPTYPE_INDICATION) {
1270    VLOG(1) << __func__ << " no one interested, ack now";
1271    GATTC_SendHandleValueConfirm(conn_id, handle);
1272  }
1273}
1274
1275/** client operation complete callback register with BTE GATT */
1276static void bta_gattc_cmpl_cback(uint16_t conn_id, tGATTC_OPTYPE op,
1277                                 tGATT_STATUS status,
1278                                 tGATT_CL_COMPLETE* p_data) {
1279  VLOG(1) << __func__ << ": conn_id:" << +conn_id << " op:" << +op
1280          << " status:" << +status;
1281
1282  /* notification and indication processed right away */
1283  if (op == GATTC_OPTYPE_NOTIFICATION || op == GATTC_OPTYPE_INDICATION) {
1284    bta_gattc_process_indicate(conn_id, op, p_data);
1285    return;
1286  }
1287  /* for all other operation, not expected if w/o connection */
1288  tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
1289  if (!p_clcb) {
1290    LOG(ERROR) << __func__ << ": unknown conn_id=" << loghex(conn_id)
1291               << " ignore data";
1292    return;
1293  }
1294
1295  /* if over BR_EDR, inform PM for mode change */
1296  if (p_clcb->transport == BTA_TRANSPORT_BR_EDR) {
1297    bta_sys_busy(BTA_ID_GATTC, BTA_ALL_APP_ID, p_clcb->bda);
1298    bta_sys_idle(BTA_ID_GATTC, BTA_ALL_APP_ID, p_clcb->bda);
1299  }
1300
1301  bta_gattc_cmpl_sendmsg(conn_id, op, status, p_data);
1302}
1303
1304/** client operation complete send message */
1305static void bta_gattc_cmpl_sendmsg(uint16_t conn_id, tGATTC_OPTYPE op,
1306                                   tGATT_STATUS status,
1307                                   tGATT_CL_COMPLETE* p_data) {
1308  const size_t len = sizeof(tBTA_GATTC_OP_CMPL) + sizeof(tGATT_CL_COMPLETE);
1309  tBTA_GATTC_OP_CMPL* p_buf = (tBTA_GATTC_OP_CMPL*)osi_calloc(len);
1310
1311  p_buf->hdr.event = BTA_GATTC_OP_CMPL_EVT;
1312  p_buf->hdr.layer_specific = conn_id;
1313  p_buf->status = status;
1314  p_buf->op_code = op;
1315
1316  if (p_data) {
1317    p_buf->p_cmpl = (tGATT_CL_COMPLETE*)(p_buf + 1);
1318    memcpy(p_buf->p_cmpl, p_data, sizeof(tGATT_CL_COMPLETE));
1319  }
1320
1321  bta_sys_sendmsg(p_buf);
1322}
1323
1324/** congestion callback for BTA GATT client */
1325static void bta_gattc_cong_cback(uint16_t conn_id, bool congested) {
1326  tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id);
1327  if (!p_clcb || !p_clcb->p_rcb->p_cback) return;
1328
1329  tBTA_GATTC cb_data;
1330  cb_data.congest.conn_id = conn_id;
1331  cb_data.congest.congested = congested;
1332
1333  (*p_clcb->p_rcb->p_cback)(BTA_GATTC_CONGEST_EVT, &cb_data);
1334}
1335
1336static void bta_gattc_phy_update_cback(tGATT_IF gatt_if, uint16_t conn_id,
1337                                       uint8_t tx_phy, uint8_t rx_phy,
1338                                       uint8_t status) {
1339  tBTA_GATTC_RCB* p_clreg = bta_gattc_cl_get_regcb(gatt_if);
1340
1341  if (!p_clreg || !p_clreg->p_cback) {
1342    LOG(ERROR) << __func__ << ": client_if=" << +gatt_if << " not found";
1343    return;
1344  }
1345
1346  tBTA_GATTC cb_data;
1347  cb_data.phy_update.conn_id = conn_id;
1348  cb_data.phy_update.server_if = gatt_if;
1349  cb_data.phy_update.tx_phy = tx_phy;
1350  cb_data.phy_update.rx_phy = rx_phy;
1351  cb_data.phy_update.status = status;
1352  (*p_clreg->p_cback)(BTA_GATTC_PHY_UPDATE_EVT, &cb_data);
1353}
1354
1355static void bta_gattc_conn_update_cback(tGATT_IF gatt_if, uint16_t conn_id,
1356                                        uint16_t interval, uint16_t latency,
1357                                        uint16_t timeout, uint8_t status) {
1358  tBTA_GATTC_RCB* p_clreg = bta_gattc_cl_get_regcb(gatt_if);
1359
1360  if (!p_clreg || !p_clreg->p_cback) {
1361    LOG(ERROR) << __func__ << ": client_if=" << gatt_if << " not found";
1362    return;
1363  }
1364
1365  tBTA_GATTC cb_data;
1366  cb_data.conn_update.conn_id = conn_id;
1367  cb_data.conn_update.interval = interval;
1368  cb_data.conn_update.latency = latency;
1369  cb_data.conn_update.timeout = timeout;
1370  cb_data.conn_update.status = status;
1371  (*p_clreg->p_cback)(BTA_GATTC_CONN_UPDATE_EVT, &cb_data);
1372}
1373