/* 
 * Copyright 2010 Stefan Lankes, Chair for Operating Systems,
 *                               RWTH Aachen University
 *
 * 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.
 *
 * This file is part of MetalSVM.
 */

/**
 * @author Stefan Lankes
 * @file arch/x86/include/asm/syscall.h
 * @brief Systemcall related code
 *
 * This file defines the syscall function and convenience 
 * based macro definitions for calling it.
 */

#ifndef __ARCH_SYSCALL_H__
#define __ARCH_SYSCALL_H__

#include <metalsvm/stddef.h>

#ifdef __cplusplus
extern "C" {
#endif

#define _STR(token)		#token
#define _SYSCALLSTR(x)		"int $" _STR(x) " "

/** @brief the syscall function which issues an interrupt to the kernel
 *
 * It's supposed to be used by the macros defined in this file as the could would read
 * cleaner then.
 *
 * @param nr System call number
 * @param arg0 Argument 0
 * @param arg1 Argument 1
 * @param arg2 Argument 2
 * @param arg3 Argument 3
 * @param arg4 Argument 4
 * @return The return value of the system call
 */
inline static long
syscall(int nr, unsigned long arg0, unsigned long arg1, unsigned long arg2,
	unsigned long arg3, unsigned long arg4)
{
        long res;

	asm volatile (_SYSCALLSTR(INT_SYSCALL)
             : "=a" (res)
             : "0" (nr), "b" (arg0), "c" (arg1), "d" (arg2), "S" (arg3), "D" (arg4)
             : "memory", "cc");

        return res;
}


/// System call macro with one single argument; the syscall number
#define SYSCALL0(NR) \
	syscall(NR, 0, 0, 0, 0, 0)
/// System call macro with system call number and one argument
#define SYSCALL1(NR, ARG1) \
	syscall(NR, (unsigned long)ARG1, 0, 0, 0, 0)
/// System call macro with system call number and 2 arguments
#define SYSCALL2(NR, ARG1, ARG2) \
	syscall(NR, (unsigned long)ARG1, (unsigned long)ARG2, 0, 0, 0)
/// System call macro with system call number and 3 arguments
#define SYSCALL3(NR, ARG1, ARG2, ARG3) \
	syscall(NR, (unsigned long)ARG1, (unsigned long)ARG2, (unsigned long)ARG3, 0, 0)
/// System call macro with system call number and 4 arguments
#define SYSCALL4(NR, ARG1, ARG2, ARG3, ARG4) \
	syscall(NR, (unsigned long)ARG1, (unsigned long)ARG2, (unsigned long)ARG3, (unsigned long) ARG4, 0)
/// System call macro with system call number and 5 arguments
#define SYSCALL5(NR, ARG1, ARG2, ARG3, ARG4) \
        syscall(NR, (unsigned long)ARG1, (unsigned long)ARG2, (unsigned long)ARG3, (unsigned long) ARG4, (unsigned long) ARG5)
#ifdef __cplusplus
}
#endif

#endif