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