Merge branch '7.8'
[mesa.git] / src / gallium / state_trackers / xorg / xorg_driver.c
index 26cf2dd7723811040a281ddfc9c126700ad47995..8ac5179545a1fb147b9bc2daf8eacaaa76a4710f 100644 (file)
@@ -45,7 +45,6 @@
 #include "miscstruct.h"
 #include "dixstruct.h"
 #include "xf86xv.h"
-#include <X11/extensions/Xv.h>
 #ifndef XSERVER_LIBPCIACCESS
 #error "libpciaccess needed"
 #endif
 #include "xorg_tracker.h"
 #include "xorg_winsys.h"
 
-static void AdjustFrame(int scrnIndex, int x, int y, int flags);
-static Bool CloseScreen(int scrnIndex, ScreenPtr pScreen);
-static Bool EnterVT(int scrnIndex, int flags);
-static Bool SaveHWState(ScrnInfoPtr pScrn);
-static Bool RestoreHWState(ScrnInfoPtr pScrn);
+#ifdef HAVE_LIBKMS
+#include "libkms.h"
+#endif
 
+/*
+ * Functions and symbols exported to Xorg via pointers.
+ */
 
-static ModeStatus ValidMode(int scrnIndex, DisplayModePtr mode, Bool verbose,
-                           int flags);
-static void FreeScreen(int scrnIndex, int flags);
-static void LeaveVT(int scrnIndex, int flags);
-static Bool SwitchMode(int scrnIndex, DisplayModePtr mode, int flags);
-static Bool ScreenInit(int scrnIndex, ScreenPtr pScreen, int argc,
-                      char **argv);
-static Bool PreInit(ScrnInfoPtr pScrn, int flags);
+static Bool drv_pre_init(ScrnInfoPtr pScrn, int flags);
+static Bool drv_screen_init(int scrnIndex, ScreenPtr pScreen, int argc,
+                           char **argv);
+static Bool drv_switch_mode(int scrnIndex, DisplayModePtr mode, int flags);
+static void drv_adjust_frame(int scrnIndex, int x, int y, int flags);
+static Bool drv_enter_vt(int scrnIndex, int flags);
+static void drv_leave_vt(int scrnIndex, int flags);
+static void drv_free_screen(int scrnIndex, int flags);
+static ModeStatus drv_valid_mode(int scrnIndex, DisplayModePtr mode, Bool verbose,
+                                int flags);
 
 typedef enum
 {
     OPTION_SW_CURSOR,
-} modesettingOpts;
+    OPTION_2D_ACCEL,
+    OPTION_DEBUG_FALLBACK,
+} drv_option_enums;
 
