mmapmump 使得程序能够更细致的控制其地址空间,例如用来在进程中共享内存,将文件映射到进程空间。

1
2
void *mmap(void *addr, size_t length, int prot, int flags,
           int fd, off_t offset);

mmap 可以用在很多方面,但是这个实验只关注 mmap 映射文件到进程地址空间这个用法。这个实验假设 mmap 的第一个参数 addr 是 0,意味着内核需要决定从哪个虚拟地址开始映射文件,mmap 返回这个地址 或 0xffffffffffffffff 表示失败。length 表示映射的空间大小是多少字节,可以不和要映射的文件大小一样。prot 表示映射的内存是可读,可写,可执行等权限。flags 要么是 MAP_SHARED,要么是 MAP_PRIVATE,前者表示对映射内存的更改要同步写到文件,而后者则不需要。fd 是要映射文件的文件描述符。offset 可以假设为 0,它表示映射文件中的起始点。

1
munmap(addr, length);

munmap 解除指定地址空间的映射,如果解除的空间是 MAP_SHARED 空间,需要先写回文件,再解除映射。munmap 有可能只是解除一部分映射,但是要么是解除前一部分,或后一部分,不会从中间解除。

实现:

  • 整体上和 lazy page allocation 那个实验相似,都是先增长内存空间,但不分配物理内存,等触发缺页中断是再分配。但是这里比较复杂的是要注意内存空间的权限以及在分配完物理内存后要加载映射文件的内容,并增加文件的引用计数。
  • 我们需要一个结构体来记录每个进程有哪些 mmap 的区域,这个结构叫做 VMA,他包含了映射空间的一些元信息。这个结构体可以提前按固定大小分配。
  • munmap 找到地址范围的 VMA 并取消映射指定的页面。如果 munmap 删除了之前 mmap 的所有页面,它应该减少相应文件的引用计数。如果修改了未映射的页面并且文件映射为 MAP_SHARED,则将页面写回文件。
  • 修改 fork 以确保 child 与 parent 具有相同的映射区域。
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
struct vma {
  uint64 addr;
  int length;
  int usedlength;
  int prot;
  int flags;
  int offset;
  struct file *fp;
};

struct proc {
  struct spinlock lock;

  // p->lock must be held when using these:
  enum procstate state;        // Process state
  struct proc *parent;         // Parent process
  void *chan;                  // If non-zero, sleeping on chan
  int killed;                  // If non-zero, have been killed
  int xstate;                  // Exit status to be returned to parent's wait
  int pid;                     // Process ID

  // these are private to the process, so p->lock need not be held.
  uint64 kstack;               // Virtual address of kernel stack
  uint64 sz;                   // Size of process memory (bytes)
  pagetable_t pagetable;       // User page table
  struct trapframe *trapframe; // data page for trampoline.S
  struct context context;      // swtch() here to run process
  struct file *ofile[NOFILE];  // Open files
  struct inode *cwd;           // Current directory
  char name[16];               // Process name (debugging)
  struct vma vmas[16];
};

uint64
sys_mmap(void)
{
  struct file *f;
  uint64 offset;
  int n;
  int addr, prot, flags, fd;
  // 检查传入参数是否合法
  if(argint(0, &addr) < 0 || argfd(4, &fd, &f) < 0 || argint(1, &n) < 0 || argaddr(5, &offset) < 0 ||
    argint(2, &prot) < 0 || argint(3, &flags) < 0)
    return 0xffffffffffffffff;
  // 检查权限
  if((!f->writable) && (prot & PROT_WRITE) && (flags & MAP_SHARED)) return 0xffffffffffffffff;
  // 增加文件引用计数
  filedup(f);
  f->off = offset;
  uint64 retaddr = myproc()->sz;
  myproc()->sz += n;
  // 寻址一个空闲的 vma
  int idx = 0;
  for(int i = 0; i < 16; i++) {
    if(myproc()->vmas[i].length == 0) {
      idx = i;
      break;
    }
  }
  // 设置 vma 信息
  struct vma *pvma = &myproc()->vmas[idx];
  pvma->addr = retaddr;
  pvma->length = n;
  pvma->prot = prot;
  pvma->flags = flags;
  pvma->fp = f;
  pvma->offset = offset;
  return retaddr;
}

