/* This file is derived from source code for the Nachos
   instructional operating system.  The Nachos copyright notice
   is reproduced in full below. */

/* Copyright (c) 1992-1996 The Regents of the University of California.
   All rights reserved.

   Permission to use, copy, modify, and distribute this software
   and its documentation for any purpose, without fee, and
   without written agreement is hereby granted, provided that the
   above copyright notice and the following two paragraphs appear
   in all copies of this software.

   IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO
   ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR
   CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE
   AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA
   HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

   THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY
   WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS"
   BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
   PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
   MODIFICATIONS.
*/

#include "threads/synch.h"
#include <stdio.h>
#include <string.h>
#include "threads/interrupt.h"
#include "threads/thread.h"

static bool
priority_less (const struct list_elem *a_, const struct list_elem *b_,
               void *aux UNUSED);

/* Initializes semaphore SEMA to VALUE.  A semaphore is a
   nonnegative integer along with two atomic operators for
   manipulating it:

   - down or "P": wait for the value to become positive, then
     decrement it.

   - up or "V": increment the value (and wake up one waiting
     thread, if any). */
void
sema_init (struct semaphore *sema, unsigned value) 
{
  ASSERT (sema != NULL);

  sema->value = value;
  list_init (&sema->waiters);
}

/* Down or "P" operation on a semaphore.  Waits for SEMA's value
   to become positive and then atomically decrements it.

   This function may sleep, so it must not be called within an
   interrupt handler.  This function may be called with
   interrupts disabled, but if it sleeps then the next scheduled
   thread will probably turn interrupts back on. */
void
sema_down (struct semaphore *sema) 
{
  enum intr_level old_level;

  ASSERT (sema != NULL);
  ASSERT (!intr_context ());

  old_level = intr_disable ();
  while (sema->value == 0) 
    {
      list_push_back (&sema->waiters, &thread_current ()->elem);
      thread_block ();
    }
  sema->value--;
  intr_set_level (old_level);
}

/* Down or "P" operation on a semaphore, but only if the
   semaphore is not already 0.  Returns true if the semaphore is
   decremented, false otherwise.

   This function may be called from an interrupt handler. */
bool
sema_try_down (struct semaphore *sema) 
{
  enum intr_level old_level;
  bool success;

  ASSERT (sema != NULL);

  old_level = intr_disable ();
  if (sema->value > 0) 
    {
      sema->value--;
      success = true; 
    }
  else
    success = false;
  intr_set_level (old_level);

  return success;
}

/* Up or "V" operation on a semaphore.  Increments SEMA's value
   and wakes up one thread of those waiting for SEMA, if any.

   This function may be called from an interrupt handler. */
void
sema_up (struct semaphore *sema)
{
  enum intr_level old_level;
  bool thread_unblocked = false; /* Flag to track if any thread was woken up. */

  ASSERT (sema != NULL);

  old_level = intr_disable ();
  if (!list_empty (&sema->waiters))
  {
    /* Enforces wake-up of the highest priority thread waiting for the
       semaphore. */
    struct list_elem *e = list_max (&sema->waiters, priority_less, NULL);
    list_remove (e);
    thread_unblock (list_entry (e, struct thread, elem));
    thread_unblocked = true;
  }
  sema->value++;
  intr_set_level (old_level);

  /* Yields the CPU in case the thread that has been woken up has a higher
     priority that the current running thread, including the case when called
     within an interrupt handler. */
  if (thread_unblocked)
  {
    if (intr_context ())
      intr_yield_on_return ();
    else
      thread_yield ();
  }
}

static void sema_test_helper (void *sema_);

/* Self-test for semaphores that makes control "ping-pong"
   between a pair of threads.  Insert calls to printf() to see
   what's going on. */
void
sema_self_test (void) 
{
  struct semaphore sema[2];
  int i;

  printf ("Testing semaphores...");
  sema_init (&sema[0], 0);
  sema_init (&sema[1], 0);
  thread_create ("sema-test", PRI_DEFAULT, sema_test_helper, &sema);
  for (i = 0; i < 10; i++) 
    {
      sema_up (&sema[0]);
      sema_down (&sema[1]);
    }
  printf ("done.\n");
}

/* Thread function used by sema_self_test(). */
static void
sema_test_helper (void *sema_) 
{
  struct semaphore *sema = sema_;
  int i;

  for (i = 0; i < 10; i++) 
    {
      sema_down (&sema[0]);
      sema_up (&sema[1]);
    }
}

