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