[e16e8f2] | 1 | /* ----------------------------------------------------------------------- * |
---|
| 2 | * |
---|
| 3 | * Copyright 2004-2008 H. Peter Anvin - All Rights Reserved |
---|
| 4 | * |
---|
| 5 | * This program is free software; you can redistribute it and/or modify |
---|
| 6 | * it under the terms of the GNU General Public License as published by |
---|
| 7 | * the Free Software Foundation, Inc., 53 Temple Place Ste 330, |
---|
| 8 | * Boston MA 02111-1307, USA; either version 2 of the License, or |
---|
| 9 | * (at your option) any later version; incorporated herein by reference. |
---|
| 10 | * |
---|
| 11 | * ----------------------------------------------------------------------- */ |
---|
| 12 | |
---|
| 13 | /* |
---|
| 14 | * cache.c |
---|
| 15 | * |
---|
| 16 | * Simple sector cache |
---|
| 17 | */ |
---|
| 18 | |
---|
| 19 | #include <stdlib.h> |
---|
| 20 | #include "libfatint.h" |
---|
| 21 | |
---|
| 22 | void *libfat_get_sector(struct libfat_filesystem *fs, libfat_sector_t n) |
---|
| 23 | { |
---|
| 24 | struct libfat_sector *ls; |
---|
| 25 | |
---|
| 26 | for (ls = fs->sectors; ls; ls = ls->next) { |
---|
| 27 | if (ls->n == n) |
---|
| 28 | return ls->data; /* Found in cache */ |
---|
| 29 | } |
---|
| 30 | |
---|
| 31 | /* Not found in cache */ |
---|
| 32 | ls = malloc(sizeof(struct libfat_sector)); |
---|
| 33 | if (!ls) { |
---|
| 34 | libfat_flush(fs); |
---|
| 35 | ls = malloc(sizeof(struct libfat_sector)); |
---|
| 36 | |
---|
| 37 | if (!ls) |
---|
| 38 | return NULL; /* Can't allocate memory */ |
---|
| 39 | } |
---|
| 40 | |
---|
| 41 | if (fs->read(fs->readptr, ls->data, LIBFAT_SECTOR_SIZE, n) |
---|
| 42 | != LIBFAT_SECTOR_SIZE) { |
---|
| 43 | free(ls); |
---|
| 44 | return NULL; /* I/O error */ |
---|
| 45 | } |
---|
| 46 | |
---|
| 47 | ls->n = n; |
---|
| 48 | ls->next = fs->sectors; |
---|
| 49 | fs->sectors = ls; |
---|
| 50 | |
---|
| 51 | return ls->data; |
---|
| 52 | } |
---|
| 53 | |
---|
| 54 | void libfat_flush(struct libfat_filesystem *fs) |
---|
| 55 | { |
---|
| 56 | struct libfat_sector *ls, *lsnext; |
---|
| 57 | |
---|
| 58 | lsnext = fs->sectors; |
---|
| 59 | fs->sectors = NULL; |
---|
| 60 | |
---|
| 61 | for (ls = lsnext; ls; ls = lsnext) { |
---|
| 62 | lsnext = ls->next; |
---|
| 63 | free(ls); |
---|
| 64 | } |
---|
| 65 | } |
---|