mem.c 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #include <u.h>
  2. #include <libc.h>
  3. #include <venti.h>
  4. enum {
  5. IdealAlignment = 32,
  6. ChunkSize = 128*1024
  7. };
  8. void
  9. vtfree(void *p)
  10. {
  11. if(p == 0)
  12. return;
  13. free(p);
  14. }
  15. void *
  16. vtmalloc(int size)
  17. {
  18. void *p;
  19. p = malloc(size);
  20. if(p == 0)
  21. sysfatal("vtmalloc: out of memory");
  22. setmalloctag(p, getcallerpc(&size));
  23. return p;
  24. }
  25. void *
  26. vtmallocz(int size)
  27. {
  28. void *p = vtmalloc(size);
  29. memset(p, 0, size);
  30. setmalloctag(p, getcallerpc(&size));
  31. return p;
  32. }
  33. void *
  34. vtrealloc(void *p, int size)
  35. {
  36. if(p == nil)
  37. return vtmalloc(size);
  38. p = realloc(p, size);
  39. if(p == 0)
  40. sysfatal("vtMemRealloc: out of memory");
  41. setrealloctag(p, getcallerpc(&size));
  42. return p;
  43. }
  44. void *
  45. vtbrk(int n)
  46. {
  47. static Lock lk;
  48. static uchar *buf;
  49. static int nbuf, nchunk;
  50. int align, pad;
  51. void *p;
  52. if(n >= IdealAlignment)
  53. align = IdealAlignment;
  54. else if(n > 8)
  55. align = 8;
  56. else
  57. align = 4;
  58. lock(&lk);
  59. pad = (align - (uintptr)buf) & (align-1);
  60. if(n + pad > nbuf) {
  61. buf = vtmallocz(ChunkSize);
  62. nbuf = ChunkSize;
  63. pad = (align - (uintptr)buf) & (align-1);
  64. nchunk++;
  65. }
  66. assert(n + pad <= nbuf);
  67. p = buf + pad;
  68. buf += pad + n;
  69. nbuf -= pad + n;
  70. unlock(&lk);
  71. return p;
  72. }