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