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 int act_mask = ~0U;
280 static int kill_running_trace;
281 static int stop_watch;
282 static int piped_output;
284 static char *debugfs_path = "/sys/kernel/debug";
285 static char *output_name;
286 static char *output_dir;
288 static unsigned long buf_size = BUF_SIZE;
289 static unsigned long buf_nr = BUF_NR;
293 static LIST_HEAD(devpaths);
294 static LIST_HEAD(tracers);
296 static volatile int done;
299 * tracer threads add entries, the main thread takes them off and processes
300 * them. These protect the dp_entries variable.
302 static pthread_cond_t dp_cond = PTHREAD_COND_INITIALIZER;
303 static pthread_mutex_t dp_mutex = PTHREAD_MUTEX_INITIALIZER;
304 static volatile int dp_entries;
307 * These synchronize master / thread interactions.
309 static pthread_cond_t mt_cond = PTHREAD_COND_INITIALIZER;
310 static pthread_mutex_t mt_mutex = PTHREAD_MUTEX_INITIALIZER;
311 static volatile int nthreads_running;
312 static volatile int nthreads_leaving;
313 static volatile int nthreads_error;
314 static volatile int tracers_run;
317 * network cmd line params
319 static struct sockaddr_in hostname_addr;
320 static char hostname[MAXHOSTNAMELEN];
321 static int net_port = TRACE_NET_PORT;
322 static int net_use_sendfile = 1;
326 static int (*handle_pfds)(struct tracer *, int, int);
327 static int (*handle_list)(struct tracer_devpath_head *, struct list_head *);
329 #define S_OPTS "d:a:A:r:o:kw:vVb:n:D:lh:p:sI:"
330 static struct option l_opts[] = {
333 .has_arg = required_argument,
338 .name = "input-devs",
339 .has_arg = required_argument,
345 .has_arg = required_argument,
351 .has_arg = required_argument,
357 .has_arg = required_argument,
363 .has_arg = required_argument,
369 .has_arg = no_argument,
375 .has_arg = required_argument,
381 .has_arg = no_argument,
387 .has_arg = no_argument,
392 .name = "buffer-size",
393 .has_arg = required_argument,
398 .name = "num-sub-buffers",
399 .has_arg = required_argument,
404 .name = "output-dir",
405 .has_arg = required_argument,
411 .has_arg = no_argument,
417 .has_arg = required_argument,
423 .has_arg = required_argument,
428 .name = "no-sendfile",
429 .has_arg = no_argument,
438 static char usage_str[] = "\n\n" \
439 "-d <dev> | --dev=<dev>\n" \
440 "[ -r <debugfs path> | --relay=<debugfs path> ]\n" \
441 "[ -o <file> | --output=<file>]\n" \
442 "[ -D <dir> | --output-dir=<dir>\n" \
443 "[ -w <time> | --stopwatch=<time>]\n" \
444 "[ -a <action field> | --act-mask=<action field>]\n" \
445 "[ -A <action mask> | --set-mask=<action mask>]\n" \
446 "[ -b <size> | --buffer-size]\n" \
447 "[ -n <number> | --num-sub-buffers=<number>]\n" \
448 "[ -l | --listen]\n" \
449 "[ -h <hostname> | --host=<hostname>]\n" \
450 "[ -p <port number> | --port=<port number>]\n" \
451 "[ -s | --no-sendfile]\n" \
452 "[ -I <devs file> | --input-devs=<devs file>]\n" \
453 "[ -v <version> | --version]\n" \
454 "[ -V <version> | --version]\n" \
456 "\t-d Use specified device. May also be given last after options\n" \
457 "\t-r Path to mounted debugfs, defaults to /sys/kernel/debug\n" \
458 "\t-o File(s) to send output to\n" \
459 "\t-D Directory to prepend to output file names\n" \
460 "\t-w Stop after defined time, in seconds\n" \
461 "\t-a Only trace specified actions. See documentation\n" \
462 "\t-A Give trace mask as a single value. See documentation\n" \
463 "\t-b Sub buffer size in KiB (default 512)\n" \
464 "\t-n Number of sub buffers (default 4)\n" \
465 "\t-l Run in network listen mode (blktrace server)\n" \
466 "\t-h Run in network client mode, connecting to the given host\n" \
467 "\t-p Network port to use (default 8462)\n" \
468 "\t-s Make the network client NOT use sendfile() to transfer data\n" \
469 "\t-I Add devices found in <devs file>\n" \
470 "\t-v Print program version info\n" \
471 "\t-V Print program version info\n\n";
473 static void clear_events(struct pollfd *pfd)
479 static inline int net_client_use_sendfile(void)
481 return net_mode == Net_client && net_use_sendfile;
484 static inline int net_client_use_send(void)
486 return net_mode == Net_client && !net_use_sendfile;
489 static inline int use_tracer_devpaths(void)
491 return piped_output || net_client_use_send();
494 static inline int in_addr_eq(struct in_addr a, struct in_addr b)
496 return a.s_addr == b.s_addr;
499 static inline void pdc_dr_update(struct devpath *dpp, int cpu, int data_read)
501 dpp->stats[cpu].data_read += data_read;
504 static inline void pdc_nev_update(struct devpath *dpp, int cpu, int nevents)
506 dpp->stats[cpu].nevents += nevents;
509 static void show_usage(char *prog)
511 fprintf(stderr, "Usage: %s %s", prog, usage_str);
515 * Create a timespec 'msec' milliseconds into the future
517 static inline void make_timespec(struct timespec *tsp, long delta_msec)
521 gettimeofday(&now, NULL);
522 tsp->tv_sec = now.tv_sec;
523 tsp->tv_nsec = 1000L * now.tv_usec;
525 tsp->tv_nsec += (delta_msec * 1000000L);
526 if (tsp->tv_nsec > 1000000000L) {
527 long secs = tsp->tv_nsec / 1000000000L;
530 tsp->tv_nsec -= (secs * 1000000000L);
535 * Add a timer to ensure wait ends
537 static void t_pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
541 make_timespec(&ts, 50);
542 pthread_cond_timedwait(cond, mutex, &ts);
545 static void unblock_tracers(void)
547 pthread_mutex_lock(&mt_mutex);
549 pthread_cond_broadcast(&mt_cond);
550 pthread_mutex_unlock(&mt_mutex);
553 static void tracer_wait_unblock(struct tracer *tp)
555 pthread_mutex_lock(&mt_mutex);
556 while (!tp->is_done && !tracers_run)
557 pthread_cond_wait(&mt_cond, &mt_mutex);
558 pthread_mutex_unlock(&mt_mutex);
561 static void tracer_signal_ready(struct tracer *tp,
562 enum thread_status th_status,
565 pthread_mutex_lock(&mt_mutex);
568 if (th_status == Th_running)
570 else if (th_status == Th_error)
575 pthread_cond_signal(&mt_cond);
576 pthread_mutex_unlock(&mt_mutex);
579 static void wait_tracers_ready(int ncpus_started)
581 pthread_mutex_lock(&mt_mutex);
582 while ((nthreads_running + nthreads_error) < ncpus_started)
583 t_pthread_cond_wait(&mt_cond, &mt_mutex);
584 pthread_mutex_unlock(&mt_mutex);
587 static void wait_tracers_leaving(void)
589 pthread_mutex_lock(&mt_mutex);
590 while (nthreads_leaving < nthreads_running)
591 t_pthread_cond_wait(&mt_cond, &mt_mutex);
592 pthread_mutex_unlock(&mt_mutex);
595 static void init_mmap_info(struct mmap_info *mip)
597 mip->buf_size = buf_size;
598 mip->buf_nr = buf_nr;
599 mip->pagesize = pagesize;
602 static void net_close_connection(int *fd)
604 shutdown(*fd, SHUT_RDWR);
609 static void dpp_free(struct devpath *dpp)
618 free(dpp->buts_name);
622 static int lock_on_cpu(int cpu)
627 CPU_SET(cpu, &cpu_mask);
628 if (sched_setaffinity(0, sizeof(cpu_mask), &cpu_mask) < 0)
634 static int increase_limit(int resource, rlim_t increase)
637 int save_errno = errno;
639 if (!getrlimit(resource, &rlim)) {
640 rlim.rlim_cur += increase;
641 if (rlim.rlim_cur >= rlim.rlim_max)
642 rlim.rlim_max = rlim.rlim_cur + increase;
644 if (!setrlimit(resource, &rlim))
652 static int handle_open_failure(void)
654 if (errno == ENFILE || errno == EMFILE)
655 return increase_limit(RLIMIT_NOFILE, 16);
659 static int handle_mem_failure(size_t length)
662 return handle_open_failure();
663 else if (errno == ENOMEM)
664 return increase_limit(RLIMIT_MEMLOCK, 2 * length);
668 static FILE *my_fopen(const char *path, const char *mode)
673 fp = fopen(path, mode);
674 } while (fp == NULL && handle_open_failure());
679 static int my_open(const char *path, int flags)
684 fd = open(path, flags);
685 } while (fd < 0 && handle_open_failure());
690 static int my_socket(int domain, int type, int protocol)
695 fd = socket(domain, type, protocol);
696 } while (fd < 0 && handle_open_failure());
701 static int my_accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen)
706 fd = accept(sockfd, addr, addrlen);
707 } while (fd < 0 && handle_open_failure());
712 static void *my_mmap(void *addr, size_t length, int prot, int flags, int fd,
718 new = mmap(addr, length, prot, flags, fd, offset);
719 } while (new == MAP_FAILED && handle_mem_failure(length));
724 static int my_mlock(struct tracer *tp,
725 const void *addr, size_t len)
730 ret = mlock(addr, len);
731 if ((retry >= 10) && tp && tp->is_done)
734 } while (ret < 0 && handle_mem_failure(len));
739 static int setup_mmap(int fd, unsigned int maxlen,
740 struct mmap_info *mip,
743 if (mip->fs_off + maxlen > mip->fs_buf_len) {
744 unsigned long nr = max(16, mip->buf_nr);
747 munlock(mip->fs_buf, mip->fs_buf_len);
748 munmap(mip->fs_buf, mip->fs_buf_len);
752 mip->fs_off = mip->fs_size & (mip->pagesize - 1);
753 mip->fs_buf_len = (nr * mip->buf_size) - mip->fs_off;
754 mip->fs_max_size += mip->fs_buf_len;
756 if (ftruncate(fd, mip->fs_max_size) < 0) {
757 perror("setup_mmap: ftruncate");
761 mip->fs_buf = my_mmap(NULL, mip->fs_buf_len, PROT_WRITE,
763 mip->fs_size - mip->fs_off);
764 if (mip->fs_buf == MAP_FAILED) {
765 perror("setup_mmap: mmap");
768 if (my_mlock(tp, mip->fs_buf, mip->fs_buf_len) < 0) {
769 perror("setup_mlock: mlock");
777 static int __stop_trace(int fd)
780 * Should be stopped, don't complain if it isn't
782 ioctl(fd, BLKTRACESTOP);
783 return ioctl(fd, BLKTRACETEARDOWN);
786 static int write_data(char *buf, int len)
791 ret = fwrite(buf, len, 1, pfp);
792 if (ferror(pfp) || ret != 1) {
793 if (errno == EINTR) {
798 if (!piped_output || (errno != EPIPE && errno != EBADF)) {
799 fprintf(stderr, "write(%d) failed: %d/%s\n",
800 len, errno, strerror(errno));
814 * Returns the number of bytes read (successfully)
816 static int __net_recv_data(int fd, void *buf, unsigned int len)
818 unsigned int bytes_left = len;
820 while (bytes_left && !done) {
821 int ret = recv(fd, buf, bytes_left, MSG_WAITALL);
826 if (errno == EAGAIN) {
830 perror("server: net_recv_data: recv failed");
838 return len - bytes_left;
841 static int net_recv_data(int fd, void *buf, unsigned int len)
843 return __net_recv_data(fd, buf, len);
847 * Returns number of bytes written
849 static int net_send_data(int fd, void *buf, unsigned int buf_len)
852 unsigned int bytes_left = buf_len;
855 ret = send(fd, buf, bytes_left, 0);
865 return buf_len - bytes_left;
868 static int net_send_header(int fd, int cpu, char *buts_name, int len)
870 struct blktrace_net_hdr hdr;
872 memset(&hdr, 0, sizeof(hdr));
874 hdr.magic = BLK_IO_TRACE_MAGIC;
875 memset(hdr.buts_name, 0, sizeof(hdr.buts_name));
876 strncpy(hdr.buts_name, buts_name, sizeof(hdr.buts_name));
877 hdr.buts_name[sizeof(hdr.buts_name) - 1] = '\0';
879 hdr.max_cpus = ncpus;
881 hdr.cl_id = getpid();
882 hdr.buf_size = buf_size;
884 hdr.page_size = pagesize;
886 return net_send_data(fd, &hdr, sizeof(hdr)) != sizeof(hdr);
889 static void net_send_open_close(int fd, int cpu, char *buts_name, int len)
891 struct blktrace_net_hdr ret_hdr;
893 net_send_header(fd, cpu, buts_name, len);
894 net_recv_data(fd, &ret_hdr, sizeof(ret_hdr));
897 static void net_send_open(int fd, int cpu, char *buts_name)
899 net_send_open_close(fd, cpu, buts_name, 0);
902 static void net_send_close(int fd, char *buts_name, int drops)
905 * Overload CPU w/ number of drops
907 * XXX: Need to clear/set done around call - done=1 (which
908 * is true here) stops reads from happening... :-(
911 net_send_open_close(fd, drops, buts_name, 1);
915 static void ack_open_close(int fd, char *buts_name)
917 net_send_header(fd, 0, buts_name, 2);
920 static void net_send_drops(int fd)
924 __list_for_each(p, &devpaths) {
925 struct devpath *dpp = list_entry(p, struct devpath, head);
927 net_send_close(fd, dpp->buts_name, dpp->drops);
937 static int net_get_header(struct cl_conn *nc, struct blktrace_net_hdr *bnh)
940 int fl = fcntl(nc->fd, F_GETFL);
942 fcntl(nc->fd, F_SETFL, fl | O_NONBLOCK);
943 bytes_read = __net_recv_data(nc->fd, bnh, sizeof(*bnh));
944 fcntl(nc->fd, F_SETFL, fl & ~O_NONBLOCK);
946 if (bytes_read == sizeof(*bnh))
948 else if (bytes_read == 0)
954 static int net_setup_addr(void)
956 struct sockaddr_in *addr = &hostname_addr;
958 memset(addr, 0, sizeof(*addr));
959 addr->sin_family = AF_INET;
960 addr->sin_port = htons(net_port);
962 if (inet_aton(hostname, &addr->sin_addr) != 1) {
963 struct hostent *hent;
965 hent = gethostbyname(hostname);
967 if (h_errno == TRY_AGAIN) {
970 } else if (h_errno == NO_RECOVERY) {
971 fprintf(stderr, "gethostbyname(%s)"
972 "non-recoverable error encountered\n",
976 * HOST_NOT_FOUND, NO_ADDRESS or NO_DATA
978 fprintf(stderr, "Host %s not found\n",
984 memcpy(&addr->sin_addr, hent->h_addr, 4);
985 memset(hostname, 0, sizeof(hostname));
986 strncpy(hostname, hent->h_name, sizeof(hostname));
987 hostname[sizeof(hostname) - 1] = '\0';
993 static int net_setup_client(void)
996 struct sockaddr_in *addr = &hostname_addr;
998 fd = my_socket(AF_INET, SOCK_STREAM, 0);
1000 perror("client: socket");
1004 if (connect(fd, (struct sockaddr *)addr, sizeof(*addr)) < 0) {
1005 if (errno == ECONNREFUSED)
1007 "\nclient: Connection to %s refused, "
1008 "perhaps the server is not started?\n\n",
1011 perror("client: connect");
1020 static int open_client_connections(void)
1024 cl_fds = calloc(ncpus, sizeof(*cl_fds));
1025 for (cpu = 0; cpu < ncpus; cpu++) {
1026 cl_fds[cpu] = net_setup_client();
1027 if (cl_fds[cpu] < 0)
1034 close(cl_fds[cpu--]);
1039 static void close_client_connections(void)
1044 for (cpu = 0, fdp = cl_fds; cpu < ncpus; cpu++, fdp++) {
1046 net_send_drops(*fdp);
1047 net_close_connection(fdp);
1054 static void setup_buts(void)
1056 struct list_head *p;
1058 __list_for_each(p, &devpaths) {
1059 struct blk_user_trace_setup buts;
1060 struct devpath *dpp = list_entry(p, struct devpath, head);
1062 memset(&buts, 0, sizeof(buts));
1063 buts.buf_size = buf_size;
1064 buts.buf_nr = buf_nr;
1065 buts.act_mask = act_mask;
1067 if (ioctl(dpp->fd, BLKTRACESETUP, &buts) >= 0) {
1069 dpp->buts_name = strdup(buts.name);
1072 dpp->stats = calloc(dpp->ncpus, sizeof(*dpp->stats));
1073 memset(dpp->stats, 0, dpp->ncpus * sizeof(*dpp->stats));
1075 fprintf(stderr, "BLKTRACESETUP(2) %s failed: %d/%s\n",
1076 dpp->path, errno, strerror(errno));
1080 static void start_buts(void)
1082 struct list_head *p;
1084 __list_for_each(p, &devpaths) {
1085 struct devpath *dpp = list_entry(p, struct devpath, head);
1087 if (ioctl(dpp->fd, BLKTRACESTART) < 0) {
1088 fprintf(stderr, "BLKTRACESTART %s failed: %d/%s\n",
1089 dpp->path, errno, strerror(errno));
1094 static int get_drops(struct devpath *dpp)
1097 char fn[MAXPATHLEN + 64], tmp[256];
1099 snprintf(fn, sizeof(fn), "%s/block/%s/dropped", debugfs_path,
1102 fd = my_open(fn, O_RDONLY);
1105 * This may be ok: the kernel may not support
1108 if (errno != ENOENT)
1109 fprintf(stderr, "Could not open %s: %d/%s\n",
1110 fn, errno, strerror(errno));
1112 } else if (read(fd, tmp, sizeof(tmp)) < 0) {
1113 fprintf(stderr, "Could not read %s: %d/%s\n",
1114 fn, errno, strerror(errno));
1122 static void get_all_drops(void)
1124 struct list_head *p;
1126 __list_for_each(p, &devpaths) {
1127 struct devpath *dpp = list_entry(p, struct devpath, head);
1129 dpp->drops = get_drops(dpp);
1133 static inline struct trace_buf *alloc_trace_buf(int cpu, int bufsize)
1135 struct trace_buf *tbp;
1137 tbp = malloc(sizeof(*tbp) + bufsize);
1138 INIT_LIST_HEAD(&tbp->head);
1140 tbp->buf = (void *)(tbp + 1);
1142 tbp->dpp = NULL; /* Will be set when tbp is added */
1147 static void free_tracer_heads(struct devpath *dpp)
1150 struct tracer_devpath_head *hd;
1152 for (cpu = 0, hd = dpp->heads; cpu < ncpus; cpu++, hd++) {
1156 pthread_mutex_destroy(&hd->mutex);
1161 static int setup_tracer_devpaths(void)
1163 struct list_head *p;
1165 if (net_client_use_send())
1166 if (open_client_connections())
1169 __list_for_each(p, &devpaths) {
1171 struct tracer_devpath_head *hd;
1172 struct devpath *dpp = list_entry(p, struct devpath, head);
1174 dpp->heads = calloc(ncpus, sizeof(struct tracer_devpath_head));
1175 for (cpu = 0, hd = dpp->heads; cpu < ncpus; cpu++, hd++) {
1176 INIT_LIST_HEAD(&hd->head);
1177 pthread_mutex_init(&hd->mutex, NULL);
1185 static inline void add_trace_buf(struct devpath *dpp, int cpu,
1186 struct trace_buf **tbpp)
1188 struct trace_buf *tbp = *tbpp;
1189 struct tracer_devpath_head *hd = &dpp->heads[cpu];
1193 pthread_mutex_lock(&hd->mutex);
1194 list_add_tail(&tbp->head, &hd->head);
1195 pthread_mutex_unlock(&hd->mutex);
1197 *tbpp = alloc_trace_buf(cpu, buf_size);
1200 static inline void incr_entries(int entries_handled)
1202 pthread_mutex_lock(&dp_mutex);
1203 if (dp_entries == 0)
1204 pthread_cond_signal(&dp_cond);
1205 dp_entries += entries_handled;
1206 pthread_mutex_unlock(&dp_mutex);
1209 static void decr_entries(int handled)
1211 pthread_mutex_lock(&dp_mutex);
1212 dp_entries -= handled;
1213 pthread_mutex_unlock(&dp_mutex);
1216 static int wait_empty_entries(void)
1218 pthread_mutex_lock(&dp_mutex);
1219 while (!done && dp_entries == 0)
1220 t_pthread_cond_wait(&dp_cond, &dp_mutex);
1221 pthread_mutex_unlock(&dp_mutex);
1226 static int add_devpath(char *path)
1229 struct devpath *dpp;
1230 struct list_head *p;
1233 * Verify device is not duplicated
1235 __list_for_each(p, &devpaths) {
1236 struct devpath *tmp = list_entry(p, struct devpath, head);
1237 if (!strcmp(tmp->path, path))
1241 * Verify device is valid before going too far
1243 fd = my_open(path, O_RDONLY | O_NONBLOCK);
1245 fprintf(stderr, "Invalid path %s specified: %d/%s\n",
1246 path, errno, strerror(errno));
1250 dpp = malloc(sizeof(*dpp));
1251 memset(dpp, 0, sizeof(*dpp));
1252 dpp->path = strdup(path);
1255 list_add_tail(&dpp->head, &devpaths);
1260 static void rel_devpaths(void)
1262 struct list_head *p, *q;
1264 list_for_each_safe(p, q, &devpaths) {
1265 struct devpath *dpp = list_entry(p, struct devpath, head);
1267 list_del(&dpp->head);
1268 __stop_trace(dpp->fd);
1272 free_tracer_heads(dpp);
1279 static int flush_subbuf_net(struct trace_buf *tbp)
1281 int fd = cl_fds[tbp->cpu];
1282 struct devpath *dpp = tbp->dpp;
1284 if (net_send_header(fd, tbp->cpu, dpp->buts_name, tbp->len))
1286 else if (net_send_data(fd, tbp->buf, tbp->len) != tbp->len)
1293 handle_list_net(__attribute__((__unused__))struct tracer_devpath_head *hd,
1294 struct list_head *list)
1296 struct trace_buf *tbp;
1297 struct list_head *p, *q;
1298 int entries_handled = 0;
1300 list_for_each_safe(p, q, list) {
1301 tbp = list_entry(p, struct trace_buf, head);
1303 list_del(&tbp->head);
1306 if (cl_fds[tbp->cpu] >= 0) {
1307 if (flush_subbuf_net(tbp)) {
1308 close(cl_fds[tbp->cpu]);
1309 cl_fds[tbp->cpu] = -1;
1316 return entries_handled;
1320 * Tack 'tbp's buf onto the tail of 'prev's buf
1322 static struct trace_buf *tb_combine(struct trace_buf *prev,
1323 struct trace_buf *tbp)
1325 unsigned long tot_len;
1327 tot_len = prev->len + tbp->len;
1328 if (tot_len > buf_size) {
1330 * tbp->head isn't connected (it was 'prev'
1331 * so it had been taken off of the list
1332 * before). Therefore, we can realloc
1333 * the whole structures, as the other fields
1336 prev = realloc(prev, sizeof(*prev) + tot_len);
1337 prev->buf = (void *)(prev + 1);
1340 memcpy(prev->buf + prev->len, tbp->buf, tbp->len);
1341 prev->len = tot_len;
1347 static int handle_list_file(struct tracer_devpath_head *hd,
1348 struct list_head *list)
1350 int off, t_len, nevents;
1351 struct blk_io_trace *t;
1352 struct list_head *p, *q;
1353 int entries_handled = 0;
1354 struct trace_buf *tbp, *prev;
1357 list_for_each_safe(p, q, list) {
1358 tbp = list_entry(p, struct trace_buf, head);
1359 list_del(&tbp->head);
1363 * If there was some leftover before, tack this new
1364 * entry onto the tail of the previous one.
1367 tbp = tb_combine(prev, tbp);
1370 * See how many whole traces there are - send them
1371 * all out in one go.
1375 while (off + (int)sizeof(*t) <= tbp->len) {
1376 t = (struct blk_io_trace *)(tbp->buf + off);
1377 t_len = sizeof(*t) + t->pdu_len;
1378 if (off + t_len > tbp->len)
1385 pdc_nev_update(tbp->dpp, tbp->cpu, nevents);
1388 * Write any full set of traces, any remaining data is kept
1389 * for the next pass.
1392 if (write_data(tbp->buf, off) || off == tbp->len) {
1398 * Move valid data to beginning of buffer
1401 memmove(tbp->buf, tbp->buf + off, tbp->len);
1409 return entries_handled;
1412 static void __process_trace_bufs(void)
1415 struct list_head *p;
1416 struct list_head list;
1419 __list_for_each(p, &devpaths) {
1420 struct devpath *dpp = list_entry(p, struct devpath, head);
1421 struct tracer_devpath_head *hd = dpp->heads;
1423 for (cpu = 0; cpu < ncpus; cpu++, hd++) {
1424 pthread_mutex_lock(&hd->mutex);
1425 if (list_empty(&hd->head)) {
1426 pthread_mutex_unlock(&hd->mutex);
1430 list_replace_init(&hd->head, &list);
1431 pthread_mutex_unlock(&hd->mutex);
1433 handled += handle_list(hd, &list);
1438 decr_entries(handled);
1441 static void process_trace_bufs(void)
1443 while (wait_empty_entries())
1444 __process_trace_bufs();
1447 static void clean_trace_bufs(void)
1450 * No mutex needed here: we're only reading from the lists,
1454 __process_trace_bufs();
1457 static inline void read_err(int cpu, char *ifn)
1459 if (errno != EAGAIN)
1460 fprintf(stderr, "Thread %d failed read of %s: %d/%s\n",
1461 cpu, ifn, errno, strerror(errno));
1464 static int net_sendfile(struct io_info *iop)
1468 ret = sendfile(iop->ofd, iop->ifd, NULL, iop->ready);
1472 } else if (ret < (int)iop->ready) {
1473 fprintf(stderr, "short sendfile send (%d of %d)\n",
1481 static inline int net_sendfile_data(struct tracer *tp, struct io_info *iop)
1483 struct devpath *dpp = iop->dpp;
1485 if (net_send_header(iop->ofd, tp->cpu, dpp->buts_name, iop->ready))
1487 return net_sendfile(iop);
1490 static int fill_ofname(struct io_info *iop, int cpu)
1494 char *dst = iop->ofn;
1497 len = snprintf(iop->ofn, sizeof(iop->ofn), "%s/", output_dir);
1499 len = snprintf(iop->ofn, sizeof(iop->ofn), "./");
1501 if (net_mode == Net_server) {
1502 struct cl_conn *nc = iop->nc;
1504 len += sprintf(dst + len, "%s-", nc->ch->hostname);
1505 len += strftime(dst + len, 64, "%F-%T/",
1506 gmtime(&iop->dpp->cl_connect_time));
1509 if (stat(iop->ofn, &sb) < 0) {
1510 if (errno != ENOENT) {
1512 "Destination dir %s stat failed: %d/%s\n",
1513 iop->ofn, errno, strerror(errno));
1517 * There is no synchronization between multiple threads
1518 * trying to create the directory at once. It's harmless
1519 * to let them try, so just detect the problem and move on.
1521 if (mkdir(iop->ofn, 0755) < 0 && errno != EEXIST) {
1523 "Destination dir %s can't be made: %d/%s\n",
1524 iop->ofn, errno, strerror(errno));
1530 snprintf(iop->ofn + len, sizeof(iop->ofn), "%s.blktrace.%d",
1533 snprintf(iop->ofn + len, sizeof(iop->ofn), "%s.blktrace.%d",
1534 iop->dpp->buts_name, cpu);
1539 static int set_vbuf(struct io_info *iop, int mode, size_t size)
1541 iop->obuf = malloc(size);
1542 if (setvbuf(iop->ofp, iop->obuf, mode, size) < 0) {
1543 fprintf(stderr, "setvbuf(%s, %d) failed: %d/%s\n",
1544 iop->dpp->path, (int)size, errno,
1553 static int iop_open(struct io_info *iop, int cpu)
1556 if (fill_ofname(iop, cpu))
1559 iop->ofp = my_fopen(iop->ofn, "w+");
1560 if (iop->ofp == NULL) {
1561 fprintf(stderr, "Open output file %s failed: %d/%s\n",
1562 iop->ofn, errno, strerror(errno));
1566 if (set_vbuf(iop, _IOLBF, FILE_VBUF_SIZE)) {
1567 fprintf(stderr, "set_vbuf for file %s failed: %d/%s\n",
1568 iop->ofn, errno, strerror(errno));
1573 iop->ofd = fileno(iop->ofp);
1577 static void close_iop(struct io_info *iop)
1579 struct mmap_info *mip = &iop->mmap_info;
1582 munmap(mip->fs_buf, mip->fs_buf_len);
1584 if (!piped_output) {
1585 if (ftruncate(fileno(iop->ofp), mip->fs_size) < 0) {
1587 "Ignoring err: ftruncate(%s): %d/%s\n",
1588 iop->ofn, errno, strerror(errno));
1598 static void close_ios(struct tracer *tp)
1600 while (tp->nios > 0) {
1601 struct io_info *iop = &tp->ios[--tp->nios];
1603 iop->dpp->drops = get_drops(iop->dpp);
1609 else if (iop->ofd >= 0) {
1610 struct devpath *dpp = iop->dpp;
1612 net_send_close(iop->ofd, dpp->buts_name, dpp->drops);
1613 net_close_connection(&iop->ofd);
1621 static int open_ios(struct tracer *tp)
1624 struct io_info *iop;
1625 struct list_head *p;
1627 tp->ios = calloc(ndevs, sizeof(struct io_info));
1628 memset(tp->ios, 0, ndevs * sizeof(struct io_info));
1630 tp->pfds = calloc(ndevs, sizeof(struct pollfd));
1631 memset(tp->pfds, 0, ndevs * sizeof(struct pollfd));
1636 __list_for_each(p, &devpaths) {
1637 struct devpath *dpp = list_entry(p, struct devpath, head);
1641 snprintf(iop->ifn, sizeof(iop->ifn), "%s/block/%s/trace%d",
1642 debugfs_path, dpp->buts_name, tp->cpu);
1644 iop->ifd = my_open(iop->ifn, O_RDONLY | O_NONBLOCK);
1646 fprintf(stderr, "Thread %d failed open %s: %d/%s\n",
1647 tp->cpu, iop->ifn, errno, strerror(errno));
1651 init_mmap_info(&iop->mmap_info);
1654 pfd->events = POLLIN;
1658 else if (net_client_use_sendfile()) {
1659 iop->ofd = net_setup_client();
1662 net_send_open(iop->ofd, tp->cpu, dpp->buts_name);
1663 } else if (net_mode == Net_none) {
1664 if (iop_open(iop, tp->cpu))
1668 * This ensures that the server knows about all
1669 * connections & devices before _any_ closes
1671 net_send_open(cl_fds[tp->cpu], tp->cpu, dpp->buts_name);
1682 close(iop->ifd); /* tp->nios _not_ bumped */
1687 static int handle_pfds_file(struct tracer *tp, int nevs, int force_read)
1689 struct mmap_info *mip;
1690 int i, ret, nentries = 0;
1691 struct pollfd *pfd = tp->pfds;
1692 struct io_info *iop = tp->ios;
1694 for (i = 0; nevs > 0 && i < ndevs; i++, pfd++, iop++) {
1695 if (pfd->revents & POLLIN || force_read) {
1696 mip = &iop->mmap_info;
1698 ret = setup_mmap(iop->ofd, buf_size, mip, tp);
1704 ret = read(iop->ifd, mip->fs_buf + mip->fs_off,
1707 pdc_dr_update(iop->dpp, tp->cpu, ret);
1708 mip->fs_size += ret;
1711 } else if (ret == 0) {
1713 * Short reads after we're done stop us
1714 * from trying reads.
1719 read_err(tp->cpu, iop->ifn);
1720 if (errno != EAGAIN || tp->is_done)
1730 static int handle_pfds_netclient(struct tracer *tp, int nevs, int force_read)
1733 int i, nentries = 0;
1734 struct pollfd *pfd = tp->pfds;
1735 struct io_info *iop = tp->ios;
1737 for (i = 0; i < ndevs; i++, pfd++, iop++) {
1738 if (pfd->revents & POLLIN || force_read) {
1739 if (fstat(iop->ifd, &sb) < 0) {
1742 } else if (sb.st_size > (off_t)iop->data_queued) {
1743 iop->ready = sb.st_size - iop->data_queued;
1744 iop->data_queued = sb.st_size;
1746 if (!net_sendfile_data(tp, iop)) {
1747 pdc_dr_update(iop->dpp, tp->cpu,
1759 incr_entries(nentries);
1764 static int handle_pfds_entries(struct tracer *tp, int nevs, int force_read)
1766 int i, nentries = 0;
1767 struct trace_buf *tbp;
1768 struct pollfd *pfd = tp->pfds;
1769 struct io_info *iop = tp->ios;
1771 tbp = alloc_trace_buf(tp->cpu, buf_size);
1772 for (i = 0; i < ndevs; i++, pfd++, iop++) {
1773 if (pfd->revents & POLLIN || force_read) {
1774 tbp->len = read(iop->ifd, tbp->buf, buf_size);
1776 pdc_dr_update(iop->dpp, tp->cpu, tbp->len);
1777 add_trace_buf(iop->dpp, tp->cpu, &tbp);
1779 } else if (tbp->len == 0) {
1781 * Short reads after we're done stop us
1782 * from trying reads.
1787 read_err(tp->cpu, iop->ifn);
1788 if (errno != EAGAIN || tp->is_done)
1791 if (!piped_output && --nevs == 0)
1798 incr_entries(nentries);
1803 static void *thread_main(void *arg)
1805 int ret, ndone, to_val;
1806 struct tracer *tp = arg;
1808 ret = lock_on_cpu(tp->cpu);
1817 to_val = 50; /* Frequent partial handles */
1819 to_val = 500; /* 1/2 second intervals */
1822 tracer_signal_ready(tp, Th_running, 0);
1823 tracer_wait_unblock(tp);
1825 while (!tp->is_done) {
1826 ndone = poll(tp->pfds, ndevs, to_val);
1827 if (ndone || piped_output)
1828 (void)handle_pfds(tp, ndone, piped_output);
1829 else if (ndone < 0 && errno != EINTR)
1830 fprintf(stderr, "Thread %d poll failed: %d/%s\n",
1831 tp->cpu, errno, strerror(errno));
1835 * Trace is stopped, pull data until we get a short read
1837 while (handle_pfds(tp, ndevs, 1) > 0)
1841 tracer_signal_ready(tp, Th_leaving, 0);
1845 tracer_signal_ready(tp, Th_error, ret);
1849 static int start_tracer(int cpu)
1853 tp = malloc(sizeof(*tp));
1854 memset(tp, 0, sizeof(*tp));
1856 INIT_LIST_HEAD(&tp->head);
1860 if (pthread_create(&tp->thread, NULL, thread_main, tp)) {
1861 fprintf(stderr, "FAILED to start thread on CPU %d: %d/%s\n",
1862 cpu, errno, strerror(errno));
1867 list_add_tail(&tp->head, &tracers);
1871 static void start_tracers(void)
1874 struct list_head *p;
1876 for (cpu = 0; cpu < ncpus; cpu++)
1877 if (start_tracer(cpu))
1880 wait_tracers_ready(cpu);
1882 __list_for_each(p, &tracers) {
1883 struct tracer *tp = list_entry(p, struct tracer, head);
1886 "FAILED to start thread on CPU %d: %d/%s\n",
1887 tp->cpu, tp->status, strerror(tp->status));
1891 static void stop_tracers(void)
1893 struct list_head *p;
1896 * Stop the tracing - makes the tracer threads clean up quicker.
1898 __list_for_each(p, &devpaths) {
1899 struct devpath *dpp = list_entry(p, struct devpath, head);
1900 (void)ioctl(dpp->fd, BLKTRACESTOP);
1904 * Tell each tracer to quit
1906 __list_for_each(p, &tracers) {
1907 struct tracer *tp = list_entry(p, struct tracer, head);
1912 static void del_tracers(void)
1914 struct list_head *p, *q;
1916 list_for_each_safe(p, q, &tracers) {
1917 struct tracer *tp = list_entry(p, struct tracer, head);
1919 list_del(&tp->head);
1924 static void wait_tracers(void)
1926 struct list_head *p;
1928 if (use_tracer_devpaths())
1929 process_trace_bufs();
1931 wait_tracers_leaving();
1933 __list_for_each(p, &tracers) {
1935 struct tracer *tp = list_entry(p, struct tracer, head);
1937 ret = pthread_join(tp->thread, NULL);
1939 fprintf(stderr, "Thread join %d failed %d\n",
1943 if (use_tracer_devpaths())
1949 static void exit_tracing(void)
1951 signal(SIGINT, SIG_IGN);
1952 signal(SIGHUP, SIG_IGN);
1953 signal(SIGTERM, SIG_IGN);
1954 signal(SIGALRM, SIG_IGN);
1962 static void handle_sigint(__attribute__((__unused__)) int sig)
1968 static void show_stats(struct list_head *devpaths)
1971 struct list_head *p;
1972 unsigned long long nevents, data_read;
1973 unsigned long long total_drops = 0;
1974 unsigned long long total_events = 0;
1977 ofp = my_fopen("/dev/null", "w");
1981 __list_for_each(p, devpaths) {
1983 struct pdc_stats *sp;
1984 struct devpath *dpp = list_entry(p, struct devpath, head);
1986 if (net_mode == Net_server)
1987 printf("server: end of run for %s:%s\n",
1988 dpp->ch->hostname, dpp->buts_name);
1993 fprintf(ofp, "=== %s ===\n", dpp->buts_name);
1994 for (cpu = 0, sp = dpp->stats; cpu < dpp->ncpus; cpu++, sp++) {
1996 * Estimate events if not known...
1998 if (sp->nevents == 0) {
1999 sp->nevents = sp->data_read /
2000 sizeof(struct blk_io_trace);
2004 " CPU%3d: %20llu events, %8llu KiB data\n",
2005 cpu, sp->nevents, (sp->data_read + 1023) >> 10);
2007 data_read += sp->data_read;
2008 nevents += sp->nevents;
2011 fprintf(ofp, " Total: %20llu events (dropped %llu),"
2012 " %8llu KiB data\n", nevents,
2013 dpp->drops, (data_read + 1024) >> 10);
2015 total_drops += dpp->drops;
2016 total_events += (nevents + dpp->drops);
2024 double drops_ratio = 1.0;
2027 drops_ratio = (double)total_drops/(double)total_events;
2029 fprintf(stderr, "\nYou have %llu (%5.1lf%%) dropped events\n"
2030 "Consider using a larger buffer size (-b) "
2031 "and/or more buffers (-n)\n",
2032 total_drops, 100.0 * drops_ratio);
2036 static int handle_args(int argc, char *argv[])
2040 int act_mask_tmp = 0;
2042 while ((c = getopt_long(argc, argv, S_OPTS, l_opts, NULL)) >= 0) {
2045 i = find_mask_map(optarg);
2047 fprintf(stderr, "Invalid action mask %s\n",
2055 if ((sscanf(optarg, "%x", &i) != 1) ||
2056 !valid_act_opt(i)) {
2058 "Invalid set action mask %s/0x%x\n",
2066 if (add_devpath(optarg) != 0)
2072 FILE *ifp = my_fopen(optarg, "r");
2076 "Invalid file for devices %s\n",
2081 while (fscanf(ifp, "%s\n", dev_line) == 1) {
2082 if (add_devpath(dev_line) != 0) {
2092 debugfs_path = optarg;
2096 output_name = optarg;
2099 kill_running_trace = 1;
2102 stop_watch = atoi(optarg);
2103 if (stop_watch <= 0) {
2105 "Invalid stopwatch value (%d secs)\n",
2112 printf("%s version %s\n", argv[0], blktrace_version);
2116 buf_size = strtoul(optarg, NULL, 10);
2117 if (buf_size <= 0 || buf_size > 16*1024) {
2118 fprintf(stderr, "Invalid buffer size (%lu)\n",
2125 buf_nr = strtoul(optarg, NULL, 10);
2128 "Invalid buffer nr (%lu)\n", buf_nr);
2133 output_dir = optarg;
2136 net_mode = Net_client;
2137 memset(hostname, 0, sizeof(hostname));
2138 strncpy(hostname, optarg, sizeof(hostname));
2139 hostname[sizeof(hostname) - 1] = '\0';
2142 net_mode = Net_server;
2145 net_port = atoi(optarg);
2148 net_use_sendfile = 0;
2151 show_usage(argv[0]);
2157 while (optind < argc)
2158 if (add_devpath(argv[optind++]) != 0)
2161 if (net_mode != Net_server && ndevs == 0) {
2162 show_usage(argv[0]);
2166 if (statfs(debugfs_path, &st) < 0) {
2167 fprintf(stderr, "Invalid debug path %s: %d/%s\n",
2168 debugfs_path, errno, strerror(errno));
2172 if (st.f_type != (long)DEBUGFS_TYPE) {
2173 fprintf(stderr, "Debugfs is not mounted at %s\n", debugfs_path);
2177 if (act_mask_tmp != 0)
2178 act_mask = act_mask_tmp;
2180 if (net_mode == Net_client && net_setup_addr())
2184 * Set up for appropriate PFD handler based upon output name.
2186 if (net_client_use_sendfile())
2187 handle_pfds = handle_pfds_netclient;
2188 else if (net_client_use_send())
2189 handle_pfds = handle_pfds_entries;
2190 else if (output_name && (strcmp(output_name, "-") == 0)) {
2192 handle_pfds = handle_pfds_entries;
2194 if (setvbuf(pfp, NULL, _IONBF, 0)) {
2195 perror("setvbuf stdout");
2199 handle_pfds = handle_pfds_file;
2203 static void ch_add_connection(struct net_server_s *ns, struct cl_host *ch,
2208 nc = malloc(sizeof(*nc));
2209 memset(nc, 0, sizeof(*nc));
2211 time(&nc->connect_time);
2216 list_add_tail(&nc->ch_head, &ch->conn_list);
2219 list_add_tail(&nc->ns_head, &ns->conn_list);
2221 ns->pfds = realloc(ns->pfds, (ns->connects+1) * sizeof(struct pollfd));
2224 static void ch_rem_connection(struct net_server_s *ns, struct cl_host *ch,
2227 net_close_connection(&nc->fd);
2229 list_del(&nc->ch_head);
2232 list_del(&nc->ns_head);
2234 ns->pfds = realloc(ns->pfds, (ns->connects+1) * sizeof(struct pollfd));
2239 static struct cl_host *net_find_client_host(struct net_server_s *ns,
2240 struct in_addr cl_in_addr)
2242 struct list_head *p;
2244 __list_for_each(p, &ns->ch_list) {
2245 struct cl_host *ch = list_entry(p, struct cl_host, head);
2247 if (in_addr_eq(ch->cl_in_addr, cl_in_addr))
2254 static struct cl_host *net_add_client_host(struct net_server_s *ns,
2255 struct sockaddr_in *addr)
2259 ch = malloc(sizeof(*ch));
2260 memset(ch, 0, sizeof(*ch));
2263 ch->cl_in_addr = addr->sin_addr;
2264 list_add_tail(&ch->head, &ns->ch_list);
2267 ch->hostname = strdup(inet_ntoa(addr->sin_addr));
2268 printf("server: connection from %s\n", ch->hostname);
2270 INIT_LIST_HEAD(&ch->conn_list);
2271 INIT_LIST_HEAD(&ch->devpaths);
2276 static void device_done(struct devpath *dpp, int ncpus)
2279 struct io_info *iop;
2281 for (cpu = 0, iop = dpp->ios; cpu < ncpus; cpu++, iop++)
2284 list_del(&dpp->head);
2288 static void net_ch_remove(struct cl_host *ch, int ncpus)
2290 struct list_head *p, *q;
2291 struct net_server_s *ns = ch->ns;
2293 list_for_each_safe(p, q, &ch->devpaths) {
2294 struct devpath *dpp = list_entry(p, struct devpath, head);
2295 device_done(dpp, ncpus);
2298 list_for_each_safe(p, q, &ch->conn_list) {
2299 struct cl_conn *nc = list_entry(p, struct cl_conn, ch_head);
2301 ch_rem_connection(ns, ch, nc);
2304 list_del(&ch->head);
2312 static void net_add_connection(struct net_server_s *ns)
2316 socklen_t socklen = sizeof(ns->addr);
2318 fd = my_accept(ns->listen_fd, (struct sockaddr *)&ns->addr, &socklen);
2321 * This is OK: we just won't accept this connection,
2326 ch = net_find_client_host(ns, ns->addr.sin_addr);
2328 ch = net_add_client_host(ns, &ns->addr);
2330 ch_add_connection(ns, ch, fd);
2334 static struct devpath *nc_add_dpp(struct cl_conn *nc,
2335 struct blktrace_net_hdr *bnh,
2336 time_t connect_time)
2339 struct io_info *iop;
2340 struct devpath *dpp;
2342 dpp = malloc(sizeof(*dpp));
2343 memset(dpp, 0, sizeof(*dpp));
2345 dpp->buts_name = strdup(bnh->buts_name);
2346 dpp->path = strdup(bnh->buts_name);
2349 dpp->cl_id = bnh->cl_id;
2350 dpp->cl_connect_time = connect_time;
2351 dpp->ncpus = nc->ncpus;
2352 dpp->stats = calloc(dpp->ncpus, sizeof(*dpp->stats));
2353 memset(dpp->stats, 0, dpp->ncpus * sizeof(*dpp->stats));
2355 list_add_tail(&dpp->head, &nc->ch->devpaths);
2358 dpp->ios = calloc(nc->ncpus, sizeof(*iop));
2359 memset(dpp->ios, 0, ndevs * sizeof(*iop));
2361 for (cpu = 0, iop = dpp->ios; cpu < nc->ncpus; cpu++, iop++) {
2364 init_mmap_info(&iop->mmap_info);
2366 if (iop_open(iop, cpu))
2374 * Need to unravel what's been done...
2377 close_iop(&dpp->ios[cpu--]);
2383 static struct devpath *nc_find_dpp(struct cl_conn *nc,
2384 struct blktrace_net_hdr *bnh)
2386 struct list_head *p;
2387 time_t connect_time = nc->connect_time;
2389 __list_for_each(p, &nc->ch->devpaths) {
2390 struct devpath *dpp = list_entry(p, struct devpath, head);
2392 if (!strcmp(dpp->buts_name, bnh->buts_name))
2395 if (dpp->cl_id == bnh->cl_id)
2396 connect_time = dpp->cl_connect_time;
2399 return nc_add_dpp(nc, bnh, connect_time);
2402 static void net_client_read_data(struct cl_conn *nc, struct devpath *dpp,
2403 struct blktrace_net_hdr *bnh)
2406 struct io_info *iop = &dpp->ios[bnh->cpu];
2407 struct mmap_info *mip = &iop->mmap_info;
2409 if (setup_mmap(iop->ofd, bnh->len, &iop->mmap_info, NULL)) {
2410 fprintf(stderr, "ncd(%s:%d): mmap failed\n",
2411 nc->ch->hostname, nc->fd);
2415 ret = net_recv_data(nc->fd, mip->fs_buf + mip->fs_off, bnh->len);
2417 pdc_dr_update(dpp, bnh->cpu, ret);
2418 mip->fs_size += ret;
2425 * Returns 1 if we closed a host - invalidates other polling information
2426 * that may be present.
2428 static int net_client_data(struct cl_conn *nc)
2431 struct devpath *dpp;
2432 struct blktrace_net_hdr bnh;
2434 ret = net_get_header(nc, &bnh);
2439 fprintf(stderr, "ncd(%d): header read failed\n", nc->fd);
2443 if (data_is_native == -1 && check_data_endianness(bnh.magic)) {
2444 fprintf(stderr, "ncd(%d): received data is bad\n", nc->fd);
2448 if (!data_is_native) {
2449 bnh.magic = be32_to_cpu(bnh.magic);
2450 bnh.cpu = be32_to_cpu(bnh.cpu);
2451 bnh.max_cpus = be32_to_cpu(bnh.max_cpus);
2452 bnh.len = be32_to_cpu(bnh.len);
2453 bnh.cl_id = be32_to_cpu(bnh.cl_id);
2454 bnh.buf_size = be32_to_cpu(bnh.buf_size);
2455 bnh.buf_nr = be32_to_cpu(bnh.buf_nr);
2456 bnh.page_size = be32_to_cpu(bnh.page_size);
2459 if ((bnh.magic & 0xffffff00) != BLK_IO_TRACE_MAGIC) {
2460 fprintf(stderr, "ncd(%s:%d): bad data magic\n",
2461 nc->ch->hostname, nc->fd);
2465 if (nc->ncpus == -1)
2466 nc->ncpus = bnh.max_cpus;
2469 * len == 0 means the other end is sending us a new connection/dpp
2470 * len == 1 means that the other end signalled end-of-run
2472 dpp = nc_find_dpp(nc, &bnh);
2475 * Just adding in the dpp above is enough
2477 ack_open_close(nc->fd, dpp->buts_name);
2479 } else if (bnh.len == 1) {
2481 * overload cpu count with dropped events
2483 dpp->drops = bnh.cpu;
2485 ack_open_close(nc->fd, dpp->buts_name);
2486 if (--nc->ch->cl_opens == 0) {
2487 show_stats(&nc->ch->devpaths);
2488 net_ch_remove(nc->ch, nc->ncpus);
2492 net_client_read_data(nc, dpp, &bnh);
2497 static void handle_client_data(struct net_server_s *ns, int events)
2501 struct list_head *p, *q;
2504 list_for_each_safe(p, q, &ns->conn_list) {
2505 if (pfd->revents & POLLIN) {
2506 nc = list_entry(p, struct cl_conn, ns_head);
2508 if (net_client_data(nc) || --events == 0)
2515 static void net_setup_pfds(struct net_server_s *ns)
2518 struct list_head *p;
2520 ns->pfds[0].fd = ns->listen_fd;
2521 ns->pfds[0].events = POLLIN;
2524 __list_for_each(p, &ns->conn_list) {
2525 struct cl_conn *nc = list_entry(p, struct cl_conn, ns_head);
2528 pfd->events = POLLIN;
2533 static int net_server_handle_connections(struct net_server_s *ns)
2537 printf("server: waiting for connections...\n");
2541 events = poll(ns->pfds, ns->connects + 1, -1);
2543 if (errno != EINTR) {
2544 perror("FATAL: poll error");
2547 } else if (events > 0) {
2548 if (ns->pfds[0].revents & POLLIN) {
2549 net_add_connection(ns);
2554 handle_client_data(ns, events);
2561 static int net_server(void)
2565 struct net_server_s net_server;
2566 struct net_server_s *ns = &net_server;
2568 memset(ns, 0, sizeof(*ns));
2569 INIT_LIST_HEAD(&ns->ch_list);
2570 INIT_LIST_HEAD(&ns->conn_list);
2571 ns->pfds = malloc(sizeof(struct pollfd));
2573 fd = my_socket(AF_INET, SOCK_STREAM, 0);
2575 perror("server: socket");
2580 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) {
2581 perror("setsockopt");
2585 memset(&ns->addr, 0, sizeof(ns->addr));
2586 ns->addr.sin_family = AF_INET;
2587 ns->addr.sin_addr.s_addr = htonl(INADDR_ANY);
2588 ns->addr.sin_port = htons(net_port);
2590 if (bind(fd, (struct sockaddr *) &ns->addr, sizeof(ns->addr)) < 0) {
2595 if (listen(fd, 1) < 0) {
2601 * The actual server looping is done here:
2604 ret = net_server_handle_connections(ns);
2607 * Clean up and return...
2614 static int run_tracers(void)
2616 atexit(exit_tracing);
2617 if (net_mode == Net_client)
2618 printf("blktrace: connecting to %s\n", hostname);
2622 if (use_tracer_devpaths()) {
2623 if (setup_tracer_devpaths())
2627 handle_list = handle_list_file;
2629 handle_list = handle_list_net;
2633 if (nthreads_running == ncpus) {
2636 if (net_mode == Net_client)
2637 printf("blktrace: connected!\n");
2644 if (nthreads_running == ncpus)
2645 show_stats(&devpaths);
2646 if (net_client_use_send())
2647 close_client_connections();
2653 int main(int argc, char *argv[])
2657 setlocale(LC_NUMERIC, "en_US");
2658 pagesize = getpagesize();
2659 ncpus = sysconf(_SC_NPROCESSORS_ONLN);
2661 fprintf(stderr, "sysconf(_SC_NPROCESSORS_ONLN) failed %d/%s\n",
2662 errno, strerror(errno));
2665 } else if (handle_args(argc, argv)) {
2670 if (ndevs > 1 && output_name && strcmp(output_name, "-") != 0) {
2671 fprintf(stderr, "-o not supported with multiple devices\n");
2676 signal(SIGINT, handle_sigint);
2677 signal(SIGHUP, handle_sigint);
2678 signal(SIGTERM, handle_sigint);
2679 signal(SIGALRM, handle_sigint);
2680 signal(SIGPIPE, SIG_IGN);
2682 if (kill_running_trace) {
2683 struct devpath *dpp;
2684 struct list_head *p;
2686 __list_for_each(p, &devpaths) {
2687 dpp = list_entry(p, struct devpath, head);
2688 if (__stop_trace(dpp->fd)) {
2690 "BLKTRACETEARDOWN %s failed: %d/%s\n",
2691 dpp->path, errno, strerror(errno));
2694 } else if (net_mode == Net_server) {
2696 fprintf(stderr, "-o ignored in server mode\n");
2701 ret = run_tracers();