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