XINU
freemem.c
Go to the documentation of this file.
1 
5 #include <xinu.h>
6 
33 syscall freemem(char *blkaddr, uint32 nbytes)
34 {
35  intmask mask; /* Saved interrupt mask */
36  struct memblk *next, *prev, *block;
37  uint32 top;
38 
39  mask = disable();
40  if ((nbytes == 0) || ((uint32)blkaddr < (uint32)minheap) || ((uint32)blkaddr > (uint32)maxheap))
41  {
42  restore(mask);
43  return SYSERR;
44  }
45 
46  nbytes = (uint32)roundmb(nbytes); /* Use memblk multiples */
47  block = (struct memblk *)blkaddr;
48 
49  prev = &memlist; /* Walk along free list */
50  next = memlist.mnext;
51  while ((next != NULL) && (next < block))
52  {
53  prev = next;
54  next = next->mnext;
55  }
56 
57  if (prev == &memlist)
58  { /* Compute top of previous block*/
59  top = (uint32)NULL;
60  }
61  else
62  {
63  top = (uint32)prev + prev->mlength;
64  }
65 
66  /* Ensure new block does not overlap previous or next blocks */
67 
68  if (((prev != &memlist) && (uint32)block < top) || ((next != NULL) && (uint32)block + nbytes > (uint32)next))
69  {
70  restore(mask);
71  return SYSERR;
72  }
73 
74  memlist.mlength += nbytes;
75 
76  /* Either coalesce with previous block or add to free list */
77 
78  if (top == (uint32)block)
79  { /* Coalesce with previous block */
80  prev->mlength += nbytes;
81  block = prev;
82  }
83  else
84  { /* Link into list as new node */
85  block->mnext = next;
86  block->mlength = nbytes;
87  prev->mnext = block;
88  }
89 
90  /* Coalesce with next block if adjacent */
91 
92  if (((uint32)block + block->mlength) == (uint32)next)
93  {
94  block->mlength += next->mlength;
95  block->mnext = next->mnext;
96  }
97  restore(mask);
98  return OK;
99 }
#define NULL
連結リスト用のNULLポインタ
Definition: kernel.h:68
メモリブロックを管理するための構造体。
Definition: memory.h:53
void restore(intmask)
全てのシステムヘッダファイルをインクルードする。
#define SYSERR
処理が失敗した場合
Definition: kernel.h:79
#define roundmb(x)
メモリブロックサイズ(8の倍数)にアドレスを変換するために、8の倍数で丸める。
Definition: memory.h:25
syscall freemem(char *blkaddr, uint32 nbytes)
メモリブロックを解放し、ブロックを空きリストに戻す。
Definition: freemem.c:33
struct memblk * mnext
次のフリーメモリブロックへのポインタ
Definition: memory.h:56
#define OK
処理が成功した場合
Definition: kernel.h:77
struct memblk memlist
フリーメモリリストの先頭
Definition: initialize.c:27
void * maxheap
最上位かつ正常なヒープアドレス
Definition: meminit.c:10
uint32 intmask
保存された割り込みマスク
Definition: kernel.h:38
void * minheap
ヒープの開始地点
Definition: meminit.c:8
uint32 mlength
memblk構造体のサイズを含むブロックサイズ
Definition: memory.h:58
int32 syscall
システムコール関数 返り値の型
Definition: kernel.h:47
unsigned int uint32
符号なし32ビット整数(unsigned int)
Definition: kernel.h:15
intmask disable(void)
割り込み禁止(intr.Sに定義がある)