/*
 * kern/sys_creat.c - create a 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 <config.h>
#include <vfs.h>
#include <sys-vfs.h>
#include <spinlock.h>
#include <process.h>
#include <thread.h>

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

	register error_t     err;
	register uint32_t    flags;
	register thread_t  * this    = durrent_thread;
	register process_t * process = current_process;
	struct vfs_file_s    file;
	struct ku_obj        ku_path;
	uint32_t             fd      = (uint32_t)-1;
   
	if( process_fd_array_full( process ) )
	{
		this->info.errno = ENFILE;
	    CPU_HW_TRACE(sys_creat);
        return fd;
	}

	flags = 0;
	KU_BUFF( ku_path , pathname );

    // get the cwd lock
	rwlock_rdlock( &process->cwd_lock );

	err = vfs_create( &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_creat);
	    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_creat);
	return fd;
}
