]> git.ozlabs.org Git - ccan/blob - ccan/tdb/tools/replay_trace.c
Print seq numbers on timeout dump
[ccan] / ccan / tdb / tools / replay_trace.c
1 #include <ccan/tdb/tdb.h>
2 #include <ccan/grab_file/grab_file.h>
3 #include <ccan/hash/hash.h>
4 #include <ccan/talloc/talloc.h>
5 #include <ccan/str_talloc/str_talloc.h>
6 #include <ccan/str/str.h>
7 #include <ccan/list/list.h>
8 #include <err.h>
9 #include <ctype.h>
10 #include <string.h>
11 #include <unistd.h>
12 #include <sys/types.h>
13 #include <sys/wait.h>
14 #include <sys/time.h>
15 #include <errno.h>
16 #include <signal.h>
17 #include <assert.h>
18
19 #define STRINGIFY2(x) #x
20 #define STRINGIFY(x) STRINGIFY2(x)
21
22 /* Avoid mod by zero */
23 static unsigned int total_keys = 1;
24
25 #define DEBUG_DEPS 1
26
27 /* Traversals block transactions in the current implementation. */
28 #define TRAVERSALS_TAKE_TRANSACTION_LOCK 1
29
30 struct pipe {
31         int fd[2];
32 };
33 static struct pipe *pipes;
34
35 static void __attribute__((noreturn)) fail(const char *filename,
36                                            unsigned int line,
37                                            const char *fmt, ...)
38 {
39         va_list ap;
40
41         va_start(ap, fmt);
42         fprintf(stderr, "%s:%u: FAIL: ", filename, line);
43         vfprintf(stderr, fmt, ap);
44         fprintf(stderr, "\n");
45         va_end(ap);
46         exit(1);
47 }
48         
49 /* Try or die. */
50 #define try(expr, expect)                                               \
51         do {                                                            \
52                 int ret = (expr);                                       \
53                 if (ret != (expect))                                    \
54                         fail(filename[file], i+1,                       \
55                              STRINGIFY(expr) "= %i", ret);              \
56         } while (0)
57
58 /* Try or imitate results. */
59 #define unreliable(expr, expect, force, undo)                           \
60         do {                                                            \
61                 int ret = expr;                                         \
62                 if (ret != expect) {                                    \
63                         fprintf(stderr, "%s:%u: %s gave %i not %i",     \
64                                 filename[file], i+1, STRINGIFY(expr),   \
65                                 ret, expect);                           \
66                         if (expect == 0)                                \
67                                 force;                                  \
68                         else                                            \
69                                 undo;                                   \
70                 }                                                       \
71         } while (0)
72
73 static bool key_eq(TDB_DATA a, TDB_DATA b)
74 {
75         if (a.dsize != b.dsize)
76                 return false;
77         return memcmp(a.dptr, b.dptr, a.dsize) == 0;
78 }
79
80 /* This is based on the hash algorithm from gdbm */
81 static unsigned int hash_key(TDB_DATA *key)
82 {
83         uint32_t value; /* Used to compute the hash value.  */
84         uint32_t   i;   /* Used to cycle through random values. */
85
86         /* Set the initial value from the key size. */
87         for (value = 0x238F13AF ^ key->dsize, i=0; i < key->dsize; i++)
88                 value = (value + (key->dptr[i] << (i*5 % 24)));
89
90         return (1103515243 * value + 12345);  
91 }
92
93 enum op_type {
94         OP_TDB_LOCKALL,
95         OP_TDB_LOCKALL_MARK,
96         OP_TDB_LOCKALL_UNMARK,
97         OP_TDB_LOCKALL_NONBLOCK,
98         OP_TDB_UNLOCKALL,
99         OP_TDB_LOCKALL_READ,
100         OP_TDB_LOCKALL_READ_NONBLOCK,
101         OP_TDB_UNLOCKALL_READ,
102         OP_TDB_CHAINLOCK,
103         OP_TDB_CHAINLOCK_NONBLOCK,
104         OP_TDB_CHAINLOCK_MARK,
105         OP_TDB_CHAINLOCK_UNMARK,
106         OP_TDB_CHAINUNLOCK,
107         OP_TDB_CHAINLOCK_READ,
108         OP_TDB_CHAINUNLOCK_READ,
109         OP_TDB_PARSE_RECORD,
110         OP_TDB_EXISTS,
111         OP_TDB_STORE,
112         OP_TDB_APPEND,
113         OP_TDB_GET_SEQNUM,
114         OP_TDB_WIPE_ALL,
115         OP_TDB_TRANSACTION_START,
116         OP_TDB_TRANSACTION_CANCEL,
117         OP_TDB_TRANSACTION_COMMIT,
118         OP_TDB_TRAVERSE_READ_START,
119         OP_TDB_TRAVERSE_START,
120         OP_TDB_TRAVERSE_END,
121         OP_TDB_TRAVERSE,
122         OP_TDB_FIRSTKEY,
123         OP_TDB_NEXTKEY,
124         OP_TDB_FETCH,
125         OP_TDB_DELETE,
126 };
127
128 struct op {
129         unsigned int serial;
130         enum op_type op;
131         TDB_DATA key;
132         TDB_DATA data;
133         int ret;
134
135         /* Who is waiting for us? */
136         struct list_head post;
137         /* What are we waiting for? */
138         struct list_head pre;
139
140         /* If I'm part of a group (traverse/transaction) where is
141          * start?  (Otherwise, 0) */
142         unsigned int group_start;
143
144         union {
145                 int flag; /* open and store */
146                 struct {  /* append */
147                         TDB_DATA pre;
148                         TDB_DATA post;
149                 } append;
150                 unsigned int group_len; /* transaction/traverse start */
151         };
152 };
153
154 static unsigned char hex_char(const char *filename, unsigned int line, char c)
155 {
156         c = toupper(c);
157         if (c >= 'A' && c <= 'F')
158                 return c - 'A' + 10;
159         if (c >= '0' && c <= '9')
160                 return c - '0';
161         fail(filename, line, "invalid hex character '%c'", c);
162 }
163
164 /* TDB data is <size>:<%02x>* */
165 static TDB_DATA make_tdb_data(const void *ctx,
166                               const char *filename, unsigned int line,
167                               const char *word)
168 {
169         TDB_DATA data;
170         unsigned int i;
171         const char *p;
172
173         if (streq(word, "NULL"))
174                 return tdb_null;
175
176         data.dsize = atoi(word);
177         data.dptr = talloc_array(ctx, unsigned char, data.dsize);
178         p = strchr(word, ':');
179         if (!p)
180                 fail(filename, line, "invalid tdb data '%s'", word);
181         p++;
182         for (i = 0; i < data.dsize; i++)
183                 data.dptr[i] = hex_char(filename, line, p[i*2])*16
184                         + hex_char(filename, line, p[i*2+1]);
185
186         return data;
187 }
188
189 static void add_op(const char *filename, struct op **op, unsigned int i,
190                    unsigned int serial, enum op_type type)
191 {
192         struct op *new;
193         *op = talloc_realloc(NULL, *op, struct op, i+1);
194         new = (*op) + i;
195         new->op = type;
196         new->serial = serial;
197         new->ret = 0;
198         new->group_start = 0;
199 }
200
201 static void op_add_nothing(const char *filename,
202                            struct op op[], unsigned int op_num, char *words[])
203 {
204         if (words[2])
205                 fail(filename, op_num+1, "Expected no arguments");
206         op[op_num].key = tdb_null;
207 }
208
209 static void op_add_key(const char *filename,
210                        struct op op[], unsigned int op_num, char *words[])
211 {
212         if (words[2] == NULL || words[3])
213                 fail(filename, op_num+1, "Expected just a key");
214
215         op[op_num].key = make_tdb_data(op, filename, op_num+1, words[2]);
216         if (op[op_num].op != OP_TDB_TRAVERSE)
217                 total_keys++;
218 }
219
220 static void op_add_key_ret(const char *filename,
221                            struct op op[], unsigned int op_num, char *words[])
222 {
223         if (!words[2] || !words[3] || !words[4] || words[5]
224             || !streq(words[3], "="))
225                 fail(filename, op_num+1, "Expected <key> = <ret>");
226         op[op_num].ret = atoi(words[4]);
227         op[op_num].key = make_tdb_data(op, filename, op_num+1, words[2]);
228         /* May only be a unique key if it fails */
229         if (op[op_num].ret != 0)
230                 total_keys++;
231 }
232
233 static void op_add_key_data(const char *filename,
234                             struct op op[], unsigned int op_num, char *words[])
235 {
236         if (!words[2] || !words[3] || !words[4] || words[5]
237             || !streq(words[3], "="))
238                 fail(filename, op_num+1, "Expected <key> = <data>");
239         op[op_num].key = make_tdb_data(op, filename, op_num+1, words[2]);
240         op[op_num].data = make_tdb_data(op, filename, op_num+1, words[4]);
241         /* May only be a unique key if it fails */
242         if (!op[op_num].data.dptr)
243                 total_keys++;
244 }
245
246 /* <serial> tdb_store <rec> <rec> <flag> = <ret> */
247 static void op_add_store(const char *filename,
248                          struct op op[], unsigned int op_num, char *words[])
249 {
250         if (!words[2] || !words[3] || !words[4] || !words[5] || !words[6]
251             || words[7] || !streq(words[5], "="))
252                 fail(filename, op_num+1, "Expect <key> <data> <flag> = <ret>");
253
254         op[op_num].flag = strtoul(words[4], NULL, 0);
255         op[op_num].ret = atoi(words[6]);
256         op[op_num].key = make_tdb_data(op, filename, op_num+1, words[2]);
257         op[op_num].data = make_tdb_data(op, filename, op_num+1, words[3]);
258         total_keys++;
259 }
260
261 /* <serial> tdb_append <rec> <rec> = <rec> */
262 static void op_add_append(const char *filename,
263                           struct op op[], unsigned int op_num, char *words[])
264 {
265         if (!words[2] || !words[3] || !words[4] || !words[5] || words[6]
266             || !streq(words[4], "="))
267                 fail(filename, op_num+1, "Expect <key> <data> = <rec>");
268
269         op[op_num].key = make_tdb_data(op, filename, op_num+1, words[2]);
270         op[op_num].data = make_tdb_data(op, filename, op_num+1, words[3]);
271
272         op[op_num].append.post
273                 = make_tdb_data(op, filename, op_num+1, words[5]);
274
275         /* By subtraction, figure out what previous data was. */
276         op[op_num].append.pre.dptr = op[op_num].append.post.dptr;
277         op[op_num].append.pre.dsize
278                 = op[op_num].append.post.dsize - op[op_num].data.dsize;
279         total_keys++;
280 }
281
282 /* <serial> tdb_get_seqnum = <ret> */
283 static void op_add_seqnum(const char *filename,
284                           struct op op[], unsigned int op_num, char *words[])
285 {
286         if (!words[2] || !words[3] || words[4] || !streq(words[2], "="))
287                 fail(filename, op_num+1, "Expect = <ret>");
288
289         op[op_num].key = tdb_null;
290         op[op_num].ret = atoi(words[3]);
291 }
292
293 static void op_add_traverse(const char *filename,
294                             struct op op[], unsigned int op_num, char *words[])
295 {
296         if (words[2])
297                 fail(filename, op_num+1, "Expect no arguments");
298
299         op[op_num].key = tdb_null;
300         op[op_num].group_len = 0;
301 }
302
303 static void op_add_transaction(const char *filename, struct op op[],
304                                unsigned int op_num, char *words[])
305 {
306         if (words[2])
307                 fail(filename, op_num+1, "Expect no arguments");
308
309         op[op_num].key = tdb_null;
310         op[op_num].group_len = 0;
311 }
312
313 static void op_analyze_transaction(const char *filename,
314                                    struct op op[], unsigned int op_num,
315                                    char *words[])
316 {
317         int i, start;
318
319         op[op_num].key = tdb_null;
320
321         if (words[2])
322                 fail(filename, op_num+1, "Expect no arguments");
323
324         for (i = op_num-1; i >= 0; i--) {
325                 if (op[i].op == OP_TDB_TRANSACTION_START && !op[i].group_len)
326                         break;
327         }
328
329         if (i < 0)
330                 fail(filename, op_num+1, "no transaction start found");
331
332         start = i;
333         op[start].group_len = op_num - i;
334
335         /* This rolls in nested transactions.  I think that's right. */
336         for (i++; i <= op_num; i++)
337                 op[i].group_start = start;
338 }
339
340 struct traverse_hash {
341         TDB_DATA key;
342         unsigned int index;
343 };
344
345 static void op_analyze_traverse(const char *filename,
346                                 struct op op[], unsigned int op_num,
347                                 char *words[])
348 {
349         int i, start;
350
351         op[op_num].key = tdb_null;
352
353         /* = %u means traverse function terminated. */
354         if (words[2]) {
355                 if (!streq(words[2], "=") || !words[3] || words[4])
356                         fail(filename, op_num+1, "expect = <num>");
357                 op[op_num].ret = atoi(words[3]);
358         } else
359                 op[op_num].ret = 0;
360
361         for (i = op_num-1; i >= 0; i--) {
362                 if (op[i].op != OP_TDB_TRAVERSE_READ_START
363                     && op[i].op != OP_TDB_TRAVERSE_START)
364                         continue;
365                 if (op[i].group_len)
366                         continue;
367                 break;
368         }
369
370         if (i < 0)
371                 fail(filename, op_num+1, "no traversal start found");
372
373         start = i;
374         op[start].group_len = op_num - start;
375
376         for (i = start; i <= op_num; i++)
377                 op[i].group_start = start;
378 }
379
380 /* Keep -Wmissing-declarations happy: */
381 const struct op_table *
382 find_keyword (register const char *str, register unsigned int len);
383
384 #include "keywords.c"
385
386 struct depend {
387         /* We can have more than one */
388         struct list_node pre_list;
389         struct list_node post_list;
390         unsigned int needs_file;
391         unsigned int needs_opnum;
392         unsigned int satisfies_file;
393         unsigned int satisfies_opnum;
394 };
395
396 static void check_deps(const char *filename, struct op op[], unsigned int num)
397 {
398 #ifdef DEBUG_DEPS
399         unsigned int i;
400
401         for (i = 1; i < num; i++)
402                 if (!list_empty(&op[i].pre))
403                         fail(filename, i+1, "Still has dependencies");
404 #endif
405 }
406
407 static void dump_pre(char *filename[], struct op *op[],
408                      unsigned int file, unsigned int i)
409 {
410         struct depend *dep;
411
412         printf("%s:%u (%u) still waiting for:\n", filename[file], i+1,
413                 op[file][i].serial);
414         list_for_each(&op[file][i].pre, dep, pre_list)
415                 printf("    %s:%u (%u)\n",
416                        filename[dep->satisfies_file], dep->satisfies_opnum+1,
417                        op[dep->satisfies_file][dep->satisfies_opnum].serial);
418         check_deps(filename[file], op[file], i);
419 }
420
421 /* We simply read/write pointers, since we all are children. */
422 static void do_pre(struct tdb_context *tdb,
423                    char *filename[], struct op *op[],
424                    unsigned int file, int pre_fd, unsigned int i)
425 {
426         while (!list_empty(&op[file][i].pre)) {
427                 struct depend *dep;
428
429 #if DEBUG_DEPS
430                 printf("%s:%u:waiting for pre\n", filename[file], i+1);
431                 fflush(stdout);
432 #endif
433                 alarm(10);
434                 while (read(pre_fd, &dep, sizeof(dep)) != sizeof(dep)) {
435                         if (errno == EINTR) {
436                                 dump_pre(filename, op, file, i);
437                                 exit(1);
438                         } else
439                                 errx(1, "Reading from pipe");
440                 }
441                 alarm(0);
442
443 #if DEBUG_DEPS
444                 printf("%s:%u:got pre %u from %s:%u\n", filename[file], i+1,
445                        dep->needs_opnum+1, filename[dep->satisfies_file],
446                        dep->satisfies_opnum+1);
447                 fflush(stdout);
448 #endif
449                 /* This could be any op, not just this one. */
450                 talloc_free(dep);
451         }
452 }
453
454 static void do_post(char *filename[], struct op *op[],
455                     unsigned int file, unsigned int i)
456 {
457         struct depend *dep;
458
459         list_for_each(&op[file][i].post, dep, post_list) {
460 #if DEBUG_DEPS
461                 printf("%s:%u:sending to file %s:%u\n", filename[file], i+1,
462                        filename[dep->needs_file], dep->needs_opnum+1);
463 #endif
464                 if (write(pipes[dep->needs_file].fd[1], &dep, sizeof(dep))
465                     != sizeof(dep))
466                         err(1, "%s:%u failed to tell file %s",
467                             filename[file], i+1, filename[dep->needs_file]);
468         }
469 }
470
471 static int get_len(TDB_DATA key, TDB_DATA data, void *private_data)
472 {
473         return data.dsize;
474 }
475
476 static unsigned run_ops(struct tdb_context *tdb,
477                         int pre_fd,
478                         char *filename[],
479                         struct op *op[],
480                         unsigned int file,
481                         unsigned int start, unsigned int stop);
482
483 struct traverse_info {
484         struct op **op;
485         char **filename;
486         unsigned file;
487         int pre_fd;
488         unsigned int start;
489         unsigned int i;
490 };
491
492 /* More complex.  Just do whatever's they did at the n'th entry. */
493 static int nontrivial_traverse(struct tdb_context *tdb,
494                                TDB_DATA key, TDB_DATA data,
495                                void *_tinfo)
496 {
497         struct traverse_info *tinfo = _tinfo;
498         unsigned int trav_len = tinfo->op[tinfo->file][tinfo->start].group_len;
499
500         if (tinfo->i == tinfo->start + trav_len) {
501                 /* This can happen if traverse expects to be empty. */
502                 if (trav_len == 1)
503                         return 1;
504                 fail(tinfo->filename[tinfo->file], tinfo->start + 1,
505                      "traverse did not terminate");
506         }
507
508         if (tinfo->op[tinfo->file][tinfo->i].op != OP_TDB_TRAVERSE)
509                 fail(tinfo->filename[tinfo->file], tinfo->start + 1,
510                      "%s:%u:traverse terminated early");
511
512         /* Run any normal ops. */
513         tinfo->i = run_ops(tdb, tinfo->pre_fd, tinfo->filename, tinfo->op,
514                            tinfo->file, tinfo->i+1, tinfo->start + trav_len);
515
516         if (tinfo->i == tinfo->start + trav_len)
517                 return 1;
518
519         return 0;
520 }
521
522 static unsigned op_traverse(struct tdb_context *tdb,
523                             int pre_fd,
524                             char *filename[],
525                             unsigned int file,
526                             int (*traversefn)(struct tdb_context *,
527                                               tdb_traverse_func, void *),
528                             struct op *op[],
529                             unsigned int start)
530 {
531         struct traverse_info tinfo = { op, filename, file, pre_fd,
532                                        start, start+1 };
533
534         traversefn(tdb, nontrivial_traverse, &tinfo);
535
536         /* Traversing in wrong order can have strange effects: eg. if
537          * original traverse went A (delete A), B, we might do B
538          * (delete A).  So if we have ops left over, we do it now. */
539         while (tinfo.i != start + op[file][start].group_len) {
540                 if (op[file][tinfo.i].op == OP_TDB_TRAVERSE)
541                         tinfo.i++;
542                 else
543                         tinfo.i = run_ops(tdb, pre_fd, filename, op, file,
544                                           tinfo.i,
545                                           start + op[file][start].group_len);
546         }
547
548         return tinfo.i;
549 }
550
551 static void break_out(int sig)
552 {
553 }
554
555 static __attribute__((noinline))
556 unsigned run_ops(struct tdb_context *tdb,
557                  int pre_fd,
558                  char *filename[],
559                  struct op *op[],
560                  unsigned int file,
561                  unsigned int start, unsigned int stop)
562 {
563         unsigned int i;
564         struct sigaction sa;
565
566         sa.sa_handler = break_out;
567         sa.sa_flags = 0;
568
569         sigaction(SIGALRM, &sa, NULL);
570         for (i = start; i < stop; i++) {
571                 do_pre(tdb, filename, op, file, pre_fd, i);
572
573                 switch (op[file][i].op) {
574                 case OP_TDB_LOCKALL:
575                         try(tdb_lockall(tdb), op[file][i].ret);
576                         break;
577                 case OP_TDB_LOCKALL_MARK:
578                         try(tdb_lockall_mark(tdb), op[file][i].ret);
579                         break;
580                 case OP_TDB_LOCKALL_UNMARK:
581                         try(tdb_lockall_unmark(tdb), op[file][i].ret);
582                         break;
583                 case OP_TDB_LOCKALL_NONBLOCK:
584                         unreliable(tdb_lockall_nonblock(tdb), op[file][i].ret,
585                                    tdb_lockall(tdb), tdb_unlockall(tdb));
586                         break;
587                 case OP_TDB_UNLOCKALL:
588                         try(tdb_unlockall(tdb), op[file][i].ret);
589                         break;
590                 case OP_TDB_LOCKALL_READ:
591                         try(tdb_lockall_read(tdb), op[file][i].ret);
592                         break;
593                 case OP_TDB_LOCKALL_READ_NONBLOCK:
594                         unreliable(tdb_lockall_read_nonblock(tdb),
595                                    op[file][i].ret,
596                                    tdb_lockall_read(tdb),
597                                    tdb_unlockall_read(tdb));
598                         break;
599                 case OP_TDB_UNLOCKALL_READ:
600                         try(tdb_unlockall_read(tdb), op[file][i].ret);
601                         break;
602                 case OP_TDB_CHAINLOCK:
603                         try(tdb_chainlock(tdb, op[file][i].key),
604                             op[file][i].ret);
605                         break;
606                 case OP_TDB_CHAINLOCK_NONBLOCK:
607                         unreliable(tdb_chainlock_nonblock(tdb, op[file][i].key),
608                                    op[file][i].ret,
609                                    tdb_chainlock(tdb, op[file][i].key),
610                                    tdb_chainunlock(tdb, op[file][i].key));
611                         break;
612                 case OP_TDB_CHAINLOCK_MARK:
613                         try(tdb_chainlock_mark(tdb, op[file][i].key),
614                             op[file][i].ret);
615                         break;
616                 case OP_TDB_CHAINLOCK_UNMARK:
617                         try(tdb_chainlock_unmark(tdb, op[file][i].key),
618                             op[file][i].ret);
619                         break;
620                 case OP_TDB_CHAINUNLOCK:
621                         try(tdb_chainunlock(tdb, op[file][i].key),
622                             op[file][i].ret);
623                         break;
624                 case OP_TDB_CHAINLOCK_READ:
625                         try(tdb_chainlock_read(tdb, op[file][i].key),
626                             op[file][i].ret);
627                         break;
628                 case OP_TDB_CHAINUNLOCK_READ:
629                         try(tdb_chainunlock_read(tdb, op[file][i].key),
630                             op[file][i].ret);
631                         break;
632                 case OP_TDB_PARSE_RECORD:
633                         try(tdb_parse_record(tdb, op[file][i].key, get_len,
634                                              NULL),
635                             op[file][i].ret);
636                         break;
637                 case OP_TDB_EXISTS:
638                         try(tdb_exists(tdb, op[file][i].key), op[file][i].ret);
639                         break;
640                 case OP_TDB_STORE:
641                         try(tdb_store(tdb, op[file][i].key, op[file][i].data,
642                                       op[file][i].flag),
643                             op[file][i].ret);
644                         break;
645                 case OP_TDB_APPEND:
646                         try(tdb_append(tdb, op[file][i].key, op[file][i].data),
647                             op[file][i].ret);
648                         break;
649                 case OP_TDB_GET_SEQNUM:
650                         try(tdb_get_seqnum(tdb), op[file][i].ret);
651                         break;
652                 case OP_TDB_WIPE_ALL:
653                         try(tdb_wipe_all(tdb), op[file][i].ret);
654                         break;
655                 case OP_TDB_TRANSACTION_START:
656                         try(tdb_transaction_start(tdb), op[file][i].ret);
657                         break;
658                 case OP_TDB_TRANSACTION_CANCEL:
659                         try(tdb_transaction_cancel(tdb), op[file][i].ret);
660                         break;
661                 case OP_TDB_TRANSACTION_COMMIT:
662                         try(tdb_transaction_commit(tdb), op[file][i].ret);
663                         break;
664                 case OP_TDB_TRAVERSE_READ_START:
665                         i = op_traverse(tdb, pre_fd, filename, file,
666                                         tdb_traverse_read, op, i);
667                         break;
668                 case OP_TDB_TRAVERSE_START:
669                         i = op_traverse(tdb, pre_fd, filename, file,
670                                         tdb_traverse, op, i);
671                         break;
672                 case OP_TDB_TRAVERSE:
673                         /* Terminate: we're in a traverse, and we've
674                          * done our ops. */
675                         return i;
676                 case OP_TDB_TRAVERSE_END:
677                         fail(filename[file], i+1, "unexpected end traverse");
678                 /* FIXME: These must be treated like traverse. */
679                 case OP_TDB_FIRSTKEY:
680                         if (!key_eq(tdb_firstkey(tdb), op[file][i].data))
681                                 fail(filename[file], i+1, "bad firstkey");
682                         break;
683                 case OP_TDB_NEXTKEY:
684                         if (!key_eq(tdb_nextkey(tdb, op[file][i].key),
685                                     op[file][i].data))
686                                 fail(filename[file], i+1, "bad nextkey");
687                         break;
688                 case OP_TDB_FETCH: {
689                         TDB_DATA f = tdb_fetch(tdb, op[file][i].key);
690                         if (!key_eq(f, op[file][i].data))
691                                 fail(filename[file], i+1, "bad fetch %u",
692                                      f.dsize);
693                         break;
694                 }
695                 case OP_TDB_DELETE:
696                         try(tdb_delete(tdb, op[file][i].key), op[file][i].ret);
697                         break;
698                 }
699                 do_post(filename, op, file, i);
700         }
701         return i;
702 }
703
704 static struct op *load_tracefile(const char *filename, unsigned int *num,
705                                  unsigned int *hashsize,
706                                  unsigned int *tdb_flags,
707                                  unsigned int *open_flags)
708 {
709         unsigned int i;
710         struct op *op = talloc_array(NULL, struct op, 1);
711         char **words;
712         char **lines;
713         char *file;
714
715         file = grab_file(NULL, filename, NULL);
716         if (!file)
717                 err(1, "Reading %s", filename);
718
719         lines = strsplit(file, file, "\n", NULL);
720         if (!lines[0])
721                 errx(1, "%s is empty", filename);
722
723         words = strsplit(lines, lines[0], " ", NULL);
724         if (!streq(words[1], "tdb_open"))
725                 fail(filename, 1, "does not start with tdb_open");
726
727         *hashsize = atoi(words[2]);
728         *tdb_flags = strtoul(words[3], NULL, 0);
729         *open_flags = strtoul(words[4], NULL, 0);
730
731         for (i = 1; lines[i]; i++) {
732                 const struct op_table *opt;
733
734                 words = strsplit(lines, lines[i], " ", NULL);
735                 if (!words[0] || !words[1])
736                         fail(filename, i+1, "Expected serial number and op");
737                
738                 opt = find_keyword(words[1], strlen(words[1]));
739                 if (!opt) {
740                         if (streq(words[1], "tdb_close")) {
741                                 if (lines[i+1])
742                                         fail(filename, i+2,
743                                              "lines after tdb_close");
744                                 *num = i;
745                                 talloc_free(lines);
746                                 return op;
747                         }
748                         fail(filename, i+1, "Unknown operation '%s'", words[1]);
749                 }
750
751                 add_op(filename, &op, i, atoi(words[0]), opt->type);
752                 opt->enhance_op(filename, op, i, words);
753         }
754
755         fprintf(stderr, "%s:%u:last operation is not tdb_close: incomplete?",
756               filename, i);
757         talloc_free(lines);
758         *num = i - 1;
759         return op;
760 }
761
762 /* We remember all the keys we've ever seen, and who has them. */
763 struct key_user {
764         unsigned int file;
765         unsigned int op_num;
766 };
767
768 struct keyinfo {
769         TDB_DATA key;
770         unsigned int num_users;
771         struct key_user *user;
772 };
773
774 static const TDB_DATA must_not_exist;
775 static const TDB_DATA must_exist;
776 static const TDB_DATA not_exists_or_empty;
777
778 /* NULL means doesn't care if it exists or not, &must_exist means
779  * it must exist but we don't care what, &must_not_exist means it must
780  * not exist, otherwise the data it needs. */
781 static const TDB_DATA *needs(const struct op *op)
782 {
783         switch (op->op) {
784         /* FIXME: Pull forward deps, since we can deadlock */
785         case OP_TDB_CHAINLOCK:
786         case OP_TDB_CHAINLOCK_NONBLOCK:
787         case OP_TDB_CHAINLOCK_MARK:
788         case OP_TDB_CHAINLOCK_UNMARK:
789         case OP_TDB_CHAINUNLOCK:
790         case OP_TDB_CHAINLOCK_READ:
791         case OP_TDB_CHAINUNLOCK_READ:
792                 return NULL;
793
794         case OP_TDB_APPEND:
795                 if (op->append.pre.dsize == 0)
796                         return &not_exists_or_empty;
797                 return &op->append.pre;
798
799         case OP_TDB_STORE:
800                 if (op->flag == TDB_INSERT) {
801                         if (op->ret < 0)
802                                 return &must_exist;
803                         else
804                                 return &must_not_exist;
805                 } else if (op->flag == TDB_MODIFY) {
806                         if (op->ret < 0)
807                                 return &must_not_exist;
808                         else
809                                 return &must_exist;
810                 }
811                 /* No flags?  Don't care */
812                 return NULL;
813
814         case OP_TDB_EXISTS:
815                 if (op->ret == 1)
816                         return &must_exist;
817                 else
818                         return &must_not_exist;
819
820         case OP_TDB_PARSE_RECORD:
821                 if (op->ret < 0)
822                         return &must_not_exist;
823                 return &must_exist;
824
825         /* FIXME: handle these. */
826         case OP_TDB_WIPE_ALL:
827         case OP_TDB_FIRSTKEY:
828         case OP_TDB_NEXTKEY:
829         case OP_TDB_GET_SEQNUM:
830         case OP_TDB_TRAVERSE:
831         case OP_TDB_TRANSACTION_COMMIT:
832         case OP_TDB_TRANSACTION_CANCEL:
833         case OP_TDB_TRANSACTION_START:
834                 return NULL;
835
836         case OP_TDB_FETCH:
837                 if (!op->data.dptr)
838                         return &must_not_exist;
839                 return &op->data;
840
841         case OP_TDB_DELETE:
842                 if (op->ret < 0)
843                         return &must_not_exist;
844                 return &must_exist;
845
846         default:
847                 errx(1, "Unexpected op %i", op->op);
848         }
849         
850 }
851
852 /* What's the data after this op?  pre if nothing changed. */
853 static const TDB_DATA *gives(const struct op *op, const TDB_DATA *pre)
854 {
855         /* Failed ops don't change state of db. */
856         if (op->ret < 0)
857                 return pre;
858
859         if (op->op == OP_TDB_DELETE || op->op == OP_TDB_WIPE_ALL)
860                 return &tdb_null;
861
862         if (op->op == OP_TDB_APPEND)
863                 return &op->append.post;
864
865         if (op->op == OP_TDB_STORE)
866                 return &op->data;
867
868         return pre;
869 }
870
871 static struct keyinfo *hash_ops(struct op *op[], unsigned int num_ops[],
872                                 unsigned int num)
873 {
874         unsigned int i, j, h;
875         struct keyinfo *hash;
876
877         hash = talloc_zero_array(op[0], struct keyinfo, total_keys*2);
878         for (i = 0; i < num; i++) {
879                 for (j = 1; j < num_ops[i]; j++) {
880                         /* We can't do this on allocation, due to realloc. */
881                         list_head_init(&op[i][j].post);
882                         list_head_init(&op[i][j].pre);
883
884                         if (!op[i][j].key.dptr)
885                                 continue;
886
887                         /* We don't wait for traverse keys */
888                         /* FIXME: We should, for trivial traversals. */
889                         if (op[i][j].op == OP_TDB_TRAVERSE)
890                                 continue;
891
892                         h = hash_key(&op[i][j].key) % (total_keys * 2);
893                         while (!key_eq(hash[h].key, op[i][j].key)) {
894                                 if (!hash[h].key.dptr) {
895                                         hash[h].key = op[i][j].key;
896                                         break;
897                                 }
898                                 h = (h + 1) % (total_keys * 2);
899                         }
900                         /* Might as well save some memory if we can. */
901                         if (op[i][j].key.dptr != hash[h].key.dptr) {
902                                 talloc_free(op[i][j].key.dptr);
903                                 op[i][j].key.dptr = hash[h].key.dptr;
904                         }
905                         hash[h].user = talloc_realloc(hash, hash[h].user,
906                                                      struct key_user,
907                                                      hash[h].num_users+1);
908                         hash[h].user[hash[h].num_users].op_num = j;
909                         hash[h].user[hash[h].num_users].file = i;
910                         hash[h].num_users++;
911                 }
912         }
913
914         return hash;
915 }
916
917 static bool satisfies(const TDB_DATA *data, const TDB_DATA *need)
918 {
919         /* Don't need anything?  Cool. */
920         if (!need)
921                 return true;
922
923         /* This should be tdb_null or a real value. */
924         assert(data != &must_exist);
925         assert(data != &must_not_exist);
926         assert(data != &not_exists_or_empty);
927
928         /* must_not_exist == must_not_exist, must_exist == must_exist, or
929            not_exists_or_empty == not_exists_or_empty. */
930         if (data->dsize == need->dsize && data->dptr == need->dptr)
931                 return true;
932
933         /* Must not exist?  data must not exist. */
934         if (need == &must_not_exist)
935                 return data->dptr == NULL;
936
937         /* Must exist? */
938         if (need == &must_exist)
939                 return data->dptr != NULL;
940
941         /* Either noexist or empty. */
942         if (need == &not_exists_or_empty)
943                 return data->dsize == 0;
944
945         /* Needs something specific. */
946         return key_eq(*data, *need);
947 }
948
949 static void move_to_front(struct key_user res[], unsigned int elem)
950 {
951         if (elem != 0) {
952                 struct key_user tmp = res[elem];
953                 memmove(res + 1, res, elem*sizeof(res[0]));
954                 res[0] = tmp;
955         }
956 }
957
958 static void restore_to_pos(struct key_user res[], unsigned int elem)
959 {
960         if (elem != 0) {
961                 struct key_user tmp = res[0];
962                 memmove(res, res + 1, elem*sizeof(res[0]));
963                 res[elem] = tmp;
964         }
965 }
966
967 static bool sort_deps(char *filename[], struct op *op[],
968                       struct key_user res[], unsigned num,
969                       const TDB_DATA *data, unsigned num_files)
970 {
971         unsigned int i, files_done;
972         struct op *this_op;
973         bool done[num_files];
974
975         /* Nothing left?  We're sorted. */
976         if (num == 0)
977                 return true;
978
979         memset(done, 0, sizeof(done));
980
981         /* Since ops within a trace file are ordered, we just need to figure
982          * out which file to try next.  Since we don't take into account
983          * inter-key relationships (which exist by virtue of trace file order),
984          * we minimize the chance of harm by trying to keep in serial order. */
985         for (files_done = 0, i = 0; i < num && files_done < num_files; i++) {
986                 if (done[res[i].file])
987                         continue;
988
989                 this_op = &op[res[i].file][res[i].op_num];
990                 /* Is what we have good enough for this op? */
991                 if (satisfies(data, needs(this_op))) {
992                         move_to_front(res, i);
993                         if (sort_deps(filename, op, res+1, num-1,
994                                       gives(this_op, data), num_files))
995                                 return true;
996                         restore_to_pos(res, i);
997                 }
998                 done[res[i].file] = true;
999                 files_done++;
1000         }
1001
1002         /* No combination worked. */
1003         return false;
1004 }
1005
1006 static void check_dep_sorting(struct key_user user[], unsigned num_users,
1007                               unsigned num_files)
1008 {
1009 #if DEBUG_DEPS
1010         unsigned int i;
1011         unsigned minima[num_files];
1012
1013         memset(minima, 0, sizeof(minima));
1014         for (i = 0; i < num_users; i++) {
1015                 assert(minima[user[i].file] < user[i].op_num);
1016                 minima[user[i].file] = user[i].op_num;
1017         }
1018 #endif
1019 }
1020
1021 /* All these ops have the same serial number.  Which comes first?
1022  *
1023  * This can happen both because read ops or failed write ops don't
1024  * change serial number, and also due to race since we access the
1025  * number unlocked (the race can cause less detectable ordering problems,
1026  * in which case we'll deadlock and report: fix manually in that case).
1027  */
1028 static void figure_deps(char *filename[], struct op *op[],
1029                         struct key_user user[], unsigned num_users,
1030                         unsigned num_files)
1031 {
1032         /* We assume database starts empty. */
1033         const struct TDB_DATA *data = &tdb_null;
1034
1035         if (!sort_deps(filename, op, user, num_users, data, num_files))
1036                 fail(filename[user[0].file], user[0].op_num+1,
1037                      "Could not resolve inter-dependencies");
1038
1039         check_dep_sorting(user, num_users, num_files);
1040 }
1041
1042 static void sort_ops(struct keyinfo hash[], char *filename[], struct op *op[],
1043                      unsigned int num)
1044 {
1045         unsigned int h;
1046
1047         /* Gcc nexted function extension.  How cool is this? */
1048         int compare_serial(const void *_a, const void *_b)
1049         {
1050                 const struct key_user *a = _a, *b = _b;
1051
1052                 /* First, maintain order within any trace file. */
1053                 if (a->file == b->file)
1054                         return a->op_num - b->op_num;
1055
1056                 /* Otherwise, arrange by serial order. */
1057                 return op[a->file][a->op_num].serial
1058                         - op[b->file][b->op_num].serial;
1059         }
1060
1061         /* Now sort into serial order. */
1062         for (h = 0; h < total_keys * 2; h++) {
1063                 struct key_user *user = hash[h].user;
1064
1065                 qsort(user, hash[h].num_users, sizeof(user[0]), compare_serial);
1066                 figure_deps(filename, op, user, hash[h].num_users, num);
1067         }
1068 }
1069
1070 static int destroy_depend(struct depend *dep)
1071 {
1072         list_del(&dep->pre_list);
1073         list_del(&dep->post_list);
1074         return 0;
1075 }
1076
1077 static void add_dependency(void *ctx,
1078                            struct op *op[],
1079                            char *filename[],
1080                            unsigned int needs_file,
1081                            unsigned int needs_opnum,
1082                            unsigned int satisfies_file,
1083                            unsigned int satisfies_opnum)
1084 {
1085         struct depend *dep;
1086         unsigned int needs_start, sat_start;
1087
1088         /* We don't depend on ourselves. */
1089         if (needs_file == satisfies_file) {
1090                 assert(satisfies_opnum < needs_opnum);
1091                 return;
1092         }
1093
1094 #if DEBUG_DEPS
1095         printf("%s:%u: depends on %s:%u\n",
1096                filename[needs_file], needs_opnum+1,
1097                filename[satisfies_file], satisfies_opnum+1);
1098 #endif
1099
1100         needs_start = op[needs_file][needs_opnum].group_start;
1101         sat_start = op[satisfies_file][satisfies_opnum].group_start;
1102
1103         /* If needs is in a transaction, we need it before start. */
1104         if (needs_start) {
1105                 switch (op[needs_file][needs_start].op) {
1106                 case OP_TDB_TRANSACTION_START:
1107                         needs_opnum = needs_start;
1108 #ifdef DEBUG_DEPS
1109                         printf("  -> Back to %u\n", needs_start+1);
1110                         fflush(stdout);
1111 #endif
1112                         break;
1113                 default:
1114                         break;
1115                 }
1116         }
1117
1118         /* If satisfies is in a transaction, we wait until after commit. */
1119         /* FIXME: If transaction is cancelled, don't need dependency. */
1120         if (sat_start) {
1121                 if (op[satisfies_file][sat_start].op
1122                     == OP_TDB_TRANSACTION_START) {
1123                         satisfies_opnum = sat_start
1124                                 + op[satisfies_file][sat_start].group_len;
1125 #ifdef DEBUG_DEPS
1126                         printf("  -> Depends on %u\n", satisfies_opnum+1);
1127                         fflush(stdout);
1128 #endif
1129                 }
1130         }
1131
1132         assert(op[needs_file][needs_opnum].op != OP_TDB_TRAVERSE);
1133         assert(op[satisfies_file][satisfies_opnum].op != OP_TDB_TRAVERSE);
1134
1135         dep = talloc(ctx, struct depend);
1136         dep->needs_file = needs_file;
1137         dep->needs_opnum = needs_opnum;
1138         dep->satisfies_file = satisfies_file;
1139         dep->satisfies_opnum = satisfies_opnum;
1140         list_add(&op[satisfies_file][satisfies_opnum].post, &dep->post_list);
1141         list_add(&op[needs_file][needs_opnum].pre, &dep->pre_list);
1142         talloc_set_destructor(dep, destroy_depend);
1143 }
1144
1145 #if TRAVERSALS_TAKE_TRANSACTION_LOCK
1146 struct traverse_dep {
1147         unsigned int file;
1148         unsigned int op_num;
1149 };
1150
1151 /* Traversals can deadlock against each other, and transactions.  Force
1152  * order. */
1153 static void make_traverse_depends(char *filename[],
1154                                   struct op *op[], unsigned int num_ops[],
1155                                   unsigned int num)
1156 {
1157         unsigned int i, j, num_traversals = 0;
1158         struct traverse_dep *dep;
1159
1160         /* Sort by which one runs first. */
1161         int compare_traverse_dep(const void *_a, const void *_b)
1162         {
1163                 const struct traverse_dep *ta = _a, *tb = _b;
1164                 const struct op *a = &op[ta->file][ta->op_num],
1165                         *b = &op[tb->file][tb->op_num];
1166
1167                 if (a->serial != b->serial)
1168                         return a->serial - b->serial;
1169
1170                 /* If they have same serial, it means one didn't make any
1171                  * changes.  Thus sort by end in that case. */
1172                 return a[a->group_len].serial - b[b->group_len].serial;
1173         }
1174
1175         dep = talloc_array(NULL, struct traverse_dep, 1);
1176
1177         /* Count them. */
1178         for (i = 0; i < num; i++) {
1179                 for (j = 1; j < num_ops[i]; j++) {
1180                         /* Transaction or traverse start. */
1181                         if (op[i][j].group_start == j) {
1182                                 dep = talloc_realloc(NULL, dep,
1183                                                      struct traverse_dep,
1184                                                      num_traversals+1);
1185                                 dep[num_traversals].file = i;
1186                                 dep[num_traversals].op_num = j;
1187                                 num_traversals++;
1188                         }
1189                 }
1190         }
1191         qsort(dep, num_traversals, sizeof(dep[0]), compare_traverse_dep);
1192         for (i = 1; i < num_traversals; i++) {
1193                 /* i depends on end of traverse i-1. */
1194                 add_dependency(NULL, op, filename, dep[i].file, dep[i].op_num,
1195                                dep[i-1].file, dep[i-1].op_num
1196                                + op[dep[i-1].file][dep[i-1].op_num].group_len);
1197         }
1198         talloc_free(dep);
1199 }
1200 #endif /* TRAVERSALS_TAKE_TRANSACTION_LOCK */
1201
1202 static bool changes_db(const struct op *op)
1203 {
1204         return gives(op, NULL) != NULL;
1205 }
1206
1207 static void depend_on_previous(struct op *op[],
1208                                char *filename[],
1209                                unsigned int num,
1210                                struct key_user user[],
1211                                unsigned int i,
1212                                int prev)
1213 {
1214         bool deps[num];
1215         int j;
1216
1217         if (i == 0)
1218                 return;
1219
1220         if (prev == i - 1) {
1221                 /* Just depend on previous. */
1222                 add_dependency(NULL, op, filename,
1223                                user[i].file, user[i].op_num,
1224                                user[prev].file, user[prev].op_num);
1225                 return;
1226         }
1227
1228         /* We have to wait for the readers.  Find last one in *each* file. */
1229         memset(deps, 0, sizeof(deps));
1230         deps[user[i].file] = true;
1231         for (j = i - 1; j > prev; j--) {
1232                 if (!deps[user[j].file]) {
1233                         add_dependency(NULL, op, filename,
1234                                        user[i].file, user[i].op_num,
1235                                        user[j].file, user[j].op_num);
1236                         deps[user[j].file] = true;
1237                 }
1238         }
1239 }
1240
1241 /* This is simple, but not complete.  We don't take into account
1242  * indirect dependencies. */
1243 static void optimize_dependencies(struct op *op[], unsigned int num_ops[],
1244                                   unsigned int num)
1245 {
1246         unsigned int i, j;
1247
1248         /* There can only be one real dependency on each file */
1249         for (i = 0; i < num; i++) {
1250                 for (j = 1; j < num_ops[i]; j++) {
1251                         struct depend *dep, *next;
1252                         struct depend *prev[num];
1253
1254                         memset(prev, 0, sizeof(prev));
1255
1256                         list_for_each_safe(&op[i][j].pre, dep, next, pre_list) {
1257                                 if (!prev[dep->satisfies_file]) {
1258                                         prev[dep->satisfies_file] = dep;
1259                                         continue;
1260                                 }
1261                                 if (prev[dep->satisfies_file]->satisfies_opnum
1262                                     < dep->satisfies_opnum) {
1263                                         talloc_free(prev[dep->satisfies_file]);
1264                                         prev[dep->satisfies_file] = dep;
1265                                 } else
1266                                         talloc_free(dep);
1267                         }
1268                 }
1269         }
1270
1271         for (i = 0; i < num; i++) {
1272                 int deps[num];
1273
1274                 for (j = 0; j < num; j++)
1275                         deps[j] = -1;
1276
1277                 for (j = 1; j < num_ops[i]; j++) {
1278                         struct depend *dep, *next;
1279
1280                         list_for_each_safe(&op[i][j].pre, dep, next, pre_list) {
1281                                 if (deps[dep->satisfies_file]
1282                                     >= (int)dep->satisfies_opnum)
1283                                         talloc_free(dep);
1284                                 else
1285                                         deps[dep->satisfies_file]
1286                                                 = dep->satisfies_opnum;
1287                         }
1288                 }
1289         }
1290 }
1291
1292 static void derive_dependencies(char *filename[],
1293                                 struct op *op[], unsigned int num_ops[],
1294                                 unsigned int num)
1295 {
1296         struct keyinfo *hash;
1297         unsigned int h, i;
1298
1299         /* Create hash table for faster key lookup. */
1300         hash = hash_ops(op, num_ops, num);
1301
1302         /* Sort them by serial number. */
1303         sort_ops(hash, filename, op, num);
1304
1305         /* Create dependencies back to the last change, rather than
1306          * creating false dependencies by naively making each one
1307          * depend on the previous.  This has two purposes: it makes
1308          * later optimization simpler, and it also avoids deadlock with
1309          * same sequence number ops inside traversals (if one
1310          * traversal doesn't write anything, two ops can have the same
1311          * sequence number yet we can create a traversal dependency
1312          * the other way). */
1313         for (h = 0; h < total_keys * 2; h++) {
1314                 int prev = -1;
1315
1316                 if (hash[h].num_users < 2)
1317                         continue;
1318
1319                 for (i = 0; i < hash[h].num_users; i++) {
1320                         if (changes_db(&op[hash[h].user[i].file]
1321                                        [hash[h].user[i].op_num])) {
1322                                 depend_on_previous(op, filename, num,
1323                                                    hash[h].user, i, prev);
1324                                 prev = i;
1325                         } else if (prev >= 0)
1326                                 add_dependency(hash, op, filename,
1327                                                hash[h].user[i].file,
1328                                                hash[h].user[i].op_num,
1329                                                hash[h].user[prev].file,
1330                                                hash[h].user[prev].op_num);
1331                 }
1332         }
1333
1334 #if TRAVERSALS_TAKE_TRANSACTION_LOCK
1335         make_traverse_depends(filename, op, num_ops, num);
1336 #endif
1337
1338         optimize_dependencies(op, num_ops, num);
1339 }
1340
1341 int main(int argc, char *argv[])
1342 {
1343         struct timeval start, end;
1344         unsigned int i, num_ops[argc], hashsize[argc], tdb_flags[argc], open_flags[argc];
1345         struct op *op[argc];
1346         int fds[2];
1347         char c;
1348         bool ok = true;
1349
1350         if (argc < 3)
1351                 errx(1, "Usage: %s <tdbfile> <tracefile>...", argv[0]);
1352
1353         pipes = talloc_array(NULL, struct pipe, argc - 2);
1354         for (i = 0; i < argc - 2; i++) {
1355                 printf("Loading tracefile %s...", argv[2+i]);
1356                 fflush(stdout);
1357                 op[i] = load_tracefile(argv[2+i], &num_ops[i], &hashsize[i],
1358                                        &tdb_flags[i], &open_flags[i]);
1359                 if (pipe(pipes[i].fd) != 0)
1360                         err(1, "creating pipe");
1361                 printf("done\n");
1362         }
1363
1364         printf("Calculating inter-dependencies...");
1365         fflush(stdout);
1366         derive_dependencies(argv+2, op, num_ops, i);
1367         printf("done\n");
1368
1369         /* Don't fork for single arg case: simple debugging. */
1370         if (argc == 3) {
1371                 struct tdb_context *tdb;
1372                 tdb = tdb_open_ex(argv[1], hashsize[0], tdb_flags[0],
1373                                   open_flags[0], 0600,
1374                                   NULL, hash_key);
1375                 printf("Single threaded run...");
1376                 fflush(stdout);
1377
1378                 run_ops(tdb, pipes[0].fd[0], argv+2, op, 0, 1, num_ops[0]);
1379                 check_deps(argv[2], op[0], num_ops[0]);
1380
1381                 printf("done\n");
1382                 exit(0);
1383         }
1384
1385         if (pipe(fds) != 0)
1386                 err(1, "creating pipe");
1387
1388         for (i = 0; i < argc - 2; i++) {
1389                 struct tdb_context *tdb;
1390
1391                 switch (fork()) {
1392                 case -1:
1393                         err(1, "fork failed");
1394                 case 0:
1395                         close(fds[1]);
1396                         tdb = tdb_open_ex(argv[1], hashsize[i], tdb_flags[i],
1397                                           open_flags[i], 0600,
1398                                           NULL, hash_key);
1399                         if (!tdb)
1400                                 err(1, "Opening tdb %s", argv[1]);
1401
1402                         /* This catches parent exiting. */
1403                         if (read(fds[0], &c, 1) != 1)
1404                                 exit(1);
1405                         run_ops(tdb, pipes[i].fd[0], argv+2, op, i, 1,
1406                                 num_ops[i]);
1407                         check_deps(argv[2+i], op[i], num_ops[i]);
1408                         exit(0);
1409                 default:
1410                         break;
1411                 }
1412         }
1413
1414         /* Let everything settle. */
1415         sleep(1);
1416
1417         printf("Starting run...");
1418         fflush(stdout);
1419         gettimeofday(&start, NULL);
1420         /* Tell them all to go!  Any write of sufficient length will do. */
1421         if (write(fds[1], hashsize, i) != i)
1422                 err(1, "Writing to wakeup pipe");
1423
1424         for (i = 0; i < argc - 2; i++) {
1425                 int status;
1426                 wait(&status);
1427                 if (!WIFEXITED(status)) {
1428                         warnx("Child died with signal %i", WTERMSIG(status));
1429                         ok = false;
1430                 } else if (WEXITSTATUS(status) != 0)
1431                         /* Assume child spat out error. */
1432                         ok = false;
1433         }
1434         if (!ok)
1435                 exit(1);
1436
1437         gettimeofday(&end, NULL);
1438         printf("done\n");
1439
1440         end.tv_sec -= start.tv_sec;
1441         printf("Time replaying: %lu usec\n",
1442                end.tv_sec * 1000000UL + (end.tv_usec - start.tv_usec));
1443         
1444         exit(0);
1445 }