2 * Empire - A multi-player, client/server Internet based war game.
3 * Copyright (C) 1986-2012, Dave Pare, Jeff Bailey, Thomas Ruschak,
4 * Ken Stevens, Steve McClure, Markus Armbruster
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.
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.
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/>.
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.
27 * file.c: Operations on Empire tables (`files' for historical reasons)
29 * Known contributors to this file:
32 * Markus Armbruster, 2005-2012
41 #include <sys/types.h>
50 #include "prototypes.h"
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 int do_extend(struct empfile *, int);
61 static void do_blank(struct empfile *, void *, int, int);
62 static int ef_check(int);
64 static unsigned ef_generation;
67 * Open the file-backed table TYPE (EF_SECTOR, ...).
68 * HOW are flags to control operation. Naturally, immutable flags are
70 * The table must not be already open.
71 * Return non-zero on success, zero on failure.
74 ef_open(int type, int how)
77 int oflags, fd, fsiz, fids, nslots, fail;
79 if (ef_check(type) < 0)
81 if (CANT_HAPPEN(how & EFF_IMMUTABLE))
82 how &= ~EFF_IMMUTABLE;
86 if (CANT_HAPPEN(!ep->file || ep->base != EF_BAD || ep->fd >= 0))
89 if (how & EFF_PRIVATE)
92 oflags |= O_CREAT | O_TRUNC;
93 fd = open_locked(ep->file, oflags, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
95 logerror("Can't open %s (%s)", ep->file, strerror(errno));
100 if (how & EFF_CREATE) {
101 fids = ep->nent >= 0 ? ep->nent : 0;
104 if (fsiz % ep->size) {
105 logerror("Can't open %s (file size not a multiple of record size %d)",
110 fids = fsiz / ep->size;
111 if (ep->nent >= 0 && ep->nent != fids) {
112 logerror("Can't open %s (got %d records instead of %d)",
113 ep->file, fids, ep->nent);
120 if (ep->flags & EFF_STATIC) {
121 /* ep->cache already points to space for ep->csize elements */
123 if (fids > ep->csize) {
124 CANT_HAPPEN(ep->nent >= 0); /* insufficient static cache */
125 logerror("Can't open %s (file larger than %d records)",
126 ep->file, ep->csize);
132 if (CANT_HAPPEN(ep->cache))
137 nslots = blksize(fd) / ep->size;
138 if (!ef_realloc_cache(ep, nslots)) {
139 logerror("Can't map %s (%s)", ep->file, strerror(errno));
146 ep->flags = (ep->flags & EFF_IMMUTABLE) | (how & ~EFF_CREATE);
149 if (how & EFF_CREATE) {
150 /* populate new file */
152 fail = !do_extend(ep, fids);
155 if ((how & EFF_MEM) && fids)
156 fail = fillcache(ep, 0) != fids;
161 ep->cids = 0; /* prevent cache flush */
172 open_locked(char *name, int oflags, mode_t mode)
174 int rdlonly = (oflags & O_ACCMODE) == O_RDONLY;
178 fd = _sopen(name, oflags | O_BINARY, rdlonly ? SH_DENYNO : SH_DENYWR,
185 fd = open(name, oflags, mode);
189 lock.l_type = rdlonly ? F_RDLCK : F_WRLCK;
190 lock.l_whence = SEEK_SET;
191 lock.l_start = lock.l_len = 0;
192 if (fcntl(fd, F_SETLK, &lock) == -1) {
201 * Reallocate cache for table EP to hold COUNT slots.
202 * The table must not be allocated statically.
203 * The cache may still be unmapped.
204 * If reallocation succeeds, any pointers obtained from ef_ptr()
206 * If it fails, the cache is unchanged, and errno is set.
207 * Return non-zero on success, zero on failure.
210 ef_realloc_cache(struct empfile *ep, int count)
214 if (CANT_HAPPEN(ep->flags & EFF_STATIC))
216 if (CANT_HAPPEN(count < 0))
220 * Avoid zero slots, because that can lead to null cache, which
221 * would be interpreted as unmapped cache.
225 cache = realloc(ep->cache, count * ep->size);
235 * Open the table TYPE, which is a view of a base table
236 * The table must not be already open.
237 * Return non-zero on success, zero on failure.
238 * Beware: views work only as long as the base table doesn't change size!
239 * You must close the view before closing its base table.
242 ef_open_view(int type)
247 if (ef_check(type) < 0)
251 if (ef_check(base) < 0)
253 if (CANT_HAPPEN(!(ef_flags(base) & EFF_MEM)
255 || ep->size != empfile[base].size
256 || ep->nent != empfile[base].nent
257 || ep->cache || ep->oninit || ep->postread
258 || ep->prewrite || ep->onresize))
261 ep->cache = empfile[base].cache;
262 ep->csize = empfile[base].csize;
263 ep->flags |= EFF_MEM;
264 ep->baseid = empfile[base].baseid;
265 ep->cids = empfile[base].cids;
266 ep->fids = empfile[base].fids;
271 * Close the open table TYPE (EF_SECTOR, ...).
272 * Return non-zero on success, zero on failure.
280 if (ef_check(type) < 0)
284 if (EF_IS_VIEW(type)) {
290 if (!(ep->flags & EFF_STATIC)) {
295 if (close(ep->fd) < 0) {
296 logerror("Error closing %s (%s)", ep->file, strerror(errno));
301 ep->flags &= EFF_IMMUTABLE;
302 ep->baseid = ep->cids = ep->fids = 0;
309 * Flush file-backed table TYPE (EF_SECTOR, ...) to its backing file.
310 * Do nothing if the table is privately mapped.
311 * Update timestamps of written elements if table is EFF_TYPED.
312 * Return non-zero on success, zero on failure.
319 if (ef_check(type) < 0)
322 if (ep->flags & EFF_PRIVATE)
323 return 1; /* nothing to do */
324 if (CANT_HAPPEN(ep->fd < 0))
327 * We don't know which cache entries are dirty. ef_write() writes
328 * through, but direct updates through ef_ptr() don't. They are
329 * allowed only with EFF_MEM. Assume the whole cash is dirty
332 if (ep->flags & EFF_MEM) {
333 if (do_write(ep, ep->cache, ep->baseid, ep->cids) < 0)
341 * Return pointer to element ID in table TYPE if it exists, else NULL.
342 * The table must be fully cached, i.e. flags & EFF_MEM.
343 * The caller is responsible for flushing changes he makes.
346 ef_ptr(int type, int id)
350 if (ef_check(type) < 0)
353 if (CANT_HAPPEN(!(ep->flags & EFF_MEM) || !ep->cache))
355 if (id < 0 || id >= ep->fids)
357 return ep->cache + ep->size * id;
361 * Read element ID from table TYPE into buffer INTO.
362 * FIXME pass buffer size!
363 * INTO is marked fresh with ef_mark_fresh().
364 * Return non-zero on success, zero on failure.
367 ef_read(int type, int id, void *into)
372 if (ef_check(type) < 0)
375 if (CANT_HAPPEN(!ep->cache))
377 if (id < 0 || id >= ep->fids)
380 if (ep->flags & EFF_MEM) {
381 cachep = ep->cache + id * ep->size;
383 if (ep->baseid + ep->cids <= id || ep->baseid > id) {
384 if (fillcache(ep, id) < 1)
387 cachep = ep->cache + (id - ep->baseid) * ep->size;
389 memcpy(into, cachep, ep->size);
390 ef_mark_fresh(type, into);
393 ep->postread(id, into);
398 * Fill cache of file-backed EP with elements starting at ID.
399 * If any were read, return their number.
400 * Else return -1 and leave the cache unchanged.
403 fillcache(struct empfile *ep, int id)
407 if (CANT_HAPPEN(!ep->cache))
410 ret = do_read(ep, ep->cache, id, MIN(ep->csize, ep->fids - id));
420 do_read(struct empfile *ep, void *buf, int id, int count)
425 if (CANT_HAPPEN(ep->fd < 0 || id < 0 || count < 0))
428 if (lseek(ep->fd, id * ep->size, SEEK_SET) == (off_t)-1) {
429 logerror("Error seeking %s to elt %d (%s)",
430 ep->file, id, strerror(errno));
435 n = count * ep->size;
437 ret = read(ep->fd, p, n);
439 if (errno != EINTR) {
440 logerror("Error reading %s elt %d (%s)",
442 id + (int)((p - (char *)buf) / ep->size),
446 } else if (ret == 0) {
447 logerror("Unexpected EOF reading %s elt %d",
448 ep->file, id + (int)((p - (char *)buf) / ep->size));
456 return (p - (char *)buf) / ep->size;
460 * Write COUNT elements starting at ID from BUF to file-backed EP.
461 * Update the timestamp if the table is EFF_TYPED.
462 * Don't actually write if table is privately mapped.
463 * Return 0 on success, -1 on error (file may be corrupt then).
466 do_write(struct empfile *ep, void *buf, int id, int count)
470 struct emptypedstr *elt;
473 if (CANT_HAPPEN(ep->fd < 0 || id < 0 || count < 0))
476 if (ep->flags & EFF_TYPED) {
477 now = ep->flags & EFF_NOTIME ? (time_t)-1 : time(NULL);
478 for (i = 0; i < count; i++) {
480 * TODO Oopses here could be due to bad data corruption.
481 * Fail instead of attempting to recover?
483 elt = (struct emptypedstr *)((char *)buf + i * ep->size);
484 if (CANT_HAPPEN(elt->ef_type != ep->uid))
485 elt->ef_type = ep->uid;
486 if (CANT_HAPPEN(elt->uid != id + i))
488 if (now != (time_t)-1)
489 elt->timestamp = now;
493 if (ep->flags & EFF_PRIVATE)
496 if (lseek(ep->fd, id * ep->size, SEEK_SET) == (off_t)-1) {
497 logerror("Error seeking %s to elt %d (%s)",
498 ep->file, id, strerror(errno));
503 n = count * ep->size;
505 ret = write(ep->fd, p, n);
507 if (errno != EINTR) {
508 logerror("Error writing %s elt %d (%s)",
510 id + (int)((p - (char *)buf) / ep->size),
524 * Write element ID into table TYPE from buffer FROM.
525 * FIXME pass buffer size!
526 * Update timestamp in FROM if table is EFF_TYPED.
527 * If table is file-backed and not privately mapped, write through
528 * cache straight to disk.
529 * Cannot write beyond the end of fully cached table (flags & EFF_MEM).
530 * Can write at the end of partially cached table.
531 * FROM must be fresh; see ef_make_stale().
532 * Return non-zero on success, zero on failure.
535 ef_write(int type, int id, void *from)
540 if (ef_check(type) < 0)
543 if (CANT_HAPPEN((ep->flags & (EFF_MEM | EFF_PRIVATE)) == EFF_PRIVATE))
545 if (CANT_HAPPEN(ep->nent >= 0 && id >= ep->nent))
546 return 0; /* beyond fixed size */
548 if (id >= ep->fids) {
549 /* beyond end of file */
550 if (CANT_HAPPEN((ep->flags & EFF_MEM) || id > ep->fids))
551 return 0; /* not implemented */
552 /* write at end of file extends it */
557 if (id >= ep->baseid && id < ep->baseid + ep->cids) {
558 cachep = ep->cache + (id - ep->baseid) * ep->size;
560 must_be_fresh(ep, from);
564 ep->prewrite(id, cachep, from);
566 if (do_write(ep, from, id, 1) < 0)
569 if (cachep && cachep != from) /* update the cache if necessary */
570 memcpy(cachep, from, ep->size);
576 * BUF is an element of table TYPE.
577 * ID is its new element ID.
578 * If table is EFF_TYPED, change id and sequence number stored in BUF.
582 ef_set_uid(int type, void *buf, int uid)
584 struct emptypedstr *elt;
587 if (ef_check(type) < 0)
590 if (!(ep->flags & EFF_TYPED))
596 elt->seqno = get_seqno(ep, uid);
600 * Return sequence number of element ID in table EP.
601 * Return zero if table is not EFF_TYPED (it has no sequence number
605 get_seqno(struct empfile *ep, int id)
607 struct emptypedstr *elt;
609 if (!(ep->flags & EFF_TYPED))
611 if (id < 0 || id >= ep->fids)
613 if (id >= ep->baseid && id < ep->baseid + ep->cids)
614 elt = (void *)(ep->cache + (id - ep->baseid) * ep->size);
616 /* need a buffer, steal last cache slot */
617 if (ep->cids == ep->csize)
619 elt = (void *)(ep->cache + ep->cids * ep->size);
620 if (do_read(ep, elt, id, 1) < 0)
621 return 0; /* deep trouble */
627 * Increment sequence number in BUF, which is about to be written to EP.
628 * Do nothing if table is not EFF_TYPED (it has no sequence number
630 * Else, BUF's sequence number must match the one in EP's cache. If
631 * it doesn't, we're about to clobber a previous write.
634 new_seqno(struct empfile *ep, void *buf)
636 struct emptypedstr *elt = buf;
639 if (!(ep->flags & EFF_TYPED))
641 old_seqno = get_seqno(ep, elt->uid);
642 CANT_HAPPEN(old_seqno != elt->seqno);
643 elt->seqno = old_seqno + 1;
647 * Make all copies stale.
648 * Only fresh copies may be written back to the cache.
649 * To be called by functions that may yield the processor.
650 * Writing an copy when there has been a yield since it was read is
651 * unsafe, because we could clobber another thread's write then.
652 * Robust code must assume the that any function that may yield does
653 * yield. Marking copies stale there lets us catch unsafe writes.
661 /* Mark copy of an element of table TYPE in BUF fresh. */
663 ef_mark_fresh(int type, void *buf)
667 if (ef_check(type) < 0)
670 if (!(ep->flags & EFF_TYPED))
672 ((struct emptypedstr *)buf)->generation = ef_generation;
676 must_be_fresh(struct empfile *ep, void *buf)
678 struct emptypedstr *elt = buf;
680 if (!(ep->flags & EFF_TYPED))
682 CANT_HAPPEN(elt->generation != (ef_generation & 0xfff));
686 * Extend table TYPE by COUNT elements.
687 * Any pointers obtained from ef_ptr() become invalid.
688 * Return non-zero on success, zero on failure.
691 ef_extend(int type, int count)
695 if (ef_check(type) < 0)
699 logerror("Can't extend %s, its size is fixed", ep->name);
702 if (!do_extend(ep, count))
710 do_extend(struct empfile *ep, int count)
713 int need_sentinel, i, id;
715 if (CANT_HAPPEN(EF_IS_VIEW(ep->uid)) || count < 0)
719 if (ep->flags & EFF_MEM) {
720 need_sentinel = (ep->flags & EFF_SENTINEL) != 0;
721 if (id + count + need_sentinel > ep->csize) {
722 if (ep->flags & EFF_STATIC) {
723 logerror("Can't extend %s beyond %d elements",
724 ep->name, ep->csize - need_sentinel);
727 if (!ef_realloc_cache(ep, id + count + need_sentinel)) {
728 logerror("Can't extend %s to %d elements (%s)",
729 ep->name, id + count, strerror(errno));
733 p = ep->cache + id * ep->size;
734 do_blank(ep, p, id, count);
736 if (do_write(ep, p, id, count) < 0)
740 memset(ep->cache + (id + count) * ep->size, 0, ep->size);
741 ep->cids = id + count;
743 /* need a buffer, steal last cache slot */
744 if (ep->cids == ep->csize)
746 p = ep->cache + ep->cids * ep->size;
747 for (i = 0; i < count; i++) {
748 do_blank(ep, p, id + i, 1);
749 if (do_write(ep, p, id + i, 1) < 0)
753 ep->fids = id + count;
758 * Initialize element ID for table TYPE in BUF.
759 * FIXME pass buffer size!
760 * BUF is marked fresh with ef_mark_fresh().
763 ef_blank(int type, int id, void *buf)
766 struct emptypedstr *elt;
768 if (ef_check(type) < 0)
771 do_blank(ep, buf, id, 1);
772 if (ep->flags & EFF_TYPED) {
774 elt->seqno = get_seqno(ep, elt->uid);
776 ef_mark_fresh(type, buf);
780 * Initialize COUNT elements of EP in BUF, starting with element ID.
783 do_blank(struct empfile *ep, void *buf, int id, int count)
786 struct emptypedstr *elt;
788 memset(buf, 0, count * ep->size);
789 for (i = 0; i < count; i++) {
790 elt = (struct emptypedstr *)((char *)buf + i * ep->size);
791 if (ep->flags & EFF_TYPED) {
792 elt->ef_type = ep->uid;
801 * Truncate table TYPE to COUNT elements.
802 * Any pointers obtained from ef_ptr() become invalid.
803 * Return non-zero on success, zero on failure.
806 ef_truncate(int type, int count)
811 if (ef_check(type) < 0 || CANT_HAPPEN(EF_IS_VIEW(type)))
815 logerror("Can't truncate %s, its size is fixed", ep->name);
818 if (CANT_HAPPEN(count < 0 || count > ep->fids))
821 if (ep->fd >= 0 && !(ep->flags & EFF_PRIVATE)) {
822 if (ftruncate(ep->fd, count * ep->size) < 0) {
823 logerror("Can't truncate %s to %d elements (%s)",
824 ep->file, count, strerror(errno));
830 if (ep->flags & EFF_MEM) {
831 need_sentinel = (ep->flags & EFF_SENTINEL) != 0;
832 if (!(ep->flags & EFF_STATIC)) {
833 if (!ef_realloc_cache(ep, count + need_sentinel)) {
834 logerror("Can't shrink %s cache after truncate (%s)",
835 ep->name, strerror(errno));
836 /* continue with unshrunk cache */
840 memset(ep->cache + count * ep->size, 0, ep->size);
843 if (ep->baseid >= count)
845 else if (ep->cids > count - ep->baseid)
846 ep->cids = count - ep->baseid;
857 if (ef_check(type) < 0)
859 return empfile[type].cadef;
865 if (ef_check(type) < 0)
867 return empfile[type].fids;
873 if (ef_check(type) < 0)
875 return empfile[type].flags;
881 if (ef_check(type) < 0)
883 if (empfile[type].fd <= 0)
885 return fdate(empfile[type].fd);
889 * Search for a table matching NAME, return its table type.
890 * Return M_NOTFOUND if there are no matches, M_NOTUNIQUE if there are
894 ef_byname(char *name)
896 return stmtch(name, empfile, offsetof(struct empfile, name),
901 * Search CHOICES[] for a table type matching NAME, return it.
902 * Return M_NOTFOUND if there are no matches, M_NOTUNIQUE if there are
904 * CHOICES[] must be terminated with a negative value.
907 ef_byname_from(char *name, int choices[])
913 for (p = choices; *p >= 0; p++) {
914 if (ef_check(*p) < 0)
916 switch (mineq(name, empfile[*p].name)) {
932 * Return name of table TYPE. Always a single, short word.
937 if (ef_check(type) < 0)
939 return empfile[type].name;
943 * Return "pretty" name of table TYPE.
946 ef_nameof_pretty(int type)
948 if (ef_check(type) < 0)
950 return empfile[type].pretty_name;
956 if (CANT_HAPPEN((unsigned)type >= EF_MAX))
962 * Ensure table contains element ID.
963 * If necessary, extend it in steps of COUNT elements.
964 * Return non-zero on success, zero on failure.
967 ef_ensure_space(int type, int id, int count)
969 if (ef_check(type) < 0)
973 while (id >= empfile[type].fids) {
974 if (!ef_extend(type, count))
981 * Return maximum ID acceptable for table TYPE.
982 * Assuming infinite memory and disk space.
985 ef_id_limit(int type)
989 if (ef_check(type) < 0)
994 if (ep->flags & EFF_MEM) {
995 if (ep->flags & EFF_STATIC)
996 return ep->csize - 1 - ((ep->flags & EFF_SENTINEL) != 0);