configure: add gettid() test
[fio.git] / fifo.c
CommitLineData
e2887563
JA
1/*
2 * A simple kernel FIFO implementation.
3 *
4 * Copyright (C) 2004 Stelian Pop <stelian@popies.net>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
fa07eaa6 18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
e2887563
JA
19 *
20 */
21
22#include <stdio.h>
23#include <stdlib.h>
24#include <string.h>
25
26#include "fifo.h"
3d2d14bc 27#include "minmax.h"
e2887563
JA
28
29struct fifo *fifo_alloc(unsigned int size)
30{
31 struct fifo *fifo;
32
33 fifo = malloc(sizeof(struct fifo));
34 if (!fifo)
cc62ea70 35 return NULL;
e2887563
JA
36
37 fifo->buffer = malloc(size);
38 fifo->size = size;
f12b323f 39 fifo->in = fifo->out = 0;
e2887563
JA
40
41 return fifo;
42}
43
44void fifo_free(struct fifo *fifo)
45{
46 free(fifo->buffer);
47 free(fifo);
48}
49
50unsigned int fifo_put(struct fifo *fifo, void *buffer, unsigned int len)
51{
52 unsigned int l;
53
104bc4bd 54 len = min(len, fifo_room(fifo));
e2887563
JA
55
56 /* first put the data starting from fifo->in to buffer end */
57 l = min(len, fifo->size - (fifo->in & (fifo->size - 1)));
58 memcpy(fifo->buffer + (fifo->in & (fifo->size - 1)), buffer, l);
59
60 /* then put the rest (if any) at the beginning of the buffer */
61 memcpy(fifo->buffer, buffer + l, len - l);
62
63 /*
64 * Ensure that we add the bytes to the fifo -before-
65 * we update the fifo->in index.
66 */
67
68 fifo->in += len;
69
70 return len;
71}
72
5ec10eaa 73unsigned int fifo_get(struct fifo *fifo, void *buf, unsigned int len)
e2887563 74{
e2887563
JA
75 len = min(len, fifo->in - fifo->out);
76
5ec10eaa 77 if (buf) {
104bc4bd 78 unsigned int l;
e2887563 79
104bc4bd
JA
80 /*
81 * first get the data from fifo->out until the end of the buffer
82 */
83 l = min(len, fifo->size - (fifo->out & (fifo->size - 1)));
5ec10eaa 84 memcpy(buf, fifo->buffer + (fifo->out & (fifo->size - 1)), l);
104bc4bd
JA
85
86 /*
87 * then get the rest (if any) from the beginning of the buffer
88 */
5ec10eaa 89 memcpy(buf + l, fifo->buffer, len - l);
104bc4bd 90 }
e2887563
JA
91
92 fifo->out += len;
93
104bc4bd
JA
94 if (fifo->in == fifo->out)
95 fifo->in = fifo->out = 0;
96
e2887563
JA
97 return len;
98}