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