2 * Empire - A multi-player, client/server Internet based war game.
3 * Copyright (C) 1986-2008, Dave Pare, Jeff Bailey, Thomas Ruschak,
4 * Ken Stevens, Steve McClure
6 * This program 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 2 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, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 * See files README, COPYING and CREDITS in the root of the source
23 * tree for related information and legal notices. It is expected
24 * that future projects/authors will amend these files as needed.
28 * file.c: Operations on Empire tables (`files' for historical reasons)
30 * Known contributors to this file:
33 * Markus Armbruster, 2005-2008
41 #include <sys/types.h>
47 #include "prototypes.h"
49 static int ef_realloc_cache(struct empfile *, int);
50 static int fillcache(struct empfile *, int);
51 static int do_write(struct empfile *, void *, int, int, time_t);
52 static void do_blank(struct empfile *, void *, int, int);
55 * Open the file-backed table TYPE (EF_SECTOR, ...).
56 * HOW are flags to control operation. Naturally, immutable flags are
58 * If NELT is non-negative, the table must have that many elements.
59 * Return non-zero on success, zero on failure.
60 * You must call ef_close() before the next ef_open().
63 ef_open(int type, int how, int nelt)
67 int oflags, fd, fsiz, nslots;
69 if (ef_check(type) < 0)
71 if (CANT_HAPPEN(how & EFF_IMMUTABLE))
72 how &= ~EFF_IMMUTABLE;
76 if (CANT_HAPPEN(ep->fd >= 0))
79 if (how & EFF_PRIVATE)
82 oflags |= O_CREAT | O_TRUNC;
86 if ((fd = open(ep->file, oflags, S_IRWUG)) < 0) {
87 logerror("Can't open %s (%s)", ep->file, strerror(errno));
91 lock.l_type = how & EFF_PRIVATE ? F_RDLCK : F_WRLCK;
92 lock.l_whence = SEEK_SET;
93 lock.l_start = lock.l_len = 0;
94 if (fcntl(fd, F_SETLK, &lock) == -1) {
95 logerror("Can't lock %s (%s)", ep->file, strerror(errno));
102 if (fsiz % ep->size) {
103 logerror("Can't open %s (file size not a multiple of record size %d)",
108 ep->fids = fsiz / ep->size;
109 if (nelt >= 0 && nelt != ep->fids) {
110 logerror("Can't open %s (got %d records instead of %d)",
111 ep->file, ep->fids, nelt);
117 if (ep->flags & EFF_STATIC) {
118 /* ep->cache already points to space for ep->csize elements */
120 if (ep->fids > ep->csize) {
121 logerror("Can't open %s: file larger than %d bytes",
122 ep->file, ep->fids * ep->size);
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));
142 ep->flags = (ep->flags & EFF_IMMUTABLE) | (how & ~EFF_CREATE);
145 /* map file into cache */
146 if ((how & EFF_MEM) && ep->fids) {
147 if (fillcache(ep, 0) != ep->fids) {
148 ep->cids = 0; /* prevent cache flush */
149 ep->flags &= EFF_IMMUTABLE; /* maintain invariant */
159 * Reallocate cache for table EP to hold COUNT slots.
160 * The table must not be allocated statically.
161 * The cache may still be unmapped.
162 * If reallocation succeeds, any pointers obtained from ef_ptr()
164 * If it fails, the cache is unchanged, and errno is set.
165 * Return non-zero on success, zero on failure.
168 ef_realloc_cache(struct empfile *ep, int count)
172 if (CANT_HAPPEN(ep->flags & EFF_STATIC))
174 if (CANT_HAPPEN(count < 0))
178 * Avoid zero slots, because that can lead to null cache, which
179 * would be interpreted as unmapped cache.
183 cache = realloc(ep->cache, count * ep->size);
193 * Close the file-backed table TYPE (EF_SECTOR, ...).
194 * Return non-zero on success, zero on failure.
202 retval = ef_flush(type);
204 ep->flags &= EFF_IMMUTABLE;
205 if (!(ep->flags & EFF_STATIC)) {
209 if (close(ep->fd) < 0) {
210 logerror("Error closing %s (%s)", ep->name, strerror(errno));
218 * Flush table TYPE (EF_SECTOR, ...) to disk.
219 * Do nothing if the table is privately mapped.
220 * Update timestamps of written elements if table is EFF_TYPED.
221 * Return non-zero on success, zero on failure.
228 if (ef_check(type) < 0)
231 if (ep->flags & EFF_PRIVATE)
232 return 1; /* nothing to do */
233 if (CANT_HAPPEN(ep->fd < 0))
236 * We don't know which cache entries are dirty. ef_write() writes
237 * through, but direct updates through ef_ptr() don't. They are
238 * allowed only with EFF_MEM. Assume the whole cash is dirty
241 if (ep->flags & EFF_MEM) {
242 if (do_write(ep, ep->cache, ep->baseid, ep->cids, time(NULL)) < 0)
250 * Return pointer to element ID in table TYPE if it exists, else NULL.
251 * The table must be fully cached, i.e. flags & EFF_MEM.
252 * The caller is responsible for flushing changes he makes.
255 ef_ptr(int type, int id)
259 if (ef_check(type) < 0)
262 if (CANT_HAPPEN(!(ep->flags & EFF_MEM) || !ep->cache))
264 if (id < 0 || id >= ep->fids)
266 return ep->cache + ep->size * id;
270 * Read element ID from table TYPE into buffer INTO.
271 * FIXME pass buffer size!
272 * Return non-zero on success, zero on failure.
275 ef_read(int type, int id, void *into)
280 if (ef_check(type) < 0)
283 if (CANT_HAPPEN(!ep->cache))
285 if (id < 0 || id >= ep->fids)
288 if (ep->flags & EFF_MEM) {
289 from = ep->cache + id * ep->size;
291 if (ep->baseid + ep->cids <= id || ep->baseid > id) {
292 if (fillcache(ep, id) < 1)
295 from = ep->cache + (id - ep->baseid) * ep->size;
297 memcpy(into, from, ep->size);
300 ep->postread(id, into);
305 * Fill cache of file-backed EP with elements starting at ID.
306 * If any were read, return their number.
307 * Else return -1 and leave the cache unchanged.
310 fillcache(struct empfile *ep, int id)
315 if (CANT_HAPPEN(ep->fd < 0 || !ep->cache))
318 if (lseek(ep->fd, id * ep->size, SEEK_SET) == (off_t)-1) {
319 logerror("Error seeking %s to elt %d (%s)",
320 ep->file, id, strerror(errno));
325 n = MIN(ep->csize, ep->fids - id) * ep->size;
327 ret = read(ep->fd, p, n);
329 if (errno != EINTR) {
330 logerror("Error reading %s elt %d (%s)",
332 id + (int)((p - ep->cache) / ep->size),
336 } else if (ret == 0) {
337 logerror("Unexpected EOF reading %s elt %d",
338 ep->file, id + (int)((p - ep->cache) / ep->size));
347 return -1; /* nothing read, old cache still ok */
350 ep->cids = (p - ep->cache) / ep->size;
355 * Write COUNT elements starting at ID from BUF to file-backed EP.
356 * Set the timestamp to NOW if the table is EFF_TYPED.
357 * Don't actually write if table is privately mapped.
358 * Return 0 on success, -1 on error (file may be corrupt then).
361 do_write(struct empfile *ep, void *buf, int id, int count, time_t now)
365 struct emptypedstr *elt;
367 if (CANT_HAPPEN(ep->fd < 0 || id < 0 || count < 0))
370 if (ep->flags & EFF_TYPED) {
371 for (i = 0; i < count; i++) {
373 * TODO Oopses here could be due to bad data corruption.
374 * Fail instead of attempting to recover?
376 elt = (struct emptypedstr *)((char *)buf + i * ep->size);
377 if (CANT_HAPPEN(elt->ef_type != ep->uid))
378 elt->ef_type = ep->uid;
379 if (CANT_HAPPEN(elt->uid != id + i))
381 elt->timestamp = now;
385 if (ep->flags & EFF_PRIVATE)
388 if (lseek(ep->fd, id * ep->size, SEEK_SET) == (off_t)-1) {
389 logerror("Error seeking %s to elt %d (%s)",
390 ep->file, id, strerror(errno));
395 n = count * ep->size;
397 ret = write(ep->fd, p, n);
399 if (errno != EINTR) {
400 logerror("Error writing %s elt %d (%s)",
402 id + (int)((p - (char *)buf) / ep->size),
416 * Write element ID into table TYPE from buffer FROM.
417 * FIXME pass buffer size!
418 * Update timestamp in FROM if table is EFF_TYPED.
419 * If table is file-backed and not privately mapped, write through
420 * cache straight to disk.
421 * Cannot write beyond the end of fully cached table (flags & EFF_MEM).
422 * Can write at the end of partially cached table.
423 * Return non-zero on success, zero on failure.
426 ef_write(int type, int id, void *from)
431 if (ef_check(type) < 0)
434 if (CANT_HAPPEN((ep->flags & (EFF_MEM | EFF_PRIVATE)) == EFF_PRIVATE))
437 ep->prewrite(id, from);
438 if (CANT_HAPPEN((ep->flags & EFF_MEM) ? id >= ep->fids : id > ep->fids))
439 return 0; /* not implemented */
441 if (do_write(ep, from, id, 1, time(NULL)) < 0)
444 if (id >= ep->baseid && id < ep->baseid + ep->cids) {
445 /* update the cache if necessary */
446 to = ep->cache + (id - ep->baseid) * ep->size;
448 memcpy(to, from, ep->size);
450 if (id >= ep->fids) {
451 /* write beyond end of file extends it, take note */
458 * Extend table TYPE by COUNT elements.
459 * Any pointers obtained from ef_ptr() become invalid.
460 * Return non-zero on success, zero on failure.
463 ef_extend(int type, int count)
468 time_t now = time(NULL);
470 if (ef_check(type) < 0)
473 if (CANT_HAPPEN(count < 0))
477 if (ep->flags & EFF_MEM) {
478 if (id + count > ep->csize) {
479 if (ep->flags & EFF_STATIC) {
480 logerror("Can't extend %s beyond %d elements",
481 ep->file, ep->csize);
484 if (!ef_realloc_cache(ep, id + count)) {
485 logerror("Can't extend %s to %d elements (%s)",
486 ep->file, id + count, strerror(errno));
490 p = ep->cache + id * ep->size;
491 do_blank(ep, p, id, count);
493 if (do_write(ep, p, id, count, now) < 0)
498 /* need a buffer, steal last cache slot */
499 if (ep->cids == ep->csize)
501 p = ep->cache + ep->cids * ep->size;
502 for (i = 0; i < count; i++) {
503 do_blank(ep, p, id + i, 1);
504 if (do_write(ep, p, id + i, 1, now) < 0)
513 * Initialize element ID for EP in BUF.
514 * FIXME pass buffer size!
517 ef_blank(int type, int id, void *buf)
519 if (ef_check(type) < 0)
521 do_blank(&empfile[type], buf, id, 1);
525 * Initialize COUNT elements of EP in BUF, starting with element ID.
528 do_blank(struct empfile *ep, void *buf, int id, int count)
531 struct emptypedstr *elt;
533 memset(buf, 0, count * ep->size);
534 if (ep->flags & EFF_TYPED) {
535 for (i = 0; i < count; i++) {
536 elt = (struct emptypedstr *)((char *)buf + i * ep->size);
537 elt->ef_type = ep->uid;
544 * Truncate table TYPE to COUNT elements.
545 * Any pointers obtained from ef_ptr() become invalid.
546 * Return non-zero on success, zero on failure.
549 ef_truncate(int type, int count)
553 if (ef_check(type) < 0)
556 if (CANT_HAPPEN(count < 0 || count > ep->fids))
559 if (ep->fd >= 0 && !(ep->flags & EFF_PRIVATE)) {
560 if (ftruncate(ep->fd, count * ep->size) < 0) {
561 logerror("Can't truncate %s to %d elements (%s)",
562 ep->file, count, strerror(errno));
568 if (ep->flags & EFF_MEM) {
569 if (!(ep->flags & EFF_STATIC)) {
570 if (!ef_realloc_cache(ep, count)) {
571 logerror("Can't shrink cache after truncate");
572 /* continue with unshrunk cache */
577 if (ep->baseid >= count)
579 else if (ep->cids > count - ep->baseid)
580 ep->cids = count - ep->baseid;
589 return empfile[type].cadef;
595 return empfile[type].fids;
601 return empfile[type].flags;
607 if (empfile[type].fd <= 0)
609 return fdate(empfile[type].fd);
613 * Search for a table matching NAME, return its table type.
614 * Return M_NOTFOUND if there are no matches, M_NOTUNIQUE if there are
618 ef_byname(char *name)
620 return stmtch(name, empfile, offsetof(struct empfile, name),
625 * Search CHOICES[] for a table type matching NAME, return it.
626 * Return M_NOTFOUND if there are no matches, M_NOTUNIQUE if there are
628 * CHOICES[] must be terminated with a negative value.
631 ef_byname_from(char *name, int choices[])
637 for (p = choices; *p >= 0; p++) {
638 if (ef_check(*p) < 0)
640 switch (mineq(name, empfile[*p].name)) {
658 if (ef_check(type) < 0)
659 return "bad ef_type";
660 return empfile[type].name;
666 if (CANT_HAPPEN((unsigned)type >= EF_MAX))
672 * Ensure file-backed table contains ID.
673 * If necessary, extend it in steps of COUNT elements.
674 * Return non-zero on success, zero on failure.
677 ef_ensure_space(int type, int id, int count)
679 if (ef_check(type) < 0)
683 while (id >= empfile[type].fids) {
684 if (!ef_extend(type, count))