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