DefaultPieceStorage.cc 25 KB

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