aboutsummaryrefslogtreecommitdiffstats
path: root/libfat/cache.c
blob: 6310a7de3bc7f67e14f58d2efe6997a85251dd34 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/* ----------------------------------------------------------------------- *
 *
 *   Copyright 2004 H. Peter Anvin - All Rights Reserved
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, Inc., 53 Temple Place Ste 330,
 *   Boston MA 02111-1307, USA; either version 2 of the License, or
 *   (at your option) any later version; incorporated herein by reference.
 *
 * ----------------------------------------------------------------------- */

/*
 * cache.c
 *
 * Simple sector cache
 */

#include <stdlib.h>
#include "libfatint.h"

void * libfat_get_sector(struct libfat_filesystem *fs, libfat_sector_t n)
{
  struct libfat_sector *ls;

  for ( ls = fs->sectors ; ls ; ls = ls->next ) {
    if ( ls->n == n )
      return ls->data;		/* Found in cache */
  }

  /* Not found in cache */
  ls = malloc(sizeof(struct libfat_sector));
  if ( !ls ) {
    libfat_flush(fs);
    ls = malloc(sizeof(struct libfat_sector));

    if ( !ls )
      return NULL;		/* Can't allocate memory */
  }

  if ( fs->read(fs->readptr, ls->data, LIBFAT_SECTOR_SIZE, n)
       != LIBFAT_SECTOR_SIZE ) {
    free(ls);
    return NULL;		/* I/O error */
  }

  ls->n = n;
  ls->next = fs->sectors;
  fs->sectors = ls;

  return ls->data;
}

void libfat_flush(struct libfat_filesystem *fs)
{
  struct libfat_sector *ls, *lsnext;

  lsnext = fs->sectors;
  fs->sectors = NULL;

  for ( ls = lsnext ; ls ; ls = lsnext ) {
    lsnext = ls->next;
    free(ls);
  }
}