Bool 
isDRI2Connected(VADriverContextP ctx, char **driver_name)
{
    struct dri_state *dri_state = (struct dri_state *)ctx->drm_state;
    int major, minor;
    int error_base;
    int event_base;
    char *device_name = NULL;
    drm_magic_t magic;        
    *driver_name = NULL;
    dri_state->base.fd = -1;
    dri_state->base.auth_type = VA_NONE;
    if (!VA_DRI2QueryExtension(ctx->native_dpy, &event_base, &error_base))
        goto err_out;

    if (!VA_DRI2QueryVersion(ctx->native_dpy, &major, &minor))
        goto err_out;


    if (!VA_DRI2Connect(ctx->native_dpy, RootWindow(ctx->native_dpy, ctx->x11_screen),
                     driver_name, &device_name) || !device_name)
        goto err_out;

    dri_state->base.fd = open(device_name, O_RDWR);
    assert(dri_state->base.fd >= 0);

    if (dri_state->base.fd < 0)
        goto err_out;

    if (drmGetMagic(dri_state->base.fd, &magic))
        goto err_out;

    if (!VA_DRI2Authenticate(ctx->native_dpy, RootWindow(ctx->native_dpy, ctx->x11_screen),
                          magic))
        goto err_out;

    dri_state->base.auth_type = VA_DRI2;
    dri_state->createDrawable = dri2CreateDrawable;
    dri_state->destroyDrawable = dri2DestroyDrawable;
    dri_state->swapBuffer = dri2SwapBuffer;
    dri_state->getRenderingBuffer = dri2GetRenderingBuffer;
    dri_state->close = dri2Close;
    gsDRI2SwapAvailable = (minor >= 2);

    Xfree(device_name);

    return True;

err_out:
    if (device_name)
        Xfree(device_name);

    if (*driver_name)
        Xfree(*driver_name);

    if (dri_state->base.fd >= 0)
        close(dri_state->base.fd);

    *driver_name = NULL;
    dri_state->base.fd = -1;
    
    return False;
}
LOCAL dri_state_t*
getDRI2State(Display* dpy, int screen, char **driver_name)
{
  int major, minor;
  int error_base;
  int event_base;
  char *device_name = NULL;
  drm_magic_t magic;
  char * internal_driver_name = NULL;
  int fd = -1;
  dri_state_t* state = NULL;

  if (!VA_DRI2QueryExtension(dpy, &event_base, &error_base))
    goto err_out;

  if (!VA_DRI2QueryVersion(dpy, &major, &minor))
    goto err_out;


  if (!VA_DRI2Connect(dpy, RootWindow(dpy, screen),
        &internal_driver_name, &device_name))
    goto err_out;

  fd = open(device_name, O_RDWR);

  if (fd < 0)
    goto err_out;

  if (drmGetMagic(fd, &magic))
    goto err_out;

  if (!VA_DRI2Authenticate(dpy, RootWindow(dpy, screen),
        magic))
    goto err_out;

  if(driver_name)
    *driver_name = internal_driver_name;
  else
    Xfree(internal_driver_name);

  state = dri_state_new();
  state->fd = fd;
  state->x11_dpy = dpy;
  state->x11_screen = screen;
  state->driConnectedFlag = DRI2;
  if (device_name)
    Xfree(device_name);
  return state;

err_out:
  if (device_name)
    Xfree(device_name);

  if (internal_driver_name)
    Xfree(internal_driver_name);

  if(driver_name) *driver_name = NULL;

  if (fd >= 0)
    close(fd);

  if (driver_name)
    *driver_name = NULL;

  return state;
}