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 { "hal", "Hardware Modules", ATRACE_TAG_HAL, { } },
81 { "sched", "CPU Scheduling", 0, {
82 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_switch/enable" },
83 { REQ, "/sys/kernel/debug/tracing/events/sched/sched_wakeup/enable" },
85 { "freq", "CPU Frequency", 0, {
86 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_frequency/enable" },
87 { OPT, "/sys/kernel/debug/tracing/events/power/clock_set_rate/enable" },
89 { "membus", "Memory Bus Utilization", 0, {
90 { REQ, "/sys/kernel/debug/tracing/events/memory_bus/enable" },
92 { "idle", "CPU Idle", 0, {
93 { REQ, "/sys/kernel/debug/tracing/events/power/cpu_idle/enable" },
95 { "disk", "Disk I/O", 0, {
96 { REQ, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_enter/enable" },
97 { REQ, "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_exit/enable" },
98 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_issue/enable" },
99 { REQ, "/sys/kernel/debug/tracing/events/block/block_rq_complete/enable" },
101 { "load", "CPU Load", 0, {
102 { REQ, "/sys/kernel/debug/tracing/events/cpufreq_interactive/enable" },
104 { "sync", "Synchronization", 0, {
105 { REQ, "/sys/kernel/debug/tracing/events/sync/enable" },
107 { "workq", "Kernel Workqueues", 0, {
108 { REQ, "/sys/kernel/debug/tracing/events/workqueue/enable" },
112 /* Command line options */
113 static int g_traceDurationSeconds = 5;
114 static bool g_traceOverwrite = false;
115 static int g_traceBufferSizeKB = 2048;
116 static bool g_compress = false;
117 static bool g_nohup = false;
118 static int g_initialSleepSecs = 0;
121 static bool g_traceAborted = false;
122 static bool g_categoryEnables[NELEM(k_categories)] = {};
125 static const char* k_traceClockPath =
126 "/sys/kernel/debug/tracing/trace_clock";
128 static const char* k_traceBufferSizePath =
129 "/sys/kernel/debug/tracing/buffer_size_kb";
131 static const char* k_tracingOverwriteEnablePath =
132 "/sys/kernel/debug/tracing/options/overwrite";
134 static const char* k_tracingOnPath =
135 "/sys/kernel/debug/tracing/tracing_on";
137 static const char* k_tracePath =
138 "/sys/kernel/debug/tracing/trace";
140 // Check whether a file exists.
141 static bool fileExists(const char* filename) {
142 return access(filename, F_OK) != -1;
145 // Check whether a file is writable.
146 static bool fileIsWritable(const char* filename) {
147 return access(filename, W_OK) != -1;
150 // Write a string to a file, returning true if the write was successful.
151 static bool writeStr(const char* filename, const char* str)
153 int fd = open(filename, O_WRONLY);
155 fprintf(stderr, "error opening %s: %s (%d)\n", filename,
156 strerror(errno), errno);
161 ssize_t len = strlen(str);
162 if (write(fd, str, len) != len) {
163 fprintf(stderr, "error writing to %s: %s (%d)\n", filename,
164 strerror(errno), errno);
173 // Enable or disable a kernel option by writing a "1" or a "0" into a /sys
175 static bool setKernelOptionEnable(const char* filename, bool enable)
177 return writeStr(filename, enable ? "1" : "0");
180 // Check whether the category is supported on the device with the current
181 // rootness. A category is supported only if all its required /sys/ files are
182 // writable and if enabling the category will enable one or more tracing tags
184 static bool isCategorySupported(const TracingCategory& category)
186 bool ok = category.tags != 0;
187 for (int i = 0; i < MAX_SYS_FILES; i++) {
188 const char* path = category.sysfiles[i].path;
189 bool req = category.sysfiles[i].required == REQ;
192 if (!fileIsWritable(path)) {
198 ok |= fileIsWritable(path);
205 // Check whether the category would be supported on the device if the user
206 // were root. This function assumes that root is able to write to any file
207 // that exists. It performs the same logic as isCategorySupported, but it
208 // uses file existance rather than writability in the /sys/ file checks.
209 static bool isCategorySupportedForRoot(const TracingCategory& category)
211 bool ok = category.tags != 0;
212 for (int i = 0; i < MAX_SYS_FILES; i++) {
213 const char* path = category.sysfiles[i].path;
214 bool req = category.sysfiles[i].required == REQ;
217 if (!fileExists(path)) {
223 ok |= fileExists(path);
230 // Enable or disable overwriting of the kernel trace buffers. Disabling this
231 // will cause tracing to stop once the trace buffers have filled up.
232 static bool setTraceOverwriteEnable(bool enable)
234 return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
237 // Enable or disable kernel tracing.
238 static bool setTracingEnabled(bool enable)
240 return setKernelOptionEnable(k_tracingOnPath, enable);
243 // Clear the contents of the kernel trace.
244 static bool clearTrace()
246 int traceFD = creat(k_tracePath, 0);
248 fprintf(stderr, "error truncating %s: %s (%d)\n", k_tracePath,
249 strerror(errno), errno);
258 // Set the size of the kernel's trace buffer in kilobytes.
259 static bool setTraceBufferSizeKB(int size)
266 snprintf(str, 32, "%d", size);
267 return writeStr(k_traceBufferSizePath, str);
270 // Enable or disable the kernel's use of the global clock. Disabling the global
271 // clock will result in the kernel using a per-CPU local clock.
272 static bool setGlobalClockEnable(bool enable)
274 return writeStr(k_traceClockPath, enable ? "global" : "local");
277 // Poke all the binder-enabled processes in the system to get them to re-read
278 // their system properties.
279 static bool pokeBinderServices()
281 sp<IServiceManager> sm = defaultServiceManager();
282 Vector<String16> services = sm->listServices();
283 for (size_t i = 0; i < services.size(); i++) {
284 sp<IBinder> obj = sm->checkService(services[i]);
287 if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
290 // XXX: For some reason this fails on tablets trying to
291 // poke the "phone" service. It's not clear whether some
292 // are expected to fail.
293 String8 svc(services[i]);
294 fprintf(stderr, "error poking binder service %s\n",
304 // Set the trace tags that userland tracing uses, and poke the running
305 // processes to pick up the new value.
306 static bool setTagsProperty(uint64_t tags)
309 snprintf(buf, 64, "%#llx", tags);
310 if (property_set(k_traceTagsProperty, buf) < 0) {
311 fprintf(stderr, "error setting trace tags system property\n");
314 return pokeBinderServices();
317 // Disable all /sys/ enable files.
318 static bool disableKernelTraceEvents() {
320 for (int i = 0; i < NELEM(k_categories); i++) {
321 const TracingCategory &c = k_categories[i];
322 for (int j = 0; j < MAX_SYS_FILES; j++) {
323 const char* path = c.sysfiles[j].path;
324 if (path != NULL && fileIsWritable(path)) {
325 ok &= setKernelOptionEnable(path, false);
332 // Enable tracing in the kernel.
333 static bool startTrace()
337 // Set up the tracing options.
338 ok &= setTraceOverwriteEnable(g_traceOverwrite);
339 ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
340 ok &= setGlobalClockEnable(true);
342 // Set up the tags property.
344 for (int i = 0; i < NELEM(k_categories); i++) {
345 if (g_categoryEnables[i]) {
346 const TracingCategory &c = k_categories[i];
350 ok &= setTagsProperty(tags);
352 // Disable all the sysfs enables. This is done as a separate loop from
353 // the enables to allow the same enable to exist in multiple categories.
354 ok &= disableKernelTraceEvents();
356 // Enable all the sysfs enables that are in an enabled category.
357 for (int i = 0; i < NELEM(k_categories); i++) {
358 if (g_categoryEnables[i]) {
359 const TracingCategory &c = k_categories[i];
360 for (int j = 0; j < MAX_SYS_FILES; j++) {
361 const char* path = c.sysfiles[j].path;
362 bool required = c.sysfiles[j].required == REQ;
364 if (fileIsWritable(path)) {
365 ok &= setKernelOptionEnable(path, true);
366 } else if (required) {
367 fprintf(stderr, "error writing file %s\n", path);
376 ok &= setTracingEnabled(true);
381 // Disable tracing in the kernel.
382 static void stopTrace()
385 setTracingEnabled(false);
387 // Disable all tracing that we're able to.
388 disableKernelTraceEvents();
390 // Disable all the trace tags.
393 // Set the options back to their defaults.
394 setTraceOverwriteEnable(true);
395 setGlobalClockEnable(false);
397 // Note that we can't reset the trace buffer size here because that would
398 // clear the trace before we've read it.
401 // Read the current kernel trace and write it to stdout.
402 static void dumpTrace()
404 int traceFD = open(k_tracePath, O_RDWR);
406 fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
407 strerror(errno), errno);
416 bzero(&zs, sizeof(zs));
417 result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
418 if (result != Z_OK) {
419 fprintf(stderr, "error initializing zlib: %d\n", result);
424 const size_t bufSize = 64*1024;
425 in = (uint8_t*)malloc(bufSize);
426 out = (uint8_t*)malloc(bufSize);
430 zs.avail_out = bufSize;
434 if (zs.avail_in == 0) {
435 // More input is needed.
436 result = read(traceFD, in, bufSize);
438 fprintf(stderr, "error reading trace: %s (%d)\n",
439 strerror(errno), errno);
440 result = Z_STREAM_END;
442 } else if (result == 0) {
446 zs.avail_in = result;
450 if (zs.avail_out == 0) {
451 // Need to write the output.
452 result = write(STDOUT_FILENO, out, bufSize);
453 if ((size_t)result < bufSize) {
454 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
455 strerror(errno), errno);
456 result = Z_STREAM_END; // skip deflate error message
457 zs.avail_out = bufSize; // skip the final write
461 zs.avail_out = bufSize;
464 } while ((result = deflate(&zs, flush)) == Z_OK);
466 if (result != Z_STREAM_END) {
467 fprintf(stderr, "error deflating trace: %s\n", zs.msg);
470 if (zs.avail_out < bufSize) {
471 size_t bytes = bufSize - zs.avail_out;
472 result = write(STDOUT_FILENO, out, bytes);
473 if ((size_t)result < bytes) {
474 fprintf(stderr, "error writing deflated trace: %s (%d)\n",
475 strerror(errno), errno);
479 result = deflateEnd(&zs);
480 if (result != Z_OK) {
481 fprintf(stderr, "error cleaning up zlib: %d\n", result);
488 while ((sent = sendfile(STDOUT_FILENO, traceFD, NULL, 64*1024*1024)) > 0);
490 fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
498 static void handleSignal(int signo)
501 g_traceAborted = true;
505 static void registerSigHandler()
508 sigemptyset(&sa.sa_mask);
510 sa.sa_handler = handleSignal;
511 sigaction(SIGHUP, &sa, NULL);
512 sigaction(SIGINT, &sa, NULL);
513 sigaction(SIGQUIT, &sa, NULL);
514 sigaction(SIGTERM, &sa, NULL);
517 static bool setCategoryEnable(const char* name, bool enable)
519 for (int i = 0; i < NELEM(k_categories); i++) {
520 const TracingCategory& c = k_categories[i];
521 if (strcmp(name, c.name) == 0) {
522 if (isCategorySupported(c)) {
523 g_categoryEnables[i] = enable;
526 if (isCategorySupportedForRoot(c)) {
527 fprintf(stderr, "error: category \"%s\" requires root "
528 "privileges.\n", name);
530 fprintf(stderr, "error: category \"%s\" is not supported "
531 "on this device.\n", name);
537 fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
541 static void listSupportedCategories()
543 for (int i = 0; i < NELEM(k_categories); i++) {
544 const TracingCategory& c = k_categories[i];
545 if (isCategorySupported(c)) {
546 printf(" %10s - %s\n", c.name, c.longname);
551 // Print the command usage help to stderr.
552 static void showHelp(const char *cmd)
554 fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
555 fprintf(stderr, "options include:\n"
556 " -b N use a trace buffer size of N KB\n"
557 " -c trace into a circular buffer\n"
558 " -n ignore signals\n"
559 " -s N sleep for N seconds before tracing [default 0]\n"
560 " -t N trace for N seconds [defualt 5]\n"
561 " -z compress the trace dump\n"
562 " --async_start start circular trace and return immediatly\n"
563 " --async_dump dump the current contents of circular trace buffer\n"
564 " --async_stop stop tracing and dump the current contents of circular\n"
566 " --list_categories\n"
567 " list the available tracing categories\n"
571 int main(int argc, char **argv)
574 bool traceStart = true;
575 bool traceStop = true;
576 bool traceDump = true;
578 if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
585 int option_index = 0;
586 static struct option long_options[] = {
587 {"async_start", no_argument, 0, 0 },
588 {"async_stop", no_argument, 0, 0 },
589 {"async_dump", no_argument, 0, 0 },
590 {"list_categories", no_argument, 0, 0 },
594 ret = getopt_long(argc, argv, "b:cns:t:z",
595 long_options, &option_index);
598 for (int i = optind; i < argc; i++) {
599 if (!setCategoryEnable(argv[i], true)) {
600 fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
609 g_traceBufferSizeKB = atoi(optarg);
613 g_traceOverwrite = true;
621 g_initialSleepSecs = atoi(optarg);
625 g_traceDurationSeconds = atoi(optarg);
633 if (!strcmp(long_options[option_index].name, "async_start")) {
637 g_traceOverwrite = true;
638 } else if (!strcmp(long_options[option_index].name, "async_stop")) {
641 } else if (!strcmp(long_options[option_index].name, "async_dump")) {
645 } else if (!strcmp(long_options[option_index].name, "list_categories")) {
646 listSupportedCategories();
652 fprintf(stderr, "\n");
659 registerSigHandler();
661 if (g_initialSleepSecs > 0) {
662 sleep(g_initialSleepSecs);
665 bool ok = startTrace();
667 if (ok && traceStart) {
668 printf("capturing trace...");
671 // We clear the trace after starting it because tracing gets enabled for
672 // each CPU individually in the kernel. Having the beginning of the trace
673 // contain entries from only one CPU can cause "begin" entries without a
674 // matching "end" entry to show up if a task gets migrated from one CPU to
679 // Sleep to allow the trace to be captured.
680 struct timespec timeLeft;
681 timeLeft.tv_sec = g_traceDurationSeconds;
682 timeLeft.tv_nsec = 0;
684 if (g_traceAborted) {
687 } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
691 // Stop the trace and restore the default settings.
695 if (ok && traceDump) {
696 if (!g_traceAborted) {
697 printf(" done\nTRACE:\n");
701 printf("\ntrace aborted.\n");
706 fprintf(stderr, "unable to start tracing\n");
709 // Reset the trace buffer size to 1.
711 setTraceBufferSizeKB(1);
713 return g_traceAborted ? 1 : 0;