radeon_driver.c revision c135eceb
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(CLOSE_SCREEN_ARGS_DECL);
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}, TRUE },
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 = xf86ScreenToScrn(screen);
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 = xf86ScreenToScrn(pScreen);
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	(info->ChipFamily != CHIP_FAMILY_SUMO) &&
1480	(info->ChipFamily != CHIP_FAMILY_SUMO2)) {
1481	if (info->IsIGP)
1482	    info->mc_fb_location = INREG(RADEON_NB_TOM);
1483	else
1484#ifdef XF86DRI
1485	/* Old DRI has restrictions on the memory map */
1486	if ( info->directRenderingEnabled &&
1487	     info->dri->pKernelDRMVersion->version_minor < 10 )
1488	    info->mc_fb_location = (mem_size - 1) & 0xffff0000U;
1489	else
1490#endif
1491	{
1492	    uint64_t aper0_base;
1493
1494	    if (info->ChipFamily >= CHIP_FAMILY_R600) {
1495		aper0_base = INREG(R600_CONFIG_F0_BASE);
1496	    } else {
1497		aper0_base = INREG(RADEON_CONFIG_APER_0_BASE);
1498	    }
1499
1500	    /* Recent chips have an "issue" with the memory controller, the
1501	     * location must be aligned to the size. We just align it down,
1502	     * too bad if we walk over the top of system memory, we don't
1503	     * use DMA without a remapped anyway.
1504	     * Affected chips are rv280, all r3xx, and all r4xx, but not IGP
1505	     */
1506	    if (info->ChipFamily == CHIP_FAMILY_RV280 ||
1507		info->ChipFamily == CHIP_FAMILY_R300 ||
1508		info->ChipFamily == CHIP_FAMILY_R350 ||
1509		info->ChipFamily == CHIP_FAMILY_RV350 ||
1510		info->ChipFamily == CHIP_FAMILY_RV380 ||
1511		info->ChipFamily == CHIP_FAMILY_R420 ||
1512		info->ChipFamily == CHIP_FAMILY_RV410)
1513		    aper0_base &= ~(mem_size - 1);
1514
1515	    if (info->ChipFamily >= CHIP_FAMILY_R600) {
1516		uint64_t mc_fb = ((aper0_base >> 24) & 0xffff) |
1517		    (((aper0_base + mem_size - 1) >> 8) & 0xffff0000);
1518		info->mc_fb_location = mc_fb & 0xffffffff;
1519		ErrorF("mc fb loc is %08x\n", (unsigned int)info->mc_fb_location);
1520	    } else {
1521		uint64_t mc_fb = ((aper0_base >> 16) & 0xffff) |
1522		    ((aper0_base + mem_size - 1) & 0xffff0000U);
1523		info->mc_fb_location = mc_fb & 0xffffffff;
1524	    }
1525	}
1526    }
1527    if (info->ChipFamily >= CHIP_FAMILY_R600) {
1528	info->fbLocation = ((uint64_t)info->mc_fb_location & 0xffff) << 24;
1529    } else {
1530	info->fbLocation = ((uint64_t)info->mc_fb_location & 0xffff) << 16;
1531    }
1532    /* Just disable the damn AGP apertures for now, it may be
1533     * re-enabled later by the DRM
1534     */
1535    if (IS_AVIVO_VARIANT)
1536	info->mc_agp_location = 0x003f0000;
1537    else
1538	info->mc_agp_location = 0xffffffc0;
1539    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
1540	       "RADEONInitMemoryMap() : \n");
1541    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
1542	       "  mem_size         : 0x%08x\n", (unsigned)mem_size);
1543    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
1544	       "  MC_FB_LOCATION   : 0x%08x\n", (unsigned)info->mc_fb_location);
1545    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
1546	       "  MC_AGP_LOCATION  : 0x%08x\n",
1547	       (unsigned)info->mc_agp_location);
1548}
1549
1550static void RADEONGetVRamType(ScrnInfoPtr pScrn)
1551{
1552    RADEONInfoPtr  info   = RADEONPTR(pScrn);
1553    RADEONEntPtr pRADEONEnt = RADEONEntPriv(pScrn);
1554    unsigned char *RADEONMMIO = info->MMIO;
1555    uint32_t tmp;
1556
1557    if (info->IsIGP || (info->ChipFamily >= CHIP_FAMILY_R300))
1558	info->IsDDR = TRUE;
1559    else if (INREG(RADEON_MEM_SDRAM_MODE_REG) & RADEON_MEM_CFG_TYPE_DDR)
1560	info->IsDDR = TRUE;
1561    else
1562	info->IsDDR = FALSE;
1563
1564    if ((info->ChipFamily >= CHIP_FAMILY_R600) &&
1565	(info->ChipFamily <= CHIP_FAMILY_RV635)) {
1566	int chansize;
1567	/* r6xx */
1568	tmp = INREG(R600_RAMCFG);
1569	if (tmp & R600_CHANSIZE_OVERRIDE)
1570	    chansize = 16;
1571	else if (tmp & R600_CHANSIZE)
1572	    chansize = 64;
1573	else
1574	    chansize = 32;
1575	if (info->ChipFamily == CHIP_FAMILY_R600)
1576	    info->RamWidth = 8 * chansize;
1577	else if (info->ChipFamily == CHIP_FAMILY_RV670)
1578	    info->RamWidth = 4 * chansize;
1579	else if ((info->ChipFamily == CHIP_FAMILY_RV610) ||
1580		 (info->ChipFamily == CHIP_FAMILY_RV620))
1581	    info->RamWidth = chansize;
1582	else if ((info->ChipFamily == CHIP_FAMILY_RV630) ||
1583		 (info->ChipFamily == CHIP_FAMILY_RV635))
1584	    info->RamWidth = 2 * chansize;
1585    } else if (info->ChipFamily == CHIP_FAMILY_RV515) {
1586	/* rv515/rv550 */
1587	tmp = INMC(pScrn, RV515_MC_CNTL);
1588	tmp &= RV515_MEM_NUM_CHANNELS_MASK;
1589	switch (tmp) {
1590	case 0: info->RamWidth = 64; break;
1591	case 1: info->RamWidth = 128; break;
1592	default: info->RamWidth = 128; break;
1593	}
1594    } else if ((info->ChipFamily >= CHIP_FAMILY_R520) &&
1595	       (info->ChipFamily <= CHIP_FAMILY_RV570)){
1596	/* r520/rv530/rv560/rv570/r580 */
1597	tmp = INMC(pScrn, R520_MC_CNTL0);
1598	switch ((tmp & R520_MEM_NUM_CHANNELS_MASK) >> R520_MEM_NUM_CHANNELS_SHIFT) {
1599	case 0: info->RamWidth = 32; break;
1600	case 1: info->RamWidth = 64; break;
1601	case 2: info->RamWidth = 128; break;
1602	case 3: info->RamWidth = 256; break;
1603	default: info->RamWidth = 64; break;
1604	}
1605	if (tmp & R520_MC_CHANNEL_SIZE) {
1606	    info->RamWidth *= 2;
1607	}
1608    } else if ((info->ChipFamily >= CHIP_FAMILY_R300) &&
1609	       (info->ChipFamily <= CHIP_FAMILY_RV410)) {
1610	/* r3xx, r4xx */
1611	tmp = INREG(RADEON_MEM_CNTL);
1612	tmp &= R300_MEM_NUM_CHANNELS_MASK;
1613	switch (tmp) {
1614	case 0: info->RamWidth = 64; break;
1615	case 1: info->RamWidth = 128; break;
1616	case 2: info->RamWidth = 256; break;
1617	default: info->RamWidth = 128; break;
1618	}
1619    } else if ((info->ChipFamily == CHIP_FAMILY_RV100) ||
1620	       (info->ChipFamily == CHIP_FAMILY_RS100) ||
1621	       (info->ChipFamily == CHIP_FAMILY_RS200)){
1622	tmp = INREG(RADEON_MEM_CNTL);
1623	if (tmp & RV100_HALF_MODE)
1624	    info->RamWidth = 32;
1625	else
1626	    info->RamWidth = 64;
1627
1628	if (!pRADEONEnt->HasCRTC2) {
1629	    info->RamWidth /= 4;
1630	    info->IsDDR = TRUE;
1631	}
1632    } else if (info->ChipFamily <= CHIP_FAMILY_RV280) {
1633	tmp = INREG(RADEON_MEM_CNTL);
1634	if (tmp & RADEON_MEM_NUM_CHANNELS_MASK)
1635	    info->RamWidth = 128;
1636	else
1637	    info->RamWidth = 64;
1638    } else {
1639	/* newer IGPs */
1640	info->RamWidth = 128;
1641    }
1642
1643    /* This may not be correct, as some cards can have half of channel disabled
1644     * ToDo: identify these cases
1645     */
1646}
1647
1648/*
1649 * Depending on card genertation, chipset bugs, etc... the amount of vram
1650 * accessible to the CPU can vary. This function is our best shot at figuring
1651 * it out. Returns a value in KB.
1652 */
1653static uint32_t RADEONGetAccessibleVRAM(ScrnInfoPtr pScrn)
1654{
1655    RADEONInfoPtr  info   = RADEONPTR(pScrn);
1656    unsigned char *RADEONMMIO = info->MMIO;
1657    uint32_t	   aper_size;
1658    unsigned char  byte;
1659
1660    if (info->ChipFamily >= CHIP_FAMILY_CEDAR)
1661	/* size in MB on evergreen and fusion */
1662	aper_size = INREG(R600_CONFIG_APER_SIZE) * 1024;
1663    else if (info->ChipFamily >= CHIP_FAMILY_R600)
1664	aper_size = INREG(R600_CONFIG_APER_SIZE) / 1024;
1665    else
1666	aper_size = INREG(RADEON_CONFIG_APER_SIZE) / 1024;
1667
1668#ifdef XF86DRI
1669    /* If we use the DRI, we need to check if it's a version that has the
1670     * bug of always cropping MC_FB_LOCATION to one aperture, in which case
1671     * we need to limit the amount of accessible video memory
1672     */
1673    if (info->directRenderingEnabled &&
1674	info->dri->pKernelDRMVersion->version_minor < 23) {
1675	xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
1676		   "[dri] limiting video memory to one aperture of %uK\n",
1677		   (unsigned)aper_size);
1678	xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
1679		   "[dri] detected radeon kernel module version 1.%d but"
1680		   " 1.23 or newer is required for full memory mapping.\n",
1681		   info->dri->pKernelDRMVersion->version_minor);
1682	info->dri->newMemoryMap = FALSE;
1683	return aper_size;
1684    }
1685    info->dri->newMemoryMap = TRUE;
1686#endif /* XF86DRI */
1687
1688    if (info->ChipFamily >= CHIP_FAMILY_R600)
1689	return aper_size;
1690
1691    /* Set HDP_APER_CNTL only on cards that are known not to be broken,
1692     * that is has the 2nd generation multifunction PCI interface
1693     */
1694    if (info->ChipFamily == CHIP_FAMILY_RV280 ||
1695	info->ChipFamily == CHIP_FAMILY_RV350 ||
1696	info->ChipFamily == CHIP_FAMILY_RV380 ||
1697	info->ChipFamily == CHIP_FAMILY_R420 ||
1698	info->ChipFamily == CHIP_FAMILY_RV410 ||
1699	IS_AVIVO_VARIANT) {
1700	    OUTREGP (RADEON_HOST_PATH_CNTL, RADEON_HDP_APER_CNTL,
1701		     ~RADEON_HDP_APER_CNTL);
1702	    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
1703		       "Generation 2 PCI interface, using max accessible memory\n");
1704	    return aper_size * 2;
1705    }
1706
1707    /* Older cards have all sorts of funny issues to deal with. First
1708     * check if it's a multifunction card by reading the PCI config
1709     * header type... Limit those to one aperture size
1710     */
1711    PCI_READ_BYTE(info->PciInfo, &byte, 0xe);
1712    if (byte & 0x80) {
1713	xf86DrvMsg(pScrn->scrnIndex, X_INFO,
1714		   "Generation 1 PCI interface in multifunction mode"
1715		   ", accessible memory limited to one aperture\n");
1716	return aper_size;
1717    }
1718
1719    /* Single function older card. We read HDP_APER_CNTL to see how the BIOS
1720     * have set it up. We don't write this as it's broken on some ASICs but
1721     * we expect the BIOS to have done the right thing (might be too optimistic...)
1722     */
1723    if (INREG(RADEON_HOST_PATH_CNTL) & RADEON_HDP_APER_CNTL)
1724        return aper_size * 2;
1725
1726    return aper_size;
1727}
1728
1729static Bool RADEONPreInitVRAM(ScrnInfoPtr pScrn)
1730{
1731    RADEONInfoPtr  info   = RADEONPTR(pScrn);
1732    EntityInfoPtr  pEnt   = info->pEnt;
1733    GDevPtr        dev    = pEnt->device;
1734    unsigned char *RADEONMMIO = info->MMIO;
1735    MessageType    from = X_PROBED;
1736    uint32_t         accessible, bar_size;
1737
1738    if ((!IS_AVIVO_VARIANT) && info->IsIGP) {
1739	uint32_t tom = INREG(RADEON_NB_TOM);
1740
1741	pScrn->videoRam = (((tom >> 16) -
1742			    (tom & 0xffff) + 1) << 6);
1743
1744	OUTREG(RADEON_CONFIG_MEMSIZE, pScrn->videoRam * 1024);
1745    } else {
1746	if (info->ChipFamily >= CHIP_FAMILY_PALM)
1747	    /* R600_CONFIG_MEMSIZE is bytes on fusion */
1748	    pScrn->videoRam = INREG(R600_CONFIG_MEMSIZE) / 1024;
1749	else if (info->ChipFamily >= CHIP_FAMILY_CEDAR)
1750	    /* R600_CONFIG_MEMSIZE is MB on evergreen */
1751	    /* XXX watch for overflow!!! */
1752	    pScrn->videoRam = INREG(R600_CONFIG_MEMSIZE) * 1024;
1753	else if (info->ChipFamily >= CHIP_FAMILY_R600)
1754	    pScrn->videoRam = INREG(R600_CONFIG_MEMSIZE) / 1024;
1755	else {
1756	    /* Read VRAM size from card */
1757	    pScrn->videoRam      = INREG(RADEON_CONFIG_MEMSIZE) / 1024;
1758
1759	    /* Some production boards of m6 will return 0 if it's 8 MB */
1760	    if (pScrn->videoRam == 0) {
1761		pScrn->videoRam = 8192;
1762		OUTREG(RADEON_CONFIG_MEMSIZE, 0x800000);
1763	    }
1764	}
1765    }
1766
1767    /* Get accessible memory */
1768    accessible = RADEONGetAccessibleVRAM(pScrn);
1769
1770    /* Crop it to the size of the PCI BAR */
1771    bar_size = PCI_REGION_SIZE(info->PciInfo, 0) / 1024;
1772    if (bar_size == 0)
1773	bar_size = 0x20000;
1774    if (accessible > bar_size)
1775	accessible = bar_size;
1776
1777    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
1778	       "Detected total video RAM=%dK, accessible=%uK (PCI BAR=%uK)\n",
1779	       pScrn->videoRam, (unsigned)accessible, (unsigned)bar_size);
1780    if (pScrn->videoRam > accessible)
1781	pScrn->videoRam = accessible;
1782
1783    if (!IS_AVIVO_VARIANT) {
1784	info->MemCntl            = INREG(RADEON_SDRAM_MODE_REG);
1785	info->BusCntl            = INREG(RADEON_BUS_CNTL);
1786    }
1787
1788    RADEONGetVRamType(pScrn);
1789
1790    if (dev->videoRam) {
1791	xf86DrvMsg(pScrn->scrnIndex, X_INFO,
1792		   "Video RAM override, using %d kB instead of %d kB\n",
1793		   dev->videoRam,
1794		   pScrn->videoRam);
1795	from             = X_CONFIG;
1796	pScrn->videoRam  = dev->videoRam;
1797    }
1798
1799    xf86DrvMsg(pScrn->scrnIndex, from,
1800	       "Mapped VideoRAM: %d kByte (%d bit %s SDRAM)\n", pScrn->videoRam, info->RamWidth, info->IsDDR?"DDR":"SDR");
1801
1802    /* Do this before we truncate since we only map fb once */
1803    info->FbMapSize  = (pScrn->videoRam & ~1023) * 1024;
1804
1805    if (info->IsPrimary) {
1806	pScrn->videoRam /= 2;
1807	xf86DrvMsg(pScrn->scrnIndex, X_INFO,
1808		   "Using %dk of videoram for primary head\n",
1809		   pScrn->videoRam);
1810    } else if (info->IsSecondary) {
1811	pScrn->videoRam /= 2;
1812	xf86DrvMsg(pScrn->scrnIndex, X_INFO,
1813		   "Using %dk of videoram for secondary head\n",
1814		   pScrn->videoRam);
1815    }
1816    pScrn->videoRam  &= ~1023;
1817
1818    /* if the card is PCI Express reserve the last 32k for the gart table */
1819#ifdef XF86DRI
1820    if (info->cardType == CARD_PCIE && info->directRenderingEnabled)
1821      /* work out the size of pcie aperture */
1822        info->FbSecureSize = RADEONDRIGetPciAperTableSize(pScrn);
1823    else
1824#endif
1825	info->FbSecureSize = 0;
1826
1827    return TRUE;
1828}
1829
1830
1831/* This is called by RADEONPreInit to handle config file overrides for
1832 * things like chipset and memory regions.  Also determine memory size
1833 * and type.  If memory type ever needs an override, put it in this
1834 * routine.
1835 */
1836static Bool RADEONPreInitChipType(ScrnInfoPtr pScrn)
1837{
1838    RADEONInfoPtr  info   = RADEONPTR(pScrn);
1839    RADEONEntPtr pRADEONEnt = RADEONEntPriv(pScrn);
1840    EntityInfoPtr  pEnt   = info->pEnt;
1841    GDevPtr        dev    = pEnt->device;
1842    unsigned char *RADEONMMIO = info->MMIO;
1843    MessageType    from = X_PROBED;
1844    int i;
1845#ifdef XF86DRI
1846    const char *s;
1847    uint32_t cmd_stat;
1848#endif
1849
1850    /* Chipset */
1851    from = X_PROBED;
1852    if (dev->chipset && *dev->chipset) {
1853	info->Chipset  = xf86StringToToken(RADEONChipsets, dev->chipset);
1854	from           = X_CONFIG;
1855    } else if (dev->chipID >= 0) {
1856	info->Chipset  = dev->chipID;
1857	from           = X_CONFIG;
1858    } else {
1859	info->Chipset = PCI_DEV_DEVICE_ID(info->PciInfo);
1860    }
1861
1862    pScrn->chipset = (char *)xf86TokenToString(RADEONChipsets, info->Chipset);
1863    if (!pScrn->chipset) {
1864	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1865		   "ChipID 0x%04x is not recognized\n", info->Chipset);
1866	return FALSE;
1867    }
1868    if (info->Chipset < 0) {
1869	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1870		   "Chipset \"%s\" is not recognized\n", pScrn->chipset);
1871	return FALSE;
1872    }
1873    xf86DrvMsg(pScrn->scrnIndex, from,
1874	       "Chipset: \"%s\" (ChipID = 0x%04x)\n",
1875	       pScrn->chipset,
1876	       info->Chipset);
1877
1878    pRADEONEnt->HasCRTC2 = TRUE;
1879    info->IsMobility = FALSE;
1880    info->IsIGP = FALSE;
1881    info->IsDellServer = FALSE;
1882    info->HasSingleDAC = FALSE;
1883    info->InternalTVOut = TRUE;
1884    info->get_hardcoded_edid_from_bios = FALSE;
1885
1886    for (i = 0; i < sizeof(RADEONCards) / sizeof(RADEONCardInfo); i++) {
1887	if (info->Chipset == RADEONCards[i].pci_device_id) {
1888	    RADEONCardInfo *card = &RADEONCards[i];
1889	    info->ChipFamily = card->chip_family;
1890	    info->IsMobility = card->mobility;
1891	    info->IsIGP = card->igp;
1892	    pRADEONEnt->HasCRTC2 = !card->nocrtc2;
1893	    info->HasSingleDAC = card->singledac;
1894	    info->InternalTVOut = !card->nointtvout;
1895	    break;
1896	}
1897    }
1898
1899    if (info->ChipFamily >= CHIP_FAMILY_SUMO) {
1900	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1901		   "Chipset: \"%s\" (ChipID = 0x%04x) requires KMS\n",
1902		   pScrn->chipset,
1903		   info->Chipset);
1904	return FALSE;
1905    }
1906
1907    switch (info->Chipset) {
1908    case PCI_CHIP_RN50_515E:  /* RN50 is based on the RV100 but 3D isn't guaranteed to work.  YMMV. */
1909    case PCI_CHIP_RN50_5969:
1910	/* Some Sun servers have a hardcoded edid so KVMs work properly */
1911	if ((PCI_SUB_VENDOR_ID(info->PciInfo) == 0x108e) &&
1912	    (PCI_SUB_DEVICE_ID(info->PciInfo) == 0x4133))
1913	    info->get_hardcoded_edid_from_bios = TRUE;
1914    case PCI_CHIP_RV100_QY:
1915    case PCI_CHIP_RV100_QZ:
1916	/* DELL triple-head configuration. */
1917	if (((PCI_SUB_VENDOR_ID(info->PciInfo) == PCI_VENDOR_DELL) &&
1918	     ((PCI_SUB_DEVICE_ID(info->PciInfo) == 0x016c) ||
1919	      (PCI_SUB_DEVICE_ID(info->PciInfo) == 0x016d) ||
1920	      (PCI_SUB_DEVICE_ID(info->PciInfo) == 0x016e) ||
1921	      (PCI_SUB_DEVICE_ID(info->PciInfo) == 0x016f) ||
1922	      (PCI_SUB_DEVICE_ID(info->PciInfo) == 0x0170) ||
1923	      (PCI_SUB_DEVICE_ID(info->PciInfo) == 0x017d) ||
1924	      (PCI_SUB_DEVICE_ID(info->PciInfo) == 0x017e) ||
1925	      (PCI_SUB_DEVICE_ID(info->PciInfo) == 0x0183) ||
1926	      (PCI_SUB_DEVICE_ID(info->PciInfo) == 0x018a) ||
1927	      (PCI_SUB_DEVICE_ID(info->PciInfo) == 0x019a) ||
1928	      (PCI_SUB_DEVICE_ID(info->PciInfo) == 0x01b1) ||
1929	      (PCI_SUB_DEVICE_ID(info->PciInfo) == 0x01b2) ||
1930	      (PCI_SUB_DEVICE_ID(info->PciInfo) == 0x0205))) ||
1931           ((PCI_SUB_VENDOR_ID(info->PciInfo) == PCI_VENDOR_HP) &&
1932              (PCI_SUB_DEVICE_ID(info->PciInfo) == 0x31fb))) {
1933	    info->IsDellServer = TRUE;
1934	    xf86DrvMsg(pScrn->scrnIndex, X_INFO, "DELL/HP server detected, force to special setup\n");
1935	}
1936	break;
1937    case PCI_CHIP_RS482_5974:
1938	/* RH BZ 444586 - non mobility version
1939 	 * Dell appear to have the Vostro 1100 with a mobility part with the same pci-id */
1940	if ((PCI_SUB_VENDOR_ID(info->PciInfo) == 0x1462) &&
1941            (PCI_SUB_DEVICE_ID(info->PciInfo) == 0x7141)) {
1942		info->IsMobility = FALSE;
1943	}
1944    default:
1945	break;
1946    }
1947
1948    from               = X_PROBED;
1949    info->LinearAddr   = PCI_REGION_BASE(info->PciInfo, 0, REGION_MEM) & ~0x1ffffffULL;
1950    pScrn->memPhysBase = info->LinearAddr;
1951    if (dev->MemBase) {
1952	xf86DrvMsg(pScrn->scrnIndex, X_INFO,
1953		   "Linear address override, using 0x%016lx instead of 0x%016llx\n",
1954		   dev->MemBase,
1955		   info->LinearAddr);
1956	info->LinearAddr = dev->MemBase;
1957	from             = X_CONFIG;
1958    } else if (!info->LinearAddr) {
1959	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1960		   "No valid linear framebuffer address\n");
1961	return FALSE;
1962    }
1963    xf86DrvMsg(pScrn->scrnIndex, from,
1964	       "Linear framebuffer at 0x%016llx\n", info->LinearAddr);
1965
1966#ifndef XSERVER_LIBPCIACCESS
1967				/* BIOS */
1968    from              = X_PROBED;
1969    info->BIOSAddr    = info->PciInfo->biosBase & 0xfffe0000;
1970    if (info->BIOSAddr) {
1971	xf86DrvMsg(pScrn->scrnIndex, from,
1972		   "BIOS at 0x%08lx\n", (unsigned long)info->BIOSAddr);
1973    }
1974#endif
1975
1976				/* Read registers used to determine options */
1977    /* Check chip errata */
1978    info->ChipErrata = 0;
1979
1980    if (info->ChipFamily == CHIP_FAMILY_R300 &&
1981	(INREG(RADEON_CONFIG_CNTL) & RADEON_CFG_ATI_REV_ID_MASK)
1982	== RADEON_CFG_ATI_REV_A11)
1983	    info->ChipErrata |= CHIP_ERRATA_R300_CG;
1984
1985    if (info->ChipFamily == CHIP_FAMILY_RV200 ||
1986	info->ChipFamily == CHIP_FAMILY_RS200)
1987	    info->ChipErrata |= CHIP_ERRATA_PLL_DUMMYREADS;
1988
1989    if (info->ChipFamily == CHIP_FAMILY_RV100 ||
1990	info->ChipFamily == CHIP_FAMILY_RS100 ||
1991	info->ChipFamily == CHIP_FAMILY_RS200)
1992	    info->ChipErrata |= CHIP_ERRATA_PLL_DELAY;
1993
1994#ifdef XF86DRI
1995				/* AGP/PCI */
1996    /* Proper autodetection of an AGP capable device requires examining
1997     * PCI config registers to determine if the device implements extended
1998     * PCI capabilities, and then walking the capability list as indicated
1999     * in the PCI 2.2 and AGP 2.0 specifications, to determine if AGP
2000     * capability is present.  The procedure is outlined as follows:
2001     *
2002     * 1) Test bit 4 (CAP_LIST) of the PCI status register of the device
2003     *    to determine wether or not this device implements any extended
2004     *    capabilities.  If this bit is zero, then the device is a PCI 2.1
2005     *    or earlier device and is not AGP capable, and we can conclude it
2006     *    to be a PCI device.
2007     *
2008     * 2) If bit 4 of the status register is set, then the device implements
2009     *    extended capabilities.  There is an 8 bit wide capabilities pointer
2010     *    register located at offset 0x34 in PCI config space which points to
2011     *    the first capability in a linked list of extended capabilities that
2012     *    this device implements.  The lower two bits of this register are
2013     *    reserved and MBZ so must be masked out.
2014     *
2015     * 3) The extended capabilities list is formed by one or more extended
2016     *    capabilities structures which are aligned on DWORD boundaries.
2017     *    The first byte of the structure is the capability ID (CAP_ID)
2018     *    indicating what extended capability this structure refers to.  The
2019     *    second byte of the structure is an offset from the beginning of
2020     *    PCI config space pointing to the next capability in the linked
2021     *    list (NEXT_PTR) or NULL (0x00) at the end of the list.  The lower
2022     *    two bits of this pointer are reserved and MBZ.  By examining the
2023     *    CAP_ID of each capability and walking through the list, we will
2024     *    either find the AGP_CAP_ID (0x02) indicating this device is an
2025     *    AGP device, or we'll reach the end of the list, indicating it is
2026     *    a PCI device.
2027     *
2028     * Mike A. Harris <mharris@redhat.com>
2029     *
2030     * References:
2031     *	- PCI Local Bus Specification Revision 2.2, Chapter 6
2032     *	- AGP Interface Specification Revision 2.0, Section 6.1.5
2033     */
2034
2035    info->cardType = CARD_PCI;
2036
2037    PCI_READ_LONG(info->PciInfo, &cmd_stat, PCI_CMD_STAT_REG);
2038    if (cmd_stat & RADEON_CAP_LIST) {
2039	uint32_t cap_ptr, cap_id;
2040
2041	PCI_READ_LONG(info->PciInfo, &cap_ptr, RADEON_CAPABILITIES_PTR_PCI_CONFIG);
2042	cap_ptr &= RADEON_CAP_PTR_MASK;
2043
2044	while(cap_ptr != RADEON_CAP_ID_NULL) {
2045	    PCI_READ_LONG(info->PciInfo, &cap_id, cap_ptr);
2046	    if ((cap_id & 0xff)== RADEON_CAP_ID_AGP) {
2047		info->cardType = CARD_AGP;
2048		break;
2049	    }
2050	    if ((cap_id & 0xff)== RADEON_CAP_ID_EXP) {
2051		info->cardType = CARD_PCIE;
2052		break;
2053	    }
2054	    cap_ptr = (cap_id >> 8) & RADEON_CAP_PTR_MASK;
2055	}
2056    }
2057
2058    xf86DrvMsg(pScrn->scrnIndex, X_INFO, "%s card detected\n",
2059	       (info->cardType==CARD_PCI) ? "PCI" :
2060		(info->cardType==CARD_PCIE) ? "PCIE" : "AGP");
2061
2062    /* treat PCIE IGP cards as PCI */
2063    if (info->cardType == CARD_PCIE && info->IsIGP)
2064	info->cardType = CARD_PCI;
2065
2066    /* some rs4xx cards report as agp */
2067    if ((info->ChipFamily == CHIP_FAMILY_RS400) ||
2068	(info->ChipFamily == CHIP_FAMILY_RS480))
2069	info->cardType = CARD_PCI;
2070
2071    if ((info->ChipFamily >= CHIP_FAMILY_R600) && info->IsIGP)
2072	info->cardType = CARD_PCIE;
2073
2074    /* not sure about gart table requirements */
2075    if ((info->ChipFamily == CHIP_FAMILY_RS600) && info->IsIGP)
2076	info->cardType = CARD_PCIE;
2077
2078    if ((s = xf86GetOptValString(info->Options, OPTION_BUS_TYPE))) {
2079	if (strcmp(s, "AGP") == 0) {
2080	    info->cardType = CARD_AGP;
2081	    xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "Forced into AGP mode\n");
2082	} else if ((strcmp(s, "PCI") == 0) ||
2083		   (strcmp(s, "PCIE") == 0)) {
2084	    if ((info->ChipFamily == CHIP_FAMILY_RS400) ||
2085		(info->ChipFamily == CHIP_FAMILY_RS480) ||
2086		(info->ChipFamily == CHIP_FAMILY_RS690) ||
2087		(info->ChipFamily == CHIP_FAMILY_RS740)) {
2088		info->cardType = CARD_PCI;
2089		xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "Forced into PCI mode\n");
2090	    } else if (info->ChipFamily >= CHIP_FAMILY_RV380) {
2091		info->cardType = CARD_PCIE;
2092		xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "Forced into PCI Express mode\n");
2093	    } else {
2094		info->cardType = CARD_PCI;
2095		xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "Forced into PCI mode\n");
2096	    }
2097	} else {
2098	    xf86DrvMsg(pScrn->scrnIndex, X_CONFIG,
2099		       "Invalid BusType option, using detected type\n");
2100	}
2101    }
2102#endif
2103#ifdef RENDER
2104    info->RenderAccel = xf86ReturnOptValBool(info->Options, OPTION_RENDER_ACCEL,
2105					     info->Chipset != PCI_CHIP_RN50_515E &&
2106					     info->Chipset != PCI_CHIP_RN50_5969);
2107#endif
2108
2109    info->r4xx_atom = FALSE;
2110    if (((info->ChipFamily == CHIP_FAMILY_R420) || (info->ChipFamily == CHIP_FAMILY_RV410)) &&
2111	xf86ReturnOptValBool(info->Options, OPTION_R4XX_ATOM, FALSE)) {
2112	info->r4xx_atom = TRUE;
2113	xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "Using ATOMBIOS for R4xx chip\n");
2114    }
2115
2116    return TRUE;
2117}
2118
2119
2120static void RADEONPreInitDDC(ScrnInfoPtr pScrn)
2121{
2122    RADEONInfoPtr  info = RADEONPTR(pScrn);
2123 /* vbeInfoPtr     pVbe; */
2124
2125    info->ddc1     = FALSE;
2126    info->ddc_bios = FALSE;
2127    if (!xf86LoadSubModule(pScrn, "ddc")) {
2128	info->ddc2 = FALSE;
2129    } else {
2130	info->ddc2 = TRUE;
2131    }
2132
2133    /* DDC can use I2C bus */
2134    /* Load I2C if we have the code to use it */
2135    if (info->ddc2) {
2136	xf86LoadSubModule(pScrn, "i2c");
2137    }
2138}
2139
2140/* This is called by RADEONPreInit to initialize gamma correction */
2141static Bool RADEONPreInitGamma(ScrnInfoPtr pScrn)
2142{
2143    Gamma  zeros = { 0.0, 0.0, 0.0 };
2144
2145    if (!xf86SetGamma(pScrn, zeros)) return FALSE;
2146    return TRUE;
2147}
2148
2149/* This is called by RADEONPreInit to initialize the hardware cursor */
2150static Bool RADEONPreInitCursor(ScrnInfoPtr pScrn)
2151{
2152    RADEONInfoPtr  info = RADEONPTR(pScrn);
2153
2154    if (!xf86ReturnOptValBool(info->Options, OPTION_SW_CURSOR, FALSE)) {
2155	if (!xf86LoadSubModule(pScrn, "ramdac")) return FALSE;
2156    }
2157    return TRUE;
2158}
2159
2160/* This is called by RADEONPreInit to initialize hardware acceleration */
2161static Bool RADEONPreInitAccel(ScrnInfoPtr pScrn)
2162{
2163    RADEONInfoPtr  info = RADEONPTR(pScrn);
2164    MessageType from;
2165#if defined(USE_EXA) && defined(USE_XAA)
2166    char *optstr;
2167#endif
2168#ifdef XF86DRI /* zaphod FbMapSize is wrong, but no dri then */
2169    int maxy = info->FbMapSize / (pScrn->displayWidth * info->CurrentLayout.pixel_bytes);
2170#endif
2171
2172    if (!(info->accel_state = calloc(1, sizeof(struct radeon_accel_state)))) {
2173	xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Unable to allocate accel_state rec!\n");
2174	return FALSE;
2175    }
2176    info->accel_state->fifo_slots                 = 0;
2177
2178    if ((info->ChipFamily == CHIP_FAMILY_RS100) ||
2179	(info->ChipFamily == CHIP_FAMILY_RS200) ||
2180	(info->ChipFamily == CHIP_FAMILY_RS300) ||
2181	(info->ChipFamily == CHIP_FAMILY_RS400) ||
2182	(info->ChipFamily == CHIP_FAMILY_RS480) ||
2183	(info->ChipFamily == CHIP_FAMILY_RS600) ||
2184	(info->ChipFamily == CHIP_FAMILY_RS690) ||
2185	(info->ChipFamily == CHIP_FAMILY_RS740))
2186	info->accel_state->has_tcl = FALSE;
2187    else {
2188	info->accel_state->has_tcl = TRUE;
2189    }
2190
2191    /* if we have shadow fb bail */
2192    if (info->r600_shadow_fb) {
2193	info->useEXA = FALSE;
2194	return TRUE;
2195    }
2196
2197#ifdef XF86DRI
2198    if ((!info->directRenderingEnabled) ||
2199	(maxy <= pScrn->virtualY * 3) ||
2200	(pScrn->videoRam <= 32768))
2201	info->useEXA = FALSE;
2202    else
2203	info->useEXA = TRUE;
2204#else
2205	info->useEXA = FALSE;
2206#endif
2207
2208    if (!xf86ReturnOptValBool(info->Options, OPTION_NOACCEL, FALSE)) {
2209	int errmaj = 0, errmin = 0;
2210
2211	from = X_DEFAULT;
2212#if defined(USE_EXA)
2213#if defined(USE_XAA)
2214	optstr = (char *)xf86GetOptValString(info->Options, OPTION_ACCELMETHOD);
2215	if (optstr != NULL) {
2216	    if (xf86NameCmp(optstr, "EXA") == 0) {
2217		from = X_CONFIG;
2218		info->useEXA = TRUE;
2219	    } else if (xf86NameCmp(optstr, "XAA") == 0) {
2220		from = X_CONFIG;
2221		if (info->ChipFamily < CHIP_FAMILY_R600)
2222		    info->useEXA = FALSE;
2223	    }
2224	}
2225#else /* USE_XAA */
2226	info->useEXA = TRUE;
2227#endif /* !USE_XAA */
2228#else
2229	info->useEXA = FALSE;
2230#endif /* USE_EXA */
2231        if (info->ChipFamily < CHIP_FAMILY_R600)
2232	    xf86DrvMsg(pScrn->scrnIndex, from,
2233		       "Using %s acceleration architecture\n",
2234		       info->useEXA ? "EXA" : "XAA");
2235	else
2236	    xf86DrvMsg(pScrn->scrnIndex, X_DEFAULT,
2237		       "Will attempt to use R6xx/R7xx EXA support if DRI is enabled.\n");
2238
2239#ifdef USE_EXA
2240	if (info->useEXA) {
2241	    info->exaReq.majorversion = EXA_VERSION_MAJOR;
2242	    info->exaReq.minorversion = EXA_VERSION_MINOR;
2243
2244	    if (!LoadSubModule(pScrn->module, "exa", NULL, NULL, NULL,
2245			       &info->exaReq, &errmaj, &errmin)) {
2246		LoaderErrorMsg(NULL, "exa", errmaj, errmin);
2247		return FALSE;
2248	    }
2249	}
2250#endif /* USE_EXA */
2251#ifdef USE_XAA
2252	if (!info->useEXA) {
2253	    info->xaaReq.majorversion = 1;
2254	    info->xaaReq.minorversion = 2;
2255
2256	    if (!LoadSubModule(pScrn->module, "xaa", NULL, NULL, NULL,
2257			   &info->xaaReq, &errmaj, &errmin)) {
2258		info->xaaReq.minorversion = 1;
2259
2260		if (!LoadSubModule(pScrn->module, "xaa", NULL, NULL, NULL,
2261			       &info->xaaReq, &errmaj, &errmin)) {
2262		    info->xaaReq.minorversion = 0;
2263
2264		    if (!LoadSubModule(pScrn->module, "xaa", NULL, NULL, NULL,
2265			       &info->xaaReq, &errmaj, &errmin)) {
2266			LoaderErrorMsg(NULL, "xaa", errmaj, errmin);
2267			return FALSE;
2268		    }
2269		}
2270	    }
2271	}
2272#endif /* USE_XAA */
2273    } else {
2274	/* NoAccel */
2275	info->useEXA = FALSE;
2276    }
2277
2278    return TRUE;
2279}
2280
2281static Bool RADEONPreInitInt10(ScrnInfoPtr pScrn, xf86Int10InfoPtr *ppInt10)
2282{
2283#if (!defined(__powerpc__) && !defined(__sparc__)) || \
2284    (defined(XSERVER_LIBPCIACCESS) && HAVE_PCI_DEVICE_ENABLE)
2285    RADEONInfoPtr  info = RADEONPTR(pScrn);
2286#endif
2287#if !defined(__powerpc__) && !defined(__sparc__)
2288    unsigned char *RADEONMMIO = info->MMIO;
2289    uint32_t       fp2_gen_ctl_save   = 0;
2290#endif
2291
2292#ifdef XSERVER_LIBPCIACCESS
2293#if HAVE_PCI_DEVICE_ENABLE
2294    pci_device_enable(info->PciInfo);
2295#endif
2296#endif
2297
2298#if !defined(__powerpc__) && !defined(__sparc__)
2299    /* don't need int10 on atom cards.
2300     * in theory all radeons, but the older stuff
2301     * isn't 100% yet
2302     * secondary atom cards tend to hang when initializing int10,
2303     * however, on some stom cards, you can't read the bios without
2304     * intitializing int10.
2305     */
2306    if (!xf86ReturnOptValBool(info->Options, OPTION_INT10, TRUE))
2307	return TRUE;
2308
2309    if (xf86LoadSubModule(pScrn, "int10")) {
2310	/* The VGA BIOS on the RV100/QY cannot be read when the digital output
2311	 * is enabled.  Clear and restore FP2_ON around int10 to avoid this.
2312	 */
2313	if (PCI_DEV_DEVICE_ID(info->PciInfo) == PCI_CHIP_RV100_QY) {
2314	    fp2_gen_ctl_save = INREG(RADEON_FP2_GEN_CNTL);
2315	    if (fp2_gen_ctl_save & RADEON_FP2_ON) {
2316		xf86DrvMsg(pScrn->scrnIndex, X_INFO, "disabling digital out\n");
2317		OUTREG(RADEON_FP2_GEN_CNTL, fp2_gen_ctl_save & ~RADEON_FP2_ON);
2318	    }
2319	}
2320
2321	xf86DrvMsg(pScrn->scrnIndex,X_INFO,"initializing int10\n");
2322	*ppInt10 = xf86InitInt10(info->pEnt->index);
2323
2324	if (PCI_DEV_DEVICE_ID(info->PciInfo) == PCI_CHIP_RV100_QY) {
2325	    if (fp2_gen_ctl_save & RADEON_FP2_ON) {
2326		xf86DrvMsg(pScrn->scrnIndex, X_INFO, "re-enabling digital out\n");
2327		OUTREG(RADEON_FP2_GEN_CNTL, fp2_gen_ctl_save);
2328	    }
2329	}
2330    }
2331#endif
2332    return TRUE;
2333}
2334
2335#ifdef XF86DRI
2336static Bool RADEONPreInitDRI(ScrnInfoPtr pScrn)
2337{
2338    RADEONInfoPtr  info = RADEONPTR(pScrn);
2339    Bool           ret;
2340    MessageType    from;
2341    char          *reason;
2342
2343    info->directRenderingEnabled = FALSE;
2344    info->directRenderingInited = FALSE;
2345
2346    if (!(info->dri = calloc(1, sizeof(struct radeon_dri)))) {
2347	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,"Unable to allocate dri rec!\n");
2348	return FALSE;
2349    }
2350
2351    if (!(info->cp = calloc(1, sizeof(struct radeon_cp)))) {
2352	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,"Unable to allocate cp rec!\n");
2353	return FALSE;
2354    }
2355    info->cp->CPInUse = FALSE;
2356    info->cp->CPStarted = FALSE;
2357    info->cp->CPusecTimeout = RADEON_DEFAULT_CP_TIMEOUT;
2358
2359   if (xf86IsEntityShared(info->pEnt->index)) {
2360        xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
2361                   "Direct Rendering Disabled -- "
2362                   "Zaphod Dual-head configuration is not working with "
2363                   "DRI at present.\n"
2364                   "Please use the xrandr 1.2 if you "
2365                   "want Dual-head with DRI.\n");
2366        return FALSE;
2367    }
2368    if (info->IsSecondary)
2369        return FALSE;
2370
2371    if (info->ChipFamily >= CHIP_FAMILY_CEDAR) {
2372	xf86DrvMsg(pScrn->scrnIndex, X_INFO,
2373		   "No DRI yet on Evergreen\n");
2374	return FALSE;
2375    }
2376
2377    if (info->Chipset == PCI_CHIP_RN50_515E ||
2378	info->Chipset == PCI_CHIP_RN50_5969) {
2379	if (xf86ReturnOptValBool(info->Options, OPTION_DRI, FALSE)) {
2380	    xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
2381		"Direct rendering for RN50 forced on -- "
2382		"This is NOT officially supported at the hardware level "
2383		"and may cause instability or lockups\n");
2384	} else {
2385	    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
2386		"Direct rendering not officially supported on RN50\n");
2387	    return FALSE;
2388	}
2389    }
2390
2391    if (!xf86ReturnOptValBool(info->Options, OPTION_DRI, TRUE)) {
2392	xf86DrvMsg(pScrn->scrnIndex, X_INFO,
2393		"Direct rendering forced off\n");
2394	return FALSE;
2395    }
2396
2397    if (xf86ReturnOptValBool(info->Options, OPTION_NOACCEL, FALSE)) {
2398	xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
2399		   "[dri] Acceleration disabled, not initializing the DRI\n");
2400	return FALSE;
2401    }
2402
2403    info->dri->pLibDRMVersion = NULL;
2404    info->dri->pKernelDRMVersion = NULL;
2405
2406    ret = RADEONDRIGetVersion(pScrn);
2407    if (ret <= 0)
2408	return ret;
2409
2410    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
2411	       "[dri] Found DRI library version %d.%d.%d and kernel"
2412	       " module version %d.%d.%d\n",
2413	       info->dri->pLibDRMVersion->version_major,
2414	       info->dri->pLibDRMVersion->version_minor,
2415	       info->dri->pLibDRMVersion->version_patchlevel,
2416	       info->dri->pKernelDRMVersion->version_major,
2417	       info->dri->pKernelDRMVersion->version_minor,
2418	       info->dri->pKernelDRMVersion->version_patchlevel);
2419
2420    if (info->Chipset == PCI_CHIP_RS400_5A41 ||
2421	info->Chipset == PCI_CHIP_RS400_5A42 ||
2422	info->Chipset == PCI_CHIP_RC410_5A61 ||
2423	info->Chipset == PCI_CHIP_RC410_5A62 ||
2424	info->Chipset == PCI_CHIP_RS480_5954 ||
2425	info->Chipset == PCI_CHIP_RS480_5955 ||
2426	info->Chipset == PCI_CHIP_RS482_5974 ||
2427	info->Chipset == PCI_CHIP_RS485_5975) {
2428
2429	if (info->dri->pKernelDRMVersion->version_minor < 27) {
2430 	     xf86DrvMsg(pScrn->scrnIndex, X_INFO,
2431			"Direct rendering broken on XPRESS 200 and 200M with DRI less than 1.27\n");
2432	     return FALSE;
2433	}
2434 	xf86DrvMsg(pScrn->scrnIndex, X_INFO,
2435	"Direct rendering experimental on RS400/Xpress 200 enabled\n");
2436    }
2437
2438    if (info->ChipFamily >= CHIP_FAMILY_R300)
2439	info->dri->gartSize      = R300_DEFAULT_GART_SIZE;
2440    else
2441	info->dri->gartSize      = RADEON_DEFAULT_GART_SIZE;
2442
2443    info->dri->ringSize      = RADEON_DEFAULT_RING_SIZE;
2444    info->dri->bufSize       = RADEON_DEFAULT_BUFFER_SIZE;
2445    info->dri->gartTexSize   = RADEON_DEFAULT_GART_TEX_SIZE;
2446    info->dri->pciAperSize   = RADEON_DEFAULT_PCI_APER_SIZE;
2447    info->cp->CPusecTimeout = RADEON_DEFAULT_CP_TIMEOUT;
2448
2449    if ((xf86GetOptValInteger(info->Options,
2450			     OPTION_GART_SIZE, (int *)&(info->dri->gartSize))) ||
2451			     (xf86GetOptValInteger(info->Options,
2452			     OPTION_GART_SIZE_OLD, (int *)&(info->dri->gartSize)))) {
2453	switch (info->dri->gartSize) {
2454	case 4:
2455	case 8:
2456	case 16:
2457	case 32:
2458	case 64:
2459	case 128:
2460	case 256:
2461	    break;
2462
2463	default:
2464	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
2465		       "Illegal GART size: %d MB\n", info->dri->gartSize);
2466	    return FALSE;
2467	}
2468    }
2469
2470    if (xf86GetOptValInteger(info->Options,
2471			     OPTION_RING_SIZE, &(info->dri->ringSize))) {
2472	if (info->dri->ringSize < 1 || info->dri->ringSize >= (int)info->dri->gartSize) {
2473	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
2474		       "Illegal ring buffer size: %d MB\n",
2475		       info->dri->ringSize);
2476	    return FALSE;
2477	}
2478    }
2479
2480    if (xf86GetOptValInteger(info->Options,
2481			     OPTION_PCIAPER_SIZE, &(info->dri->pciAperSize))) {
2482      switch(info->dri->pciAperSize) {
2483      case 32:
2484      case 64:
2485      case 128:
2486      case 256:
2487	break;
2488      default:
2489	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
2490		       "Illegal pci aper size: %d MB\n",
2491		       info->dri->pciAperSize);
2492	return FALSE;
2493      }
2494    }
2495
2496
2497    if (xf86GetOptValInteger(info->Options,
2498			     OPTION_BUFFER_SIZE, &(info->dri->bufSize))) {
2499	if (info->dri->bufSize < 1 || info->dri->bufSize >= (int)info->dri->gartSize) {
2500	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
2501		       "Illegal vertex/indirect buffers size: %d MB\n",
2502		       info->dri->bufSize);
2503	    return FALSE;
2504	}
2505	if (info->dri->bufSize > 2) {
2506	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
2507		       "Illegal vertex/indirect buffers size: %d MB\n",
2508		       info->dri->bufSize);
2509	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
2510		       "Clamping vertex/indirect buffers size to 2 MB\n");
2511	    info->dri->bufSize = 2;
2512	}
2513    }
2514
2515    if (info->dri->ringSize + info->dri->bufSize + info->dri->gartTexSize >
2516	(int)info->dri->gartSize) {
2517	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
2518		   "Buffers are too big for requested GART space\n");
2519	return FALSE;
2520    }
2521
2522    info->dri->gartTexSize = info->dri->gartSize - (info->dri->ringSize + info->dri->bufSize);
2523
2524    if (xf86GetOptValInteger(info->Options, OPTION_USEC_TIMEOUT,
2525			     &(info->cp->CPusecTimeout))) {
2526	/* This option checked by the RADEON DRM kernel module */
2527    }
2528
2529    /* Two options to try and squeeze as much texture memory as possible
2530     * for dedicated 3d rendering boxes
2531     */
2532    info->dri->noBackBuffer = xf86ReturnOptValBool(info->Options,
2533						   OPTION_NO_BACKBUFFER,
2534						   FALSE);
2535
2536    info->dri->allowPageFlip = 0;
2537
2538#ifdef DAMAGE
2539    if (info->dri->noBackBuffer) {
2540	from = X_DEFAULT;
2541	reason = " because back buffer disabled";
2542    } else {
2543	from = xf86GetOptValBool(info->Options, OPTION_PAGE_FLIP,
2544				 &info->dri->allowPageFlip) ? X_CONFIG : X_DEFAULT;
2545
2546	if (IS_AVIVO_VARIANT) {
2547	    info->dri->allowPageFlip = 0;
2548	    reason = " on r5xx and newer chips.\n";
2549	} else {
2550	    reason = "";
2551	}
2552
2553    }
2554#else
2555    from = X_DEFAULT;
2556    reason = " because Damage layer not available at build time";
2557#endif
2558
2559    xf86DrvMsg(pScrn->scrnIndex, from, "Page Flipping %sabled%s\n",
2560	       info->dri->allowPageFlip ? "en" : "dis", reason);
2561
2562    /* AGP seems to have problems with gart transfers */
2563    if ((info->ChipFamily >= CHIP_FAMILY_R600) && (info->cardType == CARD_AGP))
2564	info->DMAForXv = FALSE;
2565    else
2566	info->DMAForXv = TRUE;
2567    from = xf86GetOptValBool(info->Options, OPTION_XV_DMA, &info->DMAForXv)
2568	 ? X_CONFIG : X_INFO;
2569    xf86DrvMsg(pScrn->scrnIndex, from,
2570	       "Will %stry to use DMA for Xv image transfers\n",
2571	       info->DMAForXv ? "" : "not ");
2572
2573    return TRUE;
2574}
2575#endif /* XF86DRI */
2576
2577static void RADEONPreInitColorTiling(ScrnInfoPtr pScrn)
2578{
2579    RADEONInfoPtr  info = RADEONPTR(pScrn);
2580
2581    info->allowColorTiling = xf86ReturnOptValBool(info->Options,
2582				        OPTION_COLOR_TILING, TRUE);
2583    if (IS_R300_VARIANT || IS_AVIVO_VARIANT) {
2584	/* this may be 4096 on r4xx -- need to double check */
2585	info->MaxSurfaceWidth = 3968; /* one would have thought 4096...*/
2586	info->MaxLines = 4096;
2587    } else {
2588	info->MaxSurfaceWidth = 2048;
2589	info->MaxLines = 2048;
2590    }
2591
2592    if (!info->allowColorTiling)
2593	return;
2594
2595    if (info->ChipFamily >= CHIP_FAMILY_R600)
2596	info->allowColorTiling = FALSE;
2597
2598    /* for zaphod disable tiling for now */
2599    if (info->IsPrimary || info->IsSecondary)
2600	info->allowColorTiling = FALSE;
2601
2602#ifdef XF86DRI
2603    if (info->directRenderingEnabled &&
2604	info->dri->pKernelDRMVersion->version_minor < 14) {
2605	xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
2606		   "[dri] color tiling disabled because of version "
2607		   "mismatch.\n"
2608		   "[dri] radeon.o kernel module version is %d.%d.%d but "
2609		   "1.14.0 or later is required for color tiling.\n",
2610		   info->dri->pKernelDRMVersion->version_major,
2611		   info->dri->pKernelDRMVersion->version_minor,
2612		   info->dri->pKernelDRMVersion->version_patchlevel);
2613	   info->allowColorTiling = FALSE;
2614	   return;
2615    }
2616#endif /* XF86DRI */
2617
2618    if (info->allowColorTiling) {
2619	xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Color tiling enabled by default\n");
2620    } else {
2621	xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Color tiling disabled\n");
2622    }
2623}
2624
2625
2626static Bool RADEONPreInitXv(ScrnInfoPtr pScrn)
2627{
2628    RADEONInfoPtr  info = RADEONPTR(pScrn);
2629    uint16_t mm_table;
2630    uint16_t bios_header;
2631    uint16_t pll_info_block;
2632#ifdef XvExtension
2633    char* microc_path = NULL;
2634    char* microc_type = NULL;
2635    MessageType from;
2636
2637    if (xf86GetOptValInteger(info->Options, OPTION_VIDEO_KEY,
2638			     &(info->videoKey))) {
2639	xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "video key set to 0x%x\n",
2640		   info->videoKey);
2641    } else {
2642	info->videoKey = 0x1E;
2643    }
2644
2645    if(xf86GetOptValInteger(info->Options, OPTION_RAGE_THEATRE_CRYSTAL, &(info->RageTheatreCrystal))) {
2646        xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "Rage Theatre Crystal frequency was specified as %d.%d Mhz\n",
2647                                info->RageTheatreCrystal/100, info->RageTheatreCrystal % 100);
2648    } else {
2649	info->RageTheatreCrystal=-1;
2650    }
2651
2652    if(xf86GetOptValInteger(info->Options, OPTION_RAGE_THEATRE_TUNER_PORT, &(info->RageTheatreTunerPort))) {
2653        xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "Rage Theatre tuner port was specified as %d\n",
2654                                info->RageTheatreTunerPort);
2655    } else {
2656	info->RageTheatreTunerPort=-1;
2657    }
2658
2659    if(info->RageTheatreTunerPort>5){
2660         xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Attempt to assign Rage Theatre tuner port to invalid value. Disabling setting\n");
2661	 info->RageTheatreTunerPort=-1;
2662	 }
2663
2664    if(xf86GetOptValInteger(info->Options, OPTION_RAGE_THEATRE_COMPOSITE_PORT, &(info->RageTheatreCompositePort))) {
2665        xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "Rage Theatre composite port was specified as %d\n",
2666                                info->RageTheatreCompositePort);
2667    } else {
2668	info->RageTheatreCompositePort=-1;
2669    }
2670
2671    if(info->RageTheatreCompositePort>6){
2672         xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Attempt to assign Rage Theatre composite port to invalid value. Disabling setting\n");
2673	 info->RageTheatreCompositePort=-1;
2674	 }
2675
2676    if(xf86GetOptValInteger(info->Options, OPTION_RAGE_THEATRE_SVIDEO_PORT, &(info->RageTheatreSVideoPort))) {
2677        xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "Rage Theatre SVideo Port was specified as %d\n",
2678                                info->RageTheatreSVideoPort);
2679    } else {
2680	info->RageTheatreSVideoPort=-1;
2681    }
2682
2683    if(info->RageTheatreSVideoPort>6){
2684         xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Attempt to assign Rage Theatre SVideo port to invalid value. Disabling setting\n");
2685	 info->RageTheatreSVideoPort=-1;
2686	 }
2687
2688    if(xf86GetOptValInteger(info->Options, OPTION_TUNER_TYPE, &(info->tunerType))) {
2689        xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "Tuner type was specified as %d\n",
2690                                info->tunerType);
2691    } else {
2692	info->tunerType=-1;
2693    }
2694
2695    if(info->tunerType>31){
2696         xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Attempt to set tuner type to invalid value. Disabling setting\n");
2697	 info->tunerType=-1;
2698	 }
2699
2700	if((microc_path = xf86GetOptValString(info->Options, OPTION_RAGE_THEATRE_MICROC_PATH)) != NULL)
2701	{
2702		xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "Rage Theatre Microcode path was specified as %s\n", microc_path);
2703		info->RageTheatreMicrocPath = microc_path;
2704    } else {
2705		info->RageTheatreMicrocPath= NULL;
2706    }
2707
2708	if((microc_type = xf86GetOptValString(info->Options, OPTION_RAGE_THEATRE_MICROC_TYPE)) != NULL)
2709	{
2710		xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "Rage Theatre Microcode type was specified as %s\n", microc_type);
2711		info->RageTheatreMicrocType = microc_type;
2712	} else {
2713		info->RageTheatreMicrocType= NULL;
2714	}
2715
2716    if(xf86GetOptValInteger(info->Options, OPTION_SCALER_WIDTH, &(info->overlay_scaler_buffer_width))) {
2717	if ((info->overlay_scaler_buffer_width < 1024) ||
2718	  (info->overlay_scaler_buffer_width > 2048) ||
2719	  ((info->overlay_scaler_buffer_width % 64) != 0)) {
2720	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Attempt to set illegal scaler width. Using default\n");
2721	    from = X_DEFAULT;
2722	    info->overlay_scaler_buffer_width = 0;
2723	} else
2724	    from = X_CONFIG;
2725    } else {
2726	from = X_DEFAULT;
2727	info->overlay_scaler_buffer_width = 0;
2728    }
2729    if (!info->overlay_scaler_buffer_width) {
2730       /* overlay scaler line length differs for different revisions
2731       this needs to be maintained by hand  */
2732	switch(info->ChipFamily){
2733	case CHIP_FAMILY_R200:
2734	case CHIP_FAMILY_R300:
2735	case CHIP_FAMILY_R350:
2736	case CHIP_FAMILY_RV350:
2737	case CHIP_FAMILY_RV380:
2738	case CHIP_FAMILY_R420:
2739	case CHIP_FAMILY_RV410:
2740		info->overlay_scaler_buffer_width = 1920;
2741		break;
2742	default:
2743		info->overlay_scaler_buffer_width = 1536;
2744	}
2745    }
2746    xf86DrvMsg(pScrn->scrnIndex, from, "Assuming overlay scaler buffer width is %d\n",
2747	info->overlay_scaler_buffer_width);
2748#endif
2749
2750    /* Rescue MM_TABLE before VBIOS is freed */
2751    info->MM_TABLE_valid = FALSE;
2752
2753    if((info->VBIOS==NULL)||(info->VBIOS[0]!=0x55)||(info->VBIOS[1]!=0xaa)){
2754       xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Cannot access BIOS or it is not valid.\n"
2755               "\t\tIf your card is TV-in capable you will need to specify options RageTheatreCrystal, RageTheatreTunerPort, \n"
2756               "\t\tRageTheatreSVideoPort and TunerType in /etc/X11/xorg.conf.\n"
2757               );
2758       info->MM_TABLE_valid = FALSE;
2759       return TRUE;
2760       }
2761
2762    bios_header=info->VBIOS[0x48];
2763    bios_header+=(((int)info->VBIOS[0x49]+0)<<8);
2764
2765    mm_table=info->VBIOS[bios_header+0x38];
2766    if(mm_table==0)
2767    {
2768        xf86DrvMsg(pScrn->scrnIndex,X_INFO,"No MM_TABLE found - assuming CARD is not TV-in capable.\n");
2769        info->MM_TABLE_valid = FALSE;
2770        return TRUE;
2771    }
2772    mm_table+=(((int)info->VBIOS[bios_header+0x39]+0)<<8)-2;
2773
2774    if(mm_table>0)
2775    {
2776        memcpy(&(info->MM_TABLE), &(info->VBIOS[mm_table]), sizeof(info->MM_TABLE));
2777        xf86DrvMsg(pScrn->scrnIndex, X_INFO, "MM_TABLE: %02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x\n",
2778            info->MM_TABLE.table_revision,
2779            info->MM_TABLE.table_size,
2780            info->MM_TABLE.tuner_type,
2781            info->MM_TABLE.audio_chip,
2782            info->MM_TABLE.product_id,
2783            info->MM_TABLE.tuner_voltage_teletext_fm,
2784            info->MM_TABLE.i2s_config,
2785            info->MM_TABLE.video_decoder_type,
2786            info->MM_TABLE.video_decoder_host_config,
2787            info->MM_TABLE.input[0],
2788            info->MM_TABLE.input[1],
2789            info->MM_TABLE.input[2],
2790            info->MM_TABLE.input[3],
2791            info->MM_TABLE.input[4]);
2792
2793	  /* Is it an MM_TABLE we know about ? */
2794	  if(info->MM_TABLE.table_size != 0xc){
2795	       xf86DrvMsg(pScrn->scrnIndex, X_INFO, "This card has MM_TABLE we do not recognize.\n"
2796			"\t\tIf your card is TV-in capable you will need to specify options RageTheatreCrystal, RageTheatreTunerPort, \n"
2797			"\t\tRageTheatreSVideoPort and TunerType in /etc/X11/xorg.conf.\n"
2798			);
2799		info->MM_TABLE_valid = FALSE;
2800		return TRUE;
2801	  	}
2802        info->MM_TABLE_valid = TRUE;
2803    } else {
2804        xf86DrvMsg(pScrn->scrnIndex, X_INFO, "No MM_TABLE found - assuming card is not TV-in capable (mm_table=%d).\n", mm_table);
2805        info->MM_TABLE_valid = FALSE;
2806    }
2807
2808    pll_info_block=info->VBIOS[bios_header+0x30];
2809    pll_info_block+=(((int)info->VBIOS[bios_header+0x31]+0)<<8);
2810
2811    info->video_decoder_type=info->VBIOS[pll_info_block+0x08];
2812    info->video_decoder_type+=(((int)info->VBIOS[pll_info_block+0x09]+0)<<8);
2813
2814    return TRUE;
2815}
2816
2817static Bool
2818RADEONPreInitBIOS(ScrnInfoPtr pScrn, xf86Int10InfoPtr  pInt10)
2819{
2820    RADEONInfoPtr info = RADEONPTR(pScrn);
2821
2822    if (!RADEONGetBIOSInfo(pScrn, pInt10)) {
2823	/* Avivo chips require bios for atom */
2824	if (IS_AVIVO_VARIANT)
2825	    return FALSE;
2826    }
2827    return TRUE;
2828}
2829
2830Bool
2831RADEONZaphodStringMatches(ScrnInfoPtr pScrn, const char *s, char *output_name)
2832{
2833    int i = 0;
2834    char s1[20];
2835
2836    do {
2837	switch(*s) {
2838	case ',':
2839	    s1[i] = '\0';
2840	    i = 0;
2841	    if (strcmp(s1, output_name) == 0)
2842		return TRUE;
2843	    break;
2844	case ' ':
2845	case '\t':
2846	case '\n':
2847	case '\r':
2848	    break;
2849	default:
2850	    s1[i] = *s;
2851	    i++;
2852	    break;
2853	}
2854    } while(*s++);
2855
2856    s1[i] = '\0';
2857    if (strcmp(s1, output_name) == 0)
2858	return TRUE;
2859
2860    return FALSE;
2861}
2862
2863static void RADEONFixZaphodOutputs(ScrnInfoPtr pScrn)
2864{
2865    RADEONInfoPtr info = RADEONPTR(pScrn);
2866    xf86CrtcConfigPtr   config = XF86_CRTC_CONFIG_PTR(pScrn);
2867    int o;
2868    char *s;
2869
2870    if ((s = xf86GetOptValString(info->Options, OPTION_ZAPHOD_HEADS))) {
2871	for (o = config->num_output; o > 0; o--) {
2872	    if (!RADEONZaphodStringMatches(pScrn, s, config->output[o - 1]->name))
2873		xf86OutputDestroy(config->output[o - 1]);
2874	}
2875    } else {
2876	if (info->IsPrimary) {
2877	    xf86OutputDestroy(config->output[0]);
2878	    while (config->num_output > 1) {
2879		xf86OutputDestroy(config->output[1]);
2880	    }
2881	} else {
2882	    while (config->num_output > 1) {
2883		xf86OutputDestroy(config->output[1]);
2884	    }
2885	}
2886    }
2887}
2888
2889static Bool RADEONPreInitControllers(ScrnInfoPtr pScrn)
2890{
2891    xf86CrtcConfigPtr   config = XF86_CRTC_CONFIG_PTR(pScrn);
2892    RADEONInfoPtr info = RADEONPTR(pScrn);
2893    int i;
2894    int mask;
2895    int found = 0;
2896
2897    if (info->IsPrimary)
2898	mask = 1;
2899    else if (info->IsSecondary)
2900	mask = 2;
2901    else
2902	mask = 3;
2903
2904    if (!RADEONAllocateControllers(pScrn, mask))
2905	return FALSE;
2906
2907    RADEONGetClockInfo(pScrn);
2908
2909    if (info->IsAtomBios && info->IsIGP)
2910	RADEONATOMGetIGPInfo(pScrn);
2911
2912    if (!RADEONSetupConnectors(pScrn)) {
2913	return FALSE;
2914    }
2915
2916    if (info->IsPrimary || info->IsSecondary) {
2917	/* fixup outputs for zaphod */
2918	RADEONFixZaphodOutputs(pScrn);
2919    }
2920
2921    RADEONPrintPortMap(pScrn);
2922
2923    info->first_load_no_devices = FALSE;
2924    for (i = 0; i < config->num_output; i++) {
2925	xf86OutputPtr	      output = config->output[i];
2926
2927	output->status = (*output->funcs->detect) (output);
2928	ErrorF("finished output detect: %d\n", i);
2929	if (info->IsPrimary || info->IsSecondary) {
2930	    if (output->status != XF86OutputStatusConnected)
2931		return FALSE;
2932	}
2933	if (output->status != XF86OutputStatusDisconnected)
2934	    found++;
2935    }
2936
2937    if (!found) {
2938	/* nothing connected, light up some defaults so the server comes up */
2939	xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "No connected devices found!\n");
2940	info->first_load_no_devices = TRUE;
2941    }
2942
2943    ErrorF("finished all detect\n");
2944    return TRUE;
2945}
2946
2947static void
2948RADEONProbeDDC(ScrnInfoPtr pScrn, int indx)
2949{
2950    vbeInfoPtr  pVbe;
2951
2952    if (xf86LoadSubModule(pScrn, "vbe")) {
2953	pVbe = VBEInit(NULL,indx);
2954	ConfiguredMonitor = vbeDoEDID(pVbe, NULL);
2955	vbeFree(pVbe);
2956    }
2957}
2958
2959static Bool
2960RADEONCRTCResize(ScrnInfoPtr scrn, int width, int height)
2961{
2962    scrn->virtualX = width;
2963    scrn->virtualY = height;
2964    /* RADEONSetPitch(scrn); */
2965    return TRUE;
2966}
2967
2968static const xf86CrtcConfigFuncsRec RADEONCRTCResizeFuncs = {
2969    RADEONCRTCResize
2970};
2971
2972Bool RADEONPreInit(ScrnInfoPtr pScrn, int flags)
2973{
2974    xf86CrtcConfigPtr   xf86_config;
2975    RADEONInfoPtr     info;
2976    xf86Int10InfoPtr  pInt10 = NULL;
2977    void *int10_save = NULL;
2978    const char *s;
2979    RADEONEntPtr pRADEONEnt;
2980    DevUnion* pPriv;
2981
2982    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
2983		   "RADEONPreInit\n");
2984    if (pScrn->numEntities != 1) return FALSE;
2985
2986    if (!RADEONGetRec(pScrn)) return FALSE;
2987
2988    info               = RADEONPTR(pScrn);
2989    info->MMIO         = NULL;
2990
2991    info->IsSecondary  = FALSE;
2992    info->IsPrimary = FALSE;
2993    info->kms_enabled = FALSE;
2994
2995    info->pEnt         = xf86GetEntityInfo(pScrn->entityList[pScrn->numEntities - 1]);
2996    if (info->pEnt->location.type != BUS_PCI) goto fail;
2997
2998    pPriv = xf86GetEntityPrivate(pScrn->entityList[0],
2999				 getRADEONEntityIndex());
3000    pRADEONEnt = pPriv->ptr;
3001
3002    if(xf86IsEntityShared(pScrn->entityList[0]))
3003    {
3004        if(xf86IsPrimInitDone(pScrn->entityList[0]))
3005        {
3006            info->IsSecondary = TRUE;
3007            pRADEONEnt->pSecondaryScrn = pScrn;
3008	    info->SavedReg = &pRADEONEnt->SavedReg;
3009	    info->ModeReg = &pRADEONEnt->ModeReg;
3010        }
3011        else
3012        {
3013	    info->IsPrimary = TRUE;
3014            xf86SetPrimInitDone(pScrn->entityList[0]);
3015            pRADEONEnt->pPrimaryScrn = pScrn;
3016            pRADEONEnt->HasSecondary = FALSE;
3017	    info->SavedReg = &pRADEONEnt->SavedReg;
3018	    info->ModeReg = &pRADEONEnt->ModeReg;
3019        }
3020    } else {
3021	info->SavedReg = &pRADEONEnt->SavedReg;
3022	info->ModeReg = &pRADEONEnt->ModeReg;
3023    }
3024
3025    info->PciInfo = xf86GetPciInfoForEntity(info->pEnt->index);
3026#ifndef XSERVER_LIBPCIACCESS
3027    info->PciTag  = pciTag(PCI_DEV_BUS(info->PciInfo),
3028			   PCI_DEV_DEV(info->PciInfo),
3029			   PCI_DEV_FUNC(info->PciInfo));
3030#endif
3031    info->MMIOAddr = PCI_REGION_BASE(info->PciInfo, 2, REGION_MEM) & ~0xffULL;
3032    info->MMIOSize = PCI_REGION_SIZE(info->PciInfo, 2);
3033	xf86DrvMsg(pScrn->scrnIndex, X_INFO, "TOTO SAYS %016llx\n",
3034		(unsigned long long)PCI_REGION_BASE(info->PciInfo,
3035		2, REGION_MEM));
3036    if (info->pEnt->device->IOBase) {
3037	xf86DrvMsg(pScrn->scrnIndex, X_CONFIG,
3038		   "MMIO address override, using 0x%08lx instead of 0x%016llx\n",
3039		   info->pEnt->device->IOBase,
3040		   info->MMIOAddr);
3041	info->MMIOAddr = info->pEnt->device->IOBase;
3042    } else if (!info->MMIOAddr) {
3043	xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "No valid MMIO address\n");
3044	goto fail1;
3045    }
3046    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
3047	       "MMIO registers at 0x%016llx: size %ldKB\n", info->MMIOAddr, info->MMIOSize / 1024);
3048
3049    if(!RADEONMapMMIO(pScrn)) {
3050	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
3051		   "Memory map the MMIO region failed\n");
3052	goto fail1;
3053    }
3054
3055#if !defined(__alpha__)
3056    if (
3057#ifndef XSERVER_LIBPCIACCESS
3058	xf86GetPciDomain(info->PciTag) ||
3059#endif
3060	!xf86IsPrimaryPci(info->PciInfo))
3061	RADEONPreInt10Save(pScrn, &int10_save);
3062#else
3063    /* [Alpha] On the primary, the console already ran the BIOS and we're
3064     *         going to run it again - so make sure to "fix up" the card
3065     *         so that (1) we can read the BIOS ROM and (2) the BIOS will
3066     *         get the memory config right.
3067     */
3068    RADEONPreInt10Save(pScrn, &int10_save);
3069#endif
3070
3071    if (flags & PROBE_DETECT) {
3072	RADEONProbeDDC(pScrn, info->pEnt->index);
3073	RADEONPostInt10Check(pScrn, int10_save);
3074	if(info->MMIO) RADEONUnmapMMIO(pScrn);
3075	return TRUE;
3076    }
3077
3078
3079    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
3080	       "PCI bus %d card %d func %d\n",
3081	       PCI_DEV_BUS(info->PciInfo),
3082	       PCI_DEV_DEV(info->PciInfo),
3083	       PCI_DEV_FUNC(info->PciInfo));
3084
3085#ifndef XSERVER_LIBPCIACCESS
3086    if (xf86RegisterResources(info->pEnt->index, 0, ResExclusive))
3087	goto fail;
3088
3089    xf86SetOperatingState(resVga, info->pEnt->index, ResUnusedOpr);
3090
3091    pScrn->racMemFlags = RAC_FB | RAC_COLORMAP | RAC_VIEWPORT | RAC_CURSOR;
3092#endif
3093    pScrn->monitor     = pScrn->confScreen->monitor;
3094
3095   /* Allocate an xf86CrtcConfig */
3096    xf86CrtcConfigInit (pScrn, &RADEONCRTCResizeFuncs);
3097    xf86_config = XF86_CRTC_CONFIG_PTR(pScrn);
3098
3099
3100    if (!RADEONPreInitVisual(pScrn))
3101	goto fail;
3102
3103				/* We can't do this until we have a
3104				   pScrn->display. */
3105    xf86CollectOptions(pScrn, NULL);
3106    if (!(info->Options = malloc(sizeof(RADEONOptions))))
3107	goto fail;
3108
3109    memcpy(info->Options, RADEONOptions, sizeof(RADEONOptions));
3110    xf86ProcessOptions(pScrn->scrnIndex, pScrn->options, info->Options);
3111
3112    /* By default, don't do VGA IOs on ppc/sparc */
3113#if defined(__powerpc__) || defined(__sparc__) || !defined(WITH_VGAHW)
3114    info->VGAAccess = FALSE;
3115#else
3116    info->VGAAccess = TRUE;
3117#endif
3118
3119#ifdef WITH_VGAHW
3120    xf86GetOptValBool(info->Options, OPTION_VGA_ACCESS, &info->VGAAccess);
3121    if (info->VGAAccess) {
3122       if (!xf86LoadSubModule(pScrn, "vgahw"))
3123           info->VGAAccess = FALSE;
3124        else {
3125            if (!vgaHWGetHWRec(pScrn))
3126               info->VGAAccess = FALSE;
3127       }
3128       if (!info->VGAAccess)
3129           xf86DrvMsg(pScrn->scrnIndex, X_WARNING, "Loading VGA module failed,"
3130                      " trying to run without it\n");
3131    } else
3132           xf86DrvMsg(pScrn->scrnIndex, X_INFO, "VGAAccess option set to FALSE,"
3133                      " VGA module load skipped\n");
3134    if (info->VGAAccess) {
3135	vgaHWSetStdFuncs(VGAHWPTR(pScrn));
3136        vgaHWGetIOBase(VGAHWPTR(pScrn));
3137    }
3138#endif
3139
3140
3141    if (!RADEONPreInitWeight(pScrn))
3142	goto fail;
3143
3144    info->DispPriority = 1;
3145    if ((s = xf86GetOptValString(info->Options, OPTION_DISP_PRIORITY))) {
3146	if (strcmp(s, "AUTO") == 0) {
3147	    info->DispPriority = 1;
3148	} else if (strcmp(s, "BIOS") == 0) {
3149	    info->DispPriority = 0;
3150	} else if (strcmp(s, "HIGH") == 0) {
3151	    info->DispPriority = 2;
3152	} else
3153	    info->DispPriority = 1;
3154    }
3155
3156    if (!RADEONPreInitChipType(pScrn))
3157	goto fail;
3158
3159    if (!RADEONPreInitInt10(pScrn, &pInt10))
3160	goto fail;
3161
3162    RADEONPostInt10Check(pScrn, int10_save);
3163
3164    if (!RADEONPreInitBIOS(pScrn, pInt10))
3165	goto fail;
3166
3167    /* Save BIOS scratch registers */
3168    RADEONSaveBIOSRegisters(pScrn, info->SavedReg);
3169
3170#ifdef XF86DRI
3171    /* PreInit DRI first of all since we need that for getting a proper
3172     * memory map
3173     */
3174    info->directRenderingEnabled = RADEONPreInitDRI(pScrn);
3175    if (info->directRenderingEnabled < 0)
3176	goto fail;
3177#endif
3178    if (!info->directRenderingEnabled) {
3179	if (info->ChipFamily >= CHIP_FAMILY_R600) {
3180	    info->r600_shadow_fb = TRUE;
3181	    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
3182			   "using shadow framebuffer\n");
3183	    if (!xf86LoadSubModule(pScrn, "shadow"))
3184		info->r600_shadow_fb = FALSE;
3185	}
3186    }
3187
3188    if (!RADEONPreInitVRAM(pScrn))
3189	goto fail;
3190
3191    RADEONPreInitColorTiling(pScrn);
3192
3193    if (IS_AVIVO_VARIANT)
3194	xf86CrtcSetSizeRange (pScrn, 320, 200, 8192, 8192);
3195    else
3196	xf86CrtcSetSizeRange (pScrn, 320, 200, 4096, 4096);
3197
3198    RADEONPreInitDDC(pScrn);
3199
3200    if (!RADEONPreInitControllers(pScrn))
3201       goto fail;
3202
3203    if (!xf86InitialConfiguration (pScrn, FALSE))
3204   {
3205      xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "No valid modes.\n");
3206      goto fail;
3207   }
3208
3209    /* fix up cloning on rn50 cards
3210     * since they only have one crtc sometimes the xserver doesn't assign
3211     * a crtc to one of the outputs even though both outputs have common modes
3212     * which results in only one monitor being enabled.  Assign a crtc here so
3213     * that both outputs light up.
3214     */
3215    if (info->ChipFamily == CHIP_FAMILY_RV100 && !pRADEONEnt->HasCRTC2) {
3216	int i;
3217
3218	for (i = 0; i < xf86_config->num_output; i++) {
3219	    xf86OutputPtr output = xf86_config->output[i];
3220
3221	    /* XXX: double check crtc mode */
3222	    if ((output->probed_modes != NULL) && (output->crtc == NULL))
3223		output->crtc = xf86_config->crtc[0];
3224	}
3225    }
3226
3227    RADEONSetPitch(pScrn);
3228
3229   /* Set display resolution */
3230   xf86SetDpi(pScrn, 0, 0);
3231
3232	/* Get ScreenInit function */
3233    if (!xf86LoadSubModule(pScrn, "fb")) return FALSE;
3234
3235    if (!RADEONPreInitGamma(pScrn))              goto fail;
3236
3237    if (!RADEONPreInitCursor(pScrn))             goto fail;
3238
3239    if (!RADEONPreInitAccel(pScrn))              goto fail;
3240
3241    if (!IS_AVIVO_VARIANT) {
3242	if (!RADEONPreInitXv(pScrn))                 goto fail;
3243    }
3244
3245    if (!xf86RandR12PreInit (pScrn))
3246    {
3247      xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "RandR initialization failure\n");
3248      goto fail;
3249    }
3250
3251    if (pScrn->modes == NULL) {
3252      xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "No modes.\n");
3253      goto fail;
3254   }
3255
3256
3257				/* Free int10 info */
3258    if (pInt10)
3259	xf86FreeInt10(pInt10);
3260
3261    if(info->MMIO) RADEONUnmapMMIO(pScrn);
3262    info->MMIO = NULL;
3263
3264    xf86DrvMsg(pScrn->scrnIndex, X_NOTICE,
3265	       "MergedFB support has been removed and replaced with"
3266	       " xrandr 1.2 support\n");
3267
3268    return TRUE;
3269
3270fail:
3271				/* Pre-init failed. */
3272				/* Free the video bios (if applicable) */
3273    if (info->VBIOS) {
3274	free(info->VBIOS);
3275	info->VBIOS = NULL;
3276    }
3277
3278				/* Free int10 info */
3279    if (pInt10)
3280	xf86FreeInt10(pInt10);
3281
3282#ifdef WITH_VGAHW
3283    if (info->VGAAccess)
3284           vgaHWFreeHWRec(pScrn);
3285#endif
3286
3287    if(info->MMIO) RADEONUnmapMMIO(pScrn);
3288    info->MMIO = NULL;
3289
3290 fail1:
3291    RADEONFreeRec(pScrn);
3292
3293    return FALSE;
3294}
3295
3296/* Load a palette */
3297static void RADEONLoadPalette(ScrnInfoPtr pScrn, int numColors,
3298			      int *indices, LOCO *colors, VisualPtr pVisual)
3299{
3300    RADEONInfoPtr  info       = RADEONPTR(pScrn);
3301    xf86CrtcConfigPtr   xf86_config = XF86_CRTC_CONFIG_PTR(pScrn);
3302    int            i;
3303    int            index, j;
3304    uint16_t       lut_r[256], lut_g[256], lut_b[256];
3305    int c;
3306
3307#ifdef XF86DRI
3308    if (info->cp->CPStarted && pScrn->pScreen) DRILock(pScrn->pScreen, 0);
3309#endif
3310
3311    if (info->accelOn && pScrn->pScreen)
3312        RADEON_SYNC(info, pScrn);
3313
3314    {
3315
3316      for (c = 0; c < xf86_config->num_crtc; c++) {
3317	  xf86CrtcPtr crtc = xf86_config->crtc[c];
3318	  RADEONCrtcPrivatePtr radeon_crtc = crtc->driver_private;
3319
3320	  for (i = 0 ; i < 256; i++) {
3321	      lut_r[i] = radeon_crtc->lut_r[i] << 6;
3322	      lut_g[i] = radeon_crtc->lut_g[i] << 6;
3323	      lut_b[i] = radeon_crtc->lut_b[i] << 6;
3324	  }
3325
3326	  switch (info->CurrentLayout.depth) {
3327	  case 15:
3328	      for (i = 0; i < numColors; i++) {
3329		  index = indices[i];
3330		  for (j = 0; j < 8; j++) {
3331		      lut_r[index * 8 + j] = colors[index].red << 6;
3332		      lut_g[index * 8 + j] = colors[index].green << 6;
3333		      lut_b[index * 8 + j] = colors[index].blue << 6;
3334		  }
3335	      }
3336	  case 16:
3337	      for (i = 0; i < numColors; i++) {
3338		  index = indices[i];
3339
3340		  if (i <= 31) {
3341		      for (j = 0; j < 8; j++) {
3342			  lut_r[index * 8 + j] = colors[index].red << 6;
3343			  lut_b[index * 8 + j] = colors[index].blue << 6;
3344		      }
3345		  }
3346
3347		  for (j = 0; j < 4; j++) {
3348		      lut_g[index * 4 + j] = colors[index].green << 6;
3349		  }
3350	      }
3351	  default:
3352	      for (i = 0; i < numColors; i++) {
3353		  index = indices[i];
3354		  lut_r[index] = colors[index].red << 6;
3355		  lut_g[index] = colors[index].green << 6;
3356		  lut_b[index] = colors[index].blue << 6;
3357	      }
3358	      break;
3359	  }
3360
3361	      /* Make the change through RandR */
3362#ifdef RANDR_12_INTERFACE
3363	  if (crtc->randr_crtc)
3364	      RRCrtcGammaSet(crtc->randr_crtc, lut_r, lut_g, lut_b);
3365	  else
3366#endif
3367	      crtc->funcs->gamma_set(crtc, lut_r, lut_g, lut_b, 256);
3368      }
3369    }
3370
3371#ifdef XF86DRI
3372    if (info->cp->CPStarted && pScrn->pScreen) DRIUnlock(pScrn->pScreen);
3373#endif
3374}
3375
3376static void RADEONBlockHandler(BLOCKHANDLER_ARGS_DECL)
3377{
3378    SCREEN_PTR(arg);
3379    ScrnInfoPtr    pScrn   = xf86ScreenToScrn(pScreen);
3380    RADEONInfoPtr  info    = RADEONPTR(pScrn);
3381
3382    pScreen->BlockHandler = info->BlockHandler;
3383    (*pScreen->BlockHandler) (BLOCKHANDLER_ARGS);
3384    pScreen->BlockHandler = RADEONBlockHandler;
3385
3386    if (info->VideoTimerCallback)
3387	(*info->VideoTimerCallback)(pScrn, currentTime.milliseconds);
3388
3389#if defined(RENDER) && defined(USE_XAA)
3390    if(info->accel_state->RenderCallback)
3391	(*info->accel_state->RenderCallback)(pScrn);
3392#endif
3393
3394#ifdef USE_EXA
3395    info->accel_state->engineMode = EXA_ENGINEMODE_UNKNOWN;
3396#endif
3397
3398    if (info->pm.dynamic_mode_enabled)
3399	RADEONPMBlockHandler(pScrn);
3400}
3401
3402static void
3403RADEONInitBIOSRegisters(ScrnInfoPtr pScrn)
3404{
3405    RADEONInfoPtr  info  = RADEONPTR(pScrn);
3406    unsigned char *RADEONMMIO = info->MMIO;
3407    RADEONSavePtr save = info->ModeReg;
3408
3409    save->bios_0_scratch = info->SavedReg->bios_0_scratch;
3410    save->bios_1_scratch = info->SavedReg->bios_1_scratch;
3411    save->bios_2_scratch = info->SavedReg->bios_2_scratch;
3412    save->bios_3_scratch = info->SavedReg->bios_3_scratch;
3413    save->bios_4_scratch = info->SavedReg->bios_4_scratch;
3414    save->bios_5_scratch = info->SavedReg->bios_5_scratch;
3415    save->bios_6_scratch = info->SavedReg->bios_6_scratch;
3416    save->bios_7_scratch = info->SavedReg->bios_7_scratch;
3417
3418    if (info->IsAtomBios) {
3419	/* let the bios control the backlight */
3420	save->bios_2_scratch &= ~ATOM_S2_VRI_BRIGHT_ENABLE;
3421	/* tell the bios not to handle mode switching */
3422	save->bios_6_scratch |= (ATOM_S6_ACC_BLOCK_DISPLAY_SWITCH |
3423				 ATOM_S6_ACC_MODE);
3424
3425	if (info->ChipFamily >= CHIP_FAMILY_R600) {
3426	    OUTREG(R600_BIOS_2_SCRATCH, save->bios_2_scratch);
3427	    OUTREG(R600_BIOS_6_SCRATCH, save->bios_6_scratch);
3428	} else {
3429	    OUTREG(RADEON_BIOS_2_SCRATCH, save->bios_2_scratch);
3430	    OUTREG(RADEON_BIOS_6_SCRATCH, save->bios_6_scratch);
3431	}
3432    } else {
3433	/* let the bios control the backlight */
3434	save->bios_0_scratch &= ~RADEON_DRIVER_BRIGHTNESS_EN;
3435	/* tell the bios not to handle mode switching */
3436	save->bios_6_scratch |= (RADEON_DISPLAY_SWITCHING_DIS |
3437				 RADEON_ACC_MODE_CHANGE);
3438	/* tell the bios a driver is loaded */
3439	save->bios_7_scratch |= RADEON_DRV_LOADED;
3440
3441	OUTREG(RADEON_BIOS_0_SCRATCH, save->bios_0_scratch);
3442	OUTREG(RADEON_BIOS_6_SCRATCH, save->bios_6_scratch);
3443	//OUTREG(RADEON_BIOS_7_SCRATCH, save->bios_7_scratch);
3444    }
3445
3446}
3447
3448
3449/* Called at the start of each server generation. */
3450Bool RADEONScreenInit(SCREEN_INIT_ARGS_DECL)
3451{
3452    ScrnInfoPtr    pScrn = xf86ScreenToScrn(pScreen);
3453    RADEONInfoPtr  info  = RADEONPTR(pScrn);
3454    int            hasDRI = 0;
3455#ifdef RENDER
3456    int            subPixelOrder = SubPixelUnknown;
3457    char*          s;
3458#endif
3459
3460
3461    info->accelOn      = FALSE;
3462#ifdef USE_XAA
3463    info->accel_state->accel        = NULL;
3464#endif
3465#ifdef XF86DRI
3466    pScrn->fbOffset    = info->dri->frontOffset;
3467#endif
3468
3469    if (info->IsSecondary)
3470        pScrn->fbOffset = pScrn->videoRam * 1024;
3471#ifdef XF86DRI
3472    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
3473		   "RADEONScreenInit %lx %ld %d\n",
3474		   pScrn->memPhysBase, pScrn->fbOffset, info->dri->frontOffset);
3475#else
3476    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
3477		   "RADEONScreenInit %lx %ld\n",
3478		   pScrn->memPhysBase, pScrn->fbOffset);
3479#endif
3480    if (!RADEONMapMem(pScrn)) return FALSE;
3481
3482#ifdef XF86DRI
3483    info->dri->fbX = 0;
3484    info->dri->fbY = 0;
3485#endif
3486
3487    info->PaletteSavedOnVT = FALSE;
3488
3489    info->crtc_on = FALSE;
3490    info->crtc2_on = FALSE;
3491
3492    /* save the real front buffer size
3493     * it changes with randr, rotation, etc.
3494     */
3495    info->virtualX = pScrn->virtualX;
3496    info->virtualY = pScrn->virtualY;
3497
3498    RADEONSave(pScrn);
3499
3500    /* set initial bios scratch reg state */
3501    RADEONInitBIOSRegisters(pScrn);
3502
3503    /* blank the outputs/crtcs */
3504    RADEONBlank(pScrn);
3505
3506    RADEONPMInit(pScrn);
3507
3508    if (info->allowColorTiling && (pScrn->virtualX > info->MaxSurfaceWidth)) {
3509	xf86DrvMsg(pScrn->scrnIndex, X_INFO,
3510		   "Color tiling not supported with virtual x resolutions larger than %d, disabling\n",
3511		    info->MaxSurfaceWidth);
3512	info->allowColorTiling = FALSE;
3513    }
3514    if (info->allowColorTiling) {
3515        info->tilingEnabled = (pScrn->currentMode->Flags & (V_DBLSCAN | V_INTERLACE)) ? FALSE : TRUE;
3516    }
3517
3518    /* Visual setup */
3519    miClearVisualTypes();
3520    if (!miSetVisualTypes(pScrn->depth,
3521			  miGetDefaultVisualMask(pScrn->depth),
3522			  pScrn->rgbBits,
3523			  pScrn->defaultVisual)) return FALSE;
3524    miSetPixmapDepths ();
3525
3526#ifdef XF86DRI
3527    if (info->directRenderingEnabled) {
3528	MessageType from;
3529
3530	info->dri->depthBits = pScrn->depth;
3531
3532	from = xf86GetOptValInteger(info->Options, OPTION_DEPTH_BITS,
3533				    &info->dri->depthBits)
3534	     ? X_CONFIG : X_DEFAULT;
3535
3536	if (info->dri->depthBits != 16 && info->dri->depthBits != 24) {
3537	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
3538		       "Value for Option \"DepthBits\" must be 16 or 24\n");
3539	    info->dri->depthBits = pScrn->depth;
3540	    from = X_DEFAULT;
3541	}
3542
3543	xf86DrvMsg(pScrn->scrnIndex, from,
3544		   "Using %d bit depth buffer\n", info->dri->depthBits);
3545    }
3546
3547
3548    hasDRI = info->directRenderingEnabled;
3549#endif /* XF86DRI */
3550
3551    /* Initialize the memory map, this basically calculates the values
3552     * we'll use later on for MC_FB_LOCATION & MC_AGP_LOCATION
3553     */
3554    RADEONInitMemoryMap(pScrn);
3555
3556    /* empty the surfaces */
3557    if (info->ChipFamily < CHIP_FAMILY_R600) {
3558	unsigned char *RADEONMMIO = info->MMIO;
3559	unsigned int j;
3560	for (j = 0; j < 8; j++) {
3561	    OUTREG(RADEON_SURFACE0_INFO + 16 * j, 0);
3562	    OUTREG(RADEON_SURFACE0_LOWER_BOUND + 16 * j, 0);
3563	    OUTREG(RADEON_SURFACE0_UPPER_BOUND + 16 * j, 0);
3564	}
3565    }
3566
3567#ifdef XF86DRI
3568    /* Depth moves are disabled by default since they are extremely slow */
3569    info->dri->depthMoves = xf86ReturnOptValBool(info->Options,
3570						 OPTION_DEPTH_MOVE, FALSE);
3571    if (info->dri->depthMoves && info->allowColorTiling) {
3572	xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "Enabling depth moves\n");
3573    } else if (info->dri->depthMoves) {
3574	xf86DrvMsg(pScrn->scrnIndex, X_INFO,
3575		   "Depth moves don't work without color tiling, disabled\n");
3576	info->dri->depthMoves = FALSE;
3577    } else {
3578	xf86DrvMsg(pScrn->scrnIndex, X_INFO,
3579		   "Depth moves disabled by default\n");
3580    }
3581#endif
3582
3583    /* Initial setup of surfaces */
3584    if (info->ChipFamily < CHIP_FAMILY_R600) {
3585        xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
3586                       "Setting up initial surfaces\n");
3587        RADEONChangeSurfaces(pScrn);
3588    }
3589
3590				/* Memory manager setup */
3591
3592    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
3593		   "Setting up accel memmap\n");
3594
3595#ifdef USE_EXA
3596    if (info->useEXA) {
3597#ifdef XF86DRI
3598	if (hasDRI) {
3599	    info->accelDFS = xf86ReturnOptValBool(info->Options, OPTION_ACCEL_DFS,
3600						  info->cardType != CARD_AGP);
3601
3602	    /* Reserve approx. half of offscreen memory for local textures by
3603	     * default, can be overridden with Option "FBTexPercent".
3604	     * Round down to a whole number of texture regions.
3605	     */
3606	    info->dri->textureSize = 50;
3607
3608	    if (xf86GetOptValInteger(info->Options, OPTION_FBTEX_PERCENT,
3609				     &(info->dri->textureSize))) {
3610		if (info->dri->textureSize < 0 || info->dri->textureSize > 100) {
3611		    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
3612			       "Illegal texture memory percentage: %dx, setting to default 50%%\n",
3613			       info->dri->textureSize);
3614		    info->dri->textureSize = 50;
3615		}
3616	    }
3617	}
3618#endif /* XF86DRI */
3619
3620	if (!RADEONSetupMemEXA(pScreen))
3621	    return FALSE;
3622    }
3623#endif
3624
3625#if defined(XF86DRI) && defined(USE_XAA)
3626    if (!info->useEXA && hasDRI) {
3627	info->dri->textureSize = -1;
3628	if (xf86GetOptValInteger(info->Options, OPTION_FBTEX_PERCENT,
3629				 &(info->dri->textureSize))) {
3630	    if (info->dri->textureSize < 0 || info->dri->textureSize > 100) {
3631		xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
3632			   "Illegal texture memory percentage: %dx, using default behaviour\n",
3633			   info->dri->textureSize);
3634		info->dri->textureSize = -1;
3635	    }
3636	}
3637	if (!RADEONSetupMemXAA_DRI(pScreen))
3638	    return FALSE;
3639    	pScrn->fbOffset    = info->dri->frontOffset;
3640    }
3641#endif
3642
3643#ifdef USE_XAA
3644    if (!info->useEXA && !hasDRI && !RADEONSetupMemXAA(pScreen))
3645	return FALSE;
3646#endif
3647
3648    info->accel_state->dst_pitch_offset =
3649	(((pScrn->displayWidth * info->CurrentLayout.pixel_bytes / 64)
3650	  << 22) | ((info->fbLocation + pScrn->fbOffset) >> 10));
3651
3652    /* Setup DRI after visuals have been established, but before fbScreenInit is
3653     * called.  fbScreenInit will eventually call the driver's InitGLXVisuals
3654     * call back. */
3655#ifdef XF86DRI
3656    if (info->directRenderingEnabled) {
3657	/* FIXME: When we move to dynamic allocation of back and depth
3658	 * buffers, we will want to revisit the following check for 3
3659	 * times the virtual size of the screen below.
3660	 */
3661	int  width_bytes = (pScrn->displayWidth *
3662			    info->CurrentLayout.pixel_bytes);
3663	int  maxy        = info->FbMapSize / width_bytes;
3664
3665	if (maxy <= pScrn->virtualY * 3) {
3666	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
3667		       "Static buffer allocation failed.  Disabling DRI.\n");
3668	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
3669		       "At least %d kB of video memory needed at this "
3670		       "resolution and depth.\n",
3671		       (pScrn->displayWidth * pScrn->virtualY *
3672			info->CurrentLayout.pixel_bytes * 3 + 1023) / 1024);
3673	    info->directRenderingEnabled = FALSE;
3674	} else {
3675	    info->directRenderingEnabled = RADEONDRIScreenInit(pScreen);
3676	}
3677    }
3678
3679    /* Tell DRI about new memory map */
3680    if (info->directRenderingEnabled && info->dri->newMemoryMap) {
3681        if (RADEONDRISetParam(pScrn, RADEON_SETPARAM_NEW_MEMMAP, 1) < 0) {
3682		xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
3683			   "[drm] failed to enable new memory map\n");
3684		RADEONDRICloseScreen(pScreen);
3685		info->directRenderingEnabled = FALSE;
3686	}
3687    }
3688#endif
3689    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
3690		   "Initializing fb layer\n");
3691
3692    if (info->r600_shadow_fb) {
3693	info->fb_shadow = calloc(1,
3694				 pScrn->displayWidth * pScrn->virtualY *
3695				 ((pScrn->bitsPerPixel + 7) >> 3));
3696	if (info->fb_shadow == NULL) {
3697	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
3698                       "Failed to allocate shadow framebuffer\n");
3699	    info->r600_shadow_fb = FALSE;
3700	} else {
3701	    if (!fbScreenInit(pScreen, info->fb_shadow,
3702			      pScrn->virtualX, pScrn->virtualY,
3703			      pScrn->xDpi, pScrn->yDpi, pScrn->displayWidth,
3704			      pScrn->bitsPerPixel))
3705		return FALSE;
3706	}
3707    }
3708
3709    if (info->r600_shadow_fb == FALSE) {
3710	/* Init fb layer */
3711	if (!fbScreenInit(pScreen, info->FB + pScrn->fbOffset,
3712			  pScrn->virtualX, pScrn->virtualY,
3713			  pScrn->xDpi, pScrn->yDpi, pScrn->displayWidth,
3714			  pScrn->bitsPerPixel))
3715	    return FALSE;
3716    }
3717
3718    xf86SetBlackWhitePixels(pScreen);
3719
3720    if (pScrn->bitsPerPixel > 8) {
3721	VisualPtr  visual;
3722
3723	visual = pScreen->visuals + pScreen->numVisuals;
3724	while (--visual >= pScreen->visuals) {
3725	    if ((visual->class | DynamicClass) == DirectColor) {
3726		visual->offsetRed   = pScrn->offset.red;
3727		visual->offsetGreen = pScrn->offset.green;
3728		visual->offsetBlue  = pScrn->offset.blue;
3729		visual->redMask     = pScrn->mask.red;
3730		visual->greenMask   = pScrn->mask.green;
3731		visual->blueMask    = pScrn->mask.blue;
3732	    }
3733	}
3734    }
3735
3736    /* Must be after RGB order fixed */
3737    fbPictureInit (pScreen, 0, 0);
3738
3739#ifdef RENDER
3740    if ((s = xf86GetOptValString(info->Options, OPTION_SUBPIXEL_ORDER))) {
3741	if (strcmp(s, "RGB") == 0) subPixelOrder = SubPixelHorizontalRGB;
3742	else if (strcmp(s, "BGR") == 0) subPixelOrder = SubPixelHorizontalBGR;
3743	else if (strcmp(s, "NONE") == 0) subPixelOrder = SubPixelNone;
3744	PictureSetSubpixelOrder (pScreen, subPixelOrder);
3745    }
3746#endif
3747
3748    pScrn->vtSema = TRUE;
3749
3750    /* restore the memory map here otherwise we may get a hang when
3751     * initializing the drm below
3752     */
3753    RADEONInitMemMapRegisters(pScrn, info->ModeReg, info);
3754    RADEONRestoreMemMapRegisters(pScrn, info->ModeReg);
3755
3756    /* Backing store setup */
3757    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
3758		   "Initializing backing store\n");
3759    miInitializeBackingStore(pScreen);
3760    xf86SetBackingStore(pScreen);
3761
3762    /* DRI finalisation */
3763#ifdef XF86DRI
3764    if (info->directRenderingEnabled &&
3765	(info->cardType==CARD_PCIE || info->cardType==CARD_PCI) &&
3766        info->dri->pKernelDRMVersion->version_minor >= 19)
3767    {
3768      if (RADEONDRISetParam(pScrn, RADEON_SETPARAM_PCIGART_LOCATION, info->dri->pciGartOffset) < 0)
3769	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
3770		   "[drm] failed set pci gart location\n");
3771
3772      if (info->dri->pKernelDRMVersion->version_minor >= 26) {
3773	if (RADEONDRISetParam(pScrn, RADEON_SETPARAM_PCIGART_TABLE_SIZE, info->dri->pciGartSize) < 0)
3774	  xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
3775		     "[drm] failed set pci gart table size\n");
3776      }
3777    }
3778    if (info->directRenderingEnabled) {
3779        xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
3780		       "DRI Finishing init !\n");
3781	info->directRenderingEnabled = RADEONDRIFinishScreenInit(pScreen);
3782    }
3783    if (info->directRenderingEnabled) {
3784	/* DRI final init might have changed the memory map, we need to adjust
3785	 * our local image to make sure we restore them properly on mode
3786	 * changes or VT switches
3787	 */
3788	RADEONAdjustMemMapRegisters(pScrn, info->ModeReg);
3789
3790	xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Direct rendering enabled\n");
3791
3792	/* we might already be in tiled mode, tell drm about it */
3793	if (info->directRenderingEnabled && info->tilingEnabled) {
3794	  if (RADEONDRISetParam(pScrn, RADEON_SETPARAM_SWITCH_TILING, (info->tilingEnabled ? 1 : 0)) < 0)
3795  	      xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
3796			 "[drm] failed changing tiling status\n");
3797	}
3798    } else {
3799	xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
3800		   "Direct rendering disabled\n");
3801    }
3802#endif
3803
3804    /* Make sure surfaces are allright since DRI setup may have changed them */
3805    if (info->ChipFamily < CHIP_FAMILY_R600) {
3806        xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
3807                       "Setting up final surfaces\n");
3808
3809        RADEONChangeSurfaces(pScrn);
3810    }
3811
3812
3813    /* Enable aceleration */
3814    if (!xf86ReturnOptValBool(info->Options, OPTION_NOACCEL, FALSE)) {
3815	xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
3816		       "Initializing Acceleration\n");
3817	if (RADEONAccelInit(pScreen)) {
3818	    xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Acceleration enabled\n");
3819	    info->accelOn = TRUE;
3820	} else {
3821	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
3822		       "Acceleration initialization failed\n");
3823	    xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Acceleration disabled\n");
3824	    info->accelOn = FALSE;
3825	}
3826    } else {
3827	xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Acceleration disabled\n");
3828	info->accelOn = FALSE;
3829    }
3830
3831    /* Init DPMS */
3832    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
3833		   "Initializing DPMS\n");
3834    xf86DPMSInit(pScreen, xf86DPMSSet, 0);
3835
3836    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
3837		   "Initializing Cursor\n");
3838
3839    /* Set Silken Mouse */
3840    xf86SetSilkenMouse(pScreen);
3841
3842    /* Cursor setup */
3843    miDCInitialize(pScreen, xf86GetPointerScreenFuncs());
3844
3845    /* Hardware cursor setup */
3846    if (!xf86ReturnOptValBool(info->Options, OPTION_SW_CURSOR, FALSE)) {
3847	if (RADEONCursorInit(pScreen)) {
3848#ifdef USE_XAA
3849	    if (!info->useEXA) {
3850		int  width, height;
3851
3852		if (xf86QueryLargestOffscreenArea(pScreen, &width, &height,
3853					      0, 0, 0)) {
3854		    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
3855			       "Largest offscreen area available: %d x %d\n",
3856			       width, height);
3857		}
3858	    }
3859#endif /* USE_XAA */
3860	} else {
3861	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
3862		       "Hardware cursor initialization failed\n");
3863	    xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Using software cursor\n");
3864	}
3865    } else {
3866	xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Using software cursor\n");
3867    }
3868
3869    /* DGA setup */
3870#ifdef XFreeXDGA
3871    xf86DiDGAInit(pScreen, info->LinearAddr + pScrn->fbOffset);
3872#endif
3873
3874    /* Init Xv */
3875    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
3876		   "Initializing Xv\n");
3877    RADEONInitVideo(pScreen);
3878
3879    if (info->r600_shadow_fb == TRUE) {
3880        if (!shadowSetup(pScreen)) {
3881            return FALSE;
3882        }
3883    }
3884
3885    /* Clear the framebuffer */
3886    memset(info->FB + pScrn->fbOffset, 0,
3887           pScrn->virtualY * pScrn->displayWidth * info->CurrentLayout.pixel_bytes);
3888
3889    pScrn->pScreen = pScreen;
3890
3891    /* set the modes with desired rotation, etc. */
3892    if (!xf86SetDesiredModes (pScrn))
3893	return FALSE;
3894
3895    /* Provide SaveScreen & wrap BlockHandler and CloseScreen */
3896    /* Wrap CloseScreen */
3897    info->CloseScreen    = pScreen->CloseScreen;
3898    pScreen->CloseScreen = RADEONCloseScreen;
3899    pScreen->SaveScreen  = RADEONSaveScreen;
3900    info->BlockHandler = pScreen->BlockHandler;
3901    pScreen->BlockHandler = RADEONBlockHandler;
3902    info->CreateScreenResources = pScreen->CreateScreenResources;
3903    pScreen->CreateScreenResources = RADEONCreateScreenResources;
3904
3905   if (!xf86CrtcScreenInit (pScreen))
3906       return FALSE;
3907
3908    /* Colormap setup */
3909    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
3910                   "Initializing color map\n");
3911    if (!miCreateDefColormap(pScreen)) return FALSE;
3912    /* all radeons support 10 bit CLUTs */
3913    if (!xf86HandleColormaps(pScreen, 256, 10,
3914			     RADEONLoadPalette, NULL,
3915			     CMAP_PALETTED_TRUECOLOR
3916#if 0 /* This option messes up text mode! (eich@suse.de) */
3917			     | CMAP_LOAD_EVEN_IF_OFFSCREEN
3918#endif
3919			     | CMAP_RELOAD_ON_MODE_SWITCH)) return FALSE;
3920
3921    /* Note unused options */
3922    if (serverGeneration == 1)
3923	xf86ShowUnusedOptions(pScrn->scrnIndex, pScrn->options);
3924
3925    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
3926		   "RADEONScreenInit finished\n");
3927
3928    return TRUE;
3929}
3930
3931/* Write memory mapping registers */
3932void RADEONRestoreMemMapRegisters(ScrnInfoPtr pScrn,
3933					 RADEONSavePtr restore)
3934{
3935    RADEONInfoPtr  info       = RADEONPTR(pScrn);
3936    RADEONEntPtr pRADEONEnt = RADEONEntPriv(pScrn);
3937    unsigned char *RADEONMMIO = info->MMIO;
3938    int timeout;
3939    uint32_t mc_fb_loc, mc_agp_loc, mc_agp_loc_hi;
3940
3941    radeon_read_mc_fb_agp_location(pScrn, LOC_FB | LOC_AGP, &mc_fb_loc,
3942				   &mc_agp_loc, &mc_agp_loc_hi);
3943
3944    if (info->IsSecondary)
3945      return;
3946    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
3947	       "RADEONRestoreMemMapRegisters() : \n");
3948    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
3949	       "  MC_FB_LOCATION   : 0x%08x 0x%08x\n",
3950	       (unsigned)restore->mc_fb_location, (unsigned int)mc_fb_loc);
3951    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
3952	       "  MC_AGP_LOCATION  : 0x%08x\n",
3953	       (unsigned)restore->mc_agp_location);
3954
3955    if (IS_DCE4_VARIANT) {
3956	if (mc_fb_loc != restore->mc_fb_location ||
3957	    mc_agp_loc != restore->mc_agp_location) {
3958	    uint32_t tmp;
3959
3960	    //XXX
3961	    //RADEONWaitForIdleMMIO(pScrn);
3962
3963            /* disable VGA rendering core */
3964    	    OUTREG(AVIVO_VGA_RENDER_CONTROL, INREG(AVIVO_VGA_RENDER_CONTROL) & ~AVIVO_VGA_VSTATUS_CNTL_MASK);
3965	    OUTREG(AVIVO_D1VGA_CONTROL, INREG(AVIVO_D1VGA_CONTROL) & ~AVIVO_DVGA_CONTROL_MODE_ENABLE);
3966	    OUTREG(AVIVO_D2VGA_CONTROL, INREG(AVIVO_D2VGA_CONTROL) & ~AVIVO_DVGA_CONTROL_MODE_ENABLE);
3967	    OUTREG(EVERGREEN_D3VGA_CONTROL, INREG(EVERGREEN_D3VGA_CONTROL) & ~AVIVO_DVGA_CONTROL_MODE_ENABLE);
3968	    OUTREG(EVERGREEN_D4VGA_CONTROL, INREG(EVERGREEN_D4VGA_CONTROL) & ~AVIVO_DVGA_CONTROL_MODE_ENABLE);
3969	    OUTREG(EVERGREEN_D5VGA_CONTROL, INREG(EVERGREEN_D5VGA_CONTROL) & ~AVIVO_DVGA_CONTROL_MODE_ENABLE);
3970	    OUTREG(EVERGREEN_D6VGA_CONTROL, INREG(EVERGREEN_D6VGA_CONTROL) & ~AVIVO_DVGA_CONTROL_MODE_ENABLE);
3971
3972	    /* Stop display & memory access */
3973	    tmp = INREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC0_REGISTER_OFFSET);
3974	    OUTREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC0_REGISTER_OFFSET, tmp & ~EVERGREEN_CRTC_MASTER_EN);
3975	    tmp = INREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC0_REGISTER_OFFSET);
3976
3977	    tmp = INREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC1_REGISTER_OFFSET);
3978	    OUTREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC1_REGISTER_OFFSET, tmp & ~EVERGREEN_CRTC_MASTER_EN);
3979	    tmp = INREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC1_REGISTER_OFFSET);
3980
3981	    if (!IS_DCE41_VARIANT) {
3982		tmp = INREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC2_REGISTER_OFFSET);
3983		OUTREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC2_REGISTER_OFFSET, tmp & ~EVERGREEN_CRTC_MASTER_EN);
3984		tmp = INREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC2_REGISTER_OFFSET);
3985
3986		tmp = INREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC3_REGISTER_OFFSET);
3987		OUTREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC3_REGISTER_OFFSET, tmp & ~EVERGREEN_CRTC_MASTER_EN);
3988		tmp = INREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC3_REGISTER_OFFSET);
3989
3990		tmp = INREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC4_REGISTER_OFFSET);
3991		OUTREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC4_REGISTER_OFFSET, tmp & ~EVERGREEN_CRTC_MASTER_EN);
3992		tmp = INREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC4_REGISTER_OFFSET);
3993
3994		tmp = INREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC5_REGISTER_OFFSET);
3995		OUTREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC5_REGISTER_OFFSET, tmp & ~EVERGREEN_CRTC_MASTER_EN);
3996		tmp = INREG(EVERGREEN_CRTC_CONTROL + EVERGREEN_CRTC5_REGISTER_OFFSET);
3997	    }
3998
3999	    usleep(10000);
4000	    timeout = 0;
4001	    while (!(radeon_get_mc_idle(pScrn))) {
4002		if (++timeout > 1000000) {
4003		    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
4004			       "Timeout trying to update memory controller settings !\n");
4005		    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
4006			       "You will probably crash now ... \n");
4007		    /* Nothing we can do except maybe try to kill the server,
4008		     * let's wait 2 seconds to leave the above message a chance
4009		     * to maybe hit the disk and continue trying to setup despite
4010		     * the MC being non-idle
4011		     */
4012		    usleep(2000000);
4013		}
4014		usleep(10);
4015	    }
4016
4017	    radeon_write_mc_fb_agp_location(pScrn, LOC_FB | LOC_AGP,
4018					    restore->mc_fb_location,
4019					    restore->mc_agp_location,
4020					    restore->mc_agp_location_hi);
4021
4022	    OUTREG(R600_HDP_NONSURFACE_BASE, (restore->mc_fb_location & 0xffff) << 16);
4023
4024	}
4025    } else if (IS_AVIVO_VARIANT) {
4026	if (mc_fb_loc != restore->mc_fb_location ||
4027	    mc_agp_loc != restore->mc_agp_location) {
4028	    uint32_t tmp;
4029
4030	    RADEONWaitForIdleMMIO(pScrn);
4031
4032            /* disable VGA rendering core */
4033    	    OUTREG(AVIVO_VGA_RENDER_CONTROL, INREG(AVIVO_VGA_RENDER_CONTROL) &~ AVIVO_VGA_VSTATUS_CNTL_MASK);
4034
4035	    OUTREG(AVIVO_D1VGA_CONTROL, INREG(AVIVO_D1VGA_CONTROL) & ~AVIVO_DVGA_CONTROL_MODE_ENABLE);
4036	    OUTREG(AVIVO_D2VGA_CONTROL, INREG(AVIVO_D2VGA_CONTROL) & ~AVIVO_DVGA_CONTROL_MODE_ENABLE);
4037
4038	    /* Stop display & memory access */
4039	    tmp = INREG(AVIVO_D1CRTC_CONTROL);
4040	    OUTREG(AVIVO_D1CRTC_CONTROL, tmp & ~AVIVO_CRTC_EN);
4041
4042	    tmp = INREG(AVIVO_D2CRTC_CONTROL);
4043	    OUTREG(AVIVO_D2CRTC_CONTROL, tmp & ~AVIVO_CRTC_EN);
4044
4045	    tmp = INREG(AVIVO_D2CRTC_CONTROL);
4046
4047	    usleep(10000);
4048	    timeout = 0;
4049	    while (!(radeon_get_mc_idle(pScrn))) {
4050		if (++timeout > 1000000) {
4051		    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
4052			       "Timeout trying to update memory controller settings !\n");
4053		    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
4054			       "You will probably crash now ... \n");
4055		    /* Nothing we can do except maybe try to kill the server,
4056		     * let's wait 2 seconds to leave the above message a chance
4057		     * to maybe hit the disk and continue trying to setup despite
4058		     * the MC being non-idle
4059		     */
4060		    usleep(2000000);
4061		}
4062		usleep(10);
4063	    }
4064
4065	    radeon_write_mc_fb_agp_location(pScrn, LOC_FB | LOC_AGP,
4066					    restore->mc_fb_location,
4067					    restore->mc_agp_location,
4068					    restore->mc_agp_location_hi);
4069
4070	    if (info->ChipFamily < CHIP_FAMILY_R600) {
4071		OUTREG(AVIVO_HDP_FB_LOCATION, restore->mc_fb_location);
4072	    } else {
4073		OUTREG(R600_HDP_NONSURFACE_BASE, (restore->mc_fb_location << 16) & 0xff0000);
4074	    }
4075
4076	    /* Reset the engine and HDP */
4077	    if (info->ChipFamily < CHIP_FAMILY_R600)
4078		RADEONEngineReset(pScrn);
4079	}
4080    } else {
4081
4082	/* Write memory mapping registers only if their value change
4083	 * since we must ensure no access is done while they are
4084	 * reprogrammed
4085	 */
4086	if (mc_fb_loc != restore->mc_fb_location ||
4087	    mc_agp_loc != restore->mc_agp_location) {
4088	    uint32_t crtc_ext_cntl, crtc_gen_cntl, crtc2_gen_cntl=0, ov0_scale_cntl;
4089	    uint32_t old_mc_status;
4090
4091	    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
4092			   "  Map Changed ! Applying ...\n");
4093
4094	    /* Make sure engine is idle. We assume the CCE is stopped
4095	     * at this point
4096	     */
4097	    RADEONWaitForIdleMMIO(pScrn);
4098
4099	    if (info->IsIGP)
4100		goto igp_no_mcfb;
4101
4102	    /* Capture MC_STATUS in case things go wrong ... */
4103	    old_mc_status = INREG(RADEON_MC_STATUS);
4104
4105	    /* Stop display & memory access */
4106	    ov0_scale_cntl = INREG(RADEON_OV0_SCALE_CNTL);
4107	    OUTREG(RADEON_OV0_SCALE_CNTL, ov0_scale_cntl & ~RADEON_SCALER_ENABLE);
4108	    crtc_ext_cntl = INREG(RADEON_CRTC_EXT_CNTL);
4109	    OUTREG(RADEON_CRTC_EXT_CNTL, crtc_ext_cntl | RADEON_CRTC_DISPLAY_DIS);
4110	    crtc_gen_cntl = INREG(RADEON_CRTC_GEN_CNTL);
4111	    RADEONWaitForVerticalSync(pScrn);
4112	    OUTREG(RADEON_CRTC_GEN_CNTL,
4113		   (crtc_gen_cntl
4114		    & ~(RADEON_CRTC_CUR_EN | RADEON_CRTC_ICON_EN))
4115		   | RADEON_CRTC_DISP_REQ_EN_B | RADEON_CRTC_EXT_DISP_EN);
4116
4117	    if (pRADEONEnt->HasCRTC2) {
4118		crtc2_gen_cntl = INREG(RADEON_CRTC2_GEN_CNTL);
4119		RADEONWaitForVerticalSync2(pScrn);
4120		OUTREG(RADEON_CRTC2_GEN_CNTL,
4121		       (crtc2_gen_cntl
4122			& ~(RADEON_CRTC2_CUR_EN | RADEON_CRTC2_ICON_EN))
4123		       | RADEON_CRTC2_DISP_REQ_EN_B);
4124	    }
4125
4126	    /* Make sure the chip settles down (paranoid !) */
4127	    usleep(100000);
4128	    timeout = 0;
4129	    while (!(radeon_get_mc_idle(pScrn))) {
4130		if (++timeout > 1000000) {
4131		    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
4132			       "Timeout trying to update memory controller settings !\n");
4133		    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
4134			       "MC_STATUS = 0x%08x (on entry = 0x%08x)\n",
4135			       (unsigned int)INREG(RADEON_MC_STATUS), (unsigned int)old_mc_status);
4136		    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
4137			       "You will probably crash now ... \n");
4138		    /* Nothing we can do except maybe try to kill the server,
4139		     * let's wait 2 seconds to leave the above message a chance
4140		     * to maybe hit the disk and continue trying to setup despite
4141		     * the MC being non-idle
4142		     */
4143		    usleep(2000000);
4144		}
4145		usleep(10);
4146	    }
4147
4148	    /* Update maps, first clearing out AGP to make sure we don't get
4149	     * a temporary overlap
4150	     */
4151	    OUTREG(RADEON_MC_AGP_LOCATION, 0xfffffffc);
4152	    OUTREG(RADEON_MC_FB_LOCATION, restore->mc_fb_location);
4153	    radeon_write_mc_fb_agp_location(pScrn, LOC_FB | LOC_AGP, restore->mc_fb_location,
4154					    0xfffffffc, 0);
4155	igp_no_mcfb:
4156	    radeon_write_mc_fb_agp_location(pScrn, LOC_AGP, 0,
4157					    restore->mc_agp_location, 0);
4158	    /* Make sure map fully reached the chip */
4159	    (void)INREG(RADEON_MC_FB_LOCATION);
4160
4161	    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
4162			   "  Map applied, resetting engine ...\n");
4163
4164	    /* Reset the engine and HDP */
4165	    RADEONEngineReset(pScrn);
4166
4167	    /* Make sure we have sane offsets before re-enabling the CRTCs, disable
4168	     * stereo, clear offsets, and wait for offsets to catch up with hw
4169	     */
4170
4171	    OUTREG(RADEON_CRTC_OFFSET_CNTL, RADEON_CRTC_OFFSET_FLIP_CNTL);
4172	    OUTREG(RADEON_CRTC_OFFSET, 0);
4173	    OUTREG(RADEON_CUR_OFFSET, 0);
4174	    timeout = 0;
4175	    while(INREG(RADEON_CRTC_OFFSET) & RADEON_CRTC_OFFSET__GUI_TRIG_OFFSET) {
4176		if (timeout++ > 1000000) {
4177		    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
4178			       "Timeout waiting for CRTC offset to update !\n");
4179		    break;
4180		}
4181		usleep(1000);
4182	    }
4183	    if (pRADEONEnt->HasCRTC2) {
4184		OUTREG(RADEON_CRTC2_OFFSET_CNTL, RADEON_CRTC2_OFFSET_FLIP_CNTL);
4185		OUTREG(RADEON_CRTC2_OFFSET, 0);
4186		OUTREG(RADEON_CUR2_OFFSET, 0);
4187		timeout = 0;
4188		while(INREG(RADEON_CRTC2_OFFSET) & RADEON_CRTC2_OFFSET__GUI_TRIG_OFFSET) {
4189		    if (timeout++ > 1000000) {
4190			xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
4191				   "Timeout waiting for CRTC2 offset to update !\n");
4192			break;
4193		    }
4194		    usleep(1000);
4195		}
4196	    }
4197	}
4198
4199	xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
4200		       "Updating display base addresses...\n");
4201
4202	OUTREG(RADEON_DISPLAY_BASE_ADDR, restore->display_base_addr);
4203	if (pRADEONEnt->HasCRTC2)
4204	    OUTREG(RADEON_DISPLAY2_BASE_ADDR, restore->display2_base_addr);
4205	OUTREG(RADEON_OV0_BASE_ADDR, restore->ov0_base_addr);
4206	(void)INREG(RADEON_OV0_BASE_ADDR);
4207
4208	/* More paranoia delays, wait 100ms */
4209	usleep(100000);
4210
4211	xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
4212		       "Memory map updated.\n");
4213    }
4214}
4215
4216#ifdef XF86DRI
4217static void RADEONAdjustMemMapRegisters(ScrnInfoPtr pScrn, RADEONSavePtr save)
4218{
4219    RADEONInfoPtr  info   = RADEONPTR(pScrn);
4220    uint32_t fb, agp, agp_hi;
4221    int changed = 0;
4222
4223    if (info->IsSecondary)
4224      return;
4225
4226    radeon_read_mc_fb_agp_location(pScrn, LOC_FB | LOC_AGP, &fb, &agp, &agp_hi);
4227
4228    if (fb != save->mc_fb_location || agp != save->mc_agp_location ||
4229	agp_hi != save->mc_agp_location_hi)
4230	changed = 1;
4231
4232    if (changed) {
4233	xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
4234		   "DRI init changed memory map, adjusting ...\n");
4235	xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
4236		   "  MC_FB_LOCATION  was: 0x%08lx is: 0x%08lx\n",
4237		   (long unsigned int)info->mc_fb_location, (long unsigned int)fb);
4238	xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
4239		   "  MC_AGP_LOCATION was: 0x%08lx is: 0x%08lx\n",
4240		   (long unsigned int)info->mc_agp_location, (long unsigned int)agp);
4241	info->mc_fb_location = fb;
4242	info->mc_agp_location = agp;
4243	if (info->ChipFamily >= CHIP_FAMILY_R600)
4244	    info->fbLocation = ((uint64_t)info->mc_fb_location & 0xffff) << 24;
4245	else
4246	    info->fbLocation = ((uint64_t)info->mc_fb_location & 0xffff) << 16;
4247
4248	info->accel_state->dst_pitch_offset =
4249	    (((pScrn->displayWidth * info->CurrentLayout.pixel_bytes / 64)
4250	      << 22) | ((info->fbLocation + pScrn->fbOffset) >> 10));
4251	RADEONInitMemMapRegisters(pScrn, save, info);
4252	RADEONRestoreMemMapRegisters(pScrn, save);
4253    }
4254
4255#ifdef USE_EXA
4256    if (info->accelDFS || (info->ChipFamily >= CHIP_FAMILY_R600))
4257    {
4258	drm_radeon_getparam_t gp;
4259	int gart_base;
4260
4261	memset(&gp, 0, sizeof(gp));
4262	gp.param = RADEON_PARAM_GART_BASE;
4263	gp.value = &gart_base;
4264
4265	if (drmCommandWriteRead(info->dri->drmFD, DRM_RADEON_GETPARAM, &gp,
4266				sizeof(gp)) < 0) {
4267	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
4268		       "Failed to determine GART area MC location, not using "
4269		       "accelerated DownloadFromScreen hook!\n");
4270	    info->accelDFS = FALSE;
4271	} else {
4272	    info->gartLocation = gart_base;
4273	}
4274    }
4275#endif /* USE_EXA */
4276}
4277#endif
4278
4279/* restore original surface info (for fb console). */
4280static void RADEONRestoreSurfaces(ScrnInfoPtr pScrn, RADEONSavePtr restore)
4281{
4282    RADEONInfoPtr      info = RADEONPTR(pScrn);
4283    unsigned char *RADEONMMIO = info->MMIO;
4284    unsigned int surfnr;
4285
4286    for ( surfnr = 0; surfnr < 8; surfnr++ ) {
4287	OUTREG(RADEON_SURFACE0_INFO + 16 * surfnr, restore->surfaces[surfnr][0]);
4288	OUTREG(RADEON_SURFACE0_LOWER_BOUND + 16 * surfnr, restore->surfaces[surfnr][1]);
4289	OUTREG(RADEON_SURFACE0_UPPER_BOUND + 16 * surfnr, restore->surfaces[surfnr][2]);
4290    }
4291}
4292
4293/* save original surface info (for fb console). */
4294static void RADEONSaveSurfaces(ScrnInfoPtr pScrn, RADEONSavePtr save)
4295{
4296    RADEONInfoPtr      info = RADEONPTR(pScrn);
4297    unsigned char *RADEONMMIO = info->MMIO;
4298    unsigned int surfnr;
4299
4300    for ( surfnr = 0; surfnr < 8; surfnr++ ) {
4301	save->surfaces[surfnr][0] = INREG(RADEON_SURFACE0_INFO + 16 * surfnr);
4302	save->surfaces[surfnr][1] = INREG(RADEON_SURFACE0_LOWER_BOUND + 16 * surfnr);
4303	save->surfaces[surfnr][2] = INREG(RADEON_SURFACE0_UPPER_BOUND + 16 * surfnr);
4304    }
4305}
4306
4307void RADEONChangeSurfaces(ScrnInfoPtr pScrn)
4308{
4309   /* the idea here is to only set up front buffer as tiled, and back/depth buffer when needed.
4310      Everything else is left as untiled. This means we need to use eplicit src/dst pitch control
4311      when blitting, based on the src/target address, and can no longer use a default offset.
4312      But OTOH we don't need to dynamically change surfaces (for xv for instance), and some
4313      ugly offset / fb reservation (cursor) is gone. And as a bonus, everything actually works...
4314      For simplicity, just always update everything (just let the ioctl fail - could do better).
4315      All surface addresses are relative to RADEON_MC_FB_LOCATION */
4316
4317    RADEONInfoPtr  info  = RADEONPTR(pScrn);
4318    int cpp = info->CurrentLayout.pixel_bytes;
4319    /* depth/front/back pitch must be identical (and the same as displayWidth) */
4320    int width_bytes = pScrn->displayWidth * cpp;
4321    int bufferSize = RADEON_ALIGN((RADEON_ALIGN(pScrn->virtualY, 16)) * width_bytes,
4322        RADEON_GPU_PAGE_SIZE);
4323    unsigned int color_pattern, swap_pattern;
4324
4325    if (!info->allowColorTiling)
4326	return;
4327
4328    swap_pattern = 0;
4329#if X_BYTE_ORDER == X_BIG_ENDIAN
4330    switch (pScrn->bitsPerPixel) {
4331    case 16:
4332	swap_pattern = RADEON_SURF_AP0_SWP_16BPP | RADEON_SURF_AP1_SWP_16BPP;
4333	break;
4334
4335    case 32:
4336	swap_pattern = RADEON_SURF_AP0_SWP_32BPP | RADEON_SURF_AP1_SWP_32BPP;
4337	break;
4338    }
4339#endif
4340    if (info->ChipFamily < CHIP_FAMILY_R200) {
4341	color_pattern = RADEON_SURF_TILE_COLOR_MACRO;
4342    } else if (IS_R300_VARIANT || IS_AVIVO_VARIANT) {
4343       color_pattern = R300_SURF_TILE_COLOR_MACRO;
4344    } else {
4345	color_pattern = R200_SURF_TILE_COLOR_MACRO;
4346    }
4347#ifdef XF86DRI
4348    if (info->directRenderingInited) {
4349	drm_radeon_surface_free_t drmsurffree;
4350	drm_radeon_surface_alloc_t drmsurfalloc;
4351	int retvalue;
4352	int depthCpp = (info->dri->depthBits - 8) / 4;
4353	int depth_width_bytes = pScrn->displayWidth * depthCpp;
4354	int depthBufferSize = RADEON_ALIGN((RADEON_ALIGN(pScrn->virtualY, 16)) * depth_width_bytes,
4355				RADEON_GPU_PAGE_SIZE);
4356	unsigned int depth_pattern;
4357
4358	drmsurffree.address = info->dri->frontOffset;
4359	retvalue = drmCommandWrite(info->dri->drmFD, DRM_RADEON_SURF_FREE,
4360	    &drmsurffree, sizeof(drmsurffree));
4361
4362	if (!((info->ChipFamily == CHIP_FAMILY_RV100) ||
4363	    (info->ChipFamily == CHIP_FAMILY_RS100) ||
4364	    (info->ChipFamily == CHIP_FAMILY_RS200))) {
4365	    drmsurffree.address = info->dri->depthOffset;
4366	    retvalue = drmCommandWrite(info->dri->drmFD, DRM_RADEON_SURF_FREE,
4367		&drmsurffree, sizeof(drmsurffree));
4368	}
4369
4370	if (!info->dri->noBackBuffer) {
4371	    drmsurffree.address = info->dri->backOffset;
4372	    retvalue = drmCommandWrite(info->dri->drmFD, DRM_RADEON_SURF_FREE,
4373		&drmsurffree, sizeof(drmsurffree));
4374	}
4375
4376	drmsurfalloc.size = bufferSize;
4377	drmsurfalloc.address = info->dri->frontOffset;
4378	drmsurfalloc.flags = swap_pattern;
4379
4380	if (info->tilingEnabled) {
4381	    if (IS_R300_VARIANT || IS_AVIVO_VARIANT)
4382		drmsurfalloc.flags |= (width_bytes / 8) | color_pattern;
4383	    else
4384		drmsurfalloc.flags |= (width_bytes / 16) | color_pattern;
4385	}
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 front buffer!\n");
4391
4392	if ((info->dri->have3DWindows) && (!info->dri->noBackBuffer)) {
4393	    drmsurfalloc.address = info->dri->backOffset;
4394	    retvalue = drmCommandWrite(info->dri->drmFD, DRM_RADEON_SURF_ALLOC,
4395				       &drmsurfalloc, sizeof(drmsurfalloc));
4396	    if (retvalue < 0)
4397		xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
4398			   "drm: could not allocate surface for back buffer!\n");
4399	}
4400
4401	if (info->ChipFamily < CHIP_FAMILY_R200) {
4402	    if (depthCpp == 2)
4403		depth_pattern = RADEON_SURF_TILE_DEPTH_16BPP;
4404	    else
4405		depth_pattern = RADEON_SURF_TILE_DEPTH_32BPP;
4406	} else if (IS_R300_VARIANT || IS_AVIVO_VARIANT) {
4407	    if (depthCpp == 2)
4408		depth_pattern = R300_SURF_TILE_COLOR_MACRO;
4409	    else
4410		depth_pattern = R300_SURF_TILE_COLOR_MACRO | R300_SURF_TILE_DEPTH_32BPP;
4411	} else {
4412	    if (depthCpp == 2)
4413		depth_pattern = R200_SURF_TILE_DEPTH_16BPP;
4414	    else
4415		depth_pattern = R200_SURF_TILE_DEPTH_32BPP;
4416	}
4417
4418	/* rv100 and probably the derivative igps don't have depth tiling on all the time? */
4419	if (info->dri->have3DWindows &&
4420	    (!((info->ChipFamily == CHIP_FAMILY_RV100) ||
4421	    (info->ChipFamily == CHIP_FAMILY_RS100) ||
4422	    (info->ChipFamily == CHIP_FAMILY_RS200)))) {
4423	    drm_radeon_surface_alloc_t drmsurfalloc;
4424	    drmsurfalloc.size = depthBufferSize;
4425	    drmsurfalloc.address = info->dri->depthOffset;
4426            if (IS_R300_VARIANT || IS_AVIVO_VARIANT)
4427                drmsurfalloc.flags = swap_pattern | (depth_width_bytes / 8) | depth_pattern;
4428            else
4429                drmsurfalloc.flags = swap_pattern | (depth_width_bytes / 16) | depth_pattern;
4430	    retvalue = drmCommandWrite(info->dri->drmFD, DRM_RADEON_SURF_ALLOC,
4431		&drmsurfalloc, sizeof(drmsurfalloc));
4432	    if (retvalue < 0)
4433		xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
4434		    "drm: could not allocate surface for depth buffer!\n");
4435	}
4436    }
4437    else
4438#endif
4439    {
4440	unsigned int surf_info = swap_pattern;
4441	unsigned char *RADEONMMIO = info->MMIO;
4442	/* we don't need anything like WaitForFifo, no? */
4443	if (info->tilingEnabled) {
4444	    if (IS_R300_VARIANT || IS_AVIVO_VARIANT)
4445		surf_info |= (width_bytes / 8) | color_pattern;
4446	    else
4447		surf_info |= (width_bytes / 16) | color_pattern;
4448	}
4449	OUTREG(RADEON_SURFACE0_INFO, surf_info);
4450	OUTREG(RADEON_SURFACE0_LOWER_BOUND, 0);
4451	OUTREG(RADEON_SURFACE0_UPPER_BOUND, bufferSize - 1);
4452/*	    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
4453		"surface0 set to %x, LB 0x%x UB 0x%x\n",
4454		surf_info, 0, bufferSize - 1024);*/
4455    }
4456
4457    /* Update surface images */
4458    if (info->ChipFamily < CHIP_FAMILY_R600)
4459        RADEONSaveSurfaces(pScrn, info->ModeReg);
4460}
4461
4462/* Read memory map */
4463static void RADEONSaveMemMapRegisters(ScrnInfoPtr pScrn, RADEONSavePtr save)
4464{
4465    RADEONInfoPtr  info       = RADEONPTR(pScrn);
4466    unsigned char *RADEONMMIO = info->MMIO;
4467
4468    radeon_read_mc_fb_agp_location(pScrn, LOC_FB | LOC_AGP, &save->mc_fb_location,
4469				   &save->mc_agp_location, &save->mc_agp_location_hi);
4470
4471    if (!IS_AVIVO_VARIANT) {
4472        save->display_base_addr  = INREG(RADEON_DISPLAY_BASE_ADDR);
4473        save->display2_base_addr = INREG(RADEON_DISPLAY2_BASE_ADDR);
4474        save->ov0_base_addr      = INREG(RADEON_OV0_BASE_ADDR);
4475    }
4476}
4477
4478/* Read palette data */
4479static void RADEONSavePalette(ScrnInfoPtr pScrn, int palID, RADEONSavePtr save)
4480{
4481    RADEONInfoPtr  info       = RADEONPTR(pScrn);
4482    unsigned char *RADEONMMIO = info->MMIO;
4483    int            i;
4484
4485    PAL_SELECT(palID);
4486    INPAL_START(0);
4487
4488    for (i = 0; i < 256; i++) {
4489	save->palette[palID][i] = INREG(RADEON_PALETTE_30_DATA);
4490    }
4491}
4492
4493static void RADEONRestorePalette(ScrnInfoPtr pScrn, RADEONSavePtr restore)
4494{
4495    RADEONInfoPtr  info       = RADEONPTR(pScrn);
4496    unsigned char *RADEONMMIO = info->MMIO;
4497    int            i;
4498
4499    if (restore->palette_saved[1]) {
4500	ErrorF("Restore Palette 2\n");
4501	PAL_SELECT(1);
4502	OUTPAL_START(0);
4503	for (i = 0; i < 256; i++) {
4504	    OUTREG(RADEON_PALETTE_30_DATA, restore->palette[1][i]);
4505	}
4506    }
4507    if (restore->palette_saved[0]) {
4508	ErrorF("Restore Palette 1\n");
4509	PAL_SELECT(0);
4510	OUTPAL_START(0);
4511	for (i = 0; i < 256; i++) {
4512	    OUTREG(RADEON_PALETTE_30_DATA, restore->palette[0][i]);
4513	}
4514    }
4515}
4516
4517static void
4518dce4_save_grph(ScrnInfoPtr pScrn, struct dce4_main_block_state *state,
4519	       uint32_t offset)
4520{
4521    RADEONInfoPtr info = RADEONPTR(pScrn);
4522    unsigned char *RADEONMMIO = info->MMIO;
4523
4524    state->grph.enable = INREG(offset + EVERGREEN_GRPH_ENABLE);
4525    state->grph.control = INREG(offset + EVERGREEN_GRPH_CONTROL);
4526    state->grph.swap_control = INREG(offset + EVERGREEN_GRPH_SWAP_CONTROL);
4527    state->grph.prim_surf_addr = INREG(offset + EVERGREEN_GRPH_PRIMARY_SURFACE_ADDRESS);
4528    state->grph.sec_surf_addr = INREG(offset + EVERGREEN_GRPH_SECONDARY_SURFACE_ADDRESS);
4529    state->grph.pitch = INREG(offset + EVERGREEN_GRPH_PITCH);
4530    state->grph.prim_surf_addr_hi = INREG(offset + EVERGREEN_GRPH_PRIMARY_SURFACE_ADDRESS_HIGH);
4531    state->grph.sec_surf_addr_hi = INREG(offset + EVERGREEN_GRPH_SECONDARY_SURFACE_ADDRESS_HIGH);
4532    state->grph.x_offset = INREG(offset + EVERGREEN_GRPH_SURFACE_OFFSET_X);
4533    state->grph.y_offset = INREG(offset + EVERGREEN_GRPH_SURFACE_OFFSET_Y);
4534    state->grph.x_start = INREG(offset + EVERGREEN_GRPH_X_START);
4535    state->grph.y_start = INREG(offset + EVERGREEN_GRPH_Y_START);
4536    state->grph.x_end = INREG(offset + EVERGREEN_GRPH_X_END);
4537    state->grph.y_end = INREG(offset + EVERGREEN_GRPH_Y_END);
4538
4539    state->grph.desktop_height = INREG(offset + EVERGREEN_DESKTOP_HEIGHT);
4540    state->grph.viewport_start = INREG(offset + EVERGREEN_VIEWPORT_START);
4541    state->grph.viewport_size = INREG(offset + EVERGREEN_VIEWPORT_SIZE);
4542    state->grph.mode_data_format = INREG(offset + EVERGREEN_DATA_FORMAT);
4543}
4544
4545static void
4546dce4_restore_grph(ScrnInfoPtr pScrn, struct dce4_main_block_state *state,
4547	       uint32_t offset)
4548{
4549    RADEONInfoPtr info = RADEONPTR(pScrn);
4550    unsigned char *RADEONMMIO = info->MMIO;
4551
4552    OUTREG(offset + EVERGREEN_GRPH_ENABLE, state->grph.enable);
4553    OUTREG(offset + EVERGREEN_GRPH_CONTROL, state->grph.control);
4554    OUTREG(offset + EVERGREEN_GRPH_SWAP_CONTROL, state->grph.swap_control);
4555    OUTREG(offset + EVERGREEN_GRPH_PRIMARY_SURFACE_ADDRESS, state->grph.prim_surf_addr);
4556    OUTREG(offset + EVERGREEN_GRPH_SECONDARY_SURFACE_ADDRESS, state->grph.sec_surf_addr);
4557    OUTREG(offset + EVERGREEN_GRPH_PITCH, state->grph.pitch);
4558    OUTREG(offset + EVERGREEN_GRPH_PRIMARY_SURFACE_ADDRESS_HIGH, state->grph.prim_surf_addr_hi);
4559    OUTREG(offset + EVERGREEN_GRPH_SECONDARY_SURFACE_ADDRESS_HIGH, state->grph.sec_surf_addr_hi);
4560    OUTREG(offset + EVERGREEN_GRPH_SURFACE_OFFSET_X, state->grph.x_offset);
4561    OUTREG(offset + EVERGREEN_GRPH_SURFACE_OFFSET_Y, state->grph.y_offset);
4562    OUTREG(offset + EVERGREEN_GRPH_X_START, state->grph.x_start);
4563    OUTREG(offset + EVERGREEN_GRPH_Y_START, state->grph.y_start);
4564    OUTREG(offset + EVERGREEN_GRPH_X_END, state->grph.x_end);
4565    OUTREG(offset + EVERGREEN_GRPH_Y_END, state->grph.y_end);
4566
4567    OUTREG(offset + EVERGREEN_DESKTOP_HEIGHT, state->grph.desktop_height);
4568    OUTREG(offset + EVERGREEN_VIEWPORT_START, state->grph.viewport_start);
4569    OUTREG(offset + EVERGREEN_VIEWPORT_SIZE, state->grph.viewport_size);
4570    OUTREG(offset + EVERGREEN_DATA_FORMAT, state->grph.mode_data_format);
4571}
4572
4573static uint32_t dce4_dac_regs[] = {
4574    0x6690, 0x6694, 0x66b0, 0x66cc, 0x66d0, 0x66d4, 0x66d8 };
4575
4576static uint32_t dce4_scl_regs[] = {
4577    0x6d08, 0x6d0c, 0x6d14, 0x6d1c };
4578
4579static uint32_t dce4_dig_regs[] = {
4580    0x7000, 0x7004, 0x7008, 0x700c, 0x7010, 0x7014,
4581    0x71f0, 0x71f4, 0x71f8, 0x71fc, 0x7200, 0x7204,
4582    0x7208, 0x720c, 0x7210, 0x7218, 0x721c, 0x7220,
4583    0x7230};
4584
4585static uint32_t dce4_crtc_regs[] = {
4586    0x6e00, 0x6e04, 0x6e08, 0x6e0c, 0x6e1c, 0x6e34, 0x6e38, 0x6e3c, 0x6e70, 0x6e74, 0x6e78};
4587
4588
4589#define DCE4_REG_SCL_NUM (sizeof(dce4_scl_regs)/sizeof(uint32_t))
4590#define DCE4_REG_CRTC_NUM (sizeof(dce4_crtc_regs)/sizeof(uint32_t))
4591#define DCE4_REG_DIG_NUM (sizeof(dce4_dig_regs)/sizeof(uint32_t))
4592#define DCE4_DAC_NUM (sizeof(dce4_dac_regs)/sizeof(uint32_t))
4593
4594
4595static void
4596dce4_save_crtc(ScrnInfoPtr pScrn, struct dce4_main_block_state *state,
4597	       uint32_t offset)
4598{
4599    RADEONInfoPtr info = RADEONPTR(pScrn);
4600    unsigned char *RADEONMMIO = info->MMIO;
4601    int i;
4602
4603    for (i = 0; i < DCE4_REG_CRTC_NUM; i++)
4604        state->crtc[i] = INREG(offset + dce4_crtc_regs[i]);
4605}
4606
4607static void
4608dce4_restore_crtc(ScrnInfoPtr pScrn, struct dce4_main_block_state *state,
4609		  uint32_t offset)
4610{
4611    RADEONInfoPtr info = RADEONPTR(pScrn);
4612    unsigned char *RADEONMMIO = info->MMIO;
4613    int i;
4614
4615    for (i = 0; i < DCE4_REG_CRTC_NUM; i++)
4616        OUTREG(offset + dce4_crtc_regs[i], state->crtc[i]);
4617}
4618
4619static void
4620dce4_save_scl(ScrnInfoPtr pScrn, struct dce4_main_block_state *state,
4621	      uint32_t offset)
4622{
4623    RADEONInfoPtr info = RADEONPTR(pScrn);
4624    unsigned char *RADEONMMIO = info->MMIO;
4625    int i;
4626
4627    for (i = 0; i < DCE4_REG_SCL_NUM; i++)
4628        state->scl[i] = INREG(offset + dce4_scl_regs[i]);
4629}
4630
4631static void
4632dce4_restore_scl(ScrnInfoPtr pScrn, struct dce4_main_block_state *state,
4633	      uint32_t offset)
4634{
4635    RADEONInfoPtr info = RADEONPTR(pScrn);
4636    unsigned char *RADEONMMIO = info->MMIO;
4637    int i;
4638
4639    for (i = 0; i < DCE4_REG_SCL_NUM; i++)
4640        OUTREG(offset + dce4_scl_regs[i], state->scl[i]);
4641}
4642
4643
4644static void
4645dce4_save_fmt(ScrnInfoPtr pScrn, struct dce4_main_block_state *state,
4646	      uint32_t offset)
4647{
4648    RADEONInfoPtr info = RADEONPTR(pScrn);
4649    unsigned char *RADEONMMIO = info->MMIO;
4650    int i, index = 0;
4651
4652    for (i = 0x6fb4; i <= 0x6fd4; i += 4)
4653	state->fmt[index++] = INREG(offset + i);
4654}
4655
4656static void
4657dce4_restore_fmt(ScrnInfoPtr pScrn, struct dce4_main_block_state *state,
4658	      uint32_t offset)
4659{
4660    RADEONInfoPtr info = RADEONPTR(pScrn);
4661    unsigned char *RADEONMMIO = info->MMIO;
4662    int i, index = 0;
4663
4664    for (i = 0x6fb4; i <= 0x6fd4; i += 4)
4665	OUTREG(offset + i, state->fmt[index++]);
4666}
4667
4668
4669static void
4670dce4_save_dig(ScrnInfoPtr pScrn, struct dce4_main_block_state *state,
4671	      uint32_t offset)
4672{
4673    RADEONInfoPtr info = RADEONPTR(pScrn);
4674    unsigned char *RADEONMMIO = info->MMIO;
4675    int i;
4676
4677    for (i = 0; i < DCE4_REG_DIG_NUM; i++)
4678        state->dig[i] = INREG(offset + dce4_dig_regs[i]);
4679}
4680
4681static void
4682dce4_restore_dig(ScrnInfoPtr pScrn, struct dce4_main_block_state *state,
4683	      uint32_t offset)
4684{
4685    RADEONInfoPtr info = RADEONPTR(pScrn);
4686    unsigned char *RADEONMMIO = info->MMIO;
4687    int i;
4688
4689    for (i = 0; i < DCE4_REG_DIG_NUM; i++)
4690        OUTREG(offset + dce4_dig_regs[i], state->dig[i]);
4691}
4692
4693
4694
4695static void dce4_save_block(ScrnInfoPtr pScrn, struct dce4_main_block_state *state,
4696			    uint32_t offset)
4697{
4698    dce4_save_grph(pScrn, state, offset);
4699    dce4_save_crtc(pScrn, state, offset);
4700    dce4_save_scl(pScrn, state, offset);
4701    dce4_save_dig(pScrn, state, offset);
4702    dce4_save_fmt(pScrn, state, offset);
4703}
4704
4705static void dce4_restore_block(ScrnInfoPtr pScrn, struct dce4_main_block_state *state,
4706			       uint32_t offset)
4707{
4708    dce4_restore_grph(pScrn, state, offset);
4709    dce4_restore_crtc(pScrn, state, offset);
4710    dce4_restore_scl(pScrn, state, offset);
4711    dce4_restore_dig(pScrn, state, offset);
4712    dce4_restore_fmt(pScrn, state, offset);
4713}
4714
4715static void dce4_save_uniphy(ScrnInfoPtr pScrn, struct dce4_state *state, int index)
4716{
4717    RADEONInfoPtr info = RADEONPTR(pScrn);
4718    unsigned char *RADEONMMIO = info->MMIO;
4719    uint32_t uniphy_offset[6] = {0x0, 0x30, 0x60, 0x100, 0x130, 0x160 };
4720    int i, ri = 0;
4721    for (i = 0; i < 0x18; i+=4)
4722	state->uniphy[index][ri++] = INREG(0x6600 + uniphy_offset[index] + i);
4723}
4724
4725static void dce4_restore_uniphy(ScrnInfoPtr pScrn, struct dce4_state *state, int index)
4726{
4727    RADEONInfoPtr info = RADEONPTR(pScrn);
4728    unsigned char *RADEONMMIO = info->MMIO;
4729    uint32_t uniphy_offset[6] = {0x0, 0x30, 0x60, 0x100, 0x130, 0x160 };
4730    int i, ri = 0;
4731    for (i = 0; i <= 0x18; i+=4)
4732	OUTREG(0x6600 + uniphy_offset[index] + i, state->uniphy[index][ri++]);
4733}
4734
4735static void dce4_save_dig_regs(ScrnInfoPtr pScrn, struct dce4_state *state)
4736{
4737    RADEONInfoPtr info = RADEONPTR(pScrn);
4738    unsigned char *RADEONMMIO = info->MMIO;
4739    int i, ri = 0;
4740
4741    for (i = 0x6578; i <= 0x6598; i += 4)
4742	state->dig[ri++] = INREG(i);
4743    for (i = 0x65ac; i <= 0x65d8; i += 4)
4744	state->dig[ri++] = INREG(i);
4745}
4746
4747static void dce4_restore_dig_regs(ScrnInfoPtr pScrn, struct dce4_state *state)
4748{
4749    RADEONInfoPtr info = RADEONPTR(pScrn);
4750    unsigned char *RADEONMMIO = info->MMIO;
4751    int i, ri = 0;
4752
4753    for (i = 0x6578; i <= 0x6598; i += 4)
4754	OUTREG(i, state->dig[ri++]);
4755    for (i = 0x65ac; i <= 0x65d8; i += 4)
4756	OUTREG(i, state->dig[ri++]);
4757}
4758
4759static void dce4_save_pll_regs(ScrnInfoPtr pScrn, struct dce4_state *state)
4760{
4761    RADEONInfoPtr info = RADEONPTR(pScrn);
4762    unsigned char *RADEONMMIO = info->MMIO;
4763    int i, ri = 0;
4764
4765    for (i = 0x360; i <= 0x368; i += 4)
4766	state->vga_pll[0][ri++] = INREG(i);
4767
4768    ri = 0;
4769    for (i = 0x370; i <= 0x378; i += 4)
4770	state->vga_pll[1][ri++] = INREG(i);
4771
4772    ri = 0;
4773    for (i = 0x390; i <= 0x398; i += 4)
4774	state->vga_pll[2][ri++] = INREG(i);
4775
4776    ri = 0;
4777    for (i = 0x400; i <= 0x408; i += 4)
4778	state->pll[0][ri++] = INREG(i);
4779    for (i = 0x410; i <= 0x43c; i += 4)
4780	state->pll[0][ri++] = INREG(i);
4781
4782    ri = 0;
4783    for (i = 0x440; i <= 0x448; i += 4)
4784	state->pll[1][ri++] = INREG(i);
4785    for (i = 0x450; i <= 0x47c; i += 4)
4786	state->pll[1][ri++] = INREG(i);
4787
4788    ri = 0;
4789    for (i = 0x500; i <= 0x550; i += 0x10)
4790	state->pll_route[ri++] = INREG(i);
4791}
4792
4793static void dce4_restore_pll_regs(ScrnInfoPtr pScrn, struct dce4_state *state)
4794{
4795    RADEONInfoPtr info = RADEONPTR(pScrn);
4796    unsigned char *RADEONMMIO = info->MMIO;
4797    int i, ri = 0;
4798
4799    for (i = 0x360; i <= 0x368; i += 4)
4800	OUTREG(i, state->vga_pll[0][ri++]);
4801
4802    ri = 0;
4803    for (i = 0x370; i <= 0x378; i += 4)
4804	OUTREG(i, state->vga_pll[1][ri++]);
4805
4806    ri = 0;
4807    for (i = 0x390; i <= 0x398; i += 4)
4808	OUTREG(i, state->vga_pll[2][ri++]);
4809
4810    ri = 0;
4811    for (i = 0x400; i <= 0x408; i += 4)
4812	OUTREG(i, state->pll[0][ri++]);
4813    for (i = 0x410; i <= 0x43c; i += 4)
4814	OUTREG(i, state->pll[0][ri++]);
4815
4816    ri = 0;
4817    for (i = 0x440; i <= 0x448; i += 4)
4818	OUTREG(i, state->pll[1][ri++]);
4819    for (i = 0x450; i <= 0x47c; i += 4)
4820	OUTREG(i, state->pll[1][ri++]);
4821
4822    ri = 0;
4823    for (i = 0x500; i <= 0x550; i += 0x10)
4824	OUTREG(i, state->pll_route[ri++]);
4825}
4826
4827static void
4828dce4_save(ScrnInfoPtr pScrn, RADEONSavePtr save)
4829{
4830    RADEONInfoPtr info = RADEONPTR(pScrn);
4831    unsigned char *RADEONMMIO = info->MMIO;
4832    struct dce4_state *state = &save->dce4;
4833    int i, j;
4834    uint32_t crtc_offset[] = {EVERGREEN_CRTC0_REGISTER_OFFSET,
4835			      EVERGREEN_CRTC1_REGISTER_OFFSET,
4836			      EVERGREEN_CRTC2_REGISTER_OFFSET,
4837			      EVERGREEN_CRTC3_REGISTER_OFFSET,
4838			      EVERGREEN_CRTC4_REGISTER_OFFSET,
4839			      EVERGREEN_CRTC5_REGISTER_OFFSET};
4840
4841    state->vga1_cntl = INREG(AVIVO_D1VGA_CONTROL);
4842    state->vga2_cntl = INREG(AVIVO_D2VGA_CONTROL);
4843    state->vga3_cntl = INREG(EVERGREEN_D3VGA_CONTROL);
4844    state->vga4_cntl = INREG(EVERGREEN_D4VGA_CONTROL);
4845    state->vga5_cntl = INREG(EVERGREEN_D5VGA_CONTROL);
4846    state->vga6_cntl = INREG(EVERGREEN_D6VGA_CONTROL);
4847    state->vga_render_control = INREG(AVIVO_VGA_RENDER_CONTROL);
4848
4849    dce4_save_pll_regs(pScrn, state);
4850    dce4_save_dig_regs(pScrn, state);
4851
4852    for (i = 0; i < 6; i++)
4853	dce4_save_block(pScrn, &state->block[i], crtc_offset[i]);
4854
4855    for (i = 0; i < 6; i++)
4856	dce4_save_uniphy(pScrn, state, i);
4857
4858    for (i = 0; i < 2; i++) {
4859	for (j = 0; j < DCE4_DAC_NUM; j++) {
4860	    uint32_t offset = i ? 0x100 : 0x0;
4861	    state->dac[i][j] = INREG(dce4_dac_regs[j] + offset);
4862	}
4863    }
4864}
4865
4866static void
4867dce4_restore(ScrnInfoPtr pScrn, RADEONSavePtr restore)
4868{
4869    RADEONInfoPtr info = RADEONPTR(pScrn);
4870    unsigned char *RADEONMMIO = info->MMIO;
4871    struct dce4_state *state = &restore->dce4;
4872    int i, j;
4873    uint32_t crtc_offset[] = {EVERGREEN_CRTC0_REGISTER_OFFSET,
4874			      EVERGREEN_CRTC1_REGISTER_OFFSET,
4875			      EVERGREEN_CRTC2_REGISTER_OFFSET,
4876			      EVERGREEN_CRTC3_REGISTER_OFFSET,
4877			      EVERGREEN_CRTC4_REGISTER_OFFSET,
4878			      EVERGREEN_CRTC5_REGISTER_OFFSET};
4879
4880    OUTREG(AVIVO_D1VGA_CONTROL, state->vga1_cntl);
4881    OUTREG(AVIVO_D2VGA_CONTROL, state->vga2_cntl);;
4882    OUTREG(EVERGREEN_D3VGA_CONTROL, state->vga3_cntl);
4883    OUTREG(EVERGREEN_D4VGA_CONTROL, state->vga4_cntl);
4884    OUTREG(EVERGREEN_D5VGA_CONTROL, state->vga5_cntl);
4885    OUTREG(EVERGREEN_D6VGA_CONTROL, state->vga6_cntl);
4886    OUTREG(AVIVO_VGA_RENDER_CONTROL, state->vga_render_control);
4887
4888    dce4_restore_dig_regs(pScrn, state);
4889    dce4_restore_pll_regs(pScrn, state);
4890    for (i = 0; i < 6; i++)
4891	dce4_restore_uniphy(pScrn, state, i);
4892
4893    for (i = 0; i < 6; i++)
4894	dce4_restore_block(pScrn, &state->block[i], crtc_offset[i]);
4895
4896    for (i = 0; i < 2; i++) {
4897	for (j = 0; j < DCE4_DAC_NUM; j++) {
4898	    uint32_t offset = i ? 0x100 : 0x0;
4899	    OUTREG(dce4_dac_regs[j] + offset, state->dac[i][j]);
4900	}
4901    }
4902}
4903
4904static void
4905avivo_save(ScrnInfoPtr pScrn, RADEONSavePtr save)
4906{
4907    RADEONInfoPtr info = RADEONPTR(pScrn);
4908    unsigned char *RADEONMMIO = info->MMIO;
4909    struct avivo_state *state = &save->avivo;
4910    int i, j;
4911
4912    //    state->vga_memory_base = INREG(AVIVO_VGA_MEMORY_BASE);
4913    //    state->vga_fb_start = INREG(AVIVO_VGA_FB_START);
4914    state->vga1_cntl = INREG(AVIVO_D1VGA_CONTROL);
4915    state->vga2_cntl = INREG(AVIVO_D2VGA_CONTROL);
4916    state->vga_render_control = INREG(AVIVO_VGA_RENDER_CONTROL);
4917
4918    state->crtc_master_en = INREG(AVIVO_DC_CRTC_MASTER_EN);
4919    state->crtc_tv_control = INREG(AVIVO_DC_CRTC_TV_CONTROL);
4920    state->dc_lb_memory_split = INREG(AVIVO_DC_LB_MEMORY_SPLIT);
4921
4922    state->pll[0].ref_div_src = INREG(AVIVO_EXT1_PPLL_REF_DIV_SRC);
4923    state->pll[0].ref_div = INREG(AVIVO_EXT1_PPLL_REF_DIV);
4924    state->pll[0].fb_div = INREG(AVIVO_EXT1_PPLL_FB_DIV);
4925    state->pll[0].post_div_src = INREG(AVIVO_EXT1_PPLL_POST_DIV_SRC);
4926    state->pll[0].post_div = INREG(AVIVO_EXT1_PPLL_POST_DIV);
4927    state->pll[0].ext_ppll_cntl = INREG(AVIVO_EXT1_PPLL_CNTL);
4928    state->pll[0].pll_cntl = INREG(AVIVO_P1PLL_CNTL);
4929    state->pll[0].int_ss_cntl = INREG(AVIVO_P1PLL_INT_SS_CNTL);
4930
4931    state->pll[1].ref_div_src = INREG(AVIVO_EXT1_PPLL_REF_DIV_SRC);
4932    state->pll[1].ref_div = INREG(AVIVO_EXT2_PPLL_REF_DIV);
4933    state->pll[1].fb_div = INREG(AVIVO_EXT2_PPLL_FB_DIV);
4934    state->pll[1].post_div_src = INREG(AVIVO_EXT2_PPLL_POST_DIV_SRC);
4935    state->pll[1].post_div = INREG(AVIVO_EXT2_PPLL_POST_DIV);
4936    state->pll[1].ext_ppll_cntl = INREG(AVIVO_EXT2_PPLL_CNTL);
4937    state->pll[1].pll_cntl = INREG(AVIVO_P2PLL_CNTL);
4938    state->pll[1].int_ss_cntl = INREG(AVIVO_P2PLL_INT_SS_CNTL);
4939
4940    state->vga25_ppll.ref_div_src = INREG(AVIVO_VGA25_PPLL_REF_DIV_SRC);
4941    state->vga25_ppll.ref_div = INREG(AVIVO_VGA25_PPLL_REF_DIV);
4942    state->vga25_ppll.fb_div = INREG(AVIVO_VGA25_PPLL_FB_DIV);
4943    state->vga25_ppll.post_div_src = INREG(AVIVO_VGA25_PPLL_POST_DIV_SRC);
4944    state->vga25_ppll.post_div = INREG(AVIVO_VGA25_PPLL_POST_DIV);
4945    state->vga25_ppll.pll_cntl = INREG(AVIVO_VGA25_PPLL_CNTL);
4946
4947    state->vga28_ppll.ref_div_src = INREG(AVIVO_VGA28_PPLL_REF_DIV_SRC);
4948    state->vga28_ppll.ref_div = INREG(AVIVO_VGA28_PPLL_REF_DIV);
4949    state->vga28_ppll.fb_div = INREG(AVIVO_VGA28_PPLL_FB_DIV);
4950    state->vga28_ppll.post_div_src = INREG(AVIVO_VGA28_PPLL_POST_DIV_SRC);
4951    state->vga28_ppll.post_div = INREG(AVIVO_VGA28_PPLL_POST_DIV);
4952    state->vga28_ppll.pll_cntl = INREG(AVIVO_VGA28_PPLL_CNTL);
4953
4954    state->vga41_ppll.ref_div_src = INREG(AVIVO_VGA41_PPLL_REF_DIV_SRC);
4955    state->vga41_ppll.ref_div = INREG(AVIVO_VGA41_PPLL_REF_DIV);
4956    state->vga41_ppll.fb_div = INREG(AVIVO_VGA41_PPLL_FB_DIV);
4957    state->vga41_ppll.post_div_src = INREG(AVIVO_VGA41_PPLL_POST_DIV_SRC);
4958    state->vga41_ppll.post_div = INREG(AVIVO_VGA41_PPLL_POST_DIV);
4959    state->vga41_ppll.pll_cntl = INREG(AVIVO_VGA41_PPLL_CNTL);
4960
4961    state->crtc[0].pll_source = INREG(AVIVO_PCLK_CRTC1_CNTL);
4962
4963    state->crtc[0].h_total = INREG(AVIVO_D1CRTC_H_TOTAL);
4964    state->crtc[0].h_blank_start_end = INREG(AVIVO_D1CRTC_H_BLANK_START_END);
4965    state->crtc[0].h_sync_a = INREG(AVIVO_D1CRTC_H_SYNC_A);
4966    state->crtc[0].h_sync_a_cntl = INREG(AVIVO_D1CRTC_H_SYNC_A_CNTL);
4967    state->crtc[0].h_sync_b = INREG(AVIVO_D1CRTC_H_SYNC_B);
4968    state->crtc[0].h_sync_b_cntl = INREG(AVIVO_D1CRTC_H_SYNC_B_CNTL);
4969
4970    state->crtc[0].v_total = INREG(AVIVO_D1CRTC_V_TOTAL);
4971    state->crtc[0].v_blank_start_end = INREG(AVIVO_D1CRTC_V_BLANK_START_END);
4972    state->crtc[0].v_sync_a = INREG(AVIVO_D1CRTC_V_SYNC_A);
4973    state->crtc[0].v_sync_a_cntl = INREG(AVIVO_D1CRTC_V_SYNC_A_CNTL);
4974    state->crtc[0].v_sync_b = INREG(AVIVO_D1CRTC_V_SYNC_B);
4975    state->crtc[0].v_sync_b_cntl = INREG(AVIVO_D1CRTC_V_SYNC_B_CNTL);
4976
4977    state->crtc[0].control = INREG(AVIVO_D1CRTC_CONTROL);
4978    state->crtc[0].blank_control = INREG(AVIVO_D1CRTC_BLANK_CONTROL);
4979    state->crtc[0].interlace_control = INREG(AVIVO_D1CRTC_INTERLACE_CONTROL);
4980    state->crtc[0].stereo_control = INREG(AVIVO_D1CRTC_STEREO_CONTROL);
4981
4982    state->crtc[0].cursor_control = INREG(AVIVO_D1CUR_CONTROL);
4983
4984    state->grph[0].enable = INREG(AVIVO_D1GRPH_ENABLE);
4985    state->grph[0].control = INREG(AVIVO_D1GRPH_CONTROL);
4986    state->grph[0].control = INREG(AVIVO_D1GRPH_CONTROL);
4987    state->grph[0].prim_surf_addr = INREG(AVIVO_D1GRPH_PRIMARY_SURFACE_ADDRESS);
4988    state->grph[0].sec_surf_addr = INREG(AVIVO_D1GRPH_SECONDARY_SURFACE_ADDRESS);
4989    state->grph[0].pitch = INREG(AVIVO_D1GRPH_PITCH);
4990    state->grph[0].x_offset = INREG(AVIVO_D1GRPH_SURFACE_OFFSET_X);
4991    state->grph[0].y_offset = INREG(AVIVO_D1GRPH_SURFACE_OFFSET_Y);
4992    state->grph[0].x_start = INREG(AVIVO_D1GRPH_X_START);
4993    state->grph[0].y_start = INREG(AVIVO_D1GRPH_Y_START);
4994    state->grph[0].x_end = INREG(AVIVO_D1GRPH_X_END);
4995    state->grph[0].y_end = INREG(AVIVO_D1GRPH_Y_END);
4996
4997    state->grph[0].desktop_height = INREG(AVIVO_D1MODE_DESKTOP_HEIGHT);
4998    state->grph[0].viewport_start = INREG(AVIVO_D1MODE_VIEWPORT_START);
4999    state->grph[0].viewport_size = INREG(AVIVO_D1MODE_VIEWPORT_SIZE);
5000    state->grph[0].mode_data_format = INREG(AVIVO_D1MODE_DATA_FORMAT);
5001
5002    state->crtc[1].pll_source = INREG(AVIVO_PCLK_CRTC2_CNTL);
5003
5004    state->crtc[1].h_total = INREG(AVIVO_D2CRTC_H_TOTAL);
5005    state->crtc[1].h_blank_start_end = INREG(AVIVO_D2CRTC_H_BLANK_START_END);
5006    state->crtc[1].h_sync_a = INREG(AVIVO_D2CRTC_H_SYNC_A);
5007    state->crtc[1].h_sync_a_cntl = INREG(AVIVO_D2CRTC_H_SYNC_A_CNTL);
5008    state->crtc[1].h_sync_b = INREG(AVIVO_D2CRTC_H_SYNC_B);
5009    state->crtc[1].h_sync_b_cntl = INREG(AVIVO_D2CRTC_H_SYNC_B_CNTL);
5010
5011    state->crtc[1].v_total = INREG(AVIVO_D2CRTC_V_TOTAL);
5012    state->crtc[1].v_blank_start_end = INREG(AVIVO_D2CRTC_V_BLANK_START_END);
5013    state->crtc[1].v_sync_a = INREG(AVIVO_D2CRTC_V_SYNC_A);
5014    state->crtc[1].v_sync_a_cntl = INREG(AVIVO_D2CRTC_V_SYNC_A_CNTL);
5015    state->crtc[1].v_sync_b = INREG(AVIVO_D2CRTC_V_SYNC_B);
5016    state->crtc[1].v_sync_b_cntl = INREG(AVIVO_D2CRTC_V_SYNC_B_CNTL);
5017
5018    state->crtc[1].control = INREG(AVIVO_D2CRTC_CONTROL);
5019    state->crtc[1].blank_control = INREG(AVIVO_D2CRTC_BLANK_CONTROL);
5020    state->crtc[1].interlace_control = INREG(AVIVO_D2CRTC_INTERLACE_CONTROL);
5021    state->crtc[1].stereo_control = INREG(AVIVO_D2CRTC_STEREO_CONTROL);
5022
5023    state->crtc[1].cursor_control = INREG(AVIVO_D2CUR_CONTROL);
5024
5025    state->grph[1].enable = INREG(AVIVO_D2GRPH_ENABLE);
5026    state->grph[1].control = INREG(AVIVO_D2GRPH_CONTROL);
5027    state->grph[1].control = INREG(AVIVO_D2GRPH_CONTROL);
5028    state->grph[1].prim_surf_addr = INREG(AVIVO_D2GRPH_PRIMARY_SURFACE_ADDRESS);
5029    state->grph[1].sec_surf_addr = INREG(AVIVO_D2GRPH_SECONDARY_SURFACE_ADDRESS);
5030    state->grph[1].pitch = INREG(AVIVO_D2GRPH_PITCH);
5031    state->grph[1].x_offset = INREG(AVIVO_D2GRPH_SURFACE_OFFSET_X);
5032    state->grph[1].y_offset = INREG(AVIVO_D2GRPH_SURFACE_OFFSET_Y);
5033    state->grph[1].x_start = INREG(AVIVO_D2GRPH_X_START);
5034    state->grph[1].y_start = INREG(AVIVO_D2GRPH_Y_START);
5035    state->grph[1].x_end = INREG(AVIVO_D2GRPH_X_END);
5036    state->grph[1].y_end = INREG(AVIVO_D2GRPH_Y_END);
5037
5038    state->grph[1].desktop_height = INREG(AVIVO_D2MODE_DESKTOP_HEIGHT);
5039    state->grph[1].viewport_start = INREG(AVIVO_D2MODE_VIEWPORT_START);
5040    state->grph[1].viewport_size = INREG(AVIVO_D2MODE_VIEWPORT_SIZE);
5041    state->grph[1].mode_data_format = INREG(AVIVO_D2MODE_DATA_FORMAT);
5042
5043    if (IS_DCE3_VARIANT) {
5044	/* save DVOA regs */
5045	state->dvoa[0] = INREG(0x7080);
5046	state->dvoa[1] = INREG(0x7084);
5047	state->dvoa[2] = INREG(0x708c);
5048	state->dvoa[3] = INREG(0x7090);
5049	state->dvoa[4] = INREG(0x7094);
5050	state->dvoa[5] = INREG(0x70ac);
5051	state->dvoa[6] = INREG(0x70b0);
5052
5053	j = 0;
5054	/* save DAC regs */
5055	for (i = 0x7000; i <= 0x7040; i += 4) {
5056	    state->daca[j] = INREG(i);
5057	    state->dacb[j] = INREG(i + 0x100);
5058	    j++;
5059	}
5060	for (i = 0x7058; i <= 0x7060; i += 4) {
5061	    state->daca[j] = INREG(i);
5062	    state->dacb[j] = INREG(i + 0x100);
5063	    j++;
5064	}
5065	for (i = 0x7068; i <= 0x706c; i += 4) {
5066	    state->daca[j] = INREG(i);
5067	    state->dacb[j] = INREG(i + 0x100);
5068	    j++;
5069	}
5070	for (i = 0x7ef0; i <= 0x7ef8; i += 4) {
5071	    state->daca[j] = INREG(i);
5072	    state->dacb[j] = INREG(i + 0x100);
5073	    j++;
5074	}
5075	state->daca[j] = INREG(0x7050);
5076	state->dacb[j] = INREG(0x7050 + 0x100);
5077
5078	j = 0;
5079	/* save FMT regs */
5080	for (i = 0x6700; i <= 0x6744; i += 4) {
5081	    state->fmt1[j] = INREG(i);
5082	    state->fmt2[j] = INREG(i + 0x800);
5083	    j++;
5084	}
5085
5086	j = 0;
5087	/* save DIG regs */
5088	for (i = 0x75a0; i <= 0x75e0; i += 4) {
5089	    state->dig1[j] = INREG(i);
5090	    state->dig2[j] = INREG(i + 0x400);
5091	    j++;
5092	}
5093	for (i = 0x75e8; i <= 0x75ec; i += 4) {
5094	    state->dig1[j] = INREG(i);
5095	    state->dig2[j] = INREG(i + 0x400);
5096	    j++;
5097	}
5098
5099	j = 0;
5100	/* save HDMI regs */
5101	for (i = 0x7400; i <= 0x741c; i += 4) {
5102	    state->hdmi1[j] = INREG(i);
5103	    state->hdmi2[j] = INREG(i + 0x400);
5104	    j++;
5105	}
5106	for (i = 0x7430; i <= 0x74ec; i += 4) {
5107	    state->hdmi1[j] = INREG(i);
5108	    state->hdmi2[j] = INREG(i + 0x400);
5109	    j++;
5110	}
5111	state->hdmi1[j] = INREG(0x7428);
5112	state->hdmi2[j] = INREG(0x7828);
5113
5114	j = 0;
5115	/* save AUX regs */
5116	for (i = 0x7780; i <= 0x77b4; i += 4) {
5117	    state->aux_cntl1[j] = INREG(i);
5118	    state->aux_cntl2[j] = INREG(i + 0x040);
5119	    state->aux_cntl3[j] = INREG(i + 0x400);
5120	    state->aux_cntl4[j] = INREG(i + 0x440);
5121	    if (IS_DCE32_VARIANT) {
5122		state->aux_cntl5[j] = INREG(i + 0x500);
5123		state->aux_cntl6[j] = INREG(i + 0x540);
5124	    }
5125	    j++;
5126	}
5127
5128	j = 0;
5129	/* save UNIPHY regs */
5130	if (IS_DCE32_VARIANT) {
5131	    for (i = 0x7680; i <= 0x7690; i += 4) {
5132		state->uniphy1[j] = INREG(i);
5133		state->uniphy2[j] = INREG(i + 0x20);
5134		state->uniphy3[j] = INREG(i + 0x400);
5135		state->uniphy4[j] = INREG(i + 0x420);
5136		state->uniphy5[j] = INREG(i + 0x840);
5137		state->uniphy6[j] = INREG(i + 0x940);
5138		j++;
5139	    }
5140	    for (i = 0x7698; i <= 0x769c; i += 4) {
5141		state->uniphy1[j] = INREG(i);
5142		state->uniphy2[j] = INREG(i + 0x20);
5143		state->uniphy3[j] = INREG(i + 0x400);
5144		state->uniphy4[j] = INREG(i + 0x420);
5145		state->uniphy5[j] = INREG(i + 0x840);
5146		state->uniphy6[j] = INREG(i + 0x940);
5147		j++;
5148	    }
5149	} else {
5150	    for (i = 0x7ec0; i <= 0x7edc; i += 4) {
5151		state->uniphy1[j] = INREG(i);
5152		state->uniphy2[j] = INREG(i + 0x100);
5153		j++;
5154	    }
5155	}
5156	j = 0;
5157	/* save PHY,LINK regs */
5158	for (i = 0x7f20; i <= 0x7f34; i += 4) {
5159	    state->phy[j] = INREG(i);
5160	    j++;
5161	}
5162	for (i = 0x7f9c; i <= 0x7fa4; i += 4) {
5163	    state->phy[j] = INREG(i);
5164	    j++;
5165	}
5166	state->phy[j] = INREG(0x7f40);
5167
5168	j = 0;
5169	/* save LVTMA regs */
5170	for (i = 0x7f00; i <= 0x7f1c; i += 4) {
5171	    state->lvtma[j] = INREG(i);
5172	    j++;
5173	}
5174	for (i = 0x7f80; i <= 0x7f98; i += 4) {
5175	    state->lvtma[j] = INREG(i);
5176	    j++;
5177	}
5178    } else {
5179	j = 0;
5180	/* save DVOA regs */
5181	for (i = 0x7980; i <= 0x79bc; i += 4) {
5182	    state->dvoa[j] = INREG(i);
5183	    j++;
5184	}
5185
5186	j = 0;
5187	/* save DAC regs */
5188	for (i = 0x7800; i <= 0x782c; i += 4) {
5189	    state->daca[j] = INREG(i);
5190	    state->dacb[j] = INREG(i + 0x200);
5191	    j++;
5192	}
5193	for (i = 0x7834; i <= 0x7840; i += 4) {
5194	    state->daca[j] = INREG(i);
5195	    state->dacb[j] = INREG(i + 0x200);
5196	    j++;
5197	}
5198	for (i = 0x7850; i <= 0x7868; i += 4) {
5199	    state->daca[j] = INREG(i);
5200	    state->dacb[j] = INREG(i + 0x200);
5201	    j++;
5202	}
5203
5204	j = 0;
5205	/* save TMDSA regs */
5206	for (i = 0x7880; i <= 0x78e0; i += 4) {
5207	    state->tmdsa[j] = INREG(i);
5208	    j++;
5209	}
5210	for (i = 0x7904; i <= 0x7918; i += 4) {
5211	    state->tmdsa[j] = INREG(i);
5212	    j++;
5213	}
5214
5215	j = 0;
5216	/* save LVTMA regs */
5217	for (i = 0x7a80; i <= 0x7b18; i += 4) {
5218	    state->lvtma[j] = INREG(i);
5219	    j++;
5220	}
5221
5222	if ((info->ChipFamily == CHIP_FAMILY_RS600) ||
5223	    (info->ChipFamily == CHIP_FAMILY_RS690) ||
5224	    (info->ChipFamily == CHIP_FAMILY_RS740)) {
5225	    j = 0;
5226	    /* save DDIA regs */
5227	    for (i = 0x7200; i <= 0x7290; i += 4) {
5228		state->ddia[j] = INREG(i);
5229		j++;
5230	    }
5231	}
5232    }
5233
5234    /* scalers */
5235    j = 0;
5236    for (i = 0x6578; i <= 0x65e4; i += 4) {
5237	state->d1scl[j] = INREG(i);
5238	state->d2scl[j] = INREG(i + 0x800);
5239	j++;
5240    }
5241    for (i = 0x6600; i <= 0x662c; i += 4) {
5242	state->d1scl[j] = INREG(i);
5243	state->d2scl[j] = INREG(i + 0x800);
5244	j++;
5245    }
5246    j = 0;
5247    for (i = 0x66e8; i <= 0x66fc; i += 4) {
5248	state->dxscl[j] = INREG(i);
5249	j++;
5250    }
5251    state->dxscl[6] = INREG(0x6e30);
5252    state->dxscl[7] = INREG(0x6e34);
5253
5254    if (state->crtc[0].control & AVIVO_CRTC_EN)
5255	info->crtc_on = TRUE;
5256
5257    if (state->crtc[1].control & AVIVO_CRTC_EN)
5258	info->crtc2_on = TRUE;
5259
5260}
5261
5262static void
5263avivo_restore(ScrnInfoPtr pScrn, RADEONSavePtr restore)
5264{
5265    RADEONInfoPtr info = RADEONPTR(pScrn);
5266    unsigned char *RADEONMMIO = info->MMIO;
5267    struct avivo_state *state = &restore->avivo;
5268    int i, j;
5269
5270    xf86DrvMsg(pScrn->scrnIndex, X_INFO, "avivo_restore !\n");
5271
5272    /* Disable VGA control for now.. maybe needs to be changed */
5273    OUTREG(AVIVO_D1VGA_CONTROL, 0);
5274    OUTREG(AVIVO_D2VGA_CONTROL, 0);
5275
5276    /* Disable CRTCs */
5277    OUTREG(AVIVO_D1CRTC_CONTROL,
5278	   (INREG(AVIVO_D1CRTC_CONTROL) & ~0x300) | 0x01000000);
5279    OUTREG(AVIVO_D2CRTC_CONTROL,
5280	   (INREG(AVIVO_D2CRTC_CONTROL) & ~0x300) | 0x01000000);
5281    OUTREG(AVIVO_D1CRTC_CONTROL,
5282	   INREG(AVIVO_D1CRTC_CONTROL) & ~0x1);
5283    OUTREG(AVIVO_D2CRTC_CONTROL,
5284	   INREG(AVIVO_D2CRTC_CONTROL) & ~0x1);
5285    OUTREG(AVIVO_D1CRTC_CONTROL,
5286	   INREG(AVIVO_D1CRTC_CONTROL) | 0x100);
5287    OUTREG(AVIVO_D2CRTC_CONTROL,
5288	   INREG(AVIVO_D2CRTC_CONTROL) | 0x100);
5289
5290    /* Lock graph registers */
5291    OUTREG(AVIVO_D1GRPH_UPDATE, AVIVO_D1GRPH_UPDATE_LOCK);
5292    OUTREG(AVIVO_D1GRPH_PRIMARY_SURFACE_ADDRESS, state->grph[0].prim_surf_addr);
5293    OUTREG(AVIVO_D1GRPH_SECONDARY_SURFACE_ADDRESS, state->grph[0].sec_surf_addr);
5294    OUTREG(AVIVO_D1GRPH_CONTROL, state->grph[0].control);
5295    OUTREG(AVIVO_D1GRPH_SURFACE_OFFSET_X, state->grph[0].x_offset);
5296    OUTREG(AVIVO_D1GRPH_SURFACE_OFFSET_Y, state->grph[0].y_offset);
5297    OUTREG(AVIVO_D1GRPH_X_START, state->grph[0].x_start);
5298    OUTREG(AVIVO_D1GRPH_Y_START, state->grph[0].y_start);
5299    OUTREG(AVIVO_D1GRPH_X_END, state->grph[0].x_end);
5300    OUTREG(AVIVO_D1GRPH_Y_END, state->grph[0].y_end);
5301    OUTREG(AVIVO_D1GRPH_PITCH, state->grph[0].pitch);
5302    OUTREG(AVIVO_D1GRPH_ENABLE, state->grph[0].enable);
5303    OUTREG(AVIVO_D1GRPH_UPDATE, 0);
5304
5305    OUTREG(AVIVO_D2GRPH_UPDATE, AVIVO_D1GRPH_UPDATE_LOCK);
5306    OUTREG(AVIVO_D2GRPH_PRIMARY_SURFACE_ADDRESS, state->grph[1].prim_surf_addr);
5307    OUTREG(AVIVO_D2GRPH_SECONDARY_SURFACE_ADDRESS, state->grph[1].sec_surf_addr);
5308    OUTREG(AVIVO_D2GRPH_CONTROL, state->grph[1].control);
5309    OUTREG(AVIVO_D2GRPH_SURFACE_OFFSET_X, state->grph[1].x_offset);
5310    OUTREG(AVIVO_D2GRPH_SURFACE_OFFSET_Y, state->grph[1].y_offset);
5311    OUTREG(AVIVO_D2GRPH_X_START, state->grph[1].x_start);
5312    OUTREG(AVIVO_D2GRPH_Y_START, state->grph[1].y_start);
5313    OUTREG(AVIVO_D2GRPH_X_END, state->grph[1].x_end);
5314    OUTREG(AVIVO_D2GRPH_Y_END, state->grph[1].y_end);
5315    OUTREG(AVIVO_D2GRPH_PITCH, state->grph[1].pitch);
5316    OUTREG(AVIVO_D2GRPH_ENABLE, state->grph[1].enable);
5317    OUTREG(AVIVO_D2GRPH_UPDATE, 0);
5318
5319    /* Whack some mode regs too */
5320    OUTREG(AVIVO_D1SCL_UPDATE, AVIVO_D1SCL_UPDATE_LOCK);
5321    OUTREG(AVIVO_D1MODE_DESKTOP_HEIGHT, state->grph[0].desktop_height);
5322    OUTREG(AVIVO_D1MODE_VIEWPORT_START, state->grph[0].viewport_start);
5323    OUTREG(AVIVO_D1MODE_VIEWPORT_SIZE, state->grph[0].viewport_size);
5324    OUTREG(AVIVO_D1MODE_DATA_FORMAT, state->grph[0].mode_data_format);
5325    OUTREG(AVIVO_D1SCL_UPDATE, 0);
5326
5327    OUTREG(AVIVO_D2SCL_UPDATE, AVIVO_D1SCL_UPDATE_LOCK);
5328    OUTREG(AVIVO_D2MODE_DESKTOP_HEIGHT, state->grph[1].desktop_height);
5329    OUTREG(AVIVO_D2MODE_VIEWPORT_START, state->grph[1].viewport_start);
5330    OUTREG(AVIVO_D2MODE_VIEWPORT_SIZE, state->grph[1].viewport_size);
5331    OUTREG(AVIVO_D2MODE_DATA_FORMAT, state->grph[1].mode_data_format);
5332    OUTREG(AVIVO_D2SCL_UPDATE, 0);
5333
5334    /* Set the PLL */
5335    OUTREG(AVIVO_EXT1_PPLL_REF_DIV_SRC, state->pll[0].ref_div_src);
5336    OUTREG(AVIVO_EXT1_PPLL_REF_DIV, state->pll[0].ref_div);
5337    OUTREG(AVIVO_EXT1_PPLL_FB_DIV, state->pll[0].fb_div);
5338    OUTREG(AVIVO_EXT1_PPLL_POST_DIV_SRC, state->pll[0].post_div_src);
5339    OUTREG(AVIVO_EXT1_PPLL_POST_DIV, state->pll[0].post_div);
5340    OUTREG(AVIVO_EXT1_PPLL_CNTL, state->pll[0].ext_ppll_cntl);
5341    OUTREG(AVIVO_P1PLL_CNTL, state->pll[0].pll_cntl);
5342    OUTREG(AVIVO_P1PLL_INT_SS_CNTL, state->pll[0].int_ss_cntl);
5343
5344    OUTREG(AVIVO_EXT2_PPLL_REF_DIV_SRC, state->pll[1].ref_div_src);
5345    OUTREG(AVIVO_EXT2_PPLL_REF_DIV, state->pll[1].ref_div);
5346    OUTREG(AVIVO_EXT2_PPLL_FB_DIV, state->pll[1].fb_div);
5347    OUTREG(AVIVO_EXT2_PPLL_POST_DIV_SRC, state->pll[1].post_div_src);
5348    OUTREG(AVIVO_EXT2_PPLL_POST_DIV, state->pll[1].post_div);
5349    OUTREG(AVIVO_EXT2_PPLL_CNTL, state->pll[1].ext_ppll_cntl);
5350    OUTREG(AVIVO_P2PLL_CNTL, state->pll[1].pll_cntl);
5351    OUTREG(AVIVO_P2PLL_INT_SS_CNTL, state->pll[1].int_ss_cntl);
5352
5353    OUTREG(AVIVO_PCLK_CRTC1_CNTL, state->crtc[0].pll_source);
5354    OUTREG(AVIVO_PCLK_CRTC2_CNTL, state->crtc[1].pll_source);
5355
5356    /* Set the vga PLL */
5357    OUTREG(AVIVO_VGA25_PPLL_REF_DIV_SRC, state->vga25_ppll.ref_div_src);
5358    OUTREG(AVIVO_VGA25_PPLL_REF_DIV, state->vga25_ppll.ref_div);
5359    OUTREG(AVIVO_VGA25_PPLL_FB_DIV, state->vga25_ppll.fb_div);
5360    OUTREG(AVIVO_VGA25_PPLL_POST_DIV_SRC, state->vga25_ppll.post_div_src);
5361    OUTREG(AVIVO_VGA25_PPLL_POST_DIV, state->vga25_ppll.post_div);
5362    OUTREG(AVIVO_VGA25_PPLL_CNTL, state->vga25_ppll.pll_cntl);
5363
5364    OUTREG(AVIVO_VGA28_PPLL_REF_DIV_SRC, state->vga28_ppll.ref_div_src);
5365    OUTREG(AVIVO_VGA28_PPLL_REF_DIV, state->vga28_ppll.ref_div);
5366    OUTREG(AVIVO_VGA28_PPLL_FB_DIV, state->vga28_ppll.fb_div);
5367    OUTREG(AVIVO_VGA28_PPLL_POST_DIV_SRC, state->vga28_ppll.post_div_src);
5368    OUTREG(AVIVO_VGA28_PPLL_POST_DIV, state->vga28_ppll.post_div);
5369    OUTREG(AVIVO_VGA28_PPLL_CNTL, state->vga28_ppll.pll_cntl);
5370
5371    OUTREG(AVIVO_VGA41_PPLL_REF_DIV_SRC, state->vga41_ppll.ref_div_src);
5372    OUTREG(AVIVO_VGA41_PPLL_REF_DIV, state->vga41_ppll.ref_div);
5373    OUTREG(AVIVO_VGA41_PPLL_FB_DIV, state->vga41_ppll.fb_div);
5374    OUTREG(AVIVO_VGA41_PPLL_POST_DIV_SRC, state->vga41_ppll.post_div_src);
5375    OUTREG(AVIVO_VGA41_PPLL_POST_DIV, state->vga41_ppll.post_div);
5376    OUTREG(AVIVO_VGA41_PPLL_CNTL, state->vga41_ppll.pll_cntl);
5377
5378    /* Set the CRTC */
5379    OUTREG(AVIVO_D1CRTC_H_TOTAL, state->crtc[0].h_total);
5380    OUTREG(AVIVO_D1CRTC_H_BLANK_START_END, state->crtc[0].h_blank_start_end);
5381    OUTREG(AVIVO_D1CRTC_H_SYNC_A, state->crtc[0].h_sync_a);
5382    OUTREG(AVIVO_D1CRTC_H_SYNC_A_CNTL, state->crtc[0].h_sync_a_cntl);
5383    OUTREG(AVIVO_D1CRTC_H_SYNC_B, state->crtc[0].h_sync_b);
5384    OUTREG(AVIVO_D1CRTC_H_SYNC_B_CNTL, state->crtc[0].h_sync_b_cntl);
5385
5386    OUTREG(AVIVO_D1CRTC_V_TOTAL, state->crtc[0].v_total);
5387    OUTREG(AVIVO_D1CRTC_V_BLANK_START_END, state->crtc[0].v_blank_start_end);
5388    OUTREG(AVIVO_D1CRTC_V_SYNC_A, state->crtc[0].v_sync_a);
5389    OUTREG(AVIVO_D1CRTC_V_SYNC_A_CNTL, state->crtc[0].v_sync_a_cntl);
5390    OUTREG(AVIVO_D1CRTC_V_SYNC_B, state->crtc[0].v_sync_b);
5391    OUTREG(AVIVO_D1CRTC_V_SYNC_B_CNTL, state->crtc[0].v_sync_b_cntl);
5392
5393    OUTREG(AVIVO_D1CRTC_INTERLACE_CONTROL, state->crtc[0].interlace_control);
5394    OUTREG(AVIVO_D1CRTC_STEREO_CONTROL, state->crtc[0].stereo_control);
5395
5396    OUTREG(AVIVO_D1CUR_CONTROL, state->crtc[0].cursor_control);
5397
5398    /* XXX Fix scaler */
5399
5400    OUTREG(AVIVO_D2CRTC_H_TOTAL, state->crtc[1].h_total);
5401    OUTREG(AVIVO_D2CRTC_H_BLANK_START_END, state->crtc[1].h_blank_start_end);
5402    OUTREG(AVIVO_D2CRTC_H_SYNC_A, state->crtc[1].h_sync_a);
5403    OUTREG(AVIVO_D2CRTC_H_SYNC_A_CNTL, state->crtc[1].h_sync_a_cntl);
5404    OUTREG(AVIVO_D2CRTC_H_SYNC_B, state->crtc[1].h_sync_b);
5405    OUTREG(AVIVO_D2CRTC_H_SYNC_B_CNTL, state->crtc[1].h_sync_b_cntl);
5406
5407    OUTREG(AVIVO_D2CRTC_V_TOTAL, state->crtc[1].v_total);
5408    OUTREG(AVIVO_D2CRTC_V_BLANK_START_END, state->crtc[1].v_blank_start_end);
5409    OUTREG(AVIVO_D2CRTC_V_SYNC_A, state->crtc[1].v_sync_a);
5410    OUTREG(AVIVO_D2CRTC_V_SYNC_A_CNTL, state->crtc[1].v_sync_a_cntl);
5411    OUTREG(AVIVO_D2CRTC_V_SYNC_B, state->crtc[1].v_sync_b);
5412    OUTREG(AVIVO_D2CRTC_V_SYNC_B_CNTL, state->crtc[1].v_sync_b_cntl);
5413
5414    OUTREG(AVIVO_D2CRTC_INTERLACE_CONTROL, state->crtc[1].interlace_control);
5415    OUTREG(AVIVO_D2CRTC_STEREO_CONTROL, state->crtc[1].stereo_control);
5416
5417    OUTREG(AVIVO_D2CUR_CONTROL, state->crtc[1].cursor_control);
5418
5419    if (IS_DCE3_VARIANT) {
5420	/* DVOA regs */
5421	OUTREG(0x7080, state->dvoa[0]);
5422	OUTREG(0x7084, state->dvoa[1]);
5423	OUTREG(0x708c, state->dvoa[2]);
5424	OUTREG(0x7090, state->dvoa[3]);
5425	OUTREG(0x7094, state->dvoa[4]);
5426	OUTREG(0x70ac, state->dvoa[5]);
5427	OUTREG(0x70b0, state->dvoa[6]);
5428
5429	j = 0;
5430	/* DAC regs */
5431	for (i = 0x7000; i <= 0x7040; i += 4) {
5432	    OUTREG(i, state->daca[j]);
5433	    OUTREG((i + 0x100), state->dacb[j]);
5434	    j++;
5435	}
5436	for (i = 0x7058; i <= 0x7060; i += 4) {
5437	    OUTREG(i, state->daca[j]);
5438	    OUTREG((i + 0x100), state->dacb[j]);
5439	    j++;
5440	}
5441	for (i = 0x7068; i <= 0x706c; i += 4) {
5442	    OUTREG(i, state->daca[j]);
5443	    OUTREG((i + 0x100), state->dacb[j]);
5444	    j++;
5445	}
5446	for (i = 0x7ef0; i <= 0x7ef8; i += 4) {
5447	    OUTREG(i, state->daca[j]);
5448	    OUTREG((i + 0x100), state->dacb[j]);
5449	    j++;
5450	}
5451	OUTREG(0x7050, state->daca[j]);
5452	OUTREG((0x7050 + 0x100), state->dacb[j]);
5453
5454	j = 0;
5455	/* FMT regs */
5456	for (i = 0x6700; i <= 0x6744; i += 4) {
5457	    OUTREG(i, state->fmt1[j]);
5458	    OUTREG((i + 0x800), state->fmt2[j]);
5459	    j++;
5460	}
5461
5462	j = 0;
5463	/* DIG regs */
5464	for (i = 0x75a0; i <= 0x75e0; i += 4) {
5465	    OUTREG(i, state->dig1[j]);
5466	    OUTREG((i + 0x400), state->dig2[j]);
5467	    j++;
5468	}
5469	for (i = 0x75e8; i <= 0x75ec; i += 4) {
5470	    OUTREG(i, state->dig1[j]);
5471	    OUTREG((i + 0x400), state->dig2[j]);
5472	    j++;
5473	}
5474
5475	j = 0;
5476	/* HDMI regs */
5477	for (i = 0x7400; i <= 0x741c; i += 4) {
5478	    OUTREG(i, state->hdmi1[j]);
5479	    OUTREG((i + 0x400), state->hdmi2[j]);
5480	    j++;
5481	}
5482	for (i = 0x7430; i <= 0x74ec; i += 4) {
5483	    OUTREG(i, state->hdmi1[j]);
5484	    OUTREG((i + 0x400), state->hdmi2[j]);
5485	    j++;
5486	}
5487	OUTREG(0x7428, state->hdmi1[j]);
5488	OUTREG((0x7428 + 0x400), state->hdmi2[j]);
5489
5490	j = 0;
5491	/* save AUX regs */
5492	for (i = 0x7780; i <= 0x77b4; i += 4) {
5493	    OUTREG(i, state->aux_cntl1[j]);
5494	    OUTREG((i + 0x040), state->aux_cntl2[j]);
5495	    OUTREG((i + 0x400), state->aux_cntl3[j]);
5496	    OUTREG((i + 0x440), state->aux_cntl4[j]);
5497	    if (IS_DCE32_VARIANT) {
5498		OUTREG((i + 0x500), state->aux_cntl5[j]);
5499		OUTREG((i + 0x540), state->aux_cntl6[j]);
5500	    }
5501	    j++;
5502	}
5503
5504	j = 0;
5505	/* save UNIPHY regs */
5506	if (IS_DCE32_VARIANT) {
5507	    for (i = 0x7680; i <= 0x7690; i += 4) {
5508		OUTREG(i, state->uniphy1[j]);
5509		OUTREG((i + 0x20), state->uniphy2[j]);
5510		OUTREG((i + 0x400), state->uniphy3[j]);
5511		OUTREG((i + 0x420), state->uniphy4[j]);
5512		OUTREG((i + 0x840), state->uniphy5[j]);
5513		OUTREG((i + 0x940), state->uniphy6[j]);
5514		j++;
5515	    }
5516	    for (i = 0x7698; i <= 0x769c; i += 4) {
5517		OUTREG(i, state->uniphy1[j]);
5518		OUTREG((i + 0x20), state->uniphy2[j]);
5519		OUTREG((i + 0x400), state->uniphy3[j]);
5520		OUTREG((i + 0x420), state->uniphy4[j]);
5521		OUTREG((i + 0x840), state->uniphy5[j]);
5522		OUTREG((i + 0x940), state->uniphy6[j]);
5523		j++;
5524	    }
5525	} else {
5526	    for (i = 0x7ec0; i <= 0x7edc; i += 4) {
5527		OUTREG(i, state->uniphy1[j]);
5528		OUTREG((i + 0x100), state->uniphy2[j]);
5529		j++;
5530	    }
5531	}
5532	j = 0;
5533	/* save PHY,LINK regs */
5534	for (i = 0x7f20; i <= 0x7f34; i += 4) {
5535	    OUTREG(i, state->phy[j]);
5536	    j++;
5537	}
5538	for (i = 0x7f9c; i <= 0x7fa4; i += 4) {
5539	    OUTREG(i, state->phy[j]);
5540	    j++;
5541	}
5542	state->phy[j] = INREG(0x7f40);
5543
5544	j = 0;
5545	/* save LVTMA regs */
5546	for (i = 0x7f00; i <= 0x7f1c; i += 4) {
5547	    OUTREG(i, state->lvtma[j]);
5548	    j++;
5549	}
5550	for (i = 0x7f80; i <= 0x7f98; i += 4) {
5551	    OUTREG(i, state->lvtma[j]);
5552	    j++;
5553	}
5554    } else {
5555	j = 0;
5556	/* DVOA regs */
5557	for (i = 0x7980; i <= 0x79bc; i += 4) {
5558	    OUTREG(i, state->dvoa[j]);
5559	    j++;
5560	}
5561
5562	j = 0;
5563	/* DAC regs */ /* -- MIGHT NEED ORDERING FIX & DELAYS -- */
5564	for (i = 0x7800; i <= 0x782c; i += 4) {
5565	    OUTREG(i, state->daca[j]);
5566	    OUTREG((i + 0x200), state->dacb[j]);
5567	    j++;
5568	}
5569	for (i = 0x7834; i <= 0x7840; i += 4) {
5570	    OUTREG(i, state->daca[j]);
5571	    OUTREG((i + 0x200), state->dacb[j]);
5572	    j++;
5573	}
5574	for (i = 0x7850; i <= 0x7868; i += 4) {
5575	    OUTREG(i, state->daca[j]);
5576	    OUTREG((i + 0x200), state->dacb[j]);
5577	    j++;
5578	}
5579
5580	j = 0;
5581	/* TMDSA regs */
5582	for (i = 0x7880; i <= 0x78e0; i += 4) {
5583	    OUTREG(i, state->tmdsa[j]);
5584	    j++;
5585	}
5586	for (i = 0x7904; i <= 0x7918; i += 4) {
5587	    OUTREG(i, state->tmdsa[j]);
5588	    j++;
5589	}
5590
5591	j = 0;
5592	/* LVTMA regs */
5593	for (i = 0x7a80; i <= 0x7b18; i += 4) {
5594	    OUTREG(i, state->lvtma[j]);
5595	    j++;
5596	}
5597
5598	/* DDIA regs */
5599	if ((info->ChipFamily == CHIP_FAMILY_RS600) ||
5600	    (info->ChipFamily == CHIP_FAMILY_RS690) ||
5601	    (info->ChipFamily == CHIP_FAMILY_RS740)) {
5602	    j = 0;
5603	    for (i = 0x7200; i <= 0x7290; i += 4) {
5604		OUTREG(i, state->ddia[j]);
5605		j++;
5606	    }
5607	}
5608    }
5609
5610    /* scalers */
5611    j = 0;
5612    for (i = 0x6578; i <= 0x65e4; i += 4) {
5613	OUTREG(i, state->d1scl[j]);
5614	OUTREG((i + 0x800), state->d2scl[j]);
5615	j++;
5616    }
5617    for (i = 0x6600; i <= 0x662c; i += 4) {
5618	OUTREG(i, state->d1scl[j]);
5619	OUTREG((i + 0x800), state->d2scl[j]);
5620	j++;
5621    }
5622    j = 0;
5623    for (i = 0x66e8; i <= 0x66fc; i += 4) {
5624	OUTREG(i, state->dxscl[j]);
5625	j++;
5626    }
5627    OUTREG(0x6e30, state->dxscl[6]);
5628    OUTREG(0x6e34, state->dxscl[7]);
5629
5630    /* Enable CRTCs */
5631    if (state->crtc[0].control & 1) {
5632	    OUTREG(AVIVO_D1CRTC_CONTROL, 0x01000101);
5633	    INREG(AVIVO_D1CRTC_CONTROL);
5634	    OUTREG(AVIVO_D1CRTC_CONTROL, 0x00010101);
5635    }
5636    if (state->crtc[1].control & 1) {
5637	    OUTREG(AVIVO_D2CRTC_CONTROL, 0x01000101);
5638	    INREG(AVIVO_D2CRTC_CONTROL);
5639	    OUTREG(AVIVO_D2CRTC_CONTROL, 0x00010101);
5640    }
5641
5642    /* Where should that go ? */
5643    OUTREG(AVIVO_DC_CRTC_TV_CONTROL, state->crtc_tv_control);
5644    OUTREG(AVIVO_DC_LB_MEMORY_SPLIT, state->dc_lb_memory_split);
5645
5646    /* Need fixing too ? */
5647    OUTREG(AVIVO_D1CRTC_BLANK_CONTROL, state->crtc[0].blank_control);
5648    OUTREG(AVIVO_D2CRTC_BLANK_CONTROL, state->crtc[1].blank_control);
5649
5650    /* Dbl check */
5651    OUTREG(AVIVO_VGA_RENDER_CONTROL, state->vga_render_control);
5652    OUTREG(AVIVO_D1VGA_CONTROL, state->vga1_cntl);
5653    OUTREG(AVIVO_D2VGA_CONTROL, state->vga2_cntl);
5654
5655    /* Should only enable outputs here */
5656}
5657
5658static void avivo_restore_vga_regs(ScrnInfoPtr pScrn, RADEONSavePtr restore)
5659{
5660    RADEONInfoPtr info = RADEONPTR(pScrn);
5661    unsigned char *RADEONMMIO = info->MMIO;
5662    struct avivo_state *state = &restore->avivo;
5663
5664    OUTREG(AVIVO_VGA_RENDER_CONTROL, state->vga_render_control);
5665    OUTREG(AVIVO_D1VGA_CONTROL, state->vga1_cntl);
5666    OUTREG(AVIVO_D2VGA_CONTROL, state->vga2_cntl);
5667}
5668
5669static void dce4_restore_vga_regs(ScrnInfoPtr pScrn, RADEONSavePtr restore)
5670{
5671    RADEONInfoPtr info = RADEONPTR(pScrn);
5672    unsigned char *RADEONMMIO = info->MMIO;
5673    struct dce4_state *state = &restore->dce4;
5674
5675    OUTREG(AVIVO_VGA_RENDER_CONTROL, state->vga_render_control);
5676    OUTREG(AVIVO_D1VGA_CONTROL, state->vga1_cntl);
5677    OUTREG(AVIVO_D2VGA_CONTROL, state->vga2_cntl);
5678    OUTREG(EVERGREEN_D3VGA_CONTROL, state->vga3_cntl);
5679    OUTREG(EVERGREEN_D4VGA_CONTROL, state->vga4_cntl);
5680    OUTREG(EVERGREEN_D5VGA_CONTROL, state->vga5_cntl);
5681    OUTREG(EVERGREEN_D6VGA_CONTROL, state->vga6_cntl);
5682}
5683
5684
5685static void
5686RADEONRestoreBIOSRegisters(ScrnInfoPtr pScrn, RADEONSavePtr restore)
5687{
5688    RADEONInfoPtr  info       = RADEONPTR(pScrn);
5689    unsigned char *RADEONMMIO = info->MMIO;
5690
5691    if (info->ChipFamily >= CHIP_FAMILY_R600) {
5692	OUTREG(R600_BIOS_0_SCRATCH, restore->bios_0_scratch);
5693	OUTREG(R600_BIOS_1_SCRATCH, restore->bios_1_scratch);
5694	OUTREG(R600_BIOS_2_SCRATCH, restore->bios_2_scratch);
5695	OUTREG(R600_BIOS_3_SCRATCH, restore->bios_3_scratch);
5696	OUTREG(R600_BIOS_4_SCRATCH, restore->bios_4_scratch);
5697	OUTREG(R600_BIOS_5_SCRATCH, restore->bios_5_scratch);
5698	OUTREG(R600_BIOS_6_SCRATCH, restore->bios_6_scratch);
5699	OUTREG(R600_BIOS_7_SCRATCH, restore->bios_7_scratch);
5700    } else {
5701	OUTREG(RADEON_BIOS_0_SCRATCH, restore->bios_0_scratch);
5702	OUTREG(RADEON_BIOS_1_SCRATCH, restore->bios_1_scratch);
5703	OUTREG(RADEON_BIOS_2_SCRATCH, restore->bios_2_scratch);
5704	OUTREG(RADEON_BIOS_3_SCRATCH, restore->bios_3_scratch);
5705	OUTREG(RADEON_BIOS_4_SCRATCH, restore->bios_4_scratch);
5706	OUTREG(RADEON_BIOS_5_SCRATCH, restore->bios_5_scratch);
5707	OUTREG(RADEON_BIOS_6_SCRATCH, restore->bios_6_scratch);
5708	OUTREG(RADEON_BIOS_7_SCRATCH, restore->bios_7_scratch);
5709    }
5710}
5711
5712static void
5713RADEONSaveBIOSRegisters(ScrnInfoPtr pScrn, RADEONSavePtr save)
5714{
5715    RADEONInfoPtr  info       = RADEONPTR(pScrn);
5716    unsigned char *RADEONMMIO = info->MMIO;
5717
5718    if (info->ChipFamily >= CHIP_FAMILY_R600) {
5719	save->bios_0_scratch       = INREG(R600_BIOS_0_SCRATCH);
5720	save->bios_1_scratch       = INREG(R600_BIOS_1_SCRATCH);
5721	save->bios_2_scratch       = INREG(R600_BIOS_2_SCRATCH);
5722	save->bios_3_scratch       = INREG(R600_BIOS_3_SCRATCH);
5723	save->bios_4_scratch       = INREG(R600_BIOS_4_SCRATCH);
5724	save->bios_5_scratch       = INREG(R600_BIOS_5_SCRATCH);
5725	save->bios_6_scratch       = INREG(R600_BIOS_6_SCRATCH);
5726	save->bios_7_scratch       = INREG(R600_BIOS_7_SCRATCH);
5727    } else {
5728	save->bios_0_scratch       = INREG(RADEON_BIOS_0_SCRATCH);
5729	save->bios_1_scratch       = INREG(RADEON_BIOS_1_SCRATCH);
5730	save->bios_2_scratch       = INREG(RADEON_BIOS_2_SCRATCH);
5731	save->bios_3_scratch       = INREG(RADEON_BIOS_3_SCRATCH);
5732	save->bios_4_scratch       = INREG(RADEON_BIOS_4_SCRATCH);
5733	save->bios_5_scratch       = INREG(RADEON_BIOS_5_SCRATCH);
5734	save->bios_6_scratch       = INREG(RADEON_BIOS_6_SCRATCH);
5735	save->bios_7_scratch       = INREG(RADEON_BIOS_7_SCRATCH);
5736    }
5737}
5738
5739void radeon_save_palette_on_demand(ScrnInfoPtr pScrn, int palID)
5740{
5741    RADEONInfoPtr  info       = RADEONPTR(pScrn);
5742    RADEONSavePtr  save       = info->SavedReg;
5743
5744    if (save->palette_saved[palID] == TRUE)
5745        return;
5746
5747    if (!IS_AVIVO_VARIANT)
5748        RADEONSavePalette(pScrn, palID, save);
5749
5750    save->palette_saved[palID] = TRUE;
5751}
5752
5753/* Save everything needed to restore the original VC state */
5754static void RADEONSave(ScrnInfoPtr pScrn)
5755{
5756    RADEONInfoPtr  info       = RADEONPTR(pScrn);
5757    RADEONEntPtr pRADEONEnt   = RADEONEntPriv(pScrn);
5758    unsigned char *RADEONMMIO = info->MMIO;
5759    RADEONSavePtr  save       = info->SavedReg;
5760
5761    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
5762		   "RADEONSave\n");
5763
5764#ifdef WITH_VGAHW
5765    if (info->VGAAccess) {
5766	vgaHWPtr hwp = VGAHWPTR(pScrn);
5767
5768	vgaHWUnlock(hwp);
5769# if defined(__powerpc__)
5770	/* temporary hack to prevent crashing on PowerMacs when trying to
5771	 * read VGA fonts and colormap, will find a better solution
5772	 * in the future. TODO: Check if there's actually some VGA stuff
5773	 * setup in the card at all !!
5774	 */
5775	vgaHWSave(pScrn, &hwp->SavedReg, VGA_SR_MODE); /* Save mode only */
5776# else
5777	/* Save only mode * & fonts */
5778	vgaHWSave(pScrn, &hwp->SavedReg, VGA_SR_MODE | VGA_SR_FONTS );
5779# endif
5780	vgaHWLock(hwp);
5781    }
5782#endif
5783
5784    if (IS_DCE4_VARIANT) {
5785	RADEONSaveMemMapRegisters(pScrn, save);
5786	dce4_save(pScrn, save);
5787	//XXX
5788    } else if (IS_AVIVO_VARIANT) {
5789	RADEONSaveMemMapRegisters(pScrn, save);
5790	avivo_save(pScrn, save);
5791    } else {
5792	save->dp_datatype      = INREG(RADEON_DP_DATATYPE);
5793	save->rbbm_soft_reset  = INREG(RADEON_RBBM_SOFT_RESET);
5794	save->clock_cntl_index = INREG(RADEON_CLOCK_CNTL_INDEX);
5795	RADEONPllErrataAfterIndex(info);
5796
5797	RADEONSaveMemMapRegisters(pScrn, save);
5798	RADEONSaveCommonRegisters(pScrn, save);
5799	RADEONSavePLLRegisters(pScrn, save);
5800	RADEONSaveCrtcRegisters(pScrn, save);
5801	RADEONSaveFPRegisters(pScrn, save);
5802	RADEONSaveDACRegisters(pScrn, save);
5803	/* Palette saving is done on demand now */
5804
5805	if (pRADEONEnt->HasCRTC2) {
5806	    RADEONSaveCrtc2Registers(pScrn, save);
5807	    RADEONSavePLL2Registers(pScrn, save);
5808	}
5809	if (info->InternalTVOut)
5810	    RADEONSaveTVRegisters(pScrn, save);
5811    }
5812
5813    if (info->ChipFamily < CHIP_FAMILY_R600)
5814        RADEONSaveSurfaces(pScrn, save);
5815
5816}
5817
5818/* Restore the original (text) mode */
5819static void RADEONRestore(ScrnInfoPtr pScrn)
5820{
5821    RADEONInfoPtr  info       = RADEONPTR(pScrn);
5822    RADEONEntPtr pRADEONEnt = RADEONEntPriv(pScrn);
5823    unsigned char *RADEONMMIO = info->MMIO;
5824    RADEONSavePtr  restore    = info->SavedReg;
5825    xf86CrtcConfigPtr   xf86_config = XF86_CRTC_CONFIG_PTR(pScrn);
5826    xf86CrtcPtr crtc;
5827
5828    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
5829		   "RADEONRestore\n");
5830
5831#if X_BYTE_ORDER == X_BIG_ENDIAN
5832    if (info->ChipFamily < CHIP_FAMILY_R600) {
5833	RADEONWaitForFifo(pScrn, 1);
5834	OUTREG(RADEON_RBBM_GUICNTL, RADEON_HOST_DATA_SWAP_NONE);
5835    }
5836#endif
5837
5838    RADEONBlank(pScrn);
5839
5840    if (IS_DCE4_VARIANT) {
5841	RADEONRestoreMemMapRegisters(pScrn, restore);
5842	dce4_restore(pScrn, restore);
5843	//XXX
5844    } else if (IS_AVIVO_VARIANT) {
5845	RADEONRestoreMemMapRegisters(pScrn, restore);
5846	avivo_restore(pScrn, restore);
5847    } else {
5848	OUTREG(RADEON_RBBM_SOFT_RESET,  restore->rbbm_soft_reset);
5849	OUTREG(RADEON_DP_DATATYPE,      restore->dp_datatype);
5850	OUTREG(RADEON_GRPH_BUFFER_CNTL, restore->grph_buffer_cntl);
5851	OUTREG(RADEON_GRPH2_BUFFER_CNTL, restore->grph2_buffer_cntl);
5852
5853	if (!info->IsSecondary) {
5854	    RADEONRestoreMemMapRegisters(pScrn, restore);
5855	    RADEONRestoreCommonRegisters(pScrn, restore);
5856
5857	    RADEONRestorePalette(pScrn, restore);
5858	    if (pRADEONEnt->HasCRTC2) {
5859		RADEONRestoreCrtc2Registers(pScrn, restore);
5860		RADEONRestorePLL2Registers(pScrn, restore);
5861	    }
5862
5863	    RADEONRestoreCrtcRegisters(pScrn, restore);
5864	    RADEONRestorePLLRegisters(pScrn, restore);
5865	    RADEONRestoreRMXRegisters(pScrn, restore);
5866	    RADEONRestoreFPRegisters(pScrn, restore);
5867	    RADEONRestoreFP2Registers(pScrn, restore);
5868	    RADEONRestoreLVDSRegisters(pScrn, restore);
5869
5870	    if (info->InternalTVOut)
5871		RADEONRestoreTVRegisters(pScrn, restore);
5872	}
5873
5874	OUTREG(RADEON_CLOCK_CNTL_INDEX, restore->clock_cntl_index);
5875	RADEONPllErrataAfterIndex(info);
5876
5877	RADEONRestoreBIOSRegisters(pScrn, restore);
5878    }
5879
5880
5881#if 1
5882    /* Temp fix to "solve" VT switch problems.  When switching VTs on
5883     * some systems, the console can either hang or the fonts can be
5884     * corrupted.  This hack solves the problem 99% of the time.  A
5885     * correct fix is being worked on.
5886     */
5887    usleep(100000);
5888#endif
5889
5890    if (info->ChipFamily < CHIP_FAMILY_R600)
5891	RADEONRestoreSurfaces(pScrn, restore);
5892
5893    /* need to make sure we don't enable a crtc by accident or we may get a hang */
5894    if (pRADEONEnt->HasCRTC2 && !info->IsSecondary) {
5895	if (info->crtc2_on && xf86_config->num_crtc > 1) {
5896	    crtc = xf86_config->crtc[1];
5897	    radeon_do_crtc_dpms(crtc, DPMSModeOn);
5898	}
5899    }
5900    if (info->crtc_on) {
5901	crtc = xf86_config->crtc[0];
5902	radeon_do_crtc_dpms(crtc, DPMSModeOn);
5903    }
5904
5905#ifdef WITH_VGAHW
5906    if (info->VGAAccess) {
5907       vgaHWPtr hwp = VGAHWPTR(pScrn);
5908       vgaHWUnlock(hwp);
5909# if defined(__powerpc__)
5910       /* Temporary hack to prevent crashing on PowerMacs when trying to
5911	* write VGA fonts, will find a better solution in the future
5912	*/
5913       vgaHWRestore(pScrn, &hwp->SavedReg, VGA_SR_MODE );
5914# else
5915       vgaHWRestore(pScrn, &hwp->SavedReg, VGA_SR_MODE | VGA_SR_FONTS );
5916# endif
5917       vgaHWLock(hwp);
5918    }
5919#endif
5920
5921    /* to restore console mode, DAC registers should be set after every other registers are set,
5922     * otherwise,we may get blank screen
5923     */
5924    if (IS_DCE4_VARIANT)
5925        dce4_restore_vga_regs(pScrn, restore);
5926    else if (IS_AVIVO_VARIANT)
5927	avivo_restore_vga_regs(pScrn, restore);
5928    else {
5929	RADEONRestoreDACRegisters(pScrn, restore);
5930    }
5931#if 0
5932    RADEONWaitForVerticalSync(pScrn);
5933#endif
5934}
5935
5936static Bool RADEONSaveScreen(ScreenPtr pScreen, int mode)
5937{
5938    ScrnInfoPtr  pScrn = xf86ScreenToScrn(pScreen);
5939    Bool         unblank;
5940
5941    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
5942		   "RADEONSaveScreen(%d)\n", mode);
5943
5944    unblank = xf86IsUnblank(mode);
5945    if (unblank) SetTimeSinceLastInputEvent();
5946
5947    if ((pScrn != NULL) && pScrn->vtSema) {
5948	if (unblank)
5949	    RADEONUnblank(pScrn);
5950	else
5951	    RADEONBlank(pScrn);
5952    }
5953    return TRUE;
5954}
5955
5956Bool RADEONSwitchMode(SWITCH_MODE_ARGS_DECL)
5957{
5958    SCRN_INFO_PTR(arg);
5959    RADEONInfoPtr  info        = RADEONPTR(pScrn);
5960    Bool           tilingOld   = info->tilingEnabled;
5961    Bool           ret;
5962#ifdef XF86DRI
5963    Bool           CPStarted   = info->cp->CPStarted;
5964
5965    if (CPStarted) {
5966	DRILock(pScrn->pScreen, 0);
5967	RADEONCP_STOP(pScrn, info);
5968    }
5969#endif
5970
5971    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
5972		   "RADEONSwitchMode() !n");
5973
5974    if (info->allowColorTiling) {
5975        info->tilingEnabled = (mode->Flags & (V_DBLSCAN | V_INTERLACE)) ? FALSE : TRUE;
5976#ifdef XF86DRI
5977	if (info->directRenderingEnabled && (info->tilingEnabled != tilingOld)) {
5978	    drm_radeon_sarea_t *pSAREAPriv;
5979	  if (RADEONDRISetParam(pScrn, RADEON_SETPARAM_SWITCH_TILING, (info->tilingEnabled ? 1 : 0)) < 0)
5980  	      xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
5981			 "[drm] failed changing tiling status\n");
5982	    pSAREAPriv = DRIGetSAREAPrivate(pScrn->pScreen);
5983	    info->tilingEnabled = pSAREAPriv->tiling_enabled ? TRUE : FALSE;
5984	}
5985#endif
5986    }
5987
5988    if (info->accelOn)
5989        RADEON_SYNC(info, pScrn);
5990
5991    ret = xf86SetSingleMode (pScrn, mode, RR_Rotate_0);
5992
5993    if (info->tilingEnabled != tilingOld) {
5994	/* need to redraw front buffer, I guess this can be considered a hack ? */
5995	xf86EnableDisableFBAccess(arg, FALSE);
5996	RADEONChangeSurfaces(pScrn);
5997	xf86EnableDisableFBAccess(arg, TRUE);
5998	/* xf86SetRootClip would do, but can't access that here */
5999    }
6000
6001    if (info->accelOn) {
6002        RADEON_SYNC(info, pScrn);
6003	if (info->ChipFamily < CHIP_FAMILY_R600)
6004	    RADEONEngineRestore(pScrn);
6005    }
6006
6007#ifdef XF86DRI
6008    if (CPStarted) {
6009	RADEONCP_START(pScrn, info);
6010	DRIUnlock(pScrn->pScreen);
6011    }
6012#endif
6013
6014    /* reset ecp for overlay */
6015    info->ecp_div = -1;
6016
6017    return ret;
6018}
6019
6020#ifdef X_XF86MiscPassMessage
6021Bool RADEONHandleMessage(int scrnIndex, const char* msgtype,
6022                                   const char* msgval, char** retmsg)
6023{
6024    ErrorF("RADEONHandleMessage(%d, \"%s\", \"%s\", retmsg)\n", scrnIndex,
6025		    msgtype, msgval);
6026    *retmsg = "";
6027    return 0;
6028}
6029#endif
6030
6031#ifndef HAVE_XF86MODEBANDWIDTH
6032/** Calculates the memory bandwidth (in MiB/sec) of a mode. */
6033_X_HIDDEN unsigned int
6034xf86ModeBandwidth(DisplayModePtr mode, int depth)
6035{
6036    float a_active, a_total, active_percent, pixels_per_second;
6037    int bytes_per_pixel = (depth + 7) / 8;
6038
6039    if (!mode->HTotal || !mode->VTotal || !mode->Clock)
6040	return 0;
6041
6042    a_active = mode->HDisplay * mode->VDisplay;
6043    a_total = mode->HTotal * mode->VTotal;
6044    active_percent = a_active / a_total;
6045    pixels_per_second = active_percent * mode->Clock * 1000.0;
6046
6047    return (unsigned int)(pixels_per_second * bytes_per_pixel / (1024 * 1024));
6048}
6049#endif
6050
6051/* Used to disallow modes that are not supported by the hardware */
6052ModeStatus RADEONValidMode(SCRN_ARG_TYPE arg, DisplayModePtr mode,
6053                                     Bool verbose, int flag)
6054{
6055    SCRN_INFO_PTR(arg);
6056    RADEONInfoPtr info = RADEONPTR(pScrn);
6057    RADEONEntPtr pRADEONEnt = RADEONEntPriv(pScrn);
6058
6059    /*
6060     * RN50 has effective maximum mode bandwidth of about 300MiB/s.
6061     * XXX should really do this for all chips by properly computing
6062     * memory bandwidth and an overhead factor.
6063     */
6064    if (info->ChipFamily == CHIP_FAMILY_RV100 && !pRADEONEnt->HasCRTC2) {
6065	if (xf86ModeBandwidth(mode, pScrn->bitsPerPixel) > 300)
6066	    return MODE_BANDWIDTH;
6067    }
6068
6069    /* There are problems with double scan mode at high clocks
6070     * They're likely related PLL and display buffer settings.
6071     * Disable these modes for now.
6072     */
6073    if (mode->Flags & V_DBLSCAN) {
6074	if ((mode->CrtcHDisplay >= 1024) || (mode->CrtcVDisplay >= 768))
6075	    return MODE_CLOCK_RANGE;
6076    }
6077    return MODE_OK;
6078}
6079
6080/* Adjust viewport into virtual desktop such that (0,0) in viewport
6081 * space is (x,y) in virtual space.
6082 */
6083void RADEONDoAdjustFrame(ScrnInfoPtr pScrn, int x, int y, Bool crtc2)
6084{
6085    RADEONInfoPtr  info       = RADEONPTR(pScrn);
6086    unsigned char *RADEONMMIO = info->MMIO;
6087    int            Base, reg, regcntl, crtcoffsetcntl, xytilereg, crtcxytile = 0;
6088#ifdef XF86DRI
6089    drm_radeon_sarea_t *pSAREAPriv;
6090    XF86DRISAREAPtr pSAREA;
6091#endif
6092
6093#if 0 /* Verbose */
6094    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
6095		   "RADEONDoAdjustFrame(%d,%d,%d)\n", x, y, clone);
6096#endif
6097
6098    Base = pScrn->fbOffset;
6099
6100  /* note we cannot really simply use the info->ModeReg.crtc_offset_cntl value, since the
6101     drm might have set FLIP_CNTL since we wrote that. Unfortunately FLIP_CNTL causes
6102     flickering when scrolling vertically in a virtual screen, possibly because crtc will
6103     pick up the new offset value at the end of each scanline, but the new offset_cntl value
6104     only after a vsync. We'd probably need to wait (in drm) for vsync and only then update
6105     OFFSET and OFFSET_CNTL, if the y coord has changed. Seems hard to fix. */
6106    if (crtc2) {
6107	reg = RADEON_CRTC2_OFFSET;
6108	regcntl = RADEON_CRTC2_OFFSET_CNTL;
6109	xytilereg = R300_CRTC2_TILE_X0_Y0;
6110    } else {
6111	reg = RADEON_CRTC_OFFSET;
6112	regcntl = RADEON_CRTC_OFFSET_CNTL;
6113	xytilereg = R300_CRTC_TILE_X0_Y0;
6114    }
6115    crtcoffsetcntl = INREG(regcntl) & ~0xf;
6116#if 0
6117    /* try to get rid of flickering when scrolling at least for 2d */
6118#ifdef XF86DRI
6119    if (!info->dri->have3DWindows)
6120#endif
6121    crtcoffsetcntl &= ~RADEON_CRTC_OFFSET_FLIP_CNTL;
6122#endif
6123    if (info->tilingEnabled) {
6124        if (IS_R300_VARIANT || IS_AVIVO_VARIANT) {
6125	/* On r300/r400 when tiling is enabled crtc_offset is set to the address of
6126	 * the surface.  the x/y offsets are handled by the X_Y tile reg for each crtc
6127	 * Makes tiling MUCH easier.
6128	 */
6129             crtcxytile = x | (y << 16);
6130             Base &= ~0x7ff;
6131         } else {
6132             int byteshift = info->CurrentLayout.bitsPerPixel >> 4;
6133             /* crtc uses 256(bytes)x8 "half-tile" start addresses? */
6134             int tile_addr = (((y >> 3) * info->CurrentLayout.displayWidth + x) >> (8 - byteshift)) << 11;
6135             Base += tile_addr + ((x << byteshift) % 256) + ((y % 8) << 8);
6136             crtcoffsetcntl = crtcoffsetcntl | (y % 16);
6137         }
6138    }
6139    else {
6140       int offset = y * info->CurrentLayout.displayWidth + x;
6141       switch (info->CurrentLayout.pixel_code) {
6142       case 15:
6143       case 16: offset *= 2; break;
6144       case 24: offset *= 3; break;
6145       case 32: offset *= 4; break;
6146       }
6147       Base += offset;
6148    }
6149
6150    Base &= ~7;                 /* 3 lower bits are always 0 */
6151
6152#ifdef XF86DRI
6153    if (info->directRenderingInited) {
6154	/* note cannot use pScrn->pScreen since this is unitialized when called from
6155	   RADEONScreenInit, and we need to call from there to get mergedfb + pageflip working */
6156        /*** NOTE: r3/4xx will need sarea and drm pageflip updates to handle the xytile regs for
6157	 *** pageflipping!
6158	 ***/
6159	pSAREAPriv = DRIGetSAREAPrivate(xf86ScrnToScreen(pScrn));
6160	/* can't get at sarea in a semi-sane way? */
6161	pSAREA = (void *)((char*)pSAREAPriv - sizeof(XF86DRISAREARec));
6162
6163	if (crtc2) {
6164	    pSAREAPriv->crtc2_base = Base;
6165	}
6166	else {
6167	    pSAREA->frame.x = (Base  / info->CurrentLayout.pixel_bytes)
6168		% info->CurrentLayout.displayWidth;
6169	    pSAREA->frame.y = (Base / info->CurrentLayout.pixel_bytes)
6170		/ info->CurrentLayout.displayWidth;
6171	    pSAREA->frame.width = pScrn->frameX1 - x + 1;
6172	    pSAREA->frame.height = pScrn->frameY1 - y + 1;
6173	}
6174
6175	if (pSAREAPriv->pfCurrentPage == 1) {
6176	    Base += info->dri->backOffset - info->dri->frontOffset;
6177	}
6178    }
6179#endif
6180
6181    if (IS_R300_VARIANT || IS_AVIVO_VARIANT) {
6182	OUTREG(xytilereg, crtcxytile);
6183    } else {
6184	OUTREG(regcntl, crtcoffsetcntl);
6185    }
6186
6187    OUTREG(reg, Base);
6188}
6189
6190void RADEONAdjustFrame(ADJUST_FRAME_ARGS_DECL)
6191{
6192    SCRN_INFO_PTR(arg);
6193    RADEONInfoPtr  info       = RADEONPTR(pScrn);
6194    RADEONEntPtr pRADEONEnt = RADEONEntPriv(pScrn);
6195    xf86CrtcConfigPtr	config = XF86_CRTC_CONFIG_PTR(pScrn);
6196    xf86OutputPtr  output = config->output[config->compat_output];
6197    xf86CrtcPtr	crtc = output->crtc;
6198
6199    /* not handled */
6200    if (IS_AVIVO_VARIANT)
6201	return;
6202
6203#ifdef XF86DRI
6204    if (info->cp->CPStarted && pScrn->pScreen) DRILock(pScrn->pScreen, 0);
6205#endif
6206
6207    if (info->accelOn)
6208        RADEON_SYNC(info, pScrn);
6209
6210    if (crtc && crtc->enabled) {
6211	if (crtc == pRADEONEnt->pCrtc[0])
6212	    RADEONDoAdjustFrame(pScrn, crtc->desiredX + x, crtc->desiredY + y, FALSE);
6213	else
6214	    RADEONDoAdjustFrame(pScrn, crtc->desiredX + x, crtc->desiredY + y, TRUE);
6215	crtc->x = output->initial_x + x;
6216	crtc->y = output->initial_y + y;
6217    }
6218
6219
6220#ifdef XF86DRI
6221	if (info->cp->CPStarted && pScrn->pScreen) DRIUnlock(pScrn->pScreen);
6222#endif
6223}
6224
6225/* Called when VT switching back to the X server.  Reinitialize the
6226 * video mode.
6227 */
6228Bool RADEONEnterVT(VT_FUNC_ARGS_DECL)
6229{
6230    SCRN_INFO_PTR(arg);
6231    RADEONInfoPtr  info  = RADEONPTR(pScrn);
6232    xf86CrtcConfigPtr config = XF86_CRTC_CONFIG_PTR(pScrn);
6233    int i;
6234
6235    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
6236		   "RADEONEnterVT\n");
6237
6238    if (!radeon_card_posted(pScrn)) { /* Softboot V_BIOS */
6239	if (info->IsAtomBios) {
6240	    rhdAtomASICInit(info->atomBIOS);
6241	} else {
6242	    xf86Int10InfoPtr pInt;
6243
6244	    pInt = xf86InitInt10 (info->pEnt->index);
6245	    if (pInt) {
6246		pInt->num = 0xe6;
6247		xf86ExecX86int10 (pInt);
6248		xf86FreeInt10 (pInt);
6249	    } else {
6250		RADEONGetBIOSInitTableOffsets(pScrn);
6251		RADEONPostCardFromBIOSTables(pScrn);
6252	    }
6253	}
6254    }
6255
6256    /* Makes sure the engine is idle before doing anything */
6257    RADEONWaitForIdleMMIO(pScrn);
6258
6259    RADEONPMEnterVT(pScrn);
6260
6261    for (i = 0; i < config->num_crtc; i++)
6262	radeon_crtc_modeset_ioctl(config->crtc[i], TRUE);
6263
6264    pScrn->vtSema = TRUE;
6265
6266    /* Clear the framebuffer */
6267    memset(info->FB + pScrn->fbOffset, 0,
6268           pScrn->virtualY * pScrn->displayWidth * info->CurrentLayout.pixel_bytes);
6269
6270    if (!xf86SetDesiredModes(pScrn))
6271	return FALSE;
6272
6273    if (info->ChipFamily < CHIP_FAMILY_R600)
6274        RADEONRestoreSurfaces(pScrn, info->ModeReg);
6275#ifdef XF86DRI
6276    if (info->directRenderingEnabled) {
6277	if (info->cardType == CARD_PCIE &&
6278	    info->dri->pKernelDRMVersion->version_minor >= 19 &&
6279	    info->FbSecureSize) {
6280#if X_BYTE_ORDER == X_BIG_ENDIAN
6281	    unsigned char *RADEONMMIO = info->MMIO;
6282	    unsigned int sctrl = INREG(RADEON_SURFACE_CNTL);
6283
6284	    /* we need to backup the PCIE GART TABLE from fb memory */
6285	    OUTREG(RADEON_SURFACE_CNTL, 0);
6286#endif
6287	    memcpy(info->FB + info->dri->pciGartOffset, info->dri->pciGartBackup, info->dri->pciGartSize);
6288#if X_BYTE_ORDER == X_BIG_ENDIAN
6289	    OUTREG(RADEON_SURFACE_CNTL, sctrl);
6290#endif
6291	}
6292
6293	/* get the DRI back into shape after resume */
6294	RADEONDRISetVBlankInterrupt (pScrn, TRUE);
6295	RADEONDRIResume(pScrn->pScreen);
6296	RADEONAdjustMemMapRegisters(pScrn, info->ModeReg);
6297
6298    }
6299#endif
6300    /* this will get XVideo going again, but only if XVideo was initialised
6301       during server startup (hence the info->adaptor if). */
6302    if (info->adaptor)
6303	RADEONResetVideo(pScrn);
6304
6305    if (info->accelOn && (info->ChipFamily < CHIP_FAMILY_R600))
6306	RADEONEngineRestore(pScrn);
6307
6308    if (info->accelOn && info->accel_state)
6309	info->accel_state->XInited3D = FALSE;
6310
6311#ifdef XF86DRI
6312    if (info->directRenderingEnabled) {
6313        if (info->ChipFamily >= CHIP_FAMILY_R600)
6314		R600LoadShaders(pScrn);
6315	RADEONCP_START(pScrn, info);
6316	DRIUnlock(pScrn->pScreen);
6317    }
6318#endif
6319    if (IS_R500_3D || IS_R300_3D)
6320	radeon_load_bicubic_texture(pScrn);
6321
6322    return TRUE;
6323}
6324
6325/* Called when VT switching away from the X server.  Restore the
6326 * original text mode.
6327 */
6328void RADEONLeaveVT(VT_FUNC_ARGS_DECL)
6329{
6330    SCRN_INFO_PTR(arg);
6331    RADEONInfoPtr  info  = RADEONPTR(pScrn);
6332    xf86CrtcConfigPtr config = XF86_CRTC_CONFIG_PTR(pScrn);
6333    int i;
6334
6335    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
6336		   "RADEONLeaveVT\n");
6337#ifdef XF86DRI
6338    if (RADEONPTR(pScrn)->directRenderingInited) {
6339
6340	RADEONDRISetVBlankInterrupt (pScrn, FALSE);
6341	DRILock(pScrn->pScreen, 0);
6342	RADEONCP_STOP(pScrn, info);
6343
6344        if (info->cardType == CARD_PCIE &&
6345	    info->dri->pKernelDRMVersion->version_minor >= 19 &&
6346	    info->FbSecureSize) {
6347#if X_BYTE_ORDER == X_BIG_ENDIAN
6348	    unsigned char *RADEONMMIO = info->MMIO;
6349	    unsigned int sctrl = INREG(RADEON_SURFACE_CNTL);
6350
6351            /* we need to backup the PCIE GART TABLE from fb memory */
6352	    OUTREG(RADEON_SURFACE_CNTL, 0);
6353#endif
6354            memcpy(info->dri->pciGartBackup, (info->FB + info->dri->pciGartOffset), info->dri->pciGartSize);
6355#if X_BYTE_ORDER == X_BIG_ENDIAN
6356	    OUTREG(RADEON_SURFACE_CNTL, sctrl);
6357#endif
6358        }
6359
6360	/* Make sure 3D clients will re-upload textures to video RAM */
6361	if (info->dri->textureSize) {
6362	    drm_radeon_sarea_t *pSAREAPriv =
6363		(drm_radeon_sarea_t*)DRIGetSAREAPrivate(pScrn->pScreen);
6364	    struct drm_tex_region *list = pSAREAPriv->tex_list[0];
6365	    int age = ++pSAREAPriv->tex_age[0];
6366
6367	    i = 0;
6368
6369	    do {
6370		list[i].age = age;
6371		i = list[i].next;
6372	    } while (i != 0);
6373	}
6374    }
6375#endif
6376
6377
6378    for (i = 0; i < config->num_crtc; i++) {
6379	xf86CrtcPtr crtc = config->crtc[i];
6380	RADEONCrtcPrivatePtr radeon_crtc = crtc->driver_private;
6381
6382	radeon_crtc->initialized = FALSE;
6383
6384#ifndef HAVE_FREE_SHADOW
6385	if (crtc->rotatedPixmap || crtc->rotatedData) {
6386	    crtc->funcs->shadow_destroy(crtc, crtc->rotatedPixmap,
6387					crtc->rotatedData);
6388	    crtc->rotatedPixmap = NULL;
6389	    crtc->rotatedData = NULL;
6390	}
6391#endif
6392    }
6393
6394#ifdef HAVE_FREE_SHADOW
6395    xf86RotateFreeShadow(pScrn);
6396#endif
6397
6398    xf86_hide_cursors (pScrn);
6399
6400    RADEONPMLeaveVT(pScrn);
6401
6402    RADEONRestore(pScrn);
6403
6404    for (i = 0; i < config->num_crtc; i++)
6405	radeon_crtc_modeset_ioctl(config->crtc[i], FALSE);
6406
6407    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
6408		   "Ok, leaving now...\n");
6409}
6410
6411/* Called at the end of each server generation.  Restore the original
6412 * text mode, unmap video memory, and unwrap and call the saved
6413 * CloseScreen function.
6414 */
6415static Bool RADEONCloseScreen(CLOSE_SCREEN_ARGS_DECL)
6416{
6417    ScrnInfoPtr pScrn = xf86ScreenToScrn(pScreen);
6418    RADEONInfoPtr  info  = RADEONPTR(pScrn);
6419    xf86CrtcConfigPtr config = XF86_CRTC_CONFIG_PTR(pScrn);
6420    int i;
6421
6422    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
6423		   "RADEONCloseScreen\n");
6424
6425    RADEONPMFini(pScrn);
6426
6427    /* Mark acceleration as stopped or we might try to access the engine at
6428     * wrong times, especially if we had DRI, after DRI has been stopped
6429     */
6430    info->accelOn = FALSE;
6431
6432    for (i = 0; i < config->num_crtc; i++) {
6433	xf86CrtcPtr crtc = config->crtc[i];
6434	RADEONCrtcPrivatePtr radeon_crtc = crtc->driver_private;
6435
6436	radeon_crtc->initialized = FALSE;
6437    }
6438
6439#ifdef XF86DRI
6440#ifdef DAMAGE
6441    if (info->dri && info->dri->pDamage) {
6442	PixmapPtr pPix = pScreen->GetScreenPixmap(pScreen);
6443
6444	DamageUnregister(&pPix->drawable, info->dri->pDamage);
6445	DamageDestroy(info->dri->pDamage);
6446	info->dri->pDamage = NULL;
6447    }
6448#endif
6449
6450    RADEONDRIStop(pScreen);
6451#endif
6452
6453#ifdef USE_XAA
6454    if(!info->useEXA && info->accel_state->RenderTex) {
6455        xf86FreeOffscreenLinear(info->accel_state->RenderTex);
6456        info->accel_state->RenderTex = NULL;
6457    }
6458#endif /* USE_XAA */
6459
6460    if (pScrn->vtSema) {
6461	RADEONRestore(pScrn);
6462    }
6463
6464    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
6465		   "Disposing accel...\n");
6466#ifdef USE_EXA
6467    if (info->accel_state->exa) {
6468	exaDriverFini(pScreen);
6469	free(info->accel_state->exa);
6470	info->accel_state->exa = NULL;
6471    }
6472#endif /* USE_EXA */
6473#ifdef USE_XAA
6474    if (!info->useEXA) {
6475	if (info->accel_state->accel)
6476		XAADestroyInfoRec(info->accel_state->accel);
6477	info->accel_state->accel = NULL;
6478
6479	if (info->accel_state->scratch_save)
6480	    free(info->accel_state->scratch_save);
6481	info->accel_state->scratch_save = NULL;
6482    }
6483#endif /* USE_XAA */
6484
6485    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
6486		   "Disposing cursor info\n");
6487    if (info->cursor) xf86DestroyCursorInfoRec(info->cursor);
6488    info->cursor = NULL;
6489
6490    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
6491		   "Unmapping memory\n");
6492    RADEONUnmapMem(pScrn);
6493
6494    pScrn->vtSema = FALSE;
6495
6496    xf86ClearPrimInitDone(info->pEnt->index);
6497
6498    pScreen->BlockHandler = info->BlockHandler;
6499    pScreen->CloseScreen = info->CloseScreen;
6500    return (*pScreen->CloseScreen)(CLOSE_SCREEN_ARGS);
6501}
6502
6503void RADEONFreeScreen(FREE_SCREEN_ARGS_DECL)
6504{
6505    SCRN_INFO_PTR(arg);
6506    RADEONInfoPtr  info  = RADEONPTR(pScrn);
6507
6508    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, RADEON_LOGLEVEL_DEBUG,
6509		   "RADEONFreeScreen\n");
6510
6511    /* when server quits at PreInit, we don't need do this anymore*/
6512    if (!info) return;
6513
6514#ifdef WITH_VGAHW
6515    if (info->VGAAccess && xf86LoaderCheckSymbol("vgaHWFreeHWRec"))
6516	vgaHWFreeHWRec(pScrn);
6517#endif
6518    RADEONFreeRec(pScrn);
6519}
6520