Fix logic bug in optimizer, and fix up DEBUG_DEPS compile.
[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_opnum+1, filename[dep->satisfies_file],
506                        dep->satisfies_opnum+1);
507                 fflush(stdout);
508 #endif
509                 /* This could be any op, not just this one. */
510                 talloc_free(dep);
511         }
512 }
513
514 static void do_post(char *filename[], unsigned int file,
515                     const struct op op[], unsigned int i)
516 {
517         struct depend *dep;
518
519         list_for_each(&op[i].post, dep, post_list) {
520 #if DEBUG_DEPS
521                 printf("%s:%u:sending to file %s:%u\n", filename[file], i+1,
522                        filename[dep->needs_file], dep->needs_opnum+1);
523 #endif
524                 if (write(pipes[dep->needs_file].fd[1], &dep, sizeof(dep))
525                     != sizeof(dep))
526                         err(1, "%s:%u failed to tell file %s",
527                             filename[file], i+1, filename[dep->needs_file]);
528         }
529 }
530
531 static int get_len(TDB_DATA key, TDB_DATA data, void *private_data)
532 {
533         return data.dsize;
534 }
535
536 static unsigned run_ops(struct tdb_context *tdb,
537                         int pre_fd,
538                         char *filename[],
539                         unsigned int file,
540                         struct op op[],
541                         unsigned int start, unsigned int stop);
542
543 struct traverse_info {
544         struct op *op;
545         char **filename;
546         unsigned file;
547         int pre_fd;
548         unsigned int start;
549         unsigned int i;
550 };
551
552 /* Trivial case: do whatever they did for this key. */
553 static int trivial_traverse(struct tdb_context *tdb,
554                             TDB_DATA key, TDB_DATA data,
555                             void *_tinfo)
556 {
557         struct traverse_info *tinfo = _tinfo;
558         struct traverse *trav = tinfo->op[tinfo->start].trav;
559         unsigned int h = hash_key(&key) % (trav->num * 2);
560
561         while (trav->hash[h].index) {
562                 if (key_eq(trav->hash[h].key, key)) {
563                         run_ops(tdb, tinfo->pre_fd, tinfo->filename,
564                                 tinfo->file, tinfo->op, trav->hash[h].index,
565                                 trav->end);
566                         tinfo->i++;
567                         return 0;
568                 }
569                 h = (h + 1) % (trav->num * 2);
570         }
571         fail(tinfo->filename[tinfo->file], tinfo->start + 1,
572              "unexpected traverse key");
573 }
574
575 /* More complex.  Just do whatever's they did at the n'th entry. */
576 static int nontrivial_traverse(struct tdb_context *tdb,
577                                TDB_DATA key, TDB_DATA data,
578                                void *_tinfo)
579 {
580         struct traverse_info *tinfo = _tinfo;
581         struct traverse *trav = tinfo->op[tinfo->start].trav;
582
583         if (tinfo->i == trav->end) {
584                 /* This can happen if traverse expects to be empty. */
585                 if (tinfo->start + 1 == trav->end)
586                         return 1;
587                 fail(tinfo->filename[tinfo->file], tinfo->start + 1,
588                      "traverse did not terminate");
589         }
590
591         if (tinfo->op[tinfo->i].op != OP_TDB_TRAVERSE)
592                 fail(tinfo->filename[tinfo->file], tinfo->start + 1,
593                      "%s:%u:traverse terminated early");
594
595         /* Run any normal ops. */
596         tinfo->i = run_ops(tdb, tinfo->pre_fd, tinfo->filename, tinfo->file,
597                            tinfo->op, tinfo->i+1, trav->end);
598
599         if (tinfo->i == trav->end)
600                 return 1;
601
602         return 0;
603 }
604
605 static unsigned op_traverse(struct tdb_context *tdb,
606                             int pre_fd,
607                             char *filename[],
608                             unsigned int file,
609                             int (*traversefn)(struct tdb_context *,
610                                               tdb_traverse_func, void *),
611                             struct op op[],
612                             unsigned int start)
613 {
614         struct traverse *trav = op[start].trav;
615         struct traverse_info tinfo = { op, filename, file, pre_fd,
616                                        start, start+1 };
617
618         /* Trivial case. */
619         if (trav->hash) {
620                 int ret = traversefn(tdb, trivial_traverse, &tinfo);
621                 if (ret != trav->num)
622                         fail(filename[file], start+1,
623                              "short traversal %i", ret);
624                 return trav->end;
625         }
626
627         traversefn(tdb, nontrivial_traverse, &tinfo);
628
629         /* Traversing in wrong order can have strange effects: eg. if
630          * original traverse went A (delete A), B, we might do B
631          * (delete A).  So if we have ops left over, we do it now. */
632         while (tinfo.i != trav->end) {
633                 if (op[tinfo.i].op == OP_TDB_TRAVERSE)
634                         tinfo.i++;
635                 else
636                         tinfo.i = run_ops(tdb, pre_fd, filename, file, op,
637                                           tinfo.i, trav->end);
638         }
639
640         return trav->end;
641 }
642
643 static void break_out(int sig)
644 {
645 }
646
647 static __attribute__((noinline))
648 unsigned run_ops(struct tdb_context *tdb,
649                  int pre_fd,
650                  char *filename[],
651                  unsigned int file,
652                  struct op op[], unsigned int start, unsigned int stop)
653 {
654         unsigned int i;
655         struct sigaction sa;
656
657         sa.sa_handler = break_out;
658         sa.sa_flags = 0;
659
660         sigaction(SIGALRM, &sa, NULL);
661         for (i = start; i < stop; i++) {
662                 do_pre(filename, file, pre_fd, op, i);
663
664                 switch (op[i].op) {
665                 case OP_TDB_LOCKALL:
666                         try(tdb_lockall(tdb), op[i].ret);
667                         break;
668                 case OP_TDB_LOCKALL_MARK:
669                         try(tdb_lockall_mark(tdb), op[i].ret);
670                         break;
671                 case OP_TDB_LOCKALL_UNMARK:
672                         try(tdb_lockall_unmark(tdb), op[i].ret);
673                         break;
674                 case OP_TDB_LOCKALL_NONBLOCK:
675                         unreliable(tdb_lockall_nonblock(tdb), op[i].ret,
676                                    tdb_lockall(tdb), tdb_unlockall(tdb));
677                         break;
678                 case OP_TDB_UNLOCKALL:
679                         try(tdb_unlockall(tdb), op[i].ret);
680                         break;
681                 case OP_TDB_LOCKALL_READ:
682                         try(tdb_lockall_read(tdb), op[i].ret);
683                         break;
684                 case OP_TDB_LOCKALL_READ_NONBLOCK:
685                         unreliable(tdb_lockall_read_nonblock(tdb), op[i].ret,
686                                    tdb_lockall_read(tdb),
687                                    tdb_unlockall_read(tdb));
688                         break;
689                 case OP_TDB_UNLOCKALL_READ:
690                         try(tdb_unlockall_read(tdb), op[i].ret);
691                         break;
692                 case OP_TDB_CHAINLOCK:
693                         try(tdb_chainlock(tdb, op[i].key), op[i].ret);
694                         break;
695                 case OP_TDB_CHAINLOCK_NONBLOCK:
696                         unreliable(tdb_chainlock_nonblock(tdb, op[i].key),
697                                    op[i].ret,
698                                    tdb_chainlock(tdb, op[i].key),
699                                    tdb_chainunlock(tdb, op[i].key));
700                         break;
701                 case OP_TDB_CHAINLOCK_MARK:
702                         try(tdb_chainlock_mark(tdb, op[i].key), op[i].ret);
703                         break;
704                 case OP_TDB_CHAINLOCK_UNMARK:
705                         try(tdb_chainlock_unmark(tdb, op[i].key), op[i].ret);
706                         break;
707                 case OP_TDB_CHAINUNLOCK:
708                         try(tdb_chainunlock(tdb, op[i].key), op[i].ret);
709                         break;
710                 case OP_TDB_CHAINLOCK_READ:
711                         try(tdb_chainlock_read(tdb, op[i].key), op[i].ret);
712                         break;
713                 case OP_TDB_CHAINUNLOCK_READ:
714                         try(tdb_chainunlock_read(tdb, op[i].key), op[i].ret);
715                         break;
716                 case OP_TDB_PARSE_RECORD:
717                         try(tdb_parse_record(tdb, op[i].key, get_len, NULL),
718                             op[i].ret);
719                         break;
720                 case OP_TDB_EXISTS:
721                         try(tdb_exists(tdb, op[i].key), op[i].ret);
722                         break;
723                 case OP_TDB_STORE:
724                         try(tdb_store(tdb, op[i].key, op[i].data, op[i].flag),
725                             op[i].ret);
726                         break;
727                 case OP_TDB_APPEND:
728                         try(tdb_append(tdb, op[i].key, op[i].data), op[i].ret);
729                         break;
730                 case OP_TDB_GET_SEQNUM:
731                         try(tdb_get_seqnum(tdb), op[i].ret);
732                         break;
733                 case OP_TDB_WIPE_ALL:
734                         try(tdb_wipe_all(tdb), op[i].ret);
735                         break;
736                 case OP_TDB_TRANSACTION_START:
737                         try(tdb_transaction_start(tdb), op[i].ret);
738                         break;
739                 case OP_TDB_TRANSACTION_CANCEL:
740                         try(tdb_transaction_cancel(tdb), op[i].ret);
741                         break;
742                 case OP_TDB_TRANSACTION_COMMIT:
743                         try(tdb_transaction_commit(tdb), op[i].ret);
744                         break;
745                 case OP_TDB_TRAVERSE_READ_START:
746                         i = op_traverse(tdb, pre_fd, filename, file,
747                                         tdb_traverse_read, op, i);
748                         break;
749                 case OP_TDB_TRAVERSE_START:
750                         i = op_traverse(tdb, pre_fd, filename, file,
751                                         tdb_traverse, op, i);
752                         break;
753                 case OP_TDB_TRAVERSE:
754                         /* Terminate: we're in a traverse, and we've
755                          * done our ops. */
756                         return i;
757                 case OP_TDB_TRAVERSE_END:
758                         fail(filename[file], i+1, "unepxected end traverse");
759                 /* FIXME: These must be treated like traverse. */
760                 case OP_TDB_FIRSTKEY:
761                         if (!key_eq(tdb_firstkey(tdb), op[i].data))
762                                 fail(filename[file], i+1, "bad firstkey");
763                         break;
764                 case OP_TDB_NEXTKEY:
765                         if (!key_eq(tdb_nextkey(tdb, op[i].key), op[i].data))
766                                 fail(filename[file], i+1, "bad nextkey");
767                         break;
768                 case OP_TDB_FETCH: {
769                         TDB_DATA f = tdb_fetch(tdb, op[i].key);
770                         if (!key_eq(f, op[i].data))
771                                 fail(filename[file], i+1, "bad fetch %u",
772                                      f.dsize);
773                         break;
774                 }
775                 case OP_TDB_DELETE:
776                         try(tdb_delete(tdb, op[i].key), op[i].ret);
777                         break;
778                 }
779                 do_post(filename, file, op, i);
780         }
781         return i;
782 }
783
784 static struct op *load_tracefile(const char *filename, unsigned int *num,
785                                  unsigned int *hashsize,
786                                  unsigned int *tdb_flags,
787                                  unsigned int *open_flags)
788 {
789         unsigned int i;
790         struct op *op = talloc_array(NULL, struct op, 1);
791         char **words;
792         char **lines;
793         char *file;
794
795         file = grab_file(NULL, filename, NULL);
796         if (!file)
797                 err(1, "Reading %s", filename);
798
799         lines = strsplit(file, file, "\n", NULL);
800         if (!lines[0])
801                 errx(1, "%s is empty", filename);
802
803         words = strsplit(lines, lines[0], " ", NULL);
804         if (!streq(words[1], "tdb_open"))
805                 fail(filename, 1, "does not start with tdb_open");
806
807         *hashsize = atoi(words[2]);
808         *tdb_flags = strtoul(words[3], NULL, 0);
809         *open_flags = strtoul(words[4], NULL, 0);
810
811         for (i = 1; lines[i]; i++) {
812                 const struct op_table *opt;
813
814                 words = strsplit(lines, lines[i], " ", NULL);
815                 if (!words[0] || !words[1])
816                         fail(filename, i+1, "Expected serial number and op");
817                
818                 opt = find_keyword(words[1], strlen(words[1]));
819                 if (!opt) {
820                         if (streq(words[1], "tdb_close")) {
821                                 if (lines[i+1])
822                                         fail(filename, i+2,
823                                              "lines after tdb_close");
824                                 *num = i;
825                                 talloc_free(lines);
826                                 return op;
827                         }
828                         fail(filename, i+1, "Unknown operation '%s'", words[1]);
829                 }
830
831                 add_op(filename, &op, i, atoi(words[0]), opt->type);
832                 opt->enhance_op(filename, op, i, words);
833         }
834
835         fprintf(stderr, "%s:%u:last operation is not tdb_close: incomplete?",
836               filename, i);
837         talloc_free(lines);
838         *num = i - 1;
839         return op;
840 }
841
842 /* We remember all the keys we've ever seen, and who has them. */
843 struct key_user {
844         unsigned int file;
845         unsigned int op_num;
846 };
847
848 struct keyinfo {
849         TDB_DATA key;
850         unsigned int num_users;
851         struct key_user *user;
852 };
853
854 static const TDB_DATA must_not_exist;
855 static const TDB_DATA must_exist;
856 static const TDB_DATA not_exists_or_empty;
857
858 /* NULL means doesn't care if it exists or not, &must_exist means
859  * it must exist but we don't care what, &must_not_exist means it must
860  * not exist, otherwise the data it needs. */
861 static const TDB_DATA *needs(const struct op *op)
862 {
863         switch (op->op) {
864         /* FIXME: Pull forward deps, since we can deadlock */
865         case OP_TDB_CHAINLOCK:
866         case OP_TDB_CHAINLOCK_NONBLOCK:
867         case OP_TDB_CHAINLOCK_MARK:
868         case OP_TDB_CHAINLOCK_UNMARK:
869         case OP_TDB_CHAINUNLOCK:
870         case OP_TDB_CHAINLOCK_READ:
871         case OP_TDB_CHAINUNLOCK_READ:
872                 return NULL;
873
874         case OP_TDB_APPEND:
875                 if (op->append.pre.dsize == 0)
876                         return &not_exists_or_empty;
877                 return &op->append.pre;
878
879         case OP_TDB_STORE:
880                 if (op->flag == TDB_INSERT) {
881                         if (op->ret < 0)
882                                 return &must_exist;
883                         else
884                                 return &must_not_exist;
885                 } else if (op->flag == TDB_MODIFY) {
886                         if (op->ret < 0)
887                                 return &must_not_exist;
888                         else
889                                 return &must_exist;
890                 }
891                 /* No flags?  Don't care */
892                 return NULL;
893
894         case OP_TDB_EXISTS:
895                 if (op->ret == 1)
896                         return &must_exist;
897                 else
898                         return &must_not_exist;
899
900         case OP_TDB_PARSE_RECORD:
901                 if (op->ret < 0)
902                         return &must_not_exist;
903                 return &must_exist;
904
905         /* FIXME: handle these. */
906         case OP_TDB_WIPE_ALL:
907         case OP_TDB_FIRSTKEY:
908         case OP_TDB_NEXTKEY:
909         case OP_TDB_GET_SEQNUM:
910         case OP_TDB_TRAVERSE:
911         case OP_TDB_TRANSACTION_COMMIT:
912         case OP_TDB_TRANSACTION_CANCEL:
913         case OP_TDB_TRANSACTION_START:
914                 return NULL;
915
916         case OP_TDB_FETCH:
917                 if (!op->data.dptr)
918                         return &must_not_exist;
919                 return &op->data;
920
921         case OP_TDB_DELETE:
922                 if (op->ret < 0)
923                         return &must_not_exist;
924                 return &must_exist;
925
926         default:
927                 errx(1, "Unexpected op %i", op->op);
928         }
929         
930 }
931
932 /* What's the data after this op?  pre if nothing changed. */
933 static const TDB_DATA *gives(const struct op *op, const TDB_DATA *pre)
934 {
935         /* Failed ops don't change state of db. */
936         if (op->ret < 0)
937                 return pre;
938
939         if (op->op == OP_TDB_DELETE || op->op == OP_TDB_WIPE_ALL)
940                 return &tdb_null;
941
942         if (op->op == OP_TDB_APPEND)
943                 return &op->append.post;
944
945         if (op->op == OP_TDB_STORE)
946                 return &op->data;
947
948         return pre;
949 }
950
951 static struct keyinfo *hash_ops(struct op *op[], unsigned int num_ops[],
952                                 unsigned int num)
953 {
954         unsigned int i, j, h;
955         struct keyinfo *hash;
956
957         hash = talloc_zero_array(op[0], struct keyinfo, total_keys*2);
958         for (i = 0; i < num; i++) {
959                 for (j = 1; j < num_ops[i]; j++) {
960                         /* We can't do this on allocation, due to realloc. */
961                         list_head_init(&op[i][j].post);
962                         list_head_init(&op[i][j].pre);
963
964                         if (!op[i][j].key.dptr)
965                                 continue;
966
967                         /* We don't wait for traverse keys */
968                         /* FIXME: We should, for trivial traversals. */
969                         if (op[i][j].op == OP_TDB_TRAVERSE)
970                                 continue;
971
972                         h = hash_key(&op[i][j].key) % (total_keys * 2);
973                         while (!key_eq(hash[h].key, op[i][j].key)) {
974                                 if (!hash[h].key.dptr) {
975                                         hash[h].key = op[i][j].key;
976                                         break;
977                                 }
978                                 h = (h + 1) % (total_keys * 2);
979                         }
980                         /* Might as well save some memory if we can. */
981                         if (op[i][j].key.dptr != hash[h].key.dptr) {
982                                 talloc_free(op[i][j].key.dptr);
983                                 op[i][j].key.dptr = hash[h].key.dptr;
984                         }
985                         hash[h].user = talloc_realloc(hash, hash[h].user,
986                                                      struct key_user,
987                                                      hash[h].num_users+1);
988                         hash[h].user[hash[h].num_users].op_num = j;
989                         hash[h].user[hash[h].num_users].file = i;
990                         hash[h].num_users++;
991                 }
992         }
993
994         return hash;
995 }
996
997 static bool satisfies(const TDB_DATA *data, const TDB_DATA *need)
998 {
999         /* Don't need anything?  Cool. */
1000         if (!need)
1001                 return true;
1002
1003         /* This should be tdb_null or a real value. */
1004         assert(data != &must_exist);
1005         assert(data != &must_not_exist);
1006         assert(data != &not_exists_or_empty);
1007
1008         /* must_not_exist == must_not_exist, must_exist == must_exist, or
1009            not_exists_or_empty == not_exists_or_empty. */
1010         if (data->dsize == need->dsize && data->dptr == need->dptr)
1011                 return true;
1012
1013         /* Must not exist?  data must not exist. */
1014         if (need == &must_not_exist)
1015                 return data->dptr == NULL;
1016
1017         /* Must exist? */
1018         if (need == &must_exist)
1019                 return data->dptr != NULL;
1020
1021         /* Either noexist or empty. */
1022         if (need == &not_exists_or_empty)
1023                 return data->dsize == 0;
1024
1025         /* Needs something specific. */
1026         return key_eq(*data, *need);
1027 }
1028
1029 static void move_to_front(struct key_user res[], unsigned int elem)
1030 {
1031         if (elem != 0) {
1032                 struct key_user tmp = res[elem];
1033                 memmove(res + 1, res, elem*sizeof(res[0]));
1034                 res[0] = tmp;
1035         }
1036 }
1037
1038 static void restore_to_pos(struct key_user res[], unsigned int elem)
1039 {
1040         if (elem != 0) {
1041                 struct key_user tmp = res[0];
1042                 memmove(res, res + 1, elem*sizeof(res[0]));
1043                 res[elem] = tmp;
1044         }
1045 }
1046
1047 static bool sort_deps(char *filename[], struct op *op[],
1048                       struct key_user res[], unsigned num,
1049                       const TDB_DATA *data, unsigned num_files)
1050 {
1051         unsigned int i, files_done;
1052         struct op *this_op;
1053         bool done[num_files];
1054
1055         /* Nothing left?  We're sorted. */
1056         if (num == 0)
1057                 return true;
1058
1059         memset(done, 0, sizeof(done));
1060
1061         /* Since ops within a trace file are ordered, we just need to figure
1062          * out which file to try next.  Since we don't take into account
1063          * inter-key relationships (which exist by virtue of trace file order),
1064          * we minimize the chance of harm by trying to keep in serial order. */
1065         for (files_done = 0, i = 0; i < num && files_done < num_files; i++) {
1066                 if (done[res[i].file])
1067                         continue;
1068
1069                 this_op = &op[res[i].file][res[i].op_num];
1070                 /* Is what we have good enough for this op? */
1071                 if (satisfies(data, needs(this_op))) {
1072                         move_to_front(res, i);
1073                         if (sort_deps(filename, op, res+1, num-1,
1074                                       gives(this_op, data), num_files))
1075                                 return true;
1076                         restore_to_pos(res, i);
1077                 }
1078                 done[res[i].file] = true;
1079                 files_done++;
1080         }
1081
1082         /* No combination worked. */
1083         return false;
1084 }
1085
1086 static void check_dep_sorting(struct key_user user[], unsigned num_users,
1087                               unsigned num_files)
1088 {
1089 #if DEBUG_DEPS
1090         unsigned int i;
1091         unsigned minima[num_files];
1092
1093         memset(minima, 0, sizeof(minima));
1094         for (i = 0; i < num_users; i++) {
1095                 assert(minima[user[i].file] < user[i].op_num);
1096                 minima[user[i].file] = user[i].op_num;
1097         }
1098 #endif
1099 }
1100
1101 /* All these ops have the same serial number.  Which comes first?
1102  *
1103  * This can happen both because read ops or failed write ops don't
1104  * change serial number, and also due to race since we access the
1105  * number unlocked (the race can cause less detectable ordering problems,
1106  * in which case we'll deadlock and report: fix manually in that case).
1107  */
1108 static void figure_deps(char *filename[], struct op *op[],
1109                         struct key_user user[], unsigned num_users,
1110                         unsigned num_files)
1111 {
1112         /* We assume database starts empty. */
1113         const struct TDB_DATA *data = &tdb_null;
1114
1115         if (!sort_deps(filename, op, user, num_users, data, num_files))
1116                 fail(filename[user[0].file], user[0].op_num+1,
1117                      "Could not resolve inter-dependencies");
1118
1119         check_dep_sorting(user, num_users, num_files);
1120 }
1121
1122 static void sort_ops(struct keyinfo hash[], char *filename[], struct op *op[],
1123                      unsigned int num)
1124 {
1125         unsigned int h;
1126
1127         /* Gcc nexted function extension.  How cool is this? */
1128         int compare_serial(const void *_a, const void *_b)
1129         {
1130                 const struct key_user *a = _a, *b = _b;
1131
1132                 /* First, maintain order within any trace file. */
1133                 if (a->file == b->file)
1134                         return a->op_num - b->op_num;
1135
1136                 /* Otherwise, arrange by serial order. */
1137                 return op[a->file][a->op_num].serial
1138                         - op[b->file][b->op_num].serial;
1139         }
1140
1141         /* Now sort into serial order. */
1142         for (h = 0; h < total_keys * 2; h++) {
1143                 struct key_user *user = hash[h].user;
1144
1145                 qsort(user, hash[h].num_users, sizeof(user[0]), compare_serial);
1146                 figure_deps(filename, op, user, hash[h].num_users, num);
1147         }
1148 }
1149
1150 static int destroy_depend(struct depend *dep)
1151 {
1152         list_del(&dep->pre_list);
1153         list_del(&dep->post_list);
1154         return 0;
1155 }
1156
1157 static void add_dependency(void *ctx,
1158                            struct op *op[],
1159                            char *filename[],
1160                            unsigned int needs_file,
1161                            unsigned int needs_opnum,
1162                            unsigned int satisfies_file,
1163                            unsigned int satisfies_opnum)
1164 {
1165         struct depend *dep;
1166         unsigned int needs_start, sat_start;
1167
1168         /* We don't depend on ourselves. */
1169         if (needs_file == satisfies_file) {
1170                 assert(satisfies_opnum < needs_opnum);
1171                 return;
1172         }
1173
1174 #if DEBUG_DEPS
1175         printf("%s:%u: depends on %s:%u\n",
1176                filename[needs_file], needs_opnum+1,
1177                filename[satisfies_file], satisfies_opnum+1);
1178 #endif
1179
1180         needs_start = op[needs_file][needs_opnum].group_start;
1181         sat_start = op[satisfies_file][satisfies_opnum].group_start;
1182
1183         /* If needs is in a transaction, we need it before start. */
1184         if (needs_start) {
1185                 switch (op[needs_file][needs_start].op) {
1186                 case OP_TDB_TRANSACTION_START:
1187                         needs_opnum = needs_start;
1188 #ifdef DEBUG_DEPS
1189                         printf("  -> Back to %u\n", needs_start+1);
1190                         fflush(stdout);
1191 #endif
1192                         break;
1193                 default:
1194                         break;
1195                 }
1196         }
1197
1198         /* If satisfies is in a transaction, we wait until after commit. */
1199         /* FIXME: If transaction is cancelled, don't need dependency. */
1200         if (sat_start) {
1201                 if (op[satisfies_file][sat_start].op
1202                     == OP_TDB_TRANSACTION_START) {
1203                         satisfies_opnum
1204                                 = op[satisfies_file][sat_start].transaction_end;
1205 #ifdef DEBUG_DEPS
1206                         printf("  -> Depends on %u\n", satisfies_opnum+1);
1207                         fflush(stdout);
1208 #endif
1209                 }
1210         }
1211
1212         dep = talloc(ctx, struct depend);
1213         dep->needs_file = needs_file;
1214         dep->needs_opnum = needs_opnum;
1215         dep->satisfies_file = satisfies_file;
1216         dep->satisfies_opnum = satisfies_opnum;
1217         list_add(&op[satisfies_file][satisfies_opnum].post, &dep->post_list);
1218         list_add(&op[needs_file][needs_opnum].pre, &dep->pre_list);
1219         talloc_set_destructor(dep, destroy_depend);
1220 }
1221
1222 #if TRAVERSALS_TAKE_TRANSACTION_LOCK
1223 struct traverse_dep {
1224         unsigned int file;
1225         unsigned int op_num;
1226         const struct op *op;
1227 };
1228
1229 /* Sort by which one runs first. */
1230 static int compare_traverse_dep(const void *_a, const void *_b)
1231 {
1232         const struct traverse_dep *a = _a, *b = _b;
1233         const struct traverse *trava = a->op->trav, *travb = b->op->trav;
1234
1235         if (a->op->serial != b->op->serial)
1236                 return a->op->serial - b->op->serial;
1237
1238         /* If they have same serial, it means one didn't make any changes.
1239          * Thus sort by end in that case. */
1240         return a->op[trava->end - a->op_num].serial
1241                 - b->op[travb->end - b->op_num].serial;
1242 }
1243
1244 /* Traversals can deadlock against each other.  Force order. */
1245 static void make_traverse_depends(char *filename[],
1246                                   struct op *op[], unsigned int num_ops[],
1247                                   unsigned int num)
1248 {
1249         unsigned int i, j, num_traversals = 0;
1250         struct traverse_dep *dep;
1251
1252         dep = talloc_array(NULL, struct traverse_dep, 1);
1253
1254         /* Count them. */
1255         for (i = 0; i < num; i++) {
1256                 for (j = 0; j < num_ops[i]; j++) {
1257                         if (op[i][j].op == OP_TDB_TRAVERSE_START
1258                             || op[i][j].op == OP_TDB_TRAVERSE_READ_START) {
1259                                 dep = talloc_realloc(NULL, dep,
1260                                                      struct traverse_dep,
1261                                                      num_traversals+1);
1262                                 dep[num_traversals].file = i;
1263                                 dep[num_traversals].op_num = j;
1264                                 dep[num_traversals].op = &op[i][j];
1265                                 num_traversals++;
1266                         }
1267                 }
1268         }
1269         qsort(dep, num_traversals, sizeof(dep[0]), compare_traverse_dep);
1270         for (i = 1; i < num_traversals; i++) {
1271                 /* i depends on end of traverse i-1. */
1272                 add_dependency(NULL, op, filename, dep[i].file, dep[i].op_num,
1273                                dep[i-1].file, dep[i-1].op->trav->end);
1274         }
1275         talloc_free(dep);
1276 }
1277 #endif /* TRAVERSALS_TAKE_TRANSACTION_LOCK */
1278
1279 static bool changes_db(const struct op *op)
1280 {
1281         return gives(op, NULL) != NULL;
1282 }
1283
1284 static void depend_on_previous(struct op *op[],
1285                                char *filename[],
1286                                unsigned int num,
1287                                struct key_user user[],
1288                                unsigned int i,
1289                                int prev)
1290 {
1291         bool deps[num];
1292         int j;
1293
1294         if (i == 0)
1295                 return;
1296
1297         if (prev == i - 1) {
1298                 /* Just depend on previous. */
1299                 add_dependency(NULL, op, filename,
1300                                user[i].file, user[i].op_num,
1301                                user[prev].file, user[prev].op_num);
1302                 return;
1303         }
1304
1305         /* We have to wait for the readers.  Find last one in *each* file. */
1306         memset(deps, 0, sizeof(deps));
1307         deps[user[i].file] = true;
1308         for (j = i - 1; j > prev; j--) {
1309                 if (!deps[user[j].file]) {
1310                         add_dependency(NULL, op, filename,
1311                                        user[i].file, user[i].op_num,
1312                                        user[j].file, user[j].op_num);
1313                         deps[user[j].file] = true;
1314                 }
1315         }
1316 }
1317
1318 /* This is simple, but not complete.  We don't take into account
1319  * indirect dependencies. */
1320 static void optimize_dependencies(struct op *op[], unsigned int num_ops[],
1321                                   unsigned int num)
1322 {
1323         unsigned int i, j;
1324
1325         /* There can only be one real dependency on each file */
1326         for (i = 0; i < num; i++) {
1327                 for (j = 1; j < num_ops[i]; j++) {
1328                         struct depend *dep, *next;
1329                         struct depend *prev[num];
1330
1331                         memset(prev, 0, sizeof(prev));
1332
1333                         list_for_each_safe(&op[i][j].pre, dep, next, pre_list) {
1334                                 if (!prev[dep->satisfies_file]) {
1335                                         prev[dep->satisfies_file] = dep;
1336                                         continue;
1337                                 }
1338                                 if (prev[dep->satisfies_file]->satisfies_opnum
1339                                     < dep->satisfies_opnum) {
1340                                         talloc_free(prev[dep->satisfies_file]);
1341                                         prev[dep->satisfies_file] = dep;
1342                                 } else
1343                                         talloc_free(dep);
1344                         }
1345                 }
1346         }
1347
1348         for (i = 0; i < num; i++) {
1349                 int deps[num];
1350
1351                 for (j = 0; j < num; j++)
1352                         deps[j] = -1;
1353
1354                 for (j = 1; j < num_ops[i]; j++) {
1355                         struct depend *dep, *next;
1356
1357                         list_for_each_safe(&op[i][j].pre, dep, next, pre_list) {
1358                                 if (deps[dep->satisfies_file]
1359                                     >= (int)dep->satisfies_opnum)
1360                                         talloc_free(dep);
1361                                 else
1362                                         deps[dep->satisfies_file]
1363                                                 = dep->satisfies_opnum;
1364                         }
1365                 }
1366         }
1367 }
1368
1369 static void derive_dependencies(char *filename[],
1370                                 struct op *op[], unsigned int num_ops[],
1371                                 unsigned int num)
1372 {
1373         struct keyinfo *hash;
1374         unsigned int h, i;
1375
1376         /* Create hash table for faster key lookup. */
1377         hash = hash_ops(op, num_ops, num);
1378
1379         /* Sort them by serial number. */
1380         sort_ops(hash, filename, op, num);
1381
1382         /* Create dependencies back to the last change, rather than
1383          * creating false dependencies by naively making each one
1384          * depend on the previous.  This has two purposes: it makes
1385          * later optimization simpler, and it also avoids deadlock with
1386          * same sequence number ops inside traversals (if one
1387          * traversal doesn't write anything, two ops can have the same
1388          * sequence number yet we can create a traversal dependency
1389          * the other way). */
1390         for (h = 0; h < total_keys * 2; h++) {
1391                 int prev = -1;
1392
1393                 if (hash[h].num_users < 2)
1394                         continue;
1395
1396                 for (i = 0; i < hash[h].num_users; i++) {
1397                         if (changes_db(&op[hash[h].user[i].file]
1398                                        [hash[h].user[i].op_num])) {
1399                                 depend_on_previous(op, filename, num,
1400                                                    hash[h].user, i, prev);
1401                                 prev = i;
1402                         } else if (prev >= 0)
1403                                 add_dependency(hash, op, filename,
1404                                                hash[h].user[i].file,
1405                                                hash[h].user[i].op_num,
1406                                                hash[h].user[prev].file,
1407                                                hash[h].user[prev].op_num);
1408                 }
1409         }
1410
1411 #if TRAVERSALS_TAKE_TRANSACTION_LOCK
1412         make_traverse_depends(filename, op, num_ops, num);
1413 #endif
1414
1415         optimize_dependencies(op, num_ops, num);
1416 }
1417
1418 int main(int argc, char *argv[])
1419 {
1420         struct timeval start, end;
1421         unsigned int i, num_ops[argc], hashsize[argc], tdb_flags[argc], open_flags[argc];
1422         struct op *op[argc];
1423         int fds[2];
1424         char c;
1425         bool ok = true;
1426
1427         if (argc < 3)
1428                 errx(1, "Usage: %s <tdbfile> <tracefile>...", argv[0]);
1429
1430         pipes = talloc_array(NULL, struct pipe, argc - 2);
1431         for (i = 0; i < argc - 2; i++) {
1432                 printf("Loading tracefile %s...", argv[2+i]);
1433                 fflush(stdout);
1434                 op[i] = load_tracefile(argv[2+i], &num_ops[i], &hashsize[i],
1435                                        &tdb_flags[i], &open_flags[i]);
1436                 if (pipe(pipes[i].fd) != 0)
1437                         err(1, "creating pipe");
1438                 printf("done\n");
1439         }
1440
1441         printf("Calculating inter-dependencies...");
1442         fflush(stdout);
1443         derive_dependencies(argv+2, op, num_ops, i);
1444         printf("done\n");
1445
1446         /* Don't fork for single arg case: simple debugging. */
1447         if (argc == 3) {
1448                 struct tdb_context *tdb;
1449                 tdb = tdb_open_ex(argv[1], hashsize[0], tdb_flags[0],
1450                                   open_flags[0], 0600,
1451                                   NULL, hash_key);
1452                 printf("Single threaded run...");
1453                 fflush(stdout);
1454
1455                 run_ops(tdb, pipes[0].fd[0], argv+2, 0, op[0], 1, num_ops[0]);
1456                 check_deps(argv[2], op[0], num_ops[0]);
1457
1458                 printf("done\n");
1459                 exit(0);
1460         }
1461
1462         if (pipe(fds) != 0)
1463                 err(1, "creating pipe");
1464
1465         for (i = 0; i < argc - 2; i++) {
1466                 struct tdb_context *tdb;
1467
1468                 switch (fork()) {
1469                 case -1:
1470                         err(1, "fork failed");
1471                 case 0:
1472                         close(fds[1]);
1473                         tdb = tdb_open_ex(argv[1], hashsize[i], tdb_flags[i],
1474                                           open_flags[i], 0600,
1475                                           NULL, hash_key);
1476                         if (!tdb)
1477                                 err(1, "Opening tdb %s", argv[1]);
1478
1479                         /* This catches parent exiting. */
1480                         if (read(fds[0], &c, 1) != 1)
1481                                 exit(1);
1482                         run_ops(tdb, pipes[i].fd[0], argv+2, i, op[i], 1,
1483                                 num_ops[i]);
1484                         check_deps(argv[2+i], op[i], num_ops[i]);
1485                         exit(0);
1486                 default:
1487                         break;
1488                 }
1489         }
1490
1491         /* Let everything settle. */
1492         sleep(1);
1493
1494         printf("Starting run...");
1495         fflush(stdout);
1496         gettimeofday(&start, NULL);
1497         /* Tell them all to go!  Any write of sufficient length will do. */
1498         if (write(fds[1], hashsize, i) != i)
1499                 err(1, "Writing to wakeup pipe");
1500
1501         for (i = 0; i < argc - 2; i++) {
1502                 int status;
1503                 wait(&status);
1504                 if (!WIFEXITED(status)) {
1505                         warnx("Child died with signal %i", WTERMSIG(status));
1506                         ok = false;
1507                 } else if (WEXITSTATUS(status) != 0)
1508                         /* Assume child spat out error. */
1509                         ok = false;
1510         }
1511         if (!ok)
1512                 exit(1);
1513
1514         gettimeofday(&end, NULL);
1515         printf("done\n");
1516
1517         end.tv_sec -= start.tv_sec;
1518         printf("Time replaying: %lu usec\n",
1519                end.tv_sec * 1000000UL + (end.tv_usec - start.tv_usec));
1520         
1521         exit(0);
1522 }