]> git.ozlabs.org Git - ccan/blob - ccan/tdb2/open.c
83a83e0ba578b75e873c7900a140f08b7cf00b22
[ccan] / ccan / tdb2 / open.c
1  /*
2    Trivial Database 2: opening and closing TDBs
3    Copyright (C) Rusty Russell 2010
4
5    This library is free software; you can redistribute it and/or
6    modify it under the terms of the GNU Lesser General Public
7    License as published by the Free Software Foundation; either
8    version 3 of the License, or (at your option) any later version.
9
10    This library is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    Lesser General Public License for more details.
14
15    You should have received a copy of the GNU Lesser General Public
16    License along with this library; if not, see <http://www.gnu.org/licenses/>.
17 */
18 #include "private.h"
19 #include <ccan/hash/hash.h>
20 #include <assert.h>
21
22 /* all lock info, to detect double-opens (fcntl file don't nest!) */
23 static struct tdb_file *files = NULL;
24
25 static struct tdb_file *find_file(dev_t device, ino_t ino)
26 {
27         struct tdb_file *i;
28
29         for (i = files; i; i = i->next) {
30                 if (i->device == device && i->inode == ino) {
31                         i->refcnt++;
32                         break;
33                 }
34         }
35         return i;
36 }
37
38 static bool read_all(int fd, void *buf, size_t len)
39 {
40         while (len) {
41                 ssize_t ret;
42                 ret = read(fd, buf, len);
43                 if (ret < 0)
44                         return false;
45                 if (ret == 0) {
46                         /* ETOOSHORT? */
47                         errno = EWOULDBLOCK;
48                         return false;
49                 }
50                 buf = (char *)buf + ret;
51                 len -= ret;
52         }
53         return true;
54 }
55
56 static uint64_t random_number(struct tdb_context *tdb)
57 {
58         int fd;
59         uint64_t ret = 0;
60         struct timeval now;
61
62         fd = open("/dev/urandom", O_RDONLY);
63         if (fd >= 0) {
64                 if (read_all(fd, &ret, sizeof(ret))) {
65                         close(fd);
66                         return ret;
67                 }
68                 close(fd);
69         }
70         /* FIXME: Untested!  Based on Wikipedia protocol description! */
71         fd = open("/dev/egd-pool", O_RDWR);
72         if (fd >= 0) {
73                 /* Command is 1, next byte is size we want to read. */
74                 char cmd[2] = { 1, sizeof(uint64_t) };
75                 if (write(fd, cmd, sizeof(cmd)) == sizeof(cmd)) {
76                         char reply[1 + sizeof(uint64_t)];
77                         int r = read(fd, reply, sizeof(reply));
78                         if (r > 1) {
79                                 /* Copy at least some bytes. */
80                                 memcpy(&ret, reply+1, r - 1);
81                                 if (reply[0] == sizeof(uint64_t)
82                                     && r == sizeof(reply)) {
83                                         close(fd);
84                                         return ret;
85                                 }
86                         }
87                 }
88                 close(fd);
89         }
90
91         /* Fallback: pid and time. */
92         gettimeofday(&now, NULL);
93         ret = getpid() * 100132289ULL + now.tv_sec * 1000000ULL + now.tv_usec;
94         tdb_logerr(tdb, TDB_SUCCESS, TDB_LOG_WARNING,
95                    "tdb_open: random from getpid and time");
96         return ret;
97 }
98
99 struct new_database {
100         struct tdb_header hdr;
101         struct tdb_freetable ftable;
102 };
103
104 /* initialise a new database */
105 static enum TDB_ERROR tdb_new_database(struct tdb_context *tdb,
106                                        struct tdb_attribute_seed *seed,
107                                        struct tdb_header *hdr)
108 {
109         /* We make it up in memory, then write it out if not internal */
110         struct new_database newdb;
111         unsigned int magic_len;
112         ssize_t rlen;
113         enum TDB_ERROR ecode;
114
115         /* Fill in the header */
116         newdb.hdr.version = TDB_VERSION;
117         if (seed)
118                 newdb.hdr.hash_seed = seed->seed;
119         else
120                 newdb.hdr.hash_seed = random_number(tdb);
121         newdb.hdr.hash_test = TDB_HASH_MAGIC;
122         newdb.hdr.hash_test = tdb->hash_fn(&newdb.hdr.hash_test,
123                                            sizeof(newdb.hdr.hash_test),
124                                            newdb.hdr.hash_seed,
125                                            tdb->hash_data);
126         newdb.hdr.recovery = 0;
127         newdb.hdr.features_used = newdb.hdr.features_offered = TDB_FEATURE_MASK;
128         newdb.hdr.seqnum = 0;
129         memset(newdb.hdr.reserved, 0, sizeof(newdb.hdr.reserved));
130         /* Initial hashes are empty. */
131         memset(newdb.hdr.hashtable, 0, sizeof(newdb.hdr.hashtable));
132
133         /* Free is empty. */
134         newdb.hdr.free_table = offsetof(struct new_database, ftable);
135         memset(&newdb.ftable, 0, sizeof(newdb.ftable));
136         ecode = set_header(NULL, &newdb.ftable.hdr, TDB_FTABLE_MAGIC, 0,
137                            sizeof(newdb.ftable) - sizeof(newdb.ftable.hdr),
138                            sizeof(newdb.ftable) - sizeof(newdb.ftable.hdr),
139                            0);
140         if (ecode != TDB_SUCCESS) {
141                 return ecode;
142         }
143
144         /* Magic food */
145         memset(newdb.hdr.magic_food, 0, sizeof(newdb.hdr.magic_food));
146         strcpy(newdb.hdr.magic_food, TDB_MAGIC_FOOD);
147
148         /* This creates an endian-converted database, as if read from disk */
149         magic_len = sizeof(newdb.hdr.magic_food);
150         tdb_convert(tdb,
151                     (char *)&newdb.hdr + magic_len, sizeof(newdb) - magic_len);
152
153         *hdr = newdb.hdr;
154
155         if (tdb->flags & TDB_INTERNAL) {
156                 tdb->file->map_size = sizeof(newdb);
157                 tdb->file->map_ptr = malloc(tdb->file->map_size);
158                 if (!tdb->file->map_ptr) {
159                         return tdb_logerr(tdb, TDB_ERR_OOM, TDB_LOG_ERROR,
160                                           "tdb_new_database:"
161                                           " failed to allocate");
162                 }
163                 memcpy(tdb->file->map_ptr, &newdb, tdb->file->map_size);
164                 return TDB_SUCCESS;
165         }
166         if (lseek(tdb->file->fd, 0, SEEK_SET) == -1) {
167                 return tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
168                                   "tdb_new_database:"
169                                   " failed to seek: %s", strerror(errno));
170         }
171
172         if (ftruncate(tdb->file->fd, 0) == -1) {
173                 return tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
174                                   "tdb_new_database:"
175                                   " failed to truncate: %s", strerror(errno));
176         }
177
178         rlen = write(tdb->file->fd, &newdb, sizeof(newdb));
179         if (rlen != sizeof(newdb)) {
180                 if (rlen >= 0)
181                         errno = ENOSPC;
182                 return tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
183                                   "tdb_new_database: %zi writing header: %s",
184                                   rlen, strerror(errno));
185         }
186         return TDB_SUCCESS;
187 }
188
189 static enum TDB_ERROR tdb_new_file(struct tdb_context *tdb)
190 {
191         tdb->file = malloc(sizeof(*tdb->file));
192         if (!tdb->file)
193                 return tdb_logerr(tdb, TDB_ERR_OOM, TDB_LOG_ERROR,
194                                   "tdb_open: cannot alloc tdb_file structure");
195         tdb->file->num_lockrecs = 0;
196         tdb->file->lockrecs = NULL;
197         tdb->file->allrecord_lock.count = 0;
198         tdb->file->refcnt = 1;
199         return TDB_SUCCESS;
200 }
201
202 enum TDB_ERROR tdb_set_attribute(struct tdb_context *tdb,
203                                  const union tdb_attribute *attr)
204 {
205         switch (attr->base.attr) {
206         case TDB_ATTRIBUTE_LOG:
207                 tdb->log_fn = attr->log.fn;
208                 tdb->log_data = attr->log.data;
209                 break;
210         case TDB_ATTRIBUTE_HASH:
211         case TDB_ATTRIBUTE_SEED:
212         case TDB_ATTRIBUTE_OPENHOOK:
213                 return tdb->last_error
214                         = tdb_logerr(tdb, TDB_ERR_EINVAL,
215                                      TDB_LOG_USE_ERROR,
216                                      "tdb_set_attribute:"
217                                      " cannot set %s after opening",
218                                      attr->base.attr == TDB_ATTRIBUTE_HASH
219                                      ? "TDB_ATTRIBUTE_HASH"
220                                      : attr->base.attr == TDB_ATTRIBUTE_SEED
221                                      ? "TDB_ATTRIBUTE_SEED"
222                                      : "TDB_ATTRIBUTE_OPENHOOK");
223         case TDB_ATTRIBUTE_STATS:
224                 return tdb->last_error
225                         = tdb_logerr(tdb, TDB_ERR_EINVAL,
226                                      TDB_LOG_USE_ERROR,
227                                      "tdb_set_attribute:"
228                                      " cannot set TDB_ATTRIBUTE_STATS");
229         case TDB_ATTRIBUTE_FLOCK:
230                 tdb->lock_fn = attr->flock.lock;
231                 tdb->unlock_fn = attr->flock.unlock;
232                 tdb->lock_data = attr->flock.data;
233                 break;
234         default:
235                 return tdb->last_error
236                         = tdb_logerr(tdb, TDB_ERR_EINVAL,
237                                      TDB_LOG_USE_ERROR,
238                                      "tdb_set_attribute:"
239                                      " unknown attribute type %u",
240                                      attr->base.attr);
241         }
242         return TDB_SUCCESS;
243 }
244
245 static uint64_t jenkins_hash(const void *key, size_t length, uint64_t seed,
246                              void *unused)
247 {
248         uint64_t ret;
249         /* hash64_stable assumes lower bits are more important; they are a
250          * slightly better hash.  We use the upper bits first, so swap them. */
251         ret = hash64_stable((const unsigned char *)key, length, seed);
252         return (ret >> 32) | (ret << 32);
253 }
254
255 enum TDB_ERROR tdb_get_attribute(struct tdb_context *tdb,
256                                  union tdb_attribute *attr)
257 {
258         switch (attr->base.attr) {
259         case TDB_ATTRIBUTE_LOG:
260                 if (!tdb->log_fn)
261                         return tdb->last_error = TDB_ERR_NOEXIST;
262                 attr->log.fn = tdb->log_fn;
263                 attr->log.data = tdb->log_data;
264                 break;
265         case TDB_ATTRIBUTE_HASH:
266                 attr->hash.fn = tdb->hash_fn;
267                 attr->hash.data = tdb->hash_data;
268                 break;
269         case TDB_ATTRIBUTE_SEED:
270                 attr->seed.seed = tdb->hash_seed;
271                 break;
272         case TDB_ATTRIBUTE_OPENHOOK:
273                 return tdb->last_error
274                         = tdb_logerr(tdb, TDB_ERR_EINVAL,
275                                      TDB_LOG_USE_ERROR,
276                                      "tdb_get_attribute:"
277                                      " cannot get TDB_ATTRIBUTE_OPENHOOK");
278         case TDB_ATTRIBUTE_STATS: {
279                 size_t size = attr->stats.size;
280                 if (size > tdb->stats.size)
281                         size = tdb->stats.size;
282                 memcpy(&attr->stats, &tdb->stats, size);
283                 break;
284         }
285         case TDB_ATTRIBUTE_FLOCK:
286                 attr->flock.lock = tdb->lock_fn;
287                 attr->flock.unlock = tdb->unlock_fn;
288                 attr->flock.data = tdb->lock_data;
289                 break;
290         default:
291                 return tdb->last_error
292                         = tdb_logerr(tdb, TDB_ERR_EINVAL,
293                                      TDB_LOG_USE_ERROR,
294                                      "tdb_get_attribute:"
295                                      " unknown attribute type %u",
296                                      attr->base.attr);
297         }
298         attr->base.next = NULL;
299         return TDB_SUCCESS;
300 }
301
302 void tdb_unset_attribute(struct tdb_context *tdb,
303                          enum tdb_attribute_type type)
304 {
305         switch (type) {
306         case TDB_ATTRIBUTE_LOG:
307                 tdb->log_fn = NULL;
308                 break;
309         case TDB_ATTRIBUTE_HASH:
310         case TDB_ATTRIBUTE_SEED:
311         case TDB_ATTRIBUTE_OPENHOOK:
312                 tdb_logerr(tdb, TDB_ERR_EINVAL, TDB_LOG_USE_ERROR,
313                            "tdb_unset_attribute: cannot unset %s after opening",
314                            type == TDB_ATTRIBUTE_HASH
315                            ? "TDB_ATTRIBUTE_HASH"
316                            : type == TDB_ATTRIBUTE_SEED
317                            ? "TDB_ATTRIBUTE_SEED"
318                            : "TDB_ATTRIBUTE_OPENHOOK");
319                 break;
320         case TDB_ATTRIBUTE_STATS:
321                 tdb_logerr(tdb, TDB_ERR_EINVAL,
322                            TDB_LOG_USE_ERROR,
323                            "tdb_unset_attribute:"
324                            "cannot unset TDB_ATTRIBUTE_STATS");
325                 break;
326         case TDB_ATTRIBUTE_FLOCK:
327                 tdb->lock_fn = tdb_fcntl_lock;
328                 tdb->unlock_fn = tdb_fcntl_unlock;
329                 break;
330         default:
331                 tdb_logerr(tdb, TDB_ERR_EINVAL,
332                            TDB_LOG_USE_ERROR,
333                            "tdb_unset_attribute: unknown attribute type %u",
334                            type);
335         }
336 }
337
338 struct tdb_context *tdb_open(const char *name, int tdb_flags,
339                              int open_flags, mode_t mode,
340                              union tdb_attribute *attr)
341 {
342         struct tdb_context *tdb;
343         struct stat st;
344         int saved_errno = 0;
345         uint64_t hash_test;
346         unsigned v;
347         ssize_t rlen;
348         struct tdb_header hdr;
349         struct tdb_attribute_seed *seed = NULL;
350         struct tdb_attribute_openhook *openhook = NULL;
351         tdb_bool_err berr;
352         enum TDB_ERROR ecode;
353         int openlock;
354
355         tdb = malloc(sizeof(*tdb) + (name ? strlen(name) + 1 : 0));
356         if (!tdb) {
357                 /* Can't log this */
358                 errno = ENOMEM;
359                 return NULL;
360         }
361         /* Set name immediately for logging functions. */
362         if (name) {
363                 tdb->name = strcpy((char *)(tdb + 1), name);
364         } else {
365                 tdb->name = NULL;
366         }
367         tdb->direct_access = 0;
368         tdb->flags = tdb_flags;
369         tdb->log_fn = NULL;
370         tdb->transaction = NULL;
371         tdb->access = NULL;
372         tdb->open_flags = open_flags;
373         tdb->last_error = TDB_SUCCESS;
374         tdb->file = NULL;
375         tdb->lock_fn = tdb_fcntl_lock;
376         tdb->unlock_fn = tdb_fcntl_unlock;
377         tdb->hash_fn = jenkins_hash;
378         memset(&tdb->stats, 0, sizeof(tdb->stats));
379         tdb->stats.base.attr = TDB_ATTRIBUTE_STATS;
380         tdb->stats.size = sizeof(tdb->stats);
381         tdb_io_init(tdb);
382
383         while (attr) {
384                 switch (attr->base.attr) {
385                 case TDB_ATTRIBUTE_HASH:
386                         tdb->hash_fn = attr->hash.fn;
387                         tdb->hash_data = attr->hash.data;
388                         break;
389                 case TDB_ATTRIBUTE_SEED:
390                         seed = &attr->seed;
391                         break;
392                 case TDB_ATTRIBUTE_OPENHOOK:
393                         openhook = &attr->openhook;
394                         break;
395                 default:
396                         /* These are set as normal. */
397                         ecode = tdb_set_attribute(tdb, attr);
398                         if (ecode != TDB_SUCCESS)
399                                 goto fail;
400                 }
401                 attr = attr->base.next;
402         }
403
404         if (tdb_flags & ~(TDB_INTERNAL | TDB_NOLOCK | TDB_NOMMAP | TDB_CONVERT
405                           | TDB_NOSYNC | TDB_SEQNUM | TDB_ALLOW_NESTING)) {
406                 ecode = tdb_logerr(tdb, TDB_ERR_EINVAL, TDB_LOG_USE_ERROR,
407                                    "tdb_open: unknown flags %u", tdb_flags);
408                 goto fail;
409         }
410
411         if ((open_flags & O_ACCMODE) == O_WRONLY) {
412                 ecode = tdb_logerr(tdb, TDB_ERR_EINVAL, TDB_LOG_USE_ERROR,
413                                    "tdb_open: can't open tdb %s write-only",
414                                    name);
415                 goto fail;
416         }
417
418         if ((open_flags & O_ACCMODE) == O_RDONLY) {
419                 tdb->read_only = true;
420                 openlock = F_RDLCK;
421         } else {
422                 tdb->read_only = false;
423                 openlock = F_WRLCK;
424         }
425
426         /* internal databases don't need any of the rest. */
427         if (tdb->flags & TDB_INTERNAL) {
428                 tdb->flags |= (TDB_NOLOCK | TDB_NOMMAP);
429                 ecode = tdb_new_file(tdb);
430                 if (ecode != TDB_SUCCESS) {
431                         goto fail;
432                 }
433                 tdb->file->fd = -1;
434                 ecode = tdb_new_database(tdb, seed, &hdr);
435                 if (ecode != TDB_SUCCESS) {
436                         goto fail;
437                 }
438                 tdb_convert(tdb, &hdr.hash_seed, sizeof(hdr.hash_seed));
439                 tdb->hash_seed = hdr.hash_seed;
440                 tdb_ftable_init(tdb);
441                 return tdb;
442         }
443
444         if (stat(name, &st) != -1)
445                 tdb->file = find_file(st.st_dev, st.st_ino);
446
447         if (!tdb->file) {
448                 int fd;
449
450                 if ((fd = open(name, open_flags, mode)) == -1) {
451                         /* errno set by open(2) */
452                         saved_errno = errno;
453                         tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
454                                    "tdb_open: could not open file %s: %s",
455                                    name, strerror(errno));
456                         goto fail_errno;
457                 }
458
459                 /* on exec, don't inherit the fd */
460                 v = fcntl(fd, F_GETFD, 0);
461                 fcntl(fd, F_SETFD, v | FD_CLOEXEC);
462
463                 if (fstat(fd, &st) == -1) {
464                         saved_errno = errno;
465                         tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
466                                    "tdb_open: could not stat open %s: %s",
467                                    name, strerror(errno));
468                         close(fd);
469                         goto fail_errno;
470                 }
471
472                 ecode = tdb_new_file(tdb);
473                 if (ecode != TDB_SUCCESS) {
474                         close(fd);
475                         goto fail;
476                 }
477
478                 tdb->file->next = files;
479                 tdb->file->fd = fd;
480                 tdb->file->device = st.st_dev;
481                 tdb->file->inode = st.st_ino;
482                 tdb->file->map_ptr = NULL;
483                 tdb->file->map_size = sizeof(struct tdb_header);
484         }
485
486         /* ensure there is only one process initialising at once */
487         ecode = tdb_lock_open(tdb, openlock, TDB_LOCK_WAIT|TDB_LOCK_NOCHECK);
488         if (ecode != TDB_SUCCESS) {
489                 saved_errno = errno;
490                 goto fail_errno;
491         }
492
493         /* call their open hook if they gave us one. */
494         if (openhook) {
495                 ecode = openhook->fn(tdb->file->fd, openhook->data);
496                 if (ecode != TDB_SUCCESS) {
497                         tdb_logerr(tdb, ecode, TDB_LOG_ERROR,
498                                    "tdb_open: open hook failed");
499                         goto fail;
500                 }
501                 open_flags |= O_CREAT;
502         }
503
504         /* If they used O_TRUNC, read will return 0. */
505         rlen = pread(tdb->file->fd, &hdr, sizeof(hdr), 0);
506         if (rlen == 0 && (open_flags & O_CREAT)) {
507                 ecode = tdb_new_database(tdb, seed, &hdr);
508                 if (ecode != TDB_SUCCESS) {
509                         goto fail;
510                 }
511         } else if (rlen < 0) {
512                 ecode = tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
513                                    "tdb_open: error %s reading %s",
514                                    strerror(errno), name);
515                 goto fail;
516         } else if (rlen < sizeof(hdr)
517                    || strcmp(hdr.magic_food, TDB_MAGIC_FOOD) != 0) {
518                 ecode = tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
519                                    "tdb_open: %s is not a tdb file", name);
520                 goto fail;
521         }
522
523         if (hdr.version != TDB_VERSION) {
524                 if (hdr.version == bswap_64(TDB_VERSION))
525                         tdb->flags |= TDB_CONVERT;
526                 else {
527                         /* wrong version */
528                         ecode = tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
529                                            "tdb_open:"
530                                            " %s is unknown version 0x%llx",
531                                            name, (long long)hdr.version);
532                         goto fail;
533                 }
534         } else if (tdb->flags & TDB_CONVERT) {
535                 ecode = tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
536                                    "tdb_open:"
537                                    " %s does not need TDB_CONVERT",
538                                    name);
539                 goto fail;
540         }
541
542         tdb_convert(tdb, &hdr, sizeof(hdr));
543         tdb->hash_seed = hdr.hash_seed;
544         hash_test = TDB_HASH_MAGIC;
545         hash_test = tdb_hash(tdb, &hash_test, sizeof(hash_test));
546         if (hdr.hash_test != hash_test) {
547                 /* wrong hash variant */
548                 ecode = tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
549                                    "tdb_open:"
550                                    " %s uses a different hash function",
551                                    name);
552                 goto fail;
553         }
554
555         /* Clear any features we don't understand. */
556         if ((open_flags & O_ACCMODE) != O_RDONLY) {
557                 hdr.features_used &= TDB_FEATURE_MASK;
558                 ecode = tdb_write_convert(tdb, offsetof(struct tdb_header,
559                                                         features_used),
560                                           &hdr.features_used,
561                                           sizeof(hdr.features_used));
562                 if (ecode != TDB_SUCCESS)
563                         goto fail;
564         }
565
566         tdb_unlock_open(tdb, openlock);
567
568         /* This make sure we have current map_size and mmap. */
569         ecode = tdb->methods->oob(tdb, tdb->file->map_size + 1, true);
570         if (unlikely(ecode != TDB_SUCCESS))
571                 goto fail;
572
573         /* Now it's fully formed, recover if necessary. */
574         berr = tdb_needs_recovery(tdb);
575         if (unlikely(berr != false)) {
576                 if (berr < 0) {
577                         ecode = berr;
578                         goto fail;
579                 }
580                 ecode = tdb_lock_and_recover(tdb);
581                 if (ecode != TDB_SUCCESS) {
582                         goto fail;
583                 }
584         }
585
586         ecode = tdb_ftable_init(tdb);
587         if (ecode != TDB_SUCCESS) {
588                 goto fail;
589         }
590
591         /* Add to linked list if we're new. */
592         if (tdb->file->refcnt == 1)
593                 files = tdb->file;
594         return tdb;
595
596  fail:
597         /* Map ecode to some logical errno. */
598         switch (ecode) {
599         case TDB_ERR_CORRUPT:
600         case TDB_ERR_IO:
601                 saved_errno = EIO;
602                 break;
603         case TDB_ERR_LOCK:
604                 saved_errno = EWOULDBLOCK;
605                 break;
606         case TDB_ERR_OOM:
607                 saved_errno = ENOMEM;
608                 break;
609         case TDB_ERR_EINVAL:
610                 saved_errno = EINVAL;
611                 break;
612         default:
613                 saved_errno = EINVAL;
614                 break;
615         }
616
617 fail_errno:
618 #ifdef TDB_TRACE
619         close(tdb->tracefd);
620 #endif
621         if (tdb->file) {
622                 tdb_lock_cleanup(tdb);
623                 if (--tdb->file->refcnt == 0) {
624                         assert(tdb->file->num_lockrecs == 0);
625                         if (tdb->file->map_ptr) {
626                                 if (tdb->flags & TDB_INTERNAL) {
627                                         free(tdb->file->map_ptr);
628                                 } else
629                                         tdb_munmap(tdb->file);
630                         }
631                         if (close(tdb->file->fd) != 0)
632                                 tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
633                                            "tdb_open: failed to close tdb fd"
634                                            " on error: %s", strerror(errno));
635                         free(tdb->file->lockrecs);
636                         free(tdb->file);
637                 }
638         }
639
640         free(tdb);
641         errno = saved_errno;
642         return NULL;
643 }
644
645 int tdb_close(struct tdb_context *tdb)
646 {
647         int ret = 0;
648
649         tdb_trace(tdb, "tdb_close");
650
651         if (tdb->transaction) {
652                 tdb_transaction_cancel(tdb);
653         }
654
655         if (tdb->file->map_ptr) {
656                 if (tdb->flags & TDB_INTERNAL)
657                         free(tdb->file->map_ptr);
658                 else
659                         tdb_munmap(tdb->file);
660         }
661         if (tdb->file) {
662                 struct tdb_file **i;
663
664                 tdb_lock_cleanup(tdb);
665                 if (--tdb->file->refcnt == 0) {
666                         ret = close(tdb->file->fd);
667
668                         /* Remove from files list */
669                         for (i = &files; *i; i = &(*i)->next) {
670                                 if (*i == tdb->file) {
671                                         *i = tdb->file->next;
672                                         break;
673                                 }
674                         }
675                         free(tdb->file->lockrecs);
676                         free(tdb->file);
677                 }
678         }
679
680 #ifdef TDB_TRACE
681         close(tdb->tracefd);
682 #endif
683         free(tdb);
684
685         return ret;
686 }