1 /*
2  * Copyright 2016 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 #include "dc.h"
28 #include "mod_freesync.h"
29 #include "core_types.h"
30 
31 #define MOD_FREESYNC_MAX_CONCURRENT_STREAMS  32
32 
33 #define MIN_REFRESH_RANGE 10
34 /* Refresh rate ramp at a fixed rate of 65 Hz/second */
35 #define STATIC_SCREEN_RAMP_DELTA_REFRESH_RATE_PER_FRAME ((1000 / 60) * 65)
36 /* Number of elements in the render times cache array */
37 #define RENDER_TIMES_MAX_COUNT 10
38 /* Threshold to exit/exit BTR (to avoid frequent enter-exits at the lower limit) */
39 #define BTR_MAX_MARGIN 2500
40 /* Threshold to change BTR multiplier (to avoid frequent changes) */
41 #define BTR_DRIFT_MARGIN 2000
42 /* Threshold to exit fixed refresh rate */
43 #define FIXED_REFRESH_EXIT_MARGIN_IN_HZ 1
44 /* Number of consecutive frames to check before entering/exiting fixed refresh */
45 #define FIXED_REFRESH_ENTER_FRAME_COUNT 5
46 #define FIXED_REFRESH_EXIT_FRAME_COUNT 10
47 /* Flip interval workaround constants */
48 #define VSYNCS_BETWEEN_FLIP_THRESHOLD 2
49 #define FREESYNC_CONSEC_FLIP_AFTER_VSYNC 5
50 #define FREESYNC_VSYNC_TO_FLIP_DELTA_IN_US 500
51 
52 struct core_freesync {
53 	struct mod_freesync public;
54 	struct dc *dc;
55 };
56 
57 #define MOD_FREESYNC_TO_CORE(mod_freesync)\
58 		container_of(mod_freesync, struct core_freesync, public)
59 
60 struct mod_freesync *mod_freesync_create(struct dc *dc)
61 {
62 	struct core_freesync *core_freesync =
63 			kzalloc(sizeof(struct core_freesync), GFP_KERNEL);
64 
65 	if (core_freesync == NULL)
66 		goto fail_alloc_context;
67 
68 	if (dc == NULL)
69 		goto fail_construct;
70 
71 	core_freesync->dc = dc;
72 	return &core_freesync->public;
73 
74 fail_construct:
75 	kfree(core_freesync);
76 
77 fail_alloc_context:
78 	return NULL;
79 }
80 
81 void mod_freesync_destroy(struct mod_freesync *mod_freesync)
82 {
83 	struct core_freesync *core_freesync = NULL;
84 	if (mod_freesync == NULL)
85 		return;
86 	core_freesync = MOD_FREESYNC_TO_CORE(mod_freesync);
87 	kfree(core_freesync);
88 }
89 
90 #if 0 /* Unused currently */
91 static unsigned int calc_refresh_in_uhz_from_duration(
92 		unsigned int duration_in_ns)
93 {
94 	unsigned int refresh_in_uhz =
95 			((unsigned int)(div64_u64((1000000000ULL * 1000000),
96 					duration_in_ns)));
97 	return refresh_in_uhz;
98 }
99 #endif
100 
101 static unsigned int calc_duration_in_us_from_refresh_in_uhz(
102 		unsigned int refresh_in_uhz)
103 {
104 	unsigned int duration_in_us =
105 			((unsigned int)(div64_u64((1000000000ULL * 1000),
106 					refresh_in_uhz)));
107 	return duration_in_us;
108 }
109 
110 static unsigned int calc_duration_in_us_from_v_total(
111 		const struct dc_stream_state *stream,
112 		const struct mod_vrr_params *in_vrr,
113 		unsigned int v_total)
114 {
115 	unsigned int duration_in_us =
116 			(unsigned int)(div64_u64(((unsigned long long)(v_total)
117 				* 10000) * stream->timing.h_total,
118 					stream->timing.pix_clk_100hz));
119 
120 	return duration_in_us;
121 }
122 
123 unsigned int mod_freesync_calc_v_total_from_refresh(
124 		const struct dc_stream_state *stream,
125 		unsigned int refresh_in_uhz)
126 {
127 	unsigned int v_total;
128 	unsigned int frame_duration_in_ns;
129 
130 	frame_duration_in_ns =
131 			((unsigned int)(div64_u64((1000000000ULL * 1000000),
132 					refresh_in_uhz)));
133 
134 	v_total = div64_u64(div64_u64(((unsigned long long)(
135 			frame_duration_in_ns) * (stream->timing.pix_clk_100hz / 10)),
136 			stream->timing.h_total), 1000000);
137 
138 	/* v_total cannot be less than nominal */
139 	if (v_total < stream->timing.v_total) {
140 		ASSERT(v_total < stream->timing.v_total);
141 		v_total = stream->timing.v_total;
142 	}
143 
144 	return v_total;
145 }
146 
147 static unsigned int calc_v_total_from_duration(
148 		const struct dc_stream_state *stream,
149 		const struct mod_vrr_params *vrr,
150 		unsigned int duration_in_us)
151 {
152 	unsigned int v_total = 0;
153 
154 	if (duration_in_us < vrr->min_duration_in_us)
155 		duration_in_us = vrr->min_duration_in_us;
156 
157 	if (duration_in_us > vrr->max_duration_in_us)
158 		duration_in_us = vrr->max_duration_in_us;
159 
160 	if (dc_is_hdmi_signal(stream->signal)) {
161 		uint32_t h_total_up_scaled;
162 
163 		h_total_up_scaled = stream->timing.h_total * 10000;
164 		v_total = div_u64((unsigned long long)duration_in_us
165 					* stream->timing.pix_clk_100hz + (h_total_up_scaled - 1),
166 					h_total_up_scaled);
167 	} else {
168 		v_total = div64_u64(div64_u64(((unsigned long long)(
169 					duration_in_us) * (stream->timing.pix_clk_100hz / 10)),
170 					stream->timing.h_total), 1000);
171 	}
172 
173 	/* v_total cannot be less than nominal */
174 	if (v_total < stream->timing.v_total) {
175 		ASSERT(v_total < stream->timing.v_total);
176 		v_total = stream->timing.v_total;
177 	}
178 
179 	return v_total;
180 }
181 
182 static void update_v_total_for_static_ramp(
183 		struct core_freesync *core_freesync,
184 		const struct dc_stream_state *stream,
185 		struct mod_vrr_params *in_out_vrr)
186 {
187 	unsigned int v_total = 0;
188 	unsigned int current_duration_in_us =
189 			calc_duration_in_us_from_v_total(
190 				stream, in_out_vrr,
191 				in_out_vrr->adjust.v_total_max);
192 	unsigned int target_duration_in_us =
193 			calc_duration_in_us_from_refresh_in_uhz(
194 				in_out_vrr->fixed.target_refresh_in_uhz);
195 	bool ramp_direction_is_up = (current_duration_in_us >
196 				target_duration_in_us) ? true : false;
197 
198 	/* Calculate ratio between new and current frame duration with 3 digit */
199 	unsigned int frame_duration_ratio = div64_u64(1000000,
200 		(1000 +  div64_u64(((unsigned long long)(
201 		STATIC_SCREEN_RAMP_DELTA_REFRESH_RATE_PER_FRAME) *
202 		current_duration_in_us),
203 		1000000)));
204 
205 	/* Calculate delta between new and current frame duration in us */
206 	unsigned int frame_duration_delta = div64_u64(((unsigned long long)(
207 		current_duration_in_us) *
208 		(1000 - frame_duration_ratio)), 1000);
209 
210 	/* Adjust frame duration delta based on ratio between current and
211 	 * standard frame duration (frame duration at 60 Hz refresh rate).
212 	 */
213 	unsigned int ramp_rate_interpolated = div64_u64(((unsigned long long)(
214 		frame_duration_delta) * current_duration_in_us), 16666);
215 
216 	/* Going to a higher refresh rate (lower frame duration) */
217 	if (ramp_direction_is_up) {
218 		/* Reduce frame duration */
219 		current_duration_in_us -= ramp_rate_interpolated;
220 
221 		/* Adjust for frame duration below min */
222 		if (current_duration_in_us <= target_duration_in_us) {
223 			in_out_vrr->fixed.ramping_active = false;
224 			in_out_vrr->fixed.ramping_done = true;
225 			current_duration_in_us =
226 				calc_duration_in_us_from_refresh_in_uhz(
227 				in_out_vrr->fixed.target_refresh_in_uhz);
228 		}
229 	/* Going to a lower refresh rate (larger frame duration) */
230 	} else {
231 		/* Increase frame duration */
232 		current_duration_in_us += ramp_rate_interpolated;
233 
234 		/* Adjust for frame duration above max */
235 		if (current_duration_in_us >= target_duration_in_us) {
236 			in_out_vrr->fixed.ramping_active = false;
237 			in_out_vrr->fixed.ramping_done = true;
238 			current_duration_in_us =
239 				calc_duration_in_us_from_refresh_in_uhz(
240 				in_out_vrr->fixed.target_refresh_in_uhz);
241 		}
242 	}
243 
244 	v_total = div64_u64(div64_u64(((unsigned long long)(
245 			current_duration_in_us) * (stream->timing.pix_clk_100hz / 10)),
246 				stream->timing.h_total), 1000);
247 
248 	/* v_total cannot be less than nominal */
249 	if (v_total < stream->timing.v_total)
250 		v_total = stream->timing.v_total;
251 
252 	in_out_vrr->adjust.v_total_min = v_total;
253 	in_out_vrr->adjust.v_total_max = v_total;
254 }
255 
256 static void apply_below_the_range(struct core_freesync *core_freesync,
257 		const struct dc_stream_state *stream,
258 		unsigned int last_render_time_in_us,
259 		struct mod_vrr_params *in_out_vrr)
260 {
261 	unsigned int inserted_frame_duration_in_us = 0;
262 	unsigned int mid_point_frames_ceil = 0;
263 	unsigned int mid_point_frames_floor = 0;
264 	unsigned int frame_time_in_us = 0;
265 	unsigned int delta_from_mid_point_in_us_1 = 0xFFFFFFFF;
266 	unsigned int delta_from_mid_point_in_us_2 = 0xFFFFFFFF;
267 	unsigned int frames_to_insert = 0;
268 	unsigned int delta_from_mid_point_delta_in_us;
269 	unsigned int max_render_time_in_us =
270 			in_out_vrr->max_duration_in_us - in_out_vrr->btr.margin_in_us;
271 
272 	/* Program BTR */
273 	if ((last_render_time_in_us + in_out_vrr->btr.margin_in_us / 2) < max_render_time_in_us) {
274 		/* Exit Below the Range */
275 		if (in_out_vrr->btr.btr_active) {
276 			in_out_vrr->btr.frame_counter = 0;
277 			in_out_vrr->btr.btr_active = false;
278 		}
279 	} else if (last_render_time_in_us > (max_render_time_in_us + in_out_vrr->btr.margin_in_us / 2)) {
280 		/* Enter Below the Range */
281 		if (!in_out_vrr->btr.btr_active) {
282 			in_out_vrr->btr.btr_active = true;
283 		}
284 	}
285 
286 	/* BTR set to "not active" so disengage */
287 	if (!in_out_vrr->btr.btr_active) {
288 		in_out_vrr->btr.inserted_duration_in_us = 0;
289 		in_out_vrr->btr.frames_to_insert = 0;
290 		in_out_vrr->btr.frame_counter = 0;
291 
292 		/* Restore FreeSync */
293 		in_out_vrr->adjust.v_total_min =
294 			mod_freesync_calc_v_total_from_refresh(stream,
295 				in_out_vrr->max_refresh_in_uhz);
296 		in_out_vrr->adjust.v_total_max =
297 			mod_freesync_calc_v_total_from_refresh(stream,
298 				in_out_vrr->min_refresh_in_uhz);
299 	/* BTR set to "active" so engage */
300 	} else {
301 
302 		/* Calculate number of midPoint frames that could fit within
303 		 * the render time interval - take ceil of this value
304 		 */
305 		mid_point_frames_ceil = (last_render_time_in_us +
306 				in_out_vrr->btr.mid_point_in_us - 1) /
307 					in_out_vrr->btr.mid_point_in_us;
308 
309 		if (mid_point_frames_ceil > 0) {
310 			frame_time_in_us = last_render_time_in_us /
311 				mid_point_frames_ceil;
312 			delta_from_mid_point_in_us_1 =
313 				(in_out_vrr->btr.mid_point_in_us >
314 				frame_time_in_us) ?
315 				(in_out_vrr->btr.mid_point_in_us - frame_time_in_us) :
316 				(frame_time_in_us - in_out_vrr->btr.mid_point_in_us);
317 		}
318 
319 		/* Calculate number of midPoint frames that could fit within
320 		 * the render time interval - take floor of this value
321 		 */
322 		mid_point_frames_floor = last_render_time_in_us /
323 				in_out_vrr->btr.mid_point_in_us;
324 
325 		if (mid_point_frames_floor > 0) {
326 
327 			frame_time_in_us = last_render_time_in_us /
328 				mid_point_frames_floor;
329 			delta_from_mid_point_in_us_2 =
330 				(in_out_vrr->btr.mid_point_in_us >
331 				frame_time_in_us) ?
332 				(in_out_vrr->btr.mid_point_in_us - frame_time_in_us) :
333 				(frame_time_in_us - in_out_vrr->btr.mid_point_in_us);
334 		}
335 
336 		/* Choose number of frames to insert based on how close it
337 		 * can get to the mid point of the variable range.
338 		 *  - Delta for CEIL: delta_from_mid_point_in_us_1
339 		 *  - Delta for FLOOR: delta_from_mid_point_in_us_2
340 		 */
341 		if ((last_render_time_in_us / mid_point_frames_ceil) < in_out_vrr->min_duration_in_us) {
342 			/* Check for out of range.
343 			 * If using CEIL produces a value that is out of range,
344 			 * then we are forced to use FLOOR.
345 			 */
346 			frames_to_insert = mid_point_frames_floor;
347 		} else if (mid_point_frames_floor < 2) {
348 			/* Check if FLOOR would result in non-LFC. In this case
349 			 * choose to use CEIL
350 			 */
351 			frames_to_insert = mid_point_frames_ceil;
352 		} else if (delta_from_mid_point_in_us_1 < delta_from_mid_point_in_us_2) {
353 			/* If choosing CEIL results in a frame duration that is
354 			 * closer to the mid point of the range.
355 			 * Choose CEIL
356 			 */
357 			frames_to_insert = mid_point_frames_ceil;
358 		} else {
359 			/* If choosing FLOOR results in a frame duration that is
360 			 * closer to the mid point of the range.
361 			 * Choose FLOOR
362 			 */
363 			frames_to_insert = mid_point_frames_floor;
364 		}
365 
366 		/* Prefer current frame multiplier when BTR is enabled unless it drifts
367 		 * too far from the midpoint
368 		 */
369 		if (delta_from_mid_point_in_us_1 < delta_from_mid_point_in_us_2) {
370 			delta_from_mid_point_delta_in_us = delta_from_mid_point_in_us_2 -
371 					delta_from_mid_point_in_us_1;
372 		} else {
373 			delta_from_mid_point_delta_in_us = delta_from_mid_point_in_us_1 -
374 					delta_from_mid_point_in_us_2;
375 		}
376 		if (in_out_vrr->btr.frames_to_insert != 0 &&
377 				delta_from_mid_point_delta_in_us < BTR_DRIFT_MARGIN) {
378 			if (((last_render_time_in_us / in_out_vrr->btr.frames_to_insert) <
379 					max_render_time_in_us) &&
380 				((last_render_time_in_us / in_out_vrr->btr.frames_to_insert) >
381 					in_out_vrr->min_duration_in_us))
382 				frames_to_insert = in_out_vrr->btr.frames_to_insert;
383 		}
384 
385 		/* Either we've calculated the number of frames to insert,
386 		 * or we need to insert min duration frames
387 		 */
388 		if (last_render_time_in_us / frames_to_insert <
389 				in_out_vrr->min_duration_in_us){
390 			frames_to_insert -= (frames_to_insert > 1) ?
391 					1 : 0;
392 		}
393 
394 		if (frames_to_insert > 0)
395 			inserted_frame_duration_in_us = last_render_time_in_us /
396 							frames_to_insert;
397 
398 		if (inserted_frame_duration_in_us < in_out_vrr->min_duration_in_us)
399 			inserted_frame_duration_in_us = in_out_vrr->min_duration_in_us;
400 
401 		/* Cache the calculated variables */
402 		in_out_vrr->btr.inserted_duration_in_us =
403 			inserted_frame_duration_in_us;
404 		in_out_vrr->btr.frames_to_insert = frames_to_insert;
405 		in_out_vrr->btr.frame_counter = frames_to_insert;
406 	}
407 }
408 
409 static void apply_fixed_refresh(struct core_freesync *core_freesync,
410 		const struct dc_stream_state *stream,
411 		unsigned int last_render_time_in_us,
412 		struct mod_vrr_params *in_out_vrr)
413 {
414 	bool update = false;
415 	unsigned int max_render_time_in_us = in_out_vrr->max_duration_in_us;
416 
417 	/* Compute the exit refresh rate and exit frame duration */
418 	unsigned int exit_refresh_rate_in_milli_hz = ((1000000000/max_render_time_in_us)
419 			+ (1000*FIXED_REFRESH_EXIT_MARGIN_IN_HZ));
420 	unsigned int exit_frame_duration_in_us = 1000000000/exit_refresh_rate_in_milli_hz;
421 
422 	if (last_render_time_in_us < exit_frame_duration_in_us) {
423 		/* Exit Fixed Refresh mode */
424 		if (in_out_vrr->fixed.fixed_active) {
425 			in_out_vrr->fixed.frame_counter++;
426 
427 			if (in_out_vrr->fixed.frame_counter >
428 					FIXED_REFRESH_EXIT_FRAME_COUNT) {
429 				in_out_vrr->fixed.frame_counter = 0;
430 				in_out_vrr->fixed.fixed_active = false;
431 				in_out_vrr->fixed.target_refresh_in_uhz = 0;
432 				update = true;
433 			}
434 		} else
435 			in_out_vrr->fixed.frame_counter = 0;
436 	} else if (last_render_time_in_us > max_render_time_in_us) {
437 		/* Enter Fixed Refresh mode */
438 		if (!in_out_vrr->fixed.fixed_active) {
439 			in_out_vrr->fixed.frame_counter++;
440 
441 			if (in_out_vrr->fixed.frame_counter >
442 					FIXED_REFRESH_ENTER_FRAME_COUNT) {
443 				in_out_vrr->fixed.frame_counter = 0;
444 				in_out_vrr->fixed.fixed_active = true;
445 				in_out_vrr->fixed.target_refresh_in_uhz =
446 						in_out_vrr->max_refresh_in_uhz;
447 				update = true;
448 			}
449 		} else
450 			in_out_vrr->fixed.frame_counter = 0;
451 	}
452 
453 	if (update) {
454 		if (in_out_vrr->fixed.fixed_active) {
455 			in_out_vrr->adjust.v_total_min =
456 				mod_freesync_calc_v_total_from_refresh(
457 				stream, in_out_vrr->max_refresh_in_uhz);
458 			in_out_vrr->adjust.v_total_max =
459 					in_out_vrr->adjust.v_total_min;
460 		} else {
461 			in_out_vrr->adjust.v_total_min =
462 				mod_freesync_calc_v_total_from_refresh(stream,
463 					in_out_vrr->max_refresh_in_uhz);
464 			in_out_vrr->adjust.v_total_max =
465 				mod_freesync_calc_v_total_from_refresh(stream,
466 					in_out_vrr->min_refresh_in_uhz);
467 		}
468 	}
469 }
470 
471 static void determine_flip_interval_workaround_req(struct mod_vrr_params *in_vrr,
472 		unsigned int curr_time_stamp_in_us)
473 {
474 	in_vrr->flip_interval.vsync_to_flip_in_us = curr_time_stamp_in_us -
475 			in_vrr->flip_interval.v_update_timestamp_in_us;
476 
477 	/* Determine conditions for stopping workaround */
478 	if (in_vrr->flip_interval.flip_interval_workaround_active &&
479 			in_vrr->flip_interval.vsyncs_between_flip < VSYNCS_BETWEEN_FLIP_THRESHOLD &&
480 			in_vrr->flip_interval.vsync_to_flip_in_us > FREESYNC_VSYNC_TO_FLIP_DELTA_IN_US) {
481 		in_vrr->flip_interval.flip_interval_detect_counter = 0;
482 		in_vrr->flip_interval.program_flip_interval_workaround = true;
483 		in_vrr->flip_interval.flip_interval_workaround_active = false;
484 	} else {
485 		/* Determine conditions for starting workaround */
486 		if (in_vrr->flip_interval.vsyncs_between_flip >= VSYNCS_BETWEEN_FLIP_THRESHOLD &&
487 				in_vrr->flip_interval.vsync_to_flip_in_us < FREESYNC_VSYNC_TO_FLIP_DELTA_IN_US) {
488 			/* Increase flip interval counter we have 2 vsyncs between flips and
489 			 * vsync to flip interval is less than 500us
490 			 */
491 			in_vrr->flip_interval.flip_interval_detect_counter++;
492 			if (in_vrr->flip_interval.flip_interval_detect_counter > FREESYNC_CONSEC_FLIP_AFTER_VSYNC) {
493 				/* Start workaround if we detect 5 consecutive instances of the above case */
494 				in_vrr->flip_interval.program_flip_interval_workaround = true;
495 				in_vrr->flip_interval.flip_interval_workaround_active = true;
496 			}
497 		} else {
498 			/* Reset the flip interval counter if we condition is no longer met */
499 			in_vrr->flip_interval.flip_interval_detect_counter = 0;
500 		}
501 	}
502 
503 	in_vrr->flip_interval.vsyncs_between_flip = 0;
504 }
505 
506 static bool vrr_settings_require_update(struct core_freesync *core_freesync,
507 		struct mod_freesync_config *in_config,
508 		unsigned int min_refresh_in_uhz,
509 		unsigned int max_refresh_in_uhz,
510 		struct mod_vrr_params *in_vrr)
511 {
512 	if (in_vrr->state != in_config->state) {
513 		return true;
514 	} else if (in_vrr->state == VRR_STATE_ACTIVE_FIXED &&
515 			in_vrr->fixed.target_refresh_in_uhz !=
516 					in_config->fixed_refresh_in_uhz) {
517 		return true;
518 	} else if (in_vrr->min_refresh_in_uhz != min_refresh_in_uhz) {
519 		return true;
520 	} else if (in_vrr->max_refresh_in_uhz != max_refresh_in_uhz) {
521 		return true;
522 	}
523 
524 	return false;
525 }
526 
527 bool mod_freesync_get_vmin_vmax(struct mod_freesync *mod_freesync,
528 		const struct dc_stream_state *stream,
529 		unsigned int *vmin,
530 		unsigned int *vmax)
531 {
532 	*vmin = stream->adjust.v_total_min;
533 	*vmax = stream->adjust.v_total_max;
534 
535 	return true;
536 }
537 
538 bool mod_freesync_get_v_position(struct mod_freesync *mod_freesync,
539 		struct dc_stream_state *stream,
540 		unsigned int *nom_v_pos,
541 		unsigned int *v_pos)
542 {
543 	struct core_freesync *core_freesync = NULL;
544 	struct crtc_position position;
545 
546 	if (mod_freesync == NULL)
547 		return false;
548 
549 	core_freesync = MOD_FREESYNC_TO_CORE(mod_freesync);
550 
551 	if (dc_stream_get_crtc_position(core_freesync->dc, &stream, 1,
552 					&position.vertical_count,
553 					&position.nominal_vcount)) {
554 
555 		*nom_v_pos = position.nominal_vcount;
556 		*v_pos = position.vertical_count;
557 
558 		return true;
559 	}
560 
561 	return false;
562 }
563 
564 static void build_vrr_infopacket_data_v1(const struct mod_vrr_params *vrr,
565 		struct dc_info_packet *infopacket,
566 		bool freesync_on_desktop)
567 {
568 	/* PB1 = 0x1A (24bit AMD IEEE OUI (0x00001A) - Byte 0) */
569 	infopacket->sb[1] = 0x1A;
570 
571 	/* PB2 = 0x00 (24bit AMD IEEE OUI (0x00001A) - Byte 1) */
572 	infopacket->sb[2] = 0x00;
573 
574 	/* PB3 = 0x00 (24bit AMD IEEE OUI (0x00001A) - Byte 2) */
575 	infopacket->sb[3] = 0x00;
576 
577 	/* PB4 = Reserved */
578 
579 	/* PB5 = Reserved */
580 
581 	/* PB6 = [Bits 7:3 = Reserved] */
582 
583 	/* PB6 = [Bit 0 = FreeSync Supported] */
584 	if (vrr->state != VRR_STATE_UNSUPPORTED)
585 		infopacket->sb[6] |= 0x01;
586 
587 	/* PB6 = [Bit 1 = FreeSync Enabled] */
588 	if (vrr->state != VRR_STATE_DISABLED &&
589 			vrr->state != VRR_STATE_UNSUPPORTED)
590 		infopacket->sb[6] |= 0x02;
591 
592 	if (freesync_on_desktop) {
593 		/* PB6 = [Bit 2 = FreeSync Active] */
594 		if (vrr->state != VRR_STATE_DISABLED &&
595 			vrr->state != VRR_STATE_UNSUPPORTED)
596 			infopacket->sb[6] |= 0x04;
597 	} else {
598 		if (vrr->state == VRR_STATE_ACTIVE_VARIABLE ||
599 			vrr->state == VRR_STATE_ACTIVE_FIXED)
600 			infopacket->sb[6] |= 0x04;
601 	}
602 
603 	// For v1 & 2 infoframes program nominal if non-fs mode, otherwise full range
604 	/* PB7 = FreeSync Minimum refresh rate (Hz) */
605 	if (vrr->state == VRR_STATE_ACTIVE_VARIABLE ||
606 			vrr->state == VRR_STATE_ACTIVE_FIXED) {
607 		infopacket->sb[7] = (unsigned char)((vrr->min_refresh_in_uhz + 500000) / 1000000);
608 	} else {
609 		infopacket->sb[7] = (unsigned char)((vrr->max_refresh_in_uhz + 500000) / 1000000);
610 	}
611 
612 	/* PB8 = FreeSync Maximum refresh rate (Hz)
613 	 * Note: We should never go above the field rate of the mode timing set.
614 	 */
615 	infopacket->sb[8] = (unsigned char)((vrr->max_refresh_in_uhz + 500000) / 1000000);
616 
617 	/* FreeSync HDR */
618 	infopacket->sb[9] = 0;
619 	infopacket->sb[10] = 0;
620 }
621 
622 static void build_vrr_infopacket_data_v3(const struct mod_vrr_params *vrr,
623 		struct dc_info_packet *infopacket)
624 {
625 	unsigned int min_refresh;
626 	unsigned int max_refresh;
627 	unsigned int fixed_refresh;
628 	unsigned int min_programmed;
629 	unsigned int max_programmed;
630 
631 	/* PB1 = 0x1A (24bit AMD IEEE OUI (0x00001A) - Byte 0) */
632 	infopacket->sb[1] = 0x1A;
633 
634 	/* PB2 = 0x00 (24bit AMD IEEE OUI (0x00001A) - Byte 1) */
635 	infopacket->sb[2] = 0x00;
636 
637 	/* PB3 = 0x00 (24bit AMD IEEE OUI (0x00001A) - Byte 2) */
638 	infopacket->sb[3] = 0x00;
639 
640 	/* PB4 = Reserved */
641 
642 	/* PB5 = Reserved */
643 
644 	/* PB6 = [Bits 7:3 = Reserved] */
645 
646 	/* PB6 = [Bit 0 = FreeSync Supported] */
647 	if (vrr->state != VRR_STATE_UNSUPPORTED)
648 		infopacket->sb[6] |= 0x01;
649 
650 	/* PB6 = [Bit 1 = FreeSync Enabled] */
651 	if (vrr->state != VRR_STATE_DISABLED &&
652 			vrr->state != VRR_STATE_UNSUPPORTED)
653 		infopacket->sb[6] |= 0x02;
654 
655 	/* PB6 = [Bit 2 = FreeSync Active] */
656 	if (vrr->state == VRR_STATE_ACTIVE_VARIABLE ||
657 			vrr->state == VRR_STATE_ACTIVE_FIXED)
658 		infopacket->sb[6] |= 0x04;
659 
660 	min_refresh = (vrr->min_refresh_in_uhz + 500000) / 1000000;
661 	max_refresh = (vrr->max_refresh_in_uhz + 500000) / 1000000;
662 	fixed_refresh = (vrr->fixed_refresh_in_uhz + 500000) / 1000000;
663 
664 	min_programmed = (vrr->state == VRR_STATE_ACTIVE_FIXED) ? fixed_refresh :
665 			(vrr->state == VRR_STATE_ACTIVE_VARIABLE) ? min_refresh :
666 			(vrr->state == VRR_STATE_INACTIVE) ? min_refresh :
667 			max_refresh; // Non-fs case, program nominal range
668 
669 	max_programmed = (vrr->state == VRR_STATE_ACTIVE_FIXED) ? fixed_refresh :
670 			(vrr->state == VRR_STATE_ACTIVE_VARIABLE) ? max_refresh :
671 			max_refresh;// Non-fs case, program nominal range
672 
673 	/* PB7 = FreeSync Minimum refresh rate (Hz) */
674 	infopacket->sb[7] = min_programmed & 0xFF;
675 
676 	/* PB8 = FreeSync Maximum refresh rate (Hz) */
677 	infopacket->sb[8] = max_programmed & 0xFF;
678 
679 	/* PB11 : MSB FreeSync Minimum refresh rate [Hz] - bits 9:8 */
680 	infopacket->sb[11] = (min_programmed >> 8) & 0x03;
681 
682 	/* PB12 : MSB FreeSync Maximum refresh rate [Hz] - bits 9:8 */
683 	infopacket->sb[12] = (max_programmed >> 8) & 0x03;
684 
685 	/* PB16 : Reserved bits 7:1, FixedRate bit 0 */
686 	infopacket->sb[16] = (vrr->state == VRR_STATE_ACTIVE_FIXED) ? 1 : 0;
687 
688 	//FreeSync HDR
689 	infopacket->sb[9] = 0;
690 	infopacket->sb[10] = 0;
691 }
692 
693 static void build_vrr_infopacket_fs2_data(enum color_transfer_func app_tf,
694 		struct dc_info_packet *infopacket)
695 {
696 	if (app_tf != TRANSFER_FUNC_UNKNOWN) {
697 		infopacket->valid = true;
698 
699 		infopacket->sb[6] |= 0x08;  // PB6 = [Bit 3 = Native Color Active]
700 
701 		if (app_tf == TRANSFER_FUNC_GAMMA_22) {
702 			infopacket->sb[9] |= 0x04;  // PB6 = [Bit 2 = Gamma 2.2 EOTF Active]
703 		}
704 	}
705 }
706 
707 static void build_vrr_infopacket_header_v1(enum signal_type signal,
708 		struct dc_info_packet *infopacket,
709 		unsigned int *payload_size)
710 {
711 	if (dc_is_hdmi_signal(signal)) {
712 
713 		/* HEADER */
714 
715 		/* HB0  = Packet Type = 0x83 (Source Product
716 		 *	  Descriptor InfoFrame)
717 		 */
718 		infopacket->hb0 = DC_HDMI_INFOFRAME_TYPE_SPD;
719 
720 		/* HB1  = Version = 0x01 */
721 		infopacket->hb1 = 0x01;
722 
723 		/* HB2  = [Bits 7:5 = 0] [Bits 4:0 = Length = 0x08] */
724 		infopacket->hb2 = 0x08;
725 
726 		*payload_size = 0x08;
727 
728 	} else if (dc_is_dp_signal(signal)) {
729 
730 		/* HEADER */
731 
732 		/* HB0  = Secondary-data Packet ID = 0 - Only non-zero
733 		 *	  when used to associate audio related info packets
734 		 */
735 		infopacket->hb0 = 0x00;
736 
737 		/* HB1  = Packet Type = 0x83 (Source Product
738 		 *	  Descriptor InfoFrame)
739 		 */
740 		infopacket->hb1 = DC_HDMI_INFOFRAME_TYPE_SPD;
741 
742 		/* HB2  = [Bits 7:0 = Least significant eight bits -
743 		 *	  For INFOFRAME, the value must be 1Bh]
744 		 */
745 		infopacket->hb2 = 0x1B;
746 
747 		/* HB3  = [Bits 7:2 = INFOFRAME SDP Version Number = 0x1]
748 		 *	  [Bits 1:0 = Most significant two bits = 0x00]
749 		 */
750 		infopacket->hb3 = 0x04;
751 
752 		*payload_size = 0x1B;
753 	}
754 }
755 
756 static void build_vrr_infopacket_header_v2(enum signal_type signal,
757 		struct dc_info_packet *infopacket,
758 		unsigned int *payload_size)
759 {
760 	if (dc_is_hdmi_signal(signal)) {
761 
762 		/* HEADER */
763 
764 		/* HB0  = Packet Type = 0x83 (Source Product
765 		 *	  Descriptor InfoFrame)
766 		 */
767 		infopacket->hb0 = DC_HDMI_INFOFRAME_TYPE_SPD;
768 
769 		/* HB1  = Version = 0x02 */
770 		infopacket->hb1 = 0x02;
771 
772 		/* HB2  = [Bits 7:5 = 0] [Bits 4:0 = Length = 0x09] */
773 		infopacket->hb2 = 0x09;
774 
775 		*payload_size = 0x0A;
776 
777 	} else if (dc_is_dp_signal(signal)) {
778 
779 		/* HEADER */
780 
781 		/* HB0  = Secondary-data Packet ID = 0 - Only non-zero
782 		 *	  when used to associate audio related info packets
783 		 */
784 		infopacket->hb0 = 0x00;
785 
786 		/* HB1  = Packet Type = 0x83 (Source Product
787 		 *	  Descriptor InfoFrame)
788 		 */
789 		infopacket->hb1 = DC_HDMI_INFOFRAME_TYPE_SPD;
790 
791 		/* HB2  = [Bits 7:0 = Least significant eight bits -
792 		 *	  For INFOFRAME, the value must be 1Bh]
793 		 */
794 		infopacket->hb2 = 0x1B;
795 
796 		/* HB3  = [Bits 7:2 = INFOFRAME SDP Version Number = 0x2]
797 		 *	  [Bits 1:0 = Most significant two bits = 0x00]
798 		 */
799 		infopacket->hb3 = 0x08;
800 
801 		*payload_size = 0x1B;
802 	}
803 }
804 
805 static void build_vrr_infopacket_header_v3(enum signal_type signal,
806 		struct dc_info_packet *infopacket,
807 		unsigned int *payload_size)
808 {
809 	unsigned char version;
810 
811 	version = 3;
812 	if (dc_is_hdmi_signal(signal)) {
813 
814 		/* HEADER */
815 
816 		/* HB0  = Packet Type = 0x83 (Source Product
817 		 *	  Descriptor InfoFrame)
818 		 */
819 		infopacket->hb0 = DC_HDMI_INFOFRAME_TYPE_SPD;
820 
821 		/* HB1  = Version = 0x03 */
822 		infopacket->hb1 = version;
823 
824 		/* HB2  = [Bits 7:5 = 0] [Bits 4:0 = Length] */
825 		*payload_size = 0x10;
826 		infopacket->hb2 = *payload_size - 1; //-1 for checksum
827 
828 	} else if (dc_is_dp_signal(signal)) {
829 
830 		/* HEADER */
831 
832 		/* HB0  = Secondary-data Packet ID = 0 - Only non-zero
833 		 *	  when used to associate audio related info packets
834 		 */
835 		infopacket->hb0 = 0x00;
836 
837 		/* HB1  = Packet Type = 0x83 (Source Product
838 		 *	  Descriptor InfoFrame)
839 		 */
840 		infopacket->hb1 = DC_HDMI_INFOFRAME_TYPE_SPD;
841 
842 		/* HB2  = [Bits 7:0 = Least significant eight bits -
843 		 *	  For INFOFRAME, the value must be 1Bh]
844 		 */
845 		infopacket->hb2 = 0x1B;
846 
847 		/* HB3  = [Bits 7:2 = INFOFRAME SDP Version Number = 0x2]
848 		 *	  [Bits 1:0 = Most significant two bits = 0x00]
849 		 */
850 
851 		infopacket->hb3 = (version & 0x3F) << 2;
852 
853 		*payload_size = 0x1B;
854 	}
855 }
856 
857 static void build_vrr_infopacket_checksum(unsigned int *payload_size,
858 		struct dc_info_packet *infopacket)
859 {
860 	/* Calculate checksum */
861 	unsigned int idx = 0;
862 	unsigned char checksum = 0;
863 
864 	checksum += infopacket->hb0;
865 	checksum += infopacket->hb1;
866 	checksum += infopacket->hb2;
867 	checksum += infopacket->hb3;
868 
869 	for (idx = 1; idx <= *payload_size; idx++)
870 		checksum += infopacket->sb[idx];
871 
872 	/* PB0 = Checksum (one byte complement) */
873 	infopacket->sb[0] = (unsigned char)(0x100 - checksum);
874 
875 	infopacket->valid = true;
876 }
877 
878 static void build_vrr_infopacket_v1(enum signal_type signal,
879 		const struct mod_vrr_params *vrr,
880 		struct dc_info_packet *infopacket,
881 		bool freesync_on_desktop)
882 {
883 	/* SPD info packet for FreeSync */
884 	unsigned int payload_size = 0;
885 
886 	build_vrr_infopacket_header_v1(signal, infopacket, &payload_size);
887 	build_vrr_infopacket_data_v1(vrr, infopacket, freesync_on_desktop);
888 	build_vrr_infopacket_checksum(&payload_size, infopacket);
889 
890 	infopacket->valid = true;
891 }
892 
893 static void build_vrr_infopacket_v2(enum signal_type signal,
894 		const struct mod_vrr_params *vrr,
895 		enum color_transfer_func app_tf,
896 		struct dc_info_packet *infopacket,
897 		bool freesync_on_desktop)
898 {
899 	unsigned int payload_size = 0;
900 
901 	build_vrr_infopacket_header_v2(signal, infopacket, &payload_size);
902 	build_vrr_infopacket_data_v1(vrr, infopacket, freesync_on_desktop);
903 
904 	build_vrr_infopacket_fs2_data(app_tf, infopacket);
905 
906 	build_vrr_infopacket_checksum(&payload_size, infopacket);
907 
908 	infopacket->valid = true;
909 }
910 #ifndef TRIM_FSFT
911 static void build_vrr_infopacket_fast_transport_data(
912 	bool ftActive,
913 	unsigned int ftOutputRate,
914 	struct dc_info_packet *infopacket)
915 {
916 	/* PB9 : bit7 - fast transport Active*/
917 	unsigned char activeBit = (ftActive) ? 1 << 7 : 0;
918 
919 	infopacket->sb[1] &= ~activeBit;  //clear bit
920 	infopacket->sb[1] |=  activeBit;  //set bit
921 
922 	/* PB13 : Target Output Pixel Rate [kHz] - bits 7:0  */
923 	infopacket->sb[13] = ftOutputRate & 0xFF;
924 
925 	/* PB14 : Target Output Pixel Rate [kHz] - bits 15:8  */
926 	infopacket->sb[14] = (ftOutputRate >> 8) & 0xFF;
927 
928 	/* PB15 : Target Output Pixel Rate [kHz] - bits 23:16  */
929 	infopacket->sb[15] = (ftOutputRate >> 16) & 0xFF;
930 
931 }
932 #endif
933 
934 static void build_vrr_infopacket_v3(enum signal_type signal,
935 		const struct mod_vrr_params *vrr,
936 #ifndef TRIM_FSFT
937 		bool ftActive, unsigned int ftOutputRate,
938 #endif
939 		enum color_transfer_func app_tf,
940 		struct dc_info_packet *infopacket)
941 {
942 	unsigned int payload_size = 0;
943 
944 	build_vrr_infopacket_header_v3(signal, infopacket, &payload_size);
945 	build_vrr_infopacket_data_v3(vrr, infopacket);
946 
947 	build_vrr_infopacket_fs2_data(app_tf, infopacket);
948 
949 #ifndef TRIM_FSFT
950 	build_vrr_infopacket_fast_transport_data(
951 			ftActive,
952 			ftOutputRate,
953 			infopacket);
954 #endif
955 
956 	build_vrr_infopacket_checksum(&payload_size, infopacket);
957 
958 	infopacket->valid = true;
959 }
960 
961 static void build_vrr_infopacket_sdp_v1_3(enum vrr_packet_type packet_type,
962 										struct dc_info_packet *infopacket)
963 {
964 	uint8_t idx = 0, size = 0;
965 
966 	size = ((packet_type == PACKET_TYPE_FS_V1) ? 0x08 :
967 			(packet_type == PACKET_TYPE_FS_V3) ? 0x10 :
968 												0x09);
969 
970 	for (idx = infopacket->hb2; idx > 1; idx--) // Data Byte Count: 0x1B
971 		infopacket->sb[idx] = infopacket->sb[idx-1];
972 
973 	infopacket->sb[1] = size;                         // Length
974 	infopacket->sb[0] = (infopacket->hb3 >> 2) & 0x3F;//Version
975 	infopacket->hb3   = (0x13 << 2);                  // Header,SDP 1.3
976 	infopacket->hb2   = 0x1D;
977 }
978 
979 void mod_freesync_build_vrr_infopacket(struct mod_freesync *mod_freesync,
980 		const struct dc_stream_state *stream,
981 		const struct mod_vrr_params *vrr,
982 		enum vrr_packet_type packet_type,
983 		enum color_transfer_func app_tf,
984 		struct dc_info_packet *infopacket,
985 		bool pack_sdp_v1_3)
986 {
987 	/* SPD info packet for FreeSync
988 	 * VTEM info packet for HdmiVRR
989 	 * Check if Freesync is supported. Return if false. If true,
990 	 * set the corresponding bit in the info packet
991 	 */
992 	if (!vrr->send_info_frame)
993 		return;
994 
995 	switch (packet_type) {
996 	case PACKET_TYPE_FS_V3:
997 #ifndef TRIM_FSFT
998 		// always populate with pixel rate.
999 		build_vrr_infopacket_v3(
1000 				stream->signal, vrr,
1001 				stream->timing.flags.FAST_TRANSPORT,
1002 				(stream->timing.flags.FAST_TRANSPORT) ?
1003 						stream->timing.fast_transport_output_rate_100hz :
1004 						stream->timing.pix_clk_100hz,
1005 				app_tf, infopacket);
1006 #else
1007 		build_vrr_infopacket_v3(stream->signal, vrr, app_tf, infopacket);
1008 #endif
1009 		break;
1010 	case PACKET_TYPE_FS_V2:
1011 		build_vrr_infopacket_v2(stream->signal, vrr, app_tf, infopacket, stream->freesync_on_desktop);
1012 		break;
1013 	case PACKET_TYPE_VRR:
1014 	case PACKET_TYPE_FS_V1:
1015 	default:
1016 		build_vrr_infopacket_v1(stream->signal, vrr, infopacket, stream->freesync_on_desktop);
1017 	}
1018 
1019 	if (true == pack_sdp_v1_3 &&
1020 		true == dc_is_dp_signal(stream->signal) &&
1021 		packet_type != PACKET_TYPE_VRR &&
1022 		packet_type != PACKET_TYPE_VTEM)
1023 		build_vrr_infopacket_sdp_v1_3(packet_type, infopacket);
1024 }
1025 
1026 void mod_freesync_build_vrr_params(struct mod_freesync *mod_freesync,
1027 		const struct dc_stream_state *stream,
1028 		struct mod_freesync_config *in_config,
1029 		struct mod_vrr_params *in_out_vrr)
1030 {
1031 	struct core_freesync *core_freesync = NULL;
1032 	unsigned long long nominal_field_rate_in_uhz = 0;
1033 	unsigned long long rounded_nominal_in_uhz = 0;
1034 	unsigned int refresh_range = 0;
1035 	unsigned long long min_refresh_in_uhz = 0;
1036 	unsigned long long max_refresh_in_uhz = 0;
1037 
1038 	if (mod_freesync == NULL)
1039 		return;
1040 
1041 	core_freesync = MOD_FREESYNC_TO_CORE(mod_freesync);
1042 
1043 	/* Calculate nominal field rate for stream */
1044 	nominal_field_rate_in_uhz =
1045 			mod_freesync_calc_nominal_field_rate(stream);
1046 
1047 	min_refresh_in_uhz = in_config->min_refresh_in_uhz;
1048 	max_refresh_in_uhz = in_config->max_refresh_in_uhz;
1049 
1050 	/* Full range may be larger than current video timing, so cap at nominal */
1051 	if (max_refresh_in_uhz > nominal_field_rate_in_uhz)
1052 		max_refresh_in_uhz = nominal_field_rate_in_uhz;
1053 
1054 	/* Full range may be larger than current video timing, so cap at nominal */
1055 	if (min_refresh_in_uhz > max_refresh_in_uhz)
1056 		min_refresh_in_uhz = max_refresh_in_uhz;
1057 
1058 	/* If a monitor reports exactly max refresh of 2x of min, enforce it on nominal */
1059 	rounded_nominal_in_uhz =
1060 			div_u64(nominal_field_rate_in_uhz + 50000, 100000) * 100000;
1061 	if (in_config->max_refresh_in_uhz == (2 * in_config->min_refresh_in_uhz) &&
1062 		in_config->max_refresh_in_uhz == rounded_nominal_in_uhz)
1063 		min_refresh_in_uhz = div_u64(nominal_field_rate_in_uhz, 2);
1064 
1065 	if (!vrr_settings_require_update(core_freesync,
1066 			in_config, (unsigned int)min_refresh_in_uhz, (unsigned int)max_refresh_in_uhz,
1067 			in_out_vrr))
1068 		return;
1069 
1070 	in_out_vrr->state = in_config->state;
1071 	in_out_vrr->send_info_frame = in_config->vsif_supported;
1072 
1073 	if (in_config->state == VRR_STATE_UNSUPPORTED) {
1074 		in_out_vrr->state = VRR_STATE_UNSUPPORTED;
1075 		in_out_vrr->supported = false;
1076 		in_out_vrr->adjust.v_total_min = stream->timing.v_total;
1077 		in_out_vrr->adjust.v_total_max = stream->timing.v_total;
1078 
1079 		return;
1080 
1081 	} else {
1082 		in_out_vrr->min_refresh_in_uhz = (unsigned int)min_refresh_in_uhz;
1083 		in_out_vrr->max_duration_in_us =
1084 				calc_duration_in_us_from_refresh_in_uhz(
1085 						(unsigned int)min_refresh_in_uhz);
1086 
1087 		in_out_vrr->max_refresh_in_uhz = (unsigned int)max_refresh_in_uhz;
1088 		in_out_vrr->min_duration_in_us =
1089 				calc_duration_in_us_from_refresh_in_uhz(
1090 						(unsigned int)max_refresh_in_uhz);
1091 
1092 		if (in_config->state == VRR_STATE_ACTIVE_FIXED)
1093 			in_out_vrr->fixed_refresh_in_uhz = in_config->fixed_refresh_in_uhz;
1094 		else
1095 			in_out_vrr->fixed_refresh_in_uhz = 0;
1096 
1097 		refresh_range = div_u64(in_out_vrr->max_refresh_in_uhz + 500000, 1000000) -
1098 +				div_u64(in_out_vrr->min_refresh_in_uhz + 500000, 1000000);
1099 
1100 		in_out_vrr->supported = true;
1101 	}
1102 
1103 	in_out_vrr->fixed.ramping_active = in_config->ramping;
1104 
1105 	in_out_vrr->btr.btr_enabled = in_config->btr;
1106 
1107 	if (in_out_vrr->max_refresh_in_uhz < (2 * in_out_vrr->min_refresh_in_uhz))
1108 		in_out_vrr->btr.btr_enabled = false;
1109 	else {
1110 		in_out_vrr->btr.margin_in_us = in_out_vrr->max_duration_in_us -
1111 				2 * in_out_vrr->min_duration_in_us;
1112 		if (in_out_vrr->btr.margin_in_us > BTR_MAX_MARGIN)
1113 			in_out_vrr->btr.margin_in_us = BTR_MAX_MARGIN;
1114 	}
1115 
1116 	in_out_vrr->btr.btr_active = false;
1117 	in_out_vrr->btr.inserted_duration_in_us = 0;
1118 	in_out_vrr->btr.frames_to_insert = 0;
1119 	in_out_vrr->btr.frame_counter = 0;
1120 	in_out_vrr->fixed.fixed_active = false;
1121 	in_out_vrr->fixed.target_refresh_in_uhz = 0;
1122 
1123 	in_out_vrr->btr.mid_point_in_us =
1124 				(in_out_vrr->min_duration_in_us +
1125 				 in_out_vrr->max_duration_in_us) / 2;
1126 
1127 	if (in_out_vrr->state == VRR_STATE_UNSUPPORTED) {
1128 		in_out_vrr->adjust.v_total_min = stream->timing.v_total;
1129 		in_out_vrr->adjust.v_total_max = stream->timing.v_total;
1130 	} else if (in_out_vrr->state == VRR_STATE_DISABLED) {
1131 		in_out_vrr->adjust.v_total_min = stream->timing.v_total;
1132 		in_out_vrr->adjust.v_total_max = stream->timing.v_total;
1133 	} else if (in_out_vrr->state == VRR_STATE_INACTIVE) {
1134 		in_out_vrr->adjust.v_total_min = stream->timing.v_total;
1135 		in_out_vrr->adjust.v_total_max = stream->timing.v_total;
1136 	} else if (in_out_vrr->state == VRR_STATE_ACTIVE_VARIABLE &&
1137 			refresh_range >= MIN_REFRESH_RANGE) {
1138 
1139 		in_out_vrr->adjust.v_total_min =
1140 			mod_freesync_calc_v_total_from_refresh(stream,
1141 				in_out_vrr->max_refresh_in_uhz);
1142 		in_out_vrr->adjust.v_total_max =
1143 			mod_freesync_calc_v_total_from_refresh(stream,
1144 				in_out_vrr->min_refresh_in_uhz);
1145 	} else if (in_out_vrr->state == VRR_STATE_ACTIVE_FIXED) {
1146 		in_out_vrr->fixed.target_refresh_in_uhz =
1147 				in_out_vrr->fixed_refresh_in_uhz;
1148 		if (in_out_vrr->fixed.ramping_active &&
1149 				in_out_vrr->fixed.fixed_active) {
1150 			/* Do not update vtotals if ramping is already active
1151 			 * in order to continue ramp from current refresh.
1152 			 */
1153 			in_out_vrr->fixed.fixed_active = true;
1154 		} else {
1155 			in_out_vrr->fixed.fixed_active = true;
1156 			in_out_vrr->adjust.v_total_min =
1157 				mod_freesync_calc_v_total_from_refresh(stream,
1158 					in_out_vrr->fixed.target_refresh_in_uhz);
1159 			in_out_vrr->adjust.v_total_max =
1160 				in_out_vrr->adjust.v_total_min;
1161 		}
1162 	} else {
1163 		in_out_vrr->state = VRR_STATE_INACTIVE;
1164 		in_out_vrr->adjust.v_total_min = stream->timing.v_total;
1165 		in_out_vrr->adjust.v_total_max = stream->timing.v_total;
1166 	}
1167 }
1168 
1169 void mod_freesync_handle_preflip(struct mod_freesync *mod_freesync,
1170 		const struct dc_plane_state *plane,
1171 		const struct dc_stream_state *stream,
1172 		unsigned int curr_time_stamp_in_us,
1173 		struct mod_vrr_params *in_out_vrr)
1174 {
1175 	struct core_freesync *core_freesync = NULL;
1176 	unsigned int last_render_time_in_us = 0;
1177 	unsigned int average_render_time_in_us = 0;
1178 
1179 	if (mod_freesync == NULL)
1180 		return;
1181 
1182 	core_freesync = MOD_FREESYNC_TO_CORE(mod_freesync);
1183 
1184 	if (in_out_vrr->supported &&
1185 			in_out_vrr->state == VRR_STATE_ACTIVE_VARIABLE) {
1186 		unsigned int i = 0;
1187 		unsigned int oldest_index = plane->time.index + 1;
1188 
1189 		if (oldest_index >= DC_PLANE_UPDATE_TIMES_MAX)
1190 			oldest_index = 0;
1191 
1192 		last_render_time_in_us = curr_time_stamp_in_us -
1193 				plane->time.prev_update_time_in_us;
1194 
1195 		/* Sum off all entries except oldest one */
1196 		for (i = 0; i < DC_PLANE_UPDATE_TIMES_MAX; i++) {
1197 			average_render_time_in_us +=
1198 					plane->time.time_elapsed_in_us[i];
1199 		}
1200 		average_render_time_in_us -=
1201 				plane->time.time_elapsed_in_us[oldest_index];
1202 
1203 		/* Add render time for current flip */
1204 		average_render_time_in_us += last_render_time_in_us;
1205 		average_render_time_in_us /= DC_PLANE_UPDATE_TIMES_MAX;
1206 
1207 		if (in_out_vrr->btr.btr_enabled) {
1208 			apply_below_the_range(core_freesync,
1209 					stream,
1210 					last_render_time_in_us,
1211 					in_out_vrr);
1212 		} else {
1213 			apply_fixed_refresh(core_freesync,
1214 				stream,
1215 				last_render_time_in_us,
1216 				in_out_vrr);
1217 		}
1218 
1219 		determine_flip_interval_workaround_req(in_out_vrr,
1220 				curr_time_stamp_in_us);
1221 
1222 	}
1223 }
1224 
1225 void mod_freesync_handle_v_update(struct mod_freesync *mod_freesync,
1226 		const struct dc_stream_state *stream,
1227 		struct mod_vrr_params *in_out_vrr)
1228 {
1229 	struct core_freesync *core_freesync = NULL;
1230 	unsigned int cur_timestamp_in_us;
1231 	unsigned long long cur_tick;
1232 
1233 	if ((mod_freesync == NULL) || (stream == NULL) || (in_out_vrr == NULL))
1234 		return;
1235 
1236 	core_freesync = MOD_FREESYNC_TO_CORE(mod_freesync);
1237 
1238 	if (in_out_vrr->supported == false)
1239 		return;
1240 
1241 	cur_tick = dm_get_timestamp(core_freesync->dc->ctx);
1242 	cur_timestamp_in_us = (unsigned int)
1243 			div_u64(dm_get_elapse_time_in_ns(core_freesync->dc->ctx, cur_tick, 0), 1000);
1244 
1245 	in_out_vrr->flip_interval.vsyncs_between_flip++;
1246 	in_out_vrr->flip_interval.v_update_timestamp_in_us = cur_timestamp_in_us;
1247 
1248 	if (in_out_vrr->state == VRR_STATE_ACTIVE_VARIABLE &&
1249 			(in_out_vrr->flip_interval.flip_interval_workaround_active ||
1250 			(!in_out_vrr->flip_interval.flip_interval_workaround_active &&
1251 			in_out_vrr->flip_interval.program_flip_interval_workaround))) {
1252 		// set freesync vmin vmax to nominal for workaround
1253 		in_out_vrr->adjust.v_total_min =
1254 			mod_freesync_calc_v_total_from_refresh(
1255 			stream, in_out_vrr->max_refresh_in_uhz);
1256 		in_out_vrr->adjust.v_total_max =
1257 				in_out_vrr->adjust.v_total_min;
1258 		in_out_vrr->flip_interval.program_flip_interval_workaround = false;
1259 		in_out_vrr->flip_interval.do_flip_interval_workaround_cleanup = true;
1260 		return;
1261 	}
1262 
1263 	if (in_out_vrr->state != VRR_STATE_ACTIVE_VARIABLE &&
1264 			in_out_vrr->flip_interval.do_flip_interval_workaround_cleanup) {
1265 		in_out_vrr->flip_interval.do_flip_interval_workaround_cleanup = false;
1266 		in_out_vrr->flip_interval.flip_interval_detect_counter = 0;
1267 		in_out_vrr->flip_interval.vsyncs_between_flip = 0;
1268 		in_out_vrr->flip_interval.vsync_to_flip_in_us = 0;
1269 	}
1270 
1271 	/* Below the Range Logic */
1272 
1273 	/* Only execute if in fullscreen mode */
1274 	if (in_out_vrr->state == VRR_STATE_ACTIVE_VARIABLE &&
1275 					in_out_vrr->btr.btr_active) {
1276 		/* TODO: pass in flag for Pre-DCE12 ASIC
1277 		 * in order for frame variable duration to take affect,
1278 		 * it needs to be done one VSYNC early, which is at
1279 		 * frameCounter == 1.
1280 		 * For DCE12 and newer updates to V_TOTAL_MIN/MAX
1281 		 * will take affect on current frame
1282 		 */
1283 		if (in_out_vrr->btr.frames_to_insert ==
1284 				in_out_vrr->btr.frame_counter) {
1285 			in_out_vrr->adjust.v_total_min =
1286 				calc_v_total_from_duration(stream,
1287 				in_out_vrr,
1288 				in_out_vrr->btr.inserted_duration_in_us);
1289 			in_out_vrr->adjust.v_total_max =
1290 				in_out_vrr->adjust.v_total_min;
1291 		}
1292 
1293 		if (in_out_vrr->btr.frame_counter > 0)
1294 			in_out_vrr->btr.frame_counter--;
1295 
1296 		/* Restore FreeSync */
1297 		if (in_out_vrr->btr.frame_counter == 0) {
1298 			in_out_vrr->adjust.v_total_min =
1299 				mod_freesync_calc_v_total_from_refresh(stream,
1300 				in_out_vrr->max_refresh_in_uhz);
1301 			in_out_vrr->adjust.v_total_max =
1302 				mod_freesync_calc_v_total_from_refresh(stream,
1303 				in_out_vrr->min_refresh_in_uhz);
1304 		}
1305 	}
1306 
1307 	/* If in fullscreen freesync mode or in video, do not program
1308 	 * static screen ramp values
1309 	 */
1310 	if (in_out_vrr->state == VRR_STATE_ACTIVE_VARIABLE)
1311 		in_out_vrr->fixed.ramping_active = false;
1312 
1313 	/* Gradual Static Screen Ramping Logic
1314 	 * Execute if ramp is active and user enabled freesync static screen
1315 	 */
1316 	if (in_out_vrr->state == VRR_STATE_ACTIVE_FIXED &&
1317 				in_out_vrr->fixed.ramping_active) {
1318 		update_v_total_for_static_ramp(
1319 				core_freesync, stream, in_out_vrr);
1320 	}
1321 }
1322 
1323 void mod_freesync_get_settings(struct mod_freesync *mod_freesync,
1324 		const struct mod_vrr_params *vrr,
1325 		unsigned int *v_total_min, unsigned int *v_total_max,
1326 		unsigned int *event_triggers,
1327 		unsigned int *window_min, unsigned int *window_max,
1328 		unsigned int *lfc_mid_point_in_us,
1329 		unsigned int *inserted_frames,
1330 		unsigned int *inserted_duration_in_us)
1331 {
1332 	if (mod_freesync == NULL)
1333 		return;
1334 
1335 	if (vrr->supported) {
1336 		*v_total_min = vrr->adjust.v_total_min;
1337 		*v_total_max = vrr->adjust.v_total_max;
1338 		*event_triggers = 0;
1339 		*lfc_mid_point_in_us = vrr->btr.mid_point_in_us;
1340 		*inserted_frames = vrr->btr.frames_to_insert;
1341 		*inserted_duration_in_us = vrr->btr.inserted_duration_in_us;
1342 	}
1343 }
1344 
1345 unsigned long long mod_freesync_calc_nominal_field_rate(
1346 			const struct dc_stream_state *stream)
1347 {
1348 	unsigned long long nominal_field_rate_in_uhz = 0;
1349 	unsigned int total = stream->timing.h_total * stream->timing.v_total;
1350 
1351 	/* Calculate nominal field rate for stream, rounded up to nearest integer */
1352 	nominal_field_rate_in_uhz = stream->timing.pix_clk_100hz;
1353 	nominal_field_rate_in_uhz *= 100000000ULL;
1354 
1355 	nominal_field_rate_in_uhz =	div_u64(nominal_field_rate_in_uhz, total);
1356 
1357 	return nominal_field_rate_in_uhz;
1358 }
1359 
1360 unsigned long long mod_freesync_calc_field_rate_from_timing(
1361 		unsigned int vtotal, unsigned int htotal, unsigned int pix_clk)
1362 {
1363 	unsigned long long field_rate_in_uhz = 0;
1364 	unsigned int total = htotal * vtotal;
1365 
1366 	/* Calculate nominal field rate for stream, rounded up to nearest integer */
1367 	field_rate_in_uhz = pix_clk;
1368 	field_rate_in_uhz *= 1000000ULL;
1369 
1370 	field_rate_in_uhz =	div_u64(field_rate_in_uhz, total);
1371 
1372 	return field_rate_in_uhz;
1373 }
1374 
1375 bool mod_freesync_get_freesync_enabled(struct mod_vrr_params *pVrr)
1376 {
1377 	return (pVrr->state != VRR_STATE_UNSUPPORTED) && (pVrr->state != VRR_STATE_DISABLED);
1378 }
1379 
1380 bool mod_freesync_is_valid_range(uint32_t min_refresh_cap_in_uhz,
1381 		uint32_t max_refresh_cap_in_uhz,
1382 		uint32_t nominal_field_rate_in_uhz)
1383 {
1384 
1385 	/* Typically nominal refresh calculated can have some fractional part.
1386 	 * Allow for some rounding error of actual video timing by taking floor
1387 	 * of caps and request. Round the nominal refresh rate.
1388 	 *
1389 	 * Dividing will convert everything to units in Hz although input
1390 	 * variable name is in uHz!
1391 	 *
1392 	 * Also note, this takes care of rounding error on the nominal refresh
1393 	 * so by rounding error we only expect it to be off by a small amount,
1394 	 * such as < 0.1 Hz. i.e. 143.9xxx or 144.1xxx.
1395 	 *
1396 	 * Example 1. Caps    Min = 40 Hz, Max = 144 Hz
1397 	 *            Request Min = 40 Hz, Max = 144 Hz
1398 	 *                    Nominal = 143.5x Hz rounded to 144 Hz
1399 	 *            This function should allow this as valid request
1400 	 *
1401 	 * Example 2. Caps    Min = 40 Hz, Max = 144 Hz
1402 	 *            Request Min = 40 Hz, Max = 144 Hz
1403 	 *                    Nominal = 144.4x Hz rounded to 144 Hz
1404 	 *            This function should allow this as valid request
1405 	 *
1406 	 * Example 3. Caps    Min = 40 Hz, Max = 144 Hz
1407 	 *            Request Min = 40 Hz, Max = 144 Hz
1408 	 *                    Nominal = 120.xx Hz rounded to 120 Hz
1409 	 *            This function should return NOT valid since the requested
1410 	 *            max is greater than current timing's nominal
1411 	 *
1412 	 * Example 4. Caps    Min = 40 Hz, Max = 120 Hz
1413 	 *            Request Min = 40 Hz, Max = 120 Hz
1414 	 *                    Nominal = 144.xx Hz rounded to 144 Hz
1415 	 *            This function should return NOT valid since the nominal
1416 	 *            is greater than the capability's max refresh
1417 	 */
1418 	nominal_field_rate_in_uhz =
1419 			div_u64(nominal_field_rate_in_uhz + 500000, 1000000);
1420 	min_refresh_cap_in_uhz /= 1000000;
1421 	max_refresh_cap_in_uhz /= 1000000;
1422 
1423 	/* Check nominal is within range */
1424 	if (nominal_field_rate_in_uhz > max_refresh_cap_in_uhz ||
1425 		nominal_field_rate_in_uhz < min_refresh_cap_in_uhz)
1426 		return false;
1427 
1428 	/* If nominal is less than max, limit the max allowed refresh rate */
1429 	if (nominal_field_rate_in_uhz < max_refresh_cap_in_uhz)
1430 		max_refresh_cap_in_uhz = nominal_field_rate_in_uhz;
1431 
1432 	/* Check min is within range */
1433 	if (min_refresh_cap_in_uhz > max_refresh_cap_in_uhz)
1434 		return false;
1435 
1436 	/* For variable range, check for at least 10 Hz range */
1437 	if (nominal_field_rate_in_uhz - min_refresh_cap_in_uhz < 10)
1438 		return false;
1439 
1440 	return true;
1441 }
1442