/* SPDX-License-Identifier: MIT */
// autogenerated by syzkaller (https://github.com/google/syzkaller)

#include <endian.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>

#include "helpers.h"

#ifndef __NR_io_uring_register
#define __NR_io_uring_register 427
#endif
#ifndef __NR_io_uring_setup
#define __NR_io_uring_setup 425
#endif

#define SIZEOF_IO_URING_SQE 64
#define SIZEOF_IO_URING_CQE 16
#define SQ_HEAD_OFFSET 0
#define SQ_TAIL_OFFSET 64
#define SQ_RING_MASK_OFFSET 256
#define SQ_RING_ENTRIES_OFFSET 264
#define SQ_FLAGS_OFFSET 276
#define SQ_DROPPED_OFFSET 272
#define CQ_HEAD_OFFSET 128
#define CQ_TAIL_OFFSET 192
#define CQ_RING_MASK_OFFSET 260
#define CQ_RING_ENTRIES_OFFSET 268
#define CQ_RING_OVERFLOW_OFFSET 284
#define CQ_FLAGS_OFFSET 280
#define CQ_CQES_OFFSET 320

static long syz_io_uring_setup(volatile long a0, volatile long a1, volatile long a2, volatile long a3, volatile long a4, volatile long a5)
{
	uint32_t entries = (uint32_t)a0;
	struct io_uring_params* setup_params = (struct io_uring_params*)a1;
	void* vma1 = (void*)a2;
	void* vma2 = (void*)a3;
	void** ring_ptr_out = (void**)a4;
	void** sqes_ptr_out = (void**)a5;
	uint32_t fd_io_uring = syscall(__NR_io_uring_setup, entries, setup_params);
	uint32_t sq_ring_sz = setup_params->sq_off.array + setup_params->sq_entries * sizeof(uint32_t);
	uint32_t cq_ring_sz = setup_params->cq_off.cqes + setup_params->cq_entries * SIZEOF_IO_URING_CQE;
	uint32_t ring_sz = sq_ring_sz > cq_ring_sz ? sq_ring_sz : cq_ring_sz;
	*ring_ptr_out = mmap(vma1, ring_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE | MAP_FIXED, fd_io_uring, IORING_OFF_SQ_RING);
	uint32_t sqes_sz = setup_params->sq_entries * SIZEOF_IO_URING_SQE;
	*sqes_ptr_out = mmap(vma2, sqes_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE | MAP_FIXED, fd_io_uring, IORING_OFF_SQES);
	return fd_io_uring;
}

static uint64_t r[1] = {0xffffffffffffffff};

int main(int argc, char *argv[])
{
	intptr_t res = 0;

	if (argc > 1)
		return T_EXIT_SKIP;

	mmap((void *) 0x1ffff000ul, 0x1000ul, PROT_NONE,
		MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0ul);
	mmap((void *) 0x20000000ul, 0x1000000ul, PROT_READ|PROT_WRITE|PROT_EXEC,
		MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0ul);
	mmap((void *) 0x21000000ul, 0x1000ul, PROT_NONE,
		MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0ul);

	*(uint32_t*)0x20000684 = 0;
	*(uint32_t*)0x20000688 = 0;
	*(uint32_t*)0x2000068c = 0;
	*(uint32_t*)0x20000690 = 0;
	*(uint32_t*)0x20000698 = -1;
	memset((void*)0x2000069c, 0, 12);

	res = syz_io_uring_setup(0x2fd6, 0x20000680, 0x20ffd000, 0x20ffc000,
					0x20000700, 0x20000740);
	if (res != -1)
		r[0] = res;

	*(uint64_t*)0x20002840 = 0;
	*(uint64_t*)0x20002848 = 0;
	*(uint64_t*)0x20002850 = 0x20000840;
	*(uint64_t*)0x20002858 = 0x1000;
	syscall(__NR_io_uring_register, r[0], 0ul, 0x20002840ul, 2ul);
	return T_EXIT_PASS;
}
