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