stream_decoder_mt.c 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016
  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 substract
  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] == 0x00)
  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. uint64_t mem_in_use;
  1135. uint64_t mem_cached;
  1136. struct worker_thread *thr = NULL; // Init to silence warning.
  1137. mythread_sync(coder->mutex) {
  1138. mem_in_use = coder->mem_in_use;
  1139. mem_cached = coder->mem_cached;
  1140. thr = coder->threads_free;
  1141. }
  1142. // The maximum amount of memory that can be held by other
  1143. // threads and cached buffers while allowing us to start
  1144. // decoding the next Block.
  1145. const uint64_t mem_max = coder->memlimit_threading
  1146. - coder->mem_next_block;
  1147. // If the existing allocations are so large that starting
  1148. // to decode this Block might exceed memlimit_threads,
  1149. // try to free memory from the output queue cache first.
  1150. //
  1151. // NOTE: This math assumes the worst case. It's possible
  1152. // that the limit wouldn't be exceeded if the existing cached
  1153. // allocations are reused.
  1154. if (mem_in_use + mem_cached + coder->outq.mem_allocated
  1155. > mem_max) {
  1156. // Clear the outq cache except leave one buffer in
  1157. // the cache if its size is correct. That way we
  1158. // don't free and almost immediately reallocate
  1159. // an identical buffer.
  1160. lzma_outq_clear_cache2(&coder->outq, allocator,
  1161. coder->block_options.uncompressed_size);
  1162. }
  1163. // If there is at least one worker_thread in the cache and
  1164. // the existing allocations are so large that starting to
  1165. // decode this Block might exceed memlimit_threads, free
  1166. // memory by freeing cached Block decoders.
  1167. //
  1168. // NOTE: The comparison is different here than above.
  1169. // Here we don't care about cached buffers in outq anymore
  1170. // and only look at memory actually in use. This is because
  1171. // if there is something in outq cache, it's a single buffer
  1172. // that can be used as is. We ensured this in the above
  1173. // if-block.
  1174. uint64_t mem_freed = 0;
  1175. if (thr != NULL && mem_in_use + mem_cached
  1176. + coder->outq.mem_in_use > mem_max) {
  1177. // Don't free the first Block decoder if its memory
  1178. // usage isn't greater than what this Block will need.
  1179. // Typically the same filter chain is used for all
  1180. // Blocks so this way the allocations can be reused
  1181. // when get_thread() picks the first worker_thread
  1182. // from the cache.
  1183. if (thr->mem_filters <= coder->mem_next_filters)
  1184. thr = thr->next;
  1185. while (thr != NULL) {
  1186. lzma_next_end(&thr->block_decoder, allocator);
  1187. mem_freed += thr->mem_filters;
  1188. thr->mem_filters = 0;
  1189. thr = thr->next;
  1190. }
  1191. }
  1192. // Update the memory usage counters. Note that coder->mem_*
  1193. // may have changed since we read them so we must substract
  1194. // or add the changes.
  1195. mythread_sync(coder->mutex) {
  1196. coder->mem_cached -= mem_freed;
  1197. // Memory needed for the filters and the input buffer.
  1198. // The output queue takes care of its own counter so
  1199. // we don't touch it here.
  1200. //
  1201. // NOTE: After this, coder->mem_in_use +
  1202. // coder->mem_cached might count the same thing twice.
  1203. // If so, this will get corrected in get_thread() when
  1204. // a worker_thread is picked from coder->free_threads
  1205. // and its memory usage is substracted from mem_cached.
  1206. coder->mem_in_use += coder->mem_next_in
  1207. + coder->mem_next_filters;
  1208. }
  1209. // Allocate memory for the output buffer in the output queue.
  1210. lzma_ret ret = lzma_outq_prealloc_buf(
  1211. &coder->outq, allocator,
  1212. coder->block_options.uncompressed_size);
  1213. if (ret != LZMA_OK) {
  1214. threads_stop(coder);
  1215. return ret;
  1216. }
  1217. // Set up coder->thr.
  1218. ret = get_thread(coder, allocator);
  1219. if (ret != LZMA_OK) {
  1220. threads_stop(coder);
  1221. return ret;
  1222. }
  1223. // The new Block decoder memory usage is already counted in
  1224. // coder->mem_in_use. Store it in the thread too.
  1225. coder->thr->mem_filters = coder->mem_next_filters;
  1226. // Initialize the Block decoder.
  1227. coder->thr->block_options = coder->block_options;
  1228. ret = lzma_block_decoder_init(
  1229. &coder->thr->block_decoder, allocator,
  1230. &coder->thr->block_options);
  1231. // Free the allocated filter options since they are needed
  1232. // only to initialize the Block decoder.
  1233. lzma_filters_free(coder->filters, allocator);
  1234. coder->thr->block_options.filters = NULL;
  1235. // Check if memory usage calculation and Block encoder
  1236. // initialization succeeded.
  1237. if (ret != LZMA_OK) {
  1238. coder->pending_error = ret;
  1239. coder->sequence = SEQ_ERROR;
  1240. break;
  1241. }
  1242. // Allocate the input buffer.
  1243. coder->thr->in_size = coder->mem_next_in;
  1244. coder->thr->in = lzma_alloc(coder->thr->in_size, allocator);
  1245. if (coder->thr->in == NULL) {
  1246. threads_stop(coder);
  1247. return LZMA_MEM_ERROR;
  1248. }
  1249. // Get the preallocated output buffer.
  1250. coder->thr->outbuf = lzma_outq_get_buf(
  1251. &coder->outq, coder->thr);
  1252. // Start the decoder.
  1253. mythread_sync(coder->thr->mutex) {
  1254. assert(coder->thr->state == THR_IDLE);
  1255. coder->thr->state = THR_RUN;
  1256. mythread_cond_signal(&coder->thr->cond);
  1257. }
  1258. // Enable output from the thread that holds the oldest output
  1259. // buffer in the output queue (if such a thread exists).
  1260. mythread_sync(coder->mutex) {
  1261. lzma_outq_enable_partial_output(&coder->outq,
  1262. &worker_enable_partial_update);
  1263. }
  1264. coder->sequence = SEQ_BLOCK_THR_RUN;
  1265. }
  1266. // Fall through
  1267. case SEQ_BLOCK_THR_RUN: {
  1268. if (action == LZMA_FINISH && coder->fail_fast) {
  1269. // We know that we won't get more input and that
  1270. // the caller wants fail-fast behavior. If we see
  1271. // that we don't have enough input to finish this
  1272. // Block, return LZMA_DATA_ERROR immediately.
  1273. // See SEQ_BLOCK_HEADER for the error code rationale.
  1274. const size_t in_avail = in_size - *in_pos;
  1275. const size_t in_needed = coder->thr->in_size
  1276. - coder->thr->in_filled;
  1277. if (in_avail < in_needed) {
  1278. threads_stop(coder);
  1279. return LZMA_DATA_ERROR;
  1280. }
  1281. }
  1282. // Copy input to the worker thread.
  1283. size_t cur_in_filled = coder->thr->in_filled;
  1284. lzma_bufcpy(in, in_pos, in_size, coder->thr->in,
  1285. &cur_in_filled, coder->thr->in_size);
  1286. // Tell the thread how much we copied.
  1287. mythread_sync(coder->thr->mutex) {
  1288. coder->thr->in_filled = cur_in_filled;
  1289. // NOTE: Most of the time we are copying input faster
  1290. // than the thread can decode so most of the time
  1291. // calling mythread_cond_signal() is useless but
  1292. // we cannot make it conditional because thr->in_pos
  1293. // is updated without a mutex. And the overhead should
  1294. // be very much negligible anyway.
  1295. mythread_cond_signal(&coder->thr->cond);
  1296. }
  1297. // Read output from the output queue. Just like in
  1298. // SEQ_BLOCK_HEADER, we wait to fill the output buffer
  1299. // only if waiting_allowed was set to true in the beginning
  1300. // of this function (see the comment there).
  1301. return_if_error(read_output_and_wait(coder, allocator,
  1302. out, out_pos, out_size,
  1303. NULL, waiting_allowed,
  1304. &wait_abs, &has_blocked));
  1305. if (coder->pending_error != LZMA_OK) {
  1306. coder->sequence = SEQ_ERROR;
  1307. break;
  1308. }
  1309. // Return if the input didn't contain the whole Block.
  1310. if (coder->thr->in_filled < coder->thr->in_size) {
  1311. assert(*in_pos == in_size);
  1312. return LZMA_OK;
  1313. }
  1314. // The whole Block has been copied to the thread-specific
  1315. // buffer. Continue from the next Block Header or Index.
  1316. coder->thr = NULL;
  1317. coder->sequence = SEQ_BLOCK_HEADER;
  1318. break;
  1319. }
  1320. case SEQ_BLOCK_DIRECT_INIT: {
  1321. // Wait for the threads to finish and that all decoded data
  1322. // has been copied to the output. That is, wait until the
  1323. // output queue becomes empty.
  1324. //
  1325. // NOTE: No need to check for coder->pending_error as
  1326. // we aren't consuming any input until the queue is empty
  1327. // and if there is a pending error, read_output_and_wait()
  1328. // will eventually return it before the queue is empty.
  1329. return_if_error(read_output_and_wait(coder, allocator,
  1330. out, out_pos, out_size,
  1331. NULL, true, &wait_abs, &has_blocked));
  1332. if (!lzma_outq_is_empty(&coder->outq))
  1333. return LZMA_OK;
  1334. // Free the cached output buffers.
  1335. lzma_outq_clear_cache(&coder->outq, allocator);
  1336. // Get rid of the worker threads, including the coder->threads
  1337. // array.
  1338. threads_end(coder, allocator);
  1339. // Initialize the Block decoder.
  1340. const lzma_ret ret = lzma_block_decoder_init(
  1341. &coder->block_decoder, allocator,
  1342. &coder->block_options);
  1343. // Free the allocated filter options since they are needed
  1344. // only to initialize the Block decoder.
  1345. lzma_filters_free(coder->filters, allocator);
  1346. coder->block_options.filters = NULL;
  1347. // Check if Block decoder initialization succeeded.
  1348. if (ret != LZMA_OK)
  1349. return ret;
  1350. // Make the memory usage visible to _memconfig().
  1351. coder->mem_direct_mode = coder->mem_next_filters;
  1352. coder->sequence = SEQ_BLOCK_DIRECT_RUN;
  1353. }
  1354. // Fall through
  1355. case SEQ_BLOCK_DIRECT_RUN: {
  1356. const size_t in_old = *in_pos;
  1357. const size_t out_old = *out_pos;
  1358. const lzma_ret ret = coder->block_decoder.code(
  1359. coder->block_decoder.coder, allocator,
  1360. in, in_pos, in_size, out, out_pos, out_size,
  1361. action);
  1362. coder->progress_in += *in_pos - in_old;
  1363. coder->progress_out += *out_pos - out_old;
  1364. if (ret != LZMA_STREAM_END)
  1365. return ret;
  1366. // Block decoded successfully. Add the new size pair to
  1367. // the Index hash.
  1368. return_if_error(lzma_index_hash_append(coder->index_hash,
  1369. lzma_block_unpadded_size(
  1370. &coder->block_options),
  1371. coder->block_options.uncompressed_size));
  1372. coder->sequence = SEQ_BLOCK_HEADER;
  1373. break;
  1374. }
  1375. case SEQ_INDEX_WAIT_OUTPUT:
  1376. // Flush the output from all worker threads so that we can
  1377. // decode the Index without thinking about threading.
  1378. return_if_error(read_output_and_wait(coder, allocator,
  1379. out, out_pos, out_size,
  1380. NULL, true, &wait_abs, &has_blocked));
  1381. if (!lzma_outq_is_empty(&coder->outq))
  1382. return LZMA_OK;
  1383. coder->sequence = SEQ_INDEX_DECODE;
  1384. // Fall through
  1385. case SEQ_INDEX_DECODE: {
  1386. // If we don't have any input, don't call
  1387. // lzma_index_hash_decode() since it would return
  1388. // LZMA_BUF_ERROR, which we must not do here.
  1389. if (*in_pos >= in_size)
  1390. return LZMA_OK;
  1391. // Decode the Index and compare it to the hash calculated
  1392. // from the sizes of the Blocks (if any).
  1393. const size_t in_old = *in_pos;
  1394. const lzma_ret ret = lzma_index_hash_decode(coder->index_hash,
  1395. in, in_pos, in_size);
  1396. coder->progress_in += *in_pos - in_old;
  1397. if (ret != LZMA_STREAM_END)
  1398. return ret;
  1399. coder->sequence = SEQ_STREAM_FOOTER;
  1400. }
  1401. // Fall through
  1402. case SEQ_STREAM_FOOTER: {
  1403. // Copy the Stream Footer to the internal buffer.
  1404. const size_t in_old = *in_pos;
  1405. lzma_bufcpy(in, in_pos, in_size, coder->buffer, &coder->pos,
  1406. LZMA_STREAM_HEADER_SIZE);
  1407. coder->progress_in += *in_pos - in_old;
  1408. // Return if we didn't get the whole Stream Footer yet.
  1409. if (coder->pos < LZMA_STREAM_HEADER_SIZE)
  1410. return LZMA_OK;
  1411. coder->pos = 0;
  1412. // Decode the Stream Footer. The decoder gives
  1413. // LZMA_FORMAT_ERROR if the magic bytes don't match,
  1414. // so convert that return code to LZMA_DATA_ERROR.
  1415. lzma_stream_flags footer_flags;
  1416. const lzma_ret ret = lzma_stream_footer_decode(
  1417. &footer_flags, coder->buffer);
  1418. if (ret != LZMA_OK)
  1419. return ret == LZMA_FORMAT_ERROR
  1420. ? LZMA_DATA_ERROR : ret;
  1421. // Check that Index Size stored in the Stream Footer matches
  1422. // the real size of the Index field.
  1423. if (lzma_index_hash_size(coder->index_hash)
  1424. != footer_flags.backward_size)
  1425. return LZMA_DATA_ERROR;
  1426. // Compare that the Stream Flags fields are identical in
  1427. // both Stream Header and Stream Footer.
  1428. return_if_error(lzma_stream_flags_compare(
  1429. &coder->stream_flags, &footer_flags));
  1430. if (!coder->concatenated)
  1431. return LZMA_STREAM_END;
  1432. coder->sequence = SEQ_STREAM_PADDING;
  1433. }
  1434. // Fall through
  1435. case SEQ_STREAM_PADDING:
  1436. assert(coder->concatenated);
  1437. // Skip over possible Stream Padding.
  1438. while (true) {
  1439. if (*in_pos >= in_size) {
  1440. // Unless LZMA_FINISH was used, we cannot
  1441. // know if there's more input coming later.
  1442. if (action != LZMA_FINISH)
  1443. return LZMA_OK;
  1444. // Stream Padding must be a multiple of
  1445. // four bytes.
  1446. return coder->pos == 0
  1447. ? LZMA_STREAM_END
  1448. : LZMA_DATA_ERROR;
  1449. }
  1450. // If the byte is not zero, it probably indicates
  1451. // beginning of a new Stream (or the file is corrupt).
  1452. if (in[*in_pos] != 0x00)
  1453. break;
  1454. ++*in_pos;
  1455. ++coder->progress_in;
  1456. coder->pos = (coder->pos + 1) & 3;
  1457. }
  1458. // Stream Padding must be a multiple of four bytes (empty
  1459. // Stream Padding is OK).
  1460. if (coder->pos != 0) {
  1461. ++*in_pos;
  1462. ++coder->progress_in;
  1463. return LZMA_DATA_ERROR;
  1464. }
  1465. // Prepare to decode the next Stream.
  1466. return_if_error(stream_decoder_reset(coder, allocator));
  1467. break;
  1468. case SEQ_ERROR:
  1469. if (!coder->fail_fast) {
  1470. // Let the application get all data before the point
  1471. // where the error was detected. This matches the
  1472. // behavior of single-threaded use.
  1473. //
  1474. // FIXME? Some errors (LZMA_MEM_ERROR) don't get here,
  1475. // they are returned immediately. Thus in rare cases
  1476. // the output will be less than in the single-threaded
  1477. // mode. Maybe this doesn't matter much in practice.
  1478. return_if_error(read_output_and_wait(coder, allocator,
  1479. out, out_pos, out_size,
  1480. NULL, true, &wait_abs, &has_blocked));
  1481. // We get here only if the error happened in the main
  1482. // thread, for example, unsupported Block Header.
  1483. if (!lzma_outq_is_empty(&coder->outq))
  1484. return LZMA_OK;
  1485. }
  1486. // We only get here if no errors were detected by the worker
  1487. // threads. Errors from worker threads would have already been
  1488. // returned by the call to read_output_and_wait() above.
  1489. return coder->pending_error;
  1490. default:
  1491. assert(0);
  1492. return LZMA_PROG_ERROR;
  1493. }
  1494. // Never reached
  1495. }
  1496. static void
  1497. stream_decoder_mt_end(void *coder_ptr, const lzma_allocator *allocator)
  1498. {
  1499. struct lzma_stream_coder *coder = coder_ptr;
  1500. threads_end(coder, allocator);
  1501. lzma_outq_end(&coder->outq, allocator);
  1502. lzma_next_end(&coder->block_decoder, allocator);
  1503. lzma_filters_free(coder->filters, allocator);
  1504. lzma_index_hash_end(coder->index_hash, allocator);
  1505. lzma_free(coder, allocator);
  1506. return;
  1507. }
  1508. static lzma_check
  1509. stream_decoder_mt_get_check(const void *coder_ptr)
  1510. {
  1511. const struct lzma_stream_coder *coder = coder_ptr;
  1512. return coder->stream_flags.check;
  1513. }
  1514. static lzma_ret
  1515. stream_decoder_mt_memconfig(void *coder_ptr, uint64_t *memusage,
  1516. uint64_t *old_memlimit, uint64_t new_memlimit)
  1517. {
  1518. // NOTE: This function gets/sets memlimit_stop. For now,
  1519. // memlimit_threading cannot be modified after initialization.
  1520. //
  1521. // *memusage will include cached memory too. Excluding cached memory
  1522. // would be misleading and it wouldn't help the applications to
  1523. // know how much memory is actually needed to decompress the file
  1524. // because the higher the number of threads and the memlimits are
  1525. // the more memory the decoder may use.
  1526. //
  1527. // Setting a new limit includes the cached memory too and too low
  1528. // limits will be rejected. Alternative could be to free the cached
  1529. // memory immediately if that helps to bring the limit down but
  1530. // the current way is the simplest. It's unlikely that limit needs
  1531. // to be lowered in the middle of a file anyway; the typical reason
  1532. // to want a new limit is to increase after LZMA_MEMLIMIT_ERROR
  1533. // and even such use isn't common.
  1534. struct lzma_stream_coder *coder = coder_ptr;
  1535. mythread_sync(coder->mutex) {
  1536. *memusage = coder->mem_direct_mode
  1537. + coder->mem_in_use
  1538. + coder->mem_cached
  1539. + coder->outq.mem_allocated;
  1540. }
  1541. // If no filter chains are allocated, *memusage may be zero.
  1542. // Always return at least LZMA_MEMUSAGE_BASE.
  1543. if (*memusage < LZMA_MEMUSAGE_BASE)
  1544. *memusage = LZMA_MEMUSAGE_BASE;
  1545. *old_memlimit = coder->memlimit_stop;
  1546. if (new_memlimit != 0) {
  1547. if (new_memlimit < *memusage)
  1548. return LZMA_MEMLIMIT_ERROR;
  1549. coder->memlimit_stop = new_memlimit;
  1550. }
  1551. return LZMA_OK;
  1552. }
  1553. static void
  1554. stream_decoder_mt_get_progress(void *coder_ptr,
  1555. uint64_t *progress_in, uint64_t *progress_out)
  1556. {
  1557. struct lzma_stream_coder *coder = coder_ptr;
  1558. // Lock coder->mutex to prevent finishing threads from moving their
  1559. // progress info from the worker_thread structure to lzma_stream_coder.
  1560. mythread_sync(coder->mutex) {
  1561. *progress_in = coder->progress_in;
  1562. *progress_out = coder->progress_out;
  1563. for (size_t i = 0; i < coder->threads_initialized; ++i) {
  1564. mythread_sync(coder->threads[i].mutex) {
  1565. *progress_in += coder->threads[i].progress_in;
  1566. *progress_out += coder->threads[i]
  1567. .progress_out;
  1568. }
  1569. }
  1570. }
  1571. return;
  1572. }
  1573. static lzma_ret
  1574. stream_decoder_mt_init(lzma_next_coder *next, const lzma_allocator *allocator,
  1575. const lzma_mt *options)
  1576. {
  1577. struct lzma_stream_coder *coder;
  1578. if (options->threads == 0 || options->threads > LZMA_THREADS_MAX)
  1579. return LZMA_OPTIONS_ERROR;
  1580. if (options->flags & ~LZMA_SUPPORTED_FLAGS)
  1581. return LZMA_OPTIONS_ERROR;
  1582. lzma_next_coder_init(&stream_decoder_mt_init, next, allocator);
  1583. coder = next->coder;
  1584. if (!coder) {
  1585. coder = lzma_alloc(sizeof(struct lzma_stream_coder), allocator);
  1586. if (coder == NULL)
  1587. return LZMA_MEM_ERROR;
  1588. next->coder = coder;
  1589. if (mythread_mutex_init(&coder->mutex)) {
  1590. lzma_free(coder, allocator);
  1591. return LZMA_MEM_ERROR;
  1592. }
  1593. if (mythread_cond_init(&coder->cond)) {
  1594. mythread_mutex_destroy(&coder->mutex);
  1595. lzma_free(coder, allocator);
  1596. return LZMA_MEM_ERROR;
  1597. }
  1598. next->code = &stream_decode_mt;
  1599. next->end = &stream_decoder_mt_end;
  1600. next->get_check = &stream_decoder_mt_get_check;
  1601. next->memconfig = &stream_decoder_mt_memconfig;
  1602. next->get_progress = &stream_decoder_mt_get_progress;
  1603. coder->filters[0].id = LZMA_VLI_UNKNOWN;
  1604. memzero(&coder->outq, sizeof(coder->outq));
  1605. coder->block_decoder = LZMA_NEXT_CODER_INIT;
  1606. coder->mem_direct_mode = 0;
  1607. coder->index_hash = NULL;
  1608. coder->threads = NULL;
  1609. coder->threads_free = NULL;
  1610. coder->threads_initialized = 0;
  1611. }
  1612. // Cleanup old filter chain if one remains after unfinished decoding
  1613. // of a previous Stream.
  1614. lzma_filters_free(coder->filters, allocator);
  1615. // By allocating threads from scratch we can start memory-usage
  1616. // accounting from scratch, too. Changes in filter and block sizes may
  1617. // affect number of threads.
  1618. //
  1619. // FIXME? Reusing should be easy but unlike the single-threaded
  1620. // decoder, with some types of input file combinations reusing
  1621. // could leave quite a lot of memory allocated but unused (first
  1622. // file could allocate a lot, the next files could use fewer
  1623. // threads and some of the allocations from the first file would not
  1624. // get freed unless memlimit_threading forces us to clear caches).
  1625. //
  1626. // NOTE: The direct mode decoder isn't freed here if one exists.
  1627. // It will be reused or freed as needed in the main loop.
  1628. threads_end(coder, allocator);
  1629. // All memusage counters start at 0 (including mem_direct_mode).
  1630. // The little extra that is needed for the structs in this file
  1631. // get accounted well enough by the filter chain memory usage
  1632. // which adds LZMA_MEMUSAGE_BASE for each chain. However,
  1633. // stream_decoder_mt_memconfig() has to handle this specially so that
  1634. // it will never return less than LZMA_MEMUSAGE_BASE as memory usage.
  1635. coder->mem_in_use = 0;
  1636. coder->mem_cached = 0;
  1637. coder->mem_next_block = 0;
  1638. coder->progress_in = 0;
  1639. coder->progress_out = 0;
  1640. coder->sequence = SEQ_STREAM_HEADER;
  1641. coder->thread_error = LZMA_OK;
  1642. coder->pending_error = LZMA_OK;
  1643. coder->thr = NULL;
  1644. coder->timeout = options->timeout;
  1645. coder->memlimit_threading = my_max(1, options->memlimit_threading);
  1646. coder->memlimit_stop = my_max(1, options->memlimit_stop);
  1647. if (coder->memlimit_threading > coder->memlimit_stop)
  1648. coder->memlimit_threading = coder->memlimit_stop;
  1649. coder->tell_no_check = (options->flags & LZMA_TELL_NO_CHECK) != 0;
  1650. coder->tell_unsupported_check
  1651. = (options->flags & LZMA_TELL_UNSUPPORTED_CHECK) != 0;
  1652. coder->tell_any_check = (options->flags & LZMA_TELL_ANY_CHECK) != 0;
  1653. coder->ignore_check = (options->flags & LZMA_IGNORE_CHECK) != 0;
  1654. coder->concatenated = (options->flags & LZMA_CONCATENATED) != 0;
  1655. coder->fail_fast = (options->flags & LZMA_FAIL_FAST) != 0;
  1656. coder->first_stream = true;
  1657. coder->out_was_filled = false;
  1658. coder->pos = 0;
  1659. coder->threads_max = options->threads;
  1660. return_if_error(lzma_outq_init(&coder->outq, allocator,
  1661. coder->threads_max));
  1662. return stream_decoder_reset(coder, allocator);
  1663. }
  1664. extern LZMA_API(lzma_ret)
  1665. lzma_stream_decoder_mt(lzma_stream *strm, const lzma_mt *options)
  1666. {
  1667. lzma_next_strm_init(stream_decoder_mt_init, strm, options);
  1668. strm->internal->supported_actions[LZMA_RUN] = true;
  1669. strm->internal->supported_actions[LZMA_FINISH] = true;
  1670. return LZMA_OK;
  1671. }