1 /*
2  * Copyright 2007-8 Advanced Micro Devices, Inc.
3  * Copyright 2008 Red Hat Inc.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
19  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
20  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
21  * OTHER DEALINGS IN THE SOFTWARE.
22  *
23  * Authors: Dave Airlie
24  *          Alex Deucher
25  */
26 
27 #include <linux/pci.h>
28 #include <linux/pm_runtime.h>
29 #include <linux/gcd.h>
30 
31 #include <asm/div64.h>
32 
33 #include <drm/drm_crtc_helper.h>
34 #include <drm/drm_device.h>
35 #include <drm/drm_drv.h>
36 #include <drm/drm_edid.h>
37 #include <drm/drm_fb_helper.h>
38 #include <drm/drm_fourcc.h>
39 #include <drm/drm_gem_framebuffer_helper.h>
40 #include <drm/drm_plane_helper.h>
41 #include <drm/drm_probe_helper.h>
42 #include <drm/drm_vblank.h>
43 #include <drm/radeon_drm.h>
44 
45 #include "atom.h"
46 #include "radeon.h"
47 #include "radeon_kms.h"
48 
49 static void avivo_crtc_load_lut(struct drm_crtc *crtc)
50 {
51 	struct radeon_crtc *radeon_crtc = to_radeon_crtc(crtc);
52 	struct drm_device *dev = crtc->dev;
53 	struct radeon_device *rdev = dev->dev_private;
54 	u16 *r, *g, *b;
55 	int i;
56 
57 	DRM_DEBUG_KMS("%d\n", radeon_crtc->crtc_id);
58 	WREG32(AVIVO_DC_LUTA_CONTROL + radeon_crtc->crtc_offset, 0);
59 
60 	WREG32(AVIVO_DC_LUTA_BLACK_OFFSET_BLUE + radeon_crtc->crtc_offset, 0);
61 	WREG32(AVIVO_DC_LUTA_BLACK_OFFSET_GREEN + radeon_crtc->crtc_offset, 0);
62 	WREG32(AVIVO_DC_LUTA_BLACK_OFFSET_RED + radeon_crtc->crtc_offset, 0);
63 
64 	WREG32(AVIVO_DC_LUTA_WHITE_OFFSET_BLUE + radeon_crtc->crtc_offset, 0xffff);
65 	WREG32(AVIVO_DC_LUTA_WHITE_OFFSET_GREEN + radeon_crtc->crtc_offset, 0xffff);
66 	WREG32(AVIVO_DC_LUTA_WHITE_OFFSET_RED + radeon_crtc->crtc_offset, 0xffff);
67 
68 	WREG32(AVIVO_DC_LUT_RW_SELECT, radeon_crtc->crtc_id);
69 	WREG32(AVIVO_DC_LUT_RW_MODE, 0);
70 	WREG32(AVIVO_DC_LUT_WRITE_EN_MASK, 0x0000003f);
71 
72 	WREG8(AVIVO_DC_LUT_RW_INDEX, 0);
73 	r = crtc->gamma_store;
74 	g = r + crtc->gamma_size;
75 	b = g + crtc->gamma_size;
76 	for (i = 0; i < 256; i++) {
77 		WREG32(AVIVO_DC_LUT_30_COLOR,
78 		       ((*r++ & 0xffc0) << 14) |
79 		       ((*g++ & 0xffc0) << 4) |
80 		       (*b++ >> 6));
81 	}
82 
83 	/* Only change bit 0 of LUT_SEL, other bits are set elsewhere */
84 	WREG32_P(AVIVO_D1GRPH_LUT_SEL + radeon_crtc->crtc_offset, radeon_crtc->crtc_id, ~1);
85 }
86 
87 static void dce4_crtc_load_lut(struct drm_crtc *crtc)
88 {
89 	struct radeon_crtc *radeon_crtc = to_radeon_crtc(crtc);
90 	struct drm_device *dev = crtc->dev;
91 	struct radeon_device *rdev = dev->dev_private;
92 	u16 *r, *g, *b;
93 	int i;
94 
95 	DRM_DEBUG_KMS("%d\n", radeon_crtc->crtc_id);
96 	WREG32(EVERGREEN_DC_LUT_CONTROL + radeon_crtc->crtc_offset, 0);
97 
98 	WREG32(EVERGREEN_DC_LUT_BLACK_OFFSET_BLUE + radeon_crtc->crtc_offset, 0);
99 	WREG32(EVERGREEN_DC_LUT_BLACK_OFFSET_GREEN + radeon_crtc->crtc_offset, 0);
100 	WREG32(EVERGREEN_DC_LUT_BLACK_OFFSET_RED + radeon_crtc->crtc_offset, 0);
101 
102 	WREG32(EVERGREEN_DC_LUT_WHITE_OFFSET_BLUE + radeon_crtc->crtc_offset, 0xffff);
103 	WREG32(EVERGREEN_DC_LUT_WHITE_OFFSET_GREEN + radeon_crtc->crtc_offset, 0xffff);
104 	WREG32(EVERGREEN_DC_LUT_WHITE_OFFSET_RED + radeon_crtc->crtc_offset, 0xffff);
105 
106 	WREG32(EVERGREEN_DC_LUT_RW_MODE + radeon_crtc->crtc_offset, 0);
107 	WREG32(EVERGREEN_DC_LUT_WRITE_EN_MASK + radeon_crtc->crtc_offset, 0x00000007);
108 
109 	WREG32(EVERGREEN_DC_LUT_RW_INDEX + radeon_crtc->crtc_offset, 0);
110 	r = crtc->gamma_store;
111 	g = r + crtc->gamma_size;
112 	b = g + crtc->gamma_size;
113 	for (i = 0; i < 256; i++) {
114 		WREG32(EVERGREEN_DC_LUT_30_COLOR + radeon_crtc->crtc_offset,
115 		       ((*r++ & 0xffc0) << 14) |
116 		       ((*g++ & 0xffc0) << 4) |
117 		       (*b++ >> 6));
118 	}
119 }
120 
121 static void dce5_crtc_load_lut(struct drm_crtc *crtc)
122 {
123 	struct radeon_crtc *radeon_crtc = to_radeon_crtc(crtc);
124 	struct drm_device *dev = crtc->dev;
125 	struct radeon_device *rdev = dev->dev_private;
126 	u16 *r, *g, *b;
127 	int i;
128 
129 	DRM_DEBUG_KMS("%d\n", radeon_crtc->crtc_id);
130 
131 	msleep(10);
132 
133 	WREG32(NI_INPUT_CSC_CONTROL + radeon_crtc->crtc_offset,
134 	       (NI_INPUT_CSC_GRPH_MODE(NI_INPUT_CSC_BYPASS) |
135 		NI_INPUT_CSC_OVL_MODE(NI_INPUT_CSC_BYPASS)));
136 	WREG32(NI_PRESCALE_GRPH_CONTROL + radeon_crtc->crtc_offset,
137 	       NI_GRPH_PRESCALE_BYPASS);
138 	WREG32(NI_PRESCALE_OVL_CONTROL + radeon_crtc->crtc_offset,
139 	       NI_OVL_PRESCALE_BYPASS);
140 	WREG32(NI_INPUT_GAMMA_CONTROL + radeon_crtc->crtc_offset,
141 	       (NI_GRPH_INPUT_GAMMA_MODE(NI_INPUT_GAMMA_USE_LUT) |
142 		NI_OVL_INPUT_GAMMA_MODE(NI_INPUT_GAMMA_USE_LUT)));
143 
144 	WREG32(EVERGREEN_DC_LUT_CONTROL + radeon_crtc->crtc_offset, 0);
145 
146 	WREG32(EVERGREEN_DC_LUT_BLACK_OFFSET_BLUE + radeon_crtc->crtc_offset, 0);
147 	WREG32(EVERGREEN_DC_LUT_BLACK_OFFSET_GREEN + radeon_crtc->crtc_offset, 0);
148 	WREG32(EVERGREEN_DC_LUT_BLACK_OFFSET_RED + radeon_crtc->crtc_offset, 0);
149 
150 	WREG32(EVERGREEN_DC_LUT_WHITE_OFFSET_BLUE + radeon_crtc->crtc_offset, 0xffff);
151 	WREG32(EVERGREEN_DC_LUT_WHITE_OFFSET_GREEN + radeon_crtc->crtc_offset, 0xffff);
152 	WREG32(EVERGREEN_DC_LUT_WHITE_OFFSET_RED + radeon_crtc->crtc_offset, 0xffff);
153 
154 	WREG32(EVERGREEN_DC_LUT_RW_MODE + radeon_crtc->crtc_offset, 0);
155 	WREG32(EVERGREEN_DC_LUT_WRITE_EN_MASK + radeon_crtc->crtc_offset, 0x00000007);
156 
157 	WREG32(EVERGREEN_DC_LUT_RW_INDEX + radeon_crtc->crtc_offset, 0);
158 	r = crtc->gamma_store;
159 	g = r + crtc->gamma_size;
160 	b = g + crtc->gamma_size;
161 	for (i = 0; i < 256; i++) {
162 		WREG32(EVERGREEN_DC_LUT_30_COLOR + radeon_crtc->crtc_offset,
163 		       ((*r++ & 0xffc0) << 14) |
164 		       ((*g++ & 0xffc0) << 4) |
165 		       (*b++ >> 6));
166 	}
167 
168 	WREG32(NI_DEGAMMA_CONTROL + radeon_crtc->crtc_offset,
169 	       (NI_GRPH_DEGAMMA_MODE(NI_DEGAMMA_BYPASS) |
170 		NI_OVL_DEGAMMA_MODE(NI_DEGAMMA_BYPASS) |
171 		NI_ICON_DEGAMMA_MODE(NI_DEGAMMA_BYPASS) |
172 		NI_CURSOR_DEGAMMA_MODE(NI_DEGAMMA_BYPASS)));
173 	WREG32(NI_GAMUT_REMAP_CONTROL + radeon_crtc->crtc_offset,
174 	       (NI_GRPH_GAMUT_REMAP_MODE(NI_GAMUT_REMAP_BYPASS) |
175 		NI_OVL_GAMUT_REMAP_MODE(NI_GAMUT_REMAP_BYPASS)));
176 	WREG32(NI_REGAMMA_CONTROL + radeon_crtc->crtc_offset,
177 	       (NI_GRPH_REGAMMA_MODE(NI_REGAMMA_BYPASS) |
178 		NI_OVL_REGAMMA_MODE(NI_REGAMMA_BYPASS)));
179 	WREG32(NI_OUTPUT_CSC_CONTROL + radeon_crtc->crtc_offset,
180 	       (NI_OUTPUT_CSC_GRPH_MODE(radeon_crtc->output_csc) |
181 		NI_OUTPUT_CSC_OVL_MODE(NI_OUTPUT_CSC_BYPASS)));
182 	/* XXX match this to the depth of the crtc fmt block, move to modeset? */
183 	WREG32(0x6940 + radeon_crtc->crtc_offset, 0);
184 	if (ASIC_IS_DCE8(rdev)) {
185 		/* XXX this only needs to be programmed once per crtc at startup,
186 		 * not sure where the best place for it is
187 		 */
188 		WREG32(CIK_ALPHA_CONTROL + radeon_crtc->crtc_offset,
189 		       CIK_CURSOR_ALPHA_BLND_ENA);
190 	}
191 }
192 
193 static void legacy_crtc_load_lut(struct drm_crtc *crtc)
194 {
195 	struct radeon_crtc *radeon_crtc = to_radeon_crtc(crtc);
196 	struct drm_device *dev = crtc->dev;
197 	struct radeon_device *rdev = dev->dev_private;
198 	u16 *r, *g, *b;
199 	int i;
200 	uint32_t dac2_cntl;
201 
202 	dac2_cntl = RREG32(RADEON_DAC_CNTL2);
203 	if (radeon_crtc->crtc_id == 0)
204 		dac2_cntl &= (uint32_t)~RADEON_DAC2_PALETTE_ACC_CTL;
205 	else
206 		dac2_cntl |= RADEON_DAC2_PALETTE_ACC_CTL;
207 	WREG32(RADEON_DAC_CNTL2, dac2_cntl);
208 
209 	WREG8(RADEON_PALETTE_INDEX, 0);
210 	r = crtc->gamma_store;
211 	g = r + crtc->gamma_size;
212 	b = g + crtc->gamma_size;
213 	for (i = 0; i < 256; i++) {
214 		WREG32(RADEON_PALETTE_30_DATA,
215 		       ((*r++ & 0xffc0) << 14) |
216 		       ((*g++ & 0xffc0) << 4) |
217 		       (*b++ >> 6));
218 	}
219 }
220 
221 void radeon_crtc_load_lut(struct drm_crtc *crtc)
222 {
223 	struct drm_device *dev = crtc->dev;
224 	struct radeon_device *rdev = dev->dev_private;
225 
226 	if (!crtc->enabled)
227 		return;
228 
229 	if (ASIC_IS_DCE5(rdev))
230 		dce5_crtc_load_lut(crtc);
231 	else if (ASIC_IS_DCE4(rdev))
232 		dce4_crtc_load_lut(crtc);
233 	else if (ASIC_IS_AVIVO(rdev))
234 		avivo_crtc_load_lut(crtc);
235 	else
236 		legacy_crtc_load_lut(crtc);
237 }
238 
239 static int radeon_crtc_gamma_set(struct drm_crtc *crtc, u16 *red, u16 *green,
240 				 u16 *blue, uint32_t size,
241 				 struct drm_modeset_acquire_ctx *ctx)
242 {
243 	radeon_crtc_load_lut(crtc);
244 
245 	return 0;
246 }
247 
248 static void radeon_crtc_destroy(struct drm_crtc *crtc)
249 {
250 	struct radeon_crtc *radeon_crtc = to_radeon_crtc(crtc);
251 
252 	drm_crtc_cleanup(crtc);
253 	destroy_workqueue(radeon_crtc->flip_queue);
254 	kfree(radeon_crtc);
255 }
256 
257 /**
258  * radeon_unpin_work_func - unpin old buffer object
259  *
260  * @__work: kernel work item
261  *
262  * Unpin the old frame buffer object outside of the interrupt handler
263  */
264 static void radeon_unpin_work_func(struct work_struct *__work)
265 {
266 	struct radeon_flip_work *work =
267 		container_of(__work, struct radeon_flip_work, unpin_work);
268 	int r;
269 
270 	/* unpin of the old buffer */
271 	r = radeon_bo_reserve(work->old_rbo, false);
272 	if (likely(r == 0)) {
273 		radeon_bo_unpin(work->old_rbo);
274 		radeon_bo_unreserve(work->old_rbo);
275 	} else
276 		DRM_ERROR("failed to reserve buffer after flip\n");
277 
278 	drm_gem_object_put(&work->old_rbo->tbo.base);
279 	kfree(work);
280 }
281 
282 void radeon_crtc_handle_vblank(struct radeon_device *rdev, int crtc_id)
283 {
284 	struct radeon_crtc *radeon_crtc = rdev->mode_info.crtcs[crtc_id];
285 	unsigned long flags;
286 	u32 update_pending;
287 	int vpos, hpos;
288 
289 	/* can happen during initialization */
290 	if (radeon_crtc == NULL)
291 		return;
292 
293 	/* Skip the pageflip completion check below (based on polling) on
294 	 * asics which reliably support hw pageflip completion irqs. pflip
295 	 * irqs are a reliable and race-free method of handling pageflip
296 	 * completion detection. A use_pflipirq module parameter < 2 allows
297 	 * to override this in case of asics with faulty pflip irqs.
298 	 * A module parameter of 0 would only use this polling based path,
299 	 * a parameter of 1 would use pflip irq only as a backup to this
300 	 * path, as in Linux 3.16.
301 	 */
302 	if ((radeon_use_pflipirq == 2) && ASIC_IS_DCE4(rdev))
303 		return;
304 
305 	spin_lock_irqsave(&rdev->ddev->event_lock, flags);
306 	if (radeon_crtc->flip_status != RADEON_FLIP_SUBMITTED) {
307 		DRM_DEBUG_DRIVER("radeon_crtc->flip_status = %d != "
308 				 "RADEON_FLIP_SUBMITTED(%d)\n",
309 				 radeon_crtc->flip_status,
310 				 RADEON_FLIP_SUBMITTED);
311 		spin_unlock_irqrestore(&rdev->ddev->event_lock, flags);
312 		return;
313 	}
314 
315 	update_pending = radeon_page_flip_pending(rdev, crtc_id);
316 
317 	/* Has the pageflip already completed in crtc, or is it certain
318 	 * to complete in this vblank? GET_DISTANCE_TO_VBLANKSTART provides
319 	 * distance to start of "fudged earlier" vblank in vpos, distance to
320 	 * start of real vblank in hpos. vpos >= 0 && hpos < 0 means we are in
321 	 * the last few scanlines before start of real vblank, where the vblank
322 	 * irq can fire, so we have sampled update_pending a bit too early and
323 	 * know the flip will complete at leading edge of the upcoming real
324 	 * vblank. On pre-AVIVO hardware, flips also complete inside the real
325 	 * vblank, not only at leading edge, so if update_pending for hpos >= 0
326 	 *  == inside real vblank, the flip will complete almost immediately.
327 	 * Note that this method of completion handling is still not 100% race
328 	 * free, as we could execute before the radeon_flip_work_func managed
329 	 * to run and set the RADEON_FLIP_SUBMITTED status, thereby we no-op,
330 	 * but the flip still gets programmed into hw and completed during
331 	 * vblank, leading to a delayed emission of the flip completion event.
332 	 * This applies at least to pre-AVIVO hardware, where flips are always
333 	 * completing inside vblank, not only at leading edge of vblank.
334 	 */
335 	if (update_pending &&
336 	    (DRM_SCANOUTPOS_VALID &
337 	     radeon_get_crtc_scanoutpos(rdev->ddev, crtc_id,
338 					GET_DISTANCE_TO_VBLANKSTART,
339 					&vpos, &hpos, NULL, NULL,
340 					&rdev->mode_info.crtcs[crtc_id]->base.hwmode)) &&
341 	    ((vpos >= 0 && hpos < 0) || (hpos >= 0 && !ASIC_IS_AVIVO(rdev)))) {
342 		/* crtc didn't flip in this target vblank interval,
343 		 * but flip is pending in crtc. Based on the current
344 		 * scanout position we know that the current frame is
345 		 * (nearly) complete and the flip will (likely)
346 		 * complete before the start of the next frame.
347 		 */
348 		update_pending = 0;
349 	}
350 	spin_unlock_irqrestore(&rdev->ddev->event_lock, flags);
351 	if (!update_pending)
352 		radeon_crtc_handle_flip(rdev, crtc_id);
353 }
354 
355 /**
356  * radeon_crtc_handle_flip - page flip completed
357  *
358  * @rdev: radeon device pointer
359  * @crtc_id: crtc number this event is for
360  *
361  * Called when we are sure that a page flip for this crtc is completed.
362  */
363 void radeon_crtc_handle_flip(struct radeon_device *rdev, int crtc_id)
364 {
365 	struct radeon_crtc *radeon_crtc = rdev->mode_info.crtcs[crtc_id];
366 	struct radeon_flip_work *work;
367 	unsigned long flags;
368 
369 	/* this can happen at init */
370 	if (radeon_crtc == NULL)
371 		return;
372 
373 	spin_lock_irqsave(&rdev->ddev->event_lock, flags);
374 	work = radeon_crtc->flip_work;
375 	if (radeon_crtc->flip_status != RADEON_FLIP_SUBMITTED) {
376 		DRM_DEBUG_DRIVER("radeon_crtc->flip_status = %d != "
377 				 "RADEON_FLIP_SUBMITTED(%d)\n",
378 				 radeon_crtc->flip_status,
379 				 RADEON_FLIP_SUBMITTED);
380 		spin_unlock_irqrestore(&rdev->ddev->event_lock, flags);
381 		return;
382 	}
383 
384 	/* Pageflip completed. Clean up. */
385 	radeon_crtc->flip_status = RADEON_FLIP_NONE;
386 	radeon_crtc->flip_work = NULL;
387 
388 	/* wakeup userspace */
389 	if (work->event)
390 		drm_crtc_send_vblank_event(&radeon_crtc->base, work->event);
391 
392 	spin_unlock_irqrestore(&rdev->ddev->event_lock, flags);
393 
394 	drm_crtc_vblank_put(&radeon_crtc->base);
395 	radeon_irq_kms_pflip_irq_put(rdev, work->crtc_id);
396 	queue_work(radeon_crtc->flip_queue, &work->unpin_work);
397 }
398 
399 /**
400  * radeon_flip_work_func - page flip framebuffer
401  *
402  * @__work: kernel work item
403  *
404  * Wait for the buffer object to become idle and do the actual page flip
405  */
406 static void radeon_flip_work_func(struct work_struct *__work)
407 {
408 	struct radeon_flip_work *work =
409 		container_of(__work, struct radeon_flip_work, flip_work);
410 	struct radeon_device *rdev = work->rdev;
411 	struct drm_device *dev = rdev->ddev;
412 	struct radeon_crtc *radeon_crtc = rdev->mode_info.crtcs[work->crtc_id];
413 
414 	struct drm_crtc *crtc = &radeon_crtc->base;
415 	unsigned long flags;
416 	int r;
417 	int vpos, hpos;
418 
419 	down_read(&rdev->exclusive_lock);
420 	if (work->fence) {
421 		struct radeon_fence *fence;
422 
423 		fence = to_radeon_fence(work->fence);
424 		if (fence && fence->rdev == rdev) {
425 			r = radeon_fence_wait(fence, false);
426 			if (r == -EDEADLK) {
427 				up_read(&rdev->exclusive_lock);
428 				do {
429 					r = radeon_gpu_reset(rdev);
430 				} while (r == -EAGAIN);
431 				down_read(&rdev->exclusive_lock);
432 			}
433 		} else
434 			r = dma_fence_wait(work->fence, false);
435 
436 		if (r)
437 			DRM_ERROR("failed to wait on page flip fence (%d)!\n", r);
438 
439 		/* We continue with the page flip even if we failed to wait on
440 		 * the fence, otherwise the DRM core and userspace will be
441 		 * confused about which BO the CRTC is scanning out
442 		 */
443 
444 		dma_fence_put(work->fence);
445 		work->fence = NULL;
446 	}
447 
448 	/* Wait until we're out of the vertical blank period before the one
449 	 * targeted by the flip. Always wait on pre DCE4 to avoid races with
450 	 * flip completion handling from vblank irq, as these old asics don't
451 	 * have reliable pageflip completion interrupts.
452 	 */
453 	while (radeon_crtc->enabled &&
454 		(radeon_get_crtc_scanoutpos(dev, work->crtc_id, 0,
455 					    &vpos, &hpos, NULL, NULL,
456 					    &crtc->hwmode)
457 		& (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
458 		(DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
459 		(!ASIC_IS_AVIVO(rdev) ||
460 		((int) (work->target_vblank -
461 		crtc->funcs->get_vblank_counter(crtc)) > 0)))
462 		usleep_range(1000, 2000);
463 
464 	/* We borrow the event spin lock for protecting flip_status */
465 	spin_lock_irqsave(&crtc->dev->event_lock, flags);
466 
467 	/* set the proper interrupt */
468 	radeon_irq_kms_pflip_irq_get(rdev, radeon_crtc->crtc_id);
469 
470 	/* do the flip (mmio) */
471 	radeon_page_flip(rdev, radeon_crtc->crtc_id, work->base, work->async);
472 
473 	radeon_crtc->flip_status = RADEON_FLIP_SUBMITTED;
474 	spin_unlock_irqrestore(&crtc->dev->event_lock, flags);
475 	up_read(&rdev->exclusive_lock);
476 }
477 
478 static int radeon_crtc_page_flip_target(struct drm_crtc *crtc,
479 					struct drm_framebuffer *fb,
480 					struct drm_pending_vblank_event *event,
481 					uint32_t page_flip_flags,
482 					uint32_t target,
483 					struct drm_modeset_acquire_ctx *ctx)
484 {
485 	struct drm_device *dev = crtc->dev;
486 	struct radeon_device *rdev = dev->dev_private;
487 	struct radeon_crtc *radeon_crtc = to_radeon_crtc(crtc);
488 	struct drm_gem_object *obj;
489 	struct radeon_flip_work *work;
490 	struct radeon_bo *new_rbo;
491 	uint32_t tiling_flags, pitch_pixels;
492 	uint64_t base;
493 	unsigned long flags;
494 	int r;
495 
496 	work = kzalloc(sizeof *work, GFP_KERNEL);
497 	if (work == NULL)
498 		return -ENOMEM;
499 
500 	INIT_WORK(&work->flip_work, radeon_flip_work_func);
501 	INIT_WORK(&work->unpin_work, radeon_unpin_work_func);
502 
503 	work->rdev = rdev;
504 	work->crtc_id = radeon_crtc->crtc_id;
505 	work->event = event;
506 	work->async = (page_flip_flags & DRM_MODE_PAGE_FLIP_ASYNC) != 0;
507 
508 	/* schedule unpin of the old buffer */
509 	obj = crtc->primary->fb->obj[0];
510 
511 	/* take a reference to the old object */
512 	drm_gem_object_get(obj);
513 	work->old_rbo = gem_to_radeon_bo(obj);
514 
515 	obj = fb->obj[0];
516 	new_rbo = gem_to_radeon_bo(obj);
517 
518 	/* pin the new buffer */
519 	DRM_DEBUG_DRIVER("flip-ioctl() cur_rbo = %p, new_rbo = %p\n",
520 			 work->old_rbo, new_rbo);
521 
522 	r = radeon_bo_reserve(new_rbo, false);
523 	if (unlikely(r != 0)) {
524 		DRM_ERROR("failed to reserve new rbo buffer before flip\n");
525 		goto cleanup;
526 	}
527 	/* Only 27 bit offset for legacy CRTC */
528 	r = radeon_bo_pin_restricted(new_rbo, RADEON_GEM_DOMAIN_VRAM,
529 				     ASIC_IS_AVIVO(rdev) ? 0 : 1 << 27, &base);
530 	if (unlikely(r != 0)) {
531 		radeon_bo_unreserve(new_rbo);
532 		r = -EINVAL;
533 		DRM_ERROR("failed to pin new rbo buffer before flip\n");
534 		goto cleanup;
535 	}
536 	work->fence = dma_fence_get(dma_resv_get_excl(new_rbo->tbo.base.resv));
537 	radeon_bo_get_tiling_flags(new_rbo, &tiling_flags, NULL);
538 	radeon_bo_unreserve(new_rbo);
539 
540 	if (!ASIC_IS_AVIVO(rdev)) {
541 		/* crtc offset is from display base addr not FB location */
542 		base -= radeon_crtc->legacy_display_base_addr;
543 		pitch_pixels = fb->pitches[0] / fb->format->cpp[0];
544 
545 		if (tiling_flags & RADEON_TILING_MACRO) {
546 			if (ASIC_IS_R300(rdev)) {
547 				base &= ~0x7ff;
548 			} else {
549 				int byteshift = fb->format->cpp[0] * 8 >> 4;
550 				int tile_addr = (((crtc->y >> 3) * pitch_pixels +  crtc->x) >> (8 - byteshift)) << 11;
551 				base += tile_addr + ((crtc->x << byteshift) % 256) + ((crtc->y % 8) << 8);
552 			}
553 		} else {
554 			int offset = crtc->y * pitch_pixels + crtc->x;
555 			switch (fb->format->cpp[0] * 8) {
556 			case 8:
557 			default:
558 				offset *= 1;
559 				break;
560 			case 15:
561 			case 16:
562 				offset *= 2;
563 				break;
564 			case 24:
565 				offset *= 3;
566 				break;
567 			case 32:
568 				offset *= 4;
569 				break;
570 			}
571 			base += offset;
572 		}
573 		base &= ~7;
574 	}
575 	work->base = base;
576 	work->target_vblank = target - (uint32_t)drm_crtc_vblank_count(crtc) +
577 		crtc->funcs->get_vblank_counter(crtc);
578 
579 	/* We borrow the event spin lock for protecting flip_work */
580 	spin_lock_irqsave(&crtc->dev->event_lock, flags);
581 
582 	if (radeon_crtc->flip_status != RADEON_FLIP_NONE) {
583 		DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
584 		spin_unlock_irqrestore(&crtc->dev->event_lock, flags);
585 		r = -EBUSY;
586 		goto pflip_cleanup;
587 	}
588 	radeon_crtc->flip_status = RADEON_FLIP_PENDING;
589 	radeon_crtc->flip_work = work;
590 
591 	/* update crtc fb */
592 	crtc->primary->fb = fb;
593 
594 	spin_unlock_irqrestore(&crtc->dev->event_lock, flags);
595 
596 	queue_work(radeon_crtc->flip_queue, &work->flip_work);
597 	return 0;
598 
599 pflip_cleanup:
600 	if (unlikely(radeon_bo_reserve(new_rbo, false) != 0)) {
601 		DRM_ERROR("failed to reserve new rbo in error path\n");
602 		goto cleanup;
603 	}
604 	radeon_bo_unpin(new_rbo);
605 	radeon_bo_unreserve(new_rbo);
606 
607 cleanup:
608 	drm_gem_object_put(&work->old_rbo->tbo.base);
609 	dma_fence_put(work->fence);
610 	kfree(work);
611 	return r;
612 }
613 
614 static int
615 radeon_crtc_set_config(struct drm_mode_set *set,
616 		       struct drm_modeset_acquire_ctx *ctx)
617 {
618 	struct drm_device *dev;
619 	struct radeon_device *rdev;
620 	struct drm_crtc *crtc;
621 	bool active = false;
622 	int ret;
623 
624 	if (!set || !set->crtc)
625 		return -EINVAL;
626 
627 	dev = set->crtc->dev;
628 
629 	ret = pm_runtime_get_sync(dev->dev);
630 	if (ret < 0) {
631 		pm_runtime_put_autosuspend(dev->dev);
632 		return ret;
633 	}
634 
635 	ret = drm_crtc_helper_set_config(set, ctx);
636 
637 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head)
638 		if (crtc->enabled)
639 			active = true;
640 
641 	pm_runtime_mark_last_busy(dev->dev);
642 
643 	rdev = dev->dev_private;
644 	/* if we have active crtcs and we don't have a power ref,
645 	   take the current one */
646 	if (active && !rdev->have_disp_power_ref) {
647 		rdev->have_disp_power_ref = true;
648 		return ret;
649 	}
650 	/* if we have no active crtcs, then drop the power ref
651 	   we got before */
652 	if (!active && rdev->have_disp_power_ref) {
653 		pm_runtime_put_autosuspend(dev->dev);
654 		rdev->have_disp_power_ref = false;
655 	}
656 
657 	/* drop the power reference we got coming in here */
658 	pm_runtime_put_autosuspend(dev->dev);
659 	return ret;
660 }
661 
662 static const struct drm_crtc_funcs radeon_crtc_funcs = {
663 	.cursor_set2 = radeon_crtc_cursor_set2,
664 	.cursor_move = radeon_crtc_cursor_move,
665 	.gamma_set = radeon_crtc_gamma_set,
666 	.set_config = radeon_crtc_set_config,
667 	.destroy = radeon_crtc_destroy,
668 	.page_flip_target = radeon_crtc_page_flip_target,
669 	.get_vblank_counter = radeon_get_vblank_counter_kms,
670 	.enable_vblank = radeon_enable_vblank_kms,
671 	.disable_vblank = radeon_disable_vblank_kms,
672 	.get_vblank_timestamp = drm_crtc_vblank_helper_get_vblank_timestamp,
673 };
674 
675 static void radeon_crtc_init(struct drm_device *dev, int index)
676 {
677 	struct radeon_device *rdev = dev->dev_private;
678 	struct radeon_crtc *radeon_crtc;
679 
680 	radeon_crtc = kzalloc(sizeof(struct radeon_crtc) + (RADEONFB_CONN_LIMIT * sizeof(struct drm_connector *)), GFP_KERNEL);
681 	if (radeon_crtc == NULL)
682 		return;
683 
684 	drm_crtc_init(dev, &radeon_crtc->base, &radeon_crtc_funcs);
685 
686 	drm_mode_crtc_set_gamma_size(&radeon_crtc->base, 256);
687 	radeon_crtc->crtc_id = index;
688 	radeon_crtc->flip_queue = alloc_workqueue("radeon-crtc", WQ_HIGHPRI, 0);
689 	rdev->mode_info.crtcs[index] = radeon_crtc;
690 
691 	if (rdev->family >= CHIP_BONAIRE) {
692 		radeon_crtc->max_cursor_width = CIK_CURSOR_WIDTH;
693 		radeon_crtc->max_cursor_height = CIK_CURSOR_HEIGHT;
694 	} else {
695 		radeon_crtc->max_cursor_width = CURSOR_WIDTH;
696 		radeon_crtc->max_cursor_height = CURSOR_HEIGHT;
697 	}
698 	dev->mode_config.cursor_width = radeon_crtc->max_cursor_width;
699 	dev->mode_config.cursor_height = radeon_crtc->max_cursor_height;
700 
701 #if 0
702 	radeon_crtc->mode_set.crtc = &radeon_crtc->base;
703 	radeon_crtc->mode_set.connectors = (struct drm_connector **)(radeon_crtc + 1);
704 	radeon_crtc->mode_set.num_connectors = 0;
705 #endif
706 
707 	if (rdev->is_atom_bios && (ASIC_IS_AVIVO(rdev) || radeon_r4xx_atom))
708 		radeon_atombios_init_crtc(dev, radeon_crtc);
709 	else
710 		radeon_legacy_init_crtc(dev, radeon_crtc);
711 }
712 
713 static const char *encoder_names[38] = {
714 	"NONE",
715 	"INTERNAL_LVDS",
716 	"INTERNAL_TMDS1",
717 	"INTERNAL_TMDS2",
718 	"INTERNAL_DAC1",
719 	"INTERNAL_DAC2",
720 	"INTERNAL_SDVOA",
721 	"INTERNAL_SDVOB",
722 	"SI170B",
723 	"CH7303",
724 	"CH7301",
725 	"INTERNAL_DVO1",
726 	"EXTERNAL_SDVOA",
727 	"EXTERNAL_SDVOB",
728 	"TITFP513",
729 	"INTERNAL_LVTM1",
730 	"VT1623",
731 	"HDMI_SI1930",
732 	"HDMI_INTERNAL",
733 	"INTERNAL_KLDSCP_TMDS1",
734 	"INTERNAL_KLDSCP_DVO1",
735 	"INTERNAL_KLDSCP_DAC1",
736 	"INTERNAL_KLDSCP_DAC2",
737 	"SI178",
738 	"MVPU_FPGA",
739 	"INTERNAL_DDI",
740 	"VT1625",
741 	"HDMI_SI1932",
742 	"DP_AN9801",
743 	"DP_DP501",
744 	"INTERNAL_UNIPHY",
745 	"INTERNAL_KLDSCP_LVTMA",
746 	"INTERNAL_UNIPHY1",
747 	"INTERNAL_UNIPHY2",
748 	"NUTMEG",
749 	"TRAVIS",
750 	"INTERNAL_VCE",
751 	"INTERNAL_UNIPHY3",
752 };
753 
754 static const char *hpd_names[6] = {
755 	"HPD1",
756 	"HPD2",
757 	"HPD3",
758 	"HPD4",
759 	"HPD5",
760 	"HPD6",
761 };
762 
763 static void radeon_print_display_setup(struct drm_device *dev)
764 {
765 	struct drm_connector *connector;
766 	struct radeon_connector *radeon_connector;
767 	struct drm_encoder *encoder;
768 	struct radeon_encoder *radeon_encoder;
769 	uint32_t devices;
770 	int i = 0;
771 
772 	DRM_INFO("Radeon Display Connectors\n");
773 	list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
774 		radeon_connector = to_radeon_connector(connector);
775 		DRM_INFO("Connector %d:\n", i);
776 		DRM_INFO("  %s\n", connector->name);
777 		if (radeon_connector->hpd.hpd != RADEON_HPD_NONE)
778 			DRM_INFO("  %s\n", hpd_names[radeon_connector->hpd.hpd]);
779 		if (radeon_connector->ddc_bus) {
780 			DRM_INFO("  DDC: 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x\n",
781 				 radeon_connector->ddc_bus->rec.mask_clk_reg,
782 				 radeon_connector->ddc_bus->rec.mask_data_reg,
783 				 radeon_connector->ddc_bus->rec.a_clk_reg,
784 				 radeon_connector->ddc_bus->rec.a_data_reg,
785 				 radeon_connector->ddc_bus->rec.en_clk_reg,
786 				 radeon_connector->ddc_bus->rec.en_data_reg,
787 				 radeon_connector->ddc_bus->rec.y_clk_reg,
788 				 radeon_connector->ddc_bus->rec.y_data_reg);
789 			if (radeon_connector->router.ddc_valid)
790 				DRM_INFO("  DDC Router 0x%x/0x%x\n",
791 					 radeon_connector->router.ddc_mux_control_pin,
792 					 radeon_connector->router.ddc_mux_state);
793 			if (radeon_connector->router.cd_valid)
794 				DRM_INFO("  Clock/Data Router 0x%x/0x%x\n",
795 					 radeon_connector->router.cd_mux_control_pin,
796 					 radeon_connector->router.cd_mux_state);
797 		} else {
798 			if (connector->connector_type == DRM_MODE_CONNECTOR_VGA ||
799 			    connector->connector_type == DRM_MODE_CONNECTOR_DVII ||
800 			    connector->connector_type == DRM_MODE_CONNECTOR_DVID ||
801 			    connector->connector_type == DRM_MODE_CONNECTOR_DVIA ||
802 			    connector->connector_type == DRM_MODE_CONNECTOR_HDMIA ||
803 			    connector->connector_type == DRM_MODE_CONNECTOR_HDMIB)
804 				DRM_INFO("  DDC: no ddc bus - possible BIOS bug - please report to xorg-driver-ati@lists.x.org\n");
805 		}
806 		DRM_INFO("  Encoders:\n");
807 		list_for_each_entry(encoder, &dev->mode_config.encoder_list, head) {
808 			radeon_encoder = to_radeon_encoder(encoder);
809 			devices = radeon_encoder->devices & radeon_connector->devices;
810 			if (devices) {
811 				if (devices & ATOM_DEVICE_CRT1_SUPPORT)
812 					DRM_INFO("    CRT1: %s\n", encoder_names[radeon_encoder->encoder_id]);
813 				if (devices & ATOM_DEVICE_CRT2_SUPPORT)
814 					DRM_INFO("    CRT2: %s\n", encoder_names[radeon_encoder->encoder_id]);
815 				if (devices & ATOM_DEVICE_LCD1_SUPPORT)
816 					DRM_INFO("    LCD1: %s\n", encoder_names[radeon_encoder->encoder_id]);
817 				if (devices & ATOM_DEVICE_DFP1_SUPPORT)
818 					DRM_INFO("    DFP1: %s\n", encoder_names[radeon_encoder->encoder_id]);
819 				if (devices & ATOM_DEVICE_DFP2_SUPPORT)
820 					DRM_INFO("    DFP2: %s\n", encoder_names[radeon_encoder->encoder_id]);
821 				if (devices & ATOM_DEVICE_DFP3_SUPPORT)
822 					DRM_INFO("    DFP3: %s\n", encoder_names[radeon_encoder->encoder_id]);
823 				if (devices & ATOM_DEVICE_DFP4_SUPPORT)
824 					DRM_INFO("    DFP4: %s\n", encoder_names[radeon_encoder->encoder_id]);
825 				if (devices & ATOM_DEVICE_DFP5_SUPPORT)
826 					DRM_INFO("    DFP5: %s\n", encoder_names[radeon_encoder->encoder_id]);
827 				if (devices & ATOM_DEVICE_DFP6_SUPPORT)
828 					DRM_INFO("    DFP6: %s\n", encoder_names[radeon_encoder->encoder_id]);
829 				if (devices & ATOM_DEVICE_TV1_SUPPORT)
830 					DRM_INFO("    TV1: %s\n", encoder_names[radeon_encoder->encoder_id]);
831 				if (devices & ATOM_DEVICE_CV_SUPPORT)
832 					DRM_INFO("    CV: %s\n", encoder_names[radeon_encoder->encoder_id]);
833 			}
834 		}
835 		i++;
836 	}
837 }
838 
839 static bool radeon_setup_enc_conn(struct drm_device *dev)
840 {
841 	struct radeon_device *rdev = dev->dev_private;
842 	bool ret = false;
843 
844 	if (rdev->bios) {
845 		if (rdev->is_atom_bios) {
846 			ret = radeon_get_atom_connector_info_from_supported_devices_table(dev);
847 			if (!ret)
848 				ret = radeon_get_atom_connector_info_from_object_table(dev);
849 		} else {
850 			ret = radeon_get_legacy_connector_info_from_bios(dev);
851 			if (!ret)
852 				ret = radeon_get_legacy_connector_info_from_table(dev);
853 		}
854 	} else {
855 		if (!ASIC_IS_AVIVO(rdev))
856 			ret = radeon_get_legacy_connector_info_from_table(dev);
857 	}
858 	if (ret) {
859 		radeon_setup_encoder_clones(dev);
860 		radeon_print_display_setup(dev);
861 	}
862 
863 	return ret;
864 }
865 
866 /* avivo */
867 
868 /**
869  * avivo_reduce_ratio - fractional number reduction
870  *
871  * @nom: nominator
872  * @den: denominator
873  * @nom_min: minimum value for nominator
874  * @den_min: minimum value for denominator
875  *
876  * Find the greatest common divisor and apply it on both nominator and
877  * denominator, but make nominator and denominator are at least as large
878  * as their minimum values.
879  */
880 static void avivo_reduce_ratio(unsigned *nom, unsigned *den,
881 			       unsigned nom_min, unsigned den_min)
882 {
883 	unsigned tmp;
884 
885 	/* reduce the numbers to a simpler ratio */
886 	tmp = gcd(*nom, *den);
887 	*nom /= tmp;
888 	*den /= tmp;
889 
890 	/* make sure nominator is large enough */
891 	if (*nom < nom_min) {
892 		tmp = DIV_ROUND_UP(nom_min, *nom);
893 		*nom *= tmp;
894 		*den *= tmp;
895 	}
896 
897 	/* make sure the denominator is large enough */
898 	if (*den < den_min) {
899 		tmp = DIV_ROUND_UP(den_min, *den);
900 		*nom *= tmp;
901 		*den *= tmp;
902 	}
903 }
904 
905 /**
906  * avivo_get_fb_ref_div - feedback and ref divider calculation
907  *
908  * @nom: nominator
909  * @den: denominator
910  * @post_div: post divider
911  * @fb_div_max: feedback divider maximum
912  * @ref_div_max: reference divider maximum
913  * @fb_div: resulting feedback divider
914  * @ref_div: resulting reference divider
915  *
916  * Calculate feedback and reference divider for a given post divider. Makes
917  * sure we stay within the limits.
918  */
919 static void avivo_get_fb_ref_div(unsigned nom, unsigned den, unsigned post_div,
920 				 unsigned fb_div_max, unsigned ref_div_max,
921 				 unsigned *fb_div, unsigned *ref_div)
922 {
923 	/* limit reference * post divider to a maximum */
924 	ref_div_max = max(min(100 / post_div, ref_div_max), 1u);
925 
926 	/* get matching reference and feedback divider */
927 	*ref_div = min(max(den/post_div, 1u), ref_div_max);
928 	*fb_div = DIV_ROUND_CLOSEST(nom * *ref_div * post_div, den);
929 
930 	/* limit fb divider to its maximum */
931 	if (*fb_div > fb_div_max) {
932 		*ref_div = (*ref_div * fb_div_max)/(*fb_div);
933 		*fb_div = fb_div_max;
934 	}
935 }
936 
937 /**
938  * radeon_compute_pll_avivo - compute PLL paramaters
939  *
940  * @pll: information about the PLL
941  * @freq: target frequency
942  * @dot_clock_p: resulting pixel clock
943  * @fb_div_p: resulting feedback divider
944  * @frac_fb_div_p: fractional part of the feedback divider
945  * @ref_div_p: resulting reference divider
946  * @post_div_p: resulting reference divider
947  *
948  * Try to calculate the PLL parameters to generate the given frequency:
949  * dot_clock = (ref_freq * feedback_div) / (ref_div * post_div)
950  */
951 void radeon_compute_pll_avivo(struct radeon_pll *pll,
952 			      u32 freq,
953 			      u32 *dot_clock_p,
954 			      u32 *fb_div_p,
955 			      u32 *frac_fb_div_p,
956 			      u32 *ref_div_p,
957 			      u32 *post_div_p)
958 {
959 	unsigned target_clock = pll->flags & RADEON_PLL_USE_FRAC_FB_DIV ?
960 		freq : freq / 10;
961 
962 	unsigned fb_div_min, fb_div_max, fb_div;
963 	unsigned post_div_min, post_div_max, post_div;
964 	unsigned ref_div_min, ref_div_max, ref_div;
965 	unsigned post_div_best, diff_best;
966 	unsigned nom, den;
967 
968 	/* determine allowed feedback divider range */
969 	fb_div_min = pll->min_feedback_div;
970 	fb_div_max = pll->max_feedback_div;
971 
972 	if (pll->flags & RADEON_PLL_USE_FRAC_FB_DIV) {
973 		fb_div_min *= 10;
974 		fb_div_max *= 10;
975 	}
976 
977 	/* determine allowed ref divider range */
978 	if (pll->flags & RADEON_PLL_USE_REF_DIV)
979 		ref_div_min = pll->reference_div;
980 	else
981 		ref_div_min = pll->min_ref_div;
982 
983 	if (pll->flags & RADEON_PLL_USE_FRAC_FB_DIV &&
984 	    pll->flags & RADEON_PLL_USE_REF_DIV)
985 		ref_div_max = pll->reference_div;
986 	else if (pll->flags & RADEON_PLL_PREFER_MINM_OVER_MAXP)
987 		/* fix for problems on RS880 */
988 		ref_div_max = min(pll->max_ref_div, 7u);
989 	else
990 		ref_div_max = pll->max_ref_div;
991 
992 	/* determine allowed post divider range */
993 	if (pll->flags & RADEON_PLL_USE_POST_DIV) {
994 		post_div_min = pll->post_div;
995 		post_div_max = pll->post_div;
996 	} else {
997 		unsigned vco_min, vco_max;
998 
999 		if (pll->flags & RADEON_PLL_IS_LCD) {
1000 			vco_min = pll->lcd_pll_out_min;
1001 			vco_max = pll->lcd_pll_out_max;
1002 		} else {
1003 			vco_min = pll->pll_out_min;
1004 			vco_max = pll->pll_out_max;
1005 		}
1006 
1007 		if (pll->flags & RADEON_PLL_USE_FRAC_FB_DIV) {
1008 			vco_min *= 10;
1009 			vco_max *= 10;
1010 		}
1011 
1012 		post_div_min = vco_min / target_clock;
1013 		if ((target_clock * post_div_min) < vco_min)
1014 			++post_div_min;
1015 		if (post_div_min < pll->min_post_div)
1016 			post_div_min = pll->min_post_div;
1017 
1018 		post_div_max = vco_max / target_clock;
1019 		if ((target_clock * post_div_max) > vco_max)
1020 			--post_div_max;
1021 		if (post_div_max > pll->max_post_div)
1022 			post_div_max = pll->max_post_div;
1023 	}
1024 
1025 	/* represent the searched ratio as fractional number */
1026 	nom = target_clock;
1027 	den = pll->reference_freq;
1028 
1029 	/* reduce the numbers to a simpler ratio */
1030 	avivo_reduce_ratio(&nom, &den, fb_div_min, post_div_min);
1031 
1032 	/* now search for a post divider */
1033 	if (pll->flags & RADEON_PLL_PREFER_MINM_OVER_MAXP)
1034 		post_div_best = post_div_min;
1035 	else
1036 		post_div_best = post_div_max;
1037 	diff_best = ~0;
1038 
1039 	for (post_div = post_div_min; post_div <= post_div_max; ++post_div) {
1040 		unsigned diff;
1041 		avivo_get_fb_ref_div(nom, den, post_div, fb_div_max,
1042 				     ref_div_max, &fb_div, &ref_div);
1043 		diff = abs(target_clock - (pll->reference_freq * fb_div) /
1044 			(ref_div * post_div));
1045 
1046 		if (diff < diff_best || (diff == diff_best &&
1047 		    !(pll->flags & RADEON_PLL_PREFER_MINM_OVER_MAXP))) {
1048 
1049 			post_div_best = post_div;
1050 			diff_best = diff;
1051 		}
1052 	}
1053 	post_div = post_div_best;
1054 
1055 	/* get the feedback and reference divider for the optimal value */
1056 	avivo_get_fb_ref_div(nom, den, post_div, fb_div_max, ref_div_max,
1057 			     &fb_div, &ref_div);
1058 
1059 	/* reduce the numbers to a simpler ratio once more */
1060 	/* this also makes sure that the reference divider is large enough */
1061 	avivo_reduce_ratio(&fb_div, &ref_div, fb_div_min, ref_div_min);
1062 
1063 	/* avoid high jitter with small fractional dividers */
1064 	if (pll->flags & RADEON_PLL_USE_FRAC_FB_DIV && (fb_div % 10)) {
1065 		fb_div_min = max(fb_div_min, (9 - (fb_div % 10)) * 20 + 50);
1066 		if (fb_div < fb_div_min) {
1067 			unsigned tmp = DIV_ROUND_UP(fb_div_min, fb_div);
1068 			fb_div *= tmp;
1069 			ref_div *= tmp;
1070 		}
1071 	}
1072 
1073 	/* and finally save the result */
1074 	if (pll->flags & RADEON_PLL_USE_FRAC_FB_DIV) {
1075 		*fb_div_p = fb_div / 10;
1076 		*frac_fb_div_p = fb_div % 10;
1077 	} else {
1078 		*fb_div_p = fb_div;
1079 		*frac_fb_div_p = 0;
1080 	}
1081 
1082 	*dot_clock_p = ((pll->reference_freq * *fb_div_p * 10) +
1083 			(pll->reference_freq * *frac_fb_div_p)) /
1084 		       (ref_div * post_div * 10);
1085 	*ref_div_p = ref_div;
1086 	*post_div_p = post_div;
1087 
1088 	DRM_DEBUG_KMS("%d - %d, pll dividers - fb: %d.%d ref: %d, post %d\n",
1089 		      freq, *dot_clock_p * 10, *fb_div_p, *frac_fb_div_p,
1090 		      ref_div, post_div);
1091 }
1092 
1093 /* pre-avivo */
1094 static inline uint32_t radeon_div(uint64_t n, uint32_t d)
1095 {
1096 	n += d / 2;
1097 
1098 	do_div(n, d);
1099 	return n;
1100 }
1101 
1102 void radeon_compute_pll_legacy(struct radeon_pll *pll,
1103 			       uint64_t freq,
1104 			       uint32_t *dot_clock_p,
1105 			       uint32_t *fb_div_p,
1106 			       uint32_t *frac_fb_div_p,
1107 			       uint32_t *ref_div_p,
1108 			       uint32_t *post_div_p)
1109 {
1110 	uint32_t min_ref_div = pll->min_ref_div;
1111 	uint32_t max_ref_div = pll->max_ref_div;
1112 	uint32_t min_post_div = pll->min_post_div;
1113 	uint32_t max_post_div = pll->max_post_div;
1114 	uint32_t min_fractional_feed_div = 0;
1115 	uint32_t max_fractional_feed_div = 0;
1116 	uint32_t best_vco = pll->best_vco;
1117 	uint32_t best_post_div = 1;
1118 	uint32_t best_ref_div = 1;
1119 	uint32_t best_feedback_div = 1;
1120 	uint32_t best_frac_feedback_div = 0;
1121 	uint32_t best_freq = -1;
1122 	uint32_t best_error = 0xffffffff;
1123 	uint32_t best_vco_diff = 1;
1124 	uint32_t post_div;
1125 	u32 pll_out_min, pll_out_max;
1126 
1127 	DRM_DEBUG_KMS("PLL freq %llu %u %u\n", freq, pll->min_ref_div, pll->max_ref_div);
1128 	freq = freq * 1000;
1129 
1130 	if (pll->flags & RADEON_PLL_IS_LCD) {
1131 		pll_out_min = pll->lcd_pll_out_min;
1132 		pll_out_max = pll->lcd_pll_out_max;
1133 	} else {
1134 		pll_out_min = pll->pll_out_min;
1135 		pll_out_max = pll->pll_out_max;
1136 	}
1137 
1138 	if (pll_out_min > 64800)
1139 		pll_out_min = 64800;
1140 
1141 	if (pll->flags & RADEON_PLL_USE_REF_DIV)
1142 		min_ref_div = max_ref_div = pll->reference_div;
1143 	else {
1144 		while (min_ref_div < max_ref_div-1) {
1145 			uint32_t mid = (min_ref_div + max_ref_div) / 2;
1146 			uint32_t pll_in = pll->reference_freq / mid;
1147 			if (pll_in < pll->pll_in_min)
1148 				max_ref_div = mid;
1149 			else if (pll_in > pll->pll_in_max)
1150 				min_ref_div = mid;
1151 			else
1152 				break;
1153 		}
1154 	}
1155 
1156 	if (pll->flags & RADEON_PLL_USE_POST_DIV)
1157 		min_post_div = max_post_div = pll->post_div;
1158 
1159 	if (pll->flags & RADEON_PLL_USE_FRAC_FB_DIV) {
1160 		min_fractional_feed_div = pll->min_frac_feedback_div;
1161 		max_fractional_feed_div = pll->max_frac_feedback_div;
1162 	}
1163 
1164 	for (post_div = max_post_div; post_div >= min_post_div; --post_div) {
1165 		uint32_t ref_div;
1166 
1167 		if ((pll->flags & RADEON_PLL_NO_ODD_POST_DIV) && (post_div & 1))
1168 			continue;
1169 
1170 		/* legacy radeons only have a few post_divs */
1171 		if (pll->flags & RADEON_PLL_LEGACY) {
1172 			if ((post_div == 5) ||
1173 			    (post_div == 7) ||
1174 			    (post_div == 9) ||
1175 			    (post_div == 10) ||
1176 			    (post_div == 11) ||
1177 			    (post_div == 13) ||
1178 			    (post_div == 14) ||
1179 			    (post_div == 15))
1180 				continue;
1181 		}
1182 
1183 		for (ref_div = min_ref_div; ref_div <= max_ref_div; ++ref_div) {
1184 			uint32_t feedback_div, current_freq = 0, error, vco_diff;
1185 			uint32_t pll_in = pll->reference_freq / ref_div;
1186 			uint32_t min_feed_div = pll->min_feedback_div;
1187 			uint32_t max_feed_div = pll->max_feedback_div + 1;
1188 
1189 			if (pll_in < pll->pll_in_min || pll_in > pll->pll_in_max)
1190 				continue;
1191 
1192 			while (min_feed_div < max_feed_div) {
1193 				uint32_t vco;
1194 				uint32_t min_frac_feed_div = min_fractional_feed_div;
1195 				uint32_t max_frac_feed_div = max_fractional_feed_div + 1;
1196 				uint32_t frac_feedback_div;
1197 				uint64_t tmp;
1198 
1199 				feedback_div = (min_feed_div + max_feed_div) / 2;
1200 
1201 				tmp = (uint64_t)pll->reference_freq * feedback_div;
1202 				vco = radeon_div(tmp, ref_div);
1203 
1204 				if (vco < pll_out_min) {
1205 					min_feed_div = feedback_div + 1;
1206 					continue;
1207 				} else if (vco > pll_out_max) {
1208 					max_feed_div = feedback_div;
1209 					continue;
1210 				}
1211 
1212 				while (min_frac_feed_div < max_frac_feed_div) {
1213 					frac_feedback_div = (min_frac_feed_div + max_frac_feed_div) / 2;
1214 					tmp = (uint64_t)pll->reference_freq * 10000 * feedback_div;
1215 					tmp += (uint64_t)pll->reference_freq * 1000 * frac_feedback_div;
1216 					current_freq = radeon_div(tmp, ref_div * post_div);
1217 
1218 					if (pll->flags & RADEON_PLL_PREFER_CLOSEST_LOWER) {
1219 						if (freq < current_freq)
1220 							error = 0xffffffff;
1221 						else
1222 							error = freq - current_freq;
1223 					} else
1224 						error = abs(current_freq - freq);
1225 					vco_diff = abs(vco - best_vco);
1226 
1227 					if ((best_vco == 0 && error < best_error) ||
1228 					    (best_vco != 0 &&
1229 					     ((best_error > 100 && error < best_error - 100) ||
1230 					      (abs(error - best_error) < 100 && vco_diff < best_vco_diff)))) {
1231 						best_post_div = post_div;
1232 						best_ref_div = ref_div;
1233 						best_feedback_div = feedback_div;
1234 						best_frac_feedback_div = frac_feedback_div;
1235 						best_freq = current_freq;
1236 						best_error = error;
1237 						best_vco_diff = vco_diff;
1238 					} else if (current_freq == freq) {
1239 						if (best_freq == -1) {
1240 							best_post_div = post_div;
1241 							best_ref_div = ref_div;
1242 							best_feedback_div = feedback_div;
1243 							best_frac_feedback_div = frac_feedback_div;
1244 							best_freq = current_freq;
1245 							best_error = error;
1246 							best_vco_diff = vco_diff;
1247 						} else if (((pll->flags & RADEON_PLL_PREFER_LOW_REF_DIV) && (ref_div < best_ref_div)) ||
1248 							   ((pll->flags & RADEON_PLL_PREFER_HIGH_REF_DIV) && (ref_div > best_ref_div)) ||
1249 							   ((pll->flags & RADEON_PLL_PREFER_LOW_FB_DIV) && (feedback_div < best_feedback_div)) ||
1250 							   ((pll->flags & RADEON_PLL_PREFER_HIGH_FB_DIV) && (feedback_div > best_feedback_div)) ||
1251 							   ((pll->flags & RADEON_PLL_PREFER_LOW_POST_DIV) && (post_div < best_post_div)) ||
1252 							   ((pll->flags & RADEON_PLL_PREFER_HIGH_POST_DIV) && (post_div > best_post_div))) {
1253 							best_post_div = post_div;
1254 							best_ref_div = ref_div;
1255 							best_feedback_div = feedback_div;
1256 							best_frac_feedback_div = frac_feedback_div;
1257 							best_freq = current_freq;
1258 							best_error = error;
1259 							best_vco_diff = vco_diff;
1260 						}
1261 					}
1262 					if (current_freq < freq)
1263 						min_frac_feed_div = frac_feedback_div + 1;
1264 					else
1265 						max_frac_feed_div = frac_feedback_div;
1266 				}
1267 				if (current_freq < freq)
1268 					min_feed_div = feedback_div + 1;
1269 				else
1270 					max_feed_div = feedback_div;
1271 			}
1272 		}
1273 	}
1274 
1275 	*dot_clock_p = best_freq / 10000;
1276 	*fb_div_p = best_feedback_div;
1277 	*frac_fb_div_p = best_frac_feedback_div;
1278 	*ref_div_p = best_ref_div;
1279 	*post_div_p = best_post_div;
1280 	DRM_DEBUG_KMS("%lld %d, pll dividers - fb: %d.%d ref: %d, post %d\n",
1281 		      (long long)freq,
1282 		      best_freq / 1000, best_feedback_div, best_frac_feedback_div,
1283 		      best_ref_div, best_post_div);
1284 
1285 }
1286 
1287 static const struct drm_framebuffer_funcs radeon_fb_funcs = {
1288 	.destroy = drm_gem_fb_destroy,
1289 	.create_handle = drm_gem_fb_create_handle,
1290 };
1291 
1292 int
1293 radeon_framebuffer_init(struct drm_device *dev,
1294 			struct drm_framebuffer *fb,
1295 			const struct drm_mode_fb_cmd2 *mode_cmd,
1296 			struct drm_gem_object *obj)
1297 {
1298 	int ret;
1299 	fb->obj[0] = obj;
1300 	drm_helper_mode_fill_fb_struct(dev, fb, mode_cmd);
1301 	ret = drm_framebuffer_init(dev, fb, &radeon_fb_funcs);
1302 	if (ret) {
1303 		fb->obj[0] = NULL;
1304 		return ret;
1305 	}
1306 	return 0;
1307 }
1308 
1309 static struct drm_framebuffer *
1310 radeon_user_framebuffer_create(struct drm_device *dev,
1311 			       struct drm_file *file_priv,
1312 			       const struct drm_mode_fb_cmd2 *mode_cmd)
1313 {
1314 	struct drm_gem_object *obj;
1315 	struct drm_framebuffer *fb;
1316 	int ret;
1317 
1318 	obj = drm_gem_object_lookup(file_priv, mode_cmd->handles[0]);
1319 	if (obj ==  NULL) {
1320 		dev_err(dev->dev, "No GEM object associated to handle 0x%08X, "
1321 			"can't create framebuffer\n", mode_cmd->handles[0]);
1322 		return ERR_PTR(-ENOENT);
1323 	}
1324 
1325 	/* Handle is imported dma-buf, so cannot be migrated to VRAM for scanout */
1326 	if (obj->import_attach) {
1327 		DRM_DEBUG_KMS("Cannot create framebuffer from imported dma_buf\n");
1328 		return ERR_PTR(-EINVAL);
1329 	}
1330 
1331 	fb = kzalloc(sizeof(*fb), GFP_KERNEL);
1332 	if (fb == NULL) {
1333 		drm_gem_object_put(obj);
1334 		return ERR_PTR(-ENOMEM);
1335 	}
1336 
1337 	ret = radeon_framebuffer_init(dev, fb, mode_cmd, obj);
1338 	if (ret) {
1339 		kfree(fb);
1340 		drm_gem_object_put(obj);
1341 		return ERR_PTR(ret);
1342 	}
1343 
1344 	return fb;
1345 }
1346 
1347 static const struct drm_mode_config_funcs radeon_mode_funcs = {
1348 	.fb_create = radeon_user_framebuffer_create,
1349 	.output_poll_changed = drm_fb_helper_output_poll_changed,
1350 };
1351 
1352 static const struct drm_prop_enum_list radeon_tmds_pll_enum_list[] =
1353 {	{ 0, "driver" },
1354 	{ 1, "bios" },
1355 };
1356 
1357 static const struct drm_prop_enum_list radeon_tv_std_enum_list[] =
1358 {	{ TV_STD_NTSC, "ntsc" },
1359 	{ TV_STD_PAL, "pal" },
1360 	{ TV_STD_PAL_M, "pal-m" },
1361 	{ TV_STD_PAL_60, "pal-60" },
1362 	{ TV_STD_NTSC_J, "ntsc-j" },
1363 	{ TV_STD_SCART_PAL, "scart-pal" },
1364 	{ TV_STD_PAL_CN, "pal-cn" },
1365 	{ TV_STD_SECAM, "secam" },
1366 };
1367 
1368 static const struct drm_prop_enum_list radeon_underscan_enum_list[] =
1369 {	{ UNDERSCAN_OFF, "off" },
1370 	{ UNDERSCAN_ON, "on" },
1371 	{ UNDERSCAN_AUTO, "auto" },
1372 };
1373 
1374 static const struct drm_prop_enum_list radeon_audio_enum_list[] =
1375 {	{ RADEON_AUDIO_DISABLE, "off" },
1376 	{ RADEON_AUDIO_ENABLE, "on" },
1377 	{ RADEON_AUDIO_AUTO, "auto" },
1378 };
1379 
1380 /* XXX support different dither options? spatial, temporal, both, etc. */
1381 static const struct drm_prop_enum_list radeon_dither_enum_list[] =
1382 {	{ RADEON_FMT_DITHER_DISABLE, "off" },
1383 	{ RADEON_FMT_DITHER_ENABLE, "on" },
1384 };
1385 
1386 static const struct drm_prop_enum_list radeon_output_csc_enum_list[] =
1387 {	{ RADEON_OUTPUT_CSC_BYPASS, "bypass" },
1388 	{ RADEON_OUTPUT_CSC_TVRGB, "tvrgb" },
1389 	{ RADEON_OUTPUT_CSC_YCBCR601, "ycbcr601" },
1390 	{ RADEON_OUTPUT_CSC_YCBCR709, "ycbcr709" },
1391 };
1392 
1393 static int radeon_modeset_create_props(struct radeon_device *rdev)
1394 {
1395 	int sz;
1396 
1397 	if (rdev->is_atom_bios) {
1398 		rdev->mode_info.coherent_mode_property =
1399 			drm_property_create_range(rdev->ddev, 0 , "coherent", 0, 1);
1400 		if (!rdev->mode_info.coherent_mode_property)
1401 			return -ENOMEM;
1402 	}
1403 
1404 	if (!ASIC_IS_AVIVO(rdev)) {
1405 		sz = ARRAY_SIZE(radeon_tmds_pll_enum_list);
1406 		rdev->mode_info.tmds_pll_property =
1407 			drm_property_create_enum(rdev->ddev, 0,
1408 					    "tmds_pll",
1409 					    radeon_tmds_pll_enum_list, sz);
1410 	}
1411 
1412 	rdev->mode_info.load_detect_property =
1413 		drm_property_create_range(rdev->ddev, 0, "load detection", 0, 1);
1414 	if (!rdev->mode_info.load_detect_property)
1415 		return -ENOMEM;
1416 
1417 	drm_mode_create_scaling_mode_property(rdev->ddev);
1418 
1419 	sz = ARRAY_SIZE(radeon_tv_std_enum_list);
1420 	rdev->mode_info.tv_std_property =
1421 		drm_property_create_enum(rdev->ddev, 0,
1422 				    "tv standard",
1423 				    radeon_tv_std_enum_list, sz);
1424 
1425 	sz = ARRAY_SIZE(radeon_underscan_enum_list);
1426 	rdev->mode_info.underscan_property =
1427 		drm_property_create_enum(rdev->ddev, 0,
1428 				    "underscan",
1429 				    radeon_underscan_enum_list, sz);
1430 
1431 	rdev->mode_info.underscan_hborder_property =
1432 		drm_property_create_range(rdev->ddev, 0,
1433 					"underscan hborder", 0, 128);
1434 	if (!rdev->mode_info.underscan_hborder_property)
1435 		return -ENOMEM;
1436 
1437 	rdev->mode_info.underscan_vborder_property =
1438 		drm_property_create_range(rdev->ddev, 0,
1439 					"underscan vborder", 0, 128);
1440 	if (!rdev->mode_info.underscan_vborder_property)
1441 		return -ENOMEM;
1442 
1443 	sz = ARRAY_SIZE(radeon_audio_enum_list);
1444 	rdev->mode_info.audio_property =
1445 		drm_property_create_enum(rdev->ddev, 0,
1446 					 "audio",
1447 					 radeon_audio_enum_list, sz);
1448 
1449 	sz = ARRAY_SIZE(radeon_dither_enum_list);
1450 	rdev->mode_info.dither_property =
1451 		drm_property_create_enum(rdev->ddev, 0,
1452 					 "dither",
1453 					 radeon_dither_enum_list, sz);
1454 
1455 	sz = ARRAY_SIZE(radeon_output_csc_enum_list);
1456 	rdev->mode_info.output_csc_property =
1457 		drm_property_create_enum(rdev->ddev, 0,
1458 					 "output_csc",
1459 					 radeon_output_csc_enum_list, sz);
1460 
1461 	return 0;
1462 }
1463 
1464 void radeon_update_display_priority(struct radeon_device *rdev)
1465 {
1466 	/* adjustment options for the display watermarks */
1467 	if ((radeon_disp_priority == 0) || (radeon_disp_priority > 2)) {
1468 		/* set display priority to high for r3xx, rv515 chips
1469 		 * this avoids flickering due to underflow to the
1470 		 * display controllers during heavy acceleration.
1471 		 * Don't force high on rs4xx igp chips as it seems to
1472 		 * affect the sound card.  See kernel bug 15982.
1473 		 */
1474 		if ((ASIC_IS_R300(rdev) || (rdev->family == CHIP_RV515)) &&
1475 		    !(rdev->flags & RADEON_IS_IGP))
1476 			rdev->disp_priority = 2;
1477 		else
1478 			rdev->disp_priority = 0;
1479 	} else
1480 		rdev->disp_priority = radeon_disp_priority;
1481 
1482 }
1483 
1484 /*
1485  * Allocate hdmi structs and determine register offsets
1486  */
1487 static void radeon_afmt_init(struct radeon_device *rdev)
1488 {
1489 	int i;
1490 
1491 	for (i = 0; i < RADEON_MAX_AFMT_BLOCKS; i++)
1492 		rdev->mode_info.afmt[i] = NULL;
1493 
1494 	if (ASIC_IS_NODCE(rdev)) {
1495 		/* nothing to do */
1496 	} else if (ASIC_IS_DCE4(rdev)) {
1497 		static uint32_t eg_offsets[] = {
1498 			EVERGREEN_CRTC0_REGISTER_OFFSET,
1499 			EVERGREEN_CRTC1_REGISTER_OFFSET,
1500 			EVERGREEN_CRTC2_REGISTER_OFFSET,
1501 			EVERGREEN_CRTC3_REGISTER_OFFSET,
1502 			EVERGREEN_CRTC4_REGISTER_OFFSET,
1503 			EVERGREEN_CRTC5_REGISTER_OFFSET,
1504 			0x13830 - 0x7030,
1505 		};
1506 		int num_afmt;
1507 
1508 		/* DCE8 has 7 audio blocks tied to DIG encoders */
1509 		/* DCE6 has 6 audio blocks tied to DIG encoders */
1510 		/* DCE4/5 has 6 audio blocks tied to DIG encoders */
1511 		/* DCE4.1 has 2 audio blocks tied to DIG encoders */
1512 		if (ASIC_IS_DCE8(rdev))
1513 			num_afmt = 7;
1514 		else if (ASIC_IS_DCE6(rdev))
1515 			num_afmt = 6;
1516 		else if (ASIC_IS_DCE5(rdev))
1517 			num_afmt = 6;
1518 		else if (ASIC_IS_DCE41(rdev))
1519 			num_afmt = 2;
1520 		else /* DCE4 */
1521 			num_afmt = 6;
1522 
1523 		BUG_ON(num_afmt > ARRAY_SIZE(eg_offsets));
1524 		for (i = 0; i < num_afmt; i++) {
1525 			rdev->mode_info.afmt[i] = kzalloc(sizeof(struct radeon_afmt), GFP_KERNEL);
1526 			if (rdev->mode_info.afmt[i]) {
1527 				rdev->mode_info.afmt[i]->offset = eg_offsets[i];
1528 				rdev->mode_info.afmt[i]->id = i;
1529 			}
1530 		}
1531 	} else if (ASIC_IS_DCE3(rdev)) {
1532 		/* DCE3.x has 2 audio blocks tied to DIG encoders */
1533 		rdev->mode_info.afmt[0] = kzalloc(sizeof(struct radeon_afmt), GFP_KERNEL);
1534 		if (rdev->mode_info.afmt[0]) {
1535 			rdev->mode_info.afmt[0]->offset = DCE3_HDMI_OFFSET0;
1536 			rdev->mode_info.afmt[0]->id = 0;
1537 		}
1538 		rdev->mode_info.afmt[1] = kzalloc(sizeof(struct radeon_afmt), GFP_KERNEL);
1539 		if (rdev->mode_info.afmt[1]) {
1540 			rdev->mode_info.afmt[1]->offset = DCE3_HDMI_OFFSET1;
1541 			rdev->mode_info.afmt[1]->id = 1;
1542 		}
1543 	} else if (ASIC_IS_DCE2(rdev)) {
1544 		/* DCE2 has at least 1 routable audio block */
1545 		rdev->mode_info.afmt[0] = kzalloc(sizeof(struct radeon_afmt), GFP_KERNEL);
1546 		if (rdev->mode_info.afmt[0]) {
1547 			rdev->mode_info.afmt[0]->offset = DCE2_HDMI_OFFSET0;
1548 			rdev->mode_info.afmt[0]->id = 0;
1549 		}
1550 		/* r6xx has 2 routable audio blocks */
1551 		if (rdev->family >= CHIP_R600) {
1552 			rdev->mode_info.afmt[1] = kzalloc(sizeof(struct radeon_afmt), GFP_KERNEL);
1553 			if (rdev->mode_info.afmt[1]) {
1554 				rdev->mode_info.afmt[1]->offset = DCE2_HDMI_OFFSET1;
1555 				rdev->mode_info.afmt[1]->id = 1;
1556 			}
1557 		}
1558 	}
1559 }
1560 
1561 static void radeon_afmt_fini(struct radeon_device *rdev)
1562 {
1563 	int i;
1564 
1565 	for (i = 0; i < RADEON_MAX_AFMT_BLOCKS; i++) {
1566 		kfree(rdev->mode_info.afmt[i]);
1567 		rdev->mode_info.afmt[i] = NULL;
1568 	}
1569 }
1570 
1571 int radeon_modeset_init(struct radeon_device *rdev)
1572 {
1573 	int i;
1574 	int ret;
1575 
1576 	drm_mode_config_init(rdev->ddev);
1577 	rdev->mode_info.mode_config_initialized = true;
1578 
1579 	rdev->ddev->mode_config.funcs = &radeon_mode_funcs;
1580 
1581 	if (radeon_use_pflipirq == 2 && rdev->family >= CHIP_R600)
1582 		rdev->ddev->mode_config.async_page_flip = true;
1583 
1584 	if (ASIC_IS_DCE5(rdev)) {
1585 		rdev->ddev->mode_config.max_width = 16384;
1586 		rdev->ddev->mode_config.max_height = 16384;
1587 	} else if (ASIC_IS_AVIVO(rdev)) {
1588 		rdev->ddev->mode_config.max_width = 8192;
1589 		rdev->ddev->mode_config.max_height = 8192;
1590 	} else {
1591 		rdev->ddev->mode_config.max_width = 4096;
1592 		rdev->ddev->mode_config.max_height = 4096;
1593 	}
1594 
1595 	rdev->ddev->mode_config.preferred_depth = 24;
1596 	rdev->ddev->mode_config.prefer_shadow = 1;
1597 
1598 	rdev->ddev->mode_config.fb_base = rdev->mc.aper_base;
1599 
1600 	ret = radeon_modeset_create_props(rdev);
1601 	if (ret) {
1602 		return ret;
1603 	}
1604 
1605 	/* init i2c buses */
1606 	radeon_i2c_init(rdev);
1607 
1608 	/* check combios for a valid hardcoded EDID - Sun servers */
1609 	if (!rdev->is_atom_bios) {
1610 		/* check for hardcoded EDID in BIOS */
1611 		radeon_combios_check_hardcoded_edid(rdev);
1612 	}
1613 
1614 	/* allocate crtcs */
1615 	for (i = 0; i < rdev->num_crtc; i++) {
1616 		radeon_crtc_init(rdev->ddev, i);
1617 	}
1618 
1619 	/* okay we should have all the bios connectors */
1620 	ret = radeon_setup_enc_conn(rdev->ddev);
1621 	if (!ret) {
1622 		return ret;
1623 	}
1624 
1625 	/* init dig PHYs, disp eng pll */
1626 	if (rdev->is_atom_bios) {
1627 		radeon_atom_encoder_init(rdev);
1628 		radeon_atom_disp_eng_pll_init(rdev);
1629 	}
1630 
1631 	/* initialize hpd */
1632 	radeon_hpd_init(rdev);
1633 
1634 	/* setup afmt */
1635 	radeon_afmt_init(rdev);
1636 
1637 	radeon_fbdev_init(rdev);
1638 	drm_kms_helper_poll_init(rdev->ddev);
1639 
1640 	/* do pm late init */
1641 	ret = radeon_pm_late_init(rdev);
1642 
1643 	return 0;
1644 }
1645 
1646 void radeon_modeset_fini(struct radeon_device *rdev)
1647 {
1648 	if (rdev->mode_info.mode_config_initialized) {
1649 		drm_kms_helper_poll_fini(rdev->ddev);
1650 		radeon_hpd_fini(rdev);
1651 		drm_helper_force_disable_all(rdev->ddev);
1652 		radeon_fbdev_fini(rdev);
1653 		radeon_afmt_fini(rdev);
1654 		drm_mode_config_cleanup(rdev->ddev);
1655 		rdev->mode_info.mode_config_initialized = false;
1656 	}
1657 
1658 	kfree(rdev->mode_info.bios_hardcoded_edid);
1659 
1660 	/* free i2c buses */
1661 	radeon_i2c_fini(rdev);
1662 }
1663 
1664 static bool is_hdtv_mode(const struct drm_display_mode *mode)
1665 {
1666 	/* try and guess if this is a tv or a monitor */
1667 	if ((mode->vdisplay == 480 && mode->hdisplay == 720) || /* 480p */
1668 	    (mode->vdisplay == 576) || /* 576p */
1669 	    (mode->vdisplay == 720) || /* 720p */
1670 	    (mode->vdisplay == 1080)) /* 1080p */
1671 		return true;
1672 	else
1673 		return false;
1674 }
1675 
1676 bool radeon_crtc_scaling_mode_fixup(struct drm_crtc *crtc,
1677 				const struct drm_display_mode *mode,
1678 				struct drm_display_mode *adjusted_mode)
1679 {
1680 	struct drm_device *dev = crtc->dev;
1681 	struct radeon_device *rdev = dev->dev_private;
1682 	struct drm_encoder *encoder;
1683 	struct radeon_crtc *radeon_crtc = to_radeon_crtc(crtc);
1684 	struct radeon_encoder *radeon_encoder;
1685 	struct drm_connector *connector;
1686 	bool first = true;
1687 	u32 src_v = 1, dst_v = 1;
1688 	u32 src_h = 1, dst_h = 1;
1689 
1690 	radeon_crtc->h_border = 0;
1691 	radeon_crtc->v_border = 0;
1692 
1693 	list_for_each_entry(encoder, &dev->mode_config.encoder_list, head) {
1694 		if (encoder->crtc != crtc)
1695 			continue;
1696 		radeon_encoder = to_radeon_encoder(encoder);
1697 		connector = radeon_get_connector_for_encoder(encoder);
1698 
1699 		if (first) {
1700 			/* set scaling */
1701 			if (radeon_encoder->rmx_type == RMX_OFF)
1702 				radeon_crtc->rmx_type = RMX_OFF;
1703 			else if (mode->hdisplay < radeon_encoder->native_mode.hdisplay ||
1704 				 mode->vdisplay < radeon_encoder->native_mode.vdisplay)
1705 				radeon_crtc->rmx_type = radeon_encoder->rmx_type;
1706 			else
1707 				radeon_crtc->rmx_type = RMX_OFF;
1708 			/* copy native mode */
1709 			memcpy(&radeon_crtc->native_mode,
1710 			       &radeon_encoder->native_mode,
1711 				sizeof(struct drm_display_mode));
1712 			src_v = crtc->mode.vdisplay;
1713 			dst_v = radeon_crtc->native_mode.vdisplay;
1714 			src_h = crtc->mode.hdisplay;
1715 			dst_h = radeon_crtc->native_mode.hdisplay;
1716 
1717 			/* fix up for overscan on hdmi */
1718 			if (ASIC_IS_AVIVO(rdev) &&
1719 			    (!(mode->flags & DRM_MODE_FLAG_INTERLACE)) &&
1720 			    ((radeon_encoder->underscan_type == UNDERSCAN_ON) ||
1721 			     ((radeon_encoder->underscan_type == UNDERSCAN_AUTO) &&
1722 			      drm_detect_hdmi_monitor(radeon_connector_edid(connector)) &&
1723 			      is_hdtv_mode(mode)))) {
1724 				if (radeon_encoder->underscan_hborder != 0)
1725 					radeon_crtc->h_border = radeon_encoder->underscan_hborder;
1726 				else
1727 					radeon_crtc->h_border = (mode->hdisplay >> 5) + 16;
1728 				if (radeon_encoder->underscan_vborder != 0)
1729 					radeon_crtc->v_border = radeon_encoder->underscan_vborder;
1730 				else
1731 					radeon_crtc->v_border = (mode->vdisplay >> 5) + 16;
1732 				radeon_crtc->rmx_type = RMX_FULL;
1733 				src_v = crtc->mode.vdisplay;
1734 				dst_v = crtc->mode.vdisplay - (radeon_crtc->v_border * 2);
1735 				src_h = crtc->mode.hdisplay;
1736 				dst_h = crtc->mode.hdisplay - (radeon_crtc->h_border * 2);
1737 			}
1738 			first = false;
1739 		} else {
1740 			if (radeon_crtc->rmx_type != radeon_encoder->rmx_type) {
1741 				/* WARNING: Right now this can't happen but
1742 				 * in the future we need to check that scaling
1743 				 * are consistent across different encoder
1744 				 * (ie all encoder can work with the same
1745 				 *  scaling).
1746 				 */
1747 				DRM_ERROR("Scaling not consistent across encoder.\n");
1748 				return false;
1749 			}
1750 		}
1751 	}
1752 	if (radeon_crtc->rmx_type != RMX_OFF) {
1753 		fixed20_12 a, b;
1754 		a.full = dfixed_const(src_v);
1755 		b.full = dfixed_const(dst_v);
1756 		radeon_crtc->vsc.full = dfixed_div(a, b);
1757 		a.full = dfixed_const(src_h);
1758 		b.full = dfixed_const(dst_h);
1759 		radeon_crtc->hsc.full = dfixed_div(a, b);
1760 	} else {
1761 		radeon_crtc->vsc.full = dfixed_const(1);
1762 		radeon_crtc->hsc.full = dfixed_const(1);
1763 	}
1764 	return true;
1765 }
1766 
1767 /*
1768  * Retrieve current video scanout position of crtc on a given gpu, and
1769  * an optional accurate timestamp of when query happened.
1770  *
1771  * \param dev Device to query.
1772  * \param crtc Crtc to query.
1773  * \param flags Flags from caller (DRM_CALLED_FROM_VBLIRQ or 0).
1774  *              For driver internal use only also supports these flags:
1775  *
1776  *              USE_REAL_VBLANKSTART to use the real start of vblank instead
1777  *              of a fudged earlier start of vblank.
1778  *
1779  *              GET_DISTANCE_TO_VBLANKSTART to return distance to the
1780  *              fudged earlier start of vblank in *vpos and the distance
1781  *              to true start of vblank in *hpos.
1782  *
1783  * \param *vpos Location where vertical scanout position should be stored.
1784  * \param *hpos Location where horizontal scanout position should go.
1785  * \param *stime Target location for timestamp taken immediately before
1786  *               scanout position query. Can be NULL to skip timestamp.
1787  * \param *etime Target location for timestamp taken immediately after
1788  *               scanout position query. Can be NULL to skip timestamp.
1789  *
1790  * Returns vpos as a positive number while in active scanout area.
1791  * Returns vpos as a negative number inside vblank, counting the number
1792  * of scanlines to go until end of vblank, e.g., -1 means "one scanline
1793  * until start of active scanout / end of vblank."
1794  *
1795  * \return Flags, or'ed together as follows:
1796  *
1797  * DRM_SCANOUTPOS_VALID = Query successful.
1798  * DRM_SCANOUTPOS_INVBL = Inside vblank.
1799  * DRM_SCANOUTPOS_ACCURATE = Returned position is accurate. A lack of
1800  * this flag means that returned position may be offset by a constant but
1801  * unknown small number of scanlines wrt. real scanout position.
1802  *
1803  */
1804 int radeon_get_crtc_scanoutpos(struct drm_device *dev, unsigned int pipe,
1805 			       unsigned int flags, int *vpos, int *hpos,
1806 			       ktime_t *stime, ktime_t *etime,
1807 			       const struct drm_display_mode *mode)
1808 {
1809 	u32 stat_crtc = 0, vbl = 0, position = 0;
1810 	int vbl_start, vbl_end, vtotal, ret = 0;
1811 	bool in_vbl = true;
1812 
1813 	struct radeon_device *rdev = dev->dev_private;
1814 
1815 	/* preempt_disable_rt() should go right here in PREEMPT_RT patchset. */
1816 
1817 	/* Get optional system timestamp before query. */
1818 	if (stime)
1819 		*stime = ktime_get();
1820 
1821 	if (ASIC_IS_DCE4(rdev)) {
1822 		if (pipe == 0) {
1823 			vbl = RREG32(EVERGREEN_CRTC_V_BLANK_START_END +
1824 				     EVERGREEN_CRTC0_REGISTER_OFFSET);
1825 			position = RREG32(EVERGREEN_CRTC_STATUS_POSITION +
1826 					  EVERGREEN_CRTC0_REGISTER_OFFSET);
1827 			ret |= DRM_SCANOUTPOS_VALID;
1828 		}
1829 		if (pipe == 1) {
1830 			vbl = RREG32(EVERGREEN_CRTC_V_BLANK_START_END +
1831 				     EVERGREEN_CRTC1_REGISTER_OFFSET);
1832 			position = RREG32(EVERGREEN_CRTC_STATUS_POSITION +
1833 					  EVERGREEN_CRTC1_REGISTER_OFFSET);
1834 			ret |= DRM_SCANOUTPOS_VALID;
1835 		}
1836 		if (pipe == 2) {
1837 			vbl = RREG32(EVERGREEN_CRTC_V_BLANK_START_END +
1838 				     EVERGREEN_CRTC2_REGISTER_OFFSET);
1839 			position = RREG32(EVERGREEN_CRTC_STATUS_POSITION +
1840 					  EVERGREEN_CRTC2_REGISTER_OFFSET);
1841 			ret |= DRM_SCANOUTPOS_VALID;
1842 		}
1843 		if (pipe == 3) {
1844 			vbl = RREG32(EVERGREEN_CRTC_V_BLANK_START_END +
1845 				     EVERGREEN_CRTC3_REGISTER_OFFSET);
1846 			position = RREG32(EVERGREEN_CRTC_STATUS_POSITION +
1847 					  EVERGREEN_CRTC3_REGISTER_OFFSET);
1848 			ret |= DRM_SCANOUTPOS_VALID;
1849 		}
1850 		if (pipe == 4) {
1851 			vbl = RREG32(EVERGREEN_CRTC_V_BLANK_START_END +
1852 				     EVERGREEN_CRTC4_REGISTER_OFFSET);
1853 			position = RREG32(EVERGREEN_CRTC_STATUS_POSITION +
1854 					  EVERGREEN_CRTC4_REGISTER_OFFSET);
1855 			ret |= DRM_SCANOUTPOS_VALID;
1856 		}
1857 		if (pipe == 5) {
1858 			vbl = RREG32(EVERGREEN_CRTC_V_BLANK_START_END +
1859 				     EVERGREEN_CRTC5_REGISTER_OFFSET);
1860 			position = RREG32(EVERGREEN_CRTC_STATUS_POSITION +
1861 					  EVERGREEN_CRTC5_REGISTER_OFFSET);
1862 			ret |= DRM_SCANOUTPOS_VALID;
1863 		}
1864 	} else if (ASIC_IS_AVIVO(rdev)) {
1865 		if (pipe == 0) {
1866 			vbl = RREG32(AVIVO_D1CRTC_V_BLANK_START_END);
1867 			position = RREG32(AVIVO_D1CRTC_STATUS_POSITION);
1868 			ret |= DRM_SCANOUTPOS_VALID;
1869 		}
1870 		if (pipe == 1) {
1871 			vbl = RREG32(AVIVO_D2CRTC_V_BLANK_START_END);
1872 			position = RREG32(AVIVO_D2CRTC_STATUS_POSITION);
1873 			ret |= DRM_SCANOUTPOS_VALID;
1874 		}
1875 	} else {
1876 		/* Pre-AVIVO: Different encoding of scanout pos and vblank interval. */
1877 		if (pipe == 0) {
1878 			/* Assume vbl_end == 0, get vbl_start from
1879 			 * upper 16 bits.
1880 			 */
1881 			vbl = (RREG32(RADEON_CRTC_V_TOTAL_DISP) &
1882 				RADEON_CRTC_V_DISP) >> RADEON_CRTC_V_DISP_SHIFT;
1883 			/* Only retrieve vpos from upper 16 bits, set hpos == 0. */
1884 			position = (RREG32(RADEON_CRTC_VLINE_CRNT_VLINE) >> 16) & RADEON_CRTC_V_TOTAL;
1885 			stat_crtc = RREG32(RADEON_CRTC_STATUS);
1886 			if (!(stat_crtc & 1))
1887 				in_vbl = false;
1888 
1889 			ret |= DRM_SCANOUTPOS_VALID;
1890 		}
1891 		if (pipe == 1) {
1892 			vbl = (RREG32(RADEON_CRTC2_V_TOTAL_DISP) &
1893 				RADEON_CRTC_V_DISP) >> RADEON_CRTC_V_DISP_SHIFT;
1894 			position = (RREG32(RADEON_CRTC2_VLINE_CRNT_VLINE) >> 16) & RADEON_CRTC_V_TOTAL;
1895 			stat_crtc = RREG32(RADEON_CRTC2_STATUS);
1896 			if (!(stat_crtc & 1))
1897 				in_vbl = false;
1898 
1899 			ret |= DRM_SCANOUTPOS_VALID;
1900 		}
1901 	}
1902 
1903 	/* Get optional system timestamp after query. */
1904 	if (etime)
1905 		*etime = ktime_get();
1906 
1907 	/* preempt_enable_rt() should go right here in PREEMPT_RT patchset. */
1908 
1909 	/* Decode into vertical and horizontal scanout position. */
1910 	*vpos = position & 0x1fff;
1911 	*hpos = (position >> 16) & 0x1fff;
1912 
1913 	/* Valid vblank area boundaries from gpu retrieved? */
1914 	if (vbl > 0) {
1915 		/* Yes: Decode. */
1916 		ret |= DRM_SCANOUTPOS_ACCURATE;
1917 		vbl_start = vbl & 0x1fff;
1918 		vbl_end = (vbl >> 16) & 0x1fff;
1919 	}
1920 	else {
1921 		/* No: Fake something reasonable which gives at least ok results. */
1922 		vbl_start = mode->crtc_vdisplay;
1923 		vbl_end = 0;
1924 	}
1925 
1926 	/* Called from driver internal vblank counter query code? */
1927 	if (flags & GET_DISTANCE_TO_VBLANKSTART) {
1928 	    /* Caller wants distance from real vbl_start in *hpos */
1929 	    *hpos = *vpos - vbl_start;
1930 	}
1931 
1932 	/* Fudge vblank to start a few scanlines earlier to handle the
1933 	 * problem that vblank irqs fire a few scanlines before start
1934 	 * of vblank. Some driver internal callers need the true vblank
1935 	 * start to be used and signal this via the USE_REAL_VBLANKSTART flag.
1936 	 *
1937 	 * The cause of the "early" vblank irq is that the irq is triggered
1938 	 * by the line buffer logic when the line buffer read position enters
1939 	 * the vblank, whereas our crtc scanout position naturally lags the
1940 	 * line buffer read position.
1941 	 */
1942 	if (!(flags & USE_REAL_VBLANKSTART))
1943 		vbl_start -= rdev->mode_info.crtcs[pipe]->lb_vblank_lead_lines;
1944 
1945 	/* Test scanout position against vblank region. */
1946 	if ((*vpos < vbl_start) && (*vpos >= vbl_end))
1947 		in_vbl = false;
1948 
1949 	/* In vblank? */
1950 	if (in_vbl)
1951 	    ret |= DRM_SCANOUTPOS_IN_VBLANK;
1952 
1953 	/* Called from driver internal vblank counter query code? */
1954 	if (flags & GET_DISTANCE_TO_VBLANKSTART) {
1955 		/* Caller wants distance from fudged earlier vbl_start */
1956 		*vpos -= vbl_start;
1957 		return ret;
1958 	}
1959 
1960 	/* Check if inside vblank area and apply corrective offsets:
1961 	 * vpos will then be >=0 in video scanout area, but negative
1962 	 * within vblank area, counting down the number of lines until
1963 	 * start of scanout.
1964 	 */
1965 
1966 	/* Inside "upper part" of vblank area? Apply corrective offset if so: */
1967 	if (in_vbl && (*vpos >= vbl_start)) {
1968 		vtotal = mode->crtc_vtotal;
1969 		*vpos = *vpos - vtotal;
1970 	}
1971 
1972 	/* Correct for shifted end of vbl at vbl_end. */
1973 	*vpos = *vpos - vbl_end;
1974 
1975 	return ret;
1976 }
1977 
1978 bool
1979 radeon_get_crtc_scanout_position(struct drm_crtc *crtc,
1980 				 bool in_vblank_irq, int *vpos, int *hpos,
1981 				 ktime_t *stime, ktime_t *etime,
1982 				 const struct drm_display_mode *mode)
1983 {
1984 	struct drm_device *dev = crtc->dev;
1985 	unsigned int pipe = crtc->index;
1986 
1987 	return radeon_get_crtc_scanoutpos(dev, pipe, 0, vpos, hpos,
1988 					  stime, etime, mode);
1989 }
1990