xref: /linux/drivers/gpu/drm/amd/display/dc/core/dc_resource.c (revision de848da12f752170c2ebe114804a985314fd5a6a)
1 /*
2  * Copyright 2012-15 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 
26 #include "dm_services.h"
27 
28 #include "resource.h"
29 #include "include/irq_service_interface.h"
30 #include "link_encoder.h"
31 #include "stream_encoder.h"
32 #include "opp.h"
33 #include "timing_generator.h"
34 #include "transform.h"
35 #include "dccg.h"
36 #include "dchubbub.h"
37 #include "dpp.h"
38 #include "core_types.h"
39 #include "set_mode_types.h"
40 #include "virtual/virtual_stream_encoder.h"
41 #include "dpcd_defs.h"
42 #include "link_enc_cfg.h"
43 #include "link.h"
44 #include "clk_mgr.h"
45 #include "dc_state_priv.h"
46 #include "dc_stream_priv.h"
47 
48 #include "virtual/virtual_link_hwss.h"
49 #include "link/hwss/link_hwss_dio.h"
50 #include "link/hwss/link_hwss_dpia.h"
51 #include "link/hwss/link_hwss_hpo_dp.h"
52 #include "link/hwss/link_hwss_dio_fixed_vs_pe_retimer.h"
53 #include "link/hwss/link_hwss_hpo_fixed_vs_pe_retimer_dp.h"
54 
55 #if defined(CONFIG_DRM_AMD_DC_SI)
56 #include "dce60/dce60_resource.h"
57 #endif
58 #include "dce80/dce80_resource.h"
59 #include "dce100/dce100_resource.h"
60 #include "dce110/dce110_resource.h"
61 #include "dce112/dce112_resource.h"
62 #include "dce120/dce120_resource.h"
63 #include "dcn10/dcn10_resource.h"
64 #include "dcn20/dcn20_resource.h"
65 #include "dcn21/dcn21_resource.h"
66 #include "dcn201/dcn201_resource.h"
67 #include "dcn30/dcn30_resource.h"
68 #include "dcn301/dcn301_resource.h"
69 #include "dcn302/dcn302_resource.h"
70 #include "dcn303/dcn303_resource.h"
71 #include "dcn31/dcn31_resource.h"
72 #include "dcn314/dcn314_resource.h"
73 #include "dcn315/dcn315_resource.h"
74 #include "dcn316/dcn316_resource.h"
75 #include "dcn32/dcn32_resource.h"
76 #include "dcn321/dcn321_resource.h"
77 #include "dcn35/dcn35_resource.h"
78 #include "dcn351/dcn351_resource.h"
79 #include "dcn401/dcn401_resource.h"
80 #if defined(CONFIG_DRM_AMD_DC_FP)
81 #include "dc_spl_translate.h"
82 #endif
83 
84 #define VISUAL_CONFIRM_BASE_DEFAULT 3
85 #define VISUAL_CONFIRM_BASE_MIN 1
86 #define VISUAL_CONFIRM_BASE_MAX 10
87 /* we choose 240 because it is a common denominator of common v addressable
88  * such as 2160, 1440, 1200, 960. So we take 1/240 portion of v addressable as
89  * the visual confirm dpp offset height. So visual confirm height can stay
90  * relatively the same independent from timing used.
91  */
92 #define VISUAL_CONFIRM_DPP_OFFSET_DENO 240
93 
94 #define DC_LOGGER \
95 	dc->ctx->logger
96 #define DC_LOGGER_INIT(logger)
97 
98 #include "dml2/dml2_wrapper.h"
99 
100 #define UNABLE_TO_SPLIT -1
101 
102 enum dce_version resource_parse_asic_id(struct hw_asic_id asic_id)
103 {
104 	enum dce_version dc_version = DCE_VERSION_UNKNOWN;
105 
106 	switch (asic_id.chip_family) {
107 
108 #if defined(CONFIG_DRM_AMD_DC_SI)
109 	case FAMILY_SI:
110 		if (ASIC_REV_IS_TAHITI_P(asic_id.hw_internal_rev) ||
111 		    ASIC_REV_IS_PITCAIRN_PM(asic_id.hw_internal_rev) ||
112 		    ASIC_REV_IS_CAPEVERDE_M(asic_id.hw_internal_rev))
113 			dc_version = DCE_VERSION_6_0;
114 		else if (ASIC_REV_IS_OLAND_M(asic_id.hw_internal_rev))
115 			dc_version = DCE_VERSION_6_4;
116 		else
117 			dc_version = DCE_VERSION_6_1;
118 		break;
119 #endif
120 	case FAMILY_CI:
121 		dc_version = DCE_VERSION_8_0;
122 		break;
123 	case FAMILY_KV:
124 		if (ASIC_REV_IS_KALINDI(asic_id.hw_internal_rev) ||
125 		    ASIC_REV_IS_BHAVANI(asic_id.hw_internal_rev) ||
126 		    ASIC_REV_IS_GODAVARI(asic_id.hw_internal_rev))
127 			dc_version = DCE_VERSION_8_3;
128 		else
129 			dc_version = DCE_VERSION_8_1;
130 		break;
131 	case FAMILY_CZ:
132 		dc_version = DCE_VERSION_11_0;
133 		break;
134 
135 	case FAMILY_VI:
136 		if (ASIC_REV_IS_TONGA_P(asic_id.hw_internal_rev) ||
137 				ASIC_REV_IS_FIJI_P(asic_id.hw_internal_rev)) {
138 			dc_version = DCE_VERSION_10_0;
139 			break;
140 		}
141 		if (ASIC_REV_IS_POLARIS10_P(asic_id.hw_internal_rev) ||
142 				ASIC_REV_IS_POLARIS11_M(asic_id.hw_internal_rev) ||
143 				ASIC_REV_IS_POLARIS12_V(asic_id.hw_internal_rev)) {
144 			dc_version = DCE_VERSION_11_2;
145 		}
146 		if (ASIC_REV_IS_VEGAM(asic_id.hw_internal_rev))
147 			dc_version = DCE_VERSION_11_22;
148 		break;
149 	case FAMILY_AI:
150 		if (ASICREV_IS_VEGA20_P(asic_id.hw_internal_rev))
151 			dc_version = DCE_VERSION_12_1;
152 		else
153 			dc_version = DCE_VERSION_12_0;
154 		break;
155 	case FAMILY_RV:
156 		dc_version = DCN_VERSION_1_0;
157 		if (ASICREV_IS_RAVEN2(asic_id.hw_internal_rev))
158 			dc_version = DCN_VERSION_1_01;
159 		if (ASICREV_IS_RENOIR(asic_id.hw_internal_rev))
160 			dc_version = DCN_VERSION_2_1;
161 		if (ASICREV_IS_GREEN_SARDINE(asic_id.hw_internal_rev))
162 			dc_version = DCN_VERSION_2_1;
163 		break;
164 
165 	case FAMILY_NV:
166 		dc_version = DCN_VERSION_2_0;
167 		if (asic_id.chip_id == DEVICE_ID_NV_13FE || asic_id.chip_id == DEVICE_ID_NV_143F) {
168 			dc_version = DCN_VERSION_2_01;
169 			break;
170 		}
171 		if (ASICREV_IS_SIENNA_CICHLID_P(asic_id.hw_internal_rev))
172 			dc_version = DCN_VERSION_3_0;
173 		if (ASICREV_IS_DIMGREY_CAVEFISH_P(asic_id.hw_internal_rev))
174 			dc_version = DCN_VERSION_3_02;
175 		if (ASICREV_IS_BEIGE_GOBY_P(asic_id.hw_internal_rev))
176 			dc_version = DCN_VERSION_3_03;
177 		break;
178 
179 	case FAMILY_VGH:
180 		dc_version = DCN_VERSION_3_01;
181 		break;
182 
183 	case FAMILY_YELLOW_CARP:
184 		if (ASICREV_IS_YELLOW_CARP(asic_id.hw_internal_rev))
185 			dc_version = DCN_VERSION_3_1;
186 		break;
187 	case AMDGPU_FAMILY_GC_10_3_6:
188 		if (ASICREV_IS_GC_10_3_6(asic_id.hw_internal_rev))
189 			dc_version = DCN_VERSION_3_15;
190 		break;
191 	case AMDGPU_FAMILY_GC_10_3_7:
192 		if (ASICREV_IS_GC_10_3_7(asic_id.hw_internal_rev))
193 			dc_version = DCN_VERSION_3_16;
194 		break;
195 	case AMDGPU_FAMILY_GC_11_0_0:
196 		dc_version = DCN_VERSION_3_2;
197 		if (ASICREV_IS_GC_11_0_2(asic_id.hw_internal_rev))
198 			dc_version = DCN_VERSION_3_21;
199 		break;
200 	case AMDGPU_FAMILY_GC_11_0_1:
201 		dc_version = DCN_VERSION_3_14;
202 		break;
203 	case AMDGPU_FAMILY_GC_11_5_0:
204 		dc_version = DCN_VERSION_3_5;
205 		if (ASICREV_IS_GC_11_0_4(asic_id.hw_internal_rev))
206 			dc_version = DCN_VERSION_3_51;
207 		break;
208 	case AMDGPU_FAMILY_GC_12_0_0:
209 		if (ASICREV_IS_GC_12_0_1_A0(asic_id.hw_internal_rev) ||
210 			ASICREV_IS_GC_12_0_0_A0(asic_id.hw_internal_rev))
211 			dc_version = DCN_VERSION_4_01;
212 		break;
213 	default:
214 		dc_version = DCE_VERSION_UNKNOWN;
215 		break;
216 	}
217 	return dc_version;
218 }
219 
220 struct resource_pool *dc_create_resource_pool(struct dc  *dc,
221 					      const struct dc_init_data *init_data,
222 					      enum dce_version dc_version)
223 {
224 	struct resource_pool *res_pool = NULL;
225 
226 	switch (dc_version) {
227 #if defined(CONFIG_DRM_AMD_DC_SI)
228 	case DCE_VERSION_6_0:
229 		res_pool = dce60_create_resource_pool(
230 			init_data->num_virtual_links, dc);
231 		break;
232 	case DCE_VERSION_6_1:
233 		res_pool = dce61_create_resource_pool(
234 			init_data->num_virtual_links, dc);
235 		break;
236 	case DCE_VERSION_6_4:
237 		res_pool = dce64_create_resource_pool(
238 			init_data->num_virtual_links, dc);
239 		break;
240 #endif
241 	case DCE_VERSION_8_0:
242 		res_pool = dce80_create_resource_pool(
243 				init_data->num_virtual_links, dc);
244 		break;
245 	case DCE_VERSION_8_1:
246 		res_pool = dce81_create_resource_pool(
247 				init_data->num_virtual_links, dc);
248 		break;
249 	case DCE_VERSION_8_3:
250 		res_pool = dce83_create_resource_pool(
251 				init_data->num_virtual_links, dc);
252 		break;
253 	case DCE_VERSION_10_0:
254 		res_pool = dce100_create_resource_pool(
255 				init_data->num_virtual_links, dc);
256 		break;
257 	case DCE_VERSION_11_0:
258 		res_pool = dce110_create_resource_pool(
259 				init_data->num_virtual_links, dc,
260 				init_data->asic_id);
261 		break;
262 	case DCE_VERSION_11_2:
263 	case DCE_VERSION_11_22:
264 		res_pool = dce112_create_resource_pool(
265 				init_data->num_virtual_links, dc);
266 		break;
267 	case DCE_VERSION_12_0:
268 	case DCE_VERSION_12_1:
269 		res_pool = dce120_create_resource_pool(
270 				init_data->num_virtual_links, dc);
271 		break;
272 
273 #if defined(CONFIG_DRM_AMD_DC_FP)
274 	case DCN_VERSION_1_0:
275 	case DCN_VERSION_1_01:
276 		res_pool = dcn10_create_resource_pool(init_data, dc);
277 		break;
278 	case DCN_VERSION_2_0:
279 		res_pool = dcn20_create_resource_pool(init_data, dc);
280 		break;
281 	case DCN_VERSION_2_1:
282 		res_pool = dcn21_create_resource_pool(init_data, dc);
283 		break;
284 	case DCN_VERSION_2_01:
285 		res_pool = dcn201_create_resource_pool(init_data, dc);
286 		break;
287 	case DCN_VERSION_3_0:
288 		res_pool = dcn30_create_resource_pool(init_data, dc);
289 		break;
290 	case DCN_VERSION_3_01:
291 		res_pool = dcn301_create_resource_pool(init_data, dc);
292 		break;
293 	case DCN_VERSION_3_02:
294 		res_pool = dcn302_create_resource_pool(init_data, dc);
295 		break;
296 	case DCN_VERSION_3_03:
297 		res_pool = dcn303_create_resource_pool(init_data, dc);
298 		break;
299 	case DCN_VERSION_3_1:
300 		res_pool = dcn31_create_resource_pool(init_data, dc);
301 		break;
302 	case DCN_VERSION_3_14:
303 		res_pool = dcn314_create_resource_pool(init_data, dc);
304 		break;
305 	case DCN_VERSION_3_15:
306 		res_pool = dcn315_create_resource_pool(init_data, dc);
307 		break;
308 	case DCN_VERSION_3_16:
309 		res_pool = dcn316_create_resource_pool(init_data, dc);
310 		break;
311 	case DCN_VERSION_3_2:
312 		res_pool = dcn32_create_resource_pool(init_data, dc);
313 		break;
314 	case DCN_VERSION_3_21:
315 		res_pool = dcn321_create_resource_pool(init_data, dc);
316 		break;
317 	case DCN_VERSION_3_5:
318 		res_pool = dcn35_create_resource_pool(init_data, dc);
319 		break;
320 	case DCN_VERSION_3_51:
321 		res_pool = dcn351_create_resource_pool(init_data, dc);
322 		break;
323 	case DCN_VERSION_4_01:
324 		res_pool = dcn401_create_resource_pool(init_data, dc);
325 		break;
326 #endif /* CONFIG_DRM_AMD_DC_FP */
327 	default:
328 		break;
329 	}
330 
331 	if (res_pool != NULL) {
332 		if (dc->ctx->dc_bios->fw_info_valid) {
333 			res_pool->ref_clocks.xtalin_clock_inKhz =
334 				dc->ctx->dc_bios->fw_info.pll_info.crystal_frequency;
335 			/* initialize with firmware data first, no all
336 			 * ASIC have DCCG SW component. FPGA or
337 			 * simulation need initialization of
338 			 * dccg_ref_clock_inKhz, dchub_ref_clock_inKhz
339 			 * with xtalin_clock_inKhz
340 			 */
341 			res_pool->ref_clocks.dccg_ref_clock_inKhz =
342 				res_pool->ref_clocks.xtalin_clock_inKhz;
343 			res_pool->ref_clocks.dchub_ref_clock_inKhz =
344 				res_pool->ref_clocks.xtalin_clock_inKhz;
345 		} else
346 			ASSERT_CRITICAL(false);
347 	}
348 
349 	return res_pool;
350 }
351 
352 void dc_destroy_resource_pool(struct dc *dc)
353 {
354 	if (dc) {
355 		if (dc->res_pool)
356 			dc->res_pool->funcs->destroy(&dc->res_pool);
357 
358 		kfree(dc->hwseq);
359 	}
360 }
361 
362 static void update_num_audio(
363 	const struct resource_straps *straps,
364 	unsigned int *num_audio,
365 	struct audio_support *aud_support)
366 {
367 	aud_support->dp_audio = true;
368 	aud_support->hdmi_audio_native = false;
369 	aud_support->hdmi_audio_on_dongle = false;
370 
371 	if (straps->hdmi_disable == 0) {
372 		if (straps->dc_pinstraps_audio & 0x2) {
373 			aud_support->hdmi_audio_on_dongle = true;
374 			aud_support->hdmi_audio_native = true;
375 		}
376 	}
377 
378 	switch (straps->audio_stream_number) {
379 	case 0: /* multi streams supported */
380 		break;
381 	case 1: /* multi streams not supported */
382 		*num_audio = 1;
383 		break;
384 	default:
385 		DC_ERR("DC: unexpected audio fuse!\n");
386 	}
387 }
388 
389 bool resource_construct(
390 	unsigned int num_virtual_links,
391 	struct dc  *dc,
392 	struct resource_pool *pool,
393 	const struct resource_create_funcs *create_funcs)
394 {
395 	struct dc_context *ctx = dc->ctx;
396 	const struct resource_caps *caps = pool->res_cap;
397 	int i;
398 	unsigned int num_audio = caps->num_audio;
399 	struct resource_straps straps = {0};
400 
401 	if (create_funcs->read_dce_straps)
402 		create_funcs->read_dce_straps(dc->ctx, &straps);
403 
404 	pool->audio_count = 0;
405 	if (create_funcs->create_audio) {
406 		/* find the total number of streams available via the
407 		 * AZALIA_F0_CODEC_PIN_CONTROL_RESPONSE_CONFIGURATION_DEFAULT
408 		 * registers (one for each pin) starting from pin 1
409 		 * up to the max number of audio pins.
410 		 * We stop on the first pin where
411 		 * PORT_CONNECTIVITY == 1 (as instructed by HW team).
412 		 */
413 		update_num_audio(&straps, &num_audio, &pool->audio_support);
414 		for (i = 0; i < caps->num_audio; i++) {
415 			struct audio *aud = create_funcs->create_audio(ctx, i);
416 
417 			if (aud == NULL) {
418 				DC_ERR("DC: failed to create audio!\n");
419 				return false;
420 			}
421 			if (!aud->funcs->endpoint_valid(aud)) {
422 				aud->funcs->destroy(&aud);
423 				break;
424 			}
425 			pool->audios[i] = aud;
426 			pool->audio_count++;
427 		}
428 	}
429 
430 	pool->stream_enc_count = 0;
431 	if (create_funcs->create_stream_encoder) {
432 		for (i = 0; i < caps->num_stream_encoder; i++) {
433 			pool->stream_enc[i] = create_funcs->create_stream_encoder(i, ctx);
434 			if (pool->stream_enc[i] == NULL)
435 				DC_ERR("DC: failed to create stream_encoder!\n");
436 			pool->stream_enc_count++;
437 		}
438 	}
439 
440 	pool->hpo_dp_stream_enc_count = 0;
441 	if (create_funcs->create_hpo_dp_stream_encoder) {
442 		for (i = 0; i < caps->num_hpo_dp_stream_encoder; i++) {
443 			pool->hpo_dp_stream_enc[i] = create_funcs->create_hpo_dp_stream_encoder(i+ENGINE_ID_HPO_DP_0, ctx);
444 			if (pool->hpo_dp_stream_enc[i] == NULL)
445 				DC_ERR("DC: failed to create HPO DP stream encoder!\n");
446 			pool->hpo_dp_stream_enc_count++;
447 
448 		}
449 	}
450 
451 	pool->hpo_dp_link_enc_count = 0;
452 	if (create_funcs->create_hpo_dp_link_encoder) {
453 		for (i = 0; i < caps->num_hpo_dp_link_encoder; i++) {
454 			pool->hpo_dp_link_enc[i] = create_funcs->create_hpo_dp_link_encoder(i, ctx);
455 			if (pool->hpo_dp_link_enc[i] == NULL)
456 				DC_ERR("DC: failed to create HPO DP link encoder!\n");
457 			pool->hpo_dp_link_enc_count++;
458 		}
459 	}
460 
461 	for (i = 0; i < caps->num_mpc_3dlut; i++) {
462 		pool->mpc_lut[i] = dc_create_3dlut_func();
463 		if (pool->mpc_lut[i] == NULL)
464 			DC_ERR("DC: failed to create MPC 3dlut!\n");
465 		pool->mpc_shaper[i] = dc_create_transfer_func();
466 		if (pool->mpc_shaper[i] == NULL)
467 			DC_ERR("DC: failed to create MPC shaper!\n");
468 	}
469 
470 	dc->caps.dynamic_audio = false;
471 	if (pool->audio_count < pool->stream_enc_count) {
472 		dc->caps.dynamic_audio = true;
473 	}
474 	for (i = 0; i < num_virtual_links; i++) {
475 		pool->stream_enc[pool->stream_enc_count] =
476 			virtual_stream_encoder_create(
477 					ctx, ctx->dc_bios);
478 		if (pool->stream_enc[pool->stream_enc_count] == NULL) {
479 			DC_ERR("DC: failed to create stream_encoder!\n");
480 			return false;
481 		}
482 		pool->stream_enc_count++;
483 	}
484 
485 	dc->hwseq = create_funcs->create_hwseq(ctx);
486 
487 	return true;
488 }
489 static int find_matching_clock_source(
490 		const struct resource_pool *pool,
491 		struct clock_source *clock_source)
492 {
493 
494 	int i;
495 
496 	for (i = 0; i < pool->clk_src_count; i++) {
497 		if (pool->clock_sources[i] == clock_source)
498 			return i;
499 	}
500 	return -1;
501 }
502 
503 void resource_unreference_clock_source(
504 		struct resource_context *res_ctx,
505 		const struct resource_pool *pool,
506 		struct clock_source *clock_source)
507 {
508 	int i = find_matching_clock_source(pool, clock_source);
509 
510 	if (i > -1)
511 		res_ctx->clock_source_ref_count[i]--;
512 
513 	if (pool->dp_clock_source == clock_source)
514 		res_ctx->dp_clock_source_ref_count--;
515 }
516 
517 void resource_reference_clock_source(
518 		struct resource_context *res_ctx,
519 		const struct resource_pool *pool,
520 		struct clock_source *clock_source)
521 {
522 	int i = find_matching_clock_source(pool, clock_source);
523 
524 	if (i > -1)
525 		res_ctx->clock_source_ref_count[i]++;
526 
527 	if (pool->dp_clock_source == clock_source)
528 		res_ctx->dp_clock_source_ref_count++;
529 }
530 
531 int resource_get_clock_source_reference(
532 		struct resource_context *res_ctx,
533 		const struct resource_pool *pool,
534 		struct clock_source *clock_source)
535 {
536 	int i = find_matching_clock_source(pool, clock_source);
537 
538 	if (i > -1)
539 		return res_ctx->clock_source_ref_count[i];
540 
541 	if (pool->dp_clock_source == clock_source)
542 		return res_ctx->dp_clock_source_ref_count;
543 
544 	return -1;
545 }
546 
547 bool resource_are_vblanks_synchronizable(
548 	struct dc_stream_state *stream1,
549 	struct dc_stream_state *stream2)
550 {
551 	uint32_t base60_refresh_rates[] = {10, 20, 5};
552 	uint8_t i;
553 	uint8_t rr_count = ARRAY_SIZE(base60_refresh_rates);
554 	uint64_t frame_time_diff;
555 
556 	if (stream1->ctx->dc->config.vblank_alignment_dto_params &&
557 		stream1->ctx->dc->config.vblank_alignment_max_frame_time_diff > 0 &&
558 		dc_is_dp_signal(stream1->signal) &&
559 		dc_is_dp_signal(stream2->signal) &&
560 		false == stream1->has_non_synchronizable_pclk &&
561 		false == stream2->has_non_synchronizable_pclk &&
562 		stream1->timing.flags.VBLANK_SYNCHRONIZABLE &&
563 		stream2->timing.flags.VBLANK_SYNCHRONIZABLE) {
564 		/* disable refresh rates higher than 60Hz for now */
565 		if (stream1->timing.pix_clk_100hz*100/stream1->timing.h_total/
566 				stream1->timing.v_total > 60)
567 			return false;
568 		if (stream2->timing.pix_clk_100hz*100/stream2->timing.h_total/
569 				stream2->timing.v_total > 60)
570 			return false;
571 		frame_time_diff = (uint64_t)10000 *
572 			stream1->timing.h_total *
573 			stream1->timing.v_total *
574 			stream2->timing.pix_clk_100hz;
575 		frame_time_diff = div_u64(frame_time_diff, stream1->timing.pix_clk_100hz);
576 		frame_time_diff = div_u64(frame_time_diff, stream2->timing.h_total);
577 		frame_time_diff = div_u64(frame_time_diff, stream2->timing.v_total);
578 		for (i = 0; i < rr_count; i++) {
579 			int64_t diff = (int64_t)div_u64(frame_time_diff * base60_refresh_rates[i], 10) - 10000;
580 
581 			if (diff < 0)
582 				diff = -diff;
583 			if (diff < stream1->ctx->dc->config.vblank_alignment_max_frame_time_diff)
584 				return true;
585 		}
586 	}
587 	return false;
588 }
589 
590 bool resource_are_streams_timing_synchronizable(
591 	struct dc_stream_state *stream1,
592 	struct dc_stream_state *stream2)
593 {
594 	if (stream1->timing.h_total != stream2->timing.h_total)
595 		return false;
596 
597 	if (stream1->timing.v_total != stream2->timing.v_total)
598 		return false;
599 
600 	if (stream1->timing.h_addressable
601 				!= stream2->timing.h_addressable)
602 		return false;
603 
604 	if (stream1->timing.v_addressable
605 				!= stream2->timing.v_addressable)
606 		return false;
607 
608 	if (stream1->timing.v_front_porch
609 				!= stream2->timing.v_front_porch)
610 		return false;
611 
612 	if (stream1->timing.pix_clk_100hz
613 				!= stream2->timing.pix_clk_100hz)
614 		return false;
615 
616 	if (stream1->clamping.c_depth != stream2->clamping.c_depth)
617 		return false;
618 
619 	if (stream1->phy_pix_clk != stream2->phy_pix_clk
620 			&& (!dc_is_dp_signal(stream1->signal)
621 			|| !dc_is_dp_signal(stream2->signal)))
622 		return false;
623 
624 	if (stream1->view_format != stream2->view_format)
625 		return false;
626 
627 	if (stream1->ignore_msa_timing_param || stream2->ignore_msa_timing_param)
628 		return false;
629 
630 	return true;
631 }
632 static bool is_dp_and_hdmi_sharable(
633 		struct dc_stream_state *stream1,
634 		struct dc_stream_state *stream2)
635 {
636 	if (stream1->ctx->dc->caps.disable_dp_clk_share)
637 		return false;
638 
639 	if (stream1->clamping.c_depth != COLOR_DEPTH_888 ||
640 		stream2->clamping.c_depth != COLOR_DEPTH_888)
641 		return false;
642 
643 	return true;
644 
645 }
646 
647 static bool is_sharable_clk_src(
648 	const struct pipe_ctx *pipe_with_clk_src,
649 	const struct pipe_ctx *pipe)
650 {
651 	if (pipe_with_clk_src->clock_source == NULL)
652 		return false;
653 
654 	if (pipe_with_clk_src->stream->signal == SIGNAL_TYPE_VIRTUAL)
655 		return false;
656 
657 	if (dc_is_dp_signal(pipe_with_clk_src->stream->signal) ||
658 		(dc_is_dp_signal(pipe->stream->signal) &&
659 		!is_dp_and_hdmi_sharable(pipe_with_clk_src->stream,
660 				     pipe->stream)))
661 		return false;
662 
663 	if (dc_is_hdmi_signal(pipe_with_clk_src->stream->signal)
664 			&& dc_is_dual_link_signal(pipe->stream->signal))
665 		return false;
666 
667 	if (dc_is_hdmi_signal(pipe->stream->signal)
668 			&& dc_is_dual_link_signal(pipe_with_clk_src->stream->signal))
669 		return false;
670 
671 	if (!resource_are_streams_timing_synchronizable(
672 			pipe_with_clk_src->stream, pipe->stream))
673 		return false;
674 
675 	return true;
676 }
677 
678 struct clock_source *resource_find_used_clk_src_for_sharing(
679 					struct resource_context *res_ctx,
680 					struct pipe_ctx *pipe_ctx)
681 {
682 	int i;
683 
684 	for (i = 0; i < MAX_PIPES; i++) {
685 		if (is_sharable_clk_src(&res_ctx->pipe_ctx[i], pipe_ctx))
686 			return res_ctx->pipe_ctx[i].clock_source;
687 	}
688 
689 	return NULL;
690 }
691 
692 static enum pixel_format convert_pixel_format_to_dalsurface(
693 		enum surface_pixel_format surface_pixel_format)
694 {
695 	enum pixel_format dal_pixel_format = PIXEL_FORMAT_UNKNOWN;
696 
697 	switch (surface_pixel_format) {
698 	case SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS:
699 		dal_pixel_format = PIXEL_FORMAT_INDEX8;
700 		break;
701 	case SURFACE_PIXEL_FORMAT_GRPH_ARGB1555:
702 		dal_pixel_format = PIXEL_FORMAT_RGB565;
703 		break;
704 	case SURFACE_PIXEL_FORMAT_GRPH_RGB565:
705 		dal_pixel_format = PIXEL_FORMAT_RGB565;
706 		break;
707 	case SURFACE_PIXEL_FORMAT_GRPH_ARGB8888:
708 		dal_pixel_format = PIXEL_FORMAT_ARGB8888;
709 		break;
710 	case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888:
711 		dal_pixel_format = PIXEL_FORMAT_ARGB8888;
712 		break;
713 	case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010:
714 		dal_pixel_format = PIXEL_FORMAT_ARGB2101010;
715 		break;
716 	case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010:
717 		dal_pixel_format = PIXEL_FORMAT_ARGB2101010;
718 		break;
719 	case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010_XR_BIAS:
720 		dal_pixel_format = PIXEL_FORMAT_ARGB2101010_XRBIAS;
721 		break;
722 	case SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616F:
723 	case SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616F:
724 		dal_pixel_format = PIXEL_FORMAT_FP16;
725 		break;
726 	case SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr:
727 	case SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb:
728 		dal_pixel_format = PIXEL_FORMAT_420BPP8;
729 		break;
730 	case SURFACE_PIXEL_FORMAT_VIDEO_420_10bpc_YCbCr:
731 	case SURFACE_PIXEL_FORMAT_VIDEO_420_10bpc_YCrCb:
732 		dal_pixel_format = PIXEL_FORMAT_420BPP10;
733 		break;
734 	case SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616:
735 	case SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616:
736 	default:
737 		dal_pixel_format = PIXEL_FORMAT_UNKNOWN;
738 		break;
739 	}
740 	return dal_pixel_format;
741 }
742 
743 static inline void get_vp_scan_direction(
744 	enum dc_rotation_angle rotation,
745 	bool horizontal_mirror,
746 	bool *orthogonal_rotation,
747 	bool *flip_vert_scan_dir,
748 	bool *flip_horz_scan_dir)
749 {
750 	*orthogonal_rotation = false;
751 	*flip_vert_scan_dir = false;
752 	*flip_horz_scan_dir = false;
753 	if (rotation == ROTATION_ANGLE_180) {
754 		*flip_vert_scan_dir = true;
755 		*flip_horz_scan_dir = true;
756 	} else if (rotation == ROTATION_ANGLE_90) {
757 		*orthogonal_rotation = true;
758 		*flip_horz_scan_dir = true;
759 	} else if (rotation == ROTATION_ANGLE_270) {
760 		*orthogonal_rotation = true;
761 		*flip_vert_scan_dir = true;
762 	}
763 
764 	if (horizontal_mirror)
765 		*flip_horz_scan_dir = !*flip_horz_scan_dir;
766 }
767 
768 /*
769  * This is a preliminary vp size calculation to allow us to check taps support.
770  * The result is completely overridden afterwards.
771  */
772 static void calculate_viewport_size(struct pipe_ctx *pipe_ctx)
773 {
774 	struct scaler_data *data = &pipe_ctx->plane_res.scl_data;
775 
776 	data->viewport.width = dc_fixpt_ceil(dc_fixpt_mul_int(data->ratios.horz, data->recout.width));
777 	data->viewport.height = dc_fixpt_ceil(dc_fixpt_mul_int(data->ratios.vert, data->recout.height));
778 	data->viewport_c.width = dc_fixpt_ceil(dc_fixpt_mul_int(data->ratios.horz_c, data->recout.width));
779 	data->viewport_c.height = dc_fixpt_ceil(dc_fixpt_mul_int(data->ratios.vert_c, data->recout.height));
780 	if (pipe_ctx->plane_state->rotation == ROTATION_ANGLE_90 ||
781 			pipe_ctx->plane_state->rotation == ROTATION_ANGLE_270) {
782 		swap(data->viewport.width, data->viewport.height);
783 		swap(data->viewport_c.width, data->viewport_c.height);
784 	}
785 }
786 
787 static struct rect intersect_rec(const struct rect *r0, const struct rect *r1)
788 {
789 	struct rect rec;
790 	int r0_x_end = r0->x + r0->width;
791 	int r1_x_end = r1->x + r1->width;
792 	int r0_y_end = r0->y + r0->height;
793 	int r1_y_end = r1->y + r1->height;
794 
795 	rec.x = r0->x > r1->x ? r0->x : r1->x;
796 	rec.width = r0_x_end > r1_x_end ? r1_x_end - rec.x : r0_x_end - rec.x;
797 	rec.y = r0->y > r1->y ? r0->y : r1->y;
798 	rec.height = r0_y_end > r1_y_end ? r1_y_end - rec.y : r0_y_end - rec.y;
799 
800 	/* in case that there is no intersection */
801 	if (rec.width < 0 || rec.height < 0)
802 		memset(&rec, 0, sizeof(rec));
803 
804 	return rec;
805 }
806 
807 static struct rect shift_rec(const struct rect *rec_in, int x, int y)
808 {
809 	struct rect rec_out = *rec_in;
810 
811 	rec_out.x += x;
812 	rec_out.y += y;
813 
814 	return rec_out;
815 }
816 
817 static struct rect calculate_plane_rec_in_timing_active(
818 		struct pipe_ctx *pipe_ctx,
819 		const struct rect *rec_in)
820 {
821 	/*
822 	 * The following diagram shows an example where we map a 1920x1200
823 	 * desktop to a 2560x1440 timing with a plane rect in the middle
824 	 * of the screen. To map a plane rect from Stream Source to Timing
825 	 * Active space, we first multiply stream scaling ratios (i.e 2304/1920
826 	 * horizontal and 1440/1200 vertical) to the plane's x and y, then
827 	 * we add stream destination offsets (i.e 128 horizontal, 0 vertical).
828 	 * This will give us a plane rect's position in Timing Active. However
829 	 * we have to remove the fractional. The rule is that we find left/right
830 	 * and top/bottom positions and round the value to the adjacent integer.
831 	 *
832 	 * Stream Source Space
833 	 * ------------
834 	 *        __________________________________________________
835 	 *       |Stream Source (1920 x 1200) ^                     |
836 	 *       |                            y                     |
837 	 *       |         <------- w --------|>                    |
838 	 *       |          __________________V                     |
839 	 *       |<-- x -->|Plane//////////////| ^                  |
840 	 *       |         |(pre scale)////////| |                  |
841 	 *       |         |///////////////////| |                  |
842 	 *       |         |///////////////////| h                  |
843 	 *       |         |///////////////////| |                  |
844 	 *       |         |///////////////////| |                  |
845 	 *       |         |///////////////////| V                  |
846 	 *       |                                                  |
847 	 *       |                                                  |
848 	 *       |__________________________________________________|
849 	 *
850 	 *
851 	 * Timing Active Space
852 	 * ---------------------------------
853 	 *
854 	 *       Timing Active (2560 x 1440)
855 	 *        __________________________________________________
856 	 *       |*****|  Stteam Destination (2304 x 1440)    |*****|
857 	 *       |*****|                                      |*****|
858 	 *       |<128>|                                      |*****|
859 	 *       |*****|     __________________               |*****|
860 	 *       |*****|    |Plane/////////////|              |*****|
861 	 *       |*****|    |(post scale)//////|              |*****|
862 	 *       |*****|    |//////////////////|              |*****|
863 	 *       |*****|    |//////////////////|              |*****|
864 	 *       |*****|    |//////////////////|              |*****|
865 	 *       |*****|    |//////////////////|              |*****|
866 	 *       |*****|                                      |*****|
867 	 *       |*****|                                      |*****|
868 	 *       |*****|                                      |*****|
869 	 *       |*****|______________________________________|*****|
870 	 *
871 	 * So the resulting formulas are shown below:
872 	 *
873 	 * recout_x = 128 + round(plane_x * 2304 / 1920)
874 	 * recout_w = 128 + round((plane_x + plane_w) * 2304 / 1920) - recout_x
875 	 * recout_y = 0 + round(plane_y * 1440 / 1280)
876 	 * recout_h = 0 + round((plane_y + plane_h) * 1440 / 1200) - recout_y
877 	 *
878 	 * NOTE: fixed point division is not error free. To reduce errors
879 	 * introduced by fixed point division, we divide only after
880 	 * multiplication is complete.
881 	 */
882 	const struct dc_stream_state *stream = pipe_ctx->stream;
883 	struct rect rec_out = {0};
884 	struct fixed31_32 temp;
885 
886 	temp = dc_fixpt_from_fraction(rec_in->x * (long long)stream->dst.width,
887 			stream->src.width);
888 	rec_out.x = stream->dst.x + dc_fixpt_round(temp);
889 
890 	temp = dc_fixpt_from_fraction(
891 			(rec_in->x + rec_in->width) * (long long)stream->dst.width,
892 			stream->src.width);
893 	rec_out.width = stream->dst.x + dc_fixpt_round(temp) - rec_out.x;
894 
895 	temp = dc_fixpt_from_fraction(rec_in->y * (long long)stream->dst.height,
896 			stream->src.height);
897 	rec_out.y = stream->dst.y + dc_fixpt_round(temp);
898 
899 	temp = dc_fixpt_from_fraction(
900 			(rec_in->y + rec_in->height) * (long long)stream->dst.height,
901 			stream->src.height);
902 	rec_out.height = stream->dst.y + dc_fixpt_round(temp) - rec_out.y;
903 
904 	return rec_out;
905 }
906 
907 static struct rect calculate_mpc_slice_in_timing_active(
908 		struct pipe_ctx *pipe_ctx,
909 		struct rect *plane_clip_rec)
910 {
911 	const struct dc_stream_state *stream = pipe_ctx->stream;
912 	int mpc_slice_count = resource_get_mpc_slice_count(pipe_ctx);
913 	int mpc_slice_idx = resource_get_mpc_slice_index(pipe_ctx);
914 	int epimo = mpc_slice_count - plane_clip_rec->width % mpc_slice_count - 1;
915 	struct rect mpc_rec;
916 
917 	mpc_rec.width = plane_clip_rec->width / mpc_slice_count;
918 	mpc_rec.x = plane_clip_rec->x + mpc_rec.width * mpc_slice_idx;
919 	mpc_rec.height = plane_clip_rec->height;
920 	mpc_rec.y = plane_clip_rec->y;
921 	ASSERT(mpc_slice_count == 1 ||
922 			stream->view_format != VIEW_3D_FORMAT_SIDE_BY_SIDE ||
923 			mpc_rec.width % 2 == 0);
924 
925 	if (stream->view_format == VIEW_3D_FORMAT_SIDE_BY_SIDE)
926 		mpc_rec.x -= (mpc_rec.width * mpc_slice_idx);
927 
928 	/* extra pixels in the division remainder need to go to pipes after
929 	 * the extra pixel index minus one(epimo) defined here as:
930 	 */
931 	if (mpc_slice_idx > epimo) {
932 		mpc_rec.x += mpc_slice_idx - epimo - 1;
933 		mpc_rec.width += 1;
934 	}
935 
936 	if (stream->view_format == VIEW_3D_FORMAT_TOP_AND_BOTTOM) {
937 		ASSERT(mpc_rec.height % 2 == 0);
938 		mpc_rec.height /= 2;
939 	}
940 	return mpc_rec;
941 }
942 
943 static void calculate_adjust_recout_for_visual_confirm(struct pipe_ctx *pipe_ctx,
944 	int *base_offset, int *dpp_offset)
945 {
946 	struct dc *dc = pipe_ctx->stream->ctx->dc;
947 	*base_offset = 0;
948 	*dpp_offset = 0;
949 
950 	if (dc->debug.visual_confirm == VISUAL_CONFIRM_DISABLE || !pipe_ctx->plane_res.dpp)
951 		return;
952 
953 	*dpp_offset = pipe_ctx->stream->timing.v_addressable / VISUAL_CONFIRM_DPP_OFFSET_DENO;
954 	*dpp_offset *= pipe_ctx->plane_res.dpp->inst;
955 
956 	if ((dc->debug.visual_confirm_rect_height >= VISUAL_CONFIRM_BASE_MIN) &&
957 			dc->debug.visual_confirm_rect_height <= VISUAL_CONFIRM_BASE_MAX)
958 		*base_offset = dc->debug.visual_confirm_rect_height;
959 	else
960 		*base_offset = VISUAL_CONFIRM_BASE_DEFAULT;
961 }
962 
963 static void adjust_recout_for_visual_confirm(struct rect *recout,
964 		struct pipe_ctx *pipe_ctx)
965 {
966 	int dpp_offset, base_offset;
967 
968 	calculate_adjust_recout_for_visual_confirm(pipe_ctx, &base_offset,
969 		&dpp_offset);
970 	recout->height -= base_offset;
971 	recout->height -= dpp_offset;
972 }
973 
974 /*
975  * The function maps a plane clip from Stream Source Space to ODM Slice Space
976  * and calculates the rec of the overlapping area of MPC slice of the plane
977  * clip, ODM slice associated with the pipe context and stream destination rec.
978  */
979 static void calculate_recout(struct pipe_ctx *pipe_ctx)
980 {
981 	/*
982 	 * A plane clip represents the desired plane size and position in Stream
983 	 * Source Space. Stream Source is the destination where all planes are
984 	 * blended (i.e. positioned, scaled and overlaid). It is a canvas where
985 	 * all planes associated with the current stream are drawn together.
986 	 * After Stream Source is completed, we will further scale and
987 	 * reposition the entire canvas of the stream source to Stream
988 	 * Destination in Timing Active Space. This could be due to display
989 	 * overscan adjustment where we will need to rescale and reposition all
990 	 * the planes so they can fit into a TV with overscan or downscale
991 	 * upscale features such as GPU scaling or VSR.
992 	 *
993 	 * This two step blending is a virtual procedure in software. In
994 	 * hardware there is no such thing as Stream Source. all planes are
995 	 * blended once in Timing Active Space. Software virtualizes a Stream
996 	 * Source space to decouple the math complicity so scaling param
997 	 * calculation focuses on one step at a time.
998 	 *
999 	 * In the following two diagrams, user applied 10% overscan adjustment
1000 	 * so the Stream Source needs to be scaled down a little before mapping
1001 	 * to Timing Active Space. As a result the Plane Clip is also scaled
1002 	 * down by the same ratio, Plane Clip position (i.e. x and y) with
1003 	 * respect to Stream Source is also scaled down. To map it in Timing
1004 	 * Active Space additional x and y offsets from Stream Destination are
1005 	 * added to Plane Clip as well.
1006 	 *
1007 	 * Stream Source Space
1008 	 * ------------
1009 	 *        __________________________________________________
1010 	 *       |Stream Source (3840 x 2160) ^                     |
1011 	 *       |                            y                     |
1012 	 *       |                            |                     |
1013 	 *       |          __________________V                     |
1014 	 *       |<-- x -->|Plane Clip/////////|                    |
1015 	 *       |         |(pre scale)////////|                    |
1016 	 *       |         |///////////////////|                    |
1017 	 *       |         |///////////////////|                    |
1018 	 *       |         |///////////////////|                    |
1019 	 *       |         |///////////////////|                    |
1020 	 *       |         |///////////////////|                    |
1021 	 *       |                                                  |
1022 	 *       |                                                  |
1023 	 *       |__________________________________________________|
1024 	 *
1025 	 *
1026 	 * Timing Active Space (3840 x 2160)
1027 	 * ---------------------------------
1028 	 *
1029 	 *       Timing Active
1030 	 *        __________________________________________________
1031 	 *       | y_____________________________________________   |
1032 	 *       |x |Stream Destination (3456 x 1944)            |  |
1033 	 *       |  |                                            |  |
1034 	 *       |  |        __________________                  |  |
1035 	 *       |  |       |Plane Clip////////|                 |  |
1036 	 *       |  |       |(post scale)//////|                 |  |
1037 	 *       |  |       |//////////////////|                 |  |
1038 	 *       |  |       |//////////////////|                 |  |
1039 	 *       |  |       |//////////////////|                 |  |
1040 	 *       |  |       |//////////////////|                 |  |
1041 	 *       |  |                                            |  |
1042 	 *       |  |                                            |  |
1043 	 *       |  |____________________________________________|  |
1044 	 *       |__________________________________________________|
1045 	 *
1046 	 *
1047 	 * In Timing Active Space a plane clip could be further sliced into
1048 	 * pieces called MPC slices. Each Pipe Context is responsible for
1049 	 * processing only one MPC slice so the plane processing workload can be
1050 	 * distributed to multiple DPP Pipes. MPC slices could be blended
1051 	 * together to a single ODM slice. Each ODM slice is responsible for
1052 	 * processing a portion of Timing Active divided horizontally so the
1053 	 * output pixel processing workload can be distributed to multiple OPP
1054 	 * pipes. All ODM slices are mapped together in ODM block so all MPC
1055 	 * slices belong to different ODM slices could be pieced together to
1056 	 * form a single image in Timing Active. MPC slices must belong to
1057 	 * single ODM slice. If an MPC slice goes across ODM slice boundary, it
1058 	 * needs to be divided into two MPC slices one for each ODM slice.
1059 	 *
1060 	 * In the following diagram the output pixel processing workload is
1061 	 * divided horizontally into two ODM slices one for each OPP blend tree.
1062 	 * OPP0 blend tree is responsible for processing left half of Timing
1063 	 * Active, while OPP2 blend tree is responsible for processing right
1064 	 * half.
1065 	 *
1066 	 * The plane has two MPC slices. However since the right MPC slice goes
1067 	 * across ODM boundary, two DPP pipes are needed one for each OPP blend
1068 	 * tree. (i.e. DPP1 for OPP0 blend tree and DPP2 for OPP2 blend tree).
1069 	 *
1070 	 * Assuming that we have a Pipe Context associated with OPP0 and DPP1
1071 	 * working on processing the plane in the diagram. We want to know the
1072 	 * width and height of the shaded rectangle and its relative position
1073 	 * with respect to the ODM slice0. This is called the recout of the pipe
1074 	 * context.
1075 	 *
1076 	 * Planes can be at arbitrary size and position and there could be an
1077 	 * arbitrary number of MPC and ODM slices. The algorithm needs to take
1078 	 * all scenarios into account.
1079 	 *
1080 	 * Timing Active Space (3840 x 2160)
1081 	 * ---------------------------------
1082 	 *
1083 	 *       Timing Active
1084 	 *        __________________________________________________
1085 	 *       |OPP0(ODM slice0)^        |OPP2(ODM slice1)        |
1086 	 *       |                y        |                        |
1087 	 *       |                |  <- w ->                        |
1088 	 *       |           _____V________|____                    |
1089 	 *       |          |DPP0 ^  |DPP1 |DPP2|                   |
1090 	 *       |<------ x |-----|->|/////|    |                   |
1091 	 *       |          |     |  |/////|    |                   |
1092 	 *       |          |     h  |/////|    |                   |
1093 	 *       |          |     |  |/////|    |                   |
1094 	 *       |          |_____V__|/////|____|                   |
1095 	 *       |                         |                        |
1096 	 *       |                         |                        |
1097 	 *       |                         |                        |
1098 	 *       |_________________________|________________________|
1099 	 *
1100 	 *
1101 	 */
1102 	struct rect plane_clip;
1103 	struct rect mpc_slice_of_plane_clip;
1104 	struct rect odm_slice_src;
1105 	struct rect overlapping_area;
1106 
1107 	plane_clip = calculate_plane_rec_in_timing_active(pipe_ctx,
1108 			&pipe_ctx->plane_state->clip_rect);
1109 	/* guard plane clip from drawing beyond stream dst here */
1110 	plane_clip = intersect_rec(&plane_clip,
1111 				&pipe_ctx->stream->dst);
1112 	mpc_slice_of_plane_clip = calculate_mpc_slice_in_timing_active(
1113 			pipe_ctx, &plane_clip);
1114 	odm_slice_src = resource_get_odm_slice_src_rect(pipe_ctx);
1115 	overlapping_area = intersect_rec(&mpc_slice_of_plane_clip, &odm_slice_src);
1116 	if (overlapping_area.height > 0 &&
1117 			overlapping_area.width > 0) {
1118 		/* shift the overlapping area so it is with respect to current
1119 		 * ODM slice source's position
1120 		 */
1121 		pipe_ctx->plane_res.scl_data.recout = shift_rec(
1122 				&overlapping_area,
1123 				-odm_slice_src.x, -odm_slice_src.y);
1124 		adjust_recout_for_visual_confirm(
1125 				&pipe_ctx->plane_res.scl_data.recout,
1126 				pipe_ctx);
1127 	} else {
1128 		/* if there is no overlap, zero recout */
1129 		memset(&pipe_ctx->plane_res.scl_data.recout, 0,
1130 				sizeof(struct rect));
1131 	}
1132 
1133 }
1134 
1135 static void calculate_scaling_ratios(struct pipe_ctx *pipe_ctx)
1136 {
1137 	const struct dc_plane_state *plane_state = pipe_ctx->plane_state;
1138 	const struct dc_stream_state *stream = pipe_ctx->stream;
1139 	struct rect surf_src = plane_state->src_rect;
1140 	const int in_w = stream->src.width;
1141 	const int in_h = stream->src.height;
1142 	const int out_w = stream->dst.width;
1143 	const int out_h = stream->dst.height;
1144 
1145 	/*Swap surf_src height and width since scaling ratios are in recout rotation*/
1146 	if (pipe_ctx->plane_state->rotation == ROTATION_ANGLE_90 ||
1147 			pipe_ctx->plane_state->rotation == ROTATION_ANGLE_270)
1148 		swap(surf_src.height, surf_src.width);
1149 
1150 	pipe_ctx->plane_res.scl_data.ratios.horz = dc_fixpt_from_fraction(
1151 					surf_src.width,
1152 					plane_state->dst_rect.width);
1153 	pipe_ctx->plane_res.scl_data.ratios.vert = dc_fixpt_from_fraction(
1154 					surf_src.height,
1155 					plane_state->dst_rect.height);
1156 
1157 	if (stream->view_format == VIEW_3D_FORMAT_SIDE_BY_SIDE)
1158 		pipe_ctx->plane_res.scl_data.ratios.horz.value *= 2;
1159 	else if (stream->view_format == VIEW_3D_FORMAT_TOP_AND_BOTTOM)
1160 		pipe_ctx->plane_res.scl_data.ratios.vert.value *= 2;
1161 
1162 	pipe_ctx->plane_res.scl_data.ratios.vert.value = div64_s64(
1163 		pipe_ctx->plane_res.scl_data.ratios.vert.value * in_h, out_h);
1164 	pipe_ctx->plane_res.scl_data.ratios.horz.value = div64_s64(
1165 		pipe_ctx->plane_res.scl_data.ratios.horz.value * in_w, out_w);
1166 
1167 	pipe_ctx->plane_res.scl_data.ratios.horz_c = pipe_ctx->plane_res.scl_data.ratios.horz;
1168 	pipe_ctx->plane_res.scl_data.ratios.vert_c = pipe_ctx->plane_res.scl_data.ratios.vert;
1169 
1170 	if (pipe_ctx->plane_res.scl_data.format == PIXEL_FORMAT_420BPP8
1171 			|| pipe_ctx->plane_res.scl_data.format == PIXEL_FORMAT_420BPP10) {
1172 		pipe_ctx->plane_res.scl_data.ratios.horz_c.value /= 2;
1173 		pipe_ctx->plane_res.scl_data.ratios.vert_c.value /= 2;
1174 	}
1175 	pipe_ctx->plane_res.scl_data.ratios.horz = dc_fixpt_truncate(
1176 			pipe_ctx->plane_res.scl_data.ratios.horz, 19);
1177 	pipe_ctx->plane_res.scl_data.ratios.vert = dc_fixpt_truncate(
1178 			pipe_ctx->plane_res.scl_data.ratios.vert, 19);
1179 	pipe_ctx->plane_res.scl_data.ratios.horz_c = dc_fixpt_truncate(
1180 			pipe_ctx->plane_res.scl_data.ratios.horz_c, 19);
1181 	pipe_ctx->plane_res.scl_data.ratios.vert_c = dc_fixpt_truncate(
1182 			pipe_ctx->plane_res.scl_data.ratios.vert_c, 19);
1183 }
1184 
1185 
1186 /*
1187  * We completely calculate vp offset, size and inits here based entirely on scaling
1188  * ratios and recout for pixel perfect pipe combine.
1189  */
1190 static void calculate_init_and_vp(
1191 		bool flip_scan_dir,
1192 		int recout_offset_within_recout_full,
1193 		int recout_size,
1194 		int src_size,
1195 		int taps,
1196 		struct fixed31_32 ratio,
1197 		struct fixed31_32 *init,
1198 		int *vp_offset,
1199 		int *vp_size)
1200 {
1201 	struct fixed31_32 temp;
1202 	int int_part;
1203 
1204 	/*
1205 	 * First of the taps starts sampling pixel number <init_int_part> corresponding to recout
1206 	 * pixel 1. Next recout pixel samples int part of <init + scaling ratio> and so on.
1207 	 * All following calculations are based on this logic.
1208 	 *
1209 	 * Init calculated according to formula:
1210 	 * 	init = (scaling_ratio + number_of_taps + 1) / 2
1211 	 * 	init_bot = init + scaling_ratio
1212 	 * 	to get pixel perfect combine add the fraction from calculating vp offset
1213 	 */
1214 	temp = dc_fixpt_mul_int(ratio, recout_offset_within_recout_full);
1215 	*vp_offset = dc_fixpt_floor(temp);
1216 	temp.value &= 0xffffffff;
1217 	*init = dc_fixpt_truncate(dc_fixpt_add(dc_fixpt_div_int(
1218 			dc_fixpt_add_int(ratio, taps + 1), 2), temp), 19);
1219 	/*
1220 	 * If viewport has non 0 offset and there are more taps than covered by init then
1221 	 * we should decrease the offset and increase init so we are never sampling
1222 	 * outside of viewport.
1223 	 */
1224 	int_part = dc_fixpt_floor(*init);
1225 	if (int_part < taps) {
1226 		int_part = taps - int_part;
1227 		if (int_part > *vp_offset)
1228 			int_part = *vp_offset;
1229 		*vp_offset -= int_part;
1230 		*init = dc_fixpt_add_int(*init, int_part);
1231 	}
1232 	/*
1233 	 * If taps are sampling outside of viewport at end of recout and there are more pixels
1234 	 * available in the surface we should increase the viewport size, regardless set vp to
1235 	 * only what is used.
1236 	 */
1237 	temp = dc_fixpt_add(*init, dc_fixpt_mul_int(ratio, recout_size - 1));
1238 	*vp_size = dc_fixpt_floor(temp);
1239 	if (*vp_size + *vp_offset > src_size)
1240 		*vp_size = src_size - *vp_offset;
1241 
1242 	/* We did all the math assuming we are scanning same direction as display does,
1243 	 * however mirror/rotation changes how vp scans vs how it is offset. If scan direction
1244 	 * is flipped we simply need to calculate offset from the other side of plane.
1245 	 * Note that outside of viewport all scaling hardware works in recout space.
1246 	 */
1247 	if (flip_scan_dir)
1248 		*vp_offset = src_size - *vp_offset - *vp_size;
1249 }
1250 
1251 static void calculate_inits_and_viewports(struct pipe_ctx *pipe_ctx)
1252 {
1253 	const struct dc_plane_state *plane_state = pipe_ctx->plane_state;
1254 	struct scaler_data *data = &pipe_ctx->plane_res.scl_data;
1255 	struct rect src = plane_state->src_rect;
1256 	struct rect recout_dst_in_active_timing;
1257 	struct rect recout_clip_in_active_timing;
1258 	struct rect recout_clip_in_recout_dst;
1259 	struct rect overlap_in_active_timing;
1260 	struct rect odm_slice_src = resource_get_odm_slice_src_rect(pipe_ctx);
1261 	int vpc_div = (data->format == PIXEL_FORMAT_420BPP8
1262 				|| data->format == PIXEL_FORMAT_420BPP10) ? 2 : 1;
1263 	bool orthogonal_rotation, flip_vert_scan_dir, flip_horz_scan_dir;
1264 
1265 	recout_clip_in_active_timing = shift_rec(
1266 			&data->recout, odm_slice_src.x, odm_slice_src.y);
1267 	recout_dst_in_active_timing = calculate_plane_rec_in_timing_active(
1268 			pipe_ctx, &plane_state->dst_rect);
1269 	overlap_in_active_timing = intersect_rec(&recout_clip_in_active_timing,
1270 			&recout_dst_in_active_timing);
1271 	if (overlap_in_active_timing.width > 0 &&
1272 			overlap_in_active_timing.height > 0)
1273 		recout_clip_in_recout_dst = shift_rec(&overlap_in_active_timing,
1274 				-recout_dst_in_active_timing.x,
1275 				-recout_dst_in_active_timing.y);
1276 	else
1277 		memset(&recout_clip_in_recout_dst, 0, sizeof(struct rect));
1278 
1279 	/*
1280 	 * Work in recout rotation since that requires less transformations
1281 	 */
1282 	get_vp_scan_direction(
1283 			plane_state->rotation,
1284 			plane_state->horizontal_mirror,
1285 			&orthogonal_rotation,
1286 			&flip_vert_scan_dir,
1287 			&flip_horz_scan_dir);
1288 
1289 	if (orthogonal_rotation) {
1290 		swap(src.width, src.height);
1291 		swap(flip_vert_scan_dir, flip_horz_scan_dir);
1292 	}
1293 
1294 	calculate_init_and_vp(
1295 			flip_horz_scan_dir,
1296 			recout_clip_in_recout_dst.x,
1297 			data->recout.width,
1298 			src.width,
1299 			data->taps.h_taps,
1300 			data->ratios.horz,
1301 			&data->inits.h,
1302 			&data->viewport.x,
1303 			&data->viewport.width);
1304 	calculate_init_and_vp(
1305 			flip_horz_scan_dir,
1306 			recout_clip_in_recout_dst.x,
1307 			data->recout.width,
1308 			src.width / vpc_div,
1309 			data->taps.h_taps_c,
1310 			data->ratios.horz_c,
1311 			&data->inits.h_c,
1312 			&data->viewport_c.x,
1313 			&data->viewport_c.width);
1314 	calculate_init_and_vp(
1315 			flip_vert_scan_dir,
1316 			recout_clip_in_recout_dst.y,
1317 			data->recout.height,
1318 			src.height,
1319 			data->taps.v_taps,
1320 			data->ratios.vert,
1321 			&data->inits.v,
1322 			&data->viewport.y,
1323 			&data->viewport.height);
1324 	calculate_init_and_vp(
1325 			flip_vert_scan_dir,
1326 			recout_clip_in_recout_dst.y,
1327 			data->recout.height,
1328 			src.height / vpc_div,
1329 			data->taps.v_taps_c,
1330 			data->ratios.vert_c,
1331 			&data->inits.v_c,
1332 			&data->viewport_c.y,
1333 			&data->viewport_c.height);
1334 	if (orthogonal_rotation) {
1335 		swap(data->viewport.x, data->viewport.y);
1336 		swap(data->viewport.width, data->viewport.height);
1337 		swap(data->viewport_c.x, data->viewport_c.y);
1338 		swap(data->viewport_c.width, data->viewport_c.height);
1339 	}
1340 	data->viewport.x += src.x;
1341 	data->viewport.y += src.y;
1342 	ASSERT(src.x % vpc_div == 0 && src.y % vpc_div == 0);
1343 	data->viewport_c.x += src.x / vpc_div;
1344 	data->viewport_c.y += src.y / vpc_div;
1345 }
1346 
1347 static bool is_subvp_high_refresh_candidate(struct dc_stream_state *stream)
1348 {
1349 	uint32_t refresh_rate;
1350 	struct dc *dc = stream->ctx->dc;
1351 
1352 	refresh_rate = (stream->timing.pix_clk_100hz * (uint64_t)100 +
1353 		stream->timing.v_total * stream->timing.h_total - (uint64_t)1);
1354 	refresh_rate = div_u64(refresh_rate, stream->timing.v_total);
1355 	refresh_rate = div_u64(refresh_rate, stream->timing.h_total);
1356 
1357 	/* If there's any stream that fits the SubVP high refresh criteria,
1358 	 * we must return true. This is because cursor updates are asynchronous
1359 	 * with full updates, so we could transition into a SubVP config and
1360 	 * remain in HW cursor mode if there's no cursor update which will
1361 	 * then cause corruption.
1362 	 */
1363 	if ((refresh_rate >= 120 && refresh_rate <= 175 &&
1364 			stream->timing.v_addressable >= 1080 &&
1365 			stream->timing.v_addressable <= 2160) &&
1366 			(dc->current_state->stream_count > 1 ||
1367 			(dc->current_state->stream_count == 1 && !stream->allow_freesync)))
1368 		return true;
1369 
1370 	return false;
1371 }
1372 
1373 static enum controller_dp_test_pattern convert_dp_to_controller_test_pattern(
1374 				enum dp_test_pattern test_pattern)
1375 {
1376 	enum controller_dp_test_pattern controller_test_pattern;
1377 
1378 	switch (test_pattern) {
1379 	case DP_TEST_PATTERN_COLOR_SQUARES:
1380 		controller_test_pattern =
1381 				CONTROLLER_DP_TEST_PATTERN_COLORSQUARES;
1382 	break;
1383 	case DP_TEST_PATTERN_COLOR_SQUARES_CEA:
1384 		controller_test_pattern =
1385 				CONTROLLER_DP_TEST_PATTERN_COLORSQUARES_CEA;
1386 	break;
1387 	case DP_TEST_PATTERN_VERTICAL_BARS:
1388 		controller_test_pattern =
1389 				CONTROLLER_DP_TEST_PATTERN_VERTICALBARS;
1390 	break;
1391 	case DP_TEST_PATTERN_HORIZONTAL_BARS:
1392 		controller_test_pattern =
1393 				CONTROLLER_DP_TEST_PATTERN_HORIZONTALBARS;
1394 	break;
1395 	case DP_TEST_PATTERN_COLOR_RAMP:
1396 		controller_test_pattern =
1397 				CONTROLLER_DP_TEST_PATTERN_COLORRAMP;
1398 	break;
1399 	default:
1400 		controller_test_pattern =
1401 				CONTROLLER_DP_TEST_PATTERN_VIDEOMODE;
1402 	break;
1403 	}
1404 
1405 	return controller_test_pattern;
1406 }
1407 
1408 static enum controller_dp_color_space convert_dp_to_controller_color_space(
1409 		enum dp_test_pattern_color_space color_space)
1410 {
1411 	enum controller_dp_color_space controller_color_space;
1412 
1413 	switch (color_space) {
1414 	case DP_TEST_PATTERN_COLOR_SPACE_RGB:
1415 		controller_color_space = CONTROLLER_DP_COLOR_SPACE_RGB;
1416 		break;
1417 	case DP_TEST_PATTERN_COLOR_SPACE_YCBCR601:
1418 		controller_color_space = CONTROLLER_DP_COLOR_SPACE_YCBCR601;
1419 		break;
1420 	case DP_TEST_PATTERN_COLOR_SPACE_YCBCR709:
1421 		controller_color_space = CONTROLLER_DP_COLOR_SPACE_YCBCR709;
1422 		break;
1423 	case DP_TEST_PATTERN_COLOR_SPACE_UNDEFINED:
1424 	default:
1425 		controller_color_space = CONTROLLER_DP_COLOR_SPACE_UDEFINED;
1426 		break;
1427 	}
1428 
1429 	return controller_color_space;
1430 }
1431 
1432 void resource_build_test_pattern_params(struct resource_context *res_ctx,
1433 				struct pipe_ctx *otg_master)
1434 {
1435 	struct pipe_ctx *opp_heads[MAX_PIPES];
1436 	struct test_pattern_params *params;
1437 	int odm_cnt;
1438 	enum controller_dp_test_pattern controller_test_pattern;
1439 	enum controller_dp_color_space controller_color_space;
1440 	enum dc_color_depth color_depth = otg_master->stream->timing.display_color_depth;
1441 	struct rect odm_slice_src;
1442 	int i;
1443 
1444 	controller_test_pattern = convert_dp_to_controller_test_pattern(
1445 			otg_master->stream->test_pattern.type);
1446 	controller_color_space = convert_dp_to_controller_color_space(
1447 			otg_master->stream->test_pattern.color_space);
1448 
1449 	if (controller_test_pattern == CONTROLLER_DP_TEST_PATTERN_VIDEOMODE)
1450 		return;
1451 
1452 	odm_cnt = resource_get_opp_heads_for_otg_master(otg_master, res_ctx, opp_heads);
1453 
1454 	for (i = 0; i < odm_cnt; i++) {
1455 		odm_slice_src = resource_get_odm_slice_src_rect(opp_heads[i]);
1456 		params = &opp_heads[i]->stream_res.test_pattern_params;
1457 		params->test_pattern = controller_test_pattern;
1458 		params->color_space = controller_color_space;
1459 		params->color_depth = color_depth;
1460 		params->height = odm_slice_src.height;
1461 		params->offset = odm_slice_src.x;
1462 		params->width = odm_slice_src.width;
1463 	}
1464 }
1465 
1466 bool resource_build_scaling_params(struct pipe_ctx *pipe_ctx)
1467 {
1468 	const struct dc_plane_state *plane_state = pipe_ctx->plane_state;
1469 	struct dc_crtc_timing *timing = &pipe_ctx->stream->timing;
1470 	const struct rect odm_slice_src = resource_get_odm_slice_src_rect(pipe_ctx);
1471 	bool res = false;
1472 
1473 	DC_LOGGER_INIT(pipe_ctx->stream->ctx->logger);
1474 
1475 	/* Invalid input */
1476 	if (!plane_state->dst_rect.width ||
1477 			!plane_state->dst_rect.height ||
1478 			!plane_state->src_rect.width ||
1479 			!plane_state->src_rect.height) {
1480 		ASSERT(0);
1481 		return false;
1482 	}
1483 
1484 	/* Timing borders are part of vactive that we are also supposed to skip in addition
1485 	 * to any stream dst offset. Since dm logic assumes dst is in addressable
1486 	 * space we need to add the left and top borders to dst offsets temporarily.
1487 	 * TODO: fix in DM, stream dst is supposed to be in vactive
1488 	 */
1489 	pipe_ctx->stream->dst.x += timing->h_border_left;
1490 	pipe_ctx->stream->dst.y += timing->v_border_top;
1491 
1492 	/* Calculate H and V active size */
1493 	pipe_ctx->plane_res.scl_data.h_active = odm_slice_src.width;
1494 	pipe_ctx->plane_res.scl_data.v_active = odm_slice_src.height;
1495 	pipe_ctx->plane_res.scl_data.format = convert_pixel_format_to_dalsurface(
1496 			pipe_ctx->plane_state->format);
1497 
1498 #if defined(CONFIG_DRM_AMD_DC_FP)
1499 	if ((pipe_ctx->stream->ctx->dc->config.use_spl)	&& (!pipe_ctx->stream->ctx->dc->debug.disable_spl)) {
1500 		struct spl_in *spl_in = &pipe_ctx->plane_res.spl_in;
1501 		struct spl_out *spl_out = &pipe_ctx->plane_res.spl_out;
1502 
1503 		if (plane_state->ctx->dce_version > DCE_VERSION_MAX)
1504 			pipe_ctx->plane_res.scl_data.lb_params.depth = LB_PIXEL_DEPTH_36BPP;
1505 		else
1506 			pipe_ctx->plane_res.scl_data.lb_params.depth = LB_PIXEL_DEPTH_30BPP;
1507 
1508 		pipe_ctx->plane_res.scl_data.lb_params.alpha_en = plane_state->per_pixel_alpha;
1509 
1510 		// Convert pipe_ctx to respective input params for SPL
1511 		translate_SPL_in_params_from_pipe_ctx(pipe_ctx, spl_in);
1512 		/* Pass visual confirm debug information */
1513 		calculate_adjust_recout_for_visual_confirm(pipe_ctx,
1514 			&spl_in->debug.visual_confirm_base_offset,
1515 			&spl_in->debug.visual_confirm_dpp_offset);
1516 		// Set SPL output parameters to dscl_prog_data to be used for hw registers
1517 		spl_out->dscl_prog_data = resource_get_dscl_prog_data(pipe_ctx);
1518 		// Calculate scaler parameters from SPL
1519 		res = spl_calculate_scaler_params(spl_in, spl_out);
1520 		// Convert respective out params from SPL to scaler data
1521 		translate_SPL_out_params_to_pipe_ctx(pipe_ctx, spl_out);
1522 	} else {
1523 #endif
1524 	/* depends on h_active */
1525 	calculate_recout(pipe_ctx);
1526 	/* depends on pixel format */
1527 	calculate_scaling_ratios(pipe_ctx);
1528 	/* depends on scaling ratios and recout, does not calculate offset yet */
1529 	calculate_viewport_size(pipe_ctx);
1530 
1531 	/*
1532 	 * LB calculations depend on vp size, h/v_active and scaling ratios
1533 	 * Setting line buffer pixel depth to 24bpp yields banding
1534 	 * on certain displays, such as the Sharp 4k. 36bpp is needed
1535 	 * to support SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616 and
1536 	 * SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616 with actual > 10 bpc
1537 	 * precision on DCN display engines, but apparently not for DCE, as
1538 	 * far as testing on DCE-11.2 and DCE-8 showed. Various DCE parts have
1539 	 * problems: Carrizo with DCE_VERSION_11_0 does not like 36 bpp lb depth,
1540 	 * neither do DCE-8 at 4k resolution, or DCE-11.2 (broken identify pixel
1541 	 * passthrough). Therefore only use 36 bpp on DCN where it is actually needed.
1542 	 */
1543 	if (plane_state->ctx->dce_version > DCE_VERSION_MAX)
1544 		pipe_ctx->plane_res.scl_data.lb_params.depth = LB_PIXEL_DEPTH_36BPP;
1545 	else
1546 		pipe_ctx->plane_res.scl_data.lb_params.depth = LB_PIXEL_DEPTH_30BPP;
1547 
1548 	pipe_ctx->plane_res.scl_data.lb_params.alpha_en = plane_state->per_pixel_alpha;
1549 
1550 	if (pipe_ctx->plane_res.xfm != NULL)
1551 		res = pipe_ctx->plane_res.xfm->funcs->transform_get_optimal_number_of_taps(
1552 				pipe_ctx->plane_res.xfm, &pipe_ctx->plane_res.scl_data, &plane_state->scaling_quality);
1553 
1554 	if (pipe_ctx->plane_res.dpp != NULL)
1555 		res = pipe_ctx->plane_res.dpp->funcs->dpp_get_optimal_number_of_taps(
1556 				pipe_ctx->plane_res.dpp, &pipe_ctx->plane_res.scl_data, &plane_state->scaling_quality);
1557 
1558 
1559 	if (!res) {
1560 		/* Try 24 bpp linebuffer */
1561 		pipe_ctx->plane_res.scl_data.lb_params.depth = LB_PIXEL_DEPTH_24BPP;
1562 
1563 		if (pipe_ctx->plane_res.xfm != NULL)
1564 			res = pipe_ctx->plane_res.xfm->funcs->transform_get_optimal_number_of_taps(
1565 					pipe_ctx->plane_res.xfm,
1566 					&pipe_ctx->plane_res.scl_data,
1567 					&plane_state->scaling_quality);
1568 
1569 		if (pipe_ctx->plane_res.dpp != NULL)
1570 			res = pipe_ctx->plane_res.dpp->funcs->dpp_get_optimal_number_of_taps(
1571 					pipe_ctx->plane_res.dpp,
1572 					&pipe_ctx->plane_res.scl_data,
1573 					&plane_state->scaling_quality);
1574 	}
1575 
1576 	/*
1577 	 * Depends on recout, scaling ratios, h_active and taps
1578 	 * May need to re-check lb size after this in some obscure scenario
1579 	 */
1580 	if (res)
1581 		calculate_inits_and_viewports(pipe_ctx);
1582 
1583 	/*
1584 	 * Handle side by side and top bottom 3d recout offsets after vp calculation
1585 	 * since 3d is special and needs to calculate vp as if there is no recout offset
1586 	 * This may break with rotation, good thing we aren't mixing hw rotation and 3d
1587 	 */
1588 	if (pipe_ctx->top_pipe && pipe_ctx->top_pipe->plane_state == plane_state) {
1589 		ASSERT(plane_state->rotation == ROTATION_ANGLE_0 ||
1590 			(pipe_ctx->stream->view_format != VIEW_3D_FORMAT_TOP_AND_BOTTOM &&
1591 				pipe_ctx->stream->view_format != VIEW_3D_FORMAT_SIDE_BY_SIDE));
1592 		if (pipe_ctx->stream->view_format == VIEW_3D_FORMAT_TOP_AND_BOTTOM)
1593 			pipe_ctx->plane_res.scl_data.recout.y += pipe_ctx->plane_res.scl_data.recout.height;
1594 		else if (pipe_ctx->stream->view_format == VIEW_3D_FORMAT_SIDE_BY_SIDE)
1595 			pipe_ctx->plane_res.scl_data.recout.x += pipe_ctx->plane_res.scl_data.recout.width;
1596 	}
1597 
1598 	/* Clamp minimum viewport size */
1599 	if (pipe_ctx->plane_res.scl_data.viewport.height < MIN_VIEWPORT_SIZE)
1600 		pipe_ctx->plane_res.scl_data.viewport.height = MIN_VIEWPORT_SIZE;
1601 	if (pipe_ctx->plane_res.scl_data.viewport.width < MIN_VIEWPORT_SIZE)
1602 		pipe_ctx->plane_res.scl_data.viewport.width = MIN_VIEWPORT_SIZE;
1603 #ifdef CONFIG_DRM_AMD_DC_FP
1604 	}
1605 #endif
1606 	DC_LOG_SCALER("%s pipe %d:\nViewport: height:%d width:%d x:%d y:%d  Recout: height:%d width:%d x:%d y:%d  HACTIVE:%d VACTIVE:%d\n"
1607 			"src_rect: height:%d width:%d x:%d y:%d  dst_rect: height:%d width:%d x:%d y:%d  clip_rect: height:%d width:%d x:%d y:%d\n",
1608 			__func__,
1609 			pipe_ctx->pipe_idx,
1610 			pipe_ctx->plane_res.scl_data.viewport.height,
1611 			pipe_ctx->plane_res.scl_data.viewport.width,
1612 			pipe_ctx->plane_res.scl_data.viewport.x,
1613 			pipe_ctx->plane_res.scl_data.viewport.y,
1614 			pipe_ctx->plane_res.scl_data.recout.height,
1615 			pipe_ctx->plane_res.scl_data.recout.width,
1616 			pipe_ctx->plane_res.scl_data.recout.x,
1617 			pipe_ctx->plane_res.scl_data.recout.y,
1618 			pipe_ctx->plane_res.scl_data.h_active,
1619 			pipe_ctx->plane_res.scl_data.v_active,
1620 			plane_state->src_rect.height,
1621 			plane_state->src_rect.width,
1622 			plane_state->src_rect.x,
1623 			plane_state->src_rect.y,
1624 			plane_state->dst_rect.height,
1625 			plane_state->dst_rect.width,
1626 			plane_state->dst_rect.x,
1627 			plane_state->dst_rect.y,
1628 			plane_state->clip_rect.height,
1629 			plane_state->clip_rect.width,
1630 			plane_state->clip_rect.x,
1631 			plane_state->clip_rect.y);
1632 
1633 	pipe_ctx->stream->dst.x -= timing->h_border_left;
1634 	pipe_ctx->stream->dst.y -= timing->v_border_top;
1635 
1636 	return res;
1637 }
1638 
1639 
1640 enum dc_status resource_build_scaling_params_for_context(
1641 	const struct dc  *dc,
1642 	struct dc_state *context)
1643 {
1644 	int i;
1645 
1646 	for (i = 0; i < MAX_PIPES; i++) {
1647 		if (context->res_ctx.pipe_ctx[i].plane_state != NULL &&
1648 				context->res_ctx.pipe_ctx[i].stream != NULL)
1649 			if (!resource_build_scaling_params(&context->res_ctx.pipe_ctx[i]))
1650 				return DC_FAIL_SCALING;
1651 	}
1652 
1653 	return DC_OK;
1654 }
1655 
1656 struct pipe_ctx *resource_find_free_secondary_pipe_legacy(
1657 		struct resource_context *res_ctx,
1658 		const struct resource_pool *pool,
1659 		const struct pipe_ctx *primary_pipe)
1660 {
1661 	int i;
1662 	struct pipe_ctx *secondary_pipe = NULL;
1663 
1664 	/*
1665 	 * We add a preferred pipe mapping to avoid the chance that
1666 	 * MPCCs already in use will need to be reassigned to other trees.
1667 	 * For example, if we went with the strict, assign backwards logic:
1668 	 *
1669 	 * (State 1)
1670 	 * Display A on, no surface, top pipe = 0
1671 	 * Display B on, no surface, top pipe = 1
1672 	 *
1673 	 * (State 2)
1674 	 * Display A on, no surface, top pipe = 0
1675 	 * Display B on, surface enable, top pipe = 1, bottom pipe = 5
1676 	 *
1677 	 * (State 3)
1678 	 * Display A on, surface enable, top pipe = 0, bottom pipe = 5
1679 	 * Display B on, surface enable, top pipe = 1, bottom pipe = 4
1680 	 *
1681 	 * The state 2->3 transition requires remapping MPCC 5 from display B
1682 	 * to display A.
1683 	 *
1684 	 * However, with the preferred pipe logic, state 2 would look like:
1685 	 *
1686 	 * (State 2)
1687 	 * Display A on, no surface, top pipe = 0
1688 	 * Display B on, surface enable, top pipe = 1, bottom pipe = 4
1689 	 *
1690 	 * This would then cause 2->3 to not require remapping any MPCCs.
1691 	 */
1692 	if (primary_pipe) {
1693 		int preferred_pipe_idx = (pool->pipe_count - 1) - primary_pipe->pipe_idx;
1694 		if (res_ctx->pipe_ctx[preferred_pipe_idx].stream == NULL) {
1695 			secondary_pipe = &res_ctx->pipe_ctx[preferred_pipe_idx];
1696 			secondary_pipe->pipe_idx = preferred_pipe_idx;
1697 		}
1698 	}
1699 
1700 	/*
1701 	 * search backwards for the second pipe to keep pipe
1702 	 * assignment more consistent
1703 	 */
1704 	if (!secondary_pipe)
1705 		for (i = pool->pipe_count - 1; i >= 0; i--) {
1706 			if (res_ctx->pipe_ctx[i].stream == NULL) {
1707 				secondary_pipe = &res_ctx->pipe_ctx[i];
1708 				secondary_pipe->pipe_idx = i;
1709 				break;
1710 			}
1711 		}
1712 
1713 	return secondary_pipe;
1714 }
1715 
1716 int resource_find_free_pipe_used_as_sec_opp_head_by_cur_otg_master(
1717 		const struct resource_context *cur_res_ctx,
1718 		struct resource_context *new_res_ctx,
1719 		const struct pipe_ctx *cur_otg_master)
1720 {
1721 	const struct pipe_ctx *cur_sec_opp_head = cur_otg_master->next_odm_pipe;
1722 	struct pipe_ctx *new_pipe;
1723 	int free_pipe_idx = FREE_PIPE_INDEX_NOT_FOUND;
1724 
1725 	while (cur_sec_opp_head) {
1726 		new_pipe = &new_res_ctx->pipe_ctx[cur_sec_opp_head->pipe_idx];
1727 		if (resource_is_pipe_type(new_pipe, FREE_PIPE)) {
1728 			free_pipe_idx = cur_sec_opp_head->pipe_idx;
1729 			break;
1730 		}
1731 		cur_sec_opp_head = cur_sec_opp_head->next_odm_pipe;
1732 	}
1733 
1734 	return free_pipe_idx;
1735 }
1736 
1737 int resource_find_free_pipe_used_in_cur_mpc_blending_tree(
1738 		const struct resource_context *cur_res_ctx,
1739 		struct resource_context *new_res_ctx,
1740 		const struct pipe_ctx *cur_opp_head)
1741 {
1742 	const struct pipe_ctx *cur_sec_dpp = cur_opp_head->bottom_pipe;
1743 	struct pipe_ctx *new_pipe;
1744 	int free_pipe_idx = FREE_PIPE_INDEX_NOT_FOUND;
1745 
1746 	while (cur_sec_dpp) {
1747 		/* find a free pipe used in current opp blend tree,
1748 		 * this is to avoid MPO pipe switching to different opp blending
1749 		 * tree
1750 		 */
1751 		new_pipe = &new_res_ctx->pipe_ctx[cur_sec_dpp->pipe_idx];
1752 		if (resource_is_pipe_type(new_pipe, FREE_PIPE)) {
1753 			free_pipe_idx = cur_sec_dpp->pipe_idx;
1754 			break;
1755 		}
1756 		cur_sec_dpp = cur_sec_dpp->bottom_pipe;
1757 	}
1758 
1759 	return free_pipe_idx;
1760 }
1761 
1762 int recource_find_free_pipe_not_used_in_cur_res_ctx(
1763 		const struct resource_context *cur_res_ctx,
1764 		struct resource_context *new_res_ctx,
1765 		const struct resource_pool *pool)
1766 {
1767 	int free_pipe_idx = FREE_PIPE_INDEX_NOT_FOUND;
1768 	const struct pipe_ctx *new_pipe, *cur_pipe;
1769 	int i;
1770 
1771 	for (i = 0; i < pool->pipe_count; i++) {
1772 		cur_pipe = &cur_res_ctx->pipe_ctx[i];
1773 		new_pipe = &new_res_ctx->pipe_ctx[i];
1774 
1775 		if (resource_is_pipe_type(cur_pipe, FREE_PIPE) &&
1776 				resource_is_pipe_type(new_pipe, FREE_PIPE)) {
1777 			free_pipe_idx = i;
1778 			break;
1779 		}
1780 	}
1781 
1782 	return free_pipe_idx;
1783 }
1784 
1785 int recource_find_free_pipe_used_as_otg_master_in_cur_res_ctx(
1786 		const struct resource_context *cur_res_ctx,
1787 		struct resource_context *new_res_ctx,
1788 		const struct resource_pool *pool)
1789 {
1790 	int free_pipe_idx = FREE_PIPE_INDEX_NOT_FOUND;
1791 	const struct pipe_ctx *new_pipe, *cur_pipe;
1792 	int i;
1793 
1794 	for (i = 0; i < pool->pipe_count; i++) {
1795 		cur_pipe = &cur_res_ctx->pipe_ctx[i];
1796 		new_pipe = &new_res_ctx->pipe_ctx[i];
1797 
1798 		if (resource_is_pipe_type(cur_pipe, OTG_MASTER) &&
1799 				resource_is_pipe_type(new_pipe, FREE_PIPE)) {
1800 			free_pipe_idx = i;
1801 			break;
1802 		}
1803 	}
1804 
1805 	return free_pipe_idx;
1806 }
1807 
1808 int resource_find_free_pipe_used_as_cur_sec_dpp(
1809 		const struct resource_context *cur_res_ctx,
1810 		struct resource_context *new_res_ctx,
1811 		const struct resource_pool *pool)
1812 {
1813 	int free_pipe_idx = FREE_PIPE_INDEX_NOT_FOUND;
1814 	const struct pipe_ctx *new_pipe, *cur_pipe;
1815 	int i;
1816 
1817 	for (i = 0; i < pool->pipe_count; i++) {
1818 		cur_pipe = &cur_res_ctx->pipe_ctx[i];
1819 		new_pipe = &new_res_ctx->pipe_ctx[i];
1820 
1821 		if (resource_is_pipe_type(cur_pipe, DPP_PIPE) &&
1822 				!resource_is_pipe_type(cur_pipe, OPP_HEAD) &&
1823 				resource_is_pipe_type(new_pipe, FREE_PIPE)) {
1824 			free_pipe_idx = i;
1825 			break;
1826 		}
1827 	}
1828 
1829 	return free_pipe_idx;
1830 }
1831 
1832 int resource_find_free_pipe_used_as_cur_sec_dpp_in_mpcc_combine(
1833 		const struct resource_context *cur_res_ctx,
1834 		struct resource_context *new_res_ctx,
1835 		const struct resource_pool *pool)
1836 {
1837 	int free_pipe_idx = FREE_PIPE_INDEX_NOT_FOUND;
1838 	const struct pipe_ctx *new_pipe, *cur_pipe;
1839 	int i;
1840 
1841 	for (i = 0; i < pool->pipe_count; i++) {
1842 		cur_pipe = &cur_res_ctx->pipe_ctx[i];
1843 		new_pipe = &new_res_ctx->pipe_ctx[i];
1844 
1845 		if (resource_is_pipe_type(cur_pipe, DPP_PIPE) &&
1846 				!resource_is_pipe_type(cur_pipe, OPP_HEAD) &&
1847 				resource_get_mpc_slice_index(cur_pipe) > 0 &&
1848 				resource_is_pipe_type(new_pipe, FREE_PIPE)) {
1849 			free_pipe_idx = i;
1850 			break;
1851 		}
1852 	}
1853 
1854 	return free_pipe_idx;
1855 }
1856 
1857 int resource_find_any_free_pipe(struct resource_context *new_res_ctx,
1858 		const struct resource_pool *pool)
1859 {
1860 	int free_pipe_idx = FREE_PIPE_INDEX_NOT_FOUND;
1861 	const struct pipe_ctx *new_pipe;
1862 	int i;
1863 
1864 	for (i = 0; i < pool->pipe_count; i++) {
1865 		new_pipe = &new_res_ctx->pipe_ctx[i];
1866 
1867 		if (resource_is_pipe_type(new_pipe, FREE_PIPE)) {
1868 			free_pipe_idx = i;
1869 			break;
1870 		}
1871 	}
1872 
1873 	return free_pipe_idx;
1874 }
1875 
1876 bool resource_is_pipe_type(const struct pipe_ctx *pipe_ctx, enum pipe_type type)
1877 {
1878 	switch (type) {
1879 	case OTG_MASTER:
1880 		return !pipe_ctx->prev_odm_pipe &&
1881 				!pipe_ctx->top_pipe &&
1882 				pipe_ctx->stream;
1883 	case OPP_HEAD:
1884 		return !pipe_ctx->top_pipe && pipe_ctx->stream;
1885 	case DPP_PIPE:
1886 		return pipe_ctx->plane_state && pipe_ctx->stream;
1887 	case FREE_PIPE:
1888 		return !pipe_ctx->plane_state && !pipe_ctx->stream;
1889 	default:
1890 		return false;
1891 	}
1892 }
1893 
1894 struct pipe_ctx *resource_get_otg_master_for_stream(
1895 		struct resource_context *res_ctx,
1896 		const struct dc_stream_state *stream)
1897 {
1898 	int i;
1899 
1900 	for (i = 0; i < MAX_PIPES; i++) {
1901 		if (res_ctx->pipe_ctx[i].stream == stream &&
1902 				resource_is_pipe_type(&res_ctx->pipe_ctx[i], OTG_MASTER))
1903 			return &res_ctx->pipe_ctx[i];
1904 	}
1905 	return NULL;
1906 }
1907 
1908 int resource_get_opp_heads_for_otg_master(const struct pipe_ctx *otg_master,
1909 		struct resource_context *res_ctx,
1910 		struct pipe_ctx *opp_heads[MAX_PIPES])
1911 {
1912 	struct pipe_ctx *opp_head = &res_ctx->pipe_ctx[otg_master->pipe_idx];
1913 	struct dc *dc = otg_master->stream->ctx->dc;
1914 	int i = 0;
1915 
1916 	DC_LOGGER_INIT(dc->ctx->logger);
1917 
1918 	if (!resource_is_pipe_type(otg_master, OTG_MASTER)) {
1919 		DC_LOG_WARNING("%s called from a non OTG master, something "
1920 			       "is wrong in the pipe configuration",
1921 			       __func__);
1922 		ASSERT(0);
1923 		return 0;
1924 	}
1925 	while (opp_head) {
1926 		ASSERT(i < MAX_PIPES);
1927 		opp_heads[i++] = opp_head;
1928 		opp_head = opp_head->next_odm_pipe;
1929 	}
1930 	return i;
1931 }
1932 
1933 int resource_get_dpp_pipes_for_opp_head(const struct pipe_ctx *opp_head,
1934 		struct resource_context *res_ctx,
1935 		struct pipe_ctx *dpp_pipes[MAX_PIPES])
1936 {
1937 	struct pipe_ctx *pipe = &res_ctx->pipe_ctx[opp_head->pipe_idx];
1938 	int i = 0;
1939 
1940 	if (!resource_is_pipe_type(opp_head, OPP_HEAD)) {
1941 		ASSERT(0);
1942 		return 0;
1943 	}
1944 	while (pipe && resource_is_pipe_type(pipe, DPP_PIPE)) {
1945 		ASSERT(i < MAX_PIPES);
1946 		dpp_pipes[i++] = pipe;
1947 		pipe = pipe->bottom_pipe;
1948 	}
1949 	return i;
1950 }
1951 
1952 int resource_get_dpp_pipes_for_plane(const struct dc_plane_state *plane,
1953 		struct resource_context *res_ctx,
1954 		struct pipe_ctx *dpp_pipes[MAX_PIPES])
1955 {
1956 	int i = 0, j;
1957 	struct pipe_ctx *pipe;
1958 
1959 	for (j = 0; j < MAX_PIPES; j++) {
1960 		pipe = &res_ctx->pipe_ctx[j];
1961 		if (pipe->plane_state == plane && pipe->prev_odm_pipe == NULL) {
1962 			if (resource_is_pipe_type(pipe, OPP_HEAD) ||
1963 					pipe->top_pipe->plane_state != plane)
1964 				break;
1965 		}
1966 	}
1967 
1968 	if (j < MAX_PIPES) {
1969 		if (pipe->next_odm_pipe)
1970 			while (pipe) {
1971 				dpp_pipes[i++] = pipe;
1972 				pipe = pipe->next_odm_pipe;
1973 			}
1974 		else
1975 			while (pipe && pipe->plane_state == plane) {
1976 				dpp_pipes[i++] = pipe;
1977 				pipe = pipe->bottom_pipe;
1978 			}
1979 	}
1980 	return i;
1981 }
1982 
1983 struct pipe_ctx *resource_get_otg_master(const struct pipe_ctx *pipe_ctx)
1984 {
1985 	struct pipe_ctx *otg_master = resource_get_opp_head(pipe_ctx);
1986 
1987 	while (otg_master->prev_odm_pipe)
1988 		otg_master = otg_master->prev_odm_pipe;
1989 	return otg_master;
1990 }
1991 
1992 struct pipe_ctx *resource_get_opp_head(const struct pipe_ctx *pipe_ctx)
1993 {
1994 	struct pipe_ctx *opp_head = (struct pipe_ctx *) pipe_ctx;
1995 
1996 	ASSERT(!resource_is_pipe_type(opp_head, FREE_PIPE));
1997 	while (opp_head->top_pipe)
1998 		opp_head = opp_head->top_pipe;
1999 	return opp_head;
2000 }
2001 
2002 struct pipe_ctx *resource_get_primary_dpp_pipe(const struct pipe_ctx *dpp_pipe)
2003 {
2004 	struct pipe_ctx *pri_dpp_pipe = (struct pipe_ctx *) dpp_pipe;
2005 
2006 	ASSERT(resource_is_pipe_type(dpp_pipe, DPP_PIPE));
2007 	while (pri_dpp_pipe->prev_odm_pipe)
2008 		pri_dpp_pipe = pri_dpp_pipe->prev_odm_pipe;
2009 	while (pri_dpp_pipe->top_pipe &&
2010 			pri_dpp_pipe->top_pipe->plane_state == pri_dpp_pipe->plane_state)
2011 		pri_dpp_pipe = pri_dpp_pipe->top_pipe;
2012 	return pri_dpp_pipe;
2013 }
2014 
2015 
2016 int resource_get_mpc_slice_index(const struct pipe_ctx *pipe_ctx)
2017 {
2018 	struct pipe_ctx *split_pipe = pipe_ctx->top_pipe;
2019 	int index = 0;
2020 
2021 	while (split_pipe && split_pipe->plane_state == pipe_ctx->plane_state) {
2022 		index++;
2023 		split_pipe = split_pipe->top_pipe;
2024 	}
2025 
2026 	return index;
2027 }
2028 
2029 int resource_get_mpc_slice_count(const struct pipe_ctx *pipe)
2030 {
2031 	int mpc_split_count = 1;
2032 	const struct pipe_ctx *other_pipe = pipe->bottom_pipe;
2033 
2034 	while (other_pipe && other_pipe->plane_state == pipe->plane_state) {
2035 		mpc_split_count++;
2036 		other_pipe = other_pipe->bottom_pipe;
2037 	}
2038 	other_pipe = pipe->top_pipe;
2039 	while (other_pipe && other_pipe->plane_state == pipe->plane_state) {
2040 		mpc_split_count++;
2041 		other_pipe = other_pipe->top_pipe;
2042 	}
2043 
2044 	return mpc_split_count;
2045 }
2046 
2047 int resource_get_odm_slice_count(const struct pipe_ctx *pipe)
2048 {
2049 	int odm_split_count = 1;
2050 
2051 	pipe = resource_get_otg_master(pipe);
2052 
2053 	while (pipe->next_odm_pipe) {
2054 		odm_split_count++;
2055 		pipe = pipe->next_odm_pipe;
2056 	}
2057 	return odm_split_count;
2058 }
2059 
2060 int resource_get_odm_slice_index(const struct pipe_ctx *pipe_ctx)
2061 {
2062 	int index = 0;
2063 
2064 	pipe_ctx = resource_get_opp_head(pipe_ctx);
2065 	if (!pipe_ctx)
2066 		return 0;
2067 
2068 	while (pipe_ctx->prev_odm_pipe) {
2069 		index++;
2070 		pipe_ctx = pipe_ctx->prev_odm_pipe;
2071 	}
2072 
2073 	return index;
2074 }
2075 
2076 int resource_get_odm_slice_dst_width(struct pipe_ctx *otg_master,
2077 		bool is_last_segment)
2078 {
2079 	const struct dc_crtc_timing *timing;
2080 	int count;
2081 	int h_active;
2082 	int width;
2083 	bool two_pixel_alignment_required = false;
2084 
2085 	if (!otg_master || !otg_master->stream)
2086 		return 0;
2087 
2088 	timing = &otg_master->stream->timing;
2089 	count = resource_get_odm_slice_count(otg_master);
2090 	h_active = timing->h_addressable +
2091 			timing->h_border_left +
2092 			timing->h_border_right;
2093 	width = h_active / count;
2094 
2095 	if (otg_master->stream_res.tg)
2096 		two_pixel_alignment_required =
2097 				otg_master->stream_res.tg->funcs->is_two_pixels_per_container(timing) ||
2098 				/*
2099 				 * 422 is sub-sampled horizontally. 1 set of chromas
2100 				 * (Cb/Cr) is shared for 2 lumas (i.e 2 Y values).
2101 				 * Therefore even if 422 is still 1 pixel per container,
2102 				 * ODM segment width still needs to be 2 pixel aligned.
2103 				 */
2104 				timing->pixel_encoding == PIXEL_ENCODING_YCBCR422;
2105 	if ((width % 2) && two_pixel_alignment_required)
2106 		width++;
2107 
2108 	return is_last_segment ?
2109 			h_active - width * (count - 1) :
2110 			width;
2111 }
2112 
2113 struct rect resource_get_odm_slice_dst_rect(struct pipe_ctx *pipe_ctx)
2114 {
2115 	const struct dc_stream_state *stream = pipe_ctx->stream;
2116 	bool is_last_odm_slice = pipe_ctx->next_odm_pipe == NULL;
2117 	struct pipe_ctx *otg_master = resource_get_otg_master(pipe_ctx);
2118 	int odm_slice_idx = resource_get_odm_slice_index(pipe_ctx);
2119 	int odm_segment_offset = resource_get_odm_slice_dst_width(otg_master, false);
2120 	struct rect odm_slice_dst;
2121 
2122 	odm_slice_dst.x = odm_segment_offset * odm_slice_idx;
2123 	odm_slice_dst.width = resource_get_odm_slice_dst_width(otg_master, is_last_odm_slice);
2124 	odm_slice_dst.y = 0;
2125 	odm_slice_dst.height = stream->timing.v_addressable +
2126 			stream->timing.v_border_bottom +
2127 			stream->timing.v_border_top;
2128 
2129 	return odm_slice_dst;
2130 }
2131 
2132 struct rect resource_get_odm_slice_src_rect(struct pipe_ctx *pipe_ctx)
2133 {
2134 	struct rect odm_slice_dst;
2135 	struct rect odm_slice_src;
2136 	struct pipe_ctx *opp_head = resource_get_opp_head(pipe_ctx);
2137 	struct output_pixel_processor *opp = opp_head->stream_res.opp;
2138 	uint32_t left_edge_extra_pixel_count;
2139 
2140 	odm_slice_dst = resource_get_odm_slice_dst_rect(opp_head);
2141 	odm_slice_src = odm_slice_dst;
2142 
2143 	if (opp && opp->funcs->opp_get_left_edge_extra_pixel_count)
2144 		left_edge_extra_pixel_count =
2145 				opp->funcs->opp_get_left_edge_extra_pixel_count(
2146 						opp, pipe_ctx->stream->timing.pixel_encoding,
2147 						resource_is_pipe_type(opp_head, OTG_MASTER));
2148 	else
2149 		left_edge_extra_pixel_count = 0;
2150 
2151 	odm_slice_src.x -= left_edge_extra_pixel_count;
2152 	odm_slice_src.width += left_edge_extra_pixel_count;
2153 
2154 	return odm_slice_src;
2155 }
2156 
2157 bool resource_is_pipe_topology_changed(const struct dc_state *state_a,
2158 		const struct dc_state *state_b)
2159 {
2160 	int i;
2161 	const struct pipe_ctx *pipe_a, *pipe_b;
2162 
2163 	if (state_a->stream_count != state_b->stream_count)
2164 		return true;
2165 
2166 	for (i = 0; i < MAX_PIPES; i++) {
2167 		pipe_a = &state_a->res_ctx.pipe_ctx[i];
2168 		pipe_b = &state_b->res_ctx.pipe_ctx[i];
2169 
2170 		if (pipe_a->stream && !pipe_b->stream)
2171 			return true;
2172 		else if (!pipe_a->stream && pipe_b->stream)
2173 			return true;
2174 
2175 		if (pipe_a->plane_state && !pipe_b->plane_state)
2176 			return true;
2177 		else if (!pipe_a->plane_state && pipe_b->plane_state)
2178 			return true;
2179 
2180 		if (pipe_a->bottom_pipe && pipe_b->bottom_pipe) {
2181 			if (pipe_a->bottom_pipe->pipe_idx != pipe_b->bottom_pipe->pipe_idx)
2182 				return true;
2183 			if ((pipe_a->bottom_pipe->plane_state == pipe_a->plane_state) &&
2184 					(pipe_b->bottom_pipe->plane_state != pipe_b->plane_state))
2185 				return true;
2186 			else if ((pipe_a->bottom_pipe->plane_state != pipe_a->plane_state) &&
2187 					(pipe_b->bottom_pipe->plane_state == pipe_b->plane_state))
2188 				return true;
2189 		} else if (pipe_a->bottom_pipe || pipe_b->bottom_pipe) {
2190 			return true;
2191 		}
2192 
2193 		if (pipe_a->next_odm_pipe && pipe_b->next_odm_pipe) {
2194 			if (pipe_a->next_odm_pipe->pipe_idx != pipe_b->next_odm_pipe->pipe_idx)
2195 				return true;
2196 		} else if (pipe_a->next_odm_pipe || pipe_b->next_odm_pipe) {
2197 			return true;
2198 		}
2199 	}
2200 	return false;
2201 }
2202 
2203 bool resource_is_odm_topology_changed(const struct pipe_ctx *otg_master_a,
2204 		const struct pipe_ctx *otg_master_b)
2205 {
2206 	const struct pipe_ctx *opp_head_a = otg_master_a;
2207 	const struct pipe_ctx *opp_head_b = otg_master_b;
2208 
2209 	if (!resource_is_pipe_type(otg_master_a, OTG_MASTER) ||
2210 			!resource_is_pipe_type(otg_master_b, OTG_MASTER))
2211 		return true;
2212 
2213 	while (opp_head_a && opp_head_b) {
2214 		if (opp_head_a->stream_res.opp != opp_head_b->stream_res.opp)
2215 			return true;
2216 		if ((opp_head_a->next_odm_pipe && !opp_head_b->next_odm_pipe) ||
2217 				(!opp_head_a->next_odm_pipe && opp_head_b->next_odm_pipe))
2218 			return true;
2219 		opp_head_a = opp_head_a->next_odm_pipe;
2220 		opp_head_b = opp_head_b->next_odm_pipe;
2221 	}
2222 
2223 	return false;
2224 }
2225 
2226 /*
2227  * Sample log:
2228  *    pipe topology update
2229  *  ________________________
2230  * | plane0  slice0  stream0|
2231  * |DPP0----OPP0----OTG0----| <--- case 0 (OTG master pipe with plane)
2232  * | plane1 |       |       |
2233  * |DPP1----|       |       | <--- case 5 (DPP pipe not in last slice)
2234  * | plane0  slice1 |       |
2235  * |DPP2----OPP2----|       | <--- case 2 (OPP head pipe with plane)
2236  * | plane1 |               |
2237  * |DPP3----|               | <--- case 4 (DPP pipe in last slice)
2238  * |         slice0  stream1|
2239  * |DPG4----OPP4----OTG4----| <--- case 1 (OTG master pipe without plane)
2240  * |         slice1 |       |
2241  * |DPG5----OPP5----|       | <--- case 3 (OPP head pipe without plane)
2242  * |________________________|
2243  */
2244 
2245 static void resource_log_pipe(struct dc *dc, struct pipe_ctx *pipe,
2246 		int stream_idx, int slice_idx, int plane_idx, int slice_count,
2247 		bool is_primary)
2248 {
2249 	DC_LOGGER_INIT(dc->ctx->logger);
2250 
2251 	if (slice_idx == 0 && plane_idx == 0 && is_primary) {
2252 		/* case 0 (OTG master pipe with plane) */
2253 		DC_LOG_DC(" | plane%d  slice%d  stream%d|",
2254 				plane_idx, slice_idx, stream_idx);
2255 		DC_LOG_DC(" |DPP%d----OPP%d----OTG%d----|",
2256 				pipe->plane_res.dpp->inst,
2257 				pipe->stream_res.opp->inst,
2258 				pipe->stream_res.tg->inst);
2259 	} else if (slice_idx == 0 && plane_idx == -1) {
2260 		/* case 1 (OTG master pipe without plane) */
2261 		DC_LOG_DC(" |         slice%d  stream%d|",
2262 				slice_idx, stream_idx);
2263 		DC_LOG_DC(" |DPG%d----OPP%d----OTG%d----|",
2264 				pipe->stream_res.opp->inst,
2265 				pipe->stream_res.opp->inst,
2266 				pipe->stream_res.tg->inst);
2267 	} else if (slice_idx != 0 && plane_idx == 0 && is_primary) {
2268 		/* case 2 (OPP head pipe with plane) */
2269 		DC_LOG_DC(" | plane%d  slice%d |       |",
2270 				plane_idx, slice_idx);
2271 		DC_LOG_DC(" |DPP%d----OPP%d----|       |",
2272 				pipe->plane_res.dpp->inst,
2273 				pipe->stream_res.opp->inst);
2274 	} else if (slice_idx != 0 && plane_idx == -1) {
2275 		/* case 3 (OPP head pipe without plane) */
2276 		DC_LOG_DC(" |         slice%d |       |", slice_idx);
2277 		DC_LOG_DC(" |DPG%d----OPP%d----|       |",
2278 				pipe->plane_res.dpp->inst,
2279 				pipe->stream_res.opp->inst);
2280 	} else if (slice_idx == slice_count - 1) {
2281 		/* case 4 (DPP pipe in last slice) */
2282 		DC_LOG_DC(" | plane%d |               |", plane_idx);
2283 		DC_LOG_DC(" |DPP%d----|               |",
2284 				pipe->plane_res.dpp->inst);
2285 	} else {
2286 		/* case 5 (DPP pipe not in last slice) */
2287 		DC_LOG_DC(" | plane%d |       |       |", plane_idx);
2288 		DC_LOG_DC(" |DPP%d----|       |       |",
2289 				pipe->plane_res.dpp->inst);
2290 	}
2291 }
2292 
2293 static void resource_log_pipe_for_stream(struct dc *dc, struct dc_state *state,
2294 		struct pipe_ctx *otg_master, int stream_idx)
2295 {
2296 	struct pipe_ctx *opp_heads[MAX_PIPES];
2297 	struct pipe_ctx *dpp_pipes[MAX_PIPES];
2298 
2299 	int slice_idx, dpp_idx, plane_idx, slice_count, dpp_count;
2300 	bool is_primary;
2301 	DC_LOGGER_INIT(dc->ctx->logger);
2302 
2303 	slice_count = resource_get_opp_heads_for_otg_master(otg_master,
2304 			&state->res_ctx, opp_heads);
2305 	for (slice_idx = 0; slice_idx < slice_count; slice_idx++) {
2306 		plane_idx = -1;
2307 		if (opp_heads[slice_idx]->plane_state) {
2308 			dpp_count = resource_get_dpp_pipes_for_opp_head(
2309 					opp_heads[slice_idx],
2310 					&state->res_ctx,
2311 					dpp_pipes);
2312 			for (dpp_idx = 0; dpp_idx < dpp_count; dpp_idx++) {
2313 				is_primary = !dpp_pipes[dpp_idx]->top_pipe ||
2314 						dpp_pipes[dpp_idx]->top_pipe->plane_state != dpp_pipes[dpp_idx]->plane_state;
2315 				if (is_primary)
2316 					plane_idx++;
2317 				resource_log_pipe(dc, dpp_pipes[dpp_idx],
2318 						stream_idx, slice_idx,
2319 						plane_idx, slice_count,
2320 						is_primary);
2321 			}
2322 		} else {
2323 			resource_log_pipe(dc, opp_heads[slice_idx],
2324 					stream_idx, slice_idx, plane_idx,
2325 					slice_count, true);
2326 		}
2327 
2328 	}
2329 }
2330 
2331 static int resource_stream_to_stream_idx(struct dc_state *state,
2332 		struct dc_stream_state *stream)
2333 {
2334 	int i, stream_idx = -1;
2335 
2336 	for (i = 0; i < state->stream_count; i++)
2337 		if (state->streams[i] == stream) {
2338 			stream_idx = i;
2339 			break;
2340 		}
2341 
2342 	/* never return negative array index */
2343 	if (stream_idx == -1) {
2344 		ASSERT(0);
2345 		return 0;
2346 	}
2347 
2348 	return stream_idx;
2349 }
2350 
2351 void resource_log_pipe_topology_update(struct dc *dc, struct dc_state *state)
2352 {
2353 	struct pipe_ctx *otg_master;
2354 	int stream_idx, phantom_stream_idx;
2355 	DC_LOGGER_INIT(dc->ctx->logger);
2356 
2357 	DC_LOG_DC("    pipe topology update");
2358 	DC_LOG_DC("  ________________________");
2359 	for (stream_idx = 0; stream_idx < state->stream_count; stream_idx++) {
2360 		if (state->streams[stream_idx]->is_phantom)
2361 			continue;
2362 
2363 		otg_master = resource_get_otg_master_for_stream(
2364 				&state->res_ctx, state->streams[stream_idx]);
2365 
2366 		if (!otg_master)
2367 			continue;
2368 
2369 		resource_log_pipe_for_stream(dc, state, otg_master, stream_idx);
2370 	}
2371 	if (state->phantom_stream_count > 0) {
2372 		DC_LOG_DC(" |    (phantom pipes)     |");
2373 		for (stream_idx = 0; stream_idx < state->stream_count; stream_idx++) {
2374 			if (state->stream_status[stream_idx].mall_stream_config.type != SUBVP_MAIN)
2375 				continue;
2376 
2377 			phantom_stream_idx = resource_stream_to_stream_idx(state,
2378 					state->stream_status[stream_idx].mall_stream_config.paired_stream);
2379 			otg_master = resource_get_otg_master_for_stream(
2380 					&state->res_ctx, state->streams[phantom_stream_idx]);
2381 			if (!otg_master)
2382 				continue;
2383 
2384 			resource_log_pipe_for_stream(dc, state, otg_master, stream_idx);
2385 		}
2386 	}
2387 	DC_LOG_DC(" |________________________|\n");
2388 }
2389 
2390 static struct pipe_ctx *get_tail_pipe(
2391 		struct pipe_ctx *head_pipe)
2392 {
2393 	struct pipe_ctx *tail_pipe = head_pipe->bottom_pipe;
2394 
2395 	while (tail_pipe) {
2396 		head_pipe = tail_pipe;
2397 		tail_pipe = tail_pipe->bottom_pipe;
2398 	}
2399 
2400 	return head_pipe;
2401 }
2402 
2403 static struct pipe_ctx *get_last_opp_head(
2404 		struct pipe_ctx *opp_head)
2405 {
2406 	ASSERT(resource_is_pipe_type(opp_head, OPP_HEAD));
2407 	while (opp_head->next_odm_pipe)
2408 		opp_head = opp_head->next_odm_pipe;
2409 	return opp_head;
2410 }
2411 
2412 static struct pipe_ctx *get_last_dpp_pipe_in_mpcc_combine(
2413 		struct pipe_ctx *dpp_pipe)
2414 {
2415 	ASSERT(resource_is_pipe_type(dpp_pipe, DPP_PIPE));
2416 	while (dpp_pipe->bottom_pipe &&
2417 			dpp_pipe->plane_state == dpp_pipe->bottom_pipe->plane_state)
2418 		dpp_pipe = dpp_pipe->bottom_pipe;
2419 	return dpp_pipe;
2420 }
2421 
2422 static bool update_pipe_params_after_odm_slice_count_change(
2423 		struct pipe_ctx *otg_master,
2424 		struct dc_state *context,
2425 		const struct resource_pool *pool)
2426 {
2427 	int i;
2428 	struct pipe_ctx *pipe;
2429 	bool result = true;
2430 
2431 	for (i = 0; i < pool->pipe_count && result; i++) {
2432 		pipe = &context->res_ctx.pipe_ctx[i];
2433 		if (pipe->stream == otg_master->stream && pipe->plane_state)
2434 			result = resource_build_scaling_params(pipe);
2435 	}
2436 
2437 	if (pool->funcs->build_pipe_pix_clk_params)
2438 		pool->funcs->build_pipe_pix_clk_params(otg_master);
2439 
2440 	resource_build_test_pattern_params(&context->res_ctx, otg_master);
2441 
2442 	return result;
2443 }
2444 
2445 static bool update_pipe_params_after_mpc_slice_count_change(
2446 		const struct dc_plane_state *plane,
2447 		struct dc_state *context,
2448 		const struct resource_pool *pool)
2449 {
2450 	int i;
2451 	struct pipe_ctx *pipe;
2452 	bool result = true;
2453 
2454 	for (i = 0; i < pool->pipe_count && result; i++) {
2455 		pipe = &context->res_ctx.pipe_ctx[i];
2456 		if (pipe->plane_state == plane)
2457 			result = resource_build_scaling_params(pipe);
2458 	}
2459 	return result;
2460 }
2461 
2462 static int acquire_first_split_pipe(
2463 		struct resource_context *res_ctx,
2464 		const struct resource_pool *pool,
2465 		struct dc_stream_state *stream)
2466 {
2467 	int i;
2468 
2469 	for (i = 0; i < pool->pipe_count; i++) {
2470 		struct pipe_ctx *split_pipe = &res_ctx->pipe_ctx[i];
2471 
2472 		if (split_pipe->top_pipe &&
2473 				split_pipe->top_pipe->plane_state == split_pipe->plane_state) {
2474 			split_pipe->top_pipe->bottom_pipe = split_pipe->bottom_pipe;
2475 			if (split_pipe->bottom_pipe)
2476 				split_pipe->bottom_pipe->top_pipe = split_pipe->top_pipe;
2477 
2478 			if (split_pipe->top_pipe->plane_state)
2479 				resource_build_scaling_params(split_pipe->top_pipe);
2480 
2481 			memset(split_pipe, 0, sizeof(*split_pipe));
2482 			split_pipe->stream_res.tg = pool->timing_generators[i];
2483 			split_pipe->plane_res.hubp = pool->hubps[i];
2484 			split_pipe->plane_res.ipp = pool->ipps[i];
2485 			split_pipe->plane_res.dpp = pool->dpps[i];
2486 			split_pipe->stream_res.opp = pool->opps[i];
2487 			split_pipe->plane_res.mpcc_inst = pool->dpps[i]->inst;
2488 			split_pipe->pipe_idx = i;
2489 
2490 			split_pipe->stream = stream;
2491 			return i;
2492 		}
2493 	}
2494 	return FREE_PIPE_INDEX_NOT_FOUND;
2495 }
2496 
2497 static void update_stream_engine_usage(
2498 		struct resource_context *res_ctx,
2499 		const struct resource_pool *pool,
2500 		struct stream_encoder *stream_enc,
2501 		bool acquired)
2502 {
2503 	int i;
2504 
2505 	for (i = 0; i < pool->stream_enc_count; i++) {
2506 		if (pool->stream_enc[i] == stream_enc)
2507 			res_ctx->is_stream_enc_acquired[i] = acquired;
2508 	}
2509 }
2510 
2511 static void update_hpo_dp_stream_engine_usage(
2512 		struct resource_context *res_ctx,
2513 		const struct resource_pool *pool,
2514 		struct hpo_dp_stream_encoder *hpo_dp_stream_enc,
2515 		bool acquired)
2516 {
2517 	int i;
2518 
2519 	for (i = 0; i < pool->hpo_dp_stream_enc_count; i++) {
2520 		if (pool->hpo_dp_stream_enc[i] == hpo_dp_stream_enc)
2521 			res_ctx->is_hpo_dp_stream_enc_acquired[i] = acquired;
2522 	}
2523 }
2524 
2525 static inline int find_acquired_hpo_dp_link_enc_for_link(
2526 		const struct resource_context *res_ctx,
2527 		const struct dc_link *link)
2528 {
2529 	int i;
2530 
2531 	for (i = 0; i < ARRAY_SIZE(res_ctx->hpo_dp_link_enc_to_link_idx); i++)
2532 		if (res_ctx->hpo_dp_link_enc_ref_cnts[i] > 0 &&
2533 				res_ctx->hpo_dp_link_enc_to_link_idx[i] == link->link_index)
2534 			return i;
2535 
2536 	return -1;
2537 }
2538 
2539 static inline int find_free_hpo_dp_link_enc(const struct resource_context *res_ctx,
2540 		const struct resource_pool *pool)
2541 {
2542 	int i;
2543 
2544 	for (i = 0; i < ARRAY_SIZE(res_ctx->hpo_dp_link_enc_ref_cnts); i++)
2545 		if (res_ctx->hpo_dp_link_enc_ref_cnts[i] == 0)
2546 			break;
2547 
2548 	return (i < ARRAY_SIZE(res_ctx->hpo_dp_link_enc_ref_cnts) &&
2549 			i < pool->hpo_dp_link_enc_count) ? i : -1;
2550 }
2551 
2552 static inline void acquire_hpo_dp_link_enc(
2553 		struct resource_context *res_ctx,
2554 		unsigned int link_index,
2555 		int enc_index)
2556 {
2557 	res_ctx->hpo_dp_link_enc_to_link_idx[enc_index] = link_index;
2558 	res_ctx->hpo_dp_link_enc_ref_cnts[enc_index] = 1;
2559 }
2560 
2561 static inline void retain_hpo_dp_link_enc(
2562 		struct resource_context *res_ctx,
2563 		int enc_index)
2564 {
2565 	res_ctx->hpo_dp_link_enc_ref_cnts[enc_index]++;
2566 }
2567 
2568 static inline void release_hpo_dp_link_enc(
2569 		struct resource_context *res_ctx,
2570 		int enc_index)
2571 {
2572 	ASSERT(res_ctx->hpo_dp_link_enc_ref_cnts[enc_index] > 0);
2573 	res_ctx->hpo_dp_link_enc_ref_cnts[enc_index]--;
2574 }
2575 
2576 static bool add_hpo_dp_link_enc_to_ctx(struct resource_context *res_ctx,
2577 		const struct resource_pool *pool,
2578 		struct pipe_ctx *pipe_ctx,
2579 		struct dc_stream_state *stream)
2580 {
2581 	int enc_index;
2582 
2583 	enc_index = find_acquired_hpo_dp_link_enc_for_link(res_ctx, stream->link);
2584 
2585 	if (enc_index >= 0) {
2586 		retain_hpo_dp_link_enc(res_ctx, enc_index);
2587 	} else {
2588 		enc_index = find_free_hpo_dp_link_enc(res_ctx, pool);
2589 		if (enc_index >= 0)
2590 			acquire_hpo_dp_link_enc(res_ctx, stream->link->link_index, enc_index);
2591 	}
2592 
2593 	if (enc_index >= 0)
2594 		pipe_ctx->link_res.hpo_dp_link_enc = pool->hpo_dp_link_enc[enc_index];
2595 
2596 	return pipe_ctx->link_res.hpo_dp_link_enc != NULL;
2597 }
2598 
2599 static void remove_hpo_dp_link_enc_from_ctx(struct resource_context *res_ctx,
2600 		struct pipe_ctx *pipe_ctx,
2601 		struct dc_stream_state *stream)
2602 {
2603 	int enc_index;
2604 
2605 	enc_index = find_acquired_hpo_dp_link_enc_for_link(res_ctx, stream->link);
2606 
2607 	if (enc_index >= 0) {
2608 		release_hpo_dp_link_enc(res_ctx, enc_index);
2609 		pipe_ctx->link_res.hpo_dp_link_enc = NULL;
2610 	}
2611 }
2612 
2613 static int get_num_of_free_pipes(const struct resource_pool *pool, const struct dc_state *context)
2614 {
2615 	int i;
2616 	int count = 0;
2617 
2618 	for (i = 0; i < pool->pipe_count; i++)
2619 		if (resource_is_pipe_type(&context->res_ctx.pipe_ctx[i], FREE_PIPE))
2620 			count++;
2621 	return count;
2622 }
2623 
2624 enum dc_status resource_add_otg_master_for_stream_output(struct dc_state *new_ctx,
2625 		const struct resource_pool *pool,
2626 		struct dc_stream_state *stream)
2627 {
2628 	struct dc *dc = stream->ctx->dc;
2629 
2630 	return dc->res_pool->funcs->add_stream_to_ctx(dc, new_ctx, stream);
2631 }
2632 
2633 void resource_remove_otg_master_for_stream_output(struct dc_state *context,
2634 		const struct resource_pool *pool,
2635 		struct dc_stream_state *stream)
2636 {
2637 	struct pipe_ctx *otg_master = resource_get_otg_master_for_stream(
2638 			&context->res_ctx, stream);
2639 
2640 	if (!otg_master)
2641 		return;
2642 
2643 	ASSERT(resource_get_odm_slice_count(otg_master) == 1);
2644 	ASSERT(otg_master->plane_state == NULL);
2645 	ASSERT(otg_master->stream_res.stream_enc);
2646 	update_stream_engine_usage(
2647 			&context->res_ctx,
2648 			pool,
2649 			otg_master->stream_res.stream_enc,
2650 			false);
2651 
2652 	if (stream->ctx->dc->link_srv->dp_is_128b_132b_signal(otg_master)) {
2653 		update_hpo_dp_stream_engine_usage(
2654 			&context->res_ctx, pool,
2655 			otg_master->stream_res.hpo_dp_stream_enc,
2656 			false);
2657 		remove_hpo_dp_link_enc_from_ctx(
2658 				&context->res_ctx, otg_master, stream);
2659 	}
2660 	if (otg_master->stream_res.audio)
2661 		update_audio_usage(
2662 			&context->res_ctx,
2663 			pool,
2664 			otg_master->stream_res.audio,
2665 			false);
2666 
2667 	resource_unreference_clock_source(&context->res_ctx,
2668 					  pool,
2669 					  otg_master->clock_source);
2670 
2671 	if (pool->funcs->remove_stream_from_ctx)
2672 		pool->funcs->remove_stream_from_ctx(
2673 				stream->ctx->dc, context, stream);
2674 	memset(otg_master, 0, sizeof(*otg_master));
2675 }
2676 
2677 /* For each OPP head of an OTG master, add top plane at plane index 0.
2678  *
2679  * In the following example, the stream has 2 ODM slices without a top plane.
2680  * By adding a plane 0 to OPP heads, we are configuring our hardware to render
2681  * plane 0 by using each OPP head's DPP.
2682  *
2683  *       Inter-pipe Relation (Before Adding Plane)
2684  *        __________________________________________________
2685  *       |PIPE IDX|   DPP PIPES   | OPP HEADS | OTG MASTER  |
2686  *       |        |               | slice 0   |             |
2687  *       |   0    |               |blank ----ODM----------- |
2688  *       |        |               | slice 1 | |             |
2689  *       |   1    |               |blank ---- |             |
2690  *       |________|_______________|___________|_____________|
2691  *
2692  *       Inter-pipe Relation (After Adding Plane)
2693  *        __________________________________________________
2694  *       |PIPE IDX|   DPP PIPES   | OPP HEADS | OTG MASTER  |
2695  *       |        |  plane 0      | slice 0   |             |
2696  *       |   0    | -------------------------ODM----------- |
2697  *       |        |  plane 0      | slice 1 | |             |
2698  *       |   1    | ------------------------- |             |
2699  *       |________|_______________|___________|_____________|
2700  */
2701 static bool add_plane_to_opp_head_pipes(struct pipe_ctx *otg_master_pipe,
2702 		struct dc_plane_state *plane_state,
2703 		struct dc_state *context)
2704 {
2705 	struct pipe_ctx *opp_head_pipe = otg_master_pipe;
2706 
2707 	while (opp_head_pipe) {
2708 		if (opp_head_pipe->plane_state) {
2709 			ASSERT(0);
2710 			return false;
2711 		}
2712 		opp_head_pipe->plane_state = plane_state;
2713 		opp_head_pipe = opp_head_pipe->next_odm_pipe;
2714 	}
2715 
2716 	return true;
2717 }
2718 
2719 /* For each OPP head of an OTG master, acquire a secondary DPP pipe and add
2720  * the plane. So the plane is added to all ODM slices associated with the OTG
2721  * master pipe in the bottom layer.
2722  *
2723  * In the following example, the stream has 2 ODM slices and a top plane 0.
2724  * By acquiring secondary DPP pipes and adding a plane 1, we are configuring our
2725  * hardware to render the plane 1 by acquiring a new pipe for each ODM slice and
2726  * render plane 1 using new pipes' DPP in the Z axis below plane 0.
2727  *
2728  *       Inter-pipe Relation (Before Adding Plane)
2729  *        __________________________________________________
2730  *       |PIPE IDX|   DPP PIPES   | OPP HEADS | OTG MASTER  |
2731  *       |        |  plane 0      | slice 0   |             |
2732  *       |   0    | -------------------------ODM----------- |
2733  *       |        |  plane 0      | slice 1 | |             |
2734  *       |   1    | ------------------------- |             |
2735  *       |________|_______________|___________|_____________|
2736  *
2737  *       Inter-pipe Relation (After Acquiring and Adding Plane)
2738  *        __________________________________________________
2739  *       |PIPE IDX|   DPP PIPES   | OPP HEADS | OTG MASTER  |
2740  *       |        |  plane 0      | slice 0   |             |
2741  *       |   0    | -------------MPC---------ODM----------- |
2742  *       |        |  plane 1    | |         | |             |
2743  *       |   2    | ------------- |         | |             |
2744  *       |        |  plane 0      | slice 1 | |             |
2745  *       |   1    | -------------MPC--------- |             |
2746  *       |        |  plane 1    | |           |             |
2747  *       |   3    | ------------- |           |             |
2748  *       |________|_______________|___________|_____________|
2749  */
2750 static bool acquire_secondary_dpp_pipes_and_add_plane(
2751 		struct pipe_ctx *otg_master_pipe,
2752 		struct dc_plane_state *plane_state,
2753 		struct dc_state *new_ctx,
2754 		struct dc_state *cur_ctx,
2755 		struct resource_pool *pool)
2756 {
2757 	struct pipe_ctx *sec_pipe, *tail_pipe;
2758 	struct pipe_ctx *opp_heads[MAX_PIPES];
2759 	int opp_head_count;
2760 	int i;
2761 
2762 	if (!pool->funcs->acquire_free_pipe_as_secondary_dpp_pipe) {
2763 		ASSERT(0);
2764 		return false;
2765 	}
2766 
2767 	opp_head_count = resource_get_opp_heads_for_otg_master(otg_master_pipe,
2768 			&new_ctx->res_ctx, opp_heads);
2769 	if (get_num_of_free_pipes(pool, new_ctx) < opp_head_count)
2770 		/* not enough free pipes */
2771 		return false;
2772 
2773 	for (i = 0; i < opp_head_count; i++) {
2774 		sec_pipe = pool->funcs->acquire_free_pipe_as_secondary_dpp_pipe(
2775 				cur_ctx,
2776 				new_ctx,
2777 				pool,
2778 				opp_heads[i]);
2779 		ASSERT(sec_pipe);
2780 		sec_pipe->plane_state = plane_state;
2781 
2782 		/* establish pipe relationship */
2783 		tail_pipe = get_tail_pipe(opp_heads[i]);
2784 		tail_pipe->bottom_pipe = sec_pipe;
2785 		sec_pipe->top_pipe = tail_pipe;
2786 		sec_pipe->bottom_pipe = NULL;
2787 		if (tail_pipe->prev_odm_pipe) {
2788 			ASSERT(tail_pipe->prev_odm_pipe->bottom_pipe);
2789 			sec_pipe->prev_odm_pipe = tail_pipe->prev_odm_pipe->bottom_pipe;
2790 			tail_pipe->prev_odm_pipe->bottom_pipe->next_odm_pipe = sec_pipe;
2791 		} else {
2792 			sec_pipe->prev_odm_pipe = NULL;
2793 		}
2794 	}
2795 	return true;
2796 }
2797 
2798 bool resource_append_dpp_pipes_for_plane_composition(
2799 		struct dc_state *new_ctx,
2800 		struct dc_state *cur_ctx,
2801 		struct resource_pool *pool,
2802 		struct pipe_ctx *otg_master_pipe,
2803 		struct dc_plane_state *plane_state)
2804 {
2805 	bool success;
2806 
2807 	if (otg_master_pipe->plane_state == NULL)
2808 		success = add_plane_to_opp_head_pipes(otg_master_pipe,
2809 				plane_state, new_ctx);
2810 	else
2811 		success = acquire_secondary_dpp_pipes_and_add_plane(
2812 				otg_master_pipe, plane_state, new_ctx,
2813 				cur_ctx, pool);
2814 	if (success) {
2815 		/* when appending a plane mpc slice count changes from 0 to 1 */
2816 		success = update_pipe_params_after_mpc_slice_count_change(
2817 				plane_state, new_ctx, pool);
2818 		if (!success)
2819 			resource_remove_dpp_pipes_for_plane_composition(new_ctx,
2820 					pool, plane_state);
2821 	}
2822 
2823 	return success;
2824 }
2825 
2826 void resource_remove_dpp_pipes_for_plane_composition(
2827 		struct dc_state *context,
2828 		const struct resource_pool *pool,
2829 		const struct dc_plane_state *plane_state)
2830 {
2831 	int i;
2832 
2833 	for (i = pool->pipe_count - 1; i >= 0; i--) {
2834 		struct pipe_ctx *pipe_ctx = &context->res_ctx.pipe_ctx[i];
2835 
2836 		if (pipe_ctx->plane_state == plane_state) {
2837 			if (pipe_ctx->top_pipe)
2838 				pipe_ctx->top_pipe->bottom_pipe = pipe_ctx->bottom_pipe;
2839 
2840 			/* Second condition is to avoid setting NULL to top pipe
2841 			 * of tail pipe making it look like head pipe in subsequent
2842 			 * deletes
2843 			 */
2844 			if (pipe_ctx->bottom_pipe && pipe_ctx->top_pipe)
2845 				pipe_ctx->bottom_pipe->top_pipe = pipe_ctx->top_pipe;
2846 
2847 			/*
2848 			 * For head pipe detach surfaces from pipe for tail
2849 			 * pipe just zero it out
2850 			 */
2851 			if (!pipe_ctx->top_pipe)
2852 				pipe_ctx->plane_state = NULL;
2853 			else
2854 				memset(pipe_ctx, 0, sizeof(*pipe_ctx));
2855 		}
2856 	}
2857 }
2858 
2859 /*
2860  * Increase ODM slice count by 1 by acquiring pipes and adding a new ODM slice
2861  * at the last index.
2862  * return - true if a new ODM slice is added and required pipes are acquired.
2863  * false if new_ctx is no longer a valid state after new ODM slice is added.
2864  *
2865  * This is achieved by duplicating MPC blending tree from previous ODM slice.
2866  * In the following example, we have a single MPC tree and 1 ODM slice 0. We
2867  * want to add a new odm slice by duplicating the MPC blending tree and add
2868  * ODM slice 1.
2869  *
2870  *       Inter-pipe Relation (Before Acquiring and Adding ODM Slice)
2871  *        __________________________________________________
2872  *       |PIPE IDX|   DPP PIPES   | OPP HEADS | OTG MASTER  |
2873  *       |        |  plane 0      | slice 0   |             |
2874  *       |   0    | -------------MPC---------ODM----------- |
2875  *       |        |  plane 1    | |           |             |
2876  *       |   1    | ------------- |           |             |
2877  *       |________|_______________|___________|_____________|
2878  *
2879  *       Inter-pipe Relation (After Acquiring and Adding ODM Slice)
2880  *        __________________________________________________
2881  *       |PIPE IDX|   DPP PIPES   | OPP HEADS | OTG MASTER  |
2882  *       |        |  plane 0      | slice 0   |             |
2883  *       |   0    | -------------MPC---------ODM----------- |
2884  *       |        |  plane 1    | |         | |             |
2885  *       |   1    | ------------- |         | |             |
2886  *       |        |  plane 0      | slice 1 | |             |
2887  *       |   2    | -------------MPC--------- |             |
2888  *       |        |  plane 1    | |           |             |
2889  *       |   3    | ------------- |           |             |
2890  *       |________|_______________|___________|_____________|
2891  */
2892 static bool acquire_pipes_and_add_odm_slice(
2893 		struct pipe_ctx *otg_master_pipe,
2894 		struct dc_state *new_ctx,
2895 		const struct dc_state *cur_ctx,
2896 		const struct resource_pool *pool)
2897 {
2898 	struct pipe_ctx *last_opp_head = get_last_opp_head(otg_master_pipe);
2899 	struct pipe_ctx *new_opp_head;
2900 	struct pipe_ctx *last_top_dpp_pipe, *last_bottom_dpp_pipe,
2901 			*new_top_dpp_pipe, *new_bottom_dpp_pipe;
2902 
2903 	if (!pool->funcs->acquire_free_pipe_as_secondary_opp_head) {
2904 		ASSERT(0);
2905 		return false;
2906 	}
2907 	new_opp_head = pool->funcs->acquire_free_pipe_as_secondary_opp_head(
2908 					cur_ctx, new_ctx, pool,
2909 					otg_master_pipe);
2910 	if (!new_opp_head)
2911 		return false;
2912 
2913 	last_opp_head->next_odm_pipe = new_opp_head;
2914 	new_opp_head->prev_odm_pipe = last_opp_head;
2915 	new_opp_head->next_odm_pipe = NULL;
2916 	new_opp_head->plane_state = last_opp_head->plane_state;
2917 	last_top_dpp_pipe = last_opp_head;
2918 	new_top_dpp_pipe = new_opp_head;
2919 
2920 	while (last_top_dpp_pipe->bottom_pipe) {
2921 		last_bottom_dpp_pipe = last_top_dpp_pipe->bottom_pipe;
2922 		new_bottom_dpp_pipe = pool->funcs->acquire_free_pipe_as_secondary_dpp_pipe(
2923 				cur_ctx, new_ctx, pool,
2924 				new_opp_head);
2925 		if (!new_bottom_dpp_pipe)
2926 			return false;
2927 
2928 		new_bottom_dpp_pipe->plane_state = last_bottom_dpp_pipe->plane_state;
2929 		new_top_dpp_pipe->bottom_pipe = new_bottom_dpp_pipe;
2930 		new_bottom_dpp_pipe->top_pipe = new_top_dpp_pipe;
2931 		last_bottom_dpp_pipe->next_odm_pipe = new_bottom_dpp_pipe;
2932 		new_bottom_dpp_pipe->prev_odm_pipe = last_bottom_dpp_pipe;
2933 		new_bottom_dpp_pipe->next_odm_pipe = NULL;
2934 		last_top_dpp_pipe = last_bottom_dpp_pipe;
2935 	}
2936 
2937 	return true;
2938 }
2939 
2940 /*
2941  * Decrease ODM slice count by 1 by releasing pipes and removing the ODM slice
2942  * at the last index.
2943  * return - true if the last ODM slice is removed and related pipes are
2944  * released. false if there is no removable ODM slice.
2945  *
2946  * In the following example, we have 2 MPC trees and ODM slice 0 and slice 1.
2947  * We want to remove the last ODM i.e slice 1. We are releasing secondary DPP
2948  * pipe 3 and OPP head pipe 2.
2949  *
2950  *       Inter-pipe Relation (Before Releasing and Removing ODM Slice)
2951  *        __________________________________________________
2952  *       |PIPE IDX|   DPP PIPES   | OPP HEADS | OTG MASTER  |
2953  *       |        |  plane 0      | slice 0   |             |
2954  *       |   0    | -------------MPC---------ODM----------- |
2955  *       |        |  plane 1    | |         | |             |
2956  *       |   1    | ------------- |         | |             |
2957  *       |        |  plane 0      | slice 1 | |             |
2958  *       |   2    | -------------MPC--------- |             |
2959  *       |        |  plane 1    | |           |             |
2960  *       |   3    | ------------- |           |             |
2961  *       |________|_______________|___________|_____________|
2962  *
2963  *       Inter-pipe Relation (After Releasing and Removing ODM Slice)
2964  *        __________________________________________________
2965  *       |PIPE IDX|   DPP PIPES   | OPP HEADS | OTG MASTER  |
2966  *       |        |  plane 0      | slice 0   |             |
2967  *       |   0    | -------------MPC---------ODM----------- |
2968  *       |        |  plane 1    | |           |             |
2969  *       |   1    | ------------- |           |             |
2970  *       |________|_______________|___________|_____________|
2971  */
2972 static bool release_pipes_and_remove_odm_slice(
2973 		struct pipe_ctx *otg_master_pipe,
2974 		struct dc_state *context,
2975 		const struct resource_pool *pool)
2976 {
2977 	struct pipe_ctx *last_opp_head = get_last_opp_head(otg_master_pipe);
2978 	struct pipe_ctx *tail_pipe = get_tail_pipe(last_opp_head);
2979 
2980 	if (!pool->funcs->release_pipe) {
2981 		ASSERT(0);
2982 		return false;
2983 	}
2984 
2985 	if (resource_is_pipe_type(last_opp_head, OTG_MASTER))
2986 		return false;
2987 
2988 	while (tail_pipe->top_pipe) {
2989 		tail_pipe->prev_odm_pipe->next_odm_pipe = NULL;
2990 		tail_pipe = tail_pipe->top_pipe;
2991 		pool->funcs->release_pipe(context, tail_pipe->bottom_pipe, pool);
2992 		tail_pipe->bottom_pipe = NULL;
2993 	}
2994 	last_opp_head->prev_odm_pipe->next_odm_pipe = NULL;
2995 	pool->funcs->release_pipe(context, last_opp_head, pool);
2996 
2997 	return true;
2998 }
2999 
3000 /*
3001  * Increase MPC slice count by 1 by acquiring a new DPP pipe and add it as the
3002  * last MPC slice of the plane associated with dpp_pipe.
3003  *
3004  * return - true if a new MPC slice is added and required pipes are acquired.
3005  * false if new_ctx is no longer a valid state after new MPC slice is added.
3006  *
3007  * In the following example, we add a new MPC slice for plane 0 into the
3008  * new_ctx. To do so we pass pipe 0 as dpp_pipe. The function acquires a new DPP
3009  * pipe 2 for plane 0 as the bottom most pipe for plane 0.
3010  *
3011  *       Inter-pipe Relation (Before Acquiring and Adding MPC Slice)
3012  *        __________________________________________________
3013  *       |PIPE IDX|   DPP PIPES   | OPP HEADS | OTG MASTER  |
3014  *       |        |  plane 0      |           |             |
3015  *       |   0    | -------------MPC----------------------- |
3016  *       |        |  plane 1    | |           |             |
3017  *       |   1    | ------------- |           |             |
3018  *       |________|_______________|___________|_____________|
3019  *
3020  *       Inter-pipe Relation (After Acquiring and Adding MPC Slice)
3021  *        __________________________________________________
3022  *       |PIPE IDX|   DPP PIPES   | OPP HEADS | OTG MASTER  |
3023  *       |        |  plane 0      |           |             |
3024  *       |   0    | -------------MPC----------------------- |
3025  *       |        |  plane 0    | |           |             |
3026  *       |   2    | ------------- |           |             |
3027  *       |        |  plane 1    | |           |             |
3028  *       |   1    | ------------- |           |             |
3029  *       |________|_______________|___________|_____________|
3030  */
3031 static bool acquire_dpp_pipe_and_add_mpc_slice(
3032 		struct pipe_ctx *dpp_pipe,
3033 		struct dc_state *new_ctx,
3034 		const struct dc_state *cur_ctx,
3035 		const struct resource_pool *pool)
3036 {
3037 	struct pipe_ctx *last_dpp_pipe =
3038 			get_last_dpp_pipe_in_mpcc_combine(dpp_pipe);
3039 	struct pipe_ctx *opp_head = resource_get_opp_head(dpp_pipe);
3040 	struct pipe_ctx *new_dpp_pipe;
3041 
3042 	if (!pool->funcs->acquire_free_pipe_as_secondary_dpp_pipe) {
3043 		ASSERT(0);
3044 		return false;
3045 	}
3046 	new_dpp_pipe = pool->funcs->acquire_free_pipe_as_secondary_dpp_pipe(
3047 			cur_ctx, new_ctx, pool, opp_head);
3048 	if (!new_dpp_pipe || resource_get_odm_slice_count(dpp_pipe) > 1)
3049 		return false;
3050 
3051 	new_dpp_pipe->bottom_pipe = last_dpp_pipe->bottom_pipe;
3052 	if (new_dpp_pipe->bottom_pipe)
3053 		new_dpp_pipe->bottom_pipe->top_pipe = new_dpp_pipe;
3054 	new_dpp_pipe->top_pipe = last_dpp_pipe;
3055 	last_dpp_pipe->bottom_pipe = new_dpp_pipe;
3056 	new_dpp_pipe->plane_state = last_dpp_pipe->plane_state;
3057 
3058 	return true;
3059 }
3060 
3061 /*
3062  * Reduce MPC slice count by 1 by releasing the bottom DPP pipe in MPCC combine
3063  * with dpp_pipe and removing last MPC slice of the plane associated with
3064  * dpp_pipe.
3065  *
3066  * return - true if the last MPC slice of the plane associated with dpp_pipe is
3067  * removed and last DPP pipe in MPCC combine with dpp_pipe is released.
3068  * false if there is no removable MPC slice.
3069  *
3070  * In the following example, we remove an MPC slice for plane 0 from the
3071  * context. To do so we pass pipe 0 as dpp_pipe. The function releases pipe 1 as
3072  * it is the last pipe for plane 0.
3073  *
3074  *       Inter-pipe Relation (Before Releasing and Removing MPC Slice)
3075  *        __________________________________________________
3076  *       |PIPE IDX|   DPP PIPES   | OPP HEADS | OTG MASTER  |
3077  *       |        |  plane 0      |           |             |
3078  *       |   0    | -------------MPC----------------------- |
3079  *       |        |  plane 0    | |           |             |
3080  *       |   1    | ------------- |           |             |
3081  *       |        |  plane 1    | |           |             |
3082  *       |   2    | ------------- |           |             |
3083  *       |________|_______________|___________|_____________|
3084  *
3085  *       Inter-pipe Relation (After Releasing and Removing MPC Slice)
3086  *        __________________________________________________
3087  *       |PIPE IDX|   DPP PIPES   | OPP HEADS | OTG MASTER  |
3088  *       |        |  plane 0      |           |             |
3089  *       |   0    | -------------MPC----------------------- |
3090  *       |        |  plane 1    | |           |             |
3091  *       |   2    | ------------- |           |             |
3092  *       |________|_______________|___________|_____________|
3093  */
3094 static bool release_dpp_pipe_and_remove_mpc_slice(
3095 		struct pipe_ctx *dpp_pipe,
3096 		struct dc_state *context,
3097 		const struct resource_pool *pool)
3098 {
3099 	struct pipe_ctx *last_dpp_pipe =
3100 			get_last_dpp_pipe_in_mpcc_combine(dpp_pipe);
3101 
3102 	if (!pool->funcs->release_pipe) {
3103 		ASSERT(0);
3104 		return false;
3105 	}
3106 
3107 	if (resource_is_pipe_type(last_dpp_pipe, OPP_HEAD) ||
3108 			resource_get_odm_slice_count(dpp_pipe) > 1)
3109 		return false;
3110 
3111 	last_dpp_pipe->top_pipe->bottom_pipe = last_dpp_pipe->bottom_pipe;
3112 	if (last_dpp_pipe->bottom_pipe)
3113 		last_dpp_pipe->bottom_pipe->top_pipe = last_dpp_pipe->top_pipe;
3114 	pool->funcs->release_pipe(context, last_dpp_pipe, pool);
3115 
3116 	return true;
3117 }
3118 
3119 bool resource_update_pipes_for_stream_with_slice_count(
3120 		struct dc_state *new_ctx,
3121 		const struct dc_state *cur_ctx,
3122 		const struct resource_pool *pool,
3123 		const struct dc_stream_state *stream,
3124 		int new_slice_count)
3125 {
3126 	int i;
3127 	struct pipe_ctx *otg_master = resource_get_otg_master_for_stream(
3128 			&new_ctx->res_ctx, stream);
3129 	int cur_slice_count;
3130 	bool result = true;
3131 
3132 	if (!otg_master)
3133 		return false;
3134 
3135 	cur_slice_count = resource_get_odm_slice_count(otg_master);
3136 
3137 	if (new_slice_count == cur_slice_count)
3138 		return result;
3139 
3140 	if (new_slice_count > cur_slice_count)
3141 		for (i = 0; i < new_slice_count - cur_slice_count && result; i++)
3142 			result = acquire_pipes_and_add_odm_slice(
3143 					otg_master, new_ctx, cur_ctx, pool);
3144 	else
3145 		for (i = 0; i < cur_slice_count - new_slice_count && result; i++)
3146 			result = release_pipes_and_remove_odm_slice(
3147 					otg_master, new_ctx, pool);
3148 	if (result)
3149 		result = update_pipe_params_after_odm_slice_count_change(
3150 				otg_master, new_ctx, pool);
3151 	return result;
3152 }
3153 
3154 bool resource_update_pipes_for_plane_with_slice_count(
3155 		struct dc_state *new_ctx,
3156 		const struct dc_state *cur_ctx,
3157 		const struct resource_pool *pool,
3158 		const struct dc_plane_state *plane,
3159 		int new_slice_count)
3160 {
3161 	int i;
3162 	int dpp_pipe_count;
3163 	int cur_slice_count;
3164 	struct pipe_ctx *dpp_pipes[MAX_PIPES] = {0};
3165 	bool result = true;
3166 
3167 	dpp_pipe_count = resource_get_dpp_pipes_for_plane(plane,
3168 			&new_ctx->res_ctx, dpp_pipes);
3169 	ASSERT(dpp_pipe_count > 0);
3170 	cur_slice_count = resource_get_mpc_slice_count(dpp_pipes[0]);
3171 
3172 	if (new_slice_count == cur_slice_count)
3173 		return result;
3174 
3175 	if (new_slice_count > cur_slice_count)
3176 		for (i = 0; i < new_slice_count - cur_slice_count && result; i++)
3177 			result = acquire_dpp_pipe_and_add_mpc_slice(
3178 					dpp_pipes[0], new_ctx, cur_ctx, pool);
3179 	else
3180 		for (i = 0; i < cur_slice_count - new_slice_count && result; i++)
3181 			result = release_dpp_pipe_and_remove_mpc_slice(
3182 					dpp_pipes[0], new_ctx, pool);
3183 	if (result)
3184 		result = update_pipe_params_after_mpc_slice_count_change(
3185 				dpp_pipes[0]->plane_state, new_ctx, pool);
3186 	return result;
3187 }
3188 
3189 bool dc_is_timing_changed(struct dc_stream_state *cur_stream,
3190 		       struct dc_stream_state *new_stream)
3191 {
3192 	if (cur_stream == NULL)
3193 		return true;
3194 
3195 	/* If output color space is changed, need to reprogram info frames */
3196 	if (cur_stream->output_color_space != new_stream->output_color_space)
3197 		return true;
3198 
3199 	return memcmp(
3200 		&cur_stream->timing,
3201 		&new_stream->timing,
3202 		sizeof(struct dc_crtc_timing)) != 0;
3203 }
3204 
3205 static bool are_stream_backends_same(
3206 	struct dc_stream_state *stream_a, struct dc_stream_state *stream_b)
3207 {
3208 	if (stream_a == stream_b)
3209 		return true;
3210 
3211 	if (stream_a == NULL || stream_b == NULL)
3212 		return false;
3213 
3214 	if (dc_is_timing_changed(stream_a, stream_b))
3215 		return false;
3216 
3217 	if (stream_a->signal != stream_b->signal)
3218 		return false;
3219 
3220 	if (stream_a->dpms_off != stream_b->dpms_off)
3221 		return false;
3222 
3223 	return true;
3224 }
3225 
3226 /*
3227  * dc_is_stream_unchanged() - Compare two stream states for equivalence.
3228  *
3229  * Checks if there a difference between the two states
3230  * that would require a mode change.
3231  *
3232  * Does not compare cursor position or attributes.
3233  */
3234 bool dc_is_stream_unchanged(
3235 	struct dc_stream_state *old_stream, struct dc_stream_state *stream)
3236 {
3237 	if (!old_stream || !stream)
3238 		return false;
3239 
3240 	if (!are_stream_backends_same(old_stream, stream))
3241 		return false;
3242 
3243 	if (old_stream->ignore_msa_timing_param != stream->ignore_msa_timing_param)
3244 		return false;
3245 
3246 	/*compare audio info*/
3247 	if (memcmp(&old_stream->audio_info, &stream->audio_info, sizeof(stream->audio_info)) != 0)
3248 		return false;
3249 
3250 	return true;
3251 }
3252 
3253 /*
3254  * dc_is_stream_scaling_unchanged() - Compare scaling rectangles of two streams.
3255  */
3256 bool dc_is_stream_scaling_unchanged(struct dc_stream_state *old_stream,
3257 				    struct dc_stream_state *stream)
3258 {
3259 	if (old_stream == stream)
3260 		return true;
3261 
3262 	if (old_stream == NULL || stream == NULL)
3263 		return false;
3264 
3265 	if (memcmp(&old_stream->src,
3266 			&stream->src,
3267 			sizeof(struct rect)) != 0)
3268 		return false;
3269 
3270 	if (memcmp(&old_stream->dst,
3271 			&stream->dst,
3272 			sizeof(struct rect)) != 0)
3273 		return false;
3274 
3275 	return true;
3276 }
3277 
3278 /* TODO: release audio object */
3279 void update_audio_usage(
3280 		struct resource_context *res_ctx,
3281 		const struct resource_pool *pool,
3282 		struct audio *audio,
3283 		bool acquired)
3284 {
3285 	int i;
3286 	for (i = 0; i < pool->audio_count; i++) {
3287 		if (pool->audios[i] == audio)
3288 			res_ctx->is_audio_acquired[i] = acquired;
3289 	}
3290 }
3291 
3292 static struct hpo_dp_stream_encoder *find_first_free_match_hpo_dp_stream_enc_for_link(
3293 		struct resource_context *res_ctx,
3294 		const struct resource_pool *pool,
3295 		struct dc_stream_state *stream)
3296 {
3297 	int i;
3298 
3299 	for (i = 0; i < pool->hpo_dp_stream_enc_count; i++) {
3300 		if (!res_ctx->is_hpo_dp_stream_enc_acquired[i] &&
3301 				pool->hpo_dp_stream_enc[i]) {
3302 
3303 			return pool->hpo_dp_stream_enc[i];
3304 		}
3305 	}
3306 
3307 	return NULL;
3308 }
3309 
3310 static struct audio *find_first_free_audio(
3311 		struct resource_context *res_ctx,
3312 		const struct resource_pool *pool,
3313 		enum engine_id id,
3314 		enum dce_version dc_version)
3315 {
3316 	int i, available_audio_count;
3317 
3318 	if (id == ENGINE_ID_UNKNOWN)
3319 		return NULL;
3320 
3321 	available_audio_count = pool->audio_count;
3322 
3323 	for (i = 0; i < available_audio_count; i++) {
3324 		if ((res_ctx->is_audio_acquired[i] == false) && (res_ctx->is_stream_enc_acquired[i] == true)) {
3325 			/*we have enough audio endpoint, find the matching inst*/
3326 			if (id != i)
3327 				continue;
3328 			return pool->audios[i];
3329 		}
3330 	}
3331 
3332 	/* use engine id to find free audio */
3333 	if ((id < available_audio_count) && (res_ctx->is_audio_acquired[id] == false)) {
3334 		return pool->audios[id];
3335 	}
3336 	/*not found the matching one, first come first serve*/
3337 	for (i = 0; i < available_audio_count; i++) {
3338 		if (res_ctx->is_audio_acquired[i] == false) {
3339 			return pool->audios[i];
3340 		}
3341 	}
3342 	return NULL;
3343 }
3344 
3345 static struct dc_stream_state *find_pll_sharable_stream(
3346 		struct dc_stream_state *stream_needs_pll,
3347 		struct dc_state *context)
3348 {
3349 	int i;
3350 
3351 	for (i = 0; i < context->stream_count; i++) {
3352 		struct dc_stream_state *stream_has_pll = context->streams[i];
3353 
3354 		/* We are looking for non dp, non virtual stream */
3355 		if (resource_are_streams_timing_synchronizable(
3356 			stream_needs_pll, stream_has_pll)
3357 			&& !dc_is_dp_signal(stream_has_pll->signal)
3358 			&& stream_has_pll->link->connector_signal
3359 			!= SIGNAL_TYPE_VIRTUAL)
3360 			return stream_has_pll;
3361 
3362 	}
3363 
3364 	return NULL;
3365 }
3366 
3367 static int get_norm_pix_clk(const struct dc_crtc_timing *timing)
3368 {
3369 	uint32_t pix_clk = timing->pix_clk_100hz;
3370 	uint32_t normalized_pix_clk = pix_clk;
3371 
3372 	if (timing->pixel_encoding == PIXEL_ENCODING_YCBCR420)
3373 		pix_clk /= 2;
3374 	if (timing->pixel_encoding != PIXEL_ENCODING_YCBCR422) {
3375 		switch (timing->display_color_depth) {
3376 		case COLOR_DEPTH_666:
3377 		case COLOR_DEPTH_888:
3378 			normalized_pix_clk = pix_clk;
3379 			break;
3380 		case COLOR_DEPTH_101010:
3381 			normalized_pix_clk = (pix_clk * 30) / 24;
3382 			break;
3383 		case COLOR_DEPTH_121212:
3384 			normalized_pix_clk = (pix_clk * 36) / 24;
3385 		break;
3386 		case COLOR_DEPTH_161616:
3387 			normalized_pix_clk = (pix_clk * 48) / 24;
3388 		break;
3389 		default:
3390 			ASSERT(0);
3391 		break;
3392 		}
3393 	}
3394 	return normalized_pix_clk;
3395 }
3396 
3397 static void calculate_phy_pix_clks(struct dc_stream_state *stream)
3398 {
3399 	/* update actual pixel clock on all streams */
3400 	if (dc_is_hdmi_signal(stream->signal))
3401 		stream->phy_pix_clk = get_norm_pix_clk(
3402 			&stream->timing) / 10;
3403 	else
3404 		stream->phy_pix_clk =
3405 			stream->timing.pix_clk_100hz / 10;
3406 
3407 	if (stream->timing.timing_3d_format == TIMING_3D_FORMAT_HW_FRAME_PACKING)
3408 		stream->phy_pix_clk *= 2;
3409 }
3410 
3411 static int acquire_resource_from_hw_enabled_state(
3412 		struct resource_context *res_ctx,
3413 		const struct resource_pool *pool,
3414 		struct dc_stream_state *stream)
3415 {
3416 	struct dc_link *link = stream->link;
3417 	unsigned int i, inst, tg_inst = 0;
3418 	uint32_t numPipes = 1;
3419 	uint32_t id_src[4] = {0};
3420 
3421 	/* Check for enabled DIG to identify enabled display */
3422 	if (!link->link_enc->funcs->is_dig_enabled(link->link_enc))
3423 		return -1;
3424 
3425 	inst = link->link_enc->funcs->get_dig_frontend(link->link_enc);
3426 
3427 	if (inst == ENGINE_ID_UNKNOWN)
3428 		return -1;
3429 
3430 	for (i = 0; i < pool->stream_enc_count; i++) {
3431 		if (pool->stream_enc[i]->id == inst) {
3432 			tg_inst = pool->stream_enc[i]->funcs->dig_source_otg(
3433 				pool->stream_enc[i]);
3434 			break;
3435 		}
3436 	}
3437 
3438 	// tg_inst not found
3439 	if (i == pool->stream_enc_count)
3440 		return -1;
3441 
3442 	if (tg_inst >= pool->timing_generator_count)
3443 		return -1;
3444 
3445 	if (!res_ctx->pipe_ctx[tg_inst].stream) {
3446 		struct pipe_ctx *pipe_ctx = &res_ctx->pipe_ctx[tg_inst];
3447 
3448 		pipe_ctx->stream_res.tg = pool->timing_generators[tg_inst];
3449 		id_src[0] = tg_inst;
3450 
3451 		if (pipe_ctx->stream_res.tg->funcs->get_optc_source)
3452 			pipe_ctx->stream_res.tg->funcs->get_optc_source(pipe_ctx->stream_res.tg,
3453 						&numPipes, &id_src[0], &id_src[1]);
3454 
3455 		if (id_src[0] == 0xf && id_src[1] == 0xf) {
3456 			id_src[0] = tg_inst;
3457 			numPipes = 1;
3458 		}
3459 
3460 		for (i = 0; i < numPipes; i++) {
3461 			//Check if src id invalid
3462 			if (id_src[i] == 0xf)
3463 				return -1;
3464 
3465 			pipe_ctx = &res_ctx->pipe_ctx[id_src[i]];
3466 
3467 			pipe_ctx->stream_res.tg = pool->timing_generators[tg_inst];
3468 			pipe_ctx->plane_res.mi = pool->mis[id_src[i]];
3469 			pipe_ctx->plane_res.hubp = pool->hubps[id_src[i]];
3470 			pipe_ctx->plane_res.ipp = pool->ipps[id_src[i]];
3471 			pipe_ctx->plane_res.xfm = pool->transforms[id_src[i]];
3472 			pipe_ctx->plane_res.dpp = pool->dpps[id_src[i]];
3473 			pipe_ctx->stream_res.opp = pool->opps[id_src[i]];
3474 
3475 			if (pool->dpps[id_src[i]]) {
3476 				pipe_ctx->plane_res.mpcc_inst = pool->dpps[id_src[i]]->inst;
3477 
3478 				if (pool->mpc->funcs->read_mpcc_state) {
3479 					struct mpcc_state s = {0};
3480 
3481 					pool->mpc->funcs->read_mpcc_state(pool->mpc, pipe_ctx->plane_res.mpcc_inst, &s);
3482 
3483 					if (s.dpp_id < MAX_MPCC)
3484 						pool->mpc->mpcc_array[pipe_ctx->plane_res.mpcc_inst].dpp_id =
3485 								s.dpp_id;
3486 
3487 					if (s.bot_mpcc_id < MAX_MPCC)
3488 						pool->mpc->mpcc_array[pipe_ctx->plane_res.mpcc_inst].mpcc_bot =
3489 								&pool->mpc->mpcc_array[s.bot_mpcc_id];
3490 
3491 					if (s.opp_id < MAX_OPP)
3492 						pipe_ctx->stream_res.opp->mpc_tree_params.opp_id = s.opp_id;
3493 				}
3494 			}
3495 			pipe_ctx->pipe_idx = id_src[i];
3496 
3497 			if (id_src[i] >= pool->timing_generator_count) {
3498 				id_src[i] = pool->timing_generator_count - 1;
3499 
3500 				pipe_ctx->stream_res.tg = pool->timing_generators[id_src[i]];
3501 				pipe_ctx->stream_res.opp = pool->opps[id_src[i]];
3502 			}
3503 
3504 			pipe_ctx->stream = stream;
3505 		}
3506 
3507 		if (numPipes == 2) {
3508 			stream->apply_boot_odm_mode = dm_odm_combine_policy_2to1;
3509 			res_ctx->pipe_ctx[id_src[0]].next_odm_pipe = &res_ctx->pipe_ctx[id_src[1]];
3510 			res_ctx->pipe_ctx[id_src[0]].prev_odm_pipe = NULL;
3511 			res_ctx->pipe_ctx[id_src[1]].next_odm_pipe = NULL;
3512 			res_ctx->pipe_ctx[id_src[1]].prev_odm_pipe = &res_ctx->pipe_ctx[id_src[0]];
3513 		} else
3514 			stream->apply_boot_odm_mode = dm_odm_combine_mode_disabled;
3515 
3516 		return id_src[0];
3517 	}
3518 
3519 	return -1;
3520 }
3521 
3522 static void mark_seamless_boot_stream(
3523 		const struct dc  *dc,
3524 		struct dc_stream_state *stream)
3525 {
3526 	struct dc_bios *dcb = dc->ctx->dc_bios;
3527 
3528 	if (dc->config.allow_seamless_boot_optimization &&
3529 			!dcb->funcs->is_accelerated_mode(dcb)) {
3530 		if (dc_validate_boot_timing(dc, stream->sink, &stream->timing))
3531 			stream->apply_seamless_boot_optimization = true;
3532 	}
3533 }
3534 
3535 /*
3536  * Acquire a pipe as OTG master and assign to the stream in new dc context.
3537  * return - true if OTG master pipe is acquired and new dc context is updated.
3538  * false if it fails to acquire an OTG master pipe for this stream.
3539  *
3540  * In the example below, we acquired pipe 0 as OTG master pipe for the stream.
3541  * After the function its Inter-pipe Relation is represented by the diagram
3542  * below.
3543  *
3544  *       Inter-pipe Relation
3545  *        __________________________________________________
3546  *       |PIPE IDX|   DPP PIPES   | OPP HEADS | OTG MASTER  |
3547  *       |        |               |           |             |
3548  *       |   0    |               |blank ------------------ |
3549  *       |________|_______________|___________|_____________|
3550  */
3551 static bool acquire_otg_master_pipe_for_stream(
3552 		const struct dc_state *cur_ctx,
3553 		struct dc_state *new_ctx,
3554 		const struct resource_pool *pool,
3555 		struct dc_stream_state *stream)
3556 {
3557 	/* TODO: Move this function to DCN specific resource file and acquire
3558 	 * DSC resource here. The reason is that the function should have the
3559 	 * same level of responsibility as when we acquire secondary OPP head.
3560 	 * We acquire DSC when we acquire secondary OPP head, so we should
3561 	 * acquire DSC when we acquire OTG master.
3562 	 */
3563 	int pipe_idx;
3564 	struct pipe_ctx *pipe_ctx = NULL;
3565 
3566 	/*
3567 	 * Upper level code is responsible to optimize unnecessary addition and
3568 	 * removal for unchanged streams. So unchanged stream will keep the same
3569 	 * OTG master instance allocated. When current stream is removed and a
3570 	 * new stream is added, we want to reuse the OTG instance made available
3571 	 * by the removed stream first. If not found, we try to avoid of using
3572 	 * any free pipes already used in current context as this could tear
3573 	 * down exiting ODM/MPC/MPO configuration unnecessarily.
3574 	 */
3575 
3576 	/*
3577 	 * Try to acquire the same OTG master already in use. This is not
3578 	 * optimal because resetting an enabled OTG master pipe for a new stream
3579 	 * requires an extra frame of wait. However there are test automation
3580 	 * and eDP assumptions that rely on reusing the same OTG master pipe
3581 	 * during mode change. We have to keep this logic as is for now.
3582 	 */
3583 	pipe_idx = recource_find_free_pipe_used_as_otg_master_in_cur_res_ctx(
3584 			&cur_ctx->res_ctx, &new_ctx->res_ctx, pool);
3585 	/*
3586 	 * Try to acquire a pipe not used in current resource context to avoid
3587 	 * pipe swapping.
3588 	 */
3589 	if (pipe_idx == FREE_PIPE_INDEX_NOT_FOUND)
3590 		pipe_idx = recource_find_free_pipe_not_used_in_cur_res_ctx(
3591 				&cur_ctx->res_ctx, &new_ctx->res_ctx, pool);
3592 	/*
3593 	 * If pipe swapping is unavoidable, try to acquire pipe used as
3594 	 * secondary DPP pipe in current state as we prioritize to support more
3595 	 * streams over supporting MPO planes.
3596 	 */
3597 	if (pipe_idx == FREE_PIPE_INDEX_NOT_FOUND)
3598 		pipe_idx = resource_find_free_pipe_used_as_cur_sec_dpp(
3599 				&cur_ctx->res_ctx, &new_ctx->res_ctx, pool);
3600 	if (pipe_idx == FREE_PIPE_INDEX_NOT_FOUND)
3601 		pipe_idx = resource_find_any_free_pipe(&new_ctx->res_ctx, pool);
3602 	if (pipe_idx != FREE_PIPE_INDEX_NOT_FOUND) {
3603 		pipe_ctx = &new_ctx->res_ctx.pipe_ctx[pipe_idx];
3604 		memset(pipe_ctx, 0, sizeof(*pipe_ctx));
3605 		pipe_ctx->pipe_idx = pipe_idx;
3606 		pipe_ctx->stream_res.tg = pool->timing_generators[pipe_idx];
3607 		pipe_ctx->plane_res.mi = pool->mis[pipe_idx];
3608 		pipe_ctx->plane_res.hubp = pool->hubps[pipe_idx];
3609 		pipe_ctx->plane_res.ipp = pool->ipps[pipe_idx];
3610 		pipe_ctx->plane_res.xfm = pool->transforms[pipe_idx];
3611 		pipe_ctx->plane_res.dpp = pool->dpps[pipe_idx];
3612 		pipe_ctx->stream_res.opp = pool->opps[pipe_idx];
3613 		if (pool->dpps[pipe_idx])
3614 			pipe_ctx->plane_res.mpcc_inst = pool->dpps[pipe_idx]->inst;
3615 
3616 		if (pipe_idx >= pool->timing_generator_count && pool->timing_generator_count != 0) {
3617 			int tg_inst = pool->timing_generator_count - 1;
3618 
3619 			pipe_ctx->stream_res.tg = pool->timing_generators[tg_inst];
3620 			pipe_ctx->stream_res.opp = pool->opps[tg_inst];
3621 		}
3622 
3623 		pipe_ctx->stream = stream;
3624 	} else {
3625 		pipe_idx = acquire_first_split_pipe(&new_ctx->res_ctx, pool, stream);
3626 	}
3627 
3628 	return pipe_idx != FREE_PIPE_INDEX_NOT_FOUND;
3629 }
3630 
3631 enum dc_status resource_map_pool_resources(
3632 		const struct dc  *dc,
3633 		struct dc_state *context,
3634 		struct dc_stream_state *stream)
3635 {
3636 	const struct resource_pool *pool = dc->res_pool;
3637 	int i;
3638 	struct dc_context *dc_ctx = dc->ctx;
3639 	struct pipe_ctx *pipe_ctx = NULL;
3640 	int pipe_idx = -1;
3641 	bool acquired = false;
3642 
3643 	calculate_phy_pix_clks(stream);
3644 
3645 	mark_seamless_boot_stream(dc, stream);
3646 
3647 	if (stream->apply_seamless_boot_optimization) {
3648 		pipe_idx = acquire_resource_from_hw_enabled_state(
3649 				&context->res_ctx,
3650 				pool,
3651 				stream);
3652 		if (pipe_idx < 0)
3653 			/* hw resource was assigned to other stream */
3654 			stream->apply_seamless_boot_optimization = false;
3655 		else
3656 			acquired = true;
3657 	}
3658 
3659 	if (!acquired)
3660 		/* acquire new resources */
3661 		acquired = acquire_otg_master_pipe_for_stream(dc->current_state,
3662 				context, pool, stream);
3663 
3664 	pipe_ctx = resource_get_otg_master_for_stream(&context->res_ctx, stream);
3665 
3666 	if (!pipe_ctx || pipe_ctx->stream_res.tg == NULL)
3667 		return DC_NO_CONTROLLER_RESOURCE;
3668 
3669 	pipe_ctx->stream_res.stream_enc =
3670 		dc->res_pool->funcs->find_first_free_match_stream_enc_for_link(
3671 			&context->res_ctx, pool, stream);
3672 
3673 	if (!pipe_ctx->stream_res.stream_enc)
3674 		return DC_NO_STREAM_ENC_RESOURCE;
3675 
3676 	update_stream_engine_usage(
3677 		&context->res_ctx, pool,
3678 		pipe_ctx->stream_res.stream_enc,
3679 		true);
3680 
3681 	/* Allocate DP HPO Stream Encoder based on signal, hw capabilities
3682 	 * and link settings
3683 	 */
3684 	if (dc_is_dp_signal(stream->signal) ||
3685 			dc_is_virtual_signal(stream->signal)) {
3686 		if (!dc->link_srv->dp_decide_link_settings(stream,
3687 				&pipe_ctx->link_config.dp_link_settings))
3688 			return DC_FAIL_DP_LINK_BANDWIDTH;
3689 		if (dc->link_srv->dp_get_encoding_format(
3690 				&pipe_ctx->link_config.dp_link_settings) == DP_128b_132b_ENCODING) {
3691 			pipe_ctx->stream_res.hpo_dp_stream_enc =
3692 					find_first_free_match_hpo_dp_stream_enc_for_link(
3693 							&context->res_ctx, pool, stream);
3694 
3695 			if (!pipe_ctx->stream_res.hpo_dp_stream_enc)
3696 				return DC_NO_STREAM_ENC_RESOURCE;
3697 
3698 			update_hpo_dp_stream_engine_usage(
3699 					&context->res_ctx, pool,
3700 					pipe_ctx->stream_res.hpo_dp_stream_enc,
3701 					true);
3702 			if (!add_hpo_dp_link_enc_to_ctx(&context->res_ctx, pool, pipe_ctx, stream))
3703 				return DC_NO_LINK_ENC_RESOURCE;
3704 		}
3705 	}
3706 
3707 	/* TODO: Add check if ASIC support and EDID audio */
3708 	if (!stream->converter_disable_audio &&
3709 	    dc_is_audio_capable_signal(pipe_ctx->stream->signal) &&
3710 	    stream->audio_info.mode_count && stream->audio_info.flags.all) {
3711 		pipe_ctx->stream_res.audio = find_first_free_audio(
3712 		&context->res_ctx, pool, pipe_ctx->stream_res.stream_enc->id, dc_ctx->dce_version);
3713 
3714 		/*
3715 		 * Audio assigned in order first come first get.
3716 		 * There are asics which has number of audio
3717 		 * resources less then number of pipes
3718 		 */
3719 		if (pipe_ctx->stream_res.audio)
3720 			update_audio_usage(&context->res_ctx, pool,
3721 					   pipe_ctx->stream_res.audio, true);
3722 	}
3723 
3724 	/* Add ABM to the resource if on EDP */
3725 	if (pipe_ctx->stream && dc_is_embedded_signal(pipe_ctx->stream->signal)) {
3726 		if (pool->abm)
3727 			pipe_ctx->stream_res.abm = pool->abm;
3728 		else
3729 			pipe_ctx->stream_res.abm = pool->multiple_abms[pipe_ctx->stream_res.tg->inst];
3730 	}
3731 
3732 	for (i = 0; i < context->stream_count; i++)
3733 		if (context->streams[i] == stream) {
3734 			context->stream_status[i].primary_otg_inst = pipe_ctx->stream_res.tg->inst;
3735 			context->stream_status[i].stream_enc_inst = pipe_ctx->stream_res.stream_enc->stream_enc_inst;
3736 			context->stream_status[i].audio_inst =
3737 				pipe_ctx->stream_res.audio ? pipe_ctx->stream_res.audio->inst : -1;
3738 
3739 			return DC_OK;
3740 		}
3741 
3742 	DC_ERROR("Stream %p not found in new ctx!\n", stream);
3743 	return DC_ERROR_UNEXPECTED;
3744 }
3745 
3746 bool dc_resource_is_dsc_encoding_supported(const struct dc *dc)
3747 {
3748 	if (dc->res_pool == NULL)
3749 		return false;
3750 
3751 	return dc->res_pool->res_cap->num_dsc > 0;
3752 }
3753 
3754 static bool planes_changed_for_existing_stream(struct dc_state *context,
3755 					       struct dc_stream_state *stream,
3756 					       const struct dc_validation_set set[],
3757 					       int set_count)
3758 {
3759 	int i, j;
3760 	struct dc_stream_status *stream_status = NULL;
3761 
3762 	for (i = 0; i < context->stream_count; i++) {
3763 		if (context->streams[i] == stream) {
3764 			stream_status = &context->stream_status[i];
3765 			break;
3766 		}
3767 	}
3768 
3769 	if (!stream_status) {
3770 		ASSERT(0);
3771 		return false;
3772 	}
3773 
3774 	for (i = 0; i < set_count; i++)
3775 		if (set[i].stream == stream)
3776 			break;
3777 
3778 	if (i == set_count)
3779 		ASSERT(0);
3780 
3781 	if (set[i].plane_count != stream_status->plane_count)
3782 		return true;
3783 
3784 	for (j = 0; j < set[i].plane_count; j++)
3785 		if (set[i].plane_states[j] != stream_status->plane_states[j])
3786 			return true;
3787 
3788 	return false;
3789 }
3790 
3791 static bool add_all_planes_for_stream(
3792 		const struct dc *dc,
3793 		struct dc_stream_state *stream,
3794 		const struct dc_validation_set set[],
3795 		int set_count,
3796 		struct dc_state *state)
3797 {
3798 	int i, j;
3799 
3800 	for (i = 0; i < set_count; i++)
3801 		if (set[i].stream == stream)
3802 			break;
3803 
3804 	if (i == set_count) {
3805 		dm_error("Stream %p not found in set!\n", stream);
3806 		return false;
3807 	}
3808 
3809 	for (j = 0; j < set[i].plane_count; j++)
3810 		if (!dc_state_add_plane(dc, stream, set[i].plane_states[j], state))
3811 			return false;
3812 
3813 	return true;
3814 }
3815 
3816 /**
3817  * dc_validate_with_context - Validate and update the potential new stream in the context object
3818  *
3819  * @dc: Used to get the current state status
3820  * @set: An array of dc_validation_set with all the current streams reference
3821  * @set_count: Total of streams
3822  * @context: New context
3823  * @fast_validate: Enable or disable fast validation
3824  *
3825  * This function updates the potential new stream in the context object. It
3826  * creates multiple lists for the add, remove, and unchanged streams. In
3827  * particular, if the unchanged streams have a plane that changed, it is
3828  * necessary to remove all planes from the unchanged streams. In summary, this
3829  * function is responsible for validating the new context.
3830  *
3831  * Return:
3832  * In case of success, return DC_OK (1), otherwise, return a DC error.
3833  */
3834 enum dc_status dc_validate_with_context(struct dc *dc,
3835 					const struct dc_validation_set set[],
3836 					int set_count,
3837 					struct dc_state *context,
3838 					bool fast_validate)
3839 {
3840 	struct dc_stream_state *unchanged_streams[MAX_PIPES] = { 0 };
3841 	struct dc_stream_state *del_streams[MAX_PIPES] = { 0 };
3842 	struct dc_stream_state *add_streams[MAX_PIPES] = { 0 };
3843 	int old_stream_count = context->stream_count;
3844 	enum dc_status res = DC_ERROR_UNEXPECTED;
3845 	int unchanged_streams_count = 0;
3846 	int del_streams_count = 0;
3847 	int add_streams_count = 0;
3848 	bool found = false;
3849 	int i, j, k;
3850 
3851 	DC_LOGGER_INIT(dc->ctx->logger);
3852 
3853 	/* First build a list of streams to be remove from current context */
3854 	for (i = 0; i < old_stream_count; i++) {
3855 		struct dc_stream_state *stream = context->streams[i];
3856 
3857 		for (j = 0; j < set_count; j++) {
3858 			if (stream == set[j].stream) {
3859 				found = true;
3860 				break;
3861 			}
3862 		}
3863 
3864 		if (!found)
3865 			del_streams[del_streams_count++] = stream;
3866 
3867 		found = false;
3868 	}
3869 
3870 	/* Second, build a list of new streams */
3871 	for (i = 0; i < set_count; i++) {
3872 		struct dc_stream_state *stream = set[i].stream;
3873 
3874 		for (j = 0; j < old_stream_count; j++) {
3875 			if (stream == context->streams[j]) {
3876 				found = true;
3877 				break;
3878 			}
3879 		}
3880 
3881 		if (!found)
3882 			add_streams[add_streams_count++] = stream;
3883 
3884 		found = false;
3885 	}
3886 
3887 	/* Build a list of unchanged streams which is necessary for handling
3888 	 * planes change such as added, removed, and updated.
3889 	 */
3890 	for (i = 0; i < set_count; i++) {
3891 		/* Check if stream is part of the delete list */
3892 		for (j = 0; j < del_streams_count; j++) {
3893 			if (set[i].stream == del_streams[j]) {
3894 				found = true;
3895 				break;
3896 			}
3897 		}
3898 
3899 		if (!found) {
3900 			/* Check if stream is part of the add list */
3901 			for (j = 0; j < add_streams_count; j++) {
3902 				if (set[i].stream == add_streams[j]) {
3903 					found = true;
3904 					break;
3905 				}
3906 			}
3907 		}
3908 
3909 		if (!found)
3910 			unchanged_streams[unchanged_streams_count++] = set[i].stream;
3911 
3912 		found = false;
3913 	}
3914 
3915 	/* Remove all planes for unchanged streams if planes changed */
3916 	for (i = 0; i < unchanged_streams_count; i++) {
3917 		if (planes_changed_for_existing_stream(context,
3918 						       unchanged_streams[i],
3919 						       set,
3920 						       set_count)) {
3921 
3922 			if (!dc_state_rem_all_planes_for_stream(dc,
3923 							  unchanged_streams[i],
3924 							  context)) {
3925 				res = DC_FAIL_DETACH_SURFACES;
3926 				goto fail;
3927 			}
3928 		}
3929 	}
3930 
3931 	/* Remove all planes for removed streams and then remove the streams */
3932 	for (i = 0; i < del_streams_count; i++) {
3933 		/* Need to cpy the dwb data from the old stream in order to efc to work */
3934 		if (del_streams[i]->num_wb_info > 0) {
3935 			for (j = 0; j < add_streams_count; j++) {
3936 				if (del_streams[i]->sink == add_streams[j]->sink) {
3937 					add_streams[j]->num_wb_info = del_streams[i]->num_wb_info;
3938 					for (k = 0; k < del_streams[i]->num_wb_info; k++)
3939 						add_streams[j]->writeback_info[k] = del_streams[i]->writeback_info[k];
3940 				}
3941 			}
3942 		}
3943 
3944 		if (dc_state_get_stream_subvp_type(context, del_streams[i]) == SUBVP_PHANTOM) {
3945 			/* remove phantoms specifically */
3946 			if (!dc_state_rem_all_phantom_planes_for_stream(dc, del_streams[i], context, true)) {
3947 				res = DC_FAIL_DETACH_SURFACES;
3948 				goto fail;
3949 			}
3950 
3951 			res = dc_state_remove_phantom_stream(dc, context, del_streams[i]);
3952 			dc_state_release_phantom_stream(dc, context, del_streams[i]);
3953 		} else {
3954 			if (!dc_state_rem_all_planes_for_stream(dc, del_streams[i], context)) {
3955 				res = DC_FAIL_DETACH_SURFACES;
3956 				goto fail;
3957 			}
3958 
3959 			res = dc_state_remove_stream(dc, context, del_streams[i]);
3960 		}
3961 
3962 		if (res != DC_OK)
3963 			goto fail;
3964 	}
3965 
3966 	/* Swap seamless boot stream to pipe 0 (if needed) to ensure pipe_ctx
3967 	 * matches. This may change in the future if seamless_boot_stream can be
3968 	 * multiple.
3969 	 */
3970 	for (i = 0; i < add_streams_count; i++) {
3971 		mark_seamless_boot_stream(dc, add_streams[i]);
3972 		if (add_streams[i]->apply_seamless_boot_optimization && i != 0) {
3973 			struct dc_stream_state *temp = add_streams[0];
3974 
3975 			add_streams[0] = add_streams[i];
3976 			add_streams[i] = temp;
3977 			break;
3978 		}
3979 	}
3980 
3981 	/* Add new streams and then add all planes for the new stream */
3982 	for (i = 0; i < add_streams_count; i++) {
3983 		calculate_phy_pix_clks(add_streams[i]);
3984 		res = dc_state_add_stream(dc, context, add_streams[i]);
3985 		if (res != DC_OK)
3986 			goto fail;
3987 
3988 		if (!add_all_planes_for_stream(dc, add_streams[i], set, set_count, context)) {
3989 			res = DC_FAIL_ATTACH_SURFACES;
3990 			goto fail;
3991 		}
3992 	}
3993 
3994 	/* Add all planes for unchanged streams if planes changed */
3995 	for (i = 0; i < unchanged_streams_count; i++) {
3996 		if (planes_changed_for_existing_stream(context,
3997 						       unchanged_streams[i],
3998 						       set,
3999 						       set_count)) {
4000 			if (!add_all_planes_for_stream(dc, unchanged_streams[i], set, set_count, context)) {
4001 				res = DC_FAIL_ATTACH_SURFACES;
4002 				goto fail;
4003 			}
4004 		}
4005 	}
4006 
4007 	res = dc_validate_global_state(dc, context, fast_validate);
4008 
4009 	/* calculate pixel rate divider after deciding pxiel clock & odm combine  */
4010 	if ((dc->hwss.calculate_pix_rate_divider) && (res == DC_OK)) {
4011 		for (i = 0; i < add_streams_count; i++)
4012 			dc->hwss.calculate_pix_rate_divider(dc, context, add_streams[i]);
4013 	}
4014 
4015 fail:
4016 	if (res != DC_OK)
4017 		DC_LOG_WARNING("%s:resource validation failed, dc_status:%d\n",
4018 			       __func__,
4019 			       res);
4020 
4021 	return res;
4022 }
4023 
4024 /**
4025  * dc_validate_global_state() - Determine if hardware can support a given state
4026  *
4027  * @dc: dc struct for this driver
4028  * @new_ctx: state to be validated
4029  * @fast_validate: set to true if only yes/no to support matters
4030  *
4031  * Checks hardware resource availability and bandwidth requirement.
4032  *
4033  * Return:
4034  * DC_OK if the result can be programmed. Otherwise, an error code.
4035  */
4036 enum dc_status dc_validate_global_state(
4037 		struct dc *dc,
4038 		struct dc_state *new_ctx,
4039 		bool fast_validate)
4040 {
4041 	enum dc_status result = DC_ERROR_UNEXPECTED;
4042 	int i, j;
4043 
4044 	if (!new_ctx)
4045 		return DC_ERROR_UNEXPECTED;
4046 
4047 	if (dc->res_pool->funcs->validate_global) {
4048 		result = dc->res_pool->funcs->validate_global(dc, new_ctx);
4049 		if (result != DC_OK)
4050 			return result;
4051 	}
4052 
4053 	for (i = 0; i < new_ctx->stream_count; i++) {
4054 		struct dc_stream_state *stream = new_ctx->streams[i];
4055 
4056 		for (j = 0; j < dc->res_pool->pipe_count; j++) {
4057 			struct pipe_ctx *pipe_ctx = &new_ctx->res_ctx.pipe_ctx[j];
4058 
4059 			if (pipe_ctx->stream != stream)
4060 				continue;
4061 
4062 			if (dc->res_pool->funcs->patch_unknown_plane_state &&
4063 					pipe_ctx->plane_state &&
4064 					pipe_ctx->plane_state->tiling_info.gfx9.swizzle == DC_SW_UNKNOWN) {
4065 				result = dc->res_pool->funcs->patch_unknown_plane_state(pipe_ctx->plane_state);
4066 				if (result != DC_OK)
4067 					return result;
4068 			}
4069 
4070 			/* Switch to dp clock source only if there is
4071 			 * no non dp stream that shares the same timing
4072 			 * with the dp stream.
4073 			 */
4074 			if (dc_is_dp_signal(pipe_ctx->stream->signal) &&
4075 				!find_pll_sharable_stream(stream, new_ctx)) {
4076 
4077 				resource_unreference_clock_source(
4078 						&new_ctx->res_ctx,
4079 						dc->res_pool,
4080 						pipe_ctx->clock_source);
4081 
4082 				pipe_ctx->clock_source = dc->res_pool->dp_clock_source;
4083 				resource_reference_clock_source(
4084 						&new_ctx->res_ctx,
4085 						dc->res_pool,
4086 						 pipe_ctx->clock_source);
4087 			}
4088 		}
4089 	}
4090 
4091 	result = resource_build_scaling_params_for_context(dc, new_ctx);
4092 
4093 	if (result == DC_OK)
4094 		if (!dc->res_pool->funcs->validate_bandwidth(dc, new_ctx, fast_validate))
4095 			result = DC_FAIL_BANDWIDTH_VALIDATE;
4096 
4097 	/*
4098 	 * Only update link encoder to stream assignment after bandwidth validation passed.
4099 	 * TODO: Split out assignment and validation.
4100 	 */
4101 	if (result == DC_OK && dc->res_pool->funcs->link_encs_assign && fast_validate == false)
4102 		dc->res_pool->funcs->link_encs_assign(
4103 			dc, new_ctx, new_ctx->streams, new_ctx->stream_count);
4104 
4105 	return result;
4106 }
4107 
4108 static void patch_gamut_packet_checksum(
4109 		struct dc_info_packet *gamut_packet)
4110 {
4111 	/* For gamut we recalc checksum */
4112 	if (gamut_packet->valid) {
4113 		uint8_t chk_sum = 0;
4114 		uint8_t *ptr;
4115 		uint8_t i;
4116 
4117 		/*start of the Gamut data. */
4118 		ptr = &gamut_packet->sb[3];
4119 
4120 		for (i = 0; i <= gamut_packet->sb[1]; i++)
4121 			chk_sum += ptr[i];
4122 
4123 		gamut_packet->sb[2] = (uint8_t) (0x100 - chk_sum);
4124 	}
4125 }
4126 
4127 static void set_avi_info_frame(
4128 		struct dc_info_packet *info_packet,
4129 		struct pipe_ctx *pipe_ctx)
4130 {
4131 	struct dc_stream_state *stream = pipe_ctx->stream;
4132 	enum dc_color_space color_space = COLOR_SPACE_UNKNOWN;
4133 	uint32_t pixel_encoding = 0;
4134 	enum scanning_type scan_type = SCANNING_TYPE_NODATA;
4135 	enum dc_aspect_ratio aspect = ASPECT_RATIO_NO_DATA;
4136 	uint8_t *check_sum = NULL;
4137 	uint8_t byte_index = 0;
4138 	union hdmi_info_packet hdmi_info;
4139 	unsigned int vic = pipe_ctx->stream->timing.vic;
4140 	unsigned int rid = pipe_ctx->stream->timing.rid;
4141 	unsigned int fr_ind = pipe_ctx->stream->timing.fr_index;
4142 	enum dc_timing_3d_format format;
4143 
4144 	memset(&hdmi_info, 0, sizeof(union hdmi_info_packet));
4145 
4146 	color_space = pipe_ctx->stream->output_color_space;
4147 	if (color_space == COLOR_SPACE_UNKNOWN)
4148 		color_space = (stream->timing.pixel_encoding == PIXEL_ENCODING_RGB) ?
4149 			COLOR_SPACE_SRGB:COLOR_SPACE_YCBCR709;
4150 
4151 	/* Initialize header */
4152 	hdmi_info.bits.header.info_frame_type = HDMI_INFOFRAME_TYPE_AVI;
4153 	/* InfoFrameVersion_3 is defined by CEA861F (Section 6.4), but shall
4154 	* not be used in HDMI 2.0 (Section 10.1) */
4155 	hdmi_info.bits.header.version = 2;
4156 	hdmi_info.bits.header.length = HDMI_AVI_INFOFRAME_SIZE;
4157 
4158 	/*
4159 	 * IDO-defined (Y2,Y1,Y0 = 1,1,1) shall not be used by devices built
4160 	 * according to HDMI 2.0 spec (Section 10.1)
4161 	 */
4162 
4163 	switch (stream->timing.pixel_encoding) {
4164 	case PIXEL_ENCODING_YCBCR422:
4165 		pixel_encoding = 1;
4166 		break;
4167 
4168 	case PIXEL_ENCODING_YCBCR444:
4169 		pixel_encoding = 2;
4170 		break;
4171 	case PIXEL_ENCODING_YCBCR420:
4172 		pixel_encoding = 3;
4173 		break;
4174 
4175 	case PIXEL_ENCODING_RGB:
4176 	default:
4177 		pixel_encoding = 0;
4178 	}
4179 
4180 	/* Y0_Y1_Y2 : The pixel encoding */
4181 	/* H14b AVI InfoFrame has extension on Y-field from 2 bits to 3 bits */
4182 	hdmi_info.bits.Y0_Y1_Y2 = pixel_encoding;
4183 
4184 	/* A0 = 1 Active Format Information valid */
4185 	hdmi_info.bits.A0 = ACTIVE_FORMAT_VALID;
4186 
4187 	/* B0, B1 = 3; Bar info data is valid */
4188 	hdmi_info.bits.B0_B1 = BAR_INFO_BOTH_VALID;
4189 
4190 	hdmi_info.bits.SC0_SC1 = PICTURE_SCALING_UNIFORM;
4191 
4192 	/* S0, S1 : Underscan / Overscan */
4193 	/* TODO: un-hardcode scan type */
4194 	scan_type = SCANNING_TYPE_UNDERSCAN;
4195 	hdmi_info.bits.S0_S1 = scan_type;
4196 
4197 	/* C0, C1 : Colorimetry */
4198 	switch (color_space) {
4199 	case COLOR_SPACE_YCBCR709:
4200 	case COLOR_SPACE_YCBCR709_LIMITED:
4201 		hdmi_info.bits.C0_C1 = COLORIMETRY_ITU709;
4202 		break;
4203 	case COLOR_SPACE_YCBCR601:
4204 	case COLOR_SPACE_YCBCR601_LIMITED:
4205 		hdmi_info.bits.C0_C1 = COLORIMETRY_ITU601;
4206 		break;
4207 	case COLOR_SPACE_2020_RGB_FULLRANGE:
4208 	case COLOR_SPACE_2020_RGB_LIMITEDRANGE:
4209 	case COLOR_SPACE_2020_YCBCR:
4210 		hdmi_info.bits.EC0_EC2 = COLORIMETRYEX_BT2020RGBYCBCR;
4211 		hdmi_info.bits.C0_C1   = COLORIMETRY_EXTENDED;
4212 		break;
4213 	case COLOR_SPACE_ADOBERGB:
4214 		hdmi_info.bits.EC0_EC2 = COLORIMETRYEX_ADOBERGB;
4215 		hdmi_info.bits.C0_C1   = COLORIMETRY_EXTENDED;
4216 		break;
4217 	case COLOR_SPACE_SRGB:
4218 	default:
4219 		hdmi_info.bits.C0_C1 = COLORIMETRY_NO_DATA;
4220 		break;
4221 	}
4222 
4223 	if (pixel_encoding && color_space == COLOR_SPACE_2020_YCBCR &&
4224 			stream->out_transfer_func.tf == TRANSFER_FUNCTION_GAMMA22) {
4225 		hdmi_info.bits.EC0_EC2 = 0;
4226 		hdmi_info.bits.C0_C1 = COLORIMETRY_ITU709;
4227 	}
4228 
4229 	/* TODO: un-hardcode aspect ratio */
4230 	aspect = stream->timing.aspect_ratio;
4231 
4232 	switch (aspect) {
4233 	case ASPECT_RATIO_4_3:
4234 	case ASPECT_RATIO_16_9:
4235 		hdmi_info.bits.M0_M1 = aspect;
4236 		break;
4237 
4238 	case ASPECT_RATIO_NO_DATA:
4239 	case ASPECT_RATIO_64_27:
4240 	case ASPECT_RATIO_256_135:
4241 	default:
4242 		hdmi_info.bits.M0_M1 = 0;
4243 	}
4244 
4245 	/* Active Format Aspect ratio - same as Picture Aspect Ratio. */
4246 	hdmi_info.bits.R0_R3 = ACTIVE_FORMAT_ASPECT_RATIO_SAME_AS_PICTURE;
4247 
4248 	switch (stream->content_type) {
4249 	case DISPLAY_CONTENT_TYPE_NO_DATA:
4250 		hdmi_info.bits.CN0_CN1 = 0;
4251 		hdmi_info.bits.ITC = 1;
4252 		break;
4253 	case DISPLAY_CONTENT_TYPE_GRAPHICS:
4254 		hdmi_info.bits.CN0_CN1 = 0;
4255 		hdmi_info.bits.ITC = 1;
4256 		break;
4257 	case DISPLAY_CONTENT_TYPE_PHOTO:
4258 		hdmi_info.bits.CN0_CN1 = 1;
4259 		hdmi_info.bits.ITC = 1;
4260 		break;
4261 	case DISPLAY_CONTENT_TYPE_CINEMA:
4262 		hdmi_info.bits.CN0_CN1 = 2;
4263 		hdmi_info.bits.ITC = 1;
4264 		break;
4265 	case DISPLAY_CONTENT_TYPE_GAME:
4266 		hdmi_info.bits.CN0_CN1 = 3;
4267 		hdmi_info.bits.ITC = 1;
4268 		break;
4269 	}
4270 
4271 	if (stream->qs_bit == 1) {
4272 		if (color_space == COLOR_SPACE_SRGB ||
4273 			color_space == COLOR_SPACE_2020_RGB_FULLRANGE)
4274 			hdmi_info.bits.Q0_Q1   = RGB_QUANTIZATION_FULL_RANGE;
4275 		else if (color_space == COLOR_SPACE_SRGB_LIMITED ||
4276 					color_space == COLOR_SPACE_2020_RGB_LIMITEDRANGE)
4277 			hdmi_info.bits.Q0_Q1   = RGB_QUANTIZATION_LIMITED_RANGE;
4278 		else
4279 			hdmi_info.bits.Q0_Q1   = RGB_QUANTIZATION_DEFAULT_RANGE;
4280 	} else
4281 		hdmi_info.bits.Q0_Q1   = RGB_QUANTIZATION_DEFAULT_RANGE;
4282 
4283 	/* TODO : We should handle YCC quantization */
4284 	/* but we do not have matrix calculation */
4285 	hdmi_info.bits.YQ0_YQ1 = YYC_QUANTIZATION_LIMITED_RANGE;
4286 
4287 	///VIC
4288 	if (pipe_ctx->stream->timing.hdmi_vic != 0)
4289 		vic = 0;
4290 	format = stream->timing.timing_3d_format;
4291 	/*todo, add 3DStereo support*/
4292 	if (format != TIMING_3D_FORMAT_NONE) {
4293 		// Based on HDMI specs hdmi vic needs to be converted to cea vic when 3D is enabled
4294 		switch (pipe_ctx->stream->timing.hdmi_vic) {
4295 		case 1:
4296 			vic = 95;
4297 			break;
4298 		case 2:
4299 			vic = 94;
4300 			break;
4301 		case 3:
4302 			vic = 93;
4303 			break;
4304 		case 4:
4305 			vic = 98;
4306 			break;
4307 		default:
4308 			break;
4309 		}
4310 	}
4311 	/* If VIC >= 128, the Source shall use AVI InfoFrame Version 3*/
4312 	hdmi_info.bits.VIC0_VIC7 = vic;
4313 	if (vic >= 128)
4314 		hdmi_info.bits.header.version = 3;
4315 	/* If (C1, C0)=(1, 1) and (EC2, EC1, EC0)=(1, 1, 1),
4316 	 * the Source shall use 20 AVI InfoFrame Version 4
4317 	 */
4318 	if (hdmi_info.bits.C0_C1 == COLORIMETRY_EXTENDED &&
4319 			hdmi_info.bits.EC0_EC2 == COLORIMETRYEX_RESERVED) {
4320 		hdmi_info.bits.header.version = 4;
4321 		hdmi_info.bits.header.length = 14;
4322 	}
4323 
4324 	if (rid != 0 && fr_ind != 0) {
4325 		hdmi_info.bits.header.version = 4;
4326 		hdmi_info.bits.header.length = 15;
4327 
4328 		hdmi_info.bits.FR0_FR3 = fr_ind & 0xF;
4329 		hdmi_info.bits.FR4 = (fr_ind >> 4) & 0x1;
4330 		hdmi_info.bits.RID0_RID5 = rid;
4331 	}
4332 
4333 	/* pixel repetition
4334 	 * PR0 - PR3 start from 0 whereas pHwPathMode->mode.timing.flags.pixel
4335 	 * repetition start from 1 */
4336 	hdmi_info.bits.PR0_PR3 = 0;
4337 
4338 	/* Bar Info
4339 	 * barTop:    Line Number of End of Top Bar.
4340 	 * barBottom: Line Number of Start of Bottom Bar.
4341 	 * barLeft:   Pixel Number of End of Left Bar.
4342 	 * barRight:  Pixel Number of Start of Right Bar. */
4343 	hdmi_info.bits.bar_top = stream->timing.v_border_top;
4344 	hdmi_info.bits.bar_bottom = (stream->timing.v_total
4345 			- stream->timing.v_border_bottom + 1);
4346 	hdmi_info.bits.bar_left  = stream->timing.h_border_left;
4347 	hdmi_info.bits.bar_right = (stream->timing.h_total
4348 			- stream->timing.h_border_right + 1);
4349 
4350     /* Additional Colorimetry Extension
4351      * Used in conduction with C0-C1 and EC0-EC2
4352      * 0 = DCI-P3 RGB (D65)
4353      * 1 = DCI-P3 RGB (theater)
4354      */
4355 	hdmi_info.bits.ACE0_ACE3 = 0;
4356 
4357 	/* check_sum - Calculate AFMT_AVI_INFO0 ~ AFMT_AVI_INFO3 */
4358 	check_sum = &hdmi_info.packet_raw_data.sb[0];
4359 
4360 	*check_sum = HDMI_INFOFRAME_TYPE_AVI + hdmi_info.bits.header.length + hdmi_info.bits.header.version;
4361 
4362 	for (byte_index = 1; byte_index <= hdmi_info.bits.header.length; byte_index++)
4363 		*check_sum += hdmi_info.packet_raw_data.sb[byte_index];
4364 
4365 	/* one byte complement */
4366 	*check_sum = (uint8_t) (0x100 - *check_sum);
4367 
4368 	/* Store in hw_path_mode */
4369 	info_packet->hb0 = hdmi_info.packet_raw_data.hb0;
4370 	info_packet->hb1 = hdmi_info.packet_raw_data.hb1;
4371 	info_packet->hb2 = hdmi_info.packet_raw_data.hb2;
4372 
4373 	for (byte_index = 0; byte_index < sizeof(hdmi_info.packet_raw_data.sb); byte_index++)
4374 		info_packet->sb[byte_index] = hdmi_info.packet_raw_data.sb[byte_index];
4375 
4376 	info_packet->valid = true;
4377 }
4378 
4379 static void set_vendor_info_packet(
4380 		struct dc_info_packet *info_packet,
4381 		struct dc_stream_state *stream)
4382 {
4383 	/* SPD info packet for FreeSync */
4384 
4385 	/* Check if Freesync is supported. Return if false. If true,
4386 	 * set the corresponding bit in the info packet
4387 	 */
4388 	if (!stream->vsp_infopacket.valid)
4389 		return;
4390 
4391 	*info_packet = stream->vsp_infopacket;
4392 }
4393 
4394 static void set_spd_info_packet(
4395 		struct dc_info_packet *info_packet,
4396 		struct dc_stream_state *stream)
4397 {
4398 	/* SPD info packet for FreeSync */
4399 
4400 	/* Check if Freesync is supported. Return if false. If true,
4401 	 * set the corresponding bit in the info packet
4402 	 */
4403 	if (!stream->vrr_infopacket.valid)
4404 		return;
4405 
4406 	*info_packet = stream->vrr_infopacket;
4407 }
4408 
4409 static void set_hdr_static_info_packet(
4410 		struct dc_info_packet *info_packet,
4411 		struct dc_stream_state *stream)
4412 {
4413 	/* HDR Static Metadata info packet for HDR10 */
4414 
4415 	if (!stream->hdr_static_metadata.valid ||
4416 			stream->use_dynamic_meta)
4417 		return;
4418 
4419 	*info_packet = stream->hdr_static_metadata;
4420 }
4421 
4422 static void set_vsc_info_packet(
4423 		struct dc_info_packet *info_packet,
4424 		struct dc_stream_state *stream)
4425 {
4426 	if (!stream->vsc_infopacket.valid)
4427 		return;
4428 
4429 	*info_packet = stream->vsc_infopacket;
4430 }
4431 static void set_hfvs_info_packet(
4432 		struct dc_info_packet *info_packet,
4433 		struct dc_stream_state *stream)
4434 {
4435 	if (!stream->hfvsif_infopacket.valid)
4436 		return;
4437 
4438 	*info_packet = stream->hfvsif_infopacket;
4439 }
4440 
4441 static void adaptive_sync_override_dp_info_packets_sdp_line_num(
4442 		const struct dc_crtc_timing *timing,
4443 		struct enc_sdp_line_num *sdp_line_num,
4444 		struct _vcs_dpi_display_pipe_dest_params_st *pipe_dlg_param)
4445 {
4446 	uint32_t asic_blank_start = 0;
4447 	uint32_t asic_blank_end   = 0;
4448 	uint32_t v_update = 0;
4449 
4450 	const struct dc_crtc_timing *tg = timing;
4451 
4452 	/* blank_start = frame end - front porch */
4453 	asic_blank_start = tg->v_total - tg->v_front_porch;
4454 
4455 	/* blank_end = blank_start - active */
4456 	asic_blank_end = (asic_blank_start - tg->v_border_bottom -
4457 						tg->v_addressable - tg->v_border_top);
4458 
4459 	if (pipe_dlg_param->vstartup_start > asic_blank_end) {
4460 		v_update = (tg->v_total - (pipe_dlg_param->vstartup_start - asic_blank_end));
4461 		sdp_line_num->adaptive_sync_line_num_valid = true;
4462 		sdp_line_num->adaptive_sync_line_num = (tg->v_total - v_update - 1);
4463 	} else {
4464 		sdp_line_num->adaptive_sync_line_num_valid = false;
4465 		sdp_line_num->adaptive_sync_line_num = 0;
4466 	}
4467 }
4468 
4469 static void set_adaptive_sync_info_packet(
4470 		struct dc_info_packet *info_packet,
4471 		const struct dc_stream_state *stream,
4472 		struct encoder_info_frame *info_frame,
4473 		struct _vcs_dpi_display_pipe_dest_params_st *pipe_dlg_param)
4474 {
4475 	if (!stream->adaptive_sync_infopacket.valid)
4476 		return;
4477 
4478 	adaptive_sync_override_dp_info_packets_sdp_line_num(
4479 			&stream->timing,
4480 			&info_frame->sdp_line_num,
4481 			pipe_dlg_param);
4482 
4483 	*info_packet = stream->adaptive_sync_infopacket;
4484 }
4485 
4486 static void set_vtem_info_packet(
4487 		struct dc_info_packet *info_packet,
4488 		struct dc_stream_state *stream)
4489 {
4490 	if (!stream->vtem_infopacket.valid)
4491 		return;
4492 
4493 	*info_packet = stream->vtem_infopacket;
4494 }
4495 
4496 struct clock_source *dc_resource_find_first_free_pll(
4497 		struct resource_context *res_ctx,
4498 		const struct resource_pool *pool)
4499 {
4500 	int i;
4501 
4502 	for (i = 0; i < pool->clk_src_count; ++i) {
4503 		if (res_ctx->clock_source_ref_count[i] == 0)
4504 			return pool->clock_sources[i];
4505 	}
4506 
4507 	return NULL;
4508 }
4509 
4510 void resource_build_info_frame(struct pipe_ctx *pipe_ctx)
4511 {
4512 	enum signal_type signal = SIGNAL_TYPE_NONE;
4513 	struct encoder_info_frame *info = &pipe_ctx->stream_res.encoder_info_frame;
4514 
4515 	/* default all packets to invalid */
4516 	info->avi.valid = false;
4517 	info->gamut.valid = false;
4518 	info->vendor.valid = false;
4519 	info->spd.valid = false;
4520 	info->hdrsmd.valid = false;
4521 	info->vsc.valid = false;
4522 	info->hfvsif.valid = false;
4523 	info->vtem.valid = false;
4524 	info->adaptive_sync.valid = false;
4525 	signal = pipe_ctx->stream->signal;
4526 
4527 	/* HDMi and DP have different info packets*/
4528 	if (dc_is_hdmi_signal(signal)) {
4529 		set_avi_info_frame(&info->avi, pipe_ctx);
4530 
4531 		set_vendor_info_packet(&info->vendor, pipe_ctx->stream);
4532 		set_hfvs_info_packet(&info->hfvsif, pipe_ctx->stream);
4533 		set_vtem_info_packet(&info->vtem, pipe_ctx->stream);
4534 
4535 		set_spd_info_packet(&info->spd, pipe_ctx->stream);
4536 
4537 		set_hdr_static_info_packet(&info->hdrsmd, pipe_ctx->stream);
4538 
4539 	} else if (dc_is_dp_signal(signal)) {
4540 		set_vsc_info_packet(&info->vsc, pipe_ctx->stream);
4541 
4542 		set_spd_info_packet(&info->spd, pipe_ctx->stream);
4543 
4544 		set_hdr_static_info_packet(&info->hdrsmd, pipe_ctx->stream);
4545 		set_adaptive_sync_info_packet(&info->adaptive_sync,
4546 										pipe_ctx->stream,
4547 										info,
4548 										&pipe_ctx->pipe_dlg_param);
4549 	}
4550 
4551 	patch_gamut_packet_checksum(&info->gamut);
4552 }
4553 
4554 enum dc_status resource_map_clock_resources(
4555 		const struct dc  *dc,
4556 		struct dc_state *context,
4557 		struct dc_stream_state *stream)
4558 {
4559 	/* acquire new resources */
4560 	const struct resource_pool *pool = dc->res_pool;
4561 	struct pipe_ctx *pipe_ctx = resource_get_otg_master_for_stream(
4562 				&context->res_ctx, stream);
4563 
4564 	if (!pipe_ctx)
4565 		return DC_ERROR_UNEXPECTED;
4566 
4567 	if (dc_is_dp_signal(pipe_ctx->stream->signal)
4568 		|| pipe_ctx->stream->signal == SIGNAL_TYPE_VIRTUAL)
4569 		pipe_ctx->clock_source = pool->dp_clock_source;
4570 	else {
4571 		pipe_ctx->clock_source = NULL;
4572 
4573 		if (!dc->config.disable_disp_pll_sharing)
4574 			pipe_ctx->clock_source = resource_find_used_clk_src_for_sharing(
4575 				&context->res_ctx,
4576 				pipe_ctx);
4577 
4578 		if (pipe_ctx->clock_source == NULL)
4579 			pipe_ctx->clock_source =
4580 				dc_resource_find_first_free_pll(
4581 					&context->res_ctx,
4582 					pool);
4583 	}
4584 
4585 	if (pipe_ctx->clock_source == NULL)
4586 		return DC_NO_CLOCK_SOURCE_RESOURCE;
4587 
4588 	resource_reference_clock_source(
4589 		&context->res_ctx, pool,
4590 		pipe_ctx->clock_source);
4591 
4592 	return DC_OK;
4593 }
4594 
4595 /*
4596  * Note: We need to disable output if clock sources change,
4597  * since bios does optimization and doesn't apply if changing
4598  * PHY when not already disabled.
4599  */
4600 bool pipe_need_reprogram(
4601 		struct pipe_ctx *pipe_ctx_old,
4602 		struct pipe_ctx *pipe_ctx)
4603 {
4604 	if (!pipe_ctx_old->stream)
4605 		return false;
4606 
4607 	if (pipe_ctx_old->stream->sink != pipe_ctx->stream->sink)
4608 		return true;
4609 
4610 	if (pipe_ctx_old->stream->signal != pipe_ctx->stream->signal)
4611 		return true;
4612 
4613 	if (pipe_ctx_old->stream_res.audio != pipe_ctx->stream_res.audio)
4614 		return true;
4615 
4616 	if (pipe_ctx_old->clock_source != pipe_ctx->clock_source
4617 			&& pipe_ctx_old->stream != pipe_ctx->stream)
4618 		return true;
4619 
4620 	if (pipe_ctx_old->stream_res.stream_enc != pipe_ctx->stream_res.stream_enc)
4621 		return true;
4622 
4623 	if (dc_is_timing_changed(pipe_ctx_old->stream, pipe_ctx->stream))
4624 		return true;
4625 
4626 	if (pipe_ctx_old->stream->dpms_off != pipe_ctx->stream->dpms_off)
4627 		return true;
4628 
4629 	if (false == pipe_ctx_old->stream->link->link_state_valid &&
4630 		false == pipe_ctx_old->stream->dpms_off)
4631 		return true;
4632 
4633 	if (pipe_ctx_old->stream_res.dsc != pipe_ctx->stream_res.dsc)
4634 		return true;
4635 
4636 	if (pipe_ctx_old->stream_res.hpo_dp_stream_enc != pipe_ctx->stream_res.hpo_dp_stream_enc)
4637 		return true;
4638 	if (pipe_ctx_old->link_res.hpo_dp_link_enc != pipe_ctx->link_res.hpo_dp_link_enc)
4639 		return true;
4640 
4641 	/* DIG link encoder resource assignment for stream changed. */
4642 	if (pipe_ctx_old->stream->ctx->dc->res_pool->funcs->link_encs_assign) {
4643 		bool need_reprogram = false;
4644 		struct dc *dc = pipe_ctx_old->stream->ctx->dc;
4645 		struct link_encoder *link_enc_prev =
4646 			link_enc_cfg_get_link_enc_used_by_stream_current(dc, pipe_ctx_old->stream);
4647 
4648 		if (link_enc_prev != pipe_ctx->stream->link_enc)
4649 			need_reprogram = true;
4650 
4651 		return need_reprogram;
4652 	}
4653 
4654 	return false;
4655 }
4656 
4657 void resource_build_bit_depth_reduction_params(struct dc_stream_state *stream,
4658 		struct bit_depth_reduction_params *fmt_bit_depth)
4659 {
4660 	enum dc_dither_option option = stream->dither_option;
4661 	enum dc_pixel_encoding pixel_encoding =
4662 			stream->timing.pixel_encoding;
4663 
4664 	memset(fmt_bit_depth, 0, sizeof(*fmt_bit_depth));
4665 
4666 	if (option == DITHER_OPTION_DEFAULT) {
4667 		switch (stream->timing.display_color_depth) {
4668 		case COLOR_DEPTH_666:
4669 			option = DITHER_OPTION_SPATIAL6;
4670 			break;
4671 		case COLOR_DEPTH_888:
4672 			option = DITHER_OPTION_SPATIAL8;
4673 			break;
4674 		case COLOR_DEPTH_101010:
4675 			option = DITHER_OPTION_TRUN10;
4676 			break;
4677 		default:
4678 			option = DITHER_OPTION_DISABLE;
4679 		}
4680 	}
4681 
4682 	if (option == DITHER_OPTION_DISABLE)
4683 		return;
4684 
4685 	if (option == DITHER_OPTION_TRUN6) {
4686 		fmt_bit_depth->flags.TRUNCATE_ENABLED = 1;
4687 		fmt_bit_depth->flags.TRUNCATE_DEPTH = 0;
4688 	} else if (option == DITHER_OPTION_TRUN8 ||
4689 			option == DITHER_OPTION_TRUN8_SPATIAL6 ||
4690 			option == DITHER_OPTION_TRUN8_FM6) {
4691 		fmt_bit_depth->flags.TRUNCATE_ENABLED = 1;
4692 		fmt_bit_depth->flags.TRUNCATE_DEPTH = 1;
4693 	} else if (option == DITHER_OPTION_TRUN10        ||
4694 			option == DITHER_OPTION_TRUN10_SPATIAL6   ||
4695 			option == DITHER_OPTION_TRUN10_SPATIAL8   ||
4696 			option == DITHER_OPTION_TRUN10_FM8     ||
4697 			option == DITHER_OPTION_TRUN10_FM6     ||
4698 			option == DITHER_OPTION_TRUN10_SPATIAL8_FM6) {
4699 		fmt_bit_depth->flags.TRUNCATE_ENABLED = 1;
4700 		fmt_bit_depth->flags.TRUNCATE_DEPTH = 2;
4701 		if (option == DITHER_OPTION_TRUN10)
4702 			fmt_bit_depth->flags.TRUNCATE_MODE = 1;
4703 	}
4704 
4705 	/* special case - Formatter can only reduce by 4 bits at most.
4706 	 * When reducing from 12 to 6 bits,
4707 	 * HW recommends we use trunc with round mode
4708 	 * (if we did nothing, trunc to 10 bits would be used)
4709 	 * note that any 12->10 bit reduction is ignored prior to DCE8,
4710 	 * as the input was 10 bits.
4711 	 */
4712 	if (option == DITHER_OPTION_SPATIAL6_FRAME_RANDOM ||
4713 			option == DITHER_OPTION_SPATIAL6 ||
4714 			option == DITHER_OPTION_FM6) {
4715 		fmt_bit_depth->flags.TRUNCATE_ENABLED = 1;
4716 		fmt_bit_depth->flags.TRUNCATE_DEPTH = 2;
4717 		fmt_bit_depth->flags.TRUNCATE_MODE = 1;
4718 	}
4719 
4720 	/* spatial dither
4721 	 * note that spatial modes 1-3 are never used
4722 	 */
4723 	if (option == DITHER_OPTION_SPATIAL6_FRAME_RANDOM            ||
4724 			option == DITHER_OPTION_SPATIAL6 ||
4725 			option == DITHER_OPTION_TRUN10_SPATIAL6      ||
4726 			option == DITHER_OPTION_TRUN8_SPATIAL6) {
4727 		fmt_bit_depth->flags.SPATIAL_DITHER_ENABLED = 1;
4728 		fmt_bit_depth->flags.SPATIAL_DITHER_DEPTH = 0;
4729 		fmt_bit_depth->flags.HIGHPASS_RANDOM = 1;
4730 		fmt_bit_depth->flags.RGB_RANDOM =
4731 				(pixel_encoding == PIXEL_ENCODING_RGB) ? 1 : 0;
4732 	} else if (option == DITHER_OPTION_SPATIAL8_FRAME_RANDOM            ||
4733 			option == DITHER_OPTION_SPATIAL8 ||
4734 			option == DITHER_OPTION_SPATIAL8_FM6        ||
4735 			option == DITHER_OPTION_TRUN10_SPATIAL8      ||
4736 			option == DITHER_OPTION_TRUN10_SPATIAL8_FM6) {
4737 		fmt_bit_depth->flags.SPATIAL_DITHER_ENABLED = 1;
4738 		fmt_bit_depth->flags.SPATIAL_DITHER_DEPTH = 1;
4739 		fmt_bit_depth->flags.HIGHPASS_RANDOM = 1;
4740 		fmt_bit_depth->flags.RGB_RANDOM =
4741 				(pixel_encoding == PIXEL_ENCODING_RGB) ? 1 : 0;
4742 	} else if (option == DITHER_OPTION_SPATIAL10_FRAME_RANDOM ||
4743 			option == DITHER_OPTION_SPATIAL10 ||
4744 			option == DITHER_OPTION_SPATIAL10_FM8 ||
4745 			option == DITHER_OPTION_SPATIAL10_FM6) {
4746 		fmt_bit_depth->flags.SPATIAL_DITHER_ENABLED = 1;
4747 		fmt_bit_depth->flags.SPATIAL_DITHER_DEPTH = 2;
4748 		fmt_bit_depth->flags.HIGHPASS_RANDOM = 1;
4749 		fmt_bit_depth->flags.RGB_RANDOM =
4750 				(pixel_encoding == PIXEL_ENCODING_RGB) ? 1 : 0;
4751 	}
4752 
4753 	if (option == DITHER_OPTION_SPATIAL6 ||
4754 			option == DITHER_OPTION_SPATIAL8 ||
4755 			option == DITHER_OPTION_SPATIAL10) {
4756 		fmt_bit_depth->flags.FRAME_RANDOM = 0;
4757 	} else {
4758 		fmt_bit_depth->flags.FRAME_RANDOM = 1;
4759 	}
4760 
4761 	//////////////////////
4762 	//// temporal dither
4763 	//////////////////////
4764 	if (option == DITHER_OPTION_FM6           ||
4765 			option == DITHER_OPTION_SPATIAL8_FM6     ||
4766 			option == DITHER_OPTION_SPATIAL10_FM6     ||
4767 			option == DITHER_OPTION_TRUN10_FM6     ||
4768 			option == DITHER_OPTION_TRUN8_FM6      ||
4769 			option == DITHER_OPTION_TRUN10_SPATIAL8_FM6) {
4770 		fmt_bit_depth->flags.FRAME_MODULATION_ENABLED = 1;
4771 		fmt_bit_depth->flags.FRAME_MODULATION_DEPTH = 0;
4772 	} else if (option == DITHER_OPTION_FM8        ||
4773 			option == DITHER_OPTION_SPATIAL10_FM8  ||
4774 			option == DITHER_OPTION_TRUN10_FM8) {
4775 		fmt_bit_depth->flags.FRAME_MODULATION_ENABLED = 1;
4776 		fmt_bit_depth->flags.FRAME_MODULATION_DEPTH = 1;
4777 	} else if (option == DITHER_OPTION_FM10) {
4778 		fmt_bit_depth->flags.FRAME_MODULATION_ENABLED = 1;
4779 		fmt_bit_depth->flags.FRAME_MODULATION_DEPTH = 2;
4780 	}
4781 
4782 	fmt_bit_depth->pixel_encoding = pixel_encoding;
4783 }
4784 
4785 enum dc_status dc_validate_stream(struct dc *dc, struct dc_stream_state *stream)
4786 {
4787 	if (dc == NULL || stream == NULL)
4788 		return DC_ERROR_UNEXPECTED;
4789 
4790 	struct dc_link *link = stream->link;
4791 	struct timing_generator *tg = dc->res_pool->timing_generators[0];
4792 	enum dc_status res = DC_OK;
4793 
4794 	calculate_phy_pix_clks(stream);
4795 
4796 	if (!tg->funcs->validate_timing(tg, &stream->timing))
4797 		res = DC_FAIL_CONTROLLER_VALIDATE;
4798 
4799 	if (res == DC_OK) {
4800 		if (link->ep_type == DISPLAY_ENDPOINT_PHY &&
4801 				!link->link_enc->funcs->validate_output_with_stream(
4802 						link->link_enc, stream))
4803 			res = DC_FAIL_ENC_VALIDATE;
4804 	}
4805 
4806 	/* TODO: validate audio ASIC caps, encoder */
4807 
4808 	if (res == DC_OK)
4809 		res = dc->link_srv->validate_mode_timing(stream,
4810 		      link,
4811 		      &stream->timing);
4812 
4813 	return res;
4814 }
4815 
4816 enum dc_status dc_validate_plane(struct dc *dc, const struct dc_plane_state *plane_state)
4817 {
4818 	enum dc_status res = DC_OK;
4819 
4820 	/* check if surface has invalid dimensions */
4821 	if (plane_state->src_rect.width == 0 || plane_state->src_rect.height == 0 ||
4822 		plane_state->dst_rect.width == 0 || plane_state->dst_rect.height == 0)
4823 		return DC_FAIL_SURFACE_VALIDATE;
4824 
4825 	/* TODO For now validates pixel format only */
4826 	if (dc->res_pool->funcs->validate_plane)
4827 		return dc->res_pool->funcs->validate_plane(plane_state, &dc->caps);
4828 
4829 	return res;
4830 }
4831 
4832 unsigned int resource_pixel_format_to_bpp(enum surface_pixel_format format)
4833 {
4834 	switch (format) {
4835 	case SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS:
4836 		return 8;
4837 	case SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr:
4838 	case SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb:
4839 		return 12;
4840 	case SURFACE_PIXEL_FORMAT_GRPH_ARGB1555:
4841 	case SURFACE_PIXEL_FORMAT_GRPH_RGB565:
4842 	case SURFACE_PIXEL_FORMAT_VIDEO_420_10bpc_YCbCr:
4843 	case SURFACE_PIXEL_FORMAT_VIDEO_420_10bpc_YCrCb:
4844 		return 16;
4845 	case SURFACE_PIXEL_FORMAT_GRPH_ARGB8888:
4846 	case SURFACE_PIXEL_FORMAT_GRPH_ABGR8888:
4847 	case SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010:
4848 	case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010:
4849 	case SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010_XR_BIAS:
4850 	case SURFACE_PIXEL_FORMAT_GRPH_RGBE:
4851 	case SURFACE_PIXEL_FORMAT_GRPH_RGBE_ALPHA:
4852 		return 32;
4853 	case SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616:
4854 	case SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616:
4855 	case SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616F:
4856 	case SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616F:
4857 		return 64;
4858 	default:
4859 		ASSERT_CRITICAL(false);
4860 		return -1;
4861 	}
4862 }
4863 static unsigned int get_max_audio_sample_rate(struct audio_mode *modes)
4864 {
4865 	if (modes) {
4866 		if (modes->sample_rates.rate.RATE_192)
4867 			return 192000;
4868 		if (modes->sample_rates.rate.RATE_176_4)
4869 			return 176400;
4870 		if (modes->sample_rates.rate.RATE_96)
4871 			return 96000;
4872 		if (modes->sample_rates.rate.RATE_88_2)
4873 			return 88200;
4874 		if (modes->sample_rates.rate.RATE_48)
4875 			return 48000;
4876 		if (modes->sample_rates.rate.RATE_44_1)
4877 			return 44100;
4878 		if (modes->sample_rates.rate.RATE_32)
4879 			return 32000;
4880 	}
4881 	/*original logic when no audio info*/
4882 	return 441000;
4883 }
4884 
4885 void get_audio_check(struct audio_info *aud_modes,
4886 	struct audio_check *audio_chk)
4887 {
4888 	unsigned int i;
4889 	unsigned int max_sample_rate = 0;
4890 
4891 	if (aud_modes) {
4892 		audio_chk->audio_packet_type = 0x2;/*audio sample packet AP = .25 for layout0, 1 for layout1*/
4893 
4894 		audio_chk->max_audiosample_rate = 0;
4895 		for (i = 0; i < aud_modes->mode_count; i++) {
4896 			max_sample_rate = get_max_audio_sample_rate(&aud_modes->modes[i]);
4897 			if (audio_chk->max_audiosample_rate < max_sample_rate)
4898 				audio_chk->max_audiosample_rate = max_sample_rate;
4899 			/*dts takes the same as type 2: AP = 0.25*/
4900 		}
4901 		/*check which one take more bandwidth*/
4902 		if (audio_chk->max_audiosample_rate > 192000)
4903 			audio_chk->audio_packet_type = 0x9;/*AP =1*/
4904 		audio_chk->acat = 0;/*not support*/
4905 	}
4906 }
4907 
4908 static struct hpo_dp_link_encoder *get_temp_hpo_dp_link_enc(
4909 		const struct resource_context *res_ctx,
4910 		const struct resource_pool *const pool,
4911 		const struct dc_link *link)
4912 {
4913 	struct hpo_dp_link_encoder *hpo_dp_link_enc = NULL;
4914 	int enc_index;
4915 
4916 	enc_index = find_acquired_hpo_dp_link_enc_for_link(res_ctx, link);
4917 
4918 	if (enc_index < 0)
4919 		enc_index = find_free_hpo_dp_link_enc(res_ctx, pool);
4920 
4921 	if (enc_index >= 0)
4922 		hpo_dp_link_enc = pool->hpo_dp_link_enc[enc_index];
4923 
4924 	return hpo_dp_link_enc;
4925 }
4926 
4927 bool get_temp_dp_link_res(struct dc_link *link,
4928 		struct link_resource *link_res,
4929 		struct dc_link_settings *link_settings)
4930 {
4931 	const struct dc *dc  = link->dc;
4932 	const struct resource_context *res_ctx = &dc->current_state->res_ctx;
4933 
4934 	memset(link_res, 0, sizeof(*link_res));
4935 
4936 	if (dc->link_srv->dp_get_encoding_format(link_settings) == DP_128b_132b_ENCODING) {
4937 		link_res->hpo_dp_link_enc = get_temp_hpo_dp_link_enc(res_ctx,
4938 				dc->res_pool, link);
4939 		if (!link_res->hpo_dp_link_enc)
4940 			return false;
4941 	}
4942 	return true;
4943 }
4944 
4945 void reset_syncd_pipes_from_disabled_pipes(struct dc *dc,
4946 		struct dc_state *context)
4947 {
4948 	int i, j;
4949 	struct pipe_ctx *pipe_ctx_old, *pipe_ctx, *pipe_ctx_syncd;
4950 
4951 	/* If pipe backend is reset, need to reset pipe syncd status */
4952 	for (i = 0; i < dc->res_pool->pipe_count; i++) {
4953 		pipe_ctx_old =	&dc->current_state->res_ctx.pipe_ctx[i];
4954 		pipe_ctx = &context->res_ctx.pipe_ctx[i];
4955 
4956 		if (!resource_is_pipe_type(pipe_ctx_old, OTG_MASTER))
4957 			continue;
4958 
4959 		if (!pipe_ctx->stream ||
4960 				pipe_need_reprogram(pipe_ctx_old, pipe_ctx)) {
4961 
4962 			/* Reset all the syncd pipes from the disabled pipe */
4963 			for (j = 0; j < dc->res_pool->pipe_count; j++) {
4964 				pipe_ctx_syncd = &context->res_ctx.pipe_ctx[j];
4965 				if ((GET_PIPE_SYNCD_FROM_PIPE(pipe_ctx_syncd) == pipe_ctx_old->pipe_idx) ||
4966 					!IS_PIPE_SYNCD_VALID(pipe_ctx_syncd))
4967 					SET_PIPE_SYNCD_TO_PIPE(pipe_ctx_syncd, j);
4968 			}
4969 		}
4970 	}
4971 }
4972 
4973 void check_syncd_pipes_for_disabled_master_pipe(struct dc *dc,
4974 	struct dc_state *context,
4975 	uint8_t disabled_master_pipe_idx)
4976 {
4977 	int i;
4978 	struct pipe_ctx *pipe_ctx, *pipe_ctx_check;
4979 
4980 	pipe_ctx = &context->res_ctx.pipe_ctx[disabled_master_pipe_idx];
4981 	if ((GET_PIPE_SYNCD_FROM_PIPE(pipe_ctx) != disabled_master_pipe_idx) ||
4982 		!IS_PIPE_SYNCD_VALID(pipe_ctx))
4983 		SET_PIPE_SYNCD_TO_PIPE(pipe_ctx, disabled_master_pipe_idx);
4984 
4985 	/* for the pipe disabled, check if any slave pipe exists and assert */
4986 	for (i = 0; i < dc->res_pool->pipe_count; i++) {
4987 		pipe_ctx_check = &context->res_ctx.pipe_ctx[i];
4988 
4989 		if ((GET_PIPE_SYNCD_FROM_PIPE(pipe_ctx_check) == disabled_master_pipe_idx) &&
4990 		    IS_PIPE_SYNCD_VALID(pipe_ctx_check) && (i != disabled_master_pipe_idx)) {
4991 			struct pipe_ctx *first_pipe = pipe_ctx_check;
4992 
4993 			while (first_pipe->prev_odm_pipe)
4994 				first_pipe = first_pipe->prev_odm_pipe;
4995 			/* When ODM combine is enabled, this case is expected. If the disabled pipe
4996 			 * is part of the ODM tree, then we should not print an error.
4997 			 * */
4998 			if (first_pipe->pipe_idx == disabled_master_pipe_idx)
4999 				continue;
5000 
5001 			DC_ERR("DC: Failure: pipe_idx[%d] syncd with disabled master pipe_idx[%d]\n",
5002 				   i, disabled_master_pipe_idx);
5003 		}
5004 	}
5005 }
5006 
5007 void reset_sync_context_for_pipe(const struct dc *dc,
5008 	struct dc_state *context,
5009 	uint8_t pipe_idx)
5010 {
5011 	int i;
5012 	struct pipe_ctx *pipe_ctx_reset;
5013 
5014 	/* reset the otg sync context for the pipe and its slave pipes if any */
5015 	for (i = 0; i < dc->res_pool->pipe_count; i++) {
5016 		pipe_ctx_reset = &context->res_ctx.pipe_ctx[i];
5017 
5018 		if (((GET_PIPE_SYNCD_FROM_PIPE(pipe_ctx_reset) == pipe_idx) &&
5019 			IS_PIPE_SYNCD_VALID(pipe_ctx_reset)) || (i == pipe_idx))
5020 			SET_PIPE_SYNCD_TO_PIPE(pipe_ctx_reset, i);
5021 	}
5022 }
5023 
5024 uint8_t resource_transmitter_to_phy_idx(const struct dc *dc, enum transmitter transmitter)
5025 {
5026 	/* TODO - get transmitter to phy idx mapping from DMUB */
5027 	uint8_t phy_idx = transmitter - TRANSMITTER_UNIPHY_A;
5028 
5029 	if (dc->ctx->dce_version == DCN_VERSION_3_1 &&
5030 			dc->ctx->asic_id.hw_internal_rev == YELLOW_CARP_B0) {
5031 		switch (transmitter) {
5032 		case TRANSMITTER_UNIPHY_A:
5033 			phy_idx = 0;
5034 			break;
5035 		case TRANSMITTER_UNIPHY_B:
5036 			phy_idx = 1;
5037 			break;
5038 		case TRANSMITTER_UNIPHY_C:
5039 			phy_idx = 5;
5040 			break;
5041 		case TRANSMITTER_UNIPHY_D:
5042 			phy_idx = 6;
5043 			break;
5044 		case TRANSMITTER_UNIPHY_E:
5045 			phy_idx = 4;
5046 			break;
5047 		default:
5048 			phy_idx = 0;
5049 			break;
5050 		}
5051 	}
5052 
5053 	return phy_idx;
5054 }
5055 
5056 const struct link_hwss *get_link_hwss(const struct dc_link *link,
5057 		const struct link_resource *link_res)
5058 {
5059 	/* Link_hwss is only accessible by getter function instead of accessing
5060 	 * by pointers in dc with the intent to protect against breaking polymorphism.
5061 	 */
5062 	if (can_use_hpo_dp_link_hwss(link, link_res))
5063 		/* TODO: some assumes that if decided link settings is 128b/132b
5064 		 * channel coding format hpo_dp_link_enc should be used.
5065 		 * Others believe that if hpo_dp_link_enc is available in link
5066 		 * resource then hpo_dp_link_enc must be used. This bound between
5067 		 * hpo_dp_link_enc != NULL and decided link settings is loosely coupled
5068 		 * with a premise that both hpo_dp_link_enc pointer and decided link
5069 		 * settings are determined based on single policy function like
5070 		 * "decide_link_settings" from upper layer. This "convention"
5071 		 * cannot be maintained and enforced at current level.
5072 		 * Therefore a refactor is due so we can enforce a strong bound
5073 		 * between those two parameters at this level.
5074 		 *
5075 		 * To put it simple, we want to make enforcement at low level so that
5076 		 * we will not return link hwss if caller plans to do 8b/10b
5077 		 * with an hpo encoder. Or we can return a very dummy one that doesn't
5078 		 * do work for all functions
5079 		 */
5080 		return (requires_fixed_vs_pe_retimer_hpo_link_hwss(link) ?
5081 				get_hpo_fixed_vs_pe_retimer_dp_link_hwss() : get_hpo_dp_link_hwss());
5082 	else if (can_use_dpia_link_hwss(link, link_res))
5083 		return get_dpia_link_hwss();
5084 	else if (can_use_dio_link_hwss(link, link_res))
5085 		return (requires_fixed_vs_pe_retimer_dio_link_hwss(link)) ?
5086 				get_dio_fixed_vs_pe_retimer_link_hwss() : get_dio_link_hwss();
5087 	else
5088 		return get_virtual_link_hwss();
5089 }
5090 
5091 bool is_h_timing_divisible_by_2(struct dc_stream_state *stream)
5092 {
5093 	bool divisible = false;
5094 	uint16_t h_blank_start = 0;
5095 	uint16_t h_blank_end = 0;
5096 
5097 	if (stream) {
5098 		h_blank_start = stream->timing.h_total - stream->timing.h_front_porch;
5099 		h_blank_end = h_blank_start - stream->timing.h_addressable;
5100 
5101 		/* HTOTAL, Hblank start/end, and Hsync start/end all must be
5102 		 * divisible by 2 in order for the horizontal timing params
5103 		 * to be considered divisible by 2. Hsync start is always 0.
5104 		 */
5105 		divisible = (stream->timing.h_total % 2 == 0) &&
5106 				(h_blank_start % 2 == 0) &&
5107 				(h_blank_end % 2 == 0) &&
5108 				(stream->timing.h_sync_width % 2 == 0);
5109 	}
5110 	return divisible;
5111 }
5112 
5113 /* This interface is deprecated for new DCNs. It is replaced by the following
5114  * new interfaces. These two interfaces encapsulate pipe selection priority
5115  * with DCN specific minimum hardware transition optimization algorithm. With
5116  * the new interfaces caller no longer needs to know the implementation detail
5117  * of a pipe topology.
5118  *
5119  * resource_update_pipes_with_odm_slice_count
5120  * resource_update_pipes_with_mpc_slice_count
5121  *
5122  */
5123 bool dc_resource_acquire_secondary_pipe_for_mpc_odm_legacy(
5124 		const struct dc *dc,
5125 		struct dc_state *state,
5126 		struct pipe_ctx *pri_pipe,
5127 		struct pipe_ctx *sec_pipe,
5128 		bool odm)
5129 {
5130 	int pipe_idx = sec_pipe->pipe_idx;
5131 	struct pipe_ctx *sec_top, *sec_bottom, *sec_next, *sec_prev;
5132 	const struct resource_pool *pool = dc->res_pool;
5133 
5134 	sec_top = sec_pipe->top_pipe;
5135 	sec_bottom = sec_pipe->bottom_pipe;
5136 	sec_next = sec_pipe->next_odm_pipe;
5137 	sec_prev = sec_pipe->prev_odm_pipe;
5138 
5139 	if (pri_pipe == NULL)
5140 		return false;
5141 
5142 	*sec_pipe = *pri_pipe;
5143 
5144 	sec_pipe->top_pipe = sec_top;
5145 	sec_pipe->bottom_pipe = sec_bottom;
5146 	sec_pipe->next_odm_pipe = sec_next;
5147 	sec_pipe->prev_odm_pipe = sec_prev;
5148 
5149 	sec_pipe->pipe_idx = pipe_idx;
5150 	sec_pipe->plane_res.mi = pool->mis[pipe_idx];
5151 	sec_pipe->plane_res.hubp = pool->hubps[pipe_idx];
5152 	sec_pipe->plane_res.ipp = pool->ipps[pipe_idx];
5153 	sec_pipe->plane_res.xfm = pool->transforms[pipe_idx];
5154 	sec_pipe->plane_res.dpp = pool->dpps[pipe_idx];
5155 	sec_pipe->plane_res.mpcc_inst = pool->dpps[pipe_idx]->inst;
5156 	sec_pipe->stream_res.dsc = NULL;
5157 	if (odm) {
5158 		if (!sec_pipe->top_pipe)
5159 			sec_pipe->stream_res.opp = pool->opps[pipe_idx];
5160 		else
5161 			sec_pipe->stream_res.opp = sec_pipe->top_pipe->stream_res.opp;
5162 		if (sec_pipe->stream->timing.flags.DSC == 1) {
5163 #if defined(CONFIG_DRM_AMD_DC_FP)
5164 			dcn20_acquire_dsc(dc, &state->res_ctx, &sec_pipe->stream_res.dsc, sec_pipe->stream_res.opp->inst);
5165 #endif
5166 			ASSERT(sec_pipe->stream_res.dsc);
5167 			if (sec_pipe->stream_res.dsc == NULL)
5168 				return false;
5169 		}
5170 #if defined(CONFIG_DRM_AMD_DC_FP)
5171 		dcn20_build_mapped_resource(dc, state, sec_pipe->stream);
5172 #endif
5173 	}
5174 
5175 	return true;
5176 }
5177 
5178 enum dc_status update_dp_encoder_resources_for_test_harness(const struct dc *dc,
5179 		struct dc_state *context,
5180 		struct pipe_ctx *pipe_ctx)
5181 {
5182 	if (dc->link_srv->dp_get_encoding_format(&pipe_ctx->link_config.dp_link_settings) == DP_128b_132b_ENCODING) {
5183 		if (pipe_ctx->stream_res.hpo_dp_stream_enc == NULL) {
5184 			pipe_ctx->stream_res.hpo_dp_stream_enc =
5185 					find_first_free_match_hpo_dp_stream_enc_for_link(
5186 							&context->res_ctx, dc->res_pool, pipe_ctx->stream);
5187 
5188 			if (!pipe_ctx->stream_res.hpo_dp_stream_enc)
5189 				return DC_NO_STREAM_ENC_RESOURCE;
5190 
5191 			update_hpo_dp_stream_engine_usage(
5192 					&context->res_ctx, dc->res_pool,
5193 					pipe_ctx->stream_res.hpo_dp_stream_enc,
5194 					true);
5195 		}
5196 
5197 		if (pipe_ctx->link_res.hpo_dp_link_enc == NULL) {
5198 			if (!add_hpo_dp_link_enc_to_ctx(&context->res_ctx, dc->res_pool, pipe_ctx, pipe_ctx->stream))
5199 				return DC_NO_LINK_ENC_RESOURCE;
5200 		}
5201 	} else {
5202 		if (pipe_ctx->stream_res.hpo_dp_stream_enc) {
5203 			update_hpo_dp_stream_engine_usage(
5204 					&context->res_ctx, dc->res_pool,
5205 					pipe_ctx->stream_res.hpo_dp_stream_enc,
5206 					false);
5207 			pipe_ctx->stream_res.hpo_dp_stream_enc = NULL;
5208 		}
5209 		if (pipe_ctx->link_res.hpo_dp_link_enc)
5210 			remove_hpo_dp_link_enc_from_ctx(&context->res_ctx, pipe_ctx, pipe_ctx->stream);
5211 	}
5212 
5213 	return DC_OK;
5214 }
5215 
5216 bool check_subvp_sw_cursor_fallback_req(const struct dc *dc, struct dc_stream_state *stream)
5217 {
5218 	if (!dc->debug.disable_subvp_high_refresh && is_subvp_high_refresh_candidate(stream))
5219 		return true;
5220 	if (dc->current_state->stream_count == 1 && stream->timing.v_addressable >= 2880 &&
5221 			((stream->timing.pix_clk_100hz * 100) / stream->timing.v_total / stream->timing.h_total) < 120)
5222 		return true;
5223 	else if (dc->current_state->stream_count > 1 && stream->timing.v_addressable >= 1080 &&
5224 			((stream->timing.pix_clk_100hz * 100) / stream->timing.v_total / stream->timing.h_total) < 120)
5225 		return true;
5226 
5227 	return false;
5228 }
5229 
5230 struct dscl_prog_data *resource_get_dscl_prog_data(struct pipe_ctx *pipe_ctx)
5231 {
5232 	return &pipe_ctx->plane_res.scl_data.dscl_prog_data;
5233 }
5234 
5235 void resource_init_common_dml2_callbacks(struct dc *dc, struct dml2_configuration_options *dml2_options)
5236 {
5237 	dml2_options->callbacks.dc = dc;
5238 	dml2_options->callbacks.build_scaling_params = &resource_build_scaling_params;
5239 	dml2_options->callbacks.build_test_pattern_params = &resource_build_test_pattern_params;
5240 	dml2_options->callbacks.acquire_secondary_pipe_for_mpc_odm = &dc_resource_acquire_secondary_pipe_for_mpc_odm_legacy;
5241 	dml2_options->callbacks.update_pipes_for_stream_with_slice_count = &resource_update_pipes_for_stream_with_slice_count;
5242 	dml2_options->callbacks.update_pipes_for_plane_with_slice_count = &resource_update_pipes_for_plane_with_slice_count;
5243 	dml2_options->callbacks.get_mpc_slice_index = &resource_get_mpc_slice_index;
5244 	dml2_options->callbacks.get_mpc_slice_count = &resource_get_mpc_slice_count;
5245 	dml2_options->callbacks.get_odm_slice_index = &resource_get_odm_slice_index;
5246 	dml2_options->callbacks.get_odm_slice_count = &resource_get_odm_slice_count;
5247 	dml2_options->callbacks.get_opp_head = &resource_get_opp_head;
5248 	dml2_options->callbacks.get_otg_master_for_stream = &resource_get_otg_master_for_stream;
5249 	dml2_options->callbacks.get_opp_heads_for_otg_master = &resource_get_opp_heads_for_otg_master;
5250 	dml2_options->callbacks.get_dpp_pipes_for_plane = &resource_get_dpp_pipes_for_plane;
5251 	dml2_options->callbacks.get_stream_status = &dc_state_get_stream_status;
5252 	dml2_options->callbacks.get_stream_from_id = &dc_state_get_stream_from_id;
5253 	dml2_options->callbacks.get_max_flickerless_instant_vtotal_increase = &dc_stream_get_max_flickerless_instant_vtotal_increase;
5254 
5255 	dml2_options->svp_pstate.callbacks.dc = dc;
5256 	dml2_options->svp_pstate.callbacks.add_phantom_plane = &dc_state_add_phantom_plane;
5257 	dml2_options->svp_pstate.callbacks.add_phantom_stream = &dc_state_add_phantom_stream;
5258 	dml2_options->svp_pstate.callbacks.build_scaling_params = &resource_build_scaling_params;
5259 	dml2_options->svp_pstate.callbacks.create_phantom_plane = &dc_state_create_phantom_plane;
5260 	dml2_options->svp_pstate.callbacks.remove_phantom_plane = &dc_state_remove_phantom_plane;
5261 	dml2_options->svp_pstate.callbacks.remove_phantom_stream = &dc_state_remove_phantom_stream;
5262 	dml2_options->svp_pstate.callbacks.create_phantom_stream = &dc_state_create_phantom_stream;
5263 	dml2_options->svp_pstate.callbacks.release_phantom_plane = &dc_state_release_phantom_plane;
5264 	dml2_options->svp_pstate.callbacks.release_phantom_stream = &dc_state_release_phantom_stream;
5265 	dml2_options->svp_pstate.callbacks.get_pipe_subvp_type = &dc_state_get_pipe_subvp_type;
5266 	dml2_options->svp_pstate.callbacks.get_stream_subvp_type = &dc_state_get_stream_subvp_type;
5267 	dml2_options->svp_pstate.callbacks.get_paired_subvp_stream = &dc_state_get_paired_subvp_stream;
5268 	dml2_options->svp_pstate.callbacks.remove_phantom_streams_and_planes = &dc_state_remove_phantom_streams_and_planes;
5269 	dml2_options->svp_pstate.callbacks.release_phantom_streams_and_planes = &dc_state_release_phantom_streams_and_planes;
5270 }
5271 
5272 /* Returns number of DET segments allocated for a given OTG_MASTER pipe */
5273 int resource_calculate_det_for_stream(struct dc_state *state, struct pipe_ctx *otg_master)
5274 {
5275 	struct pipe_ctx *opp_heads[MAX_PIPES];
5276 	struct pipe_ctx *dpp_pipes[MAX_PIPES];
5277 
5278 	int dpp_count = 0;
5279 	int det_segments = 0;
5280 
5281 	if (!otg_master->stream)
5282 		return 0;
5283 
5284 	int slice_count = resource_get_opp_heads_for_otg_master(otg_master,
5285 			&state->res_ctx, opp_heads);
5286 
5287 	for (int slice_idx = 0; slice_idx < slice_count; slice_idx++) {
5288 		if (opp_heads[slice_idx]->plane_state) {
5289 			dpp_count = resource_get_dpp_pipes_for_opp_head(
5290 					opp_heads[slice_idx],
5291 					&state->res_ctx,
5292 					dpp_pipes);
5293 			for (int dpp_idx = 0; dpp_idx < dpp_count; dpp_idx++)
5294 				det_segments += dpp_pipes[dpp_idx]->hubp_regs.det_size;
5295 		}
5296 	}
5297 	return det_segments;
5298 }
5299 
5300 bool resource_is_hpo_acquired(struct dc_state *context)
5301 {
5302 	int i;
5303 
5304 	for (i = 0; i < MAX_HPO_DP2_ENCODERS; i++) {
5305 		if (context->res_ctx.is_hpo_dp_stream_enc_acquired[i]) {
5306 			return true;
5307 		}
5308 	}
5309 
5310 	return false;
5311 }
5312