stream_decoder_mt.c 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017
  1. // SPDX-License-Identifier: 0BSD
  2. ///////////////////////////////////////////////////////////////////////////////
  3. //
  4. /// \file stream_decoder_mt.c
  5. /// \brief Multithreaded .xz Stream decoder
  6. //
  7. // Authors: Sebastian Andrzej Siewior
  8. // Lasse Collin
  9. //
  10. ///////////////////////////////////////////////////////////////////////////////
  11. #include "common.h"
  12. #include "block_decoder.h"
  13. #include "stream_decoder.h"
  14. #include "index.h"
  15. #include "outqueue.h"
  16. typedef enum {
  17. /// Waiting for work.
  18. /// Main thread may change this to THR_RUN or THR_EXIT.
  19. THR_IDLE,
  20. /// Decoding is in progress.
  21. /// Main thread may change this to THR_STOP or THR_EXIT.
  22. /// The worker thread may change this to THR_IDLE.
  23. THR_RUN,
  24. /// The main thread wants the thread to stop whatever it was doing
  25. /// but not exit. Main thread may change this to THR_EXIT.
  26. /// The worker thread may change this to THR_IDLE.
  27. THR_STOP,
  28. /// The main thread wants the thread to exit.
  29. THR_EXIT,
  30. } worker_state;
  31. typedef enum {
  32. /// Partial updates (storing of worker thread progress
  33. /// to lzma_outbuf) are disabled.
  34. PARTIAL_DISABLED,
  35. /// Main thread requests partial updates to be enabled but
  36. /// no partial update has been done by the worker thread yet.
  37. ///
  38. /// Changing from PARTIAL_DISABLED to PARTIAL_START requires
  39. /// use of the worker-thread mutex. Other transitions don't
  40. /// need a mutex.
  41. PARTIAL_START,
  42. /// Partial updates are enabled and the worker thread has done
  43. /// at least one partial update.
  44. PARTIAL_ENABLED,
  45. } partial_update_mode;
  46. struct worker_thread {
  47. /// Worker state is protected with our mutex.
  48. worker_state state;
  49. /// Input buffer that will contain the whole Block except Block Header.
  50. uint8_t *in;
  51. /// Amount of memory allocated for "in"
  52. size_t in_size;
  53. /// Number of bytes written to "in" by the main thread
  54. size_t in_filled;
  55. /// Number of bytes consumed from "in" by the worker thread.
  56. size_t in_pos;
  57. /// Amount of uncompressed data that has been decoded. This local
  58. /// copy is needed because updating outbuf->pos requires locking
  59. /// the main mutex (coder->mutex).
  60. size_t out_pos;
  61. /// Pointer to the main structure is needed to (1) lock the main
  62. /// mutex (coder->mutex) when updating outbuf->pos and (2) when
  63. /// putting this thread back to the stack of free threads.
  64. struct lzma_stream_coder *coder;
  65. /// The allocator is set by the main thread. Since a copy of the
  66. /// pointer is kept here, the application must not change the
  67. /// allocator before calling lzma_end().
  68. const lzma_allocator *allocator;
  69. /// Output queue buffer to which the uncompressed data is written.
  70. lzma_outbuf *outbuf;
  71. /// Amount of compressed data that has already been decompressed.
  72. /// This is updated from in_pos when our mutex is locked.
  73. /// This is size_t, not uint64_t, because per-thread progress
  74. /// is limited to sizes of allocated buffers.
  75. size_t progress_in;
  76. /// Like progress_in but for uncompressed data.
  77. size_t progress_out;
  78. /// Updating outbuf->pos requires locking the main mutex
  79. /// (coder->mutex). Since the main thread will only read output
  80. /// from the oldest outbuf in the queue, only the worker thread
  81. /// that is associated with the oldest outbuf needs to update its
  82. /// outbuf->pos. This avoids useless mutex contention that would
  83. /// happen if all worker threads were frequently locking the main
  84. /// mutex to update their outbuf->pos.
  85. ///
  86. /// Only when partial_update is something else than PARTIAL_DISABLED,
  87. /// this worker thread will update outbuf->pos after each call to
  88. /// the Block decoder.
  89. partial_update_mode partial_update;
  90. /// Block decoder
  91. lzma_next_coder block_decoder;
  92. /// Thread-specific Block options are needed because the Block
  93. /// decoder modifies the struct given to it at initialization.
  94. lzma_block block_options;
  95. /// Filter chain memory usage
  96. uint64_t mem_filters;
  97. /// Next structure in the stack of free worker threads.
  98. struct worker_thread *next;
  99. mythread_mutex mutex;
  100. mythread_cond cond;
  101. /// The ID of this thread is used to join the thread
  102. /// when it's not needed anymore.
  103. mythread thread_id;
  104. };
  105. struct lzma_stream_coder {
  106. enum {
  107. SEQ_STREAM_HEADER,
  108. SEQ_BLOCK_HEADER,
  109. SEQ_BLOCK_INIT,
  110. SEQ_BLOCK_THR_INIT,
  111. SEQ_BLOCK_THR_RUN,
  112. SEQ_BLOCK_DIRECT_INIT,
  113. SEQ_BLOCK_DIRECT_RUN,
  114. SEQ_INDEX_WAIT_OUTPUT,
  115. SEQ_INDEX_DECODE,
  116. SEQ_STREAM_FOOTER,
  117. SEQ_STREAM_PADDING,
  118. SEQ_ERROR,
  119. } sequence;
  120. /// Block decoder
  121. lzma_next_coder block_decoder;
  122. /// Every Block Header will be decoded into this structure.
  123. /// This is also used to initialize a Block decoder when in
  124. /// direct mode. In threaded mode, a thread-specific copy will
  125. /// be made for decoder initialization because the Block decoder
  126. /// will modify the structure given to it.
  127. lzma_block block_options;
  128. /// Buffer to hold a filter chain for Block Header decoding and
  129. /// initialization. These are freed after successful Block decoder
  130. /// initialization or at stream_decoder_mt_end(). The thread-specific
  131. /// copy of block_options won't hold a pointer to filters[] after
  132. /// initialization.
  133. lzma_filter filters[LZMA_FILTERS_MAX + 1];
  134. /// Stream Flags from Stream Header
  135. lzma_stream_flags stream_flags;
  136. /// Index is hashed so that it can be compared to the sizes of Blocks
  137. /// with O(1) memory usage.
  138. lzma_index_hash *index_hash;
  139. /// Maximum wait time if cannot use all the input and cannot
  140. /// fill the output buffer. This is in milliseconds.
  141. uint32_t timeout;
  142. /// Error code from a worker thread.
  143. ///
  144. /// \note Use mutex.
  145. lzma_ret thread_error;
  146. /// Error code to return after pending output has been copied out. If
  147. /// set in read_output_and_wait(), this is a mirror of thread_error.
  148. /// If set in stream_decode_mt() then it's, for example, error that
  149. /// occurred when decoding Block Header.
  150. lzma_ret pending_error;
  151. /// Number of threads that will be created at maximum.
  152. uint32_t threads_max;
  153. /// Number of thread structures that have been initialized from
  154. /// "threads", and thus the number of worker threads actually
  155. /// created so far.
  156. uint32_t threads_initialized;
  157. /// Array of allocated thread-specific structures. When no threads
  158. /// are in use (direct mode) this is NULL. In threaded mode this
  159. /// points to an array of threads_max number of worker_thread structs.
  160. struct worker_thread *threads;
  161. /// Stack of free threads. When a thread finishes, it puts itself
  162. /// back into this stack. This starts as empty because threads
  163. /// are created only when actually needed.
  164. ///
  165. /// \note Use mutex.
  166. struct worker_thread *threads_free;
  167. /// The most recent worker thread to which the main thread writes
  168. /// the new input from the application.
  169. struct worker_thread *thr;
  170. /// Output buffer queue for decompressed data from the worker threads
  171. ///
  172. /// \note Use mutex with operations that need it.
  173. lzma_outq outq;
  174. mythread_mutex mutex;
  175. mythread_cond cond;
  176. /// Memory usage that will not be exceeded in multi-threaded mode.
  177. /// Single-threaded mode can exceed this even by a large amount.
  178. uint64_t memlimit_threading;
  179. /// Memory usage limit that should never be exceeded.
  180. /// LZMA_MEMLIMIT_ERROR will be returned if decoding isn't possible
  181. /// even in single-threaded mode without exceeding this limit.
  182. uint64_t memlimit_stop;
  183. /// Amount of memory in use by the direct mode decoder
  184. /// (coder->block_decoder). In threaded mode this is 0.
  185. uint64_t mem_direct_mode;
  186. /// Amount of memory needed by the running worker threads.
  187. /// This doesn't include the memory needed by the output buffer.
  188. ///
  189. /// \note Use mutex.
  190. uint64_t mem_in_use;
  191. /// Amount of memory used by the idle (cached) threads.
  192. ///
  193. /// \note Use mutex.
  194. uint64_t mem_cached;
  195. /// Amount of memory needed for the filter chain of the next Block.
  196. uint64_t mem_next_filters;
  197. /// Amount of memory needed for the thread-specific input buffer
  198. /// for the next Block.
  199. uint64_t mem_next_in;
  200. /// Amount of memory actually needed to decode the next Block
  201. /// in threaded mode. This is
  202. /// mem_next_filters + mem_next_in + memory needed for lzma_outbuf.
  203. uint64_t mem_next_block;
  204. /// Amount of compressed data in Stream Header + Blocks that have
  205. /// already been finished.
  206. ///
  207. /// \note Use mutex.
  208. uint64_t progress_in;
  209. /// Amount of uncompressed data in Blocks that have already
  210. /// been finished.
  211. ///
  212. /// \note Use mutex.
  213. uint64_t progress_out;
  214. /// If true, LZMA_NO_CHECK is returned if the Stream has
  215. /// no integrity check.
  216. bool tell_no_check;
  217. /// If true, LZMA_UNSUPPORTED_CHECK is returned if the Stream has
  218. /// an integrity check that isn't supported by this liblzma build.
  219. bool tell_unsupported_check;
  220. /// If true, LZMA_GET_CHECK is returned after decoding Stream Header.
  221. bool tell_any_check;
  222. /// If true, we will tell the Block decoder to skip calculating
  223. /// and verifying the integrity check.
  224. bool ignore_check;
  225. /// If true, we will decode concatenated Streams that possibly have
  226. /// Stream Padding between or after them. LZMA_STREAM_END is returned
  227. /// once the application isn't giving us any new input (LZMA_FINISH),
  228. /// and we aren't in the middle of a Stream, and possible
  229. /// Stream Padding is a multiple of four bytes.
  230. bool concatenated;
  231. /// If true, we will return any errors immediately instead of first
  232. /// producing all output before the location of the error.
  233. bool fail_fast;
  234. /// When decoding concatenated Streams, this is true as long as we
  235. /// are decoding the first Stream. This is needed to avoid misleading
  236. /// LZMA_FORMAT_ERROR in case the later Streams don't have valid magic
  237. /// bytes.
  238. bool first_stream;
  239. /// This is used to track if the previous call to stream_decode_mt()
  240. /// had output space (*out_pos < out_size) and managed to fill the
  241. /// output buffer (*out_pos == out_size). This may be set to true
  242. /// in read_output_and_wait(). This is read and then reset to false
  243. /// at the beginning of stream_decode_mt().
  244. ///
  245. /// This is needed to support applications that call lzma_code() in
  246. /// such a way that more input is provided only when lzma_code()
  247. /// didn't fill the output buffer completely. Basically, this makes
  248. /// it easier to convert such applications from single-threaded
  249. /// decoder to multi-threaded decoder.
  250. bool out_was_filled;
  251. /// Write position in buffer[] and position in Stream Padding
  252. size_t pos;
  253. /// Buffer to hold Stream Header, Block Header, and Stream Footer.
  254. /// Block Header has biggest maximum size.
  255. uint8_t buffer[LZMA_BLOCK_HEADER_SIZE_MAX];
  256. };
  257. /// Enables updating of outbuf->pos. This is a callback function that is
  258. /// used with lzma_outq_enable_partial_output().
  259. static void
  260. worker_enable_partial_update(void *thr_ptr)
  261. {
  262. struct worker_thread *thr = thr_ptr;
  263. mythread_sync(thr->mutex) {
  264. thr->partial_update = PARTIAL_START;
  265. mythread_cond_signal(&thr->cond);
  266. }
  267. }
  268. /// Things do to at THR_STOP or when finishing a Block.
  269. /// This is called with thr->mutex locked.
  270. static void
  271. worker_stop(struct worker_thread *thr)
  272. {
  273. // Update memory usage counters.
  274. thr->coder->mem_in_use -= thr->in_size;
  275. thr->in_size = 0; // thr->in was freed above.
  276. thr->coder->mem_in_use -= thr->mem_filters;
  277. thr->coder->mem_cached += thr->mem_filters;
  278. // Put this thread to the stack of free threads.
  279. thr->next = thr->coder->threads_free;
  280. thr->coder->threads_free = thr;
  281. mythread_cond_signal(&thr->coder->cond);
  282. return;
  283. }
  284. static MYTHREAD_RET_TYPE
  285. worker_decoder(void *thr_ptr)
  286. {
  287. struct worker_thread *thr = thr_ptr;
  288. size_t in_filled;
  289. partial_update_mode partial_update;
  290. lzma_ret ret;
  291. next_loop_lock:
  292. mythread_mutex_lock(&thr->mutex);
  293. next_loop_unlocked:
  294. if (thr->state == THR_IDLE) {
  295. mythread_cond_wait(&thr->cond, &thr->mutex);
  296. goto next_loop_unlocked;
  297. }
  298. if (thr->state == THR_EXIT) {
  299. mythread_mutex_unlock(&thr->mutex);
  300. lzma_free(thr->in, thr->allocator);
  301. lzma_next_end(&thr->block_decoder, thr->allocator);
  302. mythread_mutex_destroy(&thr->mutex);
  303. mythread_cond_destroy(&thr->cond);
  304. return MYTHREAD_RET_VALUE;
  305. }
  306. if (thr->state == THR_STOP) {
  307. thr->state = THR_IDLE;
  308. mythread_mutex_unlock(&thr->mutex);
  309. mythread_sync(thr->coder->mutex) {
  310. worker_stop(thr);
  311. }
  312. goto next_loop_lock;
  313. }
  314. assert(thr->state == THR_RUN);
  315. // Update progress info for get_progress().
  316. thr->progress_in = thr->in_pos;
  317. thr->progress_out = thr->out_pos;
  318. // If we don't have any new input, wait for a signal from the main
  319. // thread except if partial output has just been enabled. In that
  320. // case we will do one normal run so that the partial output info
  321. // gets passed to the main thread. The call to block_decoder.code()
  322. // is useless but harmless as it can occur only once per Block.
  323. in_filled = thr->in_filled;
  324. partial_update = thr->partial_update;
  325. if (in_filled == thr->in_pos && partial_update != PARTIAL_START) {
  326. mythread_cond_wait(&thr->cond, &thr->mutex);
  327. goto next_loop_unlocked;
  328. }
  329. mythread_mutex_unlock(&thr->mutex);
  330. // Pass the input in small chunks to the Block decoder.
  331. // This way we react reasonably fast if we are told to stop/exit,
  332. // and (when partial update is enabled) we tell about our progress
  333. // to the main thread frequently enough.
  334. const size_t chunk_size = 16384;
  335. if ((in_filled - thr->in_pos) > chunk_size)
  336. in_filled = thr->in_pos + chunk_size;
  337. ret = thr->block_decoder.code(
  338. thr->block_decoder.coder, thr->allocator,
  339. thr->in, &thr->in_pos, in_filled,
  340. thr->outbuf->buf, &thr->out_pos,
  341. thr->outbuf->allocated, LZMA_RUN);
  342. if (ret == LZMA_OK) {
  343. if (partial_update != PARTIAL_DISABLED) {
  344. // The main thread uses thr->mutex to change from
  345. // PARTIAL_DISABLED to PARTIAL_START. The main thread
  346. // doesn't care about this variable after that so we
  347. // can safely change it here to PARTIAL_ENABLED
  348. // without a mutex.
  349. thr->partial_update = PARTIAL_ENABLED;
  350. // The main thread is reading decompressed data
  351. // from thr->outbuf. Tell the main thread about
  352. // our progress.
  353. //
  354. // NOTE: It's possible that we consumed input without
  355. // producing any new output so it's possible that
  356. // only in_pos has changed. In case of PARTIAL_START
  357. // it is possible that neither in_pos nor out_pos has
  358. // changed.
  359. mythread_sync(thr->coder->mutex) {
  360. thr->outbuf->pos = thr->out_pos;
  361. thr->outbuf->decoder_in_pos = thr->in_pos;
  362. mythread_cond_signal(&thr->coder->cond);
  363. }
  364. }
  365. goto next_loop_lock;
  366. }
  367. // Either we finished successfully (LZMA_STREAM_END) or an error
  368. // occurred. Both cases are handled almost identically. The error
  369. // case requires updating thr->coder->thread_error.
  370. //
  371. // The sizes are in the Block Header and the Block decoder
  372. // checks that they match, thus we know these:
  373. assert(ret != LZMA_STREAM_END || thr->in_pos == thr->in_size);
  374. assert(ret != LZMA_STREAM_END
  375. || thr->out_pos == thr->block_options.uncompressed_size);
  376. // Free the input buffer. Don't update in_size as we need
  377. // it later to update thr->coder->mem_in_use.
  378. lzma_free(thr->in, thr->allocator);
  379. thr->in = NULL;
  380. mythread_sync(thr->mutex) {
  381. if (thr->state != THR_EXIT)
  382. thr->state = THR_IDLE;
  383. }
  384. mythread_sync(thr->coder->mutex) {
  385. // Move our progress info to the main thread.
  386. thr->coder->progress_in += thr->in_pos;
  387. thr->coder->progress_out += thr->out_pos;
  388. thr->progress_in = 0;
  389. thr->progress_out = 0;
  390. // Mark the outbuf as finished.
  391. thr->outbuf->pos = thr->out_pos;
  392. thr->outbuf->decoder_in_pos = thr->in_pos;
  393. thr->outbuf->finished = true;
  394. thr->outbuf->finish_ret = ret;
  395. thr->outbuf = NULL;
  396. // If an error occurred, tell it to the main thread.
  397. if (ret != LZMA_STREAM_END
  398. && thr->coder->thread_error == LZMA_OK)
  399. thr->coder->thread_error = ret;
  400. worker_stop(thr);
  401. }
  402. goto next_loop_lock;
  403. }
  404. /// Tells the worker threads to exit and waits for them to terminate.
  405. static void
  406. threads_end(struct lzma_stream_coder *coder, const lzma_allocator *allocator)
  407. {
  408. for (uint32_t i = 0; i < coder->threads_initialized; ++i) {
  409. mythread_sync(coder->threads[i].mutex) {
  410. coder->threads[i].state = THR_EXIT;
  411. mythread_cond_signal(&coder->threads[i].cond);
  412. }
  413. }
  414. for (uint32_t i = 0; i < coder->threads_initialized; ++i)
  415. mythread_join(coder->threads[i].thread_id);
  416. lzma_free(coder->threads, allocator);
  417. coder->threads_initialized = 0;
  418. coder->threads = NULL;
  419. coder->threads_free = NULL;
  420. // The threads don't update these when they exit. Do it here.
  421. coder->mem_in_use = 0;
  422. coder->mem_cached = 0;
  423. return;
  424. }
  425. static void
  426. threads_stop(struct lzma_stream_coder *coder)
  427. {
  428. for (uint32_t i = 0; i < coder->threads_initialized; ++i) {
  429. mythread_sync(coder->threads[i].mutex) {
  430. // The state must be changed conditionally because
  431. // THR_IDLE -> THR_STOP is not a valid state change.
  432. if (coder->threads[i].state != THR_IDLE) {
  433. coder->threads[i].state = THR_STOP;
  434. mythread_cond_signal(&coder->threads[i].cond);
  435. }
  436. }
  437. }
  438. return;
  439. }
  440. /// Initialize a new worker_thread structure and create a new thread.
  441. static lzma_ret
  442. initialize_new_thread(struct lzma_stream_coder *coder,
  443. const lzma_allocator *allocator)
  444. {
  445. // Allocate the coder->threads array if needed. It's done here instead
  446. // of when initializing the decoder because we don't need this if we
  447. // use the direct mode (we may even free coder->threads in the middle
  448. // of the file if we switch from threaded to direct mode).
  449. if (coder->threads == NULL) {
  450. coder->threads = lzma_alloc(
  451. coder->threads_max * sizeof(struct worker_thread),
  452. allocator);
  453. if (coder->threads == NULL)
  454. return LZMA_MEM_ERROR;
  455. }
  456. // Pick a free structure.
  457. assert(coder->threads_initialized < coder->threads_max);
  458. struct worker_thread *thr
  459. = &coder->threads[coder->threads_initialized];
  460. if (mythread_mutex_init(&thr->mutex))
  461. goto error_mutex;
  462. if (mythread_cond_init(&thr->cond))
  463. goto error_cond;
  464. thr->state = THR_IDLE;
  465. thr->in = NULL;
  466. thr->in_size = 0;
  467. thr->allocator = allocator;
  468. thr->coder = coder;
  469. thr->outbuf = NULL;
  470. thr->block_decoder = LZMA_NEXT_CODER_INIT;
  471. thr->mem_filters = 0;
  472. if (mythread_create(&thr->thread_id, worker_decoder, thr))
  473. goto error_thread;
  474. ++coder->threads_initialized;
  475. coder->thr = thr;
  476. return LZMA_OK;
  477. error_thread:
  478. mythread_cond_destroy(&thr->cond);
  479. error_cond:
  480. mythread_mutex_destroy(&thr->mutex);
  481. error_mutex:
  482. return LZMA_MEM_ERROR;
  483. }
  484. static lzma_ret
  485. get_thread(struct lzma_stream_coder *coder, const lzma_allocator *allocator)
  486. {
  487. // If there is a free structure on the stack, use it.
  488. mythread_sync(coder->mutex) {
  489. if (coder->threads_free != NULL) {
  490. coder->thr = coder->threads_free;
  491. coder->threads_free = coder->threads_free->next;
  492. // The thread is no longer in the cache so subtract
  493. // it from the cached memory usage. Don't add it
  494. // to mem_in_use though; the caller will handle it
  495. // since it knows how much memory it will actually
  496. // use (the filter chain might change).
  497. coder->mem_cached -= coder->thr->mem_filters;
  498. }
  499. }
  500. if (coder->thr == NULL) {
  501. assert(coder->threads_initialized < coder->threads_max);
  502. // Initialize a new thread.
  503. return_if_error(initialize_new_thread(coder, allocator));
  504. }
  505. coder->thr->in_filled = 0;
  506. coder->thr->in_pos = 0;
  507. coder->thr->out_pos = 0;
  508. coder->thr->progress_in = 0;
  509. coder->thr->progress_out = 0;
  510. coder->thr->partial_update = PARTIAL_DISABLED;
  511. return LZMA_OK;
  512. }
  513. static lzma_ret
  514. read_output_and_wait(struct lzma_stream_coder *coder,
  515. const lzma_allocator *allocator,
  516. uint8_t *restrict out, size_t *restrict out_pos,
  517. size_t out_size,
  518. bool *input_is_possible,
  519. bool waiting_allowed,
  520. mythread_condtime *wait_abs, bool *has_blocked)
  521. {
  522. lzma_ret ret = LZMA_OK;
  523. mythread_sync(coder->mutex) {
  524. do {
  525. // Get as much output from the queue as is possible
  526. // without blocking.
  527. const size_t out_start = *out_pos;
  528. do {
  529. ret = lzma_outq_read(&coder->outq, allocator,
  530. out, out_pos, out_size,
  531. NULL, NULL);
  532. // If a Block was finished, tell the worker
  533. // thread of the next Block (if it is still
  534. // running) to start telling the main thread
  535. // when new output is available.
  536. if (ret == LZMA_STREAM_END)
  537. lzma_outq_enable_partial_output(
  538. &coder->outq,
  539. &worker_enable_partial_update);
  540. // Loop until a Block wasn't finished.
  541. // It's important to loop around even if
  542. // *out_pos == out_size because there could
  543. // be an empty Block that will return
  544. // LZMA_STREAM_END without needing any
  545. // output space.
  546. } while (ret == LZMA_STREAM_END);
  547. // Check if lzma_outq_read reported an error from
  548. // the Block decoder.
  549. if (ret != LZMA_OK)
  550. break;
  551. // If the output buffer is now full but it wasn't full
  552. // when this function was called, set out_was_filled.
  553. // This way the next call to stream_decode_mt() knows
  554. // that some output was produced and no output space
  555. // remained in the previous call to stream_decode_mt().
  556. if (*out_pos == out_size && *out_pos != out_start)
  557. coder->out_was_filled = true;
  558. // Check if any thread has indicated an error.
  559. if (coder->thread_error != LZMA_OK) {
  560. // If LZMA_FAIL_FAST was used, report errors
  561. // from worker threads immediately.
  562. if (coder->fail_fast) {
  563. ret = coder->thread_error;
  564. break;
  565. }
  566. // Otherwise set pending_error. The value we
  567. // set here will not actually get used other
  568. // than working as a flag that an error has
  569. // occurred. This is because in SEQ_ERROR
  570. // all output before the error will be read
  571. // first by calling this function, and once we
  572. // reach the location of the (first) error the
  573. // error code from the above lzma_outq_read()
  574. // will be returned to the application.
  575. //
  576. // Use LZMA_PROG_ERROR since the value should
  577. // never leak to the application. It's
  578. // possible that pending_error has already
  579. // been set but that doesn't matter: if we get
  580. // here, pending_error only works as a flag.
  581. coder->pending_error = LZMA_PROG_ERROR;
  582. }
  583. // Check if decoding of the next Block can be started.
  584. // The memusage of the active threads must be low
  585. // enough, there must be a free buffer slot in the
  586. // output queue, and there must be a free thread
  587. // (that can be either created or an existing one
  588. // reused).
  589. //
  590. // NOTE: This is checked after reading the output
  591. // above because reading the output can free a slot in
  592. // the output queue and also reduce active memusage.
  593. //
  594. // NOTE: If output queue is empty, then input will
  595. // always be possible.
  596. if (input_is_possible != NULL
  597. && coder->memlimit_threading
  598. - coder->mem_in_use
  599. - coder->outq.mem_in_use
  600. >= coder->mem_next_block
  601. && lzma_outq_has_buf(&coder->outq)
  602. && (coder->threads_initialized
  603. < coder->threads_max
  604. || coder->threads_free
  605. != NULL)) {
  606. *input_is_possible = true;
  607. break;
  608. }
  609. // If the caller doesn't want us to block, return now.
  610. if (!waiting_allowed)
  611. break;
  612. // This check is needed only when input_is_possible
  613. // is NULL. We must return if we aren't waiting for
  614. // input to become possible and there is no more
  615. // output coming from the queue.
  616. if (lzma_outq_is_empty(&coder->outq)) {
  617. assert(input_is_possible == NULL);
  618. break;
  619. }
  620. // If there is more data available from the queue,
  621. // our out buffer must be full and we need to return
  622. // so that the application can provide more output
  623. // space.
  624. //
  625. // NOTE: In general lzma_outq_is_readable() can return
  626. // true also when there are no more bytes available.
  627. // This can happen when a Block has finished without
  628. // providing any new output. We know that this is not
  629. // the case because in the beginning of this loop we
  630. // tried to read as much as possible even when we had
  631. // no output space left and the mutex has been locked
  632. // all the time (so worker threads cannot have changed
  633. // anything). Thus there must be actual pending output
  634. // in the queue.
  635. if (lzma_outq_is_readable(&coder->outq)) {
  636. assert(*out_pos == out_size);
  637. break;
  638. }
  639. // If the application stops providing more input
  640. // in the middle of a Block, there will eventually
  641. // be one worker thread left that is stuck waiting for
  642. // more input (that might never arrive) and a matching
  643. // outbuf which the worker thread cannot finish due
  644. // to lack of input. We must detect this situation,
  645. // otherwise we would end up waiting indefinitely
  646. // (if no timeout is in use) or keep returning
  647. // LZMA_TIMED_OUT while making no progress. Thus, the
  648. // application would never get LZMA_BUF_ERROR from
  649. // lzma_code() which would tell the application that
  650. // no more progress is possible. No LZMA_BUF_ERROR
  651. // means that, for example, truncated .xz files could
  652. // cause an infinite loop.
  653. //
  654. // A worker thread doing partial updates will
  655. // store not only the output position in outbuf->pos
  656. // but also the matching input position in
  657. // outbuf->decoder_in_pos. Here we check if that
  658. // input position matches the amount of input that
  659. // the worker thread has been given (in_filled).
  660. // If so, we must return and not wait as no more
  661. // output will be coming without first getting more
  662. // input to the worker thread. If the application
  663. // keeps calling lzma_code() without providing more
  664. // input, it will eventually get LZMA_BUF_ERROR.
  665. //
  666. // NOTE: We can read partial_update and in_filled
  667. // without thr->mutex as only the main thread
  668. // modifies these variables. decoder_in_pos requires
  669. // coder->mutex which we are already holding.
  670. if (coder->thr != NULL && coder->thr->partial_update
  671. != PARTIAL_DISABLED) {
  672. // There is exactly one outbuf in the queue.
  673. assert(coder->thr->outbuf == coder->outq.head);
  674. assert(coder->thr->outbuf == coder->outq.tail);
  675. if (coder->thr->outbuf->decoder_in_pos
  676. == coder->thr->in_filled)
  677. break;
  678. }
  679. // Wait for input or output to become possible.
  680. if (coder->timeout != 0) {
  681. // See the comment in stream_encoder_mt.c
  682. // about why mythread_condtime_set() is used
  683. // like this.
  684. //
  685. // FIXME?
  686. // In contrast to the encoder, this calls
  687. // _condtime_set while the mutex is locked.
  688. if (!*has_blocked) {
  689. *has_blocked = true;
  690. mythread_condtime_set(wait_abs,
  691. &coder->cond,
  692. coder->timeout);
  693. }
  694. if (mythread_cond_timedwait(&coder->cond,
  695. &coder->mutex,
  696. wait_abs) != 0) {
  697. ret = LZMA_TIMED_OUT;
  698. break;
  699. }
  700. } else {
  701. mythread_cond_wait(&coder->cond,
  702. &coder->mutex);
  703. }
  704. } while (ret == LZMA_OK);
  705. }
  706. // If we are returning an error, then the application cannot get
  707. // more output from us and thus keeping the threads running is
  708. // useless and waste of CPU time.
  709. if (ret != LZMA_OK && ret != LZMA_TIMED_OUT)
  710. threads_stop(coder);
  711. return ret;
  712. }
  713. static lzma_ret
  714. decode_block_header(struct lzma_stream_coder *coder,
  715. const lzma_allocator *allocator, const uint8_t *restrict in,
  716. size_t *restrict in_pos, size_t in_size)
  717. {
  718. if (*in_pos >= in_size)
  719. return LZMA_OK;
  720. if (coder->pos == 0) {
  721. // Detect if it's Index.
  722. if (in[*in_pos] == INDEX_INDICATOR)
  723. return LZMA_INDEX_DETECTED;
  724. // Calculate the size of the Block Header. Note that
  725. // Block Header decoder wants to see this byte too
  726. // so don't advance *in_pos.
  727. coder->block_options.header_size
  728. = lzma_block_header_size_decode(
  729. in[*in_pos]);
  730. }
  731. // Copy the Block Header to the internal buffer.
  732. lzma_bufcpy(in, in_pos, in_size, coder->buffer, &coder->pos,
  733. coder->block_options.header_size);
  734. // Return if we didn't get the whole Block Header yet.
  735. if (coder->pos < coder->block_options.header_size)
  736. return LZMA_OK;
  737. coder->pos = 0;
  738. // Version 1 is needed to support the .ignore_check option.
  739. coder->block_options.version = 1;
  740. // Block Header decoder will initialize all members of this array
  741. // so we don't need to do it here.
  742. coder->block_options.filters = coder->filters;
  743. // Decode the Block Header.
  744. return_if_error(lzma_block_header_decode(&coder->block_options,
  745. allocator, coder->buffer));
  746. // If LZMA_IGNORE_CHECK was used, this flag needs to be set.
  747. // It has to be set after lzma_block_header_decode() because
  748. // it always resets this to false.
  749. coder->block_options.ignore_check = coder->ignore_check;
  750. // coder->block_options is ready now.
  751. return LZMA_STREAM_END;
  752. }
  753. /// Get the size of the Compressed Data + Block Padding + Check.
  754. static size_t
  755. comp_blk_size(const struct lzma_stream_coder *coder)
  756. {
  757. return vli_ceil4(coder->block_options.compressed_size)
  758. + lzma_check_size(coder->stream_flags.check);
  759. }
  760. /// Returns true if the size (compressed or uncompressed) is such that
  761. /// threaded decompression cannot be used. Sizes that are too big compared
  762. /// to SIZE_MAX must be rejected to avoid integer overflows and truncations
  763. /// when lzma_vli is assigned to a size_t.
  764. static bool
  765. is_direct_mode_needed(lzma_vli size)
  766. {
  767. return size == LZMA_VLI_UNKNOWN || size > SIZE_MAX / 3;
  768. }
  769. static lzma_ret
  770. stream_decoder_reset(struct lzma_stream_coder *coder,
  771. const lzma_allocator *allocator)
  772. {
  773. // Initialize the Index hash used to verify the Index.
  774. coder->index_hash = lzma_index_hash_init(coder->index_hash, allocator);
  775. if (coder->index_hash == NULL)
  776. return LZMA_MEM_ERROR;
  777. // Reset the rest of the variables.
  778. coder->sequence = SEQ_STREAM_HEADER;
  779. coder->pos = 0;
  780. return LZMA_OK;
  781. }
  782. static lzma_ret
  783. stream_decode_mt(void *coder_ptr, const lzma_allocator *allocator,
  784. const uint8_t *restrict in, size_t *restrict in_pos,
  785. size_t in_size,
  786. uint8_t *restrict out, size_t *restrict out_pos,
  787. size_t out_size, lzma_action action)
  788. {
  789. struct lzma_stream_coder *coder = coder_ptr;
  790. mythread_condtime wait_abs;
  791. bool has_blocked = false;
  792. // Determine if in SEQ_BLOCK_HEADER and SEQ_BLOCK_THR_RUN we should
  793. // tell read_output_and_wait() to wait until it can fill the output
  794. // buffer (or a timeout occurs). Two conditions must be met:
  795. //
  796. // (1) If the caller provided no new input. The reason for this
  797. // can be, for example, the end of the file or that there is
  798. // a pause in the input stream and more input is available
  799. // a little later. In this situation we should wait for output
  800. // because otherwise we would end up in a busy-waiting loop where
  801. // we make no progress and the application just calls us again
  802. // without providing any new input. This would then result in
  803. // LZMA_BUF_ERROR even though more output would be available
  804. // once the worker threads decode more data.
  805. //
  806. // (2) Even if (1) is true, we will not wait if the previous call to
  807. // this function managed to produce some output and the output
  808. // buffer became full. This is for compatibility with applications
  809. // that call lzma_code() in such a way that new input is provided
  810. // only when the output buffer didn't become full. Without this
  811. // trick such applications would have bad performance (bad
  812. // parallelization due to decoder not getting input fast enough).
  813. //
  814. // NOTE: Such loops might require that timeout is disabled (0)
  815. // if they assume that output-not-full implies that all input has
  816. // been consumed. If and only if timeout is enabled, we may return
  817. // when output isn't full *and* not all input has been consumed.
  818. //
  819. // However, if LZMA_FINISH is used, the above is ignored and we always
  820. // wait (timeout can still cause us to return) because we know that
  821. // we won't get any more input. This matters if the input file is
  822. // truncated and we are doing single-shot decoding, that is,
  823. // timeout = 0 and LZMA_FINISH is used on the first call to
  824. // lzma_code() and the output buffer is known to be big enough
  825. // to hold all uncompressed data:
  826. //
  827. // - If LZMA_FINISH wasn't handled specially, we could return
  828. // LZMA_OK before providing all output that is possible with the
  829. // truncated input. The rest would be available if lzma_code() was
  830. // called again but then it's not single-shot decoding anymore.
  831. //
  832. // - By handling LZMA_FINISH specially here, the first call will
  833. // produce all the output, matching the behavior of the
  834. // single-threaded decoder.
  835. //
  836. // So it's a very specific corner case but also easy to avoid. Note
  837. // that this special handling of LZMA_FINISH has no effect for
  838. // single-shot decoding when the input file is valid (not truncated);
  839. // premature LZMA_OK wouldn't be possible as long as timeout = 0.
  840. const bool waiting_allowed = action == LZMA_FINISH
  841. || (*in_pos == in_size && !coder->out_was_filled);
  842. coder->out_was_filled = false;
  843. while (true)
  844. switch (coder->sequence) {
  845. case SEQ_STREAM_HEADER: {
  846. // Copy the Stream Header to the internal buffer.
  847. const size_t in_old = *in_pos;
  848. lzma_bufcpy(in, in_pos, in_size, coder->buffer, &coder->pos,
  849. LZMA_STREAM_HEADER_SIZE);
  850. coder->progress_in += *in_pos - in_old;
  851. // Return if we didn't get the whole Stream Header yet.
  852. if (coder->pos < LZMA_STREAM_HEADER_SIZE)
  853. return LZMA_OK;
  854. coder->pos = 0;
  855. // Decode the Stream Header.
  856. const lzma_ret ret = lzma_stream_header_decode(
  857. &coder->stream_flags, coder->buffer);
  858. if (ret != LZMA_OK)
  859. return ret == LZMA_FORMAT_ERROR && !coder->first_stream
  860. ? LZMA_DATA_ERROR : ret;
  861. // If we are decoding concatenated Streams, and the later
  862. // Streams have invalid Header Magic Bytes, we give
  863. // LZMA_DATA_ERROR instead of LZMA_FORMAT_ERROR.
  864. coder->first_stream = false;
  865. // Copy the type of the Check so that Block Header and Block
  866. // decoders see it.
  867. coder->block_options.check = coder->stream_flags.check;
  868. // Even if we return LZMA_*_CHECK below, we want
  869. // to continue from Block Header decoding.
  870. coder->sequence = SEQ_BLOCK_HEADER;
  871. // Detect if there's no integrity check or if it is
  872. // unsupported if those were requested by the application.
  873. if (coder->tell_no_check && coder->stream_flags.check
  874. == LZMA_CHECK_NONE)
  875. return LZMA_NO_CHECK;
  876. if (coder->tell_unsupported_check
  877. && !lzma_check_is_supported(
  878. coder->stream_flags.check))
  879. return LZMA_UNSUPPORTED_CHECK;
  880. if (coder->tell_any_check)
  881. return LZMA_GET_CHECK;
  882. }
  883. // Fall through
  884. case SEQ_BLOCK_HEADER: {
  885. const size_t in_old = *in_pos;
  886. const lzma_ret ret = decode_block_header(coder, allocator,
  887. in, in_pos, in_size);
  888. coder->progress_in += *in_pos - in_old;
  889. if (ret == LZMA_OK) {
  890. // We didn't decode the whole Block Header yet.
  891. //
  892. // Read output from the queue before returning. This
  893. // is important because it is possible that the
  894. // application doesn't have any new input available
  895. // immediately. If we didn't try to copy output from
  896. // the output queue here, lzma_code() could end up
  897. // returning LZMA_BUF_ERROR even though queued output
  898. // is available.
  899. //
  900. // If the lzma_code() call provided at least one input
  901. // byte, only copy as much data from the output queue
  902. // as is available immediately. This way the
  903. // application will be able to provide more input
  904. // without a delay.
  905. //
  906. // On the other hand, if lzma_code() was called with
  907. // an empty input buffer(*), treat it specially: try
  908. // to fill the output buffer even if it requires
  909. // waiting for the worker threads to provide output
  910. // (timeout, if specified, can still cause us to
  911. // return).
  912. //
  913. // - This way the application will be able to get all
  914. // data that can be decoded from the input provided
  915. // so far.
  916. //
  917. // - We avoid both premature LZMA_BUF_ERROR and
  918. // busy-waiting where the application repeatedly
  919. // calls lzma_code() which immediately returns
  920. // LZMA_OK without providing new data.
  921. //
  922. // - If the queue becomes empty, we won't wait
  923. // anything and will return LZMA_OK immediately
  924. // (coder->timeout is completely ignored).
  925. //
  926. // (*) See the comment at the beginning of this
  927. // function how waiting_allowed is determined
  928. // and why there is an exception to the rule
  929. // of "called with an empty input buffer".
  930. assert(*in_pos == in_size);
  931. // If LZMA_FINISH was used we know that we won't get
  932. // more input, so the file must be truncated if we
  933. // get here. If worker threads don't detect any
  934. // errors, eventually there will be no more output
  935. // while we keep returning LZMA_OK which gets
  936. // converted to LZMA_BUF_ERROR in lzma_code().
  937. //
  938. // If fail-fast is enabled then we will return
  939. // immediately using LZMA_DATA_ERROR instead of
  940. // LZMA_OK or LZMA_BUF_ERROR. Rationale for the
  941. // error code:
  942. //
  943. // - Worker threads may have a large amount of
  944. // not-yet-decoded input data and we don't
  945. // know for sure if all data is valid. Bad
  946. // data there would result in LZMA_DATA_ERROR
  947. // when fail-fast isn't used.
  948. //
  949. // - Immediate LZMA_BUF_ERROR would be a bit weird
  950. // considering the older liblzma code. lzma_code()
  951. // even has an assertion to prevent coders from
  952. // returning LZMA_BUF_ERROR directly.
  953. //
  954. // The downside of this is that with fail-fast apps
  955. // cannot always distinguish between corrupt and
  956. // truncated files.
  957. if (action == LZMA_FINISH && coder->fail_fast) {
  958. // We won't produce any more output. Stop
  959. // the unfinished worker threads so they
  960. // won't waste CPU time.
  961. threads_stop(coder);
  962. return LZMA_DATA_ERROR;
  963. }
  964. // read_output_and_wait() will call threads_stop()
  965. // if needed so with that we can use return_if_error.
  966. return_if_error(read_output_and_wait(coder, allocator,
  967. out, out_pos, out_size,
  968. NULL, waiting_allowed,
  969. &wait_abs, &has_blocked));
  970. if (coder->pending_error != LZMA_OK) {
  971. coder->sequence = SEQ_ERROR;
  972. break;
  973. }
  974. return LZMA_OK;
  975. }
  976. if (ret == LZMA_INDEX_DETECTED) {
  977. coder->sequence = SEQ_INDEX_WAIT_OUTPUT;
  978. break;
  979. }
  980. // See if an error occurred.
  981. if (ret != LZMA_STREAM_END) {
  982. // NOTE: Here and in all other places where
  983. // pending_error is set, it may overwrite the value
  984. // (LZMA_PROG_ERROR) set by read_output_and_wait().
  985. // That function might overwrite value set here too.
  986. // These are fine because when read_output_and_wait()
  987. // sets pending_error, it actually works as a flag
  988. // variable only ("some error has occurred") and the
  989. // actual value of pending_error is not used in
  990. // SEQ_ERROR. In such cases SEQ_ERROR will eventually
  991. // get the correct error code from the return value of
  992. // a later read_output_and_wait() call.
  993. coder->pending_error = ret;
  994. coder->sequence = SEQ_ERROR;
  995. break;
  996. }
  997. // Calculate the memory usage of the filters / Block decoder.
  998. coder->mem_next_filters = lzma_raw_decoder_memusage(
  999. coder->filters);
  1000. if (coder->mem_next_filters == UINT64_MAX) {
  1001. // One or more unknown Filter IDs.
  1002. coder->pending_error = LZMA_OPTIONS_ERROR;
  1003. coder->sequence = SEQ_ERROR;
  1004. break;
  1005. }
  1006. coder->sequence = SEQ_BLOCK_INIT;
  1007. }
  1008. // Fall through
  1009. case SEQ_BLOCK_INIT: {
  1010. // Check if decoding is possible at all with the current
  1011. // memlimit_stop which we must never exceed.
  1012. //
  1013. // This needs to be the first thing in SEQ_BLOCK_INIT
  1014. // to make it possible to restart decoding after increasing
  1015. // memlimit_stop with lzma_memlimit_set().
  1016. if (coder->mem_next_filters > coder->memlimit_stop) {
  1017. // Flush pending output before returning
  1018. // LZMA_MEMLIMIT_ERROR. If the application doesn't
  1019. // want to increase the limit, at least it will get
  1020. // all the output possible so far.
  1021. return_if_error(read_output_and_wait(coder, allocator,
  1022. out, out_pos, out_size,
  1023. NULL, true, &wait_abs, &has_blocked));
  1024. if (!lzma_outq_is_empty(&coder->outq))
  1025. return LZMA_OK;
  1026. return LZMA_MEMLIMIT_ERROR;
  1027. }
  1028. // Check if the size information is available in Block Header.
  1029. // If it is, check if the sizes are small enough that we don't
  1030. // need to worry *too* much about integer overflows later in
  1031. // the code. If these conditions are not met, we must use the
  1032. // single-threaded direct mode.
  1033. if (is_direct_mode_needed(coder->block_options.compressed_size)
  1034. || is_direct_mode_needed(
  1035. coder->block_options.uncompressed_size)) {
  1036. coder->sequence = SEQ_BLOCK_DIRECT_INIT;
  1037. break;
  1038. }
  1039. // Calculate the amount of memory needed for the input and
  1040. // output buffers in threaded mode.
  1041. //
  1042. // These cannot overflow because we already checked that
  1043. // the sizes are small enough using is_direct_mode_needed().
  1044. coder->mem_next_in = comp_blk_size(coder);
  1045. const uint64_t mem_buffers = coder->mem_next_in
  1046. + lzma_outq_outbuf_memusage(
  1047. coder->block_options.uncompressed_size);
  1048. // Add the amount needed by the filters.
  1049. // Avoid integer overflows.
  1050. if (UINT64_MAX - mem_buffers < coder->mem_next_filters) {
  1051. // Use direct mode if the memusage would overflow.
  1052. // This is a theoretical case that shouldn't happen
  1053. // in practice unless the input file is weird (broken
  1054. // or malicious).
  1055. coder->sequence = SEQ_BLOCK_DIRECT_INIT;
  1056. break;
  1057. }
  1058. // Amount of memory needed to decode this Block in
  1059. // threaded mode:
  1060. coder->mem_next_block = coder->mem_next_filters + mem_buffers;
  1061. // If this alone would exceed memlimit_threading, then we must
  1062. // use the single-threaded direct mode.
  1063. if (coder->mem_next_block > coder->memlimit_threading) {
  1064. coder->sequence = SEQ_BLOCK_DIRECT_INIT;
  1065. break;
  1066. }
  1067. // Use the threaded mode. Free the direct mode decoder in
  1068. // case it has been initialized.
  1069. lzma_next_end(&coder->block_decoder, allocator);
  1070. coder->mem_direct_mode = 0;
  1071. // Since we already know what the sizes are supposed to be,
  1072. // we can already add them to the Index hash. The Block
  1073. // decoder will verify the values while decoding.
  1074. const lzma_ret ret = lzma_index_hash_append(coder->index_hash,
  1075. lzma_block_unpadded_size(
  1076. &coder->block_options),
  1077. coder->block_options.uncompressed_size);
  1078. if (ret != LZMA_OK) {
  1079. coder->pending_error = ret;
  1080. coder->sequence = SEQ_ERROR;
  1081. break;
  1082. }
  1083. coder->sequence = SEQ_BLOCK_THR_INIT;
  1084. }
  1085. // Fall through
  1086. case SEQ_BLOCK_THR_INIT: {
  1087. // We need to wait for a multiple conditions to become true
  1088. // until we can initialize the Block decoder and let a worker
  1089. // thread decode it:
  1090. //
  1091. // - Wait for the memory usage of the active threads to drop
  1092. // so that starting the decoding of this Block won't make
  1093. // us go over memlimit_threading.
  1094. //
  1095. // - Wait for at least one free output queue slot.
  1096. //
  1097. // - Wait for a free worker thread.
  1098. //
  1099. // While we wait, we must copy decompressed data to the out
  1100. // buffer and catch possible decoder errors.
  1101. //
  1102. // read_output_and_wait() does all the above.
  1103. bool block_can_start = false;
  1104. return_if_error(read_output_and_wait(coder, allocator,
  1105. out, out_pos, out_size,
  1106. &block_can_start, true,
  1107. &wait_abs, &has_blocked));
  1108. if (coder->pending_error != LZMA_OK) {
  1109. coder->sequence = SEQ_ERROR;
  1110. break;
  1111. }
  1112. if (!block_can_start) {
  1113. // It's not a timeout because return_if_error handles
  1114. // it already. Output queue cannot be empty either
  1115. // because in that case block_can_start would have
  1116. // been true. Thus the output buffer must be full and
  1117. // the queue isn't empty.
  1118. assert(*out_pos == out_size);
  1119. assert(!lzma_outq_is_empty(&coder->outq));
  1120. return LZMA_OK;
  1121. }
  1122. // We know that we can start decoding this Block without
  1123. // exceeding memlimit_threading. However, to stay below
  1124. // memlimit_threading may require freeing some of the
  1125. // cached memory.
  1126. //
  1127. // Get a local copy of variables that require locking the
  1128. // mutex. It is fine if the worker threads modify the real
  1129. // values after we read these as those changes can only be
  1130. // towards more favorable conditions (less memory in use,
  1131. // more in cache).
  1132. //
  1133. // These are initialized to silence warnings.
  1134. uint64_t mem_in_use = 0;
  1135. uint64_t mem_cached = 0;
  1136. struct worker_thread *thr = NULL;
  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 subtract
  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 subtracted 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. }