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