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