• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /******************************************************************************
2  *
3  *  Copyright 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 <base/logging.h>
27 #include <log/log.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 
32 #include "bt_common.h"
33 #include "bt_types.h"
34 #include "btm_api.h"
35 #include "btm_int.h"
36 #include "btu.h"
37 #include "common/time_util.h"
38 #include "hcimsgs.h"
39 #include "l2c_api.h"
40 #include "l2c_int.h"
41 #include "l2cdefs.h"
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 */
48 static const uint16_t OBX_BUF_MIN_OFFSET = 4;
49 
50 static const char* SAR_types[] = {"Unsegmented", "Start", "End",
51                                   "Continuation"};
52 static const char* SUP_types[] = {"RR", "REJ", "RNR", "SREJ"};
53 
54 /* Look-up table for the CRC calculation */
55 static 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 */
90 static bool process_reqseq(tL2C_CCB* p_ccb, uint16_t ctrl_word);
91 static void process_s_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, uint16_t ctrl_word);
92 static void process_i_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, uint16_t ctrl_word,
93                             bool delay_ack);
94 static bool retransmit_i_frames(tL2C_CCB* p_ccb, uint8_t tx_seq);
95 static void prepare_I_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf,
96                             bool is_retransmission);
97 static void process_stream_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf);
98 static bool do_sar_reassembly(tL2C_CCB* p_ccb, BT_HDR* p_buf,
99                               uint16_t ctrl_word);
100 
101 #if (L2CAP_ERTM_STATS == TRUE)
102 static 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  ******************************************************************************/
l2c_fcr_updcrc(unsigned short icrc,unsigned char * icp,int icnt)114 static 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  ******************************************************************************/
l2c_fcr_tx_get_fcs(BT_HDR * p_buf)136 static 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  ******************************************************************************/
l2c_fcr_rx_get_fcs(BT_HDR * p_buf)151 static 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  ******************************************************************************/
l2c_fcr_start_timer(tL2C_CCB * p_ccb)170 void l2c_fcr_start_timer(tL2C_CCB* p_ccb) {
171   CHECK(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_mloop(p_ccb->fcrb.mon_retrans_timer, tout,
184                        l2c_ccb_timer_timeout, p_ccb);
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  ******************************************************************************/
l2c_fcr_stop_timer(tL2C_CCB * p_ccb)197 void l2c_fcr_stop_timer(tL2C_CCB* p_ccb) {
198   CHECK(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  ******************************************************************************/
l2c_fcr_cleanup(tL2C_CCB * p_ccb)212 void l2c_fcr_cleanup(tL2C_CCB* p_ccb) {
213   CHECK(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     uint64_t dur = bluetooth::common::time_get_os_boottime_ms() -
236                    p_ccb->fcrb.connect_tick_count;
237     size_t p_str_size = 120;
238     char* p_str = (char*)osi_malloc(p_str_size);
239     uint16_t i;
240     uint32_t throughput_avg, ack_delay_avg, ack_q_count_avg;
241 
242     BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI,
243              TRACE_TYPE_GENERIC,
244              "---  L2CAP ERTM  Stats for CID: 0x%04x   Duration: %08ums",
245              p_ccb->local_cid, dur);
246     BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI,
247              TRACE_TYPE_GENERIC,
248              "Retransmissions:%08u Times Flow Controlled:%08u Retrans "
249              "Touts:%08u Ack Touts:%08u",
250              p_ccb->fcrb.pkts_retransmitted, p_ccb->fcrb.xmit_window_closed,
251              p_ccb->fcrb.retrans_touts, p_ccb->fcrb.xmit_ack_touts);
252     BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI,
253              TRACE_TYPE_GENERIC,
254              "Times there is less than 2 packets in controller when flow "
255              "controlled:%08u",
256              p_ccb->fcrb.controller_idle);
257     BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI,
258              TRACE_TYPE_GENERIC,
259              "max_held_acks:%08u, in_cfg.fcr.tx_win_sz:%08u",
260              p_ccb->fcrb.max_held_acks, p_ccb->peer_cfg.fcr.tx_win_sz);
261 
262     snprintf(
263         p_str, p_str_size,
264         "Sent Pkts:%08u Bytes:%10u(%06u/sec) RR:%08u REJ:%08u RNR:%08u "
265         "SREJ:%08u",
266         p_ccb->fcrb.ertm_pkt_counts[0], p_ccb->fcrb.ertm_byte_counts[0],
267         (dur >= 10 ? (p_ccb->fcrb.ertm_byte_counts[0] * 100) / (dur / 10) : 0),
268         p_ccb->fcrb.s_frames_sent[0], p_ccb->fcrb.s_frames_sent[1],
269         p_ccb->fcrb.s_frames_sent[2], p_ccb->fcrb.s_frames_sent[3]);
270 
271     BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI,
272              TRACE_TYPE_GENERIC, "%s", p_str);
273 
274     snprintf(
275         p_str, p_str_size,
276         "Rcvd Pkts:%08u Bytes:%10u(%06u/sec) RR:%08u REJ:%08u RNR:%08u "
277         "SREJ:%08u",
278         p_ccb->fcrb.ertm_pkt_counts[1], p_ccb->fcrb.ertm_byte_counts[1],
279         (dur >= 10 ? (p_ccb->fcrb.ertm_byte_counts[1] * 100) / (dur / 10) : 0),
280         p_ccb->fcrb.s_frames_rcvd[0], p_ccb->fcrb.s_frames_rcvd[1],
281         p_ccb->fcrb.s_frames_rcvd[2], p_ccb->fcrb.s_frames_rcvd[3]);
282 
283     BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI,
284              TRACE_TYPE_GENERIC, "%s", p_str);
285 
286     throughput_avg = 0;
287     ack_delay_avg = 0;
288     ack_q_count_avg = 0;
289 
290     for (i = 0; i < L2CAP_ERTM_STATS_NUM_AVG; i++) {
291       if (i == p_ccb->fcrb.ack_delay_avg_index) {
292         BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI,
293                  TRACE_TYPE_GENERIC, "[%02u] collecting data ...", i);
294         continue;
295       }
296 
297       snprintf(p_str, p_str_size,
298                "[%02u] throughput: %5u, ack_delay avg:%3u, min:%3u, max:%3u, "
299                "ack_q_count avg:%3u, min:%3u, max:%3u",
300                i, p_ccb->fcrb.throughput[i], p_ccb->fcrb.ack_delay_avg[i],
301                p_ccb->fcrb.ack_delay_min[i], p_ccb->fcrb.ack_delay_max[i],
302                p_ccb->fcrb.ack_q_count_avg[i], p_ccb->fcrb.ack_q_count_min[i],
303                p_ccb->fcrb.ack_q_count_max[i]);
304 
305       BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI,
306                TRACE_TYPE_GENERIC, "%s", p_str);
307 
308       throughput_avg += p_ccb->fcrb.throughput[i];
309       ack_delay_avg += p_ccb->fcrb.ack_delay_avg[i];
310       ack_q_count_avg += p_ccb->fcrb.ack_q_count_avg[i];
311     }
312 
313     throughput_avg /= (L2CAP_ERTM_STATS_NUM_AVG - 1);
314     ack_delay_avg /= (L2CAP_ERTM_STATS_NUM_AVG - 1);
315     ack_q_count_avg /= (L2CAP_ERTM_STATS_NUM_AVG - 1);
316 
317     BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI,
318              TRACE_TYPE_GENERIC,
319              "throughput_avg: %8u (kbytes/sec), ack_delay_avg: %8u ms, "
320              "ack_q_count_avg: %8u",
321              throughput_avg, ack_delay_avg, ack_q_count_avg);
322 
323     osi_free(p_str);
324 
325     BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI,
326              TRACE_TYPE_GENERIC, "---");
327   }
328 #endif
329 
330   memset(p_fcrb, 0, sizeof(tL2C_FCRB));
331 }
332 
333 /*******************************************************************************
334  *
335  * Function         l2c_fcr_clone_buf
336  *
337  * Description      This function allocates and copies requested part of a
338  *                  buffer at a new-offset.
339  *
340  * Returns          pointer to new buffer
341  *
342  ******************************************************************************/
l2c_fcr_clone_buf(BT_HDR * p_buf,uint16_t new_offset,uint16_t no_of_bytes)343 BT_HDR* l2c_fcr_clone_buf(BT_HDR* p_buf, uint16_t new_offset,
344                           uint16_t no_of_bytes) {
345   CHECK(p_buf != NULL);
346   /*
347    * NOTE: We allocate extra L2CAP_FCS_LEN octets, in case we need to put
348    * the FCS (Frame Check Sequence) at the end of the buffer.
349    */
350   uint16_t buf_size = no_of_bytes + sizeof(BT_HDR) + new_offset + L2CAP_FCS_LEN;
351 #if (L2CAP_ERTM_STATS == TRUE)
352   /*
353    * NOTE: If L2CAP_ERTM_STATS is enabled, we need 4 extra octets at the
354    * end for a timestamp at the end of an I-frame.
355    */
356   buf_size += sizeof(uint32_t);
357 #endif
358   BT_HDR* p_buf2 = (BT_HDR*)osi_malloc(buf_size);
359 
360   p_buf2->offset = new_offset;
361   p_buf2->len = no_of_bytes;
362   memcpy(((uint8_t*)(p_buf2 + 1)) + p_buf2->offset,
363          ((uint8_t*)(p_buf + 1)) + p_buf->offset, no_of_bytes);
364 
365   return (p_buf2);
366 }
367 
368 /*******************************************************************************
369  *
370  * Function         l2c_fcr_is_flow_controlled
371  *
372  * Description      This function checks if the CCB is flow controlled by peer.
373  *
374  * Returns          The control word
375  *
376  ******************************************************************************/
l2c_fcr_is_flow_controlled(tL2C_CCB * p_ccb)377 bool l2c_fcr_is_flow_controlled(tL2C_CCB* p_ccb) {
378   CHECK(p_ccb != NULL);
379   if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) {
380     /* Check if remote side flowed us off or the transmit window is full */
381     if ((p_ccb->fcrb.remote_busy) ||
382         (fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q) >=
383          p_ccb->peer_cfg.fcr.tx_win_sz)) {
384 #if (L2CAP_ERTM_STATS == TRUE)
385       if (!fixed_queue_is_empty(p_ccb->xmit_hold_q)) {
386         p_ccb->fcrb.xmit_window_closed++;
387 
388         if ((p_ccb->p_lcb->sent_not_acked < 2) &&
389             (l2cb.controller_xmit_window > 0))
390           p_ccb->fcrb.controller_idle++;
391       }
392 #endif
393       return (true);
394     }
395   }
396   return (false);
397 }
398 
399 /*******************************************************************************
400  *
401  * Function         prepare_I_frame
402  *
403  * Description      This function sets the FCR variables in an I-frame that is
404  *                  about to be sent to HCI for transmission. This may be the
405  *                  first time the I-frame is sent, or a retransmission
406  *
407  * Returns          -
408  *
409  ******************************************************************************/
prepare_I_frame(tL2C_CCB * p_ccb,BT_HDR * p_buf,bool is_retransmission)410 static void prepare_I_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf,
411                             bool is_retransmission) {
412   CHECK(p_ccb != NULL);
413   CHECK(p_buf != NULL);
414   tL2C_FCRB* p_fcrb = &p_ccb->fcrb;
415   uint8_t* p;
416   uint16_t fcs;
417   uint16_t ctrl_word;
418   bool set_f_bit = p_fcrb->send_f_rsp;
419 
420   p_fcrb->send_f_rsp = false;
421 
422   if (is_retransmission) {
423     /* Get the old control word and clear out the old req_seq and F bits */
424     p = ((uint8_t*)(p_buf + 1)) + p_buf->offset + L2CAP_PKT_OVERHEAD;
425 
426     STREAM_TO_UINT16(ctrl_word, p);
427 
428     ctrl_word &= ~(L2CAP_FCR_REQ_SEQ_BITS + L2CAP_FCR_F_BIT);
429   } else {
430     ctrl_word = p_buf->layer_specific & L2CAP_FCR_SEG_BITS; /* SAR bits */
431     ctrl_word |=
432         (p_fcrb->next_tx_seq << L2CAP_FCR_TX_SEQ_BITS_SHIFT); /* Tx Seq */
433 
434     p_fcrb->next_tx_seq = (p_fcrb->next_tx_seq + 1) & L2CAP_FCR_SEQ_MODULO;
435   }
436 
437   /* Set the F-bit and reqseq only if using re-transmission mode */
438   if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) {
439     if (set_f_bit) ctrl_word |= L2CAP_FCR_F_BIT;
440 
441     ctrl_word |= (p_fcrb->next_seq_expected) << L2CAP_FCR_REQ_SEQ_BITS_SHIFT;
442 
443     p_fcrb->last_ack_sent = p_ccb->fcrb.next_seq_expected;
444 
445     alarm_cancel(p_ccb->fcrb.ack_timer);
446   }
447 
448   /* Set the control word */
449   p = ((uint8_t*)(p_buf + 1)) + p_buf->offset + L2CAP_PKT_OVERHEAD;
450 
451   UINT16_TO_STREAM(p, ctrl_word);
452 
453   /* Compute the FCS and add to the end of the buffer if not bypassed */
454   if (p_ccb->bypass_fcs != L2CAP_BYPASS_FCS) {
455     /* length field in l2cap header has to include FCS length */
456     p = ((uint8_t*)(p_buf + 1)) + p_buf->offset;
457     UINT16_TO_STREAM(p, p_buf->len + L2CAP_FCS_LEN - L2CAP_PKT_OVERHEAD);
458 
459     /* Calculate the FCS */
460     fcs = l2c_fcr_tx_get_fcs(p_buf);
461 
462     /* Point to the end of the buffer and put the FCS there */
463     /*
464      * NOTE: Here we assume the allocated buffer is large enough
465      * to include extra L2CAP_FCS_LEN octets at the end.
466      */
467     p = ((uint8_t*)(p_buf + 1)) + p_buf->offset + p_buf->len;
468 
469     UINT16_TO_STREAM(p, fcs);
470 
471     p_buf->len += L2CAP_FCS_LEN;
472   }
473 
474   if (is_retransmission) {
475     L2CAP_TRACE_EVENT(
476         "L2CAP eRTM ReTx I-frame  CID: 0x%04x  Len: %u  SAR: %s  TxSeq: %u  "
477         "ReqSeq: %u  F: %u",
478         p_ccb->local_cid, p_buf->len,
479         SAR_types[(ctrl_word & L2CAP_FCR_SAR_BITS) >> L2CAP_FCR_SAR_BITS_SHIFT],
480         (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT,
481         (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
482         (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
483   } else {
484     L2CAP_TRACE_EVENT(
485         "L2CAP eRTM Tx I-frame CID: 0x%04x  Len: %u  SAR: %-12s  TxSeq: %u  "
486         "ReqSeq: %u  F: %u",
487         p_ccb->local_cid, p_buf->len,
488         SAR_types[(ctrl_word & L2CAP_FCR_SAR_BITS) >> L2CAP_FCR_SAR_BITS_SHIFT],
489         (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT,
490         (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
491         (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
492   }
493 
494   /* Start the retransmission timer if not already running */
495   if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE)
496     l2c_fcr_start_timer(p_ccb);
497 }
498 
499 /*******************************************************************************
500  *
501  * Function         l2c_fcr_send_S_frame
502  *
503  * Description      This function formats and sends an S-frame for transmission.
504  *
505  * Returns          -
506  *
507  ******************************************************************************/
l2c_fcr_send_S_frame(tL2C_CCB * p_ccb,uint16_t function_code,uint16_t pf_bit)508 void l2c_fcr_send_S_frame(tL2C_CCB* p_ccb, uint16_t function_code,
509                           uint16_t pf_bit) {
510   CHECK(p_ccb != NULL);
511   uint8_t* p;
512   uint16_t ctrl_word;
513   uint16_t fcs;
514 
515   if ((!p_ccb->in_use) || (p_ccb->chnl_state != CST_OPEN)) return;
516 
517 #if (L2CAP_ERTM_STATS == TRUE)
518   p_ccb->fcrb.s_frames_sent[function_code]++;
519 #endif
520 
521   if (pf_bit == L2CAP_FCR_P_BIT) {
522     p_ccb->fcrb.wait_ack = true;
523 
524     l2c_fcr_stop_timer(p_ccb); /* Restart the monitor timer */
525     l2c_fcr_start_timer(p_ccb);
526   }
527 
528   /* Create the control word to use */
529   ctrl_word = (function_code << L2CAP_FCR_SUP_SHIFT) | L2CAP_FCR_S_FRAME_BIT;
530   ctrl_word |= (p_ccb->fcrb.next_seq_expected << L2CAP_FCR_REQ_SEQ_BITS_SHIFT);
531   ctrl_word |= pf_bit;
532 
533   BT_HDR* p_buf = (BT_HDR*)osi_malloc(L2CAP_CMD_BUF_SIZE);
534   p_buf->offset = HCI_DATA_PREAMBLE_SIZE;
535   p_buf->len = L2CAP_PKT_OVERHEAD + L2CAP_FCR_OVERHEAD;
536 
537   /* Set the pointer to the beginning of the data */
538   p = (uint8_t*)(p_buf + 1) + p_buf->offset;
539 
540   /* Put in the L2CAP header */
541   UINT16_TO_STREAM(p, L2CAP_FCR_OVERHEAD + L2CAP_FCS_LEN);
542   UINT16_TO_STREAM(p, p_ccb->remote_cid);
543   UINT16_TO_STREAM(p, ctrl_word);
544 
545   /* Compute the FCS and add to the end of the buffer if not bypassed */
546   if (p_ccb->bypass_fcs != L2CAP_BYPASS_FCS) {
547     fcs = l2c_fcr_tx_get_fcs(p_buf);
548 
549     UINT16_TO_STREAM(p, fcs);
550     p_buf->len += L2CAP_FCS_LEN;
551   } else {
552     /* rewrite the length without FCS length */
553     p -= 6;
554     UINT16_TO_STREAM(p, L2CAP_FCR_OVERHEAD);
555   }
556 
557   /* Now, the HCI transport header */
558   p_buf->layer_specific = L2CAP_NON_FLUSHABLE_PKT;
559   l2cu_set_acl_hci_header(p_buf, p_ccb);
560 
561   if ((((ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT) == 1) ||
562       (((ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT) == 3)) {
563     L2CAP_TRACE_WARNING(
564         "L2CAP eRTM Tx S-frame  CID: 0x%04x  ctrlword: 0x%04x  Type: %s  "
565         "ReqSeq: %u  P: %u  F: %u",
566         p_ccb->local_cid, ctrl_word,
567         SUP_types[(ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT],
568         (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
569         (ctrl_word & L2CAP_FCR_P_BIT) >> L2CAP_FCR_P_BIT_SHIFT,
570         (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
571     L2CAP_TRACE_WARNING("                  Buf Len: %u", p_buf->len);
572   } else {
573     L2CAP_TRACE_EVENT(
574         "L2CAP eRTM Tx S-frame  CID: 0x%04x  ctrlword: 0x%04x  Type: %s  "
575         "ReqSeq: %u  P: %u  F: %u",
576         p_ccb->local_cid, ctrl_word,
577         SUP_types[(ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT],
578         (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
579         (ctrl_word & L2CAP_FCR_P_BIT) >> L2CAP_FCR_P_BIT_SHIFT,
580         (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
581     L2CAP_TRACE_EVENT("                  Buf Len: %u", p_buf->len);
582   }
583 
584   l2c_link_check_send_pkts(p_ccb->p_lcb, NULL, p_buf);
585 
586   p_ccb->fcrb.last_ack_sent = p_ccb->fcrb.next_seq_expected;
587 
588   alarm_cancel(p_ccb->fcrb.ack_timer);
589 }
590 
591 /*******************************************************************************
592  *
593  * Function         l2c_fcr_proc_pdu
594  *
595  * Description      This function is the entry point for processing of a
596  *                  received PDU when in flow control and/or retransmission
597  *                  modes.
598  *
599  * Returns          -
600  *
601  ******************************************************************************/
l2c_fcr_proc_pdu(tL2C_CCB * p_ccb,BT_HDR * p_buf)602 void l2c_fcr_proc_pdu(tL2C_CCB* p_ccb, BT_HDR* p_buf) {
603   CHECK(p_ccb != NULL);
604   CHECK(p_buf != NULL);
605   uint8_t* p;
606   uint16_t fcs;
607   uint16_t min_pdu_len;
608   uint16_t ctrl_word;
609 
610   /* Check the length */
611   min_pdu_len = (p_ccb->bypass_fcs == L2CAP_BYPASS_FCS)
612                     ? (uint16_t)L2CAP_FCR_OVERHEAD
613                     : (uint16_t)(L2CAP_FCS_LEN + L2CAP_FCR_OVERHEAD);
614 
615   if (p_buf->len < min_pdu_len) {
616     L2CAP_TRACE_WARNING("Rx L2CAP PDU: CID: 0x%04x  Len too short: %u",
617                         p_ccb->local_cid, p_buf->len);
618     osi_free(p_buf);
619     return;
620   }
621 
622   if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_STREAM_MODE) {
623     process_stream_frame(p_ccb, p_buf);
624     return;
625   }
626 
627   /* Get the control word */
628   p = ((uint8_t*)(p_buf + 1)) + p_buf->offset;
629   STREAM_TO_UINT16(ctrl_word, p);
630 
631   if (ctrl_word & L2CAP_FCR_S_FRAME_BIT) {
632     if ((((ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT) == 1) ||
633         (((ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT) == 3)) {
634       /* REJ or SREJ */
635       L2CAP_TRACE_WARNING(
636           "L2CAP eRTM Rx S-frame: cid: 0x%04x  Len: %u  Type: %s  ReqSeq: %u  "
637           "P: %u  F: %u",
638           p_ccb->local_cid, p_buf->len,
639           SUP_types[(ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT],
640           (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
641           (ctrl_word & L2CAP_FCR_P_BIT) >> L2CAP_FCR_P_BIT_SHIFT,
642           (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
643     } else {
644       L2CAP_TRACE_EVENT(
645           "L2CAP eRTM Rx S-frame: cid: 0x%04x  Len: %u  Type: %s  ReqSeq: %u  "
646           "P: %u  F: %u",
647           p_ccb->local_cid, p_buf->len,
648           SUP_types[(ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT],
649           (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
650           (ctrl_word & L2CAP_FCR_P_BIT) >> L2CAP_FCR_P_BIT_SHIFT,
651           (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
652     }
653   } else {
654     L2CAP_TRACE_EVENT(
655         "L2CAP eRTM Rx I-frame: cid: 0x%04x  Len: %u  SAR: %-12s  TxSeq: %u  "
656         "ReqSeq: %u  F: %u",
657         p_ccb->local_cid, p_buf->len,
658         SAR_types[(ctrl_word & L2CAP_FCR_SAR_BITS) >> L2CAP_FCR_SAR_BITS_SHIFT],
659         (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT,
660         (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
661         (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
662   }
663 
664   L2CAP_TRACE_EVENT(
665       "      eRTM Rx Nxt_tx_seq %u, Lst_rx_ack %u, Nxt_seq_exp %u, Lst_ack_snt "
666       "%u, wt_q.cnt %u, tries %u",
667       p_ccb->fcrb.next_tx_seq, p_ccb->fcrb.last_rx_ack,
668       p_ccb->fcrb.next_seq_expected, p_ccb->fcrb.last_ack_sent,
669       fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q), p_ccb->fcrb.num_tries);
670 
671   /* Verify FCS if using */
672   if (p_ccb->bypass_fcs != L2CAP_BYPASS_FCS) {
673     p = ((uint8_t*)(p_buf + 1)) + p_buf->offset + p_buf->len - L2CAP_FCS_LEN;
674 
675     /* Extract and drop the FCS from the packet */
676     STREAM_TO_UINT16(fcs, p);
677     p_buf->len -= L2CAP_FCS_LEN;
678 
679     if (l2c_fcr_rx_get_fcs(p_buf) != fcs) {
680       L2CAP_TRACE_WARNING("Rx L2CAP PDU: CID: 0x%04x  BAD FCS",
681                           p_ccb->local_cid);
682       osi_free(p_buf);
683       return;
684     }
685   }
686 
687   /* Get the control word */
688   p = ((uint8_t*)(p_buf + 1)) + p_buf->offset;
689 
690   STREAM_TO_UINT16(ctrl_word, p);
691 
692   p_buf->len -= L2CAP_FCR_OVERHEAD;
693   p_buf->offset += L2CAP_FCR_OVERHEAD;
694 
695   /* If we had a poll bit outstanding, check if we got a final response */
696   if (p_ccb->fcrb.wait_ack) {
697     /* If final bit not set, ignore the frame unless it is a polled S-frame */
698     if (!(ctrl_word & L2CAP_FCR_F_BIT)) {
699       if ((ctrl_word & L2CAP_FCR_P_BIT) &&
700           (ctrl_word & L2CAP_FCR_S_FRAME_BIT)) {
701         if (p_ccb->fcrb.srej_sent)
702           l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_SREJ, L2CAP_FCR_F_BIT);
703         else if (p_ccb->fcrb.local_busy)
704           l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RNR, L2CAP_FCR_F_BIT);
705         else
706           l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RR, L2CAP_FCR_F_BIT);
707 
708         /* Got a poll while in wait_ack state, so re-start our timer with
709          * 1-second */
710         /* This is a small optimization... the monitor timer is 12 secs, but we
711          * saw */
712         /* that if the other side sends us a poll when we are waiting for a
713          * final,  */
714         /* then it speeds up recovery significantly if we poll him back soon
715          * after his poll. */
716         alarm_set_on_mloop(p_ccb->fcrb.mon_retrans_timer, BT_1SEC_TIMEOUT_MS,
717                            l2c_ccb_timer_timeout, p_ccb);
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) && (!l2c_fcr_is_flow_controlled(p_ccb))) {
809     l2c_link_check_send_pkts(p_ccb->p_lcb, NULL, NULL);
810   }
811 }
812 
813 /*******************************************************************************
814  *
815  * Function         l2c_lcc_proc_pdu
816  *
817  * Description      This function is the entry point for processing of a
818  *                  received PDU when in LE Coc flow control modes.
819  *
820  * Returns          -
821  *
822  ******************************************************************************/
l2c_lcc_proc_pdu(tL2C_CCB * p_ccb,BT_HDR * p_buf)823 void l2c_lcc_proc_pdu(tL2C_CCB* p_ccb, BT_HDR* p_buf) {
824   CHECK(p_ccb != NULL);
825   CHECK(p_buf != NULL);
826   uint8_t* p = (uint8_t*)(p_buf + 1) + p_buf->offset;
827   uint16_t sdu_length;
828   BT_HDR* p_data = NULL;
829 
830   /* Buffer length should not exceed local mps */
831   if (p_buf->len > p_ccb->local_conn_cfg.mps) {
832     /* Discard the buffer */
833     osi_free(p_buf);
834     return;
835   }
836 
837   if (p_ccb->is_first_seg) {
838     if (p_buf->len < sizeof(sdu_length)) {
839       L2CAP_TRACE_ERROR("%s: buffer length=%d too small. Need at least 2.",
840                         __func__, p_buf->len);
841       android_errorWriteWithInfoLog(0x534e4554, "120665616", -1, NULL, 0);
842       /* Discard the buffer */
843       osi_free(p_buf);
844       return;
845     }
846     STREAM_TO_UINT16(sdu_length, p);
847 
848     /* Check the SDU Length with local MTU size */
849     if (sdu_length > p_ccb->local_conn_cfg.mtu) {
850       /* Discard the buffer */
851       osi_free(p_buf);
852       return;
853     }
854 
855     p_buf->len -= sizeof(sdu_length);
856     p_buf->offset += sizeof(sdu_length);
857 
858     if (sdu_length < p_buf->len) {
859       L2CAP_TRACE_ERROR("%s: Invalid sdu_length: %d", __func__, sdu_length);
860       android_errorWriteWithInfoLog(0x534e4554, "112321180", -1, NULL, 0);
861       /* Discard the buffer */
862       osi_free(p_buf);
863       return;
864     }
865 
866     p_data = (BT_HDR*)osi_malloc(BT_HDR_SIZE + sdu_length);
867     if (p_data == NULL) {
868       osi_free(p_buf);
869       return;
870     }
871 
872     p_ccb->ble_sdu = p_data;
873     p_data->len = 0;
874     p_ccb->ble_sdu_length = sdu_length;
875     L2CAP_TRACE_DEBUG("%s SDU Length = %d", __func__, sdu_length);
876     p_data->offset = 0;
877 
878   } else {
879     p_data = p_ccb->ble_sdu;
880     if (p_buf->len > (p_ccb->ble_sdu_length - p_data->len)) {
881       L2CAP_TRACE_ERROR("%s: buffer length=%d too big. max=%d. Dropped",
882                         __func__, p_data->len,
883                         (p_ccb->ble_sdu_length - p_data->len));
884       android_errorWriteWithInfoLog(0x534e4554, "75298652", -1, NULL, 0);
885       osi_free(p_buf);
886 
887       /* Throw away all pending fragments and disconnects */
888       p_ccb->is_first_seg = true;
889       osi_free(p_ccb->ble_sdu);
890       p_ccb->ble_sdu = NULL;
891       p_ccb->ble_sdu_length = 0;
892       l2cu_disconnect_chnl(p_ccb);
893       return;
894     }
895   }
896 
897   memcpy((uint8_t*)(p_data + 1) + p_data->offset + p_data->len,
898          (uint8_t*)(p_buf + 1) + p_buf->offset, p_buf->len);
899   p_data->len += p_buf->len;
900   p = (uint8_t*)(p_data + 1) + p_data->offset;
901   if (p_data->len == p_ccb->ble_sdu_length) {
902     l2c_csm_execute(p_ccb, L2CEVT_L2CAP_DATA, p_data);
903     p_ccb->is_first_seg = true;
904     p_ccb->ble_sdu = NULL;
905     p_ccb->ble_sdu_length = 0;
906   } else if (p_data->len < p_ccb->ble_sdu_length) {
907     p_ccb->is_first_seg = false;
908   }
909 
910   osi_free(p_buf);
911   return;
912 }
913 
914 /*******************************************************************************
915  *
916  * Function         l2c_fcr_proc_tout
917  *
918  * Description      Handle a timeout. We should be in error recovery state.
919  *
920  * Returns          -
921  *
922  ******************************************************************************/
l2c_fcr_proc_tout(tL2C_CCB * p_ccb)923 void l2c_fcr_proc_tout(tL2C_CCB* p_ccb) {
924   CHECK(p_ccb != NULL);
925   L2CAP_TRACE_DEBUG(
926       "l2c_fcr_proc_tout:  CID: 0x%04x  num_tries: %u (max: %u)  wait_ack: %u  "
927       "ack_q_count: %u",
928       p_ccb->local_cid, p_ccb->fcrb.num_tries, p_ccb->peer_cfg.fcr.max_transmit,
929       p_ccb->fcrb.wait_ack, fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q));
930 
931 #if (L2CAP_ERTM_STATS == TRUE)
932   p_ccb->fcrb.retrans_touts++;
933 #endif
934 
935   if ((p_ccb->peer_cfg.fcr.max_transmit != 0) &&
936       (++p_ccb->fcrb.num_tries > p_ccb->peer_cfg.fcr.max_transmit)) {
937     l2cu_disconnect_chnl(p_ccb);
938   } else {
939     if (!p_ccb->fcrb.srej_sent && !p_ccb->fcrb.rej_sent) {
940       if (p_ccb->fcrb.local_busy)
941         l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RNR, L2CAP_FCR_P_BIT);
942       else
943         l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RR, L2CAP_FCR_P_BIT);
944     }
945   }
946 }
947 
948 /*******************************************************************************
949  *
950  * Function         l2c_fcr_proc_ack_tout
951  *
952  * Description      Send RR/RNR if we have not acked I frame
953  *
954  * Returns          -
955  *
956  ******************************************************************************/
l2c_fcr_proc_ack_tout(tL2C_CCB * p_ccb)957 void l2c_fcr_proc_ack_tout(tL2C_CCB* p_ccb) {
958   CHECK(p_ccb != NULL);
959   L2CAP_TRACE_DEBUG(
960       "l2c_fcr_proc_ack_tout:  CID: 0x%04x State: %u  Wack:%u  Rq:%d  Acked:%d",
961       p_ccb->local_cid, p_ccb->chnl_state, p_ccb->fcrb.wait_ack,
962       p_ccb->fcrb.next_seq_expected, p_ccb->fcrb.last_ack_sent);
963 
964   if ((p_ccb->chnl_state == CST_OPEN) && (!p_ccb->fcrb.wait_ack) &&
965       (p_ccb->fcrb.last_ack_sent != p_ccb->fcrb.next_seq_expected)) {
966 #if (L2CAP_ERTM_STATS == TRUE)
967     p_ccb->fcrb.xmit_ack_touts++;
968 #endif
969     if (p_ccb->fcrb.local_busy)
970       l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RNR, 0);
971     else
972       l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RR, 0);
973   }
974 }
975 
976 /*******************************************************************************
977  *
978  * Function         process_reqseq
979  *
980  * Description      Handle receive sequence number
981  *
982  * Returns          -
983  *
984  ******************************************************************************/
process_reqseq(tL2C_CCB * p_ccb,uint16_t ctrl_word)985 static bool process_reqseq(tL2C_CCB* p_ccb, uint16_t ctrl_word) {
986   CHECK(p_ccb != NULL);
987   tL2C_FCRB* p_fcrb = &p_ccb->fcrb;
988   uint8_t req_seq, num_bufs_acked, xx;
989   uint16_t ls;
990   uint16_t full_sdus_xmitted;
991 
992   /* Receive sequence number does not ack anything for SREJ with P-bit set to
993    * zero */
994   if ((ctrl_word & L2CAP_FCR_S_FRAME_BIT) &&
995       ((ctrl_word & L2CAP_FCR_SUP_BITS) ==
996        (L2CAP_FCR_SUP_SREJ << L2CAP_FCR_SUP_SHIFT)) &&
997       ((ctrl_word & L2CAP_FCR_P_BIT) == 0)) {
998     /* If anything still waiting for ack, restart the timer if it was stopped */
999     if (!fixed_queue_is_empty(p_fcrb->waiting_for_ack_q))
1000       l2c_fcr_start_timer(p_ccb);
1001 
1002     return (true);
1003   }
1004 
1005   /* Extract the receive sequence number from the control word */
1006   req_seq =
1007       (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT;
1008 
1009   num_bufs_acked = (req_seq - p_fcrb->last_rx_ack) & L2CAP_FCR_SEQ_MODULO;
1010 
1011   /* Verify the request sequence is in range before proceeding */
1012   if (num_bufs_acked > fixed_queue_length(p_fcrb->waiting_for_ack_q)) {
1013     /* The channel is closed if ReqSeq is not in range */
1014     L2CAP_TRACE_WARNING(
1015         "L2CAP eRTM Frame BAD Req_Seq - ctrl_word: 0x%04x  req_seq 0x%02x  "
1016         "last_rx_ack: 0x%02x  QCount: %u",
1017         ctrl_word, req_seq, p_fcrb->last_rx_ack,
1018         fixed_queue_length(p_fcrb->waiting_for_ack_q));
1019 
1020     l2cu_disconnect_chnl(p_ccb);
1021     return (false);
1022   }
1023 
1024   p_fcrb->last_rx_ack = req_seq;
1025 
1026   /* Now we can release all acknowledged frames, and restart the retransmission
1027    * timer if needed */
1028   if (num_bufs_acked != 0) {
1029     p_fcrb->num_tries = 0;
1030     full_sdus_xmitted = 0;
1031 
1032 #if (L2CAP_ERTM_STATS == TRUE)
1033     l2c_fcr_collect_ack_delay(p_ccb, num_bufs_acked);
1034 #endif
1035 
1036     for (xx = 0; xx < num_bufs_acked; xx++) {
1037       BT_HDR* p_tmp =
1038           (BT_HDR*)fixed_queue_try_dequeue(p_fcrb->waiting_for_ack_q);
1039       ls = p_tmp->layer_specific & L2CAP_FCR_SAR_BITS;
1040 
1041       if ((ls == L2CAP_FCR_UNSEG_SDU) || (ls == L2CAP_FCR_END_SDU))
1042         full_sdus_xmitted++;
1043 
1044       osi_free(p_tmp);
1045     }
1046 
1047     /* If we are still in a wait_ack state, do not mess with the timer */
1048     if (!p_ccb->fcrb.wait_ack) l2c_fcr_stop_timer(p_ccb);
1049 
1050     /* Check if we need to call the "packet_sent" callback */
1051     if ((p_ccb->p_rcb) && (p_ccb->p_rcb->api.pL2CA_TxComplete_Cb) &&
1052         (full_sdus_xmitted)) {
1053       /* Special case for eRTM, if all packets sent, send 0xFFFF */
1054       if (fixed_queue_is_empty(p_fcrb->waiting_for_ack_q) &&
1055           fixed_queue_is_empty(p_ccb->xmit_hold_q)) {
1056         full_sdus_xmitted = 0xFFFF;
1057       }
1058 
1059       (*p_ccb->p_rcb->api.pL2CA_TxComplete_Cb)(p_ccb->local_cid,
1060                                                full_sdus_xmitted);
1061     }
1062   }
1063 
1064   /* If anything still waiting for ack, restart the timer if it was stopped */
1065   if (!fixed_queue_is_empty(p_fcrb->waiting_for_ack_q))
1066     l2c_fcr_start_timer(p_ccb);
1067   return (true);
1068 }
1069 
1070 /*******************************************************************************
1071  *
1072  * Function         process_s_frame
1073  *
1074  * Description      Process an S frame
1075  *
1076  * Returns          -
1077  *
1078  ******************************************************************************/
process_s_frame(tL2C_CCB * p_ccb,BT_HDR * p_buf,uint16_t ctrl_word)1079 static void process_s_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf,
1080                             uint16_t ctrl_word) {
1081   CHECK(p_ccb != NULL);
1082   CHECK(p_buf != NULL);
1083 
1084   tL2C_FCRB* p_fcrb = &p_ccb->fcrb;
1085   uint16_t s_frame_type =
1086       (ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT;
1087   bool remote_was_busy;
1088   bool all_ok = true;
1089 
1090   if (p_buf->len != 0) {
1091     L2CAP_TRACE_WARNING("Incorrect S-frame Length (%d)", p_buf->len);
1092   }
1093 
1094   L2CAP_TRACE_DEBUG("process_s_frame ctrl_word 0x%04x fcrb_remote_busy:%d",
1095                     ctrl_word, p_fcrb->remote_busy);
1096 
1097 #if (L2CAP_ERTM_STATS == TRUE)
1098   p_ccb->fcrb.s_frames_rcvd[s_frame_type]++;
1099 #endif
1100 
1101   if (ctrl_word & L2CAP_FCR_P_BIT) {
1102     p_fcrb->rej_sent = false;  /* After checkpoint, we can send anoher REJ */
1103     p_fcrb->send_f_rsp = true; /* Set a flag in case an I-frame is pending */
1104   }
1105 
1106   switch (s_frame_type) {
1107     case L2CAP_FCR_SUP_RR:
1108       remote_was_busy = p_fcrb->remote_busy;
1109       p_fcrb->remote_busy = false;
1110 
1111       if ((ctrl_word & L2CAP_FCR_F_BIT) || (remote_was_busy))
1112         all_ok = retransmit_i_frames(p_ccb, L2C_FCR_RETX_ALL_PKTS);
1113       break;
1114 
1115     case L2CAP_FCR_SUP_REJ:
1116       p_fcrb->remote_busy = false;
1117       all_ok = retransmit_i_frames(p_ccb, L2C_FCR_RETX_ALL_PKTS);
1118       break;
1119 
1120     case L2CAP_FCR_SUP_RNR:
1121       p_fcrb->remote_busy = true;
1122       l2c_fcr_stop_timer(p_ccb);
1123       break;
1124 
1125     case L2CAP_FCR_SUP_SREJ:
1126       p_fcrb->remote_busy = false;
1127       all_ok = retransmit_i_frames(
1128           p_ccb, (uint8_t)((ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >>
1129                            L2CAP_FCR_REQ_SEQ_BITS_SHIFT));
1130       break;
1131   }
1132 
1133   if (all_ok) {
1134     /* If polled, we need to respond with F-bit. Note, we may have sent a
1135      * I-frame with the F-bit */
1136     if (p_fcrb->send_f_rsp) {
1137       if (p_fcrb->srej_sent)
1138         l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_SREJ, L2CAP_FCR_F_BIT);
1139       else if (p_fcrb->local_busy)
1140         l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RNR, L2CAP_FCR_F_BIT);
1141       else
1142         l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RR, L2CAP_FCR_F_BIT);
1143 
1144       p_fcrb->send_f_rsp = false;
1145     }
1146   } else {
1147     L2CAP_TRACE_DEBUG("process_s_frame hit_max_retries");
1148   }
1149 
1150   osi_free(p_buf);
1151 }
1152 
1153 /*******************************************************************************
1154  *
1155  * Function         process_i_frame
1156  *
1157  * Description      Process an I frame
1158  *
1159  * Returns          -
1160  *
1161  ******************************************************************************/
process_i_frame(tL2C_CCB * p_ccb,BT_HDR * p_buf,uint16_t ctrl_word,bool delay_ack)1162 static void process_i_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, uint16_t ctrl_word,
1163                             bool delay_ack) {
1164   CHECK(p_ccb != NULL);
1165   CHECK(p_buf != NULL);
1166 
1167   tL2C_FCRB* p_fcrb = &p_ccb->fcrb;
1168   uint8_t tx_seq, num_lost, num_to_ack, next_srej;
1169 
1170   /* If we were doing checkpoint recovery, first retransmit all unacked I-frames
1171    */
1172   if (ctrl_word & L2CAP_FCR_F_BIT) {
1173     if (!retransmit_i_frames(p_ccb, L2C_FCR_RETX_ALL_PKTS)) {
1174       osi_free(p_buf);
1175       return;
1176     }
1177   }
1178 
1179 #if (L2CAP_ERTM_STATS == TRUE)
1180   p_ccb->fcrb.ertm_pkt_counts[1]++;
1181   p_ccb->fcrb.ertm_byte_counts[1] += p_buf->len;
1182 #endif
1183 
1184   /* Extract the sequence number */
1185   tx_seq = (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT;
1186 
1187   /* If we have flow controlled the peer, ignore any bad I-frames from him */
1188   if ((tx_seq != p_fcrb->next_seq_expected) && (p_fcrb->local_busy)) {
1189     L2CAP_TRACE_WARNING("Dropping bad I-Frame since we flowed off, tx_seq:%u",
1190                         tx_seq);
1191     l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RNR, 0);
1192     osi_free(p_buf);
1193     return;
1194   }
1195 
1196   /* Check if tx-sequence is the expected one */
1197   if (tx_seq != p_fcrb->next_seq_expected) {
1198     num_lost = (tx_seq - p_fcrb->next_seq_expected) & L2CAP_FCR_SEQ_MODULO;
1199 
1200     /* Is the frame a duplicate ? If so, just drop it */
1201     if (num_lost >= p_ccb->our_cfg.fcr.tx_win_sz) {
1202       /* Duplicate - simply drop it */
1203       L2CAP_TRACE_WARNING(
1204           "process_i_frame() Dropping Duplicate Frame tx_seq:%u  ExpectedTxSeq "
1205           "%u",
1206           tx_seq, p_fcrb->next_seq_expected);
1207       osi_free(p_buf);
1208     } else {
1209       L2CAP_TRACE_WARNING(
1210           "process_i_frame() CID: 0x%04x  Lost: %u  tx_seq:%u  ExpTxSeq %u  "
1211           "Rej: %u  SRej: %u",
1212           p_ccb->local_cid, num_lost, tx_seq, p_fcrb->next_seq_expected,
1213           p_fcrb->rej_sent, p_fcrb->srej_sent);
1214 
1215       if (p_fcrb->srej_sent) {
1216         /* If SREJ sent, save the frame for later processing as long as it is in
1217          * sequence */
1218         next_srej =
1219             (((BT_HDR*)fixed_queue_try_peek_last(p_fcrb->srej_rcv_hold_q))
1220                  ->layer_specific +
1221              1) &
1222             L2CAP_FCR_SEQ_MODULO;
1223 
1224         if ((tx_seq == next_srej) &&
1225             (fixed_queue_length(p_fcrb->srej_rcv_hold_q) <
1226              p_ccb->our_cfg.fcr.tx_win_sz)) {
1227           /* If user gave us a pool for held rx buffers, use that */
1228           /* TODO: Could that happen? Get rid of this code. */
1229           if (p_ccb->ertm_info.fcr_rx_buf_size != L2CAP_FCR_RX_BUF_SIZE) {
1230             BT_HDR* p_buf2;
1231 
1232             /* Adjust offset and len so that control word is copied */
1233             p_buf->offset -= L2CAP_FCR_OVERHEAD;
1234             p_buf->len += L2CAP_FCR_OVERHEAD;
1235 
1236             p_buf2 = l2c_fcr_clone_buf(p_buf, p_buf->offset, p_buf->len);
1237 
1238             if (p_buf2) {
1239               osi_free(p_buf);
1240               p_buf = p_buf2;
1241             }
1242             p_buf->offset += L2CAP_FCR_OVERHEAD;
1243             p_buf->len -= L2CAP_FCR_OVERHEAD;
1244           }
1245           L2CAP_TRACE_DEBUG(
1246               "process_i_frame() Lost: %u  tx_seq:%u  ExpTxSeq %u  Rej: %u  "
1247               "SRej1",
1248               num_lost, tx_seq, p_fcrb->next_seq_expected, p_fcrb->rej_sent);
1249 
1250           p_buf->layer_specific = tx_seq;
1251           fixed_queue_enqueue(p_fcrb->srej_rcv_hold_q, p_buf);
1252         } else {
1253           L2CAP_TRACE_WARNING(
1254               "process_i_frame() CID: 0x%04x  frame dropped in Srej Sent "
1255               "next_srej:%u  hold_q.count:%u  win_sz:%u",
1256               p_ccb->local_cid, next_srej,
1257               fixed_queue_length(p_fcrb->srej_rcv_hold_q),
1258               p_ccb->our_cfg.fcr.tx_win_sz);
1259 
1260           p_fcrb->rej_after_srej = true;
1261           osi_free(p_buf);
1262         }
1263       } else if (p_fcrb->rej_sent) {
1264         L2CAP_TRACE_WARNING(
1265             "process_i_frame() CID: 0x%04x  Lost: %u  tx_seq:%u  ExpTxSeq %u  "
1266             "Rej: 1  SRej: %u",
1267             p_ccb->local_cid, num_lost, tx_seq, p_fcrb->next_seq_expected,
1268             p_fcrb->srej_sent);
1269 
1270         /* If REJ sent, just drop the frame */
1271         osi_free(p_buf);
1272       } else {
1273         L2CAP_TRACE_DEBUG(
1274             "process_i_frame() CID: 0x%04x  tx_seq:%u  ExpTxSeq %u  Rej: %u",
1275             p_ccb->local_cid, tx_seq, p_fcrb->next_seq_expected,
1276             p_fcrb->rej_sent);
1277 
1278         /* If only one lost, we will send SREJ, otherwise we will send REJ */
1279         if (num_lost > 1) {
1280           osi_free(p_buf);
1281           p_fcrb->rej_sent = true;
1282           l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_REJ, 0);
1283         } else {
1284           if (!fixed_queue_is_empty(p_fcrb->srej_rcv_hold_q)) {
1285             L2CAP_TRACE_ERROR(
1286                 "process_i_frame() CID: 0x%04x  sending SREJ tx_seq:%d "
1287                 "hold_q.count:%u",
1288                 p_ccb->local_cid, tx_seq,
1289                 fixed_queue_length(p_fcrb->srej_rcv_hold_q));
1290           }
1291           p_buf->layer_specific = tx_seq;
1292           fixed_queue_enqueue(p_fcrb->srej_rcv_hold_q, p_buf);
1293           p_fcrb->srej_sent = true;
1294           l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_SREJ, 0);
1295         }
1296         alarm_cancel(p_ccb->fcrb.ack_timer);
1297       }
1298     }
1299     return;
1300   }
1301 
1302   /* Seq number is the next expected. Clear possible reject exception in case it
1303    * occured */
1304   p_fcrb->rej_sent = p_fcrb->srej_sent = false;
1305 
1306   /* Adjust the next_seq, so that if the upper layer sends more data in the
1307      callback
1308      context, the received frame is acked by an I-frame. */
1309   p_fcrb->next_seq_expected = (tx_seq + 1) & L2CAP_FCR_SEQ_MODULO;
1310 
1311   /* If any SAR problem in eRTM mode, spec says disconnect. */
1312   if (!do_sar_reassembly(p_ccb, p_buf, ctrl_word)) {
1313     L2CAP_TRACE_WARNING("process_i_frame() CID: 0x%04x  reassembly failed",
1314                         p_ccb->local_cid);
1315     l2cu_disconnect_chnl(p_ccb);
1316     return;
1317   }
1318 
1319   /* RR optimization - if peer can still send us more, then start an ACK timer
1320    */
1321   num_to_ack = (p_fcrb->next_seq_expected - p_fcrb->last_ack_sent) &
1322                L2CAP_FCR_SEQ_MODULO;
1323 
1324   if ((num_to_ack < p_ccb->fcrb.max_held_acks) && (!p_fcrb->local_busy))
1325     delay_ack = true;
1326 
1327   /* We should neve never ack frame if we are not in OPEN state */
1328   if ((num_to_ack != 0) && p_ccb->in_use && (p_ccb->chnl_state == CST_OPEN)) {
1329     /* If no frames are awaiting transmission or are held, send an RR or RNR
1330      * S-frame for ack */
1331     if (delay_ack) {
1332       /* If it is the first I frame we did not ack, start ack timer */
1333       if (!alarm_is_scheduled(p_ccb->fcrb.ack_timer)) {
1334         alarm_set_on_mloop(p_ccb->fcrb.ack_timer, L2CAP_FCR_ACK_TIMEOUT_MS,
1335                            l2c_fcrb_ack_timer_timeout, p_ccb);
1336       }
1337     } else if ((fixed_queue_is_empty(p_ccb->xmit_hold_q) ||
1338                 l2c_fcr_is_flow_controlled(p_ccb)) &&
1339                fixed_queue_is_empty(p_ccb->fcrb.srej_rcv_hold_q)) {
1340       if (p_fcrb->local_busy)
1341         l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RNR, 0);
1342       else
1343         l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RR, 0);
1344     }
1345   }
1346 }
1347 
1348 /*******************************************************************************
1349  *
1350  * Function         process_stream_frame
1351  *
1352  * Description      This function processes frames in streaming mode
1353  *
1354  * Returns          -
1355  *
1356  ******************************************************************************/
process_stream_frame(tL2C_CCB * p_ccb,BT_HDR * p_buf)1357 static void process_stream_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf) {
1358   CHECK(p_ccb != NULL);
1359   CHECK(p_buf != NULL);
1360 
1361   uint16_t ctrl_word;
1362   uint16_t fcs;
1363   uint8_t* p;
1364   uint8_t tx_seq;
1365 
1366   /* Verify FCS if using */
1367   if (p_ccb->bypass_fcs != L2CAP_BYPASS_FCS) {
1368     p = ((uint8_t*)(p_buf + 1)) + p_buf->offset + p_buf->len - L2CAP_FCS_LEN;
1369 
1370     /* Extract and drop the FCS from the packet */
1371     STREAM_TO_UINT16(fcs, p);
1372     p_buf->len -= L2CAP_FCS_LEN;
1373 
1374     if (l2c_fcr_rx_get_fcs(p_buf) != fcs) {
1375       L2CAP_TRACE_WARNING("Rx L2CAP PDU: CID: 0x%04x  BAD FCS",
1376                           p_ccb->local_cid);
1377       osi_free(p_buf);
1378       return;
1379     }
1380   }
1381 
1382   /* Get the control word */
1383   p = ((uint8_t*)(p_buf + 1)) + p_buf->offset;
1384 
1385   STREAM_TO_UINT16(ctrl_word, p);
1386 
1387   p_buf->len -= L2CAP_FCR_OVERHEAD;
1388   p_buf->offset += L2CAP_FCR_OVERHEAD;
1389 
1390   /* Make sure it is an I-frame */
1391   if (ctrl_word & L2CAP_FCR_S_FRAME_BIT) {
1392     L2CAP_TRACE_WARNING(
1393         "Rx L2CAP PDU: CID: 0x%04x  BAD S-frame in streaming mode  ctrl_word: "
1394         "0x%04x",
1395         p_ccb->local_cid, ctrl_word);
1396     osi_free(p_buf);
1397     return;
1398   }
1399 
1400   L2CAP_TRACE_EVENT(
1401       "L2CAP eRTM Rx I-frame: cid: 0x%04x  Len: %u  SAR: %-12s  TxSeq: %u  "
1402       "ReqSeq: %u  F: %u",
1403       p_ccb->local_cid, p_buf->len,
1404       SAR_types[(ctrl_word & L2CAP_FCR_SAR_BITS) >> L2CAP_FCR_SAR_BITS_SHIFT],
1405       (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT,
1406       (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
1407       (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
1408 
1409   /* Extract the sequence number */
1410   tx_seq = (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT;
1411 
1412   /* Check if tx-sequence is the expected one */
1413   if (tx_seq != p_ccb->fcrb.next_seq_expected) {
1414     L2CAP_TRACE_WARNING(
1415         "Rx L2CAP PDU: CID: 0x%04x  Lost frames Exp: %u  Got: %u  p_rx_sdu: "
1416         "0x%08x",
1417         p_ccb->local_cid, p_ccb->fcrb.next_seq_expected, tx_seq,
1418         p_ccb->fcrb.p_rx_sdu);
1419 
1420     /* Lost one or more packets, so flush the SAR queue */
1421     osi_free_and_reset((void**)&p_ccb->fcrb.p_rx_sdu);
1422   }
1423 
1424   p_ccb->fcrb.next_seq_expected = (tx_seq + 1) & L2CAP_FCR_SEQ_MODULO;
1425 
1426   if (!do_sar_reassembly(p_ccb, p_buf, ctrl_word)) {
1427     /* Some sort of SAR error, so flush the SAR queue */
1428     osi_free_and_reset((void**)&p_ccb->fcrb.p_rx_sdu);
1429   }
1430 }
1431 
1432 /*******************************************************************************
1433  *
1434  * Function         do_sar_reassembly
1435  *
1436  * Description      Process SAR bits and re-assemble frame
1437  *
1438  * Returns          true if all OK, else false
1439  *
1440  ******************************************************************************/
do_sar_reassembly(tL2C_CCB * p_ccb,BT_HDR * p_buf,uint16_t ctrl_word)1441 static bool do_sar_reassembly(tL2C_CCB* p_ccb, BT_HDR* p_buf,
1442                               uint16_t ctrl_word) {
1443   CHECK(p_ccb != NULL);
1444   CHECK(p_buf != NULL);
1445 
1446   tL2C_FCRB* p_fcrb = &p_ccb->fcrb;
1447   uint16_t sar_type = ctrl_word & L2CAP_FCR_SEG_BITS;
1448   bool packet_ok = true;
1449   uint8_t* p;
1450 
1451   /* Check if the SAR state is correct */
1452   if ((sar_type == L2CAP_FCR_UNSEG_SDU) || (sar_type == L2CAP_FCR_START_SDU)) {
1453     if (p_fcrb->p_rx_sdu != NULL) {
1454       L2CAP_TRACE_WARNING(
1455           "SAR - got unexpected unsegmented or start SDU  Expected len: %u  "
1456           "Got so far: %u",
1457           p_fcrb->rx_sdu_len, p_fcrb->p_rx_sdu->len);
1458 
1459       packet_ok = false;
1460     }
1461     /* Check the length of the packet */
1462     if ((sar_type == L2CAP_FCR_START_SDU) &&
1463         (p_buf->len < L2CAP_SDU_LEN_OVERHEAD)) {
1464       L2CAP_TRACE_WARNING("SAR start packet too short: %u", p_buf->len);
1465       packet_ok = false;
1466     }
1467   } else {
1468     if (p_fcrb->p_rx_sdu == NULL) {
1469       L2CAP_TRACE_WARNING("SAR - got unexpected cont or end SDU");
1470       packet_ok = false;
1471     }
1472   }
1473 
1474   if ((packet_ok) && (sar_type != L2CAP_FCR_UNSEG_SDU)) {
1475     p = ((uint8_t*)(p_buf + 1)) + p_buf->offset;
1476 
1477     /* For start SDU packet, extract the SDU length */
1478     if (sar_type == L2CAP_FCR_START_SDU) {
1479       /* Get the SDU length */
1480       STREAM_TO_UINT16(p_fcrb->rx_sdu_len, p);
1481       p_buf->offset += 2;
1482       p_buf->len -= 2;
1483 
1484       if (p_fcrb->rx_sdu_len > p_ccb->max_rx_mtu) {
1485         L2CAP_TRACE_WARNING("SAR - SDU len: %u  larger than MTU: %u",
1486                             p_fcrb->rx_sdu_len, p_fcrb->rx_sdu_len);
1487         packet_ok = false;
1488       } else {
1489         p_fcrb->p_rx_sdu = (BT_HDR*)osi_malloc(
1490             BT_HDR_SIZE + OBX_BUF_MIN_OFFSET + p_fcrb->rx_sdu_len);
1491         p_fcrb->p_rx_sdu->offset = OBX_BUF_MIN_OFFSET;
1492         p_fcrb->p_rx_sdu->len = 0;
1493       }
1494     }
1495 
1496     if (packet_ok) {
1497       if ((p_fcrb->p_rx_sdu->len + p_buf->len) > p_fcrb->rx_sdu_len) {
1498         L2CAP_TRACE_ERROR(
1499             "SAR - SDU len exceeded  Type: %u   Lengths: %u %u %u", sar_type,
1500             p_fcrb->p_rx_sdu->len, p_buf->len, p_fcrb->rx_sdu_len);
1501         packet_ok = false;
1502       } else if ((sar_type == L2CAP_FCR_END_SDU) &&
1503                  ((p_fcrb->p_rx_sdu->len + p_buf->len) != p_fcrb->rx_sdu_len)) {
1504         L2CAP_TRACE_WARNING("SAR - SDU end rcvd but SDU incomplete: %u %u %u",
1505                             p_fcrb->p_rx_sdu->len, p_buf->len,
1506                             p_fcrb->rx_sdu_len);
1507         packet_ok = false;
1508       } else {
1509         memcpy(((uint8_t*)(p_fcrb->p_rx_sdu + 1)) + p_fcrb->p_rx_sdu->offset +
1510                    p_fcrb->p_rx_sdu->len,
1511                p, p_buf->len);
1512 
1513         p_fcrb->p_rx_sdu->len += p_buf->len;
1514 
1515         osi_free(p_buf);
1516         p_buf = NULL;
1517 
1518         if (sar_type == L2CAP_FCR_END_SDU) {
1519           p_buf = p_fcrb->p_rx_sdu;
1520           p_fcrb->p_rx_sdu = NULL;
1521         }
1522       }
1523     }
1524   }
1525 
1526   if (!packet_ok) {
1527     osi_free(p_buf);
1528   } else if (p_buf != NULL) {
1529 #if (L2CAP_NUM_FIXED_CHNLS > 0)
1530     if (p_ccb->local_cid < L2CAP_BASE_APPL_CID &&
1531         (p_ccb->local_cid >= L2CAP_FIRST_FIXED_CHNL &&
1532          p_ccb->local_cid <= L2CAP_LAST_FIXED_CHNL)) {
1533       if (l2cb.fixed_reg[p_ccb->local_cid - L2CAP_FIRST_FIXED_CHNL]
1534               .pL2CA_FixedData_Cb)
1535         (*l2cb.fixed_reg[p_ccb->local_cid - L2CAP_FIRST_FIXED_CHNL]
1536               .pL2CA_FixedData_Cb)(p_ccb->local_cid,
1537                                    p_ccb->p_lcb->remote_bd_addr, p_buf);
1538     } else
1539 #endif
1540       l2c_csm_execute(p_ccb, L2CEVT_L2CAP_DATA, p_buf);
1541   }
1542 
1543   return (packet_ok);
1544 }
1545 
1546 /*******************************************************************************
1547  *
1548  * Function         retransmit_i_frames
1549  *
1550  * Description      This function retransmits i-frames awaiting acks.
1551  *
1552  * Returns          bool    - true if retransmitted
1553  *
1554  ******************************************************************************/
retransmit_i_frames(tL2C_CCB * p_ccb,uint8_t tx_seq)1555 static bool retransmit_i_frames(tL2C_CCB* p_ccb, uint8_t tx_seq) {
1556   CHECK(p_ccb != NULL);
1557 
1558   BT_HDR* p_buf = NULL;
1559   uint8_t* p;
1560   uint8_t buf_seq;
1561   uint16_t ctrl_word;
1562 
1563   if ((!fixed_queue_is_empty(p_ccb->fcrb.waiting_for_ack_q)) &&
1564       (p_ccb->peer_cfg.fcr.max_transmit != 0) &&
1565       (p_ccb->fcrb.num_tries >= p_ccb->peer_cfg.fcr.max_transmit)) {
1566     L2CAP_TRACE_EVENT(
1567         "Max Tries Exceeded:  (last_acq: %d  CID: 0x%04x  num_tries: %u (max: "
1568         "%u) ack_q_count: %u",
1569         p_ccb->fcrb.last_rx_ack, p_ccb->local_cid, p_ccb->fcrb.num_tries,
1570         p_ccb->peer_cfg.fcr.max_transmit,
1571         fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q));
1572 
1573     l2cu_disconnect_chnl(p_ccb);
1574     return (false);
1575   }
1576 
1577   /* tx_seq indicates whether to retransmit a specific sequence or all (if ==
1578    * L2C_FCR_RETX_ALL_PKTS) */
1579   list_t* list_ack = NULL;
1580   const list_node_t* node_ack = NULL;
1581   if (!fixed_queue_is_empty(p_ccb->fcrb.waiting_for_ack_q)) {
1582     list_ack = fixed_queue_get_list(p_ccb->fcrb.waiting_for_ack_q);
1583     node_ack = list_begin(list_ack);
1584   }
1585   if (tx_seq != L2C_FCR_RETX_ALL_PKTS) {
1586     /* If sending only one, the sequence number tells us which one. Look for it.
1587     */
1588     if (list_ack != NULL) {
1589       for (; node_ack != list_end(list_ack); node_ack = list_next(node_ack)) {
1590         p_buf = (BT_HDR*)list_node(node_ack);
1591         /* Get the old control word */
1592         p = ((uint8_t*)(p_buf + 1)) + p_buf->offset + L2CAP_PKT_OVERHEAD;
1593 
1594         STREAM_TO_UINT16(ctrl_word, p);
1595 
1596         buf_seq =
1597             (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT;
1598 
1599         L2CAP_TRACE_DEBUG(
1600             "retransmit_i_frames()   cur seq: %u  looking for: %u", buf_seq,
1601             tx_seq);
1602 
1603         if (tx_seq == buf_seq) break;
1604       }
1605     }
1606 
1607     if (!p_buf) {
1608       L2CAP_TRACE_ERROR("retransmit_i_frames() UNKNOWN seq: %u  q_count: %u",
1609                         tx_seq,
1610                         fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q));
1611       return (true);
1612     }
1613   } else {
1614     // Iterate though list and flush the amount requested from
1615     // the transmit data queue that satisfy the layer and event conditions.
1616     for (list_node_t* node_tmp = list_begin(p_ccb->p_lcb->link_xmit_data_q);
1617          node_tmp != list_end(p_ccb->p_lcb->link_xmit_data_q);) {
1618       BT_HDR* p_tmp = (BT_HDR*)list_node(node_tmp);
1619       node_tmp = list_next(node_tmp);
1620 
1621       /* Do not flush other CIDs or partial segments */
1622       if ((p_tmp->layer_specific == 0) && (p_tmp->event == p_ccb->local_cid)) {
1623         list_remove(p_ccb->p_lcb->link_xmit_data_q, p_tmp);
1624         osi_free(p_tmp);
1625       }
1626     }
1627 
1628     /* Also flush our retransmission queue */
1629     while (!fixed_queue_is_empty(p_ccb->fcrb.retrans_q))
1630       osi_free(fixed_queue_try_dequeue(p_ccb->fcrb.retrans_q));
1631 
1632     if (list_ack != NULL) node_ack = list_begin(list_ack);
1633   }
1634 
1635   if (list_ack != NULL) {
1636     while (node_ack != list_end(list_ack)) {
1637       p_buf = (BT_HDR*)list_node(node_ack);
1638       node_ack = list_next(node_ack);
1639 
1640       BT_HDR* p_buf2 = l2c_fcr_clone_buf(p_buf, p_buf->offset, p_buf->len);
1641       if (p_buf2) {
1642         p_buf2->layer_specific = p_buf->layer_specific;
1643 
1644         fixed_queue_enqueue(p_ccb->fcrb.retrans_q, p_buf2);
1645       }
1646 
1647       if ((tx_seq != L2C_FCR_RETX_ALL_PKTS) || (p_buf2 == NULL)) break;
1648     }
1649   }
1650 
1651   l2c_link_check_send_pkts(p_ccb->p_lcb, NULL, NULL);
1652 
1653   if (fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q)) {
1654     p_ccb->fcrb.num_tries++;
1655     l2c_fcr_start_timer(p_ccb);
1656   }
1657 
1658   return (true);
1659 }
1660 
1661 /*******************************************************************************
1662  *
1663  * Function         l2c_fcr_get_next_xmit_sdu_seg
1664  *
1665  * Description      Get the next SDU segment to transmit.
1666  *
1667  * Returns          pointer to buffer with segment or NULL
1668  *
1669  ******************************************************************************/
l2c_fcr_get_next_xmit_sdu_seg(tL2C_CCB * p_ccb,uint16_t max_packet_length)1670 BT_HDR* l2c_fcr_get_next_xmit_sdu_seg(tL2C_CCB* p_ccb,
1671                                       uint16_t max_packet_length) {
1672   CHECK(p_ccb != NULL);
1673 
1674   bool first_seg = false, /* The segment is the first part of data  */
1675       mid_seg = false,    /* The segment is the middle part of data */
1676       last_seg = false;   /* The segment is the last part of data   */
1677   uint16_t sdu_len = 0;
1678   BT_HDR *p_buf, *p_xmit;
1679   uint8_t* p;
1680   uint16_t max_pdu = p_ccb->tx_mps /* Needed? - L2CAP_MAX_HEADER_FCS*/;
1681 
1682   /* If there is anything in the retransmit queue, that goes first
1683   */
1684   p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_ccb->fcrb.retrans_q);
1685   if (p_buf != NULL) {
1686     /* Update Rx Seq and FCS if we acked some packets while this one was queued
1687      */
1688     prepare_I_frame(p_ccb, p_buf, true);
1689 
1690     p_buf->event = p_ccb->local_cid;
1691 
1692 #if (L2CAP_ERTM_STATS == TRUE)
1693     p_ccb->fcrb.pkts_retransmitted++;
1694     p_ccb->fcrb.ertm_pkt_counts[0]++;
1695     p_ccb->fcrb.ertm_byte_counts[0] += (p_buf->len - 8);
1696 #endif
1697     return (p_buf);
1698   }
1699 
1700   /* For BD/EDR controller, max_packet_length is set to 0             */
1701   /* For AMP controller, max_packet_length is set by available blocks */
1702   if ((max_packet_length > L2CAP_MAX_HEADER_FCS) &&
1703       (max_pdu + L2CAP_MAX_HEADER_FCS > max_packet_length)) {
1704     max_pdu = max_packet_length - L2CAP_MAX_HEADER_FCS;
1705   }
1706 
1707   p_buf = (BT_HDR*)fixed_queue_try_peek_first(p_ccb->xmit_hold_q);
1708 
1709   /* If there is more data than the MPS, it requires segmentation */
1710   if (p_buf->len > max_pdu) {
1711     /* We are using the "event" field to tell is if we already started
1712      * segmentation */
1713     if (p_buf->event == 0) {
1714       first_seg = true;
1715       sdu_len = p_buf->len;
1716     } else
1717       mid_seg = true;
1718 
1719     /* Get a new buffer and copy the data that can be sent in a PDU */
1720     p_xmit = l2c_fcr_clone_buf(p_buf, L2CAP_MIN_OFFSET + L2CAP_SDU_LEN_OFFSET,
1721                                max_pdu);
1722 
1723     if (p_xmit != NULL) {
1724       p_buf->event = p_ccb->local_cid;
1725       p_xmit->event = p_ccb->local_cid;
1726 
1727       p_buf->len -= max_pdu;
1728       p_buf->offset += max_pdu;
1729 
1730       /* copy PBF setting */
1731       p_xmit->layer_specific = p_buf->layer_specific;
1732     } else /* Should never happen if the application has configured buffers
1733               correctly */
1734     {
1735       L2CAP_TRACE_ERROR(
1736           "L2CAP - cannot get buffer for segmentation, max_pdu: %u", max_pdu);
1737       return (NULL);
1738     }
1739   } else /* Use the original buffer if no segmentation, or the last segment */
1740   {
1741     p_xmit = (BT_HDR*)fixed_queue_try_dequeue(p_ccb->xmit_hold_q);
1742 
1743     if (p_xmit->event != 0) last_seg = true;
1744 
1745     p_xmit->event = p_ccb->local_cid;
1746   }
1747 
1748   /* Step back to add the L2CAP headers */
1749   p_xmit->offset -= (L2CAP_PKT_OVERHEAD + L2CAP_FCR_OVERHEAD);
1750   p_xmit->len += L2CAP_PKT_OVERHEAD + L2CAP_FCR_OVERHEAD;
1751 
1752   if (first_seg) {
1753     p_xmit->offset -= L2CAP_SDU_LEN_OVERHEAD;
1754     p_xmit->len += L2CAP_SDU_LEN_OVERHEAD;
1755   }
1756 
1757   /* Set the pointer to the beginning of the data */
1758   p = (uint8_t*)(p_xmit + 1) + p_xmit->offset;
1759 
1760   /* Now the L2CAP header */
1761 
1762   /* Note: if FCS has to be included then the length is recalculated later */
1763   UINT16_TO_STREAM(p, p_xmit->len - L2CAP_PKT_OVERHEAD);
1764 
1765   UINT16_TO_STREAM(p, p_ccb->remote_cid);
1766 
1767   if (first_seg) {
1768     /* Skip control word and add SDU length */
1769     p += 2;
1770     UINT16_TO_STREAM(p, sdu_len);
1771 
1772     /* We will store the SAR type in layer-specific */
1773     /* layer_specific is shared with flushable flag(bits 0-1), don't clear it */
1774     p_xmit->layer_specific |= L2CAP_FCR_START_SDU;
1775 
1776     first_seg = false;
1777   } else if (mid_seg)
1778     p_xmit->layer_specific |= L2CAP_FCR_CONT_SDU;
1779   else if (last_seg)
1780     p_xmit->layer_specific |= L2CAP_FCR_END_SDU;
1781   else
1782     p_xmit->layer_specific |= L2CAP_FCR_UNSEG_SDU;
1783 
1784   prepare_I_frame(p_ccb, p_xmit, false);
1785 
1786   if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) {
1787     BT_HDR* p_wack =
1788         l2c_fcr_clone_buf(p_xmit, HCI_DATA_PREAMBLE_SIZE, p_xmit->len);
1789 
1790     if (!p_wack) {
1791       L2CAP_TRACE_ERROR(
1792           "L2CAP - no buffer for xmit cloning, CID: 0x%04x  Length: %u",
1793           p_ccb->local_cid, p_xmit->len);
1794 
1795       /* We will not save the FCS in case we reconfigure and change options */
1796       if (p_ccb->bypass_fcs != L2CAP_BYPASS_FCS) p_xmit->len -= L2CAP_FCS_LEN;
1797 
1798       /* Pretend we sent it and it got lost */
1799       fixed_queue_enqueue(p_ccb->fcrb.waiting_for_ack_q, p_xmit);
1800       return (NULL);
1801     } else {
1802 #if (L2CAP_ERTM_STATS == TRUE)
1803       /* set timestamp at the end of tx I-frame to get acking delay */
1804       /*
1805        * NOTE: Here we assume the allocate buffer is large enough
1806        * to include extra 4 octets at the end.
1807        */
1808       p = ((uint8_t*)(p_wack + 1)) + p_wack->offset + p_wack->len;
1809       // Have to cast to uint32_t which wraps in 49.7 days
1810       UINT32_TO_STREAM(p, static_cast<uint32_t>(
1811                               bluetooth::common::time_get_os_boottime_ms()));
1812 #endif
1813       /* We will not save the FCS in case we reconfigure and change options */
1814       if (p_ccb->bypass_fcs != L2CAP_BYPASS_FCS) p_wack->len -= L2CAP_FCS_LEN;
1815 
1816       p_wack->layer_specific = p_xmit->layer_specific;
1817       fixed_queue_enqueue(p_ccb->fcrb.waiting_for_ack_q, p_wack);
1818     }
1819 
1820 #if (L2CAP_ERTM_STATS == TRUE)
1821     p_ccb->fcrb.ertm_pkt_counts[0]++;
1822     p_ccb->fcrb.ertm_byte_counts[0] += (p_xmit->len - 8);
1823 #endif
1824   }
1825 
1826   return (p_xmit);
1827 }
1828 
1829 /** Get the next PDU to transmit for LE connection oriented channel. Returns
1830  * pointer to buffer with PDU. |last_piece_of_sdu| will be set to true, if
1831  * returned PDU is last piece from this SDU.*/
l2c_lcc_get_next_xmit_sdu_seg(tL2C_CCB * p_ccb,bool * last_piece_of_sdu)1832 BT_HDR* l2c_lcc_get_next_xmit_sdu_seg(tL2C_CCB* p_ccb,
1833                                       bool* last_piece_of_sdu) {
1834   uint16_t max_pdu = p_ccb->peer_conn_cfg.mps - 4 /* Length and CID */;
1835 
1836   BT_HDR* p_buf = (BT_HDR*)fixed_queue_try_peek_first(p_ccb->xmit_hold_q);
1837   bool first_pdu = (p_buf->event == 0) ? true : false;
1838 
1839   uint16_t no_of_bytes_to_send = std::min(
1840       p_buf->len,
1841       (uint16_t)(first_pdu ? (max_pdu - L2CAP_LCC_SDU_LENGTH) : max_pdu));
1842   bool last_pdu = (no_of_bytes_to_send == p_buf->len);
1843 
1844   /* Get a new buffer and copy the data that can be sent in a PDU */
1845   BT_HDR* p_xmit =
1846       l2c_fcr_clone_buf(p_buf, first_pdu ? L2CAP_LCC_OFFSET : L2CAP_MIN_OFFSET,
1847                         no_of_bytes_to_send);
1848 
1849   p_buf->event = p_ccb->local_cid;
1850   p_xmit->event = p_ccb->local_cid;
1851 
1852   if (first_pdu) {
1853     p_xmit->offset -= L2CAP_LCC_SDU_LENGTH; /* for writing the SDU length. */
1854     uint8_t* p = (uint8_t*)(p_xmit + 1) + p_xmit->offset;
1855     UINT16_TO_STREAM(p, p_buf->len);
1856     p_xmit->len += L2CAP_LCC_SDU_LENGTH;
1857   }
1858 
1859   p_buf->len -= no_of_bytes_to_send;
1860   p_buf->offset += no_of_bytes_to_send;
1861 
1862   /* copy PBF setting */
1863   p_xmit->layer_specific = p_buf->layer_specific;
1864 
1865   if (last_piece_of_sdu) *last_piece_of_sdu = last_pdu;
1866 
1867   if (last_pdu) {
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   uint8_t* 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  ******************************************************************************/
l2c_fcr_chk_chan_modes(tL2C_CCB * p_ccb)1906 uint8_t l2c_fcr_chk_chan_modes(tL2C_CCB* p_ccb) {
1907   CHECK(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  ******************************************************************************/
l2c_fcr_adj_our_req_options(tL2C_CCB * p_ccb,tL2CAP_CFG_INFO * p_cfg)1935 bool l2c_fcr_adj_our_req_options(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) {
1936   CHECK(p_ccb != NULL);
1937   CHECK(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  ******************************************************************************/
l2c_fcr_adj_monitor_retran_timeout(tL2C_CCB * p_ccb)2056 void l2c_fcr_adj_monitor_retran_timeout(tL2C_CCB* p_ccb) {
2057   CHECK(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  ******************************************************************************/
l2c_fcr_adj_our_rsp_options(tL2C_CCB * p_ccb,tL2CAP_CFG_INFO * p_cfg)2092 void l2c_fcr_adj_our_rsp_options(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) {
2093   CHECK(p_ccb != NULL);
2094   CHECK(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  ******************************************************************************/
l2c_fcr_renegotiate_chan(tL2C_CCB * p_ccb,tL2CAP_CFG_INFO * p_cfg)2134 bool l2c_fcr_renegotiate_chan(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) {
2135   CHECK(p_ccb != NULL);
2136   CHECK(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_mloop(p_ccb->l2c_ccb_timer, L2CAP_CHNL_CFG_TIMEOUT_MS,
2202                            l2c_ccb_timer_timeout, p_ccb);
2203         return (true);
2204       }
2205     }
2206   }
2207 
2208   /* Disconnect if the channels do not match */
2209   if (p_ccb->our_cfg.fcr.mode != peer_mode) {
2210     L2CAP_TRACE_WARNING("L2C CFG:  Channels incompatible (local %d, peer %d)",
2211                         p_ccb->our_cfg.fcr.mode, peer_mode);
2212     l2cu_disconnect_chnl(p_ccb);
2213   }
2214 
2215   return (false);
2216 }
2217 
2218 /*******************************************************************************
2219  *
2220  * Function         l2c_fcr_process_peer_cfg_req
2221  *
2222  * Description      This function is called to process the FCR options passed
2223  *                  in the peer's configuration request.
2224  *
2225  * Returns          uint8_t - L2CAP_PEER_CFG_OK, L2CAP_PEER_CFG_UNACCEPTABLE,
2226  *                          or L2CAP_PEER_CFG_DISCONNECT.
2227  *
2228  ******************************************************************************/
l2c_fcr_process_peer_cfg_req(tL2C_CCB * p_ccb,tL2CAP_CFG_INFO * p_cfg)2229 uint8_t l2c_fcr_process_peer_cfg_req(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) {
2230   CHECK(p_ccb != NULL);
2231   CHECK(p_cfg != NULL);
2232 
2233   uint16_t max_retrans_size;
2234   uint8_t fcr_ok = L2CAP_PEER_CFG_OK;
2235 
2236   p_ccb->p_lcb->w4_info_rsp =
2237       false; /* Handles T61x SonyEricsson Bug in Info Request */
2238 
2239   L2CAP_TRACE_EVENT(
2240       "l2c_fcr_process_peer_cfg_req() CFG fcr_present:%d fcr.mode:%d CCB FCR "
2241       "mode:%d preferred: %u allowed:%u",
2242       p_cfg->fcr_present, p_cfg->fcr.mode, p_ccb->our_cfg.fcr.mode,
2243       p_ccb->ertm_info.preferred_mode, p_ccb->ertm_info.allowed_modes);
2244 
2245   /* If Peer wants basic, we are done (accept it or disconnect) */
2246   if (p_cfg->fcr.mode == L2CAP_FCR_BASIC_MODE) {
2247     /* If we do not allow basic, disconnect */
2248     if (!(p_ccb->ertm_info.allowed_modes & L2CAP_FCR_CHAN_OPT_BASIC))
2249       fcr_ok = L2CAP_PEER_CFG_DISCONNECT;
2250   }
2251 
2252   /* Need to negotiate if our modes are not the same */
2253   else if (p_cfg->fcr.mode != p_ccb->ertm_info.preferred_mode) {
2254     /* If peer wants a mode that we don't support then retry our mode (ex.
2255     *rtx/flc), OR
2256     ** If we want ERTM and they wanted streaming retry our mode.
2257     ** Note: If we have already determined they support our mode previously
2258     **       from their EXF mask.
2259     */
2260     if ((((1 << p_cfg->fcr.mode) & L2CAP_FCR_CHAN_OPT_ALL_MASK) == 0) ||
2261         (p_ccb->ertm_info.preferred_mode == L2CAP_FCR_ERTM_MODE)) {
2262       p_cfg->fcr.mode = p_ccb->our_cfg.fcr.mode;
2263       p_cfg->fcr.tx_win_sz = p_ccb->our_cfg.fcr.tx_win_sz;
2264       p_cfg->fcr.max_transmit = p_ccb->our_cfg.fcr.max_transmit;
2265       fcr_ok = L2CAP_PEER_CFG_UNACCEPTABLE;
2266     }
2267 
2268     /* If we wanted basic, then try to renegotiate it */
2269     else if (p_ccb->ertm_info.preferred_mode == L2CAP_FCR_BASIC_MODE) {
2270       p_cfg->fcr.mode = L2CAP_FCR_BASIC_MODE;
2271       p_cfg->fcr.max_transmit = p_cfg->fcr.tx_win_sz = 0;
2272       p_cfg->fcr.rtrans_tout = p_cfg->fcr.mon_tout = p_cfg->fcr.mps = 0;
2273       p_ccb->our_cfg.fcr.rtrans_tout = p_ccb->our_cfg.fcr.mon_tout =
2274           p_ccb->our_cfg.fcr.mps = 0;
2275       fcr_ok = L2CAP_PEER_CFG_UNACCEPTABLE;
2276     }
2277 
2278     /* Only other valid case is if they want ERTM and we wanted STM which should
2279        be
2280        accepted if we support it; otherwise the channel should be disconnected
2281        */
2282     else if ((p_cfg->fcr.mode != L2CAP_FCR_ERTM_MODE) ||
2283              !(p_ccb->ertm_info.allowed_modes & L2CAP_FCR_CHAN_OPT_ERTM)) {
2284       fcr_ok = L2CAP_PEER_CFG_DISCONNECT;
2285     }
2286   }
2287 
2288   /* Configuration for FCR channels so make any adjustments and fwd to upper
2289    * layer */
2290   if (fcr_ok == L2CAP_PEER_CFG_OK) {
2291     /* by default don't need to send params in the response */
2292     p_ccb->out_cfg_fcr_present = false;
2293 
2294     /* Make any needed adjustments for the response to the peer */
2295     if (p_cfg->fcr_present && p_cfg->fcr.mode != L2CAP_FCR_BASIC_MODE) {
2296       /* Peer desires to bypass FCS check, and streaming or ERTM mode */
2297       if (p_cfg->fcs_present) {
2298         p_ccb->peer_cfg.fcs = p_cfg->fcs;
2299         p_ccb->peer_cfg_bits |= L2CAP_CH_CFG_MASK_FCS;
2300         if (p_cfg->fcs == L2CAP_CFG_FCS_BYPASS)
2301           p_ccb->bypass_fcs |= L2CAP_CFG_FCS_PEER;
2302       }
2303 
2304       max_retrans_size = p_ccb->ertm_info.fcr_tx_buf_size - sizeof(BT_HDR) -
2305                          L2CAP_MIN_OFFSET - L2CAP_SDU_LEN_OFFSET -
2306                          L2CAP_FCS_LEN;
2307 
2308       /* Ensure the MPS is not bigger than the MTU */
2309       if ((p_cfg->fcr.mps == 0) || (p_cfg->fcr.mps > p_ccb->peer_cfg.mtu)) {
2310         p_cfg->fcr.mps = p_ccb->peer_cfg.mtu;
2311         p_ccb->out_cfg_fcr_present = true;
2312       }
2313 
2314       /* Ensure the MPS is not bigger than our retransmission buffer */
2315       if (p_cfg->fcr.mps > max_retrans_size) {
2316         L2CAP_TRACE_DEBUG("CFG: Overriding MPS to %d (orig %d)",
2317                           max_retrans_size, p_cfg->fcr.mps);
2318 
2319         p_cfg->fcr.mps = max_retrans_size;
2320         p_ccb->out_cfg_fcr_present = true;
2321       }
2322 
2323       if (p_cfg->fcr.mode == L2CAP_FCR_ERTM_MODE ||
2324           p_cfg->fcr.mode == L2CAP_FCR_STREAM_MODE) {
2325         /* Always respond with FCR ERTM parameters */
2326         p_ccb->out_cfg_fcr_present = true;
2327       }
2328     }
2329 
2330     /* Everything ok, so save the peer's adjusted fcr options */
2331     p_ccb->peer_cfg.fcr = p_cfg->fcr;
2332 
2333     if (p_cfg->fcr_present) p_ccb->peer_cfg_bits |= L2CAP_CH_CFG_MASK_FCR;
2334   } else if (fcr_ok == L2CAP_PEER_CFG_UNACCEPTABLE) {
2335     /* Allow peer only one retry for mode */
2336     if (p_ccb->peer_cfg_already_rejected)
2337       fcr_ok = L2CAP_PEER_CFG_DISCONNECT;
2338     else
2339       p_ccb->peer_cfg_already_rejected = true;
2340   }
2341 
2342   return (fcr_ok);
2343 }
2344 
2345 #if (L2CAP_ERTM_STATS == TRUE)
2346 /*******************************************************************************
2347  *
2348  * Function         l2c_fcr_collect_ack_delay
2349  *
2350  * Description      collect throughput, delay, queue size of waiting ack
2351  *
2352  * Parameters
2353  *                  tL2C_CCB
2354  *
2355  * Returns          void
2356  *
2357  ******************************************************************************/
l2c_fcr_collect_ack_delay(tL2C_CCB * p_ccb,uint8_t num_bufs_acked)2358 static void l2c_fcr_collect_ack_delay(tL2C_CCB* p_ccb, uint8_t num_bufs_acked) {
2359   uint32_t index;
2360   BT_HDR* p_buf;
2361   uint8_t* p;
2362   uint32_t timestamp, delay;
2363   uint8_t xx;
2364   uint8_t str[120];
2365 
2366   index = p_ccb->fcrb.ack_delay_avg_index;
2367 
2368   /* update sum, max and min of waiting for ack queue size */
2369   p_ccb->fcrb.ack_q_count_avg[index] +=
2370       fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q);
2371 
2372   if (fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q) >
2373       p_ccb->fcrb.ack_q_count_max[index])
2374     p_ccb->fcrb.ack_q_count_max[index] =
2375         fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q);
2376 
2377   if (fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q) <
2378       p_ccb->fcrb.ack_q_count_min[index])
2379     p_ccb->fcrb.ack_q_count_min[index] =
2380         fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q);
2381 
2382   /* update sum, max and min of round trip delay of acking */
2383   list_t* list = NULL;
2384   if (!fixed_queue_is_empty(p_ccb->fcrb.waiting_for_ack_q))
2385     list = fixed_queue_get_list(p_ccb->fcrb.waiting_for_ack_q);
2386   if (list != NULL) {
2387     for (const list_node_t *node = list_begin(list), xx = 0;
2388          (node != list_end(list)) && (xx < num_bufs_acked);
2389          node = list_next(node), xx++) {
2390       p_buf = list_node(node);
2391       /* adding up length of acked I-frames to get throughput */
2392       p_ccb->fcrb.throughput[index] += p_buf->len - 8;
2393 
2394       if (xx == num_bufs_acked - 1) {
2395         /* get timestamp from tx I-frame that receiver is acking */
2396         p = ((uint8_t*)(p_buf + 1)) + p_buf->offset + p_buf->len;
2397         if (p_ccb->bypass_fcs != L2CAP_BYPASS_FCS) {
2398           p += L2CAP_FCS_LEN;
2399         }
2400 
2401         STREAM_TO_UINT32(timestamp, p);
2402         delay = static_cast<uint32_t>(
2403                     bluetooth::common::time_get_os_boottime_ms()) -
2404                 timestamp;
2405 
2406         p_ccb->fcrb.ack_delay_avg[index] += delay;
2407         if (delay > p_ccb->fcrb.ack_delay_max[index])
2408           p_ccb->fcrb.ack_delay_max[index] = delay;
2409         if (delay < p_ccb->fcrb.ack_delay_min[index])
2410           p_ccb->fcrb.ack_delay_min[index] = delay;
2411       }
2412     }
2413   }
2414 
2415   p_ccb->fcrb.ack_delay_avg_count++;
2416 
2417   /* calculate average and initialize next avg, min and max */
2418   if (p_ccb->fcrb.ack_delay_avg_count > L2CAP_ERTM_STATS_AVG_NUM_SAMPLES) {
2419     p_ccb->fcrb.ack_delay_avg_count = 0;
2420 
2421     p_ccb->fcrb.ack_q_count_avg[index] /= L2CAP_ERTM_STATS_AVG_NUM_SAMPLES;
2422     p_ccb->fcrb.ack_delay_avg[index] /= L2CAP_ERTM_STATS_AVG_NUM_SAMPLES;
2423 
2424     /* calculate throughput */
2425     timestamp = bluetooth::common::time_get_os_boottime_ms();
2426     if (timestamp - p_ccb->fcrb.throughput_start > 0)
2427       p_ccb->fcrb.throughput[index] /=
2428           (timestamp - p_ccb->fcrb.throughput_start);
2429 
2430     p_ccb->fcrb.throughput_start = timestamp;
2431 
2432     snprintf(
2433         str, sizeof(str),
2434         "[%02u] throughput: %5u, ack_delay avg:%3u, min:%3u, max:%3u, "
2435         "ack_q_count avg:%3u, min:%3u, max:%3u",
2436         index, p_ccb->fcrb.throughput[index], p_ccb->fcrb.ack_delay_avg[index],
2437         p_ccb->fcrb.ack_delay_min[index], p_ccb->fcrb.ack_delay_max[index],
2438         p_ccb->fcrb.ack_q_count_avg[index], p_ccb->fcrb.ack_q_count_min[index],
2439         p_ccb->fcrb.ack_q_count_max[index]);
2440 
2441     BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI,
2442              TRACE_TYPE_GENERIC, "%s", str);
2443 
2444     index = (index + 1) % L2CAP_ERTM_STATS_NUM_AVG;
2445     p_ccb->fcrb.ack_delay_avg_index = index;
2446 
2447     p_ccb->fcrb.ack_q_count_max[index] = 0;
2448     p_ccb->fcrb.ack_q_count_min[index] = 0xFFFFFFFF;
2449     p_ccb->fcrb.ack_q_count_avg[index] = 0;
2450 
2451     p_ccb->fcrb.ack_delay_max[index] = 0;
2452     p_ccb->fcrb.ack_delay_min[index] = 0xFFFFFFFF;
2453     p_ccb->fcrb.ack_delay_avg[index] = 0;
2454 
2455     p_ccb->fcrb.throughput[index] = 0;
2456   }
2457 }
2458 #endif
2459