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