DefaultPieceStorage.cc 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  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 "fmt.h"
  56. #include "RarestPieceSelector.h"
  57. #include "DefaultStreamPieceSelector.h"
  58. #include "InorderStreamPieceSelector.h"
  59. #include "RandomStreamPieceSelector.h"
  60. #include "GeomStreamPieceSelector.h"
  61. #include "array_fun.h"
  62. #include "PieceStatMan.h"
  63. #include "wallclock.h"
  64. #include "bitfield.h"
  65. #include "SingletonHolder.h"
  66. #include "Notifier.h"
  67. #include "WrDiskCache.h"
  68. #include "RequestGroup.h"
  69. #include "SimpleRandomizer.h"
  70. #ifdef ENABLE_BITTORRENT
  71. #include "bittorrent_helper.h"
  72. #endif // ENABLE_BITTORRENT
  73. namespace aria2 {
  74. DefaultPieceStorage::DefaultPieceStorage(
  75. const std::shared_ptr<DownloadContext>& downloadContext,
  76. const Option* option)
  77. : downloadContext_(downloadContext),
  78. bitfieldMan_(make_unique<BitfieldMan>(downloadContext->getPieceLength(),
  79. downloadContext->getTotalLength())),
  80. diskWriterFactory_(std::make_shared<DefaultDiskWriterFactory>()),
  81. endGame_(false),
  82. endGamePieceNum_(END_GAME_PIECE_NUM),
  83. option_(option),
  84. // The DefaultBtInteractive has the default value of
  85. // lastHaveIndex of 0, so we need to make nextHaveIndex_ more
  86. // than that.
  87. nextHaveIndex_(1),
  88. pieceStatMan_(std::make_shared<PieceStatMan>(
  89. downloadContext->getNumPieces(), true)),
  90. pieceSelector_(make_unique<RarestPieceSelector>(pieceStatMan_)),
  91. wrDiskCache_(nullptr)
  92. {
  93. const std::string& pieceSelectorOpt =
  94. option_->get(PREF_STREAM_PIECE_SELECTOR);
  95. if (pieceSelectorOpt.empty() || pieceSelectorOpt == A2_V_DEFAULT) {
  96. streamPieceSelector_ =
  97. make_unique<DefaultStreamPieceSelector>(bitfieldMan_.get());
  98. }
  99. else if (pieceSelectorOpt == V_INORDER) {
  100. streamPieceSelector_ =
  101. make_unique<InorderStreamPieceSelector>(bitfieldMan_.get());
  102. }
  103. else if (pieceSelectorOpt == A2_V_RANDOM) {
  104. streamPieceSelector_ =
  105. make_unique<RandomStreamPieceSelector>(bitfieldMan_.get());
  106. }
  107. else if (pieceSelectorOpt == A2_V_GEOM) {
  108. streamPieceSelector_ =
  109. make_unique<GeomStreamPieceSelector>(bitfieldMan_.get(), 1.5);
  110. }
  111. }
  112. DefaultPieceStorage::~DefaultPieceStorage() = default;
  113. std::shared_ptr<Piece> DefaultPieceStorage::checkOutPiece(size_t index,
  114. cuid_t cuid)
  115. {
  116. assert(!bitfieldMan_->isFilterEnabled() ||
  117. bitfieldMan_->isFilterBitSet(index));
  118. bitfieldMan_->setUseBit(index);
  119. std::shared_ptr<Piece> piece = findUsedPiece(index);
  120. if (!piece) {
  121. piece = std::make_shared<Piece>(index, bitfieldMan_->getBlockLength(index));
  122. piece->setHashType(downloadContext_->getPieceHashType());
  123. addUsedPiece(piece);
  124. }
  125. piece->addUser(cuid);
  126. RequestGroup* group = downloadContext_->getOwnerRequestGroup();
  127. if ((!group || !group->inMemoryDownload()) && wrDiskCache_ &&
  128. !piece->getWrDiskCacheEntry()) {
  129. // So, we rely on the fact that diskAdaptor_ is not reinitialized
  130. // in the session.
  131. piece->initWrCache(wrDiskCache_, diskAdaptor_);
  132. }
  133. return piece;
  134. }
  135. /**
  136. * Newly instantiated piece is not added to usedPieces.
  137. * Because it is waste of memory and there is no chance to use them later.
  138. */
  139. std::shared_ptr<Piece> DefaultPieceStorage::getPiece(size_t index)
  140. {
  141. std::shared_ptr<Piece> piece;
  142. if (index <= bitfieldMan_->getMaxIndex()) {
  143. piece = findUsedPiece(index);
  144. if (!piece) {
  145. piece =
  146. std::make_shared<Piece>(index, bitfieldMan_->getBlockLength(index));
  147. if (hasPiece(index)) {
  148. piece->setAllBlock();
  149. }
  150. }
  151. }
  152. return piece;
  153. }
  154. void DefaultPieceStorage::addUsedPiece(const std::shared_ptr<Piece>& piece)
  155. {
  156. usedPieces_.insert(piece);
  157. A2_LOG_DEBUG(fmt("usedPieces_.size()=%lu",
  158. static_cast<unsigned long>(usedPieces_.size())));
  159. }
  160. std::shared_ptr<Piece> DefaultPieceStorage::findUsedPiece(size_t index) const
  161. {
  162. auto p = std::make_shared<Piece>();
  163. p->setIndex(index);
  164. auto i = usedPieces_.find(p);
  165. if (i == usedPieces_.end()) {
  166. p.reset();
  167. return p;
  168. }
  169. else {
  170. return *i;
  171. }
  172. }
  173. #ifdef ENABLE_BITTORRENT
  174. bool DefaultPieceStorage::hasMissingPiece(const std::shared_ptr<Peer>& peer)
  175. {
  176. return bitfieldMan_->hasMissingPiece(peer->getBitfield(),
  177. peer->getBitfieldLength());
  178. }
  179. void DefaultPieceStorage::getMissingPiece(
  180. std::vector<std::shared_ptr<Piece>>& pieces, size_t minMissingBlocks,
  181. const unsigned char* bitfield, size_t length, cuid_t cuid)
  182. {
  183. const size_t mislen = bitfieldMan_->getBitfieldLength();
  184. auto misbitfield = make_unique<unsigned char[]>(mislen);
  185. size_t blocks = bitfieldMan_->countBlock();
  186. size_t misBlock = 0;
  187. if (isEndGame()) {
  188. bool r = bitfieldMan_->getAllMissingIndexes(misbitfield.get(), mislen,
  189. bitfield, length);
  190. if (!r) {
  191. return;
  192. }
  193. std::vector<size_t> indexes;
  194. for (size_t i = 0; i < blocks; ++i) {
  195. if (bitfield::test(misbitfield, blocks, i)) {
  196. indexes.push_back(i);
  197. }
  198. }
  199. std::shuffle(indexes.begin(), indexes.end(),
  200. *SimpleRandomizer::getInstance());
  201. for (std::vector<size_t>::const_iterator i = indexes.begin(),
  202. eoi = indexes.end();
  203. i != eoi && misBlock < minMissingBlocks; ++i) {
  204. std::shared_ptr<Piece> piece = checkOutPiece(*i, cuid);
  205. if (piece->getUsedBySegment()) {
  206. // We don't share piece downloaded via HTTP/FTP
  207. piece->removeUser(cuid);
  208. }
  209. else {
  210. pieces.push_back(piece);
  211. misBlock += piece->countMissingBlock();
  212. }
  213. }
  214. }
  215. else {
  216. bool r = bitfieldMan_->getAllMissingUnusedIndexes(misbitfield.get(), mislen,
  217. bitfield, length);
  218. if (!r) {
  219. return;
  220. }
  221. while (misBlock < minMissingBlocks) {
  222. size_t index;
  223. if (pieceSelector_->select(index, misbitfield.get(), blocks)) {
  224. pieces.push_back(checkOutPiece(index, cuid));
  225. bitfield::flipBit(misbitfield.get(), blocks, index);
  226. misBlock += pieces.back()->countMissingBlock();
  227. }
  228. else {
  229. break;
  230. }
  231. }
  232. }
  233. }
  234. namespace {
  235. void unsetExcludedIndexes(BitfieldMan& bitfield,
  236. const std::vector<size_t>& excludedIndexes)
  237. {
  238. using namespace std::placeholders;
  239. std::for_each(excludedIndexes.begin(), excludedIndexes.end(),
  240. std::bind(&BitfieldMan::unsetBit, &bitfield, _1));
  241. }
  242. } // namespace
  243. void DefaultPieceStorage::createFastIndexBitfield(
  244. BitfieldMan& bitfield, const std::shared_ptr<Peer>& peer)
  245. {
  246. const auto& is = peer->getPeerAllowedIndexSet();
  247. for (const auto& i : is) {
  248. if (!bitfieldMan_->isBitSet(i) && peer->hasPiece(i)) {
  249. bitfield.setBit(i);
  250. }
  251. }
  252. }
  253. void DefaultPieceStorage::getMissingPiece(
  254. std::vector<std::shared_ptr<Piece>>& pieces, size_t minMissingBlocks,
  255. const std::shared_ptr<Peer>& peer, cuid_t cuid)
  256. {
  257. getMissingPiece(pieces, minMissingBlocks, peer->getBitfield(),
  258. peer->getBitfieldLength(), cuid);
  259. }
  260. void DefaultPieceStorage::getMissingPiece(
  261. std::vector<std::shared_ptr<Piece>>& pieces, size_t minMissingBlocks,
  262. const std::shared_ptr<Peer>& peer,
  263. const std::vector<size_t>& excludedIndexes, cuid_t cuid)
  264. {
  265. BitfieldMan tempBitfield(bitfieldMan_->getBlockLength(),
  266. bitfieldMan_->getTotalLength());
  267. tempBitfield.setBitfield(peer->getBitfield(), peer->getBitfieldLength());
  268. unsetExcludedIndexes(tempBitfield, excludedIndexes);
  269. getMissingPiece(pieces, minMissingBlocks, tempBitfield.getBitfield(),
  270. tempBitfield.getBitfieldLength(), cuid);
  271. }
  272. void DefaultPieceStorage::getMissingFastPiece(
  273. std::vector<std::shared_ptr<Piece>>& pieces, size_t minMissingBlocks,
  274. const std::shared_ptr<Peer>& peer, cuid_t cuid)
  275. {
  276. if (peer->isFastExtensionEnabled() && peer->countPeerAllowedIndexSet() > 0) {
  277. BitfieldMan tempBitfield(bitfieldMan_->getBlockLength(),
  278. bitfieldMan_->getTotalLength());
  279. createFastIndexBitfield(tempBitfield, peer);
  280. getMissingPiece(pieces, minMissingBlocks, tempBitfield.getBitfield(),
  281. tempBitfield.getBitfieldLength(), cuid);
  282. }
  283. }
  284. void DefaultPieceStorage::getMissingFastPiece(
  285. std::vector<std::shared_ptr<Piece>>& pieces, size_t minMissingBlocks,
  286. const std::shared_ptr<Peer>& peer,
  287. const std::vector<size_t>& excludedIndexes, cuid_t cuid)
  288. {
  289. if (peer->isFastExtensionEnabled() && peer->countPeerAllowedIndexSet() > 0) {
  290. BitfieldMan tempBitfield(bitfieldMan_->getBlockLength(),
  291. bitfieldMan_->getTotalLength());
  292. createFastIndexBitfield(tempBitfield, peer);
  293. unsetExcludedIndexes(tempBitfield, excludedIndexes);
  294. getMissingPiece(pieces, minMissingBlocks, tempBitfield.getBitfield(),
  295. tempBitfield.getBitfieldLength(), cuid);
  296. }
  297. }
  298. std::shared_ptr<Piece>
  299. DefaultPieceStorage::getMissingPiece(const std::shared_ptr<Peer>& peer,
  300. cuid_t cuid)
  301. {
  302. std::vector<std::shared_ptr<Piece>> pieces;
  303. getMissingPiece(pieces, 1, peer, cuid);
  304. if (pieces.empty()) {
  305. return nullptr;
  306. }
  307. else {
  308. return pieces.front();
  309. }
  310. }
  311. std::shared_ptr<Piece>
  312. DefaultPieceStorage::getMissingPiece(const std::shared_ptr<Peer>& peer,
  313. const std::vector<size_t>& excludedIndexes,
  314. cuid_t cuid)
  315. {
  316. std::vector<std::shared_ptr<Piece>> pieces;
  317. getMissingPiece(pieces, 1, peer, excludedIndexes, cuid);
  318. if (pieces.empty()) {
  319. return nullptr;
  320. }
  321. else {
  322. return pieces.front();
  323. }
  324. }
  325. std::shared_ptr<Piece>
  326. DefaultPieceStorage::getMissingFastPiece(const std::shared_ptr<Peer>& peer,
  327. cuid_t cuid)
  328. {
  329. std::vector<std::shared_ptr<Piece>> pieces;
  330. getMissingFastPiece(pieces, 1, peer, cuid);
  331. if (pieces.empty()) {
  332. return nullptr;
  333. }
  334. else {
  335. return pieces.front();
  336. }
  337. }
  338. std::shared_ptr<Piece> DefaultPieceStorage::getMissingFastPiece(
  339. const std::shared_ptr<Peer>& peer,
  340. const std::vector<size_t>& excludedIndexes, cuid_t cuid)
  341. {
  342. std::vector<std::shared_ptr<Piece>> pieces;
  343. getMissingFastPiece(pieces, 1, peer, excludedIndexes, cuid);
  344. if (pieces.empty()) {
  345. return nullptr;
  346. }
  347. else {
  348. return pieces.front();
  349. }
  350. }
  351. #endif // ENABLE_BITTORRENT
  352. bool DefaultPieceStorage::hasMissingUnusedPiece()
  353. {
  354. size_t index;
  355. return bitfieldMan_->getFirstMissingUnusedIndex(index);
  356. }
  357. std::shared_ptr<Piece>
  358. DefaultPieceStorage::getMissingPiece(size_t minSplitSize,
  359. const unsigned char* ignoreBitfield,
  360. size_t length, cuid_t cuid)
  361. {
  362. size_t index;
  363. if (streamPieceSelector_->select(index, minSplitSize, ignoreBitfield,
  364. length)) {
  365. return checkOutPiece(index, cuid);
  366. }
  367. else {
  368. return nullptr;
  369. }
  370. }
  371. std::shared_ptr<Piece> DefaultPieceStorage::getMissingPiece(size_t index,
  372. cuid_t cuid)
  373. {
  374. if (hasPiece(index) || isPieceUsed(index) ||
  375. (bitfieldMan_->isFilterEnabled() &&
  376. !bitfieldMan_->isFilterBitSet(index))) {
  377. return nullptr;
  378. }
  379. else {
  380. return checkOutPiece(index, cuid);
  381. }
  382. }
  383. void DefaultPieceStorage::deleteUsedPiece(const std::shared_ptr<Piece>& piece)
  384. {
  385. if (!piece) {
  386. return;
  387. }
  388. usedPieces_.erase(piece);
  389. piece->releaseWrCache(wrDiskCache_);
  390. }
  391. // void DefaultPieceStorage::reduceUsedPieces(size_t upperBound)
  392. // {
  393. // size_t usedPiecesSize = usedPieces.size();
  394. // if(usedPiecesSize <= upperBound) {
  395. // return;
  396. // }
  397. // size_t delNum = usedPiecesSize-upperBound;
  398. // int fillRate = 10;
  399. // while(delNum && fillRate <= 15) {
  400. // delNum -= deleteUsedPiecesByFillRate(fillRate, delNum);
  401. // fillRate += 5;
  402. // }
  403. // }
  404. // size_t DefaultPieceStorage::deleteUsedPiecesByFillRate(int fillRate,
  405. // size_t delNum)
  406. // {
  407. // size_t deleted = 0;
  408. // for(Pieces::iterator itr = usedPieces.begin();
  409. // itr != usedPieces.end() && deleted < delNum;) {
  410. // std::shared_ptr<Piece>& piece = *itr;
  411. // if(!bitfieldMan->isUseBitSet(piece->getIndex()) &&
  412. // piece->countCompleteBlock() <= piece->countBlock()*(fillRate/100.0)) {
  413. // logger->info(MSG_DELETING_USED_PIECE,
  414. // piece->getIndex(),
  415. // (piece->countCompleteBlock()*100)/piece->countBlock(),
  416. // fillRate);
  417. // itr = usedPieces.erase(itr);
  418. // ++deleted;
  419. // } else {
  420. // ++itr;
  421. // }
  422. // }
  423. // return deleted;
  424. // }
  425. void DefaultPieceStorage::completePiece(const std::shared_ptr<Piece>& piece)
  426. {
  427. if (!piece) {
  428. return;
  429. }
  430. deleteUsedPiece(piece);
  431. // if(!isEndGame()) {
  432. // reduceUsedPieces(100);
  433. // }
  434. if (allDownloadFinished()) {
  435. return;
  436. }
  437. bitfieldMan_->setBit(piece->getIndex());
  438. bitfieldMan_->unsetUseBit(piece->getIndex());
  439. addPieceStats(piece->getIndex());
  440. if (downloadFinished()) {
  441. downloadContext_->resetDownloadStopTime();
  442. if (isSelectiveDownloadingMode()) {
  443. A2_LOG_NOTICE(MSG_SELECTIVE_DOWNLOAD_COMPLETED);
  444. // following line was commented out in order to stop sending request
  445. // message after user-specified files were downloaded.
  446. // finishSelectiveDownloadingMode();
  447. }
  448. else {
  449. A2_LOG_INFO(MSG_DOWNLOAD_COMPLETED);
  450. }
  451. #ifdef ENABLE_BITTORRENT
  452. if (downloadContext_->hasAttribute(CTX_ATTR_BT)) {
  453. if (!bittorrent::getTorrentAttrs(downloadContext_)->metadata.empty()) {
  454. #ifdef __MINGW32__
  455. // On Windows, if aria2 opens files with GENERIC_WRITE access
  456. // right, some programs cannot open them aria2 is seeding. To
  457. // avoid this situation, re-open the files with read-only
  458. // enabled.
  459. A2_LOG_INFO("Closing files and re-open them with read-only mode"
  460. " enabled.");
  461. diskAdaptor_->closeFile();
  462. diskAdaptor_->enableReadOnly();
  463. diskAdaptor_->openFile();
  464. #endif // __MINGW32__
  465. auto group = downloadContext_->getOwnerRequestGroup();
  466. util::executeHookByOptName(group, option_,
  467. PREF_ON_BT_DOWNLOAD_COMPLETE);
  468. SingletonHolder<Notifier>::instance()->notifyDownloadEvent(
  469. EVENT_ON_BT_DOWNLOAD_COMPLETE, group);
  470. group->enableSeedOnly();
  471. }
  472. }
  473. #endif // ENABLE_BITTORRENT
  474. }
  475. }
  476. bool DefaultPieceStorage::isSelectiveDownloadingMode()
  477. {
  478. return bitfieldMan_->isFilterEnabled();
  479. }
  480. // not unittested
  481. void DefaultPieceStorage::cancelPiece(const std::shared_ptr<Piece>& piece,
  482. cuid_t cuid)
  483. {
  484. if (!piece) {
  485. return;
  486. }
  487. piece->removeUser(cuid);
  488. if (!piece->getUsed()) {
  489. bitfieldMan_->unsetUseBit(piece->getIndex());
  490. }
  491. if (!isEndGame()) {
  492. if (piece->getCompletedLength() == 0) {
  493. deleteUsedPiece(piece);
  494. }
  495. }
  496. }
  497. bool DefaultPieceStorage::hasPiece(size_t index)
  498. {
  499. return bitfieldMan_->isBitSet(index);
  500. }
  501. bool DefaultPieceStorage::isPieceUsed(size_t index)
  502. {
  503. return bitfieldMan_->isUseBitSet(index);
  504. }
  505. int64_t DefaultPieceStorage::getTotalLength()
  506. {
  507. return bitfieldMan_->getTotalLength();
  508. }
  509. int64_t DefaultPieceStorage::getFilteredTotalLength()
  510. {
  511. return bitfieldMan_->getFilteredTotalLength();
  512. }
  513. int64_t DefaultPieceStorage::getCompletedLength()
  514. {
  515. int64_t completedLength =
  516. bitfieldMan_->getCompletedLength() + getInFlightPieceCompletedLength();
  517. int64_t totalLength = getTotalLength();
  518. if (completedLength > totalLength) {
  519. completedLength = totalLength;
  520. }
  521. return completedLength;
  522. }
  523. int64_t DefaultPieceStorage::getFilteredCompletedLength()
  524. {
  525. return bitfieldMan_->getFilteredCompletedLength() +
  526. getInFlightPieceFilteredCompletedLength();
  527. }
  528. int64_t DefaultPieceStorage::getInFlightPieceCompletedLength() const
  529. {
  530. int64_t len = 0;
  531. for (auto& elem : usedPieces_) {
  532. len += elem->getCompletedLength();
  533. }
  534. return len;
  535. }
  536. int64_t DefaultPieceStorage::getInFlightPieceFilteredCompletedLength() const
  537. {
  538. int64_t len = 0;
  539. for (auto& elem : usedPieces_) {
  540. if (bitfieldMan_->isFilterBitSet(elem->getIndex())) {
  541. len += elem->getCompletedLength();
  542. }
  543. }
  544. return len;
  545. }
  546. // not unittested
  547. void DefaultPieceStorage::setupFileFilter()
  548. {
  549. const std::vector<std::shared_ptr<FileEntry>>& fileEntries =
  550. downloadContext_->getFileEntries();
  551. bool allSelected = true;
  552. for (auto& e : fileEntries) {
  553. if (!e->isRequested()) {
  554. allSelected = false;
  555. break;
  556. }
  557. }
  558. if (allSelected) {
  559. return;
  560. }
  561. for (auto& e : fileEntries) {
  562. if (e->isRequested()) {
  563. bitfieldMan_->addFilter(e->getOffset(), e->getLength());
  564. }
  565. }
  566. bitfieldMan_->enableFilter();
  567. }
  568. // not unittested
  569. void DefaultPieceStorage::clearFileFilter() { bitfieldMan_->clearFilter(); }
  570. // not unittested
  571. bool DefaultPieceStorage::downloadFinished()
  572. {
  573. // TODO iterate all requested FileEntry and Call
  574. // bitfieldMan->isBitSetOffsetRange()
  575. return bitfieldMan_->isFilteredAllBitSet();
  576. }
  577. // not unittested
  578. bool DefaultPieceStorage::allDownloadFinished()
  579. {
  580. return bitfieldMan_->isAllBitSet();
  581. }
  582. // not unittested
  583. void DefaultPieceStorage::initStorage()
  584. {
  585. if (downloadContext_->getFileEntries().size() == 1) {
  586. A2_LOG_DEBUG("Instantiating DirectDiskAdaptor");
  587. auto directDiskAdaptor = std::make_shared<DirectDiskAdaptor>();
  588. directDiskAdaptor->setTotalLength(downloadContext_->getTotalLength());
  589. directDiskAdaptor->setFileEntries(
  590. downloadContext_->getFileEntries().begin(),
  591. downloadContext_->getFileEntries().end());
  592. directDiskAdaptor->setDiskWriter(
  593. diskWriterFactory_->newDiskWriter(directDiskAdaptor->getFilePath()));
  594. diskAdaptor_ = std::move(directDiskAdaptor);
  595. }
  596. else {
  597. A2_LOG_DEBUG("Instantiating MultiDiskAdaptor");
  598. auto multiDiskAdaptor = std::make_shared<MultiDiskAdaptor>();
  599. multiDiskAdaptor->setFileEntries(downloadContext_->getFileEntries().begin(),
  600. downloadContext_->getFileEntries().end());
  601. multiDiskAdaptor->setPieceLength(downloadContext_->getPieceLength());
  602. diskAdaptor_ = std::move(multiDiskAdaptor);
  603. }
  604. if (option_->get(PREF_FILE_ALLOCATION) == V_FALLOC) {
  605. diskAdaptor_->setFileAllocationMethod(DiskAdaptor::FILE_ALLOC_FALLOC);
  606. }
  607. else if (option_->get(PREF_FILE_ALLOCATION) == V_TRUNC) {
  608. diskAdaptor_->setFileAllocationMethod(DiskAdaptor::FILE_ALLOC_TRUNC);
  609. }
  610. }
  611. void DefaultPieceStorage::setBitfield(const unsigned char* bitfield,
  612. size_t bitfieldLength)
  613. {
  614. bitfieldMan_->setBitfield(bitfield, bitfieldLength);
  615. addPieceStats(bitfield, bitfieldLength);
  616. }
  617. size_t DefaultPieceStorage::getBitfieldLength()
  618. {
  619. return bitfieldMan_->getBitfieldLength();
  620. }
  621. const unsigned char* DefaultPieceStorage::getBitfield()
  622. {
  623. return bitfieldMan_->getBitfield();
  624. }
  625. std::shared_ptr<DiskAdaptor> DefaultPieceStorage::getDiskAdaptor()
  626. {
  627. return diskAdaptor_;
  628. }
  629. WrDiskCache* DefaultPieceStorage::getWrDiskCache() { return wrDiskCache_; }
  630. void DefaultPieceStorage::flushWrDiskCacheEntry()
  631. {
  632. if (!wrDiskCache_) {
  633. return;
  634. }
  635. // UsedPieceSet is sorted by piece index. It means we can flush
  636. // cache by non-decreasing offset, which is good to reduce disk seek
  637. // unless the file is heavily fragmented.
  638. for (auto& piece : usedPieces_) {
  639. auto ce = piece->getWrDiskCacheEntry();
  640. if (ce) {
  641. piece->flushWrCache(wrDiskCache_);
  642. piece->releaseWrCache(wrDiskCache_);
  643. }
  644. }
  645. }
  646. int32_t DefaultPieceStorage::getPieceLength(size_t index)
  647. {
  648. return bitfieldMan_->getBlockLength(index);
  649. }
  650. void DefaultPieceStorage::advertisePiece(cuid_t cuid, size_t index,
  651. Timer registeredTime)
  652. {
  653. haves_.emplace_back(nextHaveIndex_++, cuid, index, std::move(registeredTime));
  654. }
  655. uint64_t DefaultPieceStorage::getAdvertisedPieceIndexes(
  656. std::vector<size_t>& indexes, cuid_t myCuid, uint64_t lastHaveIndex)
  657. {
  658. auto it =
  659. std::upper_bound(std::begin(haves_), std::end(haves_), lastHaveIndex,
  660. [](uint64_t lastHaveIndex, const HaveEntry& have) {
  661. return lastHaveIndex < have.haveIndex;
  662. });
  663. if (it == std::end(haves_)) {
  664. return lastHaveIndex;
  665. }
  666. for (; it != std::end(haves_); ++it) {
  667. indexes.push_back((*it).index);
  668. }
  669. return (*(std::end(haves_) - 1)).haveIndex;
  670. }
  671. void DefaultPieceStorage::removeAdvertisedPiece(const Timer& expiry)
  672. {
  673. auto it = std::upper_bound(std::begin(haves_), std::end(haves_), expiry,
  674. [](const Timer& expiry, const HaveEntry& have) {
  675. return expiry < have.registeredTime;
  676. });
  677. A2_LOG_DEBUG(
  678. fmt(MSG_REMOVED_HAVE_ENTRY,
  679. static_cast<unsigned long>(std::distance(std::begin(haves_), it))));
  680. haves_.erase(std::begin(haves_), it);
  681. }
  682. void DefaultPieceStorage::markAllPiecesDone() { bitfieldMan_->setAllBit(); }
  683. void DefaultPieceStorage::markPiecesDone(int64_t length)
  684. {
  685. if (length == bitfieldMan_->getTotalLength()) {
  686. bitfieldMan_->setAllBit();
  687. }
  688. else if (length == 0) {
  689. // TODO this would go to markAllPiecesUndone()
  690. bitfieldMan_->clearAllBit();
  691. usedPieces_.clear();
  692. }
  693. else {
  694. size_t numPiece = length / bitfieldMan_->getBlockLength();
  695. if (numPiece > 0) {
  696. bitfieldMan_->setBitRange(0, numPiece - 1);
  697. }
  698. size_t r = (length % bitfieldMan_->getBlockLength()) / Piece::BLOCK_LENGTH;
  699. if (r > 0) {
  700. auto p = std::make_shared<Piece>(numPiece,
  701. bitfieldMan_->getBlockLength(numPiece));
  702. for (size_t i = 0; i < r; ++i) {
  703. p->completeBlock(i);
  704. }
  705. p->setHashType(downloadContext_->getPieceHashType());
  706. addUsedPiece(p);
  707. }
  708. }
  709. }
  710. void DefaultPieceStorage::markPieceMissing(size_t index)
  711. {
  712. bitfieldMan_->unsetBit(index);
  713. }
  714. void DefaultPieceStorage::addInFlightPiece(
  715. const std::vector<std::shared_ptr<Piece>>& pieces)
  716. {
  717. usedPieces_.insert(pieces.begin(), pieces.end());
  718. }
  719. size_t DefaultPieceStorage::countInFlightPiece() { return usedPieces_.size(); }
  720. void DefaultPieceStorage::getInFlightPieces(
  721. std::vector<std::shared_ptr<Piece>>& pieces)
  722. {
  723. pieces.insert(pieces.end(), usedPieces_.begin(), usedPieces_.end());
  724. }
  725. void DefaultPieceStorage::setDiskWriterFactory(
  726. const std::shared_ptr<DiskWriterFactory>& diskWriterFactory)
  727. {
  728. diskWriterFactory_ = diskWriterFactory;
  729. }
  730. void DefaultPieceStorage::addPieceStats(const unsigned char* bitfield,
  731. size_t bitfieldLength)
  732. {
  733. pieceStatMan_->addPieceStats(bitfield, bitfieldLength);
  734. }
  735. void DefaultPieceStorage::subtractPieceStats(const unsigned char* bitfield,
  736. size_t bitfieldLength)
  737. {
  738. pieceStatMan_->subtractPieceStats(bitfield, bitfieldLength);
  739. }
  740. void DefaultPieceStorage::updatePieceStats(const unsigned char* newBitfield,
  741. size_t newBitfieldLength,
  742. const unsigned char* oldBitfield)
  743. {
  744. pieceStatMan_->updatePieceStats(newBitfield, newBitfieldLength, oldBitfield);
  745. }
  746. void DefaultPieceStorage::addPieceStats(size_t index)
  747. {
  748. pieceStatMan_->addPieceStats(index);
  749. }
  750. size_t DefaultPieceStorage::getNextUsedIndex(size_t index)
  751. {
  752. for (size_t i = index + 1; i < bitfieldMan_->countBlock(); ++i) {
  753. if (bitfieldMan_->isUseBitSet(i) || bitfieldMan_->isBitSet(i)) {
  754. return i;
  755. }
  756. }
  757. return bitfieldMan_->countBlock();
  758. }
  759. void DefaultPieceStorage::onDownloadIncomplete()
  760. {
  761. streamPieceSelector_->onBitfieldInit();
  762. }
  763. void DefaultPieceStorage::setPieceSelector(
  764. std::unique_ptr<PieceSelector> pieceSelector)
  765. {
  766. pieceSelector_ = std::move(pieceSelector);
  767. }
  768. std::unique_ptr<PieceSelector> DefaultPieceStorage::popPieceSelector()
  769. {
  770. return std::move(pieceSelector_);
  771. }
  772. } // namespace aria2