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
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-2011
41 #include <sys/types.h>
51 #include "prototypes.h"
53 static int open_locked(char *, int, mode_t);
54 static int ef_realloc_cache(struct empfile *, int);
55 static int fillcache(struct empfile *, int);
56 static int do_read(struct empfile *, void *, int, int);
57 static int do_write(struct empfile *, void *, int, int);
58 static unsigned get_seqno(struct empfile *, int);
59 static void new_seqno(struct empfile *, void *);
60 static void must_be_fresh(struct empfile *, void *);
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;
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));
101 if (fsiz % ep->size) {
102 logerror("Can't open %s (file size not a multiple of record size %d)",
107 fids = fsiz / ep->size;
108 if (ep->nent >= 0 && ep->nent != fids && !(how & EFF_CREATE)) {
109 logerror("Can't open %s (got %d records instead of %d)",
110 ep->file, fids, ep->nent);
116 if (ep->flags & EFF_STATIC) {
117 /* ep->cache already points to space for ep->csize elements */
119 if (fids > ep->csize) {
120 CANT_HAPPEN(ep->nent >= 0); /* insufficient static cache */
121 logerror("Can't open %s (file larger than %d records)",
122 ep->file, ep->csize);
128 if (CANT_HAPPEN(ep->cache))
133 nslots = blksize(fd) / ep->size;
134 if (!ef_realloc_cache(ep, nslots)) {
135 logerror("Can't map %s (%s)", ep->file, strerror(errno));
143 ep->flags = (ep->flags & EFF_IMMUTABLE) | (how & ~EFF_CREATE);
146 /* map file into cache */
147 if ((how & EFF_MEM) && fids) {
148 if (fillcache(ep, 0) != fids) {
149 ep->cids = 0; /* prevent cache flush */
161 open_locked(char *name, int oflags, mode_t mode)
163 int rdlonly = (oflags & O_ACCMODE) == O_RDONLY;
167 fd = _sopen(name, oflags | O_BINARY, rdlonly ? SH_DENYNO : SH_DENYWR,
174 fd = open(name, oflags, mode);
178 lock.l_type = rdlonly ? F_RDLCK : F_WRLCK;
179 lock.l_whence = SEEK_SET;
180 lock.l_start = lock.l_len = 0;
181 if (fcntl(fd, F_SETLK, &lock) == -1) {
190 * Reallocate cache for table EP to hold COUNT slots.
191 * The table must not be allocated statically.
192 * The cache may still be unmapped.
193 * If reallocation succeeds, any pointers obtained from ef_ptr()
195 * If it fails, the cache is unchanged, and errno is set.
196 * Return non-zero on success, zero on failure.
199 ef_realloc_cache(struct empfile *ep, int count)
203 if (CANT_HAPPEN(ep->flags & EFF_STATIC))
205 if (CANT_HAPPEN(count < 0))
209 * Avoid zero slots, because that can lead to null cache, which
210 * would be interpreted as unmapped cache.
214 cache = realloc(ep->cache, count * ep->size);
224 * Open the table TYPE, which is a view of a base table
225 * The table must not be already open.
226 * Return non-zero on success, zero on failure.
227 * Beware: views work only as long as the base table doesn't change size!
228 * You must close the view before closing its base table.
231 ef_open_view(int type)
236 if (ef_check(type) < 0)
240 if (ef_check(base) < 0)
242 if (CANT_HAPPEN(!(ef_flags(base) & EFF_MEM)
244 || ep->size != empfile[base].size
245 || ep->nent != empfile[base].nent
246 || ep->cache || ep->oninit || ep->postread
247 || ep->prewrite || ep->onresize))
250 ep->cache = empfile[base].cache;
251 ep->csize = empfile[base].csize;
252 ep->flags |= EFF_MEM;
253 ep->baseid = empfile[base].baseid;
254 ep->cids = empfile[base].cids;
255 ep->fids = empfile[base].fids;
260 * Close the open table TYPE (EF_SECTOR, ...).
261 * Return non-zero on success, zero on failure.
269 if (ef_check(type) < 0)
273 if (EF_IS_VIEW(type)) {
279 if (!(ep->flags & EFF_STATIC)) {
284 if (close(ep->fd) < 0) {
285 logerror("Error closing %s (%s)", ep->file, strerror(errno));
290 ep->flags &= EFF_IMMUTABLE;
291 ep->baseid = ep->cids = ep->fids = 0;
298 * Flush file-backed table TYPE (EF_SECTOR, ...) to its backing file.
299 * Do nothing if the table is privately mapped.
300 * Update timestamps of written elements if table is EFF_TYPED.
301 * Return non-zero on success, zero on failure.
308 if (ef_check(type) < 0)
311 if (ep->flags & EFF_PRIVATE)
312 return 1; /* nothing to do */
313 if (CANT_HAPPEN(ep->fd < 0))
316 * We don't know which cache entries are dirty. ef_write() writes
317 * through, but direct updates through ef_ptr() don't. They are
318 * allowed only with EFF_MEM. Assume the whole cash is dirty
321 if (ep->flags & EFF_MEM) {
322 if (do_write(ep, ep->cache, ep->baseid, ep->cids) < 0)
330 * Return pointer to element ID in table TYPE if it exists, else NULL.
331 * The table must be fully cached, i.e. flags & EFF_MEM.
332 * The caller is responsible for flushing changes he makes.
335 ef_ptr(int type, int id)
339 if (ef_check(type) < 0)
342 if (CANT_HAPPEN(!(ep->flags & EFF_MEM) || !ep->cache))
344 if (id < 0 || id >= ep->fids)
346 return ep->cache + ep->size * id;
350 * Read element ID from table TYPE into buffer INTO.
351 * FIXME pass buffer size!
352 * INTO is marked fresh with ef_mark_fresh().
353 * Return non-zero on success, zero on failure.
356 ef_read(int type, int id, void *into)
361 if (ef_check(type) < 0)
364 if (CANT_HAPPEN(!ep->cache))
366 if (id < 0 || id >= ep->fids)
369 if (ep->flags & EFF_MEM) {
370 cachep = ep->cache + id * ep->size;
372 if (ep->baseid + ep->cids <= id || ep->baseid > id) {
373 if (fillcache(ep, id) < 1)
376 cachep = ep->cache + (id - ep->baseid) * ep->size;
378 memcpy(into, cachep, ep->size);
379 ef_mark_fresh(type, into);
382 ep->postread(id, into);
387 * Fill cache of file-backed EP with elements starting at ID.
388 * If any were read, return their number.
389 * Else return -1 and leave the cache unchanged.
392 fillcache(struct empfile *ep, int id)
396 if (CANT_HAPPEN(!ep->cache))
399 ret = do_read(ep, ep->cache, id, MIN(ep->csize, ep->fids - id));
409 do_read(struct empfile *ep, void *buf, int id, int count)
414 if (CANT_HAPPEN(ep->fd < 0 || id < 0 || count < 0))
417 if (lseek(ep->fd, id * ep->size, SEEK_SET) == (off_t)-1) {
418 logerror("Error seeking %s to elt %d (%s)",
419 ep->file, id, strerror(errno));
424 n = count * ep->size;
426 ret = read(ep->fd, p, n);
428 if (errno != EINTR) {
429 logerror("Error reading %s elt %d (%s)",
431 id + (int)((p - (char *)buf) / ep->size),
435 } else if (ret == 0) {
436 logerror("Unexpected EOF reading %s elt %d",
437 ep->file, id + (int)((p - (char *)buf) / ep->size));
445 return (p - (char *)buf) / ep->size;
449 * Write COUNT elements starting at ID from BUF to file-backed EP.
450 * Update the timestamp if the table is EFF_TYPED.
451 * Don't actually write if table is privately mapped.
452 * Return 0 on success, -1 on error (file may be corrupt then).
455 do_write(struct empfile *ep, void *buf, int id, int count)
459 struct emptypedstr *elt;
462 if (CANT_HAPPEN(ep->fd < 0 || id < 0 || count < 0))
465 if (ep->flags & EFF_TYPED) {
466 now = ep->flags & EFF_NOTIME ? (time_t)-1 : time(NULL);
467 for (i = 0; i < count; i++) {
469 * TODO Oopses here could be due to bad data corruption.
470 * Fail instead of attempting to recover?
472 elt = (struct emptypedstr *)((char *)buf + i * ep->size);
473 if (CANT_HAPPEN(elt->ef_type != ep->uid))
474 elt->ef_type = ep->uid;
475 if (CANT_HAPPEN(elt->uid != id + i))
477 if (now != (time_t)-1)
478 elt->timestamp = now;
482 if (ep->flags & EFF_PRIVATE)
485 if (lseek(ep->fd, id * ep->size, SEEK_SET) == (off_t)-1) {
486 logerror("Error seeking %s to elt %d (%s)",
487 ep->file, id, strerror(errno));
492 n = count * ep->size;
494 ret = write(ep->fd, p, n);
496 if (errno != EINTR) {
497 logerror("Error writing %s elt %d (%s)",
499 id + (int)((p - (char *)buf) / ep->size),
513 * Write element ID into table TYPE from buffer FROM.
514 * FIXME pass buffer size!
515 * Update timestamp in FROM if table is EFF_TYPED.
516 * If table is file-backed and not privately mapped, write through
517 * cache straight to disk.
518 * Cannot write beyond the end of fully cached table (flags & EFF_MEM).
519 * Can write at the end of partially cached table.
520 * FROM must be fresh; see ef_make_stale().
521 * Return non-zero on success, zero on failure.
524 ef_write(int type, int id, void *from)
529 if (ef_check(type) < 0)
532 if (CANT_HAPPEN((ep->flags & (EFF_MEM | EFF_PRIVATE)) == EFF_PRIVATE))
535 if (id >= ep->fids) {
536 /* beyond end of file */
537 if (CANT_HAPPEN((ep->flags & EFF_MEM) || id > ep->fids))
538 return 0; /* not implemented */
539 /* write at end of file extends it */
544 if (id >= ep->baseid && id < ep->baseid + ep->cids) {
545 cachep = ep->cache + (id - ep->baseid) * ep->size;
547 must_be_fresh(ep, from);
551 ep->prewrite(id, cachep, from);
553 if (do_write(ep, from, id, 1) < 0)
556 if (cachep && cachep != from) /* update the cache if necessary */
557 memcpy(cachep, from, ep->size);
563 * BUF is an element of table TYPE.
564 * ID is its new element ID.
565 * If table is EFF_TYPED, change id and sequence number stored in BUF.
569 ef_set_uid(int type, void *buf, int uid)
571 struct emptypedstr *elt;
574 if (ef_check(type) < 0)
577 if (!(ep->flags & EFF_TYPED))
583 elt->seqno = get_seqno(ep, uid);
587 * Return sequence number of element ID in table EP.
588 * Return zero if table is not EFF_TYPED (it has no sequence number
592 get_seqno(struct empfile *ep, int id)
594 struct emptypedstr *elt;
596 if (!(ep->flags & EFF_TYPED))
598 if (id < 0 || id >= ep->fids)
600 if (id >= ep->baseid && id < ep->baseid + ep->cids)
601 elt = (void *)(ep->cache + (id - ep->baseid) * ep->size);
603 /* need a buffer, steal last cache slot */
604 if (ep->cids == ep->csize)
606 elt = (void *)(ep->cache + ep->cids * ep->size);
607 if (do_read(ep, elt, id, 1) < 0)
608 return 0; /* deep trouble */
614 * Increment sequence number in BUF, which is about to be written to EP.
615 * Do nothing if table is not EFF_TYPED (it has no sequence number
617 * Else, BUF's sequence number must match the one in EP's cache. If
618 * it doesn't, we're about to clobber a previous write.
621 new_seqno(struct empfile *ep, void *buf)
623 struct emptypedstr *elt = buf;
626 if (!(ep->flags & EFF_TYPED))
628 old_seqno = get_seqno(ep, elt->uid);
629 CANT_HAPPEN(old_seqno != elt->seqno);
630 elt->seqno = old_seqno + 1;
634 * Make all copies stale.
635 * Only fresh copies may be written back to the cache.
636 * To be called by functions that may yield the processor.
637 * Writing an copy when there has been a yield since it was read is
638 * unsafe, because we could clobber another thread's write then.
639 * Robust code must assume the that any function that may yield does
640 * yield. Marking copies stale there lets us catch unsafe writes.
648 /* Mark copy of an element of table TYPE in BUF fresh. */
650 ef_mark_fresh(int type, void *buf)
654 if (ef_check(type) < 0)
657 if (!(ep->flags & EFF_TYPED))
659 ((struct emptypedstr *)buf)->generation = ef_generation;
663 must_be_fresh(struct empfile *ep, void *buf)
665 struct emptypedstr *elt = buf;
667 if (!(ep->flags & EFF_TYPED))
669 CANT_HAPPEN(elt->generation != (ef_generation & 0xfff));
673 * Extend table TYPE by COUNT elements.
674 * Any pointers obtained from ef_ptr() become invalid.
675 * Return non-zero on success, zero on failure.
678 ef_extend(int type, int count)
682 int need_sentinel, i, id;
684 if (ef_check(type) < 0 || CANT_HAPPEN(EF_IS_VIEW(type)))
687 if (CANT_HAPPEN(count < 0))
691 if (ep->flags & EFF_MEM) {
692 need_sentinel = (ep->flags & EFF_SENTINEL) != 0;
693 if (id + count + need_sentinel > ep->csize) {
694 if (ep->flags & EFF_STATIC) {
695 logerror("Can't extend %s beyond %d elements",
696 ep->name, ep->csize - need_sentinel);
699 if (!ef_realloc_cache(ep, id + count + need_sentinel)) {
700 logerror("Can't extend %s to %d elements (%s)",
701 ep->name, id + count, strerror(errno));
705 p = ep->cache + id * ep->size;
706 do_blank(ep, p, id, count);
708 if (do_write(ep, p, id, count) < 0)
712 memset(ep->cache + (id + count) * ep->size, 0, ep->size);
713 ep->cids = id + count;
715 /* need a buffer, steal last cache slot */
716 if (ep->cids == ep->csize)
718 p = ep->cache + ep->cids * ep->size;
719 for (i = 0; i < count; i++) {
720 do_blank(ep, p, id + i, 1);
721 if (do_write(ep, p, id + i, 1) < 0)
725 ep->fids = id + count;
732 * Initialize element ID for table TYPE in BUF.
733 * FIXME pass buffer size!
734 * BUF is marked fresh with ef_mark_fresh().
737 ef_blank(int type, int id, void *buf)
740 struct emptypedstr *elt;
742 if (ef_check(type) < 0)
745 do_blank(ep, buf, id, 1);
746 if (ep->flags & EFF_TYPED) {
748 elt->seqno = get_seqno(ep, elt->uid);
750 ef_mark_fresh(type, buf);
754 * Initialize COUNT elements of EP in BUF, starting with element ID.
757 do_blank(struct empfile *ep, void *buf, int id, int count)
760 struct emptypedstr *elt;
762 memset(buf, 0, count * ep->size);
763 for (i = 0; i < count; i++) {
764 elt = (struct emptypedstr *)((char *)buf + i * ep->size);
765 if (ep->flags & EFF_TYPED) {
766 elt->ef_type = ep->uid;
775 * Truncate table TYPE to COUNT elements.
776 * Any pointers obtained from ef_ptr() become invalid.
777 * Return non-zero on success, zero on failure.
780 ef_truncate(int type, int count)
785 if (ef_check(type) < 0 || CANT_HAPPEN(EF_IS_VIEW(type)))
788 if (CANT_HAPPEN(count < 0 || count > ep->fids))
791 if (ep->fd >= 0 && !(ep->flags & EFF_PRIVATE)) {
792 if (ftruncate(ep->fd, count * ep->size) < 0) {
793 logerror("Can't truncate %s to %d elements (%s)",
794 ep->file, count, strerror(errno));
800 if (ep->flags & EFF_MEM) {
801 need_sentinel = (ep->flags & EFF_SENTINEL) != 0;
802 if (!(ep->flags & EFF_STATIC)) {
803 if (!ef_realloc_cache(ep, count + need_sentinel)) {
804 logerror("Can't shrink %s cache after truncate (%s)",
805 ep->name, strerror(errno));
806 /* continue with unshrunk cache */
810 memset(ep->cache + count * ep->size, 0, ep->size);
813 if (ep->baseid >= count)
815 else if (ep->cids > count - ep->baseid)
816 ep->cids = count - ep->baseid;
827 if (ef_check(type) < 0)
829 return empfile[type].cadef;
835 if (ef_check(type) < 0)
837 return empfile[type].fids;
843 if (ef_check(type) < 0)
845 return empfile[type].flags;
851 if (ef_check(type) < 0)
853 if (empfile[type].fd <= 0)
855 return fdate(empfile[type].fd);
859 * Search for a table matching NAME, return its table type.
860 * Return M_NOTFOUND if there are no matches, M_NOTUNIQUE if there are
864 ef_byname(char *name)
866 return stmtch(name, empfile, offsetof(struct empfile, name),
871 * Search CHOICES[] for a table type matching NAME, return it.
872 * Return M_NOTFOUND if there are no matches, M_NOTUNIQUE if there are
874 * CHOICES[] must be terminated with a negative value.
877 ef_byname_from(char *name, int choices[])
883 for (p = choices; *p >= 0; p++) {
884 if (ef_check(*p) < 0)
886 switch (mineq(name, empfile[*p].name)) {
904 if (ef_check(type) < 0)
905 return "bad ef_type";
906 return empfile[type].name;
912 if (CANT_HAPPEN((unsigned)type >= EF_MAX))
918 * Ensure table contains element ID.
919 * If necessary, extend it in steps of COUNT elements.
920 * Return non-zero on success, zero on failure.
923 ef_ensure_space(int type, int id, int count)
925 if (ef_check(type) < 0)
929 while (id >= empfile[type].fids) {
930 if (!ef_extend(type, count))
937 * Return maximum ID acceptable for table TYPE.
938 * Assuming infinite memory and disk space.
941 ef_id_limit(int type)
945 if (ef_check(type) < 0)
950 if (ep->flags & EFF_MEM) {
951 if (ep->flags & EFF_STATIC)
952 return ep->csize - 1 - ((ep->flags & EFF_SENTINEL) != 0);