blob: b0568f8fa8427dd1b1738b3573a6b24e0156e056 [file] [log] [blame]
Willy Tarreau609aad92018-11-22 08:31:09 +01001/*
2 * activity measurement functions.
3 *
4 * Copyright 2000-2018 Willy Tarreau <w@1wt.eu>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Willy Tarreaudb87fc72021-05-05 16:50:40 +020013#include <malloc.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020014#include <haproxy/activity-t.h>
Willy Tarreau4c7e4b72020-05-27 12:58:42 +020015#include <haproxy/api.h>
Willy Tarreau6be78492020-06-05 00:00:29 +020016#include <haproxy/cfgparse.h>
Willy Tarreauf1d32c42020-06-04 21:07:02 +020017#include <haproxy/channel.h>
Willy Tarreau83487a82020-06-04 20:19:54 +020018#include <haproxy/cli.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020019#include <haproxy/freq_ctr.h>
Willy Tarreau5e539c92020-06-04 20:45:39 +020020#include <haproxy/stream_interface.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020021#include <haproxy/tools.h>
Willy Tarreau75c62c22018-11-22 11:02:09 +010022
Willy Tarreauf93c7be2021-05-05 17:07:09 +020023#if defined(DEBUG_MEM_STATS)
24/* these ones are macros in bug.h when DEBUG_MEM_STATS is set, and will
25 * prevent the new ones from being redefined.
26 */
27#undef calloc
28#undef malloc
29#undef realloc
30#endif
Willy Tarreau75c62c22018-11-22 11:02:09 +010031
32/* bit field of profiling options. Beware, may be modified at runtime! */
Willy Tarreauef7380f2021-05-05 16:28:31 +020033unsigned int profiling __read_mostly = HA_PROF_TASKS_AOFF;
34unsigned long task_profiling_mask __read_mostly = 0;
Willy Tarreau609aad92018-11-22 08:31:09 +010035
36/* One struct per thread containing all collected measurements */
37struct activity activity[MAX_THREADS] __attribute__((aligned(64))) = { };
38
Willy Tarreau3fb6a7b2021-01-28 19:19:26 +010039/* One struct per function pointer hash entry (256 values, 0=collision) */
40struct sched_activity sched_activity[256] __attribute__((aligned(64))) = { };
Willy Tarreau609aad92018-11-22 08:31:09 +010041
Willy Tarreaudb87fc72021-05-05 16:50:40 +020042
43#if USE_MEMORY_PROFILING
44/* determine the number of buckets to store stats */
45#define MEMPROF_HASH_BITS 10
46#define MEMPROF_HASH_BUCKETS (1U << MEMPROF_HASH_BITS)
47
48/* stats:
49 * - malloc increases alloc
50 * - free increases free (if non null)
51 * - realloc increases either depending on the size change.
52 * when the real size is known (malloc_usable_size()), it's used in free_tot
53 * and alloc_tot, otherwise the requested size is reported in alloc_tot and
54 * zero in free_tot.
55 */
56struct memprof_stats {
57 const void *caller;
58 unsigned long long alloc_calls;
59 unsigned long long free_calls;
60 unsigned long long alloc_tot;
61 unsigned long long free_tot;
62};
63
64/* last one is for hash collisions ("others") and has no caller address */
65struct memprof_stats memprof_stats[MEMPROF_HASH_BUCKETS + 1] = { };
66
Willy Tarreauf93c7be2021-05-05 17:07:09 +020067/* used to detect recursive calls */
68static THREAD_LOCAL int in_memprof = 0;
69
70/* perform a pointer hash by scrambling its bits and retrieving the most
71 * mixed ones (topmost ones in 32-bit, middle ones in 64-bit).
72 */
73static unsigned int memprof_hash_ptr(const void *p)
74{
75 unsigned long long x = (unsigned long)p;
76
77 x = 0xcbda9653U * x;
78 if (sizeof(long) == 4)
79 x >>= 32;
80 else
81 x >>= 33 - MEMPROF_HASH_BITS / 2;
82 return x & (MEMPROF_HASH_BUCKETS - 1);
83}
84
85/* These ones are used by glibc and will be called early. They are in charge of
86 * initializing the handlers with the original functions.
87 */
88static void *memprof_malloc_initial_handler(size_t size);
89static void *memprof_calloc_initial_handler(size_t nmemb, size_t size);
90static void *memprof_realloc_initial_handler(void *ptr, size_t size);
91static void memprof_free_initial_handler(void *ptr);
92
93/* Fallback handlers for the main alloc/free functions. They are preset to
94 * the initializer in order to save a test in the functions's critical path.
95 */
96static void *(*memprof_malloc_handler)(size_t size) = memprof_malloc_initial_handler;
97static void *(*memprof_calloc_handler)(size_t nmemb, size_t size) = memprof_calloc_initial_handler;
98static void *(*memprof_realloc_handler)(void *ptr, size_t size) = memprof_realloc_initial_handler;
99static void (*memprof_free_handler)(void *ptr) = memprof_free_initial_handler;
100
101/* Used to force to die if it's not possible to retrieve the allocation
102 * functions. We cannot even use stdio in this case.
103 */
104static __attribute__((noreturn)) void memprof_die(const char *msg)
105{
106 DISGUISE(write(2, msg, strlen(msg)));
107 exit(1);
108}
109
110/* Resolve original allocation functions and initialize all handlers.
111 * This must be called very early at boot, before the very first malloc()
112 * call, and is not thread-safe! It's not even possible to use stdio there.
113 * Worse, we have to account for the risk of reentrance from dlsym() when
114 * it tries to prepare its error messages. Here its ahndled by in_memprof
115 * that makes allocators return NULL. dlsym() handles it gracefully. An
116 * alternate approch consists in calling aligned_alloc() from these places
117 * but that would mean not being able to intercept it later if considered
118 * useful to do so.
119 */
120static void memprof_init()
121{
122 in_memprof++;
123 memprof_malloc_handler = get_sym_next_addr("malloc");
124 if (!memprof_malloc_handler)
125 memprof_die("FATAL: malloc() function not found.\n");
126
127 memprof_calloc_handler = get_sym_next_addr("calloc");
128 if (!memprof_calloc_handler)
129 memprof_die("FATAL: calloc() function not found.\n");
130
131 memprof_realloc_handler = get_sym_next_addr("realloc");
132 if (!memprof_realloc_handler)
133 memprof_die("FATAL: realloc() function not found.\n");
134
135 memprof_free_handler = get_sym_next_addr("free");
136 if (!memprof_free_handler)
137 memprof_die("FATAL: free() function not found.\n");
138 in_memprof--;
139}
140
141/* the initial handlers will initialize all regular handlers and will call the
142 * one they correspond to. A single one of these functions will typically be
143 * called, though it's unknown which one (as any might be called before main).
144 */
145static void *memprof_malloc_initial_handler(size_t size)
146{
147 if (in_memprof) {
148 /* it's likely that dlsym() needs malloc(), let's fail */
149 return NULL;
150 }
151
152 memprof_init();
153 return memprof_malloc_handler(size);
154}
155
156static void *memprof_calloc_initial_handler(size_t nmemb, size_t size)
157{
158 if (in_memprof) {
159 /* it's likely that dlsym() needs calloc(), let's fail */
160 return NULL;
161 }
162 memprof_init();
163 return memprof_calloc_handler(nmemb, size);
164}
165
166static void *memprof_realloc_initial_handler(void *ptr, size_t size)
167{
168 if (in_memprof) {
169 /* it's likely that dlsym() needs realloc(), let's fail */
170 return NULL;
171 }
172
173 memprof_init();
174 return memprof_realloc_handler(ptr, size);
175}
176
177static void memprof_free_initial_handler(void *ptr)
178{
179 memprof_init();
180 memprof_free_handler(ptr);
181}
182
183/* Assign a bin for the memprof_stats to the return address. May perform a few
184 * attempts before finding the right one, but always succeeds (in the worst
185 * case, returns a default bin). The caller address is atomically set except
186 * for the default one which is never set.
187 */
188static struct memprof_stats *memprof_get_bin(const void *ra)
189{
190 int retries = 16; // up to 16 consecutive entries may be tested.
191 void *old;
192 unsigned int bin;
193
194 bin = memprof_hash_ptr(ra);
195 for (; memprof_stats[bin].caller != ra; bin = (bin + 1) & (MEMPROF_HASH_BUCKETS - 1)) {
196 if (!--retries) {
197 bin = MEMPROF_HASH_BUCKETS;
198 break;
199 }
200
201 old = NULL;
202 if (!memprof_stats[bin].caller &&
203 HA_ATOMIC_CAS(&memprof_stats[bin].caller, &old, ra))
204 break;
205 }
206 return &memprof_stats[bin];
207}
208
209/* This is the new global malloc() function. It must optimize for the normal
210 * case (i.e. profiling disabled) hence the first test to permit a direct jump.
211 * It must remain simple to guarantee the lack of reentrance. stdio is not
212 * possible there even for debugging. The reported size is the really allocated
213 * one as returned by malloc_usable_size(), because this will allow it to be
214 * compared to the one before realloc() or free(). This is a GNU and jemalloc
215 * extension but other systems may also store this size in ptr[-1].
216 */
217void *malloc(size_t size)
218{
219 struct memprof_stats *bin;
220 void *ret;
221
222 if (likely(!(profiling & HA_PROF_MEMORY)))
223 return memprof_malloc_handler(size);
224
225 ret = memprof_malloc_handler(size);
226 size = malloc_usable_size(ret);
227
228 bin = memprof_get_bin(__builtin_return_address(0));
229 _HA_ATOMIC_ADD(&bin->alloc_calls, 1);
230 _HA_ATOMIC_ADD(&bin->alloc_tot, size);
231 return ret;
232}
233
234/* This is the new global calloc() function. It must optimize for the normal
235 * case (i.e. profiling disabled) hence the first test to permit a direct jump.
236 * It must remain simple to guarantee the lack of reentrance. stdio is not
237 * possible there even for debugging. The reported size is the really allocated
238 * one as returned by malloc_usable_size(), because this will allow it to be
239 * compared to the one before realloc() or free(). This is a GNU and jemalloc
240 * extension but other systems may also store this size in ptr[-1].
241 */
242void *calloc(size_t nmemb, size_t size)
243{
244 struct memprof_stats *bin;
245 void *ret;
246
247 if (likely(!(profiling & HA_PROF_MEMORY)))
248 return memprof_calloc_handler(nmemb, size);
249
250 ret = memprof_calloc_handler(nmemb, size);
251 size = malloc_usable_size(ret);
252
253 bin = memprof_get_bin(__builtin_return_address(0));
254 _HA_ATOMIC_ADD(&bin->alloc_calls, 1);
255 _HA_ATOMIC_ADD(&bin->alloc_tot, size);
256 return ret;
257}
258
259/* This is the new global realloc() function. It must optimize for the normal
260 * case (i.e. profiling disabled) hence the first test to permit a direct jump.
261 * It must remain simple to guarantee the lack of reentrance. stdio is not
262 * possible there even for debugging. The reported size is the really allocated
263 * one as returned by malloc_usable_size(), because this will allow it to be
264 * compared to the one before realloc() or free(). This is a GNU and jemalloc
265 * extension but other systems may also store this size in ptr[-1].
266 * Depending on the old vs new size, it's considered as an allocation or a free
267 * (or neither if the size remains the same).
268 */
269void *realloc(void *ptr, size_t size)
270{
271 struct memprof_stats *bin;
272 size_t size_before;
273 void *ret;
274
275 if (likely(!(profiling & HA_PROF_MEMORY)))
276 return memprof_realloc_handler(ptr, size);
277
278 size_before = malloc_usable_size(ptr);
279 ret = memprof_realloc_handler(ptr, size);
280 size = malloc_usable_size(ptr);
281
282 bin = memprof_get_bin(__builtin_return_address(0));
283 if (size > size_before) {
284 _HA_ATOMIC_ADD(&bin->alloc_calls, 1);
285 _HA_ATOMIC_ADD(&bin->alloc_tot, size);
286 } else if (size < size_before) {
287 _HA_ATOMIC_ADD(&bin->free_calls, 1);
288 _HA_ATOMIC_ADD(&bin->free_tot, size_before);
289 }
290 return ret;
291}
292
293/* This is the new global free() function. It must optimize for the normal
294 * case (i.e. profiling disabled) hence the first test to permit a direct jump.
295 * It must remain simple to guarantee the lack of reentrance. stdio is not
296 * possible there even for debugging. The reported size is the really allocated
297 * one as returned by malloc_usable_size(), because this will allow it to be
298 * compared to the one before realloc() or free(). This is a GNU and jemalloc
299 * extension but other systems may also store this size in ptr[-1]. Since
300 * free() is often called on NULL pointers to collect garbage at the end of
301 * many functions or during config parsing, as a special case free(NULL)
302 * doesn't update any stats.
303 */
304void free(void *ptr)
305{
306 struct memprof_stats *bin;
307 size_t size_before;
308
309 if (likely(!(profiling & HA_PROF_MEMORY) || !ptr)) {
310 memprof_free_handler(ptr);
311 return;
312 }
313
314 size_before = malloc_usable_size(ptr);
315 memprof_free_handler(ptr);
316
317 bin = memprof_get_bin(__builtin_return_address(0));
318 _HA_ATOMIC_ADD(&bin->free_calls, 1);
319 _HA_ATOMIC_ADD(&bin->free_tot, size_before);
320}
321
Willy Tarreaudb87fc72021-05-05 16:50:40 +0200322#endif // USE_MEMORY_PROFILING
323
Willy Tarreau609aad92018-11-22 08:31:09 +0100324/* Updates the current thread's statistics about stolen CPU time. The unit for
325 * <stolen> is half-milliseconds.
326 */
327void report_stolen_time(uint64_t stolen)
328{
329 activity[tid].cpust_total += stolen;
330 update_freq_ctr(&activity[tid].cpust_1s, stolen);
331 update_freq_ctr_period(&activity[tid].cpust_15s, 15000, stolen);
332}
Willy Tarreau75c62c22018-11-22 11:02:09 +0100333
334/* config parser for global "profiling.tasks", accepts "on" or "off" */
335static int cfg_parse_prof_tasks(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +0100336 const struct proxy *defpx, const char *file, int line,
Willy Tarreau75c62c22018-11-22 11:02:09 +0100337 char **err)
338{
339 if (too_many_args(1, args, err, NULL))
340 return -1;
341
342 if (strcmp(args[1], "on") == 0)
Willy Tarreaud2d33482019-04-25 17:09:07 +0200343 profiling = (profiling & ~HA_PROF_TASKS_MASK) | HA_PROF_TASKS_ON;
344 else if (strcmp(args[1], "auto") == 0)
Willy Tarreauaa622b82021-01-28 21:44:22 +0100345 profiling = (profiling & ~HA_PROF_TASKS_MASK) | HA_PROF_TASKS_AOFF;
Willy Tarreau75c62c22018-11-22 11:02:09 +0100346 else if (strcmp(args[1], "off") == 0)
Willy Tarreaud2d33482019-04-25 17:09:07 +0200347 profiling = (profiling & ~HA_PROF_TASKS_MASK) | HA_PROF_TASKS_OFF;
Willy Tarreau75c62c22018-11-22 11:02:09 +0100348 else {
Willy Tarreaud2d33482019-04-25 17:09:07 +0200349 memprintf(err, "'%s' expects either 'on', 'auto', or 'off' but got '%s'.", args[0], args[1]);
Willy Tarreau75c62c22018-11-22 11:02:09 +0100350 return -1;
351 }
352 return 0;
353}
354
355/* parse a "set profiling" command. It always returns 1. */
356static int cli_parse_set_profiling(char **args, char *payload, struct appctx *appctx, void *private)
357{
Willy Tarreau75c62c22018-11-22 11:02:09 +0100358 if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
359 return 1;
360
Willy Tarreau00dd44f2021-05-05 16:44:23 +0200361 if (strcmp(args[2], "memory") == 0) {
Willy Tarreaudb87fc72021-05-05 16:50:40 +0200362#ifdef USE_MEMORY_PROFILING
363 if (strcmp(args[3], "on") == 0) {
364 unsigned int old = profiling;
365 int i;
366
367 while (!_HA_ATOMIC_CAS(&profiling, &old, old | HA_PROF_MEMORY))
368 ;
369
370 /* also flush current profiling stats */
371 for (i = 0; i < sizeof(memprof_stats) / sizeof(memprof_stats[0]); i++) {
372 HA_ATOMIC_STORE(&memprof_stats[i].alloc_calls, 0);
373 HA_ATOMIC_STORE(&memprof_stats[i].free_calls, 0);
374 HA_ATOMIC_STORE(&memprof_stats[i].alloc_tot, 0);
375 HA_ATOMIC_STORE(&memprof_stats[i].free_tot, 0);
376 HA_ATOMIC_STORE(&memprof_stats[i].caller, NULL);
377 }
378 }
379 else if (strcmp(args[3], "off") == 0) {
380 unsigned int old = profiling;
381
382 while (!_HA_ATOMIC_CAS(&profiling, &old, old & ~HA_PROF_MEMORY))
383 ;
384 }
385 else
386 return cli_err(appctx, "Expects either 'on' or 'off'.\n");
387 return 1;
388#else
Willy Tarreau00dd44f2021-05-05 16:44:23 +0200389 return cli_err(appctx, "Memory profiling not compiled in.\n");
Willy Tarreaudb87fc72021-05-05 16:50:40 +0200390#endif
Willy Tarreau00dd44f2021-05-05 16:44:23 +0200391 }
392
Willy Tarreau9d008692019-08-09 11:21:01 +0200393 if (strcmp(args[2], "tasks") != 0)
Willy Tarreau00dd44f2021-05-05 16:44:23 +0200394 return cli_err(appctx, "Expects etiher 'tasks' or 'memory'.\n");
Willy Tarreau75c62c22018-11-22 11:02:09 +0100395
Willy Tarreaud2d33482019-04-25 17:09:07 +0200396 if (strcmp(args[3], "on") == 0) {
397 unsigned int old = profiling;
Willy Tarreaucfa71012021-01-29 11:56:21 +0100398 int i;
399
Willy Tarreaud2d33482019-04-25 17:09:07 +0200400 while (!_HA_ATOMIC_CAS(&profiling, &old, (old & ~HA_PROF_TASKS_MASK) | HA_PROF_TASKS_ON))
401 ;
Willy Tarreaucfa71012021-01-29 11:56:21 +0100402 /* also flush current profiling stats */
403 for (i = 0; i < 256; i++) {
404 HA_ATOMIC_STORE(&sched_activity[i].calls, 0);
405 HA_ATOMIC_STORE(&sched_activity[i].cpu_time, 0);
406 HA_ATOMIC_STORE(&sched_activity[i].lat_time, 0);
407 HA_ATOMIC_STORE(&sched_activity[i].func, NULL);
408 }
Willy Tarreaud2d33482019-04-25 17:09:07 +0200409 }
410 else if (strcmp(args[3], "auto") == 0) {
411 unsigned int old = profiling;
Willy Tarreauaa622b82021-01-28 21:44:22 +0100412 unsigned int new;
413
414 do {
415 if ((old & HA_PROF_TASKS_MASK) >= HA_PROF_TASKS_AON)
416 new = (old & ~HA_PROF_TASKS_MASK) | HA_PROF_TASKS_AON;
417 else
418 new = (old & ~HA_PROF_TASKS_MASK) | HA_PROF_TASKS_AOFF;
419 } while (!_HA_ATOMIC_CAS(&profiling, &old, new));
Willy Tarreaud2d33482019-04-25 17:09:07 +0200420 }
421 else if (strcmp(args[3], "off") == 0) {
422 unsigned int old = profiling;
423 while (!_HA_ATOMIC_CAS(&profiling, &old, (old & ~HA_PROF_TASKS_MASK) | HA_PROF_TASKS_OFF))
424 ;
425 }
Willy Tarreau9d008692019-08-09 11:21:01 +0200426 else
427 return cli_err(appctx, "Expects 'on', 'auto', or 'off'.\n");
428
Willy Tarreau75c62c22018-11-22 11:02:09 +0100429 return 1;
430}
431
Willy Tarreau1bd67e92021-01-29 00:07:40 +0100432static int cmp_sched_activity(const void *a, const void *b)
433{
434 const struct sched_activity *l = (const struct sched_activity *)a;
435 const struct sched_activity *r = (const struct sched_activity *)b;
436
437 if (l->calls > r->calls)
438 return -1;
439 else if (l->calls < r->calls)
440 return 1;
441 else
442 return 0;
443}
444
Willy Tarreau75c62c22018-11-22 11:02:09 +0100445/* This function dumps all profiling settings. It returns 0 if the output
446 * buffer is full and it needs to be called again, otherwise non-zero.
447 */
448static int cli_io_handler_show_profiling(struct appctx *appctx)
449{
Willy Tarreau1bd67e92021-01-29 00:07:40 +0100450 struct sched_activity tmp_activity[256] __attribute__((aligned(64)));
Willy Tarreau75c62c22018-11-22 11:02:09 +0100451 struct stream_interface *si = appctx->owner;
Willy Tarreau1bd67e92021-01-29 00:07:40 +0100452 struct buffer *name_buffer = get_trash_chunk();
Willy Tarreaud2d33482019-04-25 17:09:07 +0200453 const char *str;
Willy Tarreau1bd67e92021-01-29 00:07:40 +0100454 int i, max;
Willy Tarreau75c62c22018-11-22 11:02:09 +0100455
456 if (unlikely(si_ic(si)->flags & (CF_WRITE_ERROR|CF_SHUTW)))
457 return 1;
458
459 chunk_reset(&trash);
460
Willy Tarreaud2d33482019-04-25 17:09:07 +0200461 switch (profiling & HA_PROF_TASKS_MASK) {
Willy Tarreauaa622b82021-01-28 21:44:22 +0100462 case HA_PROF_TASKS_AOFF: str="auto-off"; break;
463 case HA_PROF_TASKS_AON: str="auto-on"; break;
Willy Tarreaud2d33482019-04-25 17:09:07 +0200464 case HA_PROF_TASKS_ON: str="on"; break;
465 default: str="off"; break;
466 }
467
Willy Tarreau1bd67e92021-01-29 00:07:40 +0100468 memcpy(tmp_activity, sched_activity, sizeof(tmp_activity));
469 qsort(tmp_activity, 256, sizeof(tmp_activity[0]), cmp_sched_activity);
470
Willy Tarreaud2d33482019-04-25 17:09:07 +0200471 chunk_printf(&trash,
Willy Tarreau00dd44f2021-05-05 16:44:23 +0200472 "Per-task CPU profiling : %-8s # set profiling tasks {on|auto|off}\n"
473 "Memory usage profiling : %-8s # set profiling memory {on|off}\n",
474 str, (profiling & HA_PROF_MEMORY) ? "on" : "off");
Willy Tarreau75c62c22018-11-22 11:02:09 +0100475
Willy Tarreau1bd67e92021-01-29 00:07:40 +0100476 chunk_appendf(&trash, "Tasks activity:\n"
477 " function calls cpu_tot cpu_avg lat_tot lat_avg\n");
478
479 for (i = 0; i < 256 && tmp_activity[i].calls; i++) {
480 chunk_reset(name_buffer);
481
482 if (!tmp_activity[i].func)
483 chunk_printf(name_buffer, "other");
484 else
485 resolve_sym_name(name_buffer, "", tmp_activity[i].func);
486
487 /* reserve 35 chars for name+' '+#calls, knowing that longer names
488 * are often used for less often called functions.
489 */
490 max = 35 - name_buffer->data;
491 if (max < 1)
492 max = 1;
493 chunk_appendf(&trash, " %s%*llu", name_buffer->area, max, (unsigned long long)tmp_activity[i].calls);
494
495 print_time_short(&trash, " ", tmp_activity[i].cpu_time, "");
496 print_time_short(&trash, " ", tmp_activity[i].cpu_time / tmp_activity[i].calls, "");
497 print_time_short(&trash, " ", tmp_activity[i].lat_time, "");
498 print_time_short(&trash, " ", tmp_activity[i].lat_time / tmp_activity[i].calls, "\n");
499 }
500
Willy Tarreau75c62c22018-11-22 11:02:09 +0100501 if (ci_putchk(si_ic(si), &trash) == -1) {
502 /* failed, try again */
503 si_rx_room_blk(si);
504 return 0;
505 }
506 return 1;
507}
508
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100509/* This function scans all threads' run queues and collects statistics about
510 * running tasks. It returns 0 if the output buffer is full and it needs to be
511 * called again, otherwise non-zero.
512 */
513static int cli_io_handler_show_tasks(struct appctx *appctx)
514{
515 struct sched_activity tmp_activity[256] __attribute__((aligned(64)));
516 struct stream_interface *si = appctx->owner;
517 struct buffer *name_buffer = get_trash_chunk();
518 struct sched_activity *entry;
519 const struct tasklet *tl;
520 const struct task *t;
521 uint64_t now_ns, lat;
522 struct eb32sc_node *rqnode;
523 uint64_t tot_calls;
524 int thr, queue;
525 int i, max;
526
527 if (unlikely(si_ic(si)->flags & (CF_WRITE_ERROR|CF_SHUTW)))
528 return 1;
529
530 /* It's not possible to scan queues in small chunks and yield in the
531 * middle of the dump and come back again. So what we're doing instead
532 * is to freeze all threads and inspect their queues at once as fast as
533 * possible, using a sched_activity array to collect metrics with
534 * limited collision, then we'll report statistics only. The tasks'
535 * #calls will reflect the number of occurrences, and the lat_time will
Willy Tarreau75f72332021-01-29 15:04:16 +0100536 * reflect the latency when set. We prefer to take the time before
537 * calling thread_isolate() so that the wait time doesn't impact the
538 * measurement accuracy. However this requires to take care of negative
539 * times since tasks might be queued after we retrieve it.
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100540 */
541
542 now_ns = now_mono_time();
543 memset(tmp_activity, 0, sizeof(tmp_activity));
544
545 thread_isolate();
546
547 /* 1. global run queue */
548
549#ifdef USE_THREAD
550 rqnode = eb32sc_first(&rqueue, ~0UL);
551 while (rqnode) {
552 t = eb32sc_entry(rqnode, struct task, rq);
553 entry = sched_activity_entry(tmp_activity, t->process);
554 if (t->call_date) {
555 lat = now_ns - t->call_date;
Willy Tarreau75f72332021-01-29 15:04:16 +0100556 if ((int64_t)lat > 0)
557 entry->lat_time += lat;
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100558 }
559 entry->calls++;
560 rqnode = eb32sc_next(rqnode, ~0UL);
561 }
562#endif
563 /* 2. all threads's local run queues */
564 for (thr = 0; thr < global.nbthread; thr++) {
565 /* task run queue */
566 rqnode = eb32sc_first(&task_per_thread[thr].rqueue, ~0UL);
567 while (rqnode) {
568 t = eb32sc_entry(rqnode, struct task, rq);
569 entry = sched_activity_entry(tmp_activity, t->process);
570 if (t->call_date) {
571 lat = now_ns - t->call_date;
Willy Tarreau75f72332021-01-29 15:04:16 +0100572 if ((int64_t)lat > 0)
573 entry->lat_time += lat;
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100574 }
575 entry->calls++;
576 rqnode = eb32sc_next(rqnode, ~0UL);
577 }
578
579 /* shared tasklet list */
580 list_for_each_entry(tl, mt_list_to_list(&task_per_thread[thr].shared_tasklet_list), list) {
581 t = (const struct task *)tl;
582 entry = sched_activity_entry(tmp_activity, t->process);
583 if (!TASK_IS_TASKLET(t) && t->call_date) {
584 lat = now_ns - t->call_date;
Willy Tarreau75f72332021-01-29 15:04:16 +0100585 if ((int64_t)lat > 0)
586 entry->lat_time += lat;
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100587 }
588 entry->calls++;
589 }
590
591 /* classful tasklets */
592 for (queue = 0; queue < TL_CLASSES; queue++) {
593 list_for_each_entry(tl, &task_per_thread[thr].tasklets[queue], list) {
594 t = (const struct task *)tl;
595 entry = sched_activity_entry(tmp_activity, t->process);
596 if (!TASK_IS_TASKLET(t) && t->call_date) {
597 lat = now_ns - t->call_date;
Willy Tarreau75f72332021-01-29 15:04:16 +0100598 if ((int64_t)lat > 0)
599 entry->lat_time += lat;
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100600 }
601 entry->calls++;
602 }
603 }
604 }
605
606 /* hopefully we're done */
607 thread_release();
608
609 chunk_reset(&trash);
610
611 tot_calls = 0;
612 for (i = 0; i < 256; i++)
613 tot_calls += tmp_activity[i].calls;
614
615 qsort(tmp_activity, 256, sizeof(tmp_activity[0]), cmp_sched_activity);
616
617 chunk_appendf(&trash, "Running tasks: %d (%d threads)\n"
618 " function places %% lat_tot lat_avg\n",
619 (int)tot_calls, global.nbthread);
620
621 for (i = 0; i < 256 && tmp_activity[i].calls; i++) {
622 chunk_reset(name_buffer);
623
624 if (!tmp_activity[i].func)
625 chunk_printf(name_buffer, "other");
626 else
627 resolve_sym_name(name_buffer, "", tmp_activity[i].func);
628
629 /* reserve 35 chars for name+' '+#calls, knowing that longer names
630 * are often used for less often called functions.
631 */
632 max = 35 - name_buffer->data;
633 if (max < 1)
634 max = 1;
635 chunk_appendf(&trash, " %s%*llu %3d.%1d",
636 name_buffer->area, max, (unsigned long long)tmp_activity[i].calls,
637 (int)(100ULL * tmp_activity[i].calls / tot_calls),
638 (int)((1000ULL * tmp_activity[i].calls / tot_calls)%10));
639 print_time_short(&trash, " ", tmp_activity[i].lat_time, "");
640 print_time_short(&trash, " ", tmp_activity[i].lat_time / tmp_activity[i].calls, "\n");
641 }
642
643 if (ci_putchk(si_ic(si), &trash) == -1) {
644 /* failed, try again */
645 si_rx_room_blk(si);
646 return 0;
647 }
648 return 1;
649}
650
Willy Tarreau75c62c22018-11-22 11:02:09 +0100651/* config keyword parsers */
652static struct cfg_kw_list cfg_kws = {ILH, {
653 { CFG_GLOBAL, "profiling.tasks", cfg_parse_prof_tasks },
654 { 0, NULL, NULL }
655}};
656
Willy Tarreau0108d902018-11-25 19:14:37 +0100657INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
658
Willy Tarreau75c62c22018-11-22 11:02:09 +0100659/* register cli keywords */
660static struct cli_kw_list cli_kws = {{ },{
661 { { "show", "profiling", NULL }, "show profiling : show CPU profiling options", NULL, cli_io_handler_show_profiling, NULL },
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100662 { { "show", "tasks", NULL }, "show tasks : show running tasks", NULL, cli_io_handler_show_tasks, NULL },
Willy Tarreau00dd44f2021-05-05 16:44:23 +0200663 { { "set", "profiling", NULL }, "set profiling : enable/disable resource profiling", cli_parse_set_profiling, NULL },
Willy Tarreau75c62c22018-11-22 11:02:09 +0100664 {{},}
665}};
666
Willy Tarreau0108d902018-11-25 19:14:37 +0100667INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);