[PATCH] blktrace: add -s sendfile option (doesn't work right now)
[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";
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 RELAYFS_TYPE    0xF0B4A981
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 = "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         off_t offset;
164 };
165
166 #define FIFO_SIZE       (1024)  /* should be plenty big! */
167 #define CL_SIZE         (128)   /* cache line, any bigger? */
168
169 struct tip_subbuf_fifo {
170         int tail __attribute__((aligned(CL_SIZE)));
171         int head __attribute__((aligned(CL_SIZE)));
172         struct tip_subbuf *q[FIFO_SIZE];
173 };
174
175 struct thread_information {
176         int cpu;
177         pthread_t thread;
178
179         int fd;
180         void *fd_buf;
181         char fn[MAXPATHLEN + 64];
182
183         FILE *ofile;
184         char *ofile_buffer;
185         off_t ofile_offset;
186         int ofile_stdout;
187         int ofile_mmap;
188
189         int (*get_subbuf)(struct thread_information *, unsigned int);
190         int (*flush_subbuf)(struct thread_information *, struct tip_subbuf *);
191         int (*read_data)(struct thread_information *, void *, unsigned int);
192
193         unsigned long events_processed;
194         unsigned long long data_read;
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
215 struct device_information {
216         int fd;
217         char *path;
218         char buts_name[32];
219         volatile int trace_started;
220         unsigned long drop_count;
221         struct thread_information *threads;
222 };
223
224 static int ncpus;
225 static struct thread_information *thread_information;
226 static int ndevs;
227 static struct device_information *device_information;
228
229 /* command line option globals */
230 static char *relay_path;
231 static char *output_name;
232 static char *output_dir;
233 static int act_mask = ~0U;
234 static int kill_running_trace;
235 static unsigned long buf_size = BUF_SIZE;
236 static unsigned long buf_nr = BUF_NR;
237 static unsigned int page_size;
238
239 #define is_done()       (*(volatile int *)(&done))
240 static volatile int done;
241
242 #define is_trace_stopped()      (*(volatile int *)(&trace_stopped))
243 static volatile int trace_stopped;
244
245 #define is_stat_shown() (*(volatile int *)(&stat_shown))
246 static volatile int stat_shown;
247
248 int data_is_native = -1;
249
250 static void exit_trace(int status);
251
252 #define dip_tracing(dip)        (*(volatile int *)(&(dip)->trace_started))
253 #define dip_set_tracing(dip, v) ((dip)->trace_started = (v))
254
255 #define __for_each_dip(__d, __i, __e)   \
256         for (__i = 0, __d = device_information; __i < __e; __i++, __d++)
257
258 #define for_each_dip(__d, __i)  __for_each_dip(__d, __i, ndevs)
259 #define for_each_tip(__d, __t, __j)     \
260         for (__j = 0, __t = (__d)->threads; __j < ncpus; __j++, __t++)
261
262 /*
263  * networking stuff follows. we include a magic number so we know whether
264  * to endianness convert or not
265  */
266 struct blktrace_net_hdr {
267         u32 magic;              /* same as trace magic */
268         char buts_name[32];     /* trace name */
269         u32 cpu;                /* for which cpu */
270         u32 max_cpus;
271         u32 len;                /* length of following trace data */
272 };
273
274 #define TRACE_NET_PORT          (8462)
275
276 enum {
277         Net_none = 0,
278         Net_server,
279         Net_client,
280 };
281
282 /*
283  * network cmd line params
284  */
285 static char hostname[MAXHOSTNAMELEN];
286 static int net_port = TRACE_NET_PORT;
287 static int net_mode = 0;
288 static int net_sendfile;
289
290 static int net_in_fd = -1;
291 static int net_out_fd = -1;
292
293 static void handle_sigint(__attribute__((__unused__)) int sig)
294 {
295         done = 1;
296 }
297
298 static int get_dropped_count(const char *buts_name)
299 {
300         int fd;
301         char tmp[MAXPATHLEN + 64];
302
303         snprintf(tmp, sizeof(tmp), "%s/block/%s/dropped",
304                  relay_path, buts_name);
305
306         fd = open(tmp, O_RDONLY);
307         if (fd < 0) {
308                 /*
309                  * this may be ok, if the kernel doesn't support dropped counts
310                  */
311                 if (errno == ENOENT)
312                         return 0;
313
314                 fprintf(stderr, "Couldn't open dropped file %s\n", tmp);
315                 return -1;
316         }
317
318         if (read(fd, tmp, sizeof(tmp)) < 0) {
319                 perror(tmp);
320                 close(fd);
321                 return -1;
322         }
323
324         close(fd);
325
326         return atoi(tmp);
327 }
328
329 static int start_trace(struct device_information *dip)
330 {
331         struct blk_user_trace_setup buts;
332
333         memset(&buts, 0, sizeof(buts));
334         buts.buf_size = buf_size;
335         buts.buf_nr = buf_nr;
336         buts.act_mask = act_mask;
337
338         if (ioctl(dip->fd, BLKTRACESETUP, &buts) < 0) {
339                 perror("BLKTRACESETUP");
340                 return 1;
341         }
342
343         if (ioctl(dip->fd, BLKTRACESTART) < 0) {
344                 perror("BLKTRACESTART");
345                 return 1;
346         }
347
348         memcpy(dip->buts_name, buts.name, sizeof(dip->buts_name));
349         dip_set_tracing(dip, 1);
350         return 0;
351 }
352
353 static void stop_trace(struct device_information *dip)
354 {
355         if (dip_tracing(dip) || kill_running_trace) {
356                 dip_set_tracing(dip, 0);
357
358                 if (ioctl(dip->fd, BLKTRACESTOP) < 0)
359                         perror("BLKTRACESTOP");
360                 if (ioctl(dip->fd, BLKTRACETEARDOWN) < 0)
361                         perror("BLKTRACETEARDOWN");
362
363                 close(dip->fd);
364                 dip->fd = -1;
365         }
366 }
367
368 static void stop_all_traces(void)
369 {
370         struct device_information *dip;
371         int i;
372
373         for_each_dip(dip, i) {
374                 dip->drop_count = get_dropped_count(dip->buts_name);
375                 stop_trace(dip);
376         }
377 }
378
379 static void wait_for_data(struct thread_information *tip)
380 {
381         struct pollfd pfd = { .fd = tip->fd, .events = POLLIN };
382
383         do {
384                 poll(&pfd, 1, 100);
385                 if (pfd.revents & POLLIN)
386                         break;
387                 if (tip->ofile_stdout)
388                         break;
389         } while (!is_done());
390 }
391
392 static int read_data_file(struct thread_information *tip, void *buf,
393                           unsigned int len)
394 {
395         int ret = 0;
396
397         do {
398                 wait_for_data(tip);
399
400                 ret = read(tip->fd, buf, len);
401                 if (!ret)
402                         continue;
403                 else if (ret > 0)
404                         return ret;
405                 else {
406                         if (errno != EAGAIN) {
407                                 perror(tip->fn);
408                                 fprintf(stderr,"Thread %d failed read of %s\n",
409                                         tip->cpu, tip->fn);
410                                 break;
411                         }
412                         continue;
413                 }
414         } while (!is_done());
415
416         return ret;
417
418 }
419
420 static int read_data_net(struct thread_information *tip, void *buf,
421                          unsigned int len)
422 {
423         unsigned int bytes_left = len;
424         int ret = 0;
425
426         do {
427                 ret = recv(net_in_fd, buf, bytes_left, MSG_WAITALL);
428
429                 if (!ret)
430                         continue;
431                 else if (ret < 0) {
432                         if (errno != EAGAIN) {
433                                 perror(tip->fn);
434                                 fprintf(stderr, "server: failed read\n");
435                                 return 0;
436                         }
437                         continue;
438                 } else {
439                         buf += ret;
440                         bytes_left -= ret;
441                 }
442         } while (!is_done() && bytes_left);
443
444         return len - bytes_left;
445 }
446
447 static int read_data(struct thread_information *tip, void *buf,
448                      unsigned int len)
449 {
450         int ret = tip->read_data(tip, buf, len);
451
452         if (ret > 0)
453                 tip->data_read += ret;
454
455         return ret;
456 }
457
458 static inline struct tip_subbuf *
459 subbuf_fifo_dequeue(struct thread_information *tip)
460 {
461         const int head = tip->fifo.head;
462         const int next = (head + 1) & (FIFO_SIZE - 1);
463
464         if (head != tip->fifo.tail) {
465                 struct tip_subbuf *ts = tip->fifo.q[head];
466
467                 store_barrier();
468                 tip->fifo.head = next;
469                 return ts;
470         }
471
472         return NULL;
473 }
474
475 static inline int subbuf_fifo_queue(struct thread_information *tip,
476                                     struct tip_subbuf *ts)
477 {
478         const int tail = tip->fifo.tail;
479         const int next = (tail + 1) & (FIFO_SIZE - 1);
480
481         if (next != tip->fifo.head) {
482                 tip->fifo.q[tail] = ts;
483                 store_barrier();
484                 tip->fifo.tail = next;
485                 return 0;
486         }
487
488         fprintf(stderr, "fifo too small!\n");
489         return 1;
490 }
491
492 /*
493  * For file output, truncate and mmap the file appropriately
494  */
495 static int mmap_subbuf(struct thread_information *tip, unsigned int maxlen)
496 {
497         int ofd = fileno(tip->ofile);
498         int ret;
499
500         /*
501          * extend file, if we have to. use chunks of 16 subbuffers.
502          */
503         if (tip->fs_off + buf_size > tip->fs_buf_len) {
504                 if (tip->fs_buf) {
505                         munlock(tip->fs_buf, tip->fs_buf_len);
506                         munmap(tip->fs_buf, tip->fs_buf_len);
507                         tip->fs_buf = NULL;
508                 }
509
510                 tip->fs_off = tip->fs_size & (page_size - 1);
511                 tip->fs_buf_len = (16 * buf_size) - tip->fs_off;
512                 tip->fs_max_size += tip->fs_buf_len;
513
514                 if (ftruncate(ofd, tip->fs_max_size) < 0) {
515                         perror("ftruncate");
516                         return -1;
517                 }
518
519                 tip->fs_buf = mmap(NULL, tip->fs_buf_len, PROT_WRITE,
520                                    MAP_SHARED, ofd, tip->fs_size - tip->fs_off);
521                 if (tip->fs_buf == MAP_FAILED) {
522                         perror("mmap");
523                         return -1;
524                 }
525                 mlock(tip->fs_buf, tip->fs_buf_len);
526         }
527
528         ret = read_data(tip, tip->fs_buf + tip->fs_off, maxlen);
529         if (ret >= 0) {
530                 tip->fs_size += ret;
531                 tip->fs_off += ret;
532                 return 0;
533         }
534
535         return -1;
536 }
537
538 static int get_subbuf_sendfile(struct thread_information *tip,
539                                unsigned int maxlen)
540 {
541         struct tip_subbuf *ts = malloc(sizeof(*ts));
542         struct stat sb;
543
544         ts->buf = malloc(buf_size);
545         ts->max_len = maxlen;
546         ts->buf = NULL;
547
548         if (fstat(tip->fd, &sb) < 0) {
549                 perror("trace stat");
550                 return 1;
551         }
552
553         ts->len = sb.st_size - tip->ofile_offset;
554         ts->max_len = ts->len;
555         ts->offset = tip->ofile_offset;
556         tip->ofile_offset += ts->len;
557         return subbuf_fifo_queue(tip, ts);
558 }
559
560 /*
561  * Use the copy approach for pipes and network
562  */
563 static int get_subbuf(struct thread_information *tip, unsigned int maxlen)
564 {
565         struct tip_subbuf *ts = malloc(sizeof(*ts));
566         int ret;
567
568         ts->buf = malloc(buf_size);
569         ts->max_len = maxlen;
570
571         ret = read_data(tip, ts->buf, ts->max_len);
572         if (ret > 0) {
573                 ts->len = ret;
574                 return subbuf_fifo_queue(tip, ts);
575         }
576
577         return ret;
578 }
579
580 static void close_thread(struct thread_information *tip)
581 {
582         if (tip->fd != -1)
583                 close(tip->fd);
584         if (tip->ofile)
585                 fclose(tip->ofile);
586         if (tip->ofile_buffer)
587                 free(tip->ofile_buffer);
588         if (tip->fd_buf)
589                 free(tip->fd_buf);
590
591         tip->fd = -1;
592         tip->ofile = NULL;
593         tip->ofile_buffer = NULL;
594         tip->fd_buf = NULL;
595 }
596
597 static void tip_ftrunc_final(struct thread_information *tip)
598 {
599         /*
600          * truncate to right size and cleanup mmap
601          */
602         if (tip->ofile_mmap) {
603                 int ofd = fileno(tip->ofile);
604
605                 if (tip->fs_buf)
606                         munmap(tip->fs_buf, tip->fs_buf_len);
607
608                 ftruncate(ofd, tip->fs_size);
609         }
610 }
611
612 static void *thread_main(void *arg)
613 {
614         struct thread_information *tip = arg;
615         pid_t pid = getpid();
616         cpu_set_t cpu_mask;
617
618         CPU_ZERO(&cpu_mask);
619         CPU_SET((tip->cpu), &cpu_mask);
620
621         if (sched_setaffinity(pid, sizeof(cpu_mask), &cpu_mask) == -1) {
622                 perror("sched_setaffinity");
623                 exit_trace(1);
624         }
625
626         snprintf(tip->fn, sizeof(tip->fn), "%s/block/%s/trace%d",
627                         relay_path, tip->device->buts_name, tip->cpu);
628         tip->fd = open(tip->fn, O_RDONLY);
629         if (tip->fd < 0) {
630                 perror(tip->fn);
631                 fprintf(stderr,"Thread %d failed open of %s\n", tip->cpu,
632                         tip->fn);
633                 exit_trace(1);
634         }
635
636         while (!is_done()) {
637                 if (tip->get_subbuf(tip, buf_size))
638                         break;
639         }
640
641         tip_ftrunc_final(tip);
642         tip->exited = 1;
643         return NULL;
644 }
645
646 static int write_data_net(int fd, void *buf, unsigned int buf_len)
647 {
648         unsigned int bytes_left = buf_len;
649         int ret;
650
651         while (bytes_left) {
652                 ret = send(fd, buf, bytes_left, 0);
653                 if (ret < 0) {
654                         perror("send");
655                         return 1;
656                 }
657
658                 buf += ret;
659                 bytes_left -= ret;
660         }
661
662         return 0;
663 }
664
665 static int net_send_header(struct thread_information *tip, unsigned int len)
666 {
667         struct blktrace_net_hdr hdr;
668
669         hdr.magic = BLK_IO_TRACE_MAGIC;
670         strcpy(hdr.buts_name, tip->device->buts_name);
671         hdr.cpu = tip->cpu;
672         hdr.max_cpus = ncpus;
673         hdr.len = len;
674
675         return write_data_net(net_out_fd, &hdr, sizeof(hdr));
676 }
677
678 static int flush_subbuf_net(struct thread_information *tip,
679                             struct tip_subbuf *ts)
680 {
681         if (net_send_header(tip, ts->len))
682                 return 1;
683         if (write_data_net(net_out_fd, ts->buf, ts->len))
684                 return 1;
685
686         free(ts->buf);
687         free(ts);
688         return 0;
689 }
690
691 static int flush_subbuf_sendfile(struct thread_information *tip,
692                                  struct tip_subbuf *ts)
693 {
694         if (net_send_header(tip, ts->len))
695                 return 1;
696         if (sendfile(net_out_fd, tip->fd, &ts->offset, ts->len) < 0) {
697                 perror("sendfile");
698                 return 1;
699         }
700
701         free(ts);
702         return 0;
703 }
704
705 static int write_data(struct thread_information *tip, void *buf,
706                       unsigned int buf_len)
707 {
708         int ret;
709
710         if (!buf_len)
711                 return 0;
712
713         while (1) {
714                 ret = fwrite(buf, buf_len, 1, tip->ofile);
715                 if (ret == 1)
716                         break;
717
718                 if (ret < 0) {
719                         perror("write");
720                         return 1;
721                 }
722         }
723
724         if (tip->ofile_stdout)
725                 fflush(tip->ofile);
726
727         return 0;
728 }
729
730 static int flush_subbuf_file(struct thread_information *tip,
731                              struct tip_subbuf *ts)
732 {
733         unsigned int offset = 0;
734         struct blk_io_trace *t;
735         int pdu_len, events = 0;
736
737         /*
738          * surplus from last run
739          */
740         if (tip->leftover_ts) {
741                 struct tip_subbuf *prev_ts = tip->leftover_ts;
742
743                 if (prev_ts->len + ts->len > prev_ts->max_len) {
744                         prev_ts->max_len += ts->len;
745                         prev_ts->buf = realloc(prev_ts->buf, prev_ts->max_len);
746                 }
747
748                 memcpy(prev_ts->buf + prev_ts->len, ts->buf, ts->len);
749                 prev_ts->len += ts->len;
750
751                 free(ts->buf);
752                 free(ts);
753
754                 ts = prev_ts;
755                 tip->leftover_ts = NULL;
756         }
757
758         while (offset + sizeof(*t) <= ts->len) {
759                 t = ts->buf + offset;
760
761                 if (verify_trace(t)) {
762                         write_data(tip, ts->buf, offset);
763                         return -1;
764                 }
765
766                 pdu_len = t->pdu_len;
767
768                 if (offset + sizeof(*t) + pdu_len > ts->len)
769                         break;
770
771                 offset += sizeof(*t) + pdu_len;
772                 tip->events_processed++;
773                 tip->data_read += sizeof(*t) + pdu_len;
774                 events++;
775         }
776
777         if (write_data(tip, ts->buf, offset))
778                 return -1;
779
780         /*
781          * leftover bytes, save them for next time
782          */
783         if (offset != ts->len) {
784                 tip->leftover_ts = ts;
785                 ts->len -= offset;
786                 memmove(ts->buf, ts->buf + offset, ts->len);
787         } else {
788                 free(ts->buf);
789                 free(ts);
790         }
791
792         return events;
793 }
794
795 static int write_tip_events(struct thread_information *tip)
796 {
797         struct tip_subbuf *ts = subbuf_fifo_dequeue(tip);
798
799         if (ts)
800                 return tip->flush_subbuf(tip, ts);
801
802         return 0;
803 }
804
805 /*
806  * scans the tips we know and writes out the subbuffers we accumulate
807  */
808 static void get_and_write_events(void)
809 {
810         struct device_information *dip;
811         struct thread_information *tip;
812         int i, j, events, ret, tips_running;
813
814         while (!is_done()) {
815                 events = 0;
816
817                 for_each_dip(dip, i) {
818                         for_each_tip(dip, tip, j) {
819                                 ret = write_tip_events(tip);
820                                 if (ret > 0)
821                                         events += ret;
822                         }
823                 }
824
825                 if (!events)
826                         usleep(10);
827         }
828
829         /*
830          * reap stored events
831          */
832         do {
833                 events = 0;
834                 tips_running = 0;
835                 for_each_dip(dip, i) {
836                         for_each_tip(dip, tip, j) {
837                                 ret = write_tip_events(tip);
838                                 if (ret > 0)
839                                         events += ret;
840                                 tips_running += !tip->exited;
841                         }
842                 }
843                 usleep(10);
844         } while (events || tips_running);
845 }
846
847 static void wait_for_threads(void)
848 {
849         /*
850          * for piped or network output, poll and fetch data for writeout.
851          * for files, we just wait around for trace threads to exit
852          */
853         if ((output_name && !strcmp(output_name, "-")) ||
854             net_mode == Net_client)
855                 get_and_write_events();
856         else {
857                 struct device_information *dip;
858                 struct thread_information *tip;
859                 int i, j, tips_running;
860
861                 do {
862                         tips_running = 0;
863                         usleep(1000);
864
865                         for_each_dip(dip, i)
866                                 for_each_tip(dip, tip, j)
867                                         tips_running += !tip->exited;
868                 } while (tips_running);
869         }
870 }
871
872 static void fill_ofname(char *dst, char *buts_name, int cpu)
873 {
874         int len = 0;
875
876         if (output_dir)
877                 len = sprintf(dst, "%s/", output_dir);
878
879         if (output_name)
880                 sprintf(dst + len, "%s.blktrace.%d", output_name, cpu);
881         else
882                 sprintf(dst + len, "%s.blktrace.%d", buts_name, cpu);
883 }
884
885 static void fill_ops(struct thread_information *tip)
886 {
887         /*
888          * setup ops
889          */
890         if (net_mode == Net_client) {
891                 if (net_sendfile) {
892                         tip->get_subbuf = get_subbuf_sendfile;
893                         tip->flush_subbuf = flush_subbuf_sendfile;
894                 } else {
895                         tip->get_subbuf = get_subbuf;
896                         tip->flush_subbuf = flush_subbuf_net;
897                 }
898         } else {
899                 if (tip->ofile_mmap)
900                         tip->get_subbuf = mmap_subbuf;
901                 else
902                         tip->get_subbuf = get_subbuf;
903
904                 tip->flush_subbuf = flush_subbuf_file;
905         }
906                         
907         if (net_mode == Net_server)
908                 tip->read_data = read_data_net;
909         else
910                 tip->read_data = read_data_file;
911 }
912
913 static int start_threads(struct device_information *dip)
914 {
915         struct thread_information *tip;
916         int j, pipeline = output_name && !strcmp(output_name, "-");
917         int mode, vbuf_size;
918         char op[64];
919
920         for_each_tip(dip, tip, j) {
921                 tip->cpu = j;
922                 tip->device = dip;
923                 tip->events_processed = 0;
924                 memset(&tip->fifo, 0, sizeof(tip->fifo));
925                 tip->leftover_ts = NULL;
926
927                 if (pipeline) {
928                         tip->ofile = fdopen(STDOUT_FILENO, "w");
929                         tip->ofile_stdout = 1;
930                         tip->ofile_mmap = 0;
931                         mode = _IOLBF;
932                         vbuf_size = 512;
933                 } else {
934                         fill_ofname(op, dip->buts_name, tip->cpu);
935                         tip->ofile = fopen(op, "w+");
936                         tip->ofile_stdout = 0;
937                         tip->ofile_mmap = 1;
938                         mode = _IOFBF;
939                         vbuf_size = OFILE_BUF;
940                 }
941
942                 if (tip->ofile == NULL) {
943                         perror(op);
944                         return 1;
945                 }
946
947                 tip->ofile_buffer = malloc(vbuf_size);
948                 if (setvbuf(tip->ofile, tip->ofile_buffer, mode, vbuf_size)) {
949                         perror("setvbuf");
950                         close_thread(tip);
951                         return 1;
952                 }
953
954                 fill_ops(tip);
955
956                 if (pthread_create(&tip->thread, NULL, thread_main, tip)) {
957                         perror("pthread_create");
958                         close_thread(tip);
959                         return 1;
960                 }
961         }
962
963         return 0;
964 }
965
966 static void stop_threads(struct device_information *dip)
967 {
968         struct thread_information *tip;
969         unsigned long ret;
970         int i;
971
972         for_each_tip(dip, tip, i) {
973                 (void) pthread_join(tip->thread, (void *) &ret);
974                 close_thread(tip);
975         }
976 }
977
978 static void stop_all_threads(void)
979 {
980         struct device_information *dip;
981         int i;
982
983         for_each_dip(dip, i)
984                 stop_threads(dip);
985 }
986
987 static void stop_all_tracing(void)
988 {
989         struct device_information *dip;
990         int i;
991
992         for_each_dip(dip, i)
993                 stop_trace(dip);
994 }
995
996 static void exit_trace(int status)
997 {
998         if (!is_trace_stopped()) {
999                 trace_stopped = 1;
1000                 stop_all_threads();
1001                 stop_all_tracing();
1002         }
1003
1004         exit(status);
1005 }
1006
1007 static int resize_devices(char *path)
1008 {
1009         int size = (ndevs + 1) * sizeof(struct device_information);
1010
1011         device_information = realloc(device_information, size);
1012         if (!device_information) {
1013                 fprintf(stderr, "Out of memory, device %s (%d)\n", path, size);
1014                 return 1;
1015         }
1016         device_information[ndevs].path = path;
1017         ndevs++;
1018         return 0;
1019 }
1020
1021 static int open_devices(void)
1022 {
1023         struct device_information *dip;
1024         int i;
1025
1026         for_each_dip(dip, i) {
1027                 dip->fd = open(dip->path, O_RDONLY | O_NONBLOCK);
1028                 if (dip->fd < 0) {
1029                         perror(dip->path);
1030                         return 1;
1031                 }
1032         }
1033
1034         return 0;
1035 }
1036
1037 static int start_devices(void)
1038 {
1039         struct device_information *dip;
1040         int i, j, size;
1041
1042         size = ncpus * sizeof(struct thread_information);
1043         thread_information = malloc(size * ndevs);
1044         if (!thread_information) {
1045                 fprintf(stderr, "Out of memory, threads (%d)\n", size * ndevs);
1046                 return 1;
1047         }
1048
1049         for_each_dip(dip, i) {
1050                 if (start_trace(dip)) {
1051                         close(dip->fd);
1052                         fprintf(stderr, "Failed to start trace on %s\n",
1053                                 dip->path);
1054                         break;
1055                 }
1056         }
1057
1058         if (i != ndevs) {
1059                 __for_each_dip(dip, j, i)
1060                         stop_trace(dip);
1061
1062                 return 1;
1063         }
1064
1065         for_each_dip(dip, i) {
1066                 dip->threads = thread_information + (i * ncpus);
1067                 if (start_threads(dip)) {
1068                         fprintf(stderr, "Failed to start worker threads\n");
1069                         break;
1070                 }
1071         }
1072
1073         if (i != ndevs) {
1074                 __for_each_dip(dip, j, i)
1075                         stop_threads(dip);
1076                 for_each_dip(dip, i)
1077                         stop_trace(dip);
1078
1079                 return 1;
1080         }
1081
1082         return 0;
1083 }
1084
1085 static void show_stats(void)
1086 {
1087         struct device_information *dip;
1088         struct thread_information *tip;
1089         unsigned long long events_processed, data_read;
1090         unsigned long total_drops;
1091         int i, j, no_stdout = 0;
1092
1093         if (is_stat_shown())
1094                 return;
1095
1096         if (output_name && !strcmp(output_name, "-"))
1097                 no_stdout = 1;
1098
1099         stat_shown = 1;
1100
1101         total_drops = 0;
1102         for_each_dip(dip, i) {
1103                 if (!no_stdout)
1104                         printf("Device: %s\n", dip->path);
1105                 events_processed = 0;
1106                 data_read = 0;
1107                 for_each_tip(dip, tip, j) {
1108                         if (!no_stdout)
1109                                 printf("  CPU%3d: %20lu events, %8llu KiB data\n",
1110                                         tip->cpu, tip->events_processed,
1111                                         tip->data_read >> 10);
1112                         events_processed += tip->events_processed;
1113                         data_read += tip->data_read;
1114                 }
1115                 total_drops += dip->drop_count;
1116                 if (!no_stdout)
1117                         printf("  Total:  %20llu events (dropped %lu), %8llu KiB data\n",
1118                                         events_processed, dip->drop_count,
1119                                         data_read >> 10);
1120         }
1121
1122         if (total_drops)
1123                 fprintf(stderr, "You have dropped events, consider using a larger buffer size (-b)\n");
1124 }
1125
1126 static struct device_information *net_get_dip(char *buts_name)
1127 {
1128         struct device_information *dip;
1129         int i;
1130
1131         for (i = 0; i < ndevs; i++) {
1132                 dip = &device_information[i];
1133
1134                 if (!strcmp(dip->buts_name, buts_name))
1135                         return dip;
1136         }
1137
1138         device_information = realloc(device_information, (ndevs + 1) * sizeof(*dip));
1139         dip = &device_information[ndevs];
1140         strcpy(dip->buts_name, buts_name);
1141         strcpy(dip->path, buts_name);
1142         ndevs++;
1143         dip->threads = malloc(ncpus * sizeof(struct thread_information));
1144         memset(dip->threads, 0, ncpus * sizeof(struct thread_information));
1145
1146         /*
1147          * open all files
1148          */
1149         for (i = 0; i < ncpus; i++) {
1150                 struct thread_information *tip = &dip->threads[i];
1151                 char op[64];
1152
1153                 tip->cpu = i;
1154                 tip->ofile_stdout = 0;
1155                 tip->ofile_mmap = 1;
1156                 tip->device = dip;
1157
1158                 fill_ofname(op, dip->buts_name, tip->cpu);
1159
1160                 tip->ofile = fopen(op, "w+");
1161                 if (!tip->ofile) {
1162                         perror("fopen");
1163                         return NULL;
1164                 }
1165         }
1166
1167         return dip;
1168 }
1169
1170 static struct thread_information *net_get_tip(struct blktrace_net_hdr *bnh)
1171 {
1172         struct device_information *dip;
1173
1174         ncpus = bnh->max_cpus;
1175         dip = net_get_dip(bnh->buts_name);
1176         return &dip->threads[bnh->cpu];
1177 }
1178
1179 static int net_get_header(struct blktrace_net_hdr *bnh)
1180 {
1181         int fl = fcntl(net_in_fd, F_GETFL);
1182         int bytes_left, ret;
1183         void *p = bnh;
1184
1185         fcntl(net_in_fd, F_SETFL, fl | O_NONBLOCK);
1186         bytes_left = sizeof(*bnh);
1187         while (bytes_left && !is_done()) {
1188                 ret = recv(net_in_fd, p, bytes_left, MSG_WAITALL);
1189                 if (ret < 0) {
1190                         if (errno != EAGAIN) {
1191                                 perror("recv header");
1192                                 return 1;
1193                         }
1194                         usleep(100);
1195                         continue;
1196                 } else if (!ret) {
1197                         usleep(100);
1198                         continue;
1199                 } else {
1200                         p += ret;
1201                         bytes_left -= ret;
1202                 }
1203         }
1204         fcntl(net_in_fd, F_SETFL, fl & ~O_NONBLOCK);
1205         return 0;
1206 }
1207
1208 static int net_server_loop(void)
1209 {
1210         struct thread_information *tip;
1211         struct blktrace_net_hdr bnh;
1212
1213         if (net_get_header(&bnh))
1214                 return 1;
1215
1216         if (data_is_native == -1 && check_data_endianness(bnh.magic)) {
1217                 fprintf(stderr, "server: received data is bad\n");
1218                 return 1;
1219         }
1220
1221         if (!data_is_native) {
1222                 bnh.cpu = be32_to_cpu(bnh.cpu);
1223                 bnh.len = be32_to_cpu(bnh.len);
1224         }
1225
1226         tip = net_get_tip(&bnh);
1227         if (!tip)
1228                 return 1;
1229
1230         if (mmap_subbuf(tip, bnh.len))
1231                 return 1;
1232
1233         return 0;
1234 }
1235
1236 /*
1237  * Start here when we are in server mode - just fetch data from the network
1238  * and dump to files
1239  */
1240 static int net_server(void)
1241 {
1242         struct sockaddr_in addr;
1243         socklen_t socklen;
1244         int fd, opt, i, j;
1245
1246         fd = socket(AF_INET, SOCK_STREAM, 0);
1247         if (fd < 0) {
1248                 perror("server: socket");
1249                 return 1;
1250         }
1251
1252         opt = 1;
1253         if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) {
1254                 perror("setsockopt");
1255                 return 1;
1256         }
1257
1258         memset(&addr, 0, sizeof(addr));
1259         addr.sin_family = AF_INET;
1260         addr.sin_addr.s_addr = htonl(INADDR_ANY);
1261         addr.sin_port = htons(net_port);
1262
1263         if (bind(fd, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
1264                 perror("bind");
1265                 return 1;
1266         }
1267
1268         if (listen(fd, 1) < 0) {
1269                 perror("listen");
1270                 return 1;
1271         }
1272
1273         printf("blktrace: waiting for incoming connection...\n");
1274
1275         socklen = sizeof(addr);
1276         net_in_fd = accept(fd, (struct sockaddr *) &addr, &socklen);
1277         if (net_in_fd < 0) {
1278                 perror("accept");
1279                 return 1;
1280         }
1281
1282         signal(SIGINT, handle_sigint);
1283         signal(SIGHUP, handle_sigint);
1284         signal(SIGTERM, handle_sigint);
1285         signal(SIGALRM, handle_sigint);
1286
1287         printf("blktrace: connected!\n");
1288
1289         while (!is_done()) {
1290                 if (net_server_loop())
1291                         break;
1292         }
1293
1294         for (i = 0; i < ndevs; i++) {
1295                 struct device_information *dip = &device_information[i];
1296
1297                 for (j = 0; j < ncpus; j++)
1298                         tip_ftrunc_final(&dip->threads[j]);
1299         }
1300
1301         show_stats();
1302         return 0;
1303 }
1304
1305 /*
1306  * Setup outgoing network connection where we will transmit data
1307  */
1308 static int net_setup_client(void)
1309 {
1310         struct sockaddr_in addr;
1311         int fd;
1312
1313         fd = socket(AF_INET, SOCK_STREAM, 0);
1314         if (fd < 0) {
1315                 perror("client: socket");
1316                 return 1;
1317         }
1318
1319         memset(&addr, 0, sizeof(addr));
1320         addr.sin_family = AF_INET;
1321         addr.sin_port = htons(net_port);
1322
1323         if (inet_aton(hostname, &addr.sin_addr) != 1) {
1324                 struct hostent *hent = gethostbyname(hostname);
1325                 if (!hent) {
1326                         perror("gethostbyname");
1327                         return 1;
1328                 }
1329
1330                 memcpy(&addr.sin_addr, hent->h_addr, 4);
1331                 strcpy(hostname, hent->h_name);
1332         }
1333
1334         printf("blktrace: connecting to %s\n", hostname);
1335
1336         if (connect(fd, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
1337                 perror("client: connect");
1338                 return 1;
1339         }
1340
1341         printf("blktrace: connected!\n");
1342         net_out_fd = fd;
1343         return 0;
1344 }
1345
1346 static char usage_str[] = \
1347         "-d <dev> [ -r relay path ] [ -o <output> ] [-k ] [ -w time ]\n" \
1348         "[ -a action ] [ -A action mask ] [ -v ]\n\n" \
1349         "\t-d Use specified device. May also be given last after options\n" \
1350         "\t-r Path to mounted relayfs, defaults to /relay\n" \
1351         "\t-o File(s) to send output to\n" \
1352         "\t-D Directory to prepend to output file names\n" \
1353         "\t-k Kill a running trace\n" \
1354         "\t-w Stop after defined time, in seconds\n" \
1355         "\t-a Only trace specified actions. See documentation\n" \
1356         "\t-A Give trace mask as a single value. See documentation\n" \
1357         "\t-b Sub buffer size in KiB\n" \
1358         "\t-n Number of sub buffers\n" \
1359         "\t-v Print program version info\n\n";
1360
1361 static void show_usage(char *program)
1362 {
1363         fprintf(stderr, "Usage: %s %s %s",program, blktrace_version, usage_str);
1364 }
1365
1366 int main(int argc, char *argv[])
1367 {
1368         static char default_relay_path[] = "/relay";
1369         struct statfs st;
1370         int i, c;
1371         int stop_watch = 0;
1372         int act_mask_tmp = 0;
1373
1374         while ((c = getopt_long(argc, argv, S_OPTS, l_opts, NULL)) >= 0) {
1375                 switch (c) {
1376                 case 'a':
1377                         i = find_mask_map(optarg);
1378                         if (i < 0) {
1379                                 fprintf(stderr,"Invalid action mask %s\n",
1380                                         optarg);
1381                                 return 1;
1382                         }
1383                         act_mask_tmp |= i;
1384                         break;
1385
1386                 case 'A':
1387                         if ((sscanf(optarg, "%x", &i) != 1) || 
1388                                                         !valid_act_opt(i)) {
1389                                 fprintf(stderr,
1390                                         "Invalid set action mask %s/0x%x\n",
1391                                         optarg, i);
1392                                 return 1;
1393                         }
1394                         act_mask_tmp = i;
1395                         break;
1396
1397                 case 'd':
1398                         if (resize_devices(optarg) != 0)
1399                                 return 1;
1400                         break;
1401
1402                 case 'r':
1403                         relay_path = optarg;
1404                         break;
1405
1406                 case 'o':
1407                         output_name = optarg;
1408                         break;
1409                 case 'k':
1410                         kill_running_trace = 1;
1411                         break;
1412                 case 'w':
1413                         stop_watch = atoi(optarg);
1414                         if (stop_watch <= 0) {
1415                                 fprintf(stderr,
1416                                         "Invalid stopwatch value (%d secs)\n",
1417                                         stop_watch);
1418                                 return 1;
1419                         }
1420                         break;
1421                 case 'V':
1422                         printf("%s version %s\n", argv[0], blktrace_version);
1423                         return 0;
1424                 case 'b':
1425                         buf_size = strtoul(optarg, NULL, 10);
1426                         if (buf_size <= 0 || buf_size > 16*1024) {
1427                                 fprintf(stderr,
1428                                         "Invalid buffer size (%lu)\n",buf_size);
1429                                 return 1;
1430                         }
1431                         buf_size <<= 10;
1432                         break;
1433                 case 'n':
1434                         buf_nr = strtoul(optarg, NULL, 10);
1435                         if (buf_nr <= 0) {
1436                                 fprintf(stderr,
1437                                         "Invalid buffer nr (%lu)\n", buf_nr);
1438                                 return 1;
1439                         }
1440                         break;
1441                 case 'D':
1442                         output_dir = optarg;
1443                         break;
1444                 case 'h':
1445                         net_mode = Net_client;
1446                         strcpy(hostname, optarg);
1447                         break;
1448                 case 'l':
1449                         net_mode = Net_server;
1450                         break;
1451                 case 'p':
1452                         net_port = atoi(optarg);
1453                         break;
1454                 case 's':
1455                         net_sendfile = 1;
1456                         break;
1457                 default:
1458                         show_usage(argv[0]);
1459                         return 1;
1460                 }
1461         }
1462
1463         setlocale(LC_NUMERIC, "en_US");
1464
1465         page_size = getpagesize();
1466
1467         if (net_mode == Net_server)
1468                 return net_server();
1469
1470         while (optind < argc) {
1471                 if (resize_devices(argv[optind++]) != 0)
1472                         return 1;
1473         }
1474
1475         if (ndevs == 0) {
1476                 show_usage(argv[0]);
1477                 return 1;
1478         }
1479
1480         if (!relay_path)
1481                 relay_path = default_relay_path;
1482
1483         if (act_mask_tmp != 0)
1484                 act_mask = act_mask_tmp;
1485
1486         if (statfs(relay_path, &st) < 0) {
1487                 perror("statfs");
1488                 fprintf(stderr,"%s does not appear to be a valid path\n",
1489                         relay_path);
1490                 return 1;
1491         } else if (st.f_type != (long) RELAYFS_TYPE) {
1492                 fprintf(stderr,"%s does not appear to be a relay filesystem\n",
1493                         relay_path);
1494                 return 1;
1495         }
1496
1497         if (open_devices() != 0)
1498                 return 1;
1499
1500         if (kill_running_trace) {
1501                 stop_all_traces();
1502                 return 0;
1503         }
1504
1505         ncpus = sysconf(_SC_NPROCESSORS_ONLN);
1506         if (ncpus < 0) {
1507                 fprintf(stderr, "sysconf(_SC_NPROCESSORS_ONLN) failed\n");
1508                 return 1;
1509         }
1510
1511         signal(SIGINT, handle_sigint);
1512         signal(SIGHUP, handle_sigint);
1513         signal(SIGTERM, handle_sigint);
1514         signal(SIGALRM, handle_sigint);
1515
1516         if (net_mode == Net_client && net_setup_client())
1517                 return 1;
1518
1519         if (start_devices() != 0)
1520                 return 1;
1521
1522         atexit(stop_all_tracing);
1523
1524         if (stop_watch)
1525                 alarm(stop_watch);
1526
1527         wait_for_threads();
1528
1529         if (!is_trace_stopped()) {
1530                 trace_stopped = 1;
1531                 stop_all_threads();
1532                 stop_all_traces();
1533         }
1534
1535         show_stats();
1536
1537         return 0;
1538 }
1539