eventstat-0.04.03/0000755000175000017500000000000013234563557012352 5ustar kingkingeventstat-0.04.03/Makefile0000644000175000017500000000334613234563554014015 0ustar kingking# # Copyright (C) 2011-2018 Canonical, Ltd. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # VERSION=0.04.03 CFLAGS += -Wall -Wextra -DVERSION='"$(VERSION)"' -O2 # # Pedantic flags # ifeq ($(PEDANTIC),1) CFLAGS += -Wabi -Wcast-qual -Wfloat-equal -Wmissing-declarations \ -Wmissing-format-attribute -Wno-long-long -Wpacked \ -Wredundant-decls -Wshadow -Wno-missing-field-initializers \ -Wno-missing-braces -Wno-sign-compare -Wno-multichar endif BINDIR=/usr/bin MANDIR=/usr/share/man/man8 eventstat: eventstat.o $(CC) $(CFLAGS) $< -lm -lncurses -o $@ $(LDFLAGS) eventstat.8.gz: eventstat.8 gzip -c $< > $@ dist: rm -rf eventstat-$(VERSION) mkdir eventstat-$(VERSION) cp -rp Makefile eventstat.c eventstat.8 COPYING snapcraft \ eventstat-$(VERSION) tar -zcf eventstat-$(VERSION).tar.gz eventstat-$(VERSION) rm -rf eventstat-$(VERSION) clean: rm -f eventstat eventstat.o eventstat.8.gz rm -f eventstat-$(VERSION).tar.gz install: eventstat eventstat.8.gz mkdir -p ${DESTDIR}${BINDIR} cp eventstat ${DESTDIR}${BINDIR} mkdir -p ${DESTDIR}${MANDIR} cp eventstat.8.gz ${DESTDIR}${MANDIR} eventstat-0.04.03/eventstat.80000644000175000017500000001105513234563554014457 0ustar kingking.\" Hey, EMACS: -*- nroff -*- .\" First parameter, NAME, should be all caps .\" Second parameter, SECTION, should be 1-8, maybe w/ subsection .\" other parameters are allowed: see man(7), man(1) .TH EVENTSTAT 8 "August 14, 2017" .\" Please adjust this date whenever revising the manpage. .\" .\" Some roff macros, for reference: .\" .nh disable hyphenation .\" .hy enable hyphenation .\" .ad l left justify .\" .ad b justify to both left and right margins .\" .nf disable filling .\" .fi enable filling .\" .br insert line break .\" .sp insert n+1 empty lines .\" for manpage-specific macros, see man(7) .SH NAME eventstat \- a tool to measure system events. .br .SH SYNOPSIS .B eventstat .RI [options] " [delay " [count]] .br .SH DESCRIPTION eventstat is a program that dumps the current active system events that are added to the kernel timer list. .SH OPTIONS eventstat options are as follow: .TP .B \-b just report events, PID and process name. By default the short task name from the kernel comm field will be displayed, however the \-s and \-l options will report more process name information. .TP .B \-c report cumulative events rather than events per sample period. .TP .B \-C report the sample event count in the CSV output rather than the default events per second rate. .TP .B \-d strip full directory path off the process name in the CSV output. .TP .B \-h show help. .TP .B \-i show timer ID information. .TP .B \-k report just kernel threads. .TP .B \-l report long process name from /proc/pid/cmdline. This reports the process name and all the command line arguments. .TP .B \-n event_count only display the first event_count number of top events. .TP .B \-q run quietly, only really makes sense with \-r option. .TP .B \-r csv_file output gathered data in a comma separated values file. This can be then imported and graphed using your favourite open source spread sheet. .TP .B \-s report short process name from /proc/pid/cmdline. This reports just the process name. .TP .B \-S report the minimum, maximum, average and population standard deviation at the end of the CSV output. .TP .B \-t threshold ignore samples where the event delta per second less than the given threshold. .TP .B \-T enable 'top' mode, refresh display on each update. .TP .B \-u report just user space processes. .TP .B \-w add timestamp (the "whence" info) to the output. .SH EXAMPLES .LP Dump events every second until stopped. .RS 8 sudo eventstat .RE .LP Dump the top 20 events every 60 seconds until stopped. .RS 8 sudo eventstat \-n 20 60 .RE .LP Dump events every 10 seconds just 5 times. .RS 8 sudo eventstat 10 5 .RE .LP Quietly dump events every 10 seconds just 5 times into a CSV file with short process name. .RS 8 sudo eventstat 10 5 \-q \-s \-r results.csv .RE .SH CSV OUTPUT .LP The \-r option generates a comma separated file report that can be imported into spreadsheets or parsed using text processing tools. Column 1 of the data is the label for each row, columns 2 onwards contain the data for each task that generated a wakeup event. .LP The first row lists the task name of the thread or process. Task names in [ ] brackets are kernel threads, other tasks are the names of user space processes. By default these names are derived from the task names from kernel trace events but the \-s \-l options fetch more complete task names from /proc/pid/cmdline instead. .LP The second and third rows list the names of the internal Linux kernel timer init function. .LP The fourth row lists the total number of wakeup events for each task during the entire run of eventstat. .LP The subsequent rows list the average number of wakeups per second measured during the sample interval for each task in column two onwards. The first column indicates the sample time (in seconds) since the start of the measuring. .SH NOTES Version 4.0 of eventstat gathers event timer data from the kernel trace event timers and hence is not compatible with previous versions of eventstat. The move to using kernel trace events was necessary as the Linux 4.12 kernel dropped support for the /proc/timer_stats interface. .SH SEE ALSO .BR powertop (8), .BR top (1) .SH AUTHOR eventstat was written by Colin King .PP This manual page was written by Colin King , for the Ubuntu project (but may be used by others). .SH COPYRIGHT Copyright \(co 2011-2016 Canonical Ltd. .br This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. eventstat-0.04.03/eventstat.c0000644000175000017500000012601113234563554014531 0ustar kingking/* * Copyright (C) 2011-2018 Canonical * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * eventstat by Colin Ian King */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define TABLE_SIZE (1009) /* Should be a prime */ #define SIZEOF_ARRAY(a) (sizeof(a) / sizeof(a[0])) #define OPT_QUIET (0x00000001) #define OPT_CUMULATIVE (0x00000002) #define OPT_CMD_SHORT (0x00000004) #define OPT_CMD_LONG (0x00000008) #define OPT_DIRNAME_STRIP (0x00000010) #define OPT_SAMPLE_COUNT (0x00000020) #define OPT_RESULT_STATS (0x00000040) #define OPT_BRIEF (0x00000080) #define OPT_KERNEL (0x00000100) #define OPT_USER (0x00000200) #define OPT_SHOW_WHENCE (0x00000400) #define OPT_TOP (0x00000800) #define OPT_TIMER_ID (0x00001000) #define OPT_CMD (OPT_CMD_SHORT | OPT_CMD_LONG) #define EVENT_BUF_SIZE (64 * 1024) #define TIMER_REAP_AGE (600) /* Age of timer before it is reaped */ #define TIMER_REAP_THRESHOLD (30) #define EVENTS_WIDTH (8) #define TASK_WIDTH (15) #define TIMER_ID_WIDTH (16) #define FUNC_WIDTH (24) #define FUNC_WIDTH_MAX (30) #define _VER_(major, minor, patchlevel) \ ((major * 10000) + (minor * 100) + patchlevel) #if defined(__GNUC__) && defined(__GNUC_MINOR__) #if defined(__GNUC_PATCHLEVEL__) #define NEED_GNUC(major, minor, patchlevel) \ _VER_(major, minor, patchlevel) <= \ _VER_(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) #else #define NEED_GNUC(major, minor, patchlevel) \ _VER_(major, minor, patchlevel) <= _VER_(__GNUC__, __GNUC_MINOR__, 0) #endif #else #define NEED_GNUC(major, minor, patchlevel) (0) #endif #if defined(__GNUC__) && NEED_GNUC(4,6,0) #define HOT __attribute__ ((hot)) #else #define HOT #endif #if defined(__GNUC__) && !defined(__clang__) && NEED_GNUC(4,6,0) #define OPTIMIZE3 __attribute__((optimize("-O3"))) #else #define OPTIMIZE3 #endif #if defined(__GNUC__) #define LIKELY(x) __builtin_expect((x),1) #define UNLIKELY(x) __builtin_expect((x),0) #else #define LIKELY(x) (x) #define UNLIKELY(x) (x) #endif #define FLOAT_TINY (0.0000001) #define FLOAT_CMP(a, b) (fabs(a - b) < FLOAT_TINY) /* * timer_info_t contains per task timer infos. */ typedef struct timer_info { struct timer_info *next; /* Next in list */ struct timer_info *hash_next; /* Next in hash list */ pid_t pid; char *task; /* Name of process/kernel task */ char *task_mangled; /* Modified name of process/kernel */ char *cmdline; /* From /proc/$pid/cmdline */ char *func; /* Kernel waiting func */ char *ident; /* Unique identity */ bool kernel_thread; /* True if task is a kernel thread */ uint32_t ref_count; /* Timer stat reference count */ uint64_t timer; /* Timer ID */ uint64_t total_events; /* Total number of events */ uint64_t delta_events; /* Events in one time period */ double time_total; /* Total time */ double last_used; /* Last referenced */ double prev_used; /* Previous time used */ } timer_info_t; typedef struct timer_stat { struct timer_stat *next; /* Next timer stat in hash table */ struct timer_stat *sorted_freq_next; /* Next timer stat in event */ /* frequency sorted list */ timer_info_t *info; /* Timer info */ } timer_stat_t; /* sample delta item as an element of the sample_delta_list_t */ typedef struct sample_delta_item { struct sample_delta_item *next; /* next in list */ int64_t delta_events; /* delta in events */ double time_delta; /* difference in time between old */ /* and new */ timer_info_t *info; /* timer this refers to */ } sample_delta_item_t; /* list of sample_delta_items */ typedef struct sample_delta_list { struct sample_delta_list *next; /* next in list */ struct sample_delta_item *list; /* list of sample delta items */ double whence; /* when the sample was taken */ } sample_delta_list_t; typedef struct { char *task; /* Name of kernel task */ size_t len; /* Length */ } kernel_task_info; #define KERN_TASK_INFO(str) { str, sizeof(str) - 1 } static const char * const g_app_name = "eventstat"; static const char * const g_sys_tracing_enable = "/sys/kernel/debug/tracing/events/timer/hrtimer_start/enable"; static const char * const g_sys_tracing_pipe = "/sys/kernel/debug/tracing/trace_pipe"; static const char * const g_sys_tracing_set_event = "/sys/kernel/debug/tracing/set_event"; static const char * const g_sys_tracing_filter = "/sys/kernel/debug/tracing/events/timer/filter"; static void es_printf(const char *fmt, ...) __attribute__((format(printf, 1, 2))); static timer_stat_t *g_timer_stat_free_list; /* free list of timer stats */ static timer_info_t *g_timer_info_list; /* cache list of timer_info */ static timer_info_t *g_timer_info_hash[TABLE_SIZE]; /* hash of timer_info */ /* head of list of samples, sorted in sample time order */ static sample_delta_list_t *g_sample_delta_list_head; /* tail of list of samples, sorted in sample time order */ static sample_delta_list_t *g_sample_delta_list_tail; /* ignore samples with event delta less than this */ static double g_opt_threshold; static char *g_csv_results; /* results in comma separated values */ static char *g_get_events_buf; /* buffer to glob events into */ static uint32_t g_timer_info_list_length; /* length of timer_info_list */ static uint32_t g_opt_flags; /* option flags */ static volatile bool g_stop_eventstat = false; /* set by sighandler */ static bool g_sane_procs; /* false if we are in a container */ static bool g_resized; /* window resized */ static bool g_curses_init; /* curses initialised */ static int g_rows = 25; /* tty size, rows */ static int g_cols = 80; /* tty size, columns */ /* * Attempt to catch a range of signals so * we can clean */ static const int g_signals[] = { /* POSIX.1-1990 */ #ifdef SIGHUP SIGHUP, #endif #ifdef SIGINT SIGINT, #endif #ifdef SIGQUIT SIGQUIT, #endif #ifdef SIGFPE SIGFPE, #endif #ifdef SIGTERM SIGTERM, #endif #ifdef SIGUSR1 SIGUSR1, #endif #ifdef SIGUSR2 SIGUSR2, /* POSIX.1-2001 */ #endif #ifdef SIGXCPU SIGXCPU, #endif #ifdef SIGXFSZ SIGXFSZ, #endif /* Linux various */ #ifdef SIGIOT SIGIOT, #endif #ifdef SIGSTKFLT SIGSTKFLT, #endif #ifdef SIGPWR SIGPWR, #endif #ifdef SIGINFO SIGINFO, #endif #ifdef SIGVTALRM SIGVTALRM, #endif }; /* * pid_max_digits() * determine (or guess) maximum digits of pids */ static int pid_max_digits(void) { static int max_digits; ssize_t n; int fd; const int default_digits = 6; const int min_digits = 5; char buf[32]; if (LIKELY(max_digits)) goto ret; max_digits = default_digits; fd = open("/proc/sys/kernel/pid_max", O_RDONLY); if (fd < 0) goto ret; n = read(fd, buf, sizeof(buf) - 1); (void)close(fd); if (n < 0) goto ret; buf[n] = '\0'; max_digits = 0; while ((buf[max_digits] >= '0') && (buf[max_digits] <= '9')) max_digits++; if (max_digits < min_digits) max_digits = min_digits; ret: return max_digits; } /* * hash_djb2a() * Hash a string, from Dan Bernstein comp.lang.c (xor version) */ static HOT OPTIMIZE3 uint32_t hash_djb2a(const char *str) { register uint32_t hash = 5381; register int c; while ((c = *str++)) { /* (hash * 33) ^ c */ hash = ((hash << 5) + hash) ^ c; hash = (hash * 33) ^ c; } return hash % TABLE_SIZE; } /* * eventstat_winsize() * get tty size */ static void eventstat_winsize(void) { struct winsize ws; if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1) { g_rows = ws.ws_row; g_cols = ws.ws_col; } } /* * eventstat_clear() * clear screen if in top mode */ static inline void eventstat_clear(void) { if (g_curses_init) clear(); } /* * eventstat_refresh() * refresh screen if in top mode */ static inline void eventstat_refresh(void) { if (g_curses_init) refresh(); } /* * eventstat_move() * move cursor if in top mode */ static inline void eventstat_move(const int y, const int x) { if (g_curses_init) move(y, x); } /* * eventstat_endwin() * call endwin if in top mode */ static void eventstat_endwin(void) { if (g_curses_init) { clear(); endwin(); } } /* * err_abort() * print an error and exit */ static void __attribute__ ((noreturn)) __attribute__((format(printf, 1, 2))) err_abort(const char *fmt, ...) { va_list ap; va_start(ap, fmt); eventstat_endwin(); (void)vfprintf(stderr,fmt, ap); va_end(ap); exit(EXIT_FAILURE); } /* * set_tracing_enable() * enable/disable timer stat */ static void set_tracing(const char *path, const char *str, const bool carp) { int fd; const ssize_t len = (ssize_t)strlen(str); if ((fd = open(path, O_WRONLY, S_IRUSR | S_IWUSR)) < 0) { if (carp) { err_abort("Cannot open %s, errno=%d (%s)\n", path, errno, strerror(errno)); } return; } if (write(fd, str, len) != len) { (void)close(fd); if (carp) { err_abort("Cannot write to %s, errno=%d (%s)\n", path, errno, strerror(errno)); } return; } (void)close(fd); } /* * set_tracing_enable() * enable/disable timer stat */ static inline void set_tracing_enable(const char *str, const bool carp) { set_tracing(g_sys_tracing_enable, str, carp); } static void set_tracing_event(void) { char buffer[64]; set_tracing(g_sys_tracing_set_event, "\n", true); set_tracing(g_sys_tracing_set_event, "hrtimer_start", true); set_tracing(g_sys_tracing_filter, "0", true); /* Ignore event stat and idle events */ (void)snprintf(buffer, sizeof(buffer), "common_pid != %d && common_pid != 0", getpid()); set_tracing(g_sys_tracing_filter, buffer, true); } /* * eventstat_exit() * exit and set timer stat to 0 */ static void __attribute__ ((noreturn)) eventstat_exit(const int status) { set_tracing_enable("0\n", false); exit(status); } /* * timeval_to_double * timeval to a double (in seconds) */ static inline double timeval_to_double(const struct timeval *const tv) { return (double)tv->tv_sec + ((double)tv->tv_usec / 1000000.0); } /* * double_to_timeval * seconds in double to timeval */ static inline struct timeval double_to_timeval(const double val) { struct timeval tv; tv.tv_sec = val; tv.tv_usec = (val - (time_t)val) * 1000000.0; return tv; } /* * gettime_to_double() * get time as a double */ static double gettime_to_double(void) { struct timeval tv; if (UNLIKELY(gettimeofday(&tv, NULL) < 0)) err_abort("gettimeofday failed: errno=%d (%s)\n", errno, strerror(errno)); return timeval_to_double(&tv); } /* * sane_proc_pid_info() * detect if proc info mapping from /proc/timer_stats * maps to proc pids OK. If we are in a container or * we can't tell, return false. */ static bool sane_proc_pid_info(void) { FILE *fp; static const char pattern[] = "container="; const char *ptr = pattern; bool ret = true; fp = fopen("/proc/1/environ", "r"); if (!fp) return false; while (!feof(fp)) { int ch = getc(fp); if (*ptr == ch) { ptr++; /* Match? So we're inside a container */ if (*ptr == '\0') { ret = false; break; } } else { /* No match, skip to end of var and restart scan */ do { ch = getc(fp); } while ((ch != EOF) && (ch != '\0')); ptr = pattern; } } (void)fclose(fp); return ret; } /* * handle_sig() * catch signal, flag a stop and restore timer stat */ static void handle_sig(int dummy) { (void)dummy; /* Stop unused parameter warning with -Wextra */ g_stop_eventstat = true; set_tracing_enable("0\n", false); } /* * samples_free() * free collected samples */ static inline void samples_free(void) { sample_delta_list_t *sdl = g_sample_delta_list_head; while (sdl) { sample_delta_list_t *sdl_next = sdl->next; sample_delta_item_t *sdi = sdl->list; while (sdi) { sample_delta_item_t *sdi_next = sdi->next; free(sdi); sdi = sdi_next; } free(sdl); sdl = sdl_next; } } /* * sample_add() * add a timer_stat's delta and info field to a * list at time position whence */ static void sample_add(timer_stat_t *timer_stat, const double whence) { bool found = false; sample_delta_list_t *sdl; sample_delta_item_t *sdi; if (g_csv_results == NULL) /* No need if not enabled */ return; for (sdl = g_sample_delta_list_head; sdl; sdl = sdl->next) { if (FLOAT_CMP(sdl->whence, whence)) { found = true; break; } } /* * New time period, need new sdl, we assume it goes at the end of the * list since time is assumed to be increasing */ if (!found) { if ((sdl = calloc(1, sizeof(*sdl))) == NULL) err_abort("Cannot allocate sample delta list\n"); sdl->whence = whence; if (g_sample_delta_list_tail) { g_sample_delta_list_tail->next = sdl; g_sample_delta_list_tail = sdl; } else { g_sample_delta_list_head = sdl; g_sample_delta_list_tail = sdl; } } /* Now append the sdi onto the list */ if (UNLIKELY(((sdi = calloc(1, sizeof(*sdi))) == NULL))) err_abort("Cannot allocate sample delta item\n"); sdi->delta_events = timer_stat->info->delta_events; sdi->time_delta = timer_stat->info->last_used - timer_stat->info->prev_used; sdi->info = timer_stat->info; sdi->next = sdl->list; sdl->list = sdi; } /* * sample_find() * scan through a sample_delta_list for timer info, * return NULL if not found */ inline HOT static sample_delta_item_t *sample_find( sample_delta_list_t *sdl, const timer_info_t *info) { sample_delta_item_t *sdi; for (sdi = sdl->list; sdi; sdi = sdi->next) { if (sdi->info == info) return sdi; } return NULL; } /* * info_compare_total() * used by qsort to sort array in sample event total order */ static int info_compare_total(const void *item1, const void *item2) { timer_info_t *const *info1 = (timer_info_t *const *)item1; timer_info_t *const *info2 = (timer_info_t *const *)item2; if (UNLIKELY((*info2)->total_events == (*info1)->total_events)) return 0; return ((*info2)->total_events > (*info1)->total_events) ? 1 : -1; } static bool pid_a_kernel_thread_guess(const char *task) { /* * This is not exactly accurate, but if we can't look up * a process then try and infer something from the comm field. * Until we have better kernel support to map /proc/timer_stats * pids to containerised pids this is the best we can do. */ static const kernel_task_info kernel_tasks[] = { KERN_TASK_INFO("swapper/"), KERN_TASK_INFO("kworker/"), KERN_TASK_INFO("ksoftirqd/"), KERN_TASK_INFO("watchdog/"), KERN_TASK_INFO("migration/"), KERN_TASK_INFO("irq/"), KERN_TASK_INFO("mmcqd/"), KERN_TASK_INFO("jbd2/"), KERN_TASK_INFO("kthreadd"), KERN_TASK_INFO("kthrotld"), KERN_TASK_INFO("kswapd"), KERN_TASK_INFO("ecryptfs-kthrea"), KERN_TASK_INFO("kauditd"), KERN_TASK_INFO("kblockd"), KERN_TASK_INFO("kcryptd"), KERN_TASK_INFO("kdevtmpfs"), KERN_TASK_INFO("khelper"), KERN_TASK_INFO("khubd"), KERN_TASK_INFO("khugepaged"), KERN_TASK_INFO("khungtaskd"), KERN_TASK_INFO("flush-"), KERN_TASK_INFO("bdi-default-"), { NULL, 0 } }; size_t i; for (i = 0; i < SIZEOF_ARRAY(kernel_tasks); i++) { if (!strncmp(task, kernel_tasks[i].task, kernel_tasks[i].len)) return true; } return false; } /* * pid_a_kernel_thread * */ static bool pid_a_kernel_thread(const char *task, const pid_t id) { const pid_t pgid = id == 0 ? 0 : getpgid(id); /* We are either in a container, or with a task with a NULL cmdline */ if (LIKELY(g_sane_procs || (id >= 0))) return (pgid == 0); /* Can't get pgid on that pid, so make a guess */ return pid_a_kernel_thread_guess(task); } /* * get_pid_cmdline * get process's /proc/pid/cmdline */ static char *get_pid_cmdline(const pid_t id) { char buffer[4096]; char *ptr; int fd; ssize_t ret; (void)snprintf(buffer, sizeof(buffer), "/proc/%d/cmdline", id); if ((fd = open(buffer, O_RDONLY)) < 0) return NULL; ret = read(fd, buffer, sizeof(buffer)); (void)close(fd); if (ret < 0) return NULL; if (ret == 0) return strdup(""); buffer[sizeof(buffer)-1] = '\0'; /* * OPT_CMD_LONG option we get the full cmdline args */ if (g_opt_flags & OPT_CMD_LONG) { for (ptr = buffer; ptr < buffer + ret - 1; ptr++) { if (*ptr == '\0') *ptr = ' '; } *ptr = '\0'; } /* * OPT_CMD_SHORT option we discard anything after a space */ if (g_opt_flags & OPT_CMD_SHORT) { for (ptr = buffer; *ptr && (ptr < buffer + ret); ptr++) { if (*ptr == ' ') *ptr = '\0'; } } if (g_opt_flags & OPT_DIRNAME_STRIP) return strdup(basename(buffer)); return strdup(buffer); } static inline double duration_round(const double duration) { return floor((duration * 100.0) + 0.5) / 100.0; } /* * samples_dump() * dump out collected sample information */ static void samples_dump(const char *filename) { timer_info_t **sorted_timer_infos; size_t i, n; FILE *fp; uint64_t count = 0; double first_time = -1.0; timer_info_t *info; sample_delta_list_t *sdl; if (filename == NULL) return; if ((fp = fopen(filename, "w")) == NULL) { (void)fprintf(stderr, "Cannot write to file %s\n", filename); return; } sorted_timer_infos = calloc(g_timer_info_list_length, sizeof(*sorted_timer_infos)); if (!sorted_timer_infos) err_abort("Cannot allocate buffer for sorting timer_infos\n"); /* Just want the timers with some non-zero total */ for (n = 0, info = g_timer_info_list; info; info = info->next) { if (info->total_events > 0) sorted_timer_infos[n++] = info; } qsort(sorted_timer_infos, n, sizeof(timer_info_t *), info_compare_total); fprintf(fp, "Time:,Task:"); for (i = 0; i < n; i++) { char *task; if (g_opt_flags & OPT_CMD) task = sorted_timer_infos[i]->cmdline; else task = sorted_timer_infos[i]->task_mangled; (void)fprintf(fp, ",%s", task); } (void)fprintf(fp, "\n"); (void)fprintf(fp, ",Init Function:"); for (i = 0; i < n; i++) (void)fprintf(fp, ",%s", sorted_timer_infos[i]->func); (void)fprintf(fp, "\n"); (void)fprintf(fp, ",Total:"); for (i = 0; i < n; i++) (void)fprintf(fp, ",%" PRIu64, sorted_timer_infos[i]->total_events); (void)fprintf(fp, "\n"); for (sdl = g_sample_delta_list_head; sdl; sdl = sdl->next) { time_t t = (time_t)sdl->whence; struct tm *tm; count++; tm = localtime(&t); (void)fprintf(fp, "%2.2d:%2.2d:%2.2d", tm->tm_hour, tm->tm_min, tm->tm_sec); if (first_time < 0) first_time = sdl->whence; (void)fprintf(fp, ",%f", duration_round(sdl->whence - first_time)); /* * Scan in timer info order to be consistent for all sdl rows */ for (i = 0; i < n; i++) { sample_delta_item_t *sdi = sample_find(sdl, sorted_timer_infos[i]); /* * duration - if -C option is used then don't scale * by the per sample duration time, instead give the * raw sample count by scaling by 1.0 (i.e. no scaling) */ if (sdi) { double duration = duration_round((g_opt_flags & OPT_SAMPLE_COUNT) ? 1.0 : sdi->time_delta); (void)fprintf(fp, ",%f", FLOAT_CMP(duration, 0.0) ? -99.99 : (double)sdi->delta_events / duration); } else (void)fprintf(fp, ",%f", 0.0); } (void)fprintf(fp, "\n"); } /* * -S option - some statistics, min, max, average, std.dev. */ if (g_opt_flags & OPT_RESULT_STATS) { (void)fprintf(fp, ",Min:"); for (i = 0; i < n; i++) { double min = DBL_MAX; for (sdl = g_sample_delta_list_head; sdl; sdl = sdl->next) { sample_delta_item_t *sdi = sample_find(sdl, sorted_timer_infos[i]); if (sdi) { double duration = duration_round((g_opt_flags & OPT_SAMPLE_COUNT) ? 1.0 : sdi->time_delta); double val = FLOAT_CMP(duration, 0.0) ? 0.0 : sdi->delta_events / duration; if (min > val) min = val; } } (void)fprintf(fp, ",%f", min); } (void)fprintf(fp, "\n"); (void)fprintf(fp, ",Max:"); for (i = 0; i < n; i++) { double max = DBL_MIN; for (sdl = g_sample_delta_list_head; sdl; sdl = sdl->next) { sample_delta_item_t *sdi = sample_find(sdl, sorted_timer_infos[i]); if (sdi) { double duration = duration_round((g_opt_flags & OPT_SAMPLE_COUNT) ? 1.0 : sdi->time_delta); double val = FLOAT_CMP(duration, 0.0) ? 0.0 : sdi->delta_events / duration; if (max < val) max = val; } } (void)fprintf(fp, ",%f", max); } (void)fprintf(fp, "\n"); (void)fprintf(fp, ",Average:"); for (i = 0; i < n; i++) (void)fprintf(fp, ",%f", count == 0 ? 0.0 : (double)sorted_timer_infos[i]->total_events / count); (void)fprintf(fp, "\n"); /* * population standard deviation */ (void)fprintf(fp, ",Std.Dev.:"); for (i = 0; i < n; i++) { double average = (double) sorted_timer_infos[i]->total_events / (double)count; double sum = 0.0; for (sdl = g_sample_delta_list_head; sdl; sdl = sdl->next) { sample_delta_item_t *sdi = sample_find(sdl, sorted_timer_infos[i]); if (sdi) { double duration = duration_round((g_opt_flags & OPT_SAMPLE_COUNT) ? 1.0 : sdi->time_delta); double diff = FLOAT_CMP(duration, 0.0) ? 0.0 : ((double)sdi->delta_events - average) / duration; diff = diff * diff; sum += diff; } } sum = sum / (double)count; (void)fprintf(fp, ",%f", sqrt(sum)); } (void)fprintf(fp, "\n"); } free(sorted_timer_infos); (void)fclose(fp); } /* * timer_info_find() * try to find existing timer info in cache, and to the cache * if it is new. */ static HOT timer_info_t *timer_info_find( const timer_info_t *new_info, const char *ident, const double time_now, const double duration) { timer_info_t *info; const uint32_t h = hash_djb2a(ident); for (info = g_timer_info_hash[h]; info; info = info->hash_next) { if (UNLIKELY(strcmp(ident, info->ident) == 0)) { info->prev_used = info->last_used; info->last_used = time_now; return info; } } info = calloc(1, sizeof(*info)); if (UNLIKELY(!info)) err_abort("Cannot allocate timer info\n"); info->pid = new_info->pid; info->task = strdup(new_info->task); info->task_mangled = strdup(new_info->task_mangled); info->cmdline = strdup(new_info->cmdline); info->func = strdup(new_info->func); info->ident = strdup(ident); info->kernel_thread = new_info->kernel_thread; info->total_events = new_info->total_events; info->delta_events = new_info->delta_events; info->time_total = new_info->time_total; info->timer = new_info->timer; info->ref_count = 0; info->prev_used = time_now - duration; /* Fake previous time */ info->last_used = time_now; info->total_events = 1; info->delta_events = 1; if (UNLIKELY(info->task == NULL || info->task_mangled == NULL || info->cmdline == NULL || info->func == NULL || info->ident == NULL)) { err_abort("Out of memory allocating a timer stat fields\n"); } /* Does not exist in list, append it */ info->next = g_timer_info_list; g_timer_info_list = info; g_timer_info_list_length++; info->hash_next = g_timer_info_hash[h]; g_timer_info_hash[h] = info; return info; } /* * timer_info_free() * free up timer_info */ static void timer_info_free(void *data) { timer_info_t *info = (timer_info_t*)data; free(info->task); if (info->cmdline != info->task_mangled) free(info->cmdline); free(info->task_mangled); free(info->func); free(info->ident); free(info); } /* * timer_info_purge_old_from_timer_list() * remove old timer info from the timer list */ static void timer_info_purge_old_from_timer_list( timer_info_t **list, const double time_now) { timer_info_t *prev = NULL, *info = *list; while (info) { timer_info_t *next = info->next; /* * Only remove from list once all timer * stats no longer reference it */ if ((info->ref_count == 0) && (info->last_used + TIMER_REAP_AGE < time_now)) { if (prev == NULL) *list = next; else prev->next = next; g_timer_info_list_length--; } else { prev = info; } info = next; } } /* * timer_info_purge_old_from_hash_list() * remove old timer info from a hash list */ static void timer_info_purge_old_from_hash_list( timer_info_t **list, const double time_now) { timer_info_t *prev = NULL, *info = *list; while (info) { timer_info_t *next = info->hash_next; /* * Only remove and free once all timer stats no * longer reference it */ if ((info->ref_count == 0) && (info->last_used + TIMER_REAP_AGE < time_now)) { if (prev == NULL) *list = next; else prev->hash_next = next; timer_info_free(info); } else { prev = info; } info = next; } } /* * timer_info_purge_old() * clean out old timer infos */ static inline void timer_info_purge_old(const double time_now) { static uint16_t count = 0; count++; if (count > TIMER_REAP_THRESHOLD) { size_t i; count = 0; timer_info_purge_old_from_timer_list(&g_timer_info_list, time_now); for (i = 0; i < TABLE_SIZE; i++) timer_info_purge_old_from_hash_list(&g_timer_info_hash[i], time_now); } } /* * timer_info_list_free() * free up all unique timer infos */ static inline void timer_info_list_free(void) { timer_info_t *info = g_timer_info_list; /* Free list and timers on list */ while (info) { timer_info_t *next = info->next; timer_info_free(info); info = next; } } /* * make_hash_ident() */ static char *make_hash_ident(const timer_info_t *info) { static char ident[128]; if (g_opt_flags & OPT_TIMER_ID) { (void)snprintf(ident, sizeof(ident), "%x%s%8.8s%" PRIx64, info->pid, info->task, info->func, info->timer); } else { (void)snprintf(ident, sizeof(ident), "%x%s%8.8s", info->pid, info->task, info->func); } return ident; } /* * timer_stat_free_list_free() * free up the timer stat free list */ static void timer_stat_free_list_free(void) { timer_stat_t *ts = g_timer_stat_free_list; while (ts) { timer_stat_t *next = ts->next; free(ts); ts = next; } g_timer_stat_free_list = NULL; } /* * timer_stat_free_contents() * Free timers from a hash table */ static void timer_stat_free_contents(timer_stat_t *timer_stats[]) { size_t i; for (i = 0; i < TABLE_SIZE; i++) { timer_stat_t *ts = timer_stats[i]; while (ts) { timer_stat_t *next = ts->next; /* Decrement info ref count */ ts->info->ref_count--; /* Add it onto the timer stat free list */ ts->next = g_timer_stat_free_list; g_timer_stat_free_list = ts; ts = next; } timer_stats[i] = NULL; } } /* * timer_stat_add() * add timer stats to a hash table if it is new, otherwise just * accumulate the event count. */ static void timer_stat_add( timer_stat_t *timer_stats[], /* timer stat hash table */ timer_info_t *info, /* timer info to be added */ const double time_now, /* time sample was taken */ const double duration) /* duration of a sample */ { const char *ident = make_hash_ident(info); const uint32_t h = hash_djb2a(ident); timer_stat_t *ts, *ts_new; for (ts = timer_stats[h]; ts; ts = ts->next) { if (UNLIKELY(strcmp(ts->info->ident, ident) == 0)) { ts->info->total_events++; ts->info->delta_events++; sample_add(ts, time_now); return; } } /* Not found, it is new */ if (g_timer_stat_free_list) { /* Get new one from free list */ ts_new = g_timer_stat_free_list; g_timer_stat_free_list = g_timer_stat_free_list->next; } else { /* Get one from heap */ if ((ts_new = malloc(sizeof(*ts_new))) == NULL) err_abort("Out of memory allocating a timer stat\n"); } ts_new->info = timer_info_find(info, ident, time_now, duration); ts_new->info->ref_count++; ts_new->next = timer_stats[h]; ts_new->sorted_freq_next = NULL; timer_stats[h] = ts_new; sample_add(ts_new, time_now); } /* * timer_stat_sort_freq_add() * add a timer stat to a sorted list of timer stats */ static void timer_stat_sort_freq_add( timer_stat_t **sorted, /* timer stat sorted list */ timer_stat_t *new) /* timer stat to add */ { while (*sorted) { if (UNLIKELY(g_opt_flags & OPT_CUMULATIVE)) { if ((*sorted)->info->total_events < new->info->total_events) { new->sorted_freq_next = *(sorted); break; } } else { if ((*sorted)->info->delta_events < new->info->delta_events) { new->sorted_freq_next = *(sorted); break; } } sorted = &(*sorted)->sorted_freq_next; } *sorted = new; } /* * es_printf() * eventstat printf - print to stdout or ncurses * print depending on the mode */ static void es_printf(const char *fmt, ...) { va_list ap; va_start(ap, fmt); if (g_curses_init) { char buf[256]; (void)vsnprintf(buf, sizeof(buf), fmt, ap); (void)printw("%s", buf); } else { (void)vprintf(fmt, ap); } va_end(ap); } /* * timer_stat_dump() */ static OPTIMIZE3 void timer_stat_dump( const double duration, /* time between each sample */ const double time_delta, /* how long been running sofar */ const int32_t n_lines, /* number of lines to output */ const double whence, /* nth sample */ timer_stat_t *timer_stats[]) /* timer stats samples */ { size_t i; timer_stat_t *sorted = NULL; for (i = 0; i < TABLE_SIZE; i++) { timer_stat_t *ts; for (ts = timer_stats[i]; ts; ts = ts->next) timer_stat_sort_freq_add(&sorted, ts); } if (!(g_opt_flags & OPT_QUIET)) { uint64_t total = 0UL, kt_total = 0UL; int32_t j = 0; const int pid_size = pid_max_digits(); int cols, sz, ta_size, fn_size = 0; int min_width; eventstat_winsize(); if (UNLIKELY(g_resized && g_curses_init)) { resizeterm(g_rows, g_cols); refresh(); g_resized = false; } /* Minimum width w/o task or func info */ min_width = EVENTS_WIDTH + 1 + \ 1 + \ pid_size + 1; if (!(g_opt_flags & OPT_BRIEF)) { if (g_opt_flags & OPT_TIMER_ID) min_width += TIMER_ID_WIDTH + 1; fn_size = FUNC_WIDTH; } if (!(g_opt_flags & OPT_CMD_LONG) && g_cols > 80) cols = 80; else cols = g_cols; sz = cols - min_width; sz = (sz < 0) ? 0 : sz; if (fn_size) { fn_size += (sz >> 1); if (fn_size > FUNC_WIDTH_MAX) fn_size = FUNC_WIDTH_MAX; min_width += fn_size; sz = cols - min_width; sz = (sz < 0) ? 0 : sz; } ta_size = sz; if (ta_size < TASK_WIDTH) ta_size = TASK_WIDTH; es_printf("%*.*s %-*.*s %-*.*s", EVENTS_WIDTH, EVENTS_WIDTH, (g_opt_flags & OPT_CUMULATIVE) ? "Events" : "Event/s", pid_size, pid_size, "PID", ta_size, ta_size, "Task"); if (!(g_opt_flags & OPT_BRIEF)) { if (g_opt_flags & OPT_TIMER_ID) { es_printf(" %-16.16s", "Timer ID"); } es_printf("%-*.*s\n", fn_size, fn_size, " Init Function"); } else { es_printf("\n"); } while (sorted) { if (((n_lines == -1) || (j < n_lines)) && (sorted->info->delta_events != 0)) { char *task = (g_opt_flags & OPT_CMD) ? sorted->info->cmdline : sorted->info->task_mangled; if (!*task) task = sorted->info->task_mangled; j++; if (g_opt_flags & OPT_CUMULATIVE) es_printf("%*" PRIu64 " ", EVENTS_WIDTH, sorted->info->total_events); else es_printf("%*.2f ", EVENTS_WIDTH, (double)sorted->info->delta_events / duration); if (g_opt_flags & OPT_BRIEF) { es_printf("%*d %s\n", pid_size, sorted->info->pid, task); } else { es_printf("%*d %-*.*s", pid_size, sorted->info->pid, ta_size, ta_size, task); if (g_opt_flags & OPT_TIMER_ID) { es_printf(" %16" PRIx64, sorted->info->timer); } es_printf(" %-*.*s\n", fn_size - 1, fn_size - 1, sorted->info->func); } } total += sorted->info->delta_events; if (sorted->info->kernel_thread) kt_total += sorted->info->delta_events; sorted->info->delta_events = 0; sorted = sorted->sorted_freq_next; } eventstat_move(LINES - 1, 0); es_printf("%" PRIu64 " Total events, %5.2f events/sec " "(kernel: %5.2f, userspace: %5.2f)\n", total, (double)total / duration, (double)kt_total / duration, (double)(total - kt_total) / duration); if ((g_opt_flags & OPT_SHOW_WHENCE) && !g_curses_init) { time_t t = (time_t)whence; char *timestr = ctime(&t); char *pos = strchr(timestr, '\n'); if (*pos) *pos = '\0'; es_printf("Timestamp: %s, Total Run Duration: " "%.1f secs\n", timestr, time_delta); } if (!g_sane_procs) es_printf("Note: this was run inside a container, " "kernel tasks were guessed.\n"); es_printf("\n"); } } /* * read_events() * read in events data into a global read buffer. * the buffer is auto-expanded where necessary and * only free'd at exit time. This way we can parse * the data a little faster. */ static char *read_events(const double time_end) { int fd; static size_t get_events_size; size_t size; if (UNLIKELY(g_get_events_buf == NULL)) { if ((g_get_events_buf = malloc(EVENT_BUF_SIZE << 1)) == NULL) err_abort("Cannot read %s, out of memory\n", g_sys_tracing_pipe); get_events_size = (EVENT_BUF_SIZE << 1); } if ((fd = open(g_sys_tracing_pipe, O_RDONLY)) < 0) err_abort("Cannot open %s\n", g_sys_tracing_pipe); size = 0; while (!g_stop_eventstat) { ssize_t ret; int rc; static char buffer[EVENT_BUF_SIZE]; const double duration = time_end - gettime_to_double(); struct timeval tv; fd_set rfds; if (UNLIKELY(duration < 0.0)) break; tv = double_to_timeval(duration); FD_ZERO(&rfds); FD_SET(fd, &rfds); errno = 0; rc = select(fd + 1, &rfds, NULL, NULL, &tv); if (UNLIKELY(rc <= 0)) break; if (!FD_ISSET(fd, &rfds)) continue; ret = read(fd, buffer, sizeof(buffer)); if (ret == 0) continue; if (UNLIKELY(ret < 0)) { if (!g_stop_eventstat && ((errno == EINTR) || (errno != EAGAIN))) { continue; } break; } /* Do we need to expand the global buffer? */ if (size + ret >= get_events_size) { char *tmpptr; get_events_size += (EVENT_BUF_SIZE << 1); tmpptr = realloc(g_get_events_buf, get_events_size + 1); if (!tmpptr) { (void)close(fd); err_abort("Cannot read %s, out of memory\n", g_sys_tracing_pipe); } g_get_events_buf = tmpptr; } (void)memcpy(g_get_events_buf + size, buffer, ret); size += ret; *(g_get_events_buf + size) = '\0'; } (void)close(fd); return g_get_events_buf; } /* * get_events() * parse /sys/kernel/debug/tracing/trace_pipe and populate * a timer stat hash table with unique events */ static void get_events( timer_stat_t *timer_stats[], const double time_now, const double duration) { const size_t app_name_len = strlen(g_app_name); const double time_end = time_now + duration - 0.05; char *tmpptr = read_events(time_end); if (!tmpptr) return; while (*tmpptr) { char *ptr, *eol = tmpptr; char task[64]; char task_mangled[64]; char func[64]; char *cmdline; int mask; timer_info_t info; /* Find the end of a line */ while (*eol) { if (UNLIKELY(*eol == '\n')) { *eol = '\0'; eol++; break; } eol++; } if (strstr(tmpptr, "hrtimer_start")) { (void)memset(&info, 0, sizeof(info)); (void)memset(task, 0, sizeof(task)); (void)memset(func, 0, sizeof(func)); /* * Parse something like the following: * gnome-shell-3515 [003] d.h. 101499.108349: hrtimer_start: hrtimer=ffff99979e2d4600 function=tick_sched_timer expires=101497144000000 softexpires=101497144000000 */ if (sscanf(tmpptr, "%s %*s %*s %*f: hrtimer_start: hrtimer=%" PRIx64 " function=%s", task, &info.timer, func) != 3) goto next; } else { goto next; } /* * task name in form: gnome-shell-3515, scan to end of * string, then scan back to find start of PID */ ptr = task; while (*ptr) ptr++; ptr--; while (ptr >= task && (*ptr >= '0' && *ptr <= '9')) ptr--; *ptr = '\0'; ptr++; if (sscanf(ptr, "%10d\n", &info.pid) != 1) goto next; if (UNLIKELY(info.pid == 0)) goto next; /* Processes without a command line are kernel threads */ cmdline = get_pid_cmdline(info.pid); info.kernel_thread = pid_a_kernel_thread(task, info.pid); /* Swapper is special, like all corner cases */ if (UNLIKELY(strncmp(task, "swapper", 6) == 0)) info.kernel_thread = true; mask = info.kernel_thread ? OPT_KERNEL : OPT_USER; if (!(g_opt_flags & mask)) goto free_next; if (info.kernel_thread) { char tmp[sizeof(task)]; (void)strcpy(tmp, task); tmp[13] = '\0'; (void)snprintf(task_mangled, sizeof(task_mangled), "[%s]", tmp); } else { (void)strcpy(task_mangled, task); } if (strncmp(task, g_app_name, app_name_len)) { info.task = task; info.cmdline = cmdline ? cmdline : task_mangled; info.task_mangled = task_mangled; info.func = func; info.time_total = 0.0; info.total_events = 1; info.ident = make_hash_ident(&info); timer_stat_add(timer_stats, &info, time_now, duration); } free_next: free(cmdline); next: tmpptr = eol; } } /* * show_usage() * show how to use */ static void show_usage(void) { (void)printf("%s, version %s\n\n", g_app_name, VERSION); (void)printf("Usage: %s [options] [duration] [count]\n", g_app_name); (void)printf("Options are:\n" " -c\t\treport cumulative events rather than events per second.\n" " -C\t\treport event count rather than event per second in CSV output.\n" " -d\t\tremove pathname from long process name in CSV output.\n" " -h\t\tprint this help.\n" " -l\t\tuse long cmdline text from /proc/pid/cmdline for process name.\n" " -n events\tspecifies number of events to display.\n" " -q\t\trun quietly, useful with option -r.\n" " -r filename\tspecifies a comma separated values (CSV) output file\n" "\t\tto dump samples into.\n" " -s\t\tuse short process name from /proc/pid/cmdline for process name.\n" " -S\t\tcalculate min, max, average and standard deviation in CSV\n" "\t\toutput.\n" " -t threshold\tsamples less than the specified threshold are ignored.\n" " -T\t\tenable \'top\' mode rather than a scrolling output.\n" " -w\t\tadd time stamp (when events occurred) to output.\n"); } /* * handle_sigwinch() * flag window resize on SIGWINCH */ static void handle_sigwinch(int sig) { (void)sig; eventstat_winsize(); g_resized = true; } int main(int argc, char **argv) { timer_stat_t **timer_stats; double duration_secs = 1.0, time_start, time_now; int64_t count = 1, t = 1; int32_t n_lines = -1; bool forever = true; bool redo = false; struct sigaction new_action; size_t i; for (;;) { int c = getopt(argc, argv, "bcCdksSlhin:qr:t:Tuw"); if (c == -1) break; switch (c) { case 'b': g_opt_flags |= OPT_BRIEF; break; case 'c': g_opt_flags |= OPT_CUMULATIVE; break; case 'C': g_opt_flags |= OPT_SAMPLE_COUNT; break; case 'd': g_opt_flags |= OPT_DIRNAME_STRIP; break; case 'h': show_usage(); eventstat_exit(EXIT_SUCCESS); case 'i': g_opt_flags |= OPT_TIMER_ID; break; case 'n': errno = 0; n_lines = (int32_t)strtol(optarg, NULL, 10); if (errno) err_abort("Invalid value for number " "of events to display\n"); if (n_lines < 1) err_abort("-n option must be greater than 0\n"); break; case 'S': g_opt_flags |= OPT_RESULT_STATS; break; case 't': g_opt_threshold = strtoull(optarg, NULL, 10); if (g_opt_threshold < 1) err_abort("-t threshold must be 1 or more.\n"); break; case 'T': g_opt_flags |= OPT_TOP; break; case 'q': g_opt_flags |= OPT_QUIET; break; case 'r': g_csv_results = optarg; break; case 's': g_opt_flags |= OPT_CMD_SHORT; break; case 'l': g_opt_flags |= OPT_CMD_LONG; break; case 'k': g_opt_flags |= OPT_KERNEL; break; case 'u': g_opt_flags |= OPT_USER; break; case 'w': g_opt_flags |= OPT_SHOW_WHENCE; break; default: show_usage(); eventstat_exit(EXIT_FAILURE); } } if (!(g_opt_flags & (OPT_KERNEL | OPT_USER))) g_opt_flags |= (OPT_KERNEL | OPT_USER); if (optind < argc) { duration_secs = atof(argv[optind++]); if (duration_secs < 0.5) err_abort("Duration must 0.5 or more.\n"); } if (optind < argc) { forever = false; errno = 0; count = (int64_t)strtoll(argv[optind++], NULL, 10); if (errno) err_abort("Invalid count value\n"); if (count < 1) err_abort("Count must be > 0\n"); } g_opt_threshold *= duration_secs; if (geteuid() != 0) err_abort("%s requires root privileges to gather " "trace event data\n", g_app_name); g_sane_procs = sane_proc_pid_info(); if (!g_sane_procs) g_opt_flags &= ~(OPT_CMD_SHORT | OPT_CMD_LONG); (void)memset(&new_action, 0, sizeof(new_action)); for (i = 0; i < SIZEOF_ARRAY(g_signals); i++) { new_action.sa_handler = handle_sig; (void)sigemptyset(&new_action.sa_mask); new_action.sa_flags = 0; if (sigaction(g_signals[i], &new_action, NULL) < 0) err_abort("sigaction failed: errno=%d (%s)\n", errno, strerror(errno)); } if ((timer_stats = calloc(TABLE_SIZE, sizeof(*timer_stats))) == NULL) err_abort("Cannot allocate timer stats table\n"); /* Should really catch signals and set back to zero before we die */ set_tracing_enable("1\n", true); set_tracing_event(); time_now = time_start = gettime_to_double(); if (g_opt_flags & OPT_TOP) { struct sigaction sa; (void)memset(&sa, 0, sizeof(sa)); sa.sa_handler = handle_sigwinch; if (sigaction(SIGWINCH, &sa, NULL) < 0) err_abort("sigaction failed: errno=%d (%s)\n", errno, strerror(errno)); initscr(); cbreak(); noecho(); nodelay(stdscr, 1); keypad(stdscr, 1); curs_set(0); g_curses_init = true; } while (!g_stop_eventstat && (forever || count--)) { double secs, duration, time_delta; /* Timeout to wait for in the future for this sample */ secs = time_start + ((double)t * duration_secs) - time_now; /* Play catch-up, probably been asleep */ if (secs < 0.0) { t = ceil((time_now - time_start) / duration_secs); secs = time_start + ((double)t * duration_secs) - time_now; /* Really, it's impossible, but just in case.. */ if (secs < 0.0) secs = 0.0; } else { if (!redo) t++; } redo = false; if (g_curses_init) { fd_set rfds; int ch, ret; struct timeval tv; (void)memset(&tv, 0, sizeof(tv)); FD_ZERO(&rfds); FD_SET(fileno(stdin), &rfds); ret = select(fileno(stdin) + 1, &rfds, NULL, NULL, &tv); ch = getch(); if ((ch == 27) || (ch == 'q')) break; if (ret > 0) redo = true; if (ret < 0) { if (errno != EINTR) { eventstat_endwin(); (void)fprintf(stderr, "select() failed: " "errno=%d (%s)\n", errno, strerror(errno)); goto abort; } redo = true; } } get_events(timer_stats, time_now, secs); duration = gettime_to_double() - time_now; duration = floor((duration * 1000.0) + 0.5) / 1000.0; time_now = gettime_to_double(); time_delta = time_now - time_start; eventstat_clear(); timer_stat_dump(duration, time_delta, n_lines, time_now, timer_stats); eventstat_refresh(); timer_stat_free_contents(timer_stats); timer_info_purge_old(time_now); } eventstat_endwin(); abort: samples_dump(g_csv_results); timer_stat_free_contents(timer_stats); free(timer_stats); samples_free(); timer_info_list_free(); timer_stat_free_list_free(); free(g_get_events_buf); eventstat_exit(EXIT_SUCCESS); } eventstat-0.04.03/snapcraft/0000755000175000017500000000000013234563554014330 5ustar kingkingeventstat-0.04.03/snapcraft/snapcraft.yaml0000644000175000017500000000124513234563554017177 0ustar kingkingname: eventstat version: 0.03.04-20170425-264-0910972 summary: kernel event states monitoring tool description: Eventstat periodically dumps out the current kernel event state. It keeps track of current events and outputs the change in events on each output update. The tool requires sudo to run since it needs to write to /proc/timer_stats to start and stop the event monitoring. confinement: strict type: app grade: stable parts: eventstat: plugin: make source: git://kernel.ubuntu.com/cking/eventstat build-packages: - gcc - make - libncurses5-dev apps: eventstat: command: usr/bin/eventstat eventstat-0.04.03/snapcraft/Makefile0000644000175000017500000000110513234563554015765 0ustar kingkingVERSION=$(shell git tag | tail -1 | cut -c2-) COMMITS=$(shell git log --oneline | wc -l) SHA=$(shell git log -1 --oneline | cut -d' ' -f1) DATE=$(shell date +'%Y%m%d') V=$(VERSION)-$(DATE)-$(COMMITS)-$(SHA) all: set_version LC_ALL=C.UTF-8 LANG=C.UTF-8 snapcraft set_version: cat snapcraft.yaml | sed 's/version: .*/version: $(V)/' > snapcraft-tmp.yaml mv snapcraft-tmp.yaml snapcraft.yaml clean: rm -rf setup *.snap LC_ALL=C.UTF-8 LANG=C.UTF-8 snapcraft clean cat snapcraft.yaml | sed 's/version: .*/version: 0/' > snapcraft-tmp.yaml mv snapcraft-tmp.yaml snapcraft.yaml eventstat-0.04.03/COPYING0000644000175000017500000004325413234563554013412 0ustar kingking GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License.