Some fixes that bring me closer to surviving to the 2nd X server generation.
[nouveau] / src / nv_driver.c
1 /*
2  * Copyright 1996-1997 David J. McKay
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
17  * THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
18  * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
19  * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20  * SOFTWARE.
21  */
22
23 #include <stdio.h>
24
25 #include "nv_include.h"
26
27 #include "xf86int10.h"
28
29 #include "xf86drm.h"
30
31 /*
32  * Forward definitions for the functions that make up the driver.
33  */
34 /* Mandatory functions */
35 static const OptionInfoRec * NVAvailableOptions(int chipid, int busid);
36 static void    NVIdentify(int flags);
37 #ifndef XSERVER_LIBPCIACCESS
38 static Bool    NVProbe(DriverPtr drv, int flags);
39 #endif /* XSERVER_LIBPCIACCESS */
40 static Bool    NVPreInit(ScrnInfoPtr pScrn, int flags);
41 static Bool    NVScreenInit(int Index, ScreenPtr pScreen, int argc,
42                             char **argv);
43 static Bool    NVEnterVT(int scrnIndex, int flags);
44 static void    NVLeaveVT(int scrnIndex, int flags);
45 static Bool    NVCloseScreen(int scrnIndex, ScreenPtr pScreen);
46 static Bool    NVSaveScreen(ScreenPtr pScreen, int mode);
47
48 /* Optional functions */
49 static Bool    NVSwitchMode(int scrnIndex, DisplayModePtr mode, int flags);
50 static void    NVAdjustFrame(int scrnIndex, int x, int y, int flags);
51 static void    NVFreeScreen(int scrnIndex, int flags);
52 static ModeStatus NVValidMode(int scrnIndex, DisplayModePtr mode,
53                               Bool verbose, int flags);
54
55 /* Internally used functions */
56
57 static Bool     NVMapMem(ScrnInfoPtr pScrn);
58 static Bool     NVUnmapMem(ScrnInfoPtr pScrn);
59 static void     NVSave(ScrnInfoPtr pScrn);
60 static void     NVRestore(ScrnInfoPtr pScrn);
61 static Bool     NVModeInit(ScrnInfoPtr pScrn, DisplayModePtr mode);
62
63 #ifdef XSERVER_LIBPCIACCESS
64
65 #define NOUVEAU_PCI_DEVICE(_vendor_id, _device_id) \
66         { (_vendor_id), (_device_id), PCI_MATCH_ANY, PCI_MATCH_ANY, 0x00030000, 0x00ffffff, 0 }
67
68 static const struct pci_id_match nouveau_device_match[] = {
69         NOUVEAU_PCI_DEVICE(PCI_VENDOR_NVIDIA, PCI_MATCH_ANY),
70         NOUVEAU_PCI_DEVICE(PCI_VENDOR_NVIDIA_SGS, PCI_MATCH_ANY),
71         { 0, 0, 0 },
72 };
73
74 static Bool NVPciProbe (        DriverPtr               drv,
75                                 int                     entity_num,
76                                 struct pci_device       *dev,
77                                 intptr_t                match_data      );
78
79 #endif /* XSERVER_LIBPCIACCESS */
80
81 /*
82  * This contains the functions needed by the server after loading the
83  * driver module.  It must be supplied, and gets added the driver list by
84  * the Module Setup funtion in the dynamic case.  In the static case a
85  * reference to this is compiled in, and this requires that the name of
86  * this DriverRec be an upper-case version of the driver name.
87  */
88
89 _X_EXPORT DriverRec NV = {
90         NV_VERSION,
91         NV_DRIVER_NAME,
92         NVIdentify,
93 #ifdef XSERVER_LIBPCIACCESS
94         NULL,
95 #else
96         NVProbe,
97 #endif /* XSERVER_LIBPCIACCESS */
98         NVAvailableOptions,
99         NULL,
100         0,
101         NULL,
102 #ifdef XSERVER_LIBPCIACCESS
103         nouveau_device_match,
104         NVPciProbe
105 #endif /* XSERVER_LIBPCIACCESS */
106 };
107
108 struct NvFamily
109 {
110   char *name;
111   char *chipset;
112 };
113
114 static struct NvFamily NVKnownFamilies[] =
115 {
116   { "RIVA TNT",    "NV04" },
117   { "RIVA TNT2",   "NV05" },
118   { "GeForce 256", "NV10" },
119   { "GeForce 2",   "NV11, NV15" },
120   { "GeForce 4MX", "NV17, NV18" },
121   { "GeForce 3",   "NV20" },
122   { "GeForce 4Ti", "NV25, NV28" },
123   { "GeForce FX",  "NV3x" },
124   { "GeForce 6",   "NV4x" },
125   { "GeForce 7",   "G7x" },
126   { "GeForce 8",   "G8x" },
127   { NULL, NULL}
128 };
129
130 /*
131  * List of symbols from other modules that this module references.  This
132  * list is used to tell the loader that it is OK for symbols here to be
133  * unresolved providing that it hasn't been told that they haven't been
134  * told that they are essential via a call to xf86LoaderReqSymbols() or
135  * xf86LoaderReqSymLists().  The purpose is this is to avoid warnings about
136  * unresolved symbols that are not required.
137  */
138
139 static const char *vgahwSymbols[] = {
140     "vgaHWUnmapMem",
141     "vgaHWDPMSSet",
142     "vgaHWFreeHWRec",
143     "vgaHWGetHWRec",
144     "vgaHWGetIndex",
145     "vgaHWInit",
146     "vgaHWMapMem",
147     "vgaHWProtect",
148     "vgaHWRestore",
149     "vgaHWSave",
150     "vgaHWSaveScreen",
151     NULL
152 };
153
154 static const char *fbSymbols[] = {
155     "fbPictureInit",
156     "fbScreenInit",
157     NULL
158 };
159
160 static const char *exaSymbols[] = {
161     "exaDriverInit",
162     "exaOffscreenInit",
163     NULL
164 };
165
166 static const char *ramdacSymbols[] = {
167     "xf86CreateCursorInfoRec",
168     "xf86DestroyCursorInfoRec",
169     "xf86InitCursor",
170     NULL
171 };
172
173 static const char *ddcSymbols[] = {
174     "xf86PrintEDID",
175     "xf86DoEDID_DDC2",
176     "xf86SetDDCproperties",
177     NULL
178 };
179
180 static const char *vbeSymbols[] = {
181     "VBEInit",
182     "vbeFree",
183     "vbeDoEDID",
184     NULL
185 };
186
187 static const char *i2cSymbols[] = {
188     "xf86CreateI2CBusRec",
189     "xf86I2CBusInit",
190     NULL
191 };
192
193 static const char *shadowSymbols[] = {
194     "ShadowFBInit",
195     NULL
196 };
197
198 static const char *int10Symbols[] = {
199     "xf86FreeInt10",
200     "xf86InitInt10",
201     "xf86ExecX86int10",
202     NULL
203 };
204
205 const char *drmSymbols[] = {
206     "drmOpen", 
207     "drmAddBufs",
208     "drmAddMap",
209     "drmAgpAcquire",
210     "drmAgpVersionMajor",
211     "drmAgpVersionMinor",
212     "drmAgpAlloc",
213     "drmAgpBind",
214     "drmAgpEnable",
215     "drmAgpFree",
216     "drmAgpRelease",
217     "drmAgpUnbind",
218     "drmAuthMagic",
219     "drmCommandNone",
220     "drmCommandWrite",
221     "drmCommandWriteRead",
222     "drmCreateContext",
223     "drmCtlInstHandler",
224     "drmCtlUninstHandler",
225     "drmDestroyContext",
226     "drmFreeVersion",
227     "drmGetInterruptFromBusID",
228     "drmGetLibVersion",
229     "drmGetVersion",
230     NULL
231 };
232
233 const char *driSymbols[] = {
234     "DRICloseScreen",
235     "DRICreateInfoRec",
236     "DRIDestroyInfoRec",
237     "DRIFinishScreenInit",
238     "DRIGetSAREAPrivate",
239     "DRILock",
240     "DRIQueryVersion",
241     "DRIScreenInit",
242     "DRIUnlock",
243     "GlxSetVisualConfigs",
244     "DRICreatePCIBusID",
245     NULL
246 };
247
248
249 static MODULESETUPPROTO(nouveauSetup);
250
251 static XF86ModuleVersionInfo nouveauVersRec =
252 {
253     "nouveau",
254     MODULEVENDORSTRING,
255     MODINFOSTRING1,
256     MODINFOSTRING2,
257     XORG_VERSION_CURRENT,
258     NV_MAJOR_VERSION, NV_MINOR_VERSION, NV_PATCHLEVEL,
259     ABI_CLASS_VIDEODRV,                     /* This is a video driver */
260     ABI_VIDEODRV_VERSION,
261     MOD_CLASS_VIDEODRV,
262     {0,0,0,0}
263 };
264
265 _X_EXPORT XF86ModuleData nouveauModuleData = { &nouveauVersRec, nouveauSetup, NULL };
266
267 static Bool
268 NVGetRec(ScrnInfoPtr pScrn)
269 {
270     /*
271      * Allocate an NVRec, and hook it into pScrn->driverPrivate.
272      * pScrn->driverPrivate is initialised to NULL, so we can check if
273      * the allocation has already been done.
274      */
275     if (pScrn->driverPrivate != NULL)
276         return TRUE;
277
278     pScrn->driverPrivate = xnfcalloc(sizeof(NVRec), 1);
279     /* Initialise it */
280
281     return TRUE;
282 }
283
284 static void
285 NVFreeRec(ScrnInfoPtr pScrn)
286 {
287         if (pScrn->driverPrivate == NULL)
288                 return;
289         NVPtr pNv = NVPTR(pScrn);
290         if (pNv->Architecture == NV_ARCH_50 && !pNv->kms_enable) {
291                 NV50ConnectorDestroy(pScrn);
292                 NV50OutputDestroy(pScrn);
293                 NV50CrtcDestroy(pScrn);
294         }
295         xfree(pScrn->driverPrivate);
296         pScrn->driverPrivate = NULL;
297 }
298
299
300 static pointer
301 nouveauSetup(pointer module, pointer opts, int *errmaj, int *errmin)
302 {
303         static Bool setupDone = FALSE;
304
305         /* This module should be loaded only once, but check to be sure. */
306
307         if (!setupDone) {
308                 setupDone = TRUE;
309                 /* The 1 here is needed to turn off a backwards compatibility mode */
310                 /* Otherwise NVPciProbe() is not called */
311                 xf86AddDriver(&NV, module, 1);
312
313                 /*
314                  * Modules that this driver always requires may be loaded here
315                  * by calling LoadSubModule().
316                  */
317                 /*
318                  * Tell the loader about symbols from other modules that this module
319                  * might refer to.
320                  */
321                 LoaderRefSymLists(vgahwSymbols, exaSymbols, fbSymbols,
322                                 ramdacSymbols, shadowSymbols, drmSymbols, 
323                                 i2cSymbols, ddcSymbols, vbeSymbols,
324                                 int10Symbols, NULL);
325
326                 /*
327                  * The return value must be non-NULL on success even though there
328                  * is no TearDownProc.
329                  */
330                 return (pointer)1;
331         } else {
332                 if (errmaj) *errmaj = LDR_ONCEONLY;
333                 return NULL;
334         }
335 }
336
337 static const OptionInfoRec *
338 NVAvailableOptions(int chipid, int busid)
339 {
340     return NVOptions;
341 }
342
343 /* Mandatory */
344 static void
345 NVIdentify(int flags)
346 {
347     struct NvFamily *family;
348     size_t maxLen=0;
349
350     xf86DrvMsg(0, X_INFO, NV_NAME " driver " NV_DRIVER_DATE "\n");
351     xf86DrvMsg(0, X_INFO, NV_NAME " driver for NVIDIA chipset families :\n");
352
353     /* maximum length for alignment */
354     family = NVKnownFamilies;
355     while(family->name && family->chipset)
356     {
357         maxLen = max(maxLen, strlen(family->name));
358         family++;
359     }
360
361     /* display */
362     family = NVKnownFamilies;
363     while(family->name && family->chipset)
364     {
365         size_t len = strlen(family->name);
366         xf86ErrorF("\t%s", family->name);
367         while(len<maxLen+1)
368         {
369             xf86ErrorF(" ");
370             len++;
371         }
372         xf86ErrorF("(%s)\n", family->chipset);
373         family++;
374     }
375 }
376
377
378 #ifndef XSERVER_LIBPCIACCESS
379 static Bool
380 NVGetScrnInfoRec(PciChipsets *chips, int chip)
381 {
382     ScrnInfoPtr pScrn;
383
384     pScrn = xf86ConfigPciEntity(NULL, 0, chip,
385                                 chips, NULL, NULL, NULL,
386                                 NULL, NULL);
387
388     if(!pScrn) return FALSE;
389
390     pScrn->driverVersion    = NV_VERSION;
391     pScrn->driverName       = NV_DRIVER_NAME;
392     pScrn->name             = NV_NAME;
393
394     pScrn->Probe = NVProbe;
395     pScrn->PreInit          = NVPreInit;
396     pScrn->ScreenInit       = NVScreenInit;
397     pScrn->SwitchMode       = NVSwitchMode;
398     pScrn->AdjustFrame      = NVAdjustFrame;
399     pScrn->EnterVT          = NVEnterVT;
400     pScrn->LeaveVT          = NVLeaveVT;
401     pScrn->FreeScreen       = NVFreeScreen;
402     pScrn->ValidMode        = NVValidMode;
403
404     return TRUE;
405 }
406 #endif
407
408 /* This returns architecture in hexdecimal, so NV40 is 0x40 */
409 static int NVGetArchitecture(volatile uint32_t *regs)
410 {
411         int architecture = 0;
412
413         /* We're dealing with >=NV10 */
414         if ((regs[0] & 0x0f000000) > 0 )
415                 /* Bit 27-20 contain the architecture in hex */
416                 architecture = (regs[0] & 0xff00000) >> 20;
417         /* NV04 or NV05 */
418         else if ((regs[0] & 0xff00fff0) == 0x20004000)
419                 architecture = 0x04;
420
421         return architecture;
422 }
423
424 /* Reading the pci_id from the card registers is the most reliable way */
425 static uint32_t NVGetPCIID(volatile uint32_t *regs)
426 {
427         int architecture = NVGetArchitecture(regs);
428         uint32_t pci_id;
429
430         /* Dealing with an unknown or unsupported card */
431         if (architecture == 0)
432                 return 0;
433
434         if (architecture >= 0x40)
435                 pci_id = regs[0x88000/4];
436         else
437                 pci_id = regs[0x1800/4];
438
439         /* A pci-id can be inverted, we must correct this */
440         if ((pci_id & 0xffff) == PCI_VENDOR_NVIDIA)
441                 pci_id = (PCI_VENDOR_NVIDIA << 16) | (pci_id >> 16);
442         else if ((pci_id & 0xffff) == PCI_VENDOR_NVIDIA_SGS)
443                 pci_id = (PCI_VENDOR_NVIDIA_SGS << 16) | (pci_id >> 16);
444         /* Checking endian issues */
445         else {
446                 /* PCI_VENDOR_NVIDIA = 0x10DE */
447                 if ((pci_id & (0xffff << 16)) == (0xDE10 << 16)) /* wrong endian */
448                         pci_id = (PCI_VENDOR_NVIDIA << 16) | ((pci_id << 8) & 0x0000ff00) |
449                                 ((pci_id >> 8) & 0x000000ff);
450                 /* PCI_VENDOR_NVIDIA_SGS = 0x12D2 */
451                 else if ((pci_id & (0xffff << 16)) == (0xD212 << 16)) /* wrong endian */
452                         pci_id = (PCI_VENDOR_NVIDIA_SGS << 16) | ((pci_id << 8) & 0x0000ff00) |
453                                 ((pci_id >> 8) & 0x000000ff);
454         }
455
456         return pci_id;
457 }
458
459 #ifdef XSERVER_LIBPCIACCESS
460
461 static Bool NVPciProbe (        DriverPtr               drv,
462                                 int                     entity_num,
463                                 struct pci_device       *dev,
464                                 intptr_t                match_data      )
465 {
466         ScrnInfoPtr pScrn = NULL;
467
468         volatile uint32_t *regs = NULL;
469
470         /* Temporary mapping to discover the architecture */
471         pci_device_map_range(dev, PCI_DEV_MEM_BASE(dev, 0), 0x90000, 0,
472                              (void *) &regs);
473
474         uint8_t architecture = NVGetArchitecture(regs);
475
476         CARD32 pci_id = NVGetPCIID(regs);
477
478         pci_device_unmap_range(dev, (void *) regs, 0x90000);
479
480         /* Currently NV04 up to NVAA is known. */
481         /* Using 0xAF as upper bound for some margin. */
482         if (architecture >= 0x04 && architecture <= 0xAF) {
483
484                 /* At this stage the pci_id should be ok, so we generate this
485                  * to avoid list duplication */
486                 /* AGP bridge chips need their bridge chip id to be detected */
487                 PciChipsets NVChipsets[] = {
488                         { pci_id, PCI_DEV_PCI_ID(dev), RES_SHARED_VGA },
489                         { -1, -1, RES_UNDEFINED }
490                 };
491
492                 pScrn = xf86ConfigPciEntity(pScrn, 0, entity_num, NVChipsets, 
493                                                 NULL, NULL, NULL, NULL, NULL);
494
495                 if (pScrn != NULL) {
496                         pScrn->driverVersion    = NV_VERSION;
497                         pScrn->driverName       = NV_DRIVER_NAME;
498                         pScrn->name             = NV_NAME;
499
500                         pScrn->Probe            = NULL;
501                         pScrn->PreInit          = NVPreInit;
502                         pScrn->ScreenInit       = NVScreenInit;
503                         pScrn->SwitchMode       = NVSwitchMode;
504                         pScrn->AdjustFrame      = NVAdjustFrame;
505                         pScrn->EnterVT          = NVEnterVT;
506                         pScrn->LeaveVT          = NVLeaveVT;
507                         pScrn->FreeScreen       = NVFreeScreen;
508                         pScrn->ValidMode        = NVValidMode;
509
510                         return TRUE;
511                 }
512         }
513
514         return FALSE;
515 }
516
517 #endif /* XSERVER_LIBPCIACCESS */
518
519 #define MAX_CHIPS MAXSCREENS
520
521 #ifndef XSERVER_LIBPCIACCESS
522 /* Mandatory */
523 static Bool
524 NVProbe(DriverPtr drv, int flags)
525 {
526         int i;
527         GDevPtr *devSections;
528         int *usedChips;
529         SymTabRec NVChipsets[MAX_CHIPS + 1];
530         PciChipsets NVPciChipsets[MAX_CHIPS + 1];
531         pciVideoPtr *ppPci;
532         int numDevSections;
533         int numUsed;
534         Bool foundScreen = FALSE;
535
536         if ((numDevSections = xf86MatchDevice(NV_DRIVER_NAME, &devSections)) <= 0) 
537                 return FALSE;  /* no matching device section */
538
539         if (!(ppPci = xf86GetPciVideoInfo())) 
540                 return FALSE;  /* no PCI cards found */
541
542         numUsed = 0;
543
544         /* Create the NVChipsets and NVPciChipsets from found devices */
545         while (*ppPci && (numUsed < MAX_CHIPS)) {
546                 if (((*ppPci)->vendor == PCI_VENDOR_NVIDIA_SGS) || 
547                         ((*ppPci)->vendor == PCI_VENDOR_NVIDIA)) 
548                 {
549                         volatile uint32_t *regs;
550                         uint32_t pcicmd;
551
552                         PCI_DEV_READ_LONG(*ppPci, PCI_CMD_STAT_REG, &pcicmd);
553                         /* Enable reading memory? */
554                         PCI_DEV_WRITE_LONG(*ppPci, PCI_CMD_STAT_REG, pcicmd | PCI_CMD_MEM_ENABLE);
555
556                         regs = xf86MapPciMem(-1, VIDMEM_MMIO, PCI_DEV_TAG(*ppPci), PCI_DEV_MEM_BASE(*ppPci, 0), 0x90000);
557                         int pciid = NVGetPCIID(regs);
558
559                         int architecture = NVGetArchitecture(regs);
560                         char name[25];
561                         sprintf(name, "NVIDIA NV%02X", architecture);
562                         /* NV04 upto NV98 is known. */
563                         if (architecture >= 0x04 && architecture <= 0x9F) {
564                                 NVChipsets[numUsed].token = pciid;
565                                 NVChipsets[numUsed].name = name;
566                                 NVPciChipsets[numUsed].numChipset = pciid;
567                                 /* AGP bridge chips need their bridge chip id to be detected */
568                                 NVPciChipsets[numUsed].PCIid = PCI_DEV_PCI_ID(*ppPci);
569                                 NVPciChipsets[numUsed].resList = RES_SHARED_VGA;
570                                 numUsed++;
571                         }
572                         xf86UnMapVidMem(-1, (pointer)regs, 0x90000);
573
574                         /* Reset previous state */
575                         PCI_DEV_WRITE_LONG(*ppPci, PCI_CMD_STAT_REG, pcicmd);
576                 }
577                 ppPci++;
578         }
579
580         /* terminate the list */
581         NVChipsets[numUsed].token = -1;
582         NVChipsets[numUsed].name = NULL; 
583         NVPciChipsets[numUsed].numChipset = -1;
584         NVPciChipsets[numUsed].PCIid = -1;
585         NVPciChipsets[numUsed].resList = RES_UNDEFINED;
586
587         numUsed = xf86MatchPciInstances(NV_NAME, 0, NVChipsets, NVPciChipsets,
588                                         devSections, numDevSections, drv,
589                                         &usedChips);
590
591         if (numUsed <= 0) {
592                 return FALSE;
593         }
594
595         if (flags & PROBE_DETECT) {
596                 foundScreen = TRUE;
597         } else {
598                 for (i = 0; i < numUsed; i++) {
599                         pciVideoPtr pPci;
600
601                         pPci = xf86GetPciInfoForEntity(usedChips[i]);
602                         if (NVGetScrnInfoRec(NVPciChipsets, usedChips[i])) {
603                                 foundScreen = TRUE;
604                         }
605                 }
606         }
607
608         xfree(devSections);
609         xfree(usedChips);
610
611         return foundScreen;
612 }
613 #endif /* XSERVER_LIBPCIACCESS */
614
615 Bool
616 NVSwitchMode(int scrnIndex, DisplayModePtr mode, int flags)
617 {
618         ScrnInfoPtr pScrn = xf86Screens[scrnIndex];
619         NVPtr pNv = NVPTR(pScrn);
620
621         if (pNv->randr12_enable)
622                 return xf86SetSingleMode(pScrn, mode, RR_Rotate_0);
623
624         return NVModeInit(xf86Screens[scrnIndex], mode);
625 }
626
627 /*
628  * This function is used to initialize the Start Address - the first
629  * displayed location in the video memory.
630  */
631 /* Usually mandatory */
632 void 
633 NVAdjustFrame(int scrnIndex, int x, int y, int flags)
634 {
635         ScrnInfoPtr pScrn = xf86Screens[scrnIndex];
636         NVPtr pNv = NVPTR(pScrn);
637
638         if (pNv->randr12_enable) {
639                 xf86CrtcConfigPtr config = XF86_CRTC_CONFIG_PTR(pScrn);
640                 xf86CrtcPtr crtc = config->output[config->compat_output]->crtc;
641
642                 if (crtc && crtc->enabled)
643                         NVCrtcSetBase(crtc, x, y);
644         } else {
645                 int startAddr;
646                 startAddr = (((y*pScrn->displayWidth)+x)*(pScrn->bitsPerPixel/8));
647                 startAddr += pNv->FB->offset;
648                 NVSetStartAddress(pNv, startAddr);
649         }
650 }
651
652 static Bool
653 NV50AcquireDisplay(ScrnInfoPtr pScrn)
654 {
655         if (!NV50DispInit(pScrn))
656                 return FALSE;
657         if (!NV50CursorAcquire(pScrn))
658                 return FALSE;
659         xf86SetDesiredModes(pScrn);
660
661         return TRUE;
662 }
663
664 static Bool
665 NV50ReleaseDisplay(ScrnInfoPtr pScrn)
666 {
667         NVPtr pNv = NVPTR(pScrn);
668
669         NV50CursorRelease(pScrn);
670         NV50DispShutdown(pScrn);
671
672         if (pNv->pInt10 && pNv->Int10Mode) {
673                 xf86Int10InfoPtr pInt10 = pNv->pInt10;
674
675                 pInt10->num = 0x10;
676                 pInt10->ax  = 0x4f02;
677                 pInt10->bx  = pNv->Int10Mode | 0x8000;
678                 pInt10->cx  =
679                 pInt10->dx  = 0;
680                 xf86ExecX86int10(pInt10);
681         }
682
683         return TRUE;
684 }
685
686 /*
687  * This is called when VT switching back to the X server.  Its job is
688  * to reinitialise the video mode.
689  *
690  * We may wish to unmap video/MMIO memory too.
691  */
692
693 /* Mandatory */
694 static Bool
695 NVEnterVT(int scrnIndex, int flags)
696 {
697         ScrnInfoPtr pScrn = xf86Screens[scrnIndex];
698         NVPtr pNv = NVPTR(pScrn);
699
700         if (!pNv->kms_enable) {
701                 if (pNv->randr12_enable) {
702                         xf86DrvMsg(pScrn->scrnIndex, X_INFO, "NVEnterVT is called.\n");
703                         xf86CrtcConfigPtr xf86_config = XF86_CRTC_CONFIG_PTR(pScrn);
704                         int i;
705                         pScrn->vtSema = TRUE;
706
707                         if (pNv->Architecture == NV_ARCH_50) {
708                                 if (!NV50AcquireDisplay(pScrn))
709                                         return FALSE;
710                                 return TRUE;
711                         }
712
713                         /* Save the current state */
714                         if (pNv->SaveGeneration != serverGeneration) {
715                                 pNv->SaveGeneration = serverGeneration;
716                                 NVSave(pScrn);
717                         }
718
719                         for (i = 0; i < xf86_config->num_crtc; i++) {
720                                 NVCrtcLockUnlock(xf86_config->crtc[i], 0);
721                         }
722
723                         if (!xf86SetDesiredModes(pScrn))
724                                 return FALSE;
725                 } else {
726                         if (!NVModeInit(pScrn, pScrn->currentMode))
727                                 return FALSE;
728
729                         NVAdjustFrame(scrnIndex, pScrn->frameX0, pScrn->frameY0, 0);
730                 }
731         } else {
732                 xf86DrvMsg(pScrn->scrnIndex, X_INFO, "NVEnterVT is called.\n");
733                 if (!xf86SetDesiredModes(pScrn)) {
734                         xf86DrvMsg(pScrn->scrnIndex, X_WARNING, "xf86SetDesiredModes failed\n");
735                         return FALSE;
736                 }
737         }
738
739         if (pNv->overlayAdaptor && pNv->Architecture != NV_ARCH_04)
740                 NV10WriteOverlayParameters(pScrn);
741
742         return TRUE;
743 }
744
745 /*
746  * This is called when VT switching away from the X server.  Its job is
747  * to restore the previous (text) mode.
748  *
749  * We may wish to remap video/MMIO memory too.
750  */
751
752 /* Mandatory */
753 static void
754 NVLeaveVT(int scrnIndex, int flags)
755 {
756         ScrnInfoPtr pScrn = xf86Screens[scrnIndex];
757         NVPtr pNv = NVPTR(pScrn);
758         if (pNv->randr12_enable)
759                 xf86DrvMsg(pScrn->scrnIndex, X_INFO, "NVLeaveVT is called.\n");
760
761         NVSync(pScrn);
762
763         if (pNv->kms_enable)
764                 return;
765
766         if (pNv->Architecture == NV_ARCH_50) {
767                 NV50ReleaseDisplay(pScrn);
768                 return;
769         }
770
771         NVRestore(pScrn);
772         if (!pNv->randr12_enable)
773                 NVLockUnlock(pScrn, 1);
774 }
775
776 static void 
777 NVBlockHandler (
778         int i, 
779         pointer blockData, 
780         pointer pTimeout,
781         pointer pReadmask
782 )
783 {
784         ScreenPtr pScreen = screenInfo.screens[i];
785         ScrnInfoPtr pScrnInfo = xf86Screens[i];
786         NVPtr pNv = NVPTR(pScrnInfo);
787
788         if (!pNv->NoAccel)
789                 FIRE_RING (pNv->chan);
790
791         pScreen->BlockHandler = pNv->BlockHandler;
792         (*pScreen->BlockHandler) (i, blockData, pTimeout, pReadmask);
793         pScreen->BlockHandler = NVBlockHandler;
794
795         if (pNv->VideoTimerCallback) 
796                 (*pNv->VideoTimerCallback)(pScrnInfo, currentTime.milliseconds);
797 }
798
799
800 /*
801  * This is called at the end of each server generation.  It restores the
802  * original (text) mode.  It should also unmap the video memory, and free
803  * any per-generation data allocated by the driver.  It should finish
804  * by unwrapping and calling the saved CloseScreen function.
805  */
806
807 /* Mandatory */
808 static Bool
809 NVCloseScreen(int scrnIndex, ScreenPtr pScreen)
810 {
811         ScrnInfoPtr pScrn = xf86Screens[scrnIndex];
812         NVPtr pNv = NVPTR(pScrn);
813
814         if (pScrn->vtSema) {
815                 pScrn->vtSema = FALSE;
816 #ifdef XF86DRM_MODE
817                 if (pNv->kms_enable) {
818                         NVSync(pScrn);
819                 } else
820 #endif
821                 if (pNv->Architecture == NV_ARCH_50) {
822                         NV50ReleaseDisplay(pScrn);
823                 } else {
824                         if (pNv->randr12_enable)
825                                 xf86DrvMsg(pScrn->scrnIndex, X_INFO, "NVCloseScreen is called.\n");
826                         NVSync(pScrn);
827                         NVRestore(pScrn);
828                         if (!pNv->randr12_enable)
829                                 NVLockUnlock(pScrn, 1);
830                 }
831         }
832
833         NVUnmapMem(pScrn);
834         vgaHWUnmapMem(pScrn);
835         NVDRICloseScreen(pScrn);
836         if (pNv->CursorInfoRec)
837                 xf86DestroyCursorInfoRec(pNv->CursorInfoRec);
838         if (pNv->ShadowPtr) {
839                 xfree(pNv->ShadowPtr);
840                 pNv->ShadowPtr = NULL;
841         }
842         if (pNv->overlayAdaptor) {
843                 xfree(pNv->overlayAdaptor);
844                 pNv->overlayAdaptor = NULL;
845         }
846         if (pNv->blitAdaptor) {
847                 xfree(pNv->blitAdaptor);
848                 pNv->blitAdaptor = NULL;
849         }
850         if (pNv->textureAdaptor[0]) {
851                 xfree(pNv->textureAdaptor[0]);
852                 pNv->textureAdaptor[0] = NULL;
853         }
854         if (pNv->textureAdaptor[1]) {
855                 xfree(pNv->textureAdaptor[1]);
856                 pNv->textureAdaptor[1] = NULL;
857         }
858         if (pNv->EXADriverPtr) {
859                 exaDriverFini(pScreen);
860                 xfree(pNv->EXADriverPtr);
861                 pNv->EXADriverPtr = NULL;
862         }
863
864         pScrn->vtSema = FALSE;
865         pScreen->CloseScreen = pNv->CloseScreen;
866         pScreen->BlockHandler = pNv->BlockHandler;
867         return (*pScreen->CloseScreen)(scrnIndex, pScreen);
868 }
869
870 /* Free up any persistent data structures */
871
872 /* Optional */
873 static void
874 NVFreeScreen(int scrnIndex, int flags)
875 {
876         /*
877          * This only gets called when a screen is being deleted.  It does not
878          * get called routinely at the end of a server generation.
879         */
880         ScrnInfoPtr pScrn = xf86Screens[scrnIndex];
881         NVPtr pNv = NVPTR(pScrn);
882
883         /* Free this here and not in CloseScreen, as it's needed after the first server generation. */
884         if (pNv->pInt10)
885                 xf86FreeInt10(pNv->pInt10);
886
887         if (xf86LoaderCheckSymbol("vgaHWFreeHWRec"))
888                 vgaHWFreeHWRec(xf86Screens[scrnIndex]);
889         NVFreeRec(xf86Screens[scrnIndex]);
890 }
891
892
893 /* Checks if a mode is suitable for the selected chipset. */
894
895 /* Optional */
896 static ModeStatus
897 NVValidMode(int scrnIndex, DisplayModePtr mode, Bool verbose, int flags)
898 {
899     NVPtr pNv = NVPTR(xf86Screens[scrnIndex]);
900
901     if(pNv->fpWidth && pNv->fpHeight)
902       if((pNv->fpWidth < mode->HDisplay) || (pNv->fpHeight < mode->VDisplay))
903         return (MODE_PANEL);
904
905     return (MODE_OK);
906 }
907
908 Bool NVI2CInit(ScrnInfoPtr pScrn)
909 {
910         NVPtr pNv = NVPTR(pScrn);
911
912         if (xf86LoadSubModule(pScrn, "i2c") && xf86LoadSubModule(pScrn, "ddc")) {
913                 xf86LoaderReqSymLists(i2cSymbols,NULL);
914                 xf86LoaderReqSymLists(ddcSymbols, NULL);
915
916                 /* randr-1.2 clients have their DDCs initialized elsewhere */
917                 if (!pNv->randr12_enable)
918                         return NVDACi2cInit(pScrn);
919                 return true;
920         } else
921                 xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
922                 "Couldn't load i2c and ddc modules.  DDC probing can't be done\n");
923         return false;
924 }
925
926 #ifdef XF86DRM_MODE
927 static bool nouveau_kernel_modesetting_enabled(ScrnInfoPtr pScrn)
928 {
929 #if XSERVER_LIBPCIACCESS
930         struct pci_device *PciInfo;
931 #else
932         pciVideoPtr PciInfo;
933 #endif
934         EntityInfoPtr pEnt;
935         char *busIdString;
936         int ret;
937
938         pEnt = xf86GetEntityInfo(pScrn->entityList[0]);
939         PciInfo = xf86GetPciInfoForEntity(pEnt->index);
940
941         busIdString = DRICreatePCIBusID(PciInfo);
942
943         ret = drmCheckModesettingSupported(busIdString);
944         xfree(busIdString);
945         if (ret)
946                 return FALSE;
947
948         return TRUE;
949 }
950 #else
951 #define nouveau_kernel_modesetting_enabled(x) FALSE
952 #endif
953
954 static Bool NVPreInitDRI(ScrnInfoPtr pScrn)
955 {
956         NVPtr pNv = NVPTR(pScrn);
957
958         if (!NVDRIGetVersion(pScrn))
959                 return FALSE;
960
961         xf86DrvMsg(pScrn->scrnIndex, X_INFO,
962                 "[dri] Found DRI library version %d.%d.%d and kernel"
963                 " module version %d.%d.%d\n",
964                 pNv->pLibDRMVersion->version_major,
965                 pNv->pLibDRMVersion->version_minor,
966                 pNv->pLibDRMVersion->version_patchlevel,
967                 pNv->pKernelDRMVersion->version_major,
968                 pNv->pKernelDRMVersion->version_minor,
969                 pNv->pKernelDRMVersion->version_patchlevel);
970
971         return TRUE;
972 }
973
974 static Bool
975 nv_xf86crtc_resize(ScrnInfoPtr pScrn, int width, int height)
976 {
977         xf86DrvMsg(pScrn->scrnIndex, X_INFO, "nv_xf86crtc_resize is called with %dx%d resolution.\n", width, height);
978         pScrn->virtualX = width;
979         pScrn->virtualY = height;
980         return TRUE;
981 }
982
983 static const xf86CrtcConfigFuncsRec nv_xf86crtc_config_funcs = {
984         nv_xf86crtc_resize
985 };
986
987 #define NVPreInitFail(fmt, args...) do {                                    \
988         xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "%d: "fmt, __LINE__, ##args); \
989         if (pNv->pInt10)                                                    \
990                 xf86FreeInt10(pNv->pInt10);                                 \
991         NVFreeRec(pScrn);                                                   \
992         return FALSE;                                                       \
993 } while(0)
994
995 /* Mandatory */
996 Bool
997 NVPreInit(ScrnInfoPtr pScrn, int flags)
998 {
999         NVPtr pNv;
1000         MessageType from;
1001         int i, max_width, max_height;
1002         ClockRangePtr clockRanges;
1003         int config_mon_rates = FALSE;
1004
1005         if (flags & PROBE_DETECT) {
1006                 EntityInfoPtr pEnt = xf86GetEntityInfo(pScrn->entityList[0]);
1007
1008                 if (!pEnt)
1009                         return FALSE;
1010
1011                 i = pEnt->index;
1012                 xfree(pEnt);
1013
1014                 if (xf86LoadSubModule(pScrn, "vbe")) {
1015                         vbeInfoPtr pVbe = VBEInit(NULL, i);
1016                         ConfiguredMonitor = vbeDoEDID(pVbe, NULL);
1017                         vbeFree(pVbe);
1018                 }
1019
1020                 return TRUE;
1021         }
1022
1023         /*
1024          * Note: This function is only called once at server startup, and
1025          * not at the start of each server generation.  This means that
1026          * only things that are persistent across server generations can
1027          * be initialised here.  xf86Screens[] is (pScrn is a pointer to one
1028          * of these).  Privates allocated using xf86AllocateScrnInfoPrivateIndex()  
1029          * are too, and should be used for data that must persist across
1030          * server generations.
1031          *
1032          * Per-generation data should be allocated with
1033          * AllocateScreenPrivateIndex() from the ScreenInit() function.
1034          */
1035
1036         /* Check the number of entities, and fail if it isn't one. */
1037         if (pScrn->numEntities != 1)
1038                 return FALSE;
1039
1040         /* Allocate the NVRec driverPrivate */
1041         if (!NVGetRec(pScrn)) {
1042                 return FALSE;
1043         }
1044         pNv = NVPTR(pScrn);
1045
1046         /* Get the entity, and make sure it is PCI. */
1047         pNv->pEnt = xf86GetEntityInfo(pScrn->entityList[0]);
1048         if (pNv->pEnt->location.type != BUS_PCI)
1049                 return FALSE;
1050  
1051         /* Find the PCI info for this screen */
1052         pNv->PciInfo = xf86GetPciInfoForEntity(pNv->pEnt->index);
1053 #ifndef XSERVER_LIBPCIACCESS
1054         pNv->PciTag = pciTag(pNv->PciInfo->bus, pNv->PciInfo->device,
1055                                 pNv->PciInfo->func);
1056 #endif /* XSERVER_LIBPCIACCESS */
1057
1058         pNv->Primary = xf86IsPrimaryPci(pNv->PciInfo);
1059
1060         volatile uint32_t *regs = NULL;
1061 #ifdef XSERVER_LIBPCIACCESS
1062         pci_device_map_range(pNv->PciInfo, PCI_DEV_MEM_BASE(pNv->PciInfo, 0),
1063                              0x90000, 0, (void *)&regs);
1064         pNv->Chipset = NVGetPCIID(regs) & 0xffff;
1065         pNv->NVArch = NVGetArchitecture(regs);
1066         pci_device_unmap_range(pNv->PciInfo, (void *) regs, 0x90000);
1067 #else
1068         CARD32 pcicmd;
1069         PCI_DEV_READ_LONG(pNv->PciInfo, PCI_CMD_STAT_REG, &pcicmd);
1070         /* Enable reading memory? */
1071         PCI_DEV_WRITE_LONG(pNv->PciInfo, PCI_CMD_STAT_REG, pcicmd | PCI_CMD_MEM_ENABLE);
1072         regs = xf86MapPciMem(-1, VIDMEM_MMIO, pNv->PciTag, PCI_DEV_MEM_BASE(pNv->PciInfo, 0), 0x90000);
1073         pNv->Chipset = NVGetPCIID(regs) & 0xffff;
1074         pNv->NVArch = NVGetArchitecture(regs);
1075         xf86UnMapVidMem(-1, (pointer)regs, 0x90000);
1076         /* Reset previous state */
1077         PCI_DEV_WRITE_LONG(pNv->PciInfo, PCI_CMD_STAT_REG, pcicmd);
1078 #endif /* XSERVER_LIBPCIACCESS */
1079
1080         pScrn->chipset = malloc(sizeof(char) * 25);
1081         sprintf(pScrn->chipset, "NVIDIA NV%02X", pNv->NVArch);
1082
1083         if(!pScrn->chipset) {
1084                 pScrn->chipset = "Unknown NVIDIA";
1085         }
1086
1087         /*
1088         * This shouldn't happen because such problems should be caught in
1089         * NVProbe(), but check it just in case.
1090         */
1091         if (pScrn->chipset == NULL)
1092                 NVPreInitFail("ChipID 0x%04X is not recognised\n", pNv->Chipset);
1093
1094         if (pNv->NVArch < 0x04)
1095                 NVPreInitFail("Chipset \"%s\" is not recognised\n", pScrn->chipset);
1096
1097         xf86DrvMsg(pScrn->scrnIndex, X_PROBED, "Chipset: \"%s\"\n", pScrn->chipset);
1098
1099         /* The highest architecture currently supported is NV5x */
1100         if (pNv->NVArch >= 0x80) {
1101                 pNv->Architecture =  NV_ARCH_50;
1102         } else if (pNv->NVArch >= 0x60) {
1103                 pNv->Architecture =  NV_ARCH_40;
1104         } else if (pNv->NVArch >= 0x50) {
1105                 pNv->Architecture =  NV_ARCH_50;
1106         } else if (pNv->NVArch >= 0x40) {
1107                 pNv->Architecture =  NV_ARCH_40;
1108         } else if (pNv->NVArch >= 0x30) {
1109                 pNv->Architecture = NV_ARCH_30;
1110         } else if (pNv->NVArch >= 0x20) {
1111                 pNv->Architecture = NV_ARCH_20;
1112         } else if (pNv->NVArch >= 0x10) {
1113                 pNv->Architecture = NV_ARCH_10;
1114         } else if (pNv->NVArch >= 0x04) {
1115                 pNv->Architecture = NV_ARCH_04;
1116         /*  The lowest architecture currently supported is NV04 */
1117         } else {
1118                 return FALSE;
1119         }
1120
1121         /* Initialize the card through int10 interface if needed */
1122         if (xf86LoadSubModule(pScrn, "int10")) {
1123                 xf86LoaderReqSymLists(int10Symbols, NULL);
1124 #if !defined(__alpha__) && !defined(__powerpc__)
1125                 xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Initializing int10\n");
1126                 pNv->pInt10 = xf86InitInt10(pNv->pEnt->index);
1127 #endif
1128         }
1129
1130         /* Save current console video mode */
1131         if (pNv->Architecture >= NV_ARCH_50 && pNv->pInt10 && !pNv->kms_enable) {
1132                 const xf86Int10InfoPtr pInt10 = pNv->pInt10;
1133
1134                 pInt10->num = 0x10;
1135                 pInt10->ax  = 0x4f03;
1136                 pInt10->bx  =
1137                 pInt10->cx  =
1138                 pInt10->dx  = 0;
1139                 xf86ExecX86int10(pInt10);
1140                 pNv->Int10Mode = pInt10->bx & 0x3fff;
1141
1142                 xf86DrvMsg(pScrn->scrnIndex, X_PROBED,
1143                            "VESA-HACK: Console VGA mode is 0x%x\n",
1144                            pNv->Int10Mode);
1145         }
1146
1147         xf86SetOperatingState(resVgaIo, pNv->pEnt->index, ResUnusedOpr);
1148         xf86SetOperatingState(resVgaMem, pNv->pEnt->index, ResDisableOpr);
1149
1150         /* Set pScrn->monitor */
1151         pScrn->monitor = pScrn->confScreen->monitor;
1152
1153         /*
1154          * The first thing we should figure out is the depth, bpp, etc.
1155          */
1156
1157         if (!xf86SetDepthBpp(pScrn, 0, 0, 0, Support32bppFb)) {
1158                 NVPreInitFail("\n");
1159         } else {
1160                 /* Check that the returned depth is one we support */
1161                 switch (pScrn->depth) {
1162                         case 16:
1163                         case 24:
1164                                 /* OK */
1165                                 break;
1166                         case 15: /* 15 may get done one day, so leave any code for it in place */
1167                         default:
1168                                 NVPreInitFail("Given depth (%d) is not supported by this driver\n",
1169                                         pScrn->depth);
1170                 }
1171         }
1172         xf86PrintDepthBpp(pScrn);
1173
1174         /*
1175          * This must happen after pScrn->display has been set because
1176          * xf86SetWeight references it.
1177          */
1178         /* The defaults are OK for us */
1179         rgb rgbzeros = {0, 0, 0};
1180
1181         if (!xf86SetWeight(pScrn, rgbzeros, rgbzeros))
1182                 NVPreInitFail("\n");
1183
1184         if (!xf86SetDefaultVisual(pScrn, -1))
1185                 NVPreInitFail("\n");
1186         /* We don't support DirectColor */
1187         else if (pScrn->defaultVisual != TrueColor)
1188                 NVPreInitFail("Given default visual (%s) is not supported at depth %d\n",
1189                               xf86GetVisualName(pScrn->defaultVisual), pScrn->depth);
1190
1191         /* The vgahw module should be loaded here when needed */
1192         if (!xf86LoadSubModule(pScrn, "vgahw")) {
1193                 NVPreInitFail("\n");
1194         }
1195
1196         xf86LoaderReqSymLists(vgahwSymbols, NULL);
1197
1198         /*
1199          * Allocate a vgaHWRec
1200          */
1201         if (!vgaHWGetHWRec(pScrn)) {
1202                 NVPreInitFail("\n");
1203         }
1204
1205         /* We use a programmable clock */
1206         pScrn->progClock = TRUE;
1207
1208         /* Collect all of the relevant option flags (fill in pScrn->options) */
1209         xf86CollectOptions(pScrn, NULL);
1210
1211         /* Process the options */
1212         if (!(pNv->Options = xalloc(sizeof(NVOptions))))
1213                 return FALSE;
1214         memcpy(pNv->Options, NVOptions, sizeof(NVOptions));
1215         xf86ProcessOptions(pScrn->scrnIndex, pScrn->options, pNv->Options);
1216
1217         from = X_DEFAULT;
1218
1219         pNv->kms_enable = false;
1220 #ifdef XF86DRM_MODE
1221         if (pNv->Architecture == NV_ARCH_50)
1222                 pNv->kms_enable = nouveau_kernel_modesetting_enabled(pScrn);
1223 #endif /* XF86DRM_MODE */
1224
1225         if (pNv->kms_enable)
1226                 xf86DrvMsg(pScrn->scrnIndex, from, "NV50 Kernel modesetting enabled\n");
1227
1228         pNv->randr12_enable = true;
1229         if (pNv->Architecture != NV_ARCH_50 && !xf86ReturnOptValBool(pNv->Options, OPTION_RANDR12, TRUE))
1230                 pNv->randr12_enable = false;
1231         xf86DrvMsg(pScrn->scrnIndex, from, "Randr1.2 support %sabled\n", pNv->randr12_enable ? "en" : "dis");
1232
1233         pNv->HWCursor = TRUE;
1234         /*
1235          * The preferred method is to use the "hw cursor" option as a tri-state
1236          * option, with the default set above.
1237          */
1238         if (xf86GetOptValBool(pNv->Options, OPTION_HW_CURSOR, &pNv->HWCursor)) {
1239                 from = X_CONFIG;
1240         }
1241         /* For compatibility, accept this too (as an override) */
1242         if (xf86ReturnOptValBool(pNv->Options, OPTION_SW_CURSOR, FALSE)) {
1243                 from = X_CONFIG;
1244                 pNv->HWCursor = FALSE;
1245         }
1246         xf86DrvMsg(pScrn->scrnIndex, from, "Using %s cursor\n",
1247                 pNv->HWCursor ? "HW" : "SW");
1248
1249         pNv->FpScale = TRUE;
1250
1251         if (xf86GetOptValBool(pNv->Options, OPTION_FP_SCALE, &pNv->FpScale)) {
1252                 xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "Flat panel scaling %s\n",
1253                         pNv->FpScale ? "on" : "off");
1254         }
1255         if (xf86ReturnOptValBool(pNv->Options, OPTION_NOACCEL, FALSE)) {
1256                 pNv->NoAccel = TRUE;
1257                 xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "Acceleration disabled\n");
1258         }
1259         if (xf86ReturnOptValBool(pNv->Options, OPTION_SHADOW_FB, FALSE)) {
1260                 pNv->ShadowFB = TRUE;
1261                 pNv->NoAccel = TRUE;
1262                 xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, 
1263                         "Using \"Shadow Framebuffer\" - acceleration disabled\n");
1264         }
1265
1266         if(xf86GetOptValInteger(pNv->Options, OPTION_VIDEO_KEY, &(pNv->videoKey))) {
1267                 xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "video key set to 0x%x\n",
1268                                         pNv->videoKey);
1269         } else {
1270                 pNv->videoKey =  (1 << pScrn->offset.red) | 
1271                                         (1 << pScrn->offset.green) |
1272                 (((pScrn->mask.blue >> pScrn->offset.blue) - 1) << pScrn->offset.blue);
1273         }
1274
1275         /* Things happen on a per output basis for a randr-1.2 driver. */
1276         if (xf86GetOptValBool(pNv->Options, OPTION_FLAT_PANEL, &(pNv->FlatPanel)) && !pNv->randr12_enable) {
1277                 xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "forcing %s usage\n",
1278                         pNv->FlatPanel ? "DFP" : "CRTC");
1279         } else {
1280                 pNv->FlatPanel = -1; /* autodetect later */
1281         }
1282
1283         pNv->FPDither = FALSE;
1284         if (xf86GetOptValBool(pNv->Options, OPTION_FP_DITHER, &(pNv->FPDither))) 
1285                 xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "enabling flat panel dither\n");
1286
1287         if (xf86GetOptValInteger(pNv->Options, OPTION_FP_TWEAK, 
1288                                                 &pNv->PanelTweak)) {
1289                 pNv->usePanelTweak = TRUE;
1290         } else {
1291                 pNv->usePanelTweak = FALSE;
1292         }
1293
1294         if (pNv->pEnt->device->MemBase != 0) {
1295                 /* Require that the config file value matches one of the PCI values. */
1296                 if (!xf86CheckPciMemBase(pNv->PciInfo, pNv->pEnt->device->MemBase)) {
1297                         NVPreInitFail(
1298                                 "MemBase 0x%08lX doesn't match any PCI base register.\n",
1299                                 pNv->pEnt->device->MemBase);
1300                 }
1301                 pNv->VRAMPhysical = pNv->pEnt->device->MemBase;
1302                 from = X_CONFIG;
1303         } else {
1304                 if (PCI_DEV_MEM_BASE(pNv->PciInfo, 1) != 0) {
1305                         pNv->VRAMPhysical = PCI_DEV_MEM_BASE(pNv->PciInfo, 1) & 0xff800000;
1306                         from = X_PROBED;
1307                 } else {
1308                         NVPreInitFail("No valid FB address in PCI config space\n");
1309                         return FALSE;
1310                 }
1311         }
1312         xf86DrvMsg(pScrn->scrnIndex, from, "Linear framebuffer at 0x%lX\n",
1313                 (unsigned long)pNv->VRAMPhysical);
1314
1315         if (pNv->pEnt->device->IOBase != 0) {
1316                 /* Require that the config file value matches one of the PCI values. */
1317                 if (!xf86CheckPciMemBase(pNv->PciInfo, pNv->pEnt->device->IOBase)) {
1318                         NVPreInitFail("IOBase 0x%08lX doesn't match any PCI base register.\n",
1319                                 pNv->pEnt->device->IOBase);
1320                 }
1321                 pNv->IOAddress = pNv->pEnt->device->IOBase;
1322                 from = X_CONFIG;
1323         } else {
1324                 if (PCI_DEV_MEM_BASE(pNv->PciInfo, 0) != 0) {
1325                         pNv->IOAddress = PCI_DEV_MEM_BASE(pNv->PciInfo, 0) & 0xffffc000;
1326                         from = X_PROBED;
1327                 } else {
1328                         NVPreInitFail("No valid MMIO address in PCI config space\n");
1329                 }
1330         }
1331         xf86DrvMsg(pScrn->scrnIndex, from, "MMIO registers at 0x%lX\n",
1332                 (unsigned long)pNv->IOAddress);
1333
1334         if (xf86RegisterResources(pNv->pEnt->index, NULL, ResExclusive))
1335                 NVPreInitFail("xf86RegisterResources() found resource conflicts\n");
1336
1337         if (pNv->Architecture < NV_ARCH_10) {
1338                 max_width = (pScrn->bitsPerPixel > 16) ? 2032 : 2048;
1339                 max_height = 2048;
1340         } else if (pNv->Architecture < NV_ARCH_50) {
1341                 max_width = (pScrn->bitsPerPixel > 16) ? 4080 : 4096;
1342                 max_height = 4096;
1343         } else {
1344                 max_width = (pScrn->bitsPerPixel > 16) ? 8176 : 8192;
1345                 max_height = 8192;
1346         }
1347
1348 #ifdef XF86DRM_MODE
1349         if (pNv->kms_enable){
1350                 int res = 0;
1351                 char *bus_id;
1352                 bus_id = DRICreatePCIBusID(pNv->PciInfo);
1353
1354                 pNv->drmmode = calloc(1, sizeof(drmmode_rec));
1355                 res = drmmode_pre_init(pScrn, bus_id, pNv->drmmode, pScrn->bitsPerPixel >> 3);
1356                 if (!res) {
1357                         xfree(bus_id);
1358                         NVPreInitFail("Kernel modesetting failed to initialize\n");
1359                 }
1360         } else
1361 #endif
1362         if (pNv->randr12_enable) {
1363                 /* Allocate an xf86CrtcConfig */
1364                 xf86CrtcConfigInit(pScrn, &nv_xf86crtc_config_funcs);
1365                 xf86CrtcSetSizeRange(pScrn, 320, 200, max_width, max_height);
1366         }
1367
1368         if (NVPreInitDRI(pScrn) == FALSE)
1369                 NVPreInitFail("\n");
1370
1371         if (!pNv->randr12_enable) {
1372                 if ((pScrn->monitor->nHsync == 0) && 
1373                         (pScrn->monitor->nVrefresh == 0)) {
1374
1375                         config_mon_rates = FALSE;
1376                 } else {
1377                         config_mon_rates = TRUE;
1378                 }
1379         }
1380
1381         NVCommonSetup(pScrn);
1382
1383         if (pNv->randr12_enable && !pNv->kms_enable) {
1384                 if (pNv->Architecture == NV_ARCH_50)
1385                         if (!NV50DispPreInit(pScrn))
1386                                 NVPreInitFail("\n");
1387
1388                 NVI2CInit(pScrn);
1389
1390                 /* This is the internal system, not the randr-1.2 ones. */
1391                 if (pNv->Architecture == NV_ARCH_50) {
1392                         NV50CrtcInit(pScrn);
1393                         NV50ConnectorInit(pScrn);
1394                         NV50OutputSetup(pScrn);
1395                 }
1396
1397                 for (i = 0; i <= pNv->twoHeads; i++) {
1398                         if (pNv->Architecture == NV_ARCH_50)
1399                                 nv50_crtc_init(pScrn, i);
1400                         else
1401                                 nv_crtc_init(pScrn, i);
1402                 }
1403
1404                 if (pNv->Architecture < NV_ARCH_50)
1405                         NvSetupOutputs(pScrn);
1406                 else
1407                         nv50_output_create(pScrn); /* create randr-1.2 "outputs". */
1408
1409                 if (!xf86InitialConfiguration(pScrn, FALSE))
1410                         NVPreInitFail("No valid modes.\n");
1411         }
1412
1413         pScrn->videoRam = pNv->RamAmountKBytes;
1414         xf86DrvMsg(pScrn->scrnIndex, X_PROBED, "VideoRAM: %d kBytes\n",
1415                 pScrn->videoRam);
1416
1417         pNv->VRAMPhysicalSize = pScrn->videoRam * 1024;
1418
1419         /*
1420          * If the driver can do gamma correction, it should call xf86SetGamma()
1421          * here.
1422          */
1423         Gamma gammazeros = {0.0, 0.0, 0.0};
1424
1425         if (!xf86SetGamma(pScrn, gammazeros))
1426                 NVPreInitFail("\n");
1427
1428         /*
1429          * Setup the ClockRanges, which describe what clock ranges are available,
1430          * and what sort of modes they can be used for.
1431          */
1432
1433         clockRanges = xnfcalloc(sizeof(ClockRange), 1);
1434         clockRanges->next = NULL;
1435         clockRanges->minClock = pNv->MinVClockFreqKHz;
1436         clockRanges->maxClock = pNv->MaxVClockFreqKHz;
1437         clockRanges->clockIndex = -1;           /* programmable */
1438         clockRanges->doubleScanAllowed = TRUE;
1439         if ((pNv->Architecture == NV_ARCH_20) ||
1440                 ((pNv->Architecture == NV_ARCH_10) && 
1441                 ((pNv->Chipset & 0x0ff0) != CHIPSET_NV10) &&
1442                 ((pNv->Chipset & 0x0ff0) != CHIPSET_NV15))) {
1443                 /* HW is broken */
1444                 clockRanges->interlaceAllowed = FALSE;
1445         } else {
1446                 clockRanges->interlaceAllowed = TRUE;
1447         }
1448
1449         if(pNv->FlatPanel == 1) {
1450                 clockRanges->interlaceAllowed = FALSE;
1451                 clockRanges->doubleScanAllowed = FALSE;
1452         }
1453
1454 #ifdef M_T_DRIVER
1455         /* If DFP, add a modeline corresponding to its panel size */
1456         if (pNv->FlatPanel && !pNv->Television && pNv->fpWidth && pNv->fpHeight) {
1457                 DisplayModePtr Mode;
1458
1459                 Mode = xnfcalloc(1, sizeof(DisplayModeRec));
1460                 Mode = xf86CVTMode(pNv->fpWidth, pNv->fpHeight, 60.00, TRUE, FALSE);
1461                 Mode->type = M_T_DRIVER;
1462                 pScrn->monitor->Modes = xf86ModesAdd(pScrn->monitor->Modes, Mode);
1463
1464                 if (!config_mon_rates) {
1465                         if (!Mode->HSync)
1466                                 Mode->HSync = ((float) Mode->Clock ) / ((float) Mode->HTotal);
1467                         if (!Mode->VRefresh)
1468                                 Mode->VRefresh = (1000.0 * ((float) Mode->Clock)) /
1469                                                         ((float) (Mode->HTotal * Mode->VTotal));
1470
1471                         if (Mode->HSync < pScrn->monitor->hsync[0].lo)
1472                                 pScrn->monitor->hsync[0].lo = Mode->HSync;
1473                         if (Mode->HSync > pScrn->monitor->hsync[0].hi)
1474                                 pScrn->monitor->hsync[0].hi = Mode->HSync;
1475                         if (Mode->VRefresh < pScrn->monitor->vrefresh[0].lo)
1476                                 pScrn->monitor->vrefresh[0].lo = Mode->VRefresh;
1477                         if (Mode->VRefresh > pScrn->monitor->vrefresh[0].hi)
1478                                 pScrn->monitor->vrefresh[0].hi = Mode->VRefresh;
1479
1480                         pScrn->monitor->nHsync = 1;
1481                         pScrn->monitor->nVrefresh = 1;
1482                 }
1483         }
1484 #endif
1485
1486         if (pNv->randr12_enable) {
1487                 pScrn->displayWidth = nv_pitch_align(pNv, pScrn->virtualX, pScrn->depth);
1488         } else {
1489                 /*
1490                  * xf86ValidateModes will check that the mode HTotal and VTotal values
1491                  * don't exceed the chipset's limit if pScrn->maxHValue and
1492                  * pScrn->maxVValue are set.  Since our NVValidMode() already takes
1493                  * care of this, we don't worry about setting them here.
1494                  */
1495                 i = xf86ValidateModes(pScrn, pScrn->monitor->Modes,
1496                                         pScrn->display->modes, clockRanges,
1497                                         NULL, 256, max_width,
1498                                         512, 128, max_height,
1499                                         pScrn->display->virtualX,
1500                                         pScrn->display->virtualY,
1501                                         pNv->VRAMPhysicalSize / 2,
1502                                         LOOKUP_BEST_REFRESH);
1503
1504                 if (i == -1) {
1505                         NVPreInitFail("\n");
1506                 }
1507
1508                 /* Prune the modes marked as invalid */
1509                 xf86PruneDriverModes(pScrn);
1510
1511                 /*
1512                  * Set the CRTC parameters for all of the modes based on the type
1513                  * of mode, and the chipset's interlace requirements.
1514                  *
1515                  * Calling this is required if the mode->Crtc* values are used by the
1516                  * driver and if the driver doesn't provide code to set them.  They
1517                  * are not pre-initialised at all.
1518                  */
1519                 xf86SetCrtcForModes(pScrn, 0);
1520
1521                 if (pScrn->modes == NULL)
1522                         NVPreInitFail("No valid modes found\n");
1523         }
1524
1525         /* Set the current mode to the first in the list */
1526         pScrn->currentMode = pScrn->modes;
1527
1528         /* Print the list of modes being used */
1529         xf86PrintModes(pScrn);
1530
1531         /* Set display resolution */
1532         xf86SetDpi(pScrn, 0, 0);
1533
1534         /*
1535          * XXX This should be taken into account in some way in the mode valdation
1536          * section.
1537          */
1538
1539         if (xf86LoadSubModule(pScrn, "fb") == NULL)
1540                 NVPreInitFail("\n");
1541
1542         xf86LoaderReqSymLists(fbSymbols, NULL);
1543
1544         /* Load EXA if needed */
1545         if (!pNv->NoAccel) {
1546                 if (!xf86LoadSubModule(pScrn, "exa")) {
1547                         NVPreInitFail("\n");
1548                 }
1549                 xf86LoaderReqSymLists(exaSymbols, NULL);
1550         }
1551
1552         /* Load ramdac if needed */
1553         if (pNv->HWCursor) {
1554                 if (!xf86LoadSubModule(pScrn, "ramdac")) {
1555                         NVPreInitFail("\n");
1556                 }
1557                 xf86LoaderReqSymLists(ramdacSymbols, NULL);
1558         }
1559
1560         /* Load shadowfb if needed */
1561         if (pNv->ShadowFB) {
1562                 if (!xf86LoadSubModule(pScrn, "shadowfb")) {
1563                         NVPreInitFail("\n");
1564                 }
1565                 xf86LoaderReqSymLists(shadowSymbols, NULL);
1566         }
1567
1568         return TRUE;
1569 }
1570
1571
1572 /*
1573  * Map the framebuffer and MMIO memory.
1574  */
1575
1576 static Bool
1577 NVMapMem(ScrnInfoPtr pScrn)
1578 {
1579         NVPtr pNv = NVPTR(pScrn);
1580         int gart_scratch_size;
1581         uint64_t res;
1582
1583         nouveau_device_get_param(pNv->dev, NOUVEAU_GETPARAM_FB_SIZE, &res);
1584         pNv->VRAMSize=res;
1585         nouveau_device_get_param(pNv->dev, NOUVEAU_GETPARAM_FB_PHYSICAL, &res);
1586         pNv->VRAMPhysical=res;
1587         nouveau_device_get_param(pNv->dev, NOUVEAU_GETPARAM_AGP_SIZE, &res);
1588         pNv->AGPSize=res;
1589
1590 #if !NOUVEAU_EXA_PIXMAPS
1591         if (nouveau_bo_new(pNv->dev, NOUVEAU_BO_VRAM | NOUVEAU_BO_PIN,
1592                 0, pNv->VRAMPhysicalSize / 2, &pNv->FB)) {
1593                         xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Failed to allocate memory for framebuffer!\n");
1594                         return FALSE;
1595         }
1596         xf86DrvMsg(pScrn->scrnIndex, X_INFO,
1597                 "Allocated %dMiB VRAM for framebuffer + offscreen pixmaps, at offset 0x%X\n",
1598                 (uint32_t)(pNv->FB->size >> 20), (uint32_t) pNv->FB->offset);
1599 #ifdef XF86DRM_MODE
1600         if (pNv->kms_enable)
1601                 drmmode_set_fb(pScrn, pNv->drmmode, pScrn->virtualX, pScrn->virtualY, pScrn->displayWidth*(pScrn->bitsPerPixel >> 3), pNv->FB);
1602 #endif
1603 #endif
1604
1605         if (pNv->AGPSize) {
1606                 xf86DrvMsg(pScrn->scrnIndex, X_INFO,
1607                            "AGPGART: %dMiB available\n",
1608                            (unsigned int)(pNv->AGPSize >> 20));
1609                 if (pNv->AGPSize > (16*1024*1024))
1610                         gart_scratch_size = 16*1024*1024;
1611                 else
1612                         /* always leave 512kb for other things like the fifos */
1613                         gart_scratch_size = pNv->AGPSize - 512*1024;
1614         } else {
1615                 gart_scratch_size = (4 << 20) - (1 << 18) ;
1616                 xf86DrvMsg(pScrn->scrnIndex, X_INFO,
1617                            "GART: PCI DMA - using %dKiB\n",
1618                            gart_scratch_size >> 10);
1619         }
1620
1621         if (nouveau_bo_new(pNv->dev, NOUVEAU_BO_GART | NOUVEAU_BO_PIN, 0,
1622                            gart_scratch_size, &pNv->GART)) {
1623                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1624                            "Unable to allocate GART memory\n");
1625         }
1626         if (pNv->GART) {
1627                 xf86DrvMsg(pScrn->scrnIndex, X_INFO,
1628                            "GART: Allocated %dMiB as a scratch buffer\n",
1629                            (unsigned int)(pNv->GART->size >> 20));
1630         }
1631
1632         if (nouveau_bo_new(pNv->dev, NOUVEAU_BO_VRAM | NOUVEAU_BO_PIN, 0,
1633                            64 * 1024, &pNv->Cursor)) {
1634                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1635                            "Failed to allocate memory for hardware cursor\n");
1636                 return FALSE;
1637         }
1638
1639         if (pNv->randr12_enable) {
1640                 if (nouveau_bo_new(pNv->dev, NOUVEAU_BO_VRAM | NOUVEAU_BO_PIN, 0,
1641                         64 * 1024, &pNv->Cursor2)) {
1642                         xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1643                                 "Failed to allocate memory for hardware cursor\n");
1644                         return FALSE;
1645                 }
1646         }
1647
1648         if (pNv->Architecture >= NV_ARCH_50) {
1649                 /* Both CRTC's have a CLUT. */
1650                 if (nouveau_bo_new(pNv->dev, NOUVEAU_BO_VRAM | NOUVEAU_BO_PIN,
1651                                    0, 0x1000, &pNv->CLUT0)) {
1652                         xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1653                                    "Failed to allocate memory for CLUT0\n");
1654                         return FALSE;
1655                 }
1656
1657                 if (nouveau_bo_new(pNv->dev, NOUVEAU_BO_VRAM | NOUVEAU_BO_PIN,
1658                                    0, 0x1000, &pNv->CLUT1)) {
1659                         xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1660                                    "Failed to allocate memory for CLUT1\n");
1661                         return FALSE;
1662                 }
1663         }
1664
1665         if ((pNv->FB && nouveau_bo_map(pNv->FB, NOUVEAU_BO_RDWR)) ||
1666             (pNv->GART && nouveau_bo_map(pNv->GART, NOUVEAU_BO_RDWR)) ||
1667             (pNv->CLUT0 && nouveau_bo_map(pNv->CLUT0, NOUVEAU_BO_RDWR)) ||
1668             (pNv->CLUT1 && nouveau_bo_map(pNv->CLUT1, NOUVEAU_BO_RDWR)) ||
1669             nouveau_bo_map(pNv->Cursor, NOUVEAU_BO_RDWR) ||
1670             (pNv->randr12_enable && nouveau_bo_map(pNv->Cursor2, NOUVEAU_BO_RDWR))) {
1671                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1672                            "Failed to map pinned buffers\n");
1673                 return FALSE;
1674         }
1675
1676         return TRUE;
1677 }
1678
1679 /*
1680  * Unmap the framebuffer and MMIO memory.
1681  */
1682
1683 static Bool
1684 NVUnmapMem(ScrnInfoPtr pScrn)
1685 {
1686         NVPtr pNv = NVPTR(pScrn);
1687
1688         nouveau_bo_del(&pNv->FB);
1689         nouveau_bo_del(&pNv->GART);
1690         nouveau_bo_del(&pNv->Cursor);
1691         if (pNv->randr12_enable) {
1692                 nouveau_bo_del(&pNv->Cursor2);
1693         }
1694         nouveau_bo_del(&pNv->CLUT0);
1695         nouveau_bo_del(&pNv->CLUT1);
1696
1697         return TRUE;
1698 }
1699
1700
1701 /*
1702  * Initialise a new mode. 
1703  */
1704
1705 static Bool
1706 NVModeInit(ScrnInfoPtr pScrn, DisplayModePtr mode)
1707 {
1708     vgaHWPtr hwp = VGAHWPTR(pScrn);
1709     vgaRegPtr vgaReg;
1710     NVPtr pNv = NVPTR(pScrn);
1711     NVRegPtr nvReg;
1712
1713     /* Initialise the ModeReg values */
1714     if (!vgaHWInit(pScrn, mode))
1715         return FALSE;
1716     pScrn->vtSema = TRUE;
1717
1718     vgaReg = &hwp->ModeReg;
1719     nvReg = &pNv->ModeReg;
1720
1721     if(!NVDACInit(pScrn, mode))
1722         return FALSE;
1723
1724     NVLockUnlock(pScrn, 0);
1725     if(pNv->twoHeads) {
1726         nvWriteCurVGA(pNv, NV_VGA_CRTCX_OWNER, nvReg->crtcOwner);
1727         NVLockUnlock(pScrn, 0);
1728     }
1729
1730     /* Program the registers */
1731     vgaHWProtect(pScrn, TRUE);
1732
1733     NVDACRestore(pScrn, vgaReg, nvReg, FALSE);
1734
1735 #if X_BYTE_ORDER == X_BIG_ENDIAN
1736     /* turn on LFB swapping */
1737     {
1738         unsigned char tmp;
1739
1740         tmp = nvReadCurVGA(pNv, NV_VGA_CRTCX_SWAPPING);
1741         tmp |= (1 << 7);
1742         nvWriteCurVGA(pNv, NV_VGA_CRTCX_SWAPPING, tmp);
1743     }
1744 #endif
1745
1746     if (!pNv->NoAccel)
1747                 NVAccelCommonInit(pScrn);
1748
1749     vgaHWProtect(pScrn, FALSE);
1750
1751     pScrn->currentMode = mode;
1752
1753     return TRUE;
1754 }
1755
1756 /*
1757  * Restore the initial (text) mode.
1758  */
1759 static void 
1760 NVRestore(ScrnInfoPtr pScrn)
1761 {
1762         NVPtr pNv = NVPTR(pScrn);
1763
1764         if (pNv->randr12_enable) {
1765                 xf86CrtcConfigPtr xf86_config = XF86_CRTC_CONFIG_PTR(pScrn);
1766                 int i;
1767
1768                 for (i = 0; i < xf86_config->num_crtc; i++)
1769                         NVCrtcLockUnlock(xf86_config->crtc[i], 0);
1770
1771                 for (i = 0; i < pNv->dcb_table.entries; i++)
1772                         nv_encoder_restore(pScrn, &pNv->encoders[i]);
1773
1774                 for (i = 0; i < xf86_config->num_crtc; i++)
1775                         xf86_config->crtc[i]->funcs->restore(xf86_config->crtc[i]);
1776
1777                 nv_save_restore_vga_fonts(pScrn, 0);
1778
1779                 for (i = 0; i < xf86_config->num_crtc; i++)
1780                         NVCrtcLockUnlock(xf86_config->crtc[i], 1);
1781         } else {
1782                 vgaHWPtr hwp = VGAHWPTR(pScrn);
1783                 vgaRegPtr vgaReg = &hwp->SavedReg;
1784                 NVRegPtr nvReg = &pNv->SavedReg;
1785
1786                 NVLockUnlock(pScrn, 0);
1787
1788                 if(pNv->twoHeads) {
1789                         nvWriteCurVGA(pNv, NV_VGA_CRTCX_OWNER, pNv->crtc_active[1] * 0x3);
1790                         NVLockUnlock(pScrn, 0);
1791                 }
1792
1793                 /* Only restore text mode fonts/text for the primary card */
1794                 vgaHWProtect(pScrn, TRUE);
1795                 NVDACRestore(pScrn, vgaReg, nvReg, pNv->Primary);
1796                 vgaHWProtect(pScrn, FALSE);
1797         }
1798
1799         if (pNv->twoHeads) {
1800                 NVSetOwner(pScrn, 0);   /* move to head A to set owner */
1801                 NVLockVgaCrtc(pNv, 0, false);
1802                 xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Restoring CRTC_OWNER to %d.\n", pNv->vtOWNER);
1803                 NVWriteVgaCrtc(pNv, 0, NV_VGA_CRTCX_OWNER, pNv->vtOWNER);
1804                 NVLockVgaCrtc(pNv, 0, true);
1805         }
1806 }
1807
1808 static void
1809 NVLoadPalette(ScrnInfoPtr pScrn, int numColors, int *indices,
1810               LOCO * colors, VisualPtr pVisual)
1811 {
1812         xf86CrtcConfigPtr xf86_config = XF86_CRTC_CONFIG_PTR(pScrn);
1813         int c;
1814         int i, j, index;
1815         CARD16 lut_r[256], lut_g[256], lut_b[256];
1816
1817         for (c = 0; c < xf86_config->num_crtc; c++) {
1818                 xf86CrtcPtr crtc = xf86_config->crtc[c];
1819
1820                 /* code borrowed from intel driver */
1821                 switch (pScrn->depth) {
1822                 case 15:
1823                         for (i = 0; i < numColors; i++) {
1824                                 index = indices[i];
1825                                 for (j = 0; j < 8; j++) {
1826                                         lut_r[index * 8 + j] = colors[index].red << 8;
1827                                         lut_g[index * 8 + j] = colors[index].green << 8;
1828                                         lut_b[index * 8 + j] = colors[index].blue << 8;
1829                                 }
1830                         }
1831                 case 16:
1832                         for (i = 0; i < numColors; i++) {
1833                                 index = indices[i];
1834
1835                                 if (i <= 31) {
1836                                         for (j = 0; j < 8; j++) {
1837                                                 lut_r[index * 8 + j] = colors[index].red << 8;
1838                                                 lut_b[index * 8 + j] = colors[index].blue << 8;
1839                                         }
1840                                 }
1841
1842                                 for (j = 0; j < 4; j++) {
1843                                         lut_g[index * 4 + j] = colors[index].green << 8;
1844                                 }
1845                         }
1846                 default:
1847                         for (i = 0; i < numColors; i++) {
1848                                 index = indices[i];
1849                                 lut_r[index] = colors[index].red << 8;
1850                                 lut_g[index] = colors[index].green << 8;
1851                                 lut_b[index] = colors[index].blue << 8;
1852                         }
1853                         break;
1854                 }
1855
1856                 /* Make the change through RandR */
1857                 RRCrtcGammaSet(crtc->randr_crtc, lut_r, lut_g, lut_b);
1858         }
1859 }
1860
1861 static void NVBacklightEnable(NVPtr pNv,  Bool on)
1862 {
1863     /* This is done differently on each laptop.  Here we
1864        define the ones we know for sure. */
1865
1866 #if defined(__powerpc__)
1867     if((pNv->Chipset & 0xffff == 0x0179) ||
1868        (pNv->Chipset & 0xffff == 0x0189) ||
1869        (pNv->Chipset & 0xffff == 0x0329))
1870     {
1871        /* NV17,18,34 Apple iMac, iBook, PowerBook */
1872       CARD32 tmp_pmc, tmp_pcrt;
1873       tmp_pmc = nvReadMC(pNv, NV_PBUS_DEBUG_DUALHEAD_CTL) & 0x7FFFFFFF;
1874       tmp_pcrt = NVReadCRTC(pNv, 0, NV_CRTC_GPIO_EXT) & 0xFFFFFFFC;
1875       if(on) {
1876           tmp_pmc |= (1 << 31);
1877           tmp_pcrt |= 0x1;
1878       }
1879       nvWriteMC(pNv, NV_PBUS_DEBUG_DUALHEAD_CTL, tmp_pmc);
1880       NVWriteCRTC(pNv, 0, NV_CRTC_GPIO_EXT, tmp_pcrt);
1881     }
1882 #endif
1883     
1884     if(pNv->LVDS) {
1885        if(pNv->twoHeads && ((pNv->Chipset & 0x0ff0) != CHIPSET_NV11)) {
1886            nvWriteMC(pNv, 0x130C, on ? 3 : 7);
1887        }
1888     } else {
1889        CARD32 fpcontrol;
1890
1891        fpcontrol = nvReadCurRAMDAC(pNv, NV_RAMDAC_FP_CONTROL) & 0xCfffffCC;
1892
1893        /* cut the TMDS output */
1894        if(on) fpcontrol |= pNv->fpSyncs;
1895        else fpcontrol |= 0x20000022;
1896
1897        nvWriteCurRAMDAC(pNv, NV_RAMDAC_FP_CONTROL, fpcontrol);
1898     }
1899 }
1900
1901 static void
1902 NVDPMSSetLCD(ScrnInfoPtr pScrn, int PowerManagementMode, int flags)
1903 {
1904   NVPtr pNv = NVPTR(pScrn);
1905
1906   if (!pScrn->vtSema) return;
1907
1908   vgaHWDPMSSet(pScrn, PowerManagementMode, flags);
1909
1910   switch (PowerManagementMode) {
1911   case DPMSModeStandby:  /* HSync: Off, VSync: On */
1912   case DPMSModeSuspend:  /* HSync: On, VSync: Off */
1913   case DPMSModeOff:      /* HSync: Off, VSync: Off */
1914     NVBacklightEnable(pNv, 0);
1915     break;
1916   case DPMSModeOn:       /* HSync: On, VSync: On */
1917     NVBacklightEnable(pNv, 1);
1918   default:
1919     break;
1920   }
1921 }
1922
1923
1924 static void
1925 NVDPMSSet(ScrnInfoPtr pScrn, int PowerManagementMode, int flags)
1926 {
1927   unsigned char crtc1A;
1928   vgaHWPtr hwp = VGAHWPTR(pScrn);
1929
1930   if (!pScrn->vtSema) return;
1931
1932   crtc1A = hwp->readCrtc(hwp, 0x1A) & ~0xC0;
1933
1934   switch (PowerManagementMode) {
1935   case DPMSModeStandby:  /* HSync: Off, VSync: On */
1936     crtc1A |= 0x80;
1937     break;
1938   case DPMSModeSuspend:  /* HSync: On, VSync: Off */
1939     crtc1A |= 0x40;
1940     break;
1941   case DPMSModeOff:      /* HSync: Off, VSync: Off */
1942     crtc1A |= 0xC0;
1943     break;
1944   case DPMSModeOn:       /* HSync: On, VSync: On */
1945   default:
1946     break;
1947   }
1948
1949   /* vgaHWDPMSSet will merely cut the dac output */
1950   vgaHWDPMSSet(pScrn, PowerManagementMode, flags);
1951
1952   hwp->writeCrtc(hwp, 0x1A, crtc1A);
1953 }
1954
1955
1956 /* Mandatory */
1957
1958 /* This gets called at the start of each server generation */
1959
1960 static Bool
1961 NVScreenInit(int scrnIndex, ScreenPtr pScreen, int argc, char **argv)
1962 {
1963         ScrnInfoPtr pScrn;
1964         vgaHWPtr hwp;
1965         NVPtr pNv;
1966         int ret;
1967         VisualPtr visual;
1968         unsigned char *FBStart;
1969         int displayWidth;
1970
1971         /* 
1972          * First get the ScrnInfoRec
1973          */
1974         pScrn = xf86Screens[pScreen->myNum];
1975
1976         hwp = VGAHWPTR(pScrn);
1977         pNv = NVPTR(pScrn);
1978
1979         /* Map the VGA memory when the primary video */
1980         if (pNv->Primary) {
1981                 hwp->MapSize = 0x10000;
1982                 if (!vgaHWMapMem(pScrn))
1983                         return FALSE;
1984         }
1985
1986         /* First init DRI/DRM */
1987         if (!NVDRIScreenInit(pScrn))
1988                 return FALSE;
1989
1990         /* Allocate and map memory areas we need */
1991         if (!NVMapMem(pScrn))
1992                 return FALSE;
1993
1994         if (!pNv->NoAccel) {
1995                 /* Init DRM - Alloc FIFO */
1996                 if (!NVInitDma(pScrn))
1997                         return FALSE;
1998
1999                 /* setup graphics objects */
2000                 if (!NVAccelCommonInit(pScrn))
2001                         return FALSE;
2002         }
2003
2004 #if NOUVEAU_EXA_PIXMAPS
2005         if (nouveau_bo_new(pNv->dev, NOUVEAU_BO_VRAM | NOUVEAU_BO_PIN,
2006                         0, NOUVEAU_ALIGN(pScrn->virtualX, 64) * NOUVEAU_ALIGN(pScrn->virtualY, 64) *
2007                         (pScrn->bitsPerPixel >> 3), &pNv->FB)) {
2008                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Failed to allocate memory for screen pixmap.\n");
2009                 return FALSE;
2010         }
2011 #endif
2012
2013         if (!pNv->randr12_enable) {
2014                 /* Save the current state */
2015                 NVSave(pScrn);
2016                 /* Initialise the first mode */
2017                 if (!NVModeInit(pScrn, pScrn->currentMode))
2018                         return FALSE;
2019
2020                 /* Darken the screen for aesthetic reasons and set the viewport */
2021                 NVSaveScreen(pScreen, SCREEN_SAVER_ON);
2022                 pScrn->AdjustFrame(scrnIndex, pScrn->frameX0, pScrn->frameY0, 0);
2023         } else {
2024                 pScrn->memPhysBase = pNv->VRAMPhysical;
2025                 pScrn->fbOffset = 0;
2026
2027                 if (!NVEnterVT(scrnIndex, 0))
2028                         return FALSE;
2029                 NVSaveScreen(pScreen, SCREEN_SAVER_ON);
2030         }
2031
2032
2033         /*
2034          * The next step is to setup the screen's visuals, and initialise the
2035          * framebuffer code.  In cases where the framebuffer's default
2036          * choices for things like visual layouts and bits per RGB are OK,
2037          * this may be as simple as calling the framebuffer's ScreenInit()
2038          * function.  If not, the visuals will need to be setup before calling
2039          * a fb ScreenInit() function and fixed up after.
2040          *
2041          * For most PC hardware at depths >= 8, the defaults that fb uses
2042          * are not appropriate.  In this driver, we fixup the visuals after.
2043          */
2044
2045         /*
2046          * Reset the visual list.
2047          */
2048         miClearVisualTypes();
2049
2050         /* Setup the visuals we support. */
2051
2052         if (!miSetVisualTypes(pScrn->depth, 
2053                                 miGetDefaultVisualMask(pScrn->depth), 8,
2054                                 pScrn->defaultVisual))
2055                 return FALSE;
2056         if (!miSetPixmapDepths ())
2057                 return FALSE;
2058
2059         /*
2060          * Call the framebuffer layer's ScreenInit function, and fill in other
2061          * pScreen fields.
2062          */
2063
2064         if (pNv->ShadowFB) {
2065                 pNv->ShadowPitch = BitmapBytePad(pScrn->bitsPerPixel * pScrn->virtualX);
2066                 pNv->ShadowPtr = xalloc(pNv->ShadowPitch * pScrn->virtualY);
2067                 displayWidth = pNv->ShadowPitch / (pScrn->bitsPerPixel >> 3);
2068                 FBStart = pNv->ShadowPtr;
2069         } else {
2070                 pNv->ShadowPtr = NULL;
2071                 displayWidth = pScrn->displayWidth;
2072                 FBStart = pNv->FB->map;
2073         }
2074
2075         switch (pScrn->bitsPerPixel) {
2076                 case 16:
2077                 case 32:
2078                         ret = fbScreenInit(pScreen, FBStart, pScrn->virtualX, pScrn->virtualY,
2079                                 pScrn->xDpi, pScrn->yDpi,
2080                                 displayWidth, pScrn->bitsPerPixel);
2081                         break;
2082                 default:
2083                         xf86DrvMsg(scrnIndex, X_ERROR,
2084                                 "Internal error: invalid bpp (%d) in NVScreenInit\n",
2085                                 pScrn->bitsPerPixel);
2086                         ret = FALSE;
2087                         break;
2088         }
2089         if (!ret)
2090                 return FALSE;
2091
2092         /* Fixup RGB ordering */
2093         visual = pScreen->visuals + pScreen->numVisuals;
2094         while (--visual >= pScreen->visuals) {
2095                 if ((visual->class | DynamicClass) == DirectColor) {
2096                         visual->offsetRed = pScrn->offset.red;
2097                         visual->offsetGreen = pScrn->offset.green;
2098                         visual->offsetBlue = pScrn->offset.blue;
2099                         visual->redMask = pScrn->mask.red;
2100                         visual->greenMask = pScrn->mask.green;
2101                         visual->blueMask = pScrn->mask.blue;
2102                 }
2103         }
2104
2105         fbPictureInit (pScreen, 0, 0);
2106
2107         xf86SetBlackWhitePixels(pScreen);
2108
2109         if (!pNv->NoAccel) {
2110                 if (!NVExaInit(pScreen))
2111                         return FALSE;
2112                 NVAccelCommonInit(pScrn);
2113         } else if (pNv->VRAMPhysicalSize / 2 < NOUVEAU_ALIGN(pScrn->virtualX, 64) * NOUVEAU_ALIGN(pScrn->virtualY, 64) * (pScrn->bitsPerPixel >> 3)) {
2114                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "The virtual screen size's resolution is too big for the video RAM framebuffer at this colour depth.\n");
2115                 return FALSE;
2116         }
2117
2118
2119         miInitializeBackingStore(pScreen);
2120         xf86SetBackingStore(pScreen);
2121         xf86SetSilkenMouse(pScreen);
2122
2123         /* Finish DRI init */
2124         NVDRIFinishScreenInit(pScrn);
2125
2126         /* 
2127          * Initialize software cursor.
2128          * Must precede creation of the default colormap.
2129          */
2130         miDCInitialize(pScreen, xf86GetPointerScreenFuncs());
2131
2132         /*
2133          * Initialize HW cursor layer. 
2134          * Must follow software cursor initialization.
2135          */
2136         if (pNv->HWCursor) { 
2137                 if (pNv->Architecture < NV_ARCH_50 && !pNv->randr12_enable)
2138                         ret = NVCursorInit(pScreen);
2139                 else if (pNv->Architecture < NV_ARCH_50 && pNv->randr12_enable)
2140                         ret = NVCursorInitRandr12(pScreen);
2141                 else
2142                         ret = NV50CursorInit(pScreen);
2143
2144                 if (ret != TRUE) {
2145                         xf86DrvMsg(pScrn->scrnIndex, X_ERROR, 
2146                                 "Hardware cursor initialization failed\n");
2147                         pNv->HWCursor = FALSE;
2148                 }
2149         }
2150
2151         if (pNv->randr12_enable) {
2152                 xf86DPMSInit(pScreen, xf86DPMSSet, 0);
2153
2154                 if (!xf86CrtcScreenInit(pScreen))
2155                         return FALSE;
2156         }
2157
2158         /* Initialise default colourmap */
2159         if (!miCreateDefColormap(pScreen))
2160                 return FALSE;
2161
2162         /*
2163          * Initialize colormap layer.
2164          * Must follow initialization of the default colormap 
2165          */
2166         if (!pNv->randr12_enable && !pNv->kms_enable) {
2167                 if(!xf86HandleColormaps(pScreen, 256, 8, NVDACLoadPalette,
2168                                 NULL, CMAP_RELOAD_ON_MODE_SWITCH | CMAP_PALETTED_TRUECOLOR))
2169                         return FALSE;
2170         } else {
2171                 if (!xf86HandleColormaps(pScreen, 256, 8, NVLoadPalette,
2172                                 NULL, CMAP_PALETTED_TRUECOLOR))
2173                         return FALSE;
2174         }
2175
2176         if (pNv->ShadowFB)
2177                 ShadowFBInit(pScreen, NVRefreshArea);
2178
2179         if (!pNv->randr12_enable) {
2180                 if(pNv->FlatPanel) {
2181                         xf86DPMSInit(pScreen, NVDPMSSetLCD, 0);
2182                 } else {
2183                         xf86DPMSInit(pScreen, NVDPMSSet, 0);
2184                 }
2185         }
2186
2187         pScrn->memPhysBase = pNv->VRAMPhysical;
2188         pScrn->fbOffset = 0;
2189
2190         NVInitVideo(pScreen);
2191
2192         pScreen->SaveScreen = NVSaveScreen;
2193
2194         /* Wrap the current CloseScreen function */
2195         pNv->CloseScreen = pScreen->CloseScreen;
2196         pScreen->CloseScreen = NVCloseScreen;
2197
2198         pNv->BlockHandler = pScreen->BlockHandler;
2199         pScreen->BlockHandler = NVBlockHandler;
2200
2201         /* Report any unused options (only for the first generation) */
2202         if (serverGeneration == 1)
2203                 xf86ShowUnusedOptions(pScrn->scrnIndex, pScrn->options);
2204
2205         return TRUE;
2206 }
2207
2208 static Bool
2209 NVSaveScreen(ScreenPtr pScreen, int mode)
2210 {
2211     ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum];
2212     NVPtr pNv = NVPTR(pScrn);
2213     int i;
2214     Bool on = xf86IsUnblank(mode);
2215     
2216     if (pNv->randr12_enable) {
2217         xf86CrtcConfigPtr xf86_config = XF86_CRTC_CONFIG_PTR(pScrn);
2218         if (pScrn->vtSema && pNv->Architecture < NV_ARCH_50) {
2219             for (i = 0; i < xf86_config->num_crtc; i++) {
2220                 
2221                 if (xf86_config->crtc[i]->enabled) {
2222                     struct nouveau_crtc *nv_crtc = to_nouveau_crtc(xf86_config->crtc[i]);
2223                     NVBlankScreen(pScrn, nv_crtc->head, !on);
2224                 }
2225             }
2226             
2227         }
2228         return TRUE;
2229     }
2230
2231         return vgaHWSaveScreen(pScreen, mode);
2232 }
2233
2234 static void
2235 NVSave(ScrnInfoPtr pScrn)
2236 {
2237         NVPtr pNv = NVPTR(pScrn);
2238         NVRegPtr nvReg = &pNv->SavedReg;
2239
2240         if (pNv->randr12_enable) {
2241                 xf86CrtcConfigPtr xf86_config = XF86_CRTC_CONFIG_PTR(pScrn);
2242                 int i;
2243
2244                 nv_save_restore_vga_fonts(pScrn, 1);
2245
2246                 for (i = 0; i < xf86_config->num_crtc; i++)
2247                         xf86_config->crtc[i]->funcs->save(xf86_config->crtc[i]);
2248
2249                 for (i = 0; i < pNv->dcb_table.entries; i++)
2250                         nv_encoder_save(pScrn, &pNv->encoders[i]);
2251         } else {
2252                 vgaHWPtr pVga = VGAHWPTR(pScrn);
2253                 vgaRegPtr vgaReg = &pVga->SavedReg;
2254                 NVLockUnlock(pScrn, 0);
2255                 if (pNv->twoHeads) {
2256                         nvWriteCurVGA(pNv, NV_VGA_CRTCX_OWNER, pNv->crtc_active[1] * 0x3);
2257                         NVLockUnlock(pScrn, 0);
2258                 }
2259
2260                 NVDACSave(pScrn, vgaReg, nvReg, pNv->Primary);
2261         }
2262 }