ctdb-daemon: Use correct tdb flags when enabling robust mutex support
[obnox/samba/samba-obnox.git] / ctdb / server / ctdb_lock.c
1 /*
2    ctdb lock handling
3    provide API to do non-blocking locks for single or all databases
4
5    Copyright (C) Amitay Isaacs  2012
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, see <http://www.gnu.org/licenses/>.
19 */
20 #include "includes.h"
21 #include "include/ctdb_private.h"
22 #include "include/ctdb_protocol.h"
23 #include "tevent.h"
24 #include "tdb.h"
25 #include "lib/tdb_wrap/tdb_wrap.h"
26 #include "system/filesys.h"
27 #include "lib/util/dlinklist.h"
28
29 /*
30  * Non-blocking Locking API
31  *
32  * 1. Create a child process to do blocking locks.
33  * 2. Once the locks are obtained, signal parent process via fd.
34  * 3. Invoke registered callback routine with locking status.
35  * 4. If the child process cannot get locks within certain time,
36  *    execute an external script to debug.
37  *
38  * ctdb_lock_record()      - get a lock on a record
39  * ctdb_lock_db()          - get a lock on a DB
40  * ctdb_lock_alldb_prio()  - get a lock on all DBs with given priority
41  * ctdb_lock_alldb()       - get a lock on all DBs
42  *
43  *  auto_mark              - whether to mark/unmark DBs in before/after callback
44  */
45
46 enum lock_type {
47         LOCK_RECORD,
48         LOCK_DB,
49         LOCK_ALLDB_PRIO,
50         LOCK_ALLDB,
51 };
52
53 static const char * const lock_type_str[] = {
54         "lock_record",
55         "lock_db",
56         "lock_alldb_prio",
57         "lock_alldb",
58 };
59
60 struct lock_request;
61
62 /* lock_context is the common part for a lock request */
63 struct lock_context {
64         struct lock_context *next, *prev;
65         enum lock_type type;
66         struct ctdb_context *ctdb;
67         struct ctdb_db_context *ctdb_db;
68         TDB_DATA key;
69         uint32_t priority;
70         bool auto_mark;
71         struct lock_request *request;
72         pid_t child;
73         int fd[2];
74         struct tevent_fd *tfd;
75         struct tevent_timer *ttimer;
76         struct timeval start_time;
77         uint32_t key_hash;
78         bool can_schedule;
79 };
80
81 /* lock_request is the client specific part for a lock request */
82 struct lock_request {
83         struct lock_context *lctx;
84         void (*callback)(void *, bool);
85         void *private_data;
86 };
87
88
89 /*
90  * Support samba 3.6.x (and older) versions which do not set db priority.
91  *
92  * By default, all databases are set to priority 1. So only when priority
93  * is set to 1, check for databases that need higher priority.
94  */
95 static bool later_db(struct ctdb_context *ctdb, const char *name)
96 {
97         if (ctdb->tunable.samba3_hack == 0) {
98                 return false;
99         }
100
101         if (strstr(name, "brlock") ||
102             strstr(name, "g_lock") ||
103             strstr(name, "notify_onelevel") ||
104             strstr(name, "serverid") ||
105             strstr(name, "xattr_tdb")) {
106                 return true;
107         }
108
109         return false;
110 }
111
112 typedef int (*db_handler_t)(struct ctdb_db_context *ctdb_db,
113                             uint32_t priority,
114                             void *private_data);
115
116 static int ctdb_db_iterator(struct ctdb_context *ctdb, uint32_t priority,
117                             db_handler_t handler, void *private_data)
118 {
119         struct ctdb_db_context *ctdb_db;
120         int ret;
121
122         for (ctdb_db = ctdb->db_list; ctdb_db; ctdb_db = ctdb_db->next) {
123                 if (ctdb_db->priority != priority) {
124                         continue;
125                 }
126                 if (later_db(ctdb, ctdb_db->db_name)) {
127                         continue;
128                 }
129                 ret = handler(ctdb_db, priority, private_data);
130                 if (ret != 0) {
131                         return -1;
132                 }
133         }
134
135         /* If priority != 1, later_db check is not required and can return */
136         if (priority != 1) {
137                 return 0;
138         }
139
140         for (ctdb_db = ctdb->db_list; ctdb_db; ctdb_db = ctdb_db->next) {
141                 if (!later_db(ctdb, ctdb_db->db_name)) {
142                         continue;
143                 }
144                 ret = handler(ctdb_db, priority, private_data);
145                 if (ret != 0) {
146                         return -1;
147                 }
148         }
149
150         return 0;
151 }
152
153
154 /*
155  * lock all databases - mark only
156  */
157 static int db_lock_mark_handler(struct ctdb_db_context *ctdb_db, uint32_t priority,
158                                 void *private_data)
159 {
160         int tdb_transaction_write_lock_mark(struct tdb_context *);
161
162         DEBUG(DEBUG_INFO, ("marking locked database %s, priority:%u\n",
163                            ctdb_db->db_name, priority));
164
165         if (tdb_transaction_write_lock_mark(ctdb_db->ltdb->tdb) != 0) {
166                 DEBUG(DEBUG_ERR, ("Failed to mark (transaction lock) database %s\n",
167                                   ctdb_db->db_name));
168                 return -1;
169         }
170
171         if (tdb_lockall_mark(ctdb_db->ltdb->tdb) != 0) {
172                 DEBUG(DEBUG_ERR, ("Failed to mark (all lock) database %s\n",
173                                   ctdb_db->db_name));
174                 return -1;
175         }
176
177         return 0;
178 }
179
180 int ctdb_lockall_mark_prio(struct ctdb_context *ctdb, uint32_t priority)
181 {
182         /*
183          * This function is only used by the main dameon during recovery.
184          * At this stage, the databases have already been locked, by a
185          * dedicated child process. The freeze_mode variable is used to track
186          * whether the actual locks are held by the child process or not.
187          */
188
189         if (ctdb->freeze_mode[priority] != CTDB_FREEZE_FROZEN) {
190                 DEBUG(DEBUG_ERR, ("Attempt to mark all databases locked when not frozen\n"));
191                 return -1;
192         }
193
194         return ctdb_db_iterator(ctdb, priority, db_lock_mark_handler, NULL);
195 }
196
197 static int ctdb_lockall_mark(struct ctdb_context *ctdb)
198 {
199         uint32_t priority;
200
201         for (priority=1; priority<=NUM_DB_PRIORITIES; priority++) {
202                 if (ctdb_db_iterator(ctdb, priority, db_lock_mark_handler, NULL) != 0) {
203                         return -1;
204                 }
205         }
206
207         return 0;
208 }
209
210
211 /*
212  * lock all databases - unmark only
213  */
214 static int db_lock_unmark_handler(struct ctdb_db_context *ctdb_db, uint32_t priority,
215                                   void *private_data)
216 {
217         int tdb_transaction_write_lock_unmark(struct tdb_context *);
218
219         DEBUG(DEBUG_INFO, ("unmarking locked database %s, priority:%u\n",
220                            ctdb_db->db_name, priority));
221
222         if (tdb_transaction_write_lock_unmark(ctdb_db->ltdb->tdb) != 0) {
223                 DEBUG(DEBUG_ERR, ("Failed to unmark (transaction lock) database %s\n",
224                                   ctdb_db->db_name));
225                 return -1;
226         }
227
228         if (tdb_lockall_unmark(ctdb_db->ltdb->tdb) != 0) {
229                 DEBUG(DEBUG_ERR, ("Failed to unmark (all lock) database %s\n",
230                                   ctdb_db->db_name));
231                 return -1;
232         }
233
234         return 0;
235 }
236
237 int ctdb_lockall_unmark_prio(struct ctdb_context *ctdb, uint32_t priority)
238 {
239         /*
240          * This function is only used by the main daemon during recovery.
241          * At this stage, the databases have already been locked, by a
242          * dedicated child process. The freeze_mode variable is used to track
243          * whether the actual locks are held by the child process or not.
244          */
245
246         if (ctdb->freeze_mode[priority] != CTDB_FREEZE_FROZEN) {
247                 DEBUG(DEBUG_ERR, ("Attempt to unmark all databases locked when not frozen\n"));
248                 return -1;
249         }
250
251         return ctdb_db_iterator(ctdb, priority, db_lock_unmark_handler, NULL);
252 }
253
254 static int ctdb_lockall_unmark(struct ctdb_context *ctdb)
255 {
256         uint32_t priority;
257
258         for (priority=NUM_DB_PRIORITIES; priority>0; priority--) {
259                 if (ctdb_db_iterator(ctdb, priority, db_lock_unmark_handler, NULL) != 0) {
260                         return -1;
261                 }
262         }
263
264         return 0;
265 }
266
267
268 static void ctdb_lock_schedule(struct ctdb_context *ctdb);
269
270 /*
271  * Destructor to kill the child locking process
272  */
273 static int ctdb_lock_context_destructor(struct lock_context *lock_ctx)
274 {
275         if (lock_ctx->request) {
276                 lock_ctx->request->lctx = NULL;
277         }
278         if (lock_ctx->child > 0) {
279                 ctdb_kill(lock_ctx->ctdb, lock_ctx->child, SIGKILL);
280                 if (lock_ctx->type == LOCK_RECORD) {
281                         DLIST_REMOVE(lock_ctx->ctdb_db->lock_current, lock_ctx);
282                 } else {
283                         DLIST_REMOVE(lock_ctx->ctdb->lock_current, lock_ctx);
284                 }
285                 if (lock_ctx->ctdb_db) {
286                         lock_ctx->ctdb_db->lock_num_current--;
287                 }
288                 CTDB_DECREMENT_STAT(lock_ctx->ctdb, locks.num_current);
289                 if (lock_ctx->ctdb_db) {
290                         CTDB_DECREMENT_DB_STAT(lock_ctx->ctdb_db, locks.num_current);
291                 }
292         } else {
293                 if (lock_ctx->type == LOCK_RECORD) {
294                         DLIST_REMOVE(lock_ctx->ctdb_db->lock_pending, lock_ctx);
295                 } else {
296                         DLIST_REMOVE(lock_ctx->ctdb->lock_pending, lock_ctx);
297                 }
298                 CTDB_DECREMENT_STAT(lock_ctx->ctdb, locks.num_pending);
299                 if (lock_ctx->ctdb_db) {
300                         CTDB_DECREMENT_DB_STAT(lock_ctx->ctdb_db, locks.num_pending);
301                 }
302         }
303
304         ctdb_lock_schedule(lock_ctx->ctdb);
305
306         return 0;
307 }
308
309
310 /*
311  * Destructor to remove lock request
312  */
313 static int ctdb_lock_request_destructor(struct lock_request *lock_request)
314 {
315         TALLOC_FREE(lock_request->lctx);
316         return 0;
317 }
318
319 /*
320  * Process all the callbacks waiting for lock
321  *
322  * If lock has failed, callback is executed with locked=false
323  */
324 static void process_callbacks(struct lock_context *lock_ctx, bool locked)
325 {
326         struct lock_request *request;
327
328         if (lock_ctx->auto_mark && locked) {
329                 switch (lock_ctx->type) {
330                 case LOCK_RECORD:
331                         tdb_chainlock_mark(lock_ctx->ctdb_db->ltdb->tdb, lock_ctx->key);
332                         break;
333
334                 case LOCK_DB:
335                         tdb_lockall_mark(lock_ctx->ctdb_db->ltdb->tdb);
336                         break;
337
338                 case LOCK_ALLDB_PRIO:
339                         ctdb_lockall_mark_prio(lock_ctx->ctdb, lock_ctx->priority);
340                         break;
341
342                 case LOCK_ALLDB:
343                         ctdb_lockall_mark(lock_ctx->ctdb);
344                         break;
345                 }
346         }
347
348         request = lock_ctx->request;
349         if (lock_ctx->auto_mark) {
350                 /* Reset the destructor, so request is not removed from the list */
351                 talloc_set_destructor(request, NULL);
352         }
353         request->callback(request->private_data, locked);
354
355         if (lock_ctx->auto_mark && locked) {
356                 switch (lock_ctx->type) {
357                 case LOCK_RECORD:
358                         tdb_chainlock_unmark(lock_ctx->ctdb_db->ltdb->tdb, lock_ctx->key);
359                         break;
360
361                 case LOCK_DB:
362                         tdb_lockall_unmark(lock_ctx->ctdb_db->ltdb->tdb);
363                         break;
364
365                 case LOCK_ALLDB_PRIO:
366                         ctdb_lockall_unmark_prio(lock_ctx->ctdb, lock_ctx->priority);
367                         break;
368
369                 case LOCK_ALLDB:
370                         ctdb_lockall_unmark(lock_ctx->ctdb);
371                         break;
372                 }
373         }
374 }
375
376
377 static int lock_bucket_id(double t)
378 {
379         double ms = 1.e-3, s = 1;
380         int id;
381
382         if (t < 1*ms) {
383                 id = 0;
384         } else if (t < 10*ms) {
385                 id = 1;
386         } else if (t < 100*ms) {
387                 id = 2;
388         } else if (t < 1*s) {
389                 id = 3;
390         } else if (t < 2*s) {
391                 id = 4;
392         } else if (t < 4*s) {
393                 id = 5;
394         } else if (t < 8*s) {
395                 id = 6;
396         } else if (t < 16*s) {
397                 id = 7;
398         } else if (t < 32*s) {
399                 id = 8;
400         } else if (t < 64*s) {
401                 id = 9;
402         } else {
403                 id = 10;
404         }
405
406         return id;
407 }
408
409 /*
410  * Callback routine when the required locks are obtained.
411  * Called from parent context
412  */
413 static void ctdb_lock_handler(struct tevent_context *ev,
414                             struct tevent_fd *tfd,
415                             uint16_t flags,
416                             void *private_data)
417 {
418         struct lock_context *lock_ctx;
419         TALLOC_CTX *tmp_ctx = NULL;
420         char c;
421         bool locked;
422         double t;
423         int id;
424
425         lock_ctx = talloc_get_type_abort(private_data, struct lock_context);
426
427         /* cancel the timeout event */
428         TALLOC_FREE(lock_ctx->ttimer);
429
430         t = timeval_elapsed(&lock_ctx->start_time);
431         id = lock_bucket_id(t);
432
433         if (lock_ctx->auto_mark) {
434                 tmp_ctx = talloc_new(ev);
435                 talloc_steal(tmp_ctx, lock_ctx);
436         }
437
438         /* Read the status from the child process */
439         if (sys_read(lock_ctx->fd[0], &c, 1) != 1) {
440                 locked = false;
441         } else {
442                 locked = (c == 0 ? true : false);
443         }
444
445         /* Update statistics */
446         CTDB_INCREMENT_STAT(lock_ctx->ctdb, locks.num_calls);
447         if (lock_ctx->ctdb_db) {
448                 CTDB_INCREMENT_DB_STAT(lock_ctx->ctdb_db, locks.num_calls);
449         }
450
451         if (locked) {
452                 if (lock_ctx->ctdb_db) {
453                         CTDB_INCREMENT_STAT(lock_ctx->ctdb, locks.buckets[id]);
454                         CTDB_UPDATE_LATENCY(lock_ctx->ctdb, lock_ctx->ctdb_db,
455                                             lock_type_str[lock_ctx->type], locks.latency,
456                                             lock_ctx->start_time);
457
458                         CTDB_UPDATE_DB_LATENCY(lock_ctx->ctdb_db, lock_type_str[lock_ctx->type], locks.latency, t);
459                         CTDB_INCREMENT_DB_STAT(lock_ctx->ctdb_db, locks.buckets[id]);
460                 }
461         } else {
462                 CTDB_INCREMENT_STAT(lock_ctx->ctdb, locks.num_failed);
463                 if (lock_ctx->ctdb_db) {
464                         CTDB_INCREMENT_DB_STAT(lock_ctx->ctdb_db, locks.num_failed);
465                 }
466         }
467
468         process_callbacks(lock_ctx, locked);
469
470         if (lock_ctx->auto_mark) {
471                 talloc_free(tmp_ctx);
472         }
473 }
474
475
476 /*
477  * Callback routine when required locks are not obtained within timeout
478  * Called from parent context
479  */
480 static void ctdb_lock_timeout_handler(struct tevent_context *ev,
481                                     struct tevent_timer *ttimer,
482                                     struct timeval current_time,
483                                     void *private_data)
484 {
485         static const char * debug_locks = NULL;
486         struct lock_context *lock_ctx;
487         struct ctdb_context *ctdb;
488         pid_t pid;
489
490         lock_ctx = talloc_get_type_abort(private_data, struct lock_context);
491         ctdb = lock_ctx->ctdb;
492
493         /* If a node stopped/banned, don't spam the logs */
494         if (ctdb->nodes[ctdb->pnn]->flags & NODE_FLAGS_INACTIVE) {
495                 lock_ctx->ttimer = NULL;
496                 return;
497         }
498         if (lock_ctx->ctdb_db) {
499                 DEBUG(DEBUG_WARNING,
500                       ("Unable to get %s lock on database %s for %.0lf seconds\n",
501                        (lock_ctx->type == LOCK_RECORD ? "RECORD" : "DB"),
502                        lock_ctx->ctdb_db->db_name,
503                        timeval_elapsed(&lock_ctx->start_time)));
504         } else {
505                 DEBUG(DEBUG_WARNING,
506                       ("Unable to get ALLDB locks for %.0lf seconds\n",
507                        timeval_elapsed(&lock_ctx->start_time)));
508         }
509
510         /* Fire a child process to find the blocking process. */
511         if (debug_locks == NULL) {
512                 debug_locks = getenv("CTDB_DEBUG_LOCKS");
513                 if (debug_locks == NULL) {
514                         debug_locks = talloc_asprintf(ctdb,
515                                                       "%s/debug_locks.sh",
516                                                       getenv("CTDB_BASE"));
517                 }
518         }
519         if (debug_locks != NULL) {
520                 pid = vfork();
521                 if (pid == 0) {
522                         execl(debug_locks, debug_locks, NULL);
523                         _exit(0);
524                 }
525                 ctdb_track_child(ctdb, pid);
526         } else {
527                 DEBUG(DEBUG_WARNING,
528                       (__location__
529                        " Unable to setup lock debugging - no memory?\n"));
530         }
531
532         /* reset the timeout timer */
533         // talloc_free(lock_ctx->ttimer);
534         lock_ctx->ttimer = tevent_add_timer(ctdb->ev,
535                                             lock_ctx,
536                                             timeval_current_ofs(10, 0),
537                                             ctdb_lock_timeout_handler,
538                                             (void *)lock_ctx);
539 }
540
541
542 static int db_count_handler(struct ctdb_db_context *ctdb_db, uint32_t priority,
543                             void *private_data)
544 {
545         int *count = (int *)private_data;
546
547         (*count) += 2;
548
549         return 0;
550 }
551
552 static int db_flags(struct ctdb_db_context *ctdb_db)
553 {
554         int tdb_flags = TDB_DEFAULT;
555
556 #ifdef TDB_MUTEX_LOCKING
557         if (!ctdb_db->persistent && ctdb_db->ctdb->tunable.mutex_enabled) {
558                 tdb_flags = (TDB_MUTEX_LOCKING | TDB_CLEAR_IF_FIRST);
559         }
560 #endif
561         return tdb_flags;
562 }
563
564 struct db_namelist {
565         const char **names;
566         int n;
567 };
568
569 static int db_name_handler(struct ctdb_db_context *ctdb_db, uint32_t priority,
570                            void *private_data)
571 {
572         struct db_namelist *list = (struct db_namelist *)private_data;
573
574         list->names[list->n] = talloc_strdup(list->names, ctdb_db->db_path);
575         list->names[list->n+1] = talloc_asprintf(list->names, "0x%x",
576                                                  db_flags(ctdb_db));
577         list->n += 2;
578
579         return 0;
580 }
581
582 static bool lock_helper_args(TALLOC_CTX *mem_ctx,
583                              struct lock_context *lock_ctx, int fd,
584                              int *argc, const char ***argv)
585 {
586         struct ctdb_context *ctdb = lock_ctx->ctdb;
587         const char **args = NULL;
588         int nargs, i;
589         int priority;
590         struct db_namelist list;
591
592         switch (lock_ctx->type) {
593         case LOCK_RECORD:
594                 nargs = 6;
595                 break;
596
597         case LOCK_DB:
598                 nargs = 5;
599                 break;
600
601         case LOCK_ALLDB_PRIO:
602                 nargs = 3;
603                 ctdb_db_iterator(ctdb, lock_ctx->priority, db_count_handler, &nargs);
604                 break;
605
606         case LOCK_ALLDB:
607                 nargs = 3;
608                 for (priority=1; priority<NUM_DB_PRIORITIES; priority++) {
609                         ctdb_db_iterator(ctdb, priority, db_count_handler, &nargs);
610                 }
611                 break;
612         }
613
614         /* Add extra argument for null termination */
615         nargs++;
616
617         args = talloc_array(mem_ctx, const char *, nargs);
618         if (args == NULL) {
619                 return false;
620         }
621
622         args[0] = talloc_asprintf(args, "%d", getpid());
623         args[1] = talloc_asprintf(args, "%d", fd);
624
625         switch (lock_ctx->type) {
626         case LOCK_RECORD:
627                 args[2] = talloc_strdup(args, "RECORD");
628                 args[3] = talloc_strdup(args, lock_ctx->ctdb_db->db_path);
629                 args[4] = talloc_asprintf(args, "0x%x",
630                                           db_flags(lock_ctx->ctdb_db));
631                 if (lock_ctx->key.dsize == 0) {
632                         args[5] = talloc_strdup(args, "NULL");
633                 } else {
634                         args[5] = hex_encode_talloc(args, lock_ctx->key.dptr, lock_ctx->key.dsize);
635                 }
636                 break;
637
638         case LOCK_DB:
639                 args[2] = talloc_strdup(args, "DB");
640                 args[3] = talloc_strdup(args, lock_ctx->ctdb_db->db_path);
641                 args[4] = talloc_asprintf(args, "0x%x",
642                                           db_flags(lock_ctx->ctdb_db));
643                 break;
644
645         case LOCK_ALLDB_PRIO:
646                 args[2] = talloc_strdup(args, "DB");
647                 list.names = args;
648                 list.n = 3;
649                 ctdb_db_iterator(ctdb, lock_ctx->priority, db_name_handler, &list);
650                 break;
651
652         case LOCK_ALLDB:
653                 args[2] = talloc_strdup(args, "DB");
654                 list.names = args;
655                 list.n = 3;
656                 for (priority=1; priority<NUM_DB_PRIORITIES; priority++) {
657                         ctdb_db_iterator(ctdb, priority, db_name_handler, &list);
658                 }
659                 break;
660         }
661
662         /* Make sure last argument is NULL */
663         args[nargs-1] = NULL;
664
665         for (i=0; i<nargs-1; i++) {
666                 if (args[i] == NULL) {
667                         talloc_free(args);
668                         return false;
669                 }
670         }
671
672         *argc = nargs;
673         *argv = args;
674         return true;
675 }
676
677 /*
678  * Find a lock request that can be scheduled
679  */
680 static struct lock_context *ctdb_find_lock_context(struct ctdb_context *ctdb)
681 {
682         struct lock_context *lock_ctx, *next_ctx;
683         struct ctdb_db_context *ctdb_db;
684
685         /* First check if there are database lock requests */
686
687         for (lock_ctx = ctdb->lock_pending; lock_ctx != NULL;
688              lock_ctx = next_ctx) {
689
690                 if (lock_ctx->request != NULL) {
691                         /* Found a lock context with a request */
692                         return lock_ctx;
693                 }
694
695                 next_ctx = lock_ctx->next;
696
697                 DEBUG(DEBUG_INFO, ("Removing lock context without lock "
698                                    "request\n"));
699                 DLIST_REMOVE(ctdb->lock_pending, lock_ctx);
700                 CTDB_DECREMENT_STAT(ctdb, locks.num_pending);
701                 if (lock_ctx->ctdb_db) {
702                         CTDB_DECREMENT_DB_STAT(lock_ctx->ctdb_db,
703                                                locks.num_pending);
704                 }
705                 talloc_free(lock_ctx);
706         }
707
708         /* Next check database queues */
709         for (ctdb_db = ctdb->db_list; ctdb_db; ctdb_db = ctdb_db->next) {
710                 if (ctdb_db->lock_num_current ==
711                     ctdb->tunable.lock_processes_per_db) {
712                         continue;
713                 }
714
715                 for (lock_ctx = ctdb_db->lock_pending; lock_ctx != NULL;
716                      lock_ctx = next_ctx) {
717
718                         next_ctx = lock_ctx->next;
719
720                         if (lock_ctx->request != NULL) {
721                                 return lock_ctx;
722                         }
723
724                         DEBUG(DEBUG_INFO, ("Removing lock context without "
725                                            "lock request\n"));
726                         DLIST_REMOVE(ctdb_db->lock_pending, lock_ctx);
727                         CTDB_DECREMENT_STAT(ctdb, locks.num_pending);
728                         CTDB_DECREMENT_DB_STAT(ctdb_db, locks.num_pending);
729                         talloc_free(lock_ctx);
730                 }
731         }
732
733         return NULL;
734 }
735
736 /*
737  * Schedule a new lock child process
738  * Set up callback handler and timeout handler
739  */
740 static void ctdb_lock_schedule(struct ctdb_context *ctdb)
741 {
742         struct lock_context *lock_ctx;
743         int ret, argc;
744         TALLOC_CTX *tmp_ctx;
745         const char *helper = CTDB_HELPER_BINDIR "/ctdb_lock_helper";
746         static const char *prog = NULL;
747         const char **args;
748
749         if (prog == NULL) {
750                 const char *t;
751
752                 t = getenv("CTDB_LOCK_HELPER");
753                 if (t != NULL) {
754                         prog = talloc_strdup(ctdb, t);
755                 } else {
756                         prog = talloc_strdup(ctdb, helper);
757                 }
758                 CTDB_NO_MEMORY_VOID(ctdb, prog);
759         }
760
761         /* Find a lock context with requests */
762         lock_ctx = ctdb_find_lock_context(ctdb);
763         if (lock_ctx == NULL) {
764                 return;
765         }
766
767         lock_ctx->child = -1;
768         ret = pipe(lock_ctx->fd);
769         if (ret != 0) {
770                 DEBUG(DEBUG_ERR, ("Failed to create pipe in ctdb_lock_schedule\n"));
771                 return;
772         }
773
774         set_close_on_exec(lock_ctx->fd[0]);
775
776         /* Create data for child process */
777         tmp_ctx = talloc_new(lock_ctx);
778         if (tmp_ctx == NULL) {
779                 DEBUG(DEBUG_ERR, ("Failed to allocate memory for helper args\n"));
780                 close(lock_ctx->fd[0]);
781                 close(lock_ctx->fd[1]);
782                 return;
783         }
784
785         /* Create arguments for lock helper */
786         if (!lock_helper_args(tmp_ctx, lock_ctx, lock_ctx->fd[1],
787                               &argc, &args)) {
788                 DEBUG(DEBUG_ERR, ("Failed to create lock helper args\n"));
789                 close(lock_ctx->fd[0]);
790                 close(lock_ctx->fd[1]);
791                 talloc_free(tmp_ctx);
792                 return;
793         }
794
795         if (!ctdb_vfork_with_logging(lock_ctx, ctdb, "lock_helper",
796                                      prog, argc, (const char **)args,
797                                      NULL, NULL, &lock_ctx->child)) {
798                 DEBUG(DEBUG_ERR, ("Failed to create a child in ctdb_lock_schedule\n"));
799                 close(lock_ctx->fd[0]);
800                 close(lock_ctx->fd[1]);
801                 talloc_free(tmp_ctx);
802                 return;
803         }
804
805         /* Parent process */
806         close(lock_ctx->fd[1]);
807
808         talloc_set_destructor(lock_ctx, ctdb_lock_context_destructor);
809
810         talloc_free(tmp_ctx);
811
812         /* Set up timeout handler */
813         lock_ctx->ttimer = tevent_add_timer(ctdb->ev,
814                                             lock_ctx,
815                                             timeval_current_ofs(10, 0),
816                                             ctdb_lock_timeout_handler,
817                                             (void *)lock_ctx);
818         if (lock_ctx->ttimer == NULL) {
819                 ctdb_kill(ctdb, lock_ctx->child, SIGKILL);
820                 lock_ctx->child = -1;
821                 talloc_set_destructor(lock_ctx, NULL);
822                 close(lock_ctx->fd[0]);
823                 return;
824         }
825
826         /* Set up callback */
827         lock_ctx->tfd = tevent_add_fd(ctdb->ev,
828                                       lock_ctx,
829                                       lock_ctx->fd[0],
830                                       EVENT_FD_READ,
831                                       ctdb_lock_handler,
832                                       (void *)lock_ctx);
833         if (lock_ctx->tfd == NULL) {
834                 TALLOC_FREE(lock_ctx->ttimer);
835                 ctdb_kill(ctdb, lock_ctx->child, SIGKILL);
836                 lock_ctx->child = -1;
837                 talloc_set_destructor(lock_ctx, NULL);
838                 close(lock_ctx->fd[0]);
839                 return;
840         }
841         tevent_fd_set_auto_close(lock_ctx->tfd);
842
843         /* Move the context from pending to current */
844         if (lock_ctx->type == LOCK_RECORD) {
845                 DLIST_REMOVE(lock_ctx->ctdb_db->lock_pending, lock_ctx);
846                 DLIST_ADD_END(lock_ctx->ctdb_db->lock_current, lock_ctx, NULL);
847         } else {
848                 DLIST_REMOVE(ctdb->lock_pending, lock_ctx);
849                 DLIST_ADD_END(ctdb->lock_current, lock_ctx, NULL);
850         }
851         CTDB_DECREMENT_STAT(lock_ctx->ctdb, locks.num_pending);
852         CTDB_INCREMENT_STAT(lock_ctx->ctdb, locks.num_current);
853         if (lock_ctx->ctdb_db) {
854                 lock_ctx->ctdb_db->lock_num_current++;
855                 CTDB_DECREMENT_DB_STAT(lock_ctx->ctdb_db, locks.num_pending);
856                 CTDB_INCREMENT_DB_STAT(lock_ctx->ctdb_db, locks.num_current);
857         }
858 }
859
860
861 /*
862  * Lock record / db depending on type
863  */
864 static struct lock_request *ctdb_lock_internal(TALLOC_CTX *mem_ctx,
865                                                struct ctdb_context *ctdb,
866                                                struct ctdb_db_context *ctdb_db,
867                                                TDB_DATA key,
868                                                uint32_t priority,
869                                                void (*callback)(void *, bool),
870                                                void *private_data,
871                                                enum lock_type type,
872                                                bool auto_mark)
873 {
874         struct lock_context *lock_ctx = NULL;
875         struct lock_request *request;
876
877         if (callback == NULL) {
878                 DEBUG(DEBUG_WARNING, ("No callback function specified, not locking\n"));
879                 return NULL;
880         }
881
882         lock_ctx = talloc_zero(ctdb, struct lock_context);
883         if (lock_ctx == NULL) {
884                 DEBUG(DEBUG_ERR, ("Failed to create a new lock context\n"));
885                 return NULL;
886         }
887
888         if ((request = talloc_zero(mem_ctx, struct lock_request)) == NULL) {
889                 talloc_free(lock_ctx);
890                 return NULL;
891         }
892
893         lock_ctx->type = type;
894         lock_ctx->ctdb = ctdb;
895         lock_ctx->ctdb_db = ctdb_db;
896         lock_ctx->key.dsize = key.dsize;
897         if (key.dsize > 0) {
898                 lock_ctx->key.dptr = talloc_memdup(lock_ctx, key.dptr, key.dsize);
899                 if (lock_ctx->key.dptr == NULL) {
900                         DEBUG(DEBUG_ERR, (__location__ "Memory allocation error\n"));
901                         talloc_free(lock_ctx);
902                         return NULL;
903                 }
904                 lock_ctx->key_hash = ctdb_hash(&key);
905         } else {
906                 lock_ctx->key.dptr = NULL;
907         }
908         lock_ctx->priority = priority;
909         lock_ctx->auto_mark = auto_mark;
910
911         lock_ctx->request = request;
912         lock_ctx->child = -1;
913
914         /* Non-record locks are required by recovery and should be scheduled
915          * immediately, so keep them at the head of the pending queue.
916          */
917         if (lock_ctx->type == LOCK_RECORD) {
918                 DLIST_ADD_END(ctdb_db->lock_pending, lock_ctx, NULL);
919         } else {
920                 DLIST_ADD_END(ctdb->lock_pending, lock_ctx, NULL);
921         }
922         CTDB_INCREMENT_STAT(ctdb, locks.num_pending);
923         if (ctdb_db) {
924                 CTDB_INCREMENT_DB_STAT(ctdb_db, locks.num_pending);
925         }
926
927         /* Start the timer when we activate the context */
928         lock_ctx->start_time = timeval_current();
929
930         request->lctx = lock_ctx;
931         request->callback = callback;
932         request->private_data = private_data;
933
934         talloc_set_destructor(request, ctdb_lock_request_destructor);
935
936         ctdb_lock_schedule(ctdb);
937
938         return request;
939 }
940
941
942 /*
943  * obtain a lock on a record in a database
944  */
945 struct lock_request *ctdb_lock_record(TALLOC_CTX *mem_ctx,
946                                       struct ctdb_db_context *ctdb_db,
947                                       TDB_DATA key,
948                                       bool auto_mark,
949                                       void (*callback)(void *, bool),
950                                       void *private_data)
951 {
952         return ctdb_lock_internal(mem_ctx,
953                                   ctdb_db->ctdb,
954                                   ctdb_db,
955                                   key,
956                                   0,
957                                   callback,
958                                   private_data,
959                                   LOCK_RECORD,
960                                   auto_mark);
961 }
962
963
964 /*
965  * obtain a lock on a database
966  */
967 struct lock_request *ctdb_lock_db(TALLOC_CTX *mem_ctx,
968                                   struct ctdb_db_context *ctdb_db,
969                                   bool auto_mark,
970                                   void (*callback)(void *, bool),
971                                   void *private_data)
972 {
973         return ctdb_lock_internal(mem_ctx,
974                                   ctdb_db->ctdb,
975                                   ctdb_db,
976                                   tdb_null,
977                                   0,
978                                   callback,
979                                   private_data,
980                                   LOCK_DB,
981                                   auto_mark);
982 }
983
984
985 /*
986  * obtain locks on all databases of specified priority
987  */
988 struct lock_request *ctdb_lock_alldb_prio(TALLOC_CTX *mem_ctx,
989                                           struct ctdb_context *ctdb,
990                                           uint32_t priority,
991                                           bool auto_mark,
992                                           void (*callback)(void *, bool),
993                                           void *private_data)
994 {
995         if (priority < 1 || priority > NUM_DB_PRIORITIES) {
996                 DEBUG(DEBUG_ERR, ("Invalid db priority: %u\n", priority));
997                 return NULL;
998         }
999
1000         return ctdb_lock_internal(mem_ctx,
1001                                   ctdb,
1002                                   NULL,
1003                                   tdb_null,
1004                                   priority,
1005                                   callback,
1006                                   private_data,
1007                                   LOCK_ALLDB_PRIO,
1008                                   auto_mark);
1009 }
1010
1011
1012 /*
1013  * obtain locks on all databases
1014  */
1015 struct lock_request *ctdb_lock_alldb(TALLOC_CTX *mem_ctx,
1016                                      struct ctdb_context *ctdb,
1017                                      bool auto_mark,
1018                                      void (*callback)(void *, bool),
1019                                      void *private_data)
1020 {
1021         return ctdb_lock_internal(mem_ctx,
1022                                   ctdb,
1023                                   NULL,
1024                                   tdb_null,
1025                                   0,
1026                                   callback,
1027                                   private_data,
1028                                   LOCK_ALLDB,
1029                                   auto_mark);
1030 }
1031