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