radeon_driver.c revision cea7510d
1/*
2 * Copyright 2000 ATI Technologies Inc., Markham, Ontario, and
3 *                VA Linux Systems Inc., Fremont, California.
4 *
5 * All Rights Reserved.
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining
8 * a copy of this software and associated documentation files (the
9 * "Software"), to deal in the Software without restriction, including
10 * without limitation on the rights to use, copy, modify, merge,
11 * publish, distribute, sublicense, and/or sell copies of the Software,
12 * and to permit persons to whom the Software is furnished to do so,
13 * subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice (including the
16 * next paragraph) shall be included in all copies or substantial
17 * portions of the Software.
18 *
19 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
20 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
22 * NON-INFRINGEMENT.  IN NO EVENT SHALL ATI, VA LINUX SYSTEMS AND/OR
23 * THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
24 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
26 * DEALINGS IN THE SOFTWARE.
27 */
28
29#ifdef HAVE_CONFIG_H
30#include "config.h"
31#endif
32
33/*
34 * Authors:
35 *   Kevin E. Martin <martin@xfree86.org>
36 *   Rickard E. Faith <faith@valinux.com>
37 *   Alan Hourihane <alanh@fairlite.demon.co.uk>
38 *
39 * Credits:
40 *
41 *   Thanks to Ani Joshi <ajoshi@shell.unixbox.com> for providing source
42 *   code to his Radeon driver.  Portions of this file are based on the
43 *   initialization code for that driver.
44 *
45 * References:
46 *
47 * !!!! FIXME !!!!
48 *   RAGE 128 VR/ RAGE 128 GL Register Reference Manual (Technical
49 *   Reference Manual P/N RRG-G04100-C Rev. 0.04), ATI Technologies: April
50 *   1999.
51 *
52 *   RAGE 128 Software Development Manual (Technical Reference Manual P/N
53 *   SDK-G04000 Rev. 0.01), ATI Technologies: June 1999.
54 *
55 * This server does not yet support these XFree86 4.0 features:
56 * !!!! FIXME !!!!
57 *   DDC1 & DDC2
58 *   shadowfb
59 *   overlay planes
60 *
61 * Modified by Marc Aurele La France (tsi@xfree86.org) for ATI driver merge.
62 *
63 * Mergedfb and pseudo xinerama support added by Alex Deucher (agd5f@yahoo.com)
64 * based on the sis driver by Thomas Winischhofer.
65 *
66 */
67
68#include <string.h>
69#include <stdio.h>
70
71				/* Driver data structures */
72#include "radeon.h"
73#include "radeon_reg.h"
74#include "radeon_macros.h"
75#include "radeon_probe.h"
76#include "radeon_version.h"
77#include "radeon_atombios.h"
78
79#ifdef XF86DRI
80#define _XF86DRI_SERVER_
81#include "radeon_dri.h"
82#include "radeon_drm.h"
83#include "sarea.h"
84#endif
85
86#include "fb.h"
87
88				/* colormap initialization */
89#include "micmap.h"
90#include "dixstruct.h"
91
92				/* X and server generic header files */
93#include "xf86.h"
94#include "xf86_OSproc.h"
95#include "xf86RandR12.h"
96#if GET_ABI_MAJOR(ABI_VIDEODRV_VERSION) < 6
97#include "xf86RAC.h"
98#include "xf86Resources.h"
99#endif
100#include "xf86cmap.h"
101#include "vbe.h"
102
103#include "shadow.h"
104				/* vgaHW definitions */
105#ifdef WITH_VGAHW
106#include "vgaHW.h"
107#endif
108
109#ifdef HAVE_XEXTPROTO_71
110#include <X11/extensions/dpmsconst.h>
111#else
112#define DPMS_SERVER
113#include <X11/extensions/dpms.h>
114#endif
115
116
117#include "atipciids.h"
118#include "radeon_chipset_gen.h"
119
120
121#include "radeon_chipinfo_gen.h"
122
123				/* Forward definitions for driver functions */
124static Bool RADEONCloseScreen(int scrnIndex, ScreenPtr pScreen);
125static Bool RADEONSaveScreen(ScreenPtr pScreen, int mode);
126static void RADEONSave(ScrnInfoPtr pScrn);
127
128static void RADEONSaveMemMapRegisters(ScrnInfoPtr pScrn, RADEONSavePtr save);
129
130static void
131RADEONSaveBIOSRegisters(ScrnInfoPtr pScrn, RADEONSavePtr save);
132
133#ifdef XF86DRI
134static void RADEONAdjustMemMapRegisters(ScrnInfoPtr pScrn, RADEONSavePtr save);
135#endif
136
137static const OptionInfoRec RADEONOptions[] = {
138    { OPTION_NOACCEL,        "NoAccel",          OPTV_BOOLEAN, {0}, FALSE },
139    { OPTION_SW_CURSOR,      "SWcursor",         OPTV_BOOLEAN, {0}, FALSE },
140    { OPTION_DAC_6BIT,       "Dac6Bit",          OPTV_BOOLEAN, {0}, FALSE },
141    { OPTION_DAC_8BIT,       "Dac8Bit",          OPTV_BOOLEAN, {0}, TRUE  },
142#ifdef XF86DRI
143    { OPTION_BUS_TYPE,       "BusType",          OPTV_ANYSTR,  {0}, FALSE },
144    { OPTION_CP_PIO,         "CPPIOMode",        OPTV_BOOLEAN, {0}, FALSE },
145    { OPTION_USEC_TIMEOUT,   "CPusecTimeout",    OPTV_INTEGER, {0}, FALSE },
146    { OPTION_AGP_MODE,       "AGPMode",          OPTV_INTEGER, {0}, FALSE },
147    { OPTION_AGP_FW,         "AGPFastWrite",     OPTV_BOOLEAN, {0}, FALSE },
148    { OPTION_GART_SIZE_OLD,  "AGPSize",          OPTV_INTEGER, {0}, FALSE },
149    { OPTION_GART_SIZE,      "GARTSize",         OPTV_INTEGER, {0}, FALSE },
150    { OPTION_RING_SIZE,      "RingSize",         OPTV_INTEGER, {0}, FALSE },
151    { OPTION_BUFFER_SIZE,    "BufferSize",       OPTV_INTEGER, {0}, FALSE },
152    { OPTION_DEPTH_MOVE,     "EnableDepthMoves", OPTV_BOOLEAN, {0}, FALSE },
153    { OPTION_PAGE_FLIP,      "EnablePageFlip",   OPTV_BOOLEAN, {0}, FALSE },
154    { OPTION_NO_BACKBUFFER,  "NoBackBuffer",     OPTV_BOOLEAN, {0}, FALSE },
155    { OPTION_XV_DMA,         "DMAForXv",         OPTV_BOOLEAN, {0}, FALSE },
156    { OPTION_FBTEX_PERCENT,  "FBTexPercent",     OPTV_INTEGER, {0}, FALSE },
157    { OPTION_DEPTH_BITS,     "DepthBits",        OPTV_INTEGER, {0}, FALSE },
158    { OPTION_PCIAPER_SIZE,  "PCIAPERSize",      OPTV_INTEGER, {0}, FALSE },
159#ifdef USE_EXA
160    { OPTION_ACCEL_DFS,      "AccelDFS",         OPTV_BOOLEAN, {0}, FALSE },
161#endif
162#endif
163    { OPTION_IGNORE_EDID,    "IgnoreEDID",       OPTV_BOOLEAN, {0}, FALSE },
164    { OPTION_CUSTOM_EDID,    "CustomEDID",       OPTV_ANYSTR,  {0}, FALSE },
165    { OPTION_DISP_PRIORITY,  "DisplayPriority",  OPTV_ANYSTR,  {0}, FALSE },
166    { OPTION_PANEL_SIZE,     "PanelSize",        OPTV_ANYSTR,  {0}, FALSE },
167    { OPTION_MIN_DOTCLOCK,   "ForceMinDotClock", OPTV_FREQ,    {0}, FALSE },
168    { OPTION_COLOR_TILING,   "ColorTiling",      OPTV_BOOLEAN, {0}, FALSE },
169#ifdef XvExtension
170    { OPTION_VIDEO_KEY,                   "VideoKey",                 OPTV_INTEGER, {0}, FALSE },
171    { OPTION_RAGE_THEATRE_CRYSTAL,        "RageTheatreCrystal",       OPTV_INTEGER, {0}, FALSE },
172    { OPTION_RAGE_THEATRE_TUNER_PORT,     "RageTheatreTunerPort",     OPTV_INTEGER, {0}, FALSE },
173    { OPTION_RAGE_THEATRE_COMPOSITE_PORT, "RageTheatreCompositePort", OPTV_INTEGER, {0}, FALSE },
174    { OPTION_RAGE_THEATRE_SVIDEO_PORT,    "RageTheatreSVideoPort",    OPTV_INTEGER, {0}, FALSE },
175    { OPTION_TUNER_TYPE,                  "TunerType",                OPTV_INTEGER, {0}, FALSE },
176    { OPTION_RAGE_THEATRE_MICROC_PATH,    "RageTheatreMicrocPath",    OPTV_STRING, {0}, FALSE },
177    { OPTION_RAGE_THEATRE_MICROC_TYPE,    "RageTheatreMicrocType",    OPTV_STRING, {0}, FALSE },
178    { OPTION_SCALER_WIDTH,                "ScalerWidth",              OPTV_INTEGER, {0}, FALSE },
179#endif
180#ifdef RENDER
181    { OPTION_RENDER_ACCEL,   "RenderAccel",      OPTV_BOOLEAN, {0}, FALSE },
182    { OPTION_SUBPIXEL_ORDER, "SubPixelOrder",    OPTV_ANYSTR,  {0}, FALSE },
183#endif
184    { OPTION_CLOCK_GATING,   "ClockGating",      OPTV_BOOLEAN, {0}, FALSE },
185    { OPTION_VGA_ACCESS,     "VGAAccess",        OPTV_BOOLEAN, {0}, TRUE  },
186    { OPTION_REVERSE_DDC,    "ReverseDDC",       OPTV_BOOLEAN, {0}, FALSE },
187    { OPTION_LVDS_PROBE_PLL, "LVDSProbePLL",     OPTV_BOOLEAN, {0}, FALSE },
188    { OPTION_ACCELMETHOD,    "AccelMethod",      OPTV_STRING,  {0}, FALSE },
189    { OPTION_DRI,            "DRI",       	 OPTV_BOOLEAN, {0}, FALSE },
190    { OPTION_CONNECTORTABLE, "ConnectorTable",   OPTV_STRING,  {0}, FALSE },
191    { OPTION_DEFAULT_CONNECTOR_TABLE, "DefaultConnectorTable", OPTV_BOOLEAN, {0}, FALSE },
192    { OPTION_DEFAULT_TMDS_PLL, "DefaultTMDSPLL", OPTV_BOOLEAN, {0}, FALSE },
193#if defined(__powerpc__)
194    { OPTION_MAC_MODEL,      "MacModel",         OPTV_STRING,  {0}, FALSE },
195#endif
196    { OPTION_TVDAC_LOAD_DETECT, "TVDACLoadDetect", OPTV_BOOLEAN, {0}, FALSE },
197    { OPTION_FORCE_TVOUT,    "ForceTVOut",         OPTV_BOOLEAN, {0}, FALSE },
198    { OPTION_TVSTD,          "TVStandard",         OPTV_STRING,  {0}, FALSE },
199    { OPTION_IGNORE_LID_STATUS, "IgnoreLidStatus", OPTV_BOOLEAN, {0}, FALSE },
200    { OPTION_DEFAULT_TVDAC_ADJ, "DefaultTVDACAdj", OPTV_BOOLEAN, {0}, FALSE },
201    { OPTION_INT10,             "Int10",           OPTV_BOOLEAN, {0}, FALSE },
202    { OPTION_EXA_VSYNC,         "EXAVSync",        OPTV_BOOLEAN, {0}, FALSE },
203    { OPTION_ATOM_TVOUT,	"ATOMTVOut",	   OPTV_BOOLEAN, {0}, FALSE },
204    { OPTION_R4XX_ATOM,	        "R4xxATOM",	   OPTV_BOOLEAN, {0}, FALSE },
205    { OPTION_FORCE_LOW_POWER,	"ForceLowPowerMode", OPTV_BOOLEAN, {0}, FALSE },
206    { OPTION_DYNAMIC_PM,	"DynamicPM",       OPTV_BOOLEAN, {0}, FALSE },
207    { OPTION_NEW_PLL,	        "NewPLL",        OPTV_BOOLEAN, {0}, FALSE },
208    { OPTION_ZAPHOD_HEADS,      "ZaphodHeads",     OPTV_STRING,  {0}, FALSE },
209    { -1,                    NULL,               OPTV_NONE,    {0}, FALSE }
210};
211
212const OptionInfoRec *RADEONOptionsWeak(void) { return RADEONOptions; }
213
214extern _X_EXPORT int gRADEONEntityIndex;
215
216static int getRADEONEntityIndex(void)
217{
218    return gRADEONEntityIndex;
219}
220
221struct RADEONInt10Save {
222	uint32_t MEM_CNTL;
223	uint32_t MEMSIZE;
224	uint32_t MPP_TB_CONFIG;
225};
226
227static Bool RADEONMapMMIO(ScrnInfoPtr pScrn);
228static Bool RADEONUnmapMMIO(ScrnInfoPtr pScrn);
229
230static void *
231radeonShadowWindow(ScreenPtr screen, CARD32 row, CARD32 offset, int mode,
232		   CARD32 *size, void *closure)
233{
234    ScrnInfoPtr pScrn = xf86Screens[screen->myNum];
235    RADEONInfoPtr  info   = RADEONPTR(pScrn);
236    int stride;
237
238    stride = (pScrn->displayWidth * pScrn->bitsPerPixel) / 8;
239    *size = stride;
240
241    return ((uint8_t *)info->FB + pScrn->fbOffset + row * stride + offset);
242}
243static Bool
244RADEONCreateScreenResources (ScreenPtr pScreen)
245{
246   ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum];
247   RADEONInfoPtr  info   = RADEONPTR(pScrn);
248   PixmapPtr pixmap;
249
250   pScreen->CreateScreenResources = info->CreateScreenResources;
251   if (!(*pScreen->CreateScreenResources)(pScreen))
252      return FALSE;
253   pScreen->CreateScreenResources = RADEONCreateScreenResources;
254
255   if (info->r600_shadow_fb) {
256       pixmap = pScreen->GetScreenPixmap(pScreen);
257
258       if (!shadowAdd(pScreen, pixmap, shadowUpdatePackedWeak(),
259		      radeonShadowWindow, 0, NULL))
260	   return FALSE;
261   }
262   return TRUE;
263}
264
265RADEONEntPtr RADEONEntPriv(ScrnInfoPtr pScrn)
266{
267    DevUnion     *pPriv;
268    RADEONInfoPtr  info   = RADEONPTR(pScrn);
269    pPriv = xf86GetEntityPrivate(info->pEnt->index,
270                                 getRADEONEntityIndex());
271    return pPriv->ptr;
272}
273
274static void
275RADEONPreInt10Save(ScrnInfoPtr pScrn, void **pPtr)
276{
277    RADEONInfoPtr  info   = RADEONPTR(pScrn);
278    unsigned char *RADEONMMIO = info->MMIO;
279    uint32_t       CardTmp;
280    static struct  RADEONInt10Save SaveStruct = { 0, 0, 0 };
281
282    if (!IS_AVIVO_VARIANT) {
283	/* Save the values and zap MEM_CNTL */
284	SaveStruct.MEM_CNTL = INREG(RADEON_MEM_CNTL);
285	SaveStruct.MEMSIZE = INREG(RADEON_CONFIG_MEMSIZE);
286	SaveStruct.MPP_TB_CONFIG = INREG(RADEON_MPP_TB_CONFIG);
287
288	/*
289	 * Zap MEM_CNTL and set MPP_TB_CONFIG<31:24> to 4
290	 */
291	OUTREG(RADEON_MEM_CNTL, 0);
292	CardTmp = SaveStruct.MPP_TB_CONFIG & 0x00ffffffu;
293	CardTmp |= 0x04 << 24;
294	OUTREG(RADEON_MPP_TB_CONFIG, CardTmp);
295    }
296
297    *pPtr = (void *)&SaveStruct;
298}
299
300static void
301RADEONPostInt10Check(ScrnInfoPtr pScrn, void *ptr)
302{
303    RADEONInfoPtr  info   = RADEONPTR(pScrn);
304    unsigned char *RADEONMMIO = info->MMIO;
305    struct RADEONInt10Save *pSave = ptr;
306    uint32_t CardTmp;
307
308    /* If we don't have a valid (non-zero) saved MEM_CNTL, get out now */
309    if (!pSave || !pSave->MEM_CNTL)
310	return;
311
312    if (IS_AVIVO_VARIANT)
313	return;
314
315    /*
316     * If either MEM_CNTL is currently zero or inconistent (configured for
317     * two channels with the two channels configured differently), restore
318     * the saved registers.
319     */
320    CardTmp = INREG(RADEON_MEM_CNTL);
321    if (!CardTmp ||
322	((CardTmp & 1) &&
323	 (((CardTmp >> 8) & 0xff) != ((CardTmp >> 24) & 0xff)))) {
324	/* Restore the saved registers */
325	xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
326		   "Restoring MEM_CNTL (%08lx), setting to %08lx\n",
327		   (unsigned long)CardTmp, (unsigned long)pSave->MEM_CNTL);
328	OUTREG(RADEON_MEM_CNTL, pSave->MEM_CNTL);
329
330	CardTmp = INREG(RADEON_CONFIG_MEMSIZE);
331	if (CardTmp != pSave->MEMSIZE) {
332	    xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
333		       "Restoring CONFIG_MEMSIZE (%08lx), setting to %08lx\n",
334		       (unsigned long)CardTmp, (unsigned long)pSave->MEMSIZE);
335	    OUTREG(RADEON_CONFIG_MEMSIZE, pSave->MEMSIZE);
336	}
337    }
338
339    CardTmp = INREG(RADEON_MPP_TB_CONFIG);
340    if ((CardTmp & 0xff000000u) != (pSave->MPP_TB_CONFIG & 0xff000000u)) {
341	xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
342	           "Restoring MPP_TB_CONFIG<31:24> (%02lx), setting to %02lx\n",
343	 	   (unsigned long)CardTmp >> 24,
344		   (unsigned long)pSave->MPP_TB_CONFIG >> 24);
345	CardTmp &= 0x00ffffffu;
346	CardTmp |= (pSave->MPP_TB_CONFIG & 0xff000000u);
347	OUTREG(RADEON_MPP_TB_CONFIG, CardTmp);
348    }
349}
350
351/* Allocate our private RADEONInfoRec */
352Bool RADEONGetRec(ScrnInfoPtr pScrn)
353{
354    if (pScrn->driverPrivate) return TRUE;
355
356    pScrn->driverPrivate = xnfcalloc(sizeof(RADEONInfoRec), 1);
357    return TRUE;
358}
359
360/* Free our private RADEONInfoRec */
361void RADEONFreeRec(ScrnInfoPtr pScrn)
362{
363    RADEONInfoPtr  info;
364    int i;
365
366    if (!pScrn || !pScrn->driverPrivate) return;
367
368    info = RADEONPTR(pScrn);
369
370    if (info->cp) {
371	free(info->cp);
372	info->cp = NULL;
373    }
374
375    if (info->dri) {
376	free(info->dri);
377	info->dri = NULL;
378    }
379
380    if (info->accel_state) {
381	free(info->accel_state);
382	info->accel_state = NULL;
383    }
384
385    for (i = 0; i < RADEON_MAX_BIOS_CONNECTOR; i++) {
386	if (info->encoders[i]) {
387	    if (info->encoders[i]->dev_priv) {
388		free(info->encoders[i]->dev_priv);
389		info->encoders[i]->dev_priv = NULL;
390	    }
391	    free(info->encoders[i]);
392	    info->encoders[i]= NULL;
393	}
394    }
395
396    free(pScrn->driverPrivate);
397    pScrn->driverPrivate = NULL;
398}
399
400/* Memory map the MMIO region.  Used during pre-init and by RADEONMapMem,
401 * below
402 */
403static Bool RADEONMapMMIO(ScrnInfoPtr pScrn)
404{
405#ifdef XSERVER_LIBPCIACCESS
406    int err;
407#endif
408    RADEONInfoPtr  info = RADEONPTR(pScrn);
409    RADEONEntPtr pRADEONEnt = RADEONEntPriv(pScrn);
410
411    if (pRADEONEnt->MMIO) {
412        pRADEONEnt->MMIO_cnt++;
413        info->MMIO = pRADEONEnt->MMIO;
414        return TRUE;
415    }
416
417#ifndef XSERVER_LIBPCIACCESS
418
419    info->MMIO = xf86MapPciMem(pScrn->scrnIndex,
420			       VIDMEM_MMIO | VIDMEM_READSIDEEFFECT,
421			       info->PciTag,
422			       info->MMIOAddr,
423			       info->MMIOSize);
424
425    if (!info->MMIO)
426        return FALSE;
427#else
428
429    err = pci_device_map_range(info->PciInfo,
430				   info->MMIOAddr,
431				   info->MMIOSize,
432				   PCI_DEV_MAP_FLAG_WRITABLE,
433				   &info->MMIO);
434
435    if (err) {
436	xf86DrvMsg (pScrn->scrnIndex, X_ERROR,
437                    "Unable to map MMIO aperture. %s (%d)\n",
438                    strerror (err), err);
439	return FALSE;
440    }
441
442#endif
443
444    pRADEONEnt->MMIO = info->MMIO;
445    pRADEONEnt->MMIO_cnt = 1;
446    return TRUE;
447}
448
449/* Unmap the MMIO region.  Used during pre-init and by RADEONUnmapMem,
450 * below
451 */
452static Bool RADEONUnmapMMIO(ScrnInfoPtr pScrn)
453{
454    RADEONInfoPtr  info = RADEONPTR(pScrn);
455    RADEONEntPtr pRADEONEnt = RADEONEntPriv(pScrn);
456
457    /* refcount for zaphod */
458    if (--pRADEONEnt->MMIO_cnt != 0) {
459      info->MMIO = NULL;
460      return TRUE;
461    }
462
463#ifndef XSERVER_LIBPCIACCESS
464    xf86UnMapVidMem(pScrn->scrnIndex, info->MMIO, info->MMIOSize);
465#else
466    pci_device_unmap_range(info->PciInfo, info->MMIO, info->MMIOSize);
467#endif
468
469    pRADEONEnt->MMIO = NULL;
470    info->MMIO = NULL;
471    return TRUE;
472}
473
474/* Memory map the frame buffer.  Used by RADEONMapMem, below. */
475static Bool RADEONMapFB(ScrnInfoPtr pScrn)
476{
477#ifdef XSERVER_LIBPCIACCESS
478    int err;
479#endif
480    RADEONInfoPtr  info = RADEONPTR(pScrn);
481    RADEONEntPtr pRADEONEnt = RADEONEntPriv(pScrn);
482
483    if (pRADEONEnt->FB) {
484        pRADEONEnt->FB_cnt++;
485        info->FB = pRADEONEnt->FB;
486        return TRUE;
487    }
488
489    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
490		   "Map: 0x%016llx, 0x%08lx\n", info->LinearAddr, info->FbMapSize);
491
492#ifndef XSERVER_LIBPCIACCESS
493
494    info->FB = xf86MapPciMem(pScrn->scrnIndex,
495			     VIDMEM_FRAMEBUFFER,
496			     info->PciTag,
497			     info->LinearAddr,
498			     info->FbMapSize);
499
500    if (!info->FB) return FALSE;
501
502#else
503
504    err = pci_device_map_range(info->PciInfo,
505				   info->LinearAddr,
506				   info->FbMapSize,
507				   PCI_DEV_MAP_FLAG_WRITABLE |
508				   PCI_DEV_MAP_FLAG_WRITE_COMBINE,
509				   &info->FB);
510
511    if (err) {
512	xf86DrvMsg (pScrn->scrnIndex, X_ERROR,
513                    "Unable to map FB aperture. %s (%d)\n",
514                    strerror (err), err);
515	return FALSE;
516    }
517
518#endif
519
520    pRADEONEnt->FB = info->FB;
521    pRADEONEnt->FB_cnt = 1;
522    return TRUE;
523}
524
525/* Unmap the frame buffer.  Used by RADEONUnmapMem, below. */
526static Bool RADEONUnmapFB(ScrnInfoPtr pScrn)
527{
528    RADEONInfoPtr  info = RADEONPTR(pScrn);
529    RADEONEntPtr pRADEONEnt = RADEONEntPriv(pScrn);
530
531    /* refcount for zaphod */
532    if (--pRADEONEnt->FB_cnt != 0) {
533      info->FB = NULL;
534      return TRUE;
535    }
536
537#ifndef XSERVER_LIBPCIACCESS
538    xf86UnMapVidMem(pScrn->scrnIndex, info->FB, info->FbMapSize);
539#else
540    pci_device_unmap_range(info->PciInfo, info->FB, info->FbMapSize);
541#endif
542
543    pRADEONEnt->FB = NULL;
544    info->FB = NULL;
545    return TRUE;
546}
547
548/* Memory map the MMIO region and the frame buffer */
549static Bool RADEONMapMem(ScrnInfoPtr pScrn)
550{
551    if (!RADEONMapMMIO(pScrn)) return FALSE;
552    if (!RADEONMapFB(pScrn)) {
553	RADEONUnmapMMIO(pScrn);
554	return FALSE;
555    }
556    return TRUE;
557}
558
559/* Unmap the MMIO region and the frame buffer */
560static Bool RADEONUnmapMem(ScrnInfoPtr pScrn)
561{
562    if (!RADEONUnmapMMIO(pScrn) || !RADEONUnmapFB(pScrn)) return FALSE;
563    return TRUE;
564}
565
566void RADEONPllErrataAfterIndex(RADEONInfoPtr info)
567{
568    unsigned char *RADEONMMIO = info->MMIO;
569
570    if (!(info->ChipErrata & CHIP_ERRATA_PLL_DUMMYREADS))
571	return;
572
573    /* This workaround is necessary on rv200 and RS200 or PLL
574     * reads may return garbage (among others...)
575     */
576    (void)INREG(RADEON_CLOCK_CNTL_DATA);
577    (void)INREG(RADEON_CRTC_GEN_CNTL);
578}
579
580void RADEONPllErrataAfterData(RADEONInfoPtr info)
581{
582    unsigned char *RADEONMMIO = info->MMIO;
583
584    /* This workarounds is necessary on RV100, RS100 and RS200 chips
585     * or the chip could hang on a subsequent access
586     */
587    if (info->ChipErrata & CHIP_ERRATA_PLL_DELAY) {
588	/* we can't deal with posted writes here ... */
589	usleep(5000);
590    }
591
592    /* This function is required to workaround a hardware bug in some (all?)
593     * revisions of the R300.  This workaround should be called after every
594     * CLOCK_CNTL_INDEX register access.  If not, register reads afterward
595     * may not be correct.
596     */
597    if (info->ChipErrata & CHIP_ERRATA_R300_CG) {
598	uint32_t save, tmp;
599
600	save = INREG(RADEON_CLOCK_CNTL_INDEX);
601	tmp = save & ~(0x3f | RADEON_PLL_WR_EN);
602	OUTREG(RADEON_CLOCK_CNTL_INDEX, tmp);
603	tmp = INREG(RADEON_CLOCK_CNTL_DATA);
604	OUTREG(RADEON_CLOCK_CNTL_INDEX, save);
605    }
606}
607
608/* Read PLL register */
609unsigned RADEONINPLL(ScrnInfoPtr pScrn, int addr)
610{
611    RADEONInfoPtr  info       = RADEONPTR(pScrn);
612    unsigned char *RADEONMMIO = info->MMIO;
613    uint32_t       data;
614
615    OUTREG8(RADEON_CLOCK_CNTL_INDEX, addr & 0x3f);
616    RADEONPllErrataAfterIndex(info);
617    data = INREG(RADEON_CLOCK_CNTL_DATA);
618    RADEONPllErrataAfterData(info);
619
620    return data;
621}
622
623/* Write PLL information */
624void RADEONOUTPLL(ScrnInfoPtr pScrn, int addr, uint32_t data)
625{
626    RADEONInfoPtr  info       = RADEONPTR(pScrn);
627    unsigned char *RADEONMMIO = info->MMIO;
628
629    OUTREG8(RADEON_CLOCK_CNTL_INDEX, (((addr) & 0x3f) |
630				      RADEON_PLL_WR_EN));
631    RADEONPllErrataAfterIndex(info);
632    OUTREG(RADEON_CLOCK_CNTL_DATA, data);
633    RADEONPllErrataAfterData(info);
634}
635
636/* Read MC register */
637unsigned RADEONINMC(ScrnInfoPtr pScrn, int addr)
638{
639    RADEONInfoPtr  info       = RADEONPTR(pScrn);
640    unsigned char *RADEONMMIO = info->MMIO;
641    uint32_t       data;
642
643    if ((info->ChipFamily == CHIP_FAMILY_RS690) ||
644	(info->ChipFamily == CHIP_FAMILY_RS740)) {
645	OUTREG(RS690_MC_INDEX, (addr & RS690_MC_INDEX_MASK));
646	data = INREG(RS690_MC_DATA);
647    } else if (info->ChipFamily == CHIP_FAMILY_RS600) {
648	OUTREG(RS600_MC_INDEX, ((addr & RS600_MC_ADDR_MASK) | RS600_MC_IND_CITF_ARB0));
649	data = INREG(RS600_MC_DATA);
650    } else if ((info->ChipFamily == CHIP_FAMILY_RS780) ||
651	       (info->ChipFamily == CHIP_FAMILY_RS880)) {
652	OUTREG(RS780_MC_INDEX, (addr & RS780_MC_INDEX_MASK));
653	data = INREG(RS780_MC_DATA);
654    } else if (info->ChipFamily >= CHIP_FAMILY_R600) {
655	data = 0;
656    } else if (IS_AVIVO_VARIANT) {
657	OUTREG(AVIVO_MC_INDEX, (addr & 0xff) | 0x7f0000);
658	(void)INREG(AVIVO_MC_INDEX);
659	data = INREG(AVIVO_MC_DATA);
660
661	OUTREG(AVIVO_MC_INDEX, 0);
662	(void)INREG(AVIVO_MC_INDEX);
663    } else {
664	OUTREG(R300_MC_IND_INDEX, addr & 0x3f);
665	(void)INREG(R300_MC_IND_INDEX);
666	data = INREG(R300_MC_IND_DATA);
667
668	OUTREG(R300_MC_IND_INDEX, 0);
669	(void)INREG(R300_MC_IND_INDEX);
670    }
671
672    return data;
673}
674
675/* Write MC information */
676void RADEONOUTMC(ScrnInfoPtr pScrn, int addr, uint32_t data)
677{
678    RADEONInfoPtr  info       = RADEONPTR(pScrn);
679    unsigned char *RADEONMMIO = info->MMIO;
680
681    if ((info->ChipFamily == CHIP_FAMILY_RS690) ||
682	(info->ChipFamily == CHIP_FAMILY_RS740)) {
683	OUTREG(RS690_MC_INDEX, ((addr & RS690_MC_INDEX_MASK) |
684				RS690_MC_INDEX_WR_EN));
685	OUTREG(RS690_MC_DATA, data);
686	OUTREG(RS690_MC_INDEX, RS690_MC_INDEX_WR_ACK);
687    } else if (info->ChipFamily == CHIP_FAMILY_RS600) {
688	OUTREG(RS600_MC_INDEX, ((addr & RS600_MC_ADDR_MASK) |
689				RS600_MC_IND_CITF_ARB0 |
690				RS600_MC_IND_WR_EN));
691	OUTREG(RS600_MC_DATA, data);
692    } else if ((info->ChipFamily == CHIP_FAMILY_RS780) ||
693	       (info->ChipFamily == CHIP_FAMILY_RS880)) {
694	OUTREG(RS780_MC_INDEX, ((addr & RS780_MC_INDEX_MASK) |
695				      RS780_MC_INDEX_WR_EN));
696	OUTREG(RS780_MC_DATA, data);
697    } else if (info->ChipFamily >= CHIP_FAMILY_R600) {
698	// do nothing
699    } else if (IS_AVIVO_VARIANT) {
700	OUTREG(AVIVO_MC_INDEX, (addr & 0xff) | 0xff0000);
701	(void)INREG(AVIVO_MC_INDEX);
702	OUTREG(AVIVO_MC_DATA, data);
703	OUTREG(AVIVO_MC_INDEX, 0);
704	(void)INREG(AVIVO_MC_INDEX);
705    } else {
706	OUTREG(R300_MC_IND_INDEX, (((addr) & 0x3f) |
707				   R300_MC_IND_WR_EN));
708	(void)INREG(R300_MC_IND_INDEX);
709	OUTREG(R300_MC_IND_DATA, data);
710	OUTREG(R300_MC_IND_INDEX, 0);
711	(void)INREG(R300_MC_IND_INDEX);
712    }
713}
714
715/* Read PCIE register */
716unsigned RADEONINPCIE(ScrnInfoPtr pScrn, int addr)
717{
718    RADEONInfoPtr  info       = RADEONPTR(pScrn);
719    unsigned char *RADEONMMIO = info->MMIO;
720    CARD32         data;
721
722    OUTREG(RADEON_PCIE_INDEX, addr & 0xff);
723    data = INREG(RADEON_PCIE_DATA);
724
725    return data;
726}
727
728/* Write PCIE register */
729void RADEONOUTPCIE(ScrnInfoPtr pScrn, int addr, uint32_t data)
730{
731    RADEONInfoPtr  info       = RADEONPTR(pScrn);
732    unsigned char *RADEONMMIO = info->MMIO;
733
734    OUTREG(RADEON_PCIE_INDEX, ((addr) & 0xff));
735    OUTREG(RADEON_PCIE_DATA, data);
736}
737
738/* Read PCIE PORT register */
739unsigned R600INPCIE_PORT(ScrnInfoPtr pScrn, int addr)
740{
741    RADEONInfoPtr  info       = RADEONPTR(pScrn);
742    unsigned char *RADEONMMIO = info->MMIO;
743    CARD32         data;
744
745    OUTREG(R600_PCIE_PORT_INDEX, addr & 0xff);
746    data = INREG(R600_PCIE_PORT_DATA);
747
748    return data;
749}
750
751/* Write PCIE PORT register */
752void R600OUTPCIE_PORT(ScrnInfoPtr pScrn, int addr, uint32_t data)
753{
754    RADEONInfoPtr  info       = RADEONPTR(pScrn);
755    unsigned char *RADEONMMIO = info->MMIO;
756
757    OUTREG(R600_PCIE_PORT_INDEX, ((addr) & 0xff));
758    OUTREG(R600_PCIE_PORT_DATA, data);
759}
760
761static Bool radeon_get_mc_idle(ScrnInfoPtr pScrn)
762{
763    RADEONInfoPtr  info       = RADEONPTR(pScrn);
764    unsigned char *RADEONMMIO = info->MMIO;
765
766    if (info->ChipFamily >= CHIP_FAMILY_CEDAR) {
767	if (INREG(R600_SRBM_STATUS) & 0x1f00)
768	    return FALSE;
769	else
770	    return TRUE;
771    } else if (info->ChipFamily >= CHIP_FAMILY_R600) {
772	if (INREG(R600_SRBM_STATUS) & 0x3f00)
773	    return FALSE;
774	else
775	    return TRUE;
776    } else if (info->ChipFamily == CHIP_FAMILY_RV515) {
777	if (INMC(pScrn, RV515_MC_STATUS) & RV515_MC_STATUS_IDLE)
778	    return TRUE;
779	else
780	    return FALSE;
781    } else if (info->ChipFamily == CHIP_FAMILY_RS600) {
782	if (INMC(pScrn, RS600_MC_STATUS) & RS600_MC_IDLE)
783	    return TRUE;
784	else
785	    return FALSE;
786    } else if ((info->ChipFamily == CHIP_FAMILY_RS690) ||
787	       (info->ChipFamily == CHIP_FAMILY_RS740)) {
788	if (INMC(pScrn, RS690_MC_STATUS) & RS690_MC_STATUS_IDLE)
789	    return TRUE;
790	else
791	    return FALSE;
792    } else if (info->ChipFamily >= CHIP_FAMILY_R520) {
793	if (INMC(pScrn, R520_MC_STATUS) & R520_MC_STATUS_IDLE)
794	    return TRUE;
795	else
796	    return FALSE;
797    } else if ((info->ChipFamily == CHIP_FAMILY_RS400) ||
798	       (info->ChipFamily == CHIP_FAMILY_RS480)) {
799	if (INREG(RADEON_MC_STATUS) & RADEON_MC_IDLE)
800	    return TRUE;
801	else
802	    return FALSE;
803    } else if (IS_R300_VARIANT) {
804	if (INREG(RADEON_MC_STATUS) & R300_MC_IDLE)
805	    return TRUE;
806	else
807	    return FALSE;
808    } else {
809	if (INREG(RADEON_MC_STATUS) & RADEON_MC_IDLE)
810	    return TRUE;
811	else
812	    return FALSE;
813    }
814}
815
816#define LOC_FB 0x1
817#define LOC_AGP 0x2
818static void radeon_write_mc_fb_agp_location(ScrnInfoPtr pScrn, int mask, uint32_t fb_loc, uint32_t agp_loc, uint32_t agp_loc_hi)
819{
820    RADEONInfoPtr  info       = RADEONPTR(pScrn);
821    unsigned char *RADEONMMIO = info->MMIO;
822
823    /* evergreen is same as r7xx */
824    if (info->ChipFamily >= CHIP_FAMILY_RV770) {
825	if (mask & LOC_FB)
826	    OUTREG(R700_MC_VM_FB_LOCATION, fb_loc);
827	if (mask & LOC_AGP) {
828	    OUTREG(R700_MC_VM_AGP_BOT, agp_loc);
829	    OUTREG(R700_MC_VM_AGP_TOP, agp_loc_hi);
830	}
831    } else if (info->ChipFamily >= CHIP_FAMILY_R600) {
832	if (mask & LOC_FB)
833	    OUTREG(R600_MC_VM_FB_LOCATION, fb_loc);
834	if (mask & LOC_AGP) {
835	    OUTREG(R600_MC_VM_AGP_BOT, agp_loc);
836	    OUTREG(R600_MC_VM_AGP_TOP, agp_loc_hi);
837	}
838    } else if (info->ChipFamily == CHIP_FAMILY_RV515) {
839	if (mask & LOC_FB)
840	    OUTMC(pScrn, RV515_MC_FB_LOCATION, fb_loc);
841	if (mask & LOC_AGP)
842	    OUTMC(pScrn, RV515_MC_AGP_LOCATION, agp_loc);
843	(void)INMC(pScrn, RV515_MC_AGP_LOCATION);
844    } else if (info->ChipFamily == CHIP_FAMILY_RS600) {
845	if (mask & LOC_FB)
846	    OUTMC(pScrn, RS600_MC_FB_LOCATION, fb_loc);
847	if (mask & LOC_AGP)
848	    OUTMC(pScrn, RS600_MC_AGP_LOCATION, agp_loc);
849    } else if ((info->ChipFamily == CHIP_FAMILY_RS690) ||
850	       (info->ChipFamily == CHIP_FAMILY_RS740)) {
851	if (mask & LOC_FB)
852	    OUTMC(pScrn, RS690_MC_FB_LOCATION, fb_loc);
853	if (mask & LOC_AGP)
854	    OUTMC(pScrn, RS690_MC_AGP_LOCATION, agp_loc);
855    } else if (info->ChipFamily >= CHIP_FAMILY_R520) {
856	if (mask & LOC_FB)
857	    OUTMC(pScrn, R520_MC_FB_LOCATION, fb_loc);
858	if (mask & LOC_AGP)
859	    OUTMC(pScrn, R520_MC_AGP_LOCATION, agp_loc);
860	(void)INMC(pScrn, R520_MC_FB_LOCATION);
861    } else {
862	if (mask & LOC_FB)
863	    OUTREG(RADEON_MC_FB_LOCATION, fb_loc);
864	if (mask & LOC_AGP)
865	    OUTREG(RADEON_MC_AGP_LOCATION, agp_loc);
866    }
867}
868
869static void radeon_read_mc_fb_agp_location(ScrnInfoPtr pScrn, int mask, uint32_t *fb_loc, uint32_t *agp_loc, uint32_t *agp_loc_hi)
870{
871    RADEONInfoPtr  info       = RADEONPTR(pScrn);
872    unsigned char *RADEONMMIO = info->MMIO;
873
874    /* evergreen is same as r7xx */
875    if (info->ChipFamily >= CHIP_FAMILY_RV770) {
876	if (mask & LOC_FB)
877	    *fb_loc = INREG(R700_MC_VM_FB_LOCATION);
878	if (mask & LOC_AGP) {
879	    *agp_loc = INREG(R700_MC_VM_AGP_BOT);
880	    *agp_loc_hi = INREG(R700_MC_VM_AGP_TOP);
881	}
882    } else if (info->ChipFamily >= CHIP_FAMILY_R600) {
883	if (mask & LOC_FB)
884	    *fb_loc = INREG(R600_MC_VM_FB_LOCATION);
885	if (mask & LOC_AGP) {
886	    *agp_loc = INREG(R600_MC_VM_AGP_BOT);
887	    *agp_loc_hi = INREG(R600_MC_VM_AGP_TOP);
888	}
889    } else if (info->ChipFamily == CHIP_FAMILY_RV515) {
890	if (mask & LOC_FB)
891	    *fb_loc = INMC(pScrn, RV515_MC_FB_LOCATION);
892	if (mask & LOC_AGP) {
893	    *agp_loc = INMC(pScrn, RV515_MC_AGP_LOCATION);
894	    *agp_loc_hi = 0;
895	}
896    } else if (info->ChipFamily == CHIP_FAMILY_RS600) {
897	if (mask & LOC_FB)
898	    *fb_loc = INMC(pScrn, RS600_MC_FB_LOCATION);
899	if (mask & LOC_AGP) {
900	    *agp_loc = INMC(pScrn, RS600_MC_AGP_LOCATION);
901	    *agp_loc_hi = 0;
902	}
903    } else if ((info->ChipFamily == CHIP_FAMILY_RS690) ||
904	       (info->ChipFamily == CHIP_FAMILY_RS740)) {
905	if (mask & LOC_FB)
906	    *fb_loc = INMC(pScrn, RS690_MC_FB_LOCATION);
907	if (mask & LOC_AGP) {
908	    *agp_loc = INMC(pScrn, RS690_MC_AGP_LOCATION);
909	    *agp_loc_hi = 0;
910	}
911    } else if (info->ChipFamily >= CHIP_FAMILY_R520) {
912	if (mask & LOC_FB)
913	    *fb_loc = INMC(pScrn, R520_MC_FB_LOCATION);
914	if (mask & LOC_AGP) {
915	    *agp_loc = INMC(pScrn, R520_MC_AGP_LOCATION);
916	    *agp_loc_hi = 0;
917	}
918    } else {
919	if (mask & LOC_FB)
920	    *fb_loc = INREG(RADEON_MC_FB_LOCATION);
921	if (mask & LOC_AGP)
922	    *agp_loc = INREG(RADEON_MC_AGP_LOCATION);
923    }
924}
925
926#if 0
927/* Read PAL information (only used for debugging) */
928static int RADEONINPAL(int idx)
929{
930    RADEONInfoPtr  info       = RADEONPTR(pScrn);
931    unsigned char *RADEONMMIO = info->MMIO;
932
933    OUTREG(RADEON_PALETTE_INDEX, idx << 16);
934    return INREG(RADEON_PALETTE_DATA);
935}
936#endif
937
938/* Wait for vertical sync on primary CRTC */
939void RADEONWaitForVerticalSync(ScrnInfoPtr pScrn)
940{
941    RADEONInfoPtr  info       = RADEONPTR(pScrn);
942    unsigned char *RADEONMMIO = info->MMIO;
943    uint32_t       crtc_gen_cntl;
944    struct timeval timeout;
945
946    crtc_gen_cntl = INREG(RADEON_CRTC_GEN_CNTL);
947    if ((crtc_gen_cntl & RADEON_CRTC_DISP_REQ_EN_B) ||
948	!(crtc_gen_cntl & RADEON_CRTC_EN))
949	return;
950
951    /* Clear the CRTC_VBLANK_SAVE bit */
952    OUTREG(RADEON_CRTC_STATUS, RADEON_CRTC_VBLANK_SAVE_CLEAR);
953
954    /* Wait for it to go back up */
955    radeon_init_timeout(&timeout, RADEON_VSYNC_TIMEOUT);
956    while (!(INREG(RADEON_CRTC_STATUS) & RADEON_CRTC_VBLANK_SAVE) &&
957        !radeon_timedout(&timeout))
958	usleep(100);
959}
960
961/* Wait for vertical sync on secondary CRTC */
962void RADEONWaitForVerticalSync2(ScrnInfoPtr pScrn)
963{
964    RADEONInfoPtr  info       = RADEONPTR(pScrn);
965    unsigned char *RADEONMMIO = info->MMIO;
966    uint32_t       crtc2_gen_cntl;
967    struct timeval timeout;
968
969    crtc2_gen_cntl = INREG(RADEON_CRTC2_GEN_CNTL);
970    if ((crtc2_gen_cntl & RADEON_CRTC2_DISP_REQ_EN_B) ||
971	!(crtc2_gen_cntl & RADEON_CRTC2_EN))
972	return;
973
974    /* Clear the CRTC2_VBLANK_SAVE bit */
975    OUTREG(RADEON_CRTC2_STATUS, RADEON_CRTC2_VBLANK_SAVE_CLEAR);
976
977    /* Wait for it to go back up */
978    radeon_init_timeout(&timeout, RADEON_VSYNC_TIMEOUT);
979    while (!(INREG(RADEON_CRTC2_STATUS) & RADEON_CRTC2_VBLANK_SAVE) &&
980        !radeon_timedout(&timeout))
981	usleep(100);
982}
983
984
985/* Compute log base 2 of val */
986int RADEONMinBits(int val)
987{
988    int  bits;
989
990    if (!val) return 1;
991    for (bits = 0; val; val >>= 1, ++bits);
992    return bits;
993}
994
995/* Compute n/d with rounding */
996static int RADEONDiv(int n, int d)
997{
998    return (n + (d / 2)) / d;
999}
1000
1001static Bool RADEONProbePLLParameters(ScrnInfoPtr pScrn)
1002{
1003    RADEONInfoPtr info = RADEONPTR(pScrn);
1004    RADEONPLLPtr  pll  = &info->pll;
1005    unsigned char *RADEONMMIO = info->MMIO;
1006    unsigned char ppll_div_sel;
1007    unsigned mpll_fb_div, spll_fb_div, M;
1008    unsigned xclk, tmp, ref_div;
1009    int hTotal, vTotal, num, denom, m, n;
1010    float hz, prev_xtal, vclk, xtal, mpll, spll;
1011    long total_usecs;
1012    struct timeval start, stop, to1, to2;
1013    unsigned int f1, f2, f3;
1014    int tries = 0;
1015
1016    prev_xtal = 0;
1017 again:
1018    xtal = 0;
1019    if (++tries > 10)
1020           goto failed;
1021
1022    gettimeofday(&to1, NULL);
1023    f1 = INREG(RADEON_CRTC_CRNT_FRAME);
1024    for (;;) {
1025       f2 = INREG(RADEON_CRTC_CRNT_FRAME);
1026       if (f1 != f2)
1027	    break;
1028       gettimeofday(&to2, NULL);
1029       if ((to2.tv_sec - to1.tv_sec) > 1) {
1030           xf86DrvMsg(pScrn->scrnIndex, X_WARNING, "Clock not counting...\n");
1031           goto failed;
1032       }
1033    }
1034    gettimeofday(&start, NULL);
1035    for(;;) {
1036       f3 = INREG(RADEON_CRTC_CRNT_FRAME);
1037       if (f3 != f2)
1038	    break;
1039       gettimeofday(&to2, NULL);
1040       if ((to2.tv_sec - start.tv_sec) > 1)
1041           goto failed;
1042    }
1043    gettimeofday(&stop, NULL);
1044
1045    if ((stop.tv_sec - start.tv_sec) != 0)
1046           goto again;
1047    total_usecs = abs(stop.tv_usec - start.tv_usec);
1048    if (total_usecs == 0)
1049           goto again;
1050    hz = 1000000.0/(float)total_usecs;
1051
1052    hTotal = ((INREG(RADEON_CRTC_H_TOTAL_DISP) & 0x3ff) + 1) * 8;
1053    vTotal = ((INREG(RADEON_CRTC_V_TOTAL_DISP) & 0xfff) + 1);
1054    vclk = (float)(hTotal * (float)(vTotal * hz));
1055
1056    switch((INPLL(pScrn, RADEON_PPLL_REF_DIV) & 0x30000) >> 16) {
1057    case 0:
1058    default:
1059        num = 1;
1060        denom = 1;
1061        break;
1062    case 1:
1063        n = ((INPLL(pScrn, RADEON_X_MPLL_REF_FB_DIV) >> 16) & 0xff);
1064        m = (INPLL(pScrn, RADEON_X_MPLL_REF_FB_DIV) & 0xff);
1065        num = 2*n;
1066        denom = 2*m;
1067        break;
1068    case 2:
1069        n = ((INPLL(pScrn, RADEON_X_MPLL_REF_FB_DIV) >> 8) & 0xff);
1070        m = (INPLL(pScrn, RADEON_X_MPLL_REF_FB_DIV) & 0xff);
1071        num = 2*n;
1072        denom = 2*m;
1073        break;
1074     }
1075
1076    ppll_div_sel = INREG8(RADEON_CLOCK_CNTL_INDEX + 1) & 0x3;
1077    RADEONPllErrataAfterIndex(info);
1078
1079    n = (INPLL(pScrn, RADEON_PPLL_DIV_0 + ppll_div_sel) & 0x7ff);
1080    m = (INPLL(pScrn, RADEON_PPLL_REF_DIV) & 0x3ff);
1081
1082    num *= n;
1083    denom *= m;
1084
1085    switch ((INPLL(pScrn, RADEON_PPLL_DIV_0 + ppll_div_sel) >> 16) & 0x7) {
1086    case 1:
1087        denom *= 2;
1088        break;
1089    case 2:
1090        denom *= 4;
1091        break;
1092    case 3:
1093        denom *= 8;
1094        break;
1095    case 4:
1096        denom *= 3;
1097        break;
1098    case 6:
1099        denom *= 6;
1100        break;
1101    case 7:
1102        denom *= 12;
1103        break;
1104    }
1105
1106    xtal = (int)(vclk *(float)denom/(float)num);
1107
1108    if ((xtal > 26900000) && (xtal < 27100000))
1109        xtal = 2700;
1110    else if ((xtal > 14200000) && (xtal < 14400000))
1111        xtal = 1432;
1112    else if ((xtal > 29400000) && (xtal < 29600000))
1113        xtal = 2950;
1114    else
1115       goto again;
1116 failed:
1117    if (xtal == 0) {
1118       xf86DrvMsg(pScrn->scrnIndex, X_WARNING, "Failed to probe xtal value ! "
1119                  "Using default 27Mhz\n");
1120       xtal = 2700;
1121    } else {
1122       if (prev_xtal == 0) {
1123	   prev_xtal = xtal;
1124	   tries = 0;
1125	   goto again;
1126       } else if (prev_xtal != xtal) {
1127	   prev_xtal = 0;
1128	   goto again;
1129       }
1130    }
1131
1132    tmp = INPLL(pScrn, RADEON_X_MPLL_REF_FB_DIV);
1133    ref_div = INPLL(pScrn, RADEON_PPLL_REF_DIV) & 0x3ff;
1134
1135    /* Some sanity check based on the BIOS code .... */
1136    if (ref_div < 2) {
1137       uint32_t tmp;
1138       tmp = INPLL(pScrn, RADEON_PPLL_REF_DIV);
1139       if (IS_R300_VARIANT
1140	   || (info->ChipFamily == CHIP_FAMILY_RS300)
1141	   || (info->ChipFamily == CHIP_FAMILY_RS400)
1142	   || (info->ChipFamily == CHIP_FAMILY_RS480))
1143	   ref_div = (tmp & R300_PPLL_REF_DIV_ACC_MASK) >>
1144	       R300_PPLL_REF_DIV_ACC_SHIFT;
1145       else
1146	   ref_div = tmp & RADEON_PPLL_REF_DIV_MASK;
1147       if (ref_div < 2)
1148	   ref_div = 12;
1149    }
1150
1151    /* Calculate "base" xclk straight from MPLL, though that isn't
1152     * really useful (hopefully). This isn't called XCLK anymore on
1153     * radeon's...
1154     */
1155    mpll_fb_div = (tmp & 0xff00) >> 8;
1156    spll_fb_div = (tmp & 0xff0000) >> 16;
1157    M = (tmp & 0xff);
1158    xclk = RADEONDiv((2 * mpll_fb_div * xtal), (M));
1159
1160    /*
1161     * Calculate MCLK based on MCLK-A
1162     */
1163    mpll = (2.0 * (float)mpll_fb_div * (xtal / 100.0)) / (float)M;
1164    spll = (2.0 * (float)spll_fb_div * (xtal / 100.0)) / (float)M;
1165
1166    tmp = INPLL(pScrn, RADEON_MCLK_CNTL) & 0x7;
1167    switch(tmp) {
1168    case 1: info->mclk = mpll; break;
1169    case 2: info->mclk = mpll / 2.0; break;
1170    case 3: info->mclk = mpll / 4.0; break;
1171    case 4: info->mclk = mpll / 8.0; break;
1172    case 7: info->mclk = spll; break;
1173    default:
1174           info->mclk = 200.00;
1175           xf86DrvMsg(pScrn->scrnIndex, X_WARNING, "Unsupported MCLKA source"
1176                      " setting %d, can't probe MCLK value !\n", tmp);
1177    }
1178
1179    /*
1180     * Calculate SCLK
1181     */
1182    tmp = INPLL(pScrn, RADEON_SCLK_CNTL) & 0x7;
1183    switch(tmp) {
1184    case 1: info->sclk = spll; break;
1185    case 2: info->sclk = spll / 2.0; break;
1186    case 3: info->sclk = spll / 4.0; break;
1187    case 4: info->sclk = spll / 8.0; break;
1188    case 7: info->sclk = mpll; break;
1189    default:
1190           info->sclk = 200.00;
1191           xf86DrvMsg(pScrn->scrnIndex, X_WARNING, "Unsupported SCLK source"
1192                      " setting %d, can't probe SCLK value !\n", tmp);
1193    }
1194
1195    /* we're done, hopefully these are sane values */
1196    pll->reference_div = ref_div;
1197    pll->xclk = xclk;
1198    pll->reference_freq = xtal;
1199
1200    xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Probed PLL values: xtal: %f Mhz, "
1201              "sclk: %f Mhz, mclk: %f Mhz\n", xtal/100.0, info->sclk, info->mclk);
1202
1203    return TRUE;
1204}
1205
1206static void RADEONGetClockInfo(ScrnInfoPtr pScrn)
1207{
1208    RADEONInfoPtr info = RADEONPTR (pScrn);
1209    RADEONPLLPtr pll = &info->pll;
1210    double min_dotclock;
1211
1212    if (RADEONGetClockInfoFromBIOS(pScrn)) {
1213	if (pll->reference_div < 2) {
1214	    /* retrive it from register setting for fitting into current PLL algorithm.
1215	       We'll probably need a new routine to calculate the best ref_div from BIOS
1216	       provided min_input_pll and max_input_pll
1217	    */
1218	    if (!IS_AVIVO_VARIANT) {
1219		uint32_t tmp;
1220		tmp = INPLL(pScrn, RADEON_PPLL_REF_DIV);
1221		if (IS_R300_VARIANT ||
1222		    (info->ChipFamily == CHIP_FAMILY_RS300) ||
1223		    (info->ChipFamily == CHIP_FAMILY_RS400) ||
1224		    (info->ChipFamily == CHIP_FAMILY_RS480)) {
1225		    pll->reference_div = (tmp & R300_PPLL_REF_DIV_ACC_MASK) >> R300_PPLL_REF_DIV_ACC_SHIFT;
1226		} else {
1227		    pll->reference_div = tmp & RADEON_PPLL_REF_DIV_MASK;
1228		}
1229	    }
1230	    if (pll->reference_div < 2) pll->reference_div = 12;
1231	}
1232    } else {
1233	xf86DrvMsg (pScrn->scrnIndex, X_WARNING,
1234		    "Video BIOS not detected, using default clock settings!\n");
1235
1236       /* Default min/max PLL values */
1237       if (info->ChipFamily == CHIP_FAMILY_R420 || info->ChipFamily == CHIP_FAMILY_RV410) {
1238	   pll->pll_in_min = 100;
1239	   pll->pll_in_max = 1350;
1240	   pll->pll_out_min = 20000;
1241	   pll->pll_out_max = 50000;
1242       } else {
1243	   pll->pll_in_min = 40;
1244	   pll->pll_in_max = 500;
1245	   pll->pll_out_min = 12500;
1246	   pll->pll_out_max = 35000;
1247       }
1248
1249       if (!RADEONProbePLLParameters(pScrn)) {
1250	   if (info->IsIGP)
1251	       pll->reference_freq = 1432;
1252	   else
1253	       pll->reference_freq = 2700;
1254
1255	   pll->reference_div = 12;
1256	   pll->xclk = 10300;
1257
1258	   info->sclk = 200.00;
1259	   info->mclk = 200.00;
1260       }
1261    }
1262
1263    /* card limits for computing PLLs */
1264    if (IS_AVIVO_VARIANT) {
1265	pll->min_post_div = 2;
1266	pll->max_post_div = 0x7f;
1267	pll->min_frac_feedback_div = 0;
1268	pll->max_frac_feedback_div = 9;
1269    } else {
1270	pll->min_post_div = 1;
1271	pll->max_post_div = 12; //16 on crtc0
1272	pll->min_frac_feedback_div = 0;
1273	pll->max_frac_feedback_div = 0;
1274    }
1275    pll->min_ref_div = 2;
1276    pll->max_ref_div = 0x3ff;
1277    pll->min_feedback_div = 4;
1278    pll->max_feedback_div = 0x7ff;
1279    pll->best_vco = 0;
1280
1281    xf86DrvMsg (pScrn->scrnIndex, X_INFO,
1282		"PLL parameters: rf=%u rd=%u min=%u max=%u; xclk=%u\n",
1283		pll->reference_freq,
1284		pll->reference_div,
1285		(unsigned)pll->pll_out_min, (unsigned)pll->pll_out_max,
1286		pll->xclk);
1287
1288    /* (Some?) Radeon BIOSes seem too lie about their minimum dot
1289     * clocks.  Allow users to override the detected minimum dot clock
1290     * value (e.g., and allow it to be suitable for TV sets).
1291     */
1292    if (xf86GetOptValFreq(info->Options, OPTION_MIN_DOTCLOCK,
1293			  OPTUNITS_MHZ, &min_dotclock)) {
1294	if (min_dotclock < 12 || min_dotclock*100 >= pll->pll_out_max) {
1295	    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
1296		       "Illegal minimum dotclock specified %.2f MHz "
1297		       "(option ignored)\n",
1298		       min_dotclock);
1299	} else {
1300	    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
1301		       "Forced minimum dotclock to %.2f MHz "
1302		       "(instead of detected %.2f MHz)\n",
1303		       min_dotclock, ((double)pll->pll_out_min/1000));
1304	    pll->pll_out_min = min_dotclock * 1000;
1305	}
1306    }
1307}
1308
1309
1310
1311/* This is called by RADEONPreInit to set up the default visual */
1312Bool RADEONPreInitVisual(ScrnInfoPtr pScrn)
1313{
1314    RADEONInfoPtr  info = RADEONPTR(pScrn);
1315
1316    if (!xf86SetDepthBpp(pScrn, 0, 0, 0, Support32bppFb))
1317	return FALSE;
1318
1319    switch (pScrn->depth) {
1320    case 8:
1321    case 15:
1322    case 16:
1323    case 24:
1324	break;
1325
1326    default:
1327	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1328		   "Given depth (%d) is not supported by %s driver\n",
1329		   pScrn->depth, RADEON_DRIVER_NAME);
1330	return FALSE;
1331    }
1332
1333    xf86PrintDepthBpp(pScrn);
1334
1335    info->pix24bpp                   = xf86GetBppFromDepth(pScrn,
1336							   pScrn->depth);
1337    info->CurrentLayout.bitsPerPixel = pScrn->bitsPerPixel;
1338    info->CurrentLayout.depth        = pScrn->depth;
1339    info->CurrentLayout.pixel_bytes  = pScrn->bitsPerPixel / 8;
1340    info->CurrentLayout.pixel_code   = (pScrn->bitsPerPixel != 16
1341				       ? pScrn->bitsPerPixel
1342				       : pScrn->depth);
1343
1344    if (info->pix24bpp == 24) {
1345	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1346		   "Radeon does NOT support 24bpp\n");
1347	return FALSE;
1348    }
1349
1350    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
1351	       "Pixel depth = %d bits stored in %d byte%s (%d bpp pixmaps)\n",
1352	       pScrn->depth,
1353	       info->CurrentLayout.pixel_bytes,
1354	       info->CurrentLayout.pixel_bytes > 1 ? "s" : "",
1355	       info->pix24bpp);
1356
1357    if (!xf86SetDefaultVisual(pScrn, -1)) return FALSE;
1358
1359    if (pScrn->depth > 8 && pScrn->defaultVisual != TrueColor) {
1360	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1361		   "Default visual (%s) is not supported at depth %d\n",
1362		   xf86GetVisualName(pScrn->defaultVisual), pScrn->depth);
1363	return FALSE;
1364    }
1365    return TRUE;
1366}
1367
1368/* This is called by RADEONPreInit to handle all color weight issues */
1369Bool RADEONPreInitWeight(ScrnInfoPtr pScrn)
1370{
1371    RADEONInfoPtr  info = RADEONPTR(pScrn);
1372
1373				/* Save flag for 6 bit DAC to use for
1374				   setting CRTC registers.  Otherwise use
1375				   an 8 bit DAC, even if xf86SetWeight sets
1376				   pScrn->rgbBits to some value other than
1377				   8. */
1378    info->dac6bits = FALSE;
1379
1380    if (pScrn->depth > 8) {
1381	rgb  defaultWeight = { 0, 0, 0 };
1382
1383	if (!xf86SetWeight(pScrn, defaultWeight, defaultWeight)) return FALSE;
1384    } else {
1385	pScrn->rgbBits = 8;
1386	if (xf86ReturnOptValBool(info->Options, OPTION_DAC_6BIT, FALSE)) {
1387	    pScrn->rgbBits = 6;
1388	    info->dac6bits = TRUE;
1389	}
1390    }
1391
1392    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
1393	       "Using %d bits per RGB (%d bit DAC)\n",
1394	       pScrn->rgbBits, info->dac6bits ? 6 : 8);
1395
1396    return TRUE;
1397}
1398
1399void RADEONInitMemMapRegisters(ScrnInfoPtr pScrn, RADEONSavePtr save,
1400				      RADEONInfoPtr info)
1401{
1402    save->mc_fb_location = info->mc_fb_location;
1403    save->mc_agp_location = info->mc_agp_location;
1404
1405    if (IS_AVIVO_VARIANT) {
1406	save->mc_agp_location_hi = info->mc_agp_location_hi;
1407    } else {
1408	save->display_base_addr = info->fbLocation;
1409	save->display2_base_addr = info->fbLocation;
1410	save->ov0_base_addr = info->fbLocation;
1411    }
1412}
1413
1414static void RADEONInitMemoryMap(ScrnInfoPtr pScrn)
1415{
1416    RADEONInfoPtr  info   = RADEONPTR(pScrn);
1417    unsigned char *RADEONMMIO = info->MMIO;
1418    uint64_t       mem_size;
1419    uint64_t       aper_size;
1420
1421    radeon_read_mc_fb_agp_location(pScrn, LOC_FB | LOC_AGP, &info->mc_fb_location,
1422				   &info->mc_agp_location, &info->mc_agp_location_hi);
1423
1424    /* We shouldn't use info->videoRam here which might have been clipped
1425     * but the real video RAM instead
1426     */
1427    if (info->ChipFamily >= CHIP_FAMILY_PALM) {
1428	/* size in bytes on fusion */
1429	mem_size = INREG(R600_CONFIG_MEMSIZE);
1430	/* size in MB on fusion */
1431	aper_size = INREG(R600_CONFIG_APER_SIZE) * 1024 * 1024;
1432    } else if (info->ChipFamily >= CHIP_FAMILY_CEDAR) {
1433	/* size in MB on evergreen */
1434	/* XXX watch for overflow!!! */
1435	mem_size = INREG(R600_CONFIG_MEMSIZE) * 1024 * 1024;
1436	aper_size = INREG(R600_CONFIG_APER_SIZE) * 1024 * 1024;
1437    } else if (info->ChipFamily >= CHIP_FAMILY_R600) {
1438	mem_size = INREG(R600_CONFIG_MEMSIZE);
1439	aper_size = INREG(R600_CONFIG_APER_SIZE);
1440    } else {
1441	mem_size = INREG(RADEON_CONFIG_MEMSIZE);
1442	aper_size = INREG(RADEON_CONFIG_APER_SIZE);
1443    }
1444
1445    if (mem_size == 0)
1446	mem_size = 0x800000;
1447
1448    /* Fix for RN50, M6, M7 with 8/16/32(??) MBs of VRAM -
1449       Novell bug 204882 + along with lots of ubuntu ones */
1450    if (aper_size > mem_size)
1451	mem_size = aper_size;
1452
1453    /* don't map the whole FB in the internal address space.
1454     * we don't currently use fb space larger than the aperture
1455     * size and on cards with more than 512 MB of vram, this can overflow
1456     * the internal top of gart calculation on some systems.
1457     * Limit it to cards with more than 512 MB as this causes problems
1458     * on some other cards due to the way the ddx and drm set up the
1459     * internal memory map.
1460     * See fdo bug 24301.
1461     */
1462    if (mem_size > 0x20000000)
1463	mem_size = aper_size;
1464
1465#ifdef XF86DRI
1466    /* Apply memory map limitation if using an old DRI */
1467    if (info->directRenderingEnabled && !info->dri->newMemoryMap) {
1468	    if (aper_size < mem_size)
1469		mem_size = aper_size;
1470    }
1471#endif
1472
1473    if ((info->ChipFamily != CHIP_FAMILY_RS600) &&
1474	(info->ChipFamily != CHIP_FAMILY_RS690) &&
1475	(info->ChipFamily != CHIP_FAMILY_RS740) &&
1476	(info->ChipFamily != CHIP_FAMILY_RS780) &&
1477	(info->ChipFamily != CHIP_FAMILY_RS880) &&
1478	(info->ChipFamily != CHIP_FAMILY_PALM)) {
1479	if (info->IsIGP)
1480	    info->mc_fb_location = INREG(RADEON_NB_TOM);
1481	else
1482#ifdef XF86DRI
1483	/* Old DRI has restrictions on the memory map */
1484	if ( info->directRenderingEnabled &&
1485	     info->dri->pKernelDRMVersion->version_minor < 10 )
1486	    info->mc_fb_location = (mem_size - 1) & 0xffff0000U;
1487	else
1488#endif
1489	{
1490	    uint64_t aper0_base;
1491
1492	    if (info->ChipFamily >= CHIP_FAMILY_R600) {
1493		aper0_base = INREG(R600_CONFIG_F0_BASE);
1494	    } else {
1495		aper0_base = INREG(RADEON_CONFIG_APER_0_BASE);
1496	    }
1497
1498	    /* Recent chips have an "issue" with the memory controller, the
1499	     * location must be aligned to the size. We just align it down,
1500	     * too bad if we walk over the top of system memory, we don't
1501	     * use DMA without a remapped anyway.
1502	     * Affected chips are rv280, all r3xx, and all r4xx, but not IGP
1503	     */
1504	    if (info->ChipFamily == CHIP_FAMILY_RV280 ||
1505		info->ChipFamily == CHIP_FAMILY_R300 ||
1506		info->ChipFamily == CHIP_FAMILY_R350 ||
1507		info->ChipFamily == CHIP_FAMILY_RV350 ||
1508		info->ChipFamily == CHIP_FAMILY_RV380 ||
1509		info->ChipFamily == CHIP_FAMILY_R420 ||
1510		info->ChipFamily == CHIP_FAMILY_RV410)
1511		    aper0_base &= ~(mem_size - 1);
1512
1513	    if (info->ChipFamily >= CHIP_FAMILY_R600) {
1514		uint64_t mc_fb = ((aper0_base >> 24) & 0xffff) |
1515		    (((aper0_base + mem_size - 1) >> 8) & 0xffff0000);
1516		info->mc_fb_location = mc_fb & 0xffffffff;
1517		ErrorF("mc fb loc is %08x\n", (unsigned int)info->mc_fb_location);
1518	    } else {
1519		uint64_t mc_fb = ((aper0_base >> 16) & 0xffff) |
1520		    ((aper0_base + mem_size - 1) & 0xffff0000U);
1521		info->mc_fb_location = mc_fb & 0xffffffff;
1522	    }
1523	}
1524    }
1525    if (info->ChipFamily >= CHIP_FAMILY_R600) {
1526	info->fbLocation = ((uint64_t)info->mc_fb_location & 0xffff) << 24;
1527    } else {
1528	info->fbLocation = ((uint64_t)info->mc_fb_location & 0xffff) << 16;
1529    }
1530    /* Just disable the damn AGP apertures for now, it may be
1531     * re-enabled later by the DRM
1532     */
1533    if (IS_AVIVO_VARIANT)
1534	info->mc_agp_location = 0x003f0000;
1535    else
1536	info->mc_agp_location = 0xffffffc0;
1537    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
1538	       "RADEONInitMemoryMap() : \n");
1539    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
1540	       "  mem_size         : 0x%08x\n", (unsigned)mem_size);
1541    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
1542	       "  MC_FB_LOCATION   : 0x%08x\n", (unsigned)info->mc_fb_location);
1543    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
1544	       "  MC_AGP_LOCATION  : 0x%08x\n",
1545	       (unsigned)info->mc_agp_location);
1546}
1547
1548static void RADEONGetVRamType(ScrnInfoPtr pScrn)
1549{
1550    RADEONInfoPtr  info   = RADEONPTR(pScrn);
1551    RADEONEntPtr pRADEONEnt = RADEONEntPriv(pScrn);
1552    unsigned char *RADEONMMIO = info->MMIO;
1553    uint32_t tmp;
1554
1555    if (info->IsIGP || (info->ChipFamily >= CHIP_FAMILY_R300))
1556	info->IsDDR = TRUE;
1557    else if (INREG(RADEON_MEM_SDRAM_MODE_REG) & RADEON_MEM_CFG_TYPE_DDR)
1558	info->IsDDR = TRUE;
1559    else
1560	info->IsDDR = FALSE;
1561
1562    if ((info->ChipFamily >= CHIP_FAMILY_R600) &&
1563	(info->ChipFamily <= CHIP_FAMILY_RV635)) {
1564	int chansize;
1565	/* r6xx */
1566	tmp = INREG(R600_RAMCFG);
1567	if (tmp & R600_CHANSIZE_OVERRIDE)
1568	    chansize = 16;
1569	else if (tmp & R600_CHANSIZE)
1570	    chansize = 64;
1571	else
1572	    chansize = 32;
1573	if (info->ChipFamily == CHIP_FAMILY_R600)
1574	    info->RamWidth = 8 * chansize;
1575	else if (info->ChipFamily == CHIP_FAMILY_RV670)
1576	    info->RamWidth = 4 * chansize;
1577	else if ((info->ChipFamily == CHIP_FAMILY_RV610) ||
1578		 (info->ChipFamily == CHIP_FAMILY_RV620))
1579	    info->RamWidth = chansize;
1580	else if ((info->ChipFamily == CHIP_FAMILY_RV630) ||
1581		 (info->ChipFamily == CHIP_FAMILY_RV635))
1582	    info->RamWidth = 2 * chansize;
1583    } else if (info->ChipFamily == CHIP_FAMILY_RV515) {
1584	/* rv515/rv550 */
1585	tmp = INMC(pScrn, RV515_MC_CNTL);
1586	tmp &= RV515_MEM_NUM_CHANNELS_MASK;
1587	switch (tmp) {
1588	case 0: info->RamWidth = 64; break;
1589	case 1: info->RamWidth = 128; break;
1590	default: info->RamWidth = 128; break;
1591	}
1592    } else if ((info->ChipFamily >= CHIP_FAMILY_R520) &&
1593	       (info->ChipFamily <= CHIP_FAMILY_RV570)){
1594	/* r520/rv530/rv560/rv570/r580 */
1595	tmp = INMC(pScrn, R520_MC_CNTL0);
1596	switch ((tmp & R520_MEM_NUM_CHANNELS_MASK) >> R520_MEM_NUM_CHANNELS_SHIFT) {
1597	case 0: info->RamWidth = 32; break;
1598	case 1: info->RamWidth = 64; break;
1599	case 2: info->RamWidth = 128; break;
1600	case 3: info->RamWidth = 256; break;
1601	default: info->RamWidth = 64; break;
1602	}
1603	if (tmp & R520_MC_CHANNEL_SIZE) {
1604	    info->RamWidth *= 2;
1605	}
1606    } else if ((info->ChipFamily >= CHIP_FAMILY_R300) &&
1607	       (info->ChipFamily <= CHIP_FAMILY_RV410)) {
1608	/* r3xx, r4xx */
1609	tmp = INREG(RADEON_MEM_CNTL);
1610	tmp &= R300_MEM_NUM_CHANNELS_MASK;
1611	switch (tmp) {
1612	case 0: info->RamWidth = 64; break;
1613	case 1: info->RamWidth = 128; break;
1614	case 2: info->RamWidth = 256; break;
1615	default: info->RamWidth = 128; break;
1616	}
1617    } else if ((info->ChipFamily == CHIP_FAMILY_RV100) ||
1618	       (info->ChipFamily == CHIP_FAMILY_RS100) ||
1619	       (info->ChipFamily == CHIP_FAMILY_RS200)){
1620	tmp = INREG(RADEON_MEM_CNTL);
1621	if (tmp & RV100_HALF_MODE)
1622	    info->RamWidth = 32;
1623	else
1624	    info->RamWidth = 64;
1625
1626	if (!pRADEONEnt->HasCRTC2) {
1627	    info->RamWidth /= 4;
1628	    info->IsDDR = TRUE;
1629	}
1630    } else if (info->ChipFamily <= CHIP_FAMILY_RV280) {
1631	tmp = INREG(RADEON_MEM_CNTL);
1632	if (tmp & RADEON_MEM_NUM_CHANNELS_MASK)
1633	    info->RamWidth = 128;
1634	else
1635	    info->RamWidth = 64;
1636    } else {
1637	/* newer IGPs */
1638	info->RamWidth = 128;
1639    }
1640
1641    /* This may not be correct, as some cards can have half of channel disabled
1642     * ToDo: identify these cases
1643     */
1644}
1645
1646/*
1647 * Depending on card genertation, chipset bugs, etc... the amount of vram
1648 * accessible to the CPU can vary. This function is our best shot at figuring
1649 * it out. Returns a value in KB.
1650 */
1651static uint32_t RADEONGetAccessibleVRAM(ScrnInfoPtr pScrn)
1652{
1653    RADEONInfoPtr  info   = RADEONPTR(pScrn);
1654    unsigned char *RADEONMMIO = info->MMIO;
1655    uint32_t	   aper_size;
1656    unsigned char  byte;
1657
1658    if (info->ChipFamily >= CHIP_FAMILY_CEDAR)
1659	/* size in MB on evergreen and fusion */
1660	aper_size = INREG(R600_CONFIG_APER_SIZE) * 1024;
1661    else if (info->ChipFamily >= CHIP_FAMILY_R600)
1662	aper_size = INREG(R600_CONFIG_APER_SIZE) / 1024;
1663    else
1664	aper_size = INREG(RADEON_CONFIG_APER_SIZE) / 1024;
1665
1666#ifdef XF86DRI
1667    /* If we use the DRI, we need to check if it's a version that has the
1668     * bug of always cropping MC_FB_LOCATION to one aperture, in which case
1669     * we need to limit the amount of accessible video memory
1670     */
1671    if (info->directRenderingEnabled &&
1672	info->dri->pKernelDRMVersion->version_minor < 23) {
1673	xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
1674		   "[dri] limiting video memory to one aperture of %uK\n",
1675		   (unsigned)aper_size);
1676	xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
1677		   "[dri] detected radeon kernel module version 1.%d but"
1678		   " 1.23 or newer is required for full memory mapping.\n",
1679		   info->dri->pKernelDRMVersion->version_minor);
1680	info->dri->newMemoryMap = FALSE;
1681	return aper_size;
1682    }
1683    info->dri->newMemoryMap = TRUE;
1684#endif /* XF86DRI */
1685
1686    if (info->ChipFamily >= CHIP_FAMILY_R600)
1687	return aper_size;
1688
1689    /* Set HDP_APER_CNTL only on cards that are known not to be broken,
1690     * that is has the 2nd generation multifunction PCI interface
1691     */
1692    if (info->ChipFamily == CHIP_FAMILY_RV280 ||
1693	info->ChipFamily == CHIP_FAMILY_RV350 ||
1694	info->ChipFamily == CHIP_FAMILY_RV380 ||
1695	info->ChipFamily == CHIP_FAMILY_R420 ||
1696	info->ChipFamily == CHIP_FAMILY_RV410 ||
1697	IS_AVIVO_VARIANT) {
1698	    OUTREGP (RADEON_HOST_PATH_CNTL, RADEON_HDP_APER_CNTL,
1699		     ~RADEON_HDP_APER_CNTL);
1700	    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
1701		       "Generation 2 PCI interface, using max accessible memory\n");
1702	    return aper_size * 2;
1703    }
1704
1705    /* Older cards have all sorts of funny issues to deal with. First
1706     * check if it's a multifunction card by reading the PCI config
1707     * header type... Limit those to one aperture size
1708     */
1709    PCI_READ_BYTE(info->PciInfo, &byte, 0xe);
1710    if (byte & 0x80) {
1711	xf86DrvMsg(pScrn->scrnIndex, X_INFO,
1712		   "Generation 1 PCI interface in multifunction mode"
1713		   ", accessible memory limited to one aperture\n");
1714	return aper_size;
1715    }
1716
1717    /* Single function older card. We read HDP_APER_CNTL to see how the BIOS
1718     * have set it up. We don't write this as it's broken on some ASICs but
1719     * we expect the BIOS to have done the right thing (might be too optimistic...)
1720     */
1721    if (INREG(RADEON_HOST_PATH_CNTL) & RADEON_HDP_APER_CNTL)
1722        return aper_size * 2;
1723
1724    return aper_size;
1725}
1726
1727static Bool RADEONPreInitVRAM(ScrnInfoPtr pScrn)
1728{
1729    RADEONInfoPtr  info   = RADEONPTR(pScrn);
1730    EntityInfoPtr  pEnt   = info->pEnt;
1731    GDevPtr        dev    = pEnt->device;
1732    unsigned char *RADEONMMIO = info->MMIO;
1733    MessageType    from = X_PROBED;
1734    uint32_t         accessible, bar_size;
1735
1736    if ((!IS_AVIVO_VARIANT) && info->IsIGP) {
1737	uint32_t tom = INREG(RADEON_NB_TOM);
1738
1739	pScrn->videoRam = (((tom >> 16) -
1740			    (tom & 0xffff) + 1) << 6);
1741
1742	OUTREG(RADEON_CONFIG_MEMSIZE, pScrn->videoRam * 1024);
1743    } else {
1744	if (info->ChipFamily >= CHIP_FAMILY_PALM)
1745	    /* R600_CONFIG_MEMSIZE is bytes on fusion */
1746	    pScrn->videoRam = INREG(R600_CONFIG_MEMSIZE) / 1024;
1747	else if (info->ChipFamily >= CHIP_FAMILY_CEDAR)
1748	    /* R600_CONFIG_MEMSIZE is MB on evergreen */
1749	    /* XXX watch for overflow!!! */
1750	    pScrn->videoRam = INREG(R600_CONFIG_MEMSIZE) * 1024;
1751	else if (info->ChipFamily >= CHIP_FAMILY_R600)
1752	    pScrn->videoRam = INREG(R600_CONFIG_MEMSIZE) / 1024;
1753	else {
1754	    /* Read VRAM size from card */
1755	    pScrn->videoRam      = INREG(RADEON_CONFIG_MEMSIZE) / 1024;
1756
1757	    /* Some production boards of m6 will return 0 if it's 8 MB */
1758	    if (pScrn->videoRam == 0) {
1759		pScrn->videoRam = 8192;
1760		OUTREG(RADEON_CONFIG_MEMSIZE, 0x800000);
1761	    }
1762	}
1763    }
1764
1765    /* Get accessible memory */
1766    accessible = RADEONGetAccessibleVRAM(pScrn);
1767
1768    /* Crop it to the size of the PCI BAR */
1769    bar_size = PCI_REGION_SIZE(info->PciInfo, 0) / 1024;
1770    if (bar_size == 0)
1771	bar_size = 0x20000;
1772    if (accessible > bar_size)
1773	accessible = bar_size;
1774
1775    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
1776	       "Detected total video RAM=%dK, accessible=%uK (PCI BAR=%uK)\n",
1777	       pScrn->videoRam, (unsigned)accessible, (unsigned)bar_size);
1778    if (pScrn->videoRam > accessible)
1779	pScrn->videoRam = accessible;
1780
1781    if (!IS_AVIVO_VARIANT) {
1782	info->MemCntl            = INREG(RADEON_SDRAM_MODE_REG);
1783	info->BusCntl            = INREG(RADEON_BUS_CNTL);
1784    }
1785
1786    RADEONGetVRamType(pScrn);
1787
1788    if (dev->videoRam) {
1789	xf86DrvMsg(pScrn->scrnIndex, X_INFO,
1790		   "Video RAM override, using %d kB instead of %d kB\n",
1791		   dev->videoRam,
1792		   pScrn->videoRam);
1793	from             = X_CONFIG;
1794	pScrn->videoRam  = dev->videoRam;
1795    }
1796
1797    xf86DrvMsg(pScrn->scrnIndex, from,
1798	       "Mapped VideoRAM: %d kByte (%d bit %s SDRAM)\n", pScrn->videoRam, info->RamWidth, info->IsDDR?"DDR":"SDR");
1799
1800    /* Do this before we truncate since we only map fb once */
1801    info->FbMapSize  = (pScrn->videoRam & ~1023) * 1024;
1802
1803    if (info->IsPrimary) {
1804	pScrn->videoRam /= 2;
1805	xf86DrvMsg(pScrn->scrnIndex, X_INFO,
1806		   "Using %dk of videoram for primary head\n",
1807		   pScrn->videoRam);
1808    } else if (info->IsSecondary) {
1809	pScrn->videoRam /= 2;
1810	xf86DrvMsg(pScrn->scrnIndex, X_INFO,
1811		   "Using %dk of videoram for secondary head\n",
1812		   pScrn->videoRam);
1813    }
1814    pScrn->videoRam  &= ~1023;
1815
1816    /* if the card is PCI Express reserve the last 32k for the gart table */
1817#ifdef XF86DRI
1818    if (info->cardType == CARD_PCIE && info->directRenderingEnabled)
1819      /* work out the size of pcie aperture */
1820        info->FbSecureSize = RADEONDRIGetPciAperTableSize(pScrn);
1821    else
1822#endif
1823	info->FbSecureSize = 0;
1824
1825    return TRUE;
1826}
1827
1828
1829/* This is called by RADEONPreInit to handle config file overrides for
1830 * things like chipset and memory regions.  Also determine memory size
1831 * and type.  If memory type ever needs an override, put it in this
1832 * routine.
1833 */
1834static Bool RADEONPreInitChipType(ScrnInfoPtr pScrn)
1835{
1836    RADEONInfoPtr  info   = RADEONPTR(pScrn);
1837    RADEONEntPtr pRADEONEnt = RADEONEntPriv(pScrn);
1838    EntityInfoPtr  pEnt   = info->pEnt;
1839    GDevPtr        dev    = pEnt->device;
1840    unsigned char *RADEONMMIO = info->MMIO;
1841    MessageType    from = X_PROBED;
1842    int i;
1843#ifdef XF86DRI
1844    const char *s;
1845    uint32_t cmd_stat;
1846#endif
1847
1848    /* Chipset */
1849    from = X_PROBED;
1850    if (dev->chipset && *dev->chipset) {
1851	info->Chipset  = xf86StringToToken(RADEONChipsets, dev->chipset);
1852	from           = X_CONFIG;
1853    } else if (dev->chipID >= 0) {
1854	info->Chipset  = dev->chipID;
1855	from           = X_CONFIG;
1856    } else {
1857	info->Chipset = PCI_DEV_DEVICE_ID(info->PciInfo);
1858    }
1859
1860    pScrn->chipset = (char *)xf86TokenToString(RADEONChipsets, info->Chipset);
1861    if (!pScrn->chipset) {
1862	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1863		   "ChipID 0x%04x is not recognized\n", info->Chipset);
1864	return FALSE;
1865    }
1866    if (info->Chipset < 0) {
1867	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1868		   "Chipset \"%s\" is not recognized\n", pScrn->chipset);
1869	return FALSE;
1870    }
1871    xf86DrvMsg(pScrn->scrnIndex, from,
1872	       "Chipset: \"%s\" (ChipID = 0x%04x)\n",
1873	       pScrn->chipset,
1874	       info->Chipset);
1875
1876    pRADEONEnt->HasCRTC2 = TRUE;
1877    info->IsMobility = FALSE;
1878    info->IsIGP = FALSE;
1879    info->IsDellServer = FALSE;
1880    info->HasSingleDAC = FALSE;
1881    info->InternalTVOut = TRUE;
1882    info->get_hardcoded_edid_from_bios = FALSE;
1883
1884    for (i = 0; i < sizeof(RADEONCards) / sizeof(RADEONCardInfo); i++) {
1885	if (info->Chipset == RADEONCards[i].pci_device_id) {
1886	    RADEONCardInfo *card = &RADEONCards[i];
1887	    info->ChipFamily = card->chip_family;
1888	    info->IsMobility = card->mobility;
1889	    info->IsIGP = card->igp;
1890	    pRADEONEnt->HasCRTC2 = !card->nocrtc2;
1891	    info->HasSingleDAC = card->singledac;
1892	    info->InternalTVOut = !card->nointtvout;
1893	    break;
1894	}
1895    }
1896
1897    if (IS_DCE5_VARIANT) {
1898	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1899		   "Chipset: \"%s\" (ChipID = 0x%04x) requires KMS\n",
1900		   pScrn->chipset,
1901		   info->Chipset);
1902	return FALSE;
1903    }
1904
1905    switch (info->Chipset) {
1906    case PCI_CHIP_RN50_515E:  /* RN50 is based on the RV100 but 3D isn't guaranteed to work.  YMMV. */
1907    case PCI_CHIP_RN50_5969:
1908	/* Some Sun servers have a hardcoded edid so KVMs work properly */
1909	if ((PCI_SUB_VENDOR_ID(info->PciInfo) == 0x108e) &&
1910	    (PCI_SUB_DEVICE_ID(info->PciInfo) == 0x4133))
1911	    info->get_hardcoded_edid_from_bios = TRUE;
1912    case PCI_CHIP_RV100_QY:
1913    case PCI_CHIP_RV100_QZ:
1914	/* DELL triple-head configuration. */
1915	if (((PCI_SUB_VENDOR_ID(info->PciInfo) == PCI_VENDOR_DELL) &&
1916	     ((PCI_SUB_DEVICE_ID(info->PciInfo) == 0x016c) ||
1917	      (PCI_SUB_DEVICE_ID(info->PciInfo) == 0x016d) ||
1918	      (PCI_SUB_DEVICE_ID(info->PciInfo) == 0x016e) ||
1919	      (PCI_SUB_DEVICE_ID(info->PciInfo) == 0x016f) ||
1920	      (PCI_SUB_DEVICE_ID(info->PciInfo) == 0x0170) ||
1921	      (PCI_SUB_DEVICE_ID(info->PciInfo) == 0x017d) ||
1922	      (PCI_SUB_DEVICE_ID(info->PciInfo) == 0x017e) ||
1923	      (PCI_SUB_DEVICE_ID(info->PciInfo) == 0x0183) ||
1924	      (PCI_SUB_DEVICE_ID(info->PciInfo) == 0x018a) ||
1925	      (PCI_SUB_DEVICE_ID(info->PciInfo) == 0x019a) ||
1926	      (PCI_SUB_DEVICE_ID(info->PciInfo) == 0x01b1) ||
1927	      (PCI_SUB_DEVICE_ID(info->PciInfo) == 0x01b2) ||
1928	      (PCI_SUB_DEVICE_ID(info->PciInfo) == 0x0205))) ||
1929           ((PCI_SUB_VENDOR_ID(info->PciInfo) == PCI_VENDOR_HP) &&
1930              (PCI_SUB_DEVICE_ID(info->PciInfo) == 0x31fb))) {
1931	    info->IsDellServer = TRUE;
1932	    xf86DrvMsg(pScrn->scrnIndex, X_INFO, "DELL/HP server detected, force to special setup\n");
1933	}
1934	break;
1935    case PCI_CHIP_RS482_5974:
1936	/* RH BZ 444586 - non mobility version
1937 	 * Dell appear to have the Vostro 1100 with a mobility part with the same pci-id */
1938	if ((PCI_SUB_VENDOR_ID(info->PciInfo) == 0x1462) &&
1939            (PCI_SUB_DEVICE_ID(info->PciInfo) == 0x7141)) {
1940		info->IsMobility = FALSE;
1941	}
1942    default:
1943	break;
1944    }
1945
1946    from               = X_PROBED;
1947    info->LinearAddr   = PCI_REGION_BASE(info->PciInfo, 0, REGION_MEM) & ~0x1ffffffULL;
1948    pScrn->memPhysBase = info->LinearAddr;
1949    if (dev->MemBase) {
1950	xf86DrvMsg(pScrn->scrnIndex, X_INFO,
1951		   "Linear address override, using 0x%016lx instead of 0x%016llx\n",
1952		   dev->MemBase,
1953		   info->LinearAddr);
1954	info->LinearAddr = dev->MemBase;
1955	from             = X_CONFIG;
1956    } else if (!info->LinearAddr) {
1957	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1958		   "No valid linear framebuffer address\n");
1959	return FALSE;
1960    }
1961    xf86DrvMsg(pScrn->scrnIndex, from,
1962	       "Linear framebuffer at 0x%016llx\n", info->LinearAddr);
1963
1964#ifndef XSERVER_LIBPCIACCESS
1965				/* BIOS */
1966    from              = X_PROBED;
1967    info->BIOSAddr    = info->PciInfo->biosBase & 0xfffe0000;
1968    if (info->BIOSAddr) {
1969	xf86DrvMsg(pScrn->scrnIndex, from,
1970		   "BIOS at 0x%08lx\n", (unsigned long)info->BIOSAddr);
1971    }
1972#endif
1973
1974				/* Read registers used to determine options */
1975    /* Check chip errata */
1976    info->ChipErrata = 0;
1977
1978    if (info->ChipFamily == CHIP_FAMILY_R300 &&
1979	(INREG(RADEON_CONFIG_CNTL) & RADEON_CFG_ATI_REV_ID_MASK)
1980	== RADEON_CFG_ATI_REV_A11)
1981	    info->ChipErrata |= CHIP_ERRATA_R300_CG;
1982
1983    if (info->ChipFamily == CHIP_FAMILY_RV200 ||
1984	info->ChipFamily == CHIP_FAMILY_RS200)
1985	    info->ChipErrata |= CHIP_ERRATA_PLL_DUMMYREADS;
1986
1987    if (info->ChipFamily == CHIP_FAMILY_RV100 ||
1988	info->ChipFamily == CHIP_FAMILY_RS100 ||
1989	info->ChipFamily == CHIP_FAMILY_RS200)
1990	    info->ChipErrata |= CHIP_ERRATA_PLL_DELAY;
1991
1992#ifdef XF86DRI
1993				/* AGP/PCI */
1994    /* Proper autodetection of an AGP capable device requires examining
1995     * PCI config registers to determine if the device implements extended
1996     * PCI capabilities, and then walking the capability list as indicated
1997     * in the PCI 2.2 and AGP 2.0 specifications, to determine if AGP
1998     * capability is present.  The procedure is outlined as follows:
1999     *
2000     * 1) Test bit 4 (CAP_LIST) of the PCI status register of the device
2001     *    to determine wether or not this device implements any extended
2002     *    capabilities.  If this bit is zero, then the device is a PCI 2.1
2003     *    or earlier device and is not AGP capable, and we can conclude it
2004     *    to be a PCI device.
2005     *
2006     * 2) If bit 4 of the status register is set, then the device implements
2007     *    extended capabilities.  There is an 8 bit wide capabilities pointer
2008     *    register located at offset 0x34 in PCI config space which points to
2009     *    the first capability in a linked list of extended capabilities that
2010     *    this device implements.  The lower two bits of this register are
2011     *    reserved and MBZ so must be masked out.
2012     *
2013     * 3) The extended capabilities list is formed by one or more extended
2014     *    capabilities structures which are aligned on DWORD boundaries.
2015     *    The first byte of the structure is the capability ID (CAP_ID)
2016     *    indicating what extended capability this structure refers to.  The
2017     *    second byte of the structure is an offset from the beginning of
2018     *    PCI config space pointing to the next capability in the linked
2019     *    list (NEXT_PTR) or NULL (0x00) at the end of the list.  The lower
2020     *    two bits of this pointer are reserved and MBZ.  By examining the
2021     *    CAP_ID of each capability and walking through the list, we will
2022     *    either find the AGP_CAP_ID (0x02) indicating this device is an
2023     *    AGP device, or we'll reach the end of the list, indicating it is
2024     *    a PCI device.
2025     *
2026     * Mike A. Harris <mharris@redhat.com>
2027     *
2028     * References:
2029     *	- PCI Local Bus Specification Revision 2.2, Chapter 6
2030     *	- AGP Interface Specification Revision 2.0, Section 6.1.5
2031     */
2032
2033    info->cardType = CARD_PCI;
2034
2035    PCI_READ_LONG(info->PciInfo, &cmd_stat, PCI_CMD_STAT_REG);
2036    if (cmd_stat & RADEON_CAP_LIST) {
2037	uint32_t cap_ptr, cap_id;
2038
2039	PCI_READ_LONG(info->PciInfo, &cap_ptr, RADEON_CAPABILITIES_PTR_PCI_CONFIG);
2040	cap_ptr &= RADEON_CAP_PTR_MASK;
2041
2042	while(cap_ptr != RADEON_CAP_ID_NULL) {
2043	    PCI_READ_LONG(info->PciInfo, &cap_id, cap_ptr);
2044	    if ((cap_id & 0xff)== RADEON_CAP_ID_AGP) {
2045		info->cardType = CARD_AGP;
2046		break;
2047	    }
2048	    if ((cap_id & 0xff)== RADEON_CAP_ID_EXP) {
2049		info->cardType = CARD_PCIE;
2050		break;
2051	    }
2052	    cap_ptr = (cap_id >> 8) & RADEON_CAP_PTR_MASK;
2053	}
2054    }
2055
2056    xf86DrvMsg(pScrn->scrnIndex, X_INFO, "%s card detected\n",
2057	       (info->cardType==CARD_PCI) ? "PCI" :
2058		(info->cardType==CARD_PCIE) ? "PCIE" : "AGP");
2059
2060    /* treat PCIE IGP cards as PCI */
2061    if (info->cardType == CARD_PCIE && info->IsIGP)
2062	info->cardType = CARD_PCI;
2063
2064    /* some rs4xx cards report as agp */
2065    if ((info->ChipFamily == CHIP_FAMILY_RS400) ||
2066	(info->ChipFamily == CHIP_FAMILY_RS480))
2067	info->cardType = CARD_PCI;
2068
2069    if ((info->ChipFamily >= CHIP_FAMILY_R600) && info->IsIGP)
2070	info->cardType = CARD_PCIE;
2071
2072    /* not sure about gart table requirements */
2073    if ((info->ChipFamily == CHIP_FAMILY_RS600) && info->IsIGP)
2074	info->cardType = CARD_PCIE;
2075
2076    if ((s = xf86GetOptValString(info->Options, OPTION_BUS_TYPE))) {
2077	if (strcmp(s, "AGP") == 0) {
2078	    info->cardType = CARD_AGP;
2079	    xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "Forced into AGP mode\n");
2080	} else if ((strcmp(s, "PCI") == 0) ||
2081		   (strcmp(s, "PCIE") == 0)) {
2082	    if ((info->ChipFamily == CHIP_FAMILY_RS400) ||
2083		(info->ChipFamily == CHIP_FAMILY_RS480) ||
2084		(info->ChipFamily == CHIP_FAMILY_RS690) ||
2085		(info->ChipFamily == CHIP_FAMILY_RS740)) {
2086		info->cardType = CARD_PCI;
2087		xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "Forced into PCI mode\n");
2088	    } else if (info->ChipFamily >= CHIP_FAMILY_RV380) {
2089		info->cardType = CARD_PCIE;
2090		xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "Forced into PCI Express mode\n");
2091	    } else {
2092		info->cardType = CARD_PCI;
2093		xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "Forced into PCI mode\n");
2094	    }
2095	} else {
2096	    xf86DrvMsg(pScrn->scrnIndex, X_CONFIG,
2097		       "Invalid BusType option, using detected type\n");
2098	}
2099    }
2100#endif
2101#ifdef RENDER
2102    info->RenderAccel = xf86ReturnOptValBool(info->Options, OPTION_RENDER_ACCEL,
2103					     info->Chipset != PCI_CHIP_RN50_515E &&
2104					     info->Chipset != PCI_CHIP_RN50_5969);
2105#endif
2106
2107    info->r4xx_atom = FALSE;
2108    if (((info->ChipFamily == CHIP_FAMILY_R420) || (info->ChipFamily == CHIP_FAMILY_RV410)) &&
2109	xf86ReturnOptValBool(info->Options, OPTION_R4XX_ATOM, FALSE)) {
2110	info->r4xx_atom = TRUE;
2111	xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "Using ATOMBIOS for R4xx chip\n");
2112    }
2113
2114    return TRUE;
2115}
2116
2117
2118static void RADEONPreInitDDC(ScrnInfoPtr pScrn)
2119{
2120    RADEONInfoPtr  info = RADEONPTR(pScrn);
2121 /* vbeInfoPtr     pVbe; */
2122
2123    info->ddc1     = FALSE;
2124    info->ddc_bios = FALSE;
2125    if (!xf86LoadSubModule(pScrn, "ddc")) {
2126	info->ddc2 = FALSE;
2127    } else {
2128	info->ddc2 = TRUE;
2129    }
2130
2131    /* DDC can use I2C bus */
2132    /* Load I2C if we have the code to use it */
2133    if (info->ddc2) {
2134	xf86LoadSubModule(pScrn, "i2c");
2135    }
2136}
2137
2138/* This is called by RADEONPreInit to initialize gamma correction */
2139static Bool RADEONPreInitGamma(ScrnInfoPtr pScrn)
2140{
2141    Gamma  zeros = { 0.0, 0.0, 0.0 };
2142
2143    if (!xf86SetGamma(pScrn, zeros)) return FALSE;
2144    return TRUE;
2145}
2146
2147/* This is called by RADEONPreInit to initialize the hardware cursor */
2148static Bool RADEONPreInitCursor(ScrnInfoPtr pScrn)
2149{
2150    RADEONInfoPtr  info = RADEONPTR(pScrn);
2151
2152    if (!xf86ReturnOptValBool(info->Options, OPTION_SW_CURSOR, FALSE)) {
2153	if (!xf86LoadSubModule(pScrn, "ramdac")) return FALSE;
2154    }
2155    return TRUE;
2156}
2157
2158/* This is called by RADEONPreInit to initialize hardware acceleration */
2159static Bool RADEONPreInitAccel(ScrnInfoPtr pScrn)
2160{
2161    RADEONInfoPtr  info = RADEONPTR(pScrn);
2162    MessageType from;
2163#if defined(USE_EXA) && defined(USE_XAA)
2164    char *optstr;
2165#endif
2166#ifdef XF86DRI /* zaphod FbMapSize is wrong, but no dri then */
2167    int maxy = info->FbMapSize / (pScrn->displayWidth * info->CurrentLayout.pixel_bytes);
2168#endif
2169
2170    if (!(info->accel_state = calloc(1, sizeof(struct radeon_accel_state)))) {
2171	xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Unable to allocate accel_state rec!\n");
2172	return FALSE;
2173    }
2174    info->accel_state->fifo_slots                 = 0;
2175
2176    if ((info->ChipFamily == CHIP_FAMILY_RS100) ||
2177	(info->ChipFamily == CHIP_FAMILY_RS200) ||
2178	(info->ChipFamily == CHIP_FAMILY_RS300) ||
2179	(info->ChipFamily == CHIP_FAMILY_RS400) ||
2180	(info->ChipFamily == CHIP_FAMILY_RS480) ||
2181	(info->ChipFamily == CHIP_FAMILY_RS600) ||
2182	(info->ChipFamily == CHIP_FAMILY_RS690) ||
2183	(info->ChipFamily == CHIP_FAMILY_RS740))
2184	info->accel_state->has_tcl = FALSE;
2185    else {
2186	info->accel_state->has_tcl = TRUE;
2187    }
2188
2189    /* if we have shadow fb bail */
2190    if (info->r600_shadow_fb) {
2191	info->useEXA = FALSE;
2192	return TRUE;
2193    }
2194
2195#ifdef XF86DRI
2196    if ((!info->directRenderingEnabled) ||
2197	(maxy <= pScrn->virtualY * 3) ||
2198	(pScrn->videoRam <= 32768))
2199	info->useEXA = FALSE;
2200    else
2201	info->useEXA = TRUE;
2202#else
2203	info->useEXA = FALSE;
2204#endif
2205
2206    if (!xf86ReturnOptValBool(info->Options, OPTION_NOACCEL, FALSE)) {
2207	int errmaj = 0, errmin = 0;
2208
2209	from = X_DEFAULT;
2210#if defined(USE_EXA)
2211#if defined(USE_XAA)
2212	optstr = (char *)xf86GetOptValString(info->Options, OPTION_ACCELMETHOD);
2213	if (optstr != NULL) {
2214	    if (xf86NameCmp(optstr, "EXA") == 0) {
2215		from = X_CONFIG;
2216		info->useEXA = TRUE;
2217	    } else if (xf86NameCmp(optstr, "XAA") == 0) {
2218		from = X_CONFIG;
2219		if (info->ChipFamily < CHIP_FAMILY_R600)
2220		    info->useEXA = FALSE;
2221	    }
2222	}
2223#else /* USE_XAA */
2224	info->useEXA = TRUE;
2225#endif /* !USE_XAA */
2226#else
2227	info->useEXA = FALSE;
2228#endif /* USE_EXA */
2229        if (info->ChipFamily < CHIP_FAMILY_R600)
2230	    xf86DrvMsg(pScrn->scrnIndex, from,
2231		       "Using %s acceleration architecture\n",
2232		       info->useEXA ? "EXA" : "XAA");
2233	else
2234	    xf86DrvMsg(pScrn->scrnIndex, X_DEFAULT,
2235		       "Will attempt to use R6xx/R7xx EXA support if DRI is enabled.\n");
2236
2237#ifdef USE_EXA
2238	if (info->useEXA) {
2239	    info->exaReq.majorversion = EXA_VERSION_MAJOR;
2240	    info->exaReq.minorversion = EXA_VERSION_MINOR;
2241
2242	    if (!LoadSubModule(pScrn->module, "exa", NULL, NULL, NULL,
2243			       &info->exaReq, &errmaj, &errmin)) {
2244		LoaderErrorMsg(NULL, "exa", errmaj, errmin);
2245		return FALSE;
2246	    }
2247	}
2248#endif /* USE_EXA */
2249#ifdef USE_XAA
2250	if (!info->useEXA) {
2251	    info->xaaReq.majorversion = 1;
2252	    info->xaaReq.minorversion = 2;
2253
2254	    if (!LoadSubModule(pScrn->module, "xaa", NULL, NULL, NULL,
2255			   &info->xaaReq, &errmaj, &errmin)) {
2256		info->xaaReq.minorversion = 1;
2257
2258		if (!LoadSubModule(pScrn->module, "xaa", NULL, NULL, NULL,
2259			       &info->xaaReq, &errmaj, &errmin)) {
2260		    info->xaaReq.minorversion = 0;
2261
2262		    if (!LoadSubModule(pScrn->module, "xaa", NULL, NULL, NULL,
2263			       &info->xaaReq, &errmaj, &errmin)) {
2264			LoaderErrorMsg(NULL, "xaa", errmaj, errmin);
2265			return FALSE;
2266		    }
2267		}
2268	    }
2269	}
2270#endif /* USE_XAA */
2271    } else {
2272	/* NoAccel */
2273	info->useEXA = FALSE;
2274    }
2275
2276    return TRUE;
2277}
2278
2279static Bool RADEONPreInitInt10(ScrnInfoPtr pScrn, xf86Int10InfoPtr *ppInt10)
2280{
2281#if (!defined(__powerpc__) && !defined(__sparc__)) || \
2282    (defined(XSERVER_LIBPCIACCESS) && HAVE_PCI_DEVICE_ENABLE)
2283    RADEONInfoPtr  info = RADEONPTR(pScrn);
2284#endif
2285#if !defined(__powerpc__) && !defined(__sparc__)
2286    unsigned char *RADEONMMIO = info->MMIO;
2287    uint32_t       fp2_gen_ctl_save   = 0;
2288#endif
2289
2290#ifdef XSERVER_LIBPCIACCESS
2291#if HAVE_PCI_DEVICE_ENABLE
2292    pci_device_enable(info->PciInfo);
2293#endif
2294#endif
2295
2296#if !defined(__powerpc__) && !defined(__sparc__)
2297    /* don't need int10 on atom cards.
2298     * in theory all radeons, but the older stuff
2299     * isn't 100% yet
2300     * secondary atom cards tend to hang when initializing int10,
2301     * however, on some stom cards, you can't read the bios without
2302     * intitializing int10.
2303     */
2304    if (!xf86ReturnOptValBool(info->Options, OPTION_INT10, TRUE))
2305	return TRUE;
2306
2307    if (xf86LoadSubModule(pScrn, "int10")) {
2308	/* The VGA BIOS on the RV100/QY cannot be read when the digital output
2309	 * is enabled.  Clear and restore FP2_ON around int10 to avoid this.
2310	 */
2311	if (PCI_DEV_DEVICE_ID(info->PciInfo) == PCI_CHIP_RV100_QY) {
2312	    fp2_gen_ctl_save = INREG(RADEON_FP2_GEN_CNTL);
2313	    if (fp2_gen_ctl_save & RADEON_FP2_ON) {
2314		xf86DrvMsg(pScrn->scrnIndex, X_INFO, "disabling digital out\n");
2315		OUTREG(RADEON_FP2_GEN_CNTL, fp2_gen_ctl_save & ~RADEON_FP2_ON);
2316	    }
2317	}
2318
2319	xf86DrvMsg(pScrn->scrnIndex,X_INFO,"initializing int10\n");
2320	*ppInt10 = xf86InitInt10(info->pEnt->index);
2321
2322	if (PCI_DEV_DEVICE_ID(info->PciInfo) == PCI_CHIP_RV100_QY) {
2323	    if (fp2_gen_ctl_save & RADEON_FP2_ON) {
2324		xf86DrvMsg(pScrn->scrnIndex, X_INFO, "re-enabling digital out\n");
2325		OUTREG(RADEON_FP2_GEN_CNTL, fp2_gen_ctl_save);
2326	    }
2327	}
2328    }
2329#endif
2330    return TRUE;
2331}
2332
2333#ifdef XF86DRI
2334static Bool RADEONPreInitDRI(ScrnInfoPtr pScrn)
2335{
2336    RADEONInfoPtr  info = RADEONPTR(pScrn);
2337    MessageType    from;
2338    char          *reason;
2339
2340    info->directRenderingEnabled = FALSE;
2341    info->directRenderingInited = FALSE;
2342
2343    if (!(info->dri = calloc(1, sizeof(struct radeon_dri)))) {
2344	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,"Unable to allocate dri rec!\n");
2345	return FALSE;
2346    }
2347
2348    if (!(info->cp = calloc(1, sizeof(struct radeon_cp)))) {
2349	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,"Unable to allocate cp rec!\n");
2350	return FALSE;
2351    }
2352    info->cp->CPInUse = FALSE;
2353    info->cp->CPStarted = FALSE;
2354    info->cp->CPusecTimeout = RADEON_DEFAULT_CP_TIMEOUT;
2355
2356   if (xf86IsEntityShared(info->pEnt->index)) {
2357        xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
2358                   "Direct Rendering Disabled -- "
2359                   "Zaphod Dual-head configuration is not working with "
2360                   "DRI at present.\n"
2361                   "Please use the xrandr 1.2 if you "
2362                   "want Dual-head with DRI.\n");
2363        return FALSE;
2364    }
2365    if (info->IsSecondary)
2366        return FALSE;
2367
2368    if (info->ChipFamily >= CHIP_FAMILY_CEDAR) {
2369	xf86DrvMsg(pScrn->scrnIndex, X_INFO,
2370		   "No DRI yet on Evergreen\n");
2371	return FALSE;
2372    }
2373
2374    if (info->Chipset == PCI_CHIP_RN50_515E ||
2375	info->Chipset == PCI_CHIP_RN50_5969) {
2376	if (xf86ReturnOptValBool(info->Options, OPTION_DRI, FALSE)) {
2377	    xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
2378		"Direct rendering for RN50 forced on -- "
2379		"This is NOT officially supported at the hardware level "
2380		"and may cause instability or lockups\n");
2381	} else {
2382	    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
2383		"Direct rendering not officially supported on RN50\n");
2384	    return FALSE;
2385	}
2386    }
2387
2388    if (!xf86ReturnOptValBool(info->Options, OPTION_DRI, TRUE)) {
2389	xf86DrvMsg(pScrn->scrnIndex, X_INFO,
2390		"Direct rendering forced off\n");
2391	return FALSE;
2392    }
2393
2394    if (xf86ReturnOptValBool(info->Options, OPTION_NOACCEL, FALSE)) {
2395	xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
2396		   "[dri] Acceleration disabled, not initializing the DRI\n");
2397	return FALSE;
2398    }
2399
2400    info->dri->pLibDRMVersion = NULL;
2401    info->dri->pKernelDRMVersion = NULL;
2402
2403    if (!RADEONDRIGetVersion(pScrn))
2404	return FALSE;
2405
2406    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
2407	       "[dri] Found DRI library version %d.%d.%d and kernel"
2408	       " module version %d.%d.%d\n",
2409	       info->dri->pLibDRMVersion->version_major,
2410	       info->dri->pLibDRMVersion->version_minor,
2411	       info->dri->pLibDRMVersion->version_patchlevel,
2412	       info->dri->pKernelDRMVersion->version_major,
2413	       info->dri->pKernelDRMVersion->version_minor,
2414	       info->dri->pKernelDRMVersion->version_patchlevel);
2415
2416    if (info->Chipset == PCI_CHIP_RS400_5A41 ||
2417	info->Chipset == PCI_CHIP_RS400_5A42 ||
2418	info->Chipset == PCI_CHIP_RC410_5A61 ||
2419	info->Chipset == PCI_CHIP_RC410_5A62 ||
2420	info->Chipset == PCI_CHIP_RS480_5954 ||
2421	info->Chipset == PCI_CHIP_RS480_5955 ||
2422	info->Chipset == PCI_CHIP_RS482_5974 ||
2423	info->Chipset == PCI_CHIP_RS485_5975) {
2424
2425	if (info->dri->pKernelDRMVersion->version_minor < 27) {
2426 	     xf86DrvMsg(pScrn->scrnIndex, X_INFO,
2427			"Direct rendering broken on XPRESS 200 and 200M with DRI less than 1.27\n");
2428	     return FALSE;
2429	}
2430 	xf86DrvMsg(pScrn->scrnIndex, X_INFO,
2431	"Direct rendering experimental on RS400/Xpress 200 enabled\n");
2432    }
2433
2434    if (info->ChipFamily >= CHIP_FAMILY_R300)
2435	info->dri->gartSize      = R300_DEFAULT_GART_SIZE;
2436    else
2437	info->dri->gartSize      = RADEON_DEFAULT_GART_SIZE;
2438
2439    info->dri->ringSize      = RADEON_DEFAULT_RING_SIZE;
2440    info->dri->bufSize       = RADEON_DEFAULT_BUFFER_SIZE;
2441    info->dri->gartTexSize   = RADEON_DEFAULT_GART_TEX_SIZE;
2442    info->dri->pciAperSize   = RADEON_DEFAULT_PCI_APER_SIZE;
2443    info->cp->CPusecTimeout = RADEON_DEFAULT_CP_TIMEOUT;
2444
2445    if ((xf86GetOptValInteger(info->Options,
2446			     OPTION_GART_SIZE, (int *)&(info->dri->gartSize))) ||
2447			     (xf86GetOptValInteger(info->Options,
2448			     OPTION_GART_SIZE_OLD, (int *)&(info->dri->gartSize)))) {
2449	switch (info->dri->gartSize) {
2450	case 4:
2451	case 8:
2452	case 16:
2453	case 32:
2454	case 64:
2455	case 128:
2456	case 256:
2457	    break;
2458
2459	default:
2460	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
2461		       "Illegal GART size: %d MB\n", info->dri->gartSize);
2462	    return FALSE;
2463	}
2464    }
2465
2466    if (xf86GetOptValInteger(info->Options,
2467			     OPTION_RING_SIZE, &(info->dri->ringSize))) {
2468	if (info->dri->ringSize < 1 || info->dri->ringSize >= (int)info->dri->gartSize) {
2469	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
2470		       "Illegal ring buffer size: %d MB\n",
2471		       info->dri->ringSize);
2472	    return FALSE;
2473	}
2474    }
2475
2476    if (xf86GetOptValInteger(info->Options,
2477			     OPTION_PCIAPER_SIZE, &(info->dri->pciAperSize))) {
2478      switch(info->dri->pciAperSize) {
2479      case 32:
2480      case 64:
2481      case 128:
2482      case 256:
2483	break;
2484      default:
2485	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
2486		       "Illegal pci aper size: %d MB\n",
2487		       info->dri->pciAperSize);
2488	return FALSE;
2489      }
2490    }
2491
2492
2493    if (xf86GetOptValInteger(info->Options,
2494			     OPTION_BUFFER_SIZE, &(info->dri->bufSize))) {
2495	if (info->dri->bufSize < 1 || info->dri->bufSize >= (int)info->dri->gartSize) {
2496	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
2497		       "Illegal vertex/indirect buffers size: %d MB\n",
2498		       info->dri->bufSize);
2499	    return FALSE;
2500	}
2501	if (info->dri->bufSize > 2) {
2502	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
2503		       "Illegal vertex/indirect buffers size: %d MB\n",
2504		       info->dri->bufSize);
2505	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
2506		       "Clamping vertex/indirect buffers size to 2 MB\n");
2507	    info->dri->bufSize = 2;
2508	}
2509    }
2510
2511    if (info->dri->ringSize + info->dri->bufSize + info->dri->gartTexSize >
2512	(int)info->dri->gartSize) {
2513	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
2514		   "Buffers are too big for requested GART space\n");
2515	return FALSE;
2516    }
2517
2518    info->dri->gartTexSize = info->dri->gartSize - (info->dri->ringSize + info->dri->bufSize);
2519
2520    if (xf86GetOptValInteger(info->Options, OPTION_USEC_TIMEOUT,
2521			     &(info->cp->CPusecTimeout))) {
2522	/* This option checked by the RADEON DRM kernel module */
2523    }
2524
2525    /* Two options to try and squeeze as much texture memory as possible
2526     * for dedicated 3d rendering boxes
2527     */
2528    info->dri->noBackBuffer = xf86ReturnOptValBool(info->Options,
2529						   OPTION_NO_BACKBUFFER,
2530						   FALSE);
2531
2532    info->dri->allowPageFlip = 0;
2533
2534#ifdef DAMAGE
2535    if (info->dri->noBackBuffer) {
2536	from = X_DEFAULT;
2537	reason = " because back buffer disabled";
2538    } else {
2539	from = xf86GetOptValBool(info->Options, OPTION_PAGE_FLIP,
2540				 &info->dri->allowPageFlip) ? X_CONFIG : X_DEFAULT;
2541
2542	if (IS_AVIVO_VARIANT) {
2543	    info->dri->allowPageFlip = 0;
2544	    reason = " on r5xx and newer chips.\n";
2545	} else {
2546	    reason = "";
2547	}
2548
2549    }
2550#else
2551    from = X_DEFAULT;
2552    reason = " because Damage layer not available at build time";
2553#endif
2554
2555    xf86DrvMsg(pScrn->scrnIndex, from, "Page Flipping %sabled%s\n",
2556	       info->dri->allowPageFlip ? "en" : "dis", reason);
2557
2558    /* AGP seems to have problems with gart transfers */
2559    if ((info->ChipFamily >= CHIP_FAMILY_R600) && (info->cardType == CARD_AGP))
2560	info->DMAForXv = FALSE;
2561    else
2562	info->DMAForXv = TRUE;
2563    from = xf86GetOptValBool(info->Options, OPTION_XV_DMA, &info->DMAForXv)
2564	 ? X_CONFIG : X_INFO;
2565    xf86DrvMsg(pScrn->scrnIndex, from,
2566	       "Will %stry to use DMA for Xv image transfers\n",
2567	       info->DMAForXv ? "" : "not ");
2568
2569    return TRUE;
2570}
2571#endif /* XF86DRI */
2572
2573static void RADEONPreInitColorTiling(ScrnInfoPtr pScrn)
2574{
2575    RADEONInfoPtr  info = RADEONPTR(pScrn);
2576
2577    info->allowColorTiling = xf86ReturnOptValBool(info->Options,
2578				        OPTION_COLOR_TILING, TRUE);
2579    if (IS_R300_VARIANT || IS_AVIVO_VARIANT) {
2580	/* this may be 4096 on r4xx -- need to double check */
2581	info->MaxSurfaceWidth = 3968; /* one would have thought 4096...*/
2582	info->MaxLines = 4096;
2583    } else {
2584	info->MaxSurfaceWidth = 2048;
2585	info->MaxLines = 2048;
2586    }
2587
2588    if (!info->allowColorTiling)
2589	return;
2590
2591    if (info->ChipFamily >= CHIP_FAMILY_R600)
2592	info->allowColorTiling = FALSE;
2593
2594    /* for zaphod disable tiling for now */
2595    if (info->IsPrimary || info->IsSecondary)
2596	info->allowColorTiling = FALSE;
2597
2598#ifdef XF86DRI
2599    if (info->directRenderingEnabled &&
2600	info->dri->pKernelDRMVersion->version_minor < 14) {
2601	xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
2602		   "[dri] color tiling disabled because of version "
2603		   "mismatch.\n"
2604		   "[dri] radeon.o kernel module version is %d.%d.%d but "
2605		   "1.14.0 or later is required for color tiling.\n",
2606		   info->dri->pKernelDRMVersion->version_major,
2607		   info->dri->pKernelDRMVersion->version_minor,
2608		   info->dri->pKernelDRMVersion->version_patchlevel);
2609	   info->allowColorTiling = FALSE;
2610	   return;
2611    }
2612#endif /* XF86DRI */
2613
2614    if (info->allowColorTiling) {
2615	xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Color tiling enabled by default\n");
2616    } else {
2617	xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Color tiling disabled\n");
2618    }
2619}
2620
2621
2622static Bool RADEONPreInitXv(ScrnInfoPtr pScrn)
2623{
2624    RADEONInfoPtr  info = RADEONPTR(pScrn);
2625    uint16_t mm_table;
2626    uint16_t bios_header;
2627    uint16_t pll_info_block;
2628#ifdef XvExtension
2629    char* microc_path = NULL;
2630    char* microc_type = NULL;
2631    MessageType from;
2632
2633    if (xf86GetOptValInteger(info->Options, OPTION_VIDEO_KEY,
2634			     &(info->videoKey))) {
2635	xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "video key set to 0x%x\n",
2636		   info->videoKey);
2637    } else {
2638	info->videoKey = 0x1E;
2639    }
2640
2641    if(xf86GetOptValInteger(info->Options, OPTION_RAGE_THEATRE_CRYSTAL, &(info->RageTheatreCrystal))) {
2642        xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "Rage Theatre Crystal frequency was specified as %d.%d Mhz\n",
2643                                info->RageTheatreCrystal/100, info->RageTheatreCrystal % 100);
2644    } else {
2645	info->RageTheatreCrystal=-1;
2646    }
2647
2648    if(xf86GetOptValInteger(info->Options, OPTION_RAGE_THEATRE_TUNER_PORT, &(info->RageTheatreTunerPort))) {
2649        xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "Rage Theatre tuner port was specified as %d\n",
2650                                info->RageTheatreTunerPort);
2651    } else {
2652	info->RageTheatreTunerPort=-1;
2653    }
2654
2655    if(info->RageTheatreTunerPort>5){
2656         xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Attempt to assign Rage Theatre tuner port to invalid value. Disabling setting\n");
2657	 info->RageTheatreTunerPort=-1;
2658	 }
2659
2660    if(xf86GetOptValInteger(info->Options, OPTION_RAGE_THEATRE_COMPOSITE_PORT, &(info->RageTheatreCompositePort))) {
2661        xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "Rage Theatre composite port was specified as %d\n",
2662                                info->RageTheatreCompositePort);
2663    } else {
2664	info->RageTheatreCompositePort=-1;
2665    }
2666
2667    if(info->RageTheatreCompositePort>6){
2668         xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Attempt to assign Rage Theatre composite port to invalid value. Disabling setting\n");
2669	 info->RageTheatreCompositePort=-1;
2670	 }
2671
2672    if(xf86GetOptValInteger(info->Options, OPTION_RAGE_THEATRE_SVIDEO_PORT, &(info->RageTheatreSVideoPort))) {
2673        xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "Rage Theatre SVideo Port was specified as %d\n",
2674                                info->RageTheatreSVideoPort);
2675    } else {
2676	info->RageTheatreSVideoPort=-1;
2677    }
2678
2679    if(info->RageTheatreSVideoPort>6){
2680         xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Attempt to assign Rage Theatre SVideo port to invalid value. Disabling setting\n");
2681	 info->RageTheatreSVideoPort=-1;
2682	 }
2683
2684    if(xf86GetOptValInteger(info->Options, OPTION_TUNER_TYPE, &(info->tunerType))) {
2685        xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "Tuner type was specified as %d\n",
2686                                info->tunerType);
2687    } else {
2688	info->tunerType=-1;
2689    }
2690
2691    if(info->tunerType>31){
2692         xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Attempt to set tuner type to invalid value. Disabling setting\n");
2693	 info->tunerType=-1;
2694	 }
2695
2696	if((microc_path = xf86GetOptValString(info->Options, OPTION_RAGE_THEATRE_MICROC_PATH)) != NULL)
2697	{
2698		xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "Rage Theatre Microcode path was specified as %s\n", microc_path);
2699		info->RageTheatreMicrocPath = microc_path;
2700    } else {
2701		info->RageTheatreMicrocPath= NULL;
2702    }
2703
2704	if((microc_type = xf86GetOptValString(info->Options, OPTION_RAGE_THEATRE_MICROC_TYPE)) != NULL)
2705	{
2706		xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "Rage Theatre Microcode type was specified as %s\n", microc_type);
2707		info->RageTheatreMicrocType = microc_type;
2708	} else {
2709		info->RageTheatreMicrocType= NULL;
2710	}
2711
2712    if(xf86GetOptValInteger(info->Options, OPTION_SCALER_WIDTH, &(info->overlay_scaler_buffer_width))) {
2713	if ((info->overlay_scaler_buffer_width < 1024) ||
2714	  (info->overlay_scaler_buffer_width > 2048) ||
2715	  ((info->overlay_scaler_buffer_width % 64) != 0)) {
2716	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Attempt to set illegal scaler width. Using default\n");
2717	    from = X_DEFAULT;
2718	    info->overlay_scaler_buffer_width = 0;
2719	} else
2720	    from = X_CONFIG;
2721    } else {
2722	from = X_DEFAULT;
2723	info->overlay_scaler_buffer_width = 0;
2724    }
2725    if (!info->overlay_scaler_buffer_width) {
2726       /* overlay scaler line length differs for different revisions
2727       this needs to be maintained by hand  */
2728	switch(info->ChipFamily){
2729	case CHIP_FAMILY_R200:
2730	case CHIP_FAMILY_R300:
2731	case CHIP_FAMILY_R350:
2732	case CHIP_FAMILY_RV350:
2733	case CHIP_FAMILY_RV380:
2734	case CHIP_FAMILY_R420:
2735	case CHIP_FAMILY_RV410:
2736		info->overlay_scaler_buffer_width = 1920;
2737		break;
2738	default:
2739		info->overlay_scaler_buffer_width = 1536;
2740	}
2741    }
2742    xf86DrvMsg(pScrn->scrnIndex, from, "Assuming overlay scaler buffer width is %d\n",
2743	info->overlay_scaler_buffer_width);
2744#endif
2745
2746    /* Rescue MM_TABLE before VBIOS is freed */
2747    info->MM_TABLE_valid = FALSE;
2748
2749    if((info->VBIOS==NULL)||(info->VBIOS[0]!=0x55)||(info->VBIOS[1]!=0xaa)){
2750       xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Cannot access BIOS or it is not valid.\n"
2751               "\t\tIf your card is TV-in capable you will need to specify options RageTheatreCrystal, RageTheatreTunerPort, \n"
2752               "\t\tRageTheatreSVideoPort and TunerType in /etc/X11/xorg.conf.\n"
2753               );
2754       info->MM_TABLE_valid = FALSE;
2755       return TRUE;
2756       }
2757
2758    bios_header=info->VBIOS[0x48];
2759    bios_header+=(((int)info->VBIOS[0x49]+0)<<8);
2760
2761    mm_table=info->VBIOS[bios_header+0x38];
2762    if(mm_table==0)
2763    {
2764        xf86DrvMsg(pScrn->scrnIndex,X_INFO,"No MM_TABLE found - assuming CARD is not TV-in capable.\n");
2765        info->MM_TABLE_valid = FALSE;
2766        return TRUE;
2767    }
2768    mm_table+=(((int)info->VBIOS[bios_header+0x39]+0)<<8)-2;
2769
2770    if(mm_table>0)
2771    {
2772        memcpy(&(info->MM_TABLE), &(info->VBIOS[mm_table]), sizeof(info->MM_TABLE));
2773        xf86DrvMsg(pScrn->scrnIndex, X_INFO, "MM_TABLE: %02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x\n",
2774            info->MM_TABLE.table_revision,
2775            info->MM_TABLE.table_size,
2776            info->MM_TABLE.tuner_type,
2777            info->MM_TABLE.audio_chip,
2778            info->MM_TABLE.product_id,
2779            info->MM_TABLE.tuner_voltage_teletext_fm,
2780            info->MM_TABLE.i2s_config,
2781            info->MM_TABLE.video_decoder_type,
2782            info->MM_TABLE.video_decoder_host_config,
2783            info->MM_TABLE.input[0],
2784            info->MM_TABLE.input[1],
2785            info->MM_TABLE.input[2],
2786            info->MM_TABLE.input[3],
2787            info->MM_TABLE.input[4]);
2788
2789	  /* Is it an MM_TABLE we know about ? */
2790	  if(info->MM_TABLE.table_size != 0xc){
2791	       xf86DrvMsg(pScrn->scrnIndex, X_INFO, "This card has MM_TABLE we do not recognize.\n"
2792			"\t\tIf your card is TV-in capable you will need to specify options RageTheatreCrystal, RageTheatreTunerPort, \n"
2793			"\t\tRageTheatreSVideoPort and TunerType in /etc/X11/xorg.conf.\n"
2794			);
2795		info->MM_TABLE_valid = FALSE;
2796		return TRUE;
2797	  	}
2798        info->MM_TABLE_valid = TRUE;
2799    } else {
2800        xf86DrvMsg(pScrn->scrnIndex, X_INFO, "No MM_TABLE found - assuming card is not TV-in capable (mm_table=%d).\n", mm_table);
2801        info->MM_TABLE_valid = FALSE;
2802    }
2803
2804    pll_info_block=info->VBIOS[bios_header+0x30];
2805    pll_info_block+=(((int)info->VBIOS[bios_header+0x31]+0)<<8);
2806
2807    info->video_decoder_type=info->VBIOS[pll_info_block+0x08];
2808    info->video_decoder_type+=(((int)info->VBIOS[pll_info_block+0x09]+0)<<8);
2809
2810    return TRUE;
2811}
2812
2813static Bool
2814RADEONPreInitBIOS(ScrnInfoPtr pScrn, xf86Int10InfoPtr  pInt10)
2815{
2816    RADEONInfoPtr info = RADEONPTR(pScrn);
2817
2818    if (!RADEONGetBIOSInfo(pScrn, pInt10)) {
2819	/* Avivo chips require bios for atom */
2820	if (IS_AVIVO_VARIANT)
2821	    return FALSE;
2822    }
2823    return TRUE;
2824}
2825
2826Bool
2827RADEONZaphodStringMatches(ScrnInfoPtr pScrn, const char *s, char *output_name)
2828{
2829    int i = 0;
2830    char s1[20];
2831
2832    do {
2833	switch(*s) {
2834	case ',':
2835	    s1[i] = '\0';
2836	    i = 0;
2837	    if (strcmp(s1, output_name) == 0)
2838		return TRUE;
2839	    break;
2840	case ' ':
2841	case '\t':
2842	case '\n':
2843	case '\r':
2844	    break;
2845	default:
2846	    s1[i] = *s;
2847	    i++;
2848	    break;
2849	}
2850    } while(*s++);
2851
2852    s1[i] = '\0';
2853    if (strcmp(s1, output_name) == 0)
2854	return TRUE;
2855
2856    return FALSE;
2857}
2858
2859static void RADEONFixZaphodOutputs(ScrnInfoPtr pScrn)
2860{
2861    RADEONInfoPtr info = RADEONPTR(pScrn);
2862    xf86CrtcConfigPtr   config = XF86_CRTC_CONFIG_PTR(pScrn);
2863    int o;
2864    char *s;
2865
2866    if ((s = xf86GetOptValString(info->Options, OPTION_ZAPHOD_HEADS))) {
2867	for (o = config->num_output; o > 0; o--) {
2868	    if (!RADEONZaphodStringMatches(pScrn, s, config->output[o - 1]->name))
2869		xf86OutputDestroy(config->output[o - 1]);
2870	}
2871    } else {
2872	if (info->IsPrimary) {
2873	    xf86OutputDestroy(config->output[0]);
2874	    while (config->num_output > 1) {
2875		xf86OutputDestroy(config->output[1]);
2876	    }
2877	} else {
2878	    while (config->num_output > 1) {
2879		xf86OutputDestroy(config->output[1]);
2880	    }
2881	}
2882    }
2883}
2884
2885static Bool RADEONPreInitControllers(ScrnInfoPtr pScrn)
2886{
2887    xf86CrtcConfigPtr   config = XF86_CRTC_CONFIG_PTR(pScrn);
2888    RADEONInfoPtr info = RADEONPTR(pScrn);
2889    int i;
2890    int mask;
2891    int found = 0;
2892
2893    if (info->IsPrimary)
2894	mask = 1;
2895    else if (info->IsSecondary)
2896	mask = 2;
2897    else
2898	mask = 3;
2899
2900    if (!RADEONAllocateControllers(pScrn, mask))
2901	return FALSE;
2902
2903    RADEONGetClockInfo(pScrn);
2904
2905    if (info->IsAtomBios && info->IsIGP)
2906	RADEONATOMGetIGPInfo(pScrn);
2907
2908    if (!RADEONSetupConnectors(pScrn)) {
2909	return FALSE;
2910    }
2911
2912    if (info->IsPrimary || info->IsSecondary) {
2913	/* fixup outputs for zaphod */
2914	RADEONFixZaphodOutputs(pScrn);
2915    }
2916
2917    RADEONPrintPortMap(pScrn);
2918
2919    info->first_load_no_devices = FALSE;
2920    for (i = 0; i < config->num_output; i++) {
2921	xf86OutputPtr	      output = config->output[i];
2922
2923	output->status = (*output->funcs->detect) (output);
2924	ErrorF("finished output detect: %d\n", i);
2925	if (info->IsPrimary || info->IsSecondary) {
2926	    if (output->status != XF86OutputStatusConnected)
2927		return FALSE;
2928	}
2929	if (output->status != XF86OutputStatusDisconnected)
2930	    found++;
2931    }
2932
2933    if (!found) {
2934	/* nothing connected, light up some defaults so the server comes up */
2935	xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "No connected devices found!\n");
2936	info->first_load_no_devices = TRUE;
2937    }
2938
2939    ErrorF("finished all detect\n");
2940    return TRUE;
2941}
2942
2943static void
2944RADEONProbeDDC(ScrnInfoPtr pScrn, int indx)
2945{
2946    vbeInfoPtr  pVbe;
2947
2948    if (xf86LoadSubModule(pScrn, "vbe")) {
2949	pVbe = VBEInit(NULL,indx);
2950	ConfiguredMonitor = vbeDoEDID(pVbe, NULL);
2951	vbeFree(pVbe);
2952    }
2953}
2954
2955static Bool
2956RADEONCRTCResize(ScrnInfoPtr scrn, int width, int height)
2957{
2958    scrn->virtualX = width;
2959    scrn->virtualY = height;
2960    /* RADEONSetPitch(scrn); */
2961    return TRUE;
2962}
2963
2964static const xf86CrtcConfigFuncsRec RADEONCRTCResizeFuncs = {
2965    RADEONCRTCResize
2966};
2967
2968Bool RADEONPreInit(ScrnInfoPtr pScrn, int flags)
2969{
2970    xf86CrtcConfigPtr   xf86_config;
2971    RADEONInfoPtr     info;
2972    xf86Int10InfoPtr  pInt10 = NULL;
2973    void *int10_save = NULL;
2974    const char *s;
2975    RADEONEntPtr pRADEONEnt;
2976    DevUnion* pPriv;
2977
2978    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
2979		   "RADEONPreInit\n");
2980    if (pScrn->numEntities != 1) return FALSE;
2981
2982    if (!RADEONGetRec(pScrn)) return FALSE;
2983
2984    info               = RADEONPTR(pScrn);
2985    info->MMIO         = NULL;
2986
2987    info->IsSecondary  = FALSE;
2988    info->IsPrimary = FALSE;
2989    info->kms_enabled = FALSE;
2990
2991    info->pEnt         = xf86GetEntityInfo(pScrn->entityList[pScrn->numEntities - 1]);
2992    if (info->pEnt->location.type != BUS_PCI) goto fail;
2993
2994    pPriv = xf86GetEntityPrivate(pScrn->entityList[0],
2995				 getRADEONEntityIndex());
2996    pRADEONEnt = pPriv->ptr;
2997
2998    if(xf86IsEntityShared(pScrn->entityList[0]))
2999    {
3000        if(xf86IsPrimInitDone(pScrn->entityList[0]))
3001        {
3002            info->IsSecondary = TRUE;
3003            pRADEONEnt->pSecondaryScrn = pScrn;
3004	    info->SavedReg = &pRADEONEnt->SavedReg;
3005	    info->ModeReg = &pRADEONEnt->ModeReg;
3006        }
3007        else
3008        {
3009	    info->IsPrimary = TRUE;
3010            xf86SetPrimInitDone(pScrn->entityList[0]);
3011            pRADEONEnt->pPrimaryScrn = pScrn;
3012            pRADEONEnt->HasSecondary = FALSE;
3013	    info->SavedReg = &pRADEONEnt->SavedReg;
3014	    info->ModeReg = &pRADEONEnt->ModeReg;
3015        }
3016    } else {
3017	info->SavedReg = &pRADEONEnt->SavedReg;
3018	info->ModeReg = &pRADEONEnt->ModeReg;
3019    }
3020
3021    info->PciInfo = xf86GetPciInfoForEntity(info->pEnt->index);
3022    info->PciTag  = pciTag(PCI_DEV_BUS(info->PciInfo),
3023			   PCI_DEV_DEV(info->PciInfo),
3024			   PCI_DEV_FUNC(info->PciInfo));
3025    info->MMIOAddr = PCI_REGION_BASE(info->PciInfo, 2, REGION_MEM) & ~0xffULL;
3026    info->MMIOSize = PCI_REGION_SIZE(info->PciInfo, 2);
3027	xf86DrvMsg(pScrn->scrnIndex, X_INFO, "TOTO SAYS %016llx\n",
3028		(unsigned long long)PCI_REGION_BASE(info->PciInfo,
3029		2, REGION_MEM));
3030    if (info->pEnt->device->IOBase) {
3031	xf86DrvMsg(pScrn->scrnIndex, X_CONFIG,
3032		   "MMIO address override, using 0x%08lx instead of 0x%016llx\n",
3033		   info->pEnt->device->IOBase,
3034		   info->MMIOAddr);
3035	info->MMIOAddr = info->pEnt->device->IOBase;
3036    } else if (!info->MMIOAddr) {
3037	xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "No valid MMIO address\n");
3038	goto fail1;
3039    }
3040    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
3041	       "MMIO registers at 0x%016llx: size %ldKB\n", info->MMIOAddr, info->MMIOSize / 1024);
3042
3043    if(!RADEONMapMMIO(pScrn)) {
3044	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
3045		   "Memory map the MMIO region failed\n");
3046	goto fail1;
3047    }
3048
3049#if !defined(__alpha__)
3050    if (
3051#ifndef XSERVER_LIBPCIACCESS
3052	xf86GetPciDomain(info->PciTag) ||
3053#endif
3054	!xf86IsPrimaryPci(info->PciInfo))
3055	RADEONPreInt10Save(pScrn, &int10_save);
3056#else
3057    /* [Alpha] On the primary, the console already ran the BIOS and we're
3058     *         going to run it again - so make sure to "fix up" the card
3059     *         so that (1) we can read the BIOS ROM and (2) the BIOS will
3060     *         get the memory config right.
3061     */
3062    RADEONPreInt10Save(pScrn, &int10_save);
3063#endif
3064
3065    if (flags & PROBE_DETECT) {
3066	RADEONProbeDDC(pScrn, info->pEnt->index);
3067	RADEONPostInt10Check(pScrn, int10_save);
3068	if(info->MMIO) RADEONUnmapMMIO(pScrn);
3069	return TRUE;
3070    }
3071
3072
3073    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
3074	       "PCI bus %d card %d func %d\n",
3075	       PCI_DEV_BUS(info->PciInfo),
3076	       PCI_DEV_DEV(info->PciInfo),
3077	       PCI_DEV_FUNC(info->PciInfo));
3078
3079#ifndef XSERVER_LIBPCIACCESS
3080    if (xf86RegisterResources(info->pEnt->index, 0, ResExclusive))
3081	goto fail;
3082
3083    xf86SetOperatingState(resVga, info->pEnt->index, ResUnusedOpr);
3084
3085    pScrn->racMemFlags = RAC_FB | RAC_COLORMAP | RAC_VIEWPORT | RAC_CURSOR;
3086#endif
3087    pScrn->monitor     = pScrn->confScreen->monitor;
3088
3089   /* Allocate an xf86CrtcConfig */
3090    xf86CrtcConfigInit (pScrn, &RADEONCRTCResizeFuncs);
3091    xf86_config = XF86_CRTC_CONFIG_PTR(pScrn);
3092
3093
3094    if (!RADEONPreInitVisual(pScrn))
3095	goto fail;
3096
3097				/* We can't do this until we have a
3098				   pScrn->display. */
3099    xf86CollectOptions(pScrn, NULL);
3100    if (!(info->Options = malloc(sizeof(RADEONOptions))))
3101	goto fail;
3102
3103    memcpy(info->Options, RADEONOptions, sizeof(RADEONOptions));
3104    xf86ProcessOptions(pScrn->scrnIndex, pScrn->options, info->Options);
3105
3106    /* By default, don't do VGA IOs on ppc/sparc */
3107#if defined(__powerpc__) || defined(__sparc__) || !defined(WITH_VGAHW)
3108    info->VGAAccess = FALSE;
3109#else
3110    info->VGAAccess = TRUE;
3111#endif
3112
3113#ifdef WITH_VGAHW
3114    xf86GetOptValBool(info->Options, OPTION_VGA_ACCESS, &info->VGAAccess);
3115    if (info->VGAAccess) {
3116       if (!xf86LoadSubModule(pScrn, "vgahw"))
3117           info->VGAAccess = FALSE;
3118        else {
3119            if (!vgaHWGetHWRec(pScrn))
3120               info->VGAAccess = FALSE;
3121       }
3122       if (!info->VGAAccess)
3123           xf86DrvMsg(pScrn->scrnIndex, X_WARNING, "Loading VGA module failed,"
3124                      " trying to run without it\n");
3125    } else
3126           xf86DrvMsg(pScrn->scrnIndex, X_INFO, "VGAAccess option set to FALSE,"
3127                      " VGA module load skipped\n");
3128    if (info->VGAAccess)
3129        vgaHWGetIOBase(VGAHWPTR(pScrn));
3130#endif
3131
3132
3133    if (!RADEONPreInitWeight(pScrn))
3134	goto fail;
3135
3136    info->DispPriority = 1;
3137    if ((s = xf86GetOptValString(info->Options, OPTION_DISP_PRIORITY))) {
3138	if (strcmp(s, "AUTO") == 0) {
3139	    info->DispPriority = 1;
3140	} else if (strcmp(s, "BIOS") == 0) {
3141	    info->DispPriority = 0;
3142	} else if (strcmp(s, "HIGH") == 0) {
3143	    info->DispPriority = 2;
3144	} else
3145	    info->DispPriority = 1;
3146    }
3147
3148    if (!RADEONPreInitChipType(pScrn))
3149	goto fail;
3150
3151    if (!RADEONPreInitInt10(pScrn, &pInt10))
3152	goto fail;
3153
3154    RADEONPostInt10Check(pScrn, int10_save);
3155
3156    if (!RADEONPreInitBIOS(pScrn, pInt10))
3157	goto fail;
3158
3159    /* Save BIOS scratch registers */
3160    RADEONSaveBIOSRegisters(pScrn, info->SavedReg);
3161
3162#ifdef XF86DRI
3163    /* PreInit DRI first of all since we need that for getting a proper
3164     * memory map
3165     */
3166    info->directRenderingEnabled = RADEONPreInitDRI(pScrn);
3167#endif
3168    if (!info->directRenderingEnabled) {
3169	if (info->ChipFamily >= CHIP_FAMILY_R600) {
3170	    info->r600_shadow_fb = TRUE;
3171	    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
3172			   "using shadow framebuffer\n");
3173	    if (!xf86LoadSubModule(pScrn, "shadow"))
3174		info->r600_shadow_fb = FALSE;
3175	}
3176    }
3177
3178    if (!RADEONPreInitVRAM(pScrn))
3179	goto fail;
3180
3181    RADEONPreInitColorTiling(pScrn);
3182
3183    if (IS_AVIVO_VARIANT)
3184	xf86CrtcSetSizeRange (pScrn, 320, 200, 8192, 8192);
3185    else
3186	xf86CrtcSetSizeRange (pScrn, 320, 200, 4096, 4096);
3187
3188    RADEONPreInitDDC(pScrn);
3189
3190    if (!RADEONPreInitControllers(pScrn))
3191       goto fail;
3192
3193    if (!xf86InitialConfiguration (pScrn, FALSE))
3194   {
3195      xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "No valid modes.\n");
3196      goto fail;
3197   }
3198
3199    /* fix up cloning on rn50 cards
3200     * since they only have one crtc sometimes the xserver doesn't assign
3201     * a crtc to one of the outputs even though both outputs have common modes
3202     * which results in only one monitor being enabled.  Assign a crtc here so
3203     * that both outputs light up.
3204     */
3205    if (info->ChipFamily == CHIP_FAMILY_RV100 && !pRADEONEnt->HasCRTC2) {
3206	int i;
3207
3208	for (i = 0; i < xf86_config->num_output; i++) {
3209	    xf86OutputPtr output = xf86_config->output[i];
3210
3211	    /* XXX: double check crtc mode */
3212	    if ((output->probed_modes != NULL) && (output->crtc == NULL))
3213		output->crtc = xf86_config->crtc[0];
3214	}
3215    }
3216
3217    RADEONSetPitch(pScrn);
3218
3219   /* Set display resolution */
3220   xf86SetDpi(pScrn, 0, 0);
3221
3222	/* Get ScreenInit function */
3223    if (!xf86LoadSubModule(pScrn, "fb")) return FALSE;
3224
3225    if (!RADEONPreInitGamma(pScrn))              goto fail;
3226
3227    if (!RADEONPreInitCursor(pScrn))             goto fail;
3228
3229    if (!RADEONPreInitAccel(pScrn))              goto fail;
3230
3231    if (!IS_AVIVO_VARIANT) {
3232	if (!RADEONPreInitXv(pScrn))                 goto fail;
3233    }
3234
3235    if (!xf86RandR12PreInit (pScrn))
3236    {
3237      xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "RandR initialization failure\n");
3238      goto fail;
3239    }
3240
3241    if (pScrn->modes == NULL) {
3242      xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "No modes.\n");
3243      goto fail;
3244   }
3245
3246
3247				/* Free int10 info */
3248    if (pInt10)
3249	xf86FreeInt10(pInt10);
3250
3251    if(info->MMIO) RADEONUnmapMMIO(pScrn);
3252    info->MMIO = NULL;
3253
3254    xf86DrvMsg(pScrn->scrnIndex, X_NOTICE,
3255	       "MergedFB support has been removed and replaced with"
3256	       " xrandr 1.2 support\n");
3257
3258    return TRUE;
3259
3260fail:
3261				/* Pre-init failed. */
3262				/* Free the video bios (if applicable) */
3263    if (info->VBIOS) {
3264	free(info->VBIOS);
3265	info->VBIOS = NULL;
3266    }
3267
3268				/* Free int10 info */
3269    if (pInt10)
3270	xf86FreeInt10(pInt10);
3271
3272#ifdef WITH_VGAHW
3273    if (info->VGAAccess)
3274           vgaHWFreeHWRec(pScrn);
3275#endif
3276
3277    if(info->MMIO) RADEONUnmapMMIO(pScrn);
3278    info->MMIO = NULL;
3279
3280 fail1:
3281    RADEONFreeRec(pScrn);
3282
3283    return FALSE;
3284}
3285
3286/* Load a palette */
3287static void RADEONLoadPalette(ScrnInfoPtr pScrn, int numColors,
3288			      int *indices, LOCO *colors, VisualPtr pVisual)
3289{
3290    RADEONInfoPtr  info       = RADEONPTR(pScrn);
3291    xf86CrtcConfigPtr   xf86_config = XF86_CRTC_CONFIG_PTR(pScrn);
3292    int            i;
3293    int            index, j;
3294    uint16_t       lut_r[256], lut_g[256], lut_b[256];
3295    int c;
3296
3297#ifdef XF86DRI
3298    if (info->cp->CPStarted && pScrn->pScreen) DRILock(pScrn->pScreen, 0);
3299#endif
3300
3301    if (info->accelOn && pScrn->pScreen)
3302        RADEON_SYNC(info, pScrn);
3303
3304    {
3305
3306      for (c = 0; c < xf86_config->num_crtc; c++) {
3307	  xf86CrtcPtr crtc = xf86_config->crtc[c];
3308	  RADEONCrtcPrivatePtr radeon_crtc = crtc->driver_private;
3309
3310	  for (i = 0 ; i < 256; i++) {
3311	      lut_r[i] = radeon_crtc->lut_r[i] << 6;
3312	      lut_g[i] = radeon_crtc->lut_g[i] << 6;
3313	      lut_b[i] = radeon_crtc->lut_b[i] << 6;
3314	  }
3315
3316	  switch (info->CurrentLayout.depth) {
3317	  case 15:
3318	      for (i = 0; i < numColors; i++) {
3319		  index = indices[i];
3320		  for (j = 0; j < 8; j++) {
3321		      lut_r[index * 8 + j] = colors[index].red << 6;
3322		      lut_g[index * 8 + j] = colors[index].green << 6;
3323		      lut_b[index * 8 + j] = colors[index].blue << 6;
3324		  }
3325	      }
3326	  case 16:
3327	      for (i = 0; i < numColors; i++) {
3328		  index = indices[i];
3329
3330		  if (i <= 31) {
3331		      for (j = 0; j < 8; j++) {
3332			  lut_r[index * 8 + j] = colors[index].red << 6;
3333			  lut_b[index * 8 + j] = colors[index].blue << 6;
3334		      }
3335		  }
3336
3337		  for (j = 0; j < 4; j++) {
3338		      lut_g[index * 4 + j] = colors[index].green << 6;
3339		  }
3340	      }
3341	  default:
3342	      for (i = 0; i < numColors; i++) {
3343		  index = indices[i];
3344		  lut_r[index] = colors[index].red << 6;
3345		  lut_g[index] = colors[index].green << 6;
3346		  lut_b[index] = colors[index].blue << 6;
3347	      }
3348	      break;
3349	  }
3350
3351	      /* Make the change through RandR */
3352#ifdef RANDR_12_INTERFACE
3353	  if (crtc->randr_crtc)
3354	      RRCrtcGammaSet(crtc->randr_crtc, lut_r, lut_g, lut_b);
3355	  else
3356#endif
3357	      crtc->funcs->gamma_set(crtc, lut_r, lut_g, lut_b, 256);
3358      }
3359    }
3360
3361#ifdef XF86DRI
3362    if (info->cp->CPStarted && pScrn->pScreen) DRIUnlock(pScrn->pScreen);
3363#endif
3364}
3365
3366static void RADEONBlockHandler(int i, pointer blockData,
3367			       pointer pTimeout, pointer pReadmask)
3368{
3369    ScreenPtr      pScreen = screenInfo.screens[i];
3370    ScrnInfoPtr    pScrn   = xf86Screens[i];
3371    RADEONInfoPtr  info    = RADEONPTR(pScrn);
3372
3373    pScreen->BlockHandler = info->BlockHandler;
3374    (*pScreen->BlockHandler) (i, blockData, pTimeout, pReadmask);
3375    pScreen->BlockHandler = RADEONBlockHandler;
3376
3377    if (info->VideoTimerCallback)
3378	(*info->VideoTimerCallback)(pScrn, currentTime.milliseconds);
3379
3380#if defined(RENDER) && defined(USE_XAA)
3381    if(info->accel_state->RenderCallback)
3382	(*info->accel_state->RenderCallback)(pScrn);
3383#endif
3384
3385#ifdef USE_EXA
3386    info->accel_state->engineMode = EXA_ENGINEMODE_UNKNOWN;
3387#endif
3388
3389    if (info->pm.dynamic_mode_enabled)
3390	RADEONPMBlockHandler(pScrn);
3391}
3392
3393static void
3394RADEONInitBIOSRegisters(ScrnInfoPtr pScrn)
3395{
3396    RADEONInfoPtr  info  = RADEONPTR(pScrn);
3397    unsigned char *RADEONMMIO = info->MMIO;
3398    RADEONSavePtr save = info->ModeReg;
3399
3400    save->bios_0_scratch = info->SavedReg->bios_0_scratch;
3401    save->bios_1_scratch = info->SavedReg->bios_1_scratch;
3402    save->bios_2_scratch = info->SavedReg->bios_2_scratch;
3403    save->bios_3_scratch = info->SavedReg->bios_3_scratch;
3404    save->bios_4_scratch = info->SavedReg->bios_4_scratch;
3405    save->bios_5_scratch = info->SavedReg->bios_5_scratch;
3406    save->bios_6_scratch = info->SavedReg->bios_6_scratch;
3407    save->bios_7_scratch = info->SavedReg->bios_7_scratch;
3408
3409    if (info->IsAtomBios) {
3410	/* let the bios control the backlight */
3411	save->bios_2_scratch &= ~ATOM_S2_VRI_BRIGHT_ENABLE;
3412	/* tell the bios not to handle mode switching */
3413	save->bios_6_scratch |= (ATOM_S6_ACC_BLOCK_DISPLAY_SWITCH |
3414				 ATOM_S6_ACC_MODE);
3415
3416	if (info->ChipFamily >= CHIP_FAMILY_R600) {
3417	    OUTREG(R600_BIOS_2_SCRATCH, save->bios_2_scratch);
3418	    OUTREG(R600_BIOS_6_SCRATCH, save->bios_6_scratch);
3419	} else {
3420	    OUTREG(RADEON_BIOS_2_SCRATCH, save->bios_2_scratch);
3421	    OUTREG(RADEON_BIOS_6_SCRATCH, save->bios_6_scratch);
3422	}
3423    } else {
3424	/* let the bios control the backlight */
3425	save->bios_0_scratch &= ~RADEON_DRIVER_BRIGHTNESS_EN;
3426	/* tell the bios not to handle mode switching */
3427	save->bios_6_scratch |= (RADEON_DISPLAY_SWITCHING_DIS |
3428				 RADEON_ACC_MODE_CHANGE);
3429	/* tell the bios a driver is loaded */
3430	save->bios_7_scratch |= RADEON_DRV_LOADED;
3431
3432	OUTREG(RADEON_BIOS_0_SCRATCH, save->bios_0_scratch);
3433	OUTREG(RADEON_BIOS_6_SCRATCH, save->bios_6_scratch);
3434	//OUTREG(RADEON_BIOS_7_SCRATCH, save->bios_7_scratch);
3435    }
3436
3437}
3438
3439
3440/* Called at the start of each server generation. */
3441Bool RADEONScreenInit(int scrnIndex, ScreenPtr pScreen,
3442                                int argc, char **argv)
3443{
3444    ScrnInfoPtr    pScrn = xf86Screens[pScreen->myNum];
3445    RADEONInfoPtr  info  = RADEONPTR(pScrn);
3446    int            hasDRI = 0;
3447#ifdef RENDER
3448    int            subPixelOrder = SubPixelUnknown;
3449    char*          s;
3450#endif
3451
3452
3453    info->accelOn      = FALSE;
3454#ifdef USE_XAA
3455    info->accel_state->accel        = NULL;
3456#endif
3457#ifdef XF86DRI
3458    pScrn->fbOffset    = info->dri->frontOffset;
3459#endif
3460
3461    if (info->IsSecondary)
3462        pScrn->fbOffset = pScrn->videoRam * 1024;
3463#ifdef XF86DRI
3464    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
3465		   "RADEONScreenInit %lx %ld %d\n",
3466		   pScrn->memPhysBase, pScrn->fbOffset, info->dri->frontOffset);
3467#else
3468    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
3469		   "RADEONScreenInit %lx %ld\n",
3470		   pScrn->memPhysBase, pScrn->fbOffset);
3471#endif
3472    if (!RADEONMapMem(pScrn)) return FALSE;
3473
3474#ifdef XF86DRI
3475    info->dri->fbX = 0;
3476    info->dri->fbY = 0;
3477#endif
3478
3479    info->PaletteSavedOnVT = FALSE;
3480
3481    info->crtc_on = FALSE;
3482    info->crtc2_on = FALSE;
3483
3484    /* save the real front buffer size
3485     * it changes with randr, rotation, etc.
3486     */
3487    info->virtualX = pScrn->virtualX;
3488    info->virtualY = pScrn->virtualY;
3489
3490    RADEONSave(pScrn);
3491
3492    /* set initial bios scratch reg state */
3493    RADEONInitBIOSRegisters(pScrn);
3494
3495    /* blank the outputs/crtcs */
3496    RADEONBlank(pScrn);
3497
3498    RADEONPMInit(pScrn);
3499
3500    if (info->allowColorTiling && (pScrn->virtualX > info->MaxSurfaceWidth)) {
3501	xf86DrvMsg(pScrn->scrnIndex, X_INFO,
3502		   "Color tiling not supported with virtual x resolutions larger than %d, disabling\n",
3503		    info->MaxSurfaceWidth);
3504	info->allowColorTiling = FALSE;
3505    }
3506    if (info->allowColorTiling) {
3507        info->tilingEnabled = (pScrn->currentMode->Flags & (V_DBLSCAN | V_INTERLACE)) ? FALSE : TRUE;
3508    }
3509
3510    /* Visual setup */
3511    miClearVisualTypes();
3512    if (!miSetVisualTypes(pScrn->depth,
3513			  miGetDefaultVisualMask(pScrn->depth),
3514			  pScrn->rgbBits,
3515			  pScrn->defaultVisual)) return FALSE;
3516    miSetPixmapDepths ();
3517
3518#ifdef XF86DRI
3519    if (info->directRenderingEnabled) {
3520	MessageType from;
3521
3522	info->dri->depthBits = pScrn->depth;
3523
3524	from = xf86GetOptValInteger(info->Options, OPTION_DEPTH_BITS,
3525				    &info->dri->depthBits)
3526	     ? X_CONFIG : X_DEFAULT;
3527
3528	if (info->dri->depthBits != 16 && info->dri->depthBits != 24) {
3529	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
3530		       "Value for Option \"DepthBits\" must be 16 or 24\n");
3531	    info->dri->depthBits = pScrn->depth;
3532	    from = X_DEFAULT;
3533	}
3534
3535	xf86DrvMsg(pScrn->scrnIndex, from,
3536		   "Using %d bit depth buffer\n", info->dri->depthBits);
3537    }
3538
3539
3540    hasDRI = info->directRenderingEnabled;
3541#endif /* XF86DRI */
3542
3543    /* Initialize the memory map, this basically calculates the values
3544     * we'll use later on for MC_FB_LOCATION & MC_AGP_LOCATION
3545     */
3546    RADEONInitMemoryMap(pScrn);
3547
3548    /* empty the surfaces */
3549    if (info->ChipFamily < CHIP_FAMILY_R600) {
3550	unsigned char *RADEONMMIO = info->MMIO;
3551	unsigned int j;
3552	for (j = 0; j < 8; j++) {
3553	    OUTREG(RADEON_SURFACE0_INFO + 16 * j, 0);
3554	    OUTREG(RADEON_SURFACE0_LOWER_BOUND + 16 * j, 0);
3555	    OUTREG(RADEON_SURFACE0_UPPER_BOUND + 16 * j, 0);
3556	}
3557    }
3558
3559#ifdef XF86DRI
3560    /* Depth moves are disabled by default since they are extremely slow */
3561    info->dri->depthMoves = xf86ReturnOptValBool(info->Options,
3562						 OPTION_DEPTH_MOVE, FALSE);
3563    if (info->dri->depthMoves && info->allowColorTiling) {
3564	xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "Enabling depth moves\n");
3565    } else if (info->dri->depthMoves) {
3566	xf86DrvMsg(pScrn->scrnIndex, X_INFO,
3567		   "Depth moves don't work without color tiling, disabled\n");
3568	info->dri->depthMoves = FALSE;
3569    } else {
3570	xf86DrvMsg(pScrn->scrnIndex, X_INFO,
3571		   "Depth moves disabled by default\n");
3572    }
3573#endif
3574
3575    /* Initial setup of surfaces */
3576    if (info->ChipFamily < CHIP_FAMILY_R600) {
3577        xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
3578                       "Setting up initial surfaces\n");
3579        RADEONChangeSurfaces(pScrn);
3580    }
3581
3582				/* Memory manager setup */
3583
3584    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
3585		   "Setting up accel memmap\n");
3586
3587#ifdef USE_EXA
3588    if (info->useEXA) {
3589#ifdef XF86DRI
3590	if (hasDRI) {
3591	    info->accelDFS = xf86ReturnOptValBool(info->Options, OPTION_ACCEL_DFS,
3592						  info->cardType != CARD_AGP);
3593
3594	    /* Reserve approx. half of offscreen memory for local textures by
3595	     * default, can be overridden with Option "FBTexPercent".
3596	     * Round down to a whole number of texture regions.
3597	     */
3598	    info->dri->textureSize = 50;
3599
3600	    if (xf86GetOptValInteger(info->Options, OPTION_FBTEX_PERCENT,
3601				     &(info->dri->textureSize))) {
3602		if (info->dri->textureSize < 0 || info->dri->textureSize > 100) {
3603		    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
3604			       "Illegal texture memory percentage: %dx, setting to default 50%%\n",
3605			       info->dri->textureSize);
3606		    info->dri->textureSize = 50;
3607		}
3608	    }
3609	}
3610#endif /* XF86DRI */
3611
3612	if (!RADEONSetupMemEXA(pScreen))
3613	    return FALSE;
3614    }
3615#endif
3616
3617#if defined(XF86DRI) && defined(USE_XAA)
3618    if (!info->useEXA && hasDRI) {
3619	info->dri->textureSize = -1;
3620	if (xf86GetOptValInteger(info->Options, OPTION_FBTEX_PERCENT,
3621				 &(info->dri->textureSize))) {
3622	    if (info->dri->textureSize < 0 || info->dri->textureSize > 100) {
3623		xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
3624			   "Illegal texture memory percentage: %dx, using default behaviour\n",
3625			   info->dri->textureSize);
3626		info->dri->textureSize = -1;
3627	    }
3628	}
3629	if (!RADEONSetupMemXAA_DRI(scrnIndex, pScreen))
3630	    return FALSE;
3631    	pScrn->fbOffset    = info->dri->frontOffset;
3632    }
3633#endif
3634
3635#ifdef USE_XAA
3636    if (!info->useEXA && !hasDRI && !RADEONSetupMemXAA(scrnIndex, pScreen))
3637	return FALSE;
3638#endif
3639
3640    info->accel_state->dst_pitch_offset =
3641	(((pScrn->displayWidth * info->CurrentLayout.pixel_bytes / 64)
3642	  << 22) | ((info->fbLocation + pScrn->fbOffset) >> 10));
3643
3644    /* Setup DRI after visuals have been established, but before fbScreenInit is
3645     * called.  fbScreenInit will eventually call the driver's InitGLXVisuals
3646     * call back. */
3647#ifdef XF86DRI
3648    if (info->directRenderingEnabled) {
3649	/* FIXME: When we move to dynamic allocation of back and depth
3650	 * buffers, we will want to revisit the following check for 3
3651	 * times the virtual size of the screen below.
3652	 */
3653	int  width_bytes = (pScrn->displayWidth *
3654			    info->CurrentLayout.pixel_bytes);
3655	int  maxy        = info->FbMapSize / width_bytes;
3656
3657	if (maxy <= pScrn->virtualY * 3) {
3658	    xf86DrvMsg(scrnIndex, X_ERROR,
3659		       "Static buffer allocation failed.  Disabling DRI.\n");
3660	    xf86DrvMsg(scrnIndex, X_ERROR,
3661		       "At least %d kB of video memory needed at this "
3662		       "resolution and depth.\n",
3663		       (pScrn->displayWidth * pScrn->virtualY *
3664			info->CurrentLayout.pixel_bytes * 3 + 1023) / 1024);
3665	    info->directRenderingEnabled = FALSE;
3666	} else {
3667	    info->directRenderingEnabled = RADEONDRIScreenInit(pScreen);
3668	}
3669    }
3670
3671    /* Tell DRI about new memory map */
3672    if (info->directRenderingEnabled && info->dri->newMemoryMap) {
3673        if (RADEONDRISetParam(pScrn, RADEON_SETPARAM_NEW_MEMMAP, 1) < 0) {
3674		xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
3675			   "[drm] failed to enable new memory map\n");
3676		RADEONDRICloseScreen(pScreen);
3677		info->directRenderingEnabled = FALSE;
3678	}
3679    }
3680#endif
3681    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
3682		   "Initializing fb layer\n");
3683
3684    if (info->r600_shadow_fb) {
3685	info->fb_shadow = calloc(1,
3686				 pScrn->displayWidth * pScrn->virtualY *
3687				 ((pScrn->bitsPerPixel + 7) >> 3));
3688	if (info->fb_shadow == NULL) {
3689	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
3690                       "Failed to allocate shadow framebuffer\n");
3691	    info->r600_shadow_fb = FALSE;
3692	} else {
3693	    if (!fbScreenInit(pScreen, info->fb_shadow,
3694			      pScrn->virtualX, pScrn->virtualY,
3695			      pScrn->xDpi, pScrn->yDpi, pScrn->displayWidth,
3696			      pScrn->bitsPerPixel))
3697		return FALSE;
3698	}
3699    }
3700
3701    if (info->r600_shadow_fb == FALSE) {
3702	/* Init fb layer */
3703	if (!fbScreenInit(pScreen, info->FB + pScrn->fbOffset,
3704			  pScrn->virtualX, pScrn->virtualY,
3705			  pScrn->xDpi, pScrn->yDpi, pScrn->displayWidth,
3706			  pScrn->bitsPerPixel))
3707	    return FALSE;
3708    }
3709
3710    xf86SetBlackWhitePixels(pScreen);
3711
3712    if (pScrn->bitsPerPixel > 8) {
3713	VisualPtr  visual;
3714
3715	visual = pScreen->visuals + pScreen->numVisuals;
3716	while (--visual >= pScreen->visuals) {
3717	    if ((visual->class | DynamicClass) == DirectColor) {
3718		visual->offsetRed   = pScrn->offset.red;
3719		visual->offsetGreen = pScrn->offset.green;
3720		visual->offsetBlue  = pScrn->offset.blue;
3721		visual->redMask     = pScrn->mask.red;
3722		visual->greenMask   = pScrn->mask.green;
3723		visual->blueMask    = pScrn->mask.blue;
3724	    }
3725	}
3726    }
3727
3728    /* Must be after RGB order fixed */
3729    fbPictureInit (pScreen, 0, 0);
3730
3731#ifdef RENDER
3732    if ((s = xf86GetOptValString(info->Options, OPTION_SUBPIXEL_ORDER))) {
3733	if (strcmp(s, "RGB") == 0) subPixelOrder = SubPixelHorizontalRGB;
3734	else if (strcmp(s, "BGR") == 0) subPixelOrder = SubPixelHorizontalBGR;
3735	else if (strcmp(s, "NONE") == 0) subPixelOrder = SubPixelNone;
3736	PictureSetSubpixelOrder (pScreen, subPixelOrder);
3737    }
3738#endif
3739
3740    pScrn->vtSema = TRUE;
3741
3742    /* restore the memory map here otherwise we may get a hang when
3743     * initializing the drm below
3744     */
3745    RADEONInitMemMapRegisters(pScrn, info->ModeReg, info);
3746    RADEONRestoreMemMapRegisters(pScrn, info->ModeReg);
3747
3748    /* Backing store setup */
3749    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
3750		   "Initializing backing store\n");
3751    miInitializeBackingStore(pScreen);
3752    xf86SetBackingStore(pScreen);
3753
3754    /* DRI finalisation */
3755#ifdef XF86DRI
3756    if (info->directRenderingEnabled &&
3757	(info->cardType==CARD_PCIE || info->cardType==CARD_PCI) &&
3758        info->dri->pKernelDRMVersion->version_minor >= 19)
3759    {
3760      if (RADEONDRISetParam(pScrn, RADEON_SETPARAM_PCIGART_LOCATION, info->dri->pciGartOffset) < 0)
3761	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
3762		   "[drm] failed set pci gart location\n");
3763
3764      if (info->dri->pKernelDRMVersion->version_minor >= 26) {
3765	if (RADEONDRISetParam(pScrn, RADEON_SETPARAM_PCIGART_TABLE_SIZE, info->dri->pciGartSize) < 0)
3766	  xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
3767		     "[drm] failed set pci gart table size\n");
3768      }
3769    }
3770    if (info->directRenderingEnabled) {
3771        xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
3772		       "DRI Finishing init !\n");
3773	info->directRenderingEnabled = RADEONDRIFinishScreenInit(pScreen);
3774    }
3775    if (info->directRenderingEnabled) {
3776	/* DRI final init might have changed the memory map, we need to adjust
3777	 * our local image to make sure we restore them properly on mode
3778	 * changes or VT switches
3779	 */
3780	RADEONAdjustMemMapRegisters(pScrn, info->ModeReg);
3781
3782	xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Direct rendering enabled\n");
3783
3784	/* we might already be in tiled mode, tell drm about it */
3785	if (info->directRenderingEnabled && info->tilingEnabled) {
3786	  if (RADEONDRISetParam(pScrn, RADEON_SETPARAM_SWITCH_TILING, (info->tilingEnabled ? 1 : 0)) < 0)
3787  	      xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
3788			 "[drm] failed changing tiling status\n");
3789	}
3790    } else {
3791	xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
3792		   "Direct rendering disabled\n");
3793    }
3794#endif
3795
3796    /* Make sure surfaces are allright since DRI setup may have changed them */
3797    if (info->ChipFamily < CHIP_FAMILY_R600) {
3798        xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
3799                       "Setting up final surfaces\n");
3800
3801        RADEONChangeSurfaces(pScrn);
3802    }
3803
3804
3805    /* Enable aceleration */
3806    if (!xf86ReturnOptValBool(info->Options, OPTION_NOACCEL, FALSE)) {
3807	xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
3808		       "Initializing Acceleration\n");
3809	if (RADEONAccelInit(pScreen)) {
3810	    xf86DrvMsg(scrnIndex, X_INFO, "Acceleration enabled\n");
3811	    info->accelOn = TRUE;
3812	} else {
3813	    xf86DrvMsg(scrnIndex, X_ERROR,
3814		       "Acceleration initialization failed\n");
3815	    xf86DrvMsg(scrnIndex, X_INFO, "Acceleration disabled\n");
3816	    info->accelOn = FALSE;
3817	}
3818    } else {
3819	xf86DrvMsg(scrnIndex, X_INFO, "Acceleration disabled\n");
3820	info->accelOn = FALSE;
3821    }
3822
3823    /* Init DPMS */
3824    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
3825		   "Initializing DPMS\n");
3826    xf86DPMSInit(pScreen, xf86DPMSSet, 0);
3827
3828    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
3829		   "Initializing Cursor\n");
3830
3831    /* Set Silken Mouse */
3832    xf86SetSilkenMouse(pScreen);
3833
3834    /* Cursor setup */
3835    miDCInitialize(pScreen, xf86GetPointerScreenFuncs());
3836
3837    /* Hardware cursor setup */
3838    if (!xf86ReturnOptValBool(info->Options, OPTION_SW_CURSOR, FALSE)) {
3839	if (RADEONCursorInit(pScreen)) {
3840#ifdef USE_XAA
3841	    if (!info->useEXA) {
3842		int  width, height;
3843
3844		if (xf86QueryLargestOffscreenArea(pScreen, &width, &height,
3845					      0, 0, 0)) {
3846		    xf86DrvMsg(scrnIndex, X_INFO,
3847			       "Largest offscreen area available: %d x %d\n",
3848			       width, height);
3849		}
3850	    }
3851#endif /* USE_XAA */
3852	} else {
3853	    xf86DrvMsg(scrnIndex, X_ERROR,
3854		       "Hardware cursor initialization failed\n");
3855	    xf86DrvMsg(scrnIndex, X_INFO, "Using software cursor\n");
3856	}
3857    } else {
3858	xf86DrvMsg(scrnIndex, X_INFO, "Using software cursor\n");
3859    }
3860
3861    /* DGA setup */
3862#ifdef XFreeXDGA
3863    xf86DiDGAInit(pScreen, info->LinearAddr + pScrn->fbOffset);
3864#endif
3865
3866    /* Init Xv */
3867    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
3868		   "Initializing Xv\n");
3869    RADEONInitVideo(pScreen);
3870
3871    if (info->r600_shadow_fb == TRUE) {
3872        if (!shadowSetup(pScreen)) {
3873            return FALSE;
3874        }
3875    }
3876
3877    /* Clear the framebuffer */
3878    memset(info->FB + pScrn->fbOffset, 0,
3879           pScrn->virtualY * pScrn->displayWidth * info->CurrentLayout.pixel_bytes);
3880
3881    pScrn->pScreen = pScreen;
3882
3883    /* set the modes with desired rotation, etc. */
3884    if (!xf86SetDesiredModes (pScrn))
3885	return FALSE;
3886
3887    /* Provide SaveScreen & wrap BlockHandler and CloseScreen */
3888    /* Wrap CloseScreen */
3889    info->CloseScreen    = pScreen->CloseScreen;
3890    pScreen->CloseScreen = RADEONCloseScreen;
3891    pScreen->SaveScreen  = RADEONSaveScreen;
3892    info->BlockHandler = pScreen->BlockHandler;
3893    pScreen->BlockHandler = RADEONBlockHandler;
3894    info->CreateScreenResources = pScreen->CreateScreenResources;
3895    pScreen->CreateScreenResources = RADEONCreateScreenResources;
3896
3897   if (!xf86CrtcScreenInit (pScreen))
3898       return FALSE;
3899
3900    /* Colormap setup */
3901    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
3902                   "Initializing color map\n");
3903    if (!miCreateDefColormap(pScreen)) return FALSE;
3904    /* all radeons support 10 bit CLUTs */
3905    if (!xf86HandleColormaps(pScreen, 256, 10,
3906			     RADEONLoadPalette, NULL,
3907			     CMAP_PALETTED_TRUECOLOR
3908#if 0 /* This option messes up text mode! (eich@suse.de) */
3909			     | CMAP_LOAD_EVEN_IF_OFFSCREEN
3910#endif
3911			     | CMAP_RELOAD_ON_MODE_SWITCH)) return FALSE;
3912
3913    /* Note unused options */
3914    if (serverGeneration == 1)
3915	xf86ShowUnusedOptions(pScrn->scrnIndex, pScrn->options);
3916
3917    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
3918		   "RADEONScreenInit finished\n");
3919
3920    return TRUE;
3921}
3922
3923/* Write memory mapping registers */
3924void RADEONRestoreMemMapRegisters(ScrnInfoPtr pScrn,
3925					 RADEONSavePtr restore)
3926{
3927    RADEONInfoPtr  info       = RADEONPTR(pScrn);
3928    RADEONEntPtr pRADEONEnt = RADEONEntPriv(pScrn);
3929    unsigned char *RADEONMMIO = info->MMIO;
3930    int timeout;
3931    uint32_t mc_fb_loc, mc_agp_loc, mc_agp_loc_hi;
3932
3933    radeon_read_mc_fb_agp_location(pScrn, LOC_FB | LOC_AGP, &mc_fb_loc,
3934				   &mc_agp_loc, &mc_agp_loc_hi);
3935
3936    if (info->IsSecondary)
3937      return;
3938    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
3939	       "RADEONRestoreMemMapRegisters() : \n");
3940    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
3941	       "  MC_FB_LOCATION   : 0x%08x 0x%08x\n",
3942	       (unsigned)restore->mc_fb_location, (unsigned int)mc_fb_loc);
3943    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
3944	       "  MC_AGP_LOCATION  : 0x%08x\n",
3945	       (unsigned)restore->mc_agp_location);
3946
3947    if (IS_DCE4_VARIANT) {
3948	if (mc_fb_loc != restore->mc_fb_location ||
3949	    mc_agp_loc != restore->mc_agp_location) {
3950	    uint32_t tmp;
3951
3952	    //XXX
3953	    //RADEONWaitForIdleMMIO(pScrn);
3954
3955            /* disable VGA rendering core */
3956    	    OUTREG(AVIVO_VGA_RENDER_CONTROL, INREG(AVIVO_VGA_RENDER_CONTROL) & ~AVIVO_VGA_VSTATUS_CNTL_MASK);
3957	    OUTREG(AVIVO_D1VGA_CONTROL, INREG(AVIVO_D1VGA_CONTROL) & ~AVIVO_DVGA_CONTROL_MODE_ENABLE);
3958	    OUTREG(AVIVO_D2VGA_CONTROL, INREG(AVIVO_D2VGA_CONTROL) & ~AVIVO_DVGA_CONTROL_MODE_ENABLE);
3959	    OUTREG(EVERGREEN_D3VGA_CONTROL, INREG(EVERGREEN_D3VGA_CONTROL) & ~AVIVO_DVGA_CONTROL_MODE_ENABLE);
3960	    OUTREG(EVERGREEN_D4VGA_CONTROL, INREG(EVERGREEN_D4VGA_CONTROL) & ~AVIVO_DVGA_CONTROL_MODE_ENABLE);
3961	    OUTREG(EVERGREEN_D5VGA_CONTROL, INREG(EVERGREEN_D5VGA_CONTROL) & ~AVIVO_DVGA_CONTROL_MODE_ENABLE);
3962	    OUTREG(EVERGREEN_D6VGA_CONTROL, INREG(EVERGREEN_D6VGA_CONTROL) & ~AVIVO_DVGA_CONTROL_MODE_ENABLE);
3963
3964	    /* Stop display & memory access */
3965	    tmp = INREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC0_REGISTER_OFFSET);
3966	    OUTREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC0_REGISTER_OFFSET, tmp & ~EVERGREEN_CRTC_MASTER_EN);
3967	    tmp = INREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC0_REGISTER_OFFSET);
3968
3969	    tmp = INREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC1_REGISTER_OFFSET);
3970	    OUTREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC1_REGISTER_OFFSET, tmp & ~EVERGREEN_CRTC_MASTER_EN);
3971	    tmp = INREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC1_REGISTER_OFFSET);
3972
3973	    if (!IS_DCE41_VARIANT) {
3974		tmp = INREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC2_REGISTER_OFFSET);
3975		OUTREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC2_REGISTER_OFFSET, tmp & ~EVERGREEN_CRTC_MASTER_EN);
3976		tmp = INREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC2_REGISTER_OFFSET);
3977
3978		tmp = INREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC3_REGISTER_OFFSET);
3979		OUTREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC3_REGISTER_OFFSET, tmp & ~EVERGREEN_CRTC_MASTER_EN);
3980		tmp = INREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC3_REGISTER_OFFSET);
3981
3982		tmp = INREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC4_REGISTER_OFFSET);
3983		OUTREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC4_REGISTER_OFFSET, tmp & ~EVERGREEN_CRTC_MASTER_EN);
3984		tmp = INREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC4_REGISTER_OFFSET);
3985
3986		tmp = INREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC5_REGISTER_OFFSET);
3987		OUTREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC5_REGISTER_OFFSET, tmp & ~EVERGREEN_CRTC_MASTER_EN);
3988		tmp = INREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC5_REGISTER_OFFSET);
3989	    }
3990
3991	    usleep(10000);
3992	    timeout = 0;
3993	    while (!(radeon_get_mc_idle(pScrn))) {
3994		if (++timeout > 1000000) {
3995		    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
3996			       "Timeout trying to update memory controller settings !\n");
3997		    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
3998			       "You will probably crash now ... \n");
3999		    /* Nothing we can do except maybe try to kill the server,
4000		     * let's wait 2 seconds to leave the above message a chance
4001		     * to maybe hit the disk and continue trying to setup despite
4002		     * the MC being non-idle
4003		     */
4004		    usleep(2000000);
4005		}
4006		usleep(10);
4007	    }
4008
4009	    radeon_write_mc_fb_agp_location(pScrn, LOC_FB | LOC_AGP,
4010					    restore->mc_fb_location,
4011					    restore->mc_agp_location,
4012					    restore->mc_agp_location_hi);
4013
4014	    OUTREG(R600_HDP_NONSURFACE_BASE, (restore->mc_fb_location & 0xffff) << 16);
4015
4016	}
4017    } else if (IS_AVIVO_VARIANT) {
4018	if (mc_fb_loc != restore->mc_fb_location ||
4019	    mc_agp_loc != restore->mc_agp_location) {
4020	    uint32_t tmp;
4021
4022	    RADEONWaitForIdleMMIO(pScrn);
4023
4024            /* disable VGA rendering core */
4025    	    OUTREG(AVIVO_VGA_RENDER_CONTROL, INREG(AVIVO_VGA_RENDER_CONTROL) &~ AVIVO_VGA_VSTATUS_CNTL_MASK);
4026
4027	    OUTREG(AVIVO_D1VGA_CONTROL, INREG(AVIVO_D1VGA_CONTROL) & ~AVIVO_DVGA_CONTROL_MODE_ENABLE);
4028	    OUTREG(AVIVO_D2VGA_CONTROL, INREG(AVIVO_D2VGA_CONTROL) & ~AVIVO_DVGA_CONTROL_MODE_ENABLE);
4029
4030	    /* Stop display & memory access */
4031	    tmp = INREG(AVIVO_D1CRTC_CONTROL);
4032	    OUTREG(AVIVO_D1CRTC_CONTROL, tmp & ~AVIVO_CRTC_EN);
4033
4034	    tmp = INREG(AVIVO_D2CRTC_CONTROL);
4035	    OUTREG(AVIVO_D2CRTC_CONTROL, tmp & ~AVIVO_CRTC_EN);
4036
4037	    tmp = INREG(AVIVO_D2CRTC_CONTROL);
4038
4039	    usleep(10000);
4040	    timeout = 0;
4041	    while (!(radeon_get_mc_idle(pScrn))) {
4042		if (++timeout > 1000000) {
4043		    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
4044			       "Timeout trying to update memory controller settings !\n");
4045		    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
4046			       "You will probably crash now ... \n");
4047		    /* Nothing we can do except maybe try to kill the server,
4048		     * let's wait 2 seconds to leave the above message a chance
4049		     * to maybe hit the disk and continue trying to setup despite
4050		     * the MC being non-idle
4051		     */
4052		    usleep(2000000);
4053		}
4054		usleep(10);
4055	    }
4056
4057	    radeon_write_mc_fb_agp_location(pScrn, LOC_FB | LOC_AGP,
4058					    restore->mc_fb_location,
4059					    restore->mc_agp_location,
4060					    restore->mc_agp_location_hi);
4061
4062	    if (info->ChipFamily < CHIP_FAMILY_R600) {
4063		OUTREG(AVIVO_HDP_FB_LOCATION, restore->mc_fb_location);
4064	    } else {
4065		OUTREG(R600_HDP_NONSURFACE_BASE, (restore->mc_fb_location << 16) & 0xff0000);
4066	    }
4067
4068	    /* Reset the engine and HDP */
4069	    if (info->ChipFamily < CHIP_FAMILY_R600)
4070		RADEONEngineReset(pScrn);
4071	}
4072    } else {
4073
4074	/* Write memory mapping registers only if their value change
4075	 * since we must ensure no access is done while they are
4076	 * reprogrammed
4077	 */
4078	if (mc_fb_loc != restore->mc_fb_location ||
4079	    mc_agp_loc != restore->mc_agp_location) {
4080	    uint32_t crtc_ext_cntl, crtc_gen_cntl, crtc2_gen_cntl=0, ov0_scale_cntl;
4081	    uint32_t old_mc_status;
4082
4083	    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
4084			   "  Map Changed ! Applying ...\n");
4085
4086	    /* Make sure engine is idle. We assume the CCE is stopped
4087	     * at this point
4088	     */
4089	    RADEONWaitForIdleMMIO(pScrn);
4090
4091	    if (info->IsIGP)
4092		goto igp_no_mcfb;
4093
4094	    /* Capture MC_STATUS in case things go wrong ... */
4095	    old_mc_status = INREG(RADEON_MC_STATUS);
4096
4097	    /* Stop display & memory access */
4098	    ov0_scale_cntl = INREG(RADEON_OV0_SCALE_CNTL);
4099	    OUTREG(RADEON_OV0_SCALE_CNTL, ov0_scale_cntl & ~RADEON_SCALER_ENABLE);
4100	    crtc_ext_cntl = INREG(RADEON_CRTC_EXT_CNTL);
4101	    OUTREG(RADEON_CRTC_EXT_CNTL, crtc_ext_cntl | RADEON_CRTC_DISPLAY_DIS);
4102	    crtc_gen_cntl = INREG(RADEON_CRTC_GEN_CNTL);
4103	    RADEONWaitForVerticalSync(pScrn);
4104	    OUTREG(RADEON_CRTC_GEN_CNTL,
4105		   (crtc_gen_cntl
4106		    & ~(RADEON_CRTC_CUR_EN | RADEON_CRTC_ICON_EN))
4107		   | RADEON_CRTC_DISP_REQ_EN_B | RADEON_CRTC_EXT_DISP_EN);
4108
4109	    if (pRADEONEnt->HasCRTC2) {
4110		crtc2_gen_cntl = INREG(RADEON_CRTC2_GEN_CNTL);
4111		RADEONWaitForVerticalSync2(pScrn);
4112		OUTREG(RADEON_CRTC2_GEN_CNTL,
4113		       (crtc2_gen_cntl
4114			& ~(RADEON_CRTC2_CUR_EN | RADEON_CRTC2_ICON_EN))
4115		       | RADEON_CRTC2_DISP_REQ_EN_B);
4116	    }
4117
4118	    /* Make sure the chip settles down (paranoid !) */
4119	    usleep(100000);
4120	    timeout = 0;
4121	    while (!(radeon_get_mc_idle(pScrn))) {
4122		if (++timeout > 1000000) {
4123		    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
4124			       "Timeout trying to update memory controller settings !\n");
4125		    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
4126			       "MC_STATUS = 0x%08x (on entry = 0x%08x)\n",
4127			       (unsigned int)INREG(RADEON_MC_STATUS), (unsigned int)old_mc_status);
4128		    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
4129			       "You will probably crash now ... \n");
4130		    /* Nothing we can do except maybe try to kill the server,
4131		     * let's wait 2 seconds to leave the above message a chance
4132		     * to maybe hit the disk and continue trying to setup despite
4133		     * the MC being non-idle
4134		     */
4135		    usleep(2000000);
4136		}
4137		usleep(10);
4138	    }
4139
4140	    /* Update maps, first clearing out AGP to make sure we don't get
4141	     * a temporary overlap
4142	     */
4143	    OUTREG(RADEON_MC_AGP_LOCATION, 0xfffffffc);
4144	    OUTREG(RADEON_MC_FB_LOCATION, restore->mc_fb_location);
4145	    radeon_write_mc_fb_agp_location(pScrn, LOC_FB | LOC_AGP, restore->mc_fb_location,
4146					    0xfffffffc, 0);
4147	igp_no_mcfb:
4148	    radeon_write_mc_fb_agp_location(pScrn, LOC_AGP, 0,
4149					    restore->mc_agp_location, 0);
4150	    /* Make sure map fully reached the chip */
4151	    (void)INREG(RADEON_MC_FB_LOCATION);
4152
4153	    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
4154			   "  Map applied, resetting engine ...\n");
4155
4156	    /* Reset the engine and HDP */
4157	    RADEONEngineReset(pScrn);
4158
4159	    /* Make sure we have sane offsets before re-enabling the CRTCs, disable
4160	     * stereo, clear offsets, and wait for offsets to catch up with hw
4161	     */
4162
4163	    OUTREG(RADEON_CRTC_OFFSET_CNTL, RADEON_CRTC_OFFSET_FLIP_CNTL);
4164	    OUTREG(RADEON_CRTC_OFFSET, 0);
4165	    OUTREG(RADEON_CUR_OFFSET, 0);
4166	    timeout = 0;
4167	    while(INREG(RADEON_CRTC_OFFSET) & RADEON_CRTC_OFFSET__GUI_TRIG_OFFSET) {
4168		if (timeout++ > 1000000) {
4169		    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
4170			       "Timeout waiting for CRTC offset to update !\n");
4171		    break;
4172		}
4173		usleep(1000);
4174	    }
4175	    if (pRADEONEnt->HasCRTC2) {
4176		OUTREG(RADEON_CRTC2_OFFSET_CNTL, RADEON_CRTC2_OFFSET_FLIP_CNTL);
4177		OUTREG(RADEON_CRTC2_OFFSET, 0);
4178		OUTREG(RADEON_CUR2_OFFSET, 0);
4179		timeout = 0;
4180		while(INREG(RADEON_CRTC2_OFFSET) & RADEON_CRTC2_OFFSET__GUI_TRIG_OFFSET) {
4181		    if (timeout++ > 1000000) {
4182			xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
4183				   "Timeout waiting for CRTC2 offset to update !\n");
4184			break;
4185		    }
4186		    usleep(1000);
4187		}
4188	    }
4189	}
4190
4191	xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
4192		       "Updating display base addresses...\n");
4193
4194	OUTREG(RADEON_DISPLAY_BASE_ADDR, restore->display_base_addr);
4195	if (pRADEONEnt->HasCRTC2)
4196	    OUTREG(RADEON_DISPLAY2_BASE_ADDR, restore->display2_base_addr);
4197	OUTREG(RADEON_OV0_BASE_ADDR, restore->ov0_base_addr);
4198	(void)INREG(RADEON_OV0_BASE_ADDR);
4199
4200	/* More paranoia delays, wait 100ms */
4201	usleep(100000);
4202
4203	xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
4204		       "Memory map updated.\n");
4205    }
4206}
4207
4208#ifdef XF86DRI
4209static void RADEONAdjustMemMapRegisters(ScrnInfoPtr pScrn, RADEONSavePtr save)
4210{
4211    RADEONInfoPtr  info   = RADEONPTR(pScrn);
4212    uint32_t fb, agp, agp_hi;
4213    int changed = 0;
4214
4215    if (info->IsSecondary)
4216      return;
4217
4218    radeon_read_mc_fb_agp_location(pScrn, LOC_FB | LOC_AGP, &fb, &agp, &agp_hi);
4219
4220    if (fb != save->mc_fb_location || agp != save->mc_agp_location ||
4221	agp_hi != save->mc_agp_location_hi)
4222	changed = 1;
4223
4224    if (changed) {
4225	xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
4226		   "DRI init changed memory map, adjusting ...\n");
4227	xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
4228		   "  MC_FB_LOCATION  was: 0x%08lx is: 0x%08lx\n",
4229		   (long unsigned int)info->mc_fb_location, (long unsigned int)fb);
4230	xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
4231		   "  MC_AGP_LOCATION was: 0x%08lx is: 0x%08lx\n",
4232		   (long unsigned int)info->mc_agp_location, (long unsigned int)agp);
4233	info->mc_fb_location = fb;
4234	info->mc_agp_location = agp;
4235	if (info->ChipFamily >= CHIP_FAMILY_R600)
4236	    info->fbLocation = ((uint64_t)info->mc_fb_location & 0xffff) << 24;
4237	else
4238	    info->fbLocation = ((uint64_t)info->mc_fb_location & 0xffff) << 16;
4239
4240	info->accel_state->dst_pitch_offset =
4241	    (((pScrn->displayWidth * info->CurrentLayout.pixel_bytes / 64)
4242	      << 22) | ((info->fbLocation + pScrn->fbOffset) >> 10));
4243	RADEONInitMemMapRegisters(pScrn, save, info);
4244	RADEONRestoreMemMapRegisters(pScrn, save);
4245    }
4246
4247#ifdef USE_EXA
4248    if (info->accelDFS || (info->ChipFamily >= CHIP_FAMILY_R600))
4249    {
4250	drm_radeon_getparam_t gp;
4251	int gart_base;
4252
4253	memset(&gp, 0, sizeof(gp));
4254	gp.param = RADEON_PARAM_GART_BASE;
4255	gp.value = &gart_base;
4256
4257	if (drmCommandWriteRead(info->dri->drmFD, DRM_RADEON_GETPARAM, &gp,
4258				sizeof(gp)) < 0) {
4259	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
4260		       "Failed to determine GART area MC location, not using "
4261		       "accelerated DownloadFromScreen hook!\n");
4262	    info->accelDFS = FALSE;
4263	} else {
4264	    info->gartLocation = gart_base;
4265	}
4266    }
4267#endif /* USE_EXA */
4268}
4269#endif
4270
4271/* restore original surface info (for fb console). */
4272static void RADEONRestoreSurfaces(ScrnInfoPtr pScrn, RADEONSavePtr restore)
4273{
4274    RADEONInfoPtr      info = RADEONPTR(pScrn);
4275    unsigned char *RADEONMMIO = info->MMIO;
4276    unsigned int surfnr;
4277
4278    for ( surfnr = 0; surfnr < 8; surfnr++ ) {
4279	OUTREG(RADEON_SURFACE0_INFO + 16 * surfnr, restore->surfaces[surfnr][0]);
4280	OUTREG(RADEON_SURFACE0_LOWER_BOUND + 16 * surfnr, restore->surfaces[surfnr][1]);
4281	OUTREG(RADEON_SURFACE0_UPPER_BOUND + 16 * surfnr, restore->surfaces[surfnr][2]);
4282    }
4283}
4284
4285/* save original surface info (for fb console). */
4286static void RADEONSaveSurfaces(ScrnInfoPtr pScrn, RADEONSavePtr save)
4287{
4288    RADEONInfoPtr      info = RADEONPTR(pScrn);
4289    unsigned char *RADEONMMIO = info->MMIO;
4290    unsigned int surfnr;
4291
4292    for ( surfnr = 0; surfnr < 8; surfnr++ ) {
4293	save->surfaces[surfnr][0] = INREG(RADEON_SURFACE0_INFO + 16 * surfnr);
4294	save->surfaces[surfnr][1] = INREG(RADEON_SURFACE0_LOWER_BOUND + 16 * surfnr);
4295	save->surfaces[surfnr][2] = INREG(RADEON_SURFACE0_UPPER_BOUND + 16 * surfnr);
4296    }
4297}
4298
4299void RADEONChangeSurfaces(ScrnInfoPtr pScrn)
4300{
4301   /* the idea here is to only set up front buffer as tiled, and back/depth buffer when needed.
4302      Everything else is left as untiled. This means we need to use eplicit src/dst pitch control
4303      when blitting, based on the src/target address, and can no longer use a default offset.
4304      But OTOH we don't need to dynamically change surfaces (for xv for instance), and some
4305      ugly offset / fb reservation (cursor) is gone. And as a bonus, everything actually works...
4306      For simplicity, just always update everything (just let the ioctl fail - could do better).
4307      All surface addresses are relative to RADEON_MC_FB_LOCATION */
4308
4309    RADEONInfoPtr  info  = RADEONPTR(pScrn);
4310    int cpp = info->CurrentLayout.pixel_bytes;
4311    /* depth/front/back pitch must be identical (and the same as displayWidth) */
4312    int width_bytes = pScrn->displayWidth * cpp;
4313    int bufferSize = RADEON_ALIGN((RADEON_ALIGN(pScrn->virtualY, 16)) * width_bytes,
4314        RADEON_GPU_PAGE_SIZE);
4315    unsigned int color_pattern, swap_pattern;
4316
4317    if (!info->allowColorTiling)
4318	return;
4319
4320    swap_pattern = 0;
4321#if X_BYTE_ORDER == X_BIG_ENDIAN
4322    switch (pScrn->bitsPerPixel) {
4323    case 16:
4324	swap_pattern = RADEON_SURF_AP0_SWP_16BPP | RADEON_SURF_AP1_SWP_16BPP;
4325	break;
4326
4327    case 32:
4328	swap_pattern = RADEON_SURF_AP0_SWP_32BPP | RADEON_SURF_AP1_SWP_32BPP;
4329	break;
4330    }
4331#endif
4332    if (info->ChipFamily < CHIP_FAMILY_R200) {
4333	color_pattern = RADEON_SURF_TILE_COLOR_MACRO;
4334    } else if (IS_R300_VARIANT || IS_AVIVO_VARIANT) {
4335       color_pattern = R300_SURF_TILE_COLOR_MACRO;
4336    } else {
4337	color_pattern = R200_SURF_TILE_COLOR_MACRO;
4338    }
4339#ifdef XF86DRI
4340    if (info->directRenderingInited) {
4341	drm_radeon_surface_free_t drmsurffree;
4342	drm_radeon_surface_alloc_t drmsurfalloc;
4343	int retvalue;
4344	int depthCpp = (info->dri->depthBits - 8) / 4;
4345	int depth_width_bytes = pScrn->displayWidth * depthCpp;
4346	int depthBufferSize = RADEON_ALIGN((RADEON_ALIGN(pScrn->virtualY, 16)) * depth_width_bytes,
4347				RADEON_GPU_PAGE_SIZE);
4348	unsigned int depth_pattern;
4349
4350	drmsurffree.address = info->dri->frontOffset;
4351	retvalue = drmCommandWrite(info->dri->drmFD, DRM_RADEON_SURF_FREE,
4352	    &drmsurffree, sizeof(drmsurffree));
4353
4354	if (!((info->ChipFamily == CHIP_FAMILY_RV100) ||
4355	    (info->ChipFamily == CHIP_FAMILY_RS100) ||
4356	    (info->ChipFamily == CHIP_FAMILY_RS200))) {
4357	    drmsurffree.address = info->dri->depthOffset;
4358	    retvalue = drmCommandWrite(info->dri->drmFD, DRM_RADEON_SURF_FREE,
4359		&drmsurffree, sizeof(drmsurffree));
4360	}
4361
4362	if (!info->dri->noBackBuffer) {
4363	    drmsurffree.address = info->dri->backOffset;
4364	    retvalue = drmCommandWrite(info->dri->drmFD, DRM_RADEON_SURF_FREE,
4365		&drmsurffree, sizeof(drmsurffree));
4366	}
4367
4368	drmsurfalloc.size = bufferSize;
4369	drmsurfalloc.address = info->dri->frontOffset;
4370	drmsurfalloc.flags = swap_pattern;
4371
4372	if (info->tilingEnabled) {
4373	    if (IS_R300_VARIANT || IS_AVIVO_VARIANT)
4374		drmsurfalloc.flags |= (width_bytes / 8) | color_pattern;
4375	    else
4376		drmsurfalloc.flags |= (width_bytes / 16) | color_pattern;
4377	}
4378	retvalue = drmCommandWrite(info->dri->drmFD, DRM_RADEON_SURF_ALLOC,
4379				   &drmsurfalloc, sizeof(drmsurfalloc));
4380	if (retvalue < 0)
4381	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
4382		       "drm: could not allocate surface for front buffer!\n");
4383
4384	if ((info->dri->have3DWindows) && (!info->dri->noBackBuffer)) {
4385	    drmsurfalloc.address = info->dri->backOffset;
4386	    retvalue = drmCommandWrite(info->dri->drmFD, DRM_RADEON_SURF_ALLOC,
4387				       &drmsurfalloc, sizeof(drmsurfalloc));
4388	    if (retvalue < 0)
4389		xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
4390			   "drm: could not allocate surface for back buffer!\n");
4391	}
4392
4393	if (info->ChipFamily < CHIP_FAMILY_R200) {
4394	    if (depthCpp == 2)
4395		depth_pattern = RADEON_SURF_TILE_DEPTH_16BPP;
4396	    else
4397		depth_pattern = RADEON_SURF_TILE_DEPTH_32BPP;
4398	} else if (IS_R300_VARIANT || IS_AVIVO_VARIANT) {
4399	    if (depthCpp == 2)
4400		depth_pattern = R300_SURF_TILE_COLOR_MACRO;
4401	    else
4402		depth_pattern = R300_SURF_TILE_COLOR_MACRO | R300_SURF_TILE_DEPTH_32BPP;
4403	} else {
4404	    if (depthCpp == 2)
4405		depth_pattern = R200_SURF_TILE_DEPTH_16BPP;
4406	    else
4407		depth_pattern = R200_SURF_TILE_DEPTH_32BPP;
4408	}
4409
4410	/* rv100 and probably the derivative igps don't have depth tiling on all the time? */
4411	if (info->dri->have3DWindows &&
4412	    (!((info->ChipFamily == CHIP_FAMILY_RV100) ||
4413	    (info->ChipFamily == CHIP_FAMILY_RS100) ||
4414	    (info->ChipFamily == CHIP_FAMILY_RS200)))) {
4415	    drm_radeon_surface_alloc_t drmsurfalloc;
4416	    drmsurfalloc.size = depthBufferSize;
4417	    drmsurfalloc.address = info->dri->depthOffset;
4418            if (IS_R300_VARIANT || IS_AVIVO_VARIANT)
4419                drmsurfalloc.flags = swap_pattern | (depth_width_bytes / 8) | depth_pattern;
4420            else
4421                drmsurfalloc.flags = swap_pattern | (depth_width_bytes / 16) | depth_pattern;
4422	    retvalue = drmCommandWrite(info->dri->drmFD, DRM_RADEON_SURF_ALLOC,
4423		&drmsurfalloc, sizeof(drmsurfalloc));
4424	    if (retvalue < 0)
4425		xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
4426		    "drm: could not allocate surface for depth buffer!\n");
4427	}
4428    }
4429    else
4430#endif
4431    {
4432	unsigned int surf_info = swap_pattern;
4433	unsigned char *RADEONMMIO = info->MMIO;
4434	/* we don't need anything like WaitForFifo, no? */
4435	if (info->tilingEnabled) {
4436	    if (IS_R300_VARIANT || IS_AVIVO_VARIANT)
4437		surf_info |= (width_bytes / 8) | color_pattern;
4438	    else
4439		surf_info |= (width_bytes / 16) | color_pattern;
4440	}
4441	OUTREG(RADEON_SURFACE0_INFO, surf_info);
4442	OUTREG(RADEON_SURFACE0_LOWER_BOUND, 0);
4443	OUTREG(RADEON_SURFACE0_UPPER_BOUND, bufferSize - 1);
4444/*	    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
4445		"surface0 set to %x, LB 0x%x UB 0x%x\n",
4446		surf_info, 0, bufferSize - 1024);*/
4447    }
4448
4449    /* Update surface images */
4450    if (info->ChipFamily < CHIP_FAMILY_R600)
4451        RADEONSaveSurfaces(pScrn, info->ModeReg);
4452}
4453
4454/* Read memory map */
4455static void RADEONSaveMemMapRegisters(ScrnInfoPtr pScrn, RADEONSavePtr save)
4456{
4457    RADEONInfoPtr  info       = RADEONPTR(pScrn);
4458    unsigned char *RADEONMMIO = info->MMIO;
4459
4460    radeon_read_mc_fb_agp_location(pScrn, LOC_FB | LOC_AGP, &save->mc_fb_location,
4461				   &save->mc_agp_location, &save->mc_agp_location_hi);
4462
4463    if (!IS_AVIVO_VARIANT) {
4464        save->display_base_addr  = INREG(RADEON_DISPLAY_BASE_ADDR);
4465        save->display2_base_addr = INREG(RADEON_DISPLAY2_BASE_ADDR);
4466        save->ov0_base_addr      = INREG(RADEON_OV0_BASE_ADDR);
4467    }
4468}
4469
4470/* Read palette data */
4471static void RADEONSavePalette(ScrnInfoPtr pScrn, RADEONSavePtr save)
4472{
4473    RADEONInfoPtr  info       = RADEONPTR(pScrn);
4474    unsigned char *RADEONMMIO = info->MMIO;
4475    int            i;
4476
4477    PAL_SELECT(1);
4478    INPAL_START(0);
4479    for (i = 0; i < 256; i++) {
4480	save->palette2[i] = INREG(RADEON_PALETTE_30_DATA);
4481    }
4482
4483    PAL_SELECT(0);
4484    INPAL_START(0);
4485    for (i = 0; i < 256; i++) {
4486	save->palette[i] = INREG(RADEON_PALETTE_30_DATA);
4487    }
4488}
4489
4490static void RADEONRestorePalette(ScrnInfoPtr pScrn, RADEONSavePtr restore)
4491{
4492    RADEONInfoPtr  info       = RADEONPTR(pScrn);
4493    unsigned char *RADEONMMIO = info->MMIO;
4494    int            i;
4495
4496    PAL_SELECT(1);
4497    OUTPAL_START(0);
4498    for (i = 0; i < 256; i++) {
4499	OUTREG(RADEON_PALETTE_30_DATA, restore->palette2[i]);
4500    }
4501
4502    PAL_SELECT(0);
4503    OUTPAL_START(0);
4504    for (i = 0; i < 256; i++) {
4505	OUTREG(RADEON_PALETTE_30_DATA, restore->palette[i]);
4506    }
4507}
4508
4509static void
4510dce4_save_grph(ScrnInfoPtr pScrn, struct dce4_main_block_state *state,
4511	       uint32_t offset)
4512{
4513    RADEONInfoPtr info = RADEONPTR(pScrn);
4514    unsigned char *RADEONMMIO = info->MMIO;
4515
4516    state->grph.enable = INREG(offset + EVERGREEN_GRPH_ENABLE);
4517    state->grph.control = INREG(offset + EVERGREEN_GRPH_CONTROL);
4518    state->grph.swap_control = INREG(offset + EVERGREEN_GRPH_SWAP_CONTROL);
4519    state->grph.prim_surf_addr = INREG(offset + EVERGREEN_GRPH_PRIMARY_SURFACE_ADDRESS);
4520    state->grph.sec_surf_addr = INREG(offset + EVERGREEN_GRPH_SECONDARY_SURFACE_ADDRESS);
4521    state->grph.pitch = INREG(offset + EVERGREEN_GRPH_PITCH);
4522    state->grph.prim_surf_addr_hi = INREG(offset + EVERGREEN_GRPH_PRIMARY_SURFACE_ADDRESS_HIGH);
4523    state->grph.sec_surf_addr_hi = INREG(offset + EVERGREEN_GRPH_SECONDARY_SURFACE_ADDRESS_HIGH);
4524    state->grph.x_offset = INREG(offset + EVERGREEN_GRPH_SURFACE_OFFSET_X);
4525    state->grph.y_offset = INREG(offset + EVERGREEN_GRPH_SURFACE_OFFSET_Y);
4526    state->grph.x_start = INREG(offset + EVERGREEN_GRPH_X_START);
4527    state->grph.y_start = INREG(offset + EVERGREEN_GRPH_Y_START);
4528    state->grph.x_end = INREG(offset + EVERGREEN_GRPH_X_END);
4529    state->grph.y_end = INREG(offset + EVERGREEN_GRPH_Y_END);
4530
4531    state->grph.desktop_height = INREG(offset + EVERGREEN_DESKTOP_HEIGHT);
4532    state->grph.viewport_start = INREG(offset + EVERGREEN_VIEWPORT_START);
4533    state->grph.viewport_size = INREG(offset + EVERGREEN_VIEWPORT_SIZE);
4534    state->grph.mode_data_format = INREG(offset + EVERGREEN_DATA_FORMAT);
4535}
4536
4537static void
4538dce4_restore_grph(ScrnInfoPtr pScrn, struct dce4_main_block_state *state,
4539	       uint32_t offset)
4540{
4541    RADEONInfoPtr info = RADEONPTR(pScrn);
4542    unsigned char *RADEONMMIO = info->MMIO;
4543
4544    OUTREG(offset + EVERGREEN_GRPH_ENABLE, state->grph.enable);
4545    OUTREG(offset + EVERGREEN_GRPH_CONTROL, state->grph.control);
4546    OUTREG(offset + EVERGREEN_GRPH_SWAP_CONTROL, state->grph.swap_control);
4547    OUTREG(offset + EVERGREEN_GRPH_PRIMARY_SURFACE_ADDRESS, state->grph.prim_surf_addr);
4548    OUTREG(offset + EVERGREEN_GRPH_SECONDARY_SURFACE_ADDRESS, state->grph.sec_surf_addr);
4549    OUTREG(offset + EVERGREEN_GRPH_PITCH, state->grph.pitch);
4550    OUTREG(offset + EVERGREEN_GRPH_PRIMARY_SURFACE_ADDRESS_HIGH, state->grph.prim_surf_addr_hi);
4551    OUTREG(offset + EVERGREEN_GRPH_SECONDARY_SURFACE_ADDRESS_HIGH, state->grph.sec_surf_addr_hi);
4552    OUTREG(offset + EVERGREEN_GRPH_SURFACE_OFFSET_X, state->grph.x_offset);
4553    OUTREG(offset + EVERGREEN_GRPH_SURFACE_OFFSET_Y, state->grph.y_offset);
4554    OUTREG(offset + EVERGREEN_GRPH_X_START, state->grph.x_start);
4555    OUTREG(offset + EVERGREEN_GRPH_Y_START, state->grph.y_start);
4556    OUTREG(offset + EVERGREEN_GRPH_X_END, state->grph.x_end);
4557    OUTREG(offset + EVERGREEN_GRPH_Y_END, state->grph.y_end);
4558
4559    OUTREG(offset + EVERGREEN_DESKTOP_HEIGHT, state->grph.desktop_height);
4560    OUTREG(offset + EVERGREEN_VIEWPORT_START, state->grph.viewport_start);
4561    OUTREG(offset + EVERGREEN_VIEWPORT_SIZE, state->grph.viewport_size);
4562    OUTREG(offset + EVERGREEN_DATA_FORMAT, state->grph.mode_data_format);
4563}
4564
4565static uint32_t dce4_dac_regs[] = {
4566    0x6690, 0x6694, 0x66b0, 0x66cc, 0x66d0, 0x66d4, 0x66d8 };
4567
4568static uint32_t dce4_scl_regs[] = {
4569    0x6d08, 0x6d0c, 0x6d14, 0x6d1c };
4570
4571static uint32_t dce4_dig_regs[] = {
4572    0x7000, 0x7004, 0x7008, 0x700c, 0x7010, 0x7014,
4573    0x71f0, 0x71f4, 0x71f8, 0x71fc, 0x7200, 0x7204,
4574    0x7208, 0x720c, 0x7210, 0x7218, 0x721c, 0x7220,
4575    0x7230};
4576
4577static uint32_t dce4_crtc_regs[] = {
4578    0x6e00, 0x6e04, 0x6e08, 0x6e0c, 0x6e1c, 0x6e34, 0x6e38, 0x6e3c, 0x6e70, 0x6e74, 0x6e78};
4579
4580
4581#define DCE4_REG_SCL_NUM (sizeof(dce4_scl_regs)/sizeof(uint32_t))
4582#define DCE4_REG_CRTC_NUM (sizeof(dce4_crtc_regs)/sizeof(uint32_t))
4583#define DCE4_REG_DIG_NUM (sizeof(dce4_dig_regs)/sizeof(uint32_t))
4584#define DCE4_DAC_NUM (sizeof(dce4_dac_regs)/sizeof(uint32_t))
4585
4586
4587static void
4588dce4_save_crtc(ScrnInfoPtr pScrn, struct dce4_main_block_state *state,
4589	       uint32_t offset)
4590{
4591    RADEONInfoPtr info = RADEONPTR(pScrn);
4592    unsigned char *RADEONMMIO = info->MMIO;
4593    int i;
4594
4595    for (i = 0; i < DCE4_REG_CRTC_NUM; i++)
4596        state->crtc[i] = INREG(offset + dce4_crtc_regs[i]);
4597}
4598
4599static void
4600dce4_restore_crtc(ScrnInfoPtr pScrn, struct dce4_main_block_state *state,
4601		  uint32_t offset)
4602{
4603    RADEONInfoPtr info = RADEONPTR(pScrn);
4604    unsigned char *RADEONMMIO = info->MMIO;
4605    int i;
4606
4607    for (i = 0; i < DCE4_REG_CRTC_NUM; i++)
4608        OUTREG(offset + dce4_crtc_regs[i], state->crtc[i]);
4609}
4610
4611static void
4612dce4_save_scl(ScrnInfoPtr pScrn, struct dce4_main_block_state *state,
4613	      uint32_t offset)
4614{
4615    RADEONInfoPtr info = RADEONPTR(pScrn);
4616    unsigned char *RADEONMMIO = info->MMIO;
4617    int i;
4618
4619    for (i = 0; i < DCE4_REG_SCL_NUM; i++)
4620        state->scl[i] = INREG(offset + dce4_scl_regs[i]);
4621}
4622
4623static void
4624dce4_restore_scl(ScrnInfoPtr pScrn, struct dce4_main_block_state *state,
4625	      uint32_t offset)
4626{
4627    RADEONInfoPtr info = RADEONPTR(pScrn);
4628    unsigned char *RADEONMMIO = info->MMIO;
4629    int i;
4630
4631    for (i = 0; i < DCE4_REG_SCL_NUM; i++)
4632        OUTREG(offset + dce4_scl_regs[i], state->scl[i]);
4633}
4634
4635
4636static void
4637dce4_save_fmt(ScrnInfoPtr pScrn, struct dce4_main_block_state *state,
4638	      uint32_t offset)
4639{
4640    RADEONInfoPtr info = RADEONPTR(pScrn);
4641    unsigned char *RADEONMMIO = info->MMIO;
4642    int i, index = 0;
4643
4644    for (i = 0x6fb4; i <= 0x6fd4; i += 4)
4645	state->fmt[index++] = INREG(offset + i);
4646}
4647
4648static void
4649dce4_restore_fmt(ScrnInfoPtr pScrn, struct dce4_main_block_state *state,
4650	      uint32_t offset)
4651{
4652    RADEONInfoPtr info = RADEONPTR(pScrn);
4653    unsigned char *RADEONMMIO = info->MMIO;
4654    int i, index = 0;
4655
4656    for (i = 0x6fb4; i <= 0x6fd4; i += 4)
4657	OUTREG(offset + i, state->fmt[index++]);
4658}
4659
4660
4661static void
4662dce4_save_dig(ScrnInfoPtr pScrn, struct dce4_main_block_state *state,
4663	      uint32_t offset)
4664{
4665    RADEONInfoPtr info = RADEONPTR(pScrn);
4666    unsigned char *RADEONMMIO = info->MMIO;
4667    int i;
4668
4669    for (i = 0; i < DCE4_REG_DIG_NUM; i++)
4670        state->dig[i] = INREG(offset + dce4_dig_regs[i]);
4671}
4672
4673static void
4674dce4_restore_dig(ScrnInfoPtr pScrn, struct dce4_main_block_state *state,
4675	      uint32_t offset)
4676{
4677    RADEONInfoPtr info = RADEONPTR(pScrn);
4678    unsigned char *RADEONMMIO = info->MMIO;
4679    int i;
4680
4681    for (i = 0; i < DCE4_REG_DIG_NUM; i++)
4682        OUTREG(offset + dce4_dig_regs[i], state->dig[i]);
4683}
4684
4685
4686
4687static void dce4_save_block(ScrnInfoPtr pScrn, struct dce4_main_block_state *state,
4688			    uint32_t offset)
4689{
4690    dce4_save_grph(pScrn, state, offset);
4691    dce4_save_crtc(pScrn, state, offset);
4692    dce4_save_scl(pScrn, state, offset);
4693    dce4_save_dig(pScrn, state, offset);
4694    dce4_save_fmt(pScrn, state, offset);
4695}
4696
4697static void dce4_restore_block(ScrnInfoPtr pScrn, struct dce4_main_block_state *state,
4698			       uint32_t offset)
4699{
4700    dce4_restore_grph(pScrn, state, offset);
4701    dce4_restore_crtc(pScrn, state, offset);
4702    dce4_restore_scl(pScrn, state, offset);
4703    dce4_restore_dig(pScrn, state, offset);
4704    dce4_restore_fmt(pScrn, state, offset);
4705}
4706
4707static void dce4_save_uniphy(ScrnInfoPtr pScrn, struct dce4_state *state, int index)
4708{
4709    RADEONInfoPtr info = RADEONPTR(pScrn);
4710    unsigned char *RADEONMMIO = info->MMIO;
4711    uint32_t uniphy_offset[6] = {0x0, 0x30, 0x60, 0x100, 0x130, 0x160 };
4712    int i, ri = 0;
4713    for (i = 0; i < 0x18; i+=4)
4714	state->uniphy[index][ri++] = INREG(0x6600 + uniphy_offset[index] + i);
4715}
4716
4717static void dce4_restore_uniphy(ScrnInfoPtr pScrn, struct dce4_state *state, int index)
4718{
4719    RADEONInfoPtr info = RADEONPTR(pScrn);
4720    unsigned char *RADEONMMIO = info->MMIO;
4721    uint32_t uniphy_offset[6] = {0x0, 0x30, 0x60, 0x100, 0x130, 0x160 };
4722    int i, ri = 0;
4723    for (i = 0; i <= 0x18; i+=4)
4724	OUTREG(0x6600 + uniphy_offset[index] + i, state->uniphy[index][ri++]);
4725}
4726
4727static void dce4_save_dig_regs(ScrnInfoPtr pScrn, struct dce4_state *state)
4728{
4729    RADEONInfoPtr info = RADEONPTR(pScrn);
4730    unsigned char *RADEONMMIO = info->MMIO;
4731    int i, ri = 0;
4732
4733    for (i = 0x6578; i <= 0x6598; i += 4)
4734	state->dig[ri++] = INREG(i);
4735    for (i = 0x65ac; i <= 0x65d8; i += 4)
4736	state->dig[ri++] = INREG(i);
4737}
4738
4739static void dce4_restore_dig_regs(ScrnInfoPtr pScrn, struct dce4_state *state)
4740{
4741    RADEONInfoPtr info = RADEONPTR(pScrn);
4742    unsigned char *RADEONMMIO = info->MMIO;
4743    int i, ri = 0;
4744
4745    for (i = 0x6578; i <= 0x6598; i += 4)
4746	OUTREG(i, state->dig[ri++]);
4747    for (i = 0x65ac; i <= 0x65d8; i += 4)
4748	OUTREG(i, state->dig[ri++]);
4749}
4750
4751static void dce4_save_pll_regs(ScrnInfoPtr pScrn, struct dce4_state *state)
4752{
4753    RADEONInfoPtr info = RADEONPTR(pScrn);
4754    unsigned char *RADEONMMIO = info->MMIO;
4755    int i, ri = 0;
4756
4757    for (i = 0x360; i <= 0x368; i += 4)
4758	state->vga_pll[0][ri++] = INREG(i);
4759
4760    ri = 0;
4761    for (i = 0x370; i <= 0x378; i += 4)
4762	state->vga_pll[1][ri++] = INREG(i);
4763
4764    ri = 0;
4765    for (i = 0x390; i <= 0x398; i += 4)
4766	state->vga_pll[2][ri++] = INREG(i);
4767
4768    ri = 0;
4769    for (i = 0x400; i <= 0x408; i += 4)
4770	state->pll[0][ri++] = INREG(i);
4771    for (i = 0x410; i <= 0x43c; i += 4)
4772	state->pll[0][ri++] = INREG(i);
4773
4774    ri = 0;
4775    for (i = 0x440; i <= 0x448; i += 4)
4776	state->pll[1][ri++] = INREG(i);
4777    for (i = 0x450; i <= 0x47c; i += 4)
4778	state->pll[1][ri++] = INREG(i);
4779
4780    ri = 0;
4781    for (i = 0x500; i <= 0x550; i += 0x10)
4782	state->pll_route[ri++] = INREG(i);
4783}
4784
4785static void dce4_restore_pll_regs(ScrnInfoPtr pScrn, struct dce4_state *state)
4786{
4787    RADEONInfoPtr info = RADEONPTR(pScrn);
4788    unsigned char *RADEONMMIO = info->MMIO;
4789    int i, ri = 0;
4790
4791    for (i = 0x360; i <= 0x368; i += 4)
4792	OUTREG(i, state->vga_pll[0][ri++]);
4793
4794    ri = 0;
4795    for (i = 0x370; i <= 0x378; i += 4)
4796	OUTREG(i, state->vga_pll[1][ri++]);
4797
4798    ri = 0;
4799    for (i = 0x390; i <= 0x398; i += 4)
4800	OUTREG(i, state->vga_pll[2][ri++]);
4801
4802    ri = 0;
4803    for (i = 0x400; i <= 0x408; i += 4)
4804	OUTREG(i, state->pll[0][ri++]);
4805    for (i = 0x410; i <= 0x43c; i += 4)
4806	OUTREG(i, state->pll[0][ri++]);
4807
4808    ri = 0;
4809    for (i = 0x440; i <= 0x448; i += 4)
4810	OUTREG(i, state->pll[1][ri++]);
4811    for (i = 0x450; i <= 0x47c; i += 4)
4812	OUTREG(i, state->pll[1][ri++]);
4813
4814    ri = 0;
4815    for (i = 0x500; i <= 0x550; i += 0x10)
4816	OUTREG(i, state->pll_route[ri++]);
4817}
4818
4819static void
4820dce4_save(ScrnInfoPtr pScrn, RADEONSavePtr save)
4821{
4822    RADEONInfoPtr info = RADEONPTR(pScrn);
4823    unsigned char *RADEONMMIO = info->MMIO;
4824    struct dce4_state *state = &save->dce4;
4825    int i, j;
4826    uint32_t crtc_offset[] = {EVERGREEN_CRTC0_REGISTER_OFFSET,
4827			      EVERGREEN_CRTC1_REGISTER_OFFSET,
4828			      EVERGREEN_CRTC2_REGISTER_OFFSET,
4829			      EVERGREEN_CRTC3_REGISTER_OFFSET,
4830			      EVERGREEN_CRTC4_REGISTER_OFFSET,
4831			      EVERGREEN_CRTC5_REGISTER_OFFSET};
4832
4833    state->vga1_cntl = INREG(AVIVO_D1VGA_CONTROL);
4834    state->vga2_cntl = INREG(AVIVO_D2VGA_CONTROL);
4835    state->vga3_cntl = INREG(EVERGREEN_D3VGA_CONTROL);
4836    state->vga4_cntl = INREG(EVERGREEN_D4VGA_CONTROL);
4837    state->vga5_cntl = INREG(EVERGREEN_D5VGA_CONTROL);
4838    state->vga6_cntl = INREG(EVERGREEN_D6VGA_CONTROL);
4839    state->vga_render_control = INREG(AVIVO_VGA_RENDER_CONTROL);
4840
4841    dce4_save_pll_regs(pScrn, state);
4842    dce4_save_dig_regs(pScrn, state);
4843
4844    for (i = 0; i < 6; i++)
4845	dce4_save_block(pScrn, &state->block[i], crtc_offset[i]);
4846
4847    for (i = 0; i < 6; i++)
4848	dce4_save_uniphy(pScrn, state, i);
4849
4850    for (i = 0; i < 2; i++) {
4851	for (j = 0; j < DCE4_DAC_NUM; j++) {
4852	    uint32_t offset = i ? 0x100 : 0x0;
4853	    state->dac[i][j] = INREG(dce4_dac_regs[j] + offset);
4854	}
4855    }
4856}
4857
4858static void
4859dce4_restore(ScrnInfoPtr pScrn, RADEONSavePtr restore)
4860{
4861    RADEONInfoPtr info = RADEONPTR(pScrn);
4862    unsigned char *RADEONMMIO = info->MMIO;
4863    struct dce4_state *state = &restore->dce4;
4864    int i, j;
4865    uint32_t crtc_offset[] = {EVERGREEN_CRTC0_REGISTER_OFFSET,
4866			      EVERGREEN_CRTC1_REGISTER_OFFSET,
4867			      EVERGREEN_CRTC2_REGISTER_OFFSET,
4868			      EVERGREEN_CRTC3_REGISTER_OFFSET,
4869			      EVERGREEN_CRTC4_REGISTER_OFFSET,
4870			      EVERGREEN_CRTC5_REGISTER_OFFSET};
4871
4872    OUTREG(AVIVO_D1VGA_CONTROL, state->vga1_cntl);
4873    OUTREG(AVIVO_D2VGA_CONTROL, state->vga2_cntl);;
4874    OUTREG(EVERGREEN_D3VGA_CONTROL, state->vga3_cntl);
4875    OUTREG(EVERGREEN_D4VGA_CONTROL, state->vga4_cntl);
4876    OUTREG(EVERGREEN_D5VGA_CONTROL, state->vga5_cntl);
4877    OUTREG(EVERGREEN_D6VGA_CONTROL, state->vga6_cntl);
4878    OUTREG(AVIVO_VGA_RENDER_CONTROL, state->vga_render_control);
4879
4880    dce4_restore_dig_regs(pScrn, state);
4881    dce4_restore_pll_regs(pScrn, state);
4882    for (i = 0; i < 6; i++)
4883	dce4_restore_uniphy(pScrn, state, i);
4884
4885    for (i = 0; i < 6; i++)
4886	dce4_restore_block(pScrn, &state->block[i], crtc_offset[i]);
4887
4888    for (i = 0; i < 2; i++) {
4889	for (j = 0; j < DCE4_DAC_NUM; j++) {
4890	    uint32_t offset = i ? 0x100 : 0x0;
4891	    OUTREG(dce4_dac_regs[j] + offset, state->dac[i][j]);
4892	}
4893    }
4894}
4895
4896static void
4897avivo_save(ScrnInfoPtr pScrn, RADEONSavePtr save)
4898{
4899    RADEONInfoPtr info = RADEONPTR(pScrn);
4900    unsigned char *RADEONMMIO = info->MMIO;
4901    struct avivo_state *state = &save->avivo;
4902    int i, j;
4903
4904    //    state->vga_memory_base = INREG(AVIVO_VGA_MEMORY_BASE);
4905    //    state->vga_fb_start = INREG(AVIVO_VGA_FB_START);
4906    state->vga1_cntl = INREG(AVIVO_D1VGA_CONTROL);
4907    state->vga2_cntl = INREG(AVIVO_D2VGA_CONTROL);
4908    state->vga_render_control = INREG(AVIVO_VGA_RENDER_CONTROL);
4909
4910    state->crtc_master_en = INREG(AVIVO_DC_CRTC_MASTER_EN);
4911    state->crtc_tv_control = INREG(AVIVO_DC_CRTC_TV_CONTROL);
4912    state->dc_lb_memory_split = INREG(AVIVO_DC_LB_MEMORY_SPLIT);
4913
4914    state->pll[0].ref_div_src = INREG(AVIVO_EXT1_PPLL_REF_DIV_SRC);
4915    state->pll[0].ref_div = INREG(AVIVO_EXT1_PPLL_REF_DIV);
4916    state->pll[0].fb_div = INREG(AVIVO_EXT1_PPLL_FB_DIV);
4917    state->pll[0].post_div_src = INREG(AVIVO_EXT1_PPLL_POST_DIV_SRC);
4918    state->pll[0].post_div = INREG(AVIVO_EXT1_PPLL_POST_DIV);
4919    state->pll[0].ext_ppll_cntl = INREG(AVIVO_EXT1_PPLL_CNTL);
4920    state->pll[0].pll_cntl = INREG(AVIVO_P1PLL_CNTL);
4921    state->pll[0].int_ss_cntl = INREG(AVIVO_P1PLL_INT_SS_CNTL);
4922
4923    state->pll[1].ref_div_src = INREG(AVIVO_EXT1_PPLL_REF_DIV_SRC);
4924    state->pll[1].ref_div = INREG(AVIVO_EXT2_PPLL_REF_DIV);
4925    state->pll[1].fb_div = INREG(AVIVO_EXT2_PPLL_FB_DIV);
4926    state->pll[1].post_div_src = INREG(AVIVO_EXT2_PPLL_POST_DIV_SRC);
4927    state->pll[1].post_div = INREG(AVIVO_EXT2_PPLL_POST_DIV);
4928    state->pll[1].ext_ppll_cntl = INREG(AVIVO_EXT2_PPLL_CNTL);
4929    state->pll[1].pll_cntl = INREG(AVIVO_P2PLL_CNTL);
4930    state->pll[1].int_ss_cntl = INREG(AVIVO_P2PLL_INT_SS_CNTL);
4931
4932    state->vga25_ppll.ref_div_src = INREG(AVIVO_VGA25_PPLL_REF_DIV_SRC);
4933    state->vga25_ppll.ref_div = INREG(AVIVO_VGA25_PPLL_REF_DIV);
4934    state->vga25_ppll.fb_div = INREG(AVIVO_VGA25_PPLL_FB_DIV);
4935    state->vga25_ppll.post_div_src = INREG(AVIVO_VGA25_PPLL_POST_DIV_SRC);
4936    state->vga25_ppll.post_div = INREG(AVIVO_VGA25_PPLL_POST_DIV);
4937    state->vga25_ppll.pll_cntl = INREG(AVIVO_VGA25_PPLL_CNTL);
4938
4939    state->vga28_ppll.ref_div_src = INREG(AVIVO_VGA28_PPLL_REF_DIV_SRC);
4940    state->vga28_ppll.ref_div = INREG(AVIVO_VGA28_PPLL_REF_DIV);
4941    state->vga28_ppll.fb_div = INREG(AVIVO_VGA28_PPLL_FB_DIV);
4942    state->vga28_ppll.post_div_src = INREG(AVIVO_VGA28_PPLL_POST_DIV_SRC);
4943    state->vga28_ppll.post_div = INREG(AVIVO_VGA28_PPLL_POST_DIV);
4944    state->vga28_ppll.pll_cntl = INREG(AVIVO_VGA28_PPLL_CNTL);
4945
4946    state->vga41_ppll.ref_div_src = INREG(AVIVO_VGA41_PPLL_REF_DIV_SRC);
4947    state->vga41_ppll.ref_div = INREG(AVIVO_VGA41_PPLL_REF_DIV);
4948    state->vga41_ppll.fb_div = INREG(AVIVO_VGA41_PPLL_FB_DIV);
4949    state->vga41_ppll.post_div_src = INREG(AVIVO_VGA41_PPLL_POST_DIV_SRC);
4950    state->vga41_ppll.post_div = INREG(AVIVO_VGA41_PPLL_POST_DIV);
4951    state->vga41_ppll.pll_cntl = INREG(AVIVO_VGA41_PPLL_CNTL);
4952
4953    state->crtc[0].pll_source = INREG(AVIVO_PCLK_CRTC1_CNTL);
4954
4955    state->crtc[0].h_total = INREG(AVIVO_D1CRTC_H_TOTAL);
4956    state->crtc[0].h_blank_start_end = INREG(AVIVO_D1CRTC_H_BLANK_START_END);
4957    state->crtc[0].h_sync_a = INREG(AVIVO_D1CRTC_H_SYNC_A);
4958    state->crtc[0].h_sync_a_cntl = INREG(AVIVO_D1CRTC_H_SYNC_A_CNTL);
4959    state->crtc[0].h_sync_b = INREG(AVIVO_D1CRTC_H_SYNC_B);
4960    state->crtc[0].h_sync_b_cntl = INREG(AVIVO_D1CRTC_H_SYNC_B_CNTL);
4961
4962    state->crtc[0].v_total = INREG(AVIVO_D1CRTC_V_TOTAL);
4963    state->crtc[0].v_blank_start_end = INREG(AVIVO_D1CRTC_V_BLANK_START_END);
4964    state->crtc[0].v_sync_a = INREG(AVIVO_D1CRTC_V_SYNC_A);
4965    state->crtc[0].v_sync_a_cntl = INREG(AVIVO_D1CRTC_V_SYNC_A_CNTL);
4966    state->crtc[0].v_sync_b = INREG(AVIVO_D1CRTC_V_SYNC_B);
4967    state->crtc[0].v_sync_b_cntl = INREG(AVIVO_D1CRTC_V_SYNC_B_CNTL);
4968
4969    state->crtc[0].control = INREG(AVIVO_D1CRTC_CONTROL);
4970    state->crtc[0].blank_control = INREG(AVIVO_D1CRTC_BLANK_CONTROL);
4971    state->crtc[0].interlace_control = INREG(AVIVO_D1CRTC_INTERLACE_CONTROL);
4972    state->crtc[0].stereo_control = INREG(AVIVO_D1CRTC_STEREO_CONTROL);
4973
4974    state->crtc[0].cursor_control = INREG(AVIVO_D1CUR_CONTROL);
4975
4976    state->grph[0].enable = INREG(AVIVO_D1GRPH_ENABLE);
4977    state->grph[0].control = INREG(AVIVO_D1GRPH_CONTROL);
4978    state->grph[0].control = INREG(AVIVO_D1GRPH_CONTROL);
4979    state->grph[0].prim_surf_addr = INREG(AVIVO_D1GRPH_PRIMARY_SURFACE_ADDRESS);
4980    state->grph[0].sec_surf_addr = INREG(AVIVO_D1GRPH_SECONDARY_SURFACE_ADDRESS);
4981    state->grph[0].pitch = INREG(AVIVO_D1GRPH_PITCH);
4982    state->grph[0].x_offset = INREG(AVIVO_D1GRPH_SURFACE_OFFSET_X);
4983    state->grph[0].y_offset = INREG(AVIVO_D1GRPH_SURFACE_OFFSET_Y);
4984    state->grph[0].x_start = INREG(AVIVO_D1GRPH_X_START);
4985    state->grph[0].y_start = INREG(AVIVO_D1GRPH_Y_START);
4986    state->grph[0].x_end = INREG(AVIVO_D1GRPH_X_END);
4987    state->grph[0].y_end = INREG(AVIVO_D1GRPH_Y_END);
4988
4989    state->grph[0].desktop_height = INREG(AVIVO_D1MODE_DESKTOP_HEIGHT);
4990    state->grph[0].viewport_start = INREG(AVIVO_D1MODE_VIEWPORT_START);
4991    state->grph[0].viewport_size = INREG(AVIVO_D1MODE_VIEWPORT_SIZE);
4992    state->grph[0].mode_data_format = INREG(AVIVO_D1MODE_DATA_FORMAT);
4993
4994    state->crtc[1].pll_source = INREG(AVIVO_PCLK_CRTC2_CNTL);
4995
4996    state->crtc[1].h_total = INREG(AVIVO_D2CRTC_H_TOTAL);
4997    state->crtc[1].h_blank_start_end = INREG(AVIVO_D2CRTC_H_BLANK_START_END);
4998    state->crtc[1].h_sync_a = INREG(AVIVO_D2CRTC_H_SYNC_A);
4999    state->crtc[1].h_sync_a_cntl = INREG(AVIVO_D2CRTC_H_SYNC_A_CNTL);
5000    state->crtc[1].h_sync_b = INREG(AVIVO_D2CRTC_H_SYNC_B);
5001    state->crtc[1].h_sync_b_cntl = INREG(AVIVO_D2CRTC_H_SYNC_B_CNTL);
5002
5003    state->crtc[1].v_total = INREG(AVIVO_D2CRTC_V_TOTAL);
5004    state->crtc[1].v_blank_start_end = INREG(AVIVO_D2CRTC_V_BLANK_START_END);
5005    state->crtc[1].v_sync_a = INREG(AVIVO_D2CRTC_V_SYNC_A);
5006    state->crtc[1].v_sync_a_cntl = INREG(AVIVO_D2CRTC_V_SYNC_A_CNTL);
5007    state->crtc[1].v_sync_b = INREG(AVIVO_D2CRTC_V_SYNC_B);
5008    state->crtc[1].v_sync_b_cntl = INREG(AVIVO_D2CRTC_V_SYNC_B_CNTL);
5009
5010    state->crtc[1].control = INREG(AVIVO_D2CRTC_CONTROL);
5011    state->crtc[1].blank_control = INREG(AVIVO_D2CRTC_BLANK_CONTROL);
5012    state->crtc[1].interlace_control = INREG(AVIVO_D2CRTC_INTERLACE_CONTROL);
5013    state->crtc[1].stereo_control = INREG(AVIVO_D2CRTC_STEREO_CONTROL);
5014
5015    state->crtc[1].cursor_control = INREG(AVIVO_D2CUR_CONTROL);
5016
5017    state->grph[1].enable = INREG(AVIVO_D2GRPH_ENABLE);
5018    state->grph[1].control = INREG(AVIVO_D2GRPH_CONTROL);
5019    state->grph[1].control = INREG(AVIVO_D2GRPH_CONTROL);
5020    state->grph[1].prim_surf_addr = INREG(AVIVO_D2GRPH_PRIMARY_SURFACE_ADDRESS);
5021    state->grph[1].sec_surf_addr = INREG(AVIVO_D2GRPH_SECONDARY_SURFACE_ADDRESS);
5022    state->grph[1].pitch = INREG(AVIVO_D2GRPH_PITCH);
5023    state->grph[1].x_offset = INREG(AVIVO_D2GRPH_SURFACE_OFFSET_X);
5024    state->grph[1].y_offset = INREG(AVIVO_D2GRPH_SURFACE_OFFSET_Y);
5025    state->grph[1].x_start = INREG(AVIVO_D2GRPH_X_START);
5026    state->grph[1].y_start = INREG(AVIVO_D2GRPH_Y_START);
5027    state->grph[1].x_end = INREG(AVIVO_D2GRPH_X_END);
5028    state->grph[1].y_end = INREG(AVIVO_D2GRPH_Y_END);
5029
5030    state->grph[1].desktop_height = INREG(AVIVO_D2MODE_DESKTOP_HEIGHT);
5031    state->grph[1].viewport_start = INREG(AVIVO_D2MODE_VIEWPORT_START);
5032    state->grph[1].viewport_size = INREG(AVIVO_D2MODE_VIEWPORT_SIZE);
5033    state->grph[1].mode_data_format = INREG(AVIVO_D2MODE_DATA_FORMAT);
5034
5035    if (IS_DCE3_VARIANT) {
5036	/* save DVOA regs */
5037	state->dvoa[0] = INREG(0x7080);
5038	state->dvoa[1] = INREG(0x7084);
5039	state->dvoa[2] = INREG(0x708c);
5040	state->dvoa[3] = INREG(0x7090);
5041	state->dvoa[4] = INREG(0x7094);
5042	state->dvoa[5] = INREG(0x70ac);
5043	state->dvoa[6] = INREG(0x70b0);
5044
5045	j = 0;
5046	/* save DAC regs */
5047	for (i = 0x7000; i <= 0x7040; i += 4) {
5048	    state->daca[j] = INREG(i);
5049	    state->dacb[j] = INREG(i + 0x100);
5050	    j++;
5051	}
5052	for (i = 0x7058; i <= 0x7060; i += 4) {
5053	    state->daca[j] = INREG(i);
5054	    state->dacb[j] = INREG(i + 0x100);
5055	    j++;
5056	}
5057	for (i = 0x7068; i <= 0x706c; i += 4) {
5058	    state->daca[j] = INREG(i);
5059	    state->dacb[j] = INREG(i + 0x100);
5060	    j++;
5061	}
5062	for (i = 0x7ef0; i <= 0x7ef8; i += 4) {
5063	    state->daca[j] = INREG(i);
5064	    state->dacb[j] = INREG(i + 0x100);
5065	    j++;
5066	}
5067	state->daca[j] = INREG(0x7050);
5068	state->dacb[j] = INREG(0x7050 + 0x100);
5069
5070	j = 0;
5071	/* save FMT regs */
5072	for (i = 0x6700; i <= 0x6744; i += 4) {
5073	    state->fmt1[j] = INREG(i);
5074	    state->fmt2[j] = INREG(i + 0x800);
5075	    j++;
5076	}
5077
5078	j = 0;
5079	/* save DIG regs */
5080	for (i = 0x75a0; i <= 0x75e0; i += 4) {
5081	    state->dig1[j] = INREG(i);
5082	    state->dig2[j] = INREG(i + 0x400);
5083	    j++;
5084	}
5085	for (i = 0x75e8; i <= 0x75ec; i += 4) {
5086	    state->dig1[j] = INREG(i);
5087	    state->dig2[j] = INREG(i + 0x400);
5088	    j++;
5089	}
5090
5091	j = 0;
5092	/* save HDMI regs */
5093	for (i = 0x7400; i <= 0x741c; i += 4) {
5094	    state->hdmi1[j] = INREG(i);
5095	    state->hdmi2[j] = INREG(i + 0x400);
5096	    j++;
5097	}
5098	for (i = 0x7430; i <= 0x74ec; i += 4) {
5099	    state->hdmi1[j] = INREG(i);
5100	    state->hdmi2[j] = INREG(i + 0x400);
5101	    j++;
5102	}
5103	state->hdmi1[j] = INREG(0x7428);
5104	state->hdmi2[j] = INREG(0x7828);
5105
5106	j = 0;
5107	/* save AUX regs */
5108	for (i = 0x7780; i <= 0x77b4; i += 4) {
5109	    state->aux_cntl1[j] = INREG(i);
5110	    state->aux_cntl2[j] = INREG(i + 0x040);
5111	    state->aux_cntl3[j] = INREG(i + 0x400);
5112	    state->aux_cntl4[j] = INREG(i + 0x440);
5113	    if (IS_DCE32_VARIANT) {
5114		state->aux_cntl5[j] = INREG(i + 0x500);
5115		state->aux_cntl6[j] = INREG(i + 0x540);
5116	    }
5117	    j++;
5118	}
5119
5120	j = 0;
5121	/* save UNIPHY regs */
5122	if (IS_DCE32_VARIANT) {
5123	    for (i = 0x7680; i <= 0x7690; i += 4) {
5124		state->uniphy1[j] = INREG(i);
5125		state->uniphy2[j] = INREG(i + 0x20);
5126		state->uniphy3[j] = INREG(i + 0x400);
5127		state->uniphy4[j] = INREG(i + 0x420);
5128		state->uniphy5[j] = INREG(i + 0x840);
5129		state->uniphy6[j] = INREG(i + 0x940);
5130		j++;
5131	    }
5132	    for (i = 0x7698; i <= 0x769c; i += 4) {
5133		state->uniphy1[j] = INREG(i);
5134		state->uniphy2[j] = INREG(i + 0x20);
5135		state->uniphy3[j] = INREG(i + 0x400);
5136		state->uniphy4[j] = INREG(i + 0x420);
5137		state->uniphy5[j] = INREG(i + 0x840);
5138		state->uniphy6[j] = INREG(i + 0x940);
5139		j++;
5140	    }
5141	} else {
5142	    for (i = 0x7ec0; i <= 0x7edc; i += 4) {
5143		state->uniphy1[j] = INREG(i);
5144		state->uniphy2[j] = INREG(i + 0x100);
5145		j++;
5146	    }
5147	}
5148	j = 0;
5149	/* save PHY,LINK regs */
5150	for (i = 0x7f20; i <= 0x7f34; i += 4) {
5151	    state->phy[j] = INREG(i);
5152	    j++;
5153	}
5154	for (i = 0x7f9c; i <= 0x7fa4; i += 4) {
5155	    state->phy[j] = INREG(i);
5156	    j++;
5157	}
5158	state->phy[j] = INREG(0x7f40);
5159
5160	j = 0;
5161	/* save LVTMA regs */
5162	for (i = 0x7f00; i <= 0x7f1c; i += 4) {
5163	    state->lvtma[j] = INREG(i);
5164	    j++;
5165	}
5166	for (i = 0x7f80; i <= 0x7f98; i += 4) {
5167	    state->lvtma[j] = INREG(i);
5168	    j++;
5169	}
5170    } else {
5171	j = 0;
5172	/* save DVOA regs */
5173	for (i = 0x7980; i <= 0x79bc; i += 4) {
5174	    state->dvoa[j] = INREG(i);
5175	    j++;
5176	}
5177
5178	j = 0;
5179	/* save DAC regs */
5180	for (i = 0x7800; i <= 0x782c; i += 4) {
5181	    state->daca[j] = INREG(i);
5182	    state->dacb[j] = INREG(i + 0x200);
5183	    j++;
5184	}
5185	for (i = 0x7834; i <= 0x7840; i += 4) {
5186	    state->daca[j] = INREG(i);
5187	    state->dacb[j] = INREG(i + 0x200);
5188	    j++;
5189	}
5190	for (i = 0x7850; i <= 0x7868; i += 4) {
5191	    state->daca[j] = INREG(i);
5192	    state->dacb[j] = INREG(i + 0x200);
5193	    j++;
5194	}
5195
5196	j = 0;
5197	/* save TMDSA regs */
5198	for (i = 0x7880; i <= 0x78e0; i += 4) {
5199	    state->tmdsa[j] = INREG(i);
5200	    j++;
5201	}
5202	for (i = 0x7904; i <= 0x7918; i += 4) {
5203	    state->tmdsa[j] = INREG(i);
5204	    j++;
5205	}
5206
5207	j = 0;
5208	/* save LVTMA regs */
5209	for (i = 0x7a80; i <= 0x7b18; i += 4) {
5210	    state->lvtma[j] = INREG(i);
5211	    j++;
5212	}
5213
5214	if ((info->ChipFamily == CHIP_FAMILY_RS600) ||
5215	    (info->ChipFamily == CHIP_FAMILY_RS690) ||
5216	    (info->ChipFamily == CHIP_FAMILY_RS740)) {
5217	    j = 0;
5218	    /* save DDIA regs */
5219	    for (i = 0x7200; i <= 0x7290; i += 4) {
5220		state->ddia[j] = INREG(i);
5221		j++;
5222	    }
5223	}
5224    }
5225
5226    /* scalers */
5227    j = 0;
5228    for (i = 0x6578; i <= 0x65e4; i += 4) {
5229	state->d1scl[j] = INREG(i);
5230	state->d2scl[j] = INREG(i + 0x800);
5231	j++;
5232    }
5233    for (i = 0x6600; i <= 0x662c; i += 4) {
5234	state->d1scl[j] = INREG(i);
5235	state->d2scl[j] = INREG(i + 0x800);
5236	j++;
5237    }
5238    j = 0;
5239    for (i = 0x66e8; i <= 0x66fc; i += 4) {
5240	state->dxscl[j] = INREG(i);
5241	j++;
5242    }
5243    state->dxscl[6] = INREG(0x6e30);
5244    state->dxscl[7] = INREG(0x6e34);
5245
5246    if (state->crtc[0].control & AVIVO_CRTC_EN)
5247	info->crtc_on = TRUE;
5248
5249    if (state->crtc[1].control & AVIVO_CRTC_EN)
5250	info->crtc2_on = TRUE;
5251
5252}
5253
5254static void
5255avivo_restore(ScrnInfoPtr pScrn, RADEONSavePtr restore)
5256{
5257    RADEONInfoPtr info = RADEONPTR(pScrn);
5258    unsigned char *RADEONMMIO = info->MMIO;
5259    struct avivo_state *state = &restore->avivo;
5260    int i, j;
5261
5262    xf86DrvMsg(pScrn->scrnIndex, X_INFO, "avivo_restore !\n");
5263
5264    /* Disable VGA control for now.. maybe needs to be changed */
5265    OUTREG(AVIVO_D1VGA_CONTROL, 0);
5266    OUTREG(AVIVO_D2VGA_CONTROL, 0);
5267
5268    /* Disable CRTCs */
5269    OUTREG(AVIVO_D1CRTC_CONTROL,
5270	   (INREG(AVIVO_D1CRTC_CONTROL) & ~0x300) | 0x01000000);
5271    OUTREG(AVIVO_D2CRTC_CONTROL,
5272	   (INREG(AVIVO_D2CRTC_CONTROL) & ~0x300) | 0x01000000);
5273    OUTREG(AVIVO_D1CRTC_CONTROL,
5274	   INREG(AVIVO_D1CRTC_CONTROL) & ~0x1);
5275    OUTREG(AVIVO_D2CRTC_CONTROL,
5276	   INREG(AVIVO_D2CRTC_CONTROL) & ~0x1);
5277    OUTREG(AVIVO_D1CRTC_CONTROL,
5278	   INREG(AVIVO_D1CRTC_CONTROL) | 0x100);
5279    OUTREG(AVIVO_D2CRTC_CONTROL,
5280	   INREG(AVIVO_D2CRTC_CONTROL) | 0x100);
5281
5282    /* Lock graph registers */
5283    OUTREG(AVIVO_D1GRPH_UPDATE, AVIVO_D1GRPH_UPDATE_LOCK);
5284    OUTREG(AVIVO_D1GRPH_PRIMARY_SURFACE_ADDRESS, state->grph[0].prim_surf_addr);
5285    OUTREG(AVIVO_D1GRPH_SECONDARY_SURFACE_ADDRESS, state->grph[0].sec_surf_addr);
5286    OUTREG(AVIVO_D1GRPH_CONTROL, state->grph[0].control);
5287    OUTREG(AVIVO_D1GRPH_SURFACE_OFFSET_X, state->grph[0].x_offset);
5288    OUTREG(AVIVO_D1GRPH_SURFACE_OFFSET_Y, state->grph[0].y_offset);
5289    OUTREG(AVIVO_D1GRPH_X_START, state->grph[0].x_start);
5290    OUTREG(AVIVO_D1GRPH_Y_START, state->grph[0].y_start);
5291    OUTREG(AVIVO_D1GRPH_X_END, state->grph[0].x_end);
5292    OUTREG(AVIVO_D1GRPH_Y_END, state->grph[0].y_end);
5293    OUTREG(AVIVO_D1GRPH_PITCH, state->grph[0].pitch);
5294    OUTREG(AVIVO_D1GRPH_ENABLE, state->grph[0].enable);
5295    OUTREG(AVIVO_D1GRPH_UPDATE, 0);
5296
5297    OUTREG(AVIVO_D2GRPH_UPDATE, AVIVO_D1GRPH_UPDATE_LOCK);
5298    OUTREG(AVIVO_D2GRPH_PRIMARY_SURFACE_ADDRESS, state->grph[1].prim_surf_addr);
5299    OUTREG(AVIVO_D2GRPH_SECONDARY_SURFACE_ADDRESS, state->grph[1].sec_surf_addr);
5300    OUTREG(AVIVO_D2GRPH_CONTROL, state->grph[1].control);
5301    OUTREG(AVIVO_D2GRPH_SURFACE_OFFSET_X, state->grph[1].x_offset);
5302    OUTREG(AVIVO_D2GRPH_SURFACE_OFFSET_Y, state->grph[1].y_offset);
5303    OUTREG(AVIVO_D2GRPH_X_START, state->grph[1].x_start);
5304    OUTREG(AVIVO_D2GRPH_Y_START, state->grph[1].y_start);
5305    OUTREG(AVIVO_D2GRPH_X_END, state->grph[1].x_end);
5306    OUTREG(AVIVO_D2GRPH_Y_END, state->grph[1].y_end);
5307    OUTREG(AVIVO_D2GRPH_PITCH, state->grph[1].pitch);
5308    OUTREG(AVIVO_D2GRPH_ENABLE, state->grph[1].enable);
5309    OUTREG(AVIVO_D2GRPH_UPDATE, 0);
5310
5311    /* Whack some mode regs too */
5312    OUTREG(AVIVO_D1SCL_UPDATE, AVIVO_D1SCL_UPDATE_LOCK);
5313    OUTREG(AVIVO_D1MODE_DESKTOP_HEIGHT, state->grph[0].desktop_height);
5314    OUTREG(AVIVO_D1MODE_VIEWPORT_START, state->grph[0].viewport_start);
5315    OUTREG(AVIVO_D1MODE_VIEWPORT_SIZE, state->grph[0].viewport_size);
5316    OUTREG(AVIVO_D1MODE_DATA_FORMAT, state->grph[0].mode_data_format);
5317    OUTREG(AVIVO_D1SCL_UPDATE, 0);
5318
5319    OUTREG(AVIVO_D2SCL_UPDATE, AVIVO_D1SCL_UPDATE_LOCK);
5320    OUTREG(AVIVO_D2MODE_DESKTOP_HEIGHT, state->grph[1].desktop_height);
5321    OUTREG(AVIVO_D2MODE_VIEWPORT_START, state->grph[1].viewport_start);
5322    OUTREG(AVIVO_D2MODE_VIEWPORT_SIZE, state->grph[1].viewport_size);
5323    OUTREG(AVIVO_D2MODE_DATA_FORMAT, state->grph[1].mode_data_format);
5324    OUTREG(AVIVO_D2SCL_UPDATE, 0);
5325
5326    /* Set the PLL */
5327    OUTREG(AVIVO_EXT1_PPLL_REF_DIV_SRC, state->pll[0].ref_div_src);
5328    OUTREG(AVIVO_EXT1_PPLL_REF_DIV, state->pll[0].ref_div);
5329    OUTREG(AVIVO_EXT1_PPLL_FB_DIV, state->pll[0].fb_div);
5330    OUTREG(AVIVO_EXT1_PPLL_POST_DIV_SRC, state->pll[0].post_div_src);
5331    OUTREG(AVIVO_EXT1_PPLL_POST_DIV, state->pll[0].post_div);
5332    OUTREG(AVIVO_EXT1_PPLL_CNTL, state->pll[0].ext_ppll_cntl);
5333    OUTREG(AVIVO_P1PLL_CNTL, state->pll[0].pll_cntl);
5334    OUTREG(AVIVO_P1PLL_INT_SS_CNTL, state->pll[0].int_ss_cntl);
5335
5336    OUTREG(AVIVO_EXT2_PPLL_REF_DIV_SRC, state->pll[1].ref_div_src);
5337    OUTREG(AVIVO_EXT2_PPLL_REF_DIV, state->pll[1].ref_div);
5338    OUTREG(AVIVO_EXT2_PPLL_FB_DIV, state->pll[1].fb_div);
5339    OUTREG(AVIVO_EXT2_PPLL_POST_DIV_SRC, state->pll[1].post_div_src);
5340    OUTREG(AVIVO_EXT2_PPLL_POST_DIV, state->pll[1].post_div);
5341    OUTREG(AVIVO_EXT2_PPLL_CNTL, state->pll[1].ext_ppll_cntl);
5342    OUTREG(AVIVO_P2PLL_CNTL, state->pll[1].pll_cntl);
5343    OUTREG(AVIVO_P2PLL_INT_SS_CNTL, state->pll[1].int_ss_cntl);
5344
5345    OUTREG(AVIVO_PCLK_CRTC1_CNTL, state->crtc[0].pll_source);
5346    OUTREG(AVIVO_PCLK_CRTC2_CNTL, state->crtc[1].pll_source);
5347
5348    /* Set the vga PLL */
5349    OUTREG(AVIVO_VGA25_PPLL_REF_DIV_SRC, state->vga25_ppll.ref_div_src);
5350    OUTREG(AVIVO_VGA25_PPLL_REF_DIV, state->vga25_ppll.ref_div);
5351    OUTREG(AVIVO_VGA25_PPLL_FB_DIV, state->vga25_ppll.fb_div);
5352    OUTREG(AVIVO_VGA25_PPLL_POST_DIV_SRC, state->vga25_ppll.post_div_src);
5353    OUTREG(AVIVO_VGA25_PPLL_POST_DIV, state->vga25_ppll.post_div);
5354    OUTREG(AVIVO_VGA25_PPLL_CNTL, state->vga25_ppll.pll_cntl);
5355
5356    OUTREG(AVIVO_VGA28_PPLL_REF_DIV_SRC, state->vga28_ppll.ref_div_src);
5357    OUTREG(AVIVO_VGA28_PPLL_REF_DIV, state->vga28_ppll.ref_div);
5358    OUTREG(AVIVO_VGA28_PPLL_FB_DIV, state->vga28_ppll.fb_div);
5359    OUTREG(AVIVO_VGA28_PPLL_POST_DIV_SRC, state->vga28_ppll.post_div_src);
5360    OUTREG(AVIVO_VGA28_PPLL_POST_DIV, state->vga28_ppll.post_div);
5361    OUTREG(AVIVO_VGA28_PPLL_CNTL, state->vga28_ppll.pll_cntl);
5362
5363    OUTREG(AVIVO_VGA41_PPLL_REF_DIV_SRC, state->vga41_ppll.ref_div_src);
5364    OUTREG(AVIVO_VGA41_PPLL_REF_DIV, state->vga41_ppll.ref_div);
5365    OUTREG(AVIVO_VGA41_PPLL_FB_DIV, state->vga41_ppll.fb_div);
5366    OUTREG(AVIVO_VGA41_PPLL_POST_DIV_SRC, state->vga41_ppll.post_div_src);
5367    OUTREG(AVIVO_VGA41_PPLL_POST_DIV, state->vga41_ppll.post_div);
5368    OUTREG(AVIVO_VGA41_PPLL_CNTL, state->vga41_ppll.pll_cntl);
5369
5370    /* Set the CRTC */
5371    OUTREG(AVIVO_D1CRTC_H_TOTAL, state->crtc[0].h_total);
5372    OUTREG(AVIVO_D1CRTC_H_BLANK_START_END, state->crtc[0].h_blank_start_end);
5373    OUTREG(AVIVO_D1CRTC_H_SYNC_A, state->crtc[0].h_sync_a);
5374    OUTREG(AVIVO_D1CRTC_H_SYNC_A_CNTL, state->crtc[0].h_sync_a_cntl);
5375    OUTREG(AVIVO_D1CRTC_H_SYNC_B, state->crtc[0].h_sync_b);
5376    OUTREG(AVIVO_D1CRTC_H_SYNC_B_CNTL, state->crtc[0].h_sync_b_cntl);
5377
5378    OUTREG(AVIVO_D1CRTC_V_TOTAL, state->crtc[0].v_total);
5379    OUTREG(AVIVO_D1CRTC_V_BLANK_START_END, state->crtc[0].v_blank_start_end);
5380    OUTREG(AVIVO_D1CRTC_V_SYNC_A, state->crtc[0].v_sync_a);
5381    OUTREG(AVIVO_D1CRTC_V_SYNC_A_CNTL, state->crtc[0].v_sync_a_cntl);
5382    OUTREG(AVIVO_D1CRTC_V_SYNC_B, state->crtc[0].v_sync_b);
5383    OUTREG(AVIVO_D1CRTC_V_SYNC_B_CNTL, state->crtc[0].v_sync_b_cntl);
5384
5385    OUTREG(AVIVO_D1CRTC_INTERLACE_CONTROL, state->crtc[0].interlace_control);
5386    OUTREG(AVIVO_D1CRTC_STEREO_CONTROL, state->crtc[0].stereo_control);
5387
5388    OUTREG(AVIVO_D1CUR_CONTROL, state->crtc[0].cursor_control);
5389
5390    /* XXX Fix scaler */
5391
5392    OUTREG(AVIVO_D2CRTC_H_TOTAL, state->crtc[1].h_total);
5393    OUTREG(AVIVO_D2CRTC_H_BLANK_START_END, state->crtc[1].h_blank_start_end);
5394    OUTREG(AVIVO_D2CRTC_H_SYNC_A, state->crtc[1].h_sync_a);
5395    OUTREG(AVIVO_D2CRTC_H_SYNC_A_CNTL, state->crtc[1].h_sync_a_cntl);
5396    OUTREG(AVIVO_D2CRTC_H_SYNC_B, state->crtc[1].h_sync_b);
5397    OUTREG(AVIVO_D2CRTC_H_SYNC_B_CNTL, state->crtc[1].h_sync_b_cntl);
5398
5399    OUTREG(AVIVO_D2CRTC_V_TOTAL, state->crtc[1].v_total);
5400    OUTREG(AVIVO_D2CRTC_V_BLANK_START_END, state->crtc[1].v_blank_start_end);
5401    OUTREG(AVIVO_D2CRTC_V_SYNC_A, state->crtc[1].v_sync_a);
5402    OUTREG(AVIVO_D2CRTC_V_SYNC_A_CNTL, state->crtc[1].v_sync_a_cntl);
5403    OUTREG(AVIVO_D2CRTC_V_SYNC_B, state->crtc[1].v_sync_b);
5404    OUTREG(AVIVO_D2CRTC_V_SYNC_B_CNTL, state->crtc[1].v_sync_b_cntl);
5405
5406    OUTREG(AVIVO_D2CRTC_INTERLACE_CONTROL, state->crtc[1].interlace_control);
5407    OUTREG(AVIVO_D2CRTC_STEREO_CONTROL, state->crtc[1].stereo_control);
5408
5409    OUTREG(AVIVO_D2CUR_CONTROL, state->crtc[1].cursor_control);
5410
5411    if (IS_DCE3_VARIANT) {
5412	/* DVOA regs */
5413	OUTREG(0x7080, state->dvoa[0]);
5414	OUTREG(0x7084, state->dvoa[1]);
5415	OUTREG(0x708c, state->dvoa[2]);
5416	OUTREG(0x7090, state->dvoa[3]);
5417	OUTREG(0x7094, state->dvoa[4]);
5418	OUTREG(0x70ac, state->dvoa[5]);
5419	OUTREG(0x70b0, state->dvoa[6]);
5420
5421	j = 0;
5422	/* DAC regs */
5423	for (i = 0x7000; i <= 0x7040; i += 4) {
5424	    OUTREG(i, state->daca[j]);
5425	    OUTREG((i + 0x100), state->dacb[j]);
5426	    j++;
5427	}
5428	for (i = 0x7058; i <= 0x7060; i += 4) {
5429	    OUTREG(i, state->daca[j]);
5430	    OUTREG((i + 0x100), state->dacb[j]);
5431	    j++;
5432	}
5433	for (i = 0x7068; i <= 0x706c; i += 4) {
5434	    OUTREG(i, state->daca[j]);
5435	    OUTREG((i + 0x100), state->dacb[j]);
5436	    j++;
5437	}
5438	for (i = 0x7ef0; i <= 0x7ef8; i += 4) {
5439	    OUTREG(i, state->daca[j]);
5440	    OUTREG((i + 0x100), state->dacb[j]);
5441	    j++;
5442	}
5443	OUTREG(0x7050, state->daca[j]);
5444	OUTREG((0x7050 + 0x100), state->dacb[j]);
5445
5446	j = 0;
5447	/* FMT regs */
5448	for (i = 0x6700; i <= 0x6744; i += 4) {
5449	    OUTREG(i, state->fmt1[j]);
5450	    OUTREG((i + 0x800), state->fmt2[j]);
5451	    j++;
5452	}
5453
5454	j = 0;
5455	/* DIG regs */
5456	for (i = 0x75a0; i <= 0x75e0; i += 4) {
5457	    OUTREG(i, state->dig1[j]);
5458	    OUTREG((i + 0x400), state->dig2[j]);
5459	    j++;
5460	}
5461	for (i = 0x75e8; i <= 0x75ec; i += 4) {
5462	    OUTREG(i, state->dig1[j]);
5463	    OUTREG((i + 0x400), state->dig2[j]);
5464	    j++;
5465	}
5466
5467	j = 0;
5468	/* HDMI regs */
5469	for (i = 0x7400; i <= 0x741c; i += 4) {
5470	    OUTREG(i, state->hdmi1[j]);
5471	    OUTREG((i + 0x400), state->hdmi2[j]);
5472	    j++;
5473	}
5474	for (i = 0x7430; i <= 0x74ec; i += 4) {
5475	    OUTREG(i, state->hdmi1[j]);
5476	    OUTREG((i + 0x400), state->hdmi2[j]);
5477	    j++;
5478	}
5479	OUTREG(0x7428, state->hdmi1[j]);
5480	OUTREG((0x7428 + 0x400), state->hdmi2[j]);
5481
5482	j = 0;
5483	/* save AUX regs */
5484	for (i = 0x7780; i <= 0x77b4; i += 4) {
5485	    OUTREG(i, state->aux_cntl1[j]);
5486	    OUTREG((i + 0x040), state->aux_cntl2[j]);
5487	    OUTREG((i + 0x400), state->aux_cntl3[j]);
5488	    OUTREG((i + 0x440), state->aux_cntl4[j]);
5489	    if (IS_DCE32_VARIANT) {
5490		OUTREG((i + 0x500), state->aux_cntl5[j]);
5491		OUTREG((i + 0x540), state->aux_cntl6[j]);
5492	    }
5493	    j++;
5494	}
5495
5496	j = 0;
5497	/* save UNIPHY regs */
5498	if (IS_DCE32_VARIANT) {
5499	    for (i = 0x7680; i <= 0x7690; i += 4) {
5500		OUTREG(i, state->uniphy1[j]);
5501		OUTREG((i + 0x20), state->uniphy2[j]);
5502		OUTREG((i + 0x400), state->uniphy3[j]);
5503		OUTREG((i + 0x420), state->uniphy4[j]);
5504		OUTREG((i + 0x840), state->uniphy5[j]);
5505		OUTREG((i + 0x940), state->uniphy6[j]);
5506		j++;
5507	    }
5508	    for (i = 0x7698; i <= 0x769c; i += 4) {
5509		OUTREG(i, state->uniphy1[j]);
5510		OUTREG((i + 0x20), state->uniphy2[j]);
5511		OUTREG((i + 0x400), state->uniphy3[j]);
5512		OUTREG((i + 0x420), state->uniphy4[j]);
5513		OUTREG((i + 0x840), state->uniphy5[j]);
5514		OUTREG((i + 0x940), state->uniphy6[j]);
5515		j++;
5516	    }
5517	} else {
5518	    for (i = 0x7ec0; i <= 0x7edc; i += 4) {
5519		OUTREG(i, state->uniphy1[j]);
5520		OUTREG((i + 0x100), state->uniphy2[j]);
5521		j++;
5522	    }
5523	}
5524	j = 0;
5525	/* save PHY,LINK regs */
5526	for (i = 0x7f20; i <= 0x7f34; i += 4) {
5527	    OUTREG(i, state->phy[j]);
5528	    j++;
5529	}
5530	for (i = 0x7f9c; i <= 0x7fa4; i += 4) {
5531	    OUTREG(i, state->phy[j]);
5532	    j++;
5533	}
5534	state->phy[j] = INREG(0x7f40);
5535
5536	j = 0;
5537	/* save LVTMA regs */
5538	for (i = 0x7f00; i <= 0x7f1c; i += 4) {
5539	    OUTREG(i, state->lvtma[j]);
5540	    j++;
5541	}
5542	for (i = 0x7f80; i <= 0x7f98; i += 4) {
5543	    OUTREG(i, state->lvtma[j]);
5544	    j++;
5545	}
5546    } else {
5547	j = 0;
5548	/* DVOA regs */
5549	for (i = 0x7980; i <= 0x79bc; i += 4) {
5550	    OUTREG(i, state->dvoa[j]);
5551	    j++;
5552	}
5553
5554	j = 0;
5555	/* DAC regs */ /* -- MIGHT NEED ORDERING FIX & DELAYS -- */
5556	for (i = 0x7800; i <= 0x782c; i += 4) {
5557	    OUTREG(i, state->daca[j]);
5558	    OUTREG((i + 0x200), state->dacb[j]);
5559	    j++;
5560	}
5561	for (i = 0x7834; i <= 0x7840; i += 4) {
5562	    OUTREG(i, state->daca[j]);
5563	    OUTREG((i + 0x200), state->dacb[j]);
5564	    j++;
5565	}
5566	for (i = 0x7850; i <= 0x7868; i += 4) {
5567	    OUTREG(i, state->daca[j]);
5568	    OUTREG((i + 0x200), state->dacb[j]);
5569	    j++;
5570	}
5571
5572	j = 0;
5573	/* TMDSA regs */
5574	for (i = 0x7880; i <= 0x78e0; i += 4) {
5575	    OUTREG(i, state->tmdsa[j]);
5576	    j++;
5577	}
5578	for (i = 0x7904; i <= 0x7918; i += 4) {
5579	    OUTREG(i, state->tmdsa[j]);
5580	    j++;
5581	}
5582
5583	j = 0;
5584	/* LVTMA regs */
5585	for (i = 0x7a80; i <= 0x7b18; i += 4) {
5586	    OUTREG(i, state->lvtma[j]);
5587	    j++;
5588	}
5589
5590	/* DDIA regs */
5591	if ((info->ChipFamily == CHIP_FAMILY_RS600) ||
5592	    (info->ChipFamily == CHIP_FAMILY_RS690) ||
5593	    (info->ChipFamily == CHIP_FAMILY_RS740)) {
5594	    j = 0;
5595	    for (i = 0x7200; i <= 0x7290; i += 4) {
5596		OUTREG(i, state->ddia[j]);
5597		j++;
5598	    }
5599	}
5600    }
5601
5602    /* scalers */
5603    j = 0;
5604    for (i = 0x6578; i <= 0x65e4; i += 4) {
5605	OUTREG(i, state->d1scl[j]);
5606	OUTREG((i + 0x800), state->d2scl[j]);
5607	j++;
5608    }
5609    for (i = 0x6600; i <= 0x662c; i += 4) {
5610	OUTREG(i, state->d1scl[j]);
5611	OUTREG((i + 0x800), state->d2scl[j]);
5612	j++;
5613    }
5614    j = 0;
5615    for (i = 0x66e8; i <= 0x66fc; i += 4) {
5616	OUTREG(i, state->dxscl[j]);
5617	j++;
5618    }
5619    OUTREG(0x6e30, state->dxscl[6]);
5620    OUTREG(0x6e34, state->dxscl[7]);
5621
5622    /* Enable CRTCs */
5623    if (state->crtc[0].control & 1) {
5624	    OUTREG(AVIVO_D1CRTC_CONTROL, 0x01000101);
5625	    INREG(AVIVO_D1CRTC_CONTROL);
5626	    OUTREG(AVIVO_D1CRTC_CONTROL, 0x00010101);
5627    }
5628    if (state->crtc[1].control & 1) {
5629	    OUTREG(AVIVO_D2CRTC_CONTROL, 0x01000101);
5630	    INREG(AVIVO_D2CRTC_CONTROL);
5631	    OUTREG(AVIVO_D2CRTC_CONTROL, 0x00010101);
5632    }
5633
5634    /* Where should that go ? */
5635    OUTREG(AVIVO_DC_CRTC_TV_CONTROL, state->crtc_tv_control);
5636    OUTREG(AVIVO_DC_LB_MEMORY_SPLIT, state->dc_lb_memory_split);
5637
5638    /* Need fixing too ? */
5639    OUTREG(AVIVO_D1CRTC_BLANK_CONTROL, state->crtc[0].blank_control);
5640    OUTREG(AVIVO_D2CRTC_BLANK_CONTROL, state->crtc[1].blank_control);
5641
5642    /* Dbl check */
5643    OUTREG(AVIVO_VGA_RENDER_CONTROL, state->vga_render_control);
5644    OUTREG(AVIVO_D1VGA_CONTROL, state->vga1_cntl);
5645    OUTREG(AVIVO_D2VGA_CONTROL, state->vga2_cntl);
5646
5647    /* Should only enable outputs here */
5648}
5649
5650static void avivo_restore_vga_regs(ScrnInfoPtr pScrn, RADEONSavePtr restore)
5651{
5652    RADEONInfoPtr info = RADEONPTR(pScrn);
5653    unsigned char *RADEONMMIO = info->MMIO;
5654    struct avivo_state *state = &restore->avivo;
5655
5656    OUTREG(AVIVO_VGA_RENDER_CONTROL, state->vga_render_control);
5657    OUTREG(AVIVO_D1VGA_CONTROL, state->vga1_cntl);
5658    OUTREG(AVIVO_D2VGA_CONTROL, state->vga2_cntl);
5659}
5660
5661static void dce4_restore_vga_regs(ScrnInfoPtr pScrn, RADEONSavePtr restore)
5662{
5663    RADEONInfoPtr info = RADEONPTR(pScrn);
5664    unsigned char *RADEONMMIO = info->MMIO;
5665    struct dce4_state *state = &restore->dce4;
5666
5667    OUTREG(AVIVO_VGA_RENDER_CONTROL, state->vga_render_control);
5668    OUTREG(AVIVO_D1VGA_CONTROL, state->vga1_cntl);
5669    OUTREG(AVIVO_D2VGA_CONTROL, state->vga2_cntl);
5670    OUTREG(EVERGREEN_D3VGA_CONTROL, state->vga3_cntl);
5671    OUTREG(EVERGREEN_D4VGA_CONTROL, state->vga4_cntl);
5672    OUTREG(EVERGREEN_D5VGA_CONTROL, state->vga5_cntl);
5673    OUTREG(EVERGREEN_D6VGA_CONTROL, state->vga6_cntl);
5674}
5675
5676
5677static void
5678RADEONRestoreBIOSRegisters(ScrnInfoPtr pScrn, RADEONSavePtr restore)
5679{
5680    RADEONInfoPtr  info       = RADEONPTR(pScrn);
5681    unsigned char *RADEONMMIO = info->MMIO;
5682
5683    if (info->ChipFamily >= CHIP_FAMILY_R600) {
5684	OUTREG(R600_BIOS_0_SCRATCH, restore->bios_0_scratch);
5685	OUTREG(R600_BIOS_1_SCRATCH, restore->bios_1_scratch);
5686	OUTREG(R600_BIOS_2_SCRATCH, restore->bios_2_scratch);
5687	OUTREG(R600_BIOS_3_SCRATCH, restore->bios_3_scratch);
5688	OUTREG(R600_BIOS_4_SCRATCH, restore->bios_4_scratch);
5689	OUTREG(R600_BIOS_5_SCRATCH, restore->bios_5_scratch);
5690	OUTREG(R600_BIOS_6_SCRATCH, restore->bios_6_scratch);
5691	OUTREG(R600_BIOS_7_SCRATCH, restore->bios_7_scratch);
5692    } else {
5693	OUTREG(RADEON_BIOS_0_SCRATCH, restore->bios_0_scratch);
5694	OUTREG(RADEON_BIOS_1_SCRATCH, restore->bios_1_scratch);
5695	OUTREG(RADEON_BIOS_2_SCRATCH, restore->bios_2_scratch);
5696	OUTREG(RADEON_BIOS_3_SCRATCH, restore->bios_3_scratch);
5697	OUTREG(RADEON_BIOS_4_SCRATCH, restore->bios_4_scratch);
5698	OUTREG(RADEON_BIOS_5_SCRATCH, restore->bios_5_scratch);
5699	OUTREG(RADEON_BIOS_6_SCRATCH, restore->bios_6_scratch);
5700	OUTREG(RADEON_BIOS_7_SCRATCH, restore->bios_7_scratch);
5701    }
5702}
5703
5704static void
5705RADEONSaveBIOSRegisters(ScrnInfoPtr pScrn, RADEONSavePtr save)
5706{
5707    RADEONInfoPtr  info       = RADEONPTR(pScrn);
5708    unsigned char *RADEONMMIO = info->MMIO;
5709
5710    if (info->ChipFamily >= CHIP_FAMILY_R600) {
5711	save->bios_0_scratch       = INREG(R600_BIOS_0_SCRATCH);
5712	save->bios_1_scratch       = INREG(R600_BIOS_1_SCRATCH);
5713	save->bios_2_scratch       = INREG(R600_BIOS_2_SCRATCH);
5714	save->bios_3_scratch       = INREG(R600_BIOS_3_SCRATCH);
5715	save->bios_4_scratch       = INREG(R600_BIOS_4_SCRATCH);
5716	save->bios_5_scratch       = INREG(R600_BIOS_5_SCRATCH);
5717	save->bios_6_scratch       = INREG(R600_BIOS_6_SCRATCH);
5718	save->bios_7_scratch       = INREG(R600_BIOS_7_SCRATCH);
5719    } else {
5720	save->bios_0_scratch       = INREG(RADEON_BIOS_0_SCRATCH);
5721	save->bios_1_scratch       = INREG(RADEON_BIOS_1_SCRATCH);
5722	save->bios_2_scratch       = INREG(RADEON_BIOS_2_SCRATCH);
5723	save->bios_3_scratch       = INREG(RADEON_BIOS_3_SCRATCH);
5724	save->bios_4_scratch       = INREG(RADEON_BIOS_4_SCRATCH);
5725	save->bios_5_scratch       = INREG(RADEON_BIOS_5_SCRATCH);
5726	save->bios_6_scratch       = INREG(RADEON_BIOS_6_SCRATCH);
5727	save->bios_7_scratch       = INREG(RADEON_BIOS_7_SCRATCH);
5728    }
5729}
5730
5731/* Save everything needed to restore the original VC state */
5732static void RADEONSave(ScrnInfoPtr pScrn)
5733{
5734    RADEONInfoPtr  info       = RADEONPTR(pScrn);
5735    RADEONEntPtr pRADEONEnt   = RADEONEntPriv(pScrn);
5736    unsigned char *RADEONMMIO = info->MMIO;
5737    RADEONSavePtr  save       = info->SavedReg;
5738
5739    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
5740		   "RADEONSave\n");
5741
5742#ifdef WITH_VGAHW
5743    if (info->VGAAccess) {
5744	vgaHWPtr hwp = VGAHWPTR(pScrn);
5745
5746	vgaHWUnlock(hwp);
5747# if defined(__powerpc__)
5748	/* temporary hack to prevent crashing on PowerMacs when trying to
5749	 * read VGA fonts and colormap, will find a better solution
5750	 * in the future. TODO: Check if there's actually some VGA stuff
5751	 * setup in the card at all !!
5752	 */
5753	vgaHWSave(pScrn, &hwp->SavedReg, VGA_SR_MODE); /* Save mode only */
5754# elif defined(__linux__)
5755	/* Save only mode * & fonts */
5756	vgaHWSave(pScrn, &hwp->SavedReg, VGA_SR_MODE | VGA_SR_FONTS );
5757# else
5758	/* Save mode * & fonts & cmap */
5759	vgaHWSave(pScrn, &hwp->SavedReg, VGA_SR_ALL);
5760# endif
5761	vgaHWLock(hwp);
5762    }
5763#endif
5764
5765    if (IS_DCE4_VARIANT) {
5766	RADEONSaveMemMapRegisters(pScrn, save);
5767	dce4_save(pScrn, save);
5768	//XXX
5769    } else if (IS_AVIVO_VARIANT) {
5770	RADEONSaveMemMapRegisters(pScrn, save);
5771	avivo_save(pScrn, save);
5772    } else {
5773	save->dp_datatype      = INREG(RADEON_DP_DATATYPE);
5774	save->rbbm_soft_reset  = INREG(RADEON_RBBM_SOFT_RESET);
5775	save->clock_cntl_index = INREG(RADEON_CLOCK_CNTL_INDEX);
5776	RADEONPllErrataAfterIndex(info);
5777
5778	RADEONSaveMemMapRegisters(pScrn, save);
5779	RADEONSaveCommonRegisters(pScrn, save);
5780	RADEONSavePLLRegisters(pScrn, save);
5781	RADEONSaveCrtcRegisters(pScrn, save);
5782	RADEONSaveFPRegisters(pScrn, save);
5783	RADEONSaveDACRegisters(pScrn, save);
5784	RADEONSavePalette(pScrn, save);
5785
5786	if (pRADEONEnt->HasCRTC2) {
5787	    RADEONSaveCrtc2Registers(pScrn, save);
5788	    RADEONSavePLL2Registers(pScrn, save);
5789	}
5790	if (info->InternalTVOut)
5791	    RADEONSaveTVRegisters(pScrn, save);
5792    }
5793
5794    if (info->ChipFamily < CHIP_FAMILY_R600)
5795        RADEONSaveSurfaces(pScrn, save);
5796
5797}
5798
5799/* Restore the original (text) mode */
5800static void RADEONRestore(ScrnInfoPtr pScrn)
5801{
5802    RADEONInfoPtr  info       = RADEONPTR(pScrn);
5803    RADEONEntPtr pRADEONEnt = RADEONEntPriv(pScrn);
5804    unsigned char *RADEONMMIO = info->MMIO;
5805    RADEONSavePtr  restore    = info->SavedReg;
5806    xf86CrtcConfigPtr   xf86_config = XF86_CRTC_CONFIG_PTR(pScrn);
5807    xf86CrtcPtr crtc;
5808
5809    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
5810		   "RADEONRestore\n");
5811
5812#if X_BYTE_ORDER == X_BIG_ENDIAN
5813    if (info->ChipFamily < CHIP_FAMILY_R600) {
5814	RADEONWaitForFifo(pScrn, 1);
5815	OUTREG(RADEON_RBBM_GUICNTL, RADEON_HOST_DATA_SWAP_NONE);
5816    }
5817#endif
5818
5819    RADEONBlank(pScrn);
5820
5821    if (IS_DCE4_VARIANT) {
5822	RADEONRestoreMemMapRegisters(pScrn, restore);
5823	dce4_restore(pScrn, restore);
5824	//XXX
5825    } else if (IS_AVIVO_VARIANT) {
5826	RADEONRestoreMemMapRegisters(pScrn, restore);
5827	avivo_restore(pScrn, restore);
5828    } else {
5829	OUTREG(RADEON_RBBM_SOFT_RESET,  restore->rbbm_soft_reset);
5830	OUTREG(RADEON_DP_DATATYPE,      restore->dp_datatype);
5831	OUTREG(RADEON_GRPH_BUFFER_CNTL, restore->grph_buffer_cntl);
5832	OUTREG(RADEON_GRPH2_BUFFER_CNTL, restore->grph2_buffer_cntl);
5833
5834	if (!info->IsSecondary) {
5835	    RADEONRestoreMemMapRegisters(pScrn, restore);
5836	    RADEONRestoreCommonRegisters(pScrn, restore);
5837
5838	    if (pRADEONEnt->HasCRTC2) {
5839		RADEONRestoreCrtc2Registers(pScrn, restore);
5840		RADEONRestorePLL2Registers(pScrn, restore);
5841	    }
5842
5843	    RADEONRestoreCrtcRegisters(pScrn, restore);
5844	    RADEONRestorePLLRegisters(pScrn, restore);
5845	    RADEONRestoreRMXRegisters(pScrn, restore);
5846	    RADEONRestoreFPRegisters(pScrn, restore);
5847	    RADEONRestoreFP2Registers(pScrn, restore);
5848	    RADEONRestoreLVDSRegisters(pScrn, restore);
5849
5850	    if (info->InternalTVOut)
5851		RADEONRestoreTVRegisters(pScrn, restore);
5852	}
5853
5854	OUTREG(RADEON_CLOCK_CNTL_INDEX, restore->clock_cntl_index);
5855	RADEONPllErrataAfterIndex(info);
5856
5857	RADEONRestoreBIOSRegisters(pScrn, restore);
5858    }
5859
5860
5861#if 1
5862    /* Temp fix to "solve" VT switch problems.  When switching VTs on
5863     * some systems, the console can either hang or the fonts can be
5864     * corrupted.  This hack solves the problem 99% of the time.  A
5865     * correct fix is being worked on.
5866     */
5867    usleep(100000);
5868#endif
5869
5870    if (info->ChipFamily < CHIP_FAMILY_R600)
5871	RADEONRestoreSurfaces(pScrn, restore);
5872
5873    /* need to make sure we don't enable a crtc by accident or we may get a hang */
5874    if (pRADEONEnt->HasCRTC2 && !info->IsSecondary) {
5875	if (info->crtc2_on && xf86_config->num_crtc > 1) {
5876	    crtc = xf86_config->crtc[1];
5877	    crtc->funcs->dpms(crtc, DPMSModeOn);
5878	}
5879    }
5880    if (info->crtc_on) {
5881	crtc = xf86_config->crtc[0];
5882	crtc->funcs->dpms(crtc, DPMSModeOn);
5883    }
5884
5885#ifdef WITH_VGAHW
5886    if (info->VGAAccess) {
5887       vgaHWPtr hwp = VGAHWPTR(pScrn);
5888       vgaHWUnlock(hwp);
5889# if defined(__powerpc__)
5890       /* Temporary hack to prevent crashing on PowerMacs when trying to
5891	* write VGA fonts, will find a better solution in the future
5892	*/
5893       vgaHWRestore(pScrn, &hwp->SavedReg, VGA_SR_MODE );
5894# elif defined(__linux__)
5895       vgaHWRestore(pScrn, &hwp->SavedReg, VGA_SR_MODE | VGA_SR_FONTS );
5896# else
5897       vgaHWRestore(pScrn, &hwp->SavedReg, VGA_SR_ALL );
5898# endif
5899       vgaHWLock(hwp);
5900    }
5901#endif
5902
5903    /* to restore console mode, DAC registers should be set after every other registers are set,
5904     * otherwise,we may get blank screen
5905     */
5906    if (IS_DCE4_VARIANT)
5907        dce4_restore_vga_regs(pScrn, restore);
5908    else if (IS_AVIVO_VARIANT)
5909	avivo_restore_vga_regs(pScrn, restore);
5910    else {
5911	RADEONRestorePalette(pScrn, restore);
5912	RADEONRestoreDACRegisters(pScrn, restore);
5913    }
5914#if 0
5915    RADEONWaitForVerticalSync(pScrn);
5916#endif
5917}
5918
5919static Bool RADEONSaveScreen(ScreenPtr pScreen, int mode)
5920{
5921    ScrnInfoPtr  pScrn = xf86Screens[pScreen->myNum];
5922    Bool         unblank;
5923
5924    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
5925		   "RADEONSaveScreen(%d)\n", mode);
5926
5927    unblank = xf86IsUnblank(mode);
5928    if (unblank) SetTimeSinceLastInputEvent();
5929
5930    if ((pScrn != NULL) && pScrn->vtSema) {
5931	if (unblank)
5932	    RADEONUnblank(pScrn);
5933	else
5934	    RADEONBlank(pScrn);
5935    }
5936    return TRUE;
5937}
5938
5939Bool RADEONSwitchMode(int scrnIndex, DisplayModePtr mode, int flags)
5940{
5941    ScrnInfoPtr    pScrn       = xf86Screens[scrnIndex];
5942    RADEONInfoPtr  info        = RADEONPTR(pScrn);
5943    Bool           tilingOld   = info->tilingEnabled;
5944    Bool           ret;
5945#ifdef XF86DRI
5946    Bool           CPStarted   = info->cp->CPStarted;
5947
5948    if (CPStarted) {
5949	DRILock(pScrn->pScreen, 0);
5950	RADEONCP_STOP(pScrn, info);
5951    }
5952#endif
5953
5954    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
5955		   "RADEONSwitchMode() !n");
5956
5957    if (info->allowColorTiling) {
5958        info->tilingEnabled = (mode->Flags & (V_DBLSCAN | V_INTERLACE)) ? FALSE : TRUE;
5959#ifdef XF86DRI
5960	if (info->directRenderingEnabled && (info->tilingEnabled != tilingOld)) {
5961	    drm_radeon_sarea_t *pSAREAPriv;
5962	  if (RADEONDRISetParam(pScrn, RADEON_SETPARAM_SWITCH_TILING, (info->tilingEnabled ? 1 : 0)) < 0)
5963  	      xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
5964			 "[drm] failed changing tiling status\n");
5965	    pSAREAPriv = DRIGetSAREAPrivate(pScrn->pScreen);
5966	    info->tilingEnabled = pSAREAPriv->tiling_enabled ? TRUE : FALSE;
5967	}
5968#endif
5969    }
5970
5971    if (info->accelOn)
5972        RADEON_SYNC(info, pScrn);
5973
5974    ret = xf86SetSingleMode (pScrn, mode, RR_Rotate_0);
5975
5976    if (info->tilingEnabled != tilingOld) {
5977	/* need to redraw front buffer, I guess this can be considered a hack ? */
5978	xf86EnableDisableFBAccess(scrnIndex, FALSE);
5979	RADEONChangeSurfaces(pScrn);
5980	xf86EnableDisableFBAccess(scrnIndex, TRUE);
5981	/* xf86SetRootClip would do, but can't access that here */
5982    }
5983
5984    if (info->accelOn) {
5985        RADEON_SYNC(info, pScrn);
5986	if (info->ChipFamily < CHIP_FAMILY_R600)
5987	    RADEONEngineRestore(pScrn);
5988    }
5989
5990#ifdef XF86DRI
5991    if (CPStarted) {
5992	RADEONCP_START(pScrn, info);
5993	DRIUnlock(pScrn->pScreen);
5994    }
5995#endif
5996
5997    /* reset ecp for overlay */
5998    info->ecp_div = -1;
5999
6000    return ret;
6001}
6002
6003#ifdef X_XF86MiscPassMessage
6004Bool RADEONHandleMessage(int scrnIndex, const char* msgtype,
6005                                   const char* msgval, char** retmsg)
6006{
6007    ErrorF("RADEONHandleMessage(%d, \"%s\", \"%s\", retmsg)\n", scrnIndex,
6008		    msgtype, msgval);
6009    *retmsg = "";
6010    return 0;
6011}
6012#endif
6013
6014#ifndef HAVE_XF86MODEBANDWIDTH
6015/** Calculates the memory bandwidth (in MiB/sec) of a mode. */
6016_X_HIDDEN unsigned int
6017xf86ModeBandwidth(DisplayModePtr mode, int depth)
6018{
6019    float a_active, a_total, active_percent, pixels_per_second;
6020    int bytes_per_pixel = (depth + 7) / 8;
6021
6022    if (!mode->HTotal || !mode->VTotal || !mode->Clock)
6023	return 0;
6024
6025    a_active = mode->HDisplay * mode->VDisplay;
6026    a_total = mode->HTotal * mode->VTotal;
6027    active_percent = a_active / a_total;
6028    pixels_per_second = active_percent * mode->Clock * 1000.0;
6029
6030    return (unsigned int)(pixels_per_second * bytes_per_pixel / (1024 * 1024));
6031}
6032#endif
6033
6034/* Used to disallow modes that are not supported by the hardware */
6035ModeStatus RADEONValidMode(int scrnIndex, DisplayModePtr mode,
6036                                     Bool verbose, int flag)
6037{
6038    ScrnInfoPtr pScrn = xf86Screens[scrnIndex];
6039    RADEONInfoPtr info = RADEONPTR(pScrn);
6040    RADEONEntPtr pRADEONEnt = RADEONEntPriv(pScrn);
6041
6042    /*
6043     * RN50 has effective maximum mode bandwidth of about 300MiB/s.
6044     * XXX should really do this for all chips by properly computing
6045     * memory bandwidth and an overhead factor.
6046     */
6047    if (info->ChipFamily == CHIP_FAMILY_RV100 && !pRADEONEnt->HasCRTC2) {
6048	if (xf86ModeBandwidth(mode, pScrn->bitsPerPixel) > 300)
6049	    return MODE_BANDWIDTH;
6050    }
6051
6052    /* There are problems with double scan mode at high clocks
6053     * They're likely related PLL and display buffer settings.
6054     * Disable these modes for now.
6055     */
6056    if (mode->Flags & V_DBLSCAN) {
6057	if ((mode->CrtcHDisplay >= 1024) || (mode->CrtcVDisplay >= 768))
6058	    return MODE_CLOCK_RANGE;
6059    }
6060    return MODE_OK;
6061}
6062
6063/* Adjust viewport into virtual desktop such that (0,0) in viewport
6064 * space is (x,y) in virtual space.
6065 */
6066void RADEONDoAdjustFrame(ScrnInfoPtr pScrn, int x, int y, Bool crtc2)
6067{
6068    RADEONInfoPtr  info       = RADEONPTR(pScrn);
6069    unsigned char *RADEONMMIO = info->MMIO;
6070    int            Base, reg, regcntl, crtcoffsetcntl, xytilereg, crtcxytile = 0;
6071#ifdef XF86DRI
6072    drm_radeon_sarea_t *pSAREAPriv;
6073    XF86DRISAREAPtr pSAREA;
6074#endif
6075
6076#if 0 /* Verbose */
6077    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
6078		   "RADEONDoAdjustFrame(%d,%d,%d)\n", x, y, clone);
6079#endif
6080
6081    Base = pScrn->fbOffset;
6082
6083  /* note we cannot really simply use the info->ModeReg.crtc_offset_cntl value, since the
6084     drm might have set FLIP_CNTL since we wrote that. Unfortunately FLIP_CNTL causes
6085     flickering when scrolling vertically in a virtual screen, possibly because crtc will
6086     pick up the new offset value at the end of each scanline, but the new offset_cntl value
6087     only after a vsync. We'd probably need to wait (in drm) for vsync and only then update
6088     OFFSET and OFFSET_CNTL, if the y coord has changed. Seems hard to fix. */
6089    if (crtc2) {
6090	reg = RADEON_CRTC2_OFFSET;
6091	regcntl = RADEON_CRTC2_OFFSET_CNTL;
6092	xytilereg = R300_CRTC2_TILE_X0_Y0;
6093    } else {
6094	reg = RADEON_CRTC_OFFSET;
6095	regcntl = RADEON_CRTC_OFFSET_CNTL;
6096	xytilereg = R300_CRTC_TILE_X0_Y0;
6097    }
6098    crtcoffsetcntl = INREG(regcntl) & ~0xf;
6099#if 0
6100    /* try to get rid of flickering when scrolling at least for 2d */
6101#ifdef XF86DRI
6102    if (!info->dri->have3DWindows)
6103#endif
6104    crtcoffsetcntl &= ~RADEON_CRTC_OFFSET_FLIP_CNTL;
6105#endif
6106    if (info->tilingEnabled) {
6107        if (IS_R300_VARIANT || IS_AVIVO_VARIANT) {
6108	/* On r300/r400 when tiling is enabled crtc_offset is set to the address of
6109	 * the surface.  the x/y offsets are handled by the X_Y tile reg for each crtc
6110	 * Makes tiling MUCH easier.
6111	 */
6112             crtcxytile = x | (y << 16);
6113             Base &= ~0x7ff;
6114         } else {
6115             int byteshift = info->CurrentLayout.bitsPerPixel >> 4;
6116             /* crtc uses 256(bytes)x8 "half-tile" start addresses? */
6117             int tile_addr = (((y >> 3) * info->CurrentLayout.displayWidth + x) >> (8 - byteshift)) << 11;
6118             Base += tile_addr + ((x << byteshift) % 256) + ((y % 8) << 8);
6119             crtcoffsetcntl = crtcoffsetcntl | (y % 16);
6120         }
6121    }
6122    else {
6123       int offset = y * info->CurrentLayout.displayWidth + x;
6124       switch (info->CurrentLayout.pixel_code) {
6125       case 15:
6126       case 16: offset *= 2; break;
6127       case 24: offset *= 3; break;
6128       case 32: offset *= 4; break;
6129       }
6130       Base += offset;
6131    }
6132
6133    Base &= ~7;                 /* 3 lower bits are always 0 */
6134
6135#ifdef XF86DRI
6136    if (info->directRenderingInited) {
6137	/* note cannot use pScrn->pScreen since this is unitialized when called from
6138	   RADEONScreenInit, and we need to call from there to get mergedfb + pageflip working */
6139        /*** NOTE: r3/4xx will need sarea and drm pageflip updates to handle the xytile regs for
6140	 *** pageflipping!
6141	 ***/
6142	pSAREAPriv = DRIGetSAREAPrivate(screenInfo.screens[pScrn->scrnIndex]);
6143	/* can't get at sarea in a semi-sane way? */
6144	pSAREA = (void *)((char*)pSAREAPriv - sizeof(XF86DRISAREARec));
6145
6146	if (crtc2) {
6147	    pSAREAPriv->crtc2_base = Base;
6148	}
6149	else {
6150	    pSAREA->frame.x = (Base  / info->CurrentLayout.pixel_bytes)
6151		% info->CurrentLayout.displayWidth;
6152	    pSAREA->frame.y = (Base / info->CurrentLayout.pixel_bytes)
6153		/ info->CurrentLayout.displayWidth;
6154	    pSAREA->frame.width = pScrn->frameX1 - x + 1;
6155	    pSAREA->frame.height = pScrn->frameY1 - y + 1;
6156	}
6157
6158	if (pSAREAPriv->pfCurrentPage == 1) {
6159	    Base += info->dri->backOffset - info->dri->frontOffset;
6160	}
6161    }
6162#endif
6163
6164    if (IS_R300_VARIANT || IS_AVIVO_VARIANT) {
6165	OUTREG(xytilereg, crtcxytile);
6166    } else {
6167	OUTREG(regcntl, crtcoffsetcntl);
6168    }
6169
6170    OUTREG(reg, Base);
6171}
6172
6173void RADEONAdjustFrame(int scrnIndex, int x, int y, int flags)
6174{
6175    ScrnInfoPtr    pScrn      = xf86Screens[scrnIndex];
6176    RADEONInfoPtr  info       = RADEONPTR(pScrn);
6177    RADEONEntPtr pRADEONEnt = RADEONEntPriv(pScrn);
6178    xf86CrtcConfigPtr	config = XF86_CRTC_CONFIG_PTR(pScrn);
6179    xf86OutputPtr  output = config->output[config->compat_output];
6180    xf86CrtcPtr	crtc = output->crtc;
6181
6182    /* not handled */
6183    if (IS_AVIVO_VARIANT)
6184	return;
6185
6186#ifdef XF86DRI
6187    if (info->cp->CPStarted && pScrn->pScreen) DRILock(pScrn->pScreen, 0);
6188#endif
6189
6190    if (info->accelOn)
6191        RADEON_SYNC(info, pScrn);
6192
6193    if (crtc && crtc->enabled) {
6194	if (crtc == pRADEONEnt->pCrtc[0])
6195	    RADEONDoAdjustFrame(pScrn, crtc->desiredX + x, crtc->desiredY + y, FALSE);
6196	else
6197	    RADEONDoAdjustFrame(pScrn, crtc->desiredX + x, crtc->desiredY + y, TRUE);
6198	crtc->x = output->initial_x + x;
6199	crtc->y = output->initial_y + y;
6200    }
6201
6202
6203#ifdef XF86DRI
6204	if (info->cp->CPStarted && pScrn->pScreen) DRIUnlock(pScrn->pScreen);
6205#endif
6206}
6207
6208/* Called when VT switching back to the X server.  Reinitialize the
6209 * video mode.
6210 */
6211Bool RADEONEnterVT(int scrnIndex, int flags)
6212{
6213    ScrnInfoPtr    pScrn = xf86Screens[scrnIndex];
6214    RADEONInfoPtr  info  = RADEONPTR(pScrn);
6215    xf86CrtcConfigPtr config = XF86_CRTC_CONFIG_PTR(pScrn);
6216    int i;
6217
6218    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
6219		   "RADEONEnterVT\n");
6220
6221    if (!radeon_card_posted(pScrn)) { /* Softboot V_BIOS */
6222	if (info->IsAtomBios) {
6223	    rhdAtomASICInit(info->atomBIOS);
6224	} else {
6225	    xf86Int10InfoPtr pInt;
6226
6227	    pInt = xf86InitInt10 (info->pEnt->index);
6228	    if (pInt) {
6229		pInt->num = 0xe6;
6230		xf86ExecX86int10 (pInt);
6231		xf86FreeInt10 (pInt);
6232	    } else {
6233		RADEONGetBIOSInitTableOffsets(pScrn);
6234		RADEONPostCardFromBIOSTables(pScrn);
6235	    }
6236	}
6237    }
6238
6239    /* Makes sure the engine is idle before doing anything */
6240    RADEONWaitForIdleMMIO(pScrn);
6241
6242    RADEONPMEnterVT(pScrn);
6243
6244    for (i = 0; i < config->num_crtc; i++)
6245	radeon_crtc_modeset_ioctl(config->crtc[i], TRUE);
6246
6247    pScrn->vtSema = TRUE;
6248
6249    /* Clear the framebuffer */
6250    memset(info->FB + pScrn->fbOffset, 0,
6251           pScrn->virtualY * pScrn->displayWidth * info->CurrentLayout.pixel_bytes);
6252
6253    if (!xf86SetDesiredModes(pScrn))
6254	return FALSE;
6255
6256    if (info->ChipFamily < CHIP_FAMILY_R600)
6257        RADEONRestoreSurfaces(pScrn, info->ModeReg);
6258#ifdef XF86DRI
6259    if (info->directRenderingEnabled) {
6260	if (info->cardType == CARD_PCIE &&
6261	    info->dri->pKernelDRMVersion->version_minor >= 19 &&
6262	    info->FbSecureSize) {
6263#if X_BYTE_ORDER == X_BIG_ENDIAN
6264	    unsigned char *RADEONMMIO = info->MMIO;
6265	    unsigned int sctrl = INREG(RADEON_SURFACE_CNTL);
6266
6267	    /* we need to backup the PCIE GART TABLE from fb memory */
6268	    OUTREG(RADEON_SURFACE_CNTL, 0);
6269#endif
6270	    memcpy(info->FB + info->dri->pciGartOffset, info->dri->pciGartBackup, info->dri->pciGartSize);
6271#if X_BYTE_ORDER == X_BIG_ENDIAN
6272	    OUTREG(RADEON_SURFACE_CNTL, sctrl);
6273#endif
6274	}
6275
6276	/* get the DRI back into shape after resume */
6277	RADEONDRISetVBlankInterrupt (pScrn, TRUE);
6278	RADEONDRIResume(pScrn->pScreen);
6279	RADEONAdjustMemMapRegisters(pScrn, info->ModeReg);
6280
6281    }
6282#endif
6283    /* this will get XVideo going again, but only if XVideo was initialised
6284       during server startup (hence the info->adaptor if). */
6285    if (info->adaptor)
6286	RADEONResetVideo(pScrn);
6287
6288    if (info->accelOn && (info->ChipFamily < CHIP_FAMILY_R600))
6289	RADEONEngineRestore(pScrn);
6290
6291    if (info->accelOn && info->accel_state)
6292	info->accel_state->XInited3D = FALSE;
6293
6294#ifdef XF86DRI
6295    if (info->directRenderingEnabled) {
6296        if (info->ChipFamily >= CHIP_FAMILY_R600)
6297		R600LoadShaders(pScrn);
6298	RADEONCP_START(pScrn, info);
6299	DRIUnlock(pScrn->pScreen);
6300    }
6301#endif
6302    if (IS_R500_3D || IS_R300_3D)
6303	radeon_load_bicubic_texture(pScrn);
6304
6305    return TRUE;
6306}
6307
6308/* Called when VT switching away from the X server.  Restore the
6309 * original text mode.
6310 */
6311void RADEONLeaveVT(int scrnIndex, int flags)
6312{
6313    ScrnInfoPtr    pScrn = xf86Screens[scrnIndex];
6314    RADEONInfoPtr  info  = RADEONPTR(pScrn);
6315    xf86CrtcConfigPtr config = XF86_CRTC_CONFIG_PTR(pScrn);
6316    int i;
6317
6318    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
6319		   "RADEONLeaveVT\n");
6320#ifdef XF86DRI
6321    if (RADEONPTR(pScrn)->directRenderingInited) {
6322
6323	RADEONDRISetVBlankInterrupt (pScrn, FALSE);
6324	DRILock(pScrn->pScreen, 0);
6325	RADEONCP_STOP(pScrn, info);
6326
6327        if (info->cardType == CARD_PCIE &&
6328	    info->dri->pKernelDRMVersion->version_minor >= 19 &&
6329	    info->FbSecureSize) {
6330#if X_BYTE_ORDER == X_BIG_ENDIAN
6331	    unsigned char *RADEONMMIO = info->MMIO;
6332	    unsigned int sctrl = INREG(RADEON_SURFACE_CNTL);
6333
6334            /* we need to backup the PCIE GART TABLE from fb memory */
6335	    OUTREG(RADEON_SURFACE_CNTL, 0);
6336#endif
6337            memcpy(info->dri->pciGartBackup, (info->FB + info->dri->pciGartOffset), info->dri->pciGartSize);
6338#if X_BYTE_ORDER == X_BIG_ENDIAN
6339	    OUTREG(RADEON_SURFACE_CNTL, sctrl);
6340#endif
6341        }
6342
6343	/* Make sure 3D clients will re-upload textures to video RAM */
6344	if (info->dri->textureSize) {
6345	    drm_radeon_sarea_t *pSAREAPriv =
6346		(drm_radeon_sarea_t*)DRIGetSAREAPrivate(pScrn->pScreen);
6347	    struct drm_tex_region *list = pSAREAPriv->tex_list[0];
6348	    int age = ++pSAREAPriv->tex_age[0];
6349
6350	    i = 0;
6351
6352	    do {
6353		list[i].age = age;
6354		i = list[i].next;
6355	    } while (i != 0);
6356	}
6357    }
6358#endif
6359
6360
6361    for (i = 0; i < config->num_crtc; i++) {
6362	xf86CrtcPtr crtc = config->crtc[i];
6363	RADEONCrtcPrivatePtr radeon_crtc = crtc->driver_private;
6364
6365	radeon_crtc->initialized = FALSE;
6366
6367#ifndef HAVE_FREE_SHADOW
6368	if (crtc->rotatedPixmap || crtc->rotatedData) {
6369	    crtc->funcs->shadow_destroy(crtc, crtc->rotatedPixmap,
6370					crtc->rotatedData);
6371	    crtc->rotatedPixmap = NULL;
6372	    crtc->rotatedData = NULL;
6373	}
6374#endif
6375    }
6376
6377#ifdef HAVE_FREE_SHADOW
6378    xf86RotateFreeShadow(pScrn);
6379#endif
6380
6381    xf86_hide_cursors (pScrn);
6382
6383    RADEONPMLeaveVT(pScrn);
6384
6385    RADEONRestore(pScrn);
6386
6387    for (i = 0; i < config->num_crtc; i++)
6388	radeon_crtc_modeset_ioctl(config->crtc[i], FALSE);
6389
6390    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
6391		   "Ok, leaving now...\n");
6392}
6393
6394/* Called at the end of each server generation.  Restore the original
6395 * text mode, unmap video memory, and unwrap and call the saved
6396 * CloseScreen function.
6397 */
6398static Bool RADEONCloseScreen(int scrnIndex, ScreenPtr pScreen)
6399{
6400    ScrnInfoPtr    pScrn = xf86Screens[scrnIndex];
6401    RADEONInfoPtr  info  = RADEONPTR(pScrn);
6402    xf86CrtcConfigPtr config = XF86_CRTC_CONFIG_PTR(pScrn);
6403    int i;
6404
6405    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
6406		   "RADEONCloseScreen\n");
6407
6408    RADEONPMFini(pScrn);
6409
6410    /* Mark acceleration as stopped or we might try to access the engine at
6411     * wrong times, especially if we had DRI, after DRI has been stopped
6412     */
6413    info->accelOn = FALSE;
6414
6415    for (i = 0; i < config->num_crtc; i++) {
6416	xf86CrtcPtr crtc = config->crtc[i];
6417	RADEONCrtcPrivatePtr radeon_crtc = crtc->driver_private;
6418
6419	radeon_crtc->initialized = FALSE;
6420    }
6421
6422#ifdef XF86DRI
6423#ifdef DAMAGE
6424    if (info->dri && info->dri->pDamage) {
6425	PixmapPtr pPix = pScreen->GetScreenPixmap(pScreen);
6426
6427	DamageUnregister(&pPix->drawable, info->dri->pDamage);
6428	DamageDestroy(info->dri->pDamage);
6429	info->dri->pDamage = NULL;
6430    }
6431#endif
6432
6433    RADEONDRIStop(pScreen);
6434#endif
6435
6436#ifdef USE_XAA
6437    if(!info->useEXA && info->accel_state->RenderTex) {
6438        xf86FreeOffscreenLinear(info->accel_state->RenderTex);
6439        info->accel_state->RenderTex = NULL;
6440    }
6441#endif /* USE_XAA */
6442
6443    if (pScrn->vtSema) {
6444	RADEONRestore(pScrn);
6445    }
6446
6447    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
6448		   "Disposing accel...\n");
6449#ifdef USE_EXA
6450    if (info->accel_state->exa) {
6451	exaDriverFini(pScreen);
6452	free(info->accel_state->exa);
6453	info->accel_state->exa = NULL;
6454    }
6455#endif /* USE_EXA */
6456#ifdef USE_XAA
6457    if (!info->useEXA) {
6458	if (info->accel_state->accel)
6459		XAADestroyInfoRec(info->accel_state->accel);
6460	info->accel_state->accel = NULL;
6461
6462	if (info->accel_state->scratch_save)
6463	    free(info->accel_state->scratch_save);
6464	info->accel_state->scratch_save = NULL;
6465    }
6466#endif /* USE_XAA */
6467
6468    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
6469		   "Disposing cursor info\n");
6470    if (info->cursor) xf86DestroyCursorInfoRec(info->cursor);
6471    info->cursor = NULL;
6472
6473    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
6474		   "Unmapping memory\n");
6475    RADEONUnmapMem(pScrn);
6476
6477    pScrn->vtSema = FALSE;
6478
6479    xf86ClearPrimInitDone(info->pEnt->index);
6480
6481    pScreen->BlockHandler = info->BlockHandler;
6482    pScreen->CloseScreen = info->CloseScreen;
6483    return (*pScreen->CloseScreen)(scrnIndex, pScreen);
6484}
6485
6486void RADEONFreeScreen(int scrnIndex, int flags)
6487{
6488    ScrnInfoPtr  pScrn = xf86Screens[scrnIndex];
6489    RADEONInfoPtr  info  = RADEONPTR(pScrn);
6490
6491    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
6492		   "RADEONFreeScreen\n");
6493
6494    /* when server quits at PreInit, we don't need do this anymore*/
6495    if (!info) return;
6496
6497#ifdef WITH_VGAHW
6498    if (info->VGAAccess && xf86LoaderCheckSymbol("vgaHWFreeHWRec"))
6499	vgaHWFreeHWRec(pScrn);
6500#endif
6501    RADEONFreeRec(pScrn);
6502}
6503