]> git.ozlabs.org Git - ccan/blob - ccan/tdb2/tdb.c
tdb2: unify tdb1_fetch into tdb_fetch
[ccan] / ccan / tdb2 / tdb.c
1  /*
2    Trivial Database 2: fetch, store and misc routines.
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/asprintf/asprintf.h>
20 #include <stdarg.h>
21
22 static enum TDB_ERROR update_rec_hdr(struct tdb_context *tdb,
23                                      tdb_off_t off,
24                                      tdb_len_t keylen,
25                                      tdb_len_t datalen,
26                                      struct tdb_used_record *rec,
27                                      uint64_t h)
28 {
29         uint64_t dataroom = rec_data_length(rec) + rec_extra_padding(rec);
30         enum TDB_ERROR ecode;
31
32         ecode = set_header(tdb, rec, TDB_USED_MAGIC, keylen, datalen,
33                            keylen + dataroom, h);
34         if (ecode == TDB_SUCCESS) {
35                 ecode = tdb_write_convert(tdb, off, rec, sizeof(*rec));
36         }
37         return ecode;
38 }
39
40 static enum TDB_ERROR replace_data(struct tdb_context *tdb,
41                                    struct hash_info *h,
42                                    struct tdb_data key, struct tdb_data dbuf,
43                                    tdb_off_t old_off, tdb_len_t old_room,
44                                    bool growing)
45 {
46         tdb_off_t new_off;
47         enum TDB_ERROR ecode;
48
49         /* Allocate a new record. */
50         new_off = alloc(tdb, key.dsize, dbuf.dsize, h->h, TDB_USED_MAGIC,
51                         growing);
52         if (TDB_OFF_IS_ERR(new_off)) {
53                 return new_off;
54         }
55
56         /* We didn't like the existing one: remove it. */
57         if (old_off) {
58                 tdb->stats.frees++;
59                 ecode = add_free_record(tdb, old_off,
60                                         sizeof(struct tdb_used_record)
61                                         + key.dsize + old_room,
62                                         TDB_LOCK_WAIT, true);
63                 if (ecode == TDB_SUCCESS)
64                         ecode = replace_in_hash(tdb, h, new_off);
65         } else {
66                 ecode = add_to_hash(tdb, h, new_off);
67         }
68         if (ecode != TDB_SUCCESS) {
69                 return ecode;
70         }
71
72         new_off += sizeof(struct tdb_used_record);
73         ecode = tdb->tdb2.io->twrite(tdb, new_off, key.dptr, key.dsize);
74         if (ecode != TDB_SUCCESS) {
75                 return ecode;
76         }
77
78         new_off += key.dsize;
79         ecode = tdb->tdb2.io->twrite(tdb, new_off, dbuf.dptr, dbuf.dsize);
80         if (ecode != TDB_SUCCESS) {
81                 return ecode;
82         }
83
84         if (tdb->flags & TDB_SEQNUM)
85                 tdb_inc_seqnum(tdb);
86
87         return TDB_SUCCESS;
88 }
89
90 static enum TDB_ERROR update_data(struct tdb_context *tdb,
91                                   tdb_off_t off,
92                                   struct tdb_data dbuf,
93                                   tdb_len_t extra)
94 {
95         enum TDB_ERROR ecode;
96
97         ecode = tdb->tdb2.io->twrite(tdb, off, dbuf.dptr, dbuf.dsize);
98         if (ecode == TDB_SUCCESS && extra) {
99                 /* Put a zero in; future versions may append other data. */
100                 ecode = tdb->tdb2.io->twrite(tdb, off + dbuf.dsize, "", 1);
101         }
102         if (tdb->flags & TDB_SEQNUM)
103                 tdb_inc_seqnum(tdb);
104
105         return ecode;
106 }
107
108 enum TDB_ERROR tdb_store(struct tdb_context *tdb,
109                          struct tdb_data key, struct tdb_data dbuf, int flag)
110 {
111         struct hash_info h;
112         tdb_off_t off;
113         tdb_len_t old_room = 0;
114         struct tdb_used_record rec;
115         enum TDB_ERROR ecode;
116
117         if (tdb->flags & TDB_VERSION1) {
118                 if (tdb1_store(tdb, key, dbuf, flag) == -1)
119                         return tdb->last_error;
120                 return TDB_SUCCESS;
121         }
122
123         off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
124         if (TDB_OFF_IS_ERR(off)) {
125                 return tdb->last_error = off;
126         }
127
128         /* Now we have lock on this hash bucket. */
129         if (flag == TDB_INSERT) {
130                 if (off) {
131                         ecode = TDB_ERR_EXISTS;
132                         goto out;
133                 }
134         } else {
135                 if (off) {
136                         old_room = rec_data_length(&rec)
137                                 + rec_extra_padding(&rec);
138                         if (old_room >= dbuf.dsize) {
139                                 /* Can modify in-place.  Easy! */
140                                 ecode = update_rec_hdr(tdb, off,
141                                                        key.dsize, dbuf.dsize,
142                                                        &rec, h.h);
143                                 if (ecode != TDB_SUCCESS) {
144                                         goto out;
145                                 }
146                                 ecode = update_data(tdb,
147                                                     off + sizeof(rec)
148                                                     + key.dsize, dbuf,
149                                                     old_room - dbuf.dsize);
150                                 if (ecode != TDB_SUCCESS) {
151                                         goto out;
152                                 }
153                                 tdb_unlock_hashes(tdb, h.hlock_start,
154                                                   h.hlock_range, F_WRLCK);
155                                 return tdb->last_error = TDB_SUCCESS;
156                         }
157                 } else {
158                         if (flag == TDB_MODIFY) {
159                                 /* if the record doesn't exist and we
160                                    are in TDB_MODIFY mode then we should fail
161                                    the store */
162                                 ecode = TDB_ERR_NOEXIST;
163                                 goto out;
164                         }
165                 }
166         }
167
168         /* If we didn't use the old record, this implies we're growing. */
169         ecode = replace_data(tdb, &h, key, dbuf, off, old_room, off);
170 out:
171         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
172         return tdb->last_error = ecode;
173 }
174
175 enum TDB_ERROR tdb_append(struct tdb_context *tdb,
176                           struct tdb_data key, struct tdb_data dbuf)
177 {
178         struct hash_info h;
179         tdb_off_t off;
180         struct tdb_used_record rec;
181         tdb_len_t old_room = 0, old_dlen;
182         unsigned char *newdata;
183         struct tdb_data new_dbuf;
184         enum TDB_ERROR ecode;
185
186         off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
187         if (TDB_OFF_IS_ERR(off)) {
188                 return tdb->last_error = off;
189         }
190
191         if (off) {
192                 old_dlen = rec_data_length(&rec);
193                 old_room = old_dlen + rec_extra_padding(&rec);
194
195                 /* Fast path: can append in place. */
196                 if (rec_extra_padding(&rec) >= dbuf.dsize) {
197                         ecode = update_rec_hdr(tdb, off, key.dsize,
198                                                old_dlen + dbuf.dsize, &rec,
199                                                h.h);
200                         if (ecode != TDB_SUCCESS) {
201                                 goto out;
202                         }
203
204                         off += sizeof(rec) + key.dsize + old_dlen;
205                         ecode = update_data(tdb, off, dbuf,
206                                             rec_extra_padding(&rec));
207                         goto out;
208                 }
209
210                 /* Slow path. */
211                 newdata = malloc(key.dsize + old_dlen + dbuf.dsize);
212                 if (!newdata) {
213                         ecode = tdb_logerr(tdb, TDB_ERR_OOM, TDB_LOG_ERROR,
214                                            "tdb_append:"
215                                            " failed to allocate %zu bytes",
216                                            (size_t)(key.dsize + old_dlen
217                                                     + dbuf.dsize));
218                         goto out;
219                 }
220                 ecode = tdb->tdb2.io->tread(tdb, off + sizeof(rec) + key.dsize,
221                                             newdata, old_dlen);
222                 if (ecode != TDB_SUCCESS) {
223                         goto out_free_newdata;
224                 }
225                 memcpy(newdata + old_dlen, dbuf.dptr, dbuf.dsize);
226                 new_dbuf.dptr = newdata;
227                 new_dbuf.dsize = old_dlen + dbuf.dsize;
228         } else {
229                 newdata = NULL;
230                 new_dbuf = dbuf;
231         }
232
233         /* If they're using tdb_append(), it implies they're growing record. */
234         ecode = replace_data(tdb, &h, key, new_dbuf, off, old_room, true);
235
236 out_free_newdata:
237         free(newdata);
238 out:
239         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
240         return tdb->last_error = ecode;
241 }
242
243 enum TDB_ERROR tdb_fetch(struct tdb_context *tdb, struct tdb_data key,
244                          struct tdb_data *data)
245 {
246         tdb_off_t off;
247         struct tdb_used_record rec;
248         struct hash_info h;
249         enum TDB_ERROR ecode;
250
251         if (tdb->flags & TDB_VERSION1)
252                 return tdb1_fetch(tdb, key, data);
253
254         off = find_and_lock(tdb, key, F_RDLCK, &h, &rec, NULL);
255         if (TDB_OFF_IS_ERR(off)) {
256                 return tdb->last_error = off;
257         }
258
259         if (!off) {
260                 ecode = TDB_ERR_NOEXIST;
261         } else {
262                 data->dsize = rec_data_length(&rec);
263                 data->dptr = tdb_alloc_read(tdb, off + sizeof(rec) + key.dsize,
264                                             data->dsize);
265                 if (TDB_PTR_IS_ERR(data->dptr)) {
266                         ecode = TDB_PTR_ERR(data->dptr);
267                 } else
268                         ecode = TDB_SUCCESS;
269         }
270
271         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_RDLCK);
272         return tdb->last_error = ecode;
273 }
274
275 bool tdb_exists(struct tdb_context *tdb, TDB_DATA key)
276 {
277         tdb_off_t off;
278         struct tdb_used_record rec;
279         struct hash_info h;
280
281         off = find_and_lock(tdb, key, F_RDLCK, &h, &rec, NULL);
282         if (TDB_OFF_IS_ERR(off)) {
283                 tdb->last_error = off;
284                 return false;
285         }
286         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_RDLCK);
287
288         tdb->last_error = TDB_SUCCESS;
289         return off ? true : false;
290 }
291
292 enum TDB_ERROR tdb_delete(struct tdb_context *tdb, struct tdb_data key)
293 {
294         tdb_off_t off;
295         struct tdb_used_record rec;
296         struct hash_info h;
297         enum TDB_ERROR ecode;
298
299         off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
300         if (TDB_OFF_IS_ERR(off)) {
301                 return tdb->last_error = off;
302         }
303
304         if (!off) {
305                 ecode = TDB_ERR_NOEXIST;
306                 goto unlock;
307         }
308
309         ecode = delete_from_hash(tdb, &h);
310         if (ecode != TDB_SUCCESS) {
311                 goto unlock;
312         }
313
314         /* Free the deleted entry. */
315         tdb->stats.frees++;
316         ecode = add_free_record(tdb, off,
317                                 sizeof(struct tdb_used_record)
318                                 + rec_key_length(&rec)
319                                 + rec_data_length(&rec)
320                                 + rec_extra_padding(&rec),
321                                 TDB_LOCK_WAIT, true);
322
323         if (tdb->flags & TDB_SEQNUM)
324                 tdb_inc_seqnum(tdb);
325
326 unlock:
327         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
328         return tdb->last_error = ecode;
329 }
330
331 unsigned int tdb_get_flags(struct tdb_context *tdb)
332 {
333         return tdb->flags;
334 }
335
336 static bool inside_transaction(const struct tdb_context *tdb)
337 {
338         if (tdb->flags & TDB_VERSION1)
339                 return tdb->tdb1.transaction != NULL;
340         else
341                 return tdb->tdb2.transaction != NULL;
342 }
343
344 static bool readonly_changable(struct tdb_context *tdb, const char *caller)
345 {
346         if (inside_transaction(tdb)) {
347                 tdb->last_error = tdb_logerr(tdb, TDB_ERR_EINVAL,
348                                              TDB_LOG_USE_ERROR,
349                                              "%s: can't change"
350                                              " TDB_RDONLY inside transaction",
351                                              caller);
352                 return false;
353         }
354
355         if (tdb->file->allrecord_lock.count != 0
356             || tdb->file->num_lockrecs != 0) {
357                 tdb->last_error = tdb_logerr(tdb, TDB_ERR_EINVAL,
358                                              TDB_LOG_USE_ERROR,
359                                              "%s: can't change"
360                                              " TDB_RDONLY holding locks",
361                                              caller);
362                 return false;
363         }
364         return true;
365 }
366
367 void tdb_add_flag(struct tdb_context *tdb, unsigned flag)
368 {
369         if (tdb->flags & TDB_INTERNAL) {
370                 tdb->last_error = tdb_logerr(tdb, TDB_ERR_EINVAL,
371                                              TDB_LOG_USE_ERROR,
372                                              "tdb_add_flag: internal db");
373                 return;
374         }
375         switch (flag) {
376         case TDB_NOLOCK:
377                 tdb->flags |= TDB_NOLOCK;
378                 break;
379         case TDB_NOMMAP:
380                 tdb->flags |= TDB_NOMMAP;
381                 tdb_munmap(tdb->file);
382                 break;
383         case TDB_NOSYNC:
384                 tdb->flags |= TDB_NOSYNC;
385                 break;
386         case TDB_SEQNUM:
387                 tdb->flags |= TDB_SEQNUM;
388                 break;
389         case TDB_ALLOW_NESTING:
390                 tdb->flags |= TDB_ALLOW_NESTING;
391                 break;
392         case TDB_RDONLY:
393                 if (readonly_changable(tdb, "tdb_add_flag"))
394                         tdb->flags |= TDB_RDONLY;
395                 break;
396         default:
397                 tdb->last_error = tdb_logerr(tdb, TDB_ERR_EINVAL,
398                                              TDB_LOG_USE_ERROR,
399                                              "tdb_add_flag: Unknown flag %u",
400                                              flag);
401         }
402 }
403
404 void tdb_remove_flag(struct tdb_context *tdb, unsigned flag)
405 {
406         if (tdb->flags & TDB_INTERNAL) {
407                 tdb->last_error = tdb_logerr(tdb, TDB_ERR_EINVAL,
408                                              TDB_LOG_USE_ERROR,
409                                              "tdb_remove_flag: internal db");
410                 return;
411         }
412         switch (flag) {
413         case TDB_NOLOCK:
414                 tdb->flags &= ~TDB_NOLOCK;
415                 break;
416         case TDB_NOMMAP:
417                 tdb->flags &= ~TDB_NOMMAP;
418                 tdb_mmap(tdb);
419                 break;
420         case TDB_NOSYNC:
421                 tdb->flags &= ~TDB_NOSYNC;
422                 break;
423         case TDB_SEQNUM:
424                 tdb->flags &= ~TDB_SEQNUM;
425                 break;
426         case TDB_ALLOW_NESTING:
427                 tdb->flags &= ~TDB_ALLOW_NESTING;
428                 break;
429         case TDB_RDONLY:
430                 if ((tdb->open_flags & O_ACCMODE) == O_RDONLY) {
431                         tdb->last_error = tdb_logerr(tdb, TDB_ERR_EINVAL,
432                                                      TDB_LOG_USE_ERROR,
433                                                      "tdb_remove_flag: can't"
434                                                      " remove TDB_RDONLY on tdb"
435                                                      " opened with O_RDONLY");
436                         break;
437                 }
438                 if (readonly_changable(tdb, "tdb_remove_flag"))
439                         tdb->flags &= ~TDB_RDONLY;
440                 break;
441         default:
442                 tdb->last_error = tdb_logerr(tdb, TDB_ERR_EINVAL,
443                                              TDB_LOG_USE_ERROR,
444                                              "tdb_remove_flag: Unknown flag %u",
445                                              flag);
446         }
447 }
448
449 const char *tdb_errorstr(enum TDB_ERROR ecode)
450 {
451         /* Gcc warns if you miss a case in the switch, so use that. */
452         switch (ecode) {
453         case TDB_SUCCESS: return "Success";
454         case TDB_ERR_CORRUPT: return "Corrupt database";
455         case TDB_ERR_IO: return "IO Error";
456         case TDB_ERR_LOCK: return "Locking error";
457         case TDB_ERR_OOM: return "Out of memory";
458         case TDB_ERR_EXISTS: return "Record exists";
459         case TDB_ERR_EINVAL: return "Invalid parameter";
460         case TDB_ERR_NOEXIST: return "Record does not exist";
461         case TDB_ERR_RDONLY: return "write not permitted";
462         }
463         return "Invalid error code";
464 }
465
466 enum TDB_ERROR tdb_error(struct tdb_context *tdb)
467 {
468         return tdb->last_error;
469 }
470
471 enum TDB_ERROR COLD tdb_logerr(struct tdb_context *tdb,
472                                enum TDB_ERROR ecode,
473                                enum tdb_log_level level,
474                                const char *fmt, ...)
475 {
476         char *message;
477         va_list ap;
478         size_t len;
479         /* tdb_open paths care about errno, so save it. */
480         int saved_errno = errno;
481
482         if (!tdb->log_fn)
483                 return ecode;
484
485         va_start(ap, fmt);
486         len = vasprintf(&message, fmt, ap);
487         va_end(ap);
488
489         if (len < 0) {
490                 tdb->log_fn(tdb, TDB_LOG_ERROR, TDB_ERR_OOM,
491                             "out of memory formatting message:", tdb->log_data);
492                 tdb->log_fn(tdb, level, ecode, fmt, tdb->log_data);
493         } else {
494                 tdb->log_fn(tdb, level, ecode, message, tdb->log_data);
495                 free(message);
496         }
497         errno = saved_errno;
498         return ecode;
499 }
500
501 enum TDB_ERROR tdb_parse_record_(struct tdb_context *tdb,
502                                  TDB_DATA key,
503                                  enum TDB_ERROR (*parse)(TDB_DATA k,
504                                                          TDB_DATA d,
505                                                          void *data),
506                                  void *data)
507 {
508         tdb_off_t off;
509         struct tdb_used_record rec;
510         struct hash_info h;
511         enum TDB_ERROR ecode;
512
513         off = find_and_lock(tdb, key, F_RDLCK, &h, &rec, NULL);
514         if (TDB_OFF_IS_ERR(off)) {
515                 return tdb->last_error = off;
516         }
517
518         if (!off) {
519                 ecode = TDB_ERR_NOEXIST;
520         } else {
521                 const void *dptr;
522                 dptr = tdb_access_read(tdb, off + sizeof(rec) + key.dsize,
523                                        rec_data_length(&rec), false);
524                 if (TDB_PTR_IS_ERR(dptr)) {
525                         ecode = TDB_PTR_ERR(dptr);
526                 } else {
527                         TDB_DATA d = tdb_mkdata(dptr, rec_data_length(&rec));
528
529                         ecode = parse(key, d, data);
530                         tdb_access_release(tdb, dptr);
531                 }
532         }
533
534         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_RDLCK);
535         return tdb->last_error = ecode;
536 }
537
538 const char *tdb_name(const struct tdb_context *tdb)
539 {
540         return tdb->name;
541 }
542
543 int64_t tdb_get_seqnum(struct tdb_context *tdb)
544 {
545         tdb_off_t off = tdb_read_off(tdb, offsetof(struct tdb_header, seqnum));
546         if (TDB_OFF_IS_ERR(off))
547                 tdb->last_error = off;
548         else
549                 tdb->last_error = TDB_SUCCESS;
550         return off;
551 }
552         
553
554 int tdb_fd(const struct tdb_context *tdb)
555 {
556         return tdb->file->fd;
557 }