<commit_before>/*

Copyright (c) 2007, <NAME>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/storage.hpp"
#include <deque>
#include "libtorrent/disk_io_thread.hpp"
#include "libtorrent/disk_buffer_holder.hpp"
#include "libtorrent/alloca.hpp"
#include "libtorrent/invariant_check.hpp"
#include "libtorrent/error_code.hpp"
#include <boost/scoped_array.hpp>

#ifdef TORRENT_DISK_STATS
#include "libtorrent/time.hpp"
#endif

#if TORRENT_USE_MLOCK && !defined TORRENT_WINDOWS
#include <sys/mman.h>
#endif

namespace libtorrent
{
	disk_buffer_pool::disk_buffer_pool(int block_size)
		: m_block_size(block_size)
#ifndef TORRENT_DISABLE_POOL_ALLOCATOR
		, m_pool(block_size)
#endif
	{
#ifdef TORRENT_STATS
		m_allocations = 0;
#endif
#ifdef TORRENT_DISK_STATS
		m_log.open("disk_buffers.log", std::ios::trunc);
#endif
	}

#ifdef TORRENT_DEBUG
	bool disk_buffer_pool::is_disk_buffer(char* buffer) const
	{
#ifdef TORRENT_DISABLE_POOL_ALLOCATOR
		return true;
#else
		mutex_t::scoped_lock l(m_pool_mutex);
		return m_pool.is_from(buffer);
#endif
	}
#endif

	char* disk_buffer_pool::allocate_buffer(char const* category)
	{
		mutex_t::scoped_lock l(m_pool_mutex);
#ifdef TORRENT_DISABLE_POOL_ALLOCATOR
		char* ret = page_aligned_allocator::malloc(m_block_size);
#else
		char* ret = (char*)m_pool.ordered_malloc();
#endif
#if TORRENT_USE_MLOCK
		if (m_settings.lock_disk_cache)
		{
#ifdef TORRENT_WINDOWS
			VirtualLock(ret, m_block_size);
#else
			mlock(ret, m_block_size);
#endif		
		}
#endif

#ifdef TORRENT_STATS
		++m_allocations;
		++m_categories[category];
		m_buf_to_category[ret] = category;
		m_log << log_time() << " " << category << ": " << m_categories[category] << "\n";
#endif
		return ret;
	}

	void disk_buffer_pool::free_buffer(char* buf)
	{
		TORRENT_ASSERT(buf);
		mutex_t::scoped_lock l(m_pool_mutex);
#ifdef TORRENT_STATS
		--m_allocations;
		TORRENT_ASSERT(m_categories.find(m_buf_to_category[buf])
			!= m_categories.end());
		std::string const& category = m_buf_to_category[buf];
		--m_categories[category];
		m_log << log_time() << " " << category << ": " << m_categories[category] << "\n";
		m_buf_to_category.erase(buf);
#endif
#if TORRENT_USE_MLOCK
		if (m_settings.lock_disk_cache)
		{
#ifdef TORRENT_WINDOWS
			VirtualUnlock(buf, m_block_size);
#else
			munlock(buf, m_block_size);
#endif		
		}
#endif
#ifdef TORRENT_DISABLE_POOL_ALLOCATOR
		page_aligned_allocator::free(buf);
#else
		m_pool.ordered_free(buf);
#endif
	}

	char* disk_buffer_pool::allocate_buffers(int num_blocks, char const* category)
	{
		mutex_t::scoped_lock l(m_pool_mutex);
#ifdef TORRENT_DISABLE_POOL_ALLOCATOR
		char* ret = page_aligned_allocator::malloc(m_block_size * num_blocks);
#else
		char* ret = (char*)m_pool.ordered_malloc(num_blocks);
#endif
#if TORRENT_USE_MLOCK
		if (m_settings.lock_disk_cache)
		{
#ifdef TORRENT_WINDOWS
			VirtualLock(ret, m_block_size * num_blocks);
#else
			mlock(ret, m_block_size * num_blocks);
#endif		
		}
#endif
#ifdef TORRENT_STATS
		m_allocations += num_blocks;
		m_categories[category] += num_blocks;
		m_buf_to_category[ret] = category;
		m_log << log_time() << " " << category << ": " << m_categories[category] << "\n";
#endif
		return ret;
	}

	void disk_buffer_pool::free_buffers(char* buf, int num_blocks)
	{
		TORRENT_ASSERT(buf);
		TORRENT_ASSERT(num_blocks >= 1);
		mutex_t::scoped_lock l(m_pool_mutex);
#ifdef TORRENT_STATS
		m_allocations -= num_blocks;
		TORRENT_ASSERT(m_categories.find(m_buf_to_category[buf])
			!= m_categories.end());
		std::string const& category = m_buf_to_category[buf];
		m_categories[category] -= num_blocks;
		m_log << log_time() << " " << category << ": " << m_categories[category] << "\n";
		m_buf_to_category.erase(buf);
#endif
#if TORRENT_USE_MLOCK
		if (m_settings.lock_disk_cache)
		{
#ifdef TORRENT_WINDOWS
			VirtualUnlock(buf, m_block_size * num_blocks);
#else
			munlock(buf, m_block_size * num_blocks);
#endif		
		}
#endif
#ifdef TORRENT_DISABLE_POOL_ALLOCATOR
		page_aligned_allocator::free(buf);
#else
		m_pool.ordered_free(buf, num_blocks);
#endif
	}

	void disk_buffer_pool::release_memory()
	{
#ifndef TORRENT_DISABLE_POOL_ALLOCATOR
		mutex_t::scoped_lock l(m_pool_mutex);
		m_pool.release_memory();
#endif
	}

// ------- disk_io_thread ------


	disk_io_thread::disk_io_thread(asio::io_service& ios, int block_size)
		: disk_buffer_pool(block_size)
		, m_abort(false)
		, m_queue_buffer_size(0)
		, m_ios(ios)
		, m_disk_io_thread(boost::ref(*this))
	{
#ifdef TORRENT_DISK_STATS
		m_log.open("disk_io_thread.log", std::ios::trunc);
#endif
	}

	disk_io_thread::~disk_io_thread()
	{
		TORRENT_ASSERT(m_abort == true);
	}

	void disk_io_thread::join()
	{
		mutex_t::scoped_lock l(m_queue_mutex);
		disk_io_job j;
		j.action = disk_io_job::abort_thread;
		m_jobs.insert(m_jobs.begin(), j);
		m_signal.notify_all();
		l.unlock();

		m_disk_io_thread.join();
		l.lock();
		TORRENT_ASSERT(m_abort == true);
		m_jobs.clear();
	}

	void disk_io_thread::get_cache_info(sha1_hash const& ih, std::vector<cached_piece_info>& ret) const
	{
		mutex_t::scoped_lock l(m_piece_mutex);
		ret.clear();
		ret.reserve(m_pieces.size());
		for (cache_t::const_iterator i = m_pieces.begin()
			, end(m_pieces.end()); i != end; ++i)
		{
			torrent_info const& ti = *i->storage->info();
			if (ti.info_hash() != ih) continue;
			cached_piece_info info;
			info.piece = i->piece;
			info.last_use = i->last_use;
			info.kind = cached_piece_info::write_cache;
			int blocks_in_piece = (ti.piece_size(i->piece) + (m_block_size) - 1) / m_block_size;
			info.blocks.resize(blocks_in_piece);
			for (int b = 0; b < blocks_in_piece; ++b)
				if (i->blocks[b]) info.blocks[b] = true;
			ret.push_back(info);
		}
		for (cache_t::const_iterator i = m_read_pieces.begin()
			, end(m_read_pieces.end()); i != end; ++i)
		{
			torrent_info const& ti = *i->storage->info();
			if (ti.info_hash() != ih) continue;
			cached_piece_info info;
			info.piece = i->piece;
			info.last_use = i->last_use;
			info.kind = cached_piece_info::read_cache;
			int blocks_in_piece = (ti.piece_size(i->piece) + (m_block_size) - 1) / m_block_size;
			info.blocks.resize(blocks_in_piece);
			for (int b = 0; b < blocks_in_piece; ++b)
				if (i->blocks[b]) info.blocks[b] = true;
			ret.push_back(info);
		}
	}
	
	cache_status disk_io_thread::status() const
	{
		mutex_t::scoped_lock l(m_piece_mutex);
		return m_cache_stats;
	}

	// aborts read operations
	void disk_io_thread::stop(boost::intrusive_ptr<piece_manager> s)
	{
		mutex_t::scoped_lock l(m_queue_mutex);
		// read jobs are aborted, write and move jobs are syncronized
		for (std::list<disk_io_job>::iterator i = m_jobs.begin();
			i != m_jobs.end();)
		{
			if (i->storage != s)
			{
				++i;
				continue;
			}
			if (i->action == disk_io_job::read)
			{
				post_callback(i->callback, *i, -1);
				m_jobs.erase(i++);
				continue;
			}
			if (i->action == disk_io_job::check_files)
			{
				post_callback(i->callback, *i, piece_manager::disk_check_aborted);
				m_jobs.erase(i++);
				continue;
			}
			++i;
		}
		disk_io_job j;
		j.action = disk_io_job::abort_torrent;
		j.storage = s;
		add_job(j);
	}

	bool range_overlap(int start1, int length1, int start2, int length2)
	{
		return (start1 <= start2 && start1 + length1 > start2)
			|| (start2 <= start1 && start2 + length2 > start1);
	}
	
	namespace
	{
		// The semantic of this operator is:
		// should lhs come before rhs in the job queue
		bool operator<(disk_io_job const& lhs, disk_io_job const& rhs)
		{
			// NOTE: comparison inverted to make higher priority
			// skip _in_front_of_ lower priority
			if (lhs.priority > rhs.priority) return true;
			if (lhs.priority < rhs.priority) return false;

			if (lhs.storage.get() < rhs.storage.get()) return true;
			if (lhs.storage.get() > rhs.storage.get()) return false;
			if (lhs.piece < rhs.piece) return true;
			if (lhs.piece > rhs.piece) return false;
			if (lhs.offset < rhs.offset) return true;
//			if (lhs.offset > rhs.offset) return false;
			return false;
		}
	}

	disk_io_thread::cache_t::iterator disk_io_thread::find_cached_piece(
		disk_io_thread::cache_t& cache
		, disk_io_job const& j, mutex_t::scoped_lock& l)
	{
		for (cache_t::iterator i = cache.begin()
			, end(cache.end()); i != end; ++i)
		{
			if (i->storage != j.storage || i->piece != j.piece) continue;
			return i;
		}
		return cache.end();
	}
	
	void disk_io_thread::flush_expired_pieces()
	{
		ptime now = time_now();

		mutex_t::scoped_lock l(m_piece_mutex);

		INVARIANT_CHECK;
		// flush write cache
		for (;;)
		{
			cache_t::iterator i = std::min_element(
				m_pieces.begin(), m_pieces.end()
				, bind(&cached_piece_entry::last_use, _1)
				< bind(&cached_piece_entry::last_use, _2));
			if (i == m_pieces.end()) break;
			int age = total_seconds(now - i->last_use);
			if (age < m_settings.cache_expiry) break;
			flush_and_remove(i, l);
		}

		// flush read cache
		for (;;)
		{
			cache_t::iterator i = std::min_element(
				m_read_pieces.begin(), m_read_pieces.end()
				, bind(&cached_piece_entry::last_use, _1)
				< bind(&cached_piece_entry::last_use, _2));
			if (i == m_read_pieces.end()) break;
			int age = total_seconds(now - i->last_use);
			if (age < m_settings.cache_expiry) break;
			free_piece(*i, l);
			m_read_pieces.erase(i);
		}
	}

	void disk_io_thread::free_piece(cached_piece_entry& p, mutex_t::scoped_lock& l)
	{
		int piece_size = p.storage->info()->piece_size(p.piece);
		int blocks_in_piece = (piece_size + m_block_size - 1) / m_block_size;

		for (int i = 0; i < blocks_in_piece; ++i)
		{
			if (p.blocks[i] == 0) continue;
			free_buffer(p.blocks[i]);
			p.blocks[i] = 0;
			--p.num_blocks;
			--m_cache_stats.cache_size;
			--m_cache_stats.read_cache_size;
		}
	}

	bool disk_io_thread::clear_oldest_read_piece(
		cache_t::iterator ignore
		, mutex_t::scoped_lock& l)
	{
		INVARIANT_CHECK;

		cache_t::iterator i = std::min_element(
			m_read_pieces.begin(), m_read_pieces.end()
			, bind(&cached_piece_entry::last_use, _1)
			< bind(&cached_piece_entry::last_use, _2));
		if (i != m_read_pieces.end() && i != ignore)
		{
			// don't replace an entry that is less than one second old
			if (time_now() - i->last_use < seconds(1)) return false;
			free_piece(*i, l);
			m_read_pieces.erase(i);
			return true;
		}
		return false;
	}

	void disk_io_thread::flush_oldest_piece(mutex_t::scoped_lock& l)
	{
		INVARIANT_CHECK;
		// first look if there are any read cache entries that can
		// be cleared
		if (clear_oldest_read_piece(m_read_pieces.end(), l)) return;

		cache_t::iterator i = std::min_element(
			m_pieces.begin(), m_pieces.end()
			, bind(&cached_piece_entry::last_use, _1)
			< bind(&cached_piece_entry::last_use, _2));
		if (i == m_pieces.end()) return;
		flush_and_remove(i, l);
	}

	void disk_io_thread::flush_and_remove(disk_io_thread::cache_t::iterator e
		, mutex_t::scoped_lock& l)
	{
		flush(e, l);
		m_pieces.erase(e);
	}

	void disk_io_thread::flush(disk_io_thread::cache_t::iterator e
		, mutex_t::scoped_lock& l)
	{
		INVARIANT_CHECK;
		// TODO: copy *e and unlink it before unlocking
		cached_piece_entry& p = *e;
		int piece_size = p.storage->info()->piece_size(p.piece);
#ifdef TORRENT_DISK_STATS
		m_log << log_time() << " flushing " << piece_size << std::endl;
#endif
		TORRENT_ASSERT(piece_size > 0);
		
		int blocks_in_piece = (piece_size + m_block_size - 1) / m_block_size;
		int buffer_size = 0;
		int offset = 0;

		boost::scoped_array<char> buf;
		file::iovec_t* iov = 0;
		int iov_counter = 0;
		if (m_settings.coalesce_writes) buf.reset(new (std::nothrow) char[piece_size]);
		else iov = TORRENT_ALLOCA(file::iovec_t, blocks_in_piece);

		for (int i = 0; i <= blocks_in_piece; ++i)
		{
			if (i == blocks_in_piece || p.blocks[i] == 0)
			{
				if (buffer_size == 0) continue;
			
				TORRENT_ASSERT(buffer_size <= i * m_block_size);
				l.unlock();
				if (iov)
				{
					p.storage->write_impl(iov, p.piece, (std::min)(
						i * m_block_size, piece_size) - buffer_size, iov_counter);
					iov_counter = 0;
				}
				else
				{
					TORRENT_ASSERT(buf);
					file::iovec_t b = { buf.get(), buffer_size };
					p.storage->write_impl(&b, p.piece, (std::min)(
						i * m_block_size, piece_size) - buffer_size, 1);
				}
				l.lock();
				++m_cache_stats.writes;
//				std::cerr << " flushing p: " << p.piece << " bytes: " << buffer_size << std::endl;
				buffer_size = 0;
				offset = 0;
				continue;
			}
			int block_size = (std::min)(piece_size - i * m_block_size, m_block_size);
			TORRENT_ASSERT(offset + block_size <= piece_size);
			TORRENT_ASSERT(offset + block_size > 0);
			if (!buf)
			{
				iov[iov_counter].iov_base = p.blocks[i];
				iov[iov_counter].iov_len = block_size;
				++iov_counter;
			}
			else
			{
				std::memcpy(buf.get() + offset, p.blocks[i], block_size);
				offset += m_block_size;
			}
			buffer_size += block_size;
			TORRENT_ASSERT(p.num_blocks > 0);
			--p.num_blocks;
			++m_cache_stats.blocks_written;
			--m_cache_stats.cache_size;
		}

		for (int i = 0; i < blocks_in_piece; ++i)
		{
			if (p.blocks[i] == 0) continue;
			free_buffer(p.blocks[i]);
			p.blocks[i] = 0;
		}

		TORRENT_ASSERT(buffer_size == 0);
//		std::cerr << " flushing p: " << p.piece << " cached_blocks: " << m_cache_stats.cache_size << std::endl;
#ifdef TORRENT_DEBUG
		for (int i = 0; i < blocks_in_piece; ++i)
			TORRENT_ASSERT(p.blocks[i] == 0);
#endif
	}

	void disk_io_thread::cache_block(disk_io_job& j, mutex_t::scoped_lock& l)
	{
		INVARIANT_CHECK;
		TORRENT_ASSERT(find_cached_piece(m_pieces, j, l) == m_pieces.end());
		cached_piece_entry p;

		int piece_size = j.storage->info()->piece_size(j.piece);
		int blocks_in_piece = (piece_size + m_block_size - 1) / m_block_size;

		p.piece = j.piece;
		p.storage = j.storage;
		p.last_use = time_now();
		p.num_blocks = 1;
		p.blocks.reset(new char*[blocks_in_piece]);
		std::memset(&p.blocks[0], 0, blocks_in_piece * sizeof(char*));
		int block = j.offset / m_block_size;
//		std::cerr << " adding cache entry for p: " << j.piece << " block: " << block << " cached_blocks: " << m_cache_stats.cache_size << std::endl;
		p.blocks[block] = j.buffer;
		++m_cache_stats.cache_size;
		m_pieces.push_back(p);
	}

	enum read_options_t
	{
		ignore_cache_size = 1
	};

	// fills a piece with data from disk, returns the total number of bytes
	// read or -1 if there was an error
	int disk_io_thread::read_into_piece(cached_piece_entry& p, int start_block
		, int options, mutex_t::scoped_lock& l)
	{
		int piece_size = p.storage->info()->piece_size(p.piece);
		int blocks_in_piece = (piece_size + m_block_size - 1) / m_block_size;

		int end_block = start_block;
		for (int i = start_block; i < blocks_in_piece
			&& (m_cache_stats.cache_size < m_settings.cache_size
				|| (options && ignore_cache_size)); ++i)
		{
			// this is a block that is already allocated
			// stop allocating and don't read more than
			// what we've allocated now
			if (p.blocks[i]) break;
			p.blocks[i] = allocate_buffer("read cache");

			// the allocation failed, break
			if (p.blocks[i] == 0) break;
			++p.num_blocks;
			++m_cache_stats.cache_size;
			++m_cache_stats.read_cache_size;
			++end_block;
		}

		if (end_block == start_block) return -2;

		// the buffer_size is the size of the buffer we need to read
		// all these blocks.
		const int buffer_size = (std::min)((end_block - start_block) * m_block_size
			, piece_size - start_block * m_block_size);
		TORRENT_ASSERT(buffer_size <= piece_size);
		TORRENT_ASSERT(buffer_size + start_block * m_block_size <= piece_size);
		boost::scoped_array<char> buf;
		boost::scoped_array<file::iovec_t> iov;
		int iov_counter = 0;
		if (m_settings.coalesce_reads) buf.reset(new (std::nothrow) char[buffer_size]);
		else iov.reset(new file::iovec_t[end_block - start_block]);

		int ret = 0;
		if (buf)
		{
			l.unlock();
			file::iovec_t b = { buf.get(), buffer_size };
			ret = p.storage->read_impl(&b, p.piece, start_block * m_block_size, 1);
			l.lock();
			TORRENT_ASSERT(ret == buffer_size || p.storage->error());
			if (p.storage->error()) { return -1; }
			++m_cache_stats.reads;
		}
		
		int piece_offset = start_block * m_block_size;
		int offset = 0;
		for (int i = start_block; i < end_block; ++i)
		{
			int block_size = (std::min)(piece_size - piece_offset, m_block_size);
			if (p.blocks[i] == 0) break;
			TORRENT_ASSERT(offset <= buffer_size);
			TORRENT_ASSERT(piece_offset <= piece_size);
			TORRENT_ASSERT(offset + block_size <= buffer_size);
			if (buf)
			{
				std::memcpy(p.blocks[i], buf.get() + offset, block_size);
			}
			else
			{
				iov[iov_counter].iov_base = p.blocks[i];
				iov[iov_counter].iov_len = block_size;
				++iov_counter;
			}
			offset += m_block_size;
			piece_offset += m_block_size;
		}

		if (iov)
		{
			l.unlock();
			ret = p.storage->read_impl(iov.get(), p.piece, start_block * m_block_size, iov_counter);
			l.lock();
			TORRENT_ASSERT(ret == buffer_size || p.storage->error());
			if (p.storage->error()) { return -1; }
			++m_cache_stats.reads;
		}

		TORRENT_ASSERT(ret <= buffer_size);
		TORRENT_ASSERT(ret == buffer_size || p.storage->error());
		return (ret != buffer_size) ? -1 : ret;
	}
	
	bool disk_io_thread::make_room(int num_blocks
		, cache_t::iterator ignore
		, mutex_t::scoped_lock& l)
	{
		if (m_settings.cache_size - m_cache_stats.cache_size < num_blocks)
		{
			// there's not enough room in the cache, clear a piece
			// from the read cache
			if (!clear_oldest_read_piece(ignore, l)) return false;
		}

		return m_settings.cache_size - m_cache_stats.cache_size >= num_blocks;
	}

	// returns -1 on read error, -2 on out of memory error or the number of bytes read
	// this function ignores the cache size limit, it will read the entire
	// piece regardless of the offset in j
	int disk_io_thread::cache_read_piece(disk_io_job const& j, mutex_t::scoped_lock& l)
	{
		INVARIANT_CHECK;

		int piece_size = j.storage->info()->piece_size(j.piece);
		int blocks_in_piece = (piece_size + m_block_size - 1) / m_block_size;

		make_room(blocks_in_piece, m_read_pieces.end(), l);

		cached_piece_entry p;
		p.piece = j.piece;
		p.storage = j.storage;
		p.last_use = time_now();
		p.num_blocks = 0;
		p.blocks.reset(new char*[blocks_in_piece]);
		std::memset(&p.blocks[0], 0, blocks_in_piece * sizeof(char*));
		int ret = read_into_piece(p, 0, ignore_cache_size, l);
		
		if (ret == -1)
			free_piece(p, l);
		else
			m_read_pieces.push_back(p);

		return ret;
	}

	// returns -1 on read error, -2 if there isn't any space in the cache
	// or the number of bytes read
	int disk_io_thread::cache_read_block(disk_io_job const& j, mutex_t::scoped_lock& l)
	{
		INVARIANT_CHECK;

		int piece_size = j.storage->info()->piece_size(j.piece);
		int blocks_in_piece = (piece_size + m_block_size - 1) / m_block_size;

		int start_block = j.offset / m_block_size;

		if (!make_room(blocks_in_piece - start_block
			, m_read_pieces.end(), l)) return -2;

		cached_piece_entry p;
		p.piece = j.piece;
		p.storage = j.storage;
		p.last_use = time_now();
		p.num_blocks = 0;
		p.blocks.reset(new char*[blocks_in_piece]);
		std::memset(&p.blocks[0], 0, blocks_in_piece * sizeof(char*));
		int ret = read_into_piece(p, start_block, 0, l);
		
		if (ret == -1)
			free_piece(p, l);
		else
			m_read_pieces.push_back(p);

		return ret;
	}

#ifdef TORRENT_DEBUG
	void disk_io_thread::check_invariant() const
	{
		int cached_write_blocks = 0;
		for (cache_t::const_iterator i = m_pieces.begin()
			, end(m_pieces.end()); i != end; ++i)
		{
			cached_piece_entry const& p = *i;
			TORRENT_ASSERT(p.blocks);
			
			if (!p.storage) continue;
			int piece_size = p.storage->info()->piece_size(p.piece);
			int blocks_in_piece = (piece_size + m_block_size - 1) / m_block_size;
			int blocks = 0;
			for (int k = 0; k < blocks_in_piece; ++k)
			{
				if (p.blocks[k])
				{
#ifndef TORRENT_DISABLE_POOL_ALLOCATOR
					TORRENT_ASSERT(is_disk_buffer(p.blocks[k]));
#endif
					++blocks;
				}
			}
//			TORRENT_ASSERT(blocks == p.num_blocks);
			cached_write_blocks += blocks;
		}
	
		int cached_read_blocks = 0;
		for (cache_t::const_iterator i = m_read_pieces.begin()
			, end(m_read_pieces.end()); i != end; ++i)
		{
			cached_piece_entry const& p = *i;
			TORRENT_ASSERT(p.blocks);
			
			int piece_size = p.storage->info()->piece_size(p.piece);
			int blocks_in_piece = (piece_size + m_block_size - 1) / m_block_size;
			int blocks = 0;
			for (int k = 0; k < blocks_in_piece; ++k)
			{
				if (p.blocks[k])
				{
#ifndef TORRENT_DISABLE_POOL_ALLOCATOR
					TORRENT_ASSERT(is_disk_buffer(p.blocks[k]));
#endif
					++blocks;
				}
			}
//			TORRENT_ASSERT(blocks == p.num_blocks);
			cached_read_blocks += blocks;
		}

		TORRENT_ASSERT(cached_read_blocks + cached_write_blocks == m_cache_stats.cache_size);
		TORRENT_ASSERT(cached_read_blocks == m_cache_stats.read_cache_size);

		// when writing, there may be a one block difference, right before an old piece
		// is flushed
		TORRENT_ASSERT(m_cache_stats.cache_size <= m_settings.cache_size + 1);
	}
#endif

	int disk_io_thread::read_piece_from_cache_and_hash(disk_io_job const& j, sha1_hash& h)
	{
		TORRENT_ASSERT(j.buffer);

		mutex_t::scoped_lock l(m_piece_mutex);
	
		cache_t::iterator p
			= find_cached_piece(m_read_pieces, j, l);

		bool hit = true;
		int ret = 0;

		// if the piece cannot be found in the cache,
		// read the whole piece starting at the block
		// we got a request for.
		if (p == m_read_pieces.end())
		{
			ret = cache_read_piece(j, l);
			hit = false;
			if (ret < 0) return ret;
			p = m_read_pieces.end();
			--p;
			TORRENT_ASSERT(!m_read_pieces.empty());
			TORRENT_ASSERT(p->piece == j.piece);
			TORRENT_ASSERT(p->storage == j.storage);
		}

		hasher ctx;

		int piece_size = j.storage->info()->piece_size(j.piece);
		int blocks_in_piece = (piece_size + m_block_size - 1) / m_block_size;

		for (int i = 0; i < blocks_in_piece; ++i)
		{
			TORRENT_ASSERT(p->blocks[i]);
			ctx.update((char const*)p->blocks[i], (std::min)(piece_size, m_block_size));
			piece_size -= m_block_size;
		}
		h = ctx.final();

		ret = copy_from_piece(p, hit, j, l);
		TORRENT_ASSERT(ret > 0);
		if (ret < 0) return ret;

		// if read cache is disabled or we exceeded the
		// limit, remove this piece from the cache
		if (m_cache_stats.cache_size >= m_settings.cache_size
			|| !m_settings.use_read_cache)
		{
			TORRENT_ASSERT(!m_read_pieces.empty());
			TORRENT_ASSERT(p->piece == j.piece);
			TORRENT_ASSERT(p->storage == j.storage);
			if (p != m_read_pieces.end())
			{
				free_piece(*p, l);
				m_read_pieces.erase(p);
			}
		}

		ret = j.buffer_size;
		++m_cache_stats.blocks_read;
		if (hit) ++m_cache_stats.blocks_read_hit;
		return ret;
	}

	int disk_io_thread::copy_from_piece(cache_t::iterator p, bool& hit
		, disk_io_job const& j, mutex_t::scoped_lock& l)
	{
		TORRENT_ASSERT(j.buffer);

		// copy from the cache and update the last use timestamp
		int block = j.offset / m_block_size;
		int block_offset = j.offset & (m_block_size-1);
		int buffer_offset = 0;
		int size = j.buffer_size;
		if (p->blocks[block] == 0)
		{
			int piece_size = j.storage->info()->piece_size(j.piece);
			int blocks_in_piece = (piece_size + m_block_size - 1) / m_block_size;
			int end_block = block;
			while (end_block < blocks_in_piece && p->blocks[end_block] == 0) ++end_block;
			if (!make_room(end_block - block, p, l)) return -2;
			int ret = read_into_piece(*p, block, 0, l);
			hit = false;
			if (ret < 0) return ret;
			TORRENT_ASSERT(p->blocks[block]);
		}

		p->last_use = time_now();
		while (size > 0)
		{
			TORRENT_ASSERT(p->blocks[block]);
			int to_copy = (std::min)(m_block_size
					- block_offset, size);
			std::memcpy(j.buffer + buffer_offset
					, p->blocks[block] + block_offset
					, to_copy);
			size -= to_copy;
			block_offset = 0;
			buffer_offset += to_copy;
			++block;
		}
		return j.buffer_size;
	}

	int disk_io_thread::try_read_from_cache(disk_io_job const& j)
	{
		TORRENT_ASSERT(j.buffer);

		mutex_t::scoped_lock l(m_piece_mutex);
		if (!m_settings.use_read_cache) return -2;

		cache_t::iterator p
			= find_cached_piece(m_read_pieces, j, l);

		bool hit = true;
		int ret = 0;

		// if the piece cannot be found in the cache,
		// read the whole piece starting at the block
		// we got a request for.
		if (p == m_read_pieces.end())
		{
			ret = cache_read_block(j, l);
			hit = false;
			if (ret < 0) return ret;
			p = m_read_pieces.end();
			--p;
			TORRENT_ASSERT(!m_read_pieces.empty());
			TORRENT_ASSERT(p->piece == j.piece);
			TORRENT_ASSERT(p->storage == j.storage);
		}

		if (p == m_read_pieces.end()) return ret;

		ret = copy_from_piece(p, hit, j, l);
		if (ret < 0) return ret;

		ret = j.buffer_size;
		++m_cache_stats.blocks_read;
		if (hit) ++m_cache_stats.blocks_read_hit;
		return ret;
	}

	void disk_io_thread::add_job(disk_io_job const& j
		, boost::function<void(int, disk_io_job const&)> const& f)
	{
		TORRENT_ASSERT(!j.callback);
		TORRENT_ASSERT(j.storage
			|| j.action == disk_io_job::abort_thread
			|| j.action == disk_io_job::update_settings);
		TORRENT_ASSERT(j.buffer_size <= m_block_size);
		mutex_t::scoped_lock l(m_queue_mutex);

		std::list<disk_io_job>::reverse_iterator i = m_jobs.rbegin();
		if (j.action == disk_io_job::read)
		{
			// when we're reading, we may not skip
			// ahead of any write operation that overlaps
			// the region we're reading
			for (; i != m_jobs.rend(); i++)
			{
				// if *i should come before j, stop
				// and insert j before i
				if (*i < j) break;
				// if we come across a write operation that
				// overlaps the region we're reading, we need
				// to stop
				if (i->action == disk_io_job::write
					&& i->storage == j.storage
					&& i->piece == j.piece
					&& range_overlap(i->offset, i->buffer_size
						, j.offset, j.buffer_size))
					break;
			}
		}
		else if (j.action == disk_io_job::write)
		{
			for (; i != m_jobs.rend(); ++i)
			{
				if (*i < j)
				{
					if (i != m_jobs.rbegin()
						&& i.base()->storage.get() != j.storage.get())
						i = m_jobs.rbegin();
					break;
				}
			}
		}
		
		// if we are placed in front of all other jobs, put it on the back of
		// the queue, to sweep the disk in the same direction, and to avoid
		// starvation. The exception is if the priority is higher than the
		// job at the front of the queue
		if (i == m_jobs.rend() && (m_jobs.empty() || j.priority <= m_jobs.back().priority))
			i = m_jobs.rbegin();

		std::list<disk_io_job>::iterator k = m_jobs.insert(i.base(), j);
		k->callback.swap(const_cast<boost::function<void(int, disk_io_job const&)>&>(f));
		if (j.action == disk_io_job::write)
			m_queue_buffer_size += j.buffer_size;
		m_signal.notify_all();
	}

	bool disk_io_thread::test_error(disk_io_job& j)
	{
		TORRENT_ASSERT(j.storage);
		error_code const& ec = j.storage->error();
		if (ec)
		{
			j.str = ec.message();
			j.error = ec;
			j.error_file = j.storage->error_file();
			j.storage->clear_error();
#ifdef TORRENT_DEBUG
			std::cout << "ERROR: '" << j.str << "' " << j.error_file << std::endl;
#endif
			return true;
		}
		return false;
	}

	void disk_io_thread::post_callback(
		boost::function<void(int, disk_io_job const&)> const& handler
		, disk_io_job const& j, int ret)
	{
		if (!handler) return;

		m_ios.post(bind(handler, ret, j));
	}

	void disk_io_thread::operator()()
	{
		for (;;)
		{
#ifdef TORRENT_DISK_STATS
			m_log << log_time() << " idle" << std::endl;
#endif
			mutex_t::scoped_lock jl(m_queue_mutex);

			while (m_jobs.empty() && !m_abort)
			{
				// if there hasn't been an event in one second
				// see if we should flush the cache
				if (!m_signal.timed_wait(jl, boost::get_system_time() + boost::posix_time::seconds(1)))
					flush_expired_pieces();
			}
<commit_msg>timed_wait does not seem to work as expected, revert to regular wait()<commit_after>/*

Copyright (c) 2007, <NAME>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/storage.hpp"
#include <deque>
#include "libtorrent/disk_io_thread.hpp"
#include "libtorrent/disk_buffer_holder.hpp"
#include "libtorrent/alloca.hpp"
#include "libtorrent/invariant_check.hpp"
#include "libtorrent/error_code.hpp"
#include <boost/scoped_array.hpp>

#ifdef TORRENT_DISK_STATS
#include "libtorrent/time.hpp"
#endif

#if TORRENT_USE_MLOCK && !defined TORRENT_WINDOWS
#include <sys/mman.h>
#endif

namespace libtorrent
{
	disk_buffer_pool::disk_buffer_pool(int block_size)
		: m_block_size(block_size)
#ifndef TORRENT_DISABLE_POOL_ALLOCATOR
		, m_pool(block_size)
#endif
	{
#ifdef TORRENT_STATS
		m_allocations = 0;
#endif
#ifdef TORRENT_DISK_STATS
		m_log.open("disk_buffers.log", std::ios::trunc);
#endif
	}

#ifdef TORRENT_DEBUG
	bool disk_buffer_pool::is_disk_buffer(char* buffer) const
	{
#ifdef TORRENT_DISABLE_POOL_ALLOCATOR
		return true;
#else
		mutex_t::scoped_lock l(m_pool_mutex);
		return m_pool.is_from(buffer);
#endif
	}
#endif

	char* disk_buffer_pool::allocate_buffer(char const* category)
	{
		mutex_t::scoped_lock l(m_pool_mutex);
#ifdef TORRENT_DISABLE_POOL_ALLOCATOR
		char* ret = page_aligned_allocator::malloc(m_block_size);
#else
		char* ret = (char*)m_pool.ordered_malloc();
#endif
#if TORRENT_USE_MLOCK
		if (m_settings.lock_disk_cache)
		{
#ifdef TORRENT_WINDOWS
			VirtualLock(ret, m_block_size);
#else
			mlock(ret, m_block_size);
#endif		
		}
#endif

#ifdef TORRENT_STATS
		++m_allocations;
		++m_categories[category];
		m_buf_to_category[ret] = category;
		m_log << log_time() << " " << category << ": " << m_categories[category] << "\n";
#endif
		return ret;
	}

	void disk_buffer_pool::free_buffer(char* buf)
	{
		TORRENT_ASSERT(buf);
		mutex_t::scoped_lock l(m_pool_mutex);
#ifdef TORRENT_STATS
		--m_allocations;
		TORRENT_ASSERT(m_categories.find(m_buf_to_category[buf])
			!= m_categories.end());
		std::string const& category = m_buf_to_category[buf];
		--m_categories[category];
		m_log << log_time() << " " << category << ": " << m_categories[category] << "\n";
		m_buf_to_category.erase(buf);
#endif
#if TORRENT_USE_MLOCK
		if (m_settings.lock_disk_cache)
		{
#ifdef TORRENT_WINDOWS
			VirtualUnlock(buf, m_block_size);
#else
			munlock(buf, m_block_size);
#endif		
		}
#endif
#ifdef TORRENT_DISABLE_POOL_ALLOCATOR
		page_aligned_allocator::free(buf);
#else
		m_pool.ordered_free(buf);
#endif
	}

	char* disk_buffer_pool::allocate_buffers(int num_blocks, char const* category)
	{
		mutex_t::scoped_lock l(m_pool_mutex);
#ifdef TORRENT_DISABLE_POOL_ALLOCATOR
		char* ret = page_aligned_allocator::malloc(m_block_size * num_blocks);
#else
		char* ret = (char*)m_pool.ordered_malloc(num_blocks);
#endif
#if TORRENT_USE_MLOCK
		if (m_settings.lock_disk_cache)
		{
#ifdef TORRENT_WINDOWS
			VirtualLock(ret, m_block_size * num_blocks);
#else
			mlock(ret, m_block_size * num_blocks);
#endif		
		}
#endif
#ifdef TORRENT_STATS
		m_allocations += num_blocks;
		m_categories[category] += num_blocks;
		m_buf_to_category[ret] = category;
		m_log << log_time() << " " << category << ": " << m_categories[category] << "\n";
#endif
		return ret;
	}

	void disk_buffer_pool::free_buffers(char* buf, int num_blocks)
	{
		TORRENT_ASSERT(buf);
		TORRENT_ASSERT(num_blocks >= 1);
		mutex_t::scoped_lock l(m_pool_mutex);
#ifdef TORRENT_STATS
		m_allocations -= num_blocks;
		TORRENT_ASSERT(m_categories.find(m_buf_to_category[buf])
			!= m_categories.end());
		std::string const& category = m_buf_to_category[buf];
		m_categories[category] -= num_blocks;
		m_log << log_time() << " " << category << ": " << m_categories[category] << "\n";
		m_buf_to_category.erase(buf);
#endif
#if TORRENT_USE_MLOCK
		if (m_settings.lock_disk_cache)
		{
#ifdef TORRENT_WINDOWS
			VirtualUnlock(buf, m_block_size * num_blocks);
#else
			munlock(buf, m_block_size * num_blocks);
#endif		
		}
#endif
#ifdef TORRENT_DISABLE_POOL_ALLOCATOR
		page_aligned_allocator::free(buf);
#else
		m_pool.ordered_free(buf, num_blocks);
#endif
	}

	void disk_buffer_pool::release_memory()
	{
#ifndef TORRENT_DISABLE_POOL_ALLOCATOR
		mutex_t::scoped_lock l(m_pool_mutex);
		m_pool.release_memory();
#endif
	}

// ------- disk_io_thread ------


	disk_io_thread::disk_io_thread(asio::io_service& ios, int block_size)
		: disk_buffer_pool(block_size)
		, m_abort(false)
		, m_queue_buffer_size(0)
		, m_ios(ios)
		, m_disk_io_thread(boost::ref(*this))
	{
#ifdef TORRENT_DISK_STATS
		m_log.open("disk_io_thread.log", std::ios::trunc);
#endif
	}

	disk_io_thread::~disk_io_thread()
	{
		TORRENT_ASSERT(m_abort == true);
	}

	void disk_io_thread::join()
	{
		mutex_t::scoped_lock l(m_queue_mutex);
		disk_io_job j;
		j.action = disk_io_job::abort_thread;
		m_jobs.insert(m_jobs.begin(), j);
		m_signal.notify_all();
		l.unlock();

		m_disk_io_thread.join();
		l.lock();
		TORRENT_ASSERT(m_abort == true);
		m_jobs.clear();
	}

	void disk_io_thread::get_cache_info(sha1_hash const& ih, std::vector<cached_piece_info>& ret) const
	{
		mutex_t::scoped_lock l(m_piece_mutex);
		ret.clear();
		ret.reserve(m_pieces.size());
		for (cache_t::const_iterator i = m_pieces.begin()
			, end(m_pieces.end()); i != end; ++i)
		{
			torrent_info const& ti = *i->storage->info();
			if (ti.info_hash() != ih) continue;
			cached_piece_info info;
			info.piece = i->piece;
			info.last_use = i->last_use;
			info.kind = cached_piece_info::write_cache;
			int blocks_in_piece = (ti.piece_size(i->piece) + (m_block_size) - 1) / m_block_size;
			info.blocks.resize(blocks_in_piece);
			for (int b = 0; b < blocks_in_piece; ++b)
				if (i->blocks[b]) info.blocks[b] = true;
			ret.push_back(info);
		}
		for (cache_t::const_iterator i = m_read_pieces.begin()
			, end(m_read_pieces.end()); i != end; ++i)
		{
			torrent_info const& ti = *i->storage->info();
			if (ti.info_hash() != ih) continue;
			cached_piece_info info;
			info.piece = i->piece;
			info.last_use = i->last_use;
			info.kind = cached_piece_info::read_cache;
			int blocks_in_piece = (ti.piece_size(i->piece) + (m_block_size) - 1) / m_block_size;
			info.blocks.resize(blocks_in_piece);
			for (int b = 0; b < blocks_in_piece; ++b)
				if (i->blocks[b]) info.blocks[b] = true;
			ret.push_back(info);
		}
	}
	
	cache_status disk_io_thread::status() const
	{
		mutex_t::scoped_lock l(m_piece_mutex);
		return m_cache_stats;
	}

	// aborts read operations
	void disk_io_thread::stop(boost::intrusive_ptr<piece_manager> s)
	{
		mutex_t::scoped_lock l(m_queue_mutex);
		// read jobs are aborted, write and move jobs are syncronized
		for (std::list<disk_io_job>::iterator i = m_jobs.begin();
			i != m_jobs.end();)
		{
			if (i->storage != s)
			{
				++i;
				continue;
			}
			if (i->action == disk_io_job::read)
			{
				post_callback(i->callback, *i, -1);
				m_jobs.erase(i++);
				continue;
			}
			if (i->action == disk_io_job::check_files)
			{
				post_callback(i->callback, *i, piece_manager::disk_check_aborted);
				m_jobs.erase(i++);
				continue;
			}
			++i;
		}
		disk_io_job j;
		j.action = disk_io_job::abort_torrent;
		j.storage = s;
		add_job(j);
	}

	bool range_overlap(int start1, int length1, int start2, int length2)
	{
		return (start1 <= start2 && start1 + length1 > start2)
			|| (start2 <= start1 && start2 + length2 > start1);
	}
	
	namespace
	{
		// The semantic of this operator is:
		// should lhs come before rhs in the job queue
		bool operator<(disk_io_job const& lhs, disk_io_job const& rhs)
		{
			// NOTE: comparison inverted to make higher priority
			// skip _in_front_of_ lower priority
			if (lhs.priority > rhs.priority) return true;
			if (lhs.priority < rhs.priority) return false;

			if (lhs.storage.get() < rhs.storage.get()) return true;
			if (lhs.storage.get() > rhs.storage.get()) return false;
			if (lhs.piece < rhs.piece) return true;
			if (lhs.piece > rhs.piece) return false;
			if (lhs.offset < rhs.offset) return true;
//			if (lhs.offset > rhs.offset) return false;
			return false;
		}
	}

	disk_io_thread::cache_t::iterator disk_io_thread::find_cached_piece(
		disk_io_thread::cache_t& cache
		, disk_io_job const& j, mutex_t::scoped_lock& l)
	{
		for (cache_t::iterator i = cache.begin()
			, end(cache.end()); i != end; ++i)
		{
			if (i->storage != j.storage || i->piece != j.piece) continue;
			return i;
		}
		return cache.end();
	}
	
	void disk_io_thread::flush_expired_pieces()
	{
		ptime now = time_now();

		mutex_t::scoped_lock l(m_piece_mutex);

		INVARIANT_CHECK;
		// flush write cache
		for (;;)
		{
			cache_t::iterator i = std::min_element(
				m_pieces.begin(), m_pieces.end()
				, bind(&cached_piece_entry::last_use, _1)
				< bind(&cached_piece_entry::last_use, _2));
			if (i == m_pieces.end()) break;
			int age = total_seconds(now - i->last_use);
			if (age < m_settings.cache_expiry) break;
			flush_and_remove(i, l);
		}

		// flush read cache
		for (;;)
		{
			cache_t::iterator i = std::min_element(
				m_read_pieces.begin(), m_read_pieces.end()
				, bind(&cached_piece_entry::last_use, _1)
				< bind(&cached_piece_entry::last_use, _2));
			if (i == m_read_pieces.end()) break;
			int age = total_seconds(now - i->last_use);
			if (age < m_settings.cache_expiry) break;
			free_piece(*i, l);
			m_read_pieces.erase(i);
		}
	}

	void disk_io_thread::free_piece(cached_piece_entry& p, mutex_t::scoped_lock& l)
	{
		int piece_size = p.storage->info()->piece_size(p.piece);
		int blocks_in_piece = (piece_size + m_block_size - 1) / m_block_size;

		for (int i = 0; i < blocks_in_piece; ++i)
		{
			if (p.blocks[i] == 0) continue;
			free_buffer(p.blocks[i]);
			p.blocks[i] = 0;
			--p.num_blocks;
			--m_cache_stats.cache_size;
			--m_cache_stats.read_cache_size;
		}
	}

	bool disk_io_thread::clear_oldest_read_piece(
		cache_t::iterator ignore
		, mutex_t::scoped_lock& l)
	{
		INVARIANT_CHECK;

		cache_t::iterator i = std::min_element(
			m_read_pieces.begin(), m_read_pieces.end()
			, bind(&cached_piece_entry::last_use, _1)
			< bind(&cached_piece_entry::last_use, _2));
		if (i != m_read_pieces.end() && i != ignore)
		{
			// don't replace an entry that is less than one second old
			if (time_now() - i->last_use < seconds(1)) return false;
			free_piece(*i, l);
			m_read_pieces.erase(i);
			return true;
		}
		return false;
	}

	void disk_io_thread::flush_oldest_piece(mutex_t::scoped_lock& l)
	{
		INVARIANT_CHECK;
		// first look if there are any read cache entries that can
		// be cleared
		if (clear_oldest_read_piece(m_read_pieces.end(), l)) return;

		cache_t::iterator i = std::min_element(
			m_pieces.begin(), m_pieces.end()
			, bind(&cached_piece_entry::last_use, _1)
			< bind(&cached_piece_entry::last_use, _2));
		if (i == m_pieces.end()) return;
		flush_and_remove(i, l);
	}

	void disk_io_thread::flush_and_remove(disk_io_thread::cache_t::iterator e
		, mutex_t::scoped_lock& l)
	{
		flush(e, l);
		m_pieces.erase(e);
	}

	void disk_io_thread::flush(disk_io_thread::cache_t::iterator e
		, mutex_t::scoped_lock& l)
	{
		INVARIANT_CHECK;
		// TODO: copy *e and unlink it before unlocking
		cached_piece_entry& p = *e;
		int piece_size = p.storage->info()->piece_size(p.piece);
#ifdef TORRENT_DISK_STATS
		m_log << log_time() << " flushing " << piece_size << std::endl;
#endif
		TORRENT_ASSERT(piece_size > 0);
		
		int blocks_in_piece = (piece_size + m_block_size - 1) / m_block_size;
		int buffer_size = 0;
		int offset = 0;

		boost::scoped_array<char> buf;
		file::iovec_t* iov = 0;
		int iov_counter = 0;
		if (m_settings.coalesce_writes) buf.reset(new (std::nothrow) char[piece_size]);
		else iov = TORRENT_ALLOCA(file::iovec_t, blocks_in_piece);

		for (int i = 0; i <= blocks_in_piece; ++i)
		{
			if (i == blocks_in_piece || p.blocks[i] == 0)
			{
				if (buffer_size == 0) continue;
			
				TORRENT_ASSERT(buffer_size <= i * m_block_size);
				l.unlock();
				if (iov)
				{
					p.storage->write_impl(iov, p.piece, (std::min)(
						i * m_block_size, piece_size) - buffer_size, iov_counter);
					iov_counter = 0;
				}
				else
				{
					TORRENT_ASSERT(buf);
					file::iovec_t b = { buf.get(), buffer_size };
					p.storage->write_impl(&b, p.piece, (std::min)(
						i * m_block_size, piece_size) - buffer_size, 1);
				}
				l.lock();
				++m_cache_stats.writes;
//				std::cerr << " flushing p: " << p.piece << " bytes: " << buffer_size << std::endl;
				buffer_size = 0;
				offset = 0;
				continue;
			}
			int block_size = (std::min)(piece_size - i * m_block_size, m_block_size);
			TORRENT_ASSERT(offset + block_size <= piece_size);
			TORRENT_ASSERT(offset + block_size > 0);
			if (!buf)
			{
				iov[iov_counter].iov_base = p.blocks[i];
				iov[iov_counter].iov_len = block_size;
				++iov_counter;
			}
			else
			{
				std::memcpy(buf.get() + offset, p.blocks[i], block_size);
				offset += m_block_size;
			}
			buffer_size += block_size;
			TORRENT_ASSERT(p.num_blocks > 0);
			--p.num_blocks;
			++m_cache_stats.blocks_written;
			--m_cache_stats.cache_size;
		}

		for (int i = 0; i < blocks_in_piece; ++i)
		{
			if (p.blocks[i] == 0) continue;
			free_buffer(p.blocks[i]);
			p.blocks[i] = 0;
		}

		TORRENT_ASSERT(buffer_size == 0);
//		std::cerr << " flushing p: " << p.piece << " cached_blocks: " << m_cache_stats.cache_size << std::endl;
#ifdef TORRENT_DEBUG
		for (int i = 0; i < blocks_in_piece; ++i)
			TORRENT_ASSERT(p.blocks[i] == 0);
#endif
	}

	void disk_io_thread::cache_block(disk_io_job& j, mutex_t::scoped_lock& l)
	{
		INVARIANT_CHECK;
		TORRENT_ASSERT(find_cached_piece(m_pieces, j, l) == m_pieces.end());
		cached_piece_entry p;

		int piece_size = j.storage->info()->piece_size(j.piece);
		int blocks_in_piece = (piece_size + m_block_size - 1) / m_block_size;

		p.piece = j.piece;
		p.storage = j.storage;
		p.last_use = time_now();
		p.num_blocks = 1;
		p.blocks.reset(new char*[blocks_in_piece]);
		std::memset(&p.blocks[0], 0, blocks_in_piece * sizeof(char*));
		int block = j.offset / m_block_size;
//		std::cerr << " adding cache entry for p: " << j.piece << " block: " << block << " cached_blocks: " << m_cache_stats.cache_size << std::endl;
		p.blocks[block] = j.buffer;
		++m_cache_stats.cache_size;
		m_pieces.push_back(p);
	}

	enum read_options_t
	{
		ignore_cache_size = 1
	};

	// fills a piece with data from disk, returns the total number of bytes
	// read or -1 if there was an error
	int disk_io_thread::read_into_piece(cached_piece_entry& p, int start_block
		, int options, mutex_t::scoped_lock& l)
	{
		int piece_size = p.storage->info()->piece_size(p.piece);
		int blocks_in_piece = (piece_size + m_block_size - 1) / m_block_size;

		int end_block = start_block;
		for (int i = start_block; i < blocks_in_piece
			&& (m_cache_stats.cache_size < m_settings.cache_size
				|| (options && ignore_cache_size)); ++i)
		{
			// this is a block that is already allocated
			// stop allocating and don't read more than
			// what we've allocated now
			if (p.blocks[i]) break;
			p.blocks[i] = allocate_buffer("read cache");

			// the allocation failed, break
			if (p.blocks[i] == 0) break;
			++p.num_blocks;
			++m_cache_stats.cache_size;
			++m_cache_stats.read_cache_size;
			++end_block;
		}

		if (end_block == start_block) return -2;

		// the buffer_size is the size of the buffer we need to read
		// all these blocks.
		const int buffer_size = (std::min)((end_block - start_block) * m_block_size
			, piece_size - start_block * m_block_size);
		TORRENT_ASSERT(buffer_size <= piece_size);
		TORRENT_ASSERT(buffer_size + start_block * m_block_size <= piece_size);
		boost::scoped_array<char> buf;
		boost::scoped_array<file::iovec_t> iov;
		int iov_counter = 0;
		if (m_settings.coalesce_reads) buf.reset(new (std::nothrow) char[buffer_size]);
		else iov.reset(new file::iovec_t[end_block - start_block]);

		int ret = 0;
		if (buf)
		{
			l.unlock();
			file::iovec_t b = { buf.get(), buffer_size };
			ret = p.storage->read_impl(&b, p.piece, start_block * m_block_size, 1);
			l.lock();
			TORRENT_ASSERT(ret == buffer_size || p.storage->error());
			if (p.storage->error()) { return -1; }
			++m_cache_stats.reads;
		}
		
		int piece_offset = start_block * m_block_size;
		int offset = 0;
		for (int i = start_block; i < end_block; ++i)
		{
			int block_size = (std::min)(piece_size - piece_offset, m_block_size);
			if (p.blocks[i] == 0) break;
			TORRENT_ASSERT(offset <= buffer_size);
			TORRENT_ASSERT(piece_offset <= piece_size);
			TORRENT_ASSERT(offset + block_size <= buffer_size);
			if (buf)
			{
				std::memcpy(p.blocks[i], buf.get() + offset, block_size);
			}
			else
			{
				iov[iov_counter].iov_base = p.blocks[i];
				iov[iov_counter].iov_len = block_size;
				++iov_counter;
			}
			offset += m_block_size;
			piece_offset += m_block_size;
		}

		if (iov)
		{
			l.unlock();
			ret = p.storage->read_impl(iov.get(), p.piece, start_block * m_block_size, iov_counter);
			l.lock();
			TORRENT_ASSERT(ret == buffer_size || p.storage->error());
			if (p.storage->error()) { return -1; }
			++m_cache_stats.reads;
		}

		TORRENT_ASSERT(ret <= buffer_size);
		TORRENT_ASSERT(ret == buffer_size || p.storage->error());
		return (ret != buffer_size) ? -1 : ret;
	}
	
	bool disk_io_thread::make_room(int num_blocks
		, cache_t::iterator ignore
		, mutex_t::scoped_lock& l)
	{
		if (m_settings.cache_size - m_cache_stats.cache_size < num_blocks)
		{
			// there's not enough room in the cache, clear a piece
			// from the read cache
			if (!clear_oldest_read_piece(ignore, l)) return false;
		}

		return m_settings.cache_size - m_cache_stats.cache_size >= num_blocks;
	}

	// returns -1 on read error, -2 on out of memory error or the number of bytes read
	// this function ignores the cache size limit, it will read the entire
	// piece regardless of the offset in j
	int disk_io_thread::cache_read_piece(disk_io_job const& j, mutex_t::scoped_lock& l)
	{
		INVARIANT_CHECK;

		int piece_size = j.storage->info()->piece_size(j.piece);
		int blocks_in_piece = (piece_size + m_block_size - 1) / m_block_size;

		make_room(blocks_in_piece, m_read_pieces.end(), l);

		cached_piece_entry p;
		p.piece = j.piece;
		p.storage = j.storage;
		p.last_use = time_now();
		p.num_blocks = 0;
		p.blocks.reset(new char*[blocks_in_piece]);
		std::memset(&p.blocks[0], 0, blocks_in_piece * sizeof(char*));
		int ret = read_into_piece(p, 0, ignore_cache_size, l);
		
		if (ret == -1)
			free_piece(p, l);
		else
			m_read_pieces.push_back(p);

		return ret;
	}

	// returns -1 on read error, -2 if there isn't any space in the cache
	// or the number of bytes read
	int disk_io_thread::cache_read_block(disk_io_job const& j, mutex_t::scoped_lock& l)
	{
		INVARIANT_CHECK;

		int piece_size = j.storage->info()->piece_size(j.piece);
		int blocks_in_piece = (piece_size + m_block_size - 1) / m_block_size;

		int start_block = j.offset / m_block_size;

		if (!make_room(blocks_in_piece - start_block
			, m_read_pieces.end(), l)) return -2;

		cached_piece_entry p;
		p.piece = j.piece;
		p.storage = j.storage;
		p.last_use = time_now();
		p.num_blocks = 0;
		p.blocks.reset(new char*[blocks_in_piece]);
		std::memset(&p.blocks[0], 0, blocks_in_piece * sizeof(char*));
		int ret = read_into_piece(p, start_block, 0, l);
		
		if (ret == -1)
			free_piece(p, l);
		else
			m_read_pieces.push_back(p);

		return ret;
	}

#ifdef TORRENT_DEBUG
	void disk_io_thread::check_invariant() const
	{
		int cached_write_blocks = 0;
		for (cache_t::const_iterator i = m_pieces.begin()
			, end(m_pieces.end()); i != end; ++i)
		{
			cached_piece_entry const& p = *i;
			TORRENT_ASSERT(p.blocks);
			
			if (!p.storage) continue;
			int piece_size = p.storage->info()->piece_size(p.piece);
			int blocks_in_piece = (piece_size + m_block_size - 1) / m_block_size;
			int blocks = 0;
			for (int k = 0; k < blocks_in_piece; ++k)
			{
				if (p.blocks[k])
				{
#ifndef TORRENT_DISABLE_POOL_ALLOCATOR
					TORRENT_ASSERT(is_disk_buffer(p.blocks[k]));
#endif
					++blocks;
				}
			}
//			TORRENT_ASSERT(blocks == p.num_blocks);
			cached_write_blocks += blocks;
		}
	
		int cached_read_blocks = 0;
		for (cache_t::const_iterator i = m_read_pieces.begin()
			, end(m_read_pieces.end()); i != end; ++i)
		{
			cached_piece_entry const& p = *i;
			TORRENT_ASSERT(p.blocks);
			
			int piece_size = p.storage->info()->piece_size(p.piece);
			int blocks_in_piece = (piece_size + m_block_size - 1) / m_block_size;
			int blocks = 0;
			for (int k = 0; k < blocks_in_piece; ++k)
			{
				if (p.blocks[k])
				{
#ifndef TORRENT_DISABLE_POOL_ALLOCATOR
					TORRENT_ASSERT(is_disk_buffer(p.blocks[k]));
#endif
					++blocks;
				}
			}
//			TORRENT_ASSERT(blocks == p.num_blocks);
			cached_read_blocks += blocks;
		}

		TORRENT_ASSERT(cached_read_blocks + cached_write_blocks == m_cache_stats.cache_size);
		TORRENT_ASSERT(cached_read_blocks == m_cache_stats.read_cache_size);

		// when writing, there may be a one block difference, right before an old piece
		// is flushed
		TORRENT_ASSERT(m_cache_stats.cache_size <= m_settings.cache_size + 1);
	}
#endif

	int disk_io_thread::read_piece_from_cache_and_hash(disk_io_job const& j, sha1_hash& h)
	{
		TORRENT_ASSERT(j.buffer);

		mutex_t::scoped_lock l(m_piece_mutex);
	
		cache_t::iterator p
			= find_cached_piece(m_read_pieces, j, l);

		bool hit = true;
		int ret = 0;

		// if the piece cannot be found in the cache,
		// read the whole piece starting at the block
		// we got a request for.
		if (p == m_read_pieces.end())
		{
			ret = cache_read_piece(j, l);
			hit = false;
			if (ret < 0) return ret;
			p = m_read_pieces.end();
			--p;
			TORRENT_ASSERT(!m_read_pieces.empty());
			TORRENT_ASSERT(p->piece == j.piece);
			TORRENT_ASSERT(p->storage == j.storage);
		}

		hasher ctx;

		int piece_size = j.storage->info()->piece_size(j.piece);
		int blocks_in_piece = (piece_size + m_block_size - 1) / m_block_size;

		for (int i = 0; i < blocks_in_piece; ++i)
		{
			TORRENT_ASSERT(p->blocks[i]);
			ctx.update((char const*)p->blocks[i], (std::min)(piece_size, m_block_size));
			piece_size -= m_block_size;
		}
		h = ctx.final();

		ret = copy_from_piece(p, hit, j, l);
		TORRENT_ASSERT(ret > 0);
		if (ret < 0) return ret;

		// if read cache is disabled or we exceeded the
		// limit, remove this piece from the cache
		if (m_cache_stats.cache_size >= m_settings.cache_size
			|| !m_settings.use_read_cache)
		{
			TORRENT_ASSERT(!m_read_pieces.empty());
			TORRENT_ASSERT(p->piece == j.piece);
			TORRENT_ASSERT(p->storage == j.storage);
			if (p != m_read_pieces.end())
			{
				free_piece(*p, l);
				m_read_pieces.erase(p);
			}
		}

		ret = j.buffer_size;
		++m_cache_stats.blocks_read;
		if (hit) ++m_cache_stats.blocks_read_hit;
		return ret;
	}

	int disk_io_thread::copy_from_piece(cache_t::iterator p, bool& hit
		, disk_io_job const& j, mutex_t::scoped_lock& l)
	{
		TORRENT_ASSERT(j.buffer);

		// copy from the cache and update the last use timestamp
		int block = j.offset / m_block_size;
		int block_offset = j.offset & (m_block_size-1);
		int buffer_offset = 0;
		int size = j.buffer_size;
		if (p->blocks[block] == 0)
		{
			int piece_size = j.storage->info()->piece_size(j.piece);
			int blocks_in_piece = (piece_size + m_block_size - 1) / m_block_size;
			int end_block = block;
			while (end_block < blocks_in_piece && p->blocks[end_block] == 0) ++end_block;
			if (!make_room(end_block - block, p, l)) return -2;
			int ret = read_into_piece(*p, block, 0, l);
			hit = false;
			if (ret < 0) return ret;
			TORRENT_ASSERT(p->blocks[block]);
		}

		p->last_use = time_now();
		while (size > 0)
		{
			TORRENT_ASSERT(p->blocks[block]);
			int to_copy = (std::min)(m_block_size
					- block_offset, size);
			std::memcpy(j.buffer + buffer_offset
					, p->blocks[block] + block_offset
					, to_copy);
			size -= to_copy;
			block_offset = 0;
			buffer_offset += to_copy;
			++block;
		}
		return j.buffer_size;
	}

	int disk_io_thread::try_read_from_cache(disk_io_job const& j)
	{
		TORRENT_ASSERT(j.buffer);

		mutex_t::scoped_lock l(m_piece_mutex);
		if (!m_settings.use_read_cache) return -2;

		cache_t::iterator p
			= find_cached_piece(m_read_pieces, j, l);

		bool hit = true;
		int ret = 0;

		// if the piece cannot be found in the cache,
		// read the whole piece starting at the block
		// we got a request for.
		if (p == m_read_pieces.end())
		{
			ret = cache_read_block(j, l);
			hit = false;
			if (ret < 0) return ret;
			p = m_read_pieces.end();
			--p;
			TORRENT_ASSERT(!m_read_pieces.empty());
			TORRENT_ASSERT(p->piece == j.piece);
			TORRENT_ASSERT(p->storage == j.storage);
		}

		if (p == m_read_pieces.end()) return ret;

		ret = copy_from_piece(p, hit, j, l);
		if (ret < 0) return ret;

		ret = j.buffer_size;
		++m_cache_stats.blocks_read;
		if (hit) ++m_cache_stats.blocks_read_hit;
		return ret;
	}

	void disk_io_thread::add_job(disk_io_job const& j
		, boost::function<void(int, disk_io_job const&)> const& f)
	{
		TORRENT_ASSERT(!j.callback);
		TORRENT_ASSERT(j.storage
			|| j.action == disk_io_job::abort_thread
			|| j.action == disk_io_job::update_settings);
		TORRENT_ASSERT(j.buffer_size <= m_block_size);
		mutex_t::scoped_lock l(m_queue_mutex);

		std::list<disk_io_job>::reverse_iterator i = m_jobs.rbegin();
		if (j.action == disk_io_job::read)
		{
			// when we're reading, we may not skip
			// ahead of any write operation that overlaps
			// the region we're reading
			for (; i != m_jobs.rend(); i++)
			{
				// if *i should come before j, stop
				// and insert j before i
				if (*i < j) break;
				// if we come across a write operation that
				// overlaps the region we're reading, we need
				// to stop
				if (i->action == disk_io_job::write
					&& i->storage == j.storage
					&& i->piece == j.piece
					&& range_overlap(i->offset, i->buffer_size
						, j.offset, j.buffer_size))
					break;
			}
		}
		else if (j.action == disk_io_job::write)
		{
			for (; i != m_jobs.rend(); ++i)
			{
				if (*i < j)
				{
					if (i != m_jobs.rbegin()
						&& i.base()->storage.get() != j.storage.get())
						i = m_jobs.rbegin();
					break;
				}
			}
		}
		
		// if we are placed in front of all other jobs, put it on the back of
		// the queue, to sweep the disk in the same direction, and to avoid
		// starvation. The exception is if the priority is higher than the
		// job at the front of the queue
		if (i == m_jobs.rend() && (m_jobs.empty() || j.priority <= m_jobs.back().priority))
			i = m_jobs.rbegin();

		std::list<disk_io_job>::iterator k = m_jobs.insert(i.base(), j);
		k->callback.swap(const_cast<boost::function<void(int, disk_io_job const&)>&>(f));
		if (j.action == disk_io_job::write)
			m_queue_buffer_size += j.buffer_size;
		m_signal.notify_all();
	}

	bool disk_io_thread::test_error(disk_io_job& j)
	{
		TORRENT_ASSERT(j.storage);
		error_code const& ec = j.storage->error();
		if (ec)
		{
			j.str = ec.message();
			j.error = ec;
			j.error_file = j.storage->error_file();
			j.storage->clear_error();
#ifdef TORRENT_DEBUG
			std::cout << "ERROR: '" << j.str << "' " << j.error_file << std::endl;
#endif
			return true;
		}
		return false;
	}

	void disk_io_thread::post_callback(
		boost::function<void(int, disk_io_job const&)> const& handler
		, disk_io_job const& j, int ret)
	{
		if (!handler) return;

		m_ios.post(bind(handler, ret, j));
	}

	void disk_io_thread::operator()()
	{
		for (;;)
		{
#ifdef TORRENT_DISK_STATS
			m_log << log_time() << " idle" << std::endl;
#endif
			mutex_t::scoped_lock jl(m_queue_mutex);

			while (m_jobs.empty() && !m_abort)
			{
				// if there hasn't been an event in one second
				// see if we should flush the cache
//				if (!m_signal.timed_wait(jl, boost::posix_time::seconds(1)))
//					flush_expired_pieces();
				m_signal.wait(jl);
			}

{'fraction_non_alphanumeric': 0.13926591965955695, 'fraction_numerical': 0.0043241759184583966, 'mean_word_length': 3.8997814023877586, 'pattern_counts': {'":': 8, '<': 339, '<?xml version=': 0, '>': 213, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4516794', 'n_tokens_mistral': 25077, 'n_tokens_neox': 22105, 'n_words': 4771}