blob: fce115e6936e833a7bed1c4f7c501dcd44b164c4 [file] [log] [blame]
Willy Tarreau982b6e32009-01-25 13:49:53 +01001/*
2 * Pipe management
3 *
4 * Copyright 2000-2009 Willy Tarreau <w@1wt.eu>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
13#include <unistd.h>
Willy Tarreau9ed560e2011-10-24 17:09:22 +020014#include <fcntl.h>
Willy Tarreau982b6e32009-01-25 13:49:53 +010015
16#include <common/config.h>
17#include <common/memory.h>
18
19#include <types/global.h>
20#include <types/pipe.h>
21
22struct pool_head *pool2_pipe = NULL;
23struct pipe *pipes_live = NULL; /* pipes which are still ready to use */
24int pipes_used = 0; /* # of pipes in use (2 fds each) */
25int pipes_free = 0; /* # of pipes unused */
26
27/* allocate memory for the pipes */
28static void init_pipe()
29{
30 pool2_pipe = create_pool("pipe", sizeof(struct pipe), MEM_F_SHARED);
31 pipes_used = 0;
32 pipes_free = 0;
33}
34
35/* return a pre-allocated empty pipe. Try to allocate one if there isn't any
36 * left. NULL is returned if a pipe could not be allocated.
37 */
38struct pipe *get_pipe()
39{
40 struct pipe *ret;
41 int pipefd[2];
42
43 if (likely(pipes_live)) {
44 ret = pipes_live;
45 pipes_live = pipes_live->next;
46 pipes_free--;
47 pipes_used++;
48 return ret;
49 }
50
51 if (pipes_used >= global.maxpipes)
52 return NULL;
53
54 ret = pool_alloc2(pool2_pipe);
55 if (!ret)
56 return NULL;
57
58 if (pipe(pipefd) < 0) {
59 pool_free2(pool2_pipe, ret);
60 return NULL;
61 }
Willy Tarreaubd9a0a72011-10-23 21:14:29 +020062#ifdef F_SETPIPE_SZ
63 if (global.tune.pipesize)
64 fcntl(pipefd[0], F_SETPIPE_SZ, global.tune.pipesize);
65#endif
Willy Tarreau982b6e32009-01-25 13:49:53 +010066 ret->data = 0;
67 ret->prod = pipefd[1];
68 ret->cons = pipefd[0];
69 ret->next = NULL;
70 pipes_used++;
71 return ret;
72}
73
74/* destroy a pipe, possibly because an error was encountered on it. Its FDs
75 * will be closed and it will not be reinjected into the live pool.
76 */
77void kill_pipe(struct pipe *p)
78{
79 close(p->prod);
80 close(p->cons);
81 pool_free2(pool2_pipe, p);
82 pipes_used--;
83 return;
84}
85
86/* put back a unused pipe into the live pool. If it still has data in it, it is
87 * closed and not reinjected into the live pool. The caller is not allowed to
88 * use it once released.
89 */
90void put_pipe(struct pipe *p)
91{
92 if (p->data) {
93 kill_pipe(p);
94 return;
95 }
96 p->next = pipes_live;
97 pipes_live = p;
98 pipes_free++;
99 pipes_used--;
100}
101
102
103__attribute__((constructor))
104static void __pipe_module_init(void)
105{
106 init_pipe();
107}
108
109/*
110 * Local variables:
111 * c-indent-level: 8
112 * c-basic-offset: 8
113 * End:
114 */