drm/amd/display: add CRTC gamma TF driver-specific property
[linux-2.6-microblaze.git] / drivers / gpu / drm / amd / display / amdgpu_dm / amdgpu_dm_color.c
1 /*
2  * Copyright 2018 Advanced Micro Devices, Inc.
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
17  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
18  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
20  * OTHER DEALINGS IN THE SOFTWARE.
21  *
22  * Authors: AMD
23  *
24  */
25 #include "amdgpu.h"
26 #include "amdgpu_mode.h"
27 #include "amdgpu_dm.h"
28 #include "dc.h"
29 #include "modules/color/color_gamma.h"
30 #include "basics/conversion.h"
31
32 /**
33  * DOC: overview
34  *
35  * The DC interface to HW gives us the following color management blocks
36  * per pipe (surface):
37  *
38  * - Input gamma LUT (de-normalized)
39  * - Input CSC (normalized)
40  * - Surface degamma LUT (normalized)
41  * - Surface CSC (normalized)
42  * - Surface regamma LUT (normalized)
43  * - Output CSC (normalized)
44  *
45  * But these aren't a direct mapping to DRM color properties. The current DRM
46  * interface exposes CRTC degamma, CRTC CTM and CRTC regamma while our hardware
47  * is essentially giving:
48  *
49  * Plane CTM -> Plane degamma -> Plane CTM -> Plane regamma -> Plane CTM
50  *
51  * The input gamma LUT block isn't really applicable here since it operates
52  * on the actual input data itself rather than the HW fp representation. The
53  * input and output CSC blocks are technically available to use as part of
54  * the DC interface but are typically used internally by DC for conversions
55  * between color spaces. These could be blended together with user
56  * adjustments in the future but for now these should remain untouched.
57  *
58  * The pipe blending also happens after these blocks so we don't actually
59  * support any CRTC props with correct blending with multiple planes - but we
60  * can still support CRTC color management properties in DM in most single
61  * plane cases correctly with clever management of the DC interface in DM.
62  *
63  * As per DRM documentation, blocks should be in hardware bypass when their
64  * respective property is set to NULL. A linear DGM/RGM LUT should also
65  * considered as putting the respective block into bypass mode.
66  *
67  * This means that the following
68  * configuration is assumed to be the default:
69  *
70  * Plane DGM Bypass -> Plane CTM Bypass -> Plane RGM Bypass -> ...
71  * CRTC DGM Bypass -> CRTC CTM Bypass -> CRTC RGM Bypass
72  */
73
74 #define MAX_DRM_LUT_VALUE 0xFFFF
75
76 /**
77  * amdgpu_dm_init_color_mod - Initialize the color module.
78  *
79  * We're not using the full color module, only certain components.
80  * Only call setup functions for components that we need.
81  */
82 void amdgpu_dm_init_color_mod(void)
83 {
84         setup_x_points_distribution();
85 }
86
87 #ifdef AMD_PRIVATE_COLOR
88 /* Pre-defined Transfer Functions (TF)
89  *
90  * AMD driver supports pre-defined mathematical functions for transferring
91  * between encoded values and optical/linear space. Depending on HW color caps,
92  * ROMs and curves built by the AMD color module support these transforms.
93  *
94  * The driver-specific color implementation exposes properties for pre-blending
95  * degamma TF, shaper TF (before 3D LUT), and blend(dpp.ogam) TF and
96  * post-blending regamma (mpc.ogam) TF. However, only pre-blending degamma
97  * supports ROM curves. AMD color module uses pre-defined coefficients to build
98  * curves for the other blocks. What can be done by each color block is
99  * described by struct dpp_color_capsand struct mpc_color_caps.
100  *
101  * AMD driver-specific color API exposes the following pre-defined transfer
102  * functions:
103  *
104  * - Identity: linear/identity relationship between pixel value and
105  *   luminance value;
106  * - Gamma 2.2, Gamma 2.4, Gamma 2.6: pure power functions;
107  * - sRGB: 2.4: The piece-wise transfer function from IEC 61966-2-1:1999;
108  * - BT.709: has a linear segment in the bottom part and then a power function
109  *   with a 0.45 (~1/2.22) gamma for the rest of the range; standardized by
110  *   ITU-R BT.709-6;
111  * - PQ (Perceptual Quantizer): used for HDR display, allows luminance range
112  *   capability of 0 to 10,000 nits; standardized by SMPTE ST 2084.
113  *
114  * The AMD color model is designed with an assumption that SDR (sRGB, BT.709,
115  * Gamma 2.2, etc.) peak white maps (normalized to 1.0 FP) to 80 nits in the PQ
116  * system. This has the implication that PQ EOTF (non-linear to linear) maps to
117  * [0.0..125.0] where 125.0 = 10,000 nits / 80 nits.
118  *
119  * Non-linear and linear forms are described in the table below:
120  *
121  * ┌───────────┬─────────────────────┬──────────────────────┐
122  * │           │     Non-linear      │   Linear             │
123  * ├───────────┼─────────────────────┼──────────────────────┤
124  * │      sRGB │ UNORM or [0.0, 1.0] │ [0.0, 1.0]           │
125  * ├───────────┼─────────────────────┼──────────────────────┤
126  * │     BT709 │ UNORM or [0.0, 1.0] │ [0.0, 1.0]           │
127  * ├───────────┼─────────────────────┼──────────────────────┤
128  * │ Gamma 2.x │ UNORM or [0.0, 1.0] │ [0.0, 1.0]           │
129  * ├───────────┼─────────────────────┼──────────────────────┤
130  * │        PQ │ UNORM or FP16 CCCS* │ [0.0, 125.0]         │
131  * ├───────────┼─────────────────────┼──────────────────────┤
132  * │  Identity │ UNORM or FP16 CCCS* │ [0.0, 1.0] or CCCS** │
133  * └───────────┴─────────────────────┴──────────────────────┘
134  * * CCCS: Windows canonical composition color space
135  * ** Respectively
136  *
137  * In the driver-specific API, color block names attached to TF properties
138  * suggest the intention regarding non-linear encoding pixel's luminance
139  * values. As some newer encodings don't use gamma curve, we make encoding and
140  * decoding explicit by defining an enum list of transfer functions supported
141  * in terms of EOTF and inverse EOTF, where:
142  *
143  * - EOTF (electro-optical transfer function): is the transfer function to go
144  *   from the encoded value to an optical (linear) value. De-gamma functions
145  *   traditionally do this.
146  * - Inverse EOTF (simply the inverse of the EOTF): is usually intended to go
147  *   from an optical/linear space (which might have been used for blending)
148  *   back to the encoded values. Gamma functions traditionally do this.
149  */
150 static const char * const
151 amdgpu_transfer_function_names[] = {
152         [AMDGPU_TRANSFER_FUNCTION_DEFAULT]              = "Default",
153         [AMDGPU_TRANSFER_FUNCTION_IDENTITY]             = "Identity",
154         [AMDGPU_TRANSFER_FUNCTION_SRGB_EOTF]            = "sRGB EOTF",
155         [AMDGPU_TRANSFER_FUNCTION_BT709_INV_OETF]       = "BT.709 inv_OETF",
156         [AMDGPU_TRANSFER_FUNCTION_PQ_EOTF]              = "PQ EOTF",
157         [AMDGPU_TRANSFER_FUNCTION_GAMMA22_EOTF]         = "Gamma 2.2 EOTF",
158         [AMDGPU_TRANSFER_FUNCTION_GAMMA24_EOTF]         = "Gamma 2.4 EOTF",
159         [AMDGPU_TRANSFER_FUNCTION_GAMMA26_EOTF]         = "Gamma 2.6 EOTF",
160         [AMDGPU_TRANSFER_FUNCTION_SRGB_INV_EOTF]        = "sRGB inv_EOTF",
161         [AMDGPU_TRANSFER_FUNCTION_BT709_OETF]           = "BT.709 OETF",
162         [AMDGPU_TRANSFER_FUNCTION_PQ_INV_EOTF]          = "PQ inv_EOTF",
163         [AMDGPU_TRANSFER_FUNCTION_GAMMA22_INV_EOTF]     = "Gamma 2.2 inv_EOTF",
164         [AMDGPU_TRANSFER_FUNCTION_GAMMA24_INV_EOTF]     = "Gamma 2.4 inv_EOTF",
165         [AMDGPU_TRANSFER_FUNCTION_GAMMA26_INV_EOTF]     = "Gamma 2.6 inv_EOTF",
166 };
167
168 static const u32 amdgpu_eotf =
169         BIT(AMDGPU_TRANSFER_FUNCTION_SRGB_EOTF) |
170         BIT(AMDGPU_TRANSFER_FUNCTION_BT709_INV_OETF) |
171         BIT(AMDGPU_TRANSFER_FUNCTION_PQ_EOTF) |
172         BIT(AMDGPU_TRANSFER_FUNCTION_GAMMA22_EOTF) |
173         BIT(AMDGPU_TRANSFER_FUNCTION_GAMMA24_EOTF) |
174         BIT(AMDGPU_TRANSFER_FUNCTION_GAMMA26_EOTF);
175
176 static const u32 amdgpu_inv_eotf =
177         BIT(AMDGPU_TRANSFER_FUNCTION_SRGB_INV_EOTF) |
178         BIT(AMDGPU_TRANSFER_FUNCTION_BT709_OETF) |
179         BIT(AMDGPU_TRANSFER_FUNCTION_PQ_INV_EOTF) |
180         BIT(AMDGPU_TRANSFER_FUNCTION_GAMMA22_INV_EOTF) |
181         BIT(AMDGPU_TRANSFER_FUNCTION_GAMMA24_INV_EOTF) |
182         BIT(AMDGPU_TRANSFER_FUNCTION_GAMMA26_INV_EOTF);
183
184 static struct drm_property *
185 amdgpu_create_tf_property(struct drm_device *dev,
186                           const char *name,
187                           u32 supported_tf)
188 {
189         u32 transfer_functions = supported_tf |
190                                  BIT(AMDGPU_TRANSFER_FUNCTION_DEFAULT) |
191                                  BIT(AMDGPU_TRANSFER_FUNCTION_IDENTITY);
192         struct drm_prop_enum_list enum_list[AMDGPU_TRANSFER_FUNCTION_COUNT];
193         int i, len;
194
195         len = 0;
196         for (i = 0; i < AMDGPU_TRANSFER_FUNCTION_COUNT; i++) {
197                 if ((transfer_functions & BIT(i)) == 0)
198                         continue;
199
200                 enum_list[len].type = i;
201                 enum_list[len].name = amdgpu_transfer_function_names[i];
202                 len++;
203         }
204
205         return drm_property_create_enum(dev, DRM_MODE_PROP_ENUM,
206                                         name, enum_list, len);
207 }
208
209 int
210 amdgpu_dm_create_color_properties(struct amdgpu_device *adev)
211 {
212         struct drm_property *prop;
213
214         prop = drm_property_create(adev_to_drm(adev),
215                                    DRM_MODE_PROP_BLOB,
216                                    "AMD_PLANE_DEGAMMA_LUT", 0);
217         if (!prop)
218                 return -ENOMEM;
219         adev->mode_info.plane_degamma_lut_property = prop;
220
221         prop = drm_property_create_range(adev_to_drm(adev),
222                                          DRM_MODE_PROP_IMMUTABLE,
223                                          "AMD_PLANE_DEGAMMA_LUT_SIZE",
224                                          0, UINT_MAX);
225         if (!prop)
226                 return -ENOMEM;
227         adev->mode_info.plane_degamma_lut_size_property = prop;
228
229         prop = amdgpu_create_tf_property(adev_to_drm(adev),
230                                          "AMD_PLANE_DEGAMMA_TF",
231                                          amdgpu_eotf);
232         if (!prop)
233                 return -ENOMEM;
234         adev->mode_info.plane_degamma_tf_property = prop;
235
236         prop = drm_property_create_range(adev_to_drm(adev),
237                                          0, "AMD_PLANE_HDR_MULT", 0, U64_MAX);
238         if (!prop)
239                 return -ENOMEM;
240         adev->mode_info.plane_hdr_mult_property = prop;
241
242         prop = drm_property_create(adev_to_drm(adev),
243                                    DRM_MODE_PROP_BLOB,
244                                    "AMD_PLANE_SHAPER_LUT", 0);
245         if (!prop)
246                 return -ENOMEM;
247         adev->mode_info.plane_shaper_lut_property = prop;
248
249         prop = drm_property_create_range(adev_to_drm(adev),
250                                          DRM_MODE_PROP_IMMUTABLE,
251                                          "AMD_PLANE_SHAPER_LUT_SIZE", 0, UINT_MAX);
252         if (!prop)
253                 return -ENOMEM;
254         adev->mode_info.plane_shaper_lut_size_property = prop;
255
256         prop = amdgpu_create_tf_property(adev_to_drm(adev),
257                                          "AMD_PLANE_SHAPER_TF",
258                                          amdgpu_inv_eotf);
259         if (!prop)
260                 return -ENOMEM;
261         adev->mode_info.plane_shaper_tf_property = prop;
262
263         prop = drm_property_create(adev_to_drm(adev),
264                                    DRM_MODE_PROP_BLOB,
265                                    "AMD_PLANE_LUT3D", 0);
266         if (!prop)
267                 return -ENOMEM;
268         adev->mode_info.plane_lut3d_property = prop;
269
270         prop = drm_property_create_range(adev_to_drm(adev),
271                                          DRM_MODE_PROP_IMMUTABLE,
272                                          "AMD_PLANE_LUT3D_SIZE", 0, UINT_MAX);
273         if (!prop)
274                 return -ENOMEM;
275         adev->mode_info.plane_lut3d_size_property = prop;
276
277         prop = drm_property_create(adev_to_drm(adev),
278                                    DRM_MODE_PROP_BLOB,
279                                    "AMD_PLANE_BLEND_LUT", 0);
280         if (!prop)
281                 return -ENOMEM;
282         adev->mode_info.plane_blend_lut_property = prop;
283
284         prop = drm_property_create_range(adev_to_drm(adev),
285                                          DRM_MODE_PROP_IMMUTABLE,
286                                          "AMD_PLANE_BLEND_LUT_SIZE", 0, UINT_MAX);
287         if (!prop)
288                 return -ENOMEM;
289         adev->mode_info.plane_blend_lut_size_property = prop;
290
291         prop = amdgpu_create_tf_property(adev_to_drm(adev),
292                                          "AMD_PLANE_BLEND_TF",
293                                          amdgpu_eotf);
294         if (!prop)
295                 return -ENOMEM;
296         adev->mode_info.plane_blend_tf_property = prop;
297
298         prop = amdgpu_create_tf_property(adev_to_drm(adev),
299                                          "AMD_CRTC_REGAMMA_TF",
300                                          amdgpu_inv_eotf);
301         if (!prop)
302                 return -ENOMEM;
303         adev->mode_info.regamma_tf_property = prop;
304
305         return 0;
306 }
307 #endif
308
309 /**
310  * __extract_blob_lut - Extracts the DRM lut and lut size from a blob.
311  * @blob: DRM color mgmt property blob
312  * @size: lut size
313  *
314  * Returns:
315  * DRM LUT or NULL
316  */
317 static const struct drm_color_lut *
318 __extract_blob_lut(const struct drm_property_blob *blob, uint32_t *size)
319 {
320         *size = blob ? drm_color_lut_size(blob) : 0;
321         return blob ? (struct drm_color_lut *)blob->data : NULL;
322 }
323
324 /**
325  * __is_lut_linear - check if the given lut is a linear mapping of values
326  * @lut: given lut to check values
327  * @size: lut size
328  *
329  * It is considered linear if the lut represents:
330  * f(a) = (0xFF00/MAX_COLOR_LUT_ENTRIES-1)a; for integer a in [0,
331  * MAX_COLOR_LUT_ENTRIES)
332  *
333  * Returns:
334  * True if the given lut is a linear mapping of values, i.e. it acts like a
335  * bypass LUT. Otherwise, false.
336  */
337 static bool __is_lut_linear(const struct drm_color_lut *lut, uint32_t size)
338 {
339         int i;
340         uint32_t expected;
341         int delta;
342
343         for (i = 0; i < size; i++) {
344                 /* All color values should equal */
345                 if ((lut[i].red != lut[i].green) || (lut[i].green != lut[i].blue))
346                         return false;
347
348                 expected = i * MAX_DRM_LUT_VALUE / (size-1);
349
350                 /* Allow a +/-1 error. */
351                 delta = lut[i].red - expected;
352                 if (delta < -1 || 1 < delta)
353                         return false;
354         }
355         return true;
356 }
357
358 /**
359  * __drm_lut_to_dc_gamma - convert the drm_color_lut to dc_gamma.
360  * @lut: DRM lookup table for color conversion
361  * @gamma: DC gamma to set entries
362  * @is_legacy: legacy or atomic gamma
363  *
364  * The conversion depends on the size of the lut - whether or not it's legacy.
365  */
366 static void __drm_lut_to_dc_gamma(const struct drm_color_lut *lut,
367                                   struct dc_gamma *gamma, bool is_legacy)
368 {
369         uint32_t r, g, b;
370         int i;
371
372         if (is_legacy) {
373                 for (i = 0; i < MAX_COLOR_LEGACY_LUT_ENTRIES; i++) {
374                         r = drm_color_lut_extract(lut[i].red, 16);
375                         g = drm_color_lut_extract(lut[i].green, 16);
376                         b = drm_color_lut_extract(lut[i].blue, 16);
377
378                         gamma->entries.red[i] = dc_fixpt_from_int(r);
379                         gamma->entries.green[i] = dc_fixpt_from_int(g);
380                         gamma->entries.blue[i] = dc_fixpt_from_int(b);
381                 }
382                 return;
383         }
384
385         /* else */
386         for (i = 0; i < MAX_COLOR_LUT_ENTRIES; i++) {
387                 r = drm_color_lut_extract(lut[i].red, 16);
388                 g = drm_color_lut_extract(lut[i].green, 16);
389                 b = drm_color_lut_extract(lut[i].blue, 16);
390
391                 gamma->entries.red[i] = dc_fixpt_from_fraction(r, MAX_DRM_LUT_VALUE);
392                 gamma->entries.green[i] = dc_fixpt_from_fraction(g, MAX_DRM_LUT_VALUE);
393                 gamma->entries.blue[i] = dc_fixpt_from_fraction(b, MAX_DRM_LUT_VALUE);
394         }
395 }
396
397 /**
398  * __drm_ctm_to_dc_matrix - converts a DRM CTM to a DC CSC float matrix
399  * @ctm: DRM color transformation matrix
400  * @matrix: DC CSC float matrix
401  *
402  * The matrix needs to be a 3x4 (12 entry) matrix.
403  */
404 static void __drm_ctm_to_dc_matrix(const struct drm_color_ctm *ctm,
405                                    struct fixed31_32 *matrix)
406 {
407         int64_t val;
408         int i;
409
410         /*
411          * DRM gives a 3x3 matrix, but DC wants 3x4. Assuming we're operating
412          * with homogeneous coordinates, augment the matrix with 0's.
413          *
414          * The format provided is S31.32, using signed-magnitude representation.
415          * Our fixed31_32 is also S31.32, but is using 2's complement. We have
416          * to convert from signed-magnitude to 2's complement.
417          */
418         for (i = 0; i < 12; i++) {
419                 /* Skip 4th element */
420                 if (i % 4 == 3) {
421                         matrix[i] = dc_fixpt_zero;
422                         continue;
423                 }
424
425                 /* gamut_remap_matrix[i] = ctm[i - floor(i/4)] */
426                 val = ctm->matrix[i - (i / 4)];
427                 /* If negative, convert to 2's complement. */
428                 if (val & (1ULL << 63))
429                         val = -(val & ~(1ULL << 63));
430
431                 matrix[i].value = val;
432         }
433 }
434
435 /**
436  * __set_legacy_tf - Calculates the legacy transfer function
437  * @func: transfer function
438  * @lut: lookup table that defines the color space
439  * @lut_size: size of respective lut
440  * @has_rom: if ROM can be used for hardcoded curve
441  *
442  * Only for sRGB input space
443  *
444  * Returns:
445  * 0 in case of success, -ENOMEM if fails
446  */
447 static int __set_legacy_tf(struct dc_transfer_func *func,
448                            const struct drm_color_lut *lut, uint32_t lut_size,
449                            bool has_rom)
450 {
451         struct dc_gamma *gamma = NULL;
452         struct calculate_buffer cal_buffer = {0};
453         bool res;
454
455         ASSERT(lut && lut_size == MAX_COLOR_LEGACY_LUT_ENTRIES);
456
457         cal_buffer.buffer_index = -1;
458
459         gamma = dc_create_gamma();
460         if (!gamma)
461                 return -ENOMEM;
462
463         gamma->type = GAMMA_RGB_256;
464         gamma->num_entries = lut_size;
465         __drm_lut_to_dc_gamma(lut, gamma, true);
466
467         res = mod_color_calculate_regamma_params(func, gamma, true, has_rom,
468                                                  NULL, &cal_buffer);
469
470         dc_gamma_release(&gamma);
471
472         return res ? 0 : -ENOMEM;
473 }
474
475 /**
476  * __set_output_tf - calculates the output transfer function based on expected input space.
477  * @func: transfer function
478  * @lut: lookup table that defines the color space
479  * @lut_size: size of respective lut
480  * @has_rom: if ROM can be used for hardcoded curve
481  *
482  * Returns:
483  * 0 in case of success. -ENOMEM if fails.
484  */
485 static int __set_output_tf(struct dc_transfer_func *func,
486                            const struct drm_color_lut *lut, uint32_t lut_size,
487                            bool has_rom)
488 {
489         struct dc_gamma *gamma = NULL;
490         struct calculate_buffer cal_buffer = {0};
491         bool res;
492
493         ASSERT(lut && lut_size == MAX_COLOR_LUT_ENTRIES);
494
495         cal_buffer.buffer_index = -1;
496
497         gamma = dc_create_gamma();
498         if (!gamma)
499                 return -ENOMEM;
500
501         gamma->num_entries = lut_size;
502         __drm_lut_to_dc_gamma(lut, gamma, false);
503
504         if (func->tf == TRANSFER_FUNCTION_LINEAR) {
505                 /*
506                  * Color module doesn't like calculating regamma params
507                  * on top of a linear input. But degamma params can be used
508                  * instead to simulate this.
509                  */
510                 gamma->type = GAMMA_CUSTOM;
511                 res = mod_color_calculate_degamma_params(NULL, func,
512                                                         gamma, true);
513         } else {
514                 /*
515                  * Assume sRGB. The actual mapping will depend on whether the
516                  * input was legacy or not.
517                  */
518                 gamma->type = GAMMA_CS_TFM_1D;
519                 res = mod_color_calculate_regamma_params(func, gamma, false,
520                                                          has_rom, NULL, &cal_buffer);
521         }
522
523         dc_gamma_release(&gamma);
524
525         return res ? 0 : -ENOMEM;
526 }
527
528 /**
529  * __set_input_tf - calculates the input transfer function based on expected
530  * input space.
531  * @func: transfer function
532  * @lut: lookup table that defines the color space
533  * @lut_size: size of respective lut.
534  *
535  * Returns:
536  * 0 in case of success. -ENOMEM if fails.
537  */
538 static int __set_input_tf(struct dc_transfer_func *func,
539                           const struct drm_color_lut *lut, uint32_t lut_size)
540 {
541         struct dc_gamma *gamma = NULL;
542         bool res;
543
544         gamma = dc_create_gamma();
545         if (!gamma)
546                 return -ENOMEM;
547
548         gamma->type = GAMMA_CUSTOM;
549         gamma->num_entries = lut_size;
550
551         __drm_lut_to_dc_gamma(lut, gamma, false);
552
553         res = mod_color_calculate_degamma_params(NULL, func, gamma, true);
554         dc_gamma_release(&gamma);
555
556         return res ? 0 : -ENOMEM;
557 }
558
559 /**
560  * amdgpu_dm_verify_lut_sizes - verifies if DRM luts match the hw supported sizes
561  * @crtc_state: the DRM CRTC state
562  *
563  * Verifies that the Degamma and Gamma LUTs attached to the &crtc_state
564  * are of the expected size.
565  *
566  * Returns:
567  * 0 on success. -EINVAL if any lut sizes are invalid.
568  */
569 int amdgpu_dm_verify_lut_sizes(const struct drm_crtc_state *crtc_state)
570 {
571         const struct drm_color_lut *lut = NULL;
572         uint32_t size = 0;
573
574         lut = __extract_blob_lut(crtc_state->degamma_lut, &size);
575         if (lut && size != MAX_COLOR_LUT_ENTRIES) {
576                 DRM_DEBUG_DRIVER(
577                         "Invalid Degamma LUT size. Should be %u but got %u.\n",
578                         MAX_COLOR_LUT_ENTRIES, size);
579                 return -EINVAL;
580         }
581
582         lut = __extract_blob_lut(crtc_state->gamma_lut, &size);
583         if (lut && size != MAX_COLOR_LUT_ENTRIES &&
584             size != MAX_COLOR_LEGACY_LUT_ENTRIES) {
585                 DRM_DEBUG_DRIVER(
586                         "Invalid Gamma LUT size. Should be %u (or %u for legacy) but got %u.\n",
587                         MAX_COLOR_LUT_ENTRIES, MAX_COLOR_LEGACY_LUT_ENTRIES,
588                         size);
589                 return -EINVAL;
590         }
591
592         return 0;
593 }
594
595 /**
596  * amdgpu_dm_update_crtc_color_mgmt: Maps DRM color management to DC stream.
597  * @crtc: amdgpu_dm crtc state
598  *
599  * With no plane level color management properties we're free to use any
600  * of the HW blocks as long as the CRTC CTM always comes before the
601  * CRTC RGM and after the CRTC DGM.
602  *
603  * - The CRTC RGM block will be placed in the RGM LUT block if it is non-linear.
604  * - The CRTC DGM block will be placed in the DGM LUT block if it is non-linear.
605  * - The CRTC CTM will be placed in the gamut remap block if it is non-linear.
606  *
607  * The RGM block is typically more fully featured and accurate across
608  * all ASICs - DCE can't support a custom non-linear CRTC DGM.
609  *
610  * For supporting both plane level color management and CRTC level color
611  * management at once we have to either restrict the usage of CRTC properties
612  * or blend adjustments together.
613  *
614  * Returns:
615  * 0 on success. Error code if setup fails.
616  */
617 int amdgpu_dm_update_crtc_color_mgmt(struct dm_crtc_state *crtc)
618 {
619         struct dc_stream_state *stream = crtc->stream;
620         struct amdgpu_device *adev = drm_to_adev(crtc->base.state->dev);
621         bool has_rom = adev->asic_type <= CHIP_RAVEN;
622         struct drm_color_ctm *ctm = NULL;
623         const struct drm_color_lut *degamma_lut, *regamma_lut;
624         uint32_t degamma_size, regamma_size;
625         bool has_regamma, has_degamma;
626         bool is_legacy;
627         int r;
628
629         r = amdgpu_dm_verify_lut_sizes(&crtc->base);
630         if (r)
631                 return r;
632
633         degamma_lut = __extract_blob_lut(crtc->base.degamma_lut, &degamma_size);
634         regamma_lut = __extract_blob_lut(crtc->base.gamma_lut, &regamma_size);
635
636         has_degamma =
637                 degamma_lut && !__is_lut_linear(degamma_lut, degamma_size);
638
639         has_regamma =
640                 regamma_lut && !__is_lut_linear(regamma_lut, regamma_size);
641
642         is_legacy = regamma_size == MAX_COLOR_LEGACY_LUT_ENTRIES;
643
644         /* Reset all adjustments. */
645         crtc->cm_has_degamma = false;
646         crtc->cm_is_degamma_srgb = false;
647
648         /* Setup regamma and degamma. */
649         if (is_legacy) {
650                 /*
651                  * Legacy regamma forces us to use the sRGB RGM as a base.
652                  * This also means we can't use linear DGM since DGM needs
653                  * to use sRGB as a base as well, resulting in incorrect CRTC
654                  * DGM and CRTC CTM.
655                  *
656                  * TODO: Just map this to the standard regamma interface
657                  * instead since this isn't really right. One of the cases
658                  * where this setup currently fails is trying to do an
659                  * inverse color ramp in legacy userspace.
660                  */
661                 crtc->cm_is_degamma_srgb = true;
662                 stream->out_transfer_func->type = TF_TYPE_DISTRIBUTED_POINTS;
663                 stream->out_transfer_func->tf = TRANSFER_FUNCTION_SRGB;
664
665                 r = __set_legacy_tf(stream->out_transfer_func, regamma_lut,
666                                     regamma_size, has_rom);
667                 if (r)
668                         return r;
669         } else if (has_regamma) {
670                 /* If atomic regamma, CRTC RGM goes into RGM LUT. */
671                 stream->out_transfer_func->type = TF_TYPE_DISTRIBUTED_POINTS;
672                 stream->out_transfer_func->tf = TRANSFER_FUNCTION_LINEAR;
673
674                 r = __set_output_tf(stream->out_transfer_func, regamma_lut,
675                                     regamma_size, has_rom);
676                 if (r)
677                         return r;
678         } else {
679                 /*
680                  * No CRTC RGM means we can just put the block into bypass
681                  * since we don't have any plane level adjustments using it.
682                  */
683                 stream->out_transfer_func->type = TF_TYPE_BYPASS;
684                 stream->out_transfer_func->tf = TRANSFER_FUNCTION_LINEAR;
685         }
686
687         /*
688          * CRTC DGM goes into DGM LUT. It would be nice to place it
689          * into the RGM since it's a more featured block but we'd
690          * have to place the CTM in the OCSC in that case.
691          */
692         crtc->cm_has_degamma = has_degamma;
693
694         /* Setup CRTC CTM. */
695         if (crtc->base.ctm) {
696                 ctm = (struct drm_color_ctm *)crtc->base.ctm->data;
697
698                 /*
699                  * Gamut remapping must be used for gamma correction
700                  * since it comes before the regamma correction.
701                  *
702                  * OCSC could be used for gamma correction, but we'd need to
703                  * blend the adjustments together with the required output
704                  * conversion matrix - so just use the gamut remap block
705                  * for now.
706                  */
707                 __drm_ctm_to_dc_matrix(ctm, stream->gamut_remap_matrix.matrix);
708
709                 stream->gamut_remap_matrix.enable_remap = true;
710                 stream->csc_color_matrix.enable_adjustment = false;
711         } else {
712                 /* Bypass CTM. */
713                 stream->gamut_remap_matrix.enable_remap = false;
714                 stream->csc_color_matrix.enable_adjustment = false;
715         }
716
717         return 0;
718 }
719
720 /**
721  * amdgpu_dm_update_plane_color_mgmt: Maps DRM color management to DC plane.
722  * @crtc: amdgpu_dm crtc state
723  * @dc_plane_state: target DC surface
724  *
725  * Update the underlying dc_stream_state's input transfer function (ITF) in
726  * preparation for hardware commit. The transfer function used depends on
727  * the preparation done on the stream for color management.
728  *
729  * Returns:
730  * 0 on success. -ENOMEM if mem allocation fails.
731  */
732 int amdgpu_dm_update_plane_color_mgmt(struct dm_crtc_state *crtc,
733                                       struct dc_plane_state *dc_plane_state)
734 {
735         const struct drm_color_lut *degamma_lut;
736         enum dc_transfer_func_predefined tf = TRANSFER_FUNCTION_SRGB;
737         uint32_t degamma_size;
738         int r;
739
740         /* Get the correct base transfer function for implicit degamma. */
741         switch (dc_plane_state->format) {
742         case SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr:
743         case SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb:
744                 /* DC doesn't have a transfer function for BT601 specifically. */
745                 tf = TRANSFER_FUNCTION_BT709;
746                 break;
747         default:
748                 break;
749         }
750
751         if (crtc->cm_has_degamma) {
752                 degamma_lut = __extract_blob_lut(crtc->base.degamma_lut,
753                                                  &degamma_size);
754                 ASSERT(degamma_size == MAX_COLOR_LUT_ENTRIES);
755
756                 dc_plane_state->in_transfer_func->type =
757                         TF_TYPE_DISTRIBUTED_POINTS;
758
759                 /*
760                  * This case isn't fully correct, but also fairly
761                  * uncommon. This is userspace trying to use a
762                  * legacy gamma LUT + atomic degamma LUT
763                  * at the same time.
764                  *
765                  * Legacy gamma requires the input to be in linear
766                  * space, so that means we need to apply an sRGB
767                  * degamma. But color module also doesn't support
768                  * a user ramp in this case so the degamma will
769                  * be lost.
770                  *
771                  * Even if we did support it, it's still not right:
772                  *
773                  * Input -> CRTC DGM -> sRGB DGM -> CRTC CTM ->
774                  * sRGB RGM -> CRTC RGM -> Output
775                  *
776                  * The CSC will be done in the wrong space since
777                  * we're applying an sRGB DGM on top of the CRTC
778                  * DGM.
779                  *
780                  * TODO: Don't use the legacy gamma interface and just
781                  * map these to the atomic one instead.
782                  */
783                 if (crtc->cm_is_degamma_srgb)
784                         dc_plane_state->in_transfer_func->tf = tf;
785                 else
786                         dc_plane_state->in_transfer_func->tf =
787                                 TRANSFER_FUNCTION_LINEAR;
788
789                 r = __set_input_tf(dc_plane_state->in_transfer_func,
790                                    degamma_lut, degamma_size);
791                 if (r)
792                         return r;
793         } else if (crtc->cm_is_degamma_srgb) {
794                 /*
795                  * For legacy gamma support we need the regamma input
796                  * in linear space. Assume that the input is sRGB.
797                  */
798                 dc_plane_state->in_transfer_func->type = TF_TYPE_PREDEFINED;
799                 dc_plane_state->in_transfer_func->tf = tf;
800
801                 if (tf != TRANSFER_FUNCTION_SRGB &&
802                     !mod_color_calculate_degamma_params(NULL,
803                             dc_plane_state->in_transfer_func, NULL, false))
804                         return -ENOMEM;
805         } else {
806                 /* ...Otherwise we can just bypass the DGM block. */
807                 dc_plane_state->in_transfer_func->type = TF_TYPE_BYPASS;
808                 dc_plane_state->in_transfer_func->tf = TRANSFER_FUNCTION_LINEAR;
809         }
810
811         return 0;
812 }