Add nettest/ tools
[splice.git] / nettest / fillfile.c
1 #include <stdio.h>
2 #include <unistd.h>
3 #include <fcntl.h>
4 #include <stdlib.h>
5
6 #include "msg.h"
7 #include "crc32.h"
8 #include "../splice.h"
9
10 static unsigned int msg_size = 4096;
11 static unsigned int file_size = 128;
12 static unsigned long seed = 0x9e37fffffffc0001UL;
13
14 static int usage(const char *name)
15 {
16         fprintf(stderr, "%s: [-s( msg size)] [-z(filesize (mb))] file\n", name);
17         return 1;
18 }
19
20 static int parse_options(int argc, char *argv[])
21 {
22         int c, index = 1;
23
24         while ((c = getopt(argc, argv, "s:z:")) != -1) {
25                 switch (c) {
26                 case 's':
27                         msg_size = atoi(optarg);
28                         index++;
29                         break;
30                 case 'z':
31                         file_size = atoi(optarg);
32                         index++;
33                         break;
34                 default:
35                         return -1;
36                 }
37         }
38
39         printf("msg_size=%u, file_size=%umb\n", msg_size, file_size);
40         return index;
41 }
42
43 static void fill_buf(struct msg *m, unsigned int len)
44 {
45         void *p = m;
46         unsigned int left;
47         unsigned long *val;
48
49         m->msg_size = len;
50         len -= sizeof(*m);
51         p += sizeof(*m);
52
53         left = len;
54         val = p;
55         while (left) {
56                 if (left < sizeof(*val))
57                         break;
58                 *val = rand() * seed;
59                 val++;
60                 left -= sizeof(*val);
61         }
62
63         m->crc32 = crc32(p, len);
64 }
65
66 static int fill_file(int fd)
67 {
68         struct msg *m = malloc(msg_size);
69         unsigned long long fs = (unsigned long long) file_size * 1024 * 1024ULL;
70
71         while (fs) {
72                 if (fs < msg_size)
73                         break;
74
75                 fill_buf(m, msg_size);
76                 write(fd, m, msg_size);
77                 fs -= msg_size;
78         }
79
80         close(fd);
81         return 0;
82 }
83
84 int main(int argc, char *argv[])
85 {
86         int fd, index;
87
88         if (argc < 2)
89                 return usage(argv[0]);
90
91         index = parse_options(argc, argv);
92         if (index == -1 || index + 1 > argc)
93                 return usage(argv[0]);
94
95         fd = open(argv[index], O_WRONLY | O_CREAT | O_TRUNC, 0644);
96         if (fd < 0)
97                 return error("open output file");
98
99         return fill_file(fd);
100 }