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