2 * block queue tracing application
4 * Copyright (C) 2005 Jens Axboe <axboe@suse.de>
5 * Copyright (C) 2006 Jens Axboe <axboe@kernel.dk>
7 * Rewrite to have a single thread per CPU (managing all devices on that CPU)
8 * Alan D. Brunelle <alan.brunelle@hp.com> - January 2009
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software
22 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
39 #include <sys/ioctl.h>
40 #include <sys/types.h>
44 #include <sys/param.h>
46 #include <sys/resource.h>
47 #include <sys/socket.h>
48 #include <netinet/in.h>
49 #include <arpa/inet.h>
51 #include <sys/sendfile.h>
57 * You may want to increase this even more, if you are logging at a high
58 * rate and see skipped/missed events
60 #define BUF_SIZE (512 * 1024)
63 #define FILE_VBUF_SIZE (128 * 1024)
65 #define DEBUGFS_TYPE (0x64626720)
66 #define TRACE_NET_PORT (8462)
81 * Generic stats collected: nevents can be _roughly_ estimated by data_read
82 * (discounting pdu...)
84 * These fields are updated w/ pdc_dr_update & pdc_nev_update below.
87 unsigned long long data_read;
88 unsigned long long nevents;
92 struct list_head head;
93 char *path; /* path to device special file */
94 char *buts_name; /* name returned from bt kernel code */
95 struct pdc_stats *stats;
97 unsigned long long drops;
100 * For piped output only:
102 * Each tracer will have a tracer_devpath_head that it will add new
103 * data onto. It's list is protected above (tracer_devpath_head.mutex)
104 * and it will signal the processing thread using the dp_cond,
105 * dp_mutex & dp_entries variables above.
107 struct tracer_devpath_head *heads;
110 * For network server mode only:
114 time_t cl_connect_time;
119 * For piped output to stdout we will have each tracer thread (one per dev)
120 * tack buffers read from the relay queues on a per-device list.
122 * The main thread will then collect trace buffers from each of lists in turn.
124 * We will use a mutex to guard each of the trace_buf list. The tracers
125 * can then signal the main thread using <dp_cond,dp_mutex> and
126 * dp_entries. (When dp_entries is 0, and a tracer adds an entry it will
127 * signal. When dp_entries is 0, the main thread will wait for that condition
130 * adb: It may be better just to have a large buffer per tracer per dev,
131 * and then use it as a ring-buffer. This would certainly cut down a lot
132 * of malloc/free thrashing, at the cost of more memory movements (potentially).
135 struct list_head head;
141 struct tracer_devpath_head {
142 pthread_mutex_t mutex;
143 struct list_head head;
144 struct trace_buf *prev;
148 * Used to handle the mmap() interfaces for output file (containing traces)
152 unsigned long long fs_size, fs_max_size, fs_off, fs_buf_len;
153 unsigned long buf_size, buf_nr;
158 * Each thread doing work on a (client) side of blktrace will have one
159 * of these. The ios array contains input/output information, pfds holds
160 * poll() data. The volatile's provide flags to/from the main executing
164 struct list_head head;
169 volatile int status, is_done;
173 * networking stuff follows. we include a magic number so we know whether
174 * to endianness convert or not.
176 * The len field is overloaded:
177 * 0 - Indicates an "open" - allowing the server to set up for a dev/cpu
178 * 1 - Indicates a "close" - Shut down connection orderly
180 * The cpu field is overloaded on close: it will contain the number of drops.
182 struct blktrace_net_hdr {
183 u32 magic; /* same as trace magic */
184 char buts_name[32]; /* trace name */
185 u32 cpu; /* for which cpu */
187 u32 len; /* length of following trace data */
188 u32 cl_id; /* id for set of client per-cpu connections */
189 u32 buf_size; /* client buf_size for this trace */
190 u32 buf_nr; /* client buf_nr for this trace */
191 u32 page_size; /* client page_size for this trace */
195 * Each host encountered has one of these. The head is used to link this
196 * on to the network server's ch_list. Connections associated with this
197 * host are linked on conn_list, and any devices traced on that host
198 * are connected on the devpaths list.
201 struct list_head head;
202 struct list_head conn_list;
203 struct list_head devpaths;
204 struct net_server_s *ns;
206 struct in_addr cl_in_addr;
207 int connects, ndevs, cl_opens;
211 * Each connection (client to server socket ('fd')) has one of these. A
212 * back reference to the host ('ch'), and lists headers (for the host
213 * list, and the network server conn_list) are also included.
216 struct list_head ch_head, ns_head;
223 * The network server requires some poll structures to be maintained -
224 * one per conection currently on conn_list. The nchs/ch_list values
225 * are for each host connected to this server. The addr field is used
226 * for scratch as new connections are established.
228 struct net_server_s {
229 struct list_head conn_list;
230 struct list_head ch_list;
232 int listen_fd, connects, nchs;
233 struct sockaddr_in addr;
237 * This structure is (generically) used to providide information
238 * for a read-to-write set of values.
240 * ifn & ifd represent input information
242 * ofn, ofd, ofp, obuf & mmap_info are used for output file (optionally).
248 struct cl_conn *nc; /* Server network connection */
251 * mmap controlled output files
253 struct mmap_info mmap_info;
256 * Client network fields
259 unsigned long long data_queued;
262 * Input/output file descriptors & names
265 char ifn[MAXPATHLEN + 64];
266 char ofn[MAXPATHLEN + 64];
269 static char blktrace_version[] = "2.0.0";
272 * Linkage to blktrace helper routines (trace conversions)
274 int data_is_native = -1;
279 static cpu_set_t *online_cpus;
281 static int act_mask = ~0U;
282 static int kill_running_trace;
283 static int stop_watch;
284 static int piped_output;
286 static char *debugfs_path = "/sys/kernel/debug";
287 static char *output_name;
288 static char *output_dir;
290 static unsigned long buf_size = BUF_SIZE;
291 static unsigned long buf_nr = BUF_NR;
295 static LIST_HEAD(devpaths);
296 static LIST_HEAD(tracers);
298 static volatile int done;
301 * tracer threads add entries, the main thread takes them off and processes
302 * them. These protect the dp_entries variable.
304 static pthread_cond_t dp_cond = PTHREAD_COND_INITIALIZER;
305 static pthread_mutex_t dp_mutex = PTHREAD_MUTEX_INITIALIZER;
306 static volatile int dp_entries;
309 * These synchronize master / thread interactions.
311 static pthread_cond_t mt_cond = PTHREAD_COND_INITIALIZER;
312 static pthread_mutex_t mt_mutex = PTHREAD_MUTEX_INITIALIZER;
313 static volatile int nthreads_running;
314 static volatile int nthreads_leaving;
315 static volatile int nthreads_error;
316 static volatile int tracers_run;
319 * network cmd line params
321 static struct sockaddr_in hostname_addr;
322 static char hostname[MAXHOSTNAMELEN];
323 static int net_port = TRACE_NET_PORT;
324 static int net_use_sendfile = 1;
328 static int (*handle_pfds)(struct tracer *, int, int);
329 static int (*handle_list)(struct tracer_devpath_head *, struct list_head *);
331 #define S_OPTS "d:a:A:r:o:kw:vVb:n:D:lh:p:sI:"
332 static struct option l_opts[] = {
335 .has_arg = required_argument,
340 .name = "input-devs",
341 .has_arg = required_argument,
347 .has_arg = required_argument,
353 .has_arg = required_argument,
359 .has_arg = required_argument,
365 .has_arg = required_argument,
371 .has_arg = no_argument,
377 .has_arg = required_argument,
383 .has_arg = no_argument,
389 .has_arg = no_argument,
394 .name = "buffer-size",
395 .has_arg = required_argument,
400 .name = "num-sub-buffers",
401 .has_arg = required_argument,
406 .name = "output-dir",
407 .has_arg = required_argument,
413 .has_arg = no_argument,
419 .has_arg = required_argument,
425 .has_arg = required_argument,
430 .name = "no-sendfile",
431 .has_arg = no_argument,
440 static char usage_str[] = "\n\n" \
441 "-d <dev> | --dev=<dev>\n" \
442 "[ -r <debugfs path> | --relay=<debugfs path> ]\n" \
443 "[ -o <file> | --output=<file>]\n" \
444 "[ -D <dir> | --output-dir=<dir>\n" \
445 "[ -w <time> | --stopwatch=<time>]\n" \
446 "[ -a <action field> | --act-mask=<action field>]\n" \
447 "[ -A <action mask> | --set-mask=<action mask>]\n" \
448 "[ -b <size> | --buffer-size]\n" \
449 "[ -n <number> | --num-sub-buffers=<number>]\n" \
450 "[ -l | --listen]\n" \
451 "[ -h <hostname> | --host=<hostname>]\n" \
452 "[ -p <port number> | --port=<port number>]\n" \
453 "[ -s | --no-sendfile]\n" \
454 "[ -I <devs file> | --input-devs=<devs file>]\n" \
455 "[ -v <version> | --version]\n" \
456 "[ -V <version> | --version]\n" \
458 "\t-d Use specified device. May also be given last after options\n" \
459 "\t-r Path to mounted debugfs, defaults to /sys/kernel/debug\n" \
460 "\t-o File(s) to send output to\n" \
461 "\t-D Directory to prepend to output file names\n" \
462 "\t-w Stop after defined time, in seconds\n" \
463 "\t-a Only trace specified actions. See documentation\n" \
464 "\t-A Give trace mask as a single value. See documentation\n" \
465 "\t-b Sub buffer size in KiB (default 512)\n" \
466 "\t-n Number of sub buffers (default 4)\n" \
467 "\t-l Run in network listen mode (blktrace server)\n" \
468 "\t-h Run in network client mode, connecting to the given host\n" \
469 "\t-p Network port to use (default 8462)\n" \
470 "\t-s Make the network client NOT use sendfile() to transfer data\n" \
471 "\t-I Add devices found in <devs file>\n" \
472 "\t-v Print program version info\n" \
473 "\t-V Print program version info\n\n";
475 static void clear_events(struct pollfd *pfd)
481 static inline int net_client_use_sendfile(void)
483 return net_mode == Net_client && net_use_sendfile;
486 static inline int net_client_use_send(void)
488 return net_mode == Net_client && !net_use_sendfile;
491 static inline int use_tracer_devpaths(void)
493 return piped_output || net_client_use_send();
496 static inline int in_addr_eq(struct in_addr a, struct in_addr b)
498 return a.s_addr == b.s_addr;
501 static inline void pdc_dr_update(struct devpath *dpp, int cpu, int data_read)
503 dpp->stats[cpu].data_read += data_read;
506 static inline void pdc_nev_update(struct devpath *dpp, int cpu, int nevents)
508 dpp->stats[cpu].nevents += nevents;
511 static void show_usage(char *prog)
513 fprintf(stderr, "Usage: %s %s", prog, usage_str);
517 * Create a timespec 'msec' milliseconds into the future
519 static inline void make_timespec(struct timespec *tsp, long delta_msec)
523 gettimeofday(&now, NULL);
524 tsp->tv_sec = now.tv_sec;
525 tsp->tv_nsec = 1000L * now.tv_usec;
527 tsp->tv_nsec += (delta_msec * 1000000L);
528 if (tsp->tv_nsec > 1000000000L) {
529 long secs = tsp->tv_nsec / 1000000000L;
532 tsp->tv_nsec -= (secs * 1000000000L);
537 * Add a timer to ensure wait ends
539 static void t_pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
543 make_timespec(&ts, 50);
544 pthread_cond_timedwait(cond, mutex, &ts);
547 static void unblock_tracers(void)
549 pthread_mutex_lock(&mt_mutex);
551 pthread_cond_broadcast(&mt_cond);
552 pthread_mutex_unlock(&mt_mutex);
555 static void tracer_wait_unblock(struct tracer *tp)
557 pthread_mutex_lock(&mt_mutex);
558 while (!tp->is_done && !tracers_run)
559 pthread_cond_wait(&mt_cond, &mt_mutex);
560 pthread_mutex_unlock(&mt_mutex);
563 static void tracer_signal_ready(struct tracer *tp,
564 enum thread_status th_status,
567 pthread_mutex_lock(&mt_mutex);
570 if (th_status == Th_running)
572 else if (th_status == Th_error)
577 pthread_cond_signal(&mt_cond);
578 pthread_mutex_unlock(&mt_mutex);
581 static void wait_tracers_ready(int ncpus_started)
583 pthread_mutex_lock(&mt_mutex);
584 while ((nthreads_running + nthreads_error) < ncpus_started)
585 t_pthread_cond_wait(&mt_cond, &mt_mutex);
586 pthread_mutex_unlock(&mt_mutex);
589 static void wait_tracers_leaving(void)
591 pthread_mutex_lock(&mt_mutex);
592 while (nthreads_leaving < nthreads_running)
593 t_pthread_cond_wait(&mt_cond, &mt_mutex);
594 pthread_mutex_unlock(&mt_mutex);
597 static void init_mmap_info(struct mmap_info *mip)
599 mip->buf_size = buf_size;
600 mip->buf_nr = buf_nr;
601 mip->pagesize = pagesize;
604 static void net_close_connection(int *fd)
606 shutdown(*fd, SHUT_RDWR);
611 static void dpp_free(struct devpath *dpp)
620 free(dpp->buts_name);
624 static int lock_on_cpu(int cpu)
626 cpu_set_t * cpu_mask;
629 cpu_mask = CPU_ALLOC(max_cpus);
630 size = CPU_ALLOC_SIZE(max_cpus);
632 CPU_ZERO_S(size, cpu_mask);
633 CPU_SET_S(cpu, size, cpu_mask);
634 if (sched_setaffinity(0, size, cpu_mask) < 0) {
643 static int increase_limit(int resource, rlim_t increase)
646 int save_errno = errno;
648 if (!getrlimit(resource, &rlim)) {
649 rlim.rlim_cur += increase;
650 if (rlim.rlim_cur >= rlim.rlim_max)
651 rlim.rlim_max = rlim.rlim_cur + increase;
653 if (!setrlimit(resource, &rlim))
661 static int handle_open_failure(void)
663 if (errno == ENFILE || errno == EMFILE)
664 return increase_limit(RLIMIT_NOFILE, 16);
668 static int handle_mem_failure(size_t length)
671 return handle_open_failure();
672 else if (errno == ENOMEM)
673 return increase_limit(RLIMIT_MEMLOCK, 2 * length);
677 static FILE *my_fopen(const char *path, const char *mode)
682 fp = fopen(path, mode);
683 } while (fp == NULL && handle_open_failure());
688 static int my_open(const char *path, int flags)
693 fd = open(path, flags);
694 } while (fd < 0 && handle_open_failure());
699 static int my_socket(int domain, int type, int protocol)
704 fd = socket(domain, type, protocol);
705 } while (fd < 0 && handle_open_failure());
710 static int my_accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen)
715 fd = accept(sockfd, addr, addrlen);
716 } while (fd < 0 && handle_open_failure());
721 static void *my_mmap(void *addr, size_t length, int prot, int flags, int fd,
727 new = mmap(addr, length, prot, flags, fd, offset);
728 } while (new == MAP_FAILED && handle_mem_failure(length));
733 static int my_mlock(struct tracer *tp,
734 const void *addr, size_t len)
739 ret = mlock(addr, len);
740 if ((retry >= 10) && tp && tp->is_done)
743 } while (ret < 0 && handle_mem_failure(len));
748 static int setup_mmap(int fd, unsigned int maxlen,
749 struct mmap_info *mip,
752 if (mip->fs_off + maxlen > mip->fs_buf_len) {
753 unsigned long nr = max(16, mip->buf_nr);
756 munlock(mip->fs_buf, mip->fs_buf_len);
757 munmap(mip->fs_buf, mip->fs_buf_len);
761 mip->fs_off = mip->fs_size & (mip->pagesize - 1);
762 mip->fs_buf_len = (nr * mip->buf_size) - mip->fs_off;
763 mip->fs_max_size += mip->fs_buf_len;
765 if (ftruncate(fd, mip->fs_max_size) < 0) {
766 perror("setup_mmap: ftruncate");
770 mip->fs_buf = my_mmap(NULL, mip->fs_buf_len, PROT_WRITE,
772 mip->fs_size - mip->fs_off);
773 if (mip->fs_buf == MAP_FAILED) {
774 perror("setup_mmap: mmap");
777 if (my_mlock(tp, mip->fs_buf, mip->fs_buf_len) < 0) {
778 perror("setup_mlock: mlock");
786 static int __stop_trace(int fd)
789 * Should be stopped, don't complain if it isn't
791 ioctl(fd, BLKTRACESTOP);
792 return ioctl(fd, BLKTRACETEARDOWN);
795 static int write_data(char *buf, int len)
800 ret = fwrite(buf, len, 1, pfp);
801 if (ferror(pfp) || ret != 1) {
802 if (errno == EINTR) {
807 if (!piped_output || (errno != EPIPE && errno != EBADF)) {
808 fprintf(stderr, "write(%d) failed: %d/%s\n",
809 len, errno, strerror(errno));
823 * Returns the number of bytes read (successfully)
825 static int __net_recv_data(int fd, void *buf, unsigned int len)
827 unsigned int bytes_left = len;
829 while (bytes_left && !done) {
830 int ret = recv(fd, buf, bytes_left, MSG_WAITALL);
835 if (errno == EAGAIN) {
839 perror("server: net_recv_data: recv failed");
847 return len - bytes_left;
850 static int net_recv_data(int fd, void *buf, unsigned int len)
852 return __net_recv_data(fd, buf, len);
856 * Returns number of bytes written
858 static int net_send_data(int fd, void *buf, unsigned int buf_len)
861 unsigned int bytes_left = buf_len;
864 ret = send(fd, buf, bytes_left, 0);
874 return buf_len - bytes_left;
877 static int net_send_header(int fd, int cpu, char *buts_name, int len)
879 struct blktrace_net_hdr hdr;
881 memset(&hdr, 0, sizeof(hdr));
883 hdr.magic = BLK_IO_TRACE_MAGIC;
884 memset(hdr.buts_name, 0, sizeof(hdr.buts_name));
885 strncpy(hdr.buts_name, buts_name, sizeof(hdr.buts_name));
886 hdr.buts_name[sizeof(hdr.buts_name) - 1] = '\0';
888 hdr.max_cpus = max_cpus;
890 hdr.cl_id = getpid();
891 hdr.buf_size = buf_size;
893 hdr.page_size = pagesize;
895 return net_send_data(fd, &hdr, sizeof(hdr)) != sizeof(hdr);
898 static void net_send_open_close(int fd, int cpu, char *buts_name, int len)
900 struct blktrace_net_hdr ret_hdr;
902 net_send_header(fd, cpu, buts_name, len);
903 net_recv_data(fd, &ret_hdr, sizeof(ret_hdr));
906 static void net_send_open(int fd, int cpu, char *buts_name)
908 net_send_open_close(fd, cpu, buts_name, 0);
911 static void net_send_close(int fd, char *buts_name, int drops)
914 * Overload CPU w/ number of drops
916 * XXX: Need to clear/set done around call - done=1 (which
917 * is true here) stops reads from happening... :-(
920 net_send_open_close(fd, drops, buts_name, 1);
924 static void ack_open_close(int fd, char *buts_name)
926 net_send_header(fd, 0, buts_name, 2);
929 static void net_send_drops(int fd)
933 __list_for_each(p, &devpaths) {
934 struct devpath *dpp = list_entry(p, struct devpath, head);
936 net_send_close(fd, dpp->buts_name, dpp->drops);
946 static int net_get_header(struct cl_conn *nc, struct blktrace_net_hdr *bnh)
949 int fl = fcntl(nc->fd, F_GETFL);
951 fcntl(nc->fd, F_SETFL, fl | O_NONBLOCK);
952 bytes_read = __net_recv_data(nc->fd, bnh, sizeof(*bnh));
953 fcntl(nc->fd, F_SETFL, fl & ~O_NONBLOCK);
955 if (bytes_read == sizeof(*bnh))
957 else if (bytes_read == 0)
963 static int net_setup_addr(void)
965 struct sockaddr_in *addr = &hostname_addr;
967 memset(addr, 0, sizeof(*addr));
968 addr->sin_family = AF_INET;
969 addr->sin_port = htons(net_port);
971 if (inet_aton(hostname, &addr->sin_addr) != 1) {
972 struct hostent *hent;
974 hent = gethostbyname(hostname);
976 if (h_errno == TRY_AGAIN) {
979 } else if (h_errno == NO_RECOVERY) {
980 fprintf(stderr, "gethostbyname(%s)"
981 "non-recoverable error encountered\n",
985 * HOST_NOT_FOUND, NO_ADDRESS or NO_DATA
987 fprintf(stderr, "Host %s not found\n",
993 memcpy(&addr->sin_addr, hent->h_addr, 4);
994 memset(hostname, 0, sizeof(hostname));
995 strncpy(hostname, hent->h_name, sizeof(hostname));
996 hostname[sizeof(hostname) - 1] = '\0';
1002 static int net_setup_client(void)
1005 struct sockaddr_in *addr = &hostname_addr;
1007 fd = my_socket(AF_INET, SOCK_STREAM, 0);
1009 perror("client: socket");
1013 if (connect(fd, (struct sockaddr *)addr, sizeof(*addr)) < 0) {
1014 if (errno == ECONNREFUSED)
1016 "\nclient: Connection to %s refused, "
1017 "perhaps the server is not started?\n\n",
1020 perror("client: connect");
1029 static int open_client_connections(void)
1032 size_t alloc_size = CPU_ALLOC_SIZE(max_cpus);
1034 cl_fds = calloc(ncpus, sizeof(*cl_fds));
1035 for (cpu = 0; cpu < max_cpus; cpu++) {
1036 if (!CPU_ISSET_S(cpu, alloc_size, online_cpus))
1038 cl_fds[cpu] = net_setup_client();
1039 if (cl_fds[cpu] < 0)
1046 close(cl_fds[cpu--]);
1051 static void close_client_connections(void)
1055 size_t alloc_size = CPU_ALLOC_SIZE(max_cpus);
1057 for (cpu = 0, fdp = cl_fds; cpu < max_cpus; cpu++, fdp++) {
1058 if (!CPU_ISSET_S(cpu, alloc_size, online_cpus))
1061 net_send_drops(*fdp);
1062 net_close_connection(fdp);
1069 static int setup_buts(void)
1071 struct list_head *p;
1074 __list_for_each(p, &devpaths) {
1075 struct blk_user_trace_setup buts;
1076 struct devpath *dpp = list_entry(p, struct devpath, head);
1078 memset(&buts, 0, sizeof(buts));
1079 buts.buf_size = buf_size;
1080 buts.buf_nr = buf_nr;
1081 buts.act_mask = act_mask;
1083 if (ioctl(dpp->fd, BLKTRACESETUP, &buts) >= 0) {
1084 dpp->ncpus = max_cpus;
1085 dpp->buts_name = strdup(buts.name);
1088 dpp->stats = calloc(dpp->ncpus, sizeof(*dpp->stats));
1089 memset(dpp->stats, 0, dpp->ncpus * sizeof(*dpp->stats));
1091 fprintf(stderr, "BLKTRACESETUP(2) %s failed: %d/%s\n",
1092 dpp->path, errno, strerror(errno));
1100 static void start_buts(void)
1102 struct list_head *p;
1104 __list_for_each(p, &devpaths) {
1105 struct devpath *dpp = list_entry(p, struct devpath, head);
1107 if (ioctl(dpp->fd, BLKTRACESTART) < 0) {
1108 fprintf(stderr, "BLKTRACESTART %s failed: %d/%s\n",
1109 dpp->path, errno, strerror(errno));
1114 static int get_drops(struct devpath *dpp)
1117 char fn[MAXPATHLEN + 64], tmp[256];
1119 snprintf(fn, sizeof(fn), "%s/block/%s/dropped", debugfs_path,
1122 fd = my_open(fn, O_RDONLY);
1125 * This may be ok: the kernel may not support
1128 if (errno != ENOENT)
1129 fprintf(stderr, "Could not open %s: %d/%s\n",
1130 fn, errno, strerror(errno));
1132 } else if (read(fd, tmp, sizeof(tmp)) < 0) {
1133 fprintf(stderr, "Could not read %s: %d/%s\n",
1134 fn, errno, strerror(errno));
1142 static void get_all_drops(void)
1144 struct list_head *p;
1146 __list_for_each(p, &devpaths) {
1147 struct devpath *dpp = list_entry(p, struct devpath, head);
1149 dpp->drops = get_drops(dpp);
1153 static inline struct trace_buf *alloc_trace_buf(int cpu, int bufsize)
1155 struct trace_buf *tbp;
1157 tbp = malloc(sizeof(*tbp) + bufsize);
1158 INIT_LIST_HEAD(&tbp->head);
1160 tbp->buf = (void *)(tbp + 1);
1162 tbp->dpp = NULL; /* Will be set when tbp is added */
1167 static void free_tracer_heads(struct devpath *dpp)
1170 struct tracer_devpath_head *hd;
1172 for (cpu = 0, hd = dpp->heads; cpu < max_cpus; cpu++, hd++) {
1176 pthread_mutex_destroy(&hd->mutex);
1181 static int setup_tracer_devpaths(void)
1183 struct list_head *p;
1185 if (net_client_use_send())
1186 if (open_client_connections())
1189 __list_for_each(p, &devpaths) {
1191 struct tracer_devpath_head *hd;
1192 struct devpath *dpp = list_entry(p, struct devpath, head);
1194 dpp->heads = calloc(max_cpus, sizeof(struct tracer_devpath_head));
1195 for (cpu = 0, hd = dpp->heads; cpu < max_cpus; cpu++, hd++) {
1196 INIT_LIST_HEAD(&hd->head);
1197 pthread_mutex_init(&hd->mutex, NULL);
1205 static inline void add_trace_buf(struct devpath *dpp, int cpu,
1206 struct trace_buf **tbpp)
1208 struct trace_buf *tbp = *tbpp;
1209 struct tracer_devpath_head *hd = &dpp->heads[cpu];
1213 pthread_mutex_lock(&hd->mutex);
1214 list_add_tail(&tbp->head, &hd->head);
1215 pthread_mutex_unlock(&hd->mutex);
1217 *tbpp = alloc_trace_buf(cpu, buf_size);
1220 static inline void incr_entries(int entries_handled)
1222 pthread_mutex_lock(&dp_mutex);
1223 if (dp_entries == 0)
1224 pthread_cond_signal(&dp_cond);
1225 dp_entries += entries_handled;
1226 pthread_mutex_unlock(&dp_mutex);
1229 static void decr_entries(int handled)
1231 pthread_mutex_lock(&dp_mutex);
1232 dp_entries -= handled;
1233 pthread_mutex_unlock(&dp_mutex);
1236 static int wait_empty_entries(void)
1238 pthread_mutex_lock(&dp_mutex);
1239 while (!done && dp_entries == 0)
1240 t_pthread_cond_wait(&dp_cond, &dp_mutex);
1241 pthread_mutex_unlock(&dp_mutex);
1246 static int add_devpath(char *path)
1249 struct devpath *dpp;
1250 struct list_head *p;
1253 * Verify device is not duplicated
1255 __list_for_each(p, &devpaths) {
1256 struct devpath *tmp = list_entry(p, struct devpath, head);
1257 if (!strcmp(tmp->path, path))
1261 * Verify device is valid before going too far
1263 fd = my_open(path, O_RDONLY | O_NONBLOCK);
1265 fprintf(stderr, "Invalid path %s specified: %d/%s\n",
1266 path, errno, strerror(errno));
1270 dpp = malloc(sizeof(*dpp));
1271 memset(dpp, 0, sizeof(*dpp));
1272 dpp->path = strdup(path);
1275 list_add_tail(&dpp->head, &devpaths);
1280 static void rel_devpaths(void)
1282 struct list_head *p, *q;
1284 list_for_each_safe(p, q, &devpaths) {
1285 struct devpath *dpp = list_entry(p, struct devpath, head);
1287 list_del(&dpp->head);
1288 __stop_trace(dpp->fd);
1292 free_tracer_heads(dpp);
1299 static int flush_subbuf_net(struct trace_buf *tbp)
1301 int fd = cl_fds[tbp->cpu];
1302 struct devpath *dpp = tbp->dpp;
1304 if (net_send_header(fd, tbp->cpu, dpp->buts_name, tbp->len))
1306 else if (net_send_data(fd, tbp->buf, tbp->len) != tbp->len)
1313 handle_list_net(__attribute__((__unused__))struct tracer_devpath_head *hd,
1314 struct list_head *list)
1316 struct trace_buf *tbp;
1317 struct list_head *p, *q;
1318 int entries_handled = 0;
1320 list_for_each_safe(p, q, list) {
1321 tbp = list_entry(p, struct trace_buf, head);
1323 list_del(&tbp->head);
1326 if (cl_fds[tbp->cpu] >= 0) {
1327 if (flush_subbuf_net(tbp)) {
1328 close(cl_fds[tbp->cpu]);
1329 cl_fds[tbp->cpu] = -1;
1336 return entries_handled;
1340 * Tack 'tbp's buf onto the tail of 'prev's buf
1342 static struct trace_buf *tb_combine(struct trace_buf *prev,
1343 struct trace_buf *tbp)
1345 unsigned long tot_len;
1347 tot_len = prev->len + tbp->len;
1348 if (tot_len > buf_size) {
1350 * tbp->head isn't connected (it was 'prev'
1351 * so it had been taken off of the list
1352 * before). Therefore, we can realloc
1353 * the whole structures, as the other fields
1356 prev = realloc(prev, sizeof(*prev) + tot_len);
1357 prev->buf = (void *)(prev + 1);
1360 memcpy(prev->buf + prev->len, tbp->buf, tbp->len);
1361 prev->len = tot_len;
1367 static int handle_list_file(struct tracer_devpath_head *hd,
1368 struct list_head *list)
1370 int off, t_len, nevents;
1371 struct blk_io_trace *t;
1372 struct list_head *p, *q;
1373 int entries_handled = 0;
1374 struct trace_buf *tbp, *prev;
1377 list_for_each_safe(p, q, list) {
1378 tbp = list_entry(p, struct trace_buf, head);
1379 list_del(&tbp->head);
1383 * If there was some leftover before, tack this new
1384 * entry onto the tail of the previous one.
1387 tbp = tb_combine(prev, tbp);
1390 * See how many whole traces there are - send them
1391 * all out in one go.
1395 while (off + (int)sizeof(*t) <= tbp->len) {
1396 t = (struct blk_io_trace *)(tbp->buf + off);
1397 t_len = sizeof(*t) + t->pdu_len;
1398 if (off + t_len > tbp->len)
1405 pdc_nev_update(tbp->dpp, tbp->cpu, nevents);
1408 * Write any full set of traces, any remaining data is kept
1409 * for the next pass.
1412 if (write_data(tbp->buf, off) || off == tbp->len) {
1418 * Move valid data to beginning of buffer
1421 memmove(tbp->buf, tbp->buf + off, tbp->len);
1429 return entries_handled;
1432 static void __process_trace_bufs(void)
1435 struct list_head *p;
1436 struct list_head list;
1439 __list_for_each(p, &devpaths) {
1440 struct devpath *dpp = list_entry(p, struct devpath, head);
1441 struct tracer_devpath_head *hd = dpp->heads;
1443 for (cpu = 0; cpu < max_cpus; cpu++, hd++) {
1444 pthread_mutex_lock(&hd->mutex);
1445 if (list_empty(&hd->head)) {
1446 pthread_mutex_unlock(&hd->mutex);
1450 list_replace_init(&hd->head, &list);
1451 pthread_mutex_unlock(&hd->mutex);
1453 handled += handle_list(hd, &list);
1458 decr_entries(handled);
1461 static void process_trace_bufs(void)
1463 while (wait_empty_entries())
1464 __process_trace_bufs();
1467 static void clean_trace_bufs(void)
1470 * No mutex needed here: we're only reading from the lists,
1474 __process_trace_bufs();
1477 static inline void read_err(int cpu, char *ifn)
1479 if (errno != EAGAIN)
1480 fprintf(stderr, "Thread %d failed read of %s: %d/%s\n",
1481 cpu, ifn, errno, strerror(errno));
1484 static int net_sendfile(struct io_info *iop)
1488 ret = sendfile(iop->ofd, iop->ifd, NULL, iop->ready);
1492 } else if (ret < (int)iop->ready) {
1493 fprintf(stderr, "short sendfile send (%d of %d)\n",
1501 static inline int net_sendfile_data(struct tracer *tp, struct io_info *iop)
1503 struct devpath *dpp = iop->dpp;
1505 if (net_send_header(iop->ofd, tp->cpu, dpp->buts_name, iop->ready))
1507 return net_sendfile(iop);
1510 static int fill_ofname(char *dst, int dstlen, char *subdir, char *buts_name,
1517 len = snprintf(dst, dstlen, "%s/", output_dir);
1519 len = snprintf(dst, dstlen, "./");
1522 len += snprintf(dst + len, dstlen - len, "%s", subdir);
1524 if (stat(dst, &sb) < 0) {
1525 if (errno != ENOENT) {
1527 "Destination dir %s stat failed: %d/%s\n",
1528 dst, errno, strerror(errno));
1532 * There is no synchronization between multiple threads
1533 * trying to create the directory at once. It's harmless
1534 * to let them try, so just detect the problem and move on.
1536 if (mkdir(dst, 0755) < 0 && errno != EEXIST) {
1538 "Destination dir %s can't be made: %d/%s\n",
1539 dst, errno, strerror(errno));
1545 snprintf(dst + len, dstlen - len, "%s.blktrace.%d",
1548 snprintf(dst + len, dstlen - len, "%s.blktrace.%d",
1554 static int set_vbuf(struct io_info *iop, int mode, size_t size)
1556 iop->obuf = malloc(size);
1557 if (setvbuf(iop->ofp, iop->obuf, mode, size) < 0) {
1558 fprintf(stderr, "setvbuf(%s, %d) failed: %d/%s\n",
1559 iop->dpp->path, (int)size, errno,
1568 static int iop_open(struct io_info *iop, int cpu)
1570 char hostdir[MAXPATHLEN + 64];
1573 if (net_mode == Net_server) {
1574 struct cl_conn *nc = iop->nc;
1577 len = snprintf(hostdir, sizeof(hostdir), "%s-",
1579 len += strftime(hostdir + len, sizeof(hostdir) - len, "%F-%T/",
1580 gmtime(&iop->dpp->cl_connect_time));
1585 if (fill_ofname(iop->ofn, sizeof(iop->ofn), hostdir,
1586 iop->dpp->buts_name, cpu))
1589 iop->ofp = my_fopen(iop->ofn, "w+");
1590 if (iop->ofp == NULL) {
1591 fprintf(stderr, "Open output file %s failed: %d/%s\n",
1592 iop->ofn, errno, strerror(errno));
1596 if (set_vbuf(iop, _IOLBF, FILE_VBUF_SIZE)) {
1597 fprintf(stderr, "set_vbuf for file %s failed: %d/%s\n",
1598 iop->ofn, errno, strerror(errno));
1603 iop->ofd = fileno(iop->ofp);
1607 static void close_iop(struct io_info *iop)
1609 struct mmap_info *mip = &iop->mmap_info;
1612 munmap(mip->fs_buf, mip->fs_buf_len);
1614 if (!piped_output) {
1615 if (ftruncate(fileno(iop->ofp), mip->fs_size) < 0) {
1617 "Ignoring err: ftruncate(%s): %d/%s\n",
1618 iop->ofn, errno, strerror(errno));
1628 static void close_ios(struct tracer *tp)
1630 while (tp->nios > 0) {
1631 struct io_info *iop = &tp->ios[--tp->nios];
1633 iop->dpp->drops = get_drops(iop->dpp);
1639 else if (iop->ofd >= 0) {
1640 struct devpath *dpp = iop->dpp;
1642 net_send_close(iop->ofd, dpp->buts_name, dpp->drops);
1643 net_close_connection(&iop->ofd);
1651 static int open_ios(struct tracer *tp)
1654 struct io_info *iop;
1655 struct list_head *p;
1657 tp->ios = calloc(ndevs, sizeof(struct io_info));
1658 memset(tp->ios, 0, ndevs * sizeof(struct io_info));
1660 tp->pfds = calloc(ndevs, sizeof(struct pollfd));
1661 memset(tp->pfds, 0, ndevs * sizeof(struct pollfd));
1666 __list_for_each(p, &devpaths) {
1667 struct devpath *dpp = list_entry(p, struct devpath, head);
1671 snprintf(iop->ifn, sizeof(iop->ifn), "%s/block/%s/trace%d",
1672 debugfs_path, dpp->buts_name, tp->cpu);
1674 iop->ifd = my_open(iop->ifn, O_RDONLY | O_NONBLOCK);
1676 fprintf(stderr, "Thread %d failed open %s: %d/%s\n",
1677 tp->cpu, iop->ifn, errno, strerror(errno));
1681 init_mmap_info(&iop->mmap_info);
1684 pfd->events = POLLIN;
1688 else if (net_client_use_sendfile()) {
1689 iop->ofd = net_setup_client();
1692 net_send_open(iop->ofd, tp->cpu, dpp->buts_name);
1693 } else if (net_mode == Net_none) {
1694 if (iop_open(iop, tp->cpu))
1698 * This ensures that the server knows about all
1699 * connections & devices before _any_ closes
1701 net_send_open(cl_fds[tp->cpu], tp->cpu, dpp->buts_name);
1712 close(iop->ifd); /* tp->nios _not_ bumped */
1717 static int handle_pfds_file(struct tracer *tp, int nevs, int force_read)
1719 struct mmap_info *mip;
1720 int i, ret, nentries = 0;
1721 struct pollfd *pfd = tp->pfds;
1722 struct io_info *iop = tp->ios;
1724 for (i = 0; nevs > 0 && i < ndevs; i++, pfd++, iop++) {
1725 if (pfd->revents & POLLIN || force_read) {
1726 mip = &iop->mmap_info;
1728 ret = setup_mmap(iop->ofd, buf_size, mip, tp);
1734 ret = read(iop->ifd, mip->fs_buf + mip->fs_off,
1737 pdc_dr_update(iop->dpp, tp->cpu, ret);
1738 mip->fs_size += ret;
1741 } else if (ret == 0) {
1743 * Short reads after we're done stop us
1744 * from trying reads.
1749 read_err(tp->cpu, iop->ifn);
1750 if (errno != EAGAIN || tp->is_done)
1760 static int handle_pfds_netclient(struct tracer *tp, int nevs, int force_read)
1763 int i, nentries = 0;
1764 struct pollfd *pfd = tp->pfds;
1765 struct io_info *iop = tp->ios;
1767 for (i = 0; i < ndevs; i++, pfd++, iop++) {
1768 if (pfd->revents & POLLIN || force_read) {
1769 if (fstat(iop->ifd, &sb) < 0) {
1772 } else if (sb.st_size > (off_t)iop->data_queued) {
1773 iop->ready = sb.st_size - iop->data_queued;
1774 iop->data_queued = sb.st_size;
1776 if (!net_sendfile_data(tp, iop)) {
1777 pdc_dr_update(iop->dpp, tp->cpu,
1789 incr_entries(nentries);
1794 static int handle_pfds_entries(struct tracer *tp, int nevs, int force_read)
1796 int i, nentries = 0;
1797 struct trace_buf *tbp;
1798 struct pollfd *pfd = tp->pfds;
1799 struct io_info *iop = tp->ios;
1801 tbp = alloc_trace_buf(tp->cpu, buf_size);
1802 for (i = 0; i < ndevs; i++, pfd++, iop++) {
1803 if (pfd->revents & POLLIN || force_read) {
1804 tbp->len = read(iop->ifd, tbp->buf, buf_size);
1806 pdc_dr_update(iop->dpp, tp->cpu, tbp->len);
1807 add_trace_buf(iop->dpp, tp->cpu, &tbp);
1809 } else if (tbp->len == 0) {
1811 * Short reads after we're done stop us
1812 * from trying reads.
1817 read_err(tp->cpu, iop->ifn);
1818 if (errno != EAGAIN || tp->is_done)
1821 if (!piped_output && --nevs == 0)
1828 incr_entries(nentries);
1833 static void *thread_main(void *arg)
1835 int ret, ndone, to_val;
1836 struct tracer *tp = arg;
1838 ret = lock_on_cpu(tp->cpu);
1847 to_val = 50; /* Frequent partial handles */
1849 to_val = 500; /* 1/2 second intervals */
1852 tracer_signal_ready(tp, Th_running, 0);
1853 tracer_wait_unblock(tp);
1855 while (!tp->is_done) {
1856 ndone = poll(tp->pfds, ndevs, to_val);
1857 if (ndone || piped_output)
1858 (void)handle_pfds(tp, ndone, piped_output);
1859 else if (ndone < 0 && errno != EINTR)
1860 fprintf(stderr, "Thread %d poll failed: %d/%s\n",
1861 tp->cpu, errno, strerror(errno));
1865 * Trace is stopped, pull data until we get a short read
1867 while (handle_pfds(tp, ndevs, 1) > 0)
1871 tracer_signal_ready(tp, Th_leaving, 0);
1875 tracer_signal_ready(tp, Th_error, ret);
1879 static int start_tracer(int cpu)
1883 tp = malloc(sizeof(*tp));
1884 memset(tp, 0, sizeof(*tp));
1886 INIT_LIST_HEAD(&tp->head);
1890 if (pthread_create(&tp->thread, NULL, thread_main, tp)) {
1891 fprintf(stderr, "FAILED to start thread on CPU %d: %d/%s\n",
1892 cpu, errno, strerror(errno));
1897 list_add_tail(&tp->head, &tracers);
1901 static int create_output_files(int cpu)
1903 char fname[MAXPATHLEN + 64];
1904 struct list_head *p;
1907 __list_for_each(p, &devpaths) {
1908 struct devpath *dpp = list_entry(p, struct devpath, head);
1910 if (fill_ofname(fname, sizeof(fname), NULL, dpp->buts_name,
1913 f = my_fopen(fname, "w+");
1921 static void start_tracers(void)
1923 int cpu, started = 0;
1924 struct list_head *p;
1925 size_t alloc_size = CPU_ALLOC_SIZE(max_cpus);
1927 for (cpu = 0; cpu < max_cpus; cpu++) {
1928 if (!CPU_ISSET_S(cpu, alloc_size, online_cpus)) {
1930 * Create fake empty output files so that other tools
1931 * like blkparse don't have to bother with sparse CPU
1934 if (create_output_files(cpu))
1938 if (start_tracer(cpu))
1943 wait_tracers_ready(started);
1945 __list_for_each(p, &tracers) {
1946 struct tracer *tp = list_entry(p, struct tracer, head);
1949 "FAILED to start thread on CPU %d: %d/%s\n",
1950 tp->cpu, tp->status, strerror(tp->status));
1954 static void stop_tracers(void)
1956 struct list_head *p;
1959 * Stop the tracing - makes the tracer threads clean up quicker.
1961 __list_for_each(p, &devpaths) {
1962 struct devpath *dpp = list_entry(p, struct devpath, head);
1963 (void)ioctl(dpp->fd, BLKTRACESTOP);
1967 * Tell each tracer to quit
1969 __list_for_each(p, &tracers) {
1970 struct tracer *tp = list_entry(p, struct tracer, head);
1973 pthread_cond_broadcast(&mt_cond);
1976 static void del_tracers(void)
1978 struct list_head *p, *q;
1980 list_for_each_safe(p, q, &tracers) {
1981 struct tracer *tp = list_entry(p, struct tracer, head);
1983 list_del(&tp->head);
1988 static void wait_tracers(void)
1990 struct list_head *p;
1992 if (use_tracer_devpaths())
1993 process_trace_bufs();
1995 wait_tracers_leaving();
1997 __list_for_each(p, &tracers) {
1999 struct tracer *tp = list_entry(p, struct tracer, head);
2001 ret = pthread_join(tp->thread, NULL);
2003 fprintf(stderr, "Thread join %d failed %d\n",
2007 if (use_tracer_devpaths())
2013 static void exit_tracing(void)
2015 signal(SIGINT, SIG_IGN);
2016 signal(SIGHUP, SIG_IGN);
2017 signal(SIGTERM, SIG_IGN);
2018 signal(SIGALRM, SIG_IGN);
2026 static void handle_sigint(__attribute__((__unused__)) int sig)
2032 static void show_stats(struct list_head *devpaths)
2035 struct list_head *p;
2036 unsigned long long nevents, data_read;
2037 unsigned long long total_drops = 0;
2038 unsigned long long total_events = 0;
2041 ofp = my_fopen("/dev/null", "w");
2045 __list_for_each(p, devpaths) {
2047 struct pdc_stats *sp;
2048 struct devpath *dpp = list_entry(p, struct devpath, head);
2050 if (net_mode == Net_server)
2051 printf("server: end of run for %s:%s\n",
2052 dpp->ch->hostname, dpp->buts_name);
2057 fprintf(ofp, "=== %s ===\n", dpp->buts_name);
2058 for (cpu = 0, sp = dpp->stats; cpu < dpp->ncpus; cpu++, sp++) {
2060 * Estimate events if not known...
2062 if (sp->nevents == 0) {
2063 sp->nevents = sp->data_read /
2064 sizeof(struct blk_io_trace);
2068 " CPU%3d: %20llu events, %8llu KiB data\n",
2069 cpu, sp->nevents, (sp->data_read + 1023) >> 10);
2071 data_read += sp->data_read;
2072 nevents += sp->nevents;
2075 fprintf(ofp, " Total: %20llu events (dropped %llu),"
2076 " %8llu KiB data\n", nevents,
2077 dpp->drops, (data_read + 1024) >> 10);
2079 total_drops += dpp->drops;
2080 total_events += (nevents + dpp->drops);
2088 double drops_ratio = 1.0;
2091 drops_ratio = (double)total_drops/(double)total_events;
2093 fprintf(stderr, "\nYou have %llu (%5.1lf%%) dropped events\n"
2094 "Consider using a larger buffer size (-b) "
2095 "and/or more buffers (-n)\n",
2096 total_drops, 100.0 * drops_ratio);
2100 static int handle_args(int argc, char *argv[])
2104 int act_mask_tmp = 0;
2106 while ((c = getopt_long(argc, argv, S_OPTS, l_opts, NULL)) >= 0) {
2109 i = find_mask_map(optarg);
2111 fprintf(stderr, "Invalid action mask %s\n",
2119 if ((sscanf(optarg, "%x", &i) != 1) ||
2120 !valid_act_opt(i)) {
2122 "Invalid set action mask %s/0x%x\n",
2130 if (add_devpath(optarg) != 0)
2136 FILE *ifp = my_fopen(optarg, "r");
2140 "Invalid file for devices %s\n",
2145 while (fscanf(ifp, "%s\n", dev_line) == 1) {
2146 if (add_devpath(dev_line) != 0) {
2156 debugfs_path = optarg;
2160 output_name = optarg;
2163 kill_running_trace = 1;
2166 stop_watch = atoi(optarg);
2167 if (stop_watch <= 0) {
2169 "Invalid stopwatch value (%d secs)\n",
2176 printf("%s version %s\n", argv[0], blktrace_version);
2180 buf_size = strtoul(optarg, NULL, 10);
2181 if (buf_size <= 0 || buf_size > 16*1024) {
2182 fprintf(stderr, "Invalid buffer size (%lu)\n",
2189 buf_nr = strtoul(optarg, NULL, 10);
2192 "Invalid buffer nr (%lu)\n", buf_nr);
2197 output_dir = optarg;
2200 net_mode = Net_client;
2201 memset(hostname, 0, sizeof(hostname));
2202 strncpy(hostname, optarg, sizeof(hostname));
2203 hostname[sizeof(hostname) - 1] = '\0';
2206 net_mode = Net_server;
2209 net_port = atoi(optarg);
2212 net_use_sendfile = 0;
2215 show_usage(argv[0]);
2221 while (optind < argc)
2222 if (add_devpath(argv[optind++]) != 0)
2225 if (net_mode != Net_server && ndevs == 0) {
2226 show_usage(argv[0]);
2230 if (statfs(debugfs_path, &st) < 0) {
2231 fprintf(stderr, "Invalid debug path %s: %d/%s\n",
2232 debugfs_path, errno, strerror(errno));
2236 if (st.f_type != (long)DEBUGFS_TYPE) {
2237 fprintf(stderr, "Debugfs is not mounted at %s\n", debugfs_path);
2241 if (act_mask_tmp != 0)
2242 act_mask = act_mask_tmp;
2244 if (net_mode == Net_client && net_setup_addr())
2248 * Set up for appropriate PFD handler based upon output name.
2250 if (net_client_use_sendfile())
2251 handle_pfds = handle_pfds_netclient;
2252 else if (net_client_use_send())
2253 handle_pfds = handle_pfds_entries;
2254 else if (output_name && (strcmp(output_name, "-") == 0)) {
2256 handle_pfds = handle_pfds_entries;
2258 if (setvbuf(pfp, NULL, _IONBF, 0)) {
2259 perror("setvbuf stdout");
2263 handle_pfds = handle_pfds_file;
2267 static void ch_add_connection(struct net_server_s *ns, struct cl_host *ch,
2272 nc = malloc(sizeof(*nc));
2273 memset(nc, 0, sizeof(*nc));
2275 time(&nc->connect_time);
2280 list_add_tail(&nc->ch_head, &ch->conn_list);
2283 list_add_tail(&nc->ns_head, &ns->conn_list);
2285 ns->pfds = realloc(ns->pfds, (ns->connects+1) * sizeof(struct pollfd));
2288 static void ch_rem_connection(struct net_server_s *ns, struct cl_host *ch,
2291 net_close_connection(&nc->fd);
2293 list_del(&nc->ch_head);
2296 list_del(&nc->ns_head);
2298 ns->pfds = realloc(ns->pfds, (ns->connects+1) * sizeof(struct pollfd));
2303 static struct cl_host *net_find_client_host(struct net_server_s *ns,
2304 struct in_addr cl_in_addr)
2306 struct list_head *p;
2308 __list_for_each(p, &ns->ch_list) {
2309 struct cl_host *ch = list_entry(p, struct cl_host, head);
2311 if (in_addr_eq(ch->cl_in_addr, cl_in_addr))
2318 static struct cl_host *net_add_client_host(struct net_server_s *ns,
2319 struct sockaddr_in *addr)
2323 ch = malloc(sizeof(*ch));
2324 memset(ch, 0, sizeof(*ch));
2327 ch->cl_in_addr = addr->sin_addr;
2328 list_add_tail(&ch->head, &ns->ch_list);
2331 ch->hostname = strdup(inet_ntoa(addr->sin_addr));
2332 printf("server: connection from %s\n", ch->hostname);
2334 INIT_LIST_HEAD(&ch->conn_list);
2335 INIT_LIST_HEAD(&ch->devpaths);
2340 static void device_done(struct devpath *dpp, int ncpus)
2343 struct io_info *iop;
2345 for (cpu = 0, iop = dpp->ios; cpu < ncpus; cpu++, iop++)
2348 list_del(&dpp->head);
2352 static void net_ch_remove(struct cl_host *ch, int ncpus)
2354 struct list_head *p, *q;
2355 struct net_server_s *ns = ch->ns;
2357 list_for_each_safe(p, q, &ch->devpaths) {
2358 struct devpath *dpp = list_entry(p, struct devpath, head);
2359 device_done(dpp, ncpus);
2362 list_for_each_safe(p, q, &ch->conn_list) {
2363 struct cl_conn *nc = list_entry(p, struct cl_conn, ch_head);
2365 ch_rem_connection(ns, ch, nc);
2368 list_del(&ch->head);
2376 static void net_add_connection(struct net_server_s *ns)
2380 socklen_t socklen = sizeof(ns->addr);
2382 fd = my_accept(ns->listen_fd, (struct sockaddr *)&ns->addr, &socklen);
2385 * This is OK: we just won't accept this connection,
2390 ch = net_find_client_host(ns, ns->addr.sin_addr);
2392 ch = net_add_client_host(ns, &ns->addr);
2394 ch_add_connection(ns, ch, fd);
2398 static struct devpath *nc_add_dpp(struct cl_conn *nc,
2399 struct blktrace_net_hdr *bnh,
2400 time_t connect_time)
2403 struct io_info *iop;
2404 struct devpath *dpp;
2406 dpp = malloc(sizeof(*dpp));
2407 memset(dpp, 0, sizeof(*dpp));
2409 dpp->buts_name = strdup(bnh->buts_name);
2410 dpp->path = strdup(bnh->buts_name);
2413 dpp->cl_id = bnh->cl_id;
2414 dpp->cl_connect_time = connect_time;
2415 dpp->ncpus = nc->ncpus;
2416 dpp->stats = calloc(dpp->ncpus, sizeof(*dpp->stats));
2417 memset(dpp->stats, 0, dpp->ncpus * sizeof(*dpp->stats));
2419 list_add_tail(&dpp->head, &nc->ch->devpaths);
2422 dpp->ios = calloc(nc->ncpus, sizeof(*iop));
2423 memset(dpp->ios, 0, ndevs * sizeof(*iop));
2425 for (cpu = 0, iop = dpp->ios; cpu < nc->ncpus; cpu++, iop++) {
2428 init_mmap_info(&iop->mmap_info);
2430 if (iop_open(iop, cpu))
2438 * Need to unravel what's been done...
2441 close_iop(&dpp->ios[cpu--]);
2447 static struct devpath *nc_find_dpp(struct cl_conn *nc,
2448 struct blktrace_net_hdr *bnh)
2450 struct list_head *p;
2451 time_t connect_time = nc->connect_time;
2453 __list_for_each(p, &nc->ch->devpaths) {
2454 struct devpath *dpp = list_entry(p, struct devpath, head);
2456 if (!strcmp(dpp->buts_name, bnh->buts_name))
2459 if (dpp->cl_id == bnh->cl_id)
2460 connect_time = dpp->cl_connect_time;
2463 return nc_add_dpp(nc, bnh, connect_time);
2466 static void net_client_read_data(struct cl_conn *nc, struct devpath *dpp,
2467 struct blktrace_net_hdr *bnh)
2470 struct io_info *iop = &dpp->ios[bnh->cpu];
2471 struct mmap_info *mip = &iop->mmap_info;
2473 if (setup_mmap(iop->ofd, bnh->len, &iop->mmap_info, NULL)) {
2474 fprintf(stderr, "ncd(%s:%d): mmap failed\n",
2475 nc->ch->hostname, nc->fd);
2479 ret = net_recv_data(nc->fd, mip->fs_buf + mip->fs_off, bnh->len);
2481 pdc_dr_update(dpp, bnh->cpu, ret);
2482 mip->fs_size += ret;
2489 * Returns 1 if we closed a host - invalidates other polling information
2490 * that may be present.
2492 static int net_client_data(struct cl_conn *nc)
2495 struct devpath *dpp;
2496 struct blktrace_net_hdr bnh;
2498 ret = net_get_header(nc, &bnh);
2503 fprintf(stderr, "ncd(%d): header read failed\n", nc->fd);
2507 if (data_is_native == -1 && check_data_endianness(bnh.magic)) {
2508 fprintf(stderr, "ncd(%d): received data is bad\n", nc->fd);
2512 if (!data_is_native) {
2513 bnh.magic = be32_to_cpu(bnh.magic);
2514 bnh.cpu = be32_to_cpu(bnh.cpu);
2515 bnh.max_cpus = be32_to_cpu(bnh.max_cpus);
2516 bnh.len = be32_to_cpu(bnh.len);
2517 bnh.cl_id = be32_to_cpu(bnh.cl_id);
2518 bnh.buf_size = be32_to_cpu(bnh.buf_size);
2519 bnh.buf_nr = be32_to_cpu(bnh.buf_nr);
2520 bnh.page_size = be32_to_cpu(bnh.page_size);
2523 if ((bnh.magic & 0xffffff00) != BLK_IO_TRACE_MAGIC) {
2524 fprintf(stderr, "ncd(%s:%d): bad data magic\n",
2525 nc->ch->hostname, nc->fd);
2529 if (nc->ncpus == -1)
2530 nc->ncpus = bnh.max_cpus;
2533 * len == 0 means the other end is sending us a new connection/dpp
2534 * len == 1 means that the other end signalled end-of-run
2536 dpp = nc_find_dpp(nc, &bnh);
2539 * Just adding in the dpp above is enough
2541 ack_open_close(nc->fd, dpp->buts_name);
2543 } else if (bnh.len == 1) {
2545 * overload cpu count with dropped events
2547 dpp->drops = bnh.cpu;
2549 ack_open_close(nc->fd, dpp->buts_name);
2550 if (--nc->ch->cl_opens == 0) {
2551 show_stats(&nc->ch->devpaths);
2552 net_ch_remove(nc->ch, nc->ncpus);
2556 net_client_read_data(nc, dpp, &bnh);
2561 static void handle_client_data(struct net_server_s *ns, int events)
2565 struct list_head *p, *q;
2568 list_for_each_safe(p, q, &ns->conn_list) {
2569 if (pfd->revents & POLLIN) {
2570 nc = list_entry(p, struct cl_conn, ns_head);
2572 if (net_client_data(nc) || --events == 0)
2579 static void net_setup_pfds(struct net_server_s *ns)
2582 struct list_head *p;
2584 ns->pfds[0].fd = ns->listen_fd;
2585 ns->pfds[0].events = POLLIN;
2588 __list_for_each(p, &ns->conn_list) {
2589 struct cl_conn *nc = list_entry(p, struct cl_conn, ns_head);
2592 pfd->events = POLLIN;
2597 static int net_server_handle_connections(struct net_server_s *ns)
2601 printf("server: waiting for connections...\n");
2605 events = poll(ns->pfds, ns->connects + 1, -1);
2607 if (errno != EINTR) {
2608 perror("FATAL: poll error");
2611 } else if (events > 0) {
2612 if (ns->pfds[0].revents & POLLIN) {
2613 net_add_connection(ns);
2618 handle_client_data(ns, events);
2625 static int net_server(void)
2629 struct net_server_s net_server;
2630 struct net_server_s *ns = &net_server;
2632 memset(ns, 0, sizeof(*ns));
2633 INIT_LIST_HEAD(&ns->ch_list);
2634 INIT_LIST_HEAD(&ns->conn_list);
2635 ns->pfds = malloc(sizeof(struct pollfd));
2637 fd = my_socket(AF_INET, SOCK_STREAM, 0);
2639 perror("server: socket");
2644 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) {
2645 perror("setsockopt");
2649 memset(&ns->addr, 0, sizeof(ns->addr));
2650 ns->addr.sin_family = AF_INET;
2651 ns->addr.sin_addr.s_addr = htonl(INADDR_ANY);
2652 ns->addr.sin_port = htons(net_port);
2654 if (bind(fd, (struct sockaddr *) &ns->addr, sizeof(ns->addr)) < 0) {
2659 if (listen(fd, 1) < 0) {
2665 * The actual server looping is done here:
2668 ret = net_server_handle_connections(ns);
2671 * Clean up and return...
2678 static int run_tracers(void)
2680 atexit(exit_tracing);
2681 if (net_mode == Net_client)
2682 printf("blktrace: connecting to %s\n", hostname);
2687 if (use_tracer_devpaths()) {
2688 if (setup_tracer_devpaths())
2692 handle_list = handle_list_file;
2694 handle_list = handle_list_net;
2698 if (nthreads_running == ncpus) {
2701 if (net_mode == Net_client)
2702 printf("blktrace: connected!\n");
2709 if (nthreads_running == ncpus)
2710 show_stats(&devpaths);
2711 if (net_client_use_send())
2712 close_client_connections();
2718 static cpu_set_t *get_online_cpus(void)
2723 int cpuid, prevcpuid = -1;
2725 int n, ncpu, curcpu = 0;
2728 ncpu = sysconf(_SC_NPROCESSORS_CONF);
2732 cpu_nums = malloc(sizeof(int)*ncpu);
2739 * There is no way to easily get maximum CPU number. So we have to
2740 * parse the file first to find it out and then create appropriate
2743 cpus = my_fopen("/sys/devices/system/cpu/online", "r");
2745 n = fscanf(cpus, "%d%c", &cpuid, &nextch);
2748 if (n == 2 && nextch == '-') {
2752 if (prevcpuid == -1)
2754 while (prevcpuid <= cpuid) {
2755 /* More CPUs listed than configured? */
2756 if (curcpu >= ncpu) {
2760 cpu_nums[curcpu++] = prevcpuid++;
2767 max_cpus = cpu_nums[ncpu - 1] + 1;
2769 /* Now that we have maximum cpu number, create a cpuset */
2770 set = CPU_ALLOC(max_cpus);
2775 alloc_size = CPU_ALLOC_SIZE(max_cpus);
2776 CPU_ZERO_S(alloc_size, set);
2778 for (curcpu = 0; curcpu < ncpu; curcpu++)
2779 CPU_SET_S(cpu_nums[curcpu], alloc_size, set);
2786 int main(int argc, char *argv[])
2790 setlocale(LC_NUMERIC, "en_US");
2791 pagesize = getpagesize();
2792 online_cpus = get_online_cpus();
2794 fprintf(stderr, "cannot get online cpus %d/%s\n",
2795 errno, strerror(errno));
2798 } else if (handle_args(argc, argv)) {
2803 ncpus = CPU_COUNT_S(CPU_ALLOC_SIZE(max_cpus), online_cpus);
2804 if (ndevs > 1 && output_name && strcmp(output_name, "-") != 0) {
2805 fprintf(stderr, "-o not supported with multiple devices\n");
2810 signal(SIGINT, handle_sigint);
2811 signal(SIGHUP, handle_sigint);
2812 signal(SIGTERM, handle_sigint);
2813 signal(SIGALRM, handle_sigint);
2814 signal(SIGPIPE, SIG_IGN);
2816 if (kill_running_trace) {
2817 struct devpath *dpp;
2818 struct list_head *p;
2820 __list_for_each(p, &devpaths) {
2821 dpp = list_entry(p, struct devpath, head);
2822 if (__stop_trace(dpp->fd)) {
2824 "BLKTRACETEARDOWN %s failed: %d/%s\n",
2825 dpp->path, errno, strerror(errno));
2828 } else if (net_mode == Net_server) {
2830 fprintf(stderr, "-o ignored in server mode\n");
2835 ret = run_tracers();