l2c_fcr.cc revision 911d1ae03efec2d54c3b1b605589d790d1745488
1/******************************************************************************
2 *
3 *  Copyright (C) 2004-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 L2CAP 1.2 Flow Control and retransmissions
22 *  functions
23 *
24 ******************************************************************************/
25
26#include <assert.h>
27#include <stdio.h>
28#include <stdlib.h>
29#include <string.h>
30
31#include "bt_common.h"
32#include "bt_types.h"
33#include "btm_api.h"
34#include "btm_int.h"
35#include "btu.h"
36#include "hcimsgs.h"
37#include "l2c_api.h"
38#include "l2c_int.h"
39#include "l2cdefs.h"
40
41extern fixed_queue_t* btu_general_alarm_queue;
42
43/* Flag passed to retransmit_i_frames() when all packets should be retransmitted
44 */
45#define L2C_FCR_RETX_ALL_PKTS 0xFF
46
47/* this is the minimal offset required by OBX to process incoming packets */
48static const uint16_t OBX_BUF_MIN_OFFSET = 4;
49
50static const char* SAR_types[] = {"Unsegmented", "Start", "End",
51                                  "Continuation"};
52static const char* SUP_types[] = {"RR", "REJ", "RNR", "SREJ"};
53
54/* Look-up table for the CRC calculation */
55static const unsigned short crctab[256] = {
56    0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601,
57    0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440, 0xcc01, 0x0cc0,
58    0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81,
59    0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841, 0xd801, 0x18c0, 0x1980, 0xd941,
60    0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01,
61    0x1dc0, 0x1c80, 0xdc41, 0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0,
62    0x1680, 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081,
63    0x1040, 0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240,
64    0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441, 0x3c00,
65    0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, 0xfa01, 0x3ac0,
66    0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840, 0x2800, 0xe8c1, 0xe981,
67    0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41,
68    0x2d00, 0xedc1, 0xec81, 0x2c40, 0xe401, 0x24c0, 0x2580, 0xe541, 0x2700,
69    0xe7c1, 0xe681, 0x2640, 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0,
70    0x2080, 0xe041, 0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281,
71    0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441,
72    0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01,
73    0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840, 0x7800, 0xb8c1,
74    0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80,
75    0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40, 0xb401, 0x74c0, 0x7580, 0xb541,
76    0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101,
77    0x71c0, 0x7080, 0xb041, 0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0,
78    0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481,
79    0x5440, 0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40,
80    0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841, 0x8801,
81    0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40, 0x4e00, 0x8ec1,
82    0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41, 0x4400, 0x84c1, 0x8581,
83    0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341,
84    0x4100, 0x81c1, 0x8081, 0x4040,
85};
86
87/*******************************************************************************
88 *  Static local functions
89*/
90static bool process_reqseq(tL2C_CCB* p_ccb, uint16_t ctrl_word);
91static void process_s_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, uint16_t ctrl_word);
92static void process_i_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, uint16_t ctrl_word,
93                            bool delay_ack);
94static bool retransmit_i_frames(tL2C_CCB* p_ccb, uint8_t tx_seq);
95static void prepare_I_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf,
96                            bool is_retransmission);
97static void process_stream_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf);
98static bool do_sar_reassembly(tL2C_CCB* p_ccb, BT_HDR* p_buf,
99                              uint16_t ctrl_word);
100
101#if (L2CAP_ERTM_STATS == TRUE)
102static void l2c_fcr_collect_ack_delay(tL2C_CCB* p_ccb, uint8_t num_bufs_acked);
103#endif
104
105/*******************************************************************************
106 *
107 * Function         l2c_fcr_updcrc
108 *
109 * Description      This function computes the CRC using the look-up table.
110 *
111 * Returns          CRC
112 *
113 ******************************************************************************/
114static unsigned short l2c_fcr_updcrc(unsigned short icrc, unsigned char* icp,
115                                     int icnt) {
116  unsigned short crc = icrc;
117  unsigned char* cp = icp;
118  int cnt = icnt;
119
120  while (cnt--) {
121    crc = ((crc >> 8) & 0xff) ^ crctab[(crc & 0xff) ^ *cp++];
122  }
123
124  return (crc);
125}
126
127/*******************************************************************************
128 *
129 * Function         l2c_fcr_tx_get_fcs
130 *
131 * Description      This function computes the CRC for a frame to be TXed.
132 *
133 * Returns          CRC
134 *
135 ******************************************************************************/
136static uint16_t l2c_fcr_tx_get_fcs(BT_HDR* p_buf) {
137  uint8_t* p = ((uint8_t*)(p_buf + 1)) + p_buf->offset;
138
139  return (l2c_fcr_updcrc(L2CAP_FCR_INIT_CRC, p, p_buf->len));
140}
141
142/*******************************************************************************
143 *
144 * Function         l2c_fcr_rx_get_fcs
145 *
146 * Description      This function computes the CRC for a received frame.
147 *
148 * Returns          CRC
149 *
150 ******************************************************************************/
151static uint16_t l2c_fcr_rx_get_fcs(BT_HDR* p_buf) {
152  uint8_t* p = ((uint8_t*)(p_buf + 1)) + p_buf->offset;
153
154  /* offset points past the L2CAP header, but the CRC check includes it */
155  p -= L2CAP_PKT_OVERHEAD;
156
157  return (
158      l2c_fcr_updcrc(L2CAP_FCR_INIT_CRC, p, p_buf->len + L2CAP_PKT_OVERHEAD));
159}
160
161/*******************************************************************************
162 *
163 * Function         l2c_fcr_start_timer
164 *
165 * Description      This function starts the (monitor or retransmission) timer.
166 *
167 * Returns          -
168 *
169 ******************************************************************************/
170void l2c_fcr_start_timer(tL2C_CCB* p_ccb) {
171  assert(p_ccb != NULL);
172  uint32_t tout;
173
174  /* The timers which are in milliseconds */
175  if (p_ccb->fcrb.wait_ack) {
176    tout = (uint32_t)p_ccb->our_cfg.fcr.mon_tout;
177  } else {
178    tout = (uint32_t)p_ccb->our_cfg.fcr.rtrans_tout;
179  }
180
181  /* Only start a timer that was not started */
182  if (!alarm_is_scheduled(p_ccb->fcrb.mon_retrans_timer)) {
183    alarm_set_on_queue(p_ccb->fcrb.mon_retrans_timer, tout,
184                       l2c_ccb_timer_timeout, p_ccb, btu_general_alarm_queue);
185  }
186}
187
188/*******************************************************************************
189 *
190 * Function         l2c_fcr_stop_timer
191 *
192 * Description      This function stops the (monitor or transmission) timer.
193 *
194 * Returns          -
195 *
196 ******************************************************************************/
197void l2c_fcr_stop_timer(tL2C_CCB* p_ccb) {
198  assert(p_ccb != NULL);
199  alarm_cancel(p_ccb->fcrb.mon_retrans_timer);
200}
201
202/*******************************************************************************
203 *
204 * Function         l2c_fcr_cleanup
205 *
206 * Description      This function cleans up the variable used for
207 *                  flow-control/retrans.
208 *
209 * Returns          -
210 *
211 ******************************************************************************/
212void l2c_fcr_cleanup(tL2C_CCB* p_ccb) {
213  assert(p_ccb != NULL);
214  tL2C_FCRB* p_fcrb = &p_ccb->fcrb;
215
216  alarm_free(p_fcrb->mon_retrans_timer);
217  p_fcrb->mon_retrans_timer = NULL;
218  alarm_free(p_fcrb->ack_timer);
219  p_fcrb->ack_timer = NULL;
220
221  osi_free_and_reset((void**)&p_fcrb->p_rx_sdu);
222
223  fixed_queue_free(p_fcrb->waiting_for_ack_q, osi_free);
224  p_fcrb->waiting_for_ack_q = NULL;
225
226  fixed_queue_free(p_fcrb->srej_rcv_hold_q, osi_free);
227  p_fcrb->srej_rcv_hold_q = NULL;
228
229  fixed_queue_free(p_fcrb->retrans_q, osi_free);
230  p_fcrb->retrans_q = NULL;
231
232#if (L2CAP_ERTM_STATS == TRUE)
233  if ((p_ccb->local_cid >= L2CAP_BASE_APPL_CID) &&
234      (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE)) {
235    uint32_t dur = time_get_os_boottime_ms() - p_ccb->fcrb.connect_tick_count;
236    size_t p_str_size = 120;
237    char* p_str = (char*)osi_malloc(p_str_size);
238    uint16_t i;
239    uint32_t throughput_avg, ack_delay_avg, ack_q_count_avg;
240
241    BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI,
242             TRACE_TYPE_GENERIC,
243             "---  L2CAP ERTM  Stats for CID: 0x%04x   Duration: %08ums",
244             p_ccb->local_cid, dur);
245    BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI,
246             TRACE_TYPE_GENERIC,
247             "Retransmissions:%08u Times Flow Controlled:%08u Retrans "
248             "Touts:%08u Ack Touts:%08u",
249             p_ccb->fcrb.pkts_retransmitted, p_ccb->fcrb.xmit_window_closed,
250             p_ccb->fcrb.retrans_touts, p_ccb->fcrb.xmit_ack_touts);
251    BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI,
252             TRACE_TYPE_GENERIC,
253             "Times there is less than 2 packets in controller when flow "
254             "controlled:%08u",
255             p_ccb->fcrb.controller_idle);
256    BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI,
257             TRACE_TYPE_GENERIC,
258             "max_held_acks:%08u, in_cfg.fcr.tx_win_sz:%08u",
259             p_ccb->fcrb.max_held_acks, p_ccb->peer_cfg.fcr.tx_win_sz);
260
261    snprintf(
262        p_str, p_str_size,
263        "Sent Pkts:%08u Bytes:%10u(%06u/sec) RR:%08u REJ:%08u RNR:%08u "
264        "SREJ:%08u",
265        p_ccb->fcrb.ertm_pkt_counts[0], p_ccb->fcrb.ertm_byte_counts[0],
266        (dur >= 10 ? (p_ccb->fcrb.ertm_byte_counts[0] * 100) / (dur / 10) : 0),
267        p_ccb->fcrb.s_frames_sent[0], p_ccb->fcrb.s_frames_sent[1],
268        p_ccb->fcrb.s_frames_sent[2], p_ccb->fcrb.s_frames_sent[3]);
269
270    BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI,
271             TRACE_TYPE_GENERIC, "%s", p_str);
272
273    snprintf(
274        p_str, p_str_size,
275        "Rcvd Pkts:%08u Bytes:%10u(%06u/sec) RR:%08u REJ:%08u RNR:%08u "
276        "SREJ:%08u",
277        p_ccb->fcrb.ertm_pkt_counts[1], p_ccb->fcrb.ertm_byte_counts[1],
278        (dur >= 10 ? (p_ccb->fcrb.ertm_byte_counts[1] * 100) / (dur / 10) : 0),
279        p_ccb->fcrb.s_frames_rcvd[0], p_ccb->fcrb.s_frames_rcvd[1],
280        p_ccb->fcrb.s_frames_rcvd[2], p_ccb->fcrb.s_frames_rcvd[3]);
281
282    BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI,
283             TRACE_TYPE_GENERIC, "%s", p_str);
284
285    throughput_avg = 0;
286    ack_delay_avg = 0;
287    ack_q_count_avg = 0;
288
289    for (i = 0; i < L2CAP_ERTM_STATS_NUM_AVG; i++) {
290      if (i == p_ccb->fcrb.ack_delay_avg_index) {
291        BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI,
292                 TRACE_TYPE_GENERIC, "[%02u] collecting data ...", i);
293        continue;
294      }
295
296      snprintf(p_str, p_str_size,
297               "[%02u] throughput: %5u, ack_delay avg:%3u, min:%3u, max:%3u, "
298               "ack_q_count avg:%3u, min:%3u, max:%3u",
299               i, p_ccb->fcrb.throughput[i], p_ccb->fcrb.ack_delay_avg[i],
300               p_ccb->fcrb.ack_delay_min[i], p_ccb->fcrb.ack_delay_max[i],
301               p_ccb->fcrb.ack_q_count_avg[i], p_ccb->fcrb.ack_q_count_min[i],
302               p_ccb->fcrb.ack_q_count_max[i]);
303
304      BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI,
305               TRACE_TYPE_GENERIC, "%s", p_str);
306
307      throughput_avg += p_ccb->fcrb.throughput[i];
308      ack_delay_avg += p_ccb->fcrb.ack_delay_avg[i];
309      ack_q_count_avg += p_ccb->fcrb.ack_q_count_avg[i];
310    }
311
312    throughput_avg /= (L2CAP_ERTM_STATS_NUM_AVG - 1);
313    ack_delay_avg /= (L2CAP_ERTM_STATS_NUM_AVG - 1);
314    ack_q_count_avg /= (L2CAP_ERTM_STATS_NUM_AVG - 1);
315
316    BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI,
317             TRACE_TYPE_GENERIC,
318             "throughput_avg: %8u (kbytes/sec), ack_delay_avg: %8u ms, "
319             "ack_q_count_avg: %8u",
320             throughput_avg, ack_delay_avg, ack_q_count_avg);
321
322    osi_free(p_str);
323
324    BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI,
325             TRACE_TYPE_GENERIC, "---");
326  }
327#endif
328
329  memset(p_fcrb, 0, sizeof(tL2C_FCRB));
330}
331
332/*******************************************************************************
333 *
334 * Function         l2c_fcr_clone_buf
335 *
336 * Description      This function allocates and copies requested part of a
337 *                  buffer at a new-offset.
338 *
339 * Returns          pointer to new buffer
340 *
341 ******************************************************************************/
342BT_HDR* l2c_fcr_clone_buf(BT_HDR* p_buf, uint16_t new_offset,
343                          uint16_t no_of_bytes) {
344  assert(p_buf != NULL);
345  /*
346   * NOTE: We allocate extra L2CAP_FCS_LEN octets, in case we need to put
347   * the FCS (Frame Check Sequence) at the end of the buffer.
348   */
349  uint16_t buf_size = no_of_bytes + sizeof(BT_HDR) + new_offset + L2CAP_FCS_LEN;
350#if (L2CAP_ERTM_STATS == TRUE)
351  /*
352   * NOTE: If L2CAP_ERTM_STATS is enabled, we need 4 extra octets at the
353   * end for a timestamp at the end of an I-frame.
354   */
355  buf_size += sizeof(uint32_t);
356#endif
357  BT_HDR* p_buf2 = (BT_HDR*)osi_malloc(buf_size);
358
359  p_buf2->offset = new_offset;
360  p_buf2->len = no_of_bytes;
361  memcpy(((uint8_t*)(p_buf2 + 1)) + p_buf2->offset,
362         ((uint8_t*)(p_buf + 1)) + p_buf->offset, no_of_bytes);
363
364  return (p_buf2);
365}
366
367/*******************************************************************************
368 *
369 * Function         l2c_fcr_is_flow_controlled
370 *
371 * Description      This function checks if the CCB is flow controlled by peer.
372 *
373 * Returns          The control word
374 *
375 ******************************************************************************/
376bool l2c_fcr_is_flow_controlled(tL2C_CCB* p_ccb) {
377  assert(p_ccb != NULL);
378  if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) {
379    /* Check if remote side flowed us off or the transmit window is full */
380    if ((p_ccb->fcrb.remote_busy == true) ||
381        (fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q) >=
382         p_ccb->peer_cfg.fcr.tx_win_sz)) {
383#if (L2CAP_ERTM_STATS == TRUE)
384      if (!fixed_queue_is_empty(p_ccb->xmit_hold_q)) {
385        p_ccb->fcrb.xmit_window_closed++;
386
387        if ((p_ccb->p_lcb->sent_not_acked < 2) &&
388            (l2cb.controller_xmit_window > 0))
389          p_ccb->fcrb.controller_idle++;
390      }
391#endif
392      return (true);
393    }
394  }
395  return (false);
396}
397
398/*******************************************************************************
399 *
400 * Function         prepare_I_frame
401 *
402 * Description      This function sets the FCR variables in an I-frame that is
403 *                  about to be sent to HCI for transmission. This may be the
404 *                  first time the I-frame is sent, or a retransmission
405 *
406 * Returns          -
407 *
408 ******************************************************************************/
409static void prepare_I_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf,
410                            bool is_retransmission) {
411  assert(p_ccb != NULL);
412  assert(p_buf != NULL);
413  tL2C_FCRB* p_fcrb = &p_ccb->fcrb;
414  uint8_t* p;
415  uint16_t fcs;
416  uint16_t ctrl_word;
417  bool set_f_bit = p_fcrb->send_f_rsp;
418
419  p_fcrb->send_f_rsp = false;
420
421  if (is_retransmission) {
422    /* Get the old control word and clear out the old req_seq and F bits */
423    p = ((uint8_t*)(p_buf + 1)) + p_buf->offset + L2CAP_PKT_OVERHEAD;
424
425    STREAM_TO_UINT16(ctrl_word, p);
426
427    ctrl_word &= ~(L2CAP_FCR_REQ_SEQ_BITS + L2CAP_FCR_F_BIT);
428  } else {
429    ctrl_word = p_buf->layer_specific & L2CAP_FCR_SEG_BITS; /* SAR bits */
430    ctrl_word |=
431        (p_fcrb->next_tx_seq << L2CAP_FCR_TX_SEQ_BITS_SHIFT); /* Tx Seq */
432
433    p_fcrb->next_tx_seq = (p_fcrb->next_tx_seq + 1) & L2CAP_FCR_SEQ_MODULO;
434  }
435
436  /* Set the F-bit and reqseq only if using re-transmission mode */
437  if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) {
438    if (set_f_bit) ctrl_word |= L2CAP_FCR_F_BIT;
439
440    ctrl_word |= (p_fcrb->next_seq_expected) << L2CAP_FCR_REQ_SEQ_BITS_SHIFT;
441
442    p_fcrb->last_ack_sent = p_ccb->fcrb.next_seq_expected;
443
444    alarm_cancel(p_ccb->fcrb.ack_timer);
445  }
446
447  /* Set the control word */
448  p = ((uint8_t*)(p_buf + 1)) + p_buf->offset + L2CAP_PKT_OVERHEAD;
449
450  UINT16_TO_STREAM(p, ctrl_word);
451
452  /* Compute the FCS and add to the end of the buffer if not bypassed */
453  if (p_ccb->bypass_fcs != L2CAP_BYPASS_FCS) {
454    /* length field in l2cap header has to include FCS length */
455    p = ((uint8_t*)(p_buf + 1)) + p_buf->offset;
456    UINT16_TO_STREAM(p, p_buf->len + L2CAP_FCS_LEN - L2CAP_PKT_OVERHEAD);
457
458    /* Calculate the FCS */
459    fcs = l2c_fcr_tx_get_fcs(p_buf);
460
461    /* Point to the end of the buffer and put the FCS there */
462    /*
463     * NOTE: Here we assume the allocated buffer is large enough
464     * to include extra L2CAP_FCS_LEN octets at the end.
465     */
466    p = ((uint8_t*)(p_buf + 1)) + p_buf->offset + p_buf->len;
467
468    UINT16_TO_STREAM(p, fcs);
469
470    p_buf->len += L2CAP_FCS_LEN;
471  }
472
473  if (is_retransmission) {
474    L2CAP_TRACE_EVENT(
475        "L2CAP eRTM ReTx I-frame  CID: 0x%04x  Len: %u  SAR: %s  TxSeq: %u  "
476        "ReqSeq: %u  F: %u",
477        p_ccb->local_cid, p_buf->len,
478        SAR_types[(ctrl_word & L2CAP_FCR_SAR_BITS) >> L2CAP_FCR_SAR_BITS_SHIFT],
479        (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT,
480        (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
481        (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
482  } else {
483    L2CAP_TRACE_EVENT(
484        "L2CAP eRTM Tx I-frame CID: 0x%04x  Len: %u  SAR: %-12s  TxSeq: %u  "
485        "ReqSeq: %u  F: %u",
486        p_ccb->local_cid, p_buf->len,
487        SAR_types[(ctrl_word & L2CAP_FCR_SAR_BITS) >> L2CAP_FCR_SAR_BITS_SHIFT],
488        (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT,
489        (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
490        (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
491  }
492
493  /* Start the retransmission timer if not already running */
494  if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE)
495    l2c_fcr_start_timer(p_ccb);
496}
497
498/*******************************************************************************
499 *
500 * Function         l2c_fcr_send_S_frame
501 *
502 * Description      This function formats and sends an S-frame for transmission.
503 *
504 * Returns          -
505 *
506 ******************************************************************************/
507void l2c_fcr_send_S_frame(tL2C_CCB* p_ccb, uint16_t function_code,
508                          uint16_t pf_bit) {
509  assert(p_ccb != NULL);
510  uint8_t* p;
511  uint16_t ctrl_word;
512  uint16_t fcs;
513
514  if ((!p_ccb->in_use) || (p_ccb->chnl_state != CST_OPEN)) return;
515
516#if (L2CAP_ERTM_STATS == TRUE)
517  p_ccb->fcrb.s_frames_sent[function_code]++;
518#endif
519
520  if (pf_bit == L2CAP_FCR_P_BIT) {
521    p_ccb->fcrb.wait_ack = true;
522
523    l2c_fcr_stop_timer(p_ccb); /* Restart the monitor timer */
524    l2c_fcr_start_timer(p_ccb);
525  }
526
527  /* Create the control word to use */
528  ctrl_word = (function_code << L2CAP_FCR_SUP_SHIFT) | L2CAP_FCR_S_FRAME_BIT;
529  ctrl_word |= (p_ccb->fcrb.next_seq_expected << L2CAP_FCR_REQ_SEQ_BITS_SHIFT);
530  ctrl_word |= pf_bit;
531
532  BT_HDR* p_buf = (BT_HDR*)osi_malloc(L2CAP_CMD_BUF_SIZE);
533  p_buf->offset = HCI_DATA_PREAMBLE_SIZE;
534  p_buf->len = L2CAP_PKT_OVERHEAD + L2CAP_FCR_OVERHEAD;
535
536  /* Set the pointer to the beginning of the data */
537  p = (uint8_t*)(p_buf + 1) + p_buf->offset;
538
539  /* Put in the L2CAP header */
540  UINT16_TO_STREAM(p, L2CAP_FCR_OVERHEAD + L2CAP_FCS_LEN);
541  UINT16_TO_STREAM(p, p_ccb->remote_cid);
542  UINT16_TO_STREAM(p, ctrl_word);
543
544  /* Compute the FCS and add to the end of the buffer if not bypassed */
545  if (p_ccb->bypass_fcs != L2CAP_BYPASS_FCS) {
546    fcs = l2c_fcr_tx_get_fcs(p_buf);
547
548    UINT16_TO_STREAM(p, fcs);
549    p_buf->len += L2CAP_FCS_LEN;
550  } else {
551    /* rewrite the length without FCS length */
552    p -= 6;
553    UINT16_TO_STREAM(p, L2CAP_FCR_OVERHEAD);
554  }
555
556  /* Now, the HCI transport header */
557  p_buf->layer_specific = L2CAP_NON_FLUSHABLE_PKT;
558  l2cu_set_acl_hci_header(p_buf, p_ccb);
559
560  if ((((ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT) == 1) ||
561      (((ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT) == 3)) {
562    L2CAP_TRACE_WARNING(
563        "L2CAP eRTM Tx S-frame  CID: 0x%04x  ctrlword: 0x%04x  Type: %s  "
564        "ReqSeq: %u  P: %u  F: %u",
565        p_ccb->local_cid, ctrl_word,
566        SUP_types[(ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT],
567        (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
568        (ctrl_word & L2CAP_FCR_P_BIT) >> L2CAP_FCR_P_BIT_SHIFT,
569        (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
570    L2CAP_TRACE_WARNING("                  Buf Len: %u", p_buf->len);
571  } else {
572    L2CAP_TRACE_EVENT(
573        "L2CAP eRTM Tx S-frame  CID: 0x%04x  ctrlword: 0x%04x  Type: %s  "
574        "ReqSeq: %u  P: %u  F: %u",
575        p_ccb->local_cid, ctrl_word,
576        SUP_types[(ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT],
577        (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
578        (ctrl_word & L2CAP_FCR_P_BIT) >> L2CAP_FCR_P_BIT_SHIFT,
579        (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
580    L2CAP_TRACE_EVENT("                  Buf Len: %u", p_buf->len);
581  }
582
583  l2c_link_check_send_pkts(p_ccb->p_lcb, NULL, p_buf);
584
585  p_ccb->fcrb.last_ack_sent = p_ccb->fcrb.next_seq_expected;
586
587  alarm_cancel(p_ccb->fcrb.ack_timer);
588}
589
590/*******************************************************************************
591 *
592 * Function         l2c_fcr_proc_pdu
593 *
594 * Description      This function is the entry point for processing of a
595 *                  received PDU when in flow control and/or retransmission
596 *                  modes.
597 *
598 * Returns          -
599 *
600 ******************************************************************************/
601void l2c_fcr_proc_pdu(tL2C_CCB* p_ccb, BT_HDR* p_buf) {
602  assert(p_ccb != NULL);
603  assert(p_buf != NULL);
604  uint8_t* p;
605  uint16_t fcs;
606  uint16_t min_pdu_len;
607  uint16_t ctrl_word;
608
609  /* Check the length */
610  min_pdu_len = (p_ccb->bypass_fcs == L2CAP_BYPASS_FCS)
611                    ? (uint16_t)L2CAP_FCR_OVERHEAD
612                    : (uint16_t)(L2CAP_FCS_LEN + L2CAP_FCR_OVERHEAD);
613
614  if (p_buf->len < min_pdu_len) {
615    L2CAP_TRACE_WARNING("Rx L2CAP PDU: CID: 0x%04x  Len too short: %u",
616                        p_ccb->local_cid, p_buf->len);
617    osi_free(p_buf);
618    return;
619  }
620
621  if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_STREAM_MODE) {
622    process_stream_frame(p_ccb, p_buf);
623    return;
624  }
625
626  /* Get the control word */
627  p = ((uint8_t*)(p_buf + 1)) + p_buf->offset;
628  STREAM_TO_UINT16(ctrl_word, p);
629
630  if (ctrl_word & L2CAP_FCR_S_FRAME_BIT) {
631    if ((((ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT) == 1) ||
632        (((ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT) == 3)) {
633      /* REJ or SREJ */
634      L2CAP_TRACE_WARNING(
635          "L2CAP eRTM Rx S-frame: cid: 0x%04x  Len: %u  Type: %s  ReqSeq: %u  "
636          "P: %u  F: %u",
637          p_ccb->local_cid, p_buf->len,
638          SUP_types[(ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT],
639          (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
640          (ctrl_word & L2CAP_FCR_P_BIT) >> L2CAP_FCR_P_BIT_SHIFT,
641          (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
642    } else {
643      L2CAP_TRACE_EVENT(
644          "L2CAP eRTM Rx S-frame: cid: 0x%04x  Len: %u  Type: %s  ReqSeq: %u  "
645          "P: %u  F: %u",
646          p_ccb->local_cid, p_buf->len,
647          SUP_types[(ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT],
648          (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
649          (ctrl_word & L2CAP_FCR_P_BIT) >> L2CAP_FCR_P_BIT_SHIFT,
650          (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
651    }
652  } else {
653    L2CAP_TRACE_EVENT(
654        "L2CAP eRTM Rx I-frame: cid: 0x%04x  Len: %u  SAR: %-12s  TxSeq: %u  "
655        "ReqSeq: %u  F: %u",
656        p_ccb->local_cid, p_buf->len,
657        SAR_types[(ctrl_word & L2CAP_FCR_SAR_BITS) >> L2CAP_FCR_SAR_BITS_SHIFT],
658        (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT,
659        (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
660        (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
661  }
662
663  L2CAP_TRACE_EVENT(
664      "      eRTM Rx Nxt_tx_seq %u, Lst_rx_ack %u, Nxt_seq_exp %u, Lst_ack_snt "
665      "%u, wt_q.cnt %u, tries %u",
666      p_ccb->fcrb.next_tx_seq, p_ccb->fcrb.last_rx_ack,
667      p_ccb->fcrb.next_seq_expected, p_ccb->fcrb.last_ack_sent,
668      fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q), p_ccb->fcrb.num_tries);
669
670  /* Verify FCS if using */
671  if (p_ccb->bypass_fcs != L2CAP_BYPASS_FCS) {
672    p = ((uint8_t*)(p_buf + 1)) + p_buf->offset + p_buf->len - L2CAP_FCS_LEN;
673
674    /* Extract and drop the FCS from the packet */
675    STREAM_TO_UINT16(fcs, p);
676    p_buf->len -= L2CAP_FCS_LEN;
677
678    if (l2c_fcr_rx_get_fcs(p_buf) != fcs) {
679      L2CAP_TRACE_WARNING("Rx L2CAP PDU: CID: 0x%04x  BAD FCS",
680                          p_ccb->local_cid);
681      osi_free(p_buf);
682      return;
683    }
684  }
685
686  /* Get the control word */
687  p = ((uint8_t*)(p_buf + 1)) + p_buf->offset;
688
689  STREAM_TO_UINT16(ctrl_word, p);
690
691  p_buf->len -= L2CAP_FCR_OVERHEAD;
692  p_buf->offset += L2CAP_FCR_OVERHEAD;
693
694  /* If we had a poll bit outstanding, check if we got a final response */
695  if (p_ccb->fcrb.wait_ack) {
696    /* If final bit not set, ignore the frame unless it is a polled S-frame */
697    if (!(ctrl_word & L2CAP_FCR_F_BIT)) {
698      if ((ctrl_word & L2CAP_FCR_P_BIT) &&
699          (ctrl_word & L2CAP_FCR_S_FRAME_BIT)) {
700        if (p_ccb->fcrb.srej_sent)
701          l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_SREJ, L2CAP_FCR_F_BIT);
702        else if (p_ccb->fcrb.local_busy)
703          l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RNR, L2CAP_FCR_F_BIT);
704        else
705          l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RR, L2CAP_FCR_F_BIT);
706
707        /* Got a poll while in wait_ack state, so re-start our timer with
708         * 1-second */
709        /* This is a small optimization... the monitor timer is 12 secs, but we
710         * saw */
711        /* that if the other side sends us a poll when we are waiting for a
712         * final,  */
713        /* then it speeds up recovery significantly if we poll him back soon
714         * after his poll. */
715        alarm_set_on_queue(p_ccb->fcrb.mon_retrans_timer, BT_1SEC_TIMEOUT_MS,
716                           l2c_ccb_timer_timeout, p_ccb,
717                           btu_general_alarm_queue);
718      }
719      osi_free(p_buf);
720      return;
721    }
722
723    p_ccb->fcrb.wait_ack = false;
724
725    /* P and F are mutually exclusive */
726    if (ctrl_word & L2CAP_FCR_S_FRAME_BIT) ctrl_word &= ~L2CAP_FCR_P_BIT;
727
728    if (fixed_queue_is_empty(p_ccb->fcrb.waiting_for_ack_q))
729      p_ccb->fcrb.num_tries = 0;
730
731    l2c_fcr_stop_timer(p_ccb);
732  } else {
733    /* Otherwise, ensure the final bit is ignored */
734    ctrl_word &= ~L2CAP_FCR_F_BIT;
735  }
736
737  /* Process receive sequence number */
738  if (!process_reqseq(p_ccb, ctrl_word)) {
739    osi_free(p_buf);
740    return;
741  }
742
743  /* Process based on whether it is an S-frame or an I-frame */
744  if (ctrl_word & L2CAP_FCR_S_FRAME_BIT)
745    process_s_frame(p_ccb, p_buf, ctrl_word);
746  else
747    process_i_frame(p_ccb, p_buf, ctrl_word, false);
748
749  /* Return if the channel got disconnected by a bad packet or max
750   * retransmissions */
751  if ((!p_ccb->in_use) || (p_ccb->chnl_state != CST_OPEN)) return;
752
753  /* If we have some buffers held while doing SREJ, and SREJ has cleared,
754   * process them now */
755  if ((!p_ccb->fcrb.local_busy) && (!p_ccb->fcrb.srej_sent) &&
756      (!fixed_queue_is_empty(p_ccb->fcrb.srej_rcv_hold_q))) {
757    fixed_queue_t* temp_q = p_ccb->fcrb.srej_rcv_hold_q;
758    p_ccb->fcrb.srej_rcv_hold_q = fixed_queue_new(SIZE_MAX);
759
760    while ((p_buf = (BT_HDR*)fixed_queue_try_dequeue(temp_q)) != NULL) {
761      if (p_ccb->in_use && (p_ccb->chnl_state == CST_OPEN)) {
762        /* Get the control word */
763        p = ((uint8_t*)(p_buf + 1)) + p_buf->offset - L2CAP_FCR_OVERHEAD;
764
765        STREAM_TO_UINT16(ctrl_word, p);
766
767        L2CAP_TRACE_DEBUG(
768            "l2c_fcr_proc_pdu() CID: 0x%04x  Process Buffer from SREJ_Hold_Q   "
769            "TxSeq: %u  Expected_Seq: %u",
770            p_ccb->local_cid,
771            (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT,
772            p_ccb->fcrb.next_seq_expected);
773
774        /* Process the SREJ held I-frame, but do not send an RR for each
775         * individual frame */
776        process_i_frame(p_ccb, p_buf, ctrl_word, true);
777      } else
778        osi_free(p_buf);
779
780      /* If more frames were lost during SREJ, send a REJ */
781      if (p_ccb->fcrb.rej_after_srej) {
782        p_ccb->fcrb.rej_after_srej = false;
783        p_ccb->fcrb.rej_sent = true;
784
785        l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_REJ, 0);
786      }
787    }
788    fixed_queue_free(temp_q, NULL);
789
790    /* Now, if needed, send one RR for the whole held queue */
791    if ((!p_ccb->fcrb.local_busy) && (!p_ccb->fcrb.rej_sent) &&
792        (!p_ccb->fcrb.srej_sent) &&
793        (p_ccb->fcrb.next_seq_expected != p_ccb->fcrb.last_ack_sent))
794      l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RR, 0);
795    else {
796      L2CAP_TRACE_DEBUG(
797          "l2c_fcr_proc_pdu() not sending RR CID: 0x%04x  local_busy:%d "
798          "rej_sent:%d srej_sent:%d Expected_Seq:%u Last_Ack:%u",
799          p_ccb->local_cid, p_ccb->fcrb.local_busy, p_ccb->fcrb.rej_sent,
800          p_ccb->fcrb.srej_sent, p_ccb->fcrb.next_seq_expected,
801          p_ccb->fcrb.last_ack_sent);
802    }
803  }
804
805  /* If a window has opened, check if we can send any more packets */
806  if ((!fixed_queue_is_empty(p_ccb->fcrb.retrans_q) ||
807       !fixed_queue_is_empty(p_ccb->xmit_hold_q)) &&
808      (p_ccb->fcrb.wait_ack == false) &&
809      (l2c_fcr_is_flow_controlled(p_ccb) == false)) {
810    l2c_link_check_send_pkts(p_ccb->p_lcb, NULL, NULL);
811  }
812}
813
814/*******************************************************************************
815 *
816 * Function         l2c_lcc_proc_pdu
817 *
818 * Description      This function is the entry point for processing of a
819 *                  received PDU when in LE Coc flow control modes.
820 *
821 * Returns          -
822 *
823 ******************************************************************************/
824void l2c_lcc_proc_pdu(tL2C_CCB* p_ccb, BT_HDR* p_buf) {
825  assert(p_ccb != NULL);
826  assert(p_buf != NULL);
827  uint8_t* p = (uint8_t*)(p_buf + 1) + p_buf->offset;
828  uint16_t sdu_length;
829  BT_HDR* p_data = NULL;
830
831  /* Buffer length should not exceed local mps */
832  if (p_buf->len > p_ccb->local_conn_cfg.mps) {
833    /* Discard the buffer */
834    osi_free(p_buf);
835    return;
836  }
837
838  if (p_ccb->is_first_seg) {
839    STREAM_TO_UINT16(sdu_length, p);
840    /* Check the SDU Length with local MTU size */
841    if (sdu_length > p_ccb->local_conn_cfg.mtu) {
842      /* Discard the buffer */
843      osi_free(p_buf);
844      return;
845    }
846
847    p_data = (BT_HDR*)osi_malloc(L2CAP_MAX_BUF_SIZE);
848    if (p_data == NULL) {
849      osi_free(p_buf);
850      return;
851    }
852
853    p_ccb->ble_sdu = p_data;
854    p_data->len = 0;
855    p_ccb->ble_sdu_length = sdu_length;
856    L2CAP_TRACE_DEBUG("%s SDU Length = %d", __func__, sdu_length);
857    p_buf->len -= sizeof(sdu_length);
858    p_buf->offset += sizeof(sdu_length);
859    p_data->offset = 0;
860
861  } else
862    p_data = p_ccb->ble_sdu;
863
864  memcpy((uint8_t*)(p_data + 1) + p_data->offset + p_data->len,
865         (uint8_t*)(p_buf + 1) + p_buf->offset, p_buf->len);
866  p_data->len += p_buf->len;
867  p = (uint8_t*)(p_data + 1) + p_data->offset;
868  if (p_data->len == p_ccb->ble_sdu_length) {
869    l2c_csm_execute(p_ccb, L2CEVT_L2CAP_DATA, p_data);
870    p_ccb->is_first_seg = true;
871    p_ccb->ble_sdu = NULL;
872    p_ccb->ble_sdu_length = 0;
873  } else if (p_data->len < p_ccb->ble_sdu_length) {
874    p_ccb->is_first_seg = false;
875  } else {
876    L2CAP_TRACE_ERROR("%s Length in the SDU messed up", __func__);
877    // TODO: reset every thing may be???
878  }
879
880  osi_free(p_buf);
881  return;
882}
883
884/*******************************************************************************
885 *
886 * Function         l2c_fcr_proc_tout
887 *
888 * Description      Handle a timeout. We should be in error recovery state.
889 *
890 * Returns          -
891 *
892 ******************************************************************************/
893void l2c_fcr_proc_tout(tL2C_CCB* p_ccb) {
894  assert(p_ccb != NULL);
895  L2CAP_TRACE_DEBUG(
896      "l2c_fcr_proc_tout:  CID: 0x%04x  num_tries: %u (max: %u)  wait_ack: %u  "
897      "ack_q_count: %u",
898      p_ccb->local_cid, p_ccb->fcrb.num_tries, p_ccb->peer_cfg.fcr.max_transmit,
899      p_ccb->fcrb.wait_ack, fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q));
900
901#if (L2CAP_ERTM_STATS == TRUE)
902  p_ccb->fcrb.retrans_touts++;
903#endif
904
905  if ((p_ccb->peer_cfg.fcr.max_transmit != 0) &&
906      (++p_ccb->fcrb.num_tries > p_ccb->peer_cfg.fcr.max_transmit)) {
907    l2cu_disconnect_chnl(p_ccb);
908  } else {
909    if (!p_ccb->fcrb.srej_sent && !p_ccb->fcrb.rej_sent) {
910      if (p_ccb->fcrb.local_busy)
911        l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RNR, L2CAP_FCR_P_BIT);
912      else
913        l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RR, L2CAP_FCR_P_BIT);
914    }
915  }
916}
917
918/*******************************************************************************
919 *
920 * Function         l2c_fcr_proc_ack_tout
921 *
922 * Description      Send RR/RNR if we have not acked I frame
923 *
924 * Returns          -
925 *
926 ******************************************************************************/
927void l2c_fcr_proc_ack_tout(tL2C_CCB* p_ccb) {
928  assert(p_ccb != NULL);
929  L2CAP_TRACE_DEBUG(
930      "l2c_fcr_proc_ack_tout:  CID: 0x%04x State: %u  Wack:%u  Rq:%d  Acked:%d",
931      p_ccb->local_cid, p_ccb->chnl_state, p_ccb->fcrb.wait_ack,
932      p_ccb->fcrb.next_seq_expected, p_ccb->fcrb.last_ack_sent);
933
934  if ((p_ccb->chnl_state == CST_OPEN) && (!p_ccb->fcrb.wait_ack) &&
935      (p_ccb->fcrb.last_ack_sent != p_ccb->fcrb.next_seq_expected)) {
936#if (L2CAP_ERTM_STATS == TRUE)
937    p_ccb->fcrb.xmit_ack_touts++;
938#endif
939    if (p_ccb->fcrb.local_busy)
940      l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RNR, 0);
941    else
942      l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RR, 0);
943  }
944}
945
946/*******************************************************************************
947 *
948 * Function         process_reqseq
949 *
950 * Description      Handle receive sequence number
951 *
952 * Returns          -
953 *
954 ******************************************************************************/
955static bool process_reqseq(tL2C_CCB* p_ccb, uint16_t ctrl_word) {
956  assert(p_ccb != NULL);
957  tL2C_FCRB* p_fcrb = &p_ccb->fcrb;
958  uint8_t req_seq, num_bufs_acked, xx;
959  uint16_t ls;
960  uint16_t full_sdus_xmitted;
961
962  /* Receive sequence number does not ack anything for SREJ with P-bit set to
963   * zero */
964  if ((ctrl_word & L2CAP_FCR_S_FRAME_BIT) &&
965      ((ctrl_word & L2CAP_FCR_SUP_BITS) ==
966       (L2CAP_FCR_SUP_SREJ << L2CAP_FCR_SUP_SHIFT)) &&
967      ((ctrl_word & L2CAP_FCR_P_BIT) == 0)) {
968    /* If anything still waiting for ack, restart the timer if it was stopped */
969    if (!fixed_queue_is_empty(p_fcrb->waiting_for_ack_q))
970      l2c_fcr_start_timer(p_ccb);
971
972    return (true);
973  }
974
975  /* Extract the receive sequence number from the control word */
976  req_seq =
977      (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT;
978
979  num_bufs_acked = (req_seq - p_fcrb->last_rx_ack) & L2CAP_FCR_SEQ_MODULO;
980
981  /* Verify the request sequence is in range before proceeding */
982  if (num_bufs_acked > fixed_queue_length(p_fcrb->waiting_for_ack_q)) {
983    /* The channel is closed if ReqSeq is not in range */
984    L2CAP_TRACE_WARNING(
985        "L2CAP eRTM Frame BAD Req_Seq - ctrl_word: 0x%04x  req_seq 0x%02x  "
986        "last_rx_ack: 0x%02x  QCount: %u",
987        ctrl_word, req_seq, p_fcrb->last_rx_ack,
988        fixed_queue_length(p_fcrb->waiting_for_ack_q));
989
990    l2cu_disconnect_chnl(p_ccb);
991    return (false);
992  }
993
994  p_fcrb->last_rx_ack = req_seq;
995
996  /* Now we can release all acknowledged frames, and restart the retransmission
997   * timer if needed */
998  if (num_bufs_acked != 0) {
999    p_fcrb->num_tries = 0;
1000    full_sdus_xmitted = 0;
1001
1002#if (L2CAP_ERTM_STATS == TRUE)
1003    l2c_fcr_collect_ack_delay(p_ccb, num_bufs_acked);
1004#endif
1005
1006    for (xx = 0; xx < num_bufs_acked; xx++) {
1007      BT_HDR* p_tmp =
1008          (BT_HDR*)fixed_queue_try_dequeue(p_fcrb->waiting_for_ack_q);
1009      ls = p_tmp->layer_specific & L2CAP_FCR_SAR_BITS;
1010
1011      if ((ls == L2CAP_FCR_UNSEG_SDU) || (ls == L2CAP_FCR_END_SDU))
1012        full_sdus_xmitted++;
1013
1014      osi_free(p_tmp);
1015    }
1016
1017    /* If we are still in a wait_ack state, do not mess with the timer */
1018    if (!p_ccb->fcrb.wait_ack) l2c_fcr_stop_timer(p_ccb);
1019
1020    /* Check if we need to call the "packet_sent" callback */
1021    if ((p_ccb->p_rcb) && (p_ccb->p_rcb->api.pL2CA_TxComplete_Cb) &&
1022        (full_sdus_xmitted)) {
1023      /* Special case for eRTM, if all packets sent, send 0xFFFF */
1024      if (fixed_queue_is_empty(p_fcrb->waiting_for_ack_q) &&
1025          fixed_queue_is_empty(p_ccb->xmit_hold_q)) {
1026        full_sdus_xmitted = 0xFFFF;
1027      }
1028
1029      (*p_ccb->p_rcb->api.pL2CA_TxComplete_Cb)(p_ccb->local_cid,
1030                                               full_sdus_xmitted);
1031    }
1032  }
1033
1034  /* If anything still waiting for ack, restart the timer if it was stopped */
1035  if (!fixed_queue_is_empty(p_fcrb->waiting_for_ack_q))
1036    l2c_fcr_start_timer(p_ccb);
1037  return (true);
1038}
1039
1040/*******************************************************************************
1041 *
1042 * Function         process_s_frame
1043 *
1044 * Description      Process an S frame
1045 *
1046 * Returns          -
1047 *
1048 ******************************************************************************/
1049static void process_s_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf,
1050                            uint16_t ctrl_word) {
1051  assert(p_ccb != NULL);
1052  assert(p_buf != NULL);
1053
1054  tL2C_FCRB* p_fcrb = &p_ccb->fcrb;
1055  uint16_t s_frame_type =
1056      (ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT;
1057  bool remote_was_busy;
1058  bool all_ok = true;
1059
1060  if (p_buf->len != 0) {
1061    L2CAP_TRACE_WARNING("Incorrect S-frame Length (%d)", p_buf->len);
1062  }
1063
1064  L2CAP_TRACE_DEBUG("process_s_frame ctrl_word 0x%04x fcrb_remote_busy:%d",
1065                    ctrl_word, p_fcrb->remote_busy);
1066
1067#if (L2CAP_ERTM_STATS == TRUE)
1068  p_ccb->fcrb.s_frames_rcvd[s_frame_type]++;
1069#endif
1070
1071  if (ctrl_word & L2CAP_FCR_P_BIT) {
1072    p_fcrb->rej_sent = false;  /* After checkpoint, we can send anoher REJ */
1073    p_fcrb->send_f_rsp = true; /* Set a flag in case an I-frame is pending */
1074  }
1075
1076  switch (s_frame_type) {
1077    case L2CAP_FCR_SUP_RR:
1078      remote_was_busy = p_fcrb->remote_busy;
1079      p_fcrb->remote_busy = false;
1080
1081      if ((ctrl_word & L2CAP_FCR_F_BIT) || (remote_was_busy))
1082        all_ok = retransmit_i_frames(p_ccb, L2C_FCR_RETX_ALL_PKTS);
1083      break;
1084
1085    case L2CAP_FCR_SUP_REJ:
1086      p_fcrb->remote_busy = false;
1087      all_ok = retransmit_i_frames(p_ccb, L2C_FCR_RETX_ALL_PKTS);
1088      break;
1089
1090    case L2CAP_FCR_SUP_RNR:
1091      p_fcrb->remote_busy = true;
1092      l2c_fcr_stop_timer(p_ccb);
1093      break;
1094
1095    case L2CAP_FCR_SUP_SREJ:
1096      p_fcrb->remote_busy = false;
1097      all_ok = retransmit_i_frames(
1098          p_ccb, (uint8_t)((ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >>
1099                           L2CAP_FCR_REQ_SEQ_BITS_SHIFT));
1100      break;
1101  }
1102
1103  if (all_ok) {
1104    /* If polled, we need to respond with F-bit. Note, we may have sent a
1105     * I-frame with the F-bit */
1106    if (p_fcrb->send_f_rsp) {
1107      if (p_fcrb->srej_sent)
1108        l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_SREJ, L2CAP_FCR_F_BIT);
1109      else if (p_fcrb->local_busy)
1110        l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RNR, L2CAP_FCR_F_BIT);
1111      else
1112        l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RR, L2CAP_FCR_F_BIT);
1113
1114      p_fcrb->send_f_rsp = false;
1115    }
1116  } else {
1117    L2CAP_TRACE_DEBUG("process_s_frame hit_max_retries");
1118  }
1119
1120  osi_free(p_buf);
1121}
1122
1123/*******************************************************************************
1124 *
1125 * Function         process_i_frame
1126 *
1127 * Description      Process an I frame
1128 *
1129 * Returns          -
1130 *
1131 ******************************************************************************/
1132static void process_i_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, uint16_t ctrl_word,
1133                            bool delay_ack) {
1134  assert(p_ccb != NULL);
1135  assert(p_buf != NULL);
1136
1137  tL2C_FCRB* p_fcrb = &p_ccb->fcrb;
1138  uint8_t tx_seq, num_lost, num_to_ack, next_srej;
1139
1140  /* If we were doing checkpoint recovery, first retransmit all unacked I-frames
1141   */
1142  if (ctrl_word & L2CAP_FCR_F_BIT) {
1143    if (!retransmit_i_frames(p_ccb, L2C_FCR_RETX_ALL_PKTS)) {
1144      osi_free(p_buf);
1145      return;
1146    }
1147  }
1148
1149#if (L2CAP_ERTM_STATS == TRUE)
1150  p_ccb->fcrb.ertm_pkt_counts[1]++;
1151  p_ccb->fcrb.ertm_byte_counts[1] += p_buf->len;
1152#endif
1153
1154  /* Extract the sequence number */
1155  tx_seq = (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT;
1156
1157  /* If we have flow controlled the peer, ignore any bad I-frames from him */
1158  if ((tx_seq != p_fcrb->next_seq_expected) && (p_fcrb->local_busy)) {
1159    L2CAP_TRACE_WARNING("Dropping bad I-Frame since we flowed off, tx_seq:%u",
1160                        tx_seq);
1161    l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RNR, 0);
1162    osi_free(p_buf);
1163    return;
1164  }
1165
1166  /* Check if tx-sequence is the expected one */
1167  if (tx_seq != p_fcrb->next_seq_expected) {
1168    num_lost = (tx_seq - p_fcrb->next_seq_expected) & L2CAP_FCR_SEQ_MODULO;
1169
1170    /* Is the frame a duplicate ? If so, just drop it */
1171    if (num_lost >= p_ccb->our_cfg.fcr.tx_win_sz) {
1172      /* Duplicate - simply drop it */
1173      L2CAP_TRACE_WARNING(
1174          "process_i_frame() Dropping Duplicate Frame tx_seq:%u  ExpectedTxSeq "
1175          "%u",
1176          tx_seq, p_fcrb->next_seq_expected);
1177      osi_free(p_buf);
1178    } else {
1179      L2CAP_TRACE_WARNING(
1180          "process_i_frame() CID: 0x%04x  Lost: %u  tx_seq:%u  ExpTxSeq %u  "
1181          "Rej: %u  SRej: %u",
1182          p_ccb->local_cid, num_lost, tx_seq, p_fcrb->next_seq_expected,
1183          p_fcrb->rej_sent, p_fcrb->srej_sent);
1184
1185      if (p_fcrb->srej_sent) {
1186        /* If SREJ sent, save the frame for later processing as long as it is in
1187         * sequence */
1188        next_srej =
1189            (((BT_HDR*)fixed_queue_try_peek_last(p_fcrb->srej_rcv_hold_q))
1190                 ->layer_specific +
1191             1) &
1192            L2CAP_FCR_SEQ_MODULO;
1193
1194        if ((tx_seq == next_srej) &&
1195            (fixed_queue_length(p_fcrb->srej_rcv_hold_q) <
1196             p_ccb->our_cfg.fcr.tx_win_sz)) {
1197          /* If user gave us a pool for held rx buffers, use that */
1198          /* TODO: Could that happen? Get rid of this code. */
1199          if (p_ccb->ertm_info.fcr_rx_buf_size != L2CAP_FCR_RX_BUF_SIZE) {
1200            BT_HDR* p_buf2;
1201
1202            /* Adjust offset and len so that control word is copied */
1203            p_buf->offset -= L2CAP_FCR_OVERHEAD;
1204            p_buf->len += L2CAP_FCR_OVERHEAD;
1205
1206            p_buf2 = l2c_fcr_clone_buf(p_buf, p_buf->offset, p_buf->len);
1207
1208            if (p_buf2) {
1209              osi_free(p_buf);
1210              p_buf = p_buf2;
1211            }
1212            p_buf->offset += L2CAP_FCR_OVERHEAD;
1213            p_buf->len -= L2CAP_FCR_OVERHEAD;
1214          }
1215          L2CAP_TRACE_DEBUG(
1216              "process_i_frame() Lost: %u  tx_seq:%u  ExpTxSeq %u  Rej: %u  "
1217              "SRej1",
1218              num_lost, tx_seq, p_fcrb->next_seq_expected, p_fcrb->rej_sent);
1219
1220          p_buf->layer_specific = tx_seq;
1221          fixed_queue_enqueue(p_fcrb->srej_rcv_hold_q, p_buf);
1222        } else {
1223          L2CAP_TRACE_WARNING(
1224              "process_i_frame() CID: 0x%04x  frame dropped in Srej Sent "
1225              "next_srej:%u  hold_q.count:%u  win_sz:%u",
1226              p_ccb->local_cid, next_srej,
1227              fixed_queue_length(p_fcrb->srej_rcv_hold_q),
1228              p_ccb->our_cfg.fcr.tx_win_sz);
1229
1230          p_fcrb->rej_after_srej = true;
1231          osi_free(p_buf);
1232        }
1233      } else if (p_fcrb->rej_sent) {
1234        L2CAP_TRACE_WARNING(
1235            "process_i_frame() CID: 0x%04x  Lost: %u  tx_seq:%u  ExpTxSeq %u  "
1236            "Rej: 1  SRej: %u",
1237            p_ccb->local_cid, num_lost, tx_seq, p_fcrb->next_seq_expected,
1238            p_fcrb->srej_sent);
1239
1240        /* If REJ sent, just drop the frame */
1241        osi_free(p_buf);
1242      } else {
1243        L2CAP_TRACE_DEBUG(
1244            "process_i_frame() CID: 0x%04x  tx_seq:%u  ExpTxSeq %u  Rej: %u",
1245            p_ccb->local_cid, tx_seq, p_fcrb->next_seq_expected,
1246            p_fcrb->rej_sent);
1247
1248        /* If only one lost, we will send SREJ, otherwise we will send REJ */
1249        if (num_lost > 1) {
1250          osi_free(p_buf);
1251          p_fcrb->rej_sent = true;
1252          l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_REJ, 0);
1253        } else {
1254          if (!fixed_queue_is_empty(p_fcrb->srej_rcv_hold_q)) {
1255            L2CAP_TRACE_ERROR(
1256                "process_i_frame() CID: 0x%04x  sending SREJ tx_seq:%d "
1257                "hold_q.count:%u",
1258                p_ccb->local_cid, tx_seq,
1259                fixed_queue_length(p_fcrb->srej_rcv_hold_q));
1260          }
1261          p_buf->layer_specific = tx_seq;
1262          fixed_queue_enqueue(p_fcrb->srej_rcv_hold_q, p_buf);
1263          p_fcrb->srej_sent = true;
1264          l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_SREJ, 0);
1265        }
1266        alarm_cancel(p_ccb->fcrb.ack_timer);
1267      }
1268    }
1269    return;
1270  }
1271
1272  /* Seq number is the next expected. Clear possible reject exception in case it
1273   * occured */
1274  p_fcrb->rej_sent = p_fcrb->srej_sent = false;
1275
1276  /* Adjust the next_seq, so that if the upper layer sends more data in the
1277     callback
1278     context, the received frame is acked by an I-frame. */
1279  p_fcrb->next_seq_expected = (tx_seq + 1) & L2CAP_FCR_SEQ_MODULO;
1280
1281  /* If any SAR problem in eRTM mode, spec says disconnect. */
1282  if (!do_sar_reassembly(p_ccb, p_buf, ctrl_word)) {
1283    L2CAP_TRACE_WARNING("process_i_frame() CID: 0x%04x  reassembly failed",
1284                        p_ccb->local_cid);
1285    l2cu_disconnect_chnl(p_ccb);
1286    return;
1287  }
1288
1289  /* RR optimization - if peer can still send us more, then start an ACK timer
1290   */
1291  num_to_ack = (p_fcrb->next_seq_expected - p_fcrb->last_ack_sent) &
1292               L2CAP_FCR_SEQ_MODULO;
1293
1294  if ((num_to_ack < p_ccb->fcrb.max_held_acks) && (!p_fcrb->local_busy))
1295    delay_ack = true;
1296
1297  /* We should neve never ack frame if we are not in OPEN state */
1298  if ((num_to_ack != 0) && p_ccb->in_use && (p_ccb->chnl_state == CST_OPEN)) {
1299    /* If no frames are awaiting transmission or are held, send an RR or RNR
1300     * S-frame for ack */
1301    if (delay_ack) {
1302      /* If it is the first I frame we did not ack, start ack timer */
1303      if (!alarm_is_scheduled(p_ccb->fcrb.ack_timer)) {
1304        alarm_set_on_queue(p_ccb->fcrb.ack_timer, L2CAP_FCR_ACK_TIMEOUT_MS,
1305                           l2c_fcrb_ack_timer_timeout, p_ccb,
1306                           btu_general_alarm_queue);
1307      }
1308    } else if ((fixed_queue_is_empty(p_ccb->xmit_hold_q) ||
1309                l2c_fcr_is_flow_controlled(p_ccb)) &&
1310               fixed_queue_is_empty(p_ccb->fcrb.srej_rcv_hold_q)) {
1311      if (p_fcrb->local_busy)
1312        l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RNR, 0);
1313      else
1314        l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RR, 0);
1315    }
1316  }
1317}
1318
1319/*******************************************************************************
1320 *
1321 * Function         process_stream_frame
1322 *
1323 * Description      This function processes frames in streaming mode
1324 *
1325 * Returns          -
1326 *
1327 ******************************************************************************/
1328static void process_stream_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf) {
1329  assert(p_ccb != NULL);
1330  assert(p_buf != NULL);
1331
1332  uint16_t ctrl_word;
1333  uint16_t fcs;
1334  uint8_t* p;
1335  uint8_t tx_seq;
1336
1337  /* Verify FCS if using */
1338  if (p_ccb->bypass_fcs != L2CAP_BYPASS_FCS) {
1339    p = ((uint8_t*)(p_buf + 1)) + p_buf->offset + p_buf->len - L2CAP_FCS_LEN;
1340
1341    /* Extract and drop the FCS from the packet */
1342    STREAM_TO_UINT16(fcs, p);
1343    p_buf->len -= L2CAP_FCS_LEN;
1344
1345    if (l2c_fcr_rx_get_fcs(p_buf) != fcs) {
1346      L2CAP_TRACE_WARNING("Rx L2CAP PDU: CID: 0x%04x  BAD FCS",
1347                          p_ccb->local_cid);
1348      osi_free(p_buf);
1349      return;
1350    }
1351  }
1352
1353  /* Get the control word */
1354  p = ((uint8_t*)(p_buf + 1)) + p_buf->offset;
1355
1356  STREAM_TO_UINT16(ctrl_word, p);
1357
1358  p_buf->len -= L2CAP_FCR_OVERHEAD;
1359  p_buf->offset += L2CAP_FCR_OVERHEAD;
1360
1361  /* Make sure it is an I-frame */
1362  if (ctrl_word & L2CAP_FCR_S_FRAME_BIT) {
1363    L2CAP_TRACE_WARNING(
1364        "Rx L2CAP PDU: CID: 0x%04x  BAD S-frame in streaming mode  ctrl_word: "
1365        "0x%04x",
1366        p_ccb->local_cid, ctrl_word);
1367    osi_free(p_buf);
1368    return;
1369  }
1370
1371  L2CAP_TRACE_EVENT(
1372      "L2CAP eRTM Rx I-frame: cid: 0x%04x  Len: %u  SAR: %-12s  TxSeq: %u  "
1373      "ReqSeq: %u  F: %u",
1374      p_ccb->local_cid, p_buf->len,
1375      SAR_types[(ctrl_word & L2CAP_FCR_SAR_BITS) >> L2CAP_FCR_SAR_BITS_SHIFT],
1376      (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT,
1377      (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
1378      (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
1379
1380  /* Extract the sequence number */
1381  tx_seq = (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT;
1382
1383  /* Check if tx-sequence is the expected one */
1384  if (tx_seq != p_ccb->fcrb.next_seq_expected) {
1385    L2CAP_TRACE_WARNING(
1386        "Rx L2CAP PDU: CID: 0x%04x  Lost frames Exp: %u  Got: %u  p_rx_sdu: "
1387        "0x%08x",
1388        p_ccb->local_cid, p_ccb->fcrb.next_seq_expected, tx_seq,
1389        p_ccb->fcrb.p_rx_sdu);
1390
1391    /* Lost one or more packets, so flush the SAR queue */
1392    osi_free_and_reset((void**)&p_ccb->fcrb.p_rx_sdu);
1393  }
1394
1395  p_ccb->fcrb.next_seq_expected = (tx_seq + 1) & L2CAP_FCR_SEQ_MODULO;
1396
1397  if (!do_sar_reassembly(p_ccb, p_buf, ctrl_word)) {
1398    /* Some sort of SAR error, so flush the SAR queue */
1399    osi_free_and_reset((void**)&p_ccb->fcrb.p_rx_sdu);
1400  }
1401}
1402
1403/*******************************************************************************
1404 *
1405 * Function         do_sar_reassembly
1406 *
1407 * Description      Process SAR bits and re-assemble frame
1408 *
1409 * Returns          true if all OK, else false
1410 *
1411 ******************************************************************************/
1412static bool do_sar_reassembly(tL2C_CCB* p_ccb, BT_HDR* p_buf,
1413                              uint16_t ctrl_word) {
1414  assert(p_ccb != NULL);
1415  assert(p_buf != NULL);
1416
1417  tL2C_FCRB* p_fcrb = &p_ccb->fcrb;
1418  uint16_t sar_type = ctrl_word & L2CAP_FCR_SEG_BITS;
1419  bool packet_ok = true;
1420  uint8_t* p;
1421
1422  /* Check if the SAR state is correct */
1423  if ((sar_type == L2CAP_FCR_UNSEG_SDU) || (sar_type == L2CAP_FCR_START_SDU)) {
1424    if (p_fcrb->p_rx_sdu != NULL) {
1425      L2CAP_TRACE_WARNING(
1426          "SAR - got unexpected unsegmented or start SDU  Expected len: %u  "
1427          "Got so far: %u",
1428          p_fcrb->rx_sdu_len, p_fcrb->p_rx_sdu->len);
1429
1430      packet_ok = false;
1431    }
1432    /* Check the length of the packet */
1433    if ((sar_type == L2CAP_FCR_START_SDU) &&
1434        (p_buf->len < L2CAP_SDU_LEN_OVERHEAD)) {
1435      L2CAP_TRACE_WARNING("SAR start packet too short: %u", p_buf->len);
1436      packet_ok = false;
1437    }
1438  } else {
1439    if (p_fcrb->p_rx_sdu == NULL) {
1440      L2CAP_TRACE_WARNING("SAR - got unexpected cont or end SDU");
1441      packet_ok = false;
1442    }
1443  }
1444
1445  if ((packet_ok) && (sar_type != L2CAP_FCR_UNSEG_SDU)) {
1446    p = ((uint8_t*)(p_buf + 1)) + p_buf->offset;
1447
1448    /* For start SDU packet, extract the SDU length */
1449    if (sar_type == L2CAP_FCR_START_SDU) {
1450      /* Get the SDU length */
1451      STREAM_TO_UINT16(p_fcrb->rx_sdu_len, p);
1452      p_buf->offset += 2;
1453      p_buf->len -= 2;
1454
1455      if (p_fcrb->rx_sdu_len > p_ccb->max_rx_mtu) {
1456        L2CAP_TRACE_WARNING("SAR - SDU len: %u  larger than MTU: %u",
1457                            p_fcrb->rx_sdu_len, p_fcrb->rx_sdu_len);
1458        packet_ok = false;
1459      } else {
1460        p_fcrb->p_rx_sdu = (BT_HDR*)osi_malloc(L2CAP_MAX_BUF_SIZE);
1461        p_fcrb->p_rx_sdu->offset = OBX_BUF_MIN_OFFSET;
1462        p_fcrb->p_rx_sdu->len = 0;
1463      }
1464    }
1465
1466    if (packet_ok) {
1467      if ((p_fcrb->p_rx_sdu->len + p_buf->len) > p_fcrb->rx_sdu_len) {
1468        L2CAP_TRACE_ERROR(
1469            "SAR - SDU len exceeded  Type: %u   Lengths: %u %u %u", sar_type,
1470            p_fcrb->p_rx_sdu->len, p_buf->len, p_fcrb->rx_sdu_len);
1471        packet_ok = false;
1472      } else if ((sar_type == L2CAP_FCR_END_SDU) &&
1473                 ((p_fcrb->p_rx_sdu->len + p_buf->len) != p_fcrb->rx_sdu_len)) {
1474        L2CAP_TRACE_WARNING("SAR - SDU end rcvd but SDU incomplete: %u %u %u",
1475                            p_fcrb->p_rx_sdu->len, p_buf->len,
1476                            p_fcrb->rx_sdu_len);
1477        packet_ok = false;
1478      } else {
1479        memcpy(((uint8_t*)(p_fcrb->p_rx_sdu + 1)) + p_fcrb->p_rx_sdu->offset +
1480                   p_fcrb->p_rx_sdu->len,
1481               p, p_buf->len);
1482
1483        p_fcrb->p_rx_sdu->len += p_buf->len;
1484
1485        osi_free(p_buf);
1486        p_buf = NULL;
1487
1488        if (sar_type == L2CAP_FCR_END_SDU) {
1489          p_buf = p_fcrb->p_rx_sdu;
1490          p_fcrb->p_rx_sdu = NULL;
1491        }
1492      }
1493    }
1494  }
1495
1496  if (packet_ok == false) {
1497    osi_free(p_buf);
1498  } else if (p_buf != NULL) {
1499#if (L2CAP_NUM_FIXED_CHNLS > 0)
1500    if (p_ccb->local_cid < L2CAP_BASE_APPL_CID &&
1501        (p_ccb->local_cid >= L2CAP_FIRST_FIXED_CHNL &&
1502         p_ccb->local_cid <= L2CAP_LAST_FIXED_CHNL)) {
1503      if (l2cb.fixed_reg[p_ccb->local_cid - L2CAP_FIRST_FIXED_CHNL]
1504              .pL2CA_FixedData_Cb)
1505        (*l2cb.fixed_reg[p_ccb->local_cid - L2CAP_FIRST_FIXED_CHNL]
1506              .pL2CA_FixedData_Cb)(p_ccb->local_cid,
1507                                   p_ccb->p_lcb->remote_bd_addr, p_buf);
1508    } else
1509#endif
1510      l2c_csm_execute(p_ccb, L2CEVT_L2CAP_DATA, p_buf);
1511  }
1512
1513  return (packet_ok);
1514}
1515
1516/*******************************************************************************
1517 *
1518 * Function         retransmit_i_frames
1519 *
1520 * Description      This function retransmits i-frames awaiting acks.
1521 *
1522 * Returns          bool    - true if retransmitted
1523 *
1524 ******************************************************************************/
1525static bool retransmit_i_frames(tL2C_CCB* p_ccb, uint8_t tx_seq) {
1526  assert(p_ccb != NULL);
1527
1528  BT_HDR* p_buf = NULL;
1529  uint8_t* p;
1530  uint8_t buf_seq;
1531  uint16_t ctrl_word;
1532
1533  if ((!fixed_queue_is_empty(p_ccb->fcrb.waiting_for_ack_q)) &&
1534      (p_ccb->peer_cfg.fcr.max_transmit != 0) &&
1535      (p_ccb->fcrb.num_tries >= p_ccb->peer_cfg.fcr.max_transmit)) {
1536    L2CAP_TRACE_EVENT(
1537        "Max Tries Exceeded:  (last_acq: %d  CID: 0x%04x  num_tries: %u (max: "
1538        "%u) ack_q_count: %u",
1539        p_ccb->fcrb.last_rx_ack, p_ccb->local_cid, p_ccb->fcrb.num_tries,
1540        p_ccb->peer_cfg.fcr.max_transmit,
1541        fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q));
1542
1543    l2cu_disconnect_chnl(p_ccb);
1544    return (false);
1545  }
1546
1547  /* tx_seq indicates whether to retransmit a specific sequence or all (if ==
1548   * L2C_FCR_RETX_ALL_PKTS) */
1549  list_t* list_ack = NULL;
1550  const list_node_t* node_ack = NULL;
1551  if (!fixed_queue_is_empty(p_ccb->fcrb.waiting_for_ack_q)) {
1552    list_ack = fixed_queue_get_list(p_ccb->fcrb.waiting_for_ack_q);
1553    node_ack = list_begin(list_ack);
1554  }
1555  if (tx_seq != L2C_FCR_RETX_ALL_PKTS) {
1556    /* If sending only one, the sequence number tells us which one. Look for it.
1557    */
1558    if (list_ack != NULL) {
1559      for (; node_ack != list_end(list_ack); node_ack = list_next(node_ack)) {
1560        p_buf = (BT_HDR*)list_node(node_ack);
1561        /* Get the old control word */
1562        p = ((uint8_t*)(p_buf + 1)) + p_buf->offset + L2CAP_PKT_OVERHEAD;
1563
1564        STREAM_TO_UINT16(ctrl_word, p);
1565
1566        buf_seq =
1567            (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT;
1568
1569        L2CAP_TRACE_DEBUG(
1570            "retransmit_i_frames()   cur seq: %u  looking for: %u", buf_seq,
1571            tx_seq);
1572
1573        if (tx_seq == buf_seq) break;
1574      }
1575    }
1576
1577    if (!p_buf) {
1578      L2CAP_TRACE_ERROR("retransmit_i_frames() UNKNOWN seq: %u  q_count: %u",
1579                        tx_seq,
1580                        fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q));
1581      return (true);
1582    }
1583  } else {
1584    // Iterate though list and flush the amount requested from
1585    // the transmit data queue that satisfy the layer and event conditions.
1586    for (list_node_t* node_tmp = list_begin(p_ccb->p_lcb->link_xmit_data_q);
1587         node_tmp != list_end(p_ccb->p_lcb->link_xmit_data_q);) {
1588      BT_HDR* p_tmp = (BT_HDR*)list_node(node_tmp);
1589      node_tmp = list_next(node_tmp);
1590
1591      /* Do not flush other CIDs or partial segments */
1592      if ((p_tmp->layer_specific == 0) && (p_tmp->event == p_ccb->local_cid)) {
1593        list_remove(p_ccb->p_lcb->link_xmit_data_q, p_tmp);
1594        osi_free(p_tmp);
1595      }
1596    }
1597
1598    /* Also flush our retransmission queue */
1599    while (!fixed_queue_is_empty(p_ccb->fcrb.retrans_q))
1600      osi_free(fixed_queue_try_dequeue(p_ccb->fcrb.retrans_q));
1601
1602    if (list_ack != NULL) node_ack = list_begin(list_ack);
1603  }
1604
1605  if (list_ack != NULL) {
1606    while (node_ack != list_end(list_ack)) {
1607      p_buf = (BT_HDR*)list_node(node_ack);
1608      node_ack = list_next(node_ack);
1609
1610      BT_HDR* p_buf2 = l2c_fcr_clone_buf(p_buf, p_buf->offset, p_buf->len);
1611      if (p_buf2) {
1612        p_buf2->layer_specific = p_buf->layer_specific;
1613
1614        fixed_queue_enqueue(p_ccb->fcrb.retrans_q, p_buf2);
1615      }
1616
1617      if ((tx_seq != L2C_FCR_RETX_ALL_PKTS) || (p_buf2 == NULL)) break;
1618    }
1619  }
1620
1621  l2c_link_check_send_pkts(p_ccb->p_lcb, NULL, NULL);
1622
1623  if (fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q)) {
1624    p_ccb->fcrb.num_tries++;
1625    l2c_fcr_start_timer(p_ccb);
1626  }
1627
1628  return (true);
1629}
1630
1631/*******************************************************************************
1632 *
1633 * Function         l2c_fcr_get_next_xmit_sdu_seg
1634 *
1635 * Description      Get the next SDU segment to transmit.
1636 *
1637 * Returns          pointer to buffer with segment or NULL
1638 *
1639 ******************************************************************************/
1640BT_HDR* l2c_fcr_get_next_xmit_sdu_seg(tL2C_CCB* p_ccb,
1641                                      uint16_t max_packet_length) {
1642  assert(p_ccb != NULL);
1643
1644  bool first_seg = false, /* The segment is the first part of data  */
1645      mid_seg = false,    /* The segment is the middle part of data */
1646      last_seg = false;   /* The segment is the last part of data   */
1647  uint16_t sdu_len = 0;
1648  BT_HDR *p_buf, *p_xmit;
1649  uint8_t* p;
1650  uint16_t max_pdu = p_ccb->tx_mps /* Needed? - L2CAP_MAX_HEADER_FCS*/;
1651
1652  /* If there is anything in the retransmit queue, that goes first
1653  */
1654  p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_ccb->fcrb.retrans_q);
1655  if (p_buf != NULL) {
1656    /* Update Rx Seq and FCS if we acked some packets while this one was queued
1657     */
1658    prepare_I_frame(p_ccb, p_buf, true);
1659
1660    p_buf->event = p_ccb->local_cid;
1661
1662#if (L2CAP_ERTM_STATS == TRUE)
1663    p_ccb->fcrb.pkts_retransmitted++;
1664    p_ccb->fcrb.ertm_pkt_counts[0]++;
1665    p_ccb->fcrb.ertm_byte_counts[0] += (p_buf->len - 8);
1666#endif
1667    return (p_buf);
1668  }
1669
1670  /* For BD/EDR controller, max_packet_length is set to 0             */
1671  /* For AMP controller, max_packet_length is set by available blocks */
1672  if ((max_packet_length > L2CAP_MAX_HEADER_FCS) &&
1673      (max_pdu + L2CAP_MAX_HEADER_FCS > max_packet_length)) {
1674    max_pdu = max_packet_length - L2CAP_MAX_HEADER_FCS;
1675  }
1676
1677  p_buf = (BT_HDR*)fixed_queue_try_peek_first(p_ccb->xmit_hold_q);
1678
1679  /* If there is more data than the MPS, it requires segmentation */
1680  if (p_buf->len > max_pdu) {
1681    /* We are using the "event" field to tell is if we already started
1682     * segmentation */
1683    if (p_buf->event == 0) {
1684      first_seg = true;
1685      sdu_len = p_buf->len;
1686    } else
1687      mid_seg = true;
1688
1689    /* Get a new buffer and copy the data that can be sent in a PDU */
1690    p_xmit = l2c_fcr_clone_buf(p_buf, L2CAP_MIN_OFFSET + L2CAP_SDU_LEN_OFFSET,
1691                               max_pdu);
1692
1693    if (p_xmit != NULL) {
1694      p_buf->event = p_ccb->local_cid;
1695      p_xmit->event = p_ccb->local_cid;
1696
1697      p_buf->len -= max_pdu;
1698      p_buf->offset += max_pdu;
1699
1700      /* copy PBF setting */
1701      p_xmit->layer_specific = p_buf->layer_specific;
1702    } else /* Should never happen if the application has configured buffers
1703              correctly */
1704    {
1705      L2CAP_TRACE_ERROR(
1706          "L2CAP - cannot get buffer for segmentation, max_pdu: %u", max_pdu);
1707      return (NULL);
1708    }
1709  } else /* Use the original buffer if no segmentation, or the last segment */
1710  {
1711    p_xmit = (BT_HDR*)fixed_queue_try_dequeue(p_ccb->xmit_hold_q);
1712
1713    if (p_xmit->event != 0) last_seg = true;
1714
1715    p_xmit->event = p_ccb->local_cid;
1716  }
1717
1718  /* Step back to add the L2CAP headers */
1719  p_xmit->offset -= (L2CAP_PKT_OVERHEAD + L2CAP_FCR_OVERHEAD);
1720  p_xmit->len += L2CAP_PKT_OVERHEAD + L2CAP_FCR_OVERHEAD;
1721
1722  if (first_seg) {
1723    p_xmit->offset -= L2CAP_SDU_LEN_OVERHEAD;
1724    p_xmit->len += L2CAP_SDU_LEN_OVERHEAD;
1725  }
1726
1727  /* Set the pointer to the beginning of the data */
1728  p = (uint8_t*)(p_xmit + 1) + p_xmit->offset;
1729
1730  /* Now the L2CAP header */
1731
1732  /* Note: if FCS has to be included then the length is recalculated later */
1733  UINT16_TO_STREAM(p, p_xmit->len - L2CAP_PKT_OVERHEAD);
1734
1735  UINT16_TO_STREAM(p, p_ccb->remote_cid);
1736
1737  if (first_seg) {
1738    /* Skip control word and add SDU length */
1739    p += 2;
1740    UINT16_TO_STREAM(p, sdu_len);
1741
1742    /* We will store the SAR type in layer-specific */
1743    /* layer_specific is shared with flushable flag(bits 0-1), don't clear it */
1744    p_xmit->layer_specific |= L2CAP_FCR_START_SDU;
1745
1746    first_seg = false;
1747  } else if (mid_seg)
1748    p_xmit->layer_specific |= L2CAP_FCR_CONT_SDU;
1749  else if (last_seg)
1750    p_xmit->layer_specific |= L2CAP_FCR_END_SDU;
1751  else
1752    p_xmit->layer_specific |= L2CAP_FCR_UNSEG_SDU;
1753
1754  prepare_I_frame(p_ccb, p_xmit, false);
1755
1756  if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) {
1757    BT_HDR* p_wack =
1758        l2c_fcr_clone_buf(p_xmit, HCI_DATA_PREAMBLE_SIZE, p_xmit->len);
1759
1760    if (!p_wack) {
1761      L2CAP_TRACE_ERROR(
1762          "L2CAP - no buffer for xmit cloning, CID: 0x%04x  Length: %u",
1763          p_ccb->local_cid, p_xmit->len);
1764
1765      /* We will not save the FCS in case we reconfigure and change options */
1766      if (p_ccb->bypass_fcs != L2CAP_BYPASS_FCS) p_xmit->len -= L2CAP_FCS_LEN;
1767
1768      /* Pretend we sent it and it got lost */
1769      fixed_queue_enqueue(p_ccb->fcrb.waiting_for_ack_q, p_xmit);
1770      return (NULL);
1771    } else {
1772#if (L2CAP_ERTM_STATS == TRUE)
1773      /* set timestamp at the end of tx I-frame to get acking delay */
1774      /*
1775       * NOTE: Here we assume the allocate buffer is large enough
1776       * to include extra 4 octets at the end.
1777       */
1778      p = ((uint8_t*)(p_wack + 1)) + p_wack->offset + p_wack->len;
1779      UINT32_TO_STREAM(p, time_get_os_boottime_ms());
1780#endif
1781      /* We will not save the FCS in case we reconfigure and change options */
1782      if (p_ccb->bypass_fcs != L2CAP_BYPASS_FCS) p_wack->len -= L2CAP_FCS_LEN;
1783
1784      p_wack->layer_specific = p_xmit->layer_specific;
1785      fixed_queue_enqueue(p_ccb->fcrb.waiting_for_ack_q, p_wack);
1786    }
1787
1788#if (L2CAP_ERTM_STATS == TRUE)
1789    p_ccb->fcrb.ertm_pkt_counts[0]++;
1790    p_ccb->fcrb.ertm_byte_counts[0] += (p_xmit->len - 8);
1791#endif
1792  }
1793
1794  return (p_xmit);
1795}
1796
1797/*******************************************************************************
1798 *
1799 * Function         l2c_lcc_get_next_xmit_sdu_seg
1800 *
1801 * Description      Get the next SDU segment to transmit for LE connection
1802 *                  oriented channel
1803 *
1804 * Returns          pointer to buffer with segment or NULL
1805 *
1806 ******************************************************************************/
1807BT_HDR* l2c_lcc_get_next_xmit_sdu_seg(tL2C_CCB* p_ccb,
1808                                      uint16_t max_packet_length) {
1809  bool first_seg = false; /* The segment is the first part of data  */
1810  bool last_seg = false;  /* The segment is the last part of data  */
1811  uint16_t no_of_bytes_to_send = 0;
1812  uint16_t sdu_len = 0;
1813  BT_HDR *p_buf, *p_xmit;
1814  uint8_t* p;
1815  uint16_t max_pdu = p_ccb->peer_conn_cfg.mps;
1816
1817  p_buf = (BT_HDR*)fixed_queue_try_peek_first(p_ccb->xmit_hold_q);
1818
1819  /* We are using the "event" field to tell is if we already started
1820   * segmentation */
1821  if (p_buf->event == 0) {
1822    first_seg = true;
1823    sdu_len = p_buf->len;
1824    if (p_buf->len <= (max_pdu - L2CAP_LCC_SDU_LENGTH)) {
1825      last_seg = true;
1826      no_of_bytes_to_send = p_buf->len;
1827    } else
1828      no_of_bytes_to_send = max_pdu - L2CAP_LCC_SDU_LENGTH;
1829  } else if (p_buf->len <= max_pdu) {
1830    last_seg = true;
1831    no_of_bytes_to_send = p_buf->len;
1832  } else {
1833    /* Middle Packet */
1834    no_of_bytes_to_send = max_pdu;
1835  }
1836
1837  /* Get a new buffer and copy the data that can be sent in a PDU */
1838  if (first_seg == true)
1839    p_xmit = l2c_fcr_clone_buf(p_buf, L2CAP_LCC_OFFSET, no_of_bytes_to_send);
1840  else
1841    p_xmit = l2c_fcr_clone_buf(p_buf, L2CAP_MIN_OFFSET, no_of_bytes_to_send);
1842
1843  if (p_xmit != NULL) {
1844    p_buf->event = p_ccb->local_cid;
1845    p_xmit->event = p_ccb->local_cid;
1846
1847    if (first_seg == true) {
1848      p_xmit->offset -= L2CAP_LCC_SDU_LENGTH; /* for writing the SDU length. */
1849      p = (uint8_t*)(p_xmit + 1) + p_xmit->offset;
1850      UINT16_TO_STREAM(p, sdu_len);
1851      p_xmit->len += L2CAP_LCC_SDU_LENGTH;
1852    }
1853
1854    p_buf->len -= no_of_bytes_to_send;
1855    p_buf->offset += no_of_bytes_to_send;
1856
1857    /* copy PBF setting */
1858    p_xmit->layer_specific = p_buf->layer_specific;
1859
1860  } else /* Should never happen if the application has configured buffers
1861            correctly */
1862  {
1863    L2CAP_TRACE_ERROR("L2CAP - cannot get buffer, for segmentation");
1864    return (NULL);
1865  }
1866
1867  if (last_seg == true) {
1868    p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_ccb->xmit_hold_q);
1869    osi_free(p_buf);
1870  }
1871
1872  /* Step back to add the L2CAP headers */
1873  p_xmit->offset -= L2CAP_PKT_OVERHEAD;
1874  p_xmit->len += L2CAP_PKT_OVERHEAD;
1875
1876  /* Set the pointer to the beginning of the data */
1877  p = (uint8_t*)(p_xmit + 1) + p_xmit->offset;
1878
1879  /* Note: if FCS has to be included then the length is recalculated later */
1880  UINT16_TO_STREAM(p, p_xmit->len - L2CAP_PKT_OVERHEAD);
1881  UINT16_TO_STREAM(p, p_ccb->remote_cid);
1882  return (p_xmit);
1883}
1884
1885/*******************************************************************************
1886 * Configuration negotiation functions
1887 *
1888 * The following functions are used in negotiating channel modes during
1889 * configuration
1890 ******************************************************************************/
1891
1892/*******************************************************************************
1893 *
1894 * Function         l2c_fcr_chk_chan_modes
1895 *
1896 * Description      Validates and adjusts if necessary, the FCR options
1897 *                  based on remote EXT features.
1898 *
1899 *                  Note: This assumes peer EXT Features have been received.
1900 *                      Basic mode is used if FCR Options have not been received
1901 *
1902 * Returns          uint8_t - nonzero if can continue, '0' if no compatible
1903 *                            channels
1904 *
1905 ******************************************************************************/
1906uint8_t l2c_fcr_chk_chan_modes(tL2C_CCB* p_ccb) {
1907  assert(p_ccb != NULL);
1908
1909  /* Remove nonbasic options that the peer does not support */
1910  if (!(p_ccb->p_lcb->peer_ext_fea & L2CAP_EXTFEA_ENH_RETRANS))
1911    p_ccb->ertm_info.allowed_modes &= ~L2CAP_FCR_CHAN_OPT_ERTM;
1912
1913  if (!(p_ccb->p_lcb->peer_ext_fea & L2CAP_EXTFEA_STREAM_MODE))
1914    p_ccb->ertm_info.allowed_modes &= ~L2CAP_FCR_CHAN_OPT_STREAM;
1915
1916  /* At least one type needs to be set (Basic, ERTM, STM) to continue */
1917  if (!p_ccb->ertm_info.allowed_modes) {
1918    L2CAP_TRACE_WARNING(
1919        "L2CAP - Peer does not support our desired channel types");
1920  }
1921
1922  return (p_ccb->ertm_info.allowed_modes);
1923}
1924
1925/*******************************************************************************
1926 *
1927 * Function         l2c_fcr_adj_our_req_options
1928 *
1929 * Description      Validates and sets up the FCR options passed in from
1930 *                  L2CA_ConfigReq based on remote device's features.
1931 *
1932 * Returns          true if no errors, Otherwise false
1933 *
1934 ******************************************************************************/
1935bool l2c_fcr_adj_our_req_options(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) {
1936  assert(p_ccb != NULL);
1937  assert(p_cfg != NULL);
1938
1939  tL2CAP_FCR_OPTS* p_fcr = &p_cfg->fcr;
1940
1941  if (p_fcr->mode != p_ccb->ertm_info.preferred_mode) {
1942    L2CAP_TRACE_WARNING(
1943        "l2c_fcr_adj_our_req_options - preferred_mode (%d), does not match "
1944        "mode (%d)",
1945        p_ccb->ertm_info.preferred_mode, p_fcr->mode);
1946
1947    /* The preferred mode is passed in through tL2CAP_ERTM_INFO, so override
1948     * this one */
1949    p_fcr->mode = p_ccb->ertm_info.preferred_mode;
1950  }
1951
1952  /* If upper layer did not request eRTM mode, BASIC must be used */
1953  if (p_ccb->ertm_info.allowed_modes == L2CAP_FCR_CHAN_OPT_BASIC) {
1954    if (p_cfg->fcr_present && p_fcr->mode != L2CAP_FCR_BASIC_MODE) {
1955      L2CAP_TRACE_WARNING(
1956          "l2c_fcr_adj_our_req_options (mode %d): ERROR: No FCR options set "
1957          "using BASIC mode",
1958          p_fcr->mode);
1959    }
1960    p_fcr->mode = L2CAP_FCR_BASIC_MODE;
1961  }
1962
1963  /* Process the FCR options if initial channel bring-up (not a reconfig
1964  *request)
1965  ** Determine initial channel mode to try based on our options and remote's
1966  *features
1967  */
1968  if (p_cfg->fcr_present && !(p_ccb->config_done & RECONFIG_FLAG)) {
1969    /* We need to have at least one mode type common with the peer */
1970    if (!l2c_fcr_chk_chan_modes(p_ccb)) {
1971      /* Two channels have incompatible supported types */
1972      l2cu_disconnect_chnl(p_ccb);
1973      return (false);
1974    }
1975
1976    /* Basic is the only common channel mode between the two devices */
1977    else if (p_ccb->ertm_info.allowed_modes == L2CAP_FCR_CHAN_OPT_BASIC) {
1978      /* We only want to try Basic, so bypass sending the FCR options entirely
1979       */
1980      p_cfg->fcr_present = false;
1981      p_cfg->fcs_present = false; /* Illegal to use FCS option in basic mode */
1982      p_cfg->ext_flow_spec_present =
1983          false; /* Illegal to use extended flow spec in basic mode */
1984    }
1985
1986    /* We have at least one non-basic mode available
1987     * Override mode from available mode options based on preference, if needed
1988     */
1989    else {
1990      /* If peer does not support STREAMING, try ERTM */
1991      if (p_fcr->mode == L2CAP_FCR_STREAM_MODE &&
1992          !(p_ccb->ertm_info.allowed_modes & L2CAP_FCR_CHAN_OPT_STREAM)) {
1993        L2CAP_TRACE_DEBUG(
1994            "L2C CFG: mode is STREAM, but peer does not support; Try ERTM");
1995        p_fcr->mode = L2CAP_FCR_ERTM_MODE;
1996      }
1997
1998      /* If peer does not support ERTM, try BASIC (will support this if made it
1999       * here in the code) */
2000      if (p_fcr->mode == L2CAP_FCR_ERTM_MODE &&
2001          !(p_ccb->ertm_info.allowed_modes & L2CAP_FCR_CHAN_OPT_ERTM)) {
2002        L2CAP_TRACE_DEBUG(
2003            "L2C CFG: mode is ERTM, but peer does not support; Try BASIC");
2004        p_fcr->mode = L2CAP_FCR_BASIC_MODE;
2005      }
2006    }
2007
2008    if (p_fcr->mode != L2CAP_FCR_BASIC_MODE) {
2009      /* MTU must be smaller than buffer size */
2010      if ((p_cfg->mtu_present) && (p_cfg->mtu > p_ccb->max_rx_mtu)) {
2011        L2CAP_TRACE_WARNING("L2CAP - MTU: %u  larger than buf size: %u",
2012                            p_cfg->mtu, p_ccb->max_rx_mtu);
2013        return (false);
2014      }
2015
2016      /* application want to use the default MPS */
2017      if (p_fcr->mps == L2CAP_DEFAULT_ERM_MPS) {
2018        p_fcr->mps = L2CAP_MPS_OVER_BR_EDR;
2019      }
2020      /* MPS must be less than MTU */
2021      else if (p_fcr->mps > p_ccb->max_rx_mtu) {
2022        L2CAP_TRACE_WARNING("L2CAP - MPS  %u  invalid  MTU: %u", p_fcr->mps,
2023                            p_ccb->max_rx_mtu);
2024        return (false);
2025      }
2026
2027      /* We always initially read into the HCI buffer pool, so make sure it fits
2028       */
2029      if (p_fcr->mps > (L2CAP_MTU_SIZE - L2CAP_MAX_HEADER_FCS))
2030        p_fcr->mps = L2CAP_MTU_SIZE - L2CAP_MAX_HEADER_FCS;
2031    } else {
2032      p_cfg->fcs_present = false; /* Illegal to use FCS option in basic mode */
2033      p_cfg->ext_flow_spec_present =
2034          false; /* Illegal to use extended flow spec in basic mode */
2035    }
2036
2037    p_ccb->our_cfg.fcr = *p_fcr;
2038  } else /* Not sure how to send a reconfiguration(??) should fcr be included?
2039            */
2040  {
2041    p_ccb->our_cfg.fcr_present = false;
2042  }
2043
2044  return (true);
2045}
2046
2047/*******************************************************************************
2048 *
2049 * Function         l2c_fcr_adj_monitor_retran_timeout
2050 *
2051 * Description      Overrides monitor/retrans timer value based on controller
2052 *
2053 * Returns          None
2054 *
2055 ******************************************************************************/
2056void l2c_fcr_adj_monitor_retran_timeout(tL2C_CCB* p_ccb) {
2057  assert(p_ccb != NULL);
2058
2059  /* adjust our monitor/retran timeout */
2060  if (p_ccb->out_cfg_fcr_present) {
2061    /*
2062    ** if we requestd ERTM or accepted ERTM
2063    ** We may accept ERTM even if we didn't request ERTM, in case of requesting
2064    *STREAM
2065    */
2066    if ((p_ccb->our_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) ||
2067        (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE)) {
2068      /* upper layer setting is ignored */
2069      p_ccb->our_cfg.fcr.mon_tout = L2CAP_MIN_MONITOR_TOUT;
2070      p_ccb->our_cfg.fcr.rtrans_tout = L2CAP_MIN_RETRANS_TOUT;
2071    } else {
2072      p_ccb->our_cfg.fcr.mon_tout = 0;
2073      p_ccb->our_cfg.fcr.rtrans_tout = 0;
2074    }
2075
2076    L2CAP_TRACE_DEBUG(
2077        "l2c_fcr_adj_monitor_retran_timeout: mon_tout:%d, rtrans_tout:%d",
2078        p_ccb->our_cfg.fcr.mon_tout, p_ccb->our_cfg.fcr.rtrans_tout);
2079  }
2080}
2081/*******************************************************************************
2082 *
2083 * Function         l2c_fcr_adj_our_rsp_options
2084 *
2085 * Description      Overrides any neccesary FCR options passed in from
2086 *                  L2CA_ConfigRsp based on our FCR options.
2087 *                  Only makes adjustments if channel is in ERTM mode.
2088 *
2089 * Returns          None
2090 *
2091 ******************************************************************************/
2092void l2c_fcr_adj_our_rsp_options(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) {
2093  assert(p_ccb != NULL);
2094  assert(p_cfg != NULL);
2095
2096  /* adjust our monitor/retran timeout */
2097  l2c_fcr_adj_monitor_retran_timeout(p_ccb);
2098
2099  p_cfg->fcr_present = p_ccb->out_cfg_fcr_present;
2100
2101  if (p_cfg->fcr_present) {
2102    /* Temporary - until a better algorithm is implemented */
2103    /* If peer's tx_wnd_sz requires too many buffers for us to support, then
2104     * adjust it. For now, respond with our own tx_wnd_sz. */
2105    /* Note: peer is not guaranteed to obey our adjustment */
2106    if (p_ccb->peer_cfg.fcr.tx_win_sz > p_ccb->our_cfg.fcr.tx_win_sz) {
2107      L2CAP_TRACE_DEBUG("%s: adjusting requested tx_win_sz from %i to %i",
2108                        __func__, p_ccb->peer_cfg.fcr.tx_win_sz,
2109                        p_ccb->our_cfg.fcr.tx_win_sz);
2110      p_ccb->peer_cfg.fcr.tx_win_sz = p_ccb->our_cfg.fcr.tx_win_sz;
2111    }
2112
2113    p_cfg->fcr.mode = p_ccb->peer_cfg.fcr.mode;
2114    p_cfg->fcr.tx_win_sz = p_ccb->peer_cfg.fcr.tx_win_sz;
2115    p_cfg->fcr.max_transmit = p_ccb->peer_cfg.fcr.max_transmit;
2116    p_cfg->fcr.mps = p_ccb->peer_cfg.fcr.mps;
2117    p_cfg->fcr.rtrans_tout = p_ccb->our_cfg.fcr.rtrans_tout;
2118    p_cfg->fcr.mon_tout = p_ccb->our_cfg.fcr.mon_tout;
2119  }
2120}
2121
2122/*******************************************************************************
2123 *
2124 * Function         l2c_fcr_renegotiate_chan
2125 *
2126 * Description      Called upon unsuccessful peer response to config request.
2127 *                  If the error is because of the channel mode, it will try
2128 *                  to resend using another supported optional channel.
2129 *
2130 * Returns          true if resent configuration, False if channel matches or
2131 *                  cannot match.
2132 *
2133 ******************************************************************************/
2134bool l2c_fcr_renegotiate_chan(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) {
2135  assert(p_ccb != NULL);
2136  assert(p_cfg != NULL);
2137
2138  uint8_t peer_mode = p_ccb->our_cfg.fcr.mode;
2139  bool can_renegotiate;
2140
2141  /* Skip if this is a reconfiguration from OPEN STATE or if FCR is not returned
2142   */
2143  if (!p_cfg->fcr_present || (p_ccb->config_done & RECONFIG_FLAG))
2144    return (false);
2145
2146  /* Only retry if there are more channel options to try */
2147  if (p_cfg->result == L2CAP_CFG_UNACCEPTABLE_PARAMS) {
2148    peer_mode = (p_cfg->fcr_present) ? p_cfg->fcr.mode : L2CAP_FCR_BASIC_MODE;
2149
2150    if (p_ccb->our_cfg.fcr.mode != peer_mode) {
2151      if ((--p_ccb->fcr_cfg_tries) == 0) {
2152        p_cfg->result = L2CAP_CFG_FAILED_NO_REASON;
2153        L2CAP_TRACE_WARNING("l2c_fcr_renegotiate_chan (Max retries exceeded)");
2154      }
2155
2156      can_renegotiate = false;
2157
2158      /* Try another supported mode if available based on our last attempted
2159       * channel */
2160      switch (p_ccb->our_cfg.fcr.mode) {
2161        /* Our Streaming mode request was unnacceptable; try ERTM or Basic */
2162        case L2CAP_FCR_STREAM_MODE:
2163          /* Peer wants ERTM and we support it */
2164          if ((peer_mode == L2CAP_FCR_ERTM_MODE) &&
2165              (p_ccb->ertm_info.allowed_modes & L2CAP_FCR_CHAN_OPT_ERTM)) {
2166            L2CAP_TRACE_DEBUG("l2c_fcr_renegotiate_chan(Trying ERTM)");
2167            p_ccb->our_cfg.fcr.mode = L2CAP_FCR_ERTM_MODE;
2168            can_renegotiate = true;
2169          } else /* Falls through */
2170
2171          case L2CAP_FCR_ERTM_MODE: {
2172            /* We can try basic for any other peer mode if we support it */
2173            if (p_ccb->ertm_info.allowed_modes & L2CAP_FCR_CHAN_OPT_BASIC) {
2174              L2CAP_TRACE_DEBUG("l2c_fcr_renegotiate_chan(Trying Basic)");
2175              can_renegotiate = true;
2176              p_ccb->our_cfg.fcr.mode = L2CAP_FCR_BASIC_MODE;
2177            }
2178          } break;
2179
2180          default:
2181            /* All other scenarios cannot be renegotiated */
2182            break;
2183      }
2184
2185      if (can_renegotiate) {
2186        p_ccb->our_cfg.fcr_present = true;
2187
2188        if (p_ccb->our_cfg.fcr.mode == L2CAP_FCR_BASIC_MODE) {
2189          p_ccb->our_cfg.fcs_present = false;
2190          p_ccb->our_cfg.ext_flow_spec_present = false;
2191
2192          /* Basic Mode uses ACL Data Pool, make sure the MTU fits */
2193          if ((p_cfg->mtu_present) && (p_cfg->mtu > L2CAP_MTU_SIZE)) {
2194            L2CAP_TRACE_WARNING("L2CAP - adjust MTU: %u too large", p_cfg->mtu);
2195            p_cfg->mtu = L2CAP_MTU_SIZE;
2196          }
2197        }
2198
2199        l2cu_process_our_cfg_req(p_ccb, &p_ccb->our_cfg);
2200        l2cu_send_peer_config_req(p_ccb, &p_ccb->our_cfg);
2201        alarm_set_on_queue(p_ccb->l2c_ccb_timer, L2CAP_CHNL_CFG_TIMEOUT_MS,
2202                           l2c_ccb_timer_timeout, p_ccb,
2203                           btu_general_alarm_queue);
2204        return (true);
2205      }
2206    }
2207  }
2208
2209  /* Disconnect if the channels do not match */
2210  if (p_ccb->our_cfg.fcr.mode != peer_mode) {
2211    L2CAP_TRACE_WARNING("L2C CFG:  Channels incompatible (local %d, peer %d)",
2212                        p_ccb->our_cfg.fcr.mode, peer_mode);
2213    l2cu_disconnect_chnl(p_ccb);
2214  }
2215
2216  return (false);
2217}
2218
2219/*******************************************************************************
2220 *
2221 * Function         l2c_fcr_process_peer_cfg_req
2222 *
2223 * Description      This function is called to process the FCR options passed
2224 *                  in the peer's configuration request.
2225 *
2226 * Returns          uint8_t - L2CAP_PEER_CFG_OK, L2CAP_PEER_CFG_UNACCEPTABLE,
2227 *                          or L2CAP_PEER_CFG_DISCONNECT.
2228 *
2229 ******************************************************************************/
2230uint8_t l2c_fcr_process_peer_cfg_req(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) {
2231  assert(p_ccb != NULL);
2232  assert(p_cfg != NULL);
2233
2234  uint16_t max_retrans_size;
2235  uint8_t fcr_ok = L2CAP_PEER_CFG_OK;
2236
2237  p_ccb->p_lcb->w4_info_rsp =
2238      false; /* Handles T61x SonyEricsson Bug in Info Request */
2239
2240  L2CAP_TRACE_EVENT(
2241      "l2c_fcr_process_peer_cfg_req() CFG fcr_present:%d fcr.mode:%d CCB FCR "
2242      "mode:%d preferred: %u allowed:%u",
2243      p_cfg->fcr_present, p_cfg->fcr.mode, p_ccb->our_cfg.fcr.mode,
2244      p_ccb->ertm_info.preferred_mode, p_ccb->ertm_info.allowed_modes);
2245
2246  /* If Peer wants basic, we are done (accept it or disconnect) */
2247  if (p_cfg->fcr.mode == L2CAP_FCR_BASIC_MODE) {
2248    /* If we do not allow basic, disconnect */
2249    if (!(p_ccb->ertm_info.allowed_modes & L2CAP_FCR_CHAN_OPT_BASIC))
2250      fcr_ok = L2CAP_PEER_CFG_DISCONNECT;
2251  }
2252
2253  /* Need to negotiate if our modes are not the same */
2254  else if (p_cfg->fcr.mode != p_ccb->ertm_info.preferred_mode) {
2255    /* If peer wants a mode that we don't support then retry our mode (ex.
2256    *rtx/flc), OR
2257    ** If we want ERTM and they wanted streaming retry our mode.
2258    ** Note: If we have already determined they support our mode previously
2259    **       from their EXF mask.
2260    */
2261    if ((((1 << p_cfg->fcr.mode) & L2CAP_FCR_CHAN_OPT_ALL_MASK) == 0) ||
2262        (p_ccb->ertm_info.preferred_mode == L2CAP_FCR_ERTM_MODE)) {
2263      p_cfg->fcr.mode = p_ccb->our_cfg.fcr.mode;
2264      p_cfg->fcr.tx_win_sz = p_ccb->our_cfg.fcr.tx_win_sz;
2265      p_cfg->fcr.max_transmit = p_ccb->our_cfg.fcr.max_transmit;
2266      fcr_ok = L2CAP_PEER_CFG_UNACCEPTABLE;
2267    }
2268
2269    /* If we wanted basic, then try to renegotiate it */
2270    else if (p_ccb->ertm_info.preferred_mode == L2CAP_FCR_BASIC_MODE) {
2271      p_cfg->fcr.mode = L2CAP_FCR_BASIC_MODE;
2272      p_cfg->fcr.max_transmit = p_cfg->fcr.tx_win_sz = 0;
2273      p_cfg->fcr.rtrans_tout = p_cfg->fcr.mon_tout = p_cfg->fcr.mps = 0;
2274      p_ccb->our_cfg.fcr.rtrans_tout = p_ccb->our_cfg.fcr.mon_tout =
2275          p_ccb->our_cfg.fcr.mps = 0;
2276      fcr_ok = L2CAP_PEER_CFG_UNACCEPTABLE;
2277    }
2278
2279    /* Only other valid case is if they want ERTM and we wanted STM which should
2280       be
2281       accepted if we support it; otherwise the channel should be disconnected
2282       */
2283    else if ((p_cfg->fcr.mode != L2CAP_FCR_ERTM_MODE) ||
2284             !(p_ccb->ertm_info.allowed_modes & L2CAP_FCR_CHAN_OPT_ERTM)) {
2285      fcr_ok = L2CAP_PEER_CFG_DISCONNECT;
2286    }
2287  }
2288
2289  /* Configuration for FCR channels so make any adjustments and fwd to upper
2290   * layer */
2291  if (fcr_ok == L2CAP_PEER_CFG_OK) {
2292    /* by default don't need to send params in the response */
2293    p_ccb->out_cfg_fcr_present = false;
2294
2295    /* Make any needed adjustments for the response to the peer */
2296    if (p_cfg->fcr_present && p_cfg->fcr.mode != L2CAP_FCR_BASIC_MODE) {
2297      /* Peer desires to bypass FCS check, and streaming or ERTM mode */
2298      if (p_cfg->fcs_present) {
2299        p_ccb->peer_cfg.fcs = p_cfg->fcs;
2300        p_ccb->peer_cfg_bits |= L2CAP_CH_CFG_MASK_FCS;
2301        if (p_cfg->fcs == L2CAP_CFG_FCS_BYPASS)
2302          p_ccb->bypass_fcs |= L2CAP_CFG_FCS_PEER;
2303      }
2304
2305      max_retrans_size = p_ccb->ertm_info.fcr_tx_buf_size - sizeof(BT_HDR) -
2306                         L2CAP_MIN_OFFSET - L2CAP_SDU_LEN_OFFSET -
2307                         L2CAP_FCS_LEN;
2308
2309      /* Ensure the MPS is not bigger than the MTU */
2310      if ((p_cfg->fcr.mps == 0) || (p_cfg->fcr.mps > p_ccb->peer_cfg.mtu)) {
2311        p_cfg->fcr.mps = p_ccb->peer_cfg.mtu;
2312        p_ccb->out_cfg_fcr_present = true;
2313      }
2314
2315      /* Ensure the MPS is not bigger than our retransmission buffer */
2316      if (p_cfg->fcr.mps > max_retrans_size) {
2317        L2CAP_TRACE_DEBUG("CFG: Overriding MPS to %d (orig %d)",
2318                          max_retrans_size, p_cfg->fcr.mps);
2319
2320        p_cfg->fcr.mps = max_retrans_size;
2321        p_ccb->out_cfg_fcr_present = true;
2322      }
2323
2324      if (p_cfg->fcr.mode == L2CAP_FCR_ERTM_MODE ||
2325          p_cfg->fcr.mode == L2CAP_FCR_STREAM_MODE) {
2326        /* Always respond with FCR ERTM parameters */
2327        p_ccb->out_cfg_fcr_present = true;
2328      }
2329    }
2330
2331    /* Everything ok, so save the peer's adjusted fcr options */
2332    p_ccb->peer_cfg.fcr = p_cfg->fcr;
2333
2334    if (p_cfg->fcr_present) p_ccb->peer_cfg_bits |= L2CAP_CH_CFG_MASK_FCR;
2335  } else if (fcr_ok == L2CAP_PEER_CFG_UNACCEPTABLE) {
2336    /* Allow peer only one retry for mode */
2337    if (p_ccb->peer_cfg_already_rejected)
2338      fcr_ok = L2CAP_PEER_CFG_DISCONNECT;
2339    else
2340      p_ccb->peer_cfg_already_rejected = true;
2341  }
2342
2343  return (fcr_ok);
2344}
2345
2346#if (L2CAP_ERTM_STATS == TRUE)
2347/*******************************************************************************
2348 *
2349 * Function         l2c_fcr_collect_ack_delay
2350 *
2351 * Description      collect throughput, delay, queue size of waiting ack
2352 *
2353 * Parameters
2354 *                  tL2C_CCB
2355 *
2356 * Returns          void
2357 *
2358 ******************************************************************************/
2359static void l2c_fcr_collect_ack_delay(tL2C_CCB* p_ccb, uint8_t num_bufs_acked) {
2360  uint32_t index;
2361  BT_HDR* p_buf;
2362  uint8_t* p;
2363  uint32_t timestamp, delay;
2364  uint8_t xx;
2365  uint8_t str[120];
2366
2367  index = p_ccb->fcrb.ack_delay_avg_index;
2368
2369  /* update sum, max and min of waiting for ack queue size */
2370  p_ccb->fcrb.ack_q_count_avg[index] +=
2371      fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q);
2372
2373  if (fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q) >
2374      p_ccb->fcrb.ack_q_count_max[index])
2375    p_ccb->fcrb.ack_q_count_max[index] =
2376        fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q);
2377
2378  if (fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q) <
2379      p_ccb->fcrb.ack_q_count_min[index])
2380    p_ccb->fcrb.ack_q_count_min[index] =
2381        fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q);
2382
2383  /* update sum, max and min of round trip delay of acking */
2384  list_t* list = NULL;
2385  if (!fixed_queue_is_empty(p_ccb->fcrb.waiting_for_ack_q))
2386    list = fixed_queue_get_list(p_ccb->fcrb.waiting_for_ack_q);
2387  if (list != NULL) {
2388    for (const list_node_t *node = list_begin(list), xx = 0;
2389         (node != list_end(list)) && (xx < num_bufs_acked);
2390         node = list_next(node), xx++) {
2391      p_buf = list_node(node);
2392      /* adding up length of acked I-frames to get throughput */
2393      p_ccb->fcrb.throughput[index] += p_buf->len - 8;
2394
2395      if (xx == num_bufs_acked - 1) {
2396        /* get timestamp from tx I-frame that receiver is acking */
2397        p = ((uint8_t*)(p_buf + 1)) + p_buf->offset + p_buf->len;
2398        if (p_ccb->bypass_fcs != L2CAP_BYPASS_FCS) {
2399          p += L2CAP_FCS_LEN;
2400        }
2401
2402        STREAM_TO_UINT32(timestamp, p);
2403        delay = time_get_os_boottime_ms() - timestamp;
2404
2405        p_ccb->fcrb.ack_delay_avg[index] += delay;
2406        if (delay > p_ccb->fcrb.ack_delay_max[index])
2407          p_ccb->fcrb.ack_delay_max[index] = delay;
2408        if (delay < p_ccb->fcrb.ack_delay_min[index])
2409          p_ccb->fcrb.ack_delay_min[index] = delay;
2410      }
2411    }
2412  }
2413
2414  p_ccb->fcrb.ack_delay_avg_count++;
2415
2416  /* calculate average and initialize next avg, min and max */
2417  if (p_ccb->fcrb.ack_delay_avg_count > L2CAP_ERTM_STATS_AVG_NUM_SAMPLES) {
2418    p_ccb->fcrb.ack_delay_avg_count = 0;
2419
2420    p_ccb->fcrb.ack_q_count_avg[index] /= L2CAP_ERTM_STATS_AVG_NUM_SAMPLES;
2421    p_ccb->fcrb.ack_delay_avg[index] /= L2CAP_ERTM_STATS_AVG_NUM_SAMPLES;
2422
2423    /* calculate throughput */
2424    timestamp = time_get_os_boottime_ms();
2425    if (timestamp - p_ccb->fcrb.throughput_start > 0)
2426      p_ccb->fcrb.throughput[index] /=
2427          (timestamp - p_ccb->fcrb.throughput_start);
2428
2429    p_ccb->fcrb.throughput_start = timestamp;
2430
2431    snprintf(
2432        str, sizeof(str),
2433        "[%02u] throughput: %5u, ack_delay avg:%3u, min:%3u, max:%3u, "
2434        "ack_q_count avg:%3u, min:%3u, max:%3u",
2435        index, p_ccb->fcrb.throughput[index], p_ccb->fcrb.ack_delay_avg[index],
2436        p_ccb->fcrb.ack_delay_min[index], p_ccb->fcrb.ack_delay_max[index],
2437        p_ccb->fcrb.ack_q_count_avg[index], p_ccb->fcrb.ack_q_count_min[index],
2438        p_ccb->fcrb.ack_q_count_max[index]);
2439
2440    BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI,
2441             TRACE_TYPE_GENERIC, "%s", str);
2442
2443    index = (index + 1) % L2CAP_ERTM_STATS_NUM_AVG;
2444    p_ccb->fcrb.ack_delay_avg_index = index;
2445
2446    p_ccb->fcrb.ack_q_count_max[index] = 0;
2447    p_ccb->fcrb.ack_q_count_min[index] = 0xFFFFFFFF;
2448    p_ccb->fcrb.ack_q_count_avg[index] = 0;
2449
2450    p_ccb->fcrb.ack_delay_max[index] = 0;
2451    p_ccb->fcrb.ack_delay_min[index] = 0xFFFFFFFF;
2452    p_ccb->fcrb.ack_delay_avg[index] = 0;
2453
2454    p_ccb->fcrb.throughput[index] = 0;
2455  }
2456}
2457#endif
2458