Exemple #1
0
/* fetch data from target, from given offset */
int cache_fetch_data(Cache *cache, unsigned int offset) {
  int i, nb=-1;
  unsigned int min;


  mylog("cache_fetch_data(%p, %u)\n", cache, offset);
  /* search for a free chunk */
  for(i=0; i<cache_chunks; i++) {
    if (cache->chunks[i] == NULL) {
      nb = i;
      break;
    }
  }
  
  mylog("cache_fetch: found empty chunk slot %d\n", nb);
  
  if (nb < 0) {
    /* none free? use the smallest offset (assume seq. read - should use older) */
    min = cache->chunks[0]->off_start;
    nb = 0;
    for(i=1; i<cache_chunks; i++) {
      if (cache->chunks[i]->off_start < min) {
	min = cache->chunks[i]->off_start;
	nb = i;
      }
    }
  } else {
    /* allocate the chunk */
    cache->chunks[nb] = malloc(sizeof(Chunk));
    if (cache->chunks[nb] == NULL) {
      return(0);
    }
    cache->chunks[nb]->off_start = 0;
    cache->chunks[nb]->off_end = 0;
    cache->chunks[nb]->data = malloc(cache_chunksize);
    if (cache->chunks[nb]->data == NULL) {
      free(cache->chunks[nb]);
      cache->chunks[nb] = NULL;
      return(0);
    }
    
  mylog("cache_fetch: chunk %d allocated (size=%d) [%p-%p[\n", nb, cache_chunksize,
          cache->chunks[nb]->data, cache->chunks[nb]->data+cache_chunksize);
  }
  
  /* set new values */
  cache->chunks[nb]->off_start = offset;
  mylog("cache_fetch: put start=%u\n", offset);
  if (offset+cache_chunksize > cache->size) {
    /* after end of file. reduce */
    cache->chunks[nb]->off_end = cache->size - 1;
  } else {
    cache->chunks[nb]->off_end = offset + cache_chunksize - 1;
  }
  mylog("cache_fetch: put end=%u\n", cache->chunks[nb]->off_end);
  
  /* perform read */
  mylog("cache_fetch: performing do_read (%p, %d)\n", cache, nb);
  if (!cache_do_read(cache, nb)) {
    /* argl. this chunk is no more valid. destroy it */
    cache_chunk_free(cache->chunks[nb]);
    cache->chunks[nb] = NULL;
    return(0);
  }
  
  return(1);
}
errno_t cache_get( cache_t *c, long blk, void *data )
{
    return cache_do_read( c, blk, data );
}