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