Fix problem with terminating on unaligned sizes
[fio.git] / flow.c
CommitLineData
9e684a49
DE
1#include "fio.h"
2#include "mutex.h"
3#include "smalloc.h"
4#include "flist.h"
5
6struct fio_flow {
7 unsigned int refs;
8 struct flist_head list;
9 unsigned int id;
10 long long int flow_counter;
11};
12
13static struct flist_head *flow_list;
14static struct fio_mutex *flow_lock;
15
16int flow_threshold_exceeded(struct thread_data *td)
17{
18 struct fio_flow *flow = td->flow;
19 int sign;
20
21 if (!flow)
22 return 0;
23
24 sign = td->o.flow > 0 ? 1 : -1;
25 if (sign * flow->flow_counter > td->o.flow_watermark) {
26 if (td->o.flow_sleep)
27 usleep(td->o.flow_sleep);
28 return 1;
29 }
30
31 /* No synchronization needed because it doesn't
32 * matter if the flow count is slightly inaccurate */
33 flow->flow_counter += td->o.flow;
34 return 0;
35}
36
37static struct fio_flow *flow_get(unsigned int id)
38{
8e8b225d 39 struct fio_flow *flow = NULL;
9e684a49
DE
40 struct flist_head *n;
41
fba5c5ff
JA
42 if (!flow_lock)
43 return NULL;
44
9e684a49
DE
45 fio_mutex_down(flow_lock);
46
47 flist_for_each(n, flow_list) {
48 flow = flist_entry(n, struct fio_flow, list);
49 if (flow->id == id)
50 break;
51
52 flow = NULL;
53 }
54
55 if (!flow) {
56 flow = smalloc(sizeof(*flow));
fba5c5ff
JA
57 if (!flow) {
58 log_err("fio: smalloc pool exhausted\n");
59 return NULL;
60 }
9e684a49
DE
61 flow->refs = 0;
62 INIT_FLIST_HEAD(&flow->list);
63 flow->id = id;
64 flow->flow_counter = 0;
65
66 flist_add_tail(&flow->list, flow_list);
67 }
68
69 flow->refs++;
70 fio_mutex_up(flow_lock);
71 return flow;
72}
73
74static void flow_put(struct fio_flow *flow)
75{
fba5c5ff
JA
76 if (!flow_lock)
77 return;
78
9e684a49
DE
79 fio_mutex_down(flow_lock);
80
81 if (!--flow->refs) {
82 flist_del(&flow->list);
83 sfree(flow);
84 }
85
86 fio_mutex_up(flow_lock);
87}
88
89void flow_init_job(struct thread_data *td)
90{
91 if (td->o.flow)
92 td->flow = flow_get(td->o.flow_id);
93}
94
95void flow_exit_job(struct thread_data *td)
96{
97 if (td->flow) {
98 flow_put(td->flow);
99 td->flow = NULL;
100 }
101}
102
103void flow_init(void)
104{
9e684a49 105 flow_list = smalloc(sizeof(*flow_list));
fba5c5ff
JA
106 if (!flow_list) {
107 log_err("fio: smalloc pool exhausted\n");
108 return;
109 }
110
111 flow_lock = fio_mutex_init(FIO_MUTEX_UNLOCKED);
112 if (!flow_lock) {
113 log_err("fio: failed to allocate flow lock\n");
114 sfree(flow_list);
115 return;
116 }
117
9e684a49
DE
118 INIT_FLIST_HEAD(flow_list);
119}
120
121void flow_exit(void)
122{
fba5c5ff
JA
123 if (flow_lock)
124 fio_mutex_remove(flow_lock);
125 if (flow_list)
126 sfree(flow_list);
9e684a49 127}