Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-only
0002 /*
0003  * cec-adap.c - HDMI Consumer Electronics Control framework - CEC adapter
0004  *
0005  * Copyright 2016 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
0006  */
0007 
0008 #include <linux/errno.h>
0009 #include <linux/init.h>
0010 #include <linux/module.h>
0011 #include <linux/kernel.h>
0012 #include <linux/kmod.h>
0013 #include <linux/ktime.h>
0014 #include <linux/slab.h>
0015 #include <linux/mm.h>
0016 #include <linux/string.h>
0017 #include <linux/types.h>
0018 
0019 #include <drm/drm_connector.h>
0020 #include <drm/drm_device.h>
0021 #include <drm/drm_edid.h>
0022 #include <drm/drm_file.h>
0023 
0024 #include "cec-priv.h"
0025 
0026 static void cec_fill_msg_report_features(struct cec_adapter *adap,
0027                      struct cec_msg *msg,
0028                      unsigned int la_idx);
0029 
0030 static int cec_log_addr2idx(const struct cec_adapter *adap, u8 log_addr)
0031 {
0032     int i;
0033 
0034     for (i = 0; i < adap->log_addrs.num_log_addrs; i++)
0035         if (adap->log_addrs.log_addr[i] == log_addr)
0036             return i;
0037     return -1;
0038 }
0039 
0040 static unsigned int cec_log_addr2dev(const struct cec_adapter *adap, u8 log_addr)
0041 {
0042     int i = cec_log_addr2idx(adap, log_addr);
0043 
0044     return adap->log_addrs.primary_device_type[i < 0 ? 0 : i];
0045 }
0046 
0047 u16 cec_get_edid_phys_addr(const u8 *edid, unsigned int size,
0048                unsigned int *offset)
0049 {
0050     unsigned int loc = cec_get_edid_spa_location(edid, size);
0051 
0052     if (offset)
0053         *offset = loc;
0054     if (loc == 0)
0055         return CEC_PHYS_ADDR_INVALID;
0056     return (edid[loc] << 8) | edid[loc + 1];
0057 }
0058 EXPORT_SYMBOL_GPL(cec_get_edid_phys_addr);
0059 
0060 void cec_fill_conn_info_from_drm(struct cec_connector_info *conn_info,
0061                  const struct drm_connector *connector)
0062 {
0063     memset(conn_info, 0, sizeof(*conn_info));
0064     conn_info->type = CEC_CONNECTOR_TYPE_DRM;
0065     conn_info->drm.card_no = connector->dev->primary->index;
0066     conn_info->drm.connector_id = connector->base.id;
0067 }
0068 EXPORT_SYMBOL_GPL(cec_fill_conn_info_from_drm);
0069 
0070 /*
0071  * Queue a new event for this filehandle. If ts == 0, then set it
0072  * to the current time.
0073  *
0074  * We keep a queue of at most max_event events where max_event differs
0075  * per event. If the queue becomes full, then drop the oldest event and
0076  * keep track of how many events we've dropped.
0077  */
0078 void cec_queue_event_fh(struct cec_fh *fh,
0079             const struct cec_event *new_ev, u64 ts)
0080 {
0081     static const u16 max_events[CEC_NUM_EVENTS] = {
0082         1, 1, 800, 800, 8, 8, 8, 8
0083     };
0084     struct cec_event_entry *entry;
0085     unsigned int ev_idx = new_ev->event - 1;
0086 
0087     if (WARN_ON(ev_idx >= ARRAY_SIZE(fh->events)))
0088         return;
0089 
0090     if (ts == 0)
0091         ts = ktime_get_ns();
0092 
0093     mutex_lock(&fh->lock);
0094     if (ev_idx < CEC_NUM_CORE_EVENTS)
0095         entry = &fh->core_events[ev_idx];
0096     else
0097         entry = kmalloc(sizeof(*entry), GFP_KERNEL);
0098     if (entry) {
0099         if (new_ev->event == CEC_EVENT_LOST_MSGS &&
0100             fh->queued_events[ev_idx]) {
0101             entry->ev.lost_msgs.lost_msgs +=
0102                 new_ev->lost_msgs.lost_msgs;
0103             goto unlock;
0104         }
0105         entry->ev = *new_ev;
0106         entry->ev.ts = ts;
0107 
0108         if (fh->queued_events[ev_idx] < max_events[ev_idx]) {
0109             /* Add new msg at the end of the queue */
0110             list_add_tail(&entry->list, &fh->events[ev_idx]);
0111             fh->queued_events[ev_idx]++;
0112             fh->total_queued_events++;
0113             goto unlock;
0114         }
0115 
0116         if (ev_idx >= CEC_NUM_CORE_EVENTS) {
0117             list_add_tail(&entry->list, &fh->events[ev_idx]);
0118             /* drop the oldest event */
0119             entry = list_first_entry(&fh->events[ev_idx],
0120                          struct cec_event_entry, list);
0121             list_del(&entry->list);
0122             kfree(entry);
0123         }
0124     }
0125     /* Mark that events were lost */
0126     entry = list_first_entry_or_null(&fh->events[ev_idx],
0127                      struct cec_event_entry, list);
0128     if (entry)
0129         entry->ev.flags |= CEC_EVENT_FL_DROPPED_EVENTS;
0130 
0131 unlock:
0132     mutex_unlock(&fh->lock);
0133     wake_up_interruptible(&fh->wait);
0134 }
0135 
0136 /* Queue a new event for all open filehandles. */
0137 static void cec_queue_event(struct cec_adapter *adap,
0138                 const struct cec_event *ev)
0139 {
0140     u64 ts = ktime_get_ns();
0141     struct cec_fh *fh;
0142 
0143     mutex_lock(&adap->devnode.lock_fhs);
0144     list_for_each_entry(fh, &adap->devnode.fhs, list)
0145         cec_queue_event_fh(fh, ev, ts);
0146     mutex_unlock(&adap->devnode.lock_fhs);
0147 }
0148 
0149 /* Notify userspace that the CEC pin changed state at the given time. */
0150 void cec_queue_pin_cec_event(struct cec_adapter *adap, bool is_high,
0151                  bool dropped_events, ktime_t ts)
0152 {
0153     struct cec_event ev = {
0154         .event = is_high ? CEC_EVENT_PIN_CEC_HIGH :
0155                    CEC_EVENT_PIN_CEC_LOW,
0156         .flags = dropped_events ? CEC_EVENT_FL_DROPPED_EVENTS : 0,
0157     };
0158     struct cec_fh *fh;
0159 
0160     mutex_lock(&adap->devnode.lock_fhs);
0161     list_for_each_entry(fh, &adap->devnode.fhs, list) {
0162         if (fh->mode_follower == CEC_MODE_MONITOR_PIN)
0163             cec_queue_event_fh(fh, &ev, ktime_to_ns(ts));
0164     }
0165     mutex_unlock(&adap->devnode.lock_fhs);
0166 }
0167 EXPORT_SYMBOL_GPL(cec_queue_pin_cec_event);
0168 
0169 /* Notify userspace that the HPD pin changed state at the given time. */
0170 void cec_queue_pin_hpd_event(struct cec_adapter *adap, bool is_high, ktime_t ts)
0171 {
0172     struct cec_event ev = {
0173         .event = is_high ? CEC_EVENT_PIN_HPD_HIGH :
0174                    CEC_EVENT_PIN_HPD_LOW,
0175     };
0176     struct cec_fh *fh;
0177 
0178     mutex_lock(&adap->devnode.lock_fhs);
0179     list_for_each_entry(fh, &adap->devnode.fhs, list)
0180         cec_queue_event_fh(fh, &ev, ktime_to_ns(ts));
0181     mutex_unlock(&adap->devnode.lock_fhs);
0182 }
0183 EXPORT_SYMBOL_GPL(cec_queue_pin_hpd_event);
0184 
0185 /* Notify userspace that the 5V pin changed state at the given time. */
0186 void cec_queue_pin_5v_event(struct cec_adapter *adap, bool is_high, ktime_t ts)
0187 {
0188     struct cec_event ev = {
0189         .event = is_high ? CEC_EVENT_PIN_5V_HIGH :
0190                    CEC_EVENT_PIN_5V_LOW,
0191     };
0192     struct cec_fh *fh;
0193 
0194     mutex_lock(&adap->devnode.lock_fhs);
0195     list_for_each_entry(fh, &adap->devnode.fhs, list)
0196         cec_queue_event_fh(fh, &ev, ktime_to_ns(ts));
0197     mutex_unlock(&adap->devnode.lock_fhs);
0198 }
0199 EXPORT_SYMBOL_GPL(cec_queue_pin_5v_event);
0200 
0201 /*
0202  * Queue a new message for this filehandle.
0203  *
0204  * We keep a queue of at most CEC_MAX_MSG_RX_QUEUE_SZ messages. If the
0205  * queue becomes full, then drop the oldest message and keep track
0206  * of how many messages we've dropped.
0207  */
0208 static void cec_queue_msg_fh(struct cec_fh *fh, const struct cec_msg *msg)
0209 {
0210     static const struct cec_event ev_lost_msgs = {
0211         .event = CEC_EVENT_LOST_MSGS,
0212         .flags = 0,
0213         {
0214             .lost_msgs = { 1 },
0215         },
0216     };
0217     struct cec_msg_entry *entry;
0218 
0219     mutex_lock(&fh->lock);
0220     entry = kmalloc(sizeof(*entry), GFP_KERNEL);
0221     if (entry) {
0222         entry->msg = *msg;
0223         /* Add new msg at the end of the queue */
0224         list_add_tail(&entry->list, &fh->msgs);
0225 
0226         if (fh->queued_msgs < CEC_MAX_MSG_RX_QUEUE_SZ) {
0227             /* All is fine if there is enough room */
0228             fh->queued_msgs++;
0229             mutex_unlock(&fh->lock);
0230             wake_up_interruptible(&fh->wait);
0231             return;
0232         }
0233 
0234         /*
0235          * if the message queue is full, then drop the oldest one and
0236          * send a lost message event.
0237          */
0238         entry = list_first_entry(&fh->msgs, struct cec_msg_entry, list);
0239         list_del(&entry->list);
0240         kfree(entry);
0241     }
0242     mutex_unlock(&fh->lock);
0243 
0244     /*
0245      * We lost a message, either because kmalloc failed or the queue
0246      * was full.
0247      */
0248     cec_queue_event_fh(fh, &ev_lost_msgs, ktime_get_ns());
0249 }
0250 
0251 /*
0252  * Queue the message for those filehandles that are in monitor mode.
0253  * If valid_la is true (this message is for us or was sent by us),
0254  * then pass it on to any monitoring filehandle. If this message
0255  * isn't for us or from us, then only give it to filehandles that
0256  * are in MONITOR_ALL mode.
0257  *
0258  * This can only happen if the CEC_CAP_MONITOR_ALL capability is
0259  * set and the CEC adapter was placed in 'monitor all' mode.
0260  */
0261 static void cec_queue_msg_monitor(struct cec_adapter *adap,
0262                   const struct cec_msg *msg,
0263                   bool valid_la)
0264 {
0265     struct cec_fh *fh;
0266     u32 monitor_mode = valid_la ? CEC_MODE_MONITOR :
0267                       CEC_MODE_MONITOR_ALL;
0268 
0269     mutex_lock(&adap->devnode.lock_fhs);
0270     list_for_each_entry(fh, &adap->devnode.fhs, list) {
0271         if (fh->mode_follower >= monitor_mode)
0272             cec_queue_msg_fh(fh, msg);
0273     }
0274     mutex_unlock(&adap->devnode.lock_fhs);
0275 }
0276 
0277 /*
0278  * Queue the message for follower filehandles.
0279  */
0280 static void cec_queue_msg_followers(struct cec_adapter *adap,
0281                     const struct cec_msg *msg)
0282 {
0283     struct cec_fh *fh;
0284 
0285     mutex_lock(&adap->devnode.lock_fhs);
0286     list_for_each_entry(fh, &adap->devnode.fhs, list) {
0287         if (fh->mode_follower == CEC_MODE_FOLLOWER)
0288             cec_queue_msg_fh(fh, msg);
0289     }
0290     mutex_unlock(&adap->devnode.lock_fhs);
0291 }
0292 
0293 /* Notify userspace of an adapter state change. */
0294 static void cec_post_state_event(struct cec_adapter *adap)
0295 {
0296     struct cec_event ev = {
0297         .event = CEC_EVENT_STATE_CHANGE,
0298     };
0299 
0300     ev.state_change.phys_addr = adap->phys_addr;
0301     ev.state_change.log_addr_mask = adap->log_addrs.log_addr_mask;
0302     ev.state_change.have_conn_info =
0303         adap->conn_info.type != CEC_CONNECTOR_TYPE_NO_CONNECTOR;
0304     cec_queue_event(adap, &ev);
0305 }
0306 
0307 /*
0308  * A CEC transmit (and a possible wait for reply) completed.
0309  * If this was in blocking mode, then complete it, otherwise
0310  * queue the message for userspace to dequeue later.
0311  *
0312  * This function is called with adap->lock held.
0313  */
0314 static void cec_data_completed(struct cec_data *data)
0315 {
0316     /*
0317      * Delete this transmit from the filehandle's xfer_list since
0318      * we're done with it.
0319      *
0320      * Note that if the filehandle is closed before this transmit
0321      * finished, then the release() function will set data->fh to NULL.
0322      * Without that we would be referring to a closed filehandle.
0323      */
0324     if (data->fh)
0325         list_del_init(&data->xfer_list);
0326 
0327     if (data->blocking) {
0328         /*
0329          * Someone is blocking so mark the message as completed
0330          * and call complete.
0331          */
0332         data->completed = true;
0333         complete(&data->c);
0334     } else {
0335         /*
0336          * No blocking, so just queue the message if needed and
0337          * free the memory.
0338          */
0339         if (data->fh)
0340             cec_queue_msg_fh(data->fh, &data->msg);
0341         kfree(data);
0342     }
0343 }
0344 
0345 /*
0346  * A pending CEC transmit needs to be cancelled, either because the CEC
0347  * adapter is disabled or the transmit takes an impossibly long time to
0348  * finish, or the reply timed out.
0349  *
0350  * This function is called with adap->lock held.
0351  */
0352 static void cec_data_cancel(struct cec_data *data, u8 tx_status, u8 rx_status)
0353 {
0354     struct cec_adapter *adap = data->adap;
0355 
0356     /*
0357      * It's either the current transmit, or it is a pending
0358      * transmit. Take the appropriate action to clear it.
0359      */
0360     if (adap->transmitting == data) {
0361         adap->transmitting = NULL;
0362     } else {
0363         list_del_init(&data->list);
0364         if (!(data->msg.tx_status & CEC_TX_STATUS_OK))
0365             if (!WARN_ON(!adap->transmit_queue_sz))
0366                 adap->transmit_queue_sz--;
0367     }
0368 
0369     if (data->msg.tx_status & CEC_TX_STATUS_OK) {
0370         data->msg.rx_ts = ktime_get_ns();
0371         data->msg.rx_status = rx_status;
0372         if (!data->blocking)
0373             data->msg.tx_status = 0;
0374     } else {
0375         data->msg.tx_ts = ktime_get_ns();
0376         data->msg.tx_status |= tx_status |
0377                        CEC_TX_STATUS_MAX_RETRIES;
0378         data->msg.tx_error_cnt++;
0379         data->attempts = 0;
0380         if (!data->blocking)
0381             data->msg.rx_status = 0;
0382     }
0383 
0384     /* Queue transmitted message for monitoring purposes */
0385     cec_queue_msg_monitor(adap, &data->msg, 1);
0386 
0387     if (!data->blocking && data->msg.sequence)
0388         /* Allow drivers to process the message first */
0389         call_op(adap, received, &data->msg);
0390 
0391     cec_data_completed(data);
0392 }
0393 
0394 /*
0395  * Flush all pending transmits and cancel any pending timeout work.
0396  *
0397  * This function is called with adap->lock held.
0398  */
0399 static void cec_flush(struct cec_adapter *adap)
0400 {
0401     struct cec_data *data, *n;
0402 
0403     /*
0404      * If the adapter is disabled, or we're asked to stop,
0405      * then cancel any pending transmits.
0406      */
0407     while (!list_empty(&adap->transmit_queue)) {
0408         data = list_first_entry(&adap->transmit_queue,
0409                     struct cec_data, list);
0410         cec_data_cancel(data, CEC_TX_STATUS_ABORTED, 0);
0411     }
0412     if (adap->transmitting)
0413         adap->transmit_in_progress_aborted = true;
0414 
0415     /* Cancel the pending timeout work. */
0416     list_for_each_entry_safe(data, n, &adap->wait_queue, list) {
0417         if (cancel_delayed_work(&data->work))
0418             cec_data_cancel(data, CEC_TX_STATUS_OK, CEC_RX_STATUS_ABORTED);
0419         /*
0420          * If cancel_delayed_work returned false, then
0421          * the cec_wait_timeout function is running,
0422          * which will call cec_data_completed. So no
0423          * need to do anything special in that case.
0424          */
0425     }
0426     /*
0427      * If something went wrong and this counter isn't what it should
0428      * be, then this will reset it back to 0. Warn if it is not 0,
0429      * since it indicates a bug, either in this framework or in a
0430      * CEC driver.
0431      */
0432     if (WARN_ON(adap->transmit_queue_sz))
0433         adap->transmit_queue_sz = 0;
0434 }
0435 
0436 /*
0437  * Main CEC state machine
0438  *
0439  * Wait until the thread should be stopped, or we are not transmitting and
0440  * a new transmit message is queued up, in which case we start transmitting
0441  * that message. When the adapter finished transmitting the message it will
0442  * call cec_transmit_done().
0443  *
0444  * If the adapter is disabled, then remove all queued messages instead.
0445  *
0446  * If the current transmit times out, then cancel that transmit.
0447  */
0448 int cec_thread_func(void *_adap)
0449 {
0450     struct cec_adapter *adap = _adap;
0451 
0452     for (;;) {
0453         unsigned int signal_free_time;
0454         struct cec_data *data;
0455         bool timeout = false;
0456         u8 attempts;
0457 
0458         if (adap->transmit_in_progress) {
0459             int err;
0460 
0461             /*
0462              * We are transmitting a message, so add a timeout
0463              * to prevent the state machine to get stuck waiting
0464              * for this message to finalize and add a check to
0465              * see if the adapter is disabled in which case the
0466              * transmit should be canceled.
0467              */
0468             err = wait_event_interruptible_timeout(adap->kthread_waitq,
0469                 (adap->needs_hpd &&
0470                  (!adap->is_configured && !adap->is_configuring)) ||
0471                 kthread_should_stop() ||
0472                 (!adap->transmit_in_progress &&
0473                  !list_empty(&adap->transmit_queue)),
0474                 msecs_to_jiffies(adap->xfer_timeout_ms));
0475             timeout = err == 0;
0476         } else {
0477             /* Otherwise we just wait for something to happen. */
0478             wait_event_interruptible(adap->kthread_waitq,
0479                 kthread_should_stop() ||
0480                 (!adap->transmit_in_progress &&
0481                  !list_empty(&adap->transmit_queue)));
0482         }
0483 
0484         mutex_lock(&adap->lock);
0485 
0486         if ((adap->needs_hpd &&
0487              (!adap->is_configured && !adap->is_configuring)) ||
0488             kthread_should_stop()) {
0489             cec_flush(adap);
0490             goto unlock;
0491         }
0492 
0493         if (adap->transmit_in_progress && timeout) {
0494             /*
0495              * If we timeout, then log that. Normally this does
0496              * not happen and it is an indication of a faulty CEC
0497              * adapter driver, or the CEC bus is in some weird
0498              * state. On rare occasions it can happen if there is
0499              * so much traffic on the bus that the adapter was
0500              * unable to transmit for xfer_timeout_ms (2.1s by
0501              * default).
0502              */
0503             if (adap->transmitting) {
0504                 pr_warn("cec-%s: message %*ph timed out\n", adap->name,
0505                     adap->transmitting->msg.len,
0506                     adap->transmitting->msg.msg);
0507                 /* Just give up on this. */
0508                 cec_data_cancel(adap->transmitting,
0509                         CEC_TX_STATUS_TIMEOUT, 0);
0510             } else {
0511                 pr_warn("cec-%s: transmit timed out\n", adap->name);
0512             }
0513             adap->transmit_in_progress = false;
0514             adap->tx_timeouts++;
0515             goto unlock;
0516         }
0517 
0518         /*
0519          * If we are still transmitting, or there is nothing new to
0520          * transmit, then just continue waiting.
0521          */
0522         if (adap->transmit_in_progress || list_empty(&adap->transmit_queue))
0523             goto unlock;
0524 
0525         /* Get a new message to transmit */
0526         data = list_first_entry(&adap->transmit_queue,
0527                     struct cec_data, list);
0528         list_del_init(&data->list);
0529         if (!WARN_ON(!data->adap->transmit_queue_sz))
0530             adap->transmit_queue_sz--;
0531 
0532         /* Make this the current transmitting message */
0533         adap->transmitting = data;
0534 
0535         /*
0536          * Suggested number of attempts as per the CEC 2.0 spec:
0537          * 4 attempts is the default, except for 'secondary poll
0538          * messages', i.e. poll messages not sent during the adapter
0539          * configuration phase when it allocates logical addresses.
0540          */
0541         if (data->msg.len == 1 && adap->is_configured)
0542             attempts = 2;
0543         else
0544             attempts = 4;
0545 
0546         /* Set the suggested signal free time */
0547         if (data->attempts) {
0548             /* should be >= 3 data bit periods for a retry */
0549             signal_free_time = CEC_SIGNAL_FREE_TIME_RETRY;
0550         } else if (adap->last_initiator !=
0551                cec_msg_initiator(&data->msg)) {
0552             /* should be >= 5 data bit periods for new initiator */
0553             signal_free_time = CEC_SIGNAL_FREE_TIME_NEW_INITIATOR;
0554             adap->last_initiator = cec_msg_initiator(&data->msg);
0555         } else {
0556             /*
0557              * should be >= 7 data bit periods for sending another
0558              * frame immediately after another.
0559              */
0560             signal_free_time = CEC_SIGNAL_FREE_TIME_NEXT_XFER;
0561         }
0562         if (data->attempts == 0)
0563             data->attempts = attempts;
0564 
0565         adap->transmit_in_progress_aborted = false;
0566         /* Tell the adapter to transmit, cancel on error */
0567         if (call_op(adap, adap_transmit, data->attempts,
0568                 signal_free_time, &data->msg))
0569             cec_data_cancel(data, CEC_TX_STATUS_ABORTED, 0);
0570         else
0571             adap->transmit_in_progress = true;
0572 
0573 unlock:
0574         mutex_unlock(&adap->lock);
0575 
0576         if (kthread_should_stop())
0577             break;
0578     }
0579     return 0;
0580 }
0581 
0582 /*
0583  * Called by the CEC adapter if a transmit finished.
0584  */
0585 void cec_transmit_done_ts(struct cec_adapter *adap, u8 status,
0586               u8 arb_lost_cnt, u8 nack_cnt, u8 low_drive_cnt,
0587               u8 error_cnt, ktime_t ts)
0588 {
0589     struct cec_data *data;
0590     struct cec_msg *msg;
0591     unsigned int attempts_made = arb_lost_cnt + nack_cnt +
0592                      low_drive_cnt + error_cnt;
0593     bool done = status & (CEC_TX_STATUS_MAX_RETRIES | CEC_TX_STATUS_OK);
0594     bool aborted = adap->transmit_in_progress_aborted;
0595 
0596     dprintk(2, "%s: status 0x%02x\n", __func__, status);
0597     if (attempts_made < 1)
0598         attempts_made = 1;
0599 
0600     mutex_lock(&adap->lock);
0601     data = adap->transmitting;
0602     if (!data) {
0603         /*
0604          * This might happen if a transmit was issued and the cable is
0605          * unplugged while the transmit is ongoing. Ignore this
0606          * transmit in that case.
0607          */
0608         if (!adap->transmit_in_progress)
0609             dprintk(1, "%s was called without an ongoing transmit!\n",
0610                 __func__);
0611         adap->transmit_in_progress = false;
0612         goto wake_thread;
0613     }
0614     adap->transmit_in_progress = false;
0615     adap->transmit_in_progress_aborted = false;
0616 
0617     msg = &data->msg;
0618 
0619     /* Drivers must fill in the status! */
0620     WARN_ON(status == 0);
0621     msg->tx_ts = ktime_to_ns(ts);
0622     msg->tx_status |= status;
0623     msg->tx_arb_lost_cnt += arb_lost_cnt;
0624     msg->tx_nack_cnt += nack_cnt;
0625     msg->tx_low_drive_cnt += low_drive_cnt;
0626     msg->tx_error_cnt += error_cnt;
0627 
0628     /* Mark that we're done with this transmit */
0629     adap->transmitting = NULL;
0630 
0631     /*
0632      * If there are still retry attempts left and there was an error and
0633      * the hardware didn't signal that it retried itself (by setting
0634      * CEC_TX_STATUS_MAX_RETRIES), then we will retry ourselves.
0635      */
0636     if (!aborted && data->attempts > attempts_made && !done) {
0637         /* Retry this message */
0638         data->attempts -= attempts_made;
0639         if (msg->timeout)
0640             dprintk(2, "retransmit: %*ph (attempts: %d, wait for 0x%02x)\n",
0641                 msg->len, msg->msg, data->attempts, msg->reply);
0642         else
0643             dprintk(2, "retransmit: %*ph (attempts: %d)\n",
0644                 msg->len, msg->msg, data->attempts);
0645         /* Add the message in front of the transmit queue */
0646         list_add(&data->list, &adap->transmit_queue);
0647         adap->transmit_queue_sz++;
0648         goto wake_thread;
0649     }
0650 
0651     if (aborted && !done)
0652         status |= CEC_TX_STATUS_ABORTED;
0653     data->attempts = 0;
0654 
0655     /* Always set CEC_TX_STATUS_MAX_RETRIES on error */
0656     if (!(status & CEC_TX_STATUS_OK))
0657         msg->tx_status |= CEC_TX_STATUS_MAX_RETRIES;
0658 
0659     /* Queue transmitted message for monitoring purposes */
0660     cec_queue_msg_monitor(adap, msg, 1);
0661 
0662     if ((status & CEC_TX_STATUS_OK) && adap->is_configured &&
0663         msg->timeout) {
0664         /*
0665          * Queue the message into the wait queue if we want to wait
0666          * for a reply.
0667          */
0668         list_add_tail(&data->list, &adap->wait_queue);
0669         schedule_delayed_work(&data->work,
0670                       msecs_to_jiffies(msg->timeout));
0671     } else {
0672         /* Otherwise we're done */
0673         cec_data_completed(data);
0674     }
0675 
0676 wake_thread:
0677     /*
0678      * Wake up the main thread to see if another message is ready
0679      * for transmitting or to retry the current message.
0680      */
0681     wake_up_interruptible(&adap->kthread_waitq);
0682     mutex_unlock(&adap->lock);
0683 }
0684 EXPORT_SYMBOL_GPL(cec_transmit_done_ts);
0685 
0686 void cec_transmit_attempt_done_ts(struct cec_adapter *adap,
0687                   u8 status, ktime_t ts)
0688 {
0689     switch (status & ~CEC_TX_STATUS_MAX_RETRIES) {
0690     case CEC_TX_STATUS_OK:
0691         cec_transmit_done_ts(adap, status, 0, 0, 0, 0, ts);
0692         return;
0693     case CEC_TX_STATUS_ARB_LOST:
0694         cec_transmit_done_ts(adap, status, 1, 0, 0, 0, ts);
0695         return;
0696     case CEC_TX_STATUS_NACK:
0697         cec_transmit_done_ts(adap, status, 0, 1, 0, 0, ts);
0698         return;
0699     case CEC_TX_STATUS_LOW_DRIVE:
0700         cec_transmit_done_ts(adap, status, 0, 0, 1, 0, ts);
0701         return;
0702     case CEC_TX_STATUS_ERROR:
0703         cec_transmit_done_ts(adap, status, 0, 0, 0, 1, ts);
0704         return;
0705     default:
0706         /* Should never happen */
0707         WARN(1, "cec-%s: invalid status 0x%02x\n", adap->name, status);
0708         return;
0709     }
0710 }
0711 EXPORT_SYMBOL_GPL(cec_transmit_attempt_done_ts);
0712 
0713 /*
0714  * Called when waiting for a reply times out.
0715  */
0716 static void cec_wait_timeout(struct work_struct *work)
0717 {
0718     struct cec_data *data = container_of(work, struct cec_data, work.work);
0719     struct cec_adapter *adap = data->adap;
0720 
0721     mutex_lock(&adap->lock);
0722     /*
0723      * Sanity check in case the timeout and the arrival of the message
0724      * happened at the same time.
0725      */
0726     if (list_empty(&data->list))
0727         goto unlock;
0728 
0729     /* Mark the message as timed out */
0730     list_del_init(&data->list);
0731     cec_data_cancel(data, CEC_TX_STATUS_OK, CEC_RX_STATUS_TIMEOUT);
0732 unlock:
0733     mutex_unlock(&adap->lock);
0734 }
0735 
0736 /*
0737  * Transmit a message. The fh argument may be NULL if the transmit is not
0738  * associated with a specific filehandle.
0739  *
0740  * This function is called with adap->lock held.
0741  */
0742 int cec_transmit_msg_fh(struct cec_adapter *adap, struct cec_msg *msg,
0743             struct cec_fh *fh, bool block)
0744 {
0745     struct cec_data *data;
0746     bool is_raw = msg_is_raw(msg);
0747 
0748     if (adap->devnode.unregistered)
0749         return -ENODEV;
0750 
0751     msg->rx_ts = 0;
0752     msg->tx_ts = 0;
0753     msg->rx_status = 0;
0754     msg->tx_status = 0;
0755     msg->tx_arb_lost_cnt = 0;
0756     msg->tx_nack_cnt = 0;
0757     msg->tx_low_drive_cnt = 0;
0758     msg->tx_error_cnt = 0;
0759     msg->sequence = 0;
0760 
0761     if (msg->reply && msg->timeout == 0) {
0762         /* Make sure the timeout isn't 0. */
0763         msg->timeout = 1000;
0764     }
0765     msg->flags &= CEC_MSG_FL_REPLY_TO_FOLLOWERS | CEC_MSG_FL_RAW;
0766 
0767     if (!msg->timeout)
0768         msg->flags &= ~CEC_MSG_FL_REPLY_TO_FOLLOWERS;
0769 
0770     /* Sanity checks */
0771     if (msg->len == 0 || msg->len > CEC_MAX_MSG_SIZE) {
0772         dprintk(1, "%s: invalid length %d\n", __func__, msg->len);
0773         return -EINVAL;
0774     }
0775 
0776     memset(msg->msg + msg->len, 0, sizeof(msg->msg) - msg->len);
0777 
0778     if (msg->timeout)
0779         dprintk(2, "%s: %*ph (wait for 0x%02x%s)\n",
0780             __func__, msg->len, msg->msg, msg->reply,
0781             !block ? ", nb" : "");
0782     else
0783         dprintk(2, "%s: %*ph%s\n",
0784             __func__, msg->len, msg->msg, !block ? " (nb)" : "");
0785 
0786     if (msg->timeout && msg->len == 1) {
0787         dprintk(1, "%s: can't reply to poll msg\n", __func__);
0788         return -EINVAL;
0789     }
0790 
0791     if (is_raw) {
0792         if (!capable(CAP_SYS_RAWIO))
0793             return -EPERM;
0794     } else {
0795         /* A CDC-Only device can only send CDC messages */
0796         if ((adap->log_addrs.flags & CEC_LOG_ADDRS_FL_CDC_ONLY) &&
0797             (msg->len == 1 || msg->msg[1] != CEC_MSG_CDC_MESSAGE)) {
0798             dprintk(1, "%s: not a CDC message\n", __func__);
0799             return -EINVAL;
0800         }
0801 
0802         if (msg->len >= 4 && msg->msg[1] == CEC_MSG_CDC_MESSAGE) {
0803             msg->msg[2] = adap->phys_addr >> 8;
0804             msg->msg[3] = adap->phys_addr & 0xff;
0805         }
0806 
0807         if (msg->len == 1) {
0808             if (cec_msg_destination(msg) == 0xf) {
0809                 dprintk(1, "%s: invalid poll message\n",
0810                     __func__);
0811                 return -EINVAL;
0812             }
0813             if (cec_has_log_addr(adap, cec_msg_destination(msg))) {
0814                 /*
0815                  * If the destination is a logical address our
0816                  * adapter has already claimed, then just NACK
0817                  * this. It depends on the hardware what it will
0818                  * do with a POLL to itself (some OK this), so
0819                  * it is just as easy to handle it here so the
0820                  * behavior will be consistent.
0821                  */
0822                 msg->tx_ts = ktime_get_ns();
0823                 msg->tx_status = CEC_TX_STATUS_NACK |
0824                     CEC_TX_STATUS_MAX_RETRIES;
0825                 msg->tx_nack_cnt = 1;
0826                 msg->sequence = ++adap->sequence;
0827                 if (!msg->sequence)
0828                     msg->sequence = ++adap->sequence;
0829                 return 0;
0830             }
0831         }
0832         if (msg->len > 1 && !cec_msg_is_broadcast(msg) &&
0833             cec_has_log_addr(adap, cec_msg_destination(msg))) {
0834             dprintk(1, "%s: destination is the adapter itself\n",
0835                 __func__);
0836             return -EINVAL;
0837         }
0838         if (msg->len > 1 && adap->is_configured &&
0839             !cec_has_log_addr(adap, cec_msg_initiator(msg))) {
0840             dprintk(1, "%s: initiator has unknown logical address %d\n",
0841                 __func__, cec_msg_initiator(msg));
0842             return -EINVAL;
0843         }
0844         /*
0845          * Special case: allow Ping and IMAGE/TEXT_VIEW_ON to be
0846          * transmitted to a TV, even if the adapter is unconfigured.
0847          * This makes it possible to detect or wake up displays that
0848          * pull down the HPD when in standby.
0849          */
0850         if (!adap->is_configured && !adap->is_configuring &&
0851             (msg->len > 2 ||
0852              cec_msg_destination(msg) != CEC_LOG_ADDR_TV ||
0853              (msg->len == 2 && msg->msg[1] != CEC_MSG_IMAGE_VIEW_ON &&
0854               msg->msg[1] != CEC_MSG_TEXT_VIEW_ON))) {
0855             dprintk(1, "%s: adapter is unconfigured\n", __func__);
0856             return -ENONET;
0857         }
0858     }
0859 
0860     if (!adap->is_configured && !adap->is_configuring) {
0861         if (adap->needs_hpd) {
0862             dprintk(1, "%s: adapter is unconfigured and needs HPD\n",
0863                 __func__);
0864             return -ENONET;
0865         }
0866         if (msg->reply) {
0867             dprintk(1, "%s: invalid msg->reply\n", __func__);
0868             return -EINVAL;
0869         }
0870     }
0871 
0872     if (adap->transmit_queue_sz >= CEC_MAX_MSG_TX_QUEUE_SZ) {
0873         dprintk(2, "%s: transmit queue full\n", __func__);
0874         return -EBUSY;
0875     }
0876 
0877     data = kzalloc(sizeof(*data), GFP_KERNEL);
0878     if (!data)
0879         return -ENOMEM;
0880 
0881     msg->sequence = ++adap->sequence;
0882     if (!msg->sequence)
0883         msg->sequence = ++adap->sequence;
0884 
0885     data->msg = *msg;
0886     data->fh = fh;
0887     data->adap = adap;
0888     data->blocking = block;
0889 
0890     init_completion(&data->c);
0891     INIT_DELAYED_WORK(&data->work, cec_wait_timeout);
0892 
0893     if (fh)
0894         list_add_tail(&data->xfer_list, &fh->xfer_list);
0895     else
0896         INIT_LIST_HEAD(&data->xfer_list);
0897 
0898     list_add_tail(&data->list, &adap->transmit_queue);
0899     adap->transmit_queue_sz++;
0900     if (!adap->transmitting)
0901         wake_up_interruptible(&adap->kthread_waitq);
0902 
0903     /* All done if we don't need to block waiting for completion */
0904     if (!block)
0905         return 0;
0906 
0907     /*
0908      * Release the lock and wait, retake the lock afterwards.
0909      */
0910     mutex_unlock(&adap->lock);
0911     wait_for_completion_killable(&data->c);
0912     if (!data->completed)
0913         cancel_delayed_work_sync(&data->work);
0914     mutex_lock(&adap->lock);
0915 
0916     /* Cancel the transmit if it was interrupted */
0917     if (!data->completed) {
0918         if (data->msg.tx_status & CEC_TX_STATUS_OK)
0919             cec_data_cancel(data, CEC_TX_STATUS_OK, CEC_RX_STATUS_ABORTED);
0920         else
0921             cec_data_cancel(data, CEC_TX_STATUS_ABORTED, 0);
0922     }
0923 
0924     /* The transmit completed (possibly with an error) */
0925     *msg = data->msg;
0926     if (WARN_ON(!list_empty(&data->list)))
0927         list_del(&data->list);
0928     if (WARN_ON(!list_empty(&data->xfer_list)))
0929         list_del(&data->xfer_list);
0930     kfree(data);
0931     return 0;
0932 }
0933 
0934 /* Helper function to be used by drivers and this framework. */
0935 int cec_transmit_msg(struct cec_adapter *adap, struct cec_msg *msg,
0936              bool block)
0937 {
0938     int ret;
0939 
0940     mutex_lock(&adap->lock);
0941     ret = cec_transmit_msg_fh(adap, msg, NULL, block);
0942     mutex_unlock(&adap->lock);
0943     return ret;
0944 }
0945 EXPORT_SYMBOL_GPL(cec_transmit_msg);
0946 
0947 /*
0948  * I don't like forward references but without this the low-level
0949  * cec_received_msg() function would come after a bunch of high-level
0950  * CEC protocol handling functions. That was very confusing.
0951  */
0952 static int cec_receive_notify(struct cec_adapter *adap, struct cec_msg *msg,
0953                   bool is_reply);
0954 
0955 #define DIRECTED    0x80
0956 #define BCAST1_4    0x40
0957 #define BCAST2_0    0x20    /* broadcast only allowed for >= 2.0 */
0958 #define BCAST       (BCAST1_4 | BCAST2_0)
0959 #define BOTH        (BCAST | DIRECTED)
0960 
0961 /*
0962  * Specify minimum length and whether the message is directed, broadcast
0963  * or both. Messages that do not match the criteria are ignored as per
0964  * the CEC specification.
0965  */
0966 static const u8 cec_msg_size[256] = {
0967     [CEC_MSG_ACTIVE_SOURCE] = 4 | BCAST,
0968     [CEC_MSG_IMAGE_VIEW_ON] = 2 | DIRECTED,
0969     [CEC_MSG_TEXT_VIEW_ON] = 2 | DIRECTED,
0970     [CEC_MSG_INACTIVE_SOURCE] = 4 | DIRECTED,
0971     [CEC_MSG_REQUEST_ACTIVE_SOURCE] = 2 | BCAST,
0972     [CEC_MSG_ROUTING_CHANGE] = 6 | BCAST,
0973     [CEC_MSG_ROUTING_INFORMATION] = 4 | BCAST,
0974     [CEC_MSG_SET_STREAM_PATH] = 4 | BCAST,
0975     [CEC_MSG_STANDBY] = 2 | BOTH,
0976     [CEC_MSG_RECORD_OFF] = 2 | DIRECTED,
0977     [CEC_MSG_RECORD_ON] = 3 | DIRECTED,
0978     [CEC_MSG_RECORD_STATUS] = 3 | DIRECTED,
0979     [CEC_MSG_RECORD_TV_SCREEN] = 2 | DIRECTED,
0980     [CEC_MSG_CLEAR_ANALOGUE_TIMER] = 13 | DIRECTED,
0981     [CEC_MSG_CLEAR_DIGITAL_TIMER] = 16 | DIRECTED,
0982     [CEC_MSG_CLEAR_EXT_TIMER] = 13 | DIRECTED,
0983     [CEC_MSG_SET_ANALOGUE_TIMER] = 13 | DIRECTED,
0984     [CEC_MSG_SET_DIGITAL_TIMER] = 16 | DIRECTED,
0985     [CEC_MSG_SET_EXT_TIMER] = 13 | DIRECTED,
0986     [CEC_MSG_SET_TIMER_PROGRAM_TITLE] = 2 | DIRECTED,
0987     [CEC_MSG_TIMER_CLEARED_STATUS] = 3 | DIRECTED,
0988     [CEC_MSG_TIMER_STATUS] = 3 | DIRECTED,
0989     [CEC_MSG_CEC_VERSION] = 3 | DIRECTED,
0990     [CEC_MSG_GET_CEC_VERSION] = 2 | DIRECTED,
0991     [CEC_MSG_GIVE_PHYSICAL_ADDR] = 2 | DIRECTED,
0992     [CEC_MSG_GET_MENU_LANGUAGE] = 2 | DIRECTED,
0993     [CEC_MSG_REPORT_PHYSICAL_ADDR] = 5 | BCAST,
0994     [CEC_MSG_SET_MENU_LANGUAGE] = 5 | BCAST,
0995     [CEC_MSG_REPORT_FEATURES] = 6 | BCAST,
0996     [CEC_MSG_GIVE_FEATURES] = 2 | DIRECTED,
0997     [CEC_MSG_DECK_CONTROL] = 3 | DIRECTED,
0998     [CEC_MSG_DECK_STATUS] = 3 | DIRECTED,
0999     [CEC_MSG_GIVE_DECK_STATUS] = 3 | DIRECTED,
1000     [CEC_MSG_PLAY] = 3 | DIRECTED,
1001     [CEC_MSG_GIVE_TUNER_DEVICE_STATUS] = 3 | DIRECTED,
1002     [CEC_MSG_SELECT_ANALOGUE_SERVICE] = 6 | DIRECTED,
1003     [CEC_MSG_SELECT_DIGITAL_SERVICE] = 9 | DIRECTED,
1004     [CEC_MSG_TUNER_DEVICE_STATUS] = 7 | DIRECTED,
1005     [CEC_MSG_TUNER_STEP_DECREMENT] = 2 | DIRECTED,
1006     [CEC_MSG_TUNER_STEP_INCREMENT] = 2 | DIRECTED,
1007     [CEC_MSG_DEVICE_VENDOR_ID] = 5 | BCAST,
1008     [CEC_MSG_GIVE_DEVICE_VENDOR_ID] = 2 | DIRECTED,
1009     [CEC_MSG_VENDOR_COMMAND] = 2 | DIRECTED,
1010     [CEC_MSG_VENDOR_COMMAND_WITH_ID] = 5 | BOTH,
1011     [CEC_MSG_VENDOR_REMOTE_BUTTON_DOWN] = 2 | BOTH,
1012     [CEC_MSG_VENDOR_REMOTE_BUTTON_UP] = 2 | BOTH,
1013     [CEC_MSG_SET_OSD_STRING] = 3 | DIRECTED,
1014     [CEC_MSG_GIVE_OSD_NAME] = 2 | DIRECTED,
1015     [CEC_MSG_SET_OSD_NAME] = 2 | DIRECTED,
1016     [CEC_MSG_MENU_REQUEST] = 3 | DIRECTED,
1017     [CEC_MSG_MENU_STATUS] = 3 | DIRECTED,
1018     [CEC_MSG_USER_CONTROL_PRESSED] = 3 | DIRECTED,
1019     [CEC_MSG_USER_CONTROL_RELEASED] = 2 | DIRECTED,
1020     [CEC_MSG_GIVE_DEVICE_POWER_STATUS] = 2 | DIRECTED,
1021     [CEC_MSG_REPORT_POWER_STATUS] = 3 | DIRECTED | BCAST2_0,
1022     [CEC_MSG_FEATURE_ABORT] = 4 | DIRECTED,
1023     [CEC_MSG_ABORT] = 2 | DIRECTED,
1024     [CEC_MSG_GIVE_AUDIO_STATUS] = 2 | DIRECTED,
1025     [CEC_MSG_GIVE_SYSTEM_AUDIO_MODE_STATUS] = 2 | DIRECTED,
1026     [CEC_MSG_REPORT_AUDIO_STATUS] = 3 | DIRECTED,
1027     [CEC_MSG_REPORT_SHORT_AUDIO_DESCRIPTOR] = 2 | DIRECTED,
1028     [CEC_MSG_REQUEST_SHORT_AUDIO_DESCRIPTOR] = 2 | DIRECTED,
1029     [CEC_MSG_SET_SYSTEM_AUDIO_MODE] = 3 | BOTH,
1030     [CEC_MSG_SYSTEM_AUDIO_MODE_REQUEST] = 2 | DIRECTED,
1031     [CEC_MSG_SYSTEM_AUDIO_MODE_STATUS] = 3 | DIRECTED,
1032     [CEC_MSG_SET_AUDIO_RATE] = 3 | DIRECTED,
1033     [CEC_MSG_INITIATE_ARC] = 2 | DIRECTED,
1034     [CEC_MSG_REPORT_ARC_INITIATED] = 2 | DIRECTED,
1035     [CEC_MSG_REPORT_ARC_TERMINATED] = 2 | DIRECTED,
1036     [CEC_MSG_REQUEST_ARC_INITIATION] = 2 | DIRECTED,
1037     [CEC_MSG_REQUEST_ARC_TERMINATION] = 2 | DIRECTED,
1038     [CEC_MSG_TERMINATE_ARC] = 2 | DIRECTED,
1039     [CEC_MSG_REQUEST_CURRENT_LATENCY] = 4 | BCAST,
1040     [CEC_MSG_REPORT_CURRENT_LATENCY] = 6 | BCAST,
1041     [CEC_MSG_CDC_MESSAGE] = 2 | BCAST,
1042 };
1043 
1044 /* Called by the CEC adapter if a message is received */
1045 void cec_received_msg_ts(struct cec_adapter *adap,
1046              struct cec_msg *msg, ktime_t ts)
1047 {
1048     struct cec_data *data;
1049     u8 msg_init = cec_msg_initiator(msg);
1050     u8 msg_dest = cec_msg_destination(msg);
1051     u8 cmd = msg->msg[1];
1052     bool is_reply = false;
1053     bool valid_la = true;
1054     u8 min_len = 0;
1055 
1056     if (WARN_ON(!msg->len || msg->len > CEC_MAX_MSG_SIZE))
1057         return;
1058 
1059     if (adap->devnode.unregistered)
1060         return;
1061 
1062     /*
1063      * Some CEC adapters will receive the messages that they transmitted.
1064      * This test filters out those messages by checking if we are the
1065      * initiator, and just returning in that case.
1066      *
1067      * Note that this won't work if this is an Unregistered device.
1068      *
1069      * It is bad practice if the hardware receives the message that it
1070      * transmitted and luckily most CEC adapters behave correctly in this
1071      * respect.
1072      */
1073     if (msg_init != CEC_LOG_ADDR_UNREGISTERED &&
1074         cec_has_log_addr(adap, msg_init))
1075         return;
1076 
1077     msg->rx_ts = ktime_to_ns(ts);
1078     msg->rx_status = CEC_RX_STATUS_OK;
1079     msg->sequence = msg->reply = msg->timeout = 0;
1080     msg->tx_status = 0;
1081     msg->tx_ts = 0;
1082     msg->tx_arb_lost_cnt = 0;
1083     msg->tx_nack_cnt = 0;
1084     msg->tx_low_drive_cnt = 0;
1085     msg->tx_error_cnt = 0;
1086     msg->flags = 0;
1087     memset(msg->msg + msg->len, 0, sizeof(msg->msg) - msg->len);
1088 
1089     mutex_lock(&adap->lock);
1090     dprintk(2, "%s: %*ph\n", __func__, msg->len, msg->msg);
1091 
1092     adap->last_initiator = 0xff;
1093 
1094     /* Check if this message was for us (directed or broadcast). */
1095     if (!cec_msg_is_broadcast(msg))
1096         valid_la = cec_has_log_addr(adap, msg_dest);
1097 
1098     /*
1099      * Check if the length is not too short or if the message is a
1100      * broadcast message where a directed message was expected or
1101      * vice versa. If so, then the message has to be ignored (according
1102      * to section CEC 7.3 and CEC 12.2).
1103      */
1104     if (valid_la && msg->len > 1 && cec_msg_size[cmd]) {
1105         u8 dir_fl = cec_msg_size[cmd] & BOTH;
1106 
1107         min_len = cec_msg_size[cmd] & 0x1f;
1108         if (msg->len < min_len)
1109             valid_la = false;
1110         else if (!cec_msg_is_broadcast(msg) && !(dir_fl & DIRECTED))
1111             valid_la = false;
1112         else if (cec_msg_is_broadcast(msg) && !(dir_fl & BCAST))
1113             valid_la = false;
1114         else if (cec_msg_is_broadcast(msg) &&
1115              adap->log_addrs.cec_version < CEC_OP_CEC_VERSION_2_0 &&
1116              !(dir_fl & BCAST1_4))
1117             valid_la = false;
1118     }
1119     if (valid_la && min_len) {
1120         /* These messages have special length requirements */
1121         switch (cmd) {
1122         case CEC_MSG_TIMER_STATUS:
1123             if (msg->msg[2] & 0x10) {
1124                 switch (msg->msg[2] & 0xf) {
1125                 case CEC_OP_PROG_INFO_NOT_ENOUGH_SPACE:
1126                 case CEC_OP_PROG_INFO_MIGHT_NOT_BE_ENOUGH_SPACE:
1127                     if (msg->len < 5)
1128                         valid_la = false;
1129                     break;
1130                 }
1131             } else if ((msg->msg[2] & 0xf) == CEC_OP_PROG_ERROR_DUPLICATE) {
1132                 if (msg->len < 5)
1133                     valid_la = false;
1134             }
1135             break;
1136         case CEC_MSG_RECORD_ON:
1137             switch (msg->msg[2]) {
1138             case CEC_OP_RECORD_SRC_OWN:
1139                 break;
1140             case CEC_OP_RECORD_SRC_DIGITAL:
1141                 if (msg->len < 10)
1142                     valid_la = false;
1143                 break;
1144             case CEC_OP_RECORD_SRC_ANALOG:
1145                 if (msg->len < 7)
1146                     valid_la = false;
1147                 break;
1148             case CEC_OP_RECORD_SRC_EXT_PLUG:
1149                 if (msg->len < 4)
1150                     valid_la = false;
1151                 break;
1152             case CEC_OP_RECORD_SRC_EXT_PHYS_ADDR:
1153                 if (msg->len < 5)
1154                     valid_la = false;
1155                 break;
1156             }
1157             break;
1158         }
1159     }
1160 
1161     /* It's a valid message and not a poll or CDC message */
1162     if (valid_la && msg->len > 1 && cmd != CEC_MSG_CDC_MESSAGE) {
1163         bool abort = cmd == CEC_MSG_FEATURE_ABORT;
1164 
1165         /* The aborted command is in msg[2] */
1166         if (abort)
1167             cmd = msg->msg[2];
1168 
1169         /*
1170          * Walk over all transmitted messages that are waiting for a
1171          * reply.
1172          */
1173         list_for_each_entry(data, &adap->wait_queue, list) {
1174             struct cec_msg *dst = &data->msg;
1175 
1176             /*
1177              * The *only* CEC message that has two possible replies
1178              * is CEC_MSG_INITIATE_ARC.
1179              * In this case allow either of the two replies.
1180              */
1181             if (!abort && dst->msg[1] == CEC_MSG_INITIATE_ARC &&
1182                 (cmd == CEC_MSG_REPORT_ARC_INITIATED ||
1183                  cmd == CEC_MSG_REPORT_ARC_TERMINATED) &&
1184                 (dst->reply == CEC_MSG_REPORT_ARC_INITIATED ||
1185                  dst->reply == CEC_MSG_REPORT_ARC_TERMINATED))
1186                 dst->reply = cmd;
1187 
1188             /* Does the command match? */
1189             if ((abort && cmd != dst->msg[1]) ||
1190                 (!abort && cmd != dst->reply))
1191                 continue;
1192 
1193             /* Does the addressing match? */
1194             if (msg_init != cec_msg_destination(dst) &&
1195                 !cec_msg_is_broadcast(dst))
1196                 continue;
1197 
1198             /* We got a reply */
1199             memcpy(dst->msg, msg->msg, msg->len);
1200             dst->len = msg->len;
1201             dst->rx_ts = msg->rx_ts;
1202             dst->rx_status = msg->rx_status;
1203             if (abort)
1204                 dst->rx_status |= CEC_RX_STATUS_FEATURE_ABORT;
1205             msg->flags = dst->flags;
1206             msg->sequence = dst->sequence;
1207             /* Remove it from the wait_queue */
1208             list_del_init(&data->list);
1209 
1210             /* Cancel the pending timeout work */
1211             if (!cancel_delayed_work(&data->work)) {
1212                 mutex_unlock(&adap->lock);
1213                 cancel_delayed_work_sync(&data->work);
1214                 mutex_lock(&adap->lock);
1215             }
1216             /*
1217              * Mark this as a reply, provided someone is still
1218              * waiting for the answer.
1219              */
1220             if (data->fh)
1221                 is_reply = true;
1222             cec_data_completed(data);
1223             break;
1224         }
1225     }
1226     mutex_unlock(&adap->lock);
1227 
1228     /* Pass the message on to any monitoring filehandles */
1229     cec_queue_msg_monitor(adap, msg, valid_la);
1230 
1231     /* We're done if it is not for us or a poll message */
1232     if (!valid_la || msg->len <= 1)
1233         return;
1234 
1235     if (adap->log_addrs.log_addr_mask == 0)
1236         return;
1237 
1238     /*
1239      * Process the message on the protocol level. If is_reply is true,
1240      * then cec_receive_notify() won't pass on the reply to the listener(s)
1241      * since that was already done by cec_data_completed() above.
1242      */
1243     cec_receive_notify(adap, msg, is_reply);
1244 }
1245 EXPORT_SYMBOL_GPL(cec_received_msg_ts);
1246 
1247 /* Logical Address Handling */
1248 
1249 /*
1250  * Attempt to claim a specific logical address.
1251  *
1252  * This function is called with adap->lock held.
1253  */
1254 static int cec_config_log_addr(struct cec_adapter *adap,
1255                    unsigned int idx,
1256                    unsigned int log_addr)
1257 {
1258     struct cec_log_addrs *las = &adap->log_addrs;
1259     struct cec_msg msg = { };
1260     const unsigned int max_retries = 2;
1261     unsigned int i;
1262     int err;
1263 
1264     if (cec_has_log_addr(adap, log_addr))
1265         return 0;
1266 
1267     /* Send poll message */
1268     msg.len = 1;
1269     msg.msg[0] = (log_addr << 4) | log_addr;
1270 
1271     for (i = 0; i < max_retries; i++) {
1272         err = cec_transmit_msg_fh(adap, &msg, NULL, true);
1273 
1274         /*
1275          * While trying to poll the physical address was reset
1276          * and the adapter was unconfigured, so bail out.
1277          */
1278         if (adap->phys_addr == CEC_PHYS_ADDR_INVALID)
1279             return -EINTR;
1280 
1281         /* Also bail out if the PA changed while configuring. */
1282         if (adap->must_reconfigure)
1283             return -EINTR;
1284 
1285         if (err)
1286             return err;
1287 
1288         /*
1289          * The message was aborted or timed out due to a disconnect or
1290          * unconfigure, just bail out.
1291          */
1292         if (msg.tx_status &
1293             (CEC_TX_STATUS_ABORTED | CEC_TX_STATUS_TIMEOUT))
1294             return -EINTR;
1295         if (msg.tx_status & CEC_TX_STATUS_OK)
1296             return 0;
1297         if (msg.tx_status & CEC_TX_STATUS_NACK)
1298             break;
1299         /*
1300          * Retry up to max_retries times if the message was neither
1301          * OKed or NACKed. This can happen due to e.g. a Lost
1302          * Arbitration condition.
1303          */
1304     }
1305 
1306     /*
1307      * If we are unable to get an OK or a NACK after max_retries attempts
1308      * (and note that each attempt already consists of four polls), then
1309      * we assume that something is really weird and that it is not a
1310      * good idea to try and claim this logical address.
1311      */
1312     if (i == max_retries) {
1313         dprintk(0, "polling for LA %u failed with tx_status=0x%04x\n",
1314             log_addr, msg.tx_status);
1315         return 0;
1316     }
1317 
1318     /*
1319      * Message not acknowledged, so this logical
1320      * address is free to use.
1321      */
1322     err = call_op(adap, adap_log_addr, log_addr);
1323     if (err)
1324         return err;
1325 
1326     las->log_addr[idx] = log_addr;
1327     las->log_addr_mask |= 1 << log_addr;
1328     return 1;
1329 }
1330 
1331 /*
1332  * Unconfigure the adapter: clear all logical addresses and send
1333  * the state changed event.
1334  *
1335  * This function is called with adap->lock held.
1336  */
1337 static void cec_adap_unconfigure(struct cec_adapter *adap)
1338 {
1339     if (!adap->needs_hpd || adap->phys_addr != CEC_PHYS_ADDR_INVALID)
1340         WARN_ON(call_op(adap, adap_log_addr, CEC_LOG_ADDR_INVALID));
1341     adap->log_addrs.log_addr_mask = 0;
1342     adap->is_configured = false;
1343     cec_flush(adap);
1344     wake_up_interruptible(&adap->kthread_waitq);
1345     cec_post_state_event(adap);
1346     call_void_op(adap, adap_configured, false);
1347 }
1348 
1349 /*
1350  * Attempt to claim the required logical addresses.
1351  */
1352 static int cec_config_thread_func(void *arg)
1353 {
1354     /* The various LAs for each type of device */
1355     static const u8 tv_log_addrs[] = {
1356         CEC_LOG_ADDR_TV, CEC_LOG_ADDR_SPECIFIC,
1357         CEC_LOG_ADDR_INVALID
1358     };
1359     static const u8 record_log_addrs[] = {
1360         CEC_LOG_ADDR_RECORD_1, CEC_LOG_ADDR_RECORD_2,
1361         CEC_LOG_ADDR_RECORD_3,
1362         CEC_LOG_ADDR_BACKUP_1, CEC_LOG_ADDR_BACKUP_2,
1363         CEC_LOG_ADDR_INVALID
1364     };
1365     static const u8 tuner_log_addrs[] = {
1366         CEC_LOG_ADDR_TUNER_1, CEC_LOG_ADDR_TUNER_2,
1367         CEC_LOG_ADDR_TUNER_3, CEC_LOG_ADDR_TUNER_4,
1368         CEC_LOG_ADDR_BACKUP_1, CEC_LOG_ADDR_BACKUP_2,
1369         CEC_LOG_ADDR_INVALID
1370     };
1371     static const u8 playback_log_addrs[] = {
1372         CEC_LOG_ADDR_PLAYBACK_1, CEC_LOG_ADDR_PLAYBACK_2,
1373         CEC_LOG_ADDR_PLAYBACK_3,
1374         CEC_LOG_ADDR_BACKUP_1, CEC_LOG_ADDR_BACKUP_2,
1375         CEC_LOG_ADDR_INVALID
1376     };
1377     static const u8 audiosystem_log_addrs[] = {
1378         CEC_LOG_ADDR_AUDIOSYSTEM,
1379         CEC_LOG_ADDR_INVALID
1380     };
1381     static const u8 specific_use_log_addrs[] = {
1382         CEC_LOG_ADDR_SPECIFIC,
1383         CEC_LOG_ADDR_BACKUP_1, CEC_LOG_ADDR_BACKUP_2,
1384         CEC_LOG_ADDR_INVALID
1385     };
1386     static const u8 *type2addrs[6] = {
1387         [CEC_LOG_ADDR_TYPE_TV] = tv_log_addrs,
1388         [CEC_LOG_ADDR_TYPE_RECORD] = record_log_addrs,
1389         [CEC_LOG_ADDR_TYPE_TUNER] = tuner_log_addrs,
1390         [CEC_LOG_ADDR_TYPE_PLAYBACK] = playback_log_addrs,
1391         [CEC_LOG_ADDR_TYPE_AUDIOSYSTEM] = audiosystem_log_addrs,
1392         [CEC_LOG_ADDR_TYPE_SPECIFIC] = specific_use_log_addrs,
1393     };
1394     static const u16 type2mask[] = {
1395         [CEC_LOG_ADDR_TYPE_TV] = CEC_LOG_ADDR_MASK_TV,
1396         [CEC_LOG_ADDR_TYPE_RECORD] = CEC_LOG_ADDR_MASK_RECORD,
1397         [CEC_LOG_ADDR_TYPE_TUNER] = CEC_LOG_ADDR_MASK_TUNER,
1398         [CEC_LOG_ADDR_TYPE_PLAYBACK] = CEC_LOG_ADDR_MASK_PLAYBACK,
1399         [CEC_LOG_ADDR_TYPE_AUDIOSYSTEM] = CEC_LOG_ADDR_MASK_AUDIOSYSTEM,
1400         [CEC_LOG_ADDR_TYPE_SPECIFIC] = CEC_LOG_ADDR_MASK_SPECIFIC,
1401     };
1402     struct cec_adapter *adap = arg;
1403     struct cec_log_addrs *las = &adap->log_addrs;
1404     int err;
1405     int i, j;
1406 
1407     mutex_lock(&adap->lock);
1408     dprintk(1, "physical address: %x.%x.%x.%x, claim %d logical addresses\n",
1409         cec_phys_addr_exp(adap->phys_addr), las->num_log_addrs);
1410     las->log_addr_mask = 0;
1411 
1412     if (las->log_addr_type[0] == CEC_LOG_ADDR_TYPE_UNREGISTERED)
1413         goto configured;
1414 
1415 reconfigure:
1416     for (i = 0; i < las->num_log_addrs; i++) {
1417         unsigned int type = las->log_addr_type[i];
1418         const u8 *la_list;
1419         u8 last_la;
1420 
1421         /*
1422          * The TV functionality can only map to physical address 0.
1423          * For any other address, try the Specific functionality
1424          * instead as per the spec.
1425          */
1426         if (adap->phys_addr && type == CEC_LOG_ADDR_TYPE_TV)
1427             type = CEC_LOG_ADDR_TYPE_SPECIFIC;
1428 
1429         la_list = type2addrs[type];
1430         last_la = las->log_addr[i];
1431         las->log_addr[i] = CEC_LOG_ADDR_INVALID;
1432         if (last_la == CEC_LOG_ADDR_INVALID ||
1433             last_la == CEC_LOG_ADDR_UNREGISTERED ||
1434             !((1 << last_la) & type2mask[type]))
1435             last_la = la_list[0];
1436 
1437         err = cec_config_log_addr(adap, i, last_la);
1438 
1439         if (adap->must_reconfigure) {
1440             adap->must_reconfigure = false;
1441             las->log_addr_mask = 0;
1442             goto reconfigure;
1443         }
1444 
1445         if (err > 0) /* Reused last LA */
1446             continue;
1447 
1448         if (err < 0)
1449             goto unconfigure;
1450 
1451         for (j = 0; la_list[j] != CEC_LOG_ADDR_INVALID; j++) {
1452             /* Tried this one already, skip it */
1453             if (la_list[j] == last_la)
1454                 continue;
1455             /* The backup addresses are CEC 2.0 specific */
1456             if ((la_list[j] == CEC_LOG_ADDR_BACKUP_1 ||
1457                  la_list[j] == CEC_LOG_ADDR_BACKUP_2) &&
1458                 las->cec_version < CEC_OP_CEC_VERSION_2_0)
1459                 continue;
1460 
1461             err = cec_config_log_addr(adap, i, la_list[j]);
1462             if (err == 0) /* LA is in use */
1463                 continue;
1464             if (err < 0)
1465                 goto unconfigure;
1466             /* Done, claimed an LA */
1467             break;
1468         }
1469 
1470         if (la_list[j] == CEC_LOG_ADDR_INVALID)
1471             dprintk(1, "could not claim LA %d\n", i);
1472     }
1473 
1474     if (adap->log_addrs.log_addr_mask == 0 &&
1475         !(las->flags & CEC_LOG_ADDRS_FL_ALLOW_UNREG_FALLBACK))
1476         goto unconfigure;
1477 
1478 configured:
1479     if (adap->log_addrs.log_addr_mask == 0) {
1480         /* Fall back to unregistered */
1481         las->log_addr[0] = CEC_LOG_ADDR_UNREGISTERED;
1482         las->log_addr_mask = 1 << las->log_addr[0];
1483         for (i = 1; i < las->num_log_addrs; i++)
1484             las->log_addr[i] = CEC_LOG_ADDR_INVALID;
1485     }
1486     for (i = las->num_log_addrs; i < CEC_MAX_LOG_ADDRS; i++)
1487         las->log_addr[i] = CEC_LOG_ADDR_INVALID;
1488     adap->is_configured = true;
1489     adap->is_configuring = false;
1490     adap->must_reconfigure = false;
1491     cec_post_state_event(adap);
1492 
1493     /*
1494      * Now post the Report Features and Report Physical Address broadcast
1495      * messages. Note that these are non-blocking transmits, meaning that
1496      * they are just queued up and once adap->lock is unlocked the main
1497      * thread will kick in and start transmitting these.
1498      *
1499      * If after this function is done (but before one or more of these
1500      * messages are actually transmitted) the CEC adapter is unconfigured,
1501      * then any remaining messages will be dropped by the main thread.
1502      */
1503     for (i = 0; i < las->num_log_addrs; i++) {
1504         struct cec_msg msg = {};
1505 
1506         if (las->log_addr[i] == CEC_LOG_ADDR_INVALID ||
1507             (las->flags & CEC_LOG_ADDRS_FL_CDC_ONLY))
1508             continue;
1509 
1510         msg.msg[0] = (las->log_addr[i] << 4) | 0x0f;
1511 
1512         /* Report Features must come first according to CEC 2.0 */
1513         if (las->log_addr[i] != CEC_LOG_ADDR_UNREGISTERED &&
1514             adap->log_addrs.cec_version >= CEC_OP_CEC_VERSION_2_0) {
1515             cec_fill_msg_report_features(adap, &msg, i);
1516             cec_transmit_msg_fh(adap, &msg, NULL, false);
1517         }
1518 
1519         /* Report Physical Address */
1520         cec_msg_report_physical_addr(&msg, adap->phys_addr,
1521                          las->primary_device_type[i]);
1522         dprintk(1, "config: la %d pa %x.%x.%x.%x\n",
1523             las->log_addr[i],
1524             cec_phys_addr_exp(adap->phys_addr));
1525         cec_transmit_msg_fh(adap, &msg, NULL, false);
1526 
1527         /* Report Vendor ID */
1528         if (adap->log_addrs.vendor_id != CEC_VENDOR_ID_NONE) {
1529             cec_msg_device_vendor_id(&msg,
1530                          adap->log_addrs.vendor_id);
1531             cec_transmit_msg_fh(adap, &msg, NULL, false);
1532         }
1533     }
1534     adap->kthread_config = NULL;
1535     complete(&adap->config_completion);
1536     mutex_unlock(&adap->lock);
1537     call_void_op(adap, adap_configured, true);
1538     return 0;
1539 
1540 unconfigure:
1541     for (i = 0; i < las->num_log_addrs; i++)
1542         las->log_addr[i] = CEC_LOG_ADDR_INVALID;
1543     cec_adap_unconfigure(adap);
1544     adap->is_configuring = false;
1545     adap->must_reconfigure = false;
1546     adap->kthread_config = NULL;
1547     complete(&adap->config_completion);
1548     mutex_unlock(&adap->lock);
1549     return 0;
1550 }
1551 
1552 /*
1553  * Called from either __cec_s_phys_addr or __cec_s_log_addrs to claim the
1554  * logical addresses.
1555  *
1556  * This function is called with adap->lock held.
1557  */
1558 static void cec_claim_log_addrs(struct cec_adapter *adap, bool block)
1559 {
1560     if (WARN_ON(adap->is_configuring || adap->is_configured))
1561         return;
1562 
1563     init_completion(&adap->config_completion);
1564 
1565     /* Ready to kick off the thread */
1566     adap->is_configuring = true;
1567     adap->kthread_config = kthread_run(cec_config_thread_func, adap,
1568                        "ceccfg-%s", adap->name);
1569     if (IS_ERR(adap->kthread_config)) {
1570         adap->kthread_config = NULL;
1571         adap->is_configuring = false;
1572     } else if (block) {
1573         mutex_unlock(&adap->lock);
1574         wait_for_completion(&adap->config_completion);
1575         mutex_lock(&adap->lock);
1576     }
1577 }
1578 
1579 /*
1580  * Helper function to enable/disable the CEC adapter.
1581  *
1582  * This function is called with adap->lock held.
1583  */
1584 static int cec_adap_enable(struct cec_adapter *adap)
1585 {
1586     bool enable;
1587     int ret = 0;
1588 
1589     enable = adap->monitor_all_cnt || adap->monitor_pin_cnt ||
1590          adap->log_addrs.num_log_addrs;
1591     if (adap->needs_hpd)
1592         enable = enable && adap->phys_addr != CEC_PHYS_ADDR_INVALID;
1593 
1594     if (enable == adap->is_enabled)
1595         return 0;
1596 
1597     /* serialize adap_enable */
1598     mutex_lock(&adap->devnode.lock);
1599     if (enable) {
1600         adap->last_initiator = 0xff;
1601         adap->transmit_in_progress = false;
1602         ret = adap->ops->adap_enable(adap, true);
1603         if (!ret) {
1604             /*
1605              * Enable monitor-all/pin modes if needed. We warn, but
1606              * continue if this fails as this is not a critical error.
1607              */
1608             if (adap->monitor_all_cnt)
1609                 WARN_ON(call_op(adap, adap_monitor_all_enable, true));
1610             if (adap->monitor_pin_cnt)
1611                 WARN_ON(call_op(adap, adap_monitor_pin_enable, true));
1612         }
1613     } else {
1614         /* Disable monitor-all/pin modes if needed (needs_hpd == 1) */
1615         if (adap->monitor_all_cnt)
1616             WARN_ON(call_op(adap, adap_monitor_all_enable, false));
1617         if (adap->monitor_pin_cnt)
1618             WARN_ON(call_op(adap, adap_monitor_pin_enable, false));
1619         WARN_ON(adap->ops->adap_enable(adap, false));
1620         adap->last_initiator = 0xff;
1621         adap->transmit_in_progress = false;
1622         adap->transmit_in_progress_aborted = false;
1623         if (adap->transmitting)
1624             cec_data_cancel(adap->transmitting, CEC_TX_STATUS_ABORTED, 0);
1625     }
1626     if (!ret)
1627         adap->is_enabled = enable;
1628     wake_up_interruptible(&adap->kthread_waitq);
1629     mutex_unlock(&adap->devnode.lock);
1630     return ret;
1631 }
1632 
1633 /* Set a new physical address and send an event notifying userspace of this.
1634  *
1635  * This function is called with adap->lock held.
1636  */
1637 void __cec_s_phys_addr(struct cec_adapter *adap, u16 phys_addr, bool block)
1638 {
1639     bool becomes_invalid = phys_addr == CEC_PHYS_ADDR_INVALID;
1640     bool is_invalid = adap->phys_addr == CEC_PHYS_ADDR_INVALID;
1641 
1642     if (phys_addr == adap->phys_addr)
1643         return;
1644     if (!becomes_invalid && adap->devnode.unregistered)
1645         return;
1646 
1647     dprintk(1, "new physical address %x.%x.%x.%x\n",
1648         cec_phys_addr_exp(phys_addr));
1649     if (becomes_invalid || !is_invalid) {
1650         adap->phys_addr = CEC_PHYS_ADDR_INVALID;
1651         cec_post_state_event(adap);
1652         cec_adap_unconfigure(adap);
1653         if (becomes_invalid) {
1654             cec_adap_enable(adap);
1655             return;
1656         }
1657     }
1658 
1659     adap->phys_addr = phys_addr;
1660     if (is_invalid)
1661         cec_adap_enable(adap);
1662 
1663     cec_post_state_event(adap);
1664     if (!adap->log_addrs.num_log_addrs)
1665         return;
1666     if (adap->is_configuring)
1667         adap->must_reconfigure = true;
1668     else
1669         cec_claim_log_addrs(adap, block);
1670 }
1671 
1672 void cec_s_phys_addr(struct cec_adapter *adap, u16 phys_addr, bool block)
1673 {
1674     if (IS_ERR_OR_NULL(adap))
1675         return;
1676 
1677     mutex_lock(&adap->lock);
1678     __cec_s_phys_addr(adap, phys_addr, block);
1679     mutex_unlock(&adap->lock);
1680 }
1681 EXPORT_SYMBOL_GPL(cec_s_phys_addr);
1682 
1683 void cec_s_phys_addr_from_edid(struct cec_adapter *adap,
1684                    const struct edid *edid)
1685 {
1686     u16 pa = CEC_PHYS_ADDR_INVALID;
1687 
1688     if (edid && edid->extensions)
1689         pa = cec_get_edid_phys_addr((const u8 *)edid,
1690                 EDID_LENGTH * (edid->extensions + 1), NULL);
1691     cec_s_phys_addr(adap, pa, false);
1692 }
1693 EXPORT_SYMBOL_GPL(cec_s_phys_addr_from_edid);
1694 
1695 void cec_s_conn_info(struct cec_adapter *adap,
1696              const struct cec_connector_info *conn_info)
1697 {
1698     if (IS_ERR_OR_NULL(adap))
1699         return;
1700 
1701     if (!(adap->capabilities & CEC_CAP_CONNECTOR_INFO))
1702         return;
1703 
1704     mutex_lock(&adap->lock);
1705     if (conn_info)
1706         adap->conn_info = *conn_info;
1707     else
1708         memset(&adap->conn_info, 0, sizeof(adap->conn_info));
1709     cec_post_state_event(adap);
1710     mutex_unlock(&adap->lock);
1711 }
1712 EXPORT_SYMBOL_GPL(cec_s_conn_info);
1713 
1714 /*
1715  * Called from either the ioctl or a driver to set the logical addresses.
1716  *
1717  * This function is called with adap->lock held.
1718  */
1719 int __cec_s_log_addrs(struct cec_adapter *adap,
1720               struct cec_log_addrs *log_addrs, bool block)
1721 {
1722     u16 type_mask = 0;
1723     int err;
1724     int i;
1725 
1726     if (adap->devnode.unregistered)
1727         return -ENODEV;
1728 
1729     if (!log_addrs || log_addrs->num_log_addrs == 0) {
1730         if (!adap->log_addrs.num_log_addrs)
1731             return 0;
1732         if (adap->is_configuring || adap->is_configured)
1733             cec_adap_unconfigure(adap);
1734         adap->log_addrs.num_log_addrs = 0;
1735         for (i = 0; i < CEC_MAX_LOG_ADDRS; i++)
1736             adap->log_addrs.log_addr[i] = CEC_LOG_ADDR_INVALID;
1737         adap->log_addrs.osd_name[0] = '\0';
1738         adap->log_addrs.vendor_id = CEC_VENDOR_ID_NONE;
1739         adap->log_addrs.cec_version = CEC_OP_CEC_VERSION_2_0;
1740         cec_adap_enable(adap);
1741         return 0;
1742     }
1743 
1744     if (log_addrs->flags & CEC_LOG_ADDRS_FL_CDC_ONLY) {
1745         /*
1746          * Sanitize log_addrs fields if a CDC-Only device is
1747          * requested.
1748          */
1749         log_addrs->num_log_addrs = 1;
1750         log_addrs->osd_name[0] = '\0';
1751         log_addrs->vendor_id = CEC_VENDOR_ID_NONE;
1752         log_addrs->log_addr_type[0] = CEC_LOG_ADDR_TYPE_UNREGISTERED;
1753         /*
1754          * This is just an internal convention since a CDC-Only device
1755          * doesn't have to be a switch. But switches already use
1756          * unregistered, so it makes some kind of sense to pick this
1757          * as the primary device. Since a CDC-Only device never sends
1758          * any 'normal' CEC messages this primary device type is never
1759          * sent over the CEC bus.
1760          */
1761         log_addrs->primary_device_type[0] = CEC_OP_PRIM_DEVTYPE_SWITCH;
1762         log_addrs->all_device_types[0] = 0;
1763         log_addrs->features[0][0] = 0;
1764         log_addrs->features[0][1] = 0;
1765     }
1766 
1767     /* Ensure the osd name is 0-terminated */
1768     log_addrs->osd_name[sizeof(log_addrs->osd_name) - 1] = '\0';
1769 
1770     /* Sanity checks */
1771     if (log_addrs->num_log_addrs > adap->available_log_addrs) {
1772         dprintk(1, "num_log_addrs > %d\n", adap->available_log_addrs);
1773         return -EINVAL;
1774     }
1775 
1776     /*
1777      * Vendor ID is a 24 bit number, so check if the value is
1778      * within the correct range.
1779      */
1780     if (log_addrs->vendor_id != CEC_VENDOR_ID_NONE &&
1781         (log_addrs->vendor_id & 0xff000000) != 0) {
1782         dprintk(1, "invalid vendor ID\n");
1783         return -EINVAL;
1784     }
1785 
1786     if (log_addrs->cec_version != CEC_OP_CEC_VERSION_1_4 &&
1787         log_addrs->cec_version != CEC_OP_CEC_VERSION_2_0) {
1788         dprintk(1, "invalid CEC version\n");
1789         return -EINVAL;
1790     }
1791 
1792     if (log_addrs->num_log_addrs > 1)
1793         for (i = 0; i < log_addrs->num_log_addrs; i++)
1794             if (log_addrs->log_addr_type[i] ==
1795                     CEC_LOG_ADDR_TYPE_UNREGISTERED) {
1796                 dprintk(1, "num_log_addrs > 1 can't be combined with unregistered LA\n");
1797                 return -EINVAL;
1798             }
1799 
1800     for (i = 0; i < log_addrs->num_log_addrs; i++) {
1801         const u8 feature_sz = ARRAY_SIZE(log_addrs->features[0]);
1802         u8 *features = log_addrs->features[i];
1803         bool op_is_dev_features = false;
1804         unsigned int j;
1805 
1806         log_addrs->log_addr[i] = CEC_LOG_ADDR_INVALID;
1807         if (log_addrs->log_addr_type[i] > CEC_LOG_ADDR_TYPE_UNREGISTERED) {
1808             dprintk(1, "unknown logical address type\n");
1809             return -EINVAL;
1810         }
1811         if (type_mask & (1 << log_addrs->log_addr_type[i])) {
1812             dprintk(1, "duplicate logical address type\n");
1813             return -EINVAL;
1814         }
1815         type_mask |= 1 << log_addrs->log_addr_type[i];
1816         if ((type_mask & (1 << CEC_LOG_ADDR_TYPE_RECORD)) &&
1817             (type_mask & (1 << CEC_LOG_ADDR_TYPE_PLAYBACK))) {
1818             /* Record already contains the playback functionality */
1819             dprintk(1, "invalid record + playback combination\n");
1820             return -EINVAL;
1821         }
1822         if (log_addrs->primary_device_type[i] >
1823                     CEC_OP_PRIM_DEVTYPE_PROCESSOR) {
1824             dprintk(1, "unknown primary device type\n");
1825             return -EINVAL;
1826         }
1827         if (log_addrs->primary_device_type[i] == 2) {
1828             dprintk(1, "invalid primary device type\n");
1829             return -EINVAL;
1830         }
1831         for (j = 0; j < feature_sz; j++) {
1832             if ((features[j] & 0x80) == 0) {
1833                 if (op_is_dev_features)
1834                     break;
1835                 op_is_dev_features = true;
1836             }
1837         }
1838         if (!op_is_dev_features || j == feature_sz) {
1839             dprintk(1, "malformed features\n");
1840             return -EINVAL;
1841         }
1842         /* Zero unused part of the feature array */
1843         memset(features + j + 1, 0, feature_sz - j - 1);
1844     }
1845 
1846     if (log_addrs->cec_version >= CEC_OP_CEC_VERSION_2_0) {
1847         if (log_addrs->num_log_addrs > 2) {
1848             dprintk(1, "CEC 2.0 allows no more than 2 logical addresses\n");
1849             return -EINVAL;
1850         }
1851         if (log_addrs->num_log_addrs == 2) {
1852             if (!(type_mask & ((1 << CEC_LOG_ADDR_TYPE_AUDIOSYSTEM) |
1853                        (1 << CEC_LOG_ADDR_TYPE_TV)))) {
1854                 dprintk(1, "two LAs is only allowed for audiosystem and TV\n");
1855                 return -EINVAL;
1856             }
1857             if (!(type_mask & ((1 << CEC_LOG_ADDR_TYPE_PLAYBACK) |
1858                        (1 << CEC_LOG_ADDR_TYPE_RECORD)))) {
1859                 dprintk(1, "an audiosystem/TV can only be combined with record or playback\n");
1860                 return -EINVAL;
1861             }
1862         }
1863     }
1864 
1865     /* Zero unused LAs */
1866     for (i = log_addrs->num_log_addrs; i < CEC_MAX_LOG_ADDRS; i++) {
1867         log_addrs->primary_device_type[i] = 0;
1868         log_addrs->log_addr_type[i] = 0;
1869         log_addrs->all_device_types[i] = 0;
1870         memset(log_addrs->features[i], 0,
1871                sizeof(log_addrs->features[i]));
1872     }
1873 
1874     log_addrs->log_addr_mask = adap->log_addrs.log_addr_mask;
1875     adap->log_addrs = *log_addrs;
1876     err = cec_adap_enable(adap);
1877     if (!err && adap->phys_addr != CEC_PHYS_ADDR_INVALID)
1878         cec_claim_log_addrs(adap, block);
1879     return err;
1880 }
1881 
1882 int cec_s_log_addrs(struct cec_adapter *adap,
1883             struct cec_log_addrs *log_addrs, bool block)
1884 {
1885     int err;
1886 
1887     mutex_lock(&adap->lock);
1888     err = __cec_s_log_addrs(adap, log_addrs, block);
1889     mutex_unlock(&adap->lock);
1890     return err;
1891 }
1892 EXPORT_SYMBOL_GPL(cec_s_log_addrs);
1893 
1894 /* High-level core CEC message handling */
1895 
1896 /* Fill in the Report Features message */
1897 static void cec_fill_msg_report_features(struct cec_adapter *adap,
1898                      struct cec_msg *msg,
1899                      unsigned int la_idx)
1900 {
1901     const struct cec_log_addrs *las = &adap->log_addrs;
1902     const u8 *features = las->features[la_idx];
1903     bool op_is_dev_features = false;
1904     unsigned int idx;
1905 
1906     /* Report Features */
1907     msg->msg[0] = (las->log_addr[la_idx] << 4) | 0x0f;
1908     msg->len = 4;
1909     msg->msg[1] = CEC_MSG_REPORT_FEATURES;
1910     msg->msg[2] = adap->log_addrs.cec_version;
1911     msg->msg[3] = las->all_device_types[la_idx];
1912 
1913     /* Write RC Profiles first, then Device Features */
1914     for (idx = 0; idx < ARRAY_SIZE(las->features[0]); idx++) {
1915         msg->msg[msg->len++] = features[idx];
1916         if ((features[idx] & CEC_OP_FEAT_EXT) == 0) {
1917             if (op_is_dev_features)
1918                 break;
1919             op_is_dev_features = true;
1920         }
1921     }
1922 }
1923 
1924 /* Transmit the Feature Abort message */
1925 static int cec_feature_abort_reason(struct cec_adapter *adap,
1926                     struct cec_msg *msg, u8 reason)
1927 {
1928     struct cec_msg tx_msg = { };
1929 
1930     /*
1931      * Don't reply with CEC_MSG_FEATURE_ABORT to a CEC_MSG_FEATURE_ABORT
1932      * message!
1933      */
1934     if (msg->msg[1] == CEC_MSG_FEATURE_ABORT)
1935         return 0;
1936     /* Don't Feature Abort messages from 'Unregistered' */
1937     if (cec_msg_initiator(msg) == CEC_LOG_ADDR_UNREGISTERED)
1938         return 0;
1939     cec_msg_set_reply_to(&tx_msg, msg);
1940     cec_msg_feature_abort(&tx_msg, msg->msg[1], reason);
1941     return cec_transmit_msg(adap, &tx_msg, false);
1942 }
1943 
1944 static int cec_feature_abort(struct cec_adapter *adap, struct cec_msg *msg)
1945 {
1946     return cec_feature_abort_reason(adap, msg,
1947                     CEC_OP_ABORT_UNRECOGNIZED_OP);
1948 }
1949 
1950 static int cec_feature_refused(struct cec_adapter *adap, struct cec_msg *msg)
1951 {
1952     return cec_feature_abort_reason(adap, msg,
1953                     CEC_OP_ABORT_REFUSED);
1954 }
1955 
1956 /*
1957  * Called when a CEC message is received. This function will do any
1958  * necessary core processing. The is_reply bool is true if this message
1959  * is a reply to an earlier transmit.
1960  *
1961  * The message is either a broadcast message or a valid directed message.
1962  */
1963 static int cec_receive_notify(struct cec_adapter *adap, struct cec_msg *msg,
1964                   bool is_reply)
1965 {
1966     bool is_broadcast = cec_msg_is_broadcast(msg);
1967     u8 dest_laddr = cec_msg_destination(msg);
1968     u8 init_laddr = cec_msg_initiator(msg);
1969     u8 devtype = cec_log_addr2dev(adap, dest_laddr);
1970     int la_idx = cec_log_addr2idx(adap, dest_laddr);
1971     bool from_unregistered = init_laddr == 0xf;
1972     struct cec_msg tx_cec_msg = { };
1973 
1974     dprintk(2, "%s: %*ph\n", __func__, msg->len, msg->msg);
1975 
1976     /* If this is a CDC-Only device, then ignore any non-CDC messages */
1977     if (cec_is_cdc_only(&adap->log_addrs) &&
1978         msg->msg[1] != CEC_MSG_CDC_MESSAGE)
1979         return 0;
1980 
1981     /* Allow drivers to process the message first */
1982     if (adap->ops->received && !adap->devnode.unregistered &&
1983         adap->ops->received(adap, msg) != -ENOMSG)
1984         return 0;
1985 
1986     /*
1987      * REPORT_PHYSICAL_ADDR, CEC_MSG_USER_CONTROL_PRESSED and
1988      * CEC_MSG_USER_CONTROL_RELEASED messages always have to be
1989      * handled by the CEC core, even if the passthrough mode is on.
1990      * The others are just ignored if passthrough mode is on.
1991      */
1992     switch (msg->msg[1]) {
1993     case CEC_MSG_GET_CEC_VERSION:
1994     case CEC_MSG_ABORT:
1995     case CEC_MSG_GIVE_DEVICE_POWER_STATUS:
1996     case CEC_MSG_GIVE_OSD_NAME:
1997         /*
1998          * These messages reply with a directed message, so ignore if
1999          * the initiator is Unregistered.
2000          */
2001         if (!adap->passthrough && from_unregistered)
2002             return 0;
2003         fallthrough;
2004     case CEC_MSG_GIVE_DEVICE_VENDOR_ID:
2005     case CEC_MSG_GIVE_FEATURES:
2006     case CEC_MSG_GIVE_PHYSICAL_ADDR:
2007         /*
2008          * Skip processing these messages if the passthrough mode
2009          * is on.
2010          */
2011         if (adap->passthrough)
2012             goto skip_processing;
2013         /* Ignore if addressing is wrong */
2014         if (is_broadcast)
2015             return 0;
2016         break;
2017 
2018     case CEC_MSG_USER_CONTROL_PRESSED:
2019     case CEC_MSG_USER_CONTROL_RELEASED:
2020         /* Wrong addressing mode: don't process */
2021         if (is_broadcast || from_unregistered)
2022             goto skip_processing;
2023         break;
2024 
2025     case CEC_MSG_REPORT_PHYSICAL_ADDR:
2026         /*
2027          * This message is always processed, regardless of the
2028          * passthrough setting.
2029          *
2030          * Exception: don't process if wrong addressing mode.
2031          */
2032         if (!is_broadcast)
2033             goto skip_processing;
2034         break;
2035 
2036     default:
2037         break;
2038     }
2039 
2040     cec_msg_set_reply_to(&tx_cec_msg, msg);
2041 
2042     switch (msg->msg[1]) {
2043     /* The following messages are processed but still passed through */
2044     case CEC_MSG_REPORT_PHYSICAL_ADDR: {
2045         u16 pa = (msg->msg[2] << 8) | msg->msg[3];
2046 
2047         dprintk(1, "reported physical address %x.%x.%x.%x for logical address %d\n",
2048             cec_phys_addr_exp(pa), init_laddr);
2049         break;
2050     }
2051 
2052     case CEC_MSG_USER_CONTROL_PRESSED:
2053         if (!(adap->capabilities & CEC_CAP_RC) ||
2054             !(adap->log_addrs.flags & CEC_LOG_ADDRS_FL_ALLOW_RC_PASSTHRU))
2055             break;
2056 
2057 #ifdef CONFIG_MEDIA_CEC_RC
2058         switch (msg->msg[2]) {
2059         /*
2060          * Play function, this message can have variable length
2061          * depending on the specific play function that is used.
2062          */
2063         case CEC_OP_UI_CMD_PLAY_FUNCTION:
2064             if (msg->len == 2)
2065                 rc_keydown(adap->rc, RC_PROTO_CEC,
2066                        msg->msg[2], 0);
2067             else
2068                 rc_keydown(adap->rc, RC_PROTO_CEC,
2069                        msg->msg[2] << 8 | msg->msg[3], 0);
2070             break;
2071         /*
2072          * Other function messages that are not handled.
2073          * Currently the RC framework does not allow to supply an
2074          * additional parameter to a keypress. These "keys" contain
2075          * other information such as channel number, an input number
2076          * etc.
2077          * For the time being these messages are not processed by the
2078          * framework and are simply forwarded to the user space.
2079          */
2080         case CEC_OP_UI_CMD_SELECT_BROADCAST_TYPE:
2081         case CEC_OP_UI_CMD_SELECT_SOUND_PRESENTATION:
2082         case CEC_OP_UI_CMD_TUNE_FUNCTION:
2083         case CEC_OP_UI_CMD_SELECT_MEDIA_FUNCTION:
2084         case CEC_OP_UI_CMD_SELECT_AV_INPUT_FUNCTION:
2085         case CEC_OP_UI_CMD_SELECT_AUDIO_INPUT_FUNCTION:
2086             break;
2087         default:
2088             rc_keydown(adap->rc, RC_PROTO_CEC, msg->msg[2], 0);
2089             break;
2090         }
2091 #endif
2092         break;
2093 
2094     case CEC_MSG_USER_CONTROL_RELEASED:
2095         if (!(adap->capabilities & CEC_CAP_RC) ||
2096             !(adap->log_addrs.flags & CEC_LOG_ADDRS_FL_ALLOW_RC_PASSTHRU))
2097             break;
2098 #ifdef CONFIG_MEDIA_CEC_RC
2099         rc_keyup(adap->rc);
2100 #endif
2101         break;
2102 
2103     /*
2104      * The remaining messages are only processed if the passthrough mode
2105      * is off.
2106      */
2107     case CEC_MSG_GET_CEC_VERSION:
2108         cec_msg_cec_version(&tx_cec_msg, adap->log_addrs.cec_version);
2109         return cec_transmit_msg(adap, &tx_cec_msg, false);
2110 
2111     case CEC_MSG_GIVE_PHYSICAL_ADDR:
2112         /* Do nothing for CEC switches using addr 15 */
2113         if (devtype == CEC_OP_PRIM_DEVTYPE_SWITCH && dest_laddr == 15)
2114             return 0;
2115         cec_msg_report_physical_addr(&tx_cec_msg, adap->phys_addr, devtype);
2116         return cec_transmit_msg(adap, &tx_cec_msg, false);
2117 
2118     case CEC_MSG_GIVE_DEVICE_VENDOR_ID:
2119         if (adap->log_addrs.vendor_id == CEC_VENDOR_ID_NONE)
2120             return cec_feature_abort(adap, msg);
2121         cec_msg_device_vendor_id(&tx_cec_msg, adap->log_addrs.vendor_id);
2122         return cec_transmit_msg(adap, &tx_cec_msg, false);
2123 
2124     case CEC_MSG_ABORT:
2125         /* Do nothing for CEC switches */
2126         if (devtype == CEC_OP_PRIM_DEVTYPE_SWITCH)
2127             return 0;
2128         return cec_feature_refused(adap, msg);
2129 
2130     case CEC_MSG_GIVE_OSD_NAME: {
2131         if (adap->log_addrs.osd_name[0] == 0)
2132             return cec_feature_abort(adap, msg);
2133         cec_msg_set_osd_name(&tx_cec_msg, adap->log_addrs.osd_name);
2134         return cec_transmit_msg(adap, &tx_cec_msg, false);
2135     }
2136 
2137     case CEC_MSG_GIVE_FEATURES:
2138         if (adap->log_addrs.cec_version < CEC_OP_CEC_VERSION_2_0)
2139             return cec_feature_abort(adap, msg);
2140         cec_fill_msg_report_features(adap, &tx_cec_msg, la_idx);
2141         return cec_transmit_msg(adap, &tx_cec_msg, false);
2142 
2143     default:
2144         /*
2145          * Unprocessed messages are aborted if userspace isn't doing
2146          * any processing either.
2147          */
2148         if (!is_broadcast && !is_reply && !adap->follower_cnt &&
2149             !adap->cec_follower && msg->msg[1] != CEC_MSG_FEATURE_ABORT)
2150             return cec_feature_abort(adap, msg);
2151         break;
2152     }
2153 
2154 skip_processing:
2155     /* If this was a reply, then we're done, unless otherwise specified */
2156     if (is_reply && !(msg->flags & CEC_MSG_FL_REPLY_TO_FOLLOWERS))
2157         return 0;
2158 
2159     /*
2160      * Send to the exclusive follower if there is one, otherwise send
2161      * to all followers.
2162      */
2163     if (adap->cec_follower)
2164         cec_queue_msg_fh(adap->cec_follower, msg);
2165     else
2166         cec_queue_msg_followers(adap, msg);
2167     return 0;
2168 }
2169 
2170 /*
2171  * Helper functions to keep track of the 'monitor all' use count.
2172  *
2173  * These functions are called with adap->lock held.
2174  */
2175 int cec_monitor_all_cnt_inc(struct cec_adapter *adap)
2176 {
2177     int ret;
2178 
2179     if (adap->monitor_all_cnt++)
2180         return 0;
2181 
2182     ret = cec_adap_enable(adap);
2183     if (ret)
2184         adap->monitor_all_cnt--;
2185     return ret;
2186 }
2187 
2188 void cec_monitor_all_cnt_dec(struct cec_adapter *adap)
2189 {
2190     if (WARN_ON(!adap->monitor_all_cnt))
2191         return;
2192     if (--adap->monitor_all_cnt)
2193         return;
2194     WARN_ON(call_op(adap, adap_monitor_all_enable, false));
2195     cec_adap_enable(adap);
2196 }
2197 
2198 /*
2199  * Helper functions to keep track of the 'monitor pin' use count.
2200  *
2201  * These functions are called with adap->lock held.
2202  */
2203 int cec_monitor_pin_cnt_inc(struct cec_adapter *adap)
2204 {
2205     int ret;
2206 
2207     if (adap->monitor_pin_cnt++)
2208         return 0;
2209 
2210     ret = cec_adap_enable(adap);
2211     if (ret)
2212         adap->monitor_pin_cnt--;
2213     return ret;
2214 }
2215 
2216 void cec_monitor_pin_cnt_dec(struct cec_adapter *adap)
2217 {
2218     if (WARN_ON(!adap->monitor_pin_cnt))
2219         return;
2220     if (--adap->monitor_pin_cnt)
2221         return;
2222     WARN_ON(call_op(adap, adap_monitor_pin_enable, false));
2223     cec_adap_enable(adap);
2224 }
2225 
2226 #ifdef CONFIG_DEBUG_FS
2227 /*
2228  * Log the current state of the CEC adapter.
2229  * Very useful for debugging.
2230  */
2231 int cec_adap_status(struct seq_file *file, void *priv)
2232 {
2233     struct cec_adapter *adap = dev_get_drvdata(file->private);
2234     struct cec_data *data;
2235 
2236     mutex_lock(&adap->lock);
2237     seq_printf(file, "enabled: %d\n", adap->is_enabled);
2238     seq_printf(file, "configured: %d\n", adap->is_configured);
2239     seq_printf(file, "configuring: %d\n", adap->is_configuring);
2240     seq_printf(file, "phys_addr: %x.%x.%x.%x\n",
2241            cec_phys_addr_exp(adap->phys_addr));
2242     seq_printf(file, "number of LAs: %d\n", adap->log_addrs.num_log_addrs);
2243     seq_printf(file, "LA mask: 0x%04x\n", adap->log_addrs.log_addr_mask);
2244     if (adap->cec_follower)
2245         seq_printf(file, "has CEC follower%s\n",
2246                adap->passthrough ? " (in passthrough mode)" : "");
2247     if (adap->cec_initiator)
2248         seq_puts(file, "has CEC initiator\n");
2249     if (adap->monitor_all_cnt)
2250         seq_printf(file, "file handles in Monitor All mode: %u\n",
2251                adap->monitor_all_cnt);
2252     if (adap->monitor_pin_cnt)
2253         seq_printf(file, "file handles in Monitor Pin mode: %u\n",
2254                adap->monitor_pin_cnt);
2255     if (adap->tx_timeouts) {
2256         seq_printf(file, "transmit timeouts: %u\n",
2257                adap->tx_timeouts);
2258         adap->tx_timeouts = 0;
2259     }
2260     data = adap->transmitting;
2261     if (data)
2262         seq_printf(file, "transmitting message: %*ph (reply: %02x, timeout: %ums)\n",
2263                data->msg.len, data->msg.msg, data->msg.reply,
2264                data->msg.timeout);
2265     seq_printf(file, "pending transmits: %u\n", adap->transmit_queue_sz);
2266     list_for_each_entry(data, &adap->transmit_queue, list) {
2267         seq_printf(file, "queued tx message: %*ph (reply: %02x, timeout: %ums)\n",
2268                data->msg.len, data->msg.msg, data->msg.reply,
2269                data->msg.timeout);
2270     }
2271     list_for_each_entry(data, &adap->wait_queue, list) {
2272         seq_printf(file, "message waiting for reply: %*ph (reply: %02x, timeout: %ums)\n",
2273                data->msg.len, data->msg.msg, data->msg.reply,
2274                data->msg.timeout);
2275     }
2276 
2277     call_void_op(adap, adap_status, file);
2278     mutex_unlock(&adap->lock);
2279     return 0;
2280 }
2281 #endif