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