2 * Empire - A multi-player, client/server Internet based war game.
3 * Copyright (C) 1986-2014, 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-2013
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))
88 if (CANT_HAPPEN(ep->prewrite && !(how & EFF_MEM)))
89 return 0; /* not implemented */
91 if (how & EFF_PRIVATE)
94 oflags |= O_CREAT | O_TRUNC;
95 fd = open_locked(ep->file, oflags, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
97 logerror("Can't open %s (%s)", ep->file, strerror(errno));
102 if (how & EFF_CREATE) {
103 fids = ep->nent >= 0 ? ep->nent : 0;
106 if (fsiz % ep->size) {
107 logerror("Can't open %s (file size not a multiple of record size %d)",
112 fids = fsiz / ep->size;
113 if (ep->nent >= 0 && ep->nent != fids) {
114 logerror("Can't open %s (got %d records instead of %d)",
115 ep->file, fids, ep->nent);
122 if (ep->flags & EFF_STATIC) {
123 /* ep->cache already points to space for ep->csize elements */
125 if (fids > ep->csize) {
126 CANT_HAPPEN(ep->nent >= 0); /* insufficient static cache */
127 logerror("Can't open %s (file larger than %d records)",
128 ep->file, ep->csize);
134 if (CANT_HAPPEN(ep->cache))
139 nslots = blksize(fd) / ep->size;
140 if (!ef_realloc_cache(ep, nslots)) {
141 logerror("Can't map %s (%s)", ep->file, strerror(errno));
148 ep->flags = (ep->flags & EFF_IMMUTABLE) | (how & ~EFF_CREATE);
151 if (how & EFF_CREATE) {
152 /* populate new file */
154 fail = !do_extend(ep, fids);
157 if ((how & EFF_MEM) && fids)
158 fail = fillcache(ep, 0) != fids;
163 ep->cids = 0; /* prevent cache flush */
174 open_locked(char *name, int oflags, mode_t mode)
176 int rdlonly = (oflags & O_ACCMODE) == O_RDONLY;
180 fd = _sopen(name, oflags | O_BINARY, rdlonly ? SH_DENYNO : SH_DENYWR,
187 fd = open(name, oflags, mode);
191 lock.l_type = rdlonly ? F_RDLCK : F_WRLCK;
192 lock.l_whence = SEEK_SET;
193 lock.l_start = lock.l_len = 0;
194 if (fcntl(fd, F_SETLK, &lock) == -1) {
203 * Reallocate cache for table EP to hold COUNT slots.
204 * The table must not be allocated statically.
205 * The cache may still be unmapped.
206 * If reallocation succeeds, any pointers obtained from ef_ptr()
208 * If it fails, the cache is unchanged, and errno is set.
209 * Return non-zero on success, zero on failure.
212 ef_realloc_cache(struct empfile *ep, int count)
216 if (CANT_HAPPEN(ep->flags & EFF_STATIC))
218 if (CANT_HAPPEN(count < 0))
222 * Avoid zero slots, because that can lead to null cache, which
223 * would be interpreted as unmapped cache.
227 cache = realloc(ep->cache, count * ep->size);
237 * Open the table TYPE, which is a view of a base table
238 * The table must not be already open.
239 * Return non-zero on success, zero on failure.
240 * Beware: views work only as long as the base table doesn't change size!
241 * You must close the view before closing its base table.
244 ef_open_view(int type)
249 if (ef_check(type) < 0)
253 if (ef_check(base) < 0)
255 if (CANT_HAPPEN(!(ef_flags(base) & EFF_MEM)
257 || ep->size != empfile[base].size
258 || ep->nent != empfile[base].nent
259 || ep->cache || ep->oninit || ep->postread
260 || ep->prewrite || ep->onresize))
263 ep->cache = empfile[base].cache;
264 ep->csize = empfile[base].csize;
265 ep->flags |= EFF_MEM;
266 ep->baseid = empfile[base].baseid;
267 ep->cids = empfile[base].cids;
268 ep->fids = empfile[base].fids;
273 * Close the open table TYPE (EF_SECTOR, ...).
274 * Return non-zero on success, zero on failure.
282 if (ef_check(type) < 0)
286 if (EF_IS_VIEW(type)) {
292 if (!(ep->flags & EFF_STATIC)) {
297 if (close(ep->fd) < 0) {
298 logerror("Error closing %s (%s)", ep->file, strerror(errno));
303 ep->flags &= EFF_IMMUTABLE;
304 ep->baseid = ep->cids = ep->fids = 0;
311 * Flush file-backed table TYPE (EF_SECTOR, ...) to its backing file.
312 * Do nothing if the table is privately mapped.
313 * Update timestamps of written elements if table is EFF_TYPED.
314 * Return non-zero on success, zero on failure.
321 if (ef_check(type) < 0)
324 if (ep->flags & EFF_PRIVATE)
325 return 1; /* nothing to do */
326 if (CANT_HAPPEN(ep->fd < 0))
329 * We don't know which cache entries are dirty. ef_write() writes
330 * through, but direct updates through ef_ptr() don't. They are
331 * allowed only with EFF_MEM. Assume the whole cash is dirty
334 if (ep->flags & EFF_MEM) {
335 if (do_write(ep, ep->cache, ep->baseid, ep->cids) < 0)
343 * Return pointer to element ID in table TYPE if it exists, else NULL.
344 * The table must be fully cached, i.e. flags & EFF_MEM.
345 * The caller is responsible for flushing changes he makes.
348 ef_ptr(int type, int id)
352 if (ef_check(type) < 0)
355 if (CANT_HAPPEN(!(ep->flags & EFF_MEM) || !ep->cache))
357 if (id < 0 || id >= ep->fids)
359 return ep->cache + ep->size * id;
363 * Read element ID from table TYPE into buffer INTO.
364 * FIXME pass buffer size!
365 * INTO is marked fresh with ef_mark_fresh().
366 * Return non-zero on success, zero on failure.
369 ef_read(int type, int id, void *into)
374 if (ef_check(type) < 0)
377 if (CANT_HAPPEN(!ep->cache))
379 if (id < 0 || id >= ep->fids)
382 if (ep->flags & EFF_MEM) {
383 cachep = ep->cache + id * ep->size;
385 if (ep->baseid + ep->cids <= id || ep->baseid > id) {
386 if (fillcache(ep, id) < 1)
389 cachep = ep->cache + (id - ep->baseid) * ep->size;
391 memcpy(into, cachep, ep->size);
392 ef_mark_fresh(type, into);
395 ep->postread(id, into);
400 * Fill cache of file-backed EP with elements starting at ID.
401 * If any were read, return their number.
402 * Else return -1 and leave the cache unchanged.
405 fillcache(struct empfile *ep, int id)
409 if (CANT_HAPPEN(!ep->cache))
412 ret = do_read(ep, ep->cache, id, MIN(ep->csize, ep->fids - id));
422 do_read(struct empfile *ep, void *buf, int id, int count)
427 if (CANT_HAPPEN(ep->fd < 0 || id < 0 || count < 0))
430 if (lseek(ep->fd, id * ep->size, SEEK_SET) == (off_t)-1) {
431 logerror("Error seeking %s to elt %d (%s)",
432 ep->file, id, strerror(errno));
437 n = count * ep->size;
439 ret = read(ep->fd, p, n);
441 if (errno != EINTR) {
442 logerror("Error reading %s elt %d (%s)",
444 id + (int)((p - (char *)buf) / ep->size),
448 } else if (ret == 0) {
449 logerror("Unexpected EOF reading %s elt %d",
450 ep->file, id + (int)((p - (char *)buf) / ep->size));
458 return (p - (char *)buf) / ep->size;
462 * Write COUNT elements starting at ID from BUF to file-backed EP.
463 * Update the timestamp if the table is EFF_TYPED.
464 * Don't actually write if table is privately mapped.
465 * Return 0 on success, -1 on error (file may be corrupt then).
468 do_write(struct empfile *ep, void *buf, int id, int count)
472 struct emptypedstr *elt;
475 if (CANT_HAPPEN(ep->fd < 0 || id < 0 || count < 0))
478 if (ep->flags & EFF_TYPED) {
479 now = ep->flags & EFF_NOTIME ? (time_t)-1 : time(NULL);
480 for (i = 0; i < count; i++) {
482 * TODO Oopses here could be due to bad data corruption.
483 * Fail instead of attempting to recover?
485 elt = (struct emptypedstr *)((char *)buf + i * ep->size);
486 if (CANT_HAPPEN(elt->ef_type != ep->uid))
487 elt->ef_type = ep->uid;
488 if (CANT_HAPPEN(elt->uid != id + i))
490 if (now != (time_t)-1)
491 elt->timestamp = now;
495 if (ep->flags & EFF_PRIVATE)
498 if (lseek(ep->fd, id * ep->size, SEEK_SET) == (off_t)-1) {
499 logerror("Error seeking %s to elt %d (%s)",
500 ep->file, id, strerror(errno));
505 n = count * ep->size;
507 ret = write(ep->fd, p, n);
509 if (errno != EINTR) {
510 logerror("Error writing %s elt %d (%s)",
512 id + (int)((p - (char *)buf) / ep->size),
526 * Write element ID into table TYPE from buffer FROM.
527 * FIXME pass buffer size!
528 * Update timestamp in FROM if table is EFF_TYPED.
529 * If table is file-backed and not privately mapped, write through
530 * cache straight to disk.
531 * Cannot write beyond the end of fully cached table (flags & EFF_MEM).
532 * Can write at the end of partially cached table.
533 * FROM must be fresh; see ef_make_stale().
534 * Return non-zero on success, zero on failure.
537 ef_write(int type, int id, void *from)
542 if (ef_check(type) < 0)
545 if (CANT_HAPPEN((ep->flags & (EFF_MEM | EFF_PRIVATE)) == EFF_PRIVATE))
547 if (CANT_HAPPEN(id < 0))
549 if (CANT_HAPPEN(ep->nent >= 0 && id >= ep->nent))
550 return 0; /* beyond fixed size */
552 if (id >= ep->fids) {
553 /* beyond end of file */
554 if (CANT_HAPPEN((ep->flags & EFF_MEM) || id > ep->fids))
555 return 0; /* not implemented */
556 /* write at end of file extends it */
561 if (id >= ep->baseid && id < ep->baseid + ep->cids) {
562 cachep = ep->cache + (id - ep->baseid) * ep->size;
564 must_be_fresh(ep, from);
568 ep->prewrite(id, cachep, from);
570 if (do_write(ep, from, id, 1) < 0)
573 if (cachep && cachep != from) /* update the cache if necessary */
574 memcpy(cachep, from, ep->size);
580 * BUF is an element of table TYPE.
581 * ID is its new element ID.
582 * If table is EFF_TYPED, change id and sequence number stored in BUF.
586 ef_set_uid(int type, void *buf, int uid)
588 struct emptypedstr *elt;
591 if (ef_check(type) < 0)
594 if (!(ep->flags & EFF_TYPED))
600 elt->seqno = get_seqno(ep, uid);
604 * Return sequence number of element ID in table EP.
605 * Return zero if table is not EFF_TYPED (it has no sequence number
609 get_seqno(struct empfile *ep, int id)
611 struct emptypedstr *elt;
613 if (!(ep->flags & EFF_TYPED))
615 if (id < 0 || id >= ep->fids)
617 if (id >= ep->baseid && id < ep->baseid + ep->cids)
618 elt = (void *)(ep->cache + (id - ep->baseid) * ep->size);
620 /* need a buffer, steal last cache slot */
621 if (ep->cids == ep->csize)
623 elt = (void *)(ep->cache + ep->cids * ep->size);
624 if (do_read(ep, elt, id, 1) < 0)
625 return 0; /* deep trouble */
631 * Increment sequence number in BUF, which is about to be written to EP.
632 * Do nothing if table is not EFF_TYPED (it has no sequence number
634 * Else, BUF's sequence number must match the one in EP's cache. If
635 * it doesn't, we're about to clobber a previous write.
638 new_seqno(struct empfile *ep, void *buf)
640 struct emptypedstr *elt = buf;
643 if (!(ep->flags & EFF_TYPED))
645 old_seqno = get_seqno(ep, elt->uid);
646 CANT_HAPPEN(old_seqno != elt->seqno);
647 elt->seqno = old_seqno + 1;
651 * Make all copies stale.
652 * Only fresh copies may be written back to the cache.
653 * To be called by functions that may yield the processor.
654 * Writing an copy when there has been a yield since it was read is
655 * unsafe, because we could clobber another thread's write then.
656 * Robust code must assume the that any function that may yield does
657 * yield. Marking copies stale there lets us catch unsafe writes.
665 /* Mark copy of an element of table TYPE in BUF fresh. */
667 ef_mark_fresh(int type, void *buf)
671 if (ef_check(type) < 0)
674 if (!(ep->flags & EFF_TYPED))
676 ((struct emptypedstr *)buf)->generation = ef_generation;
680 must_be_fresh(struct empfile *ep, void *buf)
682 struct emptypedstr *elt = buf;
684 if (!(ep->flags & EFF_TYPED))
686 CANT_HAPPEN(elt->generation != (ef_generation & 0xfff));
690 * Extend table TYPE by COUNT elements.
691 * Any pointers obtained from ef_ptr() become invalid.
692 * Return non-zero on success, zero on failure.
695 ef_extend(int type, int count)
699 if (ef_check(type) < 0)
703 logerror("Can't extend %s, its size is fixed", ep->name);
706 if (!do_extend(ep, count))
714 do_extend(struct empfile *ep, int count)
717 int need_sentinel, i, id;
719 if (CANT_HAPPEN(EF_IS_VIEW(ep->uid)) || count < 0)
723 if (ep->flags & EFF_MEM) {
724 need_sentinel = (ep->flags & EFF_SENTINEL) != 0;
725 if (id + count + need_sentinel > ep->csize) {
726 if (ep->flags & EFF_STATIC) {
727 logerror("Can't extend %s beyond %d elements",
728 ep->name, ep->csize - need_sentinel);
731 if (!ef_realloc_cache(ep, id + count + need_sentinel)) {
732 logerror("Can't extend %s to %d elements (%s)",
733 ep->name, id + count, strerror(errno));
737 p = ep->cache + id * ep->size;
738 do_blank(ep, p, id, count);
740 if (do_write(ep, p, id, count) < 0)
744 memset(ep->cache + (id + count) * ep->size, 0, ep->size);
745 ep->cids = id + count;
747 /* need a buffer, steal last cache slot */
748 if (ep->cids == ep->csize)
750 p = ep->cache + ep->cids * ep->size;
751 for (i = 0; i < count; i++) {
752 do_blank(ep, p, id + i, 1);
753 if (do_write(ep, p, id + i, 1) < 0)
757 ep->fids = id + count;
762 * Initialize element ID for table TYPE in BUF.
763 * FIXME pass buffer size!
764 * BUF is marked fresh with ef_mark_fresh().
767 ef_blank(int type, int id, void *buf)
770 struct emptypedstr *elt;
772 if (ef_check(type) < 0)
775 do_blank(ep, buf, id, 1);
776 if (ep->flags & EFF_TYPED) {
778 elt->seqno = get_seqno(ep, elt->uid);
780 ef_mark_fresh(type, buf);
784 * Initialize COUNT elements of EP in BUF, starting with element ID.
787 do_blank(struct empfile *ep, void *buf, int id, int count)
790 struct emptypedstr *elt;
792 memset(buf, 0, count * ep->size);
793 for (i = 0; i < count; i++) {
794 elt = (struct emptypedstr *)((char *)buf + i * ep->size);
795 if (ep->flags & EFF_TYPED) {
796 elt->ef_type = ep->uid;
805 * Truncate table TYPE to COUNT elements.
806 * Any pointers obtained from ef_ptr() become invalid.
807 * Return non-zero on success, zero on failure.
810 ef_truncate(int type, int count)
815 if (ef_check(type) < 0 || CANT_HAPPEN(EF_IS_VIEW(type)))
819 logerror("Can't truncate %s, its size is fixed", ep->name);
822 if (CANT_HAPPEN(count < 0 || count > ep->fids))
825 if (ep->fd >= 0 && !(ep->flags & EFF_PRIVATE)) {
826 if (ftruncate(ep->fd, count * ep->size) < 0) {
827 logerror("Can't truncate %s to %d elements (%s)",
828 ep->file, count, strerror(errno));
834 if (ep->flags & EFF_MEM) {
835 need_sentinel = (ep->flags & EFF_SENTINEL) != 0;
836 if (!(ep->flags & EFF_STATIC)) {
837 if (!ef_realloc_cache(ep, count + need_sentinel)) {
838 logerror("Can't shrink %s cache after truncate (%s)",
839 ep->name, strerror(errno));
840 /* continue with unshrunk cache */
844 memset(ep->cache + count * ep->size, 0, ep->size);
847 if (ep->baseid >= count)
849 else if (ep->cids > count - ep->baseid)
850 ep->cids = count - ep->baseid;
861 if (ef_check(type) < 0)
863 return empfile[type].cadef;
869 if (ef_check(type) < 0)
871 return empfile[type].fids;
877 if (ef_check(type) < 0)
879 return empfile[type].flags;
885 if (ef_check(type) < 0)
887 if (empfile[type].fd <= 0)
889 return fdate(empfile[type].fd);
893 * Search for a table matching NAME, return its table type.
894 * Return M_NOTFOUND if there are no matches, M_NOTUNIQUE if there are
898 ef_byname(char *name)
900 return stmtch(name, empfile, offsetof(struct empfile, name),
905 * Search CHOICES[] for a table type matching NAME, return it.
906 * Return M_NOTFOUND if there are no matches, M_NOTUNIQUE if there are
908 * CHOICES[] must be terminated with a negative value.
911 ef_byname_from(char *name, int choices[])
917 for (p = choices; *p >= 0; p++) {
918 if (ef_check(*p) < 0)
920 switch (mineq(name, empfile[*p].name)) {
936 * Return name of table TYPE. Always a single, short word.
941 if (ef_check(type) < 0)
943 return empfile[type].name;
947 * Return "pretty" name of table TYPE.
950 ef_nameof_pretty(int type)
952 if (ef_check(type) < 0)
954 return empfile[type].pretty_name;
960 if (CANT_HAPPEN((unsigned)type >= EF_MAX))
966 * Ensure table contains element ID.
967 * If necessary, extend it in steps of COUNT elements.
968 * Return non-zero on success, zero on failure.
971 ef_ensure_space(int type, int id, int count)
973 if (ef_check(type) < 0 || CANT_HAPPEN(id < 0))
976 while (id >= empfile[type].fids) {
977 if (!ef_extend(type, count))
984 * Return maximum ID acceptable for table TYPE.
985 * Assuming infinite memory and disk space.
988 ef_id_limit(int type)
992 if (ef_check(type) < 0)
997 if (ep->flags & EFF_MEM) {
998 if (ep->flags & EFF_STATIC)
999 return ep->csize - 1 - ((ep->flags & EFF_SENTINEL) != 0);