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