-static const OptionInfoRec Options[] = {
+static const OptionInfoRec drv_options[] = {
     {OPTION_SW_CURSOR, "SWcursor", OPTV_BOOLEAN, {0}, FALSE},
+    {OPTION_2D_ACCEL, "2DAccel", OPTV_BOOLEAN, {0}, FALSE},
+    {OPTION_DEBUG_FALLBACK, "DebugFallback", OPTV_BOOLEAN, {0}, FALSE},
     {-1, NULL, OPTV_NONE, {0}, FALSE}
 };
 
+
 /*
  * Exported Xorg driver functions to winsys
  */
@@ -89,39 +96,72 @@ static const OptionInfoRec Options[] = {
 const OptionInfoRec *
 xorg_tracker_available_options(int chipid, int busid)
 {
-    return Options;
+    return drv_options;
 }
 
 void
 xorg_tracker_set_functions(ScrnInfoPtr scrn)
 {
-    scrn->PreInit = PreInit;
-    scrn->ScreenInit = ScreenInit;
-    scrn->SwitchMode = SwitchMode;
-    scrn->AdjustFrame = AdjustFrame;
-    scrn->EnterVT = EnterVT;
-    scrn->LeaveVT = LeaveVT;
-    scrn->FreeScreen = FreeScreen;
-    scrn->ValidMode = ValidMode;
+    scrn->PreInit = drv_pre_init;
+    scrn->ScreenInit = drv_screen_init;
+    scrn->SwitchMode = drv_switch_mode;
+    scrn->AdjustFrame = drv_adjust_frame;
+    scrn->EnterVT = drv_enter_vt;
+    scrn->LeaveVT = drv_leave_vt;
+    scrn->FreeScreen = drv_free_screen;
+    scrn->ValidMode = drv_valid_mode;
 }
 
+Bool
+xorg_tracker_have_modesetting(ScrnInfoPtr pScrn, struct pci_device *device)
+{
+    char *BusID = xalloc(64);
+    sprintf(BusID, "pci:%04x:%02x:%02x.%d",
+           device->domain, device->bus,
+           device->dev, device->func);
+
+    if (drmCheckModesettingSupported(BusID)) {
+       xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, 0,
+                      "Drm modesetting not supported %s\n", BusID);
+       xfree(BusID);
+       return FALSE;
+    }
+
+    xf86DrvMsgVerb(pScrn->scrnIndex, X_INFO, 0,
+                  "Drm modesetting supported on %s\n", BusID);
+
+    xfree(BusID);
+    return TRUE;
+}
+
+
 /*
- * Static Xorg funtctions
+ * Internal function definitions
+ */
+
+static Bool drv_init_front_buffer_functions(ScrnInfoPtr pScrn);
+static Bool drv_close_screen(int scrnIndex, ScreenPtr pScreen);
+static Bool drv_save_hw_state(ScrnInfoPtr pScrn);
+static Bool drv_restore_hw_state(ScrnInfoPtr pScrn);
+
+
+/*
+ * Internal functions
  */
 
 static Bool
-GetRec(ScrnInfoPtr pScrn)
+drv_get_rec(ScrnInfoPtr pScrn)
 {
     if (pScrn->driverPrivate)
        return TRUE;
 
-    pScrn->driverPrivate = xnfcalloc(sizeof(modesettingRec), 1);
+    pScrn->driverPrivate = xnfcalloc(1, sizeof(modesettingRec));
 
     return TRUE;
 }
 
 static void
-FreeRec(ScrnInfoPtr pScrn)
+drv_free_rec(ScrnInfoPtr pScrn)
 {
     if (!pScrn)
        return;
@@ -135,164 +175,192 @@ FreeRec(ScrnInfoPtr pScrn)
 }
 
 static void
-ProbeDDC(ScrnInfoPtr pScrn, int index)
+drv_probe_ddc(ScrnInfoPtr pScrn, int index)
 {
     ConfiguredMonitor = NULL;
 }
 
 static Bool
-CreateFrontBuffer(ScrnInfoPtr pScrn)
+drv_crtc_resize(ScrnInfoPtr pScrn, int width, int height)
 {
+    xf86CrtcConfigPtr xf86_config = XF86_CRTC_CONFIG_PTR(pScrn);
     modesettingPtr ms = modesettingPTR(pScrn);
-    unsigned handle, stride;
-    struct pipe_texture *tex;
+    ScreenPtr pScreen = pScrn->pScreen;
+    int old_width, old_height;
+    PixmapPtr rootPixmap;
+    int i;
 
-    ms->noEvict = TRUE;
+    if (width == pScrn->virtualX && height == pScrn->virtualY)
+       return TRUE;
 
-    tex = xorg_exa_create_root_texture(pScrn, pScrn->virtualX, pScrn->virtualY,
-                                      pScrn->depth, pScrn->bitsPerPixel);
+    old_width = pScrn->virtualX;
+    old_height = pScrn->virtualY;
+    pScrn->virtualX = width;
+    pScrn->virtualY = height;
 
-    if (!tex)
-       return FALSE;
+    /* ms->create_front_buffer will remove the old front buffer */
 
-    if (!ms->api->local_handle_from_texture(ms->api, ms->screen,
-                                           tex,
-                                           &stride,
-                                           &handle))
-       return FALSE;
+    rootPixmap = pScreen->GetScreenPixmap(pScreen);
+    if (!pScreen->ModifyPixmapHeader(rootPixmap, width, height, -1, -1, -1, NULL))
+       goto error_modify;
 
-    drmModeAddFB(ms->fd,
-                pScrn->virtualX,
-                pScrn->virtualY,
-                pScrn->depth,
-                pScrn->bitsPerPixel,
-                stride,
-                handle,
-                 &ms->fb_id);
+    pScrn->displayWidth = rootPixmap->devKind / (rootPixmap->drawable.bitsPerPixel / 8);
 
-    pScrn->frameX0 = 0;
-    pScrn->frameY0 = 0;
-    AdjustFrame(pScrn->scrnIndex, pScrn->frameX0, pScrn->frameY0, 0);
+    if (!ms->create_front_buffer(pScrn) || !ms->bind_front_buffer(pScrn))
+       goto error_create;
+
+    /*
+     * create && bind will turn off all crtc(s) in the kernel so we need to
+     * re-enable all the crtcs again. For real HW we might want to do this
+     * before destroying the old framebuffer.
+     */
+    for (i = 0; i < xf86_config->num_crtc; i++) {
+       xf86CrtcPtr crtc = xf86_config->crtc[i];
+
+       if (!crtc->enabled)
+           continue;
+
+       crtc->funcs->set_mode_major(crtc, &crtc->mode, crtc->rotation, crtc->x, crtc->y);
+    }
 
-    pipe_texture_reference(&ms->root_texture, tex);
-    pipe_texture_reference(&tex, NULL);
     return TRUE;
+
+    /*
+     * This is the error recovery path.
+     */
+error_create:
+    if (!pScreen->ModifyPixmapHeader(rootPixmap, old_width, old_height, -1, -1, -1, NULL))
+       FatalError("failed to resize rootPixmap error path\n");
+
+    pScrn->displayWidth = rootPixmap->devKind / (rootPixmap->drawable.bitsPerPixel / 8);
+
+error_modify:
+    pScrn->virtualX = old_width;
+    pScrn->virtualY = old_height;
+
+    if (ms->create_front_buffer(pScrn) && ms->bind_front_buffer(pScrn))
+       return FALSE;
+
+    FatalError("failed to setup old framebuffer\n");
+    return FALSE;
 }
 
+static const xf86CrtcConfigFuncsRec crtc_config_funcs = {
+    .resize = drv_crtc_resize
+};
+
 static Bool
-BindTextureToRoot(ScrnInfoPtr pScrn)
+drv_init_drm(ScrnInfoPtr pScrn)
 {
     modesettingPtr ms = modesettingPTR(pScrn);
-    ScreenPtr pScreen = pScrn->pScreen;
-    struct pipe_texture *check;
-    PixmapPtr rootPixmap;
 
-    rootPixmap = pScreen->GetScreenPixmap(pScreen);
+    /* deal with server regeneration */
+    if (ms->fd < 0) {
+       char *BusID;
 
-    xorg_exa_set_displayed_usage(rootPixmap);
-    xorg_exa_set_shared_usage(rootPixmap);
-    xorg_exa_set_texture(rootPixmap, ms->root_texture);
-    if (!pScreen->ModifyPixmapHeader(rootPixmap, -1, -1, -1, -1, -1, NULL))
-       FatalError("Couldn't adjust screen pixmap\n");
+       BusID = xalloc(64);
+       sprintf(BusID, "PCI:%d:%d:%d",
+               ((ms->PciInfo->domain << 8) | ms->PciInfo->bus),
+               ms->PciInfo->dev, ms->PciInfo->func
+           );
 
-    check = xorg_exa_get_texture(rootPixmap);
-    if (ms->root_texture != check)
-       FatalError("Created new root texture\n");
 
-    pipe_texture_reference(&check, NULL);
+       ms->api = drm_api_create();
+       ms->fd = drmOpen(ms->api ? ms->api->driver_name : NULL, BusID);
+       xfree(BusID);
+
+       if (ms->fd >= 0)
+           return TRUE;
+
+       if (ms->api && ms->api->destroy)
+           ms->api->destroy(ms->api);
+
+       ms->api = NULL;
+
+       return FALSE;
+    }
 
     return TRUE;
 }
 
 static Bool
-crtc_resize(ScrnInfoPtr pScrn, int width, int height)
+drv_close_drm(ScrnInfoPtr pScrn)
 {
     modesettingPtr ms = modesettingPTR(pScrn);
-    unsigned handle, stride;
-    PixmapPtr rootPixmap;
-    ScreenPtr pScreen = pScrn->pScreen;
 
-    if (width == pScrn->virtualX && height == pScrn->virtualY)
-       return TRUE;
+    if (ms->api && ms->api->destroy)
+       ms->api->destroy(ms->api);
+    ms->api = NULL;
 
-    ErrorF("RESIZING TO %dx%d\n", width, height);
+    drmClose(ms->fd);
+    ms->fd = -1;
 
-    pScrn->virtualX = width;
-    pScrn->virtualY = height;
+    return TRUE;
+}
 
+static Bool
+drv_init_resource_management(ScrnInfoPtr pScrn)
+{
+    modesettingPtr ms = modesettingPTR(pScrn);
     /*
-     * Remove the old framebuffer & texture.
+    ScreenPtr pScreen = pScrn->pScreen;
+    PixmapPtr rootPixmap = pScreen->GetScreenPixmap(pScreen);
+    Bool fbAccessDisabled;
+    CARD8 *fbstart;
      */
-    drmModeRmFB(ms->fd, ms->fb_id);
-    pipe_texture_reference(&ms->root_texture, NULL);
 
+    if (ms->screen || ms->kms)
+       return TRUE;
 
-    rootPixmap = pScreen->GetScreenPixmap(pScreen);
-    if (!pScreen->ModifyPixmapHeader(rootPixmap, width, height, -1, -1, -1, NULL))
-       return FALSE;
+    if (ms->api) {
+       ms->screen = ms->api->create_screen(ms->api, ms->fd, NULL);
 
-    /* takes one ref */
-    ms->root_texture = xorg_exa_get_texture(rootPixmap);
+       if (ms->screen)
+           return TRUE;
 
-    if (!ms->api->local_handle_from_texture(ms->api, ms->screen,
-                                           ms->root_texture,
-                                           &stride,
-                                           &handle))
-       FatalError("Could not get handle and stride from texture\n");
+       if (ms->api->destroy)
+           ms->api->destroy(ms->api);
 
-    drmModeAddFB(ms->fd,
-                pScrn->virtualX,
-                pScrn->virtualY,
-                pScrn->depth,
-                pScrn->bitsPerPixel,
-                stride,
-                handle,
-                 &ms->fb_id);
+       ms->api = NULL;
+    }
 
-    /* HW dependent - FIXME */
-    pScrn->displayWidth = pScrn->virtualX;
+#ifdef HAVE_LIBKMS
+    if (!kms_create(ms->fd, &ms->kms))
+       return TRUE;
+#endif
 
-    /* now create new frontbuffer */
-    return CreateFrontBuffer(pScrn) && BindTextureToRoot(pScrn);
+    return FALSE;
 }
 
-static const xf86CrtcConfigFuncsRec crtc_config_funcs = {
-    crtc_resize
-};
-
 static Bool
-InitDRM(ScrnInfoPtr pScrn)
+drv_close_resource_management(ScrnInfoPtr pScrn)
 {
     modesettingPtr ms = modesettingPTR(pScrn);
+    int i;
 
-    /* deal with server regeneration */
-    if (ms->fd < 0) {
-       char *BusID;
+    if (ms->screen) {
+       assert(ms->ctx == NULL);
 
-       BusID = xalloc(64);
-       sprintf(BusID, "PCI:%d:%d:%d",
-               ((ms->PciInfo->domain << 8) | ms->PciInfo->bus),
-               ms->PciInfo->dev, ms->PciInfo->func
-           );
-
-       ms->fd = drmOpen(NULL, BusID);
-
-       if (ms->fd < 0)
-           return FALSE;
+       for (i = 0; i < XORG_NR_FENCES; i++) {
+           if (ms->fence[i]) {
+               ms->screen->fence_finish(ms->screen, ms->fence[i], 0);
+               ms->screen->fence_reference(ms->screen, &ms->fence[i], NULL);
+           }
+       }
+       ms->screen->destroy(ms->screen);
     }
+    ms->screen = NULL;
 
-    if (!ms->api) {
-       ms->api = drm_api_create();
-
-       if (!ms->api)
-           return FALSE;
-    }
+#ifdef HAVE_LIBKMS
+    if (ms->kms)
+       kms_destroy(&ms->kms);
+#endif
 
     return TRUE;
 }
 
 static Bool
-PreInit(ScrnInfoPtr pScrn, int flags)
+drv_pre_init(ScrnInfoPtr pScrn, int flags)
 {
     xf86CrtcConfigPtr xf86_config;
     modesettingPtr ms;
@@ -300,6 +368,7 @@ PreInit(ScrnInfoPtr pScrn, int flags)
     EntityInfoPtr pEnt;
     EntPtr msEnt = NULL;
     int max_width, max_height;
+    CustomizerPtr cust;
 
     if (pScrn->numEntities != 1)
        return FALSE;
@@ -307,17 +376,21 @@ PreInit(ScrnInfoPtr pScrn, int flags)
     pEnt = xf86GetEntityInfo(pScrn->entityList[0]);
 
     if (flags & PROBE_DETECT) {
-       ProbeDDC(pScrn, pEnt->index);
+       drv_probe_ddc(pScrn, pEnt->index);
        return TRUE;
     }
 
+    cust = (CustomizerPtr) pScrn->driverPrivate;
+    pScrn->driverPrivate = NULL;
+
     /* Allocate driverPrivate */
-    if (!GetRec(pScrn))
+    if (!drv_get_rec(pScrn))
        return FALSE;
 
     ms = modesettingPTR(pScrn);
     ms->SaveGeneration = -1;
     ms->pEnt = pEnt;
+    ms->cust = cust;
 
     pScrn->displayWidth = 640;        /* default it */
 
@@ -349,7 +422,7 @@ PreInit(ScrnInfoPtr pScrn, int flags)
 
     ms->fd = -1;
     ms->api = NULL;
-    if (!InitDRM(pScrn))
+    if (!drv_init_drm(pScrn))
        return FALSE;
 
     pScrn->monitor = pScrn->confScreen->monitor;
@@ -381,35 +454,35 @@ PreInit(ScrnInfoPtr pScrn, int flags)
 
     /* Process the options */
     xf86CollectOptions(pScrn, NULL);
-    if (!(ms->Options = xalloc(sizeof(Options))))
+    if (!(ms->Options = xalloc(sizeof(drv_options))))
        return FALSE;
-    memcpy(ms->Options, Options, sizeof(Options));
+    memcpy(ms->Options, drv_options, sizeof(drv_options));
     xf86ProcessOptions(pScrn->scrnIndex, pScrn->options, ms->Options);
 
     /* Allocate an xf86CrtcConfig */
     xf86CrtcConfigInit(pScrn, &crtc_config_funcs);
     xf86_config = XF86_CRTC_CONFIG_PTR(pScrn);
 
-    max_width = 8192;
-    max_height = 8192;
+    max_width = 2048;  /* A very low default */
+    max_height = 2048; /* see screen_init */
     xf86CrtcSetSizeRange(pScrn, 320, 200, max_width, max_height);
 
     if (xf86ReturnOptValBool(ms->Options, OPTION_SW_CURSOR, FALSE)) {
        ms->SWCursor = TRUE;
     }
 
-    SaveHWState(pScrn);
+    drv_save_hw_state(pScrn);
 
-    crtc_init(pScrn);
-    output_init(pScrn);
+    xorg_crtc_init(pScrn);
+    xorg_output_init(pScrn);
 
     if (!xf86InitialConfiguration(pScrn, TRUE)) {
        xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "No valid modes.\n");
-       RestoreHWState(pScrn);
+       drv_restore_hw_state(pScrn);
        return FALSE;
     }
 
-    RestoreHWState(pScrn);
+    drv_restore_hw_state(pScrn);
 
     /*
      * If the driver can do gamma correction, it should call xf86SetGamma() here.
@@ -433,21 +506,23 @@ PreInit(ScrnInfoPtr pScrn, int flags)
     xf86SetDpi(pScrn, 0, 0);
 
     /* Load the required sub modules */
-    if (!xf86LoadSubModule(pScrn, "fb")) {
+    if (!xf86LoadSubModule(pScrn, "fb"))
        return FALSE;
-    }
 
-    xf86LoadSubModule(pScrn, "exa");
+    /* XXX: these aren't needed when we are using libkms */
+    if (!xf86LoadSubModule(pScrn, "exa"))
+       return FALSE;
 
 #ifdef DRI2
-    xf86LoadSubModule(pScrn, "dri2");
+    if (!xf86LoadSubModule(pScrn, "dri2"))
+       return FALSE;
 #endif
 
     return TRUE;
 }
 
 static Bool
-SaveHWState(ScrnInfoPtr pScrn)
+drv_save_hw_state(ScrnInfoPtr pScrn)
 {
     /*xf86CrtcConfigPtr xf86_config = XF86_CRTC_CONFIG_PTR(pScrn);*/
 
@@ -455,24 +530,45 @@ SaveHWState(ScrnInfoPtr pScrn)
 }
 
 static Bool
-RestoreHWState(ScrnInfoPtr pScrn)
+drv_restore_hw_state(ScrnInfoPtr pScrn)
 {
     /*xf86CrtcConfigPtr config = XF86_CRTC_CONFIG_PTR(pScrn);*/
 
     return TRUE;
 }
 
-static void xorgBlockHandler(int i, pointer blockData, pointer pTimeout,
-                             pointer pReadmask)
+static void drv_block_handler(int i, pointer blockData, pointer pTimeout,
+                              pointer pReadmask)
 {
     ScreenPtr pScreen = screenInfo.screens[i];
     modesettingPtr ms = modesettingPTR(xf86Screens[pScreen->myNum]);
 
     pScreen->BlockHandler = ms->blockHandler;
     pScreen->BlockHandler(i, blockData, pTimeout, pReadmask);
-    pScreen->BlockHandler = xorgBlockHandler;
-
-    ms->ctx->flush(ms->ctx, PIPE_FLUSH_RENDER_CACHE, NULL);
+    pScreen->BlockHandler = drv_block_handler;
+
+    if (ms->ctx) {
+       int j;
+
+       ms->ctx->flush(ms->ctx, PIPE_FLUSH_RENDER_CACHE, &ms->fence[XORG_NR_FENCES-1]);
+       
+       if (ms->fence[0])
+          ms->ctx->screen->fence_finish(ms->ctx->screen, ms->fence[0], 0);
+  
+       /* The amount of rendering generated by a block handler can be
+        * quite small.  Let us get a fair way ahead of hardware before
+        * throttling.
+        */
+       for (j = 0; j < XORG_NR_FENCES - 1; j++)
+          ms->screen->fence_reference(ms->screen,
+                                      &ms->fence[j],
+                                      ms->fence[j+1]);
+
+       ms->screen->fence_reference(ms->screen,
+                                   &ms->fence[XORG_NR_FENCES-1],
+                                   NULL);
+    }
+        
 
 #ifdef DRM_MODE_FEATURE_DIRTYFB
     {
@@ -482,7 +578,7 @@ static void xorgBlockHandler(int i, pointer blockData, pointer pTimeout,
        if (num_cliprects) {
            drmModeClip *clip = alloca(num_cliprects * sizeof(drmModeClip));
            BoxPtr rect = REGION_RECTS(dirty);
-           int i;
+           int i, ret;
 
            /* XXX no need for copy? */
            for (i = 0; i < num_cliprects; i++, rect++) {
@@ -493,7 +589,11 @@ static void xorgBlockHandler(int i, pointer blockData, pointer pTimeout,
            }
 
            /* TODO query connector property to see if this is needed */
-           drmModeDirtyFB(ms->fd, ms->fb_id, clip, num_cliprects);
+           ret = drmModeDirtyFB(ms->fd, ms->fb_id, clip, num_cliprects);
+           if (ret) {
+               debug_printf("%s: failed to send dirty (%i, %s)\n",
+                            __func__, ret, strerror(-ret));
+           }
 
            DamageEmpty(ms->damage);
        }
@@ -502,7 +602,7 @@ static void xorgBlockHandler(int i, pointer blockData, pointer pTimeout,
 }
 
 static Bool
-CreateScreenResources(ScreenPtr pScreen)
+drv_create_screen_resources(ScreenPtr pScreen)
 {
     ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum];
     modesettingPtr ms = modesettingPTR(pScrn);
@@ -513,13 +613,13 @@ CreateScreenResources(ScreenPtr pScreen)
 
     pScreen->CreateScreenResources = ms->createScreenResources;
     ret = pScreen->CreateScreenResources(pScreen);
-    pScreen->CreateScreenResources = CreateScreenResources;
+    pScreen->CreateScreenResources = drv_create_screen_resources;
 
-    BindTextureToRoot(pScrn);
+    ms->bind_front_buffer(pScrn);
 
     ms->noEvict = FALSE;
 
-    AdjustFrame(pScrn->scrnIndex, pScrn->frameX0, pScrn->frameY0, 0);
+    drv_adjust_frame(pScrn->scrnIndex, pScrn->frameX0, pScrn->frameY0, 0);
 
 #ifdef DRM_MODE_FEATURE_DIRTYFB
     rootPixmap = pScreen->GetScreenPixmap(pScreen);
@@ -543,24 +643,49 @@ CreateScreenResources(ScreenPtr pScreen)
 }
 
 static Bool
-ScreenInit(int scrnIndex, ScreenPtr pScreen, int argc, char **argv)
+drv_screen_init(int scrnIndex, ScreenPtr pScreen, int argc, char **argv)
 {
     ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum];
     modesettingPtr ms = modesettingPTR(pScrn);
+    unsigned max_width, max_height;
     VisualPtr visual;
+    CustomizerPtr cust = ms->cust;
 
-    if (!InitDRM(pScrn))
+    if (!drv_init_drm(pScrn)) {
+       FatalError("Could not init DRM");
        return FALSE;
+    }
 
-    if (!ms->screen) {
-       ms->screen = ms->api->create_screen(ms->api, ms->fd, NULL);
+    if (!drv_init_resource_management(pScrn)) {
+       FatalError("Could not init resource management (!pipe_screen && !libkms)");
+       return FALSE;
+    }
 
-       if (!ms->screen) {
-           FatalError("Could not init pipe_screen\n");
-           return FALSE;
-       }
+    if (!drv_init_front_buffer_functions(pScrn)) {
+       FatalError("Could not init front buffer manager");
+       return FALSE;
+    }
+
+    /* get max width and height */
+    {
+       drmModeResPtr res;
+       res = drmModeGetResources(ms->fd);
+       max_width = res->max_width;
+       max_height = res->max_height;
+       drmModeFreeResources(res);
     }
 
+    if (ms->screen) {
+       float maxf;
+       int max;
+       maxf = ms->screen->get_paramf(ms->screen, PIPE_CAP_MAX_TEXTURE_2D_LEVELS);
+       max = (1 << (int)(maxf - 1.0f));
+       max_width = max < max_width ? max : max_width;
+       max_height = max < max_height ? max : max_height;
+    }
+
+    xf86CrtcSetSizeRange(pScrn, 1, 1, max_width, max_height);
+
     pScrn->pScreen = pScreen;
 
     /* HW dependent - FIXME */
@@ -603,16 +728,40 @@ ScreenInit(int scrnIndex, ScreenPtr pScreen, int argc, char **argv)
     fbPictureInit(pScreen, NULL, 0);
 
     ms->blockHandler = pScreen->BlockHandler;
-    pScreen->BlockHandler = xorgBlockHandler;
+    pScreen->BlockHandler = drv_block_handler;
     ms->createScreenResources = pScreen->CreateScreenResources;
-    pScreen->CreateScreenResources = CreateScreenResources;
+    pScreen->CreateScreenResources = drv_create_screen_resources;
 
     xf86SetBlackWhitePixels(pScreen);
 
-    ms->exa = xorg_exa_init(pScrn);
-    ms->debug_fallback = debug_get_bool_option("XORG_DEBUG_FALLBACK", TRUE);
+    ms->accelerate_2d = xf86ReturnOptValBool(ms->Options, OPTION_2D_ACCEL, FALSE);
+    ms->debug_fallback = xf86ReturnOptValBool(ms->Options, OPTION_DEBUG_FALLBACK, ms->accelerate_2d);
 
-    xorg_init_video(pScreen);
+    if (ms->screen) {
+       ms->exa = xorg_exa_init(pScrn, ms->accelerate_2d);
+
+       xorg_xv_init(pScreen);
+#ifdef DRI2
+       xorg_dri2_init(pScreen);
+#endif
+    }
+
+    xf86DrvMsg(pScrn->scrnIndex, X_INFO, "##################################\n");
+    xf86DrvMsg(pScrn->scrnIndex, X_INFO, "# Usefull debugging info follows #\n");
+    xf86DrvMsg(pScrn->scrnIndex, X_INFO, "##################################\n");
+    xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Using %s backend\n",
+              ms->screen ? "Gallium3D" : "libkms");
+    xf86DrvMsg(pScrn->scrnIndex, X_INFO, "2D Acceleration is %s\n",
+              ms->screen && ms->accelerate_2d ? "enabled" : "disabled");
+    xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Fallback debugging is %s\n",
+              ms->debug_fallback ? "enabled" : "disabled");
+#ifdef DRI2
+    xf86DrvMsg(pScrn->scrnIndex, X_INFO, "3D Acceleration is %s\n",
+              ms->screen ? "enabled" : "disabled");
+#else
+    xf86DrvMsg(pScrn->scrnIndex, X_INFO, "3D Acceleration is disabled\n");
+#endif
+    xf86DrvMsg(pScrn->scrnIndex, X_INFO, "##################################\n");
 
     miInitializeBackingStore(pScreen);
     xf86SetBackingStore(pScreen);
@@ -631,7 +780,7 @@ ScreenInit(int scrnIndex, ScreenPtr pScreen, int argc, char **argv)
 
     pScreen->SaveScreen = xf86SaveScreen;
     ms->CloseScreen = pScreen->CloseScreen;
-    pScreen->CloseScreen = CloseScreen;
+    pScreen->CloseScreen = drv_close_screen;
 
     if (!xf86CrtcScreenInit(pScreen))
        return FALSE;
@@ -644,17 +793,14 @@ ScreenInit(int scrnIndex, ScreenPtr pScreen, int argc, char **argv)
     if (serverGeneration == 1)
        xf86ShowUnusedOptions(pScrn->scrnIndex, pScrn->options);
 
-#if 1
-#ifdef DRI2
-    driScreenInit(pScreen);
-#endif
-#endif
+    if (cust && cust->winsys_screen_init)
+       cust->winsys_screen_init(cust, ms->fd);
 
-    return EnterVT(scrnIndex, 1);
+    return drv_enter_vt(scrnIndex, 1);
 }
 
 static void
-AdjustFrame(int scrnIndex, int x, int y, int flags)
+drv_adjust_frame(int scrnIndex, int x, int y, int flags)
 {
     ScrnInfoPtr pScrn = xf86Screens[scrnIndex];
     xf86CrtcConfigPtr config = XF86_CRTC_CONFIG_PTR(pScrn);
@@ -670,23 +816,27 @@ AdjustFrame(int scrnIndex, int x, int y, int flags)
 }
 
 static void
-FreeScreen(int scrnIndex, int flags)
+drv_free_screen(int scrnIndex, int flags)
 {
-    FreeRec(xf86Screens[scrnIndex]);
+    drv_free_rec(xf86Screens[scrnIndex]);
 }
 
 static void
-LeaveVT(int scrnIndex, int flags)
+drv_leave_vt(int scrnIndex, int flags)
 {
     ScrnInfoPtr pScrn = xf86Screens[scrnIndex];
     modesettingPtr ms = modesettingPTR(pScrn);
     xf86CrtcConfigPtr config = XF86_CRTC_CONFIG_PTR(pScrn);
+    CustomizerPtr cust = ms->cust;
     int o;
 
+    if (cust && cust->winsys_leave_vt)
+       cust->winsys_leave_vt(cust);
+
     for (o = 0; o < config->num_crtc; o++) {
        xf86CrtcPtr crtc = config->crtc[o];
 
-       crtc_cursor_destroy(crtc);
+       xorg_crtc_cursor_destroy(crtc);
 
        if (crtc->rotatedPixmap || crtc->rotatedData) {
            crtc->funcs->shadow_destroy(crtc, crtc->rotatedPixmap,
@@ -697,8 +847,9 @@ LeaveVT(int scrnIndex, int flags)
     }
 
     drmModeRmFB(ms->fd, ms->fb_id);
+    ms->fb_id = -1;
 
-    RestoreHWState(pScrn);
+    drv_restore_hw_state(pScrn);
 
     if (drmDropMaster(ms->fd))
        xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
@@ -711,10 +862,11 @@ LeaveVT(int scrnIndex, int flags)
  * This gets called when gaining control of the VT, and from ScreenInit().
  */
 static Bool
-EnterVT(int scrnIndex, int flags)
+drv_enter_vt(int scrnIndex, int flags)
 {
     ScrnInfoPtr pScrn = xf86Screens[scrnIndex];
     modesettingPtr ms = modesettingPTR(pScrn);
+    CustomizerPtr cust = ms->cust;
 
     if (drmSetMaster(ms->fd)) {
        if (errno == EINVAL) {
@@ -733,23 +885,26 @@ EnterVT(int scrnIndex, int flags)
      */
     if (ms->SaveGeneration != serverGeneration) {
        ms->SaveGeneration = serverGeneration;
-       SaveHWState(pScrn);
+       drv_save_hw_state(pScrn);
     }
 
-    if (!CreateFrontBuffer(pScrn))
+    if (!ms->create_front_buffer(pScrn))
        return FALSE;
 
-    if (!flags && !BindTextureToRoot(pScrn))
+    if (!flags && !ms->bind_front_buffer(pScrn))
        return FALSE;
 
     if (!xf86SetDesiredModes(pScrn))
        return FALSE;
 
+    if (cust && cust->winsys_enter_vt)
+       cust->winsys_enter_vt(cust);
+
     return TRUE;
 }
 
 static Bool
-SwitchMode(int scrnIndex, DisplayModePtr mode, int flags)
+drv_switch_mode(int scrnIndex, DisplayModePtr mode, int flags)
 {
     ScrnInfoPtr pScrn = xf86Screens[scrnIndex];
 
@@ -757,16 +912,27 @@ SwitchMode(int scrnIndex, DisplayModePtr mode, int flags)
 }
 
 static Bool
-CloseScreen(int scrnIndex, ScreenPtr pScreen)
+drv_close_screen(int scrnIndex, ScreenPtr pScreen)
 {
     ScrnInfoPtr pScrn = xf86Screens[scrnIndex];
     modesettingPtr ms = modesettingPTR(pScrn);
+    CustomizerPtr cust = ms->cust;
 
     if (pScrn->vtSema) {
-       LeaveVT(scrnIndex, 0);
+       drv_leave_vt(scrnIndex, 0);
+    }
+
+    if (ms->cursor) {
+       FreeCursor(ms->cursor, None);
+       ms->cursor = NULL;
     }
+
+    if (cust && cust->winsys_screen_close)
+       cust->winsys_screen_close(cust);
+
 #ifdef DRI2
-    driCloseScreen(pScreen);
+    if (ms->screen)
+       xorg_dri2_close(pScreen);
 #endif
 
     pScreen->BlockHandler = ms->blockHandler;
@@ -780,17 +946,16 @@ CloseScreen(int scrnIndex, ScreenPtr pScreen)
     }
 #endif
 
-    pipe_texture_reference(&ms->root_texture, NULL);
+    drmModeRmFB(ms->fd, ms->fb_id);
+    ms->destroy_front_buffer(pScrn);
 
     if (ms->exa)
        xorg_exa_close(pScrn);
+    ms->exa = NULL;
 
-    if (ms->api && ms->api->destroy)
-       ms->api->destroy(ms->api);
-    ms->api = NULL;
+    drv_close_resource_management(pScrn);
 
-    drmClose(ms->fd);
-    ms->fd = -1;
+    drv_close_drm(pScrn);
 
     pScrn->vtSema = FALSE;
     pScreen->CloseScreen = ms->CloseScreen;
@@ -798,9 +963,265 @@ CloseScreen(int scrnIndex, ScreenPtr pScreen)
 }
 
 static ModeStatus
-ValidMode(int scrnIndex, DisplayModePtr mode, Bool verbose, int flags)
+drv_valid_mode(int scrnIndex, DisplayModePtr mode, Bool verbose, int flags)
 {
     return MODE_OK;
 }
 
+
+/*
+ * Front buffer backing store functions.
+ */
+
+static Bool
+drv_destroy_front_buffer_ga3d(ScrnInfoPtr pScrn)
+{
+    modesettingPtr ms = modesettingPTR(pScrn);
+
+    if (!ms->root_texture)
+       return TRUE;
+
+    if (ms->fb_id != -1) {
+       drmModeRmFB(ms->fd, ms->fb_id);
+       ms->fb_id = -1;
+    }
+
+    pipe_texture_reference(&ms->root_texture, NULL);
+    return TRUE;
+}
+
+static Bool
+drv_create_front_buffer_ga3d(ScrnInfoPtr pScrn)
+{
+    modesettingPtr ms = modesettingPTR(pScrn);
+    struct pipe_texture *tex;
+    struct winsys_handle whandle;
+    unsigned fb_id;
+    int ret;
+
+    ms->noEvict = TRUE;
+
+    tex = xorg_exa_create_root_texture(pScrn, pScrn->virtualX, pScrn->virtualY,
+                                      pScrn->depth, pScrn->bitsPerPixel);
+
+    if (!tex)
+       return FALSE;
+
+    memset(&whandle, 0, sizeof(whandle));
+    whandle.type = DRM_API_HANDLE_TYPE_KMS;
+
+    if (!ms->screen->texture_get_handle(ms->screen, tex, &whandle))
+       goto err_destroy;
+
+    ret = drmModeAddFB(ms->fd,
+                      pScrn->virtualX,
+                      pScrn->virtualY,
+                      pScrn->depth,
+                      pScrn->bitsPerPixel,
+                      whandle.stride,
+                      whandle.handle,
+                      &fb_id);
+    if (ret) {
+       debug_printf("%s: failed to create framebuffer (%i, %s)\n",
+                    __func__, ret, strerror(-ret));
+       goto err_destroy;
+    }
+
+    if (!drv_destroy_front_buffer_ga3d(pScrn))
+       FatalError("%s: failed to take down old framebuffer\n", __func__);
+
+    pScrn->frameX0 = 0;
+    pScrn->frameY0 = 0;
+    drv_adjust_frame(pScrn->scrnIndex, pScrn->frameX0, pScrn->frameY0, 0);
+
+    pipe_texture_reference(&ms->root_texture, tex);
+    pipe_texture_reference(&tex, NULL);
+    ms->fb_id = fb_id;
+
+    return TRUE;
+
+err_destroy:
+    pipe_texture_reference(&tex, NULL);
+    return FALSE;
+}
+
+static Bool
+drv_bind_front_buffer_ga3d(ScrnInfoPtr pScrn)
+{
+    modesettingPtr ms = modesettingPTR(pScrn);
+    ScreenPtr pScreen = pScrn->pScreen;
+    PixmapPtr rootPixmap = pScreen->GetScreenPixmap(pScreen);
+    struct pipe_texture *check;
+
+    xorg_exa_set_displayed_usage(rootPixmap);
+    xorg_exa_set_shared_usage(rootPixmap);
+    xorg_exa_set_texture(rootPixmap, ms->root_texture);
+    if (!pScreen->ModifyPixmapHeader(rootPixmap, -1, -1, -1, -1, -1, NULL))
+       FatalError("Couldn't adjust screen pixmap\n");
+
+    check = xorg_exa_get_texture(rootPixmap);
+    if (ms->root_texture != check)
+       FatalError("Created new root texture\n");
+
+    pipe_texture_reference(&check, NULL);
+    return TRUE;
+}
+
+#ifdef HAVE_LIBKMS
+static Bool
+drv_destroy_front_buffer_kms(ScrnInfoPtr pScrn)
+{
+    modesettingPtr ms = modesettingPTR(pScrn);
+    ScreenPtr pScreen = pScrn->pScreen;
+    PixmapPtr rootPixmap = pScreen->GetScreenPixmap(pScreen);
+
+    /* XXX Do something with the rootPixmap.
+     * This currently works fine but if we are getting crashes in
+     * the fb functions after VT switches maybe look more into it.
+     */
+    (void)rootPixmap;
+
+    if (!ms->root_bo)
+       return TRUE;
+
+    if (ms->fb_id != -1) {
+       drmModeRmFB(ms->fd, ms->fb_id);
+       ms->fb_id = -1;
+    }
+
+    kms_bo_unmap(ms->root_bo);
+    kms_bo_destroy(&ms->root_bo);
+    return TRUE;
+}
+
+static Bool
+drv_create_front_buffer_kms(ScrnInfoPtr pScrn)
+{
+    modesettingPtr ms = modesettingPTR(pScrn);
+    unsigned handle, stride;
+    struct kms_bo *bo;
+    unsigned attr[8];
+    unsigned fb_id;
+    int ret;
+
+    attr[0] = KMS_BO_TYPE;
+#ifdef KMS_BO_TYPE_SCANOUT_X8R8G8B8
+    attr[1] = KMS_BO_TYPE_SCANOUT_X8R8G8B8;
+#else
+    attr[1] = KMS_BO_TYPE_SCANOUT;
+#endif
+    attr[2] = KMS_WIDTH;
+    attr[3] = pScrn->virtualX;
+    attr[4] = KMS_HEIGHT;
+    attr[5] = pScrn->virtualY;
+    attr[6] = 0;
+
+    if (kms_bo_create(ms->kms, attr, &bo))
+       return FALSE;
+
+    if (kms_bo_get_prop(bo, KMS_PITCH, &stride))
+       goto err_destroy;
+
+    if (kms_bo_get_prop(bo, KMS_HANDLE, &handle))
+       goto err_destroy;
+
+    ret = drmModeAddFB(ms->fd,
+                      pScrn->virtualX,
+                      pScrn->virtualY,
+                      pScrn->depth,
+                      pScrn->bitsPerPixel,
+                      stride,
+                      handle,
+                      &fb_id);
+    if (ret) {
+       debug_printf("%s: failed to create framebuffer (%i, %s)",
+                    __func__, ret, strerror(-ret));
+       goto err_destroy;
+    }
+
+    if (!drv_destroy_front_buffer_kms(pScrn))
+       FatalError("%s: could not takedown old bo", __func__);
+
+    pScrn->frameX0 = 0;
+    pScrn->frameY0 = 0;
+    drv_adjust_frame(pScrn->scrnIndex, pScrn->frameX0, pScrn->frameY0, 0);
+    ms->root_bo = bo;
+    ms->fb_id = fb_id;
+
+    return TRUE;
+
+err_destroy:
+    kms_bo_destroy(&bo);
+    return FALSE;
+}
+
+static Bool
+drv_bind_front_buffer_kms(ScrnInfoPtr pScrn)
+{
+    modesettingPtr ms = modesettingPTR(pScrn);
+    ScreenPtr pScreen = pScrn->pScreen;
+    PixmapPtr rootPixmap = pScreen->GetScreenPixmap(pScreen);
+    unsigned stride;
+    void *ptr;
+
+    if (kms_bo_get_prop(ms->root_bo, KMS_PITCH, &stride))
+       return FALSE;
+
+    if (kms_bo_map(ms->root_bo, &ptr))
+       goto err_destroy;
+
+    pScreen->ModifyPixmapHeader(rootPixmap,
+                               pScrn->virtualX,
+                               pScrn->virtualY,
+                               pScreen->rootDepth,
+                               pScrn->bitsPerPixel,
+                               stride,
+                               ptr);
+
+    /* This a hack to work around EnableDisableFBAccess setting the pointer
+     * the real fix would be to replace pScrn->EnableDisableFBAccess hook
+     * and set the rootPixmap->devPrivate.ptr to something valid before that.
+     *
+     * But in its infinit visdome something uses either this some times before
+     * that, so our hook doesn't get called before the crash happens.
+     */
+    pScrn->pixmapPrivate.ptr = ptr;
+
+    return TRUE;
+
+err_destroy:
+    kms_bo_destroy(&ms->root_bo);
+    return FALSE;
+}
+#endif /* HAVE_LIBKMS */
+
+static Bool drv_init_front_buffer_functions(ScrnInfoPtr pScrn)
+{
+    modesettingPtr ms = modesettingPTR(pScrn);
+    if (ms->screen) {
+       ms->destroy_front_buffer = drv_destroy_front_buffer_ga3d;
+       ms->create_front_buffer = drv_create_front_buffer_ga3d;
+       ms->bind_front_buffer = drv_bind_front_buffer_ga3d;
+#ifdef HAVE_LIBKMS
+    } else if (ms->kms) {
+       ms->destroy_front_buffer = drv_destroy_front_buffer_kms;
+       ms->create_front_buffer = drv_create_front_buffer_kms;
+       ms->bind_front_buffer = drv_bind_front_buffer_kms;
+#endif
+    } else
+       return FALSE;
+
+    return TRUE;
+}
+
+CustomizerPtr xorg_customizer(ScrnInfoPtr pScrn)
+{
+    return modesettingPTR(pScrn)->cust;
+}
+
+Bool xorg_has_gallium(ScrnInfoPtr pScrn)
+{
+    return modesettingPTR(pScrn)->screen != NULL;
+}
+
 /* vim: set sw=4 ts=8 sts=4: */