/*
 * scheduler.c - Core scheduler implementation.
 * 
 * Author    Alain Greiner (2016)
 *
 * Copyright (c)  UPMC Sorbonne Universites
 *
 * This file is part of ALMOS-MKH.
 *
 * ALMOS-MKH. 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-MKH. 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-MKH.; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include <kernel_config.h>
#include <hal_types.h>
#include <hal_switch.h>
#include <hal_irqmask.h>
#include <hal_context.h>
#include <printk.h>
#include <list.h>
#include <core.h>
#include <thread.h>
#include <chdev.h>
#include <scheduler.h>

///////////////////////////////////////////////////////////////////////////////////////////
// Extern global variables
///////////////////////////////////////////////////////////////////////////////////////////

extern chdev_directory_t    chdev_dir;            // allocated in kernel_init.c file
extern uint32_t             switch_save_sr[];     // allocated in kernel_init.c file

////////////////////////////////
void sched_init( core_t * core )
{
    scheduler_t * sched = &core->scheduler;

    sched->u_threads_nr   = 0;
    sched->k_threads_nr   = 0;

    sched->current        = CURRENT_THREAD;
    sched->idle           = NULL;             // initialized in kernel_init()
    sched->u_last         = NULL;             // initialized in sched_register_thread()
    sched->k_last         = NULL;             // initialized in sched_register_thread()

    // initialise threads lists
    list_root_init( &sched->u_root );
    list_root_init( &sched->k_root );

    sched->sig_pending    = false;            // no pending signal

}  // end sched_init()

////////////////////////////////////////////
void sched_register_thread( core_t   * core,
                            thread_t * thread )
{
    scheduler_t * sched = &core->scheduler;
    thread_type_t type  = thread->type;

    // take lock protecting sheduler lists
    spinlock_lock( &sched->lock );

    if( type == THREAD_USER )
    {
        list_add_last( &sched->u_root , &thread->sched_list );
        sched->u_threads_nr++;
        if( sched->u_last == NULL ) sched->u_last = &thread->sched_list;
    }
    else // kernel thread
    {
        list_add_last( &sched->k_root , &thread->sched_list );
        sched->k_threads_nr++;
        if( sched->k_last == NULL ) sched->k_last = &thread->sched_list; 
    }

    // release lock 
    spinlock_unlock( &sched->lock );

}  // end sched_register_thread()

/////////////////////////////////////////////
void sched_remove_thread( thread_t * thread )
{
    scheduler_t * sched = &thread->core->scheduler;
    thread_type_t type  = thread->type;

    // take lock protecting sheduler lists
    spinlock_lock( &sched->lock );

    if( type == THREAD_USER )
    {
        list_unlink( &thread->sched_list );
        sched->u_threads_nr--;
        if( sched->u_threads_nr == 0 ) sched->u_last = NULL;
    }
    else // kernel thread
    {
        list_unlink( &thread->sched_list );
        sched->k_threads_nr--;
        if( sched->k_threads_nr == 0 ) sched->k_last = NULL;
    }

    // release lock 
    spinlock_unlock( &sched->lock );

}  // end sched_remove_thread()

//////////////////////////////////////////////
thread_t * sched_select( scheduler_t * sched )
{
    thread_t     * thread;
    list_entry_t * current;
    list_entry_t * last;

    // take lock protecting sheduler lists
    spinlock_lock( &sched->lock );

    // first loop : scan the kernel threads list if not empty 
    if( list_is_empty( &sched->k_root ) == false )
    {
        last    = sched->k_last;
        current = sched->k_last;
        do
        {
            // get next entry in kernel list
            current = list_next( &sched->k_root , current );

            // skip the root that does not contain a thread
            if( current == NULL ) current = sched->k_root.next;

            // get thread pointer for this entry
            thread = LIST_ELEMENT( current , thread_t , sched_list );

            // analyse kernel thread type
            switch( thread->type )
            {
                case THREAD_IDLE: // skip IDLE thread
                break;

                case THREAD_RPC:  // RPC thread if non blocked and FIFO non-empty
                if( (thread->blocked == 0) && 
                    (local_fifo_is_empty( &LOCAL_CLUSTER->rpc_fifo ) == 0) )
                {
                    spinlock_unlock( &sched->lock );
                    return thread;
                }
                break;

                default:          // DEV thread if non blocked and waiting queue non empty
                if( (thread->blocked == 0) &&
                    (xlist_is_empty( XPTR( local_cxy , &thread->chdev->wait_root)) == 0) ) 
                {
                    spinlock_unlock( &sched->lock );
                    return thread;
                }
                break;
            }  // end switch type
        }
        while( current != last );
    }

    // second loop : scan the user threads list if not empty 
    if( list_is_empty( &sched->u_root ) == false )
    {
        last    = sched->u_last;
        current = sched->u_last;
        do
        {
            // get next entry in user list
            current = list_next( &sched->u_root , current );

            // skip the root that does not contain a thread
            if( current == NULL ) current = sched->u_root.next;

            // get thread pointer for this entry
            thread = LIST_ELEMENT( current , thread_t , sched_list );

            // return thread if runnable
            if( thread->blocked == 0 )
            {
                spinlock_unlock( &sched->lock );
                return thread;
            }
        }
        while( current != last );
    }

    // third : return idle thread if no runnable thread
    spinlock_unlock( &sched->lock );
    return sched->idle;

}  // end sched_select()

//////////////////////////////////////////
void sched_handle_signals( core_t * core )
{
    list_entry_t * iter;
    thread_t     * thread;

    scheduler_t  * sched = &core->scheduler;

    // take lock protecting threads lists
    spinlock_lock( &sched->lock );

    // handle user threads
    LIST_FOREACH( &sched->u_root , iter )
    {
        thread = LIST_ELEMENT( iter , thread_t , sched_list );

        if( thread->flags & THREAD_FLAG_SIGNAL )  // thread has signal
        {
            // decrement response counter to acknowledge signal
            hal_atomic_add( thread->sig_rsp_count , -1 );

            // reset signal
            thread_reset_signal( thread );
        }
    }

    // release lock 
    spinlock_unlock( &sched->lock );

} // end sched_handle_signals()

////////////////////////////////
void sched_yield( char * cause )
{
    thread_t    * next;
    thread_t    * current = CURRENT_THREAD;
    core_t      * core    = current->core;
    scheduler_t * sched   = &core->scheduler;
 
#if( CONFIG_SCHED_DEBUG & 0x1 )
if( hal_time_stamp() > CONFIG_SCHED_DEBUG ) sched_display( core->lid );
#endif

    // delay the yield if current thread has locks
    if( (current->local_locks != 0) || (current->remote_locks != 0) )
    {
        current->flags |= THREAD_FLAG_SCHED;
        return;
    }

    // enter critical section / save SR in current thread context
    hal_disable_irq( &current->save_sr );

    // loop on threads to select next thread 
    next = sched_select( sched );

    // check next thread attached to same core as the calling thread
    assert( (next->core == current->core), __FUNCTION__ , 
    "next core != current core\n");

    // check next thread not blocked when type != IDLE
    assert( (next->blocked == 0) || (next->type = THREAD_IDLE) , __FUNCTION__ ,
    "next thread %x (%s) is blocked on core[%x,%d]\n", 
    next->trdid , thread_type_str(next->type) , local_cxy , core->lid );

    // switch contexts and update scheduler state if next != current
	if( next != current )
    {

sched_dmsg("\n[DBG] %s : core[%x,%d] / cause = %s\n"
"      thread %x (%s) (%x,%x) => thread %x (%s) (%x,%x) / cycle %d\n",
__FUNCTION__, local_cxy, core->lid, cause, 
current, thread_type_str(current->type), current->process->pid, current->trdid,
next   , thread_type_str(next->type)   , next->process->pid   , next->trdid,
(uint32_t)hal_get_cycles() );

        // update scheduler 
        sched->current = next;
        if( next->type == THREAD_USER ) sched->u_last = &next->sched_list;
        else                            sched->k_last = &next->sched_list;

        // handle FPU ownership
	    if( next->type == THREAD_USER )
        {
	        if( next == current->core->fpu_owner )  hal_fpu_enable();
	        else                                    hal_fpu_disable();
        }

        // switch CPU from calling thread context to new thread context
        hal_do_cpu_switch( current->cpu_context, next->cpu_context );
    }
    else
    {

sched_dmsg("\n[DBG] %s : core[%x,%d] / cause = %s\n" 
"      thread %x (%s) (%x,%x) continue / cycle %d\n",
__FUNCTION__, local_cxy, core->lid, cause,
current, thread_type_str(current->type), current->process->pid, current->trdid, 
(uint32_t)hal_get_cycles() );

    }

    // handle signals for all threads executing on this core.
    sched_handle_signals( core );

    // exit critical section / restore SR from next thread context
    hal_restore_irq( next->save_sr );

}  // end sched_yield()


///////////////////////////////
void sched_display( lid_t lid )
{
    list_entry_t * iter;
    thread_t     * thread;
    uint32_t       save_sr;

    if( lid >= LOCAL_CLUSTER->cores_nr )
    {
        printk("\n[ERROR] in %s : illegal local index %d in cluster %x\n",
        __FUNCTION__ , lid , local_cxy );
        return;
    }

    core_t       * core    = &LOCAL_CLUSTER->core_tbl[lid];
    scheduler_t  * sched   = &core->scheduler;
    
    // get pointers on TXT0 chdev
    xptr_t    txt0_xp  = chdev_dir.txt_tx[0];
    cxy_t     txt0_cxy = GET_CXY( txt0_xp );
    chdev_t * txt0_ptr = GET_PTR( txt0_xp );

    // get extended pointer on remote TXT0 chdev lock
    xptr_t  lock_xp = XPTR( txt0_cxy , &txt0_ptr->wait_lock );

    // get TXT0 lock in busy waiting mode
    remote_spinlock_lock_busy( lock_xp , &save_sr );

    nolock_printk("\n***** scheduler state for core[%x,%d] at cycle %d\n"
           "kernel_threads = %d / user_threads = %d / current = (%x,%x)\n",
            local_cxy , core->lid, hal_time_stamp(),
            sched->k_threads_nr, sched->u_threads_nr,
            sched->current->process->pid , sched->current->trdid );

    // display kernel threads
    LIST_FOREACH( &sched->k_root , iter )
    {
        thread = LIST_ELEMENT( iter , thread_t , sched_list );
        if (thread->type == THREAD_DEV) 
        {
            nolock_printk(" - %s / pid %X / trdid %X / desc %X / blocked %X / %s\n",
            thread_type_str( thread->type ), thread->process->pid, thread->trdid,
            thread, thread->blocked , thread->chdev->name );
        }
        else
        {
            nolock_printk(" - %s / pid %X / trdid %X / desc %X / blocked %X\n",
            thread_type_str( thread->type ), thread->process->pid, thread->trdid,
            thread, thread->blocked );
        }
    }

    // display user threads
    LIST_FOREACH( &sched->u_root , iter )
    {
        thread = LIST_ELEMENT( iter , thread_t , sched_list );
        nolock_printk(" - %s / pid %X / trdid %X / desc %X / blocked %X\n",
        thread_type_str( thread->type ), thread->process->pid, thread->trdid,
        thread, thread->blocked );
    }

    // release TXT0 lock
    remote_spinlock_unlock_busy( lock_xp , save_sr );

}  // end sched_display()

