xref: /linux/drivers/gpu/drm/vc4/vc4_hdmi.c (revision 90d32e92011eaae8e70a9169b4e7acf4ca8f9d3a)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2015 Broadcom
4  * Copyright (c) 2014 The Linux Foundation. All rights reserved.
5  * Copyright (C) 2013 Red Hat
6  * Author: Rob Clark <robdclark@gmail.com>
7  */
8 
9 /**
10  * DOC: VC4 Falcon HDMI module
11  *
12  * The HDMI core has a state machine and a PHY.  On BCM2835, most of
13  * the unit operates off of the HSM clock from CPRMAN.  It also
14  * internally uses the PLLH_PIX clock for the PHY.
15  *
16  * HDMI infoframes are kept within a small packet ram, where each
17  * packet can be individually enabled for including in a frame.
18  *
19  * HDMI audio is implemented entirely within the HDMI IP block.  A
20  * register in the HDMI encoder takes SPDIF frames from the DMA engine
21  * and transfers them over an internal MAI (multi-channel audio
22  * interconnect) bus to the encoder side for insertion into the video
23  * blank regions.
24  *
25  * The driver's HDMI encoder does not yet support power management.
26  * The HDMI encoder's power domain and the HSM/pixel clocks are kept
27  * continuously running, and only the HDMI logic and packet ram are
28  * powered off/on at disable/enable time.
29  *
30  * The driver does not yet support CEC control, though the HDMI
31  * encoder block has CEC support.
32  */
33 
34 #include <drm/display/drm_hdmi_helper.h>
35 #include <drm/display/drm_scdc_helper.h>
36 #include <drm/drm_atomic_helper.h>
37 #include <drm/drm_drv.h>
38 #include <drm/drm_edid.h>
39 #include <drm/drm_probe_helper.h>
40 #include <drm/drm_simple_kms_helper.h>
41 #include <linux/clk.h>
42 #include <linux/component.h>
43 #include <linux/gpio/consumer.h>
44 #include <linux/i2c.h>
45 #include <linux/of.h>
46 #include <linux/of_address.h>
47 #include <linux/pm_runtime.h>
48 #include <linux/rational.h>
49 #include <linux/reset.h>
50 #include <sound/dmaengine_pcm.h>
51 #include <sound/hdmi-codec.h>
52 #include <sound/pcm_drm_eld.h>
53 #include <sound/pcm_params.h>
54 #include <sound/soc.h>
55 #include "media/cec.h"
56 #include "vc4_drv.h"
57 #include "vc4_hdmi.h"
58 #include "vc4_hdmi_regs.h"
59 #include "vc4_regs.h"
60 
61 #define VC5_HDMI_HORZA_HFP_SHIFT		16
62 #define VC5_HDMI_HORZA_HFP_MASK			VC4_MASK(28, 16)
63 #define VC5_HDMI_HORZA_VPOS			BIT(15)
64 #define VC5_HDMI_HORZA_HPOS			BIT(14)
65 #define VC5_HDMI_HORZA_HAP_SHIFT		0
66 #define VC5_HDMI_HORZA_HAP_MASK			VC4_MASK(13, 0)
67 
68 #define VC5_HDMI_HORZB_HBP_SHIFT		16
69 #define VC5_HDMI_HORZB_HBP_MASK			VC4_MASK(26, 16)
70 #define VC5_HDMI_HORZB_HSP_SHIFT		0
71 #define VC5_HDMI_HORZB_HSP_MASK			VC4_MASK(10, 0)
72 
73 #define VC5_HDMI_VERTA_VSP_SHIFT		24
74 #define VC5_HDMI_VERTA_VSP_MASK			VC4_MASK(28, 24)
75 #define VC5_HDMI_VERTA_VFP_SHIFT		16
76 #define VC5_HDMI_VERTA_VFP_MASK			VC4_MASK(22, 16)
77 #define VC5_HDMI_VERTA_VAL_SHIFT		0
78 #define VC5_HDMI_VERTA_VAL_MASK			VC4_MASK(12, 0)
79 
80 #define VC5_HDMI_VERTB_VSPO_SHIFT		16
81 #define VC5_HDMI_VERTB_VSPO_MASK		VC4_MASK(29, 16)
82 
83 #define VC4_HDMI_MISC_CONTROL_PIXEL_REP_SHIFT	0
84 #define VC4_HDMI_MISC_CONTROL_PIXEL_REP_MASK	VC4_MASK(3, 0)
85 #define VC5_HDMI_MISC_CONTROL_PIXEL_REP_SHIFT	0
86 #define VC5_HDMI_MISC_CONTROL_PIXEL_REP_MASK	VC4_MASK(3, 0)
87 
88 #define VC5_HDMI_SCRAMBLER_CTL_ENABLE		BIT(0)
89 
90 #define VC5_HDMI_DEEP_COLOR_CONFIG_1_INIT_PACK_PHASE_SHIFT	8
91 #define VC5_HDMI_DEEP_COLOR_CONFIG_1_INIT_PACK_PHASE_MASK	VC4_MASK(10, 8)
92 
93 #define VC5_HDMI_DEEP_COLOR_CONFIG_1_COLOR_DEPTH_SHIFT		0
94 #define VC5_HDMI_DEEP_COLOR_CONFIG_1_COLOR_DEPTH_MASK		VC4_MASK(3, 0)
95 
96 #define VC5_HDMI_GCP_CONFIG_GCP_ENABLE		BIT(31)
97 
98 #define VC5_HDMI_GCP_WORD_1_GCP_SUBPACKET_BYTE_1_SHIFT	8
99 #define VC5_HDMI_GCP_WORD_1_GCP_SUBPACKET_BYTE_1_MASK	VC4_MASK(15, 8)
100 
101 #define VC5_HDMI_GCP_WORD_1_GCP_SUBPACKET_BYTE_0_MASK	VC4_MASK(7, 0)
102 #define VC5_HDMI_GCP_WORD_1_GCP_SUBPACKET_BYTE_0_SET_AVMUTE	BIT(0)
103 #define VC5_HDMI_GCP_WORD_1_GCP_SUBPACKET_BYTE_0_CLEAR_AVMUTE	BIT(4)
104 
105 # define VC4_HD_M_SW_RST			BIT(2)
106 # define VC4_HD_M_ENABLE			BIT(0)
107 
108 #define HSM_MIN_CLOCK_FREQ	120000000
109 #define CEC_CLOCK_FREQ 40000
110 
111 #define HDMI_14_MAX_TMDS_CLK   (340 * 1000 * 1000)
112 
113 static const char * const output_format_str[] = {
114 	[VC4_HDMI_OUTPUT_RGB]		= "RGB",
115 	[VC4_HDMI_OUTPUT_YUV420]	= "YUV 4:2:0",
116 	[VC4_HDMI_OUTPUT_YUV422]	= "YUV 4:2:2",
117 	[VC4_HDMI_OUTPUT_YUV444]	= "YUV 4:4:4",
118 };
119 
120 static const char *vc4_hdmi_output_fmt_str(enum vc4_hdmi_output_format fmt)
121 {
122 	if (fmt >= ARRAY_SIZE(output_format_str))
123 		return "invalid";
124 
125 	return output_format_str[fmt];
126 }
127 
128 static unsigned long long
129 vc4_hdmi_encoder_compute_mode_clock(const struct drm_display_mode *mode,
130 				    unsigned int bpc, enum vc4_hdmi_output_format fmt);
131 
132 static bool vc4_hdmi_supports_scrambling(struct vc4_hdmi *vc4_hdmi)
133 {
134 	struct drm_display_info *display = &vc4_hdmi->connector.display_info;
135 
136 	lockdep_assert_held(&vc4_hdmi->mutex);
137 
138 	if (!display->is_hdmi)
139 		return false;
140 
141 	if (!display->hdmi.scdc.supported ||
142 	    !display->hdmi.scdc.scrambling.supported)
143 		return false;
144 
145 	return true;
146 }
147 
148 static bool vc4_hdmi_mode_needs_scrambling(const struct drm_display_mode *mode,
149 					   unsigned int bpc,
150 					   enum vc4_hdmi_output_format fmt)
151 {
152 	unsigned long long clock = vc4_hdmi_encoder_compute_mode_clock(mode, bpc, fmt);
153 
154 	return clock > HDMI_14_MAX_TMDS_CLK;
155 }
156 
157 static bool vc4_hdmi_is_full_range(struct vc4_hdmi *vc4_hdmi,
158 				   struct vc4_hdmi_connector_state *vc4_state)
159 {
160 	const struct drm_display_mode *mode = &vc4_hdmi->saved_adjusted_mode;
161 	struct drm_display_info *display = &vc4_hdmi->connector.display_info;
162 
163 	if (vc4_state->broadcast_rgb == VC4_HDMI_BROADCAST_RGB_LIMITED)
164 		return false;
165 	else if (vc4_state->broadcast_rgb == VC4_HDMI_BROADCAST_RGB_FULL)
166 		return true;
167 
168 	return !display->is_hdmi ||
169 		drm_default_rgb_quant_range(mode) == HDMI_QUANTIZATION_RANGE_FULL;
170 }
171 
172 static int vc4_hdmi_debugfs_regs(struct seq_file *m, void *unused)
173 {
174 	struct drm_debugfs_entry *entry = m->private;
175 	struct vc4_hdmi *vc4_hdmi = entry->file.data;
176 	struct drm_device *drm = vc4_hdmi->connector.dev;
177 	struct drm_printer p = drm_seq_file_printer(m);
178 	int idx;
179 
180 	if (!drm_dev_enter(drm, &idx))
181 		return -ENODEV;
182 
183 	drm_print_regset32(&p, &vc4_hdmi->hdmi_regset);
184 	drm_print_regset32(&p, &vc4_hdmi->hd_regset);
185 	drm_print_regset32(&p, &vc4_hdmi->cec_regset);
186 	drm_print_regset32(&p, &vc4_hdmi->csc_regset);
187 	drm_print_regset32(&p, &vc4_hdmi->dvp_regset);
188 	drm_print_regset32(&p, &vc4_hdmi->phy_regset);
189 	drm_print_regset32(&p, &vc4_hdmi->ram_regset);
190 	drm_print_regset32(&p, &vc4_hdmi->rm_regset);
191 
192 	drm_dev_exit(idx);
193 
194 	return 0;
195 }
196 
197 static void vc4_hdmi_reset(struct vc4_hdmi *vc4_hdmi)
198 {
199 	struct drm_device *drm = vc4_hdmi->connector.dev;
200 	unsigned long flags;
201 	int idx;
202 
203 	/*
204 	 * We can be called by our bind callback, when the
205 	 * connector->dev pointer might not be initialised yet.
206 	 */
207 	if (drm && !drm_dev_enter(drm, &idx))
208 		return;
209 
210 	spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
211 
212 	HDMI_WRITE(HDMI_M_CTL, VC4_HD_M_SW_RST);
213 	udelay(1);
214 	HDMI_WRITE(HDMI_M_CTL, 0);
215 
216 	HDMI_WRITE(HDMI_M_CTL, VC4_HD_M_ENABLE);
217 
218 	HDMI_WRITE(HDMI_SW_RESET_CONTROL,
219 		   VC4_HDMI_SW_RESET_HDMI |
220 		   VC4_HDMI_SW_RESET_FORMAT_DETECT);
221 
222 	HDMI_WRITE(HDMI_SW_RESET_CONTROL, 0);
223 
224 	spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
225 
226 	if (drm)
227 		drm_dev_exit(idx);
228 }
229 
230 static void vc5_hdmi_reset(struct vc4_hdmi *vc4_hdmi)
231 {
232 	struct drm_device *drm = vc4_hdmi->connector.dev;
233 	unsigned long flags;
234 	int idx;
235 
236 	/*
237 	 * We can be called by our bind callback, when the
238 	 * connector->dev pointer might not be initialised yet.
239 	 */
240 	if (drm && !drm_dev_enter(drm, &idx))
241 		return;
242 
243 	reset_control_reset(vc4_hdmi->reset);
244 
245 	spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
246 
247 	HDMI_WRITE(HDMI_DVP_CTL, 0);
248 
249 	HDMI_WRITE(HDMI_CLOCK_STOP,
250 		   HDMI_READ(HDMI_CLOCK_STOP) | VC4_DVP_HT_CLOCK_STOP_PIXEL);
251 
252 	spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
253 
254 	if (drm)
255 		drm_dev_exit(idx);
256 }
257 
258 #ifdef CONFIG_DRM_VC4_HDMI_CEC
259 static void vc4_hdmi_cec_update_clk_div(struct vc4_hdmi *vc4_hdmi)
260 {
261 	struct drm_device *drm = vc4_hdmi->connector.dev;
262 	unsigned long cec_rate;
263 	unsigned long flags;
264 	u16 clk_cnt;
265 	u32 value;
266 	int idx;
267 
268 	/*
269 	 * This function is called by our runtime_resume implementation
270 	 * and thus at bind time, when we haven't registered our
271 	 * connector yet and thus don't have a pointer to the DRM
272 	 * device.
273 	 */
274 	if (drm && !drm_dev_enter(drm, &idx))
275 		return;
276 
277 	cec_rate = clk_get_rate(vc4_hdmi->cec_clock);
278 
279 	spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
280 
281 	value = HDMI_READ(HDMI_CEC_CNTRL_1);
282 	value &= ~VC4_HDMI_CEC_DIV_CLK_CNT_MASK;
283 
284 	/*
285 	 * Set the clock divider: the hsm_clock rate and this divider
286 	 * setting will give a 40 kHz CEC clock.
287 	 */
288 	clk_cnt = cec_rate / CEC_CLOCK_FREQ;
289 	value |= clk_cnt << VC4_HDMI_CEC_DIV_CLK_CNT_SHIFT;
290 	HDMI_WRITE(HDMI_CEC_CNTRL_1, value);
291 
292 	spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
293 
294 	if (drm)
295 		drm_dev_exit(idx);
296 }
297 #else
298 static void vc4_hdmi_cec_update_clk_div(struct vc4_hdmi *vc4_hdmi) {}
299 #endif
300 
301 static int reset_pipe(struct drm_crtc *crtc,
302 			struct drm_modeset_acquire_ctx *ctx)
303 {
304 	struct drm_atomic_state *state;
305 	struct drm_crtc_state *crtc_state;
306 	int ret;
307 
308 	state = drm_atomic_state_alloc(crtc->dev);
309 	if (!state)
310 		return -ENOMEM;
311 
312 	state->acquire_ctx = ctx;
313 
314 	crtc_state = drm_atomic_get_crtc_state(state, crtc);
315 	if (IS_ERR(crtc_state)) {
316 		ret = PTR_ERR(crtc_state);
317 		goto out;
318 	}
319 
320 	crtc_state->connectors_changed = true;
321 
322 	ret = drm_atomic_commit(state);
323 out:
324 	drm_atomic_state_put(state);
325 
326 	return ret;
327 }
328 
329 static int vc4_hdmi_reset_link(struct drm_connector *connector,
330 			       struct drm_modeset_acquire_ctx *ctx)
331 {
332 	struct drm_device *drm;
333 	struct vc4_hdmi *vc4_hdmi;
334 	struct drm_connector_state *conn_state;
335 	struct drm_crtc_state *crtc_state;
336 	struct drm_crtc *crtc;
337 	bool scrambling_needed;
338 	u8 config;
339 	int ret;
340 
341 	if (!connector)
342 		return 0;
343 
344 	drm = connector->dev;
345 	ret = drm_modeset_lock(&drm->mode_config.connection_mutex, ctx);
346 	if (ret)
347 		return ret;
348 
349 	conn_state = connector->state;
350 	crtc = conn_state->crtc;
351 	if (!crtc)
352 		return 0;
353 
354 	ret = drm_modeset_lock(&crtc->mutex, ctx);
355 	if (ret)
356 		return ret;
357 
358 	crtc_state = crtc->state;
359 	if (!crtc_state->active)
360 		return 0;
361 
362 	vc4_hdmi = connector_to_vc4_hdmi(connector);
363 	mutex_lock(&vc4_hdmi->mutex);
364 
365 	if (!vc4_hdmi_supports_scrambling(vc4_hdmi)) {
366 		mutex_unlock(&vc4_hdmi->mutex);
367 		return 0;
368 	}
369 
370 	scrambling_needed = vc4_hdmi_mode_needs_scrambling(&vc4_hdmi->saved_adjusted_mode,
371 							   vc4_hdmi->output_bpc,
372 							   vc4_hdmi->output_format);
373 	if (!scrambling_needed) {
374 		mutex_unlock(&vc4_hdmi->mutex);
375 		return 0;
376 	}
377 
378 	if (conn_state->commit &&
379 	    !try_wait_for_completion(&conn_state->commit->hw_done)) {
380 		mutex_unlock(&vc4_hdmi->mutex);
381 		return 0;
382 	}
383 
384 	ret = drm_scdc_readb(connector->ddc, SCDC_TMDS_CONFIG, &config);
385 	if (ret < 0) {
386 		drm_err(drm, "Failed to read TMDS config: %d\n", ret);
387 		mutex_unlock(&vc4_hdmi->mutex);
388 		return 0;
389 	}
390 
391 	if (!!(config & SCDC_SCRAMBLING_ENABLE) == scrambling_needed) {
392 		mutex_unlock(&vc4_hdmi->mutex);
393 		return 0;
394 	}
395 
396 	mutex_unlock(&vc4_hdmi->mutex);
397 
398 	/*
399 	 * HDMI 2.0 says that one should not send scrambled data
400 	 * prior to configuring the sink scrambling, and that
401 	 * TMDS clock/data transmission should be suspended when
402 	 * changing the TMDS clock rate in the sink. So let's
403 	 * just do a full modeset here, even though some sinks
404 	 * would be perfectly happy if were to just reconfigure
405 	 * the SCDC settings on the fly.
406 	 */
407 	return reset_pipe(crtc, ctx);
408 }
409 
410 static void vc4_hdmi_handle_hotplug(struct vc4_hdmi *vc4_hdmi,
411 				    struct drm_modeset_acquire_ctx *ctx,
412 				    enum drm_connector_status status)
413 {
414 	struct drm_connector *connector = &vc4_hdmi->connector;
415 	const struct drm_edid *drm_edid;
416 	int ret;
417 
418 	/*
419 	 * NOTE: This function should really be called with vc4_hdmi->mutex
420 	 * held, but doing so results in reentrancy issues since
421 	 * cec_s_phys_addr() might call .adap_enable, which leads to that
422 	 * funtion being called with our mutex held.
423 	 *
424 	 * A similar situation occurs with vc4_hdmi_reset_link() that
425 	 * will call into our KMS hooks if the scrambling was enabled.
426 	 *
427 	 * Concurrency isn't an issue at the moment since we don't share
428 	 * any state with any of the other frameworks so we can ignore
429 	 * the lock for now.
430 	 */
431 
432 	if (status == connector_status_disconnected) {
433 		cec_phys_addr_invalidate(vc4_hdmi->cec_adap);
434 		return;
435 	}
436 
437 	drm_edid = drm_edid_read_ddc(connector, vc4_hdmi->ddc);
438 
439 	drm_edid_connector_update(connector, drm_edid);
440 	cec_s_phys_addr(vc4_hdmi->cec_adap,
441 			connector->display_info.source_physical_address, false);
442 
443 	if (!drm_edid)
444 		return;
445 
446 	drm_edid_free(drm_edid);
447 
448 	for (;;) {
449 		ret = vc4_hdmi_reset_link(connector, ctx);
450 		if (ret == -EDEADLK) {
451 			drm_modeset_backoff(ctx);
452 			continue;
453 		}
454 
455 		break;
456 	}
457 }
458 
459 static int vc4_hdmi_connector_detect_ctx(struct drm_connector *connector,
460 					 struct drm_modeset_acquire_ctx *ctx,
461 					 bool force)
462 {
463 	struct vc4_hdmi *vc4_hdmi = connector_to_vc4_hdmi(connector);
464 	enum drm_connector_status status = connector_status_disconnected;
465 
466 	/*
467 	 * NOTE: This function should really take vc4_hdmi->mutex, but
468 	 * doing so results in reentrancy issues since
469 	 * vc4_hdmi_handle_hotplug() can call into other functions that
470 	 * would take the mutex while it's held here.
471 	 *
472 	 * Concurrency isn't an issue at the moment since we don't share
473 	 * any state with any of the other frameworks so we can ignore
474 	 * the lock for now.
475 	 */
476 
477 	WARN_ON(pm_runtime_resume_and_get(&vc4_hdmi->pdev->dev));
478 
479 	if (vc4_hdmi->hpd_gpio) {
480 		if (gpiod_get_value_cansleep(vc4_hdmi->hpd_gpio))
481 			status = connector_status_connected;
482 	} else {
483 		if (vc4_hdmi->variant->hp_detect &&
484 		    vc4_hdmi->variant->hp_detect(vc4_hdmi))
485 			status = connector_status_connected;
486 	}
487 
488 	vc4_hdmi_handle_hotplug(vc4_hdmi, ctx, status);
489 	pm_runtime_put(&vc4_hdmi->pdev->dev);
490 
491 	return status;
492 }
493 
494 static int vc4_hdmi_connector_get_modes(struct drm_connector *connector)
495 {
496 	struct vc4_hdmi *vc4_hdmi = connector_to_vc4_hdmi(connector);
497 	struct vc4_dev *vc4 = to_vc4_dev(connector->dev);
498 	const struct drm_edid *drm_edid;
499 	int ret = 0;
500 
501 	/*
502 	 * NOTE: This function should really take vc4_hdmi->mutex, but doing so
503 	 * results in reentrancy issues since cec_s_phys_addr() might call
504 	 * .adap_enable, which leads to that funtion being called with our mutex
505 	 * held.
506 	 *
507 	 * Concurrency isn't an issue at the moment since we don't share
508 	 * any state with any of the other frameworks so we can ignore
509 	 * the lock for now.
510 	 */
511 
512 	drm_edid = drm_edid_read_ddc(connector, vc4_hdmi->ddc);
513 	drm_edid_connector_update(connector, drm_edid);
514 	cec_s_phys_addr(vc4_hdmi->cec_adap,
515 			connector->display_info.source_physical_address, false);
516 	if (!drm_edid)
517 		return 0;
518 
519 	ret = drm_edid_connector_add_modes(connector);
520 	drm_edid_free(drm_edid);
521 
522 	if (!vc4->hvs->vc5_hdmi_enable_hdmi_20) {
523 		struct drm_device *drm = connector->dev;
524 		const struct drm_display_mode *mode;
525 
526 		list_for_each_entry(mode, &connector->probed_modes, head) {
527 			if (vc4_hdmi_mode_needs_scrambling(mode, 8, VC4_HDMI_OUTPUT_RGB)) {
528 				drm_warn_once(drm, "The core clock cannot reach frequencies high enough to support 4k @ 60Hz.");
529 				drm_warn_once(drm, "Please change your config.txt file to add hdmi_enable_4kp60.");
530 			}
531 		}
532 	}
533 
534 	return ret;
535 }
536 
537 static int vc4_hdmi_connector_atomic_check(struct drm_connector *connector,
538 					   struct drm_atomic_state *state)
539 {
540 	struct drm_connector_state *old_state =
541 		drm_atomic_get_old_connector_state(state, connector);
542 	struct vc4_hdmi_connector_state *old_vc4_state =
543 		conn_state_to_vc4_hdmi_conn_state(old_state);
544 	struct drm_connector_state *new_state =
545 		drm_atomic_get_new_connector_state(state, connector);
546 	struct vc4_hdmi_connector_state *new_vc4_state =
547 		conn_state_to_vc4_hdmi_conn_state(new_state);
548 	struct drm_crtc *crtc = new_state->crtc;
549 
550 	if (!crtc)
551 		return 0;
552 
553 	if (old_state->tv.margins.left != new_state->tv.margins.left ||
554 	    old_state->tv.margins.right != new_state->tv.margins.right ||
555 	    old_state->tv.margins.top != new_state->tv.margins.top ||
556 	    old_state->tv.margins.bottom != new_state->tv.margins.bottom) {
557 		struct drm_crtc_state *crtc_state;
558 		int ret;
559 
560 		crtc_state = drm_atomic_get_crtc_state(state, crtc);
561 		if (IS_ERR(crtc_state))
562 			return PTR_ERR(crtc_state);
563 
564 		/*
565 		 * Strictly speaking, we should be calling
566 		 * drm_atomic_helper_check_planes() after our call to
567 		 * drm_atomic_add_affected_planes(). However, the
568 		 * connector atomic_check is called as part of
569 		 * drm_atomic_helper_check_modeset() that already
570 		 * happens before a call to
571 		 * drm_atomic_helper_check_planes() in
572 		 * drm_atomic_helper_check().
573 		 */
574 		ret = drm_atomic_add_affected_planes(state, crtc);
575 		if (ret)
576 			return ret;
577 	}
578 
579 	if (old_state->colorspace != new_state->colorspace ||
580 	    old_vc4_state->broadcast_rgb != new_vc4_state->broadcast_rgb ||
581 	    !drm_connector_atomic_hdr_metadata_equal(old_state, new_state)) {
582 		struct drm_crtc_state *crtc_state;
583 
584 		crtc_state = drm_atomic_get_crtc_state(state, crtc);
585 		if (IS_ERR(crtc_state))
586 			return PTR_ERR(crtc_state);
587 
588 		crtc_state->mode_changed = true;
589 	}
590 
591 	return 0;
592 }
593 
594 static int vc4_hdmi_connector_get_property(struct drm_connector *connector,
595 					   const struct drm_connector_state *state,
596 					   struct drm_property *property,
597 					   uint64_t *val)
598 {
599 	struct drm_device *drm = connector->dev;
600 	struct vc4_hdmi *vc4_hdmi =
601 		connector_to_vc4_hdmi(connector);
602 	const struct vc4_hdmi_connector_state *vc4_conn_state =
603 		conn_state_to_vc4_hdmi_conn_state(state);
604 
605 	if (property == vc4_hdmi->broadcast_rgb_property) {
606 		*val = vc4_conn_state->broadcast_rgb;
607 	} else {
608 		drm_dbg(drm, "Unknown property [PROP:%d:%s]\n",
609 			property->base.id, property->name);
610 		return -EINVAL;
611 	}
612 
613 	return 0;
614 }
615 
616 static int vc4_hdmi_connector_set_property(struct drm_connector *connector,
617 					   struct drm_connector_state *state,
618 					   struct drm_property *property,
619 					   uint64_t val)
620 {
621 	struct drm_device *drm = connector->dev;
622 	struct vc4_hdmi *vc4_hdmi =
623 		connector_to_vc4_hdmi(connector);
624 	struct vc4_hdmi_connector_state *vc4_conn_state =
625 		conn_state_to_vc4_hdmi_conn_state(state);
626 
627 	if (property == vc4_hdmi->broadcast_rgb_property) {
628 		vc4_conn_state->broadcast_rgb = val;
629 		return 0;
630 	}
631 
632 	drm_dbg(drm, "Unknown property [PROP:%d:%s]\n",
633 		property->base.id, property->name);
634 	return -EINVAL;
635 }
636 
637 static void vc4_hdmi_connector_reset(struct drm_connector *connector)
638 {
639 	struct vc4_hdmi_connector_state *old_state =
640 		conn_state_to_vc4_hdmi_conn_state(connector->state);
641 	struct vc4_hdmi_connector_state *new_state =
642 		kzalloc(sizeof(*new_state), GFP_KERNEL);
643 
644 	if (connector->state)
645 		__drm_atomic_helper_connector_destroy_state(connector->state);
646 
647 	kfree(old_state);
648 	__drm_atomic_helper_connector_reset(connector, &new_state->base);
649 
650 	if (!new_state)
651 		return;
652 
653 	new_state->base.max_bpc = 8;
654 	new_state->base.max_requested_bpc = 8;
655 	new_state->output_format = VC4_HDMI_OUTPUT_RGB;
656 	new_state->broadcast_rgb = VC4_HDMI_BROADCAST_RGB_AUTO;
657 	drm_atomic_helper_connector_tv_margins_reset(connector);
658 }
659 
660 static struct drm_connector_state *
661 vc4_hdmi_connector_duplicate_state(struct drm_connector *connector)
662 {
663 	struct drm_connector_state *conn_state = connector->state;
664 	struct vc4_hdmi_connector_state *vc4_state = conn_state_to_vc4_hdmi_conn_state(conn_state);
665 	struct vc4_hdmi_connector_state *new_state;
666 
667 	new_state = kzalloc(sizeof(*new_state), GFP_KERNEL);
668 	if (!new_state)
669 		return NULL;
670 
671 	new_state->tmds_char_rate = vc4_state->tmds_char_rate;
672 	new_state->output_bpc = vc4_state->output_bpc;
673 	new_state->output_format = vc4_state->output_format;
674 	new_state->broadcast_rgb = vc4_state->broadcast_rgb;
675 	__drm_atomic_helper_connector_duplicate_state(connector, &new_state->base);
676 
677 	return &new_state->base;
678 }
679 
680 static void vc4_hdmi_connector_destroy_state(struct drm_connector *connector,
681 					     struct drm_connector_state *state)
682 {
683 	struct vc4_hdmi_connector_state *vc4_state =
684 		conn_state_to_vc4_hdmi_conn_state(state);
685 
686 	__drm_atomic_helper_connector_destroy_state(state);
687 	kfree(vc4_state);
688 }
689 
690 static const struct drm_connector_funcs vc4_hdmi_connector_funcs = {
691 	.fill_modes = drm_helper_probe_single_connector_modes,
692 	.reset = vc4_hdmi_connector_reset,
693 	.atomic_duplicate_state = vc4_hdmi_connector_duplicate_state,
694 	.atomic_destroy_state = vc4_hdmi_connector_destroy_state,
695 	.atomic_get_property = vc4_hdmi_connector_get_property,
696 	.atomic_set_property = vc4_hdmi_connector_set_property,
697 };
698 
699 static const struct drm_connector_helper_funcs vc4_hdmi_connector_helper_funcs = {
700 	.detect_ctx = vc4_hdmi_connector_detect_ctx,
701 	.get_modes = vc4_hdmi_connector_get_modes,
702 	.atomic_check = vc4_hdmi_connector_atomic_check,
703 };
704 
705 static const struct drm_prop_enum_list broadcast_rgb_names[] = {
706 	{ VC4_HDMI_BROADCAST_RGB_AUTO, "Automatic" },
707 	{ VC4_HDMI_BROADCAST_RGB_FULL, "Full" },
708 	{ VC4_HDMI_BROADCAST_RGB_LIMITED, "Limited 16:235" },
709 };
710 
711 static void
712 vc4_hdmi_attach_broadcast_rgb_property(struct drm_device *dev,
713 				       struct vc4_hdmi *vc4_hdmi)
714 {
715 	struct drm_property *prop = vc4_hdmi->broadcast_rgb_property;
716 
717 	if (!prop) {
718 		prop = drm_property_create_enum(dev, DRM_MODE_PROP_ENUM,
719 						"Broadcast RGB",
720 						broadcast_rgb_names,
721 						ARRAY_SIZE(broadcast_rgb_names));
722 		if (!prop)
723 			return;
724 
725 		vc4_hdmi->broadcast_rgb_property = prop;
726 	}
727 
728 	drm_object_attach_property(&vc4_hdmi->connector.base, prop,
729 				   VC4_HDMI_BROADCAST_RGB_AUTO);
730 }
731 
732 static int vc4_hdmi_connector_init(struct drm_device *dev,
733 				   struct vc4_hdmi *vc4_hdmi)
734 {
735 	struct drm_connector *connector = &vc4_hdmi->connector;
736 	struct drm_encoder *encoder = &vc4_hdmi->encoder.base;
737 	int ret;
738 
739 	ret = drmm_connector_init(dev, connector,
740 				  &vc4_hdmi_connector_funcs,
741 				  DRM_MODE_CONNECTOR_HDMIA,
742 				  vc4_hdmi->ddc);
743 	if (ret)
744 		return ret;
745 
746 	drm_connector_helper_add(connector, &vc4_hdmi_connector_helper_funcs);
747 
748 	/*
749 	 * Some of the properties below require access to state, like bpc.
750 	 * Allocate some default initial connector state with our reset helper.
751 	 */
752 	if (connector->funcs->reset)
753 		connector->funcs->reset(connector);
754 
755 	/* Create and attach TV margin props to this connector. */
756 	ret = drm_mode_create_tv_margin_properties(dev);
757 	if (ret)
758 		return ret;
759 
760 	ret = drm_mode_create_hdmi_colorspace_property(connector, 0);
761 	if (ret)
762 		return ret;
763 
764 	drm_connector_attach_colorspace_property(connector);
765 	drm_connector_attach_tv_margin_properties(connector);
766 	drm_connector_attach_max_bpc_property(connector, 8, 12);
767 
768 	connector->polled = (DRM_CONNECTOR_POLL_CONNECT |
769 			     DRM_CONNECTOR_POLL_DISCONNECT);
770 
771 	connector->interlace_allowed = 1;
772 	connector->doublescan_allowed = 0;
773 	connector->stereo_allowed = 1;
774 
775 	if (vc4_hdmi->variant->supports_hdr)
776 		drm_connector_attach_hdr_output_metadata_property(connector);
777 
778 	vc4_hdmi_attach_broadcast_rgb_property(dev, vc4_hdmi);
779 
780 	drm_connector_attach_encoder(connector, encoder);
781 
782 	return 0;
783 }
784 
785 static int vc4_hdmi_stop_packet(struct drm_encoder *encoder,
786 				enum hdmi_infoframe_type type,
787 				bool poll)
788 {
789 	struct vc4_hdmi *vc4_hdmi = encoder_to_vc4_hdmi(encoder);
790 	struct drm_device *drm = vc4_hdmi->connector.dev;
791 	u32 packet_id = type - 0x80;
792 	unsigned long flags;
793 	int ret = 0;
794 	int idx;
795 
796 	if (!drm_dev_enter(drm, &idx))
797 		return -ENODEV;
798 
799 	spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
800 	HDMI_WRITE(HDMI_RAM_PACKET_CONFIG,
801 		   HDMI_READ(HDMI_RAM_PACKET_CONFIG) & ~BIT(packet_id));
802 	spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
803 
804 	if (poll) {
805 		ret = wait_for(!(HDMI_READ(HDMI_RAM_PACKET_STATUS) &
806 				 BIT(packet_id)), 100);
807 	}
808 
809 	drm_dev_exit(idx);
810 	return ret;
811 }
812 
813 static void vc4_hdmi_write_infoframe(struct drm_encoder *encoder,
814 				     union hdmi_infoframe *frame)
815 {
816 	struct vc4_hdmi *vc4_hdmi = encoder_to_vc4_hdmi(encoder);
817 	struct drm_device *drm = vc4_hdmi->connector.dev;
818 	u32 packet_id = frame->any.type - 0x80;
819 	const struct vc4_hdmi_register *ram_packet_start =
820 		&vc4_hdmi->variant->registers[HDMI_RAM_PACKET_START];
821 	u32 packet_reg = ram_packet_start->offset + VC4_HDMI_PACKET_STRIDE * packet_id;
822 	u32 packet_reg_next = ram_packet_start->offset +
823 		VC4_HDMI_PACKET_STRIDE * (packet_id + 1);
824 	void __iomem *base = __vc4_hdmi_get_field_base(vc4_hdmi,
825 						       ram_packet_start->reg);
826 	uint8_t buffer[VC4_HDMI_PACKET_STRIDE] = {};
827 	unsigned long flags;
828 	ssize_t len, i;
829 	int ret;
830 	int idx;
831 
832 	if (!drm_dev_enter(drm, &idx))
833 		return;
834 
835 	WARN_ONCE(!(HDMI_READ(HDMI_RAM_PACKET_CONFIG) &
836 		    VC4_HDMI_RAM_PACKET_ENABLE),
837 		  "Packet RAM has to be on to store the packet.");
838 
839 	len = hdmi_infoframe_pack(frame, buffer, sizeof(buffer));
840 	if (len < 0)
841 		goto out;
842 
843 	ret = vc4_hdmi_stop_packet(encoder, frame->any.type, true);
844 	if (ret) {
845 		DRM_ERROR("Failed to wait for infoframe to go idle: %d\n", ret);
846 		goto out;
847 	}
848 
849 	spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
850 
851 	for (i = 0; i < len; i += 7) {
852 		writel(buffer[i + 0] << 0 |
853 		       buffer[i + 1] << 8 |
854 		       buffer[i + 2] << 16,
855 		       base + packet_reg);
856 		packet_reg += 4;
857 
858 		writel(buffer[i + 3] << 0 |
859 		       buffer[i + 4] << 8 |
860 		       buffer[i + 5] << 16 |
861 		       buffer[i + 6] << 24,
862 		       base + packet_reg);
863 		packet_reg += 4;
864 	}
865 
866 	/*
867 	 * clear remainder of packet ram as it's included in the
868 	 * infoframe and triggers a checksum error on hdmi analyser
869 	 */
870 	for (; packet_reg < packet_reg_next; packet_reg += 4)
871 		writel(0, base + packet_reg);
872 
873 	HDMI_WRITE(HDMI_RAM_PACKET_CONFIG,
874 		   HDMI_READ(HDMI_RAM_PACKET_CONFIG) | BIT(packet_id));
875 
876 	spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
877 
878 	ret = wait_for((HDMI_READ(HDMI_RAM_PACKET_STATUS) &
879 			BIT(packet_id)), 100);
880 	if (ret)
881 		DRM_ERROR("Failed to wait for infoframe to start: %d\n", ret);
882 
883 out:
884 	drm_dev_exit(idx);
885 }
886 
887 static void vc4_hdmi_avi_infoframe_colorspace(struct hdmi_avi_infoframe *frame,
888 					      enum vc4_hdmi_output_format fmt)
889 {
890 	switch (fmt) {
891 	case VC4_HDMI_OUTPUT_RGB:
892 		frame->colorspace = HDMI_COLORSPACE_RGB;
893 		break;
894 
895 	case VC4_HDMI_OUTPUT_YUV420:
896 		frame->colorspace = HDMI_COLORSPACE_YUV420;
897 		break;
898 
899 	case VC4_HDMI_OUTPUT_YUV422:
900 		frame->colorspace = HDMI_COLORSPACE_YUV422;
901 		break;
902 
903 	case VC4_HDMI_OUTPUT_YUV444:
904 		frame->colorspace = HDMI_COLORSPACE_YUV444;
905 		break;
906 
907 	default:
908 		break;
909 	}
910 }
911 
912 static void vc4_hdmi_set_avi_infoframe(struct drm_encoder *encoder)
913 {
914 	struct vc4_hdmi *vc4_hdmi = encoder_to_vc4_hdmi(encoder);
915 	struct drm_connector *connector = &vc4_hdmi->connector;
916 	struct drm_connector_state *cstate = connector->state;
917 	struct vc4_hdmi_connector_state *vc4_state =
918 		conn_state_to_vc4_hdmi_conn_state(cstate);
919 	const struct drm_display_mode *mode = &vc4_hdmi->saved_adjusted_mode;
920 	union hdmi_infoframe frame;
921 	int ret;
922 
923 	lockdep_assert_held(&vc4_hdmi->mutex);
924 
925 	ret = drm_hdmi_avi_infoframe_from_display_mode(&frame.avi,
926 						       connector, mode);
927 	if (ret < 0) {
928 		DRM_ERROR("couldn't fill AVI infoframe\n");
929 		return;
930 	}
931 
932 	drm_hdmi_avi_infoframe_quant_range(&frame.avi,
933 					   connector, mode,
934 					   vc4_hdmi_is_full_range(vc4_hdmi, vc4_state) ?
935 					   HDMI_QUANTIZATION_RANGE_FULL :
936 					   HDMI_QUANTIZATION_RANGE_LIMITED);
937 	drm_hdmi_avi_infoframe_colorimetry(&frame.avi, cstate);
938 	vc4_hdmi_avi_infoframe_colorspace(&frame.avi, vc4_state->output_format);
939 	drm_hdmi_avi_infoframe_bars(&frame.avi, cstate);
940 
941 	vc4_hdmi_write_infoframe(encoder, &frame);
942 }
943 
944 static void vc4_hdmi_set_spd_infoframe(struct drm_encoder *encoder)
945 {
946 	union hdmi_infoframe frame;
947 	int ret;
948 
949 	ret = hdmi_spd_infoframe_init(&frame.spd, "Broadcom", "Videocore");
950 	if (ret < 0) {
951 		DRM_ERROR("couldn't fill SPD infoframe\n");
952 		return;
953 	}
954 
955 	frame.spd.sdi = HDMI_SPD_SDI_PC;
956 
957 	vc4_hdmi_write_infoframe(encoder, &frame);
958 }
959 
960 static void vc4_hdmi_set_audio_infoframe(struct drm_encoder *encoder)
961 {
962 	struct vc4_hdmi *vc4_hdmi = encoder_to_vc4_hdmi(encoder);
963 	struct hdmi_audio_infoframe *audio = &vc4_hdmi->audio.infoframe;
964 	union hdmi_infoframe frame;
965 
966 	memcpy(&frame.audio, audio, sizeof(*audio));
967 
968 	if (vc4_hdmi->packet_ram_enabled)
969 		vc4_hdmi_write_infoframe(encoder, &frame);
970 }
971 
972 static void vc4_hdmi_set_hdr_infoframe(struct drm_encoder *encoder)
973 {
974 	struct vc4_hdmi *vc4_hdmi = encoder_to_vc4_hdmi(encoder);
975 	struct drm_connector *connector = &vc4_hdmi->connector;
976 	struct drm_connector_state *conn_state = connector->state;
977 	union hdmi_infoframe frame;
978 
979 	lockdep_assert_held(&vc4_hdmi->mutex);
980 
981 	if (!vc4_hdmi->variant->supports_hdr)
982 		return;
983 
984 	if (!conn_state->hdr_output_metadata)
985 		return;
986 
987 	if (drm_hdmi_infoframe_set_hdr_metadata(&frame.drm, conn_state))
988 		return;
989 
990 	vc4_hdmi_write_infoframe(encoder, &frame);
991 }
992 
993 static void vc4_hdmi_set_infoframes(struct drm_encoder *encoder)
994 {
995 	struct vc4_hdmi *vc4_hdmi = encoder_to_vc4_hdmi(encoder);
996 
997 	lockdep_assert_held(&vc4_hdmi->mutex);
998 
999 	vc4_hdmi_set_avi_infoframe(encoder);
1000 	vc4_hdmi_set_spd_infoframe(encoder);
1001 	/*
1002 	 * If audio was streaming, then we need to reenabled the audio
1003 	 * infoframe here during encoder_enable.
1004 	 */
1005 	if (vc4_hdmi->audio.streaming)
1006 		vc4_hdmi_set_audio_infoframe(encoder);
1007 
1008 	vc4_hdmi_set_hdr_infoframe(encoder);
1009 }
1010 
1011 #define SCRAMBLING_POLLING_DELAY_MS	1000
1012 
1013 static void vc4_hdmi_enable_scrambling(struct drm_encoder *encoder)
1014 {
1015 	struct vc4_hdmi *vc4_hdmi = encoder_to_vc4_hdmi(encoder);
1016 	struct drm_connector *connector = &vc4_hdmi->connector;
1017 	struct drm_device *drm = connector->dev;
1018 	const struct drm_display_mode *mode = &vc4_hdmi->saved_adjusted_mode;
1019 	unsigned long flags;
1020 	int idx;
1021 
1022 	lockdep_assert_held(&vc4_hdmi->mutex);
1023 
1024 	if (!vc4_hdmi_supports_scrambling(vc4_hdmi))
1025 		return;
1026 
1027 	if (!vc4_hdmi_mode_needs_scrambling(mode,
1028 					    vc4_hdmi->output_bpc,
1029 					    vc4_hdmi->output_format))
1030 		return;
1031 
1032 	if (!drm_dev_enter(drm, &idx))
1033 		return;
1034 
1035 	drm_scdc_set_high_tmds_clock_ratio(connector, true);
1036 	drm_scdc_set_scrambling(connector, true);
1037 
1038 	spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
1039 	HDMI_WRITE(HDMI_SCRAMBLER_CTL, HDMI_READ(HDMI_SCRAMBLER_CTL) |
1040 		   VC5_HDMI_SCRAMBLER_CTL_ENABLE);
1041 	spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
1042 
1043 	drm_dev_exit(idx);
1044 
1045 	vc4_hdmi->scdc_enabled = true;
1046 
1047 	queue_delayed_work(system_wq, &vc4_hdmi->scrambling_work,
1048 			   msecs_to_jiffies(SCRAMBLING_POLLING_DELAY_MS));
1049 }
1050 
1051 static void vc4_hdmi_disable_scrambling(struct drm_encoder *encoder)
1052 {
1053 	struct vc4_hdmi *vc4_hdmi = encoder_to_vc4_hdmi(encoder);
1054 	struct drm_connector *connector = &vc4_hdmi->connector;
1055 	struct drm_device *drm = connector->dev;
1056 	unsigned long flags;
1057 	int idx;
1058 
1059 	lockdep_assert_held(&vc4_hdmi->mutex);
1060 
1061 	if (!vc4_hdmi->scdc_enabled)
1062 		return;
1063 
1064 	vc4_hdmi->scdc_enabled = false;
1065 
1066 	if (delayed_work_pending(&vc4_hdmi->scrambling_work))
1067 		cancel_delayed_work_sync(&vc4_hdmi->scrambling_work);
1068 
1069 	if (!drm_dev_enter(drm, &idx))
1070 		return;
1071 
1072 	spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
1073 	HDMI_WRITE(HDMI_SCRAMBLER_CTL, HDMI_READ(HDMI_SCRAMBLER_CTL) &
1074 		   ~VC5_HDMI_SCRAMBLER_CTL_ENABLE);
1075 	spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
1076 
1077 	drm_scdc_set_scrambling(connector, false);
1078 	drm_scdc_set_high_tmds_clock_ratio(connector, false);
1079 
1080 	drm_dev_exit(idx);
1081 }
1082 
1083 static void vc4_hdmi_scrambling_wq(struct work_struct *work)
1084 {
1085 	struct vc4_hdmi *vc4_hdmi = container_of(to_delayed_work(work),
1086 						 struct vc4_hdmi,
1087 						 scrambling_work);
1088 	struct drm_connector *connector = &vc4_hdmi->connector;
1089 
1090 	if (drm_scdc_get_scrambling_status(connector))
1091 		return;
1092 
1093 	drm_scdc_set_high_tmds_clock_ratio(connector, true);
1094 	drm_scdc_set_scrambling(connector, true);
1095 
1096 	queue_delayed_work(system_wq, &vc4_hdmi->scrambling_work,
1097 			   msecs_to_jiffies(SCRAMBLING_POLLING_DELAY_MS));
1098 }
1099 
1100 static void vc4_hdmi_encoder_post_crtc_disable(struct drm_encoder *encoder,
1101 					       struct drm_atomic_state *state)
1102 {
1103 	struct vc4_hdmi *vc4_hdmi = encoder_to_vc4_hdmi(encoder);
1104 	struct drm_device *drm = vc4_hdmi->connector.dev;
1105 	unsigned long flags;
1106 	int idx;
1107 
1108 	mutex_lock(&vc4_hdmi->mutex);
1109 
1110 	vc4_hdmi->packet_ram_enabled = false;
1111 
1112 	if (!drm_dev_enter(drm, &idx))
1113 		goto out;
1114 
1115 	spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
1116 
1117 	HDMI_WRITE(HDMI_RAM_PACKET_CONFIG, 0);
1118 
1119 	HDMI_WRITE(HDMI_VID_CTL, HDMI_READ(HDMI_VID_CTL) | VC4_HD_VID_CTL_CLRRGB);
1120 
1121 	spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
1122 
1123 	mdelay(1);
1124 
1125 	spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
1126 	HDMI_WRITE(HDMI_VID_CTL,
1127 		   HDMI_READ(HDMI_VID_CTL) & ~VC4_HD_VID_CTL_ENABLE);
1128 	spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
1129 
1130 	vc4_hdmi_disable_scrambling(encoder);
1131 
1132 	drm_dev_exit(idx);
1133 
1134 out:
1135 	mutex_unlock(&vc4_hdmi->mutex);
1136 }
1137 
1138 static void vc4_hdmi_encoder_post_crtc_powerdown(struct drm_encoder *encoder,
1139 						 struct drm_atomic_state *state)
1140 {
1141 	struct vc4_hdmi *vc4_hdmi = encoder_to_vc4_hdmi(encoder);
1142 	struct drm_device *drm = vc4_hdmi->connector.dev;
1143 	unsigned long flags;
1144 	int ret;
1145 	int idx;
1146 
1147 	mutex_lock(&vc4_hdmi->mutex);
1148 
1149 	if (!drm_dev_enter(drm, &idx))
1150 		goto out;
1151 
1152 	spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
1153 	HDMI_WRITE(HDMI_VID_CTL,
1154 		   HDMI_READ(HDMI_VID_CTL) | VC4_HD_VID_CTL_BLANKPIX);
1155 	spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
1156 
1157 	if (vc4_hdmi->variant->phy_disable)
1158 		vc4_hdmi->variant->phy_disable(vc4_hdmi);
1159 
1160 	clk_disable_unprepare(vc4_hdmi->pixel_bvb_clock);
1161 	clk_disable_unprepare(vc4_hdmi->pixel_clock);
1162 
1163 	ret = pm_runtime_put(&vc4_hdmi->pdev->dev);
1164 	if (ret < 0)
1165 		DRM_ERROR("Failed to release power domain: %d\n", ret);
1166 
1167 	drm_dev_exit(idx);
1168 
1169 out:
1170 	mutex_unlock(&vc4_hdmi->mutex);
1171 }
1172 
1173 static void vc4_hdmi_csc_setup(struct vc4_hdmi *vc4_hdmi,
1174 			       struct drm_connector_state *state,
1175 			       const struct drm_display_mode *mode)
1176 {
1177 	struct vc4_hdmi_connector_state *vc4_state =
1178 		conn_state_to_vc4_hdmi_conn_state(state);
1179 	struct drm_device *drm = vc4_hdmi->connector.dev;
1180 	unsigned long flags;
1181 	u32 csc_ctl;
1182 	int idx;
1183 
1184 	if (!drm_dev_enter(drm, &idx))
1185 		return;
1186 
1187 	spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
1188 
1189 	csc_ctl = VC4_SET_FIELD(VC4_HD_CSC_CTL_ORDER_BGR,
1190 				VC4_HD_CSC_CTL_ORDER);
1191 
1192 	if (!vc4_hdmi_is_full_range(vc4_hdmi, vc4_state)) {
1193 		/* CEA VICs other than #1 requre limited range RGB
1194 		 * output unless overridden by an AVI infoframe.
1195 		 * Apply a colorspace conversion to squash 0-255 down
1196 		 * to 16-235.  The matrix here is:
1197 		 *
1198 		 * [ 0      0      0.8594 16]
1199 		 * [ 0      0.8594 0      16]
1200 		 * [ 0.8594 0      0      16]
1201 		 * [ 0      0      0       1]
1202 		 */
1203 		csc_ctl |= VC4_HD_CSC_CTL_ENABLE;
1204 		csc_ctl |= VC4_HD_CSC_CTL_RGB2YCC;
1205 		csc_ctl |= VC4_SET_FIELD(VC4_HD_CSC_CTL_MODE_CUSTOM,
1206 					 VC4_HD_CSC_CTL_MODE);
1207 
1208 		HDMI_WRITE(HDMI_CSC_12_11, (0x000 << 16) | 0x000);
1209 		HDMI_WRITE(HDMI_CSC_14_13, (0x100 << 16) | 0x6e0);
1210 		HDMI_WRITE(HDMI_CSC_22_21, (0x6e0 << 16) | 0x000);
1211 		HDMI_WRITE(HDMI_CSC_24_23, (0x100 << 16) | 0x000);
1212 		HDMI_WRITE(HDMI_CSC_32_31, (0x000 << 16) | 0x6e0);
1213 		HDMI_WRITE(HDMI_CSC_34_33, (0x100 << 16) | 0x000);
1214 	}
1215 
1216 	/* The RGB order applies even when CSC is disabled. */
1217 	HDMI_WRITE(HDMI_CSC_CTL, csc_ctl);
1218 
1219 	spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
1220 
1221 	drm_dev_exit(idx);
1222 }
1223 
1224 /*
1225  * Matrices for (internal) RGB to RGB output.
1226  *
1227  * Matrices are signed 2p13 fixed point, with signed 9p6 offsets
1228  */
1229 static const u16 vc5_hdmi_csc_full_rgb_to_rgb[2][3][4] = {
1230 	{
1231 		/*
1232 		 * Full range - unity
1233 		 *
1234 		 * [ 1      0      0      0]
1235 		 * [ 0      1      0      0]
1236 		 * [ 0      0      1      0]
1237 		 */
1238 		{ 0x2000, 0x0000, 0x0000, 0x0000 },
1239 		{ 0x0000, 0x2000, 0x0000, 0x0000 },
1240 		{ 0x0000, 0x0000, 0x2000, 0x0000 },
1241 	},
1242 	{
1243 		/*
1244 		 * Limited range
1245 		 *
1246 		 * CEA VICs other than #1 require limited range RGB
1247 		 * output unless overridden by an AVI infoframe. Apply a
1248 		 * colorspace conversion to squash 0-255 down to 16-235.
1249 		 * The matrix here is:
1250 		 *
1251 		 * [ 0.8594 0      0      16]
1252 		 * [ 0      0.8594 0      16]
1253 		 * [ 0      0      0.8594 16]
1254 		 */
1255 		{ 0x1b80, 0x0000, 0x0000, 0x0400 },
1256 		{ 0x0000, 0x1b80, 0x0000, 0x0400 },
1257 		{ 0x0000, 0x0000, 0x1b80, 0x0400 },
1258 	},
1259 };
1260 
1261 /*
1262  * Conversion between Full Range RGB and YUV using the BT.601 Colorspace
1263  *
1264  * Matrices are signed 2p13 fixed point, with signed 9p6 offsets
1265  */
1266 static const u16 vc5_hdmi_csc_full_rgb_to_yuv_bt601[2][3][4] = {
1267 	{
1268 		/*
1269 		 * Full Range
1270 		 *
1271 		 * [  0.299000  0.587000  0.114000  0   ]
1272 		 * [ -0.168736 -0.331264  0.500000  128 ]
1273 		 * [  0.500000 -0.418688 -0.081312  128 ]
1274 		 */
1275 		{ 0x0991, 0x12c9, 0x03a6, 0x0000 },
1276 		{ 0xfa9b, 0xf567, 0x1000, 0x2000 },
1277 		{ 0x1000, 0xf29b, 0xfd67, 0x2000 },
1278 	},
1279 	{
1280 		/* Limited Range
1281 		 *
1282 		 * [  0.255785  0.502160  0.097523  16  ]
1283 		 * [ -0.147644 -0.289856  0.437500  128 ]
1284 		 * [  0.437500 -0.366352 -0.071148  128 ]
1285 		 */
1286 		{ 0x082f, 0x1012, 0x031f, 0x0400 },
1287 		{ 0xfb48, 0xf6ba, 0x0e00, 0x2000 },
1288 		{ 0x0e00, 0xf448, 0xfdba, 0x2000 },
1289 	},
1290 };
1291 
1292 /*
1293  * Conversion between Full Range RGB and YUV using the BT.709 Colorspace
1294  *
1295  * Matrices are signed 2p13 fixed point, with signed 9p6 offsets
1296  */
1297 static const u16 vc5_hdmi_csc_full_rgb_to_yuv_bt709[2][3][4] = {
1298 	{
1299 		/*
1300 		 * Full Range
1301 		 *
1302 		 * [  0.212600  0.715200  0.072200  0   ]
1303 		 * [ -0.114572 -0.385428  0.500000  128 ]
1304 		 * [  0.500000 -0.454153 -0.045847  128 ]
1305 		 */
1306 		{ 0x06ce, 0x16e3, 0x024f, 0x0000 },
1307 		{ 0xfc56, 0xf3ac, 0x1000, 0x2000 },
1308 		{ 0x1000, 0xf179, 0xfe89, 0x2000 },
1309 	},
1310 	{
1311 		/*
1312 		 * Limited Range
1313 		 *
1314 		 * [  0.181906  0.611804  0.061758  16  ]
1315 		 * [ -0.100268 -0.337232  0.437500  128 ]
1316 		 * [  0.437500 -0.397386 -0.040114  128 ]
1317 		 */
1318 		{ 0x05d2, 0x1394, 0x01fa, 0x0400 },
1319 		{ 0xfccc, 0xf536, 0x0e00, 0x2000 },
1320 		{ 0x0e00, 0xf34a, 0xfeb8, 0x2000 },
1321 	},
1322 };
1323 
1324 /*
1325  * Conversion between Full Range RGB and YUV using the BT.2020 Colorspace
1326  *
1327  * Matrices are signed 2p13 fixed point, with signed 9p6 offsets
1328  */
1329 static const u16 vc5_hdmi_csc_full_rgb_to_yuv_bt2020[2][3][4] = {
1330 	{
1331 		/*
1332 		 * Full Range
1333 		 *
1334 		 * [  0.262700  0.678000  0.059300  0   ]
1335 		 * [ -0.139630 -0.360370  0.500000  128 ]
1336 		 * [  0.500000 -0.459786 -0.040214  128 ]
1337 		 */
1338 		{ 0x0868, 0x15b2, 0x01e6, 0x0000 },
1339 		{ 0xfb89, 0xf479, 0x1000, 0x2000 },
1340 		{ 0x1000, 0xf14a, 0xfeb8, 0x2000 },
1341 	},
1342 	{
1343 		/* Limited Range
1344 		 *
1345 		 * [  0.224732  0.580008  0.050729  16  ]
1346 		 * [ -0.122176 -0.315324  0.437500  128 ]
1347 		 * [  0.437500 -0.402312 -0.035188  128 ]
1348 		 */
1349 		{ 0x082f, 0x1012, 0x031f, 0x0400 },
1350 		{ 0xfb48, 0xf6ba, 0x0e00, 0x2000 },
1351 		{ 0x0e00, 0xf448, 0xfdba, 0x2000 },
1352 	},
1353 };
1354 
1355 static void vc5_hdmi_set_csc_coeffs(struct vc4_hdmi *vc4_hdmi,
1356 				    const u16 coeffs[3][4])
1357 {
1358 	lockdep_assert_held(&vc4_hdmi->hw_lock);
1359 
1360 	HDMI_WRITE(HDMI_CSC_12_11, (coeffs[0][1] << 16) | coeffs[0][0]);
1361 	HDMI_WRITE(HDMI_CSC_14_13, (coeffs[0][3] << 16) | coeffs[0][2]);
1362 	HDMI_WRITE(HDMI_CSC_22_21, (coeffs[1][1] << 16) | coeffs[1][0]);
1363 	HDMI_WRITE(HDMI_CSC_24_23, (coeffs[1][3] << 16) | coeffs[1][2]);
1364 	HDMI_WRITE(HDMI_CSC_32_31, (coeffs[2][1] << 16) | coeffs[2][0]);
1365 	HDMI_WRITE(HDMI_CSC_34_33, (coeffs[2][3] << 16) | coeffs[2][2]);
1366 }
1367 
1368 static void vc5_hdmi_set_csc_coeffs_swap(struct vc4_hdmi *vc4_hdmi,
1369 					 const u16 coeffs[3][4])
1370 {
1371 	lockdep_assert_held(&vc4_hdmi->hw_lock);
1372 
1373 	/* YUV444 needs the CSC matrices using the channels in a different order */
1374 	HDMI_WRITE(HDMI_CSC_12_11, (coeffs[1][1] << 16) | coeffs[1][0]);
1375 	HDMI_WRITE(HDMI_CSC_14_13, (coeffs[1][3] << 16) | coeffs[1][2]);
1376 	HDMI_WRITE(HDMI_CSC_22_21, (coeffs[2][1] << 16) | coeffs[2][0]);
1377 	HDMI_WRITE(HDMI_CSC_24_23, (coeffs[2][3] << 16) | coeffs[2][2]);
1378 	HDMI_WRITE(HDMI_CSC_32_31, (coeffs[0][1] << 16) | coeffs[0][0]);
1379 	HDMI_WRITE(HDMI_CSC_34_33, (coeffs[0][3] << 16) | coeffs[0][2]);
1380 }
1381 
1382 static const u16
1383 (*vc5_hdmi_find_yuv_csc_coeffs(struct vc4_hdmi *vc4_hdmi, u32 colorspace, bool limited))[4]
1384 {
1385 	switch (colorspace) {
1386 	case DRM_MODE_COLORIMETRY_SMPTE_170M_YCC:
1387 	case DRM_MODE_COLORIMETRY_XVYCC_601:
1388 	case DRM_MODE_COLORIMETRY_SYCC_601:
1389 	case DRM_MODE_COLORIMETRY_OPYCC_601:
1390 	case DRM_MODE_COLORIMETRY_BT601_YCC:
1391 		return vc5_hdmi_csc_full_rgb_to_yuv_bt601[limited];
1392 
1393 	default:
1394 	case DRM_MODE_COLORIMETRY_NO_DATA:
1395 	case DRM_MODE_COLORIMETRY_BT709_YCC:
1396 	case DRM_MODE_COLORIMETRY_XVYCC_709:
1397 	case DRM_MODE_COLORIMETRY_RGB_WIDE_FIXED:
1398 	case DRM_MODE_COLORIMETRY_RGB_WIDE_FLOAT:
1399 		return vc5_hdmi_csc_full_rgb_to_yuv_bt709[limited];
1400 
1401 	case DRM_MODE_COLORIMETRY_BT2020_CYCC:
1402 	case DRM_MODE_COLORIMETRY_BT2020_YCC:
1403 	case DRM_MODE_COLORIMETRY_BT2020_RGB:
1404 	case DRM_MODE_COLORIMETRY_DCI_P3_RGB_D65:
1405 	case DRM_MODE_COLORIMETRY_DCI_P3_RGB_THEATER:
1406 		return vc5_hdmi_csc_full_rgb_to_yuv_bt2020[limited];
1407 	}
1408 }
1409 
1410 static void vc5_hdmi_csc_setup(struct vc4_hdmi *vc4_hdmi,
1411 			       struct drm_connector_state *state,
1412 			       const struct drm_display_mode *mode)
1413 {
1414 	struct drm_device *drm = vc4_hdmi->connector.dev;
1415 	struct vc4_hdmi_connector_state *vc4_state =
1416 		conn_state_to_vc4_hdmi_conn_state(state);
1417 	unsigned int lim_range = vc4_hdmi_is_full_range(vc4_hdmi, vc4_state) ? 0 : 1;
1418 	unsigned long flags;
1419 	const u16 (*csc)[4];
1420 	u32 if_cfg = 0;
1421 	u32 if_xbar = 0x543210;
1422 	u32 csc_chan_ctl = 0;
1423 	u32 csc_ctl = VC5_MT_CP_CSC_CTL_ENABLE | VC4_SET_FIELD(VC4_HD_CSC_CTL_MODE_CUSTOM,
1424 							       VC5_MT_CP_CSC_CTL_MODE);
1425 	int idx;
1426 
1427 	if (!drm_dev_enter(drm, &idx))
1428 		return;
1429 
1430 	spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
1431 
1432 	switch (vc4_state->output_format) {
1433 	case VC4_HDMI_OUTPUT_YUV444:
1434 		csc = vc5_hdmi_find_yuv_csc_coeffs(vc4_hdmi, state->colorspace, !!lim_range);
1435 
1436 		vc5_hdmi_set_csc_coeffs_swap(vc4_hdmi, csc);
1437 		break;
1438 
1439 	case VC4_HDMI_OUTPUT_YUV422:
1440 		csc = vc5_hdmi_find_yuv_csc_coeffs(vc4_hdmi, state->colorspace, !!lim_range);
1441 
1442 		csc_ctl |= VC4_SET_FIELD(VC5_MT_CP_CSC_CTL_FILTER_MODE_444_TO_422_STANDARD,
1443 					 VC5_MT_CP_CSC_CTL_FILTER_MODE_444_TO_422) |
1444 			VC5_MT_CP_CSC_CTL_USE_444_TO_422 |
1445 			VC5_MT_CP_CSC_CTL_USE_RNG_SUPPRESSION;
1446 
1447 		csc_chan_ctl |= VC4_SET_FIELD(VC5_MT_CP_CHANNEL_CTL_OUTPUT_REMAP_LEGACY_STYLE,
1448 					      VC5_MT_CP_CHANNEL_CTL_OUTPUT_REMAP);
1449 
1450 		if_cfg |= VC4_SET_FIELD(VC5_DVP_HT_VEC_INTERFACE_CFG_SEL_422_FORMAT_422_LEGACY,
1451 					VC5_DVP_HT_VEC_INTERFACE_CFG_SEL_422);
1452 
1453 		vc5_hdmi_set_csc_coeffs(vc4_hdmi, csc);
1454 		break;
1455 
1456 	case VC4_HDMI_OUTPUT_RGB:
1457 		if_xbar = 0x354021;
1458 
1459 		vc5_hdmi_set_csc_coeffs(vc4_hdmi, vc5_hdmi_csc_full_rgb_to_rgb[lim_range]);
1460 		break;
1461 
1462 	default:
1463 		break;
1464 	}
1465 
1466 	HDMI_WRITE(HDMI_VEC_INTERFACE_CFG, if_cfg);
1467 	HDMI_WRITE(HDMI_VEC_INTERFACE_XBAR, if_xbar);
1468 	HDMI_WRITE(HDMI_CSC_CHANNEL_CTL, csc_chan_ctl);
1469 	HDMI_WRITE(HDMI_CSC_CTL, csc_ctl);
1470 
1471 	spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
1472 
1473 	drm_dev_exit(idx);
1474 }
1475 
1476 static void vc4_hdmi_set_timings(struct vc4_hdmi *vc4_hdmi,
1477 				 struct drm_connector_state *state,
1478 				 const struct drm_display_mode *mode)
1479 {
1480 	struct drm_device *drm = vc4_hdmi->connector.dev;
1481 	bool hsync_pos = mode->flags & DRM_MODE_FLAG_PHSYNC;
1482 	bool vsync_pos = mode->flags & DRM_MODE_FLAG_PVSYNC;
1483 	bool interlaced = mode->flags & DRM_MODE_FLAG_INTERLACE;
1484 	u32 pixel_rep = (mode->flags & DRM_MODE_FLAG_DBLCLK) ? 2 : 1;
1485 	u32 verta = (VC4_SET_FIELD(mode->crtc_vsync_end - mode->crtc_vsync_start,
1486 				   VC4_HDMI_VERTA_VSP) |
1487 		     VC4_SET_FIELD(mode->crtc_vsync_start - mode->crtc_vdisplay,
1488 				   VC4_HDMI_VERTA_VFP) |
1489 		     VC4_SET_FIELD(mode->crtc_vdisplay, VC4_HDMI_VERTA_VAL));
1490 	u32 vertb = (VC4_SET_FIELD(0, VC4_HDMI_VERTB_VSPO) |
1491 		     VC4_SET_FIELD(mode->crtc_vtotal - mode->crtc_vsync_end +
1492 				   interlaced,
1493 				   VC4_HDMI_VERTB_VBP));
1494 	u32 vertb_even = (VC4_SET_FIELD(0, VC4_HDMI_VERTB_VSPO) |
1495 			  VC4_SET_FIELD(mode->crtc_vtotal -
1496 					mode->crtc_vsync_end,
1497 					VC4_HDMI_VERTB_VBP));
1498 	unsigned long flags;
1499 	u32 reg;
1500 	int idx;
1501 
1502 	if (!drm_dev_enter(drm, &idx))
1503 		return;
1504 
1505 	spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
1506 
1507 	HDMI_WRITE(HDMI_HORZA,
1508 		   (vsync_pos ? VC4_HDMI_HORZA_VPOS : 0) |
1509 		   (hsync_pos ? VC4_HDMI_HORZA_HPOS : 0) |
1510 		   VC4_SET_FIELD(mode->hdisplay * pixel_rep,
1511 				 VC4_HDMI_HORZA_HAP));
1512 
1513 	HDMI_WRITE(HDMI_HORZB,
1514 		   VC4_SET_FIELD((mode->htotal -
1515 				  mode->hsync_end) * pixel_rep,
1516 				 VC4_HDMI_HORZB_HBP) |
1517 		   VC4_SET_FIELD((mode->hsync_end -
1518 				  mode->hsync_start) * pixel_rep,
1519 				 VC4_HDMI_HORZB_HSP) |
1520 		   VC4_SET_FIELD((mode->hsync_start -
1521 				  mode->hdisplay) * pixel_rep,
1522 				 VC4_HDMI_HORZB_HFP));
1523 
1524 	HDMI_WRITE(HDMI_VERTA0, verta);
1525 	HDMI_WRITE(HDMI_VERTA1, verta);
1526 
1527 	HDMI_WRITE(HDMI_VERTB0, vertb_even);
1528 	HDMI_WRITE(HDMI_VERTB1, vertb);
1529 
1530 	reg = HDMI_READ(HDMI_MISC_CONTROL);
1531 	reg &= ~VC4_HDMI_MISC_CONTROL_PIXEL_REP_MASK;
1532 	reg |= VC4_SET_FIELD(pixel_rep - 1, VC4_HDMI_MISC_CONTROL_PIXEL_REP);
1533 	HDMI_WRITE(HDMI_MISC_CONTROL, reg);
1534 
1535 	spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
1536 
1537 	drm_dev_exit(idx);
1538 }
1539 
1540 static void vc5_hdmi_set_timings(struct vc4_hdmi *vc4_hdmi,
1541 				 struct drm_connector_state *state,
1542 				 const struct drm_display_mode *mode)
1543 {
1544 	struct drm_device *drm = vc4_hdmi->connector.dev;
1545 	const struct vc4_hdmi_connector_state *vc4_state =
1546 		conn_state_to_vc4_hdmi_conn_state(state);
1547 	bool hsync_pos = mode->flags & DRM_MODE_FLAG_PHSYNC;
1548 	bool vsync_pos = mode->flags & DRM_MODE_FLAG_PVSYNC;
1549 	bool interlaced = mode->flags & DRM_MODE_FLAG_INTERLACE;
1550 	u32 pixel_rep = (mode->flags & DRM_MODE_FLAG_DBLCLK) ? 2 : 1;
1551 	u32 verta = (VC4_SET_FIELD(mode->crtc_vsync_end - mode->crtc_vsync_start,
1552 				   VC5_HDMI_VERTA_VSP) |
1553 		     VC4_SET_FIELD(mode->crtc_vsync_start - mode->crtc_vdisplay,
1554 				   VC5_HDMI_VERTA_VFP) |
1555 		     VC4_SET_FIELD(mode->crtc_vdisplay, VC5_HDMI_VERTA_VAL));
1556 	u32 vertb = (VC4_SET_FIELD(mode->htotal >> (2 - pixel_rep),
1557 				   VC5_HDMI_VERTB_VSPO) |
1558 		     VC4_SET_FIELD(mode->crtc_vtotal - mode->crtc_vsync_end +
1559 				   interlaced,
1560 				   VC4_HDMI_VERTB_VBP));
1561 	u32 vertb_even = (VC4_SET_FIELD(0, VC5_HDMI_VERTB_VSPO) |
1562 			  VC4_SET_FIELD(mode->crtc_vtotal -
1563 					mode->crtc_vsync_end,
1564 					VC4_HDMI_VERTB_VBP));
1565 	unsigned long flags;
1566 	unsigned char gcp;
1567 	u32 reg;
1568 	int idx;
1569 
1570 	if (!drm_dev_enter(drm, &idx))
1571 		return;
1572 
1573 	spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
1574 
1575 	HDMI_WRITE(HDMI_HORZA,
1576 		   (vsync_pos ? VC5_HDMI_HORZA_VPOS : 0) |
1577 		   (hsync_pos ? VC5_HDMI_HORZA_HPOS : 0) |
1578 		   VC4_SET_FIELD(mode->hdisplay * pixel_rep,
1579 				 VC5_HDMI_HORZA_HAP) |
1580 		   VC4_SET_FIELD((mode->hsync_start -
1581 				  mode->hdisplay) * pixel_rep,
1582 				 VC5_HDMI_HORZA_HFP));
1583 
1584 	HDMI_WRITE(HDMI_HORZB,
1585 		   VC4_SET_FIELD((mode->htotal -
1586 				  mode->hsync_end) * pixel_rep,
1587 				 VC5_HDMI_HORZB_HBP) |
1588 		   VC4_SET_FIELD((mode->hsync_end -
1589 				  mode->hsync_start) * pixel_rep,
1590 				 VC5_HDMI_HORZB_HSP));
1591 
1592 	HDMI_WRITE(HDMI_VERTA0, verta);
1593 	HDMI_WRITE(HDMI_VERTA1, verta);
1594 
1595 	HDMI_WRITE(HDMI_VERTB0, vertb_even);
1596 	HDMI_WRITE(HDMI_VERTB1, vertb);
1597 
1598 	switch (vc4_state->output_bpc) {
1599 	case 12:
1600 		gcp = 6;
1601 		break;
1602 	case 10:
1603 		gcp = 5;
1604 		break;
1605 	case 8:
1606 	default:
1607 		gcp = 0;
1608 		break;
1609 	}
1610 
1611 	/*
1612 	 * YCC422 is always 36-bit and not considered deep colour so
1613 	 * doesn't signal in GCP.
1614 	 */
1615 	if (vc4_state->output_format == VC4_HDMI_OUTPUT_YUV422) {
1616 		gcp = 0;
1617 	}
1618 
1619 	reg = HDMI_READ(HDMI_DEEP_COLOR_CONFIG_1);
1620 	reg &= ~(VC5_HDMI_DEEP_COLOR_CONFIG_1_INIT_PACK_PHASE_MASK |
1621 		 VC5_HDMI_DEEP_COLOR_CONFIG_1_COLOR_DEPTH_MASK);
1622 	reg |= VC4_SET_FIELD(2, VC5_HDMI_DEEP_COLOR_CONFIG_1_INIT_PACK_PHASE) |
1623 	       VC4_SET_FIELD(gcp, VC5_HDMI_DEEP_COLOR_CONFIG_1_COLOR_DEPTH);
1624 	HDMI_WRITE(HDMI_DEEP_COLOR_CONFIG_1, reg);
1625 
1626 	reg = HDMI_READ(HDMI_GCP_WORD_1);
1627 	reg &= ~VC5_HDMI_GCP_WORD_1_GCP_SUBPACKET_BYTE_1_MASK;
1628 	reg |= VC4_SET_FIELD(gcp, VC5_HDMI_GCP_WORD_1_GCP_SUBPACKET_BYTE_1);
1629 	reg &= ~VC5_HDMI_GCP_WORD_1_GCP_SUBPACKET_BYTE_0_MASK;
1630 	reg |= VC5_HDMI_GCP_WORD_1_GCP_SUBPACKET_BYTE_0_CLEAR_AVMUTE;
1631 	HDMI_WRITE(HDMI_GCP_WORD_1, reg);
1632 
1633 	reg = HDMI_READ(HDMI_GCP_CONFIG);
1634 	reg |= VC5_HDMI_GCP_CONFIG_GCP_ENABLE;
1635 	HDMI_WRITE(HDMI_GCP_CONFIG, reg);
1636 
1637 	reg = HDMI_READ(HDMI_MISC_CONTROL);
1638 	reg &= ~VC5_HDMI_MISC_CONTROL_PIXEL_REP_MASK;
1639 	reg |= VC4_SET_FIELD(pixel_rep - 1, VC5_HDMI_MISC_CONTROL_PIXEL_REP);
1640 	HDMI_WRITE(HDMI_MISC_CONTROL, reg);
1641 
1642 	HDMI_WRITE(HDMI_CLOCK_STOP, 0);
1643 
1644 	spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
1645 
1646 	drm_dev_exit(idx);
1647 }
1648 
1649 static void vc4_hdmi_recenter_fifo(struct vc4_hdmi *vc4_hdmi)
1650 {
1651 	struct drm_device *drm = vc4_hdmi->connector.dev;
1652 	unsigned long flags;
1653 	u32 drift;
1654 	int ret;
1655 	int idx;
1656 
1657 	if (!drm_dev_enter(drm, &idx))
1658 		return;
1659 
1660 	spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
1661 
1662 	drift = HDMI_READ(HDMI_FIFO_CTL);
1663 	drift &= VC4_HDMI_FIFO_VALID_WRITE_MASK;
1664 
1665 	HDMI_WRITE(HDMI_FIFO_CTL,
1666 		   drift & ~VC4_HDMI_FIFO_CTL_RECENTER);
1667 	HDMI_WRITE(HDMI_FIFO_CTL,
1668 		   drift | VC4_HDMI_FIFO_CTL_RECENTER);
1669 
1670 	spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
1671 
1672 	usleep_range(1000, 1100);
1673 
1674 	spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
1675 
1676 	HDMI_WRITE(HDMI_FIFO_CTL,
1677 		   drift & ~VC4_HDMI_FIFO_CTL_RECENTER);
1678 	HDMI_WRITE(HDMI_FIFO_CTL,
1679 		   drift | VC4_HDMI_FIFO_CTL_RECENTER);
1680 
1681 	spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
1682 
1683 	ret = wait_for(HDMI_READ(HDMI_FIFO_CTL) &
1684 		       VC4_HDMI_FIFO_CTL_RECENTER_DONE, 1);
1685 	WARN_ONCE(ret, "Timeout waiting for "
1686 		  "VC4_HDMI_FIFO_CTL_RECENTER_DONE");
1687 
1688 	drm_dev_exit(idx);
1689 }
1690 
1691 static void vc4_hdmi_encoder_pre_crtc_configure(struct drm_encoder *encoder,
1692 						struct drm_atomic_state *state)
1693 {
1694 	struct vc4_hdmi *vc4_hdmi = encoder_to_vc4_hdmi(encoder);
1695 	struct drm_device *drm = vc4_hdmi->connector.dev;
1696 	struct drm_connector *connector = &vc4_hdmi->connector;
1697 	struct drm_connector_state *conn_state =
1698 		drm_atomic_get_new_connector_state(state, connector);
1699 	struct vc4_hdmi_connector_state *vc4_conn_state =
1700 		conn_state_to_vc4_hdmi_conn_state(conn_state);
1701 	const struct drm_display_mode *mode = &vc4_hdmi->saved_adjusted_mode;
1702 	unsigned long tmds_char_rate = vc4_conn_state->tmds_char_rate;
1703 	unsigned long bvb_rate, hsm_rate;
1704 	unsigned long flags;
1705 	int ret;
1706 	int idx;
1707 
1708 	mutex_lock(&vc4_hdmi->mutex);
1709 
1710 	if (!drm_dev_enter(drm, &idx))
1711 		goto out;
1712 
1713 	ret = pm_runtime_resume_and_get(&vc4_hdmi->pdev->dev);
1714 	if (ret < 0) {
1715 		DRM_ERROR("Failed to retain power domain: %d\n", ret);
1716 		goto err_dev_exit;
1717 	}
1718 
1719 	/*
1720 	 * As stated in RPi's vc4 firmware "HDMI state machine (HSM) clock must
1721 	 * be faster than pixel clock, infinitesimally faster, tested in
1722 	 * simulation. Otherwise, exact value is unimportant for HDMI
1723 	 * operation." This conflicts with bcm2835's vc4 documentation, which
1724 	 * states HSM's clock has to be at least 108% of the pixel clock.
1725 	 *
1726 	 * Real life tests reveal that vc4's firmware statement holds up, and
1727 	 * users are able to use pixel clocks closer to HSM's, namely for
1728 	 * 1920x1200@60Hz. So it was decided to have leave a 1% margin between
1729 	 * both clocks. Which, for RPi0-3 implies a maximum pixel clock of
1730 	 * 162MHz.
1731 	 *
1732 	 * Additionally, the AXI clock needs to be at least 25% of
1733 	 * pixel clock, but HSM ends up being the limiting factor.
1734 	 */
1735 	hsm_rate = max_t(unsigned long,
1736 			 HSM_MIN_CLOCK_FREQ,
1737 			 (tmds_char_rate / 100) * 101);
1738 	ret = clk_set_min_rate(vc4_hdmi->hsm_clock, hsm_rate);
1739 	if (ret) {
1740 		DRM_ERROR("Failed to set HSM clock rate: %d\n", ret);
1741 		goto err_put_runtime_pm;
1742 	}
1743 
1744 	ret = clk_set_rate(vc4_hdmi->pixel_clock, tmds_char_rate);
1745 	if (ret) {
1746 		DRM_ERROR("Failed to set pixel clock rate: %d\n", ret);
1747 		goto err_put_runtime_pm;
1748 	}
1749 
1750 	ret = clk_prepare_enable(vc4_hdmi->pixel_clock);
1751 	if (ret) {
1752 		DRM_ERROR("Failed to turn on pixel clock: %d\n", ret);
1753 		goto err_put_runtime_pm;
1754 	}
1755 
1756 
1757 	vc4_hdmi_cec_update_clk_div(vc4_hdmi);
1758 
1759 	if (tmds_char_rate > 297000000)
1760 		bvb_rate = 300000000;
1761 	else if (tmds_char_rate > 148500000)
1762 		bvb_rate = 150000000;
1763 	else
1764 		bvb_rate = 75000000;
1765 
1766 	ret = clk_set_min_rate(vc4_hdmi->pixel_bvb_clock, bvb_rate);
1767 	if (ret) {
1768 		DRM_ERROR("Failed to set pixel bvb clock rate: %d\n", ret);
1769 		goto err_disable_pixel_clock;
1770 	}
1771 
1772 	ret = clk_prepare_enable(vc4_hdmi->pixel_bvb_clock);
1773 	if (ret) {
1774 		DRM_ERROR("Failed to turn on pixel bvb clock: %d\n", ret);
1775 		goto err_disable_pixel_clock;
1776 	}
1777 
1778 	if (vc4_hdmi->variant->phy_init)
1779 		vc4_hdmi->variant->phy_init(vc4_hdmi, vc4_conn_state);
1780 
1781 	spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
1782 
1783 	HDMI_WRITE(HDMI_SCHEDULER_CONTROL,
1784 		   HDMI_READ(HDMI_SCHEDULER_CONTROL) |
1785 		   VC4_HDMI_SCHEDULER_CONTROL_MANUAL_FORMAT |
1786 		   VC4_HDMI_SCHEDULER_CONTROL_IGNORE_VSYNC_PREDICTS);
1787 
1788 	spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
1789 
1790 	if (vc4_hdmi->variant->set_timings)
1791 		vc4_hdmi->variant->set_timings(vc4_hdmi, conn_state, mode);
1792 
1793 	drm_dev_exit(idx);
1794 
1795 	mutex_unlock(&vc4_hdmi->mutex);
1796 
1797 	return;
1798 
1799 err_disable_pixel_clock:
1800 	clk_disable_unprepare(vc4_hdmi->pixel_clock);
1801 err_put_runtime_pm:
1802 	pm_runtime_put(&vc4_hdmi->pdev->dev);
1803 err_dev_exit:
1804 	drm_dev_exit(idx);
1805 out:
1806 	mutex_unlock(&vc4_hdmi->mutex);
1807 	return;
1808 }
1809 
1810 static void vc4_hdmi_encoder_pre_crtc_enable(struct drm_encoder *encoder,
1811 					     struct drm_atomic_state *state)
1812 {
1813 	struct vc4_hdmi *vc4_hdmi = encoder_to_vc4_hdmi(encoder);
1814 	struct drm_device *drm = vc4_hdmi->connector.dev;
1815 	struct drm_connector *connector = &vc4_hdmi->connector;
1816 	const struct drm_display_mode *mode = &vc4_hdmi->saved_adjusted_mode;
1817 	struct drm_connector_state *conn_state =
1818 		drm_atomic_get_new_connector_state(state, connector);
1819 	unsigned long flags;
1820 	int idx;
1821 
1822 	mutex_lock(&vc4_hdmi->mutex);
1823 
1824 	if (!drm_dev_enter(drm, &idx))
1825 		goto out;
1826 
1827 	if (vc4_hdmi->variant->csc_setup)
1828 		vc4_hdmi->variant->csc_setup(vc4_hdmi, conn_state, mode);
1829 
1830 	spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
1831 	HDMI_WRITE(HDMI_FIFO_CTL, VC4_HDMI_FIFO_CTL_MASTER_SLAVE_N);
1832 	spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
1833 
1834 	drm_dev_exit(idx);
1835 
1836 out:
1837 	mutex_unlock(&vc4_hdmi->mutex);
1838 }
1839 
1840 static void vc4_hdmi_encoder_post_crtc_enable(struct drm_encoder *encoder,
1841 					      struct drm_atomic_state *state)
1842 {
1843 	struct vc4_hdmi *vc4_hdmi = encoder_to_vc4_hdmi(encoder);
1844 	struct drm_device *drm = vc4_hdmi->connector.dev;
1845 	const struct drm_display_mode *mode = &vc4_hdmi->saved_adjusted_mode;
1846 	struct drm_display_info *display = &vc4_hdmi->connector.display_info;
1847 	bool hsync_pos = mode->flags & DRM_MODE_FLAG_PHSYNC;
1848 	bool vsync_pos = mode->flags & DRM_MODE_FLAG_PVSYNC;
1849 	unsigned long flags;
1850 	int ret;
1851 	int idx;
1852 
1853 	mutex_lock(&vc4_hdmi->mutex);
1854 
1855 	if (!drm_dev_enter(drm, &idx))
1856 		goto out;
1857 
1858 	spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
1859 
1860 	HDMI_WRITE(HDMI_VID_CTL,
1861 		   VC4_HD_VID_CTL_ENABLE |
1862 		   VC4_HD_VID_CTL_CLRRGB |
1863 		   VC4_HD_VID_CTL_UNDERFLOW_ENABLE |
1864 		   VC4_HD_VID_CTL_FRAME_COUNTER_RESET |
1865 		   (vsync_pos ? 0 : VC4_HD_VID_CTL_VSYNC_LOW) |
1866 		   (hsync_pos ? 0 : VC4_HD_VID_CTL_HSYNC_LOW));
1867 
1868 	HDMI_WRITE(HDMI_VID_CTL,
1869 		   HDMI_READ(HDMI_VID_CTL) & ~VC4_HD_VID_CTL_BLANKPIX);
1870 
1871 	if (display->is_hdmi) {
1872 		HDMI_WRITE(HDMI_SCHEDULER_CONTROL,
1873 			   HDMI_READ(HDMI_SCHEDULER_CONTROL) |
1874 			   VC4_HDMI_SCHEDULER_CONTROL_MODE_HDMI);
1875 
1876 		spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
1877 
1878 		ret = wait_for(HDMI_READ(HDMI_SCHEDULER_CONTROL) &
1879 			       VC4_HDMI_SCHEDULER_CONTROL_HDMI_ACTIVE, 1000);
1880 		WARN_ONCE(ret, "Timeout waiting for "
1881 			  "VC4_HDMI_SCHEDULER_CONTROL_HDMI_ACTIVE\n");
1882 	} else {
1883 		HDMI_WRITE(HDMI_RAM_PACKET_CONFIG,
1884 			   HDMI_READ(HDMI_RAM_PACKET_CONFIG) &
1885 			   ~(VC4_HDMI_RAM_PACKET_ENABLE));
1886 		HDMI_WRITE(HDMI_SCHEDULER_CONTROL,
1887 			   HDMI_READ(HDMI_SCHEDULER_CONTROL) &
1888 			   ~VC4_HDMI_SCHEDULER_CONTROL_MODE_HDMI);
1889 
1890 		spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
1891 
1892 		ret = wait_for(!(HDMI_READ(HDMI_SCHEDULER_CONTROL) &
1893 				 VC4_HDMI_SCHEDULER_CONTROL_HDMI_ACTIVE), 1000);
1894 		WARN_ONCE(ret, "Timeout waiting for "
1895 			  "!VC4_HDMI_SCHEDULER_CONTROL_HDMI_ACTIVE\n");
1896 	}
1897 
1898 	if (display->is_hdmi) {
1899 		spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
1900 
1901 		WARN_ON(!(HDMI_READ(HDMI_SCHEDULER_CONTROL) &
1902 			  VC4_HDMI_SCHEDULER_CONTROL_HDMI_ACTIVE));
1903 
1904 		HDMI_WRITE(HDMI_RAM_PACKET_CONFIG,
1905 			   VC4_HDMI_RAM_PACKET_ENABLE);
1906 
1907 		spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
1908 		vc4_hdmi->packet_ram_enabled = true;
1909 
1910 		vc4_hdmi_set_infoframes(encoder);
1911 	}
1912 
1913 	vc4_hdmi_recenter_fifo(vc4_hdmi);
1914 	vc4_hdmi_enable_scrambling(encoder);
1915 
1916 	drm_dev_exit(idx);
1917 
1918 out:
1919 	mutex_unlock(&vc4_hdmi->mutex);
1920 }
1921 
1922 static void vc4_hdmi_encoder_atomic_mode_set(struct drm_encoder *encoder,
1923 					     struct drm_crtc_state *crtc_state,
1924 					     struct drm_connector_state *conn_state)
1925 {
1926 	struct vc4_hdmi *vc4_hdmi = encoder_to_vc4_hdmi(encoder);
1927 	struct vc4_hdmi_connector_state *vc4_state =
1928 		conn_state_to_vc4_hdmi_conn_state(conn_state);
1929 
1930 	mutex_lock(&vc4_hdmi->mutex);
1931 	drm_mode_copy(&vc4_hdmi->saved_adjusted_mode,
1932 		      &crtc_state->adjusted_mode);
1933 	vc4_hdmi->output_bpc = vc4_state->output_bpc;
1934 	vc4_hdmi->output_format = vc4_state->output_format;
1935 	mutex_unlock(&vc4_hdmi->mutex);
1936 }
1937 
1938 static bool
1939 vc4_hdmi_sink_supports_format_bpc(const struct vc4_hdmi *vc4_hdmi,
1940 				  const struct drm_display_info *info,
1941 				  const struct drm_display_mode *mode,
1942 				  unsigned int format, unsigned int bpc)
1943 {
1944 	struct drm_device *dev = vc4_hdmi->connector.dev;
1945 	u8 vic = drm_match_cea_mode(mode);
1946 
1947 	if (vic == 1 && bpc != 8) {
1948 		drm_dbg(dev, "VIC1 requires a bpc of 8, got %u\n", bpc);
1949 		return false;
1950 	}
1951 
1952 	if (!info->is_hdmi &&
1953 	    (format != VC4_HDMI_OUTPUT_RGB || bpc != 8)) {
1954 		drm_dbg(dev, "DVI Monitors require an RGB output at 8 bpc\n");
1955 		return false;
1956 	}
1957 
1958 	switch (format) {
1959 	case VC4_HDMI_OUTPUT_RGB:
1960 		drm_dbg(dev, "RGB Format, checking the constraints.\n");
1961 
1962 		if (!(info->color_formats & DRM_COLOR_FORMAT_RGB444))
1963 			return false;
1964 
1965 		if (bpc == 10 && !(info->edid_hdmi_rgb444_dc_modes & DRM_EDID_HDMI_DC_30)) {
1966 			drm_dbg(dev, "10 BPC but sink doesn't support Deep Color 30.\n");
1967 			return false;
1968 		}
1969 
1970 		if (bpc == 12 && !(info->edid_hdmi_rgb444_dc_modes & DRM_EDID_HDMI_DC_36)) {
1971 			drm_dbg(dev, "12 BPC but sink doesn't support Deep Color 36.\n");
1972 			return false;
1973 		}
1974 
1975 		drm_dbg(dev, "RGB format supported in that configuration.\n");
1976 
1977 		return true;
1978 
1979 	case VC4_HDMI_OUTPUT_YUV422:
1980 		drm_dbg(dev, "YUV422 format, checking the constraints.\n");
1981 
1982 		if (!(info->color_formats & DRM_COLOR_FORMAT_YCBCR422)) {
1983 			drm_dbg(dev, "Sink doesn't support YUV422.\n");
1984 			return false;
1985 		}
1986 
1987 		if (bpc != 12) {
1988 			drm_dbg(dev, "YUV422 only supports 12 bpc.\n");
1989 			return false;
1990 		}
1991 
1992 		drm_dbg(dev, "YUV422 format supported in that configuration.\n");
1993 
1994 		return true;
1995 
1996 	case VC4_HDMI_OUTPUT_YUV444:
1997 		drm_dbg(dev, "YUV444 format, checking the constraints.\n");
1998 
1999 		if (!(info->color_formats & DRM_COLOR_FORMAT_YCBCR444)) {
2000 			drm_dbg(dev, "Sink doesn't support YUV444.\n");
2001 			return false;
2002 		}
2003 
2004 		if (bpc == 10 && !(info->edid_hdmi_ycbcr444_dc_modes & DRM_EDID_HDMI_DC_30)) {
2005 			drm_dbg(dev, "10 BPC but sink doesn't support Deep Color 30.\n");
2006 			return false;
2007 		}
2008 
2009 		if (bpc == 12 && !(info->edid_hdmi_ycbcr444_dc_modes & DRM_EDID_HDMI_DC_36)) {
2010 			drm_dbg(dev, "12 BPC but sink doesn't support Deep Color 36.\n");
2011 			return false;
2012 		}
2013 
2014 		drm_dbg(dev, "YUV444 format supported in that configuration.\n");
2015 
2016 		return true;
2017 	}
2018 
2019 	return false;
2020 }
2021 
2022 static enum drm_mode_status
2023 vc4_hdmi_encoder_clock_valid(const struct vc4_hdmi *vc4_hdmi,
2024 			     const struct drm_display_mode *mode,
2025 			     unsigned long long clock)
2026 {
2027 	const struct drm_connector *connector = &vc4_hdmi->connector;
2028 	const struct drm_display_info *info = &connector->display_info;
2029 	struct vc4_dev *vc4 = to_vc4_dev(connector->dev);
2030 
2031 	if (clock > vc4_hdmi->variant->max_pixel_clock)
2032 		return MODE_CLOCK_HIGH;
2033 
2034 	if (!vc4->hvs->vc5_hdmi_enable_hdmi_20 && clock > HDMI_14_MAX_TMDS_CLK)
2035 		return MODE_CLOCK_HIGH;
2036 
2037 	/* 4096x2160@60 is not reliable without overclocking core */
2038 	if (!vc4->hvs->vc5_hdmi_enable_4096by2160 &&
2039 	    mode->hdisplay > 3840 && mode->vdisplay >= 2160 &&
2040 	    drm_mode_vrefresh(mode) >= 50)
2041 		return MODE_CLOCK_HIGH;
2042 
2043 	if (info->max_tmds_clock && clock > (info->max_tmds_clock * 1000))
2044 		return MODE_CLOCK_HIGH;
2045 
2046 	return MODE_OK;
2047 }
2048 
2049 static unsigned long long
2050 vc4_hdmi_encoder_compute_mode_clock(const struct drm_display_mode *mode,
2051 				    unsigned int bpc,
2052 				    enum vc4_hdmi_output_format fmt)
2053 {
2054 	unsigned long long clock = mode->clock * 1000ULL;
2055 
2056 	if (mode->flags & DRM_MODE_FLAG_DBLCLK)
2057 		clock = clock * 2;
2058 
2059 	if (fmt == VC4_HDMI_OUTPUT_YUV422)
2060 		bpc = 8;
2061 
2062 	clock = clock * bpc;
2063 	do_div(clock, 8);
2064 
2065 	return clock;
2066 }
2067 
2068 static int
2069 vc4_hdmi_encoder_compute_clock(const struct vc4_hdmi *vc4_hdmi,
2070 			       struct vc4_hdmi_connector_state *vc4_state,
2071 			       const struct drm_display_mode *mode,
2072 			       unsigned int bpc, unsigned int fmt)
2073 {
2074 	unsigned long long clock;
2075 
2076 	clock = vc4_hdmi_encoder_compute_mode_clock(mode, bpc, fmt);
2077 	if (vc4_hdmi_encoder_clock_valid(vc4_hdmi, mode, clock) != MODE_OK)
2078 		return -EINVAL;
2079 
2080 	vc4_state->tmds_char_rate = clock;
2081 
2082 	return 0;
2083 }
2084 
2085 static int
2086 vc4_hdmi_encoder_compute_format(const struct vc4_hdmi *vc4_hdmi,
2087 				struct vc4_hdmi_connector_state *vc4_state,
2088 				const struct drm_display_mode *mode,
2089 				unsigned int bpc)
2090 {
2091 	struct drm_device *dev = vc4_hdmi->connector.dev;
2092 	const struct drm_connector *connector = &vc4_hdmi->connector;
2093 	const struct drm_display_info *info = &connector->display_info;
2094 	unsigned int format;
2095 
2096 	drm_dbg(dev, "Trying with an RGB output\n");
2097 
2098 	format = VC4_HDMI_OUTPUT_RGB;
2099 	if (vc4_hdmi_sink_supports_format_bpc(vc4_hdmi, info, mode, format, bpc)) {
2100 		int ret;
2101 
2102 		ret = vc4_hdmi_encoder_compute_clock(vc4_hdmi, vc4_state,
2103 						     mode, bpc, format);
2104 		if (!ret) {
2105 			vc4_state->output_format = format;
2106 			return 0;
2107 		}
2108 	}
2109 
2110 	drm_dbg(dev, "Failed, Trying with an YUV422 output\n");
2111 
2112 	format = VC4_HDMI_OUTPUT_YUV422;
2113 	if (vc4_hdmi_sink_supports_format_bpc(vc4_hdmi, info, mode, format, bpc)) {
2114 		int ret;
2115 
2116 		ret = vc4_hdmi_encoder_compute_clock(vc4_hdmi, vc4_state,
2117 						     mode, bpc, format);
2118 		if (!ret) {
2119 			vc4_state->output_format = format;
2120 			return 0;
2121 		}
2122 	}
2123 
2124 	drm_dbg(dev, "Failed. No Format Supported for that bpc count.\n");
2125 
2126 	return -EINVAL;
2127 }
2128 
2129 static int
2130 vc4_hdmi_encoder_compute_config(const struct vc4_hdmi *vc4_hdmi,
2131 				struct vc4_hdmi_connector_state *vc4_state,
2132 				const struct drm_display_mode *mode)
2133 {
2134 	struct drm_device *dev = vc4_hdmi->connector.dev;
2135 	struct drm_connector_state *conn_state = &vc4_state->base;
2136 	unsigned int max_bpc = clamp_t(unsigned int, conn_state->max_bpc, 8, 12);
2137 	unsigned int bpc;
2138 	int ret;
2139 
2140 	for (bpc = max_bpc; bpc >= 8; bpc -= 2) {
2141 		drm_dbg(dev, "Trying with a %d bpc output\n", bpc);
2142 
2143 		ret = vc4_hdmi_encoder_compute_format(vc4_hdmi, vc4_state,
2144 						      mode, bpc);
2145 		if (ret)
2146 			continue;
2147 
2148 		vc4_state->output_bpc = bpc;
2149 
2150 		drm_dbg(dev,
2151 			"Mode %ux%u @ %uHz: Found configuration: bpc: %u, fmt: %s, clock: %llu\n",
2152 			mode->hdisplay, mode->vdisplay, drm_mode_vrefresh(mode),
2153 			vc4_state->output_bpc,
2154 			vc4_hdmi_output_fmt_str(vc4_state->output_format),
2155 			vc4_state->tmds_char_rate);
2156 
2157 		break;
2158 	}
2159 
2160 	return ret;
2161 }
2162 
2163 #define WIFI_2_4GHz_CH1_MIN_FREQ	2400000000ULL
2164 #define WIFI_2_4GHz_CH1_MAX_FREQ	2422000000ULL
2165 
2166 static int vc4_hdmi_encoder_atomic_check(struct drm_encoder *encoder,
2167 					 struct drm_crtc_state *crtc_state,
2168 					 struct drm_connector_state *conn_state)
2169 {
2170 	struct vc4_hdmi *vc4_hdmi = encoder_to_vc4_hdmi(encoder);
2171 	struct drm_connector *connector = &vc4_hdmi->connector;
2172 	struct drm_connector_state *old_conn_state =
2173 		drm_atomic_get_old_connector_state(conn_state->state, connector);
2174 	struct vc4_hdmi_connector_state *old_vc4_state =
2175 		conn_state_to_vc4_hdmi_conn_state(old_conn_state);
2176 	struct vc4_hdmi_connector_state *vc4_state = conn_state_to_vc4_hdmi_conn_state(conn_state);
2177 	struct drm_display_mode *mode = &crtc_state->adjusted_mode;
2178 	unsigned long long tmds_char_rate = mode->clock * 1000;
2179 	unsigned long long tmds_bit_rate;
2180 	int ret;
2181 
2182 	if (vc4_hdmi->variant->unsupported_odd_h_timings) {
2183 		if (mode->flags & DRM_MODE_FLAG_DBLCLK) {
2184 			/* Only try to fixup DBLCLK modes to get 480i and 576i
2185 			 * working.
2186 			 * A generic solution for all modes with odd horizontal
2187 			 * timing values seems impossible based on trying to
2188 			 * solve it for 1366x768 monitors.
2189 			 */
2190 			if ((mode->hsync_start - mode->hdisplay) & 1)
2191 				mode->hsync_start--;
2192 			if ((mode->hsync_end - mode->hsync_start) & 1)
2193 				mode->hsync_end--;
2194 		}
2195 
2196 		/* Now check whether we still have odd values remaining */
2197 		if ((mode->hdisplay % 2) || (mode->hsync_start % 2) ||
2198 		    (mode->hsync_end % 2) || (mode->htotal % 2))
2199 			return -EINVAL;
2200 	}
2201 
2202 	/*
2203 	 * The 1440p@60 pixel rate is in the same range than the first
2204 	 * WiFi channel (between 2.4GHz and 2.422GHz with 22MHz
2205 	 * bandwidth). Slightly lower the frequency to bring it out of
2206 	 * the WiFi range.
2207 	 */
2208 	tmds_bit_rate = tmds_char_rate * 10;
2209 	if (vc4_hdmi->disable_wifi_frequencies &&
2210 	    (tmds_bit_rate >= WIFI_2_4GHz_CH1_MIN_FREQ &&
2211 	     tmds_bit_rate <= WIFI_2_4GHz_CH1_MAX_FREQ)) {
2212 		mode->clock = 238560;
2213 		tmds_char_rate = mode->clock * 1000;
2214 	}
2215 
2216 	ret = vc4_hdmi_encoder_compute_config(vc4_hdmi, vc4_state, mode);
2217 	if (ret)
2218 		return ret;
2219 
2220 	/* vc4_hdmi_encoder_compute_config may have changed output_bpc and/or output_format */
2221 	if (vc4_state->output_bpc != old_vc4_state->output_bpc ||
2222 	    vc4_state->output_format != old_vc4_state->output_format)
2223 		crtc_state->mode_changed = true;
2224 
2225 	return 0;
2226 }
2227 
2228 static enum drm_mode_status
2229 vc4_hdmi_encoder_mode_valid(struct drm_encoder *encoder,
2230 			    const struct drm_display_mode *mode)
2231 {
2232 	struct vc4_hdmi *vc4_hdmi = encoder_to_vc4_hdmi(encoder);
2233 
2234 	if (vc4_hdmi->variant->unsupported_odd_h_timings &&
2235 	    !(mode->flags & DRM_MODE_FLAG_DBLCLK) &&
2236 	    ((mode->hdisplay % 2) || (mode->hsync_start % 2) ||
2237 	     (mode->hsync_end % 2) || (mode->htotal % 2)))
2238 		return MODE_H_ILLEGAL;
2239 
2240 	return vc4_hdmi_encoder_clock_valid(vc4_hdmi, mode, mode->clock * 1000);
2241 }
2242 
2243 static const struct drm_encoder_helper_funcs vc4_hdmi_encoder_helper_funcs = {
2244 	.atomic_check = vc4_hdmi_encoder_atomic_check,
2245 	.atomic_mode_set = vc4_hdmi_encoder_atomic_mode_set,
2246 	.mode_valid = vc4_hdmi_encoder_mode_valid,
2247 };
2248 
2249 static int vc4_hdmi_late_register(struct drm_encoder *encoder)
2250 {
2251 	struct drm_device *drm = encoder->dev;
2252 	struct vc4_hdmi *vc4_hdmi = encoder_to_vc4_hdmi(encoder);
2253 	const struct vc4_hdmi_variant *variant = vc4_hdmi->variant;
2254 
2255 	drm_debugfs_add_file(drm, variant->debugfs_name,
2256 			     vc4_hdmi_debugfs_regs, vc4_hdmi);
2257 
2258 	return 0;
2259 }
2260 
2261 static const struct drm_encoder_funcs vc4_hdmi_encoder_funcs = {
2262 	.late_register = vc4_hdmi_late_register,
2263 };
2264 
2265 static u32 vc4_hdmi_channel_map(struct vc4_hdmi *vc4_hdmi, u32 channel_mask)
2266 {
2267 	int i;
2268 	u32 channel_map = 0;
2269 
2270 	for (i = 0; i < 8; i++) {
2271 		if (channel_mask & BIT(i))
2272 			channel_map |= i << (3 * i);
2273 	}
2274 	return channel_map;
2275 }
2276 
2277 static u32 vc5_hdmi_channel_map(struct vc4_hdmi *vc4_hdmi, u32 channel_mask)
2278 {
2279 	int i;
2280 	u32 channel_map = 0;
2281 
2282 	for (i = 0; i < 8; i++) {
2283 		if (channel_mask & BIT(i))
2284 			channel_map |= i << (4 * i);
2285 	}
2286 	return channel_map;
2287 }
2288 
2289 static bool vc5_hdmi_hp_detect(struct vc4_hdmi *vc4_hdmi)
2290 {
2291 	struct drm_device *drm = vc4_hdmi->connector.dev;
2292 	unsigned long flags;
2293 	u32 hotplug;
2294 	int idx;
2295 
2296 	if (!drm_dev_enter(drm, &idx))
2297 		return false;
2298 
2299 	spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
2300 	hotplug = HDMI_READ(HDMI_HOTPLUG);
2301 	spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
2302 
2303 	drm_dev_exit(idx);
2304 
2305 	return !!(hotplug & VC4_HDMI_HOTPLUG_CONNECTED);
2306 }
2307 
2308 /* HDMI audio codec callbacks */
2309 static void vc4_hdmi_audio_set_mai_clock(struct vc4_hdmi *vc4_hdmi,
2310 					 unsigned int samplerate)
2311 {
2312 	struct drm_device *drm = vc4_hdmi->connector.dev;
2313 	u32 hsm_clock;
2314 	unsigned long flags;
2315 	unsigned long n, m;
2316 	int idx;
2317 
2318 	if (!drm_dev_enter(drm, &idx))
2319 		return;
2320 
2321 	hsm_clock = clk_get_rate(vc4_hdmi->audio_clock);
2322 	rational_best_approximation(hsm_clock, samplerate,
2323 				    VC4_HD_MAI_SMP_N_MASK >>
2324 				    VC4_HD_MAI_SMP_N_SHIFT,
2325 				    (VC4_HD_MAI_SMP_M_MASK >>
2326 				     VC4_HD_MAI_SMP_M_SHIFT) + 1,
2327 				    &n, &m);
2328 
2329 	spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
2330 	HDMI_WRITE(HDMI_MAI_SMP,
2331 		   VC4_SET_FIELD(n, VC4_HD_MAI_SMP_N) |
2332 		   VC4_SET_FIELD(m - 1, VC4_HD_MAI_SMP_M));
2333 	spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
2334 
2335 	drm_dev_exit(idx);
2336 }
2337 
2338 static void vc4_hdmi_set_n_cts(struct vc4_hdmi *vc4_hdmi, unsigned int samplerate)
2339 {
2340 	const struct drm_display_mode *mode = &vc4_hdmi->saved_adjusted_mode;
2341 	u32 n, cts;
2342 	u64 tmp;
2343 
2344 	lockdep_assert_held(&vc4_hdmi->mutex);
2345 	lockdep_assert_held(&vc4_hdmi->hw_lock);
2346 
2347 	n = 128 * samplerate / 1000;
2348 	tmp = (u64)(mode->clock * 1000) * n;
2349 	do_div(tmp, 128 * samplerate);
2350 	cts = tmp;
2351 
2352 	HDMI_WRITE(HDMI_CRP_CFG,
2353 		   VC4_HDMI_CRP_CFG_EXTERNAL_CTS_EN |
2354 		   VC4_SET_FIELD(n, VC4_HDMI_CRP_CFG_N));
2355 
2356 	/*
2357 	 * We could get slightly more accurate clocks in some cases by
2358 	 * providing a CTS_1 value.  The two CTS values are alternated
2359 	 * between based on the period fields
2360 	 */
2361 	HDMI_WRITE(HDMI_CTS_0, cts);
2362 	HDMI_WRITE(HDMI_CTS_1, cts);
2363 }
2364 
2365 static inline struct vc4_hdmi *dai_to_hdmi(struct snd_soc_dai *dai)
2366 {
2367 	struct snd_soc_card *card = snd_soc_dai_get_drvdata(dai);
2368 
2369 	return snd_soc_card_get_drvdata(card);
2370 }
2371 
2372 static bool vc4_hdmi_audio_can_stream(struct vc4_hdmi *vc4_hdmi)
2373 {
2374 	struct drm_display_info *display = &vc4_hdmi->connector.display_info;
2375 
2376 	lockdep_assert_held(&vc4_hdmi->mutex);
2377 
2378 	/*
2379 	 * If the encoder is currently in DVI mode, treat the codec DAI
2380 	 * as missing.
2381 	 */
2382 	if (!display->is_hdmi)
2383 		return false;
2384 
2385 	return true;
2386 }
2387 
2388 static int vc4_hdmi_audio_startup(struct device *dev, void *data)
2389 {
2390 	struct vc4_hdmi *vc4_hdmi = dev_get_drvdata(dev);
2391 	struct drm_device *drm = vc4_hdmi->connector.dev;
2392 	unsigned long flags;
2393 	int ret = 0;
2394 	int idx;
2395 
2396 	mutex_lock(&vc4_hdmi->mutex);
2397 
2398 	if (!drm_dev_enter(drm, &idx)) {
2399 		ret = -ENODEV;
2400 		goto out;
2401 	}
2402 
2403 	if (!vc4_hdmi_audio_can_stream(vc4_hdmi)) {
2404 		ret = -ENODEV;
2405 		goto out_dev_exit;
2406 	}
2407 
2408 	vc4_hdmi->audio.streaming = true;
2409 
2410 	spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
2411 	HDMI_WRITE(HDMI_MAI_CTL,
2412 		   VC4_HD_MAI_CTL_RESET |
2413 		   VC4_HD_MAI_CTL_FLUSH |
2414 		   VC4_HD_MAI_CTL_DLATE |
2415 		   VC4_HD_MAI_CTL_ERRORE |
2416 		   VC4_HD_MAI_CTL_ERRORF);
2417 	spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
2418 
2419 	if (vc4_hdmi->variant->phy_rng_enable)
2420 		vc4_hdmi->variant->phy_rng_enable(vc4_hdmi);
2421 
2422 out_dev_exit:
2423 	drm_dev_exit(idx);
2424 out:
2425 	mutex_unlock(&vc4_hdmi->mutex);
2426 
2427 	return ret;
2428 }
2429 
2430 static void vc4_hdmi_audio_reset(struct vc4_hdmi *vc4_hdmi)
2431 {
2432 	struct drm_encoder *encoder = &vc4_hdmi->encoder.base;
2433 	struct device *dev = &vc4_hdmi->pdev->dev;
2434 	unsigned long flags;
2435 	int ret;
2436 
2437 	lockdep_assert_held(&vc4_hdmi->mutex);
2438 
2439 	vc4_hdmi->audio.streaming = false;
2440 	ret = vc4_hdmi_stop_packet(encoder, HDMI_INFOFRAME_TYPE_AUDIO, false);
2441 	if (ret)
2442 		dev_err(dev, "Failed to stop audio infoframe: %d\n", ret);
2443 
2444 	spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
2445 
2446 	HDMI_WRITE(HDMI_MAI_CTL, VC4_HD_MAI_CTL_RESET);
2447 	HDMI_WRITE(HDMI_MAI_CTL, VC4_HD_MAI_CTL_ERRORF);
2448 	HDMI_WRITE(HDMI_MAI_CTL, VC4_HD_MAI_CTL_FLUSH);
2449 
2450 	spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
2451 }
2452 
2453 static void vc4_hdmi_audio_shutdown(struct device *dev, void *data)
2454 {
2455 	struct vc4_hdmi *vc4_hdmi = dev_get_drvdata(dev);
2456 	struct drm_device *drm = vc4_hdmi->connector.dev;
2457 	unsigned long flags;
2458 	int idx;
2459 
2460 	mutex_lock(&vc4_hdmi->mutex);
2461 
2462 	if (!drm_dev_enter(drm, &idx))
2463 		goto out;
2464 
2465 	spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
2466 
2467 	HDMI_WRITE(HDMI_MAI_CTL,
2468 		   VC4_HD_MAI_CTL_DLATE |
2469 		   VC4_HD_MAI_CTL_ERRORE |
2470 		   VC4_HD_MAI_CTL_ERRORF);
2471 
2472 	spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
2473 
2474 	if (vc4_hdmi->variant->phy_rng_disable)
2475 		vc4_hdmi->variant->phy_rng_disable(vc4_hdmi);
2476 
2477 	vc4_hdmi->audio.streaming = false;
2478 	vc4_hdmi_audio_reset(vc4_hdmi);
2479 
2480 	drm_dev_exit(idx);
2481 
2482 out:
2483 	mutex_unlock(&vc4_hdmi->mutex);
2484 }
2485 
2486 static int sample_rate_to_mai_fmt(int samplerate)
2487 {
2488 	switch (samplerate) {
2489 	case 8000:
2490 		return VC4_HDMI_MAI_SAMPLE_RATE_8000;
2491 	case 11025:
2492 		return VC4_HDMI_MAI_SAMPLE_RATE_11025;
2493 	case 12000:
2494 		return VC4_HDMI_MAI_SAMPLE_RATE_12000;
2495 	case 16000:
2496 		return VC4_HDMI_MAI_SAMPLE_RATE_16000;
2497 	case 22050:
2498 		return VC4_HDMI_MAI_SAMPLE_RATE_22050;
2499 	case 24000:
2500 		return VC4_HDMI_MAI_SAMPLE_RATE_24000;
2501 	case 32000:
2502 		return VC4_HDMI_MAI_SAMPLE_RATE_32000;
2503 	case 44100:
2504 		return VC4_HDMI_MAI_SAMPLE_RATE_44100;
2505 	case 48000:
2506 		return VC4_HDMI_MAI_SAMPLE_RATE_48000;
2507 	case 64000:
2508 		return VC4_HDMI_MAI_SAMPLE_RATE_64000;
2509 	case 88200:
2510 		return VC4_HDMI_MAI_SAMPLE_RATE_88200;
2511 	case 96000:
2512 		return VC4_HDMI_MAI_SAMPLE_RATE_96000;
2513 	case 128000:
2514 		return VC4_HDMI_MAI_SAMPLE_RATE_128000;
2515 	case 176400:
2516 		return VC4_HDMI_MAI_SAMPLE_RATE_176400;
2517 	case 192000:
2518 		return VC4_HDMI_MAI_SAMPLE_RATE_192000;
2519 	default:
2520 		return VC4_HDMI_MAI_SAMPLE_RATE_NOT_INDICATED;
2521 	}
2522 }
2523 
2524 /* HDMI audio codec callbacks */
2525 static int vc4_hdmi_audio_prepare(struct device *dev, void *data,
2526 				  struct hdmi_codec_daifmt *daifmt,
2527 				  struct hdmi_codec_params *params)
2528 {
2529 	struct vc4_hdmi *vc4_hdmi = dev_get_drvdata(dev);
2530 	struct drm_device *drm = vc4_hdmi->connector.dev;
2531 	struct drm_encoder *encoder = &vc4_hdmi->encoder.base;
2532 	unsigned int sample_rate = params->sample_rate;
2533 	unsigned int channels = params->channels;
2534 	unsigned long flags;
2535 	u32 audio_packet_config, channel_mask;
2536 	u32 channel_map;
2537 	u32 mai_audio_format;
2538 	u32 mai_sample_rate;
2539 	int ret = 0;
2540 	int idx;
2541 
2542 	dev_dbg(dev, "%s: %u Hz, %d bit, %d channels\n", __func__,
2543 		sample_rate, params->sample_width, channels);
2544 
2545 	mutex_lock(&vc4_hdmi->mutex);
2546 
2547 	if (!drm_dev_enter(drm, &idx)) {
2548 		ret = -ENODEV;
2549 		goto out;
2550 	}
2551 
2552 	if (!vc4_hdmi_audio_can_stream(vc4_hdmi)) {
2553 		ret = -EINVAL;
2554 		goto out_dev_exit;
2555 	}
2556 
2557 	vc4_hdmi_audio_set_mai_clock(vc4_hdmi, sample_rate);
2558 
2559 	spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
2560 	HDMI_WRITE(HDMI_MAI_CTL,
2561 		   VC4_SET_FIELD(channels, VC4_HD_MAI_CTL_CHNUM) |
2562 		   VC4_HD_MAI_CTL_WHOLSMP |
2563 		   VC4_HD_MAI_CTL_CHALIGN |
2564 		   VC4_HD_MAI_CTL_ENABLE);
2565 
2566 	mai_sample_rate = sample_rate_to_mai_fmt(sample_rate);
2567 	if (params->iec.status[0] & IEC958_AES0_NONAUDIO &&
2568 	    params->channels == 8)
2569 		mai_audio_format = VC4_HDMI_MAI_FORMAT_HBR;
2570 	else
2571 		mai_audio_format = VC4_HDMI_MAI_FORMAT_PCM;
2572 	HDMI_WRITE(HDMI_MAI_FMT,
2573 		   VC4_SET_FIELD(mai_sample_rate,
2574 				 VC4_HDMI_MAI_FORMAT_SAMPLE_RATE) |
2575 		   VC4_SET_FIELD(mai_audio_format,
2576 				 VC4_HDMI_MAI_FORMAT_AUDIO_FORMAT));
2577 
2578 	/* The B frame identifier should match the value used by alsa-lib (8) */
2579 	audio_packet_config =
2580 		VC4_HDMI_AUDIO_PACKET_ZERO_DATA_ON_SAMPLE_FLAT |
2581 		VC4_HDMI_AUDIO_PACKET_ZERO_DATA_ON_INACTIVE_CHANNELS |
2582 		VC4_SET_FIELD(0x8, VC4_HDMI_AUDIO_PACKET_B_FRAME_IDENTIFIER);
2583 
2584 	channel_mask = GENMASK(channels - 1, 0);
2585 	audio_packet_config |= VC4_SET_FIELD(channel_mask,
2586 					     VC4_HDMI_AUDIO_PACKET_CEA_MASK);
2587 
2588 	/* Set the MAI threshold */
2589 	HDMI_WRITE(HDMI_MAI_THR,
2590 		   VC4_SET_FIELD(0x08, VC4_HD_MAI_THR_PANICHIGH) |
2591 		   VC4_SET_FIELD(0x08, VC4_HD_MAI_THR_PANICLOW) |
2592 		   VC4_SET_FIELD(0x06, VC4_HD_MAI_THR_DREQHIGH) |
2593 		   VC4_SET_FIELD(0x08, VC4_HD_MAI_THR_DREQLOW));
2594 
2595 	HDMI_WRITE(HDMI_MAI_CONFIG,
2596 		   VC4_HDMI_MAI_CONFIG_BIT_REVERSE |
2597 		   VC4_HDMI_MAI_CONFIG_FORMAT_REVERSE |
2598 		   VC4_SET_FIELD(channel_mask, VC4_HDMI_MAI_CHANNEL_MASK));
2599 
2600 	channel_map = vc4_hdmi->variant->channel_map(vc4_hdmi, channel_mask);
2601 	HDMI_WRITE(HDMI_MAI_CHANNEL_MAP, channel_map);
2602 	HDMI_WRITE(HDMI_AUDIO_PACKET_CONFIG, audio_packet_config);
2603 
2604 	vc4_hdmi_set_n_cts(vc4_hdmi, sample_rate);
2605 
2606 	spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
2607 
2608 	memcpy(&vc4_hdmi->audio.infoframe, &params->cea, sizeof(params->cea));
2609 	vc4_hdmi_set_audio_infoframe(encoder);
2610 
2611 out_dev_exit:
2612 	drm_dev_exit(idx);
2613 out:
2614 	mutex_unlock(&vc4_hdmi->mutex);
2615 
2616 	return ret;
2617 }
2618 
2619 static const struct snd_soc_component_driver vc4_hdmi_audio_cpu_dai_comp = {
2620 	.name = "vc4-hdmi-cpu-dai-component",
2621 	.legacy_dai_naming = 1,
2622 };
2623 
2624 static int vc4_hdmi_audio_cpu_dai_probe(struct snd_soc_dai *dai)
2625 {
2626 	struct vc4_hdmi *vc4_hdmi = dai_to_hdmi(dai);
2627 
2628 	snd_soc_dai_init_dma_data(dai, &vc4_hdmi->audio.dma_data, NULL);
2629 
2630 	return 0;
2631 }
2632 
2633 static const struct snd_soc_dai_ops vc4_snd_dai_ops = {
2634 	.probe  = vc4_hdmi_audio_cpu_dai_probe,
2635 };
2636 
2637 static struct snd_soc_dai_driver vc4_hdmi_audio_cpu_dai_drv = {
2638 	.name = "vc4-hdmi-cpu-dai",
2639 	.ops = &vc4_snd_dai_ops,
2640 	.playback = {
2641 		.stream_name = "Playback",
2642 		.channels_min = 1,
2643 		.channels_max = 8,
2644 		.rates = SNDRV_PCM_RATE_32000 | SNDRV_PCM_RATE_44100 |
2645 			 SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_88200 |
2646 			 SNDRV_PCM_RATE_96000 | SNDRV_PCM_RATE_176400 |
2647 			 SNDRV_PCM_RATE_192000,
2648 		.formats = SNDRV_PCM_FMTBIT_IEC958_SUBFRAME_LE,
2649 	},
2650 };
2651 
2652 static const struct snd_dmaengine_pcm_config pcm_conf = {
2653 	.chan_names[SNDRV_PCM_STREAM_PLAYBACK] = "audio-rx",
2654 	.prepare_slave_config = snd_dmaengine_pcm_prepare_slave_config,
2655 };
2656 
2657 static int vc4_hdmi_audio_get_eld(struct device *dev, void *data,
2658 				  uint8_t *buf, size_t len)
2659 {
2660 	struct vc4_hdmi *vc4_hdmi = dev_get_drvdata(dev);
2661 	struct drm_connector *connector = &vc4_hdmi->connector;
2662 
2663 	mutex_lock(&vc4_hdmi->mutex);
2664 	memcpy(buf, connector->eld, min(sizeof(connector->eld), len));
2665 	mutex_unlock(&vc4_hdmi->mutex);
2666 
2667 	return 0;
2668 }
2669 
2670 static const struct hdmi_codec_ops vc4_hdmi_codec_ops = {
2671 	.get_eld = vc4_hdmi_audio_get_eld,
2672 	.prepare = vc4_hdmi_audio_prepare,
2673 	.audio_shutdown = vc4_hdmi_audio_shutdown,
2674 	.audio_startup = vc4_hdmi_audio_startup,
2675 };
2676 
2677 static struct hdmi_codec_pdata vc4_hdmi_codec_pdata = {
2678 	.ops = &vc4_hdmi_codec_ops,
2679 	.max_i2s_channels = 8,
2680 	.i2s = 1,
2681 };
2682 
2683 static void vc4_hdmi_audio_codec_release(void *ptr)
2684 {
2685 	struct vc4_hdmi *vc4_hdmi = ptr;
2686 
2687 	platform_device_unregister(vc4_hdmi->audio.codec_pdev);
2688 	vc4_hdmi->audio.codec_pdev = NULL;
2689 }
2690 
2691 static int vc4_hdmi_audio_init(struct vc4_hdmi *vc4_hdmi)
2692 {
2693 	const struct vc4_hdmi_register *mai_data =
2694 		&vc4_hdmi->variant->registers[HDMI_MAI_DATA];
2695 	struct snd_soc_dai_link *dai_link = &vc4_hdmi->audio.link;
2696 	struct snd_soc_card *card = &vc4_hdmi->audio.card;
2697 	struct device *dev = &vc4_hdmi->pdev->dev;
2698 	struct platform_device *codec_pdev;
2699 	const __be32 *addr;
2700 	int index, len;
2701 	int ret;
2702 
2703 	/*
2704 	 * ASoC makes it a bit hard to retrieve a pointer to the
2705 	 * vc4_hdmi structure. Registering the card will overwrite our
2706 	 * device drvdata with a pointer to the snd_soc_card structure,
2707 	 * which can then be used to retrieve whatever drvdata we want
2708 	 * to associate.
2709 	 *
2710 	 * However, that doesn't fly in the case where we wouldn't
2711 	 * register an ASoC card (because of an old DT that is missing
2712 	 * the dmas properties for example), then the card isn't
2713 	 * registered and the device drvdata wouldn't be set.
2714 	 *
2715 	 * We can deal with both cases by making sure a snd_soc_card
2716 	 * pointer and a vc4_hdmi structure are pointing to the same
2717 	 * memory address, so we can treat them indistinctly without any
2718 	 * issue.
2719 	 */
2720 	BUILD_BUG_ON(offsetof(struct vc4_hdmi_audio, card) != 0);
2721 	BUILD_BUG_ON(offsetof(struct vc4_hdmi, audio) != 0);
2722 
2723 	if (!of_find_property(dev->of_node, "dmas", &len) || !len) {
2724 		dev_warn(dev,
2725 			 "'dmas' DT property is missing or empty, no HDMI audio\n");
2726 		return 0;
2727 	}
2728 
2729 	if (mai_data->reg != VC4_HD) {
2730 		WARN_ONCE(true, "MAI isn't in the HD block\n");
2731 		return -EINVAL;
2732 	}
2733 
2734 	/*
2735 	 * Get the physical address of VC4_HD_MAI_DATA. We need to retrieve
2736 	 * the bus address specified in the DT, because the physical address
2737 	 * (the one returned by platform_get_resource()) is not appropriate
2738 	 * for DMA transfers.
2739 	 * This VC/MMU should probably be exposed to avoid this kind of hacks.
2740 	 */
2741 	index = of_property_match_string(dev->of_node, "reg-names", "hd");
2742 	/* Before BCM2711, we don't have a named register range */
2743 	if (index < 0)
2744 		index = 1;
2745 
2746 	addr = of_get_address(dev->of_node, index, NULL, NULL);
2747 	if (!addr)
2748 		return -EINVAL;
2749 
2750 	vc4_hdmi->audio.dma_data.addr = be32_to_cpup(addr) + mai_data->offset;
2751 	vc4_hdmi->audio.dma_data.addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
2752 	vc4_hdmi->audio.dma_data.maxburst = 2;
2753 
2754 	/*
2755 	 * NOTE: Strictly speaking, we should probably use a DRM-managed
2756 	 * registration there to avoid removing all the audio components
2757 	 * by the time the driver doesn't have any user anymore.
2758 	 *
2759 	 * However, the ASoC core uses a number of devm_kzalloc calls
2760 	 * when registering, even when using non-device-managed
2761 	 * functions (such as in snd_soc_register_component()).
2762 	 *
2763 	 * If we call snd_soc_unregister_component() in a DRM-managed
2764 	 * action, the device-managed actions have already been executed
2765 	 * and thus we would access memory that has been freed.
2766 	 *
2767 	 * Using device-managed hooks here probably leaves us open to a
2768 	 * bunch of issues if userspace still has a handle on the ALSA
2769 	 * device when the device is removed. However, this is mitigated
2770 	 * by the use of drm_dev_enter()/drm_dev_exit() in the audio
2771 	 * path to prevent the access to the device resources if it
2772 	 * isn't there anymore.
2773 	 *
2774 	 * Then, the vc4_hdmi structure is DRM-managed and thus only
2775 	 * freed whenever the last user has closed the DRM device file.
2776 	 * It should thus outlive ALSA in most situations.
2777 	 */
2778 	ret = devm_snd_dmaengine_pcm_register(dev, &pcm_conf, 0);
2779 	if (ret) {
2780 		dev_err(dev, "Could not register PCM component: %d\n", ret);
2781 		return ret;
2782 	}
2783 
2784 	ret = devm_snd_soc_register_component(dev, &vc4_hdmi_audio_cpu_dai_comp,
2785 					      &vc4_hdmi_audio_cpu_dai_drv, 1);
2786 	if (ret) {
2787 		dev_err(dev, "Could not register CPU DAI: %d\n", ret);
2788 		return ret;
2789 	}
2790 
2791 	codec_pdev = platform_device_register_data(dev, HDMI_CODEC_DRV_NAME,
2792 						   PLATFORM_DEVID_AUTO,
2793 						   &vc4_hdmi_codec_pdata,
2794 						   sizeof(vc4_hdmi_codec_pdata));
2795 	if (IS_ERR(codec_pdev)) {
2796 		dev_err(dev, "Couldn't register the HDMI codec: %ld\n", PTR_ERR(codec_pdev));
2797 		return PTR_ERR(codec_pdev);
2798 	}
2799 	vc4_hdmi->audio.codec_pdev = codec_pdev;
2800 
2801 	ret = devm_add_action_or_reset(dev, vc4_hdmi_audio_codec_release, vc4_hdmi);
2802 	if (ret)
2803 		return ret;
2804 
2805 	dai_link->cpus		= &vc4_hdmi->audio.cpu;
2806 	dai_link->codecs	= &vc4_hdmi->audio.codec;
2807 	dai_link->platforms	= &vc4_hdmi->audio.platform;
2808 
2809 	dai_link->num_cpus	= 1;
2810 	dai_link->num_codecs	= 1;
2811 	dai_link->num_platforms	= 1;
2812 
2813 	dai_link->name = "MAI";
2814 	dai_link->stream_name = "MAI PCM";
2815 	dai_link->codecs->dai_name = "i2s-hifi";
2816 	dai_link->cpus->dai_name = dev_name(dev);
2817 	dai_link->codecs->name = dev_name(&codec_pdev->dev);
2818 	dai_link->platforms->name = dev_name(dev);
2819 
2820 	card->dai_link = dai_link;
2821 	card->num_links = 1;
2822 	card->name = vc4_hdmi->variant->card_name;
2823 	card->driver_name = "vc4-hdmi";
2824 	card->dev = dev;
2825 	card->owner = THIS_MODULE;
2826 
2827 	/*
2828 	 * Be careful, snd_soc_register_card() calls dev_set_drvdata() and
2829 	 * stores a pointer to the snd card object in dev->driver_data. This
2830 	 * means we cannot use it for something else. The hdmi back-pointer is
2831 	 * now stored in card->drvdata and should be retrieved with
2832 	 * snd_soc_card_get_drvdata() if needed.
2833 	 */
2834 	snd_soc_card_set_drvdata(card, vc4_hdmi);
2835 	ret = devm_snd_soc_register_card(dev, card);
2836 	if (ret)
2837 		dev_err_probe(dev, ret, "Could not register sound card\n");
2838 
2839 	return ret;
2840 
2841 }
2842 
2843 static irqreturn_t vc4_hdmi_hpd_irq_thread(int irq, void *priv)
2844 {
2845 	struct vc4_hdmi *vc4_hdmi = priv;
2846 	struct drm_connector *connector = &vc4_hdmi->connector;
2847 	struct drm_device *dev = connector->dev;
2848 
2849 	if (dev && dev->registered)
2850 		drm_connector_helper_hpd_irq_event(connector);
2851 
2852 	return IRQ_HANDLED;
2853 }
2854 
2855 static int vc4_hdmi_hotplug_init(struct vc4_hdmi *vc4_hdmi)
2856 {
2857 	struct drm_connector *connector = &vc4_hdmi->connector;
2858 	struct platform_device *pdev = vc4_hdmi->pdev;
2859 	int ret;
2860 
2861 	if (vc4_hdmi->variant->external_irq_controller) {
2862 		unsigned int hpd_con = platform_get_irq_byname(pdev, "hpd-connected");
2863 		unsigned int hpd_rm = platform_get_irq_byname(pdev, "hpd-removed");
2864 
2865 		ret = devm_request_threaded_irq(&pdev->dev, hpd_con,
2866 						NULL,
2867 						vc4_hdmi_hpd_irq_thread, IRQF_ONESHOT,
2868 						"vc4 hdmi hpd connected", vc4_hdmi);
2869 		if (ret)
2870 			return ret;
2871 
2872 		ret = devm_request_threaded_irq(&pdev->dev, hpd_rm,
2873 						NULL,
2874 						vc4_hdmi_hpd_irq_thread, IRQF_ONESHOT,
2875 						"vc4 hdmi hpd disconnected", vc4_hdmi);
2876 		if (ret)
2877 			return ret;
2878 
2879 		connector->polled = DRM_CONNECTOR_POLL_HPD;
2880 	}
2881 
2882 	return 0;
2883 }
2884 
2885 #ifdef CONFIG_DRM_VC4_HDMI_CEC
2886 static irqreturn_t vc4_cec_irq_handler_rx_thread(int irq, void *priv)
2887 {
2888 	struct vc4_hdmi *vc4_hdmi = priv;
2889 
2890 	if (vc4_hdmi->cec_rx_msg.len)
2891 		cec_received_msg(vc4_hdmi->cec_adap,
2892 				 &vc4_hdmi->cec_rx_msg);
2893 
2894 	return IRQ_HANDLED;
2895 }
2896 
2897 static irqreturn_t vc4_cec_irq_handler_tx_thread(int irq, void *priv)
2898 {
2899 	struct vc4_hdmi *vc4_hdmi = priv;
2900 
2901 	if (vc4_hdmi->cec_tx_ok) {
2902 		cec_transmit_done(vc4_hdmi->cec_adap, CEC_TX_STATUS_OK,
2903 				  0, 0, 0, 0);
2904 	} else {
2905 		/*
2906 		 * This CEC implementation makes 1 retry, so if we
2907 		 * get a NACK, then that means it made 2 attempts.
2908 		 */
2909 		cec_transmit_done(vc4_hdmi->cec_adap, CEC_TX_STATUS_NACK,
2910 				  0, 2, 0, 0);
2911 	}
2912 	return IRQ_HANDLED;
2913 }
2914 
2915 static irqreturn_t vc4_cec_irq_handler_thread(int irq, void *priv)
2916 {
2917 	struct vc4_hdmi *vc4_hdmi = priv;
2918 	irqreturn_t ret;
2919 
2920 	if (vc4_hdmi->cec_irq_was_rx)
2921 		ret = vc4_cec_irq_handler_rx_thread(irq, priv);
2922 	else
2923 		ret = vc4_cec_irq_handler_tx_thread(irq, priv);
2924 
2925 	return ret;
2926 }
2927 
2928 static void vc4_cec_read_msg(struct vc4_hdmi *vc4_hdmi, u32 cntrl1)
2929 {
2930 	struct drm_device *dev = vc4_hdmi->connector.dev;
2931 	struct cec_msg *msg = &vc4_hdmi->cec_rx_msg;
2932 	unsigned int i;
2933 
2934 	lockdep_assert_held(&vc4_hdmi->hw_lock);
2935 
2936 	msg->len = 1 + ((cntrl1 & VC4_HDMI_CEC_REC_WRD_CNT_MASK) >>
2937 					VC4_HDMI_CEC_REC_WRD_CNT_SHIFT);
2938 
2939 	if (msg->len > 16) {
2940 		drm_err(dev, "Attempting to read too much data (%d)\n", msg->len);
2941 		return;
2942 	}
2943 
2944 	for (i = 0; i < msg->len; i += 4) {
2945 		u32 val = HDMI_READ(HDMI_CEC_RX_DATA_1 + (i >> 2));
2946 
2947 		msg->msg[i] = val & 0xff;
2948 		msg->msg[i + 1] = (val >> 8) & 0xff;
2949 		msg->msg[i + 2] = (val >> 16) & 0xff;
2950 		msg->msg[i + 3] = (val >> 24) & 0xff;
2951 	}
2952 }
2953 
2954 static irqreturn_t vc4_cec_irq_handler_tx_bare_locked(struct vc4_hdmi *vc4_hdmi)
2955 {
2956 	u32 cntrl1;
2957 
2958 	/*
2959 	 * We don't need to protect the register access using
2960 	 * drm_dev_enter() there because the interrupt handler lifetime
2961 	 * is tied to the device itself, and not to the DRM device.
2962 	 *
2963 	 * So when the device will be gone, one of the first thing we
2964 	 * will be doing will be to unregister the interrupt handler,
2965 	 * and then unregister the DRM device. drm_dev_enter() would
2966 	 * thus always succeed if we are here.
2967 	 */
2968 
2969 	lockdep_assert_held(&vc4_hdmi->hw_lock);
2970 
2971 	cntrl1 = HDMI_READ(HDMI_CEC_CNTRL_1);
2972 	vc4_hdmi->cec_tx_ok = cntrl1 & VC4_HDMI_CEC_TX_STATUS_GOOD;
2973 	cntrl1 &= ~VC4_HDMI_CEC_START_XMIT_BEGIN;
2974 	HDMI_WRITE(HDMI_CEC_CNTRL_1, cntrl1);
2975 
2976 	return IRQ_WAKE_THREAD;
2977 }
2978 
2979 static irqreturn_t vc4_cec_irq_handler_tx_bare(int irq, void *priv)
2980 {
2981 	struct vc4_hdmi *vc4_hdmi = priv;
2982 	irqreturn_t ret;
2983 
2984 	spin_lock(&vc4_hdmi->hw_lock);
2985 	ret = vc4_cec_irq_handler_tx_bare_locked(vc4_hdmi);
2986 	spin_unlock(&vc4_hdmi->hw_lock);
2987 
2988 	return ret;
2989 }
2990 
2991 static irqreturn_t vc4_cec_irq_handler_rx_bare_locked(struct vc4_hdmi *vc4_hdmi)
2992 {
2993 	u32 cntrl1;
2994 
2995 	lockdep_assert_held(&vc4_hdmi->hw_lock);
2996 
2997 	/*
2998 	 * We don't need to protect the register access using
2999 	 * drm_dev_enter() there because the interrupt handler lifetime
3000 	 * is tied to the device itself, and not to the DRM device.
3001 	 *
3002 	 * So when the device will be gone, one of the first thing we
3003 	 * will be doing will be to unregister the interrupt handler,
3004 	 * and then unregister the DRM device. drm_dev_enter() would
3005 	 * thus always succeed if we are here.
3006 	 */
3007 
3008 	vc4_hdmi->cec_rx_msg.len = 0;
3009 	cntrl1 = HDMI_READ(HDMI_CEC_CNTRL_1);
3010 	vc4_cec_read_msg(vc4_hdmi, cntrl1);
3011 	cntrl1 |= VC4_HDMI_CEC_CLEAR_RECEIVE_OFF;
3012 	HDMI_WRITE(HDMI_CEC_CNTRL_1, cntrl1);
3013 	cntrl1 &= ~VC4_HDMI_CEC_CLEAR_RECEIVE_OFF;
3014 
3015 	HDMI_WRITE(HDMI_CEC_CNTRL_1, cntrl1);
3016 
3017 	return IRQ_WAKE_THREAD;
3018 }
3019 
3020 static irqreturn_t vc4_cec_irq_handler_rx_bare(int irq, void *priv)
3021 {
3022 	struct vc4_hdmi *vc4_hdmi = priv;
3023 	irqreturn_t ret;
3024 
3025 	spin_lock(&vc4_hdmi->hw_lock);
3026 	ret = vc4_cec_irq_handler_rx_bare_locked(vc4_hdmi);
3027 	spin_unlock(&vc4_hdmi->hw_lock);
3028 
3029 	return ret;
3030 }
3031 
3032 static irqreturn_t vc4_cec_irq_handler(int irq, void *priv)
3033 {
3034 	struct vc4_hdmi *vc4_hdmi = priv;
3035 	u32 stat = HDMI_READ(HDMI_CEC_CPU_STATUS);
3036 	irqreturn_t ret;
3037 	u32 cntrl5;
3038 
3039 	/*
3040 	 * We don't need to protect the register access using
3041 	 * drm_dev_enter() there because the interrupt handler lifetime
3042 	 * is tied to the device itself, and not to the DRM device.
3043 	 *
3044 	 * So when the device will be gone, one of the first thing we
3045 	 * will be doing will be to unregister the interrupt handler,
3046 	 * and then unregister the DRM device. drm_dev_enter() would
3047 	 * thus always succeed if we are here.
3048 	 */
3049 
3050 	if (!(stat & VC4_HDMI_CPU_CEC))
3051 		return IRQ_NONE;
3052 
3053 	spin_lock(&vc4_hdmi->hw_lock);
3054 	cntrl5 = HDMI_READ(HDMI_CEC_CNTRL_5);
3055 	vc4_hdmi->cec_irq_was_rx = cntrl5 & VC4_HDMI_CEC_RX_CEC_INT;
3056 	if (vc4_hdmi->cec_irq_was_rx)
3057 		ret = vc4_cec_irq_handler_rx_bare_locked(vc4_hdmi);
3058 	else
3059 		ret = vc4_cec_irq_handler_tx_bare_locked(vc4_hdmi);
3060 
3061 	HDMI_WRITE(HDMI_CEC_CPU_CLEAR, VC4_HDMI_CPU_CEC);
3062 	spin_unlock(&vc4_hdmi->hw_lock);
3063 
3064 	return ret;
3065 }
3066 
3067 static int vc4_hdmi_cec_enable(struct cec_adapter *adap)
3068 {
3069 	struct vc4_hdmi *vc4_hdmi = cec_get_drvdata(adap);
3070 	struct drm_device *drm = vc4_hdmi->connector.dev;
3071 	/* clock period in microseconds */
3072 	const u32 usecs = 1000000 / CEC_CLOCK_FREQ;
3073 	unsigned long flags;
3074 	u32 val;
3075 	int ret;
3076 	int idx;
3077 
3078 	if (!drm_dev_enter(drm, &idx))
3079 		/*
3080 		 * We can't return an error code, because the CEC
3081 		 * framework will emit WARN_ON messages at unbind
3082 		 * otherwise.
3083 		 */
3084 		return 0;
3085 
3086 	ret = pm_runtime_resume_and_get(&vc4_hdmi->pdev->dev);
3087 	if (ret) {
3088 		drm_dev_exit(idx);
3089 		return ret;
3090 	}
3091 
3092 	mutex_lock(&vc4_hdmi->mutex);
3093 
3094 	spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
3095 
3096 	val = HDMI_READ(HDMI_CEC_CNTRL_5);
3097 	val &= ~(VC4_HDMI_CEC_TX_SW_RESET | VC4_HDMI_CEC_RX_SW_RESET |
3098 		 VC4_HDMI_CEC_CNT_TO_4700_US_MASK |
3099 		 VC4_HDMI_CEC_CNT_TO_4500_US_MASK);
3100 	val |= ((4700 / usecs) << VC4_HDMI_CEC_CNT_TO_4700_US_SHIFT) |
3101 	       ((4500 / usecs) << VC4_HDMI_CEC_CNT_TO_4500_US_SHIFT);
3102 
3103 	HDMI_WRITE(HDMI_CEC_CNTRL_5, val |
3104 		   VC4_HDMI_CEC_TX_SW_RESET | VC4_HDMI_CEC_RX_SW_RESET);
3105 	HDMI_WRITE(HDMI_CEC_CNTRL_5, val);
3106 	HDMI_WRITE(HDMI_CEC_CNTRL_2,
3107 		   ((1500 / usecs) << VC4_HDMI_CEC_CNT_TO_1500_US_SHIFT) |
3108 		   ((1300 / usecs) << VC4_HDMI_CEC_CNT_TO_1300_US_SHIFT) |
3109 		   ((800 / usecs) << VC4_HDMI_CEC_CNT_TO_800_US_SHIFT) |
3110 		   ((600 / usecs) << VC4_HDMI_CEC_CNT_TO_600_US_SHIFT) |
3111 		   ((400 / usecs) << VC4_HDMI_CEC_CNT_TO_400_US_SHIFT));
3112 	HDMI_WRITE(HDMI_CEC_CNTRL_3,
3113 		   ((2750 / usecs) << VC4_HDMI_CEC_CNT_TO_2750_US_SHIFT) |
3114 		   ((2400 / usecs) << VC4_HDMI_CEC_CNT_TO_2400_US_SHIFT) |
3115 		   ((2050 / usecs) << VC4_HDMI_CEC_CNT_TO_2050_US_SHIFT) |
3116 		   ((1700 / usecs) << VC4_HDMI_CEC_CNT_TO_1700_US_SHIFT));
3117 	HDMI_WRITE(HDMI_CEC_CNTRL_4,
3118 		   ((4300 / usecs) << VC4_HDMI_CEC_CNT_TO_4300_US_SHIFT) |
3119 		   ((3900 / usecs) << VC4_HDMI_CEC_CNT_TO_3900_US_SHIFT) |
3120 		   ((3600 / usecs) << VC4_HDMI_CEC_CNT_TO_3600_US_SHIFT) |
3121 		   ((3500 / usecs) << VC4_HDMI_CEC_CNT_TO_3500_US_SHIFT));
3122 
3123 	if (!vc4_hdmi->variant->external_irq_controller)
3124 		HDMI_WRITE(HDMI_CEC_CPU_MASK_CLEAR, VC4_HDMI_CPU_CEC);
3125 
3126 	spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
3127 
3128 	mutex_unlock(&vc4_hdmi->mutex);
3129 	drm_dev_exit(idx);
3130 
3131 	return 0;
3132 }
3133 
3134 static int vc4_hdmi_cec_disable(struct cec_adapter *adap)
3135 {
3136 	struct vc4_hdmi *vc4_hdmi = cec_get_drvdata(adap);
3137 	struct drm_device *drm = vc4_hdmi->connector.dev;
3138 	unsigned long flags;
3139 	int idx;
3140 
3141 	if (!drm_dev_enter(drm, &idx))
3142 		/*
3143 		 * We can't return an error code, because the CEC
3144 		 * framework will emit WARN_ON messages at unbind
3145 		 * otherwise.
3146 		 */
3147 		return 0;
3148 
3149 	mutex_lock(&vc4_hdmi->mutex);
3150 
3151 	spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
3152 
3153 	if (!vc4_hdmi->variant->external_irq_controller)
3154 		HDMI_WRITE(HDMI_CEC_CPU_MASK_SET, VC4_HDMI_CPU_CEC);
3155 
3156 	HDMI_WRITE(HDMI_CEC_CNTRL_5, HDMI_READ(HDMI_CEC_CNTRL_5) |
3157 		   VC4_HDMI_CEC_TX_SW_RESET | VC4_HDMI_CEC_RX_SW_RESET);
3158 
3159 	spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
3160 
3161 	mutex_unlock(&vc4_hdmi->mutex);
3162 
3163 	pm_runtime_put(&vc4_hdmi->pdev->dev);
3164 
3165 	drm_dev_exit(idx);
3166 
3167 	return 0;
3168 }
3169 
3170 static int vc4_hdmi_cec_adap_enable(struct cec_adapter *adap, bool enable)
3171 {
3172 	if (enable)
3173 		return vc4_hdmi_cec_enable(adap);
3174 	else
3175 		return vc4_hdmi_cec_disable(adap);
3176 }
3177 
3178 static int vc4_hdmi_cec_adap_log_addr(struct cec_adapter *adap, u8 log_addr)
3179 {
3180 	struct vc4_hdmi *vc4_hdmi = cec_get_drvdata(adap);
3181 	struct drm_device *drm = vc4_hdmi->connector.dev;
3182 	unsigned long flags;
3183 	int idx;
3184 
3185 	if (!drm_dev_enter(drm, &idx))
3186 		/*
3187 		 * We can't return an error code, because the CEC
3188 		 * framework will emit WARN_ON messages at unbind
3189 		 * otherwise.
3190 		 */
3191 		return 0;
3192 
3193 	mutex_lock(&vc4_hdmi->mutex);
3194 	spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
3195 	HDMI_WRITE(HDMI_CEC_CNTRL_1,
3196 		   (HDMI_READ(HDMI_CEC_CNTRL_1) & ~VC4_HDMI_CEC_ADDR_MASK) |
3197 		   (log_addr & 0xf) << VC4_HDMI_CEC_ADDR_SHIFT);
3198 	spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
3199 	mutex_unlock(&vc4_hdmi->mutex);
3200 
3201 	drm_dev_exit(idx);
3202 
3203 	return 0;
3204 }
3205 
3206 static int vc4_hdmi_cec_adap_transmit(struct cec_adapter *adap, u8 attempts,
3207 				      u32 signal_free_time, struct cec_msg *msg)
3208 {
3209 	struct vc4_hdmi *vc4_hdmi = cec_get_drvdata(adap);
3210 	struct drm_device *dev = vc4_hdmi->connector.dev;
3211 	unsigned long flags;
3212 	u32 val;
3213 	unsigned int i;
3214 	int idx;
3215 
3216 	if (!drm_dev_enter(dev, &idx))
3217 		return -ENODEV;
3218 
3219 	if (msg->len > 16) {
3220 		drm_err(dev, "Attempting to transmit too much data (%d)\n", msg->len);
3221 		drm_dev_exit(idx);
3222 		return -ENOMEM;
3223 	}
3224 
3225 	mutex_lock(&vc4_hdmi->mutex);
3226 
3227 	spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
3228 
3229 	for (i = 0; i < msg->len; i += 4)
3230 		HDMI_WRITE(HDMI_CEC_TX_DATA_1 + (i >> 2),
3231 			   (msg->msg[i]) |
3232 			   (msg->msg[i + 1] << 8) |
3233 			   (msg->msg[i + 2] << 16) |
3234 			   (msg->msg[i + 3] << 24));
3235 
3236 	val = HDMI_READ(HDMI_CEC_CNTRL_1);
3237 	val &= ~VC4_HDMI_CEC_START_XMIT_BEGIN;
3238 	HDMI_WRITE(HDMI_CEC_CNTRL_1, val);
3239 	val &= ~VC4_HDMI_CEC_MESSAGE_LENGTH_MASK;
3240 	val |= (msg->len - 1) << VC4_HDMI_CEC_MESSAGE_LENGTH_SHIFT;
3241 	val |= VC4_HDMI_CEC_START_XMIT_BEGIN;
3242 
3243 	HDMI_WRITE(HDMI_CEC_CNTRL_1, val);
3244 
3245 	spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
3246 	mutex_unlock(&vc4_hdmi->mutex);
3247 	drm_dev_exit(idx);
3248 
3249 	return 0;
3250 }
3251 
3252 static const struct cec_adap_ops vc4_hdmi_cec_adap_ops = {
3253 	.adap_enable = vc4_hdmi_cec_adap_enable,
3254 	.adap_log_addr = vc4_hdmi_cec_adap_log_addr,
3255 	.adap_transmit = vc4_hdmi_cec_adap_transmit,
3256 };
3257 
3258 static void vc4_hdmi_cec_release(void *ptr)
3259 {
3260 	struct vc4_hdmi *vc4_hdmi = ptr;
3261 
3262 	cec_unregister_adapter(vc4_hdmi->cec_adap);
3263 	vc4_hdmi->cec_adap = NULL;
3264 }
3265 
3266 static int vc4_hdmi_cec_init(struct vc4_hdmi *vc4_hdmi)
3267 {
3268 	struct cec_connector_info conn_info;
3269 	struct platform_device *pdev = vc4_hdmi->pdev;
3270 	struct device *dev = &pdev->dev;
3271 	int ret;
3272 
3273 	if (!of_property_present(dev->of_node, "interrupts")) {
3274 		dev_warn(dev, "'interrupts' DT property is missing, no CEC\n");
3275 		return 0;
3276 	}
3277 
3278 	vc4_hdmi->cec_adap = cec_allocate_adapter(&vc4_hdmi_cec_adap_ops,
3279 						  vc4_hdmi,
3280 						  vc4_hdmi->variant->card_name,
3281 						  CEC_CAP_DEFAULTS |
3282 						  CEC_CAP_CONNECTOR_INFO, 1);
3283 	ret = PTR_ERR_OR_ZERO(vc4_hdmi->cec_adap);
3284 	if (ret < 0)
3285 		return ret;
3286 
3287 	cec_fill_conn_info_from_drm(&conn_info, &vc4_hdmi->connector);
3288 	cec_s_conn_info(vc4_hdmi->cec_adap, &conn_info);
3289 
3290 	if (vc4_hdmi->variant->external_irq_controller) {
3291 		ret = devm_request_threaded_irq(dev, platform_get_irq_byname(pdev, "cec-rx"),
3292 						vc4_cec_irq_handler_rx_bare,
3293 						vc4_cec_irq_handler_rx_thread, 0,
3294 						"vc4 hdmi cec rx", vc4_hdmi);
3295 		if (ret)
3296 			goto err_delete_cec_adap;
3297 
3298 		ret = devm_request_threaded_irq(dev, platform_get_irq_byname(pdev, "cec-tx"),
3299 						vc4_cec_irq_handler_tx_bare,
3300 						vc4_cec_irq_handler_tx_thread, 0,
3301 						"vc4 hdmi cec tx", vc4_hdmi);
3302 		if (ret)
3303 			goto err_delete_cec_adap;
3304 	} else {
3305 		ret = devm_request_threaded_irq(dev, platform_get_irq(pdev, 0),
3306 						vc4_cec_irq_handler,
3307 						vc4_cec_irq_handler_thread, 0,
3308 						"vc4 hdmi cec", vc4_hdmi);
3309 		if (ret)
3310 			goto err_delete_cec_adap;
3311 	}
3312 
3313 	ret = cec_register_adapter(vc4_hdmi->cec_adap, &pdev->dev);
3314 	if (ret < 0)
3315 		goto err_delete_cec_adap;
3316 
3317 	/*
3318 	 * NOTE: Strictly speaking, we should probably use a DRM-managed
3319 	 * registration there to avoid removing the CEC adapter by the
3320 	 * time the DRM driver doesn't have any user anymore.
3321 	 *
3322 	 * However, the CEC framework already cleans up the CEC adapter
3323 	 * only when the last user has closed its file descriptor, so we
3324 	 * don't need to handle it in DRM.
3325 	 *
3326 	 * By the time the device-managed hook is executed, we will give
3327 	 * up our reference to the CEC adapter and therefore don't
3328 	 * really care when it's actually freed.
3329 	 *
3330 	 * There's still a problematic sequence: if we unregister our
3331 	 * CEC adapter, but the userspace keeps a handle on the CEC
3332 	 * adapter but not the DRM device for some reason. In such a
3333 	 * case, our vc4_hdmi structure will be freed, but the
3334 	 * cec_adapter structure will have a dangling pointer to what
3335 	 * used to be our HDMI controller. If we get a CEC call at that
3336 	 * moment, we could end up with a use-after-free. Fortunately,
3337 	 * the CEC framework already handles this too, by calling
3338 	 * cec_is_registered() in cec_ioctl() and cec_poll().
3339 	 */
3340 	ret = devm_add_action_or_reset(dev, vc4_hdmi_cec_release, vc4_hdmi);
3341 	if (ret)
3342 		return ret;
3343 
3344 	return 0;
3345 
3346 err_delete_cec_adap:
3347 	cec_delete_adapter(vc4_hdmi->cec_adap);
3348 
3349 	return ret;
3350 }
3351 #else
3352 static int vc4_hdmi_cec_init(struct vc4_hdmi *vc4_hdmi)
3353 {
3354 	return 0;
3355 }
3356 #endif
3357 
3358 static void vc4_hdmi_free_regset(struct drm_device *drm, void *ptr)
3359 {
3360 	struct debugfs_reg32 *regs = ptr;
3361 
3362 	kfree(regs);
3363 }
3364 
3365 static int vc4_hdmi_build_regset(struct drm_device *drm,
3366 				 struct vc4_hdmi *vc4_hdmi,
3367 				 struct debugfs_regset32 *regset,
3368 				 enum vc4_hdmi_regs reg)
3369 {
3370 	const struct vc4_hdmi_variant *variant = vc4_hdmi->variant;
3371 	struct debugfs_reg32 *regs, *new_regs;
3372 	unsigned int count = 0;
3373 	unsigned int i;
3374 	int ret;
3375 
3376 	regs = kcalloc(variant->num_registers, sizeof(*regs),
3377 		       GFP_KERNEL);
3378 	if (!regs)
3379 		return -ENOMEM;
3380 
3381 	for (i = 0; i < variant->num_registers; i++) {
3382 		const struct vc4_hdmi_register *field =	&variant->registers[i];
3383 
3384 		if (field->reg != reg)
3385 			continue;
3386 
3387 		regs[count].name = field->name;
3388 		regs[count].offset = field->offset;
3389 		count++;
3390 	}
3391 
3392 	new_regs = krealloc(regs, count * sizeof(*regs), GFP_KERNEL);
3393 	if (!new_regs)
3394 		return -ENOMEM;
3395 
3396 	regset->base = __vc4_hdmi_get_field_base(vc4_hdmi, reg);
3397 	regset->regs = new_regs;
3398 	regset->nregs = count;
3399 
3400 	ret = drmm_add_action_or_reset(drm, vc4_hdmi_free_regset, new_regs);
3401 	if (ret)
3402 		return ret;
3403 
3404 	return 0;
3405 }
3406 
3407 static int vc4_hdmi_init_resources(struct drm_device *drm,
3408 				   struct vc4_hdmi *vc4_hdmi)
3409 {
3410 	struct platform_device *pdev = vc4_hdmi->pdev;
3411 	struct device *dev = &pdev->dev;
3412 	int ret;
3413 
3414 	vc4_hdmi->hdmicore_regs = vc4_ioremap_regs(pdev, 0);
3415 	if (IS_ERR(vc4_hdmi->hdmicore_regs))
3416 		return PTR_ERR(vc4_hdmi->hdmicore_regs);
3417 
3418 	vc4_hdmi->hd_regs = vc4_ioremap_regs(pdev, 1);
3419 	if (IS_ERR(vc4_hdmi->hd_regs))
3420 		return PTR_ERR(vc4_hdmi->hd_regs);
3421 
3422 	ret = vc4_hdmi_build_regset(drm, vc4_hdmi, &vc4_hdmi->hd_regset, VC4_HD);
3423 	if (ret)
3424 		return ret;
3425 
3426 	ret = vc4_hdmi_build_regset(drm, vc4_hdmi, &vc4_hdmi->hdmi_regset, VC4_HDMI);
3427 	if (ret)
3428 		return ret;
3429 
3430 	vc4_hdmi->pixel_clock = devm_clk_get(dev, "pixel");
3431 	if (IS_ERR(vc4_hdmi->pixel_clock)) {
3432 		ret = PTR_ERR(vc4_hdmi->pixel_clock);
3433 		if (ret != -EPROBE_DEFER)
3434 			DRM_ERROR("Failed to get pixel clock\n");
3435 		return ret;
3436 	}
3437 
3438 	vc4_hdmi->hsm_clock = devm_clk_get(dev, "hdmi");
3439 	if (IS_ERR(vc4_hdmi->hsm_clock)) {
3440 		DRM_ERROR("Failed to get HDMI state machine clock\n");
3441 		return PTR_ERR(vc4_hdmi->hsm_clock);
3442 	}
3443 	vc4_hdmi->audio_clock = vc4_hdmi->hsm_clock;
3444 	vc4_hdmi->cec_clock = vc4_hdmi->hsm_clock;
3445 
3446 	return 0;
3447 }
3448 
3449 static int vc5_hdmi_init_resources(struct drm_device *drm,
3450 				   struct vc4_hdmi *vc4_hdmi)
3451 {
3452 	struct platform_device *pdev = vc4_hdmi->pdev;
3453 	struct device *dev = &pdev->dev;
3454 	struct resource *res;
3455 	int ret;
3456 
3457 	res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "hdmi");
3458 	if (!res)
3459 		return -ENODEV;
3460 
3461 	vc4_hdmi->hdmicore_regs = devm_ioremap(dev, res->start,
3462 					       resource_size(res));
3463 	if (!vc4_hdmi->hdmicore_regs)
3464 		return -ENOMEM;
3465 
3466 	res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "hd");
3467 	if (!res)
3468 		return -ENODEV;
3469 
3470 	vc4_hdmi->hd_regs = devm_ioremap(dev, res->start, resource_size(res));
3471 	if (!vc4_hdmi->hd_regs)
3472 		return -ENOMEM;
3473 
3474 	res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "cec");
3475 	if (!res)
3476 		return -ENODEV;
3477 
3478 	vc4_hdmi->cec_regs = devm_ioremap(dev, res->start, resource_size(res));
3479 	if (!vc4_hdmi->cec_regs)
3480 		return -ENOMEM;
3481 
3482 	res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "csc");
3483 	if (!res)
3484 		return -ENODEV;
3485 
3486 	vc4_hdmi->csc_regs = devm_ioremap(dev, res->start, resource_size(res));
3487 	if (!vc4_hdmi->csc_regs)
3488 		return -ENOMEM;
3489 
3490 	res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "dvp");
3491 	if (!res)
3492 		return -ENODEV;
3493 
3494 	vc4_hdmi->dvp_regs = devm_ioremap(dev, res->start, resource_size(res));
3495 	if (!vc4_hdmi->dvp_regs)
3496 		return -ENOMEM;
3497 
3498 	res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "phy");
3499 	if (!res)
3500 		return -ENODEV;
3501 
3502 	vc4_hdmi->phy_regs = devm_ioremap(dev, res->start, resource_size(res));
3503 	if (!vc4_hdmi->phy_regs)
3504 		return -ENOMEM;
3505 
3506 	res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "packet");
3507 	if (!res)
3508 		return -ENODEV;
3509 
3510 	vc4_hdmi->ram_regs = devm_ioremap(dev, res->start, resource_size(res));
3511 	if (!vc4_hdmi->ram_regs)
3512 		return -ENOMEM;
3513 
3514 	res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "rm");
3515 	if (!res)
3516 		return -ENODEV;
3517 
3518 	vc4_hdmi->rm_regs = devm_ioremap(dev, res->start, resource_size(res));
3519 	if (!vc4_hdmi->rm_regs)
3520 		return -ENOMEM;
3521 
3522 	vc4_hdmi->hsm_clock = devm_clk_get(dev, "hdmi");
3523 	if (IS_ERR(vc4_hdmi->hsm_clock)) {
3524 		DRM_ERROR("Failed to get HDMI state machine clock\n");
3525 		return PTR_ERR(vc4_hdmi->hsm_clock);
3526 	}
3527 
3528 	vc4_hdmi->pixel_bvb_clock = devm_clk_get(dev, "bvb");
3529 	if (IS_ERR(vc4_hdmi->pixel_bvb_clock)) {
3530 		DRM_ERROR("Failed to get pixel bvb clock\n");
3531 		return PTR_ERR(vc4_hdmi->pixel_bvb_clock);
3532 	}
3533 
3534 	vc4_hdmi->audio_clock = devm_clk_get(dev, "audio");
3535 	if (IS_ERR(vc4_hdmi->audio_clock)) {
3536 		DRM_ERROR("Failed to get audio clock\n");
3537 		return PTR_ERR(vc4_hdmi->audio_clock);
3538 	}
3539 
3540 	vc4_hdmi->cec_clock = devm_clk_get(dev, "cec");
3541 	if (IS_ERR(vc4_hdmi->cec_clock)) {
3542 		DRM_ERROR("Failed to get CEC clock\n");
3543 		return PTR_ERR(vc4_hdmi->cec_clock);
3544 	}
3545 
3546 	vc4_hdmi->reset = devm_reset_control_get(dev, NULL);
3547 	if (IS_ERR(vc4_hdmi->reset)) {
3548 		DRM_ERROR("Failed to get HDMI reset line\n");
3549 		return PTR_ERR(vc4_hdmi->reset);
3550 	}
3551 
3552 	ret = vc4_hdmi_build_regset(drm, vc4_hdmi, &vc4_hdmi->hdmi_regset, VC4_HDMI);
3553 	if (ret)
3554 		return ret;
3555 
3556 	ret = vc4_hdmi_build_regset(drm, vc4_hdmi, &vc4_hdmi->hd_regset, VC4_HD);
3557 	if (ret)
3558 		return ret;
3559 
3560 	ret = vc4_hdmi_build_regset(drm, vc4_hdmi, &vc4_hdmi->cec_regset, VC5_CEC);
3561 	if (ret)
3562 		return ret;
3563 
3564 	ret = vc4_hdmi_build_regset(drm, vc4_hdmi, &vc4_hdmi->csc_regset, VC5_CSC);
3565 	if (ret)
3566 		return ret;
3567 
3568 	ret = vc4_hdmi_build_regset(drm, vc4_hdmi, &vc4_hdmi->dvp_regset, VC5_DVP);
3569 	if (ret)
3570 		return ret;
3571 
3572 	ret = vc4_hdmi_build_regset(drm, vc4_hdmi, &vc4_hdmi->phy_regset, VC5_PHY);
3573 	if (ret)
3574 		return ret;
3575 
3576 	ret = vc4_hdmi_build_regset(drm, vc4_hdmi, &vc4_hdmi->ram_regset, VC5_RAM);
3577 	if (ret)
3578 		return ret;
3579 
3580 	ret = vc4_hdmi_build_regset(drm, vc4_hdmi, &vc4_hdmi->rm_regset, VC5_RM);
3581 	if (ret)
3582 		return ret;
3583 
3584 	return 0;
3585 }
3586 
3587 static int vc4_hdmi_runtime_suspend(struct device *dev)
3588 {
3589 	struct vc4_hdmi *vc4_hdmi = dev_get_drvdata(dev);
3590 
3591 	clk_disable_unprepare(vc4_hdmi->hsm_clock);
3592 
3593 	return 0;
3594 }
3595 
3596 static int vc4_hdmi_runtime_resume(struct device *dev)
3597 {
3598 	struct vc4_hdmi *vc4_hdmi = dev_get_drvdata(dev);
3599 	unsigned long __maybe_unused flags;
3600 	u32 __maybe_unused value;
3601 	unsigned long rate;
3602 	int ret;
3603 
3604 	ret = clk_prepare_enable(vc4_hdmi->hsm_clock);
3605 	if (ret)
3606 		return ret;
3607 
3608 	/*
3609 	 * Whenever the RaspberryPi boots without an HDMI monitor
3610 	 * plugged in, the firmware won't have initialized the HSM clock
3611 	 * rate and it will be reported as 0.
3612 	 *
3613 	 * If we try to access a register of the controller in such a
3614 	 * case, it will lead to a silent CPU stall. Let's make sure we
3615 	 * prevent such a case.
3616 	 */
3617 	rate = clk_get_rate(vc4_hdmi->hsm_clock);
3618 	if (!rate) {
3619 		ret = -EINVAL;
3620 		goto err_disable_clk;
3621 	}
3622 
3623 	if (vc4_hdmi->variant->reset)
3624 		vc4_hdmi->variant->reset(vc4_hdmi);
3625 
3626 #ifdef CONFIG_DRM_VC4_HDMI_CEC
3627 	spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
3628 	value = HDMI_READ(HDMI_CEC_CNTRL_1);
3629 	/* Set the logical address to Unregistered */
3630 	value |= VC4_HDMI_CEC_ADDR_MASK;
3631 	HDMI_WRITE(HDMI_CEC_CNTRL_1, value);
3632 	spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
3633 
3634 	vc4_hdmi_cec_update_clk_div(vc4_hdmi);
3635 
3636 	if (!vc4_hdmi->variant->external_irq_controller) {
3637 		spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
3638 		HDMI_WRITE(HDMI_CEC_CPU_MASK_SET, 0xffffffff);
3639 		spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
3640 	}
3641 #endif
3642 
3643 	return 0;
3644 
3645 err_disable_clk:
3646 	clk_disable_unprepare(vc4_hdmi->hsm_clock);
3647 	return ret;
3648 }
3649 
3650 static void vc4_hdmi_put_ddc_device(void *ptr)
3651 {
3652 	struct vc4_hdmi *vc4_hdmi = ptr;
3653 
3654 	put_device(&vc4_hdmi->ddc->dev);
3655 }
3656 
3657 static int vc4_hdmi_bind(struct device *dev, struct device *master, void *data)
3658 {
3659 	const struct vc4_hdmi_variant *variant = of_device_get_match_data(dev);
3660 	struct platform_device *pdev = to_platform_device(dev);
3661 	struct drm_device *drm = dev_get_drvdata(master);
3662 	struct vc4_hdmi *vc4_hdmi;
3663 	struct drm_encoder *encoder;
3664 	struct device_node *ddc_node;
3665 	int ret;
3666 
3667 	vc4_hdmi = drmm_kzalloc(drm, sizeof(*vc4_hdmi), GFP_KERNEL);
3668 	if (!vc4_hdmi)
3669 		return -ENOMEM;
3670 
3671 	ret = drmm_mutex_init(drm, &vc4_hdmi->mutex);
3672 	if (ret)
3673 		return ret;
3674 
3675 	spin_lock_init(&vc4_hdmi->hw_lock);
3676 	INIT_DELAYED_WORK(&vc4_hdmi->scrambling_work, vc4_hdmi_scrambling_wq);
3677 
3678 	dev_set_drvdata(dev, vc4_hdmi);
3679 	encoder = &vc4_hdmi->encoder.base;
3680 	vc4_hdmi->encoder.type = variant->encoder_type;
3681 	vc4_hdmi->encoder.pre_crtc_configure = vc4_hdmi_encoder_pre_crtc_configure;
3682 	vc4_hdmi->encoder.pre_crtc_enable = vc4_hdmi_encoder_pre_crtc_enable;
3683 	vc4_hdmi->encoder.post_crtc_enable = vc4_hdmi_encoder_post_crtc_enable;
3684 	vc4_hdmi->encoder.post_crtc_disable = vc4_hdmi_encoder_post_crtc_disable;
3685 	vc4_hdmi->encoder.post_crtc_powerdown = vc4_hdmi_encoder_post_crtc_powerdown;
3686 	vc4_hdmi->pdev = pdev;
3687 	vc4_hdmi->variant = variant;
3688 
3689 	/*
3690 	 * Since we don't know the state of the controller and its
3691 	 * display (if any), let's assume it's always enabled.
3692 	 * vc4_hdmi_disable_scrambling() will thus run at boot, make
3693 	 * sure it's disabled, and avoid any inconsistency.
3694 	 */
3695 	if (variant->max_pixel_clock > HDMI_14_MAX_TMDS_CLK)
3696 		vc4_hdmi->scdc_enabled = true;
3697 
3698 	ret = variant->init_resources(drm, vc4_hdmi);
3699 	if (ret)
3700 		return ret;
3701 
3702 	ddc_node = of_parse_phandle(dev->of_node, "ddc", 0);
3703 	if (!ddc_node) {
3704 		DRM_ERROR("Failed to find ddc node in device tree\n");
3705 		return -ENODEV;
3706 	}
3707 
3708 	vc4_hdmi->ddc = of_find_i2c_adapter_by_node(ddc_node);
3709 	of_node_put(ddc_node);
3710 	if (!vc4_hdmi->ddc) {
3711 		DRM_DEBUG("Failed to get ddc i2c adapter by node\n");
3712 		return -EPROBE_DEFER;
3713 	}
3714 
3715 	ret = devm_add_action_or_reset(dev, vc4_hdmi_put_ddc_device, vc4_hdmi);
3716 	if (ret)
3717 		return ret;
3718 
3719 	/* Only use the GPIO HPD pin if present in the DT, otherwise
3720 	 * we'll use the HDMI core's register.
3721 	 */
3722 	vc4_hdmi->hpd_gpio = devm_gpiod_get_optional(dev, "hpd", GPIOD_IN);
3723 	if (IS_ERR(vc4_hdmi->hpd_gpio)) {
3724 		return PTR_ERR(vc4_hdmi->hpd_gpio);
3725 	}
3726 
3727 	vc4_hdmi->disable_wifi_frequencies =
3728 		of_property_read_bool(dev->of_node, "wifi-2.4ghz-coexistence");
3729 
3730 	ret = devm_pm_runtime_enable(dev);
3731 	if (ret)
3732 		return ret;
3733 
3734 	/*
3735 	 *  We need to have the device powered up at this point to call
3736 	 *  our reset hook and for the CEC init.
3737 	 */
3738 	ret = pm_runtime_resume_and_get(dev);
3739 	if (ret)
3740 		return ret;
3741 
3742 	if ((of_device_is_compatible(dev->of_node, "brcm,bcm2711-hdmi0") ||
3743 	     of_device_is_compatible(dev->of_node, "brcm,bcm2711-hdmi1")) &&
3744 	    HDMI_READ(HDMI_VID_CTL) & VC4_HD_VID_CTL_ENABLE) {
3745 		clk_prepare_enable(vc4_hdmi->pixel_clock);
3746 		clk_prepare_enable(vc4_hdmi->hsm_clock);
3747 		clk_prepare_enable(vc4_hdmi->pixel_bvb_clock);
3748 	}
3749 
3750 	ret = drmm_encoder_init(drm, encoder,
3751 				&vc4_hdmi_encoder_funcs,
3752 				DRM_MODE_ENCODER_TMDS,
3753 				NULL);
3754 	if (ret)
3755 		goto err_put_runtime_pm;
3756 
3757 	drm_encoder_helper_add(encoder, &vc4_hdmi_encoder_helper_funcs);
3758 
3759 	ret = vc4_hdmi_connector_init(drm, vc4_hdmi);
3760 	if (ret)
3761 		goto err_put_runtime_pm;
3762 
3763 	ret = vc4_hdmi_hotplug_init(vc4_hdmi);
3764 	if (ret)
3765 		goto err_put_runtime_pm;
3766 
3767 	ret = vc4_hdmi_cec_init(vc4_hdmi);
3768 	if (ret)
3769 		goto err_put_runtime_pm;
3770 
3771 	ret = vc4_hdmi_audio_init(vc4_hdmi);
3772 	if (ret)
3773 		goto err_put_runtime_pm;
3774 
3775 	pm_runtime_put_sync(dev);
3776 
3777 	return 0;
3778 
3779 err_put_runtime_pm:
3780 	pm_runtime_put_sync(dev);
3781 
3782 	return ret;
3783 }
3784 
3785 static const struct component_ops vc4_hdmi_ops = {
3786 	.bind   = vc4_hdmi_bind,
3787 };
3788 
3789 static int vc4_hdmi_dev_probe(struct platform_device *pdev)
3790 {
3791 	return component_add(&pdev->dev, &vc4_hdmi_ops);
3792 }
3793 
3794 static void vc4_hdmi_dev_remove(struct platform_device *pdev)
3795 {
3796 	component_del(&pdev->dev, &vc4_hdmi_ops);
3797 }
3798 
3799 static const struct vc4_hdmi_variant bcm2835_variant = {
3800 	.encoder_type		= VC4_ENCODER_TYPE_HDMI0,
3801 	.debugfs_name		= "hdmi_regs",
3802 	.card_name		= "vc4-hdmi",
3803 	.max_pixel_clock	= 162000000,
3804 	.registers		= vc4_hdmi_fields,
3805 	.num_registers		= ARRAY_SIZE(vc4_hdmi_fields),
3806 
3807 	.init_resources		= vc4_hdmi_init_resources,
3808 	.csc_setup		= vc4_hdmi_csc_setup,
3809 	.reset			= vc4_hdmi_reset,
3810 	.set_timings		= vc4_hdmi_set_timings,
3811 	.phy_init		= vc4_hdmi_phy_init,
3812 	.phy_disable		= vc4_hdmi_phy_disable,
3813 	.phy_rng_enable		= vc4_hdmi_phy_rng_enable,
3814 	.phy_rng_disable	= vc4_hdmi_phy_rng_disable,
3815 	.channel_map		= vc4_hdmi_channel_map,
3816 	.supports_hdr		= false,
3817 };
3818 
3819 static const struct vc4_hdmi_variant bcm2711_hdmi0_variant = {
3820 	.encoder_type		= VC4_ENCODER_TYPE_HDMI0,
3821 	.debugfs_name		= "hdmi0_regs",
3822 	.card_name		= "vc4-hdmi-0",
3823 	.max_pixel_clock	= 600000000,
3824 	.registers		= vc5_hdmi_hdmi0_fields,
3825 	.num_registers		= ARRAY_SIZE(vc5_hdmi_hdmi0_fields),
3826 	.phy_lane_mapping	= {
3827 		PHY_LANE_0,
3828 		PHY_LANE_1,
3829 		PHY_LANE_2,
3830 		PHY_LANE_CK,
3831 	},
3832 	.unsupported_odd_h_timings	= true,
3833 	.external_irq_controller	= true,
3834 
3835 	.init_resources		= vc5_hdmi_init_resources,
3836 	.csc_setup		= vc5_hdmi_csc_setup,
3837 	.reset			= vc5_hdmi_reset,
3838 	.set_timings		= vc5_hdmi_set_timings,
3839 	.phy_init		= vc5_hdmi_phy_init,
3840 	.phy_disable		= vc5_hdmi_phy_disable,
3841 	.phy_rng_enable		= vc5_hdmi_phy_rng_enable,
3842 	.phy_rng_disable	= vc5_hdmi_phy_rng_disable,
3843 	.channel_map		= vc5_hdmi_channel_map,
3844 	.supports_hdr		= true,
3845 	.hp_detect		= vc5_hdmi_hp_detect,
3846 };
3847 
3848 static const struct vc4_hdmi_variant bcm2711_hdmi1_variant = {
3849 	.encoder_type		= VC4_ENCODER_TYPE_HDMI1,
3850 	.debugfs_name		= "hdmi1_regs",
3851 	.card_name		= "vc4-hdmi-1",
3852 	.max_pixel_clock	= HDMI_14_MAX_TMDS_CLK,
3853 	.registers		= vc5_hdmi_hdmi1_fields,
3854 	.num_registers		= ARRAY_SIZE(vc5_hdmi_hdmi1_fields),
3855 	.phy_lane_mapping	= {
3856 		PHY_LANE_1,
3857 		PHY_LANE_0,
3858 		PHY_LANE_CK,
3859 		PHY_LANE_2,
3860 	},
3861 	.unsupported_odd_h_timings	= true,
3862 	.external_irq_controller	= true,
3863 
3864 	.init_resources		= vc5_hdmi_init_resources,
3865 	.csc_setup		= vc5_hdmi_csc_setup,
3866 	.reset			= vc5_hdmi_reset,
3867 	.set_timings		= vc5_hdmi_set_timings,
3868 	.phy_init		= vc5_hdmi_phy_init,
3869 	.phy_disable		= vc5_hdmi_phy_disable,
3870 	.phy_rng_enable		= vc5_hdmi_phy_rng_enable,
3871 	.phy_rng_disable	= vc5_hdmi_phy_rng_disable,
3872 	.channel_map		= vc5_hdmi_channel_map,
3873 	.supports_hdr		= true,
3874 	.hp_detect		= vc5_hdmi_hp_detect,
3875 };
3876 
3877 static const struct of_device_id vc4_hdmi_dt_match[] = {
3878 	{ .compatible = "brcm,bcm2835-hdmi", .data = &bcm2835_variant },
3879 	{ .compatible = "brcm,bcm2711-hdmi0", .data = &bcm2711_hdmi0_variant },
3880 	{ .compatible = "brcm,bcm2711-hdmi1", .data = &bcm2711_hdmi1_variant },
3881 	{}
3882 };
3883 
3884 static const struct dev_pm_ops vc4_hdmi_pm_ops = {
3885 	SET_RUNTIME_PM_OPS(vc4_hdmi_runtime_suspend,
3886 			   vc4_hdmi_runtime_resume,
3887 			   NULL)
3888 };
3889 
3890 struct platform_driver vc4_hdmi_driver = {
3891 	.probe = vc4_hdmi_dev_probe,
3892 	.remove_new = vc4_hdmi_dev_remove,
3893 	.driver = {
3894 		.name = "vc4_hdmi",
3895 		.of_match_table = vc4_hdmi_dt_match,
3896 		.pm = &vc4_hdmi_pm_ops,
3897 	},
3898 };
3899