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
40 #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 void do_blank(struct empfile *, void *, int, int);
61 static int ef_check(int);
63 static unsigned ef_generation;
66 * Open the file-backed table TYPE (EF_SECTOR, ...).
67 * HOW are flags to control operation. Naturally, immutable flags are
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().
74 ef_open(int type, int how, int nelt)
77 int oflags, fd, fsiz, nslots;
79 if (ef_check(type) < 0)
81 if (CANT_HAPPEN(how & EFF_IMMUTABLE))
82 how &= ~EFF_IMMUTABLE;
86 if (CANT_HAPPEN(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 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);
116 if (ep->flags & EFF_STATIC) {
117 /* ep->cache already points to space for ep->csize elements */
119 if (ep->fids > ep->csize) {
120 logerror("Can't open %s (file larger than %d records)",
121 ep->file, ep->csize);
127 if (CANT_HAPPEN(ep->cache))
132 nslots = blksize(fd) / ep->size;
133 if (!ef_realloc_cache(ep, nslots)) {
134 logerror("Can't map %s (%s)", ep->file, strerror(errno));
141 ep->flags = (ep->flags & EFF_IMMUTABLE) | (how & ~EFF_CREATE);
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 ep->flags &= EFF_IMMUTABLE; /* maintain invariant */
154 if (ep->onresize && ep->onresize(type) < 0)
160 open_locked(char *name, int oflags, mode_t mode)
162 int rdlonly = (oflags & O_ACCMODE) == O_RDONLY;
166 fd = _sopen(name, oflags | O_BINARY, rdlonly ? SH_DENYNO : SH_DENYWR,
173 fd = open(name, oflags, mode);
177 lock.l_type = rdlonly ? F_RDLCK : F_WRLCK;
178 lock.l_whence = SEEK_SET;
179 lock.l_start = lock.l_len = 0;
180 if (fcntl(fd, F_SETLK, &lock) == -1) {
189 * Reallocate cache for table EP to hold COUNT slots.
190 * The table must not be allocated statically.
191 * The cache may still be unmapped.
192 * If reallocation succeeds, any pointers obtained from ef_ptr()
194 * If it fails, the cache is unchanged, and errno is set.
195 * Return non-zero on success, zero on failure.
198 ef_realloc_cache(struct empfile *ep, int count)
202 if (CANT_HAPPEN(ep->flags & EFF_STATIC))
204 if (CANT_HAPPEN(count < 0))
208 * Avoid zero slots, because that can lead to null cache, which
209 * would be interpreted as unmapped cache.
213 cache = realloc(ep->cache, count * ep->size);
223 * Open the table TYPE as view of table BASE.
224 * Return non-zero on success, zero on failure.
225 * Beware: views work only as long as BASE doesn't change size!
226 * You must call ef_close(TYPE) before closing BASE.
229 ef_open_view(int type, int base)
233 if (CANT_HAPPEN(!EF_IS_VIEW(type)))
236 if (CANT_HAPPEN(!(ef_flags(base) & EFF_MEM)))
239 ep->cache = empfile[base].cache;
240 ep->csize = empfile[base].csize;
241 ep->flags |= EFF_MEM;
242 ep->baseid = empfile[base].baseid;
243 ep->cids = empfile[base].cids;
244 ep->fids = empfile[base].fids;
249 * Close the open table TYPE (EF_SECTOR, ...).
250 * Return non-zero on success, zero on failure.
258 if (ef_check(type) < 0)
262 if (EF_IS_VIEW(type))
267 ep->flags &= EFF_IMMUTABLE;
268 if (!(ep->flags & EFF_STATIC)) {
272 if (close(ep->fd) < 0) {
273 logerror("Error closing %s (%s)", ep->file, strerror(errno));
278 ep->baseid = ep->cids = ep->fids = 0;
279 if (ep->onresize && ep->onresize(type) < 0)
285 * Flush file-backed table TYPE (EF_SECTOR, ...) to its backing file.
286 * Do nothing if the table is privately mapped.
287 * Update timestamps of written elements if table is EFF_TYPED.
288 * Return non-zero on success, zero on failure.
295 if (ef_check(type) < 0)
298 if (ep->flags & EFF_PRIVATE)
299 return 1; /* nothing to do */
300 if (CANT_HAPPEN(ep->fd < 0))
303 * We don't know which cache entries are dirty. ef_write() writes
304 * through, but direct updates through ef_ptr() don't. They are
305 * allowed only with EFF_MEM. Assume the whole cash is dirty
308 if (ep->flags & EFF_MEM) {
309 if (do_write(ep, ep->cache, ep->baseid, ep->cids) < 0)
317 * Return pointer to element ID in table TYPE if it exists, else NULL.
318 * The table must be fully cached, i.e. flags & EFF_MEM.
319 * The caller is responsible for flushing changes he makes.
322 ef_ptr(int type, int id)
326 if (ef_check(type) < 0)
329 if (CANT_HAPPEN(!(ep->flags & EFF_MEM) || !ep->cache))
331 if (id < 0 || id >= ep->fids)
333 return ep->cache + ep->size * id;
337 * Read element ID from table TYPE into buffer INTO.
338 * FIXME pass buffer size!
339 * INTO is marked fresh with ef_mark_fresh().
340 * Return non-zero on success, zero on failure.
343 ef_read(int type, int id, void *into)
348 if (ef_check(type) < 0)
351 if (CANT_HAPPEN(!ep->cache))
353 if (id < 0 || id >= ep->fids)
356 if (ep->flags & EFF_MEM) {
357 cachep = ep->cache + id * ep->size;
359 if (ep->baseid + ep->cids <= id || ep->baseid > id) {
360 if (fillcache(ep, id) < 1)
363 cachep = ep->cache + (id - ep->baseid) * ep->size;
365 memcpy(into, cachep, ep->size);
366 ef_mark_fresh(type, into);
369 ep->postread(id, into);
374 * Fill cache of file-backed EP with elements starting at ID.
375 * If any were read, return their number.
376 * Else return -1 and leave the cache unchanged.
379 fillcache(struct empfile *ep, int id)
383 if (CANT_HAPPEN(!ep->cache))
386 ret = do_read(ep, ep->cache, id, MIN(ep->csize, ep->fids - id));
396 do_read(struct empfile *ep, void *buf, int id, int count)
401 if (CANT_HAPPEN(ep->fd < 0 || id < 0 || count < 0))
404 if (lseek(ep->fd, id * ep->size, SEEK_SET) == (off_t)-1) {
405 logerror("Error seeking %s to elt %d (%s)",
406 ep->file, id, strerror(errno));
411 n = count * ep->size;
413 ret = read(ep->fd, p, n);
415 if (errno != EINTR) {
416 logerror("Error reading %s elt %d (%s)",
418 id + (int)((p - (char *)buf) / ep->size),
422 } else if (ret == 0) {
423 logerror("Unexpected EOF reading %s elt %d",
424 ep->file, id + (int)((p - (char *)buf) / ep->size));
432 return (p - (char *)buf) / ep->size;
436 * Write COUNT elements starting at ID from BUF to file-backed EP.
437 * Update the timestamp if the table is EFF_TYPED.
438 * Don't actually write if table is privately mapped.
439 * Return 0 on success, -1 on error (file may be corrupt then).
442 do_write(struct empfile *ep, void *buf, int id, int count)
446 struct emptypedstr *elt;
449 if (CANT_HAPPEN(ep->fd < 0 || id < 0 || count < 0))
452 if (ep->flags & EFF_TYPED) {
453 now = ep->flags & EFF_NOTIME ? (time_t)-1 : time(NULL);
454 for (i = 0; i < count; i++) {
456 * TODO Oopses here could be due to bad data corruption.
457 * Fail instead of attempting to recover?
459 elt = (struct emptypedstr *)((char *)buf + i * ep->size);
460 if (CANT_HAPPEN(elt->ef_type != ep->uid))
461 elt->ef_type = ep->uid;
462 if (CANT_HAPPEN(elt->uid != id + i))
464 if (now != (time_t)-1)
465 elt->timestamp = now;
469 if (ep->flags & EFF_PRIVATE)
472 if (lseek(ep->fd, id * ep->size, SEEK_SET) == (off_t)-1) {
473 logerror("Error seeking %s to elt %d (%s)",
474 ep->file, id, strerror(errno));
479 n = count * ep->size;
481 ret = write(ep->fd, p, n);
483 if (errno != EINTR) {
484 logerror("Error writing %s elt %d (%s)",
486 id + (int)((p - (char *)buf) / ep->size),
500 * Write element ID into table TYPE from buffer FROM.
501 * FIXME pass buffer size!
502 * Update timestamp in FROM if table is EFF_TYPED.
503 * If table is file-backed and not privately mapped, write through
504 * cache straight to disk.
505 * Cannot write beyond the end of fully cached table (flags & EFF_MEM).
506 * Can write at the end of partially cached table.
507 * FROM must be fresh; see ef_make_stale().
508 * Return non-zero on success, zero on failure.
511 ef_write(int type, int id, void *from)
516 if (ef_check(type) < 0)
519 if (CANT_HAPPEN((ep->flags & (EFF_MEM | EFF_PRIVATE)) == EFF_PRIVATE))
521 if (CANT_HAPPEN((ep->flags & EFF_MEM) ? id >= ep->fids : id > ep->fids))
522 return 0; /* not implemented */
524 if (id >= ep->fids) {
525 /* write beyond end of file extends it, take note */
527 if (ep->onresize && ep->onresize(type) < 0)
530 if (id >= ep->baseid && id < ep->baseid + ep->cids) {
531 cachep = ep->cache + (id - ep->baseid) * ep->size;
533 must_be_fresh(ep, from);
537 ep->prewrite(id, cachep, from);
539 if (do_write(ep, from, id, 1) < 0)
542 if (cachep && cachep != from) /* update the cache if necessary */
543 memcpy(cachep, from, ep->size);
549 * BUF is an element of table TYPE.
550 * ID is its new element ID.
551 * If table is EFF_TYPED, change id and sequence number stored in BUF.
555 ef_set_uid(int type, void *buf, int uid)
557 struct emptypedstr *elt;
560 if (ef_check(type) < 0)
563 if (!(ep->flags & EFF_TYPED))
569 elt->seqno = get_seqno(ep, uid);
573 * Return sequence number of element ID in table EP.
574 * Return zero if table is not EFF_TYPED (it has no sequence number
578 get_seqno(struct empfile *ep, int id)
580 struct emptypedstr *elt;
582 if (!(ep->flags & EFF_TYPED))
584 if (id < 0 || id >= ep->fids)
586 if (id >= ep->baseid && id < ep->baseid + ep->cids)
587 elt = (void *)(ep->cache + (id - ep->baseid) * ep->size);
589 /* need a buffer, steal last cache slot */
590 if (ep->cids == ep->csize)
592 elt = (void *)(ep->cache + ep->cids * ep->size);
593 if (do_read(ep, elt, id, 1) < 0)
594 return 0; /* deep trouble */
600 * Increment sequence number in BUF, which is about to be written to EP.
601 * Do nothing if table is not EFF_TYPED (it has no sequence number
603 * Else, BUF's sequence number must match the one in EP's cache. If
604 * it doesn't, we're about to clobber a previous write.
607 new_seqno(struct empfile *ep, void *buf)
609 struct emptypedstr *elt = buf;
612 if (!(ep->flags & EFF_TYPED))
614 old_seqno = get_seqno(ep, elt->uid);
615 CANT_HAPPEN(old_seqno != elt->seqno);
616 elt->seqno = old_seqno + 1;
620 * Make all copies stale.
621 * Only fresh copies may be written back to the cache.
622 * To be called by functions that may yield the processor.
623 * Writing an copy when there has been a yield since it was read is
624 * unsafe, because we could clobber another thread's write then.
625 * Robust code must assume the that any function that may yield does
626 * yield. Marking copies stale there lets us catch unsafe writes.
634 /* Mark copy of an element of table TYPE in BUF fresh. */
636 ef_mark_fresh(int type, void *buf)
640 if (ef_check(type) < 0)
643 if (!(ep->flags & EFF_TYPED))
645 ((struct emptypedstr *)buf)->generation = ef_generation;
649 must_be_fresh(struct empfile *ep, void *buf)
651 struct emptypedstr *elt = buf;
653 if (!(ep->flags & EFF_TYPED))
655 CANT_HAPPEN(elt->generation != (ef_generation & 0xfff));
659 * Extend table TYPE by COUNT elements.
660 * Any pointers obtained from ef_ptr() become invalid.
661 * Return non-zero on success, zero on failure.
664 ef_extend(int type, int count)
668 int need_sentinel, i, id;
670 if (ef_check(type) < 0 || CANT_HAPPEN(EF_IS_VIEW(type)))
673 if (CANT_HAPPEN(count < 0))
677 if (ep->flags & EFF_MEM) {
678 need_sentinel = (ep->flags & EFF_SENTINEL) != 0;
679 if (id + count + need_sentinel > ep->csize) {
680 if (ep->flags & EFF_STATIC) {
681 logerror("Can't extend %s beyond %d elements",
682 ep->name, ep->csize - need_sentinel);
685 if (!ef_realloc_cache(ep, id + count + need_sentinel)) {
686 logerror("Can't extend %s to %d elements (%s)",
687 ep->name, id + count, strerror(errno));
691 p = ep->cache + id * ep->size;
692 do_blank(ep, p, id, count);
694 if (do_write(ep, p, id, count) < 0)
698 memset(ep->cache + (id + count) * ep->size, 0, ep->size);
699 ep->cids = id + count;
701 /* need a buffer, steal last cache slot */
702 if (ep->cids == ep->csize)
704 p = ep->cache + ep->cids * ep->size;
705 for (i = 0; i < count; i++) {
706 do_blank(ep, p, id + i, 1);
707 if (do_write(ep, p, id + i, 1) < 0)
711 ep->fids = id + count;
712 if (ep->onresize && ep->onresize(type) < 0)
718 * Initialize element ID for table TYPE in BUF.
719 * FIXME pass buffer size!
720 * BUF is marked fresh with ef_mark_fresh().
723 ef_blank(int type, int id, void *buf)
726 struct emptypedstr *elt;
728 if (ef_check(type) < 0)
731 do_blank(ep, buf, id, 1);
732 if (ep->flags & EFF_TYPED) {
734 elt->seqno = get_seqno(ep, elt->uid);
736 ef_mark_fresh(type, buf);
740 * Initialize COUNT elements of EP in BUF, starting with element ID.
743 do_blank(struct empfile *ep, void *buf, int id, int count)
746 struct emptypedstr *elt;
748 memset(buf, 0, count * ep->size);
749 for (i = 0; i < count; i++) {
750 elt = (struct emptypedstr *)((char *)buf + i * ep->size);
751 if (ep->flags & EFF_TYPED) {
752 elt->ef_type = ep->uid;
761 * Truncate table TYPE to COUNT elements.
762 * Any pointers obtained from ef_ptr() become invalid.
763 * Return non-zero on success, zero on failure.
766 ef_truncate(int type, int count)
771 if (ef_check(type) < 0 || CANT_HAPPEN(EF_IS_VIEW(type)))
774 if (CANT_HAPPEN(count < 0 || count > ep->fids))
777 if (ep->fd >= 0 && !(ep->flags & EFF_PRIVATE)) {
778 if (ftruncate(ep->fd, count * ep->size) < 0) {
779 logerror("Can't truncate %s to %d elements (%s)",
780 ep->file, count, strerror(errno));
786 if (ep->flags & EFF_MEM) {
787 need_sentinel = (ep->flags & EFF_SENTINEL) != 0;
788 if (!(ep->flags & EFF_STATIC)) {
789 if (!ef_realloc_cache(ep, count + need_sentinel)) {
790 logerror("Can't shrink %s cache after truncate (%s)",
791 ep->name, strerror(errno));
792 /* continue with unshrunk cache */
796 memset(ep->cache + count * ep->size, 0, ep->size);
799 if (ep->baseid >= count)
801 else if (ep->cids > count - ep->baseid)
802 ep->cids = count - ep->baseid;
805 if (ep->onresize && ep->onresize(type) < 0)
813 if (ef_check(type) < 0)
815 return empfile[type].cadef;
821 if (ef_check(type) < 0)
823 return empfile[type].fids;
829 if (ef_check(type) < 0)
831 return empfile[type].flags;
837 if (ef_check(type) < 0)
839 if (empfile[type].fd <= 0)
841 return fdate(empfile[type].fd);
845 * Search for a table matching NAME, return its table type.
846 * Return M_NOTFOUND if there are no matches, M_NOTUNIQUE if there are
850 ef_byname(char *name)
852 return stmtch(name, empfile, offsetof(struct empfile, name),
857 * Search CHOICES[] for a table type matching NAME, return it.
858 * Return M_NOTFOUND if there are no matches, M_NOTUNIQUE if there are
860 * CHOICES[] must be terminated with a negative value.
863 ef_byname_from(char *name, int choices[])
869 for (p = choices; *p >= 0; p++) {
870 if (ef_check(*p) < 0)
872 switch (mineq(name, empfile[*p].name)) {
890 if (ef_check(type) < 0)
891 return "bad ef_type";
892 return empfile[type].name;
898 if (CANT_HAPPEN((unsigned)type >= EF_MAX))
904 * Ensure table contains element ID.
905 * If necessary, extend it in steps of COUNT elements.
906 * Return non-zero on success, zero on failure.
909 ef_ensure_space(int type, int id, int count)
911 if (ef_check(type) < 0)
915 while (id >= empfile[type].fids) {
916 if (!ef_extend(type, count))