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