DefaultPieceStorage.cc 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2006 Tatsuhiro Tsujikawa
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * In addition, as a special exception, the copyright holders give
  22. * permission to link the code of portions of this program with the
  23. * OpenSSL library under certain conditions as described in each
  24. * individual source file, and distribute linked combinations
  25. * including the two.
  26. * You must obey the GNU General Public License in all respects
  27. * for all of the code used other than OpenSSL. If you modify
  28. * file(s) with this exception, you may extend this exception to your
  29. * version of the file(s), but you are not obligated to do so. If you
  30. * do not wish to do so, delete this exception statement from your
  31. * version. If you delete this exception statement from all source
  32. * files in the program, then also delete it here.
  33. */
  34. /* copyright --> */
  35. #include "DefaultPieceStorage.h"
  36. #include <numeric>
  37. #include <algorithm>
  38. #include "DownloadContext.h"
  39. #include "Piece.h"
  40. #include "Peer.h"
  41. #include "LogFactory.h"
  42. #include "Logger.h"
  43. #include "prefs.h"
  44. #include "DirectDiskAdaptor.h"
  45. #include "MultiDiskAdaptor.h"
  46. #include "DiskWriter.h"
  47. #include "BitfieldMan.h"
  48. #include "message.h"
  49. #include "DefaultDiskWriterFactory.h"
  50. #include "FileEntry.h"
  51. #include "DlAbortEx.h"
  52. #include "util.h"
  53. #include "a2functional.h"
  54. #include "Option.h"
  55. #include "StringFormat.h"
  56. #include "RarestPieceSelector.h"
  57. #include "array_fun.h"
  58. #include "PieceStatMan.h"
  59. #include "wallclock.h"
  60. #ifdef ENABLE_BITTORRENT
  61. # include "bittorrent_helper.h"
  62. #endif // ENABLE_BITTORRENT
  63. namespace aria2 {
  64. DefaultPieceStorage::DefaultPieceStorage
  65. (const SharedHandle<DownloadContext>& downloadContext, const Option* option):
  66. downloadContext_(downloadContext),
  67. bitfieldMan_(new BitfieldMan(downloadContext->getPieceLength(),
  68. downloadContext->getTotalLength())),
  69. diskWriterFactory_(new DefaultDiskWriterFactory()),
  70. endGamePieceNum_(END_GAME_PIECE_NUM),
  71. logger_(LogFactory::getInstance()),
  72. option_(option),
  73. pieceStatMan_(new PieceStatMan(downloadContext->getNumPieces(), true)),
  74. pieceSelector_(new RarestPieceSelector(pieceStatMan_))
  75. {}
  76. DefaultPieceStorage::~DefaultPieceStorage() {
  77. delete bitfieldMan_;
  78. }
  79. bool DefaultPieceStorage::isEndGame()
  80. {
  81. return bitfieldMan_->countMissingBlock() <= endGamePieceNum_;
  82. }
  83. bool DefaultPieceStorage::getMissingPieceIndex(size_t& index,
  84. const unsigned char* bitfield,
  85. size_t length)
  86. {
  87. const size_t mislen = bitfieldMan_->getBitfieldLength();
  88. array_ptr<unsigned char> misbitfield(new unsigned char[mislen]);
  89. bool r;
  90. if(isEndGame()) {
  91. r = bitfieldMan_->getAllMissingIndexes(misbitfield, mislen,
  92. bitfield, length);
  93. } else {
  94. r = bitfieldMan_->getAllMissingUnusedIndexes(misbitfield, mislen,
  95. bitfield, length);
  96. }
  97. if(r) {
  98. // We assume indexes is sorted using comparator less.
  99. return
  100. pieceSelector_->select(index, misbitfield,bitfieldMan_->countBlock());
  101. } else {
  102. return false;
  103. }
  104. }
  105. SharedHandle<Piece> DefaultPieceStorage::checkOutPiece(size_t index)
  106. {
  107. bitfieldMan_->setUseBit(index);
  108. SharedHandle<Piece> piece = findUsedPiece(index);
  109. if(piece.isNull()) {
  110. piece.reset(new Piece(index, bitfieldMan_->getBlockLength(index)));
  111. #ifdef ENABLE_MESSAGE_DIGEST
  112. piece->setHashAlgo(downloadContext_->getPieceHashAlgo());
  113. #endif // ENABLE_MESSAGE_DIGEST
  114. addUsedPiece(piece);
  115. return piece;
  116. } else {
  117. return piece;
  118. }
  119. }
  120. /**
  121. * Newly instantiated piece is not added to usedPieces.
  122. * Because it is waste of memory and there is no chance to use them later.
  123. */
  124. SharedHandle<Piece> DefaultPieceStorage::getPiece(size_t index)
  125. {
  126. SharedHandle<Piece> piece;
  127. if(0 <= index && index <= bitfieldMan_->getMaxIndex()) {
  128. piece = findUsedPiece(index);
  129. if(piece.isNull()) {
  130. piece.reset(new Piece(index, bitfieldMan_->getBlockLength(index)));
  131. if(hasPiece(index)) {
  132. piece->setAllBlock();
  133. }
  134. }
  135. }
  136. return piece;
  137. }
  138. void DefaultPieceStorage::addUsedPiece(const SharedHandle<Piece>& piece)
  139. {
  140. std::deque<SharedHandle<Piece> >::iterator i =
  141. std::lower_bound(usedPieces_.begin(), usedPieces_.end(), piece);
  142. usedPieces_.insert(i, piece);
  143. if(logger_->debug()) {
  144. logger_->debug("usedPieces_.size()=%lu",
  145. static_cast<unsigned long>(usedPieces_.size()));
  146. }
  147. }
  148. SharedHandle<Piece> DefaultPieceStorage::findUsedPiece(size_t index) const
  149. {
  150. SharedHandle<Piece> p(new Piece());
  151. p->setIndex(index);
  152. std::deque<SharedHandle<Piece> >::const_iterator i =
  153. std::lower_bound(usedPieces_.begin(), usedPieces_.end(), p);
  154. if(i != usedPieces_.end() && (*i) == p) {
  155. return *i;
  156. } else {
  157. p.reset(0);
  158. return p;
  159. }
  160. }
  161. SharedHandle<Piece> DefaultPieceStorage::getMissingPiece
  162. (const unsigned char* bitfield, size_t length)
  163. {
  164. size_t index;
  165. if(getMissingPieceIndex(index, bitfield, length)) {
  166. return checkOutPiece(index);
  167. } else {
  168. return SharedHandle<Piece>();
  169. }
  170. }
  171. SharedHandle<Piece> DefaultPieceStorage::getMissingPiece
  172. (const BitfieldMan& bitfield)
  173. {
  174. return getMissingPiece(bitfield.getBitfield(), bitfield.getBitfieldLength());
  175. }
  176. #ifdef ENABLE_BITTORRENT
  177. bool DefaultPieceStorage::hasMissingPiece(const SharedHandle<Peer>& peer)
  178. {
  179. return bitfieldMan_->hasMissingPiece(peer->getBitfield(),
  180. peer->getBitfieldLength());
  181. }
  182. SharedHandle<Piece>
  183. DefaultPieceStorage::getMissingPiece(const SharedHandle<Peer>& peer)
  184. {
  185. return getMissingPiece(peer->getBitfield(), peer->getBitfieldLength());
  186. }
  187. void DefaultPieceStorage::createFastIndexBitfield
  188. (BitfieldMan& bitfield, const SharedHandle<Peer>& peer)
  189. {
  190. for(std::vector<size_t>::const_iterator itr =
  191. peer->getPeerAllowedIndexSet().begin(),
  192. eoi = peer->getPeerAllowedIndexSet().end(); itr != eoi; ++itr) {
  193. if(!bitfieldMan_->isBitSet(*itr) && peer->hasPiece(*itr)) {
  194. bitfield.setBit(*itr);
  195. }
  196. }
  197. }
  198. SharedHandle<Piece> DefaultPieceStorage::getMissingFastPiece
  199. (const SharedHandle<Peer>& peer)
  200. {
  201. if(peer->isFastExtensionEnabled() && peer->countPeerAllowedIndexSet() > 0) {
  202. BitfieldMan tempBitfield(bitfieldMan_->getBlockLength(),
  203. bitfieldMan_->getTotalLength());
  204. createFastIndexBitfield(tempBitfield, peer);
  205. return getMissingPiece(tempBitfield);
  206. } else {
  207. return SharedHandle<Piece>();
  208. }
  209. }
  210. static void unsetExcludedIndexes(BitfieldMan& bitfield,
  211. const std::vector<size_t>& excludedIndexes)
  212. {
  213. std::for_each(excludedIndexes.begin(), excludedIndexes.end(),
  214. std::bind1st(std::mem_fun(&BitfieldMan::unsetBit), &bitfield));
  215. }
  216. SharedHandle<Piece> DefaultPieceStorage::getMissingPiece
  217. (const SharedHandle<Peer>& peer, const std::vector<size_t>& excludedIndexes)
  218. {
  219. BitfieldMan tempBitfield(bitfieldMan_->getBlockLength(),
  220. bitfieldMan_->getTotalLength());
  221. tempBitfield.setBitfield(peer->getBitfield(), peer->getBitfieldLength());
  222. unsetExcludedIndexes(tempBitfield, excludedIndexes);
  223. return getMissingPiece(tempBitfield);
  224. }
  225. SharedHandle<Piece> DefaultPieceStorage::getMissingFastPiece
  226. (const SharedHandle<Peer>& peer, const std::vector<size_t>& excludedIndexes)
  227. {
  228. if(peer->isFastExtensionEnabled() && peer->countPeerAllowedIndexSet() > 0) {
  229. BitfieldMan tempBitfield(bitfieldMan_->getBlockLength(),
  230. bitfieldMan_->getTotalLength());
  231. createFastIndexBitfield(tempBitfield, peer);
  232. unsetExcludedIndexes(tempBitfield, excludedIndexes);
  233. return getMissingPiece(tempBitfield);
  234. } else {
  235. return SharedHandle<Piece>();
  236. }
  237. }
  238. #endif // ENABLE_BITTORRENT
  239. bool DefaultPieceStorage::hasMissingUnusedPiece()
  240. {
  241. size_t index;
  242. return bitfieldMan_->getFirstMissingUnusedIndex(index);
  243. }
  244. SharedHandle<Piece> DefaultPieceStorage::getSparseMissingUnusedPiece
  245. (size_t minSplitSize, const unsigned char* ignoreBitfield, size_t length)
  246. {
  247. size_t index;
  248. if(bitfieldMan_->getSparseMissingUnusedIndex
  249. (index, minSplitSize, ignoreBitfield, length)) {
  250. return checkOutPiece(index);
  251. } else {
  252. return SharedHandle<Piece>();
  253. }
  254. }
  255. SharedHandle<Piece> DefaultPieceStorage::getMissingPiece(size_t index)
  256. {
  257. if(hasPiece(index) || isPieceUsed(index)) {
  258. return SharedHandle<Piece>();
  259. } else {
  260. return checkOutPiece(index);
  261. }
  262. }
  263. void DefaultPieceStorage::deleteUsedPiece(const SharedHandle<Piece>& piece)
  264. {
  265. if(piece.isNull()) {
  266. return;
  267. }
  268. std::deque<SharedHandle<Piece> >::iterator i =
  269. std::lower_bound(usedPieces_.begin(), usedPieces_.end(), piece);
  270. if(i != usedPieces_.end() && (*i) == piece) {
  271. usedPieces_.erase(i);
  272. }
  273. }
  274. // void DefaultPieceStorage::reduceUsedPieces(size_t upperBound)
  275. // {
  276. // size_t usedPiecesSize = usedPieces.size();
  277. // if(usedPiecesSize <= upperBound) {
  278. // return;
  279. // }
  280. // size_t delNum = usedPiecesSize-upperBound;
  281. // int fillRate = 10;
  282. // while(delNum && fillRate <= 15) {
  283. // delNum -= deleteUsedPiecesByFillRate(fillRate, delNum);
  284. // fillRate += 5;
  285. // }
  286. // }
  287. // size_t DefaultPieceStorage::deleteUsedPiecesByFillRate(int fillRate,
  288. // size_t delNum)
  289. // {
  290. // size_t deleted = 0;
  291. // for(Pieces::iterator itr = usedPieces.begin();
  292. // itr != usedPieces.end() && deleted < delNum;) {
  293. // SharedHandle<Piece>& piece = *itr;
  294. // if(!bitfieldMan->isUseBitSet(piece->getIndex()) &&
  295. // piece->countCompleteBlock() <= piece->countBlock()*(fillRate/100.0)) {
  296. // logger->info(MSG_DELETING_USED_PIECE,
  297. // piece->getIndex(),
  298. // (piece->countCompleteBlock()*100)/piece->countBlock(),
  299. // fillRate);
  300. // itr = usedPieces.erase(itr);
  301. // ++deleted;
  302. // } else {
  303. // ++itr;
  304. // }
  305. // }
  306. // return deleted;
  307. // }
  308. void DefaultPieceStorage::completePiece(const SharedHandle<Piece>& piece)
  309. {
  310. if(piece.isNull()) {
  311. return;
  312. }
  313. deleteUsedPiece(piece);
  314. // if(!isEndGame()) {
  315. // reduceUsedPieces(100);
  316. // }
  317. if(allDownloadFinished()) {
  318. return;
  319. }
  320. bitfieldMan_->setBit(piece->getIndex());
  321. bitfieldMan_->unsetUseBit(piece->getIndex());
  322. addPieceStats(piece->getIndex());
  323. if(downloadFinished()) {
  324. downloadContext_->resetDownloadStopTime();
  325. if(isSelectiveDownloadingMode()) {
  326. logger_->notice(MSG_SELECTIVE_DOWNLOAD_COMPLETED);
  327. // following line was commented out in order to stop sending request
  328. // message after user-specified files were downloaded.
  329. //finishSelectiveDownloadingMode();
  330. } else {
  331. logger_->info(MSG_DOWNLOAD_COMPLETED);
  332. }
  333. #ifdef ENABLE_BITTORRENT
  334. if(downloadContext_->hasAttribute(bittorrent::BITTORRENT)) {
  335. SharedHandle<TorrentAttribute> torrentAttrs =
  336. bittorrent::getTorrentAttrs(downloadContext_);
  337. if(!torrentAttrs->metadata.empty()) {
  338. util::executeHookByOptName(downloadContext_->getOwnerRequestGroup(),
  339. option_, PREF_ON_BT_DOWNLOAD_COMPLETE);
  340. }
  341. }
  342. #endif // ENABLE_BITTORRENT
  343. }
  344. }
  345. bool DefaultPieceStorage::isSelectiveDownloadingMode()
  346. {
  347. return bitfieldMan_->isFilterEnabled();
  348. }
  349. // not unittested
  350. void DefaultPieceStorage::cancelPiece(const SharedHandle<Piece>& piece)
  351. {
  352. if(piece.isNull()) {
  353. return;
  354. }
  355. bitfieldMan_->unsetUseBit(piece->getIndex());
  356. if(!isEndGame()) {
  357. if(piece->getCompletedLength() == 0) {
  358. deleteUsedPiece(piece);
  359. }
  360. }
  361. }
  362. bool DefaultPieceStorage::hasPiece(size_t index)
  363. {
  364. return bitfieldMan_->isBitSet(index);
  365. }
  366. bool DefaultPieceStorage::isPieceUsed(size_t index)
  367. {
  368. return bitfieldMan_->isUseBitSet(index);
  369. }
  370. uint64_t DefaultPieceStorage::getTotalLength()
  371. {
  372. return bitfieldMan_->getTotalLength();
  373. }
  374. uint64_t DefaultPieceStorage::getFilteredTotalLength()
  375. {
  376. return bitfieldMan_->getFilteredTotalLength();
  377. }
  378. uint64_t DefaultPieceStorage::getCompletedLength()
  379. {
  380. uint64_t completedLength =
  381. bitfieldMan_->getCompletedLength()+getInFlightPieceCompletedLength();
  382. uint64_t totalLength = getTotalLength();
  383. if(completedLength > totalLength) {
  384. completedLength = totalLength;
  385. }
  386. return completedLength;
  387. }
  388. uint64_t DefaultPieceStorage::getFilteredCompletedLength()
  389. {
  390. return bitfieldMan_->getFilteredCompletedLength()+
  391. getInFlightPieceCompletedLength();
  392. }
  393. size_t DefaultPieceStorage::getInFlightPieceCompletedLength() const
  394. {
  395. return std::accumulate(usedPieces_.begin(), usedPieces_.end(),
  396. 0, adopt2nd(std::plus<size_t>(),
  397. mem_fun_sh(&Piece::getCompletedLength)));
  398. }
  399. // not unittested
  400. void DefaultPieceStorage::setupFileFilter()
  401. {
  402. const std::vector<SharedHandle<FileEntry> >& fileEntries =
  403. downloadContext_->getFileEntries();
  404. bool allSelected = true;
  405. for(std::vector<SharedHandle<FileEntry> >::const_iterator i =
  406. fileEntries.begin(), eoi = fileEntries.end();
  407. i != eoi; ++i) {
  408. if(!(*i)->isRequested()) {
  409. allSelected = false;
  410. break;
  411. }
  412. }
  413. if(allSelected) {
  414. return;
  415. }
  416. for(std::vector<SharedHandle<FileEntry> >::const_iterator i =
  417. fileEntries.begin(), eoi = fileEntries.end(); i != eoi; ++i) {
  418. if((*i)->isRequested()) {
  419. bitfieldMan_->addFilter((*i)->getOffset(), (*i)->getLength());
  420. }
  421. }
  422. bitfieldMan_->enableFilter();
  423. }
  424. // not unittested
  425. void DefaultPieceStorage::clearFileFilter()
  426. {
  427. bitfieldMan_->clearFilter();
  428. }
  429. // not unittested
  430. bool DefaultPieceStorage::downloadFinished()
  431. {
  432. // TODO iterate all requested FileEntry and Call
  433. // bitfieldMan->isBitSetOffsetRange()
  434. return bitfieldMan_->isFilteredAllBitSet();
  435. }
  436. // not unittested
  437. bool DefaultPieceStorage::allDownloadFinished()
  438. {
  439. return bitfieldMan_->isAllBitSet();
  440. }
  441. // not unittested
  442. void DefaultPieceStorage::initStorage()
  443. {
  444. if(downloadContext_->getFileEntries().size() == 1) {
  445. if(logger_->debug()) {
  446. logger_->debug("Instantiating DirectDiskAdaptor");
  447. }
  448. DirectDiskAdaptorHandle directDiskAdaptor(new DirectDiskAdaptor());
  449. directDiskAdaptor->setTotalLength(downloadContext_->getTotalLength());
  450. directDiskAdaptor->setFileEntries
  451. (downloadContext_->getFileEntries().begin(),
  452. downloadContext_->getFileEntries().end());
  453. DiskWriterHandle writer =
  454. diskWriterFactory_->newDiskWriter(directDiskAdaptor->getFilePath());
  455. if(option_->getAsBool(PREF_ENABLE_DIRECT_IO)) {
  456. writer->allowDirectIO();
  457. }
  458. directDiskAdaptor->setDiskWriter(writer);
  459. diskAdaptor_ = directDiskAdaptor;
  460. } else {
  461. if(logger_->debug()) {
  462. logger_->debug("Instantiating MultiDiskAdaptor");
  463. }
  464. MultiDiskAdaptorHandle multiDiskAdaptor(new MultiDiskAdaptor());
  465. multiDiskAdaptor->setFileEntries(downloadContext_->getFileEntries().begin(),
  466. downloadContext_->getFileEntries().end());
  467. if(option_->getAsBool(PREF_ENABLE_DIRECT_IO)) {
  468. multiDiskAdaptor->allowDirectIO();
  469. }
  470. multiDiskAdaptor->setPieceLength(downloadContext_->getPieceLength());
  471. multiDiskAdaptor->setMaxOpenFiles
  472. (option_->getAsInt(PREF_BT_MAX_OPEN_FILES));
  473. diskAdaptor_ = multiDiskAdaptor;
  474. }
  475. if(option_->get(PREF_FILE_ALLOCATION) == V_FALLOC) {
  476. diskAdaptor_->enableFallocate();
  477. }
  478. }
  479. void DefaultPieceStorage::setBitfield(const unsigned char* bitfield,
  480. size_t bitfieldLength)
  481. {
  482. bitfieldMan_->setBitfield(bitfield, bitfieldLength);
  483. addPieceStats(bitfield, bitfieldLength);
  484. }
  485. size_t DefaultPieceStorage::getBitfieldLength()
  486. {
  487. return bitfieldMan_->getBitfieldLength();
  488. }
  489. const unsigned char* DefaultPieceStorage::getBitfield()
  490. {
  491. return bitfieldMan_->getBitfield();
  492. }
  493. DiskAdaptorHandle DefaultPieceStorage::getDiskAdaptor() {
  494. return diskAdaptor_;
  495. }
  496. size_t DefaultPieceStorage::getPieceLength(size_t index)
  497. {
  498. return bitfieldMan_->getBlockLength(index);
  499. }
  500. void DefaultPieceStorage::advertisePiece(cuid_t cuid, size_t index)
  501. {
  502. HaveEntry entry(cuid, index, global::wallclock);
  503. haves_.push_front(entry);
  504. }
  505. void
  506. DefaultPieceStorage::getAdvertisedPieceIndexes(std::vector<size_t>& indexes,
  507. cuid_t myCuid,
  508. const Timer& lastCheckTime)
  509. {
  510. for(std::deque<HaveEntry>::const_iterator itr = haves_.begin(),
  511. eoi = haves_.end(); itr != eoi; ++itr) {
  512. const HaveEntry& have = *itr;
  513. if(have.getCuid() == myCuid) {
  514. continue;
  515. }
  516. if(lastCheckTime > have.getRegisteredTime()) {
  517. break;
  518. }
  519. indexes.push_back(have.getIndex());
  520. }
  521. }
  522. class FindElapsedHave
  523. {
  524. private:
  525. time_t elapsed;
  526. public:
  527. FindElapsedHave(time_t elapsed):elapsed(elapsed) {}
  528. bool operator()(const HaveEntry& have) {
  529. if(have.getRegisteredTime().difference(global::wallclock) >= elapsed) {
  530. return true;
  531. } else {
  532. return false;
  533. }
  534. }
  535. };
  536. void DefaultPieceStorage::removeAdvertisedPiece(time_t elapsed)
  537. {
  538. std::deque<HaveEntry>::iterator itr =
  539. std::find_if(haves_.begin(), haves_.end(), FindElapsedHave(elapsed));
  540. if(itr != haves_.end()) {
  541. if(logger_->debug()) {
  542. logger_->debug(MSG_REMOVED_HAVE_ENTRY, haves_.end()-itr);
  543. }
  544. haves_.erase(itr, haves_.end());
  545. }
  546. }
  547. void DefaultPieceStorage::markAllPiecesDone()
  548. {
  549. bitfieldMan_->setAllBit();
  550. }
  551. void DefaultPieceStorage::markPiecesDone(uint64_t length)
  552. {
  553. if(length == bitfieldMan_->getTotalLength()) {
  554. bitfieldMan_->setAllBit();
  555. } else if(length == 0) {
  556. // TODO this would go to markAllPiecesUndone()
  557. bitfieldMan_->clearAllBit();
  558. usedPieces_.clear();
  559. } else {
  560. size_t numPiece = length/bitfieldMan_->getBlockLength();
  561. if(numPiece > 0) {
  562. bitfieldMan_->setBitRange(0, numPiece-1);
  563. }
  564. size_t r = (length%bitfieldMan_->getBlockLength())/Piece::BLOCK_LENGTH;
  565. if(r > 0) {
  566. SharedHandle<Piece> p
  567. (new Piece(numPiece, bitfieldMan_->getBlockLength(numPiece)));
  568. for(size_t i = 0; i < r; ++i) {
  569. p->completeBlock(i);
  570. }
  571. #ifdef ENABLE_MESSAGE_DIGEST
  572. p->setHashAlgo(downloadContext_->getPieceHashAlgo());
  573. #endif // ENABLE_MESSAGE_DIGEST
  574. addUsedPiece(p);
  575. }
  576. }
  577. }
  578. void DefaultPieceStorage::markPieceMissing(size_t index)
  579. {
  580. bitfieldMan_->unsetBit(index);
  581. }
  582. void DefaultPieceStorage::addInFlightPiece
  583. (const std::vector<SharedHandle<Piece> >& pieces)
  584. {
  585. usedPieces_.insert(usedPieces_.end(), pieces.begin(), pieces.end());
  586. std::sort(usedPieces_.begin(), usedPieces_.end());
  587. }
  588. size_t DefaultPieceStorage::countInFlightPiece()
  589. {
  590. return usedPieces_.size();
  591. }
  592. void DefaultPieceStorage::getInFlightPieces
  593. (std::vector<SharedHandle<Piece> >& pieces)
  594. {
  595. pieces.insert(pieces.end(), usedPieces_.begin(), usedPieces_.end());
  596. }
  597. void DefaultPieceStorage::setDiskWriterFactory
  598. (const DiskWriterFactoryHandle& diskWriterFactory)
  599. {
  600. diskWriterFactory_ = diskWriterFactory;
  601. }
  602. void DefaultPieceStorage::addPieceStats(const unsigned char* bitfield,
  603. size_t bitfieldLength)
  604. {
  605. pieceStatMan_->addPieceStats(bitfield, bitfieldLength);
  606. }
  607. void DefaultPieceStorage::subtractPieceStats(const unsigned char* bitfield,
  608. size_t bitfieldLength)
  609. {
  610. pieceStatMan_->subtractPieceStats(bitfield, bitfieldLength);
  611. }
  612. void DefaultPieceStorage::updatePieceStats(const unsigned char* newBitfield,
  613. size_t newBitfieldLength,
  614. const unsigned char* oldBitfield)
  615. {
  616. pieceStatMan_->updatePieceStats(newBitfield, newBitfieldLength,
  617. oldBitfield);
  618. }
  619. void DefaultPieceStorage::addPieceStats(size_t index)
  620. {
  621. pieceStatMan_->addPieceStats(index);
  622. }
  623. size_t DefaultPieceStorage::getNextUsedIndex(size_t index)
  624. {
  625. for(size_t i = index+1; i < bitfieldMan_->countBlock(); ++i) {
  626. if(bitfieldMan_->isUseBitSet(i) || bitfieldMan_->isBitSet(i)) {
  627. return i;
  628. }
  629. }
  630. return bitfieldMan_->countBlock();
  631. }
  632. } // namespace aria2