blob: 5ee5fbb10e640041597034d0ee652aa340fdcec5 [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>
Willy Tarreaub2551052020-06-09 09:07:15 +020020#include <haproxy/freq_ctr.h>
Willy Tarreauf9607f82022-11-25 15:32:38 +010021#include <haproxy/listener.h>
Willy Tarreau5edca2f2022-05-27 09:25:10 +020022#include <haproxy/sc_strm.h>
Willy Tarreaucb086c62022-05-27 09:47:12 +020023#include <haproxy/stconn.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020024#include <haproxy/tools.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) */
Willy Tarreaue86bc352022-09-08 16:38:10 +020031 int by_what; /* 0=sort by usage, 1=sort by address, 2=sort by time */
Willy Tarreaudc89b182022-09-08 16:05:57 +020032 int aggr; /* 0=dump raw, 1=aggregate on callee */
Willy Tarreaue8d006a2022-05-05 14:19:00 +020033};
34
Willy Tarreauf9607f82022-11-25 15:32:38 +010035/* CLI context for the "show activity" command */
36struct show_activity_ctx {
37 int thr; /* thread ID to show or -1 for all */
38};
39
Willy Tarreauf93c7be2021-05-05 17:07:09 +020040#if defined(DEBUG_MEM_STATS)
41/* these ones are macros in bug.h when DEBUG_MEM_STATS is set, and will
42 * prevent the new ones from being redefined.
43 */
44#undef calloc
45#undef malloc
46#undef realloc
47#endif
Willy Tarreau75c62c22018-11-22 11:02:09 +010048
49/* bit field of profiling options. Beware, may be modified at runtime! */
Willy Tarreauef7380f2021-05-05 16:28:31 +020050unsigned int profiling __read_mostly = HA_PROF_TASKS_AOFF;
Willy Tarreau609aad92018-11-22 08:31:09 +010051
52/* One struct per thread containing all collected measurements */
53struct activity activity[MAX_THREADS] __attribute__((aligned(64))) = { };
54
Willy Tarreaua3423872022-09-07 18:49:55 +020055/* One struct per function pointer hash entry (SCHED_ACT_HASH_BUCKETS values, 0=collision) */
56struct sched_activity sched_activity[SCHED_ACT_HASH_BUCKETS] __attribute__((aligned(64))) = { };
Willy Tarreau609aad92018-11-22 08:31:09 +010057
Willy Tarreaudb87fc72021-05-05 16:50:40 +020058
Willy Tarreaue15615c2021-08-28 12:04:25 +020059#ifdef USE_MEMORY_PROFILING
Willy Tarreau616491b2021-05-11 09:26:23 +020060
61static const char *const memprof_methods[MEMPROF_METH_METHODS] = {
Willy Tarreaufacfad22022-08-17 09:12:53 +020062 "unknown", "malloc", "calloc", "realloc", "free", "p_alloc", "p_free",
Willy Tarreau616491b2021-05-11 09:26:23 +020063};
64
Willy Tarreaudb87fc72021-05-05 16:50:40 +020065/* last one is for hash collisions ("others") and has no caller address */
66struct memprof_stats memprof_stats[MEMPROF_HASH_BUCKETS + 1] = { };
67
Willy Tarreauf93c7be2021-05-05 17:07:09 +020068/* used to detect recursive calls */
69static THREAD_LOCAL int in_memprof = 0;
70
Willy Tarreauf93c7be2021-05-05 17:07:09 +020071/* These ones are used by glibc and will be called early. They are in charge of
72 * initializing the handlers with the original functions.
73 */
74static void *memprof_malloc_initial_handler(size_t size);
75static void *memprof_calloc_initial_handler(size_t nmemb, size_t size);
76static void *memprof_realloc_initial_handler(void *ptr, size_t size);
77static void memprof_free_initial_handler(void *ptr);
78
79/* Fallback handlers for the main alloc/free functions. They are preset to
80 * the initializer in order to save a test in the functions's critical path.
81 */
82static void *(*memprof_malloc_handler)(size_t size) = memprof_malloc_initial_handler;
83static void *(*memprof_calloc_handler)(size_t nmemb, size_t size) = memprof_calloc_initial_handler;
84static void *(*memprof_realloc_handler)(void *ptr, size_t size) = memprof_realloc_initial_handler;
85static void (*memprof_free_handler)(void *ptr) = memprof_free_initial_handler;
86
87/* Used to force to die if it's not possible to retrieve the allocation
88 * functions. We cannot even use stdio in this case.
89 */
90static __attribute__((noreturn)) void memprof_die(const char *msg)
91{
92 DISGUISE(write(2, msg, strlen(msg)));
93 exit(1);
94}
95
96/* Resolve original allocation functions and initialize all handlers.
97 * This must be called very early at boot, before the very first malloc()
98 * call, and is not thread-safe! It's not even possible to use stdio there.
99 * Worse, we have to account for the risk of reentrance from dlsym() when
100 * it tries to prepare its error messages. Here its ahndled by in_memprof
101 * that makes allocators return NULL. dlsym() handles it gracefully. An
Ilya Shipitsin3df59892021-05-10 12:50:00 +0500102 * alternate approach consists in calling aligned_alloc() from these places
Willy Tarreauf93c7be2021-05-05 17:07:09 +0200103 * but that would mean not being able to intercept it later if considered
104 * useful to do so.
105 */
106static void memprof_init()
107{
108 in_memprof++;
109 memprof_malloc_handler = get_sym_next_addr("malloc");
110 if (!memprof_malloc_handler)
111 memprof_die("FATAL: malloc() function not found.\n");
112
113 memprof_calloc_handler = get_sym_next_addr("calloc");
114 if (!memprof_calloc_handler)
115 memprof_die("FATAL: calloc() function not found.\n");
116
117 memprof_realloc_handler = get_sym_next_addr("realloc");
118 if (!memprof_realloc_handler)
119 memprof_die("FATAL: realloc() function not found.\n");
120
121 memprof_free_handler = get_sym_next_addr("free");
122 if (!memprof_free_handler)
123 memprof_die("FATAL: free() function not found.\n");
124 in_memprof--;
125}
126
127/* the initial handlers will initialize all regular handlers and will call the
128 * one they correspond to. A single one of these functions will typically be
129 * called, though it's unknown which one (as any might be called before main).
130 */
131static void *memprof_malloc_initial_handler(size_t size)
132{
133 if (in_memprof) {
134 /* it's likely that dlsym() needs malloc(), let's fail */
135 return NULL;
136 }
137
138 memprof_init();
139 return memprof_malloc_handler(size);
140}
141
142static void *memprof_calloc_initial_handler(size_t nmemb, size_t size)
143{
144 if (in_memprof) {
145 /* it's likely that dlsym() needs calloc(), let's fail */
146 return NULL;
147 }
148 memprof_init();
149 return memprof_calloc_handler(nmemb, size);
150}
151
152static void *memprof_realloc_initial_handler(void *ptr, size_t size)
153{
154 if (in_memprof) {
155 /* it's likely that dlsym() needs realloc(), let's fail */
156 return NULL;
157 }
158
159 memprof_init();
160 return memprof_realloc_handler(ptr, size);
161}
162
163static void memprof_free_initial_handler(void *ptr)
164{
165 memprof_init();
166 memprof_free_handler(ptr);
167}
168
169/* Assign a bin for the memprof_stats to the return address. May perform a few
170 * attempts before finding the right one, but always succeeds (in the worst
171 * case, returns a default bin). The caller address is atomically set except
172 * for the default one which is never set.
173 */
Willy Tarreau219afa22022-08-17 08:53:36 +0200174struct memprof_stats *memprof_get_bin(const void *ra, enum memprof_method meth)
Willy Tarreauf93c7be2021-05-05 17:07:09 +0200175{
176 int retries = 16; // up to 16 consecutive entries may be tested.
Willy Tarreau4a753282021-05-09 23:18:50 +0200177 const void *old;
Willy Tarreauf93c7be2021-05-05 17:07:09 +0200178 unsigned int bin;
179
Willy Tarreau245d32f2022-09-07 11:20:01 +0200180 bin = ptr_hash(ra, MEMPROF_HASH_BITS);
Willy Tarreauf93c7be2021-05-05 17:07:09 +0200181 for (; memprof_stats[bin].caller != ra; bin = (bin + 1) & (MEMPROF_HASH_BUCKETS - 1)) {
182 if (!--retries) {
183 bin = MEMPROF_HASH_BUCKETS;
184 break;
185 }
186
187 old = NULL;
188 if (!memprof_stats[bin].caller &&
Willy Tarreau616491b2021-05-11 09:26:23 +0200189 HA_ATOMIC_CAS(&memprof_stats[bin].caller, &old, ra)) {
190 memprof_stats[bin].method = meth;
Willy Tarreauf93c7be2021-05-05 17:07:09 +0200191 break;
Willy Tarreau616491b2021-05-11 09:26:23 +0200192 }
Willy Tarreauf93c7be2021-05-05 17:07:09 +0200193 }
194 return &memprof_stats[bin];
195}
196
197/* This is the new global malloc() function. It must optimize for the normal
198 * case (i.e. profiling disabled) hence the first test to permit a direct jump.
199 * It must remain simple to guarantee the lack of reentrance. stdio is not
200 * possible there even for debugging. The reported size is the really allocated
201 * one as returned by malloc_usable_size(), because this will allow it to be
202 * compared to the one before realloc() or free(). This is a GNU and jemalloc
203 * extension but other systems may also store this size in ptr[-1].
204 */
205void *malloc(size_t size)
206{
207 struct memprof_stats *bin;
208 void *ret;
209
210 if (likely(!(profiling & HA_PROF_MEMORY)))
211 return memprof_malloc_handler(size);
212
213 ret = memprof_malloc_handler(size);
Willy Tarreau1de51eb2021-10-22 16:33:53 +0200214 size = malloc_usable_size(ret) + sizeof(void *);
Willy Tarreauf93c7be2021-05-05 17:07:09 +0200215
Willy Tarreau616491b2021-05-11 09:26:23 +0200216 bin = memprof_get_bin(__builtin_return_address(0), MEMPROF_METH_MALLOC);
Willy Tarreauf93c7be2021-05-05 17:07:09 +0200217 _HA_ATOMIC_ADD(&bin->alloc_calls, 1);
218 _HA_ATOMIC_ADD(&bin->alloc_tot, size);
219 return ret;
220}
221
222/* This is the new global calloc() function. It must optimize for the normal
223 * case (i.e. profiling disabled) hence the first test to permit a direct jump.
224 * It must remain simple to guarantee the lack of reentrance. stdio is not
225 * possible there even for debugging. The reported size is the really allocated
226 * one as returned by malloc_usable_size(), because this will allow it to be
227 * compared to the one before realloc() or free(). This is a GNU and jemalloc
228 * extension but other systems may also store this size in ptr[-1].
229 */
230void *calloc(size_t nmemb, size_t size)
231{
232 struct memprof_stats *bin;
233 void *ret;
234
235 if (likely(!(profiling & HA_PROF_MEMORY)))
236 return memprof_calloc_handler(nmemb, size);
237
238 ret = memprof_calloc_handler(nmemb, size);
Willy Tarreau1de51eb2021-10-22 16:33:53 +0200239 size = malloc_usable_size(ret) + sizeof(void *);
Willy Tarreauf93c7be2021-05-05 17:07:09 +0200240
Willy Tarreau616491b2021-05-11 09:26:23 +0200241 bin = memprof_get_bin(__builtin_return_address(0), MEMPROF_METH_CALLOC);
Willy Tarreauf93c7be2021-05-05 17:07:09 +0200242 _HA_ATOMIC_ADD(&bin->alloc_calls, 1);
243 _HA_ATOMIC_ADD(&bin->alloc_tot, size);
244 return ret;
245}
246
247/* This is the new global realloc() function. It must optimize for the normal
248 * case (i.e. profiling disabled) hence the first test to permit a direct jump.
249 * It must remain simple to guarantee the lack of reentrance. stdio is not
250 * possible there even for debugging. The reported size is the really allocated
251 * one as returned by malloc_usable_size(), because this will allow it to be
252 * compared to the one before realloc() or free(). This is a GNU and jemalloc
253 * extension but other systems may also store this size in ptr[-1].
254 * Depending on the old vs new size, it's considered as an allocation or a free
255 * (or neither if the size remains the same).
256 */
257void *realloc(void *ptr, size_t size)
258{
259 struct memprof_stats *bin;
260 size_t size_before;
261 void *ret;
262
263 if (likely(!(profiling & HA_PROF_MEMORY)))
264 return memprof_realloc_handler(ptr, size);
265
266 size_before = malloc_usable_size(ptr);
267 ret = memprof_realloc_handler(ptr, size);
Willy Tarreau2639e2e2021-05-07 08:01:35 +0200268 size = malloc_usable_size(ret);
Willy Tarreauf93c7be2021-05-05 17:07:09 +0200269
Willy Tarreau1de51eb2021-10-22 16:33:53 +0200270 /* only count the extra link for new allocations */
271 if (!ptr)
272 size += sizeof(void *);
273
Willy Tarreau616491b2021-05-11 09:26:23 +0200274 bin = memprof_get_bin(__builtin_return_address(0), MEMPROF_METH_REALLOC);
Willy Tarreauf93c7be2021-05-05 17:07:09 +0200275 if (size > size_before) {
276 _HA_ATOMIC_ADD(&bin->alloc_calls, 1);
Willy Tarreau79acefa2021-05-11 09:12:56 +0200277 _HA_ATOMIC_ADD(&bin->alloc_tot, size - size_before);
Willy Tarreauf93c7be2021-05-05 17:07:09 +0200278 } else if (size < size_before) {
279 _HA_ATOMIC_ADD(&bin->free_calls, 1);
Willy Tarreau79acefa2021-05-11 09:12:56 +0200280 _HA_ATOMIC_ADD(&bin->free_tot, size_before - size);
Willy Tarreauf93c7be2021-05-05 17:07:09 +0200281 }
282 return ret;
283}
284
285/* This is the new global free() function. It must optimize for the normal
286 * case (i.e. profiling disabled) hence the first test to permit a direct jump.
287 * It must remain simple to guarantee the lack of reentrance. stdio is not
288 * possible there even for debugging. The reported size is the really allocated
289 * one as returned by malloc_usable_size(), because this will allow it to be
290 * compared to the one before realloc() or free(). This is a GNU and jemalloc
291 * extension but other systems may also store this size in ptr[-1]. Since
292 * free() is often called on NULL pointers to collect garbage at the end of
293 * many functions or during config parsing, as a special case free(NULL)
294 * doesn't update any stats.
295 */
296void free(void *ptr)
297{
298 struct memprof_stats *bin;
299 size_t size_before;
300
301 if (likely(!(profiling & HA_PROF_MEMORY) || !ptr)) {
302 memprof_free_handler(ptr);
303 return;
304 }
305
Willy Tarreau1de51eb2021-10-22 16:33:53 +0200306 size_before = malloc_usable_size(ptr) + sizeof(void *);
Willy Tarreauf93c7be2021-05-05 17:07:09 +0200307 memprof_free_handler(ptr);
308
Willy Tarreau616491b2021-05-11 09:26:23 +0200309 bin = memprof_get_bin(__builtin_return_address(0), MEMPROF_METH_FREE);
Willy Tarreauf93c7be2021-05-05 17:07:09 +0200310 _HA_ATOMIC_ADD(&bin->free_calls, 1);
311 _HA_ATOMIC_ADD(&bin->free_tot, size_before);
312}
313
Willy Tarreaudb87fc72021-05-05 16:50:40 +0200314#endif // USE_MEMORY_PROFILING
315
Willy Tarreau609aad92018-11-22 08:31:09 +0100316/* Updates the current thread's statistics about stolen CPU time. The unit for
317 * <stolen> is half-milliseconds.
318 */
319void report_stolen_time(uint64_t stolen)
320{
321 activity[tid].cpust_total += stolen;
322 update_freq_ctr(&activity[tid].cpust_1s, stolen);
323 update_freq_ctr_period(&activity[tid].cpust_15s, 15000, stolen);
324}
Willy Tarreau75c62c22018-11-22 11:02:09 +0100325
Willy Tarreau20adfde2021-10-08 11:34:46 +0200326/* Update avg_loop value for the current thread and possibly decide to enable
327 * task-level profiling on the current thread based on its average run time.
328 * The <run_time> argument is the number of microseconds elapsed since the
329 * last time poll() returned.
Willy Tarreaue0650222021-10-06 16:22:09 +0200330 */
Willy Tarreau20adfde2021-10-08 11:34:46 +0200331void activity_count_runtime(uint32_t run_time)
Willy Tarreaue0650222021-10-06 16:22:09 +0200332{
Willy Tarreaue0650222021-10-06 16:22:09 +0200333 uint32_t up, down;
334
335 /* 1 millisecond per loop on average over last 1024 iterations is
336 * enough to turn on profiling.
337 */
338 up = 1000;
339 down = up * 99 / 100;
340
Willy Tarreaue0650222021-10-06 16:22:09 +0200341 run_time = swrate_add(&activity[tid].avg_loop_us, TIME_STATS_SAMPLES, run_time);
342
343 /* In automatic mode, reaching the "up" threshold on average switches
344 * profiling to "on" when automatic, and going back below the "down"
345 * threshold switches to off. The forced modes don't check the load.
346 */
Willy Tarreaubdcd3252022-06-22 09:19:46 +0200347 if (!(_HA_ATOMIC_LOAD(&th_ctx->flags) & TH_FL_TASK_PROFILING)) {
Willy Tarreaue0650222021-10-06 16:22:09 +0200348 if (unlikely((profiling & HA_PROF_TASKS_MASK) == HA_PROF_TASKS_ON ||
349 ((profiling & HA_PROF_TASKS_MASK) == HA_PROF_TASKS_AON &&
350 swrate_avg(run_time, TIME_STATS_SAMPLES) >= up)))
Willy Tarreau680ed5f2022-06-13 15:59:39 +0200351 _HA_ATOMIC_OR(&th_ctx->flags, TH_FL_TASK_PROFILING);
Willy Tarreaue0650222021-10-06 16:22:09 +0200352 } else {
353 if (unlikely((profiling & HA_PROF_TASKS_MASK) == HA_PROF_TASKS_OFF ||
354 ((profiling & HA_PROF_TASKS_MASK) == HA_PROF_TASKS_AOFF &&
355 swrate_avg(run_time, TIME_STATS_SAMPLES) <= down)))
Willy Tarreau680ed5f2022-06-13 15:59:39 +0200356 _HA_ATOMIC_AND(&th_ctx->flags, ~TH_FL_TASK_PROFILING);
Willy Tarreaue0650222021-10-06 16:22:09 +0200357 }
358}
359
Willy Tarreauca3afc22021-05-05 18:33:19 +0200360#ifdef USE_MEMORY_PROFILING
361/* config parser for global "profiling.memory", accepts "on" or "off" */
362static int cfg_parse_prof_memory(char **args, int section_type, struct proxy *curpx,
363 const struct proxy *defpx, const char *file, int line,
364 char **err)
365{
366 if (too_many_args(1, args, err, NULL))
367 return -1;
368
369 if (strcmp(args[1], "on") == 0)
370 profiling |= HA_PROF_MEMORY;
371 else if (strcmp(args[1], "off") == 0)
372 profiling &= ~HA_PROF_MEMORY;
373 else {
374 memprintf(err, "'%s' expects either 'on' or 'off' but got '%s'.", args[0], args[1]);
375 return -1;
376 }
377 return 0;
378}
379#endif // USE_MEMORY_PROFILING
380
Willy Tarreau75c62c22018-11-22 11:02:09 +0100381/* config parser for global "profiling.tasks", accepts "on" or "off" */
382static int cfg_parse_prof_tasks(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +0100383 const struct proxy *defpx, const char *file, int line,
Willy Tarreau75c62c22018-11-22 11:02:09 +0100384 char **err)
385{
386 if (too_many_args(1, args, err, NULL))
387 return -1;
388
389 if (strcmp(args[1], "on") == 0)
Willy Tarreaud2d33482019-04-25 17:09:07 +0200390 profiling = (profiling & ~HA_PROF_TASKS_MASK) | HA_PROF_TASKS_ON;
391 else if (strcmp(args[1], "auto") == 0)
Willy Tarreauaa622b82021-01-28 21:44:22 +0100392 profiling = (profiling & ~HA_PROF_TASKS_MASK) | HA_PROF_TASKS_AOFF;
Willy Tarreau75c62c22018-11-22 11:02:09 +0100393 else if (strcmp(args[1], "off") == 0)
Willy Tarreaud2d33482019-04-25 17:09:07 +0200394 profiling = (profiling & ~HA_PROF_TASKS_MASK) | HA_PROF_TASKS_OFF;
Willy Tarreau75c62c22018-11-22 11:02:09 +0100395 else {
Willy Tarreaud2d33482019-04-25 17:09:07 +0200396 memprintf(err, "'%s' expects either 'on', 'auto', or 'off' but got '%s'.", args[0], args[1]);
Willy Tarreau75c62c22018-11-22 11:02:09 +0100397 return -1;
398 }
399 return 0;
400}
401
402/* parse a "set profiling" command. It always returns 1. */
403static int cli_parse_set_profiling(char **args, char *payload, struct appctx *appctx, void *private)
404{
Willy Tarreau75c62c22018-11-22 11:02:09 +0100405 if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
406 return 1;
407
Willy Tarreau00dd44f2021-05-05 16:44:23 +0200408 if (strcmp(args[2], "memory") == 0) {
Willy Tarreaudb87fc72021-05-05 16:50:40 +0200409#ifdef USE_MEMORY_PROFILING
410 if (strcmp(args[3], "on") == 0) {
411 unsigned int old = profiling;
412 int i;
413
414 while (!_HA_ATOMIC_CAS(&profiling, &old, old | HA_PROF_MEMORY))
415 ;
416
417 /* also flush current profiling stats */
418 for (i = 0; i < sizeof(memprof_stats) / sizeof(memprof_stats[0]); i++) {
419 HA_ATOMIC_STORE(&memprof_stats[i].alloc_calls, 0);
420 HA_ATOMIC_STORE(&memprof_stats[i].free_calls, 0);
421 HA_ATOMIC_STORE(&memprof_stats[i].alloc_tot, 0);
422 HA_ATOMIC_STORE(&memprof_stats[i].free_tot, 0);
423 HA_ATOMIC_STORE(&memprof_stats[i].caller, NULL);
424 }
425 }
426 else if (strcmp(args[3], "off") == 0) {
427 unsigned int old = profiling;
428
429 while (!_HA_ATOMIC_CAS(&profiling, &old, old & ~HA_PROF_MEMORY))
430 ;
431 }
432 else
433 return cli_err(appctx, "Expects either 'on' or 'off'.\n");
434 return 1;
435#else
Willy Tarreau00dd44f2021-05-05 16:44:23 +0200436 return cli_err(appctx, "Memory profiling not compiled in.\n");
Willy Tarreaudb87fc72021-05-05 16:50:40 +0200437#endif
Willy Tarreau00dd44f2021-05-05 16:44:23 +0200438 }
439
Willy Tarreau9d008692019-08-09 11:21:01 +0200440 if (strcmp(args[2], "tasks") != 0)
Ilya Shipitsin3df59892021-05-10 12:50:00 +0500441 return cli_err(appctx, "Expects either 'tasks' or 'memory'.\n");
Willy Tarreau75c62c22018-11-22 11:02:09 +0100442
Willy Tarreaud2d33482019-04-25 17:09:07 +0200443 if (strcmp(args[3], "on") == 0) {
444 unsigned int old = profiling;
Willy Tarreaucfa71012021-01-29 11:56:21 +0100445 int i;
446
Willy Tarreaud2d33482019-04-25 17:09:07 +0200447 while (!_HA_ATOMIC_CAS(&profiling, &old, (old & ~HA_PROF_TASKS_MASK) | HA_PROF_TASKS_ON))
448 ;
Willy Tarreaucfa71012021-01-29 11:56:21 +0100449 /* also flush current profiling stats */
Willy Tarreaua3423872022-09-07 18:49:55 +0200450 for (i = 0; i < SCHED_ACT_HASH_BUCKETS; i++) {
Willy Tarreaucfa71012021-01-29 11:56:21 +0100451 HA_ATOMIC_STORE(&sched_activity[i].calls, 0);
452 HA_ATOMIC_STORE(&sched_activity[i].cpu_time, 0);
453 HA_ATOMIC_STORE(&sched_activity[i].lat_time, 0);
454 HA_ATOMIC_STORE(&sched_activity[i].func, NULL);
Willy Tarreau3d4cdb12022-09-07 18:37:47 +0200455 HA_ATOMIC_STORE(&sched_activity[i].caller, NULL);
Willy Tarreaucfa71012021-01-29 11:56:21 +0100456 }
Willy Tarreaud2d33482019-04-25 17:09:07 +0200457 }
458 else if (strcmp(args[3], "auto") == 0) {
459 unsigned int old = profiling;
Willy Tarreauaa622b82021-01-28 21:44:22 +0100460 unsigned int new;
461
462 do {
463 if ((old & HA_PROF_TASKS_MASK) >= HA_PROF_TASKS_AON)
464 new = (old & ~HA_PROF_TASKS_MASK) | HA_PROF_TASKS_AON;
465 else
466 new = (old & ~HA_PROF_TASKS_MASK) | HA_PROF_TASKS_AOFF;
467 } while (!_HA_ATOMIC_CAS(&profiling, &old, new));
Willy Tarreaud2d33482019-04-25 17:09:07 +0200468 }
469 else if (strcmp(args[3], "off") == 0) {
470 unsigned int old = profiling;
471 while (!_HA_ATOMIC_CAS(&profiling, &old, (old & ~HA_PROF_TASKS_MASK) | HA_PROF_TASKS_OFF))
472 ;
473 }
Willy Tarreau9d008692019-08-09 11:21:01 +0200474 else
475 return cli_err(appctx, "Expects 'on', 'auto', or 'off'.\n");
476
Willy Tarreau75c62c22018-11-22 11:02:09 +0100477 return 1;
478}
479
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200480static int cmp_sched_activity_calls(const void *a, const void *b)
Willy Tarreau1bd67e92021-01-29 00:07:40 +0100481{
482 const struct sched_activity *l = (const struct sched_activity *)a;
483 const struct sched_activity *r = (const struct sched_activity *)b;
484
485 if (l->calls > r->calls)
486 return -1;
487 else if (l->calls < r->calls)
488 return 1;
489 else
490 return 0;
491}
492
Willy Tarreau3d4cdb12022-09-07 18:37:47 +0200493/* sort by address first, then by call count */
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200494static int cmp_sched_activity_addr(const void *a, const void *b)
495{
496 const struct sched_activity *l = (const struct sched_activity *)a;
497 const struct sched_activity *r = (const struct sched_activity *)b;
498
499 if (l->func > r->func)
500 return -1;
501 else if (l->func < r->func)
502 return 1;
Willy Tarreau3d4cdb12022-09-07 18:37:47 +0200503 else if (l->calls > r->calls)
504 return -1;
505 else if (l->calls < r->calls)
506 return 1;
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200507 else
508 return 0;
509}
510
Willy Tarreaue86bc352022-09-08 16:38:10 +0200511/* sort by cpu time first, then by inverse call count (to spot highest offenders) */
512static int cmp_sched_activity_cpu(const void *a, const void *b)
513{
514 const struct sched_activity *l = (const struct sched_activity *)a;
515 const struct sched_activity *r = (const struct sched_activity *)b;
516
517 if (l->cpu_time > r->cpu_time)
518 return -1;
519 else if (l->cpu_time < r->cpu_time)
520 return 1;
521 else if (l->calls < r->calls)
522 return -1;
523 else if (l->calls > r->calls)
524 return 1;
525 else
526 return 0;
527}
528
Willy Tarreaue15615c2021-08-28 12:04:25 +0200529#ifdef USE_MEMORY_PROFILING
Willy Tarreau993d44d2021-05-05 18:07:02 +0200530/* used by qsort below */
531static int cmp_memprof_stats(const void *a, const void *b)
532{
533 const struct memprof_stats *l = (const struct memprof_stats *)a;
534 const struct memprof_stats *r = (const struct memprof_stats *)b;
535
536 if (l->alloc_tot + l->free_tot > r->alloc_tot + r->free_tot)
537 return -1;
538 else if (l->alloc_tot + l->free_tot < r->alloc_tot + r->free_tot)
539 return 1;
540 else
541 return 0;
542}
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200543
544static int cmp_memprof_addr(const void *a, const void *b)
545{
546 const struct memprof_stats *l = (const struct memprof_stats *)a;
547 const struct memprof_stats *r = (const struct memprof_stats *)b;
548
549 if (l->caller > r->caller)
550 return -1;
551 else if (l->caller < r->caller)
552 return 1;
553 else
554 return 0;
555}
Willy Tarreau993d44d2021-05-05 18:07:02 +0200556#endif // USE_MEMORY_PROFILING
557
Willy Tarreau3d4cdb12022-09-07 18:37:47 +0200558/* Computes the index of function pointer <func> and caller <caller> for use
559 * with sched_activity[] or any other similar array passed in <array>, and
560 * returns a pointer to the entry after having atomically assigned it to this
561 * function pointer and caller combination. Note that in case of collision,
562 * the first entry is returned instead ("other").
Willy Tarreaua26be372021-10-06 16:26:33 +0200563 */
Willy Tarreau3d4cdb12022-09-07 18:37:47 +0200564struct sched_activity *sched_activity_entry(struct sched_activity *array, const void *func, const void *caller)
Willy Tarreaua26be372021-10-06 16:26:33 +0200565{
Willy Tarreau3d4cdb12022-09-07 18:37:47 +0200566 uint32_t hash = ptr2_hash(func, caller, SCHED_ACT_HASH_BITS);
Willy Tarreaua26be372021-10-06 16:26:33 +0200567 struct sched_activity *ret;
Willy Tarreau64435aa2022-09-07 18:54:30 +0200568 const void *old;
569 int tries = 16;
Willy Tarreaua26be372021-10-06 16:26:33 +0200570
Willy Tarreau64435aa2022-09-07 18:54:30 +0200571 for (tries = 16; tries > 0; tries--, hash++) {
572 ret = &array[hash];
Willy Tarreaua26be372021-10-06 16:26:33 +0200573
Willy Tarreau64435aa2022-09-07 18:54:30 +0200574 while (1) {
575 if (likely(ret->func)) {
576 if (likely(ret->func == func && ret->caller == caller))
577 return ret;
578 break;
579 }
Willy Tarreaua26be372021-10-06 16:26:33 +0200580
Willy Tarreau64435aa2022-09-07 18:54:30 +0200581 /* try to create the new entry. Func is sufficient to
582 * reserve the node.
583 */
584 old = NULL;
585 if (HA_ATOMIC_CAS(&ret->func, &old, func)) {
586 ret->caller = caller;
587 return ret;
588 }
589 /* changed in parallel, check again */
590 }
591 }
Willy Tarreaua26be372021-10-06 16:26:33 +0200592
593 return array;
594}
595
Willy Tarreau75c62c22018-11-22 11:02:09 +0100596/* This function dumps all profiling settings. It returns 0 if the output
597 * buffer is full and it needs to be called again, otherwise non-zero.
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200598 * It dumps some parts depending on the following states from show_prof_ctx:
599 * dump_step:
Willy Tarreau637d85a2021-05-05 17:33:27 +0200600 * 0, 4: dump status, then jump to 1 if 0
601 * 1, 5: dump tasks, then jump to 2 if 1
602 * 2, 6: dump memory, then stop
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200603 * linenum:
Willy Tarreau637d85a2021-05-05 17:33:27 +0200604 * restart line for each step (starts at zero)
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200605 * maxcnt:
Willy Tarreau637d85a2021-05-05 17:33:27 +0200606 * may contain a configured max line count for each step (0=not set)
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200607 * byaddr:
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200608 * 0: sort by usage
609 * 1: sort by address
Willy Tarreau75c62c22018-11-22 11:02:09 +0100610 */
611static int cli_io_handler_show_profiling(struct appctx *appctx)
612{
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200613 struct show_prof_ctx *ctx = appctx->svcctx;
Willy Tarreaua3423872022-09-07 18:49:55 +0200614 struct sched_activity tmp_activity[SCHED_ACT_HASH_BUCKETS] __attribute__((aligned(64)));
Willy Tarreaue15615c2021-08-28 12:04:25 +0200615#ifdef USE_MEMORY_PROFILING
Willy Tarreau993d44d2021-05-05 18:07:02 +0200616 struct memprof_stats tmp_memstats[MEMPROF_HASH_BUCKETS + 1];
Willy Tarreauf5fb8582021-05-11 14:06:24 +0200617 unsigned long long tot_alloc_calls, tot_free_calls;
618 unsigned long long tot_alloc_bytes, tot_free_bytes;
Willy Tarreau993d44d2021-05-05 18:07:02 +0200619#endif
Willy Tarreauc12b3212022-05-27 11:08:15 +0200620 struct stconn *sc = appctx_sc(appctx);
Willy Tarreau1bd67e92021-01-29 00:07:40 +0100621 struct buffer *name_buffer = get_trash_chunk();
Willy Tarreau3d4cdb12022-09-07 18:37:47 +0200622 const struct ha_caller *caller;
Willy Tarreaud2d33482019-04-25 17:09:07 +0200623 const char *str;
Willy Tarreau637d85a2021-05-05 17:33:27 +0200624 int max_lines;
Willy Tarreaudc89b182022-09-08 16:05:57 +0200625 int i, j, max;
Willy Tarreau75c62c22018-11-22 11:02:09 +0100626
Christopher Fauletda89e9b2023-01-04 14:11:10 +0100627 if (unlikely(sc_ic(sc)->flags & CF_SHUTW))
Willy Tarreau75c62c22018-11-22 11:02:09 +0100628 return 1;
629
630 chunk_reset(&trash);
631
Willy Tarreaud2d33482019-04-25 17:09:07 +0200632 switch (profiling & HA_PROF_TASKS_MASK) {
Willy Tarreauaa622b82021-01-28 21:44:22 +0100633 case HA_PROF_TASKS_AOFF: str="auto-off"; break;
634 case HA_PROF_TASKS_AON: str="auto-on"; break;
Willy Tarreaud2d33482019-04-25 17:09:07 +0200635 case HA_PROF_TASKS_ON: str="on"; break;
636 default: str="off"; break;
637 }
638
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200639 if ((ctx->dump_step & 3) != 0)
Willy Tarreau637d85a2021-05-05 17:33:27 +0200640 goto skip_status;
Willy Tarreau1bd67e92021-01-29 00:07:40 +0100641
Willy Tarreaud2d33482019-04-25 17:09:07 +0200642 chunk_printf(&trash,
Willy Tarreau00dd44f2021-05-05 16:44:23 +0200643 "Per-task CPU profiling : %-8s # set profiling tasks {on|auto|off}\n"
644 "Memory usage profiling : %-8s # set profiling memory {on|off}\n",
645 str, (profiling & HA_PROF_MEMORY) ? "on" : "off");
Willy Tarreau75c62c22018-11-22 11:02:09 +0100646
Willy Tarreaud0a06d52022-05-18 15:07:19 +0200647 if (applet_putchk(appctx, &trash) == -1) {
Willy Tarreau637d85a2021-05-05 17:33:27 +0200648 /* failed, try again */
Willy Tarreau637d85a2021-05-05 17:33:27 +0200649 return 0;
650 }
651
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200652 ctx->linenum = 0; // reset first line to dump
653 if ((ctx->dump_step & 4) == 0)
654 ctx->dump_step++; // next step
Willy Tarreau637d85a2021-05-05 17:33:27 +0200655
656 skip_status:
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200657 if ((ctx->dump_step & 3) != 1)
Willy Tarreau637d85a2021-05-05 17:33:27 +0200658 goto skip_tasks;
Willy Tarreau1bd67e92021-01-29 00:07:40 +0100659
Willy Tarreau637d85a2021-05-05 17:33:27 +0200660 memcpy(tmp_activity, sched_activity, sizeof(tmp_activity));
Willy Tarreaudc89b182022-09-08 16:05:57 +0200661 /* for addr sort and for callee aggregation we have to first sort by address */
Willy Tarreaue86bc352022-09-08 16:38:10 +0200662 if (ctx->aggr || ctx->by_what == 1) // sort by addr
Willy Tarreaudc89b182022-09-08 16:05:57 +0200663 qsort(tmp_activity, SCHED_ACT_HASH_BUCKETS, sizeof(tmp_activity[0]), cmp_sched_activity_addr);
664
665 if (ctx->aggr) {
666 /* merge entries for the same callee and reset their count */
667 for (i = j = 0; i < SCHED_ACT_HASH_BUCKETS; i = j) {
668 for (j = i + 1; j < SCHED_ACT_HASH_BUCKETS && tmp_activity[j].func == tmp_activity[i].func; j++) {
669 tmp_activity[i].calls += tmp_activity[j].calls;
670 tmp_activity[i].cpu_time += tmp_activity[j].cpu_time;
671 tmp_activity[i].lat_time += tmp_activity[j].lat_time;
672 tmp_activity[j].calls = 0;
673 }
674 }
675 }
676
Willy Tarreaue86bc352022-09-08 16:38:10 +0200677 if (!ctx->by_what) // sort by usage
Willy Tarreaua3423872022-09-07 18:49:55 +0200678 qsort(tmp_activity, SCHED_ACT_HASH_BUCKETS, sizeof(tmp_activity[0]), cmp_sched_activity_calls);
Willy Tarreaue86bc352022-09-08 16:38:10 +0200679 else if (ctx->by_what == 2) // by cpu_tot
680 qsort(tmp_activity, SCHED_ACT_HASH_BUCKETS, sizeof(tmp_activity[0]), cmp_sched_activity_cpu);
Willy Tarreau637d85a2021-05-05 17:33:27 +0200681
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200682 if (!ctx->linenum)
Willy Tarreau637d85a2021-05-05 17:33:27 +0200683 chunk_appendf(&trash, "Tasks activity:\n"
684 " function calls cpu_tot cpu_avg lat_tot lat_avg\n");
685
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200686 max_lines = ctx->maxcnt;
Willy Tarreau637d85a2021-05-05 17:33:27 +0200687 if (!max_lines)
Willy Tarreaua3423872022-09-07 18:49:55 +0200688 max_lines = SCHED_ACT_HASH_BUCKETS;
Willy Tarreau637d85a2021-05-05 17:33:27 +0200689
Willy Tarreaudc89b182022-09-08 16:05:57 +0200690 for (i = ctx->linenum; i < max_lines; i++) {
691 if (!tmp_activity[i].calls)
692 continue; // skip aggregated or empty entries
693
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200694 ctx->linenum = i;
Willy Tarreau1bd67e92021-01-29 00:07:40 +0100695 chunk_reset(name_buffer);
Willy Tarreau3d4cdb12022-09-07 18:37:47 +0200696 caller = HA_ATOMIC_LOAD(&tmp_activity[i].caller);
Willy Tarreau1bd67e92021-01-29 00:07:40 +0100697
698 if (!tmp_activity[i].func)
699 chunk_printf(name_buffer, "other");
700 else
701 resolve_sym_name(name_buffer, "", tmp_activity[i].func);
702
703 /* reserve 35 chars for name+' '+#calls, knowing that longer names
704 * are often used for less often called functions.
705 */
706 max = 35 - name_buffer->data;
707 if (max < 1)
708 max = 1;
709 chunk_appendf(&trash, " %s%*llu", name_buffer->area, max, (unsigned long long)tmp_activity[i].calls);
710
711 print_time_short(&trash, " ", tmp_activity[i].cpu_time, "");
712 print_time_short(&trash, " ", tmp_activity[i].cpu_time / tmp_activity[i].calls, "");
713 print_time_short(&trash, " ", tmp_activity[i].lat_time, "");
Willy Tarreau3d4cdb12022-09-07 18:37:47 +0200714 print_time_short(&trash, " ", tmp_activity[i].lat_time / tmp_activity[i].calls, "");
715
Willy Tarreaudc89b182022-09-08 16:05:57 +0200716 if (caller && !ctx->aggr && caller->what <= WAKEUP_TYPE_APPCTX_WAKEUP)
Willy Tarreau3d4cdb12022-09-07 18:37:47 +0200717 chunk_appendf(&trash, " <- %s@%s:%d %s",
718 caller->func, caller->file, caller->line,
719 task_wakeup_type_str(caller->what));
720
721 b_putchr(&trash, '\n');
Willy Tarreau637d85a2021-05-05 17:33:27 +0200722
Willy Tarreaud0a06d52022-05-18 15:07:19 +0200723 if (applet_putchk(appctx, &trash) == -1) {
Willy Tarreau637d85a2021-05-05 17:33:27 +0200724 /* failed, try again */
Willy Tarreau637d85a2021-05-05 17:33:27 +0200725 return 0;
726 }
Willy Tarreau1bd67e92021-01-29 00:07:40 +0100727 }
728
Willy Tarreaud0a06d52022-05-18 15:07:19 +0200729 if (applet_putchk(appctx, &trash) == -1) {
Willy Tarreau75c62c22018-11-22 11:02:09 +0100730 /* failed, try again */
Willy Tarreau75c62c22018-11-22 11:02:09 +0100731 return 0;
732 }
Willy Tarreau637d85a2021-05-05 17:33:27 +0200733
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200734 ctx->linenum = 0; // reset first line to dump
735 if ((ctx->dump_step & 4) == 0)
736 ctx->dump_step++; // next step
Willy Tarreau637d85a2021-05-05 17:33:27 +0200737
738 skip_tasks:
739
Willy Tarreaue15615c2021-08-28 12:04:25 +0200740#ifdef USE_MEMORY_PROFILING
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200741 if ((ctx->dump_step & 3) != 2)
Willy Tarreau993d44d2021-05-05 18:07:02 +0200742 goto skip_mem;
743
744 memcpy(tmp_memstats, memprof_stats, sizeof(tmp_memstats));
Willy Tarreaue86bc352022-09-08 16:38:10 +0200745 if (ctx->by_what)
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200746 qsort(tmp_memstats, MEMPROF_HASH_BUCKETS+1, sizeof(tmp_memstats[0]), cmp_memprof_addr);
747 else
748 qsort(tmp_memstats, MEMPROF_HASH_BUCKETS+1, sizeof(tmp_memstats[0]), cmp_memprof_stats);
Willy Tarreau993d44d2021-05-05 18:07:02 +0200749
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200750 if (!ctx->linenum)
Willy Tarreau993d44d2021-05-05 18:07:02 +0200751 chunk_appendf(&trash,
752 "Alloc/Free statistics by call place:\n"
Willy Tarreau616491b2021-05-11 09:26:23 +0200753 " Calls | Tot Bytes | Caller and method\n"
Willy Tarreau993d44d2021-05-05 18:07:02 +0200754 "<- alloc -> <- free ->|<-- alloc ---> <-- free ---->|\n");
755
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200756 max_lines = ctx->maxcnt;
Willy Tarreau993d44d2021-05-05 18:07:02 +0200757 if (!max_lines)
758 max_lines = MEMPROF_HASH_BUCKETS + 1;
759
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200760 for (i = ctx->linenum; i < max_lines; i++) {
Willy Tarreau993d44d2021-05-05 18:07:02 +0200761 struct memprof_stats *entry = &tmp_memstats[i];
762
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200763 ctx->linenum = i;
Willy Tarreau993d44d2021-05-05 18:07:02 +0200764 if (!entry->alloc_calls && !entry->free_calls)
765 continue;
766 chunk_appendf(&trash, "%11llu %11llu %14llu %14llu| %16p ",
767 entry->alloc_calls, entry->free_calls,
768 entry->alloc_tot, entry->free_tot,
769 entry->caller);
770
771 if (entry->caller)
772 resolve_sym_name(&trash, NULL, entry->caller);
773 else
774 chunk_appendf(&trash, "[other]");
775
Willy Tarreau8cce4d72021-10-22 16:26:12 +0200776 chunk_appendf(&trash," %s(%lld)", memprof_methods[entry->method],
Willy Tarreau616491b2021-05-11 09:26:23 +0200777 (long long)(entry->alloc_tot - entry->free_tot) / (long long)(entry->alloc_calls + entry->free_calls));
Willy Tarreau993d44d2021-05-05 18:07:02 +0200778
Willy Tarreau8cce4d72021-10-22 16:26:12 +0200779 if (entry->alloc_tot && entry->free_tot) {
780 /* that's a realloc, show the total diff to help spot leaks */
781 chunk_appendf(&trash," [delta=%lld]", (long long)(entry->alloc_tot - entry->free_tot));
782 }
783
Willy Tarreau42b180d2022-08-17 09:35:16 +0200784 if (entry->info) {
785 /* that's a pool name */
786 const struct pool_head *pool = entry->info;
787 chunk_appendf(&trash," [pool=%s]", pool->name);
788 }
789
Willy Tarreau8cce4d72021-10-22 16:26:12 +0200790 chunk_appendf(&trash, "\n");
791
Willy Tarreaud0a06d52022-05-18 15:07:19 +0200792 if (applet_putchk(appctx, &trash) == -1)
Willy Tarreau993d44d2021-05-05 18:07:02 +0200793 return 0;
Willy Tarreau993d44d2021-05-05 18:07:02 +0200794 }
795
Willy Tarreaud0a06d52022-05-18 15:07:19 +0200796 if (applet_putchk(appctx, &trash) == -1)
Willy Tarreau993d44d2021-05-05 18:07:02 +0200797 return 0;
Willy Tarreau993d44d2021-05-05 18:07:02 +0200798
Willy Tarreauf5fb8582021-05-11 14:06:24 +0200799 tot_alloc_calls = tot_free_calls = tot_alloc_bytes = tot_free_bytes = 0;
800 for (i = 0; i < max_lines; i++) {
801 tot_alloc_calls += tmp_memstats[i].alloc_calls;
802 tot_free_calls += tmp_memstats[i].free_calls;
803 tot_alloc_bytes += tmp_memstats[i].alloc_tot;
804 tot_free_bytes += tmp_memstats[i].free_tot;
805 }
806
807 chunk_appendf(&trash,
808 "-----------------------|-----------------------------|\n"
809 "%11llu %11llu %14llu %14llu| <- Total; Delta_calls=%lld; Delta_bytes=%lld\n",
810 tot_alloc_calls, tot_free_calls,
811 tot_alloc_bytes, tot_free_bytes,
812 tot_alloc_calls - tot_free_calls,
813 tot_alloc_bytes - tot_free_bytes);
814
Willy Tarreaud0a06d52022-05-18 15:07:19 +0200815 if (applet_putchk(appctx, &trash) == -1)
Willy Tarreauf5fb8582021-05-11 14:06:24 +0200816 return 0;
Willy Tarreauf5fb8582021-05-11 14:06:24 +0200817
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200818 ctx->linenum = 0; // reset first line to dump
819 if ((ctx->dump_step & 4) == 0)
820 ctx->dump_step++; // next step
Willy Tarreau993d44d2021-05-05 18:07:02 +0200821
822 skip_mem:
823#endif // USE_MEMORY_PROFILING
824
Willy Tarreau75c62c22018-11-22 11:02:09 +0100825 return 1;
826}
827
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200828/* parse a "show profiling" command. It returns 1 on failure, 0 if it starts to dump.
829 * - cli.i0 is set to the first state (0=all, 4=status, 5=tasks, 6=memory)
830 * - cli.o1 is set to 1 if the output must be sorted by addr instead of usage
831 * - cli.o0 is set to the number of lines of output
832 */
Willy Tarreau42712cb2021-05-05 17:48:13 +0200833static int cli_parse_show_profiling(char **args, char *payload, struct appctx *appctx, void *private)
834{
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200835 struct show_prof_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200836 int arg;
837
Willy Tarreau42712cb2021-05-05 17:48:13 +0200838 if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
839 return 1;
840
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200841 for (arg = 2; *args[arg]; arg++) {
842 if (strcmp(args[arg], "all") == 0) {
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200843 ctx->dump_step = 0; // will cycle through 0,1,2; default
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200844 }
845 else if (strcmp(args[arg], "status") == 0) {
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200846 ctx->dump_step = 4; // will visit status only
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200847 }
848 else if (strcmp(args[arg], "tasks") == 0) {
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200849 ctx->dump_step = 5; // will visit tasks only
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200850 }
851 else if (strcmp(args[arg], "memory") == 0) {
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200852 ctx->dump_step = 6; // will visit memory only
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200853 }
854 else if (strcmp(args[arg], "byaddr") == 0) {
Willy Tarreaue86bc352022-09-08 16:38:10 +0200855 ctx->by_what = 1; // sort output by address instead of usage
856 }
857 else if (strcmp(args[arg], "bytime") == 0) {
858 ctx->by_what = 2; // sort output by total time instead of usage
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200859 }
Willy Tarreaudc89b182022-09-08 16:05:57 +0200860 else if (strcmp(args[arg], "aggr") == 0) {
861 ctx->aggr = 1; // aggregate output by callee
862 }
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200863 else if (isdigit((unsigned char)*args[arg])) {
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200864 ctx->maxcnt = atoi(args[arg]); // number of entries to dump
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200865 }
866 else
Willy Tarreaue86bc352022-09-08 16:38:10 +0200867 return cli_err(appctx, "Expects either 'all', 'status', 'tasks', 'memory', 'byaddr', 'bytime', 'aggr' or a max number of output lines.\n");
Willy Tarreau42712cb2021-05-05 17:48:13 +0200868 }
869 return 0;
870}
871
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100872/* This function scans all threads' run queues and collects statistics about
873 * running tasks. It returns 0 if the output buffer is full and it needs to be
874 * called again, otherwise non-zero.
875 */
876static int cli_io_handler_show_tasks(struct appctx *appctx)
877{
Willy Tarreaua3423872022-09-07 18:49:55 +0200878 struct sched_activity tmp_activity[SCHED_ACT_HASH_BUCKETS] __attribute__((aligned(64)));
Willy Tarreauc12b3212022-05-27 11:08:15 +0200879 struct stconn *sc = appctx_sc(appctx);
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100880 struct buffer *name_buffer = get_trash_chunk();
881 struct sched_activity *entry;
882 const struct tasklet *tl;
883 const struct task *t;
884 uint64_t now_ns, lat;
Willy Tarreau319d1362022-06-16 16:28:01 +0200885 struct eb32_node *rqnode;
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100886 uint64_t tot_calls;
887 int thr, queue;
888 int i, max;
889
Christopher Fauletda89e9b2023-01-04 14:11:10 +0100890 if (unlikely(sc_ic(sc)->flags & CF_SHUTW))
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100891 return 1;
892
893 /* It's not possible to scan queues in small chunks and yield in the
894 * middle of the dump and come back again. So what we're doing instead
895 * is to freeze all threads and inspect their queues at once as fast as
896 * possible, using a sched_activity array to collect metrics with
897 * limited collision, then we'll report statistics only. The tasks'
898 * #calls will reflect the number of occurrences, and the lat_time will
Willy Tarreau75f72332021-01-29 15:04:16 +0100899 * reflect the latency when set. We prefer to take the time before
900 * calling thread_isolate() so that the wait time doesn't impact the
901 * measurement accuracy. However this requires to take care of negative
902 * times since tasks might be queued after we retrieve it.
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100903 */
904
905 now_ns = now_mono_time();
906 memset(tmp_activity, 0, sizeof(tmp_activity));
907
908 thread_isolate();
909
910 /* 1. global run queue */
911
912#ifdef USE_THREAD
Willy Tarreau6f780382022-06-16 15:30:50 +0200913 for (thr = 0; thr < global.nbthread; thr++) {
914 /* task run queue */
Willy Tarreau319d1362022-06-16 16:28:01 +0200915 rqnode = eb32_first(&ha_thread_ctx[thr].rqueue_shared);
Willy Tarreau6f780382022-06-16 15:30:50 +0200916 while (rqnode) {
Willy Tarreau319d1362022-06-16 16:28:01 +0200917 t = eb32_entry(rqnode, struct task, rq);
Willy Tarreau3d4cdb12022-09-07 18:37:47 +0200918 entry = sched_activity_entry(tmp_activity, t->process, NULL);
Willy Tarreau04e50b32022-09-07 14:49:50 +0200919 if (t->wake_date) {
920 lat = now_ns - t->wake_date;
Willy Tarreau6f780382022-06-16 15:30:50 +0200921 if ((int64_t)lat > 0)
922 entry->lat_time += lat;
923 }
924 entry->calls++;
Willy Tarreau319d1362022-06-16 16:28:01 +0200925 rqnode = eb32_next(rqnode);
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100926 }
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100927 }
928#endif
929 /* 2. all threads's local run queues */
930 for (thr = 0; thr < global.nbthread; thr++) {
931 /* task run queue */
Willy Tarreau319d1362022-06-16 16:28:01 +0200932 rqnode = eb32_first(&ha_thread_ctx[thr].rqueue);
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100933 while (rqnode) {
Willy Tarreau319d1362022-06-16 16:28:01 +0200934 t = eb32_entry(rqnode, struct task, rq);
Willy Tarreau3d4cdb12022-09-07 18:37:47 +0200935 entry = sched_activity_entry(tmp_activity, t->process, NULL);
Willy Tarreau04e50b32022-09-07 14:49:50 +0200936 if (t->wake_date) {
937 lat = now_ns - t->wake_date;
Willy Tarreau75f72332021-01-29 15:04:16 +0100938 if ((int64_t)lat > 0)
939 entry->lat_time += lat;
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100940 }
941 entry->calls++;
Willy Tarreau319d1362022-06-16 16:28:01 +0200942 rqnode = eb32_next(rqnode);
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100943 }
944
945 /* shared tasklet list */
Willy Tarreau1a9c9222021-10-01 11:30:33 +0200946 list_for_each_entry(tl, mt_list_to_list(&ha_thread_ctx[thr].shared_tasklet_list), list) {
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100947 t = (const struct task *)tl;
Willy Tarreau3d4cdb12022-09-07 18:37:47 +0200948 entry = sched_activity_entry(tmp_activity, t->process, NULL);
Willy Tarreau04e50b32022-09-07 14:49:50 +0200949 if (!TASK_IS_TASKLET(t) && t->wake_date) {
950 lat = now_ns - t->wake_date;
Willy Tarreau75f72332021-01-29 15:04:16 +0100951 if ((int64_t)lat > 0)
952 entry->lat_time += lat;
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100953 }
954 entry->calls++;
955 }
956
957 /* classful tasklets */
958 for (queue = 0; queue < TL_CLASSES; queue++) {
Willy Tarreau1a9c9222021-10-01 11:30:33 +0200959 list_for_each_entry(tl, &ha_thread_ctx[thr].tasklets[queue], list) {
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100960 t = (const struct task *)tl;
Willy Tarreau3d4cdb12022-09-07 18:37:47 +0200961 entry = sched_activity_entry(tmp_activity, t->process, NULL);
Willy Tarreau04e50b32022-09-07 14:49:50 +0200962 if (!TASK_IS_TASKLET(t) && t->wake_date) {
963 lat = now_ns - t->wake_date;
Willy Tarreau75f72332021-01-29 15:04:16 +0100964 if ((int64_t)lat > 0)
965 entry->lat_time += lat;
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100966 }
967 entry->calls++;
968 }
969 }
970 }
971
972 /* hopefully we're done */
973 thread_release();
974
975 chunk_reset(&trash);
976
977 tot_calls = 0;
Willy Tarreaua3423872022-09-07 18:49:55 +0200978 for (i = 0; i < SCHED_ACT_HASH_BUCKETS; i++)
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100979 tot_calls += tmp_activity[i].calls;
980
Willy Tarreaua3423872022-09-07 18:49:55 +0200981 qsort(tmp_activity, SCHED_ACT_HASH_BUCKETS, sizeof(tmp_activity[0]), cmp_sched_activity_calls);
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100982
983 chunk_appendf(&trash, "Running tasks: %d (%d threads)\n"
984 " function places %% lat_tot lat_avg\n",
985 (int)tot_calls, global.nbthread);
986
Willy Tarreaua3423872022-09-07 18:49:55 +0200987 for (i = 0; i < SCHED_ACT_HASH_BUCKETS && tmp_activity[i].calls; i++) {
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100988 chunk_reset(name_buffer);
989
990 if (!tmp_activity[i].func)
991 chunk_printf(name_buffer, "other");
992 else
993 resolve_sym_name(name_buffer, "", tmp_activity[i].func);
994
995 /* reserve 35 chars for name+' '+#calls, knowing that longer names
996 * are often used for less often called functions.
997 */
998 max = 35 - name_buffer->data;
999 if (max < 1)
1000 max = 1;
1001 chunk_appendf(&trash, " %s%*llu %3d.%1d",
1002 name_buffer->area, max, (unsigned long long)tmp_activity[i].calls,
1003 (int)(100ULL * tmp_activity[i].calls / tot_calls),
1004 (int)((1000ULL * tmp_activity[i].calls / tot_calls)%10));
1005 print_time_short(&trash, " ", tmp_activity[i].lat_time, "");
1006 print_time_short(&trash, " ", tmp_activity[i].lat_time / tmp_activity[i].calls, "\n");
1007 }
1008
Willy Tarreaud0a06d52022-05-18 15:07:19 +02001009 if (applet_putchk(appctx, &trash) == -1) {
Willy Tarreau7eff06e2021-01-29 11:32:55 +01001010 /* failed, try again */
Willy Tarreau7eff06e2021-01-29 11:32:55 +01001011 return 0;
1012 }
1013 return 1;
1014}
1015
Willy Tarreauf9607f82022-11-25 15:32:38 +01001016/* This function dumps some activity counters used by developers and support to
1017 * rule out some hypothesis during bug reports. It returns 0 if the output
1018 * buffer is full and it needs to be called again, otherwise non-zero. It dumps
1019 * everything at once in the buffer and is not designed to do it in multiple
1020 * passes.
1021 */
1022static int cli_io_handler_show_activity(struct appctx *appctx)
1023{
1024 struct stconn *sc = appctx_sc(appctx);
1025 struct show_activity_ctx *actctx = appctx->svcctx;
1026 int tgt = actctx->thr; // target thread, -1 for all, 0 for total only
1027 struct timeval up;
1028 int thr;
1029
Christopher Fauletda89e9b2023-01-04 14:11:10 +01001030 if (unlikely(sc_ic(sc)->flags & CF_SHUTW))
Willy Tarreauf9607f82022-11-25 15:32:38 +01001031 return 1;
1032
1033 chunk_reset(&trash);
1034
1035#undef SHOW_TOT
1036#define SHOW_TOT(t, x) \
1037 do { \
1038 unsigned int _v[MAX_THREADS]; \
1039 unsigned int _tot; \
1040 const unsigned int _nbt = global.nbthread; \
1041 _tot = t = 0; \
1042 do { \
1043 _tot += _v[t] = (x); \
1044 } while (++t < _nbt); \
1045 if (_nbt == 1) { \
1046 chunk_appendf(&trash, " %u\n", _tot); \
1047 break; \
1048 } \
1049 if (tgt == -1) { \
1050 chunk_appendf(&trash, " %u [", _tot); \
1051 for (t = 0; t < _nbt; t++) \
1052 chunk_appendf(&trash, " %u", _v[t]); \
1053 chunk_appendf(&trash, " ]\n"); \
1054 } else if (tgt == 0) \
1055 chunk_appendf(&trash, " %u\n", _tot); \
1056 else \
1057 chunk_appendf(&trash, " %u\n", _v[tgt-1]);\
1058 } while (0)
1059
1060#undef SHOW_AVG
1061#define SHOW_AVG(t, x) \
1062 do { \
1063 unsigned int _v[MAX_THREADS]; \
1064 unsigned int _tot; \
1065 const unsigned int _nbt = global.nbthread; \
1066 _tot = t = 0; \
1067 do { \
1068 _tot += _v[t] = (x); \
1069 } while (++t < _nbt); \
1070 if (_nbt == 1) { \
1071 chunk_appendf(&trash, " %u\n", _tot); \
1072 break; \
1073 } \
1074 if (tgt == -1) { \
1075 chunk_appendf(&trash, " %u [", (_tot + _nbt/2) / _nbt); \
1076 for (t = 0; t < _nbt; t++) \
1077 chunk_appendf(&trash, " %u", _v[t]); \
1078 chunk_appendf(&trash, " ]\n"); \
1079 } else if (tgt == 0) \
1080 chunk_appendf(&trash, " %u\n", (_tot + _nbt/2) / _nbt); \
1081 else \
1082 chunk_appendf(&trash, " %u\n", _v[tgt-1]);\
1083 } while (0)
1084
1085 /* retrieve uptime */
1086 tv_remain(&start_date, &now, &up);
1087
1088 chunk_appendf(&trash, "thread_id: %u (%u..%u)\n", tid + 1, 1, global.nbthread);
1089 chunk_appendf(&trash, "date_now: %lu.%06lu\n", (ulong)now.tv_sec, (ulong)now.tv_usec);
1090 chunk_appendf(&trash, "uptime_now: %lu.%06lu\n", (ulong)up.tv_sec, (ulong)up.tv_usec);
1091 chunk_appendf(&trash, "ctxsw:"); SHOW_TOT(thr, activity[thr].ctxsw);
1092 chunk_appendf(&trash, "tasksw:"); SHOW_TOT(thr, activity[thr].tasksw);
1093 chunk_appendf(&trash, "empty_rq:"); SHOW_TOT(thr, activity[thr].empty_rq);
1094 chunk_appendf(&trash, "long_rq:"); SHOW_TOT(thr, activity[thr].long_rq);
1095 chunk_appendf(&trash, "loops:"); SHOW_TOT(thr, activity[thr].loops);
1096 chunk_appendf(&trash, "wake_tasks:"); SHOW_TOT(thr, activity[thr].wake_tasks);
1097 chunk_appendf(&trash, "wake_signal:"); SHOW_TOT(thr, activity[thr].wake_signal);
1098 chunk_appendf(&trash, "poll_io:"); SHOW_TOT(thr, activity[thr].poll_io);
1099 chunk_appendf(&trash, "poll_exp:"); SHOW_TOT(thr, activity[thr].poll_exp);
1100 chunk_appendf(&trash, "poll_drop_fd:"); SHOW_TOT(thr, activity[thr].poll_drop_fd);
1101 chunk_appendf(&trash, "poll_skip_fd:"); SHOW_TOT(thr, activity[thr].poll_skip_fd);
1102 chunk_appendf(&trash, "conn_dead:"); SHOW_TOT(thr, activity[thr].conn_dead);
1103 chunk_appendf(&trash, "stream_calls:"); SHOW_TOT(thr, activity[thr].stream_calls);
1104 chunk_appendf(&trash, "pool_fail:"); SHOW_TOT(thr, activity[thr].pool_fail);
1105 chunk_appendf(&trash, "buf_wait:"); SHOW_TOT(thr, activity[thr].buf_wait);
1106 chunk_appendf(&trash, "cpust_ms_tot:"); SHOW_TOT(thr, activity[thr].cpust_total / 2);
1107 chunk_appendf(&trash, "cpust_ms_1s:"); SHOW_TOT(thr, read_freq_ctr(&activity[thr].cpust_1s) / 2);
1108 chunk_appendf(&trash, "cpust_ms_15s:"); SHOW_TOT(thr, read_freq_ctr_period(&activity[thr].cpust_15s, 15000) / 2);
1109 chunk_appendf(&trash, "avg_loop_us:"); SHOW_AVG(thr, swrate_avg(activity[thr].avg_loop_us, TIME_STATS_SAMPLES));
1110 chunk_appendf(&trash, "accepted:"); SHOW_TOT(thr, activity[thr].accepted);
1111 chunk_appendf(&trash, "accq_pushed:"); SHOW_TOT(thr, activity[thr].accq_pushed);
1112 chunk_appendf(&trash, "accq_full:"); SHOW_TOT(thr, activity[thr].accq_full);
1113#ifdef USE_THREAD
1114 chunk_appendf(&trash, "accq_ring:"); SHOW_TOT(thr, (accept_queue_rings[thr].tail - accept_queue_rings[thr].head + ACCEPT_QUEUE_SIZE) % ACCEPT_QUEUE_SIZE);
1115 chunk_appendf(&trash, "fd_takeover:"); SHOW_TOT(thr, activity[thr].fd_takeover);
1116#endif
1117
1118#if defined(DEBUG_DEV)
1119 /* keep these ones at the end */
1120 chunk_appendf(&trash, "ctr0:"); SHOW_TOT(thr, activity[thr].ctr0);
1121 chunk_appendf(&trash, "ctr1:"); SHOW_TOT(thr, activity[thr].ctr1);
1122 chunk_appendf(&trash, "ctr2:"); SHOW_TOT(thr, activity[thr].ctr2);
1123#endif
1124
1125 if (applet_putchk(appctx, &trash) == -1) {
1126 chunk_reset(&trash);
1127 chunk_printf(&trash, "[output too large, cannot dump]\n");
1128 }
1129
1130#undef SHOW_AVG
1131#undef SHOW_TOT
1132 /* dump complete */
1133 return 1;
1134}
1135
1136/* parse a "show activity" CLI request. Returns 0 if it needs to continue, 1 if it
1137 * wants to stop here. It sets a show_activity_ctx context where, if a specific
1138 * thread is requested, it puts the thread number into ->thr otherwise sets it to
1139 * -1.
1140 */
1141static int cli_parse_show_activity(char **args, char *payload, struct appctx *appctx, void *private)
1142{
1143 struct show_activity_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
1144
1145 if (!cli_has_level(appctx, ACCESS_LVL_OPER))
1146 return 1;
1147
1148 ctx->thr = -1; // show all by default
1149 if (*args[2])
1150 ctx->thr = atoi(args[2]);
1151
1152 if (ctx->thr < -1 || ctx->thr > global.nbthread)
1153 return cli_err(appctx, "Thread ID number must be between -1 and nbthread\n");
1154
1155 return 0;
1156}
1157
Willy Tarreau75c62c22018-11-22 11:02:09 +01001158/* config keyword parsers */
1159static struct cfg_kw_list cfg_kws = {ILH, {
Willy Tarreauca3afc22021-05-05 18:33:19 +02001160#ifdef USE_MEMORY_PROFILING
1161 { CFG_GLOBAL, "profiling.memory", cfg_parse_prof_memory },
1162#endif
Willy Tarreau75c62c22018-11-22 11:02:09 +01001163 { CFG_GLOBAL, "profiling.tasks", cfg_parse_prof_tasks },
1164 { 0, NULL, NULL }
1165}};
1166
Willy Tarreau0108d902018-11-25 19:14:37 +01001167INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
1168
Willy Tarreau75c62c22018-11-22 11:02:09 +01001169/* register cli keywords */
1170static struct cli_kw_list cli_kws = {{ },{
Daniel Corbett67b3cef2021-05-10 14:08:40 -04001171 { { "set", "profiling", NULL }, "set profiling <what> {auto|on|off} : enable/disable resource profiling (tasks,memory)", cli_parse_set_profiling, NULL },
Willy Tarreauf9607f82022-11-25 15:32:38 +01001172 { { "show", "activity", NULL }, "show activity [-1|0|thread_num] : show per-thread activity stats (for support/developers)", cli_parse_show_activity, cli_io_handler_show_activity, NULL },
Willy Tarreaudc89b182022-09-08 16:05:57 +02001173 { { "show", "profiling", NULL }, "show profiling [<what>|<#lines>|<opts>]*: show profiling state (all,status,tasks,memory)", cli_parse_show_profiling, cli_io_handler_show_profiling, NULL },
Willy Tarreaub205bfd2021-05-07 11:38:37 +02001174 { { "show", "tasks", NULL }, "show tasks : show running tasks", NULL, cli_io_handler_show_tasks, NULL },
Willy Tarreau75c62c22018-11-22 11:02:09 +01001175 {{},}
1176}};
1177
Willy Tarreau0108d902018-11-25 19:14:37 +01001178INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);