Rewrote blktrace to have a single thread per CPU
[blktrace.git] / blktrace.c
1 /*
2  * block queue tracing application
3  *
4  * Copyright (C) 2005 Jens Axboe <axboe@suse.de>
5  * Copyright (C) 2006 Jens Axboe <axboe@kernel.dk>
6  *
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
9  *
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.
14  *
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.
19  *
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
23  *
24  */
25
26 #include <errno.h>
27 #include <stdarg.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <fcntl.h>
32 #include <getopt.h>
33 #include <sched.h>
34 #include <unistd.h>
35 #include <poll.h>
36 #include <signal.h>
37 #include <pthread.h>
38 #include <locale.h>
39 #include <sys/ioctl.h>
40 #include <sys/types.h>
41 #include <sys/stat.h>
42 #include <sys/vfs.h>
43 #include <sys/mman.h>
44 #include <sys/param.h>
45 #include <sys/time.h>
46 #include <sys/resource.h>
47 #include <sys/socket.h>
48 #include <netinet/in.h>
49 #include <arpa/inet.h>
50 #include <netdb.h>
51 #include <sys/sendfile.h>
52
53 #include "btt/list.h"
54 #include "blktrace.h"
55
56 /*
57  * You may want to increase this even more, if you are logging at a high
58  * rate and see skipped/missed events
59  */
60 #define BUF_SIZE                (512 * 1024)
61 #define BUF_NR                  (4)
62
63 #define FILE_VBUF_SIZE          (128 * 1024)
64
65 #define DEBUGFS_TYPE            (0x64626720)
66 #define TRACE_NET_PORT          (8462)
67
68 enum {
69         Net_none = 0,
70         Net_server,
71         Net_client,
72 };
73
74 /*
75  * Generic stats collected: nevents can be _roughly_ estimated by data_read
76  * (discounting pdu...)
77  *
78  * These fields are updated w/ pdc_dr_update & pdc_nev_update below.
79  */
80 struct pdc_stats {
81         unsigned long long data_read;
82         unsigned long long nevents;
83 };
84
85 struct devpath {
86         struct list_head head;
87         char *path;                     /* path to device special file */
88         char *buts_name;                /* name returned from bt kernel code */
89         struct pdc_stats *stats;
90         int fd, idx, ncpus;
91         unsigned long long drops;
92
93         /*
94          * For piped output only:
95          *
96          * Each tracer will have a tracer_devpath_head that it will add new
97          * data onto. It's list is protected above (tracer_devpath_head.mutex)
98          * and it will signal the processing thread using the dp_cond,
99          * dp_mutex & dp_entries variables above.
100          */
101         struct tracer_devpath_head *heads;
102
103         /*
104          * For network server mode only:
105          */
106         struct cl_host *ch;
107         u32 cl_id;
108         time_t cl_connect_time;
109         struct io_info *ios;
110 };
111
112 /*
113  * For piped output to stdout we will have each tracer thread (one per dev)
114  * tack buffers read from the relay queues on a per-device list.
115  *
116  * The main thread will then collect trace buffers from each of lists in turn.
117  *
118  * We will use a mutex to guard each of the trace_buf list. The tracers
119  * can then signal the main thread using <dp_cond,dp_mutex> and
120  * dp_entries. (When dp_entries is 0, and a tracer adds an entry it will
121  * signal. When dp_entries is 0, the main thread will wait for that condition
122  * to be signalled.)
123  *
124  * adb: It may be better just to have a large buffer per tracer per dev,
125  * and then use it as a ring-buffer. This would certainly cut down a lot
126  * of malloc/free thrashing, at the cost of more memory movements (potentially).
127  */
128 struct trace_buf {
129         struct list_head head;
130         struct devpath *dpp;
131         void *buf;
132         int cpu, len;
133 };
134
135 struct tracer_devpath_head {
136         pthread_mutex_t mutex;
137         struct list_head head;
138         struct trace_buf *prev;
139 };
140
141 /*
142  * Used to handle the mmap() interfaces for output file (containing traces)
143  */
144 struct mmap_info {
145         void *fs_buf;
146         unsigned long long fs_size, fs_max_size, fs_off, fs_buf_len;
147         unsigned long buf_size, buf_nr;
148         int pagesize;
149 };
150
151 /*
152  * Each thread doing work on a (client) side of blktrace will have one
153  * of these. The ios array contains input/output information, pfds holds
154  * poll() data. The volatile's provide flags to/from the main executing
155  * thread.
156  */
157 struct tracer {
158         struct list_head head;
159         struct io_info *ios;
160         struct pollfd *pfds;
161         pthread_t thread;
162         pthread_mutex_t mutex;
163         pthread_cond_t cond;
164         int cpu, nios;
165         volatile int running, status, is_done;
166 };
167
168 /*
169  * networking stuff follows. we include a magic number so we know whether
170  * to endianness convert or not.
171  *
172  * The len field is overloaded:
173  *      0 - Indicates an "open" - allowing the server to set up for a dev/cpu
174  *      1 - Indicates a "close" - Shut down connection orderly
175  *
176  * The cpu field is overloaded on close: it will contain the number of drops.
177  */
178 struct blktrace_net_hdr {
179         u32 magic;              /* same as trace magic */
180         char buts_name[32];     /* trace name */
181         u32 cpu;                /* for which cpu */
182         u32 max_cpus;
183         u32 len;                /* length of following trace data */
184         u32 cl_id;              /* id for set of client per-cpu connections */
185         u32 buf_size;           /* client buf_size for this trace  */
186         u32 buf_nr;             /* client buf_nr for this trace  */
187         u32 page_size;          /* client page_size for this trace  */
188 };
189
190 /*
191  * Each host encountered has one of these. The head is used to link this
192  * on to the network server's ch_list. Connections associated with this
193  * host are linked on conn_list, and any devices traced on that host
194  * are connected on the devpaths list.
195  */
196 struct cl_host {
197         struct list_head head;
198         struct list_head conn_list;
199         struct list_head devpaths;
200         struct net_server_s *ns;
201         char *hostname;
202         struct in_addr cl_in_addr;
203         int connects, ndevs, cl_opens;
204 };
205
206 /*
207  * Each connection (client to server socket ('fd')) has one of these. A
208  * back reference to the host ('ch'), and lists headers (for the host
209  * list, and the network server conn_list) are also included.
210  */
211 struct cl_conn {
212         struct list_head ch_head, ns_head;
213         struct cl_host *ch;
214         int fd, ncpus;
215         time_t connect_time;
216 };
217
218 /*
219  * The network server requires some poll structures to be maintained -
220  * one per conection currently on conn_list. The nchs/ch_list values
221  * are for each host connected to this server. The addr field is used
222  * for scratch as new connections are established.
223  */
224 struct net_server_s {
225         struct list_head conn_list;
226         struct list_head ch_list;
227         struct pollfd *pfds;
228         int listen_fd, connects, nchs;
229         struct sockaddr_in addr;
230 };
231
232 /*
233  * This structure is (generically) used to providide information
234  * for a read-to-write set of values.
235  *
236  * ifn & ifd represent input information
237  *
238  * ofn, ofd, ofp, obuf & mmap_info are used for output file (optionally).
239  */
240 struct io_info {
241         struct devpath *dpp;
242         FILE *ofp;
243         char *obuf;
244         struct cl_conn *nc;     /* Server network connection */
245
246         /*
247          * mmap controlled output files
248          */
249         struct mmap_info mmap_info;
250
251         /*
252          * Client network fields
253          */
254         unsigned int ready;
255         unsigned long long data_queued;
256
257         /*
258          * Input/output file descriptors & names
259          */
260         int ifd, ofd;
261         char ifn[MAXPATHLEN + 64];
262         char ofn[MAXPATHLEN + 64];
263 };
264
265 static char blktrace_version[] = "2.0.0";
266
267 /*
268  * Linkage to blktrace helper routines (trace conversions)
269  */
270 int data_is_native = -1;
271
272 static int ncpus;
273 static int pagesize;
274 static int act_mask = ~0U;
275 static char *debugfs_path = "/sys/kernel/debug";
276 static char *output_name;
277 static char *output_dir;
278 static int kill_running_trace;
279 static int stop_watch;
280 static unsigned long buf_size = BUF_SIZE;
281 static unsigned long buf_nr = BUF_NR;
282 static LIST_HEAD(devpaths);
283 static LIST_HEAD(tracers);
284 static int ndevs;
285 static volatile int done;
286 static FILE *pfp;
287 static int piped_output;
288 static int ntracers;
289
290 static pthread_cond_t dp_cond = PTHREAD_COND_INITIALIZER;
291 static pthread_mutex_t dp_mutex = PTHREAD_MUTEX_INITIALIZER;
292 static volatile int dp_entries;
293
294 /*
295  * network cmd line params
296  */
297 static char hostname[MAXHOSTNAMELEN];
298 static int net_port = TRACE_NET_PORT;
299 static int net_use_sendfile = 1;
300 static int net_mode;
301 static int *cl_fds;
302
303 static int (*handle_pfds)(struct tracer *, int, int);
304 static int (*handle_list)(struct tracer_devpath_head *, struct list_head *);
305
306 #define S_OPTS  "d:a:A:r:o:kw:vVb:n:D:lh:p:sI:"
307 static struct option l_opts[] = {
308         {
309                 .name = "dev",
310                 .has_arg = required_argument,
311                 .flag = NULL,
312                 .val = 'd'
313         },
314         {
315                 .name = "input-devs",
316                 .has_arg = required_argument,
317                 .flag = NULL,
318                 .val = 'I'
319         },
320         {
321                 .name = "act-mask",
322                 .has_arg = required_argument,
323                 .flag = NULL,
324                 .val = 'a'
325         },
326         {
327                 .name = "set-mask",
328                 .has_arg = required_argument,
329                 .flag = NULL,
330                 .val = 'A'
331         },
332         {
333                 .name = "relay",
334                 .has_arg = required_argument,
335                 .flag = NULL,
336                 .val = 'r'
337         },
338         {
339                 .name = "output",
340                 .has_arg = required_argument,
341                 .flag = NULL,
342                 .val = 'o'
343         },
344         {
345                 .name = "kill",
346                 .has_arg = no_argument,
347                 .flag = NULL,
348                 .val = 'k'
349         },
350         {
351                 .name = "stopwatch",
352                 .has_arg = required_argument,
353                 .flag = NULL,
354                 .val = 'w'
355         },
356         {
357                 .name = "version",
358                 .has_arg = no_argument,
359                 .flag = NULL,
360                 .val = 'v'
361         },
362         {
363                 .name = "version",
364                 .has_arg = no_argument,
365                 .flag = NULL,
366                 .val = 'V'
367         },
368         {
369                 .name = "buffer-size",
370                 .has_arg = required_argument,
371                 .flag = NULL,
372                 .val = 'b'
373         },
374         {
375                 .name = "num-sub-buffers",
376                 .has_arg = required_argument,
377                 .flag = NULL,
378                 .val = 'n'
379         },
380         {
381                 .name = "output-dir",
382                 .has_arg = required_argument,
383                 .flag = NULL,
384                 .val = 'D'
385         },
386         {
387                 .name = "listen",
388                 .has_arg = no_argument,
389                 .flag = NULL,
390                 .val = 'l'
391         },
392         {
393                 .name = "host",
394                 .has_arg = required_argument,
395                 .flag = NULL,
396                 .val = 'h'
397         },
398         {
399                 .name = "port",
400                 .has_arg = required_argument,
401                 .flag = NULL,
402                 .val = 'p'
403         },
404         {
405                 .name = "no-sendfile",
406                 .has_arg = no_argument,
407                 .flag = NULL,
408                 .val = 's'
409         },
410         {
411                 .name = NULL,
412         }
413 };
414
415 static char usage_str[] = \
416         "-d <dev> [ -r debugfs path ] [ -o <output> ] [-k ] [ -w time ]\n" \
417         "[ -a action ] [ -A action mask ] [ -I  <devs file> ] [ -v ]\n\n" \
418         "\t-d Use specified device. May also be given last after options\n" \
419         "\t-r Path to mounted debugfs, defaults to /sys/kernel/debug\n" \
420         "\t-o File(s) to send output to\n" \
421         "\t-D Directory to prepend to output file names\n" \
422         "\t-k Kill a running trace\n" \
423         "\t-w Stop after defined time, in seconds\n" \
424         "\t-a Only trace specified actions. See documentation\n" \
425         "\t-A Give trace mask as a single value. See documentation\n" \
426         "\t-b Sub buffer size in KiB\n" \
427         "\t-n Number of sub buffers\n" \
428         "\t-l Run in network listen mode (blktrace server)\n" \
429         "\t-h Run in network client mode, connecting to the given host\n" \
430         "\t-p Network port to use (default 8462)\n" \
431         "\t-s Make the network client NOT use sendfile() to transfer data\n" \
432         "\t-I Add devices found in <devs file>\n" \
433         "\t-V Print program version info\n\n";
434
435 static void clear_events(struct pollfd *pfd)
436 {
437         pfd->events = 0;
438         pfd->revents = 0;
439 }
440
441 static inline int net_client_use_sendfile(void)
442 {
443         return net_mode == Net_client && net_use_sendfile;
444 }
445
446 static inline int net_client_use_send(void)
447 {
448         return net_mode == Net_client && !net_use_sendfile;
449 }
450
451 static inline int use_tracer_devpaths(void)
452 {
453         return piped_output || net_client_use_send();
454 }
455
456 static inline int in_addr_eq(struct in_addr a, struct in_addr b)
457 {
458         return a.s_addr == b.s_addr;
459 }
460
461 static inline void pdc_dr_update(struct devpath *dpp, int cpu, int data_read)
462 {
463         dpp->stats[cpu].data_read += data_read;
464 }
465
466 static inline void pdc_nev_update(struct devpath *dpp, int cpu, int nevents)
467 {
468         dpp->stats[cpu].nevents += nevents;
469 }
470
471 static void show_usage(char *prog)
472 {
473         fprintf(stderr, "Usage: %s %s %s", prog, blktrace_version, usage_str);
474 }
475
476 static void init_mmap_info(struct mmap_info *mip)
477 {
478         mip->buf_size = buf_size;
479         mip->buf_nr = buf_nr;
480         mip->pagesize = pagesize;
481 }
482
483 static void net_close_connection(int *fd)
484 {
485         shutdown(*fd, SHUT_RDWR);
486         close(*fd);
487         *fd = -1;
488 }
489
490 static void dpp_free(struct devpath *dpp)
491 {
492         if (dpp->stats)
493                 free(dpp->stats);
494         if (dpp->ios)
495                 free(dpp->ios);
496         if (dpp->path)
497                 free(dpp->path);
498         if (dpp->buts_name)
499                 free(dpp->buts_name);
500         free(dpp);
501 }
502
503 static int lock_on_cpu(int cpu)
504 {
505         cpu_set_t cpu_mask;
506
507         CPU_ZERO(&cpu_mask);
508         CPU_SET(cpu, &cpu_mask);
509         if (sched_setaffinity(getpid(), sizeof(cpu_mask), &cpu_mask) < 0)
510                 return errno;
511
512         return 0;
513 }
514
515 /*
516  * Create a timespec 'msec' milliseconds into the future
517  */
518 static inline void make_timespec(struct timespec *tsp, long delta_msec)
519 {
520         struct timeval now;
521
522         gettimeofday(&now, NULL);
523         tsp->tv_sec = now.tv_sec;
524         tsp->tv_nsec = 1000L * now.tv_usec;
525
526         tsp->tv_nsec += (delta_msec * 1000000L);
527         if (tsp->tv_nsec > 1000000000L) {
528                 long secs = tsp->tv_nsec / 1000000000L;
529
530                 tsp->tv_sec += secs;
531                 tsp->tv_nsec -= (secs * 1000000000L);
532         }
533 }
534
535 static int increase_limit(int resource, rlim_t increase)
536 {
537         struct rlimit rlim;
538         int save_errno = errno;
539
540         if (!getrlimit(resource, &rlim)) {
541                 rlim.rlim_cur += increase;
542                 if (rlim.rlim_cur >= rlim.rlim_max)
543                         rlim.rlim_max = rlim.rlim_cur + increase;
544
545                 if (!setrlimit(resource, &rlim))
546                         return 1;
547         }
548
549         errno = save_errno;
550         return 0;
551 }
552
553 static int handle_open_failure(void)
554 {
555         if (errno == ENFILE || errno == EMFILE)
556                 return increase_limit(RLIMIT_NOFILE, 16);
557         return 0;
558 }
559
560 static int handle_mem_failure(size_t length)
561 {
562         if (errno == ENFILE)
563                 return handle_open_failure();
564         else if (errno == ENOMEM)
565                 return increase_limit(RLIMIT_MEMLOCK, 2 * length);
566         return 0;
567 }
568
569 static FILE *my_fopen(const char *path, const char *mode)
570 {
571         FILE *fp;
572
573         do {
574                 fp = fopen(path, mode);
575         } while (fp == NULL && handle_open_failure());
576
577         return fp;
578 }
579
580 static int my_open(const char *path, int flags)
581 {
582         int fd;
583
584         do {
585                 fd = open(path, flags);
586         } while (fd < 0 && handle_open_failure());
587
588         return fd;
589 }
590
591 static int my_socket(int domain, int type, int protocol)
592 {
593         int fd;
594
595         do {
596                 fd = socket(domain, type, protocol);
597         } while (fd < 0 && handle_open_failure());
598
599         return fd;
600 }
601
602 static void *my_mmap(void *addr, size_t length, int prot, int flags, int fd,
603                      off_t offset)
604 {
605         void *new;
606
607         do {
608                 new = mmap(addr, length, prot, flags, fd, offset);
609         } while (new == MAP_FAILED && handle_mem_failure(length));
610
611         return new;
612 }
613
614 static int my_mlock(const void *addr, size_t len)
615 {
616         int ret;
617
618         do {
619                 ret = mlock(addr, len);
620         } while (ret < 0 && handle_mem_failure(len));
621
622         return ret;
623 }
624
625 static int __stop_trace(int fd)
626 {
627         /*
628          * Should be stopped, don't complain if it isn't
629          */
630         ioctl(fd, BLKTRACESTOP);
631         return ioctl(fd, BLKTRACETEARDOWN);
632 }
633
634 static int write_data(char *buf, int len)
635 {
636         int ret;
637
638 rewrite:
639         ret = fwrite(buf, len, 1, pfp);
640         if (ferror(pfp) || ret != 1) {
641                 if (errno == EINTR) {
642                         clearerr(pfp);
643                         goto rewrite;
644                 }
645
646                 if (!piped_output || (errno != EPIPE && errno != EBADF)) {
647                         fprintf(stderr, "write(%d) failed: %d/%s\n",
648                                 len, errno, strerror(errno));
649                 }
650                 goto err;
651         }
652
653         fflush(pfp);
654         return 0;
655
656 err:
657         clearerr(pfp);
658         return 1;
659 }
660
661 /*
662  * Returns the number of bytes read (successfully)
663  */
664 static int __net_recv_data(int fd, void *buf, unsigned int len)
665 {
666         unsigned int bytes_left = len;
667
668         while (bytes_left && !done) {
669                 int ret = recv(fd, buf, bytes_left, MSG_WAITALL);
670
671                 if (ret == 0)
672                         break;
673                 else if (ret < 0) {
674                         if (errno != EAGAIN) {
675                                 perror("server: net_recv_data: recv failed");
676                                 break;
677                         } else
678                                 break;
679                 } else {
680                         buf += ret;
681                         bytes_left -= ret;
682                 }
683         }
684
685         return len - bytes_left;
686 }
687
688 static int net_recv_data(int fd, void *buf, unsigned int len)
689 {
690         return __net_recv_data(fd, buf, len);
691 }
692
693 /*
694  * Returns number of bytes written
695  */
696 static int net_send_data(int fd, void *buf, unsigned int buf_len)
697 {
698         int ret;
699         unsigned int bytes_left = buf_len;
700
701         while (bytes_left) {
702                 ret = send(fd, buf, bytes_left, 0);
703                 if (ret < 0) {
704                         perror("send");
705                         break;
706                 }
707
708                 buf += ret;
709                 bytes_left -= ret;
710         }
711
712         return buf_len - bytes_left;
713 }
714
715 static int net_send_header(int fd, int cpu, char *buts_name, int len)
716 {
717         struct blktrace_net_hdr hdr;
718
719         memset(&hdr, 0, sizeof(hdr));
720
721         hdr.magic = BLK_IO_TRACE_MAGIC;
722         strncpy(hdr.buts_name, buts_name, sizeof(hdr.buts_name));
723         hdr.buts_name[sizeof(hdr.buts_name)-1] = '\0';
724         hdr.cpu = cpu;
725         hdr.max_cpus = ncpus;
726         hdr.len = len;
727         hdr.cl_id = getpid();
728         hdr.buf_size = buf_size;
729         hdr.buf_nr = buf_nr;
730         hdr.page_size = pagesize;
731
732         return net_send_data(fd, &hdr, sizeof(hdr)) != sizeof(hdr);
733 }
734
735 static void net_send_open_close(int fd, int cpu, char *buts_name, int len)
736 {
737         struct blktrace_net_hdr ret_hdr;
738
739         net_send_header(fd, cpu, buts_name, len);
740         net_recv_data(fd, &ret_hdr, sizeof(ret_hdr));
741 }
742
743 static void net_send_open(int fd, int cpu, char *buts_name)
744 {
745         net_send_open_close(fd, cpu, buts_name, 0);
746 }
747
748 static void net_send_close(int fd, char *buts_name, int drops)
749 {
750         /*
751          * Overload CPU w/ number of drops
752          *
753          * XXX: Need to clear/set done around call - done=1 (which
754          * is true here) stops reads from happening... :-(
755          */
756         done = 0;
757         net_send_open_close(fd, drops, buts_name, 1);
758         done = 1;
759 }
760
761 static void ack_open_close(int fd, char *buts_name)
762 {
763         net_send_header(fd, 0, buts_name, 2);
764 }
765
766 static void net_send_drops(int fd)
767 {
768         struct list_head *p;
769
770         __list_for_each(p, &devpaths) {
771                 struct devpath *dpp = list_entry(p, struct devpath, head);
772
773                 net_send_close(fd, dpp->buts_name, dpp->drops);
774         }
775 }
776
777 /*
778  * Returns:
779  *       0: "EOF"
780  *       1: OK
781  *      -1: Error
782  */
783 static int net_get_header(struct cl_conn *nc, struct blktrace_net_hdr *bnh)
784 {
785         int bytes_read;
786         int fl = fcntl(nc->fd, F_GETFL);
787
788         fcntl(nc->fd, F_SETFL, fl | O_NONBLOCK);
789         bytes_read = __net_recv_data(nc->fd, bnh, sizeof(*bnh));
790         fcntl(nc->fd, F_SETFL, fl & ~O_NONBLOCK);
791
792         if (bytes_read == sizeof(*bnh))
793                 return 1;
794         else if (bytes_read == 0)
795                 return 0;
796         return -1;
797 }
798
799 static int net_setup_client(void)
800 {
801         int fd;
802         struct sockaddr_in addr;
803
804         memset(&addr, 0, sizeof(addr));
805         addr.sin_family = AF_INET;
806         addr.sin_port = htons(net_port);
807
808         if (inet_aton(hostname, &addr.sin_addr) != 1) {
809                 struct hostent *hent = gethostbyname(hostname);
810                 if (!hent) {
811                         perror("gethostbyname");
812                         return 1;
813                 }
814
815                 memcpy(&addr.sin_addr, hent->h_addr, 4);
816                 strcpy(hostname, hent->h_name);
817         }
818
819         fd = my_socket(AF_INET, SOCK_STREAM, 0);
820         if (fd < 0) {
821                 perror("client: socket");
822                 return -1;
823         }
824
825         if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
826                 if (errno == ECONNREFUSED)
827                         fprintf(stderr,
828                                 "\nclient: Connection to %s refused, "
829                                 "perhaps the server is not started?\n\n",
830                                 hostname);
831                 else
832                         perror("client: connect");
833                 close(fd);
834                 return -1;
835         }
836
837         return fd;
838 }
839
840 static int open_client_connections(void)
841 {
842         int cpu;
843
844         cl_fds = calloc(ncpus, sizeof(*cl_fds));
845         for (cpu = 0; cpu < ncpus; cpu++) {
846                 cl_fds[cpu] = net_setup_client();
847                 if (cl_fds[cpu] < 0)
848                         goto err;
849         }
850         return 0;
851
852 err:
853         while (cpu > 0)
854                 close(cl_fds[cpu--]);
855         free(cl_fds);
856         return 1;
857 }
858
859 static void close_client_connections(void)
860 {
861         if (cl_fds) {
862                 int cpu, *fdp;
863
864                 for (cpu = 0, fdp = cl_fds; cpu < ncpus; cpu++, fdp++) {
865                         if (*fdp >= 0) {
866                                 net_send_drops(*fdp);
867                                 net_close_connection(fdp);
868                         }
869                 }
870                 free(cl_fds);
871         }
872 }
873
874 static void setup_buts(void)
875 {
876         struct list_head *p;
877
878         __list_for_each(p, &devpaths) {
879                 struct blk_user_trace_setup buts;
880                 struct devpath *dpp = list_entry(p, struct devpath, head);
881
882                 memset(&buts, 0, sizeof(buts));
883                 buts.buf_size = buf_size;
884                 buts.buf_nr = buf_nr;
885                 buts.act_mask = act_mask;
886
887                 if (ioctl(dpp->fd, BLKTRACESETUP, &buts) < 0) {
888                         fprintf(stderr, "BLKTRACESETUP(2) %s failed: %d/%s\n",
889                                 dpp->path, errno, strerror(errno));
890                         continue;
891                 } else if (ioctl(dpp->fd, BLKTRACESTART) < 0) {
892                         fprintf(stderr, "BLKTRACESTART %s failed: %d/%s\n",
893                                 dpp->path, errno, strerror(errno));
894                         continue;
895                 }
896
897                 dpp->ncpus = ncpus;
898                 dpp->buts_name = strdup(buts.name);
899                 if (dpp->stats)
900                         free(dpp->stats);
901                 dpp->stats = calloc(dpp->ncpus, sizeof(*dpp->stats));
902                 memset(dpp->stats, 0, dpp->ncpus * sizeof(*dpp->stats));
903         }
904 }
905
906 static int get_drops(struct devpath *dpp)
907 {
908         int fd, drops = 0;
909         char fn[MAXPATHLEN + 64], tmp[256];
910
911         snprintf(fn, sizeof(fn), "%s/block/%s/dropped", debugfs_path,
912                  dpp->buts_name);
913
914         fd = my_open(fn, O_RDONLY);
915         if (fd < 0) {
916                 /*
917                  * This may be ok: the kernel may not support
918                  * dropped counts.
919                  */
920                 if (errno != ENOENT)
921                         fprintf(stderr, "Could not open %s: %d/%s\n",
922                                 fn, errno, strerror(errno));
923                 return 0;
924         } else if (read(fd, tmp, sizeof(tmp)) < 0) {
925                 fprintf(stderr, "Could not read %s: %d/%s\n",
926                         fn, errno, strerror(errno));
927         } else
928                 drops = atoi(tmp);
929         close(fd);
930
931         return drops;
932 }
933
934 static void get_all_drops(void)
935 {
936         struct list_head *p;
937
938         __list_for_each(p, &devpaths) {
939                 struct devpath *dpp = list_entry(p, struct devpath, head);
940                 dpp->drops = get_drops(dpp);
941         }
942 }
943
944 static inline struct trace_buf *alloc_trace_buf(int cpu, int bufsize)
945 {
946         struct trace_buf *tbp;
947
948         tbp = malloc(sizeof(*tbp) + bufsize);
949         INIT_LIST_HEAD(&tbp->head);
950         tbp->len = 0;
951         tbp->buf = (void *)(tbp + 1);
952         tbp->cpu = cpu;
953         tbp->dpp = NULL;        /* Will be set when tbp is added */
954
955         return tbp;
956 }
957
958 static void free_tracer_heads(struct devpath *dpp)
959 {
960         int cpu;
961         struct tracer_devpath_head *hd;
962
963         for (cpu = 0, hd = dpp->heads; cpu < ncpus; cpu++, hd++) {
964                 if (hd->prev)
965                         free(hd->prev);
966                 pthread_mutex_destroy(&hd->mutex);
967         }
968         free(dpp->heads);
969 }
970
971 static int setup_tracer_devpaths(void)
972 {
973         struct list_head *p;
974
975         if (net_client_use_send())
976                 if (open_client_connections())
977                         return 1;
978
979         __list_for_each(p, &devpaths) {
980                 int cpu;
981                 struct tracer_devpath_head *hd;
982                 struct devpath *dpp = list_entry(p, struct devpath, head);
983
984                 dpp->heads = calloc(ncpus, sizeof(struct tracer_devpath_head));
985                 for (cpu = 0, hd = dpp->heads; cpu < ncpus; cpu++, hd++) {
986                         INIT_LIST_HEAD(&hd->head);
987                         pthread_mutex_init(&hd->mutex, NULL);
988                         hd->prev = NULL;
989                 }
990         }
991
992         return 0;
993 }
994
995 static inline void add_trace_buf(struct devpath *dpp, int cpu,
996                                                 struct trace_buf **tbpp)
997 {
998         struct trace_buf *tbp = *tbpp;
999         struct tracer_devpath_head *hd = &dpp->heads[cpu];
1000
1001         tbp->dpp = dpp;
1002
1003         pthread_mutex_lock(&hd->mutex);
1004         list_add_tail(&tbp->head, &hd->head);
1005         pthread_mutex_unlock(&hd->mutex);
1006
1007         *tbpp = alloc_trace_buf(cpu, buf_size);
1008 }
1009
1010 static inline void incr_entries(int entries_handled)
1011 {
1012         pthread_mutex_lock(&dp_mutex);
1013         if (dp_entries == 0)
1014                 pthread_cond_signal(&dp_cond);
1015         dp_entries += entries_handled;
1016         pthread_mutex_unlock(&dp_mutex);
1017 }
1018
1019 static int add_devpath(char *path)
1020 {
1021         int fd;
1022         struct devpath *dpp;
1023
1024         /*
1025          * Verify device is valid before going too far
1026          */
1027         fd = my_open(path, O_RDONLY | O_NONBLOCK);
1028         if (fd < 0) {
1029                 fprintf(stderr, "Invalid path %s specified: %d/%s\n",
1030                         path, errno, strerror(errno));
1031                 return 1;
1032         }
1033
1034         dpp = malloc(sizeof(*dpp));
1035         memset(dpp, 0, sizeof(*dpp));
1036         dpp->path = strdup(path);
1037         dpp->fd = fd;
1038         dpp->idx = ndevs++;
1039         list_add_tail(&dpp->head, &devpaths);
1040
1041         return 0;
1042 }
1043
1044 static void rel_devpaths(void)
1045 {
1046         struct list_head *p, *q;
1047
1048         list_for_each_safe(p, q, &devpaths) {
1049                 struct devpath *dpp = list_entry(p, struct devpath, head);
1050
1051                 list_del(&dpp->head);
1052                 __stop_trace(dpp->fd);
1053                 close(dpp->fd);
1054
1055                 if (dpp->heads)
1056                         free_tracer_heads(dpp);
1057
1058                 dpp_free(dpp);
1059                 ndevs--;
1060         }
1061 }
1062
1063 static int flush_subbuf_net(struct trace_buf *tbp)
1064 {
1065         int fd = cl_fds[tbp->cpu];
1066         struct devpath *dpp = tbp->dpp;
1067
1068         if (net_send_header(fd, tbp->cpu, dpp->buts_name, tbp->len))
1069                 return 1;
1070
1071         if (net_send_data(fd, tbp->buf, tbp->len) != tbp->len)
1072                 return 1;
1073
1074         return 0;
1075 }
1076
1077 static int
1078 handle_list_net(__attribute__((__unused__))struct tracer_devpath_head *hd,
1079                 struct list_head *list)
1080 {
1081         struct trace_buf *tbp;
1082         struct list_head *p, *q;
1083         int entries_handled = 0;
1084
1085         list_for_each_safe(p, q, list) {
1086                 tbp = list_entry(p, struct trace_buf, head);
1087
1088                 list_del(&tbp->head);
1089                 entries_handled++;
1090
1091                 if (cl_fds[tbp->cpu] >= 0) {
1092                         if (flush_subbuf_net(tbp)) {
1093                                 close(cl_fds[tbp->cpu]);
1094                                 cl_fds[tbp->cpu] = -1;
1095                         }
1096                 }
1097
1098                 free(tbp);
1099         }
1100
1101         return entries_handled;
1102 }
1103
1104 static int handle_list_file(struct tracer_devpath_head *hd,
1105                             struct list_head *list)
1106 {
1107         int off, t_len, nevents;
1108         struct blk_io_trace *t;
1109         struct list_head *p, *q;
1110         int entries_handled = 0;
1111         struct trace_buf *tbp, *prev;
1112
1113         prev = hd->prev;
1114         list_for_each_safe(p, q, list) {
1115                 tbp = list_entry(p, struct trace_buf, head);
1116                 list_del(&tbp->head);
1117                 entries_handled++;
1118
1119                 /*
1120                  * If there was some leftover before, tack this new
1121                  * entry onto the tail of the previous one.
1122                  */
1123                 if (prev) {
1124                         unsigned long tot_len;
1125                         struct trace_buf *tmp = tbp;
1126
1127                         tbp = prev;
1128                         prev = NULL;
1129
1130                         tot_len = tbp->len + tmp->len;
1131                         if (tot_len > buf_size) {
1132                                 /*
1133                                  * tbp->head isn't connected (it was 'prev'
1134                                  * so it had been taken off of the list
1135                                  * before). Therefore, we can realloc
1136                                  * the whole structures, as the other fields
1137                                  * are "static".
1138                                  */
1139                                 tbp = realloc(tbp->buf, sizeof(*tbp) + tot_len);
1140                                 tbp->buf = (void *)(tbp + 1);
1141                         }
1142
1143                         memcpy(tbp->buf + tbp->len, tmp->buf, tmp->len);
1144                         tbp->len = tot_len;
1145
1146                         free(tmp);
1147                 }
1148
1149                 /*
1150                  * See how many whole traces there are - send them
1151                  * all out in one go.
1152                  */
1153                 off = 0;
1154                 nevents = 0;
1155                 while (off + (int)sizeof(*t) <= tbp->len) {
1156                         t = (struct blk_io_trace *)(tbp->buf + off);
1157                         t_len = sizeof(*t) + t->pdu_len;
1158                         if (off + t_len > tbp->len)
1159                                 break;
1160
1161                         off += t_len;
1162                         nevents++;
1163                 }
1164                 if (nevents)
1165                         pdc_nev_update(tbp->dpp, tbp->cpu, nevents);
1166
1167                 /*
1168                  * Write any full set of traces, any remaining data is kept
1169                  * for the next pass.
1170                  */
1171                 if (off) {
1172                         if (write_data(tbp->buf, off) || off == tbp->len)
1173                                 free(tbp);
1174                         else {
1175                                 /*
1176                                  * Move valid data to beginning of buffer
1177                                  */
1178                                 tbp->len -= off;
1179                                 memmove(tbp->buf, tbp->buf + off, tbp->len);
1180                                 prev = tbp;
1181                         }
1182                 } else
1183                         prev = tbp;
1184         }
1185         hd->prev = prev;
1186
1187         return entries_handled;
1188 }
1189
1190 static void __process_trace_bufs(void)
1191 {
1192         int cpu;
1193         struct list_head *p;
1194         struct list_head list;
1195         int handled = 0;
1196
1197         __list_for_each(p, &devpaths) {
1198                 struct devpath *dpp = list_entry(p, struct devpath, head);
1199                 struct tracer_devpath_head *hd = dpp->heads;
1200
1201                 for (cpu = 0; cpu < ncpus; cpu++, hd++) {
1202                         pthread_mutex_lock(&hd->mutex);
1203                         if (list_empty(&hd->head)) {
1204                                 pthread_mutex_unlock(&hd->mutex);
1205                                 continue;
1206                         }
1207
1208                         list_replace_init(&hd->head, &list);
1209                         pthread_mutex_unlock(&hd->mutex);
1210
1211                         handled += handle_list(hd, &list);
1212                 }
1213         }
1214
1215         if (handled) {
1216                 pthread_mutex_lock(&dp_mutex);
1217                 dp_entries -= handled;
1218                 pthread_mutex_unlock(&dp_mutex);
1219         }
1220 }
1221
1222 static void process_trace_bufs(void)
1223 {
1224         while (!done) {
1225                 pthread_mutex_lock(&dp_mutex);
1226                 while (!done && dp_entries == 0) {
1227                         struct timespec ts;
1228
1229                         make_timespec(&ts, 50);
1230                         pthread_cond_timedwait(&dp_cond, &dp_mutex, &ts);
1231                 }
1232                 pthread_mutex_unlock(&dp_mutex);
1233
1234                 __process_trace_bufs();
1235         }
1236 }
1237
1238 static void clean_trace_bufs(void)
1239 {
1240         /*
1241          * No mutex needed here: we're only reading from the lists,
1242          * tracers are done
1243          */
1244         while (dp_entries)
1245                 __process_trace_bufs();
1246 }
1247
1248 static inline void read_err(int cpu, char *ifn)
1249 {
1250         if (errno != EAGAIN)
1251                 fprintf(stderr, "Thread %d failed read of %s: %d/%s\n",
1252                         cpu, ifn, errno, strerror(errno));
1253 }
1254
1255 static int net_sendfile(struct io_info *iop)
1256 {
1257         int ret;
1258
1259         ret = sendfile(iop->ofd, iop->ifd, NULL, iop->ready);
1260         if (ret < 0) {
1261                 perror("sendfile");
1262                 return 1;
1263         } else if (ret < (int)iop->ready) {
1264                 fprintf(stderr, "short sendfile send (%d of %d)\n",
1265                         ret, iop->ready);
1266                 return 1;
1267         }
1268
1269         return 0;
1270 }
1271
1272 static inline int net_sendfile_data(struct tracer *tp, struct io_info *iop)
1273 {
1274         struct devpath *dpp = iop->dpp;
1275
1276         if (net_send_header(iop->ofd, tp->cpu, dpp->buts_name, iop->ready))
1277                 return 1;
1278         return net_sendfile(iop);
1279 }
1280
1281 static int handle_pfds_netclient(struct tracer *tp, int nevs, int force_read)
1282 {
1283         struct stat sb;
1284         int i, nentries = 0;
1285         struct pdc_stats *sp;
1286         struct pollfd *pfd = tp->pfds;
1287         struct io_info *iop = tp->ios;
1288
1289         for (i = 0; nevs > 0 && i < ndevs; i++, pfd++, iop++, sp++) {
1290                 if (pfd->revents & POLLIN || force_read) {
1291                         if (fstat(iop->ifd, &sb) < 0) {
1292                                 perror(iop->ifn);
1293                                 pfd->events = 0;
1294                         } else if (sb.st_size > (off_t)iop->data_queued) {
1295                                 iop->ready = sb.st_size - iop->data_queued;
1296                                 iop->data_queued = sb.st_size;
1297                                 if (!net_sendfile_data(tp, iop)) {
1298                                         pdc_dr_update(iop->dpp, tp->cpu,
1299                                                       iop->ready);
1300                                         nentries++;
1301                                 } else
1302                                         clear_events(pfd);
1303                         }
1304                         nevs--;
1305                 }
1306         }
1307
1308         if (nentries)
1309                 incr_entries(nentries);
1310
1311         return nentries;
1312 }
1313
1314 static int handle_pfds_entries(struct tracer *tp, int nevs, int force_read)
1315 {
1316         int i, nentries = 0;
1317         struct trace_buf *tbp;
1318         struct pollfd *pfd = tp->pfds;
1319         struct io_info *iop = tp->ios;
1320
1321         tbp = alloc_trace_buf(tp->cpu, buf_size);
1322         for (i = 0; i < ndevs; i++, pfd++, iop++) {
1323                 if (pfd->revents & POLLIN || force_read) {
1324                         tbp->len = read(iop->ifd, tbp->buf, buf_size);
1325                         if (tbp->len > 0) {
1326                                 pdc_dr_update(iop->dpp, tp->cpu, tbp->len);
1327                                 add_trace_buf(iop->dpp, tp->cpu, &tbp);
1328                                 nentries++;
1329                         } else if (tbp->len == 0) {
1330                                 /*
1331                                  * Short reads after we're done stop us
1332                                  * from trying reads.
1333                                  */
1334                                 if (tp->is_done)
1335                                         clear_events(pfd);
1336                         } else {
1337                                 read_err(tp->cpu, iop->ifn);
1338                                 if (errno != EAGAIN || tp->is_done)
1339                                         clear_events(pfd);
1340                         }
1341                         if (!piped_output && --nevs == 0)
1342                                 break;
1343                 }
1344         }
1345         free(tbp);
1346
1347         if (nentries)
1348                 incr_entries(nentries);
1349
1350         return nentries;
1351 }
1352
1353 static int fill_ofname(struct io_info *iop, int cpu)
1354 {
1355         int len;
1356         struct stat sb;
1357         char *dst = iop->ofn;
1358
1359         if (output_dir)
1360                 len = snprintf(iop->ofn, sizeof(iop->ofn), "%s/", output_dir);
1361         else
1362                 len = snprintf(iop->ofn, sizeof(iop->ofn), "./");
1363
1364         if (net_mode == Net_server) {
1365                 struct cl_conn *nc = iop->nc;
1366
1367                 len += sprintf(dst + len, "%s-", nc->ch->hostname);
1368                 len += strftime(dst + len, 64, "%F-%T/",
1369                                 gmtime(&iop->dpp->cl_connect_time));
1370         }
1371
1372         if (stat(iop->ofn, &sb) < 0) {
1373                 if (errno != ENOENT) {
1374                         fprintf(stderr,
1375                                 "Destination dir %s stat failed: %d/%s\n",
1376                                 iop->ofn, errno, strerror(errno));
1377                         return 1;
1378                 }
1379                 if (mkdir(iop->ofn, 0755) < 0) {
1380                         fprintf(stderr,
1381                                 "Destination dir %s can't be made: %d/%s\n",
1382                                 iop->ofn, errno, strerror(errno));
1383                         return 1;
1384                 }
1385         }
1386
1387         if (output_name)
1388                 snprintf(iop->ofn + len, sizeof(iop->ofn), "%s.blktrace.%d",
1389                          output_name, cpu);
1390         else
1391                 snprintf(iop->ofn + len, sizeof(iop->ofn), "%s.blktrace.%d",
1392                          iop->dpp->buts_name, cpu);
1393
1394         return 0;
1395 }
1396
1397 static int set_vbuf(struct io_info *iop, int mode, size_t size)
1398 {
1399         iop->obuf = malloc(size);
1400         if (setvbuf(iop->ofp, iop->obuf, mode, size) < 0) {
1401                 fprintf(stderr, "setvbuf(%s, %d) failed: %d/%s\n",
1402                         iop->dpp->path, (int)size, errno,
1403                         strerror(errno));
1404                 free(iop->obuf);
1405                 return 1;
1406         }
1407
1408         return 0;
1409 }
1410
1411 static int iop_open(struct io_info *iop, int cpu)
1412 {
1413         iop->ofd = -1;
1414         if (fill_ofname(iop, cpu))
1415                 return 1;
1416
1417         iop->ofp = my_fopen(iop->ofn, "w+");
1418         if (iop->ofp == NULL) {
1419                 fprintf(stderr, "Open output file %s failed: %d/%s\n",
1420                         iop->ofn, errno, strerror(errno));
1421                 return 1;
1422         }
1423         if (set_vbuf(iop, _IOLBF, FILE_VBUF_SIZE)) {
1424                 fprintf(stderr, "set_vbuf for file %s failed: %d/%s\n",
1425                         iop->ofn, errno, strerror(errno));
1426                 fclose(iop->ofp);
1427                 return 1;
1428         }
1429
1430         iop->ofd = fileno(iop->ofp);
1431         return 0;
1432 }
1433
1434 static int open_ios(struct tracer *tp)
1435 {
1436         struct pollfd *pfd;
1437         struct io_info *iop;
1438         struct list_head *p;
1439
1440         tp->ios = calloc(ndevs, sizeof(struct io_info));
1441         tp->pfds = calloc(ndevs, sizeof(struct pollfd));
1442
1443         memset(tp->ios, 0, ndevs * sizeof(struct io_info));
1444         memset(tp->pfds, 0, ndevs * sizeof(struct pollfd));
1445
1446         tp->nios = 0;
1447         iop = tp->ios;
1448         pfd = tp->pfds;
1449         __list_for_each(p, &devpaths) {
1450                 struct devpath *dpp = list_entry(p, struct devpath, head);
1451
1452                 iop->dpp = dpp;
1453                 iop->ofd = -1;
1454                 snprintf(iop->ifn, sizeof(iop->ifn), "%s/block/%s/trace%d",
1455                         debugfs_path, dpp->buts_name, tp->cpu);
1456
1457                 iop->ifd = my_open(iop->ifn, O_RDONLY | O_NONBLOCK);
1458                 if (iop->ifd < 0) {
1459                         fprintf(stderr, "Thread %d failed open %s: %d/%s\n",
1460                                 tp->cpu, iop->ifn, errno, strerror(errno));
1461                         return 1;
1462                 }
1463
1464                 init_mmap_info(&iop->mmap_info);
1465
1466                 pfd->fd = iop->ifd;
1467                 pfd->events = POLLIN;
1468
1469                 if (piped_output)
1470                         ;
1471                 else if (net_client_use_sendfile()) {
1472                         iop->ofd = net_setup_client();
1473                         if (iop->ofd < 0)
1474                                 goto err;
1475                         net_send_open(iop->ofd, tp->cpu, dpp->buts_name);
1476                 } else if (net_mode == Net_none) {
1477                         if (iop_open(iop, tp->cpu))
1478                                 goto err;
1479                 } else {
1480                         /*
1481                          * This ensures that the server knows about all
1482                          * connections & devices before _any_ closes
1483                          */
1484                         net_send_open(cl_fds[tp->cpu], tp->cpu, dpp->buts_name);
1485                 }
1486
1487                 pfd++;
1488                 iop++;
1489                 tp->nios++;
1490         }
1491
1492         return 0;
1493
1494 err:
1495         close(iop->ifd);        /* tp->nios _not_ bumped */
1496         return 1;
1497 }
1498
1499 static void close_iop(struct io_info *iop)
1500 {
1501         struct mmap_info *mip = &iop->mmap_info;
1502
1503         if (mip->fs_buf)
1504                 munmap(mip->fs_buf, mip->fs_buf_len);
1505
1506         if (!piped_output) {
1507                 if (ftruncate(fileno(iop->ofp), mip->fs_size) < 0) {
1508                         fprintf(stderr,
1509                                 "Ignoring err: ftruncate(%s): %d/%s\n",
1510                                 iop->ofn, errno, strerror(errno));
1511                 }
1512         }
1513
1514         if (iop->ofp)
1515                 fclose(iop->ofp);
1516         if (iop->obuf)
1517                 free(iop->obuf);
1518 }
1519
1520 static void close_ios(struct tracer *tp)
1521 {
1522         while (tp->nios > 0) {
1523                 struct io_info *iop = &tp->ios[--tp->nios];
1524
1525                 iop->dpp->drops = get_drops(iop->dpp);
1526                 if (iop->ifd >= 0)
1527                         close(iop->ifd);
1528
1529                 if (iop->ofp)
1530                         close_iop(iop);
1531                 else if (iop->ofd >= 0) {
1532                         struct devpath *dpp = iop->dpp;
1533
1534                         net_send_close(iop->ofd, dpp->buts_name, dpp->drops);
1535                         net_close_connection(&iop->ofd);
1536                 }
1537         }
1538
1539         free(tp->ios);
1540         free(tp->pfds);
1541 }
1542
1543 static int setup_mmap(int fd, unsigned int maxlen, struct mmap_info *mip)
1544 {
1545         if (mip->fs_off + maxlen > mip->fs_buf_len) {
1546                 unsigned long nr = max(16, mip->buf_nr);
1547
1548                 if (mip->fs_buf) {
1549                         munlock(mip->fs_buf, mip->fs_buf_len);
1550                         munmap(mip->fs_buf, mip->fs_buf_len);
1551                         mip->fs_buf = NULL;
1552                 }
1553
1554                 mip->fs_off = mip->fs_size & (mip->pagesize - 1);
1555                 mip->fs_buf_len = (nr * mip->buf_size) - mip->fs_off;
1556                 mip->fs_max_size += mip->fs_buf_len;
1557
1558                 if (ftruncate(fd, mip->fs_max_size) < 0) {
1559                         perror("__setup_mmap: ftruncate");
1560                         return 1;
1561                 }
1562
1563                 mip->fs_buf = my_mmap(NULL, mip->fs_buf_len, PROT_WRITE,
1564                                       MAP_SHARED, fd,
1565                                       mip->fs_size - mip->fs_off);
1566                 if (mip->fs_buf == MAP_FAILED) {
1567                         perror("__setup_mmap: mmap");
1568                         return 1;
1569                 }
1570                 my_mlock(mip->fs_buf, mip->fs_buf_len);
1571         }
1572
1573         return 0;
1574 }
1575
1576 static int handle_pfds_file(struct tracer *tp, int nevs, int force_read)
1577 {
1578         struct mmap_info *mip;
1579         int i, ret, nentries = 0;
1580         struct pollfd *pfd = tp->pfds;
1581         struct io_info *iop = tp->ios;
1582
1583         for (i = 0; nevs > 0 && i < ndevs; i++, pfd++, iop++) {
1584                 if (pfd->revents & POLLIN || force_read) {
1585                         mip = &iop->mmap_info;
1586
1587                         ret = setup_mmap(iop->ofd, buf_size, mip);
1588                         if (ret < 0) {
1589                                 pfd->events = 0;
1590                                 break;
1591                         }
1592
1593                         ret = read(iop->ifd, mip->fs_buf + mip->fs_off,
1594                                    buf_size);
1595                         if (ret > 0) {
1596                                 pdc_dr_update(iop->dpp, tp->cpu, ret);
1597                                 mip->fs_size += ret;
1598                                 mip->fs_off += ret;
1599                                 nentries++;
1600                         } else if (ret == 0) {
1601                                 /*
1602                                  * Short reads after we're done stop us
1603                                  * from trying reads.
1604                                  */
1605                                 if (tp->is_done)
1606                                         clear_events(pfd);
1607                         } else {
1608                                 read_err(tp->cpu, iop->ifn);
1609                                 if (errno != EAGAIN || tp->is_done)
1610                                         clear_events(pfd);
1611                         }
1612                         nevs--;
1613                 }
1614         }
1615
1616         return nentries;
1617 }
1618
1619 static void *thread_main(void *arg)
1620 {
1621         int ret, ndone;
1622         int to_val;
1623
1624         struct tracer *tp = arg;
1625
1626         ret = lock_on_cpu(tp->cpu);
1627         if (ret)
1628                 goto err;
1629
1630         ret = open_ios(tp);
1631         if (ret) {
1632                 close_ios(tp);
1633                 goto err;
1634         }
1635
1636         pthread_mutex_lock(&tp->mutex);
1637         tp->running = 1;
1638         pthread_cond_signal(&tp->cond);
1639         pthread_mutex_unlock(&tp->mutex);
1640
1641         if (piped_output)
1642                 to_val = 50;            /* Frequent partial handles */
1643         else
1644                 to_val = 500;           /* 1/2 second intervals */
1645
1646         while (!tp->is_done) {
1647                 ndone = poll(tp->pfds, ndevs, to_val);
1648                 if (ndone || piped_output)
1649                         (void)handle_pfds(tp, ndone, piped_output);
1650                 else if (ndone < 0 && errno != EINTR)
1651                         fprintf(stderr, "Thread %d poll failed: %d/%s\n",
1652                                 tp->cpu, errno, strerror(errno));
1653         }
1654
1655         /*
1656          * Trace is stopped, pull data until we get a short read
1657          */
1658         while (handle_pfds(tp, ndevs, 1) > 0)
1659                 ;
1660
1661         close_ios(tp);
1662
1663 err:
1664         pthread_mutex_lock(&tp->mutex);
1665         tp->running = 0;
1666         tp->status = ret;
1667         pthread_cond_signal(&tp->cond);
1668         pthread_mutex_unlock(&tp->mutex);
1669         return NULL;
1670 }
1671
1672 static int start_tracer(int cpu)
1673 {
1674         struct tracer *tp;
1675
1676         tp = malloc(sizeof(*tp));
1677         memset(tp, 0, sizeof(*tp));
1678
1679         INIT_LIST_HEAD(&tp->head);
1680         pthread_mutex_init(&tp->mutex, NULL);
1681         pthread_cond_init(&tp->cond, NULL);
1682         tp->running = 0;
1683         tp->status = 0;
1684         tp->cpu = cpu;
1685
1686         if (pthread_create(&tp->thread, NULL, thread_main, tp)) {
1687                 fprintf(stderr, "FAILED to start thread on CPU %d: %d/%s\n",
1688                         cpu, errno, strerror(errno));
1689                 goto err;
1690         }
1691
1692         pthread_mutex_lock(&tp->mutex);
1693         while (!tp->running && (tp->status == 0))
1694                 pthread_cond_wait(&tp->cond, &tp->mutex);
1695         pthread_mutex_unlock(&tp->mutex);
1696
1697         if (tp->status == 0) {
1698                 list_add_tail(&tp->head, &tracers);
1699                 return 0;
1700         }
1701
1702         fprintf(stderr, "FAILED to start thread on CPU %d\n", cpu);
1703
1704 err:
1705         pthread_mutex_destroy(&tp->mutex);
1706         pthread_cond_destroy(&tp->cond);
1707         free(tp);
1708         return 1;
1709 }
1710
1711 static int start_tracers(void)
1712 {
1713         int cpu;
1714
1715         for (cpu = 0; cpu < ncpus; cpu++)
1716                 if (start_tracer(cpu))
1717                         break;
1718
1719         return cpu;
1720 }
1721
1722 static void stop_tracers(void)
1723 {
1724         struct list_head *p;
1725
1726         /*
1727          * Stop the tracing - makes the tracer threads clean up quicker.
1728          */
1729         __list_for_each(p, &devpaths) {
1730                 struct devpath *dpp = list_entry(p, struct devpath, head);
1731                 (void)ioctl(dpp->fd, BLKTRACESTOP);
1732         }
1733
1734         /*
1735          * Tell each tracer to quit
1736          */
1737         __list_for_each(p, &tracers) {
1738                 struct tracer *tp = list_entry(p, struct tracer, head);
1739                 tp->is_done = 1;
1740         }
1741 }
1742
1743 static void del_tracers(void)
1744 {
1745         struct list_head *p, *q;
1746
1747         list_for_each_safe(p, q, &tracers) {
1748                 struct tracer *tp = list_entry(p, struct tracer, head);
1749
1750                 list_del(&tp->head);
1751                 free(tp);
1752         }
1753         ntracers = 0;
1754 }
1755
1756 static void wait_tracers(void)
1757 {
1758         struct list_head *p;
1759
1760         if (use_tracer_devpaths())
1761                 process_trace_bufs();
1762
1763         __list_for_each(p, &tracers) {
1764                 int ret;
1765                 struct tracer *tp = list_entry(p, struct tracer, head);
1766
1767                 pthread_mutex_lock(&tp->mutex);
1768                 while (tp->running)
1769                         pthread_cond_wait(&tp->cond, &tp->mutex);
1770                 pthread_mutex_unlock(&tp->mutex);
1771
1772                 ret = pthread_join(tp->thread, NULL);
1773                 if (ret)
1774                         fprintf(stderr, "Thread join %d failed %d\n",
1775                                 tp->cpu, ret);
1776         }
1777
1778         if (use_tracer_devpaths())
1779                 clean_trace_bufs();
1780
1781         get_all_drops();
1782 }
1783
1784 static void exit_tracing(void)
1785 {
1786         signal(SIGINT, SIG_IGN);
1787         signal(SIGHUP, SIG_IGN);
1788         signal(SIGTERM, SIG_IGN);
1789         signal(SIGALRM, SIG_IGN);
1790
1791         stop_tracers();
1792         wait_tracers();
1793         del_tracers();
1794         rel_devpaths();
1795 }
1796
1797 static void handle_sigint(__attribute__((__unused__)) int sig)
1798 {
1799         done = 1;
1800         stop_tracers();
1801 }
1802
1803 static void show_stats(struct list_head *devpaths)
1804 {
1805         FILE *ofp;
1806         struct list_head *p;
1807         unsigned long long nevents, data_read;
1808         unsigned long long total_drops = 0;
1809         unsigned long long total_events = 0;
1810
1811         if (piped_output)
1812                 ofp = my_fopen("/dev/null", "w");
1813         else
1814                 ofp = stdout;
1815
1816         __list_for_each(p, devpaths) {
1817                 int cpu;
1818                 struct pdc_stats *sp;
1819                 struct devpath *dpp = list_entry(p, struct devpath, head);
1820
1821                 if (net_mode == Net_server)
1822                         printf("server: end of run for %s:%s\n",
1823                                 dpp->ch->hostname, dpp->buts_name);
1824
1825                 data_read = 0;
1826                 nevents = 0;
1827
1828                 fprintf(ofp, "=== %s ===\n", dpp->buts_name);
1829                 for (cpu = 0, sp = dpp->stats; cpu < dpp->ncpus; cpu++, sp++) {
1830                         /*
1831                          * Estimate events if not known...
1832                          */
1833                         if (sp->nevents == 0) {
1834                                 sp->nevents = sp->data_read /
1835                                                 sizeof(struct blk_io_trace);
1836                         }
1837
1838                         fprintf(ofp,
1839                                 "  CPU%3d: %20llu events, %8llu KiB data\n",
1840                                 cpu, sp->nevents, (sp->data_read + 1023) >> 10);
1841
1842                         data_read += sp->data_read;
1843                         nevents += sp->nevents;
1844                 }
1845
1846                 fprintf(ofp, "  Total:  %20llu events (dropped %llu),"
1847                              " %8llu KiB data\n", nevents,
1848                              dpp->drops, (data_read + 1024) >> 10);
1849
1850                 total_drops += dpp->drops;
1851                 total_events += (nevents + dpp->drops);
1852         }
1853
1854         fflush(ofp);
1855         if (piped_output)
1856                 fclose(ofp);
1857
1858         if (total_drops) {
1859                 double drops_ratio = 1.0;
1860
1861                 if (total_events)
1862                         drops_ratio = (double)total_drops/(double)total_events;
1863
1864                 fprintf(stderr, "\nYou have %llu (%5.1lf%%) dropped events\n"
1865                                 "Consider using a larger buffer size (-b) "
1866                                 "and/or more buffers (-n)\n",
1867                         total_drops, 100.0 * drops_ratio);
1868         }
1869 }
1870
1871 static int handle_args(int argc, char *argv[])
1872 {
1873         int c, i;
1874         struct statfs st;
1875         int act_mask_tmp = 0;
1876
1877         while ((c = getopt_long(argc, argv, S_OPTS, l_opts, NULL)) >= 0) {
1878                 switch (c) {
1879                 case 'a':
1880                         i = find_mask_map(optarg);
1881                         if (i < 0) {
1882                                 fprintf(stderr, "Invalid action mask %s\n",
1883                                         optarg);
1884                                 return 1;
1885                         }
1886                         act_mask_tmp |= i;
1887                         break;
1888
1889                 case 'A':
1890                         if ((sscanf(optarg, "%x", &i) != 1) ||
1891                                                         !valid_act_opt(i)) {
1892                                 fprintf(stderr,
1893                                         "Invalid set action mask %s/0x%x\n",
1894                                         optarg, i);
1895                                 return 1;
1896                         }
1897                         act_mask_tmp = i;
1898                         break;
1899
1900                 case 'd':
1901                         if (add_devpath(optarg) != 0)
1902                                 return 1;
1903                         break;
1904
1905                 case 'I': {
1906                         char dev_line[256];
1907                         FILE *ifp = my_fopen(optarg, "r");
1908
1909                         if (!ifp) {
1910                                 fprintf(stderr,
1911                                         "Invalid file for devices %s\n",
1912                                         optarg);
1913                                 return 1;
1914                         }
1915
1916                         while (fscanf(ifp, "%s\n", dev_line) == 1)
1917                                 if (add_devpath(dev_line) != 0)
1918                                         return 1;
1919                         break;
1920                 }
1921
1922                 case 'r':
1923                         debugfs_path = optarg;
1924                         break;
1925
1926                 case 'o':
1927                         output_name = optarg;
1928                         break;
1929                 case 'k':
1930                         kill_running_trace = 1;
1931                         break;
1932                 case 'w':
1933                         stop_watch = atoi(optarg);
1934                         if (stop_watch <= 0) {
1935                                 fprintf(stderr,
1936                                         "Invalid stopwatch value (%d secs)\n",
1937                                         stop_watch);
1938                                 return 1;
1939                         }
1940                         break;
1941                 case 'V':
1942                 case 'v':
1943                         printf("%s version %s\n", argv[0], blktrace_version);
1944                         exit(0);
1945                         /*NOTREACHED*/
1946                 case 'b':
1947                         buf_size = strtoul(optarg, NULL, 10);
1948                         if (buf_size <= 0 || buf_size > 16*1024) {
1949                                 fprintf(stderr, "Invalid buffer size (%lu)\n",
1950                                         buf_size);
1951                                 return 1;
1952                         }
1953                         buf_size <<= 10;
1954                         break;
1955                 case 'n':
1956                         buf_nr = strtoul(optarg, NULL, 10);
1957                         if (buf_nr <= 0) {
1958                                 fprintf(stderr,
1959                                         "Invalid buffer nr (%lu)\n", buf_nr);
1960                                 return 1;
1961                         }
1962                         break;
1963                 case 'D':
1964                         output_dir = optarg;
1965                         break;
1966                 case 'h':
1967                         net_mode = Net_client;
1968                         strcpy(hostname, optarg);
1969                         break;
1970                 case 'l':
1971                         net_mode = Net_server;
1972                         break;
1973                 case 'p':
1974                         net_port = atoi(optarg);
1975                         break;
1976                 case 's':
1977                         net_use_sendfile = 0;
1978                         break;
1979                 default:
1980                         show_usage(argv[0]);
1981                         exit(1);
1982                         /*NOTREACHED*/
1983                 }
1984         }
1985
1986         while (optind < argc)
1987                 if (add_devpath(argv[optind++]) != 0)
1988                         return 1;
1989
1990         if (net_mode != Net_server && ndevs == 0) {
1991                 show_usage(argv[0]);
1992                 return 1;
1993         }
1994
1995         if (statfs(debugfs_path, &st) < 0 || st.f_type != (long)DEBUGFS_TYPE) {
1996                 fprintf(stderr, "Invalid debug path %s: %d/%s\n",
1997                         debugfs_path, errno, strerror(errno));
1998                 return 1;
1999         }
2000
2001         if (act_mask_tmp != 0)
2002                 act_mask = act_mask_tmp;
2003
2004         /*
2005          * Set up for appropriate PFD handler based upon output name.
2006          */
2007         if (net_client_use_sendfile())
2008                 handle_pfds = handle_pfds_netclient;
2009         else if (net_client_use_send())
2010                 handle_pfds = handle_pfds_entries;
2011         else if (output_name && (strcmp(output_name, "-") == 0)) {
2012                 piped_output = 1;
2013                 handle_pfds = handle_pfds_entries;
2014                 pfp = stdout;
2015                 setvbuf(pfp, NULL, _IONBF, 0);
2016         } else
2017                 handle_pfds = handle_pfds_file;
2018         return 0;
2019 }
2020
2021 static void ch_add_connection(struct net_server_s *ns, struct cl_host *ch,
2022                               int fd)
2023 {
2024         struct cl_conn *nc;
2025
2026         nc = malloc(sizeof(*nc));
2027         memset(nc, 0, sizeof(*nc));
2028
2029         time(&nc->connect_time);
2030         nc->ch = ch;
2031         nc->fd = fd;
2032         nc->ncpus = -1;
2033
2034         list_add_tail(&nc->ch_head, &ch->conn_list);
2035         ch->connects++;
2036
2037         list_add_tail(&nc->ns_head, &ns->conn_list);
2038         ns->connects++;
2039         ns->pfds = realloc(ns->pfds, (ns->connects+1) * sizeof(struct pollfd));
2040 }
2041
2042 static void ch_rem_connection(struct net_server_s *ns, struct cl_host *ch,
2043                               struct cl_conn *nc)
2044 {
2045         net_close_connection(&nc->fd);
2046
2047         list_del(&nc->ch_head);
2048         ch->connects--;
2049
2050         list_del(&nc->ns_head);
2051         ns->connects--;
2052         ns->pfds = realloc(ns->pfds, (ns->connects+1) * sizeof(struct pollfd));
2053
2054         free(nc);
2055 }
2056
2057 static struct cl_host *net_find_client_host(struct net_server_s *ns,
2058                                             struct in_addr cl_in_addr)
2059 {
2060         struct list_head *p;
2061
2062         __list_for_each(p, &ns->ch_list) {
2063                 struct cl_host *ch = list_entry(p, struct cl_host, head);
2064
2065                 if (in_addr_eq(ch->cl_in_addr, cl_in_addr))
2066                         return ch;
2067         }
2068
2069         return NULL;
2070 }
2071
2072 static struct cl_host *net_add_client_host(struct net_server_s *ns,
2073                                            struct sockaddr_in *addr)
2074 {
2075         struct cl_host *ch;
2076
2077         ch = malloc(sizeof(*ch));
2078         memset(ch, 0, sizeof(*ch));
2079
2080         ch->ns = ns;
2081         ch->cl_in_addr = addr->sin_addr;
2082         list_add_tail(&ch->head, &ns->ch_list);
2083         ns->nchs++;
2084
2085         ch->hostname = strdup(inet_ntoa(addr->sin_addr));
2086         printf("server: connection from %s\n", ch->hostname);
2087
2088         INIT_LIST_HEAD(&ch->conn_list);
2089         INIT_LIST_HEAD(&ch->devpaths);
2090
2091         return ch;
2092 }
2093
2094 static void device_done(struct devpath *dpp, int ncpus)
2095 {
2096         int cpu;
2097         struct io_info *iop;
2098
2099         for (cpu = 0, iop = dpp->ios; cpu < ncpus; cpu++, iop++)
2100                 close_iop(iop);
2101
2102         list_del(&dpp->head);
2103         dpp_free(dpp);
2104 }
2105
2106 static void net_ch_remove(struct cl_host *ch, int ncpus)
2107 {
2108         struct list_head *p, *q;
2109         struct net_server_s *ns = ch->ns;
2110
2111         list_for_each_safe(p, q, &ch->devpaths) {
2112                 struct devpath *dpp = list_entry(p, struct devpath, head);
2113                 device_done(dpp, ncpus);
2114         }
2115
2116         list_for_each_safe(p, q, &ch->conn_list) {
2117                 struct cl_conn *nc = list_entry(p, struct cl_conn, ch_head);
2118
2119                 ch_rem_connection(ns, ch, nc);
2120         }
2121
2122         list_del(&ch->head);
2123         ns->nchs--;
2124
2125         if (ch->hostname)
2126                 free(ch->hostname);
2127         free(ch);
2128 }
2129
2130 static void net_add_connection(struct net_server_s *ns)
2131 {
2132         int fd;
2133         struct cl_host *ch;
2134         socklen_t socklen = sizeof(ns->addr);
2135
2136         fd = accept(ns->listen_fd, (struct sockaddr *)&ns->addr, &socklen);
2137         if (fd < 0) {
2138                 /*
2139                  * This is OK: we just won't accept this connection,
2140                  * nothing fatal.
2141                  */
2142                 perror("accept");
2143         } else {
2144                 ch = net_find_client_host(ns, ns->addr.sin_addr);
2145                 if (!ch)
2146                         ch = net_add_client_host(ns, &ns->addr);
2147
2148                 ch_add_connection(ns, ch, fd);
2149         }
2150 }
2151
2152 static struct devpath *nc_add_dpp(struct cl_conn *nc,
2153                                   struct blktrace_net_hdr *bnh,
2154                                   time_t connect_time)
2155 {
2156         int cpu;
2157         struct io_info *iop;
2158         struct devpath *dpp;
2159
2160         dpp = malloc(sizeof(*dpp));
2161         memset(dpp, 0, sizeof(*dpp));
2162
2163         dpp->buts_name = strdup(bnh->buts_name);
2164         dpp->path = strdup(bnh->buts_name);
2165         dpp->fd = -1;
2166         dpp->ch = nc->ch;
2167         dpp->cl_id = bnh->cl_id;
2168         dpp->cl_connect_time = connect_time;
2169         dpp->ncpus = nc->ncpus;
2170         dpp->stats = calloc(dpp->ncpus, sizeof(*dpp->stats));
2171         memset(dpp->stats, 0, dpp->ncpus * sizeof(*dpp->stats));
2172
2173         list_add_tail(&dpp->head, &nc->ch->devpaths);
2174         nc->ch->ndevs++;
2175
2176         dpp->ios = calloc(nc->ncpus, sizeof(*iop));
2177         memset(dpp->ios, 0, ndevs * sizeof(*iop));
2178
2179         for (cpu = 0, iop = dpp->ios; cpu < nc->ncpus; cpu++, iop++) {
2180                 iop->dpp = dpp;
2181                 iop->nc = nc;
2182                 init_mmap_info(&iop->mmap_info);
2183
2184                 if (iop_open(iop, cpu))
2185                         goto err;
2186         }
2187
2188         return dpp;
2189
2190 err:
2191         /*
2192          * Need to unravel what's been done...
2193          */
2194         while (cpu >= 0)
2195                 close_iop(&dpp->ios[cpu--]);
2196         dpp_free(dpp);
2197
2198         return NULL;
2199 }
2200
2201 static struct devpath *nc_find_dpp(struct cl_conn *nc,
2202                                    struct blktrace_net_hdr *bnh)
2203 {
2204         struct list_head *p;
2205         time_t connect_time = nc->connect_time;
2206
2207         __list_for_each(p, &nc->ch->devpaths) {
2208                 struct devpath *dpp = list_entry(p, struct devpath, head);
2209
2210                 if (!strcmp(dpp->buts_name, bnh->buts_name))
2211                         return dpp;
2212
2213                 if (dpp->cl_id == bnh->cl_id)
2214                         connect_time = dpp->cl_connect_time;
2215         }
2216
2217         return nc_add_dpp(nc, bnh, connect_time);
2218 }
2219
2220 static void net_client_read_data(struct cl_conn *nc, struct devpath *dpp,
2221                                  struct blktrace_net_hdr *bnh)
2222 {
2223         int ret;
2224         struct io_info *iop = &dpp->ios[bnh->cpu];
2225         struct mmap_info *mip = &iop->mmap_info;
2226
2227         if (setup_mmap(iop->ofd, bnh->len, &iop->mmap_info)) {
2228                 fprintf(stderr, "ncd(%s:%d): mmap failed\n",
2229                         nc->ch->hostname, nc->fd);
2230                 exit(1);
2231         }
2232
2233         ret = net_recv_data(nc->fd, mip->fs_buf + mip->fs_off, bnh->len);
2234         if (ret > 0) {
2235                 pdc_dr_update(dpp, bnh->cpu, ret);
2236                 mip->fs_size += ret;
2237                 mip->fs_off += ret;
2238         } else if (ret < 0)
2239                 exit(1);
2240 }
2241
2242 /*
2243  * Returns 1 if we closed a host - invalidates other polling information
2244  * that may be present.
2245  */
2246 static int net_client_data(struct cl_conn *nc)
2247 {
2248         int ret;
2249         struct devpath *dpp;
2250         struct blktrace_net_hdr bnh;
2251
2252         ret = net_get_header(nc, &bnh);
2253         if (ret == 0)
2254                 return 0;
2255
2256         if (ret < 0) {
2257                 fprintf(stderr, "ncd(%d): header read failed\n", nc->fd);
2258                 exit(1);
2259         }
2260
2261         if (data_is_native == -1 && check_data_endianness(bnh.magic)) {
2262                 fprintf(stderr, "ncd(%d): received data is bad\n", nc->fd);
2263                 exit(1);
2264         }
2265
2266         if (!data_is_native) {
2267                 bnh.magic = be32_to_cpu(bnh.magic);
2268                 bnh.cpu = be32_to_cpu(bnh.cpu);
2269                 bnh.max_cpus = be32_to_cpu(bnh.max_cpus);
2270                 bnh.len = be32_to_cpu(bnh.len);
2271                 bnh.cl_id = be32_to_cpu(bnh.cl_id);
2272                 bnh.buf_size = be32_to_cpu(bnh.buf_size);
2273                 bnh.buf_nr = be32_to_cpu(bnh.buf_nr);
2274                 bnh.page_size = be32_to_cpu(bnh.page_size);
2275         }
2276
2277         if ((bnh.magic & 0xffffff00) != BLK_IO_TRACE_MAGIC) {
2278                 fprintf(stderr, "ncd(%s:%d): bad data magic\n",
2279                         nc->ch->hostname, nc->fd);
2280                 exit(1);
2281         }
2282
2283         if (nc->ncpus == -1)
2284                 nc->ncpus = bnh.max_cpus;
2285
2286         /*
2287          * len == 0 means the other end is sending us a new connection/dpp
2288          * len == 1 means that the other end signalled end-of-run
2289          */
2290         dpp = nc_find_dpp(nc, &bnh);
2291         if (bnh.len == 0) {
2292                 /*
2293                  * Just adding in the dpp above is enough
2294                  */
2295                 ack_open_close(nc->fd, dpp->buts_name);
2296                 nc->ch->cl_opens++;
2297         } else if (bnh.len == 1) {
2298                 /*
2299                  * overload cpu count with dropped events
2300                  */
2301                 dpp->drops = bnh.cpu;
2302
2303                 ack_open_close(nc->fd, dpp->buts_name);
2304                 if (--nc->ch->cl_opens == 0) {
2305                         show_stats(&nc->ch->devpaths);
2306                         net_ch_remove(nc->ch, nc->ncpus);
2307                         return 1;
2308                 }
2309         } else
2310                 net_client_read_data(nc, dpp, &bnh);
2311
2312         return 0;
2313 }
2314
2315 static void handle_client_data(struct net_server_s *ns, int events)
2316 {
2317         struct cl_conn *nc;
2318         struct pollfd *pfd;
2319         struct list_head *p, *q;
2320
2321         pfd = &ns->pfds[1];
2322         list_for_each_safe(p, q, &ns->conn_list) {
2323                 if (pfd->revents & POLLIN) {
2324                         nc = list_entry(p, struct cl_conn, ns_head);
2325
2326                         if (net_client_data(nc) || --events == 0)
2327                                 break;
2328                 }
2329                 pfd++;
2330         }
2331 }
2332
2333 static void net_setup_pfds(struct net_server_s *ns)
2334 {
2335         struct pollfd *pfd;
2336         struct list_head *p;
2337
2338         ns->pfds[0].fd = ns->listen_fd;
2339         ns->pfds[0].events = POLLIN;
2340
2341         pfd = &ns->pfds[1];
2342         __list_for_each(p, &ns->conn_list) {
2343                 struct cl_conn *nc = list_entry(p, struct cl_conn, ns_head);
2344
2345                 pfd->fd = nc->fd;
2346                 pfd->events = POLLIN;
2347                 pfd++;
2348         }
2349 }
2350
2351 static int net_server_handle_connections(struct net_server_s *ns)
2352 {
2353         int events;
2354
2355         printf("server: waiting for connections...\n");
2356
2357         while (!done) {
2358                 net_setup_pfds(ns);
2359                 events = poll(ns->pfds, ns->connects + 1, -1);
2360                 if (events < 0) {
2361                         if (errno != EINTR) {
2362                                 perror("FATAL: poll error");
2363                                 return 1;
2364                         }
2365                 } else if (events > 0) {
2366                         if (ns->pfds[0].revents & POLLIN) {
2367                                 net_add_connection(ns);
2368                                 events--;
2369                         }
2370
2371                         if (events)
2372                                 handle_client_data(ns, events);
2373                 }
2374         }
2375
2376         return 0;
2377 }
2378
2379 static int net_server(void)
2380 {
2381         int fd, opt;
2382         int ret = 1;
2383         struct net_server_s net_server;
2384         struct net_server_s *ns = &net_server;
2385
2386         memset(ns, 0, sizeof(*ns));
2387         INIT_LIST_HEAD(&ns->ch_list);
2388         INIT_LIST_HEAD(&ns->conn_list);
2389         ns->pfds = malloc(sizeof(struct pollfd));
2390
2391         fd = my_socket(AF_INET, SOCK_STREAM, 0);
2392         if (fd < 0) {
2393                 perror("server: socket");
2394                 goto out;
2395         }
2396
2397         opt = 1;
2398         if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) {
2399                 perror("setsockopt");
2400                 goto out;
2401         }
2402
2403         memset(&ns->addr, 0, sizeof(ns->addr));
2404         ns->addr.sin_family = AF_INET;
2405         ns->addr.sin_addr.s_addr = htonl(INADDR_ANY);
2406         ns->addr.sin_port = htons(net_port);
2407
2408         if (bind(fd, (struct sockaddr *) &ns->addr, sizeof(ns->addr)) < 0) {
2409                 perror("bind");
2410                 goto out;
2411         }
2412
2413         if (listen(fd, 1) < 0) {
2414                 perror("listen");
2415                 goto out;
2416         }
2417
2418         /*
2419          * The actual server looping is done here:
2420          */
2421         ns->listen_fd = fd;
2422         ret = net_server_handle_connections(ns);
2423
2424         /*
2425          * Clean up and return...
2426          */
2427 out:
2428         free(ns->pfds);
2429         return ret;
2430 }
2431
2432 int main(int argc, char *argv[])
2433 {
2434         int ret = 0;
2435
2436         setlocale(LC_NUMERIC, "en_US");
2437         pagesize = getpagesize();
2438         ncpus = sysconf(_SC_NPROCESSORS_ONLN);
2439         if (ncpus < 0) {
2440                 fprintf(stderr, "sysconf(_SC_NPROCESSORS_ONLN) failed %d/%s\n",
2441                         errno, strerror(errno));
2442                 ret = 1;
2443                 goto out;
2444         }
2445
2446         if (handle_args(argc, argv)) {
2447                 ret = 1;
2448                 goto out;
2449         }
2450
2451         signal(SIGINT, handle_sigint);
2452         signal(SIGHUP, handle_sigint);
2453         signal(SIGTERM, handle_sigint);
2454         signal(SIGALRM, handle_sigint);
2455         signal(SIGPIPE, SIG_IGN);
2456
2457         if (kill_running_trace) {
2458                 struct devpath *dpp;
2459                 struct list_head *p;
2460
2461                 __list_for_each(p, &devpaths) {
2462                         dpp = list_entry(p, struct devpath, head);
2463                         if (__stop_trace(dpp->fd)) {
2464                                 fprintf(stderr,
2465                                         "BLKTRACETEARDOWN %s failed: %d/%s\n",
2466                                         dpp->path, errno, strerror(errno));
2467                         }
2468                 }
2469         } else if (net_mode == Net_server) {
2470                 if (output_name) {
2471                         fprintf(stderr, "-o ignored in server mode\n");
2472                         output_name = NULL;
2473                 }
2474
2475                 ret = net_server();
2476         } else {
2477                 atexit(exit_tracing);
2478
2479                 if (net_mode == Net_client)
2480                         printf("blktrace: connecting to %s\n", hostname);
2481
2482                 setup_buts();
2483
2484                 if (use_tracer_devpaths()) {
2485                         if (setup_tracer_devpaths())
2486                                 goto out;
2487
2488                         if (piped_output)
2489                                 handle_list = handle_list_file;
2490                         else
2491                                 handle_list = handle_list_net;
2492                 }
2493
2494                 ntracers = start_tracers();
2495                 if (ntracers != ncpus)
2496                         stop_tracers();
2497                 else {
2498                         if (net_mode == Net_client)
2499                                 printf("blktrace: connected!\n");
2500                         if (stop_watch)
2501                                 alarm(stop_watch);
2502                 }
2503
2504                 wait_tracers();
2505                 if (ntracers == ncpus)
2506                         show_stats(&devpaths);
2507
2508                 if (net_client_use_send())
2509                         close_client_connections();
2510                 del_tracers();
2511         }
2512
2513 out:
2514         if (pfp)
2515                 fclose(pfp);
2516         rel_devpaths();
2517         return ret;
2518 }