DefaultPieceStorage.cc 22 KB

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