[PATCH] kernel: update to -rc6
[blktrace.git] / blktrace.c
1 /*
2  * block queue tracing application
3  *
4  * Copyright (C) 2005 Jens Axboe <axboe@suse.de>
5  *
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation; either version 2 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  */
21 #include <pthread.h>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <unistd.h>
25 #include <locale.h>
26 #include <signal.h>
27 #include <fcntl.h>
28 #include <string.h>
29 #include <sys/ioctl.h>
30 #include <sys/param.h>
31 #include <sys/statfs.h>
32 #include <sys/poll.h>
33 #include <sys/mman.h>
34 #include <sys/socket.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <sched.h>
38 #include <ctype.h>
39 #include <getopt.h>
40 #include <errno.h>
41 #include <netinet/in.h>
42 #include <arpa/inet.h>
43 #include <netdb.h>
44 #include <sys/sendfile.h>
45
46 #include "blktrace.h"
47 #include "barrier.h"
48
49 static char blktrace_version[] = "0.99.1";
50
51 /*
52  * You may want to increase this even more, if you are logging at a high
53  * rate and see skipped/missed events
54  */
55 #define BUF_SIZE        (512 * 1024)
56 #define BUF_NR          (4)
57
58 #define OFILE_BUF       (128 * 1024)
59
60 #define DEBUGFS_TYPE    0x64626720
61
62 #define S_OPTS  "d:a:A:r:o:kw:Vb:n:D:lh:p:s"
63 static struct option l_opts[] = {
64         {
65                 .name = "dev",
66                 .has_arg = required_argument,
67                 .flag = NULL,
68                 .val = 'd'
69         },
70         {
71                 .name = "act-mask",
72                 .has_arg = required_argument,
73                 .flag = NULL,
74                 .val = 'a'
75         },
76         {
77                 .name = "set-mask",
78                 .has_arg = required_argument,
79                 .flag = NULL,
80                 .val = 'A'
81         },
82         {
83                 .name = "relay",
84                 .has_arg = required_argument,
85                 .flag = NULL,
86                 .val = 'r'
87         },
88         {
89                 .name = "output",
90                 .has_arg = required_argument,
91                 .flag = NULL,
92                 .val = 'o'
93         },
94         {
95                 .name = "kill",
96                 .has_arg = no_argument,
97                 .flag = NULL,
98                 .val = 'k'
99         },
100         {
101                 .name = "stopwatch",
102                 .has_arg = required_argument,
103                 .flag = NULL,
104                 .val = 'w'
105         },
106         {
107                 .name = "version",
108                 .has_arg = no_argument,
109                 .flag = NULL,
110                 .val = 'V'
111         },
112         {
113                 .name = "buffer-size",
114                 .has_arg = required_argument,
115                 .flag = NULL,
116                 .val = 'b'
117         },
118         {
119                 .name = "num-sub-buffers",
120                 .has_arg = required_argument,
121                 .flag = NULL,
122                 .val = 'n'
123         },
124         {
125                 .name = "output-dir",
126                 .has_arg = required_argument,
127                 .flag = NULL,
128                 .val = 'D'
129         },
130         {
131                 .name = "listen",
132                 .has_arg = no_argument,
133                 .flag = NULL,
134                 .val = 'l'
135         },
136         {
137                 .name = "host",
138                 .has_arg = required_argument,
139                 .flag = NULL,
140                 .val = 'h'
141         },
142         {
143                 .name = "port",
144                 .has_arg = required_argument,
145                 .flag = NULL,
146                 .val = 'p'
147         },
148         {
149                 .name = "no-sendfile",
150                 .has_arg = no_argument,
151                 .flag = NULL,
152                 .val = 's'
153         },
154         {
155                 .name = NULL,
156         }
157 };
158
159 struct tip_subbuf {
160         void *buf;
161         unsigned int len;
162         unsigned int max_len;
163 };
164
165 #define FIFO_SIZE       (1024)  /* should be plenty big! */
166 #define CL_SIZE         (128)   /* cache line, any bigger? */
167
168 struct tip_subbuf_fifo {
169         int tail __attribute__((aligned(CL_SIZE)));
170         int head __attribute__((aligned(CL_SIZE)));
171         struct tip_subbuf *q[FIFO_SIZE];
172 };
173
174 struct thread_information {
175         int cpu;
176         pthread_t thread;
177
178         int fd;
179         void *fd_buf;
180         char fn[MAXPATHLEN + 64];
181
182         FILE *ofile;
183         char *ofile_buffer;
184         off_t ofile_offset;
185         int ofile_stdout;
186         int ofile_mmap;
187
188         int (*get_subbuf)(struct thread_information *, unsigned int);
189         int (*flush_subbuf)(struct thread_information *, struct tip_subbuf *);
190         int (*read_data)(struct thread_information *, void *, unsigned int);
191
192         unsigned long events_processed;
193         unsigned long long data_read;
194         unsigned long long data_queued;
195         struct device_information *device;
196
197         int exited;
198
199         /*
200          * piped fifo buffers
201          */
202         struct tip_subbuf_fifo fifo;
203         struct tip_subbuf *leftover_ts;
204
205         /*
206          * mmap controlled output files
207          */
208         unsigned long long fs_size;
209         unsigned long long fs_max_size;
210         unsigned long fs_off;
211         void *fs_buf;
212         unsigned long fs_buf_len;
213
214         struct net_connection *nc;
215 };
216
217 struct device_information {
218         int fd;
219         char *path;
220         char buts_name[32];
221         volatile int trace_started;
222         unsigned long drop_count;
223         struct thread_information *threads;
224
225         struct cl_host *ch;
226         u32 cl_id;
227         time_t cl_connect_time;
228 };
229
230 static int ncpus;
231 static struct thread_information *thread_information;
232 static int ndevs;
233 static struct device_information *device_information;
234
235 /* command line option globals */
236 static char *debugfs_path;
237 static char *output_name;
238 static char *output_dir;
239 static int act_mask = ~0U;
240 static int kill_running_trace;
241 static unsigned long buf_size = BUF_SIZE;
242 static unsigned long buf_nr = BUF_NR;
243 static unsigned int page_size;
244
245 #define is_done()       (*(volatile int *)(&done))
246 static volatile int done;
247
248 #define is_trace_stopped()      (*(volatile int *)(&trace_stopped))
249 static volatile int trace_stopped;
250
251 #define is_stat_shown() (*(volatile int *)(&stat_shown))
252 static volatile int stat_shown;
253
254 int data_is_native = -1;
255
256 static void exit_trace(int status);
257
258 #define dip_tracing(dip)        (*(volatile int *)(&(dip)->trace_started))
259 #define dip_set_tracing(dip, v) ((dip)->trace_started = (v))
260
261 #define __for_each_dip(__d, __di, __e, __i)     \
262         for (__i = 0, __d = __di; __i < __e; __i++, __d++)
263
264 #define for_each_dip(__d, __i)          \
265         __for_each_dip(__d, device_information, ndevs, __i)
266 #define for_each_nc_dip(__nc, __d, __i)         \
267         __for_each_dip(__d, (__nc)->ch->device_information, (__nc)->ch->ndevs, __i)
268
269 #define __for_each_tip(__d, __t, __ncpus, __j)  \
270         for (__j = 0, __t = (__d)->threads; __j < __ncpus; __j++, __t++)
271 #define for_each_tip(__d, __t, __j)     \
272         __for_each_tip(__d, __t, ncpus, __j)
273 #define for_each_cl_host(__c)   \
274         for (__c = cl_host_list; __c; __c = __c->list_next)
275
276 /*
277  * networking stuff follows. we include a magic number so we know whether
278  * to endianness convert or not
279  */
280 struct blktrace_net_hdr {
281         u32 magic;              /* same as trace magic */
282         char buts_name[32];     /* trace name */
283         u32 cpu;                /* for which cpu */
284         u32 max_cpus;
285         u32 len;                /* length of following trace data */
286         u32 cl_id;              /* id for set of client per-cpu connections */
287 };
288
289 #define TRACE_NET_PORT          (8462)
290
291 enum {
292         Net_none = 0,
293         Net_server,
294         Net_client,
295 };
296
297 /*
298  * network cmd line params
299  */
300 static char hostname[MAXHOSTNAMELEN];
301 static int net_port = TRACE_NET_PORT;
302 static int net_mode = 0;
303 static int net_use_sendfile = 1;
304
305 struct cl_host {
306         struct cl_host *list_next;
307         struct in_addr cl_in_addr;
308         struct net_connection *net_connections;
309         int nconn;
310         struct device_information *device_information;
311         int ndevs;
312         int ncpus;
313         int ndevs_done;
314 };
315
316 struct net_connection {
317         int in_fd;
318         struct pollfd pfd;
319         time_t connect_time;
320         struct cl_host *ch;
321         int ncpus;
322 };
323
324 #define NET_MAX_CL_HOSTS        (1024)
325 static struct cl_host *cl_host_list;
326 static int cl_hosts;
327 static int net_connects;
328
329 static int *net_out_fd;
330
331 static void handle_sigint(__attribute__((__unused__)) int sig)
332 {
333         struct device_information *dip;
334         int i;
335
336         /*
337          * stop trace so we can reap currently produced data
338          */
339         for_each_dip(dip, i) {
340                 if (dip->fd == -1)
341                         continue;
342                 if (ioctl(dip->fd, BLKTRACESTOP) < 0)
343                         perror("BLKTRACESTOP");
344         }
345
346         done = 1;
347 }
348
349 static int get_dropped_count(const char *buts_name)
350 {
351         int fd;
352         char tmp[MAXPATHLEN + 64];
353
354         snprintf(tmp, sizeof(tmp), "%s/block/%s/dropped",
355                  debugfs_path, buts_name);
356
357         fd = open(tmp, O_RDONLY);
358         if (fd < 0) {
359                 /*
360                  * this may be ok, if the kernel doesn't support dropped counts
361                  */
362                 if (errno == ENOENT)
363                         return 0;
364
365                 fprintf(stderr, "Couldn't open dropped file %s\n", tmp);
366                 return -1;
367         }
368
369         if (read(fd, tmp, sizeof(tmp)) < 0) {
370                 perror(tmp);
371                 close(fd);
372                 return -1;
373         }
374
375         close(fd);
376
377         return atoi(tmp);
378 }
379
380 static int start_trace(struct device_information *dip)
381 {
382         struct blk_user_trace_setup buts;
383
384         memset(&buts, 0, sizeof(buts));
385         buts.buf_size = buf_size;
386         buts.buf_nr = buf_nr;
387         buts.act_mask = act_mask;
388
389         if (ioctl(dip->fd, BLKTRACESETUP, &buts) < 0) {
390                 perror("BLKTRACESETUP");
391                 return 1;
392         }
393
394         if (ioctl(dip->fd, BLKTRACESTART) < 0) {
395                 perror("BLKTRACESTART");
396                 return 1;
397         }
398
399         memcpy(dip->buts_name, buts.name, sizeof(dip->buts_name));
400         dip_set_tracing(dip, 1);
401         return 0;
402 }
403
404 static void stop_trace(struct device_information *dip)
405 {
406         if (dip_tracing(dip) || kill_running_trace) {
407                 dip_set_tracing(dip, 0);
408
409                 /*
410                  * should be stopped, just don't complain if it isn't
411                  */
412                 ioctl(dip->fd, BLKTRACESTOP);
413
414                 if (ioctl(dip->fd, BLKTRACETEARDOWN) < 0)
415                         perror("BLKTRACETEARDOWN");
416
417                 close(dip->fd);
418                 dip->fd = -1;
419         }
420 }
421
422 static void stop_all_traces(void)
423 {
424         struct device_information *dip;
425         int i;
426
427         for_each_dip(dip, i) {
428                 dip->drop_count = get_dropped_count(dip->buts_name);
429                 stop_trace(dip);
430         }
431 }
432
433 static void wait_for_data(struct thread_information *tip, int timeout)
434 {
435         struct pollfd pfd = { .fd = tip->fd, .events = POLLIN };
436
437         while (!is_done()) {
438                 if (poll(&pfd, 1, timeout) < 0) {
439                         perror("poll");
440                         break;
441                 }
442                 if (pfd.revents & POLLIN)
443                         break;
444                 if (tip->ofile_stdout)
445                         break;
446         }
447 }
448
449 static int read_data_file(struct thread_information *tip, void *buf,
450                           unsigned int len)
451 {
452         int ret = 0;
453
454         do {
455                 wait_for_data(tip, 100);
456
457                 ret = read(tip->fd, buf, len);
458                 if (!ret)
459                         continue;
460                 else if (ret > 0)
461                         return ret;
462                 else {
463                         if (errno != EAGAIN) {
464                                 perror(tip->fn);
465                                 fprintf(stderr,"Thread %d failed read of %s\n",
466                                         tip->cpu, tip->fn);
467                                 break;
468                         }
469                         continue;
470                 }
471         } while (!is_done());
472
473         return ret;
474
475 }
476
477 static int read_data_net(struct thread_information *tip, void *buf,
478                          unsigned int len)
479 {
480         struct net_connection *nc = tip->nc;
481         unsigned int bytes_left = len;
482         int ret = 0;
483
484         do {
485                 ret = recv(nc->in_fd, buf, bytes_left, MSG_WAITALL);
486
487                 if (!ret)
488                         continue;
489                 else if (ret < 0) {
490                         if (errno != EAGAIN) {
491                                 perror(tip->fn);
492                                 fprintf(stderr, "server: failed read\n");
493                                 return 0;
494                         }
495                         continue;
496                 } else {
497                         buf += ret;
498                         bytes_left -= ret;
499                 }
500         } while (!is_done() && bytes_left);
501
502         return len - bytes_left;
503 }
504
505 static inline struct tip_subbuf *
506 subbuf_fifo_dequeue(struct thread_information *tip)
507 {
508         const int head = tip->fifo.head;
509         const int next = (head + 1) & (FIFO_SIZE - 1);
510
511         if (head != tip->fifo.tail) {
512                 struct tip_subbuf *ts = tip->fifo.q[head];
513
514                 store_barrier();
515                 tip->fifo.head = next;
516                 return ts;
517         }
518
519         return NULL;
520 }
521
522 static inline int subbuf_fifo_queue(struct thread_information *tip,
523                                     struct tip_subbuf *ts)
524 {
525         const int tail = tip->fifo.tail;
526         const int next = (tail + 1) & (FIFO_SIZE - 1);
527
528         if (next != tip->fifo.head) {
529                 tip->fifo.q[tail] = ts;
530                 store_barrier();
531                 tip->fifo.tail = next;
532                 return 0;
533         }
534
535         fprintf(stderr, "fifo too small!\n");
536         return 1;
537 }
538
539 /*
540  * For file output, truncate and mmap the file appropriately
541  */
542 static int mmap_subbuf(struct thread_information *tip, unsigned int maxlen)
543 {
544         int ofd = fileno(tip->ofile);
545         int ret;
546
547         /*
548          * extend file, if we have to. use chunks of 16 subbuffers.
549          */
550         if (tip->fs_off + buf_size > tip->fs_buf_len) {
551                 if (tip->fs_buf) {
552                         munlock(tip->fs_buf, tip->fs_buf_len);
553                         munmap(tip->fs_buf, tip->fs_buf_len);
554                         tip->fs_buf = NULL;
555                 }
556
557                 tip->fs_off = tip->fs_size & (page_size - 1);
558                 tip->fs_buf_len = (16 * buf_size) - tip->fs_off;
559                 tip->fs_max_size += tip->fs_buf_len;
560
561                 if (ftruncate(ofd, tip->fs_max_size) < 0) {
562                         perror("ftruncate");
563                         return -1;
564                 }
565
566                 tip->fs_buf = mmap(NULL, tip->fs_buf_len, PROT_WRITE,
567                                    MAP_SHARED, ofd, tip->fs_size - tip->fs_off);
568                 if (tip->fs_buf == MAP_FAILED) {
569                         perror("mmap");
570                         return -1;
571                 }
572                 mlock(tip->fs_buf, tip->fs_buf_len);
573         }
574
575         ret = tip->read_data(tip, tip->fs_buf + tip->fs_off, maxlen);
576         if (ret >= 0) {
577                 tip->data_read += ret;
578                 tip->fs_size += ret;
579                 tip->fs_off += ret;
580                 return 0;
581         }
582
583         return -1;
584 }
585
586 /*
587  * Use the copy approach for pipes and network
588  */
589 static int get_subbuf(struct thread_information *tip, unsigned int maxlen)
590 {
591         struct tip_subbuf *ts = malloc(sizeof(*ts));
592         int ret;
593
594         ts->buf = malloc(buf_size);
595         ts->max_len = maxlen;
596
597         ret = tip->read_data(tip, ts->buf, ts->max_len);
598         if (ret > 0) {
599                 ts->len = ret;
600                 tip->data_read += ret;
601                 if (subbuf_fifo_queue(tip, ts))
602                         return -1;
603         }
604
605         return ret;
606 }
607
608 static void close_thread(struct thread_information *tip)
609 {
610         if (tip->fd != -1)
611                 close(tip->fd);
612         if (tip->ofile)
613                 fclose(tip->ofile);
614         if (tip->ofile_buffer)
615                 free(tip->ofile_buffer);
616         if (tip->fd_buf)
617                 free(tip->fd_buf);
618
619         tip->fd = -1;
620         tip->ofile = NULL;
621         tip->ofile_buffer = NULL;
622         tip->fd_buf = NULL;
623 }
624
625 static void tip_ftrunc_final(struct thread_information *tip)
626 {
627         /*
628          * truncate to right size and cleanup mmap
629          */
630         if (tip->ofile_mmap && tip->ofile) {
631                 int ofd = fileno(tip->ofile);
632
633                 if (tip->fs_buf)
634                         munmap(tip->fs_buf, tip->fs_buf_len);
635
636                 ftruncate(ofd, tip->fs_size);
637         }
638 }
639
640 static void *thread_main(void *arg)
641 {
642         struct thread_information *tip = arg;
643         pid_t pid = getpid();
644         cpu_set_t cpu_mask;
645
646         CPU_ZERO(&cpu_mask);
647         CPU_SET((tip->cpu), &cpu_mask);
648
649         if (sched_setaffinity(pid, sizeof(cpu_mask), &cpu_mask) == -1) {
650                 perror("sched_setaffinity");
651                 exit_trace(1);
652         }
653
654         snprintf(tip->fn, sizeof(tip->fn), "%s/block/%s/trace%d",
655                         debugfs_path, tip->device->buts_name, tip->cpu);
656         tip->fd = open(tip->fn, O_RDONLY);
657         if (tip->fd < 0) {
658                 perror(tip->fn);
659                 fprintf(stderr,"Thread %d failed open of %s\n", tip->cpu,
660                         tip->fn);
661                 exit_trace(1);
662         }
663
664         while (!is_done()) {
665                 if (tip->get_subbuf(tip, buf_size) < 0)
666                         break;
667         }
668
669         /*
670          * trace is stopped, pull data until we get a short read
671          */
672         while (tip->get_subbuf(tip, buf_size) > 0)
673                 ;
674
675         tip_ftrunc_final(tip);
676         tip->exited = 1;
677         return NULL;
678 }
679
680 static int write_data_net(int fd, void *buf, unsigned int buf_len)
681 {
682         unsigned int bytes_left = buf_len;
683         int ret;
684
685         while (bytes_left) {
686                 ret = send(fd, buf, bytes_left, 0);
687                 if (ret < 0) {
688                         perror("send");
689                         return 1;
690                 }
691
692                 buf += ret;
693                 bytes_left -= ret;
694         }
695
696         return 0;
697 }
698
699 static int net_send_header(struct thread_information *tip, unsigned int len)
700 {
701         struct blktrace_net_hdr hdr;
702
703         hdr.magic = BLK_IO_TRACE_MAGIC;
704         strcpy(hdr.buts_name, tip->device->buts_name);
705         hdr.cpu = tip->cpu;
706         hdr.max_cpus = ncpus;
707         hdr.len = len;
708         hdr.cl_id = getpid();
709
710         return write_data_net(net_out_fd[tip->cpu], &hdr, sizeof(hdr));
711 }
712
713 /*
714  * send header with 0 length to signal end-of-run
715  */
716 static void net_client_send_close(void)
717 {
718         struct device_information *dip;
719         struct blktrace_net_hdr hdr;
720         int i;
721
722         for_each_dip(dip, i) {
723                 hdr.magic = BLK_IO_TRACE_MAGIC;
724                 hdr.max_cpus = ncpus;
725                 hdr.len = 0;
726                 strcpy(hdr.buts_name, dip->buts_name);
727                 hdr.cpu = get_dropped_count(dip->buts_name);
728                 hdr.cl_id = getpid();
729
730                 write_data_net(net_out_fd[0], &hdr, sizeof(hdr));
731         }
732
733 }
734
735 static int flush_subbuf_net(struct thread_information *tip,
736                             struct tip_subbuf *ts)
737 {
738         if (net_send_header(tip, ts->len))
739                 return -1;
740         if (write_data_net(net_out_fd[tip->cpu], ts->buf, ts->len))
741                 return -1;
742
743         free(ts->buf);
744         free(ts);
745         return 1;
746 }
747
748 static int net_sendfile(struct thread_information *tip, struct tip_subbuf *ts)
749 {
750         int ret = sendfile(net_out_fd[tip->cpu], tip->fd, NULL, ts->len);
751
752         if (ret < 0) {
753                 perror("sendfile");
754                 return 1;
755         } else if (ret < (int) ts->len) {
756                 fprintf(stderr, "short sendfile send (%d of %d)\n", ret, ts->len);
757                 return 1;
758         }
759
760         return 0;
761 }
762
763 static int flush_subbuf_sendfile(struct thread_information *tip,
764                                  struct tip_subbuf *ts)
765 {
766         int ret = -1;
767
768         if (net_send_header(tip, ts->len))
769                 goto err;
770         if (net_sendfile(tip, ts))
771                 goto err;
772
773         tip->data_read += ts->len;
774         tip->ofile_offset += buf_size;
775         ret = 1;
776 err:
777         free(ts);
778         return ret;
779 }
780
781 static int get_subbuf_sendfile(struct thread_information *tip,
782                                __attribute__((__unused__)) unsigned int maxlen)
783 {
784         struct tip_subbuf *ts;
785         struct stat sb;
786         unsigned int ready;
787
788         wait_for_data(tip, -1);
789
790         if (fstat(tip->fd, &sb) < 0) {
791                 perror("trace stat");
792                 return -1;
793         }
794         ready = sb.st_size - tip->data_queued;
795         if (!ready) {
796                 usleep(1000);
797                 return 0;
798         }
799
800         ts = malloc(sizeof(*ts));
801         ts->buf = NULL;
802         ts->max_len = 0;
803         ts->len = ready;
804         tip->data_queued += ready;
805
806         if (flush_subbuf_sendfile(tip, ts) < 0)
807                 return -1;
808
809         return ready;
810 }
811
812 static int write_data(struct thread_information *tip, void *buf,
813                       unsigned int buf_len)
814 {
815         int ret;
816
817         if (!buf_len)
818                 return 0;
819
820         while (1) {
821                 ret = fwrite(buf, buf_len, 1, tip->ofile);
822                 if (ret == 1)
823                         break;
824
825                 if (ret < 0) {
826                         perror("write");
827                         return 1;
828                 }
829         }
830
831         if (tip->ofile_stdout)
832                 fflush(tip->ofile);
833
834         return 0;
835 }
836
837 static int flush_subbuf_file(struct thread_information *tip,
838                              struct tip_subbuf *ts)
839 {
840         unsigned int offset = 0;
841         struct blk_io_trace *t;
842         int pdu_len, events = 0;
843
844         /*
845          * surplus from last run
846          */
847         if (tip->leftover_ts) {
848                 struct tip_subbuf *prev_ts = tip->leftover_ts;
849
850                 if (prev_ts->len + ts->len > prev_ts->max_len) {
851                         prev_ts->max_len += ts->len;
852                         prev_ts->buf = realloc(prev_ts->buf, prev_ts->max_len);
853                 }
854
855                 memcpy(prev_ts->buf + prev_ts->len, ts->buf, ts->len);
856                 prev_ts->len += ts->len;
857
858                 free(ts->buf);
859                 free(ts);
860
861                 ts = prev_ts;
862                 tip->leftover_ts = NULL;
863         }
864
865         while (offset + sizeof(*t) <= ts->len) {
866                 t = ts->buf + offset;
867
868                 if (verify_trace(t)) {
869                         write_data(tip, ts->buf, offset);
870                         return -1;
871                 }
872
873                 pdu_len = t->pdu_len;
874
875                 if (offset + sizeof(*t) + pdu_len > ts->len)
876                         break;
877
878                 offset += sizeof(*t) + pdu_len;
879                 tip->events_processed++;
880                 tip->data_read += sizeof(*t) + pdu_len;
881                 events++;
882         }
883
884         if (write_data(tip, ts->buf, offset))
885                 return -1;
886
887         /*
888          * leftover bytes, save them for next time
889          */
890         if (offset != ts->len) {
891                 tip->leftover_ts = ts;
892                 ts->len -= offset;
893                 memmove(ts->buf, ts->buf + offset, ts->len);
894         } else {
895                 free(ts->buf);
896                 free(ts);
897         }
898
899         return events;
900 }
901
902 static int write_tip_events(struct thread_information *tip)
903 {
904         struct tip_subbuf *ts = subbuf_fifo_dequeue(tip);
905
906         if (ts)
907                 return tip->flush_subbuf(tip, ts);
908
909         return 0;
910 }
911
912 /*
913  * scans the tips we know and writes out the subbuffers we accumulate
914  */
915 static void get_and_write_events(void)
916 {
917         struct device_information *dip;
918         struct thread_information *tip;
919         int i, j, events, ret, tips_running;
920
921         while (!is_done()) {
922                 events = 0;
923
924                 for_each_dip(dip, i) {
925                         for_each_tip(dip, tip, j) {
926                                 ret = write_tip_events(tip);
927                                 if (ret > 0)
928                                         events += ret;
929                         }
930                 }
931
932                 if (!events)
933                         usleep(100000);
934         }
935
936         /*
937          * reap stored events
938          */
939         do {
940                 events = 0;
941                 tips_running = 0;
942                 for_each_dip(dip, i) {
943                         for_each_tip(dip, tip, j) {
944                                 ret = write_tip_events(tip);
945                                 if (ret > 0)
946                                         events += ret;
947                                 tips_running += !tip->exited;
948                         }
949                 }
950                 usleep(10);
951         } while (events || tips_running);
952 }
953
954 static void wait_for_threads(void)
955 {
956         /*
957          * for piped or network output, poll and fetch data for writeout.
958          * for files, we just wait around for trace threads to exit
959          */
960         if ((output_name && !strcmp(output_name, "-")) ||
961             ((net_mode == Net_client) && !net_use_sendfile))
962                 get_and_write_events();
963         else {
964                 struct device_information *dip;
965                 struct thread_information *tip;
966                 int i, j, tips_running;
967
968                 do {
969                         tips_running = 0;
970                         usleep(100000);
971
972                         for_each_dip(dip, i)
973                                 for_each_tip(dip, tip, j)
974                                         tips_running += !tip->exited;
975                 } while (tips_running);
976         }
977
978         if (net_mode == Net_client)
979                 net_client_send_close();
980 }
981
982 static int fill_ofname(struct device_information *dip,
983                        struct thread_information *tip, char *dst,
984                        char *buts_name)
985 {
986         struct stat sb;
987         int len = 0;
988
989         if (output_dir)
990                 len = sprintf(dst, "%s/", output_dir);
991         else
992                 len = sprintf(dst, "./");
993
994         if (net_mode == Net_server) {
995                 struct net_connection *nc = tip->nc;
996
997                 len += sprintf(dst + len, "%s-", inet_ntoa(nc->ch->cl_in_addr));
998                 len += strftime(dst + len, 64, "%F-%T/", gmtime(&dip->cl_connect_time));
999         }
1000
1001         if (stat(dst, &sb) < 0) {
1002                 if (errno != ENOENT) {
1003                         perror("stat");
1004                         return 1;
1005                 }
1006                 if (mkdir(dst, 0755) < 0) {
1007                         perror(dst);
1008                         fprintf(stderr, "Can't make output dir\n");
1009                         return 1;
1010                 }
1011         }
1012
1013         if (output_name)
1014                 sprintf(dst + len, "%s.blktrace.%d", output_name, tip->cpu);
1015         else
1016                 sprintf(dst + len, "%s.blktrace.%d", buts_name, tip->cpu);
1017
1018         return 0;
1019 }
1020
1021 static void fill_ops(struct thread_information *tip)
1022 {
1023         /*
1024          * setup ops
1025          */
1026         if (net_mode == Net_client) {
1027                 if (net_use_sendfile) {
1028                         tip->get_subbuf = get_subbuf_sendfile;
1029                         tip->flush_subbuf = NULL;
1030                 } else {
1031                         tip->get_subbuf = get_subbuf;
1032                         tip->flush_subbuf = flush_subbuf_net;
1033                 }
1034         } else {
1035                 if (tip->ofile_mmap)
1036                         tip->get_subbuf = mmap_subbuf;
1037                 else
1038                         tip->get_subbuf = get_subbuf;
1039
1040                 tip->flush_subbuf = flush_subbuf_file;
1041         }
1042                         
1043         if (net_mode == Net_server)
1044                 tip->read_data = read_data_net;
1045         else
1046                 tip->read_data = read_data_file;
1047 }
1048
1049 static int tip_open_output(struct device_information *dip,
1050                            struct thread_information *tip)
1051 {
1052         int pipeline = output_name && !strcmp(output_name, "-");
1053         int mode, vbuf_size;
1054         char op[128];
1055
1056         if (net_mode == Net_client) {
1057                 tip->ofile = NULL;
1058                 tip->ofile_stdout = 0;
1059                 tip->ofile_mmap = 0;
1060                 goto done;
1061         } else if (pipeline) {
1062                 tip->ofile = fdopen(STDOUT_FILENO, "w");
1063                 tip->ofile_stdout = 1;
1064                 tip->ofile_mmap = 0;
1065                 mode = _IOLBF;
1066                 vbuf_size = 512;
1067         } else {
1068                 if (fill_ofname(dip, tip, op, dip->buts_name))
1069                         return 1;
1070                 tip->ofile = fopen(op, "w+");
1071                 tip->ofile_stdout = 0;
1072                 tip->ofile_mmap = 1;
1073                 mode = _IOFBF;
1074                 vbuf_size = OFILE_BUF;
1075         }
1076
1077         if (tip->ofile == NULL) {
1078                 perror(op);
1079                 return 1;
1080         }
1081
1082         tip->ofile_buffer = malloc(vbuf_size);
1083         if (setvbuf(tip->ofile, tip->ofile_buffer, mode, vbuf_size)) {
1084                 perror("setvbuf");
1085                 close_thread(tip);
1086                 return 1;
1087         }
1088
1089 done:
1090         fill_ops(tip);
1091         return 0;
1092 }
1093
1094 static int start_threads(struct device_information *dip)
1095 {
1096         struct thread_information *tip;
1097         int j;
1098
1099         for_each_tip(dip, tip, j) {
1100                 tip->cpu = j;
1101                 tip->device = dip;
1102                 tip->events_processed = 0;
1103                 tip->fd = -1;
1104                 memset(&tip->fifo, 0, sizeof(tip->fifo));
1105                 tip->leftover_ts = NULL;
1106
1107                 if (tip_open_output(dip, tip))
1108                         return 1;
1109
1110                 if (pthread_create(&tip->thread, NULL, thread_main, tip)) {
1111                         perror("pthread_create");
1112                         close_thread(tip);
1113                         return 1;
1114                 }
1115         }
1116
1117         return 0;
1118 }
1119
1120 static void stop_threads(struct device_information *dip)
1121 {
1122         struct thread_information *tip;
1123         unsigned long ret;
1124         int i;
1125
1126         for_each_tip(dip, tip, i) {
1127                 (void) pthread_join(tip->thread, (void *) &ret);
1128                 close_thread(tip);
1129         }
1130 }
1131
1132 static void stop_all_threads(void)
1133 {
1134         struct device_information *dip;
1135         int i;
1136
1137         for_each_dip(dip, i)
1138                 stop_threads(dip);
1139 }
1140
1141 static void stop_all_tracing(void)
1142 {
1143         struct device_information *dip;
1144         int i;
1145
1146         for_each_dip(dip, i)
1147                 stop_trace(dip);
1148 }
1149
1150 static void exit_trace(int status)
1151 {
1152         if (!is_trace_stopped()) {
1153                 trace_stopped = 1;
1154                 stop_all_threads();
1155                 stop_all_tracing();
1156         }
1157
1158         exit(status);
1159 }
1160
1161 static int resize_devices(char *path)
1162 {
1163         int size = (ndevs + 1) * sizeof(struct device_information);
1164
1165         device_information = realloc(device_information, size);
1166         if (!device_information) {
1167                 fprintf(stderr, "Out of memory, device %s (%d)\n", path, size);
1168                 return 1;
1169         }
1170         device_information[ndevs].path = path;
1171         ndevs++;
1172         return 0;
1173 }
1174
1175 static int open_devices(void)
1176 {
1177         struct device_information *dip;
1178         int i;
1179
1180         for_each_dip(dip, i) {
1181                 dip->fd = open(dip->path, O_RDONLY | O_NONBLOCK);
1182                 if (dip->fd < 0) {
1183                         perror(dip->path);
1184                         return 1;
1185                 }
1186         }
1187
1188         return 0;
1189 }
1190
1191 static int start_devices(void)
1192 {
1193         struct device_information *dip;
1194         int i, j, size;
1195
1196         size = ncpus * sizeof(struct thread_information);
1197         thread_information = malloc(size * ndevs);
1198         if (!thread_information) {
1199                 fprintf(stderr, "Out of memory, threads (%d)\n", size * ndevs);
1200                 return 1;
1201         }
1202
1203         for_each_dip(dip, i) {
1204                 if (start_trace(dip)) {
1205                         close(dip->fd);
1206                         fprintf(stderr, "Failed to start trace on %s\n",
1207                                 dip->path);
1208                         break;
1209                 }
1210         }
1211
1212         if (i != ndevs) {
1213                 __for_each_dip(dip, device_information, i, j)
1214                         stop_trace(dip);
1215
1216                 return 1;
1217         }
1218
1219         for_each_dip(dip, i) {
1220                 dip->threads = thread_information + (i * ncpus);
1221                 if (start_threads(dip)) {
1222                         fprintf(stderr, "Failed to start worker threads\n");
1223                         break;
1224                 }
1225         }
1226
1227         if (i != ndevs) {
1228                 __for_each_dip(dip, device_information, i, j)
1229                         stop_threads(dip);
1230                 for_each_dip(dip, i)
1231                         stop_trace(dip);
1232
1233                 return 1;
1234         }
1235
1236         return 0;
1237 }
1238
1239 static void show_stats(struct device_information *dips, int ndips, int cpus)
1240 {
1241         struct device_information *dip;
1242         struct thread_information *tip;
1243         unsigned long long events_processed, data_read;
1244         unsigned long total_drops;
1245         int i, j, no_stdout = 0;
1246
1247         if (is_stat_shown())
1248                 return;
1249
1250         if (output_name && !strcmp(output_name, "-"))
1251                 no_stdout = 1;
1252
1253         stat_shown = 1;
1254
1255         total_drops = 0;
1256         __for_each_dip(dip, dips, ndips, i) {
1257                 if (!no_stdout)
1258                         printf("Device: %s\n", dip->path);
1259                 events_processed = 0;
1260                 data_read = 0;
1261                 __for_each_tip(dip, tip, cpus, j) {
1262                         if (!no_stdout)
1263                                 printf("  CPU%3d: %20lu events, %8llu KiB data\n",
1264                                         tip->cpu, tip->events_processed,
1265                                         (tip->data_read + 1023) >> 10);
1266                         events_processed += tip->events_processed;
1267                         data_read += tip->data_read;
1268                 }
1269                 total_drops += dip->drop_count;
1270                 if (!no_stdout)
1271                         printf("  Total:  %20llu events (dropped %lu), %8llu KiB data\n",
1272                                         events_processed, dip->drop_count,
1273                                         (data_read + 1023) >> 10);
1274         }
1275
1276         if (total_drops)
1277                 fprintf(stderr, "You have dropped events, consider using a larger buffer size (-b)\n");
1278 }
1279
1280 static struct device_information *net_get_dip(struct net_connection *nc,
1281                                               char *buts_name, u32 cl_id)
1282 {
1283         struct device_information *dip, *cl_dip = NULL;
1284         struct cl_host *ch = nc->ch;
1285         int i;
1286
1287         for (i = 0; i < ch->ndevs; i++) {
1288                 dip = &ch->device_information[i];
1289
1290                 if (!strcmp(dip->buts_name, buts_name))
1291                         return dip;
1292
1293                 if (dip->cl_id == cl_id)
1294                         cl_dip = dip;
1295         }
1296
1297         ch->device_information = realloc(ch->device_information, (ch->ndevs + 1) * sizeof(*dip));
1298         dip = &ch->device_information[ch->ndevs];
1299         memset(dip, 0, sizeof(*dip));
1300         dip->fd = -1;
1301         dip->ch = ch;
1302         dip->cl_id = cl_id;
1303         if (cl_dip)
1304                 dip->cl_connect_time = cl_dip->cl_connect_time;
1305         else
1306                 dip->cl_connect_time = nc->connect_time;
1307         strcpy(dip->buts_name, buts_name);
1308         dip->path = strdup(buts_name);
1309         dip->trace_started = 1;
1310         ch->ndevs++;
1311         dip->threads = malloc(nc->ncpus * sizeof(struct thread_information));
1312         memset(dip->threads, 0, nc->ncpus * sizeof(struct thread_information));
1313
1314         /*
1315          * open all files
1316          */
1317         for (i = 0; i < nc->ncpus; i++) {
1318                 struct thread_information *tip = &dip->threads[i];
1319
1320                 tip->cpu = i;
1321                 tip->device = dip;
1322                 tip->fd = -1;
1323                 tip->nc = nc;
1324                 
1325                 if (tip_open_output(dip, tip))
1326                         return NULL;
1327
1328                 tip->nc = NULL;
1329         }
1330
1331         return dip;
1332 }
1333
1334 static struct thread_information *net_get_tip(struct net_connection *nc,
1335                                               struct blktrace_net_hdr *bnh)
1336 {
1337         struct device_information *dip;
1338         struct thread_information *tip;
1339
1340         nc->ncpus = bnh->max_cpus;
1341         dip = net_get_dip(nc, bnh->buts_name, bnh->cl_id);
1342         if (!dip->trace_started) {
1343                 fprintf(stderr, "Events for closed devices %s\n", dip->buts_name);
1344                 return NULL;
1345         }
1346
1347         tip = &dip->threads[bnh->cpu];
1348         if (!tip->nc)
1349                 tip->nc = nc;
1350         
1351         return tip;
1352 }
1353
1354 static int net_get_header(struct net_connection *nc,
1355                           struct blktrace_net_hdr *bnh)
1356 {
1357         int fl = fcntl(nc->in_fd, F_GETFL);
1358         int bytes_left, ret;
1359         void *p = bnh;
1360
1361         fcntl(nc->in_fd, F_SETFL, fl | O_NONBLOCK);
1362         bytes_left = sizeof(*bnh);
1363         while (bytes_left && !is_done()) {
1364                 ret = recv(nc->in_fd, p, bytes_left, MSG_WAITALL);
1365                 if (ret < 0) {
1366                         if (errno != EAGAIN) {
1367                                 perror("recv header");
1368                                 return 1;
1369                         }
1370                         usleep(1000);
1371                         continue;
1372                 } else if (!ret) {
1373                         usleep(1000);
1374                         continue;
1375                 } else {
1376                         p += ret;
1377                         bytes_left -= ret;
1378                 }
1379         }
1380         fcntl(nc->in_fd, F_SETFL, fl & ~O_NONBLOCK);
1381         return bytes_left;
1382 }
1383
1384 /*
1385  * finalize a net client: truncate files, show stats, cleanup, etc
1386  */
1387 static void device_done(struct net_connection *nc, struct device_information *dip)
1388 {
1389         struct thread_information *tip;
1390         int i;
1391
1392         __for_each_tip(dip, tip, nc->ncpus, i)
1393                 tip_ftrunc_final(tip);
1394
1395         show_stats(dip, 1, nc->ncpus);
1396
1397         /*
1398          * cleanup for next run
1399          */
1400         __for_each_tip(dip, tip, nc->ncpus, i) {
1401                 if (tip->ofile)
1402                         fclose(tip->ofile);
1403         }
1404
1405         free(dip->threads);
1406         free(dip->path);
1407
1408         close(nc->in_fd);
1409         nc->in_fd = -1;
1410
1411         stat_shown = 0;
1412 }
1413
1414 static inline int in_addr_eq(struct in_addr a, struct in_addr b)
1415 {
1416         return a.s_addr == b.s_addr;
1417 }
1418
1419 static void net_add_client_host(struct cl_host *ch)
1420 {
1421         ch->list_next = cl_host_list;
1422         cl_host_list = ch;
1423         cl_hosts++;
1424 }
1425
1426 static void net_remove_client_host(struct cl_host *ch)
1427 {
1428         struct cl_host *p, *c;
1429         
1430         for (p = c = cl_host_list; c; c = c->list_next) {
1431                 if (c == ch) {
1432                         if (p == c)
1433                                 cl_host_list = c->list_next;
1434                         else
1435                                 p->list_next = c->list_next;
1436                         cl_hosts--;
1437                         return;
1438                 }
1439                 p = c;
1440         }
1441 }
1442
1443 static struct cl_host *net_find_client_host(struct in_addr cl_in_addr)
1444 {
1445         struct cl_host *ch = cl_host_list;
1446
1447         while (ch) {
1448                 if (in_addr_eq(ch->cl_in_addr, cl_in_addr))
1449                         return ch;
1450                 ch = ch->list_next;
1451         }
1452
1453         return NULL;
1454 }
1455
1456 /*
1457  * finalize a net client: truncate files, show stats, cleanup, etc
1458  */
1459 static void net_client_host_done(struct cl_host *ch)
1460 {
1461         free(ch->device_information);
1462         free(ch->net_connections);
1463         net_connects -= ch->nconn;
1464         net_remove_client_host(ch);
1465         free(ch);
1466 }
1467
1468 /*
1469  * handle incoming events from a net client
1470  */
1471 static int net_client_data(struct net_connection *nc)
1472 {
1473         struct thread_information *tip;
1474         struct blktrace_net_hdr bnh;
1475
1476         if (net_get_header(nc, &bnh))
1477                 return 1;
1478
1479         if (data_is_native == -1 && check_data_endianness(bnh.magic)) {
1480                 fprintf(stderr, "server: received data is bad\n");
1481                 return 1;
1482         }
1483
1484         if (!data_is_native) {
1485                 bnh.magic = be32_to_cpu(bnh.magic);
1486                 bnh.cpu = be32_to_cpu(bnh.cpu);
1487                 bnh.len = be32_to_cpu(bnh.len);
1488                 bnh.cl_id = be32_to_cpu(bnh.cl_id);
1489         }
1490
1491         if ((bnh.magic & 0xffffff00) != BLK_IO_TRACE_MAGIC) {
1492                 fprintf(stderr, "server: bad data magic\n");
1493                 return 1;
1494         }
1495
1496         /*
1497          * len == 0 means that the other end signalled end-of-run
1498          */
1499         if (!bnh.len) {
1500                 /*
1501                  * overload cpu count with dropped events
1502                  */
1503                 struct device_information *dip;
1504
1505                 dip = net_get_dip(nc, bnh.buts_name, bnh.cl_id);
1506                 dip->drop_count = bnh.cpu;
1507                 dip->trace_started = 0;
1508
1509                 printf("server: end of run for %s\n", dip->buts_name);
1510                 device_done(nc, dip);
1511
1512                 if (++nc->ch->ndevs_done == nc->ch->ndevs)
1513                         net_client_host_done(nc->ch);
1514                 return 0;
1515         }
1516
1517         tip = net_get_tip(nc, &bnh);
1518         if (!tip)
1519                 return 1;
1520
1521         if (mmap_subbuf(tip, bnh.len))
1522                 return 1;
1523
1524         return 0;
1525 }
1526
1527 static void net_add_connection(int listen_fd, struct sockaddr_in *addr)
1528 {
1529         socklen_t socklen = sizeof(*addr);
1530         struct net_connection *nc;
1531         struct cl_host *ch;
1532         int in_fd;
1533
1534         in_fd = accept(listen_fd, (struct sockaddr *) addr, &socklen);
1535         if (in_fd < 0) {
1536                 perror("accept");
1537                 return;
1538         }
1539
1540         ch = net_find_client_host(addr->sin_addr);
1541         if (!ch) {
1542                 if (cl_hosts == NET_MAX_CL_HOSTS) {
1543                         fprintf(stderr, "server: no more clients allowed\n");
1544                         return;
1545                 }
1546                 ch = malloc(sizeof(struct cl_host));
1547                 memset(ch, 0, sizeof(*ch));
1548                 ch->cl_in_addr = addr->sin_addr;
1549                 net_add_client_host(ch);
1550         }
1551
1552         ch->net_connections = realloc(ch->net_connections, (ch->nconn + 1) * sizeof(*nc));
1553         nc = &ch->net_connections[ch->nconn++];
1554         memset(nc, 0, sizeof(*nc));
1555
1556         printf("server: connection from %s\n", inet_ntoa(addr->sin_addr));
1557         time(&nc->connect_time);
1558         nc->ch = ch;
1559         nc->in_fd = in_fd;
1560         net_connects++;
1561 }
1562
1563 /*
1564  * event driven loop, handle new incoming connections and data from
1565  * existing connections
1566  */
1567 static void net_server_handle_connections(int listen_fd,
1568                                           struct sockaddr_in *addr)
1569 {
1570         struct pollfd *pfds = NULL;
1571         struct net_connection **ncs = NULL;
1572         int max_connects = 0;
1573         int i, nconns, events;
1574         struct cl_host *ch;
1575         struct net_connection *nc;
1576         
1577         printf("server: waiting for connections...\n");
1578
1579         while (!is_done()) {
1580                 if (net_connects >= max_connects) {
1581                         pfds = realloc(pfds, (net_connects + 1) * sizeof(*pfds));
1582                         ncs = realloc(ncs, (net_connects + 1) * sizeof(*ncs));
1583                         max_connects = net_connects + 1;
1584                 }
1585                 /*
1586                  * the zero entry is for incoming connections, remaining
1587                  * entries for clients
1588                  */
1589                 pfds[0].fd = listen_fd;
1590                 pfds[0].events = POLLIN;
1591                 nconns = 0;
1592                 for_each_cl_host(ch) {
1593                         for (i = 0; i < ch->nconn; i++) {
1594                                 nc = &ch->net_connections[i];
1595                                 pfds[nconns + 1].fd = nc->in_fd;
1596                                 pfds[nconns + 1].events = POLLIN;
1597                                 ncs[nconns++] = nc;
1598                         }
1599                 }
1600
1601                 events = poll(pfds, 1 + nconns, -1);
1602                 if (events < 0) {
1603                         if (errno == EINTR)
1604                                 continue;
1605
1606                         perror("poll");
1607                         break;
1608                 } else if (!events)
1609                         continue;
1610
1611                 if (pfds[0].revents & POLLIN) {
1612                         net_add_connection(listen_fd, addr);
1613                         events--;
1614                 }
1615
1616                 for (i = 0; events && i < nconns; i++) {
1617                         if (pfds[i + 1].revents & POLLIN) {
1618                                 net_client_data(ncs[i]);
1619                                 events--;
1620                         }
1621                 }
1622         }
1623 }
1624
1625 /*
1626  * Start here when we are in server mode - just fetch data from the network
1627  * and dump to files
1628  */
1629 static int net_server(void)
1630 {
1631         struct sockaddr_in addr;
1632         int fd, opt;
1633
1634         fd = socket(AF_INET, SOCK_STREAM, 0);
1635         if (fd < 0) {
1636                 perror("server: socket");
1637                 return 1;
1638         }
1639
1640         opt = 1;
1641         if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) {
1642                 perror("setsockopt");
1643                 return 1;
1644         }
1645
1646         memset(&addr, 0, sizeof(addr));
1647         addr.sin_family = AF_INET;
1648         addr.sin_addr.s_addr = htonl(INADDR_ANY);
1649         addr.sin_port = htons(net_port);
1650
1651         if (bind(fd, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
1652                 perror("bind");
1653                 return 1;
1654         }
1655
1656         if (listen(fd, 1) < 0) {
1657                 perror("listen");
1658                 return 1;
1659         }
1660
1661         net_server_handle_connections(fd, &addr);
1662         return 0;
1663 }
1664
1665 /*
1666  * Setup outgoing network connection where we will transmit data
1667  */
1668 static int net_setup_client_cpu(int i, struct sockaddr_in *addr)
1669 {
1670         int fd;
1671
1672         fd = socket(AF_INET, SOCK_STREAM, 0);
1673         if (fd < 0) {
1674                 perror("client: socket");
1675                 return 1;
1676         }
1677
1678         if (connect(fd, (struct sockaddr *) addr, sizeof(*addr)) < 0) {
1679                 perror("client: connect");
1680                 return 1;
1681         }
1682
1683         net_out_fd[i] = fd;
1684         return 0;
1685 }
1686
1687 static int net_setup_client(void)
1688 {
1689         struct sockaddr_in addr;
1690         int i;
1691
1692         memset(&addr, 0, sizeof(addr));
1693         addr.sin_family = AF_INET;
1694         addr.sin_port = htons(net_port);
1695
1696         if (inet_aton(hostname, &addr.sin_addr) != 1) {
1697                 struct hostent *hent = gethostbyname(hostname);
1698                 if (!hent) {
1699                         perror("gethostbyname");
1700                         return 1;
1701                 }
1702
1703                 memcpy(&addr.sin_addr, hent->h_addr, 4);
1704                 strcpy(hostname, hent->h_name);
1705         }
1706
1707         printf("blktrace: connecting to %s\n", hostname);
1708
1709         net_out_fd = malloc(ncpus * sizeof(*net_out_fd));
1710         for (i = 0; i < ncpus; i++) {
1711                 if (net_setup_client_cpu(i, &addr))
1712                         return 1;
1713         }
1714
1715         printf("blktrace: connected!\n");
1716         
1717         return 0;
1718 }
1719
1720 static char usage_str[] = \
1721         "-d <dev> [ -r debugfs path ] [ -o <output> ] [-k ] [ -w time ]\n" \
1722         "[ -a action ] [ -A action mask ] [ -v ]\n\n" \
1723         "\t-d Use specified device. May also be given last after options\n" \
1724         "\t-r Path to mounted debugfs, defaults to /debug\n" \
1725         "\t-o File(s) to send output to\n" \
1726         "\t-D Directory to prepend to output file names\n" \
1727         "\t-k Kill a running trace\n" \
1728         "\t-w Stop after defined time, in seconds\n" \
1729         "\t-a Only trace specified actions. See documentation\n" \
1730         "\t-A Give trace mask as a single value. See documentation\n" \
1731         "\t-b Sub buffer size in KiB\n" \
1732         "\t-n Number of sub buffers\n" \
1733         "\t-l Run in network listen mode (blktrace server)\n" \
1734         "\t-h Run in network client mode, connecting to the given host\n" \
1735         "\t-p Network port to use (default 8462)\n" \
1736         "\t-s Make the network client NOT use sendfile() to transfer data\n" \
1737         "\t-V Print program version info\n\n";
1738
1739 static void show_usage(char *program)
1740 {
1741         fprintf(stderr, "Usage: %s %s %s",program, blktrace_version, usage_str);
1742 }
1743
1744 int main(int argc, char *argv[])
1745 {
1746         static char default_debugfs_path[] = "/debug";
1747         struct statfs st;
1748         int i, c;
1749         int stop_watch = 0;
1750         int act_mask_tmp = 0;
1751
1752         while ((c = getopt_long(argc, argv, S_OPTS, l_opts, NULL)) >= 0) {
1753                 switch (c) {
1754                 case 'a':
1755                         i = find_mask_map(optarg);
1756                         if (i < 0) {
1757                                 fprintf(stderr,"Invalid action mask %s\n",
1758                                         optarg);
1759                                 return 1;
1760                         }
1761                         act_mask_tmp |= i;
1762                         break;
1763
1764                 case 'A':
1765                         if ((sscanf(optarg, "%x", &i) != 1) || 
1766                                                         !valid_act_opt(i)) {
1767                                 fprintf(stderr,
1768                                         "Invalid set action mask %s/0x%x\n",
1769                                         optarg, i);
1770                                 return 1;
1771                         }
1772                         act_mask_tmp = i;
1773                         break;
1774
1775                 case 'd':
1776                         if (resize_devices(optarg) != 0)
1777                                 return 1;
1778                         break;
1779
1780                 case 'r':
1781                         debugfs_path = optarg;
1782                         break;
1783
1784                 case 'o':
1785                         output_name = optarg;
1786                         break;
1787                 case 'k':
1788                         kill_running_trace = 1;
1789                         break;
1790                 case 'w':
1791                         stop_watch = atoi(optarg);
1792                         if (stop_watch <= 0) {
1793                                 fprintf(stderr,
1794                                         "Invalid stopwatch value (%d secs)\n",
1795                                         stop_watch);
1796                                 return 1;
1797                         }
1798                         break;
1799                 case 'V':
1800                         printf("%s version %s\n", argv[0], blktrace_version);
1801                         return 0;
1802                 case 'b':
1803                         buf_size = strtoul(optarg, NULL, 10);
1804                         if (buf_size <= 0 || buf_size > 16*1024) {
1805                                 fprintf(stderr,
1806                                         "Invalid buffer size (%lu)\n",buf_size);
1807                                 return 1;
1808                         }
1809                         buf_size <<= 10;
1810                         break;
1811                 case 'n':
1812                         buf_nr = strtoul(optarg, NULL, 10);
1813                         if (buf_nr <= 0) {
1814                                 fprintf(stderr,
1815                                         "Invalid buffer nr (%lu)\n", buf_nr);
1816                                 return 1;
1817                         }
1818                         break;
1819                 case 'D':
1820                         output_dir = optarg;
1821                         break;
1822                 case 'h':
1823                         net_mode = Net_client;
1824                         strcpy(hostname, optarg);
1825                         break;
1826                 case 'l':
1827                         net_mode = Net_server;
1828                         break;
1829                 case 'p':
1830                         net_port = atoi(optarg);
1831                         break;
1832                 case 's':
1833                         net_use_sendfile = 0;
1834                         break;
1835                 default:
1836                         show_usage(argv[0]);
1837                         return 1;
1838                 }
1839         }
1840
1841         setlocale(LC_NUMERIC, "en_US");
1842
1843         page_size = getpagesize();
1844
1845         if (net_mode == Net_server)
1846                 return net_server();
1847
1848         while (optind < argc) {
1849                 if (resize_devices(argv[optind++]) != 0)
1850                         return 1;
1851         }
1852
1853         if (ndevs == 0) {
1854                 show_usage(argv[0]);
1855                 return 1;
1856         }
1857
1858         if (act_mask_tmp != 0)
1859                 act_mask = act_mask_tmp;
1860
1861         if (!debugfs_path)
1862                 debugfs_path = default_debugfs_path;
1863
1864         if (statfs(debugfs_path, &st) < 0) {
1865                 perror("statfs");
1866                 fprintf(stderr,"%s does not appear to be a valid path\n",
1867                         debugfs_path);
1868                 return 1;
1869         } else if (st.f_type != (long) DEBUGFS_TYPE) {
1870                 fprintf(stderr,"%s does not appear to be a debug filesystem\n",
1871                         debugfs_path);
1872                 return 1;
1873         }
1874
1875         if (open_devices() != 0)
1876                 return 1;
1877
1878         if (kill_running_trace) {
1879                 stop_all_traces();
1880                 return 0;
1881         }
1882
1883         ncpus = sysconf(_SC_NPROCESSORS_ONLN);
1884         if (ncpus < 0) {
1885                 fprintf(stderr, "sysconf(_SC_NPROCESSORS_ONLN) failed\n");
1886                 return 1;
1887         }
1888
1889         signal(SIGINT, handle_sigint);
1890         signal(SIGHUP, handle_sigint);
1891         signal(SIGTERM, handle_sigint);
1892         signal(SIGALRM, handle_sigint);
1893
1894         if (net_mode == Net_client && net_setup_client())
1895                 return 1;
1896
1897         if (start_devices() != 0)
1898                 return 1;
1899
1900         atexit(stop_all_tracing);
1901
1902         if (stop_watch)
1903                 alarm(stop_watch);
1904
1905         wait_for_threads();
1906
1907         if (!is_trace_stopped()) {
1908                 trace_stopped = 1;
1909                 stop_all_threads();
1910                 stop_all_traces();
1911         }
1912
1913         show_stats(device_information, ndevs, ncpus);
1914
1915         return 0;
1916 }
1917