2 * Copyright (c) 2015, The Android Open Source Project
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
14 * * Neither the name of Google, Inc. nor the names of its contributors
15 * may be used to endorse or promote products derived from this
16 * software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
21 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
22 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
23 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
24 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
25 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
26 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
28 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 #include <binder/IBinder.h>
33 #include <binder/IServiceManager.h>
34 #include <binder/Parcel.h>
37 #include <cutils/properties.h>
44 #include <sys/resource.h>
47 #include <sys/types.h>
50 #include <utils/Log.h>
51 #include <utils/String8.h>
52 #include <utils/Trace.h>
55 using namespace android;
61 #define LOG_TAG "anrdaemon"
63 static const int check_period = 1; // in sec
64 static const int tracing_check_period = 500000; // in micro sec
65 static const int cpu_stat_entries = 7; // number of cpu stat entries
66 static const int min_buffer_size = 16;
67 static const int max_buffer_size = 2048;
68 static const char *min_buffer_size_str = "16";
69 static const char *max_buffer_size_str = "2048";
71 typedef struct cpu_stat {
72 unsigned long utime, ntime, stime, itime;
73 unsigned long iowtime, irqtime, sirqtime, steal;
78 * Logging on/off threshold.
79 * Uint: 0.01%; default to 99.90% cpu.
81 static int idle_threshold = 10;
83 static bool quit = false;
84 static bool suspend= false;
85 static bool err = false;
86 static char err_msg[100];
87 static bool tracing = false;
89 static const char *buf_size_kb = "2048";
90 static const char *apps = "";
91 static uint64_t tag = 0;
93 static cpu_stat_t new_cpu;
94 static cpu_stat_t old_cpu;
96 /* Log certain kernel activity when enabled */
97 static bool log_sched = false;
98 static bool log_stack = false;
99 static bool log_irq = false;
100 static bool log_sync = false;
101 static bool log_workq = false;
103 /* Paths for debugfs controls*/
104 static const char* dfs_trace_output_path =
106 static const char* dfs_irq_path =
107 "/d/tracing/events/irq/enable";
108 static const char* dfs_sync_path =
109 "/d/tracing/events/sync/enable";
110 static const char* dfs_workq_path =
111 "/d/tracing/events/workqueue/enable";
112 static const char* dfs_stack_path =
113 "/d/tracing/options/stacktrace";
114 static const char* dfs_sched_switch_path =
115 "/d/tracing/events/sched/sched_switch/enable";
116 static const char* dfs_sched_wakeup_path =
117 "/d/tracing/events/sched/sched_wakeup/enable";
118 static const char* dfs_control_path =
119 "/d/tracing/tracing_on";
120 static const char* dfs_buffer_size_path =
121 "/d/tracing/buffer_size_kb";
122 static const char* dfs_tags_property = "debug.atrace.tags.enableflags";
123 static const char* dfs_apps_property = "debug.atrace.app_cmdlines";
126 * Read accumulated cpu data from /proc/stat
128 static void get_cpu_stat(cpu_stat_t *cpu) {
130 const char *params = "cpu %lu %lu %lu %lu %lu %lu %lu %*d %*d %*d\n";
132 if ((fp = fopen("/proc/stat", "r")) == NULL) {
134 sprintf(err_msg, "can't read from /proc/stat with errno %d", errno);
136 if (fscanf(fp, params, &cpu->utime, &cpu->ntime,
137 &cpu->stime, &cpu->itime, &cpu->iowtime, &cpu->irqtime,
138 &cpu->sirqtime) != cpu_stat_entries) {
140 * If failed in getting status, new_cpu won't be updated and
141 * is_heavy_loaded() will return false.
143 ALOGE("Error in getting cpu status. Skipping this check.");
147 cpu->total = cpu->utime + cpu->ntime + cpu->stime + cpu->itime
148 + cpu->iowtime + cpu->irqtime + cpu->sirqtime;
155 * Calculate cpu usage in the past interval.
156 * If tracing is on, increase the idle threshold by 1.00% so that we do not
157 * turn on and off tracing frequently whe the cpu load is right close to
160 static bool is_heavy_load(void) {
161 unsigned long diff_idle, diff_total;
162 int threshold = idle_threshold + (tracing?100:0);
163 get_cpu_stat(&new_cpu);
164 diff_idle = new_cpu.itime - old_cpu.itime;
165 diff_total = new_cpu.total - old_cpu.total;
167 return (diff_idle * 10000 < diff_total * threshold);
171 * Force the userland processes to refresh their property for logging.
173 static void dfs_poke_binder(void) {
174 sp<IServiceManager> sm = defaultServiceManager();
175 Vector<String16> services = sm->listServices();
176 for (size_t i = 0; i < services.size(); i++) {
177 sp<IBinder> obj = sm->checkService(services[i]);
180 obj->transact(IBinder::SYSPROPS_TRANSACTION, data, NULL, 0);
186 * Enable/disable a debugfs property by writing 0/1 to its path.
188 static int dfs_enable(bool enable, const char* path) {
189 int fd = open(path, O_WRONLY);
192 sprintf(err_msg, "Can't open %s. Error: %d", path, errno);
195 const char* control = (enable?"1":"0");
196 ssize_t len = strlen(control);
197 int max_try = 10; // Fail if write was interrupted for 10 times
198 while (write(fd, control, len) != len) {
199 if (errno == EINTR && max_try-- > 0) {
205 sprintf(err_msg, "Error %d in writing to %s.", errno, path);
212 * Set the userland tracing properties.
214 static void dfs_set_property(uint64_t mtag, const char* mapp, bool enable) {
216 snprintf(buf, 64, "%#" PRIx64, mtag);
217 if (property_set(dfs_tags_property, buf) < 0) {
219 sprintf(err_msg, "Failed to set debug tags system properties.");
223 && property_set(dfs_apps_property, mapp) < 0) {
225 sprintf(err_msg, "Failed to set debug applications.");
229 dfs_enable(enable, dfs_sched_switch_path);
230 dfs_enable(enable, dfs_sched_wakeup_path);
233 dfs_enable(enable, dfs_stack_path);
236 dfs_enable(enable, dfs_irq_path);
239 dfs_enable(enable, dfs_sync_path);
242 dfs_enable(enable, dfs_workq_path);
247 * Start logging when cpu usage is high. Meanwhile, moniter the cpu usage and
248 * stop logging when it drops down.
250 static void start_tracing(void) {
251 ALOGD("High cpu usage, start logging.");
253 if (dfs_enable(true, dfs_control_path) != 0) {
254 ALOGE("Failed to start tracing.");
259 /* Stop logging when cpu usage drops or the daemon is suspended.*/
261 usleep(tracing_check_period);
262 } while (!suspend && is_heavy_load());
264 if (dfs_enable(false, dfs_control_path) != 0) {
265 ALOGE("Failed to stop tracing.");
268 ALOGD("Usage back to low, stop logging.");
273 * Set the tracing log buffer size.
274 * Note the actual buffer size will be buf_size_kb * number of cores.
275 * E.g. for dory, the total buffer size is buf_size_kb * 4.
277 static int set_tracing_buffer_size(void) {
278 int fd = open(dfs_buffer_size_path, O_WRONLY);
281 sprintf(err_msg, "Can't open atrace buffer size file under /d/tracing.");
284 ssize_t len = strlen(buf_size_kb);
285 if (write(fd, buf_size_kb, len) != len) {
287 sprintf(err_msg, "Error in writing to atrace buffer size file.");
295 * Main loop to moniter the cpu usage and decided whether to start logging.
297 static void start(void) {
298 if ((set_tracing_buffer_size()) != 0)
301 dfs_set_property(tag, apps, true);
304 get_cpu_stat(&old_cpu);
307 while (!quit && !err) {
308 if (!suspend && is_heavy_load()) {
310 * Increase process priority to make sure we can stop logging when
311 * necessary and do not overwrite the buffer
313 setpriority(PRIO_PROCESS, 0, -20);
315 setpriority(PRIO_PROCESS, 0, 0);
323 * Dump the log in a compressed format for systrace to visualize.
325 static void dump_trace()
327 int remain_attempts = 5;
330 ALOGI("Waiting logging to stop.");
331 usleep(tracing_check_period);
333 if (remain_attempts == 0) {
334 ALOGE("Can't stop logging after 5 attempts. Dump aborted.");
340 * Create /sdcard/ANRdaemon/ if it doesn't exist
343 if (stat("/sdcard/ANRdaemon", &st) == -1) {
344 ALOGI("Creating /sdcard/ANRdaemon/");
345 int err = mkdir("/sdcard/ANRdaemon", 0700);
347 ALOGI("Creating /sdcard/ANRdaemon/ failed with %s", strerror(err));
351 * Create a dump file "dump_of_anrdaemon.<current_time>" under /sdcard/ANRdaemon/
353 time_t now = time(0);
357 const char* header = " done\nTRACE:\n";
358 ssize_t header_len = strlen(header);
359 tstruct = *localtime(&now);
360 strftime(time_buf, sizeof(time_buf), "%Y-%m-%d.%X", &tstruct);
361 sprintf(path_buf, "/sdcard/ANRdaemon/dump_of_anrdaemon.%s", time_buf);
362 int output_fd = creat(path_buf, S_IRWXU);
363 if (output_fd == -1) {
364 ALOGE("Failed to create %s. Dump aborted.", path_buf);
368 if (write(output_fd, header, strlen(header)) != header_len) {
369 ALOGE("Failed to write the header.");
374 int trace_fd = open(dfs_trace_output_path, O_RDWR);
375 if (trace_fd == -1) {
376 ALOGE("Failed to open %s. Dump aborted.", dfs_trace_output_path);
385 memset(&zs, 0, sizeof(zs));
386 result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
387 if (result != Z_OK) {
388 ALOGE("error initializing zlib: %d\n", result);
394 const size_t bufSize = 64*1024;
395 in = (uint8_t*)malloc(bufSize);
396 out = (uint8_t*)malloc(bufSize);
400 zs.avail_out = bufSize;
403 if (zs.avail_in == 0) {
404 result = read(trace_fd, in, bufSize);
406 ALOGE("error reading trace: %s", strerror(errno));
407 result = Z_STREAM_END;
409 } else if (result == 0) {
413 zs.avail_in = result;
417 if (zs.avail_out == 0) {
418 result = write(output_fd, out, bufSize);
419 if ((size_t)result < bufSize) {
420 ALOGE("error writing deflated trace: %s", strerror(errno));
421 result = Z_STREAM_END;
422 zs.avail_out = bufSize;
426 zs.avail_out = bufSize;
429 } while ((result = deflate(&zs, flush)) == Z_OK);
431 if (result != Z_STREAM_END) {
432 ALOGE("error deflating trace: %s\n", zs.msg);
435 if (zs.avail_out < bufSize) {
436 size_t bytes = bufSize - zs.avail_out;
437 result = write(output_fd, out, bytes);
438 if ((size_t)result < bytes) {
439 ALOGE("error writing deflated trace: %s", strerror(errno));
443 result = deflateEnd(&zs);
444 if (result != Z_OK) {
445 ALOGE("error cleaning up zlib: %d\n", result);
455 ALOGI("Finished dump. Output file stored at: %s", path_buf);
458 static void handle_signal(int signo)
477 * Set the signal handler:
478 * SIGQUIT: Reset debugfs and tracing property and terminate the daemon.
479 * SIGSTOP: Stop logging and suspend the daemon.
480 * SIGCONT: Resume the daemon as normal.
481 * SIGUSR1: Dump the logging to a compressed format for systrace to visualize.
483 static void register_sighandler(void)
488 sigemptyset(&block_mask);
489 sigaddset (&block_mask, SIGQUIT);
490 sigaddset (&block_mask, SIGSTOP);
491 sigaddset (&block_mask, SIGCONT);
492 sigaddset (&block_mask, SIGUSR1);
495 sa.sa_mask = block_mask;
496 sa.sa_handler = handle_signal;
497 sigaction(SIGQUIT, &sa, NULL);
498 sigaction(SIGSTOP, &sa, NULL);
499 sigaction(SIGCONT, &sa, NULL);
500 sigaction(SIGUSR1, &sa, NULL);
503 static void show_help(void) {
505 fprintf(stderr, "usage: ANRdaemon [options] [categoris...]\n");
506 fprintf(stdout, "Options includes:\n"
507 " -a appname enable app-level tracing for a comma "
508 "separated list of cmdlines\n"
509 " -t N cpu threshold for logging to start "
510 "(uint = 0.01%%, min = 5000, max = 9999, default = 9990)\n"
511 " -s N use a trace buffer size of N KB "
512 "default to 2048KB\n"
514 fprintf(stdout, "Categoris includes:\n"
515 " am - activity manager\n"
516 " sm - sync manager\n"
518 " dalvik - dalvik VM\n"
521 " rs - RenderScript\n"
522 " hal - Hardware Modules\n"
523 " irq - kernel irq events\n"
524 " sched - kernel scheduler activity\n"
525 " stack - kernel stack\n"
526 " sync - kernel sync activity\n"
527 " workq - kernel work queues\n");
528 fprintf(stdout, "Control includes:\n"
529 " SIGQUIT: terminate the process\n"
530 " SIGSTOP: suspend all function of the daemon\n"
531 " SIGCONT: resume the normal function\n"
532 " SIGUSR1: dump the current logging in a compressed form\n");
536 static int get_options(int argc, char *argv[]) {
539 while ((opt = getopt(argc, argv, "a:s:t:h")) >= 0) {
545 if (atoi(optarg) > max_buffer_size)
546 buf_size_kb = max_buffer_size_str;
547 else if (atoi(optarg) < min_buffer_size)
548 buf_size_kb = min_buffer_size_str;
550 buf_size_kb = optarg;
553 threshold = atoi(optarg);
554 if (threshold > 9999 || threshold < 5000) {
555 fprintf(stderr, "logging threshold should be 5000-9999\n");
558 idle_threshold = 10000 - threshold;
564 fprintf(stderr, "Error in getting options.\n"
565 "run \"%s -h\" for usage.\n", argv[0]);
570 for (int i = optind; i < argc; i++) {
571 if (strcmp(argv[i], "am") == 0) {
572 tag |= ATRACE_TAG_ACTIVITY_MANAGER;
573 } else if (strcmp(argv[i], "input") == 0) {
574 tag |= ATRACE_TAG_INPUT;
575 } else if (strcmp(argv[i], "sm") == 0) {
576 tag |= ATRACE_TAG_SYNC_MANAGER;
577 } else if (strcmp(argv[i], "dalvik") == 0) {
578 tag |= ATRACE_TAG_DALVIK;
579 } else if (strcmp(argv[i], "gfx") == 0) {
580 tag |= ATRACE_TAG_GRAPHICS;
581 } else if (strcmp(argv[i], "audio") == 0) {
582 tag |= ATRACE_TAG_AUDIO;
583 } else if (strcmp(argv[i], "hal") == 0) {
584 tag |= ATRACE_TAG_HAL;
585 } else if (strcmp(argv[i], "rs") == 0) {
586 tag |= ATRACE_TAG_RS;
587 } else if (strcmp(argv[i], "sched") == 0) {
589 } else if (strcmp(argv[i], "stack") == 0) {
591 } else if (strcmp(argv[i], "workq") == 0) {
593 } else if (strcmp(argv[i], "irq") == 0) {
595 } else if (strcmp(argv[i], "sync") == 0) {
598 fprintf(stderr, "invalid category: %s\n"
599 "run \"%s -h\" for usage.\n", argv[i], argv[0]);
604 /* If nothing is enabled, don't run */
605 if (!tag && !log_sched && !log_stack && !log_workq && !log_irq && !log_sync) {
606 ALOGE("Specify at least one category to trace.");
613 int main(int argc, char *argv[])
615 if(get_options(argc, argv) != 0)
618 if (daemon(0, 0) != 0)
621 register_sighandler();
623 /* Clear any the trace log file by overwrite it with a new file */
624 int fd = creat(dfs_trace_output_path, 0);
626 ALOGE("Faield to open and cleaup previous log");
631 ALOGI("ANRdaemon starting");
635 ALOGE("ANRdaemon stopped due to Error: %s", err_msg);
637 ALOGI("ANRdaemon terminated.");