blob: 2638022d4794351a90ea3bd9b23f02854466719a [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 Tarreaub2551052020-06-09 09:07:15 +020013#include <haproxy/activity-t.h>
Willy Tarreau4c7e4b72020-05-27 12:58:42 +020014#include <haproxy/api.h>
Willy Tarreaue8d006a2022-05-05 14:19:00 +020015#include <haproxy/applet.h>
Willy Tarreau6be78492020-06-05 00:00:29 +020016#include <haproxy/cfgparse.h>
Willy Tarreau55542642021-10-08 09:33:24 +020017#include <haproxy/clock.h>
Willy Tarreauf1d32c42020-06-04 21:07:02 +020018#include <haproxy/channel.h>
Willy Tarreau83487a82020-06-04 20:19:54 +020019#include <haproxy/cli.h>
Christopher Faulet908628c2022-03-25 16:43:49 +010020#include <haproxy/conn_stream.h>
21#include <haproxy/cs_utils.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020022#include <haproxy/freq_ctr.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020023#include <haproxy/tools.h>
Willy Tarreaua26be372021-10-06 16:26:33 +020024#include <haproxy/xxhash.h>
Willy Tarreau75c62c22018-11-22 11:02:09 +010025
Willy Tarreaue8d006a2022-05-05 14:19:00 +020026/* CLI context for the "show profiling" command */
27struct show_prof_ctx {
28 int dump_step; /* 0,1,2,4,5,6; see cli_iohandler_show_profiling() */
29 int linenum; /* next line to be dumped (starts at 0) */
30 int maxcnt; /* max line count per step (0=not set) */
31 int by_addr; /* 0=sort by usage, 1=sort by address */
32};
33
Willy Tarreauf93c7be2021-05-05 17:07:09 +020034#if defined(DEBUG_MEM_STATS)
35/* these ones are macros in bug.h when DEBUG_MEM_STATS is set, and will
36 * prevent the new ones from being redefined.
37 */
38#undef calloc
39#undef malloc
40#undef realloc
41#endif
Willy Tarreau75c62c22018-11-22 11:02:09 +010042
43/* bit field of profiling options. Beware, may be modified at runtime! */
Willy Tarreauef7380f2021-05-05 16:28:31 +020044unsigned int profiling __read_mostly = HA_PROF_TASKS_AOFF;
45unsigned long task_profiling_mask __read_mostly = 0;
Willy Tarreau609aad92018-11-22 08:31:09 +010046
47/* One struct per thread containing all collected measurements */
48struct activity activity[MAX_THREADS] __attribute__((aligned(64))) = { };
49
Willy Tarreau3fb6a7b2021-01-28 19:19:26 +010050/* One struct per function pointer hash entry (256 values, 0=collision) */
51struct sched_activity sched_activity[256] __attribute__((aligned(64))) = { };
Willy Tarreau609aad92018-11-22 08:31:09 +010052
Willy Tarreaudb87fc72021-05-05 16:50:40 +020053
Willy Tarreaue15615c2021-08-28 12:04:25 +020054#ifdef USE_MEMORY_PROFILING
Willy Tarreaudb87fc72021-05-05 16:50:40 +020055/* determine the number of buckets to store stats */
56#define MEMPROF_HASH_BITS 10
57#define MEMPROF_HASH_BUCKETS (1U << MEMPROF_HASH_BITS)
58
Willy Tarreau616491b2021-05-11 09:26:23 +020059enum memprof_method {
60 MEMPROF_METH_UNKNOWN = 0,
61 MEMPROF_METH_MALLOC,
62 MEMPROF_METH_CALLOC,
63 MEMPROF_METH_REALLOC,
64 MEMPROF_METH_FREE,
65 MEMPROF_METH_METHODS /* count, must be last */
66};
67
68static const char *const memprof_methods[MEMPROF_METH_METHODS] = {
69 "unknown", "malloc", "calloc", "realloc", "free",
70};
71
Willy Tarreaudb87fc72021-05-05 16:50:40 +020072/* stats:
73 * - malloc increases alloc
74 * - free increases free (if non null)
75 * - realloc increases either depending on the size change.
76 * when the real size is known (malloc_usable_size()), it's used in free_tot
77 * and alloc_tot, otherwise the requested size is reported in alloc_tot and
78 * zero in free_tot.
79 */
80struct memprof_stats {
81 const void *caller;
Willy Tarreau616491b2021-05-11 09:26:23 +020082 enum memprof_method method;
83 /* 4-7 bytes hole here */
Willy Tarreaudb87fc72021-05-05 16:50:40 +020084 unsigned long long alloc_calls;
85 unsigned long long free_calls;
86 unsigned long long alloc_tot;
87 unsigned long long free_tot;
88};
89
90/* last one is for hash collisions ("others") and has no caller address */
91struct memprof_stats memprof_stats[MEMPROF_HASH_BUCKETS + 1] = { };
92
Willy Tarreauf93c7be2021-05-05 17:07:09 +020093/* used to detect recursive calls */
94static THREAD_LOCAL int in_memprof = 0;
95
96/* perform a pointer hash by scrambling its bits and retrieving the most
97 * mixed ones (topmost ones in 32-bit, middle ones in 64-bit).
98 */
99static unsigned int memprof_hash_ptr(const void *p)
100{
101 unsigned long long x = (unsigned long)p;
102
103 x = 0xcbda9653U * x;
104 if (sizeof(long) == 4)
105 x >>= 32;
106 else
107 x >>= 33 - MEMPROF_HASH_BITS / 2;
108 return x & (MEMPROF_HASH_BUCKETS - 1);
109}
110
111/* These ones are used by glibc and will be called early. They are in charge of
112 * initializing the handlers with the original functions.
113 */
114static void *memprof_malloc_initial_handler(size_t size);
115static void *memprof_calloc_initial_handler(size_t nmemb, size_t size);
116static void *memprof_realloc_initial_handler(void *ptr, size_t size);
117static void memprof_free_initial_handler(void *ptr);
118
119/* Fallback handlers for the main alloc/free functions. They are preset to
120 * the initializer in order to save a test in the functions's critical path.
121 */
122static void *(*memprof_malloc_handler)(size_t size) = memprof_malloc_initial_handler;
123static void *(*memprof_calloc_handler)(size_t nmemb, size_t size) = memprof_calloc_initial_handler;
124static void *(*memprof_realloc_handler)(void *ptr, size_t size) = memprof_realloc_initial_handler;
125static void (*memprof_free_handler)(void *ptr) = memprof_free_initial_handler;
126
127/* Used to force to die if it's not possible to retrieve the allocation
128 * functions. We cannot even use stdio in this case.
129 */
130static __attribute__((noreturn)) void memprof_die(const char *msg)
131{
132 DISGUISE(write(2, msg, strlen(msg)));
133 exit(1);
134}
135
136/* Resolve original allocation functions and initialize all handlers.
137 * This must be called very early at boot, before the very first malloc()
138 * call, and is not thread-safe! It's not even possible to use stdio there.
139 * Worse, we have to account for the risk of reentrance from dlsym() when
140 * it tries to prepare its error messages. Here its ahndled by in_memprof
141 * that makes allocators return NULL. dlsym() handles it gracefully. An
Ilya Shipitsin3df59892021-05-10 12:50:00 +0500142 * alternate approach consists in calling aligned_alloc() from these places
Willy Tarreauf93c7be2021-05-05 17:07:09 +0200143 * but that would mean not being able to intercept it later if considered
144 * useful to do so.
145 */
146static void memprof_init()
147{
148 in_memprof++;
149 memprof_malloc_handler = get_sym_next_addr("malloc");
150 if (!memprof_malloc_handler)
151 memprof_die("FATAL: malloc() function not found.\n");
152
153 memprof_calloc_handler = get_sym_next_addr("calloc");
154 if (!memprof_calloc_handler)
155 memprof_die("FATAL: calloc() function not found.\n");
156
157 memprof_realloc_handler = get_sym_next_addr("realloc");
158 if (!memprof_realloc_handler)
159 memprof_die("FATAL: realloc() function not found.\n");
160
161 memprof_free_handler = get_sym_next_addr("free");
162 if (!memprof_free_handler)
163 memprof_die("FATAL: free() function not found.\n");
164 in_memprof--;
165}
166
167/* the initial handlers will initialize all regular handlers and will call the
168 * one they correspond to. A single one of these functions will typically be
169 * called, though it's unknown which one (as any might be called before main).
170 */
171static void *memprof_malloc_initial_handler(size_t size)
172{
173 if (in_memprof) {
174 /* it's likely that dlsym() needs malloc(), let's fail */
175 return NULL;
176 }
177
178 memprof_init();
179 return memprof_malloc_handler(size);
180}
181
182static void *memprof_calloc_initial_handler(size_t nmemb, size_t size)
183{
184 if (in_memprof) {
185 /* it's likely that dlsym() needs calloc(), let's fail */
186 return NULL;
187 }
188 memprof_init();
189 return memprof_calloc_handler(nmemb, size);
190}
191
192static void *memprof_realloc_initial_handler(void *ptr, size_t size)
193{
194 if (in_memprof) {
195 /* it's likely that dlsym() needs realloc(), let's fail */
196 return NULL;
197 }
198
199 memprof_init();
200 return memprof_realloc_handler(ptr, size);
201}
202
203static void memprof_free_initial_handler(void *ptr)
204{
205 memprof_init();
206 memprof_free_handler(ptr);
207}
208
209/* Assign a bin for the memprof_stats to the return address. May perform a few
210 * attempts before finding the right one, but always succeeds (in the worst
211 * case, returns a default bin). The caller address is atomically set except
212 * for the default one which is never set.
213 */
Willy Tarreau616491b2021-05-11 09:26:23 +0200214static struct memprof_stats *memprof_get_bin(const void *ra, enum memprof_method meth)
Willy Tarreauf93c7be2021-05-05 17:07:09 +0200215{
216 int retries = 16; // up to 16 consecutive entries may be tested.
Willy Tarreau4a753282021-05-09 23:18:50 +0200217 const void *old;
Willy Tarreauf93c7be2021-05-05 17:07:09 +0200218 unsigned int bin;
219
220 bin = memprof_hash_ptr(ra);
221 for (; memprof_stats[bin].caller != ra; bin = (bin + 1) & (MEMPROF_HASH_BUCKETS - 1)) {
222 if (!--retries) {
223 bin = MEMPROF_HASH_BUCKETS;
224 break;
225 }
226
227 old = NULL;
228 if (!memprof_stats[bin].caller &&
Willy Tarreau616491b2021-05-11 09:26:23 +0200229 HA_ATOMIC_CAS(&memprof_stats[bin].caller, &old, ra)) {
230 memprof_stats[bin].method = meth;
Willy Tarreauf93c7be2021-05-05 17:07:09 +0200231 break;
Willy Tarreau616491b2021-05-11 09:26:23 +0200232 }
Willy Tarreauf93c7be2021-05-05 17:07:09 +0200233 }
234 return &memprof_stats[bin];
235}
236
237/* This is the new global malloc() function. It must optimize for the normal
238 * case (i.e. profiling disabled) hence the first test to permit a direct jump.
239 * It must remain simple to guarantee the lack of reentrance. stdio is not
240 * possible there even for debugging. The reported size is the really allocated
241 * one as returned by malloc_usable_size(), because this will allow it to be
242 * compared to the one before realloc() or free(). This is a GNU and jemalloc
243 * extension but other systems may also store this size in ptr[-1].
244 */
245void *malloc(size_t size)
246{
247 struct memprof_stats *bin;
248 void *ret;
249
250 if (likely(!(profiling & HA_PROF_MEMORY)))
251 return memprof_malloc_handler(size);
252
253 ret = memprof_malloc_handler(size);
Willy Tarreau1de51eb2021-10-22 16:33:53 +0200254 size = malloc_usable_size(ret) + sizeof(void *);
Willy Tarreauf93c7be2021-05-05 17:07:09 +0200255
Willy Tarreau616491b2021-05-11 09:26:23 +0200256 bin = memprof_get_bin(__builtin_return_address(0), MEMPROF_METH_MALLOC);
Willy Tarreauf93c7be2021-05-05 17:07:09 +0200257 _HA_ATOMIC_ADD(&bin->alloc_calls, 1);
258 _HA_ATOMIC_ADD(&bin->alloc_tot, size);
259 return ret;
260}
261
262/* This is the new global calloc() function. It must optimize for the normal
263 * case (i.e. profiling disabled) hence the first test to permit a direct jump.
264 * It must remain simple to guarantee the lack of reentrance. stdio is not
265 * possible there even for debugging. The reported size is the really allocated
266 * one as returned by malloc_usable_size(), because this will allow it to be
267 * compared to the one before realloc() or free(). This is a GNU and jemalloc
268 * extension but other systems may also store this size in ptr[-1].
269 */
270void *calloc(size_t nmemb, size_t size)
271{
272 struct memprof_stats *bin;
273 void *ret;
274
275 if (likely(!(profiling & HA_PROF_MEMORY)))
276 return memprof_calloc_handler(nmemb, size);
277
278 ret = memprof_calloc_handler(nmemb, size);
Willy Tarreau1de51eb2021-10-22 16:33:53 +0200279 size = malloc_usable_size(ret) + sizeof(void *);
Willy Tarreauf93c7be2021-05-05 17:07:09 +0200280
Willy Tarreau616491b2021-05-11 09:26:23 +0200281 bin = memprof_get_bin(__builtin_return_address(0), MEMPROF_METH_CALLOC);
Willy Tarreauf93c7be2021-05-05 17:07:09 +0200282 _HA_ATOMIC_ADD(&bin->alloc_calls, 1);
283 _HA_ATOMIC_ADD(&bin->alloc_tot, size);
284 return ret;
285}
286
287/* This is the new global realloc() function. It must optimize for the normal
288 * case (i.e. profiling disabled) hence the first test to permit a direct jump.
289 * It must remain simple to guarantee the lack of reentrance. stdio is not
290 * possible there even for debugging. The reported size is the really allocated
291 * one as returned by malloc_usable_size(), because this will allow it to be
292 * compared to the one before realloc() or free(). This is a GNU and jemalloc
293 * extension but other systems may also store this size in ptr[-1].
294 * Depending on the old vs new size, it's considered as an allocation or a free
295 * (or neither if the size remains the same).
296 */
297void *realloc(void *ptr, size_t size)
298{
299 struct memprof_stats *bin;
300 size_t size_before;
301 void *ret;
302
303 if (likely(!(profiling & HA_PROF_MEMORY)))
304 return memprof_realloc_handler(ptr, size);
305
306 size_before = malloc_usable_size(ptr);
307 ret = memprof_realloc_handler(ptr, size);
Willy Tarreau2639e2e2021-05-07 08:01:35 +0200308 size = malloc_usable_size(ret);
Willy Tarreauf93c7be2021-05-05 17:07:09 +0200309
Willy Tarreau1de51eb2021-10-22 16:33:53 +0200310 /* only count the extra link for new allocations */
311 if (!ptr)
312 size += sizeof(void *);
313
Willy Tarreau616491b2021-05-11 09:26:23 +0200314 bin = memprof_get_bin(__builtin_return_address(0), MEMPROF_METH_REALLOC);
Willy Tarreauf93c7be2021-05-05 17:07:09 +0200315 if (size > size_before) {
316 _HA_ATOMIC_ADD(&bin->alloc_calls, 1);
Willy Tarreau79acefa2021-05-11 09:12:56 +0200317 _HA_ATOMIC_ADD(&bin->alloc_tot, size - size_before);
Willy Tarreauf93c7be2021-05-05 17:07:09 +0200318 } else if (size < size_before) {
319 _HA_ATOMIC_ADD(&bin->free_calls, 1);
Willy Tarreau79acefa2021-05-11 09:12:56 +0200320 _HA_ATOMIC_ADD(&bin->free_tot, size_before - size);
Willy Tarreauf93c7be2021-05-05 17:07:09 +0200321 }
322 return ret;
323}
324
325/* This is the new global free() function. It must optimize for the normal
326 * case (i.e. profiling disabled) hence the first test to permit a direct jump.
327 * It must remain simple to guarantee the lack of reentrance. stdio is not
328 * possible there even for debugging. The reported size is the really allocated
329 * one as returned by malloc_usable_size(), because this will allow it to be
330 * compared to the one before realloc() or free(). This is a GNU and jemalloc
331 * extension but other systems may also store this size in ptr[-1]. Since
332 * free() is often called on NULL pointers to collect garbage at the end of
333 * many functions or during config parsing, as a special case free(NULL)
334 * doesn't update any stats.
335 */
336void free(void *ptr)
337{
338 struct memprof_stats *bin;
339 size_t size_before;
340
341 if (likely(!(profiling & HA_PROF_MEMORY) || !ptr)) {
342 memprof_free_handler(ptr);
343 return;
344 }
345
Willy Tarreau1de51eb2021-10-22 16:33:53 +0200346 size_before = malloc_usable_size(ptr) + sizeof(void *);
Willy Tarreauf93c7be2021-05-05 17:07:09 +0200347 memprof_free_handler(ptr);
348
Willy Tarreau616491b2021-05-11 09:26:23 +0200349 bin = memprof_get_bin(__builtin_return_address(0), MEMPROF_METH_FREE);
Willy Tarreauf93c7be2021-05-05 17:07:09 +0200350 _HA_ATOMIC_ADD(&bin->free_calls, 1);
351 _HA_ATOMIC_ADD(&bin->free_tot, size_before);
352}
353
Willy Tarreaudb87fc72021-05-05 16:50:40 +0200354#endif // USE_MEMORY_PROFILING
355
Willy Tarreau609aad92018-11-22 08:31:09 +0100356/* Updates the current thread's statistics about stolen CPU time. The unit for
357 * <stolen> is half-milliseconds.
358 */
359void report_stolen_time(uint64_t stolen)
360{
361 activity[tid].cpust_total += stolen;
362 update_freq_ctr(&activity[tid].cpust_1s, stolen);
363 update_freq_ctr_period(&activity[tid].cpust_15s, 15000, stolen);
364}
Willy Tarreau75c62c22018-11-22 11:02:09 +0100365
Willy Tarreau20adfde2021-10-08 11:34:46 +0200366/* Update avg_loop value for the current thread and possibly decide to enable
367 * task-level profiling on the current thread based on its average run time.
368 * The <run_time> argument is the number of microseconds elapsed since the
369 * last time poll() returned.
Willy Tarreaue0650222021-10-06 16:22:09 +0200370 */
Willy Tarreau20adfde2021-10-08 11:34:46 +0200371void activity_count_runtime(uint32_t run_time)
Willy Tarreaue0650222021-10-06 16:22:09 +0200372{
Willy Tarreaue0650222021-10-06 16:22:09 +0200373 uint32_t up, down;
374
375 /* 1 millisecond per loop on average over last 1024 iterations is
376 * enough to turn on profiling.
377 */
378 up = 1000;
379 down = up * 99 / 100;
380
Willy Tarreaue0650222021-10-06 16:22:09 +0200381 run_time = swrate_add(&activity[tid].avg_loop_us, TIME_STATS_SAMPLES, run_time);
382
383 /* In automatic mode, reaching the "up" threshold on average switches
384 * profiling to "on" when automatic, and going back below the "down"
385 * threshold switches to off. The forced modes don't check the load.
386 */
387 if (!(task_profiling_mask & tid_bit)) {
388 if (unlikely((profiling & HA_PROF_TASKS_MASK) == HA_PROF_TASKS_ON ||
389 ((profiling & HA_PROF_TASKS_MASK) == HA_PROF_TASKS_AON &&
390 swrate_avg(run_time, TIME_STATS_SAMPLES) >= up)))
391 _HA_ATOMIC_OR(&task_profiling_mask, tid_bit);
392 } else {
393 if (unlikely((profiling & HA_PROF_TASKS_MASK) == HA_PROF_TASKS_OFF ||
394 ((profiling & HA_PROF_TASKS_MASK) == HA_PROF_TASKS_AOFF &&
395 swrate_avg(run_time, TIME_STATS_SAMPLES) <= down)))
396 _HA_ATOMIC_AND(&task_profiling_mask, ~tid_bit);
397 }
398}
399
Willy Tarreauca3afc22021-05-05 18:33:19 +0200400#ifdef USE_MEMORY_PROFILING
401/* config parser for global "profiling.memory", accepts "on" or "off" */
402static int cfg_parse_prof_memory(char **args, int section_type, struct proxy *curpx,
403 const struct proxy *defpx, const char *file, int line,
404 char **err)
405{
406 if (too_many_args(1, args, err, NULL))
407 return -1;
408
409 if (strcmp(args[1], "on") == 0)
410 profiling |= HA_PROF_MEMORY;
411 else if (strcmp(args[1], "off") == 0)
412 profiling &= ~HA_PROF_MEMORY;
413 else {
414 memprintf(err, "'%s' expects either 'on' or 'off' but got '%s'.", args[0], args[1]);
415 return -1;
416 }
417 return 0;
418}
419#endif // USE_MEMORY_PROFILING
420
Willy Tarreau75c62c22018-11-22 11:02:09 +0100421/* config parser for global "profiling.tasks", accepts "on" or "off" */
422static int cfg_parse_prof_tasks(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +0100423 const struct proxy *defpx, const char *file, int line,
Willy Tarreau75c62c22018-11-22 11:02:09 +0100424 char **err)
425{
426 if (too_many_args(1, args, err, NULL))
427 return -1;
428
429 if (strcmp(args[1], "on") == 0)
Willy Tarreaud2d33482019-04-25 17:09:07 +0200430 profiling = (profiling & ~HA_PROF_TASKS_MASK) | HA_PROF_TASKS_ON;
431 else if (strcmp(args[1], "auto") == 0)
Willy Tarreauaa622b82021-01-28 21:44:22 +0100432 profiling = (profiling & ~HA_PROF_TASKS_MASK) | HA_PROF_TASKS_AOFF;
Willy Tarreau75c62c22018-11-22 11:02:09 +0100433 else if (strcmp(args[1], "off") == 0)
Willy Tarreaud2d33482019-04-25 17:09:07 +0200434 profiling = (profiling & ~HA_PROF_TASKS_MASK) | HA_PROF_TASKS_OFF;
Willy Tarreau75c62c22018-11-22 11:02:09 +0100435 else {
Willy Tarreaud2d33482019-04-25 17:09:07 +0200436 memprintf(err, "'%s' expects either 'on', 'auto', or 'off' but got '%s'.", args[0], args[1]);
Willy Tarreau75c62c22018-11-22 11:02:09 +0100437 return -1;
438 }
439 return 0;
440}
441
442/* parse a "set profiling" command. It always returns 1. */
443static int cli_parse_set_profiling(char **args, char *payload, struct appctx *appctx, void *private)
444{
Willy Tarreau75c62c22018-11-22 11:02:09 +0100445 if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
446 return 1;
447
Willy Tarreau00dd44f2021-05-05 16:44:23 +0200448 if (strcmp(args[2], "memory") == 0) {
Willy Tarreaudb87fc72021-05-05 16:50:40 +0200449#ifdef USE_MEMORY_PROFILING
450 if (strcmp(args[3], "on") == 0) {
451 unsigned int old = profiling;
452 int i;
453
454 while (!_HA_ATOMIC_CAS(&profiling, &old, old | HA_PROF_MEMORY))
455 ;
456
457 /* also flush current profiling stats */
458 for (i = 0; i < sizeof(memprof_stats) / sizeof(memprof_stats[0]); i++) {
459 HA_ATOMIC_STORE(&memprof_stats[i].alloc_calls, 0);
460 HA_ATOMIC_STORE(&memprof_stats[i].free_calls, 0);
461 HA_ATOMIC_STORE(&memprof_stats[i].alloc_tot, 0);
462 HA_ATOMIC_STORE(&memprof_stats[i].free_tot, 0);
463 HA_ATOMIC_STORE(&memprof_stats[i].caller, NULL);
464 }
465 }
466 else if (strcmp(args[3], "off") == 0) {
467 unsigned int old = profiling;
468
469 while (!_HA_ATOMIC_CAS(&profiling, &old, old & ~HA_PROF_MEMORY))
470 ;
471 }
472 else
473 return cli_err(appctx, "Expects either 'on' or 'off'.\n");
474 return 1;
475#else
Willy Tarreau00dd44f2021-05-05 16:44:23 +0200476 return cli_err(appctx, "Memory profiling not compiled in.\n");
Willy Tarreaudb87fc72021-05-05 16:50:40 +0200477#endif
Willy Tarreau00dd44f2021-05-05 16:44:23 +0200478 }
479
Willy Tarreau9d008692019-08-09 11:21:01 +0200480 if (strcmp(args[2], "tasks") != 0)
Ilya Shipitsin3df59892021-05-10 12:50:00 +0500481 return cli_err(appctx, "Expects either 'tasks' or 'memory'.\n");
Willy Tarreau75c62c22018-11-22 11:02:09 +0100482
Willy Tarreaud2d33482019-04-25 17:09:07 +0200483 if (strcmp(args[3], "on") == 0) {
484 unsigned int old = profiling;
Willy Tarreaucfa71012021-01-29 11:56:21 +0100485 int i;
486
Willy Tarreaud2d33482019-04-25 17:09:07 +0200487 while (!_HA_ATOMIC_CAS(&profiling, &old, (old & ~HA_PROF_TASKS_MASK) | HA_PROF_TASKS_ON))
488 ;
Willy Tarreaucfa71012021-01-29 11:56:21 +0100489 /* also flush current profiling stats */
490 for (i = 0; i < 256; i++) {
491 HA_ATOMIC_STORE(&sched_activity[i].calls, 0);
492 HA_ATOMIC_STORE(&sched_activity[i].cpu_time, 0);
493 HA_ATOMIC_STORE(&sched_activity[i].lat_time, 0);
494 HA_ATOMIC_STORE(&sched_activity[i].func, NULL);
495 }
Willy Tarreaud2d33482019-04-25 17:09:07 +0200496 }
497 else if (strcmp(args[3], "auto") == 0) {
498 unsigned int old = profiling;
Willy Tarreauaa622b82021-01-28 21:44:22 +0100499 unsigned int new;
500
501 do {
502 if ((old & HA_PROF_TASKS_MASK) >= HA_PROF_TASKS_AON)
503 new = (old & ~HA_PROF_TASKS_MASK) | HA_PROF_TASKS_AON;
504 else
505 new = (old & ~HA_PROF_TASKS_MASK) | HA_PROF_TASKS_AOFF;
506 } while (!_HA_ATOMIC_CAS(&profiling, &old, new));
Willy Tarreaud2d33482019-04-25 17:09:07 +0200507 }
508 else if (strcmp(args[3], "off") == 0) {
509 unsigned int old = profiling;
510 while (!_HA_ATOMIC_CAS(&profiling, &old, (old & ~HA_PROF_TASKS_MASK) | HA_PROF_TASKS_OFF))
511 ;
512 }
Willy Tarreau9d008692019-08-09 11:21:01 +0200513 else
514 return cli_err(appctx, "Expects 'on', 'auto', or 'off'.\n");
515
Willy Tarreau75c62c22018-11-22 11:02:09 +0100516 return 1;
517}
518
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200519static int cmp_sched_activity_calls(const void *a, const void *b)
Willy Tarreau1bd67e92021-01-29 00:07:40 +0100520{
521 const struct sched_activity *l = (const struct sched_activity *)a;
522 const struct sched_activity *r = (const struct sched_activity *)b;
523
524 if (l->calls > r->calls)
525 return -1;
526 else if (l->calls < r->calls)
527 return 1;
528 else
529 return 0;
530}
531
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200532static int cmp_sched_activity_addr(const void *a, const void *b)
533{
534 const struct sched_activity *l = (const struct sched_activity *)a;
535 const struct sched_activity *r = (const struct sched_activity *)b;
536
537 if (l->func > r->func)
538 return -1;
539 else if (l->func < r->func)
540 return 1;
541 else
542 return 0;
543}
544
Willy Tarreaue15615c2021-08-28 12:04:25 +0200545#ifdef USE_MEMORY_PROFILING
Willy Tarreau993d44d2021-05-05 18:07:02 +0200546/* used by qsort below */
547static int cmp_memprof_stats(const void *a, const void *b)
548{
549 const struct memprof_stats *l = (const struct memprof_stats *)a;
550 const struct memprof_stats *r = (const struct memprof_stats *)b;
551
552 if (l->alloc_tot + l->free_tot > r->alloc_tot + r->free_tot)
553 return -1;
554 else if (l->alloc_tot + l->free_tot < r->alloc_tot + r->free_tot)
555 return 1;
556 else
557 return 0;
558}
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200559
560static int cmp_memprof_addr(const void *a, const void *b)
561{
562 const struct memprof_stats *l = (const struct memprof_stats *)a;
563 const struct memprof_stats *r = (const struct memprof_stats *)b;
564
565 if (l->caller > r->caller)
566 return -1;
567 else if (l->caller < r->caller)
568 return 1;
569 else
570 return 0;
571}
Willy Tarreau993d44d2021-05-05 18:07:02 +0200572#endif // USE_MEMORY_PROFILING
573
Willy Tarreaua26be372021-10-06 16:26:33 +0200574/* Computes the index of function pointer <func> for use with sched_activity[]
575 * or any other similar array passed in <array>, and returns a pointer to the
576 * entry after having atomically assigned it to this function pointer. Note
577 * that in case of collision, the first entry is returned instead ("other").
578 */
579struct sched_activity *sched_activity_entry(struct sched_activity *array, const void *func)
580{
581 uint64_t hash = XXH64_avalanche(XXH64_mergeRound((size_t)func, (size_t)func));
582 struct sched_activity *ret;
583 const void *old = NULL;
584
585 hash ^= (hash >> 32);
586 hash ^= (hash >> 16);
587 hash ^= (hash >> 8);
588 hash &= 0xff;
589 ret = &array[hash];
590
591 if (likely(ret->func == func))
592 return ret;
593
594 if (HA_ATOMIC_CAS(&ret->func, &old, func))
595 return ret;
596
597 return array;
598}
599
Willy Tarreau75c62c22018-11-22 11:02:09 +0100600/* This function dumps all profiling settings. It returns 0 if the output
601 * buffer is full and it needs to be called again, otherwise non-zero.
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200602 * It dumps some parts depending on the following states from show_prof_ctx:
603 * dump_step:
Willy Tarreau637d85a2021-05-05 17:33:27 +0200604 * 0, 4: dump status, then jump to 1 if 0
605 * 1, 5: dump tasks, then jump to 2 if 1
606 * 2, 6: dump memory, then stop
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200607 * linenum:
Willy Tarreau637d85a2021-05-05 17:33:27 +0200608 * restart line for each step (starts at zero)
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200609 * maxcnt:
Willy Tarreau637d85a2021-05-05 17:33:27 +0200610 * may contain a configured max line count for each step (0=not set)
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200611 * byaddr:
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200612 * 0: sort by usage
613 * 1: sort by address
Willy Tarreau75c62c22018-11-22 11:02:09 +0100614 */
615static int cli_io_handler_show_profiling(struct appctx *appctx)
616{
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200617 struct show_prof_ctx *ctx = appctx->svcctx;
Willy Tarreau1bd67e92021-01-29 00:07:40 +0100618 struct sched_activity tmp_activity[256] __attribute__((aligned(64)));
Willy Tarreaue15615c2021-08-28 12:04:25 +0200619#ifdef USE_MEMORY_PROFILING
Willy Tarreau993d44d2021-05-05 18:07:02 +0200620 struct memprof_stats tmp_memstats[MEMPROF_HASH_BUCKETS + 1];
Willy Tarreauf5fb8582021-05-11 14:06:24 +0200621 unsigned long long tot_alloc_calls, tot_free_calls;
622 unsigned long long tot_alloc_bytes, tot_free_bytes;
Willy Tarreau993d44d2021-05-05 18:07:02 +0200623#endif
Willy Tarreau0698c802022-05-11 14:09:57 +0200624 struct conn_stream *cs = appctx_cs(appctx);
Willy Tarreau1bd67e92021-01-29 00:07:40 +0100625 struct buffer *name_buffer = get_trash_chunk();
Willy Tarreaud2d33482019-04-25 17:09:07 +0200626 const char *str;
Willy Tarreau637d85a2021-05-05 17:33:27 +0200627 int max_lines;
Willy Tarreau1bd67e92021-01-29 00:07:40 +0100628 int i, max;
Willy Tarreau75c62c22018-11-22 11:02:09 +0100629
Christopher Faulet908628c2022-03-25 16:43:49 +0100630 if (unlikely(cs_ic(cs)->flags & (CF_WRITE_ERROR|CF_SHUTW)))
Willy Tarreau75c62c22018-11-22 11:02:09 +0100631 return 1;
632
633 chunk_reset(&trash);
634
Willy Tarreaud2d33482019-04-25 17:09:07 +0200635 switch (profiling & HA_PROF_TASKS_MASK) {
Willy Tarreauaa622b82021-01-28 21:44:22 +0100636 case HA_PROF_TASKS_AOFF: str="auto-off"; break;
637 case HA_PROF_TASKS_AON: str="auto-on"; break;
Willy Tarreaud2d33482019-04-25 17:09:07 +0200638 case HA_PROF_TASKS_ON: str="on"; break;
639 default: str="off"; break;
640 }
641
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200642 if ((ctx->dump_step & 3) != 0)
Willy Tarreau637d85a2021-05-05 17:33:27 +0200643 goto skip_status;
Willy Tarreau1bd67e92021-01-29 00:07:40 +0100644
Willy Tarreaud2d33482019-04-25 17:09:07 +0200645 chunk_printf(&trash,
Willy Tarreau00dd44f2021-05-05 16:44:23 +0200646 "Per-task CPU profiling : %-8s # set profiling tasks {on|auto|off}\n"
647 "Memory usage profiling : %-8s # set profiling memory {on|off}\n",
648 str, (profiling & HA_PROF_MEMORY) ? "on" : "off");
Willy Tarreau75c62c22018-11-22 11:02:09 +0100649
Christopher Faulet908628c2022-03-25 16:43:49 +0100650 if (ci_putchk(cs_ic(cs), &trash) == -1) {
Willy Tarreau637d85a2021-05-05 17:33:27 +0200651 /* failed, try again */
Christopher Fauleta0bdec32022-04-04 07:51:21 +0200652 cs_rx_room_blk(cs);
Willy Tarreau637d85a2021-05-05 17:33:27 +0200653 return 0;
654 }
655
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200656 ctx->linenum = 0; // reset first line to dump
657 if ((ctx->dump_step & 4) == 0)
658 ctx->dump_step++; // next step
Willy Tarreau637d85a2021-05-05 17:33:27 +0200659
660 skip_status:
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200661 if ((ctx->dump_step & 3) != 1)
Willy Tarreau637d85a2021-05-05 17:33:27 +0200662 goto skip_tasks;
Willy Tarreau1bd67e92021-01-29 00:07:40 +0100663
Willy Tarreau637d85a2021-05-05 17:33:27 +0200664 memcpy(tmp_activity, sched_activity, sizeof(tmp_activity));
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200665 if (ctx->by_addr)
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200666 qsort(tmp_activity, 256, sizeof(tmp_activity[0]), cmp_sched_activity_addr);
667 else
668 qsort(tmp_activity, 256, sizeof(tmp_activity[0]), cmp_sched_activity_calls);
Willy Tarreau637d85a2021-05-05 17:33:27 +0200669
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200670 if (!ctx->linenum)
Willy Tarreau637d85a2021-05-05 17:33:27 +0200671 chunk_appendf(&trash, "Tasks activity:\n"
672 " function calls cpu_tot cpu_avg lat_tot lat_avg\n");
673
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200674 max_lines = ctx->maxcnt;
Willy Tarreau637d85a2021-05-05 17:33:27 +0200675 if (!max_lines)
676 max_lines = 256;
677
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200678 for (i = ctx->linenum; i < max_lines && tmp_activity[i].calls; i++) {
679 ctx->linenum = i;
Willy Tarreau1bd67e92021-01-29 00:07:40 +0100680 chunk_reset(name_buffer);
681
682 if (!tmp_activity[i].func)
683 chunk_printf(name_buffer, "other");
684 else
685 resolve_sym_name(name_buffer, "", tmp_activity[i].func);
686
687 /* reserve 35 chars for name+' '+#calls, knowing that longer names
688 * are often used for less often called functions.
689 */
690 max = 35 - name_buffer->data;
691 if (max < 1)
692 max = 1;
693 chunk_appendf(&trash, " %s%*llu", name_buffer->area, max, (unsigned long long)tmp_activity[i].calls);
694
695 print_time_short(&trash, " ", tmp_activity[i].cpu_time, "");
696 print_time_short(&trash, " ", tmp_activity[i].cpu_time / tmp_activity[i].calls, "");
697 print_time_short(&trash, " ", tmp_activity[i].lat_time, "");
698 print_time_short(&trash, " ", tmp_activity[i].lat_time / tmp_activity[i].calls, "\n");
Willy Tarreau637d85a2021-05-05 17:33:27 +0200699
Christopher Faulet908628c2022-03-25 16:43:49 +0100700 if (ci_putchk(cs_ic(cs), &trash) == -1) {
Willy Tarreau637d85a2021-05-05 17:33:27 +0200701 /* failed, try again */
Christopher Fauleta0bdec32022-04-04 07:51:21 +0200702 cs_rx_room_blk(cs);
Willy Tarreau637d85a2021-05-05 17:33:27 +0200703 return 0;
704 }
Willy Tarreau1bd67e92021-01-29 00:07:40 +0100705 }
706
Christopher Faulet908628c2022-03-25 16:43:49 +0100707 if (ci_putchk(cs_ic(cs), &trash) == -1) {
Willy Tarreau75c62c22018-11-22 11:02:09 +0100708 /* failed, try again */
Christopher Fauleta0bdec32022-04-04 07:51:21 +0200709 cs_rx_room_blk(cs);
Willy Tarreau75c62c22018-11-22 11:02:09 +0100710 return 0;
711 }
Willy Tarreau637d85a2021-05-05 17:33:27 +0200712
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200713 ctx->linenum = 0; // reset first line to dump
714 if ((ctx->dump_step & 4) == 0)
715 ctx->dump_step++; // next step
Willy Tarreau637d85a2021-05-05 17:33:27 +0200716
717 skip_tasks:
718
Willy Tarreaue15615c2021-08-28 12:04:25 +0200719#ifdef USE_MEMORY_PROFILING
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200720 if ((ctx->dump_step & 3) != 2)
Willy Tarreau993d44d2021-05-05 18:07:02 +0200721 goto skip_mem;
722
723 memcpy(tmp_memstats, memprof_stats, sizeof(tmp_memstats));
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200724 if (ctx->by_addr)
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200725 qsort(tmp_memstats, MEMPROF_HASH_BUCKETS+1, sizeof(tmp_memstats[0]), cmp_memprof_addr);
726 else
727 qsort(tmp_memstats, MEMPROF_HASH_BUCKETS+1, sizeof(tmp_memstats[0]), cmp_memprof_stats);
Willy Tarreau993d44d2021-05-05 18:07:02 +0200728
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200729 if (!ctx->linenum)
Willy Tarreau993d44d2021-05-05 18:07:02 +0200730 chunk_appendf(&trash,
731 "Alloc/Free statistics by call place:\n"
Willy Tarreau616491b2021-05-11 09:26:23 +0200732 " Calls | Tot Bytes | Caller and method\n"
Willy Tarreau993d44d2021-05-05 18:07:02 +0200733 "<- alloc -> <- free ->|<-- alloc ---> <-- free ---->|\n");
734
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200735 max_lines = ctx->maxcnt;
Willy Tarreau993d44d2021-05-05 18:07:02 +0200736 if (!max_lines)
737 max_lines = MEMPROF_HASH_BUCKETS + 1;
738
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200739 for (i = ctx->linenum; i < max_lines; i++) {
Willy Tarreau993d44d2021-05-05 18:07:02 +0200740 struct memprof_stats *entry = &tmp_memstats[i];
741
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200742 ctx->linenum = i;
Willy Tarreau993d44d2021-05-05 18:07:02 +0200743 if (!entry->alloc_calls && !entry->free_calls)
744 continue;
745 chunk_appendf(&trash, "%11llu %11llu %14llu %14llu| %16p ",
746 entry->alloc_calls, entry->free_calls,
747 entry->alloc_tot, entry->free_tot,
748 entry->caller);
749
750 if (entry->caller)
751 resolve_sym_name(&trash, NULL, entry->caller);
752 else
753 chunk_appendf(&trash, "[other]");
754
Willy Tarreau8cce4d72021-10-22 16:26:12 +0200755 chunk_appendf(&trash," %s(%lld)", memprof_methods[entry->method],
Willy Tarreau616491b2021-05-11 09:26:23 +0200756 (long long)(entry->alloc_tot - entry->free_tot) / (long long)(entry->alloc_calls + entry->free_calls));
Willy Tarreau993d44d2021-05-05 18:07:02 +0200757
Willy Tarreau8cce4d72021-10-22 16:26:12 +0200758 if (entry->alloc_tot && entry->free_tot) {
759 /* that's a realloc, show the total diff to help spot leaks */
760 chunk_appendf(&trash," [delta=%lld]", (long long)(entry->alloc_tot - entry->free_tot));
761 }
762
763 chunk_appendf(&trash, "\n");
764
Christopher Faulet908628c2022-03-25 16:43:49 +0100765 if (ci_putchk(cs_ic(cs), &trash) == -1) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +0200766 cs_rx_room_blk(cs);
Willy Tarreau993d44d2021-05-05 18:07:02 +0200767 return 0;
768 }
769 }
770
Christopher Faulet908628c2022-03-25 16:43:49 +0100771 if (ci_putchk(cs_ic(cs), &trash) == -1) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +0200772 cs_rx_room_blk(cs);
Willy Tarreau993d44d2021-05-05 18:07:02 +0200773 return 0;
774 }
775
Willy Tarreauf5fb8582021-05-11 14:06:24 +0200776 tot_alloc_calls = tot_free_calls = tot_alloc_bytes = tot_free_bytes = 0;
777 for (i = 0; i < max_lines; i++) {
778 tot_alloc_calls += tmp_memstats[i].alloc_calls;
779 tot_free_calls += tmp_memstats[i].free_calls;
780 tot_alloc_bytes += tmp_memstats[i].alloc_tot;
781 tot_free_bytes += tmp_memstats[i].free_tot;
782 }
783
784 chunk_appendf(&trash,
785 "-----------------------|-----------------------------|\n"
786 "%11llu %11llu %14llu %14llu| <- Total; Delta_calls=%lld; Delta_bytes=%lld\n",
787 tot_alloc_calls, tot_free_calls,
788 tot_alloc_bytes, tot_free_bytes,
789 tot_alloc_calls - tot_free_calls,
790 tot_alloc_bytes - tot_free_bytes);
791
Christopher Faulet908628c2022-03-25 16:43:49 +0100792 if (ci_putchk(cs_ic(cs), &trash) == -1) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +0200793 cs_rx_room_blk(cs);
Willy Tarreauf5fb8582021-05-11 14:06:24 +0200794 return 0;
795 }
796
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200797 ctx->linenum = 0; // reset first line to dump
798 if ((ctx->dump_step & 4) == 0)
799 ctx->dump_step++; // next step
Willy Tarreau993d44d2021-05-05 18:07:02 +0200800
801 skip_mem:
802#endif // USE_MEMORY_PROFILING
803
Willy Tarreau75c62c22018-11-22 11:02:09 +0100804 return 1;
805}
806
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200807/* parse a "show profiling" command. It returns 1 on failure, 0 if it starts to dump.
808 * - cli.i0 is set to the first state (0=all, 4=status, 5=tasks, 6=memory)
809 * - cli.o1 is set to 1 if the output must be sorted by addr instead of usage
810 * - cli.o0 is set to the number of lines of output
811 */
Willy Tarreau42712cb2021-05-05 17:48:13 +0200812static int cli_parse_show_profiling(char **args, char *payload, struct appctx *appctx, void *private)
813{
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200814 struct show_prof_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200815 int arg;
816
Willy Tarreau42712cb2021-05-05 17:48:13 +0200817 if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
818 return 1;
819
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200820 for (arg = 2; *args[arg]; arg++) {
821 if (strcmp(args[arg], "all") == 0) {
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200822 ctx->dump_step = 0; // will cycle through 0,1,2; default
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200823 }
824 else if (strcmp(args[arg], "status") == 0) {
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200825 ctx->dump_step = 4; // will visit status only
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200826 }
827 else if (strcmp(args[arg], "tasks") == 0) {
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200828 ctx->dump_step = 5; // will visit tasks only
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200829 }
830 else if (strcmp(args[arg], "memory") == 0) {
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200831 ctx->dump_step = 6; // will visit memory only
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200832 }
833 else if (strcmp(args[arg], "byaddr") == 0) {
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200834 ctx->by_addr = 1; // sort output by address instead of usage
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200835 }
836 else if (isdigit((unsigned char)*args[arg])) {
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200837 ctx->maxcnt = atoi(args[arg]); // number of entries to dump
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200838 }
839 else
840 return cli_err(appctx, "Expects either 'all', 'status', 'tasks', 'memory', 'byaddr' or a max number of output lines.\n");
Willy Tarreau42712cb2021-05-05 17:48:13 +0200841 }
842 return 0;
843}
844
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100845/* This function scans all threads' run queues and collects statistics about
846 * running tasks. It returns 0 if the output buffer is full and it needs to be
847 * called again, otherwise non-zero.
848 */
849static int cli_io_handler_show_tasks(struct appctx *appctx)
850{
851 struct sched_activity tmp_activity[256] __attribute__((aligned(64)));
Willy Tarreau0698c802022-05-11 14:09:57 +0200852 struct conn_stream *cs = appctx_cs(appctx);
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100853 struct buffer *name_buffer = get_trash_chunk();
854 struct sched_activity *entry;
855 const struct tasklet *tl;
856 const struct task *t;
857 uint64_t now_ns, lat;
858 struct eb32sc_node *rqnode;
859 uint64_t tot_calls;
860 int thr, queue;
861 int i, max;
862
Christopher Faulet908628c2022-03-25 16:43:49 +0100863 if (unlikely(cs_ic(cs)->flags & (CF_WRITE_ERROR|CF_SHUTW)))
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100864 return 1;
865
866 /* It's not possible to scan queues in small chunks and yield in the
867 * middle of the dump and come back again. So what we're doing instead
868 * is to freeze all threads and inspect their queues at once as fast as
869 * possible, using a sched_activity array to collect metrics with
870 * limited collision, then we'll report statistics only. The tasks'
871 * #calls will reflect the number of occurrences, and the lat_time will
Willy Tarreau75f72332021-01-29 15:04:16 +0100872 * reflect the latency when set. We prefer to take the time before
873 * calling thread_isolate() so that the wait time doesn't impact the
874 * measurement accuracy. However this requires to take care of negative
875 * times since tasks might be queued after we retrieve it.
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100876 */
877
878 now_ns = now_mono_time();
879 memset(tmp_activity, 0, sizeof(tmp_activity));
880
881 thread_isolate();
882
883 /* 1. global run queue */
884
885#ifdef USE_THREAD
886 rqnode = eb32sc_first(&rqueue, ~0UL);
887 while (rqnode) {
888 t = eb32sc_entry(rqnode, struct task, rq);
889 entry = sched_activity_entry(tmp_activity, t->process);
890 if (t->call_date) {
891 lat = now_ns - t->call_date;
Willy Tarreau75f72332021-01-29 15:04:16 +0100892 if ((int64_t)lat > 0)
893 entry->lat_time += lat;
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100894 }
895 entry->calls++;
896 rqnode = eb32sc_next(rqnode, ~0UL);
897 }
898#endif
899 /* 2. all threads's local run queues */
900 for (thr = 0; thr < global.nbthread; thr++) {
901 /* task run queue */
Willy Tarreau1a9c9222021-10-01 11:30:33 +0200902 rqnode = eb32sc_first(&ha_thread_ctx[thr].rqueue, ~0UL);
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100903 while (rqnode) {
904 t = eb32sc_entry(rqnode, struct task, rq);
905 entry = sched_activity_entry(tmp_activity, t->process);
906 if (t->call_date) {
907 lat = now_ns - t->call_date;
Willy Tarreau75f72332021-01-29 15:04:16 +0100908 if ((int64_t)lat > 0)
909 entry->lat_time += lat;
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100910 }
911 entry->calls++;
912 rqnode = eb32sc_next(rqnode, ~0UL);
913 }
914
915 /* shared tasklet list */
Willy Tarreau1a9c9222021-10-01 11:30:33 +0200916 list_for_each_entry(tl, mt_list_to_list(&ha_thread_ctx[thr].shared_tasklet_list), list) {
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100917 t = (const struct task *)tl;
918 entry = sched_activity_entry(tmp_activity, t->process);
919 if (!TASK_IS_TASKLET(t) && t->call_date) {
920 lat = now_ns - t->call_date;
Willy Tarreau75f72332021-01-29 15:04:16 +0100921 if ((int64_t)lat > 0)
922 entry->lat_time += lat;
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100923 }
924 entry->calls++;
925 }
926
927 /* classful tasklets */
928 for (queue = 0; queue < TL_CLASSES; queue++) {
Willy Tarreau1a9c9222021-10-01 11:30:33 +0200929 list_for_each_entry(tl, &ha_thread_ctx[thr].tasklets[queue], list) {
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100930 t = (const struct task *)tl;
931 entry = sched_activity_entry(tmp_activity, t->process);
932 if (!TASK_IS_TASKLET(t) && t->call_date) {
933 lat = now_ns - t->call_date;
Willy Tarreau75f72332021-01-29 15:04:16 +0100934 if ((int64_t)lat > 0)
935 entry->lat_time += lat;
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100936 }
937 entry->calls++;
938 }
939 }
940 }
941
942 /* hopefully we're done */
943 thread_release();
944
945 chunk_reset(&trash);
946
947 tot_calls = 0;
948 for (i = 0; i < 256; i++)
949 tot_calls += tmp_activity[i].calls;
950
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200951 qsort(tmp_activity, 256, sizeof(tmp_activity[0]), cmp_sched_activity_calls);
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100952
953 chunk_appendf(&trash, "Running tasks: %d (%d threads)\n"
954 " function places %% lat_tot lat_avg\n",
955 (int)tot_calls, global.nbthread);
956
957 for (i = 0; i < 256 && tmp_activity[i].calls; i++) {
958 chunk_reset(name_buffer);
959
960 if (!tmp_activity[i].func)
961 chunk_printf(name_buffer, "other");
962 else
963 resolve_sym_name(name_buffer, "", tmp_activity[i].func);
964
965 /* reserve 35 chars for name+' '+#calls, knowing that longer names
966 * are often used for less often called functions.
967 */
968 max = 35 - name_buffer->data;
969 if (max < 1)
970 max = 1;
971 chunk_appendf(&trash, " %s%*llu %3d.%1d",
972 name_buffer->area, max, (unsigned long long)tmp_activity[i].calls,
973 (int)(100ULL * tmp_activity[i].calls / tot_calls),
974 (int)((1000ULL * tmp_activity[i].calls / tot_calls)%10));
975 print_time_short(&trash, " ", tmp_activity[i].lat_time, "");
976 print_time_short(&trash, " ", tmp_activity[i].lat_time / tmp_activity[i].calls, "\n");
977 }
978
Christopher Faulet908628c2022-03-25 16:43:49 +0100979 if (ci_putchk(cs_ic(cs), &trash) == -1) {
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100980 /* failed, try again */
Christopher Fauleta0bdec32022-04-04 07:51:21 +0200981 cs_rx_room_blk(cs);
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100982 return 0;
983 }
984 return 1;
985}
986
Willy Tarreau75c62c22018-11-22 11:02:09 +0100987/* config keyword parsers */
988static struct cfg_kw_list cfg_kws = {ILH, {
Willy Tarreauca3afc22021-05-05 18:33:19 +0200989#ifdef USE_MEMORY_PROFILING
990 { CFG_GLOBAL, "profiling.memory", cfg_parse_prof_memory },
991#endif
Willy Tarreau75c62c22018-11-22 11:02:09 +0100992 { CFG_GLOBAL, "profiling.tasks", cfg_parse_prof_tasks },
993 { 0, NULL, NULL }
994}};
995
Willy Tarreau0108d902018-11-25 19:14:37 +0100996INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
997
Willy Tarreau75c62c22018-11-22 11:02:09 +0100998/* register cli keywords */
999static struct cli_kw_list cli_kws = {{ },{
Daniel Corbett67b3cef2021-05-10 14:08:40 -04001000 { { "set", "profiling", NULL }, "set profiling <what> {auto|on|off} : enable/disable resource profiling (tasks,memory)", cli_parse_set_profiling, NULL },
Willy Tarreauf1c8a382021-05-13 10:00:17 +02001001 { { "show", "profiling", NULL }, "show profiling [<what>|<#lines>|byaddr]*: show profiling state (all,status,tasks,memory)", cli_parse_show_profiling, cli_io_handler_show_profiling, NULL },
Willy Tarreaub205bfd2021-05-07 11:38:37 +02001002 { { "show", "tasks", NULL }, "show tasks : show running tasks", NULL, cli_io_handler_show_tasks, NULL },
Willy Tarreau75c62c22018-11-22 11:02:09 +01001003 {{},}
1004}};
1005
Willy Tarreau0108d902018-11-25 19:14:37 +01001006INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);