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