# Loading corresponding pages of datastructures



## pauldaviesc (Jan 14, 2014)

Hi,

I am learning the internals of the FreeBSD kernel. I wrote a simple kernel module which is supposed to list all the process IDs, while loading the module, by traversing the process list. Below is the relevant part of the code:


```
case MOD_LOAD:
    curr = curproc->p_list.le_next;
    while(curr->p_pid != curproc->p_pid) {
        uprintf("%d\n",curr->p_pid);
        curr = curr->p_list.le_next;
   }
```

Note: curr is defined as struct proc.

Now when I load this kernel module using `kldload`, I get a page fault error after some PIDs are listed and the system reboots. My understanding of this issue is that some processes are not in memory and when I tries to access it, I get the page fault. So my question is how can I ensure that relevant data structure is loaded to the memory before accessing it in the FreeBSD kernel?


----------



## sossego (Jan 15, 2014)

May we see all of the code?  You are trying Linux kernel hacking on a completely different system, yes?

Is this related to one of your math problems and trying to solve it?


----------



## worldi (Jan 15, 2014)

There is a FOREACH_PROC_IN_SYSTEM() macro in sys/proc.h. Then there is this _allproc_lock_ that's acquired every time _allproc_ is used (e.g. here). They probably do this for a reason. 

Here's a snippet of a module that does what you ask for (at least on a virtual-boxed 10-RC1):

```
...
#include <sys/kernel.h>
#include <sys/lock.h>
#include <sys/sx.h>
#include <sys/proc.h>

static int
proctest_loader(struct module *m, int what, void *arg)
{
  int err = 0;
  struct proc *p;

  switch (what) {
  case MOD_LOAD:
    sx_slock(&allproc_lock);
    FOREACH_PROC_IN_SYSTEM(p) {
      uprintf("%d\n", p->p_pid);
    }
    sx_sunlock(&allproc_lock);

    uprintf("Proctest KLD loaded.\n");
    break;
  case MOD_UNLOAD:
...
```


----------