void
usertrap(void)
{
  int which_dev = 0;

  if((r_sstatus() & SSTATUS_SPP) != 0)
    panic("usertrap: not from user mode");

  // send interrupts and exceptions to kerneltrap(),
  // since we're now in the kernel.
  w_stvec((uint64)kernelvec);

  struct proc *p = myproc();

  // save user program counter.
  p->trapframe->epc = r_sepc();

  if(r_scause() == 8){
    // system call

    if(p->killed)
      exit(-1);

    // sepc points to the ecall instruction,
    // but we want to return to the next instruction.
    p->trapframe->epc += 4;

    // an interrupt will change sstatus &c registers,
    // so don't enable until done with those registers.
    intr_on();

    syscall();
  } else if((which_dev = devintr()) != 0){
    // ok
  } else {
    if(r_scause() == 13 || r_scause() == 15) { // 根据 r_scause 的值判断是不是缺页中断
      uint64 va = r_stval(); // 获取发生中断的虚拟地址
      // 找到发生缺页的 vma
      int idx = 0;
      for(int i = 0; i < 16; i++) {
          if(myproc()->vmas[i].length == 0) continue;
          if(va>= myproc()->vmas[i].addr && va < myproc()->vmas[i].addr+myproc()->vmas[i].length) {
          idx =i;
          break;
        }
      }
        struct vma* pvma = &myproc()->vmas[idx];
        if(va>= pvma->addr && va < pvma->addr + pvma->length) {
          uint64 a = PGROUNDDOWN(va);
          char* mem = kalloc(); // 分配物理页
          if(mem == 0){ // 判断是否内存不足
            p->killed = 1;
          } else {
            memset(mem, 0, PGSIZE);
            int flags = 0;
            // 设置权限位
            int prot = pvma->prot;
            if(prot & PROT_READ){
              flags |= PTE_R;
            }
            if(prot & PROT_WRITE){
              flags |= PTE_W;
            }
            if(prot & PROT_EXEC){
              flags |= PTE_X;
            }
            if(mappages(p->pagetable, a, PGSIZE, (uint64)mem, flags|PTE_U) != 0){ // 完成映射
              kfree(mem);
              p->killed = 1;
            }
          }
          // 将文件内容加载到物理内存
          struct file *f = pvma->fp;
          int r = 0;
          ilock(f->ip);
          if((r = readi(f->ip, 1, a, a-pvma->addr, PGSIZE)) > 0) {
            f->off += r;
            pvma->usedlength += PGSIZE;
          }
          iunlock(f->ip);
        } else {
          p->killed = 1;
        }
    } else {
      printf("usertrap(): unexpected scause %p pid=%d\n", r_scause(), p->pid);
      printf("sepc=%p stval=%p\n", r_sepc(), r_stval());
      p->killed = 1;
    }
  }

  if(p->killed)
    exit(-1);

  // give up the CPU if this is a timer interrupt.
  if(which_dev == 2)
    yield();

  usertrapret();
}

void decrmmap(struct file *f)
{
  acquire(&ftable.lock);
  if(f->ref < 1) {
    release(&ftable.lock);
    return;
  }
  if(--f->ref > 0){
    release(&ftable.lock);
    return;
  }
  release(&ftable.lock);
}

uint64
sys_munmap(void)
{
  int addr, length;
  if(argint(0, &addr) < 0 || argint(1, &length) < 0)
    return -1;
  // 查找 vma
  int idx = 0;
  for(int i = 0; i < 16; i++) {
    if(myproc()->vmas[i].length == 0) continue;
    if(addr>= myproc()->vmas[i].addr && addr < myproc()->vmas[i].addr+myproc()->vmas[i].length) {
      idx = i;
      break;
    }
  }
  struct vma *pvma = &myproc()->vmas[idx];
  pte_t *pte;
  pvma->fp->off = pvma->offset;
  int flag = 0;
  // 从 vma 空间中找到要解除映射的页并解除映射
  for(int va = addr; va < addr + length; va += PGSIZE){
    if((pte = walk(myproc()->pagetable, va, 0)) == 0)
      continue;
    if((*pte & PTE_V) == 0)
      continue;
    if(PTE_FLAGS(*pte) == PTE_V)
      panic("uvmunmap: not a leaf");
    if(pvma->flags & MAP_SHARED){ // 写回文件
      filewrite(pvma->fp, va, PGSIZE);
    }
    uint64 pa = PTE2PA(*pte);
    kfree((void*)pa);
    pvma->usedlength -= PGSIZE;
    flag = 1;
    myproc()->sz -= PGSIZE;
    *pte = 0;
  }
  // 所有映射都解除了,释放文件引用计数
  if(pvma->usedlength == 0 && flag) {
    struct file* f = pvma->fp;
    decrmmap(f);
    pvma->length = 0;
  }
  return 0;
}

