xref: /linux/net/bluetooth/l2cap_core.c (revision f4cdf7ca9a1fdcca413157df19753f388a5a224e)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3    BlueZ - Bluetooth protocol stack for Linux
4    Copyright (C) 2000-2001 Qualcomm Incorporated
5    Copyright (C) 2009-2010 Gustavo F. Padovan <gustavo@padovan.org>
6    Copyright (C) 2010 Google Inc.
7    Copyright (C) 2011 ProFUSION Embedded Systems
8    Copyright (c) 2012 Code Aurora Forum.  All rights reserved.
9 
10    Written 2000,2001 by Maxim Krasnyansky <maxk@qualcomm.com>
11 
12    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13    OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
15    IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY
16    CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES
17    WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
18    ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
19    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20 
21    ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS,
22    COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS
23    SOFTWARE IS DISCLAIMED.
24 */
25 
26 /* Bluetooth L2CAP core. */
27 
28 #include <linux/module.h>
29 
30 #include <linux/debugfs.h>
31 #include <linux/crc16.h>
32 #include <linux/filter.h>
33 
34 #include <net/bluetooth/bluetooth.h>
35 #include <net/bluetooth/hci_core.h>
36 #include <net/bluetooth/l2cap.h>
37 
38 #include "smp.h"
39 
40 #define LE_FLOWCTL_MAX_CREDITS 65535
41 
42 bool disable_ertm;
43 bool enable_ecred = IS_ENABLED(CONFIG_BT_LE_L2CAP_ECRED);
44 
45 static u32 l2cap_feat_mask = L2CAP_FEAT_FIXED_CHAN | L2CAP_FEAT_UCD;
46 
47 static LIST_HEAD(chan_list);
48 static DEFINE_RWLOCK(chan_list_lock);
49 
50 static struct sk_buff *l2cap_build_cmd(struct l2cap_conn *conn,
51 				       u8 code, u8 ident, u16 dlen, void *data);
52 static void l2cap_send_cmd(struct l2cap_conn *conn, u8 ident, u8 code, u16 len,
53 			   void *data);
54 static int l2cap_build_conf_req(struct l2cap_chan *chan, void *data, size_t data_size);
55 static void l2cap_send_disconn_req(struct l2cap_chan *chan, int err);
56 
57 static void l2cap_tx(struct l2cap_chan *chan, struct l2cap_ctrl *control,
58 		     struct sk_buff_head *skbs, u8 event);
59 static void l2cap_retrans_timeout(struct work_struct *work);
60 static void l2cap_monitor_timeout(struct work_struct *work);
61 static void l2cap_ack_timeout(struct work_struct *work);
62 
63 static inline u8 bdaddr_type(u8 link_type, u8 bdaddr_type)
64 {
65 	if (link_type == LE_LINK) {
66 		if (bdaddr_type == ADDR_LE_DEV_PUBLIC)
67 			return BDADDR_LE_PUBLIC;
68 		else
69 			return BDADDR_LE_RANDOM;
70 	}
71 
72 	return BDADDR_BREDR;
73 }
74 
75 static inline u8 bdaddr_src_type(struct hci_conn *hcon)
76 {
77 	return bdaddr_type(hcon->type, hcon->src_type);
78 }
79 
80 static inline u8 bdaddr_dst_type(struct hci_conn *hcon)
81 {
82 	return bdaddr_type(hcon->type, hcon->dst_type);
83 }
84 
85 /* ---- L2CAP channels ---- */
86 
87 static struct l2cap_chan *__l2cap_get_chan_by_dcid(struct l2cap_conn *conn,
88 						   u16 cid)
89 {
90 	struct l2cap_chan *c;
91 
92 	list_for_each_entry(c, &conn->chan_l, list) {
93 		if (c->dcid == cid)
94 			return c;
95 	}
96 	return NULL;
97 }
98 
99 static struct l2cap_chan *__l2cap_get_chan_by_scid(struct l2cap_conn *conn,
100 						   u16 cid)
101 {
102 	struct l2cap_chan *c;
103 
104 	list_for_each_entry(c, &conn->chan_l, list) {
105 		if (c->scid == cid)
106 			return c;
107 	}
108 	return NULL;
109 }
110 
111 /* Find channel with given SCID.
112  * Returns a reference locked channel.
113  */
114 static struct l2cap_chan *l2cap_get_chan_by_scid(struct l2cap_conn *conn,
115 						 u16 cid)
116 {
117 	struct l2cap_chan *c;
118 
119 	c = __l2cap_get_chan_by_scid(conn, cid);
120 	if (c) {
121 		/* Only lock if chan reference is not 0 */
122 		c = l2cap_chan_hold_unless_zero(c);
123 		if (c)
124 			l2cap_chan_lock(c);
125 	}
126 
127 	return c;
128 }
129 
130 /* Find channel with given DCID.
131  * Returns a reference locked channel.
132  */
133 static struct l2cap_chan *l2cap_get_chan_by_dcid(struct l2cap_conn *conn,
134 						 u16 cid)
135 {
136 	struct l2cap_chan *c;
137 
138 	c = __l2cap_get_chan_by_dcid(conn, cid);
139 	if (c) {
140 		/* Only lock if chan reference is not 0 */
141 		c = l2cap_chan_hold_unless_zero(c);
142 		if (c)
143 			l2cap_chan_lock(c);
144 	}
145 
146 	return c;
147 }
148 
149 static struct l2cap_chan *__l2cap_get_chan_by_ident(struct l2cap_conn *conn,
150 						    u8 ident)
151 {
152 	struct l2cap_chan *c;
153 
154 	list_for_each_entry(c, &conn->chan_l, list) {
155 		if (c->ident == ident)
156 			return c;
157 	}
158 	return NULL;
159 }
160 
161 static struct l2cap_chan *__l2cap_global_chan_by_addr(__le16 psm, bdaddr_t *src,
162 						      u8 src_type)
163 {
164 	struct l2cap_chan *c;
165 
166 	list_for_each_entry(c, &chan_list, global_l) {
167 		if (src_type == BDADDR_BREDR && c->src_type != BDADDR_BREDR)
168 			continue;
169 
170 		if (src_type != BDADDR_BREDR && c->src_type == BDADDR_BREDR)
171 			continue;
172 
173 		if (c->sport == psm && !bacmp(&c->src, src))
174 			return c;
175 	}
176 	return NULL;
177 }
178 
179 int l2cap_add_psm(struct l2cap_chan *chan, bdaddr_t *src, __le16 psm)
180 {
181 	int err;
182 
183 	write_lock(&chan_list_lock);
184 
185 	if (psm && __l2cap_global_chan_by_addr(psm, src, chan->src_type)) {
186 		err = -EADDRINUSE;
187 		goto done;
188 	}
189 
190 	if (psm) {
191 		chan->psm = psm;
192 		chan->sport = psm;
193 		err = 0;
194 	} else {
195 		u16 p, start, end, incr;
196 
197 		if (chan->src_type == BDADDR_BREDR) {
198 			start = L2CAP_PSM_DYN_START;
199 			end = L2CAP_PSM_AUTO_END;
200 			incr = 2;
201 		} else {
202 			start = L2CAP_PSM_LE_DYN_START;
203 			end = L2CAP_PSM_LE_DYN_END;
204 			incr = 1;
205 		}
206 
207 		err = -EINVAL;
208 		for (p = start; p <= end; p += incr)
209 			if (!__l2cap_global_chan_by_addr(cpu_to_le16(p), src,
210 							 chan->src_type)) {
211 				chan->psm   = cpu_to_le16(p);
212 				chan->sport = cpu_to_le16(p);
213 				err = 0;
214 				break;
215 			}
216 	}
217 
218 done:
219 	write_unlock(&chan_list_lock);
220 	return err;
221 }
222 EXPORT_SYMBOL_GPL(l2cap_add_psm);
223 
224 int l2cap_add_scid(struct l2cap_chan *chan,  __u16 scid)
225 {
226 	write_lock(&chan_list_lock);
227 
228 	/* Override the defaults (which are for conn-oriented) */
229 	chan->omtu = L2CAP_DEFAULT_MTU;
230 	chan->chan_type = L2CAP_CHAN_FIXED;
231 
232 	chan->scid = scid;
233 
234 	write_unlock(&chan_list_lock);
235 
236 	return 0;
237 }
238 
239 static u16 l2cap_alloc_cid(struct l2cap_conn *conn)
240 {
241 	u16 cid, dyn_end;
242 
243 	if (conn->hcon->type == LE_LINK)
244 		dyn_end = L2CAP_CID_LE_DYN_END;
245 	else
246 		dyn_end = L2CAP_CID_DYN_END;
247 
248 	for (cid = L2CAP_CID_DYN_START; cid <= dyn_end; cid++) {
249 		if (!__l2cap_get_chan_by_scid(conn, cid))
250 			return cid;
251 	}
252 
253 	return 0;
254 }
255 
256 static void l2cap_state_change(struct l2cap_chan *chan, int state)
257 {
258 	BT_DBG("chan %p %s -> %s", chan, state_to_string(chan->state),
259 	       state_to_string(state));
260 
261 	chan->state = state;
262 	chan->ops->state_change(chan, state, 0);
263 }
264 
265 static inline void l2cap_state_change_and_error(struct l2cap_chan *chan,
266 						int state, int err)
267 {
268 	chan->state = state;
269 	chan->ops->state_change(chan, chan->state, err);
270 }
271 
272 static inline void l2cap_chan_set_err(struct l2cap_chan *chan, int err)
273 {
274 	chan->ops->state_change(chan, chan->state, err);
275 }
276 
277 static void __set_retrans_timer(struct l2cap_chan *chan)
278 {
279 	if (!delayed_work_pending(&chan->monitor_timer) &&
280 	    chan->retrans_timeout) {
281 		l2cap_set_timer(chan, &chan->retrans_timer,
282 				msecs_to_jiffies(chan->retrans_timeout));
283 	}
284 }
285 
286 static void __set_monitor_timer(struct l2cap_chan *chan)
287 {
288 	__clear_retrans_timer(chan);
289 	if (chan->monitor_timeout) {
290 		l2cap_set_timer(chan, &chan->monitor_timer,
291 				msecs_to_jiffies(chan->monitor_timeout));
292 	}
293 }
294 
295 static struct sk_buff *l2cap_ertm_seq_in_queue(struct sk_buff_head *head,
296 					       u16 seq)
297 {
298 	struct sk_buff *skb;
299 
300 	skb_queue_walk(head, skb) {
301 		if (bt_cb(skb)->l2cap.txseq == seq)
302 			return skb;
303 	}
304 
305 	return NULL;
306 }
307 
308 /* ---- L2CAP sequence number lists ---- */
309 
310 /* For ERTM, ordered lists of sequence numbers must be tracked for
311  * SREJ requests that are received and for frames that are to be
312  * retransmitted. These seq_list functions implement a singly-linked
313  * list in an array, where membership in the list can also be checked
314  * in constant time. Items can also be added to the tail of the list
315  * and removed from the head in constant time, without further memory
316  * allocs or frees.
317  */
318 
319 static int l2cap_seq_list_init(struct l2cap_seq_list *seq_list, u16 size)
320 {
321 	size_t alloc_size, i;
322 
323 	/* Allocated size is a power of 2 to map sequence numbers
324 	 * (which may be up to 14 bits) in to a smaller array that is
325 	 * sized for the negotiated ERTM transmit windows.
326 	 */
327 	alloc_size = roundup_pow_of_two(size);
328 
329 	seq_list->list = kmalloc_array(alloc_size, sizeof(u16), GFP_KERNEL);
330 	if (!seq_list->list)
331 		return -ENOMEM;
332 
333 	seq_list->mask = alloc_size - 1;
334 	seq_list->head = L2CAP_SEQ_LIST_CLEAR;
335 	seq_list->tail = L2CAP_SEQ_LIST_CLEAR;
336 	for (i = 0; i < alloc_size; i++)
337 		seq_list->list[i] = L2CAP_SEQ_LIST_CLEAR;
338 
339 	return 0;
340 }
341 
342 static inline void l2cap_seq_list_free(struct l2cap_seq_list *seq_list)
343 {
344 	kfree(seq_list->list);
345 }
346 
347 static inline bool l2cap_seq_list_contains(struct l2cap_seq_list *seq_list,
348 					   u16 seq)
349 {
350 	/* Constant-time check for list membership */
351 	return seq_list->list[seq & seq_list->mask] != L2CAP_SEQ_LIST_CLEAR;
352 }
353 
354 static inline u16 l2cap_seq_list_pop(struct l2cap_seq_list *seq_list)
355 {
356 	u16 seq = seq_list->head;
357 	u16 mask = seq_list->mask;
358 
359 	seq_list->head = seq_list->list[seq & mask];
360 	seq_list->list[seq & mask] = L2CAP_SEQ_LIST_CLEAR;
361 
362 	if (seq_list->head == L2CAP_SEQ_LIST_TAIL) {
363 		seq_list->head = L2CAP_SEQ_LIST_CLEAR;
364 		seq_list->tail = L2CAP_SEQ_LIST_CLEAR;
365 	}
366 
367 	return seq;
368 }
369 
370 static void l2cap_seq_list_clear(struct l2cap_seq_list *seq_list)
371 {
372 	u16 i;
373 
374 	if (seq_list->head == L2CAP_SEQ_LIST_CLEAR)
375 		return;
376 
377 	for (i = 0; i <= seq_list->mask; i++)
378 		seq_list->list[i] = L2CAP_SEQ_LIST_CLEAR;
379 
380 	seq_list->head = L2CAP_SEQ_LIST_CLEAR;
381 	seq_list->tail = L2CAP_SEQ_LIST_CLEAR;
382 }
383 
384 static void l2cap_seq_list_append(struct l2cap_seq_list *seq_list, u16 seq)
385 {
386 	u16 mask = seq_list->mask;
387 
388 	/* All appends happen in constant time */
389 
390 	if (seq_list->list[seq & mask] != L2CAP_SEQ_LIST_CLEAR)
391 		return;
392 
393 	if (seq_list->tail == L2CAP_SEQ_LIST_CLEAR)
394 		seq_list->head = seq;
395 	else
396 		seq_list->list[seq_list->tail & mask] = seq;
397 
398 	seq_list->tail = seq;
399 	seq_list->list[seq & mask] = L2CAP_SEQ_LIST_TAIL;
400 }
401 
402 static void l2cap_chan_timeout(struct work_struct *work)
403 {
404 	struct l2cap_chan *chan = container_of(work, struct l2cap_chan,
405 					       chan_timer.work);
406 	struct l2cap_conn *conn = chan->conn;
407 	int reason;
408 
409 	BT_DBG("chan %p state %s", chan, state_to_string(chan->state));
410 
411 	if (test_bit(FLAG_DEL, &chan->flags)) {
412 		l2cap_chan_put(chan);
413 		return;
414 	}
415 
416 	mutex_lock(&conn->lock);
417 	/* __set_chan_timer() calls l2cap_chan_hold(chan) while scheduling
418 	 * this work. No need to call l2cap_chan_hold(chan) here again.
419 	 */
420 	l2cap_chan_lock(chan);
421 
422 	if (test_bit(FLAG_DEL, &chan->flags))
423 		goto unlock;
424 
425 	if (chan->state == BT_CONNECTED || chan->state == BT_CONFIG)
426 		reason = ECONNREFUSED;
427 	else if (chan->state == BT_CONNECT &&
428 		 chan->sec_level != BT_SECURITY_SDP)
429 		reason = ECONNREFUSED;
430 	else
431 		reason = ETIMEDOUT;
432 
433 	l2cap_chan_close(chan, reason);
434 
435 	chan->ops->close(chan);
436 
437 unlock:
438 	l2cap_chan_unlock(chan);
439 	mutex_unlock(&conn->lock);
440 	l2cap_chan_put(chan);
441 }
442 
443 struct l2cap_chan *l2cap_chan_create(void)
444 {
445 	struct l2cap_chan *chan;
446 
447 	chan = kzalloc_obj(*chan, GFP_ATOMIC);
448 	if (!chan)
449 		return NULL;
450 
451 	skb_queue_head_init(&chan->tx_q);
452 	skb_queue_head_init(&chan->srej_q);
453 	mutex_init(&chan->lock);
454 
455 	/* Set default lock nesting level */
456 	atomic_set(&chan->nesting, L2CAP_NESTING_NORMAL);
457 
458 	/* Available receive buffer space is initially unknown */
459 	chan->rx_avail = -1;
460 
461 	write_lock(&chan_list_lock);
462 	list_add(&chan->global_l, &chan_list);
463 	write_unlock(&chan_list_lock);
464 
465 	INIT_DELAYED_WORK(&chan->chan_timer, l2cap_chan_timeout);
466 	INIT_DELAYED_WORK(&chan->retrans_timer, l2cap_retrans_timeout);
467 	INIT_DELAYED_WORK(&chan->monitor_timer, l2cap_monitor_timeout);
468 	INIT_DELAYED_WORK(&chan->ack_timer, l2cap_ack_timeout);
469 
470 	chan->state = BT_OPEN;
471 
472 	kref_init(&chan->kref);
473 
474 	/* This flag is cleared in l2cap_chan_ready() */
475 	set_bit(CONF_NOT_COMPLETE, &chan->conf_state);
476 
477 	BT_DBG("chan %p", chan);
478 
479 	return chan;
480 }
481 EXPORT_SYMBOL_GPL(l2cap_chan_create);
482 
483 static void l2cap_chan_destroy(struct kref *kref)
484 {
485 	struct l2cap_chan *chan = container_of(kref, struct l2cap_chan, kref);
486 
487 	BT_DBG("chan %p", chan);
488 
489 	write_lock(&chan_list_lock);
490 	list_del(&chan->global_l);
491 	write_unlock(&chan_list_lock);
492 
493 	if (chan->conn)
494 		l2cap_conn_put(chan->conn);
495 
496 	kfree(chan);
497 }
498 
499 void l2cap_chan_hold(struct l2cap_chan *c)
500 {
501 	BT_DBG("chan %p orig refcnt %u", c, kref_read(&c->kref));
502 
503 	kref_get(&c->kref);
504 }
505 EXPORT_SYMBOL_GPL(l2cap_chan_hold);
506 
507 struct l2cap_chan *l2cap_chan_hold_unless_zero(struct l2cap_chan *c)
508 {
509 	BT_DBG("chan %p orig refcnt %u", c, kref_read(&c->kref));
510 
511 	if (!kref_get_unless_zero(&c->kref))
512 		return NULL;
513 
514 	return c;
515 }
516 
517 void l2cap_chan_put(struct l2cap_chan *c)
518 {
519 	BT_DBG("chan %p orig refcnt %u", c, kref_read(&c->kref));
520 
521 	kref_put(&c->kref, l2cap_chan_destroy);
522 }
523 EXPORT_SYMBOL_GPL(l2cap_chan_put);
524 
525 /* Initialise @chan with default values, inheriting from the parent channel
526  * @pchan when it is given.
527  */
528 void l2cap_chan_set_defaults(struct l2cap_chan *chan, struct l2cap_chan *pchan)
529 {
530 	chan->fcs  = L2CAP_FCS_CRC16;
531 	chan->max_tx = L2CAP_DEFAULT_MAX_TX;
532 	chan->tx_win = L2CAP_DEFAULT_TX_WINDOW;
533 	chan->tx_win_max = L2CAP_DEFAULT_TX_WINDOW;
534 	chan->remote_max_tx = chan->max_tx;
535 	chan->remote_tx_win = chan->tx_win;
536 	chan->ack_win = L2CAP_DEFAULT_TX_WINDOW;
537 	chan->sec_level = BT_SECURITY_LOW;
538 	chan->flush_to = L2CAP_DEFAULT_FLUSH_TO;
539 	chan->retrans_timeout = L2CAP_DEFAULT_RETRANS_TO;
540 	chan->monitor_timeout = L2CAP_DEFAULT_MONITOR_TO;
541 
542 	if (pchan) {
543 		BT_DBG("chan %p pchan %p", chan, pchan);
544 
545 		chan->chan_type = pchan->chan_type;
546 		chan->imtu = pchan->imtu;
547 		chan->omtu = pchan->omtu;
548 		chan->mode = pchan->mode;
549 		chan->fcs = pchan->fcs;
550 		chan->max_tx = pchan->max_tx;
551 		chan->tx_win = pchan->tx_win;
552 		chan->tx_win_max = pchan->tx_win_max;
553 		chan->sec_level = pchan->sec_level;
554 		chan->conf_state = pchan->conf_state;
555 		chan->flags = pchan->flags;
556 		chan->tx_credits = pchan->tx_credits;
557 		chan->rx_credits = pchan->rx_credits;
558 
559 		if (chan->chan_type == L2CAP_CHAN_FIXED) {
560 			chan->scid = pchan->scid;
561 			chan->dcid = pchan->scid;
562 		}
563 
564 		return;
565 	}
566 
567 	chan->conf_state = 0;
568 	set_bit(CONF_NOT_COMPLETE, &chan->conf_state);
569 
570 	set_bit(FLAG_FORCE_ACTIVE, &chan->flags);
571 }
572 EXPORT_SYMBOL_GPL(l2cap_chan_set_defaults);
573 
574 static __u16 l2cap_le_rx_credits(struct l2cap_chan *chan)
575 {
576 	size_t sdu_len = chan->sdu ? chan->sdu->len : 0;
577 
578 	if (chan->mps == 0)
579 		return 0;
580 
581 	/* If we don't know the available space in the receiver buffer, give
582 	 * enough credits for a full packet.
583 	 */
584 	if (chan->rx_avail == -1)
585 		return (chan->imtu / chan->mps) + 1;
586 
587 	/* If we know how much space is available in the receive buffer, give
588 	 * out as many credits as would fill the buffer.
589 	 */
590 	if (chan->rx_avail <= sdu_len)
591 		return 0;
592 
593 	return DIV_ROUND_UP(chan->rx_avail - sdu_len, chan->mps);
594 }
595 
596 static void l2cap_le_flowctl_init(struct l2cap_chan *chan, u16 tx_credits)
597 {
598 	chan->sdu = NULL;
599 	chan->sdu_last_frag = NULL;
600 	chan->sdu_len = 0;
601 	chan->tx_credits = tx_credits;
602 	/* Derive MPS from connection MTU to stop HCI fragmentation */
603 	chan->mps = min_t(u16, chan->imtu, chan->conn->mtu - L2CAP_HDR_SIZE);
604 	chan->rx_credits = l2cap_le_rx_credits(chan);
605 
606 	skb_queue_head_init(&chan->tx_q);
607 }
608 
609 static void l2cap_ecred_init(struct l2cap_chan *chan, u16 tx_credits)
610 {
611 	l2cap_le_flowctl_init(chan, tx_credits);
612 
613 	/* L2CAP implementations shall support a minimum MPS of 64 octets */
614 	if (chan->mps < L2CAP_ECRED_MIN_MPS) {
615 		chan->mps = L2CAP_ECRED_MIN_MPS;
616 		chan->rx_credits = l2cap_le_rx_credits(chan);
617 	}
618 }
619 
620 void __l2cap_chan_add(struct l2cap_conn *conn, struct l2cap_chan *chan)
621 {
622 	BT_DBG("conn %p, psm 0x%2.2x, dcid 0x%4.4x", conn,
623 	       __le16_to_cpu(chan->psm), chan->dcid);
624 
625 	conn->disc_reason = HCI_ERROR_REMOTE_USER_TERM;
626 
627 	chan->conn = l2cap_conn_get(conn);
628 
629 	switch (chan->chan_type) {
630 	case L2CAP_CHAN_CONN_ORIENTED:
631 		/* Alloc CID for connection-oriented socket */
632 		chan->scid = l2cap_alloc_cid(conn);
633 		if (conn->hcon->type == ACL_LINK)
634 			chan->omtu = L2CAP_DEFAULT_MTU;
635 		break;
636 
637 	case L2CAP_CHAN_CONN_LESS:
638 		/* Connectionless socket */
639 		chan->scid = L2CAP_CID_CONN_LESS;
640 		chan->dcid = L2CAP_CID_CONN_LESS;
641 		chan->omtu = L2CAP_DEFAULT_MTU;
642 		break;
643 
644 	case L2CAP_CHAN_FIXED:
645 		/* Caller will set CID and CID specific MTU values */
646 		break;
647 
648 	default:
649 		/* Raw socket can send/recv signalling messages only */
650 		chan->scid = L2CAP_CID_SIGNALING;
651 		chan->dcid = L2CAP_CID_SIGNALING;
652 		chan->omtu = L2CAP_DEFAULT_MTU;
653 	}
654 
655 	chan->local_id		= L2CAP_BESTEFFORT_ID;
656 	chan->local_stype	= L2CAP_SERV_BESTEFFORT;
657 	chan->local_msdu	= L2CAP_DEFAULT_MAX_SDU_SIZE;
658 	chan->local_sdu_itime	= L2CAP_DEFAULT_SDU_ITIME;
659 	chan->local_acc_lat	= L2CAP_DEFAULT_ACC_LAT;
660 	chan->local_flush_to	= L2CAP_EFS_DEFAULT_FLUSH_TO;
661 
662 	l2cap_chan_hold(chan);
663 
664 	/* Only keep a reference for fixed channels if they requested it */
665 	if (chan->chan_type != L2CAP_CHAN_FIXED ||
666 	    test_bit(FLAG_HOLD_HCI_CONN, &chan->flags))
667 		hci_conn_hold(conn->hcon);
668 
669 	/* Append to the list since the order matters for ECRED */
670 	list_add_tail(&chan->list, &conn->chan_l);
671 }
672 
673 void l2cap_chan_add(struct l2cap_conn *conn, struct l2cap_chan *chan)
674 {
675 	mutex_lock(&conn->lock);
676 	__l2cap_chan_add(conn, chan);
677 	mutex_unlock(&conn->lock);
678 }
679 
680 void l2cap_chan_del(struct l2cap_chan *chan, int err)
681 {
682 	__clear_chan_timer(chan);
683 
684 	BT_DBG("chan %p, err %d, state %s", chan, err,
685 	       state_to_string(chan->state));
686 
687 	chan->ops->teardown(chan, err);
688 
689 	if (!test_and_set_bit(FLAG_DEL, &chan->flags)) {
690 		/* Delete from channel list */
691 		list_del(&chan->list);
692 
693 		l2cap_chan_put(chan);
694 
695 		/* Reference was only held for non-fixed channels or
696 		 * fixed channels that explicitly requested it using the
697 		 * FLAG_HOLD_HCI_CONN flag.
698 		 */
699 		if (chan->chan_type != L2CAP_CHAN_FIXED ||
700 		    test_bit(FLAG_HOLD_HCI_CONN, &chan->flags))
701 			hci_conn_drop(chan->conn->hcon);
702 	}
703 
704 	if (test_bit(CONF_NOT_COMPLETE, &chan->conf_state))
705 		return;
706 
707 	switch (chan->mode) {
708 	case L2CAP_MODE_BASIC:
709 		break;
710 
711 	case L2CAP_MODE_LE_FLOWCTL:
712 	case L2CAP_MODE_EXT_FLOWCTL:
713 		skb_queue_purge(&chan->tx_q);
714 		break;
715 
716 	case L2CAP_MODE_ERTM:
717 		__clear_retrans_timer(chan);
718 		__clear_monitor_timer(chan);
719 		__clear_ack_timer(chan);
720 
721 		skb_queue_purge(&chan->srej_q);
722 
723 		l2cap_seq_list_free(&chan->srej_list);
724 		l2cap_seq_list_free(&chan->retrans_list);
725 		fallthrough;
726 
727 	case L2CAP_MODE_STREAMING:
728 		skb_queue_purge(&chan->tx_q);
729 		break;
730 	}
731 }
732 EXPORT_SYMBOL_GPL(l2cap_chan_del);
733 
734 static void __l2cap_chan_list_id(struct l2cap_conn *conn, u16 id,
735 				 l2cap_chan_func_t func, void *data)
736 {
737 	struct l2cap_chan *chan, *l;
738 
739 	list_for_each_entry_safe(chan, l, &conn->chan_l, list) {
740 		if (chan->ident == id)
741 			func(chan, data);
742 	}
743 }
744 
745 static void __l2cap_chan_list(struct l2cap_conn *conn, l2cap_chan_func_t func,
746 			      void *data)
747 {
748 	struct l2cap_chan *chan;
749 
750 	list_for_each_entry(chan, &conn->chan_l, list) {
751 		func(chan, data);
752 	}
753 }
754 
755 void l2cap_chan_list(struct l2cap_conn *conn, l2cap_chan_func_t func,
756 		     void *data)
757 {
758 	if (!conn)
759 		return;
760 
761 	mutex_lock(&conn->lock);
762 	__l2cap_chan_list(conn, func, data);
763 	mutex_unlock(&conn->lock);
764 }
765 
766 EXPORT_SYMBOL_GPL(l2cap_chan_list);
767 
768 static void l2cap_conn_update_id_addr(struct work_struct *work)
769 {
770 	struct l2cap_conn *conn = container_of(work, struct l2cap_conn,
771 					       id_addr_timer.work);
772 	struct hci_conn *hcon = conn->hcon;
773 	struct l2cap_chan *chan;
774 
775 	mutex_lock(&conn->lock);
776 
777 	list_for_each_entry(chan, &conn->chan_l, list) {
778 		l2cap_chan_lock(chan);
779 		bacpy(&chan->dst, &hcon->dst);
780 		chan->dst_type = bdaddr_dst_type(hcon);
781 		l2cap_chan_unlock(chan);
782 	}
783 
784 	mutex_unlock(&conn->lock);
785 }
786 
787 static void l2cap_chan_le_connect_reject(struct l2cap_chan *chan)
788 {
789 	struct l2cap_conn *conn = chan->conn;
790 	struct l2cap_le_conn_rsp rsp;
791 	u16 result;
792 
793 	if (test_bit(FLAG_DEFER_SETUP, &chan->flags))
794 		result = L2CAP_CR_LE_AUTHORIZATION;
795 	else
796 		result = L2CAP_CR_LE_BAD_PSM;
797 
798 	l2cap_state_change(chan, BT_DISCONN);
799 
800 	rsp.dcid    = cpu_to_le16(chan->scid);
801 	rsp.mtu     = cpu_to_le16(chan->imtu);
802 	rsp.mps     = cpu_to_le16(chan->mps);
803 	rsp.credits = cpu_to_le16(chan->rx_credits);
804 	rsp.result  = cpu_to_le16(result);
805 
806 	l2cap_send_cmd(conn, chan->ident, L2CAP_LE_CONN_RSP, sizeof(rsp),
807 		       &rsp);
808 }
809 
810 static void l2cap_chan_ecred_connect_reject(struct l2cap_chan *chan)
811 {
812 	l2cap_state_change(chan, BT_DISCONN);
813 
814 	__l2cap_ecred_conn_rsp_defer(chan);
815 }
816 
817 static void l2cap_chan_connect_reject(struct l2cap_chan *chan)
818 {
819 	struct l2cap_conn *conn = chan->conn;
820 	struct l2cap_conn_rsp rsp;
821 	u16 result;
822 
823 	if (test_bit(FLAG_DEFER_SETUP, &chan->flags))
824 		result = L2CAP_CR_SEC_BLOCK;
825 	else
826 		result = L2CAP_CR_BAD_PSM;
827 
828 	l2cap_state_change(chan, BT_DISCONN);
829 
830 	rsp.scid   = cpu_to_le16(chan->dcid);
831 	rsp.dcid   = cpu_to_le16(chan->scid);
832 	rsp.result = cpu_to_le16(result);
833 	rsp.status = cpu_to_le16(L2CAP_CS_NO_INFO);
834 
835 	l2cap_send_cmd(conn, chan->ident, L2CAP_CONN_RSP, sizeof(rsp), &rsp);
836 }
837 
838 void l2cap_chan_close(struct l2cap_chan *chan, int reason)
839 {
840 	struct l2cap_conn *conn = chan->conn;
841 
842 	BT_DBG("chan %p state %s", chan, state_to_string(chan->state));
843 
844 	switch (chan->state) {
845 	case BT_LISTEN:
846 		chan->ops->teardown(chan, 0);
847 		break;
848 
849 	case BT_CONNECTED:
850 	case BT_CONFIG:
851 		if (chan->chan_type == L2CAP_CHAN_CONN_ORIENTED) {
852 			__set_chan_timer(chan, chan->ops->get_sndtimeo(chan));
853 			l2cap_send_disconn_req(chan, reason);
854 		} else
855 			l2cap_chan_del(chan, reason);
856 		break;
857 
858 	case BT_CONNECT2:
859 		if (chan->chan_type == L2CAP_CHAN_CONN_ORIENTED) {
860 			if (conn->hcon->type == ACL_LINK)
861 				l2cap_chan_connect_reject(chan);
862 			else if (conn->hcon->type == LE_LINK) {
863 				switch (chan->mode) {
864 				case L2CAP_MODE_LE_FLOWCTL:
865 					l2cap_chan_le_connect_reject(chan);
866 					break;
867 				case L2CAP_MODE_EXT_FLOWCTL:
868 					l2cap_chan_ecred_connect_reject(chan);
869 					return;
870 				}
871 			}
872 		}
873 
874 		l2cap_chan_del(chan, reason);
875 		break;
876 
877 	case BT_CONNECT:
878 	case BT_DISCONN:
879 		l2cap_chan_del(chan, reason);
880 		break;
881 
882 	default:
883 		chan->ops->teardown(chan, 0);
884 		break;
885 	}
886 }
887 EXPORT_SYMBOL(l2cap_chan_close);
888 
889 static inline u8 l2cap_get_auth_type(struct l2cap_chan *chan)
890 {
891 	switch (chan->chan_type) {
892 	case L2CAP_CHAN_RAW:
893 		switch (chan->sec_level) {
894 		case BT_SECURITY_HIGH:
895 		case BT_SECURITY_FIPS:
896 			return HCI_AT_DEDICATED_BONDING_MITM;
897 		case BT_SECURITY_MEDIUM:
898 			return HCI_AT_DEDICATED_BONDING;
899 		default:
900 			return HCI_AT_NO_BONDING;
901 		}
902 		break;
903 	case L2CAP_CHAN_CONN_LESS:
904 		if (chan->psm == cpu_to_le16(L2CAP_PSM_3DSP)) {
905 			if (chan->sec_level == BT_SECURITY_LOW)
906 				chan->sec_level = BT_SECURITY_SDP;
907 		}
908 		if (chan->sec_level == BT_SECURITY_HIGH ||
909 		    chan->sec_level == BT_SECURITY_FIPS)
910 			return HCI_AT_NO_BONDING_MITM;
911 		else
912 			return HCI_AT_NO_BONDING;
913 		break;
914 	case L2CAP_CHAN_CONN_ORIENTED:
915 		if (chan->psm == cpu_to_le16(L2CAP_PSM_SDP)) {
916 			if (chan->sec_level == BT_SECURITY_LOW)
917 				chan->sec_level = BT_SECURITY_SDP;
918 
919 			if (chan->sec_level == BT_SECURITY_HIGH ||
920 			    chan->sec_level == BT_SECURITY_FIPS)
921 				return HCI_AT_NO_BONDING_MITM;
922 			else
923 				return HCI_AT_NO_BONDING;
924 		}
925 		fallthrough;
926 
927 	default:
928 		switch (chan->sec_level) {
929 		case BT_SECURITY_HIGH:
930 		case BT_SECURITY_FIPS:
931 			return HCI_AT_GENERAL_BONDING_MITM;
932 		case BT_SECURITY_MEDIUM:
933 			return HCI_AT_GENERAL_BONDING;
934 		default:
935 			return HCI_AT_NO_BONDING;
936 		}
937 		break;
938 	}
939 }
940 
941 /* Service level security */
942 int l2cap_chan_check_security(struct l2cap_chan *chan, bool initiator)
943 {
944 	struct l2cap_conn *conn = chan->conn;
945 	__u8 auth_type;
946 
947 	if (conn->hcon->type == LE_LINK)
948 		return smp_conn_security(conn->hcon, chan->sec_level);
949 
950 	auth_type = l2cap_get_auth_type(chan);
951 
952 	return hci_conn_security(conn->hcon, chan->sec_level, auth_type,
953 				 initiator);
954 }
955 
956 static int l2cap_get_ident(struct l2cap_conn *conn)
957 {
958 	u8 max;
959 	int ident;
960 
961 	/* LE link does not support tools like l2ping so use the full range */
962 	if (conn->hcon->type == LE_LINK)
963 		max = 255;
964 	/* Get next available identificator.
965 	 *    1 - 128 are used by kernel.
966 	 *  129 - 199 are reserved.
967 	 *  200 - 254 are used by utilities like l2ping, etc.
968 	 */
969 	else
970 		max = 128;
971 
972 	/* Allocate ident using min as last used + 1 (cyclic) */
973 	ident = ida_alloc_range(&conn->tx_ida, READ_ONCE(conn->tx_ident) + 1,
974 				max, GFP_ATOMIC);
975 	/* Force min 1 to start over */
976 	if (ident <= 0) {
977 		ident = ida_alloc_range(&conn->tx_ida, 1, max, GFP_ATOMIC);
978 		if (ident <= 0) {
979 			/* If all idents are in use, log an error, this is
980 			 * extremely unlikely to happen and would indicate a bug
981 			 * in the code that idents are not being freed properly.
982 			 */
983 			BT_ERR("Unable to allocate ident: %d", ident);
984 			return 0;
985 		}
986 	}
987 
988 	WRITE_ONCE(conn->tx_ident, ident);
989 
990 	return ident;
991 }
992 
993 static void l2cap_send_acl(struct l2cap_conn *conn, struct sk_buff *skb,
994 			   u8 flags)
995 {
996 	/* Check if the hcon still valid before attempting to send */
997 	if (hci_conn_valid(conn->hcon->hdev, conn->hcon))
998 		hci_send_acl(conn->hchan, skb, flags);
999 	else
1000 		kfree_skb(skb);
1001 }
1002 
1003 static void l2cap_send_cmd(struct l2cap_conn *conn, u8 ident, u8 code, u16 len,
1004 			   void *data)
1005 {
1006 	struct sk_buff *skb = l2cap_build_cmd(conn, code, ident, len, data);
1007 	u8 flags;
1008 
1009 	BT_DBG("code 0x%2.2x", code);
1010 
1011 	if (!skb)
1012 		return;
1013 
1014 	/* Use NO_FLUSH if supported or we have an LE link (which does
1015 	 * not support auto-flushing packets) */
1016 	if (lmp_no_flush_capable(conn->hcon->hdev) ||
1017 	    conn->hcon->type == LE_LINK)
1018 		flags = ACL_START_NO_FLUSH;
1019 	else
1020 		flags = ACL_START;
1021 
1022 	bt_cb(skb)->force_active = BT_POWER_FORCE_ACTIVE_ON;
1023 	skb->priority = HCI_PRIO_MAX;
1024 
1025 	l2cap_send_acl(conn, skb, flags);
1026 }
1027 
1028 static void l2cap_do_send(struct l2cap_chan *chan, struct sk_buff *skb)
1029 {
1030 	struct hci_conn *hcon = chan->conn->hcon;
1031 	u16 flags;
1032 
1033 	BT_DBG("chan %p, skb %p len %d priority %u", chan, skb, skb->len,
1034 	       skb->priority);
1035 
1036 	/* Use NO_FLUSH for LE links (where this is the only option) or
1037 	 * if the BR/EDR link supports it and flushing has not been
1038 	 * explicitly requested (through FLAG_FLUSHABLE).
1039 	 */
1040 	if (hcon->type == LE_LINK ||
1041 	    (!test_bit(FLAG_FLUSHABLE, &chan->flags) &&
1042 	     lmp_no_flush_capable(hcon->hdev)))
1043 		flags = ACL_START_NO_FLUSH;
1044 	else
1045 		flags = ACL_START;
1046 
1047 	bt_cb(skb)->force_active = test_bit(FLAG_FORCE_ACTIVE, &chan->flags);
1048 	hci_send_acl(chan->conn->hchan, skb, flags);
1049 }
1050 
1051 static void __unpack_enhanced_control(u16 enh, struct l2cap_ctrl *control)
1052 {
1053 	control->reqseq = (enh & L2CAP_CTRL_REQSEQ) >> L2CAP_CTRL_REQSEQ_SHIFT;
1054 	control->final = (enh & L2CAP_CTRL_FINAL) >> L2CAP_CTRL_FINAL_SHIFT;
1055 
1056 	if (enh & L2CAP_CTRL_FRAME_TYPE) {
1057 		/* S-Frame */
1058 		control->sframe = 1;
1059 		control->poll = (enh & L2CAP_CTRL_POLL) >> L2CAP_CTRL_POLL_SHIFT;
1060 		control->super = (enh & L2CAP_CTRL_SUPERVISE) >> L2CAP_CTRL_SUPER_SHIFT;
1061 
1062 		control->sar = 0;
1063 		control->txseq = 0;
1064 	} else {
1065 		/* I-Frame */
1066 		control->sframe = 0;
1067 		control->sar = (enh & L2CAP_CTRL_SAR) >> L2CAP_CTRL_SAR_SHIFT;
1068 		control->txseq = (enh & L2CAP_CTRL_TXSEQ) >> L2CAP_CTRL_TXSEQ_SHIFT;
1069 
1070 		control->poll = 0;
1071 		control->super = 0;
1072 	}
1073 }
1074 
1075 static void __unpack_extended_control(u32 ext, struct l2cap_ctrl *control)
1076 {
1077 	control->reqseq = (ext & L2CAP_EXT_CTRL_REQSEQ) >> L2CAP_EXT_CTRL_REQSEQ_SHIFT;
1078 	control->final = (ext & L2CAP_EXT_CTRL_FINAL) >> L2CAP_EXT_CTRL_FINAL_SHIFT;
1079 
1080 	if (ext & L2CAP_EXT_CTRL_FRAME_TYPE) {
1081 		/* S-Frame */
1082 		control->sframe = 1;
1083 		control->poll = (ext & L2CAP_EXT_CTRL_POLL) >> L2CAP_EXT_CTRL_POLL_SHIFT;
1084 		control->super = (ext & L2CAP_EXT_CTRL_SUPERVISE) >> L2CAP_EXT_CTRL_SUPER_SHIFT;
1085 
1086 		control->sar = 0;
1087 		control->txseq = 0;
1088 	} else {
1089 		/* I-Frame */
1090 		control->sframe = 0;
1091 		control->sar = (ext & L2CAP_EXT_CTRL_SAR) >> L2CAP_EXT_CTRL_SAR_SHIFT;
1092 		control->txseq = (ext & L2CAP_EXT_CTRL_TXSEQ) >> L2CAP_EXT_CTRL_TXSEQ_SHIFT;
1093 
1094 		control->poll = 0;
1095 		control->super = 0;
1096 	}
1097 }
1098 
1099 static inline void __unpack_control(struct l2cap_chan *chan,
1100 				    struct sk_buff *skb)
1101 {
1102 	if (test_bit(FLAG_EXT_CTRL, &chan->flags)) {
1103 		__unpack_extended_control(get_unaligned_le32(skb->data),
1104 					  &bt_cb(skb)->l2cap);
1105 		skb_pull(skb, L2CAP_EXT_CTRL_SIZE);
1106 	} else {
1107 		__unpack_enhanced_control(get_unaligned_le16(skb->data),
1108 					  &bt_cb(skb)->l2cap);
1109 		skb_pull(skb, L2CAP_ENH_CTRL_SIZE);
1110 	}
1111 }
1112 
1113 static u32 __pack_extended_control(struct l2cap_ctrl *control)
1114 {
1115 	u32 packed;
1116 
1117 	packed = control->reqseq << L2CAP_EXT_CTRL_REQSEQ_SHIFT;
1118 	packed |= control->final << L2CAP_EXT_CTRL_FINAL_SHIFT;
1119 
1120 	if (control->sframe) {
1121 		packed |= control->poll << L2CAP_EXT_CTRL_POLL_SHIFT;
1122 		packed |= control->super << L2CAP_EXT_CTRL_SUPER_SHIFT;
1123 		packed |= L2CAP_EXT_CTRL_FRAME_TYPE;
1124 	} else {
1125 		packed |= control->sar << L2CAP_EXT_CTRL_SAR_SHIFT;
1126 		packed |= control->txseq << L2CAP_EXT_CTRL_TXSEQ_SHIFT;
1127 	}
1128 
1129 	return packed;
1130 }
1131 
1132 static u16 __pack_enhanced_control(struct l2cap_ctrl *control)
1133 {
1134 	u16 packed;
1135 
1136 	packed = control->reqseq << L2CAP_CTRL_REQSEQ_SHIFT;
1137 	packed |= control->final << L2CAP_CTRL_FINAL_SHIFT;
1138 
1139 	if (control->sframe) {
1140 		packed |= control->poll << L2CAP_CTRL_POLL_SHIFT;
1141 		packed |= control->super << L2CAP_CTRL_SUPER_SHIFT;
1142 		packed |= L2CAP_CTRL_FRAME_TYPE;
1143 	} else {
1144 		packed |= control->sar << L2CAP_CTRL_SAR_SHIFT;
1145 		packed |= control->txseq << L2CAP_CTRL_TXSEQ_SHIFT;
1146 	}
1147 
1148 	return packed;
1149 }
1150 
1151 static inline void __pack_control(struct l2cap_chan *chan,
1152 				  struct l2cap_ctrl *control,
1153 				  struct sk_buff *skb)
1154 {
1155 	if (test_bit(FLAG_EXT_CTRL, &chan->flags)) {
1156 		put_unaligned_le32(__pack_extended_control(control),
1157 				   skb->data + L2CAP_HDR_SIZE);
1158 	} else {
1159 		put_unaligned_le16(__pack_enhanced_control(control),
1160 				   skb->data + L2CAP_HDR_SIZE);
1161 	}
1162 }
1163 
1164 static inline unsigned int __ertm_hdr_size(struct l2cap_chan *chan)
1165 {
1166 	if (test_bit(FLAG_EXT_CTRL, &chan->flags))
1167 		return L2CAP_EXT_HDR_SIZE;
1168 	else
1169 		return L2CAP_ENH_HDR_SIZE;
1170 }
1171 
1172 static struct sk_buff *l2cap_create_sframe_pdu(struct l2cap_chan *chan,
1173 					       u32 control)
1174 {
1175 	struct sk_buff *skb;
1176 	struct l2cap_hdr *lh;
1177 	int hlen = __ertm_hdr_size(chan);
1178 
1179 	if (chan->fcs == L2CAP_FCS_CRC16)
1180 		hlen += L2CAP_FCS_SIZE;
1181 
1182 	skb = bt_skb_alloc(hlen, GFP_KERNEL);
1183 
1184 	if (!skb)
1185 		return ERR_PTR(-ENOMEM);
1186 
1187 	lh = skb_put(skb, L2CAP_HDR_SIZE);
1188 	lh->len = cpu_to_le16(hlen - L2CAP_HDR_SIZE);
1189 	lh->cid = cpu_to_le16(chan->dcid);
1190 
1191 	if (test_bit(FLAG_EXT_CTRL, &chan->flags))
1192 		put_unaligned_le32(control, skb_put(skb, L2CAP_EXT_CTRL_SIZE));
1193 	else
1194 		put_unaligned_le16(control, skb_put(skb, L2CAP_ENH_CTRL_SIZE));
1195 
1196 	if (chan->fcs == L2CAP_FCS_CRC16) {
1197 		u16 fcs = crc16(0, (u8 *)skb->data, skb->len);
1198 		put_unaligned_le16(fcs, skb_put(skb, L2CAP_FCS_SIZE));
1199 	}
1200 
1201 	skb->priority = HCI_PRIO_MAX;
1202 	return skb;
1203 }
1204 
1205 static void l2cap_send_sframe(struct l2cap_chan *chan,
1206 			      struct l2cap_ctrl *control)
1207 {
1208 	struct sk_buff *skb;
1209 	u32 control_field;
1210 
1211 	BT_DBG("chan %p, control %p", chan, control);
1212 
1213 	if (!control->sframe)
1214 		return;
1215 
1216 	if (test_and_clear_bit(CONN_SEND_FBIT, &chan->conn_state) &&
1217 	    !control->poll)
1218 		control->final = 1;
1219 
1220 	if (control->super == L2CAP_SUPER_RR)
1221 		clear_bit(CONN_RNR_SENT, &chan->conn_state);
1222 	else if (control->super == L2CAP_SUPER_RNR)
1223 		set_bit(CONN_RNR_SENT, &chan->conn_state);
1224 
1225 	if (control->super != L2CAP_SUPER_SREJ) {
1226 		chan->last_acked_seq = control->reqseq;
1227 		__clear_ack_timer(chan);
1228 	}
1229 
1230 	BT_DBG("reqseq %d, final %d, poll %d, super %d", control->reqseq,
1231 	       control->final, control->poll, control->super);
1232 
1233 	if (test_bit(FLAG_EXT_CTRL, &chan->flags))
1234 		control_field = __pack_extended_control(control);
1235 	else
1236 		control_field = __pack_enhanced_control(control);
1237 
1238 	skb = l2cap_create_sframe_pdu(chan, control_field);
1239 	if (!IS_ERR(skb))
1240 		l2cap_do_send(chan, skb);
1241 }
1242 
1243 static void l2cap_send_rr_or_rnr(struct l2cap_chan *chan, bool poll)
1244 {
1245 	struct l2cap_ctrl control;
1246 
1247 	BT_DBG("chan %p, poll %d", chan, poll);
1248 
1249 	memset(&control, 0, sizeof(control));
1250 	control.sframe = 1;
1251 	control.poll = poll;
1252 
1253 	if (test_bit(CONN_LOCAL_BUSY, &chan->conn_state))
1254 		control.super = L2CAP_SUPER_RNR;
1255 	else
1256 		control.super = L2CAP_SUPER_RR;
1257 
1258 	control.reqseq = chan->buffer_seq;
1259 	l2cap_send_sframe(chan, &control);
1260 }
1261 
1262 static inline int __l2cap_no_conn_pending(struct l2cap_chan *chan)
1263 {
1264 	if (chan->chan_type != L2CAP_CHAN_CONN_ORIENTED)
1265 		return true;
1266 
1267 	return !test_bit(CONF_CONNECT_PEND, &chan->conf_state);
1268 }
1269 
1270 void l2cap_send_conn_req(struct l2cap_chan *chan)
1271 {
1272 	struct l2cap_conn *conn = chan->conn;
1273 	struct l2cap_conn_req req;
1274 
1275 	req.scid = cpu_to_le16(chan->scid);
1276 	req.psm  = chan->psm;
1277 
1278 	chan->ident = l2cap_get_ident(conn);
1279 
1280 	set_bit(CONF_CONNECT_PEND, &chan->conf_state);
1281 
1282 	l2cap_send_cmd(conn, chan->ident, L2CAP_CONN_REQ, sizeof(req), &req);
1283 }
1284 
1285 static void l2cap_chan_ready(struct l2cap_chan *chan)
1286 {
1287 	/* The channel may have already been flagged as connected in
1288 	 * case of receiving data before the L2CAP info req/rsp
1289 	 * procedure is complete.
1290 	 */
1291 	if (chan->state == BT_CONNECTED)
1292 		return;
1293 
1294 	/* This clears all conf flags, including CONF_NOT_COMPLETE */
1295 	chan->conf_state = 0;
1296 	__clear_chan_timer(chan);
1297 
1298 	switch (chan->mode) {
1299 	case L2CAP_MODE_LE_FLOWCTL:
1300 	case L2CAP_MODE_EXT_FLOWCTL:
1301 		if (!chan->tx_credits)
1302 			chan->ops->suspend(chan);
1303 		break;
1304 	}
1305 
1306 	chan->state = BT_CONNECTED;
1307 
1308 	chan->ops->ready(chan);
1309 }
1310 
1311 static void l2cap_le_connect(struct l2cap_chan *chan)
1312 {
1313 	struct l2cap_conn *conn = chan->conn;
1314 	struct l2cap_le_conn_req req;
1315 
1316 	if (test_and_set_bit(FLAG_LE_CONN_REQ_SENT, &chan->flags))
1317 		return;
1318 
1319 	if (!chan->imtu)
1320 		chan->imtu = chan->conn->mtu;
1321 
1322 	l2cap_le_flowctl_init(chan, 0);
1323 
1324 	memset(&req, 0, sizeof(req));
1325 	req.psm     = chan->psm;
1326 	req.scid    = cpu_to_le16(chan->scid);
1327 	req.mtu     = cpu_to_le16(chan->imtu);
1328 	req.mps     = cpu_to_le16(chan->mps);
1329 	req.credits = cpu_to_le16(chan->rx_credits);
1330 
1331 	chan->ident = l2cap_get_ident(conn);
1332 
1333 	l2cap_send_cmd(conn, chan->ident, L2CAP_LE_CONN_REQ,
1334 		       sizeof(req), &req);
1335 }
1336 
1337 struct l2cap_ecred_conn_data {
1338 	struct {
1339 		struct l2cap_ecred_conn_req_hdr req;
1340 		__le16 scid[5];
1341 	} __packed pdu;
1342 	struct l2cap_chan *chan;
1343 	struct pid *pid;
1344 	int count;
1345 };
1346 
1347 static void l2cap_ecred_defer_connect(struct l2cap_chan *chan, void *data)
1348 {
1349 	struct l2cap_ecred_conn_data *conn = data;
1350 	struct pid *pid;
1351 
1352 	if (chan == conn->chan)
1353 		return;
1354 
1355 	if (!test_and_clear_bit(FLAG_DEFER_SETUP, &chan->flags))
1356 		return;
1357 
1358 	pid = chan->ops->get_peer_pid(chan);
1359 
1360 	/* Only add deferred channels with the same PID/PSM */
1361 	if (conn->pid != pid || chan->psm != conn->chan->psm || chan->ident ||
1362 	    chan->mode != L2CAP_MODE_EXT_FLOWCTL || chan->state != BT_CONNECT)
1363 		return;
1364 
1365 	if (test_and_set_bit(FLAG_ECRED_CONN_REQ_SENT, &chan->flags))
1366 		return;
1367 
1368 	l2cap_ecred_init(chan, 0);
1369 
1370 	/* Set the same ident so we can match on the rsp */
1371 	chan->ident = conn->chan->ident;
1372 
1373 	/* Include all channels deferred */
1374 	conn->pdu.scid[conn->count] = cpu_to_le16(chan->scid);
1375 
1376 	conn->count++;
1377 }
1378 
1379 static void l2cap_ecred_connect(struct l2cap_chan *chan)
1380 {
1381 	struct l2cap_conn *conn = chan->conn;
1382 	struct l2cap_ecred_conn_data data;
1383 
1384 	if (test_bit(FLAG_DEFER_SETUP, &chan->flags))
1385 		return;
1386 
1387 	if (test_and_set_bit(FLAG_ECRED_CONN_REQ_SENT, &chan->flags))
1388 		return;
1389 
1390 	l2cap_ecred_init(chan, 0);
1391 
1392 	memset(&data, 0, sizeof(data));
1393 	data.pdu.req.psm     = chan->psm;
1394 	data.pdu.req.mtu     = cpu_to_le16(chan->imtu);
1395 	data.pdu.req.mps     = cpu_to_le16(chan->mps);
1396 	data.pdu.req.credits = cpu_to_le16(chan->rx_credits);
1397 	data.pdu.scid[0]     = cpu_to_le16(chan->scid);
1398 
1399 	chan->ident = l2cap_get_ident(conn);
1400 
1401 	data.count = 1;
1402 	data.chan = chan;
1403 	data.pid = chan->ops->get_peer_pid(chan);
1404 
1405 	__l2cap_chan_list(conn, l2cap_ecred_defer_connect, &data);
1406 
1407 	l2cap_send_cmd(conn, chan->ident, L2CAP_ECRED_CONN_REQ,
1408 		       sizeof(data.pdu.req) + data.count * sizeof(__le16),
1409 		       &data.pdu);
1410 }
1411 
1412 static void l2cap_le_start(struct l2cap_chan *chan)
1413 {
1414 	struct l2cap_conn *conn = chan->conn;
1415 
1416 	if (!smp_conn_security(conn->hcon, chan->sec_level))
1417 		return;
1418 
1419 	if (!chan->psm) {
1420 		l2cap_chan_ready(chan);
1421 		return;
1422 	}
1423 
1424 	if (chan->state == BT_CONNECT) {
1425 		if (chan->mode == L2CAP_MODE_EXT_FLOWCTL)
1426 			l2cap_ecred_connect(chan);
1427 		else
1428 			l2cap_le_connect(chan);
1429 	}
1430 }
1431 
1432 static void l2cap_start_connection(struct l2cap_chan *chan)
1433 {
1434 	if (chan->conn->hcon->type == LE_LINK) {
1435 		l2cap_le_start(chan);
1436 	} else {
1437 		l2cap_send_conn_req(chan);
1438 	}
1439 }
1440 
1441 static void l2cap_request_info(struct l2cap_conn *conn)
1442 {
1443 	struct l2cap_info_req req;
1444 
1445 	if (conn->info_state & L2CAP_INFO_FEAT_MASK_REQ_SENT)
1446 		return;
1447 
1448 	req.type = cpu_to_le16(L2CAP_IT_FEAT_MASK);
1449 
1450 	conn->info_state |= L2CAP_INFO_FEAT_MASK_REQ_SENT;
1451 	conn->info_ident = l2cap_get_ident(conn);
1452 
1453 	schedule_delayed_work(&conn->info_timer, L2CAP_INFO_TIMEOUT);
1454 
1455 	l2cap_send_cmd(conn, conn->info_ident, L2CAP_INFO_REQ,
1456 		       sizeof(req), &req);
1457 }
1458 
1459 static bool l2cap_check_enc_key_size(struct hci_conn *hcon,
1460 				     struct l2cap_chan *chan)
1461 {
1462 	/* The minimum encryption key size needs to be enforced by the
1463 	 * host stack before establishing any L2CAP connections. The
1464 	 * specification in theory allows a minimum of 1, but to align
1465 	 * BR/EDR and LE transports, a minimum of 7 is chosen.
1466 	 *
1467 	 * This check might also be called for unencrypted connections
1468 	 * that have no key size requirements. Ensure that the link is
1469 	 * actually encrypted before enforcing a key size.
1470 	 */
1471 	int min_key_size = hcon->hdev->min_enc_key_size;
1472 
1473 	/* On FIPS security level, key size must be 16 bytes */
1474 	if (chan->sec_level == BT_SECURITY_FIPS)
1475 		min_key_size = 16;
1476 
1477 	return (!test_bit(HCI_CONN_ENCRYPT, &hcon->flags) ||
1478 		hcon->enc_key_size >= min_key_size);
1479 }
1480 
1481 static void l2cap_do_start(struct l2cap_chan *chan)
1482 {
1483 	struct l2cap_conn *conn = chan->conn;
1484 
1485 	if (conn->hcon->type == LE_LINK) {
1486 		l2cap_le_start(chan);
1487 		return;
1488 	}
1489 
1490 	if (!(conn->info_state & L2CAP_INFO_FEAT_MASK_REQ_SENT)) {
1491 		l2cap_request_info(conn);
1492 		return;
1493 	}
1494 
1495 	if (!(conn->info_state & L2CAP_INFO_FEAT_MASK_REQ_DONE))
1496 		return;
1497 
1498 	if (!l2cap_chan_check_security(chan, true) ||
1499 	    !__l2cap_no_conn_pending(chan))
1500 		return;
1501 
1502 	if (l2cap_check_enc_key_size(conn->hcon, chan))
1503 		l2cap_start_connection(chan);
1504 	else
1505 		__set_chan_timer(chan, L2CAP_DISC_TIMEOUT);
1506 }
1507 
1508 static inline int l2cap_mode_supported(__u8 mode, __u32 feat_mask)
1509 {
1510 	u32 local_feat_mask = l2cap_feat_mask;
1511 	if (!disable_ertm)
1512 		local_feat_mask |= L2CAP_FEAT_ERTM | L2CAP_FEAT_STREAMING;
1513 
1514 	switch (mode) {
1515 	case L2CAP_MODE_ERTM:
1516 		return L2CAP_FEAT_ERTM & feat_mask & local_feat_mask;
1517 	case L2CAP_MODE_STREAMING:
1518 		return L2CAP_FEAT_STREAMING & feat_mask & local_feat_mask;
1519 	default:
1520 		return 0x00;
1521 	}
1522 }
1523 
1524 static void l2cap_send_disconn_req(struct l2cap_chan *chan, int err)
1525 {
1526 	struct l2cap_conn *conn = chan->conn;
1527 	struct l2cap_disconn_req req;
1528 
1529 	if (!conn)
1530 		return;
1531 
1532 	if (chan->mode == L2CAP_MODE_ERTM && chan->state == BT_CONNECTED) {
1533 		__clear_retrans_timer(chan);
1534 		__clear_monitor_timer(chan);
1535 		__clear_ack_timer(chan);
1536 	}
1537 
1538 	req.dcid = cpu_to_le16(chan->dcid);
1539 	req.scid = cpu_to_le16(chan->scid);
1540 	l2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_DISCONN_REQ,
1541 		       sizeof(req), &req);
1542 
1543 	l2cap_state_change_and_error(chan, BT_DISCONN, err);
1544 }
1545 
1546 /* ---- L2CAP connections ---- */
1547 static void l2cap_conn_start(struct l2cap_conn *conn)
1548 {
1549 	struct l2cap_chan *chan, *tmp;
1550 
1551 	BT_DBG("conn %p", conn);
1552 
1553 	list_for_each_entry_safe(chan, tmp, &conn->chan_l, list) {
1554 		l2cap_chan_lock(chan);
1555 
1556 		if (chan->chan_type != L2CAP_CHAN_CONN_ORIENTED) {
1557 			l2cap_chan_ready(chan);
1558 			l2cap_chan_unlock(chan);
1559 			continue;
1560 		}
1561 
1562 		if (chan->state == BT_CONNECT) {
1563 			if (!l2cap_chan_check_security(chan, true) ||
1564 			    !__l2cap_no_conn_pending(chan)) {
1565 				l2cap_chan_unlock(chan);
1566 				continue;
1567 			}
1568 
1569 			if (!l2cap_mode_supported(chan->mode, conn->feat_mask)
1570 			    && test_bit(CONF_STATE2_DEVICE,
1571 					&chan->conf_state)) {
1572 				l2cap_chan_close(chan, ECONNRESET);
1573 				l2cap_chan_unlock(chan);
1574 				continue;
1575 			}
1576 
1577 			if (l2cap_check_enc_key_size(conn->hcon, chan))
1578 				l2cap_start_connection(chan);
1579 			else
1580 				l2cap_chan_close(chan, ECONNREFUSED);
1581 
1582 		} else if (chan->state == BT_CONNECT2) {
1583 			struct l2cap_conn_rsp rsp;
1584 			char buf[128];
1585 			rsp.scid = cpu_to_le16(chan->dcid);
1586 			rsp.dcid = cpu_to_le16(chan->scid);
1587 
1588 			if (l2cap_chan_check_security(chan, false)) {
1589 				if (test_bit(FLAG_DEFER_SETUP, &chan->flags)) {
1590 					rsp.result = cpu_to_le16(L2CAP_CR_PEND);
1591 					rsp.status = cpu_to_le16(L2CAP_CS_AUTHOR_PEND);
1592 					chan->ops->defer(chan);
1593 
1594 				} else {
1595 					l2cap_state_change(chan, BT_CONFIG);
1596 					rsp.result = cpu_to_le16(L2CAP_CR_SUCCESS);
1597 					rsp.status = cpu_to_le16(L2CAP_CS_NO_INFO);
1598 				}
1599 			} else {
1600 				rsp.result = cpu_to_le16(L2CAP_CR_PEND);
1601 				rsp.status = cpu_to_le16(L2CAP_CS_AUTHEN_PEND);
1602 			}
1603 
1604 			l2cap_send_cmd(conn, chan->ident, L2CAP_CONN_RSP,
1605 				       sizeof(rsp), &rsp);
1606 
1607 			if (test_bit(CONF_REQ_SENT, &chan->conf_state) ||
1608 			    rsp.result != L2CAP_CR_SUCCESS) {
1609 				l2cap_chan_unlock(chan);
1610 				continue;
1611 			}
1612 
1613 			set_bit(CONF_REQ_SENT, &chan->conf_state);
1614 			l2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_CONF_REQ,
1615 				       l2cap_build_conf_req(chan, buf, sizeof(buf)), buf);
1616 			chan->num_conf_req++;
1617 		}
1618 
1619 		l2cap_chan_unlock(chan);
1620 	}
1621 }
1622 
1623 static void l2cap_le_conn_ready(struct l2cap_conn *conn)
1624 {
1625 	struct hci_conn *hcon = conn->hcon;
1626 	struct hci_dev *hdev = hcon->hdev;
1627 
1628 	BT_DBG("%s conn %p", hdev->name, conn);
1629 
1630 	/* For outgoing pairing which doesn't necessarily have an
1631 	 * associated socket (e.g. mgmt_pair_device).
1632 	 */
1633 	if (hcon->out)
1634 		smp_conn_security(hcon, hcon->pending_sec_level);
1635 
1636 	/* For LE peripheral connections, make sure the connection interval
1637 	 * is in the range of the minimum and maximum interval that has
1638 	 * been configured for this connection. If not, then trigger
1639 	 * the connection update procedure.
1640 	 */
1641 	if (hcon->role == HCI_ROLE_SLAVE &&
1642 	    (hcon->le_conn_interval < hcon->le_conn_min_interval ||
1643 	     hcon->le_conn_interval > hcon->le_conn_max_interval)) {
1644 		struct l2cap_conn_param_update_req req;
1645 
1646 		req.min = cpu_to_le16(hcon->le_conn_min_interval);
1647 		req.max = cpu_to_le16(hcon->le_conn_max_interval);
1648 		req.latency = cpu_to_le16(hcon->le_conn_latency);
1649 		req.to_multiplier = cpu_to_le16(hcon->le_supv_timeout);
1650 
1651 		l2cap_send_cmd(conn, l2cap_get_ident(conn),
1652 			       L2CAP_CONN_PARAM_UPDATE_REQ, sizeof(req), &req);
1653 	}
1654 }
1655 
1656 static void l2cap_conn_ready(struct l2cap_conn *conn)
1657 {
1658 	struct l2cap_chan *chan;
1659 	struct hci_conn *hcon = conn->hcon;
1660 
1661 	BT_DBG("conn %p", conn);
1662 
1663 	if (hcon->type == ACL_LINK)
1664 		l2cap_request_info(conn);
1665 
1666 	mutex_lock(&conn->lock);
1667 
1668 	list_for_each_entry(chan, &conn->chan_l, list) {
1669 
1670 		l2cap_chan_lock(chan);
1671 
1672 		if (hcon->type == LE_LINK) {
1673 			l2cap_le_start(chan);
1674 		} else if (chan->chan_type != L2CAP_CHAN_CONN_ORIENTED) {
1675 			if (conn->info_state & L2CAP_INFO_FEAT_MASK_REQ_DONE)
1676 				l2cap_chan_ready(chan);
1677 		} else if (chan->state == BT_CONNECT) {
1678 			l2cap_do_start(chan);
1679 		}
1680 
1681 		l2cap_chan_unlock(chan);
1682 	}
1683 
1684 	mutex_unlock(&conn->lock);
1685 
1686 	if (hcon->type == LE_LINK)
1687 		l2cap_le_conn_ready(conn);
1688 
1689 	queue_work(hcon->hdev->workqueue, &conn->pending_rx_work);
1690 }
1691 
1692 /* Notify sockets that we cannot guaranty reliability anymore */
1693 static void l2cap_conn_unreliable(struct l2cap_conn *conn, int err)
1694 {
1695 	struct l2cap_chan *chan;
1696 
1697 	BT_DBG("conn %p", conn);
1698 
1699 	list_for_each_entry(chan, &conn->chan_l, list) {
1700 		if (test_bit(FLAG_FORCE_RELIABLE, &chan->flags))
1701 			l2cap_chan_set_err(chan, err);
1702 	}
1703 }
1704 
1705 static void l2cap_info_timeout(struct work_struct *work)
1706 {
1707 	struct l2cap_conn *conn = container_of(work, struct l2cap_conn,
1708 					       info_timer.work);
1709 
1710 	conn->info_state |= L2CAP_INFO_FEAT_MASK_REQ_DONE;
1711 	conn->info_ident = 0;
1712 
1713 	mutex_lock(&conn->lock);
1714 	l2cap_conn_start(conn);
1715 	mutex_unlock(&conn->lock);
1716 }
1717 
1718 /*
1719  * l2cap_user
1720  * External modules can register l2cap_user objects on l2cap_conn. The ->probe
1721  * callback is called during registration. The ->remove callback is called
1722  * during unregistration.
1723  * An l2cap_user object can either be explicitly unregistered or when the
1724  * underlying l2cap_conn object is deleted. This guarantees that l2cap->hcon,
1725  * l2cap->hchan, .. are valid as long as the remove callback hasn't been called.
1726  * External modules must own a reference to the l2cap_conn object if they intend
1727  * to call l2cap_unregister_user(). The l2cap_conn object might get destroyed at
1728  * any time if they don't.
1729  */
1730 
1731 int l2cap_register_user(struct l2cap_conn *conn, struct l2cap_user *user)
1732 {
1733 	int ret;
1734 
1735 	/* We need to check whether l2cap_conn is registered. If it is not, we
1736 	 * must not register the l2cap_user. l2cap_conn_del() unregisters
1737 	 * l2cap_conn objects under conn->lock, and we use the same lock here
1738 	 * to protect access to conn->users and conn->hchan.
1739 	 */
1740 
1741 	mutex_lock(&conn->lock);
1742 
1743 	if (!list_empty(&user->list)) {
1744 		ret = -EINVAL;
1745 		goto out_unlock;
1746 	}
1747 
1748 	/* conn->hchan is NULL after l2cap_conn_del() was called */
1749 	if (!conn->hchan) {
1750 		ret = -ENODEV;
1751 		goto out_unlock;
1752 	}
1753 
1754 	ret = user->probe(conn, user);
1755 	if (ret)
1756 		goto out_unlock;
1757 
1758 	list_add(&user->list, &conn->users);
1759 	ret = 0;
1760 
1761 out_unlock:
1762 	mutex_unlock(&conn->lock);
1763 	return ret;
1764 }
1765 EXPORT_SYMBOL(l2cap_register_user);
1766 
1767 void l2cap_unregister_user(struct l2cap_conn *conn, struct l2cap_user *user)
1768 {
1769 	mutex_lock(&conn->lock);
1770 
1771 	if (list_empty(&user->list))
1772 		goto out_unlock;
1773 
1774 	list_del_init(&user->list);
1775 	user->remove(conn, user);
1776 
1777 out_unlock:
1778 	mutex_unlock(&conn->lock);
1779 }
1780 EXPORT_SYMBOL(l2cap_unregister_user);
1781 
1782 static void l2cap_unregister_all_users(struct l2cap_conn *conn)
1783 {
1784 	struct l2cap_user *user;
1785 
1786 	while (!list_empty(&conn->users)) {
1787 		user = list_first_entry(&conn->users, struct l2cap_user, list);
1788 		list_del_init(&user->list);
1789 		user->remove(conn, user);
1790 	}
1791 }
1792 
1793 static void l2cap_conn_del(struct hci_conn *hcon, int err)
1794 {
1795 	struct l2cap_conn *conn = hcon->l2cap_data;
1796 	struct l2cap_chan *chan, *l;
1797 
1798 	if (!conn)
1799 		return;
1800 
1801 	BT_DBG("hcon %p conn %p, err %d", hcon, conn, err);
1802 
1803 	disable_delayed_work_sync(&conn->info_timer);
1804 	disable_delayed_work_sync(&conn->id_addr_timer);
1805 
1806 	cancel_work_sync(&conn->pending_rx_work);
1807 
1808 	mutex_lock(&conn->lock);
1809 
1810 	kfree_skb(conn->rx_skb);
1811 
1812 	skb_queue_purge(&conn->pending_rx);
1813 	ida_destroy(&conn->tx_ida);
1814 
1815 	l2cap_unregister_all_users(conn);
1816 
1817 	/* Force the connection to be immediately dropped */
1818 	hcon->disc_timeout = 0;
1819 
1820 	/* Kill channels */
1821 	list_for_each_entry_safe(chan, l, &conn->chan_l, list) {
1822 		l2cap_chan_hold(chan);
1823 		l2cap_chan_lock(chan);
1824 
1825 		l2cap_chan_del(chan, err);
1826 
1827 		chan->ops->close(chan);
1828 
1829 		l2cap_chan_unlock(chan);
1830 		l2cap_chan_put(chan);
1831 	}
1832 
1833 	hci_chan_del(conn->hchan);
1834 	conn->hchan = NULL;
1835 
1836 	hcon->l2cap_data = NULL;
1837 	mutex_unlock(&conn->lock);
1838 	l2cap_conn_put(conn);
1839 }
1840 
1841 static void l2cap_conn_free(struct kref *ref)
1842 {
1843 	struct l2cap_conn *conn = container_of(ref, struct l2cap_conn, ref);
1844 
1845 	hci_conn_put(conn->hcon);
1846 	kfree(conn);
1847 }
1848 
1849 struct l2cap_conn *l2cap_conn_get(struct l2cap_conn *conn)
1850 {
1851 	kref_get(&conn->ref);
1852 	return conn;
1853 }
1854 EXPORT_SYMBOL(l2cap_conn_get);
1855 
1856 void l2cap_conn_put(struct l2cap_conn *conn)
1857 {
1858 	kref_put(&conn->ref, l2cap_conn_free);
1859 }
1860 EXPORT_SYMBOL(l2cap_conn_put);
1861 
1862 /* ---- Socket interface ---- */
1863 
1864 /* Find socket with psm and source / destination bdaddr.
1865  * Returns closest match.
1866  */
1867 static struct l2cap_chan *l2cap_global_chan_by_psm(int state, __le16 psm,
1868 						   bdaddr_t *src,
1869 						   bdaddr_t *dst,
1870 						   u8 link_type)
1871 {
1872 	struct l2cap_chan *c, *tmp, *c1 = NULL;
1873 
1874 	read_lock(&chan_list_lock);
1875 
1876 	list_for_each_entry_safe(c, tmp, &chan_list, global_l) {
1877 		if (state && c->state != state)
1878 			continue;
1879 
1880 		if (link_type == ACL_LINK && c->src_type != BDADDR_BREDR)
1881 			continue;
1882 
1883 		if (link_type == LE_LINK && c->src_type == BDADDR_BREDR)
1884 			continue;
1885 
1886 		if (c->chan_type != L2CAP_CHAN_FIXED && c->psm == psm) {
1887 			int src_match, dst_match;
1888 			int src_any, dst_any;
1889 
1890 			/* Exact match. */
1891 			src_match = !bacmp(&c->src, src);
1892 			dst_match = !bacmp(&c->dst, dst);
1893 			if (src_match && dst_match) {
1894 				if (!l2cap_chan_hold_unless_zero(c))
1895 					continue;
1896 
1897 				read_unlock(&chan_list_lock);
1898 				return c;
1899 			}
1900 
1901 			/* Closest match */
1902 			src_any = !bacmp(&c->src, BDADDR_ANY);
1903 			dst_any = !bacmp(&c->dst, BDADDR_ANY);
1904 			if ((src_match && dst_any) || (src_any && dst_match) ||
1905 			    (src_any && dst_any))
1906 				c1 = c;
1907 		}
1908 	}
1909 
1910 	if (c1)
1911 		c1 = l2cap_chan_hold_unless_zero(c1);
1912 
1913 	read_unlock(&chan_list_lock);
1914 
1915 	return c1;
1916 }
1917 
1918 static void l2cap_monitor_timeout(struct work_struct *work)
1919 {
1920 	struct l2cap_chan *chan = container_of(work, struct l2cap_chan,
1921 					       monitor_timer.work);
1922 
1923 	BT_DBG("chan %p", chan);
1924 
1925 	l2cap_chan_lock(chan);
1926 
1927 	if (test_bit(FLAG_DEL, &chan->flags)) {
1928 		l2cap_chan_unlock(chan);
1929 		l2cap_chan_put(chan);
1930 		return;
1931 	}
1932 
1933 	l2cap_tx(chan, NULL, NULL, L2CAP_EV_MONITOR_TO);
1934 
1935 	l2cap_chan_unlock(chan);
1936 	l2cap_chan_put(chan);
1937 }
1938 
1939 static void l2cap_retrans_timeout(struct work_struct *work)
1940 {
1941 	struct l2cap_chan *chan = container_of(work, struct l2cap_chan,
1942 					       retrans_timer.work);
1943 
1944 	BT_DBG("chan %p", chan);
1945 
1946 	l2cap_chan_lock(chan);
1947 
1948 	if (test_bit(FLAG_DEL, &chan->flags)) {
1949 		l2cap_chan_unlock(chan);
1950 		l2cap_chan_put(chan);
1951 		return;
1952 	}
1953 
1954 	l2cap_tx(chan, NULL, NULL, L2CAP_EV_RETRANS_TO);
1955 	l2cap_chan_unlock(chan);
1956 	l2cap_chan_put(chan);
1957 }
1958 
1959 static void l2cap_streaming_send(struct l2cap_chan *chan,
1960 				 struct sk_buff_head *skbs)
1961 {
1962 	struct sk_buff *skb;
1963 	struct l2cap_ctrl *control;
1964 
1965 	BT_DBG("chan %p, skbs %p", chan, skbs);
1966 
1967 	skb_queue_splice_tail_init(skbs, &chan->tx_q);
1968 
1969 	while (!skb_queue_empty(&chan->tx_q)) {
1970 
1971 		skb = skb_dequeue(&chan->tx_q);
1972 
1973 		bt_cb(skb)->l2cap.retries = 1;
1974 		control = &bt_cb(skb)->l2cap;
1975 
1976 		control->reqseq = 0;
1977 		control->txseq = chan->next_tx_seq;
1978 
1979 		__pack_control(chan, control, skb);
1980 
1981 		if (chan->fcs == L2CAP_FCS_CRC16) {
1982 			u16 fcs = crc16(0, (u8 *) skb->data, skb->len);
1983 			put_unaligned_le16(fcs, skb_put(skb, L2CAP_FCS_SIZE));
1984 		}
1985 
1986 		l2cap_do_send(chan, skb);
1987 
1988 		BT_DBG("Sent txseq %u", control->txseq);
1989 
1990 		chan->next_tx_seq = __next_seq(chan, chan->next_tx_seq);
1991 		chan->frames_sent++;
1992 	}
1993 }
1994 
1995 static int l2cap_ertm_send(struct l2cap_chan *chan)
1996 {
1997 	struct sk_buff *skb, *tx_skb;
1998 	struct l2cap_ctrl *control;
1999 	int sent = 0;
2000 
2001 	BT_DBG("chan %p", chan);
2002 
2003 	if (chan->state != BT_CONNECTED)
2004 		return -ENOTCONN;
2005 
2006 	if (test_bit(CONN_REMOTE_BUSY, &chan->conn_state))
2007 		return 0;
2008 
2009 	while (chan->tx_send_head &&
2010 	       chan->unacked_frames < chan->remote_tx_win &&
2011 	       chan->tx_state == L2CAP_TX_STATE_XMIT) {
2012 
2013 		skb = chan->tx_send_head;
2014 
2015 		bt_cb(skb)->l2cap.retries = 1;
2016 		control = &bt_cb(skb)->l2cap;
2017 
2018 		if (test_and_clear_bit(CONN_SEND_FBIT, &chan->conn_state))
2019 			control->final = 1;
2020 
2021 		control->reqseq = chan->buffer_seq;
2022 		chan->last_acked_seq = chan->buffer_seq;
2023 		control->txseq = chan->next_tx_seq;
2024 
2025 		__pack_control(chan, control, skb);
2026 
2027 		if (chan->fcs == L2CAP_FCS_CRC16) {
2028 			u16 fcs = crc16(0, (u8 *) skb->data, skb->len);
2029 			put_unaligned_le16(fcs, skb_put(skb, L2CAP_FCS_SIZE));
2030 		}
2031 
2032 		/* Clone after data has been modified. Data is assumed to be
2033 		   read-only (for locking purposes) on cloned sk_buffs.
2034 		 */
2035 		tx_skb = skb_clone(skb, GFP_KERNEL);
2036 
2037 		if (!tx_skb)
2038 			break;
2039 
2040 		__set_retrans_timer(chan);
2041 
2042 		chan->next_tx_seq = __next_seq(chan, chan->next_tx_seq);
2043 		chan->unacked_frames++;
2044 		chan->frames_sent++;
2045 		sent++;
2046 
2047 		if (skb_queue_is_last(&chan->tx_q, skb))
2048 			chan->tx_send_head = NULL;
2049 		else
2050 			chan->tx_send_head = skb_queue_next(&chan->tx_q, skb);
2051 
2052 		l2cap_do_send(chan, tx_skb);
2053 		BT_DBG("Sent txseq %u", control->txseq);
2054 	}
2055 
2056 	BT_DBG("Sent %d, %u unacked, %u in ERTM queue", sent,
2057 	       chan->unacked_frames, skb_queue_len(&chan->tx_q));
2058 
2059 	return sent;
2060 }
2061 
2062 static void l2cap_ertm_resend(struct l2cap_chan *chan)
2063 {
2064 	struct l2cap_ctrl control;
2065 	struct sk_buff *skb;
2066 	struct sk_buff *tx_skb;
2067 	u16 seq;
2068 
2069 	BT_DBG("chan %p", chan);
2070 
2071 	if (test_bit(CONN_REMOTE_BUSY, &chan->conn_state))
2072 		return;
2073 
2074 	while (chan->retrans_list.head != L2CAP_SEQ_LIST_CLEAR) {
2075 		seq = l2cap_seq_list_pop(&chan->retrans_list);
2076 
2077 		skb = l2cap_ertm_seq_in_queue(&chan->tx_q, seq);
2078 		if (!skb) {
2079 			BT_DBG("Error: Can't retransmit seq %d, frame missing",
2080 			       seq);
2081 			continue;
2082 		}
2083 
2084 		bt_cb(skb)->l2cap.retries++;
2085 		control = bt_cb(skb)->l2cap;
2086 
2087 		if (chan->max_tx != 0 &&
2088 		    bt_cb(skb)->l2cap.retries > chan->max_tx) {
2089 			BT_DBG("Retry limit exceeded (%d)", chan->max_tx);
2090 			l2cap_send_disconn_req(chan, ECONNRESET);
2091 			l2cap_seq_list_clear(&chan->retrans_list);
2092 			break;
2093 		}
2094 
2095 		control.reqseq = chan->buffer_seq;
2096 		if (test_and_clear_bit(CONN_SEND_FBIT, &chan->conn_state))
2097 			control.final = 1;
2098 		else
2099 			control.final = 0;
2100 
2101 		if (skb_cloned(skb)) {
2102 			/* Cloned sk_buffs are read-only, so we need a
2103 			 * writeable copy
2104 			 */
2105 			tx_skb = skb_copy(skb, GFP_KERNEL);
2106 		} else {
2107 			tx_skb = skb_clone(skb, GFP_KERNEL);
2108 		}
2109 
2110 		if (!tx_skb) {
2111 			l2cap_seq_list_clear(&chan->retrans_list);
2112 			break;
2113 		}
2114 
2115 		/* Update skb contents */
2116 		if (test_bit(FLAG_EXT_CTRL, &chan->flags)) {
2117 			put_unaligned_le32(__pack_extended_control(&control),
2118 					   tx_skb->data + L2CAP_HDR_SIZE);
2119 		} else {
2120 			put_unaligned_le16(__pack_enhanced_control(&control),
2121 					   tx_skb->data + L2CAP_HDR_SIZE);
2122 		}
2123 
2124 		/* Update FCS */
2125 		if (chan->fcs == L2CAP_FCS_CRC16) {
2126 			u16 fcs = crc16(0, (u8 *) tx_skb->data,
2127 					tx_skb->len - L2CAP_FCS_SIZE);
2128 			put_unaligned_le16(fcs, skb_tail_pointer(tx_skb) -
2129 						L2CAP_FCS_SIZE);
2130 		}
2131 
2132 		l2cap_do_send(chan, tx_skb);
2133 
2134 		BT_DBG("Resent txseq %d", control.txseq);
2135 
2136 		chan->last_acked_seq = chan->buffer_seq;
2137 	}
2138 }
2139 
2140 static void l2cap_retransmit(struct l2cap_chan *chan,
2141 			     struct l2cap_ctrl *control)
2142 {
2143 	BT_DBG("chan %p, control %p", chan, control);
2144 
2145 	l2cap_seq_list_append(&chan->retrans_list, control->reqseq);
2146 	l2cap_ertm_resend(chan);
2147 }
2148 
2149 static void l2cap_retransmit_all(struct l2cap_chan *chan,
2150 				 struct l2cap_ctrl *control)
2151 {
2152 	struct sk_buff *skb;
2153 
2154 	BT_DBG("chan %p, control %p", chan, control);
2155 
2156 	if (control->poll)
2157 		set_bit(CONN_SEND_FBIT, &chan->conn_state);
2158 
2159 	l2cap_seq_list_clear(&chan->retrans_list);
2160 
2161 	if (test_bit(CONN_REMOTE_BUSY, &chan->conn_state))
2162 		return;
2163 
2164 	if (chan->unacked_frames) {
2165 		skb_queue_walk(&chan->tx_q, skb) {
2166 			if (bt_cb(skb)->l2cap.txseq == control->reqseq ||
2167 			    skb == chan->tx_send_head)
2168 				break;
2169 		}
2170 
2171 		skb_queue_walk_from(&chan->tx_q, skb) {
2172 			if (skb == chan->tx_send_head)
2173 				break;
2174 
2175 			l2cap_seq_list_append(&chan->retrans_list,
2176 					      bt_cb(skb)->l2cap.txseq);
2177 		}
2178 
2179 		l2cap_ertm_resend(chan);
2180 	}
2181 }
2182 
2183 static void l2cap_send_ack(struct l2cap_chan *chan)
2184 {
2185 	struct l2cap_ctrl control;
2186 	u16 frames_to_ack = __seq_offset(chan, chan->buffer_seq,
2187 					 chan->last_acked_seq);
2188 	int threshold;
2189 
2190 	BT_DBG("chan %p last_acked_seq %d buffer_seq %d",
2191 	       chan, chan->last_acked_seq, chan->buffer_seq);
2192 
2193 	memset(&control, 0, sizeof(control));
2194 	control.sframe = 1;
2195 
2196 	if (test_bit(CONN_LOCAL_BUSY, &chan->conn_state) &&
2197 	    chan->rx_state == L2CAP_RX_STATE_RECV) {
2198 		__clear_ack_timer(chan);
2199 		control.super = L2CAP_SUPER_RNR;
2200 		control.reqseq = chan->buffer_seq;
2201 		l2cap_send_sframe(chan, &control);
2202 	} else {
2203 		if (!test_bit(CONN_REMOTE_BUSY, &chan->conn_state)) {
2204 			l2cap_ertm_send(chan);
2205 			/* If any i-frames were sent, they included an ack */
2206 			if (chan->buffer_seq == chan->last_acked_seq)
2207 				frames_to_ack = 0;
2208 		}
2209 
2210 		/* Ack now if the window is 3/4ths full.
2211 		 * Calculate without mul or div
2212 		 */
2213 		threshold = chan->ack_win;
2214 		threshold += threshold << 1;
2215 		threshold >>= 2;
2216 
2217 		BT_DBG("frames_to_ack %u, threshold %d", frames_to_ack,
2218 		       threshold);
2219 
2220 		if (frames_to_ack >= threshold) {
2221 			__clear_ack_timer(chan);
2222 			control.super = L2CAP_SUPER_RR;
2223 			control.reqseq = chan->buffer_seq;
2224 			l2cap_send_sframe(chan, &control);
2225 			frames_to_ack = 0;
2226 		}
2227 
2228 		if (frames_to_ack)
2229 			__set_ack_timer(chan);
2230 	}
2231 }
2232 
2233 static inline int l2cap_skbuff_fromiovec(struct l2cap_chan *chan,
2234 					 struct msghdr *msg, int len,
2235 					 int count, struct sk_buff *skb)
2236 {
2237 	struct l2cap_conn *conn = chan->conn;
2238 	struct sk_buff **frag;
2239 	int sent = 0;
2240 
2241 	if (!copy_from_iter_full(skb_put(skb, count), count, &msg->msg_iter))
2242 		return -EFAULT;
2243 
2244 	sent += count;
2245 	len  -= count;
2246 
2247 	/* Continuation fragments (no L2CAP header) */
2248 	frag = &skb_shinfo(skb)->frag_list;
2249 	while (len) {
2250 		struct sk_buff *tmp;
2251 
2252 		count = min_t(unsigned int, conn->mtu, len);
2253 
2254 		tmp = chan->ops->alloc_skb(chan, 0, count,
2255 					   msg->msg_flags & MSG_DONTWAIT);
2256 		if (IS_ERR(tmp))
2257 			return PTR_ERR(tmp);
2258 
2259 		*frag = tmp;
2260 
2261 		if (!copy_from_iter_full(skb_put(*frag, count), count,
2262 				   &msg->msg_iter))
2263 			return -EFAULT;
2264 
2265 		sent += count;
2266 		len  -= count;
2267 
2268 		skb->len += (*frag)->len;
2269 		skb->data_len += (*frag)->len;
2270 
2271 		frag = &(*frag)->next;
2272 	}
2273 
2274 	return sent;
2275 }
2276 
2277 static struct sk_buff *l2cap_create_connless_pdu(struct l2cap_chan *chan,
2278 						 struct msghdr *msg, size_t len)
2279 {
2280 	struct l2cap_conn *conn = chan->conn;
2281 	struct sk_buff *skb;
2282 	int err, count, hlen = L2CAP_HDR_SIZE + L2CAP_PSMLEN_SIZE;
2283 	struct l2cap_hdr *lh;
2284 
2285 	BT_DBG("chan %p psm 0x%2.2x len %zu", chan,
2286 	       __le16_to_cpu(chan->psm), len);
2287 
2288 	count = min_t(unsigned int, (conn->mtu - hlen), len);
2289 
2290 	skb = chan->ops->alloc_skb(chan, hlen, count,
2291 				   msg->msg_flags & MSG_DONTWAIT);
2292 	if (IS_ERR(skb))
2293 		return skb;
2294 
2295 	/* Create L2CAP header */
2296 	lh = skb_put(skb, L2CAP_HDR_SIZE);
2297 	lh->cid = cpu_to_le16(chan->dcid);
2298 	lh->len = cpu_to_le16(len + L2CAP_PSMLEN_SIZE);
2299 	put_unaligned(chan->psm, (__le16 *) skb_put(skb, L2CAP_PSMLEN_SIZE));
2300 
2301 	err = l2cap_skbuff_fromiovec(chan, msg, len, count, skb);
2302 	if (unlikely(err < 0)) {
2303 		kfree_skb(skb);
2304 		return ERR_PTR(err);
2305 	}
2306 	return skb;
2307 }
2308 
2309 static struct sk_buff *l2cap_create_basic_pdu(struct l2cap_chan *chan,
2310 					      struct msghdr *msg, size_t len)
2311 {
2312 	struct l2cap_conn *conn = chan->conn;
2313 	struct sk_buff *skb;
2314 	int err, count;
2315 	struct l2cap_hdr *lh;
2316 
2317 	BT_DBG("chan %p len %zu", chan, len);
2318 
2319 	count = min_t(unsigned int, (conn->mtu - L2CAP_HDR_SIZE), len);
2320 
2321 	skb = chan->ops->alloc_skb(chan, L2CAP_HDR_SIZE, count,
2322 				   msg->msg_flags & MSG_DONTWAIT);
2323 	if (IS_ERR(skb))
2324 		return skb;
2325 
2326 	/* Create L2CAP header */
2327 	lh = skb_put(skb, L2CAP_HDR_SIZE);
2328 	lh->cid = cpu_to_le16(chan->dcid);
2329 	lh->len = cpu_to_le16(len);
2330 
2331 	err = l2cap_skbuff_fromiovec(chan, msg, len, count, skb);
2332 	if (unlikely(err < 0)) {
2333 		kfree_skb(skb);
2334 		return ERR_PTR(err);
2335 	}
2336 	return skb;
2337 }
2338 
2339 static struct sk_buff *l2cap_create_iframe_pdu(struct l2cap_chan *chan,
2340 					       struct msghdr *msg, size_t len,
2341 					       u16 sdulen)
2342 {
2343 	struct l2cap_conn *conn = chan->conn;
2344 	struct sk_buff *skb;
2345 	int err, count, hlen;
2346 	struct l2cap_hdr *lh;
2347 
2348 	BT_DBG("chan %p len %zu", chan, len);
2349 
2350 	if (!conn)
2351 		return ERR_PTR(-ENOTCONN);
2352 
2353 	hlen = __ertm_hdr_size(chan);
2354 
2355 	if (sdulen)
2356 		hlen += L2CAP_SDULEN_SIZE;
2357 
2358 	if (chan->fcs == L2CAP_FCS_CRC16)
2359 		hlen += L2CAP_FCS_SIZE;
2360 
2361 	count = min_t(unsigned int, (conn->mtu - hlen), len);
2362 
2363 	skb = chan->ops->alloc_skb(chan, hlen, count,
2364 				   msg->msg_flags & MSG_DONTWAIT);
2365 	if (IS_ERR(skb))
2366 		return skb;
2367 
2368 	/* Create L2CAP header */
2369 	lh = skb_put(skb, L2CAP_HDR_SIZE);
2370 	lh->cid = cpu_to_le16(chan->dcid);
2371 	lh->len = cpu_to_le16(len + (hlen - L2CAP_HDR_SIZE));
2372 
2373 	/* Control header is populated later */
2374 	if (test_bit(FLAG_EXT_CTRL, &chan->flags))
2375 		put_unaligned_le32(0, skb_put(skb, L2CAP_EXT_CTRL_SIZE));
2376 	else
2377 		put_unaligned_le16(0, skb_put(skb, L2CAP_ENH_CTRL_SIZE));
2378 
2379 	if (sdulen)
2380 		put_unaligned_le16(sdulen, skb_put(skb, L2CAP_SDULEN_SIZE));
2381 
2382 	err = l2cap_skbuff_fromiovec(chan, msg, len, count, skb);
2383 	if (unlikely(err < 0)) {
2384 		kfree_skb(skb);
2385 		return ERR_PTR(err);
2386 	}
2387 
2388 	bt_cb(skb)->l2cap.fcs = chan->fcs;
2389 	bt_cb(skb)->l2cap.retries = 0;
2390 	return skb;
2391 }
2392 
2393 static int l2cap_segment_sdu(struct l2cap_chan *chan,
2394 			     struct sk_buff_head *seg_queue,
2395 			     struct msghdr *msg, size_t len)
2396 {
2397 	struct sk_buff *skb;
2398 	u16 sdu_len;
2399 	size_t pdu_len;
2400 	u8 sar;
2401 
2402 	BT_DBG("chan %p, msg %p, len %zu", chan, msg, len);
2403 
2404 	/* It is critical that ERTM PDUs fit in a single HCI fragment,
2405 	 * so fragmented skbs are not used.  The HCI layer's handling
2406 	 * of fragmented skbs is not compatible with ERTM's queueing.
2407 	 */
2408 
2409 	/* PDU size is derived from the HCI MTU */
2410 	pdu_len = chan->conn->mtu;
2411 
2412 	/* Constrain PDU size for BR/EDR connections */
2413 	pdu_len = min_t(size_t, pdu_len, L2CAP_BREDR_MAX_PAYLOAD);
2414 
2415 	/* Adjust for largest possible L2CAP overhead. */
2416 	if (chan->fcs)
2417 		pdu_len -= L2CAP_FCS_SIZE;
2418 
2419 	pdu_len -= __ertm_hdr_size(chan);
2420 
2421 	/* Remote device may have requested smaller PDUs */
2422 	pdu_len = min_t(size_t, pdu_len, chan->remote_mps);
2423 
2424 	if (!pdu_len)
2425 		return -EINVAL;
2426 
2427 	if (len <= pdu_len) {
2428 		sar = L2CAP_SAR_UNSEGMENTED;
2429 		sdu_len = 0;
2430 		pdu_len = len;
2431 	} else {
2432 		sar = L2CAP_SAR_START;
2433 		sdu_len = len;
2434 	}
2435 
2436 	while (len > 0) {
2437 		skb = l2cap_create_iframe_pdu(chan, msg, pdu_len, sdu_len);
2438 
2439 		if (IS_ERR(skb)) {
2440 			__skb_queue_purge(seg_queue);
2441 			return PTR_ERR(skb);
2442 		}
2443 
2444 		bt_cb(skb)->l2cap.sar = sar;
2445 		__skb_queue_tail(seg_queue, skb);
2446 
2447 		len -= pdu_len;
2448 		if (sdu_len)
2449 			sdu_len = 0;
2450 
2451 		if (len <= pdu_len) {
2452 			sar = L2CAP_SAR_END;
2453 			pdu_len = len;
2454 		} else {
2455 			sar = L2CAP_SAR_CONTINUE;
2456 		}
2457 	}
2458 
2459 	return 0;
2460 }
2461 
2462 static struct sk_buff *l2cap_create_le_flowctl_pdu(struct l2cap_chan *chan,
2463 						   struct msghdr *msg,
2464 						   size_t len, u16 sdulen)
2465 {
2466 	struct l2cap_conn *conn = chan->conn;
2467 	struct sk_buff *skb;
2468 	int err, count, hlen;
2469 	struct l2cap_hdr *lh;
2470 
2471 	BT_DBG("chan %p len %zu", chan, len);
2472 
2473 	if (!conn)
2474 		return ERR_PTR(-ENOTCONN);
2475 
2476 	hlen = L2CAP_HDR_SIZE;
2477 
2478 	if (sdulen)
2479 		hlen += L2CAP_SDULEN_SIZE;
2480 
2481 	count = min_t(unsigned int, (conn->mtu - hlen), len);
2482 
2483 	skb = chan->ops->alloc_skb(chan, hlen, count,
2484 				   msg->msg_flags & MSG_DONTWAIT);
2485 	if (IS_ERR(skb))
2486 		return skb;
2487 
2488 	/* Create L2CAP header */
2489 	lh = skb_put(skb, L2CAP_HDR_SIZE);
2490 	lh->cid = cpu_to_le16(chan->dcid);
2491 	lh->len = cpu_to_le16(len + (hlen - L2CAP_HDR_SIZE));
2492 
2493 	if (sdulen)
2494 		put_unaligned_le16(sdulen, skb_put(skb, L2CAP_SDULEN_SIZE));
2495 
2496 	err = l2cap_skbuff_fromiovec(chan, msg, len, count, skb);
2497 	if (unlikely(err < 0)) {
2498 		kfree_skb(skb);
2499 		return ERR_PTR(err);
2500 	}
2501 
2502 	return skb;
2503 }
2504 
2505 static int l2cap_segment_le_sdu(struct l2cap_chan *chan,
2506 				struct sk_buff_head *seg_queue,
2507 				struct msghdr *msg, size_t len)
2508 {
2509 	struct sk_buff *skb;
2510 	size_t pdu_len;
2511 	u16 sdu_len;
2512 
2513 	BT_DBG("chan %p, msg %p, len %zu", chan, msg, len);
2514 
2515 	sdu_len = len;
2516 	pdu_len = chan->remote_mps - L2CAP_SDULEN_SIZE;
2517 
2518 	while (len > 0) {
2519 		if (len <= pdu_len)
2520 			pdu_len = len;
2521 
2522 		skb = l2cap_create_le_flowctl_pdu(chan, msg, pdu_len, sdu_len);
2523 		if (IS_ERR(skb)) {
2524 			__skb_queue_purge(seg_queue);
2525 			return PTR_ERR(skb);
2526 		}
2527 
2528 		__skb_queue_tail(seg_queue, skb);
2529 
2530 		len -= pdu_len;
2531 
2532 		if (sdu_len) {
2533 			sdu_len = 0;
2534 			pdu_len += L2CAP_SDULEN_SIZE;
2535 		}
2536 	}
2537 
2538 	return 0;
2539 }
2540 
2541 static void l2cap_le_flowctl_send(struct l2cap_chan *chan)
2542 {
2543 	int sent = 0;
2544 
2545 	BT_DBG("chan %p", chan);
2546 
2547 	while (chan->tx_credits && !skb_queue_empty(&chan->tx_q)) {
2548 		l2cap_do_send(chan, skb_dequeue(&chan->tx_q));
2549 		chan->tx_credits--;
2550 		sent++;
2551 	}
2552 
2553 	BT_DBG("Sent %d credits %u queued %u", sent, chan->tx_credits,
2554 	       skb_queue_len(&chan->tx_q));
2555 }
2556 
2557 static void l2cap_tx_timestamp(struct sk_buff *skb,
2558 			       const struct sockcm_cookie *sockc,
2559 			       size_t len)
2560 {
2561 	struct sock *sk = skb ? skb->sk : NULL;
2562 
2563 	if (sk && sk->sk_type == SOCK_STREAM)
2564 		hci_setup_tx_timestamp(skb, len, sockc);
2565 	else
2566 		hci_setup_tx_timestamp(skb, 1, sockc);
2567 }
2568 
2569 static void l2cap_tx_timestamp_seg(struct sk_buff_head *queue,
2570 				   const struct sockcm_cookie *sockc,
2571 				   size_t len)
2572 {
2573 	struct sk_buff *skb = skb_peek(queue);
2574 	struct sock *sk = skb ? skb->sk : NULL;
2575 
2576 	if (sk && sk->sk_type == SOCK_STREAM)
2577 		l2cap_tx_timestamp(skb_peek_tail(queue), sockc, len);
2578 	else
2579 		l2cap_tx_timestamp(skb, sockc, len);
2580 }
2581 
2582 int l2cap_chan_send(struct l2cap_chan *chan, struct msghdr *msg, size_t len,
2583 		    const struct sockcm_cookie *sockc)
2584 {
2585 	struct sk_buff *skb;
2586 	int err;
2587 	struct sk_buff_head seg_queue;
2588 
2589 	if (test_bit(FLAG_DEL, &chan->flags))
2590 		return -ENOTCONN;
2591 
2592 	/* Connectionless channel */
2593 	if (chan->chan_type == L2CAP_CHAN_CONN_LESS) {
2594 		skb = l2cap_create_connless_pdu(chan, msg, len);
2595 		if (IS_ERR(skb))
2596 			return PTR_ERR(skb);
2597 
2598 		l2cap_tx_timestamp(skb, sockc, len);
2599 
2600 		l2cap_do_send(chan, skb);
2601 		return len;
2602 	}
2603 
2604 	switch (chan->mode) {
2605 	case L2CAP_MODE_LE_FLOWCTL:
2606 	case L2CAP_MODE_EXT_FLOWCTL:
2607 		/* Check outgoing MTU */
2608 		if (len > chan->omtu)
2609 			return -EMSGSIZE;
2610 
2611 		__skb_queue_head_init(&seg_queue);
2612 
2613 		err = l2cap_segment_le_sdu(chan, &seg_queue, msg, len);
2614 
2615 		if (chan->state != BT_CONNECTED) {
2616 			__skb_queue_purge(&seg_queue);
2617 			err = -ENOTCONN;
2618 		}
2619 
2620 		if (err)
2621 			return err;
2622 
2623 		l2cap_tx_timestamp_seg(&seg_queue, sockc, len);
2624 
2625 		skb_queue_splice_tail_init(&seg_queue, &chan->tx_q);
2626 
2627 		l2cap_le_flowctl_send(chan);
2628 
2629 		if (!chan->tx_credits)
2630 			chan->ops->suspend(chan);
2631 
2632 		err = len;
2633 
2634 		break;
2635 
2636 	case L2CAP_MODE_BASIC:
2637 		/* Check outgoing MTU */
2638 		if (len > chan->omtu)
2639 			return -EMSGSIZE;
2640 
2641 		/* Create a basic PDU */
2642 		skb = l2cap_create_basic_pdu(chan, msg, len);
2643 		if (IS_ERR(skb))
2644 			return PTR_ERR(skb);
2645 
2646 		l2cap_tx_timestamp(skb, sockc, len);
2647 
2648 		l2cap_do_send(chan, skb);
2649 		err = len;
2650 		break;
2651 
2652 	case L2CAP_MODE_ERTM:
2653 	case L2CAP_MODE_STREAMING:
2654 		/* Check outgoing MTU */
2655 		if (len > chan->omtu) {
2656 			err = -EMSGSIZE;
2657 			break;
2658 		}
2659 
2660 		__skb_queue_head_init(&seg_queue);
2661 
2662 		/* Do segmentation before calling in to the state machine,
2663 		 * since it's possible to block while waiting for memory
2664 		 * allocation.
2665 		 */
2666 		err = l2cap_segment_sdu(chan, &seg_queue, msg, len);
2667 
2668 		if (err)
2669 			break;
2670 
2671 		if (chan->mode == L2CAP_MODE_ERTM) {
2672 			/* TODO: ERTM mode timestamping */
2673 			l2cap_tx(chan, NULL, &seg_queue, L2CAP_EV_DATA_REQUEST);
2674 		} else {
2675 			l2cap_tx_timestamp_seg(&seg_queue, sockc, len);
2676 			l2cap_streaming_send(chan, &seg_queue);
2677 		}
2678 
2679 		err = len;
2680 
2681 		/* If the skbs were not queued for sending, they'll still be in
2682 		 * seg_queue and need to be purged.
2683 		 */
2684 		__skb_queue_purge(&seg_queue);
2685 		break;
2686 
2687 	default:
2688 		BT_DBG("bad state %1.1x", chan->mode);
2689 		err = -EBADFD;
2690 	}
2691 
2692 	return err;
2693 }
2694 EXPORT_SYMBOL_GPL(l2cap_chan_send);
2695 
2696 static void l2cap_send_srej(struct l2cap_chan *chan, u16 txseq)
2697 {
2698 	struct l2cap_ctrl control;
2699 	u16 seq;
2700 
2701 	BT_DBG("chan %p, txseq %u", chan, txseq);
2702 
2703 	memset(&control, 0, sizeof(control));
2704 	control.sframe = 1;
2705 	control.super = L2CAP_SUPER_SREJ;
2706 
2707 	for (seq = chan->expected_tx_seq; seq != txseq;
2708 	     seq = __next_seq(chan, seq)) {
2709 		if (!l2cap_ertm_seq_in_queue(&chan->srej_q, seq)) {
2710 			control.reqseq = seq;
2711 			l2cap_send_sframe(chan, &control);
2712 			l2cap_seq_list_append(&chan->srej_list, seq);
2713 		}
2714 	}
2715 
2716 	chan->expected_tx_seq = __next_seq(chan, txseq);
2717 }
2718 
2719 static void l2cap_send_srej_tail(struct l2cap_chan *chan)
2720 {
2721 	struct l2cap_ctrl control;
2722 
2723 	BT_DBG("chan %p", chan);
2724 
2725 	if (chan->srej_list.tail == L2CAP_SEQ_LIST_CLEAR)
2726 		return;
2727 
2728 	memset(&control, 0, sizeof(control));
2729 	control.sframe = 1;
2730 	control.super = L2CAP_SUPER_SREJ;
2731 	control.reqseq = chan->srej_list.tail;
2732 	l2cap_send_sframe(chan, &control);
2733 }
2734 
2735 static void l2cap_send_srej_list(struct l2cap_chan *chan, u16 txseq)
2736 {
2737 	struct l2cap_ctrl control;
2738 	u16 initial_head;
2739 	u16 seq;
2740 
2741 	BT_DBG("chan %p, txseq %u", chan, txseq);
2742 
2743 	memset(&control, 0, sizeof(control));
2744 	control.sframe = 1;
2745 	control.super = L2CAP_SUPER_SREJ;
2746 
2747 	/* Capture initial list head to allow only one pass through the list. */
2748 	initial_head = chan->srej_list.head;
2749 
2750 	do {
2751 		seq = l2cap_seq_list_pop(&chan->srej_list);
2752 		if (seq == txseq || seq == L2CAP_SEQ_LIST_CLEAR)
2753 			break;
2754 
2755 		control.reqseq = seq;
2756 		l2cap_send_sframe(chan, &control);
2757 		l2cap_seq_list_append(&chan->srej_list, seq);
2758 	} while (chan->srej_list.head != initial_head);
2759 }
2760 
2761 static void l2cap_process_reqseq(struct l2cap_chan *chan, u16 reqseq)
2762 {
2763 	struct sk_buff *acked_skb;
2764 	u16 ackseq;
2765 
2766 	BT_DBG("chan %p, reqseq %u", chan, reqseq);
2767 
2768 	if (chan->unacked_frames == 0 || reqseq == chan->expected_ack_seq)
2769 		return;
2770 
2771 	BT_DBG("expected_ack_seq %u, unacked_frames %u",
2772 	       chan->expected_ack_seq, chan->unacked_frames);
2773 
2774 	for (ackseq = chan->expected_ack_seq; ackseq != reqseq;
2775 	     ackseq = __next_seq(chan, ackseq)) {
2776 
2777 		acked_skb = l2cap_ertm_seq_in_queue(&chan->tx_q, ackseq);
2778 		if (acked_skb) {
2779 			skb_unlink(acked_skb, &chan->tx_q);
2780 			kfree_skb(acked_skb);
2781 			chan->unacked_frames--;
2782 		}
2783 	}
2784 
2785 	chan->expected_ack_seq = reqseq;
2786 
2787 	if (chan->unacked_frames == 0)
2788 		__clear_retrans_timer(chan);
2789 
2790 	BT_DBG("unacked_frames %u", chan->unacked_frames);
2791 }
2792 
2793 static void l2cap_abort_rx_srej_sent(struct l2cap_chan *chan)
2794 {
2795 	BT_DBG("chan %p", chan);
2796 
2797 	chan->expected_tx_seq = chan->buffer_seq;
2798 	l2cap_seq_list_clear(&chan->srej_list);
2799 	skb_queue_purge(&chan->srej_q);
2800 	chan->rx_state = L2CAP_RX_STATE_RECV;
2801 }
2802 
2803 static void l2cap_tx_state_xmit(struct l2cap_chan *chan,
2804 				struct l2cap_ctrl *control,
2805 				struct sk_buff_head *skbs, u8 event)
2806 {
2807 	BT_DBG("chan %p, control %p, skbs %p, event %d", chan, control, skbs,
2808 	       event);
2809 
2810 	switch (event) {
2811 	case L2CAP_EV_DATA_REQUEST:
2812 		if (chan->tx_send_head == NULL)
2813 			chan->tx_send_head = skb_peek(skbs);
2814 
2815 		skb_queue_splice_tail_init(skbs, &chan->tx_q);
2816 		l2cap_ertm_send(chan);
2817 		break;
2818 	case L2CAP_EV_LOCAL_BUSY_DETECTED:
2819 		BT_DBG("Enter LOCAL_BUSY");
2820 		set_bit(CONN_LOCAL_BUSY, &chan->conn_state);
2821 
2822 		if (chan->rx_state == L2CAP_RX_STATE_SREJ_SENT) {
2823 			/* The SREJ_SENT state must be aborted if we are to
2824 			 * enter the LOCAL_BUSY state.
2825 			 */
2826 			l2cap_abort_rx_srej_sent(chan);
2827 		}
2828 
2829 		l2cap_send_ack(chan);
2830 
2831 		break;
2832 	case L2CAP_EV_LOCAL_BUSY_CLEAR:
2833 		BT_DBG("Exit LOCAL_BUSY");
2834 		clear_bit(CONN_LOCAL_BUSY, &chan->conn_state);
2835 
2836 		if (test_bit(CONN_RNR_SENT, &chan->conn_state)) {
2837 			struct l2cap_ctrl local_control;
2838 
2839 			memset(&local_control, 0, sizeof(local_control));
2840 			local_control.sframe = 1;
2841 			local_control.super = L2CAP_SUPER_RR;
2842 			local_control.poll = 1;
2843 			local_control.reqseq = chan->buffer_seq;
2844 			l2cap_send_sframe(chan, &local_control);
2845 
2846 			chan->retry_count = 1;
2847 			__set_monitor_timer(chan);
2848 			chan->tx_state = L2CAP_TX_STATE_WAIT_F;
2849 		}
2850 		break;
2851 	case L2CAP_EV_RECV_REQSEQ_AND_FBIT:
2852 		l2cap_process_reqseq(chan, control->reqseq);
2853 		break;
2854 	case L2CAP_EV_EXPLICIT_POLL:
2855 		l2cap_send_rr_or_rnr(chan, 1);
2856 		chan->retry_count = 1;
2857 		__set_monitor_timer(chan);
2858 		__clear_ack_timer(chan);
2859 		chan->tx_state = L2CAP_TX_STATE_WAIT_F;
2860 		break;
2861 	case L2CAP_EV_RETRANS_TO:
2862 		l2cap_send_rr_or_rnr(chan, 1);
2863 		chan->retry_count = 1;
2864 		__set_monitor_timer(chan);
2865 		chan->tx_state = L2CAP_TX_STATE_WAIT_F;
2866 		break;
2867 	case L2CAP_EV_RECV_FBIT:
2868 		/* Nothing to process */
2869 		break;
2870 	default:
2871 		break;
2872 	}
2873 }
2874 
2875 static void l2cap_tx_state_wait_f(struct l2cap_chan *chan,
2876 				  struct l2cap_ctrl *control,
2877 				  struct sk_buff_head *skbs, u8 event)
2878 {
2879 	BT_DBG("chan %p, control %p, skbs %p, event %d", chan, control, skbs,
2880 	       event);
2881 
2882 	switch (event) {
2883 	case L2CAP_EV_DATA_REQUEST:
2884 		if (chan->tx_send_head == NULL)
2885 			chan->tx_send_head = skb_peek(skbs);
2886 		/* Queue data, but don't send. */
2887 		skb_queue_splice_tail_init(skbs, &chan->tx_q);
2888 		break;
2889 	case L2CAP_EV_LOCAL_BUSY_DETECTED:
2890 		BT_DBG("Enter LOCAL_BUSY");
2891 		set_bit(CONN_LOCAL_BUSY, &chan->conn_state);
2892 
2893 		if (chan->rx_state == L2CAP_RX_STATE_SREJ_SENT) {
2894 			/* The SREJ_SENT state must be aborted if we are to
2895 			 * enter the LOCAL_BUSY state.
2896 			 */
2897 			l2cap_abort_rx_srej_sent(chan);
2898 		}
2899 
2900 		l2cap_send_ack(chan);
2901 
2902 		break;
2903 	case L2CAP_EV_LOCAL_BUSY_CLEAR:
2904 		BT_DBG("Exit LOCAL_BUSY");
2905 		clear_bit(CONN_LOCAL_BUSY, &chan->conn_state);
2906 
2907 		if (test_bit(CONN_RNR_SENT, &chan->conn_state)) {
2908 			struct l2cap_ctrl local_control;
2909 			memset(&local_control, 0, sizeof(local_control));
2910 			local_control.sframe = 1;
2911 			local_control.super = L2CAP_SUPER_RR;
2912 			local_control.poll = 1;
2913 			local_control.reqseq = chan->buffer_seq;
2914 			l2cap_send_sframe(chan, &local_control);
2915 
2916 			chan->retry_count = 1;
2917 			__set_monitor_timer(chan);
2918 			chan->tx_state = L2CAP_TX_STATE_WAIT_F;
2919 		}
2920 		break;
2921 	case L2CAP_EV_RECV_REQSEQ_AND_FBIT:
2922 		l2cap_process_reqseq(chan, control->reqseq);
2923 		fallthrough;
2924 
2925 	case L2CAP_EV_RECV_FBIT:
2926 		if (control && control->final) {
2927 			__clear_monitor_timer(chan);
2928 			if (chan->unacked_frames > 0)
2929 				__set_retrans_timer(chan);
2930 			chan->retry_count = 0;
2931 			chan->tx_state = L2CAP_TX_STATE_XMIT;
2932 			BT_DBG("recv fbit tx_state 0x2.2%x", chan->tx_state);
2933 		}
2934 		break;
2935 	case L2CAP_EV_EXPLICIT_POLL:
2936 		/* Ignore */
2937 		break;
2938 	case L2CAP_EV_MONITOR_TO:
2939 		if (chan->max_tx == 0 || chan->retry_count < chan->max_tx) {
2940 			l2cap_send_rr_or_rnr(chan, 1);
2941 			__set_monitor_timer(chan);
2942 			chan->retry_count++;
2943 		} else {
2944 			l2cap_send_disconn_req(chan, ECONNABORTED);
2945 		}
2946 		break;
2947 	default:
2948 		break;
2949 	}
2950 }
2951 
2952 static void l2cap_tx(struct l2cap_chan *chan, struct l2cap_ctrl *control,
2953 		     struct sk_buff_head *skbs, u8 event)
2954 {
2955 	BT_DBG("chan %p, control %p, skbs %p, event %d, state %d",
2956 	       chan, control, skbs, event, chan->tx_state);
2957 
2958 	switch (chan->tx_state) {
2959 	case L2CAP_TX_STATE_XMIT:
2960 		l2cap_tx_state_xmit(chan, control, skbs, event);
2961 		break;
2962 	case L2CAP_TX_STATE_WAIT_F:
2963 		l2cap_tx_state_wait_f(chan, control, skbs, event);
2964 		break;
2965 	default:
2966 		/* Ignore event */
2967 		break;
2968 	}
2969 }
2970 
2971 static void l2cap_pass_to_tx(struct l2cap_chan *chan,
2972 			     struct l2cap_ctrl *control)
2973 {
2974 	BT_DBG("chan %p, control %p", chan, control);
2975 	l2cap_tx(chan, control, NULL, L2CAP_EV_RECV_REQSEQ_AND_FBIT);
2976 }
2977 
2978 static void l2cap_pass_to_tx_fbit(struct l2cap_chan *chan,
2979 				  struct l2cap_ctrl *control)
2980 {
2981 	BT_DBG("chan %p, control %p", chan, control);
2982 	l2cap_tx(chan, control, NULL, L2CAP_EV_RECV_FBIT);
2983 }
2984 
2985 /* Copy frame to all raw sockets on that connection */
2986 static void l2cap_raw_recv(struct l2cap_conn *conn, struct sk_buff *skb)
2987 {
2988 	struct sk_buff *nskb;
2989 	struct l2cap_chan *chan;
2990 
2991 	BT_DBG("conn %p", conn);
2992 
2993 	list_for_each_entry(chan, &conn->chan_l, list) {
2994 		if (chan->chan_type != L2CAP_CHAN_RAW)
2995 			continue;
2996 
2997 		/* Don't send frame to the channel it came from */
2998 		if (bt_cb(skb)->l2cap.chan == chan)
2999 			continue;
3000 
3001 		nskb = skb_clone(skb, GFP_KERNEL);
3002 		if (!nskb)
3003 			continue;
3004 		if (chan->ops->recv(chan, nskb))
3005 			kfree_skb(nskb);
3006 	}
3007 }
3008 
3009 /* ---- L2CAP signalling commands ---- */
3010 static struct sk_buff *l2cap_build_cmd(struct l2cap_conn *conn, u8 code,
3011 				       u8 ident, u16 dlen, void *data)
3012 {
3013 	struct sk_buff *skb, **frag;
3014 	struct l2cap_cmd_hdr *cmd;
3015 	struct l2cap_hdr *lh;
3016 	int len, count;
3017 
3018 	BT_DBG("conn %p, code 0x%2.2x, ident 0x%2.2x, len %u",
3019 	       conn, code, ident, dlen);
3020 
3021 	if (conn->mtu < L2CAP_HDR_SIZE + L2CAP_CMD_HDR_SIZE)
3022 		return NULL;
3023 
3024 	len = L2CAP_HDR_SIZE + L2CAP_CMD_HDR_SIZE + dlen;
3025 	count = min_t(unsigned int, conn->mtu, len);
3026 
3027 	skb = bt_skb_alloc(count, GFP_KERNEL);
3028 	if (!skb)
3029 		return NULL;
3030 
3031 	lh = skb_put(skb, L2CAP_HDR_SIZE);
3032 	lh->len = cpu_to_le16(L2CAP_CMD_HDR_SIZE + dlen);
3033 
3034 	if (conn->hcon->type == LE_LINK)
3035 		lh->cid = cpu_to_le16(L2CAP_CID_LE_SIGNALING);
3036 	else
3037 		lh->cid = cpu_to_le16(L2CAP_CID_SIGNALING);
3038 
3039 	cmd = skb_put(skb, L2CAP_CMD_HDR_SIZE);
3040 	cmd->code  = code;
3041 	cmd->ident = ident;
3042 	cmd->len   = cpu_to_le16(dlen);
3043 
3044 	if (dlen) {
3045 		count -= L2CAP_HDR_SIZE + L2CAP_CMD_HDR_SIZE;
3046 		skb_put_data(skb, data, count);
3047 		data += count;
3048 	}
3049 
3050 	len -= skb->len;
3051 
3052 	/* Continuation fragments (no L2CAP header) */
3053 	frag = &skb_shinfo(skb)->frag_list;
3054 	while (len) {
3055 		count = min_t(unsigned int, conn->mtu, len);
3056 
3057 		*frag = bt_skb_alloc(count, GFP_KERNEL);
3058 		if (!*frag)
3059 			goto fail;
3060 
3061 		skb_put_data(*frag, data, count);
3062 
3063 		len  -= count;
3064 		data += count;
3065 
3066 		frag = &(*frag)->next;
3067 	}
3068 
3069 	return skb;
3070 
3071 fail:
3072 	kfree_skb(skb);
3073 	return NULL;
3074 }
3075 
3076 static inline int l2cap_get_conf_opt(void **ptr, void *end, int *type,
3077 				     int *olen, unsigned long *val)
3078 {
3079 	struct l2cap_conf_opt *opt = *ptr;
3080 	int len;
3081 
3082 	/* opt->len is attacker-controlled. Validate that the full option
3083 	 * (header + value) actually fits in the buffer before touching
3084 	 * opt->val, otherwise the switch below reads past the end of the
3085 	 * caller's buffer.
3086 	 */
3087 	if (end - *ptr < L2CAP_CONF_OPT_SIZE)
3088 		return -EINVAL;
3089 
3090 	len = L2CAP_CONF_OPT_SIZE + opt->len;
3091 	if (end - *ptr < len)
3092 		return -EINVAL;
3093 
3094 	*ptr += len;
3095 
3096 	*type = opt->type;
3097 	*olen = opt->len;
3098 
3099 	switch (opt->len) {
3100 	case 1:
3101 		*val = *((u8 *) opt->val);
3102 		break;
3103 
3104 	case 2:
3105 		*val = get_unaligned_le16(opt->val);
3106 		break;
3107 
3108 	case 4:
3109 		*val = get_unaligned_le32(opt->val);
3110 		break;
3111 
3112 	default:
3113 		*val = (unsigned long) opt->val;
3114 		break;
3115 	}
3116 
3117 	BT_DBG("type 0x%2.2x len %u val 0x%lx", *type, opt->len, *val);
3118 	return len;
3119 }
3120 
3121 static void l2cap_add_conf_opt(void **ptr, u8 type, u8 len, unsigned long val, size_t size)
3122 {
3123 	struct l2cap_conf_opt *opt = *ptr;
3124 
3125 	BT_DBG("type 0x%2.2x len %u val 0x%lx", type, len, val);
3126 
3127 	if (size < L2CAP_CONF_OPT_SIZE + len)
3128 		return;
3129 
3130 	opt->type = type;
3131 	opt->len  = len;
3132 
3133 	switch (len) {
3134 	case 1:
3135 		*((u8 *) opt->val)  = val;
3136 		break;
3137 
3138 	case 2:
3139 		put_unaligned_le16(val, opt->val);
3140 		break;
3141 
3142 	case 4:
3143 		put_unaligned_le32(val, opt->val);
3144 		break;
3145 
3146 	default:
3147 		memcpy(opt->val, (void *) val, len);
3148 		break;
3149 	}
3150 
3151 	*ptr += L2CAP_CONF_OPT_SIZE + len;
3152 }
3153 
3154 static void l2cap_add_opt_efs(void **ptr, struct l2cap_chan *chan, size_t size)
3155 {
3156 	struct l2cap_conf_efs efs;
3157 
3158 	switch (chan->mode) {
3159 	case L2CAP_MODE_ERTM:
3160 		efs.id		= chan->local_id;
3161 		efs.stype	= chan->local_stype;
3162 		efs.msdu	= cpu_to_le16(chan->local_msdu);
3163 		efs.sdu_itime	= cpu_to_le32(chan->local_sdu_itime);
3164 		efs.acc_lat	= cpu_to_le32(L2CAP_DEFAULT_ACC_LAT);
3165 		efs.flush_to	= cpu_to_le32(L2CAP_EFS_DEFAULT_FLUSH_TO);
3166 		break;
3167 
3168 	case L2CAP_MODE_STREAMING:
3169 		efs.id		= 1;
3170 		efs.stype	= L2CAP_SERV_BESTEFFORT;
3171 		efs.msdu	= cpu_to_le16(chan->local_msdu);
3172 		efs.sdu_itime	= cpu_to_le32(chan->local_sdu_itime);
3173 		efs.acc_lat	= 0;
3174 		efs.flush_to	= 0;
3175 		break;
3176 
3177 	default:
3178 		return;
3179 	}
3180 
3181 	l2cap_add_conf_opt(ptr, L2CAP_CONF_EFS, sizeof(efs),
3182 			   (unsigned long) &efs, size);
3183 }
3184 
3185 static void l2cap_ack_timeout(struct work_struct *work)
3186 {
3187 	struct l2cap_chan *chan = container_of(work, struct l2cap_chan,
3188 					       ack_timer.work);
3189 	u16 frames_to_ack;
3190 
3191 	BT_DBG("chan %p", chan);
3192 
3193 	l2cap_chan_lock(chan);
3194 
3195 	if (test_bit(FLAG_DEL, &chan->flags))
3196 		goto unlock;
3197 
3198 	frames_to_ack = __seq_offset(chan, chan->buffer_seq,
3199 				     chan->last_acked_seq);
3200 
3201 	if (frames_to_ack)
3202 		l2cap_send_rr_or_rnr(chan, 0);
3203 
3204 unlock:
3205 	l2cap_chan_unlock(chan);
3206 	l2cap_chan_put(chan);
3207 }
3208 
3209 int l2cap_ertm_init(struct l2cap_chan *chan)
3210 {
3211 	int err;
3212 
3213 	chan->next_tx_seq = 0;
3214 	chan->expected_tx_seq = 0;
3215 	chan->expected_ack_seq = 0;
3216 	chan->unacked_frames = 0;
3217 	chan->buffer_seq = 0;
3218 	chan->frames_sent = 0;
3219 	chan->last_acked_seq = 0;
3220 	chan->sdu = NULL;
3221 	chan->sdu_last_frag = NULL;
3222 	chan->sdu_len = 0;
3223 
3224 	skb_queue_head_init(&chan->tx_q);
3225 
3226 	if (chan->mode != L2CAP_MODE_ERTM)
3227 		return 0;
3228 
3229 	chan->rx_state = L2CAP_RX_STATE_RECV;
3230 	chan->tx_state = L2CAP_TX_STATE_XMIT;
3231 
3232 	skb_queue_head_init(&chan->srej_q);
3233 
3234 	err = l2cap_seq_list_init(&chan->srej_list, chan->tx_win);
3235 	if (err < 0)
3236 		return err;
3237 
3238 	err = l2cap_seq_list_init(&chan->retrans_list, chan->remote_tx_win);
3239 	if (err < 0)
3240 		l2cap_seq_list_free(&chan->srej_list);
3241 
3242 	return err;
3243 }
3244 
3245 static inline __u8 l2cap_select_mode(__u8 mode, __u16 remote_feat_mask)
3246 {
3247 	switch (mode) {
3248 	case L2CAP_MODE_STREAMING:
3249 	case L2CAP_MODE_ERTM:
3250 		if (l2cap_mode_supported(mode, remote_feat_mask))
3251 			return mode;
3252 		fallthrough;
3253 	default:
3254 		return L2CAP_MODE_BASIC;
3255 	}
3256 }
3257 
3258 static inline bool __l2cap_ews_supported(struct l2cap_conn *conn)
3259 {
3260 	return (conn->feat_mask & L2CAP_FEAT_EXT_WINDOW);
3261 }
3262 
3263 static inline bool __l2cap_efs_supported(struct l2cap_conn *conn)
3264 {
3265 	return (conn->feat_mask & L2CAP_FEAT_EXT_FLOW);
3266 }
3267 
3268 static void __l2cap_set_ertm_timeouts(struct l2cap_chan *chan,
3269 				      struct l2cap_conf_rfc *rfc)
3270 {
3271 	rfc->retrans_timeout = cpu_to_le16(L2CAP_DEFAULT_RETRANS_TO);
3272 	rfc->monitor_timeout = cpu_to_le16(L2CAP_DEFAULT_MONITOR_TO);
3273 }
3274 
3275 static inline void l2cap_txwin_setup(struct l2cap_chan *chan)
3276 {
3277 	if (chan->tx_win > L2CAP_DEFAULT_TX_WINDOW &&
3278 	    __l2cap_ews_supported(chan->conn)) {
3279 		/* use extended control field */
3280 		set_bit(FLAG_EXT_CTRL, &chan->flags);
3281 		chan->tx_win_max = L2CAP_DEFAULT_EXT_WINDOW;
3282 	} else {
3283 		chan->tx_win = min_t(u16, chan->tx_win,
3284 				     L2CAP_DEFAULT_TX_WINDOW);
3285 		chan->tx_win_max = L2CAP_DEFAULT_TX_WINDOW;
3286 	}
3287 	chan->ack_win = chan->tx_win;
3288 }
3289 
3290 static void l2cap_mtu_auto(struct l2cap_chan *chan)
3291 {
3292 	struct hci_conn *conn = chan->conn->hcon;
3293 
3294 	chan->imtu = L2CAP_DEFAULT_MIN_MTU;
3295 
3296 	/* The 2-DH1 packet has between 2 and 56 information bytes
3297 	 * (including the 2-byte payload header)
3298 	 */
3299 	if (!(conn->pkt_type & HCI_2DH1))
3300 		chan->imtu = 54;
3301 
3302 	/* The 3-DH1 packet has between 2 and 85 information bytes
3303 	 * (including the 2-byte payload header)
3304 	 */
3305 	if (!(conn->pkt_type & HCI_3DH1))
3306 		chan->imtu = 83;
3307 
3308 	/* The 2-DH3 packet has between 2 and 369 information bytes
3309 	 * (including the 2-byte payload header)
3310 	 */
3311 	if (!(conn->pkt_type & HCI_2DH3))
3312 		chan->imtu = 367;
3313 
3314 	/* The 3-DH3 packet has between 2 and 554 information bytes
3315 	 * (including the 2-byte payload header)
3316 	 */
3317 	if (!(conn->pkt_type & HCI_3DH3))
3318 		chan->imtu = 552;
3319 
3320 	/* The 2-DH5 packet has between 2 and 681 information bytes
3321 	 * (including the 2-byte payload header)
3322 	 */
3323 	if (!(conn->pkt_type & HCI_2DH5))
3324 		chan->imtu = 679;
3325 
3326 	/* The 3-DH5 packet has between 2 and 1023 information bytes
3327 	 * (including the 2-byte payload header)
3328 	 */
3329 	if (!(conn->pkt_type & HCI_3DH5))
3330 		chan->imtu = 1021;
3331 }
3332 
3333 static int l2cap_build_conf_req(struct l2cap_chan *chan, void *data, size_t data_size)
3334 {
3335 	struct l2cap_conf_req *req = data;
3336 	struct l2cap_conf_rfc rfc = { .mode = chan->mode };
3337 	void *ptr = req->data;
3338 	void *endptr = data + data_size;
3339 	u16 size;
3340 
3341 	BT_DBG("chan %p", chan);
3342 
3343 	if (chan->num_conf_req || chan->num_conf_rsp)
3344 		goto done;
3345 
3346 	switch (chan->mode) {
3347 	case L2CAP_MODE_STREAMING:
3348 	case L2CAP_MODE_ERTM:
3349 		if (test_bit(CONF_STATE2_DEVICE, &chan->conf_state))
3350 			break;
3351 
3352 		if (__l2cap_efs_supported(chan->conn))
3353 			set_bit(FLAG_EFS_ENABLE, &chan->flags);
3354 
3355 		fallthrough;
3356 	default:
3357 		chan->mode = l2cap_select_mode(rfc.mode, chan->conn->feat_mask);
3358 		break;
3359 	}
3360 
3361 done:
3362 	if (chan->imtu != L2CAP_DEFAULT_MTU) {
3363 		if (!chan->imtu)
3364 			l2cap_mtu_auto(chan);
3365 		l2cap_add_conf_opt(&ptr, L2CAP_CONF_MTU, 2, chan->imtu,
3366 				   endptr - ptr);
3367 	}
3368 
3369 	switch (chan->mode) {
3370 	case L2CAP_MODE_BASIC:
3371 		if (disable_ertm)
3372 			break;
3373 
3374 		if (!(chan->conn->feat_mask & L2CAP_FEAT_ERTM) &&
3375 		    !(chan->conn->feat_mask & L2CAP_FEAT_STREAMING))
3376 			break;
3377 
3378 		rfc.mode            = L2CAP_MODE_BASIC;
3379 		rfc.txwin_size      = 0;
3380 		rfc.max_transmit    = 0;
3381 		rfc.retrans_timeout = 0;
3382 		rfc.monitor_timeout = 0;
3383 		rfc.max_pdu_size    = 0;
3384 
3385 		l2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC, sizeof(rfc),
3386 				   (unsigned long) &rfc, endptr - ptr);
3387 		break;
3388 
3389 	case L2CAP_MODE_ERTM:
3390 		rfc.mode            = L2CAP_MODE_ERTM;
3391 		rfc.max_transmit    = chan->max_tx;
3392 
3393 		__l2cap_set_ertm_timeouts(chan, &rfc);
3394 
3395 		size = min_t(u16, L2CAP_DEFAULT_MAX_PDU_SIZE, chan->conn->mtu -
3396 			     L2CAP_EXT_HDR_SIZE - L2CAP_SDULEN_SIZE -
3397 			     L2CAP_FCS_SIZE);
3398 		rfc.max_pdu_size = cpu_to_le16(size);
3399 
3400 		l2cap_txwin_setup(chan);
3401 
3402 		rfc.txwin_size = min_t(u16, chan->tx_win,
3403 				       L2CAP_DEFAULT_TX_WINDOW);
3404 
3405 		l2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC, sizeof(rfc),
3406 				   (unsigned long) &rfc, endptr - ptr);
3407 
3408 		if (test_bit(FLAG_EFS_ENABLE, &chan->flags))
3409 			l2cap_add_opt_efs(&ptr, chan, endptr - ptr);
3410 
3411 		if (test_bit(FLAG_EXT_CTRL, &chan->flags))
3412 			l2cap_add_conf_opt(&ptr, L2CAP_CONF_EWS, 2,
3413 					   chan->tx_win, endptr - ptr);
3414 
3415 		if (chan->conn->feat_mask & L2CAP_FEAT_FCS)
3416 			if (chan->fcs == L2CAP_FCS_NONE ||
3417 			    test_bit(CONF_RECV_NO_FCS, &chan->conf_state)) {
3418 				chan->fcs = L2CAP_FCS_NONE;
3419 				l2cap_add_conf_opt(&ptr, L2CAP_CONF_FCS, 1,
3420 						   chan->fcs, endptr - ptr);
3421 			}
3422 		break;
3423 
3424 	case L2CAP_MODE_STREAMING:
3425 		l2cap_txwin_setup(chan);
3426 		rfc.mode            = L2CAP_MODE_STREAMING;
3427 		rfc.txwin_size      = 0;
3428 		rfc.max_transmit    = 0;
3429 		rfc.retrans_timeout = 0;
3430 		rfc.monitor_timeout = 0;
3431 
3432 		size = min_t(u16, L2CAP_DEFAULT_MAX_PDU_SIZE, chan->conn->mtu -
3433 			     L2CAP_EXT_HDR_SIZE - L2CAP_SDULEN_SIZE -
3434 			     L2CAP_FCS_SIZE);
3435 		rfc.max_pdu_size = cpu_to_le16(size);
3436 
3437 		l2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC, sizeof(rfc),
3438 				   (unsigned long) &rfc, endptr - ptr);
3439 
3440 		if (test_bit(FLAG_EFS_ENABLE, &chan->flags))
3441 			l2cap_add_opt_efs(&ptr, chan, endptr - ptr);
3442 
3443 		if (chan->conn->feat_mask & L2CAP_FEAT_FCS)
3444 			if (chan->fcs == L2CAP_FCS_NONE ||
3445 			    test_bit(CONF_RECV_NO_FCS, &chan->conf_state)) {
3446 				chan->fcs = L2CAP_FCS_NONE;
3447 				l2cap_add_conf_opt(&ptr, L2CAP_CONF_FCS, 1,
3448 						   chan->fcs, endptr - ptr);
3449 			}
3450 		break;
3451 	}
3452 
3453 	req->dcid  = cpu_to_le16(chan->dcid);
3454 	req->flags = cpu_to_le16(0);
3455 
3456 	return ptr - data;
3457 }
3458 
3459 static int l2cap_parse_conf_req(struct l2cap_chan *chan, void *data, size_t data_size)
3460 {
3461 	struct l2cap_conf_rsp *rsp = data;
3462 	void *ptr = rsp->data;
3463 	void *endptr = data + data_size;
3464 	void *req = chan->conf_req;
3465 	void *req_end = req + chan->conf_len;
3466 	int len = chan->conf_len;
3467 	int type, hint, olen;
3468 	unsigned long val;
3469 	struct l2cap_conf_rfc rfc = { .mode = L2CAP_MODE_BASIC };
3470 	struct l2cap_conf_efs efs;
3471 	u8 remote_efs = 0;
3472 	u16 mtu = 0;
3473 	u16 result = L2CAP_CONF_SUCCESS;
3474 	u16 size;
3475 
3476 	BT_DBG("chan %p", chan);
3477 
3478 	while (len >= L2CAP_CONF_OPT_SIZE) {
3479 		int ret = l2cap_get_conf_opt(&req, req_end, &type, &olen, &val);
3480 
3481 		if (ret < 0)
3482 			break;
3483 		len -= ret;
3484 
3485 		hint  = type & L2CAP_CONF_HINT;
3486 		type &= L2CAP_CONF_MASK;
3487 
3488 		switch (type) {
3489 		case L2CAP_CONF_MTU:
3490 			if (olen != 2)
3491 				break;
3492 			mtu = val;
3493 			break;
3494 
3495 		case L2CAP_CONF_FLUSH_TO:
3496 			if (olen != 2)
3497 				break;
3498 			chan->flush_to = val;
3499 			break;
3500 
3501 		case L2CAP_CONF_QOS:
3502 			break;
3503 
3504 		case L2CAP_CONF_RFC:
3505 			if (olen != sizeof(rfc))
3506 				break;
3507 			memcpy(&rfc, (void *) val, olen);
3508 			break;
3509 
3510 		case L2CAP_CONF_FCS:
3511 			if (olen != 1)
3512 				break;
3513 			if (val == L2CAP_FCS_NONE)
3514 				set_bit(CONF_RECV_NO_FCS, &chan->conf_state);
3515 			break;
3516 
3517 		case L2CAP_CONF_EFS:
3518 			if (olen != sizeof(efs))
3519 				break;
3520 			remote_efs = 1;
3521 			memcpy(&efs, (void *) val, olen);
3522 			break;
3523 
3524 		case L2CAP_CONF_EWS:
3525 			if (olen != 2)
3526 				break;
3527 			return -ECONNREFUSED;
3528 
3529 		default:
3530 			if (hint)
3531 				break;
3532 			result = L2CAP_CONF_UNKNOWN;
3533 			l2cap_add_conf_opt(&ptr, (u8)type, sizeof(u8), type, endptr - ptr);
3534 			break;
3535 		}
3536 	}
3537 
3538 	if (chan->num_conf_rsp || chan->num_conf_req > 1)
3539 		goto done;
3540 
3541 	switch (chan->mode) {
3542 	case L2CAP_MODE_STREAMING:
3543 	case L2CAP_MODE_ERTM:
3544 		if (!test_bit(CONF_STATE2_DEVICE, &chan->conf_state)) {
3545 			chan->mode = l2cap_select_mode(rfc.mode,
3546 						       chan->conn->feat_mask);
3547 			break;
3548 		}
3549 
3550 		if (remote_efs) {
3551 			if (__l2cap_efs_supported(chan->conn))
3552 				set_bit(FLAG_EFS_ENABLE, &chan->flags);
3553 			else
3554 				return -ECONNREFUSED;
3555 		}
3556 
3557 		if (chan->mode != rfc.mode)
3558 			return -ECONNREFUSED;
3559 
3560 		break;
3561 	}
3562 
3563 done:
3564 	if (chan->mode != rfc.mode) {
3565 		result = L2CAP_CONF_UNACCEPT;
3566 		rfc.mode = chan->mode;
3567 
3568 		if (chan->num_conf_rsp == 1)
3569 			return -ECONNREFUSED;
3570 
3571 		l2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC, sizeof(rfc),
3572 				   (unsigned long) &rfc, endptr - ptr);
3573 	}
3574 
3575 	if (result == L2CAP_CONF_SUCCESS) {
3576 		/* Configure output options and let the other side know
3577 		 * which ones we don't like. */
3578 
3579 		/* If MTU is not provided in configure request, try adjusting it
3580 		 * to the current output MTU if it has been set
3581 		 *
3582 		 * Bluetooth Core 6.1, Vol 3, Part A, Section 4.5
3583 		 *
3584 		 * Each configuration parameter value (if any is present) in an
3585 		 * L2CAP_CONFIGURATION_RSP packet reflects an ‘adjustment’ to a
3586 		 * configuration parameter value that has been sent (or, in case
3587 		 * of default values, implied) in the corresponding
3588 		 * L2CAP_CONFIGURATION_REQ packet.
3589 		 */
3590 		if (!mtu) {
3591 			/* Only adjust for ERTM channels as for older modes the
3592 			 * remote stack may not be able to detect that the
3593 			 * adjustment causing it to silently drop packets.
3594 			 */
3595 			if (chan->mode == L2CAP_MODE_ERTM &&
3596 			    chan->omtu && chan->omtu != L2CAP_DEFAULT_MTU)
3597 				mtu = chan->omtu;
3598 			else
3599 				mtu = L2CAP_DEFAULT_MTU;
3600 		}
3601 
3602 		if (mtu < L2CAP_DEFAULT_MIN_MTU)
3603 			result = L2CAP_CONF_UNACCEPT;
3604 		else {
3605 			chan->omtu = mtu;
3606 			set_bit(CONF_MTU_DONE, &chan->conf_state);
3607 		}
3608 		l2cap_add_conf_opt(&ptr, L2CAP_CONF_MTU, 2, chan->omtu, endptr - ptr);
3609 
3610 		if (remote_efs) {
3611 			if (chan->local_stype != L2CAP_SERV_NOTRAFIC &&
3612 			    efs.stype != L2CAP_SERV_NOTRAFIC &&
3613 			    efs.stype != chan->local_stype) {
3614 
3615 				result = L2CAP_CONF_UNACCEPT;
3616 
3617 				if (chan->num_conf_req >= 1)
3618 					return -ECONNREFUSED;
3619 
3620 				l2cap_add_conf_opt(&ptr, L2CAP_CONF_EFS,
3621 						   sizeof(efs),
3622 						   (unsigned long) &efs, endptr - ptr);
3623 			} else {
3624 				/* Send PENDING Conf Rsp */
3625 				result = L2CAP_CONF_PENDING;
3626 				set_bit(CONF_LOC_CONF_PEND, &chan->conf_state);
3627 			}
3628 		}
3629 
3630 		switch (rfc.mode) {
3631 		case L2CAP_MODE_BASIC:
3632 			chan->fcs = L2CAP_FCS_NONE;
3633 			set_bit(CONF_MODE_DONE, &chan->conf_state);
3634 			break;
3635 
3636 		case L2CAP_MODE_ERTM:
3637 			if (!test_bit(CONF_EWS_RECV, &chan->conf_state))
3638 				chan->remote_tx_win = rfc.txwin_size;
3639 			else
3640 				rfc.txwin_size = L2CAP_DEFAULT_TX_WINDOW;
3641 
3642 			chan->remote_max_tx = rfc.max_transmit;
3643 
3644 			size = min_t(u16, le16_to_cpu(rfc.max_pdu_size),
3645 				     chan->conn->mtu - L2CAP_EXT_HDR_SIZE -
3646 				     L2CAP_SDULEN_SIZE - L2CAP_FCS_SIZE);
3647 			rfc.max_pdu_size = cpu_to_le16(size);
3648 			chan->remote_mps = size;
3649 
3650 			__l2cap_set_ertm_timeouts(chan, &rfc);
3651 
3652 			set_bit(CONF_MODE_DONE, &chan->conf_state);
3653 
3654 			l2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC,
3655 					   sizeof(rfc), (unsigned long) &rfc, endptr - ptr);
3656 
3657 			if (remote_efs &&
3658 			    test_bit(FLAG_EFS_ENABLE, &chan->flags)) {
3659 				chan->remote_id = efs.id;
3660 				chan->remote_stype = efs.stype;
3661 				chan->remote_msdu = le16_to_cpu(efs.msdu);
3662 				chan->remote_flush_to =
3663 					le32_to_cpu(efs.flush_to);
3664 				chan->remote_acc_lat =
3665 					le32_to_cpu(efs.acc_lat);
3666 				chan->remote_sdu_itime =
3667 					le32_to_cpu(efs.sdu_itime);
3668 				l2cap_add_conf_opt(&ptr, L2CAP_CONF_EFS,
3669 						   sizeof(efs),
3670 						   (unsigned long) &efs, endptr - ptr);
3671 			}
3672 			break;
3673 
3674 		case L2CAP_MODE_STREAMING:
3675 			size = min_t(u16, le16_to_cpu(rfc.max_pdu_size),
3676 				     chan->conn->mtu - L2CAP_EXT_HDR_SIZE -
3677 				     L2CAP_SDULEN_SIZE - L2CAP_FCS_SIZE);
3678 			rfc.max_pdu_size = cpu_to_le16(size);
3679 			chan->remote_mps = size;
3680 
3681 			set_bit(CONF_MODE_DONE, &chan->conf_state);
3682 
3683 			l2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC, sizeof(rfc),
3684 					   (unsigned long) &rfc, endptr - ptr);
3685 
3686 			break;
3687 
3688 		default:
3689 			result = L2CAP_CONF_UNACCEPT;
3690 
3691 			memset(&rfc, 0, sizeof(rfc));
3692 			rfc.mode = chan->mode;
3693 		}
3694 
3695 		if (result == L2CAP_CONF_SUCCESS)
3696 			set_bit(CONF_OUTPUT_DONE, &chan->conf_state);
3697 	}
3698 	rsp->scid   = cpu_to_le16(chan->dcid);
3699 	rsp->result = cpu_to_le16(result);
3700 	rsp->flags  = cpu_to_le16(0);
3701 
3702 	return ptr - data;
3703 }
3704 
3705 static int l2cap_parse_conf_rsp(struct l2cap_chan *chan, void *rsp, int len,
3706 				void *data, size_t size, u16 *result)
3707 {
3708 	struct l2cap_conf_req *req = data;
3709 	void *ptr = req->data;
3710 	void *endptr = data + size;
3711 	void *rsp_end = rsp + len;
3712 	int type, olen;
3713 	unsigned long val;
3714 	struct l2cap_conf_rfc rfc = { .mode = L2CAP_MODE_BASIC };
3715 	struct l2cap_conf_efs efs;
3716 
3717 	BT_DBG("chan %p, rsp %p, len %d, req %p", chan, rsp, len, data);
3718 
3719 	while (len >= L2CAP_CONF_OPT_SIZE) {
3720 		int ret = l2cap_get_conf_opt(&rsp, rsp_end, &type, &olen, &val);
3721 
3722 		if (ret < 0)
3723 			break;
3724 		len -= ret;
3725 
3726 		switch (type) {
3727 		case L2CAP_CONF_MTU:
3728 			if (olen != 2)
3729 				break;
3730 			if (val < L2CAP_DEFAULT_MIN_MTU) {
3731 				*result = L2CAP_CONF_UNACCEPT;
3732 				chan->imtu = L2CAP_DEFAULT_MIN_MTU;
3733 			} else
3734 				chan->imtu = val;
3735 			l2cap_add_conf_opt(&ptr, L2CAP_CONF_MTU, 2, chan->imtu,
3736 					   endptr - ptr);
3737 			break;
3738 
3739 		case L2CAP_CONF_FLUSH_TO:
3740 			if (olen != 2)
3741 				break;
3742 			chan->flush_to = val;
3743 			l2cap_add_conf_opt(&ptr, L2CAP_CONF_FLUSH_TO, 2,
3744 					   chan->flush_to, endptr - ptr);
3745 			break;
3746 
3747 		case L2CAP_CONF_RFC:
3748 			if (olen != sizeof(rfc))
3749 				break;
3750 			memcpy(&rfc, (void *)val, olen);
3751 			if (test_bit(CONF_STATE2_DEVICE, &chan->conf_state) &&
3752 			    rfc.mode != chan->mode)
3753 				return -ECONNREFUSED;
3754 			chan->fcs = 0;
3755 			l2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC, sizeof(rfc),
3756 					   (unsigned long) &rfc, endptr - ptr);
3757 			break;
3758 
3759 		case L2CAP_CONF_EWS:
3760 			if (olen != 2)
3761 				break;
3762 			chan->ack_win = min_t(u16, val, chan->ack_win);
3763 			l2cap_add_conf_opt(&ptr, L2CAP_CONF_EWS, 2,
3764 					   chan->tx_win, endptr - ptr);
3765 			break;
3766 
3767 		case L2CAP_CONF_EFS:
3768 			if (olen != sizeof(efs))
3769 				break;
3770 			memcpy(&efs, (void *)val, olen);
3771 			if (chan->local_stype != L2CAP_SERV_NOTRAFIC &&
3772 			    efs.stype != L2CAP_SERV_NOTRAFIC &&
3773 			    efs.stype != chan->local_stype)
3774 				return -ECONNREFUSED;
3775 			l2cap_add_conf_opt(&ptr, L2CAP_CONF_EFS, sizeof(efs),
3776 					   (unsigned long) &efs, endptr - ptr);
3777 			break;
3778 
3779 		case L2CAP_CONF_FCS:
3780 			if (olen != 1)
3781 				break;
3782 			if (*result == L2CAP_CONF_PENDING)
3783 				if (val == L2CAP_FCS_NONE)
3784 					set_bit(CONF_RECV_NO_FCS,
3785 						&chan->conf_state);
3786 			break;
3787 		}
3788 	}
3789 
3790 	if (chan->mode == L2CAP_MODE_BASIC && chan->mode != rfc.mode)
3791 		return -ECONNREFUSED;
3792 
3793 	chan->mode = rfc.mode;
3794 
3795 	if (*result == L2CAP_CONF_SUCCESS || *result == L2CAP_CONF_PENDING) {
3796 		switch (rfc.mode) {
3797 		case L2CAP_MODE_ERTM:
3798 			chan->retrans_timeout = le16_to_cpu(rfc.retrans_timeout);
3799 			chan->monitor_timeout = le16_to_cpu(rfc.monitor_timeout);
3800 			chan->mps    = le16_to_cpu(rfc.max_pdu_size);
3801 			if (!test_bit(FLAG_EXT_CTRL, &chan->flags))
3802 				chan->ack_win = min_t(u16, chan->ack_win,
3803 						      rfc.txwin_size);
3804 
3805 			if (test_bit(FLAG_EFS_ENABLE, &chan->flags)) {
3806 				chan->local_msdu = le16_to_cpu(efs.msdu);
3807 				chan->local_sdu_itime =
3808 					le32_to_cpu(efs.sdu_itime);
3809 				chan->local_acc_lat = le32_to_cpu(efs.acc_lat);
3810 				chan->local_flush_to =
3811 					le32_to_cpu(efs.flush_to);
3812 			}
3813 			break;
3814 
3815 		case L2CAP_MODE_STREAMING:
3816 			chan->mps    = le16_to_cpu(rfc.max_pdu_size);
3817 		}
3818 	}
3819 
3820 	req->dcid   = cpu_to_le16(chan->dcid);
3821 	req->flags  = cpu_to_le16(0);
3822 
3823 	return ptr - data;
3824 }
3825 
3826 static int l2cap_build_conf_rsp(struct l2cap_chan *chan, void *data,
3827 				u16 result, u16 flags)
3828 {
3829 	struct l2cap_conf_rsp *rsp = data;
3830 	void *ptr = rsp->data;
3831 
3832 	BT_DBG("chan %p", chan);
3833 
3834 	rsp->scid   = cpu_to_le16(chan->dcid);
3835 	rsp->result = cpu_to_le16(result);
3836 	rsp->flags  = cpu_to_le16(flags);
3837 
3838 	return ptr - data;
3839 }
3840 
3841 void __l2cap_le_connect_rsp_defer(struct l2cap_chan *chan)
3842 {
3843 	struct l2cap_le_conn_rsp rsp;
3844 	struct l2cap_conn *conn = chan->conn;
3845 
3846 	BT_DBG("chan %p", chan);
3847 
3848 	rsp.dcid    = cpu_to_le16(chan->scid);
3849 	rsp.mtu     = cpu_to_le16(chan->imtu);
3850 	rsp.mps     = cpu_to_le16(chan->mps);
3851 	rsp.credits = cpu_to_le16(chan->rx_credits);
3852 	rsp.result  = cpu_to_le16(L2CAP_CR_LE_SUCCESS);
3853 
3854 	l2cap_send_cmd(conn, chan->ident, L2CAP_LE_CONN_RSP, sizeof(rsp),
3855 		       &rsp);
3856 }
3857 
3858 static void l2cap_ecred_list_defer(struct l2cap_chan *chan, void *data)
3859 {
3860 	int *result = data;
3861 
3862 	if (*result || test_bit(FLAG_ECRED_CONN_REQ_SENT, &chan->flags))
3863 		return;
3864 
3865 	switch (chan->state) {
3866 	case BT_CONNECT2:
3867 		/* If channel still pending accept add to result */
3868 		(*result)++;
3869 		return;
3870 	case BT_CONNECTED:
3871 		return;
3872 	default:
3873 		/* If not connected or pending accept it has been refused */
3874 		*result = -ECONNREFUSED;
3875 		return;
3876 	}
3877 }
3878 
3879 struct l2cap_ecred_rsp_data {
3880 	struct {
3881 		struct l2cap_ecred_conn_rsp_hdr rsp;
3882 		__le16 scid[L2CAP_ECRED_MAX_CID];
3883 	} __packed pdu;
3884 	int count;
3885 };
3886 
3887 static void l2cap_ecred_rsp_defer(struct l2cap_chan *chan, void *data)
3888 {
3889 	struct l2cap_ecred_rsp_data *rsp = data;
3890 	struct l2cap_ecred_conn_rsp *rsp_flex =
3891 		container_of(&rsp->pdu.rsp, struct l2cap_ecred_conn_rsp, hdr);
3892 
3893 	/* Check if channel for outgoing connection or if it wasn't deferred
3894 	 * since in those cases it must be skipped.
3895 	 */
3896 	if (test_bit(FLAG_ECRED_CONN_REQ_SENT, &chan->flags) ||
3897 	    !test_and_clear_bit(FLAG_DEFER_SETUP, &chan->flags))
3898 		return;
3899 
3900 	/* Reset ident so only one response is sent */
3901 	chan->ident = 0;
3902 
3903 	/* Include all channels pending with the same ident */
3904 	if (!rsp->pdu.rsp.result)
3905 		rsp_flex->dcid[rsp->count++] = cpu_to_le16(chan->scid);
3906 	else
3907 		l2cap_chan_del(chan, ECONNRESET);
3908 }
3909 
3910 void __l2cap_ecred_conn_rsp_defer(struct l2cap_chan *chan)
3911 {
3912 	struct l2cap_conn *conn = chan->conn;
3913 	struct l2cap_ecred_rsp_data data;
3914 	u16 id = chan->ident;
3915 	int result = 0;
3916 
3917 	if (!id)
3918 		return;
3919 
3920 	BT_DBG("chan %p id %d", chan, id);
3921 
3922 	memset(&data, 0, sizeof(data));
3923 
3924 	data.pdu.rsp.mtu     = cpu_to_le16(chan->imtu);
3925 	data.pdu.rsp.mps     = cpu_to_le16(chan->mps);
3926 	data.pdu.rsp.credits = cpu_to_le16(chan->rx_credits);
3927 	data.pdu.rsp.result  = cpu_to_le16(L2CAP_CR_LE_SUCCESS);
3928 
3929 	/* Verify that all channels are ready */
3930 	__l2cap_chan_list_id(conn, id, l2cap_ecred_list_defer, &result);
3931 
3932 	if (result > 0)
3933 		return;
3934 
3935 	if (result < 0)
3936 		data.pdu.rsp.result = cpu_to_le16(L2CAP_CR_LE_AUTHORIZATION);
3937 
3938 	/* Build response */
3939 	__l2cap_chan_list_id(conn, id, l2cap_ecred_rsp_defer, &data);
3940 
3941 	l2cap_send_cmd(conn, id, L2CAP_ECRED_CONN_RSP,
3942 		       sizeof(data.pdu.rsp) + (data.count * sizeof(__le16)),
3943 		       &data.pdu);
3944 }
3945 
3946 void __l2cap_connect_rsp_defer(struct l2cap_chan *chan)
3947 {
3948 	struct l2cap_conn_rsp rsp;
3949 	struct l2cap_conn *conn = chan->conn;
3950 	u8 buf[128];
3951 	u8 rsp_code;
3952 
3953 	rsp.scid   = cpu_to_le16(chan->dcid);
3954 	rsp.dcid   = cpu_to_le16(chan->scid);
3955 	rsp.result = cpu_to_le16(L2CAP_CR_SUCCESS);
3956 	rsp.status = cpu_to_le16(L2CAP_CS_NO_INFO);
3957 	rsp_code = L2CAP_CONN_RSP;
3958 
3959 	BT_DBG("chan %p rsp_code %u", chan, rsp_code);
3960 
3961 	l2cap_send_cmd(conn, chan->ident, rsp_code, sizeof(rsp), &rsp);
3962 
3963 	if (test_and_set_bit(CONF_REQ_SENT, &chan->conf_state))
3964 		return;
3965 
3966 	l2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_CONF_REQ,
3967 		       l2cap_build_conf_req(chan, buf, sizeof(buf)), buf);
3968 	chan->num_conf_req++;
3969 }
3970 
3971 static void l2cap_conf_rfc_get(struct l2cap_chan *chan, void *rsp, int len)
3972 {
3973 	int type, olen;
3974 	unsigned long val;
3975 	void *rsp_end = rsp + len;
3976 	/* Use sane default values in case a misbehaving remote device
3977 	 * did not send an RFC or extended window size option.
3978 	 */
3979 	u16 txwin_ext = chan->ack_win;
3980 	struct l2cap_conf_rfc rfc = {
3981 		.mode = chan->mode,
3982 		.retrans_timeout = cpu_to_le16(L2CAP_DEFAULT_RETRANS_TO),
3983 		.monitor_timeout = cpu_to_le16(L2CAP_DEFAULT_MONITOR_TO),
3984 		.max_pdu_size = cpu_to_le16(chan->imtu),
3985 		.txwin_size = min_t(u16, chan->ack_win, L2CAP_DEFAULT_TX_WINDOW),
3986 	};
3987 
3988 	BT_DBG("chan %p, rsp %p, len %d", chan, rsp, len);
3989 
3990 	if ((chan->mode != L2CAP_MODE_ERTM) && (chan->mode != L2CAP_MODE_STREAMING))
3991 		return;
3992 
3993 	while (len >= L2CAP_CONF_OPT_SIZE) {
3994 		int ret = l2cap_get_conf_opt(&rsp, rsp_end, &type, &olen, &val);
3995 
3996 		if (ret < 0)
3997 			break;
3998 		len -= ret;
3999 
4000 		switch (type) {
4001 		case L2CAP_CONF_RFC:
4002 			if (olen != sizeof(rfc))
4003 				break;
4004 			memcpy(&rfc, (void *)val, olen);
4005 			break;
4006 		case L2CAP_CONF_EWS:
4007 			if (olen != 2)
4008 				break;
4009 			txwin_ext = val;
4010 			break;
4011 		}
4012 	}
4013 
4014 	switch (rfc.mode) {
4015 	case L2CAP_MODE_ERTM:
4016 		chan->retrans_timeout = le16_to_cpu(rfc.retrans_timeout);
4017 		chan->monitor_timeout = le16_to_cpu(rfc.monitor_timeout);
4018 		chan->mps = le16_to_cpu(rfc.max_pdu_size);
4019 		if (test_bit(FLAG_EXT_CTRL, &chan->flags))
4020 			chan->ack_win = min_t(u16, chan->ack_win, txwin_ext);
4021 		else
4022 			chan->ack_win = min_t(u16, chan->ack_win,
4023 					      rfc.txwin_size);
4024 		break;
4025 	case L2CAP_MODE_STREAMING:
4026 		chan->mps    = le16_to_cpu(rfc.max_pdu_size);
4027 	}
4028 }
4029 
4030 static inline int l2cap_command_rej(struct l2cap_conn *conn,
4031 				    struct l2cap_cmd_hdr *cmd, u16 cmd_len,
4032 				    u8 *data)
4033 {
4034 	struct l2cap_cmd_rej_unk *rej = (struct l2cap_cmd_rej_unk *) data;
4035 
4036 	if (cmd_len < sizeof(*rej))
4037 		return -EPROTO;
4038 
4039 	if (rej->reason != L2CAP_REJ_NOT_UNDERSTOOD)
4040 		return 0;
4041 
4042 	if ((conn->info_state & L2CAP_INFO_FEAT_MASK_REQ_SENT) &&
4043 	    cmd->ident == conn->info_ident) {
4044 		cancel_delayed_work(&conn->info_timer);
4045 
4046 		conn->info_state |= L2CAP_INFO_FEAT_MASK_REQ_DONE;
4047 		conn->info_ident = 0;
4048 
4049 		l2cap_conn_start(conn);
4050 	}
4051 
4052 	return 0;
4053 }
4054 
4055 /* Allocate and initialise a channel for an incoming connection.
4056  *
4057  * The channel inherits its configuration from @pchan and is linked into @conn
4058  * before ->new_connection() runs, so the conn list reference keeps it alive if
4059  * the callback exposes it (e.g. via the socket accept queue) before this
4060  * returns. The l2cap_chan_create() reference is taken over by the subsystem on
4061  * success and dropped here on failure.
4062  */
4063 static struct l2cap_chan *l2cap_new_connection(struct l2cap_conn *conn,
4064 					       struct l2cap_chan *pchan)
4065 {
4066 	struct l2cap_chan *chan;
4067 
4068 	chan = l2cap_chan_create();
4069 	if (!chan)
4070 		return NULL;
4071 
4072 	l2cap_chan_set_defaults(chan, pchan);
4073 	chan->ops = pchan->ops;
4074 
4075 	__l2cap_chan_add(conn, chan);
4076 
4077 	if (pchan->ops->new_connection &&
4078 	    pchan->ops->new_connection(pchan, chan) < 0) {
4079 		l2cap_chan_del(chan, 0);
4080 		l2cap_chan_put(chan);
4081 		return NULL;
4082 	}
4083 
4084 	return chan;
4085 }
4086 
4087 static void l2cap_connect(struct l2cap_conn *conn, struct l2cap_cmd_hdr *cmd,
4088 			  u8 *data, u8 rsp_code)
4089 {
4090 	struct l2cap_conn_req *req = (struct l2cap_conn_req *) data;
4091 	struct l2cap_conn_rsp rsp;
4092 	struct l2cap_chan *chan = NULL, *pchan = NULL;
4093 	int result, status = L2CAP_CS_NO_INFO;
4094 
4095 	u16 dcid = 0, scid = __le16_to_cpu(req->scid);
4096 	__le16 psm = req->psm;
4097 
4098 	BT_DBG("psm 0x%2.2x scid 0x%4.4x", __le16_to_cpu(psm), scid);
4099 
4100 	/* Check if we have socket listening on psm */
4101 	pchan = l2cap_global_chan_by_psm(BT_LISTEN, psm, &conn->hcon->src,
4102 					 &conn->hcon->dst, ACL_LINK);
4103 	if (!pchan) {
4104 		result = L2CAP_CR_BAD_PSM;
4105 		goto response;
4106 	}
4107 
4108 	l2cap_chan_lock(pchan);
4109 
4110 	/* Check if the ACL is secure enough (if not SDP) */
4111 	if (psm != cpu_to_le16(L2CAP_PSM_SDP) &&
4112 	    (!hci_conn_check_link_mode(conn->hcon) ||
4113 	    !l2cap_check_enc_key_size(conn->hcon, pchan))) {
4114 		conn->disc_reason = HCI_ERROR_AUTH_FAILURE;
4115 		result = L2CAP_CR_SEC_BLOCK;
4116 		goto response;
4117 	}
4118 
4119 	result = L2CAP_CR_NO_MEM;
4120 
4121 	/* Check for valid dynamic CID range (as per Erratum 3253) */
4122 	if (scid < L2CAP_CID_DYN_START || scid > L2CAP_CID_DYN_END) {
4123 		result = L2CAP_CR_INVALID_SCID;
4124 		goto response;
4125 	}
4126 
4127 	/* Check if we already have channel with that dcid */
4128 	if (__l2cap_get_chan_by_dcid(conn, scid)) {
4129 		result = L2CAP_CR_SCID_IN_USE;
4130 		goto response;
4131 	}
4132 
4133 	chan = l2cap_new_connection(conn, pchan);
4134 	if (!chan)
4135 		goto response;
4136 
4137 	/* For certain devices (ex: HID mouse), support for authentication,
4138 	 * pairing and bonding is optional. For such devices, inorder to avoid
4139 	 * the ACL alive for too long after L2CAP disconnection, reset the ACL
4140 	 * disc_timeout back to HCI_DISCONN_TIMEOUT during L2CAP connect.
4141 	 */
4142 	conn->hcon->disc_timeout = HCI_DISCONN_TIMEOUT;
4143 
4144 	bacpy(&chan->src, &conn->hcon->src);
4145 	bacpy(&chan->dst, &conn->hcon->dst);
4146 	chan->src_type = bdaddr_src_type(conn->hcon);
4147 	chan->dst_type = bdaddr_dst_type(conn->hcon);
4148 	chan->psm  = psm;
4149 	chan->dcid = scid;
4150 
4151 	dcid = chan->scid;
4152 
4153 	__set_chan_timer(chan, chan->ops->get_sndtimeo(chan));
4154 
4155 	chan->ident = cmd->ident;
4156 
4157 	if (conn->info_state & L2CAP_INFO_FEAT_MASK_REQ_DONE) {
4158 		if (l2cap_chan_check_security(chan, false)) {
4159 			if (test_bit(FLAG_DEFER_SETUP, &chan->flags)) {
4160 				l2cap_state_change(chan, BT_CONNECT2);
4161 				result = L2CAP_CR_PEND;
4162 				status = L2CAP_CS_AUTHOR_PEND;
4163 				chan->ops->defer(chan);
4164 			} else {
4165 				l2cap_state_change(chan, BT_CONFIG);
4166 				result = L2CAP_CR_SUCCESS;
4167 				status = L2CAP_CS_NO_INFO;
4168 			}
4169 		} else {
4170 			l2cap_state_change(chan, BT_CONNECT2);
4171 			result = L2CAP_CR_PEND;
4172 			status = L2CAP_CS_AUTHEN_PEND;
4173 		}
4174 	} else {
4175 		l2cap_state_change(chan, BT_CONNECT2);
4176 		result = L2CAP_CR_PEND;
4177 		status = L2CAP_CS_NO_INFO;
4178 	}
4179 
4180 response:
4181 	rsp.scid   = cpu_to_le16(scid);
4182 	rsp.dcid   = cpu_to_le16(dcid);
4183 	rsp.result = cpu_to_le16(result);
4184 	rsp.status = cpu_to_le16(status);
4185 	l2cap_send_cmd(conn, cmd->ident, rsp_code, sizeof(rsp), &rsp);
4186 
4187 	if (!pchan)
4188 		return;
4189 
4190 	if (result == L2CAP_CR_PEND && status == L2CAP_CS_NO_INFO) {
4191 		struct l2cap_info_req info;
4192 		info.type = cpu_to_le16(L2CAP_IT_FEAT_MASK);
4193 
4194 		conn->info_state |= L2CAP_INFO_FEAT_MASK_REQ_SENT;
4195 		conn->info_ident = l2cap_get_ident(conn);
4196 
4197 		schedule_delayed_work(&conn->info_timer, L2CAP_INFO_TIMEOUT);
4198 
4199 		l2cap_send_cmd(conn, conn->info_ident, L2CAP_INFO_REQ,
4200 			       sizeof(info), &info);
4201 	}
4202 
4203 	if (chan && !test_bit(CONF_REQ_SENT, &chan->conf_state) &&
4204 	    result == L2CAP_CR_SUCCESS) {
4205 		u8 buf[128];
4206 		set_bit(CONF_REQ_SENT, &chan->conf_state);
4207 		l2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_CONF_REQ,
4208 			       l2cap_build_conf_req(chan, buf, sizeof(buf)), buf);
4209 		chan->num_conf_req++;
4210 	}
4211 
4212 	l2cap_chan_unlock(pchan);
4213 	l2cap_chan_put(pchan);
4214 }
4215 
4216 static int l2cap_connect_req(struct l2cap_conn *conn,
4217 			     struct l2cap_cmd_hdr *cmd, u16 cmd_len, u8 *data)
4218 {
4219 	if (cmd_len < sizeof(struct l2cap_conn_req))
4220 		return -EPROTO;
4221 
4222 	l2cap_connect(conn, cmd, data, L2CAP_CONN_RSP);
4223 	return 0;
4224 }
4225 
4226 static int l2cap_connect_create_rsp(struct l2cap_conn *conn,
4227 				    struct l2cap_cmd_hdr *cmd, u16 cmd_len,
4228 				    u8 *data)
4229 {
4230 	struct l2cap_conn_rsp *rsp = (struct l2cap_conn_rsp *) data;
4231 	u16 scid, dcid, result, status;
4232 	struct l2cap_chan *chan;
4233 	u8 req[128];
4234 	int err;
4235 
4236 	if (cmd_len < sizeof(*rsp))
4237 		return -EPROTO;
4238 
4239 	scid   = __le16_to_cpu(rsp->scid);
4240 	dcid   = __le16_to_cpu(rsp->dcid);
4241 	result = __le16_to_cpu(rsp->result);
4242 	status = __le16_to_cpu(rsp->status);
4243 
4244 	if (result == L2CAP_CR_SUCCESS && (dcid < L2CAP_CID_DYN_START ||
4245 					   dcid > L2CAP_CID_DYN_END))
4246 		return -EPROTO;
4247 
4248 	BT_DBG("dcid 0x%4.4x scid 0x%4.4x result 0x%2.2x status 0x%2.2x",
4249 	       dcid, scid, result, status);
4250 
4251 	if (scid) {
4252 		chan = __l2cap_get_chan_by_scid(conn, scid);
4253 		if (!chan)
4254 			return -EBADSLT;
4255 	} else {
4256 		chan = __l2cap_get_chan_by_ident(conn, cmd->ident);
4257 		if (!chan)
4258 			return -EBADSLT;
4259 	}
4260 
4261 	chan = l2cap_chan_hold_unless_zero(chan);
4262 	if (!chan)
4263 		return -EBADSLT;
4264 
4265 	err = 0;
4266 
4267 	l2cap_chan_lock(chan);
4268 
4269 	switch (result) {
4270 	case L2CAP_CR_SUCCESS:
4271 		if (__l2cap_get_chan_by_dcid(conn, dcid)) {
4272 			err = -EBADSLT;
4273 			break;
4274 		}
4275 
4276 		l2cap_state_change(chan, BT_CONFIG);
4277 		chan->ident = 0;
4278 		chan->dcid = dcid;
4279 		clear_bit(CONF_CONNECT_PEND, &chan->conf_state);
4280 
4281 		if (test_and_set_bit(CONF_REQ_SENT, &chan->conf_state))
4282 			break;
4283 
4284 		l2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_CONF_REQ,
4285 			       l2cap_build_conf_req(chan, req, sizeof(req)), req);
4286 		chan->num_conf_req++;
4287 		break;
4288 
4289 	case L2CAP_CR_PEND:
4290 		set_bit(CONF_CONNECT_PEND, &chan->conf_state);
4291 		break;
4292 
4293 	default:
4294 		l2cap_chan_del(chan, ECONNREFUSED);
4295 		break;
4296 	}
4297 
4298 	l2cap_chan_unlock(chan);
4299 	l2cap_chan_put(chan);
4300 
4301 	return err;
4302 }
4303 
4304 static inline void set_default_fcs(struct l2cap_chan *chan)
4305 {
4306 	/* FCS is enabled only in ERTM or streaming mode, if one or both
4307 	 * sides request it.
4308 	 */
4309 	if (chan->mode != L2CAP_MODE_ERTM && chan->mode != L2CAP_MODE_STREAMING)
4310 		chan->fcs = L2CAP_FCS_NONE;
4311 	else if (!test_bit(CONF_RECV_NO_FCS, &chan->conf_state))
4312 		chan->fcs = L2CAP_FCS_CRC16;
4313 }
4314 
4315 static void l2cap_send_efs_conf_rsp(struct l2cap_chan *chan, void *data,
4316 				    u8 ident, u16 flags)
4317 {
4318 	struct l2cap_conn *conn = chan->conn;
4319 
4320 	BT_DBG("conn %p chan %p ident %d flags 0x%4.4x", conn, chan, ident,
4321 	       flags);
4322 
4323 	clear_bit(CONF_LOC_CONF_PEND, &chan->conf_state);
4324 	set_bit(CONF_OUTPUT_DONE, &chan->conf_state);
4325 
4326 	l2cap_send_cmd(conn, ident, L2CAP_CONF_RSP,
4327 		       l2cap_build_conf_rsp(chan, data,
4328 					    L2CAP_CONF_SUCCESS, flags), data);
4329 }
4330 
4331 static void cmd_reject_invalid_cid(struct l2cap_conn *conn, u8 ident,
4332 				   u16 scid, u16 dcid)
4333 {
4334 	struct l2cap_cmd_rej_cid rej;
4335 
4336 	rej.reason = cpu_to_le16(L2CAP_REJ_INVALID_CID);
4337 	rej.scid = __cpu_to_le16(scid);
4338 	rej.dcid = __cpu_to_le16(dcid);
4339 
4340 	l2cap_send_cmd(conn, ident, L2CAP_COMMAND_REJ, sizeof(rej), &rej);
4341 }
4342 
4343 static inline int l2cap_config_req(struct l2cap_conn *conn,
4344 				   struct l2cap_cmd_hdr *cmd, u16 cmd_len,
4345 				   u8 *data)
4346 {
4347 	struct l2cap_conf_req *req = (struct l2cap_conf_req *) data;
4348 	u16 dcid, flags;
4349 	u8 rsp[64];
4350 	struct l2cap_chan *chan;
4351 	int len, err = 0;
4352 
4353 	if (cmd_len < sizeof(*req))
4354 		return -EPROTO;
4355 
4356 	dcid  = __le16_to_cpu(req->dcid);
4357 	flags = __le16_to_cpu(req->flags);
4358 
4359 	BT_DBG("dcid 0x%4.4x flags 0x%2.2x", dcid, flags);
4360 
4361 	chan = l2cap_get_chan_by_scid(conn, dcid);
4362 	if (!chan) {
4363 		cmd_reject_invalid_cid(conn, cmd->ident, dcid, 0);
4364 		return 0;
4365 	}
4366 
4367 	if (chan->state != BT_CONFIG && chan->state != BT_CONNECT2 &&
4368 	    chan->state != BT_CONNECTED) {
4369 		cmd_reject_invalid_cid(conn, cmd->ident, chan->scid,
4370 				       chan->dcid);
4371 		goto unlock;
4372 	}
4373 
4374 	/* Reject if config buffer is too small. */
4375 	len = cmd_len - sizeof(*req);
4376 	if (chan->conf_len + len > sizeof(chan->conf_req)) {
4377 		l2cap_send_cmd(conn, cmd->ident, L2CAP_CONF_RSP,
4378 			       l2cap_build_conf_rsp(chan, rsp,
4379 			       L2CAP_CONF_REJECT, flags), rsp);
4380 		goto unlock;
4381 	}
4382 
4383 	/* Store config. */
4384 	memcpy(chan->conf_req + chan->conf_len, req->data, len);
4385 	chan->conf_len += len;
4386 
4387 	if (flags & L2CAP_CONF_FLAG_CONTINUATION) {
4388 		/* Incomplete config. Send empty response. */
4389 		l2cap_send_cmd(conn, cmd->ident, L2CAP_CONF_RSP,
4390 			       l2cap_build_conf_rsp(chan, rsp,
4391 			       L2CAP_CONF_SUCCESS, flags), rsp);
4392 		goto unlock;
4393 	}
4394 
4395 	/* Complete config. */
4396 	len = l2cap_parse_conf_req(chan, rsp, sizeof(rsp));
4397 	if (len < 0) {
4398 		l2cap_send_disconn_req(chan, ECONNRESET);
4399 		goto unlock;
4400 	}
4401 
4402 	chan->ident = cmd->ident;
4403 	l2cap_send_cmd(conn, cmd->ident, L2CAP_CONF_RSP, len, rsp);
4404 	if (chan->num_conf_rsp < L2CAP_CONF_MAX_CONF_RSP)
4405 		chan->num_conf_rsp++;
4406 
4407 	/* Reset config buffer. */
4408 	chan->conf_len = 0;
4409 
4410 	if (!test_bit(CONF_OUTPUT_DONE, &chan->conf_state))
4411 		goto unlock;
4412 
4413 	if (test_bit(CONF_INPUT_DONE, &chan->conf_state)) {
4414 		set_default_fcs(chan);
4415 
4416 		if (chan->state != BT_CONNECTED) {
4417 			if (chan->mode == L2CAP_MODE_ERTM ||
4418 			    chan->mode == L2CAP_MODE_STREAMING)
4419 				err = l2cap_ertm_init(chan);
4420 
4421 			if (err < 0)
4422 				l2cap_send_disconn_req(chan, -err);
4423 			else
4424 				l2cap_chan_ready(chan);
4425 		}
4426 
4427 		goto unlock;
4428 	}
4429 
4430 	if (!test_and_set_bit(CONF_REQ_SENT, &chan->conf_state)) {
4431 		u8 buf[64];
4432 		l2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_CONF_REQ,
4433 			       l2cap_build_conf_req(chan, buf, sizeof(buf)), buf);
4434 		chan->num_conf_req++;
4435 	}
4436 
4437 	/* Got Conf Rsp PENDING from remote side and assume we sent
4438 	   Conf Rsp PENDING in the code above */
4439 	if (test_bit(CONF_REM_CONF_PEND, &chan->conf_state) &&
4440 	    test_bit(CONF_LOC_CONF_PEND, &chan->conf_state)) {
4441 
4442 		/* check compatibility */
4443 
4444 		/* Send rsp for BR/EDR channel */
4445 		l2cap_send_efs_conf_rsp(chan, rsp, cmd->ident, flags);
4446 	}
4447 
4448 unlock:
4449 	l2cap_chan_unlock(chan);
4450 	l2cap_chan_put(chan);
4451 	return err;
4452 }
4453 
4454 static inline int l2cap_config_rsp(struct l2cap_conn *conn,
4455 				   struct l2cap_cmd_hdr *cmd, u16 cmd_len,
4456 				   u8 *data)
4457 {
4458 	struct l2cap_conf_rsp *rsp = (struct l2cap_conf_rsp *)data;
4459 	u16 scid, flags, result;
4460 	struct l2cap_chan *chan;
4461 	int len = cmd_len - sizeof(*rsp);
4462 	int err = 0;
4463 
4464 	if (cmd_len < sizeof(*rsp))
4465 		return -EPROTO;
4466 
4467 	scid   = __le16_to_cpu(rsp->scid);
4468 	flags  = __le16_to_cpu(rsp->flags);
4469 	result = __le16_to_cpu(rsp->result);
4470 
4471 	BT_DBG("scid 0x%4.4x flags 0x%2.2x result 0x%2.2x len %d", scid, flags,
4472 	       result, len);
4473 
4474 	chan = l2cap_get_chan_by_scid(conn, scid);
4475 	if (!chan)
4476 		return 0;
4477 
4478 	switch (result) {
4479 	case L2CAP_CONF_SUCCESS:
4480 		l2cap_conf_rfc_get(chan, rsp->data, len);
4481 		clear_bit(CONF_REM_CONF_PEND, &chan->conf_state);
4482 		break;
4483 
4484 	case L2CAP_CONF_PENDING:
4485 		set_bit(CONF_REM_CONF_PEND, &chan->conf_state);
4486 
4487 		if (test_bit(CONF_LOC_CONF_PEND, &chan->conf_state)) {
4488 			char buf[64];
4489 
4490 			len = l2cap_parse_conf_rsp(chan, rsp->data, len,
4491 						   buf, sizeof(buf), &result);
4492 			if (len < 0) {
4493 				l2cap_send_disconn_req(chan, ECONNRESET);
4494 				goto done;
4495 			}
4496 
4497 			l2cap_send_efs_conf_rsp(chan, buf, cmd->ident, 0);
4498 		}
4499 		goto done;
4500 
4501 	case L2CAP_CONF_UNKNOWN:
4502 	case L2CAP_CONF_UNACCEPT:
4503 		if (chan->num_conf_rsp <= L2CAP_CONF_MAX_CONF_RSP) {
4504 			char req[64];
4505 
4506 			if (len > sizeof(req) - sizeof(struct l2cap_conf_req)) {
4507 				l2cap_send_disconn_req(chan, ECONNRESET);
4508 				goto done;
4509 			}
4510 
4511 			/* throw out any old stored conf requests */
4512 			result = L2CAP_CONF_SUCCESS;
4513 			len = l2cap_parse_conf_rsp(chan, rsp->data, len,
4514 						   req, sizeof(req), &result);
4515 			if (len < 0) {
4516 				l2cap_send_disconn_req(chan, ECONNRESET);
4517 				goto done;
4518 			}
4519 
4520 			l2cap_send_cmd(conn, l2cap_get_ident(conn),
4521 				       L2CAP_CONF_REQ, len, req);
4522 			chan->num_conf_req++;
4523 			if (result != L2CAP_CONF_SUCCESS)
4524 				goto done;
4525 			break;
4526 		}
4527 		fallthrough;
4528 
4529 	default:
4530 		l2cap_chan_set_err(chan, ECONNRESET);
4531 
4532 		__set_chan_timer(chan, L2CAP_DISC_REJ_TIMEOUT);
4533 		l2cap_send_disconn_req(chan, ECONNRESET);
4534 		goto done;
4535 	}
4536 
4537 	if (flags & L2CAP_CONF_FLAG_CONTINUATION)
4538 		goto done;
4539 
4540 	set_bit(CONF_INPUT_DONE, &chan->conf_state);
4541 
4542 	if (test_bit(CONF_OUTPUT_DONE, &chan->conf_state)) {
4543 		set_default_fcs(chan);
4544 
4545 		if (chan->mode == L2CAP_MODE_ERTM ||
4546 		    chan->mode == L2CAP_MODE_STREAMING)
4547 			err = l2cap_ertm_init(chan);
4548 
4549 		if (err < 0)
4550 			l2cap_send_disconn_req(chan, -err);
4551 		else
4552 			l2cap_chan_ready(chan);
4553 	}
4554 
4555 done:
4556 	l2cap_chan_unlock(chan);
4557 	l2cap_chan_put(chan);
4558 	return err;
4559 }
4560 
4561 static inline int l2cap_disconnect_req(struct l2cap_conn *conn,
4562 				       struct l2cap_cmd_hdr *cmd, u16 cmd_len,
4563 				       u8 *data)
4564 {
4565 	struct l2cap_disconn_req *req = (struct l2cap_disconn_req *) data;
4566 	struct l2cap_disconn_rsp rsp;
4567 	u16 dcid, scid;
4568 	struct l2cap_chan *chan;
4569 
4570 	if (cmd_len != sizeof(*req))
4571 		return -EPROTO;
4572 
4573 	scid = __le16_to_cpu(req->scid);
4574 	dcid = __le16_to_cpu(req->dcid);
4575 
4576 	BT_DBG("scid 0x%4.4x dcid 0x%4.4x", scid, dcid);
4577 
4578 	chan = l2cap_get_chan_by_scid(conn, dcid);
4579 	if (!chan) {
4580 		cmd_reject_invalid_cid(conn, cmd->ident, dcid, scid);
4581 		return 0;
4582 	}
4583 
4584 	rsp.dcid = cpu_to_le16(chan->scid);
4585 	rsp.scid = cpu_to_le16(chan->dcid);
4586 	l2cap_send_cmd(conn, cmd->ident, L2CAP_DISCONN_RSP, sizeof(rsp), &rsp);
4587 
4588 	chan->ops->set_shutdown(chan);
4589 
4590 	l2cap_chan_del(chan, ECONNRESET);
4591 
4592 	chan->ops->close(chan);
4593 
4594 	l2cap_chan_unlock(chan);
4595 	l2cap_chan_put(chan);
4596 
4597 	return 0;
4598 }
4599 
4600 static inline int l2cap_disconnect_rsp(struct l2cap_conn *conn,
4601 				       struct l2cap_cmd_hdr *cmd, u16 cmd_len,
4602 				       u8 *data)
4603 {
4604 	struct l2cap_disconn_rsp *rsp = (struct l2cap_disconn_rsp *) data;
4605 	u16 dcid, scid;
4606 	struct l2cap_chan *chan;
4607 
4608 	if (cmd_len != sizeof(*rsp))
4609 		return -EPROTO;
4610 
4611 	scid = __le16_to_cpu(rsp->scid);
4612 	dcid = __le16_to_cpu(rsp->dcid);
4613 
4614 	BT_DBG("dcid 0x%4.4x scid 0x%4.4x", dcid, scid);
4615 
4616 	chan = l2cap_get_chan_by_scid(conn, scid);
4617 	if (!chan) {
4618 		return 0;
4619 	}
4620 
4621 	if (chan->state != BT_DISCONN) {
4622 		l2cap_chan_unlock(chan);
4623 		l2cap_chan_put(chan);
4624 		return 0;
4625 	}
4626 
4627 	l2cap_chan_del(chan, 0);
4628 
4629 	chan->ops->close(chan);
4630 
4631 	l2cap_chan_unlock(chan);
4632 	l2cap_chan_put(chan);
4633 
4634 	return 0;
4635 }
4636 
4637 static inline int l2cap_information_req(struct l2cap_conn *conn,
4638 					struct l2cap_cmd_hdr *cmd, u16 cmd_len,
4639 					u8 *data)
4640 {
4641 	struct l2cap_info_req *req = (struct l2cap_info_req *) data;
4642 	u16 type;
4643 
4644 	if (cmd_len != sizeof(*req))
4645 		return -EPROTO;
4646 
4647 	type = __le16_to_cpu(req->type);
4648 
4649 	BT_DBG("type 0x%4.4x", type);
4650 
4651 	if (type == L2CAP_IT_FEAT_MASK) {
4652 		u8 buf[8];
4653 		u32 feat_mask = l2cap_feat_mask;
4654 		struct l2cap_info_rsp *rsp = (struct l2cap_info_rsp *) buf;
4655 		rsp->type   = cpu_to_le16(L2CAP_IT_FEAT_MASK);
4656 		rsp->result = cpu_to_le16(L2CAP_IR_SUCCESS);
4657 		if (!disable_ertm)
4658 			feat_mask |= L2CAP_FEAT_ERTM | L2CAP_FEAT_STREAMING
4659 				| L2CAP_FEAT_FCS;
4660 
4661 		put_unaligned_le32(feat_mask, rsp->data);
4662 		l2cap_send_cmd(conn, cmd->ident, L2CAP_INFO_RSP, sizeof(buf),
4663 			       buf);
4664 	} else if (type == L2CAP_IT_FIXED_CHAN) {
4665 		u8 buf[12];
4666 		struct l2cap_info_rsp *rsp = (struct l2cap_info_rsp *) buf;
4667 
4668 		rsp->type   = cpu_to_le16(L2CAP_IT_FIXED_CHAN);
4669 		rsp->result = cpu_to_le16(L2CAP_IR_SUCCESS);
4670 		rsp->data[0] = conn->local_fixed_chan;
4671 		memset(rsp->data + 1, 0, 7);
4672 		l2cap_send_cmd(conn, cmd->ident, L2CAP_INFO_RSP, sizeof(buf),
4673 			       buf);
4674 	} else {
4675 		struct l2cap_info_rsp rsp;
4676 		rsp.type   = cpu_to_le16(type);
4677 		rsp.result = cpu_to_le16(L2CAP_IR_NOTSUPP);
4678 		l2cap_send_cmd(conn, cmd->ident, L2CAP_INFO_RSP, sizeof(rsp),
4679 			       &rsp);
4680 	}
4681 
4682 	return 0;
4683 }
4684 
4685 static inline int l2cap_information_rsp(struct l2cap_conn *conn,
4686 					struct l2cap_cmd_hdr *cmd, u16 cmd_len,
4687 					u8 *data)
4688 {
4689 	struct l2cap_info_rsp *rsp = (struct l2cap_info_rsp *) data;
4690 	u16 type, result;
4691 
4692 	if (cmd_len < sizeof(*rsp))
4693 		return -EPROTO;
4694 
4695 	type   = __le16_to_cpu(rsp->type);
4696 	result = __le16_to_cpu(rsp->result);
4697 
4698 	BT_DBG("type 0x%4.4x result 0x%2.2x", type, result);
4699 
4700 	/* L2CAP Info req/rsp are unbound to channels, add extra checks */
4701 	if (cmd->ident != conn->info_ident ||
4702 	    conn->info_state & L2CAP_INFO_FEAT_MASK_REQ_DONE)
4703 		return 0;
4704 
4705 	cancel_delayed_work(&conn->info_timer);
4706 
4707 	if (result != L2CAP_IR_SUCCESS) {
4708 		conn->info_state |= L2CAP_INFO_FEAT_MASK_REQ_DONE;
4709 		conn->info_ident = 0;
4710 
4711 		l2cap_conn_start(conn);
4712 
4713 		return 0;
4714 	}
4715 
4716 	switch (type) {
4717 	case L2CAP_IT_FEAT_MASK:
4718 		if (cmd_len >= sizeof(*rsp) + sizeof(u32))
4719 			conn->feat_mask = get_unaligned_le32(rsp->data);
4720 
4721 		if (conn->feat_mask & L2CAP_FEAT_FIXED_CHAN) {
4722 			struct l2cap_info_req req;
4723 			req.type = cpu_to_le16(L2CAP_IT_FIXED_CHAN);
4724 
4725 			conn->info_ident = l2cap_get_ident(conn);
4726 
4727 			l2cap_send_cmd(conn, conn->info_ident,
4728 				       L2CAP_INFO_REQ, sizeof(req), &req);
4729 		} else {
4730 			conn->info_state |= L2CAP_INFO_FEAT_MASK_REQ_DONE;
4731 			conn->info_ident = 0;
4732 
4733 			l2cap_conn_start(conn);
4734 		}
4735 		break;
4736 
4737 	case L2CAP_IT_FIXED_CHAN:
4738 		if (cmd_len >= sizeof(*rsp) + sizeof(rsp->data[0]))
4739 			conn->remote_fixed_chan = rsp->data[0];
4740 		conn->info_state |= L2CAP_INFO_FEAT_MASK_REQ_DONE;
4741 		conn->info_ident = 0;
4742 
4743 		l2cap_conn_start(conn);
4744 		break;
4745 	}
4746 
4747 	return 0;
4748 }
4749 
4750 static inline int l2cap_conn_param_update_req(struct l2cap_conn *conn,
4751 					      struct l2cap_cmd_hdr *cmd,
4752 					      u16 cmd_len, u8 *data)
4753 {
4754 	struct hci_conn *hcon = conn->hcon;
4755 	struct l2cap_conn_param_update_req *req;
4756 	struct l2cap_conn_param_update_rsp rsp;
4757 	u16 min, max, latency, to_multiplier;
4758 	int err;
4759 
4760 	if (hcon->role != HCI_ROLE_MASTER)
4761 		return -EINVAL;
4762 
4763 	if (cmd_len != sizeof(struct l2cap_conn_param_update_req))
4764 		return -EPROTO;
4765 
4766 	req = (struct l2cap_conn_param_update_req *) data;
4767 	min		= __le16_to_cpu(req->min);
4768 	max		= __le16_to_cpu(req->max);
4769 	latency		= __le16_to_cpu(req->latency);
4770 	to_multiplier	= __le16_to_cpu(req->to_multiplier);
4771 
4772 	BT_DBG("min 0x%4.4x max 0x%4.4x latency: 0x%4.4x Timeout: 0x%4.4x",
4773 	       min, max, latency, to_multiplier);
4774 
4775 	memset(&rsp, 0, sizeof(rsp));
4776 
4777 	err = hci_check_conn_params(min, max, latency, to_multiplier);
4778 	if (err)
4779 		rsp.result = cpu_to_le16(L2CAP_CONN_PARAM_REJECTED);
4780 	else
4781 		rsp.result = cpu_to_le16(L2CAP_CONN_PARAM_ACCEPTED);
4782 
4783 	l2cap_send_cmd(conn, cmd->ident, L2CAP_CONN_PARAM_UPDATE_RSP,
4784 		       sizeof(rsp), &rsp);
4785 
4786 	if (!err)
4787 		hci_le_conn_update(hcon, min, max, latency, to_multiplier);
4788 
4789 	return 0;
4790 }
4791 
4792 static int l2cap_le_connect_rsp(struct l2cap_conn *conn,
4793 				struct l2cap_cmd_hdr *cmd, u16 cmd_len,
4794 				u8 *data)
4795 {
4796 	struct l2cap_le_conn_rsp *rsp = (struct l2cap_le_conn_rsp *) data;
4797 	struct hci_conn *hcon = conn->hcon;
4798 	u16 dcid, mtu, mps, credits, result;
4799 	struct l2cap_chan *chan;
4800 	int err, sec_level;
4801 
4802 	if (cmd_len < sizeof(*rsp))
4803 		return -EPROTO;
4804 
4805 	dcid    = __le16_to_cpu(rsp->dcid);
4806 	mtu     = __le16_to_cpu(rsp->mtu);
4807 	mps     = __le16_to_cpu(rsp->mps);
4808 	credits = __le16_to_cpu(rsp->credits);
4809 	result  = __le16_to_cpu(rsp->result);
4810 
4811 	if (result == L2CAP_CR_LE_SUCCESS && (mtu < 23 || mps < 23 ||
4812 					   dcid < L2CAP_CID_DYN_START ||
4813 					   dcid > L2CAP_CID_LE_DYN_END))
4814 		return -EPROTO;
4815 
4816 	BT_DBG("dcid 0x%4.4x mtu %u mps %u credits %u result 0x%2.2x",
4817 	       dcid, mtu, mps, credits, result);
4818 
4819 	chan = __l2cap_get_chan_by_ident(conn, cmd->ident);
4820 	if (!chan)
4821 		return -EBADSLT;
4822 
4823 	chan = l2cap_chan_hold_unless_zero(chan);
4824 	if (!chan)
4825 		return -EBADSLT;
4826 
4827 	err = 0;
4828 
4829 	l2cap_chan_lock(chan);
4830 
4831 	switch (result) {
4832 	case L2CAP_CR_LE_SUCCESS:
4833 		if (__l2cap_get_chan_by_dcid(conn, dcid)) {
4834 			err = -EBADSLT;
4835 			break;
4836 		}
4837 
4838 		chan->ident = 0;
4839 		chan->dcid = dcid;
4840 		chan->omtu = mtu;
4841 		chan->remote_mps = mps;
4842 		chan->tx_credits = credits;
4843 		l2cap_chan_ready(chan);
4844 		break;
4845 
4846 	case L2CAP_CR_LE_AUTHENTICATION:
4847 	case L2CAP_CR_LE_ENCRYPTION:
4848 		/* If we already have MITM protection we can't do
4849 		 * anything.
4850 		 */
4851 		if (hcon->sec_level > BT_SECURITY_MEDIUM) {
4852 			l2cap_chan_del(chan, ECONNREFUSED);
4853 			break;
4854 		}
4855 
4856 		sec_level = hcon->sec_level + 1;
4857 		if (chan->sec_level < sec_level)
4858 			chan->sec_level = sec_level;
4859 
4860 		/* We'll need to send a new Connect Request */
4861 		clear_bit(FLAG_LE_CONN_REQ_SENT, &chan->flags);
4862 
4863 		smp_conn_security(hcon, chan->sec_level);
4864 		break;
4865 
4866 	default:
4867 		l2cap_chan_del(chan, ECONNREFUSED);
4868 		break;
4869 	}
4870 
4871 	l2cap_chan_unlock(chan);
4872 	l2cap_chan_put(chan);
4873 
4874 	return err;
4875 }
4876 
4877 static void l2cap_put_ident(struct l2cap_conn *conn, u8 code, u8 id)
4878 {
4879 	switch (code) {
4880 	case L2CAP_COMMAND_REJ:
4881 	case L2CAP_CONN_RSP:
4882 	case L2CAP_CONF_RSP:
4883 	case L2CAP_DISCONN_RSP:
4884 	case L2CAP_ECHO_RSP:
4885 	case L2CAP_INFO_RSP:
4886 	case L2CAP_CONN_PARAM_UPDATE_RSP:
4887 	case L2CAP_LE_CONN_RSP:
4888 	case L2CAP_ECRED_CONN_RSP:
4889 	case L2CAP_ECRED_RECONF_RSP:
4890 		/* First do a lookup since the remote may send bogus ids that
4891 		 * would make ida_free to generate warnings.
4892 		 */
4893 		if (ida_find_first_range(&conn->tx_ida, id, id) >= 0)
4894 			ida_free(&conn->tx_ida, id);
4895 	}
4896 }
4897 
4898 static inline int l2cap_bredr_sig_cmd(struct l2cap_conn *conn,
4899 				      struct l2cap_cmd_hdr *cmd, u16 cmd_len,
4900 				      u8 *data)
4901 {
4902 	int err = 0;
4903 
4904 	l2cap_put_ident(conn, cmd->code, cmd->ident);
4905 
4906 	switch (cmd->code) {
4907 	case L2CAP_COMMAND_REJ:
4908 		l2cap_command_rej(conn, cmd, cmd_len, data);
4909 		break;
4910 
4911 	case L2CAP_CONN_REQ:
4912 		err = l2cap_connect_req(conn, cmd, cmd_len, data);
4913 		break;
4914 
4915 	case L2CAP_CONN_RSP:
4916 		l2cap_connect_create_rsp(conn, cmd, cmd_len, data);
4917 		break;
4918 
4919 	case L2CAP_CONF_REQ:
4920 		err = l2cap_config_req(conn, cmd, cmd_len, data);
4921 		break;
4922 
4923 	case L2CAP_CONF_RSP:
4924 		l2cap_config_rsp(conn, cmd, cmd_len, data);
4925 		break;
4926 
4927 	case L2CAP_DISCONN_REQ:
4928 		err = l2cap_disconnect_req(conn, cmd, cmd_len, data);
4929 		break;
4930 
4931 	case L2CAP_DISCONN_RSP:
4932 		l2cap_disconnect_rsp(conn, cmd, cmd_len, data);
4933 		break;
4934 
4935 	case L2CAP_ECHO_REQ:
4936 		l2cap_send_cmd(conn, cmd->ident, L2CAP_ECHO_RSP, cmd_len, data);
4937 		break;
4938 
4939 	case L2CAP_ECHO_RSP:
4940 		break;
4941 
4942 	case L2CAP_INFO_REQ:
4943 		err = l2cap_information_req(conn, cmd, cmd_len, data);
4944 		break;
4945 
4946 	case L2CAP_INFO_RSP:
4947 		l2cap_information_rsp(conn, cmd, cmd_len, data);
4948 		break;
4949 
4950 	default:
4951 		BT_ERR("Unknown BR/EDR signaling command 0x%2.2x", cmd->code);
4952 		err = -EINVAL;
4953 		break;
4954 	}
4955 
4956 	return err;
4957 }
4958 
4959 static int l2cap_le_connect_req(struct l2cap_conn *conn,
4960 				struct l2cap_cmd_hdr *cmd, u16 cmd_len,
4961 				u8 *data)
4962 {
4963 	struct l2cap_le_conn_req *req = (struct l2cap_le_conn_req *) data;
4964 	struct l2cap_le_conn_rsp rsp;
4965 	struct l2cap_chan *chan, *pchan;
4966 	u16 dcid, scid, credits, mtu, mps;
4967 	__le16 psm;
4968 	u8 result;
4969 
4970 	if (cmd_len != sizeof(*req))
4971 		return -EPROTO;
4972 
4973 	scid = __le16_to_cpu(req->scid);
4974 	mtu  = __le16_to_cpu(req->mtu);
4975 	mps  = __le16_to_cpu(req->mps);
4976 	psm  = req->psm;
4977 	dcid = 0;
4978 	credits = 0;
4979 
4980 	if (mtu < 23 || mps < 23)
4981 		return -EPROTO;
4982 
4983 	BT_DBG("psm 0x%2.2x scid 0x%4.4x mtu %u mps %u", __le16_to_cpu(psm),
4984 	       scid, mtu, mps);
4985 
4986 	/* BLUETOOTH CORE SPECIFICATION Version 5.3 | Vol 3, Part A
4987 	 * page 1059:
4988 	 *
4989 	 * Valid range: 0x0001-0x00ff
4990 	 *
4991 	 * Table 4.15: L2CAP_LE_CREDIT_BASED_CONNECTION_REQ SPSM ranges
4992 	 */
4993 	if (!psm || __le16_to_cpu(psm) > L2CAP_PSM_LE_DYN_END) {
4994 		result = L2CAP_CR_LE_BAD_PSM;
4995 		chan = NULL;
4996 		goto response;
4997 	}
4998 
4999 	/* Check if we have socket listening on psm */
5000 	pchan = l2cap_global_chan_by_psm(BT_LISTEN, psm, &conn->hcon->src,
5001 					 &conn->hcon->dst, LE_LINK);
5002 	if (!pchan) {
5003 		result = L2CAP_CR_LE_BAD_PSM;
5004 		chan = NULL;
5005 		goto response;
5006 	}
5007 
5008 	l2cap_chan_lock(pchan);
5009 
5010 	if (!smp_sufficient_security(conn->hcon, pchan->sec_level,
5011 				     SMP_ALLOW_STK)) {
5012 		result = pchan->sec_level == BT_SECURITY_MEDIUM ?
5013 			L2CAP_CR_LE_ENCRYPTION : L2CAP_CR_LE_AUTHENTICATION;
5014 		chan = NULL;
5015 		goto response_unlock;
5016 	}
5017 
5018 	/* Check if Key Size is sufficient for the security level */
5019 	if (!l2cap_check_enc_key_size(conn->hcon, pchan)) {
5020 		result = L2CAP_CR_LE_BAD_KEY_SIZE;
5021 		chan = NULL;
5022 		goto response_unlock;
5023 	}
5024 
5025 	/* Check for valid dynamic CID range */
5026 	if (scid < L2CAP_CID_DYN_START || scid > L2CAP_CID_LE_DYN_END) {
5027 		result = L2CAP_CR_LE_INVALID_SCID;
5028 		chan = NULL;
5029 		goto response_unlock;
5030 	}
5031 
5032 	/* Check if we already have channel with that dcid */
5033 	if (__l2cap_get_chan_by_dcid(conn, scid)) {
5034 		result = L2CAP_CR_LE_SCID_IN_USE;
5035 		chan = NULL;
5036 		goto response_unlock;
5037 	}
5038 
5039 	chan = l2cap_new_connection(conn, pchan);
5040 	if (!chan) {
5041 		result = L2CAP_CR_LE_NO_MEM;
5042 		goto response_unlock;
5043 	}
5044 
5045 	bacpy(&chan->src, &conn->hcon->src);
5046 	bacpy(&chan->dst, &conn->hcon->dst);
5047 	chan->src_type = bdaddr_src_type(conn->hcon);
5048 	chan->dst_type = bdaddr_dst_type(conn->hcon);
5049 	chan->psm  = psm;
5050 	chan->dcid = scid;
5051 	chan->omtu = mtu;
5052 	chan->remote_mps = mps;
5053 
5054 	l2cap_le_flowctl_init(chan, __le16_to_cpu(req->credits));
5055 
5056 	dcid = chan->scid;
5057 	credits = chan->rx_credits;
5058 
5059 	__set_chan_timer(chan, chan->ops->get_sndtimeo(chan));
5060 
5061 	chan->ident = cmd->ident;
5062 
5063 	if (test_bit(FLAG_DEFER_SETUP, &chan->flags)) {
5064 		l2cap_state_change(chan, BT_CONNECT2);
5065 		/* The following result value is actually not defined
5066 		 * for LE CoC but we use it to let the function know
5067 		 * that it should bail out after doing its cleanup
5068 		 * instead of sending a response.
5069 		 */
5070 		result = L2CAP_CR_PEND;
5071 		chan->ops->defer(chan);
5072 	} else {
5073 		l2cap_chan_ready(chan);
5074 		result = L2CAP_CR_LE_SUCCESS;
5075 	}
5076 
5077 response_unlock:
5078 	l2cap_chan_unlock(pchan);
5079 	l2cap_chan_put(pchan);
5080 
5081 	if (result == L2CAP_CR_PEND)
5082 		return 0;
5083 
5084 response:
5085 	if (chan) {
5086 		rsp.mtu = cpu_to_le16(chan->imtu);
5087 		rsp.mps = cpu_to_le16(chan->mps);
5088 	} else {
5089 		rsp.mtu = 0;
5090 		rsp.mps = 0;
5091 	}
5092 
5093 	rsp.dcid    = cpu_to_le16(dcid);
5094 	rsp.credits = cpu_to_le16(credits);
5095 	rsp.result  = cpu_to_le16(result);
5096 
5097 	l2cap_send_cmd(conn, cmd->ident, L2CAP_LE_CONN_RSP, sizeof(rsp), &rsp);
5098 
5099 	return 0;
5100 }
5101 
5102 static inline int l2cap_le_credits(struct l2cap_conn *conn,
5103 				   struct l2cap_cmd_hdr *cmd, u16 cmd_len,
5104 				   u8 *data)
5105 {
5106 	struct l2cap_le_credits *pkt;
5107 	struct l2cap_chan *chan;
5108 	u16 cid, credits, max_credits;
5109 
5110 	if (cmd_len != sizeof(*pkt))
5111 		return -EPROTO;
5112 
5113 	pkt = (struct l2cap_le_credits *) data;
5114 	cid	= __le16_to_cpu(pkt->cid);
5115 	credits	= __le16_to_cpu(pkt->credits);
5116 
5117 	BT_DBG("cid 0x%4.4x credits 0x%4.4x", cid, credits);
5118 
5119 	chan = l2cap_get_chan_by_dcid(conn, cid);
5120 	if (!chan)
5121 		return -EBADSLT;
5122 
5123 	max_credits = LE_FLOWCTL_MAX_CREDITS - chan->tx_credits;
5124 	if (credits > max_credits) {
5125 		BT_ERR("LE credits overflow");
5126 		l2cap_send_disconn_req(chan, ECONNRESET);
5127 
5128 		/* Return 0 so that we don't trigger an unnecessary
5129 		 * command reject packet.
5130 		 */
5131 		goto unlock;
5132 	}
5133 
5134 	chan->tx_credits += credits;
5135 
5136 	/* Resume sending */
5137 	l2cap_le_flowctl_send(chan);
5138 
5139 	if (chan->tx_credits)
5140 		chan->ops->resume(chan);
5141 
5142 unlock:
5143 	l2cap_chan_unlock(chan);
5144 	l2cap_chan_put(chan);
5145 
5146 	return 0;
5147 }
5148 
5149 static inline int l2cap_ecred_conn_req(struct l2cap_conn *conn,
5150 				       struct l2cap_cmd_hdr *cmd, u16 cmd_len,
5151 				       u8 *data)
5152 {
5153 	struct l2cap_ecred_conn_req *req = (void *) data;
5154 	DEFINE_RAW_FLEX(struct l2cap_ecred_conn_rsp, pdu, dcid, L2CAP_ECRED_MAX_CID);
5155 	struct l2cap_chan *chan, *pchan;
5156 	u16 mtu, mps;
5157 	__le16 psm;
5158 	u8 result, rsp_len = 0;
5159 	int i, num_scid = 0;
5160 	bool defer = false;
5161 
5162 	if (!enable_ecred)
5163 		return -EINVAL;
5164 
5165 	memset(pdu, 0, sizeof(*pdu));
5166 
5167 	if (cmd_len < sizeof(*req) || (cmd_len - sizeof(*req)) % sizeof(u16)) {
5168 		result = L2CAP_CR_LE_INVALID_PARAMS;
5169 		goto response;
5170 	}
5171 
5172 	/* Check if there are no pending channels with the same ident */
5173 	__l2cap_chan_list_id(conn, cmd->ident, l2cap_ecred_list_defer,
5174 			     &num_scid);
5175 	if (num_scid) {
5176 		result = L2CAP_CR_LE_INVALID_PARAMS;
5177 		goto response;
5178 	}
5179 
5180 	cmd_len -= sizeof(*req);
5181 	num_scid = cmd_len / sizeof(u16);
5182 
5183 	if (num_scid > L2CAP_ECRED_MAX_CID) {
5184 		result = L2CAP_CR_LE_INVALID_PARAMS;
5185 		goto response;
5186 	}
5187 
5188 	/* Always respond with the same number of scids as in the request */
5189 	rsp_len = cmd_len;
5190 
5191 	mtu  = __le16_to_cpu(req->mtu);
5192 	mps  = __le16_to_cpu(req->mps);
5193 
5194 	if (mtu < L2CAP_ECRED_MIN_MTU || mps < L2CAP_ECRED_MIN_MPS) {
5195 		result = L2CAP_CR_LE_INVALID_PARAMS;
5196 		goto response;
5197 	}
5198 
5199 	psm  = req->psm;
5200 
5201 	/* BLUETOOTH CORE SPECIFICATION Version 5.3 | Vol 3, Part A
5202 	 * page 1059:
5203 	 *
5204 	 * Valid range: 0x0001-0x00ff
5205 	 *
5206 	 * Table 4.15: L2CAP_LE_CREDIT_BASED_CONNECTION_REQ SPSM ranges
5207 	 */
5208 	if (!psm || __le16_to_cpu(psm) > L2CAP_PSM_LE_DYN_END) {
5209 		result = L2CAP_CR_LE_BAD_PSM;
5210 		goto response;
5211 	}
5212 
5213 	BT_DBG("psm 0x%2.2x mtu %u mps %u", __le16_to_cpu(psm), mtu, mps);
5214 
5215 	/* Check if we have socket listening on psm */
5216 	pchan = l2cap_global_chan_by_psm(BT_LISTEN, psm, &conn->hcon->src,
5217 					 &conn->hcon->dst, LE_LINK);
5218 	if (!pchan) {
5219 		result = L2CAP_CR_LE_BAD_PSM;
5220 		goto response;
5221 	}
5222 
5223 	l2cap_chan_lock(pchan);
5224 
5225 	if (!smp_sufficient_security(conn->hcon, pchan->sec_level,
5226 				     SMP_ALLOW_STK)) {
5227 		result = pchan->sec_level == BT_SECURITY_MEDIUM ?
5228 			L2CAP_CR_LE_ENCRYPTION : L2CAP_CR_LE_AUTHENTICATION;
5229 		goto unlock;
5230 	}
5231 
5232 	/* Check if the listening channel has set an output MTU then the
5233 	 * requested MTU shall be less than or equal to that value.
5234 	 */
5235 	if (pchan->omtu && mtu < pchan->omtu) {
5236 		result = L2CAP_CR_LE_UNACCEPT_PARAMS;
5237 		goto unlock;
5238 	}
5239 
5240 	result = L2CAP_CR_LE_SUCCESS;
5241 
5242 	for (i = 0; i < num_scid; i++) {
5243 		u16 scid = __le16_to_cpu(req->scid[i]);
5244 
5245 		BT_DBG("scid[%d] 0x%4.4x", i, scid);
5246 
5247 		pdu->dcid[i] = 0x0000;
5248 
5249 		/* Check for valid dynamic CID range */
5250 		if (scid < L2CAP_CID_DYN_START || scid > L2CAP_CID_LE_DYN_END) {
5251 			result = L2CAP_CR_LE_INVALID_SCID;
5252 			continue;
5253 		}
5254 
5255 		/* Check if we already have channel with that dcid */
5256 		if (__l2cap_get_chan_by_dcid(conn, scid)) {
5257 			result = L2CAP_CR_LE_SCID_IN_USE;
5258 			continue;
5259 		}
5260 
5261 		chan = l2cap_new_connection(conn, pchan);
5262 		if (!chan) {
5263 			result = L2CAP_CR_LE_NO_MEM;
5264 			continue;
5265 		}
5266 
5267 		bacpy(&chan->src, &conn->hcon->src);
5268 		bacpy(&chan->dst, &conn->hcon->dst);
5269 		chan->src_type = bdaddr_src_type(conn->hcon);
5270 		chan->dst_type = bdaddr_dst_type(conn->hcon);
5271 		chan->psm  = psm;
5272 		chan->dcid = scid;
5273 		chan->omtu = mtu;
5274 		chan->remote_mps = mps;
5275 
5276 		l2cap_ecred_init(chan, __le16_to_cpu(req->credits));
5277 
5278 		/* Init response */
5279 		if (!pdu->credits) {
5280 			pdu->mtu = cpu_to_le16(chan->imtu);
5281 			pdu->mps = cpu_to_le16(chan->mps);
5282 			pdu->credits = cpu_to_le16(chan->rx_credits);
5283 		}
5284 
5285 		pdu->dcid[i] = cpu_to_le16(chan->scid);
5286 
5287 		__set_chan_timer(chan, chan->ops->get_sndtimeo(chan));
5288 
5289 		chan->ident = cmd->ident;
5290 		chan->mode = L2CAP_MODE_EXT_FLOWCTL;
5291 
5292 		if (test_bit(FLAG_DEFER_SETUP, &chan->flags)) {
5293 			l2cap_state_change(chan, BT_CONNECT2);
5294 			defer = true;
5295 			chan->ops->defer(chan);
5296 		} else {
5297 			l2cap_chan_ready(chan);
5298 		}
5299 	}
5300 
5301 unlock:
5302 	l2cap_chan_unlock(pchan);
5303 	l2cap_chan_put(pchan);
5304 
5305 response:
5306 	pdu->result = cpu_to_le16(result);
5307 
5308 	if (defer)
5309 		return 0;
5310 
5311 	l2cap_send_cmd(conn, cmd->ident, L2CAP_ECRED_CONN_RSP,
5312 		       sizeof(*pdu) + rsp_len, pdu);
5313 
5314 	return 0;
5315 }
5316 
5317 static inline int l2cap_ecred_conn_rsp(struct l2cap_conn *conn,
5318 				       struct l2cap_cmd_hdr *cmd, u16 cmd_len,
5319 				       u8 *data)
5320 {
5321 	struct l2cap_ecred_conn_rsp *rsp = (void *) data;
5322 	struct hci_conn *hcon = conn->hcon;
5323 	u16 mtu, mps, credits, result;
5324 	struct l2cap_chan *chan, *tmp;
5325 	int err = 0, sec_level;
5326 	int i = 0;
5327 
5328 	if (cmd_len < sizeof(*rsp))
5329 		return -EPROTO;
5330 
5331 	mtu     = __le16_to_cpu(rsp->mtu);
5332 	mps     = __le16_to_cpu(rsp->mps);
5333 	credits = __le16_to_cpu(rsp->credits);
5334 	result  = __le16_to_cpu(rsp->result);
5335 
5336 	BT_DBG("mtu %u mps %u credits %u result 0x%4.4x", mtu, mps, credits,
5337 	       result);
5338 
5339 	cmd_len -= sizeof(*rsp);
5340 
5341 	list_for_each_entry_safe(chan, tmp, &conn->chan_l, list) {
5342 		struct l2cap_chan *orig;
5343 		u16 dcid;
5344 
5345 		if (chan->ident != cmd->ident ||
5346 		    chan->mode != L2CAP_MODE_EXT_FLOWCTL ||
5347 		    chan->state == BT_CONNECTED)
5348 			continue;
5349 
5350 		l2cap_chan_lock(chan);
5351 
5352 		/* Check that there is a dcid for each pending channel */
5353 		if (cmd_len < sizeof(dcid)) {
5354 			l2cap_chan_del(chan, ECONNREFUSED);
5355 			l2cap_chan_unlock(chan);
5356 			continue;
5357 		}
5358 
5359 		dcid = __le16_to_cpu(rsp->dcid[i++]);
5360 		cmd_len -= sizeof(u16);
5361 
5362 		BT_DBG("dcid[%d] 0x%4.4x", i, dcid);
5363 
5364 		orig = __l2cap_get_chan_by_dcid(conn, dcid);
5365 
5366 		/* Check if dcid is already in use */
5367 		if (dcid && orig) {
5368 			/* If a device receives a
5369 			 * L2CAP_CREDIT_BASED_CONNECTION_RSP packet with an
5370 			 * already-assigned Destination CID, then both the
5371 			 * original channel and the new channel shall be
5372 			 * immediately discarded and not used.
5373 			 */
5374 			l2cap_chan_del(chan, ECONNREFUSED);
5375 			l2cap_chan_unlock(chan);
5376 
5377 			/* Check that the dcid channel mode is
5378 			 * L2CAP_MODE_EXT_FLOWCTL since this procedure is only
5379 			 * valid for that mode and shouldn't disconnect a dcid
5380 			 * in other modes.
5381 			 */
5382 			if (orig->mode == L2CAP_MODE_EXT_FLOWCTL) {
5383 				l2cap_chan_lock(orig);
5384 				/* Disconnect the original channel as it may be
5385 				 * considered connected since dcid has already
5386 				 * been assigned; don't call l2cap_chan_close
5387 				 * directly since that could lead to
5388 				 * l2cap_chan_del and then removing the channel
5389 				 * from the list while we're iterating over it.
5390 				 */
5391 				__set_chan_timer(orig, 0);
5392 				l2cap_chan_unlock(orig);
5393 			}
5394 			continue;
5395 		}
5396 
5397 		switch (result) {
5398 		case L2CAP_CR_LE_AUTHENTICATION:
5399 		case L2CAP_CR_LE_ENCRYPTION:
5400 			/* If we already have MITM protection we can't do
5401 			 * anything.
5402 			 */
5403 			if (hcon->sec_level > BT_SECURITY_MEDIUM) {
5404 				l2cap_chan_del(chan, ECONNREFUSED);
5405 				break;
5406 			}
5407 
5408 			sec_level = hcon->sec_level + 1;
5409 			if (chan->sec_level < sec_level)
5410 				chan->sec_level = sec_level;
5411 
5412 			/* We'll need to send a new Connect Request */
5413 			clear_bit(FLAG_ECRED_CONN_REQ_SENT, &chan->flags);
5414 
5415 			smp_conn_security(hcon, chan->sec_level);
5416 			break;
5417 
5418 		case L2CAP_CR_LE_BAD_PSM:
5419 			l2cap_chan_del(chan, ECONNREFUSED);
5420 			break;
5421 
5422 		default:
5423 			/* If dcid was not set it means channels was refused */
5424 			if (!dcid) {
5425 				l2cap_chan_del(chan, ECONNREFUSED);
5426 				break;
5427 			}
5428 
5429 			chan->ident = 0;
5430 			chan->dcid = dcid;
5431 			chan->omtu = mtu;
5432 			chan->remote_mps = mps;
5433 			chan->tx_credits = credits;
5434 			l2cap_chan_ready(chan);
5435 			break;
5436 		}
5437 
5438 		l2cap_chan_unlock(chan);
5439 	}
5440 
5441 	return err;
5442 }
5443 
5444 static inline int l2cap_ecred_reconf_req(struct l2cap_conn *conn,
5445 					 struct l2cap_cmd_hdr *cmd, u16 cmd_len,
5446 					 u8 *data)
5447 {
5448 	struct l2cap_ecred_reconf_req *req = (void *) data;
5449 	struct l2cap_ecred_reconf_rsp rsp;
5450 	u16 mtu, mps, result;
5451 	struct l2cap_chan *chan[L2CAP_ECRED_MAX_CID] = {};
5452 	int i, num_scid;
5453 
5454 	if (!enable_ecred)
5455 		return -EINVAL;
5456 
5457 	if (cmd_len < sizeof(*req) || (cmd_len - sizeof(*req)) % sizeof(u16)) {
5458 		result = L2CAP_RECONF_INVALID_CID;
5459 		goto respond;
5460 	}
5461 
5462 	mtu = __le16_to_cpu(req->mtu);
5463 	mps = __le16_to_cpu(req->mps);
5464 
5465 	BT_DBG("mtu %u mps %u", mtu, mps);
5466 
5467 	if (mtu < L2CAP_ECRED_MIN_MTU) {
5468 		result = L2CAP_RECONF_INVALID_PARAMS;
5469 		goto respond;
5470 	}
5471 
5472 	if (mps < L2CAP_ECRED_MIN_MPS) {
5473 		result = L2CAP_RECONF_INVALID_PARAMS;
5474 		goto respond;
5475 	}
5476 
5477 	cmd_len -= sizeof(*req);
5478 	num_scid = cmd_len / sizeof(u16);
5479 
5480 	if (num_scid > L2CAP_ECRED_MAX_CID) {
5481 		result = L2CAP_RECONF_INVALID_PARAMS;
5482 		goto respond;
5483 	}
5484 
5485 	result = L2CAP_RECONF_SUCCESS;
5486 
5487 	/* Check if each SCID, MTU and MPS are valid */
5488 	for (i = 0; i < num_scid; i++) {
5489 		u16 scid;
5490 
5491 		scid = __le16_to_cpu(req->scid[i]);
5492 		if (!scid) {
5493 			result = L2CAP_RECONF_INVALID_CID;
5494 			goto respond;
5495 		}
5496 
5497 		chan[i] = __l2cap_get_chan_by_dcid(conn, scid);
5498 		if (!chan[i]) {
5499 			result = L2CAP_RECONF_INVALID_CID;
5500 			goto respond;
5501 		}
5502 
5503 		/* The MTU field shall be greater than or equal to the greatest
5504 		 * current MTU size of these channels.
5505 		 */
5506 		if (chan[i]->omtu > mtu) {
5507 			BT_ERR("chan %p decreased MTU %u -> %u", chan[i],
5508 			       chan[i]->omtu, mtu);
5509 			result = L2CAP_RECONF_INVALID_MTU;
5510 			goto respond;
5511 		}
5512 
5513 		/* If more than one channel is being configured, the MPS field
5514 		 * shall be greater than or equal to the current MPS size of
5515 		 * each of these channels. If only one channel is being
5516 		 * configured, the MPS field may be less than the current MPS
5517 		 * of that channel.
5518 		 */
5519 		if (chan[i]->remote_mps > mps && num_scid > 1) {
5520 			BT_ERR("chan %p decreased MPS %u -> %u", chan[i],
5521 			       chan[i]->remote_mps, mps);
5522 			result = L2CAP_RECONF_INVALID_MPS;
5523 			goto respond;
5524 		}
5525 	}
5526 
5527 	/* Commit the new MTU and MPS values after checking they are valid */
5528 	for (i = 0; i < num_scid; i++) {
5529 		chan[i]->omtu = mtu;
5530 		chan[i]->remote_mps = mps;
5531 	}
5532 
5533 respond:
5534 	rsp.result = cpu_to_le16(result);
5535 
5536 	l2cap_send_cmd(conn, cmd->ident, L2CAP_ECRED_RECONF_RSP, sizeof(rsp),
5537 		       &rsp);
5538 
5539 	return 0;
5540 }
5541 
5542 static inline int l2cap_ecred_reconf_rsp(struct l2cap_conn *conn,
5543 					 struct l2cap_cmd_hdr *cmd, u16 cmd_len,
5544 					 u8 *data)
5545 {
5546 	struct l2cap_chan *chan, *tmp;
5547 	struct l2cap_ecred_reconf_rsp *rsp = (void *)data;
5548 	u16 result;
5549 
5550 	if (cmd_len < sizeof(*rsp))
5551 		return -EPROTO;
5552 
5553 	result = __le16_to_cpu(rsp->result);
5554 
5555 	BT_DBG("result 0x%4.4x", result);
5556 
5557 	if (!result) {
5558 		list_for_each_entry(chan, &conn->chan_l, list) {
5559 			if (chan->ident == cmd->ident)
5560 				chan->ident = 0;
5561 		}
5562 		return 0;
5563 	}
5564 
5565 	list_for_each_entry_safe(chan, tmp, &conn->chan_l, list) {
5566 		if (chan->ident != cmd->ident)
5567 			continue;
5568 
5569 		if (!l2cap_chan_hold_unless_zero(chan))
5570 			continue;
5571 		l2cap_chan_lock(chan);
5572 
5573 		l2cap_chan_del(chan, ECONNRESET);
5574 
5575 		l2cap_chan_unlock(chan);
5576 		l2cap_chan_put(chan);
5577 	}
5578 
5579 	return 0;
5580 }
5581 
5582 static inline int l2cap_le_command_rej(struct l2cap_conn *conn,
5583 				       struct l2cap_cmd_hdr *cmd, u16 cmd_len,
5584 				       u8 *data)
5585 {
5586 	struct l2cap_cmd_rej_unk *rej = (struct l2cap_cmd_rej_unk *) data;
5587 	struct l2cap_chan *chan;
5588 
5589 	if (cmd_len < sizeof(*rej))
5590 		return -EPROTO;
5591 
5592 	chan = __l2cap_get_chan_by_ident(conn, cmd->ident);
5593 	if (!chan)
5594 		goto done;
5595 
5596 	chan = l2cap_chan_hold_unless_zero(chan);
5597 	if (!chan)
5598 		goto done;
5599 
5600 	l2cap_chan_lock(chan);
5601 	l2cap_chan_del(chan, ECONNREFUSED);
5602 	l2cap_chan_unlock(chan);
5603 	l2cap_chan_put(chan);
5604 
5605 done:
5606 	return 0;
5607 }
5608 
5609 static inline int l2cap_le_sig_cmd(struct l2cap_conn *conn,
5610 				   struct l2cap_cmd_hdr *cmd, u16 cmd_len,
5611 				   u8 *data)
5612 {
5613 	int err = 0;
5614 
5615 	l2cap_put_ident(conn, cmd->code, cmd->ident);
5616 
5617 	switch (cmd->code) {
5618 	case L2CAP_COMMAND_REJ:
5619 		l2cap_le_command_rej(conn, cmd, cmd_len, data);
5620 		break;
5621 
5622 	case L2CAP_CONN_PARAM_UPDATE_REQ:
5623 		err = l2cap_conn_param_update_req(conn, cmd, cmd_len, data);
5624 		break;
5625 
5626 	case L2CAP_CONN_PARAM_UPDATE_RSP:
5627 		break;
5628 
5629 	case L2CAP_LE_CONN_RSP:
5630 		l2cap_le_connect_rsp(conn, cmd, cmd_len, data);
5631 		break;
5632 
5633 	case L2CAP_LE_CONN_REQ:
5634 		err = l2cap_le_connect_req(conn, cmd, cmd_len, data);
5635 		break;
5636 
5637 	case L2CAP_LE_CREDITS:
5638 		err = l2cap_le_credits(conn, cmd, cmd_len, data);
5639 		break;
5640 
5641 	case L2CAP_ECRED_CONN_REQ:
5642 		err = l2cap_ecred_conn_req(conn, cmd, cmd_len, data);
5643 		break;
5644 
5645 	case L2CAP_ECRED_CONN_RSP:
5646 		err = l2cap_ecred_conn_rsp(conn, cmd, cmd_len, data);
5647 		break;
5648 
5649 	case L2CAP_ECRED_RECONF_REQ:
5650 		err = l2cap_ecred_reconf_req(conn, cmd, cmd_len, data);
5651 		break;
5652 
5653 	case L2CAP_ECRED_RECONF_RSP:
5654 		err = l2cap_ecred_reconf_rsp(conn, cmd, cmd_len, data);
5655 		break;
5656 
5657 	case L2CAP_DISCONN_REQ:
5658 		err = l2cap_disconnect_req(conn, cmd, cmd_len, data);
5659 		break;
5660 
5661 	case L2CAP_DISCONN_RSP:
5662 		l2cap_disconnect_rsp(conn, cmd, cmd_len, data);
5663 		break;
5664 
5665 	default:
5666 		BT_ERR("Unknown LE signaling command 0x%2.2x", cmd->code);
5667 		err = -EINVAL;
5668 		break;
5669 	}
5670 
5671 	return err;
5672 }
5673 
5674 static inline void l2cap_le_sig_channel(struct l2cap_conn *conn,
5675 					struct sk_buff *skb)
5676 {
5677 	struct hci_conn *hcon = conn->hcon;
5678 	struct l2cap_cmd_hdr *cmd;
5679 	u16 len;
5680 	int err;
5681 
5682 	if (hcon->type != LE_LINK)
5683 		goto drop;
5684 
5685 	if (skb->len < L2CAP_CMD_HDR_SIZE)
5686 		goto drop;
5687 
5688 	cmd = (void *) skb->data;
5689 	skb_pull(skb, L2CAP_CMD_HDR_SIZE);
5690 
5691 	len = le16_to_cpu(cmd->len);
5692 
5693 	BT_DBG("code 0x%2.2x len %d id 0x%2.2x", cmd->code, len, cmd->ident);
5694 
5695 	if (len != skb->len || !cmd->ident) {
5696 		BT_DBG("corrupted command");
5697 		goto drop;
5698 	}
5699 
5700 	err = l2cap_le_sig_cmd(conn, cmd, len, skb->data);
5701 	if (err) {
5702 		struct l2cap_cmd_rej_unk rej;
5703 
5704 		BT_ERR("Wrong link type (%d)", err);
5705 
5706 		rej.reason = cpu_to_le16(L2CAP_REJ_NOT_UNDERSTOOD);
5707 		l2cap_send_cmd(conn, cmd->ident, L2CAP_COMMAND_REJ,
5708 			       sizeof(rej), &rej);
5709 	}
5710 
5711 drop:
5712 	kfree_skb(skb);
5713 }
5714 
5715 static inline void l2cap_sig_send_rej(struct l2cap_conn *conn, u16 ident)
5716 {
5717 	struct l2cap_cmd_rej_unk rej;
5718 
5719 	rej.reason = cpu_to_le16(L2CAP_REJ_NOT_UNDERSTOOD);
5720 	l2cap_send_cmd(conn, ident, L2CAP_COMMAND_REJ, sizeof(rej), &rej);
5721 }
5722 
5723 static inline void l2cap_sig_send_mtu_rej(struct l2cap_conn *conn, u8 ident)
5724 {
5725 	struct l2cap_cmd_rej_mtu rej;
5726 
5727 	rej.reason = cpu_to_le16(L2CAP_REJ_MTU_EXCEEDED);
5728 	rej.max_mtu = cpu_to_le16(L2CAP_SIG_MTU);
5729 	l2cap_send_cmd(conn, ident, L2CAP_COMMAND_REJ, sizeof(rej), &rej);
5730 }
5731 
5732 static inline void l2cap_sig_channel(struct l2cap_conn *conn,
5733 				     struct sk_buff *skb)
5734 {
5735 	struct hci_conn *hcon = conn->hcon;
5736 	struct l2cap_cmd_hdr *cmd;
5737 	int err;
5738 
5739 	l2cap_raw_recv(conn, skb);
5740 
5741 	if (hcon->type != ACL_LINK)
5742 		goto drop;
5743 
5744 	/*
5745 	 * Bluetooth Core v5.4, Vol 3, Part A, Section 4: the BR/EDR
5746 	 * signaling channel has a fixed signaling MTU (MTUsig) whose
5747 	 * minimum and default is 48 octets.  Section 4.1 says that on
5748 	 * an MTUExceeded command reject the identifier "shall match
5749 	 * the first request command in the L2CAP packet" and that
5750 	 * packets containing only response commands "shall be
5751 	 * silently discarded".
5752 	 *
5753 	 * Linux intentionally deviates from that prescription:
5754 	 *
5755 	 *   1. Silently discarding desynchronizes the peer.  The
5756 	 *      remote stack never learns its responses were dropped,
5757 	 *      so any state machine waiting on a paired response
5758 	 *      stalls until its own timer fires.
5759 	 *
5760 	 *   2. Locating "the first request command" requires walking
5761 	 *      command headers past MTUsig, i.e. processing bytes
5762 	 *      from a packet we have already decided is too large to
5763 	 *      process.
5764 	 *
5765 	 * Reject every over-MTUsig signaling packet with one
5766 	 * L2CAP_REJ_MTU_EXCEEDED command reject.  The reject's
5767 	 * reason field is what tells the peer that the whole packet
5768 	 * was discarded; the identifier value is informational, so
5769 	 * we use the identifier from the first command header, a
5770 	 * single fixed-offset byte read.
5771 	 */
5772 	if (skb->len > L2CAP_SIG_MTU) {
5773 		u8 ident = skb->data[1];
5774 
5775 		BT_DBG("signaling packet exceeds MTU: %u > %u",
5776 		       skb->len, L2CAP_SIG_MTU);
5777 		l2cap_sig_send_mtu_rej(conn, ident);
5778 		goto drop;
5779 	}
5780 
5781 	while (skb->len >= L2CAP_CMD_HDR_SIZE) {
5782 		u16 len;
5783 
5784 		cmd = (void *) skb->data;
5785 		skb_pull(skb, L2CAP_CMD_HDR_SIZE);
5786 
5787 		len = le16_to_cpu(cmd->len);
5788 
5789 		BT_DBG("code 0x%2.2x len %d id 0x%2.2x", cmd->code, len,
5790 		       cmd->ident);
5791 
5792 		if (len > skb->len || !cmd->ident) {
5793 			BT_DBG("corrupted command");
5794 			l2cap_sig_send_rej(conn, cmd->ident);
5795 			skb_pull(skb, len > skb->len ? skb->len : len);
5796 			continue;
5797 		}
5798 
5799 		err = l2cap_bredr_sig_cmd(conn, cmd, len, skb->data);
5800 		if (err) {
5801 			BT_ERR("Wrong link type (%d)", err);
5802 			l2cap_sig_send_rej(conn, cmd->ident);
5803 		}
5804 
5805 		skb_pull(skb, len);
5806 	}
5807 
5808 	if (skb->len > 0) {
5809 		BT_DBG("corrupted command");
5810 		l2cap_sig_send_rej(conn, 0);
5811 	}
5812 
5813 drop:
5814 	kfree_skb(skb);
5815 }
5816 
5817 static int l2cap_check_fcs(struct l2cap_chan *chan,  struct sk_buff *skb)
5818 {
5819 	u16 our_fcs, rcv_fcs;
5820 	int hdr_size;
5821 
5822 	if (test_bit(FLAG_EXT_CTRL, &chan->flags))
5823 		hdr_size = L2CAP_EXT_HDR_SIZE;
5824 	else
5825 		hdr_size = L2CAP_ENH_HDR_SIZE;
5826 
5827 	if (chan->fcs == L2CAP_FCS_CRC16) {
5828 		skb_trim(skb, skb->len - L2CAP_FCS_SIZE);
5829 		rcv_fcs = get_unaligned_le16(skb->data + skb->len);
5830 		our_fcs = crc16(0, skb->data - hdr_size, skb->len + hdr_size);
5831 
5832 		if (our_fcs != rcv_fcs)
5833 			return -EBADMSG;
5834 	}
5835 	return 0;
5836 }
5837 
5838 static void l2cap_send_i_or_rr_or_rnr(struct l2cap_chan *chan)
5839 {
5840 	struct l2cap_ctrl control;
5841 
5842 	BT_DBG("chan %p", chan);
5843 
5844 	memset(&control, 0, sizeof(control));
5845 	control.sframe = 1;
5846 	control.final = 1;
5847 	control.reqseq = chan->buffer_seq;
5848 	set_bit(CONN_SEND_FBIT, &chan->conn_state);
5849 
5850 	if (test_bit(CONN_LOCAL_BUSY, &chan->conn_state)) {
5851 		control.super = L2CAP_SUPER_RNR;
5852 		l2cap_send_sframe(chan, &control);
5853 	}
5854 
5855 	if (test_and_clear_bit(CONN_REMOTE_BUSY, &chan->conn_state) &&
5856 	    chan->unacked_frames > 0)
5857 		__set_retrans_timer(chan);
5858 
5859 	/* Send pending iframes */
5860 	l2cap_ertm_send(chan);
5861 
5862 	if (!test_bit(CONN_LOCAL_BUSY, &chan->conn_state) &&
5863 	    test_bit(CONN_SEND_FBIT, &chan->conn_state)) {
5864 		/* F-bit wasn't sent in an s-frame or i-frame yet, so
5865 		 * send it now.
5866 		 */
5867 		control.super = L2CAP_SUPER_RR;
5868 		l2cap_send_sframe(chan, &control);
5869 	}
5870 }
5871 
5872 static void append_skb_frag(struct sk_buff *skb, struct sk_buff *new_frag,
5873 			    struct sk_buff **last_frag)
5874 {
5875 	/* skb->len reflects data in skb as well as all fragments
5876 	 * skb->data_len reflects only data in fragments
5877 	 */
5878 	if (!skb_has_frag_list(skb))
5879 		skb_shinfo(skb)->frag_list = new_frag;
5880 
5881 	new_frag->next = NULL;
5882 
5883 	(*last_frag)->next = new_frag;
5884 	*last_frag = new_frag;
5885 
5886 	skb->len += new_frag->len;
5887 	skb->data_len += new_frag->len;
5888 	skb->truesize += new_frag->truesize;
5889 }
5890 
5891 static int l2cap_reassemble_sdu(struct l2cap_chan *chan, struct sk_buff *skb,
5892 				struct l2cap_ctrl *control)
5893 {
5894 	int err = -EINVAL;
5895 
5896 	switch (control->sar) {
5897 	case L2CAP_SAR_UNSEGMENTED:
5898 		if (chan->sdu)
5899 			break;
5900 
5901 		err = chan->ops->recv(chan, skb);
5902 		break;
5903 
5904 	case L2CAP_SAR_START:
5905 		if (chan->sdu)
5906 			break;
5907 
5908 		if (!pskb_may_pull(skb, L2CAP_SDULEN_SIZE))
5909 			break;
5910 
5911 		chan->sdu_len = get_unaligned_le16(skb->data);
5912 		skb_pull(skb, L2CAP_SDULEN_SIZE);
5913 
5914 		if (chan->sdu_len > chan->imtu) {
5915 			err = -EMSGSIZE;
5916 			break;
5917 		}
5918 
5919 		if (skb->len >= chan->sdu_len)
5920 			break;
5921 
5922 		chan->sdu = skb;
5923 		chan->sdu_last_frag = skb;
5924 
5925 		skb = NULL;
5926 		err = 0;
5927 		break;
5928 
5929 	case L2CAP_SAR_CONTINUE:
5930 		if (!chan->sdu)
5931 			break;
5932 
5933 		append_skb_frag(chan->sdu, skb,
5934 				&chan->sdu_last_frag);
5935 		skb = NULL;
5936 
5937 		if (chan->sdu->len >= chan->sdu_len)
5938 			break;
5939 
5940 		err = 0;
5941 		break;
5942 
5943 	case L2CAP_SAR_END:
5944 		if (!chan->sdu)
5945 			break;
5946 
5947 		append_skb_frag(chan->sdu, skb,
5948 				&chan->sdu_last_frag);
5949 		skb = NULL;
5950 
5951 		if (chan->sdu->len != chan->sdu_len)
5952 			break;
5953 
5954 		err = chan->ops->recv(chan, chan->sdu);
5955 
5956 		if (!err) {
5957 			/* Reassembly complete */
5958 			chan->sdu = NULL;
5959 			chan->sdu_last_frag = NULL;
5960 			chan->sdu_len = 0;
5961 		}
5962 		break;
5963 	}
5964 
5965 	if (err) {
5966 		kfree_skb(skb);
5967 		kfree_skb(chan->sdu);
5968 		chan->sdu = NULL;
5969 		chan->sdu_last_frag = NULL;
5970 		chan->sdu_len = 0;
5971 	}
5972 
5973 	return err;
5974 }
5975 
5976 static int l2cap_resegment(struct l2cap_chan *chan)
5977 {
5978 	/* Placeholder */
5979 	return 0;
5980 }
5981 
5982 void l2cap_chan_busy(struct l2cap_chan *chan, int busy)
5983 {
5984 	u8 event;
5985 
5986 	if (chan->mode != L2CAP_MODE_ERTM)
5987 		return;
5988 
5989 	event = busy ? L2CAP_EV_LOCAL_BUSY_DETECTED : L2CAP_EV_LOCAL_BUSY_CLEAR;
5990 	l2cap_tx(chan, NULL, NULL, event);
5991 }
5992 
5993 static int l2cap_rx_queued_iframes(struct l2cap_chan *chan)
5994 {
5995 	int err = 0;
5996 	/* Pass sequential frames to l2cap_reassemble_sdu()
5997 	 * until a gap is encountered.
5998 	 */
5999 
6000 	BT_DBG("chan %p", chan);
6001 
6002 	while (!test_bit(CONN_LOCAL_BUSY, &chan->conn_state)) {
6003 		struct sk_buff *skb;
6004 		BT_DBG("Searching for skb with txseq %d (queue len %d)",
6005 		       chan->buffer_seq, skb_queue_len(&chan->srej_q));
6006 
6007 		skb = l2cap_ertm_seq_in_queue(&chan->srej_q, chan->buffer_seq);
6008 
6009 		if (!skb)
6010 			break;
6011 
6012 		skb_unlink(skb, &chan->srej_q);
6013 		chan->buffer_seq = __next_seq(chan, chan->buffer_seq);
6014 		err = l2cap_reassemble_sdu(chan, skb, &bt_cb(skb)->l2cap);
6015 		if (err)
6016 			break;
6017 	}
6018 
6019 	if (skb_queue_empty(&chan->srej_q)) {
6020 		chan->rx_state = L2CAP_RX_STATE_RECV;
6021 		l2cap_send_ack(chan);
6022 	}
6023 
6024 	return err;
6025 }
6026 
6027 static void l2cap_handle_srej(struct l2cap_chan *chan,
6028 			      struct l2cap_ctrl *control)
6029 {
6030 	struct sk_buff *skb;
6031 
6032 	BT_DBG("chan %p, control %p", chan, control);
6033 
6034 	if (control->reqseq == chan->next_tx_seq) {
6035 		BT_DBG("Invalid reqseq %d, disconnecting", control->reqseq);
6036 		l2cap_send_disconn_req(chan, ECONNRESET);
6037 		return;
6038 	}
6039 
6040 	skb = l2cap_ertm_seq_in_queue(&chan->tx_q, control->reqseq);
6041 
6042 	if (skb == NULL) {
6043 		BT_DBG("Seq %d not available for retransmission",
6044 		       control->reqseq);
6045 		return;
6046 	}
6047 
6048 	if (chan->max_tx != 0 && bt_cb(skb)->l2cap.retries >= chan->max_tx) {
6049 		BT_DBG("Retry limit exceeded (%d)", chan->max_tx);
6050 		l2cap_send_disconn_req(chan, ECONNRESET);
6051 		return;
6052 	}
6053 
6054 	clear_bit(CONN_REMOTE_BUSY, &chan->conn_state);
6055 
6056 	if (control->poll) {
6057 		l2cap_pass_to_tx(chan, control);
6058 
6059 		set_bit(CONN_SEND_FBIT, &chan->conn_state);
6060 		l2cap_retransmit(chan, control);
6061 		l2cap_ertm_send(chan);
6062 
6063 		if (chan->tx_state == L2CAP_TX_STATE_WAIT_F) {
6064 			set_bit(CONN_SREJ_ACT, &chan->conn_state);
6065 			chan->srej_save_reqseq = control->reqseq;
6066 		}
6067 	} else {
6068 		l2cap_pass_to_tx_fbit(chan, control);
6069 
6070 		if (control->final) {
6071 			if (chan->srej_save_reqseq != control->reqseq ||
6072 			    !test_and_clear_bit(CONN_SREJ_ACT,
6073 						&chan->conn_state))
6074 				l2cap_retransmit(chan, control);
6075 		} else {
6076 			l2cap_retransmit(chan, control);
6077 			if (chan->tx_state == L2CAP_TX_STATE_WAIT_F) {
6078 				set_bit(CONN_SREJ_ACT, &chan->conn_state);
6079 				chan->srej_save_reqseq = control->reqseq;
6080 			}
6081 		}
6082 	}
6083 }
6084 
6085 static void l2cap_handle_rej(struct l2cap_chan *chan,
6086 			     struct l2cap_ctrl *control)
6087 {
6088 	struct sk_buff *skb;
6089 
6090 	BT_DBG("chan %p, control %p", chan, control);
6091 
6092 	if (control->reqseq == chan->next_tx_seq) {
6093 		BT_DBG("Invalid reqseq %d, disconnecting", control->reqseq);
6094 		l2cap_send_disconn_req(chan, ECONNRESET);
6095 		return;
6096 	}
6097 
6098 	skb = l2cap_ertm_seq_in_queue(&chan->tx_q, control->reqseq);
6099 
6100 	if (chan->max_tx && skb &&
6101 	    bt_cb(skb)->l2cap.retries >= chan->max_tx) {
6102 		BT_DBG("Retry limit exceeded (%d)", chan->max_tx);
6103 		l2cap_send_disconn_req(chan, ECONNRESET);
6104 		return;
6105 	}
6106 
6107 	clear_bit(CONN_REMOTE_BUSY, &chan->conn_state);
6108 
6109 	l2cap_pass_to_tx(chan, control);
6110 
6111 	if (control->final) {
6112 		if (!test_and_clear_bit(CONN_REJ_ACT, &chan->conn_state))
6113 			l2cap_retransmit_all(chan, control);
6114 	} else {
6115 		l2cap_retransmit_all(chan, control);
6116 		l2cap_ertm_send(chan);
6117 		if (chan->tx_state == L2CAP_TX_STATE_WAIT_F)
6118 			set_bit(CONN_REJ_ACT, &chan->conn_state);
6119 	}
6120 }
6121 
6122 static u8 l2cap_classify_txseq(struct l2cap_chan *chan, u16 txseq)
6123 {
6124 	BT_DBG("chan %p, txseq %d", chan, txseq);
6125 
6126 	BT_DBG("last_acked_seq %d, expected_tx_seq %d", chan->last_acked_seq,
6127 	       chan->expected_tx_seq);
6128 
6129 	if (chan->rx_state == L2CAP_RX_STATE_SREJ_SENT) {
6130 		if (__seq_offset(chan, txseq, chan->last_acked_seq) >=
6131 		    chan->tx_win) {
6132 			/* See notes below regarding "double poll" and
6133 			 * invalid packets.
6134 			 */
6135 			if (chan->tx_win <= ((chan->tx_win_max + 1) >> 1)) {
6136 				BT_DBG("Invalid/Ignore - after SREJ");
6137 				return L2CAP_TXSEQ_INVALID_IGNORE;
6138 			} else {
6139 				BT_DBG("Invalid - in window after SREJ sent");
6140 				return L2CAP_TXSEQ_INVALID;
6141 			}
6142 		}
6143 
6144 		if (chan->srej_list.head == txseq) {
6145 			BT_DBG("Expected SREJ");
6146 			return L2CAP_TXSEQ_EXPECTED_SREJ;
6147 		}
6148 
6149 		if (l2cap_ertm_seq_in_queue(&chan->srej_q, txseq)) {
6150 			BT_DBG("Duplicate SREJ - txseq already stored");
6151 			return L2CAP_TXSEQ_DUPLICATE_SREJ;
6152 		}
6153 
6154 		if (l2cap_seq_list_contains(&chan->srej_list, txseq)) {
6155 			BT_DBG("Unexpected SREJ - not requested");
6156 			return L2CAP_TXSEQ_UNEXPECTED_SREJ;
6157 		}
6158 	}
6159 
6160 	if (chan->expected_tx_seq == txseq) {
6161 		if (__seq_offset(chan, txseq, chan->last_acked_seq) >=
6162 		    chan->tx_win) {
6163 			BT_DBG("Invalid - txseq outside tx window");
6164 			return L2CAP_TXSEQ_INVALID;
6165 		} else {
6166 			BT_DBG("Expected");
6167 			return L2CAP_TXSEQ_EXPECTED;
6168 		}
6169 	}
6170 
6171 	if (__seq_offset(chan, txseq, chan->last_acked_seq) <
6172 	    __seq_offset(chan, chan->expected_tx_seq, chan->last_acked_seq)) {
6173 		BT_DBG("Duplicate - expected_tx_seq later than txseq");
6174 		return L2CAP_TXSEQ_DUPLICATE;
6175 	}
6176 
6177 	if (__seq_offset(chan, txseq, chan->last_acked_seq) >= chan->tx_win) {
6178 		/* A source of invalid packets is a "double poll" condition,
6179 		 * where delays cause us to send multiple poll packets.  If
6180 		 * the remote stack receives and processes both polls,
6181 		 * sequence numbers can wrap around in such a way that a
6182 		 * resent frame has a sequence number that looks like new data
6183 		 * with a sequence gap.  This would trigger an erroneous SREJ
6184 		 * request.
6185 		 *
6186 		 * Fortunately, this is impossible with a tx window that's
6187 		 * less than half of the maximum sequence number, which allows
6188 		 * invalid frames to be safely ignored.
6189 		 *
6190 		 * With tx window sizes greater than half of the tx window
6191 		 * maximum, the frame is invalid and cannot be ignored.  This
6192 		 * causes a disconnect.
6193 		 */
6194 
6195 		if (chan->tx_win <= ((chan->tx_win_max + 1) >> 1)) {
6196 			BT_DBG("Invalid/Ignore - txseq outside tx window");
6197 			return L2CAP_TXSEQ_INVALID_IGNORE;
6198 		} else {
6199 			BT_DBG("Invalid - txseq outside tx window");
6200 			return L2CAP_TXSEQ_INVALID;
6201 		}
6202 	} else {
6203 		BT_DBG("Unexpected - txseq indicates missing frames");
6204 		return L2CAP_TXSEQ_UNEXPECTED;
6205 	}
6206 }
6207 
6208 static int l2cap_rx_state_recv(struct l2cap_chan *chan,
6209 			       struct l2cap_ctrl *control,
6210 			       struct sk_buff *skb, u8 event)
6211 {
6212 	struct l2cap_ctrl local_control;
6213 	int err = 0;
6214 	bool skb_in_use = false;
6215 
6216 	BT_DBG("chan %p, control %p, skb %p, event %d", chan, control, skb,
6217 	       event);
6218 
6219 	switch (event) {
6220 	case L2CAP_EV_RECV_IFRAME:
6221 		switch (l2cap_classify_txseq(chan, control->txseq)) {
6222 		case L2CAP_TXSEQ_EXPECTED:
6223 			l2cap_pass_to_tx(chan, control);
6224 
6225 			if (test_bit(CONN_LOCAL_BUSY, &chan->conn_state)) {
6226 				BT_DBG("Busy, discarding expected seq %d",
6227 				       control->txseq);
6228 				break;
6229 			}
6230 
6231 			chan->expected_tx_seq = __next_seq(chan,
6232 							   control->txseq);
6233 
6234 			chan->buffer_seq = chan->expected_tx_seq;
6235 			skb_in_use = true;
6236 
6237 			/* l2cap_reassemble_sdu may free skb, hence invalidate
6238 			 * control, so make a copy in advance to use it after
6239 			 * l2cap_reassemble_sdu returns and to avoid the race
6240 			 * condition, for example:
6241 			 *
6242 			 * The current thread calls:
6243 			 *   l2cap_reassemble_sdu
6244 			 *     chan->ops->recv == l2cap_sock_recv_cb
6245 			 *       __sock_queue_rcv_skb
6246 			 * Another thread calls:
6247 			 *   bt_sock_recvmsg
6248 			 *     skb_recv_datagram
6249 			 *     skb_free_datagram
6250 			 * Then the current thread tries to access control, but
6251 			 * it was freed by skb_free_datagram.
6252 			 */
6253 			local_control = *control;
6254 			err = l2cap_reassemble_sdu(chan, skb, control);
6255 			if (err)
6256 				break;
6257 
6258 			if (local_control.final) {
6259 				if (!test_and_clear_bit(CONN_REJ_ACT,
6260 							&chan->conn_state)) {
6261 					local_control.final = 0;
6262 					l2cap_retransmit_all(chan, &local_control);
6263 					l2cap_ertm_send(chan);
6264 				}
6265 			}
6266 
6267 			if (!test_bit(CONN_LOCAL_BUSY, &chan->conn_state))
6268 				l2cap_send_ack(chan);
6269 			break;
6270 		case L2CAP_TXSEQ_UNEXPECTED:
6271 			l2cap_pass_to_tx(chan, control);
6272 
6273 			/* Can't issue SREJ frames in the local busy state.
6274 			 * Drop this frame, it will be seen as missing
6275 			 * when local busy is exited.
6276 			 */
6277 			if (test_bit(CONN_LOCAL_BUSY, &chan->conn_state)) {
6278 				BT_DBG("Busy, discarding unexpected seq %d",
6279 				       control->txseq);
6280 				break;
6281 			}
6282 
6283 			/* There was a gap in the sequence, so an SREJ
6284 			 * must be sent for each missing frame.  The
6285 			 * current frame is stored for later use.
6286 			 */
6287 			skb_queue_tail(&chan->srej_q, skb);
6288 			skb_in_use = true;
6289 			BT_DBG("Queued %p (queue len %d)", skb,
6290 			       skb_queue_len(&chan->srej_q));
6291 
6292 			clear_bit(CONN_SREJ_ACT, &chan->conn_state);
6293 			l2cap_seq_list_clear(&chan->srej_list);
6294 			l2cap_send_srej(chan, control->txseq);
6295 
6296 			chan->rx_state = L2CAP_RX_STATE_SREJ_SENT;
6297 			break;
6298 		case L2CAP_TXSEQ_DUPLICATE:
6299 			l2cap_pass_to_tx(chan, control);
6300 			break;
6301 		case L2CAP_TXSEQ_INVALID_IGNORE:
6302 			break;
6303 		case L2CAP_TXSEQ_INVALID:
6304 		default:
6305 			l2cap_send_disconn_req(chan, ECONNRESET);
6306 			break;
6307 		}
6308 		break;
6309 	case L2CAP_EV_RECV_RR:
6310 		l2cap_pass_to_tx(chan, control);
6311 		if (control->final) {
6312 			clear_bit(CONN_REMOTE_BUSY, &chan->conn_state);
6313 
6314 			if (!test_and_clear_bit(CONN_REJ_ACT,
6315 						&chan->conn_state)) {
6316 				control->final = 0;
6317 				l2cap_retransmit_all(chan, control);
6318 			}
6319 
6320 			l2cap_ertm_send(chan);
6321 		} else if (control->poll) {
6322 			l2cap_send_i_or_rr_or_rnr(chan);
6323 		} else {
6324 			if (test_and_clear_bit(CONN_REMOTE_BUSY,
6325 					       &chan->conn_state) &&
6326 			    chan->unacked_frames)
6327 				__set_retrans_timer(chan);
6328 
6329 			l2cap_ertm_send(chan);
6330 		}
6331 		break;
6332 	case L2CAP_EV_RECV_RNR:
6333 		set_bit(CONN_REMOTE_BUSY, &chan->conn_state);
6334 		l2cap_pass_to_tx(chan, control);
6335 		if (control && control->poll) {
6336 			set_bit(CONN_SEND_FBIT, &chan->conn_state);
6337 			l2cap_send_rr_or_rnr(chan, 0);
6338 		}
6339 		__clear_retrans_timer(chan);
6340 		l2cap_seq_list_clear(&chan->retrans_list);
6341 		break;
6342 	case L2CAP_EV_RECV_REJ:
6343 		l2cap_handle_rej(chan, control);
6344 		break;
6345 	case L2CAP_EV_RECV_SREJ:
6346 		l2cap_handle_srej(chan, control);
6347 		break;
6348 	default:
6349 		break;
6350 	}
6351 
6352 	if (skb && !skb_in_use) {
6353 		BT_DBG("Freeing %p", skb);
6354 		kfree_skb(skb);
6355 	}
6356 
6357 	return err;
6358 }
6359 
6360 static int l2cap_rx_state_srej_sent(struct l2cap_chan *chan,
6361 				    struct l2cap_ctrl *control,
6362 				    struct sk_buff *skb, u8 event)
6363 {
6364 	int err = 0;
6365 	u16 txseq = control->txseq;
6366 	bool skb_in_use = false;
6367 
6368 	BT_DBG("chan %p, control %p, skb %p, event %d", chan, control, skb,
6369 	       event);
6370 
6371 	switch (event) {
6372 	case L2CAP_EV_RECV_IFRAME:
6373 		switch (l2cap_classify_txseq(chan, txseq)) {
6374 		case L2CAP_TXSEQ_EXPECTED:
6375 			/* Keep frame for reassembly later */
6376 			l2cap_pass_to_tx(chan, control);
6377 			skb_queue_tail(&chan->srej_q, skb);
6378 			skb_in_use = true;
6379 			BT_DBG("Queued %p (queue len %d)", skb,
6380 			       skb_queue_len(&chan->srej_q));
6381 
6382 			chan->expected_tx_seq = __next_seq(chan, txseq);
6383 			break;
6384 		case L2CAP_TXSEQ_EXPECTED_SREJ:
6385 			l2cap_seq_list_pop(&chan->srej_list);
6386 
6387 			l2cap_pass_to_tx(chan, control);
6388 			skb_queue_tail(&chan->srej_q, skb);
6389 			skb_in_use = true;
6390 			BT_DBG("Queued %p (queue len %d)", skb,
6391 			       skb_queue_len(&chan->srej_q));
6392 
6393 			err = l2cap_rx_queued_iframes(chan);
6394 			if (err)
6395 				break;
6396 
6397 			break;
6398 		case L2CAP_TXSEQ_UNEXPECTED:
6399 			/* Got a frame that can't be reassembled yet.
6400 			 * Save it for later, and send SREJs to cover
6401 			 * the missing frames.
6402 			 */
6403 			skb_queue_tail(&chan->srej_q, skb);
6404 			skb_in_use = true;
6405 			BT_DBG("Queued %p (queue len %d)", skb,
6406 			       skb_queue_len(&chan->srej_q));
6407 
6408 			l2cap_pass_to_tx(chan, control);
6409 			l2cap_send_srej(chan, control->txseq);
6410 			break;
6411 		case L2CAP_TXSEQ_UNEXPECTED_SREJ:
6412 			/* This frame was requested with an SREJ, but
6413 			 * some expected retransmitted frames are
6414 			 * missing.  Request retransmission of missing
6415 			 * SREJ'd frames.
6416 			 */
6417 			skb_queue_tail(&chan->srej_q, skb);
6418 			skb_in_use = true;
6419 			BT_DBG("Queued %p (queue len %d)", skb,
6420 			       skb_queue_len(&chan->srej_q));
6421 
6422 			l2cap_pass_to_tx(chan, control);
6423 			l2cap_send_srej_list(chan, control->txseq);
6424 			break;
6425 		case L2CAP_TXSEQ_DUPLICATE_SREJ:
6426 			/* We've already queued this frame.  Drop this copy. */
6427 			l2cap_pass_to_tx(chan, control);
6428 			break;
6429 		case L2CAP_TXSEQ_DUPLICATE:
6430 			/* Expecting a later sequence number, so this frame
6431 			 * was already received.  Ignore it completely.
6432 			 */
6433 			break;
6434 		case L2CAP_TXSEQ_INVALID_IGNORE:
6435 			break;
6436 		case L2CAP_TXSEQ_INVALID:
6437 		default:
6438 			l2cap_send_disconn_req(chan, ECONNRESET);
6439 			break;
6440 		}
6441 		break;
6442 	case L2CAP_EV_RECV_RR:
6443 		l2cap_pass_to_tx(chan, control);
6444 		if (control->final) {
6445 			clear_bit(CONN_REMOTE_BUSY, &chan->conn_state);
6446 
6447 			if (!test_and_clear_bit(CONN_REJ_ACT,
6448 						&chan->conn_state)) {
6449 				control->final = 0;
6450 				l2cap_retransmit_all(chan, control);
6451 			}
6452 
6453 			l2cap_ertm_send(chan);
6454 		} else if (control->poll) {
6455 			if (test_and_clear_bit(CONN_REMOTE_BUSY,
6456 					       &chan->conn_state) &&
6457 			    chan->unacked_frames) {
6458 				__set_retrans_timer(chan);
6459 			}
6460 
6461 			set_bit(CONN_SEND_FBIT, &chan->conn_state);
6462 			l2cap_send_srej_tail(chan);
6463 		} else {
6464 			if (test_and_clear_bit(CONN_REMOTE_BUSY,
6465 					       &chan->conn_state) &&
6466 			    chan->unacked_frames)
6467 				__set_retrans_timer(chan);
6468 
6469 			l2cap_send_ack(chan);
6470 		}
6471 		break;
6472 	case L2CAP_EV_RECV_RNR:
6473 		set_bit(CONN_REMOTE_BUSY, &chan->conn_state);
6474 		l2cap_pass_to_tx(chan, control);
6475 		if (control->poll) {
6476 			l2cap_send_srej_tail(chan);
6477 		} else {
6478 			struct l2cap_ctrl rr_control;
6479 			memset(&rr_control, 0, sizeof(rr_control));
6480 			rr_control.sframe = 1;
6481 			rr_control.super = L2CAP_SUPER_RR;
6482 			rr_control.reqseq = chan->buffer_seq;
6483 			l2cap_send_sframe(chan, &rr_control);
6484 		}
6485 
6486 		break;
6487 	case L2CAP_EV_RECV_REJ:
6488 		l2cap_handle_rej(chan, control);
6489 		break;
6490 	case L2CAP_EV_RECV_SREJ:
6491 		l2cap_handle_srej(chan, control);
6492 		break;
6493 	}
6494 
6495 	if (skb && !skb_in_use) {
6496 		BT_DBG("Freeing %p", skb);
6497 		kfree_skb(skb);
6498 	}
6499 
6500 	return err;
6501 }
6502 
6503 static int l2cap_finish_move(struct l2cap_chan *chan)
6504 {
6505 	BT_DBG("chan %p", chan);
6506 
6507 	chan->rx_state = L2CAP_RX_STATE_RECV;
6508 	chan->conn->mtu = chan->conn->hcon->mtu;
6509 
6510 	return l2cap_resegment(chan);
6511 }
6512 
6513 static int l2cap_rx_state_wait_p(struct l2cap_chan *chan,
6514 				 struct l2cap_ctrl *control,
6515 				 struct sk_buff *skb, u8 event)
6516 {
6517 	int err;
6518 
6519 	BT_DBG("chan %p, control %p, skb %p, event %d", chan, control, skb,
6520 	       event);
6521 
6522 	if (!control->poll)
6523 		return -EPROTO;
6524 
6525 	l2cap_process_reqseq(chan, control->reqseq);
6526 
6527 	if (!skb_queue_empty(&chan->tx_q))
6528 		chan->tx_send_head = skb_peek(&chan->tx_q);
6529 	else
6530 		chan->tx_send_head = NULL;
6531 
6532 	/* Rewind next_tx_seq to the point expected
6533 	 * by the receiver.
6534 	 */
6535 	chan->next_tx_seq = control->reqseq;
6536 	chan->unacked_frames = 0;
6537 
6538 	err = l2cap_finish_move(chan);
6539 	if (err)
6540 		return err;
6541 
6542 	set_bit(CONN_SEND_FBIT, &chan->conn_state);
6543 	l2cap_send_i_or_rr_or_rnr(chan);
6544 
6545 	if (event == L2CAP_EV_RECV_IFRAME)
6546 		return -EPROTO;
6547 
6548 	return l2cap_rx_state_recv(chan, control, NULL, event);
6549 }
6550 
6551 static int l2cap_rx_state_wait_f(struct l2cap_chan *chan,
6552 				 struct l2cap_ctrl *control,
6553 				 struct sk_buff *skb, u8 event)
6554 {
6555 	int err;
6556 
6557 	if (!control->final)
6558 		return -EPROTO;
6559 
6560 	clear_bit(CONN_REMOTE_BUSY, &chan->conn_state);
6561 
6562 	chan->rx_state = L2CAP_RX_STATE_RECV;
6563 	l2cap_process_reqseq(chan, control->reqseq);
6564 
6565 	if (!skb_queue_empty(&chan->tx_q))
6566 		chan->tx_send_head = skb_peek(&chan->tx_q);
6567 	else
6568 		chan->tx_send_head = NULL;
6569 
6570 	/* Rewind next_tx_seq to the point expected
6571 	 * by the receiver.
6572 	 */
6573 	chan->next_tx_seq = control->reqseq;
6574 	chan->unacked_frames = 0;
6575 	chan->conn->mtu = chan->conn->hcon->mtu;
6576 
6577 	err = l2cap_resegment(chan);
6578 
6579 	if (!err)
6580 		err = l2cap_rx_state_recv(chan, control, skb, event);
6581 
6582 	return err;
6583 }
6584 
6585 static bool __valid_reqseq(struct l2cap_chan *chan, u16 reqseq)
6586 {
6587 	/* Make sure reqseq is for a packet that has been sent but not acked */
6588 	u16 unacked;
6589 
6590 	unacked = __seq_offset(chan, chan->next_tx_seq, chan->expected_ack_seq);
6591 	return __seq_offset(chan, chan->next_tx_seq, reqseq) <= unacked;
6592 }
6593 
6594 static int l2cap_rx(struct l2cap_chan *chan, struct l2cap_ctrl *control,
6595 		    struct sk_buff *skb, u8 event)
6596 {
6597 	int err = 0;
6598 
6599 	BT_DBG("chan %p, control %p, skb %p, event %d, state %d", chan,
6600 	       control, skb, event, chan->rx_state);
6601 
6602 	if (__valid_reqseq(chan, control->reqseq)) {
6603 		switch (chan->rx_state) {
6604 		case L2CAP_RX_STATE_RECV:
6605 			err = l2cap_rx_state_recv(chan, control, skb, event);
6606 			break;
6607 		case L2CAP_RX_STATE_SREJ_SENT:
6608 			err = l2cap_rx_state_srej_sent(chan, control, skb,
6609 						       event);
6610 			break;
6611 		case L2CAP_RX_STATE_WAIT_P:
6612 			err = l2cap_rx_state_wait_p(chan, control, skb, event);
6613 			break;
6614 		case L2CAP_RX_STATE_WAIT_F:
6615 			err = l2cap_rx_state_wait_f(chan, control, skb, event);
6616 			break;
6617 		default:
6618 			/* shut it down */
6619 			break;
6620 		}
6621 	} else {
6622 		BT_DBG("Invalid reqseq %d (next_tx_seq %d, expected_ack_seq %d",
6623 		       control->reqseq, chan->next_tx_seq,
6624 		       chan->expected_ack_seq);
6625 		l2cap_send_disconn_req(chan, ECONNRESET);
6626 	}
6627 
6628 	return err;
6629 }
6630 
6631 static int l2cap_stream_rx(struct l2cap_chan *chan, struct l2cap_ctrl *control,
6632 			   struct sk_buff *skb)
6633 {
6634 	/* l2cap_reassemble_sdu may free skb, hence invalidate control, so store
6635 	 * the txseq field in advance to use it after l2cap_reassemble_sdu
6636 	 * returns and to avoid the race condition, for example:
6637 	 *
6638 	 * The current thread calls:
6639 	 *   l2cap_reassemble_sdu
6640 	 *     chan->ops->recv == l2cap_sock_recv_cb
6641 	 *       __sock_queue_rcv_skb
6642 	 * Another thread calls:
6643 	 *   bt_sock_recvmsg
6644 	 *     skb_recv_datagram
6645 	 *     skb_free_datagram
6646 	 * Then the current thread tries to access control, but it was freed by
6647 	 * skb_free_datagram.
6648 	 */
6649 	u16 txseq = control->txseq;
6650 
6651 	BT_DBG("chan %p, control %p, skb %p, state %d", chan, control, skb,
6652 	       chan->rx_state);
6653 
6654 	if (l2cap_classify_txseq(chan, txseq) == L2CAP_TXSEQ_EXPECTED) {
6655 		l2cap_pass_to_tx(chan, control);
6656 
6657 		BT_DBG("buffer_seq %u->%u", chan->buffer_seq,
6658 		       __next_seq(chan, chan->buffer_seq));
6659 
6660 		chan->buffer_seq = __next_seq(chan, chan->buffer_seq);
6661 
6662 		l2cap_reassemble_sdu(chan, skb, control);
6663 	} else {
6664 		if (chan->sdu) {
6665 			kfree_skb(chan->sdu);
6666 			chan->sdu = NULL;
6667 		}
6668 		chan->sdu_last_frag = NULL;
6669 		chan->sdu_len = 0;
6670 
6671 		if (skb) {
6672 			BT_DBG("Freeing %p", skb);
6673 			kfree_skb(skb);
6674 		}
6675 	}
6676 
6677 	chan->last_acked_seq = txseq;
6678 	chan->expected_tx_seq = __next_seq(chan, txseq);
6679 
6680 	return 0;
6681 }
6682 
6683 static int l2cap_data_rcv(struct l2cap_chan *chan, struct sk_buff *skb)
6684 {
6685 	struct l2cap_ctrl *control = &bt_cb(skb)->l2cap;
6686 	u16 len;
6687 	u8 event;
6688 
6689 	__unpack_control(chan, skb);
6690 
6691 	len = skb->len;
6692 
6693 	/*
6694 	 * We can just drop the corrupted I-frame here.
6695 	 * Receiver will miss it and start proper recovery
6696 	 * procedures and ask for retransmission.
6697 	 */
6698 	if (l2cap_check_fcs(chan, skb))
6699 		goto drop;
6700 
6701 	if (!control->sframe && control->sar == L2CAP_SAR_START)
6702 		len -= L2CAP_SDULEN_SIZE;
6703 
6704 	if (chan->fcs == L2CAP_FCS_CRC16)
6705 		len -= L2CAP_FCS_SIZE;
6706 
6707 	if (len > chan->mps) {
6708 		l2cap_send_disconn_req(chan, ECONNRESET);
6709 		goto drop;
6710 	}
6711 
6712 	if (chan->ops->filter) {
6713 		if (chan->ops->filter(chan, skb))
6714 			goto drop;
6715 	}
6716 
6717 	if (!control->sframe) {
6718 		int err;
6719 
6720 		BT_DBG("iframe sar %d, reqseq %d, final %d, txseq %d",
6721 		       control->sar, control->reqseq, control->final,
6722 		       control->txseq);
6723 
6724 		/* Validate F-bit - F=0 always valid, F=1 only
6725 		 * valid in TX WAIT_F
6726 		 */
6727 		if (control->final && chan->tx_state != L2CAP_TX_STATE_WAIT_F)
6728 			goto drop;
6729 
6730 		if (chan->mode != L2CAP_MODE_STREAMING) {
6731 			event = L2CAP_EV_RECV_IFRAME;
6732 			err = l2cap_rx(chan, control, skb, event);
6733 		} else {
6734 			err = l2cap_stream_rx(chan, control, skb);
6735 		}
6736 
6737 		if (err)
6738 			l2cap_send_disconn_req(chan, ECONNRESET);
6739 	} else {
6740 		const u8 rx_func_to_event[4] = {
6741 			L2CAP_EV_RECV_RR, L2CAP_EV_RECV_REJ,
6742 			L2CAP_EV_RECV_RNR, L2CAP_EV_RECV_SREJ
6743 		};
6744 
6745 		/* Only I-frames are expected in streaming mode */
6746 		if (chan->mode == L2CAP_MODE_STREAMING)
6747 			goto drop;
6748 
6749 		BT_DBG("sframe reqseq %d, final %d, poll %d, super %d",
6750 		       control->reqseq, control->final, control->poll,
6751 		       control->super);
6752 
6753 		if (len != 0) {
6754 			BT_ERR("Trailing bytes: %d in sframe", len);
6755 			l2cap_send_disconn_req(chan, ECONNRESET);
6756 			goto drop;
6757 		}
6758 
6759 		/* Validate F and P bits */
6760 		if (control->final && (control->poll ||
6761 				       chan->tx_state != L2CAP_TX_STATE_WAIT_F))
6762 			goto drop;
6763 
6764 		event = rx_func_to_event[control->super];
6765 		if (l2cap_rx(chan, control, skb, event))
6766 			l2cap_send_disconn_req(chan, ECONNRESET);
6767 	}
6768 
6769 	return 0;
6770 
6771 drop:
6772 	kfree_skb(skb);
6773 	return 0;
6774 }
6775 
6776 static void l2cap_chan_le_send_credits(struct l2cap_chan *chan)
6777 {
6778 	struct l2cap_conn *conn = chan->conn;
6779 	struct l2cap_le_credits pkt;
6780 	u16 return_credits = l2cap_le_rx_credits(chan);
6781 	int ident;
6782 
6783 	if (chan->mode != L2CAP_MODE_LE_FLOWCTL &&
6784 	    chan->mode != L2CAP_MODE_EXT_FLOWCTL)
6785 		return;
6786 
6787 	if (chan->rx_credits >= return_credits)
6788 		return;
6789 
6790 	return_credits -= chan->rx_credits;
6791 
6792 	BT_DBG("chan %p returning %u credits to sender", chan, return_credits);
6793 
6794 	chan->rx_credits += return_credits;
6795 
6796 	pkt.cid     = cpu_to_le16(chan->scid);
6797 	pkt.credits = cpu_to_le16(return_credits);
6798 
6799 	ident = l2cap_get_ident(conn);
6800 
6801 	l2cap_send_cmd(conn, ident, L2CAP_LE_CREDITS, sizeof(pkt), &pkt);
6802 
6803 	/* L2CAP_LE_CREDITS has no response so the ident is never released by
6804 	 * l2cap_put_ident() - release it right away, otherwise the tx_ida
6805 	 * range is exhausted after 254 packets and from then on credits are
6806 	 * sent with the invalid ident 0, which some remote stacks ignore,
6807 	 * stalling the channel.
6808 	 */
6809 	if (ident > 0)
6810 		ida_free(&conn->tx_ida, ident);
6811 }
6812 
6813 void l2cap_chan_rx_avail(struct l2cap_chan *chan, ssize_t rx_avail)
6814 {
6815 	if (chan->rx_avail == rx_avail)
6816 		return;
6817 
6818 	BT_DBG("chan %p has %zd bytes avail for rx", chan, rx_avail);
6819 
6820 	chan->rx_avail = rx_avail;
6821 
6822 	if (chan->state == BT_CONNECTED)
6823 		l2cap_chan_le_send_credits(chan);
6824 }
6825 
6826 static int l2cap_ecred_recv(struct l2cap_chan *chan, struct sk_buff *skb)
6827 {
6828 	int err;
6829 
6830 	BT_DBG("SDU reassemble complete: chan %p skb->len %u", chan, skb->len);
6831 
6832 	/* Wait recv to confirm reception before updating the credits */
6833 	err = chan->ops->recv(chan, skb);
6834 
6835 	if (err < 0 && chan->rx_avail != -1) {
6836 		BT_ERR("Queueing received LE L2CAP data failed");
6837 		l2cap_send_disconn_req(chan, ECONNRESET);
6838 		return err;
6839 	}
6840 
6841 	/* Update credits whenever an SDU is received */
6842 	l2cap_chan_le_send_credits(chan);
6843 
6844 	return err;
6845 }
6846 
6847 static int l2cap_ecred_data_rcv(struct l2cap_chan *chan, struct sk_buff *skb)
6848 {
6849 	int err;
6850 
6851 	if (!chan->rx_credits) {
6852 		BT_ERR("No credits to receive LE L2CAP data");
6853 		l2cap_send_disconn_req(chan, ECONNRESET);
6854 		return -ENOBUFS;
6855 	}
6856 
6857 	if (skb->len > chan->imtu) {
6858 		BT_ERR("Too big LE L2CAP PDU: len %u > %u", skb->len,
6859 		       chan->imtu);
6860 		l2cap_send_disconn_req(chan, ECONNRESET);
6861 		return -ENOBUFS;
6862 	}
6863 
6864 	if (skb->len > chan->mps) {
6865 		BT_ERR("Too big LE L2CAP MPS: len %u > %u", skb->len,
6866 		       chan->mps);
6867 		l2cap_send_disconn_req(chan, ECONNRESET);
6868 		return -ENOBUFS;
6869 	}
6870 
6871 	chan->rx_credits--;
6872 	BT_DBG("chan %p: rx_credits %u -> %u",
6873 	       chan, chan->rx_credits + 1, chan->rx_credits);
6874 
6875 	/* Update if remote had run out of credits, this should only happens
6876 	 * if the remote is not using the entire MPS.
6877 	 */
6878 	if (!chan->rx_credits)
6879 		l2cap_chan_le_send_credits(chan);
6880 
6881 	err = 0;
6882 
6883 	if (!chan->sdu) {
6884 		u16 sdu_len;
6885 
6886 		if (!pskb_may_pull(skb, L2CAP_SDULEN_SIZE)) {
6887 			err = -EINVAL;
6888 			goto failed;
6889 		}
6890 
6891 		sdu_len = get_unaligned_le16(skb->data);
6892 		skb_pull(skb, L2CAP_SDULEN_SIZE);
6893 
6894 		BT_DBG("Start of new SDU. sdu_len %u skb->len %u imtu %u",
6895 		       sdu_len, skb->len, chan->imtu);
6896 
6897 		if (sdu_len > chan->imtu) {
6898 			BT_ERR("Too big LE L2CAP SDU length: len %u > %u",
6899 			       sdu_len, chan->imtu);
6900 			l2cap_send_disconn_req(chan, ECONNRESET);
6901 			err = -EMSGSIZE;
6902 			goto failed;
6903 		}
6904 
6905 		if (skb->len > sdu_len) {
6906 			BT_ERR("Too much LE L2CAP data received");
6907 			err = -EINVAL;
6908 			goto failed;
6909 		}
6910 
6911 		if (skb->len == sdu_len)
6912 			return l2cap_ecred_recv(chan, skb);
6913 
6914 		chan->sdu = skb;
6915 		chan->sdu_len = sdu_len;
6916 		chan->sdu_last_frag = skb;
6917 
6918 		/* Detect if remote is not able to use the selected MPS */
6919 		if (skb->len + L2CAP_SDULEN_SIZE < chan->mps) {
6920 			u16 mps_len = skb->len + L2CAP_SDULEN_SIZE;
6921 
6922 			/* Adjust the number of credits */
6923 			BT_DBG("chan->mps %u -> %u", chan->mps, mps_len);
6924 			chan->mps = mps_len;
6925 			l2cap_chan_le_send_credits(chan);
6926 		}
6927 
6928 		return 0;
6929 	}
6930 
6931 	BT_DBG("SDU fragment. chan->sdu->len %u skb->len %u chan->sdu_len %u",
6932 	       chan->sdu->len, skb->len, chan->sdu_len);
6933 
6934 	if (chan->sdu->len + skb->len > chan->sdu_len) {
6935 		BT_ERR("Too much LE L2CAP data received");
6936 		l2cap_send_disconn_req(chan, ECONNRESET);
6937 		err = -EINVAL;
6938 		goto failed;
6939 	}
6940 
6941 	append_skb_frag(chan->sdu, skb, &chan->sdu_last_frag);
6942 	skb = NULL;
6943 
6944 	if (chan->sdu->len == chan->sdu_len) {
6945 		err = l2cap_ecred_recv(chan, chan->sdu);
6946 		if (!err) {
6947 			chan->sdu = NULL;
6948 			chan->sdu_last_frag = NULL;
6949 			chan->sdu_len = 0;
6950 		}
6951 	}
6952 
6953 failed:
6954 	if (err) {
6955 		kfree_skb(skb);
6956 		kfree_skb(chan->sdu);
6957 		chan->sdu = NULL;
6958 		chan->sdu_last_frag = NULL;
6959 		chan->sdu_len = 0;
6960 	}
6961 
6962 	/* We can't return an error here since we took care of the skb
6963 	 * freeing internally. An error return would cause the caller to
6964 	 * do a double-free of the skb.
6965 	 */
6966 	return 0;
6967 }
6968 
6969 static void l2cap_data_channel(struct l2cap_conn *conn, u16 cid,
6970 			       struct sk_buff *skb)
6971 {
6972 	struct l2cap_chan *chan;
6973 
6974 	chan = l2cap_get_chan_by_scid(conn, cid);
6975 	if (!chan) {
6976 		BT_DBG("unknown cid 0x%4.4x", cid);
6977 		/* Drop packet and return */
6978 		kfree_skb(skb);
6979 		return;
6980 	}
6981 
6982 	BT_DBG("chan %p, len %d", chan, skb->len);
6983 
6984 	/* If we receive data on a fixed channel before the info req/rsp
6985 	 * procedure is done simply assume that the channel is supported
6986 	 * and mark it as ready.
6987 	 */
6988 	if (chan->chan_type == L2CAP_CHAN_FIXED)
6989 		l2cap_chan_ready(chan);
6990 
6991 	if (chan->state != BT_CONNECTED)
6992 		goto drop;
6993 
6994 	switch (chan->mode) {
6995 	case L2CAP_MODE_LE_FLOWCTL:
6996 	case L2CAP_MODE_EXT_FLOWCTL:
6997 		if (l2cap_ecred_data_rcv(chan, skb) < 0)
6998 			goto drop;
6999 
7000 		goto done;
7001 
7002 	case L2CAP_MODE_BASIC:
7003 		/* If socket recv buffers overflows we drop data here
7004 		 * which is *bad* because L2CAP has to be reliable.
7005 		 * But we don't have any other choice. L2CAP doesn't
7006 		 * provide flow control mechanism. */
7007 
7008 		if (chan->imtu < skb->len) {
7009 			BT_ERR("Dropping L2CAP data: receive buffer overflow");
7010 			goto drop;
7011 		}
7012 
7013 		if (!chan->ops->recv(chan, skb))
7014 			goto done;
7015 		break;
7016 
7017 	case L2CAP_MODE_ERTM:
7018 	case L2CAP_MODE_STREAMING:
7019 		l2cap_data_rcv(chan, skb);
7020 		goto done;
7021 
7022 	default:
7023 		BT_DBG("chan %p: bad mode 0x%2.2x", chan, chan->mode);
7024 		break;
7025 	}
7026 
7027 drop:
7028 	kfree_skb(skb);
7029 
7030 done:
7031 	l2cap_chan_unlock(chan);
7032 	l2cap_chan_put(chan);
7033 }
7034 
7035 static void l2cap_conless_channel(struct l2cap_conn *conn, __le16 psm,
7036 				  struct sk_buff *skb)
7037 {
7038 	struct hci_conn *hcon = conn->hcon;
7039 	struct l2cap_chan *chan;
7040 
7041 	if (hcon->type != ACL_LINK)
7042 		goto free_skb;
7043 
7044 	chan = l2cap_global_chan_by_psm(0, psm, &hcon->src, &hcon->dst,
7045 					ACL_LINK);
7046 	if (!chan)
7047 		goto free_skb;
7048 
7049 	BT_DBG("chan %p, len %d", chan, skb->len);
7050 
7051 	l2cap_chan_lock(chan);
7052 
7053 	if (chan->state != BT_BOUND && chan->state != BT_CONNECTED)
7054 		goto drop;
7055 
7056 	if (chan->imtu < skb->len)
7057 		goto drop;
7058 
7059 	/* Store remote BD_ADDR and PSM for msg_name */
7060 	bacpy(&bt_cb(skb)->l2cap.bdaddr, &hcon->dst);
7061 	bt_cb(skb)->l2cap.psm = psm;
7062 
7063 	if (!chan->ops->recv(chan, skb)) {
7064 		l2cap_chan_unlock(chan);
7065 		l2cap_chan_put(chan);
7066 		return;
7067 	}
7068 
7069 drop:
7070 	l2cap_chan_unlock(chan);
7071 	l2cap_chan_put(chan);
7072 free_skb:
7073 	kfree_skb(skb);
7074 }
7075 
7076 static void l2cap_recv_frame(struct l2cap_conn *conn, struct sk_buff *skb)
7077 {
7078 	struct l2cap_hdr *lh = (void *) skb->data;
7079 	struct hci_conn *hcon = conn->hcon;
7080 	u16 cid, len;
7081 	__le16 psm;
7082 
7083 	if (hcon->state != BT_CONNECTED) {
7084 		BT_DBG("queueing pending rx skb");
7085 		skb_queue_tail(&conn->pending_rx, skb);
7086 		return;
7087 	}
7088 
7089 	skb_pull(skb, L2CAP_HDR_SIZE);
7090 	cid = __le16_to_cpu(lh->cid);
7091 	len = __le16_to_cpu(lh->len);
7092 
7093 	if (len != skb->len) {
7094 		kfree_skb(skb);
7095 		return;
7096 	}
7097 
7098 	/* Since we can't actively block incoming LE connections we must
7099 	 * at least ensure that we ignore incoming data from them.
7100 	 */
7101 	if (hcon->type == LE_LINK &&
7102 	    hci_bdaddr_list_lookup(&hcon->hdev->reject_list, &hcon->dst,
7103 				   bdaddr_dst_type(hcon))) {
7104 		kfree_skb(skb);
7105 		return;
7106 	}
7107 
7108 	BT_DBG("len %d, cid 0x%4.4x", len, cid);
7109 
7110 	switch (cid) {
7111 	case L2CAP_CID_SIGNALING:
7112 		l2cap_sig_channel(conn, skb);
7113 		break;
7114 
7115 	case L2CAP_CID_CONN_LESS:
7116 		if (skb->len < L2CAP_PSMLEN_SIZE) {
7117 			kfree_skb(skb);
7118 			break;
7119 		}
7120 
7121 		psm = get_unaligned((__le16 *) skb->data);
7122 		skb_pull(skb, L2CAP_PSMLEN_SIZE);
7123 		l2cap_conless_channel(conn, psm, skb);
7124 		break;
7125 
7126 	case L2CAP_CID_LE_SIGNALING:
7127 		l2cap_le_sig_channel(conn, skb);
7128 		break;
7129 
7130 	default:
7131 		l2cap_data_channel(conn, cid, skb);
7132 		break;
7133 	}
7134 }
7135 
7136 static void process_pending_rx(struct work_struct *work)
7137 {
7138 	struct l2cap_conn *conn = container_of(work, struct l2cap_conn,
7139 					       pending_rx_work);
7140 	struct sk_buff *skb;
7141 
7142 	BT_DBG("");
7143 
7144 	mutex_lock(&conn->lock);
7145 
7146 	while ((skb = skb_dequeue(&conn->pending_rx)))
7147 		l2cap_recv_frame(conn, skb);
7148 
7149 	mutex_unlock(&conn->lock);
7150 }
7151 
7152 static struct l2cap_conn *l2cap_conn_add(struct hci_conn *hcon)
7153 {
7154 	struct l2cap_conn *conn = hcon->l2cap_data;
7155 	struct hci_chan *hchan;
7156 
7157 	if (conn)
7158 		return conn;
7159 
7160 	hchan = hci_chan_create(hcon);
7161 	if (!hchan)
7162 		return NULL;
7163 
7164 	conn = kzalloc_obj(*conn);
7165 	if (!conn) {
7166 		hci_chan_del(hchan);
7167 		return NULL;
7168 	}
7169 
7170 	kref_init(&conn->ref);
7171 	hcon->l2cap_data = conn;
7172 	conn->hcon = hci_conn_get(hcon);
7173 	conn->hchan = hchan;
7174 
7175 	BT_DBG("hcon %p conn %p hchan %p", hcon, conn, hchan);
7176 
7177 	conn->mtu = hcon->mtu;
7178 	conn->feat_mask = 0;
7179 
7180 	conn->local_fixed_chan = L2CAP_FC_SIG_BREDR | L2CAP_FC_CONNLESS;
7181 
7182 	if (hci_dev_test_flag(hcon->hdev, HCI_LE_ENABLED) &&
7183 	    (bredr_sc_enabled(hcon->hdev) ||
7184 	     hci_dev_test_flag(hcon->hdev, HCI_FORCE_BREDR_SMP)))
7185 		conn->local_fixed_chan |= L2CAP_FC_SMP_BREDR;
7186 
7187 	mutex_init(&conn->lock);
7188 
7189 	INIT_LIST_HEAD(&conn->chan_l);
7190 	INIT_LIST_HEAD(&conn->users);
7191 
7192 	INIT_DELAYED_WORK(&conn->info_timer, l2cap_info_timeout);
7193 	ida_init(&conn->tx_ida);
7194 
7195 	skb_queue_head_init(&conn->pending_rx);
7196 	INIT_WORK(&conn->pending_rx_work, process_pending_rx);
7197 	INIT_DELAYED_WORK(&conn->id_addr_timer, l2cap_conn_update_id_addr);
7198 
7199 	conn->disc_reason = HCI_ERROR_REMOTE_USER_TERM;
7200 
7201 	return conn;
7202 }
7203 
7204 static bool is_valid_psm(u16 psm, u8 dst_type)
7205 {
7206 	if (!psm)
7207 		return false;
7208 
7209 	if (bdaddr_type_is_le(dst_type))
7210 		return (psm <= 0x00ff);
7211 
7212 	/* PSM must be odd and lsb of upper byte must be 0 */
7213 	return ((psm & 0x0101) == 0x0001);
7214 }
7215 
7216 struct l2cap_chan_data {
7217 	struct l2cap_chan *chan;
7218 	struct pid *pid;
7219 	int count;
7220 };
7221 
7222 static void l2cap_chan_by_pid(struct l2cap_chan *chan, void *data)
7223 {
7224 	struct l2cap_chan_data *d = data;
7225 	struct pid *pid;
7226 
7227 	if (chan == d->chan)
7228 		return;
7229 
7230 	if (!test_bit(FLAG_DEFER_SETUP, &chan->flags))
7231 		return;
7232 
7233 	pid = chan->ops->get_peer_pid(chan);
7234 
7235 	/* Only count deferred channels with the same PID/PSM */
7236 	if (d->pid != pid || chan->psm != d->chan->psm || chan->ident ||
7237 	    chan->mode != L2CAP_MODE_EXT_FLOWCTL || chan->state != BT_CONNECT)
7238 		return;
7239 
7240 	d->count++;
7241 }
7242 
7243 int l2cap_chan_connect(struct l2cap_chan *chan, __le16 psm, u16 cid,
7244 		       bdaddr_t *dst, u8 dst_type, u16 timeout)
7245 {
7246 	struct l2cap_conn *conn;
7247 	struct hci_conn *hcon;
7248 	struct hci_dev *hdev;
7249 	int err;
7250 
7251 	BT_DBG("%pMR -> %pMR (type %u) psm 0x%4.4x mode 0x%2.2x", &chan->src,
7252 	       dst, dst_type, __le16_to_cpu(psm), chan->mode);
7253 
7254 	hdev = hci_get_route(dst, &chan->src, chan->src_type);
7255 	if (!hdev)
7256 		return -EHOSTUNREACH;
7257 
7258 	hci_dev_lock(hdev);
7259 
7260 	if (!is_valid_psm(__le16_to_cpu(psm), dst_type) && !cid &&
7261 	    chan->chan_type != L2CAP_CHAN_RAW) {
7262 		err = -EINVAL;
7263 		goto done;
7264 	}
7265 
7266 	if (chan->chan_type == L2CAP_CHAN_CONN_ORIENTED && !psm) {
7267 		err = -EINVAL;
7268 		goto done;
7269 	}
7270 
7271 	if (chan->chan_type == L2CAP_CHAN_FIXED && !cid) {
7272 		err = -EINVAL;
7273 		goto done;
7274 	}
7275 
7276 	switch (chan->mode) {
7277 	case L2CAP_MODE_BASIC:
7278 		break;
7279 	case L2CAP_MODE_LE_FLOWCTL:
7280 		break;
7281 	case L2CAP_MODE_EXT_FLOWCTL:
7282 		if (!enable_ecred) {
7283 			err = -EOPNOTSUPP;
7284 			goto done;
7285 		}
7286 		break;
7287 	case L2CAP_MODE_ERTM:
7288 	case L2CAP_MODE_STREAMING:
7289 		if (!disable_ertm)
7290 			break;
7291 		fallthrough;
7292 	default:
7293 		err = -EOPNOTSUPP;
7294 		goto done;
7295 	}
7296 
7297 	switch (chan->state) {
7298 	case BT_CONNECT:
7299 	case BT_CONNECT2:
7300 	case BT_CONFIG:
7301 		/* Already connecting */
7302 		err = 0;
7303 		goto done;
7304 
7305 	case BT_CONNECTED:
7306 		/* Already connected */
7307 		err = -EISCONN;
7308 		goto done;
7309 
7310 	case BT_OPEN:
7311 	case BT_BOUND:
7312 		/* Can connect */
7313 		break;
7314 
7315 	default:
7316 		err = -EBADFD;
7317 		goto done;
7318 	}
7319 
7320 	/* Set destination address and psm */
7321 	bacpy(&chan->dst, dst);
7322 	chan->dst_type = dst_type;
7323 
7324 	chan->psm = psm;
7325 	chan->dcid = cid;
7326 
7327 	if (bdaddr_type_is_le(dst_type)) {
7328 		/* Convert from L2CAP channel address type to HCI address type
7329 		 */
7330 		if (dst_type == BDADDR_LE_PUBLIC)
7331 			dst_type = ADDR_LE_DEV_PUBLIC;
7332 		else
7333 			dst_type = ADDR_LE_DEV_RANDOM;
7334 
7335 		if (hci_dev_test_flag(hdev, HCI_ADVERTISING))
7336 			hcon = hci_connect_le(hdev, dst, dst_type, false,
7337 					      chan->sec_level, timeout,
7338 					      HCI_ROLE_SLAVE, 0, 0);
7339 		else
7340 			hcon = hci_connect_le_scan(hdev, dst, dst_type,
7341 						   chan->sec_level, timeout,
7342 						   CONN_REASON_L2CAP_CHAN);
7343 
7344 	} else {
7345 		u8 auth_type = l2cap_get_auth_type(chan);
7346 		hcon = hci_connect_acl(hdev, dst, chan->sec_level, auth_type,
7347 				       CONN_REASON_L2CAP_CHAN, timeout);
7348 	}
7349 
7350 	if (IS_ERR(hcon)) {
7351 		err = PTR_ERR(hcon);
7352 		goto done;
7353 	}
7354 
7355 	conn = l2cap_conn_add(hcon);
7356 	if (!conn) {
7357 		hci_conn_drop(hcon);
7358 		err = -ENOMEM;
7359 		goto done;
7360 	}
7361 
7362 	if (chan->mode == L2CAP_MODE_EXT_FLOWCTL) {
7363 		struct l2cap_chan_data data;
7364 
7365 		data.chan = chan;
7366 		data.pid = chan->ops->get_peer_pid(chan);
7367 		data.count = 1;
7368 
7369 		l2cap_chan_list(conn, l2cap_chan_by_pid, &data);
7370 
7371 		/* Check if there isn't too many channels being connected */
7372 		if (data.count > L2CAP_ECRED_CONN_SCID_MAX) {
7373 			hci_conn_drop(hcon);
7374 			err = -EPROTO;
7375 			goto done;
7376 		}
7377 	}
7378 
7379 	mutex_lock(&conn->lock);
7380 	l2cap_chan_lock(chan);
7381 
7382 	if (cid && __l2cap_get_chan_by_dcid(conn, cid)) {
7383 		hci_conn_drop(hcon);
7384 		err = -EBUSY;
7385 		goto chan_unlock;
7386 	}
7387 
7388 	/* Update source addr of the socket */
7389 	bacpy(&chan->src, &hcon->src);
7390 	chan->src_type = bdaddr_src_type(hcon);
7391 
7392 	__l2cap_chan_add(conn, chan);
7393 
7394 	/* l2cap_chan_add takes its own ref so we can drop this one */
7395 	hci_conn_drop(hcon);
7396 
7397 	l2cap_state_change(chan, BT_CONNECT);
7398 	__set_chan_timer(chan, chan->ops->get_sndtimeo(chan));
7399 
7400 	/* Release chan->sport so that it can be reused by other
7401 	 * sockets (as it's only used for listening sockets).
7402 	 */
7403 	write_lock(&chan_list_lock);
7404 	chan->sport = 0;
7405 	write_unlock(&chan_list_lock);
7406 
7407 	if (hcon->state == BT_CONNECTED) {
7408 		if (chan->chan_type != L2CAP_CHAN_CONN_ORIENTED) {
7409 			__clear_chan_timer(chan);
7410 			if (l2cap_chan_check_security(chan, true))
7411 				l2cap_state_change(chan, BT_CONNECTED);
7412 		} else
7413 			l2cap_do_start(chan);
7414 	}
7415 
7416 	err = 0;
7417 
7418 chan_unlock:
7419 	l2cap_chan_unlock(chan);
7420 	mutex_unlock(&conn->lock);
7421 done:
7422 	hci_dev_unlock(hdev);
7423 	hci_dev_put(hdev);
7424 	return err;
7425 }
7426 EXPORT_SYMBOL_GPL(l2cap_chan_connect);
7427 
7428 static void l2cap_ecred_reconfigure(struct l2cap_chan *chan)
7429 {
7430 	struct l2cap_conn *conn = chan->conn;
7431 	DEFINE_RAW_FLEX(struct l2cap_ecred_reconf_req, pdu, scid, 1);
7432 
7433 	pdu->mtu = cpu_to_le16(chan->imtu);
7434 	pdu->mps = cpu_to_le16(chan->mps);
7435 	pdu->scid[0] = cpu_to_le16(chan->scid);
7436 
7437 	chan->ident = l2cap_get_ident(conn);
7438 
7439 	l2cap_send_cmd(conn, chan->ident, L2CAP_ECRED_RECONF_REQ,
7440 		       struct_size(pdu, scid, 1), pdu);
7441 }
7442 
7443 int l2cap_chan_reconfigure(struct l2cap_chan *chan, __u16 mtu)
7444 {
7445 	if (chan->imtu > mtu)
7446 		return -EINVAL;
7447 
7448 	BT_DBG("chan %p mtu 0x%4.4x", chan, mtu);
7449 
7450 	chan->imtu = mtu;
7451 
7452 	l2cap_ecred_reconfigure(chan);
7453 
7454 	return 0;
7455 }
7456 
7457 /* ---- L2CAP interface with lower layer (HCI) ---- */
7458 
7459 int l2cap_connect_ind(struct hci_dev *hdev, bdaddr_t *bdaddr)
7460 {
7461 	int exact = 0, lm1 = 0, lm2 = 0;
7462 	struct l2cap_chan *c;
7463 
7464 	BT_DBG("hdev %s, bdaddr %pMR", hdev->name, bdaddr);
7465 
7466 	/* Find listening sockets and check their link_mode */
7467 	read_lock(&chan_list_lock);
7468 	list_for_each_entry(c, &chan_list, global_l) {
7469 		if (c->state != BT_LISTEN)
7470 			continue;
7471 
7472 		if (!bacmp(&c->src, &hdev->bdaddr)) {
7473 			lm1 |= HCI_LM_ACCEPT;
7474 			if (test_bit(FLAG_ROLE_SWITCH, &c->flags))
7475 				lm1 |= HCI_LM_MASTER;
7476 			exact++;
7477 		} else if (!bacmp(&c->src, BDADDR_ANY)) {
7478 			lm2 |= HCI_LM_ACCEPT;
7479 			if (test_bit(FLAG_ROLE_SWITCH, &c->flags))
7480 				lm2 |= HCI_LM_MASTER;
7481 		}
7482 	}
7483 	read_unlock(&chan_list_lock);
7484 
7485 	return exact ? lm1 : lm2;
7486 }
7487 
7488 /* Find the next fixed channel in BT_LISTEN state, continue iteration
7489  * from an existing channel in the list or from the beginning of the
7490  * global list (by passing NULL as first parameter).
7491  */
7492 static struct l2cap_chan *l2cap_global_fixed_chan(struct l2cap_chan *c,
7493 						  struct hci_conn *hcon)
7494 {
7495 	u8 src_type = bdaddr_src_type(hcon);
7496 
7497 	read_lock(&chan_list_lock);
7498 
7499 	if (c)
7500 		c = list_next_entry(c, global_l);
7501 	else
7502 		c = list_entry(chan_list.next, typeof(*c), global_l);
7503 
7504 	list_for_each_entry_from(c, &chan_list, global_l) {
7505 		if (c->chan_type != L2CAP_CHAN_FIXED)
7506 			continue;
7507 		if (c->state != BT_LISTEN)
7508 			continue;
7509 		if (bacmp(&c->src, &hcon->src) && bacmp(&c->src, BDADDR_ANY))
7510 			continue;
7511 		if (src_type != c->src_type)
7512 			continue;
7513 
7514 		c = l2cap_chan_hold_unless_zero(c);
7515 		read_unlock(&chan_list_lock);
7516 		return c;
7517 	}
7518 
7519 	read_unlock(&chan_list_lock);
7520 
7521 	return NULL;
7522 }
7523 
7524 static void l2cap_connect_cfm(struct hci_conn *hcon, u8 status)
7525 {
7526 	struct hci_dev *hdev = hcon->hdev;
7527 	struct l2cap_conn *conn;
7528 	struct l2cap_chan *pchan;
7529 	u8 dst_type;
7530 
7531 	if (hcon->type != ACL_LINK && hcon->type != LE_LINK)
7532 		return;
7533 
7534 	BT_DBG("hcon %p bdaddr %pMR status %d", hcon, &hcon->dst, status);
7535 
7536 	if (status) {
7537 		l2cap_conn_del(hcon, bt_to_errno(status));
7538 		return;
7539 	}
7540 
7541 	conn = l2cap_conn_add(hcon);
7542 	if (!conn)
7543 		return;
7544 
7545 	dst_type = bdaddr_dst_type(hcon);
7546 
7547 	/* If device is blocked, do not create channels for it */
7548 	if (hci_bdaddr_list_lookup(&hdev->reject_list, &hcon->dst, dst_type))
7549 		return;
7550 
7551 	/* Find fixed channels and notify them of the new connection. We
7552 	 * use multiple individual lookups, continuing each time where
7553 	 * we left off, because the list lock would prevent calling the
7554 	 * potentially sleeping l2cap_chan_lock() function.
7555 	 */
7556 	pchan = l2cap_global_fixed_chan(NULL, hcon);
7557 	while (pchan) {
7558 		struct l2cap_chan *chan, *next;
7559 
7560 		/* Client fixed channels should override server ones */
7561 		if (__l2cap_get_chan_by_dcid(conn, pchan->scid))
7562 			goto next;
7563 
7564 		l2cap_chan_lock(pchan);
7565 		chan = l2cap_new_connection(conn, pchan);
7566 		if (chan) {
7567 			bacpy(&chan->src, &hcon->src);
7568 			bacpy(&chan->dst, &hcon->dst);
7569 			chan->src_type = bdaddr_src_type(hcon);
7570 			chan->dst_type = dst_type;
7571 		}
7572 
7573 		l2cap_chan_unlock(pchan);
7574 next:
7575 		next = l2cap_global_fixed_chan(pchan, hcon);
7576 		l2cap_chan_put(pchan);
7577 		pchan = next;
7578 	}
7579 
7580 	l2cap_conn_ready(conn);
7581 }
7582 
7583 int l2cap_disconn_ind(struct hci_conn *hcon)
7584 {
7585 	struct l2cap_conn *conn = hcon->l2cap_data;
7586 
7587 	BT_DBG("hcon %p", hcon);
7588 
7589 	if (!conn)
7590 		return HCI_ERROR_REMOTE_USER_TERM;
7591 	return conn->disc_reason;
7592 }
7593 
7594 static void l2cap_disconn_cfm(struct hci_conn *hcon, u8 reason)
7595 {
7596 	if (hcon->type != ACL_LINK && hcon->type != LE_LINK)
7597 		return;
7598 
7599 	BT_DBG("hcon %p reason %d", hcon, reason);
7600 
7601 	l2cap_conn_del(hcon, bt_to_errno(reason));
7602 }
7603 
7604 static inline void l2cap_check_encryption(struct l2cap_chan *chan, u8 encrypt)
7605 {
7606 	if (chan->chan_type != L2CAP_CHAN_CONN_ORIENTED)
7607 		return;
7608 
7609 	if (encrypt == 0x00) {
7610 		if (chan->sec_level == BT_SECURITY_MEDIUM) {
7611 			__set_chan_timer(chan, L2CAP_ENC_TIMEOUT);
7612 		} else if (chan->sec_level == BT_SECURITY_HIGH ||
7613 			   chan->sec_level == BT_SECURITY_FIPS)
7614 			l2cap_chan_close(chan, ECONNREFUSED);
7615 	} else {
7616 		if (chan->sec_level == BT_SECURITY_MEDIUM)
7617 			__clear_chan_timer(chan);
7618 	}
7619 }
7620 
7621 static void l2cap_security_cfm(struct hci_conn *hcon, u8 status, u8 encrypt)
7622 {
7623 	struct l2cap_conn *conn = hcon->l2cap_data;
7624 	struct l2cap_chan *chan;
7625 
7626 	if (!conn)
7627 		return;
7628 
7629 	BT_DBG("conn %p status 0x%2.2x encrypt %u", conn, status, encrypt);
7630 
7631 	mutex_lock(&conn->lock);
7632 
7633 	list_for_each_entry(chan, &conn->chan_l, list) {
7634 		l2cap_chan_lock(chan);
7635 
7636 		BT_DBG("chan %p scid 0x%4.4x state %s", chan, chan->scid,
7637 		       state_to_string(chan->state));
7638 
7639 		if (!status && encrypt)
7640 			chan->sec_level = hcon->sec_level;
7641 
7642 		if (!__l2cap_no_conn_pending(chan)) {
7643 			l2cap_chan_unlock(chan);
7644 			continue;
7645 		}
7646 
7647 		if (!status && (chan->state == BT_CONNECTED ||
7648 				chan->state == BT_CONFIG)) {
7649 			chan->ops->resume(chan);
7650 			l2cap_check_encryption(chan, encrypt);
7651 			l2cap_chan_unlock(chan);
7652 			continue;
7653 		}
7654 
7655 		if (chan->state == BT_CONNECT) {
7656 			if (!status && l2cap_check_enc_key_size(hcon, chan))
7657 				l2cap_start_connection(chan);
7658 			else
7659 				__set_chan_timer(chan, L2CAP_DISC_TIMEOUT);
7660 		} else if (chan->state == BT_CONNECT2 &&
7661 			   !(chan->mode == L2CAP_MODE_EXT_FLOWCTL ||
7662 			     chan->mode == L2CAP_MODE_LE_FLOWCTL)) {
7663 			struct l2cap_conn_rsp rsp;
7664 			__u16 res, stat;
7665 
7666 			if (!status && l2cap_check_enc_key_size(hcon, chan)) {
7667 				if (test_bit(FLAG_DEFER_SETUP, &chan->flags)) {
7668 					res = L2CAP_CR_PEND;
7669 					stat = L2CAP_CS_AUTHOR_PEND;
7670 					chan->ops->defer(chan);
7671 				} else {
7672 					l2cap_state_change(chan, BT_CONFIG);
7673 					res = L2CAP_CR_SUCCESS;
7674 					stat = L2CAP_CS_NO_INFO;
7675 				}
7676 			} else {
7677 				l2cap_state_change(chan, BT_DISCONN);
7678 				__set_chan_timer(chan, L2CAP_DISC_TIMEOUT);
7679 				res = L2CAP_CR_SEC_BLOCK;
7680 				stat = L2CAP_CS_NO_INFO;
7681 			}
7682 
7683 			rsp.scid   = cpu_to_le16(chan->dcid);
7684 			rsp.dcid   = cpu_to_le16(chan->scid);
7685 			rsp.result = cpu_to_le16(res);
7686 			rsp.status = cpu_to_le16(stat);
7687 			l2cap_send_cmd(conn, chan->ident, L2CAP_CONN_RSP,
7688 				       sizeof(rsp), &rsp);
7689 
7690 			if (!test_bit(CONF_REQ_SENT, &chan->conf_state) &&
7691 			    res == L2CAP_CR_SUCCESS) {
7692 				char buf[128];
7693 				set_bit(CONF_REQ_SENT, &chan->conf_state);
7694 				l2cap_send_cmd(conn, l2cap_get_ident(conn),
7695 					       L2CAP_CONF_REQ,
7696 					       l2cap_build_conf_req(chan, buf, sizeof(buf)),
7697 					       buf);
7698 				chan->num_conf_req++;
7699 			}
7700 		}
7701 
7702 		l2cap_chan_unlock(chan);
7703 	}
7704 
7705 	mutex_unlock(&conn->lock);
7706 }
7707 
7708 /* Append fragment into frame respecting the maximum len of rx_skb */
7709 static int l2cap_recv_frag(struct l2cap_conn *conn, struct sk_buff *skb,
7710 			   u16 len)
7711 {
7712 	if (!conn->rx_skb) {
7713 		/* Allocate skb for the complete frame (with header) */
7714 		conn->rx_skb = bt_skb_alloc(len, GFP_KERNEL);
7715 		if (!conn->rx_skb)
7716 			return -ENOMEM;
7717 		/* Init rx_len */
7718 		conn->rx_len = len;
7719 
7720 		skb_set_delivery_time(conn->rx_skb, skb->tstamp,
7721 				      skb->tstamp_type);
7722 	}
7723 
7724 	/* Copy as much as the rx_skb can hold */
7725 	len = min_t(u16, len, skb->len);
7726 	skb_copy_from_linear_data(skb, skb_put(conn->rx_skb, len), len);
7727 	skb_pull(skb, len);
7728 	conn->rx_len -= len;
7729 
7730 	return len;
7731 }
7732 
7733 static int l2cap_recv_len(struct l2cap_conn *conn, struct sk_buff *skb)
7734 {
7735 	struct sk_buff *rx_skb;
7736 	int len;
7737 
7738 	/* Append just enough to complete the header */
7739 	len = l2cap_recv_frag(conn, skb, L2CAP_LEN_SIZE - conn->rx_skb->len);
7740 
7741 	/* If header could not be read just continue */
7742 	if (len < 0 || conn->rx_skb->len < L2CAP_LEN_SIZE)
7743 		return len;
7744 
7745 	rx_skb = conn->rx_skb;
7746 	len = get_unaligned_le16(rx_skb->data);
7747 
7748 	/* Check if rx_skb has enough space to received all fragments */
7749 	if (len + (L2CAP_HDR_SIZE - L2CAP_LEN_SIZE) <= skb_tailroom(rx_skb)) {
7750 		/* Update expected len */
7751 		conn->rx_len = len + (L2CAP_HDR_SIZE - L2CAP_LEN_SIZE);
7752 		return L2CAP_LEN_SIZE;
7753 	}
7754 
7755 	/* Reset conn->rx_skb since it will need to be reallocated in order to
7756 	 * fit all fragments.
7757 	 */
7758 	conn->rx_skb = NULL;
7759 
7760 	/* Reallocates rx_skb using the exact expected length */
7761 	len = l2cap_recv_frag(conn, rx_skb,
7762 			      len + (L2CAP_HDR_SIZE - L2CAP_LEN_SIZE));
7763 	kfree_skb(rx_skb);
7764 
7765 	return len;
7766 }
7767 
7768 static void l2cap_recv_reset(struct l2cap_conn *conn)
7769 {
7770 	kfree_skb(conn->rx_skb);
7771 	conn->rx_skb = NULL;
7772 	conn->rx_len = 0;
7773 }
7774 
7775 struct l2cap_conn *l2cap_conn_hold_unless_zero(struct l2cap_conn *c)
7776 {
7777 	if (!c)
7778 		return NULL;
7779 
7780 	BT_DBG("conn %p orig refcnt %u", c, kref_read(&c->ref));
7781 
7782 	if (!kref_get_unless_zero(&c->ref))
7783 		return NULL;
7784 
7785 	return c;
7786 }
7787 EXPORT_SYMBOL(l2cap_conn_hold_unless_zero);
7788 
7789 int l2cap_recv_acldata(struct hci_dev *hdev, u16 handle,
7790 		       struct sk_buff *skb, u16 flags)
7791 {
7792 	struct hci_conn *hcon;
7793 	struct l2cap_conn *conn;
7794 	int len;
7795 
7796 	/* Lock hdev for hci_conn, and race on l2cap_data vs. l2cap_conn_del */
7797 	hci_dev_lock(hdev);
7798 
7799 	hcon = hci_conn_hash_lookup_handle(hdev, handle);
7800 	if (!hcon) {
7801 		hci_dev_unlock(hdev);
7802 		kfree_skb(skb);
7803 		return -ENOENT;
7804 	}
7805 
7806 	hci_conn_enter_active_mode(hcon, BT_POWER_FORCE_ACTIVE_OFF);
7807 
7808 	conn = hcon->l2cap_data;
7809 
7810 	if (!conn)
7811 		conn = l2cap_conn_add(hcon);
7812 
7813 	conn = l2cap_conn_hold_unless_zero(conn);
7814 	hcon = NULL;
7815 
7816 	hci_dev_unlock(hdev);
7817 
7818 	if (!conn) {
7819 		kfree_skb(skb);
7820 		return -EINVAL;
7821 	}
7822 
7823 	BT_DBG("conn %p len %u flags 0x%x", conn, skb->len, flags);
7824 
7825 	mutex_lock(&conn->lock);
7826 
7827 	switch (flags) {
7828 	case ACL_START:
7829 	case ACL_START_NO_FLUSH:
7830 	case ACL_COMPLETE:
7831 		if (conn->rx_skb) {
7832 			BT_ERR("Unexpected start frame (len %d)", skb->len);
7833 			l2cap_recv_reset(conn);
7834 			l2cap_conn_unreliable(conn, ECOMM);
7835 		}
7836 
7837 		/* Start fragment may not contain the L2CAP length so just
7838 		 * copy the initial byte when that happens and use conn->mtu as
7839 		 * expected length.
7840 		 */
7841 		if (skb->len < L2CAP_LEN_SIZE) {
7842 			l2cap_recv_frag(conn, skb, conn->mtu);
7843 			break;
7844 		}
7845 
7846 		len = get_unaligned_le16(skb->data) + L2CAP_HDR_SIZE;
7847 
7848 		if (len == skb->len) {
7849 			/* Complete frame received */
7850 			l2cap_recv_frame(conn, skb);
7851 			goto unlock;
7852 		}
7853 
7854 		BT_DBG("Start: total len %d, frag len %u", len, skb->len);
7855 
7856 		if (skb->len > len) {
7857 			BT_ERR("Frame is too long (len %u, expected len %d)",
7858 			       skb->len, len);
7859 			/* PTS test cases L2CAP/COS/CED/BI-14-C and BI-15-C
7860 			 * (Multiple Signaling Command in one PDU, Data
7861 			 * Truncated, BR/EDR) send a C-frame to the IUT with
7862 			 * PDU Length set to 8 and Channel ID set to the
7863 			 * correct signaling channel for the logical link.
7864 			 * The Information payload contains one L2CAP_ECHO_REQ
7865 			 * packet with Data Length set to 0 with 0 octets of
7866 			 * echo data and one invalid command packet due to
7867 			 * data truncated in PDU but present in HCI packet.
7868 			 *
7869 			 * Shorter the socket buffer to the PDU length to
7870 			 * allow to process valid commands from the PDU before
7871 			 * setting the socket unreliable.
7872 			 */
7873 			skb->len = len;
7874 			l2cap_recv_frame(conn, skb);
7875 			l2cap_conn_unreliable(conn, ECOMM);
7876 			goto unlock;
7877 		}
7878 
7879 		/* Append fragment into frame (with header) */
7880 		if (l2cap_recv_frag(conn, skb, len) < 0)
7881 			goto drop;
7882 
7883 		break;
7884 
7885 	case ACL_CONT:
7886 		BT_DBG("Cont: frag len %u (expecting %u)", skb->len, conn->rx_len);
7887 
7888 		if (!conn->rx_skb) {
7889 			BT_ERR("Unexpected continuation frame (len %d)", skb->len);
7890 			l2cap_conn_unreliable(conn, ECOMM);
7891 			goto drop;
7892 		}
7893 
7894 		/* Complete the L2CAP length if it has not been read */
7895 		if (conn->rx_skb->len < L2CAP_LEN_SIZE) {
7896 			if (l2cap_recv_len(conn, skb) < 0) {
7897 				l2cap_conn_unreliable(conn, ECOMM);
7898 				goto drop;
7899 			}
7900 
7901 			/* Header still could not be read just continue */
7902 			if (conn->rx_skb->len < L2CAP_LEN_SIZE)
7903 				break;
7904 		}
7905 
7906 		if (skb->len > conn->rx_len) {
7907 			BT_ERR("Fragment is too long (len %u, expected %u)",
7908 			       skb->len, conn->rx_len);
7909 			l2cap_recv_reset(conn);
7910 			l2cap_conn_unreliable(conn, ECOMM);
7911 			goto drop;
7912 		}
7913 
7914 		/* Append fragment into frame (with header) */
7915 		l2cap_recv_frag(conn, skb, skb->len);
7916 
7917 		if (!conn->rx_len) {
7918 			/* Complete frame received. l2cap_recv_frame
7919 			 * takes ownership of the skb so set the global
7920 			 * rx_skb pointer to NULL first.
7921 			 */
7922 			struct sk_buff *rx_skb = conn->rx_skb;
7923 			conn->rx_skb = NULL;
7924 			l2cap_recv_frame(conn, rx_skb);
7925 		}
7926 		break;
7927 	}
7928 
7929 drop:
7930 	kfree_skb(skb);
7931 unlock:
7932 	mutex_unlock(&conn->lock);
7933 	l2cap_conn_put(conn);
7934 	return 0;
7935 }
7936 
7937 static struct hci_cb l2cap_cb = {
7938 	.name		= "L2CAP",
7939 	.connect_cfm	= l2cap_connect_cfm,
7940 	.disconn_cfm	= l2cap_disconn_cfm,
7941 	.security_cfm	= l2cap_security_cfm,
7942 };
7943 
7944 static int l2cap_debugfs_show(struct seq_file *f, void *p)
7945 {
7946 	struct l2cap_chan *c;
7947 
7948 	read_lock(&chan_list_lock);
7949 
7950 	list_for_each_entry(c, &chan_list, global_l) {
7951 		seq_printf(f, "%pMR (%u) %pMR (%u) %d %d 0x%4.4x 0x%4.4x %d %d %d %d\n",
7952 			   &c->src, c->src_type, &c->dst, c->dst_type,
7953 			   c->state, __le16_to_cpu(c->psm),
7954 			   c->scid, c->dcid, c->imtu, c->omtu,
7955 			   c->sec_level, c->mode);
7956 	}
7957 
7958 	read_unlock(&chan_list_lock);
7959 
7960 	return 0;
7961 }
7962 
7963 DEFINE_SHOW_ATTRIBUTE(l2cap_debugfs);
7964 
7965 static struct dentry *l2cap_debugfs;
7966 
7967 int __init l2cap_init(void)
7968 {
7969 	int err;
7970 
7971 	err = l2cap_init_sockets();
7972 	if (err < 0)
7973 		return err;
7974 
7975 	hci_register_cb(&l2cap_cb);
7976 
7977 	if (IS_ERR_OR_NULL(bt_debugfs))
7978 		return 0;
7979 
7980 	l2cap_debugfs = debugfs_create_file("l2cap", 0444, bt_debugfs,
7981 					    NULL, &l2cap_debugfs_fops);
7982 
7983 	return 0;
7984 }
7985 
7986 void l2cap_exit(void)
7987 {
7988 	debugfs_remove(l2cap_debugfs);
7989 	hci_unregister_cb(&l2cap_cb);
7990 	l2cap_cleanup_sockets();
7991 }
7992 
7993 module_param(disable_ertm, bool, 0644);
7994 MODULE_PARM_DESC(disable_ertm, "Disable enhanced retransmission mode");
7995 
7996 module_param(enable_ecred, bool, 0644);
7997 MODULE_PARM_DESC(enable_ecred, "Enable enhanced credit flow control mode");
7998