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