summaryrefslogtreecommitdiff
path: root/sys/src/liboventi/plan9-io.c
blob: e34a8d37599c7e5be874b9feeeed710184be77ae (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#include <u.h>
#include <libc.h>
#include <oventi.h>

enum {
	IdealAlignment = 32,
	ChunkSize 	= 128*1024,
};


void
vtMemFree(void *p)
{
	if(p == 0)
		return;
	free(p);
}


void *
vtMemAlloc(int size)
{
	void *p;

	p = malloc(size);
	if(p == 0)
		vtFatal("vtMemAlloc: out of memory");
	setmalloctag(p, getcallerpc(&size));
	return p;
}

void *
vtMemAllocZ(int size)
{
	void *p = vtMemAlloc(size);
	memset(p, 0, size);
	setmalloctag(p, getcallerpc(&size));
	return p;
}

void *
vtMemRealloc(void *p, int size)
{
	if(p == nil)
		return vtMemAlloc(size);
	p = realloc(p, size);
	if(p == 0)
		vtFatal("vtRealloc: out of memory");
	setrealloctag(p, getcallerpc(&size));
	return p;
}


void *
vtMemBrk(int n)
{
	static Lock lk;
	static uchar *buf;
	static int nbuf;
	static int nchunk;
	int align, pad;
	void *p;

	if(n >= IdealAlignment)
		align = IdealAlignment;
	else if(n > 8)
		align = 8;
	else	
		align = 4;

	lock(&lk);
	pad = (align - (uintptr)buf) & (align-1);
	if(n + pad > nbuf) {
		buf = vtMemAllocZ(ChunkSize);
		setmalloctag(buf, getcallerpc(&n));
		nbuf = ChunkSize;
		pad = (align - (uintptr)buf) & (align-1);
		nchunk++;
	}

	assert(n + pad <= nbuf);	
	
	p = buf + pad;
	buf += pad + n;
	nbuf -= pad + n;
	unlock(&lk);

	return p;
}

void
vtThreadSetName(char *name)
{
	int fd;
	char buf[32];

	sprint(buf, "/proc/%d/args", getpid());
	if((fd = open(buf, OWRITE)) >= 0){
		write(fd, name, strlen(name));
		close(fd);
	}
}

int
vtFdRead(int fd, uchar *buf, int n)
{
	n = read(fd, buf, n);
	if(n < 0) {
		vtOSError();
		return -1;
	}
	if(n == 0) {
		vtSetError("unexpected EOF");
		return 0;
	}
	return n;
}

int
vtFdWrite(int fd, uchar *buf, int n)
{
	int nn;
	
	nn = write(fd, buf, n);
	if(nn < 0) {
		vtOSError();
		return 0;
	}
	if(n != nn) {
		vtSetError("truncated write");
		return 0;
	}
	return 1;
}

void
vtFdClose(int fd)
{
	close(fd);
}

char *
vtOSError(void)
{
	return vtSetError("%r");
}