aboutsummaryrefslogtreecommitdiff
path: root/src/lib9pclient/read.c
blob: 605372884cd371b0f3f41476c76e5a98f1e49aa8 (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
/* Copyright (C) 2003 Russ Cox, Massachusetts Institute of Technology */
/* See COPYRIGHT */

#include <u.h>
#include <libc.h>
#include <fcall.h>
#include <9pclient.h>
#include "fsimpl.h"

long
fspread(CFid *fid, void *buf, long n, vlong offset)
{
	Fcall tx, rx;
	void *freep;
	uint msize;

	msize = fid->fs->msize - IOHDRSZ;
	if(n > msize)
		n = msize;
	tx.type = Tread;
	tx.fid = fid->fid;
	if(offset == -1){
		qlock(&fid->lk);
		tx.offset = fid->offset;
		qunlock(&fid->lk);
	}else
		tx.offset = offset;
	tx.count = n;

	if(_fsrpc(fid->fs, &tx, &rx, &freep) < 0)
		return -1;
	if(rx.type == Rerror){
		werrstr("%s", rx.ename);
		free(freep);
		return -1;
	}
	if(rx.count){
		memmove(buf, rx.data, rx.count);
		if(offset == -1){
			qlock(&fid->lk);
			fid->offset += rx.count;
			qunlock(&fid->lk);
		}
	}
	free(freep);
	
	return rx.count;
}

long
fsread(CFid *fid, void *buf, long n)
{
	return fspread(fid, buf, n, -1);
}

long
fsreadn(CFid *fid, void *buf, long n)
{
	long tot, nn;

	for(tot=0; tot<n; tot+=nn){
		nn = fsread(fid, (char*)buf+tot, n-tot);
		if(nn <= 0){
			if(tot == 0)
				return nn;
			break;
		}
	}
	return tot;
}