source: trunk/libtransmission/fdlimit.c @ 9346

Last change on this file since 9346 was 9346, checked in by charles, 13 years ago

libT doesn't need to create the Incomplete directory until it's needed

  • Property svn:keywords set to Date Rev Author Id
File size: 17.1 KB
Line 
1/******************************************************************************
2 * $Id: fdlimit.c 9346 2009-10-21 19:33:37Z charles $
3 *
4 * Copyright (c) 2005-2008 Transmission authors and contributors
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 * DEALINGS IN THE SOFTWARE.
23 *****************************************************************************/
24
25#ifndef WIN32
26 #define HAVE_GETRLIMIT
27#endif
28
29#ifdef HAVE_POSIX_FADVISE
30 #ifdef _XOPEN_SOURCE
31  #undef _XOPEN_SOURCE
32 #endif
33 #define _XOPEN_SOURCE 600
34#endif
35
36#include <assert.h>
37#include <errno.h>
38#include <inttypes.h>
39#include <stdio.h>
40#include <stdlib.h>
41#include <string.h>
42#ifdef SYS_DARWIN
43 #include <fcntl.h>
44#endif
45
46#ifdef HAVE_XFS_XFS_H
47 #include <xfs/xfs.h>
48#endif
49
50#include <sys/types.h>
51#include <sys/stat.h>
52#ifdef HAVE_GETRLIMIT
53 #include <sys/time.h> /* getrlimit */
54 #include <sys/resource.h> /* getrlimit */
55#endif
56#include <unistd.h>
57#include <fcntl.h> /* O_LARGEFILE posix_fadvise */
58
59#include <evutil.h>
60
61#include "transmission.h"
62#include "fdlimit.h"
63#include "list.h"
64#include "net.h"
65#include "platform.h" /* MAX_PATH_LENGTH, TR_PATH_DELIMITER */
66#include "utils.h"
67
68#define dbgmsg( ... ) \
69    do { \
70        if( tr_deepLoggingIsActive( ) ) \
71            tr_deepLog( __FILE__, __LINE__, NULL, __VA_ARGS__ ); \
72    } while( 0 )
73
74/**
75***
76**/
77
78enum
79{
80    NOFILE_BUFFER = 512, /* the process' number of open files is
81                            globalMaxPeers + NOFILE_BUFFER */
82};
83
84struct tr_openfile
85{
86    tr_bool          isWritable;
87    int              torrentId;
88    tr_file_index_t  fileNum;
89    char             filename[MAX_PATH_LENGTH];
90    int              fd;
91    uint64_t         date;
92};
93
94struct tr_fd_s
95{
96    int                   socketCount;
97    int                   socketLimit;
98    int                   openFileLimit;
99    struct tr_openfile  * openFiles;
100};
101
102static struct tr_fd_s * gFd = NULL;
103
104/***
105****
106****  Local Files
107****
108***/
109
110#ifndef O_LARGEFILE
111 #define O_LARGEFILE 0
112#endif
113
114static tr_bool
115preallocateFileSparse( int fd, uint64_t length )
116{
117    const char zero = '\0';
118
119    if( length == 0 )
120        return TRUE;
121
122    if( lseek( fd, length-1, SEEK_SET ) == -1 )
123        return FALSE;
124    if( write( fd, &zero, 1 ) == -1 )
125        return FALSE;
126    if( ftruncate( fd, length ) == -1 )
127        return FALSE;
128
129    return TRUE;
130}
131
132static tr_bool
133preallocateFileFull( const char * filename, uint64_t length )
134{
135    tr_bool success = 0;
136
137#ifdef WIN32
138
139    HANDLE hFile = CreateFile( filename, GENERIC_WRITE, 0, 0, CREATE_NEW, 0, 0 );
140    if( hFile != INVALID_HANDLE_VALUE )
141    {
142        LARGE_INTEGER li;
143        li.QuadPart = length;
144        success = SetFilePointerEx( hFile, li, NULL, FILE_BEGIN ) && SetEndOfFile( hFile );
145        CloseHandle( hFile );
146    }
147
148#else
149
150    int flags = O_RDWR | O_CREAT | O_LARGEFILE;
151    int fd = open( filename, flags, 0666 );
152    if( fd >= 0 )
153    {
154# ifdef HAVE_XFS_XFS_H
155        if( !success && platform_test_xfs_fd( fd ) )
156        {
157            xfs_flock64_t fl;
158            fl.l_whence = 0;
159            fl.l_start = 0;
160            fl.l_len = length;
161            success = !xfsctl( NULL, fd, XFS_IOC_RESVSP64, &fl );
162        }
163# endif
164# ifdef SYS_DARWIN
165        if( !success )
166        {
167            fstore_t fst;
168            fst.fst_flags = F_ALLOCATECONTIG;
169            fst.fst_posmode = F_PEOFPOSMODE;
170            fst.fst_offset = 0;
171            fst.fst_length = length;
172            fst.fst_bytesalloc = 0;
173            success = !fcntl( fd, F_PREALLOCATE, &fst );
174        }
175# endif
176# ifdef HAVE_POSIX_FALLOCATE
177        if( !success )
178        {
179            success = !posix_fallocate( fd, 0, length );
180        }
181# endif
182
183        if( !success ) /* if nothing else works, do it the old-fashioned way */
184        {
185            uint8_t buf[ 4096 ];
186            memset( buf, 0, sizeof( buf ) );
187            success = TRUE;
188            while ( success && ( length > 0 ) )
189            {
190                const int thisPass = MIN( length, sizeof( buf ) );
191                success = write( fd, buf, thisPass ) == thisPass;
192                length -= thisPass;
193            }
194        }
195
196        close( fd );
197    }
198
199#endif
200
201    return success;
202}
203
204tr_bool
205tr_preallocate_file( const char * filename, uint64_t length )
206{
207    return preallocateFileFull( filename, length );
208}
209
210int
211tr_open_file_for_writing( const char * filename )
212{
213    int flags = O_WRONLY | O_CREAT;
214#ifdef O_BINARY
215    flags |= O_BINARY;
216#endif
217#ifdef O_LARGEFILE
218    flags |= O_LARGEFILE;
219#endif
220    return open( filename, flags, 0666 );
221}
222
223int
224tr_open_file_for_scanning( const char * filename )
225{
226    int fd;
227    int flags;
228
229    /* build the flags */
230    flags = O_RDONLY;
231#ifdef O_SEQUENTIAL
232    flags |= O_SEQUENTIAL;
233#endif
234#ifdef O_BINARY
235    flags |= O_BINARY;
236#endif
237#ifdef O_LARGEFILE
238    flags |= O_LARGEFILE;
239#endif
240
241    /* open the file */
242    fd = open( filename, flags, 0666 );
243    if( fd >= 0 )
244    {
245        /* Set hints about the lookahead buffer and caching. It's okay
246           for these to fail silently, so don't let them affect errno */
247        const int err = errno;
248#ifdef HAVE_POSIX_FADVISE
249        posix_fadvise( fd, 0, 0, POSIX_FADV_SEQUENTIAL );
250#endif
251#ifdef SYS_DARWIN
252        fcntl( fd, F_NOCACHE, 1 );
253        fcntl( fd, F_RDAHEAD, 1 );
254#endif
255        errno = err;
256    }
257
258    return fd;
259}
260
261void
262tr_close_file( int fd )
263{
264#if defined(HAVE_POSIX_FADVISE)
265    /* Set hint about not caching this file.
266       It's okay for this to fail silently, so don't let it affect errno */
267    const int err = errno;
268    posix_fadvise( fd, 0, 0, POSIX_FADV_DONTNEED );
269    errno = err;
270#endif
271    close( fd );
272}
273
274/**
275 * returns 0 on success, or an errno value on failure.
276 * errno values include ENOENT if the parent folder doesn't exist,
277 * plus the errno values set by tr_mkdirp() and open().
278 */
279static int
280TrOpenFile( int                      i,
281            const char             * filename,
282            tr_bool                  doWrite,
283            tr_preallocation_mode    preallocationMode,
284            uint64_t                 desiredFileSize )
285{
286    struct tr_openfile * file = &gFd->openFiles[i];
287    int                  flags;
288    struct stat          sb;
289    tr_bool              alreadyExisted;
290
291    /* create subfolders, if any */
292    if( doWrite )
293    {
294        char * dir = tr_dirname( filename );
295        const int err = tr_mkdirp( dir, 0777 ) ? errno : 0;
296        if( err ) {
297            tr_err( _( "Couldn't create \"%1$s\": %2$s" ), dir, tr_strerror( err ) );
298            tr_free( dir );
299            return err;
300        }
301        tr_free( dir );
302    }
303
304    alreadyExisted = !stat( filename, &sb ) && S_ISREG( sb.st_mode );
305
306    if( doWrite && !alreadyExisted && ( preallocationMode == TR_PREALLOCATE_FULL ) )
307        if( preallocateFileFull( filename, desiredFileSize ) )
308            tr_inf( _( "Preallocated file \"%s\"" ), filename );
309
310    /* open the file */
311    flags = doWrite ? ( O_RDWR | O_CREAT ) : O_RDONLY;
312#ifdef O_SEQUENTIAL
313    flags |= O_SEQUENTIAL;
314#endif
315#ifdef O_LARGEFILE
316    flags |= O_LARGEFILE;
317#endif
318#ifdef WIN32
319    flags |= O_BINARY;
320#endif
321    file->fd = open( filename, flags, 0666 );
322    if( file->fd == -1 )
323    {
324        const int err = errno;
325        tr_err( _( "Couldn't open \"%1$s\": %2$s" ), filename, tr_strerror( err ) );
326        return err;
327    }
328
329    /* If the file already exists and it's too large, truncate it.
330     * This is a fringe case that happens if a torrent's been updated
331     * and one of the updated torrent's files is smaller.
332     * http://trac.transmissionbt.com/ticket/2228
333     * https://bugs.launchpad.net/ubuntu/+source/transmission/+bug/318249
334     */
335    if( alreadyExisted && ( desiredFileSize < (uint64_t)sb.st_size ) )
336        ftruncate( file->fd, desiredFileSize );
337
338    if( doWrite && !alreadyExisted && ( preallocationMode == TR_PREALLOCATE_SPARSE ) )
339        preallocateFileSparse( file->fd, desiredFileSize );
340
341#ifdef HAVE_POSIX_FADVISE
342    /* this doubles the OS level readahead buffer, which in practice
343     * turns out to be a good thing, because many (most?) clients request
344     * chunks of blocks in order.
345     * It's okay for this to fail silently, so don't let it affect errno */
346    {
347        const int err = errno;
348        posix_fadvise( file->fd, 0, 0, POSIX_FADV_SEQUENTIAL );
349        errno = err;
350    }
351#endif
352
353    return 0;
354}
355
356static TR_INLINE tr_bool
357fileIsOpen( const struct tr_openfile * o )
358{
359    return o->fd >= 0;
360}
361
362static void
363TrCloseFile( struct tr_openfile * o )
364{
365    assert( o != NULL );
366    assert( fileIsOpen( o ) );
367
368    tr_close_file( o->fd );
369    o->fd = -1;
370}
371
372int
373tr_fdFileGetCached( int              torrentId,
374                    tr_file_index_t  fileNum,
375                    tr_bool          doWrite )
376{
377    struct tr_openfile * match = NULL;
378
379    assert( torrentId > 0 );
380    assert( tr_isBool( doWrite ) );
381
382    /* is it already open? */
383    {
384        int i;
385        struct tr_openfile * o;
386        for( i=0; i<gFd->openFileLimit; ++i )
387        {
388            o = &gFd->openFiles[i];
389
390            if( torrentId != o->torrentId )
391                continue;
392            if( fileNum != o->fileNum )
393                continue;
394            if( !fileIsOpen( o ) )
395                continue;
396
397            match = o;
398            break;
399        }
400    }
401
402    if( ( match != NULL ) && ( !doWrite || match->isWritable ) )
403    {
404        match->date = tr_date( );
405        return match->fd;
406    }
407
408    return -1;
409}
410
411/* returns an fd on success, or a -1 on failure and sets errno */
412int
413tr_fdFileCheckout( int                      torrentId,
414                   tr_file_index_t          fileNum,
415                   const char             * filename,
416                   tr_bool                  doWrite,
417                   tr_preallocation_mode    preallocationMode,
418                   uint64_t                 desiredFileSize )
419{
420    int i, winner = -1;
421    struct tr_openfile * o;
422
423    assert( torrentId > 0 );
424    assert( filename && *filename );
425    assert( tr_isBool( doWrite ) );
426
427    dbgmsg( "looking for file '%s', writable %c", filename, doWrite ? 'y' : 'n' );
428
429    /* is it already open? */
430    for( i=0; i<gFd->openFileLimit; ++i )
431    {
432        o = &gFd->openFiles[i];
433
434        if( torrentId != o->torrentId )
435            continue;
436        if( fileNum != o->fileNum )
437            continue;
438        if( !fileIsOpen( o ) )
439            continue;
440
441        if( doWrite && !o->isWritable )
442        {
443            dbgmsg( "found it!  it's open and available, but isn't writable. closing..." );
444            TrCloseFile( o );
445            break;
446        }
447
448        dbgmsg( "found it!  it's ready for use!" );
449        winner = i;
450        break;
451    }
452
453    dbgmsg( "it's not already open.  looking for an open slot or an old file." );
454    while( winner < 0 )
455    {
456        uint64_t date = tr_date( ) + 1;
457
458        /* look for the file that's been open longest */
459        for( i=0; i<gFd->openFileLimit; ++i )
460        {
461            o = &gFd->openFiles[i];
462
463            if( !fileIsOpen( o ) )
464            {
465                winner = i;
466                dbgmsg( "found an empty slot in %d", winner );
467                break;
468            }
469
470            if( date > o->date )
471            {
472                date = o->date;
473                winner = i;
474            }
475        }
476
477        assert( winner >= 0 );
478
479        if( fileIsOpen( &gFd->openFiles[winner] ) )
480        {
481            dbgmsg( "closing file \"%s\"", gFd->openFiles[winner].filename );
482            TrCloseFile( &gFd->openFiles[winner] );
483        }
484    }
485
486    assert( winner >= 0 );
487    o = &gFd->openFiles[winner];
488    if( !fileIsOpen( o ) )
489    {
490        const int err = TrOpenFile( winner, filename, doWrite,
491                                    preallocationMode, desiredFileSize );
492        if( err ) {
493            errno = err;
494            return -1;
495        }
496
497        dbgmsg( "opened '%s' in slot %d, doWrite %c", filename, winner,
498                doWrite ? 'y' : 'n' );
499        tr_strlcpy( o->filename, filename, sizeof( o->filename ) );
500        o->isWritable = doWrite;
501    }
502
503    dbgmsg( "checking out '%s' in slot %d", filename, winner );
504    o->torrentId = torrentId;
505    o->fileNum = fileNum;
506    o->date = tr_date( );
507    return o->fd;
508}
509
510void
511tr_fdFileClose( const tr_torrent * tor, tr_file_index_t fileNum )
512{
513    struct tr_openfile * o;
514    const struct tr_openfile * end;
515    const int torrentId = tr_torrentId( tor );
516    for( o=gFd->openFiles, end=o+gFd->openFileLimit; o!=end; ++o )
517    {
518        if( torrentId != o->torrentId )
519            continue;
520        if( fileNum != o->fileNum )
521            continue;
522        if( !fileIsOpen( o ) )
523            continue;
524
525        dbgmsg( "tr_fdFileClose closing \"%s\"", o->filename );
526        TrCloseFile( o );
527    }
528}
529
530void
531tr_fdTorrentClose( int torrentId )
532{
533    struct tr_openfile * o;
534    const struct tr_openfile * end;
535
536    for( o=gFd->openFiles, end=o+gFd->openFileLimit; o!=end; ++o )
537        if( fileIsOpen( o ) && ( o->torrentId == torrentId ) )
538            TrCloseFile( o );
539}
540
541/***
542****
543****  Sockets
544****
545***/
546
547static TR_INLINE int
548getSocketMax( struct tr_fd_s * gFd )
549{
550    return gFd->socketLimit;
551}
552
553int
554tr_fdSocketCreate( int domain, int type )
555{
556    int s = -1;
557
558    if( gFd->socketCount < getSocketMax( gFd ) )
559        if( ( s = socket( domain, type, 0 ) ) < 0 )
560        {
561            if( sockerrno != EAFNOSUPPORT )
562                tr_err( _( "Couldn't create socket: %s" ),
563                        tr_strerror( sockerrno ) );
564        }
565
566    if( s > -1 )
567        ++gFd->socketCount;
568
569    assert( gFd->socketCount >= 0 );
570
571    return s;
572}
573
574int
575tr_fdSocketAccept( int           b,
576                   tr_address  * addr,
577                   tr_port     * port )
578{
579    int s;
580    unsigned int len;
581    struct sockaddr_storage sock;
582
583    assert( addr );
584    assert( port );
585
586    len = sizeof( struct sockaddr_storage );
587    s = accept( b, (struct sockaddr *) &sock, &len );
588
589    if( ( s >= 0 ) && gFd->socketCount > getSocketMax( gFd ) )
590    {
591        EVUTIL_CLOSESOCKET( s );
592        s = -1;
593    }
594
595    if( s >= 0 )
596    {
597        /* "The ss_family field of the sockaddr_storage structure will always
598         * align with the family field of any protocol-specific structure." */
599        if( sock.ss_family == AF_INET )
600        {
601            struct sockaddr_in *si;
602            union { struct sockaddr_storage dummy; struct sockaddr_in si; } s;
603            s.dummy = sock;
604            si = &s.si;
605            addr->type = TR_AF_INET;
606            addr->addr.addr4.s_addr = si->sin_addr.s_addr;
607            *port = si->sin_port;
608        }
609        else
610        {
611            struct sockaddr_in6 *si;
612            union { struct sockaddr_storage dummy; struct sockaddr_in6 si; } s;
613            s.dummy = sock;
614            si = &s.si;
615            addr->type = TR_AF_INET6;
616            addr->addr.addr6 = si->sin6_addr;
617            *port = si->sin6_port;
618        }
619        ++gFd->socketCount;
620    }
621
622    return s;
623}
624
625void
626tr_fdSocketClose( int fd )
627{
628    if( fd >= 0 )
629    {
630        EVUTIL_CLOSESOCKET( fd );
631        --gFd->socketCount;
632    }
633
634    assert( gFd->socketCount >= 0 );
635}
636
637/***
638****
639****  Startup / Shutdown
640****
641***/
642
643void
644tr_fdInit( size_t openFileLimit, size_t socketLimit )
645{
646    int i;
647
648    assert( gFd == NULL );
649    gFd = tr_new0( struct tr_fd_s, 1 );
650    gFd->openFiles = tr_new0( struct tr_openfile, openFileLimit );
651    gFd->openFileLimit = openFileLimit;
652
653#ifdef HAVE_GETRLIMIT
654    {
655        struct rlimit rlim;
656        getrlimit( RLIMIT_NOFILE, &rlim );
657        rlim.rlim_cur = MIN( rlim.rlim_max,
658                            (rlim_t)( socketLimit + NOFILE_BUFFER ) );
659        setrlimit( RLIMIT_NOFILE, &rlim );
660        gFd->socketLimit = rlim.rlim_cur - NOFILE_BUFFER;
661        tr_dbg( "setrlimit( RLIMIT_NOFILE, %d )", (int)rlim.rlim_cur );
662    }
663#else
664    gFd->socketLimit = socketLimit;
665#endif
666    tr_dbg( "%zu usable file descriptors", socketLimit );
667
668    for( i = 0; i < gFd->openFileLimit; ++i )
669        gFd->openFiles[i].fd = -1;
670}
671
672void
673tr_fdClose( void )
674{
675    struct tr_openfile * o;
676    const struct tr_openfile * end;
677
678    for( o=gFd->openFiles, end=o+gFd->openFileLimit; o!=end; ++o )
679        if( fileIsOpen( o ) )
680            TrCloseFile( o );
681
682    tr_free( gFd->openFiles );
683    tr_free( gFd );
684    gFd = NULL;
685}
686
687void
688tr_fdSetPeerLimit( uint16_t n )
689{
690    assert( gFd != NULL && "tr_fdInit() must be called first!" );
691    gFd->socketLimit = n;
692}
693
694uint16_t
695tr_fdGetPeerLimit( void )
696{
697    return gFd ? gFd->socketLimit : -1;
698}
Note: See TracBrowser for help on using the repository browser.