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