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