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