source: trunk/libtransmission/cache.c @ 10924

Last change on this file since 10924 was 10924, checked in by charles, 12 years ago

(trunk libT) #1521 "memory cache to reduce disk IO" -- improved revision from sadface

File size: 10.7 KB
Line 
1/*
2 * This file Copyright (C) 2010 Mnemosyne LLC
3 *
4 * This file is licensed by the GPL version 2.  Works owned by the
5 * Transmission project are granted a special exemption to clause 2(b)
6 * so that the bulk of its code can remain under the MIT license.
7 * This exemption does not extend to derived works not owned by
8 * the Transmission project.
9 *
10 * $Id$
11 */
12
13#include "transmission.h"
14#include "cache.h"
15#include "inout.h"
16#include "peer-common.h" /* MAX_BLOCK_SIZE */
17#include "ptrarray.h"
18#include "torrent.h"
19#include "utils.h"
20
21#define MY_NAME "Cache"
22
23#define dbgmsg( ... ) \
24    do { \
25        if( tr_deepLoggingIsActive( ) ) \
26            tr_deepLog( __FILE__, __LINE__, MY_NAME, __VA_ARGS__ ); \
27    } while( 0 )
28
29
30/****
31*****
32****/
33
34struct cache_block
35{
36    tr_torrent * tor;
37
38    tr_piece_index_t piece;
39    uint32_t offset;
40    uint32_t length;
41
42    time_t time;
43    tr_block_index_t block;
44
45    uint8_t * buf;
46};
47
48struct tr_cache
49{
50    tr_ptrArray blocks;
51    int maxBlocks;
52    size_t maxMiB;
53
54    size_t disk_writes;
55    size_t disk_write_bytes;
56    size_t cache_writes;
57    size_t cache_write_bytes;
58};
59
60/****
61*****
62****/
63
64struct run_info
65{
66  time_t  last_block_time;
67  tr_bool is_aligned;
68};
69
70
71/* return a count of how many contiguous blocks there are starting at this pos */
72static int
73getBlockRun( const tr_cache * cache, int pos, struct run_info * info )
74{
75    int i;
76    const int n = tr_ptrArraySize( &cache->blocks );
77    const struct cache_block ** blocks = (const struct cache_block**) tr_ptrArrayBase( &cache->blocks );
78    const struct cache_block * ref = blocks[pos];
79    tr_block_index_t block = ref->block;
80
81    for( i=pos; i<n; ++i, ++block ) {
82        const struct cache_block * b = blocks[i];
83        if( b->block != block ) break;
84        if( b->tor != ref->tor ) break;
85//fprintf( stderr, "pos %d tor %d block %zu time %zu\n", i, b->tor->uniqueId, (size_t)b->block, (size_t)b->time );
86    }
87
88//fprintf( stderr, "run is %d long from [%d to %d)\n", (int)(i-pos), i, (int)pos );
89    if( info != NULL ) {
90        info->last_block_time = blocks[i-1]->time;
91        info->is_aligned = (blocks[pos]->block % 2 == 0) ? TRUE : FALSE;
92    }
93
94    return i-pos;
95}
96
97/* return the starting index of the longest contiguous run of blocks BUT:
98 *   - Run should begin with a even block and length of run should be even.
99 *   - Oldest run is preferred.
100 */
101static int
102findChunk2Discard( tr_cache * cache, int * setme_n )
103{
104    const int n = tr_ptrArraySize( &cache->blocks );
105    int pos;
106    int bestpos = 0;
107    unsigned bestlen = 1;
108    unsigned jump;
109    time_t oldest_time = tr_time() + 1;
110    struct run_info run;
111
112    for( pos=0; pos<n; pos+=jump )
113    {
114        unsigned len = getBlockRun( cache, pos, &run );
115        jump = len;
116
117        /* shortcut */
118        if( len < bestlen )
119            continue;
120
121        /* check alignment */
122        if( len % 2 == 0 ) {
123            if( !run.is_aligned ) {
124                /* Let it grow. Otherwise we contribute to fragmentation */
125                if( bestlen == 1) {
126                    /* But if all other blocks are non-contiguous, we prefer this one */
127                    bestpos = pos;
128                    oldest_time = cache->maxBlocks - len;
129                }
130                continue;
131            }
132        } else {
133            if( len != 1 ) {
134                --len;
135                if( !run.is_aligned ) {
136                    ++pos;
137                    --jump;
138                }
139            }
140        }
141
142        if( bestlen < len ) {
143            bestlen = len;
144            bestpos = pos;
145            oldest_time = run.last_block_time;
146        } else if( (bestlen == len) && (oldest_time > run.last_block_time) ) {
147            bestpos = pos;
148            oldest_time = run.last_block_time;
149        }
150    }
151
152//fprintf( stderr, "DISCARDED run is %d long from [%d to %d)\n", bestlen, bestpos, bestpos+bestlen );
153    *setme_n = bestlen;
154    return bestpos;
155}
156
157static int
158flushContiguous( tr_cache * cache, int pos, int n )
159{
160    int i;
161    int err = 0;
162    uint8_t * buf = tr_new( uint8_t, n * MAX_BLOCK_SIZE );
163    uint8_t * walk = buf;
164    struct cache_block ** blocks = (struct cache_block**) tr_ptrArrayBase( &cache->blocks );
165
166    struct cache_block * b = blocks[pos];
167    tr_torrent * tor             = b->tor;
168    const tr_piece_index_t piece = b->piece;
169    const uint32_t offset        = b->offset;
170
171//fprintf( stderr, "flushing %d contiguous blocks [%d-%d) from cache to disk\n", n, pos, n+pos );
172
173    for( i=pos; i<pos+n; ++i ) {
174        b = blocks[i];
175        memcpy( walk, b->buf, b->length );
176        walk += b->length;
177        tr_free( b->buf );
178        tr_free( b );
179    }
180    tr_ptrArrayErase( &cache->blocks, pos, pos+n );
181
182    tr_tordbg( tor, "Writing to disk piece %d, offset %d, len %d", (int)piece, (int)offset, (int)(walk-buf) );
183    tr_ndbg( MY_NAME, "Removing %d blocks from cache; %d left", n, tr_ptrArraySize(&cache->blocks) );
184    //fprintf( stderr, "%s - Writing to disk piece %d, offset %d, len %d\n", tr_torrentName(tor), (int)piece, (int)offset, (int)(walk-buf) );
185    //fprintf( stderr, "%s - Removing %d blocks from cache; %d left\n", MY_NAME, n, tr_ptrArraySize(&cache->blocks) );
186
187    err = tr_ioWrite( tor, piece, offset, walk-buf, buf );
188    tr_free( buf );
189
190    ++cache->disk_writes;
191    cache->disk_write_bytes += walk-buf;
192    return err;
193}
194
195static int
196cacheTrim( tr_cache * cache )
197{
198    int err = 0;
199
200    while( !err && ( tr_ptrArraySize( &cache->blocks ) > cache->maxBlocks ) )
201    {
202        int n;
203        const int i = findChunk2Discard( cache, &n );
204        err = flushContiguous( cache, i, n );
205    }
206
207    return err;
208}
209
210/***
211****
212***/
213
214static int
215getMaxBlocks( double maxMiB )
216{
217    const double maxBytes = maxMiB * (1024 * 1024);
218    return maxBytes / MAX_BLOCK_SIZE;
219}
220
221int
222tr_cacheSetLimit( tr_cache * cache, double maxMiB )
223{
224    cache->maxMiB = maxMiB;
225    cache->maxBlocks = getMaxBlocks( maxMiB );
226    tr_ndbg( MY_NAME, "Maximum cache size set to %.2f MiB (%d blocks)", maxMiB, cache->maxBlocks );
227    return cacheTrim( cache );
228}
229
230double
231tr_cacheGetLimit( const tr_cache * cache )
232{
233    return cache->maxMiB;
234}
235
236tr_cache *
237tr_cacheNew( double maxMiB )
238{
239    tr_cache * cache = tr_new0( tr_cache, 1 );
240    cache->blocks = TR_PTR_ARRAY_INIT;
241    cache->maxBlocks = getMaxBlocks( maxMiB );
242    return cache;
243}
244
245void
246tr_cacheFree( tr_cache * cache )
247{
248    assert( tr_ptrArrayEmpty( &cache->blocks ) );
249    tr_ptrArrayDestruct( &cache->blocks, NULL );
250    tr_free( cache );
251}
252
253/***
254****
255***/
256
257static int
258cache_block_compare( const void * va, const void * vb )
259{
260    const struct cache_block * a = va;
261    const struct cache_block * b = vb;
262
263    /* primary key: torrent id */
264    if( a->tor->uniqueId != b->tor->uniqueId )
265        return a->tor->uniqueId < b->tor->uniqueId ? -1 : 1;
266
267    /* secondary key: block # */
268    if( a->block != b->block )
269        return a->block < b->block ? -1 : 1;
270
271    /* they're equal */
272    return 0;
273}
274
275static struct cache_block *
276findBlock( tr_cache           * cache,
277           tr_torrent         * torrent, 
278           tr_piece_index_t     piece,
279           uint32_t             offset )
280{
281    struct cache_block key;
282    key.tor = torrent;
283    key.block = _tr_block( torrent, piece, offset );
284    return tr_ptrArrayFindSorted( &cache->blocks, &key, cache_block_compare );
285}
286
287int
288tr_cacheWriteBlock( tr_cache         * cache,
289                    tr_torrent       * torrent,
290                    tr_piece_index_t   piece,
291                    uint32_t           offset,
292                    uint32_t           length,
293                    const uint8_t    * writeme )
294{
295    struct cache_block * cb = findBlock( cache, torrent, piece, offset );
296
297    if( cb == NULL )
298    {
299        cb = tr_new( struct cache_block, 1 );
300        cb->tor = torrent;
301        cb->piece = piece;
302        cb->offset = offset;
303        cb->length = length;
304        cb->block = _tr_block( torrent, piece, offset );
305        cb->buf = NULL;
306        tr_ptrArrayInsertSorted( &cache->blocks, cb, cache_block_compare );
307    }
308
309    cb->time = tr_time();
310
311    tr_free( cb->buf );
312    cb->buf = tr_memdup( writeme, cb->length );
313
314    ++cache->cache_writes;
315    cache->cache_write_bytes += cb->length;
316
317    return cacheTrim( cache );
318}
319
320int
321tr_cacheReadBlock( tr_cache         * cache,
322                   tr_torrent       * torrent,
323                   tr_piece_index_t   piece,
324                   uint32_t           offset,
325                   uint32_t           len,
326                   uint8_t          * setme )
327{
328    int err = 0;
329    struct cache_block * cb = findBlock( cache, torrent, piece, offset );
330
331    if( cb )
332        memcpy( setme, cb->buf, len );
333    else
334        err = tr_ioRead( torrent, piece, offset, len, setme );
335
336    return err;
337}
338
339int
340tr_cachePrefetchBlock( tr_cache         * cache,
341                       tr_torrent       * torrent,
342                       tr_piece_index_t   piece,
343                       uint32_t           offset,
344                       uint32_t           len )
345{
346    int err = 0;
347    struct cache_block * cb = findBlock( cache, torrent, piece, offset );
348
349    if( cb == NULL )
350        err = tr_ioPrefetch( torrent, piece, offset, len );
351
352    return err;
353}
354
355/***
356****
357***/
358
359static int
360findPiece( tr_cache * cache, tr_torrent * torrent, tr_piece_index_t piece )
361{
362    struct cache_block key;
363    key.tor = torrent;
364    key.block = tr_torPieceFirstBlock( torrent, piece );
365    return tr_ptrArrayLowerBound( &cache->blocks, &key, cache_block_compare, NULL );
366}
367
368int
369tr_cacheFlushFile( tr_cache * cache, tr_torrent * torrent, tr_file_index_t i )
370{
371    int err = 0;
372    const tr_file * file = &torrent->info.files[i];
373    const tr_block_index_t begin = tr_torPieceFirstBlock( torrent, file->firstPiece );
374    const tr_block_index_t end  = tr_torPieceFirstBlock( torrent, file->lastPiece ) + tr_torPieceCountBlocks( torrent, file->lastPiece );
375    const int pos = findPiece( cache, torrent, file->firstPiece );
376    dbgmsg( "flushing file %d from cache to disk: blocks [%zu...%zu)", (int)i, (size_t)begin, (size_t)end );
377
378    /* flush out all the blocks in that file */
379    while( !err && ( pos < tr_ptrArraySize( &cache->blocks ) ) )
380    {
381        const struct cache_block * b = tr_ptrArrayNth( &cache->blocks, pos );
382        if( b->tor != torrent ) break;
383        if( ( b->block < begin ) || ( b->block >= end ) ) break;
384        err = flushContiguous( cache, pos, getBlockRun( cache, pos, NULL ) );
385    }
386
387    return err;
388}
389
390int
391tr_cacheFlushTorrent( tr_cache * cache, tr_torrent * torrent )
392{
393    int err = 0;
394    const int pos = findPiece( cache, torrent, 0 );
395
396    /* flush out all the blocks in that torrent */
397    while( !err && ( pos < tr_ptrArraySize( &cache->blocks ) ) )
398    {
399        const struct cache_block * b = tr_ptrArrayNth( &cache->blocks, pos );
400        if( b->tor != torrent ) break;
401        err = flushContiguous( cache, pos, getBlockRun( cache, pos, NULL ) );
402    }
403
404    return err;
405}
Note: See TracBrowser for help on using the repository browser.