plan9-io.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. #include <u.h>
  2. #include <libc.h>
  3. #include <oventi.h>
  4. enum {
  5. IdealAlignment = 32,
  6. ChunkSize = 128*1024,
  7. };
  8. void
  9. vtMemFree(void *p)
  10. {
  11. if(p == 0)
  12. return;
  13. free(p);
  14. }
  15. void *
  16. vtMemAlloc(int size)
  17. {
  18. void *p;
  19. p = malloc(size);
  20. if(p == 0)
  21. vtFatal("vtMemAlloc: out of memory");
  22. setmalloctag(p, getcallerpc(&size));
  23. return p;
  24. }
  25. void *
  26. vtMemAllocZ(int size)
  27. {
  28. void *p = vtMemAlloc(size);
  29. memset(p, 0, size);
  30. setmalloctag(p, getcallerpc(&size));
  31. return p;
  32. }
  33. void *
  34. vtMemRealloc(void *p, int size)
  35. {
  36. if(p == nil)
  37. return vtMemAlloc(size);
  38. p = realloc(p, size);
  39. if(p == 0)
  40. vtFatal("vtRealloc: out of memory");
  41. setrealloctag(p, getcallerpc(&size));
  42. return p;
  43. }
  44. void *
  45. vtMemBrk(int n)
  46. {
  47. static Lock lk;
  48. static uchar *buf;
  49. static int nbuf;
  50. static int nchunk;
  51. int align, pad;
  52. void *p;
  53. if(n >= IdealAlignment)
  54. align = IdealAlignment;
  55. else if(n > 8)
  56. align = 8;
  57. else
  58. align = 4;
  59. lock(&lk);
  60. pad = (align - (uintptr)buf) & (align-1);
  61. if(n + pad > nbuf) {
  62. buf = vtMemAllocZ(ChunkSize);
  63. setmalloctag(buf, getcallerpc(&n));
  64. nbuf = ChunkSize;
  65. pad = (align - (uintptr)buf) & (align-1);
  66. nchunk++;
  67. }
  68. assert(n + pad <= nbuf);
  69. p = buf + pad;
  70. buf += pad + n;
  71. nbuf -= pad + n;
  72. unlock(&lk);
  73. return p;
  74. }
  75. void
  76. vtThreadSetName(char *name)
  77. {
  78. int fd;
  79. char buf[32];
  80. sprint(buf, "/proc/%d/args", getpid());
  81. if((fd = open(buf, OWRITE)) >= 0){
  82. write(fd, name, strlen(name));
  83. close(fd);
  84. }
  85. }
  86. int
  87. vtFdRead(int fd, uchar *buf, int n)
  88. {
  89. n = read(fd, buf, n);
  90. if(n < 0) {
  91. vtOSError();
  92. return -1;
  93. }
  94. if(n == 0) {
  95. vtSetError("unexpected EOF");
  96. return 0;
  97. }
  98. return n;
  99. }
  100. int
  101. vtFdWrite(int fd, uchar *buf, int n)
  102. {
  103. int nn;
  104. nn = write(fd, buf, n);
  105. if(nn < 0) {
  106. vtOSError();
  107. return 0;
  108. }
  109. if(n != nn) {
  110. vtSetError("truncated write");
  111. return 0;
  112. }
  113. return 1;
  114. }
  115. void
  116. vtFdClose(int fd)
  117. {
  118. close(fd);
  119. }
  120. char *
  121. vtOSError(void)
  122. {
  123. return vtSetError("%r");
  124. }