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