mem.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #include <u.h>
  10. #include <libc.h>
  11. #include <venti.h>
  12. enum {
  13. IdealAlignment = 32,
  14. ChunkSize = 128*1024
  15. };
  16. void
  17. vtfree(void *p)
  18. {
  19. if(p == 0)
  20. return;
  21. free(p);
  22. }
  23. void *
  24. vtmalloc(int size)
  25. {
  26. void *p;
  27. p = malloc(size);
  28. if(p == 0)
  29. sysfatal("vtmalloc: out of memory");
  30. setmalloctag(p, getcallerpc());
  31. return p;
  32. }
  33. void *
  34. vtmallocz(int size)
  35. {
  36. void *p = vtmalloc(size);
  37. memset(p, 0, size);
  38. setmalloctag(p, getcallerpc());
  39. return p;
  40. }
  41. void *
  42. vtrealloc(void *p, int size)
  43. {
  44. if(p == nil)
  45. return vtmalloc(size);
  46. p = realloc(p, size);
  47. if(p == 0)
  48. sysfatal("vtMemRealloc: out of memory");
  49. setrealloctag(p, getcallerpc());
  50. return p;
  51. }
  52. void *
  53. vtbrk(int n)
  54. {
  55. static Lock lk;
  56. static uint8_t *buf;
  57. static int nbuf, nchunk;
  58. int align, pad;
  59. void *p;
  60. if(n >= IdealAlignment)
  61. align = IdealAlignment;
  62. else if(n > 8)
  63. align = 8;
  64. else
  65. align = 4;
  66. lock(&lk);
  67. pad = (align - (uintptr)buf) & (align-1);
  68. if(n + pad > nbuf) {
  69. buf = vtmallocz(ChunkSize);
  70. nbuf = ChunkSize;
  71. pad = (align - (uintptr)buf) & (align-1);
  72. nchunk++;
  73. }
  74. assert(n + pad <= nbuf);
  75. p = buf + pad;
  76. buf += pad + n;
  77. nbuf -= pad + n;
  78. unlock(&lk);
  79. return p;
  80. }