plan9-io.c 1.7 KB

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