/* Initializes LOCK.  A lock can be held by at most a single
   thread at any given time.  Our locks are not "recursive", that
   is, it is an error for the thread currently holding a lock to
   try to acquire that lock.

   A lock is a specialization of a semaphore with an initial
   value of 1.  The difference between a lock and such a
   semaphore is twofold.  First, a semaphore can have a value
   greater than 1, but a lock can only be owned by a single
   thread at a time.  Second, a semaphore does not have an owner,
   meaning that one thread can "down" the semaphore and then
   another one "up" it, but with a lock the same thread must both
   acquire and release it.  When these restrictions prove
   onerous, it's a good sign that a semaphore should be used,
   instead of a lock. */
void
lock_init (struct lock *lock)
{
  ASSERT (lock != NULL);

  lock->holder = NULL;
  sema_init (&lock->semaphore, 1);
}

/* Current thread donates its priority to donee, iteratively
   propagating the donation in the case of chains in the wait-for graph.
   Also keeps track of the donation by updating the donors list. Expects
   interrupts to be disabled. */
static void
donate_priority (struct thread *donee) {
  ASSERT (intr_get_level () == INTR_OFF);

  struct thread *donor = thread_current ();
  list_push_back (&donee->donors_list, &donor->donor_elem);
  
  while (donee != NULL)
    {
      /* Stop propagation of donation once a donee is reached that has
         a higher effective priority (as its donees can't have less
         priority than that being donated). */
      if (donor->priority <= donee->priority)
          break;

      /* Also stop propagation of donation once a donee is reached with
         no donees of its own (sink node in WFG). */
      if (donee->waiting_lock == NULL)
        {
          /* Only the sink node of the WFG isn't waiting for a lock and
             could be on the ready list. Thus, as its priority changed,
             it must be reinserted into the list. */
          enum intr_level old_level = intr_disable ();
          donee->priority = donor->priority;
          ready_list_reinsert (donee);
          intr_set_level (old_level);
          
          donee = NULL;
        }
      else
        {
          donee->priority = donor->priority;
          donee = donee->waiting_lock->holder;
        }
    }
}

/* Acquires LOCK, sleeping until it becomes available if
   necessary.  The lock must not already be held by the current
   thread.

   This function may sleep, so it must not be called within an
   interrupt handler.  This function may be called with
   interrupts disabled, but interrupts will be turned back on if
   we need to sleep. */
void
lock_acquire (struct lock *lock)
{
  ASSERT (lock != NULL);
  ASSERT (!intr_context ());
  ASSERT (!lock_held_by_current_thread (lock));

  struct thread *t = thread_current ();

  enum intr_level old_level = intr_disable ();
  if (lock->holder != NULL)
    {
      t->waiting_lock = lock;
      donate_priority (lock->holder);
    }
  intr_set_level (old_level);

  sema_down (&lock->semaphore);
  lock->holder = thread_current ();
  t->waiting_lock = NULL;
}

/* Tries to acquires LOCK and returns true if successful or false
   on failure.  The lock must not already be held by the current
   thread.

   This function will not sleep, so it may be called within an
   interrupt handler. */
bool
lock_try_acquire (struct lock *lock)
{
  bool success;

  ASSERT (lock != NULL);
  ASSERT (!lock_held_by_current_thread (lock));

  success = sema_try_down (&lock->semaphore);
  if (success)
    lock->holder = thread_current ();
  return success;
}

/* Releases LOCK, which must be owned by the current thread.

   An interrupt handler cannot acquire a lock, so it does not
   make sense to try to release a lock within an interrupt
   handler. */
void
lock_release (struct lock *lock) 
{
  ASSERT (lock != NULL);
  ASSERT (lock_held_by_current_thread (lock));

  struct thread *current_thread = thread_current ();
  struct thread *max_donor = NULL;

  struct list orphan_list;
  list_init (&orphan_list);

  enum intr_level old_level = intr_disable ();
  /* Loop through current thread's donors, removing the ones waiting for the
     lock being released and keeping track of them (within orphan_list).
     Also identifies the highest priority donor thread among them. */
  struct list_elem *tail = list_tail (&current_thread->donors_list);
  struct list_elem *e = list_begin (&current_thread->donors_list);
  while (e != tail)
    {
      struct thread *donor = list_entry (e, struct thread, donor_elem);
      struct list_elem *next = list_next (e);

      /* Excludes donors that aren't waiting for the lock being released,
         and tracks the rest. */
      if (donor->waiting_lock == lock)
        {
          list_remove (e);
          list_push_back (&orphan_list, e);

          /* Identify highest priority donor. */
          if (max_donor == NULL || donor->priority > max_donor->priority)
            max_donor = donor;
        }

      e = next;
    }

  /* If there exists a maximum donor thread waiting for this lock to be
     released, transfer the remaining orphaned donors to its donor list. */
  if (max_donor != NULL)
    {
      while (!list_empty (&orphan_list))
        list_push_back (&max_donor->donors_list, list_pop_front (&orphan_list));
    }

  intr_set_level (old_level);
  /* Removal of donors to this thread may change its effective priority,
     so recalculate. */
  thread_recalculate_priority ();

  lock->holder = NULL;
  sema_up (&lock->semaphore);
}

