PageRenderTime 54ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 1ms

/indra/llvfs/llvfs.cpp

https://bitbucket.org/lindenlab/viewer-beta/
C++ | 2203 lines | 1641 code | 324 blank | 238 comment | 283 complexity | 0a0817c9115987fb04a19241b0351be4 MD5 | raw file
Possible License(s): LGPL-2.1
  1. /**
  2. * @file llvfs.cpp
  3. * @brief Implementation of virtual file system
  4. *
  5. * $LicenseInfo:firstyear=2002&license=viewerlgpl$
  6. * Second Life Viewer Source Code
  7. * Copyright (C) 2010, Linden Research, Inc.
  8. *
  9. * This library is free software; you can redistribute it and/or
  10. * modify it under the terms of the GNU Lesser General Public
  11. * License as published by the Free Software Foundation;
  12. * version 2.1 of the License only.
  13. *
  14. * This library is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  17. * Lesser General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU Lesser General Public
  20. * License along with this library; if not, write to the Free Software
  21. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  22. *
  23. * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
  24. * $/LicenseInfo$
  25. */
  26. #include "linden_common.h"
  27. #include "llvfs.h"
  28. #include <sys/stat.h>
  29. #include <set>
  30. #include <map>
  31. #if LL_WINDOWS
  32. #include <share.h>
  33. #elif LL_SOLARIS
  34. #include <sys/types.h>
  35. #include <unistd.h>
  36. #include <fcntl.h>
  37. #else
  38. #include <sys/file.h>
  39. #endif
  40. #include "llstl.h"
  41. #include "lltimer.h"
  42. const S32 FILE_BLOCK_MASK = 0x000003FF; // 1024-byte blocks
  43. const S32 VFS_CLEANUP_SIZE = 5242880; // how much space we free up in a single stroke
  44. const S32 BLOCK_LENGTH_INVALID = -1; // mLength for invalid LLVFSFileBlocks
  45. LLVFS *gVFS = NULL;
  46. // internal class definitions
  47. class LLVFSBlock
  48. {
  49. public:
  50. LLVFSBlock()
  51. {
  52. mLocation = 0;
  53. mLength = 0;
  54. }
  55. LLVFSBlock(U32 loc, S32 size)
  56. {
  57. mLocation = loc;
  58. mLength = size;
  59. }
  60. static bool locationSortPredicate(
  61. const LLVFSBlock* lhs,
  62. const LLVFSBlock* rhs)
  63. {
  64. return lhs->mLocation < rhs->mLocation;
  65. }
  66. public:
  67. U32 mLocation;
  68. S32 mLength; // allocated block size
  69. };
  70. LLVFSFileSpecifier::LLVFSFileSpecifier()
  71. : mFileID(),
  72. mFileType( LLAssetType::AT_NONE )
  73. {
  74. }
  75. LLVFSFileSpecifier::LLVFSFileSpecifier(const LLUUID &file_id, const LLAssetType::EType file_type)
  76. {
  77. mFileID = file_id;
  78. mFileType = file_type;
  79. }
  80. bool LLVFSFileSpecifier::operator<(const LLVFSFileSpecifier &rhs) const
  81. {
  82. return (mFileID == rhs.mFileID)
  83. ? mFileType < rhs.mFileType
  84. : mFileID < rhs.mFileID;
  85. }
  86. bool LLVFSFileSpecifier::operator==(const LLVFSFileSpecifier &rhs) const
  87. {
  88. return (mFileID == rhs.mFileID &&
  89. mFileType == rhs.mFileType);
  90. }
  91. class LLVFSFileBlock : public LLVFSBlock, public LLVFSFileSpecifier
  92. {
  93. public:
  94. LLVFSFileBlock() : LLVFSBlock(), LLVFSFileSpecifier()
  95. {
  96. init();
  97. }
  98. LLVFSFileBlock(const LLUUID &file_id, LLAssetType::EType file_type, U32 loc = 0, S32 size = 0)
  99. : LLVFSBlock(loc, size), LLVFSFileSpecifier( file_id, file_type )
  100. {
  101. init();
  102. }
  103. void init()
  104. {
  105. mSize = 0;
  106. mIndexLocation = -1;
  107. mAccessTime = (U32)time(NULL);
  108. for (S32 i = 0; i < (S32)VFSLOCK_COUNT; i++)
  109. {
  110. mLocks[(EVFSLock)i] = 0;
  111. }
  112. }
  113. #ifdef LL_LITTLE_ENDIAN
  114. inline void swizzleCopy(void *dst, void *src, int size) { memcpy(dst, src, size); /* Flawfinder: ignore */}
  115. #else
  116. inline U32 swizzle32(U32 x)
  117. {
  118. return(((x >> 24) & 0x000000FF) | ((x >> 8) & 0x0000FF00) | ((x << 8) & 0x00FF0000) |((x << 24) & 0xFF000000));
  119. }
  120. inline U16 swizzle16(U16 x)
  121. {
  122. return( ((x >> 8) & 0x000000FF) | ((x << 8) & 0x0000FF00) );
  123. }
  124. inline void swizzleCopy(void *dst, void *src, int size)
  125. {
  126. if(size == 4)
  127. {
  128. ((U32*)dst)[0] = swizzle32(((U32*)src)[0]);
  129. }
  130. else if(size == 2)
  131. {
  132. ((U16*)dst)[0] = swizzle16(((U16*)src)[0]);
  133. }
  134. else
  135. {
  136. // Perhaps this should assert...
  137. memcpy(dst, src, size); /* Flawfinder: ignore */
  138. }
  139. }
  140. #endif
  141. void serialize(U8 *buffer)
  142. {
  143. swizzleCopy(buffer, &mLocation, 4);
  144. buffer += 4;
  145. swizzleCopy(buffer, &mLength, 4);
  146. buffer +=4;
  147. swizzleCopy(buffer, &mAccessTime, 4);
  148. buffer +=4;
  149. memcpy(buffer, &mFileID.mData, 16); /* Flawfinder: ignore */
  150. buffer += 16;
  151. S16 temp_type = mFileType;
  152. swizzleCopy(buffer, &temp_type, 2);
  153. buffer += 2;
  154. swizzleCopy(buffer, &mSize, 4);
  155. }
  156. void deserialize(U8 *buffer, const S32 index_loc)
  157. {
  158. mIndexLocation = index_loc;
  159. swizzleCopy(&mLocation, buffer, 4);
  160. buffer += 4;
  161. swizzleCopy(&mLength, buffer, 4);
  162. buffer += 4;
  163. swizzleCopy(&mAccessTime, buffer, 4);
  164. buffer += 4;
  165. memcpy(&mFileID.mData, buffer, 16);
  166. buffer += 16;
  167. S16 temp_type;
  168. swizzleCopy(&temp_type, buffer, 2);
  169. mFileType = (LLAssetType::EType)temp_type;
  170. buffer += 2;
  171. swizzleCopy(&mSize, buffer, 4);
  172. }
  173. static BOOL insertLRU(LLVFSFileBlock* const& first,
  174. LLVFSFileBlock* const& second)
  175. {
  176. return (first->mAccessTime == second->mAccessTime)
  177. ? *first < *second
  178. : first->mAccessTime < second->mAccessTime;
  179. }
  180. public:
  181. S32 mSize;
  182. S32 mIndexLocation; // location of index entry
  183. U32 mAccessTime;
  184. BOOL mLocks[VFSLOCK_COUNT]; // number of outstanding locks of each type
  185. static const S32 SERIAL_SIZE;
  186. };
  187. // Helper structure for doing lru w/ stl... is there a simpler way?
  188. struct LLVFSFileBlock_less
  189. {
  190. bool operator()(LLVFSFileBlock* const& lhs, LLVFSFileBlock* const& rhs) const
  191. {
  192. return (LLVFSFileBlock::insertLRU(lhs, rhs)) ? true : false;
  193. }
  194. };
  195. const S32 LLVFSFileBlock::SERIAL_SIZE = 34;
  196. LLVFS::LLVFS(const std::string& index_filename, const std::string& data_filename, const BOOL read_only, const U32 presize, const BOOL remove_after_crash)
  197. : mRemoveAfterCrash(remove_after_crash),
  198. mDataFP(NULL),
  199. mIndexFP(NULL)
  200. {
  201. mDataMutex = new LLMutex(0);
  202. S32 i;
  203. for (i = 0; i < VFSLOCK_COUNT; i++)
  204. {
  205. mLockCounts[i] = 0;
  206. }
  207. mValid = VFSVALID_OK;
  208. mReadOnly = read_only;
  209. mIndexFilename = index_filename;
  210. mDataFilename = data_filename;
  211. const char *file_mode = mReadOnly ? "rb" : "r+b";
  212. LL_INFOS("VFS") << "Attempting to open VFS index file " << mIndexFilename << LL_ENDL;
  213. LL_INFOS("VFS") << "Attempting to open VFS data file " << mDataFilename << LL_ENDL;
  214. mDataFP = openAndLock(mDataFilename, file_mode, mReadOnly);
  215. if (!mDataFP)
  216. {
  217. if (mReadOnly)
  218. {
  219. LL_WARNS("VFS") << "Can't find " << mDataFilename << " to open read-only VFS" << LL_ENDL;
  220. mValid = VFSVALID_BAD_CANNOT_OPEN_READONLY;
  221. return;
  222. }
  223. mDataFP = openAndLock(mDataFilename, "w+b", FALSE);
  224. if (mDataFP)
  225. {
  226. // Since we're creating this data file, assume any index file is bogus
  227. // remove the index, since this vfs is now blank
  228. LLFile::remove(mIndexFilename);
  229. }
  230. else
  231. {
  232. LL_WARNS("VFS") << "Couldn't open vfs data file "
  233. << mDataFilename << LL_ENDL;
  234. mValid = VFSVALID_BAD_CANNOT_CREATE;
  235. return;
  236. }
  237. if (presize)
  238. {
  239. presizeDataFile(presize);
  240. }
  241. }
  242. // Did we leave this file open for writing last time?
  243. // If so, close it and start over.
  244. if (!mReadOnly && mRemoveAfterCrash)
  245. {
  246. llstat marker_info;
  247. std::string marker = mDataFilename + ".open";
  248. if (!LLFile::stat(marker, &marker_info))
  249. {
  250. // marker exists, kill the lock and the VFS files
  251. unlockAndClose(mDataFP);
  252. mDataFP = NULL;
  253. LL_WARNS("VFS") << "VFS: File left open on last run, removing old VFS file " << mDataFilename << LL_ENDL;
  254. LLFile::remove(mIndexFilename);
  255. LLFile::remove(mDataFilename);
  256. LLFile::remove(marker);
  257. mDataFP = openAndLock(mDataFilename, "w+b", FALSE);
  258. if (!mDataFP)
  259. {
  260. LL_WARNS("VFS") << "Can't open VFS data file in crash recovery" << LL_ENDL;
  261. mValid = VFSVALID_BAD_CANNOT_CREATE;
  262. return;
  263. }
  264. if (presize)
  265. {
  266. presizeDataFile(presize);
  267. }
  268. }
  269. }
  270. // determine the real file size
  271. fseek(mDataFP, 0, SEEK_END);
  272. U32 data_size = ftell(mDataFP);
  273. // read the index file
  274. // make sure there's at least one file in it too
  275. // if not, we'll treat this as a new vfs
  276. llstat fbuf;
  277. if (! LLFile::stat(mIndexFilename, &fbuf) &&
  278. fbuf.st_size >= LLVFSFileBlock::SERIAL_SIZE &&
  279. (mIndexFP = openAndLock(mIndexFilename, file_mode, mReadOnly)) // Yes, this is an assignment and not '=='
  280. )
  281. {
  282. std::vector<U8> buffer(fbuf.st_size);
  283. size_t buf_offset = 0;
  284. size_t nread = fread(&buffer[0], 1, fbuf.st_size, mIndexFP);
  285. std::vector<LLVFSFileBlock*> files_by_loc;
  286. while (buf_offset < nread)
  287. {
  288. LLVFSFileBlock *block = new LLVFSFileBlock();
  289. block->deserialize(&buffer[buf_offset], (S32)buf_offset);
  290. // Do sanity check on this block.
  291. // Note that this skips zero size blocks, which helps VFS
  292. // to heal after some errors. JC
  293. if (block->mLength > 0 &&
  294. (U32)block->mLength <= data_size &&
  295. block->mLocation < data_size &&
  296. block->mSize > 0 &&
  297. block->mSize <= block->mLength &&
  298. block->mFileType >= LLAssetType::AT_NONE &&
  299. block->mFileType < LLAssetType::AT_COUNT)
  300. {
  301. mFileBlocks.insert(fileblock_map::value_type(*block, block));
  302. files_by_loc.push_back(block);
  303. }
  304. else
  305. if (block->mLength && block->mSize > 0)
  306. {
  307. // this is corrupt, not empty
  308. LL_WARNS("VFS") << "VFS corruption: " << block->mFileID << " (" << block->mFileType << ") at index " << block->mIndexLocation << " DS: " << data_size << LL_ENDL;
  309. LL_WARNS("VFS") << "Length: " << block->mLength << "\tLocation: " << block->mLocation << "\tSize: " << block->mSize << LL_ENDL;
  310. LL_WARNS("VFS") << "File has bad data - VFS removed" << LL_ENDL;
  311. delete block;
  312. unlockAndClose( mIndexFP );
  313. mIndexFP = NULL;
  314. LLFile::remove( mIndexFilename );
  315. unlockAndClose( mDataFP );
  316. mDataFP = NULL;
  317. LLFile::remove( mDataFilename );
  318. LL_WARNS("VFS") << "Deleted corrupt VFS files "
  319. << mDataFilename
  320. << " and "
  321. << mIndexFilename
  322. << LL_ENDL;
  323. mValid = VFSVALID_BAD_CORRUPT;
  324. return;
  325. }
  326. else
  327. {
  328. // this is a null or bad entry, skip it
  329. mIndexHoles.push_back(buf_offset);
  330. delete block;
  331. }
  332. buf_offset += LLVFSFileBlock::SERIAL_SIZE;
  333. }
  334. std::sort(
  335. files_by_loc.begin(),
  336. files_by_loc.end(),
  337. LLVFSFileBlock::locationSortPredicate);
  338. // There are 3 cases that have to be considered.
  339. // 1. No blocks
  340. // 2. One block.
  341. // 3. Two or more blocks.
  342. if (!files_by_loc.empty())
  343. {
  344. // cur walks through the list.
  345. std::vector<LLVFSFileBlock*>::iterator cur = files_by_loc.begin();
  346. std::vector<LLVFSFileBlock*>::iterator end = files_by_loc.end();
  347. LLVFSFileBlock* last_file_block = *cur;
  348. // Check to see if there is an empty space before the first file.
  349. if (last_file_block->mLocation > 0)
  350. {
  351. // If so, create a free block.
  352. addFreeBlock(new LLVFSBlock(0, last_file_block->mLocation));
  353. }
  354. // Walk through the 2nd+ block. If there is a free space
  355. // between cur_file_block and last_file_block, add it to
  356. // the free space collection. This block will not need to
  357. // run in the case there is only one entry in the VFS.
  358. ++cur;
  359. while( cur != end )
  360. {
  361. LLVFSFileBlock* cur_file_block = *cur;
  362. // Dupe check on the block
  363. if (cur_file_block->mLocation == last_file_block->mLocation
  364. && cur_file_block->mLength == last_file_block->mLength)
  365. {
  366. LL_WARNS("VFS") << "VFS: removing duplicate entry"
  367. << " at " << cur_file_block->mLocation
  368. << " length " << cur_file_block->mLength
  369. << " size " << cur_file_block->mSize
  370. << " ID " << cur_file_block->mFileID
  371. << " type " << cur_file_block->mFileType
  372. << LL_ENDL;
  373. // Duplicate entries. Nuke them both for safety.
  374. mFileBlocks.erase(*cur_file_block); // remove ID/type entry
  375. if (cur_file_block->mLength > 0)
  376. {
  377. // convert to hole
  378. addFreeBlock(
  379. new LLVFSBlock(
  380. cur_file_block->mLocation,
  381. cur_file_block->mLength));
  382. }
  383. lockData(); // needed for sync()
  384. sync(cur_file_block, TRUE); // remove first on disk
  385. sync(last_file_block, TRUE); // remove last on disk
  386. unlockData(); // needed for sync()
  387. last_file_block = cur_file_block;
  388. ++cur;
  389. continue;
  390. }
  391. // Figure out where the last block ended.
  392. S32 loc = last_file_block->mLocation+last_file_block->mLength;
  393. // Figure out how much space there is between where
  394. // the last block ended and this block begins.
  395. S32 length = cur_file_block->mLocation - loc;
  396. // Check for more errors... Seeing if the current
  397. // entry and the last entry make sense together.
  398. if (length < 0 || loc < 0 || (U32)loc > data_size)
  399. {
  400. // Invalid VFS
  401. unlockAndClose( mIndexFP );
  402. mIndexFP = NULL;
  403. LLFile::remove( mIndexFilename );
  404. unlockAndClose( mDataFP );
  405. mDataFP = NULL;
  406. LLFile::remove( mDataFilename );
  407. LL_WARNS("VFS") << "VFS: overlapping entries"
  408. << " at " << cur_file_block->mLocation
  409. << " length " << cur_file_block->mLength
  410. << " ID " << cur_file_block->mFileID
  411. << " type " << cur_file_block->mFileType
  412. << LL_ENDL;
  413. LL_WARNS("VFS") << "Deleted corrupt VFS files "
  414. << mDataFilename
  415. << " and "
  416. << mIndexFilename
  417. << LL_ENDL;
  418. mValid = VFSVALID_BAD_CORRUPT;
  419. return;
  420. }
  421. // we don't want to add empty blocks to the list...
  422. if (length > 0)
  423. {
  424. addFreeBlock(new LLVFSBlock(loc, length));
  425. }
  426. last_file_block = cur_file_block;
  427. ++cur;
  428. }
  429. // also note any empty space at the end
  430. U32 loc = last_file_block->mLocation + last_file_block->mLength;
  431. if (loc < data_size)
  432. {
  433. addFreeBlock(new LLVFSBlock(loc, data_size - loc));
  434. }
  435. }
  436. else // There where no blocks in the file.
  437. {
  438. addFreeBlock(new LLVFSBlock(0, data_size));
  439. }
  440. }
  441. else // Pre-existing index file wasn't opened
  442. {
  443. if (mReadOnly)
  444. {
  445. LL_WARNS("VFS") << "Can't find " << mIndexFilename << " to open read-only VFS" << LL_ENDL;
  446. mValid = VFSVALID_BAD_CANNOT_OPEN_READONLY;
  447. return;
  448. }
  449. mIndexFP = openAndLock(mIndexFilename, "w+b", FALSE);
  450. if (!mIndexFP)
  451. {
  452. LL_WARNS("VFS") << "Couldn't open an index file for the VFS, probably a sharing violation!" << LL_ENDL;
  453. unlockAndClose( mDataFP );
  454. mDataFP = NULL;
  455. LLFile::remove( mDataFilename );
  456. mValid = VFSVALID_BAD_CANNOT_CREATE;
  457. return;
  458. }
  459. // no index file, start from scratch w/ 1GB allocation
  460. LLVFSBlock *first_block = new LLVFSBlock(0, data_size ? data_size : 0x40000000);
  461. addFreeBlock(first_block);
  462. }
  463. // Open marker file to look for bad shutdowns
  464. if (!mReadOnly && mRemoveAfterCrash)
  465. {
  466. std::string marker = mDataFilename + ".open";
  467. LLFILE* marker_fp = LLFile::fopen(marker, "w"); /* Flawfinder: ignore */
  468. if (marker_fp)
  469. {
  470. fclose(marker_fp);
  471. marker_fp = NULL;
  472. }
  473. }
  474. LL_INFOS("VFS") << "Using VFS index file " << mIndexFilename << LL_ENDL;
  475. LL_INFOS("VFS") << "Using VFS data file " << mDataFilename << LL_ENDL;
  476. mValid = VFSVALID_OK;
  477. }
  478. LLVFS::~LLVFS()
  479. {
  480. if (mDataMutex->isLocked())
  481. {
  482. LL_ERRS("VFS") << "LLVFS destroyed with mutex locked" << LL_ENDL;
  483. }
  484. unlockAndClose(mIndexFP);
  485. mIndexFP = NULL;
  486. fileblock_map::const_iterator it;
  487. for (it = mFileBlocks.begin(); it != mFileBlocks.end(); ++it)
  488. {
  489. delete (*it).second;
  490. }
  491. mFileBlocks.clear();
  492. mFreeBlocksByLength.clear();
  493. for_each(mFreeBlocksByLocation.begin(), mFreeBlocksByLocation.end(), DeletePairedPointer());
  494. unlockAndClose(mDataFP);
  495. mDataFP = NULL;
  496. // Remove marker file
  497. if (!mReadOnly && mRemoveAfterCrash)
  498. {
  499. std::string marker = mDataFilename + ".open";
  500. LLFile::remove(marker);
  501. }
  502. delete mDataMutex;
  503. }
  504. // Use this function normally to create LLVFS files.
  505. // Will append digits to the end of the filename with multiple re-trys
  506. // static
  507. LLVFS * LLVFS::createLLVFS(const std::string& index_filename,
  508. const std::string& data_filename,
  509. const BOOL read_only,
  510. const U32 presize,
  511. const BOOL remove_after_crash)
  512. {
  513. LLVFS * new_vfs = new LLVFS(index_filename, data_filename, read_only, presize, remove_after_crash);
  514. if( !new_vfs->isValid() )
  515. { // First name failed, retry with new names
  516. std::string retry_vfs_index_name;
  517. std::string retry_vfs_data_name;
  518. S32 count = 0;
  519. while (!new_vfs->isValid() &&
  520. count < 256)
  521. { // Append '.<number>' to end of filenames
  522. retry_vfs_index_name = index_filename + llformat(".%u",count);
  523. retry_vfs_data_name = data_filename + llformat(".%u", count);
  524. delete new_vfs; // Delete bad VFS and try again
  525. new_vfs = new LLVFS(retry_vfs_index_name, retry_vfs_data_name, read_only, presize, remove_after_crash);
  526. count++;
  527. }
  528. }
  529. if( !new_vfs->isValid() )
  530. {
  531. delete new_vfs; // Delete bad VFS
  532. new_vfs = NULL; // Total failure
  533. }
  534. return new_vfs;
  535. }
  536. void LLVFS::presizeDataFile(const U32 size)
  537. {
  538. if (!mDataFP)
  539. {
  540. llerrs << "LLVFS::presizeDataFile() with no data file open" << llendl;
  541. return;
  542. }
  543. // we're creating this file for the first time, size it
  544. fseek(mDataFP, size-1, SEEK_SET);
  545. S32 tmp = 0;
  546. tmp = (S32)fwrite(&tmp, 1, 1, mDataFP);
  547. // fflush(mDataFP);
  548. // also remove any index, since this vfs is now blank
  549. LLFile::remove(mIndexFilename);
  550. if (tmp)
  551. {
  552. llinfos << "Pre-sized VFS data file to " << ftell(mDataFP) << " bytes" << llendl;
  553. }
  554. else
  555. {
  556. llwarns << "Failed to pre-size VFS data file" << llendl;
  557. }
  558. }
  559. BOOL LLVFS::getExists(const LLUUID &file_id, const LLAssetType::EType file_type)
  560. {
  561. LLVFSFileBlock *block = NULL;
  562. if (!isValid())
  563. {
  564. llerrs << "Attempting to use invalid VFS!" << llendl;
  565. }
  566. lockData();
  567. LLVFSFileSpecifier spec(file_id, file_type);
  568. fileblock_map::iterator it = mFileBlocks.find(spec);
  569. if (it != mFileBlocks.end())
  570. {
  571. block = (*it).second;
  572. block->mAccessTime = (U32)time(NULL);
  573. }
  574. BOOL res = (block && block->mLength > 0) ? TRUE : FALSE;
  575. unlockData();
  576. return res;
  577. }
  578. S32 LLVFS::getSize(const LLUUID &file_id, const LLAssetType::EType file_type)
  579. {
  580. S32 size = 0;
  581. if (!isValid())
  582. {
  583. llerrs << "Attempting to use invalid VFS!" << llendl;
  584. }
  585. lockData();
  586. LLVFSFileSpecifier spec(file_id, file_type);
  587. fileblock_map::iterator it = mFileBlocks.find(spec);
  588. if (it != mFileBlocks.end())
  589. {
  590. LLVFSFileBlock *block = (*it).second;
  591. block->mAccessTime = (U32)time(NULL);
  592. size = block->mSize;
  593. }
  594. unlockData();
  595. return size;
  596. }
  597. S32 LLVFS::getMaxSize(const LLUUID &file_id, const LLAssetType::EType file_type)
  598. {
  599. S32 size = 0;
  600. if (!isValid())
  601. {
  602. llerrs << "Attempting to use invalid VFS!" << llendl;
  603. }
  604. lockData();
  605. LLVFSFileSpecifier spec(file_id, file_type);
  606. fileblock_map::iterator it = mFileBlocks.find(spec);
  607. if (it != mFileBlocks.end())
  608. {
  609. LLVFSFileBlock *block = (*it).second;
  610. block->mAccessTime = (U32)time(NULL);
  611. size = block->mLength;
  612. }
  613. unlockData();
  614. return size;
  615. }
  616. BOOL LLVFS::checkAvailable(S32 max_size)
  617. {
  618. lockData();
  619. blocks_length_map_t::iterator iter = mFreeBlocksByLength.lower_bound(max_size); // first entry >= size
  620. const BOOL res(iter == mFreeBlocksByLength.end() ? FALSE : TRUE);
  621. unlockData();
  622. return res;
  623. }
  624. BOOL LLVFS::setMaxSize(const LLUUID &file_id, const LLAssetType::EType file_type, S32 max_size)
  625. {
  626. if (!isValid())
  627. {
  628. llerrs << "Attempting to use invalid VFS!" << llendl;
  629. }
  630. if (mReadOnly)
  631. {
  632. llerrs << "Attempt to write to read-only VFS" << llendl;
  633. }
  634. if (max_size <= 0)
  635. {
  636. llwarns << "VFS: Attempt to assign size " << max_size << " to vfile " << file_id << llendl;
  637. return FALSE;
  638. }
  639. lockData();
  640. LLVFSFileSpecifier spec(file_id, file_type);
  641. LLVFSFileBlock *block = NULL;
  642. fileblock_map::iterator it = mFileBlocks.find(spec);
  643. if (it != mFileBlocks.end())
  644. {
  645. block = (*it).second;
  646. }
  647. // round all sizes upward to KB increments
  648. // SJB: Need to not round for the new texture-pipeline code so we know the correct
  649. // max file size. Need to investigate the potential problems with this...
  650. if (file_type != LLAssetType::AT_TEXTURE)
  651. {
  652. if (max_size & FILE_BLOCK_MASK)
  653. {
  654. max_size += FILE_BLOCK_MASK;
  655. max_size &= ~FILE_BLOCK_MASK;
  656. }
  657. }
  658. if (block && block->mLength > 0)
  659. {
  660. block->mAccessTime = (U32)time(NULL);
  661. if (max_size == block->mLength)
  662. {
  663. unlockData();
  664. return TRUE;
  665. }
  666. else if (max_size < block->mLength)
  667. {
  668. // this file is shrinking
  669. LLVFSBlock *free_block = new LLVFSBlock(block->mLocation + max_size, block->mLength - max_size);
  670. addFreeBlock(free_block);
  671. block->mLength = max_size;
  672. if (block->mLength < block->mSize)
  673. {
  674. // JC: Was a warning, but Ian says it's bad.
  675. llerrs << "Truncating virtual file " << file_id << " to " << block->mLength << " bytes" << llendl;
  676. block->mSize = block->mLength;
  677. }
  678. sync(block);
  679. //mergeFreeBlocks();
  680. unlockData();
  681. return TRUE;
  682. }
  683. else if (max_size > block->mLength)
  684. {
  685. // this file is growing
  686. // first check for an adjacent free block to grow into
  687. S32 size_increase = max_size - block->mLength;
  688. // Find the first free block with and addres > block->mLocation
  689. LLVFSBlock *free_block;
  690. blocks_location_map_t::iterator iter = mFreeBlocksByLocation.upper_bound(block->mLocation);
  691. if (iter != mFreeBlocksByLocation.end())
  692. {
  693. free_block = iter->second;
  694. if (free_block->mLocation == block->mLocation + block->mLength &&
  695. free_block->mLength >= size_increase)
  696. {
  697. // this free block is at the end of the file and is large enough
  698. // Must call useFreeSpace before sync(), as sync()
  699. // unlocks data structures.
  700. useFreeSpace(free_block, size_increase);
  701. block->mLength += size_increase;
  702. sync(block);
  703. unlockData();
  704. return TRUE;
  705. }
  706. }
  707. // no adjecent free block, find one in the list
  708. free_block = findFreeBlock(max_size, block);
  709. if (free_block)
  710. {
  711. // Save location where data is going, useFreeSpace will move free_block->mLocation;
  712. U32 new_data_location = free_block->mLocation;
  713. //mark the free block as used so it does not
  714. //interfere with other operations such as addFreeBlock
  715. useFreeSpace(free_block, max_size); // useFreeSpace takes ownership (and may delete) free_block
  716. if (block->mLength > 0)
  717. {
  718. // create a new free block where this file used to be
  719. LLVFSBlock *new_free_block = new LLVFSBlock(block->mLocation, block->mLength);
  720. addFreeBlock(new_free_block);
  721. if (block->mSize > 0)
  722. {
  723. // move the file into the new block
  724. std::vector<U8> buffer(block->mSize);
  725. fseek(mDataFP, block->mLocation, SEEK_SET);
  726. if (fread(&buffer[0], block->mSize, 1, mDataFP) == 1)
  727. {
  728. fseek(mDataFP, new_data_location, SEEK_SET);
  729. if (fwrite(&buffer[0], block->mSize, 1, mDataFP) != 1)
  730. {
  731. llwarns << "Short write" << llendl;
  732. }
  733. } else {
  734. llwarns << "Short read" << llendl;
  735. }
  736. }
  737. }
  738. block->mLocation = new_data_location;
  739. block->mLength = max_size;
  740. sync(block);
  741. unlockData();
  742. return TRUE;
  743. }
  744. else
  745. {
  746. llwarns << "VFS: No space (" << max_size << ") to resize existing vfile " << file_id << llendl;
  747. //dumpMap();
  748. unlockData();
  749. dumpStatistics();
  750. return FALSE;
  751. }
  752. }
  753. }
  754. else
  755. {
  756. // find a free block in the list
  757. LLVFSBlock *free_block = findFreeBlock(max_size);
  758. if (free_block)
  759. {
  760. if (block)
  761. {
  762. block->mLocation = free_block->mLocation;
  763. block->mLength = max_size;
  764. }
  765. else
  766. {
  767. // this file doesn't exist, create it
  768. block = new LLVFSFileBlock(file_id, file_type, free_block->mLocation, max_size);
  769. mFileBlocks.insert(fileblock_map::value_type(spec, block));
  770. }
  771. // Must call useFreeSpace before sync(), as sync()
  772. // unlocks data structures.
  773. useFreeSpace(free_block, max_size);
  774. block->mAccessTime = (U32)time(NULL);
  775. sync(block);
  776. }
  777. else
  778. {
  779. llwarns << "VFS: No space (" << max_size << ") for new virtual file " << file_id << llendl;
  780. //dumpMap();
  781. unlockData();
  782. dumpStatistics();
  783. return FALSE;
  784. }
  785. }
  786. unlockData();
  787. return TRUE;
  788. }
  789. // WARNING: HERE BE DRAGONS!
  790. // rename is the weirdest VFS op, because the file moves but the locks don't!
  791. void LLVFS::renameFile(const LLUUID &file_id, const LLAssetType::EType file_type,
  792. const LLUUID &new_id, const LLAssetType::EType &new_type)
  793. {
  794. if (!isValid())
  795. {
  796. llerrs << "Attempting to use invalid VFS!" << llendl;
  797. }
  798. if (mReadOnly)
  799. {
  800. llerrs << "Attempt to write to read-only VFS" << llendl;
  801. }
  802. lockData();
  803. LLVFSFileSpecifier new_spec(new_id, new_type);
  804. LLVFSFileSpecifier old_spec(file_id, file_type);
  805. fileblock_map::iterator it = mFileBlocks.find(old_spec);
  806. if (it != mFileBlocks.end())
  807. {
  808. LLVFSFileBlock *src_block = (*it).second;
  809. // this will purge the data but leave the file block in place, w/ locks, if any
  810. // WAS: removeFile(new_id, new_type); NOW uses removeFileBlock() to avoid mutex lock recursion
  811. fileblock_map::iterator new_it = mFileBlocks.find(new_spec);
  812. if (new_it != mFileBlocks.end())
  813. {
  814. LLVFSFileBlock *new_block = (*new_it).second;
  815. removeFileBlock(new_block);
  816. }
  817. // if there's something in the target location, remove it but inherit its locks
  818. it = mFileBlocks.find(new_spec);
  819. if (it != mFileBlocks.end())
  820. {
  821. LLVFSFileBlock *dest_block = (*it).second;
  822. for (S32 i = 0; i < (S32)VFSLOCK_COUNT; i++)
  823. {
  824. if(dest_block->mLocks[i])
  825. {
  826. llerrs << "Renaming VFS block to a locked file." << llendl;
  827. }
  828. dest_block->mLocks[i] = src_block->mLocks[i];
  829. }
  830. mFileBlocks.erase(new_spec);
  831. delete dest_block;
  832. }
  833. src_block->mFileID = new_id;
  834. src_block->mFileType = new_type;
  835. src_block->mAccessTime = (U32)time(NULL);
  836. mFileBlocks.erase(old_spec);
  837. mFileBlocks.insert(fileblock_map::value_type(new_spec, src_block));
  838. sync(src_block);
  839. }
  840. else
  841. {
  842. llwarns << "VFS: Attempt to rename nonexistent vfile " << file_id << ":" << file_type << llendl;
  843. }
  844. unlockData();
  845. }
  846. // mDataMutex must be LOCKED before calling this
  847. void LLVFS::removeFileBlock(LLVFSFileBlock *fileblock)
  848. {
  849. // convert this into an unsaved, dummy fileblock to preserve locks
  850. // a more rubust solution would store the locks in a seperate data structure
  851. sync(fileblock, TRUE);
  852. if (fileblock->mLength > 0)
  853. {
  854. // turn this file into an empty block
  855. LLVFSBlock *free_block = new LLVFSBlock(fileblock->mLocation, fileblock->mLength);
  856. addFreeBlock(free_block);
  857. }
  858. fileblock->mLocation = 0;
  859. fileblock->mSize = 0;
  860. fileblock->mLength = BLOCK_LENGTH_INVALID;
  861. fileblock->mIndexLocation = -1;
  862. //mergeFreeBlocks();
  863. }
  864. void LLVFS::removeFile(const LLUUID &file_id, const LLAssetType::EType file_type)
  865. {
  866. if (!isValid())
  867. {
  868. llerrs << "Attempting to use invalid VFS!" << llendl;
  869. }
  870. if (mReadOnly)
  871. {
  872. llerrs << "Attempt to write to read-only VFS" << llendl;
  873. }
  874. lockData();
  875. LLVFSFileSpecifier spec(file_id, file_type);
  876. fileblock_map::iterator it = mFileBlocks.find(spec);
  877. if (it != mFileBlocks.end())
  878. {
  879. LLVFSFileBlock *block = (*it).second;
  880. removeFileBlock(block);
  881. }
  882. else
  883. {
  884. llwarns << "VFS: attempting to remove nonexistent file " << file_id << " type " << file_type << llendl;
  885. }
  886. unlockData();
  887. }
  888. S32 LLVFS::getData(const LLUUID &file_id, const LLAssetType::EType file_type, U8 *buffer, S32 location, S32 length)
  889. {
  890. S32 bytesread = 0;
  891. if (!isValid())
  892. {
  893. llerrs << "Attempting to use invalid VFS!" << llendl;
  894. }
  895. llassert(location >= 0);
  896. llassert(length >= 0);
  897. BOOL do_read = FALSE;
  898. lockData();
  899. LLVFSFileSpecifier spec(file_id, file_type);
  900. fileblock_map::iterator it = mFileBlocks.find(spec);
  901. if (it != mFileBlocks.end())
  902. {
  903. LLVFSFileBlock *block = (*it).second;
  904. block->mAccessTime = (U32)time(NULL);
  905. if (location > block->mSize)
  906. {
  907. llwarns << "VFS: Attempt to read location " << location << " in file " << file_id << " of length " << block->mSize << llendl;
  908. }
  909. else
  910. {
  911. if (length > block->mSize - location)
  912. {
  913. length = block->mSize - location;
  914. }
  915. location += block->mLocation;
  916. do_read = TRUE;
  917. }
  918. }
  919. if (do_read)
  920. {
  921. fseek(mDataFP, location, SEEK_SET);
  922. bytesread = (S32)fread(buffer, 1, length, mDataFP);
  923. }
  924. unlockData();
  925. return bytesread;
  926. }
  927. S32 LLVFS::storeData(const LLUUID &file_id, const LLAssetType::EType file_type, const U8 *buffer, S32 location, S32 length)
  928. {
  929. if (!isValid())
  930. {
  931. llerrs << "Attempting to use invalid VFS!" << llendl;
  932. }
  933. if (mReadOnly)
  934. {
  935. llerrs << "Attempt to write to read-only VFS" << llendl;
  936. }
  937. llassert(length > 0);
  938. lockData();
  939. LLVFSFileSpecifier spec(file_id, file_type);
  940. fileblock_map::iterator it = mFileBlocks.find(spec);
  941. if (it != mFileBlocks.end())
  942. {
  943. LLVFSFileBlock *block = (*it).second;
  944. S32 in_loc = location;
  945. if (location == -1)
  946. {
  947. location = block->mSize;
  948. }
  949. llassert(location >= 0);
  950. block->mAccessTime = (U32)time(NULL);
  951. if (block->mLength == BLOCK_LENGTH_INVALID)
  952. {
  953. // Block was removed, ignore write
  954. llwarns << "VFS: Attempt to write to invalid block"
  955. << " in file " << file_id
  956. << " location: " << in_loc
  957. << " bytes: " << length
  958. << llendl;
  959. unlockData();
  960. return length;
  961. }
  962. else if (location > block->mLength)
  963. {
  964. llwarns << "VFS: Attempt to write to location " << location
  965. << " in file " << file_id
  966. << " type " << S32(file_type)
  967. << " of size " << block->mSize
  968. << " block length " << block->mLength
  969. << llendl;
  970. unlockData();
  971. return length;
  972. }
  973. else
  974. {
  975. if (length > block->mLength - location )
  976. {
  977. llwarns << "VFS: Truncating write to virtual file " << file_id << " type " << S32(file_type) << llendl;
  978. length = block->mLength - location;
  979. }
  980. U32 file_location = location + block->mLocation;
  981. fseek(mDataFP, file_location, SEEK_SET);
  982. S32 write_len = (S32)fwrite(buffer, 1, length, mDataFP);
  983. if (write_len != length)
  984. {
  985. llwarns << llformat("VFS Write Error: %d != %d",write_len,length) << llendl;
  986. }
  987. // fflush(mDataFP);
  988. if (location + length > block->mSize)
  989. {
  990. block->mSize = location + write_len;
  991. sync(block);
  992. }
  993. unlockData();
  994. return write_len;
  995. }
  996. }
  997. else
  998. {
  999. unlockData();
  1000. return 0;
  1001. }
  1002. }
  1003. void LLVFS::incLock(const LLUUID &file_id, const LLAssetType::EType file_type, EVFSLock lock)
  1004. {
  1005. lockData();
  1006. LLVFSFileSpecifier spec(file_id, file_type);
  1007. LLVFSFileBlock *block;
  1008. fileblock_map::iterator it = mFileBlocks.find(spec);
  1009. if (it != mFileBlocks.end())
  1010. {
  1011. block = (*it).second;
  1012. }
  1013. else
  1014. {
  1015. // Create a dummy block which isn't saved
  1016. block = new LLVFSFileBlock(file_id, file_type, 0, BLOCK_LENGTH_INVALID);
  1017. block->mAccessTime = (U32)time(NULL);
  1018. mFileBlocks.insert(fileblock_map::value_type(spec, block));
  1019. }
  1020. block->mLocks[lock]++;
  1021. mLockCounts[lock]++;
  1022. unlockData();
  1023. }
  1024. void LLVFS::decLock(const LLUUID &file_id, const LLAssetType::EType file_type, EVFSLock lock)
  1025. {
  1026. lockData();
  1027. LLVFSFileSpecifier spec(file_id, file_type);
  1028. fileblock_map::iterator it = mFileBlocks.find(spec);
  1029. if (it != mFileBlocks.end())
  1030. {
  1031. LLVFSFileBlock *block = (*it).second;
  1032. if (block->mLocks[lock] > 0)
  1033. {
  1034. block->mLocks[lock]--;
  1035. }
  1036. else
  1037. {
  1038. llwarns << "VFS: Decrementing zero-value lock " << lock << llendl;
  1039. }
  1040. mLockCounts[lock]--;
  1041. }
  1042. unlockData();
  1043. }
  1044. BOOL LLVFS::isLocked(const LLUUID &file_id, const LLAssetType::EType file_type, EVFSLock lock)
  1045. {
  1046. lockData();
  1047. BOOL res = FALSE;
  1048. LLVFSFileSpecifier spec(file_id, file_type);
  1049. fileblock_map::iterator it = mFileBlocks.find(spec);
  1050. if (it != mFileBlocks.end())
  1051. {
  1052. LLVFSFileBlock *block = (*it).second;
  1053. res = (block->mLocks[lock] > 0);
  1054. }
  1055. unlockData();
  1056. return res;
  1057. }
  1058. //============================================================================
  1059. // protected
  1060. //============================================================================
  1061. void LLVFS::eraseBlockLength(LLVFSBlock *block)
  1062. {
  1063. // find the corresponding map entry in the length map and erase it
  1064. S32 length = block->mLength;
  1065. blocks_length_map_t::iterator iter = mFreeBlocksByLength.lower_bound(length);
  1066. blocks_length_map_t::iterator end = mFreeBlocksByLength.end();
  1067. bool found_block = false;
  1068. while(iter != end)
  1069. {
  1070. LLVFSBlock *tblock = iter->second;
  1071. llassert(tblock->mLength == length); // there had -better- be an entry with our length!
  1072. if (tblock == block)
  1073. {
  1074. mFreeBlocksByLength.erase(iter);
  1075. found_block = true;
  1076. break;
  1077. }
  1078. ++iter;
  1079. }
  1080. if(!found_block)
  1081. {
  1082. llerrs << "eraseBlock could not find block" << llendl;
  1083. }
  1084. }
  1085. // Remove block from both free lists (by location and by length).
  1086. void LLVFS::eraseBlock(LLVFSBlock *block)
  1087. {
  1088. eraseBlockLength(block);
  1089. // find the corresponding map entry in the location map and erase it
  1090. U32 location = block->mLocation;
  1091. llverify(mFreeBlocksByLocation.erase(location) == 1); // we should only have one entry per location.
  1092. }
  1093. // Add the region specified by block location and length to the free lists.
  1094. // Also incrementally defragment by merging with previous and next free blocks.
  1095. void LLVFS::addFreeBlock(LLVFSBlock *block)
  1096. {
  1097. #if LL_DEBUG
  1098. size_t dbgcount = mFreeBlocksByLocation.count(block->mLocation);
  1099. if(dbgcount > 0)
  1100. {
  1101. llerrs << "addFreeBlock called with block already in list" << llendl;
  1102. }
  1103. #endif
  1104. // Get a pointer to the next free block (by location).
  1105. blocks_location_map_t::iterator next_free_it = mFreeBlocksByLocation.lower_bound(block->mLocation);
  1106. // We can merge with previous if it ends at our requested location.
  1107. LLVFSBlock* prev_block = NULL;
  1108. bool merge_prev = false;
  1109. if (next_free_it != mFreeBlocksByLocation.begin())
  1110. {
  1111. blocks_location_map_t::iterator prev_free_it = next_free_it;
  1112. --prev_free_it;
  1113. prev_block = prev_free_it->second;
  1114. merge_prev = (prev_block->mLocation + prev_block->mLength == block->mLocation);
  1115. }
  1116. // We can merge with next if our block ends at the next block's location.
  1117. LLVFSBlock* next_block = NULL;
  1118. bool merge_next = false;
  1119. if (next_free_it != mFreeBlocksByLocation.end())
  1120. {
  1121. next_block = next_free_it->second;
  1122. merge_next = (block->mLocation + block->mLength == next_block->mLocation);
  1123. }
  1124. if (merge_prev && merge_next)
  1125. {
  1126. // llinfos << "VFS merge BOTH" << llendl;
  1127. // Previous block is changing length (a lot), so only need to update length map.
  1128. // Next block is going away completely. JC
  1129. eraseBlockLength(prev_block);
  1130. eraseBlock(next_block);
  1131. prev_block->mLength += block->mLength + next_block->mLength;
  1132. mFreeBlocksByLength.insert(blocks_length_map_t::value_type(prev_block->mLength, prev_block));
  1133. delete block;
  1134. block = NULL;
  1135. delete next_block;
  1136. next_block = NULL;
  1137. }
  1138. else if (merge_prev)
  1139. {
  1140. // llinfos << "VFS merge previous" << llendl;
  1141. // Previous block is maintaining location, only changing length,
  1142. // therefore only need to update the length map. JC
  1143. eraseBlockLength(prev_block);
  1144. prev_block->mLength += block->mLength;
  1145. mFreeBlocksByLength.insert(blocks_length_map_t::value_type(prev_block->mLength, prev_block)); // multimap insert
  1146. delete block;
  1147. block = NULL;
  1148. }
  1149. else if (merge_next)
  1150. {
  1151. // llinfos << "VFS merge next" << llendl;
  1152. // Next block is changing both location and length,
  1153. // so both free lists must update. JC
  1154. eraseBlock(next_block);
  1155. next_block->mLocation = block->mLocation;
  1156. next_block->mLength += block->mLength;
  1157. // Don't hint here, next_free_it iterator may be invalid.
  1158. mFreeBlocksByLocation.insert(blocks_location_map_t::value_type(next_block->mLocation, next_block)); // multimap insert
  1159. mFreeBlocksByLength.insert(blocks_length_map_t::value_type(next_block->mLength, next_block)); // multimap insert
  1160. delete block;
  1161. block = NULL;
  1162. }
  1163. else
  1164. {
  1165. // Can't merge with other free blocks.
  1166. // Hint that insert should go near next_free_it.
  1167. mFreeBlocksByLocation.insert(next_free_it, blocks_location_map_t::value_type(block->mLocation, block)); // multimap insert
  1168. mFreeBlocksByLength.insert(blocks_length_map_t::value_type(block->mLength, block)); // multimap insert
  1169. }
  1170. }
  1171. // Superceeded by new addFreeBlock which does incremental free space merging.
  1172. // Incremental is faster overall.
  1173. //void LLVFS::mergeFreeBlocks()
  1174. //{
  1175. // if (!isValid())
  1176. // {
  1177. // llerrs << "Attempting to use invalid VFS!" << llendl;
  1178. // }
  1179. // // TODO: could we optimize this with hints from the calling code?
  1180. // blocks_location_map_t::iterator iter = mFreeBlocksByLocation.begin();
  1181. // blocks_location_map_t::iterator end = mFreeBlocksByLocation.end();
  1182. // LLVFSBlock *first_block = iter->second;
  1183. // while(iter != end)
  1184. // {
  1185. // blocks_location_map_t::iterator first_iter = iter; // save for if we do a merge
  1186. // if (++iter == end)
  1187. // break;
  1188. // LLVFSBlock *second_block = iter->second;
  1189. // if (first_block->mLocation + first_block->mLength == second_block->mLocation)
  1190. // {
  1191. // // remove the first block from the length map
  1192. // eraseBlockLength(first_block);
  1193. // // merge first_block with second_block, since they're adjacent
  1194. // first_block->mLength += second_block->mLength;
  1195. // // add the first block to the length map (with the new size)
  1196. // mFreeBlocksByLength.insert(blocks_length_map_t::value_type(first_block->mLength, first_block)); // multimap insert
  1197. //
  1198. // // erase and delete the second block
  1199. // eraseBlock(second_block);
  1200. // delete second_block;
  1201. //
  1202. // // reset iterator
  1203. // iter = first_iter; // haven't changed first_block, so corresponding iterator is still valid
  1204. // end = mFreeBlocksByLocation.end();
  1205. // }
  1206. // first_block = second_block;
  1207. // }
  1208. //}
  1209. // length bytes from free_block are going to be used (so they are no longer free)
  1210. void LLVFS::useFreeSpace(LLVFSBlock *free_block, S32 length)
  1211. {
  1212. if (free_block->mLength == length)
  1213. {
  1214. eraseBlock(free_block);
  1215. delete free_block;
  1216. }
  1217. else
  1218. {
  1219. eraseBlock(free_block);
  1220. free_block->mLocation += length;
  1221. free_block->mLength -= length;
  1222. addFreeBlock(free_block);
  1223. }
  1224. }
  1225. // NOTE! mDataMutex must be LOCKED before calling this
  1226. // sync this index entry out to the index file
  1227. // we need to do this constantly to avoid corruption on viewer crash
  1228. void LLVFS::sync(LLVFSFileBlock *block, BOOL remove)
  1229. {
  1230. if (!isValid())
  1231. {
  1232. llerrs << "Attempting to use invalid VFS!" << llendl;
  1233. }
  1234. if (mReadOnly)
  1235. {
  1236. llwarns << "Attempt to sync read-only VFS" << llendl;
  1237. return;
  1238. }
  1239. if (block->mLength == BLOCK_LENGTH_INVALID)
  1240. {
  1241. // This is a dummy file, don't save
  1242. return;
  1243. }
  1244. if (block->mLength == 0)
  1245. {
  1246. llerrs << "VFS syncing zero-length block" << llendl;
  1247. }
  1248. BOOL set_index_to_end = FALSE;
  1249. long seek_pos = block->mIndexLocation;
  1250. if (-1 == seek_pos)
  1251. {
  1252. if (!mIndexHoles.empty())
  1253. {
  1254. seek_pos = mIndexHoles.front();
  1255. mIndexHoles.pop_front();
  1256. }
  1257. else
  1258. {
  1259. set_index_to_end = TRUE;
  1260. }
  1261. }
  1262. if (set_index_to_end)
  1263. {
  1264. // Need fseek/ftell to update the seek_pos and hence data
  1265. // structures, so can't unlockData() before this.
  1266. fseek(mIndexFP, 0, SEEK_END);
  1267. seek_pos = ftell(mIndexFP);
  1268. }
  1269. block->mIndexLocation = seek_pos;
  1270. if (remove)
  1271. {
  1272. mIndexHoles.push_back(seek_pos);
  1273. }
  1274. U8 buffer[LLVFSFileBlock::SERIAL_SIZE];
  1275. if (remove)
  1276. {
  1277. memset(buffer, 0, LLVFSFileBlock::SERIAL_SIZE);
  1278. }
  1279. else
  1280. {
  1281. block->serialize(buffer);
  1282. }
  1283. // If set_index_to_end, file pointer is already at seek_pos
  1284. // and we don't need to do anything. Only seek if not at end.
  1285. if (!set_index_to_end)
  1286. {
  1287. fseek(mIndexFP, seek_pos, SEEK_SET);
  1288. }
  1289. if (fwrite(buffer, LLVFSFileBlock::SERIAL_SIZE, 1, mIndexFP) != 1)
  1290. {
  1291. llwarns << "Short write" << llendl;
  1292. }
  1293. // *NOTE: Why was this commented out?
  1294. // fflush(mIndexFP);
  1295. return;
  1296. }
  1297. // mDataMutex must be LOCKED before calling this
  1298. // Can initiate LRU-based file removal to make space.
  1299. // The immune file block will not be removed.
  1300. LLVFSBlock *LLVFS::findFreeBlock(S32 size, LLVFSFileBlock *immune)
  1301. {
  1302. if (!isValid())
  1303. {
  1304. llerrs << "Attempting to use invalid VFS!" << llendl;
  1305. }
  1306. LLVFSBlock *block = NULL;
  1307. BOOL have_lru_list = FALSE;
  1308. typedef std::set<LLVFSFileBlock*, LLVFSFileBlock_less> lru_set;
  1309. lru_set lru_list;
  1310. LLTimer timer;
  1311. while (! block)
  1312. {
  1313. // look for a suitable free block
  1314. blocks_length_map_t::iterator iter = mFreeBlocksByLength.lower_bound(size); // first entry >= size
  1315. if (iter != mFreeBlocksByLength.end())
  1316. block = iter->second;
  1317. // no large enough free blocks, time to clean out some junk
  1318. if (! block)
  1319. {
  1320. // create a list of files sorted by usage time
  1321. // this is far faster than sorting a linked list
  1322. if (! have_lru_list)
  1323. {
  1324. for (fileblock_map::iterator it = mFileBlocks.begin(); it != mFileBlocks.end(); ++it)
  1325. {
  1326. LLVFSFileBlock *tmp = (*it).second;
  1327. if (tmp != immune &&
  1328. tmp->mLength > 0 &&
  1329. ! tmp->mLocks[VFSLOCK_READ] &&
  1330. ! tmp->mLocks[VFSLOCK_APPEND] &&
  1331. ! tmp->mLocks[VFSLOCK_OPEN])
  1332. {
  1333. lru_list.insert(tmp);
  1334. }
  1335. }
  1336. have_lru_list = TRUE;
  1337. }
  1338. if (lru_list.size() == 0)
  1339. {
  1340. // No more files to delete, and still not enough room!
  1341. llwarns << "VFS: Can't make " << size << " bytes of free space in VFS, giving up" << llendl;
  1342. break;
  1343. }
  1344. // is the oldest file big enough? (Should be about half the time)
  1345. lru_set::iterator it = lru_list.begin();
  1346. LLVFSFileBlock *file_block = *it;
  1347. if (file_block->mLength >= size && file_block != immune)
  1348. {
  1349. // ditch this file and look again for a free block - should find it
  1350. // TODO: it'll be faster just to assign the free block and break
  1351. llinfos << "LRU: Removing " << file_block->mFileID << ":" << file_block->mFileType << llendl;
  1352. lru_list.erase(it);
  1353. removeFileBlock(file_block);
  1354. file_block = NULL;
  1355. continue;
  1356. }
  1357. llinfos << "VFS: LRU: Aggressive: " << (S32)lru_list.size() << " files remain" << llendl;
  1358. dumpLockCounts();
  1359. // Now it's time to aggressively make more space
  1360. // Delete the oldest 5MB of the vfs or enough to hold the file, which ever is larger
  1361. // This may yield too much free space, but we'll use it up soon enough
  1362. U32 cleanup_target = (size > VFS_CLEANUP_SIZE) ? size : VFS_CLEANUP_SIZE;
  1363. U32 cleaned_up = 0;
  1364. for (it = lru_list.begin();
  1365. it != lru_list.end() && cleaned_up < cleanup_target;
  1366. )
  1367. {
  1368. file_block = *it;
  1369. // TODO: it would be great to be able to batch all these sync() calls
  1370. // llinfos << "LRU2: Removing " << file_block->mFileID << ":" << file_block->mFileType << " last accessed" << file_block->mAccessTime << llendl;
  1371. cleaned_up += file_block->mLength;
  1372. lru_list.erase(it++);
  1373. removeFileBlock(file_block);
  1374. file_block = NULL;
  1375. }
  1376. //mergeFreeBlocks();
  1377. }
  1378. }
  1379. F32 time = timer.getElapsedTimeF32();
  1380. if (time > 0.5f)
  1381. {
  1382. llwarns << "VFS: Spent " << time << " seconds in findFreeBlock!" << llendl;
  1383. }
  1384. return block;
  1385. }
  1386. //============================================================================
  1387. // public
  1388. //============================================================================
  1389. void LLVFS::pokeFiles()
  1390. {
  1391. if (!isValid())
  1392. {
  1393. llerrs << "Attempting to use invalid VFS!" << llendl;
  1394. }
  1395. U32 word;
  1396. // only write data if we actually read 4 bytes
  1397. // otherwise we're writing garbage and screwing up the file
  1398. fseek(mDataFP, 0, SEEK_SET);
  1399. if (fread(&word, sizeof(word), 1, mDataFP) == 1)
  1400. {
  1401. fseek(mDataFP, 0, SEEK_SET);
  1402. if (fwrite(&word, sizeof(word), 1, mDataFP) != 1)
  1403. {
  1404. llwarns << "Could not write to data file" << llendl;
  1405. }
  1406. fflush(mDataFP);
  1407. }
  1408. fseek(mIndexFP, 0, SEEK_SET);
  1409. if (fread(&word, sizeof(word), 1, mIndexFP) == 1)
  1410. {
  1411. fseek(mIndexFP, 0, SEEK_SET);
  1412. if (fwrite(&word, sizeof(word), 1, mIndexFP) != 1)
  1413. {
  1414. llwarns << "Could not write to index file" << llendl;
  1415. }
  1416. fflush(mIndexFP);
  1417. }
  1418. }
  1419. void LLVFS::dumpMap()
  1420. {
  1421. llinfos << "Files:" << llendl;
  1422. for (fileblock_map::iterator it = mFileBlocks.begin(); it != mFileBlocks.end(); ++it)
  1423. {
  1424. LLVFSFileBlock *file_block = (*it).second;
  1425. llinfos << "Location: " << file_block->mLocation << "\tLength: " << file_block->mLength << "\t" << file_block->mFileID << "\t" << file_block->mFileType << llendl;
  1426. }
  1427. llinfos << "Free Blocks:" << llendl;
  1428. for (blocks_location_map_t::iterator iter = mFreeBlocksByLocation.begin(),
  1429. end = mFreeBlocksByLocation.end();
  1430. iter != end; iter++)
  1431. {
  1432. LLVFSBlock *free_block = iter->second;
  1433. llinfos << "Location: " << free_block->mLocation << "\tLength: " << free_block->mLength << llendl;
  1434. }
  1435. }
  1436. // verify that the index file contents match the in-memory file structure
  1437. // Very slow, do not call routinely. JC
  1438. void LLVFS::audit()
  1439. {
  1440. // Lock the mutex through this whole function.
  1441. LLMutexLock lock_data(mDataMutex);
  1442. fflush(mIndexFP);
  1443. fseek(mIndexFP, 0, SEEK_END);
  1444. size_t index_size = ftell(mIndexFP);
  1445. fseek(mIndexFP, 0, SEEK_SET);
  1446. BOOL vfs_corrupt = FALSE;
  1447. // since we take the address of element 0, we need to have at least one element.
  1448. std::vector<U8> buffer(llmax<size_t>(index_size,1U));
  1449. if (fread(&buffer[0], 1, index_size, mIndexFP) != index_size)
  1450. {
  1451. llwarns << "Index truncated" << llendl;
  1452. vfs_corrupt = TRUE;
  1453. }
  1454. size_t buf_offset = 0;
  1455. std::map<LLVFSFileSpecifier, LLVFSFileBlock*> found_files;
  1456. U32 cur_time = (U32)time(NULL);
  1457. std::vector<LLVFSFileBlock*> audit_blocks;
  1458. while (!vfs_corrupt && buf_offset < index_size)
  1459. {
  1460. LLVFSFileBlock *block = new LLVFSFileBlock();
  1461. audit_blocks.push_back(block);
  1462. block->deserialize(&buffer[buf_offset], (S32)buf_offset);
  1463. buf_offset += block->SERIAL_SIZE;
  1464. // do sanity check on this block
  1465. if (block->mLength >= 0 &&
  1466. block->mSize >= 0 &&
  1467. block->mSize <= block->mLength &&
  1468. block->mFileType >= LLAssetType::AT_NONE &&
  1469. block->mFileType < LLAssetType::AT_COUNT &&
  1470. block->mAccessTime <= cur_time &&
  1471. block->mFileID != LLUUID::null)
  1472. {
  1473. if (mFileBlocks.find(*block) == mFileBlocks.end())
  1474. {
  1475. llwarns << "VFile " << block->mFileID << ":" << block->mFileType << " on disk, not in memory, loc " << block->mIndexLocation << llendl;
  1476. }
  1477. else if (found_files.find(*block) != found_files.end())
  1478. {
  1479. std::map<LLVFSFileSpecifier, LLVFSFileBlock*>::iterator it;
  1480. it = found_files.find(*block);
  1481. LLVFSFileBlock* dupe = it->second;
  1482. // try to keep data from being lost
  1483. unlockAndClose(mIndexFP);
  1484. mIndexFP = NULL;
  1485. unlockAndClose(mDataFP);
  1486. mDataFP = NULL;
  1487. llwarns << "VFS: Original block index " << block->mIndexLocation
  1488. << " location " << block->mLocation
  1489. << " length " << block->mLength
  1490. << " size " << block->mSize
  1491. << " id " << block->mFileID
  1492. << " type " << block->mFileType
  1493. << llendl;
  1494. llwarns << "VFS: Duplicate block index " << dupe->mIndexLocation
  1495. << " location " << dupe->mLocation
  1496. << " length " << dupe->mLength
  1497. << " size " << dupe->mSize
  1498. << " id " << dupe->mFileID
  1499. << " type " << dupe->mFileType
  1500. << llendl;
  1501. llwarns << "VFS: Index size " << index_size << llendl;
  1502. llwarns << "VFS: INDEX CORRUPT" << llendl;
  1503. vfs_corrupt = TRUE;
  1504. break;
  1505. }
  1506. else
  1507. {
  1508. found_files[*block] = block;
  1509. }
  1510. }
  1511. else
  1512. {
  1513. if (block->mLength)
  1514. {
  1515. llwarns << "VFile " << block->mFileID << ":" << block->mFileType << " corrupt on disk" << llendl;
  1516. }
  1517. // else this is just a hole
  1518. }
  1519. }
  1520. if (!vfs_corrupt)
  1521. {
  1522. for (fileblock_map::iterator it = mFileBlocks.begin(); it != mFileBlocks.end(); ++it)
  1523. {
  1524. LLVFSFileBlock* block = (*it).second;
  1525. if (block->mSize > 0)
  1526. {
  1527. if (! found_files.count(*block))
  1528. {
  1529. llwarns << "VFile " << block->mFileID << ":" << block->mFileType << " in memory, not on disk, loc " << block->mIndexLocation<< llendl;
  1530. fseek(mIndexFP, block->mIndexLocation, SEEK_SET);
  1531. U8 buf[LLVFSFileBlock::SERIAL_SIZE];
  1532. if (fread(buf, LLVFSFileBlock::SERIAL_SIZE, 1, mIndexFP) != 1)
  1533. {
  1534. llwarns << "VFile " << block->mFileID
  1535. << " gave short read" << llendl;
  1536. }
  1537. LLVFSFileBlock disk_block;
  1538. disk_block.deserialize(buf, block->mIndexLocation);
  1539. llwarns << "Instead found " << disk_block.mFileID << ":" << block->mFileType << llendl;
  1540. }
  1541. else
  1542. {
  1543. block = found_files.find(*block)->second;
  1544. found_files.erase(*block);
  1545. }
  1546. }
  1547. }
  1548. for (std::map<LLVFSFileSpecifier, LLVFSFileBlock*>::iterator iter = found_files.begin();
  1549. iter != found_files.end(); iter++)
  1550. {
  1551. LLVFSFileBlock* block = iter->second;
  1552. llwarns << "VFile " << block->mFileID << ":" << block->mFileType << " szie:" << block->mSize << " leftover" << llendl;
  1553. }
  1554. llinfos << "VFS: audit OK" << llendl;
  1555. // mutex released by LLMutexLock() destructor.
  1556. }
  1557. for_each(audit_blocks.begin(), audit_blocks.end(), DeletePointer());
  1558. }
  1559. // quick check for uninitialized blocks
  1560. // Slow, do not call in release.
  1561. void LLVFS::checkMem()
  1562. {
  1563. lockData();
  1564. for (fileblock_map::iterator it = mFileBlocks.begin(); it != mFileBlocks.end(); ++it)
  1565. {
  1566. LLVFSFileBlock *block = (*it).second;
  1567. llassert(block->mFileType >= LLAssetType::AT_NONE &&
  1568. block->mFileType < LLAssetType::AT_COUNT &&
  1569. block->mFileID != LLUUID::null);
  1570. for (std::deque<S32>::iterator iter = mIndexHoles.begin();
  1571. iter != mIndexHoles.end(); ++iter)
  1572. {
  1573. S32 index_loc = *iter;
  1574. if (index_loc == block->mIndexLocation)
  1575. {
  1576. llwarns << "VFile block " << block->mFileID << ":" << block->mFileType << " is marked as a hole" << llendl;
  1577. }
  1578. }
  1579. }
  1580. llinfos << "VFS: mem check OK" << llendl;
  1581. unlockData();
  1582. }
  1583. void LLVFS::dumpLockCounts()
  1584. {
  1585. S32 i;
  1586. for (i = 0; i < VFSLOCK_COUNT; i++)
  1587. {
  1588. llinfos << "LockType: " << i << ": " << mLockCounts[i] << llendl;
  1589. }
  1590. }
  1591. void LLVFS::dumpStatistics()
  1592. {
  1593. lockData();
  1594. // Investigate file blocks.
  1595. std::map<S32, S32> size_counts;
  1596. std::map<U32, S32> location_counts;
  1597. std::map<LLAssetType::EType, std::pair<S32,S32> > filetype_counts;
  1598. S32 max_file_size = 0;
  1599. S32 total_file_size = 0;
  1600. S32 invalid_file_count = 0;
  1601. for (fileblock_map::iterator it = mFileBlocks.begin(); it != mFileBlocks.end(); ++it)
  1602. {
  1603. LLVFSFileBlock *file_block = (*it).second;
  1604. if (file_block->mLength == BLOCK_LENGTH_INVALID)
  1605. {
  1606. invalid_file_count++;
  1607. }
  1608. else if (file_block->mLength <= 0)
  1609. {
  1610. llinfos << "Bad file block at: " << file_block->mLocation << "\tLength: " << file_block->mLength << "\t" << file_block->mFileID << "\t" << file_block->mFileType << llendl;
  1611. size_counts[file_block->mLength]++;
  1612. location_counts[file_block->mLocation]++;
  1613. }
  1614. else
  1615. {
  1616. total_file_size += file_block->mLength;
  1617. }
  1618. if (file_block->mLength > max_file_size)
  1619. {
  1620. max_file_size = file_block->mLength;
  1621. }
  1622. filetype_counts[file_block->mFileType].first++;
  1623. filetype_counts[file_block->mFileType].second += file_block->mLength;
  1624. }
  1625. for (std::map<S32,S32>::iterator it = size_counts.begin(); it != size_counts.end(); ++it)
  1626. {
  1627. S32 size = it->first;
  1628. S32 size_count = it->second;
  1629. llinfos << "Bad files size " << size << " count " << size_count << llendl;
  1630. }
  1631. for (std::map<U32,S32>::iterator it = location_counts.begin(); it != location_counts.end(); ++it)
  1632. {
  1633. U32 location = it->first;
  1634. S32 location_count = it->second;
  1635. llinfos << "Bad files location " << location << " count " << location_count << llendl;
  1636. }
  1637. // Investigate free list.
  1638. S32 max_free_size = 0;
  1639. S32 total_free_size = 0;
  1640. std::map<S32, S32> free_length_counts;
  1641. for (blocks_location_map_t::iterator iter = mFreeBlocksByLocation.begin(),
  1642. end = mFreeBlocksByLocation.end();
  1643. iter != end; iter++)
  1644. {
  1645. LLVFSBlock *free_block = iter->second;
  1646. if (free_block->mLength <= 0)
  1647. {
  1648. llinfos << "Bad free block at: " << free_block->mLocation << "\tLength: " << free_block->mLength << llendl;
  1649. }
  1650. else
  1651. {
  1652. llinfos << "Block: " << free_block->mLocation
  1653. << "\tLength: " << free_block->mLength
  1654. << "\tEnd: " << free_block->mLocation + free_block->mLength
  1655. << llendl;
  1656. total_free_size += free_block->mLength;
  1657. }
  1658. if (free_block->mLength > max_free_size)
  1659. {
  1660. max_free_size = free_block->mLength;
  1661. }
  1662. free_length_counts[free_block->mLength]++;
  1663. }
  1664. // Dump histogram of free block sizes
  1665. for (std::map<S32,S32>::iterator it = free_length_counts.begin(); it != free_length_counts.end(); ++it)
  1666. {
  1667. llinfos << "Free length " << it->first << " count " << it->second << llendl;
  1668. }
  1669. llinfos << "Invalid blocks: " << invalid_file_count << llendl;
  1670. llinfos << "File blocks: " << mFileBlocks.size() << llendl;
  1671. S32 length_list_count = (S32)mFreeBlocksByLength.size();
  1672. S32 location_list_count = (S32)mFreeBlocksByLocation.size();
  1673. if (length_list_count == location_list_count)
  1674. {
  1675. llinfos << "Free list lengths match, free blocks: " << location_list_count << llendl;
  1676. }
  1677. else
  1678. {
  1679. llwarns << "Free list lengths do not match!" << llendl;
  1680. llwarns << "By length: " << length_list_count << llendl;
  1681. llwarns << "By location: " << location_list_count << llendl;
  1682. }
  1683. llinfos << "Max file: " << max_file_size/1024 << "K" << llendl;
  1684. llinfos << "Max free: " << max_free_size/1024 << "K" << llendl;
  1685. llinfos << "Total file size: " << total_file_size/1024 << "K" << llendl;
  1686. llinfos << "Total free size: " << total_free_size/1024 << "K" << llendl;
  1687. llinfos << "Sum: " << (total_file_size + total_free_size) << " bytes" << llendl;
  1688. llinfos << llformat("%.0f%% full",((F32)(total_file_size)/(F32)(total_file_size+total_free_size))*100.f) << llendl;
  1689. llinfos << " " << llendl;
  1690. for (std::map<LLAssetType::EType, std::pair<S32,S32> >::iterator iter = filetype_counts.begin();
  1691. iter != filetype_counts.end(); ++iter)
  1692. {
  1693. llinfos << "Type: " << LLAssetType::getDesc(iter->first)
  1694. << " Count: " << iter->second.first
  1695. << " Bytes: " << (iter->second.second>>20) << " MB" << llendl;
  1696. }
  1697. // Look for potential merges
  1698. {
  1699. blocks_location_map_t::iterator iter = mFreeBlocksByLocation.begin();
  1700. blocks_location_map_t::iterator end = mFreeBlocksByLocation.end();
  1701. LLVFSBlock *first_block = iter->second;
  1702. while(iter != end)
  1703. {
  1704. if (++iter == end)
  1705. break;
  1706. LLVFSBlock *second_block = iter->second;
  1707. if (first_block->mLocation + first_block->mLength == second_block->mLocation)
  1708. {
  1709. llinfos << "Potential merge at " << first_block->mLocation << llendl;
  1710. }
  1711. first_block = second_block;
  1712. }
  1713. }
  1714. unlockData();
  1715. }
  1716. // Debug Only!
  1717. std::string get_extension(LLAssetType::EType type)
  1718. {
  1719. std::string extension;
  1720. switch(type)
  1721. {
  1722. case LLAssetType::AT_TEXTURE:
  1723. extension = ".jp2"; // formerly ".j2c"
  1724. break;
  1725. case LLAssetType::AT_SOUND:
  1726. extension = ".ogg";
  1727. break;
  1728. case LLAssetType::AT_SOUND_WAV:
  1729. extension = ".wav";
  1730. break;
  1731. case LLAssetType::AT_TEXTURE_TGA:
  1732. extension = ".tga";
  1733. break;
  1734. case LLAssetType::AT_ANIMATION:
  1735. extension = ".lla";
  1736. break;
  1737. case LLAssetType::AT_MESH:
  1738. extension = ".slm";
  1739. break;
  1740. default:
  1741. // Just use the asset server filename extension in most cases
  1742. extension += ".";
  1743. extension += LLAssetType::lookup(type);
  1744. break;
  1745. }
  1746. return extension;
  1747. }
  1748. void LLVFS::listFiles()
  1749. {
  1750. lockData();
  1751. for (fileblock_map::iterator it = mFileBlocks.begin(); it != mFileBlocks.end(); ++it)
  1752. {
  1753. LLVFSFileSpecifier file_spec = it->first;
  1754. LLVFSFileBlock *file_block = it->second;
  1755. S32 length = file_block->mLength;
  1756. S32 size = file_block->mSize;
  1757. if (length != BLOCK_LENGTH_INVALID && size > 0)
  1758. {
  1759. LLUUID id = file_spec.mFileID;
  1760. std::string extension = get_extension(file_spec.mFileType);
  1761. llinfos << " File: " << id
  1762. << " Type: " << LLAssetType::getDesc(file_spec.mFileType)
  1763. << " Size: " << size
  1764. << llendl;
  1765. }
  1766. }
  1767. unlockData();
  1768. }
  1769. #include "llapr.h"
  1770. void LLVFS::dumpFiles()
  1771. {
  1772. lockData();
  1773. S32 files_extracted = 0;
  1774. for (fileblock_map::iterator it = mFileBlocks.begin(); it != mFileBlocks.end(); ++it)
  1775. {
  1776. LLVFSFileSpecifier file_spec = it->first;
  1777. LLVFSFileBlock *file_block = it->second;
  1778. S32 length = file_block->mLength;
  1779. S32 size = file_block->mSize;
  1780. if (length != BLOCK_LENGTH_INVALID && size > 0)
  1781. {
  1782. LLUUID id = file_spec.mFileID;
  1783. LLAssetType::EType type = file_spec.mFileType;
  1784. std::vector<U8> buffer(size);
  1785. unlockData();
  1786. getData(id, type, &buffer[0], 0, size);
  1787. lockData();
  1788. std::string extension = get_extension(type);
  1789. std::string filename = id.asString() + extension;
  1790. llinfos << " Writing " << filename << llendl;
  1791. LLAPRFile outfile;
  1792. outfile.open(filename, LL_APR_WB);
  1793. outfile.write(&buffer[0], size);
  1794. outfile.close();
  1795. files_extracted++;
  1796. }
  1797. }
  1798. unlockData();
  1799. llinfos << "Extracted " << files_extracted << " files out of " << mFileBlocks.size() << llendl;
  1800. }
  1801. //============================================================================
  1802. // protected
  1803. //============================================================================
  1804. // static
  1805. LLFILE *LLVFS::openAndLock(const std::string& filename, const char* mode, BOOL read_lock)
  1806. {
  1807. #if LL_WINDOWS
  1808. return LLFile::_fsopen(filename, mode, (read_lock ? _SH_DENYWR : _SH_DENYRW));
  1809. #else
  1810. LLFILE *fp;
  1811. int fd;
  1812. // first test the lock in a non-destructive way
  1813. #if LL_SOLARIS
  1814. struct flock fl;
  1815. fl.l_whence = SEEK_SET;
  1816. fl.l_start = 0;
  1817. fl.l_len = 1;
  1818. #else // !LL_SOLARIS
  1819. if (strchr(mode, 'w') != NULL)
  1820. {
  1821. fp = LLFile::fopen(filename, "rb"); /* Flawfinder: ignore */
  1822. if (fp)
  1823. {
  1824. fd = fileno(fp);
  1825. if (flock(fd, (read_lock ? LOCK_SH : LOCK_EX) | LOCK_NB) == -1)
  1826. {
  1827. fclose(fp);
  1828. return NULL;
  1829. }
  1830. fclose(fp);
  1831. }
  1832. }
  1833. #endif // !LL_SOLARIS
  1834. // now actually open the file for use
  1835. fp = LLFile::fopen(filename, mode); /* Flawfinder: ignore */
  1836. if (fp)
  1837. {
  1838. fd = fileno(fp);
  1839. #if LL_SOLARIS
  1840. fl.l_type = read_lock ? F_RDLCK : F_WRLCK;
  1841. if (fcntl(fd, F_SETLK, &fl) == -1)
  1842. #else
  1843. if (flock(fd, (read_lock ? LOCK_SH : LOCK_EX) | LOCK_NB) == -1)
  1844. #endif
  1845. {
  1846. fclose(fp);
  1847. fp = NULL;
  1848. }
  1849. }
  1850. return fp;
  1851. #endif
  1852. }
  1853. // static
  1854. void LLVFS::unlockAndClose(LLFILE *fp)
  1855. {
  1856. if (fp)
  1857. {
  1858. // IW: we don't actually want to unlock on linux
  1859. // this is because a forked process can kill the parent's lock
  1860. // with an explicit unlock
  1861. // however, fclose() will implicitly remove the lock
  1862. // but only once both parent and child have closed the file
  1863. /*
  1864. #if !LL_WINDOWS
  1865. int fd = fileno(fp);
  1866. flock(fd, LOCK_UN);
  1867. #endif
  1868. */
  1869. #if LL_SOLARIS
  1870. struct flock fl;
  1871. fl.l_whence = SEEK_SET;
  1872. fl.l_start = 0;
  1873. fl.l_len = 1;
  1874. fl.l_type = F_UNLCK;
  1875. fcntl(fileno(fp), F_SETLK, &fl);
  1876. #endif
  1877. fclose(fp);
  1878. }
  1879. }