1/* $Id: vboxvideo.c,v 1.2 2020/10/22 20:47:23 thorpej Exp $ */
2/** @file
3 * Linux Additions X11 graphics driver
4 */
5
6/*
7 * Copyright (C) 2006-2017 Oracle Corporation
8 *
9 * This code is based on the X.Org VESA driver with the following copyrights:
10 *
11 * Copyright (c) 2000 by Conectiva S.A. (http://www.conectiva.com)
12 * Copyright 2008 Red Hat, Inc.
13 * Copyright 2012 Red Hat, Inc.
14 *
15 * Permission is hereby granted, free of charge, to any person obtaining a
16 * copy of this software and associated documentation files (the "Software"),
17 * to deal in the Software without restriction, including without limitation
18 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
19 * and/or sell copies of the Software, and to permit persons to whom the
20 * Software is furnished to do so, subject to the following conditions:
21 *
22 * The above copyright notice and this permission notice shall be included in
23 * all copies or substantial portions of the Software.
24 *
25 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27 * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
28 * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM,
29 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
30 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
31 * USE OR OTHER DEALINGS IN THE SOFTWARE.
32 *
33 * Except as contained in this notice, the name of Conectiva Linux shall
34 * not be used in advertising or otherwise to promote the sale, use or other
35 * dealings in this Software without prior written authorization from
36 * Conectiva Linux.
37 *
38 * Authors: Paulo César Pereira de Andrade <pcpa@conectiva.com.br>
39 *          David Dawes <dawes@xfree86.org>
40 *          Adam Jackson <ajax@redhat.com>
41 *          Dave Airlie <airlied@redhat.com>
42 *          Michael Thayer <michael.thayer@oracle.com>
43 */
44
45#include "vboxvideo_drv.h"
46#include <VBoxVideoVBE.h>
47
48/* Basic definitions and functions needed by all drivers. */
49#include "xf86.h"
50/* For video memory mapping. */
51#include "xf86_OSproc.h"
52#if GET_ABI_MAJOR(ABI_VIDEODRV_VERSION) < 6
53/* PCI resources. */
54# include "xf86Resources.h"
55#endif
56/* Generic server linear frame-buffer APIs. */
57#include "fb.h"
58/* Colormap and visual handling. */
59#include "micmap.h"
60#include "xf86cmap.h"
61/* ShadowFB support */
62#include "shadowfb.h"
63/* VGA hardware functions for setting and restoring text mode */
64#include "vgaHW.h"
65#ifdef VBOXVIDEO_13
66/* X.org 1.3+ mode setting */
67# define _HAVE_STRING_ARCH_strsep /* bits/string2.h, __strsep_1c. */
68# include "xf86Crtc.h"
69# include "xf86Modes.h"
70/* For xf86RandR12GetOriginalVirtualSize(). */
71# include "xf86RandR12.h"
72#endif
73/* For setting the root window property. */
74#include "property.h"
75#include <X11/Xatom.h>
76
77#ifdef XORG_7X
78# include <stdlib.h>
79# include <string.h>
80# include <fcntl.h>
81# include <unistd.h>
82#endif
83
84/* Mandatory functions */
85
86static const OptionInfoRec * VBOXAvailableOptions(int chipid, int busid);
87static void VBOXIdentify(int flags);
88#ifndef PCIACCESS
89static Bool VBOXProbe(DriverPtr drv, int flags);
90#else
91static Bool VBOXPciProbe(DriverPtr drv, int entity_num,
92     struct pci_device *dev, intptr_t match_data);
93#endif
94static Bool VBOXPreInit(ScrnInfoPtr pScrn, int flags);
95static Bool VBOXScreenInit(ScreenPtr pScreen, int argc, char **argv);
96static Bool VBOXEnterVT(ScrnInfoPtr pScrn);
97static void VBOXLeaveVT(ScrnInfoPtr pScrn);
98static Bool VBOXCloseScreen(ScreenPtr pScreen);
99#ifndef VBOXVIDEO_13
100static Bool VBOXSaveScreen(ScreenPtr pScreen, int mode);
101#endif
102static Bool VBOXSwitchMode(ScrnInfoPtr pScrn, DisplayModePtr pMode);
103static void VBOXAdjustFrame(ScrnInfoPtr pScrn, int x, int y);
104static void VBOXFreeScreen(ScrnInfoPtr pScrn);
105#ifndef VBOXVIDEO_13
106static void VBOXDisplayPowerManagementSet(ScrnInfoPtr pScrn, int mode, int flags);
107#endif
108
109/* locally used functions */
110static Bool VBOXMapVidMem(ScrnInfoPtr pScrn);
111static void VBOXUnmapVidMem(ScrnInfoPtr pScrn);
112static void VBOXSaveMode(ScrnInfoPtr pScrn);
113static void VBOXRestoreMode(ScrnInfoPtr pScrn);
114static void setSizesAndCursorIntegration(ScrnInfoPtr pScrn, Bool fScreenInitTime);
115
116#ifndef XF86_SCRN_INTERFACE
117# define xf86ScreenToScrn(pScreen) xf86Screens[(pScreen)->myNum]
118# define xf86ScrnToScreen(pScrn) screenInfo.screens[(pScrn)->scrnIndex]
119#endif
120
121static inline void VBOXSetRec(ScrnInfoPtr pScrn)
122{
123    if (!pScrn->driverPrivate)
124    {
125        VBOXPtr pVBox = (VBOXPtr)xnfcalloc(sizeof(VBOXRec), 1);
126        pScrn->driverPrivate = pVBox;
127#if defined(VBOXVIDEO_13) && defined(RT_OS_LINUX)
128        pVBox->fdACPIDevices = -1;
129#endif
130    }
131}
132
133enum GenericTypes
134{
135    CHIP_VBOX_GENERIC
136};
137
138#ifdef PCIACCESS
139static const struct pci_id_match vbox_device_match[] = {
140    {
141        VBOX_VENDORID, VBOX_DEVICEID, PCI_MATCH_ANY, PCI_MATCH_ANY,
142        0, 0, 0
143    },
144
145    { 0, 0, 0 },
146};
147#endif
148
149/* Supported chipsets */
150static SymTabRec VBOXChipsets[] =
151{
152    {VBOX_DEVICEID, "vbox"},
153    {-1,            NULL}
154};
155
156static PciChipsets VBOXPCIchipsets[] = {
157  { VBOX_DEVICEID, VBOX_DEVICEID, RES_SHARED_VGA },
158  { -1,            -1,            RES_UNDEFINED },
159};
160
161/*
162 * This contains the functions needed by the server after loading the
163 * driver module.  It must be supplied, and gets added the driver list by
164 * the Module Setup function in the dynamic case.  In the static case a
165 * reference to this is compiled in, and this requires that the name of
166 * this DriverRec be an upper-case version of the driver name.
167 */
168
169#ifdef XORG_7X
170_X_EXPORT
171#endif
172DriverRec VBOXVIDEO = {
173    VBOX_VERSION,
174    VBOX_DRIVER_NAME,
175    VBOXIdentify,
176#ifdef PCIACCESS
177    NULL,
178#else
179    VBOXProbe,
180#endif
181    VBOXAvailableOptions,
182    NULL,
183    0,
184#ifdef XORG_7X
185    NULL,
186#endif
187#ifdef PCIACCESS
188    vbox_device_match,
189    VBOXPciProbe
190#endif
191};
192
193/* No options for now */
194static const OptionInfoRec VBOXOptions[] = {
195    { -1, NULL, OPTV_NONE, {0}, FALSE }
196};
197
198#ifndef XORG_7X
199/*
200 * List of symbols from other modules that this module references.  This
201 * list is used to tell the loader that it is OK for symbols here to be
202 * unresolved providing that it hasn't been told that they haven't been
203 * told that they are essential via a call to xf86LoaderReqSymbols() or
204 * xf86LoaderReqSymLists().  The purpose is this is to avoid warnings about
205 * unresolved symbols that are not required.
206 */
207static const char *fbSymbols[] = {
208    "fbPictureInit",
209    "fbScreenInit",
210    NULL
211};
212
213static const char *shadowfbSymbols[] = {
214    "ShadowFBInit2",
215    NULL
216};
217
218static const char *ramdacSymbols[] = {
219    "xf86DestroyCursorInfoRec",
220    "xf86InitCursor",
221    "xf86CreateCursorInfoRec",
222    NULL
223};
224
225static const char *vgahwSymbols[] = {
226    "vgaHWFreeHWRec",
227    "vgaHWGetHWRec",
228    "vgaHWGetIOBase",
229    "vgaHWGetIndex",
230    "vgaHWRestore",
231    "vgaHWSave",
232    "vgaHWSetStdFuncs",
233    NULL
234};
235#endif /* !XORG_7X */
236
237/** Resize the virtual framebuffer. */
238static Bool adjustScreenPixmap(ScrnInfoPtr pScrn, int width, int height)
239{
240    ScreenPtr pScreen = xf86ScrnToScreen(pScrn);
241    VBOXPtr pVBox = VBOXGetRec(pScrn);
242    int adjustedWidth = pScrn->bitsPerPixel == 16 ? (width + 1) & ~1 : width;
243    int cbLine = adjustedWidth * pScrn->bitsPerPixel / 8;
244    PixmapPtr pPixmap;
245
246    TRACE_LOG("width=%d, height=%d\n", width, height);
247    AssertMsg(width >= 0 && height >= 0, ("Invalid negative width (%d) or height (%d)\n", width, height));
248    if (pScreen == NULL)  /* Not yet initialised. */
249        return TRUE;
250    pPixmap = pScreen->GetScreenPixmap(pScreen);
251    AssertMsg(pPixmap != NULL, ("Failed to get the screen pixmap.\n"));
252    TRACE_LOG("pPixmap=%p adjustedWidth=%d height=%d pScrn->depth=%d pScrn->bitsPerPixel=%d cbLine=%d pVBox->base=%p pPixmap->drawable.width=%d pPixmap->drawable.height=%d\n",
253              (void *)pPixmap, adjustedWidth, height, pScrn->depth,
254              pScrn->bitsPerPixel, cbLine, pVBox->base,
255              pPixmap->drawable.width, pPixmap->drawable.height);
256    if (   adjustedWidth != pPixmap->drawable.width
257        || height != pPixmap->drawable.height)
258    {
259        if (   adjustedWidth > VBOX_VIDEO_MAX_VIRTUAL || height > VBOX_VIDEO_MAX_VIRTUAL
260            || (unsigned)cbLine * (unsigned)height >= pVBox->cbFBMax)
261        {
262            xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
263                       "Virtual framebuffer %dx%d too large.  For information, video memory: %u Kb.\n",
264                       adjustedWidth, height, (unsigned) pVBox->cbFBMax / 1024);
265            return FALSE;
266        }
267        if (pScrn->vtSema)
268            vbvxClearVRAM(pScrn, ((size_t)pScrn->virtualX) * pScrn->virtualY * (pScrn->bitsPerPixel / 8),
269                          ((size_t)adjustedWidth) * height * (pScrn->bitsPerPixel / 8));
270        pScreen->ModifyPixmapHeader(pPixmap, adjustedWidth, height, pScrn->depth, pScrn->bitsPerPixel, cbLine, pVBox->base);
271    }
272    pScrn->displayWidth = pScrn->virtualX = adjustedWidth;
273    pScrn->virtualY = height;
274    return TRUE;
275}
276
277#ifndef VBOXVIDEO_13
278/** Set a video mode to the hardware, RandR 1.1 version.
279 *
280 * Since we no longer do virtual frame buffers, adjust the screen pixmap
281 * dimensions to match.  The "override" parameters are for when we received a
282 * mode hint while switched to a virtual terminal.  In this case VBoxClient will
283 * have told us about the mode, but not yet been able to do a mode switch using
284 * RandR.  We solve this by setting the requested mode to the host but keeping
285 * the virtual frame-
286 * buffer matching what the X server expects. */
287static void setModeRandR11(ScrnInfoPtr pScrn, DisplayModePtr pMode, Bool fScreenInitTime, Bool fEnterVTTime,
288                           int cXOverRide, int cYOverRide)
289{
290    VBOXPtr pVBox = VBOXGetRec(pScrn);
291    struct vbvxFrameBuffer frameBuffer = { 0, 0, pMode->HDisplay, pMode->VDisplay, pScrn->bitsPerPixel};
292    int cXPhysical = cXOverRide > 0 ? min(cXOverRide, pMode->HDisplay) : pMode->HDisplay;
293    int cYPhysical = cYOverRide > 0 ? min(cYOverRide, pMode->VDisplay) : pMode->VDisplay;
294
295    pVBox->pScreens[0].aScreenLocation.cx = pMode->HDisplay;
296    pVBox->pScreens[0].aScreenLocation.cy = pMode->VDisplay;
297    if (fScreenInitTime)
298    {
299        /* The screen structure is not fully set up yet, so do not touch it. */
300        pScrn->displayWidth = pScrn->virtualX = pMode->HDisplay;
301        pScrn->virtualY = pMode->VDisplay;
302    }
303    else
304    {
305        xf86ScrnToScreen(pScrn)->width = pMode->HDisplay;
306        xf86ScrnToScreen(pScrn)->height = pMode->VDisplay;
307        /* This prevents a crash in CentOS 3.  I was unable to debug it to
308         * satisfaction, partly due to the lack of symbols.  My guess is that
309         * pScrn->ModifyPixmapHeader() expects certain things to be set up when
310         * it sees pScrn->vtSema set to true which are not quite done at this
311         * point of the VT switch. */
312        if (fEnterVTTime)
313            pScrn->vtSema = FALSE;
314        adjustScreenPixmap(pScrn, pMode->HDisplay, pMode->VDisplay);
315        if (fEnterVTTime)
316            pScrn->vtSema = TRUE;
317    }
318    if (pMode->HDisplay != 0 && pMode->VDisplay != 0 && pScrn->vtSema)
319        vbvxSetMode(pScrn, 0, cXPhysical, cYPhysical, 0, 0, true, true, &frameBuffer);
320    pScrn->currentMode = pMode;
321}
322#endif
323
324#ifdef VBOXVIDEO_13
325/* X.org 1.3+ mode-setting support ******************************************/
326
327/** Set a video mode to the hardware, RandR 1.2 version.  If this is the first
328 * screen, re-set the current mode for all others (the offset for the first
329 * screen is always treated as zero by the hardware, so all other screens need
330 * to be changed to compensate for any changes!).  The mode to set is taken
331 * from the X.Org Crtc structure. */
332static void setModeRandR12(ScrnInfoPtr pScrn, unsigned cScreen)
333{
334    VBOXPtr pVBox = VBOXGetRec(pScrn);
335    unsigned i;
336    struct vbvxFrameBuffer frameBuffer = { pVBox->pScreens[0].paCrtcs->x, pVBox->pScreens[0].paCrtcs->y, pScrn->virtualX,
337                                           pScrn->virtualY, pScrn->bitsPerPixel };
338    unsigned cFirst = cScreen;
339    unsigned cLast = cScreen != 0 ? cScreen + 1 : pVBox->cScreens;
340    int originalX, originalY;
341
342    /* Check that this code cannot trigger the resizing bug in X.Org Server 1.3.
343     * See the work-around in ScreenInit. */
344    xf86RandR12GetOriginalVirtualSize(pScrn, &originalX, &originalY);
345    AssertMsg(originalX == VBOX_VIDEO_MAX_VIRTUAL && originalY == VBOX_VIDEO_MAX_VIRTUAL, ("OriginalSize=%dx%d",
346               originalX, originalY));
347    for (i = cFirst; i < cLast; ++i)
348        if (pVBox->pScreens[i].paCrtcs->mode.HDisplay != 0 && pVBox->pScreens[i].paCrtcs->mode.VDisplay != 0 && pScrn->vtSema)
349            vbvxSetMode(pScrn, i, pVBox->pScreens[i].paCrtcs->mode.HDisplay, pVBox->pScreens[i].paCrtcs->mode.VDisplay,
350                        pVBox->pScreens[i].paCrtcs->x, pVBox->pScreens[i].paCrtcs->y, pVBox->pScreens[i].fPowerOn,
351                        pVBox->pScreens[i].paOutputs->status == XF86OutputStatusConnected, &frameBuffer);
352}
353
354/** Wrapper around setModeRandR12() to avoid exposing non-obvious semantics.
355 */
356static void setAllModesRandR12(ScrnInfoPtr pScrn)
357{
358    setModeRandR12(pScrn, 0);
359}
360
361/* For descriptions of these functions and structures, see
362   hw/xfree86/modes/xf86Crtc.h and hw/xfree86/modes/xf86Modes.h in the
363   X.Org source tree. */
364
365static Bool vbox_config_resize(ScrnInfoPtr pScrn, int cw, int ch)
366{
367    VBOXPtr pVBox = VBOXGetRec(pScrn);
368    Bool rc;
369    unsigned i;
370
371    TRACE_LOG("width=%d, height=%d\n", cw, ch);
372    rc = adjustScreenPixmap(pScrn, cw, ch);
373    /* Power-on all screens (the server expects this) and set the new pitch to them. */
374    for (i = 0; i < pVBox->cScreens; ++i)
375        pVBox->pScreens[i].fPowerOn = true;
376    setAllModesRandR12(pScrn);
377    vbvxSetSolarisMouseRange(cw, ch);
378    return rc;
379}
380
381static const xf86CrtcConfigFuncsRec VBOXCrtcConfigFuncs = {
382    vbox_config_resize
383};
384
385static void
386vbox_crtc_dpms(xf86CrtcPtr crtc, int mode)
387{
388    ScrnInfoPtr pScrn = crtc->scrn;
389    VBOXPtr pVBox = VBOXGetRec(pScrn);
390    unsigned cDisplay = (uintptr_t)crtc->driver_private;
391
392    TRACE_LOG("mode=%d\n", mode);
393    pVBox->pScreens[cDisplay].fPowerOn = (mode != DPMSModeOff);
394    setModeRandR12(pScrn, cDisplay);
395}
396
397static Bool
398vbox_crtc_lock (xf86CrtcPtr crtc)
399{ RT_NOREF(crtc); return FALSE; }
400
401
402/* We use this function to check whether the X server owns the active virtual
403 * terminal before attempting a mode switch, since the RandR extension isn't
404 * very dilligent here, which can mean crashes if we are unlucky.  This is
405 * not the way it the function is intended - it is meant for reporting modes
406 * which the hardware can't handle.  I hope that this won't confuse any clients
407 * connecting to us. */
408static Bool
409vbox_crtc_mode_fixup (xf86CrtcPtr crtc, DisplayModePtr mode,
410                      DisplayModePtr adjusted_mode)
411{ RT_NOREF(crtc, mode, adjusted_mode); return TRUE; }
412
413static void
414vbox_crtc_stub (xf86CrtcPtr crtc)
415{ RT_NOREF(crtc); }
416
417static void
418vbox_crtc_mode_set (xf86CrtcPtr crtc, DisplayModePtr mode,
419                    DisplayModePtr adjusted_mode, int x, int y)
420{
421    RT_NOREF(mode);
422    VBOXPtr pVBox = VBOXGetRec(crtc->scrn);
423    unsigned cDisplay = (uintptr_t)crtc->driver_private;
424
425    TRACE_LOG("name=%s, HDisplay=%d, VDisplay=%d, x=%d, y=%d\n", adjusted_mode->name,
426           adjusted_mode->HDisplay, adjusted_mode->VDisplay, x, y);
427    pVBox->pScreens[cDisplay].fPowerOn = true;
428    pVBox->pScreens[cDisplay].aScreenLocation.cx = adjusted_mode->HDisplay;
429    pVBox->pScreens[cDisplay].aScreenLocation.cy = adjusted_mode->VDisplay;
430    pVBox->pScreens[cDisplay].aScreenLocation.x = x;
431    pVBox->pScreens[cDisplay].aScreenLocation.y = y;
432    setModeRandR12(crtc->scrn, cDisplay);
433}
434
435static void
436vbox_crtc_gamma_set (xf86CrtcPtr crtc, CARD16 *red,
437                     CARD16 *green, CARD16 *blue, int size)
438{ RT_NOREF(crtc, red, green, blue, size); }
439
440static void *
441vbox_crtc_shadow_allocate (xf86CrtcPtr crtc, int width, int height)
442{ RT_NOREF(crtc, width, height); return NULL; }
443
444static const xf86CrtcFuncsRec VBOXCrtcFuncs = {
445    .dpms = vbox_crtc_dpms,
446    .save = NULL, /* These two are never called by the server. */
447    .restore = NULL,
448    .lock = vbox_crtc_lock,
449    .unlock = NULL, /* This will not be invoked if lock returns FALSE. */
450    .mode_fixup = vbox_crtc_mode_fixup,
451    .prepare = vbox_crtc_stub,
452    .mode_set = vbox_crtc_mode_set,
453    .commit = vbox_crtc_stub,
454    .gamma_set = vbox_crtc_gamma_set,
455    .shadow_allocate = vbox_crtc_shadow_allocate,
456    .shadow_create = NULL, /* These two should not be invoked if allocate
457                              returns NULL. */
458    .shadow_destroy = NULL,
459    .set_cursor_colors = NULL, /* We are still using the old cursor API. */
460    .set_cursor_position = NULL,
461    .show_cursor = NULL,
462    .hide_cursor = NULL,
463    .load_cursor_argb = NULL,
464    .destroy = vbox_crtc_stub
465};
466
467static void
468vbox_output_stub (xf86OutputPtr output)
469{ RT_NOREF(output); }
470
471static void
472vbox_output_dpms (xf86OutputPtr output, int mode)
473{
474    RT_NOREF(output, mode);
475}
476
477static int
478vbox_output_mode_valid (xf86OutputPtr output, DisplayModePtr mode)
479{
480    return MODE_OK;
481}
482
483static Bool
484vbox_output_mode_fixup (xf86OutputPtr output, DisplayModePtr mode,
485                        DisplayModePtr adjusted_mode)
486{ RT_NOREF(output, mode, adjusted_mode); return TRUE; }
487
488static void
489vbox_output_mode_set (xf86OutputPtr output, DisplayModePtr mode,
490                        DisplayModePtr adjusted_mode)
491{ RT_NOREF(output, mode, adjusted_mode); }
492
493static xf86OutputStatus
494vbox_output_detect (xf86OutputPtr output)
495{
496    ScrnInfoPtr pScrn = output->scrn;
497    VBOXPtr pVBox = VBOXGetRec(pScrn);
498    uint32_t iScreen = (uintptr_t)output->driver_private;
499    return   pVBox->pScreens[iScreen].afConnected
500           ? XF86OutputStatusConnected : XF86OutputStatusDisconnected;
501}
502
503static DisplayModePtr vbox_output_add_mode(VBOXPtr pVBox, DisplayModePtr *pModes, const char *pszName, int x, int y,
504                                           Bool isPreferred, Bool isUserDef)
505{
506    TRACE_LOG("pszName=%s, x=%d, y=%d\n", pszName ? pszName : "(null)", x, y);
507    DisplayModePtr pMode = xnfcalloc(1, sizeof(DisplayModeRec));
508    int cRefresh = 60;
509
510    pMode->status        = MODE_OK;
511    /* We don't ask the host whether it likes user defined modes,
512     * as we assume that the user really wanted that mode. */
513    pMode->type          = isUserDef ? M_T_USERDEF : M_T_BUILTIN;
514    if (isPreferred)
515        pMode->type     |= M_T_PREFERRED;
516    /* Older versions of VBox only support screen widths which are a multiple
517     * of 8 */
518    if (pVBox->fAnyX)
519        pMode->HDisplay  = x;
520    else
521        pMode->HDisplay  = x & ~7;
522    pMode->HSyncStart    = pMode->HDisplay + 2;
523    pMode->HSyncEnd      = pMode->HDisplay + 4;
524    pMode->HTotal        = pMode->HDisplay + 6;
525    pMode->VDisplay      = y;
526    pMode->VSyncStart    = pMode->VDisplay + 2;
527    pMode->VSyncEnd      = pMode->VDisplay + 4;
528    pMode->VTotal        = pMode->VDisplay + 6;
529    pMode->Clock         = pMode->HTotal * pMode->VTotal * cRefresh / 1000; /* kHz */
530    if (NULL == pszName) {
531        xf86SetModeDefaultName(pMode);
532    } else {
533        pMode->name          = xnfstrdup(pszName);
534    }
535    *pModes = xf86ModesAdd(*pModes, pMode);
536    return pMode;
537}
538
539static DisplayModePtr
540vbox_output_get_modes (xf86OutputPtr output)
541{
542    DisplayModePtr pModes = NULL;
543    DisplayModePtr pPreferred = NULL;
544    ScrnInfoPtr pScrn = output->scrn;
545    VBOXPtr pVBox = VBOXGetRec(pScrn);
546
547    TRACE_ENTRY();
548    uint32_t iScreen = (uintptr_t)output->driver_private;
549    pPreferred = vbox_output_add_mode(pVBox, &pModes, NULL,
550                         RT_CLAMP(pVBox->pScreens[iScreen].aPreferredSize.cx, VBOX_VIDEO_MIN_SIZE, VBOX_VIDEO_MAX_VIRTUAL),
551                         RT_CLAMP(pVBox->pScreens[iScreen].aPreferredSize.cy, VBOX_VIDEO_MIN_SIZE, VBOX_VIDEO_MAX_VIRTUAL),
552                         TRUE, FALSE);
553    vbox_output_add_mode(pVBox, &pModes, NULL, 2560, 1600, FALSE, FALSE);
554    vbox_output_add_mode(pVBox, &pModes, NULL, 2560, 1440, FALSE, FALSE);
555    vbox_output_add_mode(pVBox, &pModes, NULL, 2048, 1536, FALSE, FALSE);
556    vbox_output_add_mode(pVBox, &pModes, NULL, 1920, 1600, FALSE, FALSE);
557    vbox_output_add_mode(pVBox, &pModes, NULL, 1920, 1080, FALSE, FALSE);
558    vbox_output_add_mode(pVBox, &pModes, NULL, 1680, 1050, FALSE, FALSE);
559    vbox_output_add_mode(pVBox, &pModes, NULL, 1600, 1200, FALSE, FALSE);
560    vbox_output_add_mode(pVBox, &pModes, NULL, 1400, 1050, FALSE, FALSE);
561    vbox_output_add_mode(pVBox, &pModes, NULL, 1280, 1024, FALSE, FALSE);
562    vbox_output_add_mode(pVBox, &pModes, NULL, 1024, 768,  FALSE, FALSE);
563    vbox_output_add_mode(pVBox, &pModes, NULL, 800,  600,  FALSE, FALSE);
564    vbox_output_add_mode(pVBox, &pModes, NULL, 640,  480,  FALSE, FALSE);
565    VBOXEDIDSet(output, pPreferred);
566    TRACE_EXIT();
567    return pModes;
568}
569
570static const xf86OutputFuncsRec VBOXOutputFuncs = {
571    .create_resources = vbox_output_stub,
572    .dpms = vbox_output_dpms,
573    .save = NULL, /* These two are never called by the server. */
574    .restore = NULL,
575    .mode_valid = vbox_output_mode_valid,
576    .mode_fixup = vbox_output_mode_fixup,
577    .prepare = vbox_output_stub,
578    .commit = vbox_output_stub,
579    .mode_set = vbox_output_mode_set,
580    .detect = vbox_output_detect,
581    .get_modes = vbox_output_get_modes,
582#ifdef RANDR_12_INTERFACE
583     .set_property = NULL,
584#endif
585    .destroy = vbox_output_stub
586};
587#endif /* VBOXVIDEO_13 */
588
589/* Module loader interface */
590static MODULESETUPPROTO(vboxSetup);
591
592static XF86ModuleVersionInfo vboxVersionRec =
593{
594    VBOX_DRIVER_NAME,
595    "Oracle Corporation",
596    MODINFOSTRING1,
597    MODINFOSTRING2,
598#ifdef XORG_7X
599    XORG_VERSION_CURRENT,
600#else
601    XF86_VERSION_CURRENT,
602#endif
603    1,                          /* Module major version. Xorg-specific */
604    0,                          /* Module minor version. Xorg-specific */
605    1,                          /* Module patchlevel. Xorg-specific */
606    ABI_CLASS_VIDEODRV,         /* This is a video driver */
607    ABI_VIDEODRV_VERSION,
608    MOD_CLASS_VIDEODRV,
609    {0, 0, 0, 0}
610};
611
612/*
613 * This data is accessed by the loader.  The name must be the module name
614 * followed by "ModuleData".
615 */
616#ifdef XORG_7X
617_X_EXPORT
618#endif
619XF86ModuleData vboxvideoModuleData = { &vboxVersionRec, vboxSetup, NULL };
620
621static pointer
622vboxSetup(pointer Module, pointer Options, int *ErrorMajor, int *ErrorMinor)
623{
624    static Bool Initialised = FALSE;
625    RT_NOREF(Options, ErrorMinor);
626
627    if (!Initialised)
628    {
629        Initialised = TRUE;
630#ifdef PCIACCESS
631        xf86AddDriver(&VBOXVIDEO, Module, HaveDriverFuncs);
632#else
633        xf86AddDriver(&VBOXVIDEO, Module, 0);
634#endif
635#ifndef XORG_7X
636        LoaderRefSymLists(fbSymbols,
637                          shadowfbSymbols,
638                          ramdacSymbols,
639                          vgahwSymbols,
640                          NULL);
641#endif
642        xf86Msg(X_CONFIG, "Load address of symbol \"VBOXVIDEO\" is %p\n",
643                (void *)&VBOXVIDEO);
644        return (pointer)TRUE;
645    }
646
647    if (ErrorMajor)
648        *ErrorMajor = LDR_ONCEONLY;
649    return (NULL);
650}
651
652
653static const OptionInfoRec *
654VBOXAvailableOptions(int chipid, int busid)
655{
656    RT_NOREF(chipid, busid);
657    return (VBOXOptions);
658}
659
660static void
661VBOXIdentify(int flags)
662{
663    RT_NOREF(flags);
664    xf86PrintChipsets(VBOX_NAME, "guest driver for VirtualBox", VBOXChipsets);
665}
666
667#ifndef XF86_SCRN_INTERFACE
668# define SCRNINDEXAPI(pfn) pfn ## Index
669static Bool VBOXScreenInitIndex(int scrnIndex, ScreenPtr pScreen, int argc, char **argv)
670{
671    RT_NOREF(scrnIndex);
672    return VBOXScreenInit(pScreen, argc, argv);
673}
674
675static Bool VBOXEnterVTIndex(int scrnIndex, int flags)
676{ RT_NOREF(flags); return VBOXEnterVT(xf86Screens[scrnIndex]); }
677
678static void VBOXLeaveVTIndex(int scrnIndex, int flags)
679{ RT_NOREF(flags); VBOXLeaveVT(xf86Screens[scrnIndex]); }
680
681static Bool VBOXCloseScreenIndex(int scrnIndex, ScreenPtr pScreen)
682{ RT_NOREF(scrnIndex); return VBOXCloseScreen(pScreen); }
683
684static Bool VBOXSwitchModeIndex(int scrnIndex, DisplayModePtr pMode, int flags)
685{ RT_NOREF(flags); return VBOXSwitchMode(xf86Screens[scrnIndex], pMode); }
686
687static void VBOXAdjustFrameIndex(int scrnIndex, int x, int y, int flags)
688{ RT_NOREF(flags); VBOXAdjustFrame(xf86Screens[scrnIndex], x, y); }
689
690static void VBOXFreeScreenIndex(int scrnIndex, int flags)
691{ RT_NOREF(flags); VBOXFreeScreen(xf86Screens[scrnIndex]); }
692# else
693# define SCRNINDEXAPI(pfn) pfn
694#endif /* XF86_SCRN_INTERFACE */
695
696static void setScreenFunctions(ScrnInfoPtr pScrn, xf86ProbeProc pfnProbe)
697{
698    pScrn->driverVersion = VBOX_VERSION;
699    pScrn->driverName    = VBOX_DRIVER_NAME;
700    pScrn->name          = VBOX_NAME;
701    pScrn->Probe         = pfnProbe;
702    pScrn->PreInit       = VBOXPreInit;
703    pScrn->ScreenInit    = SCRNINDEXAPI(VBOXScreenInit);
704    pScrn->SwitchMode    = SCRNINDEXAPI(VBOXSwitchMode);
705    pScrn->AdjustFrame   = SCRNINDEXAPI(VBOXAdjustFrame);
706    pScrn->EnterVT       = SCRNINDEXAPI(VBOXEnterVT);
707    pScrn->LeaveVT       = SCRNINDEXAPI(VBOXLeaveVT);
708    pScrn->FreeScreen    = SCRNINDEXAPI(VBOXFreeScreen);
709}
710
711/*
712 * One of these functions is called once, at the start of the first server
713 * generation to do a minimal probe for supported hardware.
714 */
715
716#ifdef PCIACCESS
717static Bool
718VBOXPciProbe(DriverPtr drv, int entity_num, struct pci_device *dev,
719             intptr_t match_data)
720{
721    ScrnInfoPtr pScrn;
722    int drmFd;
723
724    TRACE_ENTRY();
725
726    drmFd = open("/dev/dri/card0", O_RDWR, 0);
727    if (drmFd >= 0)
728    {
729        xf86Msg(X_INFO, "vboxvideo: kernel driver found, not loading.\n");
730        close(drmFd);
731        return FALSE;
732    }
733    /* It is safe to call this, as the X server enables I/O access before
734     * calling the probe call-backs. */
735    if (!xf86EnableIO())
736    {
737        xf86Msg(X_INFO, "vboxvideo: this driver requires direct hardware access.  You may wish to use the kernel driver instead.\n");
738        return FALSE;
739    }
740    pScrn = xf86ConfigPciEntity(NULL, 0, entity_num, VBOXPCIchipsets,
741                                NULL, NULL, NULL, NULL, NULL);
742    if (pScrn != NULL) {
743        VBOXPtr pVBox;
744
745        VBOXSetRec(pScrn);
746        pVBox = VBOXGetRec(pScrn);
747        if (!pVBox)
748            return FALSE;
749        setScreenFunctions(pScrn, NULL);
750        pVBox->pciInfo = dev;
751    }
752
753    TRACE_LOG("returning %s\n", pScrn == NULL ? "false" : "true");
754    return (pScrn != NULL);
755}
756#endif
757
758#ifndef PCIACCESS
759static Bool
760VBOXProbe(DriverPtr drv, int flags)
761{
762    Bool foundScreen = FALSE;
763    int numDevSections;
764    GDevPtr *devSections;
765
766    /*
767     * Find the config file Device sections that match this
768     * driver, and return if there are none.
769     */
770    if ((numDevSections = xf86MatchDevice(VBOX_NAME,
771                      &devSections)) <= 0)
772    return (FALSE);
773
774    /* PCI BUS */
775    if (xf86GetPciVideoInfo())
776    {
777        int numUsed;
778        int *usedChips;
779        int i;
780        numUsed = xf86MatchPciInstances(VBOX_NAME, VBOX_VENDORID,
781                        VBOXChipsets, VBOXPCIchipsets,
782                        devSections, numDevSections,
783                        drv, &usedChips);
784        if (numUsed > 0)
785        {
786            if (flags & PROBE_DETECT)
787                foundScreen = TRUE;
788            else
789                for (i = 0; i < numUsed; i++)
790                {
791                    ScrnInfoPtr pScrn = NULL;
792                    /* Allocate a ScrnInfoRec  */
793                    if ((pScrn = xf86ConfigPciEntity(pScrn,0,usedChips[i],
794                                     VBOXPCIchipsets,NULL,
795                                     NULL,NULL,NULL,NULL)))
796                    {
797                        setScreenFunctions(pScrn, VBOXProbe);
798                        foundScreen = TRUE;
799                    }
800                }
801            free(usedChips);
802        }
803    }
804    free(devSections);
805    return (foundScreen);
806}
807#endif
808
809
810/*
811 * QUOTE from the XFree86 DESIGN document:
812 *
813 * The purpose of this function is to find out all the information
814 * required to determine if the configuration is usable, and to initialise
815 * those parts of the ScrnInfoRec that can be set once at the beginning of
816 * the first server generation.
817 *
818 * (...)
819 *
820 * This includes probing for video memory, clocks, ramdac, and all other
821 * HW info that is needed. It includes determining the depth/bpp/visual
822 * and related info. It includes validating and determining the set of
823 * video modes that will be used (and anything that is required to
824 * determine that).
825 *
826 * This information should be determined in the least intrusive way
827 * possible. The state of the HW must remain unchanged by this function.
828 * Although video memory (including MMIO) may be mapped within this
829 * function, it must be unmapped before returning.
830 *
831 * END QUOTE
832 */
833
834static Bool
835VBOXPreInit(ScrnInfoPtr pScrn, int flags)
836{
837    VBOXPtr pVBox;
838    Gamma gzeros = {0.0, 0.0, 0.0};
839    rgb rzeros = {0, 0, 0};
840
841    TRACE_ENTRY();
842    /* Are we really starting the server, or is this just a dummy run? */
843    if (flags & PROBE_DETECT)
844        return (FALSE);
845
846    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
847               "VirtualBox guest additions video driver version %d.%d\n",
848               VBOX_VERSION_MAJOR, VBOX_VERSION_MINOR);
849
850    /* The ramdac module is needed for the hardware cursor. */
851    if (!xf86LoadSubModule(pScrn, "ramdac"))
852        return FALSE;
853
854    /* The framebuffer module. */
855    if (!xf86LoadSubModule(pScrn, "fb"))
856        return (FALSE);
857
858    if (!xf86LoadSubModule(pScrn, "shadowfb"))
859        return FALSE;
860
861    if (!xf86LoadSubModule(pScrn, "vgahw"))
862        return FALSE;
863
864    /* Get our private data from the ScrnInfoRec structure. */
865    VBOXSetRec(pScrn);
866    pVBox = VBOXGetRec(pScrn);
867    if (!pVBox)
868        return FALSE;
869
870    /* Entity information seems to mean bus information. */
871    pVBox->pEnt = xf86GetEntityInfo(pScrn->entityList[0]);
872
873#ifndef PCIACCESS
874    if (pVBox->pEnt->location.type != BUS_PCI)
875        return FALSE;
876
877    pVBox->pciInfo = xf86GetPciInfoForEntity(pVBox->pEnt->index);
878    pVBox->pciTag = pciTag(pVBox->pciInfo->bus,
879                           pVBox->pciInfo->device,
880                           pVBox->pciInfo->func);
881#endif
882
883    /* Set up our ScrnInfoRec structure to describe our virtual
884       capabilities to X. */
885
886    pScrn->chipset = "vbox";
887    /** @note needed during colourmap initialisation */
888    pScrn->rgbBits = 8;
889
890    /* Let's create a nice, capable virtual monitor. */
891    pScrn->monitor = pScrn->confScreen->monitor;
892    pScrn->monitor->DDC = NULL;
893    pScrn->monitor->nHsync = 1;
894    pScrn->monitor->hsync[0].lo = 1;
895    pScrn->monitor->hsync[0].hi = 10000;
896    pScrn->monitor->nVrefresh = 1;
897    pScrn->monitor->vrefresh[0].lo = 1;
898    pScrn->monitor->vrefresh[0].hi = 100;
899
900    pScrn->progClock = TRUE;
901
902    /* Using the PCI information caused problems with non-powers-of-two
903       sized video RAM configurations */
904    pVBox->cbFBMax = VBoxVideoGetVRAMSize();
905    pScrn->videoRam = pVBox->cbFBMax / 1024;
906
907    /* Check if the chip restricts horizontal resolution or not. */
908    pVBox->fAnyX = VBoxVideoAnyWidthAllowed();
909
910    /* Set up clock information that will support all modes we need. */
911    pScrn->clockRanges = xnfcalloc(sizeof(ClockRange), 1);
912    pScrn->clockRanges->minClock = 1000;
913    pScrn->clockRanges->maxClock = 1000000000;
914    pScrn->clockRanges->clockIndex = -1;
915    pScrn->clockRanges->ClockMulFactor = 1;
916    pScrn->clockRanges->ClockDivFactor = 1;
917
918    if (!xf86SetDepthBpp(pScrn, 24, 0, 0, Support32bppFb))
919        return FALSE;
920    /* We only support 16 and 24 bits depth (i.e. 16 and 32bpp) */
921    if (pScrn->bitsPerPixel != 32 && pScrn->bitsPerPixel != 16)
922    {
923        xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
924                   "The VBox additions only support 16 and 32bpp graphics modes\n");
925        return FALSE;
926    }
927    xf86PrintDepthBpp(pScrn);
928    vboxAddModes(pScrn);
929
930#ifdef VBOXVIDEO_13
931    pScrn->virtualX = VBOX_VIDEO_MAX_VIRTUAL;
932    pScrn->virtualY = VBOX_VIDEO_MAX_VIRTUAL;
933#else
934    /* We don't validate with xf86ValidateModes and xf86PruneModes as we
935     * already know what we like and what we don't. */
936
937    pScrn->currentMode = pScrn->modes;
938
939    /* Set the right virtual resolution. */
940    pScrn->virtualX = pScrn->bitsPerPixel == 16 ? (pScrn->currentMode->HDisplay + 1) & ~1 : pScrn->currentMode->HDisplay;
941    pScrn->virtualY = pScrn->currentMode->VDisplay;
942
943#endif /* !VBOXVIDEO_13 */
944
945    pScrn->displayWidth = pScrn->virtualX;
946
947    xf86PrintModes(pScrn);
948
949    /* VGA hardware initialisation */
950    if (!vgaHWGetHWRec(pScrn))
951        return FALSE;
952    /* Must be called before any VGA registers are saved or restored */
953    vgaHWSetStdFuncs(VGAHWPTR(pScrn));
954    vgaHWGetIOBase(VGAHWPTR(pScrn));
955
956    /* Colour weight - we always call this, since we are always in
957       truecolour. */
958    if (!xf86SetWeight(pScrn, rzeros, rzeros))
959        return (FALSE);
960
961    /* visual init */
962    if (!xf86SetDefaultVisual(pScrn, -1))
963        return (FALSE);
964
965    xf86SetGamma(pScrn, gzeros);
966
967    /* Set the DPI.  Perhaps we should read this from the host? */
968    xf86SetDpi(pScrn, 96, 96);
969
970    if (pScrn->memPhysBase == 0) {
971#ifdef PCIACCESS
972        pScrn->memPhysBase = pVBox->pciInfo->regions[0].base_addr;
973#else
974        pScrn->memPhysBase = pVBox->pciInfo->memBase[0];
975#endif
976        pScrn->fbOffset = 0;
977    }
978
979    TRACE_EXIT();
980    return (TRUE);
981}
982
983/**
984 * Dummy function for setting the colour palette, which we actually never
985 * touch.  However, the server still requires us to provide this.
986 */
987static void
988vboxLoadPalette(ScrnInfoPtr pScrn, int numColors, int *indices,
989          LOCO *colors, VisualPtr pVisual)
990{
991    RT_NOREF(pScrn, numColors, indices, colors, pVisual);
992}
993
994/** Set the graphics and guest cursor support capabilities to the host if
995 *  the user-space helper is running. */
996static void updateGraphicsCapability(ScrnInfoPtr pScrn, Bool hasVT)
997{
998    VBOXPtr pVBox = VBOXGetRec(pScrn);
999
1000    if (!pVBox->fHaveHGSMIModeHints)
1001        return;
1002    VBoxHGSMISendCapsInfo(&pVBox->guestCtx,   hasVT
1003                                            ? VBVACAPS_VIDEO_MODE_HINTS | VBVACAPS_DISABLE_CURSOR_INTEGRATION
1004                                            : VBVACAPS_DISABLE_CURSOR_INTEGRATION);
1005}
1006
1007#ifndef VBOXVIDEO_13
1008
1009#define PREFERRED_MODE_ATOM_NAME "VBOXVIDEO_PREFERRED_MODE"
1010
1011static void setSizesRandR11(ScrnInfoPtr pScrn)
1012{
1013    VBOXPtr pVBox = VBOXGetRec(pScrn);
1014    DisplayModePtr pNewMode;
1015    int32_t propertyValue;
1016
1017    pNewMode = pScrn->modes != pScrn->currentMode ? pScrn->modes : pScrn->modes->next;
1018    pNewMode->HDisplay = RT_CLAMP(pVBox->pScreens[0].aPreferredSize.cx, VBOX_VIDEO_MIN_SIZE, VBOX_VIDEO_MAX_VIRTUAL);
1019    pNewMode->VDisplay = RT_CLAMP(pVBox->pScreens[0].aPreferredSize.cy, VBOX_VIDEO_MIN_SIZE, VBOX_VIDEO_MAX_VIRTUAL);
1020    propertyValue = (pNewMode->HDisplay << 16) + pNewMode->VDisplay;
1021    ChangeWindowProperty(ROOT_WINDOW(pScrn), MakeAtom(PREFERRED_MODE_ATOM_NAME,
1022                         sizeof(PREFERRED_MODE_ATOM_NAME) - 1, TRUE), XA_INTEGER, 32,
1023                         PropModeReplace, 1, &propertyValue, TRUE);
1024}
1025
1026#endif
1027
1028static void reprobeCursor(ScrnInfoPtr pScrn)
1029{
1030    if (ROOT_WINDOW(pScrn) == NULL)
1031        return;
1032#ifdef XF86_SCRN_INTERFACE
1033    pScrn->EnableDisableFBAccess(pScrn, FALSE);
1034    pScrn->EnableDisableFBAccess(pScrn, TRUE);
1035#else
1036    pScrn->EnableDisableFBAccess(pScrn->scrnIndex, FALSE);
1037    pScrn->EnableDisableFBAccess(pScrn->scrnIndex, TRUE);
1038#endif
1039}
1040
1041static void setSizesAndCursorIntegration(ScrnInfoPtr pScrn, Bool fScreenInitTime)
1042{
1043    RT_NOREF(fScreenInitTime);
1044    TRACE_LOG("fScreenInitTime=%d\n", (int)fScreenInitTime);
1045#ifdef VBOXVIDEO_13
1046# if GET_ABI_MAJOR(ABI_VIDEODRV_VERSION) >= 5
1047    RRGetInfo(xf86ScrnToScreen(pScrn), TRUE);
1048# else
1049    RRGetInfo(xf86ScrnToScreen(pScrn));
1050# endif
1051#else
1052    setSizesRandR11(pScrn);
1053#endif
1054    /* This calls EnableDisableFBAccess(), so only use when switched in. */
1055    if (pScrn->vtSema)
1056        reprobeCursor(pScrn);
1057}
1058
1059/* We update the size hints from the X11 property set by VBoxClient every time
1060 * that the X server goes to sleep (to catch the property change request).
1061 * Although this is far more often than necessary it should not have real-life
1062 * performance consequences and allows us to simplify the code quite a bit. */
1063static void vboxBlockHandler(pointer pData,
1064#if GET_ABI_MAJOR(ABI_VIDEODRV_VERSION) < 23
1065                             OSTimePtr pTimeout,
1066                             pointer pReadmask
1067#else
1068                             void *pTimeout
1069#endif
1070                  )
1071{
1072    ScrnInfoPtr pScrn = (ScrnInfoPtr)pData;
1073    Bool fNeedUpdate = false;
1074
1075    RT_NOREF(pTimeout);
1076#if GET_ABI_MAJOR(ABI_VIDEODRV_VERSION) < 23
1077    RT_NOREF(pReadmask);
1078#endif
1079    if (pScrn->vtSema)
1080        vbvxReadSizesAndCursorIntegrationFromHGSMI(pScrn, &fNeedUpdate);
1081    if (fNeedUpdate)
1082        setSizesAndCursorIntegration(pScrn, false);
1083}
1084
1085/*
1086 * QUOTE from the XFree86 DESIGN document:
1087 *
1088 * This is called at the start of each server generation.
1089 *
1090 * (...)
1091 *
1092 * Decide which operations need to be placed under resource access
1093 * control. (...) Map any video memory or other memory regions. (...)
1094 * Save the video card state. (...) Initialise the initial video
1095 * mode.
1096 *
1097 * End QUOTE.
1098 */
1099static Bool VBOXScreenInit(ScreenPtr pScreen, int argc, char **argv)
1100{
1101    ScrnInfoPtr pScrn = xf86ScreenToScrn(pScreen);
1102    VBOXPtr pVBox = VBOXGetRec(pScrn);
1103    VisualPtr visual;
1104    RT_NOREF(argc, argv);
1105
1106    TRACE_ENTRY();
1107
1108    if (!VBOXMapVidMem(pScrn))
1109        return (FALSE);
1110
1111    /* save current video state */
1112    VBOXSaveMode(pScrn);
1113
1114    /* mi layer - reset the visual list (?)*/
1115    miClearVisualTypes();
1116    if (!miSetVisualTypes(pScrn->depth, TrueColorMask,
1117                          pScrn->rgbBits, TrueColor))
1118        return (FALSE);
1119    if (!miSetPixmapDepths())
1120        return (FALSE);
1121
1122    if (!fbScreenInit(pScreen, pVBox->base,
1123                      pScrn->virtualX, pScrn->virtualY,
1124                      pScrn->xDpi, pScrn->yDpi,
1125                      pScrn->displayWidth, pScrn->bitsPerPixel))
1126        return (FALSE);
1127
1128    /* Fixup RGB ordering */
1129    /** @note the X server uses this even in true colour. */
1130    visual = pScreen->visuals + pScreen->numVisuals;
1131    while (--visual >= pScreen->visuals) {
1132        if ((visual->class | DynamicClass) == DirectColor) {
1133            visual->offsetRed   = pScrn->offset.red;
1134            visual->offsetGreen = pScrn->offset.green;
1135            visual->offsetBlue  = pScrn->offset.blue;
1136            visual->redMask     = pScrn->mask.red;
1137            visual->greenMask   = pScrn->mask.green;
1138            visual->blueMask    = pScrn->mask.blue;
1139        }
1140    }
1141
1142    /* must be after RGB ordering fixed */
1143    fbPictureInit(pScreen, 0, 0);
1144
1145    xf86SetBlackWhitePixels(pScreen);
1146    pScrn->vtSema = TRUE;
1147
1148#if defined(VBOXVIDEO_13) && defined(RT_OS_LINUX)
1149    vbvxSetUpLinuxACPI(pScreen);
1150#endif
1151
1152    if (!VBoxHGSMIIsSupported())
1153    {
1154        xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Graphics device too old to support.\n");
1155        return FALSE;
1156    }
1157    vbvxSetUpHGSMIHeapInGuest(pVBox, pScrn->videoRam * 1024);
1158    pVBox->cScreens = VBoxHGSMIGetMonitorCount(&pVBox->guestCtx);
1159    pVBox->pScreens = xnfcalloc(pVBox->cScreens, sizeof(*pVBox->pScreens));
1160    pVBox->paVBVAModeHints = xnfcalloc(pVBox->cScreens, sizeof(*pVBox->paVBVAModeHints));
1161    xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Requested monitor count: %u\n", pVBox->cScreens);
1162    vboxEnableVbva(pScrn);
1163    /* Set up the dirty rectangle handler.  It will be added into a function
1164     * chain and gets removed when the screen is cleaned up. */
1165    if (ShadowFBInit2(pScreen, NULL, vbvxHandleDirtyRect) != TRUE)
1166        return FALSE;
1167    VBoxInitialiseSizeHints(pScrn);
1168
1169#ifdef VBOXVIDEO_13
1170    /* Initialise CRTC and output configuration for use with randr1.2. */
1171    xf86CrtcConfigInit(pScrn, &VBOXCrtcConfigFuncs);
1172
1173    {
1174        uint32_t i;
1175
1176        for (i = 0; i < pVBox->cScreens; ++i)
1177        {
1178            char szOutput[256];
1179
1180            /* Setup our virtual CRTCs. */
1181            pVBox->pScreens[i].paCrtcs = xf86CrtcCreate(pScrn, &VBOXCrtcFuncs);
1182            pVBox->pScreens[i].paCrtcs->driver_private = (void *)(uintptr_t)i;
1183
1184            /* Set up our virtual outputs. */
1185            snprintf(szOutput, sizeof(szOutput), "VGA-%u", i);
1186            pVBox->pScreens[i].paOutputs
1187                = xf86OutputCreate(pScrn, &VBOXOutputFuncs, szOutput);
1188
1189            /* We are not interested in the monitor section in the
1190             * configuration file. */
1191            xf86OutputUseScreenMonitor(pVBox->pScreens[i].paOutputs, FALSE);
1192            pVBox->pScreens[i].paOutputs->possible_crtcs = 1 << i;
1193            pVBox->pScreens[i].paOutputs->possible_clones = 0;
1194            pVBox->pScreens[i].paOutputs->driver_private = (void *)(uintptr_t)i;
1195            TRACE_LOG("Created crtc (%p) and output %s (%p)\n",
1196                      (void *)pVBox->pScreens[i].paCrtcs, szOutput,
1197                      (void *)pVBox->pScreens[i].paOutputs);
1198        }
1199    }
1200
1201    /* Set a sane minimum and maximum mode size to match what the hardware
1202     * supports. */
1203    xf86CrtcSetSizeRange(pScrn, VBOX_VIDEO_MIN_SIZE, VBOX_VIDEO_MIN_SIZE, VBOX_VIDEO_MAX_VIRTUAL, VBOX_VIDEO_MAX_VIRTUAL);
1204
1205    /* Now create our initial CRTC/output configuration. */
1206    if (!xf86InitialConfiguration(pScrn, TRUE)) {
1207        xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Initial CRTC configuration failed!\n");
1208        return (FALSE);
1209    }
1210
1211    /* Work around a bug in the original X server modesetting code, which took
1212     * the first valid values set to these two as maxima over the server
1213     * lifetime.  This bug was introduced on Feb 15 2007 and was fixed in commit
1214     * fa877d7f three months later, so it was present in X.Org Server 1.3. */
1215    pScrn->virtualX = VBOX_VIDEO_MAX_VIRTUAL;
1216    pScrn->virtualY = VBOX_VIDEO_MAX_VIRTUAL;
1217
1218    /* Initialise randr 1.2 mode-setting functions. */
1219    if (!xf86CrtcScreenInit(pScreen)) {
1220        return FALSE;
1221    }
1222
1223    /* set first video mode */
1224    if (!xf86SetDesiredModes(pScrn)) {
1225        return FALSE;
1226    }
1227#else  /* !VBOXVIDEO_13 */
1228    /* set first video mode */
1229    setModeRandR11(pScrn, pScrn->currentMode, true, false, 0, 0);
1230#endif /* !VBOXVIDEO_13 */
1231
1232    /* Say that we support graphics. */
1233    updateGraphicsCapability(pScrn, TRUE);
1234
1235#if GET_ABI_MAJOR(ABI_VIDEODRV_VERSION) >= 23
1236# define WakeupHandlerProcPtr ServerWakeupHandlerProcPtr
1237#endif
1238
1239    /* Register block and wake-up handlers for getting new screen size hints. */
1240    RegisterBlockAndWakeupHandlers(vboxBlockHandler, (WakeupHandlerProcPtr)NoopDDA, (pointer)pScrn);
1241
1242    /* software cursor */
1243    miDCInitialize(pScreen, xf86GetPointerScreenFuncs());
1244
1245    /* colourmap code */
1246    if (!miCreateDefColormap(pScreen))
1247        return (FALSE);
1248
1249    if(!xf86HandleColormaps(pScreen, 256, 8, vboxLoadPalette, NULL, 0))
1250        return (FALSE);
1251
1252    pVBox->CloseScreen = pScreen->CloseScreen;
1253    pScreen->CloseScreen = SCRNINDEXAPI(VBOXCloseScreen);
1254#ifdef VBOXVIDEO_13
1255    pScreen->SaveScreen = xf86SaveScreen;
1256#else
1257    pScreen->SaveScreen = VBOXSaveScreen;
1258#endif
1259
1260#ifdef VBOXVIDEO_13
1261    xf86DPMSInit(pScreen, xf86DPMSSet, 0);
1262#else
1263    /* We probably do want to support power management - even if we just use
1264       a dummy function. */
1265    xf86DPMSInit(pScreen, VBOXDisplayPowerManagementSet, 0);
1266#endif
1267
1268    /* Report any unused options (only for the first generation) */
1269    if (serverGeneration == 1)
1270        xf86ShowUnusedOptions(pScrn->scrnIndex, pScrn->options);
1271
1272    if (vbvxCursorInit(pScreen) != TRUE)
1273        xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1274                   "Unable to start the VirtualBox mouse pointer integration with the host system.\n");
1275
1276    return (TRUE);
1277}
1278
1279#define NO_VT_ATOM_NAME "VBOXVIDEO_NO_VT"
1280
1281static Bool VBOXEnterVT(ScrnInfoPtr pScrn)
1282{
1283    VBOXPtr pVBox = VBOXGetRec(pScrn);
1284#ifndef VBOXVIDEO_13
1285    /* If we got a mode request while we were switched out, temporarily override
1286     * the physical mode set to the device while keeping things consistent from
1287     * the server's point of view. */
1288    int cXOverRide = RT_CLAMP(pVBox->pScreens[0].aPreferredSize.cx, VBOX_VIDEO_MIN_SIZE, VBOX_VIDEO_MAX_VIRTUAL);
1289    int cYOverRide = RT_CLAMP(pVBox->pScreens[0].aPreferredSize.cy, VBOX_VIDEO_MIN_SIZE, VBOX_VIDEO_MAX_VIRTUAL);
1290#endif
1291
1292    TRACE_ENTRY();
1293    vbvxSetUpHGSMIHeapInGuest(pVBox, pScrn->videoRam * 1024);
1294    vboxEnableVbva(pScrn);
1295    /* Re-set video mode */
1296#ifdef VBOXVIDEO_13
1297    if (!xf86SetDesiredModes(pScrn)) {
1298        return FALSE;
1299    }
1300#else
1301    setModeRandR11(pScrn, pScrn->currentMode, false, true, cXOverRide, cYOverRide);
1302    DeleteProperty(ROOT_WINDOW(pScrn), MakeAtom(NO_VT_ATOM_NAME, sizeof(NO_VT_ATOM_NAME) - 1, TRUE));
1303#endif
1304    updateGraphicsCapability(pScrn, TRUE);
1305    return TRUE;
1306}
1307
1308static void VBOXLeaveVT(ScrnInfoPtr pScrn)
1309{
1310#ifdef VBOXVIDEO_13
1311    VBOXPtr pVBox = VBOXGetRec(pScrn);
1312    unsigned i;
1313#else
1314    int32_t propertyValue = 0;
1315#endif
1316
1317    TRACE_ENTRY();
1318#ifdef VBOXVIDEO_13
1319    for (i = 0; i < pVBox->cScreens; ++i)
1320        vbox_crtc_dpms(pVBox->pScreens[i].paCrtcs, DPMSModeOff);
1321#else
1322    ChangeWindowProperty(ROOT_WINDOW(pScrn), MakeAtom(NO_VT_ATOM_NAME, sizeof(NO_VT_ATOM_NAME) - 1, FALSE), XA_INTEGER, 32,
1323                         PropModeReplace, 1, &propertyValue, TRUE);
1324#endif
1325    updateGraphicsCapability(pScrn, FALSE);
1326    vboxDisableVbva(pScrn);
1327    vbvxClearVRAM(pScrn, ((size_t)pScrn->virtualX) * pScrn->virtualY * (pScrn->bitsPerPixel / 8), 0);
1328    VBOXRestoreMode(pScrn);
1329    TRACE_EXIT();
1330}
1331
1332static Bool VBOXCloseScreen(ScreenPtr pScreen)
1333{
1334    ScrnInfoPtr pScrn = xf86ScreenToScrn(pScreen);
1335    VBOXPtr pVBox = VBOXGetRec(pScrn);
1336    BOOL ret;
1337
1338    if (pScrn->vtSema)
1339    {
1340#ifdef VBOXVIDEO_13
1341        unsigned i;
1342
1343        for (i = 0; i < pVBox->cScreens; ++i)
1344            vbox_crtc_dpms(pVBox->pScreens[i].paCrtcs, DPMSModeOff);
1345#endif
1346        vboxDisableVbva(pScrn);
1347        vbvxClearVRAM(pScrn, ((size_t)pScrn->virtualX) * pScrn->virtualY * (pScrn->bitsPerPixel / 8), 0);
1348    }
1349    if (pScrn->vtSema)
1350        VBOXRestoreMode(pScrn);
1351    if (pScrn->vtSema)
1352        VBOXUnmapVidMem(pScrn);
1353    pScrn->vtSema = FALSE;
1354
1355    vbvxCursorTerm(pVBox);
1356
1357    pScreen->CloseScreen = pVBox->CloseScreen;
1358#if defined(VBOXVIDEO_13) && defined(RT_OS_LINUX)
1359    vbvxCleanUpLinuxACPI(pScreen);
1360#endif
1361#ifndef XF86_SCRN_INTERFACE
1362    ret = pScreen->CloseScreen(pScreen->myNum, pScreen);
1363#else
1364    ret = pScreen->CloseScreen(pScreen);
1365#endif
1366    return ret;
1367}
1368
1369static Bool VBOXSwitchMode(ScrnInfoPtr pScrn, DisplayModePtr pMode)
1370{
1371    Bool rc = TRUE;
1372
1373    TRACE_LOG("HDisplay=%d, VDisplay=%d\n", pMode->HDisplay, pMode->VDisplay);
1374#ifdef VBOXVIDEO_13
1375    rc = xf86SetSingleMode(pScrn, pMode, RR_Rotate_0);
1376#else
1377    setModeRandR11(pScrn, pMode, false, false, 0, 0);
1378#endif
1379    TRACE_LOG("returning %s\n", rc ? "TRUE" : "FALSE");
1380    return rc;
1381}
1382
1383static void VBOXAdjustFrame(ScrnInfoPtr pScrn, int x, int y)
1384{ RT_NOREF(pScrn, x, y); }
1385
1386static void VBOXFreeScreen(ScrnInfoPtr pScrn)
1387{
1388    /* Destroy the VGA hardware record */
1389    vgaHWFreeHWRec(pScrn);
1390    /* And our private record */
1391    free(pScrn->driverPrivate);
1392    pScrn->driverPrivate = NULL;
1393}
1394
1395static Bool
1396VBOXMapVidMem(ScrnInfoPtr pScrn)
1397{
1398    VBOXPtr pVBox = VBOXGetRec(pScrn);
1399    Bool rc = TRUE;
1400
1401    TRACE_ENTRY();
1402    if (!pVBox->base)
1403    {
1404#ifdef PCIACCESS
1405        (void) pci_device_map_range(pVBox->pciInfo,
1406                                    pScrn->memPhysBase,
1407                                    pScrn->videoRam * 1024,
1408                                    PCI_DEV_MAP_FLAG_WRITABLE,
1409                                    & pVBox->base);
1410#else
1411        pVBox->base = xf86MapPciMem(pScrn->scrnIndex,
1412                                    VIDMEM_FRAMEBUFFER,
1413                                    pVBox->pciTag, pScrn->memPhysBase,
1414                                    (unsigned) pScrn->videoRam * 1024);
1415#endif
1416        if (!pVBox->base)
1417            rc = FALSE;
1418    }
1419    TRACE_LOG("returning %s\n", rc ? "TRUE" : "FALSE");
1420    return rc;
1421}
1422
1423static void
1424VBOXUnmapVidMem(ScrnInfoPtr pScrn)
1425{
1426    VBOXPtr pVBox = VBOXGetRec(pScrn);
1427
1428    TRACE_ENTRY();
1429    if (pVBox->base == NULL)
1430        return;
1431
1432#ifdef PCIACCESS
1433    (void) pci_device_unmap_range(pVBox->pciInfo,
1434                                  pVBox->base,
1435                                  pScrn->videoRam * 1024);
1436#else
1437    xf86UnMapVidMem(pScrn->scrnIndex, pVBox->base,
1438                    (unsigned) pScrn->videoRam * 1024);
1439#endif
1440    pVBox->base = NULL;
1441    TRACE_EXIT();
1442}
1443
1444#ifndef VBOXVIDEO_13
1445static Bool
1446VBOXSaveScreen(ScreenPtr pScreen, int mode)
1447{
1448    RT_NOREF(pScreen, mode);
1449    return TRUE;
1450}
1451#endif
1452
1453void
1454VBOXSaveMode(ScrnInfoPtr pScrn)
1455{
1456    VBOXPtr pVBox = VBOXGetRec(pScrn);
1457    vgaRegPtr vgaReg;
1458
1459    TRACE_ENTRY();
1460    vgaReg = &VGAHWPTR(pScrn)->SavedReg;
1461    vgaHWSave(pScrn, vgaReg, VGA_SR_ALL);
1462    pVBox->fSavedVBEMode = VBoxVideoGetModeRegisters(&pVBox->cSavedWidth,
1463                                                     &pVBox->cSavedHeight,
1464                                                     &pVBox->cSavedPitch,
1465                                                     &pVBox->cSavedBPP,
1466                                                     &pVBox->fSavedFlags);
1467}
1468
1469void
1470VBOXRestoreMode(ScrnInfoPtr pScrn)
1471{
1472    VBOXPtr pVBox = VBOXGetRec(pScrn);
1473    vgaRegPtr vgaReg;
1474
1475    TRACE_ENTRY();
1476    vgaReg = &VGAHWPTR(pScrn)->SavedReg;
1477    vgaHWRestore(pScrn, vgaReg, VGA_SR_ALL);
1478    if (pVBox->fSavedVBEMode)
1479        VBoxVideoSetModeRegisters(pVBox->cSavedWidth, pVBox->cSavedHeight,
1480                                  pVBox->cSavedPitch, pVBox->cSavedBPP,
1481                                  pVBox->fSavedFlags, 0, 0);
1482    else
1483        VBoxVideoDisableVBE();
1484}
1485
1486#ifndef VBOXVIDEO_13
1487static void
1488VBOXDisplayPowerManagementSet(ScrnInfoPtr pScrn, int mode, int flags)
1489{
1490    RT_NOREF(pScrn, mode, flags);
1491}
1492#endif
1493