stream_decoder_mt.c 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018
  1. ///////////////////////////////////////////////////////////////////////////////
  2. //
  3. /// \file stream_decoder_mt.c
  4. /// \brief Multithreaded .xz Stream decoder
  5. //
  6. // Authors: Sebastian Andrzej Siewior
  7. // Lasse Collin
  8. //
  9. // This file has been put into the public domain.
  10. // You can do whatever you want with this file.
  11. //
  12. ///////////////////////////////////////////////////////////////////////////////
  13. #include "common.h"
  14. #include "block_decoder.h"
  15. #include "stream_decoder.h"
  16. #include "index.h"
  17. #include "outqueue.h"
  18. typedef enum {
  19. /// Waiting for work.
  20. /// Main thread may change this to THR_RUN or THR_EXIT.
  21. THR_IDLE,
  22. /// Decoding is in progress.
  23. /// Main thread may change this to THR_STOP or THR_EXIT.
  24. /// The worker thread may change this to THR_IDLE.
  25. THR_RUN,
  26. /// The main thread wants the thread to stop whatever it was doing
  27. /// but not exit. Main thread may change this to THR_EXIT.
  28. /// The worker thread may change this to THR_IDLE.
  29. THR_STOP,
  30. /// The main thread wants the thread to exit.
  31. THR_EXIT,
  32. } worker_state;
  33. typedef enum {
  34. /// Partial updates (storing of worker thread progress
  35. /// to lzma_outbuf) are disabled.
  36. PARTIAL_DISABLED,
  37. /// Main thread requests partial updates to be enabled but
  38. /// no partial update has been done by the worker thread yet.
  39. ///
  40. /// Changing from PARTIAL_DISABLED to PARTIAL_START requires
  41. /// use of the worker-thread mutex. Other transitions don't
  42. /// need a mutex.
  43. PARTIAL_START,
  44. /// Partial updates are enabled and the worker thread has done
  45. /// at least one partial update.
  46. PARTIAL_ENABLED,
  47. } partial_update_mode;
  48. struct worker_thread {
  49. /// Worker state is protected with our mutex.
  50. worker_state state;
  51. /// Input buffer that will contain the whole Block except Block Header.
  52. uint8_t *in;
  53. /// Amount of memory allocated for "in"
  54. size_t in_size;
  55. /// Number of bytes written to "in" by the main thread
  56. size_t in_filled;
  57. /// Number of bytes consumed from "in" by the worker thread.
  58. size_t in_pos;
  59. /// Amount of uncompressed data that has been decoded. This local
  60. /// copy is needed because updating outbuf->pos requires locking
  61. /// the main mutex (coder->mutex).
  62. size_t out_pos;
  63. /// Pointer to the main structure is needed to (1) lock the main
  64. /// mutex (coder->mutex) when updating outbuf->pos and (2) when
  65. /// putting this thread back to the stack of free threads.
  66. struct lzma_stream_coder *coder;
  67. /// The allocator is set by the main thread. Since a copy of the
  68. /// pointer is kept here, the application must not change the
  69. /// allocator before calling lzma_end().
  70. const lzma_allocator *allocator;
  71. /// Output queue buffer to which the uncompressed data is written.
  72. lzma_outbuf *outbuf;
  73. /// Amount of compressed data that has already been decompressed.
  74. /// This is updated from in_pos when our mutex is locked.
  75. /// This is size_t, not uint64_t, because per-thread progress
  76. /// is limited to sizes of allocated buffers.
  77. size_t progress_in;
  78. /// Like progress_in but for uncompressed data.
  79. size_t progress_out;
  80. /// Updating outbuf->pos requires locking the main mutex
  81. /// (coder->mutex). Since the main thread will only read output
  82. /// from the oldest outbuf in the queue, only the worker thread
  83. /// that is associated with the oldest outbuf needs to update its
  84. /// outbuf->pos. This avoids useless mutex contention that would
  85. /// happen if all worker threads were frequently locking the main
  86. /// mutex to update their outbuf->pos.
  87. ///
  88. /// Only when partial_update is something else than PARTIAL_DISABLED,
  89. /// this worker thread will update outbuf->pos after each call to
  90. /// the Block decoder.
  91. partial_update_mode partial_update;
  92. /// Block decoder
  93. lzma_next_coder block_decoder;
  94. /// Thread-specific Block options are needed because the Block
  95. /// decoder modifies the struct given to it at initialization.
  96. lzma_block block_options;
  97. /// Filter chain memory usage
  98. uint64_t mem_filters;
  99. /// Next structure in the stack of free worker threads.
  100. struct worker_thread *next;
  101. mythread_mutex mutex;
  102. mythread_cond cond;
  103. /// The ID of this thread is used to join the thread
  104. /// when it's not needed anymore.
  105. mythread thread_id;
  106. };
  107. struct lzma_stream_coder {
  108. enum {
  109. SEQ_STREAM_HEADER,
  110. SEQ_BLOCK_HEADER,
  111. SEQ_BLOCK_INIT,
  112. SEQ_BLOCK_THR_INIT,
  113. SEQ_BLOCK_THR_RUN,
  114. SEQ_BLOCK_DIRECT_INIT,
  115. SEQ_BLOCK_DIRECT_RUN,
  116. SEQ_INDEX_WAIT_OUTPUT,
  117. SEQ_INDEX_DECODE,
  118. SEQ_STREAM_FOOTER,
  119. SEQ_STREAM_PADDING,
  120. SEQ_ERROR,
  121. } sequence;
  122. /// Block decoder
  123. lzma_next_coder block_decoder;
  124. /// Every Block Header will be decoded into this structure.
  125. /// This is also used to initialize a Block decoder when in
  126. /// direct mode. In threaded mode, a thread-specific copy will
  127. /// be made for decoder initialization because the Block decoder
  128. /// will modify the structure given to it.
  129. lzma_block block_options;
  130. /// Buffer to hold a filter chain for Block Header decoding and
  131. /// initialization. These are freed after successful Block decoder
  132. /// initialization or at stream_decoder_mt_end(). The thread-specific
  133. /// copy of block_options won't hold a pointer to filters[] after
  134. /// initialization.
  135. lzma_filter filters[LZMA_FILTERS_MAX + 1];
  136. /// Stream Flags from Stream Header
  137. lzma_stream_flags stream_flags;
  138. /// Index is hashed so that it can be compared to the sizes of Blocks
  139. /// with O(1) memory usage.
  140. lzma_index_hash *index_hash;
  141. /// Maximum wait time if cannot use all the input and cannot
  142. /// fill the output buffer. This is in milliseconds.
  143. uint32_t timeout;
  144. /// Error code from a worker thread.
  145. ///
  146. /// \note Use mutex.
  147. lzma_ret thread_error;
  148. /// Error code to return after pending output has been copied out. If
  149. /// set in read_output_and_wait(), this is a mirror of thread_error.
  150. /// If set in stream_decode_mt() then it's, for example, error that
  151. /// occurred when decoding Block Header.
  152. lzma_ret pending_error;
  153. /// Number of threads that will be created at maximum.
  154. uint32_t threads_max;
  155. /// Number of thread structures that have been initialized from
  156. /// "threads", and thus the number of worker threads actually
  157. /// created so far.
  158. uint32_t threads_initialized;
  159. /// Array of allocated thread-specific structures. When no threads
  160. /// are in use (direct mode) this is NULL. In threaded mode this
  161. /// points to an array of threads_max number of worker_thread structs.
  162. struct worker_thread *threads;
  163. /// Stack of free threads. When a thread finishes, it puts itself
  164. /// back into this stack. This starts as empty because threads
  165. /// are created only when actually needed.
  166. ///
  167. /// \note Use mutex.
  168. struct worker_thread *threads_free;
  169. /// The most recent worker thread to which the main thread writes
  170. /// the new input from the application.
  171. struct worker_thread *thr;
  172. /// Output buffer queue for decompressed data from the worker threads
  173. ///
  174. /// \note Use mutex with operations that need it.
  175. lzma_outq outq;
  176. mythread_mutex mutex;
  177. mythread_cond cond;
  178. /// Memory usage that will not be exceeded in multi-threaded mode.
  179. /// Single-threaded mode can exceed this even by a large amount.
  180. uint64_t memlimit_threading;
  181. /// Memory usage limit that should never be exceeded.
  182. /// LZMA_MEMLIMIT_ERROR will be returned if decoding isn't possible
  183. /// even in single-threaded mode without exceeding this limit.
  184. uint64_t memlimit_stop;
  185. /// Amount of memory in use by the direct mode decoder
  186. /// (coder->block_decoder). In threaded mode this is 0.
  187. uint64_t mem_direct_mode;
  188. /// Amount of memory needed by the running worker threads.
  189. /// This doesn't include the memory needed by the output buffer.
  190. ///
  191. /// \note Use mutex.
  192. uint64_t mem_in_use;
  193. /// Amount of memory used by the idle (cached) threads.
  194. ///
  195. /// \note Use mutex.
  196. uint64_t mem_cached;
  197. /// Amount of memory needed for the filter chain of the next Block.
  198. uint64_t mem_next_filters;
  199. /// Amount of memory needed for the thread-specific input buffer
  200. /// for the next Block.
  201. uint64_t mem_next_in;
  202. /// Amount of memory actually needed to decode the next Block
  203. /// in threaded mode. This is
  204. /// mem_next_filters + mem_next_in + memory needed for lzma_outbuf.
  205. uint64_t mem_next_block;
  206. /// Amount of compressed data in Stream Header + Blocks that have
  207. /// already been finished.
  208. ///
  209. /// \note Use mutex.
  210. uint64_t progress_in;
  211. /// Amount of uncompressed data in Blocks that have already
  212. /// been finished.
  213. ///
  214. /// \note Use mutex.
  215. uint64_t progress_out;
  216. /// If true, LZMA_NO_CHECK is returned if the Stream has
  217. /// no integrity check.
  218. bool tell_no_check;
  219. /// If true, LZMA_UNSUPPORTED_CHECK is returned if the Stream has
  220. /// an integrity check that isn't supported by this liblzma build.
  221. bool tell_unsupported_check;
  222. /// If true, LZMA_GET_CHECK is returned after decoding Stream Header.
  223. bool tell_any_check;
  224. /// If true, we will tell the Block decoder to skip calculating
  225. /// and verifying the integrity check.
  226. bool ignore_check;
  227. /// If true, we will decode concatenated Streams that possibly have
  228. /// Stream Padding between or after them. LZMA_STREAM_END is returned
  229. /// once the application isn't giving us any new input (LZMA_FINISH),
  230. /// and we aren't in the middle of a Stream, and possible
  231. /// Stream Padding is a multiple of four bytes.
  232. bool concatenated;
  233. /// If true, we will return any errors immediately instead of first
  234. /// producing all output before the location of the error.
  235. bool fail_fast;
  236. /// When decoding concatenated Streams, this is true as long as we
  237. /// are decoding the first Stream. This is needed to avoid misleading
  238. /// LZMA_FORMAT_ERROR in case the later Streams don't have valid magic
  239. /// bytes.
  240. bool first_stream;
  241. /// This is used to track if the previous call to stream_decode_mt()
  242. /// had output space (*out_pos < out_size) and managed to fill the
  243. /// output buffer (*out_pos == out_size). This may be set to true
  244. /// in read_output_and_wait(). This is read and then reset to false
  245. /// at the beginning of stream_decode_mt().
  246. ///
  247. /// This is needed to support applications that call lzma_code() in
  248. /// such a way that more input is provided only when lzma_code()
  249. /// didn't fill the output buffer completely. Basically, this makes
  250. /// it easier to convert such applications from single-threaded
  251. /// decoder to multi-threaded decoder.
  252. bool out_was_filled;
  253. /// Write position in buffer[] and position in Stream Padding
  254. size_t pos;
  255. /// Buffer to hold Stream Header, Block Header, and Stream Footer.
  256. /// Block Header has biggest maximum size.
  257. uint8_t buffer[LZMA_BLOCK_HEADER_SIZE_MAX];
  258. };
  259. /// Enables updating of outbuf->pos. This is a callback function that is
  260. /// used with lzma_outq_enable_partial_output().
  261. static void
  262. worker_enable_partial_update(void *thr_ptr)
  263. {
  264. struct worker_thread *thr = thr_ptr;
  265. mythread_sync(thr->mutex) {
  266. thr->partial_update = PARTIAL_START;
  267. mythread_cond_signal(&thr->cond);
  268. }
  269. }
  270. /// Things do to at THR_STOP or when finishing a Block.
  271. /// This is called with thr->mutex locked.
  272. static void
  273. worker_stop(struct worker_thread *thr)
  274. {
  275. // Update memory usage counters.
  276. thr->coder->mem_in_use -= thr->in_size;
  277. thr->in_size = 0; // thr->in was freed above.
  278. thr->coder->mem_in_use -= thr->mem_filters;
  279. thr->coder->mem_cached += thr->mem_filters;
  280. // Put this thread to the stack of free threads.
  281. thr->next = thr->coder->threads_free;
  282. thr->coder->threads_free = thr;
  283. mythread_cond_signal(&thr->coder->cond);
  284. return;
  285. }
  286. static MYTHREAD_RET_TYPE
  287. worker_decoder(void *thr_ptr)
  288. {
  289. struct worker_thread *thr = thr_ptr;
  290. size_t in_filled;
  291. partial_update_mode partial_update;
  292. lzma_ret ret;
  293. next_loop_lock:
  294. mythread_mutex_lock(&thr->mutex);
  295. next_loop_unlocked:
  296. if (thr->state == THR_IDLE) {
  297. mythread_cond_wait(&thr->cond, &thr->mutex);
  298. goto next_loop_unlocked;
  299. }
  300. if (thr->state == THR_EXIT) {
  301. mythread_mutex_unlock(&thr->mutex);
  302. lzma_free(thr->in, thr->allocator);
  303. lzma_next_end(&thr->block_decoder, thr->allocator);
  304. mythread_mutex_destroy(&thr->mutex);
  305. mythread_cond_destroy(&thr->cond);
  306. return MYTHREAD_RET_VALUE;
  307. }
  308. if (thr->state == THR_STOP) {
  309. thr->state = THR_IDLE;
  310. mythread_mutex_unlock(&thr->mutex);
  311. mythread_sync(thr->coder->mutex) {
  312. worker_stop(thr);
  313. }
  314. goto next_loop_lock;
  315. }
  316. assert(thr->state == THR_RUN);
  317. // Update progress info for get_progress().
  318. thr->progress_in = thr->in_pos;
  319. thr->progress_out = thr->out_pos;
  320. // If we don't have any new input, wait for a signal from the main
  321. // thread except if partial output has just been enabled. In that
  322. // case we will do one normal run so that the partial output info
  323. // gets passed to the main thread. The call to block_decoder.code()
  324. // is useless but harmless as it can occur only once per Block.
  325. in_filled = thr->in_filled;
  326. partial_update = thr->partial_update;
  327. if (in_filled == thr->in_pos && partial_update != PARTIAL_START) {
  328. mythread_cond_wait(&thr->cond, &thr->mutex);
  329. goto next_loop_unlocked;
  330. }
  331. mythread_mutex_unlock(&thr->mutex);
  332. // Pass the input in small chunks to the Block decoder.
  333. // This way we react reasonably fast if we are told to stop/exit,
  334. // and (when partial update is enabled) we tell about our progress
  335. // to the main thread frequently enough.
  336. const size_t chunk_size = 16384;
  337. if ((in_filled - thr->in_pos) > chunk_size)
  338. in_filled = thr->in_pos + chunk_size;
  339. ret = thr->block_decoder.code(
  340. thr->block_decoder.coder, thr->allocator,
  341. thr->in, &thr->in_pos, in_filled,
  342. thr->outbuf->buf, &thr->out_pos,
  343. thr->outbuf->allocated, LZMA_RUN);
  344. if (ret == LZMA_OK) {
  345. if (partial_update != PARTIAL_DISABLED) {
  346. // The main thread uses thr->mutex to change from
  347. // PARTIAL_DISABLED to PARTIAL_START. The main thread
  348. // doesn't care about this variable after that so we
  349. // can safely change it here to PARTIAL_ENABLED
  350. // without a mutex.
  351. thr->partial_update = PARTIAL_ENABLED;
  352. // The main thread is reading decompressed data
  353. // from thr->outbuf. Tell the main thread about
  354. // our progress.
  355. //
  356. // NOTE: It's possible that we consumed input without
  357. // producing any new output so it's possible that
  358. // only in_pos has changed. In case of PARTIAL_START
  359. // it is possible that neither in_pos nor out_pos has
  360. // changed.
  361. mythread_sync(thr->coder->mutex) {
  362. thr->outbuf->pos = thr->out_pos;
  363. thr->outbuf->decoder_in_pos = thr->in_pos;
  364. mythread_cond_signal(&thr->coder->cond);
  365. }
  366. }
  367. goto next_loop_lock;
  368. }
  369. // Either we finished successfully (LZMA_STREAM_END) or an error
  370. // occurred. Both cases are handled almost identically. The error
  371. // case requires updating thr->coder->thread_error.
  372. //
  373. // The sizes are in the Block Header and the Block decoder
  374. // checks that they match, thus we know these:
  375. assert(ret != LZMA_STREAM_END || thr->in_pos == thr->in_size);
  376. assert(ret != LZMA_STREAM_END
  377. || thr->out_pos == thr->block_options.uncompressed_size);
  378. // Free the input buffer. Don't update in_size as we need
  379. // it later to update thr->coder->mem_in_use.
  380. lzma_free(thr->in, thr->allocator);
  381. thr->in = NULL;
  382. mythread_sync(thr->mutex) {
  383. if (thr->state != THR_EXIT)
  384. thr->state = THR_IDLE;
  385. }
  386. mythread_sync(thr->coder->mutex) {
  387. // Move our progress info to the main thread.
  388. thr->coder->progress_in += thr->in_pos;
  389. thr->coder->progress_out += thr->out_pos;
  390. thr->progress_in = 0;
  391. thr->progress_out = 0;
  392. // Mark the outbuf as finished.
  393. thr->outbuf->pos = thr->out_pos;
  394. thr->outbuf->decoder_in_pos = thr->in_pos;
  395. thr->outbuf->finished = true;
  396. thr->outbuf->finish_ret = ret;
  397. thr->outbuf = NULL;
  398. // If an error occurred, tell it to the main thread.
  399. if (ret != LZMA_STREAM_END
  400. && thr->coder->thread_error == LZMA_OK)
  401. thr->coder->thread_error = ret;
  402. worker_stop(thr);
  403. }
  404. goto next_loop_lock;
  405. }
  406. /// Tells the worker threads to exit and waits for them to terminate.
  407. static void
  408. threads_end(struct lzma_stream_coder *coder, const lzma_allocator *allocator)
  409. {
  410. for (uint32_t i = 0; i < coder->threads_initialized; ++i) {
  411. mythread_sync(coder->threads[i].mutex) {
  412. coder->threads[i].state = THR_EXIT;
  413. mythread_cond_signal(&coder->threads[i].cond);
  414. }
  415. }
  416. for (uint32_t i = 0; i < coder->threads_initialized; ++i)
  417. mythread_join(coder->threads[i].thread_id);
  418. lzma_free(coder->threads, allocator);
  419. coder->threads_initialized = 0;
  420. coder->threads = NULL;
  421. coder->threads_free = NULL;
  422. // The threads don't update these when they exit. Do it here.
  423. coder->mem_in_use = 0;
  424. coder->mem_cached = 0;
  425. return;
  426. }
  427. static void
  428. threads_stop(struct lzma_stream_coder *coder)
  429. {
  430. for (uint32_t i = 0; i < coder->threads_initialized; ++i) {
  431. mythread_sync(coder->threads[i].mutex) {
  432. // The state must be changed conditionally because
  433. // THR_IDLE -> THR_STOP is not a valid state change.
  434. if (coder->threads[i].state != THR_IDLE) {
  435. coder->threads[i].state = THR_STOP;
  436. mythread_cond_signal(&coder->threads[i].cond);
  437. }
  438. }
  439. }
  440. return;
  441. }
  442. /// Initialize a new worker_thread structure and create a new thread.
  443. static lzma_ret
  444. initialize_new_thread(struct lzma_stream_coder *coder,
  445. const lzma_allocator *allocator)
  446. {
  447. // Allocate the coder->threads array if needed. It's done here instead
  448. // of when initializing the decoder because we don't need this if we
  449. // use the direct mode (we may even free coder->threads in the middle
  450. // of the file if we switch from threaded to direct mode).
  451. if (coder->threads == NULL) {
  452. coder->threads = lzma_alloc(
  453. coder->threads_max * sizeof(struct worker_thread),
  454. allocator);
  455. if (coder->threads == NULL)
  456. return LZMA_MEM_ERROR;
  457. }
  458. // Pick a free structure.
  459. assert(coder->threads_initialized < coder->threads_max);
  460. struct worker_thread *thr
  461. = &coder->threads[coder->threads_initialized];
  462. if (mythread_mutex_init(&thr->mutex))
  463. goto error_mutex;
  464. if (mythread_cond_init(&thr->cond))
  465. goto error_cond;
  466. thr->state = THR_IDLE;
  467. thr->in = NULL;
  468. thr->in_size = 0;
  469. thr->allocator = allocator;
  470. thr->coder = coder;
  471. thr->outbuf = NULL;
  472. thr->block_decoder = LZMA_NEXT_CODER_INIT;
  473. thr->mem_filters = 0;
  474. if (mythread_create(&thr->thread_id, worker_decoder, thr))
  475. goto error_thread;
  476. ++coder->threads_initialized;
  477. coder->thr = thr;
  478. return LZMA_OK;
  479. error_thread:
  480. mythread_cond_destroy(&thr->cond);
  481. error_cond:
  482. mythread_mutex_destroy(&thr->mutex);
  483. error_mutex:
  484. return LZMA_MEM_ERROR;
  485. }
  486. static lzma_ret
  487. get_thread(struct lzma_stream_coder *coder, const lzma_allocator *allocator)
  488. {
  489. // If there is a free structure on the stack, use it.
  490. mythread_sync(coder->mutex) {
  491. if (coder->threads_free != NULL) {
  492. coder->thr = coder->threads_free;
  493. coder->threads_free = coder->threads_free->next;
  494. // The thread is no longer in the cache so subtract
  495. // it from the cached memory usage. Don't add it
  496. // to mem_in_use though; the caller will handle it
  497. // since it knows how much memory it will actually
  498. // use (the filter chain might change).
  499. coder->mem_cached -= coder->thr->mem_filters;
  500. }
  501. }
  502. if (coder->thr == NULL) {
  503. assert(coder->threads_initialized < coder->threads_max);
  504. // Initialize a new thread.
  505. return_if_error(initialize_new_thread(coder, allocator));
  506. }
  507. coder->thr->in_filled = 0;
  508. coder->thr->in_pos = 0;
  509. coder->thr->out_pos = 0;
  510. coder->thr->progress_in = 0;
  511. coder->thr->progress_out = 0;
  512. coder->thr->partial_update = PARTIAL_DISABLED;
  513. return LZMA_OK;
  514. }
  515. static lzma_ret
  516. read_output_and_wait(struct lzma_stream_coder *coder,
  517. const lzma_allocator *allocator,
  518. uint8_t *restrict out, size_t *restrict out_pos,
  519. size_t out_size,
  520. bool *input_is_possible,
  521. bool waiting_allowed,
  522. mythread_condtime *wait_abs, bool *has_blocked)
  523. {
  524. lzma_ret ret = LZMA_OK;
  525. mythread_sync(coder->mutex) {
  526. do {
  527. // Get as much output from the queue as is possible
  528. // without blocking.
  529. const size_t out_start = *out_pos;
  530. do {
  531. ret = lzma_outq_read(&coder->outq, allocator,
  532. out, out_pos, out_size,
  533. NULL, NULL);
  534. // If a Block was finished, tell the worker
  535. // thread of the next Block (if it is still
  536. // running) to start telling the main thread
  537. // when new output is available.
  538. if (ret == LZMA_STREAM_END)
  539. lzma_outq_enable_partial_output(
  540. &coder->outq,
  541. &worker_enable_partial_update);
  542. // Loop until a Block wasn't finished.
  543. // It's important to loop around even if
  544. // *out_pos == out_size because there could
  545. // be an empty Block that will return
  546. // LZMA_STREAM_END without needing any
  547. // output space.
  548. } while (ret == LZMA_STREAM_END);
  549. // Check if lzma_outq_read reported an error from
  550. // the Block decoder.
  551. if (ret != LZMA_OK)
  552. break;
  553. // If the output buffer is now full but it wasn't full
  554. // when this function was called, set out_was_filled.
  555. // This way the next call to stream_decode_mt() knows
  556. // that some output was produced and no output space
  557. // remained in the previous call to stream_decode_mt().
  558. if (*out_pos == out_size && *out_pos != out_start)
  559. coder->out_was_filled = true;
  560. // Check if any thread has indicated an error.
  561. if (coder->thread_error != LZMA_OK) {
  562. // If LZMA_FAIL_FAST was used, report errors
  563. // from worker threads immediately.
  564. if (coder->fail_fast) {
  565. ret = coder->thread_error;
  566. break;
  567. }
  568. // Otherwise set pending_error. The value we
  569. // set here will not actually get used other
  570. // than working as a flag that an error has
  571. // occurred. This is because in SEQ_ERROR
  572. // all output before the error will be read
  573. // first by calling this function, and once we
  574. // reach the location of the (first) error the
  575. // error code from the above lzma_outq_read()
  576. // will be returned to the application.
  577. //
  578. // Use LZMA_PROG_ERROR since the value should
  579. // never leak to the application. It's
  580. // possible that pending_error has already
  581. // been set but that doesn't matter: if we get
  582. // here, pending_error only works as a flag.
  583. coder->pending_error = LZMA_PROG_ERROR;
  584. }
  585. // Check if decoding of the next Block can be started.
  586. // The memusage of the active threads must be low
  587. // enough, there must be a free buffer slot in the
  588. // output queue, and there must be a free thread
  589. // (that can be either created or an existing one
  590. // reused).
  591. //
  592. // NOTE: This is checked after reading the output
  593. // above because reading the output can free a slot in
  594. // the output queue and also reduce active memusage.
  595. //
  596. // NOTE: If output queue is empty, then input will
  597. // always be possible.
  598. if (input_is_possible != NULL
  599. && coder->memlimit_threading
  600. - coder->mem_in_use
  601. - coder->outq.mem_in_use
  602. >= coder->mem_next_block
  603. && lzma_outq_has_buf(&coder->outq)
  604. && (coder->threads_initialized
  605. < coder->threads_max
  606. || coder->threads_free
  607. != NULL)) {
  608. *input_is_possible = true;
  609. break;
  610. }
  611. // If the caller doesn't want us to block, return now.
  612. if (!waiting_allowed)
  613. break;
  614. // This check is needed only when input_is_possible
  615. // is NULL. We must return if we aren't waiting for
  616. // input to become possible and there is no more
  617. // output coming from the queue.
  618. if (lzma_outq_is_empty(&coder->outq)) {
  619. assert(input_is_possible == NULL);
  620. break;
  621. }
  622. // If there is more data available from the queue,
  623. // our out buffer must be full and we need to return
  624. // so that the application can provide more output
  625. // space.
  626. //
  627. // NOTE: In general lzma_outq_is_readable() can return
  628. // true also when there are no more bytes available.
  629. // This can happen when a Block has finished without
  630. // providing any new output. We know that this is not
  631. // the case because in the beginning of this loop we
  632. // tried to read as much as possible even when we had
  633. // no output space left and the mutex has been locked
  634. // all the time (so worker threads cannot have changed
  635. // anything). Thus there must be actual pending output
  636. // in the queue.
  637. if (lzma_outq_is_readable(&coder->outq)) {
  638. assert(*out_pos == out_size);
  639. break;
  640. }
  641. // If the application stops providing more input
  642. // in the middle of a Block, there will eventually
  643. // be one worker thread left that is stuck waiting for
  644. // more input (that might never arrive) and a matching
  645. // outbuf which the worker thread cannot finish due
  646. // to lack of input. We must detect this situation,
  647. // otherwise we would end up waiting indefinitely
  648. // (if no timeout is in use) or keep returning
  649. // LZMA_TIMED_OUT while making no progress. Thus, the
  650. // application would never get LZMA_BUF_ERROR from
  651. // lzma_code() which would tell the application that
  652. // no more progress is possible. No LZMA_BUF_ERROR
  653. // means that, for example, truncated .xz files could
  654. // cause an infinite loop.
  655. //
  656. // A worker thread doing partial updates will
  657. // store not only the output position in outbuf->pos
  658. // but also the matching input position in
  659. // outbuf->decoder_in_pos. Here we check if that
  660. // input position matches the amount of input that
  661. // the worker thread has been given (in_filled).
  662. // If so, we must return and not wait as no more
  663. // output will be coming without first getting more
  664. // input to the worker thread. If the application
  665. // keeps calling lzma_code() without providing more
  666. // input, it will eventually get LZMA_BUF_ERROR.
  667. //
  668. // NOTE: We can read partial_update and in_filled
  669. // without thr->mutex as only the main thread
  670. // modifies these variables. decoder_in_pos requires
  671. // coder->mutex which we are already holding.
  672. if (coder->thr != NULL && coder->thr->partial_update
  673. != PARTIAL_DISABLED) {
  674. // There is exactly one outbuf in the queue.
  675. assert(coder->thr->outbuf == coder->outq.head);
  676. assert(coder->thr->outbuf == coder->outq.tail);
  677. if (coder->thr->outbuf->decoder_in_pos
  678. == coder->thr->in_filled)
  679. break;
  680. }
  681. // Wait for input or output to become possible.
  682. if (coder->timeout != 0) {
  683. // See the comment in stream_encoder_mt.c
  684. // about why mythread_condtime_set() is used
  685. // like this.
  686. //
  687. // FIXME?
  688. // In contrast to the encoder, this calls
  689. // _condtime_set while the mutex is locked.
  690. if (!*has_blocked) {
  691. *has_blocked = true;
  692. mythread_condtime_set(wait_abs,
  693. &coder->cond,
  694. coder->timeout);
  695. }
  696. if (mythread_cond_timedwait(&coder->cond,
  697. &coder->mutex,
  698. wait_abs) != 0) {
  699. ret = LZMA_TIMED_OUT;
  700. break;
  701. }
  702. } else {
  703. mythread_cond_wait(&coder->cond,
  704. &coder->mutex);
  705. }
  706. } while (ret == LZMA_OK);
  707. }
  708. // If we are returning an error, then the application cannot get
  709. // more output from us and thus keeping the threads running is
  710. // useless and waste of CPU time.
  711. if (ret != LZMA_OK && ret != LZMA_TIMED_OUT)
  712. threads_stop(coder);
  713. return ret;
  714. }
  715. static lzma_ret
  716. decode_block_header(struct lzma_stream_coder *coder,
  717. const lzma_allocator *allocator, const uint8_t *restrict in,
  718. size_t *restrict in_pos, size_t in_size)
  719. {
  720. if (*in_pos >= in_size)
  721. return LZMA_OK;
  722. if (coder->pos == 0) {
  723. // Detect if it's Index.
  724. if (in[*in_pos] == INDEX_INDICATOR)
  725. return LZMA_INDEX_DETECTED;
  726. // Calculate the size of the Block Header. Note that
  727. // Block Header decoder wants to see this byte too
  728. // so don't advance *in_pos.
  729. coder->block_options.header_size
  730. = lzma_block_header_size_decode(
  731. in[*in_pos]);
  732. }
  733. // Copy the Block Header to the internal buffer.
  734. lzma_bufcpy(in, in_pos, in_size, coder->buffer, &coder->pos,
  735. coder->block_options.header_size);
  736. // Return if we didn't get the whole Block Header yet.
  737. if (coder->pos < coder->block_options.header_size)
  738. return LZMA_OK;
  739. coder->pos = 0;
  740. // Version 1 is needed to support the .ignore_check option.
  741. coder->block_options.version = 1;
  742. // Block Header decoder will initialize all members of this array
  743. // so we don't need to do it here.
  744. coder->block_options.filters = coder->filters;
  745. // Decode the Block Header.
  746. return_if_error(lzma_block_header_decode(&coder->block_options,
  747. allocator, coder->buffer));
  748. // If LZMA_IGNORE_CHECK was used, this flag needs to be set.
  749. // It has to be set after lzma_block_header_decode() because
  750. // it always resets this to false.
  751. coder->block_options.ignore_check = coder->ignore_check;
  752. // coder->block_options is ready now.
  753. return LZMA_STREAM_END;
  754. }
  755. /// Get the size of the Compressed Data + Block Padding + Check.
  756. static size_t
  757. comp_blk_size(const struct lzma_stream_coder *coder)
  758. {
  759. return vli_ceil4(coder->block_options.compressed_size)
  760. + lzma_check_size(coder->stream_flags.check);
  761. }
  762. /// Returns true if the size (compressed or uncompressed) is such that
  763. /// threaded decompression cannot be used. Sizes that are too big compared
  764. /// to SIZE_MAX must be rejected to avoid integer overflows and truncations
  765. /// when lzma_vli is assigned to a size_t.
  766. static bool
  767. is_direct_mode_needed(lzma_vli size)
  768. {
  769. return size == LZMA_VLI_UNKNOWN || size > SIZE_MAX / 3;
  770. }
  771. static lzma_ret
  772. stream_decoder_reset(struct lzma_stream_coder *coder,
  773. const lzma_allocator *allocator)
  774. {
  775. // Initialize the Index hash used to verify the Index.
  776. coder->index_hash = lzma_index_hash_init(coder->index_hash, allocator);
  777. if (coder->index_hash == NULL)
  778. return LZMA_MEM_ERROR;
  779. // Reset the rest of the variables.
  780. coder->sequence = SEQ_STREAM_HEADER;
  781. coder->pos = 0;
  782. return LZMA_OK;
  783. }
  784. static lzma_ret
  785. stream_decode_mt(void *coder_ptr, const lzma_allocator *allocator,
  786. const uint8_t *restrict in, size_t *restrict in_pos,
  787. size_t in_size,
  788. uint8_t *restrict out, size_t *restrict out_pos,
  789. size_t out_size, lzma_action action)
  790. {
  791. struct lzma_stream_coder *coder = coder_ptr;
  792. mythread_condtime wait_abs;
  793. bool has_blocked = false;
  794. // Determine if in SEQ_BLOCK_HEADER and SEQ_BLOCK_THR_RUN we should
  795. // tell read_output_and_wait() to wait until it can fill the output
  796. // buffer (or a timeout occurs). Two conditions must be met:
  797. //
  798. // (1) If the caller provided no new input. The reason for this
  799. // can be, for example, the end of the file or that there is
  800. // a pause in the input stream and more input is available
  801. // a little later. In this situation we should wait for output
  802. // because otherwise we would end up in a busy-waiting loop where
  803. // we make no progress and the application just calls us again
  804. // without providing any new input. This would then result in
  805. // LZMA_BUF_ERROR even though more output would be available
  806. // once the worker threads decode more data.
  807. //
  808. // (2) Even if (1) is true, we will not wait if the previous call to
  809. // this function managed to produce some output and the output
  810. // buffer became full. This is for compatibility with applications
  811. // that call lzma_code() in such a way that new input is provided
  812. // only when the output buffer didn't become full. Without this
  813. // trick such applications would have bad performance (bad
  814. // parallelization due to decoder not getting input fast enough).
  815. //
  816. // NOTE: Such loops might require that timeout is disabled (0)
  817. // if they assume that output-not-full implies that all input has
  818. // been consumed. If and only if timeout is enabled, we may return
  819. // when output isn't full *and* not all input has been consumed.
  820. //
  821. // However, if LZMA_FINISH is used, the above is ignored and we always
  822. // wait (timeout can still cause us to return) because we know that
  823. // we won't get any more input. This matters if the input file is
  824. // truncated and we are doing single-shot decoding, that is,
  825. // timeout = 0 and LZMA_FINISH is used on the first call to
  826. // lzma_code() and the output buffer is known to be big enough
  827. // to hold all uncompressed data:
  828. //
  829. // - If LZMA_FINISH wasn't handled specially, we could return
  830. // LZMA_OK before providing all output that is possible with the
  831. // truncated input. The rest would be available if lzma_code() was
  832. // called again but then it's not single-shot decoding anymore.
  833. //
  834. // - By handling LZMA_FINISH specially here, the first call will
  835. // produce all the output, matching the behavior of the
  836. // single-threaded decoder.
  837. //
  838. // So it's a very specific corner case but also easy to avoid. Note
  839. // that this special handling of LZMA_FINISH has no effect for
  840. // single-shot decoding when the input file is valid (not truncated);
  841. // premature LZMA_OK wouldn't be possible as long as timeout = 0.
  842. const bool waiting_allowed = action == LZMA_FINISH
  843. || (*in_pos == in_size && !coder->out_was_filled);
  844. coder->out_was_filled = false;
  845. while (true)
  846. switch (coder->sequence) {
  847. case SEQ_STREAM_HEADER: {
  848. // Copy the Stream Header to the internal buffer.
  849. const size_t in_old = *in_pos;
  850. lzma_bufcpy(in, in_pos, in_size, coder->buffer, &coder->pos,
  851. LZMA_STREAM_HEADER_SIZE);
  852. coder->progress_in += *in_pos - in_old;
  853. // Return if we didn't get the whole Stream Header yet.
  854. if (coder->pos < LZMA_STREAM_HEADER_SIZE)
  855. return LZMA_OK;
  856. coder->pos = 0;
  857. // Decode the Stream Header.
  858. const lzma_ret ret = lzma_stream_header_decode(
  859. &coder->stream_flags, coder->buffer);
  860. if (ret != LZMA_OK)
  861. return ret == LZMA_FORMAT_ERROR && !coder->first_stream
  862. ? LZMA_DATA_ERROR : ret;
  863. // If we are decoding concatenated Streams, and the later
  864. // Streams have invalid Header Magic Bytes, we give
  865. // LZMA_DATA_ERROR instead of LZMA_FORMAT_ERROR.
  866. coder->first_stream = false;
  867. // Copy the type of the Check so that Block Header and Block
  868. // decoders see it.
  869. coder->block_options.check = coder->stream_flags.check;
  870. // Even if we return LZMA_*_CHECK below, we want
  871. // to continue from Block Header decoding.
  872. coder->sequence = SEQ_BLOCK_HEADER;
  873. // Detect if there's no integrity check or if it is
  874. // unsupported if those were requested by the application.
  875. if (coder->tell_no_check && coder->stream_flags.check
  876. == LZMA_CHECK_NONE)
  877. return LZMA_NO_CHECK;
  878. if (coder->tell_unsupported_check
  879. && !lzma_check_is_supported(
  880. coder->stream_flags.check))
  881. return LZMA_UNSUPPORTED_CHECK;
  882. if (coder->tell_any_check)
  883. return LZMA_GET_CHECK;
  884. }
  885. // Fall through
  886. case SEQ_BLOCK_HEADER: {
  887. const size_t in_old = *in_pos;
  888. const lzma_ret ret = decode_block_header(coder, allocator,
  889. in, in_pos, in_size);
  890. coder->progress_in += *in_pos - in_old;
  891. if (ret == LZMA_OK) {
  892. // We didn't decode the whole Block Header yet.
  893. //
  894. // Read output from the queue before returning. This
  895. // is important because it is possible that the
  896. // application doesn't have any new input available
  897. // immediately. If we didn't try to copy output from
  898. // the output queue here, lzma_code() could end up
  899. // returning LZMA_BUF_ERROR even though queued output
  900. // is available.
  901. //
  902. // If the lzma_code() call provided at least one input
  903. // byte, only copy as much data from the output queue
  904. // as is available immediately. This way the
  905. // application will be able to provide more input
  906. // without a delay.
  907. //
  908. // On the other hand, if lzma_code() was called with
  909. // an empty input buffer(*), treat it specially: try
  910. // to fill the output buffer even if it requires
  911. // waiting for the worker threads to provide output
  912. // (timeout, if specified, can still cause us to
  913. // return).
  914. //
  915. // - This way the application will be able to get all
  916. // data that can be decoded from the input provided
  917. // so far.
  918. //
  919. // - We avoid both premature LZMA_BUF_ERROR and
  920. // busy-waiting where the application repeatedly
  921. // calls lzma_code() which immediately returns
  922. // LZMA_OK without providing new data.
  923. //
  924. // - If the queue becomes empty, we won't wait
  925. // anything and will return LZMA_OK immediately
  926. // (coder->timeout is completely ignored).
  927. //
  928. // (*) See the comment at the beginning of this
  929. // function how waiting_allowed is determined
  930. // and why there is an exception to the rule
  931. // of "called with an empty input buffer".
  932. assert(*in_pos == in_size);
  933. // If LZMA_FINISH was used we know that we won't get
  934. // more input, so the file must be truncated if we
  935. // get here. If worker threads don't detect any
  936. // errors, eventually there will be no more output
  937. // while we keep returning LZMA_OK which gets
  938. // converted to LZMA_BUF_ERROR in lzma_code().
  939. //
  940. // If fail-fast is enabled then we will return
  941. // immediately using LZMA_DATA_ERROR instead of
  942. // LZMA_OK or LZMA_BUF_ERROR. Rationale for the
  943. // error code:
  944. //
  945. // - Worker threads may have a large amount of
  946. // not-yet-decoded input data and we don't
  947. // know for sure if all data is valid. Bad
  948. // data there would result in LZMA_DATA_ERROR
  949. // when fail-fast isn't used.
  950. //
  951. // - Immediate LZMA_BUF_ERROR would be a bit weird
  952. // considering the older liblzma code. lzma_code()
  953. // even has an assertion to prevent coders from
  954. // returning LZMA_BUF_ERROR directly.
  955. //
  956. // The downside of this is that with fail-fast apps
  957. // cannot always distinguish between corrupt and
  958. // truncated files.
  959. if (action == LZMA_FINISH && coder->fail_fast) {
  960. // We won't produce any more output. Stop
  961. // the unfinished worker threads so they
  962. // won't waste CPU time.
  963. threads_stop(coder);
  964. return LZMA_DATA_ERROR;
  965. }
  966. // read_output_and_wait() will call threads_stop()
  967. // if needed so with that we can use return_if_error.
  968. return_if_error(read_output_and_wait(coder, allocator,
  969. out, out_pos, out_size,
  970. NULL, waiting_allowed,
  971. &wait_abs, &has_blocked));
  972. if (coder->pending_error != LZMA_OK) {
  973. coder->sequence = SEQ_ERROR;
  974. break;
  975. }
  976. return LZMA_OK;
  977. }
  978. if (ret == LZMA_INDEX_DETECTED) {
  979. coder->sequence = SEQ_INDEX_WAIT_OUTPUT;
  980. break;
  981. }
  982. // See if an error occurred.
  983. if (ret != LZMA_STREAM_END) {
  984. // NOTE: Here and in all other places where
  985. // pending_error is set, it may overwrite the value
  986. // (LZMA_PROG_ERROR) set by read_output_and_wait().
  987. // That function might overwrite value set here too.
  988. // These are fine because when read_output_and_wait()
  989. // sets pending_error, it actually works as a flag
  990. // variable only ("some error has occurred") and the
  991. // actual value of pending_error is not used in
  992. // SEQ_ERROR. In such cases SEQ_ERROR will eventually
  993. // get the correct error code from the return value of
  994. // a later read_output_and_wait() call.
  995. coder->pending_error = ret;
  996. coder->sequence = SEQ_ERROR;
  997. break;
  998. }
  999. // Calculate the memory usage of the filters / Block decoder.
  1000. coder->mem_next_filters = lzma_raw_decoder_memusage(
  1001. coder->filters);
  1002. if (coder->mem_next_filters == UINT64_MAX) {
  1003. // One or more unknown Filter IDs.
  1004. coder->pending_error = LZMA_OPTIONS_ERROR;
  1005. coder->sequence = SEQ_ERROR;
  1006. break;
  1007. }
  1008. coder->sequence = SEQ_BLOCK_INIT;
  1009. }
  1010. // Fall through
  1011. case SEQ_BLOCK_INIT: {
  1012. // Check if decoding is possible at all with the current
  1013. // memlimit_stop which we must never exceed.
  1014. //
  1015. // This needs to be the first thing in SEQ_BLOCK_INIT
  1016. // to make it possible to restart decoding after increasing
  1017. // memlimit_stop with lzma_memlimit_set().
  1018. if (coder->mem_next_filters > coder->memlimit_stop) {
  1019. // Flush pending output before returning
  1020. // LZMA_MEMLIMIT_ERROR. If the application doesn't
  1021. // want to increase the limit, at least it will get
  1022. // all the output possible so far.
  1023. return_if_error(read_output_and_wait(coder, allocator,
  1024. out, out_pos, out_size,
  1025. NULL, true, &wait_abs, &has_blocked));
  1026. if (!lzma_outq_is_empty(&coder->outq))
  1027. return LZMA_OK;
  1028. return LZMA_MEMLIMIT_ERROR;
  1029. }
  1030. // Check if the size information is available in Block Header.
  1031. // If it is, check if the sizes are small enough that we don't
  1032. // need to worry *too* much about integer overflows later in
  1033. // the code. If these conditions are not met, we must use the
  1034. // single-threaded direct mode.
  1035. if (is_direct_mode_needed(coder->block_options.compressed_size)
  1036. || is_direct_mode_needed(
  1037. coder->block_options.uncompressed_size)) {
  1038. coder->sequence = SEQ_BLOCK_DIRECT_INIT;
  1039. break;
  1040. }
  1041. // Calculate the amount of memory needed for the input and
  1042. // output buffers in threaded mode.
  1043. //
  1044. // These cannot overflow because we already checked that
  1045. // the sizes are small enough using is_direct_mode_needed().
  1046. coder->mem_next_in = comp_blk_size(coder);
  1047. const uint64_t mem_buffers = coder->mem_next_in
  1048. + lzma_outq_outbuf_memusage(
  1049. coder->block_options.uncompressed_size);
  1050. // Add the amount needed by the filters.
  1051. // Avoid integer overflows.
  1052. if (UINT64_MAX - mem_buffers < coder->mem_next_filters) {
  1053. // Use direct mode if the memusage would overflow.
  1054. // This is a theoretical case that shouldn't happen
  1055. // in practice unless the input file is weird (broken
  1056. // or malicious).
  1057. coder->sequence = SEQ_BLOCK_DIRECT_INIT;
  1058. break;
  1059. }
  1060. // Amount of memory needed to decode this Block in
  1061. // threaded mode:
  1062. coder->mem_next_block = coder->mem_next_filters + mem_buffers;
  1063. // If this alone would exceed memlimit_threading, then we must
  1064. // use the single-threaded direct mode.
  1065. if (coder->mem_next_block > coder->memlimit_threading) {
  1066. coder->sequence = SEQ_BLOCK_DIRECT_INIT;
  1067. break;
  1068. }
  1069. // Use the threaded mode. Free the direct mode decoder in
  1070. // case it has been initialized.
  1071. lzma_next_end(&coder->block_decoder, allocator);
  1072. coder->mem_direct_mode = 0;
  1073. // Since we already know what the sizes are supposed to be,
  1074. // we can already add them to the Index hash. The Block
  1075. // decoder will verify the values while decoding.
  1076. const lzma_ret ret = lzma_index_hash_append(coder->index_hash,
  1077. lzma_block_unpadded_size(
  1078. &coder->block_options),
  1079. coder->block_options.uncompressed_size);
  1080. if (ret != LZMA_OK) {
  1081. coder->pending_error = ret;
  1082. coder->sequence = SEQ_ERROR;
  1083. break;
  1084. }
  1085. coder->sequence = SEQ_BLOCK_THR_INIT;
  1086. }
  1087. // Fall through
  1088. case SEQ_BLOCK_THR_INIT: {
  1089. // We need to wait for a multiple conditions to become true
  1090. // until we can initialize the Block decoder and let a worker
  1091. // thread decode it:
  1092. //
  1093. // - Wait for the memory usage of the active threads to drop
  1094. // so that starting the decoding of this Block won't make
  1095. // us go over memlimit_threading.
  1096. //
  1097. // - Wait for at least one free output queue slot.
  1098. //
  1099. // - Wait for a free worker thread.
  1100. //
  1101. // While we wait, we must copy decompressed data to the out
  1102. // buffer and catch possible decoder errors.
  1103. //
  1104. // read_output_and_wait() does all the above.
  1105. bool block_can_start = false;
  1106. return_if_error(read_output_and_wait(coder, allocator,
  1107. out, out_pos, out_size,
  1108. &block_can_start, true,
  1109. &wait_abs, &has_blocked));
  1110. if (coder->pending_error != LZMA_OK) {
  1111. coder->sequence = SEQ_ERROR;
  1112. break;
  1113. }
  1114. if (!block_can_start) {
  1115. // It's not a timeout because return_if_error handles
  1116. // it already. Output queue cannot be empty either
  1117. // because in that case block_can_start would have
  1118. // been true. Thus the output buffer must be full and
  1119. // the queue isn't empty.
  1120. assert(*out_pos == out_size);
  1121. assert(!lzma_outq_is_empty(&coder->outq));
  1122. return LZMA_OK;
  1123. }
  1124. // We know that we can start decoding this Block without
  1125. // exceeding memlimit_threading. However, to stay below
  1126. // memlimit_threading may require freeing some of the
  1127. // cached memory.
  1128. //
  1129. // Get a local copy of variables that require locking the
  1130. // mutex. It is fine if the worker threads modify the real
  1131. // values after we read these as those changes can only be
  1132. // towards more favorable conditions (less memory in use,
  1133. // more in cache).
  1134. //
  1135. // These are initialized to silence warnings.
  1136. uint64_t mem_in_use = 0;
  1137. uint64_t mem_cached = 0;
  1138. struct worker_thread *thr = NULL;
  1139. mythread_sync(coder->mutex) {
  1140. mem_in_use = coder->mem_in_use;
  1141. mem_cached = coder->mem_cached;
  1142. thr = coder->threads_free;
  1143. }
  1144. // The maximum amount of memory that can be held by other
  1145. // threads and cached buffers while allowing us to start
  1146. // decoding the next Block.
  1147. const uint64_t mem_max = coder->memlimit_threading
  1148. - coder->mem_next_block;
  1149. // If the existing allocations are so large that starting
  1150. // to decode this Block might exceed memlimit_threads,
  1151. // try to free memory from the output queue cache first.
  1152. //
  1153. // NOTE: This math assumes the worst case. It's possible
  1154. // that the limit wouldn't be exceeded if the existing cached
  1155. // allocations are reused.
  1156. if (mem_in_use + mem_cached + coder->outq.mem_allocated
  1157. > mem_max) {
  1158. // Clear the outq cache except leave one buffer in
  1159. // the cache if its size is correct. That way we
  1160. // don't free and almost immediately reallocate
  1161. // an identical buffer.
  1162. lzma_outq_clear_cache2(&coder->outq, allocator,
  1163. coder->block_options.uncompressed_size);
  1164. }
  1165. // If there is at least one worker_thread in the cache and
  1166. // the existing allocations are so large that starting to
  1167. // decode this Block might exceed memlimit_threads, free
  1168. // memory by freeing cached Block decoders.
  1169. //
  1170. // NOTE: The comparison is different here than above.
  1171. // Here we don't care about cached buffers in outq anymore
  1172. // and only look at memory actually in use. This is because
  1173. // if there is something in outq cache, it's a single buffer
  1174. // that can be used as is. We ensured this in the above
  1175. // if-block.
  1176. uint64_t mem_freed = 0;
  1177. if (thr != NULL && mem_in_use + mem_cached
  1178. + coder->outq.mem_in_use > mem_max) {
  1179. // Don't free the first Block decoder if its memory
  1180. // usage isn't greater than what this Block will need.
  1181. // Typically the same filter chain is used for all
  1182. // Blocks so this way the allocations can be reused
  1183. // when get_thread() picks the first worker_thread
  1184. // from the cache.
  1185. if (thr->mem_filters <= coder->mem_next_filters)
  1186. thr = thr->next;
  1187. while (thr != NULL) {
  1188. lzma_next_end(&thr->block_decoder, allocator);
  1189. mem_freed += thr->mem_filters;
  1190. thr->mem_filters = 0;
  1191. thr = thr->next;
  1192. }
  1193. }
  1194. // Update the memory usage counters. Note that coder->mem_*
  1195. // may have changed since we read them so we must subtract
  1196. // or add the changes.
  1197. mythread_sync(coder->mutex) {
  1198. coder->mem_cached -= mem_freed;
  1199. // Memory needed for the filters and the input buffer.
  1200. // The output queue takes care of its own counter so
  1201. // we don't touch it here.
  1202. //
  1203. // NOTE: After this, coder->mem_in_use +
  1204. // coder->mem_cached might count the same thing twice.
  1205. // If so, this will get corrected in get_thread() when
  1206. // a worker_thread is picked from coder->free_threads
  1207. // and its memory usage is subtracted from mem_cached.
  1208. coder->mem_in_use += coder->mem_next_in
  1209. + coder->mem_next_filters;
  1210. }
  1211. // Allocate memory for the output buffer in the output queue.
  1212. lzma_ret ret = lzma_outq_prealloc_buf(
  1213. &coder->outq, allocator,
  1214. coder->block_options.uncompressed_size);
  1215. if (ret != LZMA_OK) {
  1216. threads_stop(coder);
  1217. return ret;
  1218. }
  1219. // Set up coder->thr.
  1220. ret = get_thread(coder, allocator);
  1221. if (ret != LZMA_OK) {
  1222. threads_stop(coder);
  1223. return ret;
  1224. }
  1225. // The new Block decoder memory usage is already counted in
  1226. // coder->mem_in_use. Store it in the thread too.
  1227. coder->thr->mem_filters = coder->mem_next_filters;
  1228. // Initialize the Block decoder.
  1229. coder->thr->block_options = coder->block_options;
  1230. ret = lzma_block_decoder_init(
  1231. &coder->thr->block_decoder, allocator,
  1232. &coder->thr->block_options);
  1233. // Free the allocated filter options since they are needed
  1234. // only to initialize the Block decoder.
  1235. lzma_filters_free(coder->filters, allocator);
  1236. coder->thr->block_options.filters = NULL;
  1237. // Check if memory usage calculation and Block encoder
  1238. // initialization succeeded.
  1239. if (ret != LZMA_OK) {
  1240. coder->pending_error = ret;
  1241. coder->sequence = SEQ_ERROR;
  1242. break;
  1243. }
  1244. // Allocate the input buffer.
  1245. coder->thr->in_size = coder->mem_next_in;
  1246. coder->thr->in = lzma_alloc(coder->thr->in_size, allocator);
  1247. if (coder->thr->in == NULL) {
  1248. threads_stop(coder);
  1249. return LZMA_MEM_ERROR;
  1250. }
  1251. // Get the preallocated output buffer.
  1252. coder->thr->outbuf = lzma_outq_get_buf(
  1253. &coder->outq, coder->thr);
  1254. // Start the decoder.
  1255. mythread_sync(coder->thr->mutex) {
  1256. assert(coder->thr->state == THR_IDLE);
  1257. coder->thr->state = THR_RUN;
  1258. mythread_cond_signal(&coder->thr->cond);
  1259. }
  1260. // Enable output from the thread that holds the oldest output
  1261. // buffer in the output queue (if such a thread exists).
  1262. mythread_sync(coder->mutex) {
  1263. lzma_outq_enable_partial_output(&coder->outq,
  1264. &worker_enable_partial_update);
  1265. }
  1266. coder->sequence = SEQ_BLOCK_THR_RUN;
  1267. }
  1268. // Fall through
  1269. case SEQ_BLOCK_THR_RUN: {
  1270. if (action == LZMA_FINISH && coder->fail_fast) {
  1271. // We know that we won't get more input and that
  1272. // the caller wants fail-fast behavior. If we see
  1273. // that we don't have enough input to finish this
  1274. // Block, return LZMA_DATA_ERROR immediately.
  1275. // See SEQ_BLOCK_HEADER for the error code rationale.
  1276. const size_t in_avail = in_size - *in_pos;
  1277. const size_t in_needed = coder->thr->in_size
  1278. - coder->thr->in_filled;
  1279. if (in_avail < in_needed) {
  1280. threads_stop(coder);
  1281. return LZMA_DATA_ERROR;
  1282. }
  1283. }
  1284. // Copy input to the worker thread.
  1285. size_t cur_in_filled = coder->thr->in_filled;
  1286. lzma_bufcpy(in, in_pos, in_size, coder->thr->in,
  1287. &cur_in_filled, coder->thr->in_size);
  1288. // Tell the thread how much we copied.
  1289. mythread_sync(coder->thr->mutex) {
  1290. coder->thr->in_filled = cur_in_filled;
  1291. // NOTE: Most of the time we are copying input faster
  1292. // than the thread can decode so most of the time
  1293. // calling mythread_cond_signal() is useless but
  1294. // we cannot make it conditional because thr->in_pos
  1295. // is updated without a mutex. And the overhead should
  1296. // be very much negligible anyway.
  1297. mythread_cond_signal(&coder->thr->cond);
  1298. }
  1299. // Read output from the output queue. Just like in
  1300. // SEQ_BLOCK_HEADER, we wait to fill the output buffer
  1301. // only if waiting_allowed was set to true in the beginning
  1302. // of this function (see the comment there).
  1303. return_if_error(read_output_and_wait(coder, allocator,
  1304. out, out_pos, out_size,
  1305. NULL, waiting_allowed,
  1306. &wait_abs, &has_blocked));
  1307. if (coder->pending_error != LZMA_OK) {
  1308. coder->sequence = SEQ_ERROR;
  1309. break;
  1310. }
  1311. // Return if the input didn't contain the whole Block.
  1312. if (coder->thr->in_filled < coder->thr->in_size) {
  1313. assert(*in_pos == in_size);
  1314. return LZMA_OK;
  1315. }
  1316. // The whole Block has been copied to the thread-specific
  1317. // buffer. Continue from the next Block Header or Index.
  1318. coder->thr = NULL;
  1319. coder->sequence = SEQ_BLOCK_HEADER;
  1320. break;
  1321. }
  1322. case SEQ_BLOCK_DIRECT_INIT: {
  1323. // Wait for the threads to finish and that all decoded data
  1324. // has been copied to the output. That is, wait until the
  1325. // output queue becomes empty.
  1326. //
  1327. // NOTE: No need to check for coder->pending_error as
  1328. // we aren't consuming any input until the queue is empty
  1329. // and if there is a pending error, read_output_and_wait()
  1330. // will eventually return it before the queue is empty.
  1331. return_if_error(read_output_and_wait(coder, allocator,
  1332. out, out_pos, out_size,
  1333. NULL, true, &wait_abs, &has_blocked));
  1334. if (!lzma_outq_is_empty(&coder->outq))
  1335. return LZMA_OK;
  1336. // Free the cached output buffers.
  1337. lzma_outq_clear_cache(&coder->outq, allocator);
  1338. // Get rid of the worker threads, including the coder->threads
  1339. // array.
  1340. threads_end(coder, allocator);
  1341. // Initialize the Block decoder.
  1342. const lzma_ret ret = lzma_block_decoder_init(
  1343. &coder->block_decoder, allocator,
  1344. &coder->block_options);
  1345. // Free the allocated filter options since they are needed
  1346. // only to initialize the Block decoder.
  1347. lzma_filters_free(coder->filters, allocator);
  1348. coder->block_options.filters = NULL;
  1349. // Check if Block decoder initialization succeeded.
  1350. if (ret != LZMA_OK)
  1351. return ret;
  1352. // Make the memory usage visible to _memconfig().
  1353. coder->mem_direct_mode = coder->mem_next_filters;
  1354. coder->sequence = SEQ_BLOCK_DIRECT_RUN;
  1355. }
  1356. // Fall through
  1357. case SEQ_BLOCK_DIRECT_RUN: {
  1358. const size_t in_old = *in_pos;
  1359. const size_t out_old = *out_pos;
  1360. const lzma_ret ret = coder->block_decoder.code(
  1361. coder->block_decoder.coder, allocator,
  1362. in, in_pos, in_size, out, out_pos, out_size,
  1363. action);
  1364. coder->progress_in += *in_pos - in_old;
  1365. coder->progress_out += *out_pos - out_old;
  1366. if (ret != LZMA_STREAM_END)
  1367. return ret;
  1368. // Block decoded successfully. Add the new size pair to
  1369. // the Index hash.
  1370. return_if_error(lzma_index_hash_append(coder->index_hash,
  1371. lzma_block_unpadded_size(
  1372. &coder->block_options),
  1373. coder->block_options.uncompressed_size));
  1374. coder->sequence = SEQ_BLOCK_HEADER;
  1375. break;
  1376. }
  1377. case SEQ_INDEX_WAIT_OUTPUT:
  1378. // Flush the output from all worker threads so that we can
  1379. // decode the Index without thinking about threading.
  1380. return_if_error(read_output_and_wait(coder, allocator,
  1381. out, out_pos, out_size,
  1382. NULL, true, &wait_abs, &has_blocked));
  1383. if (!lzma_outq_is_empty(&coder->outq))
  1384. return LZMA_OK;
  1385. coder->sequence = SEQ_INDEX_DECODE;
  1386. // Fall through
  1387. case SEQ_INDEX_DECODE: {
  1388. // If we don't have any input, don't call
  1389. // lzma_index_hash_decode() since it would return
  1390. // LZMA_BUF_ERROR, which we must not do here.
  1391. if (*in_pos >= in_size)
  1392. return LZMA_OK;
  1393. // Decode the Index and compare it to the hash calculated
  1394. // from the sizes of the Blocks (if any).
  1395. const size_t in_old = *in_pos;
  1396. const lzma_ret ret = lzma_index_hash_decode(coder->index_hash,
  1397. in, in_pos, in_size);
  1398. coder->progress_in += *in_pos - in_old;
  1399. if (ret != LZMA_STREAM_END)
  1400. return ret;
  1401. coder->sequence = SEQ_STREAM_FOOTER;
  1402. }
  1403. // Fall through
  1404. case SEQ_STREAM_FOOTER: {
  1405. // Copy the Stream Footer to the internal buffer.
  1406. const size_t in_old = *in_pos;
  1407. lzma_bufcpy(in, in_pos, in_size, coder->buffer, &coder->pos,
  1408. LZMA_STREAM_HEADER_SIZE);
  1409. coder->progress_in += *in_pos - in_old;
  1410. // Return if we didn't get the whole Stream Footer yet.
  1411. if (coder->pos < LZMA_STREAM_HEADER_SIZE)
  1412. return LZMA_OK;
  1413. coder->pos = 0;
  1414. // Decode the Stream Footer. The decoder gives
  1415. // LZMA_FORMAT_ERROR if the magic bytes don't match,
  1416. // so convert that return code to LZMA_DATA_ERROR.
  1417. lzma_stream_flags footer_flags;
  1418. const lzma_ret ret = lzma_stream_footer_decode(
  1419. &footer_flags, coder->buffer);
  1420. if (ret != LZMA_OK)
  1421. return ret == LZMA_FORMAT_ERROR
  1422. ? LZMA_DATA_ERROR : ret;
  1423. // Check that Index Size stored in the Stream Footer matches
  1424. // the real size of the Index field.
  1425. if (lzma_index_hash_size(coder->index_hash)
  1426. != footer_flags.backward_size)
  1427. return LZMA_DATA_ERROR;
  1428. // Compare that the Stream Flags fields are identical in
  1429. // both Stream Header and Stream Footer.
  1430. return_if_error(lzma_stream_flags_compare(
  1431. &coder->stream_flags, &footer_flags));
  1432. if (!coder->concatenated)
  1433. return LZMA_STREAM_END;
  1434. coder->sequence = SEQ_STREAM_PADDING;
  1435. }
  1436. // Fall through
  1437. case SEQ_STREAM_PADDING:
  1438. assert(coder->concatenated);
  1439. // Skip over possible Stream Padding.
  1440. while (true) {
  1441. if (*in_pos >= in_size) {
  1442. // Unless LZMA_FINISH was used, we cannot
  1443. // know if there's more input coming later.
  1444. if (action != LZMA_FINISH)
  1445. return LZMA_OK;
  1446. // Stream Padding must be a multiple of
  1447. // four bytes.
  1448. return coder->pos == 0
  1449. ? LZMA_STREAM_END
  1450. : LZMA_DATA_ERROR;
  1451. }
  1452. // If the byte is not zero, it probably indicates
  1453. // beginning of a new Stream (or the file is corrupt).
  1454. if (in[*in_pos] != 0x00)
  1455. break;
  1456. ++*in_pos;
  1457. ++coder->progress_in;
  1458. coder->pos = (coder->pos + 1) & 3;
  1459. }
  1460. // Stream Padding must be a multiple of four bytes (empty
  1461. // Stream Padding is OK).
  1462. if (coder->pos != 0) {
  1463. ++*in_pos;
  1464. ++coder->progress_in;
  1465. return LZMA_DATA_ERROR;
  1466. }
  1467. // Prepare to decode the next Stream.
  1468. return_if_error(stream_decoder_reset(coder, allocator));
  1469. break;
  1470. case SEQ_ERROR:
  1471. if (!coder->fail_fast) {
  1472. // Let the application get all data before the point
  1473. // where the error was detected. This matches the
  1474. // behavior of single-threaded use.
  1475. //
  1476. // FIXME? Some errors (LZMA_MEM_ERROR) don't get here,
  1477. // they are returned immediately. Thus in rare cases
  1478. // the output will be less than in the single-threaded
  1479. // mode. Maybe this doesn't matter much in practice.
  1480. return_if_error(read_output_and_wait(coder, allocator,
  1481. out, out_pos, out_size,
  1482. NULL, true, &wait_abs, &has_blocked));
  1483. // We get here only if the error happened in the main
  1484. // thread, for example, unsupported Block Header.
  1485. if (!lzma_outq_is_empty(&coder->outq))
  1486. return LZMA_OK;
  1487. }
  1488. // We only get here if no errors were detected by the worker
  1489. // threads. Errors from worker threads would have already been
  1490. // returned by the call to read_output_and_wait() above.
  1491. return coder->pending_error;
  1492. default:
  1493. assert(0);
  1494. return LZMA_PROG_ERROR;
  1495. }
  1496. // Never reached
  1497. }
  1498. static void
  1499. stream_decoder_mt_end(void *coder_ptr, const lzma_allocator *allocator)
  1500. {
  1501. struct lzma_stream_coder *coder = coder_ptr;
  1502. threads_end(coder, allocator);
  1503. lzma_outq_end(&coder->outq, allocator);
  1504. lzma_next_end(&coder->block_decoder, allocator);
  1505. lzma_filters_free(coder->filters, allocator);
  1506. lzma_index_hash_end(coder->index_hash, allocator);
  1507. lzma_free(coder, allocator);
  1508. return;
  1509. }
  1510. static lzma_check
  1511. stream_decoder_mt_get_check(const void *coder_ptr)
  1512. {
  1513. const struct lzma_stream_coder *coder = coder_ptr;
  1514. return coder->stream_flags.check;
  1515. }
  1516. static lzma_ret
  1517. stream_decoder_mt_memconfig(void *coder_ptr, uint64_t *memusage,
  1518. uint64_t *old_memlimit, uint64_t new_memlimit)
  1519. {
  1520. // NOTE: This function gets/sets memlimit_stop. For now,
  1521. // memlimit_threading cannot be modified after initialization.
  1522. //
  1523. // *memusage will include cached memory too. Excluding cached memory
  1524. // would be misleading and it wouldn't help the applications to
  1525. // know how much memory is actually needed to decompress the file
  1526. // because the higher the number of threads and the memlimits are
  1527. // the more memory the decoder may use.
  1528. //
  1529. // Setting a new limit includes the cached memory too and too low
  1530. // limits will be rejected. Alternative could be to free the cached
  1531. // memory immediately if that helps to bring the limit down but
  1532. // the current way is the simplest. It's unlikely that limit needs
  1533. // to be lowered in the middle of a file anyway; the typical reason
  1534. // to want a new limit is to increase after LZMA_MEMLIMIT_ERROR
  1535. // and even such use isn't common.
  1536. struct lzma_stream_coder *coder = coder_ptr;
  1537. mythread_sync(coder->mutex) {
  1538. *memusage = coder->mem_direct_mode
  1539. + coder->mem_in_use
  1540. + coder->mem_cached
  1541. + coder->outq.mem_allocated;
  1542. }
  1543. // If no filter chains are allocated, *memusage may be zero.
  1544. // Always return at least LZMA_MEMUSAGE_BASE.
  1545. if (*memusage < LZMA_MEMUSAGE_BASE)
  1546. *memusage = LZMA_MEMUSAGE_BASE;
  1547. *old_memlimit = coder->memlimit_stop;
  1548. if (new_memlimit != 0) {
  1549. if (new_memlimit < *memusage)
  1550. return LZMA_MEMLIMIT_ERROR;
  1551. coder->memlimit_stop = new_memlimit;
  1552. }
  1553. return LZMA_OK;
  1554. }
  1555. static void
  1556. stream_decoder_mt_get_progress(void *coder_ptr,
  1557. uint64_t *progress_in, uint64_t *progress_out)
  1558. {
  1559. struct lzma_stream_coder *coder = coder_ptr;
  1560. // Lock coder->mutex to prevent finishing threads from moving their
  1561. // progress info from the worker_thread structure to lzma_stream_coder.
  1562. mythread_sync(coder->mutex) {
  1563. *progress_in = coder->progress_in;
  1564. *progress_out = coder->progress_out;
  1565. for (size_t i = 0; i < coder->threads_initialized; ++i) {
  1566. mythread_sync(coder->threads[i].mutex) {
  1567. *progress_in += coder->threads[i].progress_in;
  1568. *progress_out += coder->threads[i]
  1569. .progress_out;
  1570. }
  1571. }
  1572. }
  1573. return;
  1574. }
  1575. static lzma_ret
  1576. stream_decoder_mt_init(lzma_next_coder *next, const lzma_allocator *allocator,
  1577. const lzma_mt *options)
  1578. {
  1579. struct lzma_stream_coder *coder;
  1580. if (options->threads == 0 || options->threads > LZMA_THREADS_MAX)
  1581. return LZMA_OPTIONS_ERROR;
  1582. if (options->flags & ~LZMA_SUPPORTED_FLAGS)
  1583. return LZMA_OPTIONS_ERROR;
  1584. lzma_next_coder_init(&stream_decoder_mt_init, next, allocator);
  1585. coder = next->coder;
  1586. if (!coder) {
  1587. coder = lzma_alloc(sizeof(struct lzma_stream_coder), allocator);
  1588. if (coder == NULL)
  1589. return LZMA_MEM_ERROR;
  1590. next->coder = coder;
  1591. if (mythread_mutex_init(&coder->mutex)) {
  1592. lzma_free(coder, allocator);
  1593. return LZMA_MEM_ERROR;
  1594. }
  1595. if (mythread_cond_init(&coder->cond)) {
  1596. mythread_mutex_destroy(&coder->mutex);
  1597. lzma_free(coder, allocator);
  1598. return LZMA_MEM_ERROR;
  1599. }
  1600. next->code = &stream_decode_mt;
  1601. next->end = &stream_decoder_mt_end;
  1602. next->get_check = &stream_decoder_mt_get_check;
  1603. next->memconfig = &stream_decoder_mt_memconfig;
  1604. next->get_progress = &stream_decoder_mt_get_progress;
  1605. coder->filters[0].id = LZMA_VLI_UNKNOWN;
  1606. memzero(&coder->outq, sizeof(coder->outq));
  1607. coder->block_decoder = LZMA_NEXT_CODER_INIT;
  1608. coder->mem_direct_mode = 0;
  1609. coder->index_hash = NULL;
  1610. coder->threads = NULL;
  1611. coder->threads_free = NULL;
  1612. coder->threads_initialized = 0;
  1613. }
  1614. // Cleanup old filter chain if one remains after unfinished decoding
  1615. // of a previous Stream.
  1616. lzma_filters_free(coder->filters, allocator);
  1617. // By allocating threads from scratch we can start memory-usage
  1618. // accounting from scratch, too. Changes in filter and block sizes may
  1619. // affect number of threads.
  1620. //
  1621. // FIXME? Reusing should be easy but unlike the single-threaded
  1622. // decoder, with some types of input file combinations reusing
  1623. // could leave quite a lot of memory allocated but unused (first
  1624. // file could allocate a lot, the next files could use fewer
  1625. // threads and some of the allocations from the first file would not
  1626. // get freed unless memlimit_threading forces us to clear caches).
  1627. //
  1628. // NOTE: The direct mode decoder isn't freed here if one exists.
  1629. // It will be reused or freed as needed in the main loop.
  1630. threads_end(coder, allocator);
  1631. // All memusage counters start at 0 (including mem_direct_mode).
  1632. // The little extra that is needed for the structs in this file
  1633. // get accounted well enough by the filter chain memory usage
  1634. // which adds LZMA_MEMUSAGE_BASE for each chain. However,
  1635. // stream_decoder_mt_memconfig() has to handle this specially so that
  1636. // it will never return less than LZMA_MEMUSAGE_BASE as memory usage.
  1637. coder->mem_in_use = 0;
  1638. coder->mem_cached = 0;
  1639. coder->mem_next_block = 0;
  1640. coder->progress_in = 0;
  1641. coder->progress_out = 0;
  1642. coder->sequence = SEQ_STREAM_HEADER;
  1643. coder->thread_error = LZMA_OK;
  1644. coder->pending_error = LZMA_OK;
  1645. coder->thr = NULL;
  1646. coder->timeout = options->timeout;
  1647. coder->memlimit_threading = my_max(1, options->memlimit_threading);
  1648. coder->memlimit_stop = my_max(1, options->memlimit_stop);
  1649. if (coder->memlimit_threading > coder->memlimit_stop)
  1650. coder->memlimit_threading = coder->memlimit_stop;
  1651. coder->tell_no_check = (options->flags & LZMA_TELL_NO_CHECK) != 0;
  1652. coder->tell_unsupported_check
  1653. = (options->flags & LZMA_TELL_UNSUPPORTED_CHECK) != 0;
  1654. coder->tell_any_check = (options->flags & LZMA_TELL_ANY_CHECK) != 0;
  1655. coder->ignore_check = (options->flags & LZMA_IGNORE_CHECK) != 0;
  1656. coder->concatenated = (options->flags & LZMA_CONCATENATED) != 0;
  1657. coder->fail_fast = (options->flags & LZMA_FAIL_FAST) != 0;
  1658. coder->first_stream = true;
  1659. coder->out_was_filled = false;
  1660. coder->pos = 0;
  1661. coder->threads_max = options->threads;
  1662. return_if_error(lzma_outq_init(&coder->outq, allocator,
  1663. coder->threads_max));
  1664. return stream_decoder_reset(coder, allocator);
  1665. }
  1666. extern LZMA_API(lzma_ret)
  1667. lzma_stream_decoder_mt(lzma_stream *strm, const lzma_mt *options)
  1668. {
  1669. lzma_next_strm_init(stream_decoder_mt_init, strm, options);
  1670. strm->internal->supported_actions[LZMA_RUN] = true;
  1671. strm->internal->supported_actions[LZMA_FINISH] = true;
  1672. return LZMA_OK;
  1673. }