/*
 * kern/sys_open.c - open a named file
 * 
 * Copyright (c) 2008,2009,2010,2011,2012 Ghassan Almaless
 * Copyright (c) 2011,2012 UPMC Sorbonne Universites
 *
 * This file is part of ALMOS-kernel.
 *
 * ALMOS-kernel is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2.0 of the License.
 *
 * ALMOS-kernel is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with ALMOS-kernel; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include <errno.h>
#include <thread.h>
#include <vfs.h>
#include <sys-vfs.h>
#include <process.h>
#include <spinlock.h>
#include <cpu-trace.h>

///////////////////////////////////
int sys_open ( char     * pathname,
               uint32_t   flags,
               uint32_t   mode )
{
	CPU_HW_TRACE(sys_open);

	error_t            err;
	struct vfs_file_s  file;   
	struct ku_obj      ku_path;
	thread_t         * this     = current_thread;
	process_t        * process  = current_process;
	uint32_t           fd       = (uint32_t)-1;

	cpu_trace_write(current_cpu, sys_open);

	if( process_fd_aray_full( process ) )
	{
		this->info.errno = ENFILE;
        CPU_HW_TRACE(sys_open);
        return fd;
	}
   
	if( VFS_IS( flags , VFS_O_DIRECTORY ) ) VFS_SET( flags , VFS_DIR );

	KU_BUFF( ku_path , pathname );

    // get the cwd lock
	rwlock_rdlock( &process->cwd_lock );
   
	err = vfs_open( &process->vfs_cwd , &ku_path , flags , mode , &file );
	if( err )
	{
		this->info.errno = (err < 0 ) ? -err : err;
	    rwlock_unlock( &process->cwd_lock );
	    CPU_HW_TRACE(sys_open);
	    return fd;
	}
	
	err = process_fd_set( process , &file , &fd );
	if( err )
	{
		vfs_close(&file, NULL);
		this->info.errno = err;
	}

	rwlock_unlock( &process->cwd_lock );
	CPU_HW_TRACE(sys_open);
	return fd;
}
