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