mem.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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(&size));
  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(&size));
  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(&size));
  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. }