blob: 0cb48361bf577823237d395d35d5534f8ffa4922 [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.
Willy Tarreau637d85a2021-05-05 17:33:27 +0200447 * It dumps some parts depending on the following states:
448 * ctx.cli.i0:
449 * 0, 4: dump status, then jump to 1 if 0
450 * 1, 5: dump tasks, then jump to 2 if 1
451 * 2, 6: dump memory, then stop
452 * ctx.cli.i1:
453 * restart line for each step (starts at zero)
454 * ctx.cli.o0:
455 * may contain a configured max line count for each step (0=not set)
Willy Tarreau75c62c22018-11-22 11:02:09 +0100456 */
457static int cli_io_handler_show_profiling(struct appctx *appctx)
458{
Willy Tarreau1bd67e92021-01-29 00:07:40 +0100459 struct sched_activity tmp_activity[256] __attribute__((aligned(64)));
Willy Tarreau75c62c22018-11-22 11:02:09 +0100460 struct stream_interface *si = appctx->owner;
Willy Tarreau1bd67e92021-01-29 00:07:40 +0100461 struct buffer *name_buffer = get_trash_chunk();
Willy Tarreaud2d33482019-04-25 17:09:07 +0200462 const char *str;
Willy Tarreau637d85a2021-05-05 17:33:27 +0200463 int max_lines;
Willy Tarreau1bd67e92021-01-29 00:07:40 +0100464 int i, max;
Willy Tarreau75c62c22018-11-22 11:02:09 +0100465
466 if (unlikely(si_ic(si)->flags & (CF_WRITE_ERROR|CF_SHUTW)))
467 return 1;
468
469 chunk_reset(&trash);
470
Willy Tarreaud2d33482019-04-25 17:09:07 +0200471 switch (profiling & HA_PROF_TASKS_MASK) {
Willy Tarreauaa622b82021-01-28 21:44:22 +0100472 case HA_PROF_TASKS_AOFF: str="auto-off"; break;
473 case HA_PROF_TASKS_AON: str="auto-on"; break;
Willy Tarreaud2d33482019-04-25 17:09:07 +0200474 case HA_PROF_TASKS_ON: str="on"; break;
475 default: str="off"; break;
476 }
477
Willy Tarreau637d85a2021-05-05 17:33:27 +0200478 if ((appctx->ctx.cli.i0 & 3) != 0)
479 goto skip_status;
Willy Tarreau1bd67e92021-01-29 00:07:40 +0100480
Willy Tarreaud2d33482019-04-25 17:09:07 +0200481 chunk_printf(&trash,
Willy Tarreau00dd44f2021-05-05 16:44:23 +0200482 "Per-task CPU profiling : %-8s # set profiling tasks {on|auto|off}\n"
483 "Memory usage profiling : %-8s # set profiling memory {on|off}\n",
484 str, (profiling & HA_PROF_MEMORY) ? "on" : "off");
Willy Tarreau75c62c22018-11-22 11:02:09 +0100485
Willy Tarreau637d85a2021-05-05 17:33:27 +0200486 if (ci_putchk(si_ic(si), &trash) == -1) {
487 /* failed, try again */
488 si_rx_room_blk(si);
489 return 0;
490 }
491
492 appctx->ctx.cli.i1 = 0; // reset first line to dump
493 if ((appctx->ctx.cli.i0 & 4) == 0)
494 appctx->ctx.cli.i0++; // next step
495
496 skip_status:
497 if ((appctx->ctx.cli.i0 & 3) != 1)
498 goto skip_tasks;
Willy Tarreau1bd67e92021-01-29 00:07:40 +0100499
Willy Tarreau637d85a2021-05-05 17:33:27 +0200500 memcpy(tmp_activity, sched_activity, sizeof(tmp_activity));
501 qsort(tmp_activity, 256, sizeof(tmp_activity[0]), cmp_sched_activity);
502
503 if (!appctx->ctx.cli.i1)
504 chunk_appendf(&trash, "Tasks activity:\n"
505 " function calls cpu_tot cpu_avg lat_tot lat_avg\n");
506
507 max_lines = appctx->ctx.cli.o0;
508 if (!max_lines)
509 max_lines = 256;
510
511 for (i = appctx->ctx.cli.i1; i < max_lines && tmp_activity[i].calls; i++) {
512 appctx->ctx.cli.i1 = i;
Willy Tarreau1bd67e92021-01-29 00:07:40 +0100513 chunk_reset(name_buffer);
514
515 if (!tmp_activity[i].func)
516 chunk_printf(name_buffer, "other");
517 else
518 resolve_sym_name(name_buffer, "", tmp_activity[i].func);
519
520 /* reserve 35 chars for name+' '+#calls, knowing that longer names
521 * are often used for less often called functions.
522 */
523 max = 35 - name_buffer->data;
524 if (max < 1)
525 max = 1;
526 chunk_appendf(&trash, " %s%*llu", name_buffer->area, max, (unsigned long long)tmp_activity[i].calls);
527
528 print_time_short(&trash, " ", tmp_activity[i].cpu_time, "");
529 print_time_short(&trash, " ", tmp_activity[i].cpu_time / tmp_activity[i].calls, "");
530 print_time_short(&trash, " ", tmp_activity[i].lat_time, "");
531 print_time_short(&trash, " ", tmp_activity[i].lat_time / tmp_activity[i].calls, "\n");
Willy Tarreau637d85a2021-05-05 17:33:27 +0200532
533 if (ci_putchk(si_ic(si), &trash) == -1) {
534 /* failed, try again */
535 si_rx_room_blk(si);
536 return 0;
537 }
Willy Tarreau1bd67e92021-01-29 00:07:40 +0100538 }
539
Willy Tarreau75c62c22018-11-22 11:02:09 +0100540 if (ci_putchk(si_ic(si), &trash) == -1) {
541 /* failed, try again */
542 si_rx_room_blk(si);
543 return 0;
544 }
Willy Tarreau637d85a2021-05-05 17:33:27 +0200545
546 appctx->ctx.cli.i1 = 0; // reset first line to dump
547 if ((appctx->ctx.cli.i0 & 4) == 0)
548 appctx->ctx.cli.i0++; // next step
549
550 skip_tasks:
551
Willy Tarreau75c62c22018-11-22 11:02:09 +0100552 return 1;
553}
554
Willy Tarreau42712cb2021-05-05 17:48:13 +0200555/* parse a "show profiling" command. It returns 1 on failure, 0 if it starts to dump. */
556static int cli_parse_show_profiling(char **args, char *payload, struct appctx *appctx, void *private)
557{
558 if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
559 return 1;
560
561 if (strcmp(args[2], "all") == 0) {
562 appctx->ctx.cli.i0 = 0; // will cycle through 0,1,2; default
563 args++;
564 }
565 else if (strcmp(args[2], "status") == 0) {
566 appctx->ctx.cli.i0 = 4; // will visit status only
567 args++;
568 }
569 else if (strcmp(args[2], "tasks") == 0) {
570 appctx->ctx.cli.i0 = 5; // will visit tasks only
571 args++;
572 }
573 else if (strcmp(args[2], "memory") == 0) {
574 appctx->ctx.cli.i0 = 6; // will visit memory only
575 args++;
576 }
577 else if (*args[2] && !isdigit((unsigned char)*args[2]))
578 return cli_err(appctx, "Expects either 'all', 'status', 'tasks' or 'memory'.\n");
579
580 if (*args[2]) {
581 /* Second arg may set a limit to number of entries to dump; default is
582 * not set and means no limit.
583 */
584 appctx->ctx.cli.o0 = atoi(args[2]);
585 }
586 return 0;
587}
588
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100589/* This function scans all threads' run queues and collects statistics about
590 * running tasks. It returns 0 if the output buffer is full and it needs to be
591 * called again, otherwise non-zero.
592 */
593static int cli_io_handler_show_tasks(struct appctx *appctx)
594{
595 struct sched_activity tmp_activity[256] __attribute__((aligned(64)));
596 struct stream_interface *si = appctx->owner;
597 struct buffer *name_buffer = get_trash_chunk();
598 struct sched_activity *entry;
599 const struct tasklet *tl;
600 const struct task *t;
601 uint64_t now_ns, lat;
602 struct eb32sc_node *rqnode;
603 uint64_t tot_calls;
604 int thr, queue;
605 int i, max;
606
607 if (unlikely(si_ic(si)->flags & (CF_WRITE_ERROR|CF_SHUTW)))
608 return 1;
609
610 /* It's not possible to scan queues in small chunks and yield in the
611 * middle of the dump and come back again. So what we're doing instead
612 * is to freeze all threads and inspect their queues at once as fast as
613 * possible, using a sched_activity array to collect metrics with
614 * limited collision, then we'll report statistics only. The tasks'
615 * #calls will reflect the number of occurrences, and the lat_time will
Willy Tarreau75f72332021-01-29 15:04:16 +0100616 * reflect the latency when set. We prefer to take the time before
617 * calling thread_isolate() so that the wait time doesn't impact the
618 * measurement accuracy. However this requires to take care of negative
619 * times since tasks might be queued after we retrieve it.
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100620 */
621
622 now_ns = now_mono_time();
623 memset(tmp_activity, 0, sizeof(tmp_activity));
624
625 thread_isolate();
626
627 /* 1. global run queue */
628
629#ifdef USE_THREAD
630 rqnode = eb32sc_first(&rqueue, ~0UL);
631 while (rqnode) {
632 t = eb32sc_entry(rqnode, struct task, rq);
633 entry = sched_activity_entry(tmp_activity, t->process);
634 if (t->call_date) {
635 lat = now_ns - t->call_date;
Willy Tarreau75f72332021-01-29 15:04:16 +0100636 if ((int64_t)lat > 0)
637 entry->lat_time += lat;
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100638 }
639 entry->calls++;
640 rqnode = eb32sc_next(rqnode, ~0UL);
641 }
642#endif
643 /* 2. all threads's local run queues */
644 for (thr = 0; thr < global.nbthread; thr++) {
645 /* task run queue */
646 rqnode = eb32sc_first(&task_per_thread[thr].rqueue, ~0UL);
647 while (rqnode) {
648 t = eb32sc_entry(rqnode, struct task, rq);
649 entry = sched_activity_entry(tmp_activity, t->process);
650 if (t->call_date) {
651 lat = now_ns - t->call_date;
Willy Tarreau75f72332021-01-29 15:04:16 +0100652 if ((int64_t)lat > 0)
653 entry->lat_time += lat;
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100654 }
655 entry->calls++;
656 rqnode = eb32sc_next(rqnode, ~0UL);
657 }
658
659 /* shared tasklet list */
660 list_for_each_entry(tl, mt_list_to_list(&task_per_thread[thr].shared_tasklet_list), list) {
661 t = (const struct task *)tl;
662 entry = sched_activity_entry(tmp_activity, t->process);
663 if (!TASK_IS_TASKLET(t) && t->call_date) {
664 lat = now_ns - t->call_date;
Willy Tarreau75f72332021-01-29 15:04:16 +0100665 if ((int64_t)lat > 0)
666 entry->lat_time += lat;
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100667 }
668 entry->calls++;
669 }
670
671 /* classful tasklets */
672 for (queue = 0; queue < TL_CLASSES; queue++) {
673 list_for_each_entry(tl, &task_per_thread[thr].tasklets[queue], list) {
674 t = (const struct task *)tl;
675 entry = sched_activity_entry(tmp_activity, t->process);
676 if (!TASK_IS_TASKLET(t) && t->call_date) {
677 lat = now_ns - t->call_date;
Willy Tarreau75f72332021-01-29 15:04:16 +0100678 if ((int64_t)lat > 0)
679 entry->lat_time += lat;
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100680 }
681 entry->calls++;
682 }
683 }
684 }
685
686 /* hopefully we're done */
687 thread_release();
688
689 chunk_reset(&trash);
690
691 tot_calls = 0;
692 for (i = 0; i < 256; i++)
693 tot_calls += tmp_activity[i].calls;
694
695 qsort(tmp_activity, 256, sizeof(tmp_activity[0]), cmp_sched_activity);
696
697 chunk_appendf(&trash, "Running tasks: %d (%d threads)\n"
698 " function places %% lat_tot lat_avg\n",
699 (int)tot_calls, global.nbthread);
700
701 for (i = 0; i < 256 && tmp_activity[i].calls; i++) {
702 chunk_reset(name_buffer);
703
704 if (!tmp_activity[i].func)
705 chunk_printf(name_buffer, "other");
706 else
707 resolve_sym_name(name_buffer, "", tmp_activity[i].func);
708
709 /* reserve 35 chars for name+' '+#calls, knowing that longer names
710 * are often used for less often called functions.
711 */
712 max = 35 - name_buffer->data;
713 if (max < 1)
714 max = 1;
715 chunk_appendf(&trash, " %s%*llu %3d.%1d",
716 name_buffer->area, max, (unsigned long long)tmp_activity[i].calls,
717 (int)(100ULL * tmp_activity[i].calls / tot_calls),
718 (int)((1000ULL * tmp_activity[i].calls / tot_calls)%10));
719 print_time_short(&trash, " ", tmp_activity[i].lat_time, "");
720 print_time_short(&trash, " ", tmp_activity[i].lat_time / tmp_activity[i].calls, "\n");
721 }
722
723 if (ci_putchk(si_ic(si), &trash) == -1) {
724 /* failed, try again */
725 si_rx_room_blk(si);
726 return 0;
727 }
728 return 1;
729}
730
Willy Tarreau75c62c22018-11-22 11:02:09 +0100731/* config keyword parsers */
732static struct cfg_kw_list cfg_kws = {ILH, {
733 { CFG_GLOBAL, "profiling.tasks", cfg_parse_prof_tasks },
734 { 0, NULL, NULL }
735}};
736
Willy Tarreau0108d902018-11-25 19:14:37 +0100737INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
738
Willy Tarreau75c62c22018-11-22 11:02:09 +0100739/* register cli keywords */
740static struct cli_kw_list cli_kws = {{ },{
Willy Tarreau42712cb2021-05-05 17:48:13 +0200741 { { "show", "profiling", NULL }, "show profiling : show CPU profiling options", cli_parse_show_profiling, cli_io_handler_show_profiling, NULL },
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100742 { { "show", "tasks", NULL }, "show tasks : show running tasks", NULL, cli_io_handler_show_tasks, NULL },
Willy Tarreau00dd44f2021-05-05 16:44:23 +0200743 { { "set", "profiling", NULL }, "set profiling : enable/disable resource profiling", cli_parse_set_profiling, NULL },
Willy Tarreau75c62c22018-11-22 11:02:09 +0100744 {{},}
745}};
746
Willy Tarreau0108d902018-11-25 19:14:37 +0100747INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);