File: | lwan-thread.c |
Warning: | line 865, column 31 Array subscript is undefined |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | /* | |||
2 | * lwan - simple web server | |||
3 | * Copyright (c) 2012, 2013 Leandro A. F. Pereira <leandro@hardinfo.org> | |||
4 | * | |||
5 | * This program is free software; you can redistribute it and/or | |||
6 | * modify it under the terms of the GNU General Public License | |||
7 | * as published by the Free Software Foundation; either version 2 | |||
8 | * of the License, or any later version. | |||
9 | * | |||
10 | * This program is distributed in the hope that it will be useful, | |||
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of | |||
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |||
13 | * GNU General Public License for more details. | |||
14 | * | |||
15 | * You should have received a copy of the GNU General Public License | |||
16 | * along with this program; if not, write to the Free Software | |||
17 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, | |||
18 | * USA. | |||
19 | */ | |||
20 | ||||
21 | #define _GNU_SOURCE | |||
22 | #include <assert.h> | |||
23 | #include <errno(*__errno_location ()).h> | |||
24 | #include <fcntl.h> | |||
25 | #include <pthread.h> | |||
26 | #include <sched.h> | |||
27 | #include <stdlib.h> | |||
28 | #include <string.h> | |||
29 | #include <sys/epoll.h> | |||
30 | #include <sys/ioctl.h> | |||
31 | #include <sys/socket.h> | |||
32 | #include <unistd.h> | |||
33 | ||||
34 | #if defined(HAVE_SO_ATTACH_REUSEPORT_CBPF) | |||
35 | #include <linux1/filter.h> | |||
36 | #endif | |||
37 | ||||
38 | #include "lwan-private.h" | |||
39 | #include "lwan-tq.h" | |||
40 | #include "list.h" | |||
41 | ||||
42 | static void lwan_strbuf_free_defer(void *data) | |||
43 | { | |||
44 | lwan_strbuf_free((struct lwan_strbuf *)data); | |||
45 | } | |||
46 | ||||
47 | static void graceful_close(struct lwan *l, | |||
48 | struct lwan_connection *conn, | |||
49 | char buffer[static DEFAULT_BUFFER_SIZE4096]) | |||
50 | { | |||
51 | int fd = lwan_connection_get_fd(l, conn); | |||
52 | ||||
53 | while (TIOCOUTQ0x5411) { | |||
54 | /* This ioctl isn't probably doing what it says on the tin; the details | |||
55 | * are subtle, but it seems to do the trick to allow gracefully closing | |||
56 | * the connection in some cases with minimal system calls. */ | |||
57 | int bytes_waiting; | |||
58 | int r = ioctl(fd, TIOCOUTQ0x5411, &bytes_waiting); | |||
59 | ||||
60 | if (!r && !bytes_waiting) /* See note about close(2) below. */ | |||
61 | return; | |||
62 | if (r < 0 && errno(*__errno_location ()) == EINTR4) | |||
63 | continue; | |||
64 | ||||
65 | break; | |||
66 | } | |||
67 | ||||
68 | if (UNLIKELY(shutdown(fd, SHUT_WR) < 0)__builtin_expect(((shutdown(fd, SHUT_WR) < 0)), (0))) { | |||
69 | if (UNLIKELY(errno == ENOTCONN)__builtin_expect((((*__errno_location ()) == 107)), (0))) | |||
70 | return; | |||
71 | } | |||
72 | ||||
73 | for (int tries = 0; tries < 20; tries++) { | |||
74 | ssize_t r = recv(fd, buffer, DEFAULT_BUFFER_SIZE4096, 0); | |||
75 | ||||
76 | if (!r) | |||
77 | break; | |||
78 | ||||
79 | if (r < 0) { | |||
80 | switch (errno(*__errno_location ())) { | |||
81 | case EAGAIN11: | |||
82 | break; | |||
83 | case EINTR4: | |||
84 | continue; | |||
85 | default: | |||
86 | return; | |||
87 | } | |||
88 | } | |||
89 | ||||
90 | coro_yield(conn->coro, CONN_CORO_WANT_READ); | |||
91 | } | |||
92 | ||||
93 | /* close(2) will be called when the coroutine yields with CONN_CORO_ABORT */ | |||
94 | } | |||
95 | ||||
96 | static __thread __uint128_t lehmer64_state; | |||
97 | ||||
98 | static void lwan_random_seed_prng_for_thread(uint64_t fallback_seed) | |||
99 | { | |||
100 | if (lwan_getentropy(&lehmer64_state, sizeof(lehmer64_state), 0) < 0) { | |||
101 | lwan_status_warning("Couldn't get proper entropy for PRNG, using fallback seed")lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 101, __FUNCTION__, "Couldn't get proper entropy for PRNG, using fallback seed" ); | |||
102 | lehmer64_state |= fallback_seed; | |||
103 | lehmer64_state <<= 32; | |||
104 | lehmer64_state |= fallback_seed; | |||
105 | } | |||
106 | } | |||
107 | ||||
108 | uint64_t lwan_random_uint64() | |||
109 | { | |||
110 | /* https://lemire.me/blog/2019/03/19/the-fastest-conventional-random-number-generator-that-can-pass-big-crush/ */ | |||
111 | lehmer64_state *= 0xda942042e4dd58b5ull; | |||
112 | return (uint64_t)(lehmer64_state >> 64); | |||
113 | } | |||
114 | ||||
115 | __attribute__((noreturn)) static int process_request_coro(struct coro *coro, | |||
116 | void *data) | |||
117 | { | |||
118 | /* NOTE: This function should not return; coro_yield should be used | |||
119 | * instead. This ensures the storage for `strbuf` is alive when the | |||
120 | * coroutine ends and lwan_strbuf_free() is called. */ | |||
121 | struct lwan_connection *conn = data; | |||
122 | struct lwan *lwan = conn->thread->lwan; | |||
123 | int fd = lwan_connection_get_fd(lwan, conn); | |||
124 | enum lwan_request_flags flags = lwan->config.request_flags; | |||
125 | struct lwan_strbuf strbuf = LWAN_STRBUF_STATIC_INIT(struct lwan_strbuf) { .buffer = "" }; | |||
126 | char request_buffer[DEFAULT_BUFFER_SIZE4096]; | |||
127 | struct lwan_value buffer = {.value = request_buffer, .len = 0}; | |||
128 | char *next_request = NULL((void*)0); | |||
129 | char *header_start[N_HEADER_START64]; | |||
130 | struct lwan_proxy proxy; | |||
131 | const int error_when_n_packets = lwan_calculate_n_packets(DEFAULT_BUFFER_SIZE4096); | |||
132 | ||||
133 | coro_defer(coro, lwan_strbuf_free_defer, &strbuf); | |||
134 | ||||
135 | const size_t init_gen = 1; /* 1 call to coro_defer() */ | |||
136 | assert(init_gen == coro_deferred_get_generation(coro))((void) sizeof ((init_gen == coro_deferred_get_generation(coro )) ? 1 : 0), __extension__ ({ if (init_gen == coro_deferred_get_generation (coro)) ; else __assert_fail ("init_gen == coro_deferred_get_generation(coro)" , "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 136, __extension__ __PRETTY_FUNCTION__); })); | |||
137 | ||||
138 | while (true1) { | |||
139 | struct lwan_request_parser_helper helper = { | |||
140 | .buffer = &buffer, | |||
141 | .next_request = next_request, | |||
142 | .error_when_n_packets = error_when_n_packets, | |||
143 | .header_start = header_start, | |||
144 | }; | |||
145 | struct lwan_request request = {.conn = conn, | |||
146 | .global_response_headers = &lwan->headers, | |||
147 | .fd = fd, | |||
148 | .request_id = lwan_random_uint64(), | |||
149 | .response = {.buffer = &strbuf}, | |||
150 | .flags = flags, | |||
151 | .proxy = &proxy, | |||
152 | .helper = &helper}; | |||
153 | ||||
154 | lwan_process_request(lwan, &request); | |||
155 | ||||
156 | /* Run the deferred instructions now (except those used to initialize | |||
157 | * the coroutine), so that if the connection is gracefully closed, | |||
158 | * the storage for ``helper'' is still there. */ | |||
159 | coro_deferred_run(coro, init_gen); | |||
160 | ||||
161 | if (UNLIKELY(!(conn->flags & CONN_IS_KEEP_ALIVE))__builtin_expect(((!(conn->flags & CONN_IS_KEEP_ALIVE) )), (0))) { | |||
162 | graceful_close(lwan, conn, request_buffer); | |||
163 | break; | |||
164 | } | |||
165 | ||||
166 | if (next_request && *next_request) { | |||
167 | conn->flags |= CONN_CORK; | |||
168 | ||||
169 | if (!(conn->flags & CONN_EVENTS_WRITE)) | |||
170 | coro_yield(coro, CONN_CORO_WANT_WRITE); | |||
171 | } else { | |||
172 | conn->flags &= ~CONN_CORK; | |||
173 | coro_yield(coro, CONN_CORO_WANT_READ); | |||
174 | } | |||
175 | ||||
176 | /* Ensure string buffer is reset between requests, and that the backing | |||
177 | * store isn't over 2KB. */ | |||
178 | lwan_strbuf_reset_trim(&strbuf, 2048); | |||
179 | ||||
180 | /* Only allow flags from config. */ | |||
181 | flags = request.flags & (REQUEST_PROXIED | REQUEST_ALLOW_CORS); | |||
182 | next_request = helper.next_request; | |||
183 | } | |||
184 | ||||
185 | coro_yield(coro, CONN_CORO_ABORT); | |||
186 | __builtin_unreachable(); | |||
187 | } | |||
188 | ||||
189 | static ALWAYS_INLINEinline __attribute__((always_inline)) uint32_t | |||
190 | conn_flags_to_epoll_events(enum lwan_connection_flags flags) | |||
191 | { | |||
192 | static const uint32_t map[CONN_EVENTS_MASK + 1] = { | |||
193 | [0 /* Suspended (timer or await) */] = EPOLLRDHUPEPOLLRDHUP, | |||
194 | [CONN_EVENTS_WRITE] = EPOLLOUTEPOLLOUT | EPOLLRDHUPEPOLLRDHUP, | |||
195 | [CONN_EVENTS_READ] = EPOLLINEPOLLIN | EPOLLRDHUPEPOLLRDHUP, | |||
196 | [CONN_EVENTS_READ_WRITE] = EPOLLINEPOLLIN | EPOLLOUTEPOLLOUT | EPOLLRDHUPEPOLLRDHUP, | |||
197 | }; | |||
198 | ||||
199 | return map[flags & CONN_EVENTS_MASK]; | |||
200 | } | |||
201 | ||||
202 | static void update_epoll_flags(int fd, | |||
203 | struct lwan_connection *conn, | |||
204 | int epoll_fd, | |||
205 | enum lwan_connection_coro_yield yield_result) | |||
206 | { | |||
207 | static const enum lwan_connection_flags or_mask[CONN_CORO_MAX] = { | |||
208 | [CONN_CORO_YIELD] = 0, | |||
209 | ||||
210 | [CONN_CORO_WANT_READ_WRITE] = CONN_EVENTS_READ_WRITE, | |||
211 | [CONN_CORO_WANT_READ] = CONN_EVENTS_READ, | |||
212 | [CONN_CORO_WANT_WRITE] = CONN_EVENTS_WRITE, | |||
213 | ||||
214 | /* While the coro is suspended, we're not interested in either EPOLLIN | |||
215 | * or EPOLLOUT events. We still want to track this fd in epoll, though, | |||
216 | * so unset both so that only EPOLLRDHUP (plus the implicitly-set ones) | |||
217 | * are set. */ | |||
218 | [CONN_CORO_SUSPEND] = CONN_SUSPENDED, | |||
219 | ||||
220 | /* Ideally, when suspending a coroutine, the current flags&CONN_EVENTS_MASK | |||
221 | * would have to be stored and restored -- however, resuming as if the | |||
222 | * client coroutine is interested in a write event always guarantees that | |||
223 | * they'll be resumed as they're TCP sockets. There's a good chance that | |||
224 | * trying to read from a socket after resuming a coroutine will succeed, | |||
225 | * but if it doesn't because read() returns -EAGAIN, the I/O wrappers will | |||
226 | * yield with CONN_CORO_WANT_READ anyway. */ | |||
227 | [CONN_CORO_RESUME] = CONN_EVENTS_WRITE, | |||
228 | }; | |||
229 | static const enum lwan_connection_flags and_mask[CONN_CORO_MAX] = { | |||
230 | [CONN_CORO_YIELD] = ~0, | |||
231 | ||||
232 | [CONN_CORO_WANT_READ_WRITE] = ~0, | |||
233 | [CONN_CORO_WANT_READ] = ~CONN_EVENTS_WRITE, | |||
234 | [CONN_CORO_WANT_WRITE] = ~CONN_EVENTS_READ, | |||
235 | ||||
236 | [CONN_CORO_SUSPEND] = ~CONN_EVENTS_READ_WRITE, | |||
237 | [CONN_CORO_RESUME] = ~CONN_SUSPENDED, | |||
238 | }; | |||
239 | enum lwan_connection_flags prev_flags = conn->flags; | |||
240 | ||||
241 | conn->flags |= or_mask[yield_result]; | |||
242 | conn->flags &= and_mask[yield_result]; | |||
243 | ||||
244 | if (conn->flags == prev_flags) | |||
245 | return; | |||
246 | ||||
247 | struct epoll_event event = { | |||
248 | .events = conn_flags_to_epoll_events(conn->flags), | |||
249 | .data.ptr = conn, | |||
250 | }; | |||
251 | ||||
252 | if (UNLIKELY(epoll_ctl(epoll_fd, EPOLL_CTL_MOD, fd, &event) < 0)__builtin_expect(((epoll_ctl(epoll_fd, 3, fd, &event) < 0)), (0))) | |||
253 | lwan_status_perror("epoll_ctl")lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 253, __FUNCTION__, "epoll_ctl"); | |||
254 | } | |||
255 | ||||
256 | static void clear_async_await_flag(void *data) | |||
257 | { | |||
258 | struct lwan_connection *async_fd_conn = data; | |||
259 | ||||
260 | async_fd_conn->flags &= ~CONN_ASYNC_AWAIT; | |||
261 | } | |||
262 | ||||
263 | static enum lwan_connection_coro_yield | |||
264 | resume_async(struct timeout_queue *tq, | |||
265 | enum lwan_connection_coro_yield yield_result, | |||
266 | int64_t from_coro, | |||
267 | struct lwan_connection *conn, | |||
268 | int epoll_fd) | |||
269 | { | |||
270 | static const enum lwan_connection_flags to_connection_flags[] = { | |||
271 | [CONN_CORO_ASYNC_AWAIT_READ] = CONN_EVENTS_READ, | |||
272 | [CONN_CORO_ASYNC_AWAIT_WRITE] = CONN_EVENTS_WRITE, | |||
273 | [CONN_CORO_ASYNC_AWAIT_READ_WRITE] = CONN_EVENTS_READ_WRITE, | |||
274 | }; | |||
275 | int await_fd = (int)((uint64_t)from_coro >> 32); | |||
276 | enum lwan_connection_flags flags; | |||
277 | int op; | |||
278 | ||||
279 | assert(await_fd >= 0)((void) sizeof ((await_fd >= 0) ? 1 : 0), __extension__ ({ if (await_fd >= 0) ; else __assert_fail ("await_fd >= 0" , "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 279, __extension__ __PRETTY_FUNCTION__); })); | |||
280 | assert(yield_result >= CONN_CORO_ASYNC_AWAIT_READ &&((void) sizeof ((yield_result >= CONN_CORO_ASYNC_AWAIT_READ && yield_result <= CONN_CORO_ASYNC_AWAIT_READ_WRITE ) ? 1 : 0), __extension__ ({ if (yield_result >= CONN_CORO_ASYNC_AWAIT_READ && yield_result <= CONN_CORO_ASYNC_AWAIT_READ_WRITE ) ; else __assert_fail ("yield_result >= CONN_CORO_ASYNC_AWAIT_READ && yield_result <= CONN_CORO_ASYNC_AWAIT_READ_WRITE" , "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 281, __extension__ __PRETTY_FUNCTION__); })) | |||
281 | yield_result <= CONN_CORO_ASYNC_AWAIT_READ_WRITE)((void) sizeof ((yield_result >= CONN_CORO_ASYNC_AWAIT_READ && yield_result <= CONN_CORO_ASYNC_AWAIT_READ_WRITE ) ? 1 : 0), __extension__ ({ if (yield_result >= CONN_CORO_ASYNC_AWAIT_READ && yield_result <= CONN_CORO_ASYNC_AWAIT_READ_WRITE ) ; else __assert_fail ("yield_result >= CONN_CORO_ASYNC_AWAIT_READ && yield_result <= CONN_CORO_ASYNC_AWAIT_READ_WRITE" , "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 281, __extension__ __PRETTY_FUNCTION__); })); | |||
282 | ||||
283 | flags = to_connection_flags[yield_result]; | |||
284 | ||||
285 | struct lwan_connection *await_fd_conn = &tq->lwan->conns[await_fd]; | |||
286 | if (LIKELY(await_fd_conn->flags & CONN_ASYNC_AWAIT)__builtin_expect((!!(await_fd_conn->flags & CONN_ASYNC_AWAIT )), (1))) { | |||
287 | if (LIKELY((await_fd_conn->flags & CONN_EVENTS_MASK) == flags)__builtin_expect((!!((await_fd_conn->flags & CONN_EVENTS_MASK ) == flags)), (1))) | |||
288 | return CONN_CORO_SUSPEND; | |||
289 | ||||
290 | op = EPOLL_CTL_MOD3; | |||
291 | } else { | |||
292 | op = EPOLL_CTL_ADD1; | |||
293 | flags |= CONN_ASYNC_AWAIT; | |||
294 | coro_defer(conn->coro, clear_async_await_flag, await_fd_conn); | |||
295 | } | |||
296 | ||||
297 | struct epoll_event event = {.events = conn_flags_to_epoll_events(flags), | |||
298 | .data.ptr = conn}; | |||
299 | if (LIKELY(!epoll_ctl(epoll_fd, op, await_fd, &event))__builtin_expect((!!(!epoll_ctl(epoll_fd, op, await_fd, & event))), (1))) { | |||
300 | await_fd_conn->flags &= ~CONN_EVENTS_MASK; | |||
301 | await_fd_conn->flags |= flags; | |||
302 | return CONN_CORO_SUSPEND; | |||
303 | } | |||
304 | ||||
305 | return CONN_CORO_ABORT; | |||
306 | } | |||
307 | ||||
308 | static ALWAYS_INLINEinline __attribute__((always_inline)) void resume_coro(struct timeout_queue *tq, | |||
309 | struct lwan_connection *conn, | |||
310 | int epoll_fd) | |||
311 | { | |||
312 | assert(conn->coro)((void) sizeof ((conn->coro) ? 1 : 0), __extension__ ({ if (conn->coro) ; else __assert_fail ("conn->coro", "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 312, __extension__ __PRETTY_FUNCTION__); })); | |||
313 | ||||
314 | int64_t from_coro = coro_resume(conn->coro); | |||
315 | enum lwan_connection_coro_yield yield_result = from_coro & 0xffffffff; | |||
316 | ||||
317 | if (UNLIKELY(yield_result >= CONN_CORO_ASYNC)__builtin_expect(((yield_result >= CONN_CORO_ASYNC)), (0))) | |||
318 | yield_result = resume_async(tq, yield_result, from_coro, conn, epoll_fd); | |||
319 | ||||
320 | if (UNLIKELY(yield_result == CONN_CORO_ABORT)__builtin_expect(((yield_result == CONN_CORO_ABORT)), (0))) | |||
321 | return timeout_queue_expire(tq, conn); | |||
322 | ||||
323 | return update_epoll_flags(lwan_connection_get_fd(tq->lwan, conn), conn, | |||
324 | epoll_fd, yield_result); | |||
325 | } | |||
326 | ||||
327 | static void update_date_cache(struct lwan_thread *thread) | |||
328 | { | |||
329 | time_t now = time(NULL((void*)0)); | |||
330 | ||||
331 | lwan_format_rfc_time(now, thread->date.date); | |||
332 | lwan_format_rfc_time(now + (time_t)thread->lwan->config.expires, | |||
333 | thread->date.expires); | |||
334 | } | |||
335 | ||||
336 | static bool_Bool send_buffer_without_coro(int fd, const char *buf, size_t buf_len) | |||
337 | { | |||
338 | size_t total_sent = 0; | |||
339 | ||||
340 | for (int try = 0; try < 10; try++) { | |||
341 | size_t to_send = buf_len - total_sent; | |||
342 | if (!to_send) | |||
343 | return true1; | |||
344 | ||||
345 | ssize_t sent = write(fd, buf + total_sent, to_send); | |||
346 | if (sent <= 0) { | |||
347 | if (errno(*__errno_location ()) == EINTR4) | |||
348 | continue; | |||
349 | break; | |||
350 | } | |||
351 | ||||
352 | total_sent += (size_t)sent; | |||
353 | } | |||
354 | ||||
355 | return false0; | |||
356 | } | |||
357 | ||||
358 | static bool_Bool send_string_without_coro(int fd, const char *str) | |||
359 | { | |||
360 | return send_buffer_without_coro(fd, str, strlen(str)); | |||
361 | } | |||
362 | ||||
363 | static ALWAYS_INLINEinline __attribute__((always_inline)) bool_Bool spawn_coro(struct lwan_connection *conn, | |||
364 | struct coro_switcher *switcher, | |||
365 | struct timeout_queue *tq) | |||
366 | { | |||
367 | struct lwan_thread *t = conn->thread; | |||
368 | ||||
369 | assert(!conn->coro)((void) sizeof ((!conn->coro) ? 1 : 0), __extension__ ({ if (!conn->coro) ; else __assert_fail ("!conn->coro", "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 369, __extension__ __PRETTY_FUNCTION__); })); | |||
370 | assert(!(conn->flags & CONN_ASYNC_AWAIT))((void) sizeof ((!(conn->flags & CONN_ASYNC_AWAIT)) ? 1 : 0), __extension__ ({ if (!(conn->flags & CONN_ASYNC_AWAIT )) ; else __assert_fail ("!(conn->flags & CONN_ASYNC_AWAIT)" , "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 370, __extension__ __PRETTY_FUNCTION__); })); | |||
371 | assert(t)((void) sizeof ((t) ? 1 : 0), __extension__ ({ if (t) ; else __assert_fail ("t", "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 371, __extension__ __PRETTY_FUNCTION__); })); | |||
372 | assert((uintptr_t)t >= (uintptr_t)tq->lwan->thread.threads)((void) sizeof (((uintptr_t)t >= (uintptr_t)tq->lwan-> thread.threads) ? 1 : 0), __extension__ ({ if ((uintptr_t)t >= (uintptr_t)tq->lwan->thread.threads) ; else __assert_fail ("(uintptr_t)t >= (uintptr_t)tq->lwan->thread.threads" , "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 372, __extension__ __PRETTY_FUNCTION__); })); | |||
373 | assert((uintptr_t)t <((void) sizeof (((uintptr_t)t < (uintptr_t)(tq->lwan-> thread.threads + tq->lwan->thread.count)) ? 1 : 0), __extension__ ({ if ((uintptr_t)t < (uintptr_t)(tq->lwan->thread. threads + tq->lwan->thread.count)) ; else __assert_fail ("(uintptr_t)t < (uintptr_t)(tq->lwan->thread.threads + tq->lwan->thread.count)" , "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 374, __extension__ __PRETTY_FUNCTION__); })) | |||
374 | (uintptr_t)(tq->lwan->thread.threads + tq->lwan->thread.count))((void) sizeof (((uintptr_t)t < (uintptr_t)(tq->lwan-> thread.threads + tq->lwan->thread.count)) ? 1 : 0), __extension__ ({ if ((uintptr_t)t < (uintptr_t)(tq->lwan->thread. threads + tq->lwan->thread.count)) ; else __assert_fail ("(uintptr_t)t < (uintptr_t)(tq->lwan->thread.threads + tq->lwan->thread.count)" , "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 374, __extension__ __PRETTY_FUNCTION__); })); | |||
375 | ||||
376 | *conn = (struct lwan_connection){ | |||
377 | .coro = coro_new(switcher, process_request_coro, conn), | |||
378 | .flags = CONN_EVENTS_READ, | |||
379 | .time_to_expire = tq->current_time + tq->move_to_last_bump, | |||
380 | .thread = t, | |||
381 | }; | |||
382 | if (LIKELY(conn->coro)__builtin_expect((!!(conn->coro)), (1))) { | |||
383 | timeout_queue_insert(tq, conn); | |||
384 | return true1; | |||
385 | } | |||
386 | ||||
387 | conn->flags = 0; | |||
388 | ||||
389 | int fd = lwan_connection_get_fd(tq->lwan, conn); | |||
390 | ||||
391 | lwan_status_error("Couldn't spawn coroutine for file descriptor %d", fd)lwan_status_error_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 391, __FUNCTION__, "Couldn't spawn coroutine for file descriptor %d" , fd); | |||
392 | ||||
393 | if (!send_string_without_coro(fd, "HTTP/1.0 503 Unavailable")) | |||
394 | goto out; | |||
395 | if (!send_string_without_coro(fd, "\r\nConnection: close")) | |||
396 | goto out; | |||
397 | if (!send_string_without_coro(fd, "\r\nContent-Type: text/html")) | |||
398 | goto out; | |||
399 | if (send_buffer_without_coro(fd, lwan_strbuf_get_buffer(&tq->lwan->headers), | |||
400 | lwan_strbuf_get_length(&tq->lwan->headers))) { | |||
401 | struct lwan_strbuf buffer; | |||
402 | ||||
403 | lwan_strbuf_init(&buffer); | |||
404 | lwan_fill_default_response(&buffer, HTTP_UNAVAILABLE); | |||
405 | ||||
406 | send_buffer_without_coro(fd, lwan_strbuf_get_buffer(&buffer), | |||
407 | lwan_strbuf_get_length(&buffer)); | |||
408 | ||||
409 | lwan_strbuf_free(&buffer); | |||
410 | } | |||
411 | ||||
412 | out: | |||
413 | shutdown(fd, SHUT_RDWRSHUT_RDWR); | |||
414 | close(fd); | |||
415 | return false0; | |||
416 | } | |||
417 | ||||
418 | static bool_Bool process_pending_timers(struct timeout_queue *tq, | |||
419 | struct lwan_thread *t, | |||
420 | int epoll_fd) | |||
421 | { | |||
422 | struct timeout *timeout; | |||
423 | bool_Bool should_expire_timers = false0; | |||
424 | ||||
425 | while ((timeout = timeouts_get(t->wheel))) { | |||
426 | struct lwan_request *request; | |||
427 | ||||
428 | if (timeout == &tq->timeout) { | |||
429 | should_expire_timers = true1; | |||
430 | continue; | |||
431 | } | |||
432 | ||||
433 | request = container_of(timeout, struct lwan_request, timeout)((struct lwan_request *) ((char *)(timeout) - __builtin_offsetof (struct lwan_request, timeout)) + ((typeof(*(timeout)) *)0 != (typeof(((struct lwan_request *)0)->timeout) *)0)); | |||
434 | ||||
435 | update_epoll_flags(request->fd, request->conn, epoll_fd, | |||
436 | CONN_CORO_RESUME); | |||
437 | } | |||
438 | ||||
439 | if (should_expire_timers) { | |||
440 | timeout_queue_expire_waiting(tq); | |||
441 | ||||
442 | /* tq timeout expires every 1000ms if there are connections, so | |||
443 | * update the date cache at this point as well. */ | |||
444 | update_date_cache(t); | |||
445 | ||||
446 | if (!timeout_queue_empty(tq)) { | |||
447 | timeouts_add(t->wheel, &tq->timeout, 1000); | |||
448 | return true1; | |||
449 | } | |||
450 | ||||
451 | timeouts_del(t->wheel, &tq->timeout); | |||
452 | } | |||
453 | ||||
454 | return false0; | |||
455 | } | |||
456 | ||||
457 | static int | |||
458 | turn_timer_wheel(struct timeout_queue *tq, struct lwan_thread *t, int epoll_fd) | |||
459 | { | |||
460 | const int infinite_timeout = -1; | |||
461 | timeout_t wheel_timeout; | |||
462 | struct timespec now; | |||
463 | ||||
464 | if (UNLIKELY(clock_gettime(monotonic_clock_id, &now) < 0)__builtin_expect(((clock_gettime(monotonic_clock_id, &now ) < 0)), (0))) | |||
465 | lwan_status_critical("Could not get monotonic time")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 465, __FUNCTION__, "Could not get monotonic time"); | |||
466 | ||||
467 | timeouts_update(t->wheel, | |||
468 | (timeout_t)(now.tv_sec * 1000 + now.tv_nsec / 1000000)); | |||
469 | ||||
470 | /* Check if there's an expired timer. */ | |||
471 | wheel_timeout = timeouts_timeout(t->wheel); | |||
472 | if (wheel_timeout > 0) { | |||
473 | return (int)wheel_timeout; /* No, but will soon. Wake us up in | |||
474 | wheel_timeout ms. */ | |||
475 | } | |||
476 | ||||
477 | if (UNLIKELY((int64_t)wheel_timeout < 0)__builtin_expect((((int64_t)wheel_timeout < 0)), (0))) | |||
478 | return infinite_timeout; /* None found. */ | |||
479 | ||||
480 | if (!process_pending_timers(tq, t, epoll_fd)) | |||
481 | return infinite_timeout; /* No more timers to process. */ | |||
482 | ||||
483 | /* After processing pending timers, determine when to wake up. */ | |||
484 | return (int)timeouts_timeout(t->wheel); | |||
485 | } | |||
486 | ||||
487 | static bool_Bool accept_waiting_clients(const struct lwan_thread *t) | |||
488 | { | |||
489 | const struct lwan_connection *conns = t->lwan->conns; | |||
490 | ||||
491 | while (true1) { | |||
492 | int fd = | |||
493 | accept4(t->listen_fd, NULL((void*)0), NULL((void*)0), SOCK_NONBLOCKSOCK_NONBLOCK | SOCK_CLOEXECSOCK_CLOEXEC); | |||
494 | ||||
495 | if (LIKELY(fd >= 0)__builtin_expect((!!(fd >= 0)), (1))) { | |||
496 | const struct lwan_connection *conn = &conns[fd]; | |||
497 | struct epoll_event ev = { | |||
498 | .data.ptr = (void *)conn, | |||
499 | .events = conn_flags_to_epoll_events(CONN_EVENTS_READ), | |||
500 | }; | |||
501 | int r = epoll_ctl(conn->thread->epoll_fd, EPOLL_CTL_ADD1, fd, &ev); | |||
502 | ||||
503 | if (UNLIKELY(r < 0)__builtin_expect(((r < 0)), (0))) { | |||
504 | /* FIXME: send a "busy" response here? No coroutine has been | |||
505 | * created at this point to use the usual stuff, though. */ | |||
506 | lwan_status_perror("Could not add file descriptor %d to epoll "lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 508, __FUNCTION__, "Could not add file descriptor %d to epoll " "set %d. Dropping connection", fd, conn->thread->epoll_fd ) | |||
507 | "set %d. Dropping connection",lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 508, __FUNCTION__, "Could not add file descriptor %d to epoll " "set %d. Dropping connection", fd, conn->thread->epoll_fd ) | |||
508 | fd, conn->thread->epoll_fd)lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 508, __FUNCTION__, "Could not add file descriptor %d to epoll " "set %d. Dropping connection", fd, conn->thread->epoll_fd ); | |||
509 | shutdown(fd, SHUT_RDWRSHUT_RDWR); | |||
510 | close(fd); | |||
511 | } | |||
512 | ||||
513 | continue; | |||
514 | } | |||
515 | ||||
516 | switch (errno(*__errno_location ())) { | |||
517 | default: | |||
518 | lwan_status_perror("Unexpected error while accepting connections")lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 518, __FUNCTION__, "Unexpected error while accepting connections" ); | |||
519 | /* fallthrough */ | |||
520 | ||||
521 | case EAGAIN11: | |||
522 | return true1; | |||
523 | ||||
524 | case EBADF9: | |||
525 | case ECONNABORTED103: | |||
526 | case EINVAL22: | |||
527 | lwan_status_info("Listening socket closed")lwan_status_info_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 527, __FUNCTION__, "Listening socket closed"); | |||
528 | return false0; | |||
529 | } | |||
530 | } | |||
531 | ||||
532 | __builtin_unreachable(); | |||
533 | } | |||
534 | ||||
535 | static int create_listen_socket(struct lwan_thread *t, | |||
536 | unsigned int num) | |||
537 | { | |||
538 | int listen_fd; | |||
539 | ||||
540 | listen_fd = lwan_create_listen_socket(t->lwan, num == 0); | |||
541 | if (listen_fd < 0) | |||
542 | lwan_status_critical("Could not create listen_fd")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 542, __FUNCTION__, "Could not create listen_fd"); | |||
543 | ||||
544 | /* Ignore errors here, as this is just a hint */ | |||
545 | #if defined(HAVE_SO_ATTACH_REUSEPORT_CBPF) | |||
546 | /* From socket(7): "These options may be set repeatedly at any time on | |||
547 | * any socket in the group to replace the current BPF program used by | |||
548 | * all sockets in the group." */ | |||
549 | if (num == 0) { | |||
550 | /* From socket(7): "The BPF program must return an index between 0 and | |||
551 | * N-1 representing the socket which should receive the packet (where N | |||
552 | * is the number of sockets in the group)." */ | |||
553 | const uint32_t cpu_ad_off = (uint32_t)SKF_AD_OFF(-0x1000) + SKF_AD_CPU36; | |||
554 | struct sock_filter filter[] = { | |||
555 | {BPF_LD0x00 | BPF_W0x00 | BPF_ABS0x20, 0, 0, cpu_ad_off}, /* A = curr_cpu_index */ | |||
556 | {BPF_RET0x06 | BPF_A0x10, 0, 0, 0}, /* return A */ | |||
557 | }; | |||
558 | struct sock_fprog fprog = {.filter = filter, .len = N_ELEMENTS(filter)((!sizeof(char[1 - 2 * __builtin_types_compatible_p( __typeof__ (filter), __typeof__(&(filter)[0]))])) | sizeof(filter) / sizeof(filter[0]))}; | |||
559 | ||||
560 | (void)setsockopt(listen_fd, SOL_SOCKET1, SO_ATTACH_REUSEPORT_CBPF51, | |||
561 | &fprog, sizeof(fprog)); | |||
562 | (void)setsockopt(listen_fd, SOL_SOCKET1, SO_LOCK_FILTER44, | |||
563 | (int[]){1}, sizeof(int)); | |||
564 | } | |||
565 | #elif defined(HAVE_SO_INCOMING_CPU) && defined(__x86_64__1) | |||
566 | (void)setsockopt(listen_fd, SOL_SOCKET1, SO_INCOMING_CPU49, &t->cpu, | |||
567 | sizeof(t->cpu)); | |||
568 | #endif | |||
569 | ||||
570 | struct epoll_event event = { | |||
571 | .events = EPOLLINEPOLLIN | EPOLLETEPOLLET | EPOLLERREPOLLERR, | |||
572 | .data.ptr = NULL((void*)0), | |||
573 | }; | |||
574 | if (epoll_ctl(t->epoll_fd, EPOLL_CTL_ADD1, listen_fd, &event) < 0) | |||
575 | lwan_status_critical_perror("Could not add socket to epoll")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 575, __FUNCTION__, "Could not add socket to epoll"); | |||
576 | ||||
577 | return listen_fd; | |||
578 | } | |||
579 | ||||
580 | static void *thread_io_loop(void *data) | |||
581 | { | |||
582 | struct lwan_thread *t = data; | |||
583 | int epoll_fd = t->epoll_fd; | |||
584 | const int max_events = LWAN_MIN((int)t->lwan->thread.max_fd, 1024)({ const __typeof__(((int)t->lwan->thread.max_fd) + 0) lwan_tmp_id4 = ((int)t->lwan->thread.max_fd); const __typeof__((1024 ) + 0) lwan_tmp_id5 = (1024); lwan_tmp_id4 > lwan_tmp_id5 ? lwan_tmp_id5 : lwan_tmp_id4; }); | |||
585 | struct lwan *lwan = t->lwan; | |||
586 | struct epoll_event *events; | |||
587 | struct coro_switcher switcher; | |||
588 | struct timeout_queue tq; | |||
589 | ||||
590 | lwan_status_debug("Worker thread #%zd starting",lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 591, __FUNCTION__, "Worker thread #%zd starting", t - t-> lwan->thread.threads + 1) | |||
591 | t - t->lwan->thread.threads + 1)lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 591, __FUNCTION__, "Worker thread #%zd starting", t - t-> lwan->thread.threads + 1); | |||
592 | lwan_set_thread_name("worker"); | |||
593 | ||||
594 | events = calloc((size_t)max_events, sizeof(*events)); | |||
595 | if (UNLIKELY(!events)__builtin_expect(((!events)), (0))) | |||
596 | lwan_status_critical("Could not allocate memory for events")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 596, __FUNCTION__, "Could not allocate memory for events"); | |||
597 | ||||
598 | update_date_cache(t); | |||
599 | ||||
600 | timeout_queue_init(&tq, lwan); | |||
601 | ||||
602 | lwan_random_seed_prng_for_thread((uint64_t)(epoll_fd | time(NULL((void*)0)))); | |||
603 | ||||
604 | pthread_barrier_wait(&lwan->thread.barrier); | |||
605 | ||||
606 | for (;;) { | |||
607 | int timeout = turn_timer_wheel(&tq, t, epoll_fd); | |||
608 | int n_fds = epoll_wait(epoll_fd, events, max_events, timeout); | |||
609 | bool_Bool accepted_connections = false0; | |||
610 | ||||
611 | if (UNLIKELY(n_fds < 0)__builtin_expect(((n_fds < 0)), (0))) { | |||
612 | if (errno(*__errno_location ()) == EBADF9 || errno(*__errno_location ()) == EINVAL22) | |||
613 | break; | |||
614 | continue; | |||
615 | } | |||
616 | ||||
617 | for (struct epoll_event *event = events; n_fds--; event++) { | |||
618 | struct lwan_connection *conn; | |||
619 | ||||
620 | if (!event->data.ptr) { | |||
621 | if (LIKELY(accept_waiting_clients(t))__builtin_expect((!!(accept_waiting_clients(t))), (1))) { | |||
622 | accepted_connections = true1; | |||
623 | continue; | |||
624 | } | |||
625 | close(epoll_fd); | |||
626 | epoll_fd = -1; | |||
627 | break; | |||
628 | } | |||
629 | ||||
630 | conn = event->data.ptr; | |||
631 | ||||
632 | if (UNLIKELY(event->events & (EPOLLRDHUP | EPOLLHUP))__builtin_expect(((event->events & (EPOLLRDHUP | EPOLLHUP ))), (0))) { | |||
633 | timeout_queue_expire(&tq, conn); | |||
634 | continue; | |||
635 | } | |||
636 | ||||
637 | if (!conn->coro) { | |||
638 | if (UNLIKELY(!spawn_coro(conn, &switcher, &tq))__builtin_expect(((!spawn_coro(conn, &switcher, &tq)) ), (0))) | |||
639 | continue; | |||
640 | } | |||
641 | ||||
642 | resume_coro(&tq, conn, epoll_fd); | |||
643 | timeout_queue_move_to_last(&tq, conn); | |||
644 | } | |||
645 | ||||
646 | if (accepted_connections) | |||
647 | timeouts_add(t->wheel, &tq.timeout, 1000); | |||
648 | } | |||
649 | ||||
650 | pthread_barrier_wait(&lwan->thread.barrier); | |||
651 | ||||
652 | timeout_queue_expire_all(&tq); | |||
653 | free(events); | |||
654 | ||||
655 | return NULL((void*)0); | |||
656 | } | |||
657 | ||||
658 | static void create_thread(struct lwan *l, struct lwan_thread *thread) | |||
659 | { | |||
660 | int ignore; | |||
661 | pthread_attr_t attr; | |||
662 | ||||
663 | thread->lwan = l; | |||
664 | ||||
665 | thread->wheel = timeouts_open(&ignore); | |||
666 | if (!thread->wheel) | |||
667 | lwan_status_critical("Could not create timer wheel")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 667, __FUNCTION__, "Could not create timer wheel"); | |||
668 | ||||
669 | if ((thread->epoll_fd = epoll_create1(EPOLL_CLOEXECEPOLL_CLOEXEC)) < 0) | |||
670 | lwan_status_critical_perror("epoll_create")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 670, __FUNCTION__, "epoll_create"); | |||
671 | ||||
672 | if (pthread_attr_init(&attr)) | |||
673 | lwan_status_critical_perror("pthread_attr_init")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 673, __FUNCTION__, "pthread_attr_init"); | |||
674 | ||||
675 | if (pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEMPTHREAD_SCOPE_SYSTEM)) | |||
676 | lwan_status_critical_perror("pthread_attr_setscope")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 676, __FUNCTION__, "pthread_attr_setscope"); | |||
677 | ||||
678 | if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLEPTHREAD_CREATE_JOINABLE)) | |||
679 | lwan_status_critical_perror("pthread_attr_setdetachstate")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 679, __FUNCTION__, "pthread_attr_setdetachstate"); | |||
680 | ||||
681 | if (pthread_create(&thread->self, &attr, thread_io_loop, thread)) | |||
682 | lwan_status_critical_perror("pthread_create")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 682, __FUNCTION__, "pthread_create"); | |||
683 | ||||
684 | if (pthread_attr_destroy(&attr)) | |||
685 | lwan_status_critical_perror("pthread_attr_destroy")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 685, __FUNCTION__, "pthread_attr_destroy"); | |||
686 | } | |||
687 | ||||
688 | #if defined(__linux__1) && defined(__x86_64__1) | |||
689 | static bool_Bool read_cpu_topology(struct lwan *l, uint32_t siblings[]) | |||
690 | { | |||
691 | char path[PATH_MAX4096]; | |||
692 | ||||
693 | for (uint32_t i = 0; i < l->available_cpus; i++) | |||
694 | siblings[i] = 0xbebacafe; | |||
695 | ||||
696 | for (unsigned int i = 0; i < l->available_cpus; i++) { | |||
697 | FILE *sib; | |||
698 | uint32_t id, sibling; | |||
699 | char separator; | |||
700 | ||||
701 | snprintf(path, sizeof(path), | |||
702 | "/sys/devices/system/cpu/cpu%d/topology/thread_siblings_list", | |||
703 | i); | |||
704 | ||||
705 | sib = fopen(path, "re"); | |||
706 | if (!sib) { | |||
707 | lwan_status_warning("Could not open `%s` to determine CPU topology",lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 708, __FUNCTION__, "Could not open `%s` to determine CPU topology" , path) | |||
708 | path)lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 708, __FUNCTION__, "Could not open `%s` to determine CPU topology" , path); | |||
709 | return false0; | |||
710 | } | |||
711 | ||||
712 | switch (fscanf(sib, "%u%c%u", &id, &separator, &sibling)) { | |||
713 | case 2: /* No SMT */ | |||
714 | siblings[i] = id; | |||
715 | break; | |||
716 | case 3: /* SMT */ | |||
717 | if (!(separator == ',' || separator == '-')) { | |||
718 | lwan_status_critical("Expecting either ',' or '-' for sibling separator")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 718, __FUNCTION__, "Expecting either ',' or '-' for sibling separator" ); | |||
719 | __builtin_unreachable(); | |||
720 | } | |||
721 | ||||
722 | siblings[i] = sibling; | |||
723 | break; | |||
724 | default: | |||
725 | lwan_status_critical("%s has invalid format", path)lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 725, __FUNCTION__, "%s has invalid format", path); | |||
726 | __builtin_unreachable(); | |||
727 | } | |||
728 | ||||
729 | fclose(sib); | |||
730 | } | |||
731 | ||||
732 | /* Perform a sanity check here, as some systems seem to filter out the | |||
733 | * result of sysconf() to obtain the number of configured and online | |||
734 | * CPUs but don't bother changing what's available through sysfs as far | |||
735 | * as the CPU topology information goes. It's better to fall back to a | |||
736 | * possibly non-optimal setup than just crash during startup while | |||
737 | * trying to perform an out-of-bounds array access. */ | |||
738 | for (unsigned int i = 0; i < l->available_cpus; i++) { | |||
739 | if (siblings[i] == 0xbebacafe) { | |||
740 | lwan_status_warning("Could not determine sibling for CPU %d", i)lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 740, __FUNCTION__, "Could not determine sibling for CPU %d" , i); | |||
741 | return false0; | |||
742 | } | |||
743 | ||||
744 | if (siblings[i] >= l->available_cpus) { | |||
745 | lwan_status_warning("CPU information topology says CPU %d exists, "lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 748, __FUNCTION__, "CPU information topology says CPU %d exists, " "but max available CPUs is %d (online CPUs: %d). " "Is Lwan running in a (broken) container?" , siblings[i], l->available_cpus, l->online_cpus) | |||
746 | "but max available CPUs is %d (online CPUs: %d). "lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 748, __FUNCTION__, "CPU information topology says CPU %d exists, " "but max available CPUs is %d (online CPUs: %d). " "Is Lwan running in a (broken) container?" , siblings[i], l->available_cpus, l->online_cpus) | |||
747 | "Is Lwan running in a (broken) container?",lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 748, __FUNCTION__, "CPU information topology says CPU %d exists, " "but max available CPUs is %d (online CPUs: %d). " "Is Lwan running in a (broken) container?" , siblings[i], l->available_cpus, l->online_cpus) | |||
748 | siblings[i], l->available_cpus, l->online_cpus)lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 748, __FUNCTION__, "CPU information topology says CPU %d exists, " "but max available CPUs is %d (online CPUs: %d). " "Is Lwan running in a (broken) container?" , siblings[i], l->available_cpus, l->online_cpus); | |||
749 | return false0; | |||
750 | } | |||
751 | } | |||
752 | ||||
753 | return true1; | |||
754 | } | |||
755 | ||||
756 | static void | |||
757 | siblings_to_schedtbl(struct lwan *l, uint32_t siblings[], uint32_t schedtbl[]) | |||
758 | { | |||
759 | int *seen = alloca(l->available_cpus * sizeof(int))__builtin_alloca (l->available_cpus * sizeof(int)); | |||
760 | unsigned int n_schedtbl = 0; | |||
761 | ||||
762 | for (uint32_t i = 0; i < l->available_cpus; i++) | |||
763 | seen[i] = -1; | |||
764 | ||||
765 | for (uint32_t i = 0; i < l->available_cpus; i++) { | |||
766 | if (seen[siblings[i]] < 0) { | |||
767 | seen[siblings[i]] = (int)i; | |||
768 | } else { | |||
769 | schedtbl[n_schedtbl++] = (uint32_t)seen[siblings[i]]; | |||
770 | schedtbl[n_schedtbl++] = i; | |||
771 | } | |||
772 | } | |||
773 | ||||
774 | if (n_schedtbl != l->available_cpus) | |||
775 | memcpy(schedtbl, seen, l->available_cpus * sizeof(int)); | |||
776 | } | |||
777 | ||||
778 | static bool_Bool | |||
779 | topology_to_schedtbl(struct lwan *l, uint32_t schedtbl[], uint32_t n_threads) | |||
780 | { | |||
781 | uint32_t *siblings = alloca(l->available_cpus * sizeof(uint32_t))__builtin_alloca (l->available_cpus * sizeof(uint32_t)); | |||
782 | ||||
783 | if (read_cpu_topology(l, siblings)) { | |||
784 | uint32_t *affinity = alloca(l->available_cpus * sizeof(uint32_t))__builtin_alloca (l->available_cpus * sizeof(uint32_t)); | |||
785 | ||||
786 | siblings_to_schedtbl(l, siblings, affinity); | |||
787 | ||||
788 | for (uint32_t i = 0; i < n_threads; i++) | |||
789 | schedtbl[i] = affinity[i % l->available_cpus]; | |||
790 | return true1; | |||
791 | } | |||
792 | ||||
793 | for (uint32_t i = 0; i < n_threads; i++) | |||
794 | schedtbl[i] = (i / 2) % l->thread.count; | |||
795 | return false0; | |||
796 | } | |||
797 | ||||
798 | static void | |||
799 | adjust_thread_affinity(const struct lwan_thread *thread) | |||
800 | { | |||
801 | cpu_set_t set; | |||
802 | ||||
803 | CPU_ZERO(&set)do __builtin_memset (&set, '\0', sizeof (cpu_set_t)); while (0); | |||
804 | CPU_SET(thread->cpu, &set)(__extension__ ({ size_t __cpu = (thread->cpu); __cpu / 8 < (sizeof (cpu_set_t)) ? (((__cpu_mask *) ((&set)->__bits ))[((__cpu) / (8 * sizeof (__cpu_mask)))] |= ((__cpu_mask) 1 << ((__cpu) % (8 * sizeof (__cpu_mask))))) : 0; })); | |||
805 | ||||
806 | if (pthread_setaffinity_np(thread->self, sizeof(set), &set)) | |||
807 | lwan_status_warning("Could not set thread affinity")lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 807, __FUNCTION__, "Could not set thread affinity"); | |||
808 | } | |||
809 | #elif defined(__x86_64__1) | |||
810 | static bool_Bool | |||
811 | topology_to_schedtbl(struct lwan *l, uint32_t schedtbl[], uint32_t n_threads) | |||
812 | { | |||
813 | for (uint32_t i = 0; i < n_threads; i++) | |||
814 | schedtbl[i] = (i / 2) % l->thread.count; | |||
815 | return false0; | |||
816 | } | |||
817 | ||||
818 | static void | |||
819 | adjust_thread_affinity(const struct lwan_thread *thread) | |||
820 | { | |||
821 | (void)thread; | |||
822 | } | |||
823 | #endif | |||
824 | ||||
825 | void lwan_thread_init(struct lwan *l) | |||
826 | { | |||
827 | const unsigned int total_conns = l->thread.max_fd * l->thread.count; | |||
828 | ||||
829 | lwan_status_debug("Initializing threads")lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 829, __FUNCTION__, "Initializing threads"); | |||
830 | ||||
831 | l->thread.threads = | |||
832 | calloc((size_t)l->thread.count, sizeof(struct lwan_thread)); | |||
833 | if (!l->thread.threads) | |||
| ||||
834 | lwan_status_critical("Could not allocate memory for threads")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 834, __FUNCTION__, "Could not allocate memory for threads"); | |||
835 | ||||
836 | #ifdef __x86_64__1 | |||
837 | static_assert(sizeof(struct lwan_connection) == 32,extern int (*__Static_assert_function (void)) [!!sizeof (struct { int __error_if_negative: (sizeof(struct lwan_connection) == 32) ? 2 : -1; })] | |||
838 | "Two connections per cache line")extern int (*__Static_assert_function (void)) [!!sizeof (struct { int __error_if_negative: (sizeof(struct lwan_connection) == 32) ? 2 : -1; })]; | |||
839 | #ifdef _SC_LEVEL1_DCACHE_LINESIZE_SC_LEVEL1_DCACHE_LINESIZE | |||
840 | assert(sysconf(_SC_LEVEL1_DCACHE_LINESIZE) == 64)((void) sizeof ((sysconf(_SC_LEVEL1_DCACHE_LINESIZE) == 64) ? 1 : 0), __extension__ ({ if (sysconf(_SC_LEVEL1_DCACHE_LINESIZE ) == 64) ; else __assert_fail ("sysconf(_SC_LEVEL1_DCACHE_LINESIZE) == 64" , "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 840, __extension__ __PRETTY_FUNCTION__); })); | |||
841 | #endif | |||
842 | ||||
843 | lwan_status_debug("%d CPUs of %d are online. "lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 845, __FUNCTION__, "%d CPUs of %d are online. " "Reading topology to pre-schedule clients" , l->online_cpus, l->available_cpus) | |||
844 | "Reading topology to pre-schedule clients",lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 845, __FUNCTION__, "%d CPUs of %d are online. " "Reading topology to pre-schedule clients" , l->online_cpus, l->available_cpus) | |||
845 | l->online_cpus, l->available_cpus)lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 845, __FUNCTION__, "%d CPUs of %d are online. " "Reading topology to pre-schedule clients" , l->online_cpus, l->available_cpus); | |||
846 | ||||
847 | /* | |||
848 | * Pre-schedule each file descriptor, to reduce some operations in the | |||
849 | * fast path. | |||
850 | * | |||
851 | * Since struct lwan_connection is guaranteed to be 32-byte long, two of | |||
852 | * them can fill up a cache line. Assume siblings share cache lines and | |||
853 | * use the CPU topology to group two connections per cache line in such | |||
854 | * a way that false sharing is avoided. | |||
855 | */ | |||
856 | uint32_t n_threads = | |||
857 | (uint32_t)lwan_nextpow2((size_t)((l->thread.count - 1) * 2)); | |||
858 | uint32_t *schedtbl = alloca(n_threads * sizeof(uint32_t))__builtin_alloca (n_threads * sizeof(uint32_t)); | |||
859 | ||||
860 | bool_Bool adj_affinity = topology_to_schedtbl(l, schedtbl, n_threads); | |||
861 | ||||
862 | n_threads--; /* Transform count into mask for AND below */ | |||
863 | ||||
864 | for (unsigned int i = 0; i < total_conns; i++) | |||
865 | l->conns[i].thread = &l->thread.threads[schedtbl[i & n_threads]]; | |||
| ||||
866 | #else | |||
867 | for (unsigned int i = 0; i < l->thread.count; i++) | |||
868 | l->thread.threads[i].cpu = i % l->online_cpus; | |||
869 | for (unsigned int i = 0; i < total_conns; i++) | |||
870 | l->conns[i].thread = &l->thread.threads[i % l->thread.count]; | |||
871 | ||||
872 | uint32_t *schedtbl = NULL((void*)0); | |||
873 | const bool_Bool adj_affinity = false0; | |||
874 | #endif | |||
875 | ||||
876 | for (unsigned int i = 0; i < l->thread.count; i++) { | |||
877 | struct lwan_thread *thread = NULL((void*)0); | |||
878 | ||||
879 | if (schedtbl) { | |||
880 | /* This is not the most elegant thing, but this assures that the | |||
881 | * listening sockets are added to the SO_REUSEPORT group in a | |||
882 | * specific order, because that's what the CBPF program to direct | |||
883 | * the incoming connection to the right CPU will use. */ | |||
884 | for (uint32_t thread_id = 0; thread_id < l->thread.count; | |||
885 | thread_id++) { | |||
886 | if (schedtbl[thread_id & n_threads] == i) { | |||
887 | thread = &l->thread.threads[thread_id]; | |||
888 | break; | |||
889 | } | |||
890 | } | |||
891 | if (!thread) { | |||
892 | /* FIXME: can this happen when we have a offline CPU? */ | |||
893 | lwan_status_critical(lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 894, __FUNCTION__, "Could not figure out which CPU thread %d should go to" , i) | |||
894 | "Could not figure out which CPU thread %d should go to", i)lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 894, __FUNCTION__, "Could not figure out which CPU thread %d should go to" , i); | |||
895 | } | |||
896 | } else { | |||
897 | thread = &l->thread.threads[i % l->thread.count]; | |||
898 | } | |||
899 | ||||
900 | if (pthread_barrier_init(&l->thread.barrier, NULL((void*)0), 2)) | |||
901 | lwan_status_critical("Could not create barrier")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 901, __FUNCTION__, "Could not create barrier"); | |||
902 | ||||
903 | create_thread(l, thread); | |||
904 | ||||
905 | if ((thread->listen_fd = create_listen_socket(thread, i)) < 0) | |||
906 | lwan_status_critical_perror("Could not create listening socket")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 906, __FUNCTION__, "Could not create listening socket"); | |||
907 | ||||
908 | if (adj_affinity) { | |||
909 | l->thread.threads[i].cpu = schedtbl[i & n_threads]; | |||
910 | adjust_thread_affinity(thread); | |||
911 | } | |||
912 | ||||
913 | pthread_barrier_wait(&l->thread.barrier); | |||
914 | } | |||
915 | ||||
916 | lwan_status_debug("Worker threads created and ready to serve")lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 916, __FUNCTION__, "Worker threads created and ready to serve" ); | |||
917 | } | |||
918 | ||||
919 | void lwan_thread_shutdown(struct lwan *l) | |||
920 | { | |||
921 | lwan_status_debug("Shutting down threads")lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 921, __FUNCTION__, "Shutting down threads"); | |||
922 | ||||
923 | for (unsigned int i = 0; i < l->thread.count; i++) { | |||
924 | struct lwan_thread *t = &l->thread.threads[i]; | |||
925 | int epoll_fd = t->epoll_fd; | |||
926 | int listen_fd = t->listen_fd; | |||
927 | ||||
928 | t->listen_fd = -1; | |||
929 | t->epoll_fd = -1; | |||
930 | close(epoll_fd); | |||
931 | close(listen_fd); | |||
932 | } | |||
933 | ||||
934 | pthread_barrier_wait(&l->thread.barrier); | |||
935 | pthread_barrier_destroy(&l->thread.barrier); | |||
936 | ||||
937 | for (unsigned int i = 0; i < l->thread.count; i++) { | |||
938 | struct lwan_thread *t = &l->thread.threads[i]; | |||
939 | ||||
940 | pthread_join(l->thread.threads[i].self, NULL((void*)0)); | |||
941 | timeouts_close(t->wheel); | |||
942 | } | |||
943 | ||||
944 | free(l->thread.threads); | |||
945 | } |