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