blob: f4f1bae81e402f1cb024565e2d45db756a89379a [file] [log] [blame]
Willy Tarreaubaaee002006-06-26 02:48:02 +02001/*
2 * File descriptors management functions.
3 *
Willy Tarreauf817e9f2014-01-10 16:58:45 +01004 * Copyright 2000-2014 Willy Tarreau <w@1wt.eu>
Willy Tarreaubaaee002006-06-26 02:48:02 +02005 *
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 *
Willy Tarreau7be79a42012-11-11 15:02:54 +010011 * There is no direct link between the FD and the updates list. There is only a
12 * bit in the fdtab[] to indicate than a file descriptor is already present in
13 * the updates list. Once an fd is present in the updates list, it will have to
14 * be considered even if its changes are reverted in the middle or if the fd is
15 * replaced.
16 *
Willy Tarreauf817e9f2014-01-10 16:58:45 +010017 * The event state for an FD, as found in fdtab[].state, is maintained for each
18 * direction. The state field is built this way, with R bits in the low nibble
19 * and W bits in the high nibble for ease of access and debugging :
Willy Tarreau7be79a42012-11-11 15:02:54 +010020 *
Willy Tarreauf817e9f2014-01-10 16:58:45 +010021 * 7 6 5 4 3 2 1 0
Willy Tarreau5bee3e22019-09-04 09:52:57 +020022 * [ 0 | 0 | RW | AW | 0 | 0 | RR | AR ]
Willy Tarreauf817e9f2014-01-10 16:58:45 +010023 *
24 * A* = active *R = read
Willy Tarreau5bee3e22019-09-04 09:52:57 +020025 * R* = ready *W = write
Willy Tarreauf817e9f2014-01-10 16:58:45 +010026 *
27 * An FD is marked "active" when there is a desire to use it.
Willy Tarreauf817e9f2014-01-10 16:58:45 +010028 * An FD is marked "ready" when it has not faced a new EAGAIN since last wake-up
Willy Tarreau5bee3e22019-09-04 09:52:57 +020029 * (it is a cache of the last EAGAIN regardless of polling changes). Each poller
30 * has its own "polled" state for the same fd, as stored in the polled_mask.
Willy Tarreau7be79a42012-11-11 15:02:54 +010031 *
Willy Tarreau5bee3e22019-09-04 09:52:57 +020032 * We have 4 possible states for each direction based on these 2 flags :
Willy Tarreau7be79a42012-11-11 15:02:54 +010033 *
Willy Tarreau5bee3e22019-09-04 09:52:57 +020034 * +---+---+----------+---------------------------------------------+
35 * | R | A | State | Description |
36 * +---+---+----------+---------------------------------------------+
37 * | 0 | 0 | DISABLED | No activity desired, not ready. |
38 * | 0 | 1 | ACTIVE | Activity desired. |
39 * | 1 | 0 | STOPPED | End of activity. |
40 * | 1 | 1 | READY | Activity desired and reported. |
41 * +---+---+----------+---------------------------------------------+
Willy Tarreau7be79a42012-11-11 15:02:54 +010042 *
Willy Tarreauf817e9f2014-01-10 16:58:45 +010043 * The transitions are pretty simple :
44 * - fd_want_*() : set flag A
45 * - fd_stop_*() : clear flag A
46 * - fd_cant_*() : clear flag R (when facing EAGAIN)
47 * - fd_may_*() : set flag R (upon return from poll())
Willy Tarreauf817e9f2014-01-10 16:58:45 +010048 *
Willy Tarreau5bee3e22019-09-04 09:52:57 +020049 * Each poller then computes its own polled state :
50 * if (A) { if (!R) P := 1 } else { P := 0 }
Willy Tarreauf817e9f2014-01-10 16:58:45 +010051 *
Willy Tarreau5bee3e22019-09-04 09:52:57 +020052 * The state transitions look like the diagram below.
Willy Tarreauf817e9f2014-01-10 16:58:45 +010053 *
Willy Tarreau5bee3e22019-09-04 09:52:57 +020054 * may +----------+
55 * ,----| DISABLED | (READY=0, ACTIVE=0)
56 * | +----------+
57 * | want | ^
58 * | | |
59 * | v | stop
60 * | +----------+
61 * | | ACTIVE | (READY=0, ACTIVE=1)
62 * | +----------+
63 * | | ^
64 * | may | |
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070065 * | v | EAGAIN (can't)
Willy Tarreau5bee3e22019-09-04 09:52:57 +020066 * | +--------+
67 * | | READY | (READY=1, ACTIVE=1)
68 * | +--------+
69 * | stop | ^
70 * | | |
71 * | v | want
72 * | +---------+
73 * `--->| STOPPED | (READY=1, ACTIVE=0)
74 * +---------+
Willy Tarreaubaaee002006-06-26 02:48:02 +020075 */
76
Willy Tarreau2ff76222007-04-09 19:29:56 +020077#include <stdio.h>
Willy Tarreau4f60f162007-04-08 16:39:58 +020078#include <string.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020079#include <unistd.h>
Olivier Houchard79321b92018-07-26 17:55:11 +020080#include <fcntl.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020081#include <sys/types.h>
Willy Tarreau2d7f81b2019-02-21 22:19:17 +010082#include <sys/resource.h>
Willy Tarreau931d8b72019-08-27 11:08:17 +020083#include <sys/uio.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020084
Willy Tarreaue5733232019-05-22 19:24:06 +020085#if defined(USE_POLL)
Willy Tarreau9188ac62019-02-21 22:12:47 +010086#include <poll.h>
87#include <errno.h>
88#endif
89
Willy Tarreau4c7e4b72020-05-27 12:58:42 +020090#include <haproxy/api.h>
Willy Tarreau5d9ddc52021-10-06 19:54:09 +020091#include <haproxy/activity.h>
Willy Tarreaubc52bec2020-06-18 08:58:47 +020092#include <haproxy/cfgparse.h>
Willy Tarreau0f6ffd62020-06-03 19:33:00 +020093#include <haproxy/fd.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020094#include <haproxy/global.h>
Willy Tarreauc28aab02021-05-08 20:35:03 +020095#include <haproxy/log.h>
Willy Tarreaufc8f6a82020-06-03 19:20:59 +020096#include <haproxy/port_range.h>
Willy Tarreaub63888c2021-10-06 19:55:29 +020097#include <haproxy/ticks.h>
Willy Tarreaubc52bec2020-06-18 08:58:47 +020098#include <haproxy/tools.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020099
Willy Tarreaub2551052020-06-09 09:07:15 +0200100
Willy Tarreaua1090a52021-04-10 16:58:13 +0200101struct fdtab *fdtab __read_mostly = NULL; /* array of all the file descriptors */
102struct polled_mask *polled_mask __read_mostly = NULL; /* Array for the polled_mask of each fd */
103struct fdinfo *fdinfo __read_mostly = NULL; /* less-often used infos for file descriptors */
Willy Tarreaubaaee002006-06-26 02:48:02 +0200104int totalconn; /* total # of terminated sessions */
105int actconn; /* # of active sessions */
106
Willy Tarreaua1090a52021-04-10 16:58:13 +0200107struct poller pollers[MAX_POLLERS] __read_mostly;
108struct poller cur_poller __read_mostly;
Willy Tarreau4f60f162007-04-08 16:39:58 +0200109int nbpollers = 0;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200110
Willy Tarreau35ee7102022-07-08 11:33:43 +0200111volatile struct fdlist update_list[MAX_TGROUPS]; // Global update list
Olivier Houchard4815c8c2018-01-24 18:17:56 +0100112
Christopher Fauletd4604ad2017-05-29 10:40:41 +0200113THREAD_LOCAL int *fd_updt = NULL; // FD updates list
114THREAD_LOCAL int fd_nbupdt = 0; // number of updates in the list
Olivier Houchard79321b92018-07-26 17:55:11 +0200115THREAD_LOCAL int poller_rd_pipe = -1; // Pipe to wake the thread
Willy Tarreaua1090a52021-04-10 16:58:13 +0200116int poller_wr_pipe[MAX_THREADS] __read_mostly; // Pipe to wake the threads
Christopher Fauletd4604ad2017-05-29 10:40:41 +0200117
Olivier Houchard7c49d2e2019-04-16 18:37:05 +0200118volatile int ha_used_fds = 0; // Number of FD we're currently using
Willy Tarreau97ea9c42022-01-27 16:10:48 +0100119static struct fdtab *fdtab_addr; /* address of the allocated area containing fdtab */
Olivier Houchard7c49d2e2019-04-16 18:37:05 +0200120
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100121/* adds fd <fd> to fd list <list> if it was not yet in it */
Willy Tarreau4d9888c2022-07-06 14:43:51 +0200122void fd_add_to_fd_list(volatile struct fdlist *list, int fd)
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100123{
124 int next;
125 int new;
126 int old;
127 int last;
128
129redo_next:
Willy Tarreau4d9888c2022-07-06 14:43:51 +0200130 next = fdtab[fd].update.next;
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100131 /* Check that we're not already in the cache, and if not, lock us. */
Olivier Houchardfc51f0f52019-12-19 18:33:08 +0100132 if (next > -2)
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100133 goto done;
Olivier Houchardfc51f0f52019-12-19 18:33:08 +0100134 if (next == -2)
135 goto redo_next;
Willy Tarreau4d9888c2022-07-06 14:43:51 +0200136 if (!_HA_ATOMIC_CAS(&fdtab[fd].update.next, &next, -2))
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100137 goto redo_next;
Olivier Houchardd2b5d162019-03-08 13:47:21 +0100138 __ha_barrier_atomic_store();
Willy Tarreau11559a72018-02-05 17:52:24 +0100139
140 new = fd;
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100141redo_last:
142 /* First, insert in the linked list */
143 last = list->last;
144 old = -1;
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100145
Willy Tarreau4d9888c2022-07-06 14:43:51 +0200146 fdtab[fd].update.prev = -2;
Willy Tarreau11559a72018-02-05 17:52:24 +0100147 /* Make sure the "prev" store is visible before we update the last entry */
148 __ha_barrier_store();
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100149
Willy Tarreau11559a72018-02-05 17:52:24 +0100150 if (unlikely(last == -1)) {
151 /* list is empty, try to add ourselves alone so that list->last=fd */
Olivier Houchardd3608792019-03-08 18:47:42 +0100152 if (unlikely(!_HA_ATOMIC_CAS(&list->last, &old, new)))
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100153 goto redo_last;
154
155 /* list->first was necessary -1, we're guaranteed to be alone here */
156 list->first = fd;
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100157 } else {
Willy Tarreau11559a72018-02-05 17:52:24 +0100158 /* adding ourselves past the last element
159 * The CAS will only succeed if its next is -1,
160 * which means it's in the cache, and the last element.
161 */
Willy Tarreau4d9888c2022-07-06 14:43:51 +0200162 if (unlikely(!_HA_ATOMIC_CAS(&fdtab[last].update.next, &old, new)))
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100163 goto redo_last;
Willy Tarreau11559a72018-02-05 17:52:24 +0100164
165 /* Then, update the last entry */
166 list->last = fd;
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100167 }
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100168 __ha_barrier_store();
Willy Tarreau11559a72018-02-05 17:52:24 +0100169 /* since we're alone at the end of the list and still locked(-2),
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +0500170 * we know no one tried to add past us. Mark the end of list.
Willy Tarreau11559a72018-02-05 17:52:24 +0100171 */
Willy Tarreau4d9888c2022-07-06 14:43:51 +0200172 fdtab[fd].update.prev = last;
173 fdtab[fd].update.next = -1;
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100174 __ha_barrier_store();
175done:
176 return;
177}
178
179/* removes fd <fd> from fd list <list> */
Willy Tarreau4d9888c2022-07-06 14:43:51 +0200180void fd_rm_from_fd_list(volatile struct fdlist *list, int fd)
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100181{
182#if defined(HA_HAVE_CAS_DW) || defined(HA_CAS_IS_8B)
Willy Tarreau2b9f0662020-02-25 09:25:53 +0100183 volatile union {
184 struct fdlist_entry ent;
185 uint64_t u64;
186 uint32_t u32[2];
187 } cur_list, next_list;
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100188#endif
189 int old;
190 int new = -2;
191 int prev;
192 int next;
193 int last;
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100194lock_self:
195#if (defined(HA_CAS_IS_8B) || defined(HA_HAVE_CAS_DW))
Willy Tarreau2b9f0662020-02-25 09:25:53 +0100196 next_list.ent.next = next_list.ent.prev = -2;
Willy Tarreau4d9888c2022-07-06 14:43:51 +0200197 cur_list.ent = fdtab[fd].update;
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100198 /* First, attempt to lock our own entries */
199 do {
200 /* The FD is not in the FD cache, give up */
Willy Tarreau2b9f0662020-02-25 09:25:53 +0100201 if (unlikely(cur_list.ent.next <= -3))
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100202 return;
Willy Tarreau2b9f0662020-02-25 09:25:53 +0100203 if (unlikely(cur_list.ent.prev == -2 || cur_list.ent.next == -2))
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100204 goto lock_self;
205 } while (
206#ifdef HA_CAS_IS_8B
Willy Tarreau4d9888c2022-07-06 14:43:51 +0200207 unlikely(!_HA_ATOMIC_CAS(((uint64_t *)&fdtab[fd].update), (uint64_t *)&cur_list.u64, next_list.u64))
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100208#else
Willy Tarreau85af7602022-09-17 11:15:29 +0200209 unlikely(!_HA_ATOMIC_DWCAS(((long *)&fdtab[fd].update), (uint32_t *)&cur_list.u32, (const uint32_t *)&next_list.u32))
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100210#endif
Willy Tarreau2b9f0662020-02-25 09:25:53 +0100211 );
212 next = cur_list.ent.next;
213 prev = cur_list.ent.prev;
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100214
215#else
216lock_self_next:
Willy Tarreau4d9888c2022-07-06 14:43:51 +0200217 next = fdtab[fd].update.next;
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100218 if (next == -2)
219 goto lock_self_next;
220 if (next <= -3)
221 goto done;
Willy Tarreau4d9888c2022-07-06 14:43:51 +0200222 if (unlikely(!_HA_ATOMIC_CAS(&fdtab[fd].update.next, &next, -2)))
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100223 goto lock_self_next;
224lock_self_prev:
Willy Tarreau4d9888c2022-07-06 14:43:51 +0200225 prev = fdtab[fd].update.prev;
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100226 if (prev == -2)
227 goto lock_self_prev;
Willy Tarreau4d9888c2022-07-06 14:43:51 +0200228 if (unlikely(!_HA_ATOMIC_CAS(&fdtab[fd].update.prev, &prev, -2)))
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100229 goto lock_self_prev;
230#endif
Olivier Houchardd2b5d162019-03-08 13:47:21 +0100231 __ha_barrier_atomic_store();
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100232
233 /* Now, lock the entries of our neighbours */
234 if (likely(prev != -1)) {
235redo_prev:
236 old = fd;
237
Willy Tarreau4d9888c2022-07-06 14:43:51 +0200238 if (unlikely(!_HA_ATOMIC_CAS(&fdtab[prev].update.next, &old, new))) {
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100239 if (unlikely(old == -2)) {
240 /* Neighbour already locked, give up and
241 * retry again once he's done
242 */
Willy Tarreau4d9888c2022-07-06 14:43:51 +0200243 fdtab[fd].update.prev = prev;
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100244 __ha_barrier_store();
Willy Tarreau4d9888c2022-07-06 14:43:51 +0200245 fdtab[fd].update.next = next;
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100246 __ha_barrier_store();
247 goto lock_self;
248 }
249 goto redo_prev;
250 }
251 }
252 if (likely(next != -1)) {
253redo_next:
254 old = fd;
Willy Tarreau4d9888c2022-07-06 14:43:51 +0200255 if (unlikely(!_HA_ATOMIC_CAS(&fdtab[next].update.prev, &old, new))) {
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100256 if (unlikely(old == -2)) {
257 /* Neighbour already locked, give up and
258 * retry again once he's done
259 */
260 if (prev != -1) {
Willy Tarreau4d9888c2022-07-06 14:43:51 +0200261 fdtab[prev].update.next = fd;
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100262 __ha_barrier_store();
263 }
Willy Tarreau4d9888c2022-07-06 14:43:51 +0200264 fdtab[fd].update.prev = prev;
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100265 __ha_barrier_store();
Willy Tarreau4d9888c2022-07-06 14:43:51 +0200266 fdtab[fd].update.next = next;
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100267 __ha_barrier_store();
268 goto lock_self;
269 }
270 goto redo_next;
271 }
272 }
273 if (list->first == fd)
274 list->first = next;
275 __ha_barrier_store();
276 last = list->last;
Olivier Houchardd3608792019-03-08 18:47:42 +0100277 while (unlikely(last == fd && (!_HA_ATOMIC_CAS(&list->last, &last, prev))))
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100278 __ha_compiler_barrier();
279 /* Make sure we let other threads know we're no longer in cache,
280 * before releasing our neighbours.
281 */
282 __ha_barrier_store();
283 if (likely(prev != -1))
Willy Tarreau4d9888c2022-07-06 14:43:51 +0200284 fdtab[prev].update.next = next;
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100285 __ha_barrier_store();
286 if (likely(next != -1))
Willy Tarreau4d9888c2022-07-06 14:43:51 +0200287 fdtab[next].update.prev = prev;
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100288 __ha_barrier_store();
289 /* Ok, now we're out of the fd cache */
Willy Tarreau4d9888c2022-07-06 14:43:51 +0200290 fdtab[fd].update.next = -(next + 4);
Willy Tarreau4cc67a22018-02-05 17:14:55 +0100291 __ha_barrier_store();
292done:
293 return;
294}
295
Willy Tarreau2c3f9812021-03-24 10:51:32 +0100296/* deletes the FD once nobody uses it anymore, as detected by the caller by its
297 * thread_mask being zero and its running mask turning to zero. There is no
298 * protection against concurrent accesses, it's up to the caller to make sure
299 * only the last thread will call it. This is only for internal use, please use
300 * fd_delete() instead.
Willy Tarreau4f60f162007-04-08 16:39:58 +0200301 */
Willy Tarreau2c3f9812021-03-24 10:51:32 +0100302void _fd_delete_orphan(int fd)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200303{
Emeric Brunf41a3f62022-07-01 17:31:25 +0200304 uint fd_disown;
305
306 fd_disown = fdtab[fd].state & FD_DISOWN;
Willy Tarreaub41a6e92021-04-06 17:49:19 +0200307 if (fdtab[fd].state & FD_LINGER_RISK) {
Willy Tarreauad38ace2013-12-15 14:19:38 +0100308 /* this is generally set when connecting to servers */
Ilya Shipitsinb7e43f02020-04-02 15:02:08 +0500309 DISGUISE(setsockopt(fd, SOL_SOCKET, SO_LINGER,
310 (struct linger *) &nolinger, sizeof(struct linger)));
Willy Tarreauad38ace2013-12-15 14:19:38 +0100311 }
Willy Tarreau2f36d902022-07-06 16:23:41 +0200312
313 /* It's expected that a close() will result in the FD disappearing from
314 * pollers, but some pollers may have some internal bookkeeping to be
315 * done prior to the call (e.g. remove references from internal tables).
316 */
Willy Tarreau6ea20b12012-11-11 16:05:19 +0100317 if (cur_poller.clo)
318 cur_poller.clo(fd);
Willy Tarreau2d423292021-03-24 15:34:25 +0100319
Willy Tarreau2f36d902022-07-06 16:23:41 +0200320 /* we don't want this FD anymore in the global list */
Willy Tarreau35ee7102022-07-08 11:33:43 +0200321 fd_rm_from_fd_list(&update_list[tgid - 1], fd);
Willy Tarreau2f36d902022-07-06 16:23:41 +0200322
323 /* no more updates on this FD are relevant anymore */
324 HA_ATOMIC_STORE(&fdtab[fd].update_mask, 0);
Willy Tarreau8e2c0fa2022-07-06 16:20:11 +0200325 if (fd_nbupdt > 0 && fd_updt[fd_nbupdt - 1] == fd)
326 fd_nbupdt--;
Willy Tarreau2f36d902022-07-06 16:23:41 +0200327
Willy Tarreau2d423292021-03-24 15:34:25 +0100328 port_range_release_port(fdinfo[fd].port_range, fdinfo[fd].local_port);
Olivier Houchardc22580c2019-08-05 18:51:52 +0200329 polled_mask[fd].poll_recv = polled_mask[fd].poll_send = 0;
Willy Tarreau6ea20b12012-11-11 16:05:19 +0100330
Willy Tarreauf817e9f2014-01-10 16:58:45 +0100331 fdtab[fd].state = 0;
Willy Tarreauddedc162022-07-07 15:05:55 +0200332 fd_reset_tgid(fd);
Willy Tarreau6ea20b12012-11-11 16:05:19 +0100333
Willy Tarreau38e8a1c2020-06-23 10:04:54 +0200334#ifdef DEBUG_FD
335 fdtab[fd].event_count = 0;
336#endif
Willy Tarreau8d5d77e2009-10-18 07:25:52 +0200337 fdinfo[fd].port_range = NULL;
Willy Tarreaudb3b3262012-07-05 23:19:22 +0200338 fdtab[fd].owner = NULL;
Willy Tarreau2f36d902022-07-06 16:23:41 +0200339
Willy Tarreau2c3f9812021-03-24 10:51:32 +0100340 /* perform the close() call last as it's what unlocks the instant reuse
341 * of this FD by any other thread.
342 */
Emeric Brunf41a3f62022-07-01 17:31:25 +0200343 if (!fd_disown)
344 close(fd);
Willy Tarreau4781b152021-04-06 13:53:36 +0200345 _HA_ATOMIC_DEC(&ha_used_fds);
Willy Tarreau2c3f9812021-03-24 10:51:32 +0100346}
347
348/* Deletes an FD from the fdsets. The file descriptor is also closed, possibly
349 * asynchronously. Only the owning thread may do this.
350 */
351void fd_delete(int fd)
352{
Willy Tarreau9aa324d2022-01-31 20:05:02 +0100353 /* This must never happen and would definitely indicate a bug, in
354 * addition to overwriting some unexpected memory areas.
355 */
356 BUG_ON(fd < 0 || fd >= global.maxsock);
357
Willy Tarreau9baff4f2022-07-15 18:56:48 +0200358 /* NOTE: The master when going into reexec mode re-closes all FDs after
359 * they were already dispatched. But we know we didn't start the polling
360 * threads so we can still close them. The masks will probably not match
361 * however so we force the value and erase the refcount if any.
362 */
363 if (unlikely(global.mode & MODE_STARTING))
364 fdtab[fd].refc_tgid = ti->tgid;
365
Willy Tarreau0dc1cc92022-07-06 18:47:38 +0200366 /* the tgid cannot change before a complete close so we should never
367 * face the situation where we try to close an fd that was reassigned.
368 */
369 BUG_ON(fd_tgid(fd) != ti->tgid && !thread_isolated());
370
Willy Tarreau2c3f9812021-03-24 10:51:32 +0100371 /* we must postpone removal of an FD that may currently be in use
Ilya Shipitsinb2be9a12021-04-24 13:25:42 +0500372 * by another thread. This can happen in the following two situations:
Willy Tarreau2c3f9812021-03-24 10:51:32 +0100373 * - after a takeover, the owning thread closes the connection but
374 * the previous one just woke up from the poller and entered
375 * the FD handler iocb. That thread holds an entry in running_mask
376 * and requires removal protection.
377 * - multiple threads are accepting connections on a listener, and
378 * one of them (or even an separate one) decides to unbind the
379 * listener under the listener's lock while other ones still hold
380 * the running bit.
381 * In both situations the FD is marked as unused (thread_mask = 0) and
382 * will not take new bits in its running_mask so we have the guarantee
383 * that the last thread eliminating running_mask is the one allowed to
384 * safely delete the FD. Most of the time it will be the current thread.
385 */
386
Willy Tarreaua707d022022-07-07 08:16:08 +0200387 HA_ATOMIC_OR(&fdtab[fd].running_mask, ti->ltid_bit);
Willy Tarreau2c3f9812021-03-24 10:51:32 +0100388 HA_ATOMIC_STORE(&fdtab[fd].thread_mask, 0);
Willy Tarreaud6e19872022-07-09 15:57:17 +0200389 if (fd_clr_running(fd) == ti->ltid_bit)
Willy Tarreau2c3f9812021-03-24 10:51:32 +0100390 _fd_delete_orphan(fd);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200391}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200392
Willy Tarreau97435892022-04-27 10:50:00 +0200393/* makes the new fd non-blocking and clears all other O_* flags; this is meant
394 * to be used on new FDs. Returns -1 on failure. The result is disguised at the
395 * end because some callers need to be able to ignore it regardless of the libc
396 * attributes.
Willy Tarreaua80e4a32022-04-26 10:18:07 +0200397 */
398int fd_set_nonblock(int fd)
399{
400 int ret = fcntl(fd, F_SETFL, O_NONBLOCK);
401
Willy Tarreau97435892022-04-27 10:50:00 +0200402 return DISGUISE(ret);
Willy Tarreaua80e4a32022-04-26 10:18:07 +0200403}
404
Willy Tarreau97435892022-04-27 10:50:00 +0200405/* sets the close-on-exec flag on fd; returns -1 on failure. The result is
406 * disguised at the end because some callers need to be able to ignore it
407 * regardless of the libc attributes.
408 */
Willy Tarreaua80e4a32022-04-26 10:18:07 +0200409int fd_set_cloexec(int fd)
410{
411 int flags, ret;
412
413 flags = fcntl(fd, F_GETFD);
414 flags |= FD_CLOEXEC;
415 ret = fcntl(fd, F_SETFD, flags);
Willy Tarreau97435892022-04-27 10:50:00 +0200416 return DISGUISE(ret);
Willy Tarreaua80e4a32022-04-26 10:18:07 +0200417}
418
Olivier Houchard88516642020-03-05 18:10:51 +0100419/*
420 * Take over a FD belonging to another thread.
421 * unexpected_conn is the expected owner of the fd.
422 * Returns 0 on success, and -1 on failure.
423 */
424int fd_takeover(int fd, void *expected_owner)
425{
Willy Tarreauf69fea62021-08-03 09:04:32 +0200426 unsigned long old;
Willy Tarreau42973632020-06-18 08:05:15 +0200427
Olivier Houchard88516642020-03-05 18:10:51 +0100428 /* protect ourself against a delete then an insert for the same fd,
429 * if it happens, then the owner will no longer be the expected
430 * connection.
431 */
Willy Tarreauf69fea62021-08-03 09:04:32 +0200432 if (fdtab[fd].owner != expected_owner)
433 return -1;
Willy Tarreauf1cad382020-06-18 08:14:59 +0200434
Willy Tarreauf69fea62021-08-03 09:04:32 +0200435 /* we must be alone to work on this idle FD. If not, it means that its
436 * poller is currently waking up and is about to use it, likely to
437 * close it on shut/error, but maybe also to process any unexpectedly
Willy Tarreau0dc1cc92022-07-06 18:47:38 +0200438 * pending data. It's also possible that the FD was closed and
439 * reassigned to another thread group, so let's be careful.
Willy Tarreauf69fea62021-08-03 09:04:32 +0200440 */
Willy Tarreau0dc1cc92022-07-06 18:47:38 +0200441 if (unlikely(!fd_grab_tgid(fd, ti->tgid)))
442 return -1;
443
Willy Tarreauf69fea62021-08-03 09:04:32 +0200444 old = 0;
Willy Tarreaua707d022022-07-07 08:16:08 +0200445 if (!HA_ATOMIC_CAS(&fdtab[fd].running_mask, &old, ti->ltid_bit)) {
Willy Tarreau0dc1cc92022-07-06 18:47:38 +0200446 fd_drop_tgid(fd);
Willy Tarreauf69fea62021-08-03 09:04:32 +0200447 return -1;
Willy Tarreau0dc1cc92022-07-06 18:47:38 +0200448 }
Willy Tarreauf69fea62021-08-03 09:04:32 +0200449
450 /* success, from now on it's ours */
Willy Tarreau3638d172022-07-07 08:23:03 +0200451 HA_ATOMIC_STORE(&fdtab[fd].thread_mask, ti->ltid_bit);
Willy Tarreauf1cad382020-06-18 08:14:59 +0200452
Olivier Houchardddc874c2020-06-17 20:34:05 +0200453 /* Make sure the FD doesn't have the active bit. It is possible that
454 * the fd is polled by the thread that used to own it, the new thread
455 * is supposed to call subscribe() later, to activate polling.
456 */
Willy Tarreauf69fea62021-08-03 09:04:32 +0200457 fd_stop_recv(fd);
458
459 /* we're done with it */
Willy Tarreaua707d022022-07-07 08:16:08 +0200460 HA_ATOMIC_AND(&fdtab[fd].running_mask, ~ti->ltid_bit);
Willy Tarreau0dc1cc92022-07-06 18:47:38 +0200461
462 /* no more changes planned */
463 fd_drop_tgid(fd);
Willy Tarreauf69fea62021-08-03 09:04:32 +0200464 return 0;
Olivier Houchard88516642020-03-05 18:10:51 +0100465}
466
Willy Tarreaudbe30602019-09-04 13:25:41 +0200467void updt_fd_polling(const int fd)
468{
Willy Tarreaucfdd20a2022-07-15 20:12:31 +0200469 uint tgrp = fd_take_tgid(fd);
470
471 /* closed ? may happen */
472 if (!tgrp)
473 return;
474
475 if (unlikely(tgrp != tgid && tgrp <= MAX_TGROUPS)) {
476 /* Hmmm delivered an update for another group... That may
477 * happen on suspend/resume of a listener for example when
478 * the FD was not even marked for running. Let's broadcast
479 * the update.
480 */
481 unsigned long update_mask = fdtab[fd].update_mask;
482 int thr;
483
484 while (!_HA_ATOMIC_CAS(&fdtab[fd].update_mask, &update_mask, ha_tgroup_info[tgrp - 1].threads_enabled))
485 __ha_cpu_relax();
486
487 fd_add_to_fd_list(&update_list[tgrp - 1], fd);
488
Willy Tarreauc1640f72022-07-19 15:58:00 +0200489 thr = one_among_mask(fdtab[fd].thread_mask & tg->threads_enabled, statistical_prng_range(tg->count));
Willy Tarreaucfdd20a2022-07-15 20:12:31 +0200490 thr += ha_tgroup_info[tgrp - 1].base;
491 wake_thread(thr);
492
493 fd_drop_tgid(fd);
494 return;
495 }
496
497 fd_drop_tgid(fd);
498
Willy Tarreau3638d172022-07-07 08:23:03 +0200499 if (tg->threads_enabled == 1UL || (fdtab[fd].thread_mask & tg->threads_enabled) == ti->ltid_bit) {
Willy Tarreau6d3c5012022-07-05 19:21:06 +0200500 if (HA_ATOMIC_BTS(&fdtab[fd].update_mask, ti->ltid))
Willy Tarreaudbe30602019-09-04 13:25:41 +0200501 return;
502
503 fd_updt[fd_nbupdt++] = fd;
504 } else {
505 unsigned long update_mask = fdtab[fd].update_mask;
506 do {
Willy Tarreau6d3c5012022-07-05 19:21:06 +0200507 if (update_mask == fdtab[fd].thread_mask) // FIXME: this works only on thread-groups 1
Willy Tarreaudbe30602019-09-04 13:25:41 +0200508 return;
Willy Tarreauf0158872020-09-25 12:18:53 +0200509 } while (!_HA_ATOMIC_CAS(&fdtab[fd].update_mask, &update_mask, fdtab[fd].thread_mask));
510
Willy Tarreau35ee7102022-07-08 11:33:43 +0200511 fd_add_to_fd_list(&update_list[tgid - 1], fd);
Willy Tarreauf0158872020-09-25 12:18:53 +0200512
Willy Tarreau3638d172022-07-07 08:23:03 +0200513 if (fd_active(fd) && !(fdtab[fd].thread_mask & ti->ltid_bit)) {
Willy Tarreau555c1922022-06-23 18:31:08 +0200514 /* we need to wake up another thread to handle it immediately, any will fit,
515 * so let's pick a random one so that it doesn't always end up on the same.
516 */
Willy Tarreau3638d172022-07-07 08:23:03 +0200517 int thr = one_among_mask(fdtab[fd].thread_mask & tg->threads_enabled,
Willy Tarreau555c1922022-06-23 18:31:08 +0200518 statistical_prng_range(MAX_THREADS));
Willy Tarreau3638d172022-07-07 08:23:03 +0200519 thr += ha_tgroup_info[tgid - 1].base;
Willy Tarreauf0158872020-09-25 12:18:53 +0200520 wake_thread(thr);
521 }
Willy Tarreaudbe30602019-09-04 13:25:41 +0200522 }
523}
524
Willy Tarreau84c79222021-07-29 16:53:46 +0200525/* Update events seen for FD <fd> and its state if needed. This should be
526 * called by the poller, passing FD_EV_*_{R,W,RW} in <evts>. FD_EV_ERR_*
527 * doesn't need to also pass FD_EV_SHUT_*, it's implied. ERR and SHUT are
Willy Tarreau200bd502021-07-29 16:57:19 +0200528 * allowed to be reported regardless of R/W readiness. Returns one of
529 * FD_UPDT_*.
Willy Tarreau84c79222021-07-29 16:53:46 +0200530 */
Willy Tarreau200bd502021-07-29 16:57:19 +0200531int fd_update_events(int fd, uint evts)
Willy Tarreau84c79222021-07-29 16:53:46 +0200532{
533 unsigned long locked;
534 uint old, new;
535 uint new_flags, must_stop;
Willy Tarreauf69fea62021-08-03 09:04:32 +0200536 ulong rmask, tmask;
Willy Tarreau84c79222021-07-29 16:53:46 +0200537
Willy Tarreaubdcd3252022-06-22 09:19:46 +0200538 _HA_ATOMIC_AND(&th_ctx->flags, ~TH_FL_STUCK); // this thread is still running
Willy Tarreau84c79222021-07-29 16:53:46 +0200539
Willy Tarreau0dc1cc92022-07-06 18:47:38 +0200540 if (unlikely(!fd_grab_tgid(fd, ti->tgid))) {
541 /* the FD changed to another tgid, we can't safely
542 * check it anymore. The bits in the masks are not
543 * ours anymore and we're not allowed to touch them.
544 * Ours have already been cleared and the FD was
545 * closed in between so we can safely leave now.
546 */
547 activity[tid].poll_drop_fd++;
548 return FD_UPDT_CLOSED;
549 }
550
Willy Tarreau84c79222021-07-29 16:53:46 +0200551 /* do nothing if the FD was taken over under us */
Willy Tarreauf69fea62021-08-03 09:04:32 +0200552 do {
553 /* make sure we read a synchronous copy of rmask and tmask
554 * (tmask is only up to date if it reflects all of rmask's
555 * bits).
556 */
557 do {
558 rmask = _HA_ATOMIC_LOAD(&fdtab[fd].running_mask);
559 tmask = _HA_ATOMIC_LOAD(&fdtab[fd].thread_mask);
560 } while (rmask & ~tmask);
561
Willy Tarreau3638d172022-07-07 08:23:03 +0200562 if (!(tmask & ti->ltid_bit)) {
Willy Tarreauf69fea62021-08-03 09:04:32 +0200563 /* a takeover has started */
564 activity[tid].poll_skip_fd++;
Willy Tarreaub1093c62022-07-09 18:55:37 +0200565
566 /* Let the poller know this FD was lost */
Willy Tarreau6d3c5012022-07-05 19:21:06 +0200567 if (!HA_ATOMIC_BTS(&fdtab[fd].update_mask, ti->ltid))
Willy Tarreaub1093c62022-07-09 18:55:37 +0200568 fd_updt[fd_nbupdt++] = fd;
Willy Tarreau0dc1cc92022-07-06 18:47:38 +0200569
570 fd_drop_tgid(fd);
Willy Tarreauf69fea62021-08-03 09:04:32 +0200571 return FD_UPDT_MIGRATED;
572 }
Willy Tarreaua707d022022-07-07 08:16:08 +0200573 } while (!HA_ATOMIC_CAS(&fdtab[fd].running_mask, &rmask, rmask | ti->ltid_bit));
Willy Tarreau84c79222021-07-29 16:53:46 +0200574
Willy Tarreau0dc1cc92022-07-06 18:47:38 +0200575 /* with running we're safe now, we can drop the reference */
576 fd_drop_tgid(fd);
577
Willy Tarreau3638d172022-07-07 08:23:03 +0200578 locked = (tmask != ti->ltid_bit);
Willy Tarreau84c79222021-07-29 16:53:46 +0200579
580 /* OK now we are guaranteed that our thread_mask was present and
581 * that we're allowed to update the FD.
582 */
583
584 new_flags =
585 ((evts & FD_EV_READY_R) ? FD_POLL_IN : 0) |
586 ((evts & FD_EV_READY_W) ? FD_POLL_OUT : 0) |
587 ((evts & FD_EV_SHUT_R) ? FD_POLL_HUP : 0) |
588 ((evts & FD_EV_ERR_RW) ? FD_POLL_ERR : 0);
589
590 /* SHUTW reported while FD was active for writes is an error */
591 if ((fdtab[fd].state & FD_EV_ACTIVE_W) && (evts & FD_EV_SHUT_W))
592 new_flags |= FD_POLL_ERR;
593
594 /* compute the inactive events reported late that must be stopped */
595 must_stop = 0;
596 if (unlikely(!fd_active(fd))) {
597 /* both sides stopped */
598 must_stop = FD_POLL_IN | FD_POLL_OUT;
599 }
600 else if (unlikely(!fd_recv_active(fd) && (evts & (FD_EV_READY_R | FD_EV_SHUT_R | FD_EV_ERR_RW)))) {
601 /* only send remains */
602 must_stop = FD_POLL_IN;
603 }
604 else if (unlikely(!fd_send_active(fd) && (evts & (FD_EV_READY_W | FD_EV_SHUT_W | FD_EV_ERR_RW)))) {
605 /* only recv remains */
606 must_stop = FD_POLL_OUT;
607 }
608
609 if (new_flags & (FD_POLL_IN | FD_POLL_HUP | FD_POLL_ERR))
610 new_flags |= FD_EV_READY_R;
611
612 if (new_flags & (FD_POLL_OUT | FD_POLL_ERR))
613 new_flags |= FD_EV_READY_W;
614
615 old = fdtab[fd].state;
616 new = (old & ~FD_POLL_UPDT_MASK) | new_flags;
617
618 if (unlikely(locked)) {
619 /* Locked FDs (those with more than 2 threads) are atomically updated */
620 while (unlikely(new != old && !_HA_ATOMIC_CAS(&fdtab[fd].state, &old, new)))
621 new = (old & ~FD_POLL_UPDT_MASK) | new_flags;
622 } else {
623 if (new != old)
624 fdtab[fd].state = new;
625 }
626
627 if (fdtab[fd].iocb && fd_active(fd)) {
628 fdtab[fd].iocb(fd);
629 }
630
Willy Tarreau0b51eab2022-07-08 15:36:14 +0200631 /*
632 * We entered iocb with running set and with the valid tgid.
633 * Since then, this is what could have happened:
634 * - another thread tried to close the FD (e.g. timeout task from
635 * another one that owns it). We still have running set, but not
636 * tmask. We must call fd_clr_running() then _fd_delete_orphan()
637 * if we were the last one.
638 *
639 * - the iocb tried to close the FD => bit no more present in running,
640 * nothing to do. If it managed to close it, the poller's ->clo()
641 * has already been called.
642 *
643 * - after we closed, the FD was reassigned to another thread in
644 * another group => running not present, tgid differs, nothing to
645 * do because if it got reassigned it indicates it was already
646 * closed.
647 *
648 * There's no risk of takeover of the valid FD here during this period.
649 * Also if we still have running, immediately after we release it, the
650 * events above might instantly happen due to another thread taking
651 * over.
652 *
653 * As such, the only cases where the FD is still relevant are:
654 * - tgid still set and running still set (most common)
655 * - tgid still valid but running cleared due to fd_delete(): we may
656 * still need to stop polling otherwise we may keep it enabled
657 * while waiting for other threads to close it.
658 * And given that we may need to program a tentative update in case we
659 * don't immediately close, it's easier to grab the tgid during the
660 * whole check.
661 */
662
663 if (!fd_grab_tgid(fd, tgid))
664 return FD_UPDT_CLOSED;
665
666 tmask = _HA_ATOMIC_LOAD(&fdtab[fd].thread_mask);
667
Willy Tarreau84c79222021-07-29 16:53:46 +0200668 /* another thread might have attempted to close this FD in the mean
669 * time (e.g. timeout task) striking on a previous thread and closing.
670 * This is detected by both thread_mask and running_mask being 0 after
Willy Tarreau0b51eab2022-07-08 15:36:14 +0200671 * we remove ourselves last. There is no risk the FD gets reassigned
672 * to a different group since it's not released until the real close()
673 * in _fd_delete_orphan().
Willy Tarreau84c79222021-07-29 16:53:46 +0200674 */
Willy Tarreau0b51eab2022-07-08 15:36:14 +0200675 if (fd_clr_running(fd) == ti->ltid_bit && !tmask) {
676 fd_drop_tgid(fd);
Willy Tarreau84c79222021-07-29 16:53:46 +0200677 _fd_delete_orphan(fd);
Willy Tarreau200bd502021-07-29 16:57:19 +0200678 return FD_UPDT_CLOSED;
Willy Tarreau84c79222021-07-29 16:53:46 +0200679 }
680
681 /* we had to stop this FD and it still must be stopped after the I/O
682 * cb's changes, so let's program an update for this.
683 */
Willy Tarreau6d3c5012022-07-05 19:21:06 +0200684 if (must_stop && !(fdtab[fd].update_mask & ti->ltid_bit)) {
Willy Tarreau84c79222021-07-29 16:53:46 +0200685 if (((must_stop & FD_POLL_IN) && !fd_recv_active(fd)) ||
686 ((must_stop & FD_POLL_OUT) && !fd_send_active(fd)))
Willy Tarreau6d3c5012022-07-05 19:21:06 +0200687 if (!HA_ATOMIC_BTS(&fdtab[fd].update_mask, ti->ltid))
Willy Tarreau84c79222021-07-29 16:53:46 +0200688 fd_updt[fd_nbupdt++] = fd;
689 }
Willy Tarreau200bd502021-07-29 16:57:19 +0200690
Willy Tarreau0b51eab2022-07-08 15:36:14 +0200691 fd_drop_tgid(fd);
Willy Tarreau200bd502021-07-29 16:57:19 +0200692 return FD_UPDT_DONE;
Willy Tarreau84c79222021-07-29 16:53:46 +0200693}
694
Willy Tarreau88c4c142022-07-09 23:19:19 +0200695/* This is used by pollers at boot time to re-register desired events for
696 * all FDs after new pollers have been created. It doesn't do much, it checks
697 * that their thread group matches the one in argument, and that the thread
698 * mask matches at least one of the bits in the mask, and if so, marks the FD
699 * as updated.
700 */
701void fd_reregister_all(int tgrp, ulong mask)
702{
703 int fd;
704
705 for (fd = 0; fd < global.maxsock; fd++) {
706 if (!fdtab[fd].owner)
707 continue;
708
709 /* make sure we don't register other tgroups' FDs. We just
710 * avoid needlessly taking the lock if not needed.
711 */
712 if (!(_HA_ATOMIC_LOAD(&fdtab[fd].thread_mask) & mask) ||
713 !fd_grab_tgid(fd, tgrp))
714 continue; // was not for us anyway
715
716 if (_HA_ATOMIC_LOAD(&fdtab[fd].thread_mask) & mask)
717 updt_fd_polling(fd);
718 fd_drop_tgid(fd);
719 }
720}
721
Willy Tarreau931d8b72019-08-27 11:08:17 +0200722/* Tries to send <npfx> parts from <prefix> followed by <nmsg> parts from <msg>
723 * optionally followed by a newline if <nl> is non-null, to file descriptor
724 * <fd>. The message is sent atomically using writev(). It may be truncated to
725 * <maxlen> bytes if <maxlen> is non-null. There is no distinction between the
726 * two lists, it's just a convenience to help the caller prepend some prefixes
727 * when necessary. It takes the fd's lock to make sure no other thread will
728 * write to the same fd in parallel. Returns the number of bytes sent, or <=0
729 * on failure. A limit to 31 total non-empty segments is enforced. The caller
730 * is responsible for taking care of making the fd non-blocking.
731 */
732ssize_t fd_write_frag_line(int fd, size_t maxlen, const struct ist pfx[], size_t npfx, const struct ist msg[], size_t nmsg, int nl)
733{
734 struct iovec iovec[32];
Willy Tarreau931d8b72019-08-27 11:08:17 +0200735 size_t sent = 0;
736 int vec = 0;
Willy Tarreaudf187872020-06-11 14:25:47 +0200737 int attempts = 0;
Willy Tarreau931d8b72019-08-27 11:08:17 +0200738
739 if (!maxlen)
740 maxlen = ~0;
741
742 /* keep one char for a possible trailing '\n' in any case */
743 maxlen--;
744
745 /* make an iovec from the concatenation of all parts of the original
746 * message. Skip empty fields and truncate the whole message to maxlen,
747 * leaving one spare iovec for the '\n'.
748 */
749 while (vec < (sizeof(iovec) / sizeof(iovec[0]) - 1)) {
750 if (!npfx) {
751 pfx = msg;
752 npfx = nmsg;
753 nmsg = 0;
754 if (!npfx)
755 break;
756 }
757
758 iovec[vec].iov_base = pfx->ptr;
759 iovec[vec].iov_len = MIN(maxlen, pfx->len);
760 maxlen -= iovec[vec].iov_len;
Willy Tarreau931d8b72019-08-27 11:08:17 +0200761 if (iovec[vec].iov_len)
762 vec++;
763 pfx++; npfx--;
764 };
765
766 if (nl) {
767 iovec[vec].iov_base = "\n";
768 iovec[vec].iov_len = 1;
769 vec++;
770 }
771
Willy Tarreaudf187872020-06-11 14:25:47 +0200772 /* make sure we never interleave writes and we never block. This means
773 * we prefer to fail on collision than to block. But we don't want to
774 * lose too many logs so we just perform a few lock attempts then give
775 * up.
776 */
777
Willy Tarreau1673c4a2021-04-07 17:36:57 +0200778 while (HA_ATOMIC_BTS(&fdtab[fd].state, FD_EXCL_SYSCALL_BIT)) {
Willy Tarreaudf187872020-06-11 14:25:47 +0200779 if (++attempts >= 200) {
780 /* so that the caller knows the message couldn't be delivered */
781 sent = -1;
782 errno = EAGAIN;
783 goto leave;
784 }
785 ha_thread_relax();
786 }
787
Willy Tarreau0cc61282021-04-06 17:57:12 +0200788 if (unlikely(!(fdtab[fd].state & FD_INITIALIZED))) {
789 HA_ATOMIC_OR(&fdtab[fd].state, FD_INITIALIZED);
Willy Tarreau7e9776a2019-08-30 14:41:47 +0200790 if (!isatty(fd))
Willy Tarreau38247432022-04-26 10:24:14 +0200791 fd_set_nonblock(fd);
Willy Tarreau7e9776a2019-08-30 14:41:47 +0200792 }
Willy Tarreau931d8b72019-08-27 11:08:17 +0200793 sent = writev(fd, iovec, vec);
Willy Tarreau1673c4a2021-04-07 17:36:57 +0200794 HA_ATOMIC_BTR(&fdtab[fd].state, FD_EXCL_SYSCALL_BIT);
Willy Tarreau931d8b72019-08-27 11:08:17 +0200795
Willy Tarreaudf187872020-06-11 14:25:47 +0200796 leave:
Willy Tarreau931d8b72019-08-27 11:08:17 +0200797 /* sent > 0 if the message was delivered */
798 return sent;
799}
800
Olivier Houchard2292edf2019-02-25 14:26:54 +0100801#if defined(USE_CLOSEFROM)
802void my_closefrom(int start)
803{
804 closefrom(start);
805}
806
Willy Tarreaue5733232019-05-22 19:24:06 +0200807#elif defined(USE_POLL)
Willy Tarreau9188ac62019-02-21 22:12:47 +0100808/* This is a portable implementation of closefrom(). It closes all open file
809 * descriptors starting at <start> and above. It relies on the fact that poll()
810 * will return POLLNVAL for each invalid (hence close) file descriptor passed
811 * in argument in order to skip them. It acts with batches of FDs and will
812 * typically perform one poll() call per 1024 FDs so the overhead is low in
813 * case all FDs have to be closed.
814 */
815void my_closefrom(int start)
816{
817 struct pollfd poll_events[1024];
818 struct rlimit limit;
819 int nbfds, fd, ret, idx;
820 int step, next;
821
822 if (getrlimit(RLIMIT_NOFILE, &limit) == 0)
823 step = nbfds = limit.rlim_cur;
824 else
825 step = nbfds = 0;
826
827 if (nbfds <= 0) {
828 /* set safe limit */
829 nbfds = 1024;
830 step = 256;
831 }
832
833 if (step > sizeof(poll_events) / sizeof(poll_events[0]))
834 step = sizeof(poll_events) / sizeof(poll_events[0]);
835
836 while (start < nbfds) {
837 next = (start / step + 1) * step;
838
839 for (fd = start; fd < next && fd < nbfds; fd++) {
840 poll_events[fd - start].fd = fd;
841 poll_events[fd - start].events = 0;
842 }
843
844 do {
845 ret = poll(poll_events, fd - start, 0);
846 if (ret >= 0)
847 break;
Willy Tarreauacef5e22022-04-25 20:32:15 +0200848 } while (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR || errno == ENOMEM);
Willy Tarreau9188ac62019-02-21 22:12:47 +0100849
Willy Tarreaub8e602c2019-02-22 09:07:42 +0100850 if (ret)
851 ret = fd - start;
852
Willy Tarreau9188ac62019-02-21 22:12:47 +0100853 for (idx = 0; idx < ret; idx++) {
854 if (poll_events[idx].revents & POLLNVAL)
855 continue; /* already closed */
856
857 fd = poll_events[idx].fd;
858 close(fd);
859 }
860 start = next;
861 }
862}
863
Willy Tarreaue5733232019-05-22 19:24:06 +0200864#else // defined(USE_POLL)
Willy Tarreau9188ac62019-02-21 22:12:47 +0100865
Willy Tarreau2d7f81b2019-02-21 22:19:17 +0100866/* This is a portable implementation of closefrom(). It closes all open file
867 * descriptors starting at <start> and above. This is a naive version for use
868 * when the operating system provides no alternative.
869 */
870void my_closefrom(int start)
871{
872 struct rlimit limit;
873 int nbfds;
874
875 if (getrlimit(RLIMIT_NOFILE, &limit) == 0)
876 nbfds = limit.rlim_cur;
877 else
878 nbfds = 0;
879
880 if (nbfds <= 0)
881 nbfds = 1024; /* safe limit */
882
883 while (start < nbfds)
884 close(start++);
885}
Willy Tarreaue5733232019-05-22 19:24:06 +0200886#endif // defined(USE_POLL)
Willy Tarreau2d7f81b2019-02-21 22:19:17 +0100887
Willy Tarreau922a9072022-09-22 16:08:47 +0200888/* Sets the RLIMIT_NOFILE setting to <new_limit> and returns the previous one
889 * in <old_limit> if the pointer is not NULL, even if set_rlimit() fails. The
890 * two pointers may point to the same variable as the copy happens after
891 * setting the new value. The value is only changed if at least one of the new
892 * limits is strictly higher than the current one, otherwise returns 0 without
893 * changing anything. The getrlimit() or setrlimit() syscall return value is
894 * returned and errno is preserved.
895 */
896int raise_rlim_nofile(struct rlimit *old_limit, struct rlimit *new_limit)
897{
898 struct rlimit limit = { };
899 int ret = 0;
900
901 ret = getrlimit(RLIMIT_NOFILE, &limit);
902
903 if (ret == 0 &&
904 (limit.rlim_max < new_limit->rlim_max ||
905 limit.rlim_cur < new_limit->rlim_cur)) {
906 ret = setrlimit(RLIMIT_NOFILE, new_limit);
907 }
908
909 if (old_limit)
910 *old_limit = limit;
911
912 return ret;
913}
914
Willy Tarreaub63888c2021-10-06 19:55:29 +0200915/* Computes the bounded poll() timeout based on the next expiration timer <next>
916 * by bounding it to MAX_DELAY_MS. <next> may equal TICK_ETERNITY. The pollers
917 * just needs to call this function right before polling to get their timeout
918 * value. Timeouts that are already expired (possibly due to a pending event)
919 * are accounted for in activity.poll_exp.
920 */
921int compute_poll_timeout(int next)
922{
923 int wait_time;
924
925 if (!tick_isset(next))
926 wait_time = MAX_DELAY_MS;
927 else if (tick_is_expired(next, now_ms)) {
928 activity[tid].poll_exp++;
929 wait_time = 0;
930 }
931 else {
932 wait_time = TICKS_TO_MS(tick_remain(now_ms, next)) + 1;
933 if (wait_time > MAX_DELAY_MS)
934 wait_time = MAX_DELAY_MS;
935 }
936 return wait_time;
937}
938
Willy Tarreau058b2c12022-06-22 15:21:34 +0200939/* Handle the return of the poller, which consists in calculating the idle
940 * time, saving a few clocks, marking the thread harmful again etc. All that
941 * is some boring stuff that all pollers have to do anyway.
942 */
943void fd_leaving_poll(int wait_time, int status)
944{
945 clock_leaving_poll(wait_time, status);
946
947 thread_harmless_end();
948 thread_idle_end();
949
Willy Tarreaue7475c82022-06-20 09:23:24 +0200950 _HA_ATOMIC_AND(&th_ctx->flags, ~TH_FL_SLEEPING);
Willy Tarreau058b2c12022-06-22 15:21:34 +0200951}
952
Willy Tarreau4f60f162007-04-08 16:39:58 +0200953/* disable the specified poller */
954void disable_poller(const char *poller_name)
955{
956 int p;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200957
Willy Tarreau4f60f162007-04-08 16:39:58 +0200958 for (p = 0; p < nbpollers; p++)
959 if (strcmp(pollers[p].name, poller_name) == 0)
960 pollers[p].pref = 0;
961}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200962
Olivier Houchard79321b92018-07-26 17:55:11 +0200963void poller_pipe_io_handler(int fd)
964{
965 char buf[1024];
966 /* Flush the pipe */
967 while (read(fd, buf, sizeof(buf)) > 0);
968 fd_cant_recv(fd);
969}
970
Willy Tarreau082b6282019-05-22 14:42:12 +0200971/* allocate the per-thread fd_updt thus needs to be called early after
972 * thread creation.
973 */
974static int alloc_pollers_per_thread()
975{
976 fd_updt = calloc(global.maxsock, sizeof(*fd_updt));
977 return fd_updt != NULL;
978}
979
980/* Initialize the pollers per thread.*/
Christopher Fauletd4604ad2017-05-29 10:40:41 +0200981static int init_pollers_per_thread()
982{
Olivier Houchard79321b92018-07-26 17:55:11 +0200983 int mypipe[2];
Willy Tarreau082b6282019-05-22 14:42:12 +0200984
985 if (pipe(mypipe) < 0)
Olivier Houchard79321b92018-07-26 17:55:11 +0200986 return 0;
Willy Tarreau082b6282019-05-22 14:42:12 +0200987
Olivier Houchard79321b92018-07-26 17:55:11 +0200988 poller_rd_pipe = mypipe[0];
989 poller_wr_pipe[tid] = mypipe[1];
Willy Tarreau38247432022-04-26 10:24:14 +0200990 fd_set_nonblock(poller_rd_pipe);
Willy Tarreau27a32452022-07-07 08:29:00 +0200991 fd_insert(poller_rd_pipe, poller_pipe_io_handler, poller_pipe_io_handler, tgid, ti->ltid_bit);
992 fd_insert(poller_wr_pipe[tid], poller_pipe_io_handler, poller_pipe_io_handler, tgid, ti->ltid_bit);
Olivier Houchard79321b92018-07-26 17:55:11 +0200993 fd_want_recv(poller_rd_pipe);
Willy Tarreau3a6af1e2022-01-24 20:33:09 +0100994 fd_stop_both(poller_wr_pipe[tid]);
Christopher Fauletd4604ad2017-05-29 10:40:41 +0200995 return 1;
996}
997
998/* Deinitialize the pollers per thread */
999static void deinit_pollers_per_thread()
1000{
William Lallemand808e1b72018-12-15 22:34:31 +01001001 /* rd and wr are init at the same place, but only rd is init to -1, so
1002 we rely to rd to close. */
1003 if (poller_rd_pipe > -1) {
Willy Tarreaue6ca4352022-08-10 17:08:17 +02001004 fd_delete(poller_rd_pipe);
William Lallemand808e1b72018-12-15 22:34:31 +01001005 poller_rd_pipe = -1;
Willy Tarreaue6ca4352022-08-10 17:08:17 +02001006 fd_delete(poller_wr_pipe[tid]);
William Lallemand808e1b72018-12-15 22:34:31 +01001007 poller_wr_pipe[tid] = -1;
1008 }
Christopher Fauletd4604ad2017-05-29 10:40:41 +02001009}
1010
Willy Tarreau082b6282019-05-22 14:42:12 +02001011/* Release the pollers per thread, to be called late */
1012static void free_pollers_per_thread()
1013{
Willy Tarreaub9831452022-07-26 19:06:17 +02001014 fd_nbupdt = 0;
Willy Tarreau61cfdf42021-02-20 10:46:51 +01001015 ha_free(&fd_updt);
Willy Tarreau082b6282019-05-22 14:42:12 +02001016}
1017
Willy Tarreaubaaee002006-06-26 02:48:02 +02001018/*
Willy Tarreau4f60f162007-04-08 16:39:58 +02001019 * Initialize the pollers till the best one is found.
1020 * If none works, returns 0, otherwise 1.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001021 */
Willy Tarreau4f60f162007-04-08 16:39:58 +02001022int init_pollers()
Willy Tarreaubaaee002006-06-26 02:48:02 +02001023{
Willy Tarreau4f60f162007-04-08 16:39:58 +02001024 int p;
1025 struct poller *bp;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001026
Willy Tarreau97ea9c42022-01-27 16:10:48 +01001027 if ((fdtab_addr = calloc(global.maxsock, sizeof(*fdtab) + 64)) == NULL) {
Willy Tarreau7c9f7562020-10-13 15:45:07 +02001028 ha_alert("Not enough memory to allocate %d entries for fdtab!\n", global.maxsock);
Christopher Faulet63fe6522017-08-31 17:52:09 +02001029 goto fail_tab;
Willy Tarreau7c9f7562020-10-13 15:45:07 +02001030 }
Christopher Faulet63fe6522017-08-31 17:52:09 +02001031
Willy Tarreau97ea9c42022-01-27 16:10:48 +01001032 /* always provide an aligned fdtab */
1033 fdtab = (struct fdtab*)((((size_t)fdtab_addr) + 63) & -(size_t)64);
1034
Willy Tarreau7c9f7562020-10-13 15:45:07 +02001035 if ((polled_mask = calloc(global.maxsock, sizeof(*polled_mask))) == NULL) {
1036 ha_alert("Not enough memory to allocate %d entries for polled_mask!\n", global.maxsock);
Olivier Houchardcb92f5c2018-04-26 14:23:07 +02001037 goto fail_polledmask;
Willy Tarreau7c9f7562020-10-13 15:45:07 +02001038 }
Uman Shahzadda7eeed2019-01-17 08:21:39 +00001039
Willy Tarreau7c9f7562020-10-13 15:45:07 +02001040 if ((fdinfo = calloc(global.maxsock, sizeof(*fdinfo))) == NULL) {
1041 ha_alert("Not enough memory to allocate %d entries for fdinfo!\n", global.maxsock);
Christopher Faulet63fe6522017-08-31 17:52:09 +02001042 goto fail_info;
Willy Tarreau7c9f7562020-10-13 15:45:07 +02001043 }
Christopher Faulet63fe6522017-08-31 17:52:09 +02001044
Willy Tarreau35ee7102022-07-08 11:33:43 +02001045 for (p = 0; p < MAX_TGROUPS; p++)
1046 update_list[p].first = update_list[p].last = -1;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001047
Olivier Houchard4815c8c2018-01-24 18:17:56 +01001048 for (p = 0; p < global.maxsock; p++) {
Olivier Houchard4815c8c2018-01-24 18:17:56 +01001049 /* Mark the fd as out of the fd cache */
Olivier Houchard6b96f722018-04-25 16:58:25 +02001050 fdtab[p].update.next = -3;
Olivier Houchard4815c8c2018-01-24 18:17:56 +01001051 }
Christopher Fauletd4604ad2017-05-29 10:40:41 +02001052
Willy Tarreau4f60f162007-04-08 16:39:58 +02001053 do {
1054 bp = NULL;
1055 for (p = 0; p < nbpollers; p++)
1056 if (!bp || (pollers[p].pref > bp->pref))
1057 bp = &pollers[p];
Willy Tarreaubaaee002006-06-26 02:48:02 +02001058
Willy Tarreau4f60f162007-04-08 16:39:58 +02001059 if (!bp || bp->pref == 0)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001060 break;
1061
Willy Tarreau4f60f162007-04-08 16:39:58 +02001062 if (bp->init(bp)) {
1063 memcpy(&cur_poller, bp, sizeof(*bp));
1064 return 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001065 }
Willy Tarreau4f60f162007-04-08 16:39:58 +02001066 } while (!bp || bp->pref == 0);
Willy Tarreau7be79a42012-11-11 15:02:54 +01001067
Christopher Faulet63fe6522017-08-31 17:52:09 +02001068 free(fdinfo);
1069 fail_info:
Olivier Houchardcb92f5c2018-04-26 14:23:07 +02001070 free(polled_mask);
1071 fail_polledmask:
Willy Tarreau97ea9c42022-01-27 16:10:48 +01001072 free(fdtab_addr);
Uman Shahzadda7eeed2019-01-17 08:21:39 +00001073 fail_tab:
Willy Tarreau7be79a42012-11-11 15:02:54 +01001074 return 0;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001075}
1076
Willy Tarreaubaaee002006-06-26 02:48:02 +02001077/*
Krzysztof Piotr Oledzkia643baf2008-05-29 23:53:44 +02001078 * Deinitialize the pollers.
1079 */
1080void deinit_pollers() {
1081
1082 struct poller *bp;
1083 int p;
1084
1085 for (p = 0; p < nbpollers; p++) {
1086 bp = &pollers[p];
1087
1088 if (bp && bp->pref)
1089 bp->term(bp);
1090 }
Christopher Fauletd4604ad2017-05-29 10:40:41 +02001091
Willy Tarreau61cfdf42021-02-20 10:46:51 +01001092 ha_free(&fdinfo);
Willy Tarreau97ea9c42022-01-27 16:10:48 +01001093 ha_free(&fdtab_addr);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01001094 ha_free(&polled_mask);
Krzysztof Piotr Oledzkia643baf2008-05-29 23:53:44 +02001095}
1096
1097/*
Willy Tarreau2ff76222007-04-09 19:29:56 +02001098 * Lists the known pollers on <out>.
1099 * Should be performed only before initialization.
1100 */
1101int list_pollers(FILE *out)
1102{
1103 int p;
1104 int last, next;
1105 int usable;
1106 struct poller *bp;
1107
1108 fprintf(out, "Available polling systems :\n");
1109
1110 usable = 0;
1111 bp = NULL;
1112 last = next = -1;
1113 while (1) {
1114 for (p = 0; p < nbpollers; p++) {
Willy Tarreau2ff76222007-04-09 19:29:56 +02001115 if ((next < 0 || pollers[p].pref > next)
Willy Tarreaue79c3b22010-11-19 10:20:36 +01001116 && (last < 0 || pollers[p].pref < last)) {
Willy Tarreau2ff76222007-04-09 19:29:56 +02001117 next = pollers[p].pref;
Willy Tarreaue79c3b22010-11-19 10:20:36 +01001118 if (!bp || (pollers[p].pref > bp->pref))
1119 bp = &pollers[p];
1120 }
Willy Tarreau2ff76222007-04-09 19:29:56 +02001121 }
1122
1123 if (next == -1)
1124 break;
1125
1126 for (p = 0; p < nbpollers; p++) {
1127 if (pollers[p].pref == next) {
1128 fprintf(out, " %10s : ", pollers[p].name);
1129 if (pollers[p].pref == 0)
1130 fprintf(out, "disabled, ");
1131 else
1132 fprintf(out, "pref=%3d, ", pollers[p].pref);
1133 if (pollers[p].test(&pollers[p])) {
1134 fprintf(out, " test result OK");
1135 if (next > 0)
1136 usable++;
Willy Tarreaue79c3b22010-11-19 10:20:36 +01001137 } else {
Willy Tarreau2ff76222007-04-09 19:29:56 +02001138 fprintf(out, " test result FAILED");
Willy Tarreaue79c3b22010-11-19 10:20:36 +01001139 if (bp == &pollers[p])
1140 bp = NULL;
1141 }
Willy Tarreau2ff76222007-04-09 19:29:56 +02001142 fprintf(out, "\n");
1143 }
1144 }
1145 last = next;
1146 next = -1;
1147 };
1148 fprintf(out, "Total: %d (%d usable), will use %s.\n", nbpollers, usable, bp ? bp->name : "none");
1149 return 0;
1150}
1151
1152/*
1153 * Some pollers may lose their connection after a fork(). It may be necessary
1154 * to create initialize part of them again. Returns 0 in case of failure,
1155 * otherwise 1. The fork() function may be NULL if unused. In case of error,
1156 * the the current poller is destroyed and the caller is responsible for trying
1157 * another one by calling init_pollers() again.
1158 */
1159int fork_poller()
1160{
Conrad Hoffmann041751c2014-05-20 14:28:24 +02001161 int fd;
Willy Tarreauce036bc2018-01-29 14:58:02 +01001162 for (fd = 0; fd < global.maxsock; fd++) {
Conrad Hoffmann041751c2014-05-20 14:28:24 +02001163 if (fdtab[fd].owner) {
Willy Tarreau030dae12021-04-06 17:53:33 +02001164 HA_ATOMIC_OR(&fdtab[fd].state, FD_CLONED);
Conrad Hoffmann041751c2014-05-20 14:28:24 +02001165 }
1166 }
1167
Willy Tarreau2ff76222007-04-09 19:29:56 +02001168 if (cur_poller.fork) {
1169 if (cur_poller.fork(&cur_poller))
1170 return 1;
1171 cur_poller.term(&cur_poller);
1172 return 0;
1173 }
1174 return 1;
1175}
1176
Willy Tarreaubc52bec2020-06-18 08:58:47 +02001177/* config parser for global "tune.fd.edge-triggered", accepts "on" or "off" */
1178static int cfg_parse_tune_fd_edge_triggered(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +01001179 const struct proxy *defpx, const char *file, int line,
Willy Tarreaubc52bec2020-06-18 08:58:47 +02001180 char **err)
1181{
1182 if (too_many_args(1, args, err, NULL))
1183 return -1;
1184
1185 if (strcmp(args[1], "on") == 0)
1186 global.tune.options |= GTUNE_FD_ET;
1187 else if (strcmp(args[1], "off") == 0)
1188 global.tune.options &= ~GTUNE_FD_ET;
1189 else {
1190 memprintf(err, "'%s' expects either 'on' or 'off' but got '%s'.", args[0], args[1]);
1191 return -1;
1192 }
1193 return 0;
1194}
1195
1196/* config keyword parsers */
1197static struct cfg_kw_list cfg_kws = {ILH, {
Willy Tarreau9eec7e22021-05-08 11:06:32 +02001198 { CFG_GLOBAL, "tune.fd.edge-triggered", cfg_parse_tune_fd_edge_triggered, KWF_EXPERIMENTAL },
Willy Tarreaubc52bec2020-06-18 08:58:47 +02001199 { 0, NULL, NULL }
1200}};
1201
1202INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
1203
Willy Tarreau082b6282019-05-22 14:42:12 +02001204REGISTER_PER_THREAD_ALLOC(alloc_pollers_per_thread);
Willy Tarreau172f5ce2018-11-26 11:21:50 +01001205REGISTER_PER_THREAD_INIT(init_pollers_per_thread);
1206REGISTER_PER_THREAD_DEINIT(deinit_pollers_per_thread);
Willy Tarreau082b6282019-05-22 14:42:12 +02001207REGISTER_PER_THREAD_FREE(free_pollers_per_thread);
Willy Tarreau172f5ce2018-11-26 11:21:50 +01001208
Willy Tarreau2ff76222007-04-09 19:29:56 +02001209/*
Willy Tarreaubaaee002006-06-26 02:48:02 +02001210 * Local variables:
1211 * c-indent-level: 8
1212 * c-basic-offset: 8
1213 * End:
1214 */