/* Returns true if the current thread holds LOCK, false
   otherwise.  (Note that testing whether some other thread holds
   a lock would be racy.) */
bool
lock_held_by_current_thread (const struct lock *lock) 
{
  ASSERT (lock != NULL);

  return lock->holder == thread_current ();
}

/* One semaphore in a list. */
struct semaphore_elem 
  {
    struct list_elem elem;              /* List element. */
    struct semaphore semaphore;         /* This semaphore. */
  };

/* Function that compares the two threads associated with the provided
   pointers to their 'elem' member. Returns true if the thread associated
   with a_ has a lower priority than that of b_. */
static bool
priority_less (const struct list_elem *a_, const struct list_elem *b_,
               void *aux UNUSED)
{
  struct thread *a = list_entry (a_, struct thread, elem);
  struct thread *b = list_entry (b_, struct thread, elem);

  return a->priority < b->priority;
}

/* Function that compares the two *semaphores* associated with the provided
   list_elem structures. [i.e., takes list_elem of semaphore_elem, and]
   Returns true if the thread associated with the semaphore associated with a_
   has a higher priority than that of b_.

    If aux is provided, then it is a pointer to an integer representing the
    priority of the first semaphore. This is useful when the thread has not been
    sema'd down yet. */
static bool
sema_priority_more(const struct list_elem *a, const struct list_elem *b,
                   void *inserting_telem)
{
  struct list_elem *te_a, *te_b;
  
  te_b = list_front (
    &list_entry (b, struct semaphore_elem, elem)->semaphore.waiters);

  if (inserting_telem == NULL)
    {
      te_a = list_front (
        &list_entry (a, struct semaphore_elem, elem)->semaphore.waiters);
    }
  else
    {
      te_a = inserting_telem;
    }

  return priority_more (te_a, te_b, NULL);
}

/* Initializes condition variable COND.  A condition variable
   allows one piece of code to signal a condition and cooperating
   code to receive the signal and act upon it. */
void
cond_init (struct condition *cond)
{
  ASSERT (cond != NULL);

  list_init (&cond->waiters);
}

/* Atomically releases LOCK and waits for COND to be signaled by
   some other piece of code.  After COND is signaled, LOCK is
   reacquired before returning.  LOCK must be held before calling
   this function.

   The monitor implemented by this function is "Mesa" style, not
   "Hoare" style, that is, sending and receiving a signal are not
   an atomic operation.  Thus, typically the caller must recheck
   the condition after the wait completes and, if necessary, wait
   again.

   A given condition variable is associated with only a single
   lock, but one lock may be associated with any number of
   condition variables.  That is, there is a one-to-many mapping
   from locks to condition variables.

   This function may sleep, so it must not be called within an
   interrupt handler.  This function may be called with
   interrupts disabled, but interrupts will be turned back on if
   we need to sleep. */
void
cond_wait (struct condition *cond, struct lock *lock) 
{
  struct semaphore_elem waiter;

  ASSERT (cond != NULL);
  ASSERT (lock != NULL);
  ASSERT (!intr_context ());
  ASSERT (lock_held_by_current_thread (lock));
  
  sema_init (&waiter.semaphore, 0);
  list_push_back (&cond->waiters, &waiter.elem);
  lock_release (lock);
  sema_down (&waiter.semaphore);
  lock_acquire (lock);
}

/* If any threads are waiting on COND (protected by LOCK), then
   this function signals one of them to wake up from its wait.
   LOCK must be held before calling this function.

   An interrupt handler cannot acquire a lock, so it does not
   make sense to try to signal a condition variable within an
   interrupt handler. */
void
cond_signal (struct condition *cond, struct lock *lock UNUSED) 
{
  ASSERT (cond != NULL);
  ASSERT (lock != NULL);
  ASSERT (!intr_context ());
  ASSERT (lock_held_by_current_thread (lock));

  if (!list_empty (&cond->waiters))
    {
      /* Enforce wake-up of highest priority thread within the singleton 
         semaphores waiting for condvar. */
      struct list_elem *e = list_min (&cond->waiters, sema_priority_more, NULL);
      list_remove (e);
      sema_up (&list_entry (e, struct semaphore_elem, elem)->semaphore);
    }
}

/* Wakes up all threads, if any, waiting on COND (protected by
   LOCK).  LOCK must be held before calling this function.

   An interrupt handler cannot acquire a lock, so it does not
   make sense to try to signal a condition variable within an
   interrupt handler. */
void
cond_broadcast (struct condition *cond, struct lock *lock) 
{
  ASSERT (cond != NULL);
  ASSERT (lock != NULL);

  while (!list_empty (&cond->waiters))
    cond_signal (cond, lock);
}
