lltexturecache.cpp 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890
  1. /**
  2. * @file lltexturecache.cpp
  3. * @brief Object which handles local texture caching
  4. *
  5. * $LicenseInfo:firstyear=2000&license=viewergpl$
  6. *
  7. * Copyright (c) 2000-2009, Linden Research, Inc.
  8. * Copyright (c) 2011-2023, Henri Beauchamp.
  9. *
  10. * Second Life Viewer Source Code
  11. * The source code in this file ("Source Code") is provided by Linden Lab
  12. * to you under the terms of the GNU General Public License, version 2.0
  13. * ("GPL"), unless you have obtained a separate licensing agreement
  14. * ("Other License"), formally executed by you and Linden Lab. Terms of
  15. * the GPL can be found in doc/GPL-license.txt in this distribution, or
  16. * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
  17. *
  18. * There are special exceptions to the terms and conditions of the GPL as
  19. * it is applied to this Source Code. View the full text of the exception
  20. * in the file doc/FLOSS-exception.txt in this software distribution, or
  21. * online at
  22. * http://secondlifegrid.net/programs/open_source/licensing/flossexception
  23. *
  24. * By copying, modifying or distributing this software, you acknowledge
  25. * that you have read and understood your obligations described above,
  26. * and agree to abide by those obligations.
  27. *
  28. * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
  29. * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
  30. * COMPLETENESS OR PERFORMANCE.
  31. * $/LicenseInfo$
  32. */
  33. #include "llviewerprecompiledheaders.h"
  34. #include "lltexturecache.h"
  35. #include "lldir.h"
  36. #include "lldiriterator.h"
  37. #include "llimage.h"
  38. #include "hbtracy.h"
  39. #include "llappviewer.h"
  40. #include "llviewercontrol.h"
  41. // Global variable
  42. LLTextureCache* gTextureCachep = NULL;
  43. // Cache organization:
  44. // cache/texture.entries
  45. // Unordered array of Entry structs
  46. // cache/texture.cache
  47. // First TEXTURE_CACHE_ENTRY_SIZE bytes of each texture in texture.entries in
  48. // the same order
  49. // cache/textures/[0-F]/UUID.texture
  50. // Actual texture body files
  51. // Version of our texture cache: increment each time its structure changes.
  52. // Note: we use an unusually large number, which should ensure that no cache
  53. // written by another viewer than the Cool VL Viewer would be considered valid
  54. // (even though the cache directory is normally already different).
  55. constexpr F32 TEXTURE_CACHE_VERSION = 10001.f;
  56. constexpr U32 ADDRESS_SIZE = sizeof(void*) * 8; // in bits
  57. // % amount of cache left after a purge.
  58. constexpr S64 TEXTURE_PURGED_CACHE_SIZE = 80;
  59. // % amount for LRU list (low overhead to regenerate)
  60. constexpr F32 TEXTURE_CACHE_LRU_SIZE = .10f;
  61. // w, h, c, level
  62. constexpr S32 TEXTURE_FAST_CACHE_ENTRY_OVERHEAD = sizeof(S32) * 4;
  63. constexpr S32 TEXTURE_FAST_CACHE_DATA_SIZE = 16 * 16 * 4;
  64. constexpr S32 TEXTURE_FAST_CACHE_ENTRY_SIZE =
  65. TEXTURE_FAST_CACHE_DATA_SIZE + TEXTURE_FAST_CACHE_ENTRY_OVERHEAD;
  66. //////////////////////////////////////////////////////////////////////////////
  67. // Pool thread worker classes. This is where reads and writes do happpen.
  68. //////////////////////////////////////////////////////////////////////////////
  69. class LLTextureCacheWorker
  70. {
  71. friend class LLTextureCache;
  72. protected:
  73. LOG_CLASS(LLTextureCacheWorker);
  74. public:
  75. LL_INLINE LLTextureCacheWorker(const LLUUID& id, U8* data, S32 datasize,
  76. S32 offset, S32 imagesize,
  77. LLTextureCache::Responder* responder)
  78. : mID(id),
  79. mReadData(NULL),
  80. mWriteData(data),
  81. mDataSize(datasize),
  82. mOffset(offset),
  83. mImageSize(imagesize), // For writes
  84. mImageFormat(IMG_CODEC_J2C),
  85. mImageLocal(false),
  86. mCorrupted(false),
  87. mResponder(responder)
  88. {
  89. }
  90. LL_INLINE virtual ~LLTextureCacheWorker()
  91. {
  92. free_texture_mem(mReadData);
  93. }
  94. // Override these methods (called from the pool thread):
  95. virtual void doRead() = 0;
  96. virtual void doWrite() = 0;
  97. private:
  98. // Called from the pool thread
  99. void finishRead();
  100. void finishWrite();
  101. protected:
  102. LLPointer<LLTextureCache::Responder> mResponder;
  103. LLUUID mID;
  104. U8* mReadData;
  105. U8* mWriteData;
  106. S32 mDataSize;
  107. S32 mOffset;
  108. S32 mImageSize;
  109. EImageCodec mImageFormat;
  110. bool mImageLocal;
  111. bool mCorrupted;
  112. };
  113. class LLTextureCacheLocalFileWorker final : public LLTextureCacheWorker
  114. {
  115. protected:
  116. LOG_CLASS(LLTextureCacheLocalFileWorker);
  117. public:
  118. LLTextureCacheLocalFileWorker(const std::string& filename,
  119. const LLUUID& id, U8* data, S32 datasize,
  120. S32 offset, S32 imagesize, // For writes
  121. LLTextureCache::Responder* responder)
  122. : LLTextureCacheWorker(id, data, datasize, offset, imagesize, responder),
  123. mFileName(filename)
  124. {
  125. }
  126. void doRead() override;
  127. void doWrite() override
  128. {
  129. llerrs << "Cannot write to a local texture file !" << llendl;
  130. }
  131. private:
  132. std::string mFileName;
  133. };
  134. void LLTextureCacheLocalFileWorker::doRead()
  135. {
  136. if (mResponder.notNull()) // Paranoia
  137. {
  138. mResponder->started();
  139. }
  140. S32 local_size = LLFile::getFileSize(mFileName);
  141. if (local_size > 0 && mFileName.size() > 4)
  142. {
  143. mDataSize = local_size; // Only a complete file is valid
  144. std::string extension = mFileName.substr(mFileName.size() - 3, 3);
  145. mImageFormat = LLImageBase::getCodecFromExtension(extension);
  146. if (mImageFormat == IMG_CODEC_INVALID)
  147. {
  148. LL_DEBUGS("TextureCache") << "Unrecognized file extension "
  149. << extension << " for local texture "
  150. << mFileName << LL_ENDL;
  151. mDataSize = 0; // No data
  152. return;
  153. }
  154. }
  155. else
  156. {
  157. // File does not exist: no data
  158. mDataSize = 0;
  159. return;
  160. }
  161. if (!mDataSize || mDataSize > local_size - mOffset)
  162. {
  163. mDataSize = local_size - mOffset;
  164. }
  165. mReadData = (U8*)allocate_texture_mem(mDataSize);
  166. if (!mReadData)
  167. {
  168. // Out of memory !
  169. mDataSize = 0;
  170. return;
  171. }
  172. S32 bytes = LLFile::readEx(mFileName, mReadData, mOffset, mDataSize);
  173. if (bytes != mDataSize)
  174. {
  175. LL_DEBUGS("TextureCache") << "Error reading from local file: "
  176. << mFileName << " - Bytes: " << mDataSize
  177. << " Offset: " << mOffset << LL_ENDL;
  178. mDataSize = 0;
  179. free_texture_mem(mReadData);
  180. mReadData = NULL;
  181. }
  182. else
  183. {
  184. mImageSize = local_size;
  185. mImageLocal = true;
  186. }
  187. }
  188. class LLTextureCacheRemoteWorker final : public LLTextureCacheWorker
  189. {
  190. public:
  191. LLTextureCacheRemoteWorker(const LLUUID& id, U8* data, S32 datasize,
  192. S32 offset, S32 imagesize,
  193. LLPointer<LLImageRaw> raw, S32 discardlevel,
  194. LLTextureCache::Responder* responder)
  195. : LLTextureCacheWorker(id, data, datasize, offset, imagesize, responder),
  196. mRawImage(raw),
  197. mRawDiscardLevel(discardlevel)
  198. {
  199. }
  200. void doRead() override;
  201. void doWrite() override;
  202. private:
  203. LLPointer<LLImageRaw> mRawImage;
  204. S32 mRawDiscardLevel;
  205. };
  206. // This is where a texture is read from the cache system (header and body)
  207. // Current assumption are:
  208. // - the whole data are in a raw form, will be stored at mReadData
  209. // - the size of this raw data is mDataSize and can be smaller than
  210. // TEXTURE_CACHE_ENTRY_SIZE (the size of a record in the header cache)
  211. // - the code supports offset reading but this is actually never exercised in
  212. // the viewer
  213. void LLTextureCacheRemoteWorker::doRead()
  214. {
  215. if (mResponder.notNull()) // Paranoia
  216. {
  217. mResponder->started();
  218. }
  219. if (!gTextureCachep)
  220. {
  221. mDataSize = -1; // Failed
  222. return;
  223. }
  224. LLTextureCache::Entry entry;
  225. S32 idx = gTextureCachep->getHeaderCacheEntry(mID, entry);
  226. if (idx < 0)
  227. {
  228. // The texture is *not* cached. We are done here...
  229. mDataSize = 0; // no data
  230. return;
  231. }
  232. mImageSize = entry.mImageSize;
  233. // If the read offset is bigger than the header cache, we read directly
  234. // from the body. Note that currently, we *never* read with offset from the
  235. // cache.
  236. if (mOffset < TEXTURE_CACHE_ENTRY_SIZE)
  237. {
  238. // Read data from the header cache (texture.entries) file.
  239. // We need an entry here or reading the header makes no sense:
  240. llassert_always(idx >= 0 && mOffset < TEXTURE_CACHE_ENTRY_SIZE);
  241. S32 offset = idx * TEXTURE_CACHE_ENTRY_SIZE + mOffset;
  242. // Compute the size we need to read (in bytes)
  243. S32 size = TEXTURE_CACHE_ENTRY_SIZE - mOffset;
  244. size = llmin(size, mDataSize);
  245. // Allocate the read buffer
  246. mReadData = (U8*)allocate_texture_mem(size);
  247. if (!mReadData)
  248. {
  249. // Out of memory !
  250. mDataSize = -1; // Failed
  251. return;
  252. }
  253. S32 bytes_read = LLFile::readEx(gTextureCachep->mHeaderDataFileName,
  254. mReadData, offset, size);
  255. if (bytes_read != size)
  256. {
  257. llwarns << "LLTextureCacheWorker: " << mID
  258. << " incorrect number of bytes read from header: "
  259. << bytes_read << " / " << size << llendl;
  260. free_texture_mem(mReadData);
  261. mReadData = NULL;
  262. mDataSize = -1; // Failed
  263. mCorrupted = true;
  264. return;
  265. }
  266. // If we already read all we expected, we are actually done
  267. if (mDataSize <= bytes_read)
  268. {
  269. return;
  270. }
  271. }
  272. // Maybe read the rest of the data from the UUID based cached file
  273. std::string filename = gTextureCachep->getTextureFileName(mID);
  274. S32 filesize = LLFile::getFileSize(filename);
  275. if (filesize && filesize + TEXTURE_CACHE_ENTRY_SIZE > mOffset)
  276. {
  277. S32 max_datasize = TEXTURE_CACHE_ENTRY_SIZE + filesize - mOffset;
  278. mDataSize = llmin(max_datasize, mDataSize);
  279. // Reserve the whole data buffer first
  280. U8* data = (U8*)allocate_texture_mem(mDataSize);
  281. if (!data)
  282. {
  283. // Out of memory !
  284. mDataSize = -1; // Failed
  285. return;
  286. }
  287. S32 data_offset, file_size, file_offset;
  288. // Set the data file pointers taking the read offset into account.
  289. // 2 cases:
  290. if (mOffset < TEXTURE_CACHE_ENTRY_SIZE)
  291. {
  292. // Offset within the header record. That means we read something
  293. // from the header cache. Note: most common case is (mOffset = 0),
  294. // so this is the "normal" code path.
  295. // I.e. TEXTURE_CACHE_ENTRY_SIZE if mOffset nul (common case):
  296. data_offset = TEXTURE_CACHE_ENTRY_SIZE - mOffset;
  297. file_offset = 0;
  298. file_size = mDataSize - data_offset;
  299. // Copy the raw data we've been holding from the header cache into
  300. // the new sized buffer
  301. llassert_always(mReadData);
  302. memcpy(data, mReadData, data_offset);
  303. free_texture_mem(mReadData);
  304. mReadData = NULL;
  305. }
  306. else
  307. {
  308. // Offset bigger than the header record. That means we have not
  309. // read anything yet.
  310. data_offset = 0;
  311. file_offset = mOffset - TEXTURE_CACHE_ENTRY_SIZE;
  312. file_size = mDataSize;
  313. // No data from header cache to copy in that case, we skipped it
  314. // all
  315. }
  316. // Now use that buffer as the object read buffer
  317. llassert_always(mReadData == NULL);
  318. mReadData = data;
  319. // Read the data at last
  320. S32 bytes_read = LLFile::readEx(filename, mReadData + data_offset,
  321. file_offset, file_size);
  322. if (bytes_read != file_size)
  323. {
  324. LL_DEBUGS("TextureCache") << "Texture: " << mID
  325. << ". Incorrect number of bytes read from body: "
  326. << bytes_read << " / " << file_size
  327. << LL_ENDL;
  328. free_texture_mem(mReadData);
  329. mReadData = NULL;
  330. mDataSize = -1; // Failed
  331. mCorrupted = true;
  332. return;
  333. }
  334. }
  335. else
  336. {
  337. // No body, we are done.
  338. mDataSize = llmax(TEXTURE_CACHE_ENTRY_SIZE - mOffset, 0);
  339. LL_DEBUGS("TextureCache") << "No body file for texture: " << mID
  340. << LL_ENDL;
  341. }
  342. // Nothing else to do at that point...
  343. }
  344. // This is where *everything* about a texture is written down into the cache
  345. // system (entry map, header and body).
  346. // Current assumption are:
  347. // - the whole data are in a raw form, starting at mWriteData
  348. // - the size of this raw data is mDataSize and can be smaller than
  349. // TEXTURE_CACHE_ENTRY_SIZE (the size of a record in the header cache)
  350. // - the code *does not* support offset writing so there are no difference
  351. // between buffer addresses and start of data
  352. void LLTextureCacheRemoteWorker::doWrite()
  353. {
  354. if (mResponder.notNull()) // Paranoia
  355. {
  356. mResponder->started();
  357. }
  358. if (!gTextureCachep)
  359. {
  360. mDataSize = -1; // Failed
  361. mRawImage = NULL;
  362. return;
  363. }
  364. // First stage: check that what we are trying to cache is in an OK shape
  365. if (mOffset != 0 || mDataSize <= 0 || mImageSize < mDataSize ||
  366. mRawDiscardLevel < 0 || !mRawImage || mRawImage->isBufferInvalid())
  367. {
  368. llwarns << "INIT state check failed for texture: " << mID
  369. << " . Aborted." << llendl;
  370. mDataSize = -1; // Failed
  371. mRawImage = NULL;
  372. return;
  373. }
  374. // Second stage: set an entry in the headers entry (texture.entries) file
  375. LLTextureCache::Entry entry;
  376. // Checks if this image is already in the entry list
  377. S32 idx = gTextureCachep->getHeaderCacheEntry(mID, entry);
  378. if (idx >= 0)
  379. {
  380. // Update the existing entry.
  381. if (gTextureCachep->updateEntry(idx, entry, mImageSize, mDataSize))
  382. {
  383. // Success, we are done !
  384. mRawImage = NULL;
  385. return;
  386. }
  387. }
  388. else
  389. {
  390. // Create the new entry.
  391. idx = gTextureCachep->setHeaderCacheEntry(mID, entry, mImageSize,
  392. mDataSize);
  393. if (idx < 0)
  394. {
  395. llwarns << "Texture: " << mID
  396. << ". Unable to create header entry for writing !"
  397. << llendl;
  398. mDataSize = -1; // Failed
  399. mRawImage = NULL;
  400. return;
  401. }
  402. }
  403. // Skip to the correct spot in the header file:
  404. S32 offset = idx * TEXTURE_CACHE_ENTRY_SIZE;
  405. // Record size is fixed for the header:
  406. S32 size = TEXTURE_CACHE_ENTRY_SIZE;
  407. S32 bytes_written;
  408. // Third stage, write the header, possibly with the texture if small enough
  409. if (mDataSize < TEXTURE_CACHE_ENTRY_SIZE)
  410. {
  411. // We need to write a full record in the header cache so, if the amount
  412. // of data is smaller than a record, we need to transfer the data to a
  413. // buffer padded with 0 and write that.
  414. U8* pad_buffer = (U8*)allocate_texture_mem(TEXTURE_CACHE_ENTRY_SIZE);
  415. if (!pad_buffer)
  416. {
  417. // Out of memory !
  418. mDataSize = -1; // Failed
  419. mRawImage = NULL;
  420. return;
  421. }
  422. // Init with zeros
  423. memset(pad_buffer, 0, TEXTURE_CACHE_ENTRY_SIZE);
  424. // Copy the write buffer
  425. memcpy(pad_buffer, mWriteData, mDataSize);
  426. bytes_written = LLFile::writeEx(gTextureCachep->mHeaderDataFileName,
  427. pad_buffer, offset, size);
  428. free_texture_mem(pad_buffer);
  429. }
  430. else
  431. {
  432. // Write the header record (== first TEXTURE_CACHE_ENTRY_SIZE bytes of
  433. // the raw file) in the header file
  434. bytes_written = LLFile::writeEx(gTextureCachep->mHeaderDataFileName,
  435. mWriteData, offset, size);
  436. }
  437. if (bytes_written <= 0)
  438. {
  439. llwarns << "Unable to write header entry for texture: " << mID
  440. << llendl;
  441. mCorrupted = true;
  442. mDataSize = -1; // Failed
  443. mRawImage = NULL;
  444. return;
  445. }
  446. // If we wrote everything (may be more with padding) in the header cache,
  447. // we do not have a body to store, so we are done...
  448. if (mDataSize <= bytes_written)
  449. {
  450. mRawImage = NULL;
  451. return;
  452. }
  453. // Fourth stage: write the body file, i.e. the rest of the texture in an
  454. // file name derived from the texture UUID.
  455. if (mDataSize <= TEXTURE_CACHE_ENTRY_SIZE)
  456. {
  457. // It would not make sense to be here otherwise...
  458. mDataSize = -1; // Failed
  459. mCorrupted = true;
  460. mRawImage = NULL;
  461. return;
  462. }
  463. S32 file_size = mDataSize - TEXTURE_CACHE_ENTRY_SIZE;
  464. // Build the cache file name from the UUID
  465. std::string filename = gTextureCachep->getTextureFileName(mID);
  466. LL_DEBUGS("TextureCache") << "Writing Body: " << filename << " - Bytes: "
  467. << file_size << LL_ENDL;
  468. bytes_written = LLFile::writeEx(filename,
  469. mWriteData + TEXTURE_CACHE_ENTRY_SIZE, 0,
  470. file_size);
  471. if (bytes_written <= 0)
  472. {
  473. llwarns << "Texture " << mID
  474. << ". Incorrect number of bytes written to body: "
  475. << bytes_written << " / " << file_size << llendl;
  476. mDataSize = -1; // Failed
  477. mCorrupted = true;
  478. }
  479. // Nothing else to do at that point... Clean up and exit
  480. mRawImage = NULL;
  481. }
  482. void LLTextureCacheWorker::finishRead()
  483. {
  484. bool success = mDataSize > 0;
  485. if (mResponder.notNull()) // Paranoia
  486. {
  487. if (success)
  488. {
  489. mResponder->setData(mReadData, mDataSize, mImageSize,
  490. mImageFormat, mImageLocal);
  491. mReadData = NULL; // Responder owns data
  492. mDataSize = 0;
  493. ++LLTextureCache::sTotalHits;
  494. }
  495. else
  496. {
  497. free_texture_mem(mReadData);
  498. mReadData = NULL;
  499. ++LLTextureCache::sTotalMisses;
  500. }
  501. mResponder->completed(success);
  502. }
  503. if (gTextureCachep && mCorrupted)
  504. {
  505. gTextureCachep->removeFromCache(mID);
  506. ++LLTextureCache::sTotalErrors;
  507. }
  508. }
  509. void LLTextureCacheWorker::finishWrite()
  510. {
  511. bool success = mDataSize > 0;
  512. if (mResponder.notNull()) // Paranoia
  513. {
  514. mWriteData = NULL; // We never owned data
  515. mDataSize = 0;
  516. mResponder->completed(success);
  517. }
  518. if (gTextureCachep && mCorrupted)
  519. {
  520. gTextureCachep->removeFromCache(mID);
  521. ++LLTextureCache::sTotalErrors;
  522. }
  523. else if (success)
  524. {
  525. ++LLTextureCache::sTotalWrites;
  526. }
  527. }
  528. //////////////////////////////////////////////////////////////////////////////
  529. // Read responder for texture cache
  530. // Called from LLTextureCacheWorker::finishRead()
  531. //virtual
  532. void LLTextureCache::ReadResponder::setData(U8* data, S32 datasize,
  533. S32 imagesize, S32 imageformat,
  534. bool imagelocal)
  535. {
  536. if (mFormattedImage.notNull())
  537. {
  538. llassert_always(mFormattedImage->getCodec() == imageformat);
  539. mFormattedImage->appendData(data, datasize);
  540. }
  541. else
  542. {
  543. mFormattedImage = LLImageFormatted::createFromType(imageformat);
  544. mFormattedImage->setData(data, datasize);
  545. }
  546. mImageSize = imagesize;
  547. mImageLocal = imagelocal;
  548. }
  549. //////////////////////////////////////////////////////////////////////////////
  550. // LLTextureCache class proper
  551. //////////////////////////////////////////////////////////////////////////////
  552. // Static members
  553. U32 LLTextureCache::sCacheMaxEntries = 1024 * 1024;
  554. S64 LLTextureCache::sCacheMaxTexturesSize = 0; // No limit
  555. LLAtomicU32 LLTextureCache::sTotalHits(0);
  556. LLAtomicU32 LLTextureCache::sTotalMisses(0);
  557. LLAtomicU32 LLTextureCache::sTotalWrites(0);
  558. LLAtomicU32 LLTextureCache::sTotalErrors(0);
  559. static const char* entries_filename = "texture.entries";
  560. static const char* cache_filename = "texture.cache";
  561. static const char* textures_dirname = "texturecache";
  562. LLTextureCache::LLTextureCache()
  563. : mHeaderFile(NULL),
  564. mTexturesSizeTotal(0),
  565. mNumReads(0),
  566. mNumWrites(0),
  567. mDoPurge(false),
  568. // Do not allow to change the texture cache until setReadOnly() is called:
  569. mReadOnly(true)
  570. {
  571. // We use two threads to service this pool, in case of a spurious slow disk
  572. // operation or file corruption (which would otherwise block the queue
  573. // until the texture fetcher timeout fires).
  574. // *TODO: maybe also use two pools, one for writes and the other for
  575. // reads ? HB
  576. llinfos << "Initializing with 2 worker threads..." << llendl;
  577. mThreadPoolp.reset(new LLThreadPool("Texture cache", 2));
  578. mThreadPoolp->start(true); // true = wait until all threads are started.
  579. }
  580. LLTextureCache::~LLTextureCache()
  581. {
  582. purgeTextureFilesTimeSliced(true);
  583. writeUpdatedEntries();
  584. }
  585. void LLTextureCache::shutdown()
  586. {
  587. if (mThreadPoolp)
  588. {
  589. mThreadPoolp->close();
  590. mThreadPoolp.reset(nullptr);
  591. llinfos << "Thread pool destroyed." << llendl;
  592. }
  593. llinfos << "Total hits: " << sTotalHits << " - Total misses: "
  594. << sTotalMisses << " - Total writes: " << sTotalWrites
  595. << " - Total errors: " << sTotalErrors << llendl;
  596. }
  597. //virtual
  598. S32 LLTextureCache::update()
  599. {
  600. S32 res = mThreadPoolp ? mThreadPoolp->getQueue().size() : 0;
  601. static F32 last_update = 0.f;
  602. constexpr F32 MAX_UPDATE_INTERVAL = 300.f; // in seconds.
  603. if (!res && gFrameTimeSeconds - last_update > MAX_UPDATE_INTERVAL)
  604. {
  605. last_update = gFrameTimeSeconds;
  606. writeUpdatedEntries();
  607. }
  608. return res;
  609. }
  610. // Searches for local copy of UUID-based image file
  611. std::string LLTextureCache::getLocalFileName(const LLUUID& id)
  612. {
  613. // Does not include extension
  614. std::string idstr = id.asString();
  615. std::string filename = gDirUtil.getFullPath(LL_PATH_SKINS, "default",
  616. "textures", idstr);
  617. return filename;
  618. }
  619. std::string LLTextureCache::getTextureFileName(const LLUUID& id)
  620. {
  621. std::string idstr = id.asString();
  622. return mTexturesDirName + LL_DIR_DELIM_STR + idstr[0] + LL_DIR_DELIM_STR +
  623. idstr + ".texture";
  624. }
  625. bool LLTextureCache::isInCache(const LLUUID& id)
  626. {
  627. bool in_cache;
  628. mHeaderMutex.lock();
  629. in_cache = mHeaderIDMap.count(id) != 0;
  630. mHeaderMutex.unlock();
  631. return in_cache;
  632. }
  633. bool LLTextureCache::isInLocal(const LLUUID& id)
  634. {
  635. S32 local_size = 0;
  636. std::string local_filename;
  637. std::string filename = getLocalFileName(id);
  638. // Is it a JPEG2000 file ?
  639. {
  640. local_filename = filename + ".j2c";
  641. local_size = LLFile::getFileSize(local_filename);
  642. if (local_size > 0)
  643. {
  644. return true;
  645. }
  646. }
  647. // If not, is it a jpeg file ?
  648. {
  649. local_filename = filename + ".jpg";
  650. local_size = LLFile::getFileSize(local_filename);
  651. if (local_size > 0)
  652. {
  653. return true;
  654. }
  655. }
  656. // Is it a PNG file (used for UI texture mostly) ?
  657. {
  658. local_filename = filename + ".png";
  659. local_size = LLFile::getFileSize(local_filename);
  660. if (local_size > 0)
  661. {
  662. return true;
  663. }
  664. }
  665. // Hmm... What about a targa file (used for UI texture mostly) ?
  666. {
  667. local_filename = filename + ".tga";
  668. local_size = LLFile::getFileSize(local_filename);
  669. if (local_size > 0)
  670. {
  671. return true;
  672. }
  673. }
  674. return false;
  675. }
  676. void LLTextureCache::setDirNames(ELLPath location)
  677. {
  678. mHeaderEntriesFileName = gDirUtil.getFullPath(location, textures_dirname,
  679. entries_filename);
  680. mHeaderDataFileName = gDirUtil.getFullPath(location, textures_dirname,
  681. cache_filename);
  682. mTexturesDirName = gDirUtil.getFullPath(location, textures_dirname);
  683. }
  684. void LLTextureCache::purgeCache(ELLPath location)
  685. {
  686. mHeaderMutex.lock();
  687. if (!mReadOnly)
  688. {
  689. setDirNames(location);
  690. llassert_always(mHeaderFile == NULL);
  691. }
  692. // Remove the current texture cache.
  693. purgeAllTextures(true);
  694. mHeaderMutex.unlock();
  695. }
  696. // Called from the main thread.
  697. S64 LLTextureCache::initCache(ELLPath location, S64 max_size)
  698. {
  699. S64 entry_size = (9 * max_size) / 25; // 0.36 * max_size
  700. S64 max_entries = entry_size / (TEXTURE_CACHE_ENTRY_SIZE +
  701. TEXTURE_FAST_CACHE_ENTRY_SIZE);
  702. sCacheMaxEntries = (S32)(llmin((S64)sCacheMaxEntries, max_entries));
  703. entry_size = sCacheMaxEntries * (TEXTURE_CACHE_ENTRY_SIZE +
  704. TEXTURE_FAST_CACHE_ENTRY_SIZE);
  705. max_size -= entry_size;
  706. if (sCacheMaxTexturesSize > 0)
  707. {
  708. sCacheMaxTexturesSize = llmin(sCacheMaxTexturesSize, max_size);
  709. }
  710. else
  711. {
  712. sCacheMaxTexturesSize = max_size;
  713. }
  714. max_size -= sCacheMaxTexturesSize;
  715. llinfos << "Headers: " << sCacheMaxEntries << " Textures size: "
  716. << sCacheMaxTexturesSize / (1024 * 1024) << " MB" << llendl;
  717. setDirNames(location);
  718. if (!mReadOnly)
  719. {
  720. LLFile::mkdir(mTexturesDirName);
  721. const char* subdirs = "0123456789abcdef";
  722. for (S32 i = 0; i < 16; ++i)
  723. {
  724. LLFile::mkdir(mTexturesDirName + LL_DIR_DELIM_STR + subdirs[i]);
  725. }
  726. }
  727. readHeaderCache();
  728. // Calculate mTexturesSize and make some room in the texture cache if we
  729. // need it
  730. purgeTextures(true);
  731. return max_size; // unused cache space
  732. }
  733. //----------------------------------------------------------------------------
  734. // mHeaderMutex must be locked for the following methods !
  735. LLFile* LLTextureCache::openHeaderEntriesFile(bool readonly, S32 offset)
  736. {
  737. llassert_always(mHeaderFile == NULL);
  738. const char* flags = readonly ? "rb" : "r+b";
  739. // All code calling openHeaderEntriesFile, immediately calls
  740. // closeHeaderEntriesFile(), so this file is very short-lived.
  741. mHeaderFile = new LLFile(mHeaderEntriesFileName, flags);
  742. if (offset > 0)
  743. {
  744. mHeaderFile->seek(offset);
  745. }
  746. return mHeaderFile;
  747. }
  748. void LLTextureCache::closeHeaderEntriesFile()
  749. {
  750. if (mHeaderFile)
  751. {
  752. delete mHeaderFile;
  753. mHeaderFile = NULL;
  754. }
  755. }
  756. void LLTextureCache::readEntriesHeader()
  757. {
  758. llassert_always(mHeaderFile == NULL);
  759. // mHeaderEntriesInfo initializes to default values so it is safe not to
  760. // read it
  761. if (LLFile::exists(mHeaderEntriesFileName))
  762. {
  763. LLFile::readEx(mHeaderEntriesFileName, (void*)&mHeaderEntriesInfo, 0,
  764. sizeof(EntriesInfo));
  765. }
  766. else // Create an empty entries header.
  767. {
  768. mHeaderEntriesInfo.mVersion = TEXTURE_CACHE_VERSION;
  769. mHeaderEntriesInfo.mAddressSize = ADDRESS_SIZE;
  770. mHeaderEntriesInfo.mEntries = 0;
  771. writeEntriesHeader();
  772. }
  773. }
  774. void LLTextureCache::writeEntriesHeader()
  775. {
  776. llassert_always(mHeaderFile == NULL);
  777. if (!mReadOnly)
  778. {
  779. LLFile::writeEx(mHeaderEntriesFileName, (void*)&mHeaderEntriesInfo, 0,
  780. sizeof(EntriesInfo));
  781. }
  782. }
  783. S32 LLTextureCache::openAndReadEntry(const LLUUID& id, Entry& entry,
  784. bool create)
  785. {
  786. mLRUMutex.lock();
  787. mLRU.erase(id);
  788. mLRUMutex.unlock();
  789. LLMutexLock hlock(&mHeaderMutex);
  790. S32 idx = -1;
  791. id_map_t::iterator iter1 = mHeaderIDMap.find(id);
  792. if (iter1 != mHeaderIDMap.end())
  793. {
  794. idx = iter1->second;
  795. }
  796. if (idx < 0)
  797. {
  798. if (create && !mReadOnly)
  799. {
  800. if (mHeaderEntriesInfo.mEntries < sCacheMaxEntries)
  801. {
  802. // Add an entry to the end of the list
  803. idx = mHeaderEntriesInfo.mEntries++;
  804. }
  805. else if (!mFreeList.empty())
  806. {
  807. std::set<S32>::iterator it = mFreeList.begin();
  808. idx = *it;
  809. mFreeList.erase(it);
  810. }
  811. else
  812. {
  813. mLRUMutex.lock();
  814. // Look for a still valid entry in the LRU
  815. for (uuid_list_t::iterator iter2 = mLRU.begin();
  816. iter2 != mLRU.end(); )
  817. {
  818. uuid_list_t::iterator curiter2 = iter2++;
  819. LLUUID oldid = *curiter2;
  820. // Erase entry from LRU regardless
  821. mLRU.erase(curiter2);
  822. // Look up entry and use it if it is valid
  823. id_map_t::iterator iter3 = mHeaderIDMap.find(oldid);
  824. if (iter3 != mHeaderIDMap.end() && iter3->second >= 0)
  825. {
  826. idx = iter3->second;
  827. // Remove the existing cached texture to release the
  828. // entry index.
  829. removeCachedTexture(oldid);
  830. break;
  831. }
  832. }
  833. // If (idx < 0) at this point, we will rebuild the LRU and
  834. // retry if called from setHeaderCacheEntry(), otherwise this
  835. // should not happen and will trigger an error
  836. mLRUMutex.unlock();
  837. }
  838. if (idx >= 0)
  839. {
  840. entry.mID = id;
  841. entry.mImageSize = -1; // Mark it is a brand-new entry.
  842. entry.mBodySize = 0;
  843. }
  844. }
  845. }
  846. else
  847. {
  848. // Read the entry
  849. S32 bytes_read = sizeof(Entry);
  850. idx_entry_map_t::iterator iter = mUpdatedEntryMap.find(idx);
  851. if (iter != mUpdatedEntryMap.end())
  852. {
  853. entry = iter->second;
  854. }
  855. else
  856. {
  857. bytes_read = readEntryFromHeaderImmediatelyShared(idx, entry);
  858. }
  859. if (bytes_read != sizeof(Entry))
  860. {
  861. clearCorruptedCache() ; // Clear the cache.
  862. idx = -1;
  863. }
  864. // It happens on 64 bits systems, do not know why
  865. else if (entry.mImageSize <= entry.mBodySize)
  866. {
  867. llwarns << "Corrupted entry: " << id << " - Entry image size: "
  868. << entry.mImageSize << " - Entry body size: "
  869. << entry.mBodySize << llendl;
  870. // Erase this entry and the cached texture from the cache.
  871. std::string tex_filename = getTextureFileName(id);
  872. removeEntry(idx, entry, tex_filename);
  873. mUpdatedEntryMap.erase(idx);
  874. idx = -1;
  875. }
  876. }
  877. return idx;
  878. }
  879. // mHeaderMutex must be locked before calling this.
  880. void LLTextureCache::writeEntryToHeaderImmediately(S32& idx, Entry& entry,
  881. bool write_header)
  882. {
  883. LLFile* file;
  884. S32 bytes_written;
  885. S32 offset = sizeof(EntriesInfo) + idx * sizeof(Entry);
  886. if (write_header)
  887. {
  888. file = openHeaderEntriesFile(false, 0);
  889. bytes_written = file->write((U8*)&mHeaderEntriesInfo,
  890. sizeof(EntriesInfo));
  891. if (bytes_written != sizeof(EntriesInfo))
  892. {
  893. clearCorruptedCache(); // Clear the cache.
  894. idx = -1; // Mark the index as invalid.
  895. return;
  896. }
  897. mHeaderFile->seek(offset);
  898. }
  899. else
  900. {
  901. file = openHeaderEntriesFile(false, offset);
  902. }
  903. bytes_written = file->write((U8*)&entry, (S32)sizeof(Entry));
  904. if (bytes_written != sizeof(Entry))
  905. {
  906. clearCorruptedCache(); // Clear the cache.
  907. idx = -1; // Mark the index as invalid.
  908. return;
  909. }
  910. closeHeaderEntriesFile();
  911. mUpdatedEntryMap.erase(idx);
  912. }
  913. // mHeaderMutex must be locked before calling this.
  914. void LLTextureCache::readEntryFromHeaderImmediately(S32& idx, Entry& entry)
  915. {
  916. S32 offset = sizeof(EntriesInfo) + idx * sizeof(Entry);
  917. LLFile* file = openHeaderEntriesFile(true, offset);
  918. S32 bytes_read = file->read((U8*)&entry, (S32)sizeof(Entry));
  919. closeHeaderEntriesFile();
  920. if (bytes_read != sizeof(Entry))
  921. {
  922. clearCorruptedCache(); // Clear the cache.
  923. idx = -1; // Mark the index as invalid.
  924. }
  925. }
  926. S32 LLTextureCache::readEntryFromHeaderImmediatelyShared(S32& idx,
  927. Entry& entry)
  928. {
  929. S32 offset = sizeof(EntriesInfo) + idx * sizeof(Entry);
  930. LLFile* file = new LLFile(mHeaderEntriesFileName, "rb");
  931. if (!file->getStream())
  932. {
  933. delete file;
  934. llwarns << "Could not read: " << mHeaderEntriesFileName << llendl;
  935. return 0;
  936. }
  937. if (offset > 0)
  938. {
  939. file->seek(offset);
  940. }
  941. S32 bytes_read = file->read((U8*)&entry, (S32)sizeof(Entry));
  942. delete file;
  943. return bytes_read;
  944. }
  945. // mHeaderMutex must be locked before calling this.
  946. // Updates an existing entry time stamp, delays writing.
  947. void LLTextureCache::updateEntryTimeStamp(S32 idx, Entry& entry)
  948. {
  949. static const U32 max_entries_without_time_stamp =
  950. (U32)(LLTextureCache::sCacheMaxEntries * 0.75f);
  951. if (mHeaderEntriesInfo.mEntries < max_entries_without_time_stamp)
  952. {
  953. // There are enough empty entry index space, no need to stamp time.
  954. return;
  955. }
  956. if (idx >= 0 && !mReadOnly)
  957. {
  958. entry.mTime = time(NULL);
  959. mUpdatedEntryMap[idx] = entry;
  960. }
  961. }
  962. // Updates an existing entry if needed, writing to header file immediately.
  963. bool LLTextureCache::updateEntry(S32& idx, Entry& entry, S32 new_image_size,
  964. S32 new_data_size)
  965. {
  966. S32 new_body_size = llmax(0, new_data_size - TEXTURE_CACHE_ENTRY_SIZE);
  967. if (new_image_size <= entry.mImageSize && new_body_size <= entry.mBodySize)
  968. {
  969. // Nothing changed, or a higher resolution version is already in cache.
  970. return true;
  971. }
  972. bool purge = false;
  973. mHeaderMutex.lock();
  974. bool update_header = false;
  975. if (entry.mImageSize < 0) // Is a brand-new entry
  976. {
  977. mHeaderIDMap[entry.mID] = idx;
  978. mTexturesSizeMap[entry.mID] = new_body_size;
  979. mTexturesSizeTotal += new_body_size;
  980. // Update Header
  981. update_header = true;
  982. }
  983. else if (entry.mBodySize != new_body_size)
  984. {
  985. // Aready in mHeaderIDMap.
  986. mTexturesSizeMap[entry.mID] = new_body_size;
  987. mTexturesSizeTotal -= entry.mBodySize;
  988. mTexturesSizeTotal += new_body_size;
  989. }
  990. entry.mTime = time(NULL);
  991. entry.mImageSize = new_image_size;
  992. entry.mBodySize = new_body_size;
  993. writeEntryToHeaderImmediately(idx, entry, update_header);
  994. if (mTexturesSizeTotal > sCacheMaxTexturesSize)
  995. {
  996. purge = true;
  997. }
  998. mHeaderMutex.unlock();
  999. if (purge)
  1000. {
  1001. mDoPurge = true;
  1002. }
  1003. return false;
  1004. }
  1005. // mHeaderMutex must be locked before calling this.
  1006. U32 LLTextureCache::openAndReadEntries(std::vector<Entry>& entries)
  1007. {
  1008. U32 num_entries = mHeaderEntriesInfo.mEntries;
  1009. mHeaderIDMap.clear();
  1010. mTexturesSizeMap.clear();
  1011. mFreeList.clear();
  1012. mTexturesSizeTotal = 0;
  1013. LLFile* file = NULL;
  1014. if (mUpdatedEntryMap.empty())
  1015. {
  1016. file = openHeaderEntriesFile(true, (S32)sizeof(EntriesInfo));
  1017. }
  1018. else // Update the header file first.
  1019. {
  1020. file = openHeaderEntriesFile(false, 0);
  1021. if (!file->getStream())
  1022. {
  1023. return 0;
  1024. }
  1025. updatedHeaderEntriesFile();
  1026. file->seek((S32)sizeof(EntriesInfo));
  1027. }
  1028. for (U32 idx = 0; idx < num_entries; ++idx)
  1029. {
  1030. Entry entry;
  1031. S32 bytes_read = file->read((U8*)&entry, (S32)sizeof(Entry));
  1032. if (bytes_read < (S32)sizeof(Entry))
  1033. {
  1034. llwarns << "Corrupted header entries, failed at " << idx << " / "
  1035. << num_entries << llendl;
  1036. closeHeaderEntriesFile();
  1037. purgeAllTextures(false);
  1038. return 0;
  1039. }
  1040. entries.emplace_back(entry);
  1041. if (entry.mImageSize > entry.mBodySize)
  1042. {
  1043. mHeaderIDMap[entry.mID] = idx;
  1044. mTexturesSizeMap[entry.mID] = entry.mBodySize;
  1045. mTexturesSizeTotal += entry.mBodySize;
  1046. }
  1047. else
  1048. {
  1049. mFreeList.insert(idx);
  1050. }
  1051. }
  1052. closeHeaderEntriesFile();
  1053. return num_entries;
  1054. }
  1055. void LLTextureCache::writeEntriesAndClose(const std::vector<Entry>& entries)
  1056. {
  1057. S32 num_entries = entries.size();
  1058. llassert_always(num_entries == (S32)mHeaderEntriesInfo.mEntries);
  1059. if (!mReadOnly)
  1060. {
  1061. LLFile* file = openHeaderEntriesFile(false, (S32)sizeof(EntriesInfo));
  1062. for (S32 idx = 0; idx < num_entries; ++idx)
  1063. {
  1064. S32 bytes_written = file->write((U8*)(&entries[idx]),
  1065. (S32)sizeof(Entry));
  1066. if (bytes_written != sizeof(Entry))
  1067. {
  1068. clearCorruptedCache(); // clear the cache.
  1069. return;
  1070. }
  1071. }
  1072. closeHeaderEntriesFile();
  1073. }
  1074. }
  1075. void LLTextureCache::writeUpdatedEntries()
  1076. {
  1077. mHeaderMutex.lock();
  1078. if (!mReadOnly && !mUpdatedEntryMap.empty())
  1079. {
  1080. openHeaderEntriesFile(false, 0);
  1081. updatedHeaderEntriesFile();
  1082. closeHeaderEntriesFile();
  1083. }
  1084. mHeaderMutex.unlock();
  1085. }
  1086. // mHeaderMutex must be locked and mHeaderFile must be created before calling
  1087. // this.
  1088. void LLTextureCache::updatedHeaderEntriesFile()
  1089. {
  1090. if (!mReadOnly && !mUpdatedEntryMap.empty() && mHeaderFile)
  1091. {
  1092. // EntriesInfo
  1093. mHeaderFile->seek(0);
  1094. S32 bytes_written = mHeaderFile->write((U8*)&mHeaderEntriesInfo,
  1095. sizeof(EntriesInfo));
  1096. if (bytes_written != sizeof(EntriesInfo))
  1097. {
  1098. clearCorruptedCache(); // Clear the cache.
  1099. return;
  1100. }
  1101. // Write each updated entry
  1102. S32 entry_size = (S32)sizeof(Entry);
  1103. S32 prev_idx = -1;
  1104. S32 delta_idx;
  1105. for (idx_entry_map_t::iterator iter = mUpdatedEntryMap.begin(),
  1106. end = mUpdatedEntryMap.end();
  1107. iter != end; ++iter)
  1108. {
  1109. delta_idx = iter->first - prev_idx - 1;
  1110. prev_idx = iter->first;
  1111. if (delta_idx)
  1112. {
  1113. mHeaderFile->seek(delta_idx * entry_size, true);
  1114. }
  1115. bytes_written = mHeaderFile->write((U8*)&iter->second, entry_size);
  1116. if (bytes_written != entry_size)
  1117. {
  1118. clearCorruptedCache(); // Clear the cache.
  1119. return;
  1120. }
  1121. }
  1122. mUpdatedEntryMap.clear();
  1123. }
  1124. }
  1125. // Called from either the main thread or the worker thread
  1126. void LLTextureCache::readHeaderCache()
  1127. {
  1128. mLRUMutex.lock();
  1129. mLRU.clear(); // Always clear the LRU
  1130. mLRUMutex.unlock();
  1131. bool repeat_reading = false;
  1132. {
  1133. LLMutexLock hlock(&mHeaderMutex);
  1134. readEntriesHeader();
  1135. if (mHeaderEntriesInfo.mVersion != TEXTURE_CACHE_VERSION ||
  1136. mHeaderEntriesInfo.mAddressSize != ADDRESS_SIZE)
  1137. {
  1138. if (!mReadOnly)
  1139. {
  1140. purgeAllTextures(false);
  1141. }
  1142. return;
  1143. }
  1144. std::vector<Entry> entries;
  1145. U32 num_entries = openAndReadEntries(entries);
  1146. if (!num_entries)
  1147. {
  1148. return;
  1149. }
  1150. U32 empty_entries = 0;
  1151. typedef std::pair<U32, S32> lru_data_t;
  1152. std::set<lru_data_t> lru;
  1153. std::set<U32> purge_list;
  1154. for (U32 i = 0; i < num_entries; ++i)
  1155. {
  1156. Entry& entry = entries[i];
  1157. if (entry.mImageSize <= 0)
  1158. {
  1159. // This will be in the Free List, do not put it in the LRU
  1160. ++empty_entries;
  1161. }
  1162. else
  1163. {
  1164. lru.emplace(entry.mTime, i);
  1165. if (entry.mBodySize > 0)
  1166. {
  1167. if (entry.mBodySize > entry.mImageSize)
  1168. {
  1169. // Should not happen, failsafe only
  1170. llwarns << "Bad entry: " << i << ": " << entry.mID
  1171. << ": BodySize: " << entry.mBodySize
  1172. << llendl;
  1173. purge_list.insert(i);
  1174. }
  1175. }
  1176. }
  1177. }
  1178. if (num_entries - empty_entries > sCacheMaxEntries)
  1179. {
  1180. // Special case: cache size was reduced, need to remove entries.
  1181. // Note: After we prune entries, we will call this again and
  1182. // create the LRU
  1183. U32 entries_to_purge = num_entries - empty_entries -
  1184. sCacheMaxEntries;
  1185. llinfos << "Texture Cache Entries: " << num_entries << " Max: "
  1186. << sCacheMaxEntries << " Empty: " << empty_entries
  1187. << " Purging: " << entries_to_purge << llendl;
  1188. for (std::set<lru_data_t>::iterator iter = lru.begin(),
  1189. end = lru.end();
  1190. iter != end; ++iter)
  1191. {
  1192. purge_list.insert(iter->second);
  1193. if (purge_list.size() >= entries_to_purge)
  1194. {
  1195. break;
  1196. }
  1197. }
  1198. }
  1199. else
  1200. {
  1201. mLRUMutex.lock();
  1202. S32 lru_entries = (S32)((F32)sCacheMaxEntries *
  1203. TEXTURE_CACHE_LRU_SIZE);
  1204. for (std::set<lru_data_t>::iterator iter = lru.begin(),
  1205. end = lru.end();
  1206. iter != end; ++iter)
  1207. {
  1208. mLRU.emplace(entries[iter->second].mID);
  1209. if (--lru_entries <= 0)
  1210. {
  1211. break;
  1212. }
  1213. }
  1214. mLRUMutex.unlock();
  1215. }
  1216. if (!purge_list.size())
  1217. {
  1218. // Entries are not changed, nothing to do.
  1219. return;
  1220. }
  1221. for (std::set<U32>::iterator iter = purge_list.begin(),
  1222. end = purge_list.end();
  1223. iter != end; ++iter)
  1224. {
  1225. std::string tex_filename =
  1226. getTextureFileName(entries[*iter].mID);
  1227. removeEntry((S32)*iter, entries[*iter], tex_filename);
  1228. }
  1229. // If we removed any entries, we need to rebuild the entries list,
  1230. // write the header, and call this again
  1231. std::vector<Entry> new_entries;
  1232. for (U32 i = 0; i < num_entries; ++i)
  1233. {
  1234. const Entry& entry = entries[i];
  1235. if (entry.mImageSize > 0)
  1236. {
  1237. new_entries.emplace_back(entry);
  1238. }
  1239. }
  1240. mFreeList.clear(); // Recreating list, no longer valid.
  1241. llassert_always(new_entries.size() <= sCacheMaxEntries);
  1242. mHeaderEntriesInfo.mEntries = new_entries.size();
  1243. writeEntriesHeader();
  1244. writeEntriesAndClose(new_entries);
  1245. repeat_reading = true;
  1246. }
  1247. // Repeat with new entries file
  1248. if (repeat_reading)
  1249. {
  1250. readHeaderCache();
  1251. }
  1252. }
  1253. // mHeaderMutex must be locked before calling this.
  1254. void LLTextureCache::clearCorruptedCache()
  1255. {
  1256. llwarns << "The texture cache is corrupted:clearing it." << llendl;
  1257. closeHeaderEntriesFile(); // Close possible file handler
  1258. purgeAllTextures(false); // Clear the cache.
  1259. if (!mReadOnly)
  1260. {
  1261. // Regenerate the directory tree if it does not exist
  1262. LLFile::mkdir(mTexturesDirName);
  1263. const char* subdirs = "0123456789abcdef";
  1264. for (S32 i = 0; i < 16; ++i)
  1265. {
  1266. LLFile::mkdir(mTexturesDirName + LL_DIR_DELIM_STR + subdirs[i]);
  1267. }
  1268. }
  1269. }
  1270. void LLTextureCache::purgeAllTextures(bool purge_directories)
  1271. {
  1272. if (!mReadOnly)
  1273. {
  1274. const char* subdirs = "0123456789abcdef";
  1275. std::string dirname;
  1276. for (S32 i = 0; i < 16; ++i)
  1277. {
  1278. dirname = mTexturesDirName + LL_DIR_DELIM_STR + subdirs[i];
  1279. llinfos << "Deleting files in directory: " << dirname << llendl;
  1280. LLDirIterator::deleteFilesInDir(dirname);
  1281. if (purge_directories)
  1282. {
  1283. LLFile::rmdir(dirname);
  1284. }
  1285. }
  1286. if (purge_directories)
  1287. {
  1288. LLDirIterator::deleteFilesInDir(mTexturesDirName);
  1289. LLFile::rmdir(mTexturesDirName);
  1290. }
  1291. }
  1292. mHeaderIDMap.clear();
  1293. mTexturesSizeMap.clear();
  1294. mTexturesSizeTotal = 0;
  1295. mFreeList.clear();
  1296. mTexturesSizeTotal = 0;
  1297. mUpdatedEntryMap.clear();
  1298. // Info with 0 entries
  1299. mHeaderEntriesInfo.mVersion = TEXTURE_CACHE_VERSION;
  1300. mHeaderEntriesInfo.mAddressSize = ADDRESS_SIZE;
  1301. mHeaderEntriesInfo.mEntries = 0;
  1302. writeEntriesHeader();
  1303. llinfos << "The entire texture cache is cleared." << llendl;
  1304. }
  1305. void LLTextureCache::purgeTextures(bool validate)
  1306. {
  1307. mDoPurge = false;
  1308. if (mReadOnly)
  1309. {
  1310. return;
  1311. }
  1312. if (!validate && mTexturesSizeTotal < sCacheMaxTexturesSize)
  1313. {
  1314. return;
  1315. }
  1316. LLMutexLock hlock(&mHeaderMutex);
  1317. // Read the entries list
  1318. std::vector<Entry> entries;
  1319. U32 num_entries = openAndReadEntries(entries);
  1320. if (!num_entries)
  1321. {
  1322. return; // Nothing to purge
  1323. }
  1324. llinfos << "Purging the cache from old textures..." << llendl;
  1325. // Use mTexturesSizeMap to collect UUIDs of textures with bodies
  1326. typedef std::set<std::pair<U32, S32> > time_idx_set_t;
  1327. time_idx_set_t time_idx_set;
  1328. id_map_t::iterator header_id_map_end = mHeaderIDMap.end();
  1329. for (size_map_t::iterator iter1 = mTexturesSizeMap.begin(),
  1330. end = mTexturesSizeMap.end();
  1331. iter1 != end; ++iter1)
  1332. {
  1333. if (iter1->second > 0)
  1334. {
  1335. id_map_t::iterator iter2 = mHeaderIDMap.find(iter1->first);
  1336. if (iter2 == header_id_map_end)
  1337. {
  1338. llwarns << "mTexturesSizeMap / mHeaderIDMap corrupted."
  1339. << llendl;
  1340. clearCorruptedCache();
  1341. return;
  1342. }
  1343. S32 idx = iter2->second;
  1344. time_idx_set.emplace(entries[idx].mTime, idx);
  1345. }
  1346. }
  1347. // Validate 1/32th of the files on startup
  1348. constexpr U32 FRACTION = 8; // 256 / 8 = 32
  1349. U32 validate_idx = 0;
  1350. if (validate)
  1351. {
  1352. validate_idx = (gSavedSettings.getU32("CacheValidateCounter") /
  1353. FRACTION) * FRACTION;
  1354. U32 next_idx = (validate_idx + FRACTION) % 256;
  1355. gSavedSettings.setU32("CacheValidateCounter", next_idx);
  1356. LL_DEBUGS("TextureCache") << "Validating indexes " << validate_idx
  1357. << " to " << validate_idx + FRACTION - 1
  1358. << LL_ENDL;
  1359. }
  1360. S64 cache_size = mTexturesSizeTotal;
  1361. S64 purged_cache_size =
  1362. (TEXTURE_PURGED_CACHE_SIZE * sCacheMaxTexturesSize) / (S64)100;
  1363. S32 purge_count = 0;
  1364. for (time_idx_set_t::iterator iter = time_idx_set.begin(),
  1365. end = time_idx_set.end();
  1366. iter != end; ++iter)
  1367. {
  1368. S32 idx = iter->second;
  1369. bool purge_entry = false;
  1370. std::string filename = getTextureFileName(entries[idx].mID);
  1371. if (cache_size >= purged_cache_size)
  1372. {
  1373. purge_entry = true;
  1374. }
  1375. else if (validate)
  1376. {
  1377. // Make sure file exists and is the correct size
  1378. U32 uuididx = entries[idx].mID.mData[0];
  1379. if (uuididx >= validate_idx && uuididx < validate_idx + 4)
  1380. {
  1381. LL_DEBUGS("TextureCache") << "Validating: " << filename
  1382. << "Size: " << entries[idx].mBodySize
  1383. << LL_ENDL;
  1384. S32 bodysize = LLFile::getFileSize(filename);
  1385. if (bodysize != entries[idx].mBodySize)
  1386. {
  1387. llwarns << "Purging corrupted cached texture (body size "
  1388. << bodysize << " != " << entries[idx].mBodySize
  1389. << "): " << filename << llendl;
  1390. purge_entry = true;
  1391. }
  1392. }
  1393. }
  1394. else
  1395. {
  1396. break;
  1397. }
  1398. if (purge_entry)
  1399. {
  1400. ++purge_count;
  1401. mFilesToDelete.emplace(entries[idx].mID, filename);
  1402. cache_size -= entries[idx].mBodySize;
  1403. // Remove the entry but not the file:
  1404. removeEntry(idx, entries[idx], filename, false);
  1405. }
  1406. }
  1407. LL_DEBUGS("TextureCache") << "Writing Entries: " << num_entries << LL_ENDL;
  1408. if (purge_count > 0)
  1409. {
  1410. writeEntriesAndClose(entries);
  1411. llinfos << "Purged: " << purge_count << " - Entries: " << num_entries
  1412. << " - Cache size: " << mTexturesSizeTotal / 1048576 << " MB"
  1413. << " - Files scheduled for deletion: " << mFilesToDelete.size()
  1414. << llendl;
  1415. }
  1416. else
  1417. {
  1418. llinfos << "Nothing to purge." << llendl;
  1419. }
  1420. mSlicedPurgeTimer.reset();
  1421. }
  1422. void LLTextureCache::purgeTextureFilesTimeSliced(bool force)
  1423. {
  1424. constexpr F32 delay_between_passes = 2.f; // seconds
  1425. constexpr F32 max_time_per_pass = 0.1f; // seconds
  1426. if (!force && mSlicedPurgeTimer.getElapsedTimeF32() <= delay_between_passes)
  1427. {
  1428. return;
  1429. }
  1430. if (!mFilesToDelete.empty())
  1431. {
  1432. llinfos << "Time-sliced purging with " << mFilesToDelete.size()
  1433. << " files scheduled for deletion" << llendl;
  1434. mSlicedPurgeTimer.reset();
  1435. mHeaderMutex.lock();
  1436. U32 purged = 0;
  1437. std::string filename;
  1438. for (LLTextureCache::purge_map_t::iterator
  1439. iter = mFilesToDelete.begin();
  1440. iter != mFilesToDelete.end(); )
  1441. {
  1442. LLTextureCache::purge_map_t::iterator curiter = iter++;
  1443. // Only remove files for textures that have not been cached again
  1444. // since we selected them for removal !
  1445. if (!mHeaderIDMap.count(curiter->first))
  1446. {
  1447. filename = curiter->second;
  1448. LLFile::remove(filename);
  1449. }
  1450. else
  1451. {
  1452. LL_DEBUGS("TextureCache") << curiter->second
  1453. << " selected for removal, but texture cached again since !"
  1454. << LL_ENDL;
  1455. }
  1456. mFilesToDelete.erase(curiter);
  1457. ++purged;
  1458. if (!force &&
  1459. mSlicedPurgeTimer.getElapsedTimeF32() > max_time_per_pass)
  1460. {
  1461. break;
  1462. }
  1463. }
  1464. if (mFilesToDelete.empty())
  1465. {
  1466. llinfos << "Time-sliced purge finished with " << purged
  1467. << " files deleted in "
  1468. << mSlicedPurgeTimer.getElapsedTimeF32() << "s" << llendl;
  1469. }
  1470. else
  1471. {
  1472. llinfos << "time sliced purge: " << purged << " files deleted in "
  1473. << mSlicedPurgeTimer.getElapsedTimeF32() << "s ("
  1474. << mFilesToDelete.size() << " files left for next pass)"
  1475. << llendl;
  1476. }
  1477. mHeaderMutex.unlock();
  1478. mSlicedPurgeTimer.reset();
  1479. }
  1480. }
  1481. //////////////////////////////////////////////////////////////////////////////
  1482. // Called from pool work threads
  1483. // Reads imagesize from the header, updates timestamp
  1484. S32 LLTextureCache::getHeaderCacheEntry(const LLUUID& id, Entry& entry)
  1485. {
  1486. S32 idx = openAndReadEntry(id, entry, false);
  1487. if (idx >= 0)
  1488. {
  1489. mHeaderMutex.lock();
  1490. updateEntryTimeStamp(idx, entry); // Updates time
  1491. mHeaderMutex.unlock();
  1492. }
  1493. return idx;
  1494. }
  1495. // Writes imagesize to the header, updates timestamp
  1496. S32 LLTextureCache::setHeaderCacheEntry(const LLUUID& id, Entry& entry,
  1497. S32 imagesize, S32 datasize)
  1498. {
  1499. S32 idx = openAndReadEntry(id, entry, true); // read or create
  1500. if (idx < 0) // Retry once
  1501. {
  1502. readHeaderCache(); // We could not write an entry, so refresh the LRU
  1503. idx = openAndReadEntry(id, entry, true);
  1504. }
  1505. if (idx >= 0)
  1506. {
  1507. updateEntry(idx, entry, imagesize, datasize);
  1508. }
  1509. else
  1510. {
  1511. llwarns << "Failed to set cache entry for image: " << id << llendl;
  1512. clearCorruptedCache();
  1513. }
  1514. return idx;
  1515. }
  1516. // Called after mHeaderMutex is locked.
  1517. void LLTextureCache::removeCachedTexture(const LLUUID& id)
  1518. {
  1519. size_map_t::iterator it = mTexturesSizeMap.find(id);
  1520. if (it != mTexturesSizeMap.end())
  1521. {
  1522. mTexturesSizeTotal -= it->second;
  1523. mTexturesSizeMap.erase(id);
  1524. }
  1525. mHeaderIDMap.erase(id);
  1526. LLFile::remove(getTextureFileName(id));
  1527. }
  1528. // Called after mHeaderMutex is locked.
  1529. void LLTextureCache::removeEntry(S32 idx, Entry& entry, std::string& filename,
  1530. bool remove_file)
  1531. {
  1532. bool file_maybe_exists = true; // Always attempt to remove when idx is invalid.
  1533. if (idx >= 0) //valid entry
  1534. {
  1535. if (entry.mBodySize == 0) // Always attempt to remove when mBodySize > 0.
  1536. {
  1537. // Sanity check. Should not exist when body size is 0.
  1538. if (LLFile::exists(filename))
  1539. {
  1540. llwarns << "Entry has body size of zero but file " << filename
  1541. << " exists. Deleting this file, too." << llendl;
  1542. }
  1543. else
  1544. {
  1545. file_maybe_exists = false;
  1546. }
  1547. }
  1548. mTexturesSizeTotal -= entry.mBodySize;
  1549. entry.mImageSize = -1;
  1550. entry.mBodySize = 0;
  1551. mHeaderIDMap.erase(entry.mID);
  1552. mTexturesSizeMap.erase(entry.mID);
  1553. mFreeList.insert(idx);
  1554. }
  1555. if (file_maybe_exists && remove_file)
  1556. {
  1557. LLFile::remove(filename);
  1558. }
  1559. }
  1560. bool LLTextureCache::removeFromCache(const LLUUID& id)
  1561. {
  1562. //llinfos << "Removing texture from cache: " << id << llendl;
  1563. bool ret = false;
  1564. if (!mReadOnly)
  1565. {
  1566. Entry entry;
  1567. S32 idx = openAndReadEntry(id, entry, false);
  1568. std::string tex_filename = getTextureFileName(id);
  1569. mHeaderMutex.lock();
  1570. removeEntry(idx, entry, tex_filename);
  1571. if (idx >= 0)
  1572. {
  1573. writeEntryToHeaderImmediately(idx, entry);
  1574. ret = true;
  1575. }
  1576. mHeaderMutex.unlock();
  1577. }
  1578. return ret;
  1579. }
  1580. ///////////////////////////////////////////////////////////////////////////////
  1581. // Called from the texture fetcher thread (i.e. LLTextureFetch) and from the
  1582. // main thread in HBObjectBackup's and LKFloaterColladaExport's idle callbacks.
  1583. bool LLTextureCache::readFromFile(const std::string& filename,
  1584. const LLUUID& id, S32 offset, S32 size,
  1585. ReadResponder* responder)
  1586. {
  1587. if (offset == 0) // To avoid spam from possible successive chunks reads.
  1588. {
  1589. LL_DEBUGS("TextureCache") << "Request to read texture from file: "
  1590. << filename << LL_ENDL;
  1591. }
  1592. if (!mThreadPoolp)
  1593. {
  1594. return false;
  1595. }
  1596. ++mNumReads;
  1597. mThreadPoolp->getQueue().post(
  1598. [req = LLTextureCacheLocalFileWorker(filename, id, NULL, size, offset,
  1599. 0, responder)]() mutable
  1600. {
  1601. LL_TRACY_TIMER(TRC_TEX_CACHE_READ);
  1602. // Queued file read operations are aborted on shutdown to prevent
  1603. // crashes (because LLThreadPool did already shut down on
  1604. // LLApp::isExiting()); this it not a big deal, since we do not
  1605. // care about rendering textures at this point ! HB
  1606. if (!LLApp::isExiting())
  1607. {
  1608. req.doRead();
  1609. req.finishRead();
  1610. }
  1611. if (gTextureCachep)
  1612. {
  1613. --gTextureCachep->mNumReads;
  1614. }
  1615. });
  1616. return true;
  1617. }
  1618. bool LLTextureCache::readFromCache(const LLUUID& id, S32 offset, S32 size,
  1619. ReadResponder* responder)
  1620. {
  1621. if (!mThreadPoolp)
  1622. {
  1623. return false;
  1624. }
  1625. ++mNumReads;
  1626. mThreadPoolp->getQueue().post(
  1627. [req = LLTextureCacheRemoteWorker(id, NULL, size, offset, 0, NULL, 0,
  1628. responder)]() mutable
  1629. {
  1630. LL_TRACY_TIMER(TRC_TEX_CACHE_READ);
  1631. // Queued file read operations are aborted on shutdown to prevent
  1632. // crashes (because LLThreadPool did already shut down on
  1633. // LLApp::isExiting()); this it not a big deal, since we do not
  1634. // care about rendering textures at this point ! HB
  1635. if (!LLApp::isExiting())
  1636. {
  1637. req.doRead();
  1638. req.finishRead();
  1639. }
  1640. if (gTextureCachep)
  1641. {
  1642. --gTextureCachep->mNumReads;
  1643. }
  1644. });
  1645. return true;
  1646. }
  1647. bool LLTextureCache::writeToCache(const LLUUID& id, U8* data, S32 datasize,
  1648. S32 imagesize, LLPointer<LLImageRaw> rawimage,
  1649. S32 discardlevel, WriteResponder* responder)
  1650. {
  1651. if (!mThreadPoolp || mReadOnly)
  1652. {
  1653. return false;
  1654. }
  1655. if (mDoPurge)
  1656. {
  1657. purgeTextures(false);
  1658. }
  1659. static LLCachedControl<bool> purge_time_sliced(gSavedSettings,
  1660. "CachePurgeTimeSliced");
  1661. purgeTextureFilesTimeSliced(!purge_time_sliced);
  1662. // This may happen when a texture fails to decode...
  1663. if (rawimage.isNull() || !rawimage->getData())
  1664. {
  1665. return false;
  1666. }
  1667. ++mNumWrites;
  1668. mThreadPoolp->getQueue().post(
  1669. [req = LLTextureCacheRemoteWorker(id, data, datasize, 0, imagesize,
  1670. rawimage, discardlevel,
  1671. responder)]() mutable
  1672. {
  1673. LL_TRACY_TIMER(TRC_TEX_CACHE_WRITE);
  1674. // Queued file write operations are aborted on shutdown to prevent
  1675. // crashes (because LLThreadPool did already shut down on
  1676. // LLApp::isExiting()); this it not a big deal, since it simply
  1677. // means the texture will not get cached at all... HB
  1678. if (!LLApp::isExiting())
  1679. {
  1680. req.doWrite();
  1681. req.finishWrite();
  1682. }
  1683. if (gTextureCachep)
  1684. {
  1685. --gTextureCachep->mNumWrites;
  1686. }
  1687. });
  1688. return true;
  1689. }