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