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