randr12: fix dpms, detect, destroy, save and restore for multiple encoders per connector
[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         if (pNv->pInt10)
834                 xf86FreeInt10(pNv->pInt10);
835
836         NVUnmapMem(pScrn);
837         vgaHWUnmapMem(pScrn);
838         NVDRICloseScreen(pScrn);
839         if (pNv->CursorInfoRec)
840                 xf86DestroyCursorInfoRec(pNv->CursorInfoRec);
841         if (pNv->ShadowPtr) {
842                 xfree(pNv->ShadowPtr);
843                 pNv->ShadowPtr = NULL;
844         }
845         if (pNv->overlayAdaptor) {
846                 xfree(pNv->overlayAdaptor);
847                 pNv->overlayAdaptor = NULL;
848         }
849         if (pNv->blitAdaptor) {
850                 xfree(pNv->blitAdaptor);
851                 pNv->blitAdaptor = NULL;
852         }
853         if (pNv->textureAdaptor[0]) {
854                 xfree(pNv->textureAdaptor[0]);
855                 pNv->textureAdaptor[0] = NULL;
856         }
857         if (pNv->textureAdaptor[1]) {
858                 xfree(pNv->textureAdaptor[1]);
859                 pNv->textureAdaptor[1] = NULL;
860         }
861         if (pNv->EXADriverPtr) {
862                 exaDriverFini(pScreen);
863                 xfree(pNv->EXADriverPtr);
864                 pNv->EXADriverPtr = NULL;
865         }
866
867         pScrn->vtSema = FALSE;
868         pScreen->CloseScreen = pNv->CloseScreen;
869         pScreen->BlockHandler = pNv->BlockHandler;
870         return (*pScreen->CloseScreen)(scrnIndex, pScreen);
871 }
872
873 /* Free up any persistent data structures */
874
875 /* Optional */
876 static void
877 NVFreeScreen(int scrnIndex, int flags)
878 {
879         /*
880          * This only gets called when a screen is being deleted.  It does not
881          * get called routinely at the end of a server generation.
882         */
883         if (xf86LoaderCheckSymbol("vgaHWFreeHWRec"))
884                 vgaHWFreeHWRec(xf86Screens[scrnIndex]);
885         NVFreeRec(xf86Screens[scrnIndex]);
886 }
887
888
889 /* Checks if a mode is suitable for the selected chipset. */
890
891 /* Optional */
892 static ModeStatus
893 NVValidMode(int scrnIndex, DisplayModePtr mode, Bool verbose, int flags)
894 {
895     NVPtr pNv = NVPTR(xf86Screens[scrnIndex]);
896
897     if(pNv->fpWidth && pNv->fpHeight)
898       if((pNv->fpWidth < mode->HDisplay) || (pNv->fpHeight < mode->VDisplay))
899         return (MODE_PANEL);
900
901     return (MODE_OK);
902 }
903
904 Bool NVI2CInit(ScrnInfoPtr pScrn)
905 {
906         NVPtr pNv = NVPTR(pScrn);
907
908         if (xf86LoadSubModule(pScrn, "i2c") && xf86LoadSubModule(pScrn, "ddc")) {
909                 xf86LoaderReqSymLists(i2cSymbols,NULL);
910                 xf86LoaderReqSymLists(ddcSymbols, NULL);
911
912                 /* randr-1.2 clients have their DDCs initialized elsewhere */
913                 if (!pNv->randr12_enable)
914                         return NVDACi2cInit(pScrn);
915                 return true;
916         } else
917                 xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
918                 "Couldn't load i2c and ddc modules.  DDC probing can't be done\n");
919         return false;
920 }
921
922 #ifdef XF86DRM_MODE
923 static bool nouveau_kernel_modesetting_enabled(ScrnInfoPtr pScrn)
924 {
925 #if XSERVER_LIBPCIACCESS
926         struct pci_device *PciInfo;
927 #else
928         pciVideoPtr PciInfo;
929 #endif
930         EntityInfoPtr pEnt;
931         char *busIdString;
932         int ret;
933
934         pEnt = xf86GetEntityInfo(pScrn->entityList[0]);
935         PciInfo = xf86GetPciInfoForEntity(pEnt->index);
936
937         busIdString = DRICreatePCIBusID(PciInfo);
938
939         ret = drmCheckModesettingSupported(busIdString);
940         xfree(busIdString);
941         if (ret)
942                 return FALSE;
943
944         return TRUE;
945 }
946 #else
947 #define nouveau_kernel_modesetting_enabled(x) FALSE
948 #endif
949
950 static Bool NVPreInitDRI(ScrnInfoPtr pScrn)
951 {
952         NVPtr pNv = NVPTR(pScrn);
953
954         if (!NVDRIGetVersion(pScrn))
955                 return FALSE;
956
957         xf86DrvMsg(pScrn->scrnIndex, X_INFO,
958                 "[dri] Found DRI library version %d.%d.%d and kernel"
959                 " module version %d.%d.%d\n",
960                 pNv->pLibDRMVersion->version_major,
961                 pNv->pLibDRMVersion->version_minor,
962                 pNv->pLibDRMVersion->version_patchlevel,
963                 pNv->pKernelDRMVersion->version_major,
964                 pNv->pKernelDRMVersion->version_minor,
965                 pNv->pKernelDRMVersion->version_patchlevel);
966
967         return TRUE;
968 }
969
970 static Bool
971 nv_xf86crtc_resize(ScrnInfoPtr pScrn, int width, int height)
972 {
973         xf86DrvMsg(pScrn->scrnIndex, X_INFO, "nv_xf86crtc_resize is called with %dx%d resolution.\n", width, height);
974         pScrn->virtualX = width;
975         pScrn->virtualY = height;
976         return TRUE;
977 }
978
979 static const xf86CrtcConfigFuncsRec nv_xf86crtc_config_funcs = {
980         nv_xf86crtc_resize
981 };
982
983 #define NVPreInitFail(fmt, args...) do {                                    \
984         xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "%d: "fmt, __LINE__, ##args); \
985         if (pNv->pInt10)                                                    \
986                 xf86FreeInt10(pNv->pInt10);                                 \
987         NVFreeRec(pScrn);                                                   \
988         return FALSE;                                                       \
989 } while(0)
990
991 /* Mandatory */
992 Bool
993 NVPreInit(ScrnInfoPtr pScrn, int flags)
994 {
995         NVPtr pNv;
996         MessageType from;
997         int i, max_width, max_height;
998         ClockRangePtr clockRanges;
999         int config_mon_rates = FALSE;
1000
1001         if (flags & PROBE_DETECT) {
1002                 EntityInfoPtr pEnt = xf86GetEntityInfo(pScrn->entityList[0]);
1003
1004                 if (!pEnt)
1005                         return FALSE;
1006
1007                 i = pEnt->index;
1008                 xfree(pEnt);
1009
1010                 if (xf86LoadSubModule(pScrn, "vbe")) {
1011                         vbeInfoPtr pVbe = VBEInit(NULL, i);
1012                         ConfiguredMonitor = vbeDoEDID(pVbe, NULL);
1013                         vbeFree(pVbe);
1014                 }
1015
1016                 return TRUE;
1017         }
1018
1019         /*
1020          * Note: This function is only called once at server startup, and
1021          * not at the start of each server generation.  This means that
1022          * only things that are persistent across server generations can
1023          * be initialised here.  xf86Screens[] is (pScrn is a pointer to one
1024          * of these).  Privates allocated using xf86AllocateScrnInfoPrivateIndex()  
1025          * are too, and should be used for data that must persist across
1026          * server generations.
1027          *
1028          * Per-generation data should be allocated with
1029          * AllocateScreenPrivateIndex() from the ScreenInit() function.
1030          */
1031
1032         /* Check the number of entities, and fail if it isn't one. */
1033         if (pScrn->numEntities != 1)
1034                 return FALSE;
1035
1036         /* Allocate the NVRec driverPrivate */
1037         if (!NVGetRec(pScrn)) {
1038                 return FALSE;
1039         }
1040         pNv = NVPTR(pScrn);
1041
1042         /* Get the entity, and make sure it is PCI. */
1043         pNv->pEnt = xf86GetEntityInfo(pScrn->entityList[0]);
1044         if (pNv->pEnt->location.type != BUS_PCI)
1045                 return FALSE;
1046  
1047         /* Find the PCI info for this screen */
1048         pNv->PciInfo = xf86GetPciInfoForEntity(pNv->pEnt->index);
1049 #ifndef XSERVER_LIBPCIACCESS
1050         pNv->PciTag = pciTag(pNv->PciInfo->bus, pNv->PciInfo->device,
1051                                 pNv->PciInfo->func);
1052 #endif /* XSERVER_LIBPCIACCESS */
1053
1054         pNv->Primary = xf86IsPrimaryPci(pNv->PciInfo);
1055
1056         volatile uint32_t *regs = NULL;
1057 #ifdef XSERVER_LIBPCIACCESS
1058         pci_device_map_range(pNv->PciInfo, PCI_DEV_MEM_BASE(pNv->PciInfo, 0),
1059                              0x90000, 0, (void *)&regs);
1060         pNv->Chipset = NVGetPCIID(regs) & 0xffff;
1061         pNv->NVArch = NVGetArchitecture(regs);
1062         pci_device_unmap_range(pNv->PciInfo, (void *) regs, 0x90000);
1063 #else
1064         CARD32 pcicmd;
1065         PCI_DEV_READ_LONG(pNv->PciInfo, PCI_CMD_STAT_REG, &pcicmd);
1066         /* Enable reading memory? */
1067         PCI_DEV_WRITE_LONG(pNv->PciInfo, PCI_CMD_STAT_REG, pcicmd | PCI_CMD_MEM_ENABLE);
1068         regs = xf86MapPciMem(-1, VIDMEM_MMIO, pNv->PciTag, PCI_DEV_MEM_BASE(pNv->PciInfo, 0), 0x90000);
1069         pNv->Chipset = NVGetPCIID(regs) & 0xffff;
1070         pNv->NVArch = NVGetArchitecture(regs);
1071         xf86UnMapVidMem(-1, (pointer)regs, 0x90000);
1072         /* Reset previous state */
1073         PCI_DEV_WRITE_LONG(pNv->PciInfo, PCI_CMD_STAT_REG, pcicmd);
1074 #endif /* XSERVER_LIBPCIACCESS */
1075
1076         pScrn->chipset = malloc(sizeof(char) * 25);
1077         sprintf(pScrn->chipset, "NVIDIA NV%02X", pNv->NVArch);
1078
1079         if(!pScrn->chipset) {
1080                 pScrn->chipset = "Unknown NVIDIA";
1081         }
1082
1083         /*
1084         * This shouldn't happen because such problems should be caught in
1085         * NVProbe(), but check it just in case.
1086         */
1087         if (pScrn->chipset == NULL)
1088                 NVPreInitFail("ChipID 0x%04X is not recognised\n", pNv->Chipset);
1089
1090         if (pNv->NVArch < 0x04)
1091                 NVPreInitFail("Chipset \"%s\" is not recognised\n", pScrn->chipset);
1092
1093         xf86DrvMsg(pScrn->scrnIndex, X_PROBED, "Chipset: \"%s\"\n", pScrn->chipset);
1094
1095         /* The highest architecture currently supported is NV5x */
1096         if (pNv->NVArch >= 0x80) {
1097                 pNv->Architecture =  NV_ARCH_50;
1098         } else if (pNv->NVArch >= 0x60) {
1099                 pNv->Architecture =  NV_ARCH_40;
1100         } else if (pNv->NVArch >= 0x50) {
1101                 pNv->Architecture =  NV_ARCH_50;
1102         } else if (pNv->NVArch >= 0x40) {
1103                 pNv->Architecture =  NV_ARCH_40;
1104         } else if (pNv->NVArch >= 0x30) {
1105                 pNv->Architecture = NV_ARCH_30;
1106         } else if (pNv->NVArch >= 0x20) {
1107                 pNv->Architecture = NV_ARCH_20;
1108         } else if (pNv->NVArch >= 0x10) {
1109                 pNv->Architecture = NV_ARCH_10;
1110         } else if (pNv->NVArch >= 0x04) {
1111                 pNv->Architecture = NV_ARCH_04;
1112         /*  The lowest architecture currently supported is NV04 */
1113         } else {
1114                 return FALSE;
1115         }
1116
1117         /* Initialize the card through int10 interface if needed */
1118         if (xf86LoadSubModule(pScrn, "int10")) {
1119                 xf86LoaderReqSymLists(int10Symbols, NULL);
1120 #if !defined(__alpha__) && !defined(__powerpc__)
1121                 xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Initializing int10\n");
1122                 pNv->pInt10 = xf86InitInt10(pNv->pEnt->index);
1123 #endif
1124         }
1125
1126         /* Save current console video mode */
1127         if (pNv->Architecture >= NV_ARCH_50 && pNv->pInt10 && !pNv->kms_enable) {
1128                 const xf86Int10InfoPtr pInt10 = pNv->pInt10;
1129
1130                 pInt10->num = 0x10;
1131                 pInt10->ax  = 0x4f03;
1132                 pInt10->bx  =
1133                 pInt10->cx  =
1134                 pInt10->dx  = 0;
1135                 xf86ExecX86int10(pInt10);
1136                 pNv->Int10Mode = pInt10->bx & 0x3fff;
1137
1138                 xf86DrvMsg(pScrn->scrnIndex, X_PROBED,
1139                            "VESA-HACK: Console VGA mode is 0x%x\n",
1140                            pNv->Int10Mode);
1141         }
1142
1143         xf86SetOperatingState(resVgaIo, pNv->pEnt->index, ResUnusedOpr);
1144         xf86SetOperatingState(resVgaMem, pNv->pEnt->index, ResDisableOpr);
1145
1146         /* Set pScrn->monitor */
1147         pScrn->monitor = pScrn->confScreen->monitor;
1148
1149         /*
1150          * The first thing we should figure out is the depth, bpp, etc.
1151          */
1152
1153         if (!xf86SetDepthBpp(pScrn, 0, 0, 0, Support32bppFb)) {
1154                 NVPreInitFail("\n");
1155         } else {
1156                 /* Check that the returned depth is one we support */
1157                 switch (pScrn->depth) {
1158                         case 16:
1159                         case 24:
1160                                 /* OK */
1161                                 break;
1162                         case 15: /* 15 may get done one day, so leave any code for it in place */
1163                         default:
1164                                 NVPreInitFail("Given depth (%d) is not supported by this driver\n",
1165                                         pScrn->depth);
1166                 }
1167         }
1168         xf86PrintDepthBpp(pScrn);
1169
1170         /*
1171          * This must happen after pScrn->display has been set because
1172          * xf86SetWeight references it.
1173          */
1174         /* The defaults are OK for us */
1175         rgb rgbzeros = {0, 0, 0};
1176
1177         if (!xf86SetWeight(pScrn, rgbzeros, rgbzeros))
1178                 NVPreInitFail("\n");
1179
1180         if (!xf86SetDefaultVisual(pScrn, -1))
1181                 NVPreInitFail("\n");
1182         /* We don't support DirectColor */
1183         else if (pScrn->defaultVisual != TrueColor)
1184                 NVPreInitFail("Given default visual (%s) is not supported at depth %d\n",
1185                               xf86GetVisualName(pScrn->defaultVisual), pScrn->depth);
1186
1187         /* The vgahw module should be loaded here when needed */
1188         if (!xf86LoadSubModule(pScrn, "vgahw")) {
1189                 NVPreInitFail("\n");
1190         }
1191
1192         xf86LoaderReqSymLists(vgahwSymbols, NULL);
1193
1194         /*
1195          * Allocate a vgaHWRec
1196          */
1197         if (!vgaHWGetHWRec(pScrn)) {
1198                 NVPreInitFail("\n");
1199         }
1200
1201         /* We use a programmable clock */
1202         pScrn->progClock = TRUE;
1203
1204         /* Collect all of the relevant option flags (fill in pScrn->options) */
1205         xf86CollectOptions(pScrn, NULL);
1206
1207         /* Process the options */
1208         if (!(pNv->Options = xalloc(sizeof(NVOptions))))
1209                 return FALSE;
1210         memcpy(pNv->Options, NVOptions, sizeof(NVOptions));
1211         xf86ProcessOptions(pScrn->scrnIndex, pScrn->options, pNv->Options);
1212
1213         from = X_DEFAULT;
1214
1215         pNv->kms_enable = false;
1216 #ifdef XF86DRM_MODE
1217         if (pNv->Architecture == NV_ARCH_50)
1218                 pNv->kms_enable = nouveau_kernel_modesetting_enabled(pScrn);
1219 #endif /* XF86DRM_MODE */
1220
1221         if (pNv->kms_enable)
1222                 xf86DrvMsg(pScrn->scrnIndex, from, "NV50 Kernel modesetting enabled\n");
1223
1224         pNv->randr12_enable = true;
1225         if (pNv->Architecture != NV_ARCH_50 && !xf86ReturnOptValBool(pNv->Options, OPTION_RANDR12, TRUE))
1226                 pNv->randr12_enable = false;
1227         xf86DrvMsg(pScrn->scrnIndex, from, "Randr1.2 support %sabled\n", pNv->randr12_enable ? "en" : "dis");
1228
1229         pNv->HWCursor = TRUE;
1230         /*
1231          * The preferred method is to use the "hw cursor" option as a tri-state
1232          * option, with the default set above.
1233          */
1234         if (xf86GetOptValBool(pNv->Options, OPTION_HW_CURSOR, &pNv->HWCursor)) {
1235                 from = X_CONFIG;
1236         }
1237         /* For compatibility, accept this too (as an override) */
1238         if (xf86ReturnOptValBool(pNv->Options, OPTION_SW_CURSOR, FALSE)) {
1239                 from = X_CONFIG;
1240                 pNv->HWCursor = FALSE;
1241         }
1242         xf86DrvMsg(pScrn->scrnIndex, from, "Using %s cursor\n",
1243                 pNv->HWCursor ? "HW" : "SW");
1244
1245         pNv->FpScale = TRUE;
1246
1247         if (xf86GetOptValBool(pNv->Options, OPTION_FP_SCALE, &pNv->FpScale)) {
1248                 xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "Flat panel scaling %s\n",
1249                         pNv->FpScale ? "on" : "off");
1250         }
1251         if (xf86ReturnOptValBool(pNv->Options, OPTION_NOACCEL, FALSE)) {
1252                 pNv->NoAccel = TRUE;
1253                 xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "Acceleration disabled\n");
1254         }
1255         if (xf86ReturnOptValBool(pNv->Options, OPTION_SHADOW_FB, FALSE)) {
1256                 pNv->ShadowFB = TRUE;
1257                 pNv->NoAccel = TRUE;
1258                 xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, 
1259                         "Using \"Shadow Framebuffer\" - acceleration disabled\n");
1260         }
1261
1262         if(xf86GetOptValInteger(pNv->Options, OPTION_VIDEO_KEY, &(pNv->videoKey))) {
1263                 xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "video key set to 0x%x\n",
1264                                         pNv->videoKey);
1265         } else {
1266                 pNv->videoKey =  (1 << pScrn->offset.red) | 
1267                                         (1 << pScrn->offset.green) |
1268                 (((pScrn->mask.blue >> pScrn->offset.blue) - 1) << pScrn->offset.blue);
1269         }
1270
1271         /* Things happen on a per output basis for a randr-1.2 driver. */
1272         if (xf86GetOptValBool(pNv->Options, OPTION_FLAT_PANEL, &(pNv->FlatPanel)) && !pNv->randr12_enable) {
1273                 xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "forcing %s usage\n",
1274                         pNv->FlatPanel ? "DFP" : "CRTC");
1275         } else {
1276                 pNv->FlatPanel = -1; /* autodetect later */
1277         }
1278
1279         pNv->FPDither = FALSE;
1280         if (xf86GetOptValBool(pNv->Options, OPTION_FP_DITHER, &(pNv->FPDither))) 
1281                 xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "enabling flat panel dither\n");
1282
1283         if (xf86GetOptValInteger(pNv->Options, OPTION_FP_TWEAK, 
1284                                                 &pNv->PanelTweak)) {
1285                 pNv->usePanelTweak = TRUE;
1286         } else {
1287                 pNv->usePanelTweak = FALSE;
1288         }
1289
1290         if (pNv->pEnt->device->MemBase != 0) {
1291                 /* Require that the config file value matches one of the PCI values. */
1292                 if (!xf86CheckPciMemBase(pNv->PciInfo, pNv->pEnt->device->MemBase)) {
1293                         NVPreInitFail(
1294                                 "MemBase 0x%08lX doesn't match any PCI base register.\n",
1295                                 pNv->pEnt->device->MemBase);
1296                 }
1297                 pNv->VRAMPhysical = pNv->pEnt->device->MemBase;
1298                 from = X_CONFIG;
1299         } else {
1300                 if (PCI_DEV_MEM_BASE(pNv->PciInfo, 1) != 0) {
1301                         pNv->VRAMPhysical = PCI_DEV_MEM_BASE(pNv->PciInfo, 1) & 0xff800000;
1302                         from = X_PROBED;
1303                 } else {
1304                         NVPreInitFail("No valid FB address in PCI config space\n");
1305                         return FALSE;
1306                 }
1307         }
1308         xf86DrvMsg(pScrn->scrnIndex, from, "Linear framebuffer at 0x%lX\n",
1309                 (unsigned long)pNv->VRAMPhysical);
1310
1311         if (pNv->pEnt->device->IOBase != 0) {
1312                 /* Require that the config file value matches one of the PCI values. */
1313                 if (!xf86CheckPciMemBase(pNv->PciInfo, pNv->pEnt->device->IOBase)) {
1314                         NVPreInitFail("IOBase 0x%08lX doesn't match any PCI base register.\n",
1315                                 pNv->pEnt->device->IOBase);
1316                 }
1317                 pNv->IOAddress = pNv->pEnt->device->IOBase;
1318                 from = X_CONFIG;
1319         } else {
1320                 if (PCI_DEV_MEM_BASE(pNv->PciInfo, 0) != 0) {
1321                         pNv->IOAddress = PCI_DEV_MEM_BASE(pNv->PciInfo, 0) & 0xffffc000;
1322                         from = X_PROBED;
1323                 } else {
1324                         NVPreInitFail("No valid MMIO address in PCI config space\n");
1325                 }
1326         }
1327         xf86DrvMsg(pScrn->scrnIndex, from, "MMIO registers at 0x%lX\n",
1328                 (unsigned long)pNv->IOAddress);
1329
1330         if (xf86RegisterResources(pNv->pEnt->index, NULL, ResExclusive))
1331                 NVPreInitFail("xf86RegisterResources() found resource conflicts\n");
1332
1333         if (pNv->Architecture < NV_ARCH_10) {
1334                 max_width = (pScrn->bitsPerPixel > 16) ? 2032 : 2048;
1335                 max_height = 2048;
1336         } else if (pNv->Architecture < NV_ARCH_50) {
1337                 max_width = (pScrn->bitsPerPixel > 16) ? 4080 : 4096;
1338                 max_height = 4096;
1339         } else {
1340                 max_width = (pScrn->bitsPerPixel > 16) ? 8176 : 8192;
1341                 max_height = 8192;
1342         }
1343
1344 #ifdef XF86DRM_MODE
1345         if (pNv->kms_enable){
1346                 int res = 0;
1347                 char *bus_id;
1348                 bus_id = DRICreatePCIBusID(pNv->PciInfo);
1349
1350                 pNv->drmmode = calloc(1, sizeof(drmmode_rec));
1351                 res = drmmode_pre_init(pScrn, bus_id, pNv->drmmode, pScrn->bitsPerPixel >> 3);
1352                 if (!res) {
1353                         xfree(bus_id);
1354                         NVPreInitFail("Kernel modesetting failed to initialize\n");
1355                 }
1356         } else
1357 #endif
1358         if (pNv->randr12_enable) {
1359                 /* Allocate an xf86CrtcConfig */
1360                 xf86CrtcConfigInit(pScrn, &nv_xf86crtc_config_funcs);
1361                 xf86CrtcSetSizeRange(pScrn, 320, 200, max_width, max_height);
1362         }
1363
1364         if (NVPreInitDRI(pScrn) == FALSE)
1365                 NVPreInitFail("\n");
1366
1367         if (!pNv->randr12_enable) {
1368                 if ((pScrn->monitor->nHsync == 0) && 
1369                         (pScrn->monitor->nVrefresh == 0)) {
1370
1371                         config_mon_rates = FALSE;
1372                 } else {
1373                         config_mon_rates = TRUE;
1374                 }
1375         }
1376
1377         NVCommonSetup(pScrn);
1378
1379         if (pNv->randr12_enable && !pNv->kms_enable) {
1380                 if (pNv->Architecture == NV_ARCH_50)
1381                         if (!NV50DispPreInit(pScrn))
1382                                 NVPreInitFail("\n");
1383
1384                 NVI2CInit(pScrn);
1385
1386                 /* This is the internal system, not the randr-1.2 ones. */
1387                 if (pNv->Architecture == NV_ARCH_50) {
1388                         NV50CrtcInit(pScrn);
1389                         NV50ConnectorInit(pScrn);
1390                         NV50OutputSetup(pScrn);
1391                 }
1392
1393                 for (i = 0; i <= pNv->twoHeads; i++) {
1394                         if (pNv->Architecture == NV_ARCH_50)
1395                                 nv50_crtc_init(pScrn, i);
1396                         else
1397                                 nv_crtc_init(pScrn, i);
1398                 }
1399
1400                 if (pNv->Architecture < NV_ARCH_50)
1401                         NvSetupOutputs(pScrn);
1402                 else
1403                         nv50_output_create(pScrn); /* create randr-1.2 "outputs". */
1404
1405                 if (!xf86InitialConfiguration(pScrn, FALSE))
1406                         NVPreInitFail("No valid modes.\n");
1407         }
1408
1409         pScrn->videoRam = pNv->RamAmountKBytes;
1410         xf86DrvMsg(pScrn->scrnIndex, X_PROBED, "VideoRAM: %d kBytes\n",
1411                 pScrn->videoRam);
1412
1413         pNv->VRAMPhysicalSize = pScrn->videoRam * 1024;
1414
1415         /*
1416          * If the driver can do gamma correction, it should call xf86SetGamma()
1417          * here.
1418          */
1419         Gamma gammazeros = {0.0, 0.0, 0.0};
1420
1421         if (!xf86SetGamma(pScrn, gammazeros))
1422                 NVPreInitFail("\n");
1423
1424         /*
1425          * Setup the ClockRanges, which describe what clock ranges are available,
1426          * and what sort of modes they can be used for.
1427          */
1428
1429         clockRanges = xnfcalloc(sizeof(ClockRange), 1);
1430         clockRanges->next = NULL;
1431         clockRanges->minClock = pNv->MinVClockFreqKHz;
1432         clockRanges->maxClock = pNv->MaxVClockFreqKHz;
1433         clockRanges->clockIndex = -1;           /* programmable */
1434         clockRanges->doubleScanAllowed = TRUE;
1435         if ((pNv->Architecture == NV_ARCH_20) ||
1436                 ((pNv->Architecture == NV_ARCH_10) && 
1437                 ((pNv->Chipset & 0x0ff0) != CHIPSET_NV10) &&
1438                 ((pNv->Chipset & 0x0ff0) != CHIPSET_NV15))) {
1439                 /* HW is broken */
1440                 clockRanges->interlaceAllowed = FALSE;
1441         } else {
1442                 clockRanges->interlaceAllowed = TRUE;
1443         }
1444
1445         if(pNv->FlatPanel == 1) {
1446                 clockRanges->interlaceAllowed = FALSE;
1447                 clockRanges->doubleScanAllowed = FALSE;
1448         }
1449
1450 #ifdef M_T_DRIVER
1451         /* If DFP, add a modeline corresponding to its panel size */
1452         if (pNv->FlatPanel && !pNv->Television && pNv->fpWidth && pNv->fpHeight) {
1453                 DisplayModePtr Mode;
1454
1455                 Mode = xnfcalloc(1, sizeof(DisplayModeRec));
1456                 Mode = xf86CVTMode(pNv->fpWidth, pNv->fpHeight, 60.00, TRUE, FALSE);
1457                 Mode->type = M_T_DRIVER;
1458                 pScrn->monitor->Modes = xf86ModesAdd(pScrn->monitor->Modes, Mode);
1459
1460                 if (!config_mon_rates) {
1461                         if (!Mode->HSync)
1462                                 Mode->HSync = ((float) Mode->Clock ) / ((float) Mode->HTotal);
1463                         if (!Mode->VRefresh)
1464                                 Mode->VRefresh = (1000.0 * ((float) Mode->Clock)) /
1465                                                         ((float) (Mode->HTotal * Mode->VTotal));
1466
1467                         if (Mode->HSync < pScrn->monitor->hsync[0].lo)
1468                                 pScrn->monitor->hsync[0].lo = Mode->HSync;
1469                         if (Mode->HSync > pScrn->monitor->hsync[0].hi)
1470                                 pScrn->monitor->hsync[0].hi = Mode->HSync;
1471                         if (Mode->VRefresh < pScrn->monitor->vrefresh[0].lo)
1472                                 pScrn->monitor->vrefresh[0].lo = Mode->VRefresh;
1473                         if (Mode->VRefresh > pScrn->monitor->vrefresh[0].hi)
1474                                 pScrn->monitor->vrefresh[0].hi = Mode->VRefresh;
1475
1476                         pScrn->monitor->nHsync = 1;
1477                         pScrn->monitor->nVrefresh = 1;
1478                 }
1479         }
1480 #endif
1481
1482         if (pNv->randr12_enable) {
1483                 pScrn->displayWidth = nv_pitch_align(pNv, pScrn->virtualX, pScrn->depth);
1484         } else {
1485                 /*
1486                  * xf86ValidateModes will check that the mode HTotal and VTotal values
1487                  * don't exceed the chipset's limit if pScrn->maxHValue and
1488                  * pScrn->maxVValue are set.  Since our NVValidMode() already takes
1489                  * care of this, we don't worry about setting them here.
1490                  */
1491                 i = xf86ValidateModes(pScrn, pScrn->monitor->Modes,
1492                                         pScrn->display->modes, clockRanges,
1493                                         NULL, 256, max_width,
1494                                         512, 128, max_height,
1495                                         pScrn->display->virtualX,
1496                                         pScrn->display->virtualY,
1497                                         pNv->VRAMPhysicalSize / 2,
1498                                         LOOKUP_BEST_REFRESH);
1499
1500                 if (i == -1) {
1501                         NVPreInitFail("\n");
1502                 }
1503
1504                 /* Prune the modes marked as invalid */
1505                 xf86PruneDriverModes(pScrn);
1506
1507                 /*
1508                  * Set the CRTC parameters for all of the modes based on the type
1509                  * of mode, and the chipset's interlace requirements.
1510                  *
1511                  * Calling this is required if the mode->Crtc* values are used by the
1512                  * driver and if the driver doesn't provide code to set them.  They
1513                  * are not pre-initialised at all.
1514                  */
1515                 xf86SetCrtcForModes(pScrn, 0);
1516
1517                 if (pScrn->modes == NULL)
1518                         NVPreInitFail("No valid modes found\n");
1519         }
1520
1521         /* Set the current mode to the first in the list */
1522         pScrn->currentMode = pScrn->modes;
1523
1524         /* Print the list of modes being used */
1525         xf86PrintModes(pScrn);
1526
1527         /* Set display resolution */
1528         xf86SetDpi(pScrn, 0, 0);
1529
1530         /*
1531          * XXX This should be taken into account in some way in the mode valdation
1532          * section.
1533          */
1534
1535         if (xf86LoadSubModule(pScrn, "fb") == NULL)
1536                 NVPreInitFail("\n");
1537
1538         xf86LoaderReqSymLists(fbSymbols, NULL);
1539
1540         /* Load EXA if needed */
1541         if (!pNv->NoAccel) {
1542                 if (!xf86LoadSubModule(pScrn, "exa")) {
1543                         NVPreInitFail("\n");
1544                 }
1545                 xf86LoaderReqSymLists(exaSymbols, NULL);
1546         }
1547
1548         /* Load ramdac if needed */
1549         if (pNv->HWCursor) {
1550                 if (!xf86LoadSubModule(pScrn, "ramdac")) {
1551                         NVPreInitFail("\n");
1552                 }
1553                 xf86LoaderReqSymLists(ramdacSymbols, NULL);
1554         }
1555
1556         /* Load shadowfb if needed */
1557         if (pNv->ShadowFB) {
1558                 if (!xf86LoadSubModule(pScrn, "shadowfb")) {
1559                         NVPreInitFail("\n");
1560                 }
1561                 xf86LoaderReqSymLists(shadowSymbols, NULL);
1562         }
1563
1564         return TRUE;
1565 }
1566
1567
1568 /*
1569  * Map the framebuffer and MMIO memory.
1570  */
1571
1572 static Bool
1573 NVMapMem(ScrnInfoPtr pScrn)
1574 {
1575         NVPtr pNv = NVPTR(pScrn);
1576         int gart_scratch_size;
1577         uint64_t res;
1578
1579         nouveau_device_get_param(pNv->dev, NOUVEAU_GETPARAM_FB_SIZE, &res);
1580         pNv->VRAMSize=res;
1581         nouveau_device_get_param(pNv->dev, NOUVEAU_GETPARAM_FB_PHYSICAL, &res);
1582         pNv->VRAMPhysical=res;
1583         nouveau_device_get_param(pNv->dev, NOUVEAU_GETPARAM_AGP_SIZE, &res);
1584         pNv->AGPSize=res;
1585
1586 #if !NOUVEAU_EXA_PIXMAPS
1587         if (nouveau_bo_new(pNv->dev, NOUVEAU_BO_VRAM | NOUVEAU_BO_PIN,
1588                 0, pNv->VRAMPhysicalSize / 2, &pNv->FB)) {
1589                         xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Failed to allocate memory for framebuffer!\n");
1590                         return FALSE;
1591         }
1592         xf86DrvMsg(pScrn->scrnIndex, X_INFO,
1593                 "Allocated %dMiB VRAM for framebuffer + offscreen pixmaps, at offset 0x%X\n",
1594                 (uint32_t)(pNv->FB->size >> 20), (uint32_t) pNv->FB->offset);
1595 #ifdef XF86DRM_MODE
1596         if (pNv->kms_enable)
1597                 drmmode_set_fb(pScrn, pNv->drmmode, pScrn->virtualX, pScrn->virtualY, pScrn->displayWidth*(pScrn->bitsPerPixel >> 3), pNv->FB);
1598 #endif
1599 #endif
1600
1601         if (pNv->AGPSize) {
1602                 xf86DrvMsg(pScrn->scrnIndex, X_INFO,
1603                            "AGPGART: %dMiB available\n",
1604                            (unsigned int)(pNv->AGPSize >> 20));
1605                 if (pNv->AGPSize > (16*1024*1024))
1606                         gart_scratch_size = 16*1024*1024;
1607                 else
1608                         /* always leave 512kb for other things like the fifos */
1609                         gart_scratch_size = pNv->AGPSize - 512*1024;
1610         } else {
1611                 gart_scratch_size = (4 << 20) - (1 << 18) ;
1612                 xf86DrvMsg(pScrn->scrnIndex, X_INFO,
1613                            "GART: PCI DMA - using %dKiB\n",
1614                            gart_scratch_size >> 10);
1615         }
1616
1617         if (nouveau_bo_new(pNv->dev, NOUVEAU_BO_GART | NOUVEAU_BO_PIN, 0,
1618                            gart_scratch_size, &pNv->GART)) {
1619                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1620                            "Unable to allocate GART memory\n");
1621         }
1622         if (pNv->GART) {
1623                 xf86DrvMsg(pScrn->scrnIndex, X_INFO,
1624                            "GART: Allocated %dMiB as a scratch buffer\n",
1625                            (unsigned int)(pNv->GART->size >> 20));
1626         }
1627
1628         if (nouveau_bo_new(pNv->dev, NOUVEAU_BO_VRAM | NOUVEAU_BO_PIN, 0,
1629                            64 * 1024, &pNv->Cursor)) {
1630                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1631                            "Failed to allocate memory for hardware cursor\n");
1632                 return FALSE;
1633         }
1634
1635         if (pNv->randr12_enable) {
1636                 if (nouveau_bo_new(pNv->dev, NOUVEAU_BO_VRAM | NOUVEAU_BO_PIN, 0,
1637                         64 * 1024, &pNv->Cursor2)) {
1638                         xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1639                                 "Failed to allocate memory for hardware cursor\n");
1640                         return FALSE;
1641                 }
1642         }
1643
1644         if (pNv->Architecture >= NV_ARCH_50) {
1645                 /* Both CRTC's have a CLUT. */
1646                 if (nouveau_bo_new(pNv->dev, NOUVEAU_BO_VRAM | NOUVEAU_BO_PIN,
1647                                    0, 0x1000, &pNv->CLUT0)) {
1648                         xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1649                                    "Failed to allocate memory for CLUT0\n");
1650                         return FALSE;
1651                 }
1652
1653                 if (nouveau_bo_new(pNv->dev, NOUVEAU_BO_VRAM | NOUVEAU_BO_PIN,
1654                                    0, 0x1000, &pNv->CLUT1)) {
1655                         xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1656                                    "Failed to allocate memory for CLUT1\n");
1657                         return FALSE;
1658                 }
1659         }
1660
1661         if ((pNv->FB && nouveau_bo_map(pNv->FB, NOUVEAU_BO_RDWR)) ||
1662             (pNv->GART && nouveau_bo_map(pNv->GART, NOUVEAU_BO_RDWR)) ||
1663             (pNv->CLUT0 && nouveau_bo_map(pNv->CLUT0, NOUVEAU_BO_RDWR)) ||
1664             (pNv->CLUT1 && nouveau_bo_map(pNv->CLUT1, NOUVEAU_BO_RDWR)) ||
1665             nouveau_bo_map(pNv->Cursor, NOUVEAU_BO_RDWR) ||
1666             (pNv->randr12_enable && nouveau_bo_map(pNv->Cursor2, NOUVEAU_BO_RDWR))) {
1667                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1668                            "Failed to map pinned buffers\n");
1669                 return FALSE;
1670         }
1671
1672         return TRUE;
1673 }
1674
1675 /*
1676  * Unmap the framebuffer and MMIO memory.
1677  */
1678
1679 static Bool
1680 NVUnmapMem(ScrnInfoPtr pScrn)
1681 {
1682         NVPtr pNv = NVPTR(pScrn);
1683
1684         nouveau_bo_del(&pNv->FB);
1685         nouveau_bo_del(&pNv->GART);
1686         nouveau_bo_del(&pNv->Cursor);
1687         if (pNv->randr12_enable) {
1688                 nouveau_bo_del(&pNv->Cursor2);
1689         }
1690         nouveau_bo_del(&pNv->CLUT0);
1691         nouveau_bo_del(&pNv->CLUT1);
1692
1693         return TRUE;
1694 }
1695
1696
1697 /*
1698  * Initialise a new mode. 
1699  */
1700
1701 static Bool
1702 NVModeInit(ScrnInfoPtr pScrn, DisplayModePtr mode)
1703 {
1704     vgaHWPtr hwp = VGAHWPTR(pScrn);
1705     vgaRegPtr vgaReg;
1706     NVPtr pNv = NVPTR(pScrn);
1707     NVRegPtr nvReg;
1708
1709     /* Initialise the ModeReg values */
1710     if (!vgaHWInit(pScrn, mode))
1711         return FALSE;
1712     pScrn->vtSema = TRUE;
1713
1714     vgaReg = &hwp->ModeReg;
1715     nvReg = &pNv->ModeReg;
1716
1717     if(!NVDACInit(pScrn, mode))
1718         return FALSE;
1719
1720     NVLockUnlock(pScrn, 0);
1721     if(pNv->twoHeads) {
1722         nvWriteCurVGA(pNv, NV_VGA_CRTCX_OWNER, nvReg->crtcOwner);
1723         NVLockUnlock(pScrn, 0);
1724     }
1725
1726     /* Program the registers */
1727     vgaHWProtect(pScrn, TRUE);
1728
1729     NVDACRestore(pScrn, vgaReg, nvReg, FALSE);
1730
1731 #if X_BYTE_ORDER == X_BIG_ENDIAN
1732     /* turn on LFB swapping */
1733     {
1734         unsigned char tmp;
1735
1736         tmp = nvReadCurVGA(pNv, NV_VGA_CRTCX_SWAPPING);
1737         tmp |= (1 << 7);
1738         nvWriteCurVGA(pNv, NV_VGA_CRTCX_SWAPPING, tmp);
1739     }
1740 #endif
1741
1742     if (!pNv->NoAccel)
1743                 NVAccelCommonInit(pScrn);
1744
1745     vgaHWProtect(pScrn, FALSE);
1746
1747     pScrn->currentMode = mode;
1748
1749     return TRUE;
1750 }
1751
1752 /*
1753  * Restore the initial (text) mode.
1754  */
1755 static void 
1756 NVRestore(ScrnInfoPtr pScrn)
1757 {
1758         NVPtr pNv = NVPTR(pScrn);
1759
1760         if (pNv->randr12_enable) {
1761                 xf86CrtcConfigPtr xf86_config = XF86_CRTC_CONFIG_PTR(pScrn);
1762                 int i;
1763
1764                 for (i = 0; i < xf86_config->num_crtc; i++)
1765                         NVCrtcLockUnlock(xf86_config->crtc[i], 0);
1766
1767                 for (i = 0; i < pNv->dcb_table.entries; i++)
1768                         nv_encoder_restore(pScrn, &pNv->encoders[i]);
1769
1770                 for (i = 0; i < xf86_config->num_crtc; i++)
1771                         xf86_config->crtc[i]->funcs->restore(xf86_config->crtc[i]);
1772
1773                 nv_save_restore_vga_fonts(pScrn, 0);
1774
1775                 for (i = 0; i < xf86_config->num_crtc; i++)
1776                         NVCrtcLockUnlock(xf86_config->crtc[i], 1);
1777         } else {
1778                 vgaHWPtr hwp = VGAHWPTR(pScrn);
1779                 vgaRegPtr vgaReg = &hwp->SavedReg;
1780                 NVRegPtr nvReg = &pNv->SavedReg;
1781
1782                 NVLockUnlock(pScrn, 0);
1783
1784                 if(pNv->twoHeads) {
1785                         nvWriteCurVGA(pNv, NV_VGA_CRTCX_OWNER, pNv->crtc_active[1] * 0x3);
1786                         NVLockUnlock(pScrn, 0);
1787                 }
1788
1789                 /* Only restore text mode fonts/text for the primary card */
1790                 vgaHWProtect(pScrn, TRUE);
1791                 NVDACRestore(pScrn, vgaReg, nvReg, pNv->Primary);
1792                 vgaHWProtect(pScrn, FALSE);
1793         }
1794
1795         if (pNv->twoHeads) {
1796                 NVSetOwner(pScrn, 0);   /* move to head A to set owner */
1797                 NVLockVgaCrtc(pNv, 0, false);
1798                 xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Restoring CRTC_OWNER to %d.\n", pNv->vtOWNER);
1799                 NVWriteVgaCrtc(pNv, 0, NV_VGA_CRTCX_OWNER, pNv->vtOWNER);
1800                 NVLockVgaCrtc(pNv, 0, true);
1801         }
1802 }
1803
1804 static void
1805 NVLoadPalette(ScrnInfoPtr pScrn, int numColors, int *indices,
1806               LOCO * colors, VisualPtr pVisual)
1807 {
1808         xf86CrtcConfigPtr xf86_config = XF86_CRTC_CONFIG_PTR(pScrn);
1809         int c;
1810         int i, j, index;
1811         CARD16 lut_r[256], lut_g[256], lut_b[256];
1812
1813         for (c = 0; c < xf86_config->num_crtc; c++) {
1814                 xf86CrtcPtr crtc = xf86_config->crtc[c];
1815
1816                 /* code borrowed from intel driver */
1817                 switch (pScrn->depth) {
1818                 case 15:
1819                         for (i = 0; i < numColors; i++) {
1820                                 index = indices[i];
1821                                 for (j = 0; j < 8; j++) {
1822                                         lut_r[index * 8 + j] = colors[index].red << 8;
1823                                         lut_g[index * 8 + j] = colors[index].green << 8;
1824                                         lut_b[index * 8 + j] = colors[index].blue << 8;
1825                                 }
1826                         }
1827                 case 16:
1828                         for (i = 0; i < numColors; i++) {
1829                                 index = indices[i];
1830
1831                                 if (i <= 31) {
1832                                         for (j = 0; j < 8; j++) {
1833                                                 lut_r[index * 8 + j] = colors[index].red << 8;
1834                                                 lut_b[index * 8 + j] = colors[index].blue << 8;
1835                                         }
1836                                 }
1837
1838                                 for (j = 0; j < 4; j++) {
1839                                         lut_g[index * 4 + j] = colors[index].green << 8;
1840                                 }
1841                         }
1842                 default:
1843                         for (i = 0; i < numColors; i++) {
1844                                 index = indices[i];
1845                                 lut_r[index] = colors[index].red << 8;
1846                                 lut_g[index] = colors[index].green << 8;
1847                                 lut_b[index] = colors[index].blue << 8;
1848                         }
1849                         break;
1850                 }
1851
1852                 /* Make the change through RandR */
1853                 RRCrtcGammaSet(crtc->randr_crtc, lut_r, lut_g, lut_b);
1854         }
1855 }
1856
1857 static void NVBacklightEnable(NVPtr pNv,  Bool on)
1858 {
1859     /* This is done differently on each laptop.  Here we
1860        define the ones we know for sure. */
1861
1862 #if defined(__powerpc__)
1863     if((pNv->Chipset & 0xffff == 0x0179) ||
1864        (pNv->Chipset & 0xffff == 0x0189) ||
1865        (pNv->Chipset & 0xffff == 0x0329))
1866     {
1867        /* NV17,18,34 Apple iMac, iBook, PowerBook */
1868       CARD32 tmp_pmc, tmp_pcrt;
1869       tmp_pmc = nvReadMC(pNv, NV_PBUS_DEBUG_DUALHEAD_CTL) & 0x7FFFFFFF;
1870       tmp_pcrt = NVReadCRTC(pNv, 0, NV_CRTC_GPIO_EXT) & 0xFFFFFFFC;
1871       if(on) {
1872           tmp_pmc |= (1 << 31);
1873           tmp_pcrt |= 0x1;
1874       }
1875       nvWriteMC(pNv, NV_PBUS_DEBUG_DUALHEAD_CTL, tmp_pmc);
1876       NVWriteCRTC(pNv, 0, NV_CRTC_GPIO_EXT, tmp_pcrt);
1877     }
1878 #endif
1879     
1880     if(pNv->LVDS) {
1881        if(pNv->twoHeads && ((pNv->Chipset & 0x0ff0) != CHIPSET_NV11)) {
1882            nvWriteMC(pNv, 0x130C, on ? 3 : 7);
1883        }
1884     } else {
1885        CARD32 fpcontrol;
1886
1887        fpcontrol = nvReadCurRAMDAC(pNv, NV_RAMDAC_FP_CONTROL) & 0xCfffffCC;
1888
1889        /* cut the TMDS output */
1890        if(on) fpcontrol |= pNv->fpSyncs;
1891        else fpcontrol |= 0x20000022;
1892
1893        nvWriteCurRAMDAC(pNv, NV_RAMDAC_FP_CONTROL, fpcontrol);
1894     }
1895 }
1896
1897 static void
1898 NVDPMSSetLCD(ScrnInfoPtr pScrn, int PowerManagementMode, int flags)
1899 {
1900   NVPtr pNv = NVPTR(pScrn);
1901
1902   if (!pScrn->vtSema) return;
1903
1904   vgaHWDPMSSet(pScrn, PowerManagementMode, flags);
1905
1906   switch (PowerManagementMode) {
1907   case DPMSModeStandby:  /* HSync: Off, VSync: On */
1908   case DPMSModeSuspend:  /* HSync: On, VSync: Off */
1909   case DPMSModeOff:      /* HSync: Off, VSync: Off */
1910     NVBacklightEnable(pNv, 0);
1911     break;
1912   case DPMSModeOn:       /* HSync: On, VSync: On */
1913     NVBacklightEnable(pNv, 1);
1914   default:
1915     break;
1916   }
1917 }
1918
1919
1920 static void
1921 NVDPMSSet(ScrnInfoPtr pScrn, int PowerManagementMode, int flags)
1922 {
1923   unsigned char crtc1A;
1924   vgaHWPtr hwp = VGAHWPTR(pScrn);
1925
1926   if (!pScrn->vtSema) return;
1927
1928   crtc1A = hwp->readCrtc(hwp, 0x1A) & ~0xC0;
1929
1930   switch (PowerManagementMode) {
1931   case DPMSModeStandby:  /* HSync: Off, VSync: On */
1932     crtc1A |= 0x80;
1933     break;
1934   case DPMSModeSuspend:  /* HSync: On, VSync: Off */
1935     crtc1A |= 0x40;
1936     break;
1937   case DPMSModeOff:      /* HSync: Off, VSync: Off */
1938     crtc1A |= 0xC0;
1939     break;
1940   case DPMSModeOn:       /* HSync: On, VSync: On */
1941   default:
1942     break;
1943   }
1944
1945   /* vgaHWDPMSSet will merely cut the dac output */
1946   vgaHWDPMSSet(pScrn, PowerManagementMode, flags);
1947
1948   hwp->writeCrtc(hwp, 0x1A, crtc1A);
1949 }
1950
1951
1952 /* Mandatory */
1953
1954 /* This gets called at the start of each server generation */
1955
1956 static Bool
1957 NVScreenInit(int scrnIndex, ScreenPtr pScreen, int argc, char **argv)
1958 {
1959         ScrnInfoPtr pScrn;
1960         vgaHWPtr hwp;
1961         NVPtr pNv;
1962         int ret;
1963         VisualPtr visual;
1964         unsigned char *FBStart;
1965         int displayWidth;
1966
1967         /* 
1968          * First get the ScrnInfoRec
1969          */
1970         pScrn = xf86Screens[pScreen->myNum];
1971
1972         hwp = VGAHWPTR(pScrn);
1973         pNv = NVPTR(pScrn);
1974
1975         /* Map the VGA memory when the primary video */
1976         if (pNv->Primary) {
1977                 hwp->MapSize = 0x10000;
1978                 if (!vgaHWMapMem(pScrn))
1979                         return FALSE;
1980         }
1981
1982         /* First init DRI/DRM */
1983         if (!NVDRIScreenInit(pScrn))
1984                 return FALSE;
1985
1986         /* Allocate and map memory areas we need */
1987         if (!NVMapMem(pScrn))
1988                 return FALSE;
1989
1990         if (!pNv->NoAccel) {
1991                 /* Init DRM - Alloc FIFO */
1992                 if (!NVInitDma(pScrn))
1993                         return FALSE;
1994
1995                 /* setup graphics objects */
1996                 if (!NVAccelCommonInit(pScrn))
1997                         return FALSE;
1998         }
1999
2000 #if NOUVEAU_EXA_PIXMAPS
2001         if (nouveau_bo_new(pNv->dev, NOUVEAU_BO_VRAM | NOUVEAU_BO_PIN,
2002                         0, NOUVEAU_ALIGN(pScrn->virtualX, 64) * NOUVEAU_ALIGN(pScrn->virtualY, 64) *
2003                         (pScrn->bitsPerPixel >> 3), &pNv->FB)) {
2004                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Failed to allocate memory for screen pixmap.\n");
2005                 return FALSE;
2006         }
2007 #endif
2008
2009         if (!pNv->randr12_enable) {
2010                 /* Save the current state */
2011                 NVSave(pScrn);
2012                 /* Initialise the first mode */
2013                 if (!NVModeInit(pScrn, pScrn->currentMode))
2014                         return FALSE;
2015
2016                 /* Darken the screen for aesthetic reasons and set the viewport */
2017                 NVSaveScreen(pScreen, SCREEN_SAVER_ON);
2018                 pScrn->AdjustFrame(scrnIndex, pScrn->frameX0, pScrn->frameY0, 0);
2019         } else {
2020                 pScrn->memPhysBase = pNv->VRAMPhysical;
2021                 pScrn->fbOffset = 0;
2022
2023                 if (!NVEnterVT(scrnIndex, 0))
2024                         return FALSE;
2025                 NVSaveScreen(pScreen, SCREEN_SAVER_ON);
2026         }
2027
2028
2029         /*
2030          * The next step is to setup the screen's visuals, and initialise the
2031          * framebuffer code.  In cases where the framebuffer's default
2032          * choices for things like visual layouts and bits per RGB are OK,
2033          * this may be as simple as calling the framebuffer's ScreenInit()
2034          * function.  If not, the visuals will need to be setup before calling
2035          * a fb ScreenInit() function and fixed up after.
2036          *
2037          * For most PC hardware at depths >= 8, the defaults that fb uses
2038          * are not appropriate.  In this driver, we fixup the visuals after.
2039          */
2040
2041         /*
2042          * Reset the visual list.
2043          */
2044         miClearVisualTypes();
2045
2046         /* Setup the visuals we support. */
2047
2048         if (!miSetVisualTypes(pScrn->depth, 
2049                                 miGetDefaultVisualMask(pScrn->depth), 8,
2050                                 pScrn->defaultVisual))
2051                 return FALSE;
2052         if (!miSetPixmapDepths ())
2053                 return FALSE;
2054
2055         /*
2056          * Call the framebuffer layer's ScreenInit function, and fill in other
2057          * pScreen fields.
2058          */
2059
2060         if (pNv->ShadowFB) {
2061                 pNv->ShadowPitch = BitmapBytePad(pScrn->bitsPerPixel * pScrn->virtualX);
2062                 pNv->ShadowPtr = xalloc(pNv->ShadowPitch * pScrn->virtualY);
2063                 displayWidth = pNv->ShadowPitch / (pScrn->bitsPerPixel >> 3);
2064                 FBStart = pNv->ShadowPtr;
2065         } else {
2066                 pNv->ShadowPtr = NULL;
2067                 displayWidth = pScrn->displayWidth;
2068                 FBStart = pNv->FB->map;
2069         }
2070
2071         switch (pScrn->bitsPerPixel) {
2072                 case 16:
2073                 case 32:
2074                         ret = fbScreenInit(pScreen, FBStart, pScrn->virtualX, pScrn->virtualY,
2075                                 pScrn->xDpi, pScrn->yDpi,
2076                                 displayWidth, pScrn->bitsPerPixel);
2077                         break;
2078                 default:
2079                         xf86DrvMsg(scrnIndex, X_ERROR,
2080                                 "Internal error: invalid bpp (%d) in NVScreenInit\n",
2081                                 pScrn->bitsPerPixel);
2082                         ret = FALSE;
2083                         break;
2084         }
2085         if (!ret)
2086                 return FALSE;
2087
2088         /* Fixup RGB ordering */
2089         visual = pScreen->visuals + pScreen->numVisuals;
2090         while (--visual >= pScreen->visuals) {
2091                 if ((visual->class | DynamicClass) == DirectColor) {
2092                         visual->offsetRed = pScrn->offset.red;
2093                         visual->offsetGreen = pScrn->offset.green;
2094                         visual->offsetBlue = pScrn->offset.blue;
2095                         visual->redMask = pScrn->mask.red;
2096                         visual->greenMask = pScrn->mask.green;
2097                         visual->blueMask = pScrn->mask.blue;
2098                 }
2099         }
2100
2101         fbPictureInit (pScreen, 0, 0);
2102
2103         xf86SetBlackWhitePixels(pScreen);
2104
2105         if (!pNv->NoAccel) {
2106                 if (!NVExaInit(pScreen))
2107                         return FALSE;
2108                 NVAccelCommonInit(pScrn);
2109         } else if (pNv->VRAMPhysicalSize / 2 < NOUVEAU_ALIGN(pScrn->virtualX, 64) * NOUVEAU_ALIGN(pScrn->virtualY, 64) * (pScrn->bitsPerPixel >> 3)) {
2110                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "The virtual screen size's resolution is too big for the video RAM framebuffer at this colour depth.\n");
2111                 return FALSE;
2112         }
2113
2114
2115         miInitializeBackingStore(pScreen);
2116         xf86SetBackingStore(pScreen);
2117         xf86SetSilkenMouse(pScreen);
2118
2119         /* Finish DRI init */
2120         NVDRIFinishScreenInit(pScrn);
2121
2122         /* 
2123          * Initialize software cursor.
2124          * Must precede creation of the default colormap.
2125          */
2126         miDCInitialize(pScreen, xf86GetPointerScreenFuncs());
2127
2128         /*
2129          * Initialize HW cursor layer. 
2130          * Must follow software cursor initialization.
2131          */
2132         if (pNv->HWCursor) { 
2133                 if (pNv->Architecture < NV_ARCH_50 && !pNv->randr12_enable)
2134                         ret = NVCursorInit(pScreen);
2135                 else if (pNv->Architecture < NV_ARCH_50 && pNv->randr12_enable)
2136                         ret = NVCursorInitRandr12(pScreen);
2137                 else
2138                         ret = NV50CursorInit(pScreen);
2139
2140                 if (ret != TRUE) {
2141                         xf86DrvMsg(pScrn->scrnIndex, X_ERROR, 
2142                                 "Hardware cursor initialization failed\n");
2143                         pNv->HWCursor = FALSE;
2144                 }
2145         }
2146
2147         if (pNv->randr12_enable) {
2148                 xf86DPMSInit(pScreen, xf86DPMSSet, 0);
2149
2150                 if (!xf86CrtcScreenInit(pScreen))
2151                         return FALSE;
2152         }
2153
2154         /* Initialise default colourmap */
2155         if (!miCreateDefColormap(pScreen))
2156                 return FALSE;
2157
2158         /*
2159          * Initialize colormap layer.
2160          * Must follow initialization of the default colormap 
2161          */
2162         if (!pNv->randr12_enable && !pNv->kms_enable) {
2163                 if(!xf86HandleColormaps(pScreen, 256, 8, NVDACLoadPalette,
2164                                 NULL, CMAP_RELOAD_ON_MODE_SWITCH | CMAP_PALETTED_TRUECOLOR))
2165                         return FALSE;
2166         } else {
2167                 if (!xf86HandleColormaps(pScreen, 256, 8, NVLoadPalette,
2168                                 NULL, CMAP_PALETTED_TRUECOLOR))
2169                         return FALSE;
2170         }
2171
2172         if (pNv->ShadowFB)
2173                 ShadowFBInit(pScreen, NVRefreshArea);
2174
2175         if (!pNv->randr12_enable) {
2176                 if(pNv->FlatPanel) {
2177                         xf86DPMSInit(pScreen, NVDPMSSetLCD, 0);
2178                 } else {
2179                         xf86DPMSInit(pScreen, NVDPMSSet, 0);
2180                 }
2181         }
2182
2183         pScrn->memPhysBase = pNv->VRAMPhysical;
2184         pScrn->fbOffset = 0;
2185
2186         NVInitVideo(pScreen);
2187
2188         pScreen->SaveScreen = NVSaveScreen;
2189
2190         /* Wrap the current CloseScreen function */
2191         pNv->CloseScreen = pScreen->CloseScreen;
2192         pScreen->CloseScreen = NVCloseScreen;
2193
2194         pNv->BlockHandler = pScreen->BlockHandler;
2195         pScreen->BlockHandler = NVBlockHandler;
2196
2197         /* Report any unused options (only for the first generation) */
2198         if (serverGeneration == 1)
2199                 xf86ShowUnusedOptions(pScrn->scrnIndex, pScrn->options);
2200
2201         return TRUE;
2202 }
2203
2204 static Bool
2205 NVSaveScreen(ScreenPtr pScreen, int mode)
2206 {
2207     ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum];
2208     NVPtr pNv = NVPTR(pScrn);
2209     int i;
2210     Bool on = xf86IsUnblank(mode);
2211     
2212     if (pNv->randr12_enable) {
2213         xf86CrtcConfigPtr xf86_config = XF86_CRTC_CONFIG_PTR(pScrn);
2214         if (pScrn->vtSema && pNv->Architecture < NV_ARCH_50) {
2215             for (i = 0; i < xf86_config->num_crtc; i++) {
2216                 
2217                 if (xf86_config->crtc[i]->enabled) {
2218                     struct nouveau_crtc *nv_crtc = to_nouveau_crtc(xf86_config->crtc[i]);
2219                     NVBlankScreen(pScrn, nv_crtc->head, !on);
2220                 }
2221             }
2222             
2223         }
2224         return TRUE;
2225     }
2226
2227         return vgaHWSaveScreen(pScreen, mode);
2228 }
2229
2230 static void
2231 NVSave(ScrnInfoPtr pScrn)
2232 {
2233         NVPtr pNv = NVPTR(pScrn);
2234         NVRegPtr nvReg = &pNv->SavedReg;
2235
2236         if (pNv->randr12_enable) {
2237                 xf86CrtcConfigPtr xf86_config = XF86_CRTC_CONFIG_PTR(pScrn);
2238                 int i;
2239
2240                 nv_save_restore_vga_fonts(pScrn, 1);
2241
2242                 for (i = 0; i < xf86_config->num_crtc; i++)
2243                         xf86_config->crtc[i]->funcs->save(xf86_config->crtc[i]);
2244
2245                 for (i = 0; i < pNv->dcb_table.entries; i++)
2246                         nv_encoder_save(pScrn, &pNv->encoders[i]);
2247         } else {
2248                 vgaHWPtr pVga = VGAHWPTR(pScrn);
2249                 vgaRegPtr vgaReg = &pVga->SavedReg;
2250                 NVLockUnlock(pScrn, 0);
2251                 if (pNv->twoHeads) {
2252                         nvWriteCurVGA(pNv, NV_VGA_CRTCX_OWNER, pNv->crtc_active[1] * 0x3);
2253                         NVLockUnlock(pScrn, 0);
2254                 }
2255
2256                 NVDACSave(pScrn, vgaReg, nvReg, pNv->Primary);
2257         }
2258 }