Upstream tarball 9574
[amule.git] / src / UploadBandwidthThrottler.cpp
blob2d327ab08f522fe0e2280cd30bb5d95a8ad54b8e
1 //
2 // This file is part of the aMule Project.
3 //
4 // Copyright (c) 2005-2008 aMule Team ( admin@amule.org / http://www.amule.org )
5 // Copyright (c) 2002-2008 Merkur ( devs@emule-project.net / http://www.emule-project.net )
6 //
7 // Any parts of this program derived from the xMule, lMule or eMule project,
8 // or contributed by third-party developers are copyrighted by their
9 // respective authors.
11 // This program is free software; you can redistribute it and/or modify
12 // it under the terms of the GNU General Public License as published by
13 // the Free Software Foundation; either version 2 of the License, or
14 // (at your option) any later version.
16 // This program is distributed in the hope that it will be useful,
17 // but WITHOUT ANY WARRANTY; without even the implied warranty of
18 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 // GNU General Public License for more details.
20 //
21 // You should have received a copy of the GNU General Public License
22 // along with this program; if not, write to the Free Software
23 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26 #include "UploadBandwidthThrottler.h"
28 #include <protocol/ed2k/Constants.h>
29 #include <common/Macros.h>
30 #include <common/Constants.h>
32 #include <cmath>
33 #include <limits> // Do_not_auto_remove (NetBSD)
34 #include "OtherFunctions.h"
35 #include "ThrottledSocket.h"
36 #include "Logger.h"
37 #include "Preferences.h"
38 #include "Statistics.h"
40 #ifndef _MSC_VER
42 #ifdef _UI64_MAX
43 #undef _UI64_MAX
44 #endif
46 #ifdef _I64_MAX
47 #undef _I64_MAX
48 #endif
50 const uint32 _UI32_MAX = std::numeric_limits<uint32>::max();
51 const sint32 _I32_MAX = std::numeric_limits<sint32>::max();
52 const uint64 _UI64_MAX = std::numeric_limits<uint64>::max();
53 const sint64 _I64_MAX = std::numeric_limits<sint64>::max();
55 #endif
57 /////////////////////////////////////
60 /**
61 * The constructor starts the thread.
63 UploadBandwidthThrottler::UploadBandwidthThrottler()
64 : wxThread( wxTHREAD_JOINABLE )
66 m_SentBytesSinceLastCall = 0;
67 m_SentBytesSinceLastCallOverhead = 0;
69 m_doRun = true;
71 Create();
72 Run();
76 /**
77 * The destructor stops the thread. If the thread has already stoppped, destructor does nothing.
79 UploadBandwidthThrottler::~UploadBandwidthThrottler()
81 EndThread();
85 /**
86 * Find out how many bytes that has been put on the sockets since the last call to this
87 * method. Includes overhead of control packets.
89 * @return the number of bytes that has been put on the sockets since the last call
91 uint64 UploadBandwidthThrottler::GetNumberOfSentBytesSinceLastCallAndReset()
93 wxMutexLocker lock( m_sendLocker );
95 uint64 numberOfSentBytesSinceLastCall = m_SentBytesSinceLastCall;
96 m_SentBytesSinceLastCall = 0;
98 return numberOfSentBytesSinceLastCall;
102 * Find out how many bytes that has been put on the sockets since the last call to this
103 * method. Excludes overhead of control packets.
105 * @return the number of bytes that has been put on the sockets since the last call
107 uint64 UploadBandwidthThrottler::GetNumberOfSentBytesOverheadSinceLastCallAndReset()
109 wxMutexLocker lock( m_sendLocker );
111 uint64 numberOfSentBytesSinceLastCall = m_SentBytesSinceLastCallOverhead;
112 m_SentBytesSinceLastCallOverhead = 0;
114 return numberOfSentBytesSinceLastCall;
119 * Add a socket to the list of sockets that have upload slots. The main thread will
120 * continously call send on these sockets, to give them chance to work off their queues.
121 * The sockets are called in the order they exist in the list, so the top socket (index 0)
122 * will be given a chance first to use bandwidth, and then the next socket (index 1) etc.
124 * It is possible to add a socket several times to the list without removing it inbetween,
125 * but that should be avoided.
127 * @param index insert the socket at this place in the list. An index that is higher than the
128 * current number of sockets in the list will mean that the socket should be inserted
129 * last in the list.
131 * @param socket the address to the socket that should be added to the list. If the address is NULL,
132 * this method will do nothing.
134 void UploadBandwidthThrottler::AddToStandardList(uint32 index, ThrottledFileSocket* socket)
136 if ( socket ) {
137 wxMutexLocker lock( m_sendLocker );
139 RemoveFromStandardListNoLock(socket);
140 if (index > (uint32)m_StandardOrder_list.size()) {
141 index = m_StandardOrder_list.size();
144 m_StandardOrder_list.insert(m_StandardOrder_list.begin() + index, socket);
150 * Remove a socket from the list of sockets that have upload slots.
152 * If the socket has mistakenly been added several times to the list, this method
153 * will return all of the entries for the socket.
155 * @param socket the address of the socket that should be removed from the list. If this socket
156 * does not exist in the list, this method will do nothing.
158 bool UploadBandwidthThrottler::RemoveFromStandardList(ThrottledFileSocket* socket)
160 wxMutexLocker lock( m_sendLocker );
162 return RemoveFromStandardListNoLock(socket);
167 * Remove a socket from the list of sockets that have upload slots. NOT THREADSAFE!
168 * This is an internal method that doesn't take the necessary lock before it removes
169 * the socket. This method should only be called when the current thread already owns
170 * the m_sendLocker lock!
172 * @param socket address of the socket that should be removed from the list. If this socket
173 * does not exist in the list, this method will do nothing.
175 bool UploadBandwidthThrottler::RemoveFromStandardListNoLock(ThrottledFileSocket* socket)
177 return (EraseFirstValue( m_StandardOrder_list, socket ) > 0);
182 * Notifies the send thread that it should try to call controlpacket send
183 * for the supplied socket. It is allowed to call this method several times
184 * for the same socket, without having controlpacket send called for the socket
185 * first. The doublette entries are never filtered, since it is incurs less cpu
186 * overhead to simply call Send() in the socket for each double. Send() will
187 * already have done its work when the second Send() is called, and will just
188 * return with little cpu overhead.
190 * @param socket address to the socket that requests to have controlpacket send
191 * to be called on it
193 void UploadBandwidthThrottler::QueueForSendingControlPacket(ThrottledControlSocket* socket, bool hasSent)
195 // Get critical section
196 wxMutexLocker lock( m_tempQueueLocker );
198 if ( m_doRun ) {
199 if( hasSent ) {
200 m_TempControlQueueFirst_list.push_back(socket);
201 } else {
202 m_TempControlQueue_list.push_back(socket);
210 * Remove the socket from all lists and queues. This will make it safe to
211 * erase/delete the socket. It will also cause the main thread to stop calling
212 * send() for the socket.
214 * @param socket address to the socket that should be removed
216 void UploadBandwidthThrottler::DoRemoveFromAllQueues(ThrottledControlSocket* socket)
218 if ( m_doRun ) {
219 // Remove this socket from control packet queue
220 EraseValue( m_ControlQueue_list, socket );
221 EraseValue( m_ControlQueueFirst_list, socket );
223 wxMutexLocker lock( m_tempQueueLocker );
224 EraseValue( m_TempControlQueue_list, socket );
225 EraseValue( m_TempControlQueueFirst_list, socket );
230 void UploadBandwidthThrottler::RemoveFromAllQueues(ThrottledControlSocket* socket)
232 wxMutexLocker lock( m_sendLocker );
234 DoRemoveFromAllQueues( socket );
238 void UploadBandwidthThrottler::RemoveFromAllQueues(ThrottledFileSocket* socket)
240 wxMutexLocker lock( m_sendLocker );
242 if (m_doRun) {
243 DoRemoveFromAllQueues(socket);
245 // And remove it from upload slots
246 RemoveFromStandardListNoLock(socket);
252 * Make the thread exit. This method will not return until the thread has stopped
253 * looping. This guarantees that the thread will not access the CEMSockets after this
254 * call has exited.
256 void UploadBandwidthThrottler::EndThread()
258 if (m_doRun) { // do it only once
260 wxMutexLocker lock(m_sendLocker);
262 // signal the thread to stop looping and exit.
263 m_doRun = false;
266 Wait();
272 * The thread method that handles calling send for the individual sockets.
274 * Control packets will always be tried to be sent first. If there is any bandwidth leftover
275 * after that, send() for the upload slot sockets will be called in priority order until we have run
276 * out of available bandwidth for this loop. Upload slots will not be allowed to go without having sent
277 * called for more than a defined amount of time (i.e. two seconds).
279 * @return always returns 0.
281 void* UploadBandwidthThrottler::Entry()
283 const uint32 TIME_BETWEEN_UPLOAD_LOOPS = 1;
285 uint32 lastLoopTick = ::GetTickCountFullRes();
286 sint64 realBytesToSpend = 0;
287 uint32 allowedDataRate = 0;
288 uint32 rememberedSlotCounter = 0;
289 uint32 extraSleepTime = TIME_BETWEEN_UPLOAD_LOOPS;
291 while (m_doRun) {
292 uint32 timeSinceLastLoop = ::GetTickCountFullRes() - lastLoopTick;
294 // Get current speed from UploadSpeedSense
295 if (thePrefs::GetMaxUpload() == UNLIMITED) {
296 // Try to increase the upload rate
297 allowedDataRate = (uint32)theStats::GetUploadRate() + 5 * 1024;
298 } else {
299 allowedDataRate = thePrefs::GetMaxUpload() * 1024;
302 uint32 minFragSize = 1300;
303 uint32 doubleSendSize = minFragSize*2; // send two packages at a time so they can share an ACK
304 if (allowedDataRate < 6*1024) {
305 minFragSize = 536;
306 doubleSendSize = minFragSize; // don't send two packages at a time at very low speeds to give them a smoother load
310 uint32 sleepTime;
311 if(allowedDataRate == 0 || allowedDataRate == _UI32_MAX || realBytesToSpend >= 1000) {
312 // we could send at once, but sleep a while to not suck up all cpu
313 sleepTime = extraSleepTime;
314 } else {
315 // sleep for just as long as we need to get back to having one byte to send
316 sleepTime = std::max((uint32)ceil((double)(-realBytesToSpend + 1000)/allowedDataRate), extraSleepTime);
319 if(timeSinceLastLoop < sleepTime) {
320 Sleep(sleepTime-timeSinceLastLoop);
323 const uint32 thisLoopTick = ::GetTickCountFullRes();
324 timeSinceLastLoop = thisLoopTick - lastLoopTick;
326 // Calculate how many bytes we can spend
327 sint64 bytesToSpend = 0;
329 if(allowedDataRate != 0 && allowedDataRate != _UI32_MAX) {
330 // prevent overflow
331 if(timeSinceLastLoop == 0) {
332 // no time has passed, so don't add any bytes. Shouldn't happen.
333 bytesToSpend = 0; //realBytesToSpend/1000;
334 } else if(_I64_MAX/timeSinceLastLoop > allowedDataRate && _I64_MAX-allowedDataRate*timeSinceLastLoop > realBytesToSpend) {
335 if(timeSinceLastLoop > sleepTime + 2000) {
336 AddDebugLogLineM(false, logGeneral, wxString::Format(wxT("UploadBandwidthThrottler: Time since last loop too long. time: %ims wanted: %ims Max: %ims"), timeSinceLastLoop, sleepTime, sleepTime + 2000));
338 timeSinceLastLoop = sleepTime + 2000;
339 lastLoopTick = thisLoopTick - timeSinceLastLoop;
342 realBytesToSpend += allowedDataRate*timeSinceLastLoop;
344 bytesToSpend = realBytesToSpend/1000;
345 } else {
346 realBytesToSpend = _I64_MAX;
347 bytesToSpend = _I32_MAX;
349 } else {
350 realBytesToSpend = 0; //_I64_MAX;
351 bytesToSpend = _I32_MAX;
354 lastLoopTick = thisLoopTick;
356 if(bytesToSpend >= 1) {
357 uint64 spentBytes = 0;
358 uint64 spentOverhead = 0;
360 wxMutexLocker sendLock(m_sendLocker);
363 wxMutexLocker queueLock(m_tempQueueLocker);
365 // are there any sockets in m_TempControlQueue_list? Move them to normal m_ControlQueue_list;
366 m_ControlQueueFirst_list.insert( m_ControlQueueFirst_list.end(),
367 m_TempControlQueueFirst_list.begin(),
368 m_TempControlQueueFirst_list.end() );
370 m_ControlQueue_list.insert( m_ControlQueue_list.end(),
371 m_TempControlQueue_list.begin(),
372 m_TempControlQueue_list.end() );
374 m_TempControlQueue_list.clear();
375 m_TempControlQueueFirst_list.clear();
378 // Send any queued up control packets first
379 while(bytesToSpend > 0 && spentBytes < (uint64)bytesToSpend && (!m_ControlQueueFirst_list.empty() || !m_ControlQueue_list.empty())) {
380 ThrottledControlSocket* socket = NULL;
382 if(!m_ControlQueueFirst_list.empty()) {
383 socket = m_ControlQueueFirst_list.front();
384 m_ControlQueueFirst_list.pop_front();
385 } else if(!m_ControlQueue_list.empty()) {
386 socket = m_ControlQueue_list.front();
387 m_ControlQueue_list.pop_front();
390 if(socket != NULL) {
391 SocketSentBytes socketSentBytes = socket->SendControlData(bytesToSpend-spentBytes, minFragSize);
392 uint32 lastSpentBytes = socketSentBytes.sentBytesControlPackets + socketSentBytes.sentBytesStandardPackets;
393 spentBytes += lastSpentBytes;
394 spentOverhead += socketSentBytes.sentBytesControlPackets;
398 // Check if any sockets haven't gotten data for a long time. Then trickle them a package.
399 for ( uint32 slotCounter = 0; slotCounter < m_StandardOrder_list.size(); slotCounter++) {
400 ThrottledFileSocket* socket = m_StandardOrder_list[ slotCounter ];
402 if(socket != NULL) {
403 if(thisLoopTick-socket->GetLastCalledSend() > SEC2MS(1)) {
404 // trickle
405 uint32 neededBytes = socket->GetNeededBytes();
407 if(neededBytes > 0) {
408 SocketSentBytes socketSentBytes = socket->SendFileAndControlData(neededBytes, minFragSize);
409 uint32 lastSpentBytes = socketSentBytes.sentBytesControlPackets + socketSentBytes.sentBytesStandardPackets;
410 spentBytes += lastSpentBytes;
411 spentOverhead += socketSentBytes.sentBytesControlPackets;
414 } else {
415 AddDebugLogLineM(false, logGeneral, wxString::Format( wxT("There was a NULL socket in the UploadBandwidthThrottler Standard list (trickle)! Prevented usage. Index: %i Size: %i"), slotCounter, m_StandardOrder_list.size()) );
419 // Equal bandwidth for all slots
420 uint32 maxSlot = m_StandardOrder_list.size();
421 if(maxSlot > 0 && allowedDataRate/maxSlot < UPLOAD_CLIENT_DATARATE) {
422 maxSlot = allowedDataRate/UPLOAD_CLIENT_DATARATE;
425 for(uint32 maxCounter = 0; maxCounter < std::min(maxSlot, (uint32)m_StandardOrder_list.size()) && bytesToSpend > 0 && spentBytes < (uint64)bytesToSpend; maxCounter++) {
426 if(rememberedSlotCounter >= m_StandardOrder_list.size() ||
427 rememberedSlotCounter >= maxSlot) {
428 rememberedSlotCounter = 0;
431 ThrottledFileSocket* socket = m_StandardOrder_list[ rememberedSlotCounter ];
433 if(socket != NULL) {
434 SocketSentBytes socketSentBytes = socket->SendFileAndControlData(std::min(doubleSendSize, (uint32)(bytesToSpend-spentBytes)), doubleSendSize);
435 uint32 lastSpentBytes = socketSentBytes.sentBytesControlPackets + socketSentBytes.sentBytesStandardPackets;
437 spentBytes += lastSpentBytes;
438 spentOverhead += socketSentBytes.sentBytesControlPackets;
439 } else {
440 AddDebugLogLineM(false, logGeneral, wxString::Format( wxT("There was a NULL socket in the UploadBandwidthThrottler Standard list (equal-for-all)! Prevented usage. Index: %i Size: %i"), rememberedSlotCounter, m_StandardOrder_list.size()));
443 rememberedSlotCounter++;
446 // Any bandwidth that hasn't been used yet are used first to last.
447 for(uint32 slotCounter = 0; slotCounter < m_StandardOrder_list.size() && bytesToSpend > 0 && spentBytes < (uint64)bytesToSpend; slotCounter++) {
448 ThrottledFileSocket* socket = m_StandardOrder_list[ slotCounter ];
450 if(socket != NULL) {
451 uint32 bytesToSpendTemp = bytesToSpend-spentBytes;
452 SocketSentBytes socketSentBytes = socket->SendFileAndControlData(bytesToSpendTemp, doubleSendSize);
453 uint32 lastSpentBytes = socketSentBytes.sentBytesControlPackets + socketSentBytes.sentBytesStandardPackets;
454 spentBytes += lastSpentBytes;
455 spentOverhead += socketSentBytes.sentBytesControlPackets;
456 } else {
457 AddDebugLogLineM( false, logGeneral, wxString::Format( wxT("There was a NULL socket in the UploadBandwidthThrottler Standard list (fully activated)! Prevented usage. Index: %i Size: %i"), slotCounter, m_StandardOrder_list.size()));
460 realBytesToSpend -= spentBytes*1000;
462 if(realBytesToSpend < -(((sint64)m_StandardOrder_list.size()+1)*minFragSize)*1000) {
463 sint64 newRealBytesToSpend = -(((sint64)m_StandardOrder_list.size()+1)*minFragSize)*1000;
465 realBytesToSpend = newRealBytesToSpend;
466 } else {
467 uint64 bandwidthSavedTolerance = m_StandardOrder_list.size()*512*1000;
468 if(realBytesToSpend > 0 && (uint64)realBytesToSpend > 999+bandwidthSavedTolerance) {
469 sint64 newRealBytesToSpend = 999+bandwidthSavedTolerance;
470 realBytesToSpend = newRealBytesToSpend;
474 m_SentBytesSinceLastCall += spentBytes;
475 m_SentBytesSinceLastCallOverhead += spentOverhead;
477 if ((spentBytes == 0) && (spentOverhead == 0)) {
478 extraSleepTime = std::min<uint32>(extraSleepTime * 5, 1000); // 1s at most
479 } else {
480 extraSleepTime = TIME_BETWEEN_UPLOAD_LOOPS;
486 wxMutexLocker queueLock(m_tempQueueLocker);
487 m_TempControlQueue_list.clear();
488 m_TempControlQueueFirst_list.clear();
491 wxMutexLocker sendLock(m_sendLocker);
492 m_ControlQueue_list.clear();
493 m_StandardOrder_list.clear();
495 return 0;
497 // File_checked_for_headers