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