Avoid client calls to recv() without prior poll()
[fio.git] / server.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <errno.h>
5 #include <poll.h>
6 #include <sys/types.h>
7 #include <sys/wait.h>
8 #include <sys/socket.h>
9 #include <sys/stat.h>
10 #include <sys/un.h>
11 #include <sys/uio.h>
12 #include <netinet/in.h>
13 #include <arpa/inet.h>
14 #include <netdb.h>
15 #include <syslog.h>
16 #include <signal.h>
17 #ifdef CONFIG_ZLIB
18 #include <zlib.h>
19 #endif
20
21 #include "fio.h"
22 #include "options.h"
23 #include "server.h"
24 #include "crc/crc16.h"
25 #include "lib/ieee754.h"
26 #include "verify-state.h"
27 #include "smalloc.h"
28
29 int fio_net_port = FIO_NET_PORT;
30
31 bool exit_backend = false;
32
33 enum {
34         SK_F_FREE       = 1,
35         SK_F_COPY       = 2,
36         SK_F_SIMPLE     = 4,
37         SK_F_VEC        = 8,
38         SK_F_INLINE     = 16,
39 };
40
41 struct sk_entry {
42         struct flist_head list; /* link on sk_out->list */
43         int flags;              /* SK_F_* */
44         int opcode;             /* Actual command fields */
45         void *buf;
46         off_t size;
47         uint64_t tag;
48         struct flist_head next; /* Other sk_entry's, if linked command */
49 };
50
51 static char *fio_server_arg;
52 static char *bind_sock;
53 static struct sockaddr_in saddr_in;
54 static struct sockaddr_in6 saddr_in6;
55 static int use_ipv6;
56 #ifdef CONFIG_ZLIB
57 static unsigned int has_zlib = 1;
58 #else
59 static unsigned int has_zlib = 0;
60 #endif
61 static unsigned int use_zlib;
62 static char me[128];
63
64 static pthread_key_t sk_out_key;
65
66 struct fio_fork_item {
67         struct flist_head list;
68         int exitval;
69         int signal;
70         int exited;
71         pid_t pid;
72 };
73
74 struct cmd_reply {
75         struct fio_sem lock;
76         void *data;
77         size_t size;
78         int error;
79 };
80
81 static const char *fio_server_ops[FIO_NET_CMD_NR] = {
82         "",
83         "QUIT",
84         "EXIT",
85         "JOB",
86         "JOBLINE",
87         "TEXT",
88         "TS",
89         "GS",
90         "SEND_ETA",
91         "ETA",
92         "PROBE",
93         "START",
94         "STOP",
95         "DISK_UTIL",
96         "SERVER_START",
97         "ADD_JOB",
98         "RUN",
99         "IOLOG",
100         "UPDATE_JOB",
101         "LOAD_FILE",
102         "VTRIGGER",
103         "SENDFILE",
104         "JOB_OPT",
105 };
106
107 static void sk_lock(struct sk_out *sk_out)
108 {
109         fio_sem_down(&sk_out->lock);
110 }
111
112 static void sk_unlock(struct sk_out *sk_out)
113 {
114         fio_sem_up(&sk_out->lock);
115 }
116
117 void sk_out_assign(struct sk_out *sk_out)
118 {
119         if (!sk_out)
120                 return;
121
122         sk_lock(sk_out);
123         sk_out->refs++;
124         sk_unlock(sk_out);
125         pthread_setspecific(sk_out_key, sk_out);
126 }
127
128 static void sk_out_free(struct sk_out *sk_out)
129 {
130         __fio_sem_remove(&sk_out->lock);
131         __fio_sem_remove(&sk_out->wait);
132         __fio_sem_remove(&sk_out->xmit);
133         sfree(sk_out);
134 }
135
136 static int __sk_out_drop(struct sk_out *sk_out)
137 {
138         if (sk_out) {
139                 int refs;
140
141                 sk_lock(sk_out);
142                 assert(sk_out->refs != 0);
143                 refs = --sk_out->refs;
144                 sk_unlock(sk_out);
145
146                 if (!refs) {
147                         sk_out_free(sk_out);
148                         pthread_setspecific(sk_out_key, NULL);
149                         return 0;
150                 }
151         }
152
153         return 1;
154 }
155
156 void sk_out_drop(void)
157 {
158         struct sk_out *sk_out;
159
160         sk_out = pthread_getspecific(sk_out_key);
161         __sk_out_drop(sk_out);
162 }
163
164 static void __fio_init_net_cmd(struct fio_net_cmd *cmd, uint16_t opcode,
165                                uint32_t pdu_len, uint64_t tag)
166 {
167         memset(cmd, 0, sizeof(*cmd));
168
169         cmd->version    = __cpu_to_le16(FIO_SERVER_VER);
170         cmd->opcode     = cpu_to_le16(opcode);
171         cmd->tag        = cpu_to_le64(tag);
172         cmd->pdu_len    = cpu_to_le32(pdu_len);
173 }
174
175
176 static void fio_init_net_cmd(struct fio_net_cmd *cmd, uint16_t opcode,
177                              const void *pdu, uint32_t pdu_len, uint64_t tag)
178 {
179         __fio_init_net_cmd(cmd, opcode, pdu_len, tag);
180
181         if (pdu)
182                 memcpy(&cmd->payload, pdu, pdu_len);
183 }
184
185 const char *fio_server_op(unsigned int op)
186 {
187         static char buf[32];
188
189         if (op < FIO_NET_CMD_NR)
190                 return fio_server_ops[op];
191
192         sprintf(buf, "UNKNOWN/%d", op);
193         return buf;
194 }
195
196 static ssize_t iov_total_len(const struct iovec *iov, int count)
197 {
198         ssize_t ret = 0;
199
200         while (count--) {
201                 ret += iov->iov_len;
202                 iov++;
203         }
204
205         return ret;
206 }
207
208 static int fio_sendv_data(int sk, struct iovec *iov, int count)
209 {
210         ssize_t total_len = iov_total_len(iov, count);
211         ssize_t ret;
212
213         do {
214                 ret = writev(sk, iov, count);
215                 if (ret > 0) {
216                         total_len -= ret;
217                         if (!total_len)
218                                 break;
219
220                         while (ret) {
221                                 if (ret >= iov->iov_len) {
222                                         ret -= iov->iov_len;
223                                         iov++;
224                                         continue;
225                                 }
226                                 iov->iov_base += ret;
227                                 iov->iov_len -= ret;
228                                 ret = 0;
229                         }
230                 } else if (!ret)
231                         break;
232                 else if (errno == EAGAIN || errno == EINTR)
233                         continue;
234                 else
235                         break;
236         } while (!exit_backend);
237
238         if (!total_len)
239                 return 0;
240
241         return 1;
242 }
243
244 static int fio_send_data(int sk, const void *p, unsigned int len)
245 {
246         struct iovec iov = { .iov_base = (void *) p, .iov_len = len };
247
248         assert(len <= sizeof(struct fio_net_cmd) + FIO_SERVER_MAX_FRAGMENT_PDU);
249
250         return fio_sendv_data(sk, &iov, 1);
251 }
252
253 bool fio_server_poll_fd(int fd, short events, int timeout) {
254         struct pollfd pfd = {
255                 .fd     = fd,
256                 .events = events,
257         };
258         int ret;
259
260         ret = poll(&pfd, 1, timeout);
261         if (ret < 0) {
262                 if (errno == EINTR)
263                         return false;
264                 log_err("fio: poll: %s\n", strerror(errno));
265                 return false;
266         } else if (!ret) {
267                 return false;
268         }
269         if (pfd.revents & events)
270                 return true;
271         return false;
272 }
273
274 static int fio_recv_data(int sk, void *buf, unsigned int len, bool wait)
275 {
276         int flags;
277         char *p = buf;
278
279         if (wait)
280                 flags = MSG_WAITALL;
281         else
282                 flags = OS_MSG_DONTWAIT;
283
284         do {
285                 int ret = recv(sk, p, len, flags);
286
287                 if (ret > 0) {
288                         len -= ret;
289                         if (!len)
290                                 break;
291                         p += ret;
292                         continue;
293                 } else if (!ret)
294                         break;
295                 else if (errno == EAGAIN || errno == EINTR) {
296                         if (wait)
297                                 continue;
298                         break;
299                 } else
300                         break;
301         } while (!exit_backend);
302
303         if (!len)
304                 return 0;
305
306         return -1;
307 }
308
309 static int verify_convert_cmd(struct fio_net_cmd *cmd)
310 {
311         uint16_t crc;
312
313         cmd->cmd_crc16 = le16_to_cpu(cmd->cmd_crc16);
314         cmd->pdu_crc16 = le16_to_cpu(cmd->pdu_crc16);
315
316         crc = fio_crc16(cmd, FIO_NET_CMD_CRC_SZ);
317         if (crc != cmd->cmd_crc16) {
318                 log_err("fio: server bad crc on command (got %x, wanted %x)\n",
319                                 cmd->cmd_crc16, crc);
320                 fprintf(f_err, "fio: server bad crc on command (got %x, wanted %x)\n",
321                                 cmd->cmd_crc16, crc);
322                 return 1;
323         }
324
325         cmd->version    = le16_to_cpu(cmd->version);
326         cmd->opcode     = le16_to_cpu(cmd->opcode);
327         cmd->flags      = le32_to_cpu(cmd->flags);
328         cmd->tag        = le64_to_cpu(cmd->tag);
329         cmd->pdu_len    = le32_to_cpu(cmd->pdu_len);
330
331         switch (cmd->version) {
332         case FIO_SERVER_VER:
333                 break;
334         default:
335                 log_err("fio: bad server cmd version %d\n", cmd->version);
336                 fprintf(f_err, "fio: client/server version mismatch (%d != %d)\n",
337                                 cmd->version, FIO_SERVER_VER);
338                 return 1;
339         }
340
341         if (cmd->pdu_len > FIO_SERVER_MAX_FRAGMENT_PDU) {
342                 log_err("fio: command payload too large: %u\n", cmd->pdu_len);
343                 return 1;
344         }
345
346         return 0;
347 }
348
349 /*
350  * Read (and defragment, if necessary) incoming commands
351  */
352 struct fio_net_cmd *fio_net_recv_cmd(int sk, bool wait)
353 {
354         struct fio_net_cmd cmd, *tmp, *cmdret = NULL;
355         size_t cmd_size = 0, pdu_offset = 0;
356         uint16_t crc;
357         int ret, first = 1;
358         void *pdu = NULL;
359
360         do {
361                 ret = fio_recv_data(sk, &cmd, sizeof(cmd), wait);
362                 if (ret)
363                         break;
364
365                 /* We have a command, verify it and swap if need be */
366                 ret = verify_convert_cmd(&cmd);
367                 if (ret)
368                         break;
369
370                 if (first) {
371                         /* if this is text, add room for \0 at the end */
372                         cmd_size = sizeof(cmd) + cmd.pdu_len + 1;
373                         assert(!cmdret);
374                 } else
375                         cmd_size += cmd.pdu_len;
376
377                 if (cmd_size / 1024 > FIO_SERVER_MAX_CMD_MB * 1024) {
378                         log_err("fio: cmd+pdu too large (%llu)\n", (unsigned long long) cmd_size);
379                         ret = 1;
380                         break;
381                 }
382
383                 tmp = realloc(cmdret, cmd_size);
384                 if (!tmp) {
385                         log_err("fio: server failed allocating cmd\n");
386                         ret = 1;
387                         break;
388                 }
389                 cmdret = tmp;
390
391                 if (first)
392                         memcpy(cmdret, &cmd, sizeof(cmd));
393                 else if (cmdret->opcode != cmd.opcode) {
394                         log_err("fio: fragment opcode mismatch (%d != %d)\n",
395                                         cmdret->opcode, cmd.opcode);
396                         ret = 1;
397                         break;
398                 }
399
400                 if (!cmd.pdu_len)
401                         break;
402
403                 /* There's payload, get it */
404                 pdu = (char *) cmdret->payload + pdu_offset;
405                 ret = fio_recv_data(sk, pdu, cmd.pdu_len, wait);
406                 if (ret)
407                         break;
408
409                 /* Verify payload crc */
410                 crc = fio_crc16(pdu, cmd.pdu_len);
411                 if (crc != cmd.pdu_crc16) {
412                         log_err("fio: server bad crc on payload ");
413                         log_err("(got %x, wanted %x)\n", cmd.pdu_crc16, crc);
414                         ret = 1;
415                         break;
416                 }
417
418                 pdu_offset += cmd.pdu_len;
419                 if (!first)
420                         cmdret->pdu_len += cmd.pdu_len;
421                 first = 0;
422         } while (cmd.flags & FIO_NET_CMD_F_MORE);
423
424         if (ret) {
425                 free(cmdret);
426                 cmdret = NULL;
427         } else if (cmdret) {
428                 /* zero-terminate text input */
429                 if (cmdret->pdu_len) {
430                         if (cmdret->opcode == FIO_NET_CMD_TEXT) {
431                                 struct cmd_text_pdu *__pdu = (struct cmd_text_pdu *) cmdret->payload;
432                                 char *buf = (char *) __pdu->buf;
433                                 int len = le32_to_cpu(__pdu->buf_len);
434
435                                 buf[len] = '\0';
436                         } else if (cmdret->opcode == FIO_NET_CMD_JOB) {
437                                 struct cmd_job_pdu *__pdu = (struct cmd_job_pdu *) cmdret->payload;
438                                 char *buf = (char *) __pdu->buf;
439                                 int len = le32_to_cpu(__pdu->buf_len);
440
441                                 buf[len] = '\0';
442                         }
443                 }
444
445                 /* frag flag is internal */
446                 cmdret->flags &= ~FIO_NET_CMD_F_MORE;
447         }
448
449         return cmdret;
450 }
451
452 static void add_reply(uint64_t tag, struct flist_head *list)
453 {
454         struct fio_net_cmd_reply *reply;
455
456         reply = (struct fio_net_cmd_reply *) (uintptr_t) tag;
457         flist_add_tail(&reply->list, list);
458 }
459
460 static uint64_t alloc_reply(uint64_t tag, uint16_t opcode)
461 {
462         struct fio_net_cmd_reply *reply;
463
464         reply = calloc(1, sizeof(*reply));
465         INIT_FLIST_HEAD(&reply->list);
466         fio_gettime(&reply->ts, NULL);
467         reply->saved_tag = tag;
468         reply->opcode = opcode;
469
470         return (uintptr_t) reply;
471 }
472
473 static void free_reply(uint64_t tag)
474 {
475         struct fio_net_cmd_reply *reply;
476
477         reply = (struct fio_net_cmd_reply *) (uintptr_t) tag;
478         free(reply);
479 }
480
481 static void fio_net_cmd_crc_pdu(struct fio_net_cmd *cmd, const void *pdu)
482 {
483         uint32_t pdu_len;
484
485         cmd->cmd_crc16 = __cpu_to_le16(fio_crc16(cmd, FIO_NET_CMD_CRC_SZ));
486
487         pdu_len = le32_to_cpu(cmd->pdu_len);
488         cmd->pdu_crc16 = __cpu_to_le16(fio_crc16(pdu, pdu_len));
489 }
490
491 static void fio_net_cmd_crc(struct fio_net_cmd *cmd)
492 {
493         fio_net_cmd_crc_pdu(cmd, cmd->payload);
494 }
495
496 int fio_net_send_cmd(int fd, uint16_t opcode, const void *buf, off_t size,
497                      uint64_t *tagptr, struct flist_head *list)
498 {
499         struct fio_net_cmd *cmd = NULL;
500         size_t this_len, cur_len = 0;
501         uint64_t tag;
502         int ret;
503
504         if (list) {
505                 assert(tagptr);
506                 tag = *tagptr = alloc_reply(*tagptr, opcode);
507         } else
508                 tag = tagptr ? *tagptr : 0;
509
510         do {
511                 this_len = size;
512                 if (this_len > FIO_SERVER_MAX_FRAGMENT_PDU)
513                         this_len = FIO_SERVER_MAX_FRAGMENT_PDU;
514
515                 if (!cmd || cur_len < sizeof(*cmd) + this_len) {
516                         if (cmd)
517                                 free(cmd);
518
519                         cur_len = sizeof(*cmd) + this_len;
520                         cmd = malloc(cur_len);
521                 }
522
523                 fio_init_net_cmd(cmd, opcode, buf, this_len, tag);
524
525                 if (this_len < size)
526                         cmd->flags = __cpu_to_le32(FIO_NET_CMD_F_MORE);
527
528                 fio_net_cmd_crc(cmd);
529
530                 ret = fio_send_data(fd, cmd, sizeof(*cmd) + this_len);
531                 size -= this_len;
532                 buf += this_len;
533         } while (!ret && size);
534
535         if (list) {
536                 if (ret)
537                         free_reply(tag);
538                 else
539                         add_reply(tag, list);
540         }
541
542         if (cmd)
543                 free(cmd);
544
545         return ret;
546 }
547
548 static struct sk_entry *fio_net_prep_cmd(uint16_t opcode, void *buf,
549                                          size_t size, uint64_t *tagptr,
550                                          int flags)
551 {
552         struct sk_entry *entry;
553
554         entry = smalloc(sizeof(*entry));
555         if (!entry)
556                 return NULL;
557
558         INIT_FLIST_HEAD(&entry->next);
559         entry->opcode = opcode;
560         if (flags & SK_F_COPY) {
561                 entry->buf = smalloc(size);
562                 memcpy(entry->buf, buf, size);
563         } else
564                 entry->buf = buf;
565
566         entry->size = size;
567         if (tagptr)
568                 entry->tag = *tagptr;
569         else
570                 entry->tag = 0;
571         entry->flags = flags;
572         return entry;
573 }
574
575 static int handle_sk_entry(struct sk_out *sk_out, struct sk_entry *entry);
576
577 static void fio_net_queue_entry(struct sk_entry *entry)
578 {
579         struct sk_out *sk_out = pthread_getspecific(sk_out_key);
580
581         if (entry->flags & SK_F_INLINE)
582                 handle_sk_entry(sk_out, entry);
583         else {
584                 sk_lock(sk_out);
585                 flist_add_tail(&entry->list, &sk_out->list);
586                 sk_unlock(sk_out);
587
588                 fio_sem_up(&sk_out->wait);
589         }
590 }
591
592 static int fio_net_queue_cmd(uint16_t opcode, void *buf, off_t size,
593                              uint64_t *tagptr, int flags)
594 {
595         struct sk_entry *entry;
596
597         entry = fio_net_prep_cmd(opcode, buf, size, tagptr, flags);
598         if (entry) {
599                 fio_net_queue_entry(entry);
600                 return 0;
601         }
602
603         return 1;
604 }
605
606 static int fio_net_send_simple_stack_cmd(int sk, uint16_t opcode, uint64_t tag)
607 {
608         struct fio_net_cmd cmd;
609
610         fio_init_net_cmd(&cmd, opcode, NULL, 0, tag);
611         fio_net_cmd_crc(&cmd);
612
613         return fio_send_data(sk, &cmd, sizeof(cmd));
614 }
615
616 /*
617  * If 'list' is non-NULL, then allocate and store the sent command for
618  * later verification.
619  */
620 int fio_net_send_simple_cmd(int sk, uint16_t opcode, uint64_t tag,
621                             struct flist_head *list)
622 {
623         int ret;
624
625         if (list)
626                 tag = alloc_reply(tag, opcode);
627
628         ret = fio_net_send_simple_stack_cmd(sk, opcode, tag);
629         if (ret) {
630                 if (list)
631                         free_reply(tag);
632
633                 return ret;
634         }
635
636         if (list)
637                 add_reply(tag, list);
638
639         return 0;
640 }
641
642 static int fio_net_queue_quit(void)
643 {
644         dprint(FD_NET, "server: sending quit\n");
645
646         return fio_net_queue_cmd(FIO_NET_CMD_QUIT, NULL, 0, NULL, SK_F_SIMPLE);
647 }
648
649 int fio_net_send_quit(int sk)
650 {
651         dprint(FD_NET, "server: sending quit\n");
652
653         return fio_net_send_simple_cmd(sk, FIO_NET_CMD_QUIT, 0, NULL);
654 }
655
656 static int fio_net_send_ack(struct fio_net_cmd *cmd, int error, int signal)
657 {
658         struct cmd_end_pdu epdu;
659         uint64_t tag = 0;
660
661         if (cmd)
662                 tag = cmd->tag;
663
664         epdu.error = __cpu_to_le32(error);
665         epdu.signal = __cpu_to_le32(signal);
666         return fio_net_queue_cmd(FIO_NET_CMD_STOP, &epdu, sizeof(epdu), &tag, SK_F_COPY);
667 }
668
669 static int fio_net_queue_stop(int error, int signal)
670 {
671         dprint(FD_NET, "server: sending stop (%d, %d)\n", error, signal);
672         return fio_net_send_ack(NULL, error, signal);
673 }
674
675 static void fio_server_add_fork_item(pid_t pid, struct flist_head *list)
676 {
677         struct fio_fork_item *ffi;
678
679         ffi = malloc(sizeof(*ffi));
680         ffi->exitval = 0;
681         ffi->signal = 0;
682         ffi->exited = 0;
683         ffi->pid = pid;
684         flist_add_tail(&ffi->list, list);
685 }
686
687 static void fio_server_add_conn_pid(struct flist_head *conn_list, pid_t pid)
688 {
689         dprint(FD_NET, "server: forked off connection job (pid=%u)\n", (int) pid);
690         fio_server_add_fork_item(pid, conn_list);
691 }
692
693 static void fio_server_add_job_pid(struct flist_head *job_list, pid_t pid)
694 {
695         dprint(FD_NET, "server: forked off job job (pid=%u)\n", (int) pid);
696         fio_server_add_fork_item(pid, job_list);
697 }
698
699 static void fio_server_check_fork_item(struct fio_fork_item *ffi)
700 {
701         int ret, status;
702
703         ret = waitpid(ffi->pid, &status, WNOHANG);
704         if (ret < 0) {
705                 if (errno == ECHILD) {
706                         log_err("fio: connection pid %u disappeared\n", (int) ffi->pid);
707                         ffi->exited = 1;
708                 } else
709                         log_err("fio: waitpid: %s\n", strerror(errno));
710         } else if (ret == ffi->pid) {
711                 if (WIFSIGNALED(status)) {
712                         ffi->signal = WTERMSIG(status);
713                         ffi->exited = 1;
714                 }
715                 if (WIFEXITED(status)) {
716                         if (WEXITSTATUS(status))
717                                 ffi->exitval = WEXITSTATUS(status);
718                         ffi->exited = 1;
719                 }
720         }
721 }
722
723 static void fio_server_fork_item_done(struct fio_fork_item *ffi, bool stop)
724 {
725         dprint(FD_NET, "pid %u exited, sig=%u, exitval=%d\n", (int) ffi->pid, ffi->signal, ffi->exitval);
726
727         /*
728          * Fold STOP and QUIT...
729          */
730         if (stop) {
731                 fio_net_queue_stop(ffi->exitval, ffi->signal);
732                 fio_net_queue_quit();
733         }
734
735         flist_del(&ffi->list);
736         free(ffi);
737 }
738
739 static void fio_server_check_fork_items(struct flist_head *list, bool stop)
740 {
741         struct flist_head *entry, *tmp;
742         struct fio_fork_item *ffi;
743
744         flist_for_each_safe(entry, tmp, list) {
745                 ffi = flist_entry(entry, struct fio_fork_item, list);
746
747                 fio_server_check_fork_item(ffi);
748
749                 if (ffi->exited)
750                         fio_server_fork_item_done(ffi, stop);
751         }
752 }
753
754 static void fio_server_check_jobs(struct flist_head *job_list)
755 {
756         fio_server_check_fork_items(job_list, true);
757 }
758
759 static void fio_server_check_conns(struct flist_head *conn_list)
760 {
761         fio_server_check_fork_items(conn_list, false);
762 }
763
764 static int handle_load_file_cmd(struct fio_net_cmd *cmd)
765 {
766         struct cmd_load_file_pdu *pdu = (struct cmd_load_file_pdu *) cmd->payload;
767         void *file_name = pdu->file;
768         struct cmd_start_pdu spdu;
769
770         dprint(FD_NET, "server: loading local file %s\n", (char *) file_name);
771
772         pdu->name_len = le16_to_cpu(pdu->name_len);
773         pdu->client_type = le16_to_cpu(pdu->client_type);
774
775         if (parse_jobs_ini(file_name, 0, 0, pdu->client_type)) {
776                 fio_net_queue_quit();
777                 return -1;
778         }
779
780         spdu.jobs = cpu_to_le32(thread_number);
781         spdu.stat_outputs = cpu_to_le32(stat_number);
782         fio_net_queue_cmd(FIO_NET_CMD_START, &spdu, sizeof(spdu), NULL, SK_F_COPY);
783         return 0;
784 }
785
786 static int handle_run_cmd(struct sk_out *sk_out, struct flist_head *job_list,
787                           struct fio_net_cmd *cmd)
788 {
789         pid_t pid;
790         int ret;
791
792         sk_out_assign(sk_out);
793
794         fio_time_init();
795         set_genesis_time();
796
797         pid = fork();
798         if (pid) {
799                 fio_server_add_job_pid(job_list, pid);
800                 return 0;
801         }
802
803         ret = fio_backend(sk_out);
804         free_threads_shm();
805         sk_out_drop();
806         _exit(ret);
807 }
808
809 static int handle_job_cmd(struct fio_net_cmd *cmd)
810 {
811         struct cmd_job_pdu *pdu = (struct cmd_job_pdu *) cmd->payload;
812         void *buf = pdu->buf;
813         struct cmd_start_pdu spdu;
814
815         pdu->buf_len = le32_to_cpu(pdu->buf_len);
816         pdu->client_type = le32_to_cpu(pdu->client_type);
817
818         if (parse_jobs_ini(buf, 1, 0, pdu->client_type)) {
819                 fio_net_queue_quit();
820                 return -1;
821         }
822
823         spdu.jobs = cpu_to_le32(thread_number);
824         spdu.stat_outputs = cpu_to_le32(stat_number);
825
826         fio_net_queue_cmd(FIO_NET_CMD_START, &spdu, sizeof(spdu), NULL, SK_F_COPY);
827         return 0;
828 }
829
830 static int handle_jobline_cmd(struct fio_net_cmd *cmd)
831 {
832         void *pdu = cmd->payload;
833         struct cmd_single_line_pdu *cslp;
834         struct cmd_line_pdu *clp;
835         unsigned long offset;
836         struct cmd_start_pdu spdu;
837         char **argv;
838         int i;
839
840         clp = pdu;
841         clp->lines = le16_to_cpu(clp->lines);
842         clp->client_type = le16_to_cpu(clp->client_type);
843         argv = malloc(clp->lines * sizeof(char *));
844         offset = sizeof(*clp);
845
846         dprint(FD_NET, "server: %d command line args\n", clp->lines);
847
848         for (i = 0; i < clp->lines; i++) {
849                 cslp = pdu + offset;
850                 argv[i] = (char *) cslp->text;
851
852                 offset += sizeof(*cslp) + le16_to_cpu(cslp->len);
853                 dprint(FD_NET, "server: %d: %s\n", i, argv[i]);
854         }
855
856         if (parse_cmd_line(clp->lines, argv, clp->client_type)) {
857                 fio_net_queue_quit();
858                 free(argv);
859                 return -1;
860         }
861
862         free(argv);
863
864         spdu.jobs = cpu_to_le32(thread_number);
865         spdu.stat_outputs = cpu_to_le32(stat_number);
866
867         fio_net_queue_cmd(FIO_NET_CMD_START, &spdu, sizeof(spdu), NULL, SK_F_COPY);
868         return 0;
869 }
870
871 static int handle_probe_cmd(struct fio_net_cmd *cmd)
872 {
873         struct cmd_client_probe_pdu *pdu = (struct cmd_client_probe_pdu *) cmd->payload;
874         uint64_t tag = cmd->tag;
875         struct cmd_probe_reply_pdu probe = {
876 #ifdef CONFIG_BIG_ENDIAN
877                 .bigendian      = 1,
878 #endif
879                 .os             = FIO_OS,
880                 .arch           = FIO_ARCH,
881                 .bpp            = sizeof(void *),
882                 .cpus           = __cpu_to_le32(cpus_online()),
883         };
884
885         dprint(FD_NET, "server: sending probe reply\n");
886
887         strcpy(me, (char *) pdu->server);
888
889         gethostname((char *) probe.hostname, sizeof(probe.hostname));
890         snprintf((char *) probe.fio_version, sizeof(probe.fio_version), "%s",
891                  fio_version_string);
892
893         /*
894          * If the client supports compression and we do too, then enable it
895          */
896         if (has_zlib && le64_to_cpu(pdu->flags) & FIO_PROBE_FLAG_ZLIB) {
897                 probe.flags = __cpu_to_le64(FIO_PROBE_FLAG_ZLIB);
898                 use_zlib = 1;
899         } else {
900                 probe.flags = 0;
901                 use_zlib = 0;
902         }
903
904         return fio_net_queue_cmd(FIO_NET_CMD_PROBE, &probe, sizeof(probe), &tag, SK_F_COPY);
905 }
906
907 static int handle_send_eta_cmd(struct fio_net_cmd *cmd)
908 {
909         struct jobs_eta *je;
910         uint64_t tag = cmd->tag;
911         size_t size;
912         int i;
913
914         dprint(FD_NET, "server sending status\n");
915
916         /*
917          * Fake ETA return if we don't have a local one, otherwise the client
918          * will end up timing out waiting for a response to the ETA request
919          */
920         je = get_jobs_eta(true, &size);
921         if (!je) {
922                 size = sizeof(*je);
923                 je = calloc(1, size);
924         } else {
925                 je->nr_running          = cpu_to_le32(je->nr_running);
926                 je->nr_ramp             = cpu_to_le32(je->nr_ramp);
927                 je->nr_pending          = cpu_to_le32(je->nr_pending);
928                 je->nr_setting_up       = cpu_to_le32(je->nr_setting_up);
929                 je->files_open          = cpu_to_le32(je->files_open);
930
931                 for (i = 0; i < DDIR_RWDIR_CNT; i++) {
932                         je->m_rate[i]   = cpu_to_le64(je->m_rate[i]);
933                         je->t_rate[i]   = cpu_to_le64(je->t_rate[i]);
934                         je->m_iops[i]   = cpu_to_le32(je->m_iops[i]);
935                         je->t_iops[i]   = cpu_to_le32(je->t_iops[i]);
936                         je->rate[i]     = cpu_to_le64(je->rate[i]);
937                         je->iops[i]     = cpu_to_le32(je->iops[i]);
938                 }
939
940                 je->elapsed_sec         = cpu_to_le64(je->elapsed_sec);
941                 je->eta_sec             = cpu_to_le64(je->eta_sec);
942                 je->nr_threads          = cpu_to_le32(je->nr_threads);
943                 je->is_pow2             = cpu_to_le32(je->is_pow2);
944                 je->unit_base           = cpu_to_le32(je->unit_base);
945         }
946
947         fio_net_queue_cmd(FIO_NET_CMD_ETA, je, size, &tag, SK_F_FREE);
948         return 0;
949 }
950
951 static int send_update_job_reply(uint64_t __tag, int error)
952 {
953         uint64_t tag = __tag;
954         uint32_t pdu_error;
955
956         pdu_error = __cpu_to_le32(error);
957         return fio_net_queue_cmd(FIO_NET_CMD_UPDATE_JOB, &pdu_error, sizeof(pdu_error), &tag, SK_F_COPY);
958 }
959
960 static int handle_update_job_cmd(struct fio_net_cmd *cmd)
961 {
962         struct cmd_add_job_pdu *pdu = (struct cmd_add_job_pdu *) cmd->payload;
963         struct thread_data *td;
964         uint32_t tnumber;
965
966         tnumber = le32_to_cpu(pdu->thread_number);
967
968         dprint(FD_NET, "server: updating options for job %u\n", tnumber);
969
970         if (!tnumber || tnumber > thread_number) {
971                 send_update_job_reply(cmd->tag, ENODEV);
972                 return 0;
973         }
974
975         td = tnumber_to_td(tnumber);
976         convert_thread_options_to_cpu(&td->o, &pdu->top);
977         send_update_job_reply(cmd->tag, 0);
978         return 0;
979 }
980
981 static int handle_trigger_cmd(struct fio_net_cmd *cmd, struct flist_head *job_list)
982 {
983         struct cmd_vtrigger_pdu *pdu = (struct cmd_vtrigger_pdu *) cmd->payload;
984         char *buf = (char *) pdu->cmd;
985         struct all_io_list *rep;
986         size_t sz;
987
988         pdu->len = le16_to_cpu(pdu->len);
989         buf[pdu->len] = '\0';
990
991         rep = get_all_io_list(IO_LIST_ALL, &sz);
992         if (!rep) {
993                 struct all_io_list state;
994
995                 state.threads = cpu_to_le64((uint64_t) 0);
996                 fio_net_queue_cmd(FIO_NET_CMD_VTRIGGER, &state, sizeof(state), NULL, SK_F_COPY | SK_F_INLINE);
997         } else
998                 fio_net_queue_cmd(FIO_NET_CMD_VTRIGGER, rep, sz, NULL, SK_F_FREE | SK_F_INLINE);
999
1000         fio_terminate_threads(TERMINATE_ALL, TERMINATE_ALL);
1001         fio_server_check_jobs(job_list);
1002         exec_trigger(buf);
1003         return 0;
1004 }
1005
1006 static int handle_command(struct sk_out *sk_out, struct flist_head *job_list,
1007                           struct fio_net_cmd *cmd)
1008 {
1009         int ret;
1010
1011         dprint(FD_NET, "server: got op [%s], pdu=%u, tag=%llx\n",
1012                         fio_server_op(cmd->opcode), cmd->pdu_len,
1013                         (unsigned long long) cmd->tag);
1014
1015         switch (cmd->opcode) {
1016         case FIO_NET_CMD_QUIT:
1017                 fio_terminate_threads(TERMINATE_ALL, TERMINATE_ALL);
1018                 ret = 0;
1019                 break;
1020         case FIO_NET_CMD_EXIT:
1021                 exit_backend = true;
1022                 return -1;
1023         case FIO_NET_CMD_LOAD_FILE:
1024                 ret = handle_load_file_cmd(cmd);
1025                 break;
1026         case FIO_NET_CMD_JOB:
1027                 ret = handle_job_cmd(cmd);
1028                 break;
1029         case FIO_NET_CMD_JOBLINE:
1030                 ret = handle_jobline_cmd(cmd);
1031                 break;
1032         case FIO_NET_CMD_PROBE:
1033                 ret = handle_probe_cmd(cmd);
1034                 break;
1035         case FIO_NET_CMD_SEND_ETA:
1036                 ret = handle_send_eta_cmd(cmd);
1037                 break;
1038         case FIO_NET_CMD_RUN:
1039                 ret = handle_run_cmd(sk_out, job_list, cmd);
1040                 break;
1041         case FIO_NET_CMD_UPDATE_JOB:
1042                 ret = handle_update_job_cmd(cmd);
1043                 break;
1044         case FIO_NET_CMD_VTRIGGER:
1045                 ret = handle_trigger_cmd(cmd, job_list);
1046                 break;
1047         case FIO_NET_CMD_SENDFILE: {
1048                 struct cmd_sendfile_reply *in;
1049                 struct cmd_reply *rep;
1050
1051                 rep = (struct cmd_reply *) (uintptr_t) cmd->tag;
1052
1053                 in = (struct cmd_sendfile_reply *) cmd->payload;
1054                 in->size = le32_to_cpu(in->size);
1055                 in->error = le32_to_cpu(in->error);
1056                 if (in->error) {
1057                         ret = 1;
1058                         rep->error = in->error;
1059                 } else {
1060                         ret = 0;
1061                         rep->data = smalloc(in->size);
1062                         if (!rep->data) {
1063                                 ret = 1;
1064                                 rep->error = ENOMEM;
1065                         } else {
1066                                 rep->size = in->size;
1067                                 memcpy(rep->data, in->data, in->size);
1068                         }
1069                 }
1070                 fio_sem_up(&rep->lock);
1071                 break;
1072                 }
1073         default:
1074                 log_err("fio: unknown opcode: %s\n", fio_server_op(cmd->opcode));
1075                 ret = 1;
1076         }
1077
1078         return ret;
1079 }
1080
1081 /*
1082  * Send a command with a separate PDU, not inlined in the command
1083  */
1084 static int fio_send_cmd_ext_pdu(int sk, uint16_t opcode, const void *buf,
1085                                 off_t size, uint64_t tag, uint32_t flags)
1086 {
1087         struct fio_net_cmd cmd;
1088         struct iovec iov[2];
1089         size_t this_len;
1090         int ret;
1091
1092         iov[0].iov_base = (void *) &cmd;
1093         iov[0].iov_len = sizeof(cmd);
1094
1095         do {
1096                 uint32_t this_flags = flags;
1097
1098                 this_len = size;
1099                 if (this_len > FIO_SERVER_MAX_FRAGMENT_PDU)
1100                         this_len = FIO_SERVER_MAX_FRAGMENT_PDU;
1101
1102                 if (this_len < size)
1103                         this_flags |= FIO_NET_CMD_F_MORE;
1104
1105                 __fio_init_net_cmd(&cmd, opcode, this_len, tag);
1106                 cmd.flags = __cpu_to_le32(this_flags);
1107                 fio_net_cmd_crc_pdu(&cmd, buf);
1108
1109                 iov[1].iov_base = (void *) buf;
1110                 iov[1].iov_len = this_len;
1111
1112                 ret = fio_sendv_data(sk, iov, 2);
1113                 size -= this_len;
1114                 buf += this_len;
1115         } while (!ret && size);
1116
1117         return ret;
1118 }
1119
1120 static void finish_entry(struct sk_entry *entry)
1121 {
1122         if (entry->flags & SK_F_FREE)
1123                 free(entry->buf);
1124         else if (entry->flags & SK_F_COPY)
1125                 sfree(entry->buf);
1126
1127         sfree(entry);
1128 }
1129
1130 static void entry_set_flags(struct sk_entry *entry, struct flist_head *list,
1131                             unsigned int *flags)
1132 {
1133         if (!flist_empty(list))
1134                 *flags = FIO_NET_CMD_F_MORE;
1135         else
1136                 *flags = 0;
1137 }
1138
1139 static int send_vec_entry(struct sk_out *sk_out, struct sk_entry *first)
1140 {
1141         unsigned int flags;
1142         int ret;
1143
1144         entry_set_flags(first, &first->next, &flags);
1145
1146         ret = fio_send_cmd_ext_pdu(sk_out->sk, first->opcode, first->buf,
1147                                         first->size, first->tag, flags);
1148
1149         while (!flist_empty(&first->next)) {
1150                 struct sk_entry *next;
1151
1152                 next = flist_first_entry(&first->next, struct sk_entry, list);
1153                 flist_del_init(&next->list);
1154
1155                 entry_set_flags(next, &first->next, &flags);
1156
1157                 ret += fio_send_cmd_ext_pdu(sk_out->sk, next->opcode, next->buf,
1158                                                 next->size, next->tag, flags);
1159                 finish_entry(next);
1160         }
1161
1162         return ret;
1163 }
1164
1165 static int handle_sk_entry(struct sk_out *sk_out, struct sk_entry *entry)
1166 {
1167         int ret;
1168
1169         fio_sem_down(&sk_out->xmit);
1170
1171         if (entry->flags & SK_F_VEC)
1172                 ret = send_vec_entry(sk_out, entry);
1173         else if (entry->flags & SK_F_SIMPLE) {
1174                 ret = fio_net_send_simple_cmd(sk_out->sk, entry->opcode,
1175                                                 entry->tag, NULL);
1176         } else {
1177                 ret = fio_net_send_cmd(sk_out->sk, entry->opcode, entry->buf,
1178                                         entry->size, &entry->tag, NULL);
1179         }
1180
1181         fio_sem_up(&sk_out->xmit);
1182
1183         if (ret)
1184                 log_err("fio: failed handling cmd %s\n", fio_server_op(entry->opcode));
1185
1186         finish_entry(entry);
1187         return ret;
1188 }
1189
1190 static int handle_xmits(struct sk_out *sk_out)
1191 {
1192         struct sk_entry *entry;
1193         FLIST_HEAD(list);
1194         int ret = 0;
1195
1196         sk_lock(sk_out);
1197         if (flist_empty(&sk_out->list)) {
1198                 sk_unlock(sk_out);
1199                 return 0;
1200         }
1201
1202         flist_splice_init(&sk_out->list, &list);
1203         sk_unlock(sk_out);
1204
1205         while (!flist_empty(&list)) {
1206                 entry = flist_entry(list.next, struct sk_entry, list);
1207                 flist_del(&entry->list);
1208                 ret += handle_sk_entry(sk_out, entry);
1209         }
1210
1211         return ret;
1212 }
1213
1214 static int handle_connection(struct sk_out *sk_out)
1215 {
1216         struct fio_net_cmd *cmd = NULL;
1217         FLIST_HEAD(job_list);
1218         int ret = 0;
1219
1220         reset_fio_state();
1221
1222         /* read forever */
1223         while (!exit_backend) {
1224                 struct pollfd pfd = {
1225                         .fd     = sk_out->sk,
1226                         .events = POLLIN,
1227                 };
1228
1229                 do {
1230                         int timeout = 1000;
1231
1232                         if (!flist_empty(&job_list))
1233                                 timeout = 100;
1234
1235                         handle_xmits(sk_out);
1236
1237                         ret = poll(&pfd, 1, 0);
1238                         if (ret < 0) {
1239                                 if (errno == EINTR)
1240                                         break;
1241                                 log_err("fio: poll: %s\n", strerror(errno));
1242                                 break;
1243                         } else if (!ret) {
1244                                 fio_server_check_jobs(&job_list);
1245                                 fio_sem_down_timeout(&sk_out->wait, timeout);
1246                                 continue;
1247                         }
1248
1249                         if (pfd.revents & POLLIN)
1250                                 break;
1251                         if (pfd.revents & (POLLERR|POLLHUP)) {
1252                                 ret = 1;
1253                                 break;
1254                         }
1255                 } while (!exit_backend);
1256
1257                 fio_server_check_jobs(&job_list);
1258
1259                 if (ret < 0)
1260                         break;
1261
1262                 if (pfd.revents & POLLIN)
1263                         cmd = fio_net_recv_cmd(sk_out->sk, true);
1264                 if (!cmd) {
1265                         ret = -1;
1266                         break;
1267                 }
1268
1269                 ret = handle_command(sk_out, &job_list, cmd);
1270                 if (ret)
1271                         break;
1272
1273                 free(cmd);
1274                 cmd = NULL;
1275         }
1276
1277         if (cmd)
1278                 free(cmd);
1279
1280         handle_xmits(sk_out);
1281
1282         close(sk_out->sk);
1283         sk_out->sk = -1;
1284         __sk_out_drop(sk_out);
1285         _exit(ret);
1286 }
1287
1288 /* get the address on this host bound by the input socket,
1289  * whether it is ipv6 or ipv4 */
1290
1291 static int get_my_addr_str(int sk)
1292 {
1293         struct sockaddr_in6 myaddr6 = { 0, };
1294         struct sockaddr_in myaddr4 = { 0, };
1295         struct sockaddr *sockaddr_p;
1296         char *net_addr;
1297         socklen_t len;
1298         int ret;
1299
1300         if (use_ipv6) {
1301                 len = sizeof(myaddr6);
1302                 sockaddr_p = (struct sockaddr * )&myaddr6;
1303                 net_addr = (char * )&myaddr6.sin6_addr;
1304         } else {
1305                 len = sizeof(myaddr4);
1306                 sockaddr_p = (struct sockaddr * )&myaddr4;
1307                 net_addr = (char * )&myaddr4.sin_addr;
1308         }
1309
1310         ret = getsockname(sk, sockaddr_p, &len);
1311         if (ret) {
1312                 log_err("fio: getsockname: %s\n", strerror(errno));
1313                 return -1;
1314         }
1315
1316         if (!inet_ntop(use_ipv6?AF_INET6:AF_INET, net_addr, client_sockaddr_str, INET6_ADDRSTRLEN - 1)) {
1317                 log_err("inet_ntop: failed to convert addr to string\n");
1318                 return -1;
1319         }
1320
1321         dprint(FD_NET, "fio server bound to addr %s\n", client_sockaddr_str);
1322         return 0;
1323 }
1324
1325 static int accept_loop(int listen_sk)
1326 {
1327         struct sockaddr_in addr;
1328         struct sockaddr_in6 addr6;
1329         socklen_t len = use_ipv6 ? sizeof(addr6) : sizeof(addr);
1330         struct pollfd pfd;
1331         int ret = 0, sk, exitval = 0;
1332         FLIST_HEAD(conn_list);
1333
1334         dprint(FD_NET, "server enter accept loop\n");
1335
1336         fio_set_fd_nonblocking(listen_sk, "server");
1337
1338         while (!exit_backend) {
1339                 struct sk_out *sk_out;
1340                 const char *from;
1341                 char buf[64];
1342                 pid_t pid;
1343
1344                 pfd.fd = listen_sk;
1345                 pfd.events = POLLIN;
1346                 do {
1347                         int timeout = 1000;
1348
1349                         if (!flist_empty(&conn_list))
1350                                 timeout = 100;
1351
1352                         ret = poll(&pfd, 1, timeout);
1353                         if (ret < 0) {
1354                                 if (errno == EINTR)
1355                                         break;
1356                                 log_err("fio: poll: %s\n", strerror(errno));
1357                                 break;
1358                         } else if (!ret) {
1359                                 fio_server_check_conns(&conn_list);
1360                                 continue;
1361                         }
1362
1363                         if (pfd.revents & POLLIN)
1364                                 break;
1365                 } while (!exit_backend);
1366
1367                 fio_server_check_conns(&conn_list);
1368
1369                 if (exit_backend || ret < 0)
1370                         break;
1371
1372                 if (use_ipv6)
1373                         sk = accept(listen_sk, (struct sockaddr *) &addr6, &len);
1374                 else
1375                         sk = accept(listen_sk, (struct sockaddr *) &addr, &len);
1376
1377                 if (sk < 0) {
1378                         log_err("fio: accept: %s\n", strerror(errno));
1379                         return -1;
1380                 }
1381
1382                 if (use_ipv6)
1383                         from = inet_ntop(AF_INET6, (struct sockaddr *) &addr6.sin6_addr, buf, sizeof(buf));
1384                 else
1385                         from = inet_ntop(AF_INET, (struct sockaddr *) &addr.sin_addr, buf, sizeof(buf));
1386
1387                 dprint(FD_NET, "server: connect from %s\n", from);
1388
1389                 sk_out = scalloc(1, sizeof(*sk_out));
1390                 if (!sk_out) {
1391                         close(sk);
1392                         return -1;
1393                 }
1394
1395                 sk_out->sk = sk;
1396                 INIT_FLIST_HEAD(&sk_out->list);
1397                 __fio_sem_init(&sk_out->lock, FIO_SEM_UNLOCKED);
1398                 __fio_sem_init(&sk_out->wait, FIO_SEM_LOCKED);
1399                 __fio_sem_init(&sk_out->xmit, FIO_SEM_UNLOCKED);
1400
1401                 pid = fork();
1402                 if (pid) {
1403                         close(sk);
1404                         fio_server_add_conn_pid(&conn_list, pid);
1405                         continue;
1406                 }
1407
1408                 /* if error, it's already logged, non-fatal */
1409                 get_my_addr_str(sk);
1410
1411                 /*
1412                  * Assign sk_out here, it'll be dropped in handle_connection()
1413                  * since that function calls _exit() when done
1414                  */
1415                 sk_out_assign(sk_out);
1416                 handle_connection(sk_out);
1417         }
1418
1419         return exitval;
1420 }
1421
1422 int fio_server_text_output(int level, const char *buf, size_t len)
1423 {
1424         struct sk_out *sk_out = pthread_getspecific(sk_out_key);
1425         struct cmd_text_pdu *pdu;
1426         unsigned int tlen;
1427         struct timeval tv;
1428
1429         if (!sk_out || sk_out->sk == -1)
1430                 return -1;
1431
1432         tlen = sizeof(*pdu) + len;
1433         pdu = malloc(tlen);
1434
1435         pdu->level      = __cpu_to_le32(level);
1436         pdu->buf_len    = __cpu_to_le32(len);
1437
1438         gettimeofday(&tv, NULL);
1439         pdu->log_sec    = __cpu_to_le64(tv.tv_sec);
1440         pdu->log_usec   = __cpu_to_le64(tv.tv_usec);
1441
1442         memcpy(pdu->buf, buf, len);
1443
1444         fio_net_queue_cmd(FIO_NET_CMD_TEXT, pdu, tlen, NULL, SK_F_COPY);
1445         free(pdu);
1446         return len;
1447 }
1448
1449 static void convert_io_stat(struct io_stat *dst, struct io_stat *src)
1450 {
1451         dst->max_val    = cpu_to_le64(src->max_val);
1452         dst->min_val    = cpu_to_le64(src->min_val);
1453         dst->samples    = cpu_to_le64(src->samples);
1454
1455         /*
1456          * Encode to IEEE 754 for network transfer
1457          */
1458         dst->mean.u.i   = cpu_to_le64(fio_double_to_uint64(src->mean.u.f));
1459         dst->S.u.i      = cpu_to_le64(fio_double_to_uint64(src->S.u.f));
1460 }
1461
1462 static void convert_gs(struct group_run_stats *dst, struct group_run_stats *src)
1463 {
1464         int i;
1465
1466         for (i = 0; i < DDIR_RWDIR_CNT; i++) {
1467                 dst->max_run[i]         = cpu_to_le64(src->max_run[i]);
1468                 dst->min_run[i]         = cpu_to_le64(src->min_run[i]);
1469                 dst->max_bw[i]          = cpu_to_le64(src->max_bw[i]);
1470                 dst->min_bw[i]          = cpu_to_le64(src->min_bw[i]);
1471                 dst->iobytes[i]         = cpu_to_le64(src->iobytes[i]);
1472                 dst->agg[i]             = cpu_to_le64(src->agg[i]);
1473         }
1474
1475         dst->kb_base    = cpu_to_le32(src->kb_base);
1476         dst->unit_base  = cpu_to_le32(src->unit_base);
1477         dst->groupid    = cpu_to_le32(src->groupid);
1478         dst->unified_rw_rep     = cpu_to_le32(src->unified_rw_rep);
1479         dst->sig_figs   = cpu_to_le32(src->sig_figs);
1480 }
1481
1482 /*
1483  * Send a CMD_TS, which packs struct thread_stat and group_run_stats
1484  * into a single payload.
1485  */
1486 void fio_server_send_ts(struct thread_stat *ts, struct group_run_stats *rs)
1487 {
1488         struct cmd_ts_pdu p;
1489         int i, j, k;
1490         void *ss_buf;
1491         uint64_t *ss_iops, *ss_bw;
1492
1493         dprint(FD_NET, "server sending end stats\n");
1494
1495         memset(&p, 0, sizeof(p));
1496
1497         snprintf(p.ts.name, sizeof(p.ts.name), "%s", ts->name);
1498         snprintf(p.ts.verror, sizeof(p.ts.verror), "%s", ts->verror);
1499         snprintf(p.ts.description, sizeof(p.ts.description), "%s",
1500                  ts->description);
1501
1502         p.ts.error              = cpu_to_le32(ts->error);
1503         p.ts.thread_number      = cpu_to_le32(ts->thread_number);
1504         p.ts.groupid            = cpu_to_le32(ts->groupid);
1505         p.ts.pid                = cpu_to_le32(ts->pid);
1506         p.ts.members            = cpu_to_le32(ts->members);
1507         p.ts.unified_rw_rep     = cpu_to_le32(ts->unified_rw_rep);
1508
1509         for (i = 0; i < DDIR_RWDIR_CNT; i++) {
1510                 convert_io_stat(&p.ts.clat_stat[i], &ts->clat_stat[i]);
1511                 convert_io_stat(&p.ts.slat_stat[i], &ts->slat_stat[i]);
1512                 convert_io_stat(&p.ts.lat_stat[i], &ts->lat_stat[i]);
1513                 convert_io_stat(&p.ts.bw_stat[i], &ts->bw_stat[i]);
1514                 convert_io_stat(&p.ts.iops_stat[i], &ts->iops_stat[i]);
1515         }
1516         convert_io_stat(&p.ts.sync_stat, &ts->sync_stat);
1517
1518         p.ts.usr_time           = cpu_to_le64(ts->usr_time);
1519         p.ts.sys_time           = cpu_to_le64(ts->sys_time);
1520         p.ts.ctx                = cpu_to_le64(ts->ctx);
1521         p.ts.minf               = cpu_to_le64(ts->minf);
1522         p.ts.majf               = cpu_to_le64(ts->majf);
1523         p.ts.clat_percentiles   = cpu_to_le32(ts->clat_percentiles);
1524         p.ts.lat_percentiles    = cpu_to_le32(ts->lat_percentiles);
1525         p.ts.slat_percentiles   = cpu_to_le32(ts->slat_percentiles);
1526         p.ts.percentile_precision = cpu_to_le64(ts->percentile_precision);
1527
1528         for (i = 0; i < FIO_IO_U_LIST_MAX_LEN; i++) {
1529                 fio_fp64_t *src = &ts->percentile_list[i];
1530                 fio_fp64_t *dst = &p.ts.percentile_list[i];
1531
1532                 dst->u.i = cpu_to_le64(fio_double_to_uint64(src->u.f));
1533         }
1534
1535         for (i = 0; i < FIO_IO_U_MAP_NR; i++) {
1536                 p.ts.io_u_map[i]        = cpu_to_le64(ts->io_u_map[i]);
1537                 p.ts.io_u_submit[i]     = cpu_to_le64(ts->io_u_submit[i]);
1538                 p.ts.io_u_complete[i]   = cpu_to_le64(ts->io_u_complete[i]);
1539         }
1540
1541         for (i = 0; i < FIO_IO_U_LAT_N_NR; i++)
1542                 p.ts.io_u_lat_n[i]      = cpu_to_le64(ts->io_u_lat_n[i]);
1543         for (i = 0; i < FIO_IO_U_LAT_U_NR; i++)
1544                 p.ts.io_u_lat_u[i]      = cpu_to_le64(ts->io_u_lat_u[i]);
1545         for (i = 0; i < FIO_IO_U_LAT_M_NR; i++)
1546                 p.ts.io_u_lat_m[i]      = cpu_to_le64(ts->io_u_lat_m[i]);
1547
1548         for (i = 0; i < FIO_LAT_CNT; i++)
1549                 for (j = 0; j < DDIR_RWDIR_CNT; j++)
1550                         for (k = 0; k < FIO_IO_U_PLAT_NR; k++)
1551                                 p.ts.io_u_plat[i][j][k] = cpu_to_le64(ts->io_u_plat[i][j][k]);
1552
1553         for (j = 0; j < FIO_IO_U_PLAT_NR; j++)
1554                 p.ts.io_u_sync_plat[j] = cpu_to_le64(ts->io_u_sync_plat[j]);
1555
1556         for (i = 0; i < DDIR_RWDIR_SYNC_CNT; i++)
1557                 p.ts.total_io_u[i]      = cpu_to_le64(ts->total_io_u[i]);
1558
1559         for (i = 0; i < DDIR_RWDIR_CNT; i++) {
1560                 p.ts.short_io_u[i]      = cpu_to_le64(ts->short_io_u[i]);
1561                 p.ts.drop_io_u[i]       = cpu_to_le64(ts->drop_io_u[i]);
1562         }
1563
1564         p.ts.total_submit       = cpu_to_le64(ts->total_submit);
1565         p.ts.total_complete     = cpu_to_le64(ts->total_complete);
1566         p.ts.nr_zone_resets     = cpu_to_le64(ts->nr_zone_resets);
1567
1568         for (i = 0; i < DDIR_RWDIR_CNT; i++) {
1569                 p.ts.io_bytes[i]        = cpu_to_le64(ts->io_bytes[i]);
1570                 p.ts.runtime[i]         = cpu_to_le64(ts->runtime[i]);
1571         }
1572
1573         p.ts.total_run_time     = cpu_to_le64(ts->total_run_time);
1574         p.ts.continue_on_error  = cpu_to_le16(ts->continue_on_error);
1575         p.ts.total_err_count    = cpu_to_le64(ts->total_err_count);
1576         p.ts.first_error        = cpu_to_le32(ts->first_error);
1577         p.ts.kb_base            = cpu_to_le32(ts->kb_base);
1578         p.ts.unit_base          = cpu_to_le32(ts->unit_base);
1579
1580         p.ts.latency_depth      = cpu_to_le32(ts->latency_depth);
1581         p.ts.latency_target     = cpu_to_le64(ts->latency_target);
1582         p.ts.latency_window     = cpu_to_le64(ts->latency_window);
1583         p.ts.latency_percentile.u.i = cpu_to_le64(fio_double_to_uint64(ts->latency_percentile.u.f));
1584
1585         p.ts.sig_figs           = cpu_to_le32(ts->sig_figs);
1586
1587         p.ts.nr_block_infos     = cpu_to_le64(ts->nr_block_infos);
1588         for (i = 0; i < p.ts.nr_block_infos; i++)
1589                 p.ts.block_infos[i] = cpu_to_le32(ts->block_infos[i]);
1590
1591         p.ts.ss_dur             = cpu_to_le64(ts->ss_dur);
1592         p.ts.ss_state           = cpu_to_le32(ts->ss_state);
1593         p.ts.ss_head            = cpu_to_le32(ts->ss_head);
1594         p.ts.ss_limit.u.i       = cpu_to_le64(fio_double_to_uint64(ts->ss_limit.u.f));
1595         p.ts.ss_slope.u.i       = cpu_to_le64(fio_double_to_uint64(ts->ss_slope.u.f));
1596         p.ts.ss_deviation.u.i   = cpu_to_le64(fio_double_to_uint64(ts->ss_deviation.u.f));
1597         p.ts.ss_criterion.u.i   = cpu_to_le64(fio_double_to_uint64(ts->ss_criterion.u.f));
1598
1599         p.ts.cachehit           = cpu_to_le64(ts->cachehit);
1600         p.ts.cachemiss          = cpu_to_le64(ts->cachemiss);
1601
1602         for (i = 0; i < DDIR_RWDIR_CNT; i++) {
1603                 for (j = 0; j < FIO_IO_U_PLAT_NR; j++) {
1604                         p.ts.io_u_plat_high_prio[i][j] = cpu_to_le64(ts->io_u_plat_high_prio[i][j]);
1605                         p.ts.io_u_plat_low_prio[i][j] = cpu_to_le64(ts->io_u_plat_low_prio[i][j]);
1606                 }
1607                 convert_io_stat(&p.ts.clat_high_prio_stat[i], &ts->clat_high_prio_stat[i]);
1608                 convert_io_stat(&p.ts.clat_low_prio_stat[i], &ts->clat_low_prio_stat[i]);
1609         }
1610
1611         convert_gs(&p.rs, rs);
1612
1613         dprint(FD_NET, "ts->ss_state = %d\n", ts->ss_state);
1614         if (ts->ss_state & FIO_SS_DATA) {
1615                 dprint(FD_NET, "server sending steadystate ring buffers\n");
1616
1617                 ss_buf = malloc(sizeof(p) + 2*ts->ss_dur*sizeof(uint64_t));
1618
1619                 memcpy(ss_buf, &p, sizeof(p));
1620
1621                 ss_iops = (uint64_t *) ((struct cmd_ts_pdu *)ss_buf + 1);
1622                 ss_bw = ss_iops + (int) ts->ss_dur;
1623                 for (i = 0; i < ts->ss_dur; i++) {
1624                         ss_iops[i] = cpu_to_le64(ts->ss_iops_data[i]);
1625                         ss_bw[i] = cpu_to_le64(ts->ss_bw_data[i]);
1626                 }
1627
1628                 fio_net_queue_cmd(FIO_NET_CMD_TS, ss_buf, sizeof(p) + 2*ts->ss_dur*sizeof(uint64_t), NULL, SK_F_COPY);
1629
1630                 free(ss_buf);
1631         }
1632         else
1633                 fio_net_queue_cmd(FIO_NET_CMD_TS, &p, sizeof(p), NULL, SK_F_COPY);
1634 }
1635
1636 void fio_server_send_gs(struct group_run_stats *rs)
1637 {
1638         struct group_run_stats gs;
1639
1640         dprint(FD_NET, "server sending group run stats\n");
1641
1642         convert_gs(&gs, rs);
1643         fio_net_queue_cmd(FIO_NET_CMD_GS, &gs, sizeof(gs), NULL, SK_F_COPY);
1644 }
1645
1646 void fio_server_send_job_options(struct flist_head *opt_list,
1647                                  unsigned int gid)
1648 {
1649         struct cmd_job_option pdu;
1650         struct flist_head *entry;
1651
1652         if (flist_empty(opt_list))
1653                 return;
1654
1655         flist_for_each(entry, opt_list) {
1656                 struct print_option *p;
1657                 size_t len;
1658
1659                 p = flist_entry(entry, struct print_option, list);
1660                 memset(&pdu, 0, sizeof(pdu));
1661
1662                 if (gid == -1U) {
1663                         pdu.global = __cpu_to_le16(1);
1664                         pdu.groupid = 0;
1665                 } else {
1666                         pdu.global = 0;
1667                         pdu.groupid = cpu_to_le32(gid);
1668                 }
1669                 len = strlen(p->name);
1670                 if (len >= sizeof(pdu.name)) {
1671                         len = sizeof(pdu.name) - 1;
1672                         pdu.truncated = __cpu_to_le16(1);
1673                 }
1674                 memcpy(pdu.name, p->name, len);
1675                 if (p->value) {
1676                         len = strlen(p->value);
1677                         if (len >= sizeof(pdu.value)) {
1678                                 len = sizeof(pdu.value) - 1;
1679                                 pdu.truncated = __cpu_to_le16(1);
1680                         }
1681                         memcpy(pdu.value, p->value, len);
1682                 }
1683                 fio_net_queue_cmd(FIO_NET_CMD_JOB_OPT, &pdu, sizeof(pdu), NULL, SK_F_COPY);
1684         }
1685 }
1686
1687 static void convert_agg(struct disk_util_agg *dst, struct disk_util_agg *src)
1688 {
1689         int i;
1690
1691         for (i = 0; i < 2; i++) {
1692                 dst->ios[i]     = cpu_to_le64(src->ios[i]);
1693                 dst->merges[i]  = cpu_to_le64(src->merges[i]);
1694                 dst->sectors[i] = cpu_to_le64(src->sectors[i]);
1695                 dst->ticks[i]   = cpu_to_le64(src->ticks[i]);
1696         }
1697
1698         dst->io_ticks           = cpu_to_le64(src->io_ticks);
1699         dst->time_in_queue      = cpu_to_le64(src->time_in_queue);
1700         dst->slavecount         = cpu_to_le32(src->slavecount);
1701         dst->max_util.u.i       = cpu_to_le64(fio_double_to_uint64(src->max_util.u.f));
1702 }
1703
1704 static void convert_dus(struct disk_util_stat *dst, struct disk_util_stat *src)
1705 {
1706         int i;
1707
1708         snprintf((char *) dst->name, sizeof(dst->name), "%s", src->name);
1709
1710         for (i = 0; i < 2; i++) {
1711                 dst->s.ios[i]           = cpu_to_le64(src->s.ios[i]);
1712                 dst->s.merges[i]        = cpu_to_le64(src->s.merges[i]);
1713                 dst->s.sectors[i]       = cpu_to_le64(src->s.sectors[i]);
1714                 dst->s.ticks[i]         = cpu_to_le64(src->s.ticks[i]);
1715         }
1716
1717         dst->s.io_ticks         = cpu_to_le64(src->s.io_ticks);
1718         dst->s.time_in_queue    = cpu_to_le64(src->s.time_in_queue);
1719         dst->s.msec             = cpu_to_le64(src->s.msec);
1720 }
1721
1722 void fio_server_send_du(void)
1723 {
1724         struct disk_util *du;
1725         struct flist_head *entry;
1726         struct cmd_du_pdu pdu;
1727
1728         dprint(FD_NET, "server: sending disk_util %d\n", !flist_empty(&disk_list));
1729
1730         memset(&pdu, 0, sizeof(pdu));
1731
1732         flist_for_each(entry, &disk_list) {
1733                 du = flist_entry(entry, struct disk_util, list);
1734
1735                 convert_dus(&pdu.dus, &du->dus);
1736                 convert_agg(&pdu.agg, &du->agg);
1737
1738                 fio_net_queue_cmd(FIO_NET_CMD_DU, &pdu, sizeof(pdu), NULL, SK_F_COPY);
1739         }
1740 }
1741
1742 #ifdef CONFIG_ZLIB
1743
1744 static inline void __fio_net_prep_tail(z_stream *stream, void *out_pdu,
1745                                         struct sk_entry **last_entry,
1746                                         struct sk_entry *first)
1747 {
1748         unsigned int this_len = FIO_SERVER_MAX_FRAGMENT_PDU - stream->avail_out;
1749
1750         *last_entry = fio_net_prep_cmd(FIO_NET_CMD_IOLOG, out_pdu, this_len,
1751                                  NULL, SK_F_VEC | SK_F_INLINE | SK_F_FREE);
1752         if (*last_entry)
1753                 flist_add_tail(&(*last_entry)->list, &first->next);
1754 }
1755
1756 /*
1757  * Deflates the next input given, creating as many new packets in the
1758  * linked list as necessary.
1759  */
1760 static int __deflate_pdu_buffer(void *next_in, unsigned int next_sz, void **out_pdu,
1761                                 struct sk_entry **last_entry, z_stream *stream,
1762                                 struct sk_entry *first)
1763 {
1764         int ret;
1765
1766         stream->next_in = next_in;
1767         stream->avail_in = next_sz;
1768         do {
1769                 if (!stream->avail_out) {
1770                         __fio_net_prep_tail(stream, *out_pdu, last_entry, first);
1771                         if (*last_entry == NULL)
1772                                 return 1;
1773
1774                         *out_pdu = malloc(FIO_SERVER_MAX_FRAGMENT_PDU);
1775
1776                         stream->avail_out = FIO_SERVER_MAX_FRAGMENT_PDU;
1777                         stream->next_out = *out_pdu;
1778                 }
1779
1780                 ret = deflate(stream, Z_BLOCK);
1781
1782                 if (ret < 0) {
1783                         free(*out_pdu);
1784                         return 1;
1785                 }
1786         } while (stream->avail_in);
1787
1788         return 0;
1789 }
1790
1791 static int __fio_append_iolog_gz_hist(struct sk_entry *first, struct io_log *log,
1792                                       struct io_logs *cur_log, z_stream *stream)
1793 {
1794         struct sk_entry *entry;
1795         void *out_pdu;
1796         int ret, i, j;
1797         int sample_sz = log_entry_sz(log);
1798
1799         out_pdu = malloc(FIO_SERVER_MAX_FRAGMENT_PDU);
1800         stream->avail_out = FIO_SERVER_MAX_FRAGMENT_PDU;
1801         stream->next_out = out_pdu;
1802
1803         for (i = 0; i < cur_log->nr_samples; i++) {
1804                 struct io_sample *s;
1805                 struct io_u_plat_entry *cur_plat_entry, *prev_plat_entry;
1806                 uint64_t *cur_plat, *prev_plat;
1807
1808                 s = get_sample(log, cur_log, i);
1809                 ret = __deflate_pdu_buffer(s, sample_sz, &out_pdu, &entry, stream, first);
1810                 if (ret)
1811                         return ret;
1812
1813                 /* Do the subtraction on server side so that client doesn't have to
1814                  * reconstruct our linked list from packets.
1815                  */
1816                 cur_plat_entry  = s->data.plat_entry;
1817                 prev_plat_entry = flist_first_entry(&cur_plat_entry->list, struct io_u_plat_entry, list);
1818                 cur_plat  = cur_plat_entry->io_u_plat;
1819                 prev_plat = prev_plat_entry->io_u_plat;
1820
1821                 for (j = 0; j < FIO_IO_U_PLAT_NR; j++) {
1822                         cur_plat[j] -= prev_plat[j];
1823                 }
1824
1825                 flist_del(&prev_plat_entry->list);
1826                 free(prev_plat_entry);
1827
1828                 ret = __deflate_pdu_buffer(cur_plat_entry, sizeof(*cur_plat_entry),
1829                                            &out_pdu, &entry, stream, first);
1830
1831                 if (ret)
1832                         return ret;
1833         }
1834
1835         __fio_net_prep_tail(stream, out_pdu, &entry, first);
1836         return entry == NULL;
1837 }
1838
1839 static int __fio_append_iolog_gz(struct sk_entry *first, struct io_log *log,
1840                                  struct io_logs *cur_log, z_stream *stream)
1841 {
1842         unsigned int this_len;
1843         void *out_pdu;
1844         int ret;
1845
1846         if (log->log_type == IO_LOG_TYPE_HIST)
1847                 return __fio_append_iolog_gz_hist(first, log, cur_log, stream);
1848
1849         stream->next_in = (void *) cur_log->log;
1850         stream->avail_in = cur_log->nr_samples * log_entry_sz(log);
1851
1852         do {
1853                 struct sk_entry *entry;
1854
1855                 /*
1856                  * Dirty - since the log is potentially huge, compress it into
1857                  * FIO_SERVER_MAX_FRAGMENT_PDU chunks and let the receiving
1858                  * side defragment it.
1859                  */
1860                 out_pdu = malloc(FIO_SERVER_MAX_FRAGMENT_PDU);
1861
1862                 stream->avail_out = FIO_SERVER_MAX_FRAGMENT_PDU;
1863                 stream->next_out = out_pdu;
1864                 ret = deflate(stream, Z_BLOCK);
1865                 /* may be Z_OK, or Z_STREAM_END */
1866                 if (ret < 0) {
1867                         free(out_pdu);
1868                         return 1;
1869                 }
1870
1871                 this_len = FIO_SERVER_MAX_FRAGMENT_PDU - stream->avail_out;
1872
1873                 entry = fio_net_prep_cmd(FIO_NET_CMD_IOLOG, out_pdu, this_len,
1874                                          NULL, SK_F_VEC | SK_F_INLINE | SK_F_FREE);
1875                 if (!entry) {
1876                         free(out_pdu);
1877                         return 1;
1878                 }
1879                 flist_add_tail(&entry->list, &first->next);
1880         } while (stream->avail_in);
1881
1882         return 0;
1883 }
1884
1885 static int fio_append_iolog_gz(struct sk_entry *first, struct io_log *log)
1886 {
1887         z_stream stream = {
1888                 .zalloc = Z_NULL,
1889                 .zfree  = Z_NULL,
1890                 .opaque = Z_NULL,
1891         };
1892         int ret = 0;
1893
1894         if (deflateInit(&stream, Z_DEFAULT_COMPRESSION) != Z_OK)
1895                 return 1;
1896
1897         while (!flist_empty(&log->io_logs)) {
1898                 struct io_logs *cur_log;
1899
1900                 cur_log = flist_first_entry(&log->io_logs, struct io_logs, list);
1901                 flist_del_init(&cur_log->list);
1902
1903                 ret = __fio_append_iolog_gz(first, log, cur_log, &stream);
1904                 if (ret)
1905                         break;
1906         }
1907
1908         ret = deflate(&stream, Z_FINISH);
1909
1910         while (ret != Z_STREAM_END) {
1911                 struct sk_entry *entry;
1912                 unsigned int this_len;
1913                 void *out_pdu;
1914
1915                 out_pdu = malloc(FIO_SERVER_MAX_FRAGMENT_PDU);
1916                 stream.avail_out = FIO_SERVER_MAX_FRAGMENT_PDU;
1917                 stream.next_out = out_pdu;
1918
1919                 ret = deflate(&stream, Z_FINISH);
1920                 /* may be Z_OK, or Z_STREAM_END */
1921                 if (ret < 0) {
1922                         free(out_pdu);
1923                         break;
1924                 }
1925
1926                 this_len = FIO_SERVER_MAX_FRAGMENT_PDU - stream.avail_out;
1927
1928                 entry = fio_net_prep_cmd(FIO_NET_CMD_IOLOG, out_pdu, this_len,
1929                                          NULL, SK_F_VEC | SK_F_INLINE | SK_F_FREE);
1930                 if (!entry) {
1931                         free(out_pdu);
1932                         break;
1933                 }
1934                 flist_add_tail(&entry->list, &first->next);
1935         }
1936
1937         ret = deflateEnd(&stream);
1938         if (ret == Z_OK)
1939                 return 0;
1940
1941         return 1;
1942 }
1943 #else
1944 static int fio_append_iolog_gz(struct sk_entry *first, struct io_log *log)
1945 {
1946         return 1;
1947 }
1948 #endif
1949
1950 static int fio_append_gz_chunks(struct sk_entry *first, struct io_log *log)
1951 {
1952         struct sk_entry *entry;
1953         struct flist_head *node;
1954         int ret = 0;
1955
1956         pthread_mutex_lock(&log->chunk_lock);
1957         flist_for_each(node, &log->chunk_list) {
1958                 struct iolog_compress *c;
1959
1960                 c = flist_entry(node, struct iolog_compress, list);
1961                 entry = fio_net_prep_cmd(FIO_NET_CMD_IOLOG, c->buf, c->len,
1962                                                 NULL, SK_F_VEC | SK_F_INLINE);
1963                 if (!entry) {
1964                         ret = 1;
1965                         break;
1966                 }
1967                 flist_add_tail(&entry->list, &first->next);
1968         }
1969         pthread_mutex_unlock(&log->chunk_lock);
1970         return ret;
1971 }
1972
1973 static int fio_append_text_log(struct sk_entry *first, struct io_log *log)
1974 {
1975         struct sk_entry *entry;
1976         int ret = 0;
1977
1978         while (!flist_empty(&log->io_logs)) {
1979                 struct io_logs *cur_log;
1980                 size_t size;
1981
1982                 cur_log = flist_first_entry(&log->io_logs, struct io_logs, list);
1983                 flist_del_init(&cur_log->list);
1984
1985                 size = cur_log->nr_samples * log_entry_sz(log);
1986
1987                 entry = fio_net_prep_cmd(FIO_NET_CMD_IOLOG, cur_log->log, size,
1988                                                 NULL, SK_F_VEC | SK_F_INLINE);
1989                 if (!entry) {
1990                         ret = 1;
1991                         break;
1992                 }
1993                 flist_add_tail(&entry->list, &first->next);
1994         }
1995
1996         return ret;
1997 }
1998
1999 int fio_send_iolog(struct thread_data *td, struct io_log *log, const char *name)
2000 {
2001         struct cmd_iolog_pdu pdu = {
2002                 .nr_samples             = cpu_to_le64(iolog_nr_samples(log)),
2003                 .thread_number          = cpu_to_le32(td->thread_number),
2004                 .log_type               = cpu_to_le32(log->log_type),
2005                 .log_hist_coarseness    = cpu_to_le32(log->hist_coarseness),
2006         };
2007         struct sk_entry *first;
2008         struct flist_head *entry;
2009         int ret = 0;
2010
2011         if (!flist_empty(&log->chunk_list))
2012                 pdu.compressed = __cpu_to_le32(STORE_COMPRESSED);
2013         else if (use_zlib)
2014                 pdu.compressed = __cpu_to_le32(XMIT_COMPRESSED);
2015         else
2016                 pdu.compressed = 0;
2017
2018         snprintf((char *) pdu.name, sizeof(pdu.name), "%s", name);
2019
2020         /*
2021          * We can't do this for a pre-compressed log, but for that case,
2022          * log->nr_samples is zero anyway.
2023          */
2024         flist_for_each(entry, &log->io_logs) {
2025                 struct io_logs *cur_log;
2026                 int i;
2027
2028                 cur_log = flist_entry(entry, struct io_logs, list);
2029
2030                 for (i = 0; i < cur_log->nr_samples; i++) {
2031                         struct io_sample *s = get_sample(log, cur_log, i);
2032
2033                         s->time         = cpu_to_le64(s->time);
2034                         s->data.val     = cpu_to_le64(s->data.val);
2035                         s->__ddir       = __cpu_to_le32(s->__ddir);
2036                         s->bs           = cpu_to_le64(s->bs);
2037
2038                         if (log->log_offset) {
2039                                 struct io_sample_offset *so = (void *) s;
2040
2041                                 so->offset = cpu_to_le64(so->offset);
2042                         }
2043                 }
2044         }
2045
2046         /*
2047          * Assemble header entry first
2048          */
2049         first = fio_net_prep_cmd(FIO_NET_CMD_IOLOG, &pdu, sizeof(pdu), NULL, SK_F_VEC | SK_F_INLINE | SK_F_COPY);
2050         if (!first)
2051                 return 1;
2052
2053         /*
2054          * Now append actual log entries. If log compression was enabled on
2055          * the job, just send out the compressed chunks directly. If we
2056          * have a plain log, compress if we can, then send. Otherwise, send
2057          * the plain text output.
2058          */
2059         if (!flist_empty(&log->chunk_list))
2060                 ret = fio_append_gz_chunks(first, log);
2061         else if (use_zlib)
2062                 ret = fio_append_iolog_gz(first, log);
2063         else
2064                 ret = fio_append_text_log(first, log);
2065
2066         fio_net_queue_entry(first);
2067         return ret;
2068 }
2069
2070 void fio_server_send_add_job(struct thread_data *td)
2071 {
2072         struct cmd_add_job_pdu pdu = {
2073                 .thread_number = cpu_to_le32(td->thread_number),
2074                 .groupid = cpu_to_le32(td->groupid),
2075         };
2076
2077         convert_thread_options_to_net(&pdu.top, &td->o);
2078
2079         fio_net_queue_cmd(FIO_NET_CMD_ADD_JOB, &pdu, sizeof(pdu), NULL,
2080                                 SK_F_COPY);
2081 }
2082
2083 void fio_server_send_start(struct thread_data *td)
2084 {
2085         struct sk_out *sk_out = pthread_getspecific(sk_out_key);
2086
2087         assert(sk_out->sk != -1);
2088
2089         fio_net_queue_cmd(FIO_NET_CMD_SERVER_START, NULL, 0, NULL, SK_F_SIMPLE);
2090 }
2091
2092 int fio_server_get_verify_state(const char *name, int threadnumber,
2093                                 void **datap)
2094 {
2095         struct thread_io_list *s;
2096         struct cmd_sendfile out;
2097         struct cmd_reply *rep;
2098         uint64_t tag;
2099         void *data;
2100         int ret;
2101
2102         dprint(FD_NET, "server: request verify state\n");
2103
2104         rep = smalloc(sizeof(*rep));
2105         if (!rep)
2106                 return ENOMEM;
2107
2108         __fio_sem_init(&rep->lock, FIO_SEM_LOCKED);
2109         rep->data = NULL;
2110         rep->error = 0;
2111
2112         verify_state_gen_name((char *) out.path, sizeof(out.path), name, me,
2113                                 threadnumber);
2114         tag = (uint64_t) (uintptr_t) rep;
2115         fio_net_queue_cmd(FIO_NET_CMD_SENDFILE, &out, sizeof(out), &tag,
2116                                 SK_F_COPY);
2117
2118         /*
2119          * Wait for the backend to receive the reply
2120          */
2121         if (fio_sem_down_timeout(&rep->lock, 10000)) {
2122                 log_err("fio: timed out waiting for reply\n");
2123                 ret = ETIMEDOUT;
2124                 goto fail;
2125         }
2126
2127         if (rep->error) {
2128                 log_err("fio: failure on receiving state file %s: %s\n",
2129                                 out.path, strerror(rep->error));
2130                 ret = rep->error;
2131 fail:
2132                 *datap = NULL;
2133                 sfree(rep);
2134                 fio_net_queue_quit();
2135                 return ret;
2136         }
2137
2138         /*
2139          * The format is verify_state_hdr, then thread_io_list. Verify
2140          * the header, and the thread_io_list checksum
2141          */
2142         s = rep->data + sizeof(struct verify_state_hdr);
2143         if (verify_state_hdr(rep->data, s)) {
2144                 ret = EILSEQ;
2145                 goto fail;
2146         }
2147
2148         /*
2149          * Don't need the header from now, copy just the thread_io_list
2150          */
2151         ret = 0;
2152         rep->size -= sizeof(struct verify_state_hdr);
2153         data = malloc(rep->size);
2154         memcpy(data, s, rep->size);
2155         *datap = data;
2156
2157         sfree(rep->data);
2158         __fio_sem_remove(&rep->lock);
2159         sfree(rep);
2160         return ret;
2161 }
2162
2163 static int fio_init_server_ip(void)
2164 {
2165         struct sockaddr *addr;
2166         socklen_t socklen;
2167         char buf[80];
2168         const char *str;
2169         int sk, opt;
2170
2171         if (use_ipv6)
2172                 sk = socket(AF_INET6, SOCK_STREAM, 0);
2173         else
2174                 sk = socket(AF_INET, SOCK_STREAM, 0);
2175
2176         if (sk < 0) {
2177                 log_err("fio: socket: %s\n", strerror(errno));
2178                 return -1;
2179         }
2180
2181         opt = 1;
2182         if (setsockopt(sk, SOL_SOCKET, SO_REUSEADDR, (void *)&opt, sizeof(opt)) < 0) {
2183                 log_err("fio: setsockopt(REUSEADDR): %s\n", strerror(errno));
2184                 close(sk);
2185                 return -1;
2186         }
2187 #ifdef SO_REUSEPORT
2188         /*
2189          * Not fatal if fails, so just ignore it if that happens
2190          */
2191         if (setsockopt(sk, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt))) {
2192         }
2193 #endif
2194
2195         if (use_ipv6) {
2196                 void *src = &saddr_in6.sin6_addr;
2197
2198                 addr = (struct sockaddr *) &saddr_in6;
2199                 socklen = sizeof(saddr_in6);
2200                 saddr_in6.sin6_family = AF_INET6;
2201                 str = inet_ntop(AF_INET6, src, buf, sizeof(buf));
2202         } else {
2203                 void *src = &saddr_in.sin_addr;
2204
2205                 addr = (struct sockaddr *) &saddr_in;
2206                 socklen = sizeof(saddr_in);
2207                 saddr_in.sin_family = AF_INET;
2208                 str = inet_ntop(AF_INET, src, buf, sizeof(buf));
2209         }
2210
2211         if (bind(sk, addr, socklen) < 0) {
2212                 log_err("fio: bind: %s\n", strerror(errno));
2213                 log_info("fio: failed with IPv%c %s\n", use_ipv6 ? '6' : '4', str);
2214                 close(sk);
2215                 return -1;
2216         }
2217
2218         return sk;
2219 }
2220
2221 static int fio_init_server_sock(void)
2222 {
2223         struct sockaddr_un addr;
2224         socklen_t len;
2225         mode_t mode;
2226         int sk;
2227
2228         sk = socket(AF_UNIX, SOCK_STREAM, 0);
2229         if (sk < 0) {
2230                 log_err("fio: socket: %s\n", strerror(errno));
2231                 return -1;
2232         }
2233
2234         mode = umask(000);
2235
2236         addr.sun_family = AF_UNIX;
2237         snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", bind_sock);
2238
2239         len = sizeof(addr.sun_family) + strlen(bind_sock) + 1;
2240
2241         if (bind(sk, (struct sockaddr *) &addr, len) < 0) {
2242                 log_err("fio: bind: %s\n", strerror(errno));
2243                 close(sk);
2244                 return -1;
2245         }
2246
2247         umask(mode);
2248         return sk;
2249 }
2250
2251 static int fio_init_server_connection(void)
2252 {
2253         char bind_str[128];
2254         int sk;
2255
2256         dprint(FD_NET, "starting server\n");
2257
2258         if (!bind_sock)
2259                 sk = fio_init_server_ip();
2260         else
2261                 sk = fio_init_server_sock();
2262
2263         if (sk < 0)
2264                 return sk;
2265
2266         memset(bind_str, 0, sizeof(bind_str));
2267
2268         if (!bind_sock) {
2269                 char *p, port[16];
2270                 void *src;
2271                 int af;
2272
2273                 if (use_ipv6) {
2274                         af = AF_INET6;
2275                         src = &saddr_in6.sin6_addr;
2276                 } else {
2277                         af = AF_INET;
2278                         src = &saddr_in.sin_addr;
2279                 }
2280
2281                 p = (char *) inet_ntop(af, src, bind_str, sizeof(bind_str));
2282
2283                 sprintf(port, ",%u", fio_net_port);
2284                 if (p)
2285                         strcat(p, port);
2286                 else
2287                         snprintf(bind_str, sizeof(bind_str), "%s", port);
2288         } else
2289                 snprintf(bind_str, sizeof(bind_str), "%s", bind_sock);
2290
2291         log_info("fio: server listening on %s\n", bind_str);
2292
2293         if (listen(sk, 4) < 0) {
2294                 log_err("fio: listen: %s\n", strerror(errno));
2295                 close(sk);
2296                 return -1;
2297         }
2298
2299         return sk;
2300 }
2301
2302 int fio_server_parse_host(const char *host, int ipv6, struct in_addr *inp,
2303                           struct in6_addr *inp6)
2304
2305 {
2306         int ret = 0;
2307
2308         if (ipv6)
2309                 ret = inet_pton(AF_INET6, host, inp6);
2310         else
2311                 ret = inet_pton(AF_INET, host, inp);
2312
2313         if (ret != 1) {
2314                 struct addrinfo *res, hints = {
2315                         .ai_family = ipv6 ? AF_INET6 : AF_INET,
2316                         .ai_socktype = SOCK_STREAM,
2317                 };
2318
2319                 ret = getaddrinfo(host, NULL, &hints, &res);
2320                 if (ret) {
2321                         log_err("fio: failed to resolve <%s> (%s)\n", host,
2322                                         gai_strerror(ret));
2323                         return 1;
2324                 }
2325
2326                 if (ipv6)
2327                         memcpy(inp6, &((struct sockaddr_in6 *) res->ai_addr)->sin6_addr, sizeof(*inp6));
2328                 else
2329                         memcpy(inp, &((struct sockaddr_in *) res->ai_addr)->sin_addr, sizeof(*inp));
2330
2331                 ret = 1;
2332                 freeaddrinfo(res);
2333         }
2334
2335         return !(ret == 1);
2336 }
2337
2338 /*
2339  * Parse a host/ip/port string. Reads from 'str'.
2340  *
2341  * Outputs:
2342  *
2343  * For IPv4:
2344  *      *ptr is the host, *port is the port, inp is the destination.
2345  * For IPv6:
2346  *      *ptr is the host, *port is the port, inp6 is the dest, and *ipv6 is 1.
2347  * For local domain sockets:
2348  *      *ptr is the filename, *is_sock is 1.
2349  */
2350 int fio_server_parse_string(const char *str, char **ptr, bool *is_sock,
2351                             int *port, struct in_addr *inp,
2352                             struct in6_addr *inp6, int *ipv6)
2353 {
2354         const char *host = str;
2355         char *portp;
2356         int lport = 0;
2357
2358         *ptr = NULL;
2359         *is_sock = false;
2360         *port = fio_net_port;
2361         *ipv6 = 0;
2362
2363         if (!strncmp(str, "sock:", 5)) {
2364                 *ptr = strdup(str + 5);
2365                 *is_sock = true;
2366
2367                 return 0;
2368         }
2369
2370         /*
2371          * Is it ip:<ip or host>:port
2372          */
2373         if (!strncmp(host, "ip:", 3))
2374                 host += 3;
2375         else if (!strncmp(host, "ip4:", 4))
2376                 host += 4;
2377         else if (!strncmp(host, "ip6:", 4)) {
2378                 host += 4;
2379                 *ipv6 = 1;
2380         } else if (host[0] == ':') {
2381                 /* String is :port */
2382                 host++;
2383                 lport = atoi(host);
2384                 if (!lport || lport > 65535) {
2385                         log_err("fio: bad server port %u\n", lport);
2386                         return 1;
2387                 }
2388                 /* no hostname given, we are done */
2389                 *port = lport;
2390                 return 0;
2391         }
2392
2393         /*
2394          * If no port seen yet, check if there's a last ',' at the end
2395          */
2396         if (!lport) {
2397                 portp = strchr(host, ',');
2398                 if (portp) {
2399                         *portp = '\0';
2400                         portp++;
2401                         lport = atoi(portp);
2402                         if (!lport || lport > 65535) {
2403                                 log_err("fio: bad server port %u\n", lport);
2404                                 return 1;
2405                         }
2406                 }
2407         }
2408
2409         if (lport)
2410                 *port = lport;
2411
2412         if (!strlen(host))
2413                 return 0;
2414
2415         *ptr = strdup(host);
2416
2417         if (fio_server_parse_host(*ptr, *ipv6, inp, inp6)) {
2418                 free(*ptr);
2419                 *ptr = NULL;
2420                 return 1;
2421         }
2422
2423         if (*port == 0)
2424                 *port = fio_net_port;
2425
2426         return 0;
2427 }
2428
2429 /*
2430  * Server arg should be one of:
2431  *
2432  * sock:/path/to/socket
2433  *   ip:1.2.3.4
2434  *      1.2.3.4
2435  *
2436  * Where sock uses unix domain sockets, and ip binds the server to
2437  * a specific interface. If no arguments are given to the server, it
2438  * uses IP and binds to 0.0.0.0.
2439  *
2440  */
2441 static int fio_handle_server_arg(void)
2442 {
2443         int port = fio_net_port;
2444         bool is_sock;
2445         int ret = 0;
2446
2447         saddr_in.sin_addr.s_addr = htonl(INADDR_ANY);
2448
2449         if (!fio_server_arg)
2450                 goto out;
2451
2452         ret = fio_server_parse_string(fio_server_arg, &bind_sock, &is_sock,
2453                                         &port, &saddr_in.sin_addr,
2454                                         &saddr_in6.sin6_addr, &use_ipv6);
2455
2456         if (!is_sock && bind_sock) {
2457                 free(bind_sock);
2458                 bind_sock = NULL;
2459         }
2460
2461 out:
2462         fio_net_port = port;
2463         saddr_in.sin_port = htons(port);
2464         saddr_in6.sin6_port = htons(port);
2465         return ret;
2466 }
2467
2468 static void sig_int(int sig)
2469 {
2470         if (bind_sock)
2471                 unlink(bind_sock);
2472 }
2473
2474 static void set_sig_handlers(void)
2475 {
2476         struct sigaction act = {
2477                 .sa_handler = sig_int,
2478                 .sa_flags = SA_RESTART,
2479         };
2480
2481         sigaction(SIGINT, &act, NULL);
2482
2483         /* Windows uses SIGBREAK as a quit signal from other applications */
2484 #ifdef WIN32
2485         sigaction(SIGBREAK, &act, NULL);
2486 #endif
2487 }
2488
2489 void fio_server_destroy_sk_key(void)
2490 {
2491         pthread_key_delete(sk_out_key);
2492 }
2493
2494 int fio_server_create_sk_key(void)
2495 {
2496         if (pthread_key_create(&sk_out_key, NULL)) {
2497                 log_err("fio: can't create sk_out backend key\n");
2498                 return 1;
2499         }
2500
2501         pthread_setspecific(sk_out_key, NULL);
2502         return 0;
2503 }
2504
2505 static int fio_server(void)
2506 {
2507         int sk, ret;
2508
2509         dprint(FD_NET, "starting server\n");
2510
2511         if (fio_handle_server_arg())
2512                 return -1;
2513
2514         sk = fio_init_server_connection();
2515         if (sk < 0)
2516                 return -1;
2517
2518         set_sig_handlers();
2519
2520         ret = accept_loop(sk);
2521
2522         close(sk);
2523
2524         if (fio_server_arg) {
2525                 free(fio_server_arg);
2526                 fio_server_arg = NULL;
2527         }
2528         if (bind_sock)
2529                 free(bind_sock);
2530
2531         return ret;
2532 }
2533
2534 void fio_server_got_signal(int signal)
2535 {
2536         struct sk_out *sk_out = pthread_getspecific(sk_out_key);
2537
2538         assert(sk_out);
2539
2540         if (signal == SIGPIPE)
2541                 sk_out->sk = -1;
2542         else {
2543                 log_info("\nfio: terminating on signal %d\n", signal);
2544                 exit_backend = true;
2545         }
2546 }
2547
2548 static int check_existing_pidfile(const char *pidfile)
2549 {
2550         struct stat sb;
2551         char buf[16];
2552         pid_t pid;
2553         FILE *f;
2554
2555         if (stat(pidfile, &sb))
2556                 return 0;
2557
2558         f = fopen(pidfile, "r");
2559         if (!f)
2560                 return 0;
2561
2562         if (fread(buf, sb.st_size, 1, f) <= 0) {
2563                 fclose(f);
2564                 return 1;
2565         }
2566         fclose(f);
2567
2568         pid = atoi(buf);
2569         if (kill(pid, SIGCONT) < 0)
2570                 return errno != ESRCH;
2571
2572         return 1;
2573 }
2574
2575 static int write_pid(pid_t pid, const char *pidfile)
2576 {
2577         FILE *fpid;
2578
2579         fpid = fopen(pidfile, "w");
2580         if (!fpid) {
2581                 log_err("fio: failed opening pid file %s\n", pidfile);
2582                 return 1;
2583         }
2584
2585         fprintf(fpid, "%u\n", (unsigned int) pid);
2586         fclose(fpid);
2587         return 0;
2588 }
2589
2590 /*
2591  * If pidfile is specified, background us.
2592  */
2593 int fio_start_server(char *pidfile)
2594 {
2595         FILE *file;
2596         pid_t pid;
2597         int ret;
2598
2599 #if defined(WIN32)
2600         WSADATA wsd;
2601         WSAStartup(MAKEWORD(2, 2), &wsd);
2602 #endif
2603
2604         if (!pidfile)
2605                 return fio_server();
2606
2607         if (check_existing_pidfile(pidfile)) {
2608                 log_err("fio: pidfile %s exists and server appears alive\n",
2609                                                                 pidfile);
2610                 free(pidfile);
2611                 return -1;
2612         }
2613
2614         pid = fork();
2615         if (pid < 0) {
2616                 log_err("fio: failed server fork: %s\n", strerror(errno));
2617                 free(pidfile);
2618                 return -1;
2619         } else if (pid) {
2620                 ret = write_pid(pid, pidfile);
2621                 free(pidfile);
2622                 _exit(ret);
2623         }
2624
2625         setsid();
2626         openlog("fio", LOG_NDELAY|LOG_NOWAIT|LOG_PID, LOG_USER);
2627         log_syslog = true;
2628
2629         file = freopen("/dev/null", "r", stdin);
2630         if (!file)
2631                 perror("freopen");
2632
2633         file = freopen("/dev/null", "w", stdout);
2634         if (!file)
2635                 perror("freopen");
2636
2637         file = freopen("/dev/null", "w", stderr);
2638         if (!file)
2639                 perror("freopen");
2640
2641         f_out = NULL;
2642         f_err = NULL;
2643
2644         ret = fio_server();
2645
2646         fclose(stdin);
2647         fclose(stdout);
2648         fclose(stderr);
2649
2650         closelog();
2651         unlink(pidfile);
2652         free(pidfile);
2653         return ret;
2654 }
2655
2656 void fio_server_set_arg(const char *arg)
2657 {
2658         fio_server_arg = strdup(arg);
2659 }