]> git.pond.sub.org Git - empserver/blob - src/lib/common/file.c
Clean up ef_close() to zap csize along with cache
[empserver] / src / lib / common / file.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2011, Dave Pare, Jeff Bailey, Thomas Ruschak,
4  *                Ken Stevens, Steve McClure, Markus Armbruster
5  *
6  *  Empire is free software: you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation, either version 3 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  *
19  *  ---
20  *
21  *  See files README, COPYING and CREDITS in the root of the source
22  *  tree for related information and legal notices.  It is expected
23  *  that future projects/authors will amend these files as needed.
24  *
25  *  ---
26  *
27  *  file.c: Operations on Empire tables (`files' for historical reasons)
28  *
29  *  Known contributors to this file:
30  *     Dave Pare, 1989
31  *     Steve McClure, 2000
32  *     Markus Armbruster, 2005-2011
33  */
34
35 #include <config.h>
36
37 #include <errno.h>
38 #include <fcntl.h>
39 #include <sys/stat.h>
40 #include <sys/types.h>
41 #include <unistd.h>
42 #ifdef _WIN32
43 #include <io.h>
44 #include <share.h>
45 #endif
46 #include "file.h"
47 #include "match.h"
48 #include "misc.h"
49 #include "nsc.h"
50 #include "prototypes.h"
51
52 static int open_locked(char *, int, mode_t);
53 static int ef_realloc_cache(struct empfile *, int);
54 static int fillcache(struct empfile *, int);
55 static int do_read(struct empfile *, void *, int, int);
56 static int do_write(struct empfile *, void *, int, int);
57 static unsigned get_seqno(struct empfile *, int);
58 static void new_seqno(struct empfile *, void *);
59 static void must_be_fresh(struct empfile *, void *);
60 static void do_blank(struct empfile *, void *, int, int);
61 static int ef_check(int);
62
63 static unsigned ef_generation;
64
65 /*
66  * Open the file-backed table TYPE (EF_SECTOR, ...).
67  * HOW are flags to control operation.  Naturally, immutable flags are
68  * not permitted.
69  * If NELT is non-negative, the table must have that many elements.
70  * Return non-zero on success, zero on failure.
71  * You must call ef_close() before the next ef_open().
72  */
73 int
74 ef_open(int type, int how, int nelt)
75 {
76     struct empfile *ep;
77     int oflags, fd, fsiz, nslots;
78
79     if (ef_check(type) < 0)
80         return 0;
81     if (CANT_HAPPEN(how & EFF_IMMUTABLE))
82         how &= ~EFF_IMMUTABLE;
83
84     /* open file */
85     ep = &empfile[type];
86     if (CANT_HAPPEN(ep->fd >= 0))
87         return 0;
88     oflags = O_RDWR;
89     if (how & EFF_PRIVATE)
90         oflags = O_RDONLY;
91     if (how & EFF_CREATE)
92         oflags |= O_CREAT | O_TRUNC;
93     fd = open_locked(ep->file, oflags, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
94     if (fd < 0) {
95         logerror("Can't open %s (%s)", ep->file, strerror(errno));
96         return 0;
97     }
98
99     /* get file size */
100     fsiz = fsize(fd);
101     if (fsiz % ep->size) {
102         logerror("Can't open %s (file size not a multiple of record size %d)",
103                  ep->file, ep->size);
104         close(fd);
105         return 0;
106     }
107     ep->fids = fsiz / ep->size;
108     if (nelt >= 0 && nelt != ep->fids) {
109         logerror("Can't open %s (got %d records instead of %d)",
110                  ep->file, ep->fids, nelt);
111         close(fd);
112         return 0;
113     }
114
115     /* allocate cache */
116     if (ep->flags & EFF_STATIC) {
117         /* ep->cache already points to space for ep->csize elements */
118         if (how & EFF_MEM) {
119             if (ep->fids > ep->csize) {
120                 logerror("Can't open %s (file larger than %d records)",
121                          ep->file, ep->csize);
122                 close(fd);
123                 return 0;
124             }
125         }
126     } else {
127         if (CANT_HAPPEN(ep->cache))
128             free(ep->cache);
129         if (how & EFF_MEM)
130             nslots = ep->fids;
131         else
132             nslots = blksize(fd) / ep->size;
133         if (!ef_realloc_cache(ep, nslots)) {
134             logerror("Can't map %s (%s)", ep->file, strerror(errno));
135             close(fd);
136             return 0;
137         }
138     }
139     ep->baseid = 0;
140     ep->cids = 0;
141     ep->flags = (ep->flags & EFF_IMMUTABLE) | (how & ~EFF_CREATE);
142     ep->fd = fd;
143
144     /* map file into cache */
145     if ((how & EFF_MEM) && ep->fids) {
146         if (fillcache(ep, 0) != ep->fids) {
147             ep->cids = 0;       /* prevent cache flush */
148             ef_close(type);
149             return 0;
150         }
151     }
152
153     if (ep->onresize)
154         ep->onresize(type);
155     return 1;
156 }
157
158 static int
159 open_locked(char *name, int oflags, mode_t mode)
160 {
161     int rdlonly = (oflags & O_ACCMODE) == O_RDONLY;
162     int fd;
163
164 #ifdef _WIN32
165     fd = _sopen(name, oflags | O_BINARY, rdlonly ? SH_DENYNO : SH_DENYWR,
166                 mode);
167     if (fd < 0)
168         return -1;
169 #else  /* !_WIN32 */
170     struct flock lock;
171
172     fd = open(name, oflags, mode);
173     if (fd < 0)
174         return -1;
175
176     lock.l_type = rdlonly ? F_RDLCK : F_WRLCK;
177     lock.l_whence = SEEK_SET;
178     lock.l_start = lock.l_len = 0;
179     if (fcntl(fd, F_SETLK, &lock) == -1) {
180         close(fd);
181         return -1;
182     }
183 #endif  /* !_WIN32 */
184     return fd;
185 }
186
187 /*
188  * Reallocate cache for table EP to hold COUNT slots.
189  * The table must not be allocated statically.
190  * The cache may still be unmapped.
191  * If reallocation succeeds, any pointers obtained from ef_ptr()
192  * become invalid.
193  * If it fails, the cache is unchanged, and errno is set.
194  * Return non-zero on success, zero on failure.
195  */
196 static int
197 ef_realloc_cache(struct empfile *ep, int count)
198 {
199     void *cache;
200
201     if (CANT_HAPPEN(ep->flags & EFF_STATIC))
202         return 0;
203     if (CANT_HAPPEN(count < 0))
204         count = 0;
205
206     /*
207      * Avoid zero slots, because that can lead to null cache, which
208      * would be interpreted as unmapped cache.
209      */
210     if (count == 0)
211         count++;
212     cache = realloc(ep->cache, count * ep->size);
213     if (!cache)
214         return 0;
215
216     ep->cache = cache;
217     ep->csize = count;
218     return 1;
219 }
220
221 /*
222  * Open the table TYPE as view of table BASE.
223  * Return non-zero on success, zero on failure.
224  * Beware: views work only as long as BASE doesn't change size!
225  * You must call ef_close(TYPE) before closing BASE.
226  */
227 int
228 ef_open_view(int type, int base)
229 {
230     struct empfile *ep;
231
232     if (CANT_HAPPEN(!EF_IS_VIEW(type)))
233         return -1;
234     ep = &empfile[type];
235     if (CANT_HAPPEN(!(ef_flags(base) & EFF_MEM)))
236         return -1;
237
238     ep->cache = empfile[base].cache;
239     ep->csize = empfile[base].csize;
240     ep->flags |= EFF_MEM;
241     ep->baseid = empfile[base].baseid;
242     ep->cids = empfile[base].cids;
243     ep->fids = empfile[base].fids;
244     return 0;
245 }
246
247 /*
248  * Close the open table TYPE (EF_SECTOR, ...).
249  * Return non-zero on success, zero on failure.
250  */
251 int
252 ef_close(int type)
253 {
254     struct empfile *ep;
255     int retval = 1;
256
257     if (ef_check(type) < 0)
258         return 0;
259     ep = &empfile[type];
260
261     if (EF_IS_VIEW(type)) {
262         ep->cache = NULL;
263         ep->csize = 0;
264     } else {
265         if (!ef_flush(type))
266             retval = 0;
267         if (!(ep->flags & EFF_STATIC)) {
268             free(ep->cache);
269             ep->cache = NULL;
270             ep->csize = 0;
271         }
272         if (close(ep->fd) < 0) {
273             logerror("Error closing %s (%s)", ep->file, strerror(errno));
274             retval = 0;
275         }
276         ep->fd = -1;
277     }
278     ep->flags &= EFF_IMMUTABLE;
279     ep->baseid = ep->cids = ep->fids = 0;
280     if (ep->onresize)
281         ep->onresize(type);
282     return retval;
283 }
284
285 /*
286  * Flush file-backed table TYPE (EF_SECTOR, ...) to its backing file.
287  * Do nothing if the table is privately mapped.
288  * Update timestamps of written elements if table is EFF_TYPED.
289  * Return non-zero on success, zero on failure.
290  */
291 int
292 ef_flush(int type)
293 {
294     struct empfile *ep;
295
296     if (ef_check(type) < 0)
297         return 0;
298     ep = &empfile[type];
299     if (ep->flags & EFF_PRIVATE)
300         return 1;               /* nothing to do */
301     if (CANT_HAPPEN(ep->fd < 0))
302         return 0;
303     /*
304      * We don't know which cache entries are dirty.  ef_write() writes
305      * through, but direct updates through ef_ptr() don't.  They are
306      * allowed only with EFF_MEM.  Assume the whole cash is dirty
307      * then.
308      */
309     if (ep->flags & EFF_MEM) {
310         if (do_write(ep, ep->cache, ep->baseid, ep->cids) < 0)
311             return 0;
312     }
313
314     return 1;
315 }
316
317 /*
318  * Return pointer to element ID in table TYPE if it exists, else NULL.
319  * The table must be fully cached, i.e. flags & EFF_MEM.
320  * The caller is responsible for flushing changes he makes.
321  */
322 void *
323 ef_ptr(int type, int id)
324 {
325     struct empfile *ep;
326
327     if (ef_check(type) < 0)
328         return NULL;
329     ep = &empfile[type];
330     if (CANT_HAPPEN(!(ep->flags & EFF_MEM) || !ep->cache))
331         return NULL;
332     if (id < 0 || id >= ep->fids)
333         return NULL;
334     return ep->cache + ep->size * id;
335 }
336
337 /*
338  * Read element ID from table TYPE into buffer INTO.
339  * FIXME pass buffer size!
340  * INTO is marked fresh with ef_mark_fresh().
341  * Return non-zero on success, zero on failure.
342  */
343 int
344 ef_read(int type, int id, void *into)
345 {
346     struct empfile *ep;
347     void *cachep;
348
349     if (ef_check(type) < 0)
350         return 0;
351     ep = &empfile[type];
352     if (CANT_HAPPEN(!ep->cache))
353         return 0;
354     if (id < 0 || id >= ep->fids)
355         return 0;
356
357     if (ep->flags & EFF_MEM) {
358         cachep = ep->cache + id * ep->size;
359     } else {
360         if (ep->baseid + ep->cids <= id || ep->baseid > id) {
361             if (fillcache(ep, id) < 1)
362                 return 0;
363         }
364         cachep = ep->cache + (id - ep->baseid) * ep->size;
365     }
366     memcpy(into, cachep, ep->size);
367     ef_mark_fresh(type, into);
368
369     if (ep->postread)
370         ep->postread(id, into);
371     return 1;
372 }
373
374 /*
375  * Fill cache of file-backed EP with elements starting at ID.
376  * If any were read, return their number.
377  * Else return -1 and leave the cache unchanged.
378  */
379 static int
380 fillcache(struct empfile *ep, int id)
381 {
382     int ret;
383
384     if (CANT_HAPPEN(!ep->cache))
385         return -1;
386
387     ret = do_read(ep, ep->cache, id, MIN(ep->csize, ep->fids - id));
388     if (ret >= 0) {
389         /* cache changed */
390         ep->baseid = id;
391         ep->cids = ret;
392     }
393     return ret;
394 }
395
396 static int
397 do_read(struct empfile *ep, void *buf, int id, int count)
398 {
399     int n, ret;
400     char *p;
401
402     if (CANT_HAPPEN(ep->fd < 0 || id < 0 || count < 0))
403         return -1;
404
405     if (lseek(ep->fd, id * ep->size, SEEK_SET) == (off_t)-1) {
406         logerror("Error seeking %s to elt %d (%s)",
407                  ep->file, id, strerror(errno));
408         return -1;
409     }
410
411     p = buf;
412     n = count * ep->size;
413     while (n > 0) {
414         ret = read(ep->fd, p, n);
415         if (ret < 0) {
416             if (errno != EINTR) {
417                 logerror("Error reading %s elt %d (%s)",
418                          ep->file,
419                          id + (int)((p - (char *)buf) / ep->size),
420                          strerror(errno));
421                 break;
422             }
423         } else if (ret == 0) {
424             logerror("Unexpected EOF reading %s elt %d",
425                      ep->file, id + (int)((p - (char *)buf) / ep->size));
426             break;
427         } else {
428             p += ret;
429             n -= ret;
430         }
431     }
432
433     return (p - (char *)buf) / ep->size;
434 }
435
436 /*
437  * Write COUNT elements starting at ID from BUF to file-backed EP.
438  * Update the timestamp if the table is EFF_TYPED.
439  * Don't actually write if table is privately mapped.
440  * Return 0 on success, -1 on error (file may be corrupt then).
441  */
442 static int
443 do_write(struct empfile *ep, void *buf, int id, int count)
444 {
445     int i, n, ret;
446     char *p;
447     struct emptypedstr *elt;
448     time_t now;
449
450     if (CANT_HAPPEN(ep->fd < 0 || id < 0 || count < 0))
451         return -1;
452
453     if (ep->flags & EFF_TYPED) {
454         now = ep->flags & EFF_NOTIME ? (time_t)-1 : time(NULL);
455         for (i = 0; i < count; i++) {
456             /*
457              * TODO Oopses here could be due to bad data corruption.
458              * Fail instead of attempting to recover?
459              */
460             elt = (struct emptypedstr *)((char *)buf + i * ep->size);
461             if (CANT_HAPPEN(elt->ef_type != ep->uid))
462                 elt->ef_type = ep->uid;
463             if (CANT_HAPPEN(elt->uid != id + i))
464                 elt->uid = id + i;
465             if (now != (time_t)-1)
466                 elt->timestamp = now;
467         }
468     }
469
470     if (ep->flags & EFF_PRIVATE)
471         return 0;
472
473     if (lseek(ep->fd, id * ep->size, SEEK_SET) == (off_t)-1) {
474         logerror("Error seeking %s to elt %d (%s)",
475                  ep->file, id, strerror(errno));
476         return -1;
477     }
478
479     p = buf;
480     n = count * ep->size;
481     while (n > 0) {
482         ret = write(ep->fd, p, n);
483         if (ret < 0) {
484             if (errno != EINTR) {
485                 logerror("Error writing %s elt %d (%s)",
486                          ep->file,
487                          id + (int)((p - (char *)buf) / ep->size),
488                          strerror(errno));
489                 return -1;
490             }
491         } else {
492             p += ret;
493             n -= ret;
494         }
495     }
496
497     return 0;
498 }
499
500 /*
501  * Write element ID into table TYPE from buffer FROM.
502  * FIXME pass buffer size!
503  * Update timestamp in FROM if table is EFF_TYPED.
504  * If table is file-backed and not privately mapped, write through
505  * cache straight to disk.
506  * Cannot write beyond the end of fully cached table (flags & EFF_MEM).
507  * Can write at the end of partially cached table.
508  * FROM must be fresh; see ef_make_stale().
509  * Return non-zero on success, zero on failure.
510  */
511 int
512 ef_write(int type, int id, void *from)
513 {
514     struct empfile *ep;
515     char *cachep;
516
517     if (ef_check(type) < 0)
518         return 0;
519     ep = &empfile[type];
520     if (CANT_HAPPEN((ep->flags & (EFF_MEM | EFF_PRIVATE)) == EFF_PRIVATE))
521         return 0;
522     if (CANT_HAPPEN((ep->flags & EFF_MEM) ? id >= ep->fids : id > ep->fids))
523         return 0;               /* not implemented */
524     new_seqno(ep, from);
525     if (id >= ep->fids) {
526         /* write beyond end of file extends it, take note */
527         ep->fids = id + 1;
528         if (ep->onresize)
529             ep->onresize(type);
530     }
531     if (id >= ep->baseid && id < ep->baseid + ep->cids) {
532         cachep = ep->cache + (id - ep->baseid) * ep->size;
533         if (cachep != from)
534             must_be_fresh(ep, from);
535     } else
536         cachep = NULL;
537     if (ep->prewrite)
538         ep->prewrite(id, cachep, from);
539     if (ep->fd >= 0) {
540         if (do_write(ep, from, id, 1) < 0)
541             return 0;
542     }
543     if (cachep && cachep != from)       /* update the cache if necessary */
544         memcpy(cachep, from, ep->size);
545     return 1;
546 }
547
548 /*
549  * Change element id.
550  * BUF is an element of table TYPE.
551  * ID is its new element ID.
552  * If table is EFF_TYPED, change id and sequence number stored in BUF.
553  * Else do nothing.
554  */
555 void
556 ef_set_uid(int type, void *buf, int uid)
557 {
558     struct emptypedstr *elt;
559     struct empfile *ep;
560
561     if (ef_check(type) < 0)
562         return;
563     ep = &empfile[type];
564     if (!(ep->flags & EFF_TYPED))
565         return;
566     elt = buf;
567     if (elt->uid == uid)
568         return;
569     elt->uid = uid;
570     elt->seqno = get_seqno(ep, uid);
571 }
572
573 /*
574  * Return sequence number of element ID in table EP.
575  * Return zero if table is not EFF_TYPED (it has no sequence number
576  * then).
577  */
578 static unsigned
579 get_seqno(struct empfile *ep, int id)
580 {
581     struct emptypedstr *elt;
582
583     if (!(ep->flags & EFF_TYPED))
584         return 0;
585     if (id < 0 || id >= ep->fids)
586         return 0;
587     if (id >= ep->baseid && id < ep->baseid + ep->cids)
588         elt = (void *)(ep->cache + (id - ep->baseid) * ep->size);
589     else {
590         /* need a buffer, steal last cache slot */
591         if (ep->cids == ep->csize)
592             ep->cids--;
593         elt = (void *)(ep->cache + ep->cids * ep->size);
594         if (do_read(ep, elt, id, 1) < 0)
595             return 0;           /* deep trouble */
596     }
597     return elt->seqno;
598 }
599
600 /*
601  * Increment sequence number in BUF, which is about to be written to EP.
602  * Do nothing if table is not EFF_TYPED (it has no sequence number
603  * then).
604  * Else, BUF's sequence number must match the one in EP's cache.  If
605  * it doesn't, we're about to clobber a previous write.
606  */
607 static void
608 new_seqno(struct empfile *ep, void *buf)
609 {
610     struct emptypedstr *elt = buf;
611     unsigned old_seqno;
612
613     if (!(ep->flags & EFF_TYPED))
614         return;
615     old_seqno = get_seqno(ep, elt->uid);
616     CANT_HAPPEN(old_seqno != elt->seqno);
617     elt->seqno = old_seqno + 1;
618 }
619
620 /*
621  * Make all copies stale.
622  * Only fresh copies may be written back to the cache.
623  * To be called by functions that may yield the processor.
624  * Writing an copy when there has been a yield since it was read is
625  * unsafe, because we could clobber another thread's write then.
626  * Robust code must assume the that any function that may yield does
627  * yield.  Marking copies stale there lets us catch unsafe writes.
628  */
629 void
630 ef_make_stale(void)
631 {
632     ef_generation++;
633 }
634
635 /* Mark copy of an element of table TYPE in BUF fresh.  */
636 void
637 ef_mark_fresh(int type, void *buf)
638 {
639     struct empfile *ep;
640
641     if (ef_check(type) < 0)
642         return;
643     ep = &empfile[type];
644     if (!(ep->flags & EFF_TYPED))
645         return;
646     ((struct emptypedstr *)buf)->generation = ef_generation;
647 }
648
649 static void
650 must_be_fresh(struct empfile *ep, void *buf)
651 {
652     struct emptypedstr *elt = buf;
653
654     if (!(ep->flags & EFF_TYPED))
655         return;
656     CANT_HAPPEN(elt->generation != (ef_generation & 0xfff));
657 }
658
659 /*
660  * Extend table TYPE by COUNT elements.
661  * Any pointers obtained from ef_ptr() become invalid.
662  * Return non-zero on success, zero on failure.
663  */
664 int
665 ef_extend(int type, int count)
666 {
667     struct empfile *ep;
668     char *p;
669     int need_sentinel, i, id;
670
671     if (ef_check(type) < 0 || CANT_HAPPEN(EF_IS_VIEW(type)))
672         return 0;
673     ep = &empfile[type];
674     if (CANT_HAPPEN(count < 0))
675         return 0;
676
677     id = ep->fids;
678     if (ep->flags & EFF_MEM) {
679         need_sentinel = (ep->flags & EFF_SENTINEL) != 0;
680         if (id + count + need_sentinel > ep->csize) {
681             if (ep->flags & EFF_STATIC) {
682                 logerror("Can't extend %s beyond %d elements",
683                          ep->name, ep->csize - need_sentinel);
684                 return 0;
685             }
686             if (!ef_realloc_cache(ep, id + count + need_sentinel)) {
687                 logerror("Can't extend %s to %d elements (%s)",
688                          ep->name, id + count, strerror(errno));
689                 return 0;
690             }
691         }
692         p = ep->cache + id * ep->size;
693         do_blank(ep, p, id, count);
694         if (ep->fd >= 0) {
695             if (do_write(ep, p, id, count) < 0)
696                 return 0;
697         }
698         if (need_sentinel)
699             memset(ep->cache + (id + count) * ep->size, 0, ep->size);
700         ep->cids = id + count;
701     } else {
702         /* need a buffer, steal last cache slot */
703         if (ep->cids == ep->csize)
704             ep->cids--;
705         p = ep->cache + ep->cids * ep->size;
706         for (i = 0; i < count; i++) {
707             do_blank(ep, p, id + i, 1);
708             if (do_write(ep, p, id + i, 1) < 0)
709                 return 0;
710         }
711     }
712     ep->fids = id + count;
713     if (ep->onresize)
714         ep->onresize(type);
715     return 1;
716 }
717
718 /*
719  * Initialize element ID for table TYPE in BUF.
720  * FIXME pass buffer size!
721  * BUF is marked fresh with ef_mark_fresh().
722  */
723 void
724 ef_blank(int type, int id, void *buf)
725 {
726     struct empfile *ep;
727     struct emptypedstr *elt;
728
729     if (ef_check(type) < 0)
730         return;
731     ep = &empfile[type];
732     do_blank(ep, buf, id, 1);
733     if (ep->flags & EFF_TYPED) {
734         elt = buf;
735         elt->seqno = get_seqno(ep, elt->uid);
736     }
737     ef_mark_fresh(type, buf);
738 }
739
740 /*
741  * Initialize COUNT elements of EP in BUF, starting with element ID.
742  */
743 static void
744 do_blank(struct empfile *ep, void *buf, int id, int count)
745 {
746     int i;
747     struct emptypedstr *elt;
748
749     memset(buf, 0, count * ep->size);
750     for (i = 0; i < count; i++) {
751         elt = (struct emptypedstr *)((char *)buf + i * ep->size);
752         if (ep->flags & EFF_TYPED) {
753             elt->ef_type = ep->uid;
754             elt->uid = id + i;
755         }
756         if (ep->oninit)
757             ep->oninit(elt);
758     }
759 }
760
761 /*
762  * Truncate table TYPE to COUNT elements.
763  * Any pointers obtained from ef_ptr() become invalid.
764  * Return non-zero on success, zero on failure.
765  */
766 int
767 ef_truncate(int type, int count)
768 {
769     struct empfile *ep;
770     int need_sentinel;
771
772     if (ef_check(type) < 0 || CANT_HAPPEN(EF_IS_VIEW(type)))
773         return 0;
774     ep = &empfile[type];
775     if (CANT_HAPPEN(count < 0 || count > ep->fids))
776         return 0;
777
778     if (ep->fd >= 0 && !(ep->flags & EFF_PRIVATE)) {
779         if (ftruncate(ep->fd, count * ep->size) < 0) {
780             logerror("Can't truncate %s to %d elements (%s)",
781                      ep->file, count, strerror(errno));
782             return 0;
783         }
784     }
785     ep->fids = count;
786
787     if (ep->flags & EFF_MEM) {
788         need_sentinel = (ep->flags & EFF_SENTINEL) != 0;
789         if (!(ep->flags & EFF_STATIC)) {
790             if (!ef_realloc_cache(ep, count + need_sentinel)) {
791                 logerror("Can't shrink %s cache after truncate (%s)",
792                          ep->name, strerror(errno));
793                 /* continue with unshrunk cache */
794             }
795         }
796         if (need_sentinel)
797             memset(ep->cache + count * ep->size, 0, ep->size);
798         ep->cids = count;
799     } else {
800         if (ep->baseid >= count)
801             ep->cids = 0;
802         else if (ep->cids > count - ep->baseid)
803             ep->cids = count - ep->baseid;
804     }
805
806     if (ep->onresize)
807         ep->onresize(type);
808     return 1;
809 }
810
811 struct castr *
812 ef_cadef(int type)
813 {
814     if (ef_check(type) < 0)
815         return NULL;
816     return empfile[type].cadef;
817 }
818
819 int
820 ef_nelem(int type)
821 {
822     if (ef_check(type) < 0)
823         return 0;
824     return empfile[type].fids;
825 }
826
827 int
828 ef_flags(int type)
829 {
830     if (ef_check(type) < 0)
831         return 0;
832     return empfile[type].flags;
833 }
834
835 time_t
836 ef_mtime(int type)
837 {
838     if (ef_check(type) < 0)
839         return 0;
840     if (empfile[type].fd <= 0)
841         return 0;
842     return fdate(empfile[type].fd);
843 }
844
845 /*
846  * Search for a table matching NAME, return its table type.
847  * Return M_NOTFOUND if there are no matches, M_NOTUNIQUE if there are
848  * several.
849  */
850 int
851 ef_byname(char *name)
852 {
853     return stmtch(name, empfile, offsetof(struct empfile, name),
854                   sizeof(empfile[0]));
855 }
856
857 /*
858  * Search CHOICES[] for a table type matching NAME, return it.
859  * Return M_NOTFOUND if there are no matches, M_NOTUNIQUE if there are
860  * several.
861  * CHOICES[] must be terminated with a negative value.
862  */
863 int
864 ef_byname_from(char *name, int choices[])
865 {
866     int res;
867     int *p;
868
869     res = M_NOTFOUND;
870     for (p = choices; *p >= 0; p++) {
871         if (ef_check(*p) < 0)
872             continue;
873         switch (mineq(name, empfile[*p].name)) {
874         case ME_MISMATCH:
875             break;
876         case ME_PARTIAL:
877             if (res >= 0)
878                 return M_NOTUNIQUE;
879             res = *p;
880             break;
881         case ME_EXACT:
882             return *p;
883         }
884     }
885     return res;
886 }
887
888 char *
889 ef_nameof(int type)
890 {
891     if (ef_check(type) < 0)
892         return "bad ef_type";
893     return empfile[type].name;
894 }
895
896 static int
897 ef_check(int type)
898 {
899     if (CANT_HAPPEN((unsigned)type >= EF_MAX))
900         return -1;
901     return 0;
902 }
903
904 /*
905  * Ensure table contains element ID.
906  * If necessary, extend it in steps of COUNT elements.
907  * Return non-zero on success, zero on failure.
908  */
909 int
910 ef_ensure_space(int type, int id, int count)
911 {
912     if (ef_check(type) < 0)
913         return 0;
914     CANT_HAPPEN(id < 0);
915
916     while (id >= empfile[type].fids) {
917         if (!ef_extend(type, count))
918             return 0;
919     }
920     return 1;
921 }