#include <libk/list.h>
#include <libk/std.h>
#include <mm/liballoc.h>
#include <proc/proc.h>
#include <proc/reschedule.h>
#include <proc/resource.h>
#include <proc/suspension_q.h>
#include <sync/spin_lock.h>
#include <sys/smp.h>
#include <sys/spin_lock.h>

void proc_sq_suspend (struct proc* proc, struct proc_suspension_q* sq, spin_lock_t* resource_lock,
                      struct reschedule_ctx* rctx) {
  struct cpu* cpu = proc->cpu;

  struct proc_sq_entry* sq_entry = malloc (sizeof (*sq_entry));
  if (!sq_entry) {
    if (resource_lock != NULL)
      spin_unlock (resource_lock);
    return;
  }

  sq_entry->proc = proc;
  sq_entry->sq = sq;

  spin_lock (&cpu->lock);
  spin_lock (&proc->lock);
  spin_lock (&sq->lock);

  if (resource_lock != NULL)
    spin_unlock (resource_lock);

  proc->state = PROC_SUSPENDED;

  /* append to sq's list */
  list_append (sq->proc_list, &sq_entry->sq_link);

  /* append to proc's list */
  list_append (proc->sq_entries, &sq_entry->proc_link);

  list_remove (cpu->proc_run_q, &proc->cpu_run_q_link);
  cpu->proc_run_q_count--;

  if (cpu->proc_current == proc)
    cpu->proc_current = NULL;

  proc->cpu = NULL;

  spin_unlock (&sq->lock);
  spin_unlock (&proc->lock);
  spin_unlock (&cpu->lock);

  rctx_insert_cpu (rctx, cpu);
}

void proc_sq_resume (struct proc* proc, struct proc_sq_entry* sq_entry,
                     struct reschedule_ctx* rctx) {
  struct cpu* cpu = cpu_find_lightest ();
  struct proc_suspension_q* sq = sq_entry->sq;

  spin_lock (&cpu->lock);
  spin_lock (&proc->lock);
  spin_lock (&sq->lock);

  /* remove from sq's list */
  list_remove (sq->proc_list, &sq_entry->sq_link);

  /* remove from proc's list */
  list_remove (proc->sq_entries, &sq_entry->proc_link);

  proc->cpu = cpu;

  if (proc->sq_entries == NULL)
    proc->state = PROC_READY;

  list_append (cpu->proc_run_q, &proc->cpu_run_q_link);
  cpu->proc_run_q_count++;

  spin_unlock (&sq->lock);
  spin_unlock (&proc->lock);
  spin_unlock (&cpu->lock);

  free (sq_entry);

  rctx_insert_cpu (rctx, cpu);
}

void proc_sqs_cleanup (struct proc* proc) {
  spin_lock (&proc->lock);

  /* clean suspension queue entries */
  struct list_node_link *sq_link, *sq_link_tmp;
  list_foreach (proc->sq_entries, sq_link, sq_link_tmp) {
    struct proc_sq_entry* sq_entry = list_entry (sq_link, struct proc_sq_entry, proc_link);
    struct proc_suspension_q* sq = sq_entry->sq;

    spin_lock (&sq->lock);

    /* remove from sq's list */
    list_remove (sq->proc_list, &sq_entry->sq_link);

    /* remove from proc's list */
    list_remove (proc->sq_entries, &sq_entry->proc_link);

    spin_unlock (&sq->lock);

    free (sq_entry);
  }

  spin_unlock (&proc->lock);
}
