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