DefaultPieceStorage.cc 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789
  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 "array_fun.h"
  60. #include "PieceStatMan.h"
  61. #include "wallclock.h"
  62. #include "bitfield.h"
  63. #ifdef ENABLE_BITTORRENT
  64. # include "bittorrent_helper.h"
  65. #endif // ENABLE_BITTORRENT
  66. namespace aria2 {
  67. DefaultPieceStorage::DefaultPieceStorage
  68. (const SharedHandle<DownloadContext>& downloadContext, const Option* option)
  69. : downloadContext_(downloadContext),
  70. bitfieldMan_(new BitfieldMan(downloadContext->getPieceLength(),
  71. downloadContext->getTotalLength())),
  72. diskWriterFactory_(new DefaultDiskWriterFactory()),
  73. endGame_(false),
  74. endGamePieceNum_(END_GAME_PIECE_NUM),
  75. option_(option),
  76. pieceStatMan_(new PieceStatMan(downloadContext->getNumPieces(), true)),
  77. pieceSelector_(new RarestPieceSelector(pieceStatMan_))
  78. {
  79. const std::string& pieceSelectorOpt =
  80. option_->get(PREF_STREAM_PIECE_SELECTOR);
  81. if(pieceSelectorOpt.empty() || pieceSelectorOpt == A2_V_DEFAULT) {
  82. streamPieceSelector_ = SharedHandle<StreamPieceSelector>
  83. (new DefaultStreamPieceSelector(bitfieldMan_));
  84. } else if(pieceSelectorOpt == V_INORDER) {
  85. streamPieceSelector_ = SharedHandle<StreamPieceSelector>
  86. (new InorderStreamPieceSelector(bitfieldMan_));
  87. }
  88. }
  89. DefaultPieceStorage::~DefaultPieceStorage()
  90. {
  91. delete bitfieldMan_;
  92. }
  93. SharedHandle<Piece> DefaultPieceStorage::checkOutPiece(size_t index)
  94. {
  95. bitfieldMan_->setUseBit(index);
  96. SharedHandle<Piece> piece = findUsedPiece(index);
  97. if(!piece) {
  98. piece.reset(new Piece(index, bitfieldMan_->getBlockLength(index)));
  99. #ifdef ENABLE_MESSAGE_DIGEST
  100. piece->setHashAlgo(downloadContext_->getPieceHashAlgo());
  101. #endif // ENABLE_MESSAGE_DIGEST
  102. addUsedPiece(piece);
  103. return piece;
  104. } else {
  105. return piece;
  106. }
  107. }
  108. /**
  109. * Newly instantiated piece is not added to usedPieces.
  110. * Because it is waste of memory and there is no chance to use them later.
  111. */
  112. SharedHandle<Piece> DefaultPieceStorage::getPiece(size_t index)
  113. {
  114. SharedHandle<Piece> piece;
  115. if(0 <= index && index <= bitfieldMan_->getMaxIndex()) {
  116. piece = findUsedPiece(index);
  117. if(!piece) {
  118. piece.reset(new Piece(index, bitfieldMan_->getBlockLength(index)));
  119. if(hasPiece(index)) {
  120. piece->setAllBlock();
  121. }
  122. }
  123. }
  124. return piece;
  125. }
  126. void DefaultPieceStorage::addUsedPiece(const SharedHandle<Piece>& piece)
  127. {
  128. std::deque<SharedHandle<Piece> >::iterator i =
  129. std::lower_bound(usedPieces_.begin(), usedPieces_.end(), piece,
  130. DerefLess<SharedHandle<Piece> >());
  131. usedPieces_.insert(i, piece);
  132. A2_LOG_DEBUG(fmt("usedPieces_.size()=%lu",
  133. static_cast<unsigned long>(usedPieces_.size())));
  134. }
  135. SharedHandle<Piece> DefaultPieceStorage::findUsedPiece(size_t index) const
  136. {
  137. SharedHandle<Piece> p(new Piece());
  138. p->setIndex(index);
  139. std::deque<SharedHandle<Piece> >::const_iterator i =
  140. std::lower_bound(usedPieces_.begin(), usedPieces_.end(), p,
  141. DerefLess<SharedHandle<Piece> >());
  142. if(i != usedPieces_.end() && *(*i) == *p) {
  143. return *i;
  144. } else {
  145. p.reset();
  146. return p;
  147. }
  148. }
  149. #ifdef ENABLE_BITTORRENT
  150. bool DefaultPieceStorage::hasMissingPiece(const SharedHandle<Peer>& peer)
  151. {
  152. return bitfieldMan_->hasMissingPiece(peer->getBitfield(),
  153. peer->getBitfieldLength());
  154. }
  155. void DefaultPieceStorage::getMissingPiece
  156. (std::vector<SharedHandle<Piece> >& pieces,
  157. size_t minMissingBlocks,
  158. const unsigned char* bitfield,
  159. size_t length)
  160. {
  161. const size_t mislen = bitfieldMan_->getBitfieldLength();
  162. array_ptr<unsigned char> misbitfield(new unsigned char[mislen]);
  163. size_t blocks = bitfieldMan_->countBlock();
  164. size_t misBlock = 0;
  165. if(isEndGame()) {
  166. bool r = bitfieldMan_->getAllMissingIndexes
  167. (misbitfield, mislen, bitfield, length);
  168. if(!r) {
  169. return;
  170. }
  171. std::vector<size_t> indexes;
  172. for(size_t i = 0; i < blocks; ++i) {
  173. if(bitfield::test(misbitfield, blocks, i)) {
  174. indexes.push_back(i);
  175. }
  176. }
  177. std::random_shuffle(indexes.begin(), indexes.end());
  178. for(std::vector<size_t>::const_iterator i = indexes.begin(),
  179. eoi = indexes.end(); i != eoi && misBlock < minMissingBlocks; ++i) {
  180. pieces.push_back(checkOutPiece(*i));
  181. misBlock += pieces.back()->countMissingBlock();
  182. }
  183. } else {
  184. bool r = bitfieldMan_->getAllMissingUnusedIndexes
  185. (misbitfield, mislen, bitfield, length);
  186. if(!r) {
  187. return;
  188. }
  189. while(misBlock < minMissingBlocks) {
  190. size_t index;
  191. if(pieceSelector_->select(index, misbitfield, blocks)) {
  192. pieces.push_back(checkOutPiece(index));
  193. bitfield::flipBit(misbitfield, blocks, index);
  194. misBlock += pieces.back()->countMissingBlock();
  195. } else {
  196. break;
  197. }
  198. }
  199. }
  200. }
  201. namespace {
  202. void unsetExcludedIndexes(BitfieldMan& bitfield,
  203. const std::vector<size_t>& excludedIndexes)
  204. {
  205. std::for_each(excludedIndexes.begin(), excludedIndexes.end(),
  206. std::bind1st(std::mem_fun(&BitfieldMan::unsetBit), &bitfield));
  207. }
  208. } // namespace
  209. void DefaultPieceStorage::createFastIndexBitfield
  210. (BitfieldMan& bitfield, const SharedHandle<Peer>& peer)
  211. {
  212. for(std::vector<size_t>::const_iterator itr =
  213. peer->getPeerAllowedIndexSet().begin(),
  214. eoi = peer->getPeerAllowedIndexSet().end(); itr != eoi; ++itr) {
  215. if(!bitfieldMan_->isBitSet(*itr) && peer->hasPiece(*itr)) {
  216. bitfield.setBit(*itr);
  217. }
  218. }
  219. }
  220. void DefaultPieceStorage::getMissingPiece
  221. (std::vector<SharedHandle<Piece> >& pieces,
  222. size_t minMissingBlocks,
  223. const SharedHandle<Peer>& peer)
  224. {
  225. getMissingPiece(pieces, minMissingBlocks,
  226. peer->getBitfield(), peer->getBitfieldLength());
  227. }
  228. void DefaultPieceStorage::getMissingPiece
  229. (std::vector<SharedHandle<Piece> >& pieces,
  230. size_t minMissingBlocks,
  231. const SharedHandle<Peer>& peer,
  232. const std::vector<size_t>& excludedIndexes)
  233. {
  234. BitfieldMan tempBitfield(bitfieldMan_->getBlockLength(),
  235. bitfieldMan_->getTotalLength());
  236. tempBitfield.setBitfield(peer->getBitfield(), peer->getBitfieldLength());
  237. unsetExcludedIndexes(tempBitfield, excludedIndexes);
  238. getMissingPiece(pieces, minMissingBlocks,
  239. tempBitfield.getBitfield(), tempBitfield.getBitfieldLength());
  240. }
  241. void DefaultPieceStorage::getMissingFastPiece
  242. (std::vector<SharedHandle<Piece> >& pieces,
  243. size_t minMissingBlocks,
  244. const SharedHandle<Peer>& peer)
  245. {
  246. if(peer->isFastExtensionEnabled() && peer->countPeerAllowedIndexSet() > 0) {
  247. BitfieldMan tempBitfield(bitfieldMan_->getBlockLength(),
  248. bitfieldMan_->getTotalLength());
  249. createFastIndexBitfield(tempBitfield, peer);
  250. getMissingPiece(pieces, minMissingBlocks,
  251. tempBitfield.getBitfield(),
  252. tempBitfield.getBitfieldLength());
  253. }
  254. }
  255. void DefaultPieceStorage::getMissingFastPiece
  256. (std::vector<SharedHandle<Piece> >& pieces,
  257. size_t minMissingBlocks,
  258. const SharedHandle<Peer>& peer,
  259. const std::vector<size_t>& excludedIndexes)
  260. {
  261. if(peer->isFastExtensionEnabled() && peer->countPeerAllowedIndexSet() > 0) {
  262. BitfieldMan tempBitfield(bitfieldMan_->getBlockLength(),
  263. bitfieldMan_->getTotalLength());
  264. createFastIndexBitfield(tempBitfield, peer);
  265. unsetExcludedIndexes(tempBitfield, excludedIndexes);
  266. getMissingPiece(pieces, minMissingBlocks,
  267. tempBitfield.getBitfield(),
  268. tempBitfield.getBitfieldLength());
  269. }
  270. }
  271. SharedHandle<Piece>
  272. DefaultPieceStorage::getMissingPiece(const SharedHandle<Peer>& peer)
  273. {
  274. std::vector<SharedHandle<Piece> > pieces;
  275. getMissingPiece(pieces, 1, peer);
  276. if(pieces.empty()) {
  277. return SharedHandle<Piece>();
  278. } else {
  279. return pieces.front();
  280. }
  281. }
  282. SharedHandle<Piece> DefaultPieceStorage::getMissingPiece
  283. (const SharedHandle<Peer>& peer, const std::vector<size_t>& excludedIndexes)
  284. {
  285. std::vector<SharedHandle<Piece> > pieces;
  286. getMissingPiece(pieces, 1, peer, excludedIndexes);
  287. if(pieces.empty()) {
  288. return SharedHandle<Piece>();
  289. } else {
  290. return pieces.front();
  291. }
  292. }
  293. SharedHandle<Piece> DefaultPieceStorage::getMissingFastPiece
  294. (const SharedHandle<Peer>& peer)
  295. {
  296. std::vector<SharedHandle<Piece> > pieces;
  297. getMissingFastPiece(pieces, 1, peer);
  298. if(pieces.empty()) {
  299. return SharedHandle<Piece>();
  300. } else {
  301. return pieces.front();
  302. }
  303. }
  304. SharedHandle<Piece> DefaultPieceStorage::getMissingFastPiece
  305. (const SharedHandle<Peer>& peer, const std::vector<size_t>& excludedIndexes)
  306. {
  307. std::vector<SharedHandle<Piece> > pieces;
  308. getMissingFastPiece(pieces, 1, peer, excludedIndexes);
  309. if(pieces.empty()) {
  310. return SharedHandle<Piece>();
  311. } else {
  312. return pieces.front();
  313. }
  314. }
  315. #endif // ENABLE_BITTORRENT
  316. bool DefaultPieceStorage::hasMissingUnusedPiece()
  317. {
  318. size_t index;
  319. return bitfieldMan_->getFirstMissingUnusedIndex(index);
  320. }
  321. SharedHandle<Piece> DefaultPieceStorage::getMissingPiece
  322. (size_t minSplitSize, const unsigned char* ignoreBitfield, size_t length)
  323. {
  324. size_t index;
  325. if(streamPieceSelector_->select
  326. (index, minSplitSize, ignoreBitfield, length)) {
  327. return checkOutPiece(index);
  328. } else {
  329. return SharedHandle<Piece>();
  330. }
  331. }
  332. SharedHandle<Piece> DefaultPieceStorage::getMissingPiece(size_t index)
  333. {
  334. if(hasPiece(index) || isPieceUsed(index)) {
  335. return SharedHandle<Piece>();
  336. } else {
  337. return checkOutPiece(index);
  338. }
  339. }
  340. void DefaultPieceStorage::deleteUsedPiece(const SharedHandle<Piece>& piece)
  341. {
  342. if(!piece) {
  343. return;
  344. }
  345. std::deque<SharedHandle<Piece> >::iterator i =
  346. std::lower_bound(usedPieces_.begin(), usedPieces_.end(), piece,
  347. DerefLess<SharedHandle<Piece> >());
  348. if(i != usedPieces_.end() && *(*i) == *piece) {
  349. usedPieces_.erase(i);
  350. }
  351. }
  352. // void DefaultPieceStorage::reduceUsedPieces(size_t upperBound)
  353. // {
  354. // size_t usedPiecesSize = usedPieces.size();
  355. // if(usedPiecesSize <= upperBound) {
  356. // return;
  357. // }
  358. // size_t delNum = usedPiecesSize-upperBound;
  359. // int fillRate = 10;
  360. // while(delNum && fillRate <= 15) {
  361. // delNum -= deleteUsedPiecesByFillRate(fillRate, delNum);
  362. // fillRate += 5;
  363. // }
  364. // }
  365. // size_t DefaultPieceStorage::deleteUsedPiecesByFillRate(int fillRate,
  366. // size_t delNum)
  367. // {
  368. // size_t deleted = 0;
  369. // for(Pieces::iterator itr = usedPieces.begin();
  370. // itr != usedPieces.end() && deleted < delNum;) {
  371. // SharedHandle<Piece>& piece = *itr;
  372. // if(!bitfieldMan->isUseBitSet(piece->getIndex()) &&
  373. // piece->countCompleteBlock() <= piece->countBlock()*(fillRate/100.0)) {
  374. // logger->info(MSG_DELETING_USED_PIECE,
  375. // piece->getIndex(),
  376. // (piece->countCompleteBlock()*100)/piece->countBlock(),
  377. // fillRate);
  378. // itr = usedPieces.erase(itr);
  379. // ++deleted;
  380. // } else {
  381. // ++itr;
  382. // }
  383. // }
  384. // return deleted;
  385. // }
  386. void DefaultPieceStorage::completePiece(const SharedHandle<Piece>& piece)
  387. {
  388. if(!piece) {
  389. return;
  390. }
  391. deleteUsedPiece(piece);
  392. // if(!isEndGame()) {
  393. // reduceUsedPieces(100);
  394. // }
  395. if(allDownloadFinished()) {
  396. return;
  397. }
  398. bitfieldMan_->setBit(piece->getIndex());
  399. bitfieldMan_->unsetUseBit(piece->getIndex());
  400. addPieceStats(piece->getIndex());
  401. if(downloadFinished()) {
  402. downloadContext_->resetDownloadStopTime();
  403. if(isSelectiveDownloadingMode()) {
  404. A2_LOG_NOTICE(MSG_SELECTIVE_DOWNLOAD_COMPLETED);
  405. // following line was commented out in order to stop sending request
  406. // message after user-specified files were downloaded.
  407. //finishSelectiveDownloadingMode();
  408. } else {
  409. A2_LOG_INFO(MSG_DOWNLOAD_COMPLETED);
  410. }
  411. #ifdef ENABLE_BITTORRENT
  412. if(downloadContext_->hasAttribute(bittorrent::BITTORRENT)) {
  413. SharedHandle<TorrentAttribute> torrentAttrs =
  414. bittorrent::getTorrentAttrs(downloadContext_);
  415. if(!torrentAttrs->metadata.empty()) {
  416. util::executeHookByOptName(downloadContext_->getOwnerRequestGroup(),
  417. option_, PREF_ON_BT_DOWNLOAD_COMPLETE);
  418. }
  419. }
  420. #endif // ENABLE_BITTORRENT
  421. }
  422. }
  423. bool DefaultPieceStorage::isSelectiveDownloadingMode()
  424. {
  425. return bitfieldMan_->isFilterEnabled();
  426. }
  427. // not unittested
  428. void DefaultPieceStorage::cancelPiece(const SharedHandle<Piece>& piece)
  429. {
  430. if(!piece) {
  431. return;
  432. }
  433. bitfieldMan_->unsetUseBit(piece->getIndex());
  434. if(!isEndGame()) {
  435. if(piece->getCompletedLength() == 0) {
  436. deleteUsedPiece(piece);
  437. }
  438. }
  439. }
  440. bool DefaultPieceStorage::hasPiece(size_t index)
  441. {
  442. return bitfieldMan_->isBitSet(index);
  443. }
  444. bool DefaultPieceStorage::isPieceUsed(size_t index)
  445. {
  446. return bitfieldMan_->isUseBitSet(index);
  447. }
  448. uint64_t DefaultPieceStorage::getTotalLength()
  449. {
  450. return bitfieldMan_->getTotalLength();
  451. }
  452. uint64_t DefaultPieceStorage::getFilteredTotalLength()
  453. {
  454. return bitfieldMan_->getFilteredTotalLength();
  455. }
  456. uint64_t DefaultPieceStorage::getCompletedLength()
  457. {
  458. uint64_t completedLength =
  459. bitfieldMan_->getCompletedLength()+getInFlightPieceCompletedLength();
  460. uint64_t totalLength = getTotalLength();
  461. if(completedLength > totalLength) {
  462. completedLength = totalLength;
  463. }
  464. return completedLength;
  465. }
  466. uint64_t DefaultPieceStorage::getFilteredCompletedLength()
  467. {
  468. return bitfieldMan_->getFilteredCompletedLength()+
  469. getInFlightPieceCompletedLength();
  470. }
  471. size_t DefaultPieceStorage::getInFlightPieceCompletedLength() const
  472. {
  473. return std::accumulate(usedPieces_.begin(), usedPieces_.end(),
  474. 0, adopt2nd(std::plus<size_t>(),
  475. mem_fun_sh(&Piece::getCompletedLength)));
  476. }
  477. // not unittested
  478. void DefaultPieceStorage::setupFileFilter()
  479. {
  480. const std::vector<SharedHandle<FileEntry> >& fileEntries =
  481. downloadContext_->getFileEntries();
  482. bool allSelected = true;
  483. for(std::vector<SharedHandle<FileEntry> >::const_iterator i =
  484. fileEntries.begin(), eoi = fileEntries.end();
  485. i != eoi; ++i) {
  486. if(!(*i)->isRequested()) {
  487. allSelected = false;
  488. break;
  489. }
  490. }
  491. if(allSelected) {
  492. return;
  493. }
  494. for(std::vector<SharedHandle<FileEntry> >::const_iterator i =
  495. fileEntries.begin(), eoi = fileEntries.end(); i != eoi; ++i) {
  496. if((*i)->isRequested()) {
  497. bitfieldMan_->addFilter((*i)->getOffset(), (*i)->getLength());
  498. }
  499. }
  500. bitfieldMan_->enableFilter();
  501. }
  502. // not unittested
  503. void DefaultPieceStorage::clearFileFilter()
  504. {
  505. bitfieldMan_->clearFilter();
  506. }
  507. // not unittested
  508. bool DefaultPieceStorage::downloadFinished()
  509. {
  510. // TODO iterate all requested FileEntry and Call
  511. // bitfieldMan->isBitSetOffsetRange()
  512. return bitfieldMan_->isFilteredAllBitSet();
  513. }
  514. // not unittested
  515. bool DefaultPieceStorage::allDownloadFinished()
  516. {
  517. return bitfieldMan_->isAllBitSet();
  518. }
  519. // not unittested
  520. void DefaultPieceStorage::initStorage()
  521. {
  522. if(downloadContext_->getFileEntries().size() == 1) {
  523. A2_LOG_DEBUG("Instantiating DirectDiskAdaptor");
  524. DirectDiskAdaptorHandle directDiskAdaptor(new DirectDiskAdaptor());
  525. directDiskAdaptor->setTotalLength(downloadContext_->getTotalLength());
  526. directDiskAdaptor->setFileEntries
  527. (downloadContext_->getFileEntries().begin(),
  528. downloadContext_->getFileEntries().end());
  529. DiskWriterHandle writer =
  530. diskWriterFactory_->newDiskWriter(directDiskAdaptor->getFilePath());
  531. if(option_->getAsBool(PREF_ENABLE_DIRECT_IO)) {
  532. writer->allowDirectIO();
  533. }
  534. directDiskAdaptor->setDiskWriter(writer);
  535. diskAdaptor_ = directDiskAdaptor;
  536. } else {
  537. A2_LOG_DEBUG("Instantiating MultiDiskAdaptor");
  538. MultiDiskAdaptorHandle multiDiskAdaptor(new MultiDiskAdaptor());
  539. multiDiskAdaptor->setFileEntries(downloadContext_->getFileEntries().begin(),
  540. downloadContext_->getFileEntries().end());
  541. if(option_->getAsBool(PREF_ENABLE_DIRECT_IO)) {
  542. multiDiskAdaptor->allowDirectIO();
  543. }
  544. multiDiskAdaptor->setPieceLength(downloadContext_->getPieceLength());
  545. multiDiskAdaptor->setMaxOpenFiles
  546. (option_->getAsInt(PREF_BT_MAX_OPEN_FILES));
  547. diskAdaptor_ = multiDiskAdaptor;
  548. }
  549. if(option_->get(PREF_FILE_ALLOCATION) == V_FALLOC) {
  550. diskAdaptor_->enableFallocate();
  551. }
  552. }
  553. void DefaultPieceStorage::setBitfield(const unsigned char* bitfield,
  554. size_t bitfieldLength)
  555. {
  556. bitfieldMan_->setBitfield(bitfield, bitfieldLength);
  557. addPieceStats(bitfield, bitfieldLength);
  558. }
  559. size_t DefaultPieceStorage::getBitfieldLength()
  560. {
  561. return bitfieldMan_->getBitfieldLength();
  562. }
  563. const unsigned char* DefaultPieceStorage::getBitfield()
  564. {
  565. return bitfieldMan_->getBitfield();
  566. }
  567. DiskAdaptorHandle DefaultPieceStorage::getDiskAdaptor() {
  568. return diskAdaptor_;
  569. }
  570. size_t DefaultPieceStorage::getPieceLength(size_t index)
  571. {
  572. return bitfieldMan_->getBlockLength(index);
  573. }
  574. void DefaultPieceStorage::advertisePiece(cuid_t cuid, size_t index)
  575. {
  576. HaveEntry entry(cuid, index, global::wallclock);
  577. haves_.push_front(entry);
  578. }
  579. void
  580. DefaultPieceStorage::getAdvertisedPieceIndexes(std::vector<size_t>& indexes,
  581. cuid_t myCuid,
  582. const Timer& lastCheckTime)
  583. {
  584. for(std::deque<HaveEntry>::const_iterator itr = haves_.begin(),
  585. eoi = haves_.end(); itr != eoi; ++itr) {
  586. const HaveEntry& have = *itr;
  587. if(have.getCuid() == myCuid) {
  588. continue;
  589. }
  590. if(lastCheckTime > have.getRegisteredTime()) {
  591. break;
  592. }
  593. indexes.push_back(have.getIndex());
  594. }
  595. }
  596. namespace {
  597. class FindElapsedHave
  598. {
  599. private:
  600. time_t elapsed;
  601. public:
  602. FindElapsedHave(time_t elapsed):elapsed(elapsed) {}
  603. bool operator()(const HaveEntry& have) {
  604. if(have.getRegisteredTime().difference(global::wallclock) >= elapsed) {
  605. return true;
  606. } else {
  607. return false;
  608. }
  609. }
  610. };
  611. } // namespace
  612. void DefaultPieceStorage::removeAdvertisedPiece(time_t elapsed)
  613. {
  614. std::deque<HaveEntry>::iterator itr =
  615. std::find_if(haves_.begin(), haves_.end(), FindElapsedHave(elapsed));
  616. if(itr != haves_.end()) {
  617. A2_LOG_DEBUG(fmt(MSG_REMOVED_HAVE_ENTRY,
  618. static_cast<unsigned long>(haves_.end()-itr)));
  619. haves_.erase(itr, haves_.end());
  620. }
  621. }
  622. void DefaultPieceStorage::markAllPiecesDone()
  623. {
  624. bitfieldMan_->setAllBit();
  625. }
  626. void DefaultPieceStorage::markPiecesDone(uint64_t length)
  627. {
  628. if(length == bitfieldMan_->getTotalLength()) {
  629. bitfieldMan_->setAllBit();
  630. } else if(length == 0) {
  631. // TODO this would go to markAllPiecesUndone()
  632. bitfieldMan_->clearAllBit();
  633. usedPieces_.clear();
  634. } else {
  635. size_t numPiece = length/bitfieldMan_->getBlockLength();
  636. if(numPiece > 0) {
  637. bitfieldMan_->setBitRange(0, numPiece-1);
  638. }
  639. size_t r = (length%bitfieldMan_->getBlockLength())/Piece::BLOCK_LENGTH;
  640. if(r > 0) {
  641. SharedHandle<Piece> p
  642. (new Piece(numPiece, bitfieldMan_->getBlockLength(numPiece)));
  643. for(size_t i = 0; i < r; ++i) {
  644. p->completeBlock(i);
  645. }
  646. #ifdef ENABLE_MESSAGE_DIGEST
  647. p->setHashAlgo(downloadContext_->getPieceHashAlgo());
  648. #endif // ENABLE_MESSAGE_DIGEST
  649. addUsedPiece(p);
  650. }
  651. }
  652. }
  653. void DefaultPieceStorage::markPieceMissing(size_t index)
  654. {
  655. bitfieldMan_->unsetBit(index);
  656. }
  657. void DefaultPieceStorage::addInFlightPiece
  658. (const std::vector<SharedHandle<Piece> >& pieces)
  659. {
  660. usedPieces_.insert(usedPieces_.end(), pieces.begin(), pieces.end());
  661. std::sort(usedPieces_.begin(), usedPieces_.end(),
  662. DerefLess<SharedHandle<Piece> >());
  663. }
  664. size_t DefaultPieceStorage::countInFlightPiece()
  665. {
  666. return usedPieces_.size();
  667. }
  668. void DefaultPieceStorage::getInFlightPieces
  669. (std::vector<SharedHandle<Piece> >& pieces)
  670. {
  671. pieces.insert(pieces.end(), usedPieces_.begin(), usedPieces_.end());
  672. }
  673. void DefaultPieceStorage::setDiskWriterFactory
  674. (const DiskWriterFactoryHandle& diskWriterFactory)
  675. {
  676. diskWriterFactory_ = diskWriterFactory;
  677. }
  678. void DefaultPieceStorage::addPieceStats(const unsigned char* bitfield,
  679. size_t bitfieldLength)
  680. {
  681. pieceStatMan_->addPieceStats(bitfield, bitfieldLength);
  682. }
  683. void DefaultPieceStorage::subtractPieceStats(const unsigned char* bitfield,
  684. size_t bitfieldLength)
  685. {
  686. pieceStatMan_->subtractPieceStats(bitfield, bitfieldLength);
  687. }
  688. void DefaultPieceStorage::updatePieceStats(const unsigned char* newBitfield,
  689. size_t newBitfieldLength,
  690. const unsigned char* oldBitfield)
  691. {
  692. pieceStatMan_->updatePieceStats(newBitfield, newBitfieldLength,
  693. oldBitfield);
  694. }
  695. void DefaultPieceStorage::addPieceStats(size_t index)
  696. {
  697. pieceStatMan_->addPieceStats(index);
  698. }
  699. size_t DefaultPieceStorage::getNextUsedIndex(size_t index)
  700. {
  701. for(size_t i = index+1; i < bitfieldMan_->countBlock(); ++i) {
  702. if(bitfieldMan_->isUseBitSet(i) || bitfieldMan_->isBitSet(i)) {
  703. return i;
  704. }
  705. }
  706. return bitfieldMan_->countBlock();
  707. }
  708. } // namespace aria2