#ifndef _KERNEL_PROC_PROC_H
#define _KERNEL_PROC_PROC_H

#include <aux/compiler.h>
#include <aux/elf.h>
#include <libk/list.h>
#include <libk/rbtree.h>
#include <libk/std.h>
#include <path_defs.h>
#include <proc/procgroup.h>
#include <proc/resource.h>
#include <proc/suspension_q.h>
#include <sync/spin_lock.h>
#include <sys/mm.h>

#if defined(__x86_64__)
#include <amd64/gdt.h>  /* KSTACK_SIZE */
#include <amd64/proc.h> /* USTACK_SIZE */
#endif

/* process states */
#define PROC_READY     0
#define PROC_DEAD      1
#define PROC_SUSPENDED 2

/* process flags */
#define PROC_USTK_PREALLOC (1 << 0)

struct cpu;
struct reschedule_ctx;

struct proc {
  int pid;
  int exec_pid;
  struct rb_node_link proc_tree_link;
  struct rb_node_link procgroup_memb_tree_link;
  struct list_node_link cpu_run_q_link;
  struct list_node_link* sq_entries;
  struct procgroup* procgroup;
  struct proc_platformdata pdata;
  uint32_t flags;
  spin_lock_t lock;
  struct cpu* cpu;
  int state;
  uintptr_t uvaddr_argument;
  void* mail_recv_buffer;
  size_t mail_recv_size;
  char cwv[VOLUME_MAX];
  struct proc_suspension_q done_sq;
};

void proc_sched (void);

void proc_kill (struct proc* proc, struct reschedule_ctx* rctx);

struct elf_aux proc_load_segments (struct proc* proc, uint8_t* elf);

void proc_register (struct proc* proc, struct cpu* register_cpu, struct reschedule_ctx* rctx);

struct proc* proc_find_pid (int pid);

struct proc* proc_from_file (struct proc* proc1, const char* volume, const char* path,
                             struct reschedule_ctx* rctx);

void proc_free_pid (int pid);

int proc_alloc_pid (void);

void proc_pid_alloc_init (void);

void proc_wait_for (struct proc* proc, struct reschedule_ctx* rctx, struct proc* wait_proc);

void proc_init (void);

#endif // _KERNEL_PROC_PROC_H
