educative.io

Silly C questions regarding xv6 proc.h

My background: I’m a Go dev and am now learning Rust, so I checked out this course on OS.

I see that struct proc represents a process in xv6, but why does proc has field kstack as char*? Isn’t char in C a byte (uint8)? They why reference to a byte is the bottom of kernel stack.

struct proc {
  char *mem;                  // Start of process memory
  uint sz;                    // Size of process memory
  char *kstack;               // Bottom of kernel stack
                              // for this process
  enum proc_state state;      // Process state
  int pid;                    // Process ID
  struct proc *parent;        // Parent process
  void *chan;                 // If !zero, sleeping on chan
  int killed;                 // If !zero, has been killed
  struct file *ofile[NOFILE]; // Open files
  struct inode *cwd;          // Current directory
  struct context context;     // Switch here to run process
  struct trapframe *tf;       // Trap frame for the current interrupt
};

Check this blog created based off the OS course from UC Irvine : First Process from XV6. Before start | by Brian Pan | Medium

My understanding of the reason to keep the kstack pointer as a pointer to a byte sized variable is that it enables to keep track of the stack size. See the below from the blog above that adjusts the stack pointer using kstack.

static struct proc*
allocproc(void)
{
  .....
  // stack ptr
  sp = p->kstack+KSTACKSIZE;
  // Leave room for trap frame
  sp -= sizeof *p->tf;
  p->tf = (struct trapframe*)sp;
  ...
}

Another reason for having a pointer to a byte sized variable is that it may allow storage of misaligned data such as datatypes that do not sit at a word boundary such as 32 bit(4 byte) for 4 byte access, 64(8 byte access) for 8 byte access etc.

1 Like