Browse Source

[KMS/DRM] Go back to the LEGACY interface only because using planes breaks compatibility with HW, so no advantage on using ATOMIC.

Manuel Alfayate Corchete 4 years ago
parent
commit
b24494734b

+ 1 - 2
cmake/sdlchecks.cmake

@@ -1182,8 +1182,7 @@ macro(CheckKMSDRM)
       set(HAVE_SDL_VIDEO TRUE)
 
       file(GLOB KMSDRM_SOURCES ${SDL2_SOURCE_DIR}/src/video/kmsdrm/*.c)
-      file(GLOB KMSDRM_LEGACY_SOURCES ${SDL2_SOURCE_DIR}/src/video/kmsdrm_legacy/*.c)
-      set(SOURCE_FILES ${SOURCE_FILES} ${KMSDRM_SOURCES} ${KMSDRM_LEGACY_SOURCES})
+      set(SOURCE_FILES ${SOURCE_FILES} ${KMSDRM_SOURCES})
 
       list(APPEND EXTRA_CFLAGS ${KMSDRM_CFLAGS})
 

+ 0 - 1
configure.ac

@@ -2252,7 +2252,6 @@ AS_HELP_STRING([--enable-kmsdrm-shared], [dynamically load kmsdrm support [[defa
 
             AC_DEFINE(SDL_VIDEO_DRIVER_KMSDRM, 1, [ ])
             SOURCES="$SOURCES $srcdir/src/video/kmsdrm/*.c"
-            SOURCES="$SOURCES $srcdir/src/video/kmsdrm_legacy/*.c"
             EXTRA_CFLAGS="$EXTRA_CFLAGS $LIBDRM_CFLAGS $LIBGBM_CFLAGS"
 
             AC_MSG_CHECKING(for kmsdrm dynamic loading support)

+ 0 - 1
src/video/SDL_video.c

@@ -96,7 +96,6 @@ static VideoBootStrap *bootstrap[] = {
 #endif
 #if SDL_VIDEO_DRIVER_KMSDRM
     &KMSDRM_bootstrap,
-    &KMSDRM_LEGACY_bootstrap,
 #endif
 #if SDL_VIDEO_DRIVER_RPI
     &RPI_bootstrap,

+ 0 - 2
src/video/kmsdrm/SDL_kmsdrmdyn.c

@@ -1,7 +1,6 @@
 /*
   Simple DirectMedia Layer
   Copyright (C) 1997-2021 Sam Lantinga <slouken@libsdl.org>
-  Atomic KMSDRM backend by Manuel Alfayate Corchete <redwindwanderer@gmail.com>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -28,7 +27,6 @@
 
 #include "SDL_kmsdrmdyn.h"
 
-
 #ifdef SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC
 
 #include "SDL_name.h"

+ 0 - 1
src/video/kmsdrm/SDL_kmsdrmdyn.h

@@ -1,7 +1,6 @@
 /*
   Simple DirectMedia Layer
   Copyright (C) 1997-2021 Sam Lantinga <slouken@libsdl.org>
-  Atomic KMSDRM backend by Manuel Alfayate Corchete <redwindwanderer@gmail.com>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages

+ 0 - 1
src/video/kmsdrm/SDL_kmsdrmevents.c

@@ -1,7 +1,6 @@
 /*
   Simple DirectMedia Layer
   Copyright (C) 1997-2021 Sam Lantinga <slouken@libsdl.org>
-  Atomic KMSDRM backend by Manuel Alfayate Corchete <redwindwanderer@gmail.com>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages

+ 0 - 1
src/video/kmsdrm/SDL_kmsdrmevents.h

@@ -1,7 +1,6 @@
 /*
   Simple DirectMedia Layer
   Copyright (C) 1997-2021 Sam Lantinga <slouken@libsdl.org>
-  Atomic KMSDRM backend by Manuel Alfayate Corchete <redwindwanderer@gmail.com>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages

+ 68 - 129
src/video/kmsdrm/SDL_kmsdrmmouse.c

@@ -1,7 +1,6 @@
 /*
   Simple DirectMedia Layer
   Copyright (C) 1997-2021 Sam Lantinga <slouken@libsdl.org>
-  Atomic KMSDRM backend by Manuel Alfayate Corchete <redwindwanderer@gmail.com>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -27,7 +26,6 @@
 #include "SDL_kmsdrmvideo.h"
 #include "SDL_kmsdrmmouse.h"
 #include "SDL_kmsdrmdyn.h"
-#include "SDL_assert.h"
 
 #include "../../events/SDL_mouse_c.h"
 #include "../../events/default_cursor.h"
@@ -55,40 +53,18 @@ static int KMSDRM_WarpMouseGlobal(int x, int y);
 /*  and mouse->cursor_shown is 1.                                                     */
 /**************************************************************************************/
 
-/**********************************/
-/* Atomic helper functions block. */
-/**********************************/
-
-int
-drm_atomic_movecursor(KMSDRM_CursorData *curdata, uint16_t x, uint16_t y)
+static SDL_Cursor *
+KMSDRM_CreateDefaultCursor(void)
 {
-    SDL_DisplayData *dispdata = (SDL_DisplayData *)SDL_GetDisplayDriverData(0);
-
-    if (!dispdata->cursor_plane) /* We can't move a non-existing cursor, but that's ok. */
-        return 0;
-
-    /* Do we have a set of changes already in the making? If not, allocate a new one. */
-    if (!dispdata->atomic_req)
-        dispdata->atomic_req = KMSDRM_drmModeAtomicAlloc();
-    
-    add_plane_property(dispdata->atomic_req,
-            dispdata->cursor_plane, "CRTC_X", x - curdata->hot_x);
-    add_plane_property(dispdata->atomic_req,
-            dispdata->cursor_plane, "CRTC_Y", y - curdata->hot_y);
-
-    return 0;
+    return SDL_CreateCursor(default_cdata, default_cmask, DEFAULT_CWIDTH, DEFAULT_CHEIGHT, DEFAULT_CHOTX, DEFAULT_CHOTY);
 }
 
-/***************************************/
-/* Atomic helper functions block ends. */
-/***************************************/
-
 /* Converts a pixel from straight-alpha [AA, RR, GG, BB], which the SDL cursor surface has,
    to premultiplied-alpha [AA. AA*RR, AA*GG, AA*BB].
    These multiplications have to be done with floats instead of uint32_t's,
    and the resulting values have to be converted to be relative to the 0-255 interval,
    where 255 is 1.00 and anything between 0 and 255 is 0.xx. */
-void alpha_premultiply_ARGB8888 (uint32_t *pixel) {
+void legacy_alpha_premultiply_ARGB8888 (uint32_t *pixel) {
 
     uint32_t A, R, G, B;
 
@@ -107,15 +83,9 @@ void alpha_premultiply_ARGB8888 (uint32_t *pixel) {
     (*pixel) = (((uint32_t)A << 24) | ((uint32_t)R << 16) | ((uint32_t)G << 8)) | ((uint32_t)B << 0);
 }
 
-static SDL_Cursor *
-KMSDRM_CreateDefaultCursor(void)
-{
-    return SDL_CreateCursor(default_cdata, default_cmask, DEFAULT_CWIDTH, DEFAULT_CHEIGHT, DEFAULT_CHOTX, DEFAULT_CHOTY);
-}
-
-/* This simply gets the cursor soft-buffer ready. We don't copy it to a GBO BO
-   until ShowCursor() because the cusor GBM BO (living in dispata) is destroyed
-   and recreated when we recreate windows, etc. */
+/* This simply gets the cursor soft-buffer ready.
+   We don't copy it to a GBO BO until ShowCursor() because the cusor GBM BO (living
+   in dispata) is destroyed and recreated when we recreate windows, etc. */
 static SDL_Cursor *
 KMSDRM_CreateCursor(SDL_Surface * surface, int hot_x, int hot_y)
 {
@@ -225,13 +195,12 @@ static int
 KMSDRM_ShowCursor(SDL_Cursor * cursor)
 {
     SDL_VideoDevice *video_device = SDL_GetVideoDevice();
-    //SDL_VideoData *viddata = ((SDL_VideoData *)video_device->driverdata);
+    SDL_VideoData *viddata = ((SDL_VideoData *)video_device->driverdata);
     SDL_DisplayData *dispdata = (SDL_DisplayData *)SDL_GetDisplayDriverData(0);
     SDL_Mouse *mouse;
     KMSDRM_CursorData *curdata;
 
-    KMSDRM_FBInfo *fb;
-    KMSDRM_PlaneInfo info = {0};
+    uint32_t bo_handle;
 
     size_t bo_stride;
     size_t bufsize;
@@ -239,7 +208,7 @@ KMSDRM_ShowCursor(SDL_Cursor * cursor)
     uint32_t pixel;
 
     int i,j;
-    int ret = 0;
+    int ret;
 
     mouse = SDL_GetMouse();
     if (!mouse) {
@@ -250,28 +219,20 @@ KMSDRM_ShowCursor(SDL_Cursor * cursor)
     /* Hide cursor if it's NULL or it has no focus(=winwow). */
     /*********************************************************/
     if (!cursor || !mouse->focus) {
-        if (dispdata->cursor_plane) {
-	    /* Hide the drm cursor with no more considerations because
-	    SDL_VideoQuit() takes us here after disabling the mouse
-	    so there is no mouse->cur_cursor by now. */
-	    info.plane = dispdata->cursor_plane;
-	    /* The rest of the members are zeroed, so this takes away the cursor
-	       from the cursor plane. */
-	    drm_atomic_set_plane_props(&info);
-	    if (drm_atomic_commit(video_device, SDL_TRUE, SDL_FALSE)) {
-		ret = SDL_SetError("Failed atomic commit in KMSDRM_ShowCursor.");
-	    }
-        }
-	return ret;
+        /* Hide the drm cursor with no more considerations because
+           SDL_VideoQuit() takes us here after disabling the mouse
+           so there is no mouse->cur_cursor by now. */
+	ret = KMSDRM_drmModeSetCursor(viddata->drm_fd,
+	    dispdata->crtc->crtc_id, 0, 0, 0);
+	if (ret) {
+	    ret = SDL_SetError("Could not hide current cursor with drmModeSetCursor().");
+	}
+        return ret;
     }
 
     /************************************************/
     /* If cursor != NULL, DO show cursor on display */
     /************************************************/
-    if (!dispdata->cursor_plane) {
-        return SDL_SetError("Hardware cursor plane not initialized.");
-    }
-    
     curdata = (KMSDRM_CursorData *) cursor->driverdata;
 
     if (!curdata || !dispdata->cursor_bo) {
@@ -297,7 +258,7 @@ KMSDRM_ShowCursor(SDL_Cursor * cursor)
     for (i = 0; i < curdata->h; i++) {
         for (j = 0; j < curdata->w; j++) {
             pixel = ((uint32_t*)curdata->buffer)[i * curdata->w + j];
-            alpha_premultiply_ARGB8888 (&pixel);
+            legacy_alpha_premultiply_ARGB8888 (&pixel);
             SDL_memcpy(ready_buffer + (i * dispdata->cursor_w) + j, &pixel, 4);
         }
     }
@@ -308,29 +269,21 @@ KMSDRM_ShowCursor(SDL_Cursor * cursor)
         goto cleanup;
     }
 
-    /* Get the fb_id for the GBM BO so we can show it on the cursor plane. */
-    fb = KMSDRM_FBFromBO(video_device, dispdata->cursor_bo);
-
-    /* Show the GBM BO buffer on the cursor plane. */
-    info.plane = dispdata->cursor_plane;
-    info.crtc_id = dispdata->crtc->crtc->crtc_id;
-    info.fb_id = fb->fb_id; 
-    info.src_w = dispdata->cursor_w;
-    info.src_h = dispdata->cursor_h;
-    info.crtc_x = mouse->x - curdata->hot_x;
-    info.crtc_y = mouse->y - curdata->hot_y;
-    info.crtc_w = curdata->w;
-    info.crtc_h = curdata->h; 
-
-    drm_atomic_set_plane_props(&info);
+    /* Put the GBM BO buffer on screen using the DRM interface. */
+    bo_handle = KMSDRM_gbm_bo_get_handle(dispdata->cursor_bo).u32;
+    if (curdata->hot_x == 0 && curdata->hot_y == 0) {
+        ret = KMSDRM_drmModeSetCursor(viddata->drm_fd, dispdata->crtc->crtc_id,
+            bo_handle, dispdata->cursor_w, dispdata->cursor_h);
+    } else {
+        ret = KMSDRM_drmModeSetCursor2(viddata->drm_fd, dispdata->crtc->crtc_id,
+            bo_handle, dispdata->cursor_w, dispdata->cursor_h, curdata->hot_x, curdata->hot_y);
+    }
 
-    if (drm_atomic_commit(video_device, SDL_TRUE, SDL_FALSE)) {
-        ret = SDL_SetError("Failed atomic commit in KMSDRM_ShowCursor.");
+    if (ret) {
+        ret = SDL_SetError("Failed to set DRM cursor.");
         goto cleanup;
     }
 
-    ret = 0;
-
 cleanup:
 
     if (ready_buffer) {
@@ -373,7 +326,6 @@ KMSDRM_WarpMouse(SDL_Window * window, int x, int y)
 static int
 KMSDRM_WarpMouseGlobal(int x, int y)
 {
-    KMSDRM_CursorData *curdata;
     SDL_Mouse *mouse = SDL_GetMouse();
     SDL_DisplayData *dispdata = (SDL_DisplayData *)SDL_GetDisplayDriverData(0);
 
@@ -382,11 +334,18 @@ KMSDRM_WarpMouseGlobal(int x, int y)
         SDL_SendMouseMotion(mouse->focus, mouse->mouseID, 0, x, y);
 
         /* And now update the cursor graphic position on screen. */
-        curdata = (KMSDRM_CursorData *) mouse->cur_cursor->driverdata;
         if (dispdata->cursor_bo) {
-            if (drm_atomic_movecursor(curdata, x, y)) {
-                return SDL_SetError("drm_atomic_movecursor() failed.");
-            }
+	    int ret, drm_fd;
+	    drm_fd = KMSDRM_gbm_device_get_fd(
+		KMSDRM_gbm_bo_get_device(dispdata->cursor_bo));
+	    ret = KMSDRM_drmModeMoveCursor(drm_fd, dispdata->crtc->crtc_id, x, y);
+
+	    if (ret) {
+		SDL_SetError("drmModeMoveCursor() failed.");
+	    }
+
+	    return ret;
+
         } else {
             return SDL_SetError("Cursor not initialized properly.");
         }
@@ -403,30 +362,15 @@ KMSDRM_DeinitMouse(_THIS)
 {
     SDL_VideoDevice *video_device = SDL_GetVideoDevice();
     SDL_DisplayData *dispdata = (SDL_DisplayData *)SDL_GetDisplayDriverData(0);
-    KMSDRM_PlaneInfo info = {0};
- 
-    /* 1- Destroy the curso GBM BO. */
+   
+    /* Destroy the curso GBM BO. */
     if (video_device && dispdata->cursor_bo) {
-	/* Unsethe the cursor BO from the cursor plane.
-	   (The other members of the plane info are zeroed). */
-	info.plane = dispdata->cursor_plane;
-	drm_atomic_set_plane_props(&info);
-	/* Wait until the cursor is unset from the cursor plane
-	   before destroying it's BO. */
-	if (drm_atomic_commit(video_device, SDL_TRUE, SDL_FALSE)) {
-	    SDL_SetError("Failed atomic commit in KMSDRM_DenitMouse.");
-	}
-	/* ..and finally destroy the cursor DRM BO! */
 	KMSDRM_gbm_bo_destroy(dispdata->cursor_bo);
 	dispdata->cursor_bo = NULL;
     }
-
-    /* 2- Free the cursor plane, on which the cursor was being shown. */
-    if (dispdata->cursor_plane) {
-        free_plane(&dispdata->cursor_plane);
-    }
 }
 
+/* Create cursor BO. */
 void
 KMSDRM_InitMouse(_THIS)
 {
@@ -442,29 +386,23 @@ KMSDRM_InitMouse(_THIS)
     mouse->WarpMouse = KMSDRM_WarpMouse;
     mouse->WarpMouseGlobal = KMSDRM_WarpMouseGlobal;
 
-    /***************************************************************************/
-    /* REMEMBER TO BE SURE OF UNDOING ALL THESE STEPS PROPERLY BEFORE CALLING  */
-    /* gbm_device_destroy, OR YOU WON'T BE ABLE TO CREATE A NEW ONE (ERROR -13 */
-    /* on gbm_create_device).                                                  */
-    /***************************************************************************/
-
-    /* 1- Init cursor plane, if we haven't yet. */
-    if (!dispdata->cursor_plane) {
-        setup_plane(_this, &(dispdata->cursor_plane), DRM_PLANE_TYPE_CURSOR);
-    }
-
-    /* 2- Create the cursor GBM BO, if we haven't yet. */
+    /************************************************/
+    /* Create the cursor GBM BO, if we haven't yet. */
+    /************************************************/
     if (!dispdata->cursor_bo) {
 
-        if (!KMSDRM_gbm_device_is_format_supported(viddata->gbm_dev, GBM_FORMAT_ARGB8888,
-                                               GBM_BO_USE_CURSOR | GBM_BO_USE_WRITE))
+        if (!KMSDRM_gbm_device_is_format_supported(viddata->gbm_dev,
+              GBM_FORMAT_ARGB8888,
+              GBM_BO_USE_CURSOR | GBM_BO_USE_WRITE))
         {
             SDL_SetError("Unsupported pixel format for cursor");
             return;
         }
 
-	if (KMSDRM_drmGetCap(viddata->drm_fd, DRM_CAP_CURSOR_WIDTH,  &dispdata->cursor_w) ||
-	    KMSDRM_drmGetCap(viddata->drm_fd, DRM_CAP_CURSOR_HEIGHT, &dispdata->cursor_h))
+	if (KMSDRM_drmGetCap(viddata->drm_fd,
+              DRM_CAP_CURSOR_WIDTH,  &dispdata->cursor_w) ||
+	      KMSDRM_drmGetCap(viddata->drm_fd, DRM_CAP_CURSOR_HEIGHT,
+              &dispdata->cursor_h))
 	{
 	    SDL_SetError("Could not get the recommended GBM cursor size");
 	    goto cleanup;
@@ -477,7 +415,7 @@ KMSDRM_InitMouse(_THIS)
 
 	dispdata->cursor_bo = KMSDRM_gbm_bo_create(viddata->gbm_dev,
 	    dispdata->cursor_w, dispdata->cursor_h,
-	    GBM_FORMAT_ARGB8888, GBM_BO_USE_CURSOR | GBM_BO_USE_WRITE);
+	    GBM_FORMAT_ARGB8888, GBM_BO_USE_CURSOR | GBM_BO_USE_WRITE | GBM_BO_USE_LINEAR);
 
 	if (!dispdata->cursor_bo) {
 	    SDL_SetError("Could not create GBM cursor BO");
@@ -505,27 +443,28 @@ cleanup:
     }
 }
 
+void
+KMSDRM_QuitMouse(_THIS)
+{
+    /* TODO: ? */
+}
+
 /* This is called when a mouse motion event occurs */
 static void
 KMSDRM_MoveCursor(SDL_Cursor * cursor)
 {
     SDL_Mouse *mouse = SDL_GetMouse();
-    KMSDRM_CursorData *curdata;
+    SDL_DisplayData *dispdata = (SDL_DisplayData *)SDL_GetDisplayDriverData(0);
+    int drm_fd, ret;
 
     /* We must NOT call SDL_SendMouseMotion() here or we will enter recursivity!
        That's why we move the cursor graphic ONLY. */
     if (mouse && mouse->cur_cursor && mouse->cur_cursor->driverdata) {
-        curdata = (KMSDRM_CursorData *) mouse->cur_cursor->driverdata;
-
-        /* Some programs expect cursor movement even while they don't do SwapWindow() calls,
-           and since we ride on the atomic_commit() in SwapWindow() for cursor movement,
-           cursor won't move in these situations. We could do an atomic_commit() here
-           for each cursor movement request, but it cripples the movement to 30FPS,
-           so a future solution is needed. SDLPoP "QUIT?" menu is an example of this
-           situation. */
+        drm_fd = KMSDRM_gbm_device_get_fd(KMSDRM_gbm_bo_get_device(dispdata->cursor_bo));
+        ret = KMSDRM_drmModeMoveCursor(drm_fd, dispdata->crtc->crtc_id, mouse->x, mouse->y);
 
-        if (drm_atomic_movecursor(curdata, mouse->x, mouse->y)) {
-            SDL_SetError("drm_atomic_movecursor() failed.");
+        if (ret) {
+            SDL_SetError("drmModeMoveCursor() failed.");
         }
     }
 }

+ 5 - 5
src/video/kmsdrm/SDL_kmsdrmmouse.h

@@ -1,7 +1,6 @@
 /*
   Simple DirectMedia Layer
   Copyright (C) 1997-2021 Sam Lantinga <slouken@libsdl.org>
-  Atomic KMSDRM backend by Manuel Alfayate Corchete <redwindwanderer@gmail.com>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -30,14 +29,14 @@
 #define MAX_CURSOR_W 512
 #define MAX_CURSOR_H 512
 
-/* Driverdata with driver-side info about the cursor. */
 typedef struct _KMSDRM_CursorData
 {
-    uint16_t       hot_x, hot_y;
-    uint16_t       w, h;
+    int            hot_x, hot_y;
+    int            w, h;
 
     /* The buffer where we store the mouse bitmap ready to be used.
-       We get it ready and filled in CreateCursor(), and copy it to a GBM BO in ShowCursor().*/     
+       We get it ready and filled in CreateCursor(), and copy it
+       to a GBM BO in ShowCursor().*/     
     uint32_t *buffer;
     size_t buffer_size;
     size_t buffer_pitch;
@@ -46,6 +45,7 @@ typedef struct _KMSDRM_CursorData
 
 extern void KMSDRM_InitMouse(_THIS);
 extern void KMSDRM_DeinitMouse(_THIS);
+extern void KMSDRM_QuitMouse(_THIS);
 
 extern void KMSDRM_InitCursor();
 

+ 48 - 269
src/video/kmsdrm/SDL_kmsdrmopengles.c

@@ -1,7 +1,6 @@
 /*
   Simple DirectMedia Layer
   Copyright (C) 1997-2021 Sam Lantinga <slouken@libsdl.org>
-  Atomic KMSDRM backend by Manuel Alfayate Corchete <redwindwanderer@gmail.com>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -24,27 +23,16 @@
 
 #if SDL_VIDEO_DRIVER_KMSDRM
 
+#include "SDL_log.h"
+
 #include "SDL_kmsdrmvideo.h"
 #include "SDL_kmsdrmopengles.h"
 #include "SDL_kmsdrmdyn.h"
-#include "SDL_hints.h"
 
 #ifndef EGL_PLATFORM_GBM_MESA
 #define EGL_PLATFORM_GBM_MESA 0x31D7
 #endif
 
-#ifndef EGL_SYNC_NATIVE_FENCE_ANDROID
-#define EGL_SYNC_NATIVE_FENCE_ANDROID     0x3144
-#endif
-
-#ifndef EGL_SYNC_NATIVE_FENCE_FD_ANDROID
-#define EGL_SYNC_NATIVE_FENCE_FD_ANDROID  0x3145
-#endif
-
-#ifndef EGL_NO_NATIVE_FENCE_FD_ANDROID
-#define EGL_NO_NATIVE_FENCE_FD_ANDROID    -1
-#endif
-
 /* EGL implementation of SDL OpenGL support */
 
 void
@@ -95,291 +83,82 @@ int KMSDRM_GLES_SetSwapInterval(_THIS, int interval) {
     return 0;
 }
 
-/*********************************/
-/* Atomic functions block        */
-/*********************************/
-
-#define VOID2U64(x) ((uint64_t)(unsigned long)(x))
-
-static EGLSyncKHR create_fence(int fd, _THIS)
-{
-    EGLint attrib_list[] = {
-        EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fd,
-        EGL_NONE,
-    };
-
-    EGLSyncKHR fence = _this->egl_data->eglCreateSyncKHR
-        (_this->egl_data->egl_display, EGL_SYNC_NATIVE_FENCE_ANDROID, attrib_list);
-
-    assert(fence);
-    return fence;
-}
-
-/***********************************************************************************/
-/* Comments about buffer access protection mechanism (=fences) are the ones boxed. */
-/* Also, DON'T remove the asserts: if a fence-related call fails, it's better that */
-/* program exits immediately, or we could leave KMS waiting for a failed/missing   */
-/* fence forevever.                                                                */
-/***********************************************************************************/
 int
-KMSDRM_GLES_SwapWindowFenced(_THIS, SDL_Window * window)
-{
+KMSDRM_GLES_SwapWindow(_THIS, SDL_Window * window) {
     SDL_WindowData *windata = ((SDL_WindowData *) window->driverdata);
     SDL_DisplayData *dispdata = (SDL_DisplayData *) SDL_GetDisplayForWindow(window)->driverdata;
-    KMSDRM_FBInfo *fb;
-    KMSDRM_PlaneInfo info = {0};
-    SDL_bool modesetting = SDL_FALSE;
-
-    /******************************************************************/
-    /* Create the GPU-side FENCE OBJECT. It will be inserted into the */
-    /* GL CMDSTREAM exactly at the end of the gl commands that form a */
-    /* frame.(KMS will have to wait on it before doing a pageflip.)   */
-    /******************************************************************/
-    dispdata->gpu_fence = create_fence(EGL_NO_NATIVE_FENCE_FD_ANDROID, _this);
-    assert(dispdata->gpu_fence);
+    SDL_VideoData *viddata = ((SDL_VideoData *)_this->driverdata);
+    KMSDRM_FBInfo *fb_info;
+    int ret, timeout;
 
-    /******************************************************************/
-    /* eglSwapBuffers flushes the fence down the GL CMDSTREAM, so we  */
-    /* know for sure it's there now.                                  */
-    /* Also it marks, at EGL level, the buffer that we want to become */
-    /* the new front buffer. (Remember that won't really happen until */
-    /* we request a pageflip at the KMS level and it completes.       */
-    /******************************************************************/
-    if (! _this->egl_data->eglSwapBuffers(_this->egl_data->egl_display, windata->egl_surface)) {
-        return SDL_EGL_SetError("Failed to swap EGL buffers", "eglSwapBuffers");
+    /* Recreate the GBM / EGL surfaces if the display mode has changed */
+    if (windata->egl_surface_dirty) {
+        KMSDRM_CreateSurfaces(_this, window);
     }
 
-    /******************************************************************/
-    /* EXPORT the GPU-side FENCE OBJECT to the fence INPUT FD, so we  */
-    /* can pass it into the kernel. Atomic ioctl will pass the        */
-    /* in-fence fd into the kernel, thus telling KMS that it has to   */
-    /* wait for GPU to finish rendering the frame (remember where we  */
-    /* put the fence in the GL CMDSTREAM) before doing the changes    */
-    /* requested in the atomic ioct (the pageflip in this case).      */
-    /* (We export the GPU-side FENCE OJECT to the fence INPUT FD now, */
-    /* not sooner, because now we are sure that the GPU-side fence is */
-    /* in the CMDSTREAM to be lifted when the CMDSTREAM to this point */
-    /* is completed).                                                 */
-    /******************************************************************/
-    dispdata->kms_in_fence_fd = _this->egl_data->eglDupNativeFenceFDANDROID (_this->egl_data->egl_display,
-        dispdata->gpu_fence);
-    
-    _this->egl_data->eglDestroySyncKHR(_this->egl_data->egl_display, dispdata->gpu_fence);
-    assert(dispdata->kms_in_fence_fd != -1);
-
-    /* Lock the buffer that is marked by eglSwapBuffers() to become the
-       next front buffer (so it can not be chosen by EGL as back buffer
-       to draw on), and get a handle to it to request the pageflip on it.
-       REMEMBER that gbm_surface_lock_front_buffer() ALWAYS has to be
-       called after eglSwapBuffers(). */
-    windata->next_bo = KMSDRM_gbm_surface_lock_front_buffer(windata->gs);
-    if (!windata->next_bo) {
-        return SDL_SetError("Failed to lock frontbuffer");
-    }
-    fb = KMSDRM_FBFromBO(_this, windata->next_bo);
-    if (!fb) {
-        return SDL_SetError("Failed to get a new framebuffer from BO");
+    /* Wait for confirmation that the next front buffer has been flipped, at which
+       point the previous front buffer can be released */
+    timeout = 0;
+    if (_this->egl_data->egl_swapinterval == 1) {
+        timeout = -1;
     }
-
-    /* Add the pageflip to the request list. */
-    info.plane = dispdata->display_plane;
-    info.crtc_id = dispdata->crtc->crtc->crtc_id;
-    info.fb_id = fb->fb_id;
-
-    info.src_w = windata->src_w;
-    info.src_h = windata->src_h;
-    info.crtc_w = windata->output_w;
-    info.crtc_h = windata->output_h;
-    info.crtc_x = windata->output_x;
-
-    drm_atomic_set_plane_props(&info);
-
-    /*****************************************************************/
-    /* Tell the display (KMS) that it will have to wait on the fence */
-    /* for the GPU-side FENCE.                                       */
-    /*                                                               */
-    /* Since KMS is a kernel thing, we have to pass an FD into       */
-    /* the kernel, and get another FD out of the kernel.             */
-    /*                                                               */
-    /* 1) To pass the GPU-side fence into the kernel, we set the     */
-    /* INPUT FD as the IN_FENCE_FD prop of the PRIMARY PLANE.        */
-    /* This FD tells KMS (the kernel) to wait for the GPU-side fence.*/
-    /*                                                               */
-    /* 2) To get the KMS-side fence out of the kernel, we set the    */
-    /* OUTPUT FD as the OUT_FEWNCE_FD prop of the CRTC.              */
-    /* This FD will be later imported as a FENCE OBJECT which will be*/
-    /* used to tell the GPU to wait for KMS to complete the changes  */
-    /* requested in atomic_commit (the pageflip in this case).       */ 
-    /*****************************************************************/
-    if (dispdata->kms_in_fence_fd != -1)
-    {
-        add_plane_property(dispdata->atomic_req, dispdata->display_plane,
-            "IN_FENCE_FD", dispdata->kms_in_fence_fd);
-        add_crtc_property(dispdata->atomic_req, dispdata->crtc,
-            "OUT_FENCE_PTR", VOID2U64(&dispdata->kms_out_fence_fd));
+    if (!KMSDRM_WaitPageFlip(_this, windata, timeout)) {
+        return 0;
     }
 
-    /* Do we have a pending modesetting? If so, set the necessary 
-       props so it's included in the incoming atomic commit. */
-    if (dispdata->modeset_pending) {
-        uint32_t blob_id;
-        SDL_VideoData *viddata = (SDL_VideoData *)_this->driverdata;
-
-        add_connector_property(dispdata->atomic_req, dispdata->connector, "CRTC_ID", dispdata->crtc->crtc->crtc_id);
-        KMSDRM_drmModeCreatePropertyBlob(viddata->drm_fd, &dispdata->mode, sizeof(dispdata->mode), &blob_id);
-        add_crtc_property(dispdata->atomic_req, dispdata->crtc, "MODE_ID", blob_id);
-        add_crtc_property(dispdata->atomic_req, dispdata->crtc, "active", 1);
-        modesetting = SDL_TRUE;
-        dispdata->modeset_pending = SDL_FALSE;
-    }
-
-    /*****************************************************************/   
-    /* Issue a non-blocking atomic commit: for triple buffering,     */
-    /* this must not block so the game can start building another    */
-    /* frame, even if the just-requested pageflip hasnt't completed. */
-    /*****************************************************************/   
-    if (drm_atomic_commit(_this, SDL_FALSE, modesetting)) {
-        return SDL_SetError("Failed to issue atomic commit on pageflip");
-    }
-
-    /* Release the previous front buffer so EGL can chose it as back buffer
-       and render on it again. */
+    /* Release the previous front buffer */
     if (windata->bo) {
         KMSDRM_gbm_surface_release_buffer(windata->gs, windata->bo);
+        windata->bo = NULL;
     }
 
-    /* Take note of the buffer about to become front buffer, so next
-       time we come here we can free it like we just did with the previous
-       front buffer. */
     windata->bo = windata->next_bo;
 
-    /****************************************************************/
-    /* Import the KMS-side FENCE OUTPUT FD from the kernel to the   */
-    /* KMS-side FENCE OBJECT so we can use use it to fence the GPU. */
-    /****************************************************************/
-    dispdata->kms_fence = create_fence(dispdata->kms_out_fence_fd, _this);
-    assert(dispdata->kms_fence);
-
-    /****************************************************************/
-    /* "Delete" the fence OUTPUT FD, because we already have the    */
-    /* KMS FENCE OBJECT, the fence itself is away from us, on the   */
-    /* kernel side.                                                 */
-    /****************************************************************/
-    dispdata->kms_out_fence_fd = -1;
-
-    /*****************************************************************/
-    /* Tell the GPU to wait on the fence for the KMS-side FENCE,     */
-    /* which means waiting until the requested pageflip is completed.*/
-    /*****************************************************************/
-    _this->egl_data->eglWaitSyncKHR(_this->egl_data->egl_display, dispdata->kms_fence, 0);
-
-    return 0;
-}
-
-int
-KMSDRM_GLES_SwapWindowDoubleBuffered(_THIS, SDL_Window * window)
-{
-    SDL_WindowData *windata = ((SDL_WindowData *) window->driverdata);
-    SDL_DisplayData *dispdata = (SDL_DisplayData *) SDL_GetDisplayForWindow(window)->driverdata;
-    KMSDRM_FBInfo *fb;
-    KMSDRM_PlaneInfo info = {0};
-    SDL_bool modesetting = SDL_FALSE;
-
-    /**********************************************************************************/
-    /* In double-buffer mode, atomic_commit will always be synchronous/blocking (ie:  */
-    /* won't return until the requested changes are really done).                     */
-    /* Also, there's no need to fence KMS or the GPU, because we won't be entering    */
-    /* game loop again (hence not building or executing a new cmdstring) until        */
-    /* pageflip is done, so we don't need to protect the KMS/GPU access to the buffer.*/     
-    /**********************************************************************************/ 
-
-    /* Mark, at EGL level, the buffer that we want to become the new front buffer.
-       It won't really happen until we request a pageflip at the KMS level and it
-       completes. */
-    if (! _this->egl_data->eglSwapBuffers(_this->egl_data->egl_display, windata->egl_surface)) {
-        return SDL_EGL_SetError("Failed to swap EGL buffers", "eglSwapBuffers");
+    /* Mark a buffer to becume the next front buffer.
+       This won't happen until pagelip completes. */
+    if (!(_this->egl_data->eglSwapBuffers(_this->egl_data->egl_display,
+                                           windata->egl_surface))) {
+        SDL_LogError(SDL_LOG_CATEGORY_VIDEO, "eglSwapBuffers failed.");
+        return 0;
     }
 
-    /* Lock the buffer that is marked by eglSwapBuffers() to become the next front buffer
-       (so it can not be chosen by EGL as back buffer to draw on), and get a handle to it,
-       to request the pageflip on it. */
+    /* Lock the next front buffer so it can't be allocated as a back buffer */
     windata->next_bo = KMSDRM_gbm_surface_lock_front_buffer(windata->gs);
     if (!windata->next_bo) {
-        return SDL_SetError("Failed to lock frontbuffer");
+        SDL_LogError(SDL_LOG_CATEGORY_VIDEO, "Could not lock GBM surface front buffer");
+        return 0;
     }
-    fb = KMSDRM_FBFromBO(_this, windata->next_bo);
-    if (!fb) {
-        return SDL_SetError("Failed to get a new framebuffer BO");
-    }
-
-    /* Add the pageflip to the request list. */
-    info.plane = dispdata->display_plane;
-    info.crtc_id = dispdata->crtc->crtc->crtc_id;
-    info.fb_id = fb->fb_id;
-
-    info.src_w = windata->src_w;
-    info.src_h = windata->src_h;
-    info.crtc_w = windata->output_w;
-    info.crtc_h = windata->output_h;
-    info.crtc_x = windata->output_x;
-
-    drm_atomic_set_plane_props(&info);
-
-    /* Do we have a pending modesetting? If so, set the necessary 
-       props so it's included in the incoming atomic commit. */
-    if (dispdata->modeset_pending) {
-        uint32_t blob_id;
 
-        SDL_VideoData *viddata = (SDL_VideoData *)_this->driverdata;
-
-        add_connector_property(dispdata->atomic_req, dispdata->connector, "CRTC_ID", dispdata->crtc->crtc->crtc_id);
-        KMSDRM_drmModeCreatePropertyBlob(viddata->drm_fd, &dispdata->mode, sizeof(dispdata->mode), &blob_id);
-        add_crtc_property(dispdata->atomic_req, dispdata->crtc, "MODE_ID", blob_id);
-        add_crtc_property(dispdata->atomic_req, dispdata->crtc, "active", 1);
-        modesetting = SDL_TRUE;
-        dispdata->modeset_pending = SDL_FALSE;
+    /* Get the fb_info for the next front buffer. */
+    fb_info = KMSDRM_FBFromBO(_this, windata->next_bo);
+    if (!fb_info) {
+        return 0;
     }
 
-    /* Issue the one and only atomic commit where all changes will be requested!. 
-       Blocking for double buffering: won't return until completed. */
-    if (drm_atomic_commit(_this, SDL_TRUE, modesetting)) {
-        return SDL_SetError("Failed to issue atomic commit on pageflip");
-    }
+    /* Issue pageflip on the next front buffer.
+       The pageflip will be done during the next vblank. */
+    ret = KMSDRM_drmModePageFlip(viddata->drm_fd, dispdata->crtc->crtc_id,
+	     fb_info->fb_id, DRM_MODE_PAGE_FLIP_EVENT, &windata->waiting_for_flip);
 
-    /* Release last front buffer so EGL can chose it as back buffer and render on it again. */
-    if (windata->bo) {
-        KMSDRM_gbm_surface_release_buffer(windata->gs, windata->bo);
+    if (_this->egl_data->egl_swapinterval == 1) {
+	if (ret == 0) {
+	    windata->waiting_for_flip = SDL_TRUE;
+	} else {
+	    SDL_LogError(SDL_LOG_CATEGORY_VIDEO, "Could not queue pageflip: %d", ret);
+	}
     }
 
-    /* Take note of current front buffer, so we can free it next time we come here. */
-    windata->bo = windata->next_bo;
-
-    return 0;
-}
-
-int
-KMSDRM_GLES_SwapWindow(_THIS, SDL_Window * window)
-{
-    SDL_WindowData *windata = ((SDL_WindowData *) window->driverdata);
-
-    if (windata->swap_window == NULL) {
-        /* We want the fenced version by default, but it needs extensions. */
-        if ( (SDL_GetHintBoolean(SDL_HINT_VIDEO_DOUBLE_BUFFER, SDL_FALSE)) ||
-             (!SDL_EGL_HasExtension(_this, SDL_EGL_DISPLAY_EXTENSION, "EGL_ANDROID_native_fence_sync")) )
-        {
-            windata->swap_window = KMSDRM_GLES_SwapWindowDoubleBuffered;
-        } else {
-            windata->swap_window = KMSDRM_GLES_SwapWindowFenced;
-        }
+    /* If we are in double-buffer mode, wait immediately for vsync
+       (as if we only had two buffers),
+       Run your SDL2 program with "SDL_KMSDRM_DOUBLE_BUFFER=1 <program_name>"
+       to enable this. */
+    if (_this->egl_data->egl_swapinterval == 1 && windata->double_buffer) {
+	KMSDRM_WaitPageFlip(_this, windata, -1);
     }
 
-    return windata->swap_window(_this, window);
+    return 0;
 }
 
-/***************************************/
-/* End of Atomic functions block       */
-/***************************************/
-
 SDL_EGL_MakeCurrent_impl(KMSDRM)
 
 #endif /* SDL_VIDEO_DRIVER_KMSDRM */

+ 0 - 1
src/video/kmsdrm/SDL_kmsdrmopengles.h

@@ -1,7 +1,6 @@
 /*
   Simple DirectMedia Layer
   Copyright (C) 1997-2021 Sam Lantinga <slouken@libsdl.org>
-  Atomic KMSDRM backend by Manuel Alfayate Corchete <redwindwanderer@gmail.com>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages

+ 20 - 29
src/video/kmsdrm/SDL_kmsdrmsym.h

@@ -41,32 +41,29 @@ SDL_KMSDRM_SYM(void,drmModeFreeCrtc,(drmModeCrtcPtr ptr))
 SDL_KMSDRM_SYM(void,drmModeFreeConnector,(drmModeConnectorPtr ptr))
 SDL_KMSDRM_SYM(void,drmModeFreeEncoder,(drmModeEncoderPtr ptr))
 SDL_KMSDRM_SYM(int,drmGetCap,(int fd, uint64_t capability, uint64_t *value))
-SDL_KMSDRM_SYM(int,drmIoctl,(int fd, unsigned long request, void *arg))
 SDL_KMSDRM_SYM(drmModeResPtr,drmModeGetResources,(int fd))
-
 SDL_KMSDRM_SYM(int,drmModeAddFB,(int fd, uint32_t width, uint32_t height, uint8_t depth,
                                  uint8_t bpp, uint32_t pitch, uint32_t bo_handle,
                                  uint32_t *buf_id))
-
-SDL_KMSDRM_SYM(int,drmModeAddFB2,(int fd, uint32_t width, uint32_t height,
-                                  uint32_t pixel_format, const uint32_t bo_handles[4],
-                                  const uint32_t pitches[4], const uint32_t offsets[4],
-                                  uint32_t *buf_id, uint32_t flags))
-
-SDL_KMSDRM_SYM(int,drmModeAddFB2WithModifiers,(int fd, uint32_t width, uint32_t height,
-                                               uint32_t pixel_format, const uint32_t bo_handles[4],
-                                               const uint32_t pitches[4], const uint32_t offsets[4],
-                                               const uint64_t modifier[4], uint32_t *buf_id,
-                                               uint32_t flags))
-
 SDL_KMSDRM_SYM(int,drmModeRmFB,(int fd, uint32_t bufferId))
 SDL_KMSDRM_SYM(drmModeFBPtr,drmModeGetFB,(int fd, uint32_t buf))
 SDL_KMSDRM_SYM(drmModeCrtcPtr,drmModeGetCrtc,(int fd, uint32_t crtcId))
+SDL_KMSDRM_SYM(int,drmModeSetCrtc,(int fd, uint32_t crtcId, uint32_t bufferId,
+                                   uint32_t x, uint32_t y, uint32_t *connectors, int count,
+                                   drmModeModeInfoPtr mode))
+SDL_KMSDRM_SYM(int,drmModeSetCursor,(int fd, uint32_t crtcId, uint32_t bo_handle,
+                                     uint32_t width, uint32_t height))
+SDL_KMSDRM_SYM(int,drmModeSetCursor2,(int fd, uint32_t crtcId, uint32_t bo_handle,
+                                      uint32_t width, uint32_t height,
+                                      int32_t hot_x, int32_t hot_y))
+SDL_KMSDRM_SYM(int,drmModeMoveCursor,(int fd, uint32_t crtcId, int x, int y))
 SDL_KMSDRM_SYM(drmModeEncoderPtr,drmModeGetEncoder,(int fd, uint32_t encoder_id))
 SDL_KMSDRM_SYM(drmModeConnectorPtr,drmModeGetConnector,(int fd, uint32_t connector_id))
+SDL_KMSDRM_SYM(int,drmHandleEvent,(int fd,drmEventContextPtr evctx))
+SDL_KMSDRM_SYM(int,drmModePageFlip,(int fd, uint32_t crtc_id, uint32_t fb_id,
+                                    uint32_t flags, void *user_data))
 
-/* Atomic functions */
-
+/* Planes stuff. */
 SDL_KMSDRM_SYM(int,drmSetClientCap,(int fd, uint64_t capability, uint64_t value))
 SDL_KMSDRM_SYM(drmModePlaneResPtr,drmModeGetPlaneResources,(int fd))
 SDL_KMSDRM_SYM(drmModePlanePtr,drmModeGetPlane,(int fd, uint32_t plane_id))
@@ -77,14 +74,13 @@ SDL_KMSDRM_SYM(void,drmModeFreeProperty,(drmModePropertyPtr ptr))
 SDL_KMSDRM_SYM(void,drmModeFreeObjectProperties,(drmModeObjectPropertiesPtr ptr))
 SDL_KMSDRM_SYM(void,drmModeFreePlane,(drmModePlanePtr ptr))
 SDL_KMSDRM_SYM(void,drmModeFreePlaneResources,(drmModePlaneResPtr ptr))
-
-SDL_KMSDRM_SYM(drmModeAtomicReqPtr,drmModeAtomicAlloc,(void))
-SDL_KMSDRM_SYM(void,drmModeAtomicFree,(drmModeAtomicReqPtr req))
-SDL_KMSDRM_SYM(int,drmModeAtomicCommit,(int fd,drmModeAtomicReqPtr req,uint32_t flags,void *user_data))
-SDL_KMSDRM_SYM(int,drmModeAtomicAddProperty,(drmModeAtomicReqPtr req,uint32_t object_id,uint32_t property_id,uint64_t value))
-SDL_KMSDRM_SYM(int,drmModeCreatePropertyBlob,(int fd,const void *data,size_t size,uint32_t *id))
-
-/* End of atomic fns */
+SDL_KMSDRM_SYM(int,drmModeSetPlane,(int fd, uint32_t plane_id, uint32_t crtc_id,
+			   uint32_t fb_id, uint32_t flags,
+			   int32_t crtc_x, int32_t crtc_y,
+			   uint32_t crtc_w, uint32_t crtc_h,
+			   uint32_t src_x, uint32_t src_y,
+			   uint32_t src_w, uint32_t src_h))
+/* Planes stuff ends. */
 
 SDL_KMSDRM_MODULE(GBM)
 SDL_KMSDRM_SYM(int,gbm_device_get_fd,(struct gbm_device *gbm))
@@ -95,11 +91,6 @@ SDL_KMSDRM_SYM(struct gbm_device *,gbm_create_device,(int fd))
 SDL_KMSDRM_SYM(unsigned int,gbm_bo_get_width,(struct gbm_bo *bo))
 SDL_KMSDRM_SYM(unsigned int,gbm_bo_get_height,(struct gbm_bo *bo))
 SDL_KMSDRM_SYM(uint32_t,gbm_bo_get_stride,(struct gbm_bo *bo))
-SDL_KMSDRM_SYM(uint32_t,gbm_bo_get_stride_for_plane,(struct gbm_bo *bo,int plane))
-SDL_KMSDRM_SYM(uint32_t,gbm_bo_get_format,(struct gbm_bo *bo))
-SDL_KMSDRM_SYM(uint32_t,gbm_bo_get_offset,(struct gbm_bo *bo, int plane))
-SDL_KMSDRM_SYM(int,gbm_bo_get_plane_count,(struct gbm_bo *bo))
-
 SDL_KMSDRM_SYM(union gbm_bo_handle,gbm_bo_get_handle,(struct gbm_bo *bo))
 SDL_KMSDRM_SYM(int,gbm_bo_write,(struct gbm_bo *bo, const void *buf, size_t count))
 SDL_KMSDRM_SYM(struct gbm_device *,gbm_bo_get_device,(struct gbm_bo *bo))

+ 298 - 861
src/video/kmsdrm/SDL_kmsdrmvideo.c

@@ -1,7 +1,6 @@
 /*
   Simple DirectMedia Layer
   Copyright (C) 1997-2021 Sam Lantinga <slouken@libsdl.org>
-  Atomic KMSDRM backend by Manuel Alfayate Corchete <redwindwanderer@gmail.com>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -27,6 +26,8 @@
 /* SDL internals */
 #include "../SDL_sysvideo.h"
 #include "SDL_syswm.h"
+#include "SDL_log.h"
+#include "SDL_hints.h"
 #include "../../events/SDL_events_c.h"
 #include "../../events/SDL_mouse_c.h"
 #include "../../events/SDL_keyboard_c.h"
@@ -47,47 +48,42 @@
 #include <errno.h>
 #include <poll.h>
 
-/* for older KMSDRM headers... */
-#ifndef DRM_FORMAT_MOD_VENDOR_NONE
-#define DRM_FORMAT_MOD_VENDOR_NONE 0
-#endif
-#ifndef DRM_FORMAT_MOD_LINEAR
-#define DRM_FORMAT_MOD_LINEAR fourcc_mod_code(NONE, 0)
-#endif
+#ifdef __OpenBSD__
+eeefine KMSDRM_DRI_PATH "/dev/"
+ce
 
+#define KMSDRM_DRI_DEVFMT "%sdrm%d"
+#define KMSDRM_DRI_DEVNAME "drm"
+#define KMSDRM_DRI_DEVNAMESIZE 3
+#define KMSDRM_DRI_CARDPATHFMT "/dev/drm%d"
+#else
 #define KMSDRM_DRI_PATH "/dev/dri/"
-
-static int set_client_caps (int fd)
-{
-    if (KMSDRM_drmSetClientCap(fd, DRM_CLIENT_CAP_ATOMIC, 1)) {
-         return SDL_SetError("no atomic modesetting support.");
-    }
-    if (KMSDRM_drmSetClientCap(fd, DRM_CLIENT_CAP_UNIVERSAL_PLANES, 1)) {
-         return SDL_SetError("no universal planes support.");
-    }
-    return 0;
-}
+#define KMSDRM_DRI_DEVFMT "%scard%d"
+#define KMSDRM_DRI_DEVNAME "card"
+#define KMSDRM_DRI_DEVNAMESIZE 4
+#define KMSDRM_DRI_CARDPATHFMT "/dev/dri/card%d"
+#endif
 
 static int
-check_modesetting(int devindex)
+check_modestting(int devindex)
 {
     SDL_bool available = SDL_FALSE;
     char device[512];
     int drm_fd;
 
-    SDL_snprintf(device, sizeof (device), "%scard%d", KMSDRM_DRI_PATH, devindex);
+    SDL_snprintf(device, sizeof (device), KMSDRM_DRI_DEVFMT, KMSDRM_DRI_PATH, devindex);
 
     drm_fd = open(device, O_RDWR | O_CLOEXEC);
     if (drm_fd >= 0) {
         if (SDL_KMSDRM_LoadSymbols()) {
             drmModeRes *resources = KMSDRM_drmModeGetResources(drm_fd);
             if (resources) {
-
                 SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO,
-                  "%scard%d connector, encoder and CRTC counts are: %d %d %d",
-                   KMSDRM_DRI_PATH, devindex,
-                   resources->count_connectors, resources->count_encoders,
-                   resources->count_crtcs);
+                  KMSDRM_DRI_DEVFMT
+                  " connector, encoder and CRTC counts are: %d %d %d",
+                  KMSDRM_DRI_PATH, devindex,
+                  resources->count_connectors, resources->count_encoders,
+                  resources->count_crtcs);
 
                 if (resources->count_connectors > 0
                  && resources->count_encoders > 0
@@ -105,30 +101,32 @@ check_modesetting(int devindex)
     return available;
 }
 
-static unsigned int get_dricount(void)
+static int get_dricount(void)
 {
-    unsigned int devcount = 0;
+    int devcount = 0;
     struct dirent *res;
     struct stat sb;
     DIR *folder;
 
-    if (!(stat(KMSDRM_DRI_PATH, &sb) == 0 && S_ISDIR(sb.st_mode))) {
-        SDL_SetError("The path %s cannot be opened or is not available",
-        KMSDRM_DRI_PATH);
+    if (!(stat(KMSDRM_DRI_PATH, &sb) == 0
+                && S_ISDIR(sb.st_mode))) {
+        printf("The path %s cannot be opened or is not available\n",
+               KMSDRM_DRI_PATH);
         return 0;
     }
 
     if (access(KMSDRM_DRI_PATH, F_OK) == -1) {
-        SDL_SetError("The path %s cannot be opened",
-            KMSDRM_DRI_PATH);
+        printf("The path %s cannot be opened\n",
+               KMSDRM_DRI_PATH);
         return 0;
     }
 
     folder = opendir(KMSDRM_DRI_PATH);
     if (folder) {
         while ((res = readdir(folder))) {
-            size_t len = SDL_strlen(res->d_name);
-            if (len > 4 && SDL_strncmp(res->d_name, "card", 4) == 0) {
+            int len = SDL_strlen(res->d_name);
+            if (len > KMSDRM_DRI_DEVNAMESIZE && SDL_strncmp(res->d_name,
+                      KMSDRM_DRI_DEVNAME, KMSDRM_DRI_DEVNAMESIZE) == 0) {
                 devcount++;
             }
         }
@@ -141,11 +139,11 @@ static unsigned int get_dricount(void)
 static int
 get_driindex(void)
 {
-    const unsigned int devcount = get_dricount();
-    unsigned int i;
+    const int devcount = get_dricount();
+    int i;
 
     for (i = 0; i < devcount; i++) {
-        if (check_modesetting(i)) {
+        if (check_modestting(i)) {
             return i;
         }
     }
@@ -153,425 +151,6 @@ get_driindex(void)
     return -ENOENT;
 }
 
-/*********************************/
-/* Atomic helper functions block */
-/*********************************/
-
-#define VOID2U64(x) ((uint64_t)(unsigned long)(x))
-
-int add_connector_property(drmModeAtomicReq *req, struct connector *connector,
-                                     const char *name, uint64_t value)
-{
-    unsigned int i;
-    int prop_id = 0;
-
-    for (i = 0 ; i < connector->props->count_props ; i++) {
-        if (strcmp(connector->props_info[i]->name, name) == 0) {
-            prop_id = connector->props_info[i]->prop_id;
-            break;
-        }
-    }
-
-    if (prop_id < 0) {
-        SDL_SetError("no connector property: %s", name);
-        return -EINVAL;
-    }
-
-    return KMSDRM_drmModeAtomicAddProperty(req, connector->connector->connector_id, prop_id, value);
-}
-
-int add_crtc_property(drmModeAtomicReq *req, struct crtc *crtc,
-                         const char *name, uint64_t value)
-{
-    unsigned int i;
-    int prop_id = -1;
-
-    for (i = 0 ; i < crtc->props->count_props ; i++) {
-        if (strcmp(crtc->props_info[i]->name, name) == 0) {
-            prop_id = crtc->props_info[i]->prop_id;
-            break;
-        }
-    }
-
-    if (prop_id < 0) {
-        SDL_SetError("no crtc property: %s", name);
-        return -EINVAL;
-    }
-
-    return KMSDRM_drmModeAtomicAddProperty(req, crtc->crtc->crtc_id, prop_id, value);
-}
-
-int add_plane_property(drmModeAtomicReq *req, struct plane *plane,
-                          const char *name, uint64_t value)
-{
-    unsigned int i;
-    int prop_id = -1;
-
-    for (i = 0 ; i < plane->props->count_props ; i++) {
-        if (strcmp(plane->props_info[i]->name, name) == 0) {
-            prop_id = plane->props_info[i]->prop_id;
-            break;
-        }
-    }
-
-    if (prop_id < 0) {
-        SDL_SetError("no plane property: %s", name);
-        return -EINVAL;
-    }
-
-    return KMSDRM_drmModeAtomicAddProperty(req, plane->plane->plane_id, prop_id, value);
-}
-
-#if 0
-
-void print_plane_info(_THIS, drmModePlanePtr plane)
-{
-    char *plane_type;
-    drmModeRes *resources;
-    uint32_t type = 0;
-    SDL_VideoData *viddata = ((SDL_VideoData *)_this->driverdata);
-    int i;
-
-    drmModeObjectPropertiesPtr props = KMSDRM_drmModeObjectGetProperties(viddata->drm_fd,
-        plane->plane_id, DRM_MODE_OBJECT_PLANE);
-
-    /* Search the plane props for the plane type. */
-    for (i = 0; i < props->count_props; i++) {
-        drmModePropertyPtr p = KMSDRM_drmModeGetProperty(viddata->drm_fd, props->props[i]);
-        if ((strcmp(p->name, "type") == 0)) {
-            type = props->prop_values[i];
-        }
-
-        KMSDRM_drmModeFreeProperty(p);
-    }
-
-    switch (type) {
-        case DRM_PLANE_TYPE_OVERLAY:
-            plane_type = "overlay";
-            break;
-
-        case DRM_PLANE_TYPE_PRIMARY:
-            plane_type = "primary";
-            break;
-
-        case DRM_PLANE_TYPE_CURSOR:
-            plane_type = "cursor";
-            break;
-    }
-
-
-    /* Remember that to present a plane on screen, it has to be
-       connected to a CRTC so the CRTC scans it,
-       scales it, etc... and presents it on screen. */
-
-    /* Now we look for the CRTCs supported by the plane. */
-    resources = KMSDRM_drmModeGetResources(viddata->drm_fd);
-    if (!resources)
-        return;
-
-    printf("--PLANE ID: %d\nPLANE TYPE: %s\nCRTC READING THIS PLANE: %d\nCRTCS SUPPORTED BY THIS PLANE: ",  plane->plane_id, plane_type, plane->crtc_id);
-    for (i = 0; i < resources->count_crtcs; i++) {
-        if (plane->possible_crtcs & (1 << i)) {
-            uint32_t crtc_id = resources->crtcs[i];
-            printf ("%d", crtc_id);
-            break;
-        }
-    }
-
-    printf ("\n\n");
-}
-
-void get_planes_info(_THIS)
-{
-    drmModePlaneResPtr plane_resources;
-    uint32_t i;
-
-    SDL_VideoData *viddata = ((SDL_VideoData *)_this->driverdata);
-    SDL_DisplayData *dispdata = (SDL_DisplayData *)SDL_GetDisplayDriverData(0);
-
-    plane_resources = KMSDRM_drmModeGetPlaneResources(viddata->drm_fd);
-    if (!plane_resources) {
-        printf("drmModeGetPlaneResources failed: %s\n", strerror(errno));
-        return;
-    }
-
-    printf("--Number of planes found: %d-- \n", plane_resources->count_planes);
-    printf("--Usable CRTC that we have chosen: %d-- \n", dispdata->crtc->crtc->crtc_id);
-
-    /* Iterate on all the available planes. */
-    for (i = 0; (i < plane_resources->count_planes); i++) {
-
-        uint32_t plane_id = plane_resources->planes[i];
-
-        drmModePlanePtr plane = KMSDRM_drmModeGetPlane(viddata->drm_fd, plane_id);
-        if (!plane) {
-            printf("drmModeGetPlane(%u) failed: %s\n", plane_id, strerror(errno));
-            continue;
-        }
-
-        /* Print plane info. */
-        print_plane_info(_this, plane);
-        KMSDRM_drmModeFreePlane(plane);
-    }
-
-    KMSDRM_drmModeFreePlaneResources(plane_resources);
-}
-
-#endif
-
-/* Get the plane_id of a plane that is of the specified plane type (primary,
-   overlay, cursor...) and can use specified CRTC. */
-static int get_plane_id(_THIS, unsigned int crtc_id, uint32_t plane_type)
-{
-    drmModeRes *resources = NULL;
-    drmModePlaneResPtr plane_resources = NULL;
-    uint32_t i, j;
-    unsigned int crtc_index = 0;
-    int ret = -EINVAL;
-    int found = 0;
-
-    SDL_VideoData *viddata = ((SDL_VideoData *)_this->driverdata);
-
-    resources = KMSDRM_drmModeGetResources(viddata->drm_fd);
-
-    /* Get the crtc_index for the current CRTC.
-       It's needed to find out if a plane supports the CRTC. */
-    for (i = 0; i < resources->count_crtcs; i++) {
-        if (resources->crtcs[i] == crtc_id) {
-            crtc_index = i;
-            break;
-        }
-    }
-
-    plane_resources = KMSDRM_drmModeGetPlaneResources(viddata->drm_fd);
-    if (!plane_resources) {
-        return SDL_SetError("drmModeGetPlaneResources failed.");
-    }
-
-    /* Iterate on all the available planes. */
-    for (i = 0; (i < plane_resources->count_planes) && !found; i++) {
-
-        uint32_t plane_id = plane_resources->planes[i];
-
-        drmModePlanePtr plane = KMSDRM_drmModeGetPlane(viddata->drm_fd, plane_id);
-        if (!plane) {
-            continue;
-        }
-
-        /* See if the current CRTC is available for this plane. */
-        if (plane->possible_crtcs & (1 << crtc_index)) {
-
-            drmModeObjectPropertiesPtr props = KMSDRM_drmModeObjectGetProperties(
-                viddata->drm_fd, plane_id, DRM_MODE_OBJECT_PLANE);
-            ret = plane_id;
-
-            /* Iterate on the plane props to find the type of the plane,
-               to see if it's of the type we want. */
-            for (j = 0; j < props->count_props; j++) {
-
-                drmModePropertyPtr p = KMSDRM_drmModeGetProperty(viddata->drm_fd,
-                    props->props[j]);
-
-                if ((strcmp(p->name, "type") == 0) && (props->prop_values[j] == plane_type)) {
-                    /* found our plane, use that: */
-                    found = 1;
-                }
-
-                KMSDRM_drmModeFreeProperty(p);
-            }
-
-            KMSDRM_drmModeFreeObjectProperties(props);
-        }
-
-        KMSDRM_drmModeFreePlane(plane);
-    }
-
-    KMSDRM_drmModeFreePlaneResources(plane_resources);
-    KMSDRM_drmModeFreeResources(resources);
-
-    return ret;
-}
-
-/* Setup a plane and it's props. */
-int
-setup_plane(_THIS, struct plane **plane, uint32_t plane_type)
-{
-    uint32_t plane_id;
-    SDL_VideoData *viddata = ((SDL_VideoData *)_this->driverdata);
-    SDL_DisplayData *dispdata = (SDL_DisplayData *)SDL_GetDisplayDriverData(0);
-    int ret = 0;
-
-    *plane = SDL_calloc(1, sizeof(**plane));
-    if (!(*plane)) {
-        ret = SDL_OutOfMemory();
-        goto cleanup;
-    }
-
-    /* Get plane ID for a given CRTC and plane type. */
-    plane_id = get_plane_id(_this, dispdata->crtc->crtc->crtc_id, plane_type);
-
-    if (!plane_id) {
-        ret = SDL_SetError("Invalid Plane ID");
-        goto cleanup;
-    }
-
-    /* Get the DRM plane itself. */
-    (*plane)->plane = KMSDRM_drmModeGetPlane(viddata->drm_fd, plane_id);
-
-    /* Get the DRM plane properties. */
-    if ((*plane)->plane) {
-        unsigned int i;
-        (*plane)->props = KMSDRM_drmModeObjectGetProperties(viddata->drm_fd,
-        (*plane)->plane->plane_id, DRM_MODE_OBJECT_PLANE);
-        (*plane)->props_info = SDL_calloc((*plane)->props->count_props,
-            sizeof(*(*plane)->props_info));
-
-        if ( !((*plane)->props_info) ) {
-            ret = SDL_OutOfMemory();
-            goto cleanup;
-        }
-
-        for (i = 0; i < (*plane)->props->count_props; i++) {
-            (*plane)->props_info[i] = KMSDRM_drmModeGetProperty(viddata->drm_fd,
-                (*plane)->props->props[i]);
-        }
-    }
-
-cleanup:
-
-    if (ret) {
-        if (*plane) {
-            SDL_free(*plane);
-            *plane = NULL;
-        }
-    }
-    return ret;
-}
-
-/* Free a plane and it's props. */
-void
-free_plane(struct plane **plane)
-{
-    if (*plane) {
-        if ((*plane)->plane) {
-            KMSDRM_drmModeFreePlane((*plane)->plane);
-            (*plane)->plane = NULL;
-        }
-        if ((*plane)->props_info) {
-            SDL_free((*plane)->props_info);
-            (*plane)->props_info = NULL;
-        }
-        SDL_free(*plane);
-        *plane = NULL;
-    }
-}
-
-/**********************************************************************************/
-/* The most important ATOMIC fn of the backend.                                   */
-/* A PLANE reads a BUFFER, and a CRTC reads a PLANE and sends it's contents       */
-/*   over to a CONNECTOR->ENCODER system (several CONNECTORS can be connected     */
-/*   to the same PLANE).                                                          */
-/*   Think of a plane as a "frame" sorrounding a picture, where the "picture"     */
-/*   is the buffer, and we move the "frame" from  a picture to another,           */
-/*   and the one that has the "frame" is the one sent over to the screen          */
-/*   via the CONNECTOR->ENCODER system.                                           */
-/*   Think of a PLANE as being "in the middle", it's the CENTRAL part             */
-/*   bewteen the CRTC and the BUFFER that is shown on screen.                     */
-/*   What we do here is connect a PLANE to a CRTC and a BUFFER.                   */
-/*   -ALWAYS set the CRTC_ID and FB_ID attribs of a plane at the same time,       */
-/*   meaning IN THE SAME atomic request.                                          */
-/*   -And NEVER destroy a GBM surface whose buffers are being read by a plane:    */
-/*   first, move the plane away from those buffers and ONLY THEN destroy the      */
-/*   buffers and/or the GBM surface containig them.                               */
-/**********************************************************************************/
-void
-drm_atomic_set_plane_props(struct KMSDRM_PlaneInfo *info)
-{
-    SDL_DisplayData *dispdata = (SDL_DisplayData *)SDL_GetDisplayDriverData(0);
-
-    /* Do we have a set of changes already in the making? If not, allocate a new one. */
-    if (!dispdata->atomic_req)
-        dispdata->atomic_req = KMSDRM_drmModeAtomicAlloc();
-
-    add_plane_property(dispdata->atomic_req, info->plane, "FB_ID", info->fb_id);
-    add_plane_property(dispdata->atomic_req, info->plane, "CRTC_ID", info->crtc_id);
-    add_plane_property(dispdata->atomic_req, info->plane, "SRC_W", info->src_w << 16);
-    add_plane_property(dispdata->atomic_req, info->plane, "SRC_H", info->src_h << 16);
-    add_plane_property(dispdata->atomic_req, info->plane, "SRC_X", info->src_x);
-    add_plane_property(dispdata->atomic_req, info->plane, "SRC_Y", info->src_y);
-    add_plane_property(dispdata->atomic_req, info->plane, "CRTC_W", info->crtc_w);
-    add_plane_property(dispdata->atomic_req, info->plane, "CRTC_H", info->crtc_h);
-    add_plane_property(dispdata->atomic_req, info->plane, "CRTC_X", info->crtc_x);
-    add_plane_property(dispdata->atomic_req, info->plane, "CRTC_Y", info->crtc_y);
-}
-
-int drm_atomic_commit(_THIS, SDL_bool blocking, SDL_bool allow_modeset)
-{
-    SDL_DisplayData *dispdata = (SDL_DisplayData *)SDL_GetDisplayDriverData(0);
-    SDL_VideoData *viddata = ((SDL_VideoData *)_this->driverdata);
-    uint32_t atomic_flags = 0;
-    int ret;
-
-    if (!blocking) {
-        atomic_flags |= DRM_MODE_ATOMIC_NONBLOCK;
-    }
-
-    if (allow_modeset) {
-        atomic_flags |= DRM_MODE_ATOMIC_ALLOW_MODESET;
-    }
-
-    /* Never issue a new atomic commit if previous has not yet completed,
-       or it will error. */
-    drm_atomic_waitpending(_this);
-
-    ret = KMSDRM_drmModeAtomicCommit(viddata->drm_fd, dispdata->atomic_req,
-              atomic_flags, NULL);
-
-    if (ret) {
-        SDL_SetError("Atomic commit failed, returned %d.", ret);
-        /* Uncomment this for fast-debugging */
-#if 0
-        printf("ATOMIC COMMIT FAILED: %s.\n", strerror(errno));
-#endif
-        goto out;
-    }
-
-    if (dispdata->kms_in_fence_fd != -1) {
-        close(dispdata->kms_in_fence_fd);
-        dispdata->kms_in_fence_fd = -1;
-    }
-
-out:
-    KMSDRM_drmModeAtomicFree(dispdata->atomic_req);
-    dispdata->atomic_req = NULL;
-
-    return ret;
-}
-
-void
-drm_atomic_waitpending(_THIS)
-{
-    SDL_DisplayData *dispdata = (SDL_DisplayData *)SDL_GetDisplayDriverData(0);
-
-    /* Will return immediately if we have already destroyed the fence, because we NULL-ify it just after.
-       Also, will return immediately in double-buffer mode, because kms_fence will alsawys be NULL. */
-    if (dispdata->kms_fence) {
-        EGLint status;
-
-        do {
-            status = _this->egl_data->eglClientWaitSyncKHR(_this->egl_data->egl_display,
-                dispdata->kms_fence, 0, EGL_FOREVER_KHR);
-        } while (status != EGL_CONDITION_SATISFIED_KHR);
-
-        _this->egl_data->eglDestroySyncKHR(_this->egl_data->egl_display, dispdata->kms_fence);
-            dispdata->kms_fence = NULL;
-    }
-}
-
-/***************************************/
-/* End of Atomic helper functions block*/
-/***************************************/
-
 static int
 KMSDRM_Available(void)
 {
@@ -581,7 +160,7 @@ KMSDRM_Available(void)
     if (ret >= 0)
         return 1;
 
-   return ret;
+    return ret;
 }
 
 static void
@@ -597,36 +176,6 @@ KMSDRM_DeleteDevice(SDL_VideoDevice * device)
     SDL_KMSDRM_UnloadSymbols();
 }
 
-static int
-KMSDRM_GetDisplayDPI(_THIS, SDL_VideoDisplay * display, float * ddpi, float * hdpi, float * vdpi)
-{
-    int w, h;
-
-    uint32_t display_mm_width;
-    uint32_t display_mm_height;
-
-    SDL_DisplayData *dispdata;
-
-    dispdata = (SDL_DisplayData *)SDL_GetDisplayDriverData(0); //viddata->devindex);
-
-
-    if (!dispdata) {
-        return SDL_SetError("No available displays");
-    }
-
-    display_mm_width = dispdata->connector->connector->mmWidth;
-    display_mm_height = dispdata->connector->connector->mmHeight;
-
-    w = dispdata->mode.hdisplay;
-    h = dispdata->mode.vdisplay;
-
-    *hdpi = display_mm_width ? (((float) w) * 25.4f / display_mm_width) : 0.0f;
-    *vdpi = display_mm_height ? (((float) h) * 25.4f / display_mm_height) : 0.0f;
-    *ddpi = SDL_ComputeDiagonalDPI(w, h, ((float) display_mm_width) / 25.4f,((float) display_mm_height) / 25.4f);
-
-    return 0;
-}
-
 static SDL_VideoDevice *
 KMSDRM_CreateDevice(int devindex)
 {
@@ -642,7 +191,7 @@ KMSDRM_CreateDevice(int devindex)
     }
 
     if (devindex < 0) {
-        SDL_SetError("devindex (%d) must be between 0 and 99.", devindex);
+        SDL_SetError("devindex (%d) must be between 0 and 99.\n", devindex);
         return NULL;
     }
 
@@ -664,16 +213,13 @@ KMSDRM_CreateDevice(int devindex)
     viddata->devindex = devindex;
     viddata->drm_fd = -1;
 
-    viddata->vulkan_mode = SDL_FALSE;
-
     device->driverdata = viddata;
 
-    /* Setup all functions that can be handled from this backend. */
+    /* Setup all functions which we can handle */
     device->VideoInit = KMSDRM_VideoInit;
     device->VideoQuit = KMSDRM_VideoQuit;
     device->GetDisplayModes = KMSDRM_GetDisplayModes;
     device->SetDisplayMode = KMSDRM_SetDisplayMode;
-    device->GetDisplayDPI = KMSDRM_GetDisplayDPI;
     device->CreateSDLWindow = KMSDRM_CreateWindow;
     device->CreateSDLWindowFrom = KMSDRM_CreateWindowFrom;
     device->SetWindowTitle = KMSDRM_SetWindowTitle;
@@ -691,17 +237,15 @@ KMSDRM_CreateDevice(int devindex)
     device->DestroyWindow = KMSDRM_DestroyWindow;
     device->GetWindowWMInfo = KMSDRM_GetWindowWMInfo;
 
-    device->GL_DefaultProfileConfig = KMSDRM_GLES_DefaultProfileConfig;
+    device->GL_LoadLibrary = KMSDRM_GLES_LoadLibrary;
     device->GL_GetProcAddress = KMSDRM_GLES_GetProcAddress;
+    device->GL_UnloadLibrary = KMSDRM_GLES_UnloadLibrary;
     device->GL_CreateContext = KMSDRM_GLES_CreateContext;
     device->GL_MakeCurrent = KMSDRM_GLES_MakeCurrent;
     device->GL_SetSwapInterval = KMSDRM_GLES_SetSwapInterval;
     device->GL_GetSwapInterval = KMSDRM_GLES_GetSwapInterval;
     device->GL_SwapWindow = KMSDRM_GLES_SwapWindow;
     device->GL_DeleteContext = KMSDRM_GLES_DeleteContext;
-    /* Those two functions are dummy. We do these things manually. */
-    device->GL_LoadLibrary = KMSDRM_GLES_LoadLibrary;
-    device->GL_UnloadLibrary = KMSDRM_GLES_UnloadLibrary;
 
 #if SDL_VIDEO_VULKAN
     device->Vulkan_LoadLibrary = KMSDRM_Vulkan_LoadLibrary;
@@ -747,11 +291,9 @@ KMSDRM_FBInfo *
 KMSDRM_FBFromBO(_THIS, struct gbm_bo *bo)
 {
     SDL_VideoData *viddata = ((SDL_VideoData *)_this->driverdata);
-    unsigned width, height;
-    uint32_t format, strides[4] = {0}, handles[4] = {0}, offsets[4] = {0};
-    const int num_planes = KMSDRM_gbm_bo_get_plane_count(bo);
-    unsigned int i;
+    unsigned w,h;
     int ret;
+    Uint32 stride, handle;
 
     /* Check for an existing framebuffer */
     KMSDRM_FBInfo *fb_info = (KMSDRM_FBInfo *)KMSDRM_gbm_bo_get_user_data(bo);
@@ -760,9 +302,10 @@ KMSDRM_FBFromBO(_THIS, struct gbm_bo *bo)
         return fb_info;
     }
 
-    /* Create a structure that contains the info about framebuffer
-       that we need to use it. */
+    /* Create a structure that contains enough info to remove the framebuffer
+       when the backing buffer is destroyed */
     fb_info = (KMSDRM_FBInfo *)SDL_calloc(1, sizeof(KMSDRM_FBInfo));
+
     if (!fb_info) {
         SDL_OutOfMemory();
         return NULL;
@@ -770,35 +313,71 @@ KMSDRM_FBFromBO(_THIS, struct gbm_bo *bo)
 
     fb_info->drm_fd = viddata->drm_fd;
 
-    width = KMSDRM_gbm_bo_get_width(bo);
-    height = KMSDRM_gbm_bo_get_height(bo);
-    format = KMSDRM_gbm_bo_get_format(bo);
-
-    for (i = 0; i < num_planes; i++) {
-        strides[i] = KMSDRM_gbm_bo_get_stride_for_plane(bo, i);
-        handles[i] = KMSDRM_gbm_bo_get_handle(bo).u32;
-        offsets[i] = KMSDRM_gbm_bo_get_offset(bo, i);
-    }
-
-    /* Create framebuffer object for the buffer.
-       It's VERY important to note that fb_id is what we use to set the FB_ID prop
-       of a plane when using the ATOMIC interface, and we get the fb_id here. */
-    ret = KMSDRM_drmModeAddFB2(viddata->drm_fd, width, height, format,
-            handles, strides, offsets, &fb_info->fb_id, 0);
-
+    /* Create framebuffer object for the buffer */
+    w = KMSDRM_gbm_bo_get_width(bo);
+    h = KMSDRM_gbm_bo_get_height(bo);
+    stride = KMSDRM_gbm_bo_get_stride(bo);
+    handle = KMSDRM_gbm_bo_get_handle(bo).u32;
+    ret = KMSDRM_drmModeAddFB(viddata->drm_fd, w, h, 24, 32, stride, handle,
+                                  &fb_info->fb_id);
     if (ret) {
       SDL_free(fb_info);
       return NULL;
     }
 
-    /* Set the userdata pointer. This pointer is used to store custom data that we need
-       to access in the future, so we store the fb_id here for later use, because fb_id is
-       what we need to set the FB_ID property of a plane when using the ATOMIC interface. */
+    SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "New DRM FB (%u): %ux%u, stride %u from BO %p",
+                 fb_info->fb_id, w, h, stride, (void *)bo);
+
+    /* Associate our DRM framebuffer with this buffer object */
     KMSDRM_gbm_bo_set_user_data(bo, fb_info, KMSDRM_FBDestroyCallback);
 
     return fb_info;
 }
 
+static void
+KMSDRM_FlipHandler(int fd, unsigned int frame, unsigned int sec, unsigned int usec, void *data)
+{
+    *((SDL_bool *) data) = SDL_FALSE;
+}
+
+SDL_bool
+KMSDRM_WaitPageFlip(_THIS, SDL_WindowData *windata, int timeout) {
+    SDL_VideoData *viddata = ((SDL_VideoData *)_this->driverdata);
+    drmEventContext ev = {0};
+    struct pollfd pfd = {0};
+
+    ev.version = DRM_EVENT_CONTEXT_VERSION;
+    ev.page_flip_handler = KMSDRM_FlipHandler;
+
+    pfd.fd = viddata->drm_fd;
+    pfd.events = POLLIN;
+
+    while (windata->waiting_for_flip) {
+        pfd.revents = 0;
+
+        if (poll(&pfd, 1, timeout) < 0) {
+            SDL_LogError(SDL_LOG_CATEGORY_VIDEO, "DRM poll error");
+            return SDL_FALSE;
+        }
+
+        if (pfd.revents & (POLLHUP | POLLERR)) {
+            SDL_LogError(SDL_LOG_CATEGORY_VIDEO, "DRM poll hup or error");
+            return SDL_FALSE;
+        }
+
+        if (pfd.revents & POLLIN) {
+            /* Page flip? If so, drmHandleEvent will unset windata->waiting_for_flip */
+            KMSDRM_drmHandleEvent(viddata->drm_fd, &ev);
+        } else {
+            /* Timed out and page flip didn't happen */
+            SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "Dropping frame while waiting_for_flip");
+            return SDL_FALSE;
+        }
+    }
+
+    return SDL_TRUE;
+}
+
 /*****************************************************************************/
 /* SDL Video and Display initialization/handling functions                   */
 /* _this is a SDL_VideoDevice *                                              */
@@ -809,29 +388,13 @@ KMSDRM_FBFromBO(_THIS, struct gbm_bo *bo)
 void KMSDRM_DisplayDataDeinit (_THIS, SDL_DisplayData *dispdata) {
     /* Free connector */
     if (dispdata && dispdata->connector) {
-        if (dispdata->connector->connector) {
-            KMSDRM_drmModeFreeConnector(dispdata->connector->connector);
-            dispdata->connector->connector = NULL;
-        }
-        if (dispdata->connector->props_info) {
-            SDL_free(dispdata->connector->props_info);
-            dispdata->connector->props_info = NULL;
-        }
-        SDL_free(dispdata->connector);
-        dispdata->connector = NULL;
+	KMSDRM_drmModeFreeConnector(dispdata->connector);
+	dispdata->connector = NULL;
     }
 
     /* Free CRTC */
     if (dispdata && dispdata->crtc) {
-        if (dispdata->crtc->crtc) {
-            KMSDRM_drmModeFreeCrtc(dispdata->crtc->crtc);
-            dispdata->crtc->crtc = NULL;
-        }
-        if (dispdata->crtc->props_info) {
-            SDL_free(dispdata->crtc->props_info);
-            dispdata->crtc->props_info = NULL;
-        }
-        SDL_free(dispdata->crtc);
+        KMSDRM_drmModeFreeCrtc(dispdata->crtc);
         dispdata->crtc = NULL;
     }
 }
@@ -849,49 +412,27 @@ int KMSDRM_DisplayDataInit (_THIS, SDL_DisplayData *dispdata) {
     drmModeConnector *connector = NULL;
     drmModeCrtc *crtc = NULL;
 
-    char devname[32];
     int ret = 0;
     unsigned i,j;
 
-    dispdata->atomic_req = NULL;
-    dispdata->kms_fence = NULL;
-    dispdata->gpu_fence = NULL;
-    dispdata->kms_out_fence_fd = -1;
     dispdata->modeset_pending = SDL_FALSE;
     dispdata->gbm_init = SDL_FALSE;
 
-    dispdata->display_plane = NULL;
-    dispdata->cursor_plane = NULL;
-
     dispdata->cursor_bo = NULL;
 
-    /* Open /dev/dri/cardNN */
-    SDL_snprintf(viddata->devpath, sizeof(viddata->devpath), "/dev/dri/card%d", viddata->devindex);
+    /* Open /dev/dri/cardNN (/dev/drmN if on OpenBSD) */
+    SDL_snprintf(viddata->devpath, sizeof(viddata->devpath), KMSDRM_DRI_CARDPATHFMT, viddata->devindex);
 
-    SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "Opening device %s", devname);
+    SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "Opening device %s", viddata->devpath);
     viddata->drm_fd = open(viddata->devpath, O_RDWR | O_CLOEXEC);
 
     if (viddata->drm_fd < 0) {
-        ret = SDL_SetError("Could not open %s", devname);
+        ret = SDL_SetError("Could not open %s", viddata->devpath);
         goto cleanup;
     }
 
     SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "Opened DRM FD (%d)", viddata->drm_fd);
 
-    /********************************************/
-    /* Block for enabling ATOMIC compatibility. */
-    /********************************************/
-
-    /* Set ATOMIC & UNIVERSAL PLANES compatibility */
-    ret = set_client_caps(viddata->drm_fd);
-    if (ret) {
-        goto cleanup;
-    }
-
-    /*******************************************/
-    /* Block for getting the ATOMIC resources. */
-    /*******************************************/
-
     /* Get all of the available connectors / devices / crtcs */
     resources = KMSDRM_drmModeGetResources(viddata->drm_fd);
     if (!resources) {
@@ -909,10 +450,7 @@ int KMSDRM_DisplayDataInit (_THIS, SDL_DisplayData *dispdata) {
         }
 
         if (conn->connection == DRM_MODE_CONNECTED && conn->count_modes) {
-            SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "Found connector %d with %d modes.",
-                         conn->connector_id, conn->count_modes);
             connector = conn;
-
             break;
         }
 
@@ -933,7 +471,6 @@ int KMSDRM_DisplayDataInit (_THIS, SDL_DisplayData *dispdata) {
         }
 
         if (encoder->encoder_id == connector->encoder_id) {
-            SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "Found encoder %d.", encoder->encoder_id);
             break;
         }
 
@@ -944,7 +481,8 @@ int KMSDRM_DisplayDataInit (_THIS, SDL_DisplayData *dispdata) {
     if (!encoder) {
         /* No encoder was connected, find the first supported one */
         for (i = 0; i < resources->count_encoders; i++) {
-            encoder = KMSDRM_drmModeGetEncoder(viddata->drm_fd, resources->encoders[i]);
+            encoder = KMSDRM_drmModeGetEncoder(viddata->drm_fd,
+                          resources->encoders[i]);
 
             if (!encoder) {
               continue;
@@ -970,8 +508,6 @@ int KMSDRM_DisplayDataInit (_THIS, SDL_DisplayData *dispdata) {
         goto cleanup;
     }
 
-    SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "Found encoder %d.", encoder->encoder_id);
-
     /* Try to find a CRTC connected to this encoder */
     crtc = KMSDRM_drmModeGetCrtc(viddata->drm_fd, encoder->crtc_id);
 
@@ -998,58 +534,22 @@ int KMSDRM_DisplayDataInit (_THIS, SDL_DisplayData *dispdata) {
     /* Save the original mode for restoration on quit. */
     dispdata->original_mode = dispdata->mode;
 
-    if (dispdata->mode.hdisplay == 0 || dispdata->mode.vdisplay == 0 ) {
-        ret = SDL_SetError("Couldn't get a valid connector videomode.");
-        goto cleanup;
-    }
-
-    /* Get CRTC properties */
-    dispdata->crtc->props = KMSDRM_drmModeObjectGetProperties(viddata->drm_fd,
-        crtc->crtc_id, DRM_MODE_OBJECT_CRTC);
-
-    dispdata->crtc->props_info = SDL_calloc(dispdata->crtc->props->count_props,
-        sizeof(*dispdata->crtc->props_info));
-
-    if (!dispdata->crtc->props_info) {
-        ret = SDL_OutOfMemory();
-        goto cleanup;
-    }
-
-    for (i = 0; i < dispdata->crtc->props->count_props; i++) {
-        dispdata->crtc->props_info[i] = KMSDRM_drmModeGetProperty(viddata->drm_fd,
-        dispdata->crtc->props->props[i]);
-    }
-
-    /* Get connector properties */
-    dispdata->connector->props = KMSDRM_drmModeObjectGetProperties(viddata->drm_fd,
-        connector->connector_id, DRM_MODE_OBJECT_CONNECTOR);
-
-    dispdata->connector->props_info = SDL_calloc(dispdata->connector->props->count_props,
-        sizeof(*dispdata->connector->props_info));
-
-    if (!dispdata->connector->props_info) {
-        ret = SDL_OutOfMemory();
-        goto cleanup;
-    }
-
-    for (i = 0; i < dispdata->connector->props->count_props; i++) {
-        dispdata->connector->props_info[i] = KMSDRM_drmModeGetProperty(viddata->drm_fd,
-        dispdata->connector->props->props[i]);
+    if (dispdata->mode.hdisplay == 0 || dispdata->mode.vdisplay == 0 ) {
+        ret = SDL_SetError("Couldn't get a valid connector videomode.");
+        goto cleanup;
     }
 
-    /* Store the connector and crtc for future use. This is all we keep from this function,
-       and these are just structs, inoffensive to VK. */
-    dispdata->connector->connector = connector;
-    dispdata->crtc->crtc = crtc;
+    /* Store the connector and crtc for future use. These are all we keep
+       from this function, and these are just structs, inoffensive to VK. */
+    dispdata->connector = connector;
+    dispdata->crtc = crtc;
 
     /***********************************/
-    /* Block fpr Vulkan compatibility. */
+    /* Block for Vulkan compatibility. */
     /***********************************/
 
     /* THIS IS FOR VULKAN! Leave the FD closed, so VK can work.
        Will reopen this in CreateWindow, but only if requested a non-VK window. */
-    KMSDRM_drmSetClientCap(viddata->drm_fd, DRM_CLIENT_CAP_ATOMIC, 0);
-    KMSDRM_drmSetClientCap(viddata->drm_fd, DRM_CLIENT_CAP_UNIVERSAL_PLANES, 0);
     close (viddata->drm_fd);
     viddata->drm_fd = -1;
 
@@ -1060,21 +560,13 @@ cleanup:
         KMSDRM_drmModeFreeResources(resources);
     if (ret) {
         /* Error (complete) cleanup */
-        if (dispdata->connector->connector) {
-            KMSDRM_drmModeFreeConnector(dispdata->connector->connector);
-            dispdata->connector->connector = NULL;
-        }
-        if (dispdata->crtc->props_info) {
-            SDL_free(dispdata->crtc->props_info);
-            dispdata->crtc->props_info = NULL;
-        }
-        if (dispdata->connector->props_info) {
-            SDL_free(dispdata->connector->props_info);
-            dispdata->connector->props_info = NULL;
+        if (dispdata->connector) {
+            KMSDRM_drmModeFreeConnector(dispdata->connector);
+            dispdata->connector = NULL;
         }
-        if (dispdata->crtc->crtc) {
-            KMSDRM_drmModeFreeCrtc(dispdata->crtc->crtc);
-            dispdata->crtc->crtc = NULL;
+        if (dispdata->crtc) {
+            KMSDRM_drmModeFreeCrtc(dispdata->crtc);
+            dispdata->crtc = NULL;
         }
         if (viddata->drm_fd >= 0) {
             close(viddata->drm_fd);
@@ -1101,7 +593,6 @@ KMSDRM_GBMInit (_THIS, SDL_DisplayData *dispdata)
 
     /* Reopen the FD! */
     viddata->drm_fd = open(viddata->devpath, O_RDWR | O_CLOEXEC);
-    set_client_caps(viddata->drm_fd);
 
     /* Create the GBM device. */
     viddata->gbm_dev = KMSDRM_gbm_create_device(viddata->drm_fd);
@@ -1109,13 +600,6 @@ KMSDRM_GBMInit (_THIS, SDL_DisplayData *dispdata)
         ret = SDL_SetError("Couldn't create gbm device.");
     }
 
-    /* Setup the display plane. ONLY do this after dispdata has the right
-       crtc and connector, because these are used in this function. */
-    ret = setup_plane(_this, &(dispdata->display_plane), DRM_PLANE_TYPE_PRIMARY);
-    if (ret) {
-        ret = SDL_SetError("can't find suitable display plane.");
-    }
-
     dispdata->gbm_init = SDL_TRUE;
 
     return ret;
@@ -1127,12 +611,6 @@ KMSDRM_GBMDeinit (_THIS, SDL_DisplayData *dispdata)
 {
     SDL_VideoData *viddata = ((SDL_VideoData *)_this->driverdata);
 
-    /* Free display plane */
-    free_plane(&dispdata->display_plane);
-
-    /* Free cursor plane (if still not freed) */
-    free_plane(&dispdata->cursor_plane);
-
     /* Destroy GBM device. GBM surface is destroyed by DestroySurfaces(),
        already called when we get here. */
     if (viddata->gbm_dev) {
@@ -1152,54 +630,35 @@ KMSDRM_GBMDeinit (_THIS, SDL_DisplayData *dispdata)
 void
 KMSDRM_DestroySurfaces(_THIS, SDL_Window *window)
 {
+    SDL_VideoData *viddata = ((SDL_VideoData *)_this->driverdata);
     SDL_WindowData *windata = (SDL_WindowData *) window->driverdata;
-    SDL_DisplayData *dispdata = (SDL_DisplayData *)SDL_GetDisplayDriverData(0);
-    KMSDRM_PlaneInfo plane_info = {0};
+    SDL_DisplayData *dispdata = (SDL_DisplayData *) SDL_GetDisplayForWindow(window)->driverdata;
+    int ret;
 
-    /* TODO : Continue investigating why this doesn't work. We should do this instead
-       of making the display plane point to the TTY console, which isn't there
-       after creating and destroying a Vulkan window. */
-#if 0
-    /* Disconnect the connector from the CRTC (remember: several connectors
-       can read a CRTC), deactivate the CRTC, and set the PRIMARY PLANE props
-       CRTC_ID and FB_ID to 0. Then we can destroy the GBM buffers and surface. */
-    add_connector_property(dispdata->atomic_req, dispdata->connector , "CRTC_ID", 0);
-    add_crtc_property(dispdata->atomic_req, dispdata->crtc , "MODE_ID", 0); 
-    add_crtc_property(dispdata->atomic_req, dispdata->crtc , "active", 0); 
+    /**********************************************/
+    /* Wait for last issued pageflip to complete. */
+    /**********************************************/
+    KMSDRM_WaitPageFlip(_this, windata, -1);
 
-    plane_info.plane = dispdata->display_plane;
-    plane_info.crtc_id = 0;
-    plane_info.fb_id = 0;
+    /***********************************************************************/
+    /* Restore the original CRTC configuration: configue the crtc with the */
+    /* original video mode and make it point to the original TTY buffer.   */
+    /***********************************************************************/
 
-    drm_atomic_set_plane_props(&plane_info);
+    ret = KMSDRM_drmModeSetCrtc(viddata->drm_fd, dispdata->crtc->crtc_id,
+            dispdata->crtc->buffer_id, 0, 0, &dispdata->connector->connector_id, 1,
+            &dispdata->original_mode);
 
-    /* Issue atomic commit that is blocking and allows modesetting. */
-    if (drm_atomic_commit(_this, SDL_TRUE, SDL_TRUE)) {
-        SDL_SetError("Failed to issue atomic commit on surfaces destruction.");
+    /* If we failed to set the original mode, try to set the connector prefered mode. */
+    if (ret && (dispdata->crtc->mode_valid == 0)) {
+        ret = KMSDRM_drmModeSetCrtc(viddata->drm_fd, dispdata->crtc->crtc_id,
+                dispdata->crtc->buffer_id, 0, 0, &dispdata->connector->connector_id, 1,
+                &dispdata->original_mode);
     }
-#endif
-
-#if 1
-    /************************************************************/
-    /* Make the display plane point to the original TTY buffer. */
-    /* We have to configure it's input and output scaling       */
-    /* parameters accordingly.                                  */
-    /************************************************************/
-
-    plane_info.plane = dispdata->display_plane;
-    plane_info.crtc_id = dispdata->crtc->crtc->crtc_id;
-    plane_info.fb_id = dispdata->crtc->crtc->buffer_id;
-    plane_info.src_w = dispdata->original_mode.hdisplay;
-    plane_info.src_h = dispdata->original_mode.vdisplay;
-    plane_info.crtc_w = dispdata->original_mode.hdisplay;
-    plane_info.crtc_h = dispdata->original_mode.vdisplay;
-
-    drm_atomic_set_plane_props(&plane_info);
 
-    if (drm_atomic_commit(_this, SDL_TRUE, SDL_FALSE)) {
-        SDL_SetError("Failed to issue atomic commit on surfaces destruction.");
+    if(ret) {
+        SDL_LogError(SDL_LOG_CATEGORY_VIDEO, "Could not restore CRTC");
     }
-#endif
 
     /***************************/
     /* Destroy the EGL surface */
@@ -1268,13 +727,13 @@ KMSDRM_CreateSurfaces(_THIS, SDL_Window * window)
     }
 
     if (!KMSDRM_gbm_device_is_format_supported(viddata->gbm_dev,
-        surface_fmt, surface_flags)) {
-            SDL_LogWarn(SDL_LOG_CATEGORY_VIDEO,
-            "GBM surface format not supported. Trying anyway.");
+             surface_fmt, surface_flags)) {
+        SDL_LogWarn(SDL_LOG_CATEGORY_VIDEO,
+        "GBM surface format not supported. Trying anyway.");
     }
 
     windata->gs = KMSDRM_gbm_surface_create(viddata->gbm_dev,
-        width, height, surface_fmt, surface_flags);
+                      width, height, surface_fmt, surface_flags);
 
     if (!windata->gs) {
         return SDL_SetError("Could not create GBM surface");
@@ -1309,113 +768,6 @@ cleanup:
     return ret;
 }
 
-void
-KMSDRM_DestroyWindow(_THIS, SDL_Window *window)
-{
-    SDL_WindowData *windata = (SDL_WindowData *) window->driverdata;
-    SDL_DisplayData *dispdata = (SDL_DisplayData *) SDL_GetDisplayForWindow(window)->driverdata;
-    SDL_VideoData *viddata = windata->viddata;
-    SDL_bool is_vulkan = window->flags & SDL_WINDOW_VULKAN; /* Is this a VK window? */
-    unsigned int i, j;
-
-    if (!windata) {
-        return;
-    }
-
-    if ( !is_vulkan && dispdata->gbm_init ) {
-
-        /* Free cursor plane. */
-        KMSDRM_DeinitMouse(_this);
-
-        /* Destroy GBM surface and buffers. */
-        KMSDRM_DestroySurfaces(_this, window);
-
-        /* Unload EGL library. */
-        if (_this->egl_data) {
-            SDL_EGL_UnloadLibrary(_this);
-        }
-
-        /* Unload GL library. */
-        if (_this->gl_config.driver_loaded) {
-            SDL_GL_UnloadLibrary();
-        }
-
-        /* Free display plane, and destroy GBM device. */
-        KMSDRM_GBMDeinit(_this, dispdata);
-    }
-
-    else {
-        /* If we were in Vulkan mode, get out of it. */
-        if (viddata->vulkan_mode) {
-            viddata->vulkan_mode = SDL_FALSE;
-        }
-    }
-
-    /********************************************/
-    /* Remove from the internal SDL window list */
-    /********************************************/
-
-    for (i = 0; i < viddata->num_windows; i++) {
-        if (viddata->windows[i] == window) {
-            viddata->num_windows--;
-
-            for (j = i; j < viddata->num_windows; j++) {
-                viddata->windows[j] = viddata->windows[j + 1];
-            }
-
-            break;
-        }
-    }
-
-    /*********************************************************************/
-    /* Free the window driverdata. Bye bye, surface and buffer pointers! */
-    /*********************************************************************/
-    window->driverdata = NULL;
-    SDL_free(windata);
-}
-
-/*****************************************************************************/
-/* Reconfigure the window scaling parameters and re-construct it's surfaces, */
-/* without destroying the window itself.                                     */
-/* To be used by SetWindowSize() and SetWindowFullscreen().                  */
-/*****************************************************************************/
-static int
-KMSDRM_ReconfigureWindow( _THIS, SDL_Window * window) {
-    SDL_WindowData *windata = window->driverdata;
-    SDL_DisplayData *dispdata = (SDL_DisplayData *) SDL_GetDisplayForWindow(window)->driverdata;
-    SDL_bool is_vulkan = window->flags & SDL_WINDOW_VULKAN; /* Is this a VK window? */
-    float ratio;
-
-    if (((window->flags & SDL_WINDOW_FULLSCREEN_DESKTOP) == SDL_WINDOW_FULLSCREEN_DESKTOP) ||
-       ((window->flags & SDL_WINDOW_FULLSCREEN) == SDL_WINDOW_FULLSCREEN)) {
-
-        windata->src_w = dispdata->mode.hdisplay;
-        windata->src_h = dispdata->mode.vdisplay;
-        windata->output_w = dispdata->mode.hdisplay;
-        windata->output_h = dispdata->mode.vdisplay;
-        windata->output_x = 0;
-
-    } else {
-        /* Normal non-fullscreen windows are scaled using the PRIMARY PLANE, so here we store:
-           input size (ie: the size of the window buffers),
-           output size (ie: th mode configured on the CRTC), an X position to compensate for AR correction.
-           These are used when we set the PRIMARY PLANE props in SwapWindow() */
-        ratio = (float)window->w / (float)window->h;
-        windata->src_w = window->w;
-        windata->src_h = window->h;
-        windata->output_w = dispdata->mode.vdisplay * ratio;
-        windata->output_h = dispdata->mode.vdisplay;
-        windata->output_x = (dispdata->mode.hdisplay - windata->output_w) / 2;
-    }
-
-    if (!is_vulkan) {
-        if (KMSDRM_CreateSurfaces(_this, window)) {
-            return -1;
-        }
-    }
-    return 0;
-}
-
 int
 KMSDRM_VideoInit(_THIS)
 {
@@ -1434,15 +786,6 @@ KMSDRM_VideoInit(_THIS)
         return SDL_OutOfMemory();
     }
 
-    /* Alloc memory for these. */
-    dispdata->display_plane = SDL_calloc(1, sizeof(*dispdata->display_plane));
-    dispdata->crtc = SDL_calloc(1, sizeof(*dispdata->crtc));
-    dispdata->connector = SDL_calloc(1, sizeof(*dispdata->connector));
-    if (!(dispdata->display_plane) || !(dispdata->crtc) || !(dispdata->connector)) {
-        ret = SDL_OutOfMemory();
-        goto cleanup;
-    }
-
     /* Get KMSDRM resources info and store what we need. Getting and storing
        this info isn't a problem for VK compatibility.
        For VK-incompatible initializations we have KMSDRM_GBMInit(), which is
@@ -1464,11 +807,6 @@ KMSDRM_VideoInit(_THIS)
     /* Add the display only when it's ready, */
     SDL_AddVideoDisplay(&display, SDL_FALSE);
 
-    /* Use this if you ever need to see info on all available planes. */
-#if 0
-    get_planes_info(_this);
-#endif
-
 #ifdef SDL_INPUT_LINUXEV
     SDL_EVDEV_Init();
 #endif
@@ -1486,9 +824,6 @@ cleanup:
 
     if (ret) {
         /* Error (complete) cleanup */
-        if (dispdata->display_plane) {
-            SDL_free(dispdata->display_plane);
-        }
         if (dispdata->crtc) {
             SDL_free(dispdata->crtc);
         }
@@ -1524,36 +859,21 @@ KMSDRM_VideoQuit(_THIS)
     viddata->video_init = SDL_FALSE;
 }
 
-#if 0
-void
-KMSDRM_GetDisplayModes(_THIS, SDL_VideoDisplay * display)
-{
-    /* Only one display mode available: the current one */
-    SDL_AddDisplayMode(display, &display->current_mode);
-}
-#endif
-
-/* We only change the video mode for FULLSCREEN windows
-   that are not FULLSCREEN_DESKTOP.
-   Normal non-fullscreen windows are scaled using the CRTC. */
 void
 KMSDRM_GetDisplayModes(_THIS, SDL_VideoDisplay * display)
 {
     SDL_DisplayData *dispdata = display->driverdata;
-    drmModeConnector *conn = dispdata->connector->connector;
+    drmModeConnector *conn = dispdata->connector;
     SDL_DisplayMode mode;
     int i;
 
     for (i = 0; i < conn->count_modes; i++) {
         SDL_DisplayModeData *modedata = SDL_calloc(1, sizeof(SDL_DisplayModeData));
 
-        if (!modedata) {
-            SDL_OutOfMemory();
-            return;
+        if (modedata) {
+          modedata->mode_index = i;
         }
 
-        modedata->mode_index = i;
-
         mode.w = conn->modes[i].hdisplay;
         mode.h = conn->modes[i].vdisplay;
         mode.refresh_rate = conn->modes[i].vrefresh;
@@ -1569,47 +889,98 @@ KMSDRM_GetDisplayModes(_THIS, SDL_VideoDisplay * display)
 int
 KMSDRM_SetDisplayMode(_THIS, SDL_VideoDisplay * display, SDL_DisplayMode * mode)
 {
-    /* Set the dispdata->mode to the new mode and leave actual modesetting
-       pending to be done on SwapWindow(), to be included on next atomic
-       commit changeset. */
-
     SDL_VideoData *viddata = (SDL_VideoData *)_this->driverdata;
     SDL_DisplayData *dispdata = (SDL_DisplayData *)display->driverdata;
     SDL_DisplayModeData *modedata = (SDL_DisplayModeData *)mode->driverdata;
-    drmModeConnector *conn = dispdata->connector->connector;
+    drmModeConnector *conn = dispdata->connector;
     int i;
 
-    /* Don't do anything if we are in Vulkan mode. */
-    if (viddata->vulkan_mode) {
-        return 0;
-    }
-
     if (!modedata) {
         return SDL_SetError("Mode doesn't have an associated index");
     }
 
-    /* Take note of the new mode to be set. */
     dispdata->mode = conn->modes[modedata->mode_index];
 
-    /* Take note that we have to change mode in SwapWindow(). We have to do it there
-       because we need a buffer of the new size so the commit that contains the
-       mode change can be completed OK.  */
-    dispdata->modeset_pending = SDL_TRUE;
-
     for (i = 0; i < viddata->num_windows; i++) {
         SDL_Window *window = viddata->windows[i];
+        SDL_WindowData *windata = (SDL_WindowData *)window->driverdata;
 
-    if (KMSDRM_CreateSurfaces(_this, window)) {
-        return -1;
-    }
+        /* Can't recreate EGL surfaces right now, need to wait until SwapWindow
+           so the correct thread-local surface and context state are available */
+        windata->egl_surface_dirty = 1;
 
-        /* Tell app about the window resize */
+        /* Tell app about the resize */
         SDL_SendWindowEvent(window, SDL_WINDOWEVENT_RESIZED, mode->w, mode->h);
     }
 
     return 0;
 }
 
+void
+KMSDRM_DestroyWindow(_THIS, SDL_Window *window)
+{
+    SDL_WindowData *windata = (SDL_WindowData *) window->driverdata;
+    SDL_DisplayData *dispdata = (SDL_DisplayData *) SDL_GetDisplayForWindow(window)->driverdata;
+    SDL_VideoData *viddata = windata->viddata;
+    SDL_bool is_vulkan = window->flags & SDL_WINDOW_VULKAN; /* Is this a VK window? */
+    unsigned int i, j;
+
+    if (!windata) {
+        return;
+    }
+
+    if ( !is_vulkan && dispdata->gbm_init ) {
+
+        /* Destroy cursor GBM plane. */
+        KMSDRM_DeinitMouse(_this);
+
+        /* Destroy GBM surface and buffers. */
+        KMSDRM_DestroySurfaces(_this, window);
+
+        /* Unload EGL library. */
+        if (_this->egl_data) {
+            SDL_EGL_UnloadLibrary(_this);
+        }
+
+        /* Unload GL library. */
+        if (_this->gl_config.driver_loaded) {
+            SDL_GL_UnloadLibrary();
+        }
+
+        /* Free display plane, and destroy GBM device. */
+        KMSDRM_GBMDeinit(_this, dispdata);
+    }
+
+    else {
+        /* If we were in Vulkan mode, get out of it. */
+        if (viddata->vulkan_mode) {
+            viddata->vulkan_mode = SDL_FALSE;
+        }
+    }
+
+    /********************************************/
+    /* Remove from the internal SDL window list */
+    /********************************************/
+
+    for (i = 0; i < viddata->num_windows; i++) {
+        if (viddata->windows[i] == window) {
+            viddata->num_windows--;
+
+            for (j = i; j < viddata->num_windows; j++) {
+                viddata->windows[j] = viddata->windows[j + 1];
+            }
+
+            break;
+        }
+    }
+
+    /*********************************************************************/
+    /* Free the window driverdata. Bye bye, surface and buffer pointers! */
+    /*********************************************************************/
+    window->driverdata = NULL;
+    SDL_free(windata);
+}
+
 int
 KMSDRM_CreateWindow(_THIS, SDL_Window * window)
 {
@@ -1637,6 +1008,15 @@ KMSDRM_CreateWindow(_THIS, SDL_Window * window)
             See previous comment on why. */
          window->flags |= SDL_WINDOW_OPENGL;
 
+         /* We need that the fb that SDL gives us has the same size as the videomode
+            currently configure on the CRTC, because the LEGACY interface doesn't
+            support scaling on the primary plane on most hardware (and overlay
+            planes are not present in all hw), so the CRTC reads the PRIMARY PLANE
+            without any scaling, and that's all.
+            So AR-correctin is also impossible on the LEGACY interface. */
+         window->w = dispdata->mode.hdisplay;
+         window->h = dispdata->mode.vdisplay;
+
          /* Reopen FD, create gbm dev, setup display plane, etc,.
             but only when we come here for the first time,
             and only if it's not a VK window. */
@@ -1664,7 +1044,7 @@ KMSDRM_CreateWindow(_THIS, SDL_Window * window)
             so we do it here. */
          KMSDRM_InitMouse(_this);
 
-         /* Since we take cursor buffer away from the cursor plane and
+         /* Since we take cursor buffer way from the cursor plane and
             destroy the cursor GBM BO when we destroy a window, we must
             also manually re-show the cursor on screen, if necessary,
             when we create a window. */
@@ -1678,8 +1058,8 @@ KMSDRM_CreateWindow(_THIS, SDL_Window * window)
         goto cleanup;
     }
 
-    if (((window->flags & SDL_WINDOW_FULLSCREEN_DESKTOP) == SDL_WINDOW_FULLSCREEN_DESKTOP) ||
-       ((window->flags & SDL_WINDOW_FULLSCREEN) == SDL_WINDOW_FULLSCREEN))
+    if (((window->flags & SDL_WINDOW_FULLSCREEN_DESKTOP) == SDL_WINDOW_FULLSCREEN_DESKTOP)
+        || ((window->flags & SDL_WINDOW_FULLSCREEN) == SDL_WINDOW_FULLSCREEN))
     {
         windata->src_w = dispdata->mode.hdisplay;
         windata->src_h = dispdata->mode.vdisplay;
@@ -1687,8 +1067,9 @@ KMSDRM_CreateWindow(_THIS, SDL_Window * window)
         windata->output_h = dispdata->mode.vdisplay;
         windata->output_x = 0;
     } else {
-        /* Normal non-fullscreen windows are scaled using the CRTC,
-           so get output (CRTC) size and position, for AR correction. */
+        /* Normal non-fullscreen windows are scaled to the in-use video mode
+           using a PLANE connected to the CRTC, so get input size,
+           output (CRTC) size, and position. */
         ratio = (float)window->w / (float)window->h;
         windata->src_w = window->w;
         windata->src_h = window->h;
@@ -1710,6 +1091,25 @@ KMSDRM_CreateWindow(_THIS, SDL_Window * window)
         if ((ret = KMSDRM_CreateSurfaces(_this, window))) {
             goto cleanup;
         }
+
+        /***************************************************************************/
+        /* This is fundamental.                                                    */
+        /* We can't display an fb smaller than the resolution currently configured */
+        /* on the CRTC, because the CRTC would be scanning out of bounds, and      */
+        /* drmModeSetCrtc() would fail.                                            */
+        /* A possible solution would be scaling on the primary plane with          */
+        /* drmModeSetPlane(), but primary plane scaling is not supported in most   */
+        /* LEGACY-only hardware, so never use drmModeSetPlane().                   */
+        /***************************************************************************/
+
+        ret = KMSDRM_drmModeSetCrtc(viddata->drm_fd, dispdata->crtc->crtc_id,
+            /*fb_info->fb_id*/ -1, 0, 0, &dispdata->connector->connector_id, 1,
+            &dispdata->mode);
+
+	if (ret) {
+	    SDL_LogError(SDL_LOG_CATEGORY_VIDEO, "Could not set CRTC");
+            goto cleanup;
+	}
     }
 
     /* Add window to the internal list of tracked windows. Note, while it may
@@ -1754,6 +1154,46 @@ cleanup:
     return ret;
 }
 
+/*****************************************************************************/
+/* Reconfigure the window scaling parameters and re-construct it's surfaces, */
+/* without destroying the window itself.                                     */
+/* To be used by SetWindowSize() and SetWindowFullscreen().                  */
+/*****************************************************************************/
+static int
+KMSDRM_ReconfigureWindow( _THIS, SDL_Window * window) {
+    SDL_WindowData *windata = window->driverdata;
+    SDL_DisplayData *dispdata = (SDL_DisplayData *) SDL_GetDisplayForWindow(window)->driverdata;
+    SDL_bool is_vulkan = window->flags & SDL_WINDOW_VULKAN; /* Is this a VK window? */
+    float ratio;
+
+    if (((window->flags & SDL_WINDOW_FULLSCREEN_DESKTOP) == SDL_WINDOW_FULLSCREEN_DESKTOP) ||
+       ((window->flags & SDL_WINDOW_FULLSCREEN) == SDL_WINDOW_FULLSCREEN)) {
+
+        windata->src_w = dispdata->mode.hdisplay;
+        windata->src_h = dispdata->mode.vdisplay;
+        windata->output_w = dispdata->mode.hdisplay;
+        windata->output_h = dispdata->mode.vdisplay;
+        windata->output_x = 0;
+
+    } else {
+        /* Normal non-fullscreen windows are scaled using the CRTC,
+           so get output (CRTC) size and position, for AR correction. */
+        ratio = (float)window->w / (float)window->h;
+        windata->src_w = window->w;
+        windata->src_h = window->h;
+        windata->output_w = dispdata->mode.vdisplay * ratio;
+        windata->output_h = dispdata->mode.vdisplay;
+        windata->output_x = (dispdata->mode.hdisplay - windata->output_w) / 2;
+    }
+
+    if (!is_vulkan) {
+        if (KMSDRM_CreateSurfaces(_this, window)) {
+            return -1;
+        }
+    }
+    return 0;
+}
+
 int
 KMSDRM_CreateWindowFrom(_THIS, SDL_Window * window, const void *data)
 {
@@ -1772,7 +1212,6 @@ void
 KMSDRM_SetWindowPosition(_THIS, SDL_Window * window)
 {
 }
-
 void
 KMSDRM_SetWindowSize(_THIS, SDL_Window * window)
 {
@@ -1780,7 +1219,6 @@ KMSDRM_SetWindowSize(_THIS, SDL_Window * window)
         SDL_SetError("Can't reconfigure window on SetWindowSize.");
     }
 }
-
 void
 KMSDRM_SetWindowFullscreen(_THIS, SDL_Window * window, SDL_VideoDisplay * display, SDL_bool fullscreen)
 {
@@ -1788,7 +1226,6 @@ KMSDRM_SetWindowFullscreen(_THIS, SDL_Window * window, SDL_VideoDisplay * displa
         SDL_SetError("Can't reconfigure window on SetWindowFullscreen.");
     }
 }
-
 void
 KMSDRM_ShowWindow(_THIS, SDL_Window * window)
 {
@@ -1829,7 +1266,7 @@ KMSDRM_GetWindowWMInfo(_THIS, SDL_Window * window, struct SDL_SysWMinfo *info)
         return SDL_TRUE;
     } else {
         SDL_SetError("application not compiled with SDL %d.%d\n",
-                      SDL_MAJOR_VERSION, SDL_MINOR_VERSION);
+                     SDL_MAJOR_VERSION, SDL_MINOR_VERSION);
         return SDL_FALSE;
     }
 

+ 18 - 85
src/video/kmsdrm/SDL_kmsdrmvideo.h

@@ -1,7 +1,6 @@
 /*
   Simple DirectMedia Layer
   Copyright (C) 1997-2021 Sam Lantinga <slouken@libsdl.org>
-  Atomic KMSDRM backend by Manuel Alfayate Corchete <redwindwanderer@gmail.com>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -31,17 +30,8 @@
 #include <unistd.h>
 #include <xf86drm.h>
 #include <xf86drmMode.h>
-
 #include <gbm.h>
-#include <assert.h>
 #include <EGL/egl.h>
-#include <EGL/eglext.h>
-
-/****************************************************************************************/
-/* Driverdata pointers are void struct* used to store backend-specific variables        */
-/* and info that supports the SDL-side structs like SDL Display Devices, SDL_Windows... */
-/* which need to be "supported" with backend-side info and mechanisms to work.          */ 
-/****************************************************************************************/
 
 typedef struct SDL_VideoData
 {
@@ -51,56 +41,30 @@ typedef struct SDL_VideoData
 
     struct gbm_device *gbm_dev;
 
-    SDL_Window **windows;
-    unsigned int max_windows;
-    unsigned int num_windows;
-
     SDL_bool video_init;        /* Has VideoInit succeeded? */
-
     SDL_bool vulkan_mode;       /* Are we in Vulkan mode? One VK window is enough to be. */
 
+    SDL_Window **windows;
+    int max_windows;
+    int num_windows;
 } SDL_VideoData;
 
-typedef struct plane {
-    drmModePlane *plane;
-    drmModeObjectProperties *props;
-    drmModePropertyRes **props_info;
-} plane;
 
-typedef struct crtc {
-    drmModeCrtc *crtc;
-    drmModeObjectProperties *props;
-    drmModePropertyRes **props_info;
-} crtc;
+typedef struct SDL_DisplayModeData
+{
+    int mode_index;
+} SDL_DisplayModeData;
 
-typedef struct connector {
-    drmModeConnector *connector;
-    drmModeObjectProperties *props;
-    drmModePropertyRes **props_info;
-} connector;
 
-/* More general driverdata info that gives support and substance to the SDL_Display. */
 typedef struct SDL_DisplayData
 {
+    drmModeConnector *connector;
+    drmModeCrtc *crtc;
     drmModeModeInfo mode;
     drmModeModeInfo original_mode;
 
-    plane *display_plane;
-    plane *cursor_plane;
-    crtc *crtc;
-    connector *connector;
-
-    /* Central atomic request list, used for the prop
-       changeset related to pageflip in SwapWindow. */ 
-    drmModeAtomicReq *atomic_req;
-
-    int kms_in_fence_fd;
-    int kms_out_fence_fd;
+    drmModeCrtc *saved_crtc;    /* CRTC to restore on quit */
 
-    EGLSyncKHR kms_fence;
-    EGLSyncKHR gpu_fence;
-
-    SDL_bool modeset_pending;
     SDL_bool gbm_init;
 
     /* DRM & GBM cursor stuff lives here, not in an SDL_Cursor's driverdata struct,
@@ -110,11 +74,12 @@ typedef struct SDL_DisplayData
     struct gbm_bo *cursor_bo;
     uint64_t cursor_w, cursor_h;
 
+    SDL_bool modeset_pending;
+
     SDL_bool set_default_cursor_pending;
 
 } SDL_DisplayData;
 
-/* Driverdata info that gives KMSDRM-side support and substance to the SDL_Window. */
 typedef struct SDL_WindowData
 {
     SDL_VideoData *viddata;
@@ -126,6 +91,10 @@ typedef struct SDL_WindowData
     struct gbm_bo *bo;
     struct gbm_bo *next_bo;
 
+    SDL_bool waiting_for_flip;
+    SDL_bool double_buffer;
+
+    int egl_surface_dirty;
     EGLSurface egl_surface;
 
     /* For scaling and AR correction. */
@@ -135,54 +104,18 @@ typedef struct SDL_WindowData
     int32_t output_h;
     int32_t output_x;
 
-    /* This dictates what approach we'll use for SwapBuffers. */
-    int (*swap_window)(_THIS, SDL_Window * window);
-
 } SDL_WindowData;
 
-typedef struct SDL_DisplayModeData
-{
-    int mode_index;
-} SDL_DisplayModeData;
-
 typedef struct KMSDRM_FBInfo
 {
     int drm_fd;         /* DRM file desc */
     uint32_t fb_id;     /* DRM framebuffer ID */
 } KMSDRM_FBInfo;
 
-typedef struct KMSDRM_PlaneInfo
-{
-    struct plane *plane;
-    uint32_t fb_id;
-    uint32_t crtc_id;
-    int32_t src_x;
-    int32_t src_y;
-    int32_t src_w;
-    int32_t src_h;
-    int32_t crtc_x;
-    int32_t crtc_y;
-    int32_t crtc_w;
-    int32_t crtc_h;
-} KMSDRM_PlaneInfo;
-
 /* Helper functions */
-int KMSDRM_CreateEGLSurface(_THIS, SDL_Window * window);
+int KMSDRM_CreateSurfaces(_THIS, SDL_Window * window);
 KMSDRM_FBInfo *KMSDRM_FBFromBO(_THIS, struct gbm_bo *bo);
-
-/* Atomic functions that are used from SDL_kmsdrmopengles.c and SDL_kmsdrmmouse.c */
-void drm_atomic_set_plane_props(struct KMSDRM_PlaneInfo *info); 
-
-void drm_atomic_waitpending(_THIS);
-int drm_atomic_commit(_THIS, SDL_bool blocking, SDL_bool allow_modeset);
-int add_plane_property(drmModeAtomicReq *req, struct plane *plane,
-                             const char *name, uint64_t value);
-int add_crtc_property(drmModeAtomicReq *req, struct crtc *crtc,
-                             const char *name, uint64_t value);
-int add_connector_property(drmModeAtomicReq *req, struct connector *connector,
-                             const char *name, uint64_t value);
-int setup_plane(_THIS, struct plane **plane, uint32_t plane_type);
-void free_plane(struct plane **plane);
+SDL_bool KMSDRM_WaitPageFlip(_THIS, SDL_WindowData *windata, int timeout);
 
 /****************************************************************************/
 /* SDL_VideoDevice functions declaration                                    */

+ 2 - 2
src/video/kmsdrm/SDL_kmsdrmvulkan.c

@@ -174,7 +174,7 @@ void KMSDRM_Vulkan_GetDrawableSize(_THIS, SDL_Window *window, int *w, int *h)
 /* Instead, programs using SDL and Vulkan create their Vulkan instance */
 /* and we get it here, ready to use.                                   */
 /* Extensions specific for this platform are activated in              */
-/* KMSDRM_Vulkan_GetInstanceExtensions(), like we do with              */
+/* KMSDRM_Vulkan_GetInstanceExtensions(), like we do with       */
 /* VK_KHR_DISPLAY_EXTENSION_NAME, which is what we need for x-less VK. */                
 /***********************************************************************/
 SDL_bool KMSDRM_Vulkan_CreateSurface(_THIS,
@@ -397,7 +397,7 @@ SDL_bool KMSDRM_Vulkan_CreateSurface(_THIS,
                                      surface);
     if(result != VK_SUCCESS)
     {
-        SDL_SetError("vkCreateKMSDRMSurfaceKHR failed: %s",
+        SDL_SetError("vkCreateDisplayPlaneSurfaceKHR failed: %s",
             SDL_Vulkan_GetResultString(result));
         goto clean;
     }

+ 3 - 3
src/video/kmsdrm/SDL_kmsdrmvulkan.h

@@ -26,8 +26,8 @@
 
 #include "../../SDL_internal.h"
 
-#ifndef SDL_kmsdrmvulkan_h_
-#define SDL_kmsdrmvulkan_h_
+#ifndef SDL_kmsdrm_vulkan_h_
+#define SDL_kmsdrm_vulkan_h_
 
 #include "../SDL_vulkan_internal.h"
 #include "../SDL_sysvideo.h"
@@ -48,6 +48,6 @@ SDL_bool KMSDRM_Vulkan_CreateSurface(_THIS,
 
 #endif
 
-#endif /* SDL_kmsdrmvulkan_h_ */
+#endif /* SDL_kmsdrm_vulkan_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */