#ifndef _KERNEL_PROC_PROCGROUP_H
#define _KERNEL_PROC_PROCGROUP_H

#include <id/id_alloc.h>
#include <libk/list.h>
#include <libk/rbtree.h>
#include <libk/std.h>
#include <proc/resource.h>
#include <sync/spin_lock.h>
#include <sys/mm.h>
#include <sys/procgroup.h>

#define PROCGROUP_VFS_HANDLES_MAX 256
#define PROCGROUP_RESOURCES_MAX   256

struct proc;
struct reschedule_ctx;

struct proc_mapping {
  struct list_node_link proc_mappings_link;

  uintptr_t paddr;
  uintptr_t vaddr;
  size_t size;
};

struct procgroup {
  int pgid;
  struct rb_node_link procgroup_tree_link;
  struct rb_node_link* memb_proc_tree;
  spin_lock_t lock;
  struct rb_node_link* resource_tree;
  struct id_alloc rid_alloc;
  struct pd pd;
  struct list_node_link* mappings;
  uintptr_t map_base;
  struct procgroup_tls tls;
  uint64_t capabilities;
};

struct procgroup* procgroup_create (void);

void procgroup_attach (struct procgroup* procgroup, struct proc* proc);

void procgroup_detach (struct procgroup* procgroup, struct proc* proc, struct reschedule_ctx* rctx);

uintptr_t procgroup_map (struct procgroup* procgroup, uintptr_t vaddr, size_t pages, uint32_t flags,
                         uintptr_t* out_paddr);

bool procgroup_unmap (struct procgroup* procgroup, uintptr_t start_vaddr, size_t pages);

struct procgroup* procgroup_find (int pgid);

void procgroup_pgid_alloc_init (void);

#endif // _KERNEL_PROC_PROCGROUP_H
