2 * Copyright (C) 2012 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
25 #include <sys/sendfile.h>
29 #include <binder/IBinder.h>
30 #include <binder/IServiceManager.h>
31 #include <binder/Parcel.h>
33 #include <cutils/properties.h>
35 #include <utils/String8.h>
36 #include <utils/Trace.h>
38 using namespace android;
40 #define NELEM(x) ((int) (sizeof(x) / sizeof((x)[0])))
42 enum { MAX_SYS_FILES = 8 };
44 const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
46 typedef enum { OPT, REQ } requiredness ;
48 struct TracingCategory {
49 // The name identifying the category.
52 // A longer description of the category.
55 // The userland tracing tags that the category enables.
58 // The fname==NULL terminated list of /sys/ files that the category
61 // Whether the file must be writable in order to enable the tracing
63 requiredness required;
65 // The path to the enable file.
67 } sysfiles[MAX_SYS_FILES];
70 /* Tracing categories */
71 static const TracingCategory k_categories[] = {
72 { "gfx", "Graphics", ATRACE_TAG_GRAPHICS, { } },
73 { "input", "Input", ATRACE_TAG_INPUT, { } },
74 { "view", "View System", ATRACE_TAG_VIEW, { } },
75 { "webview", "WebView", ATRACE_TAG_WEBVIEW, { } },
76 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
77 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
78 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
79 { "video", "Video", ATRACE_TAG_VIDEO, { } },
80 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
81 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
82 { "sched", "CPU Scheduling", 0, {
83 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_switch/enable" },
84 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_wakeup/enable" },
86 { "freq", "CPU Frequency", 0, {
87 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_frequency/enable" },
88 { OPT, "/sys/kernel/debug/tracing/events/power/clock_set_rate/enable" },
90 { "membus", "Memory Bus Utilization", 0, {
91 { REQ, "/sys/kernel/debug/tracing/events/memory_bus/enable" },
93 { "idle", "CPU Idle", 0, {
94 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_idle/enable" },
96 { "disk", "Disk I/O", 0, {
97 { REQ, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_enter/enable" },
98 { REQ, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_exit/enable" },
99 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_issue/enable" },
100 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_complete/enable" },
102 { "load", "CPU Load", 0, {
103 { REQ, "/sys/kernel/debug/tracing/events/cpufreq_interactive/enable" },
105 { "sync", "Synchronization", 0, {
106 { REQ, "/sys/kernel/debug/tracing/events/sync/enable" },
108 { "workq", "Kernel Workqueues", 0, {
109 { REQ, "/sys/kernel/debug/tracing/events/workqueue/enable" },
113 /* Command line options */
114 static int g_traceDurationSeconds = 5;
115 static bool g_traceOverwrite = false;
116 static int g_traceBufferSizeKB = 2048;
117 static bool g_compress = false;
118 static bool g_nohup = false;
119 static int g_initialSleepSecs = 0;
120 static const char* g_kernelTraceFuncs = NULL;
123 static bool g_traceAborted = false;
124 static bool g_categoryEnables[NELEM(k_categories)] = {};
127 static const char* k_traceClockPath =
128 "/sys/kernel/debug/tracing/trace_clock";
130 static const char* k_traceBufferSizePath =
131 "/sys/kernel/debug/tracing/buffer_size_kb";
133 static const char* k_tracingOverwriteEnablePath =
134 "/sys/kernel/debug/tracing/options/overwrite";
136 static const char* k_currentTracerPath =
137 "/sys/kernel/debug/tracing/current_tracer";
139 static const char* k_printTgidPath =
140 "/sys/kernel/debug/tracing/options/print-tgid";
142 static const char* k_funcgraphAbsTimePath =
143 "/sys/kernel/debug/tracing/options/funcgraph-abstime";
145 static const char* k_funcgraphCpuPath =
146 "/sys/kernel/debug/tracing/options/funcgraph-cpu";
148 static const char* k_funcgraphProcPath =
149 "/sys/kernel/debug/tracing/options/funcgraph-proc";
151 static const char* k_funcgraphFlatPath =
152 "/sys/kernel/debug/tracing/options/funcgraph-flat";
154 static const char* k_funcgraphDurationPath =
155 "/sys/kernel/debug/tracing/options/funcgraph-duration";
157 static const char* k_ftraceFilterPath =
158 "/sys/kernel/debug/tracing/set_ftrace_filter";
160 static const char* k_tracingOnPath =
161 "/sys/kernel/debug/tracing/tracing_on";
163 static const char* k_tracePath =
164 "/sys/kernel/debug/tracing/trace";
166 // Check whether a file exists.
167 static bool fileExists(const char* filename) {
168 return access(filename, F_OK) != -1;
171 // Check whether a file is writable.
172 static bool fileIsWritable(const char* filename) {
173 return access(filename, W_OK) != -1;
177 static bool truncateFile(const char* path)
179 // This uses creat rather than truncate because some of the debug kernel
180 // device nodes (e.g. k_ftraceFilterPath) currently aren't changed by
181 // calls to truncate, but they are cleared by calls to creat.
182 int traceFD = creat(path, 0);
184 fprintf(stderr, "error truncating %s: %s (%d)\n", path,
185 strerror(errno), errno);
194 static bool _writeStr(const char* filename, const char* str, int flags)
196 int fd = open(filename, flags);
198 fprintf(stderr, "error opening %s: %s (%d)\n", filename,
199 strerror(errno), errno);
204 ssize_t len = strlen(str);
205 if (write(fd, str, len) != len) {
206 fprintf(stderr, "error writing to %s: %s (%d)\n", filename,
207 strerror(errno), errno);
216 // Write a string to a file, returning true if the write was successful.
217 static bool writeStr(const char* filename, const char* str)
219 return _writeStr(filename, str, O_WRONLY);
222 // Append a string to a file, returning true if the write was successful.
223 static bool appendStr(const char* filename, const char* str)
225 return _writeStr(filename, str, O_APPEND|O_WRONLY);
228 // Enable or disable a kernel option by writing a "1" or a "0" into a /sys
230 static bool setKernelOptionEnable(const char* filename, bool enable)
232 return writeStr(filename, enable ? "1" : "0");
235 // Check whether the category is supported on the device with the current
236 // rootness. A category is supported only if all its required /sys/ files are
237 // writable and if enabling the category will enable one or more tracing tags
239 static bool isCategorySupported(const TracingCategory& category)
241 bool ok = category.tags != 0;
242 for (int i = 0; i < MAX_SYS_FILES; i++) {
243 const char* path = category.sysfiles[i].path;
244 bool req = category.sysfiles[i].required == REQ;
247 if (!fileIsWritable(path)) {
253 ok |= fileIsWritable(path);
260 // Check whether the category would be supported on the device if the user
261 // were root. This function assumes that root is able to write to any file
262 // that exists. It performs the same logic as isCategorySupported, but it
263 // uses file existance rather than writability in the /sys/ file checks.
264 static bool isCategorySupportedForRoot(const TracingCategory& category)
266 bool ok = category.tags != 0;
267 for (int i = 0; i < MAX_SYS_FILES; i++) {
268 const char* path = category.sysfiles[i].path;
269 bool req = category.sysfiles[i].required == REQ;
272 if (!fileExists(path)) {
278 ok |= fileExists(path);
285 // Enable or disable overwriting of the kernel trace buffers. Disabling this
286 // will cause tracing to stop once the trace buffers have filled up.
287 static bool setTraceOverwriteEnable(bool enable)
289 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
292 // Enable or disable kernel tracing.
293 static bool setTracingEnabled(bool enable)
295 return setKernelOptionEnable(k_tracingOnPath, enable);
298 // Clear the contents of the kernel trace.
299 static bool clearTrace()
301 return truncateFile(k_tracePath);
304 // Set the size of the kernel's trace buffer in kilobytes.
305 static bool setTraceBufferSizeKB(int size)
312 snprintf(str, 32, "%d", size);
313 return writeStr(k_traceBufferSizePath, str);
316 // Enable or disable the kernel's use of the global clock. Disabling the global
317 // clock will result in the kernel using a per-CPU local clock.
318 static bool setGlobalClockEnable(bool enable)
320 return writeStr(k_traceClockPath, enable ? "global" : "local");
323 static bool setPrintTgidEnableIfPresent(bool enable)
325 if (fileExists(k_printTgidPath)) {
326 return setKernelOptionEnable(k_printTgidPath, enable);
331 // Poke all the binder-enabled processes in the system to get them to re-read
332 // their system properties.
333 static bool pokeBinderServices()
335 sp<IServiceManager> sm = defaultServiceManager();
336 Vector<String16> services = sm->listServices();
337 for (size_t i = 0; i < services.size(); i++) {
338 sp<IBinder> obj = sm->checkService(services[i]);
341 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
344 // XXX: For some reason this fails on tablets trying to
345 // poke the "phone" service. It's not clear whether some
346 // are expected to fail.
347 String8 svc(services[i]);
348 fprintf(stderr, "error poking binder service %s\n",
358 // Set the trace tags that userland tracing uses, and poke the running
359 // processes to pick up the new value.
360 static bool setTagsProperty(uint64_t tags)
363 snprintf(buf, 64, "%#llx", tags);
364 if (property_set(k_traceTagsProperty, buf) < 0) {
365 fprintf(stderr, "error setting trace tags system property\n");
368 return pokeBinderServices();
371 // Disable all /sys/ enable files.
372 static bool disableKernelTraceEvents() {
374 for (int i = 0; i < NELEM(k_categories); i++) {
375 const TracingCategory &c = k_categories[i];
376 for (int j = 0; j < MAX_SYS_FILES; j++) {
377 const char* path = c.sysfiles[j].path;
378 if (path != NULL && fileIsWritable(path)) {
379 ok &= setKernelOptionEnable(path, false);
386 // Verify that the comma separated list of functions are being traced by the
388 static bool verifyKernelTraceFuncs(const char* funcs)
390 int fd = open(k_ftraceFilterPath, O_RDONLY);
392 fprintf(stderr, "error opening %s: %s (%d)\n", k_ftraceFilterPath,
393 strerror(errno), errno);
398 ssize_t n = read(fd, buf, 4096);
401 fprintf(stderr, "error reading %s: %s (%d)\n", k_ftraceFilterPath,
402 strerror(errno), errno);
407 String8 funcList = String8::format("\n%s", buf);
409 // Make sure that every function listed in funcs is in the list we just
410 // read from the kernel.
412 char* myFuncs = strdup(funcs);
413 char* func = strtok(myFuncs, ",");
415 String8 fancyFunc = String8::format("\n%s\n", func);
416 bool found = funcList.find(fancyFunc.string(), 0) >= 0;
417 if (!found || func[0] == '\0') {
418 fprintf(stderr, "error: \"%s\" is not a valid kernel function "
419 "to trace.\n", func);
422 func = strtok(NULL, ",");
429 // Set the comma separated list of functions that the kernel is to trace.
430 static bool setKernelTraceFuncs(const char* funcs)
434 if (funcs == NULL || funcs[0] == '\0') {
435 // Disable kernel function tracing.
436 ok &= writeStr(k_currentTracerPath, "nop");
437 if (fileExists(k_ftraceFilterPath)) {
438 ok &= truncateFile(k_ftraceFilterPath);
441 // Enable kernel function tracing.
442 ok &= writeStr(k_currentTracerPath, "function_graph");
443 ok &= setKernelOptionEnable(k_funcgraphAbsTimePath, true);
444 ok &= setKernelOptionEnable(k_funcgraphCpuPath, true);
445 ok &= setKernelOptionEnable(k_funcgraphProcPath, true);
446 ok &= setKernelOptionEnable(k_funcgraphFlatPath, true);
448 // Set the requested filter functions.
449 ok &= truncateFile(k_ftraceFilterPath);
450 char* myFuncs = strdup(funcs);
451 char* func = strtok(myFuncs, ",");
453 ok &= appendStr(k_ftraceFilterPath, func);
454 func = strtok(NULL, ",");
458 // Verify that the set functions are being traced.
460 ok &= verifyKernelTraceFuncs(funcs);
467 // Set all the kernel tracing settings to the desired state for this trace
469 static bool setUpTrace()
473 // Set up the tracing options.
474 ok &= setTraceOverwriteEnable(g_traceOverwrite);
475 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
476 ok &= setGlobalClockEnable(true);
477 ok &= setPrintTgidEnableIfPresent(true);
478 ok &= setKernelTraceFuncs(g_kernelTraceFuncs);
480 // Set up the tags property.
482 for (int i = 0; i < NELEM(k_categories); i++) {
483 if (g_categoryEnables[i]) {
484 const TracingCategory &c = k_categories[i];
488 ok &= setTagsProperty(tags);
490 // Disable all the sysfs enables. This is done as a separate loop from
491 // the enables to allow the same enable to exist in multiple categories.
492 ok &= disableKernelTraceEvents();
494 // Enable all the sysfs enables that are in an enabled category.
495 for (int i = 0; i < NELEM(k_categories); i++) {
496 if (g_categoryEnables[i]) {
497 const TracingCategory &c = k_categories[i];
498 for (int j = 0; j < MAX_SYS_FILES; j++) {
499 const char* path = c.sysfiles[j].path;
500 bool required = c.sysfiles[j].required == REQ;
502 if (fileIsWritable(path)) {
503 ok &= setKernelOptionEnable(path, true);
504 } else if (required) {
505 fprintf(stderr, "error writing file %s\n", path);
516 // Reset all the kernel tracing settings to their default state.
517 static void cleanUpTrace()
519 // Disable all tracing that we're able to.
520 disableKernelTraceEvents();
522 // Disable all the trace tags.
525 // Set the options back to their defaults.
526 setTraceOverwriteEnable(true);
527 setTraceBufferSizeKB(1);
528 setGlobalClockEnable(false);
529 setPrintTgidEnableIfPresent(false);
530 setKernelTraceFuncs(NULL);
534 // Enable tracing in the kernel.
535 static bool startTrace()
537 return setTracingEnabled(true);
540 // Disable tracing in the kernel.
541 static void stopTrace()
543 setTracingEnabled(false);
546 // Read the current kernel trace and write it to stdout.
547 static void dumpTrace()
549 int traceFD = open(k_tracePath, O_RDWR);
551 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
552 strerror(errno), errno);
561 bzero(&zs, sizeof(zs));
562 result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
563 if (result != Z_OK) {
564 fprintf(stderr, "error initializing zlib: %d\n", result);
569 const size_t bufSize = 64*1024;
570 in = (uint8_t*)malloc(bufSize);
571 out = (uint8_t*)malloc(bufSize);
575 zs.avail_out = bufSize;
579 if (zs.avail_in == 0) {
580 // More input is needed.
581 result = read(traceFD, in, bufSize);
583 fprintf(stderr, "error reading trace: %s (%d)\n",
584 strerror(errno), errno);
585 result = Z_STREAM_END;
587 } else if (result == 0) {
591 zs.avail_in = result;
595 if (zs.avail_out == 0) {
596 // Need to write the output.
597 result = write(STDOUT_FILENO, out, bufSize);
598 if ((size_t)result < bufSize) {
599 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
600 strerror(errno), errno);
601 result = Z_STREAM_END; // skip deflate error message
602 zs.avail_out = bufSize; // skip the final write
606 zs.avail_out = bufSize;
609 } while ((result = deflate(&zs, flush)) == Z_OK);
611 if (result != Z_STREAM_END) {
612 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
615 if (zs.avail_out < bufSize) {
616 size_t bytes = bufSize - zs.avail_out;
617 result = write(STDOUT_FILENO, out, bytes);
618 if ((size_t)result < bytes) {
619 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
620 strerror(errno), errno);
624 result = deflateEnd(&zs);
625 if (result != Z_OK) {
626 fprintf(stderr, "error cleaning up zlib: %d\n", result);
633 while ((sent = sendfile(STDOUT_FILENO, traceFD, NULL, 64*1024*1024)) > 0);
635 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
643 static void handleSignal(int signo)
646 g_traceAborted = true;
650 static void registerSigHandler()
653 sigemptyset(&sa.sa_mask);
655 sa.sa_handler = handleSignal;
656 sigaction(SIGHUP, &sa, NULL);
657 sigaction(SIGINT, &sa, NULL);
658 sigaction(SIGQUIT, &sa, NULL);
659 sigaction(SIGTERM, &sa, NULL);
662 static bool setCategoryEnable(const char* name, bool enable)
664 for (int i = 0; i < NELEM(k_categories); i++) {
665 const TracingCategory& c = k_categories[i];
666 if (strcmp(name, c.name) == 0) {
667 if (isCategorySupported(c)) {
668 g_categoryEnables[i] = enable;
671 if (isCategorySupportedForRoot(c)) {
672 fprintf(stderr, "error: category \"%s\" requires root "
673 "privileges.\n", name);
675 fprintf(stderr, "error: category \"%s\" is not supported "
676 "on this device.\n", name);
682 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
686 static void listSupportedCategories()
688 for (int i = 0; i < NELEM(k_categories); i++) {
689 const TracingCategory& c = k_categories[i];
690 if (isCategorySupported(c)) {
691 printf(" %10s - %s\n", c.name, c.longname);
696 // Print the command usage help to stderr.
697 static void showHelp(const char *cmd)
699 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
700 fprintf(stderr, "options include:\n"
701 " -b N use a trace buffer size of N KB\n"
702 " -c trace into a circular buffer\n"
703 " -k fname,... trace the listed kernel functions\n"
704 " -n ignore signals\n"
705 " -s N sleep for N seconds before tracing [default 0]\n"
706 " -t N trace for N seconds [defualt 5]\n"
707 " -z compress the trace dump\n"
708 " --async_start start circular trace and return immediatly\n"
709 " --async_dump dump the current contents of circular trace buffer\n"
710 " --async_stop stop tracing and dump the current contents of circular\n"
712 " --list_categories\n"
713 " list the available tracing categories\n"
717 int main(int argc, char **argv)
720 bool traceStart = true;
721 bool traceStop = true;
722 bool traceDump = true;
724 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
731 int option_index = 0;
732 static struct option long_options[] = {
733 {"async_start", no_argument, 0, 0 },
734 {"async_stop", no_argument, 0, 0 },
735 {"async_dump", no_argument, 0, 0 },
736 {"list_categories", no_argument, 0, 0 },
740 ret = getopt_long(argc, argv, "b:ck:ns:t:z",
741 long_options, &option_index);
744 for (int i = optind; i < argc; i++) {
745 if (!setCategoryEnable(argv[i], true)) {
746 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
755 g_traceBufferSizeKB = atoi(optarg);
759 g_traceOverwrite = true;
763 g_kernelTraceFuncs = optarg;
771 g_initialSleepSecs = atoi(optarg);
775 g_traceDurationSeconds = atoi(optarg);
783 if (!strcmp(long_options[option_index].name, "async_start")) {
787 g_traceOverwrite = true;
788 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
791 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
795 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
796 listSupportedCategories();
802 fprintf(stderr, "\n");
809 registerSigHandler();
811 if (g_initialSleepSecs > 0) {
812 sleep(g_initialSleepSecs);
819 if (ok && traceStart) {
820 printf("capturing trace...");
823 // We clear the trace after starting it because tracing gets enabled for
824 // each CPU individually in the kernel. Having the beginning of the trace
825 // contain entries from only one CPU can cause "begin" entries without a
826 // matching "end" entry to show up if a task gets migrated from one CPU to
831 // Sleep to allow the trace to be captured.
832 struct timespec timeLeft;
833 timeLeft.tv_sec = g_traceDurationSeconds;
834 timeLeft.tv_nsec = 0;
836 if (g_traceAborted) {
839 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
843 // Stop the trace and restore the default settings.
847 if (ok && traceDump) {
848 if (!g_traceAborted) {
849 printf(" done\nTRACE:\n");
853 printf("\ntrace aborted.\n");
858 fprintf(stderr, "unable to start tracing\n");
861 // Reset the trace buffer size to 1.
865 return g_traceAborted ? 1 : 0;