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