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