linux/net/bluetooth/l2cap_core.c
<<
>>
Prefs
   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#include "a2mp.h"
  43#include "amp.h"
  44
  45#define LE_FLOWCTL_MAX_CREDITS 65535
  46
  47bool disable_ertm;
  48bool enable_ecred;
  49
  50static u32 l2cap_feat_mask = L2CAP_FEAT_FIXED_CHAN | L2CAP_FEAT_UCD;
  51
  52static LIST_HEAD(chan_list);
  53static DEFINE_RWLOCK(chan_list_lock);
  54
  55static struct sk_buff *l2cap_build_cmd(struct l2cap_conn *conn,
  56                                       u8 code, u8 ident, u16 dlen, void *data);
  57static void l2cap_send_cmd(struct l2cap_conn *conn, u8 ident, u8 code, u16 len,
  58                           void *data);
  59static int l2cap_build_conf_req(struct l2cap_chan *chan, void *data, size_t data_size);
  60static void l2cap_send_disconn_req(struct l2cap_chan *chan, int err);
  61
  62static void l2cap_tx(struct l2cap_chan *chan, struct l2cap_ctrl *control,
  63                     struct sk_buff_head *skbs, u8 event);
  64
  65static inline u8 bdaddr_type(u8 link_type, u8 bdaddr_type)
  66{
  67        if (link_type == LE_LINK) {
  68                if (bdaddr_type == ADDR_LE_DEV_PUBLIC)
  69                        return BDADDR_LE_PUBLIC;
  70                else
  71                        return BDADDR_LE_RANDOM;
  72        }
  73
  74        return BDADDR_BREDR;
  75}
  76
  77static inline u8 bdaddr_src_type(struct hci_conn *hcon)
  78{
  79        return bdaddr_type(hcon->type, hcon->src_type);
  80}
  81
  82static inline u8 bdaddr_dst_type(struct hci_conn *hcon)
  83{
  84        return bdaddr_type(hcon->type, hcon->dst_type);
  85}
  86
  87/* ---- L2CAP channels ---- */
  88
  89static struct l2cap_chan *__l2cap_get_chan_by_dcid(struct l2cap_conn *conn,
  90                                                   u16 cid)
  91{
  92        struct l2cap_chan *c;
  93
  94        list_for_each_entry(c, &conn->chan_l, list) {
  95                if (c->dcid == cid)
  96                        return c;
  97        }
  98        return NULL;
  99}
 100
 101static struct l2cap_chan *__l2cap_get_chan_by_scid(struct l2cap_conn *conn,
 102                                                   u16 cid)
 103{
 104        struct l2cap_chan *c;
 105
 106        list_for_each_entry(c, &conn->chan_l, list) {
 107                if (c->scid == cid)
 108                        return c;
 109        }
 110        return NULL;
 111}
 112
 113/* Find channel with given SCID.
 114 * Returns locked channel. */
 115static struct l2cap_chan *l2cap_get_chan_by_scid(struct l2cap_conn *conn,
 116                                                 u16 cid)
 117{
 118        struct l2cap_chan *c;
 119
 120        mutex_lock(&conn->chan_lock);
 121        c = __l2cap_get_chan_by_scid(conn, cid);
 122        if (c)
 123                l2cap_chan_lock(c);
 124        mutex_unlock(&conn->chan_lock);
 125
 126        return c;
 127}
 128
 129/* Find channel with given DCID.
 130 * Returns locked channel.
 131 */
 132static struct l2cap_chan *l2cap_get_chan_by_dcid(struct l2cap_conn *conn,
 133                                                 u16 cid)
 134{
 135        struct l2cap_chan *c;
 136
 137        mutex_lock(&conn->chan_lock);
 138        c = __l2cap_get_chan_by_dcid(conn, cid);
 139        if (c)
 140                l2cap_chan_lock(c);
 141        mutex_unlock(&conn->chan_lock);
 142
 143        return c;
 144}
 145
 146static struct l2cap_chan *__l2cap_get_chan_by_ident(struct l2cap_conn *conn,
 147                                                    u8 ident)
 148{
 149        struct l2cap_chan *c;
 150
 151        list_for_each_entry(c, &conn->chan_l, list) {
 152                if (c->ident == ident)
 153                        return c;
 154        }
 155        return NULL;
 156}
 157
 158static struct l2cap_chan *l2cap_get_chan_by_ident(struct l2cap_conn *conn,
 159                                                  u8 ident)
 160{
 161        struct l2cap_chan *c;
 162
 163        mutex_lock(&conn->chan_lock);
 164        c = __l2cap_get_chan_by_ident(conn, ident);
 165        if (c)
 166                l2cap_chan_lock(c);
 167        mutex_unlock(&conn->chan_lock);
 168
 169        return c;
 170}
 171
 172static struct l2cap_chan *__l2cap_global_chan_by_addr(__le16 psm, bdaddr_t *src,
 173                                                      u8 src_type)
 174{
 175        struct l2cap_chan *c;
 176
 177        list_for_each_entry(c, &chan_list, global_l) {
 178                if (src_type == BDADDR_BREDR && c->src_type != BDADDR_BREDR)
 179                        continue;
 180
 181                if (src_type != BDADDR_BREDR && c->src_type == BDADDR_BREDR)
 182                        continue;
 183
 184                if (c->sport == psm && !bacmp(&c->src, src))
 185                        return c;
 186        }
 187        return NULL;
 188}
 189
 190int l2cap_add_psm(struct l2cap_chan *chan, bdaddr_t *src, __le16 psm)
 191{
 192        int err;
 193
 194        write_lock(&chan_list_lock);
 195
 196        if (psm && __l2cap_global_chan_by_addr(psm, src, chan->src_type)) {
 197                err = -EADDRINUSE;
 198                goto done;
 199        }
 200
 201        if (psm) {
 202                chan->psm = psm;
 203                chan->sport = psm;
 204                err = 0;
 205        } else {
 206                u16 p, start, end, incr;
 207
 208                if (chan->src_type == BDADDR_BREDR) {
 209                        start = L2CAP_PSM_DYN_START;
 210                        end = L2CAP_PSM_AUTO_END;
 211                        incr = 2;
 212                } else {
 213                        start = L2CAP_PSM_LE_DYN_START;
 214                        end = L2CAP_PSM_LE_DYN_END;
 215                        incr = 1;
 216                }
 217
 218                err = -EINVAL;
 219                for (p = start; p <= end; p += incr)
 220                        if (!__l2cap_global_chan_by_addr(cpu_to_le16(p), src,
 221                                                         chan->src_type)) {
 222                                chan->psm   = cpu_to_le16(p);
 223                                chan->sport = cpu_to_le16(p);
 224                                err = 0;
 225                                break;
 226                        }
 227        }
 228
 229done:
 230        write_unlock(&chan_list_lock);
 231        return err;
 232}
 233EXPORT_SYMBOL_GPL(l2cap_add_psm);
 234
 235int l2cap_add_scid(struct l2cap_chan *chan,  __u16 scid)
 236{
 237        write_lock(&chan_list_lock);
 238
 239        /* Override the defaults (which are for conn-oriented) */
 240        chan->omtu = L2CAP_DEFAULT_MTU;
 241        chan->chan_type = L2CAP_CHAN_FIXED;
 242
 243        chan->scid = scid;
 244
 245        write_unlock(&chan_list_lock);
 246
 247        return 0;
 248}
 249
 250static u16 l2cap_alloc_cid(struct l2cap_conn *conn)
 251{
 252        u16 cid, dyn_end;
 253
 254        if (conn->hcon->type == LE_LINK)
 255                dyn_end = L2CAP_CID_LE_DYN_END;
 256        else
 257                dyn_end = L2CAP_CID_DYN_END;
 258
 259        for (cid = L2CAP_CID_DYN_START; cid <= dyn_end; cid++) {
 260                if (!__l2cap_get_chan_by_scid(conn, cid))
 261                        return cid;
 262        }
 263
 264        return 0;
 265}
 266
 267static void l2cap_state_change(struct l2cap_chan *chan, int state)
 268{
 269        BT_DBG("chan %p %s -> %s", chan, state_to_string(chan->state),
 270               state_to_string(state));
 271
 272        chan->state = state;
 273        chan->ops->state_change(chan, state, 0);
 274}
 275
 276static inline void l2cap_state_change_and_error(struct l2cap_chan *chan,
 277                                                int state, int err)
 278{
 279        chan->state = state;
 280        chan->ops->state_change(chan, chan->state, err);
 281}
 282
 283static inline void l2cap_chan_set_err(struct l2cap_chan *chan, int err)
 284{
 285        chan->ops->state_change(chan, chan->state, err);
 286}
 287
 288static void __set_retrans_timer(struct l2cap_chan *chan)
 289{
 290        if (!delayed_work_pending(&chan->monitor_timer) &&
 291            chan->retrans_timeout) {
 292                l2cap_set_timer(chan, &chan->retrans_timer,
 293                                msecs_to_jiffies(chan->retrans_timeout));
 294        }
 295}
 296
 297static void __set_monitor_timer(struct l2cap_chan *chan)
 298{
 299        __clear_retrans_timer(chan);
 300        if (chan->monitor_timeout) {
 301                l2cap_set_timer(chan, &chan->monitor_timer,
 302                                msecs_to_jiffies(chan->monitor_timeout));
 303        }
 304}
 305
 306static struct sk_buff *l2cap_ertm_seq_in_queue(struct sk_buff_head *head,
 307                                               u16 seq)
 308{
 309        struct sk_buff *skb;
 310
 311        skb_queue_walk(head, skb) {
 312                if (bt_cb(skb)->l2cap.txseq == seq)
 313                        return skb;
 314        }
 315
 316        return NULL;
 317}
 318
 319/* ---- L2CAP sequence number lists ---- */
 320
 321/* For ERTM, ordered lists of sequence numbers must be tracked for
 322 * SREJ requests that are received and for frames that are to be
 323 * retransmitted. These seq_list functions implement a singly-linked
 324 * list in an array, where membership in the list can also be checked
 325 * in constant time. Items can also be added to the tail of the list
 326 * and removed from the head in constant time, without further memory
 327 * allocs or frees.
 328 */
 329
 330static int l2cap_seq_list_init(struct l2cap_seq_list *seq_list, u16 size)
 331{
 332        size_t alloc_size, i;
 333
 334        /* Allocated size is a power of 2 to map sequence numbers
 335         * (which may be up to 14 bits) in to a smaller array that is
 336         * sized for the negotiated ERTM transmit windows.
 337         */
 338        alloc_size = roundup_pow_of_two(size);
 339
 340        seq_list->list = kmalloc_array(alloc_size, sizeof(u16), GFP_KERNEL);
 341        if (!seq_list->list)
 342                return -ENOMEM;
 343
 344        seq_list->mask = alloc_size - 1;
 345        seq_list->head = L2CAP_SEQ_LIST_CLEAR;
 346        seq_list->tail = L2CAP_SEQ_LIST_CLEAR;
 347        for (i = 0; i < alloc_size; i++)
 348                seq_list->list[i] = L2CAP_SEQ_LIST_CLEAR;
 349
 350        return 0;
 351}
 352
 353static inline void l2cap_seq_list_free(struct l2cap_seq_list *seq_list)
 354{
 355        kfree(seq_list->list);
 356}
 357
 358static inline bool l2cap_seq_list_contains(struct l2cap_seq_list *seq_list,
 359                                           u16 seq)
 360{
 361        /* Constant-time check for list membership */
 362        return seq_list->list[seq & seq_list->mask] != L2CAP_SEQ_LIST_CLEAR;
 363}
 364
 365static inline u16 l2cap_seq_list_pop(struct l2cap_seq_list *seq_list)
 366{
 367        u16 seq = seq_list->head;
 368        u16 mask = seq_list->mask;
 369
 370        seq_list->head = seq_list->list[seq & mask];
 371        seq_list->list[seq & mask] = L2CAP_SEQ_LIST_CLEAR;
 372
 373        if (seq_list->head == L2CAP_SEQ_LIST_TAIL) {
 374                seq_list->head = L2CAP_SEQ_LIST_CLEAR;
 375                seq_list->tail = L2CAP_SEQ_LIST_CLEAR;
 376        }
 377
 378        return seq;
 379}
 380
 381static void l2cap_seq_list_clear(struct l2cap_seq_list *seq_list)
 382{
 383        u16 i;
 384
 385        if (seq_list->head == L2CAP_SEQ_LIST_CLEAR)
 386                return;
 387
 388        for (i = 0; i <= seq_list->mask; i++)
 389                seq_list->list[i] = L2CAP_SEQ_LIST_CLEAR;
 390
 391        seq_list->head = L2CAP_SEQ_LIST_CLEAR;
 392        seq_list->tail = L2CAP_SEQ_LIST_CLEAR;
 393}
 394
 395static void l2cap_seq_list_append(struct l2cap_seq_list *seq_list, u16 seq)
 396{
 397        u16 mask = seq_list->mask;
 398
 399        /* All appends happen in constant time */
 400
 401        if (seq_list->list[seq & mask] != L2CAP_SEQ_LIST_CLEAR)
 402                return;
 403
 404        if (seq_list->tail == L2CAP_SEQ_LIST_CLEAR)
 405                seq_list->head = seq;
 406        else
 407                seq_list->list[seq_list->tail & mask] = seq;
 408
 409        seq_list->tail = seq;
 410        seq_list->list[seq & mask] = L2CAP_SEQ_LIST_TAIL;
 411}
 412
 413static void l2cap_chan_timeout(struct work_struct *work)
 414{
 415        struct l2cap_chan *chan = container_of(work, struct l2cap_chan,
 416                                               chan_timer.work);
 417        struct l2cap_conn *conn = chan->conn;
 418        int reason;
 419
 420        BT_DBG("chan %p state %s", chan, state_to_string(chan->state));
 421
 422        mutex_lock(&conn->chan_lock);
 423        /* __set_chan_timer() calls l2cap_chan_hold(chan) while scheduling
 424         * this work. No need to call l2cap_chan_hold(chan) here again.
 425         */
 426        l2cap_chan_lock(chan);
 427
 428        if (chan->state == BT_CONNECTED || chan->state == BT_CONFIG)
 429                reason = ECONNREFUSED;
 430        else if (chan->state == BT_CONNECT &&
 431                 chan->sec_level != BT_SECURITY_SDP)
 432                reason = ECONNREFUSED;
 433        else
 434                reason = ETIMEDOUT;
 435
 436        l2cap_chan_close(chan, reason);
 437
 438        chan->ops->close(chan);
 439
 440        l2cap_chan_unlock(chan);
 441        l2cap_chan_put(chan);
 442
 443        mutex_unlock(&conn->chan_lock);
 444}
 445
 446struct l2cap_chan *l2cap_chan_create(void)
 447{
 448        struct l2cap_chan *chan;
 449
 450        chan = kzalloc(sizeof(*chan), GFP_ATOMIC);
 451        if (!chan)
 452                return NULL;
 453
 454        skb_queue_head_init(&chan->tx_q);
 455        skb_queue_head_init(&chan->srej_q);
 456        mutex_init(&chan->lock);
 457
 458        /* Set default lock nesting level */
 459        atomic_set(&chan->nesting, L2CAP_NESTING_NORMAL);
 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
 467        chan->state = BT_OPEN;
 468
 469        kref_init(&chan->kref);
 470
 471        /* This flag is cleared in l2cap_chan_ready() */
 472        set_bit(CONF_NOT_COMPLETE, &chan->conf_state);
 473
 474        BT_DBG("chan %p", chan);
 475
 476        return chan;
 477}
 478EXPORT_SYMBOL_GPL(l2cap_chan_create);
 479
 480static void l2cap_chan_destroy(struct kref *kref)
 481{
 482        struct l2cap_chan *chan = container_of(kref, struct l2cap_chan, kref);
 483
 484        BT_DBG("chan %p", chan);
 485
 486        write_lock(&chan_list_lock);
 487        list_del(&chan->global_l);
 488        write_unlock(&chan_list_lock);
 489
 490        kfree(chan);
 491}
 492
 493void l2cap_chan_hold(struct l2cap_chan *c)
 494{
 495        BT_DBG("chan %p orig refcnt %u", c, kref_read(&c->kref));
 496
 497        kref_get(&c->kref);
 498}
 499
 500void l2cap_chan_put(struct l2cap_chan *c)
 501{
 502        BT_DBG("chan %p orig refcnt %u", c, kref_read(&c->kref));
 503
 504        kref_put(&c->kref, l2cap_chan_destroy);
 505}
 506EXPORT_SYMBOL_GPL(l2cap_chan_put);
 507
 508void l2cap_chan_set_defaults(struct l2cap_chan *chan)
 509{
 510        chan->fcs  = L2CAP_FCS_CRC16;
 511        chan->max_tx = L2CAP_DEFAULT_MAX_TX;
 512        chan->tx_win = L2CAP_DEFAULT_TX_WINDOW;
 513        chan->tx_win_max = L2CAP_DEFAULT_TX_WINDOW;
 514        chan->remote_max_tx = chan->max_tx;
 515        chan->remote_tx_win = chan->tx_win;
 516        chan->ack_win = L2CAP_DEFAULT_TX_WINDOW;
 517        chan->sec_level = BT_SECURITY_LOW;
 518        chan->flush_to = L2CAP_DEFAULT_FLUSH_TO;
 519        chan->retrans_timeout = L2CAP_DEFAULT_RETRANS_TO;
 520        chan->monitor_timeout = L2CAP_DEFAULT_MONITOR_TO;
 521
 522        chan->conf_state = 0;
 523        set_bit(CONF_NOT_COMPLETE, &chan->conf_state);
 524
 525        set_bit(FLAG_FORCE_ACTIVE, &chan->flags);
 526}
 527EXPORT_SYMBOL_GPL(l2cap_chan_set_defaults);
 528
 529static void l2cap_le_flowctl_init(struct l2cap_chan *chan, u16 tx_credits)
 530{
 531        chan->sdu = NULL;
 532        chan->sdu_last_frag = NULL;
 533        chan->sdu_len = 0;
 534        chan->tx_credits = tx_credits;
 535        /* Derive MPS from connection MTU to stop HCI fragmentation */
 536        chan->mps = min_t(u16, chan->imtu, chan->conn->mtu - L2CAP_HDR_SIZE);
 537        /* Give enough credits for a full packet */
 538        chan->rx_credits = (chan->imtu / chan->mps) + 1;
 539
 540        skb_queue_head_init(&chan->tx_q);
 541}
 542
 543static void l2cap_ecred_init(struct l2cap_chan *chan, u16 tx_credits)
 544{
 545        l2cap_le_flowctl_init(chan, tx_credits);
 546
 547        /* L2CAP implementations shall support a minimum MPS of 64 octets */
 548        if (chan->mps < L2CAP_ECRED_MIN_MPS) {
 549                chan->mps = L2CAP_ECRED_MIN_MPS;
 550                chan->rx_credits = (chan->imtu / chan->mps) + 1;
 551        }
 552}
 553
 554void __l2cap_chan_add(struct l2cap_conn *conn, struct l2cap_chan *chan)
 555{
 556        BT_DBG("conn %p, psm 0x%2.2x, dcid 0x%4.4x", conn,
 557               __le16_to_cpu(chan->psm), chan->dcid);
 558
 559        conn->disc_reason = HCI_ERROR_REMOTE_USER_TERM;
 560
 561        chan->conn = conn;
 562
 563        switch (chan->chan_type) {
 564        case L2CAP_CHAN_CONN_ORIENTED:
 565                /* Alloc CID for connection-oriented socket */
 566                chan->scid = l2cap_alloc_cid(conn);
 567                if (conn->hcon->type == ACL_LINK)
 568                        chan->omtu = L2CAP_DEFAULT_MTU;
 569                break;
 570
 571        case L2CAP_CHAN_CONN_LESS:
 572                /* Connectionless socket */
 573                chan->scid = L2CAP_CID_CONN_LESS;
 574                chan->dcid = L2CAP_CID_CONN_LESS;
 575                chan->omtu = L2CAP_DEFAULT_MTU;
 576                break;
 577
 578        case L2CAP_CHAN_FIXED:
 579                /* Caller will set CID and CID specific MTU values */
 580                break;
 581
 582        default:
 583                /* Raw socket can send/recv signalling messages only */
 584                chan->scid = L2CAP_CID_SIGNALING;
 585                chan->dcid = L2CAP_CID_SIGNALING;
 586                chan->omtu = L2CAP_DEFAULT_MTU;
 587        }
 588
 589        chan->local_id          = L2CAP_BESTEFFORT_ID;
 590        chan->local_stype       = L2CAP_SERV_BESTEFFORT;
 591        chan->local_msdu        = L2CAP_DEFAULT_MAX_SDU_SIZE;
 592        chan->local_sdu_itime   = L2CAP_DEFAULT_SDU_ITIME;
 593        chan->local_acc_lat     = L2CAP_DEFAULT_ACC_LAT;
 594        chan->local_flush_to    = L2CAP_EFS_DEFAULT_FLUSH_TO;
 595
 596        l2cap_chan_hold(chan);
 597
 598        /* Only keep a reference for fixed channels if they requested it */
 599        if (chan->chan_type != L2CAP_CHAN_FIXED ||
 600            test_bit(FLAG_HOLD_HCI_CONN, &chan->flags))
 601                hci_conn_hold(conn->hcon);
 602
 603        list_add(&chan->list, &conn->chan_l);
 604}
 605
 606void l2cap_chan_add(struct l2cap_conn *conn, struct l2cap_chan *chan)
 607{
 608        mutex_lock(&conn->chan_lock);
 609        __l2cap_chan_add(conn, chan);
 610        mutex_unlock(&conn->chan_lock);
 611}
 612
 613void l2cap_chan_del(struct l2cap_chan *chan, int err)
 614{
 615        struct l2cap_conn *conn = chan->conn;
 616
 617        __clear_chan_timer(chan);
 618
 619        BT_DBG("chan %p, conn %p, err %d, state %s", chan, conn, err,
 620               state_to_string(chan->state));
 621
 622        chan->ops->teardown(chan, err);
 623
 624        if (conn) {
 625                struct amp_mgr *mgr = conn->hcon->amp_mgr;
 626                /* Delete from channel list */
 627                list_del(&chan->list);
 628
 629                l2cap_chan_put(chan);
 630
 631                chan->conn = NULL;
 632
 633                /* Reference was only held for non-fixed channels or
 634                 * fixed channels that explicitly requested it using the
 635                 * FLAG_HOLD_HCI_CONN flag.
 636                 */
 637                if (chan->chan_type != L2CAP_CHAN_FIXED ||
 638                    test_bit(FLAG_HOLD_HCI_CONN, &chan->flags))
 639                        hci_conn_drop(conn->hcon);
 640
 641                if (mgr && mgr->bredr_chan == chan)
 642                        mgr->bredr_chan = NULL;
 643        }
 644
 645        if (chan->hs_hchan) {
 646                struct hci_chan *hs_hchan = chan->hs_hchan;
 647
 648                BT_DBG("chan %p disconnect hs_hchan %p", chan, hs_hchan);
 649                amp_disconnect_logical_link(hs_hchan);
 650        }
 651
 652        if (test_bit(CONF_NOT_COMPLETE, &chan->conf_state))
 653                return;
 654
 655        switch (chan->mode) {
 656        case L2CAP_MODE_BASIC:
 657                break;
 658
 659        case L2CAP_MODE_LE_FLOWCTL:
 660        case L2CAP_MODE_EXT_FLOWCTL:
 661                skb_queue_purge(&chan->tx_q);
 662                break;
 663
 664        case L2CAP_MODE_ERTM:
 665                __clear_retrans_timer(chan);
 666                __clear_monitor_timer(chan);
 667                __clear_ack_timer(chan);
 668
 669                skb_queue_purge(&chan->srej_q);
 670
 671                l2cap_seq_list_free(&chan->srej_list);
 672                l2cap_seq_list_free(&chan->retrans_list);
 673                fallthrough;
 674
 675        case L2CAP_MODE_STREAMING:
 676                skb_queue_purge(&chan->tx_q);
 677                break;
 678        }
 679}
 680EXPORT_SYMBOL_GPL(l2cap_chan_del);
 681
 682static void __l2cap_chan_list(struct l2cap_conn *conn, l2cap_chan_func_t func,
 683                              void *data)
 684{
 685        struct l2cap_chan *chan;
 686
 687        list_for_each_entry(chan, &conn->chan_l, list) {
 688                func(chan, data);
 689        }
 690}
 691
 692void l2cap_chan_list(struct l2cap_conn *conn, l2cap_chan_func_t func,
 693                     void *data)
 694{
 695        if (!conn)
 696                return;
 697
 698        mutex_lock(&conn->chan_lock);
 699        __l2cap_chan_list(conn, func, data);
 700        mutex_unlock(&conn->chan_lock);
 701}
 702
 703EXPORT_SYMBOL_GPL(l2cap_chan_list);
 704
 705static void l2cap_conn_update_id_addr(struct work_struct *work)
 706{
 707        struct l2cap_conn *conn = container_of(work, struct l2cap_conn,
 708                                               id_addr_update_work);
 709        struct hci_conn *hcon = conn->hcon;
 710        struct l2cap_chan *chan;
 711
 712        mutex_lock(&conn->chan_lock);
 713
 714        list_for_each_entry(chan, &conn->chan_l, list) {
 715                l2cap_chan_lock(chan);
 716                bacpy(&chan->dst, &hcon->dst);
 717                chan->dst_type = bdaddr_dst_type(hcon);
 718                l2cap_chan_unlock(chan);
 719        }
 720
 721        mutex_unlock(&conn->chan_lock);
 722}
 723
 724static void l2cap_chan_le_connect_reject(struct l2cap_chan *chan)
 725{
 726        struct l2cap_conn *conn = chan->conn;
 727        struct l2cap_le_conn_rsp rsp;
 728        u16 result;
 729
 730        if (test_bit(FLAG_DEFER_SETUP, &chan->flags))
 731                result = L2CAP_CR_LE_AUTHORIZATION;
 732        else
 733                result = L2CAP_CR_LE_BAD_PSM;
 734
 735        l2cap_state_change(chan, BT_DISCONN);
 736
 737        rsp.dcid    = cpu_to_le16(chan->scid);
 738        rsp.mtu     = cpu_to_le16(chan->imtu);
 739        rsp.mps     = cpu_to_le16(chan->mps);
 740        rsp.credits = cpu_to_le16(chan->rx_credits);
 741        rsp.result  = cpu_to_le16(result);
 742
 743        l2cap_send_cmd(conn, chan->ident, L2CAP_LE_CONN_RSP, sizeof(rsp),
 744                       &rsp);
 745}
 746
 747static void l2cap_chan_ecred_connect_reject(struct l2cap_chan *chan)
 748{
 749        struct l2cap_conn *conn = chan->conn;
 750        struct l2cap_ecred_conn_rsp rsp;
 751        u16 result;
 752
 753        if (test_bit(FLAG_DEFER_SETUP, &chan->flags))
 754                result = L2CAP_CR_LE_AUTHORIZATION;
 755        else
 756                result = L2CAP_CR_LE_BAD_PSM;
 757
 758        l2cap_state_change(chan, BT_DISCONN);
 759
 760        memset(&rsp, 0, sizeof(rsp));
 761
 762        rsp.result  = cpu_to_le16(result);
 763
 764        l2cap_send_cmd(conn, chan->ident, L2CAP_LE_CONN_RSP, sizeof(rsp),
 765                       &rsp);
 766}
 767
 768static void l2cap_chan_connect_reject(struct l2cap_chan *chan)
 769{
 770        struct l2cap_conn *conn = chan->conn;
 771        struct l2cap_conn_rsp rsp;
 772        u16 result;
 773
 774        if (test_bit(FLAG_DEFER_SETUP, &chan->flags))
 775                result = L2CAP_CR_SEC_BLOCK;
 776        else
 777                result = L2CAP_CR_BAD_PSM;
 778
 779        l2cap_state_change(chan, BT_DISCONN);
 780
 781        rsp.scid   = cpu_to_le16(chan->dcid);
 782        rsp.dcid   = cpu_to_le16(chan->scid);
 783        rsp.result = cpu_to_le16(result);
 784        rsp.status = cpu_to_le16(L2CAP_CS_NO_INFO);
 785
 786        l2cap_send_cmd(conn, chan->ident, L2CAP_CONN_RSP, sizeof(rsp), &rsp);
 787}
 788
 789void l2cap_chan_close(struct l2cap_chan *chan, int reason)
 790{
 791        struct l2cap_conn *conn = chan->conn;
 792
 793        BT_DBG("chan %p state %s", chan, state_to_string(chan->state));
 794
 795        switch (chan->state) {
 796        case BT_LISTEN:
 797                chan->ops->teardown(chan, 0);
 798                break;
 799
 800        case BT_CONNECTED:
 801        case BT_CONFIG:
 802                if (chan->chan_type == L2CAP_CHAN_CONN_ORIENTED) {
 803                        __set_chan_timer(chan, chan->ops->get_sndtimeo(chan));
 804                        l2cap_send_disconn_req(chan, reason);
 805                } else
 806                        l2cap_chan_del(chan, reason);
 807                break;
 808
 809        case BT_CONNECT2:
 810                if (chan->chan_type == L2CAP_CHAN_CONN_ORIENTED) {
 811                        if (conn->hcon->type == ACL_LINK)
 812                                l2cap_chan_connect_reject(chan);
 813                        else if (conn->hcon->type == LE_LINK) {
 814                                switch (chan->mode) {
 815                                case L2CAP_MODE_LE_FLOWCTL:
 816                                        l2cap_chan_le_connect_reject(chan);
 817                                        break;
 818                                case L2CAP_MODE_EXT_FLOWCTL:
 819                                        l2cap_chan_ecred_connect_reject(chan);
 820                                        break;
 821                                }
 822                        }
 823                }
 824
 825                l2cap_chan_del(chan, reason);
 826                break;
 827
 828        case BT_CONNECT:
 829        case BT_DISCONN:
 830                l2cap_chan_del(chan, reason);
 831                break;
 832
 833        default:
 834                chan->ops->teardown(chan, 0);
 835                break;
 836        }
 837}
 838EXPORT_SYMBOL(l2cap_chan_close);
 839
 840static inline u8 l2cap_get_auth_type(struct l2cap_chan *chan)
 841{
 842        switch (chan->chan_type) {
 843        case L2CAP_CHAN_RAW:
 844                switch (chan->sec_level) {
 845                case BT_SECURITY_HIGH:
 846                case BT_SECURITY_FIPS:
 847                        return HCI_AT_DEDICATED_BONDING_MITM;
 848                case BT_SECURITY_MEDIUM:
 849                        return HCI_AT_DEDICATED_BONDING;
 850                default:
 851                        return HCI_AT_NO_BONDING;
 852                }
 853                break;
 854        case L2CAP_CHAN_CONN_LESS:
 855                if (chan->psm == cpu_to_le16(L2CAP_PSM_3DSP)) {
 856                        if (chan->sec_level == BT_SECURITY_LOW)
 857                                chan->sec_level = BT_SECURITY_SDP;
 858                }
 859                if (chan->sec_level == BT_SECURITY_HIGH ||
 860                    chan->sec_level == BT_SECURITY_FIPS)
 861                        return HCI_AT_NO_BONDING_MITM;
 862                else
 863                        return HCI_AT_NO_BONDING;
 864                break;
 865        case L2CAP_CHAN_CONN_ORIENTED:
 866                if (chan->psm == cpu_to_le16(L2CAP_PSM_SDP)) {
 867                        if (chan->sec_level == BT_SECURITY_LOW)
 868                                chan->sec_level = BT_SECURITY_SDP;
 869
 870                        if (chan->sec_level == BT_SECURITY_HIGH ||
 871                            chan->sec_level == BT_SECURITY_FIPS)
 872                                return HCI_AT_NO_BONDING_MITM;
 873                        else
 874                                return HCI_AT_NO_BONDING;
 875                }
 876                fallthrough;
 877
 878        default:
 879                switch (chan->sec_level) {
 880                case BT_SECURITY_HIGH:
 881                case BT_SECURITY_FIPS:
 882                        return HCI_AT_GENERAL_BONDING_MITM;
 883                case BT_SECURITY_MEDIUM:
 884                        return HCI_AT_GENERAL_BONDING;
 885                default:
 886                        return HCI_AT_NO_BONDING;
 887                }
 888                break;
 889        }
 890}
 891
 892/* Service level security */
 893int l2cap_chan_check_security(struct l2cap_chan *chan, bool initiator)
 894{
 895        struct l2cap_conn *conn = chan->conn;
 896        __u8 auth_type;
 897
 898        if (conn->hcon->type == LE_LINK)
 899                return smp_conn_security(conn->hcon, chan->sec_level);
 900
 901        auth_type = l2cap_get_auth_type(chan);
 902
 903        return hci_conn_security(conn->hcon, chan->sec_level, auth_type,
 904                                 initiator);
 905}
 906
 907static u8 l2cap_get_ident(struct l2cap_conn *conn)
 908{
 909        u8 id;
 910
 911        /* Get next available identificator.
 912         *    1 - 128 are used by kernel.
 913         *  129 - 199 are reserved.
 914         *  200 - 254 are used by utilities like l2ping, etc.
 915         */
 916
 917        mutex_lock(&conn->ident_lock);
 918
 919        if (++conn->tx_ident > 128)
 920                conn->tx_ident = 1;
 921
 922        id = conn->tx_ident;
 923
 924        mutex_unlock(&conn->ident_lock);
 925
 926        return id;
 927}
 928
 929static void l2cap_send_cmd(struct l2cap_conn *conn, u8 ident, u8 code, u16 len,
 930                           void *data)
 931{
 932        struct sk_buff *skb = l2cap_build_cmd(conn, code, ident, len, data);
 933        u8 flags;
 934
 935        BT_DBG("code 0x%2.2x", code);
 936
 937        if (!skb)
 938                return;
 939
 940        /* Use NO_FLUSH if supported or we have an LE link (which does
 941         * not support auto-flushing packets) */
 942        if (lmp_no_flush_capable(conn->hcon->hdev) ||
 943            conn->hcon->type == LE_LINK)
 944                flags = ACL_START_NO_FLUSH;
 945        else
 946                flags = ACL_START;
 947
 948        bt_cb(skb)->force_active = BT_POWER_FORCE_ACTIVE_ON;
 949        skb->priority = HCI_PRIO_MAX;
 950
 951        hci_send_acl(conn->hchan, skb, flags);
 952}
 953
 954static bool __chan_is_moving(struct l2cap_chan *chan)
 955{
 956        return chan->move_state != L2CAP_MOVE_STABLE &&
 957               chan->move_state != L2CAP_MOVE_WAIT_PREPARE;
 958}
 959
 960static void l2cap_do_send(struct l2cap_chan *chan, struct sk_buff *skb)
 961{
 962        struct hci_conn *hcon = chan->conn->hcon;
 963        u16 flags;
 964
 965        BT_DBG("chan %p, skb %p len %d priority %u", chan, skb, skb->len,
 966               skb->priority);
 967
 968        if (chan->hs_hcon && !__chan_is_moving(chan)) {
 969                if (chan->hs_hchan)
 970                        hci_send_acl(chan->hs_hchan, skb, ACL_COMPLETE);
 971                else
 972                        kfree_skb(skb);
 973
 974                return;
 975        }
 976
 977        /* Use NO_FLUSH for LE links (where this is the only option) or
 978         * if the BR/EDR link supports it and flushing has not been
 979         * explicitly requested (through FLAG_FLUSHABLE).
 980         */
 981        if (hcon->type == LE_LINK ||
 982            (!test_bit(FLAG_FLUSHABLE, &chan->flags) &&
 983             lmp_no_flush_capable(hcon->hdev)))
 984                flags = ACL_START_NO_FLUSH;
 985        else
 986                flags = ACL_START;
 987
 988        bt_cb(skb)->force_active = test_bit(FLAG_FORCE_ACTIVE, &chan->flags);
 989        hci_send_acl(chan->conn->hchan, skb, flags);
 990}
 991
 992static void __unpack_enhanced_control(u16 enh, struct l2cap_ctrl *control)
 993{
 994        control->reqseq = (enh & L2CAP_CTRL_REQSEQ) >> L2CAP_CTRL_REQSEQ_SHIFT;
 995        control->final = (enh & L2CAP_CTRL_FINAL) >> L2CAP_CTRL_FINAL_SHIFT;
 996
 997        if (enh & L2CAP_CTRL_FRAME_TYPE) {
 998                /* S-Frame */
 999                control->sframe = 1;
1000                control->poll = (enh & L2CAP_CTRL_POLL) >> L2CAP_CTRL_POLL_SHIFT;
1001                control->super = (enh & L2CAP_CTRL_SUPERVISE) >> L2CAP_CTRL_SUPER_SHIFT;
1002
1003                control->sar = 0;
1004                control->txseq = 0;
1005        } else {
1006                /* I-Frame */
1007                control->sframe = 0;
1008                control->sar = (enh & L2CAP_CTRL_SAR) >> L2CAP_CTRL_SAR_SHIFT;
1009                control->txseq = (enh & L2CAP_CTRL_TXSEQ) >> L2CAP_CTRL_TXSEQ_SHIFT;
1010
1011                control->poll = 0;
1012                control->super = 0;
1013        }
1014}
1015
1016static void __unpack_extended_control(u32 ext, struct l2cap_ctrl *control)
1017{
1018        control->reqseq = (ext & L2CAP_EXT_CTRL_REQSEQ) >> L2CAP_EXT_CTRL_REQSEQ_SHIFT;
1019        control->final = (ext & L2CAP_EXT_CTRL_FINAL) >> L2CAP_EXT_CTRL_FINAL_SHIFT;
1020
1021        if (ext & L2CAP_EXT_CTRL_FRAME_TYPE) {
1022                /* S-Frame */
1023                control->sframe = 1;
1024                control->poll = (ext & L2CAP_EXT_CTRL_POLL) >> L2CAP_EXT_CTRL_POLL_SHIFT;
1025                control->super = (ext & L2CAP_EXT_CTRL_SUPERVISE) >> L2CAP_EXT_CTRL_SUPER_SHIFT;
1026
1027                control->sar = 0;
1028                control->txseq = 0;
1029        } else {
1030                /* I-Frame */
1031                control->sframe = 0;
1032                control->sar = (ext & L2CAP_EXT_CTRL_SAR) >> L2CAP_EXT_CTRL_SAR_SHIFT;
1033                control->txseq = (ext & L2CAP_EXT_CTRL_TXSEQ) >> L2CAP_EXT_CTRL_TXSEQ_SHIFT;
1034
1035                control->poll = 0;
1036                control->super = 0;
1037        }
1038}
1039
1040static inline void __unpack_control(struct l2cap_chan *chan,
1041                                    struct sk_buff *skb)
1042{
1043        if (test_bit(FLAG_EXT_CTRL, &chan->flags)) {
1044                __unpack_extended_control(get_unaligned_le32(skb->data),
1045                                          &bt_cb(skb)->l2cap);
1046                skb_pull(skb, L2CAP_EXT_CTRL_SIZE);
1047        } else {
1048                __unpack_enhanced_control(get_unaligned_le16(skb->data),
1049                                          &bt_cb(skb)->l2cap);
1050                skb_pull(skb, L2CAP_ENH_CTRL_SIZE);
1051        }
1052}
1053
1054static u32 __pack_extended_control(struct l2cap_ctrl *control)
1055{
1056        u32 packed;
1057
1058        packed = control->reqseq << L2CAP_EXT_CTRL_REQSEQ_SHIFT;
1059        packed |= control->final << L2CAP_EXT_CTRL_FINAL_SHIFT;
1060
1061        if (control->sframe) {
1062                packed |= control->poll << L2CAP_EXT_CTRL_POLL_SHIFT;
1063                packed |= control->super << L2CAP_EXT_CTRL_SUPER_SHIFT;
1064                packed |= L2CAP_EXT_CTRL_FRAME_TYPE;
1065        } else {
1066                packed |= control->sar << L2CAP_EXT_CTRL_SAR_SHIFT;
1067                packed |= control->txseq << L2CAP_EXT_CTRL_TXSEQ_SHIFT;
1068        }
1069
1070        return packed;
1071}
1072
1073static u16 __pack_enhanced_control(struct l2cap_ctrl *control)
1074{
1075        u16 packed;
1076
1077        packed = control->reqseq << L2CAP_CTRL_REQSEQ_SHIFT;
1078        packed |= control->final << L2CAP_CTRL_FINAL_SHIFT;
1079
1080        if (control->sframe) {
1081                packed |= control->poll << L2CAP_CTRL_POLL_SHIFT;
1082                packed |= control->super << L2CAP_CTRL_SUPER_SHIFT;
1083                packed |= L2CAP_CTRL_FRAME_TYPE;
1084        } else {
1085                packed |= control->sar << L2CAP_CTRL_SAR_SHIFT;
1086                packed |= control->txseq << L2CAP_CTRL_TXSEQ_SHIFT;
1087        }
1088
1089        return packed;
1090}
1091
1092static inline void __pack_control(struct l2cap_chan *chan,
1093                                  struct l2cap_ctrl *control,
1094                                  struct sk_buff *skb)
1095{
1096        if (test_bit(FLAG_EXT_CTRL, &chan->flags)) {
1097                put_unaligned_le32(__pack_extended_control(control),
1098                                   skb->data + L2CAP_HDR_SIZE);
1099        } else {
1100                put_unaligned_le16(__pack_enhanced_control(control),
1101                                   skb->data + L2CAP_HDR_SIZE);
1102        }
1103}
1104
1105static inline unsigned int __ertm_hdr_size(struct l2cap_chan *chan)
1106{
1107        if (test_bit(FLAG_EXT_CTRL, &chan->flags))
1108                return L2CAP_EXT_HDR_SIZE;
1109        else
1110                return L2CAP_ENH_HDR_SIZE;
1111}
1112
1113static struct sk_buff *l2cap_create_sframe_pdu(struct l2cap_chan *chan,
1114                                               u32 control)
1115{
1116        struct sk_buff *skb;
1117        struct l2cap_hdr *lh;
1118        int hlen = __ertm_hdr_size(chan);
1119
1120        if (chan->fcs == L2CAP_FCS_CRC16)
1121                hlen += L2CAP_FCS_SIZE;
1122
1123        skb = bt_skb_alloc(hlen, GFP_KERNEL);
1124
1125        if (!skb)
1126                return ERR_PTR(-ENOMEM);
1127
1128        lh = skb_put(skb, L2CAP_HDR_SIZE);
1129        lh->len = cpu_to_le16(hlen - L2CAP_HDR_SIZE);
1130        lh->cid = cpu_to_le16(chan->dcid);
1131
1132        if (test_bit(FLAG_EXT_CTRL, &chan->flags))
1133                put_unaligned_le32(control, skb_put(skb, L2CAP_EXT_CTRL_SIZE));
1134        else
1135                put_unaligned_le16(control, skb_put(skb, L2CAP_ENH_CTRL_SIZE));
1136
1137        if (chan->fcs == L2CAP_FCS_CRC16) {
1138                u16 fcs = crc16(0, (u8 *)skb->data, skb->len);
1139                put_unaligned_le16(fcs, skb_put(skb, L2CAP_FCS_SIZE));
1140        }
1141
1142        skb->priority = HCI_PRIO_MAX;
1143        return skb;
1144}
1145
1146static void l2cap_send_sframe(struct l2cap_chan *chan,
1147                              struct l2cap_ctrl *control)
1148{
1149        struct sk_buff *skb;
1150        u32 control_field;
1151
1152        BT_DBG("chan %p, control %p", chan, control);
1153
1154        if (!control->sframe)
1155                return;
1156
1157        if (__chan_is_moving(chan))
1158                return;
1159
1160        if (test_and_clear_bit(CONN_SEND_FBIT, &chan->conn_state) &&
1161            !control->poll)
1162                control->final = 1;
1163
1164        if (control->super == L2CAP_SUPER_RR)
1165                clear_bit(CONN_RNR_SENT, &chan->conn_state);
1166        else if (control->super == L2CAP_SUPER_RNR)
1167                set_bit(CONN_RNR_SENT, &chan->conn_state);
1168
1169        if (control->super != L2CAP_SUPER_SREJ) {
1170                chan->last_acked_seq = control->reqseq;
1171                __clear_ack_timer(chan);
1172        }
1173
1174        BT_DBG("reqseq %d, final %d, poll %d, super %d", control->reqseq,
1175               control->final, control->poll, control->super);
1176
1177        if (test_bit(FLAG_EXT_CTRL, &chan->flags))
1178                control_field = __pack_extended_control(control);
1179        else
1180                control_field = __pack_enhanced_control(control);
1181
1182        skb = l2cap_create_sframe_pdu(chan, control_field);
1183        if (!IS_ERR(skb))
1184                l2cap_do_send(chan, skb);
1185}
1186
1187static void l2cap_send_rr_or_rnr(struct l2cap_chan *chan, bool poll)
1188{
1189        struct l2cap_ctrl control;
1190
1191        BT_DBG("chan %p, poll %d", chan, poll);
1192
1193        memset(&control, 0, sizeof(control));
1194        control.sframe = 1;
1195        control.poll = poll;
1196
1197        if (test_bit(CONN_LOCAL_BUSY, &chan->conn_state))
1198                control.super = L2CAP_SUPER_RNR;
1199        else
1200                control.super = L2CAP_SUPER_RR;
1201
1202        control.reqseq = chan->buffer_seq;
1203        l2cap_send_sframe(chan, &control);
1204}
1205
1206static inline int __l2cap_no_conn_pending(struct l2cap_chan *chan)
1207{
1208        if (chan->chan_type != L2CAP_CHAN_CONN_ORIENTED)
1209                return true;
1210
1211        return !test_bit(CONF_CONNECT_PEND, &chan->conf_state);
1212}
1213
1214static bool __amp_capable(struct l2cap_chan *chan)
1215{
1216        struct l2cap_conn *conn = chan->conn;
1217        struct hci_dev *hdev;
1218        bool amp_available = false;
1219
1220        if (!(conn->local_fixed_chan & L2CAP_FC_A2MP))
1221                return false;
1222
1223        if (!(conn->remote_fixed_chan & L2CAP_FC_A2MP))
1224                return false;
1225
1226        read_lock(&hci_dev_list_lock);
1227        list_for_each_entry(hdev, &hci_dev_list, list) {
1228                if (hdev->amp_type != AMP_TYPE_BREDR &&
1229                    test_bit(HCI_UP, &hdev->flags)) {
1230                        amp_available = true;
1231                        break;
1232                }
1233        }
1234        read_unlock(&hci_dev_list_lock);
1235
1236        if (chan->chan_policy == BT_CHANNEL_POLICY_AMP_PREFERRED)
1237                return amp_available;
1238
1239        return false;
1240}
1241
1242static bool l2cap_check_efs(struct l2cap_chan *chan)
1243{
1244        /* Check EFS parameters */
1245        return true;
1246}
1247
1248void l2cap_send_conn_req(struct l2cap_chan *chan)
1249{
1250        struct l2cap_conn *conn = chan->conn;
1251        struct l2cap_conn_req req;
1252
1253        req.scid = cpu_to_le16(chan->scid);
1254        req.psm  = chan->psm;
1255
1256        chan->ident = l2cap_get_ident(conn);
1257
1258        set_bit(CONF_CONNECT_PEND, &chan->conf_state);
1259
1260        l2cap_send_cmd(conn, chan->ident, L2CAP_CONN_REQ, sizeof(req), &req);
1261}
1262
1263static void l2cap_send_create_chan_req(struct l2cap_chan *chan, u8 amp_id)
1264{
1265        struct l2cap_create_chan_req req;
1266        req.scid = cpu_to_le16(chan->scid);
1267        req.psm  = chan->psm;
1268        req.amp_id = amp_id;
1269
1270        chan->ident = l2cap_get_ident(chan->conn);
1271
1272        l2cap_send_cmd(chan->conn, chan->ident, L2CAP_CREATE_CHAN_REQ,
1273                       sizeof(req), &req);
1274}
1275
1276static void l2cap_move_setup(struct l2cap_chan *chan)
1277{
1278        struct sk_buff *skb;
1279
1280        BT_DBG("chan %p", chan);
1281
1282        if (chan->mode != L2CAP_MODE_ERTM)
1283                return;
1284
1285        __clear_retrans_timer(chan);
1286        __clear_monitor_timer(chan);
1287        __clear_ack_timer(chan);
1288
1289        chan->retry_count = 0;
1290        skb_queue_walk(&chan->tx_q, skb) {
1291                if (bt_cb(skb)->l2cap.retries)
1292                        bt_cb(skb)->l2cap.retries = 1;
1293                else
1294                        break;
1295        }
1296
1297        chan->expected_tx_seq = chan->buffer_seq;
1298
1299        clear_bit(CONN_REJ_ACT, &chan->conn_state);
1300        clear_bit(CONN_SREJ_ACT, &chan->conn_state);
1301        l2cap_seq_list_clear(&chan->retrans_list);
1302        l2cap_seq_list_clear(&chan->srej_list);
1303        skb_queue_purge(&chan->srej_q);
1304
1305        chan->tx_state = L2CAP_TX_STATE_XMIT;
1306        chan->rx_state = L2CAP_RX_STATE_MOVE;
1307
1308        set_bit(CONN_REMOTE_BUSY, &chan->conn_state);
1309}
1310
1311static void l2cap_move_done(struct l2cap_chan *chan)
1312{
1313        u8 move_role = chan->move_role;
1314        BT_DBG("chan %p", chan);
1315
1316        chan->move_state = L2CAP_MOVE_STABLE;
1317        chan->move_role = L2CAP_MOVE_ROLE_NONE;
1318
1319        if (chan->mode != L2CAP_MODE_ERTM)
1320                return;
1321
1322        switch (move_role) {
1323        case L2CAP_MOVE_ROLE_INITIATOR:
1324                l2cap_tx(chan, NULL, NULL, L2CAP_EV_EXPLICIT_POLL);
1325                chan->rx_state = L2CAP_RX_STATE_WAIT_F;
1326                break;
1327        case L2CAP_MOVE_ROLE_RESPONDER:
1328                chan->rx_state = L2CAP_RX_STATE_WAIT_P;
1329                break;
1330        }
1331}
1332
1333static void l2cap_chan_ready(struct l2cap_chan *chan)
1334{
1335        /* The channel may have already been flagged as connected in
1336         * case of receiving data before the L2CAP info req/rsp
1337         * procedure is complete.
1338         */
1339        if (chan->state == BT_CONNECTED)
1340                return;
1341
1342        /* This clears all conf flags, including CONF_NOT_COMPLETE */
1343        chan->conf_state = 0;
1344        __clear_chan_timer(chan);
1345
1346        switch (chan->mode) {
1347        case L2CAP_MODE_LE_FLOWCTL:
1348        case L2CAP_MODE_EXT_FLOWCTL:
1349                if (!chan->tx_credits)
1350                        chan->ops->suspend(chan);
1351                break;
1352        }
1353
1354        chan->state = BT_CONNECTED;
1355
1356        chan->ops->ready(chan);
1357}
1358
1359static void l2cap_le_connect(struct l2cap_chan *chan)
1360{
1361        struct l2cap_conn *conn = chan->conn;
1362        struct l2cap_le_conn_req req;
1363
1364        if (test_and_set_bit(FLAG_LE_CONN_REQ_SENT, &chan->flags))
1365                return;
1366
1367        if (!chan->imtu)
1368                chan->imtu = chan->conn->mtu;
1369
1370        l2cap_le_flowctl_init(chan, 0);
1371
1372        req.psm     = chan->psm;
1373        req.scid    = cpu_to_le16(chan->scid);
1374        req.mtu     = cpu_to_le16(chan->imtu);
1375        req.mps     = cpu_to_le16(chan->mps);
1376        req.credits = cpu_to_le16(chan->rx_credits);
1377
1378        chan->ident = l2cap_get_ident(conn);
1379
1380        l2cap_send_cmd(conn, chan->ident, L2CAP_LE_CONN_REQ,
1381                       sizeof(req), &req);
1382}
1383
1384struct l2cap_ecred_conn_data {
1385        struct {
1386                struct l2cap_ecred_conn_req req;
1387                __le16 scid[5];
1388        } __packed pdu;
1389        struct l2cap_chan *chan;
1390        struct pid *pid;
1391        int count;
1392};
1393
1394static void l2cap_ecred_defer_connect(struct l2cap_chan *chan, void *data)
1395{
1396        struct l2cap_ecred_conn_data *conn = data;
1397        struct pid *pid;
1398
1399        if (chan == conn->chan)
1400                return;
1401
1402        if (!test_and_clear_bit(FLAG_DEFER_SETUP, &chan->flags))
1403                return;
1404
1405        pid = chan->ops->get_peer_pid(chan);
1406
1407        /* Only add deferred channels with the same PID/PSM */
1408        if (conn->pid != pid || chan->psm != conn->chan->psm || chan->ident ||
1409            chan->mode != L2CAP_MODE_EXT_FLOWCTL || chan->state != BT_CONNECT)
1410                return;
1411
1412        if (test_and_set_bit(FLAG_ECRED_CONN_REQ_SENT, &chan->flags))
1413                return;
1414
1415        l2cap_ecred_init(chan, 0);
1416
1417        /* Set the same ident so we can match on the rsp */
1418        chan->ident = conn->chan->ident;
1419
1420        /* Include all channels deferred */
1421        conn->pdu.scid[conn->count] = cpu_to_le16(chan->scid);
1422
1423        conn->count++;
1424}
1425
1426static void l2cap_ecred_connect(struct l2cap_chan *chan)
1427{
1428        struct l2cap_conn *conn = chan->conn;
1429        struct l2cap_ecred_conn_data data;
1430
1431        if (test_bit(FLAG_DEFER_SETUP, &chan->flags))
1432                return;
1433
1434        if (test_and_set_bit(FLAG_ECRED_CONN_REQ_SENT, &chan->flags))
1435                return;
1436
1437        l2cap_ecred_init(chan, 0);
1438
1439        data.pdu.req.psm     = chan->psm;
1440        data.pdu.req.mtu     = cpu_to_le16(chan->imtu);
1441        data.pdu.req.mps     = cpu_to_le16(chan->mps);
1442        data.pdu.req.credits = cpu_to_le16(chan->rx_credits);
1443        data.pdu.scid[0]     = cpu_to_le16(chan->scid);
1444
1445        chan->ident = l2cap_get_ident(conn);
1446        data.pid = chan->ops->get_peer_pid(chan);
1447
1448        data.count = 1;
1449        data.chan = chan;
1450        data.pid = chan->ops->get_peer_pid(chan);
1451
1452        __l2cap_chan_list(conn, l2cap_ecred_defer_connect, &data);
1453
1454        l2cap_send_cmd(conn, chan->ident, L2CAP_ECRED_CONN_REQ,
1455                       sizeof(data.pdu.req) + data.count * sizeof(__le16),
1456                       &data.pdu);
1457}
1458
1459static void l2cap_le_start(struct l2cap_chan *chan)
1460{
1461        struct l2cap_conn *conn = chan->conn;
1462
1463        if (!smp_conn_security(conn->hcon, chan->sec_level))
1464                return;
1465
1466        if (!chan->psm) {
1467                l2cap_chan_ready(chan);
1468                return;
1469        }
1470
1471        if (chan->state == BT_CONNECT) {
1472                if (chan->mode == L2CAP_MODE_EXT_FLOWCTL)
1473                        l2cap_ecred_connect(chan);
1474                else
1475                        l2cap_le_connect(chan);
1476        }
1477}
1478
1479static void l2cap_start_connection(struct l2cap_chan *chan)
1480{
1481        if (__amp_capable(chan)) {
1482                BT_DBG("chan %p AMP capable: discover AMPs", chan);
1483                a2mp_discover_amp(chan);
1484        } else if (chan->conn->hcon->type == LE_LINK) {
1485                l2cap_le_start(chan);
1486        } else {
1487                l2cap_send_conn_req(chan);
1488        }
1489}
1490
1491static void l2cap_request_info(struct l2cap_conn *conn)
1492{
1493        struct l2cap_info_req req;
1494
1495        if (conn->info_state & L2CAP_INFO_FEAT_MASK_REQ_SENT)
1496                return;
1497
1498        req.type = cpu_to_le16(L2CAP_IT_FEAT_MASK);
1499
1500        conn->info_state |= L2CAP_INFO_FEAT_MASK_REQ_SENT;
1501        conn->info_ident = l2cap_get_ident(conn);
1502
1503        schedule_delayed_work(&conn->info_timer, L2CAP_INFO_TIMEOUT);
1504
1505        l2cap_send_cmd(conn, conn->info_ident, L2CAP_INFO_REQ,
1506                       sizeof(req), &req);
1507}
1508
1509static bool l2cap_check_enc_key_size(struct hci_conn *hcon)
1510{
1511        /* The minimum encryption key size needs to be enforced by the
1512         * host stack before establishing any L2CAP connections. The
1513         * specification in theory allows a minimum of 1, but to align
1514         * BR/EDR and LE transports, a minimum of 7 is chosen.
1515         *
1516         * This check might also be called for unencrypted connections
1517         * that have no key size requirements. Ensure that the link is
1518         * actually encrypted before enforcing a key size.
1519         */
1520        int min_key_size = hcon->hdev->min_enc_key_size;
1521
1522        /* On FIPS security level, key size must be 16 bytes */
1523        if (hcon->sec_level == BT_SECURITY_FIPS)
1524                min_key_size = 16;
1525
1526        return (!test_bit(HCI_CONN_ENCRYPT, &hcon->flags) ||
1527                hcon->enc_key_size >= min_key_size);
1528}
1529
1530static void l2cap_do_start(struct l2cap_chan *chan)
1531{
1532        struct l2cap_conn *conn = chan->conn;
1533
1534        if (conn->hcon->type == LE_LINK) {
1535                l2cap_le_start(chan);
1536                return;
1537        }
1538
1539        if (!(conn->info_state & L2CAP_INFO_FEAT_MASK_REQ_SENT)) {
1540                l2cap_request_info(conn);
1541                return;
1542        }
1543
1544        if (!(conn->info_state & L2CAP_INFO_FEAT_MASK_REQ_DONE))
1545                return;
1546
1547        if (!l2cap_chan_check_security(chan, true) ||
1548            !__l2cap_no_conn_pending(chan))
1549                return;
1550
1551        if (l2cap_check_enc_key_size(conn->hcon))
1552                l2cap_start_connection(chan);
1553        else
1554                __set_chan_timer(chan, L2CAP_DISC_TIMEOUT);
1555}
1556
1557static inline int l2cap_mode_supported(__u8 mode, __u32 feat_mask)
1558{
1559        u32 local_feat_mask = l2cap_feat_mask;
1560        if (!disable_ertm)
1561                local_feat_mask |= L2CAP_FEAT_ERTM | L2CAP_FEAT_STREAMING;
1562
1563        switch (mode) {
1564        case L2CAP_MODE_ERTM:
1565                return L2CAP_FEAT_ERTM & feat_mask & local_feat_mask;
1566        case L2CAP_MODE_STREAMING:
1567                return L2CAP_FEAT_STREAMING & feat_mask & local_feat_mask;
1568        default:
1569                return 0x00;
1570        }
1571}
1572
1573static void l2cap_send_disconn_req(struct l2cap_chan *chan, int err)
1574{
1575        struct l2cap_conn *conn = chan->conn;
1576        struct l2cap_disconn_req req;
1577
1578        if (!conn)
1579                return;
1580
1581        if (chan->mode == L2CAP_MODE_ERTM && chan->state == BT_CONNECTED) {
1582                __clear_retrans_timer(chan);
1583                __clear_monitor_timer(chan);
1584                __clear_ack_timer(chan);
1585        }
1586
1587        if (chan->scid == L2CAP_CID_A2MP) {
1588                l2cap_state_change(chan, BT_DISCONN);
1589                return;
1590        }
1591
1592        req.dcid = cpu_to_le16(chan->dcid);
1593        req.scid = cpu_to_le16(chan->scid);
1594        l2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_DISCONN_REQ,
1595                       sizeof(req), &req);
1596
1597        l2cap_state_change_and_error(chan, BT_DISCONN, err);
1598}
1599
1600/* ---- L2CAP connections ---- */
1601static void l2cap_conn_start(struct l2cap_conn *conn)
1602{
1603        struct l2cap_chan *chan, *tmp;
1604
1605        BT_DBG("conn %p", conn);
1606
1607        mutex_lock(&conn->chan_lock);
1608
1609        list_for_each_entry_safe(chan, tmp, &conn->chan_l, list) {
1610                l2cap_chan_lock(chan);
1611
1612                if (chan->chan_type != L2CAP_CHAN_CONN_ORIENTED) {
1613                        l2cap_chan_ready(chan);
1614                        l2cap_chan_unlock(chan);
1615                        continue;
1616                }
1617
1618                if (chan->state == BT_CONNECT) {
1619                        if (!l2cap_chan_check_security(chan, true) ||
1620                            !__l2cap_no_conn_pending(chan)) {
1621                                l2cap_chan_unlock(chan);
1622                                continue;
1623                        }
1624
1625                        if (!l2cap_mode_supported(chan->mode, conn->feat_mask)
1626                            && test_bit(CONF_STATE2_DEVICE,
1627                                        &chan->conf_state)) {
1628                                l2cap_chan_close(chan, ECONNRESET);
1629                                l2cap_chan_unlock(chan);
1630                                continue;
1631                        }
1632
1633                        if (l2cap_check_enc_key_size(conn->hcon))
1634                                l2cap_start_connection(chan);
1635                        else
1636                                l2cap_chan_close(chan, ECONNREFUSED);
1637
1638                } else if (chan->state == BT_CONNECT2) {
1639                        struct l2cap_conn_rsp rsp;
1640                        char buf[128];
1641                        rsp.scid = cpu_to_le16(chan->dcid);
1642                        rsp.dcid = cpu_to_le16(chan->scid);
1643
1644                        if (l2cap_chan_check_security(chan, false)) {
1645                                if (test_bit(FLAG_DEFER_SETUP, &chan->flags)) {
1646                                        rsp.result = cpu_to_le16(L2CAP_CR_PEND);
1647                                        rsp.status = cpu_to_le16(L2CAP_CS_AUTHOR_PEND);
1648                                        chan->ops->defer(chan);
1649
1650                                } else {
1651                                        l2cap_state_change(chan, BT_CONFIG);
1652                                        rsp.result = cpu_to_le16(L2CAP_CR_SUCCESS);
1653                                        rsp.status = cpu_to_le16(L2CAP_CS_NO_INFO);
1654                                }
1655                        } else {
1656                                rsp.result = cpu_to_le16(L2CAP_CR_PEND);
1657                                rsp.status = cpu_to_le16(L2CAP_CS_AUTHEN_PEND);
1658                        }
1659
1660                        l2cap_send_cmd(conn, chan->ident, L2CAP_CONN_RSP,
1661                                       sizeof(rsp), &rsp);
1662
1663                        if (test_bit(CONF_REQ_SENT, &chan->conf_state) ||
1664                            rsp.result != L2CAP_CR_SUCCESS) {
1665                                l2cap_chan_unlock(chan);
1666                                continue;
1667                        }
1668
1669                        set_bit(CONF_REQ_SENT, &chan->conf_state);
1670                        l2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_CONF_REQ,
1671                                       l2cap_build_conf_req(chan, buf, sizeof(buf)), buf);
1672                        chan->num_conf_req++;
1673                }
1674
1675                l2cap_chan_unlock(chan);
1676        }
1677
1678        mutex_unlock(&conn->chan_lock);
1679}
1680
1681static void l2cap_le_conn_ready(struct l2cap_conn *conn)
1682{
1683        struct hci_conn *hcon = conn->hcon;
1684        struct hci_dev *hdev = hcon->hdev;
1685
1686        BT_DBG("%s conn %p", hdev->name, conn);
1687
1688        /* For outgoing pairing which doesn't necessarily have an
1689         * associated socket (e.g. mgmt_pair_device).
1690         */
1691        if (hcon->out)
1692                smp_conn_security(hcon, hcon->pending_sec_level);
1693
1694        /* For LE peripheral connections, make sure the connection interval
1695         * is in the range of the minimum and maximum interval that has
1696         * been configured for this connection. If not, then trigger
1697         * the connection update procedure.
1698         */
1699        if (hcon->role == HCI_ROLE_SLAVE &&
1700            (hcon->le_conn_interval < hcon->le_conn_min_interval ||
1701             hcon->le_conn_interval > hcon->le_conn_max_interval)) {
1702                struct l2cap_conn_param_update_req req;
1703
1704                req.min = cpu_to_le16(hcon->le_conn_min_interval);
1705                req.max = cpu_to_le16(hcon->le_conn_max_interval);
1706                req.latency = cpu_to_le16(hcon->le_conn_latency);
1707                req.to_multiplier = cpu_to_le16(hcon->le_supv_timeout);
1708
1709                l2cap_send_cmd(conn, l2cap_get_ident(conn),
1710                               L2CAP_CONN_PARAM_UPDATE_REQ, sizeof(req), &req);
1711        }
1712}
1713
1714static void l2cap_conn_ready(struct l2cap_conn *conn)
1715{
1716        struct l2cap_chan *chan;
1717        struct hci_conn *hcon = conn->hcon;
1718
1719        BT_DBG("conn %p", conn);
1720
1721        if (hcon->type == ACL_LINK)
1722                l2cap_request_info(conn);
1723
1724        mutex_lock(&conn->chan_lock);
1725
1726        list_for_each_entry(chan, &conn->chan_l, list) {
1727
1728                l2cap_chan_lock(chan);
1729
1730                if (chan->scid == L2CAP_CID_A2MP) {
1731                        l2cap_chan_unlock(chan);
1732                        continue;
1733                }
1734
1735                if (hcon->type == LE_LINK) {
1736                        l2cap_le_start(chan);
1737                } else if (chan->chan_type != L2CAP_CHAN_CONN_ORIENTED) {
1738                        if (conn->info_state & L2CAP_INFO_FEAT_MASK_REQ_DONE)
1739                                l2cap_chan_ready(chan);
1740                } else if (chan->state == BT_CONNECT) {
1741                        l2cap_do_start(chan);
1742                }
1743
1744                l2cap_chan_unlock(chan);
1745        }
1746
1747        mutex_unlock(&conn->chan_lock);
1748
1749        if (hcon->type == LE_LINK)
1750                l2cap_le_conn_ready(conn);
1751
1752        queue_work(hcon->hdev->workqueue, &conn->pending_rx_work);
1753}
1754
1755/* Notify sockets that we cannot guaranty reliability anymore */
1756static void l2cap_conn_unreliable(struct l2cap_conn *conn, int err)
1757{
1758        struct l2cap_chan *chan;
1759
1760        BT_DBG("conn %p", conn);
1761
1762        mutex_lock(&conn->chan_lock);
1763
1764        list_for_each_entry(chan, &conn->chan_l, list) {
1765                if (test_bit(FLAG_FORCE_RELIABLE, &chan->flags))
1766                        l2cap_chan_set_err(chan, err);
1767        }
1768
1769        mutex_unlock(&conn->chan_lock);
1770}
1771
1772static void l2cap_info_timeout(struct work_struct *work)
1773{
1774        struct l2cap_conn *conn = container_of(work, struct l2cap_conn,
1775                                               info_timer.work);
1776
1777        conn->info_state |= L2CAP_INFO_FEAT_MASK_REQ_DONE;
1778        conn->info_ident = 0;
1779
1780        l2cap_conn_start(conn);
1781}
1782
1783/*
1784 * l2cap_user
1785 * External modules can register l2cap_user objects on l2cap_conn. The ->probe
1786 * callback is called during registration. The ->remove callback is called
1787 * during unregistration.
1788 * An l2cap_user object can either be explicitly unregistered or when the
1789 * underlying l2cap_conn object is deleted. This guarantees that l2cap->hcon,
1790 * l2cap->hchan, .. are valid as long as the remove callback hasn't been called.
1791 * External modules must own a reference to the l2cap_conn object if they intend
1792 * to call l2cap_unregister_user(). The l2cap_conn object might get destroyed at
1793 * any time if they don't.
1794 */
1795
1796int l2cap_register_user(struct l2cap_conn *conn, struct l2cap_user *user)
1797{
1798        struct hci_dev *hdev = conn->hcon->hdev;
1799        int ret;
1800
1801        /* We need to check whether l2cap_conn is registered. If it is not, we
1802         * must not register the l2cap_user. l2cap_conn_del() is unregisters
1803         * l2cap_conn objects, but doesn't provide its own locking. Instead, it
1804         * relies on the parent hci_conn object to be locked. This itself relies
1805         * on the hci_dev object to be locked. So we must lock the hci device
1806         * here, too. */
1807
1808        hci_dev_lock(hdev);
1809
1810        if (!list_empty(&user->list)) {
1811                ret = -EINVAL;
1812                goto out_unlock;
1813        }
1814
1815        /* conn->hchan is NULL after l2cap_conn_del() was called */
1816        if (!conn->hchan) {
1817                ret = -ENODEV;
1818                goto out_unlock;
1819        }
1820
1821        ret = user->probe(conn, user);
1822        if (ret)
1823                goto out_unlock;
1824
1825        list_add(&user->list, &conn->users);
1826        ret = 0;
1827
1828out_unlock:
1829        hci_dev_unlock(hdev);
1830        return ret;
1831}
1832EXPORT_SYMBOL(l2cap_register_user);
1833
1834void l2cap_unregister_user(struct l2cap_conn *conn, struct l2cap_user *user)
1835{
1836        struct hci_dev *hdev = conn->hcon->hdev;
1837
1838        hci_dev_lock(hdev);
1839
1840        if (list_empty(&user->list))
1841                goto out_unlock;
1842
1843        list_del_init(&user->list);
1844        user->remove(conn, user);
1845
1846out_unlock:
1847        hci_dev_unlock(hdev);
1848}
1849EXPORT_SYMBOL(l2cap_unregister_user);
1850
1851static void l2cap_unregister_all_users(struct l2cap_conn *conn)
1852{
1853        struct l2cap_user *user;
1854
1855        while (!list_empty(&conn->users)) {
1856                user = list_first_entry(&conn->users, struct l2cap_user, list);
1857                list_del_init(&user->list);
1858                user->remove(conn, user);
1859        }
1860}
1861
1862static void l2cap_conn_del(struct hci_conn *hcon, int err)
1863{
1864        struct l2cap_conn *conn = hcon->l2cap_data;
1865        struct l2cap_chan *chan, *l;
1866
1867        if (!conn)
1868                return;
1869
1870        BT_DBG("hcon %p conn %p, err %d", hcon, conn, err);
1871
1872        kfree_skb(conn->rx_skb);
1873
1874        skb_queue_purge(&conn->pending_rx);
1875
1876        /* We can not call flush_work(&conn->pending_rx_work) here since we
1877         * might block if we are running on a worker from the same workqueue
1878         * pending_rx_work is waiting on.
1879         */
1880        if (work_pending(&conn->pending_rx_work))
1881                cancel_work_sync(&conn->pending_rx_work);
1882
1883        if (work_pending(&conn->id_addr_update_work))
1884                cancel_work_sync(&conn->id_addr_update_work);
1885
1886        l2cap_unregister_all_users(conn);
1887
1888        /* Force the connection to be immediately dropped */
1889        hcon->disc_timeout = 0;
1890
1891        mutex_lock(&conn->chan_lock);
1892
1893        /* Kill channels */
1894        list_for_each_entry_safe(chan, l, &conn->chan_l, list) {
1895                l2cap_chan_hold(chan);
1896                l2cap_chan_lock(chan);
1897
1898                l2cap_chan_del(chan, err);
1899
1900                chan->ops->close(chan);
1901
1902                l2cap_chan_unlock(chan);
1903                l2cap_chan_put(chan);
1904        }
1905
1906        mutex_unlock(&conn->chan_lock);
1907
1908        hci_chan_del(conn->hchan);
1909
1910        if (conn->info_state & L2CAP_INFO_FEAT_MASK_REQ_SENT)
1911                cancel_delayed_work_sync(&conn->info_timer);
1912
1913        hcon->l2cap_data = NULL;
1914        conn->hchan = NULL;
1915        l2cap_conn_put(conn);
1916}
1917
1918static void l2cap_conn_free(struct kref *ref)
1919{
1920        struct l2cap_conn *conn = container_of(ref, struct l2cap_conn, ref);
1921
1922        hci_conn_put(conn->hcon);
1923        kfree(conn);
1924}
1925
1926struct l2cap_conn *l2cap_conn_get(struct l2cap_conn *conn)
1927{
1928        kref_get(&conn->ref);
1929        return conn;
1930}
1931EXPORT_SYMBOL(l2cap_conn_get);
1932
1933void l2cap_conn_put(struct l2cap_conn *conn)
1934{
1935        kref_put(&conn->ref, l2cap_conn_free);
1936}
1937EXPORT_SYMBOL(l2cap_conn_put);
1938
1939/* ---- Socket interface ---- */
1940
1941/* Find socket with psm and source / destination bdaddr.
1942 * Returns closest match.
1943 */
1944static struct l2cap_chan *l2cap_global_chan_by_psm(int state, __le16 psm,
1945                                                   bdaddr_t *src,
1946                                                   bdaddr_t *dst,
1947                                                   u8 link_type)
1948{
1949        struct l2cap_chan *c, *c1 = NULL;
1950
1951        read_lock(&chan_list_lock);
1952
1953        list_for_each_entry(c, &chan_list, global_l) {
1954                if (state && c->state != state)
1955                        continue;
1956
1957                if (link_type == ACL_LINK && c->src_type != BDADDR_BREDR)
1958                        continue;
1959
1960                if (link_type == LE_LINK && c->src_type == BDADDR_BREDR)
1961                        continue;
1962
1963                if (c->psm == psm) {
1964                        int src_match, dst_match;
1965                        int src_any, dst_any;
1966
1967                        /* Exact match. */
1968                        src_match = !bacmp(&c->src, src);
1969                        dst_match = !bacmp(&c->dst, dst);
1970                        if (src_match && dst_match) {
1971                                l2cap_chan_hold(c);
1972                                read_unlock(&chan_list_lock);
1973                                return c;
1974                        }
1975
1976                        /* Closest match */
1977                        src_any = !bacmp(&c->src, BDADDR_ANY);
1978                        dst_any = !bacmp(&c->dst, BDADDR_ANY);
1979                        if ((src_match && dst_any) || (src_any && dst_match) ||
1980                            (src_any && dst_any))
1981                                c1 = c;
1982                }
1983        }
1984
1985        if (c1)
1986                l2cap_chan_hold(c1);
1987
1988        read_unlock(&chan_list_lock);
1989
1990        return c1;
1991}
1992
1993static void l2cap_monitor_timeout(struct work_struct *work)
1994{
1995        struct l2cap_chan *chan = container_of(work, struct l2cap_chan,
1996                                               monitor_timer.work);
1997
1998        BT_DBG("chan %p", chan);
1999
2000        l2cap_chan_lock(chan);
2001
2002        if (!chan->conn) {
2003                l2cap_chan_unlock(chan);
2004                l2cap_chan_put(chan);
2005                return;
2006        }
2007
2008        l2cap_tx(chan, NULL, NULL, L2CAP_EV_MONITOR_TO);
2009
2010        l2cap_chan_unlock(chan);
2011        l2cap_chan_put(chan);
2012}
2013
2014static void l2cap_retrans_timeout(struct work_struct *work)
2015{
2016        struct l2cap_chan *chan = container_of(work, struct l2cap_chan,
2017                                               retrans_timer.work);
2018
2019        BT_DBG("chan %p", chan);
2020
2021        l2cap_chan_lock(chan);
2022
2023        if (!chan->conn) {
2024                l2cap_chan_unlock(chan);
2025                l2cap_chan_put(chan);
2026                return;
2027        }
2028
2029        l2cap_tx(chan, NULL, NULL, L2CAP_EV_RETRANS_TO);
2030        l2cap_chan_unlock(chan);
2031        l2cap_chan_put(chan);
2032}
2033
2034static void l2cap_streaming_send(struct l2cap_chan *chan,
2035                                 struct sk_buff_head *skbs)
2036{
2037        struct sk_buff *skb;
2038        struct l2cap_ctrl *control;
2039
2040        BT_DBG("chan %p, skbs %p", chan, skbs);
2041
2042        if (__chan_is_moving(chan))
2043                return;
2044
2045        skb_queue_splice_tail_init(skbs, &chan->tx_q);
2046
2047        while (!skb_queue_empty(&chan->tx_q)) {
2048
2049                skb = skb_dequeue(&chan->tx_q);
2050
2051                bt_cb(skb)->l2cap.retries = 1;
2052                control = &bt_cb(skb)->l2cap;
2053
2054                control->reqseq = 0;
2055                control->txseq = chan->next_tx_seq;
2056
2057                __pack_control(chan, control, skb);
2058
2059                if (chan->fcs == L2CAP_FCS_CRC16) {
2060                        u16 fcs = crc16(0, (u8 *) skb->data, skb->len);
2061                        put_unaligned_le16(fcs, skb_put(skb, L2CAP_FCS_SIZE));
2062                }
2063
2064                l2cap_do_send(chan, skb);
2065
2066                BT_DBG("Sent txseq %u", control->txseq);
2067
2068                chan->next_tx_seq = __next_seq(chan, chan->next_tx_seq);
2069                chan->frames_sent++;
2070        }
2071}
2072
2073static int l2cap_ertm_send(struct l2cap_chan *chan)
2074{
2075        struct sk_buff *skb, *tx_skb;
2076        struct l2cap_ctrl *control;
2077        int sent = 0;
2078
2079        BT_DBG("chan %p", chan);
2080
2081        if (chan->state != BT_CONNECTED)
2082                return -ENOTCONN;
2083
2084        if (test_bit(CONN_REMOTE_BUSY, &chan->conn_state))
2085                return 0;
2086
2087        if (__chan_is_moving(chan))
2088                return 0;
2089
2090        while (chan->tx_send_head &&
2091               chan->unacked_frames < chan->remote_tx_win &&
2092               chan->tx_state == L2CAP_TX_STATE_XMIT) {
2093
2094                skb = chan->tx_send_head;
2095
2096                bt_cb(skb)->l2cap.retries = 1;
2097                control = &bt_cb(skb)->l2cap;
2098
2099                if (test_and_clear_bit(CONN_SEND_FBIT, &chan->conn_state))
2100                        control->final = 1;
2101
2102                control->reqseq = chan->buffer_seq;
2103                chan->last_acked_seq = chan->buffer_seq;
2104                control->txseq = chan->next_tx_seq;
2105
2106                __pack_control(chan, control, skb);
2107
2108                if (chan->fcs == L2CAP_FCS_CRC16) {
2109                        u16 fcs = crc16(0, (u8 *) skb->data, skb->len);
2110                        put_unaligned_le16(fcs, skb_put(skb, L2CAP_FCS_SIZE));
2111                }
2112
2113                /* Clone after data has been modified. Data is assumed to be
2114                   read-only (for locking purposes) on cloned sk_buffs.
2115                 */
2116                tx_skb = skb_clone(skb, GFP_KERNEL);
2117
2118                if (!tx_skb)
2119                        break;
2120
2121                __set_retrans_timer(chan);
2122
2123                chan->next_tx_seq = __next_seq(chan, chan->next_tx_seq);
2124                chan->unacked_frames++;
2125                chan->frames_sent++;
2126                sent++;
2127
2128                if (skb_queue_is_last(&chan->tx_q, skb))
2129                        chan->tx_send_head = NULL;
2130                else
2131                        chan->tx_send_head = skb_queue_next(&chan->tx_q, skb);
2132
2133                l2cap_do_send(chan, tx_skb);
2134                BT_DBG("Sent txseq %u", control->txseq);
2135        }
2136
2137        BT_DBG("Sent %d, %u unacked, %u in ERTM queue", sent,
2138               chan->unacked_frames, skb_queue_len(&chan->tx_q));
2139
2140        return sent;
2141}
2142
2143static void l2cap_ertm_resend(struct l2cap_chan *chan)
2144{
2145        struct l2cap_ctrl control;
2146        struct sk_buff *skb;
2147        struct sk_buff *tx_skb;
2148        u16 seq;
2149
2150        BT_DBG("chan %p", chan);
2151
2152        if (test_bit(CONN_REMOTE_BUSY, &chan->conn_state))
2153                return;
2154
2155        if (__chan_is_moving(chan))
2156                return;
2157
2158        while (chan->retrans_list.head != L2CAP_SEQ_LIST_CLEAR) {
2159                seq = l2cap_seq_list_pop(&chan->retrans_list);
2160
2161                skb = l2cap_ertm_seq_in_queue(&chan->tx_q, seq);
2162                if (!skb) {
2163                        BT_DBG("Error: Can't retransmit seq %d, frame missing",
2164                               seq);
2165                        continue;
2166                }
2167
2168                bt_cb(skb)->l2cap.retries++;
2169                control = bt_cb(skb)->l2cap;
2170
2171                if (chan->max_tx != 0 &&
2172                    bt_cb(skb)->l2cap.retries > chan->max_tx) {
2173                        BT_DBG("Retry limit exceeded (%d)", chan->max_tx);
2174                        l2cap_send_disconn_req(chan, ECONNRESET);
2175                        l2cap_seq_list_clear(&chan->retrans_list);
2176                        break;
2177                }
2178
2179                control.reqseq = chan->buffer_seq;
2180                if (test_and_clear_bit(CONN_SEND_FBIT, &chan->conn_state))
2181                        control.final = 1;
2182                else
2183                        control.final = 0;
2184
2185                if (skb_cloned(skb)) {
2186                        /* Cloned sk_buffs are read-only, so we need a
2187                         * writeable copy
2188                         */
2189                        tx_skb = skb_copy(skb, GFP_KERNEL);
2190                } else {
2191                        tx_skb = skb_clone(skb, GFP_KERNEL);
2192                }
2193
2194                if (!tx_skb) {
2195                        l2cap_seq_list_clear(&chan->retrans_list);
2196                        break;
2197                }
2198
2199                /* Update skb contents */
2200                if (test_bit(FLAG_EXT_CTRL, &chan->flags)) {
2201                        put_unaligned_le32(__pack_extended_control(&control),
2202                                           tx_skb->data + L2CAP_HDR_SIZE);
2203                } else {
2204                        put_unaligned_le16(__pack_enhanced_control(&control),
2205                                           tx_skb->data + L2CAP_HDR_SIZE);
2206                }
2207
2208                /* Update FCS */
2209                if (chan->fcs == L2CAP_FCS_CRC16) {
2210                        u16 fcs = crc16(0, (u8 *) tx_skb->data,
2211                                        tx_skb->len - L2CAP_FCS_SIZE);
2212                        put_unaligned_le16(fcs, skb_tail_pointer(tx_skb) -
2213                                                L2CAP_FCS_SIZE);
2214                }
2215
2216                l2cap_do_send(chan, tx_skb);
2217
2218                BT_DBG("Resent txseq %d", control.txseq);
2219
2220                chan->last_acked_seq = chan->buffer_seq;
2221        }
2222}
2223
2224static void l2cap_retransmit(struct l2cap_chan *chan,
2225                             struct l2cap_ctrl *control)
2226{
2227        BT_DBG("chan %p, control %p", chan, control);
2228
2229        l2cap_seq_list_append(&chan->retrans_list, control->reqseq);
2230        l2cap_ertm_resend(chan);
2231}
2232
2233static void l2cap_retransmit_all(struct l2cap_chan *chan,
2234                                 struct l2cap_ctrl *control)
2235{
2236        struct sk_buff *skb;
2237
2238        BT_DBG("chan %p, control %p", chan, control);
2239
2240        if (control->poll)
2241                set_bit(CONN_SEND_FBIT, &chan->conn_state);
2242
2243        l2cap_seq_list_clear(&chan->retrans_list);
2244
2245        if (test_bit(CONN_REMOTE_BUSY, &chan->conn_state))
2246                return;
2247
2248        if (chan->unacked_frames) {
2249                skb_queue_walk(&chan->tx_q, skb) {
2250                        if (bt_cb(skb)->l2cap.txseq == control->reqseq ||
2251                            skb == chan->tx_send_head)
2252                                break;
2253                }
2254
2255                skb_queue_walk_from(&chan->tx_q, skb) {
2256                        if (skb == chan->tx_send_head)
2257                                break;
2258
2259                        l2cap_seq_list_append(&chan->retrans_list,
2260                                              bt_cb(skb)->l2cap.txseq);
2261                }
2262
2263                l2cap_ertm_resend(chan);
2264        }
2265}
2266
2267static void l2cap_send_ack(struct l2cap_chan *chan)
2268{
2269        struct l2cap_ctrl control;
2270        u16 frames_to_ack = __seq_offset(chan, chan->buffer_seq,
2271                                         chan->last_acked_seq);
2272        int threshold;
2273
2274        BT_DBG("chan %p last_acked_seq %d buffer_seq %d",
2275               chan, chan->last_acked_seq, chan->buffer_seq);
2276
2277        memset(&control, 0, sizeof(control));
2278        control.sframe = 1;
2279
2280        if (test_bit(CONN_LOCAL_BUSY, &chan->conn_state) &&
2281            chan->rx_state == L2CAP_RX_STATE_RECV) {
2282                __clear_ack_timer(chan);
2283                control.super = L2CAP_SUPER_RNR;
2284                control.reqseq = chan->buffer_seq;
2285                l2cap_send_sframe(chan, &control);
2286        } else {
2287                if (!test_bit(CONN_REMOTE_BUSY, &chan->conn_state)) {
2288                        l2cap_ertm_send(chan);
2289                        /* If any i-frames were sent, they included an ack */
2290                        if (chan->buffer_seq == chan->last_acked_seq)
2291                                frames_to_ack = 0;
2292                }
2293
2294                /* Ack now if the window is 3/4ths full.
2295                 * Calculate without mul or div
2296                 */
2297                threshold = chan->ack_win;
2298                threshold += threshold << 1;
2299                threshold >>= 2;
2300
2301                BT_DBG("frames_to_ack %u, threshold %d", frames_to_ack,
2302                       threshold);
2303
2304                if (frames_to_ack >= threshold) {
2305                        __clear_ack_timer(chan);
2306                        control.super = L2CAP_SUPER_RR;
2307                        control.reqseq = chan->buffer_seq;
2308                        l2cap_send_sframe(chan, &control);
2309                        frames_to_ack = 0;
2310                }
2311
2312                if (frames_to_ack)
2313                        __set_ack_timer(chan);
2314        }
2315}
2316
2317static inline int l2cap_skbuff_fromiovec(struct l2cap_chan *chan,
2318                                         struct msghdr *msg, int len,
2319                                         int count, struct sk_buff *skb)
2320{
2321        struct l2cap_conn *conn = chan->conn;
2322        struct sk_buff **frag;
2323        int sent = 0;
2324
2325        if (!copy_from_iter_full(skb_put(skb, count), count, &msg->msg_iter))
2326                return -EFAULT;
2327
2328        sent += count;
2329        len  -= count;
2330
2331        /* Continuation fragments (no L2CAP header) */
2332        frag = &skb_shinfo(skb)->frag_list;
2333        while (len) {
2334                struct sk_buff *tmp;
2335
2336                count = min_t(unsigned int, conn->mtu, len);
2337
2338                tmp = chan->ops->alloc_skb(chan, 0, count,
2339                                           msg->msg_flags & MSG_DONTWAIT);
2340                if (IS_ERR(tmp))
2341                        return PTR_ERR(tmp);
2342
2343                *frag = tmp;
2344
2345                if (!copy_from_iter_full(skb_put(*frag, count), count,
2346                                   &msg->msg_iter))
2347                        return -EFAULT;
2348
2349                sent += count;
2350                len  -= count;
2351
2352                skb->len += (*frag)->len;
2353                skb->data_len += (*frag)->len;
2354
2355                frag = &(*frag)->next;
2356        }
2357
2358        return sent;
2359}
2360
2361static struct sk_buff *l2cap_create_connless_pdu(struct l2cap_chan *chan,
2362                                                 struct msghdr *msg, size_t len)
2363{
2364        struct l2cap_conn *conn = chan->conn;
2365        struct sk_buff *skb;
2366        int err, count, hlen = L2CAP_HDR_SIZE + L2CAP_PSMLEN_SIZE;
2367        struct l2cap_hdr *lh;
2368
2369        BT_DBG("chan %p psm 0x%2.2x len %zu", chan,
2370               __le16_to_cpu(chan->psm), len);
2371
2372        count = min_t(unsigned int, (conn->mtu - hlen), len);
2373
2374        skb = chan->ops->alloc_skb(chan, hlen, count,
2375                                   msg->msg_flags & MSG_DONTWAIT);
2376        if (IS_ERR(skb))
2377                return skb;
2378
2379        /* Create L2CAP header */
2380        lh = skb_put(skb, L2CAP_HDR_SIZE);
2381        lh->cid = cpu_to_le16(chan->dcid);
2382        lh->len = cpu_to_le16(len + L2CAP_PSMLEN_SIZE);
2383        put_unaligned(chan->psm, (__le16 *) skb_put(skb, L2CAP_PSMLEN_SIZE));
2384
2385        err = l2cap_skbuff_fromiovec(chan, msg, len, count, skb);
2386        if (unlikely(err < 0)) {
2387                kfree_skb(skb);
2388                return ERR_PTR(err);
2389        }
2390        return skb;
2391}
2392
2393static struct sk_buff *l2cap_create_basic_pdu(struct l2cap_chan *chan,
2394                                              struct msghdr *msg, size_t len)
2395{
2396        struct l2cap_conn *conn = chan->conn;
2397        struct sk_buff *skb;
2398        int err, count;
2399        struct l2cap_hdr *lh;
2400
2401        BT_DBG("chan %p len %zu", chan, len);
2402
2403        count = min_t(unsigned int, (conn->mtu - L2CAP_HDR_SIZE), len);
2404
2405        skb = chan->ops->alloc_skb(chan, L2CAP_HDR_SIZE, count,
2406                                   msg->msg_flags & MSG_DONTWAIT);
2407        if (IS_ERR(skb))
2408                return skb;
2409
2410        /* Create L2CAP header */
2411        lh = skb_put(skb, L2CAP_HDR_SIZE);
2412        lh->cid = cpu_to_le16(chan->dcid);
2413        lh->len = cpu_to_le16(len);
2414
2415        err = l2cap_skbuff_fromiovec(chan, msg, len, count, skb);
2416        if (unlikely(err < 0)) {
2417                kfree_skb(skb);
2418                return ERR_PTR(err);
2419        }
2420        return skb;
2421}
2422
2423static struct sk_buff *l2cap_create_iframe_pdu(struct l2cap_chan *chan,
2424                                               struct msghdr *msg, size_t len,
2425                                               u16 sdulen)
2426{
2427        struct l2cap_conn *conn = chan->conn;
2428        struct sk_buff *skb;
2429        int err, count, hlen;
2430        struct l2cap_hdr *lh;
2431
2432        BT_DBG("chan %p len %zu", chan, len);
2433
2434        if (!conn)
2435                return ERR_PTR(-ENOTCONN);
2436
2437        hlen = __ertm_hdr_size(chan);
2438
2439        if (sdulen)
2440                hlen += L2CAP_SDULEN_SIZE;
2441
2442        if (chan->fcs == L2CAP_FCS_CRC16)
2443                hlen += L2CAP_FCS_SIZE;
2444
2445        count = min_t(unsigned int, (conn->mtu - hlen), len);
2446
2447        skb = chan->ops->alloc_skb(chan, hlen, count,
2448                                   msg->msg_flags & MSG_DONTWAIT);
2449        if (IS_ERR(skb))
2450                return skb;
2451
2452        /* Create L2CAP header */
2453        lh = skb_put(skb, L2CAP_HDR_SIZE);
2454        lh->cid = cpu_to_le16(chan->dcid);
2455        lh->len = cpu_to_le16(len + (hlen - L2CAP_HDR_SIZE));
2456
2457        /* Control header is populated later */
2458        if (test_bit(FLAG_EXT_CTRL, &chan->flags))
2459                put_unaligned_le32(0, skb_put(skb, L2CAP_EXT_CTRL_SIZE));
2460        else
2461                put_unaligned_le16(0, skb_put(skb, L2CAP_ENH_CTRL_SIZE));
2462
2463        if (sdulen)
2464                put_unaligned_le16(sdulen, skb_put(skb, L2CAP_SDULEN_SIZE));
2465
2466        err = l2cap_skbuff_fromiovec(chan, msg, len, count, skb);
2467        if (unlikely(err < 0)) {
2468                kfree_skb(skb);
2469                return ERR_PTR(err);
2470        }
2471
2472        bt_cb(skb)->l2cap.fcs = chan->fcs;
2473        bt_cb(skb)->l2cap.retries = 0;
2474        return skb;
2475}
2476
2477static int l2cap_segment_sdu(struct l2cap_chan *chan,
2478                             struct sk_buff_head *seg_queue,
2479                             struct msghdr *msg, size_t len)
2480{
2481        struct sk_buff *skb;
2482        u16 sdu_len;
2483        size_t pdu_len;
2484        u8 sar;
2485
2486        BT_DBG("chan %p, msg %p, len %zu", chan, msg, len);
2487
2488        /* It is critical that ERTM PDUs fit in a single HCI fragment,
2489         * so fragmented skbs are not used.  The HCI layer's handling
2490         * of fragmented skbs is not compatible with ERTM's queueing.
2491         */
2492
2493        /* PDU size is derived from the HCI MTU */
2494        pdu_len = chan->conn->mtu;
2495
2496        /* Constrain PDU size for BR/EDR connections */
2497        if (!chan->hs_hcon)
2498                pdu_len = min_t(size_t, pdu_len, L2CAP_BREDR_MAX_PAYLOAD);
2499
2500        /* Adjust for largest possible L2CAP overhead. */
2501        if (chan->fcs)
2502                pdu_len -= L2CAP_FCS_SIZE;
2503
2504        pdu_len -= __ertm_hdr_size(chan);
2505
2506        /* Remote device may have requested smaller PDUs */
2507        pdu_len = min_t(size_t, pdu_len, chan->remote_mps);
2508
2509        if (len <= pdu_len) {
2510                sar = L2CAP_SAR_UNSEGMENTED;
2511                sdu_len = 0;
2512                pdu_len = len;
2513        } else {
2514                sar = L2CAP_SAR_START;
2515                sdu_len = len;
2516        }
2517
2518        while (len > 0) {
2519                skb = l2cap_create_iframe_pdu(chan, msg, pdu_len, sdu_len);
2520
2521                if (IS_ERR(skb)) {
2522                        __skb_queue_purge(seg_queue);
2523                        return PTR_ERR(skb);
2524                }
2525
2526                bt_cb(skb)->l2cap.sar = sar;
2527                __skb_queue_tail(seg_queue, skb);
2528
2529                len -= pdu_len;
2530                if (sdu_len)
2531                        sdu_len = 0;
2532
2533                if (len <= pdu_len) {
2534                        sar = L2CAP_SAR_END;
2535                        pdu_len = len;
2536                } else {
2537                        sar = L2CAP_SAR_CONTINUE;
2538                }
2539        }
2540
2541        return 0;
2542}
2543
2544static struct sk_buff *l2cap_create_le_flowctl_pdu(struct l2cap_chan *chan,
2545                                                   struct msghdr *msg,
2546                                                   size_t len, u16 sdulen)
2547{
2548        struct l2cap_conn *conn = chan->conn;
2549        struct sk_buff *skb;
2550        int err, count, hlen;
2551        struct l2cap_hdr *lh;
2552
2553        BT_DBG("chan %p len %zu", chan, len);
2554
2555        if (!conn)
2556                return ERR_PTR(-ENOTCONN);
2557
2558        hlen = L2CAP_HDR_SIZE;
2559
2560        if (sdulen)
2561                hlen += L2CAP_SDULEN_SIZE;
2562
2563        count = min_t(unsigned int, (conn->mtu - hlen), len);
2564
2565        skb = chan->ops->alloc_skb(chan, hlen, count,
2566                                   msg->msg_flags & MSG_DONTWAIT);
2567        if (IS_ERR(skb))
2568                return skb;
2569
2570        /* Create L2CAP header */
2571        lh = skb_put(skb, L2CAP_HDR_SIZE);
2572        lh->cid = cpu_to_le16(chan->dcid);
2573        lh->len = cpu_to_le16(len + (hlen - L2CAP_HDR_SIZE));
2574
2575        if (sdulen)
2576                put_unaligned_le16(sdulen, skb_put(skb, L2CAP_SDULEN_SIZE));
2577
2578        err = l2cap_skbuff_fromiovec(chan, msg, len, count, skb);
2579        if (unlikely(err < 0)) {
2580                kfree_skb(skb);
2581                return ERR_PTR(err);
2582        }
2583
2584        return skb;
2585}
2586
2587static int l2cap_segment_le_sdu(struct l2cap_chan *chan,
2588                                struct sk_buff_head *seg_queue,
2589                                struct msghdr *msg, size_t len)
2590{
2591        struct sk_buff *skb;
2592        size_t pdu_len;
2593        u16 sdu_len;
2594
2595        BT_DBG("chan %p, msg %p, len %zu", chan, msg, len);
2596
2597        sdu_len = len;
2598        pdu_len = chan->remote_mps - L2CAP_SDULEN_SIZE;
2599
2600        while (len > 0) {
2601                if (len <= pdu_len)
2602                        pdu_len = len;
2603
2604                skb = l2cap_create_le_flowctl_pdu(chan, msg, pdu_len, sdu_len);
2605                if (IS_ERR(skb)) {
2606                        __skb_queue_purge(seg_queue);
2607                        return PTR_ERR(skb);
2608                }
2609
2610                __skb_queue_tail(seg_queue, skb);
2611
2612                len -= pdu_len;
2613
2614                if (sdu_len) {
2615                        sdu_len = 0;
2616                        pdu_len += L2CAP_SDULEN_SIZE;
2617                }
2618        }
2619
2620        return 0;
2621}
2622
2623static void l2cap_le_flowctl_send(struct l2cap_chan *chan)
2624{
2625        int sent = 0;
2626
2627        BT_DBG("chan %p", chan);
2628
2629        while (chan->tx_credits && !skb_queue_empty(&chan->tx_q)) {
2630                l2cap_do_send(chan, skb_dequeue(&chan->tx_q));
2631                chan->tx_credits--;
2632                sent++;
2633        }
2634
2635        BT_DBG("Sent %d credits %u queued %u", sent, chan->tx_credits,
2636               skb_queue_len(&chan->tx_q));
2637}
2638
2639int l2cap_chan_send(struct l2cap_chan *chan, struct msghdr *msg, size_t len)
2640{
2641        struct sk_buff *skb;
2642        int err;
2643        struct sk_buff_head seg_queue;
2644
2645        if (!chan->conn)
2646                return -ENOTCONN;
2647
2648        /* Connectionless channel */
2649        if (chan->chan_type == L2CAP_CHAN_CONN_LESS) {
2650                skb = l2cap_create_connless_pdu(chan, msg, len);
2651                if (IS_ERR(skb))
2652                        return PTR_ERR(skb);
2653
2654                /* Channel lock is released before requesting new skb and then
2655                 * reacquired thus we need to recheck channel state.
2656                 */
2657                if (chan->state != BT_CONNECTED) {
2658                        kfree_skb(skb);
2659                        return -ENOTCONN;
2660                }
2661
2662                l2cap_do_send(chan, skb);
2663                return len;
2664        }
2665
2666        switch (chan->mode) {
2667        case L2CAP_MODE_LE_FLOWCTL:
2668        case L2CAP_MODE_EXT_FLOWCTL:
2669                /* Check outgoing MTU */
2670                if (len > chan->omtu)
2671                        return -EMSGSIZE;
2672
2673                __skb_queue_head_init(&seg_queue);
2674
2675                err = l2cap_segment_le_sdu(chan, &seg_queue, msg, len);
2676
2677                if (chan->state != BT_CONNECTED) {
2678                        __skb_queue_purge(&seg_queue);
2679                        err = -ENOTCONN;
2680                }
2681
2682                if (err)
2683                        return err;
2684
2685                skb_queue_splice_tail_init(&seg_queue, &chan->tx_q);
2686
2687                l2cap_le_flowctl_send(chan);
2688
2689                if (!chan->tx_credits)
2690                        chan->ops->suspend(chan);
2691
2692                err = len;
2693
2694                break;
2695
2696        case L2CAP_MODE_BASIC:
2697                /* Check outgoing MTU */
2698                if (len > chan->omtu)
2699                        return -EMSGSIZE;
2700
2701                /* Create a basic PDU */
2702                skb = l2cap_create_basic_pdu(chan, msg, len);
2703                if (IS_ERR(skb))
2704                        return PTR_ERR(skb);
2705
2706                /* Channel lock is released before requesting new skb and then
2707                 * reacquired thus we need to recheck channel state.
2708                 */
2709                if (chan->state != BT_CONNECTED) {
2710                        kfree_skb(skb);
2711                        return -ENOTCONN;
2712                }
2713
2714                l2cap_do_send(chan, skb);
2715                err = len;
2716                break;
2717
2718        case L2CAP_MODE_ERTM:
2719        case L2CAP_MODE_STREAMING:
2720                /* Check outgoing MTU */
2721                if (len > chan->omtu) {
2722                        err = -EMSGSIZE;
2723                        break;
2724                }
2725
2726                __skb_queue_head_init(&seg_queue);
2727
2728                /* Do segmentation before calling in to the state machine,
2729                 * since it's possible to block while waiting for memory
2730                 * allocation.
2731                 */
2732                err = l2cap_segment_sdu(chan, &seg_queue, msg, len);
2733
2734                /* The channel could have been closed while segmenting,
2735                 * check that it is still connected.
2736                 */
2737                if (chan->state != BT_CONNECTED) {
2738                        __skb_queue_purge(&seg_queue);
2739                        err = -ENOTCONN;
2740                }
2741
2742                if (err)
2743                        break;
2744
2745                if (chan->mode == L2CAP_MODE_ERTM)
2746                        l2cap_tx(chan, NULL, &seg_queue, L2CAP_EV_DATA_REQUEST);
2747                else
2748                        l2cap_streaming_send(chan, &seg_queue);
2749
2750                err = len;
2751
2752                /* If the skbs were not queued for sending, they'll still be in
2753                 * seg_queue and need to be purged.
2754                 */
2755                __skb_queue_purge(&seg_queue);
2756                break;
2757
2758        default:
2759                BT_DBG("bad state %1.1x", chan->mode);
2760                err = -EBADFD;
2761        }
2762
2763        return err;
2764}
2765EXPORT_SYMBOL_GPL(l2cap_chan_send);
2766
2767static void l2cap_send_srej(struct l2cap_chan *chan, u16 txseq)
2768{
2769        struct l2cap_ctrl control;
2770        u16 seq;
2771
2772        BT_DBG("chan %p, txseq %u", chan, txseq);
2773
2774        memset(&control, 0, sizeof(control));
2775        control.sframe = 1;
2776        control.super = L2CAP_SUPER_SREJ;
2777
2778        for (seq = chan->expected_tx_seq; seq != txseq;
2779             seq = __next_seq(chan, seq)) {
2780                if (!l2cap_ertm_seq_in_queue(&chan->srej_q, seq)) {
2781                        control.reqseq = seq;
2782                        l2cap_send_sframe(chan, &control);
2783                        l2cap_seq_list_append(&chan->srej_list, seq);
2784                }
2785        }
2786
2787        chan->expected_tx_seq = __next_seq(chan, txseq);
2788}
2789
2790static void l2cap_send_srej_tail(struct l2cap_chan *chan)
2791{
2792        struct l2cap_ctrl control;
2793
2794        BT_DBG("chan %p", chan);
2795
2796        if (chan->srej_list.tail == L2CAP_SEQ_LIST_CLEAR)
2797                return;
2798
2799        memset(&control, 0, sizeof(control));
2800        control.sframe = 1;
2801        control.super = L2CAP_SUPER_SREJ;
2802        control.reqseq = chan->srej_list.tail;
2803        l2cap_send_sframe(chan, &control);
2804}
2805
2806static void l2cap_send_srej_list(struct l2cap_chan *chan, u16 txseq)
2807{
2808        struct l2cap_ctrl control;
2809        u16 initial_head;
2810        u16 seq;
2811
2812        BT_DBG("chan %p, txseq %u", chan, txseq);
2813
2814        memset(&control, 0, sizeof(control));
2815        control.sframe = 1;
2816        control.super = L2CAP_SUPER_SREJ;
2817
2818        /* Capture initial list head to allow only one pass through the list. */
2819        initial_head = chan->srej_list.head;
2820
2821        do {
2822                seq = l2cap_seq_list_pop(&chan->srej_list);
2823                if (seq == txseq || seq == L2CAP_SEQ_LIST_CLEAR)
2824                        break;
2825
2826                control.reqseq = seq;
2827                l2cap_send_sframe(chan, &control);
2828                l2cap_seq_list_append(&chan->srej_list, seq);
2829        } while (chan->srej_list.head != initial_head);
2830}
2831
2832static void l2cap_process_reqseq(struct l2cap_chan *chan, u16 reqseq)
2833{
2834        struct sk_buff *acked_skb;
2835        u16 ackseq;
2836
2837        BT_DBG("chan %p, reqseq %u", chan, reqseq);
2838
2839        if (chan->unacked_frames == 0 || reqseq == chan->expected_ack_seq)
2840                return;
2841
2842        BT_DBG("expected_ack_seq %u, unacked_frames %u",
2843               chan->expected_ack_seq, chan->unacked_frames);
2844
2845        for (ackseq = chan->expected_ack_seq; ackseq != reqseq;
2846             ackseq = __next_seq(chan, ackseq)) {
2847
2848                acked_skb = l2cap_ertm_seq_in_queue(&chan->tx_q, ackseq);
2849                if (acked_skb) {
2850                        skb_unlink(acked_skb, &chan->tx_q);
2851                        kfree_skb(acked_skb);
2852                        chan->unacked_frames--;
2853                }
2854        }
2855
2856        chan->expected_ack_seq = reqseq;
2857
2858        if (chan->unacked_frames == 0)
2859                __clear_retrans_timer(chan);
2860
2861        BT_DBG("unacked_frames %u", chan->unacked_frames);
2862}
2863
2864static void l2cap_abort_rx_srej_sent(struct l2cap_chan *chan)
2865{
2866        BT_DBG("chan %p", chan);
2867
2868        chan->expected_tx_seq = chan->buffer_seq;
2869        l2cap_seq_list_clear(&chan->srej_list);
2870        skb_queue_purge(&chan->srej_q);
2871        chan->rx_state = L2CAP_RX_STATE_RECV;
2872}
2873
2874static void l2cap_tx_state_xmit(struct l2cap_chan *chan,
2875                                struct l2cap_ctrl *control,
2876                                struct sk_buff_head *skbs, u8 event)
2877{
2878        BT_DBG("chan %p, control %p, skbs %p, event %d", chan, control, skbs,
2879               event);
2880
2881        switch (event) {
2882        case L2CAP_EV_DATA_REQUEST:
2883                if (chan->tx_send_head == NULL)
2884                        chan->tx_send_head = skb_peek(skbs);
2885
2886                skb_queue_splice_tail_init(skbs, &chan->tx_q);
2887                l2cap_ertm_send(chan);
2888                break;
2889        case L2CAP_EV_LOCAL_BUSY_DETECTED:
2890                BT_DBG("Enter LOCAL_BUSY");
2891                set_bit(CONN_LOCAL_BUSY, &chan->conn_state);
2892
2893                if (chan->rx_state == L2CAP_RX_STATE_SREJ_SENT) {
2894                        /* The SREJ_SENT state must be aborted if we are to
2895                         * enter the LOCAL_BUSY state.
2896                         */
2897                        l2cap_abort_rx_srej_sent(chan);
2898                }
2899
2900                l2cap_send_ack(chan);
2901
2902                break;
2903        case L2CAP_EV_LOCAL_BUSY_CLEAR:
2904                BT_DBG("Exit LOCAL_BUSY");
2905                clear_bit(CONN_LOCAL_BUSY, &chan->conn_state);
2906
2907                if (test_bit(CONN_RNR_SENT, &chan->conn_state)) {
2908                        struct l2cap_ctrl local_control;
2909
2910                        memset(&local_control, 0, sizeof(local_control));
2911                        local_control.sframe = 1;
2912                        local_control.super = L2CAP_SUPER_RR;
2913                        local_control.poll = 1;
2914                        local_control.reqseq = chan->buffer_seq;
2915                        l2cap_send_sframe(chan, &local_control);
2916
2917                        chan->retry_count = 1;
2918                        __set_monitor_timer(chan);
2919                        chan->tx_state = L2CAP_TX_STATE_WAIT_F;
2920                }
2921                break;
2922        case L2CAP_EV_RECV_REQSEQ_AND_FBIT:
2923                l2cap_process_reqseq(chan, control->reqseq);
2924                break;
2925        case L2CAP_EV_EXPLICIT_POLL:
2926                l2cap_send_rr_or_rnr(chan, 1);
2927                chan->retry_count = 1;
2928                __set_monitor_timer(chan);
2929                __clear_ack_timer(chan);
2930                chan->tx_state = L2CAP_TX_STATE_WAIT_F;
2931                break;
2932        case L2CAP_EV_RETRANS_TO:
2933                l2cap_send_rr_or_rnr(chan, 1);
2934                chan->retry_count = 1;
2935                __set_monitor_timer(chan);
2936                chan->tx_state = L2CAP_TX_STATE_WAIT_F;
2937                break;
2938        case L2CAP_EV_RECV_FBIT:
2939                /* Nothing to process */
2940                break;
2941        default:
2942                break;
2943        }
2944}
2945
2946static void l2cap_tx_state_wait_f(struct l2cap_chan *chan,
2947                                  struct l2cap_ctrl *control,
2948                                  struct sk_buff_head *skbs, u8 event)
2949{
2950        BT_DBG("chan %p, control %p, skbs %p, event %d", chan, control, skbs,
2951               event);
2952
2953        switch (event) {
2954        case L2CAP_EV_DATA_REQUEST:
2955                if (chan->tx_send_head == NULL)
2956                        chan->tx_send_head = skb_peek(skbs);
2957                /* Queue data, but don't send. */
2958                skb_queue_splice_tail_init(skbs, &chan->tx_q);
2959                break;
2960        case L2CAP_EV_LOCAL_BUSY_DETECTED:
2961                BT_DBG("Enter LOCAL_BUSY");
2962                set_bit(CONN_LOCAL_BUSY, &chan->conn_state);
2963
2964                if (chan->rx_state == L2CAP_RX_STATE_SREJ_SENT) {
2965                        /* The SREJ_SENT state must be aborted if we are to
2966                         * enter the LOCAL_BUSY state.
2967                         */
2968                        l2cap_abort_rx_srej_sent(chan);
2969                }
2970
2971                l2cap_send_ack(chan);
2972
2973                break;
2974        case L2CAP_EV_LOCAL_BUSY_CLEAR:
2975                BT_DBG("Exit LOCAL_BUSY");
2976                clear_bit(CONN_LOCAL_BUSY, &chan->conn_state);
2977
2978                if (test_bit(CONN_RNR_SENT, &chan->conn_state)) {
2979                        struct l2cap_ctrl local_control;
2980                        memset(&local_control, 0, sizeof(local_control));
2981                        local_control.sframe = 1;
2982                        local_control.super = L2CAP_SUPER_RR;
2983                        local_control.poll = 1;
2984                        local_control.reqseq = chan->buffer_seq;
2985                        l2cap_send_sframe(chan, &local_control);
2986
2987                        chan->retry_count = 1;
2988                        __set_monitor_timer(chan);
2989                        chan->tx_state = L2CAP_TX_STATE_WAIT_F;
2990                }
2991                break;
2992        case L2CAP_EV_RECV_REQSEQ_AND_FBIT:
2993                l2cap_process_reqseq(chan, control->reqseq);
2994                fallthrough;
2995
2996        case L2CAP_EV_RECV_FBIT:
2997                if (control && control->final) {
2998                        __clear_monitor_timer(chan);
2999                        if (chan->unacked_frames > 0)
3000                                __set_retrans_timer(chan);
3001                        chan->retry_count = 0;
3002                        chan->tx_state = L2CAP_TX_STATE_XMIT;
3003                        BT_DBG("recv fbit tx_state 0x2.2%x", chan->tx_state);
3004                }
3005                break;
3006        case L2CAP_EV_EXPLICIT_POLL:
3007                /* Ignore */
3008                break;
3009        case L2CAP_EV_MONITOR_TO:
3010                if (chan->max_tx == 0 || chan->retry_count < chan->max_tx) {
3011                        l2cap_send_rr_or_rnr(chan, 1);
3012                        __set_monitor_timer(chan);
3013                        chan->retry_count++;
3014                } else {
3015                        l2cap_send_disconn_req(chan, ECONNABORTED);
3016                }
3017                break;
3018        default:
3019                break;
3020        }
3021}
3022
3023static void l2cap_tx(struct l2cap_chan *chan, struct l2cap_ctrl *control,
3024                     struct sk_buff_head *skbs, u8 event)
3025{
3026        BT_DBG("chan %p, control %p, skbs %p, event %d, state %d",
3027               chan, control, skbs, event, chan->tx_state);
3028
3029        switch (chan->tx_state) {
3030        case L2CAP_TX_STATE_XMIT:
3031                l2cap_tx_state_xmit(chan, control, skbs, event);
3032                break;
3033        case L2CAP_TX_STATE_WAIT_F:
3034                l2cap_tx_state_wait_f(chan, control, skbs, event);
3035                break;
3036        default:
3037                /* Ignore event */
3038                break;
3039        }
3040}
3041
3042static void l2cap_pass_to_tx(struct l2cap_chan *chan,
3043                             struct l2cap_ctrl *control)
3044{
3045        BT_DBG("chan %p, control %p", chan, control);
3046        l2cap_tx(chan, control, NULL, L2CAP_EV_RECV_REQSEQ_AND_FBIT);
3047}
3048
3049static void l2cap_pass_to_tx_fbit(struct l2cap_chan *chan,
3050                                  struct l2cap_ctrl *control)
3051{
3052        BT_DBG("chan %p, control %p", chan, control);
3053        l2cap_tx(chan, control, NULL, L2CAP_EV_RECV_FBIT);
3054}
3055
3056/* Copy frame to all raw sockets on that connection */
3057static void l2cap_raw_recv(struct l2cap_conn *conn, struct sk_buff *skb)
3058{
3059        struct sk_buff *nskb;
3060        struct l2cap_chan *chan;
3061
3062        BT_DBG("conn %p", conn);
3063
3064        mutex_lock(&conn->chan_lock);
3065
3066        list_for_each_entry(chan, &conn->chan_l, list) {
3067                if (chan->chan_type != L2CAP_CHAN_RAW)
3068                        continue;
3069
3070                /* Don't send frame to the channel it came from */
3071                if (bt_cb(skb)->l2cap.chan == chan)
3072                        continue;
3073
3074                nskb = skb_clone(skb, GFP_KERNEL);
3075                if (!nskb)
3076                        continue;
3077                if (chan->ops->recv(chan, nskb))
3078                        kfree_skb(nskb);
3079        }
3080
3081        mutex_unlock(&conn->chan_lock);
3082}
3083
3084/* ---- L2CAP signalling commands ---- */
3085static struct sk_buff *l2cap_build_cmd(struct l2cap_conn *conn, u8 code,
3086                                       u8 ident, u16 dlen, void *data)
3087{
3088        struct sk_buff *skb, **frag;
3089        struct l2cap_cmd_hdr *cmd;
3090        struct l2cap_hdr *lh;
3091        int len, count;
3092
3093        BT_DBG("conn %p, code 0x%2.2x, ident 0x%2.2x, len %u",
3094               conn, code, ident, dlen);
3095
3096        if (conn->mtu < L2CAP_HDR_SIZE + L2CAP_CMD_HDR_SIZE)
3097                return NULL;
3098
3099        len = L2CAP_HDR_SIZE + L2CAP_CMD_HDR_SIZE + dlen;
3100        count = min_t(unsigned int, conn->mtu, len);
3101
3102        skb = bt_skb_alloc(count, GFP_KERNEL);
3103        if (!skb)
3104                return NULL;
3105
3106        lh = skb_put(skb, L2CAP_HDR_SIZE);
3107        lh->len = cpu_to_le16(L2CAP_CMD_HDR_SIZE + dlen);
3108
3109        if (conn->hcon->type == LE_LINK)
3110                lh->cid = cpu_to_le16(L2CAP_CID_LE_SIGNALING);
3111        else
3112                lh->cid = cpu_to_le16(L2CAP_CID_SIGNALING);
3113
3114        cmd = skb_put(skb, L2CAP_CMD_HDR_SIZE);
3115        cmd->code  = code;
3116        cmd->ident = ident;
3117        cmd->len   = cpu_to_le16(dlen);
3118
3119        if (dlen) {
3120                count -= L2CAP_HDR_SIZE + L2CAP_CMD_HDR_SIZE;
3121                skb_put_data(skb, data, count);
3122                data += count;
3123        }
3124
3125        len -= skb->len;
3126
3127        /* Continuation fragments (no L2CAP header) */
3128        frag = &skb_shinfo(skb)->frag_list;
3129        while (len) {
3130                count = min_t(unsigned int, conn->mtu, len);
3131
3132                *frag = bt_skb_alloc(count, GFP_KERNEL);
3133                if (!*frag)
3134                        goto fail;
3135
3136                skb_put_data(*frag, data, count);
3137
3138                len  -= count;
3139                data += count;
3140
3141                frag = &(*frag)->next;
3142        }
3143
3144        return skb;
3145
3146fail:
3147        kfree_skb(skb);
3148        return NULL;
3149}
3150
3151static inline int l2cap_get_conf_opt(void **ptr, int *type, int *olen,
3152                                     unsigned long *val)
3153{
3154        struct l2cap_conf_opt *opt = *ptr;
3155        int len;
3156
3157        len = L2CAP_CONF_OPT_SIZE + opt->len;
3158        *ptr += len;
3159
3160        *type = opt->type;
3161        *olen = opt->len;
3162
3163        switch (opt->len) {
3164        case 1:
3165                *val = *((u8 *) opt->val);
3166                break;
3167
3168        case 2:
3169                *val = get_unaligned_le16(opt->val);
3170                break;
3171
3172        case 4:
3173                *val = get_unaligned_le32(opt->val);
3174                break;
3175
3176        default:
3177                *val = (unsigned long) opt->val;
3178                break;
3179        }
3180
3181        BT_DBG("type 0x%2.2x len %u val 0x%lx", *type, opt->len, *val);
3182        return len;
3183}
3184
3185static void l2cap_add_conf_opt(void **ptr, u8 type, u8 len, unsigned long val, size_t size)
3186{
3187        struct l2cap_conf_opt *opt = *ptr;
3188
3189        BT_DBG("type 0x%2.2x len %u val 0x%lx", type, len, val);
3190
3191        if (size < L2CAP_CONF_OPT_SIZE + len)
3192                return;
3193
3194        opt->type = type;
3195        opt->len  = len;
3196
3197        switch (len) {
3198        case 1:
3199                *((u8 *) opt->val)  = val;
3200                break;
3201
3202        case 2:
3203                put_unaligned_le16(val, opt->val);
3204                break;
3205
3206        case 4:
3207                put_unaligned_le32(val, opt->val);
3208                break;
3209
3210        default:
3211                memcpy(opt->val, (void *) val, len);
3212                break;
3213        }
3214
3215        *ptr += L2CAP_CONF_OPT_SIZE + len;
3216}
3217
3218static void l2cap_add_opt_efs(void **ptr, struct l2cap_chan *chan, size_t size)
3219{
3220        struct l2cap_conf_efs efs;
3221
3222        switch (chan->mode) {
3223        case L2CAP_MODE_ERTM:
3224                efs.id          = chan->local_id;
3225                efs.stype       = chan->local_stype;
3226                efs.msdu        = cpu_to_le16(chan->local_msdu);
3227                efs.sdu_itime   = cpu_to_le32(chan->local_sdu_itime);
3228                efs.acc_lat     = cpu_to_le32(L2CAP_DEFAULT_ACC_LAT);
3229                efs.flush_to    = cpu_to_le32(L2CAP_EFS_DEFAULT_FLUSH_TO);
3230                break;
3231
3232        case L2CAP_MODE_STREAMING:
3233                efs.id          = 1;
3234                efs.stype       = L2CAP_SERV_BESTEFFORT;
3235                efs.msdu        = cpu_to_le16(chan->local_msdu);
3236                efs.sdu_itime   = cpu_to_le32(chan->local_sdu_itime);
3237                efs.acc_lat     = 0;
3238                efs.flush_to    = 0;
3239                break;
3240
3241        default:
3242                return;
3243        }
3244
3245        l2cap_add_conf_opt(ptr, L2CAP_CONF_EFS, sizeof(efs),
3246                           (unsigned long) &efs, size);
3247}
3248
3249static void l2cap_ack_timeout(struct work_struct *work)
3250{
3251        struct l2cap_chan *chan = container_of(work, struct l2cap_chan,
3252                                               ack_timer.work);
3253        u16 frames_to_ack;
3254
3255        BT_DBG("chan %p", chan);
3256
3257        l2cap_chan_lock(chan);
3258
3259        frames_to_ack = __seq_offset(chan, chan->buffer_seq,
3260                                     chan->last_acked_seq);
3261
3262        if (frames_to_ack)
3263                l2cap_send_rr_or_rnr(chan, 0);
3264
3265        l2cap_chan_unlock(chan);
3266        l2cap_chan_put(chan);
3267}
3268
3269int l2cap_ertm_init(struct l2cap_chan *chan)
3270{
3271        int err;
3272
3273        chan->next_tx_seq = 0;
3274        chan->expected_tx_seq = 0;
3275        chan->expected_ack_seq = 0;
3276        chan->unacked_frames = 0;
3277        chan->buffer_seq = 0;
3278        chan->frames_sent = 0;
3279        chan->last_acked_seq = 0;
3280        chan->sdu = NULL;
3281        chan->sdu_last_frag = NULL;
3282        chan->sdu_len = 0;
3283
3284        skb_queue_head_init(&chan->tx_q);
3285
3286        chan->local_amp_id = AMP_ID_BREDR;
3287        chan->move_id = AMP_ID_BREDR;
3288        chan->move_state = L2CAP_MOVE_STABLE;
3289        chan->move_role = L2CAP_MOVE_ROLE_NONE;
3290
3291        if (chan->mode != L2CAP_MODE_ERTM)
3292                return 0;
3293
3294        chan->rx_state = L2CAP_RX_STATE_RECV;
3295        chan->tx_state = L2CAP_TX_STATE_XMIT;
3296
3297        INIT_DELAYED_WORK(&chan->retrans_timer, l2cap_retrans_timeout);
3298        INIT_DELAYED_WORK(&chan->monitor_timer, l2cap_monitor_timeout);
3299        INIT_DELAYED_WORK(&chan->ack_timer, l2cap_ack_timeout);
3300
3301        skb_queue_head_init(&chan->srej_q);
3302
3303        err = l2cap_seq_list_init(&chan->srej_list, chan->tx_win);
3304        if (err < 0)
3305                return err;
3306
3307        err = l2cap_seq_list_init(&chan->retrans_list, chan->remote_tx_win);
3308        if (err < 0)
3309                l2cap_seq_list_free(&chan->srej_list);
3310
3311        return err;
3312}
3313
3314static inline __u8 l2cap_select_mode(__u8 mode, __u16 remote_feat_mask)
3315{
3316        switch (mode) {
3317        case L2CAP_MODE_STREAMING:
3318        case L2CAP_MODE_ERTM:
3319                if (l2cap_mode_supported(mode, remote_feat_mask))
3320                        return mode;
3321                fallthrough;
3322        default:
3323                return L2CAP_MODE_BASIC;
3324        }
3325}
3326
3327static inline bool __l2cap_ews_supported(struct l2cap_conn *conn)
3328{
3329        return ((conn->local_fixed_chan & L2CAP_FC_A2MP) &&
3330                (conn->feat_mask & L2CAP_FEAT_EXT_WINDOW));
3331}
3332
3333static inline bool __l2cap_efs_supported(struct l2cap_conn *conn)
3334{
3335        return ((conn->local_fixed_chan & L2CAP_FC_A2MP) &&
3336                (conn->feat_mask & L2CAP_FEAT_EXT_FLOW));
3337}
3338
3339static void __l2cap_set_ertm_timeouts(struct l2cap_chan *chan,
3340                                      struct l2cap_conf_rfc *rfc)
3341{
3342        if (chan->local_amp_id != AMP_ID_BREDR && chan->hs_hcon) {
3343                u64 ertm_to = chan->hs_hcon->hdev->amp_be_flush_to;
3344
3345                /* Class 1 devices have must have ERTM timeouts
3346                 * exceeding the Link Supervision Timeout.  The
3347                 * default Link Supervision Timeout for AMP
3348                 * controllers is 10 seconds.
3349                 *
3350                 * Class 1 devices use 0xffffffff for their
3351                 * best-effort flush timeout, so the clamping logic
3352                 * will result in a timeout that meets the above
3353                 * requirement.  ERTM timeouts are 16-bit values, so
3354                 * the maximum timeout is 65.535 seconds.
3355                 */
3356
3357                /* Convert timeout to milliseconds and round */
3358                ertm_to = DIV_ROUND_UP_ULL(ertm_to, 1000);
3359
3360                /* This is the recommended formula for class 2 devices
3361                 * that start ERTM timers when packets are sent to the
3362                 * controller.
3363                 */
3364                ertm_to = 3 * ertm_to + 500;
3365
3366                if (ertm_to > 0xffff)
3367                        ertm_to = 0xffff;
3368
3369                rfc->retrans_timeout = cpu_to_le16((u16) ertm_to);
3370                rfc->monitor_timeout = rfc->retrans_timeout;
3371        } else {
3372                rfc->retrans_timeout = cpu_to_le16(L2CAP_DEFAULT_RETRANS_TO);
3373                rfc->monitor_timeout = cpu_to_le16(L2CAP_DEFAULT_MONITOR_TO);
3374        }
3375}
3376
3377static inline void l2cap_txwin_setup(struct l2cap_chan *chan)
3378{
3379        if (chan->tx_win > L2CAP_DEFAULT_TX_WINDOW &&
3380            __l2cap_ews_supported(chan->conn)) {
3381                /* use extended control field */
3382                set_bit(FLAG_EXT_CTRL, &chan->flags);
3383                chan->tx_win_max = L2CAP_DEFAULT_EXT_WINDOW;
3384        } else {
3385                chan->tx_win = min_t(u16, chan->tx_win,
3386                                     L2CAP_DEFAULT_TX_WINDOW);
3387                chan->tx_win_max = L2CAP_DEFAULT_TX_WINDOW;
3388        }
3389        chan->ack_win = chan->tx_win;
3390}
3391
3392static void l2cap_mtu_auto(struct l2cap_chan *chan)
3393{
3394        struct hci_conn *conn = chan->conn->hcon;
3395
3396        chan->imtu = L2CAP_DEFAULT_MIN_MTU;
3397
3398        /* The 2-DH1 packet has between 2 and 56 information bytes
3399         * (including the 2-byte payload header)
3400         */
3401        if (!(conn->pkt_type & HCI_2DH1))
3402                chan->imtu = 54;
3403
3404        /* The 3-DH1 packet has between 2 and 85 information bytes
3405         * (including the 2-byte payload header)
3406         */
3407        if (!(conn->pkt_type & HCI_3DH1))
3408                chan->imtu = 83;
3409
3410        /* The 2-DH3 packet has between 2 and 369 information bytes
3411         * (including the 2-byte payload header)
3412         */
3413        if (!(conn->pkt_type & HCI_2DH3))
3414                chan->imtu = 367;
3415
3416        /* The 3-DH3 packet has between 2 and 554 information bytes
3417         * (including the 2-byte payload header)
3418         */
3419        if (!(conn->pkt_type & HCI_3DH3))
3420                chan->imtu = 552;
3421
3422        /* The 2-DH5 packet has between 2 and 681 information bytes
3423         * (including the 2-byte payload header)
3424         */
3425        if (!(conn->pkt_type & HCI_2DH5))
3426                chan->imtu = 679;
3427
3428        /* The 3-DH5 packet has between 2 and 1023 information bytes
3429         * (including the 2-byte payload header)
3430         */
3431        if (!(conn->pkt_type & HCI_3DH5))
3432                chan->imtu = 1021;
3433}
3434
3435static int l2cap_build_conf_req(struct l2cap_chan *chan, void *data, size_t data_size)
3436{
3437        struct l2cap_conf_req *req = data;
3438        struct l2cap_conf_rfc rfc = { .mode = chan->mode };
3439        void *ptr = req->data;
3440        void *endptr = data + data_size;
3441        u16 size;
3442
3443        BT_DBG("chan %p", chan);
3444
3445        if (chan->num_conf_req || chan->num_conf_rsp)
3446                goto done;
3447
3448        switch (chan->mode) {
3449        case L2CAP_MODE_STREAMING:
3450        case L2CAP_MODE_ERTM:
3451                if (test_bit(CONF_STATE2_DEVICE, &chan->conf_state))
3452                        break;
3453
3454                if (__l2cap_efs_supported(chan->conn))
3455                        set_bit(FLAG_EFS_ENABLE, &chan->flags);
3456
3457                fallthrough;
3458        default:
3459                chan->mode = l2cap_select_mode(rfc.mode, chan->conn->feat_mask);
3460                break;
3461        }
3462
3463done:
3464        if (chan->imtu != L2CAP_DEFAULT_MTU) {
3465                if (!chan->imtu)
3466                        l2cap_mtu_auto(chan);
3467                l2cap_add_conf_opt(&ptr, L2CAP_CONF_MTU, 2, chan->imtu,
3468                                   endptr - ptr);
3469        }
3470
3471        switch (chan->mode) {
3472        case L2CAP_MODE_BASIC:
3473                if (disable_ertm)
3474                        break;
3475
3476                if (!(chan->conn->feat_mask & L2CAP_FEAT_ERTM) &&
3477                    !(chan->conn->feat_mask & L2CAP_FEAT_STREAMING))
3478                        break;
3479
3480                rfc.mode            = L2CAP_MODE_BASIC;
3481                rfc.txwin_size      = 0;
3482                rfc.max_transmit    = 0;
3483                rfc.retrans_timeout = 0;
3484                rfc.monitor_timeout = 0;
3485                rfc.max_pdu_size    = 0;
3486
3487                l2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC, sizeof(rfc),
3488                                   (unsigned long) &rfc, endptr - ptr);
3489                break;
3490
3491        case L2CAP_MODE_ERTM:
3492                rfc.mode            = L2CAP_MODE_ERTM;
3493                rfc.max_transmit    = chan->max_tx;
3494
3495                __l2cap_set_ertm_timeouts(chan, &rfc);
3496
3497                size = min_t(u16, L2CAP_DEFAULT_MAX_PDU_SIZE, chan->conn->mtu -
3498                             L2CAP_EXT_HDR_SIZE - L2CAP_SDULEN_SIZE -
3499                             L2CAP_FCS_SIZE);
3500                rfc.max_pdu_size = cpu_to_le16(size);
3501
3502                l2cap_txwin_setup(chan);
3503
3504                rfc.txwin_size = min_t(u16, chan->tx_win,
3505                                       L2CAP_DEFAULT_TX_WINDOW);
3506
3507                l2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC, sizeof(rfc),
3508                                   (unsigned long) &rfc, endptr - ptr);
3509
3510                if (test_bit(FLAG_EFS_ENABLE, &chan->flags))
3511                        l2cap_add_opt_efs(&ptr, chan, endptr - ptr);
3512
3513                if (test_bit(FLAG_EXT_CTRL, &chan->flags))
3514                        l2cap_add_conf_opt(&ptr, L2CAP_CONF_EWS, 2,
3515                                           chan->tx_win, endptr - ptr);
3516
3517                if (chan->conn->feat_mask & L2CAP_FEAT_FCS)
3518                        if (chan->fcs == L2CAP_FCS_NONE ||
3519                            test_bit(CONF_RECV_NO_FCS, &chan->conf_state)) {
3520                                chan->fcs = L2CAP_FCS_NONE;
3521                                l2cap_add_conf_opt(&ptr, L2CAP_CONF_FCS, 1,
3522                                                   chan->fcs, endptr - ptr);
3523                        }
3524                break;
3525
3526        case L2CAP_MODE_STREAMING:
3527                l2cap_txwin_setup(chan);
3528                rfc.mode            = L2CAP_MODE_STREAMING;
3529                rfc.txwin_size      = 0;
3530                rfc.max_transmit    = 0;
3531                rfc.retrans_timeout = 0;
3532                rfc.monitor_timeout = 0;
3533
3534                size = min_t(u16, L2CAP_DEFAULT_MAX_PDU_SIZE, chan->conn->mtu -
3535                             L2CAP_EXT_HDR_SIZE - L2CAP_SDULEN_SIZE -
3536                             L2CAP_FCS_SIZE);
3537                rfc.max_pdu_size = cpu_to_le16(size);
3538
3539                l2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC, sizeof(rfc),
3540                                   (unsigned long) &rfc, endptr - ptr);
3541
3542                if (test_bit(FLAG_EFS_ENABLE, &chan->flags))
3543                        l2cap_add_opt_efs(&ptr, chan, endptr - ptr);
3544
3545                if (chan->conn->feat_mask & L2CAP_FEAT_FCS)
3546                        if (chan->fcs == L2CAP_FCS_NONE ||
3547                            test_bit(CONF_RECV_NO_FCS, &chan->conf_state)) {
3548                                chan->fcs = L2CAP_FCS_NONE;
3549                                l2cap_add_conf_opt(&ptr, L2CAP_CONF_FCS, 1,
3550                                                   chan->fcs, endptr - ptr);
3551                        }
3552                break;
3553        }
3554
3555        req->dcid  = cpu_to_le16(chan->dcid);
3556        req->flags = cpu_to_le16(0);
3557
3558        return ptr - data;
3559}
3560
3561static int l2cap_parse_conf_req(struct l2cap_chan *chan, void *data, size_t data_size)
3562{
3563        struct l2cap_conf_rsp *rsp = data;
3564        void *ptr = rsp->data;
3565        void *endptr = data + data_size;
3566        void *req = chan->conf_req;
3567        int len = chan->conf_len;
3568        int type, hint, olen;
3569        unsigned long val;
3570        struct l2cap_conf_rfc rfc = { .mode = L2CAP_MODE_BASIC };
3571        struct l2cap_conf_efs efs;
3572        u8 remote_efs = 0;
3573        u16 mtu = L2CAP_DEFAULT_MTU;
3574        u16 result = L2CAP_CONF_SUCCESS;
3575        u16 size;
3576
3577        BT_DBG("chan %p", chan);
3578
3579        while (len >= L2CAP_CONF_OPT_SIZE) {
3580                len -= l2cap_get_conf_opt(&req, &type, &olen, &val);
3581                if (len < 0)
3582                        break;
3583
3584                hint  = type & L2CAP_CONF_HINT;
3585                type &= L2CAP_CONF_MASK;
3586
3587                switch (type) {
3588                case L2CAP_CONF_MTU:
3589                        if (olen != 2)
3590                                break;
3591                        mtu = val;
3592                        break;
3593
3594                case L2CAP_CONF_FLUSH_TO:
3595                        if (olen != 2)
3596                                break;
3597                        chan->flush_to = val;
3598                        break;
3599
3600                case L2CAP_CONF_QOS:
3601                        break;
3602
3603                case L2CAP_CONF_RFC:
3604                        if (olen != sizeof(rfc))
3605                                break;
3606                        memcpy(&rfc, (void *) val, olen);
3607                        break;
3608
3609                case L2CAP_CONF_FCS:
3610                        if (olen != 1)
3611                                break;
3612                        if (val == L2CAP_FCS_NONE)
3613                                set_bit(CONF_RECV_NO_FCS, &chan->conf_state);
3614                        break;
3615
3616                case L2CAP_CONF_EFS:
3617                        if (olen != sizeof(efs))
3618                                break;
3619                        remote_efs = 1;
3620                        memcpy(&efs, (void *) val, olen);
3621                        break;
3622
3623                case L2CAP_CONF_EWS:
3624                        if (olen != 2)
3625                                break;
3626                        if (!(chan->conn->local_fixed_chan & L2CAP_FC_A2MP))
3627                                return -ECONNREFUSED;
3628                        set_bit(FLAG_EXT_CTRL, &chan->flags);
3629                        set_bit(CONF_EWS_RECV, &chan->conf_state);
3630                        chan->tx_win_max = L2CAP_DEFAULT_EXT_WINDOW;
3631                        chan->remote_tx_win = val;
3632                        break;
3633
3634                default:
3635                        if (hint)
3636                                break;
3637                        result = L2CAP_CONF_UNKNOWN;
3638                        l2cap_add_conf_opt(&ptr, (u8)type, sizeof(u8), type, endptr - ptr);
3639                        break;
3640                }
3641        }
3642
3643        if (chan->num_conf_rsp || chan->num_conf_req > 1)
3644                goto done;
3645
3646        switch (chan->mode) {
3647        case L2CAP_MODE_STREAMING:
3648        case L2CAP_MODE_ERTM:
3649                if (!test_bit(CONF_STATE2_DEVICE, &chan->conf_state)) {
3650                        chan->mode = l2cap_select_mode(rfc.mode,
3651                                                       chan->conn->feat_mask);
3652                        break;
3653                }
3654
3655                if (remote_efs) {
3656                        if (__l2cap_efs_supported(chan->conn))
3657                                set_bit(FLAG_EFS_ENABLE, &chan->flags);
3658                        else
3659                                return -ECONNREFUSED;
3660                }
3661
3662                if (chan->mode != rfc.mode)
3663                        return -ECONNREFUSED;
3664
3665                break;
3666        }
3667
3668done:
3669        if (chan->mode != rfc.mode) {
3670                result = L2CAP_CONF_UNACCEPT;
3671                rfc.mode = chan->mode;
3672
3673                if (chan->num_conf_rsp == 1)
3674                        return -ECONNREFUSED;
3675
3676                l2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC, sizeof(rfc),
3677                                   (unsigned long) &rfc, endptr - ptr);
3678        }
3679
3680        if (result == L2CAP_CONF_SUCCESS) {
3681                /* Configure output options and let the other side know
3682                 * which ones we don't like. */
3683
3684                if (mtu < L2CAP_DEFAULT_MIN_MTU)
3685                        result = L2CAP_CONF_UNACCEPT;
3686                else {
3687                        chan->omtu = mtu;
3688                        set_bit(CONF_MTU_DONE, &chan->conf_state);
3689                }
3690                l2cap_add_conf_opt(&ptr, L2CAP_CONF_MTU, 2, chan->omtu, endptr - ptr);
3691
3692                if (remote_efs) {
3693                        if (chan->local_stype != L2CAP_SERV_NOTRAFIC &&
3694                            efs.stype != L2CAP_SERV_NOTRAFIC &&
3695                            efs.stype != chan->local_stype) {
3696
3697                                result = L2CAP_CONF_UNACCEPT;
3698
3699                                if (chan->num_conf_req >= 1)
3700                                        return -ECONNREFUSED;
3701
3702                                l2cap_add_conf_opt(&ptr, L2CAP_CONF_EFS,
3703                                                   sizeof(efs),
3704                                                   (unsigned long) &efs, endptr - ptr);
3705                        } else {
3706                                /* Send PENDING Conf Rsp */
3707                                result = L2CAP_CONF_PENDING;
3708                                set_bit(CONF_LOC_CONF_PEND, &chan->conf_state);
3709                        }
3710                }
3711
3712                switch (rfc.mode) {
3713                case L2CAP_MODE_BASIC:
3714                        chan->fcs = L2CAP_FCS_NONE;
3715                        set_bit(CONF_MODE_DONE, &chan->conf_state);
3716                        break;
3717
3718                case L2CAP_MODE_ERTM:
3719                        if (!test_bit(CONF_EWS_RECV, &chan->conf_state))
3720                                chan->remote_tx_win = rfc.txwin_size;
3721                        else
3722                                rfc.txwin_size = L2CAP_DEFAULT_TX_WINDOW;
3723
3724                        chan->remote_max_tx = rfc.max_transmit;
3725
3726                        size = min_t(u16, le16_to_cpu(rfc.max_pdu_size),
3727                                     chan->conn->mtu - L2CAP_EXT_HDR_SIZE -
3728                                     L2CAP_SDULEN_SIZE - L2CAP_FCS_SIZE);
3729                        rfc.max_pdu_size = cpu_to_le16(size);
3730                        chan->remote_mps = size;
3731
3732                        __l2cap_set_ertm_timeouts(chan, &rfc);
3733
3734                        set_bit(CONF_MODE_DONE, &chan->conf_state);
3735
3736                        l2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC,
3737                                           sizeof(rfc), (unsigned long) &rfc, endptr - ptr);
3738
3739                        if (test_bit(FLAG_EFS_ENABLE, &chan->flags)) {
3740                                chan->remote_id = efs.id;
3741                                chan->remote_stype = efs.stype;
3742                                chan->remote_msdu = le16_to_cpu(efs.msdu);
3743                                chan->remote_flush_to =
3744                                        le32_to_cpu(efs.flush_to);
3745                                chan->remote_acc_lat =
3746                                        le32_to_cpu(efs.acc_lat);
3747                                chan->remote_sdu_itime =
3748                                        le32_to_cpu(efs.sdu_itime);
3749                                l2cap_add_conf_opt(&ptr, L2CAP_CONF_EFS,
3750                                                   sizeof(efs),
3751                                                   (unsigned long) &efs, endptr - ptr);
3752                        }
3753                        break;
3754
3755                case L2CAP_MODE_STREAMING:
3756                        size = min_t(u16, le16_to_cpu(rfc.max_pdu_size),
3757                                     chan->conn->mtu - L2CAP_EXT_HDR_SIZE -
3758                                     L2CAP_SDULEN_SIZE - L2CAP_FCS_SIZE);
3759                        rfc.max_pdu_size = cpu_to_le16(size);
3760                        chan->remote_mps = size;
3761
3762                        set_bit(CONF_MODE_DONE, &chan->conf_state);
3763
3764                        l2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC, sizeof(rfc),
3765                                           (unsigned long) &rfc, endptr - ptr);
3766
3767                        break;
3768
3769                default:
3770                        result = L2CAP_CONF_UNACCEPT;
3771
3772                        memset(&rfc, 0, sizeof(rfc));
3773                        rfc.mode = chan->mode;
3774                }
3775
3776                if (result == L2CAP_CONF_SUCCESS)
3777                        set_bit(CONF_OUTPUT_DONE, &chan->conf_state);
3778        }
3779        rsp->scid   = cpu_to_le16(chan->dcid);
3780        rsp->result = cpu_to_le16(result);
3781        rsp->flags  = cpu_to_le16(0);
3782
3783        return ptr - data;
3784}
3785
3786static int l2cap_parse_conf_rsp(struct l2cap_chan *chan, void *rsp, int len,
3787                                void *data, size_t size, u16 *result)
3788{
3789        struct l2cap_conf_req *req = data;
3790        void *ptr = req->data;
3791        void *endptr = data + size;
3792        int type, olen;
3793        unsigned long val;
3794        struct l2cap_conf_rfc rfc = { .mode = L2CAP_MODE_BASIC };
3795        struct l2cap_conf_efs efs;
3796
3797        BT_DBG("chan %p, rsp %p, len %d, req %p", chan, rsp, len, data);
3798
3799        while (len >= L2CAP_CONF_OPT_SIZE) {
3800                len -= l2cap_get_conf_opt(&rsp, &type, &olen, &val);
3801                if (len < 0)
3802                        break;
3803
3804                switch (type) {
3805                case L2CAP_CONF_MTU:
3806                        if (olen != 2)
3807                                break;
3808                        if (val < L2CAP_DEFAULT_MIN_MTU) {
3809                                *result = L2CAP_CONF_UNACCEPT;
3810                                chan->imtu = L2CAP_DEFAULT_MIN_MTU;
3811                        } else
3812                                chan->imtu = val;
3813                        l2cap_add_conf_opt(&ptr, L2CAP_CONF_MTU, 2, chan->imtu,
3814                                           endptr - ptr);
3815                        break;
3816
3817                case L2CAP_CONF_FLUSH_TO:
3818                        if (olen != 2)
3819                                break;
3820                        chan->flush_to = val;
3821                        l2cap_add_conf_opt(&ptr, L2CAP_CONF_FLUSH_TO, 2,
3822                                           chan->flush_to, endptr - ptr);
3823                        break;
3824
3825                case L2CAP_CONF_RFC:
3826                        if (olen != sizeof(rfc))
3827                                break;
3828                        memcpy(&rfc, (void *)val, olen);
3829                        if (test_bit(CONF_STATE2_DEVICE, &chan->conf_state) &&
3830                            rfc.mode != chan->mode)
3831                                return -ECONNREFUSED;
3832                        chan->fcs = 0;
3833                        l2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC, sizeof(rfc),
3834                                           (unsigned long) &rfc, endptr - ptr);
3835                        break;
3836
3837                case L2CAP_CONF_EWS:
3838                        if (olen != 2)
3839                                break;
3840                        chan->ack_win = min_t(u16, val, chan->ack_win);
3841                        l2cap_add_conf_opt(&ptr, L2CAP_CONF_EWS, 2,
3842                                           chan->tx_win, endptr - ptr);
3843                        break;
3844
3845                case L2CAP_CONF_EFS:
3846                        if (olen != sizeof(efs))
3847                                break;
3848                        memcpy(&efs, (void *)val, olen);
3849                        if (chan->local_stype != L2CAP_SERV_NOTRAFIC &&
3850                            efs.stype != L2CAP_SERV_NOTRAFIC &&
3851                            efs.stype != chan->local_stype)
3852                                return -ECONNREFUSED;
3853                        l2cap_add_conf_opt(&ptr, L2CAP_CONF_EFS, sizeof(efs),
3854                                           (unsigned long) &efs, endptr - ptr);
3855                        break;
3856
3857                case L2CAP_CONF_FCS:
3858                        if (olen != 1)
3859                                break;
3860                        if (*result == L2CAP_CONF_PENDING)
3861                                if (val == L2CAP_FCS_NONE)
3862                                        set_bit(CONF_RECV_NO_FCS,
3863                                                &chan->conf_state);
3864                        break;
3865                }
3866        }
3867
3868        if (chan->mode == L2CAP_MODE_BASIC && chan->mode != rfc.mode)
3869                return -ECONNREFUSED;
3870
3871        chan->mode = rfc.mode;
3872
3873        if (*result == L2CAP_CONF_SUCCESS || *result == L2CAP_CONF_PENDING) {
3874                switch (rfc.mode) {
3875                case L2CAP_MODE_ERTM:
3876                        chan->retrans_timeout = le16_to_cpu(rfc.retrans_timeout);
3877                        chan->monitor_timeout = le16_to_cpu(rfc.monitor_timeout);
3878                        chan->mps    = le16_to_cpu(rfc.max_pdu_size);
3879                        if (!test_bit(FLAG_EXT_CTRL, &chan->flags))
3880                                chan->ack_win = min_t(u16, chan->ack_win,
3881                                                      rfc.txwin_size);
3882
3883                        if (test_bit(FLAG_EFS_ENABLE, &chan->flags)) {
3884                                chan->local_msdu = le16_to_cpu(efs.msdu);
3885                                chan->local_sdu_itime =
3886                                        le32_to_cpu(efs.sdu_itime);
3887                                chan->local_acc_lat = le32_to_cpu(efs.acc_lat);
3888                                chan->local_flush_to =
3889                                        le32_to_cpu(efs.flush_to);
3890                        }
3891                        break;
3892
3893                case L2CAP_MODE_STREAMING:
3894                        chan->mps    = le16_to_cpu(rfc.max_pdu_size);
3895                }
3896        }
3897
3898        req->dcid   = cpu_to_le16(chan->dcid);
3899        req->flags  = cpu_to_le16(0);
3900
3901        return ptr - data;
3902}
3903
3904static int l2cap_build_conf_rsp(struct l2cap_chan *chan, void *data,
3905                                u16 result, u16 flags)
3906{
3907        struct l2cap_conf_rsp *rsp = data;
3908        void *ptr = rsp->data;
3909
3910        BT_DBG("chan %p", chan);
3911
3912        rsp->scid   = cpu_to_le16(chan->dcid);
3913        rsp->result = cpu_to_le16(result);
3914        rsp->flags  = cpu_to_le16(flags);
3915
3916        return ptr - data;
3917}
3918
3919void __l2cap_le_connect_rsp_defer(struct l2cap_chan *chan)
3920{
3921        struct l2cap_le_conn_rsp rsp;
3922        struct l2cap_conn *conn = chan->conn;
3923
3924        BT_DBG("chan %p", chan);
3925
3926        rsp.dcid    = cpu_to_le16(chan->scid);
3927        rsp.mtu     = cpu_to_le16(chan->imtu);
3928        rsp.mps     = cpu_to_le16(chan->mps);
3929        rsp.credits = cpu_to_le16(chan->rx_credits);
3930        rsp.result  = cpu_to_le16(L2CAP_CR_LE_SUCCESS);
3931
3932        l2cap_send_cmd(conn, chan->ident, L2CAP_LE_CONN_RSP, sizeof(rsp),
3933                       &rsp);
3934}
3935
3936void __l2cap_ecred_conn_rsp_defer(struct l2cap_chan *chan)
3937{
3938        struct {
3939                struct l2cap_ecred_conn_rsp rsp;
3940                __le16 dcid[5];
3941        } __packed pdu;
3942        struct l2cap_conn *conn = chan->conn;
3943        u16 ident = chan->ident;
3944        int i = 0;
3945
3946        if (!ident)
3947                return;
3948
3949        BT_DBG("chan %p ident %d", chan, ident);
3950
3951        pdu.rsp.mtu     = cpu_to_le16(chan->imtu);
3952        pdu.rsp.mps     = cpu_to_le16(chan->mps);
3953        pdu.rsp.credits = cpu_to_le16(chan->rx_credits);
3954        pdu.rsp.result  = cpu_to_le16(L2CAP_CR_LE_SUCCESS);
3955
3956        mutex_lock(&conn->chan_lock);
3957
3958        list_for_each_entry(chan, &conn->chan_l, list) {
3959                if (chan->ident != ident)
3960                        continue;
3961
3962                /* Reset ident so only one response is sent */
3963                chan->ident = 0;
3964
3965                /* Include all channels pending with the same ident */
3966                pdu.dcid[i++] = cpu_to_le16(chan->scid);
3967        }
3968
3969        mutex_unlock(&conn->chan_lock);
3970
3971        l2cap_send_cmd(conn, ident, L2CAP_ECRED_CONN_RSP,
3972                        sizeof(pdu.rsp) + i * sizeof(__le16), &pdu);
3973}
3974
3975void __l2cap_connect_rsp_defer(struct l2cap_chan *chan)
3976{
3977        struct l2cap_conn_rsp rsp;
3978        struct l2cap_conn *conn = chan->conn;
3979        u8 buf[128];
3980        u8 rsp_code;
3981
3982        rsp.scid   = cpu_to_le16(chan->dcid);
3983        rsp.dcid   = cpu_to_le16(chan->scid);
3984        rsp.result = cpu_to_le16(L2CAP_CR_SUCCESS);
3985        rsp.status = cpu_to_le16(L2CAP_CS_NO_INFO);
3986
3987        if (chan->hs_hcon)
3988                rsp_code = L2CAP_CREATE_CHAN_RSP;
3989        else
3990                rsp_code = L2CAP_CONN_RSP;
3991
3992        BT_DBG("chan %p rsp_code %u", chan, rsp_code);
3993
3994        l2cap_send_cmd(conn, chan->ident, rsp_code, sizeof(rsp), &rsp);
3995
3996        if (test_and_set_bit(CONF_REQ_SENT, &chan->conf_state))
3997                return;
3998
3999        l2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_CONF_REQ,
4000                       l2cap_build_conf_req(chan, buf, sizeof(buf)), buf);
4001        chan->num_conf_req++;
4002}
4003
4004static void l2cap_conf_rfc_get(struct l2cap_chan *chan, void *rsp, int len)
4005{
4006        int type, olen;
4007        unsigned long val;
4008        /* Use sane default values in case a misbehaving remote device
4009         * did not send an RFC or extended window size option.
4010         */
4011        u16 txwin_ext = chan->ack_win;
4012        struct l2cap_conf_rfc rfc = {
4013                .mode = chan->mode,
4014                .retrans_timeout = cpu_to_le16(L2CAP_DEFAULT_RETRANS_TO),
4015                .monitor_timeout = cpu_to_le16(L2CAP_DEFAULT_MONITOR_TO),
4016                .max_pdu_size = cpu_to_le16(chan->imtu),
4017                .txwin_size = min_t(u16, chan->ack_win, L2CAP_DEFAULT_TX_WINDOW),
4018        };
4019
4020        BT_DBG("chan %p, rsp %p, len %d", chan, rsp, len);
4021
4022        if ((chan->mode != L2CAP_MODE_ERTM) && (chan->mode != L2CAP_MODE_STREAMING))
4023                return;
4024
4025        while (len >= L2CAP_CONF_OPT_SIZE) {
4026                len -= l2cap_get_conf_opt(&rsp, &type, &olen, &val);
4027                if (len < 0)
4028                        break;
4029
4030                switch (type) {
4031                case L2CAP_CONF_RFC:
4032                        if (olen != sizeof(rfc))
4033                                break;
4034                        memcpy(&rfc, (void *)val, olen);
4035                        break;
4036                case L2CAP_CONF_EWS:
4037                        if (olen != 2)
4038                                break;
4039                        txwin_ext = val;
4040                        break;
4041                }
4042        }
4043
4044        switch (rfc.mode) {
4045        case L2CAP_MODE_ERTM:
4046                chan->retrans_timeout = le16_to_cpu(rfc.retrans_timeout);
4047                chan->monitor_timeout = le16_to_cpu(rfc.monitor_timeout);
4048                chan->mps = le16_to_cpu(rfc.max_pdu_size);
4049                if (test_bit(FLAG_EXT_CTRL, &chan->flags))
4050                        chan->ack_win = min_t(u16, chan->ack_win, txwin_ext);
4051                else
4052                        chan->ack_win = min_t(u16, chan->ack_win,
4053                                              rfc.txwin_size);
4054                break;
4055        case L2CAP_MODE_STREAMING:
4056                chan->mps    = le16_to_cpu(rfc.max_pdu_size);
4057        }
4058}
4059
4060static inline int l2cap_command_rej(struct l2cap_conn *conn,
4061                                    struct l2cap_cmd_hdr *cmd, u16 cmd_len,
4062                                    u8 *data)
4063{
4064        struct l2cap_cmd_rej_unk *rej = (struct l2cap_cmd_rej_unk *) data;
4065
4066        if (cmd_len < sizeof(*rej))
4067                return -EPROTO;
4068
4069        if (rej->reason != L2CAP_REJ_NOT_UNDERSTOOD)
4070                return 0;
4071
4072        if ((conn->info_state & L2CAP_INFO_FEAT_MASK_REQ_SENT) &&
4073            cmd->ident == conn->info_ident) {
4074                cancel_delayed_work(&conn->info_timer);
4075
4076                conn->info_state |= L2CAP_INFO_FEAT_MASK_REQ_DONE;
4077                conn->info_ident = 0;
4078
4079                l2cap_conn_start(conn);
4080        }
4081
4082        return 0;
4083}
4084
4085static struct l2cap_chan *l2cap_connect(struct l2cap_conn *conn,
4086                                        struct l2cap_cmd_hdr *cmd,
4087                                        u8 *data, u8 rsp_code, u8 amp_id)
4088{
4089        struct l2cap_conn_req *req = (struct l2cap_conn_req *) data;
4090        struct l2cap_conn_rsp rsp;
4091        struct l2cap_chan *chan = NULL, *pchan;
4092        int result, status = L2CAP_CS_NO_INFO;
4093
4094        u16 dcid = 0, scid = __le16_to_cpu(req->scid);
4095        __le16 psm = req->psm;
4096
4097        BT_DBG("psm 0x%2.2x scid 0x%4.4x", __le16_to_cpu(psm), scid);
4098
4099        /* Check if we have socket listening on psm */
4100        pchan = l2cap_global_chan_by_psm(BT_LISTEN, psm, &conn->hcon->src,
4101                                         &conn->hcon->dst, ACL_LINK);
4102        if (!pchan) {
4103                result = L2CAP_CR_BAD_PSM;
4104                goto sendresp;
4105        }
4106
4107        mutex_lock(&conn->chan_lock);
4108        l2cap_chan_lock(pchan);
4109
4110        /* Check if the ACL is secure enough (if not SDP) */
4111        if (psm != cpu_to_le16(L2CAP_PSM_SDP) &&
4112            !hci_conn_check_link_mode(conn->hcon)) {
4113                conn->disc_reason = HCI_ERROR_AUTH_FAILURE;
4114                result = L2CAP_CR_SEC_BLOCK;
4115                goto response;
4116        }
4117
4118        result = L2CAP_CR_NO_MEM;
4119
4120        /* Check for valid dynamic CID range (as per Erratum 3253) */
4121        if (scid < L2CAP_CID_DYN_START || scid > L2CAP_CID_DYN_END) {
4122                result = L2CAP_CR_INVALID_SCID;
4123                goto response;
4124        }
4125
4126        /* Check if we already have channel with that dcid */
4127        if (__l2cap_get_chan_by_dcid(conn, scid)) {
4128                result = L2CAP_CR_SCID_IN_USE;
4129                goto response;
4130        }
4131
4132        chan = pchan->ops->new_connection(pchan);
4133        if (!chan)
4134                goto response;
4135
4136        /* For certain devices (ex: HID mouse), support for authentication,
4137         * pairing and bonding is optional. For such devices, inorder to avoid
4138         * the ACL alive for too long after L2CAP disconnection, reset the ACL
4139         * disc_timeout back to HCI_DISCONN_TIMEOUT during L2CAP connect.
4140         */
4141        conn->hcon->disc_timeout = HCI_DISCONN_TIMEOUT;
4142
4143        bacpy(&chan->src, &conn->hcon->src);
4144        bacpy(&chan->dst, &conn->hcon->dst);
4145        chan->src_type = bdaddr_src_type(conn->hcon);
4146        chan->dst_type = bdaddr_dst_type(conn->hcon);
4147        chan->psm  = psm;
4148        chan->dcid = scid;
4149        chan->local_amp_id = amp_id;
4150
4151        __l2cap_chan_add(conn, chan);
4152
4153        dcid = chan->scid;
4154
4155        __set_chan_timer(chan, chan->ops->get_sndtimeo(chan));
4156
4157        chan->ident = cmd->ident;
4158
4159        if (conn->info_state & L2CAP_INFO_FEAT_MASK_REQ_DONE) {
4160                if (l2cap_chan_check_security(chan, false)) {
4161                        if (test_bit(FLAG_DEFER_SETUP, &chan->flags)) {
4162                                l2cap_state_change(chan, BT_CONNECT2);
4163                                result = L2CAP_CR_PEND;
4164                                status = L2CAP_CS_AUTHOR_PEND;
4165                                chan->ops->defer(chan);
4166                        } else {
4167                                /* Force pending result for AMP controllers.
4168                                 * The connection will succeed after the
4169                                 * physical link is up.
4170                                 */
4171                                if (amp_id == AMP_ID_BREDR) {
4172                                        l2cap_state_change(chan, BT_CONFIG);
4173                                        result = L2CAP_CR_SUCCESS;
4174                                } else {
4175                                        l2cap_state_change(chan, BT_CONNECT2);
4176                                        result = L2CAP_CR_PEND;
4177                                }
4178                                status = L2CAP_CS_NO_INFO;
4179                        }
4180                } else {
4181                        l2cap_state_change(chan, BT_CONNECT2);
4182                        result = L2CAP_CR_PEND;
4183                        status = L2CAP_CS_AUTHEN_PEND;
4184                }
4185        } else {
4186                l2cap_state_change(chan, BT_CONNECT2);
4187                result = L2CAP_CR_PEND;
4188                status = L2CAP_CS_NO_INFO;
4189        }
4190
4191response:
4192        l2cap_chan_unlock(pchan);
4193        mutex_unlock(&conn->