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