source: trunk/libtransmission/cache.c @ 12171

Last change on this file since 12171 was 12171, checked in by jordan, 11 years ago

(trunk libT) minor tweak to the cache sorting code

  • Property svn:keywords set to Date Rev Author Id
File size: 12.1 KB
Line 
1/*
2 * This file Copyright (C) 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: cache.c 12171 2011-03-16 00:49:43Z jordan $
11 */
12
13#include <event2/buffer.h>
14
15#include "transmission.h"
16#include "cache.h"
17#include "inout.h"
18#include "peer-common.h" /* MAX_BLOCK_SIZE */
19#include "ptrarray.h"
20#include "torrent.h"
21#include "utils.h"
22
23#define MY_NAME "Cache"
24
25#define dbgmsg( ... ) \
26    do { \
27        if( tr_deepLoggingIsActive( ) ) \
28            tr_deepLog( __FILE__, __LINE__, MY_NAME, __VA_ARGS__ ); \
29    } while( 0 )
30
31
32/****
33*****
34****/
35
36struct cache_block
37{
38    tr_torrent * tor;
39
40    tr_piece_index_t piece;
41    uint32_t offset;
42    uint32_t length;
43
44    time_t time;
45    tr_block_index_t block;
46
47    struct evbuffer * evbuf;
48};
49
50struct tr_cache
51{
52    tr_ptrArray blocks;
53    int max_blocks;
54    size_t max_bytes;
55
56    size_t disk_writes;
57    size_t disk_write_bytes;
58    size_t cache_writes;
59    size_t cache_write_bytes;
60};
61
62/****
63*****
64****/
65
66struct run_info
67{
68  int       pos;
69  int       rank;
70  time_t    last_block_time;
71  tr_bool   is_multi_piece;
72  tr_bool   is_piece_done;
73  unsigned  len;
74};
75
76
77/* return a count of how many contiguous blocks there are starting at this pos */
78static int
79getBlockRun( const tr_cache * cache, int pos, struct run_info * info )
80{
81    int i;
82    const int n = tr_ptrArraySize( &cache->blocks );
83    const struct cache_block ** blocks = (const struct cache_block**) tr_ptrArrayBase( &cache->blocks );
84    const struct cache_block * ref = blocks[pos];
85    tr_block_index_t block = ref->block;
86
87    for( i=pos; i<n; ++i, ++block ) {
88        const struct cache_block * b = blocks[i];
89        if( b->block != block ) break;
90        if( b->tor != ref->tor ) break;
91//fprintf( stderr, "pos %d tor %d block %zu time %zu\n", i, b->tor->uniqueId, (size_t)b->block, (size_t)b->time );
92    }
93
94//fprintf( stderr, "run is %d long from [%d to %d)\n", (int)(i-pos), i, (int)pos );
95    if( info != NULL ) {
96        const struct cache_block * b = blocks[i-1];
97        info->last_block_time = b->time;
98        info->is_piece_done = tr_cpPieceIsComplete( &b->tor->completion, b->piece );
99        info->is_multi_piece = b->piece != blocks[pos]->piece ? TRUE : FALSE;
100        info->len = i - pos;
101        info->pos = pos;
102    }
103
104    return i-pos;
105}
106
107/* higher rank comes before lower rank */
108static int
109compareRuns( const void * va, const void * vb )
110{
111    const struct run_info * a = va;
112    const struct run_info * b = vb;
113    return b->rank - a->rank;
114}
115
116enum
117{
118    MULTIFLAG   = 0x1000,
119    DONEFLAG    = 0x2000,
120    SESSIONFLAG = 0x4000
121};
122/* Calculte runs
123 *   - Stale runs, runs sitting in cache for a long time or runs not growing, get priority.
124 *     Returns number of runs.
125 */
126static int
127calcRuns( tr_cache * cache, struct run_info * runs )
128{
129    const int n = tr_ptrArraySize( &cache->blocks );
130    int i = 0, pos;
131    const time_t now = tr_time();
132
133    for( pos = 0; pos < n; pos += runs[i++].len )
134    {
135        int rank = getBlockRun( cache, pos, &runs[i] );
136
137        /* This adds ~2 to the relative length of a run for every minute it has
138         * languished in the cache. */
139        rank += ( now - runs[i].last_block_time ) / 32;
140
141        /* Flushing stale blocks should be a top priority as the probability of them
142         * growing is very small, for blocks on piece boundaries, and nonexistant for
143         * blocks inside pieces. */
144        rank |= runs[i].is_piece_done ? DONEFLAG : 0;
145
146        /* Move the multi piece runs higher */
147        rank |= runs[i].is_multi_piece ? MULTIFLAG : 0;
148
149        runs[i].rank = rank;
150//fprintf(stderr,"block run at pos %d of length %d and age %ld adjusted +%d\n",runs[i].pos,runs[i].len,now-runs[i].last_block_time,rank-runs[i].len);
151    }
152
153    //fprintf( stderr, "%d block runs\n", i );
154    qsort( runs, i, sizeof( struct run_info ), compareRuns );
155    return i;
156}
157
158static int
159flushContiguous( tr_cache * cache, int pos, int n )
160{
161    int i;
162    int err = 0;
163    uint8_t * buf = tr_new( uint8_t, n * MAX_BLOCK_SIZE );
164    uint8_t * walk = buf;
165    struct cache_block ** blocks = (struct cache_block**) tr_ptrArrayBase( &cache->blocks );
166
167    struct cache_block * b = blocks[pos];
168    tr_torrent * tor             = b->tor;
169    const tr_piece_index_t piece = b->piece;
170    const uint32_t offset        = b->offset;
171
172//fprintf( stderr, "flushing %d contiguous blocks [%d-%d) from cache to disk\n", n, pos, n+pos );
173
174    for( i=pos; i<pos+n; ++i ) {
175        b = blocks[i];
176        evbuffer_copyout( b->evbuf, walk, b->length );
177        walk += b->length;
178        evbuffer_free( b->evbuf );
179        tr_free( b );
180    }
181    tr_ptrArrayErase( &cache->blocks, pos, pos+n );
182
183#if 0
184    tr_tordbg( tor, "Writing to disk piece %d, offset %d, len %d", (int)piece, (int)offset, (int)(walk-buf) );
185    tr_ndbg( MY_NAME, "Removing %d blocks from cache, rank: %d - %d left", n, rank, tr_ptrArraySize(&cache->blocks) );
186    fprintf( stderr, "%s - Writing to disk piece %d, offset %d, len %d\n", tr_torrentName(tor), (int)piece, (int)offset, (int)(walk-buf) );
187    fprintf( stderr, "%s - Removing %d blocks from cache; %d left\n", MY_NAME, n, tr_ptrArraySize(&cache->blocks) );
188#endif
189
190    err = tr_ioWrite( tor, piece, offset, walk-buf, buf );
191    tr_free( buf );
192
193    ++cache->disk_writes;
194    cache->disk_write_bytes += walk-buf;
195    return err;
196}
197
198static int
199flushRuns( tr_cache * cache, struct run_info * runs, int n )
200{
201    int i, j, err = 0;
202
203    for( i = 0; !err && i < n; ++i )
204    {
205        err = flushContiguous( cache, runs[i].pos, runs[i].len );
206        for( j = i + 1; j < n; ++j )
207            if( runs[j].pos > runs[i].pos )
208                runs[j].pos -= runs[i].len;
209    }
210
211    return err;
212}
213
214static int
215cacheTrim( tr_cache * cache )
216{
217    int err = 0;
218
219    if( tr_ptrArraySize( &cache->blocks ) > cache->max_blocks )
220    {
221        /* Amount of cache that should be removed by the flush. This influences how large
222         * runs can grow as well as how often flushes will happen. */
223        const int cacheCutoff = 1 + cache->max_blocks / 4;
224        struct run_info * runs = tr_new( struct run_info, tr_ptrArraySize( &cache->blocks ) );
225        int i = 0, j = 0;
226
227        calcRuns( cache, runs );
228        while( j < cacheCutoff )
229            j += runs[i++].len;
230        err = flushRuns( cache, runs, i );
231        tr_free( runs );
232    }
233
234    return err;
235}
236
237/***
238****
239***/
240
241static int
242getMaxBlocks( int64_t max_bytes )
243{
244    return max_bytes / (double)MAX_BLOCK_SIZE;
245}
246
247int
248tr_cacheSetLimit( tr_cache * cache, int64_t max_bytes )
249{
250    char buf[128];
251
252    cache->max_bytes = max_bytes;
253    cache->max_blocks = getMaxBlocks( max_bytes );
254
255    tr_formatter_mem_B( buf, cache->max_bytes, sizeof( buf ) );
256    tr_ndbg( MY_NAME, "Maximum cache size set to %s (%d blocks)", buf, cache->max_blocks );
257
258    return cacheTrim( cache );
259}
260
261int64_t
262tr_cacheGetLimit( const tr_cache * cache )
263{
264    return cache->max_bytes;
265}
266
267tr_cache *
268tr_cacheNew( int64_t max_bytes )
269{
270    tr_cache * cache = tr_new0( tr_cache, 1 );
271    cache->blocks = TR_PTR_ARRAY_INIT;
272    cache->max_bytes = max_bytes;
273    cache->max_blocks = getMaxBlocks( max_bytes );
274    return cache;
275}
276
277void
278tr_cacheFree( tr_cache * cache )
279{
280    assert( tr_ptrArrayEmpty( &cache->blocks ) );
281    tr_ptrArrayDestruct( &cache->blocks, NULL );
282    tr_free( cache );
283}
284
285/***
286****
287***/
288
289static int
290cache_block_compare( const void * va, const void * vb )
291{
292    const struct cache_block * a = va;
293    const struct cache_block * b = vb;
294
295    /* primary key: torrent id */
296    if( a->tor->uniqueId != b->tor->uniqueId )
297        return a->tor->uniqueId < b->tor->uniqueId ? -1 : 1;
298
299    /* secondary key: block # */
300    if( a->block != b->block )
301        return a->block < b->block ? -1 : 1;
302
303    /* they're equal */
304    return 0;
305}
306
307static struct cache_block *
308findBlock( tr_cache           * cache,
309           tr_torrent         * torrent,
310           tr_piece_index_t     piece,
311           uint32_t             offset )
312{
313    struct cache_block key;
314    key.tor = torrent;
315    key.block = _tr_block( torrent, piece, offset );
316    return tr_ptrArrayFindSorted( &cache->blocks, &key, cache_block_compare );
317}
318
319int
320tr_cacheWriteBlock( tr_cache         * cache,
321                    tr_torrent       * torrent,
322                    tr_piece_index_t   piece,
323                    uint32_t           offset,
324                    uint32_t           length,
325                    struct evbuffer  * writeme )
326{
327    struct cache_block * cb = findBlock( cache, torrent, piece, offset );
328
329    if( cb == NULL )
330    {
331        cb = tr_new( struct cache_block, 1 );
332        cb->tor = torrent;
333        cb->piece = piece;
334        cb->offset = offset;
335        cb->length = length;
336        cb->block = _tr_block( torrent, piece, offset );
337        cb->evbuf = evbuffer_new( );
338        tr_ptrArrayInsertSorted( &cache->blocks, cb, cache_block_compare );
339    }
340
341    cb->time = tr_time();
342
343    assert( cb->length == length );
344    evbuffer_drain( cb->evbuf, evbuffer_get_length( cb->evbuf ) );
345    evbuffer_remove_buffer( writeme, cb->evbuf, cb->length );
346
347    ++cache->cache_writes;
348    cache->cache_write_bytes += cb->length;
349
350    return cacheTrim( cache );
351}
352
353int
354tr_cacheReadBlock( tr_cache         * cache,
355                   tr_torrent       * torrent,
356                   tr_piece_index_t   piece,
357                   uint32_t           offset,
358                   uint32_t           len,
359                   uint8_t          * setme )
360{
361    int err = 0;
362    struct cache_block * cb = findBlock( cache, torrent, piece, offset );
363
364    if( cb )
365        evbuffer_copyout( cb->evbuf, setme, len );
366    else
367        err = tr_ioRead( torrent, piece, offset, len, setme );
368
369    return err;
370}
371
372int
373tr_cachePrefetchBlock( tr_cache         * cache,
374                       tr_torrent       * torrent,
375                       tr_piece_index_t   piece,
376                       uint32_t           offset,
377                       uint32_t           len )
378{
379    int err = 0;
380    struct cache_block * cb = findBlock( cache, torrent, piece, offset );
381
382    if( cb == NULL )
383        err = tr_ioPrefetch( torrent, piece, offset, len );
384
385    return err;
386}
387
388/***
389****
390***/
391
392static int
393findBlockPos( tr_cache * cache, tr_torrent * torrent, tr_piece_index_t block )
394{
395    struct cache_block key;
396    key.tor = torrent;
397    key.block = block;
398    return tr_ptrArrayLowerBound( &cache->blocks, &key, cache_block_compare, NULL );
399}
400
401int tr_cacheFlushDone( tr_cache * cache )
402{
403    int err = 0;
404
405    if( tr_ptrArraySize( &cache->blocks ) > 0 )
406    {
407        struct run_info * runs = tr_new( struct run_info, tr_ptrArraySize( &cache->blocks ) );
408        int i = 0, n;
409
410        n = calcRuns( cache, runs );
411        while( i < n && ( runs[i].is_piece_done || runs[i].is_multi_piece ) )
412            runs[i++].rank |= SESSIONFLAG;
413        err = flushRuns( cache, runs, i );
414        tr_free( runs );
415    }
416
417    return err;
418}
419
420int
421tr_cacheFlushFile( tr_cache * cache, tr_torrent * torrent, tr_file_index_t i )
422{
423    int pos;
424    int err = 0;
425    tr_block_index_t first;
426    tr_block_index_t last;
427    tr_torGetFileBlockRange( torrent, i, &first, &last );
428    pos = findBlockPos( cache, torrent, first );
429    dbgmsg( "flushing file %d from cache to disk: blocks [%zu...%zu]", (int)i, (size_t)first, (size_t)last );
430
431    /* flush out all the blocks in that file */
432    while( !err && ( pos < tr_ptrArraySize( &cache->blocks ) ) )
433    {
434        const struct cache_block * b = tr_ptrArrayNth( &cache->blocks, pos );
435        if( b->tor != torrent ) break;
436        if( ( b->block < first ) || ( b->block > last ) ) break;
437        err = flushContiguous( cache, pos, getBlockRun( cache, pos, NULL ) );
438    }
439
440    return err;
441}
442
443int
444tr_cacheFlushTorrent( tr_cache * cache, tr_torrent * torrent )
445{
446    int err = 0;
447    const int pos = findBlockPos( cache, torrent, 0 );
448
449    /* flush out all the blocks in that torrent */
450    while( !err && ( pos < tr_ptrArraySize( &cache->blocks ) ) )
451    {
452        const struct cache_block * b = tr_ptrArrayNth( &cache->blocks, pos );
453        if( b->tor != torrent ) break;
454        err = flushContiguous( cache, pos, getBlockRun( cache, pos, NULL ) );
455    }
456
457    return err;
458}
Note: See TracBrowser for help on using the repository browser.