source: trunk/libtransmission/fdlimit.c @ 8777

Last change on this file since 8777 was 8777, checked in by charles, 14 years ago

(trunk libT) dead code removal

  • Property svn:keywords set to Date Rev Author Id
File size: 18.2 KB
Line 
1/******************************************************************************
2 * $Id: fdlimit.c 8777 2009-07-03 19:45:29Z 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" /* tr_lock */
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    isCheckedOut;
87    tr_bool    isWritable;
88    int        torrentId;
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
99    struct tr_openfile  * openFiles;
100    int                   openFileLimit;
101
102    tr_lock             * lock;
103};
104
105static struct tr_fd_s * gFd = NULL;
106
107/***
108****
109****  Local Files
110****
111***/
112
113#ifndef O_LARGEFILE
114 #define O_LARGEFILE 0
115#endif
116
117static tr_bool
118preallocateFileSparse( int fd, uint64_t length )
119{
120    const char zero = '\0';
121
122    if( length == 0 )
123        return TRUE;
124
125    if( lseek( fd, length-1, SEEK_SET ) == -1 )
126        return FALSE;
127    if( write( fd, &zero, 1 ) == -1 )
128        return FALSE;
129    if( ftruncate( fd, length ) == -1 )
130        return FALSE;
131
132    return TRUE;
133}
134
135static tr_bool
136preallocateFileFull( const char * filename, uint64_t length )
137{
138    tr_bool success = 0;
139
140#ifdef WIN32
141
142    HANDLE hFile = CreateFile( filename, GENERIC_WRITE, 0, 0, CREATE_NEW, 0, 0 );
143    if( hFile != INVALID_HANDLE_VALUE )
144    {
145        LARGE_INTEGER li;
146        li.QuadPart = length;
147        success = SetFilePointerEx( hFile, li, NULL, FILE_BEGIN ) && SetEndOfFile( hFile );
148        CloseHandle( hFile );
149    }
150
151#else
152
153    int flags = O_RDWR | O_CREAT | O_LARGEFILE;
154    int fd = open( filename, flags, 0666 );
155    if( fd >= 0 )
156    {
157# ifdef HAVE_XFS_XFS_H
158        if( !success && platform_test_xfs_fd( fd ) )
159        {
160            xfs_flock64_t fl;
161            fl.l_whence = 0;
162            fl.l_start = 0;
163            fl.l_len = length;
164            success = !xfsctl( NULL, fd, XFS_IOC_RESVSP64, &fl );
165        }
166# endif
167# ifdef SYS_DARWIN
168        if( !success )
169        {
170            fstore_t fst;
171            fst.fst_flags = F_ALLOCATECONTIG;
172            fst.fst_posmode = F_PEOFPOSMODE;
173            fst.fst_offset = 0;
174            fst.fst_length = length;
175            fst.fst_bytesalloc = 0;
176            success = !fcntl( fd, F_PREALLOCATE, &fst );
177        }
178# endif
179# ifdef HAVE_POSIX_FALLOCATE
180        if( !success )
181        {
182            success = !posix_fallocate( fd, 0, length );
183        }
184# endif
185
186        if( !success ) /* if nothing else works, do it the old-fashioned way */
187        {
188            uint8_t buf[ 4096 ]; 
189            memset( buf, 0, sizeof( buf ) ); 
190            success = TRUE; 
191            while ( success && ( length > 0 ) ) 
192            { 
193                const int thisPass = MIN( length, sizeof( buf ) ); 
194                success = write( fd, buf, thisPass ) == thisPass; 
195                length -= thisPass; 
196            } 
197        }
198
199        close( fd );
200    }
201
202#endif
203
204    return success;
205}
206
207tr_bool
208tr_preallocate_file( const char * filename, uint64_t length )
209{
210    return preallocateFileFull( filename, length );
211}
212
213int
214tr_open_file_for_writing( const char * filename )
215{
216    int flags = O_WRONLY | O_CREAT;
217#ifdef O_BINARY
218    flags |= O_BINARY;
219#endif
220#ifdef O_LARGEFILE
221    flags |= O_LARGEFILE;
222#endif
223    return open( filename, flags, 0666 );
224}
225
226int
227tr_open_file_for_scanning( const char * filename )
228{
229    int fd;
230    int flags;
231
232    /* build the flags */
233    flags = O_RDONLY;
234#ifdef O_SEQUENTIAL
235    flags |= O_SEQUENTIAL;
236#endif
237#ifdef O_BINARY
238    flags |= O_BINARY;
239#endif
240#ifdef O_LARGEFILE
241    flags |= O_LARGEFILE;
242#endif
243
244    /* open the file */
245    fd = open( filename, flags, 0666 );
246    if( fd >= 0 )
247    {
248        /* Set hints about the lookahead buffer and caching. It's okay
249           for these to fail silently, so don't let them affect errno */
250        const int err = errno;
251#ifdef HAVE_POSIX_FADVISE
252        posix_fadvise( fd, 0, 0, POSIX_FADV_SEQUENTIAL );
253#endif
254#ifdef SYS_DARWIN
255        fcntl( fd, F_NOCACHE, 1 );
256        fcntl( fd, F_RDAHEAD, 1 );
257#endif
258        errno = err;
259    }
260
261    return fd;
262}
263
264void
265tr_close_file( int fd )
266{
267#if defined(HAVE_POSIX_FADVISE)
268    /* Set hint about not caching this file.
269       It's okay for this to fail silently, so don't let it affect errno */
270    const int err = errno;
271    posix_fadvise( fd, 0, 0, POSIX_FADV_DONTNEED );
272    errno = err;
273#endif
274    close( fd );
275}
276
277/**
278 * returns 0 on success, or an errno value on failure.
279 * errno values include ENOENT if the parent folder doesn't exist,
280 * plus the errno values set by tr_mkdirp() and open().
281 */
282static int
283TrOpenFile( int                      i,
284            const char             * folder,
285            const char             * torrentFile,
286            tr_bool                  doWrite,
287            tr_preallocation_mode    preallocationMode,
288            uint64_t                 desiredFileSize )
289{
290    struct tr_openfile * file = &gFd->openFiles[i];
291    int                  flags;
292    char               * filename;
293    struct stat          sb;
294    int                  alreadyExisted;
295
296    /* confirm the parent folder exists */
297    if( stat( folder, &sb ) || !S_ISDIR( sb.st_mode ) )
298    {
299        tr_err( _( "Couldn't create \"%1$s\": parent folder \"%2$s\" does not exist" ), torrentFile, folder );
300        return ENOENT;
301    }
302
303    /* create subfolders, if any */
304    filename = tr_buildPath( folder, torrentFile, NULL );
305    if( doWrite )
306    {
307        char * tmp = tr_dirname( filename );
308        const int err = tr_mkdirp( tmp, 0777 ) ? errno : 0;
309        if( err ) {
310            tr_err( _( "Couldn't create \"%1$s\": %2$s" ), tmp, tr_strerror( err ) );
311            tr_free( tmp );
312            tr_free( filename );
313            return err;
314        }
315        tr_free( tmp );
316    }
317
318    alreadyExisted = !stat( filename, &sb ) && S_ISREG( sb.st_mode );
319
320    if( doWrite && !alreadyExisted && ( preallocationMode == TR_PREALLOCATE_FULL ) )
321        if( preallocateFileFull( filename, desiredFileSize ) )
322            tr_inf( _( "Preallocated file \"%s\"" ), filename );
323   
324    /* open the file */
325    flags = doWrite ? ( O_RDWR | O_CREAT ) : O_RDONLY;
326#ifdef O_SEQUENTIAL
327    flags |= O_SEQUENTIAL;
328#endif
329#ifdef O_LARGEFILE
330    flags |= O_LARGEFILE;
331#endif
332#ifdef WIN32
333    flags |= O_BINARY;
334#endif
335    file->fd = open( filename, flags, 0666 );
336    if( file->fd == -1 )
337    {
338        const int err = errno;
339        tr_err( _( "Couldn't open \"%1$s\": %2$s" ), filename, tr_strerror( err ) );
340        tr_free( filename );
341        return err;
342    }
343
344    /* If the file already exists and it's too large, truncate it.
345     * This is a fringe case that happens if a torrent's been updated
346     * and one of the updated torrent's files is smaller.
347     * http://trac.transmissionbt.com/ticket/2228
348     * https://bugs.launchpad.net/ubuntu/+source/transmission/+bug/318249
349     */
350    if( alreadyExisted && ( desiredFileSize < (uint64_t)sb.st_size ) )
351        ftruncate( file->fd, desiredFileSize );
352
353    if( doWrite && !alreadyExisted && ( preallocationMode == TR_PREALLOCATE_SPARSE ) )
354        preallocateFileSparse( file->fd, desiredFileSize );
355
356#ifdef HAVE_POSIX_FADVISE
357    posix_fadvise( file->fd, 0, 0, POSIX_FADV_SEQUENTIAL );
358#endif
359
360    tr_free( filename );
361    return 0;
362}
363
364static int
365fileIsOpen( const struct tr_openfile * o )
366{
367    return o->fd >= 0;
368}
369
370static void
371TrCloseFile( int i )
372{
373    struct tr_openfile * o = &gFd->openFiles[i];
374
375    assert( i >= 0 );
376    assert( i < gFd->openFileLimit );
377    assert( fileIsOpen( o ) );
378
379    tr_close_file( o->fd );
380    o->fd = -1;
381    o->isCheckedOut = 0;
382}
383
384static int
385fileIsCheckedOut( const struct tr_openfile * o )
386{
387    return fileIsOpen( o ) && o->isCheckedOut;
388}
389
390/* returns an fd on success, or a -1 on failure and sets errno */
391int
392tr_fdFileCheckout( int                      torrentId,
393                   const char             * folder,
394                   const char             * torrentFile,
395                   tr_bool                  doWrite,
396                   tr_preallocation_mode    preallocationMode,
397                   uint64_t                 desiredFileSize )
398{
399    int i, winner = -1;
400    struct tr_openfile * o;
401    char filename[MAX_PATH_LENGTH];
402
403    assert( torrentId > 0 );
404    assert( folder && *folder );
405    assert( torrentFile && *torrentFile );
406    assert( doWrite == 0 || doWrite == 1 );
407
408    tr_snprintf( filename, sizeof( filename ), "%s%c%s", folder, TR_PATH_DELIMITER, torrentFile );
409    dbgmsg( "looking for file '%s', writable %c", filename, doWrite ? 'y' : 'n' );
410
411    tr_lockLock( gFd->lock );
412
413    /* is it already open? */
414    for( i=0; i<gFd->openFileLimit; ++i )
415    {
416        o = &gFd->openFiles[i];
417
418        if( !fileIsOpen( o ) )
419            continue;
420        if( torrentId != o->torrentId )
421            continue;
422        if( strcmp( filename, o->filename ) )
423            continue;
424
425        if( fileIsCheckedOut( o ) )
426        {
427            dbgmsg( "found it!  it's open, but checked out.  waiting..." );
428            tr_lockUnlock( gFd->lock );
429            tr_wait( 200 );
430            tr_lockLock( gFd->lock );
431            i = -1; /* reloop */
432            continue;
433        }
434
435        if( doWrite && !o->isWritable )
436        {
437            dbgmsg( "found it!  it's open and available, but isn't writable. closing..." );
438            TrCloseFile( i );
439            break;
440        }
441
442        dbgmsg( "found it!  it's ready for use!" );
443        winner = i;
444        break;
445    }
446
447    dbgmsg( "it's not already open.  looking for an open slot or an old file." );
448    while( winner < 0 )
449    {
450        uint64_t date = tr_date( ) + 1;
451
452        /* look for the file that's been open longest */
453        for( i=0; i<gFd->openFileLimit; ++i )
454        {
455            o = &gFd->openFiles[i];
456
457            if( !fileIsOpen( o ) )
458            {
459                winner = i;
460                dbgmsg( "found an empty slot in %d", winner );
461                break;
462            }
463
464            if( date > o->date )
465            {
466                date = o->date;
467                winner = i;
468            }
469        }
470
471        if( winner >= 0 )
472        {
473            if( fileIsOpen( &gFd->openFiles[winner] ) )
474            {
475                dbgmsg( "closing file '%s', slot #%d",
476                        gFd->openFiles[winner].filename,
477                        winner );
478                TrCloseFile( winner );
479            }
480        }
481        else
482        {
483            dbgmsg( "everything's full!  waiting for someone else to finish something" );
484            tr_lockUnlock( gFd->lock );
485            tr_wait( 200 );
486            tr_lockLock( gFd->lock );
487        }
488    }
489
490    assert( winner >= 0 );
491    o = &gFd->openFiles[winner];
492    if( !fileIsOpen( o ) )
493    {
494        const int err = TrOpenFile( winner, folder, torrentFile, doWrite, preallocationMode, desiredFileSize );
495        if( err ) {
496            tr_lockUnlock( gFd->lock );
497            errno = err;
498            return -1;
499        }
500
501        dbgmsg( "opened '%s' in slot %d, doWrite %c", filename, winner,
502                doWrite ? 'y' : 'n' );
503        tr_strlcpy( o->filename, filename, sizeof( o->filename ) );
504        o->isWritable = doWrite;
505    }
506
507    dbgmsg( "checking out '%s' in slot %d", filename, winner );
508    o->torrentId = torrentId;
509    o->isCheckedOut = 1;
510    o->date = tr_date( );
511    tr_lockUnlock( gFd->lock );
512    return o->fd;
513}
514
515void
516tr_fdFileReturn( int fd )
517{
518    int i;
519
520    tr_lockLock( gFd->lock );
521
522    for( i = 0; i < gFd->openFileLimit; ++i )
523    {
524        struct tr_openfile * o = &gFd->openFiles[i];
525        if( o->fd != fd )
526            continue;
527
528        dbgmsg( "releasing file '%s' in slot #%d", o->filename, i );
529        o->isCheckedOut = 0;
530
531        break;
532    }
533
534    tr_lockUnlock( gFd->lock );
535}
536
537void
538tr_fdFileClose( const char * filename )
539{
540    int i;
541    tr_lockLock( gFd->lock );
542
543    for( i=0; i<gFd->openFileLimit; ++i )
544    {
545        struct tr_openfile * o = &gFd->openFiles[i];
546        if( !fileIsOpen( o ) || strcmp( filename, o->filename ) )
547            continue;
548
549        dbgmsg( "tr_fdFileClose closing '%s'", filename );
550
551        assert( !o->isCheckedOut && "this is a test assertion... I *think* this is always true now" );
552
553        TrCloseFile( i );
554    }
555
556    tr_lockUnlock( gFd->lock );
557}
558
559void
560tr_fdTorrentClose( int torrentId )
561{
562    int i;
563    tr_lockLock( gFd->lock );
564
565    for( i=0; i<gFd->openFileLimit; ++i )
566    {
567        struct tr_openfile * o = &gFd->openFiles[i];
568
569        assert( !o->isCheckedOut && "this is a test assertion... I *think* this is always true now" );
570
571        if( fileIsOpen( o ) && o->torrentId == torrentId )
572            TrCloseFile( i );
573    }
574
575    tr_lockUnlock( gFd->lock );
576}
577
578
579/***
580****
581****  Sockets
582****
583***/
584
585static int
586getSocketMax( struct tr_fd_s * gFd )
587{
588    return gFd->socketLimit;
589}
590
591int
592tr_fdSocketCreate( int domain, int type )
593{
594    int s = -1;
595
596    tr_lockLock( gFd->lock );
597
598    if( gFd->socketCount < getSocketMax( gFd ) )
599        if( ( s = socket( domain, type, 0 ) ) < 0 )
600        {
601#ifdef SYS_DARWIN
602            if( sockerrno != EAFNOSUPPORT )
603#endif
604            tr_err( _( "Couldn't create socket: %s" ),
605                   tr_strerror( sockerrno ) );
606            s = -sockerrno;
607        }
608
609    if( s > -1 )
610        ++gFd->socketCount;
611
612    assert( gFd->socketCount >= 0 );
613
614    tr_lockUnlock( gFd->lock );
615    return s;
616}
617
618int
619tr_fdSocketAccept( int           b,
620                   tr_address  * addr,
621                   tr_port     * port )
622{
623    int s;
624    unsigned int len;
625    struct sockaddr_storage sock;
626    tr_lockLock( gFd->lock );
627
628    assert( addr );
629    assert( port );
630
631    len = sizeof( struct sockaddr_storage );
632    s = accept( b, (struct sockaddr *) &sock, &len );
633
634    if( ( s >= 0 ) && gFd->socketCount > getSocketMax( gFd ) )
635    {
636        EVUTIL_CLOSESOCKET( s );
637        s = -1;
638    }
639
640    if( s >= 0 )
641    {
642        /* "The ss_family field of the sockaddr_storage structure will always
643         * align with the family field of any protocol-specific structure." */ 
644        if( sock.ss_family == AF_INET ) 
645        {
646            struct sockaddr_in *si;
647            union { struct sockaddr_storage dummy; struct sockaddr_in si; } s;
648            s.dummy = sock;
649            si = &s.si;
650            addr->type = TR_AF_INET; 
651            addr->addr.addr4.s_addr = si->sin_addr.s_addr; 
652            *port = si->sin_port; 
653        } 
654        else 
655        { 
656            struct sockaddr_in6 *si;
657            union { struct sockaddr_storage dummy; struct sockaddr_in6 si; } s;
658            s.dummy = sock;
659            si = &s.si;
660            addr->type = TR_AF_INET6; 
661            addr->addr.addr6 = si->sin6_addr;
662            *port = si->sin6_port; 
663        } 
664        ++gFd->socketCount;
665    }
666
667    tr_lockUnlock( gFd->lock );
668    return s;
669}
670
671static void
672socketClose( int fd )
673{
674    EVUTIL_CLOSESOCKET( fd );
675}
676
677void
678tr_fdSocketClose( int s )
679{
680    tr_lockLock( gFd->lock );
681
682    if( s >= 0 )
683    {
684        socketClose( s );
685        --gFd->socketCount;
686    }
687
688    assert( gFd->socketCount >= 0 );
689
690    tr_lockUnlock( gFd->lock );
691}
692
693/***
694****
695****  Startup / Shutdown
696****
697***/
698
699void
700tr_fdInit( size_t openFileLimit, size_t socketLimit )
701{
702    int i;
703
704    assert( gFd == NULL );
705    gFd = tr_new0( struct tr_fd_s, 1 );
706    gFd->openFiles = tr_new0( struct tr_openfile, openFileLimit );
707    gFd->openFileLimit = openFileLimit;
708    gFd->lock = tr_lockNew( );
709
710#ifdef HAVE_GETRLIMIT
711    {
712        struct rlimit rlim;
713        getrlimit( RLIMIT_NOFILE, &rlim );
714        rlim.rlim_cur = MIN( rlim.rlim_max,
715                            (rlim_t)( socketLimit + NOFILE_BUFFER ) );
716        setrlimit( RLIMIT_NOFILE, &rlim );
717        gFd->socketLimit = rlim.rlim_cur - NOFILE_BUFFER;
718        tr_dbg( "setrlimit( RLIMIT_NOFILE, %d )", (int)rlim.rlim_cur );
719    }
720#else
721    gFd->socketLimit = socketLimit;
722#endif
723    tr_dbg( "%zu usable file descriptors", socketLimit );
724
725    for( i = 0; i < gFd->openFileLimit; ++i )
726        gFd->openFiles[i].fd = -1;
727}
728
729void
730tr_fdClose( void )
731{
732    int i = 0;
733
734    for( i = 0; i < gFd->openFileLimit; ++i )
735        if( fileIsOpen( &gFd->openFiles[i] ) )
736            TrCloseFile( i );
737
738    tr_lockFree( gFd->lock );
739
740    tr_free( gFd->openFiles );
741    tr_free( gFd );
742    gFd = NULL;
743}
744
745void
746tr_fdSetPeerLimit( uint16_t n )
747{
748    assert( gFd != NULL && "tr_fdInit() must be called first!" );
749    gFd->socketLimit = n;
750}
751
752uint16_t
753tr_fdGetPeerLimit( void )
754{
755    return gFd ? gFd->socketLimit : -1;
756}
Note: See TracBrowser for help on using the repository browser.