blob: 9d396cd9066a0ab7a46d47aa50f2e6d025a7cc6d [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 Faulet87633c32023-04-03 18:32:50 +0200627 /* FIXME: Don't watch the other side ! */
Christopher Faulet7faac7c2023-04-04 10:05:27 +0200628 if (unlikely(sc_opposite(sc)->flags & SC_FL_SHUTW))
Willy Tarreau75c62c22018-11-22 11:02:09 +0100629 return 1;
630
631 chunk_reset(&trash);
632
Willy Tarreaud2d33482019-04-25 17:09:07 +0200633 switch (profiling & HA_PROF_TASKS_MASK) {
Willy Tarreauaa622b82021-01-28 21:44:22 +0100634 case HA_PROF_TASKS_AOFF: str="auto-off"; break;
635 case HA_PROF_TASKS_AON: str="auto-on"; break;
Willy Tarreaud2d33482019-04-25 17:09:07 +0200636 case HA_PROF_TASKS_ON: str="on"; break;
637 default: str="off"; break;
638 }
639
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200640 if ((ctx->dump_step & 3) != 0)
Willy Tarreau637d85a2021-05-05 17:33:27 +0200641 goto skip_status;
Willy Tarreau1bd67e92021-01-29 00:07:40 +0100642
Willy Tarreaud2d33482019-04-25 17:09:07 +0200643 chunk_printf(&trash,
Willy Tarreau00dd44f2021-05-05 16:44:23 +0200644 "Per-task CPU profiling : %-8s # set profiling tasks {on|auto|off}\n"
645 "Memory usage profiling : %-8s # set profiling memory {on|off}\n",
646 str, (profiling & HA_PROF_MEMORY) ? "on" : "off");
Willy Tarreau75c62c22018-11-22 11:02:09 +0100647
Willy Tarreaud0a06d52022-05-18 15:07:19 +0200648 if (applet_putchk(appctx, &trash) == -1) {
Willy Tarreau637d85a2021-05-05 17:33:27 +0200649 /* failed, try again */
Willy Tarreau637d85a2021-05-05 17:33:27 +0200650 return 0;
651 }
652
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200653 ctx->linenum = 0; // reset first line to dump
654 if ((ctx->dump_step & 4) == 0)
655 ctx->dump_step++; // next step
Willy Tarreau637d85a2021-05-05 17:33:27 +0200656
657 skip_status:
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200658 if ((ctx->dump_step & 3) != 1)
Willy Tarreau637d85a2021-05-05 17:33:27 +0200659 goto skip_tasks;
Willy Tarreau1bd67e92021-01-29 00:07:40 +0100660
Willy Tarreau637d85a2021-05-05 17:33:27 +0200661 memcpy(tmp_activity, sched_activity, sizeof(tmp_activity));
Willy Tarreaudc89b182022-09-08 16:05:57 +0200662 /* for addr sort and for callee aggregation we have to first sort by address */
Willy Tarreaue86bc352022-09-08 16:38:10 +0200663 if (ctx->aggr || ctx->by_what == 1) // sort by addr
Willy Tarreaudc89b182022-09-08 16:05:57 +0200664 qsort(tmp_activity, SCHED_ACT_HASH_BUCKETS, sizeof(tmp_activity[0]), cmp_sched_activity_addr);
665
666 if (ctx->aggr) {
667 /* merge entries for the same callee and reset their count */
668 for (i = j = 0; i < SCHED_ACT_HASH_BUCKETS; i = j) {
669 for (j = i + 1; j < SCHED_ACT_HASH_BUCKETS && tmp_activity[j].func == tmp_activity[i].func; j++) {
670 tmp_activity[i].calls += tmp_activity[j].calls;
671 tmp_activity[i].cpu_time += tmp_activity[j].cpu_time;
672 tmp_activity[i].lat_time += tmp_activity[j].lat_time;
673 tmp_activity[j].calls = 0;
674 }
675 }
676 }
677
Willy Tarreaue86bc352022-09-08 16:38:10 +0200678 if (!ctx->by_what) // sort by usage
Willy Tarreaua3423872022-09-07 18:49:55 +0200679 qsort(tmp_activity, SCHED_ACT_HASH_BUCKETS, sizeof(tmp_activity[0]), cmp_sched_activity_calls);
Willy Tarreaue86bc352022-09-08 16:38:10 +0200680 else if (ctx->by_what == 2) // by cpu_tot
681 qsort(tmp_activity, SCHED_ACT_HASH_BUCKETS, sizeof(tmp_activity[0]), cmp_sched_activity_cpu);
Willy Tarreau637d85a2021-05-05 17:33:27 +0200682
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200683 if (!ctx->linenum)
Willy Tarreau637d85a2021-05-05 17:33:27 +0200684 chunk_appendf(&trash, "Tasks activity:\n"
685 " function calls cpu_tot cpu_avg lat_tot lat_avg\n");
686
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200687 max_lines = ctx->maxcnt;
Willy Tarreau637d85a2021-05-05 17:33:27 +0200688 if (!max_lines)
Willy Tarreaua3423872022-09-07 18:49:55 +0200689 max_lines = SCHED_ACT_HASH_BUCKETS;
Willy Tarreau637d85a2021-05-05 17:33:27 +0200690
Willy Tarreaudc89b182022-09-08 16:05:57 +0200691 for (i = ctx->linenum; i < max_lines; i++) {
692 if (!tmp_activity[i].calls)
693 continue; // skip aggregated or empty entries
694
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200695 ctx->linenum = i;
Willy Tarreau1bd67e92021-01-29 00:07:40 +0100696 chunk_reset(name_buffer);
Willy Tarreau3d4cdb12022-09-07 18:37:47 +0200697 caller = HA_ATOMIC_LOAD(&tmp_activity[i].caller);
Willy Tarreau1bd67e92021-01-29 00:07:40 +0100698
699 if (!tmp_activity[i].func)
700 chunk_printf(name_buffer, "other");
701 else
702 resolve_sym_name(name_buffer, "", tmp_activity[i].func);
703
704 /* reserve 35 chars for name+' '+#calls, knowing that longer names
705 * are often used for less often called functions.
706 */
707 max = 35 - name_buffer->data;
708 if (max < 1)
709 max = 1;
710 chunk_appendf(&trash, " %s%*llu", name_buffer->area, max, (unsigned long long)tmp_activity[i].calls);
711
712 print_time_short(&trash, " ", tmp_activity[i].cpu_time, "");
713 print_time_short(&trash, " ", tmp_activity[i].cpu_time / tmp_activity[i].calls, "");
714 print_time_short(&trash, " ", tmp_activity[i].lat_time, "");
Willy Tarreau3d4cdb12022-09-07 18:37:47 +0200715 print_time_short(&trash, " ", tmp_activity[i].lat_time / tmp_activity[i].calls, "");
716
Willy Tarreaudc89b182022-09-08 16:05:57 +0200717 if (caller && !ctx->aggr && caller->what <= WAKEUP_TYPE_APPCTX_WAKEUP)
Willy Tarreau3d4cdb12022-09-07 18:37:47 +0200718 chunk_appendf(&trash, " <- %s@%s:%d %s",
719 caller->func, caller->file, caller->line,
720 task_wakeup_type_str(caller->what));
721
722 b_putchr(&trash, '\n');
Willy Tarreau637d85a2021-05-05 17:33:27 +0200723
Willy Tarreaud0a06d52022-05-18 15:07:19 +0200724 if (applet_putchk(appctx, &trash) == -1) {
Willy Tarreau637d85a2021-05-05 17:33:27 +0200725 /* failed, try again */
Willy Tarreau637d85a2021-05-05 17:33:27 +0200726 return 0;
727 }
Willy Tarreau1bd67e92021-01-29 00:07:40 +0100728 }
729
Willy Tarreaud0a06d52022-05-18 15:07:19 +0200730 if (applet_putchk(appctx, &trash) == -1) {
Willy Tarreau75c62c22018-11-22 11:02:09 +0100731 /* failed, try again */
Willy Tarreau75c62c22018-11-22 11:02:09 +0100732 return 0;
733 }
Willy Tarreau637d85a2021-05-05 17:33:27 +0200734
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200735 ctx->linenum = 0; // reset first line to dump
736 if ((ctx->dump_step & 4) == 0)
737 ctx->dump_step++; // next step
Willy Tarreau637d85a2021-05-05 17:33:27 +0200738
739 skip_tasks:
740
Willy Tarreaue15615c2021-08-28 12:04:25 +0200741#ifdef USE_MEMORY_PROFILING
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200742 if ((ctx->dump_step & 3) != 2)
Willy Tarreau993d44d2021-05-05 18:07:02 +0200743 goto skip_mem;
744
745 memcpy(tmp_memstats, memprof_stats, sizeof(tmp_memstats));
Willy Tarreaue86bc352022-09-08 16:38:10 +0200746 if (ctx->by_what)
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200747 qsort(tmp_memstats, MEMPROF_HASH_BUCKETS+1, sizeof(tmp_memstats[0]), cmp_memprof_addr);
748 else
749 qsort(tmp_memstats, MEMPROF_HASH_BUCKETS+1, sizeof(tmp_memstats[0]), cmp_memprof_stats);
Willy Tarreau993d44d2021-05-05 18:07:02 +0200750
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200751 if (!ctx->linenum)
Willy Tarreau993d44d2021-05-05 18:07:02 +0200752 chunk_appendf(&trash,
753 "Alloc/Free statistics by call place:\n"
Willy Tarreau616491b2021-05-11 09:26:23 +0200754 " Calls | Tot Bytes | Caller and method\n"
Willy Tarreau993d44d2021-05-05 18:07:02 +0200755 "<- alloc -> <- free ->|<-- alloc ---> <-- free ---->|\n");
756
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200757 max_lines = ctx->maxcnt;
Willy Tarreau993d44d2021-05-05 18:07:02 +0200758 if (!max_lines)
759 max_lines = MEMPROF_HASH_BUCKETS + 1;
760
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200761 for (i = ctx->linenum; i < max_lines; i++) {
Willy Tarreau993d44d2021-05-05 18:07:02 +0200762 struct memprof_stats *entry = &tmp_memstats[i];
763
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200764 ctx->linenum = i;
Willy Tarreau993d44d2021-05-05 18:07:02 +0200765 if (!entry->alloc_calls && !entry->free_calls)
766 continue;
767 chunk_appendf(&trash, "%11llu %11llu %14llu %14llu| %16p ",
768 entry->alloc_calls, entry->free_calls,
769 entry->alloc_tot, entry->free_tot,
770 entry->caller);
771
772 if (entry->caller)
773 resolve_sym_name(&trash, NULL, entry->caller);
774 else
775 chunk_appendf(&trash, "[other]");
776
Willy Tarreau8cce4d72021-10-22 16:26:12 +0200777 chunk_appendf(&trash," %s(%lld)", memprof_methods[entry->method],
Willy Tarreau616491b2021-05-11 09:26:23 +0200778 (long long)(entry->alloc_tot - entry->free_tot) / (long long)(entry->alloc_calls + entry->free_calls));
Willy Tarreau993d44d2021-05-05 18:07:02 +0200779
Willy Tarreau8cce4d72021-10-22 16:26:12 +0200780 if (entry->alloc_tot && entry->free_tot) {
781 /* that's a realloc, show the total diff to help spot leaks */
782 chunk_appendf(&trash," [delta=%lld]", (long long)(entry->alloc_tot - entry->free_tot));
783 }
784
Willy Tarreau42b180d2022-08-17 09:35:16 +0200785 if (entry->info) {
786 /* that's a pool name */
787 const struct pool_head *pool = entry->info;
788 chunk_appendf(&trash," [pool=%s]", pool->name);
789 }
790
Willy Tarreau8cce4d72021-10-22 16:26:12 +0200791 chunk_appendf(&trash, "\n");
792
Willy Tarreaud0a06d52022-05-18 15:07:19 +0200793 if (applet_putchk(appctx, &trash) == -1)
Willy Tarreau993d44d2021-05-05 18:07:02 +0200794 return 0;
Willy Tarreau993d44d2021-05-05 18:07:02 +0200795 }
796
Willy Tarreaud0a06d52022-05-18 15:07:19 +0200797 if (applet_putchk(appctx, &trash) == -1)
Willy Tarreau993d44d2021-05-05 18:07:02 +0200798 return 0;
Willy Tarreau993d44d2021-05-05 18:07:02 +0200799
Willy Tarreauf5fb8582021-05-11 14:06:24 +0200800 tot_alloc_calls = tot_free_calls = tot_alloc_bytes = tot_free_bytes = 0;
801 for (i = 0; i < max_lines; i++) {
802 tot_alloc_calls += tmp_memstats[i].alloc_calls;
803 tot_free_calls += tmp_memstats[i].free_calls;
804 tot_alloc_bytes += tmp_memstats[i].alloc_tot;
805 tot_free_bytes += tmp_memstats[i].free_tot;
806 }
807
808 chunk_appendf(&trash,
809 "-----------------------|-----------------------------|\n"
810 "%11llu %11llu %14llu %14llu| <- Total; Delta_calls=%lld; Delta_bytes=%lld\n",
811 tot_alloc_calls, tot_free_calls,
812 tot_alloc_bytes, tot_free_bytes,
813 tot_alloc_calls - tot_free_calls,
814 tot_alloc_bytes - tot_free_bytes);
815
Willy Tarreaud0a06d52022-05-18 15:07:19 +0200816 if (applet_putchk(appctx, &trash) == -1)
Willy Tarreauf5fb8582021-05-11 14:06:24 +0200817 return 0;
Willy Tarreauf5fb8582021-05-11 14:06:24 +0200818
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200819 ctx->linenum = 0; // reset first line to dump
820 if ((ctx->dump_step & 4) == 0)
821 ctx->dump_step++; // next step
Willy Tarreau993d44d2021-05-05 18:07:02 +0200822
823 skip_mem:
824#endif // USE_MEMORY_PROFILING
825
Willy Tarreau75c62c22018-11-22 11:02:09 +0100826 return 1;
827}
828
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200829/* parse a "show profiling" command. It returns 1 on failure, 0 if it starts to dump.
830 * - cli.i0 is set to the first state (0=all, 4=status, 5=tasks, 6=memory)
831 * - cli.o1 is set to 1 if the output must be sorted by addr instead of usage
832 * - cli.o0 is set to the number of lines of output
833 */
Willy Tarreau42712cb2021-05-05 17:48:13 +0200834static int cli_parse_show_profiling(char **args, char *payload, struct appctx *appctx, void *private)
835{
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200836 struct show_prof_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200837 int arg;
838
Willy Tarreau42712cb2021-05-05 17:48:13 +0200839 if (!cli_has_level(appctx, ACCESS_LVL_ADMIN))
840 return 1;
841
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200842 for (arg = 2; *args[arg]; arg++) {
843 if (strcmp(args[arg], "all") == 0) {
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200844 ctx->dump_step = 0; // will cycle through 0,1,2; default
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200845 }
846 else if (strcmp(args[arg], "status") == 0) {
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200847 ctx->dump_step = 4; // will visit status only
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200848 }
849 else if (strcmp(args[arg], "tasks") == 0) {
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200850 ctx->dump_step = 5; // will visit tasks only
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200851 }
852 else if (strcmp(args[arg], "memory") == 0) {
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200853 ctx->dump_step = 6; // will visit memory only
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200854 }
855 else if (strcmp(args[arg], "byaddr") == 0) {
Willy Tarreaue86bc352022-09-08 16:38:10 +0200856 ctx->by_what = 1; // sort output by address instead of usage
857 }
858 else if (strcmp(args[arg], "bytime") == 0) {
859 ctx->by_what = 2; // sort output by total time instead of usage
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200860 }
Willy Tarreaudc89b182022-09-08 16:05:57 +0200861 else if (strcmp(args[arg], "aggr") == 0) {
862 ctx->aggr = 1; // aggregate output by callee
863 }
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200864 else if (isdigit((unsigned char)*args[arg])) {
Willy Tarreaue8d006a2022-05-05 14:19:00 +0200865 ctx->maxcnt = atoi(args[arg]); // number of entries to dump
Willy Tarreauf1c8a382021-05-13 10:00:17 +0200866 }
867 else
Willy Tarreaue86bc352022-09-08 16:38:10 +0200868 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 +0200869 }
870 return 0;
871}
872
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100873/* This function scans all threads' run queues and collects statistics about
874 * running tasks. It returns 0 if the output buffer is full and it needs to be
875 * called again, otherwise non-zero.
876 */
877static int cli_io_handler_show_tasks(struct appctx *appctx)
878{
Willy Tarreaua3423872022-09-07 18:49:55 +0200879 struct sched_activity tmp_activity[SCHED_ACT_HASH_BUCKETS] __attribute__((aligned(64)));
Willy Tarreauc12b3212022-05-27 11:08:15 +0200880 struct stconn *sc = appctx_sc(appctx);
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100881 struct buffer *name_buffer = get_trash_chunk();
882 struct sched_activity *entry;
883 const struct tasklet *tl;
884 const struct task *t;
885 uint64_t now_ns, lat;
Willy Tarreau319d1362022-06-16 16:28:01 +0200886 struct eb32_node *rqnode;
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100887 uint64_t tot_calls;
888 int thr, queue;
889 int i, max;
890
Christopher Faulet87633c32023-04-03 18:32:50 +0200891 /* FIXME: Don't watch the other side ! */
Christopher Faulet7faac7c2023-04-04 10:05:27 +0200892 if (unlikely(sc_opposite(sc)->flags & SC_FL_SHUTW))
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100893 return 1;
894
895 /* It's not possible to scan queues in small chunks and yield in the
896 * middle of the dump and come back again. So what we're doing instead
897 * is to freeze all threads and inspect their queues at once as fast as
898 * possible, using a sched_activity array to collect metrics with
899 * limited collision, then we'll report statistics only. The tasks'
900 * #calls will reflect the number of occurrences, and the lat_time will
Willy Tarreau75f72332021-01-29 15:04:16 +0100901 * reflect the latency when set. We prefer to take the time before
902 * calling thread_isolate() so that the wait time doesn't impact the
903 * measurement accuracy. However this requires to take care of negative
904 * times since tasks might be queued after we retrieve it.
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100905 */
906
907 now_ns = now_mono_time();
908 memset(tmp_activity, 0, sizeof(tmp_activity));
909
910 thread_isolate();
911
912 /* 1. global run queue */
913
914#ifdef USE_THREAD
Willy Tarreau6f780382022-06-16 15:30:50 +0200915 for (thr = 0; thr < global.nbthread; thr++) {
916 /* task run queue */
Willy Tarreau319d1362022-06-16 16:28:01 +0200917 rqnode = eb32_first(&ha_thread_ctx[thr].rqueue_shared);
Willy Tarreau6f780382022-06-16 15:30:50 +0200918 while (rqnode) {
Willy Tarreau319d1362022-06-16 16:28:01 +0200919 t = eb32_entry(rqnode, struct task, rq);
Willy Tarreau3d4cdb12022-09-07 18:37:47 +0200920 entry = sched_activity_entry(tmp_activity, t->process, NULL);
Willy Tarreau04e50b32022-09-07 14:49:50 +0200921 if (t->wake_date) {
922 lat = now_ns - t->wake_date;
Willy Tarreau6f780382022-06-16 15:30:50 +0200923 if ((int64_t)lat > 0)
924 entry->lat_time += lat;
925 }
926 entry->calls++;
Willy Tarreau319d1362022-06-16 16:28:01 +0200927 rqnode = eb32_next(rqnode);
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100928 }
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100929 }
930#endif
931 /* 2. all threads's local run queues */
932 for (thr = 0; thr < global.nbthread; thr++) {
933 /* task run queue */
Willy Tarreau319d1362022-06-16 16:28:01 +0200934 rqnode = eb32_first(&ha_thread_ctx[thr].rqueue);
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100935 while (rqnode) {
Willy Tarreau319d1362022-06-16 16:28:01 +0200936 t = eb32_entry(rqnode, struct task, rq);
Willy Tarreau3d4cdb12022-09-07 18:37:47 +0200937 entry = sched_activity_entry(tmp_activity, t->process, NULL);
Willy Tarreau04e50b32022-09-07 14:49:50 +0200938 if (t->wake_date) {
939 lat = now_ns - t->wake_date;
Willy Tarreau75f72332021-01-29 15:04:16 +0100940 if ((int64_t)lat > 0)
941 entry->lat_time += lat;
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100942 }
943 entry->calls++;
Willy Tarreau319d1362022-06-16 16:28:01 +0200944 rqnode = eb32_next(rqnode);
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100945 }
946
947 /* shared tasklet list */
Willy Tarreau1a9c9222021-10-01 11:30:33 +0200948 list_for_each_entry(tl, mt_list_to_list(&ha_thread_ctx[thr].shared_tasklet_list), list) {
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100949 t = (const struct task *)tl;
Willy Tarreau3d4cdb12022-09-07 18:37:47 +0200950 entry = sched_activity_entry(tmp_activity, t->process, NULL);
Willy Tarreau04e50b32022-09-07 14:49:50 +0200951 if (!TASK_IS_TASKLET(t) && t->wake_date) {
952 lat = now_ns - t->wake_date;
Willy Tarreau75f72332021-01-29 15:04:16 +0100953 if ((int64_t)lat > 0)
954 entry->lat_time += lat;
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100955 }
956 entry->calls++;
957 }
958
959 /* classful tasklets */
960 for (queue = 0; queue < TL_CLASSES; queue++) {
Willy Tarreau1a9c9222021-10-01 11:30:33 +0200961 list_for_each_entry(tl, &ha_thread_ctx[thr].tasklets[queue], list) {
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100962 t = (const struct task *)tl;
Willy Tarreau3d4cdb12022-09-07 18:37:47 +0200963 entry = sched_activity_entry(tmp_activity, t->process, NULL);
Willy Tarreau04e50b32022-09-07 14:49:50 +0200964 if (!TASK_IS_TASKLET(t) && t->wake_date) {
965 lat = now_ns - t->wake_date;
Willy Tarreau75f72332021-01-29 15:04:16 +0100966 if ((int64_t)lat > 0)
967 entry->lat_time += lat;
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100968 }
969 entry->calls++;
970 }
971 }
972 }
973
974 /* hopefully we're done */
975 thread_release();
976
977 chunk_reset(&trash);
978
979 tot_calls = 0;
Willy Tarreaua3423872022-09-07 18:49:55 +0200980 for (i = 0; i < SCHED_ACT_HASH_BUCKETS; i++)
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100981 tot_calls += tmp_activity[i].calls;
982
Willy Tarreaua3423872022-09-07 18:49:55 +0200983 qsort(tmp_activity, SCHED_ACT_HASH_BUCKETS, sizeof(tmp_activity[0]), cmp_sched_activity_calls);
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100984
985 chunk_appendf(&trash, "Running tasks: %d (%d threads)\n"
986 " function places %% lat_tot lat_avg\n",
987 (int)tot_calls, global.nbthread);
988
Willy Tarreaua3423872022-09-07 18:49:55 +0200989 for (i = 0; i < SCHED_ACT_HASH_BUCKETS && tmp_activity[i].calls; i++) {
Willy Tarreau7eff06e2021-01-29 11:32:55 +0100990 chunk_reset(name_buffer);
991
992 if (!tmp_activity[i].func)
993 chunk_printf(name_buffer, "other");
994 else
995 resolve_sym_name(name_buffer, "", tmp_activity[i].func);
996
997 /* reserve 35 chars for name+' '+#calls, knowing that longer names
998 * are often used for less often called functions.
999 */
1000 max = 35 - name_buffer->data;
1001 if (max < 1)
1002 max = 1;
1003 chunk_appendf(&trash, " %s%*llu %3d.%1d",
1004 name_buffer->area, max, (unsigned long long)tmp_activity[i].calls,
1005 (int)(100ULL * tmp_activity[i].calls / tot_calls),
1006 (int)((1000ULL * tmp_activity[i].calls / tot_calls)%10));
1007 print_time_short(&trash, " ", tmp_activity[i].lat_time, "");
1008 print_time_short(&trash, " ", tmp_activity[i].lat_time / tmp_activity[i].calls, "\n");
1009 }
1010
Willy Tarreaud0a06d52022-05-18 15:07:19 +02001011 if (applet_putchk(appctx, &trash) == -1) {
Willy Tarreau7eff06e2021-01-29 11:32:55 +01001012 /* failed, try again */
Willy Tarreau7eff06e2021-01-29 11:32:55 +01001013 return 0;
1014 }
1015 return 1;
1016}
1017
Willy Tarreauf9607f82022-11-25 15:32:38 +01001018/* This function dumps some activity counters used by developers and support to
1019 * rule out some hypothesis during bug reports. It returns 0 if the output
1020 * buffer is full and it needs to be called again, otherwise non-zero. It dumps
1021 * everything at once in the buffer and is not designed to do it in multiple
1022 * passes.
1023 */
1024static int cli_io_handler_show_activity(struct appctx *appctx)
1025{
1026 struct stconn *sc = appctx_sc(appctx);
1027 struct show_activity_ctx *actctx = appctx->svcctx;
1028 int tgt = actctx->thr; // target thread, -1 for all, 0 for total only
1029 struct timeval up;
1030 int thr;
1031
Christopher Faulet87633c32023-04-03 18:32:50 +02001032 /* FIXME: Don't watch the other side ! */
Christopher Faulet7faac7c2023-04-04 10:05:27 +02001033 if (unlikely(sc_opposite(sc)->flags & SC_FL_SHUTW))
Willy Tarreauf9607f82022-11-25 15:32:38 +01001034 return 1;
1035
1036 chunk_reset(&trash);
1037
1038#undef SHOW_TOT
1039#define SHOW_TOT(t, x) \
1040 do { \
1041 unsigned int _v[MAX_THREADS]; \
1042 unsigned int _tot; \
1043 const unsigned int _nbt = global.nbthread; \
1044 _tot = t = 0; \
1045 do { \
1046 _tot += _v[t] = (x); \
1047 } while (++t < _nbt); \
1048 if (_nbt == 1) { \
1049 chunk_appendf(&trash, " %u\n", _tot); \
1050 break; \
1051 } \
1052 if (tgt == -1) { \
1053 chunk_appendf(&trash, " %u [", _tot); \
1054 for (t = 0; t < _nbt; t++) \
1055 chunk_appendf(&trash, " %u", _v[t]); \
1056 chunk_appendf(&trash, " ]\n"); \
1057 } else if (tgt == 0) \
1058 chunk_appendf(&trash, " %u\n", _tot); \
1059 else \
1060 chunk_appendf(&trash, " %u\n", _v[tgt-1]);\
1061 } while (0)
1062
1063#undef SHOW_AVG
1064#define SHOW_AVG(t, x) \
1065 do { \
1066 unsigned int _v[MAX_THREADS]; \
1067 unsigned int _tot; \
1068 const unsigned int _nbt = global.nbthread; \
1069 _tot = t = 0; \
1070 do { \
1071 _tot += _v[t] = (x); \
1072 } while (++t < _nbt); \
1073 if (_nbt == 1) { \
1074 chunk_appendf(&trash, " %u\n", _tot); \
1075 break; \
1076 } \
1077 if (tgt == -1) { \
1078 chunk_appendf(&trash, " %u [", (_tot + _nbt/2) / _nbt); \
1079 for (t = 0; t < _nbt; t++) \
1080 chunk_appendf(&trash, " %u", _v[t]); \
1081 chunk_appendf(&trash, " ]\n"); \
1082 } else if (tgt == 0) \
1083 chunk_appendf(&trash, " %u\n", (_tot + _nbt/2) / _nbt); \
1084 else \
1085 chunk_appendf(&trash, " %u\n", _v[tgt-1]);\
1086 } while (0)
1087
1088 /* retrieve uptime */
Willy Tarreau6093ba42023-02-07 15:52:14 +01001089 tv_remain(&start_time, &now, &up);
Willy Tarreauf9607f82022-11-25 15:32:38 +01001090
1091 chunk_appendf(&trash, "thread_id: %u (%u..%u)\n", tid + 1, 1, global.nbthread);
1092 chunk_appendf(&trash, "date_now: %lu.%06lu\n", (ulong)now.tv_sec, (ulong)now.tv_usec);
1093 chunk_appendf(&trash, "uptime_now: %lu.%06lu\n", (ulong)up.tv_sec, (ulong)up.tv_usec);
1094 chunk_appendf(&trash, "ctxsw:"); SHOW_TOT(thr, activity[thr].ctxsw);
1095 chunk_appendf(&trash, "tasksw:"); SHOW_TOT(thr, activity[thr].tasksw);
1096 chunk_appendf(&trash, "empty_rq:"); SHOW_TOT(thr, activity[thr].empty_rq);
1097 chunk_appendf(&trash, "long_rq:"); SHOW_TOT(thr, activity[thr].long_rq);
1098 chunk_appendf(&trash, "loops:"); SHOW_TOT(thr, activity[thr].loops);
1099 chunk_appendf(&trash, "wake_tasks:"); SHOW_TOT(thr, activity[thr].wake_tasks);
1100 chunk_appendf(&trash, "wake_signal:"); SHOW_TOT(thr, activity[thr].wake_signal);
1101 chunk_appendf(&trash, "poll_io:"); SHOW_TOT(thr, activity[thr].poll_io);
1102 chunk_appendf(&trash, "poll_exp:"); SHOW_TOT(thr, activity[thr].poll_exp);
1103 chunk_appendf(&trash, "poll_drop_fd:"); SHOW_TOT(thr, activity[thr].poll_drop_fd);
1104 chunk_appendf(&trash, "poll_skip_fd:"); SHOW_TOT(thr, activity[thr].poll_skip_fd);
1105 chunk_appendf(&trash, "conn_dead:"); SHOW_TOT(thr, activity[thr].conn_dead);
1106 chunk_appendf(&trash, "stream_calls:"); SHOW_TOT(thr, activity[thr].stream_calls);
1107 chunk_appendf(&trash, "pool_fail:"); SHOW_TOT(thr, activity[thr].pool_fail);
1108 chunk_appendf(&trash, "buf_wait:"); SHOW_TOT(thr, activity[thr].buf_wait);
1109 chunk_appendf(&trash, "cpust_ms_tot:"); SHOW_TOT(thr, activity[thr].cpust_total / 2);
1110 chunk_appendf(&trash, "cpust_ms_1s:"); SHOW_TOT(thr, read_freq_ctr(&activity[thr].cpust_1s) / 2);
1111 chunk_appendf(&trash, "cpust_ms_15s:"); SHOW_TOT(thr, read_freq_ctr_period(&activity[thr].cpust_15s, 15000) / 2);
1112 chunk_appendf(&trash, "avg_loop_us:"); SHOW_AVG(thr, swrate_avg(activity[thr].avg_loop_us, TIME_STATS_SAMPLES));
1113 chunk_appendf(&trash, "accepted:"); SHOW_TOT(thr, activity[thr].accepted);
1114 chunk_appendf(&trash, "accq_pushed:"); SHOW_TOT(thr, activity[thr].accq_pushed);
1115 chunk_appendf(&trash, "accq_full:"); SHOW_TOT(thr, activity[thr].accq_full);
1116#ifdef USE_THREAD
1117 chunk_appendf(&trash, "accq_ring:"); SHOW_TOT(thr, (accept_queue_rings[thr].tail - accept_queue_rings[thr].head + ACCEPT_QUEUE_SIZE) % ACCEPT_QUEUE_SIZE);
1118 chunk_appendf(&trash, "fd_takeover:"); SHOW_TOT(thr, activity[thr].fd_takeover);
1119#endif
1120
1121#if defined(DEBUG_DEV)
1122 /* keep these ones at the end */
1123 chunk_appendf(&trash, "ctr0:"); SHOW_TOT(thr, activity[thr].ctr0);
1124 chunk_appendf(&trash, "ctr1:"); SHOW_TOT(thr, activity[thr].ctr1);
1125 chunk_appendf(&trash, "ctr2:"); SHOW_TOT(thr, activity[thr].ctr2);
1126#endif
1127
1128 if (applet_putchk(appctx, &trash) == -1) {
1129 chunk_reset(&trash);
1130 chunk_printf(&trash, "[output too large, cannot dump]\n");
1131 }
1132
1133#undef SHOW_AVG
1134#undef SHOW_TOT
1135 /* dump complete */
1136 return 1;
1137}
1138
1139/* parse a "show activity" CLI request. Returns 0 if it needs to continue, 1 if it
1140 * wants to stop here. It sets a show_activity_ctx context where, if a specific
1141 * thread is requested, it puts the thread number into ->thr otherwise sets it to
1142 * -1.
1143 */
1144static int cli_parse_show_activity(char **args, char *payload, struct appctx *appctx, void *private)
1145{
1146 struct show_activity_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
1147
1148 if (!cli_has_level(appctx, ACCESS_LVL_OPER))
1149 return 1;
1150
1151 ctx->thr = -1; // show all by default
1152 if (*args[2])
1153 ctx->thr = atoi(args[2]);
1154
1155 if (ctx->thr < -1 || ctx->thr > global.nbthread)
1156 return cli_err(appctx, "Thread ID number must be between -1 and nbthread\n");
1157
1158 return 0;
1159}
1160
Willy Tarreau75c62c22018-11-22 11:02:09 +01001161/* config keyword parsers */
1162static struct cfg_kw_list cfg_kws = {ILH, {
Willy Tarreauca3afc22021-05-05 18:33:19 +02001163#ifdef USE_MEMORY_PROFILING
1164 { CFG_GLOBAL, "profiling.memory", cfg_parse_prof_memory },
1165#endif
Willy Tarreau75c62c22018-11-22 11:02:09 +01001166 { CFG_GLOBAL, "profiling.tasks", cfg_parse_prof_tasks },
1167 { 0, NULL, NULL }
1168}};
1169
Willy Tarreau0108d902018-11-25 19:14:37 +01001170INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
1171
Willy Tarreau75c62c22018-11-22 11:02:09 +01001172/* register cli keywords */
1173static struct cli_kw_list cli_kws = {{ },{
Daniel Corbett67b3cef2021-05-10 14:08:40 -04001174 { { "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 +01001175 { { "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 +02001176 { { "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 +02001177 { { "show", "tasks", NULL }, "show tasks : show running tasks", NULL, cli_io_handler_show_tasks, NULL },
Willy Tarreau75c62c22018-11-22 11:02:09 +01001178 {{},}
1179}};
1180
Willy Tarreau0108d902018-11-25 19:14:37 +01001181INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);