int
fork(void)
{
  int i, pid;
  struct proc *np;
  struct proc *p = myproc();

  // Allocate process.
  if((np = allocproc()) == 0){
    return -1;
  }

  // 复制 vma
  for(int i = 0; i < 16; i++){
    if(p->vmas[i].length == 0) continue;
      struct vma* pvma = &np->vmas[i];
      struct vma* ppvma = &p->vmas[i];
      pvma->addr = ppvma->addr;
      pvma->length = ppvma->length;
      pvma->prot = ppvma->prot;
      pvma->flags = ppvma->flags;
      pvma->fp = ppvma->fp;
      pvma->offset = ppvma->offset;
      pvma->usedlength = ppvma->usedlength;
      filedup(pvma->fp);
  }

  // Copy user memory from parent to child.
  if(uvmcopy(p->pagetable, np->pagetable, p->sz) < 0){
    freeproc(np);
    release(&np->lock);
    return -1;
  }
  np->sz = p->sz;

  np->parent = p;

  // copy saved user registers.
  *(np->trapframe) = *(p->trapframe);

  // Cause fork to return 0 in the child.
  np->trapframe->a0 = 0;

  // increment reference counts on open file descriptors.
  for(i = 0; i < NOFILE; i++)
    if(p->ofile[i])
      np->ofile[i] = filedup(p->ofile[i]);
  np->cwd = idup(p->cwd);

  safestrcpy(np->name, p->name, sizeof(p->name));

  pid = np->pid;

  np->state = RUNNABLE;

  release(&np->lock);

  return pid;
}

int
uvmcopy(pagetable_t old, pagetable_t new, uint64 sz)
{
  pte_t *pte;
  uint64 pa, i;
  uint flags;
  char *mem;

  for(i = 0; i < sz; i += PGSIZE){
    if((pte = walk(old, i, 0)) == 0)
      // panic("uvmcopy: pte should exist"); 由于是懒加载所以这里需要忽略没有 pte 的情况,下面的一行同理
      continue;
    if((*pte & PTE_V) == 0)
      // panic("uvmcopy: page not present");
      continue;
    pa = PTE2PA(*pte);
    flags = PTE_FLAGS(*pte);
    if((mem = kalloc()) == 0)
      goto err;
    memmove(mem, (char*)pa, PGSIZE);
    if(mappages(new, i, PGSIZE, (uint64)mem, flags) != 0){
      kfree(mem);
      goto err;
    }
  }
  return 0;

 err:
  uvmunmap(new, 0, i / PGSIZE, 1);
  return -1;
}

void
uvmunmap(pagetable_t pagetable, uint64 va, uint64 npages, int do_free)
{
  uint64 a;
  pte_t *pte;

  if((va % PGSIZE) != 0)
    panic("uvmunmap: not aligned");

  for(a = va; a < va + npages*PGSIZE; a += PGSIZE){
    if((pte = walk(pagetable, a, 0)) == 0)
      // panic("uvmunmap: walk"); 同 uvmcopy
      continue;
    if((*pte & PTE_V) == 0)
      // panic("uvmunmap: not mapped");
      continue;
    if(PTE_FLAGS(*pte) == PTE_V)
      panic("uvmunmap: not a leaf");
    if(do_free){
      uint64 pa = PTE2PA(*pte);
      kfree((void*)pa);
    }
    *pte = 0;
  }
}

总结

这个实验让我们实现了简单的 mmap,整体流程和 lazy page allocation 类似,但是涉及到了对文件的操作,有很多细节需要注意,比如 vma 如何设计,文件读写,加引用,解引用,文件权限设置,mmap 参数校验等,做的过程也是跑了很多次测试才完善这些细节的。