8c0c0b5495c8005d637c309075157074008e1e2a
[platform/kernel/linux-rpi.git] / drivers / gpu / drm / vc4 / vc4_hdmi.c
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/drm_atomic_helper.h>
35 #include <drm/drm_drv.h>
36 #include <drm/drm_edid.h>
37 #include <drm/drm_probe_helper.h>
38 #include <drm/drm_simple_kms_helper.h>
39 #include <drm/drm_scdc_helper.h>
40 #include <linux/clk.h>
41 #include <linux/component.h>
42 #include <linux/gpio/consumer.h>
43 #include <linux/extcon-provider.h>
44 #include <linux/i2c.h>
45 #include <linux/module.h>
46 #include <linux/moduleparam.h>
47 #include <linux/of_address.h>
48 #include <linux/of_gpio.h>
49 #include <linux/of_platform.h>
50 #include <linux/pm_runtime.h>
51 #include <linux/rational.h>
52 #include <linux/reset.h>
53 #include <sound/dmaengine_pcm.h>
54 #include <sound/hdmi-codec.h>
55 #include <sound/pcm_drm_eld.h>
56 #include <sound/pcm_params.h>
57 #include <sound/soc.h>
58 #include "media/cec.h"
59 #include "vc4_drv.h"
60 #include "vc4_hdmi.h"
61 #include "vc4_hdmi_regs.h"
62 #include "vc4_regs.h"
63
64 /*
65  * "Broadcast RGB" property.
66  * Allows overriding of HDMI full or limited range RGB
67  */
68 #define VC4_BROADCAST_RGB_AUTO 0
69 #define VC4_BROADCAST_RGB_FULL 1
70 #define VC4_BROADCAST_RGB_LIMITED 2
71
72 #define VC5_HDMI_HORZA_HFP_SHIFT                16
73 #define VC5_HDMI_HORZA_HFP_MASK                 VC4_MASK(28, 16)
74 #define VC5_HDMI_HORZA_VPOS                     BIT(15)
75 #define VC5_HDMI_HORZA_HPOS                     BIT(14)
76 #define VC5_HDMI_HORZA_HAP_SHIFT                0
77 #define VC5_HDMI_HORZA_HAP_MASK                 VC4_MASK(13, 0)
78
79 #define VC5_HDMI_HORZB_HBP_SHIFT                16
80 #define VC5_HDMI_HORZB_HBP_MASK                 VC4_MASK(26, 16)
81 #define VC5_HDMI_HORZB_HSP_SHIFT                0
82 #define VC5_HDMI_HORZB_HSP_MASK                 VC4_MASK(10, 0)
83
84 #define VC5_HDMI_VERTA_VSP_SHIFT                24
85 #define VC5_HDMI_VERTA_VSP_MASK                 VC4_MASK(28, 24)
86 #define VC5_HDMI_VERTA_VFP_SHIFT                16
87 #define VC5_HDMI_VERTA_VFP_MASK                 VC4_MASK(22, 16)
88 #define VC5_HDMI_VERTA_VAL_SHIFT                0
89 #define VC5_HDMI_VERTA_VAL_MASK                 VC4_MASK(12, 0)
90
91 #define VC5_HDMI_VERTB_VSPO_SHIFT               16
92 #define VC5_HDMI_VERTB_VSPO_MASK                VC4_MASK(29, 16)
93
94 #define VC4_HDMI_MISC_CONTROL_PIXEL_REP_SHIFT   0
95 #define VC4_HDMI_MISC_CONTROL_PIXEL_REP_MASK    VC4_MASK(3, 0)
96 #define VC5_HDMI_MISC_CONTROL_PIXEL_REP_SHIFT   0
97 #define VC5_HDMI_MISC_CONTROL_PIXEL_REP_MASK    VC4_MASK(3, 0)
98
99 #define VC5_HDMI_SCRAMBLER_CTL_ENABLE           BIT(0)
100
101 #define VC5_HDMI_DEEP_COLOR_CONFIG_1_INIT_PACK_PHASE_SHIFT      8
102 #define VC5_HDMI_DEEP_COLOR_CONFIG_1_INIT_PACK_PHASE_MASK       VC4_MASK(10, 8)
103
104 #define VC5_HDMI_DEEP_COLOR_CONFIG_1_COLOR_DEPTH_SHIFT          0
105 #define VC5_HDMI_DEEP_COLOR_CONFIG_1_COLOR_DEPTH_MASK           VC4_MASK(3, 0)
106
107 #define VC5_HDMI_GCP_CONFIG_GCP_ENABLE          BIT(31)
108
109 #define VC5_HDMI_GCP_WORD_1_GCP_SUBPACKET_BYTE_1_SHIFT  8
110 #define VC5_HDMI_GCP_WORD_1_GCP_SUBPACKET_BYTE_1_MASK   VC4_MASK(15, 8)
111
112 #define VC5_HDMI_GCP_WORD_1_GCP_SUBPACKET_BYTE_0_MASK   VC4_MASK(7, 0)
113 #define VC5_HDMI_GCP_WORD_1_GCP_SUBPACKET_BYTE_0_SET_AVMUTE     BIT(0)
114 #define VC5_HDMI_GCP_WORD_1_GCP_SUBPACKET_BYTE_0_CLEAR_AVMUTE   BIT(4)
115
116 # define VC4_HD_M_SW_RST                        BIT(2)
117 # define VC4_HD_M_ENABLE                        BIT(0)
118
119 #define HSM_MIN_CLOCK_FREQ      120000000
120 #define CEC_CLOCK_FREQ 40000
121
122 #define HDMI_14_MAX_TMDS_CLK   (340 * 1000 * 1000)
123
124 /* bit field to force hotplug detection. bit0 = HDMI0 */
125 static int force_hotplug = 0;
126 module_param(force_hotplug, int, 0644);
127
128 static const char * const output_format_str[] = {
129         [VC4_HDMI_OUTPUT_RGB]           = "RGB",
130         [VC4_HDMI_OUTPUT_YUV420]        = "YUV 4:2:0",
131         [VC4_HDMI_OUTPUT_YUV422]        = "YUV 4:2:2",
132         [VC4_HDMI_OUTPUT_YUV444]        = "YUV 4:4:4",
133 };
134
135 static const char *vc4_hdmi_output_fmt_str(enum vc4_hdmi_output_format fmt)
136 {
137         if (fmt >= ARRAY_SIZE(output_format_str))
138                 return "invalid";
139
140         return output_format_str[fmt];
141 }
142
143 static unsigned long long
144 vc4_hdmi_encoder_compute_mode_clock(const struct drm_display_mode *mode,
145                                     unsigned int bpc, enum vc4_hdmi_output_format fmt);
146
147 static bool vc4_hdmi_supports_scrambling(struct drm_encoder *encoder)
148 {
149         struct vc4_hdmi *vc4_hdmi = encoder_to_vc4_hdmi(encoder);
150         struct drm_display_info *display = &vc4_hdmi->connector.display_info;
151
152         lockdep_assert_held(&vc4_hdmi->mutex);
153
154         if (!display->is_hdmi)
155                 return false;
156
157         if (!display->hdmi.scdc.supported ||
158             !display->hdmi.scdc.scrambling.supported)
159                 return false;
160
161         return true;
162 }
163
164 static bool vc4_hdmi_mode_needs_scrambling(const struct drm_display_mode *mode,
165                                            unsigned int bpc,
166                                            enum vc4_hdmi_output_format fmt)
167 {
168         unsigned long long clock = vc4_hdmi_encoder_compute_mode_clock(mode, bpc, fmt);
169
170         return clock > HDMI_14_MAX_TMDS_CLK;
171 }
172
173 static bool vc4_hdmi_is_full_range(struct vc4_hdmi *vc4_hdmi,
174                                    const struct drm_display_mode *mode)
175 {
176         struct drm_display_info *display = &vc4_hdmi->connector.display_info;
177
178         if (vc4_hdmi->broadcast_rgb == VC4_BROADCAST_RGB_LIMITED)
179                 return false;
180         else if (vc4_hdmi->broadcast_rgb == VC4_BROADCAST_RGB_FULL)
181                 return true;
182         return !display->is_hdmi ||
183                 drm_default_rgb_quant_range(mode) == HDMI_QUANTIZATION_RANGE_FULL;
184 }
185
186 static int vc4_hdmi_debugfs_regs(struct seq_file *m, void *unused)
187 {
188         struct drm_info_node *node = (struct drm_info_node *)m->private;
189         struct vc4_hdmi *vc4_hdmi = node->info_ent->data;
190         struct drm_device *drm = vc4_hdmi->connector.dev;
191         struct drm_printer p = drm_seq_file_printer(m);
192         int idx;
193
194         if (!drm_dev_enter(drm, &idx))
195                 return -ENODEV;
196
197         drm_print_regset32(&p, &vc4_hdmi->hdmi_regset);
198         drm_print_regset32(&p, &vc4_hdmi->hd_regset);
199         drm_print_regset32(&p, &vc4_hdmi->cec_regset);
200         drm_print_regset32(&p, &vc4_hdmi->csc_regset);
201         drm_print_regset32(&p, &vc4_hdmi->dvp_regset);
202         drm_print_regset32(&p, &vc4_hdmi->phy_regset);
203         drm_print_regset32(&p, &vc4_hdmi->ram_regset);
204         drm_print_regset32(&p, &vc4_hdmi->rm_regset);
205
206         drm_dev_exit(idx);
207
208         return 0;
209 }
210
211 static void vc4_hdmi_reset(struct vc4_hdmi *vc4_hdmi)
212 {
213         struct drm_device *drm = vc4_hdmi->connector.dev;
214         unsigned long flags;
215         int idx;
216
217         /*
218          * We can be called by our bind callback, when the
219          * connector->dev pointer might not be initialised yet.
220          */
221         if (drm && !drm_dev_enter(drm, &idx))
222                 return;
223
224         spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
225
226         HDMI_WRITE(HDMI_M_CTL, VC4_HD_M_SW_RST);
227         udelay(1);
228         HDMI_WRITE(HDMI_M_CTL, 0);
229
230         HDMI_WRITE(HDMI_M_CTL, VC4_HD_M_ENABLE);
231
232         HDMI_WRITE(HDMI_SW_RESET_CONTROL,
233                    VC4_HDMI_SW_RESET_HDMI |
234                    VC4_HDMI_SW_RESET_FORMAT_DETECT);
235
236         HDMI_WRITE(HDMI_SW_RESET_CONTROL, 0);
237
238         spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
239
240         if (drm)
241                 drm_dev_exit(idx);
242 }
243
244 static void vc5_hdmi_reset(struct vc4_hdmi *vc4_hdmi)
245 {
246         struct drm_device *drm = vc4_hdmi->connector.dev;
247         unsigned long flags;
248         int idx;
249
250         /*
251          * We can be called by our bind callback, when the
252          * connector->dev pointer might not be initialised yet.
253          */
254         if (drm && !drm_dev_enter(drm, &idx))
255                 return;
256
257         reset_control_reset(vc4_hdmi->reset);
258
259         spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
260
261         HDMI_WRITE(HDMI_DVP_CTL, 0);
262
263         HDMI_WRITE(HDMI_CLOCK_STOP,
264                    HDMI_READ(HDMI_CLOCK_STOP) | VC4_DVP_HT_CLOCK_STOP_PIXEL);
265
266         spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
267
268         if (drm)
269                 drm_dev_exit(idx);
270 }
271
272 #ifdef CONFIG_DRM_VC4_HDMI_CEC
273 static void vc4_hdmi_cec_update_clk_div(struct vc4_hdmi *vc4_hdmi)
274 {
275         struct drm_device *drm = vc4_hdmi->connector.dev;
276         unsigned long cec_rate;
277         unsigned long flags;
278         u16 clk_cnt;
279         u32 value;
280         int idx;
281
282         /*
283          * This function is called by our runtime_resume implementation
284          * and thus at bind time, when we haven't registered our
285          * connector yet and thus don't have a pointer to the DRM
286          * device.
287          */
288         if (drm && !drm_dev_enter(drm, &idx))
289                 return;
290
291         cec_rate = clk_get_rate(vc4_hdmi->cec_clock);
292
293         spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
294
295         value = HDMI_READ(HDMI_CEC_CNTRL_1);
296         value &= ~VC4_HDMI_CEC_DIV_CLK_CNT_MASK;
297
298         /*
299          * Set the clock divider: the hsm_clock rate and this divider
300          * setting will give a 40 kHz CEC clock.
301          */
302         clk_cnt = cec_rate / CEC_CLOCK_FREQ;
303         value |= clk_cnt << VC4_HDMI_CEC_DIV_CLK_CNT_SHIFT;
304         HDMI_WRITE(HDMI_CEC_CNTRL_1, value);
305
306         spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
307
308         if (drm)
309                 drm_dev_exit(idx);
310 }
311 #else
312 static void vc4_hdmi_cec_update_clk_div(struct vc4_hdmi *vc4_hdmi) {}
313 #endif
314
315 static int reset_pipe(struct drm_crtc *crtc,
316                         struct drm_modeset_acquire_ctx *ctx)
317 {
318         struct drm_atomic_state *state;
319         struct drm_crtc_state *crtc_state;
320         int ret;
321
322         state = drm_atomic_state_alloc(crtc->dev);
323         if (!state)
324                 return -ENOMEM;
325
326         state->acquire_ctx = ctx;
327
328         crtc_state = drm_atomic_get_crtc_state(state, crtc);
329         if (IS_ERR(crtc_state)) {
330                 ret = PTR_ERR(crtc_state);
331                 goto out;
332         }
333
334         crtc_state->connectors_changed = true;
335
336         ret = drm_atomic_commit(state);
337 out:
338         drm_atomic_state_put(state);
339
340         return ret;
341 }
342
343 static int vc4_hdmi_reset_link(struct drm_connector *connector,
344                                struct drm_modeset_acquire_ctx *ctx)
345 {
346         struct drm_device *drm = connector->dev;
347         struct vc4_hdmi *vc4_hdmi = connector_to_vc4_hdmi(connector);
348         struct drm_encoder *encoder = &vc4_hdmi->encoder.base;
349         struct drm_connector_state *conn_state;
350         struct drm_crtc_state *crtc_state;
351         struct drm_crtc *crtc;
352         bool scrambling_needed;
353         u8 config;
354         int ret;
355
356         if (!connector)
357                 return 0;
358
359         ret = drm_modeset_lock(&drm->mode_config.connection_mutex, ctx);
360         if (ret)
361                 return ret;
362
363         conn_state = connector->state;
364         crtc = conn_state->crtc;
365         if (!crtc)
366                 return 0;
367
368         ret = drm_modeset_lock(&crtc->mutex, ctx);
369         if (ret)
370                 return ret;
371
372         crtc_state = crtc->state;
373         if (!crtc_state->active)
374                 return 0;
375
376         if (!vc4_hdmi_supports_scrambling(encoder))
377                 return 0;
378
379         scrambling_needed = vc4_hdmi_mode_needs_scrambling(&vc4_hdmi->saved_adjusted_mode,
380                                                            vc4_hdmi->output_bpc,
381                                                            vc4_hdmi->output_format);
382         if (!scrambling_needed)
383                 return 0;
384
385         if (conn_state->commit &&
386             !try_wait_for_completion(&conn_state->commit->hw_done))
387                 return 0;
388
389         ret = drm_scdc_readb(connector->ddc, SCDC_TMDS_CONFIG, &config);
390         if (ret < 0) {
391                 drm_err(drm, "Failed to read TMDS config: %d\n", ret);
392                 return 0;
393         }
394
395         if (!!(config & SCDC_SCRAMBLING_ENABLE) == scrambling_needed)
396                 return 0;
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         struct edid *edid;
416         int ret;
417
418         /*
419          * NOTE: This function should really be called with
420          * vc4_hdmi->mutex held, but doing so results in reentrancy
421          * issues since cec_s_phys_addr_from_edid might call
422          * .adap_enable, which leads to that funtion being called with
423          * our mutex held.
424          *
425          * A similar situation occurs with
426          * drm_atomic_helper_connector_hdmi_reset_link() that will call
427          * into our KMS hooks if the scrambling was enabled.
428          *
429          * Concurrency isn't an issue at the moment since we don't share
430          * any state with any of the other frameworks so we can ignore
431          * the lock for now.
432          */
433
434         if (status == connector->status)
435                 return;
436
437         if (status == connector_status_disconnected) {
438                 cec_phys_addr_invalidate(vc4_hdmi->cec_adap);
439                 return;
440         }
441
442         edid = drm_get_edid(connector, vc4_hdmi->ddc);
443         if (!edid)
444                 return;
445
446         cec_s_phys_addr_from_edid(vc4_hdmi->cec_adap, edid);
447         kfree(edid);
448
449         vc4_hdmi_reset_link(connector, ctx);
450
451 #ifdef CONFIG_EXTCON
452         if (ret != vc4_hdmi->status) {
453                 extcon_set_state_sync(vc4_hdmi->edev, EXTCON_DISP_HDMI,
454                                       (status == connector_status_connected ?
455                                       true : false));
456                 vc4_hdmi->status = ret;
457         }
458 #endif
459 }
460
461 static int vc4_hdmi_connector_detect_ctx(struct drm_connector *connector,
462                                          struct drm_modeset_acquire_ctx *ctx,
463                                          bool force)
464 {
465         struct vc4_hdmi *vc4_hdmi = connector_to_vc4_hdmi(connector);
466         enum drm_connector_status status = connector_status_disconnected;
467
468         /*
469          * NOTE: This function should really take vc4_hdmi->mutex, but
470          * doing so results in reentrancy issues since
471          * vc4_hdmi_handle_hotplug() can call into other functions that
472          * would take the mutex while it's held here.
473          *
474          * Concurrency isn't an issue at the moment since we don't share
475          * any state with any of the other frameworks so we can ignore
476          * the lock for now.
477          */
478
479         WARN_ON(pm_runtime_resume_and_get(&vc4_hdmi->pdev->dev));
480
481         if (force_hotplug & BIT(vc4_hdmi->encoder.type - VC4_ENCODER_TYPE_HDMI0))
482                 status = connector_status_connected;
483         else if (vc4_hdmi->hpd_gpio) {
484                 if (gpiod_get_value_cansleep(vc4_hdmi->hpd_gpio))
485                         status = connector_status_connected;
486         } else {
487                 if (vc4_hdmi->variant->hp_detect &&
488                     vc4_hdmi->variant->hp_detect(vc4_hdmi))
489                         status = connector_status_connected;
490         }
491
492         vc4_hdmi_handle_hotplug(vc4_hdmi, ctx, status);
493         pm_runtime_put(&vc4_hdmi->pdev->dev);
494
495         return status;
496 }
497
498 static int vc4_hdmi_connector_get_modes(struct drm_connector *connector)
499 {
500         struct vc4_hdmi *vc4_hdmi = connector_to_vc4_hdmi(connector);
501         struct vc4_dev *vc4 = to_vc4_dev(connector->dev);
502         int ret = 0;
503         struct edid *edid;
504
505         /*
506          * NOTE: This function should really take vc4_hdmi->mutex, but
507          * doing so results in reentrancy issues since
508          * cec_s_phys_addr_from_edid might call .adap_enable, which
509          * leads to that funtion being called with our mutex held.
510          *
511          * Concurrency isn't an issue at the moment since we don't share
512          * any state with any of the other frameworks so we can ignore
513          * the lock for now.
514          */
515
516         edid = drm_get_edid(connector, vc4_hdmi->ddc);
517         cec_s_phys_addr_from_edid(vc4_hdmi->cec_adap, edid);
518         if (!edid)
519                 return -ENODEV;
520
521         drm_connector_update_edid_property(connector, edid);
522         ret = drm_add_edid_modes(connector, edid);
523         kfree(edid);
524
525         if (!vc4->hvs->vc5_hdmi_enable_hdmi_20) {
526                 struct drm_device *drm = connector->dev;
527                 const struct drm_display_mode *mode;
528
529                 list_for_each_entry(mode, &connector->probed_modes, head) {
530                         if (vc4_hdmi_mode_needs_scrambling(mode, 8, VC4_HDMI_OUTPUT_RGB)) {
531                                 drm_warn_once(drm, "The core clock cannot reach frequencies high enough to support 4k @ 60Hz.");
532                                 drm_warn_once(drm, "Please change your config.txt file to add hdmi_enable_4kp60.");
533                         }
534                 }
535         }
536
537         return ret;
538 }
539
540 static int vc4_hdmi_connector_atomic_check(struct drm_connector *connector,
541                                            struct drm_atomic_state *state)
542 {
543         struct drm_connector_state *old_state =
544                 drm_atomic_get_old_connector_state(state, connector);
545         struct vc4_hdmi_connector_state *old_vc4_state = conn_state_to_vc4_hdmi_conn_state(old_state);
546         struct drm_connector_state *new_state =
547                 drm_atomic_get_new_connector_state(state, connector);
548         struct vc4_hdmi_connector_state *new_vc4_state = conn_state_to_vc4_hdmi_conn_state(new_state);
549         struct drm_crtc *crtc = new_state->crtc;
550
551         if (!crtc)
552                 return 0;
553
554         if (old_state->colorspace != new_state->colorspace ||
555             old_vc4_state->broadcast_rgb != new_vc4_state->broadcast_rgb ||
556             old_vc4_state->requested_output_format != new_vc4_state->requested_output_format ||
557             !drm_connector_atomic_hdr_metadata_equal(old_state, new_state)) {
558                 struct drm_crtc_state *crtc_state;
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                 crtc_state->mode_changed = true;
565         }
566
567         return 0;
568 }
569
570 /**
571  * vc4_hdmi_connector_atomic_get_property - hook for
572  *                                              connector->atomic_get_property.
573  * @connector: Connector to get the property for.
574  * @state: Connector state to retrieve the property from.
575  * @property: Property to retrieve.
576  * @val: Return value for the property.
577  *
578  * Returns the atomic property value for a digital connector.
579  */
580 int vc4_hdmi_connector_get_property(struct drm_connector *connector,
581                                     const struct drm_connector_state *state,
582                                     struct drm_property *property,
583                                     uint64_t *val)
584 {
585         struct vc4_hdmi *vc4_hdmi = connector_to_vc4_hdmi(connector);
586         const struct vc4_hdmi_connector_state *vc4_conn_state =
587                                 const_conn_state_to_vc4_hdmi_conn_state(state);
588
589         if (property == vc4_hdmi->broadcast_rgb_property) {
590                 *val = vc4_conn_state->broadcast_rgb;
591         } else if (property == vc4_hdmi->output_format_property) {
592                 *val = vc4_conn_state->requested_output_format;
593         } else {
594                 DRM_DEBUG_ATOMIC("Unknown property [PROP:%d:%s]\n",
595                                  property->base.id, property->name);
596                 return -EINVAL;
597         }
598
599         return 0;
600 }
601
602 /**
603  * vc4_hdmi_connector_atomic_set_property - hook for
604  *                                              connector->atomic_set_property.
605  * @connector: Connector to set the property for.
606  * @state: Connector state to set the property on.
607  * @property: Property to set.
608  * @val: New value for the property.
609  *
610  * Sets the atomic property value for a digital connector.
611  */
612 int vc4_hdmi_connector_set_property(struct drm_connector *connector,
613                                     struct drm_connector_state *state,
614                                     struct drm_property *property,
615                                     uint64_t val)
616 {
617         struct vc4_hdmi *vc4_hdmi = connector_to_vc4_hdmi(connector);
618         struct vc4_hdmi_connector_state *vc4_conn_state =
619                                 conn_state_to_vc4_hdmi_conn_state(state);
620
621         if (property == vc4_hdmi->broadcast_rgb_property) {
622                 vc4_conn_state->broadcast_rgb = val;
623                 return 0;
624         } else if (property == vc4_hdmi->output_format_property) {
625                 vc4_conn_state->requested_output_format = val;
626                 return 0;
627         }
628
629         DRM_DEBUG_ATOMIC("Unknown property [PROP:%d:%s]\n",
630                          property->base.id, property->name);
631         return -EINVAL;
632 }
633
634 static void vc4_hdmi_connector_reset(struct drm_connector *connector)
635 {
636         struct vc4_hdmi_connector_state *old_state =
637                 conn_state_to_vc4_hdmi_conn_state(connector->state);
638         struct vc4_hdmi_connector_state *new_state =
639                 kzalloc(sizeof(*new_state), GFP_KERNEL);
640
641         if (connector->state)
642                 __drm_atomic_helper_connector_destroy_state(connector->state);
643
644         kfree(old_state);
645         __drm_atomic_helper_connector_reset(connector, &new_state->base);
646
647         if (!new_state)
648                 return;
649
650         new_state->base.max_bpc = 8;
651         new_state->base.max_requested_bpc = 8;
652         new_state->output_format = VC4_HDMI_OUTPUT_RGB;
653         drm_atomic_helper_connector_tv_reset(connector);
654 }
655
656 static struct drm_connector_state *
657 vc4_hdmi_connector_duplicate_state(struct drm_connector *connector)
658 {
659         struct drm_connector_state *conn_state = connector->state;
660         struct vc4_hdmi_connector_state *vc4_state = conn_state_to_vc4_hdmi_conn_state(conn_state);
661         struct vc4_hdmi_connector_state *new_state;
662
663         new_state = kzalloc(sizeof(*new_state), GFP_KERNEL);
664         if (!new_state)
665                 return NULL;
666
667         new_state->pixel_rate = vc4_state->pixel_rate;
668         new_state->output_bpc = vc4_state->output_bpc;
669         new_state->output_format = vc4_state->output_format;
670         new_state->requested_output_format = vc4_state->requested_output_format;
671         new_state->broadcast_rgb = vc4_state->broadcast_rgb;
672         __drm_atomic_helper_connector_duplicate_state(connector, &new_state->base);
673
674         return &new_state->base;
675 }
676
677 static const struct drm_connector_funcs vc4_hdmi_connector_funcs = {
678         .fill_modes = drm_helper_probe_single_connector_modes,
679         .reset = vc4_hdmi_connector_reset,
680         .atomic_duplicate_state = vc4_hdmi_connector_duplicate_state,
681         .atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
682         .atomic_get_property = vc4_hdmi_connector_get_property,
683         .atomic_set_property = vc4_hdmi_connector_set_property,
684 };
685
686 static const struct drm_connector_helper_funcs vc4_hdmi_connector_helper_funcs = {
687         .detect_ctx = vc4_hdmi_connector_detect_ctx,
688         .get_modes = vc4_hdmi_connector_get_modes,
689         .atomic_check = vc4_hdmi_connector_atomic_check,
690 };
691
692 static const struct drm_prop_enum_list broadcast_rgb_names[] = {
693         { VC4_BROADCAST_RGB_AUTO, "Automatic" },
694         { VC4_BROADCAST_RGB_FULL, "Full" },
695         { VC4_BROADCAST_RGB_LIMITED, "Limited 16:235" },
696 };
697
698 static void
699 vc4_hdmi_attach_broadcast_rgb_property(struct drm_device *dev,
700                                        struct vc4_hdmi *vc4_hdmi)
701 {
702         struct drm_property *prop = vc4_hdmi->broadcast_rgb_property;
703
704         if (!prop) {
705                 prop = drm_property_create_enum(dev, DRM_MODE_PROP_ENUM,
706                                                 "Broadcast RGB",
707                                                 broadcast_rgb_names,
708                                                 ARRAY_SIZE(broadcast_rgb_names));
709                 if (!prop)
710                         return;
711
712                 vc4_hdmi->broadcast_rgb_property = prop;
713         }
714
715         drm_object_attach_property(&vc4_hdmi->connector.base, prop, 0);
716 }
717
718 static const struct drm_prop_enum_list output_format_names[] = {
719         { VC4_HDMI_OUTPUT_AUTO, "Automatic" },
720         { VC4_HDMI_OUTPUT_RGB, "RGB" },
721         { VC4_HDMI_OUTPUT_YUV422, "YCbCr 4:2:2" },
722         { VC4_HDMI_OUTPUT_YUV444, "YCbCr 4:4:4" },
723 };
724
725 static void
726 vc4_hdmi_attach_output_format_property(struct drm_device *dev,
727                                        struct vc4_hdmi *vc4_hdmi)
728 {
729         struct drm_property *prop = vc4_hdmi->output_format_property;
730
731         if (!prop) {
732                 prop = drm_property_create_enum(dev, DRM_MODE_PROP_ENUM,
733                                                 "Output format",
734                                                 output_format_names,
735                                                 ARRAY_SIZE(output_format_names));
736                 if (!prop)
737                         return;
738
739                 vc4_hdmi->output_format_property = prop;
740         }
741
742         drm_object_attach_property(&vc4_hdmi->connector.base, prop, 0);
743 }
744
745 static int vc4_hdmi_connector_init(struct drm_device *dev,
746                                    struct vc4_hdmi *vc4_hdmi)
747 {
748         struct drm_connector *connector = &vc4_hdmi->connector;
749         struct drm_encoder *encoder = &vc4_hdmi->encoder.base;
750         int ret;
751
752         ret = drmm_connector_init(dev, connector,
753                                   &vc4_hdmi_connector_funcs,
754                                   DRM_MODE_CONNECTOR_HDMIA,
755                                   vc4_hdmi->ddc);
756         if (ret)
757                 return ret;
758
759         drm_connector_helper_add(connector, &vc4_hdmi_connector_helper_funcs);
760
761         /*
762          * Some of the properties below require access to state, like bpc.
763          * Allocate some default initial connector state with our reset helper.
764          */
765         if (connector->funcs->reset)
766                 connector->funcs->reset(connector);
767
768         /* Create and attach TV margin props to this connector. */
769         ret = drm_mode_create_tv_margin_properties(dev);
770         if (ret)
771                 return ret;
772
773         ret = drm_mode_create_hdmi_colorspace_property(connector);
774         if (ret)
775                 return ret;
776
777         drm_connector_attach_colorspace_property(connector);
778         drm_connector_attach_tv_margin_properties(connector);
779         drm_connector_attach_max_bpc_property(connector, 8, 12);
780
781         connector->polled = (DRM_CONNECTOR_POLL_CONNECT |
782                              DRM_CONNECTOR_POLL_DISCONNECT);
783
784         connector->interlace_allowed = 1;
785         connector->doublescan_allowed = 0;
786         connector->stereo_allowed = 1;
787
788         if (vc4_hdmi->variant->supports_hdr)
789                 drm_connector_attach_hdr_output_metadata_property(connector);
790
791         vc4_hdmi_attach_broadcast_rgb_property(dev, vc4_hdmi);
792         vc4_hdmi_attach_output_format_property(dev, vc4_hdmi);
793
794         drm_connector_attach_encoder(connector, encoder);
795
796         return 0;
797 }
798
799 static int vc4_hdmi_stop_packet(struct drm_encoder *encoder,
800                                 enum hdmi_infoframe_type type,
801                                 bool poll)
802 {
803         struct vc4_hdmi *vc4_hdmi = encoder_to_vc4_hdmi(encoder);
804         struct drm_device *drm = vc4_hdmi->connector.dev;
805         u32 packet_id = type - 0x80;
806         unsigned long flags;
807         int ret = 0;
808         int idx;
809
810         if (!drm_dev_enter(drm, &idx))
811                 return -ENODEV;
812
813         spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
814         HDMI_WRITE(HDMI_RAM_PACKET_CONFIG,
815                    HDMI_READ(HDMI_RAM_PACKET_CONFIG) & ~BIT(packet_id));
816         spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
817
818         if (poll) {
819                 ret = wait_for(!(HDMI_READ(HDMI_RAM_PACKET_STATUS) &
820                                  BIT(packet_id)), 100);
821         }
822
823         drm_dev_exit(idx);
824         return ret;
825 }
826
827 static void vc4_hdmi_write_infoframe(struct drm_encoder *encoder,
828                                      union hdmi_infoframe *frame)
829 {
830         struct vc4_hdmi *vc4_hdmi = encoder_to_vc4_hdmi(encoder);
831         struct drm_device *drm = vc4_hdmi->connector.dev;
832         u32 packet_id = frame->any.type - 0x80;
833         const struct vc4_hdmi_register *ram_packet_start =
834                 &vc4_hdmi->variant->registers[HDMI_RAM_PACKET_START];
835         u32 packet_reg = ram_packet_start->offset + VC4_HDMI_PACKET_STRIDE * packet_id;
836         u32 packet_reg_next = ram_packet_start->offset +
837                 VC4_HDMI_PACKET_STRIDE * (packet_id + 1);
838         void __iomem *base = __vc4_hdmi_get_field_base(vc4_hdmi,
839                                                        ram_packet_start->reg);
840         uint8_t buffer[VC4_HDMI_PACKET_STRIDE] = {};
841         unsigned long flags;
842         ssize_t len, i;
843         int ret;
844         int idx;
845
846         if (!drm_dev_enter(drm, &idx))
847                 return;
848
849         WARN_ONCE(!(HDMI_READ(HDMI_RAM_PACKET_CONFIG) &
850                     VC4_HDMI_RAM_PACKET_ENABLE),
851                   "Packet RAM has to be on to store the packet.");
852
853         len = hdmi_infoframe_pack(frame, buffer, sizeof(buffer));
854         if (len < 0)
855                 goto out;
856
857         ret = vc4_hdmi_stop_packet(encoder, frame->any.type, true);
858         if (ret) {
859                 DRM_ERROR("Failed to wait for infoframe to go idle: %d\n", ret);
860                 goto out;
861         }
862
863         spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
864
865         for (i = 0; i < len; i += 7) {
866                 writel(buffer[i + 0] << 0 |
867                        buffer[i + 1] << 8 |
868                        buffer[i + 2] << 16,
869                        base + packet_reg);
870                 packet_reg += 4;
871
872                 writel(buffer[i + 3] << 0 |
873                        buffer[i + 4] << 8 |
874                        buffer[i + 5] << 16 |
875                        buffer[i + 6] << 24,
876                        base + packet_reg);
877                 packet_reg += 4;
878         }
879
880         /*
881          * clear remainder of packet ram as it's included in the
882          * infoframe and triggers a checksum error on hdmi analyser
883          */
884         for (; packet_reg < packet_reg_next; packet_reg += 4)
885                 writel(0, base + packet_reg);
886
887         HDMI_WRITE(HDMI_RAM_PACKET_CONFIG,
888                    HDMI_READ(HDMI_RAM_PACKET_CONFIG) | BIT(packet_id));
889
890         spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
891
892         ret = wait_for((HDMI_READ(HDMI_RAM_PACKET_STATUS) &
893                         BIT(packet_id)), 100);
894         if (ret)
895                 DRM_ERROR("Failed to wait for infoframe to start: %d\n", ret);
896
897 out:
898         drm_dev_exit(idx);
899 }
900
901 static void vc4_hdmi_avi_infoframe_colorspace(struct hdmi_avi_infoframe *frame,
902                                               enum vc4_hdmi_output_format fmt)
903 {
904         switch (fmt) {
905         case VC4_HDMI_OUTPUT_RGB:
906                 frame->colorspace = HDMI_COLORSPACE_RGB;
907                 break;
908
909         case VC4_HDMI_OUTPUT_YUV420:
910                 frame->colorspace = HDMI_COLORSPACE_YUV420;
911                 break;
912
913         case VC4_HDMI_OUTPUT_YUV422:
914                 frame->colorspace = HDMI_COLORSPACE_YUV422;
915                 break;
916
917         case VC4_HDMI_OUTPUT_YUV444:
918                 frame->colorspace = HDMI_COLORSPACE_YUV444;
919                 break;
920
921         default:
922                 break;
923         }
924 }
925
926 static void vc4_hdmi_set_avi_infoframe(struct drm_encoder *encoder)
927 {
928         struct vc4_hdmi *vc4_hdmi = encoder_to_vc4_hdmi(encoder);
929         struct drm_connector *connector = &vc4_hdmi->connector;
930         struct drm_connector_state *cstate = connector->state;
931         struct vc4_hdmi_connector_state *vc4_state =
932                 conn_state_to_vc4_hdmi_conn_state(cstate);
933         const struct drm_display_mode *mode = &vc4_hdmi->saved_adjusted_mode;
934         union hdmi_infoframe frame;
935         int ret;
936
937         lockdep_assert_held(&vc4_hdmi->mutex);
938
939         ret = drm_hdmi_avi_infoframe_from_display_mode(&frame.avi,
940                                                        connector, mode);
941         if (ret < 0) {
942                 DRM_ERROR("couldn't fill AVI infoframe\n");
943                 return;
944         }
945
946         drm_hdmi_avi_infoframe_quant_range(&frame.avi,
947                                            connector, mode,
948                                            vc4_hdmi_is_full_range(vc4_hdmi, mode) ?
949                                            HDMI_QUANTIZATION_RANGE_FULL :
950                                            HDMI_QUANTIZATION_RANGE_LIMITED);
951         drm_hdmi_avi_infoframe_colorimetry(&frame.avi, cstate);
952         vc4_hdmi_avi_infoframe_colorspace(&frame.avi, vc4_state->output_format);
953         drm_hdmi_avi_infoframe_bars(&frame.avi, cstate);
954
955         vc4_hdmi_write_infoframe(encoder, &frame);
956 }
957
958 static void vc4_hdmi_set_spd_infoframe(struct drm_encoder *encoder)
959 {
960         union hdmi_infoframe frame;
961         int ret;
962
963         ret = hdmi_spd_infoframe_init(&frame.spd, "Broadcom", "Videocore");
964         if (ret < 0) {
965                 DRM_ERROR("couldn't fill SPD infoframe\n");
966                 return;
967         }
968
969         frame.spd.sdi = HDMI_SPD_SDI_PC;
970
971         vc4_hdmi_write_infoframe(encoder, &frame);
972 }
973
974 static void vc4_hdmi_set_audio_infoframe(struct drm_encoder *encoder)
975 {
976         struct vc4_hdmi *vc4_hdmi = encoder_to_vc4_hdmi(encoder);
977         struct hdmi_audio_infoframe *audio = &vc4_hdmi->audio.infoframe;
978         union hdmi_infoframe frame;
979
980         memcpy(&frame.audio, audio, sizeof(*audio));
981         vc4_hdmi_write_infoframe(encoder, &frame);
982 }
983
984 static void vc4_hdmi_set_hdr_infoframe(struct drm_encoder *encoder)
985 {
986         struct vc4_hdmi *vc4_hdmi = encoder_to_vc4_hdmi(encoder);
987         struct drm_connector *connector = &vc4_hdmi->connector;
988         struct drm_connector_state *conn_state = connector->state;
989         union hdmi_infoframe frame;
990
991         lockdep_assert_held(&vc4_hdmi->mutex);
992
993         if (!vc4_hdmi->variant->supports_hdr)
994                 return;
995
996         if (!conn_state->hdr_output_metadata)
997                 return;
998
999         if (drm_hdmi_infoframe_set_hdr_metadata(&frame.drm, conn_state))
1000                 return;
1001
1002         vc4_hdmi_write_infoframe(encoder, &frame);
1003 }
1004
1005 static void vc4_hdmi_set_infoframes(struct drm_encoder *encoder)
1006 {
1007         struct vc4_hdmi *vc4_hdmi = encoder_to_vc4_hdmi(encoder);
1008
1009         lockdep_assert_held(&vc4_hdmi->mutex);
1010
1011         vc4_hdmi_set_avi_infoframe(encoder);
1012         vc4_hdmi_set_spd_infoframe(encoder);
1013         /*
1014          * If audio was streaming, then we need to reenabled the audio
1015          * infoframe here during encoder_enable.
1016          */
1017         if (vc4_hdmi->audio.streaming)
1018                 vc4_hdmi_set_audio_infoframe(encoder);
1019
1020         vc4_hdmi_set_hdr_infoframe(encoder);
1021 }
1022
1023 #define SCRAMBLING_POLLING_DELAY_MS     1000
1024
1025 static void vc4_hdmi_enable_scrambling(struct drm_encoder *encoder)
1026 {
1027         struct vc4_hdmi *vc4_hdmi = encoder_to_vc4_hdmi(encoder);
1028         struct drm_device *drm = vc4_hdmi->connector.dev;
1029         const struct drm_display_mode *mode = &vc4_hdmi->saved_adjusted_mode;
1030         unsigned long flags;
1031         int idx;
1032
1033         lockdep_assert_held(&vc4_hdmi->mutex);
1034
1035         if (!vc4_hdmi_supports_scrambling(encoder))
1036                 return;
1037
1038         if (!vc4_hdmi_mode_needs_scrambling(mode,
1039                                             vc4_hdmi->output_bpc,
1040                                             vc4_hdmi->output_format))
1041                 return;
1042
1043         if (!drm_dev_enter(drm, &idx))
1044                 return;
1045
1046         drm_scdc_set_high_tmds_clock_ratio(vc4_hdmi->ddc, true);
1047         drm_scdc_set_scrambling(vc4_hdmi->ddc, true);
1048
1049         spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
1050         HDMI_WRITE(HDMI_SCRAMBLER_CTL, HDMI_READ(HDMI_SCRAMBLER_CTL) |
1051                    VC5_HDMI_SCRAMBLER_CTL_ENABLE);
1052         spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
1053
1054         drm_dev_exit(idx);
1055
1056         vc4_hdmi->scdc_enabled = true;
1057
1058         queue_delayed_work(system_wq, &vc4_hdmi->scrambling_work,
1059                            msecs_to_jiffies(SCRAMBLING_POLLING_DELAY_MS));
1060 }
1061
1062 static void vc4_hdmi_disable_scrambling(struct drm_encoder *encoder)
1063 {
1064         struct vc4_hdmi *vc4_hdmi = encoder_to_vc4_hdmi(encoder);
1065         struct drm_device *drm = vc4_hdmi->connector.dev;
1066         unsigned long flags;
1067         int idx;
1068
1069         lockdep_assert_held(&vc4_hdmi->mutex);
1070
1071         if (!vc4_hdmi->scdc_enabled)
1072                 return;
1073
1074         vc4_hdmi->scdc_enabled = false;
1075
1076         if (delayed_work_pending(&vc4_hdmi->scrambling_work))
1077                 cancel_delayed_work_sync(&vc4_hdmi->scrambling_work);
1078
1079         if (!drm_dev_enter(drm, &idx))
1080                 return;
1081
1082         spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
1083         HDMI_WRITE(HDMI_SCRAMBLER_CTL, HDMI_READ(HDMI_SCRAMBLER_CTL) &
1084                    ~VC5_HDMI_SCRAMBLER_CTL_ENABLE);
1085         spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
1086
1087         drm_scdc_set_scrambling(vc4_hdmi->ddc, false);
1088         drm_scdc_set_high_tmds_clock_ratio(vc4_hdmi->ddc, false);
1089
1090         drm_dev_exit(idx);
1091 }
1092
1093 static void vc4_hdmi_scrambling_wq(struct work_struct *work)
1094 {
1095         struct vc4_hdmi *vc4_hdmi = container_of(to_delayed_work(work),
1096                                                  struct vc4_hdmi,
1097                                                  scrambling_work);
1098
1099         if (drm_scdc_get_scrambling_status(vc4_hdmi->ddc))
1100                 return;
1101
1102         drm_scdc_set_high_tmds_clock_ratio(vc4_hdmi->ddc, true);
1103         drm_scdc_set_scrambling(vc4_hdmi->ddc, true);
1104
1105         queue_delayed_work(system_wq, &vc4_hdmi->scrambling_work,
1106                            msecs_to_jiffies(SCRAMBLING_POLLING_DELAY_MS));
1107 }
1108
1109 static void vc4_hdmi_encoder_post_crtc_disable(struct drm_encoder *encoder,
1110                                                struct drm_atomic_state *state)
1111 {
1112         struct vc4_hdmi *vc4_hdmi = encoder_to_vc4_hdmi(encoder);
1113         struct drm_device *drm = vc4_hdmi->connector.dev;
1114         unsigned long flags;
1115         int idx;
1116
1117         mutex_lock(&vc4_hdmi->mutex);
1118
1119         vc4_hdmi->output_enabled = false;
1120
1121         if (!drm_dev_enter(drm, &idx))
1122                 goto out;
1123
1124         spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
1125
1126         HDMI_WRITE(HDMI_RAM_PACKET_CONFIG, 0);
1127
1128         HDMI_WRITE(HDMI_VID_CTL, HDMI_READ(HDMI_VID_CTL) | VC4_HD_VID_CTL_CLRRGB);
1129
1130         spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
1131
1132         mdelay(1);
1133
1134         spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
1135         HDMI_WRITE(HDMI_VID_CTL,
1136                    HDMI_READ(HDMI_VID_CTL) & ~VC4_HD_VID_CTL_ENABLE);
1137         spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
1138
1139         vc4_hdmi_disable_scrambling(encoder);
1140
1141         drm_dev_exit(idx);
1142
1143 out:
1144         mutex_unlock(&vc4_hdmi->mutex);
1145 }
1146
1147 static void vc4_hdmi_encoder_post_crtc_powerdown(struct drm_encoder *encoder,
1148                                                  struct drm_atomic_state *state)
1149 {
1150         struct vc4_hdmi *vc4_hdmi = encoder_to_vc4_hdmi(encoder);
1151         struct drm_device *drm = vc4_hdmi->connector.dev;
1152         unsigned long flags;
1153         int ret;
1154         int idx;
1155
1156         mutex_lock(&vc4_hdmi->mutex);
1157
1158         if (!drm_dev_enter(drm, &idx))
1159                 goto out;
1160
1161         spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
1162         HDMI_WRITE(HDMI_VID_CTL,
1163                    HDMI_READ(HDMI_VID_CTL) | VC4_HD_VID_CTL_BLANKPIX);
1164         spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
1165
1166         if (vc4_hdmi->variant->phy_disable)
1167                 vc4_hdmi->variant->phy_disable(vc4_hdmi);
1168
1169         clk_disable_unprepare(vc4_hdmi->pixel_bvb_clock);
1170         clk_disable_unprepare(vc4_hdmi->pixel_clock);
1171
1172         ret = pm_runtime_put(&vc4_hdmi->pdev->dev);
1173         if (ret < 0)
1174                 DRM_ERROR("Failed to release power domain: %d\n", ret);
1175
1176         drm_dev_exit(idx);
1177
1178 out:
1179         mutex_unlock(&vc4_hdmi->mutex);
1180 }
1181
1182 static void vc4_hdmi_csc_setup(struct vc4_hdmi *vc4_hdmi,
1183                                struct drm_connector_state *state,
1184                                const struct drm_display_mode *mode)
1185 {
1186         struct drm_device *drm = vc4_hdmi->connector.dev;
1187         unsigned long flags;
1188         u32 csc_ctl;
1189         int idx;
1190
1191         if (!drm_dev_enter(drm, &idx))
1192                 return;
1193
1194         spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
1195
1196         csc_ctl = VC4_SET_FIELD(VC4_HD_CSC_CTL_ORDER_BGR,
1197                                 VC4_HD_CSC_CTL_ORDER);
1198
1199         if (!vc4_hdmi_is_full_range(vc4_hdmi, mode)) {
1200                 /* CEA VICs other than #1 requre limited range RGB
1201                  * output unless overridden by an AVI infoframe.
1202                  * Apply a colorspace conversion to squash 0-255 down
1203                  * to 16-235.  The matrix here is:
1204                  *
1205                  * [ 0      0      0.8594 16]
1206                  * [ 0      0.8594 0      16]
1207                  * [ 0.8594 0      0      16]
1208                  * [ 0      0      0       1]
1209                  */
1210                 csc_ctl |= VC4_HD_CSC_CTL_ENABLE;
1211                 csc_ctl |= VC4_HD_CSC_CTL_RGB2YCC;
1212                 csc_ctl |= VC4_SET_FIELD(VC4_HD_CSC_CTL_MODE_CUSTOM,
1213                                          VC4_HD_CSC_CTL_MODE);
1214
1215                 HDMI_WRITE(HDMI_CSC_12_11, (0x000 << 16) | 0x000);
1216                 HDMI_WRITE(HDMI_CSC_14_13, (0x100 << 16) | 0x6e0);
1217                 HDMI_WRITE(HDMI_CSC_22_21, (0x6e0 << 16) | 0x000);
1218                 HDMI_WRITE(HDMI_CSC_24_23, (0x100 << 16) | 0x000);
1219                 HDMI_WRITE(HDMI_CSC_32_31, (0x000 << 16) | 0x6e0);
1220                 HDMI_WRITE(HDMI_CSC_34_33, (0x100 << 16) | 0x000);
1221         }
1222
1223         /* The RGB order applies even when CSC is disabled. */
1224         HDMI_WRITE(HDMI_CSC_CTL, csc_ctl);
1225
1226         spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
1227
1228         drm_dev_exit(idx);
1229 }
1230
1231 /*
1232  * If we need to output Full Range RGB, then use the unity matrix
1233  *
1234  * [ 1      0      0      0]
1235  * [ 0      1      0      0]
1236  * [ 0      0      1      0]
1237  *
1238  * CEA VICs other than #1 require limited range RGB output unless
1239  * overridden by an AVI infoframe. Apply a colorspace conversion to
1240  * squash 0-255 down to 16-235. The matrix here is:
1241  *
1242  * [ 0.8594 0      0      16]
1243  * [ 0      0.8594 0      16]
1244  * [ 0      0      0.8594 16]
1245  *
1246  * Matrix is signed 2p13 fixed point, with signed 9p6 offsets
1247  */
1248 static const u16 vc5_hdmi_csc_full_rgb_to_rgb[2][3][4] = {
1249         {
1250                 /* Full range - unity */
1251                 { 0x2000, 0x0000, 0x0000, 0x0000 },
1252                 { 0x0000, 0x2000, 0x0000, 0x0000 },
1253                 { 0x0000, 0x0000, 0x2000, 0x0000 },
1254         }, {
1255                 /* Limited range */
1256                 { 0x1b80, 0x0000, 0x0000, 0x0400 },
1257                 { 0x0000, 0x1b80, 0x0000, 0x0400 },
1258                 { 0x0000, 0x0000, 0x1b80, 0x0400 },
1259         }
1260 };
1261
1262 /*
1263  * Conversion between Full Range RGB and YUV using the BT.601 Colorspace
1264  *
1265  * Full range
1266  * [    0.299000   0.587000   0.114000   0.000000 ]
1267  * [   -0.168736  -0.331264   0.500000 128.000000 ]
1268  * [    0.500000  -0.418688  -0.081312 128.000000 ]
1269  *
1270  * Limited range
1271  * [    0.255785   0.502160   0.097523  16.000000 ]
1272  * [   -0.147644  -0.289856   0.437500 128.000000 ]
1273  * [    0.437500  -0.366352  -0.071148 128.000000 ]
1274  *
1275  * Matrix is signed 2p13 fixed point, with signed 9p6 offsets
1276  */
1277 static const u16 vc5_hdmi_csc_full_rgb_to_yuv_bt601[2][3][4] = {
1278         {
1279                 /* Full range */
1280                 { 0x0991, 0x12c9, 0x03a6, 0x0000 },
1281                 { 0xfa9b, 0xf567, 0x1000, 0x2000 },
1282                 { 0x1000, 0xf29b, 0xfd67, 0x2000 },
1283         }, {
1284                 /* Limited range */
1285                 { 0x082f, 0x1012, 0x031f, 0x0400 },
1286                 { 0xfb48, 0xf6ba, 0x0e00, 0x2000 },
1287                 { 0x0e00, 0xf448, 0xfdba, 0x2000 },
1288         }
1289 };
1290
1291 /*
1292  * Conversion between Full Range RGB and YUV using the BT.709 Colorspace
1293  *
1294  * Full range
1295  * [    0.212600   0.715200   0.072200   0.000000 ]
1296  * [   -0.114572  -0.385428   0.500000 128.000000 ]
1297  * [    0.500000  -0.454153  -0.045847 128.000000 ]
1298  *
1299  * Limited range
1300  * [    0.181873   0.611831   0.061765  16.000000 ]
1301  * [   -0.100251  -0.337249   0.437500 128.000000 ]
1302  * [    0.437500  -0.397384  -0.040116 128.000000 ]
1303  *
1304  * Matrix is signed 2p13 fixed point, with signed 9p6 offsets
1305  */
1306 static const u16 vc5_hdmi_csc_full_rgb_to_yuv_bt709[2][3][4] = {
1307         {
1308                 /* Full range */
1309                 { 0x06ce, 0x16e3, 0x024f, 0x0000 },
1310                 { 0xfc56, 0xf3ac, 0x1000, 0x2000 },
1311                 { 0x1000, 0xf179, 0xfe89, 0x2000 },
1312         }, {
1313                 /* Limited range        */
1314                 { 0x05d2, 0x1394, 0x01fa, 0x0400 },
1315                 { 0xfccc, 0xf536, 0x0e00, 0x2000 },
1316                 { 0x0e00, 0xf34a, 0xfeb8, 0x2000 },
1317         }
1318 };
1319
1320 /*
1321  * Conversion between Full Range RGB and YUV using the BT.2020 Colorspace
1322  *
1323  * Full range
1324  * [    0.262700   0.678000   0.059300   0.000000 ]
1325  * [   -0.139630  -0.360370   0.500000 128.000000 ]
1326  * [    0.500000  -0.459786  -0.040214 128.000000 ]
1327  *
1328  * Limited range
1329  * [    0.224732   0.580008   0.050729  16.000000 ]
1330  * [   -0.122176  -0.315324   0.437500 128.000000 ]
1331  * [    0.437500  -0.402312  -0.035188 128.000000 ]
1332  *
1333  * Matrix is signed 2p13 fixed point, with signed 9p6 offsets
1334  */
1335 static const u16 vc5_hdmi_csc_full_rgb_to_yuv_bt2020[2][3][4] = {
1336         {
1337                 /* Full range */
1338                 { 0x0868, 0x15b2, 0x01e6, 0x0000 },
1339                 { 0xfb89, 0xf479, 0x1000, 0x2000 },
1340                 { 0x1000, 0xf14a, 0xfeb8, 0x2000 },
1341         }, {
1342                 /* Limited range */
1343                 { 0x0731, 0x128f, 0x01a0, 0x0400 },
1344                 { 0xfc18, 0xf5ea, 0x0e00, 0x2000 },
1345                 { 0x0e00, 0xf321, 0xfee1, 0x2000 },
1346         }
1347 };
1348
1349 static void vc5_hdmi_set_csc_coeffs(struct vc4_hdmi *vc4_hdmi,
1350                                     const u16 coeffs[3][4])
1351 {
1352         lockdep_assert_held(&vc4_hdmi->hw_lock);
1353
1354         HDMI_WRITE(HDMI_CSC_12_11, (coeffs[0][1] << 16) | coeffs[0][0]);
1355         HDMI_WRITE(HDMI_CSC_14_13, (coeffs[0][3] << 16) | coeffs[0][2]);
1356         HDMI_WRITE(HDMI_CSC_22_21, (coeffs[1][1] << 16) | coeffs[1][0]);
1357         HDMI_WRITE(HDMI_CSC_24_23, (coeffs[1][3] << 16) | coeffs[1][2]);
1358         HDMI_WRITE(HDMI_CSC_32_31, (coeffs[2][1] << 16) | coeffs[2][0]);
1359         HDMI_WRITE(HDMI_CSC_34_33, (coeffs[2][3] << 16) | coeffs[2][2]);
1360 }
1361
1362 static void vc5_hdmi_set_csc_coeffs_swap(struct vc4_hdmi *vc4_hdmi,
1363                                          const u16 coeffs[3][4])
1364 {
1365         lockdep_assert_held(&vc4_hdmi->hw_lock);
1366
1367         /* YUV444 needs the CSC matrices using the channels in a different order */
1368         HDMI_WRITE(HDMI_CSC_12_11, (coeffs[1][1] << 16) | coeffs[1][0]);
1369         HDMI_WRITE(HDMI_CSC_14_13, (coeffs[1][3] << 16) | coeffs[1][2]);
1370         HDMI_WRITE(HDMI_CSC_22_21, (coeffs[2][1] << 16) | coeffs[2][0]);
1371         HDMI_WRITE(HDMI_CSC_24_23, (coeffs[2][3] << 16) | coeffs[2][2]);
1372         HDMI_WRITE(HDMI_CSC_32_31, (coeffs[0][1] << 16) | coeffs[0][0]);
1373         HDMI_WRITE(HDMI_CSC_34_33, (coeffs[0][3] << 16) | coeffs[0][2]);
1374 }
1375
1376 static void vc5_hdmi_csc_setup(struct vc4_hdmi *vc4_hdmi,
1377                                struct drm_connector_state *state,
1378                                const struct drm_display_mode *mode)
1379 {
1380         struct drm_device *drm = vc4_hdmi->connector.dev;
1381         struct vc4_hdmi_connector_state *vc4_state =
1382                 conn_state_to_vc4_hdmi_conn_state(state);
1383         unsigned int lim_range = vc4_hdmi_is_full_range(vc4_hdmi, mode) ? 0 : 1;
1384         const u16 (*csc)[4];
1385         unsigned long flags;
1386         u32 if_cfg = 0;
1387         u32 if_xbar = 0x543210;
1388         u32 csc_chan_ctl = 0;
1389         u32 csc_ctl = VC5_MT_CP_CSC_CTL_ENABLE | VC4_SET_FIELD(VC4_HD_CSC_CTL_MODE_CUSTOM,
1390                                                                VC5_MT_CP_CSC_CTL_MODE);
1391         int idx;
1392
1393         if (!drm_dev_enter(drm, &idx))
1394                 return;
1395
1396         spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
1397
1398         switch (vc4_state->output_format) {
1399         case VC4_HDMI_OUTPUT_YUV444:
1400         case VC4_HDMI_OUTPUT_YUV422:
1401                 switch (state->colorspace) {
1402                 default:
1403                 case DRM_MODE_COLORIMETRY_NO_DATA:
1404                 case DRM_MODE_COLORIMETRY_BT709_YCC:
1405                 case DRM_MODE_COLORIMETRY_XVYCC_709:
1406                 case DRM_MODE_COLORIMETRY_RGB_WIDE_FIXED:
1407                 case DRM_MODE_COLORIMETRY_RGB_WIDE_FLOAT:
1408                         csc = vc5_hdmi_csc_full_rgb_to_yuv_bt709[lim_range];
1409                         break;
1410                 case DRM_MODE_COLORIMETRY_SMPTE_170M_YCC:
1411                 case DRM_MODE_COLORIMETRY_XVYCC_601:
1412                 case DRM_MODE_COLORIMETRY_SYCC_601:
1413                 case DRM_MODE_COLORIMETRY_OPYCC_601:
1414                 case DRM_MODE_COLORIMETRY_BT601_YCC:
1415                         csc = vc5_hdmi_csc_full_rgb_to_yuv_bt601[lim_range];
1416                         break;
1417                 case DRM_MODE_COLORIMETRY_BT2020_CYCC:
1418                 case DRM_MODE_COLORIMETRY_BT2020_YCC:
1419                 case DRM_MODE_COLORIMETRY_BT2020_RGB:
1420                 case DRM_MODE_COLORIMETRY_DCI_P3_RGB_D65:
1421                 case DRM_MODE_COLORIMETRY_DCI_P3_RGB_THEATER:
1422                         csc = vc5_hdmi_csc_full_rgb_to_yuv_bt2020[lim_range];
1423                         break;
1424                 }
1425
1426                 if (vc4_state->output_format == VC4_HDMI_OUTPUT_YUV422) {
1427                         csc_ctl |= VC4_SET_FIELD(VC5_MT_CP_CSC_CTL_FILTER_MODE_444_TO_422_STANDARD,
1428                                                  VC5_MT_CP_CSC_CTL_FILTER_MODE_444_TO_422) |
1429                                 VC5_MT_CP_CSC_CTL_USE_444_TO_422 |
1430                                 VC5_MT_CP_CSC_CTL_USE_RNG_SUPPRESSION;
1431
1432                         csc_chan_ctl |= VC4_SET_FIELD(VC5_MT_CP_CHANNEL_CTL_OUTPUT_REMAP_LEGACY_STYLE,
1433                                                       VC5_MT_CP_CHANNEL_CTL_OUTPUT_REMAP);
1434
1435                         if_cfg |= VC4_SET_FIELD(VC5_DVP_HT_VEC_INTERFACE_CFG_SEL_422_FORMAT_422_LEGACY,
1436                                                 VC5_DVP_HT_VEC_INTERFACE_CFG_SEL_422);
1437
1438                         vc5_hdmi_set_csc_coeffs(vc4_hdmi, csc);
1439                 } else {
1440                         vc5_hdmi_set_csc_coeffs_swap(vc4_hdmi, csc);
1441                 }
1442
1443                 break;
1444
1445         case VC4_HDMI_OUTPUT_RGB:
1446                 if_xbar = 0x354021;
1447
1448                 vc5_hdmi_set_csc_coeffs(vc4_hdmi,
1449                                         vc5_hdmi_csc_full_rgb_to_rgb[lim_range]);
1450                 break;
1451
1452         default:
1453                 break;
1454         }
1455
1456         HDMI_WRITE(HDMI_VEC_INTERFACE_CFG, if_cfg);
1457         HDMI_WRITE(HDMI_VEC_INTERFACE_XBAR, if_xbar);
1458         HDMI_WRITE(HDMI_CSC_CHANNEL_CTL, csc_chan_ctl);
1459         HDMI_WRITE(HDMI_CSC_CTL, csc_ctl);
1460
1461         spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
1462
1463         drm_dev_exit(idx);
1464 }
1465
1466 static void vc4_hdmi_set_timings(struct vc4_hdmi *vc4_hdmi,
1467                                  struct drm_connector_state *state,
1468                                  const struct drm_display_mode *mode)
1469 {
1470         struct drm_device *drm = vc4_hdmi->connector.dev;
1471         bool hsync_pos = mode->flags & DRM_MODE_FLAG_PHSYNC;
1472         bool vsync_pos = mode->flags & DRM_MODE_FLAG_PVSYNC;
1473         bool interlaced = mode->flags & DRM_MODE_FLAG_INTERLACE;
1474         u32 pixel_rep = (mode->flags & DRM_MODE_FLAG_DBLCLK) ? 2 : 1;
1475         u32 verta = (VC4_SET_FIELD(mode->crtc_vsync_end - mode->crtc_vsync_start,
1476                                    VC4_HDMI_VERTA_VSP) |
1477                      VC4_SET_FIELD(mode->crtc_vsync_start - mode->crtc_vdisplay,
1478                                    VC4_HDMI_VERTA_VFP) |
1479                      VC4_SET_FIELD(mode->crtc_vdisplay, VC4_HDMI_VERTA_VAL));
1480         u32 vertb = (VC4_SET_FIELD(0, VC4_HDMI_VERTB_VSPO) |
1481                      VC4_SET_FIELD(mode->crtc_vtotal - mode->crtc_vsync_end +
1482                                    interlaced,
1483                                    VC4_HDMI_VERTB_VBP));
1484         u32 vertb_even = (VC4_SET_FIELD(0, VC4_HDMI_VERTB_VSPO) |
1485                           VC4_SET_FIELD(mode->crtc_vtotal -
1486                                         mode->crtc_vsync_end,
1487                                         VC4_HDMI_VERTB_VBP));
1488         unsigned long flags;
1489         u32 reg;
1490         int idx;
1491
1492         if (!drm_dev_enter(drm, &idx))
1493                 return;
1494
1495         spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
1496
1497         HDMI_WRITE(HDMI_HORZA,
1498                    (vsync_pos ? VC4_HDMI_HORZA_VPOS : 0) |
1499                    (hsync_pos ? VC4_HDMI_HORZA_HPOS : 0) |
1500                    VC4_SET_FIELD(mode->hdisplay * pixel_rep,
1501                                  VC4_HDMI_HORZA_HAP));
1502
1503         HDMI_WRITE(HDMI_HORZB,
1504                    VC4_SET_FIELD((mode->htotal -
1505                                   mode->hsync_end) * pixel_rep,
1506                                  VC4_HDMI_HORZB_HBP) |
1507                    VC4_SET_FIELD((mode->hsync_end -
1508                                   mode->hsync_start) * pixel_rep,
1509                                  VC4_HDMI_HORZB_HSP) |
1510                    VC4_SET_FIELD((mode->hsync_start -
1511                                   mode->hdisplay) * pixel_rep,
1512                                  VC4_HDMI_HORZB_HFP));
1513
1514         HDMI_WRITE(HDMI_VERTA0, verta);
1515         HDMI_WRITE(HDMI_VERTA1, verta);
1516
1517         HDMI_WRITE(HDMI_VERTB0, vertb_even);
1518         HDMI_WRITE(HDMI_VERTB1, vertb);
1519
1520         reg = HDMI_READ(HDMI_MISC_CONTROL);
1521         reg &= ~VC4_HDMI_MISC_CONTROL_PIXEL_REP_MASK;
1522         reg |= VC4_SET_FIELD(pixel_rep - 1, VC4_HDMI_MISC_CONTROL_PIXEL_REP);
1523         HDMI_WRITE(HDMI_MISC_CONTROL, reg);
1524
1525         spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
1526
1527         drm_dev_exit(idx);
1528 }
1529
1530 static void vc5_hdmi_set_timings(struct vc4_hdmi *vc4_hdmi,
1531                                  struct drm_connector_state *state,
1532                                  const struct drm_display_mode *mode)
1533 {
1534         struct drm_device *drm = vc4_hdmi->connector.dev;
1535         const struct vc4_hdmi_connector_state *vc4_state =
1536                 conn_state_to_vc4_hdmi_conn_state(state);
1537         bool hsync_pos = mode->flags & DRM_MODE_FLAG_PHSYNC;
1538         bool vsync_pos = mode->flags & DRM_MODE_FLAG_PVSYNC;
1539         bool interlaced = mode->flags & DRM_MODE_FLAG_INTERLACE;
1540         u32 pixel_rep = (mode->flags & DRM_MODE_FLAG_DBLCLK) ? 2 : 1;
1541         u32 verta = (VC4_SET_FIELD(mode->crtc_vsync_end - mode->crtc_vsync_start,
1542                                    VC5_HDMI_VERTA_VSP) |
1543                      VC4_SET_FIELD(mode->crtc_vsync_start - mode->crtc_vdisplay,
1544                                    VC5_HDMI_VERTA_VFP) |
1545                      VC4_SET_FIELD(mode->crtc_vdisplay, VC5_HDMI_VERTA_VAL));
1546         u32 vertb = (VC4_SET_FIELD(mode->htotal >> (2 - pixel_rep),
1547                                    VC5_HDMI_VERTB_VSPO) |
1548                      VC4_SET_FIELD(mode->crtc_vtotal - mode->crtc_vsync_end +
1549                                    interlaced,
1550                                    VC4_HDMI_VERTB_VBP));
1551         u32 vertb_even = (VC4_SET_FIELD(0, VC5_HDMI_VERTB_VSPO) |
1552                           VC4_SET_FIELD(mode->crtc_vtotal -
1553                                         mode->crtc_vsync_end,
1554                                         VC4_HDMI_VERTB_VBP));
1555         unsigned long flags;
1556         unsigned char gcp;
1557         u32 reg;
1558         int idx;
1559
1560         if (!drm_dev_enter(drm, &idx))
1561                 return;
1562
1563         spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
1564
1565         HDMI_WRITE(HDMI_HORZA,
1566                    (vsync_pos ? VC5_HDMI_HORZA_VPOS : 0) |
1567                    (hsync_pos ? VC5_HDMI_HORZA_HPOS : 0) |
1568                    VC4_SET_FIELD(mode->hdisplay * pixel_rep,
1569                                  VC5_HDMI_HORZA_HAP) |
1570                    VC4_SET_FIELD((mode->hsync_start -
1571                                   mode->hdisplay) * pixel_rep,
1572                                  VC5_HDMI_HORZA_HFP));
1573
1574         HDMI_WRITE(HDMI_HORZB,
1575                    VC4_SET_FIELD((mode->htotal -
1576                                   mode->hsync_end) * pixel_rep,
1577                                  VC5_HDMI_HORZB_HBP) |
1578                    VC4_SET_FIELD((mode->hsync_end -
1579                                   mode->hsync_start) * pixel_rep,
1580                                  VC5_HDMI_HORZB_HSP));
1581
1582         HDMI_WRITE(HDMI_VERTA0, verta);
1583         HDMI_WRITE(HDMI_VERTA1, verta);
1584
1585         HDMI_WRITE(HDMI_VERTB0, vertb_even);
1586         HDMI_WRITE(HDMI_VERTB1, vertb);
1587
1588         switch (vc4_state->output_bpc) {
1589         case 12:
1590                 gcp = 6;
1591                 break;
1592         case 10:
1593                 gcp = 5;
1594                 break;
1595         case 8:
1596         default:
1597                 gcp = 0;
1598                 break;
1599         }
1600
1601         /*
1602          * YCC422 is always 36-bit and not considered deep colour so
1603          * doesn't signal in GCP
1604          */
1605         if (vc4_state->output_format == VC4_HDMI_OUTPUT_YUV422) {
1606                 gcp = 0;
1607         }
1608
1609         reg = HDMI_READ(HDMI_DEEP_COLOR_CONFIG_1);
1610         reg &= ~(VC5_HDMI_DEEP_COLOR_CONFIG_1_INIT_PACK_PHASE_MASK |
1611                  VC5_HDMI_DEEP_COLOR_CONFIG_1_COLOR_DEPTH_MASK);
1612         reg |= VC4_SET_FIELD(2, VC5_HDMI_DEEP_COLOR_CONFIG_1_INIT_PACK_PHASE) |
1613                VC4_SET_FIELD(gcp, VC5_HDMI_DEEP_COLOR_CONFIG_1_COLOR_DEPTH);
1614         HDMI_WRITE(HDMI_DEEP_COLOR_CONFIG_1, reg);
1615
1616         reg = HDMI_READ(HDMI_GCP_WORD_1);
1617         reg &= ~VC5_HDMI_GCP_WORD_1_GCP_SUBPACKET_BYTE_1_MASK;
1618         reg |= VC4_SET_FIELD(gcp, VC5_HDMI_GCP_WORD_1_GCP_SUBPACKET_BYTE_1);
1619         reg &= ~VC5_HDMI_GCP_WORD_1_GCP_SUBPACKET_BYTE_0_MASK;
1620         reg |= VC5_HDMI_GCP_WORD_1_GCP_SUBPACKET_BYTE_0_CLEAR_AVMUTE;
1621         HDMI_WRITE(HDMI_GCP_WORD_1, reg);
1622
1623         reg = HDMI_READ(HDMI_GCP_CONFIG);
1624         reg |= VC5_HDMI_GCP_CONFIG_GCP_ENABLE;
1625         HDMI_WRITE(HDMI_GCP_CONFIG, reg);
1626
1627         reg = HDMI_READ(HDMI_MISC_CONTROL);
1628         reg &= ~VC5_HDMI_MISC_CONTROL_PIXEL_REP_MASK;
1629         reg |= VC4_SET_FIELD(pixel_rep - 1, VC5_HDMI_MISC_CONTROL_PIXEL_REP);
1630         HDMI_WRITE(HDMI_MISC_CONTROL, reg);
1631
1632         HDMI_WRITE(HDMI_CLOCK_STOP, 0);
1633
1634         spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
1635
1636         drm_dev_exit(idx);
1637 }
1638
1639 static void vc4_hdmi_recenter_fifo(struct vc4_hdmi *vc4_hdmi)
1640 {
1641         struct drm_device *drm = vc4_hdmi->connector.dev;
1642         unsigned long flags;
1643         u32 drift;
1644         int ret;
1645         int idx;
1646
1647         if (!drm_dev_enter(drm, &idx))
1648                 return;
1649
1650         spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
1651
1652         drift = HDMI_READ(HDMI_FIFO_CTL);
1653         drift &= VC4_HDMI_FIFO_VALID_WRITE_MASK;
1654
1655         HDMI_WRITE(HDMI_FIFO_CTL,
1656                    drift & ~VC4_HDMI_FIFO_CTL_RECENTER);
1657         HDMI_WRITE(HDMI_FIFO_CTL,
1658                    drift | VC4_HDMI_FIFO_CTL_RECENTER);
1659
1660         spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
1661
1662         usleep_range(1000, 1100);
1663
1664         spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
1665
1666         HDMI_WRITE(HDMI_FIFO_CTL,
1667                    drift & ~VC4_HDMI_FIFO_CTL_RECENTER);
1668         HDMI_WRITE(HDMI_FIFO_CTL,
1669                    drift | VC4_HDMI_FIFO_CTL_RECENTER);
1670
1671         spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
1672
1673         ret = wait_for(HDMI_READ(HDMI_FIFO_CTL) &
1674                        VC4_HDMI_FIFO_CTL_RECENTER_DONE, 1);
1675         WARN_ONCE(ret, "Timeout waiting for "
1676                   "VC4_HDMI_FIFO_CTL_RECENTER_DONE");
1677
1678         drm_dev_exit(idx);
1679 }
1680
1681 static void vc4_hdmi_encoder_pre_crtc_configure(struct drm_encoder *encoder,
1682                                                 struct drm_atomic_state *state)
1683 {
1684         struct vc4_hdmi *vc4_hdmi = encoder_to_vc4_hdmi(encoder);
1685         struct drm_device *drm = vc4_hdmi->connector.dev;
1686         struct drm_connector *connector = &vc4_hdmi->connector;
1687         struct drm_connector_state *conn_state =
1688                 drm_atomic_get_new_connector_state(state, connector);
1689         struct vc4_hdmi_connector_state *vc4_conn_state =
1690                 conn_state_to_vc4_hdmi_conn_state(conn_state);
1691         const struct drm_display_mode *mode = &vc4_hdmi->saved_adjusted_mode;
1692         unsigned long pixel_rate = vc4_conn_state->pixel_rate;
1693         unsigned long bvb_rate, hsm_rate;
1694         unsigned long flags;
1695         int ret;
1696         int idx;
1697
1698         mutex_lock(&vc4_hdmi->mutex);
1699
1700         if (!drm_dev_enter(drm, &idx))
1701                 goto out;
1702
1703         /*
1704          * As stated in RPi's vc4 firmware "HDMI state machine (HSM) clock must
1705          * be faster than pixel clock, infinitesimally faster, tested in
1706          * simulation. Otherwise, exact value is unimportant for HDMI
1707          * operation." This conflicts with bcm2835's vc4 documentation, which
1708          * states HSM's clock has to be at least 108% of the pixel clock.
1709          *
1710          * Real life tests reveal that vc4's firmware statement holds up, and
1711          * users are able to use pixel clocks closer to HSM's, namely for
1712          * 1920x1200@60Hz. So it was decided to have leave a 1% margin between
1713          * both clocks. Which, for RPi0-3 implies a maximum pixel clock of
1714          * 162MHz.
1715          *
1716          * Additionally, the AXI clock needs to be at least 25% of
1717          * pixel clock, but HSM ends up being the limiting factor.
1718          */
1719         hsm_rate = max_t(unsigned long, 120000000, (pixel_rate / 100) * 101);
1720         ret = clk_set_min_rate(vc4_hdmi->hsm_clock, hsm_rate);
1721         if (ret) {
1722                 DRM_ERROR("Failed to set HSM clock rate: %d\n", ret);
1723                 goto err_dev_exit;
1724         }
1725
1726         ret = pm_runtime_resume_and_get(&vc4_hdmi->pdev->dev);
1727         if (ret < 0) {
1728                 DRM_ERROR("Failed to retain power domain: %d\n", ret);
1729                 goto err_dev_exit;
1730         }
1731
1732         ret = clk_set_rate(vc4_hdmi->pixel_clock, pixel_rate);
1733         if (ret) {
1734                 DRM_ERROR("Failed to set pixel clock rate: %d\n", ret);
1735                 goto err_put_runtime_pm;
1736         }
1737
1738         ret = clk_prepare_enable(vc4_hdmi->pixel_clock);
1739         if (ret) {
1740                 DRM_ERROR("Failed to turn on pixel clock: %d\n", ret);
1741                 goto err_put_runtime_pm;
1742         }
1743
1744
1745         vc4_hdmi_cec_update_clk_div(vc4_hdmi);
1746
1747         if (pixel_rate > 297000000)
1748                 bvb_rate = 300000000;
1749         else if (pixel_rate > 148500000)
1750                 bvb_rate = 150000000;
1751         else
1752                 bvb_rate = 75000000;
1753
1754         ret = clk_set_min_rate(vc4_hdmi->pixel_bvb_clock, bvb_rate);
1755         if (ret) {
1756                 DRM_ERROR("Failed to set pixel bvb clock rate: %d\n", ret);
1757                 goto err_disable_pixel_clock;
1758         }
1759
1760         ret = clk_prepare_enable(vc4_hdmi->pixel_bvb_clock);
1761         if (ret) {
1762                 DRM_ERROR("Failed to turn on pixel bvb clock: %d\n", ret);
1763                 goto err_disable_pixel_clock;
1764         }
1765
1766         if (vc4_hdmi->variant->phy_init)
1767                 vc4_hdmi->variant->phy_init(vc4_hdmi, vc4_conn_state);
1768
1769         spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
1770
1771         HDMI_WRITE(HDMI_SCHEDULER_CONTROL,
1772                    HDMI_READ(HDMI_SCHEDULER_CONTROL) |
1773                    VC4_HDMI_SCHEDULER_CONTROL_MANUAL_FORMAT |
1774                    VC4_HDMI_SCHEDULER_CONTROL_IGNORE_VSYNC_PREDICTS);
1775
1776         spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
1777
1778         if (vc4_hdmi->variant->set_timings)
1779                 vc4_hdmi->variant->set_timings(vc4_hdmi, conn_state, mode);
1780
1781         drm_dev_exit(idx);
1782
1783         mutex_unlock(&vc4_hdmi->mutex);
1784
1785         return;
1786
1787 err_disable_pixel_clock:
1788         clk_disable_unprepare(vc4_hdmi->pixel_clock);
1789 err_put_runtime_pm:
1790         pm_runtime_put(&vc4_hdmi->pdev->dev);
1791 err_dev_exit:
1792         drm_dev_exit(idx);
1793 out:
1794         mutex_unlock(&vc4_hdmi->mutex);
1795         return;
1796 }
1797
1798 static void vc4_hdmi_encoder_pre_crtc_enable(struct drm_encoder *encoder,
1799                                              struct drm_atomic_state *state)
1800 {
1801         struct vc4_hdmi *vc4_hdmi = encoder_to_vc4_hdmi(encoder);
1802         struct drm_device *drm = vc4_hdmi->connector.dev;
1803         struct drm_connector *connector = &vc4_hdmi->connector;
1804         const struct drm_display_mode *mode = &vc4_hdmi->saved_adjusted_mode;
1805         struct drm_connector_state *conn_state =
1806                 drm_atomic_get_new_connector_state(state, connector);
1807         unsigned long flags;
1808         int idx;
1809
1810         mutex_lock(&vc4_hdmi->mutex);
1811
1812         if (!drm_dev_enter(drm, &idx))
1813                 return;
1814
1815         if (vc4_hdmi->variant->csc_setup)
1816                 vc4_hdmi->variant->csc_setup(vc4_hdmi, conn_state, mode);
1817
1818         spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
1819         HDMI_WRITE(HDMI_FIFO_CTL, VC4_HDMI_FIFO_CTL_MASTER_SLAVE_N);
1820         spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
1821
1822         drm_dev_exit(idx);
1823
1824         mutex_unlock(&vc4_hdmi->mutex);
1825 }
1826
1827 static void vc4_hdmi_encoder_post_crtc_enable(struct drm_encoder *encoder,
1828                                               struct drm_atomic_state *state)
1829 {
1830         struct vc4_hdmi *vc4_hdmi = encoder_to_vc4_hdmi(encoder);
1831         struct drm_device *drm = vc4_hdmi->connector.dev;
1832         const struct drm_display_mode *mode = &vc4_hdmi->saved_adjusted_mode;
1833         struct drm_display_info *display = &vc4_hdmi->connector.display_info;
1834         bool hsync_pos = mode->flags & DRM_MODE_FLAG_PHSYNC;
1835         bool vsync_pos = mode->flags & DRM_MODE_FLAG_PVSYNC;
1836         unsigned long flags;
1837         int ret;
1838         int idx;
1839
1840         mutex_lock(&vc4_hdmi->mutex);
1841
1842         if (!drm_dev_enter(drm, &idx))
1843                 return;
1844
1845         spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
1846
1847         HDMI_WRITE(HDMI_VID_CTL,
1848                    VC4_HD_VID_CTL_ENABLE |
1849                    VC4_HD_VID_CTL_CLRRGB |
1850                    VC4_HD_VID_CTL_UNDERFLOW_ENABLE |
1851                    VC4_HD_VID_CTL_FRAME_COUNTER_RESET |
1852                    (vsync_pos ? 0 : VC4_HD_VID_CTL_VSYNC_LOW) |
1853                    (hsync_pos ? 0 : VC4_HD_VID_CTL_HSYNC_LOW));
1854
1855         HDMI_WRITE(HDMI_VID_CTL,
1856                    HDMI_READ(HDMI_VID_CTL) & ~VC4_HD_VID_CTL_BLANKPIX);
1857
1858         if (display->is_hdmi) {
1859                 HDMI_WRITE(HDMI_SCHEDULER_CONTROL,
1860                            HDMI_READ(HDMI_SCHEDULER_CONTROL) |
1861                            VC4_HDMI_SCHEDULER_CONTROL_MODE_HDMI);
1862
1863                 spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
1864
1865                 ret = wait_for(HDMI_READ(HDMI_SCHEDULER_CONTROL) &
1866                                VC4_HDMI_SCHEDULER_CONTROL_HDMI_ACTIVE, 1000);
1867                 WARN_ONCE(ret, "Timeout waiting for "
1868                           "VC4_HDMI_SCHEDULER_CONTROL_HDMI_ACTIVE\n");
1869         } else {
1870                 HDMI_WRITE(HDMI_RAM_PACKET_CONFIG,
1871                            HDMI_READ(HDMI_RAM_PACKET_CONFIG) &
1872                            ~(VC4_HDMI_RAM_PACKET_ENABLE));
1873                 HDMI_WRITE(HDMI_SCHEDULER_CONTROL,
1874                            HDMI_READ(HDMI_SCHEDULER_CONTROL) &
1875                            ~VC4_HDMI_SCHEDULER_CONTROL_MODE_HDMI);
1876
1877                 spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
1878
1879                 ret = wait_for(!(HDMI_READ(HDMI_SCHEDULER_CONTROL) &
1880                                  VC4_HDMI_SCHEDULER_CONTROL_HDMI_ACTIVE), 1000);
1881                 WARN_ONCE(ret, "Timeout waiting for "
1882                           "!VC4_HDMI_SCHEDULER_CONTROL_HDMI_ACTIVE\n");
1883         }
1884
1885         if (display->is_hdmi) {
1886                 spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
1887
1888                 WARN_ON(!(HDMI_READ(HDMI_SCHEDULER_CONTROL) &
1889                           VC4_HDMI_SCHEDULER_CONTROL_HDMI_ACTIVE));
1890
1891                 HDMI_WRITE(HDMI_RAM_PACKET_CONFIG,
1892                            VC4_HDMI_RAM_PACKET_ENABLE);
1893
1894                 spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
1895                 vc4_hdmi->output_enabled = true;
1896
1897                 vc4_hdmi_set_infoframes(encoder);
1898         }
1899
1900         vc4_hdmi_recenter_fifo(vc4_hdmi);
1901         vc4_hdmi_enable_scrambling(encoder);
1902
1903         drm_dev_exit(idx);
1904         mutex_unlock(&vc4_hdmi->mutex);
1905 }
1906
1907 static void vc4_hdmi_encoder_atomic_mode_set(struct drm_encoder *encoder,
1908                                              struct drm_crtc_state *crtc_state,
1909                                              struct drm_connector_state *conn_state)
1910 {
1911         struct vc4_hdmi *vc4_hdmi = encoder_to_vc4_hdmi(encoder);
1912         struct vc4_hdmi_connector_state *vc4_state =
1913                 conn_state_to_vc4_hdmi_conn_state(conn_state);
1914
1915         mutex_lock(&vc4_hdmi->mutex);
1916         vc4_hdmi->output_bpc = vc4_state->output_bpc;
1917         vc4_hdmi->output_format = vc4_state->output_format;
1918         vc4_hdmi->requested_output_format = vc4_state->requested_output_format;
1919         vc4_hdmi->broadcast_rgb = vc4_state->broadcast_rgb;
1920         memcpy(&vc4_hdmi->saved_adjusted_mode,
1921                &crtc_state->adjusted_mode,
1922                sizeof(vc4_hdmi->saved_adjusted_mode));
1923         mutex_unlock(&vc4_hdmi->mutex);
1924 }
1925
1926 static bool
1927 vc4_hdmi_sink_supports_format_bpc(const struct vc4_hdmi *vc4_hdmi,
1928                                   const struct drm_display_info *info,
1929                                   const struct drm_display_mode *mode,
1930                                   unsigned int format, unsigned int bpc)
1931 {
1932         struct drm_device *dev = vc4_hdmi->connector.dev;
1933         u8 vic = drm_match_cea_mode(mode);
1934
1935         if (vic == 1 && bpc != 8) {
1936                 drm_dbg(dev, "VIC1 requires a bpc of 8, got %u\n", bpc);
1937                 return false;
1938         }
1939
1940         if (!info->is_hdmi &&
1941             (format != VC4_HDMI_OUTPUT_RGB || bpc != 8)) {
1942                 drm_dbg(dev, "DVI Monitors require an RGB output at 8 bpc\n");
1943                 return false;
1944         }
1945
1946         switch (format) {
1947         case VC4_HDMI_OUTPUT_RGB:
1948                 drm_dbg(dev, "RGB Format, checking the constraints.\n");
1949
1950                 if (bpc == 10 && !(info->edid_hdmi_rgb444_dc_modes & DRM_EDID_HDMI_DC_30)) {
1951                         drm_dbg(dev, "10 BPC but sink doesn't support Deep Color 30.\n");
1952                         return false;
1953                 }
1954
1955                 if (bpc == 12 && !(info->edid_hdmi_rgb444_dc_modes & DRM_EDID_HDMI_DC_36)) {
1956                         drm_dbg(dev, "12 BPC but sink doesn't support Deep Color 36.\n");
1957                         return false;
1958                 }
1959
1960                 drm_dbg(dev, "RGB format supported in that configuration.\n");
1961
1962                 return true;
1963
1964         case VC4_HDMI_OUTPUT_YUV422:
1965                 drm_dbg(dev, "YUV422 format, checking the constraints.\n");
1966
1967                 if (!(info->color_formats & DRM_COLOR_FORMAT_YCRCB422)) {
1968                         drm_dbg(dev, "Sink doesn't support YUV422.\n");
1969                         return false;
1970                 }
1971
1972                 if (bpc != 12) {
1973                         drm_dbg(dev, "YUV422 only supports 12 bpc.\n");
1974                         return false;
1975                 }
1976
1977                 drm_dbg(dev, "YUV422 format supported in that configuration.\n");
1978
1979                 return true;
1980
1981         case VC4_HDMI_OUTPUT_YUV444:
1982                 drm_dbg(dev, "YUV444 format, checking the constraints.\n");
1983
1984                 if (!(info->color_formats & DRM_COLOR_FORMAT_YCRCB444)) {
1985                         drm_dbg(dev, "Sink doesn't support YUV444.\n");
1986                         return false;
1987                 }
1988
1989                 if (bpc == 10 && !(info->edid_hdmi_rgb444_dc_modes & DRM_EDID_HDMI_DC_30)) {
1990                         drm_dbg(dev, "10 BPC but sink doesn't support Deep Color 30.\n");
1991                         return false;
1992                 }
1993
1994                 if (bpc == 12 && !(info->edid_hdmi_rgb444_dc_modes & DRM_EDID_HDMI_DC_36)) {
1995                         drm_dbg(dev, "12 BPC but sink doesn't support Deep Color 36.\n");
1996                         return false;
1997                 }
1998
1999                 drm_dbg(dev, "YUV444 format supported in that configuration.\n");
2000
2001                 return true;
2002         }
2003
2004         return false;
2005 }
2006
2007 static enum drm_mode_status
2008 vc4_hdmi_encoder_clock_valid(const struct vc4_hdmi *vc4_hdmi,
2009                              const struct drm_display_mode *mode,
2010                              unsigned long long clock)
2011 {
2012         const struct drm_connector *connector = &vc4_hdmi->connector;
2013         const struct drm_display_info *info = &connector->display_info;
2014         struct vc4_dev *vc4 = to_vc4_dev(connector->dev);
2015
2016         if (clock > vc4_hdmi->variant->max_pixel_clock)
2017                 return MODE_CLOCK_HIGH;
2018
2019         if (!vc4->hvs->vc5_hdmi_enable_hdmi_20 && clock > HDMI_14_MAX_TMDS_CLK)
2020                 return MODE_CLOCK_HIGH;
2021
2022         /* 4096x2160@60 is not reliable without overclocking core */
2023         if (!vc4->hvs->vc5_hdmi_enable_4096by2160 &&
2024             mode->hdisplay > 3840 && mode->vdisplay >= 2160 &&
2025             drm_mode_vrefresh(mode) >= 50)
2026                 return MODE_CLOCK_HIGH;
2027
2028         if (info->max_tmds_clock && clock > (info->max_tmds_clock * 1000))
2029                 return MODE_CLOCK_HIGH;
2030
2031         return MODE_OK;
2032 }
2033
2034 static unsigned long long
2035 vc4_hdmi_encoder_compute_mode_clock(const struct drm_display_mode *mode,
2036                                     unsigned int bpc,
2037                                     enum vc4_hdmi_output_format fmt)
2038 {
2039         unsigned long long clock = mode->clock * 1000;
2040
2041         if (mode->flags & DRM_MODE_FLAG_DBLCLK)
2042                 clock = clock * 2;
2043
2044         if (fmt == VC4_HDMI_OUTPUT_YUV422)
2045                 bpc = 8;
2046
2047         return clock * bpc / 8;
2048 }
2049
2050 static int
2051 vc4_hdmi_encoder_compute_clock(const struct vc4_hdmi *vc4_hdmi,
2052                                struct vc4_hdmi_connector_state *vc4_state,
2053                                const struct drm_display_mode *mode,
2054                                unsigned int bpc, unsigned int fmt)
2055 {
2056         unsigned long long clock;
2057
2058         clock = vc4_hdmi_encoder_compute_mode_clock(mode, bpc, fmt);
2059         if (vc4_hdmi_encoder_clock_valid(vc4_hdmi, mode, clock) != MODE_OK)
2060                 return -EINVAL;
2061
2062         vc4_state->pixel_rate = clock;
2063
2064         return 0;
2065 }
2066
2067 static int
2068 vc4_hdmi_encoder_compute_format(const struct vc4_hdmi *vc4_hdmi,
2069                                 struct vc4_hdmi_connector_state *vc4_state,
2070                                 const struct drm_display_mode *mode,
2071                                 unsigned int bpc)
2072 {
2073         struct drm_device *dev = vc4_hdmi->connector.dev;
2074         const struct drm_connector *connector = &vc4_hdmi->connector;
2075         const struct drm_display_info *info = &connector->display_info;
2076         unsigned int format;
2077
2078         if (vc4_state->requested_output_format != VC4_HDMI_OUTPUT_AUTO) {
2079                 drm_dbg(dev, "Trying with user requested output %u\n",
2080                         vc4_state->requested_output_format);
2081
2082                 format = vc4_state->requested_output_format;
2083                 if (vc4_hdmi_sink_supports_format_bpc(vc4_hdmi, info, mode,
2084                                                       format, bpc)) {
2085                         int ret;
2086
2087                         ret = vc4_hdmi_encoder_compute_clock(vc4_hdmi, vc4_state,
2088                                                              mode, bpc, format);
2089                         if (!ret) {
2090                                 vc4_state->output_format = format;
2091                                 return 0;
2092                         }
2093                 }
2094
2095                 return -EINVAL;
2096         }
2097
2098         drm_dbg(dev, "Trying with an RGB output\n");
2099
2100         format = VC4_HDMI_OUTPUT_RGB;
2101         if (vc4_hdmi_sink_supports_format_bpc(vc4_hdmi, info, mode, format, bpc)) {
2102                 int ret;
2103
2104                 ret = vc4_hdmi_encoder_compute_clock(vc4_hdmi, vc4_state,
2105                                                      mode, bpc, format);
2106                 if (!ret) {
2107                         vc4_state->output_format = format;
2108                         return 0;
2109                 }
2110         }
2111
2112         drm_dbg(dev, "Failed, Trying with an YUV422 output\n");
2113
2114         format = VC4_HDMI_OUTPUT_YUV422;
2115         if (vc4_hdmi_sink_supports_format_bpc(vc4_hdmi, info, mode, format, bpc)) {
2116                 int ret;
2117
2118                 ret = vc4_hdmi_encoder_compute_clock(vc4_hdmi, vc4_state,
2119                                                      mode, bpc, format);
2120                 if (!ret) {
2121                         vc4_state->output_format = format;
2122                         return 0;
2123                 }
2124         }
2125
2126         drm_dbg(dev, "Failed. No Format Supported for that bpc count.\n");
2127
2128         return -EINVAL;
2129 }
2130
2131 static int
2132 vc4_hdmi_encoder_compute_config(const struct vc4_hdmi *vc4_hdmi,
2133                                 struct vc4_hdmi_connector_state *vc4_state,
2134                                 const struct drm_display_mode *mode)
2135 {
2136         struct drm_device *dev = vc4_hdmi->connector.dev;
2137         struct drm_connector_state *conn_state = &vc4_state->base;
2138         unsigned int max_bpc = clamp_t(unsigned int, conn_state->max_requested_bpc, 8, 12);
2139         unsigned int bpc;
2140         int ret;
2141
2142         for (bpc = max_bpc; bpc >= 8; bpc -= 2) {
2143                 drm_dbg(dev, "Trying with a %d bpc output\n", bpc);
2144
2145                 ret = vc4_hdmi_encoder_compute_format(vc4_hdmi, vc4_state,
2146                                                       mode, bpc);
2147                 if (ret)
2148                         continue;
2149
2150                 vc4_state->output_bpc = bpc;
2151
2152                 drm_dbg(dev,
2153                         "Mode %ux%u @ %uHz: Found configuration: bpc: %u, fmt: %s, clock: %llu\n",
2154                         mode->hdisplay, mode->vdisplay, drm_mode_vrefresh(mode),
2155                         vc4_state->output_bpc,
2156                         vc4_hdmi_output_fmt_str(vc4_state->output_format),
2157                         vc4_state->pixel_rate);
2158
2159                 break;
2160         }
2161
2162         return ret;
2163 }
2164
2165 #define WIFI_2_4GHz_CH1_MIN_FREQ        2400000000ULL
2166 #define WIFI_2_4GHz_CH1_MAX_FREQ        2422000000ULL
2167
2168 static int vc4_hdmi_encoder_atomic_check(struct drm_encoder *encoder,
2169                                          struct drm_crtc_state *crtc_state,
2170                                          struct drm_connector_state *conn_state)
2171 {
2172         struct vc4_hdmi_connector_state *vc4_state = conn_state_to_vc4_hdmi_conn_state(conn_state);
2173         struct drm_display_mode *mode = &crtc_state->adjusted_mode;
2174         struct vc4_hdmi *vc4_hdmi = encoder_to_vc4_hdmi(encoder);
2175         struct drm_connector *connector = &vc4_hdmi->connector;
2176         struct drm_connector_state *old_conn_state = drm_atomic_get_old_connector_state(conn_state->state, connector);
2177         struct vc4_hdmi_connector_state *old_vc4_state = conn_state_to_vc4_hdmi_conn_state(old_conn_state);
2178         unsigned long long pixel_rate = mode->clock * 1000;
2179         unsigned long long tmds_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_rate = pixel_rate * 10;
2209         if (vc4_hdmi->disable_wifi_frequencies &&
2210             (tmds_rate >= WIFI_2_4GHz_CH1_MIN_FREQ &&
2211              tmds_rate <= WIFI_2_4GHz_CH1_MAX_FREQ)) {
2212                 mode->clock = 238560;
2213                 pixel_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         int ret;
2255
2256         ret = vc4_debugfs_add_file(drm->primary, variant->debugfs_name,
2257                                    vc4_hdmi_debugfs_regs,
2258                                    vc4_hdmi);
2259         if (ret)
2260                 return ret;
2261
2262         return 0;
2263 }
2264
2265 static const struct drm_encoder_funcs vc4_hdmi_encoder_funcs = {
2266         .late_register = vc4_hdmi_late_register,
2267 };
2268
2269 static u32 vc4_hdmi_channel_map(struct vc4_hdmi *vc4_hdmi, u32 channel_mask)
2270 {
2271         int i;
2272         u32 channel_map = 0;
2273
2274         for (i = 0; i < 8; i++) {
2275                 if (channel_mask & BIT(i))
2276                         channel_map |= i << (3 * i);
2277         }
2278         return channel_map;
2279 }
2280
2281 static u32 vc5_hdmi_channel_map(struct vc4_hdmi *vc4_hdmi, u32 channel_mask)
2282 {
2283         int i;
2284         u32 channel_map = 0;
2285
2286         for (i = 0; i < 8; i++) {
2287                 if (channel_mask & BIT(i))
2288                         channel_map |= i << (4 * i);
2289         }
2290         return channel_map;
2291 }
2292
2293 static bool vc5_hdmi_hp_detect(struct vc4_hdmi *vc4_hdmi)
2294 {
2295         struct drm_device *drm = vc4_hdmi->connector.dev;
2296         unsigned long flags;
2297         u32 hotplug;
2298         int idx;
2299
2300         if (!drm_dev_enter(drm, &idx))
2301                 return false;
2302
2303         spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
2304         hotplug = HDMI_READ(HDMI_HOTPLUG);
2305         spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
2306
2307         drm_dev_exit(idx);
2308
2309         return !!(hotplug & VC4_HDMI_HOTPLUG_CONNECTED);
2310 }
2311
2312 /* HDMI audio codec callbacks */
2313 static void vc4_hdmi_audio_set_mai_clock(struct vc4_hdmi *vc4_hdmi,
2314                                          unsigned int samplerate)
2315 {
2316         struct drm_device *drm = vc4_hdmi->connector.dev;
2317         u32 hsm_clock;
2318         unsigned long flags;
2319         unsigned long n, m;
2320         int idx;
2321
2322         if (!drm_dev_enter(drm, &idx))
2323                 return;
2324
2325         hsm_clock = clk_get_rate(vc4_hdmi->audio_clock);
2326         rational_best_approximation(hsm_clock, samplerate,
2327                                     VC4_HD_MAI_SMP_N_MASK >>
2328                                     VC4_HD_MAI_SMP_N_SHIFT,
2329                                     (VC4_HD_MAI_SMP_M_MASK >>
2330                                      VC4_HD_MAI_SMP_M_SHIFT) + 1,
2331                                     &n, &m);
2332
2333         spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
2334         HDMI_WRITE(HDMI_MAI_SMP,
2335                    VC4_SET_FIELD(n, VC4_HD_MAI_SMP_N) |
2336                    VC4_SET_FIELD(m - 1, VC4_HD_MAI_SMP_M));
2337         spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
2338
2339         drm_dev_exit(idx);
2340 }
2341
2342 static void vc4_hdmi_set_n_cts(struct vc4_hdmi *vc4_hdmi, unsigned int samplerate)
2343 {
2344         const struct drm_display_mode *mode = &vc4_hdmi->saved_adjusted_mode;
2345         u32 n, cts;
2346         u64 tmp;
2347
2348         lockdep_assert_held(&vc4_hdmi->mutex);
2349         lockdep_assert_held(&vc4_hdmi->hw_lock);
2350
2351         n = 128 * samplerate / 1000;
2352         tmp = (u64)(mode->clock * 1000) * n;
2353         do_div(tmp, 128 * samplerate);
2354         cts = tmp;
2355
2356         HDMI_WRITE(HDMI_CRP_CFG,
2357                    VC4_HDMI_CRP_CFG_EXTERNAL_CTS_EN |
2358                    VC4_SET_FIELD(n, VC4_HDMI_CRP_CFG_N));
2359
2360         /*
2361          * We could get slightly more accurate clocks in some cases by
2362          * providing a CTS_1 value.  The two CTS values are alternated
2363          * between based on the period fields
2364          */
2365         HDMI_WRITE(HDMI_CTS_0, cts);
2366         HDMI_WRITE(HDMI_CTS_1, cts);
2367 }
2368
2369 static inline struct vc4_hdmi *dai_to_hdmi(struct snd_soc_dai *dai)
2370 {
2371         struct snd_soc_card *card = snd_soc_dai_get_drvdata(dai);
2372
2373         return snd_soc_card_get_drvdata(card);
2374 }
2375
2376 static bool vc4_hdmi_audio_can_stream(struct vc4_hdmi *vc4_hdmi)
2377 {
2378         struct drm_display_info *display = &vc4_hdmi->connector.display_info;
2379
2380         lockdep_assert_held(&vc4_hdmi->mutex);
2381
2382         /*
2383          * If the encoder is currently in DVI mode, treat the codec DAI
2384          * as missing.
2385          */
2386         if (!display->is_hdmi)
2387                 return false;
2388
2389         return true;
2390 }
2391
2392 static int vc4_hdmi_audio_startup(struct device *dev, void *data)
2393 {
2394         struct vc4_hdmi *vc4_hdmi = dev_get_drvdata(dev);
2395         struct drm_device *drm = vc4_hdmi->connector.dev;
2396         unsigned long flags;
2397         int ret = 0;
2398         int idx;
2399
2400         mutex_lock(&vc4_hdmi->mutex);
2401
2402         if (!drm_dev_enter(drm, &idx)) {
2403                 ret = -ENODEV;
2404                 goto out;
2405         }
2406
2407         if (!vc4_hdmi_audio_can_stream(vc4_hdmi)) {
2408                 ret = -ENOTSUPP;
2409                 goto out_dev_exit;
2410         }
2411
2412         vc4_hdmi->audio.streaming = true;
2413
2414         spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
2415         HDMI_WRITE(HDMI_MAI_CTL,
2416                    VC4_HD_MAI_CTL_RESET |
2417                    VC4_HD_MAI_CTL_FLUSH |
2418                    VC4_HD_MAI_CTL_DLATE |
2419                    VC4_HD_MAI_CTL_ERRORE |
2420                    VC4_HD_MAI_CTL_ERRORF);
2421         spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
2422
2423         if (vc4_hdmi->variant->phy_rng_enable)
2424                 vc4_hdmi->variant->phy_rng_enable(vc4_hdmi);
2425
2426 out_dev_exit:
2427         drm_dev_exit(idx);
2428 out:
2429         mutex_unlock(&vc4_hdmi->mutex);
2430
2431         return ret;
2432 }
2433
2434 static void vc4_hdmi_audio_reset(struct vc4_hdmi *vc4_hdmi)
2435 {
2436         struct drm_encoder *encoder = &vc4_hdmi->encoder.base;
2437         struct device *dev = &vc4_hdmi->pdev->dev;
2438         unsigned long flags;
2439         int ret;
2440
2441         lockdep_assert_held(&vc4_hdmi->mutex);
2442
2443         vc4_hdmi->audio.streaming = false;
2444         ret = vc4_hdmi_stop_packet(encoder, HDMI_INFOFRAME_TYPE_AUDIO, false);
2445         if (ret)
2446                 dev_err(dev, "Failed to stop audio infoframe: %d\n", ret);
2447
2448         spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
2449
2450         HDMI_WRITE(HDMI_MAI_CTL, VC4_HD_MAI_CTL_RESET);
2451         HDMI_WRITE(HDMI_MAI_CTL, VC4_HD_MAI_CTL_ERRORF);
2452         HDMI_WRITE(HDMI_MAI_CTL, VC4_HD_MAI_CTL_FLUSH);
2453
2454         spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
2455 }
2456
2457 static void vc4_hdmi_audio_shutdown(struct device *dev, void *data)
2458 {
2459         struct vc4_hdmi *vc4_hdmi = dev_get_drvdata(dev);
2460         struct drm_device *drm = vc4_hdmi->connector.dev;
2461         unsigned long flags;
2462         int idx;
2463
2464         mutex_lock(&vc4_hdmi->mutex);
2465
2466         if (!drm_dev_enter(drm, &idx))
2467                 goto out;
2468
2469         spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
2470
2471         HDMI_WRITE(HDMI_MAI_CTL,
2472                    VC4_HD_MAI_CTL_DLATE |
2473                    VC4_HD_MAI_CTL_ERRORE |
2474                    VC4_HD_MAI_CTL_ERRORF);
2475
2476         spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
2477
2478         if (vc4_hdmi->variant->phy_rng_disable)
2479                 vc4_hdmi->variant->phy_rng_disable(vc4_hdmi);
2480
2481         vc4_hdmi->audio.streaming = false;
2482         vc4_hdmi_audio_reset(vc4_hdmi);
2483
2484         drm_dev_exit(idx);
2485
2486 out:
2487         mutex_unlock(&vc4_hdmi->mutex);
2488 }
2489
2490 static int sample_rate_to_mai_fmt(int samplerate)
2491 {
2492         switch (samplerate) {
2493         case 8000:
2494                 return VC4_HDMI_MAI_SAMPLE_RATE_8000;
2495         case 11025:
2496                 return VC4_HDMI_MAI_SAMPLE_RATE_11025;
2497         case 12000:
2498                 return VC4_HDMI_MAI_SAMPLE_RATE_12000;
2499         case 16000:
2500                 return VC4_HDMI_MAI_SAMPLE_RATE_16000;
2501         case 22050:
2502                 return VC4_HDMI_MAI_SAMPLE_RATE_22050;
2503         case 24000:
2504                 return VC4_HDMI_MAI_SAMPLE_RATE_24000;
2505         case 32000:
2506                 return VC4_HDMI_MAI_SAMPLE_RATE_32000;
2507         case 44100:
2508                 return VC4_HDMI_MAI_SAMPLE_RATE_44100;
2509         case 48000:
2510                 return VC4_HDMI_MAI_SAMPLE_RATE_48000;
2511         case 64000:
2512                 return VC4_HDMI_MAI_SAMPLE_RATE_64000;
2513         case 88200:
2514                 return VC4_HDMI_MAI_SAMPLE_RATE_88200;
2515         case 96000:
2516                 return VC4_HDMI_MAI_SAMPLE_RATE_96000;
2517         case 128000:
2518                 return VC4_HDMI_MAI_SAMPLE_RATE_128000;
2519         case 176400:
2520                 return VC4_HDMI_MAI_SAMPLE_RATE_176400;
2521         case 192000:
2522                 return VC4_HDMI_MAI_SAMPLE_RATE_192000;
2523         default:
2524                 return VC4_HDMI_MAI_SAMPLE_RATE_NOT_INDICATED;
2525         }
2526 }
2527
2528 /* HDMI audio codec callbacks */
2529 static int vc4_hdmi_audio_prepare(struct device *dev, void *data,
2530                                   struct hdmi_codec_daifmt *daifmt,
2531                                   struct hdmi_codec_params *params)
2532 {
2533         struct vc4_hdmi *vc4_hdmi = dev_get_drvdata(dev);
2534         struct drm_device *drm = vc4_hdmi->connector.dev;
2535         struct drm_encoder *encoder = &vc4_hdmi->encoder.base;
2536         unsigned int sample_rate = params->sample_rate;
2537         unsigned int channels = params->channels;
2538         unsigned long flags;
2539         u32 audio_packet_config, channel_mask;
2540         u32 channel_map;
2541         u32 mai_audio_format;
2542         u32 mai_sample_rate;
2543         int ret = 0;
2544         int idx;
2545
2546         dev_dbg(dev, "%s: %u Hz, %d bit, %d channels\n", __func__,
2547                 sample_rate, params->sample_width, channels);
2548
2549         mutex_lock(&vc4_hdmi->mutex);
2550
2551         if (!drm_dev_enter(drm, &idx)) {
2552                 ret = -ENODEV;
2553                 goto out;
2554         }
2555
2556         if (!vc4_hdmi_audio_can_stream(vc4_hdmi)) {
2557                 ret = -EINVAL;
2558                 goto out_dev_exit;
2559         }
2560
2561         vc4_hdmi_audio_set_mai_clock(vc4_hdmi, sample_rate);
2562
2563         spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
2564         HDMI_WRITE(HDMI_MAI_CTL,
2565                    VC4_SET_FIELD(channels, VC4_HD_MAI_CTL_CHNUM) |
2566                    VC4_HD_MAI_CTL_WHOLSMP |
2567                    VC4_HD_MAI_CTL_CHALIGN |
2568                    VC4_HD_MAI_CTL_ENABLE);
2569
2570         mai_sample_rate = sample_rate_to_mai_fmt(sample_rate);
2571         if (params->iec.status[0] & IEC958_AES0_NONAUDIO &&
2572             params->channels == 8)
2573                 mai_audio_format = VC4_HDMI_MAI_FORMAT_HBR;
2574         else
2575                 mai_audio_format = VC4_HDMI_MAI_FORMAT_PCM;
2576         HDMI_WRITE(HDMI_MAI_FMT,
2577                    VC4_SET_FIELD(mai_sample_rate,
2578                                  VC4_HDMI_MAI_FORMAT_SAMPLE_RATE) |
2579                    VC4_SET_FIELD(mai_audio_format,
2580                                  VC4_HDMI_MAI_FORMAT_AUDIO_FORMAT));
2581
2582         /* The B frame identifier should match the value used by alsa-lib (8) */
2583         audio_packet_config =
2584                 VC4_HDMI_AUDIO_PACKET_ZERO_DATA_ON_SAMPLE_FLAT |
2585                 VC4_HDMI_AUDIO_PACKET_ZERO_DATA_ON_INACTIVE_CHANNELS |
2586                 VC4_SET_FIELD(0x8, VC4_HDMI_AUDIO_PACKET_B_FRAME_IDENTIFIER);
2587
2588         channel_mask = GENMASK(channels - 1, 0);
2589         audio_packet_config |= VC4_SET_FIELD(channel_mask,
2590                                              VC4_HDMI_AUDIO_PACKET_CEA_MASK);
2591
2592         /* Set the MAI threshold */
2593         HDMI_WRITE(HDMI_MAI_THR,
2594                    VC4_SET_FIELD(0x08, VC4_HD_MAI_THR_PANICHIGH) |
2595                    VC4_SET_FIELD(0x08, VC4_HD_MAI_THR_PANICLOW) |
2596                    VC4_SET_FIELD(0x06, VC4_HD_MAI_THR_DREQHIGH) |
2597                    VC4_SET_FIELD(0x08, VC4_HD_MAI_THR_DREQLOW));
2598
2599         HDMI_WRITE(HDMI_MAI_CONFIG,
2600                    VC4_HDMI_MAI_CONFIG_BIT_REVERSE |
2601                    VC4_HDMI_MAI_CONFIG_FORMAT_REVERSE |
2602                    VC4_SET_FIELD(channel_mask, VC4_HDMI_MAI_CHANNEL_MASK));
2603
2604         channel_map = vc4_hdmi->variant->channel_map(vc4_hdmi, channel_mask);
2605         HDMI_WRITE(HDMI_MAI_CHANNEL_MAP, channel_map);
2606         HDMI_WRITE(HDMI_AUDIO_PACKET_CONFIG, audio_packet_config);
2607
2608         vc4_hdmi_set_n_cts(vc4_hdmi, sample_rate);
2609
2610         spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
2611
2612         memcpy(&vc4_hdmi->audio.infoframe, &params->cea, sizeof(params->cea));
2613         if (vc4_hdmi->output_enabled)
2614                 vc4_hdmi_set_audio_infoframe(encoder);
2615
2616 out_dev_exit:
2617         drm_dev_exit(idx);
2618 out:
2619         mutex_unlock(&vc4_hdmi->mutex);
2620
2621         return ret;
2622 }
2623
2624 static const struct snd_soc_component_driver vc4_hdmi_audio_cpu_dai_comp = {
2625         .name = "vc4-hdmi-cpu-dai-component",
2626 };
2627
2628 static int vc4_hdmi_audio_cpu_dai_probe(struct snd_soc_dai *dai)
2629 {
2630         struct vc4_hdmi *vc4_hdmi = dai_to_hdmi(dai);
2631
2632         snd_soc_dai_init_dma_data(dai, &vc4_hdmi->audio.dma_data, NULL);
2633
2634         return 0;
2635 }
2636
2637 static struct snd_soc_dai_driver vc4_hdmi_audio_cpu_dai_drv = {
2638         .name = "vc4-hdmi-cpu-dai",
2639         .probe  = vc4_hdmi_audio_cpu_dai_probe,
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;
2701         int ret;
2702         int len;
2703
2704         /*
2705          * ASoC makes it a bit hard to retrieve a pointer to the
2706          * vc4_hdmi structure. Registering the card will overwrite our
2707          * device drvdata with a pointer to the snd_soc_card structure,
2708          * which can then be used to retrieve whatever drvdata we want
2709          * to associate.
2710          *
2711          * However, that doesn't fly in the case where we wouldn't
2712          * register an ASoC card (because of an old DT that is missing
2713          * the dmas properties for example), then the card isn't
2714          * registered and the device drvdata wouldn't be set.
2715          *
2716          * We can deal with both cases by making sure a snd_soc_card
2717          * pointer and a vc4_hdmi structure are pointing to the same
2718          * memory address, so we can treat them indistinctly without any
2719          * issue.
2720          */
2721         BUILD_BUG_ON(offsetof(struct vc4_hdmi_audio, card) != 0);
2722         BUILD_BUG_ON(offsetof(struct vc4_hdmi, audio) != 0);
2723
2724         if (!of_find_property(dev->of_node, "dmas", &len) ||
2725             len == 0) {
2726                 dev_warn(dev,
2727                          "'dmas' DT property is missing or empty, no HDMI audio\n");
2728                 return 0;
2729         }
2730
2731         if (mai_data->reg != VC4_HD) {
2732                 WARN_ONCE(true, "MAI isn't in the HD block\n");
2733                 return -EINVAL;
2734         }
2735
2736         /*
2737          * Get the physical address of VC4_HD_MAI_DATA. We need to retrieve
2738          * the bus address specified in the DT, because the physical address
2739          * (the one returned by platform_get_resource()) is not appropriate
2740          * for DMA transfers.
2741          * This VC/MMU should probably be exposed to avoid this kind of hacks.
2742          */
2743         index = of_property_match_string(dev->of_node, "reg-names", "hd");
2744         /* Before BCM2711, we don't have a named register range */
2745         if (index < 0)
2746                 index = 1;
2747
2748         addr = of_get_address(dev->of_node, index, NULL, NULL);
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         unsigned long flags;
3272         int ret;
3273
3274         if (!of_find_property(dev->of_node, "interrupts", NULL)) {
3275                 dev_warn(dev, "'interrupts' DT property is missing, no CEC\n");
3276                 return 0;
3277         }
3278
3279         vc4_hdmi->cec_adap = cec_allocate_adapter(&vc4_hdmi_cec_adap_ops,
3280                                                   vc4_hdmi, "vc4",
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                 spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
3306                 HDMI_WRITE(HDMI_CEC_CPU_MASK_SET, 0xffffffff);
3307                 spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
3308
3309                 ret = devm_request_threaded_irq(dev, platform_get_irq(pdev, 0),
3310                                                 vc4_cec_irq_handler,
3311                                                 vc4_cec_irq_handler_thread, 0,
3312                                                 "vc4 hdmi cec", vc4_hdmi);
3313                 if (ret)
3314                         goto err_delete_cec_adap;
3315         }
3316
3317         ret = cec_register_adapter(vc4_hdmi->cec_adap, &pdev->dev);
3318         if (ret < 0)
3319                 goto err_delete_cec_adap;
3320
3321         /*
3322          * NOTE: Strictly speaking, we should probably use a DRM-managed
3323          * registration there to avoid removing the CEC adapter by the
3324          * time the DRM driver doesn't have any user anymore.
3325          *
3326          * However, the CEC framework already cleans up the CEC adapter
3327          * only when the last user has closed its file descriptor, so we
3328          * don't need to handle it in DRM.
3329          *
3330          * By the time the device-managed hook is executed, we will give
3331          * up our reference to the CEC adapter and therefore don't
3332          * really care when it's actually freed.
3333          *
3334          * There's still a problematic sequence: if we unregister our
3335          * CEC adapter, but the userspace keeps a handle on the CEC
3336          * adapter but not the DRM device for some reason. In such a
3337          * case, our vc4_hdmi structure will be freed, but the
3338          * cec_adapter structure will have a dangling pointer to what
3339          * used to be our HDMI controller. If we get a CEC call at that
3340          * moment, we could end up with a use-after-free. Fortunately,
3341          * the CEC framework already handles this too, by calling
3342          * cec_is_registered() in cec_ioctl() and cec_poll().
3343          */
3344         ret = devm_add_action_or_reset(dev, vc4_hdmi_cec_release, vc4_hdmi);
3345         if (ret)
3346                 return ret;
3347
3348         return 0;
3349
3350 err_delete_cec_adap:
3351         cec_delete_adapter(vc4_hdmi->cec_adap);
3352
3353         return ret;
3354 }
3355
3356 static int vc4_hdmi_cec_resume(struct vc4_hdmi *vc4_hdmi)
3357 {
3358         unsigned long flags;
3359         u32 value;
3360
3361         spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
3362         value = HDMI_READ(HDMI_CEC_CNTRL_1);
3363         /* Set the logical address to Unregistered */
3364         value |= VC4_HDMI_CEC_ADDR_MASK;
3365         HDMI_WRITE(HDMI_CEC_CNTRL_1, value);
3366         spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
3367
3368         vc4_hdmi_cec_update_clk_div(vc4_hdmi);
3369
3370         if (!vc4_hdmi->variant->external_irq_controller) {
3371                 spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
3372                 HDMI_WRITE(HDMI_CEC_CPU_MASK_SET, 0xffffffff);
3373                 spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
3374         }
3375
3376         return 0;
3377 }
3378 #else
3379 static int vc4_hdmi_cec_init(struct vc4_hdmi *vc4_hdmi)
3380 {
3381         return 0;
3382 }
3383
3384 static int vc4_hdmi_cec_resume(struct vc4_hdmi *vc4_hdmi)
3385 {
3386         return 0;
3387 }
3388 #endif
3389
3390 static void vc4_hdmi_free_regset(struct drm_device *drm, void *ptr)
3391 {
3392         struct debugfs_reg32 *regs = ptr;
3393
3394         kfree(regs);
3395 }
3396
3397 static int vc4_hdmi_build_regset(struct drm_device *drm,
3398                                  struct vc4_hdmi *vc4_hdmi,
3399                                  struct debugfs_regset32 *regset,
3400                                  enum vc4_hdmi_regs reg)
3401 {
3402         const struct vc4_hdmi_variant *variant = vc4_hdmi->variant;
3403         struct debugfs_reg32 *regs, *new_regs;
3404         unsigned int count = 0;
3405         unsigned int i;
3406         int ret;
3407
3408         regs = kcalloc(variant->num_registers, sizeof(*regs),
3409                        GFP_KERNEL);
3410         if (!regs)
3411                 return -ENOMEM;
3412
3413         for (i = 0; i < variant->num_registers; i++) {
3414                 const struct vc4_hdmi_register *field = &variant->registers[i];
3415
3416                 if (field->reg != reg)
3417                         continue;
3418
3419                 regs[count].name = field->name;
3420                 regs[count].offset = field->offset;
3421                 count++;
3422         }
3423
3424         new_regs = krealloc(regs, count * sizeof(*regs), GFP_KERNEL);
3425         if (!new_regs)
3426                 return -ENOMEM;
3427
3428         regset->base = __vc4_hdmi_get_field_base(vc4_hdmi, reg);
3429         regset->regs = new_regs;
3430         regset->nregs = count;
3431
3432         ret = drmm_add_action_or_reset(drm, vc4_hdmi_free_regset, new_regs);
3433         if (ret)
3434                 return ret;
3435
3436         return 0;
3437 }
3438
3439 static int vc4_hdmi_init_resources(struct drm_device *drm,
3440                                    struct vc4_hdmi *vc4_hdmi)
3441 {
3442         struct platform_device *pdev = vc4_hdmi->pdev;
3443         struct device *dev = &pdev->dev;
3444         int ret;
3445
3446         vc4_hdmi->hdmicore_regs = vc4_ioremap_regs(pdev, 0);
3447         if (IS_ERR(vc4_hdmi->hdmicore_regs))
3448                 return PTR_ERR(vc4_hdmi->hdmicore_regs);
3449
3450         vc4_hdmi->hd_regs = vc4_ioremap_regs(pdev, 1);
3451         if (IS_ERR(vc4_hdmi->hd_regs))
3452                 return PTR_ERR(vc4_hdmi->hd_regs);
3453
3454         ret = vc4_hdmi_build_regset(drm, vc4_hdmi, &vc4_hdmi->hd_regset, VC4_HD);
3455         if (ret)
3456                 return ret;
3457
3458         ret = vc4_hdmi_build_regset(drm, vc4_hdmi, &vc4_hdmi->hdmi_regset, VC4_HDMI);
3459         if (ret)
3460                 return ret;
3461
3462         vc4_hdmi->pixel_clock = devm_clk_get(dev, "pixel");
3463         if (IS_ERR(vc4_hdmi->pixel_clock)) {
3464                 ret = PTR_ERR(vc4_hdmi->pixel_clock);
3465                 if (ret != -EPROBE_DEFER)
3466                         DRM_ERROR("Failed to get pixel clock\n");
3467                 return ret;
3468         }
3469
3470         vc4_hdmi->hsm_clock = devm_clk_get(dev, "hdmi");
3471         if (IS_ERR(vc4_hdmi->hsm_clock)) {
3472                 DRM_ERROR("Failed to get HDMI state machine clock\n");
3473                 return PTR_ERR(vc4_hdmi->hsm_clock);
3474         }
3475         vc4_hdmi->audio_clock = vc4_hdmi->hsm_clock;
3476         vc4_hdmi->cec_clock = vc4_hdmi->hsm_clock;
3477
3478         return 0;
3479 }
3480
3481 static int vc5_hdmi_init_resources(struct drm_device *drm,
3482                                    struct vc4_hdmi *vc4_hdmi)
3483 {
3484         struct platform_device *pdev = vc4_hdmi->pdev;
3485         struct device *dev = &pdev->dev;
3486         struct resource *res;
3487         int ret;
3488
3489         res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "hdmi");
3490         if (!res)
3491                 return -ENODEV;
3492
3493         vc4_hdmi->hdmicore_regs = devm_ioremap(dev, res->start,
3494                                                resource_size(res));
3495         if (!vc4_hdmi->hdmicore_regs)
3496                 return -ENOMEM;
3497
3498         res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "hd");
3499         if (!res)
3500                 return -ENODEV;
3501
3502         vc4_hdmi->hd_regs = devm_ioremap(dev, res->start, resource_size(res));
3503         if (!vc4_hdmi->hd_regs)
3504                 return -ENOMEM;
3505
3506         res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "cec");
3507         if (!res)
3508                 return -ENODEV;
3509
3510         vc4_hdmi->cec_regs = devm_ioremap(dev, res->start, resource_size(res));
3511         if (!vc4_hdmi->cec_regs)
3512                 return -ENOMEM;
3513
3514         res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "csc");
3515         if (!res)
3516                 return -ENODEV;
3517
3518         vc4_hdmi->csc_regs = devm_ioremap(dev, res->start, resource_size(res));
3519         if (!vc4_hdmi->csc_regs)
3520                 return -ENOMEM;
3521
3522         res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "dvp");
3523         if (!res)
3524                 return -ENODEV;
3525
3526         vc4_hdmi->dvp_regs = devm_ioremap(dev, res->start, resource_size(res));
3527         if (!vc4_hdmi->dvp_regs)
3528                 return -ENOMEM;
3529
3530         res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "phy");
3531         if (!res)
3532                 return -ENODEV;
3533
3534         vc4_hdmi->phy_regs = devm_ioremap(dev, res->start, resource_size(res));
3535         if (!vc4_hdmi->phy_regs)
3536                 return -ENOMEM;
3537
3538         res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "packet");
3539         if (!res)
3540                 return -ENODEV;
3541
3542         vc4_hdmi->ram_regs = devm_ioremap(dev, res->start, resource_size(res));
3543         if (!vc4_hdmi->ram_regs)
3544                 return -ENOMEM;
3545
3546         res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "rm");
3547         if (!res)
3548                 return -ENODEV;
3549
3550         vc4_hdmi->rm_regs = devm_ioremap(dev, res->start, resource_size(res));
3551         if (!vc4_hdmi->rm_regs)
3552                 return -ENOMEM;
3553
3554         vc4_hdmi->hsm_clock = devm_clk_get(dev, "hdmi");
3555         if (IS_ERR(vc4_hdmi->hsm_clock)) {
3556                 DRM_ERROR("Failed to get HDMI state machine clock\n");
3557                 return PTR_ERR(vc4_hdmi->hsm_clock);
3558         }
3559
3560         vc4_hdmi->pixel_bvb_clock = devm_clk_get(dev, "bvb");
3561         if (IS_ERR(vc4_hdmi->pixel_bvb_clock)) {
3562                 DRM_ERROR("Failed to get pixel bvb clock\n");
3563                 return PTR_ERR(vc4_hdmi->pixel_bvb_clock);
3564         }
3565
3566         vc4_hdmi->audio_clock = devm_clk_get(dev, "audio");
3567         if (IS_ERR(vc4_hdmi->audio_clock)) {
3568                 DRM_ERROR("Failed to get audio clock\n");
3569                 return PTR_ERR(vc4_hdmi->audio_clock);
3570         }
3571
3572         vc4_hdmi->cec_clock = devm_clk_get(dev, "cec");
3573         if (IS_ERR(vc4_hdmi->cec_clock)) {
3574                 DRM_ERROR("Failed to get CEC clock\n");
3575                 return PTR_ERR(vc4_hdmi->cec_clock);
3576         }
3577
3578         vc4_hdmi->reset = devm_reset_control_get(dev, NULL);
3579         if (IS_ERR(vc4_hdmi->reset)) {
3580                 DRM_ERROR("Failed to get HDMI reset line\n");
3581                 return PTR_ERR(vc4_hdmi->reset);
3582         }
3583
3584         ret = vc4_hdmi_build_regset(drm, vc4_hdmi, &vc4_hdmi->hdmi_regset, VC4_HDMI);
3585         if (ret)
3586                 return ret;
3587
3588         ret = vc4_hdmi_build_regset(drm, vc4_hdmi, &vc4_hdmi->hd_regset, VC4_HD);
3589         if (ret)
3590                 return ret;
3591
3592         ret = vc4_hdmi_build_regset(drm, vc4_hdmi, &vc4_hdmi->cec_regset, VC5_CEC);
3593         if (ret)
3594                 return ret;
3595
3596         ret = vc4_hdmi_build_regset(drm, vc4_hdmi, &vc4_hdmi->csc_regset, VC5_CSC);
3597         if (ret)
3598                 return ret;
3599
3600         ret = vc4_hdmi_build_regset(drm, vc4_hdmi, &vc4_hdmi->dvp_regset, VC5_DVP);
3601         if (ret)
3602                 return ret;
3603
3604         ret = vc4_hdmi_build_regset(drm, vc4_hdmi, &vc4_hdmi->phy_regset, VC5_PHY);
3605         if (ret)
3606                 return ret;
3607
3608         ret = vc4_hdmi_build_regset(drm, vc4_hdmi, &vc4_hdmi->ram_regset, VC5_RAM);
3609         if (ret)
3610                 return ret;
3611
3612         ret = vc4_hdmi_build_regset(drm, vc4_hdmi, &vc4_hdmi->rm_regset, VC5_RM);
3613         if (ret)
3614                 return ret;
3615
3616         return 0;
3617 }
3618
3619 static int __maybe_unused vc4_hdmi_runtime_suspend(struct device *dev)
3620 {
3621         struct vc4_hdmi *vc4_hdmi = dev_get_drvdata(dev);
3622
3623         clk_disable_unprepare(vc4_hdmi->hsm_clock);
3624
3625         return 0;
3626 }
3627
3628 static int vc4_hdmi_runtime_resume(struct device *dev)
3629 {
3630         struct vc4_hdmi *vc4_hdmi = dev_get_drvdata(dev);
3631         int ret;
3632
3633         ret = clk_prepare_enable(vc4_hdmi->hsm_clock);
3634         if (ret)
3635                 return ret;
3636
3637         if (vc4_hdmi->variant->reset)
3638                 vc4_hdmi->variant->reset(vc4_hdmi);
3639
3640         ret = vc4_hdmi_cec_resume(vc4_hdmi);
3641         if (ret) {
3642                 clk_disable_unprepare(vc4_hdmi->hsm_clock);
3643                 return ret;
3644         }
3645
3646         return 0;
3647 }
3648
3649 static void vc4_hdmi_put_ddc_device(void *ptr)
3650 {
3651         struct vc4_hdmi *vc4_hdmi = ptr;
3652
3653         put_device(&vc4_hdmi->ddc->dev);
3654 }
3655
3656 #ifdef CONFIG_EXTCON
3657 static const unsigned int vc4_hdmi_extcon_cable[] = {
3658         EXTCON_DISP_HDMI,
3659         EXTCON_NONE,
3660 };
3661 #endif
3662
3663 static int vc4_hdmi_bind(struct device *dev, struct device *master, void *data)
3664 {
3665         const struct vc4_hdmi_variant *variant = of_device_get_match_data(dev);
3666         struct platform_device *pdev = to_platform_device(dev);
3667         struct drm_device *drm = dev_get_drvdata(master);
3668         struct vc4_hdmi *vc4_hdmi;
3669         struct drm_encoder *encoder;
3670         struct device_node *ddc_node;
3671         int ret;
3672
3673         vc4_hdmi = drmm_kzalloc(drm, sizeof(*vc4_hdmi), GFP_KERNEL);
3674         if (!vc4_hdmi)
3675                 return -ENOMEM;
3676
3677         ret = drmm_mutex_init(drm, &vc4_hdmi->mutex);
3678         if (ret)
3679                 return ret;
3680
3681         spin_lock_init(&vc4_hdmi->hw_lock);
3682         INIT_DELAYED_WORK(&vc4_hdmi->scrambling_work, vc4_hdmi_scrambling_wq);
3683
3684         dev_set_drvdata(dev, vc4_hdmi);
3685         encoder = &vc4_hdmi->encoder.base;
3686         vc4_hdmi->encoder.type = variant->encoder_type;
3687         vc4_hdmi->encoder.pre_crtc_configure = vc4_hdmi_encoder_pre_crtc_configure;
3688         vc4_hdmi->encoder.pre_crtc_enable = vc4_hdmi_encoder_pre_crtc_enable;
3689         vc4_hdmi->encoder.post_crtc_enable = vc4_hdmi_encoder_post_crtc_enable;
3690         vc4_hdmi->encoder.post_crtc_disable = vc4_hdmi_encoder_post_crtc_disable;
3691         vc4_hdmi->encoder.post_crtc_powerdown = vc4_hdmi_encoder_post_crtc_powerdown;
3692         vc4_hdmi->pdev = pdev;
3693         vc4_hdmi->variant = variant;
3694
3695         /*
3696          * Since we don't know the state of the controller and its
3697          * display (if any), let's assume it's always enabled.
3698          * vc4_hdmi_disable_scrambling() will thus run at boot, make
3699          * sure it's disabled, and avoid any inconsistency.
3700          */
3701         if (variant->max_pixel_clock > HDMI_14_MAX_TMDS_CLK)
3702                 vc4_hdmi->scdc_enabled = true;
3703
3704         ret = variant->init_resources(drm, vc4_hdmi);
3705         if (ret)
3706                 return ret;
3707
3708         ddc_node = of_parse_phandle(dev->of_node, "ddc", 0);
3709         if (!ddc_node) {
3710                 DRM_ERROR("Failed to find ddc node in device tree\n");
3711                 return -ENODEV;
3712         }
3713
3714         vc4_hdmi->ddc = of_find_i2c_adapter_by_node(ddc_node);
3715         of_node_put(ddc_node);
3716         if (!vc4_hdmi->ddc) {
3717                 DRM_DEBUG("Failed to get ddc i2c adapter by node\n");
3718                 return -EPROBE_DEFER;
3719         }
3720
3721         ret = devm_add_action_or_reset(dev, vc4_hdmi_put_ddc_device, vc4_hdmi);
3722         if (ret)
3723                 return ret;
3724
3725 #ifdef CONFIG_EXTCON
3726         vc4_hdmi->status = connector_status_disconnected;
3727
3728         /* Initialize extcon device */
3729         vc4_hdmi->edev = devm_extcon_dev_allocate(dev, vc4_hdmi_extcon_cable);
3730         if (IS_ERR(vc4_hdmi->edev)) {
3731                 dev_err(dev, "failed to allocate memory for extcon\n");
3732                 return PTR_ERR(vc4_hdmi->edev);
3733         }
3734
3735         ret = devm_extcon_dev_register(dev, vc4_hdmi->edev);
3736         if (ret) {
3737                 dev_err(dev, "failed to register extcon device\n");
3738                 return ret;
3739         }
3740 #endif
3741
3742         /* Only use the GPIO HPD pin if present in the DT, otherwise
3743          * we'll use the HDMI core's register.
3744          */
3745         vc4_hdmi->hpd_gpio = devm_gpiod_get_optional(dev, "hpd", GPIOD_IN);
3746         if (IS_ERR(vc4_hdmi->hpd_gpio)) {
3747                 return PTR_ERR(vc4_hdmi->hpd_gpio);
3748         }
3749
3750         vc4_hdmi->disable_wifi_frequencies =
3751                 of_property_read_bool(dev->of_node, "wifi-2.4ghz-coexistence");
3752
3753         /*
3754          * If we boot without any cable connected to the HDMI connector,
3755          * the firmware will skip the HSM initialization and leave it
3756          * with a rate of 0, resulting in a bus lockup when we're
3757          * accessing the registers even if it's enabled.
3758          *
3759          * Let's put a sensible default at runtime_resume so that we
3760          * don't end up in this situation.
3761          */
3762         ret = clk_set_min_rate(vc4_hdmi->hsm_clock, HSM_MIN_CLOCK_FREQ);
3763         if (ret)
3764                 return ret;
3765
3766         ret = devm_pm_runtime_enable(dev);
3767         if (ret)
3768                 return ret;
3769
3770         ret = pm_runtime_resume_and_get(dev);
3771         if (ret)
3772                 return ret;
3773
3774         if ((of_device_is_compatible(dev->of_node, "brcm,bcm2711-hdmi0") ||
3775              of_device_is_compatible(dev->of_node, "brcm,bcm2711-hdmi1")) &&
3776             HDMI_READ(HDMI_VID_CTL) & VC4_HD_VID_CTL_ENABLE) {
3777                 clk_prepare_enable(vc4_hdmi->pixel_clock);
3778                 clk_prepare_enable(vc4_hdmi->hsm_clock);
3779                 clk_prepare_enable(vc4_hdmi->pixel_bvb_clock);
3780         }
3781
3782         ret = drmm_encoder_init(drm, encoder,
3783                                 &vc4_hdmi_encoder_funcs,
3784                                 DRM_MODE_ENCODER_TMDS,
3785                                 NULL);
3786         if (ret)
3787                 goto err_put_runtime_pm;
3788
3789         drm_encoder_helper_add(encoder, &vc4_hdmi_encoder_helper_funcs);
3790
3791         ret = vc4_hdmi_connector_init(drm, vc4_hdmi);
3792         if (ret)
3793                 goto err_put_runtime_pm;
3794
3795         ret = vc4_hdmi_hotplug_init(vc4_hdmi);
3796         if (ret)
3797                 goto err_put_runtime_pm;
3798
3799         ret = vc4_hdmi_cec_init(vc4_hdmi);
3800         if (ret)
3801                 goto err_put_runtime_pm;
3802
3803         ret = vc4_hdmi_audio_init(vc4_hdmi);
3804         if (ret)
3805                 goto err_put_runtime_pm;
3806
3807         pm_runtime_put_sync(dev);
3808
3809         return 0;
3810
3811 err_put_runtime_pm:
3812         pm_runtime_put_sync(dev);
3813
3814         return ret;
3815 }
3816
3817 static const struct component_ops vc4_hdmi_ops = {
3818         .bind   = vc4_hdmi_bind,
3819 };
3820
3821 static int vc4_hdmi_dev_probe(struct platform_device *pdev)
3822 {
3823         return component_add(&pdev->dev, &vc4_hdmi_ops);
3824 }
3825
3826 static int vc4_hdmi_dev_remove(struct platform_device *pdev)
3827 {
3828         component_del(&pdev->dev, &vc4_hdmi_ops);
3829         return 0;
3830 }
3831
3832 static const struct vc4_hdmi_variant bcm2835_variant = {
3833         .encoder_type           = VC4_ENCODER_TYPE_HDMI0,
3834         .debugfs_name           = "hdmi_regs",
3835         .card_name              = "vc4-hdmi",
3836         .max_pixel_clock        = 162000000,
3837         .registers              = vc4_hdmi_fields,
3838         .num_registers          = ARRAY_SIZE(vc4_hdmi_fields),
3839
3840         .init_resources         = vc4_hdmi_init_resources,
3841         .csc_setup              = vc4_hdmi_csc_setup,
3842         .reset                  = vc4_hdmi_reset,
3843         .set_timings            = vc4_hdmi_set_timings,
3844         .phy_init               = vc4_hdmi_phy_init,
3845         .phy_disable            = vc4_hdmi_phy_disable,
3846         .phy_rng_enable         = vc4_hdmi_phy_rng_enable,
3847         .phy_rng_disable        = vc4_hdmi_phy_rng_disable,
3848         .channel_map            = vc4_hdmi_channel_map,
3849         .supports_hdr           = false,
3850 };
3851
3852 static const struct vc4_hdmi_variant bcm2711_hdmi0_variant = {
3853         .encoder_type           = VC4_ENCODER_TYPE_HDMI0,
3854         .debugfs_name           = "hdmi0_regs",
3855         .card_name              = "vc4-hdmi-0",
3856         .max_pixel_clock        = 600000000,
3857         .registers              = vc5_hdmi_hdmi0_fields,
3858         .num_registers          = ARRAY_SIZE(vc5_hdmi_hdmi0_fields),
3859         .phy_lane_mapping       = {
3860                 PHY_LANE_0,
3861                 PHY_LANE_1,
3862                 PHY_LANE_2,
3863                 PHY_LANE_CK,
3864         },
3865         .unsupported_odd_h_timings      = true,
3866         .external_irq_controller        = true,
3867
3868         .init_resources         = vc5_hdmi_init_resources,
3869         .csc_setup              = vc5_hdmi_csc_setup,
3870         .reset                  = vc5_hdmi_reset,
3871         .set_timings            = vc5_hdmi_set_timings,
3872         .phy_init               = vc5_hdmi_phy_init,
3873         .phy_disable            = vc5_hdmi_phy_disable,
3874         .phy_rng_enable         = vc5_hdmi_phy_rng_enable,
3875         .phy_rng_disable        = vc5_hdmi_phy_rng_disable,
3876         .channel_map            = vc5_hdmi_channel_map,
3877         .supports_hdr           = true,
3878         .hp_detect              = vc5_hdmi_hp_detect,
3879 };
3880
3881 static const struct vc4_hdmi_variant bcm2711_hdmi1_variant = {
3882         .encoder_type           = VC4_ENCODER_TYPE_HDMI1,
3883         .debugfs_name           = "hdmi1_regs",
3884         .card_name              = "vc4-hdmi-1",
3885         .max_pixel_clock        = HDMI_14_MAX_TMDS_CLK,
3886         .registers              = vc5_hdmi_hdmi1_fields,
3887         .num_registers          = ARRAY_SIZE(vc5_hdmi_hdmi1_fields),
3888         .phy_lane_mapping       = {
3889                 PHY_LANE_1,
3890                 PHY_LANE_0,
3891                 PHY_LANE_CK,
3892                 PHY_LANE_2,
3893         },
3894         .unsupported_odd_h_timings      = true,
3895         .external_irq_controller        = true,
3896
3897         .init_resources         = vc5_hdmi_init_resources,
3898         .csc_setup              = vc5_hdmi_csc_setup,
3899         .reset                  = vc5_hdmi_reset,
3900         .set_timings            = vc5_hdmi_set_timings,
3901         .phy_init               = vc5_hdmi_phy_init,
3902         .phy_disable            = vc5_hdmi_phy_disable,
3903         .phy_rng_enable         = vc5_hdmi_phy_rng_enable,
3904         .phy_rng_disable        = vc5_hdmi_phy_rng_disable,
3905         .channel_map            = vc5_hdmi_channel_map,
3906         .supports_hdr           = true,
3907         .hp_detect              = vc5_hdmi_hp_detect,
3908 };
3909
3910 static const struct of_device_id vc4_hdmi_dt_match[] = {
3911         { .compatible = "brcm,bcm2835-hdmi", .data = &bcm2835_variant },
3912         { .compatible = "brcm,bcm2711-hdmi0", .data = &bcm2711_hdmi0_variant },
3913         { .compatible = "brcm,bcm2711-hdmi1", .data = &bcm2711_hdmi1_variant },
3914         {}
3915 };
3916
3917 static const struct dev_pm_ops vc4_hdmi_pm_ops = {
3918         SET_RUNTIME_PM_OPS(vc4_hdmi_runtime_suspend,
3919                            vc4_hdmi_runtime_resume,
3920                            NULL)
3921 };
3922
3923 struct platform_driver vc4_hdmi_driver = {
3924         .probe = vc4_hdmi_dev_probe,
3925         .remove = vc4_hdmi_dev_remove,
3926         .driver = {
3927                 .name = "vc4_hdmi",
3928                 .of_match_table = vc4_hdmi_dt_match,
3929                 .pm = &vc4_hdmi_pm_ops,
3930         },
3931 };