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