Distributed engine: Avoid unlikely race condition in buffer recycling
[pachi.git] / distributed / protocol.c
blobe26d09501f6d77512b5b48d2f578bcaebb458a09
1 /* The functions implementing the master-slave protocol of the
2 * distributed engine are grouped here. They are independent
3 * of the gtp protocol. See the comments at the top of distributed.c
4 * for a general introduction to the distributed engine. */
6 /* The receive queue is an array of pointers to binary buffers.
7 * These pointers are invalidated in one of two ways when a buffer
8 * is recycled: (1) the queue age is increased when the queue is
9 * emptied at a new move, (2) the pointer itself is set to NULL
10 * immmediately, and stays so until at least the next queue age
11 * increment. */
13 #include <assert.h>
14 #include <stdio.h>
15 #include <pthread.h>
16 #include <ctype.h>
18 #define DEBUG
20 #include "random.h"
21 #include "timeinfo.h"
22 #include "playout.h"
23 #include "network.h"
24 #include "debug.h"
25 #include "distributed/distributed.h"
26 #include "distributed/protocol.h"
28 /* All gtp commands for current game separated by \n */
29 static char gtp_cmds[CMDS_SIZE];
31 /* Latest gtp command sent to slaves. */
32 static char *gtp_cmd = NULL;
34 /* Slaves send gtp_cmd when cmd_count changes. */
35 static int cmd_count = 0;
37 /* Remember at most 10 gtp ids per move: kgs-rules, boardsize, clear_board,
38 * time_settings, komi, handicap, genmoves, play pass, play pass, final_status_list */
39 #define MAX_CMDS_PER_MOVE 10
41 /* History of gtp commands sent for current game, indexed by move. */
42 static struct cmd_history {
43 int gtp_id;
44 char *next_cmd;
45 } history[MAX_GAMELEN][MAX_CMDS_PER_MOVE];
47 /* Number of active slave machines working for this master. */
48 int active_slaves = 0;
50 /* Number of replies to last gtp command already received. */
51 int reply_count = 0;
53 /* All replies to latest gtp command are in gtp_replies[0..reply_count-1]. */
54 char **gtp_replies;
57 struct buf_state **receive_queue;
58 int queue_length = 0;
59 int queue_age = 0;
60 static int queue_max_length;
62 /* Mutex protecting all variables above. receive_queue may be
63 * read without the lock but is only written with lock held. */
64 static pthread_mutex_t slave_lock = PTHREAD_MUTEX_INITIALIZER;
66 /* Condition signaled when a new gtp command is available. */
67 static pthread_cond_t cmd_cond = PTHREAD_COND_INITIALIZER;
69 /* Condition signaled when reply_count increases. */
70 static pthread_cond_t reply_cond = PTHREAD_COND_INITIALIZER;
72 /* Mutex protecting stderr. Must not be held at same time as slave_lock. */
73 static pthread_mutex_t log_lock = PTHREAD_MUTEX_INITIALIZER;
75 /* Absolute time when this program was started.
76 * For debugging only. */
77 static double start_time;
79 /* Default slave state. */
80 struct slave_state default_sstate;
83 /* Get exclusive access to the threads and commands state. */
84 void
85 protocol_lock(void)
87 pthread_mutex_lock(&slave_lock);
90 /* Release exclusive access to the threads and commands state. */
91 void
92 protocol_unlock(void)
94 pthread_mutex_unlock(&slave_lock);
97 /* Write the time, client address, prefix, and string s to stderr atomically.
98 * s should end with a \n */
99 void
100 logline(struct in_addr *client, char *prefix, char *s)
102 double now = time_now();
104 char addr[INET_ADDRSTRLEN];
105 if (client) {
106 inet_ntop(AF_INET, client, addr, sizeof(addr));
107 } else {
108 addr[0] = '\0';
110 pthread_mutex_lock(&log_lock);
111 fprintf(stderr, "%s%15s %9.3f: %s", prefix, addr, now - start_time, s);
112 pthread_mutex_unlock(&log_lock);
115 /* Thread opening a connection on the given socket and copying input
116 * from there to stderr. */
117 static void *
118 proxy_thread(void *arg)
120 int proxy_sock = (long)arg;
121 assert(proxy_sock >= 0);
122 for (;;) {
123 struct in_addr client;
124 int conn = open_server_connection(proxy_sock, &client);
125 FILE *f = fdopen(conn, "r");
126 char buf[BSIZE];
127 while (fgets(buf, BSIZE, f)) {
128 logline(&client, "< ", buf);
130 fclose(f);
134 /* Get a reply to one gtp command. Return the gtp command id,
135 * or -1 if error. reply must have at least CMDS_SIZE bytes.
136 * The ascii reply ends with an empty line; if the first line
137 * contains "@size", a binary reply of size bytes follows the
138 * empty line. @size is not standard gtp, it is only used
139 * internally by Pachi for the genmoves command; it must be the
140 * last parameter on the line.
141 * *bin_size is the maximum size upon entry, actual size on return.
142 * slave_lock is not held on either entry or exit of this function. */
143 static int
144 get_reply(FILE *f, struct in_addr client, char *reply, void *bin_reply, int *bin_size)
146 int reply_id = -1;
147 *reply = '\0';
148 if (!fgets(reply, CMDS_SIZE, f)) return -1;
150 /* Check for binary reply. */
151 char *s = strchr(reply, '@');
152 int size = 0;
153 if (s) size = atoi(s+1);
154 assert(size <= *bin_size);
155 *bin_size = size;
157 if (DEBUGV(s, 2))
158 logline(&client, "<<", reply);
159 if ((*reply == '=' || *reply == '?') && isdigit(reply[1]))
160 reply_id = atoi(reply+1);
162 /* Read the rest of the ascii reply */
163 char *line = reply + strlen(reply);
164 while (fgets(line, reply + CMDS_SIZE - line, f) && *line != '\n') {
165 if (DEBUGL(3))
166 logline(&client, "<<", line);
167 line += strlen(line);
169 if (*line != '\n') return -1;
171 /* Read the binary reply if any. */
172 double start = time_now();
173 int len;
174 while (size && (len = fread(bin_reply, 1, size, f)) > 0) {
175 bin_reply = (char *)bin_reply + len;
176 size -= len;
178 if (*bin_size && DEBUGVV(2)) {
179 char buf[1024];
180 snprintf(buf, sizeof(buf), "read reply %d bytes in %.4fms\n", *bin_size,
181 (time_now() - start)*1000);
182 logline(&client, "= ", buf);
184 return size ? -1 : reply_id;
187 /* Send the gtp command to_send and get a reply from the slave machine.
188 * Write the reply in buf which must have at least CMDS_SIZE bytes.
189 * If *bin_size > 0, send bin_buf after the gtp command.
190 * Return any binary reply in bin_buf and set its size in bin_size.
191 * bin_buf is private to the slave and need not be copied.
192 * Return the gtp command id, or -1 if error.
193 * slave_lock is held on both entry and exit of this function. */
194 static int
195 send_command(char *to_send, void *bin_buf, int *bin_size,
196 FILE *f, struct slave_state *sstate, char *buf)
198 assert(to_send && gtp_cmd && bin_buf && bin_size);
199 strncpy(buf, to_send, CMDS_SIZE);
200 bool resend = to_send != gtp_cmd;
202 pthread_mutex_unlock(&slave_lock);
204 if (DEBUGL(1) && resend)
205 logline(&sstate->client, "? ",
206 to_send == gtp_cmds ? "resend all\n" : "partial resend\n");
207 fputs(buf, f);
209 double start = time_now();
210 if (*bin_size)
211 fwrite(bin_buf, 1, *bin_size, f);
212 fflush(f);
214 if (DEBUGV(strchr(buf, '@'), 2)) {
215 double ms = (time_now() - start) * 1000.0;
216 if (!DEBUGL(3)) {
217 char *s = strchr(buf, '\n');
218 if (s) s[1] = '\0';
220 logline(&sstate->client, ">>", buf);
221 if (*bin_size) {
222 char b[1024];
223 snprintf(b, sizeof(b),
224 "sent args %d bytes in %.4fms\n", *bin_size, ms);
225 logline(&sstate->client, "= ", b);
229 /* Reuse the buffers for the reply. */
230 *bin_size = sstate->max_buf_size;
231 int reply_id = get_reply(f, sstate->client, buf, bin_buf, bin_size);
233 pthread_mutex_lock(&slave_lock);
234 return reply_id;
237 /* Return the command sent after that with the given gtp id,
238 * or gtp_cmds if the id wasn't used in this game. If a play command
239 * has overwritten a genmoves command, return the play command.
240 * slave_lock is held on both entry and exit of this function. */
241 static char *
242 next_command(int cmd_id)
244 if (cmd_id == -1) return gtp_cmds;
246 int last_id = atoi(gtp_cmd);
247 int reply_move = move_number(cmd_id);
248 if (reply_move > move_number(last_id)) return gtp_cmds;
250 int slot;
251 for (slot = 0; slot < MAX_CMDS_PER_MOVE; slot++) {
252 if (cmd_id == history[reply_move][slot].gtp_id) break;
254 if (slot == MAX_CMDS_PER_MOVE) return gtp_cmds;
256 char *next = history[reply_move][slot].next_cmd;
257 assert(next);
258 return next;
261 /* Allocate buffers for a slave thread. The state should have been
262 * initialized already as a copy of the default slave state.
263 * slave_lock is not held on either entry or exit of this function. */
264 static void
265 slave_state_alloc(struct slave_state *sstate)
267 for (int n = 0; n < BUFFERS_PER_SLAVE; n++) {
268 sstate->b[n].buf = malloc2(sstate->max_buf_size);
269 sstate->b[n].owner = sstate->thread_id;
271 if (sstate->alloc_hook) sstate->alloc_hook(sstate);
274 /* Get a free binary buffer, first invalidating it in the receive
275 * queue if necessary. In practice all buffers should be used
276 * before they are invalidated, if BUFFERS_PER_SLAVE is large enough.
277 * slave_lock is held on both entry and exit of this function. */
278 static void *
279 get_free_buf(struct slave_state *sstate)
281 int newest = (sstate->newest_buf + 1) & (BUFFERS_PER_SLAVE - 1);
282 sstate->newest_buf = newest;
283 void *buf = sstate->b[newest].buf;
285 if (DEBUGVV(7)) {
286 char b[1024];
287 snprintf(b, sizeof(b),
288 "get free %d index %d buf=%p age %d qlength %d\n", newest,
289 sstate->b[newest].queue_index, buf, queue_age, queue_length);
290 logline(&sstate->client, "? ", b);
293 int index = sstate->b[newest].queue_index;
294 if (index < 0) return buf;
296 /* Invalidate the buffer if the calling thread still owns its previous
297 * entry in the receive queue. The entry may have been overwritten by
298 * another thread, but only after a new move which invalidates the
299 * entire receive queue. */
300 if (receive_queue[index] && receive_queue[index]->owner == sstate->thread_id) {
301 receive_queue[index] = NULL;
303 sstate->b[newest].queue_index = -1;
304 return buf;
307 /* Insert a buffer in the receive queue. It should be the most
308 * recent buffer allocated by the calling thread.
309 * slave_lock is held on both entry and exit of this function. */
310 static void
311 insert_buf(struct slave_state *sstate, void *buf, int size)
313 assert(queue_length < queue_max_length);
315 int newest = sstate->newest_buf;
316 assert(buf == sstate->b[newest].buf);
318 /* Update the buffer if necessary before making it
319 * available to other threads. */
320 if (sstate->insert_hook) sstate->insert_hook(buf, size);
322 if (DEBUGVV(7)) {
323 char b[1024];
324 snprintf(b, sizeof(b),
325 "insert newest %d age %d rq[%d]->%p owner %d\n",
326 newest, queue_age, queue_length, buf, sstate->thread_id);
327 logline(&sstate->client, "? ", b);
329 receive_queue[queue_length] = &sstate->b[newest];
330 receive_queue[queue_length]->size = size;
331 receive_queue[queue_length]->queue_index = queue_length;
332 queue_length++;
335 /* Clear the receive queue. The buffer pointers do not have to be cleared
336 * here, this is done as each buffer is recycled.
337 * slave_lock is held on both entry and exit of this function. */
338 void
339 clear_receive_queue(void)
341 if (DEBUGL(3)) {
342 char buf[1024];
343 snprintf(buf, sizeof(buf), "clear queue, old length %d age %d\n",
344 queue_length, queue_age);
345 logline(NULL, "? ", buf);
347 queue_length = 0;
348 queue_age++;
351 /* Process the reply received from a slave machine.
352 * Copy the ascii part to reply_buf and insert the binary part
353 * (if any) in the receive queue.
354 * Return false if ok, true if the slave is out of sync.
355 * slave_lock is held on both entry and exit of this function. */
356 static bool
357 process_reply(int reply_id, char *reply, char *reply_buf,
358 void *bin_reply, int bin_size, int *last_reply_id,
359 int *reply_slot, struct slave_state *sstate)
361 /* Resend everything if slave returned an error. */
362 if (*reply != '=') {
363 *last_reply_id = -1;
364 return true;
366 /* Make sure we are still in sync. cmd_count may have
367 * changed but the reply is valid as long as cmd_id didn't
368 * change (this only occurs for consecutive genmoves). */
369 int cmd_id = atoi(gtp_cmd);
370 if (reply_id != cmd_id) {
371 *last_reply_id = reply_id;
372 return true;
375 strncpy(reply_buf, reply, CMDS_SIZE);
376 if (reply_id != *last_reply_id)
377 *reply_slot = reply_count++;
378 gtp_replies[*reply_slot] = reply_buf;
380 if (bin_size) insert_buf(sstate, bin_reply, bin_size);
382 pthread_cond_signal(&reply_cond);
383 *last_reply_id = reply_id;
384 return false;
387 /* Get the binary arg for the given command, and update the command
388 * if necessary. For now, only genmoves has a binary argument, and
389 * we return the best stats increments from all other slaves.
390 * Set *bin_size to 0 if the command doesn't take binary arguments,
391 * but still return a buffer, to be used for the reply.
392 * Return NULL if the binary arg is obsolete by the time we have
393 * finished computing it, because a new command is available.
394 * This version only gets the buffer for the reply, to be completed
395 * in future commits.
396 * slave_lock is held on both entry and exit of this function. */
397 void *
398 get_binary_arg(struct slave_state *sstate, char *cmd, int cmd_size, int *bin_size)
400 int cmd_id = atoi(gtp_cmd);
401 void *buf = get_free_buf(sstate);
403 *bin_size = 0;
404 char *s = strchr(cmd, '@');
405 if (!s || !sstate->args_hook) return buf;
407 int size = sstate->args_hook(buf, sstate, cmd_id);
409 /* Check that the command is still valid. */
410 if (atoi(gtp_cmd) != cmd_id) return NULL;
412 /* Set the correct binary size for this slave.
413 * cmd may have been overwritten with new parameters. */
414 *bin_size = size;
415 s = strchr(cmd, '@');
416 assert(s);
417 snprintf(s, cmd + cmd_size - s, "@%d\n", size);
418 return buf;
421 /* Main loop of a slave thread.
422 * Send the current command to the slave machine and wait for a reply.
423 * Resend command history if the slave machine is out of sync.
424 * Returns when the connection with the slave machine is cut.
425 * slave_lock is held on both entry and exit of this function. */
426 static void
427 slave_loop(FILE *f, char *reply_buf, struct slave_state *sstate, bool resend)
429 char *to_send;
430 int last_cmd_count = 0;
431 int last_reply_id = -1;
432 int reply_slot = -1;
433 for (;;) {
434 if (resend) {
435 /* Resend complete or partial history */
436 to_send = next_command(last_reply_id);
437 } else {
438 /* Wait for a new command. */
439 while (last_cmd_count == cmd_count)
440 pthread_cond_wait(&cmd_cond, &slave_lock);
441 to_send = gtp_cmd;
444 /* Command available, send it to slave machine.
445 * If slave was out of sync, send the history.
446 * But first get binary arguments if necessary. */
447 int bin_size = 0;
448 void *bin_buf = get_binary_arg(sstate, gtp_cmd,
449 gtp_cmds + CMDS_SIZE - gtp_cmd,
450 &bin_size);
451 /* Check that the command is still valid. */
452 resend = true;
453 if (!bin_buf) continue;
455 /* Send the command and get the reply, which always ends with \n\n
456 * The slave machine sends "=id reply" or "?id reply"
457 * with id == cmd_id if it is in sync. */
458 last_cmd_count = cmd_count;
459 char buf[CMDS_SIZE];
460 int reply_id = send_command(to_send, bin_buf, &bin_size, f,
461 sstate, buf);
462 if (reply_id == -1) return;
464 resend = process_reply(reply_id, buf, reply_buf, bin_buf, bin_size,
465 &last_reply_id, &reply_slot, sstate);
469 /* Thread sending gtp commands to one slave machine, and
470 * reading replies. If a slave machine dies, this thread waits
471 * for a connection from another slave.
472 * The large buffers are allocated only once we get a first
473 * connection, to avoid wasting memory if max_slaves is too large.
474 * We do not invalidate the received buffers if a slave disconnects;
475 * they are still useful for other slaves. */
476 static void *
477 slave_thread(void *arg)
479 struct slave_state sstate = default_sstate;
480 sstate.thread_id = (long)arg;
482 assert(sstate.slave_sock >= 0);
483 char reply_buf[CMDS_SIZE];
484 bool resend = false;
486 for (;;) {
487 /* Wait for a connection from any slave. */
488 struct in_addr client;
489 int conn = open_server_connection(sstate.slave_sock, &client);
491 FILE *f = fdopen(conn, "r+");
492 if (DEBUGL(2)) {
493 snprintf(reply_buf, sizeof(reply_buf),
494 "new slave, id %d\n", sstate.thread_id);
495 logline(&client, "= ", reply_buf);
498 /* Minimal check of the slave identity. */
499 fputs("name\n", f);
500 if (!fgets(reply_buf, sizeof(reply_buf), f)
501 || strncasecmp(reply_buf, "= Pachi", 7)
502 || !fgets(reply_buf, sizeof(reply_buf), f)
503 || strcmp(reply_buf, "\n")) {
504 logline(&client, "? ", "bad slave\n");
505 fclose(f);
506 continue;
509 if (!resend) slave_state_alloc(&sstate);
510 sstate.client = client;
512 pthread_mutex_lock(&slave_lock);
513 active_slaves++;
514 slave_loop(f, reply_buf, &sstate, resend);
516 assert(active_slaves > 0);
517 active_slaves--;
518 // Unblock main thread if it was waiting for this slave.
519 pthread_cond_signal(&reply_cond);
520 pthread_mutex_unlock(&slave_lock);
522 resend = true;
523 if (DEBUGL(2))
524 logline(&client, "= ", "lost slave\n");
525 fclose(f);
529 /* Create a new gtp command for all slaves. The slave lock is held
530 * upon entry and upon return, so the command will actually be
531 * sent when the lock is released. The last command is overwritten
532 * if gtp_cmd points to a non-empty string. cmd is a single word;
533 * args has all arguments and is empty or has a trailing \n */
534 void
535 update_cmd(struct board *b, char *cmd, char *args, bool new_id)
537 assert(gtp_cmd);
538 /* To make sure the slaves are in sync, we ignore the original id
539 * and use the board number plus some random bits as gtp id. */
540 static int gtp_id = -1;
541 int moves = is_reset(cmd) ? 0 : b->moves;
542 if (new_id) {
543 int prev_id = gtp_id;
544 do {
545 /* fast_random() is 16-bit only so the multiplication can't overflow. */
546 gtp_id = force_reply(moves + fast_random(65535) * DIST_GAMELEN);
547 } while (gtp_id == prev_id);
548 reply_count = 0;
550 snprintf(gtp_cmd, gtp_cmds + CMDS_SIZE - gtp_cmd, "%d %s %s",
551 gtp_id, cmd, *args ? args : "\n");
552 cmd_count++;
554 /* Remember history for out-of-sync slaves. */
555 static int slot = 0;
556 static struct cmd_history *last = NULL;
557 if (new_id) {
558 if (last) last->next_cmd = gtp_cmd;
559 slot = (slot + 1) % MAX_CMDS_PER_MOVE;
560 last = &history[moves][slot];
561 last->gtp_id = gtp_id;
562 last->next_cmd = NULL;
564 // Notify the slave threads about the new command.
565 pthread_cond_broadcast(&cmd_cond);
568 /* Update the command history, then create a new gtp command
569 * for all slaves. The slave lock is held upon entry and
570 * upon return, so the command will actually be sent when the
571 * lock is released. cmd is a single word; args has all
572 * arguments and is empty or has a trailing \n */
573 void
574 new_cmd(struct board *b, char *cmd, char *args)
576 // Clear the history when a new game starts:
577 if (!gtp_cmd || is_gamestart(cmd)) {
578 gtp_cmd = gtp_cmds;
579 memset(history, 0, sizeof(history));
580 } else {
581 /* Preserve command history for new slaves.
582 * To indicate that the slave should only reply to
583 * the last command we force the id of previous
584 * commands to be just the move number. */
585 int id = prevent_reply(atoi(gtp_cmd));
586 int len = strspn(gtp_cmd, "0123456789");
587 char buf[32];
588 snprintf(buf, sizeof(buf), "%0*d", len, id);
589 memcpy(gtp_cmd, buf, len);
591 gtp_cmd += strlen(gtp_cmd);
594 // Let the slave threads send the new gtp command:
595 update_cmd(b, cmd, args, true);
598 /* Wait for at least one new reply. Return when at least
599 * min_replies slaves have already replied, or when the
600 * given absolute time is passed.
601 * The replies are returned in gtp_replies[0..reply_count-1]
602 * slave_lock is held on entry and on return. */
603 void
604 get_replies(double time_limit, int min_replies)
606 for (;;) {
607 if (reply_count > 0) {
608 struct timespec ts;
609 double sec;
610 ts.tv_nsec = (int)(modf(time_limit, &sec)*1000000000.0);
611 ts.tv_sec = (int)sec;
612 pthread_cond_timedwait(&reply_cond, &slave_lock, &ts);
613 } else {
614 pthread_cond_wait(&reply_cond, &slave_lock);
616 if (reply_count == 0) continue;
617 if (reply_count >= min_replies || reply_count >= active_slaves) return;
618 if (time_now() >= time_limit) break;
620 if (DEBUGL(1)) {
621 char buf[1024];
622 snprintf(buf, sizeof(buf),
623 "get_replies timeout %.3f >= %.3f, replies %d < min %d, active %d\n",
624 time_now() - start_time, time_limit - start_time,
625 reply_count, min_replies, active_slaves);
626 logline(NULL, "? ", buf);
628 assert(reply_count > 0);
631 /* In a 30s move with at least 5ms per genmoves we get at most
632 * 6000 genmoves per slave. */
633 #define MAX_GENMOVES_PER_SLAVE 6000
635 /* Allocate the receive queue, and create the slave and proxy threads.
636 * max_buf_size and the merge-related fields of default_sstate must
637 * already be initialized. */
638 void
639 protocol_init(char *slave_port, char *proxy_port, int max_slaves)
641 start_time = time_now();
643 queue_max_length = max_slaves * MAX_GENMOVES_PER_SLAVE;
644 receive_queue = calloc2(queue_max_length, sizeof(*receive_queue));
646 default_sstate.slave_sock = port_listen(slave_port, max_slaves);
647 default_sstate.last_processed = -1;
649 for (int n = 0; n < BUFFERS_PER_SLAVE; n++) {
650 default_sstate.b[n].queue_index = -1;
653 pthread_t thread;
654 for (int id = 0; id < max_slaves; id++) {
655 pthread_create(&thread, NULL, slave_thread, (void *)(long)id);
658 if (proxy_port) {
659 int proxy_sock = port_listen(proxy_port, max_slaves);
660 for (int id = 0; id < max_slaves; id++) {
661 pthread_create(&thread, NULL, proxy_thread, (void *)(long)proxy_sock);