linux/drivers/media/cec/cec-adap.c
<<
>>
Prefs
   1// SPDX-License-Identifier: GPL-2.0-only
   2/*
   3 * cec-adap.c - HDMI Consumer Electronics Control framework - CEC adapter
   4 *
   5 * Copyright 2016 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
   6 */
   7
   8#include <linux/errno.h>
   9#include <linux/init.h>
  10#include <linux/module.h>
  11#include <linux/kernel.h>
  12#include <linux/kmod.h>
  13#include <linux/ktime.h>
  14#include <linux/slab.h>
  15#include <linux/mm.h>
  16#include <linux/string.h>
  17#include <linux/types.h>
  18
  19#include <drm/drm_connector.h>
  20#include <drm/drm_device.h>
  21#include <drm/drm_edid.h>
  22#include <drm/drm_file.h>
  23
  24#include "cec-priv.h"
  25
  26static void cec_fill_msg_report_features(struct cec_adapter *adap,
  27                                         struct cec_msg *msg,
  28                                         unsigned int la_idx);
  29
  30/*
  31 * 400 ms is the time it takes for one 16 byte message to be
  32 * transferred and 5 is the maximum number of retries. Add
  33 * another 100 ms as a margin. So if the transmit doesn't
  34 * finish before that time something is really wrong and we
  35 * have to time out.
  36 *
  37 * This is a sign that something it really wrong and a warning
  38 * will be issued.
  39 */
  40#define CEC_XFER_TIMEOUT_MS (5 * 400 + 100)
  41
  42#define call_op(adap, op, arg...) \
  43        (adap->ops->op ? adap->ops->op(adap, ## arg) : 0)
  44
  45#define call_void_op(adap, op, arg...)                  \
  46        do {                                            \
  47                if (adap->ops->op)                      \
  48                        adap->ops->op(adap, ## arg);    \
  49        } while (0)
  50
  51static int cec_log_addr2idx(const struct cec_adapter *adap, u8 log_addr)
  52{
  53        int i;
  54
  55        for (i = 0; i < adap->log_addrs.num_log_addrs; i++)
  56                if (adap->log_addrs.log_addr[i] == log_addr)
  57                        return i;
  58        return -1;
  59}
  60
  61static unsigned int cec_log_addr2dev(const struct cec_adapter *adap, u8 log_addr)
  62{
  63        int i = cec_log_addr2idx(adap, log_addr);
  64
  65        return adap->log_addrs.primary_device_type[i < 0 ? 0 : i];
  66}
  67
  68u16 cec_get_edid_phys_addr(const u8 *edid, unsigned int size,
  69                           unsigned int *offset)
  70{
  71        unsigned int loc = cec_get_edid_spa_location(edid, size);
  72
  73        if (offset)
  74                *offset = loc;
  75        if (loc == 0)
  76                return CEC_PHYS_ADDR_INVALID;
  77        return (edid[loc] << 8) | edid[loc + 1];
  78}
  79EXPORT_SYMBOL_GPL(cec_get_edid_phys_addr);
  80
  81void cec_fill_conn_info_from_drm(struct cec_connector_info *conn_info,
  82                                 const struct drm_connector *connector)
  83{
  84        memset(conn_info, 0, sizeof(*conn_info));
  85        conn_info->type = CEC_CONNECTOR_TYPE_DRM;
  86        conn_info->drm.card_no = connector->dev->primary->index;
  87        conn_info->drm.connector_id = connector->base.id;
  88}
  89EXPORT_SYMBOL_GPL(cec_fill_conn_info_from_drm);
  90
  91/*
  92 * Queue a new event for this filehandle. If ts == 0, then set it
  93 * to the current time.
  94 *
  95 * We keep a queue of at most max_event events where max_event differs
  96 * per event. If the queue becomes full, then drop the oldest event and
  97 * keep track of how many events we've dropped.
  98 */
  99void cec_queue_event_fh(struct cec_fh *fh,
 100                        const struct cec_event *new_ev, u64 ts)
 101{
 102        static const u16 max_events[CEC_NUM_EVENTS] = {
 103                1, 1, 800, 800, 8, 8, 8, 8
 104        };
 105        struct cec_event_entry *entry;
 106        unsigned int ev_idx = new_ev->event - 1;
 107
 108        if (WARN_ON(ev_idx >= ARRAY_SIZE(fh->events)))
 109                return;
 110
 111        if (ts == 0)
 112                ts = ktime_get_ns();
 113
 114        mutex_lock(&fh->lock);
 115        if (ev_idx < CEC_NUM_CORE_EVENTS)
 116                entry = &fh->core_events[ev_idx];
 117        else
 118                entry = kmalloc(sizeof(*entry), GFP_KERNEL);
 119        if (entry) {
 120                if (new_ev->event == CEC_EVENT_LOST_MSGS &&
 121                    fh->queued_events[ev_idx]) {
 122                        entry->ev.lost_msgs.lost_msgs +=
 123                                new_ev->lost_msgs.lost_msgs;
 124                        goto unlock;
 125                }
 126                entry->ev = *new_ev;
 127                entry->ev.ts = ts;
 128
 129                if (fh->queued_events[ev_idx] < max_events[ev_idx]) {
 130                        /* Add new msg at the end of the queue */
 131                        list_add_tail(&entry->list, &fh->events[ev_idx]);
 132                        fh->queued_events[ev_idx]++;
 133                        fh->total_queued_events++;
 134                        goto unlock;
 135                }
 136
 137                if (ev_idx >= CEC_NUM_CORE_EVENTS) {
 138                        list_add_tail(&entry->list, &fh->events[ev_idx]);
 139                        /* drop the oldest event */
 140                        entry = list_first_entry(&fh->events[ev_idx],
 141                                                 struct cec_event_entry, list);
 142                        list_del(&entry->list);
 143                        kfree(entry);
 144                }
 145        }
 146        /* Mark that events were lost */
 147        entry = list_first_entry_or_null(&fh->events[ev_idx],
 148                                         struct cec_event_entry, list);
 149        if (entry)
 150                entry->ev.flags |= CEC_EVENT_FL_DROPPED_EVENTS;
 151
 152unlock:
 153        mutex_unlock(&fh->lock);
 154        wake_up_interruptible(&fh->wait);
 155}
 156
 157/* Queue a new event for all open filehandles. */
 158static void cec_queue_event(struct cec_adapter *adap,
 159                            const struct cec_event *ev)
 160{
 161        u64 ts = ktime_get_ns();
 162        struct cec_fh *fh;
 163
 164        mutex_lock(&adap->devnode.lock);
 165        list_for_each_entry(fh, &adap->devnode.fhs, list)
 166                cec_queue_event_fh(fh, ev, ts);
 167        mutex_unlock(&adap->devnode.lock);
 168}
 169
 170/* Notify userspace that the CEC pin changed state at the given time. */
 171void cec_queue_pin_cec_event(struct cec_adapter *adap, bool is_high,
 172                             bool dropped_events, ktime_t ts)
 173{
 174        struct cec_event ev = {
 175                .event = is_high ? CEC_EVENT_PIN_CEC_HIGH :
 176                                   CEC_EVENT_PIN_CEC_LOW,
 177                .flags = dropped_events ? CEC_EVENT_FL_DROPPED_EVENTS : 0,
 178        };
 179        struct cec_fh *fh;
 180
 181        mutex_lock(&adap->devnode.lock);
 182        list_for_each_entry(fh, &adap->devnode.fhs, list)
 183                if (fh->mode_follower == CEC_MODE_MONITOR_PIN)
 184                        cec_queue_event_fh(fh, &ev, ktime_to_ns(ts));
 185        mutex_unlock(&adap->devnode.lock);
 186}
 187EXPORT_SYMBOL_GPL(cec_queue_pin_cec_event);
 188
 189/* Notify userspace that the HPD pin changed state at the given time. */
 190void cec_queue_pin_hpd_event(struct cec_adapter *adap, bool is_high, ktime_t ts)
 191{
 192        struct cec_event ev = {
 193                .event = is_high ? CEC_EVENT_PIN_HPD_HIGH :
 194                                   CEC_EVENT_PIN_HPD_LOW,
 195        };
 196        struct cec_fh *fh;
 197
 198        mutex_lock(&adap->devnode.lock);
 199        list_for_each_entry(fh, &adap->devnode.fhs, list)
 200                cec_queue_event_fh(fh, &ev, ktime_to_ns(ts));
 201        mutex_unlock(&adap->devnode.lock);
 202}
 203EXPORT_SYMBOL_GPL(cec_queue_pin_hpd_event);
 204
 205/* Notify userspace that the 5V pin changed state at the given time. */
 206void cec_queue_pin_5v_event(struct cec_adapter *adap, bool is_high, ktime_t ts)
 207{
 208        struct cec_event ev = {
 209                .event = is_high ? CEC_EVENT_PIN_5V_HIGH :
 210                                   CEC_EVENT_PIN_5V_LOW,
 211        };
 212        struct cec_fh *fh;
 213
 214        mutex_lock(&adap->devnode.lock);
 215        list_for_each_entry(fh, &adap->devnode.fhs, list)
 216                cec_queue_event_fh(fh, &ev, ktime_to_ns(ts));
 217        mutex_unlock(&adap->devnode.lock);
 218}
 219EXPORT_SYMBOL_GPL(cec_queue_pin_5v_event);
 220
 221/*
 222 * Queue a new message for this filehandle.
 223 *
 224 * We keep a queue of at most CEC_MAX_MSG_RX_QUEUE_SZ messages. If the
 225 * queue becomes full, then drop the oldest message and keep track
 226 * of how many messages we've dropped.
 227 */
 228static void cec_queue_msg_fh(struct cec_fh *fh, const struct cec_msg *msg)
 229{
 230        static const struct cec_event ev_lost_msgs = {
 231                .event = CEC_EVENT_LOST_MSGS,
 232                .flags = 0,
 233                {
 234                        .lost_msgs = { 1 },
 235                },
 236        };
 237        struct cec_msg_entry *entry;
 238
 239        mutex_lock(&fh->lock);
 240        entry = kmalloc(sizeof(*entry), GFP_KERNEL);
 241        if (entry) {
 242                entry->msg = *msg;
 243                /* Add new msg at the end of the queue */
 244                list_add_tail(&entry->list, &fh->msgs);
 245
 246                if (fh->queued_msgs < CEC_MAX_MSG_RX_QUEUE_SZ) {
 247                        /* All is fine if there is enough room */
 248                        fh->queued_msgs++;
 249                        mutex_unlock(&fh->lock);
 250                        wake_up_interruptible(&fh->wait);
 251                        return;
 252                }
 253
 254                /*
 255                 * if the message queue is full, then drop the oldest one and
 256                 * send a lost message event.
 257                 */
 258                entry = list_first_entry(&fh->msgs, struct cec_msg_entry, list);
 259                list_del(&entry->list);
 260                kfree(entry);
 261        }
 262        mutex_unlock(&fh->lock);
 263
 264        /*
 265         * We lost a message, either because kmalloc failed or the queue
 266         * was full.
 267         */
 268        cec_queue_event_fh(fh, &ev_lost_msgs, ktime_get_ns());
 269}
 270
 271/*
 272 * Queue the message for those filehandles that are in monitor mode.
 273 * If valid_la is true (this message is for us or was sent by us),
 274 * then pass it on to any monitoring filehandle. If this message
 275 * isn't for us or from us, then only give it to filehandles that
 276 * are in MONITOR_ALL mode.
 277 *
 278 * This can only happen if the CEC_CAP_MONITOR_ALL capability is
 279 * set and the CEC adapter was placed in 'monitor all' mode.
 280 */
 281static void cec_queue_msg_monitor(struct cec_adapter *adap,
 282                                  const struct cec_msg *msg,
 283                                  bool valid_la)
 284{
 285        struct cec_fh *fh;
 286        u32 monitor_mode = valid_la ? CEC_MODE_MONITOR :
 287                                      CEC_MODE_MONITOR_ALL;
 288
 289        mutex_lock(&adap->devnode.lock);
 290        list_for_each_entry(fh, &adap->devnode.fhs, list) {
 291                if (fh->mode_follower >= monitor_mode)
 292                        cec_queue_msg_fh(fh, msg);
 293        }
 294        mutex_unlock(&adap->devnode.lock);
 295}
 296
 297/*
 298 * Queue the message for follower filehandles.
 299 */
 300static void cec_queue_msg_followers(struct cec_adapter *adap,
 301                                    const struct cec_msg *msg)
 302{
 303        struct cec_fh *fh;
 304
 305        mutex_lock(&adap->devnode.lock);
 306        list_for_each_entry(fh, &adap->devnode.fhs, list) {
 307                if (fh->mode_follower == CEC_MODE_FOLLOWER)
 308                        cec_queue_msg_fh(fh, msg);
 309        }
 310        mutex_unlock(&adap->devnode.lock);
 311}
 312
 313/* Notify userspace of an adapter state change. */
 314static void cec_post_state_event(struct cec_adapter *adap)
 315{
 316        struct cec_event ev = {
 317                .event = CEC_EVENT_STATE_CHANGE,
 318        };
 319
 320        ev.state_change.phys_addr = adap->phys_addr;
 321        ev.state_change.log_addr_mask = adap->log_addrs.log_addr_mask;
 322        cec_queue_event(adap, &ev);
 323}
 324
 325/*
 326 * A CEC transmit (and a possible wait for reply) completed.
 327 * If this was in blocking mode, then complete it, otherwise
 328 * queue the message for userspace to dequeue later.
 329 *
 330 * This function is called with adap->lock held.
 331 */
 332static void cec_data_completed(struct cec_data *data)
 333{
 334        /*
 335         * Delete this transmit from the filehandle's xfer_list since
 336         * we're done with it.
 337         *
 338         * Note that if the filehandle is closed before this transmit
 339         * finished, then the release() function will set data->fh to NULL.
 340         * Without that we would be referring to a closed filehandle.
 341         */
 342        if (data->fh)
 343                list_del(&data->xfer_list);
 344
 345        if (data->blocking) {
 346                /*
 347                 * Someone is blocking so mark the message as completed
 348                 * and call complete.
 349                 */
 350                data->completed = true;
 351                complete(&data->c);
 352        } else {
 353                /*
 354                 * No blocking, so just queue the message if needed and
 355                 * free the memory.
 356                 */
 357                if (data->fh)
 358                        cec_queue_msg_fh(data->fh, &data->msg);
 359                kfree(data);
 360        }
 361}
 362
 363/*
 364 * A pending CEC transmit needs to be cancelled, either because the CEC
 365 * adapter is disabled or the transmit takes an impossibly long time to
 366 * finish.
 367 *
 368 * This function is called with adap->lock held.
 369 */
 370static void cec_data_cancel(struct cec_data *data, u8 tx_status)
 371{
 372        /*
 373         * It's either the current transmit, or it is a pending
 374         * transmit. Take the appropriate action to clear it.
 375         */
 376        if (data->adap->transmitting == data) {
 377                data->adap->transmitting = NULL;
 378        } else {
 379                list_del_init(&data->list);
 380                if (!(data->msg.tx_status & CEC_TX_STATUS_OK))
 381                        data->adap->transmit_queue_sz--;
 382        }
 383
 384        if (data->msg.tx_status & CEC_TX_STATUS_OK) {
 385                data->msg.rx_ts = ktime_get_ns();
 386                data->msg.rx_status = CEC_RX_STATUS_ABORTED;
 387        } else {
 388                data->msg.tx_ts = ktime_get_ns();
 389                data->msg.tx_status |= tx_status |
 390                                       CEC_TX_STATUS_MAX_RETRIES;
 391                data->msg.tx_error_cnt++;
 392                data->attempts = 0;
 393        }
 394
 395        /* Queue transmitted message for monitoring purposes */
 396        cec_queue_msg_monitor(data->adap, &data->msg, 1);
 397
 398        cec_data_completed(data);
 399}
 400
 401/*
 402 * Flush all pending transmits and cancel any pending timeout work.
 403 *
 404 * This function is called with adap->lock held.
 405 */
 406static void cec_flush(struct cec_adapter *adap)
 407{
 408        struct cec_data *data, *n;
 409
 410        /*
 411         * If the adapter is disabled, or we're asked to stop,
 412         * then cancel any pending transmits.
 413         */
 414        while (!list_empty(&adap->transmit_queue)) {
 415                data = list_first_entry(&adap->transmit_queue,
 416                                        struct cec_data, list);
 417                cec_data_cancel(data, CEC_TX_STATUS_ABORTED);
 418        }
 419        if (adap->transmitting)
 420                cec_data_cancel(adap->transmitting, CEC_TX_STATUS_ABORTED);
 421
 422        /* Cancel the pending timeout work. */
 423        list_for_each_entry_safe(data, n, &adap->wait_queue, list) {
 424                if (cancel_delayed_work(&data->work))
 425                        cec_data_cancel(data, CEC_TX_STATUS_OK);
 426                /*
 427                 * If cancel_delayed_work returned false, then
 428                 * the cec_wait_timeout function is running,
 429                 * which will call cec_data_completed. So no
 430                 * need to do anything special in that case.
 431                 */
 432        }
 433}
 434
 435/*
 436 * Main CEC state machine
 437 *
 438 * Wait until the thread should be stopped, or we are not transmitting and
 439 * a new transmit message is queued up, in which case we start transmitting
 440 * that message. When the adapter finished transmitting the message it will
 441 * call cec_transmit_done().
 442 *
 443 * If the adapter is disabled, then remove all queued messages instead.
 444 *
 445 * If the current transmit times out, then cancel that transmit.
 446 */
 447int cec_thread_func(void *_adap)
 448{
 449        struct cec_adapter *adap = _adap;
 450
 451        for (;;) {
 452                unsigned int signal_free_time;
 453                struct cec_data *data;
 454                bool timeout = false;
 455                u8 attempts;
 456
 457                if (adap->transmitting) {
 458                        int err;
 459
 460                        /*
 461                         * We are transmitting a message, so add a timeout
 462                         * to prevent the state machine to get stuck waiting
 463                         * for this message to finalize and add a check to
 464                         * see if the adapter is disabled in which case the
 465                         * transmit should be canceled.
 466                         */
 467                        err = wait_event_interruptible_timeout(adap->kthread_waitq,
 468                                (adap->needs_hpd &&
 469                                 (!adap->is_configured && !adap->is_configuring)) ||
 470                                kthread_should_stop() ||
 471                                (!adap->transmit_in_progress &&
 472                                 !list_empty(&adap->transmit_queue)),
 473                                msecs_to_jiffies(CEC_XFER_TIMEOUT_MS));
 474                        timeout = err == 0;
 475                } else {
 476                        /* Otherwise we just wait for something to happen. */
 477                        wait_event_interruptible(adap->kthread_waitq,
 478                                kthread_should_stop() ||
 479                                (!adap->transmit_in_progress &&
 480                                 !list_empty(&adap->transmit_queue)));
 481                }
 482
 483                mutex_lock(&adap->lock);
 484
 485                if ((adap->needs_hpd &&
 486                     (!adap->is_configured && !adap->is_configuring)) ||
 487                    kthread_should_stop()) {
 488                        cec_flush(adap);
 489                        goto unlock;
 490                }
 491
 492                if (adap->transmitting && timeout) {
 493                        /*
 494                         * If we timeout, then log that. Normally this does
 495                         * not happen and it is an indication of a faulty CEC
 496                         * adapter driver, or the CEC bus is in some weird
 497                         * state. On rare occasions it can happen if there is
 498                         * so much traffic on the bus that the adapter was
 499                         * unable to transmit for CEC_XFER_TIMEOUT_MS (2.1s).
 500                         */
 501                        pr_warn("cec-%s: message %*ph timed out\n", adap->name,
 502                                adap->transmitting->msg.len,
 503                                adap->transmitting->msg.msg);
 504                        adap->transmit_in_progress = false;
 505                        adap->tx_timeouts++;
 506                        /* Just give up on this. */
 507                        cec_data_cancel(adap->transmitting,
 508                                        CEC_TX_STATUS_TIMEOUT);
 509                        goto unlock;
 510                }
 511
 512                /*
 513                 * If we are still transmitting, or there is nothing new to
 514                 * transmit, then just continue waiting.
 515                 */
 516                if (adap->transmit_in_progress || list_empty(&adap->transmit_queue))
 517                        goto unlock;
 518
 519                /* Get a new message to transmit */
 520                data = list_first_entry(&adap->transmit_queue,
 521                                        struct cec_data, list);
 522                list_del_init(&data->list);
 523                adap->transmit_queue_sz--;
 524
 525                /* Make this the current transmitting message */
 526                adap->transmitting = data;
 527
 528                /*
 529                 * Suggested number of attempts as per the CEC 2.0 spec:
 530                 * 4 attempts is the default, except for 'secondary poll
 531                 * messages', i.e. poll messages not sent during the adapter
 532                 * configuration phase when it allocates logical addresses.
 533                 */
 534                if (data->msg.len == 1 && adap->is_configured)
 535                        attempts = 2;
 536                else
 537                        attempts = 4;
 538
 539                /* Set the suggested signal free time */
 540                if (data->attempts) {
 541                        /* should be >= 3 data bit periods for a retry */
 542                        signal_free_time = CEC_SIGNAL_FREE_TIME_RETRY;
 543                } else if (adap->last_initiator !=
 544                           cec_msg_initiator(&data->msg)) {
 545                        /* should be >= 5 data bit periods for new initiator */
 546                        signal_free_time = CEC_SIGNAL_FREE_TIME_NEW_INITIATOR;
 547                        adap->last_initiator = cec_msg_initiator(&data->msg);
 548                } else {
 549                        /*
 550                         * should be >= 7 data bit periods for sending another
 551                         * frame immediately after another.
 552                         */
 553                        signal_free_time = CEC_SIGNAL_FREE_TIME_NEXT_XFER;
 554                }
 555                if (data->attempts == 0)
 556                        data->attempts = attempts;
 557
 558                /* Tell the adapter to transmit, cancel on error */
 559                if (adap->ops->adap_transmit(adap, data->attempts,
 560                                             signal_free_time, &data->msg))
 561                        cec_data_cancel(data, CEC_TX_STATUS_ABORTED);
 562                else
 563                        adap->transmit_in_progress = true;
 564
 565unlock:
 566                mutex_unlock(&adap->lock);
 567
 568                if (kthread_should_stop())
 569                        break;
 570        }
 571        return 0;
 572}
 573
 574/*
 575 * Called by the CEC adapter if a transmit finished.
 576 */
 577void cec_transmit_done_ts(struct cec_adapter *adap, u8 status,
 578                          u8 arb_lost_cnt, u8 nack_cnt, u8 low_drive_cnt,
 579                          u8 error_cnt, ktime_t ts)
 580{
 581        struct cec_data *data;
 582        struct cec_msg *msg;
 583        unsigned int attempts_made = arb_lost_cnt + nack_cnt +
 584                                     low_drive_cnt + error_cnt;
 585
 586        dprintk(2, "%s: status 0x%02x\n", __func__, status);
 587        if (attempts_made < 1)
 588                attempts_made = 1;
 589
 590        mutex_lock(&adap->lock);
 591        data = adap->transmitting;
 592        if (!data) {
 593                /*
 594                 * This might happen if a transmit was issued and the cable is
 595                 * unplugged while the transmit is ongoing. Ignore this
 596                 * transmit in that case.
 597                 */
 598                if (!adap->transmit_in_progress)
 599                        dprintk(1, "%s was called without an ongoing transmit!\n",
 600                                __func__);
 601                adap->transmit_in_progress = false;
 602                goto wake_thread;
 603        }
 604        adap->transmit_in_progress = false;
 605
 606        msg = &data->msg;
 607
 608        /* Drivers must fill in the status! */
 609        WARN_ON(status == 0);
 610        msg->tx_ts = ktime_to_ns(ts);
 611        msg->tx_status |= status;
 612        msg->tx_arb_lost_cnt += arb_lost_cnt;
 613        msg->tx_nack_cnt += nack_cnt;
 614        msg->tx_low_drive_cnt += low_drive_cnt;
 615        msg->tx_error_cnt += error_cnt;
 616
 617        /* Mark that we're done with this transmit */
 618        adap->transmitting = NULL;
 619
 620        /*
 621         * If there are still retry attempts left and there was an error and
 622         * the hardware didn't signal that it retried itself (by setting
 623         * CEC_TX_STATUS_MAX_RETRIES), then we will retry ourselves.
 624         */
 625        if (data->attempts > attempts_made &&
 626            !(status & (CEC_TX_STATUS_MAX_RETRIES | CEC_TX_STATUS_OK))) {
 627                /* Retry this message */
 628                data->attempts -= attempts_made;
 629                if (msg->timeout)
 630                        dprintk(2, "retransmit: %*ph (attempts: %d, wait for 0x%02x)\n",
 631                                msg->len, msg->msg, data->attempts, msg->reply);
 632                else
 633                        dprintk(2, "retransmit: %*ph (attempts: %d)\n",
 634                                msg->len, msg->msg, data->attempts);
 635                /* Add the message in front of the transmit queue */
 636                list_add(&data->list, &adap->transmit_queue);
 637                adap->transmit_queue_sz++;
 638                goto wake_thread;
 639        }
 640
 641        data->attempts = 0;
 642
 643        /* Always set CEC_TX_STATUS_MAX_RETRIES on error */
 644        if (!(status & CEC_TX_STATUS_OK))
 645                msg->tx_status |= CEC_TX_STATUS_MAX_RETRIES;
 646
 647        /* Queue transmitted message for monitoring purposes */
 648        cec_queue_msg_monitor(adap, msg, 1);
 649
 650        if ((status & CEC_TX_STATUS_OK) && adap->is_configured &&
 651            msg->timeout) {
 652                /*
 653                 * Queue the message into the wait queue if we want to wait
 654                 * for a reply.
 655                 */
 656                list_add_tail(&data->list, &adap->wait_queue);
 657                schedule_delayed_work(&data->work,
 658                                      msecs_to_jiffies(msg->timeout));
 659        } else {
 660                /* Otherwise we're done */
 661                cec_data_completed(data);
 662        }
 663
 664wake_thread:
 665        /*
 666         * Wake up the main thread to see if another message is ready
 667         * for transmitting or to retry the current message.
 668         */
 669        wake_up_interruptible(&adap->kthread_waitq);
 670        mutex_unlock(&adap->lock);
 671}
 672EXPORT_SYMBOL_GPL(cec_transmit_done_ts);
 673
 674void cec_transmit_attempt_done_ts(struct cec_adapter *adap,
 675                                  u8 status, ktime_t ts)
 676{
 677        switch (status & ~CEC_TX_STATUS_MAX_RETRIES) {
 678        case CEC_TX_STATUS_OK:
 679                cec_transmit_done_ts(adap, status, 0, 0, 0, 0, ts);
 680                return;
 681        case CEC_TX_STATUS_ARB_LOST:
 682                cec_transmit_done_ts(adap, status, 1, 0, 0, 0, ts);
 683                return;
 684        case CEC_TX_STATUS_NACK:
 685                cec_transmit_done_ts(adap, status, 0, 1, 0, 0, ts);
 686                return;
 687        case CEC_TX_STATUS_LOW_DRIVE:
 688                cec_transmit_done_ts(adap, status, 0, 0, 1, 0, ts);
 689                return;
 690        case CEC_TX_STATUS_ERROR:
 691                cec_transmit_done_ts(adap, status, 0, 0, 0, 1, ts);
 692                return;
 693        default:
 694                /* Should never happen */
 695                WARN(1, "cec-%s: invalid status 0x%02x\n", adap->name, status);
 696                return;
 697        }
 698}
 699EXPORT_SYMBOL_GPL(cec_transmit_attempt_done_ts);
 700
 701/*
 702 * Called when waiting for a reply times out.
 703 */
 704static void cec_wait_timeout(struct work_struct *work)
 705{
 706        struct cec_data *data = container_of(work, struct cec_data, work.work);
 707        struct cec_adapter *adap = data->adap;
 708
 709        mutex_lock(&adap->lock);
 710        /*
 711         * Sanity check in case the timeout and the arrival of the message
 712         * happened at the same time.
 713         */
 714        if (list_empty(&data->list))
 715                goto unlock;
 716
 717        /* Mark the message as timed out */
 718        list_del_init(&data->list);
 719        data->msg.rx_ts = ktime_get_ns();
 720        data->msg.rx_status = CEC_RX_STATUS_TIMEOUT;
 721        cec_data_completed(data);
 722unlock:
 723        mutex_unlock(&adap->lock);
 724}
 725
 726/*
 727 * Transmit a message. The fh argument may be NULL if the transmit is not
 728 * associated with a specific filehandle.
 729 *
 730 * This function is called with adap->lock held.
 731 */
 732int cec_transmit_msg_fh(struct cec_adapter *adap, struct cec_msg *msg,
 733                        struct cec_fh *fh, bool block)
 734{
 735        struct cec_data *data;
 736        bool is_raw = msg_is_raw(msg);
 737
 738        msg->rx_ts = 0;
 739        msg->tx_ts = 0;
 740        msg->rx_status = 0;
 741        msg->tx_status = 0;
 742        msg->tx_arb_lost_cnt = 0;
 743        msg->tx_nack_cnt = 0;
 744        msg->tx_low_drive_cnt = 0;
 745        msg->tx_error_cnt = 0;
 746        msg->sequence = 0;
 747
 748        if (msg->reply && msg->timeout == 0) {
 749                /* Make sure the timeout isn't 0. */
 750                msg->timeout = 1000;
 751        }
 752        msg->flags &= CEC_MSG_FL_REPLY_TO_FOLLOWERS | CEC_MSG_FL_RAW;
 753
 754        if (!msg->timeout)
 755                msg->flags &= ~CEC_MSG_FL_REPLY_TO_FOLLOWERS;
 756
 757        /* Sanity checks */
 758        if (msg->len == 0 || msg->len > CEC_MAX_MSG_SIZE) {
 759                dprintk(1, "%s: invalid length %d\n", __func__, msg->len);
 760                return -EINVAL;
 761        }
 762
 763        memset(msg->msg + msg->len, 0, sizeof(msg->msg) - msg->len);
 764
 765        if (msg->timeout)
 766                dprintk(2, "%s: %*ph (wait for 0x%02x%s)\n",
 767                        __func__, msg->len, msg->msg, msg->reply,
 768                        !block ? ", nb" : "");
 769        else
 770                dprintk(2, "%s: %*ph%s\n",
 771                        __func__, msg->len, msg->msg, !block ? " (nb)" : "");
 772
 773        if (msg->timeout && msg->len == 1) {
 774                dprintk(1, "%s: can't reply to poll msg\n", __func__);
 775                return -EINVAL;
 776        }
 777
 778        if (is_raw) {
 779                if (!capable(CAP_SYS_RAWIO))
 780                        return -EPERM;
 781        } else {
 782                /* A CDC-Only device can only send CDC messages */
 783                if ((adap->log_addrs.flags & CEC_LOG_ADDRS_FL_CDC_ONLY) &&
 784                    (msg->len == 1 || msg->msg[1] != CEC_MSG_CDC_MESSAGE)) {
 785                        dprintk(1, "%s: not a CDC message\n", __func__);
 786                        return -EINVAL;
 787                }
 788
 789                if (msg->len >= 4 && msg->msg[1] == CEC_MSG_CDC_MESSAGE) {
 790                        msg->msg[2] = adap->phys_addr >> 8;
 791                        msg->msg[3] = adap->phys_addr & 0xff;
 792                }
 793
 794                if (msg->len == 1) {
 795                        if (cec_msg_destination(msg) == 0xf) {
 796                                dprintk(1, "%s: invalid poll message\n",
 797                                        __func__);
 798                                return -EINVAL;
 799                        }
 800                        if (cec_has_log_addr(adap, cec_msg_destination(msg))) {
 801                                /*
 802                                 * If the destination is a logical address our
 803                                 * adapter has already claimed, then just NACK
 804                                 * this. It depends on the hardware what it will
 805                                 * do with a POLL to itself (some OK this), so
 806                                 * it is just as easy to handle it here so the
 807                                 * behavior will be consistent.
 808                                 */
 809                                msg->tx_ts = ktime_get_ns();
 810                                msg->tx_status = CEC_TX_STATUS_NACK |
 811                                        CEC_TX_STATUS_MAX_RETRIES;
 812                                msg->tx_nack_cnt = 1;
 813                                msg->sequence = ++adap->sequence;
 814                                if (!msg->sequence)
 815                                        msg->sequence = ++adap->sequence;
 816                                return 0;
 817                        }
 818                }
 819                if (msg->len > 1 && !cec_msg_is_broadcast(msg) &&
 820                    cec_has_log_addr(adap, cec_msg_destination(msg))) {
 821                        dprintk(1, "%s: destination is the adapter itself\n",
 822                                __func__);
 823                        return -EINVAL;
 824                }
 825                if (msg->len > 1 && adap->is_configured &&
 826                    !cec_has_log_addr(adap, cec_msg_initiator(msg))) {
 827                        dprintk(1, "%s: initiator has unknown logical address %d\n",
 828                                __func__, cec_msg_initiator(msg));
 829                        return -EINVAL;
 830                }
 831                /*
 832                 * Special case: allow Ping and IMAGE/TEXT_VIEW_ON to be
 833                 * transmitted to a TV, even if the adapter is unconfigured.
 834                 * This makes it possible to detect or wake up displays that
 835                 * pull down the HPD when in standby.
 836                 */
 837                if (!adap->is_configured && !adap->is_configuring &&
 838                    (msg->len > 2 ||
 839                     cec_msg_destination(msg) != CEC_LOG_ADDR_TV ||
 840                     (msg->len == 2 && msg->msg[1] != CEC_MSG_IMAGE_VIEW_ON &&
 841                      msg->msg[1] != CEC_MSG_TEXT_VIEW_ON))) {
 842                        dprintk(1, "%s: adapter is unconfigured\n", __func__);
 843                        return -ENONET;
 844                }
 845        }
 846
 847        if (!adap->is_configured && !adap->is_configuring) {
 848                if (adap->needs_hpd) {
 849                        dprintk(1, "%s: adapter is unconfigured and needs HPD\n",
 850                                __func__);
 851                        return -ENONET;
 852                }
 853                if (msg->reply) {
 854                        dprintk(1, "%s: invalid msg->reply\n", __func__);
 855                        return -EINVAL;
 856                }
 857        }
 858
 859        if (adap->transmit_queue_sz >= CEC_MAX_MSG_TX_QUEUE_SZ) {
 860                dprintk(2, "%s: transmit queue full\n", __func__);
 861                return -EBUSY;
 862        }
 863
 864        data = kzalloc(sizeof(*data), GFP_KERNEL);
 865        if (!data)
 866                return -ENOMEM;
 867
 868        msg->sequence = ++adap->sequence;
 869        if (!msg->sequence)
 870                msg->sequence = ++adap->sequence;
 871
 872        data->msg = *msg;
 873        data->fh = fh;
 874        data->adap = adap;
 875        data->blocking = block;
 876
 877        init_completion(&data->c);
 878        INIT_DELAYED_WORK(&data->work, cec_wait_timeout);
 879
 880        if (fh)
 881                list_add_tail(&data->xfer_list, &fh->xfer_list);
 882
 883        list_add_tail(&data->list, &adap->transmit_queue);
 884        adap->transmit_queue_sz++;
 885        if (!adap->transmitting)
 886                wake_up_interruptible(&adap->kthread_waitq);
 887
 888        /* All done if we don't need to block waiting for completion */
 889        if (!block)
 890                return 0;
 891
 892        /*
 893         * Release the lock and wait, retake the lock afterwards.
 894         */
 895        mutex_unlock(&adap->lock);
 896        wait_for_completion_killable(&data->c);
 897        if (!data->completed)
 898                cancel_delayed_work_sync(&data->work);
 899        mutex_lock(&adap->lock);
 900
 901        /* Cancel the transmit if it was interrupted */
 902        if (!data->completed)
 903                cec_data_cancel(data, CEC_TX_STATUS_ABORTED);
 904
 905        /* The transmit completed (possibly with an error) */
 906        *msg = data->msg;
 907        kfree(data);
 908        return 0;
 909}
 910
 911/* Helper function to be used by drivers and this framework. */
 912int cec_transmit_msg(struct cec_adapter *adap, struct cec_msg *msg,
 913                     bool block)
 914{
 915        int ret;
 916
 917        mutex_lock(&adap->lock);
 918        ret = cec_transmit_msg_fh(adap, msg, NULL, block);
 919        mutex_unlock(&adap->lock);
 920        return ret;
 921}
 922EXPORT_SYMBOL_GPL(cec_transmit_msg);
 923
 924/*
 925 * I don't like forward references but without this the low-level
 926 * cec_received_msg() function would come after a bunch of high-level
 927 * CEC protocol handling functions. That was very confusing.
 928 */
 929static int cec_receive_notify(struct cec_adapter *adap, struct cec_msg *msg,
 930                              bool is_reply);
 931
 932#define DIRECTED        0x80
 933#define BCAST1_4        0x40
 934#define BCAST2_0        0x20    /* broadcast only allowed for >= 2.0 */
 935#define BCAST           (BCAST1_4 | BCAST2_0)
 936#define BOTH            (BCAST | DIRECTED)
 937
 938/*
 939 * Specify minimum length and whether the message is directed, broadcast
 940 * or both. Messages that do not match the criteria are ignored as per
 941 * the CEC specification.
 942 */
 943static const u8 cec_msg_size[256] = {
 944        [CEC_MSG_ACTIVE_SOURCE] = 4 | BCAST,
 945        [CEC_MSG_IMAGE_VIEW_ON] = 2 | DIRECTED,
 946        [CEC_MSG_TEXT_VIEW_ON] = 2 | DIRECTED,
 947        [CEC_MSG_INACTIVE_SOURCE] = 4 | DIRECTED,
 948        [CEC_MSG_REQUEST_ACTIVE_SOURCE] = 2 | BCAST,
 949        [CEC_MSG_ROUTING_CHANGE] = 6 | BCAST,
 950        [CEC_MSG_ROUTING_INFORMATION] = 4 | BCAST,
 951        [CEC_MSG_SET_STREAM_PATH] = 4 | BCAST,
 952        [CEC_MSG_STANDBY] = 2 | BOTH,
 953        [CEC_MSG_RECORD_OFF] = 2 | DIRECTED,
 954        [CEC_MSG_RECORD_ON] = 3 | DIRECTED,
 955        [CEC_MSG_RECORD_STATUS] = 3 | DIRECTED,
 956        [CEC_MSG_RECORD_TV_SCREEN] = 2 | DIRECTED,
 957        [CEC_MSG_CLEAR_ANALOGUE_TIMER] = 13 | DIRECTED,
 958        [CEC_MSG_CLEAR_DIGITAL_TIMER] = 16 | DIRECTED,
 959        [CEC_MSG_CLEAR_EXT_TIMER] = 13 | DIRECTED,
 960        [CEC_MSG_SET_ANALOGUE_TIMER] = 13 | DIRECTED,
 961        [CEC_MSG_SET_DIGITAL_TIMER] = 16 | DIRECTED,
 962        [CEC_MSG_SET_EXT_TIMER] = 13 | DIRECTED,
 963        [CEC_MSG_SET_TIMER_PROGRAM_TITLE] = 2 | DIRECTED,
 964        [CEC_MSG_TIMER_CLEARED_STATUS] = 3 | DIRECTED,
 965        [CEC_MSG_TIMER_STATUS] = 3 | DIRECTED,
 966        [CEC_MSG_CEC_VERSION] = 3 | DIRECTED,
 967        [CEC_MSG_GET_CEC_VERSION] = 2 | DIRECTED,
 968        [CEC_MSG_GIVE_PHYSICAL_ADDR] = 2 | DIRECTED,
 969        [CEC_MSG_GET_MENU_LANGUAGE] = 2 | DIRECTED,
 970        [CEC_MSG_REPORT_PHYSICAL_ADDR] = 5 | BCAST,
 971        [CEC_MSG_SET_MENU_LANGUAGE] = 5 | BCAST,
 972        [CEC_MSG_REPORT_FEATURES] = 6 | BCAST,
 973        [CEC_MSG_GIVE_FEATURES] = 2 | DIRECTED,
 974        [CEC_MSG_DECK_CONTROL] = 3 | DIRECTED,
 975        [CEC_MSG_DECK_STATUS] = 3 | DIRECTED,
 976        [CEC_MSG_GIVE_DECK_STATUS] = 3 | DIRECTED,
 977        [CEC_MSG_PLAY] = 3 | DIRECTED,
 978        [CEC_MSG_GIVE_TUNER_DEVICE_STATUS] = 3 | DIRECTED,
 979        [CEC_MSG_SELECT_ANALOGUE_SERVICE] = 6 | DIRECTED,
 980        [CEC_MSG_SELECT_DIGITAL_SERVICE] = 9 | DIRECTED,
 981        [CEC_MSG_TUNER_DEVICE_STATUS] = 7 | DIRECTED,
 982        [CEC_MSG_TUNER_STEP_DECREMENT] = 2 | DIRECTED,
 983        [CEC_MSG_TUNER_STEP_INCREMENT] = 2 | DIRECTED,
 984        [CEC_MSG_DEVICE_VENDOR_ID] = 5 | BCAST,
 985        [CEC_MSG_GIVE_DEVICE_VENDOR_ID] = 2 | DIRECTED,
 986        [CEC_MSG_VENDOR_COMMAND] = 2 | DIRECTED,
 987        [CEC_MSG_VENDOR_COMMAND_WITH_ID] = 5 | BOTH,
 988        [CEC_MSG_VENDOR_REMOTE_BUTTON_DOWN] = 2 | BOTH,
 989        [CEC_MSG_VENDOR_REMOTE_BUTTON_UP] = 2 | BOTH,
 990        [CEC_MSG_SET_OSD_STRING] = 3 | DIRECTED,
 991        [CEC_MSG_GIVE_OSD_NAME] = 2 | DIRECTED,
 992        [CEC_MSG_SET_OSD_NAME] = 2 | DIRECTED,
 993        [CEC_MSG_MENU_REQUEST] = 3 | DIRECTED,
 994        [CEC_MSG_MENU_STATUS] = 3 | DIRECTED,
 995        [CEC_MSG_USER_CONTROL_PRESSED] = 3 | DIRECTED,
 996        [CEC_MSG_USER_CONTROL_RELEASED] = 2 | DIRECTED,
 997        [CEC_MSG_GIVE_DEVICE_POWER_STATUS] = 2 | DIRECTED,
 998        [CEC_MSG_REPORT_POWER_STATUS] = 3 | DIRECTED | BCAST2_0,
 999        [CEC_MSG_FEATURE_ABORT] = 4 | DIRECTED,
1000        [CEC_MSG_ABORT] = 2 | DIRECTED,
1001        [CEC_MSG_GIVE_AUDIO_STATUS] = 2 | DIRECTED,
1002        [CEC_MSG_GIVE_SYSTEM_AUDIO_MODE_STATUS] = 2 | DIRECTED,
1003        [CEC_MSG_REPORT_AUDIO_STATUS] = 3 | DIRECTED,
1004        [CEC_MSG_REPORT_SHORT_AUDIO_DESCRIPTOR] = 2 | DIRECTED,
1005        [CEC_MSG_REQUEST_SHORT_AUDIO_DESCRIPTOR] = 2 | DIRECTED,
1006        [CEC_MSG_SET_SYSTEM_AUDIO_MODE] = 3 | BOTH,
1007        [CEC_MSG_SYSTEM_AUDIO_MODE_REQUEST] = 2 | DIRECTED,
1008        [CEC_MSG_SYSTEM_AUDIO_MODE_STATUS] = 3 | DIRECTED,
1009        [CEC_MSG_SET_AUDIO_RATE] = 3 | DIRECTED,
1010        [CEC_MSG_INITIATE_ARC] = 2 | DIRECTED,
1011        [CEC_MSG_REPORT_ARC_INITIATED] = 2 | DIRECTED,
1012        [CEC_MSG_REPORT_ARC_TERMINATED] = 2 | DIRECTED,
1013        [CEC_MSG_REQUEST_ARC_INITIATION] = 2 | DIRECTED,
1014        [CEC_MSG_REQUEST_ARC_TERMINATION] = 2 | DIRECTED,
1015        [CEC_MSG_TERMINATE_ARC] = 2 | DIRECTED,
1016        [CEC_MSG_REQUEST_CURRENT_LATENCY] = 4 | BCAST,
1017        [CEC_MSG_REPORT_CURRENT_LATENCY] = 6 | BCAST,
1018        [CEC_MSG_CDC_MESSAGE] = 2 | BCAST,
1019};
1020
1021/* Called by the CEC adapter if a message is received */
1022void cec_received_msg_ts(struct cec_adapter *adap,
1023                         struct cec_msg *msg, ktime_t ts)
1024{
1025        struct cec_data *data;
1026        u8 msg_init = cec_msg_initiator(msg);
1027        u8 msg_dest = cec_msg_destination(msg);
1028        u8 cmd = msg->msg[1];
1029        bool is_reply = false;
1030        bool valid_la = true;
1031        u8 min_len = 0;
1032
1033        if (WARN_ON(!msg->len || msg->len > CEC_MAX_MSG_SIZE))
1034                return;
1035
1036        /*
1037         * Some CEC adapters will receive the messages that they transmitted.
1038         * This test filters out those messages by checking if we are the
1039         * initiator, and just returning in that case.
1040         *
1041         * Note that this won't work if this is an Unregistered device.
1042         *
1043         * It is bad practice if the hardware receives the message that it
1044         * transmitted and luckily most CEC adapters behave correctly in this
1045         * respect.
1046         */
1047        if (msg_init != CEC_LOG_ADDR_UNREGISTERED &&
1048            cec_has_log_addr(adap, msg_init))
1049                return;
1050
1051        msg->rx_ts = ktime_to_ns(ts);
1052        msg->rx_status = CEC_RX_STATUS_OK;
1053        msg->sequence = msg->reply = msg->timeout = 0;
1054        msg->tx_status = 0;
1055        msg->tx_ts = 0;
1056        msg->tx_arb_lost_cnt = 0;
1057        msg->tx_nack_cnt = 0;
1058        msg->tx_low_drive_cnt = 0;
1059        msg->tx_error_cnt = 0;
1060        msg->flags = 0;
1061        memset(msg->msg + msg->len, 0, sizeof(msg->msg) - msg->len);
1062
1063        mutex_lock(&adap->lock);
1064        dprintk(2, "%s: %*ph\n", __func__, msg->len, msg->msg);
1065
1066        adap->last_initiator = 0xff;
1067
1068        /* Check if this message was for us (directed or broadcast). */
1069        if (!cec_msg_is_broadcast(msg))
1070                valid_la = cec_has_log_addr(adap, msg_dest);
1071
1072        /*
1073         * Check if the length is not too short or if the message is a
1074         * broadcast message where a directed message was expected or
1075         * vice versa. If so, then the message has to be ignored (according
1076         * to section CEC 7.3 and CEC 12.2).
1077         */
1078        if (valid_la && msg->len > 1 && cec_msg_size[cmd]) {
1079                u8 dir_fl = cec_msg_size[cmd] & BOTH;
1080
1081                min_len = cec_msg_size[cmd] & 0x1f;
1082                if (msg->len < min_len)
1083                        valid_la = false;
1084                else if (!cec_msg_is_broadcast(msg) && !(dir_fl & DIRECTED))
1085                        valid_la = false;
1086                else if (cec_msg_is_broadcast(msg) && !(dir_fl & BCAST1_4))
1087                        valid_la = false;
1088                else if (cec_msg_is_broadcast(msg) &&
1089                         adap->log_addrs.cec_version >= CEC_OP_CEC_VERSION_2_0 &&
1090                         !(dir_fl & BCAST2_0))
1091                        valid_la = false;
1092        }
1093        if (valid_la && min_len) {
1094                /* These messages have special length requirements */
1095                switch (cmd) {
1096                case CEC_MSG_TIMER_STATUS:
1097                        if (msg->msg[2] & 0x10) {
1098                                switch (msg->msg[2] & 0xf) {
1099                                case CEC_OP_PROG_INFO_NOT_ENOUGH_SPACE:
1100                                case CEC_OP_PROG_INFO_MIGHT_NOT_BE_ENOUGH_SPACE:
1101                                        if (msg->len < 5)
1102                                                valid_la = false;
1103                                        break;
1104                                }
1105                        } else if ((msg->msg[2] & 0xf) == CEC_OP_PROG_ERROR_DUPLICATE) {
1106                                if (msg->len < 5)
1107                                        valid_la = false;
1108                        }
1109                        break;
1110                case CEC_MSG_RECORD_ON:
1111                        switch (msg->msg[2]) {
1112                        case CEC_OP_RECORD_SRC_OWN:
1113                                break;
1114                        case CEC_OP_RECORD_SRC_DIGITAL:
1115                                if (msg->len < 10)
1116                                        valid_la = false;
1117                                break;
1118                        case CEC_OP_RECORD_SRC_ANALOG:
1119                                if (msg->len < 7)
1120                                        valid_la = false;
1121                                break;
1122                        case CEC_OP_RECORD_SRC_EXT_PLUG:
1123                                if (msg->len < 4)
1124                                        valid_la = false;
1125                                break;
1126                        case CEC_OP_RECORD_SRC_EXT_PHYS_ADDR:
1127                                if (msg->len < 5)
1128                                        valid_la = false;
1129                                break;
1130                        }
1131                        break;
1132                }
1133        }
1134
1135        /* It's a valid message and not a poll or CDC message */
1136        if (valid_la && msg->len > 1 && cmd != CEC_MSG_CDC_MESSAGE) {
1137                bool abort = cmd == CEC_MSG_FEATURE_ABORT;
1138
1139                /* The aborted command is in msg[2] */
1140                if (abort)
1141                        cmd = msg->msg[2];
1142
1143                /*
1144                 * Walk over all transmitted messages that are waiting for a
1145                 * reply.
1146                 */
1147                list_for_each_entry(data, &adap->wait_queue, list) {
1148                        struct cec_msg *dst = &data->msg;
1149
1150                        /*
1151                         * The *only* CEC message that has two possible replies
1152                         * is CEC_MSG_INITIATE_ARC.
1153                         * In this case allow either of the two replies.
1154                         */
1155                        if (!abort && dst->msg[1] == CEC_MSG_INITIATE_ARC &&
1156                            (cmd == CEC_MSG_REPORT_ARC_INITIATED ||
1157                             cmd == CEC_MSG_REPORT_ARC_TERMINATED) &&
1158                            (dst->reply == CEC_MSG_REPORT_ARC_INITIATED ||
1159                             dst->reply == CEC_MSG_REPORT_ARC_TERMINATED))
1160                                dst->reply = cmd;
1161
1162                        /* Does the command match? */
1163                        if ((abort && cmd != dst->msg[1]) ||
1164                            (!abort && cmd != dst->reply))
1165                                continue;
1166
1167                        /* Does the addressing match? */
1168                        if (msg_init != cec_msg_destination(dst) &&
1169                            !cec_msg_is_broadcast(dst))
1170                                continue;
1171
1172                        /* We got a reply */
1173                        memcpy(dst->msg, msg->msg, msg->len);
1174                        dst->len = msg->len;
1175                        dst->rx_ts = msg->rx_ts;
1176                        dst->rx_status = msg->rx_status;
1177                        if (abort)
1178                                dst->rx_status |= CEC_RX_STATUS_FEATURE_ABORT;
1179                        msg->flags = dst->flags;
1180                        /* Remove it from the wait_queue */
1181                        list_del_init(&data->list);
1182
1183                        /* Cancel the pending timeout work */
1184                        if (!cancel_delayed_work(&data->work)) {
1185                                mutex_unlock(&adap->lock);
1186                                flush_scheduled_work();
1187                                mutex_lock(&adap->lock);
1188                        }
1189                        /*
1190                         * Mark this as a reply, provided someone is still
1191                         * waiting for the answer.
1192                         */
1193                        if (data->fh)
1194                                is_reply = true;
1195                        cec_data_completed(data);
1196                        break;
1197                }
1198        }
1199        mutex_unlock(&adap->lock);
1200
1201        /* Pass the message on to any monitoring filehandles */
1202        cec_queue_msg_monitor(adap, msg, valid_la);
1203
1204        /* We're done if it is not for us or a poll message */
1205        if (!valid_la || msg->len <= 1)
1206                return;
1207
1208        if (adap->log_addrs.log_addr_mask == 0)
1209                return;
1210
1211        /*
1212         * Process the message on the protocol level. If is_reply is true,
1213         * then cec_receive_notify() won't pass on the reply to the listener(s)
1214         * since that was already done by cec_data_completed() above.
1215         */
1216        cec_receive_notify(adap, msg, is_reply);
1217}
1218EXPORT_SYMBOL_GPL(cec_received_msg_ts);
1219
1220/* Logical Address Handling */
1221
1222/*
1223 * Attempt to claim a specific logical address.
1224 *
1225 * This function is called with adap->lock held.
1226 */
1227static int cec_config_log_addr(struct cec_adapter *adap,
1228                               unsigned int idx,
1229                               unsigned int log_addr)
1230{
1231        struct cec_log_addrs *las = &adap->log_addrs;
1232        struct cec_msg msg = { };
1233        const unsigned int max_retries = 2;
1234        unsigned int i;
1235        int err;
1236
1237        if (cec_has_log_addr(adap, log_addr))
1238                return 0;
1239
1240        /* Send poll message */
1241        msg.len = 1;
1242        msg.msg[0] = (log_addr << 4) | log_addr;
1243
1244        for (i = 0; i < max_retries; i++) {
1245                err = cec_transmit_msg_fh(adap, &msg, NULL, true);
1246
1247                /*
1248                 * While trying to poll the physical address was reset
1249                 * and the adapter was unconfigured, so bail out.
1250                 */
1251                if (!adap->is_configuring)
1252                        return -EINTR;
1253
1254                if (err)
1255                        return err;
1256
1257                /*
1258                 * The message was aborted due to a disconnect or
1259                 * unconfigure, just bail out.
1260                 */
1261                if (msg.tx_status & CEC_TX_STATUS_ABORTED)
1262                        return -EINTR;
1263                if (msg.tx_status & CEC_TX_STATUS_OK)
1264                        return 0;
1265                if (msg.tx_status & CEC_TX_STATUS_NACK)
1266                        break;
1267                /*
1268                 * Retry up to max_retries times if the message was neither
1269                 * OKed or NACKed. This can happen due to e.g. a Lost
1270                 * Arbitration condition.
1271                 */
1272        }
1273
1274        /*
1275         * If we are unable to get an OK or a NACK after max_retries attempts
1276         * (and note that each attempt already consists of four polls), then
1277         * then we assume that something is really weird and that it is not a
1278         * good idea to try and claim this logical address.
1279         */
1280        if (i == max_retries)
1281                return 0;
1282
1283        /*
1284         * Message not acknowledged, so this logical
1285         * address is free to use.
1286         */
1287        err = adap->ops->adap_log_addr(adap, log_addr);
1288        if (err)
1289                return err;
1290
1291        las->log_addr[idx] = log_addr;
1292        las->log_addr_mask |= 1 << log_addr;
1293        adap->phys_addrs[log_addr] = adap->phys_addr;
1294        return 1;
1295}
1296
1297/*
1298 * Unconfigure the adapter: clear all logical addresses and send
1299 * the state changed event.
1300 *
1301 * This function is called with adap->lock held.
1302 */
1303static void cec_adap_unconfigure(struct cec_adapter *adap)
1304{
1305        if (!adap->needs_hpd ||
1306            adap->phys_addr != CEC_PHYS_ADDR_INVALID)
1307                WARN_ON(adap->ops->adap_log_addr(adap, CEC_LOG_ADDR_INVALID));
1308        adap->log_addrs.log_addr_mask = 0;
1309        adap->is_configuring = false;
1310        adap->is_configured = false;
1311        memset(adap->phys_addrs, 0xff, sizeof(adap->phys_addrs));
1312        cec_flush(adap);
1313        wake_up_interruptible(&adap->kthread_waitq);
1314        cec_post_state_event(adap);
1315}
1316
1317/*
1318 * Attempt to claim the required logical addresses.
1319 */
1320static int cec_config_thread_func(void *arg)
1321{
1322        /* The various LAs for each type of device */
1323        static const u8 tv_log_addrs[] = {
1324                CEC_LOG_ADDR_TV, CEC_LOG_ADDR_SPECIFIC,
1325                CEC_LOG_ADDR_INVALID
1326        };
1327        static const u8 record_log_addrs[] = {
1328                CEC_LOG_ADDR_RECORD_1, CEC_LOG_ADDR_RECORD_2,
1329                CEC_LOG_ADDR_RECORD_3,
1330                CEC_LOG_ADDR_BACKUP_1, CEC_LOG_ADDR_BACKUP_2,
1331                CEC_LOG_ADDR_INVALID
1332        };
1333        static const u8 tuner_log_addrs[] = {
1334                CEC_LOG_ADDR_TUNER_1, CEC_LOG_ADDR_TUNER_2,
1335                CEC_LOG_ADDR_TUNER_3, CEC_LOG_ADDR_TUNER_4,
1336                CEC_LOG_ADDR_BACKUP_1, CEC_LOG_ADDR_BACKUP_2,
1337                CEC_LOG_ADDR_INVALID
1338        };
1339        static const u8 playback_log_addrs[] = {
1340                CEC_LOG_ADDR_PLAYBACK_1, CEC_LOG_ADDR_PLAYBACK_2,
1341                CEC_LOG_ADDR_PLAYBACK_3,
1342                CEC_LOG_ADDR_BACKUP_1, CEC_LOG_ADDR_BACKUP_2,
1343                CEC_LOG_ADDR_INVALID
1344        };
1345        static const u8 audiosystem_log_addrs[] = {
1346                CEC_LOG_ADDR_AUDIOSYSTEM,
1347                CEC_LOG_ADDR_INVALID
1348        };
1349        static const u8 specific_use_log_addrs[] = {
1350                CEC_LOG_ADDR_SPECIFIC,
1351                CEC_LOG_ADDR_BACKUP_1, CEC_LOG_ADDR_BACKUP_2,
1352                CEC_LOG_ADDR_INVALID
1353        };
1354        static const u8 *type2addrs[6] = {
1355                [CEC_LOG_ADDR_TYPE_TV] = tv_log_addrs,
1356                [CEC_LOG_ADDR_TYPE_RECORD] = record_log_addrs,
1357                [CEC_LOG_ADDR_TYPE_TUNER] = tuner_log_addrs,
1358                [CEC_LOG_ADDR_TYPE_PLAYBACK] = playback_log_addrs,
1359                [CEC_LOG_ADDR_TYPE_AUDIOSYSTEM] = audiosystem_log_addrs,
1360                [CEC_LOG_ADDR_TYPE_SPECIFIC] = specific_use_log_addrs,
1361        };
1362        static const u16 type2mask[] = {
1363                [CEC_LOG_ADDR_TYPE_TV] = CEC_LOG_ADDR_MASK_TV,
1364                [CEC_LOG_ADDR_TYPE_RECORD] = CEC_LOG_ADDR_MASK_RECORD,
1365                [CEC_LOG_ADDR_TYPE_TUNER] = CEC_LOG_ADDR_MASK_TUNER,
1366                [CEC_LOG_ADDR_TYPE_PLAYBACK] = CEC_LOG_ADDR_MASK_PLAYBACK,
1367                [CEC_LOG_ADDR_TYPE_AUDIOSYSTEM] = CEC_LOG_ADDR_MASK_AUDIOSYSTEM,
1368                [CEC_LOG_ADDR_TYPE_SPECIFIC] = CEC_LOG_ADDR_MASK_SPECIFIC,
1369        };
1370        struct cec_adapter *adap = arg;
1371        struct cec_log_addrs *las = &adap->log_addrs;
1372        int err;
1373        int i, j;
1374
1375        mutex_lock(&adap->lock);
1376        dprintk(1, "physical address: %x.%x.%x.%x, claim %d logical addresses\n",
1377                cec_phys_addr_exp(adap->phys_addr), las->num_log_addrs);
1378        las->log_addr_mask = 0;
1379
1380        if (las->log_addr_type[0] == CEC_LOG_ADDR_TYPE_UNREGISTERED)
1381                goto configured;
1382
1383        for (i = 0; i < las->num_log_addrs; i++) {
1384                unsigned int type = las->log_addr_type[i];
1385                const u8 *la_list;
1386                u8 last_la;
1387
1388                /*
1389                 * The TV functionality can only map to physical address 0.
1390                 * For any other address, try the Specific functionality
1391                 * instead as per the spec.
1392                 */
1393                if (adap->phys_addr && type == CEC_LOG_ADDR_TYPE_TV)
1394                        type = CEC_LOG_ADDR_TYPE_SPECIFIC;
1395
1396                la_list = type2addrs[type];
1397                last_la = las->log_addr[i];
1398                las->log_addr[i] = CEC_LOG_ADDR_INVALID;
1399                if (last_la == CEC_LOG_ADDR_INVALID ||
1400                    last_la == CEC_LOG_ADDR_UNREGISTERED ||
1401                    !((1 << last_la) & type2mask[type]))
1402                        last_la = la_list[0];
1403
1404                err = cec_config_log_addr(adap, i, last_la);
1405                if (err > 0) /* Reused last LA */
1406                        continue;
1407
1408                if (err < 0)
1409                        goto unconfigure;
1410
1411                for (j = 0; la_list[j] != CEC_LOG_ADDR_INVALID; j++) {
1412                        /* Tried this one already, skip it */
1413                        if (la_list[j] == last_la)
1414                                continue;
1415                        /* The backup addresses are CEC 2.0 specific */
1416                        if ((la_list[j] == CEC_LOG_ADDR_BACKUP_1 ||
1417                             la_list[j] == CEC_LOG_ADDR_BACKUP_2) &&
1418                            las->cec_version < CEC_OP_CEC_VERSION_2_0)
1419                                continue;
1420
1421                        err = cec_config_log_addr(adap, i, la_list[j]);
1422                        if (err == 0) /* LA is in use */
1423                                continue;
1424                        if (err < 0)
1425                                goto unconfigure;
1426                        /* Done, claimed an LA */
1427                        break;
1428                }
1429
1430                if (la_list[j] == CEC_LOG_ADDR_INVALID)
1431                        dprintk(1, "could not claim LA %d\n", i);
1432        }
1433
1434        if (adap->log_addrs.log_addr_mask == 0 &&
1435            !(las->flags & CEC_LOG_ADDRS_FL_ALLOW_UNREG_FALLBACK))
1436                goto unconfigure;
1437
1438configured:
1439        if (adap->log_addrs.log_addr_mask == 0) {
1440                /* Fall back to unregistered */
1441                las->log_addr[0] = CEC_LOG_ADDR_UNREGISTERED;
1442                las->log_addr_mask = 1 << las->log_addr[0];
1443                for (i = 1; i < las->num_log_addrs; i++)
1444                        las->log_addr[i] = CEC_LOG_ADDR_INVALID;
1445        }
1446        for (i = las->num_log_addrs; i < CEC_MAX_LOG_ADDRS; i++)
1447                las->log_addr[i] = CEC_LOG_ADDR_INVALID;
1448        adap->is_configured = true;
1449        adap->is_configuring = false;
1450        cec_post_state_event(adap);
1451
1452        /*
1453         * Now post the Report Features and Report Physical Address broadcast
1454         * messages. Note that these are non-blocking transmits, meaning that
1455         * they are just queued up and once adap->lock is unlocked the main
1456         * thread will kick in and start transmitting these.
1457         *
1458         * If after this function is done (but before one or more of these
1459         * messages are actually transmitted) the CEC adapter is unconfigured,
1460         * then any remaining messages will be dropped by the main thread.
1461         */
1462        for (i = 0; i < las->num_log_addrs; i++) {
1463                struct cec_msg msg = {};
1464
1465                if (las->log_addr[i] == CEC_LOG_ADDR_INVALID ||
1466                    (las->flags & CEC_LOG_ADDRS_FL_CDC_ONLY))
1467                        continue;
1468
1469                msg.msg[0] = (las->log_addr[i] << 4) | 0x0f;
1470
1471                /* Report Features must come first according to CEC 2.0 */
1472                if (las->log_addr[i] != CEC_LOG_ADDR_UNREGISTERED &&
1473                    adap->log_addrs.cec_version >= CEC_OP_CEC_VERSION_2_0) {
1474                        cec_fill_msg_report_features(adap, &msg, i);
1475                        cec_transmit_msg_fh(adap, &msg, NULL, false);
1476                }
1477
1478                /* Report Physical Address */
1479                cec_msg_report_physical_addr(&msg, adap->phys_addr,
1480                                             las->primary_device_type[i]);
1481                dprintk(1, "config: la %d pa %x.%x.%x.%x\n",
1482                        las->log_addr[i],
1483                        cec_phys_addr_exp(adap->phys_addr));
1484                cec_transmit_msg_fh(adap, &msg, NULL, false);
1485
1486                /* Report Vendor ID */
1487                if (adap->log_addrs.vendor_id != CEC_VENDOR_ID_NONE) {
1488                        cec_msg_device_vendor_id(&msg,
1489                                                 adap->log_addrs.vendor_id);
1490                        cec_transmit_msg_fh(adap, &msg, NULL, false);
1491                }
1492        }
1493        adap->kthread_config = NULL;
1494        complete(&adap->config_completion);
1495        mutex_unlock(&adap->lock);
1496        return 0;
1497
1498unconfigure:
1499        for (i = 0; i < las->num_log_addrs; i++)
1500                las->log_addr[i] = CEC_LOG_ADDR_INVALID;
1501        cec_adap_unconfigure(adap);
1502        adap->kthread_config = NULL;
1503        mutex_unlock(&adap->lock);
1504        complete(&adap->config_completion);
1505        return 0;
1506}
1507
1508/*
1509 * Called from either __cec_s_phys_addr or __cec_s_log_addrs to claim the
1510 * logical addresses.
1511 *
1512 * This function is called with adap->lock held.
1513 */
1514static void cec_claim_log_addrs(struct cec_adapter *adap, bool block)
1515{
1516        if (WARN_ON(adap->is_configuring || adap->is_configured))
1517                return;
1518
1519        init_completion(&adap->config_completion);
1520
1521        /* Ready to kick off the thread */
1522        adap->is_configuring = true;
1523        adap->kthread_config = kthread_run(cec_config_thread_func, adap,
1524                                           "ceccfg-%s", adap->name);
1525        if (IS_ERR(adap->kthread_config)) {
1526                adap->kthread_config = NULL;
1527        } else if (block) {
1528                mutex_unlock(&adap->lock);
1529                wait_for_completion(&adap->config_completion);
1530                mutex_lock(&adap->lock);
1531        }
1532}
1533
1534/* Set a new physical address and send an event notifying userspace of this.
1535 *
1536 * This function is called with adap->lock held.
1537 */
1538void __cec_s_phys_addr(struct cec_adapter *adap, u16 phys_addr, bool block)
1539{
1540        if (phys_addr == adap->phys_addr)
1541                return;
1542        if (phys_addr != CEC_PHYS_ADDR_INVALID && adap->devnode.unregistered)
1543                return;
1544
1545        dprintk(1, "new physical address %x.%x.%x.%x\n",
1546                cec_phys_addr_exp(phys_addr));
1547        if (phys_addr == CEC_PHYS_ADDR_INVALID ||
1548            adap->phys_addr != CEC_PHYS_ADDR_INVALID) {
1549                adap->phys_addr = CEC_PHYS_ADDR_INVALID;
1550                cec_post_state_event(adap);
1551                cec_adap_unconfigure(adap);
1552                /* Disabling monitor all mode should always succeed */
1553                if (adap->monitor_all_cnt)
1554                        WARN_ON(call_op(adap, adap_monitor_all_enable, false));
1555                mutex_lock(&adap->devnode.lock);
1556                if (adap->needs_hpd || list_empty(&adap->devnode.fhs)) {
1557                        WARN_ON(adap->ops->adap_enable(adap, false));
1558                        adap->transmit_in_progress = false;
1559                        wake_up_interruptible(&adap->kthread_waitq);
1560                }
1561                mutex_unlock(&adap->devnode.lock);
1562                if (phys_addr == CEC_PHYS_ADDR_INVALID)
1563                        return;
1564        }
1565
1566        mutex_lock(&adap->devnode.lock);
1567        adap->last_initiator = 0xff;
1568        adap->transmit_in_progress = false;
1569
1570        if ((adap->needs_hpd || list_empty(&adap->devnode.fhs)) &&
1571            adap->ops->adap_enable(adap, true)) {
1572                mutex_unlock(&adap->devnode.lock);
1573                return;
1574        }
1575
1576        if (adap->monitor_all_cnt &&
1577            call_op(adap, adap_monitor_all_enable, true)) {
1578                if (adap->needs_hpd || list_empty(&adap->devnode.fhs))
1579                        WARN_ON(adap->ops->adap_enable(adap, false));
1580                mutex_unlock(&adap->devnode.lock);
1581                return;
1582        }
1583        mutex_unlock(&adap->devnode.lock);
1584
1585        adap->phys_addr = phys_addr;
1586        cec_post_state_event(adap);
1587        if (adap->log_addrs.num_log_addrs)
1588                cec_claim_log_addrs(adap, block);
1589}
1590
1591void cec_s_phys_addr(struct cec_adapter *adap, u16 phys_addr, bool block)
1592{
1593        if (IS_ERR_OR_NULL(adap))
1594                return;
1595
1596        mutex_lock(&adap->lock);
1597        __cec_s_phys_addr(adap, phys_addr, block);
1598        mutex_unlock(&adap->lock);
1599}
1600EXPORT_SYMBOL_GPL(cec_s_phys_addr);
1601
1602void cec_s_phys_addr_from_edid(struct cec_adapter *adap,
1603                               const struct edid *edid)
1604{
1605        u16 pa = CEC_PHYS_ADDR_INVALID;
1606
1607        if (edid && edid->extensions)
1608                pa = cec_get_edid_phys_addr((const u8 *)edid,
1609                                EDID_LENGTH * (edid->extensions + 1), NULL);
1610        cec_s_phys_addr(adap, pa, false);
1611}
1612EXPORT_SYMBOL_GPL(cec_s_phys_addr_from_edid);
1613
1614void cec_s_conn_info(struct cec_adapter *adap,
1615                     const struct cec_connector_info *conn_info)
1616{
1617        if (!(adap->capabilities & CEC_CAP_CONNECTOR_INFO))
1618                return;
1619
1620        mutex_lock(&adap->lock);
1621        if (conn_info)
1622                adap->conn_info = *conn_info;
1623        else
1624                memset(&adap->conn_info, 0, sizeof(adap->conn_info));
1625        cec_post_state_event(adap);
1626        mutex_unlock(&adap->lock);
1627}
1628EXPORT_SYMBOL_GPL(cec_s_conn_info);
1629
1630/*
1631 * Called from either the ioctl or a driver to set the logical addresses.
1632 *
1633 * This function is called with adap->lock held.
1634 */
1635int __cec_s_log_addrs(struct cec_adapter *adap,
1636                      struct cec_log_addrs *log_addrs, bool block)
1637{
1638        u16 type_mask = 0;
1639        int i;
1640
1641        if (adap->devnode.unregistered)
1642                return -ENODEV;
1643
1644        if (!log_addrs || log_addrs->num_log_addrs == 0) {
1645                cec_adap_unconfigure(adap);
1646                adap->log_addrs.num_log_addrs = 0;
1647                for (i = 0; i < CEC_MAX_LOG_ADDRS; i++)
1648                        adap->log_addrs.log_addr[i] = CEC_LOG_ADDR_INVALID;
1649                adap->log_addrs.osd_name[0] = '\0';
1650                adap->log_addrs.vendor_id = CEC_VENDOR_ID_NONE;
1651                adap->log_addrs.cec_version = CEC_OP_CEC_VERSION_2_0;
1652                return 0;
1653        }
1654
1655        if (log_addrs->flags & CEC_LOG_ADDRS_FL_CDC_ONLY) {
1656                /*
1657                 * Sanitize log_addrs fields if a CDC-Only device is
1658                 * requested.
1659                 */
1660                log_addrs->num_log_addrs = 1;
1661                log_addrs->osd_name[0] = '\0';
1662                log_addrs->vendor_id = CEC_VENDOR_ID_NONE;
1663                log_addrs->log_addr_type[0] = CEC_LOG_ADDR_TYPE_UNREGISTERED;
1664                /*
1665                 * This is just an internal convention since a CDC-Only device
1666                 * doesn't have to be a switch. But switches already use
1667                 * unregistered, so it makes some kind of sense to pick this
1668                 * as the primary device. Since a CDC-Only device never sends
1669                 * any 'normal' CEC messages this primary device type is never
1670                 * sent over the CEC bus.
1671                 */
1672                log_addrs->primary_device_type[0] = CEC_OP_PRIM_DEVTYPE_SWITCH;
1673                log_addrs->all_device_types[0] = 0;
1674                log_addrs->features[0][0] = 0;
1675                log_addrs->features[0][1] = 0;
1676        }
1677
1678        /* Ensure the osd name is 0-terminated */
1679        log_addrs->osd_name[sizeof(log_addrs->osd_name) - 1] = '\0';
1680
1681        /* Sanity checks */
1682        if (log_addrs->num_log_addrs > adap->available_log_addrs) {
1683                dprintk(1, "num_log_addrs > %d\n", adap->available_log_addrs);
1684                return -EINVAL;
1685        }
1686
1687        /*
1688         * Vendor ID is a 24 bit number, so check if the value is
1689         * within the correct range.
1690         */
1691        if (log_addrs->vendor_id != CEC_VENDOR_ID_NONE &&
1692            (log_addrs->vendor_id & 0xff000000) != 0) {
1693                dprintk(1, "invalid vendor ID\n");
1694                return -EINVAL;
1695        }
1696
1697        if (log_addrs->cec_version != CEC_OP_CEC_VERSION_1_4 &&
1698            log_addrs->cec_version != CEC_OP_CEC_VERSION_2_0) {
1699                dprintk(1, "invalid CEC version\n");
1700                return -EINVAL;
1701        }
1702
1703        if (log_addrs->num_log_addrs > 1)
1704                for (i = 0; i < log_addrs->num_log_addrs; i++)
1705                        if (log_addrs->log_addr_type[i] ==
1706                                        CEC_LOG_ADDR_TYPE_UNREGISTERED) {
1707                                dprintk(1, "num_log_addrs > 1 can't be combined with unregistered LA\n");
1708                                return -EINVAL;
1709                        }
1710
1711        for (i = 0; i < log_addrs->num_log_addrs; i++) {
1712                const u8 feature_sz = ARRAY_SIZE(log_addrs->features[0]);
1713                u8 *features = log_addrs->features[i];
1714                bool op_is_dev_features = false;
1715                unsigned j;
1716
1717                log_addrs->log_addr[i] = CEC_LOG_ADDR_INVALID;
1718                if (type_mask & (1 << log_addrs->log_addr_type[i])) {
1719                        dprintk(1, "duplicate logical address type\n");
1720                        return -EINVAL;
1721                }
1722                type_mask |= 1 << log_addrs->log_addr_type[i];
1723                if ((type_mask & (1 << CEC_LOG_ADDR_TYPE_RECORD)) &&
1724                    (type_mask & (1 << CEC_LOG_ADDR_TYPE_PLAYBACK))) {
1725                        /* Record already contains the playback functionality */
1726                        dprintk(1, "invalid record + playback combination\n");
1727                        return -EINVAL;
1728                }
1729                if (log_addrs->primary_device_type[i] >
1730                                        CEC_OP_PRIM_DEVTYPE_PROCESSOR) {
1731                        dprintk(1, "unknown primary device type\n");
1732                        return -EINVAL;
1733                }
1734                if (log_addrs->primary_device_type[i] == 2) {
1735                        dprintk(1, "invalid primary device type\n");
1736                        return -EINVAL;
1737                }
1738                if (log_addrs->log_addr_type[i] > CEC_LOG_ADDR_TYPE_UNREGISTERED) {
1739                        dprintk(1, "unknown logical address type\n");
1740                        return -EINVAL;
1741                }
1742                for (j = 0; j < feature_sz; j++) {
1743                        if ((features[j] & 0x80) == 0) {
1744                                if (op_is_dev_features)
1745                                        break;
1746                                op_is_dev_features = true;
1747                        }
1748                }
1749                if (!op_is_dev_features || j == feature_sz) {
1750                        dprintk(1, "malformed features\n");
1751                        return -EINVAL;
1752                }
1753                /* Zero unused part of the feature array */
1754                memset(features + j + 1, 0, feature_sz - j - 1);
1755        }
1756
1757        if (log_addrs->cec_version >= CEC_OP_CEC_VERSION_2_0) {
1758                if (log_addrs->num_log_addrs > 2) {
1759                        dprintk(1, "CEC 2.0 allows no more than 2 logical addresses\n");
1760                        return -EINVAL;
1761                }
1762                if (log_addrs->num_log_addrs == 2) {
1763                        if (!(type_mask & ((1 << CEC_LOG_ADDR_TYPE_AUDIOSYSTEM) |
1764                                           (1 << CEC_LOG_ADDR_TYPE_TV)))) {
1765                                dprintk(1, "two LAs is only allowed for audiosystem and TV\n");
1766                                return -EINVAL;
1767                        }
1768                        if (!(type_mask & ((1 << CEC_LOG_ADDR_TYPE_PLAYBACK) |
1769                                           (1 << CEC_LOG_ADDR_TYPE_RECORD)))) {
1770                                dprintk(1, "an audiosystem/TV can only be combined with record or playback\n");
1771                                return -EINVAL;
1772                        }
1773                }
1774        }
1775
1776        /* Zero unused LAs */
1777        for (i = log_addrs->num_log_addrs; i < CEC_MAX_LOG_ADDRS; i++) {
1778                log_addrs->primary_device_type[i] = 0;
1779                log_addrs->log_addr_type[i] = 0;
1780                log_addrs->all_device_types[i] = 0;
1781                memset(log_addrs->features[i], 0,
1782                       sizeof(log_addrs->features[i]));
1783        }
1784
1785        log_addrs->log_addr_mask = adap->log_addrs.log_addr_mask;
1786        adap->log_addrs = *log_addrs;
1787        if (adap->phys_addr != CEC_PHYS_ADDR_INVALID)
1788                cec_claim_log_addrs(adap, block);
1789        return 0;
1790}
1791
1792int cec_s_log_addrs(struct cec_adapter *adap,
1793                    struct cec_log_addrs *log_addrs, bool block)
1794{
1795        int err;
1796
1797        mutex_lock(&adap->lock);
1798        err = __cec_s_log_addrs(adap, log_addrs, block);
1799        mutex_unlock(&adap->lock);
1800        return err;
1801}
1802EXPORT_SYMBOL_GPL(cec_s_log_addrs);
1803
1804/* High-level core CEC message handling */
1805
1806/* Fill in the Report Features message */
1807static void cec_fill_msg_report_features(struct cec_adapter *adap,
1808                                         struct cec_msg *msg,
1809                                         unsigned int la_idx)
1810{
1811        const struct cec_log_addrs *las = &adap->log_addrs;
1812        const u8 *features = las->features[la_idx];
1813        bool op_is_dev_features = false;
1814        unsigned int idx;
1815
1816        /* Report Features */
1817        msg->msg[0] = (las->log_addr[la_idx] << 4) | 0x0f;
1818        msg->len = 4;
1819        msg->msg[1] = CEC_MSG_REPORT_FEATURES;
1820        msg->msg[2] = adap->log_addrs.cec_version;
1821        msg->msg[3] = las->all_device_types[la_idx];
1822
1823        /* Write RC Profiles first, then Device Features */
1824        for (idx = 0; idx < ARRAY_SIZE(las->features[0]); idx++) {
1825                msg->msg[msg->len++] = features[idx];
1826                if ((features[idx] & CEC_OP_FEAT_EXT) == 0) {
1827                        if (op_is_dev_features)
1828                                break;
1829                        op_is_dev_features = true;
1830                }
1831        }
1832}
1833
1834/* Transmit the Feature Abort message */
1835static int cec_feature_abort_reason(struct cec_adapter *adap,
1836                                    struct cec_msg *msg, u8 reason)
1837{
1838        struct cec_msg tx_msg = { };
1839
1840        /*
1841         * Don't reply with CEC_MSG_FEATURE_ABORT to a CEC_MSG_FEATURE_ABORT
1842         * message!
1843         */
1844        if (msg->msg[1] == CEC_MSG_FEATURE_ABORT)
1845                return 0;
1846        /* Don't Feature Abort messages from 'Unregistered' */
1847        if (cec_msg_initiator(msg) == CEC_LOG_ADDR_UNREGISTERED)
1848                return 0;
1849        cec_msg_set_reply_to(&tx_msg, msg);
1850        cec_msg_feature_abort(&tx_msg, msg->msg[1], reason);
1851        return cec_transmit_msg(adap, &tx_msg, false);
1852}
1853
1854static int cec_feature_abort(struct cec_adapter *adap, struct cec_msg *msg)
1855{
1856        return cec_feature_abort_reason(adap, msg,
1857                                        CEC_OP_ABORT_UNRECOGNIZED_OP);
1858}
1859
1860static int cec_feature_refused(struct cec_adapter *adap, struct cec_msg *msg)
1861{
1862        return cec_feature_abort_reason(adap, msg,
1863                                        CEC_OP_ABORT_REFUSED);
1864}
1865
1866/*
1867 * Called when a CEC message is received. This function will do any
1868 * necessary core processing. The is_reply bool is true if this message
1869 * is a reply to an earlier transmit.
1870 *
1871 * The message is either a broadcast message or a valid directed message.
1872 */
1873static int cec_receive_notify(struct cec_adapter *adap, struct cec_msg *msg,
1874                              bool is_reply)
1875{
1876        bool is_broadcast = cec_msg_is_broadcast(msg);
1877        u8 dest_laddr = cec_msg_destination(msg);
1878        u8 init_laddr = cec_msg_initiator(msg);
1879        u8 devtype = cec_log_addr2dev(adap, dest_laddr);
1880        int la_idx = cec_log_addr2idx(adap, dest_laddr);
1881        bool from_unregistered = init_laddr == 0xf;
1882        struct cec_msg tx_cec_msg = { };
1883
1884        dprintk(2, "%s: %*ph\n", __func__, msg->len, msg->msg);
1885
1886        /* If this is a CDC-Only device, then ignore any non-CDC messages */
1887        if (cec_is_cdc_only(&adap->log_addrs) &&
1888            msg->msg[1] != CEC_MSG_CDC_MESSAGE)
1889                return 0;
1890
1891        if (adap->ops->received) {
1892                /* Allow drivers to process the message first */
1893                if (adap->ops->received(adap, msg) != -ENOMSG)
1894                        return 0;
1895        }
1896
1897        /*
1898         * REPORT_PHYSICAL_ADDR, CEC_MSG_USER_CONTROL_PRESSED and
1899         * CEC_MSG_USER_CONTROL_RELEASED messages always have to be
1900         * handled by the CEC core, even if the passthrough mode is on.
1901         * The others are just ignored if passthrough mode is on.
1902         */
1903        switch (msg->msg[1]) {
1904        case CEC_MSG_GET_CEC_VERSION:
1905        case CEC_MSG_ABORT:
1906        case CEC_MSG_GIVE_DEVICE_POWER_STATUS:
1907        case CEC_MSG_GIVE_OSD_NAME:
1908                /*
1909                 * These messages reply with a directed message, so ignore if
1910                 * the initiator is Unregistered.
1911                 */
1912                if (!adap->passthrough && from_unregistered)
1913                        return 0;
1914                /* Fall through */
1915        case CEC_MSG_GIVE_DEVICE_VENDOR_ID:
1916        case CEC_MSG_GIVE_FEATURES:
1917        case CEC_MSG_GIVE_PHYSICAL_ADDR:
1918                /*
1919                 * Skip processing these messages if the passthrough mode
1920                 * is on.
1921                 */
1922                if (adap->passthrough)
1923                        goto skip_processing;
1924                /* Ignore if addressing is wrong */
1925                if (is_broadcast)
1926                        return 0;
1927                break;
1928
1929        case CEC_MSG_USER_CONTROL_PRESSED:
1930        case CEC_MSG_USER_CONTROL_RELEASED:
1931                /* Wrong addressing mode: don't process */
1932                if (is_broadcast || from_unregistered)
1933                        goto skip_processing;
1934                break;
1935
1936        case CEC_MSG_REPORT_PHYSICAL_ADDR:
1937                /*
1938                 * This message is always processed, regardless of the
1939                 * passthrough setting.
1940                 *
1941                 * Exception: don't process if wrong addressing mode.
1942                 */
1943                if (!is_broadcast)
1944                        goto skip_processing;
1945                break;
1946
1947        default:
1948                break;
1949        }
1950
1951        cec_msg_set_reply_to(&tx_cec_msg, msg);
1952
1953        switch (msg->msg[1]) {
1954        /* The following messages are processed but still passed through */
1955        case CEC_MSG_REPORT_PHYSICAL_ADDR: {
1956                u16 pa = (msg->msg[2] << 8) | msg->msg[3];
1957
1958                if (!from_unregistered)
1959                        adap->phys_addrs[init_laddr] = pa;
1960                dprintk(1, "reported physical address %x.%x.%x.%x for logical address %d\n",
1961                        cec_phys_addr_exp(pa), init_laddr);
1962                break;
1963        }
1964
1965        case CEC_MSG_USER_CONTROL_PRESSED:
1966                if (!(adap->capabilities & CEC_CAP_RC) ||
1967                    !(adap->log_addrs.flags & CEC_LOG_ADDRS_FL_ALLOW_RC_PASSTHRU))
1968                        break;
1969
1970#ifdef CONFIG_MEDIA_CEC_RC
1971                switch (msg->msg[2]) {
1972                /*
1973                 * Play function, this message can have variable length
1974                 * depending on the specific play function that is used.
1975                 */
1976                case 0x60:
1977                        if (msg->len == 2)
1978                                rc_keydown(adap->rc, RC_PROTO_CEC,
1979                                           msg->msg[2], 0);
1980                        else
1981                                rc_keydown(adap->rc, RC_PROTO_CEC,
1982                                           msg->msg[2] << 8 | msg->msg[3], 0);
1983                        break;
1984                /*
1985                 * Other function messages that are not handled.
1986                 * Currently the RC framework does not allow to supply an
1987                 * additional parameter to a keypress. These "keys" contain
1988                 * other information such as channel number, an input number
1989                 * etc.
1990                 * For the time being these messages are not processed by the
1991                 * framework and are simply forwarded to the user space.
1992                 */
1993                case 0x56: case 0x57:
1994                case 0x67: case 0x68: case 0x69: case 0x6a:
1995                        break;
1996                default:
1997                        rc_keydown(adap->rc, RC_PROTO_CEC, msg->msg[2], 0);
1998                        break;
1999                }
2000#endif
2001                break;
2002
2003        case CEC_MSG_USER_CONTROL_RELEASED:
2004                if (!(adap->capabilities & CEC_CAP_RC) ||
2005                    !(adap->log_addrs.flags & CEC_LOG_ADDRS_FL_ALLOW_RC_PASSTHRU))
2006                        break;
2007#ifdef CONFIG_MEDIA_CEC_RC
2008                rc_keyup(adap->rc);
2009#endif
2010                break;
2011
2012        /*
2013         * The remaining messages are only processed if the passthrough mode
2014         * is off.
2015         */
2016        case CEC_MSG_GET_CEC_VERSION:
2017                cec_msg_cec_version(&tx_cec_msg, adap->log_addrs.cec_version);
2018                return cec_transmit_msg(adap, &tx_cec_msg, false);
2019
2020        case CEC_MSG_GIVE_PHYSICAL_ADDR:
2021                /* Do nothing for CEC switches using addr 15 */
2022                if (devtype == CEC_OP_PRIM_DEVTYPE_SWITCH && dest_laddr == 15)
2023                        return 0;
2024                cec_msg_report_physical_addr(&tx_cec_msg, adap->phys_addr, devtype);
2025                return cec_transmit_msg(adap, &tx_cec_msg, false);
2026
2027        case CEC_MSG_GIVE_DEVICE_VENDOR_ID:
2028                if (adap->log_addrs.vendor_id == CEC_VENDOR_ID_NONE)
2029                        return cec_feature_abort(adap, msg);
2030                cec_msg_device_vendor_id(&tx_cec_msg, adap->log_addrs.vendor_id);
2031                return cec_transmit_msg(adap, &tx_cec_msg, false);
2032
2033        case CEC_MSG_ABORT:
2034                /* Do nothing for CEC switches */
2035                if (devtype == CEC_OP_PRIM_DEVTYPE_SWITCH)
2036                        return 0;
2037                return cec_feature_refused(adap, msg);
2038
2039        case CEC_MSG_GIVE_OSD_NAME: {
2040                if (adap->log_addrs.osd_name[0] == 0)
2041                        return cec_feature_abort(adap, msg);
2042                cec_msg_set_osd_name(&tx_cec_msg, adap->log_addrs.osd_name);
2043                return cec_transmit_msg(adap, &tx_cec_msg, false);
2044        }
2045
2046        case CEC_MSG_GIVE_FEATURES:
2047                if (adap->log_addrs.cec_version < CEC_OP_CEC_VERSION_2_0)
2048                        return cec_feature_abort(adap, msg);
2049                cec_fill_msg_report_features(adap, &tx_cec_msg, la_idx);
2050                return cec_transmit_msg(adap, &tx_cec_msg, false);
2051
2052        default:
2053                /*
2054                 * Unprocessed messages are aborted if userspace isn't doing
2055                 * any processing either.
2056                 */
2057                if (!is_broadcast && !is_reply && !adap->follower_cnt &&
2058                    !adap->cec_follower && msg->msg[1] != CEC_MSG_FEATURE_ABORT)
2059                        return cec_feature_abort(adap, msg);
2060                break;
2061        }
2062
2063skip_processing:
2064        /* If this was a reply, then we're done, unless otherwise specified */
2065        if (is_reply && !(msg->flags & CEC_MSG_FL_REPLY_TO_FOLLOWERS))
2066                return 0;
2067
2068        /*
2069         * Send to the exclusive follower if there is one, otherwise send
2070         * to all followers.
2071         */
2072        if (adap->cec_follower)
2073                cec_queue_msg_fh(adap->cec_follower, msg);
2074        else
2075                cec_queue_msg_followers(adap, msg);
2076        return 0;
2077}
2078
2079/*
2080 * Helper functions to keep track of the 'monitor all' use count.
2081 *
2082 * These functions are called with adap->lock held.
2083 */
2084int cec_monitor_all_cnt_inc(struct cec_adapter *adap)
2085{
2086        int ret = 0;
2087
2088        if (adap->monitor_all_cnt == 0)
2089                ret = call_op(adap, adap_monitor_all_enable, 1);
2090        if (ret == 0)
2091                adap->monitor_all_cnt++;
2092        return ret;
2093}
2094
2095void cec_monitor_all_cnt_dec(struct cec_adapter *adap)
2096{
2097        adap->monitor_all_cnt--;
2098        if (adap->monitor_all_cnt == 0)
2099                WARN_ON(call_op(adap, adap_monitor_all_enable, 0));
2100}
2101
2102/*
2103 * Helper functions to keep track of the 'monitor pin' use count.
2104 *
2105 * These functions are called with adap->lock held.
2106 */
2107int cec_monitor_pin_cnt_inc(struct cec_adapter *adap)
2108{
2109        int ret = 0;
2110
2111        if (adap->monitor_pin_cnt == 0)
2112                ret = call_op(adap, adap_monitor_pin_enable, 1);
2113        if (ret == 0)
2114                adap->monitor_pin_cnt++;
2115        return ret;
2116}
2117
2118void cec_monitor_pin_cnt_dec(struct cec_adapter *adap)
2119{
2120        adap->monitor_pin_cnt--;
2121        if (adap->monitor_pin_cnt == 0)
2122                WARN_ON(call_op(adap, adap_monitor_pin_enable, 0));
2123}
2124
2125#ifdef CONFIG_DEBUG_FS
2126/*
2127 * Log the current state of the CEC adapter.
2128 * Very useful for debugging.
2129 */
2130int cec_adap_status(struct seq_file *file, void *priv)
2131{
2132        struct cec_adapter *adap = dev_get_drvdata(file->private);
2133        struct cec_data *data;
2134
2135        mutex_lock(&adap->lock);
2136        seq_printf(file, "configured: %d\n", adap->is_configured);
2137        seq_printf(file, "configuring: %d\n", adap->is_configuring);
2138        seq_printf(file, "phys_addr: %x.%x.%x.%x\n",
2139                   cec_phys_addr_exp(adap->phys_addr));
2140        seq_printf(file, "number of LAs: %d\n", adap->log_addrs.num_log_addrs);
2141        seq_printf(file, "LA mask: 0x%04x\n", adap->log_addrs.log_addr_mask);
2142        if (adap->cec_follower)
2143                seq_printf(file, "has CEC follower%s\n",
2144                           adap->passthrough ? " (in passthrough mode)" : "");
2145        if (adap->cec_initiator)
2146                seq_puts(file, "has CEC initiator\n");
2147        if (adap->monitor_all_cnt)
2148                seq_printf(file, "file handles in Monitor All mode: %u\n",
2149                           adap->monitor_all_cnt);
2150        if (adap->tx_timeouts) {
2151                seq_printf(file, "transmit timeouts: %u\n",
2152                           adap->tx_timeouts);
2153                adap->tx_timeouts = 0;
2154        }
2155        data = adap->transmitting;
2156        if (data)
2157                seq_printf(file, "transmitting message: %*ph (reply: %02x, timeout: %ums)\n",
2158                           data->msg.len, data->msg.msg, data->msg.reply,
2159                           data->msg.timeout);
2160        seq_printf(file, "pending transmits: %u\n", adap->transmit_queue_sz);
2161        list_for_each_entry(data, &adap->transmit_queue, list) {
2162                seq_printf(file, "queued tx message: %*ph (reply: %02x, timeout: %ums)\n",
2163                           data->msg.len, data->msg.msg, data->msg.reply,
2164                           data->msg.timeout);
2165        }
2166        list_for_each_entry(data, &adap->wait_queue, list) {
2167                seq_printf(file, "message waiting for reply: %*ph (reply: %02x, timeout: %ums)\n",
2168                           data->msg.len, data->msg.msg, data->msg.reply,
2169                           data->msg.timeout);
2170        }
2171
2172        call_void_op(adap, adap_status, file);
2173        mutex_unlock(&adap->lock);
2174        return 0;
2175}
2176#endif
2177