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 { "wm", "Window Manager", ATRACE_TAG_WINDOW_MANAGER, { } },
76 { "am", "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
77 { "audio", "Audio", ATRACE_TAG_AUDIO, { } },
78 { "video", "Video", ATRACE_TAG_VIDEO, { } },
79 { "camera", "Camera", ATRACE_TAG_CAMERA, { } },
80 { "sched", "CPU Scheduling", 0, {
81 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_switch/enable" },
82 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_wakeup/enable" },
84 { "freq", "CPU Frequency", 0, {
85 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_frequency/enable" },
86 { OPT, "/sys/kernel/debug/tracing/events/power/clock_set_rate/enable" },
88 { "membus", "Memory Bus Utilization", 0, {
89 { REQ, "/sys/kernel/debug/tracing/events/memory_bus/enable" },
91 { "idle", "CPU Idle", 0, {
92 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_idle/enable" },
94 { "disk", "Disk I/O", 0, {
95 { REQ, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_enter/enable" },
96 { REQ, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_exit/enable" },
97 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_issue/enable" },
98 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_complete/enable" },
100 { "load", "CPU Load", 0, {
101 { REQ, "/sys/kernel/debug/tracing/events/cpufreq_interactive/enable" },
103 { "sync", "Synchronization", 0, {
104 { REQ, "/sys/kernel/debug/tracing/events/sync/enable" },
106 { "workq", "Kernel Workqueues", 0, {
107 { REQ, "/sys/kernel/debug/tracing/events/workqueue/enable" },
111 /* Command line options */
112 static int g_traceDurationSeconds = 5;
113 static bool g_traceOverwrite = false;
114 static int g_traceBufferSizeKB = 2048;
115 static bool g_compress = false;
116 static bool g_nohup = false;
117 static int g_initialSleepSecs = 0;
120 static bool g_traceAborted = false;
121 static bool g_categoryEnables[NELEM(k_categories)] = {};
124 static const char* k_traceClockPath =
125 "/sys/kernel/debug/tracing/trace_clock";
127 static const char* k_traceBufferSizePath =
128 "/sys/kernel/debug/tracing/buffer_size_kb";
130 static const char* k_tracingOverwriteEnablePath =
131 "/sys/kernel/debug/tracing/options/overwrite";
133 static const char* k_tracingOnPath =
134 "/sys/kernel/debug/tracing/tracing_on";
136 static const char* k_tracePath =
137 "/sys/kernel/debug/tracing/trace";
139 // Check whether a file exists.
140 static bool fileExists(const char* filename) {
141 return access(filename, F_OK) != -1;
144 // Check whether a file is writable.
145 static bool fileIsWritable(const char* filename) {
146 return access(filename, W_OK) != -1;
149 // Write a string to a file, returning true if the write was successful.
150 static bool writeStr(const char* filename, const char* str)
152 int fd = open(filename, O_WRONLY);
154 fprintf(stderr, "error opening %s: %s (%d)\n", filename,
155 strerror(errno), errno);
160 ssize_t len = strlen(str);
161 if (write(fd, str, len) != len) {
162 fprintf(stderr, "error writing to %s: %s (%d)\n", filename,
163 strerror(errno), errno);
172 // Enable or disable a kernel option by writing a "1" or a "0" into a /sys
174 static bool setKernelOptionEnable(const char* filename, bool enable)
176 return writeStr(filename, enable ? "1" : "0");
179 // Check whether the category is supported on the device with the current
180 // rootness. A category is supported only if all its required /sys/ files are
181 // writable and if enabling the category will enable one or more tracing tags
183 static bool isCategorySupported(const TracingCategory& category)
185 bool ok = category.tags != 0;
186 for (int i = 0; i < MAX_SYS_FILES; i++) {
187 const char* path = category.sysfiles[i].path;
188 bool req = category.sysfiles[i].required == REQ;
191 if (!fileIsWritable(path)) {
197 ok |= fileIsWritable(path);
204 // Check whether the category would be supported on the device if the user
205 // were root. This function assumes that root is able to write to any file
206 // that exists. It performs the same logic as isCategorySupported, but it
207 // uses file existance rather than writability in the /sys/ file checks.
208 static bool isCategorySupportedForRoot(const TracingCategory& category)
210 bool ok = category.tags != 0;
211 for (int i = 0; i < MAX_SYS_FILES; i++) {
212 const char* path = category.sysfiles[i].path;
213 bool req = category.sysfiles[i].required == REQ;
216 if (!fileExists(path)) {
222 ok |= fileExists(path);
229 // Enable or disable overwriting of the kernel trace buffers. Disabling this
230 // will cause tracing to stop once the trace buffers have filled up.
231 static bool setTraceOverwriteEnable(bool enable)
233 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
236 // Enable or disable kernel tracing.
237 static bool setTracingEnabled(bool enable)
239 return setKernelOptionEnable(k_tracingOnPath, enable);
242 // Clear the contents of the kernel trace.
243 static bool clearTrace()
245 int traceFD = creat(k_tracePath, 0);
247 fprintf(stderr, "error truncating %s: %s (%d)\n", k_tracePath,
248 strerror(errno), errno);
257 // Set the size of the kernel's trace buffer in kilobytes.
258 static bool setTraceBufferSizeKB(int size)
265 snprintf(str, 32, "%d", size);
266 return writeStr(k_traceBufferSizePath, str);
269 // Enable or disable the kernel's use of the global clock. Disabling the global
270 // clock will result in the kernel using a per-CPU local clock.
271 static bool setGlobalClockEnable(bool enable)
273 return writeStr(k_traceClockPath, enable ? "global" : "local");
276 // Poke all the binder-enabled processes in the system to get them to re-read
277 // their system properties.
278 static bool pokeBinderServices()
280 sp<IServiceManager> sm = defaultServiceManager();
281 Vector<String16> services = sm->listServices();
282 for (size_t i = 0; i < services.size(); i++) {
283 sp<IBinder> obj = sm->checkService(services[i]);
286 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
289 // XXX: For some reason this fails on tablets trying to
290 // poke the "phone" service. It's not clear whether some
291 // are expected to fail.
292 String8 svc(services[i]);
293 fprintf(stderr, "error poking binder service %s\n",
303 // Set the trace tags that userland tracing uses, and poke the running
304 // processes to pick up the new value.
305 static bool setTagsProperty(uint64_t tags)
308 snprintf(buf, 64, "%#llx", tags);
309 if (property_set(k_traceTagsProperty, buf) < 0) {
310 fprintf(stderr, "error setting trace tags system property\n");
313 return pokeBinderServices();
316 // Disable all /sys/ enable files.
317 static bool disableKernelTraceEvents() {
319 for (int i = 0; i < NELEM(k_categories); i++) {
320 const TracingCategory &c = k_categories[i];
321 for (int j = 0; j < MAX_SYS_FILES; j++) {
322 const char* path = c.sysfiles[j].path;
323 if (path != NULL && fileIsWritable(path)) {
324 ok &= setKernelOptionEnable(path, false);
331 // Enable tracing in the kernel.
332 static bool startTrace()
336 // Set up the tracing options.
337 ok &= setTraceOverwriteEnable(g_traceOverwrite);
338 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
339 ok &= setGlobalClockEnable(true);
341 // Set up the tags property.
343 for (int i = 0; i < NELEM(k_categories); i++) {
344 if (g_categoryEnables[i]) {
345 const TracingCategory &c = k_categories[i];
349 ok &= setTagsProperty(tags);
351 // Disable all the sysfs enables. This is done as a separate loop from
352 // the enables to allow the same enable to exist in multiple categories.
353 ok &= disableKernelTraceEvents();
355 // Enable all the sysfs enables that are in an enabled category.
356 for (int i = 0; i < NELEM(k_categories); i++) {
357 if (g_categoryEnables[i]) {
358 const TracingCategory &c = k_categories[i];
359 for (int j = 0; j < MAX_SYS_FILES; j++) {
360 const char* path = c.sysfiles[j].path;
361 bool required = c.sysfiles[j].required == REQ;
363 if (fileIsWritable(path)) {
364 ok &= setKernelOptionEnable(path, true);
365 } else if (required) {
366 fprintf(stderr, "error writing file %s\n", path);
375 ok &= setTracingEnabled(true);
380 // Disable tracing in the kernel.
381 static void stopTrace()
384 setTracingEnabled(false);
386 // Disable all tracing that we're able to.
387 disableKernelTraceEvents();
389 // Disable all the trace tags.
392 // Set the options back to their defaults.
393 setTraceOverwriteEnable(true);
394 setGlobalClockEnable(false);
396 // Note that we can't reset the trace buffer size here because that would
397 // clear the trace before we've read it.
400 // Read the current kernel trace and write it to stdout.
401 static void dumpTrace()
403 int traceFD = open(k_tracePath, O_RDWR);
405 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
406 strerror(errno), errno);
415 bzero(&zs, sizeof(zs));
416 result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
417 if (result != Z_OK) {
418 fprintf(stderr, "error initializing zlib: %d\n", result);
423 const size_t bufSize = 64*1024;
424 in = (uint8_t*)malloc(bufSize);
425 out = (uint8_t*)malloc(bufSize);
429 zs.avail_out = bufSize;
433 if (zs.avail_in == 0) {
434 // More input is needed.
435 result = read(traceFD, in, bufSize);
437 fprintf(stderr, "error reading trace: %s (%d)\n",
438 strerror(errno), errno);
439 result = Z_STREAM_END;
441 } else if (result == 0) {
445 zs.avail_in = result;
449 if (zs.avail_out == 0) {
450 // Need to write the output.
451 result = write(STDOUT_FILENO, out, bufSize);
452 if ((size_t)result < bufSize) {
453 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
454 strerror(errno), errno);
455 result = Z_STREAM_END; // skip deflate error message
456 zs.avail_out = bufSize; // skip the final write
460 zs.avail_out = bufSize;
463 } while ((result = deflate(&zs, flush)) == Z_OK);
465 if (result != Z_STREAM_END) {
466 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
469 if (zs.avail_out < bufSize) {
470 size_t bytes = bufSize - zs.avail_out;
471 result = write(STDOUT_FILENO, out, bytes);
472 if ((size_t)result < bytes) {
473 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
474 strerror(errno), errno);
478 result = deflateEnd(&zs);
479 if (result != Z_OK) {
480 fprintf(stderr, "error cleaning up zlib: %d\n", result);
487 while ((sent = sendfile(STDOUT_FILENO, traceFD, NULL, 64*1024*1024)) > 0);
489 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
497 static void handleSignal(int signo)
500 g_traceAborted = true;
504 static void registerSigHandler()
507 sigemptyset(&sa.sa_mask);
509 sa.sa_handler = handleSignal;
510 sigaction(SIGHUP, &sa, NULL);
511 sigaction(SIGINT, &sa, NULL);
512 sigaction(SIGQUIT, &sa, NULL);
513 sigaction(SIGTERM, &sa, NULL);
516 static bool setCategoryEnable(const char* name, bool enable)
518 for (int i = 0; i < NELEM(k_categories); i++) {
519 const TracingCategory& c = k_categories[i];
520 if (strcmp(name, c.name) == 0) {
521 if (isCategorySupported(c)) {
522 g_categoryEnables[i] = enable;
525 if (isCategorySupportedForRoot(c)) {
526 fprintf(stderr, "error: category \"%s\" requires root "
527 "privileges.\n", name);
529 fprintf(stderr, "error: category \"%s\" is not supported "
530 "on this device.\n", name);
536 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
540 static void listSupportedCategories()
542 for (int i = 0; i < NELEM(k_categories); i++) {
543 const TracingCategory& c = k_categories[i];
544 if (isCategorySupported(c)) {
545 printf(" %10s - %s\n", c.name, c.longname);
550 // Print the command usage help to stderr.
551 static void showHelp(const char *cmd)
553 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
554 fprintf(stderr, "options include:\n"
555 " -b N use a trace buffer size of N KB\n"
556 " -c trace into a circular buffer\n"
557 " -n ignore signals\n"
558 " -s N sleep for N seconds before tracing [default 0]\n"
559 " -t N trace for N seconds [defualt 5]\n"
560 " -z compress the trace dump\n"
561 " --async_start start circular trace and return immediatly\n"
562 " --async_dump dump the current contents of circular trace buffer\n"
563 " --async_stop stop tracing and dump the current contents of circular\n"
568 int main(int argc, char **argv)
571 bool traceStart = true;
572 bool traceStop = true;
573 bool traceDump = true;
575 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
582 int option_index = 0;
583 static struct option long_options[] = {
584 {"async_start", no_argument, 0, 0 },
585 {"async_stop", no_argument, 0, 0 },
586 {"async_dump", no_argument, 0, 0 },
587 {"list_categories", no_argument, 0, 0 },
591 ret = getopt_long(argc, argv, "b:cns:t:z",
592 long_options, &option_index);
595 for (int i = optind; i < argc; i++) {
596 if (!setCategoryEnable(argv[i], true)) {
597 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
606 g_traceBufferSizeKB = atoi(optarg);
610 g_traceOverwrite = true;
618 g_initialSleepSecs = atoi(optarg);
622 g_traceDurationSeconds = atoi(optarg);
630 if (!strcmp(long_options[option_index].name, "async_start")) {
634 g_traceOverwrite = true;
635 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
638 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
642 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
643 listSupportedCategories();
649 fprintf(stderr, "\n");
656 registerSigHandler();
658 if (g_initialSleepSecs > 0) {
659 sleep(g_initialSleepSecs);
662 bool ok = startTrace();
664 if (ok && traceStart) {
665 printf("capturing trace...");
668 // We clear the trace after starting it because tracing gets enabled for
669 // each CPU individually in the kernel. Having the beginning of the trace
670 // contain entries from only one CPU can cause "begin" entries without a
671 // matching "end" entry to show up if a task gets migrated from one CPU to
676 // Sleep to allow the trace to be captured.
677 struct timespec timeLeft;
678 timeLeft.tv_sec = g_traceDurationSeconds;
679 timeLeft.tv_nsec = 0;
681 if (g_traceAborted) {
684 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
688 // Stop the trace and restore the default settings.
692 if (ok && traceDump) {
693 if (!g_traceAborted) {
694 printf(" done\nTRACE:\n");
698 printf("\ntrace aborted.\n");
703 fprintf(stderr, "unable to start tracing\n");
706 // Reset the trace buffer size to 1.
708 setTraceBufferSizeKB(1);
710 return g_traceAborted ? 1 : 0;