xref: /freebsd/contrib/xz/src/liblzma/common/stream_decoder_mt.c (revision 3b35e7ee8de9b0260149a2b77e87a2b9c7a36244)
1*3b35e7eeSXin LI // SPDX-License-Identifier: 0BSD
2*3b35e7eeSXin LI 
373ed8e77SXin LI ///////////////////////////////////////////////////////////////////////////////
473ed8e77SXin LI //
573ed8e77SXin LI /// \file       stream_decoder_mt.c
673ed8e77SXin LI /// \brief      Multithreaded .xz Stream decoder
773ed8e77SXin LI //
873ed8e77SXin LI //  Authors:    Sebastian Andrzej Siewior
973ed8e77SXin LI //              Lasse Collin
1073ed8e77SXin LI //
1173ed8e77SXin LI ///////////////////////////////////////////////////////////////////////////////
1273ed8e77SXin LI 
1373ed8e77SXin LI #include "common.h"
1473ed8e77SXin LI #include "block_decoder.h"
1573ed8e77SXin LI #include "stream_decoder.h"
1673ed8e77SXin LI #include "index.h"
1773ed8e77SXin LI #include "outqueue.h"
1873ed8e77SXin LI 
1973ed8e77SXin LI 
2073ed8e77SXin LI typedef enum {
2173ed8e77SXin LI 	/// Waiting for work.
2273ed8e77SXin LI 	/// Main thread may change this to THR_RUN or THR_EXIT.
2373ed8e77SXin LI 	THR_IDLE,
2473ed8e77SXin LI 
2573ed8e77SXin LI 	/// Decoding is in progress.
2673ed8e77SXin LI 	/// Main thread may change this to THR_STOP or THR_EXIT.
2773ed8e77SXin LI 	/// The worker thread may change this to THR_IDLE.
2873ed8e77SXin LI 	THR_RUN,
2973ed8e77SXin LI 
3073ed8e77SXin LI 	/// The main thread wants the thread to stop whatever it was doing
3173ed8e77SXin LI 	/// but not exit. Main thread may change this to THR_EXIT.
3273ed8e77SXin LI 	/// The worker thread may change this to THR_IDLE.
3373ed8e77SXin LI 	THR_STOP,
3473ed8e77SXin LI 
3573ed8e77SXin LI 	/// The main thread wants the thread to exit.
3673ed8e77SXin LI 	THR_EXIT,
3773ed8e77SXin LI 
3873ed8e77SXin LI } worker_state;
3973ed8e77SXin LI 
4073ed8e77SXin LI 
4173ed8e77SXin LI typedef enum {
4273ed8e77SXin LI 	/// Partial updates (storing of worker thread progress
4373ed8e77SXin LI 	/// to lzma_outbuf) are disabled.
4473ed8e77SXin LI 	PARTIAL_DISABLED,
4573ed8e77SXin LI 
4673ed8e77SXin LI 	/// Main thread requests partial updates to be enabled but
4773ed8e77SXin LI 	/// no partial update has been done by the worker thread yet.
4873ed8e77SXin LI 	///
4973ed8e77SXin LI 	/// Changing from PARTIAL_DISABLED to PARTIAL_START requires
5073ed8e77SXin LI 	/// use of the worker-thread mutex. Other transitions don't
5173ed8e77SXin LI 	/// need a mutex.
5273ed8e77SXin LI 	PARTIAL_START,
5373ed8e77SXin LI 
5473ed8e77SXin LI 	/// Partial updates are enabled and the worker thread has done
5573ed8e77SXin LI 	/// at least one partial update.
5673ed8e77SXin LI 	PARTIAL_ENABLED,
5773ed8e77SXin LI 
5873ed8e77SXin LI } partial_update_mode;
5973ed8e77SXin LI 
6073ed8e77SXin LI 
6173ed8e77SXin LI struct worker_thread {
6273ed8e77SXin LI 	/// Worker state is protected with our mutex.
6373ed8e77SXin LI 	worker_state state;
6473ed8e77SXin LI 
6573ed8e77SXin LI 	/// Input buffer that will contain the whole Block except Block Header.
6673ed8e77SXin LI 	uint8_t *in;
6773ed8e77SXin LI 
6873ed8e77SXin LI 	/// Amount of memory allocated for "in"
6973ed8e77SXin LI 	size_t in_size;
7073ed8e77SXin LI 
7173ed8e77SXin LI 	/// Number of bytes written to "in" by the main thread
7273ed8e77SXin LI 	size_t in_filled;
7373ed8e77SXin LI 
7473ed8e77SXin LI 	/// Number of bytes consumed from "in" by the worker thread.
7573ed8e77SXin LI 	size_t in_pos;
7673ed8e77SXin LI 
7773ed8e77SXin LI 	/// Amount of uncompressed data that has been decoded. This local
7873ed8e77SXin LI 	/// copy is needed because updating outbuf->pos requires locking
7973ed8e77SXin LI 	/// the main mutex (coder->mutex).
8073ed8e77SXin LI 	size_t out_pos;
8173ed8e77SXin LI 
8273ed8e77SXin LI 	/// Pointer to the main structure is needed to (1) lock the main
8373ed8e77SXin LI 	/// mutex (coder->mutex) when updating outbuf->pos and (2) when
8473ed8e77SXin LI 	/// putting this thread back to the stack of free threads.
8573ed8e77SXin LI 	struct lzma_stream_coder *coder;
8673ed8e77SXin LI 
8773ed8e77SXin LI 	/// The allocator is set by the main thread. Since a copy of the
8873ed8e77SXin LI 	/// pointer is kept here, the application must not change the
8973ed8e77SXin LI 	/// allocator before calling lzma_end().
9073ed8e77SXin LI 	const lzma_allocator *allocator;
9173ed8e77SXin LI 
9273ed8e77SXin LI 	/// Output queue buffer to which the uncompressed data is written.
9373ed8e77SXin LI 	lzma_outbuf *outbuf;
9473ed8e77SXin LI 
9573ed8e77SXin LI 	/// Amount of compressed data that has already been decompressed.
9673ed8e77SXin LI 	/// This is updated from in_pos when our mutex is locked.
9773ed8e77SXin LI 	/// This is size_t, not uint64_t, because per-thread progress
9873ed8e77SXin LI 	/// is limited to sizes of allocated buffers.
9973ed8e77SXin LI 	size_t progress_in;
10073ed8e77SXin LI 
10173ed8e77SXin LI 	/// Like progress_in but for uncompressed data.
10273ed8e77SXin LI 	size_t progress_out;
10373ed8e77SXin LI 
10473ed8e77SXin LI 	/// Updating outbuf->pos requires locking the main mutex
10573ed8e77SXin LI 	/// (coder->mutex). Since the main thread will only read output
10673ed8e77SXin LI 	/// from the oldest outbuf in the queue, only the worker thread
10773ed8e77SXin LI 	/// that is associated with the oldest outbuf needs to update its
10873ed8e77SXin LI 	/// outbuf->pos. This avoids useless mutex contention that would
10973ed8e77SXin LI 	/// happen if all worker threads were frequently locking the main
11073ed8e77SXin LI 	/// mutex to update their outbuf->pos.
11173ed8e77SXin LI 	///
11273ed8e77SXin LI 	/// Only when partial_update is something else than PARTIAL_DISABLED,
11373ed8e77SXin LI 	/// this worker thread will update outbuf->pos after each call to
11473ed8e77SXin LI 	/// the Block decoder.
11573ed8e77SXin LI 	partial_update_mode partial_update;
11673ed8e77SXin LI 
11773ed8e77SXin LI 	/// Block decoder
11873ed8e77SXin LI 	lzma_next_coder block_decoder;
11973ed8e77SXin LI 
12073ed8e77SXin LI 	/// Thread-specific Block options are needed because the Block
12173ed8e77SXin LI 	/// decoder modifies the struct given to it at initialization.
12273ed8e77SXin LI 	lzma_block block_options;
12373ed8e77SXin LI 
12473ed8e77SXin LI 	/// Filter chain memory usage
12573ed8e77SXin LI 	uint64_t mem_filters;
12673ed8e77SXin LI 
12773ed8e77SXin LI 	/// Next structure in the stack of free worker threads.
12873ed8e77SXin LI 	struct worker_thread *next;
12973ed8e77SXin LI 
13073ed8e77SXin LI 	mythread_mutex mutex;
13173ed8e77SXin LI 	mythread_cond cond;
13273ed8e77SXin LI 
13373ed8e77SXin LI 	/// The ID of this thread is used to join the thread
13473ed8e77SXin LI 	/// when it's not needed anymore.
13573ed8e77SXin LI 	mythread thread_id;
13673ed8e77SXin LI };
13773ed8e77SXin LI 
13873ed8e77SXin LI 
13973ed8e77SXin LI struct lzma_stream_coder {
14073ed8e77SXin LI 	enum {
14173ed8e77SXin LI 		SEQ_STREAM_HEADER,
14273ed8e77SXin LI 		SEQ_BLOCK_HEADER,
14373ed8e77SXin LI 		SEQ_BLOCK_INIT,
14473ed8e77SXin LI 		SEQ_BLOCK_THR_INIT,
14573ed8e77SXin LI 		SEQ_BLOCK_THR_RUN,
14673ed8e77SXin LI 		SEQ_BLOCK_DIRECT_INIT,
14773ed8e77SXin LI 		SEQ_BLOCK_DIRECT_RUN,
14873ed8e77SXin LI 		SEQ_INDEX_WAIT_OUTPUT,
14973ed8e77SXin LI 		SEQ_INDEX_DECODE,
15073ed8e77SXin LI 		SEQ_STREAM_FOOTER,
15173ed8e77SXin LI 		SEQ_STREAM_PADDING,
15273ed8e77SXin LI 		SEQ_ERROR,
15373ed8e77SXin LI 	} sequence;
15473ed8e77SXin LI 
15573ed8e77SXin LI 	/// Block decoder
15673ed8e77SXin LI 	lzma_next_coder block_decoder;
15773ed8e77SXin LI 
15873ed8e77SXin LI 	/// Every Block Header will be decoded into this structure.
15973ed8e77SXin LI 	/// This is also used to initialize a Block decoder when in
16073ed8e77SXin LI 	/// direct mode. In threaded mode, a thread-specific copy will
16173ed8e77SXin LI 	/// be made for decoder initialization because the Block decoder
16273ed8e77SXin LI 	/// will modify the structure given to it.
16373ed8e77SXin LI 	lzma_block block_options;
16473ed8e77SXin LI 
16573ed8e77SXin LI 	/// Buffer to hold a filter chain for Block Header decoding and
16673ed8e77SXin LI 	/// initialization. These are freed after successful Block decoder
16773ed8e77SXin LI 	/// initialization or at stream_decoder_mt_end(). The thread-specific
16873ed8e77SXin LI 	/// copy of block_options won't hold a pointer to filters[] after
16973ed8e77SXin LI 	/// initialization.
17073ed8e77SXin LI 	lzma_filter filters[LZMA_FILTERS_MAX + 1];
17173ed8e77SXin LI 
17273ed8e77SXin LI 	/// Stream Flags from Stream Header
17373ed8e77SXin LI 	lzma_stream_flags stream_flags;
17473ed8e77SXin LI 
17573ed8e77SXin LI 	/// Index is hashed so that it can be compared to the sizes of Blocks
17673ed8e77SXin LI 	/// with O(1) memory usage.
17773ed8e77SXin LI 	lzma_index_hash *index_hash;
17873ed8e77SXin LI 
17973ed8e77SXin LI 
18073ed8e77SXin LI 	/// Maximum wait time if cannot use all the input and cannot
18173ed8e77SXin LI 	/// fill the output buffer. This is in milliseconds.
18273ed8e77SXin LI 	uint32_t timeout;
18373ed8e77SXin LI 
18473ed8e77SXin LI 
18573ed8e77SXin LI 	/// Error code from a worker thread.
18673ed8e77SXin LI 	///
18773ed8e77SXin LI 	/// \note       Use mutex.
18873ed8e77SXin LI 	lzma_ret thread_error;
18973ed8e77SXin LI 
19073ed8e77SXin LI 	/// Error code to return after pending output has been copied out. If
19173ed8e77SXin LI 	/// set in read_output_and_wait(), this is a mirror of thread_error.
19273ed8e77SXin LI 	/// If set in stream_decode_mt() then it's, for example, error that
19373ed8e77SXin LI 	/// occurred when decoding Block Header.
19473ed8e77SXin LI 	lzma_ret pending_error;
19573ed8e77SXin LI 
19673ed8e77SXin LI 	/// Number of threads that will be created at maximum.
19773ed8e77SXin LI 	uint32_t threads_max;
19873ed8e77SXin LI 
19973ed8e77SXin LI 	/// Number of thread structures that have been initialized from
20073ed8e77SXin LI 	/// "threads", and thus the number of worker threads actually
20173ed8e77SXin LI 	/// created so far.
20273ed8e77SXin LI 	uint32_t threads_initialized;
20373ed8e77SXin LI 
20473ed8e77SXin LI 	/// Array of allocated thread-specific structures. When no threads
20573ed8e77SXin LI 	/// are in use (direct mode) this is NULL. In threaded mode this
20673ed8e77SXin LI 	/// points to an array of threads_max number of worker_thread structs.
20773ed8e77SXin LI 	struct worker_thread *threads;
20873ed8e77SXin LI 
20973ed8e77SXin LI 	/// Stack of free threads. When a thread finishes, it puts itself
21073ed8e77SXin LI 	/// back into this stack. This starts as empty because threads
21173ed8e77SXin LI 	/// are created only when actually needed.
21273ed8e77SXin LI 	///
21373ed8e77SXin LI 	/// \note       Use mutex.
21473ed8e77SXin LI 	struct worker_thread *threads_free;
21573ed8e77SXin LI 
21673ed8e77SXin LI 	/// The most recent worker thread to which the main thread writes
21773ed8e77SXin LI 	/// the new input from the application.
21873ed8e77SXin LI 	struct worker_thread *thr;
21973ed8e77SXin LI 
22073ed8e77SXin LI 	/// Output buffer queue for decompressed data from the worker threads
22173ed8e77SXin LI 	///
22273ed8e77SXin LI 	/// \note       Use mutex with operations that need it.
22373ed8e77SXin LI 	lzma_outq outq;
22473ed8e77SXin LI 
22573ed8e77SXin LI 	mythread_mutex mutex;
22673ed8e77SXin LI 	mythread_cond cond;
22773ed8e77SXin LI 
22873ed8e77SXin LI 
22973ed8e77SXin LI 	/// Memory usage that will not be exceeded in multi-threaded mode.
23073ed8e77SXin LI 	/// Single-threaded mode can exceed this even by a large amount.
23173ed8e77SXin LI 	uint64_t memlimit_threading;
23273ed8e77SXin LI 
23373ed8e77SXin LI 	/// Memory usage limit that should never be exceeded.
23473ed8e77SXin LI 	/// LZMA_MEMLIMIT_ERROR will be returned if decoding isn't possible
23573ed8e77SXin LI 	/// even in single-threaded mode without exceeding this limit.
23673ed8e77SXin LI 	uint64_t memlimit_stop;
23773ed8e77SXin LI 
23873ed8e77SXin LI 	/// Amount of memory in use by the direct mode decoder
23973ed8e77SXin LI 	/// (coder->block_decoder). In threaded mode this is 0.
24073ed8e77SXin LI 	uint64_t mem_direct_mode;
24173ed8e77SXin LI 
24273ed8e77SXin LI 	/// Amount of memory needed by the running worker threads.
24373ed8e77SXin LI 	/// This doesn't include the memory needed by the output buffer.
24473ed8e77SXin LI 	///
24573ed8e77SXin LI 	/// \note       Use mutex.
24673ed8e77SXin LI 	uint64_t mem_in_use;
24773ed8e77SXin LI 
24873ed8e77SXin LI 	/// Amount of memory used by the idle (cached) threads.
24973ed8e77SXin LI 	///
25073ed8e77SXin LI 	/// \note       Use mutex.
25173ed8e77SXin LI 	uint64_t mem_cached;
25273ed8e77SXin LI 
25373ed8e77SXin LI 
25473ed8e77SXin LI 	/// Amount of memory needed for the filter chain of the next Block.
25573ed8e77SXin LI 	uint64_t mem_next_filters;
25673ed8e77SXin LI 
25773ed8e77SXin LI 	/// Amount of memory needed for the thread-specific input buffer
25873ed8e77SXin LI 	/// for the next Block.
25973ed8e77SXin LI 	uint64_t mem_next_in;
26073ed8e77SXin LI 
26173ed8e77SXin LI 	/// Amount of memory actually needed to decode the next Block
26273ed8e77SXin LI 	/// in threaded mode. This is
26373ed8e77SXin LI 	/// mem_next_filters + mem_next_in + memory needed for lzma_outbuf.
26473ed8e77SXin LI 	uint64_t mem_next_block;
26573ed8e77SXin LI 
26673ed8e77SXin LI 
26773ed8e77SXin LI 	/// Amount of compressed data in Stream Header + Blocks that have
26873ed8e77SXin LI 	/// already been finished.
26973ed8e77SXin LI 	///
27073ed8e77SXin LI 	/// \note       Use mutex.
27173ed8e77SXin LI 	uint64_t progress_in;
27273ed8e77SXin LI 
27373ed8e77SXin LI 	/// Amount of uncompressed data in Blocks that have already
27473ed8e77SXin LI 	/// been finished.
27573ed8e77SXin LI 	///
27673ed8e77SXin LI 	/// \note       Use mutex.
27773ed8e77SXin LI 	uint64_t progress_out;
27873ed8e77SXin LI 
27973ed8e77SXin LI 
28073ed8e77SXin LI 	/// If true, LZMA_NO_CHECK is returned if the Stream has
28173ed8e77SXin LI 	/// no integrity check.
28273ed8e77SXin LI 	bool tell_no_check;
28373ed8e77SXin LI 
28473ed8e77SXin LI 	/// If true, LZMA_UNSUPPORTED_CHECK is returned if the Stream has
28573ed8e77SXin LI 	/// an integrity check that isn't supported by this liblzma build.
28673ed8e77SXin LI 	bool tell_unsupported_check;
28773ed8e77SXin LI 
28873ed8e77SXin LI 	/// If true, LZMA_GET_CHECK is returned after decoding Stream Header.
28973ed8e77SXin LI 	bool tell_any_check;
29073ed8e77SXin LI 
29173ed8e77SXin LI 	/// If true, we will tell the Block decoder to skip calculating
29273ed8e77SXin LI 	/// and verifying the integrity check.
29373ed8e77SXin LI 	bool ignore_check;
29473ed8e77SXin LI 
29573ed8e77SXin LI 	/// If true, we will decode concatenated Streams that possibly have
29673ed8e77SXin LI 	/// Stream Padding between or after them. LZMA_STREAM_END is returned
29773ed8e77SXin LI 	/// once the application isn't giving us any new input (LZMA_FINISH),
29873ed8e77SXin LI 	/// and we aren't in the middle of a Stream, and possible
29973ed8e77SXin LI 	/// Stream Padding is a multiple of four bytes.
30073ed8e77SXin LI 	bool concatenated;
30173ed8e77SXin LI 
30273ed8e77SXin LI 	/// If true, we will return any errors immediately instead of first
30373ed8e77SXin LI 	/// producing all output before the location of the error.
30473ed8e77SXin LI 	bool fail_fast;
30573ed8e77SXin LI 
30673ed8e77SXin LI 
30773ed8e77SXin LI 	/// When decoding concatenated Streams, this is true as long as we
30873ed8e77SXin LI 	/// are decoding the first Stream. This is needed to avoid misleading
30973ed8e77SXin LI 	/// LZMA_FORMAT_ERROR in case the later Streams don't have valid magic
31073ed8e77SXin LI 	/// bytes.
31173ed8e77SXin LI 	bool first_stream;
31273ed8e77SXin LI 
31373ed8e77SXin LI 	/// This is used to track if the previous call to stream_decode_mt()
31473ed8e77SXin LI 	/// had output space (*out_pos < out_size) and managed to fill the
31573ed8e77SXin LI 	/// output buffer (*out_pos == out_size). This may be set to true
31673ed8e77SXin LI 	/// in read_output_and_wait(). This is read and then reset to false
31773ed8e77SXin LI 	/// at the beginning of stream_decode_mt().
31873ed8e77SXin LI 	///
31973ed8e77SXin LI 	/// This is needed to support applications that call lzma_code() in
32073ed8e77SXin LI 	/// such a way that more input is provided only when lzma_code()
32173ed8e77SXin LI 	/// didn't fill the output buffer completely. Basically, this makes
32273ed8e77SXin LI 	/// it easier to convert such applications from single-threaded
32373ed8e77SXin LI 	/// decoder to multi-threaded decoder.
32473ed8e77SXin LI 	bool out_was_filled;
32573ed8e77SXin LI 
32673ed8e77SXin LI 	/// Write position in buffer[] and position in Stream Padding
32773ed8e77SXin LI 	size_t pos;
32873ed8e77SXin LI 
32973ed8e77SXin LI 	/// Buffer to hold Stream Header, Block Header, and Stream Footer.
33073ed8e77SXin LI 	/// Block Header has biggest maximum size.
33173ed8e77SXin LI 	uint8_t buffer[LZMA_BLOCK_HEADER_SIZE_MAX];
33273ed8e77SXin LI };
33373ed8e77SXin LI 
33473ed8e77SXin LI 
33573ed8e77SXin LI /// Enables updating of outbuf->pos. This is a callback function that is
33673ed8e77SXin LI /// used with lzma_outq_enable_partial_output().
33773ed8e77SXin LI static void
33873ed8e77SXin LI worker_enable_partial_update(void *thr_ptr)
33973ed8e77SXin LI {
34073ed8e77SXin LI 	struct worker_thread *thr = thr_ptr;
34173ed8e77SXin LI 
34273ed8e77SXin LI 	mythread_sync(thr->mutex) {
34373ed8e77SXin LI 		thr->partial_update = PARTIAL_START;
34473ed8e77SXin LI 		mythread_cond_signal(&thr->cond);
34573ed8e77SXin LI 	}
34673ed8e77SXin LI }
34773ed8e77SXin LI 
34873ed8e77SXin LI 
34973ed8e77SXin LI /// Things do to at THR_STOP or when finishing a Block.
35073ed8e77SXin LI /// This is called with thr->mutex locked.
35173ed8e77SXin LI static void
35273ed8e77SXin LI worker_stop(struct worker_thread *thr)
35373ed8e77SXin LI {
35473ed8e77SXin LI 	// Update memory usage counters.
35573ed8e77SXin LI 	thr->coder->mem_in_use -= thr->in_size;
35673ed8e77SXin LI 	thr->in_size = 0; // thr->in was freed above.
35773ed8e77SXin LI 
35873ed8e77SXin LI 	thr->coder->mem_in_use -= thr->mem_filters;
35973ed8e77SXin LI 	thr->coder->mem_cached += thr->mem_filters;
36073ed8e77SXin LI 
36173ed8e77SXin LI 	// Put this thread to the stack of free threads.
36273ed8e77SXin LI 	thr->next = thr->coder->threads_free;
36373ed8e77SXin LI 	thr->coder->threads_free = thr;
36473ed8e77SXin LI 
36573ed8e77SXin LI 	mythread_cond_signal(&thr->coder->cond);
36673ed8e77SXin LI 	return;
36773ed8e77SXin LI }
36873ed8e77SXin LI 
36973ed8e77SXin LI 
37073ed8e77SXin LI static MYTHREAD_RET_TYPE
37173ed8e77SXin LI worker_decoder(void *thr_ptr)
37273ed8e77SXin LI {
37373ed8e77SXin LI 	struct worker_thread *thr = thr_ptr;
37473ed8e77SXin LI 	size_t in_filled;
37573ed8e77SXin LI 	partial_update_mode partial_update;
37673ed8e77SXin LI 	lzma_ret ret;
37773ed8e77SXin LI 
37873ed8e77SXin LI next_loop_lock:
37973ed8e77SXin LI 
38073ed8e77SXin LI 	mythread_mutex_lock(&thr->mutex);
38173ed8e77SXin LI next_loop_unlocked:
38273ed8e77SXin LI 
38373ed8e77SXin LI 	if (thr->state == THR_IDLE) {
38473ed8e77SXin LI 		mythread_cond_wait(&thr->cond, &thr->mutex);
38573ed8e77SXin LI 		goto next_loop_unlocked;
38673ed8e77SXin LI 	}
38773ed8e77SXin LI 
38873ed8e77SXin LI 	if (thr->state == THR_EXIT) {
38973ed8e77SXin LI 		mythread_mutex_unlock(&thr->mutex);
39073ed8e77SXin LI 
39173ed8e77SXin LI 		lzma_free(thr->in, thr->allocator);
39273ed8e77SXin LI 		lzma_next_end(&thr->block_decoder, thr->allocator);
39373ed8e77SXin LI 
39473ed8e77SXin LI 		mythread_mutex_destroy(&thr->mutex);
39573ed8e77SXin LI 		mythread_cond_destroy(&thr->cond);
39673ed8e77SXin LI 
39773ed8e77SXin LI 		return MYTHREAD_RET_VALUE;
39873ed8e77SXin LI 	}
39973ed8e77SXin LI 
40073ed8e77SXin LI 	if (thr->state == THR_STOP) {
40173ed8e77SXin LI 		thr->state = THR_IDLE;
40273ed8e77SXin LI 		mythread_mutex_unlock(&thr->mutex);
40373ed8e77SXin LI 
40473ed8e77SXin LI 		mythread_sync(thr->coder->mutex) {
40573ed8e77SXin LI 			worker_stop(thr);
40673ed8e77SXin LI 		}
40773ed8e77SXin LI 
40873ed8e77SXin LI 		goto next_loop_lock;
40973ed8e77SXin LI 	}
41073ed8e77SXin LI 
41173ed8e77SXin LI 	assert(thr->state == THR_RUN);
41273ed8e77SXin LI 
41373ed8e77SXin LI 	// Update progress info for get_progress().
41473ed8e77SXin LI 	thr->progress_in = thr->in_pos;
41573ed8e77SXin LI 	thr->progress_out = thr->out_pos;
41673ed8e77SXin LI 
41773ed8e77SXin LI 	// If we don't have any new input, wait for a signal from the main
41873ed8e77SXin LI 	// thread except if partial output has just been enabled. In that
41973ed8e77SXin LI 	// case we will do one normal run so that the partial output info
42073ed8e77SXin LI 	// gets passed to the main thread. The call to block_decoder.code()
42173ed8e77SXin LI 	// is useless but harmless as it can occur only once per Block.
42273ed8e77SXin LI 	in_filled = thr->in_filled;
42373ed8e77SXin LI 	partial_update = thr->partial_update;
42473ed8e77SXin LI 
42573ed8e77SXin LI 	if (in_filled == thr->in_pos && partial_update != PARTIAL_START) {
42673ed8e77SXin LI 		mythread_cond_wait(&thr->cond, &thr->mutex);
42773ed8e77SXin LI 		goto next_loop_unlocked;
42873ed8e77SXin LI 	}
42973ed8e77SXin LI 
43073ed8e77SXin LI 	mythread_mutex_unlock(&thr->mutex);
43173ed8e77SXin LI 
43273ed8e77SXin LI 	// Pass the input in small chunks to the Block decoder.
43373ed8e77SXin LI 	// This way we react reasonably fast if we are told to stop/exit,
43473ed8e77SXin LI 	// and (when partial update is enabled) we tell about our progress
43573ed8e77SXin LI 	// to the main thread frequently enough.
43673ed8e77SXin LI 	const size_t chunk_size = 16384;
43773ed8e77SXin LI 	if ((in_filled - thr->in_pos) > chunk_size)
43873ed8e77SXin LI 		in_filled = thr->in_pos + chunk_size;
43973ed8e77SXin LI 
44073ed8e77SXin LI 	ret = thr->block_decoder.code(
44173ed8e77SXin LI 			thr->block_decoder.coder, thr->allocator,
44273ed8e77SXin LI 			thr->in, &thr->in_pos, in_filled,
44373ed8e77SXin LI 			thr->outbuf->buf, &thr->out_pos,
44473ed8e77SXin LI 			thr->outbuf->allocated, LZMA_RUN);
44573ed8e77SXin LI 
44673ed8e77SXin LI 	if (ret == LZMA_OK) {
44773ed8e77SXin LI 		if (partial_update != PARTIAL_DISABLED) {
44873ed8e77SXin LI 			// The main thread uses thr->mutex to change from
44973ed8e77SXin LI 			// PARTIAL_DISABLED to PARTIAL_START. The main thread
45073ed8e77SXin LI 			// doesn't care about this variable after that so we
45173ed8e77SXin LI 			// can safely change it here to PARTIAL_ENABLED
45273ed8e77SXin LI 			// without a mutex.
45373ed8e77SXin LI 			thr->partial_update = PARTIAL_ENABLED;
45473ed8e77SXin LI 
45573ed8e77SXin LI 			// The main thread is reading decompressed data
45673ed8e77SXin LI 			// from thr->outbuf. Tell the main thread about
45773ed8e77SXin LI 			// our progress.
45873ed8e77SXin LI 			//
45973ed8e77SXin LI 			// NOTE: It's possible that we consumed input without
46073ed8e77SXin LI 			// producing any new output so it's possible that
46173ed8e77SXin LI 			// only in_pos has changed. In case of PARTIAL_START
46273ed8e77SXin LI 			// it is possible that neither in_pos nor out_pos has
46373ed8e77SXin LI 			// changed.
46473ed8e77SXin LI 			mythread_sync(thr->coder->mutex) {
46573ed8e77SXin LI 				thr->outbuf->pos = thr->out_pos;
46673ed8e77SXin LI 				thr->outbuf->decoder_in_pos = thr->in_pos;
46773ed8e77SXin LI 				mythread_cond_signal(&thr->coder->cond);
46873ed8e77SXin LI 			}
46973ed8e77SXin LI 		}
47073ed8e77SXin LI 
47173ed8e77SXin LI 		goto next_loop_lock;
47273ed8e77SXin LI 	}
47373ed8e77SXin LI 
47473ed8e77SXin LI 	// Either we finished successfully (LZMA_STREAM_END) or an error
47573ed8e77SXin LI 	// occurred. Both cases are handled almost identically. The error
47673ed8e77SXin LI 	// case requires updating thr->coder->thread_error.
47773ed8e77SXin LI 	//
47873ed8e77SXin LI 	// The sizes are in the Block Header and the Block decoder
47973ed8e77SXin LI 	// checks that they match, thus we know these:
48073ed8e77SXin LI 	assert(ret != LZMA_STREAM_END || thr->in_pos == thr->in_size);
48173ed8e77SXin LI 	assert(ret != LZMA_STREAM_END
48273ed8e77SXin LI 		|| thr->out_pos == thr->block_options.uncompressed_size);
48373ed8e77SXin LI 
48473ed8e77SXin LI 	// Free the input buffer. Don't update in_size as we need
48573ed8e77SXin LI 	// it later to update thr->coder->mem_in_use.
48673ed8e77SXin LI 	lzma_free(thr->in, thr->allocator);
48773ed8e77SXin LI 	thr->in = NULL;
48873ed8e77SXin LI 
48973ed8e77SXin LI 	mythread_sync(thr->mutex) {
49073ed8e77SXin LI 		if (thr->state != THR_EXIT)
49173ed8e77SXin LI 			thr->state = THR_IDLE;
49273ed8e77SXin LI 	}
49373ed8e77SXin LI 
49473ed8e77SXin LI 	mythread_sync(thr->coder->mutex) {
49573ed8e77SXin LI 		// Move our progress info to the main thread.
49673ed8e77SXin LI 		thr->coder->progress_in += thr->in_pos;
49773ed8e77SXin LI 		thr->coder->progress_out += thr->out_pos;
49873ed8e77SXin LI 		thr->progress_in = 0;
49973ed8e77SXin LI 		thr->progress_out = 0;
50073ed8e77SXin LI 
50173ed8e77SXin LI 		// Mark the outbuf as finished.
50273ed8e77SXin LI 		thr->outbuf->pos = thr->out_pos;
50373ed8e77SXin LI 		thr->outbuf->decoder_in_pos = thr->in_pos;
50473ed8e77SXin LI 		thr->outbuf->finished = true;
50573ed8e77SXin LI 		thr->outbuf->finish_ret = ret;
50673ed8e77SXin LI 		thr->outbuf = NULL;
50773ed8e77SXin LI 
50873ed8e77SXin LI 		// If an error occurred, tell it to the main thread.
50973ed8e77SXin LI 		if (ret != LZMA_STREAM_END
51073ed8e77SXin LI 				&& thr->coder->thread_error == LZMA_OK)
51173ed8e77SXin LI 			thr->coder->thread_error = ret;
51273ed8e77SXin LI 
51373ed8e77SXin LI 		worker_stop(thr);
51473ed8e77SXin LI 	}
51573ed8e77SXin LI 
51673ed8e77SXin LI 	goto next_loop_lock;
51773ed8e77SXin LI }
51873ed8e77SXin LI 
51973ed8e77SXin LI 
52073ed8e77SXin LI /// Tells the worker threads to exit and waits for them to terminate.
52173ed8e77SXin LI static void
52273ed8e77SXin LI threads_end(struct lzma_stream_coder *coder, const lzma_allocator *allocator)
52373ed8e77SXin LI {
52473ed8e77SXin LI 	for (uint32_t i = 0; i < coder->threads_initialized; ++i) {
52573ed8e77SXin LI 		mythread_sync(coder->threads[i].mutex) {
52673ed8e77SXin LI 			coder->threads[i].state = THR_EXIT;
52773ed8e77SXin LI 			mythread_cond_signal(&coder->threads[i].cond);
52873ed8e77SXin LI 		}
52973ed8e77SXin LI 	}
53073ed8e77SXin LI 
53173ed8e77SXin LI 	for (uint32_t i = 0; i < coder->threads_initialized; ++i)
53273ed8e77SXin LI 		mythread_join(coder->threads[i].thread_id);
53373ed8e77SXin LI 
53473ed8e77SXin LI 	lzma_free(coder->threads, allocator);
53573ed8e77SXin LI 	coder->threads_initialized = 0;
53673ed8e77SXin LI 	coder->threads = NULL;
53773ed8e77SXin LI 	coder->threads_free = NULL;
53873ed8e77SXin LI 
53973ed8e77SXin LI 	// The threads don't update these when they exit. Do it here.
54073ed8e77SXin LI 	coder->mem_in_use = 0;
54173ed8e77SXin LI 	coder->mem_cached = 0;
54273ed8e77SXin LI 
54373ed8e77SXin LI 	return;
54473ed8e77SXin LI }
54573ed8e77SXin LI 
54673ed8e77SXin LI 
54773ed8e77SXin LI static void
54873ed8e77SXin LI threads_stop(struct lzma_stream_coder *coder)
54973ed8e77SXin LI {
55073ed8e77SXin LI 	for (uint32_t i = 0; i < coder->threads_initialized; ++i) {
55173ed8e77SXin LI 		mythread_sync(coder->threads[i].mutex) {
55273ed8e77SXin LI 			// The state must be changed conditionally because
55373ed8e77SXin LI 			// THR_IDLE -> THR_STOP is not a valid state change.
55473ed8e77SXin LI 			if (coder->threads[i].state != THR_IDLE) {
55573ed8e77SXin LI 				coder->threads[i].state = THR_STOP;
55673ed8e77SXin LI 				mythread_cond_signal(&coder->threads[i].cond);
55773ed8e77SXin LI 			}
55873ed8e77SXin LI 		}
55973ed8e77SXin LI 	}
56073ed8e77SXin LI 
56173ed8e77SXin LI 	return;
56273ed8e77SXin LI }
56373ed8e77SXin LI 
56473ed8e77SXin LI 
56573ed8e77SXin LI /// Initialize a new worker_thread structure and create a new thread.
56673ed8e77SXin LI static lzma_ret
56773ed8e77SXin LI initialize_new_thread(struct lzma_stream_coder *coder,
56873ed8e77SXin LI 		const lzma_allocator *allocator)
56973ed8e77SXin LI {
57073ed8e77SXin LI 	// Allocate the coder->threads array if needed. It's done here instead
57173ed8e77SXin LI 	// of when initializing the decoder because we don't need this if we
57273ed8e77SXin LI 	// use the direct mode (we may even free coder->threads in the middle
57373ed8e77SXin LI 	// of the file if we switch from threaded to direct mode).
57473ed8e77SXin LI 	if (coder->threads == NULL) {
57573ed8e77SXin LI 		coder->threads = lzma_alloc(
57673ed8e77SXin LI 			coder->threads_max * sizeof(struct worker_thread),
57773ed8e77SXin LI 			allocator);
57873ed8e77SXin LI 
57973ed8e77SXin LI 		if (coder->threads == NULL)
58073ed8e77SXin LI 			return LZMA_MEM_ERROR;
58173ed8e77SXin LI 	}
58273ed8e77SXin LI 
58373ed8e77SXin LI 	// Pick a free structure.
58473ed8e77SXin LI 	assert(coder->threads_initialized < coder->threads_max);
58573ed8e77SXin LI 	struct worker_thread *thr
58673ed8e77SXin LI 			= &coder->threads[coder->threads_initialized];
58773ed8e77SXin LI 
58873ed8e77SXin LI 	if (mythread_mutex_init(&thr->mutex))
58973ed8e77SXin LI 		goto error_mutex;
59073ed8e77SXin LI 
59173ed8e77SXin LI 	if (mythread_cond_init(&thr->cond))
59273ed8e77SXin LI 		goto error_cond;
59373ed8e77SXin LI 
59473ed8e77SXin LI 	thr->state = THR_IDLE;
59573ed8e77SXin LI 	thr->in = NULL;
59673ed8e77SXin LI 	thr->in_size = 0;
59773ed8e77SXin LI 	thr->allocator = allocator;
59873ed8e77SXin LI 	thr->coder = coder;
59973ed8e77SXin LI 	thr->outbuf = NULL;
60073ed8e77SXin LI 	thr->block_decoder = LZMA_NEXT_CODER_INIT;
60173ed8e77SXin LI 	thr->mem_filters = 0;
60273ed8e77SXin LI 
60373ed8e77SXin LI 	if (mythread_create(&thr->thread_id, worker_decoder, thr))
60473ed8e77SXin LI 		goto error_thread;
60573ed8e77SXin LI 
60673ed8e77SXin LI 	++coder->threads_initialized;
60773ed8e77SXin LI 	coder->thr = thr;
60873ed8e77SXin LI 
60973ed8e77SXin LI 	return LZMA_OK;
61073ed8e77SXin LI 
61173ed8e77SXin LI error_thread:
61273ed8e77SXin LI 	mythread_cond_destroy(&thr->cond);
61373ed8e77SXin LI 
61473ed8e77SXin LI error_cond:
61573ed8e77SXin LI 	mythread_mutex_destroy(&thr->mutex);
61673ed8e77SXin LI 
61773ed8e77SXin LI error_mutex:
61873ed8e77SXin LI 	return LZMA_MEM_ERROR;
61973ed8e77SXin LI }
62073ed8e77SXin LI 
62173ed8e77SXin LI 
62273ed8e77SXin LI static lzma_ret
62373ed8e77SXin LI get_thread(struct lzma_stream_coder *coder, const lzma_allocator *allocator)
62473ed8e77SXin LI {
62573ed8e77SXin LI 	// If there is a free structure on the stack, use it.
62673ed8e77SXin LI 	mythread_sync(coder->mutex) {
62773ed8e77SXin LI 		if (coder->threads_free != NULL) {
62873ed8e77SXin LI 			coder->thr = coder->threads_free;
62973ed8e77SXin LI 			coder->threads_free = coder->threads_free->next;
63073ed8e77SXin LI 
6311f3ced26SXin LI 			// The thread is no longer in the cache so subtract
63273ed8e77SXin LI 			// it from the cached memory usage. Don't add it
63373ed8e77SXin LI 			// to mem_in_use though; the caller will handle it
63473ed8e77SXin LI 			// since it knows how much memory it will actually
63573ed8e77SXin LI 			// use (the filter chain might change).
63673ed8e77SXin LI 			coder->mem_cached -= coder->thr->mem_filters;
63773ed8e77SXin LI 		}
63873ed8e77SXin LI 	}
63973ed8e77SXin LI 
64073ed8e77SXin LI 	if (coder->thr == NULL) {
64173ed8e77SXin LI 		assert(coder->threads_initialized < coder->threads_max);
64273ed8e77SXin LI 
64373ed8e77SXin LI 		// Initialize a new thread.
64473ed8e77SXin LI 		return_if_error(initialize_new_thread(coder, allocator));
64573ed8e77SXin LI 	}
64673ed8e77SXin LI 
64773ed8e77SXin LI 	coder->thr->in_filled = 0;
64873ed8e77SXin LI 	coder->thr->in_pos = 0;
64973ed8e77SXin LI 	coder->thr->out_pos = 0;
65073ed8e77SXin LI 
65173ed8e77SXin LI 	coder->thr->progress_in = 0;
65273ed8e77SXin LI 	coder->thr->progress_out = 0;
65373ed8e77SXin LI 
65473ed8e77SXin LI 	coder->thr->partial_update = PARTIAL_DISABLED;
65573ed8e77SXin LI 
65673ed8e77SXin LI 	return LZMA_OK;
65773ed8e77SXin LI }
65873ed8e77SXin LI 
65973ed8e77SXin LI 
66073ed8e77SXin LI static lzma_ret
66173ed8e77SXin LI read_output_and_wait(struct lzma_stream_coder *coder,
66273ed8e77SXin LI 		const lzma_allocator *allocator,
66373ed8e77SXin LI 		uint8_t *restrict out, size_t *restrict out_pos,
66473ed8e77SXin LI 		size_t out_size,
66573ed8e77SXin LI 		bool *input_is_possible,
66673ed8e77SXin LI 		bool waiting_allowed,
66773ed8e77SXin LI 		mythread_condtime *wait_abs, bool *has_blocked)
66873ed8e77SXin LI {
66973ed8e77SXin LI 	lzma_ret ret = LZMA_OK;
67073ed8e77SXin LI 
67173ed8e77SXin LI 	mythread_sync(coder->mutex) {
67273ed8e77SXin LI 		do {
67373ed8e77SXin LI 			// Get as much output from the queue as is possible
67473ed8e77SXin LI 			// without blocking.
67573ed8e77SXin LI 			const size_t out_start = *out_pos;
67673ed8e77SXin LI 			do {
67773ed8e77SXin LI 				ret = lzma_outq_read(&coder->outq, allocator,
67873ed8e77SXin LI 						out, out_pos, out_size,
67973ed8e77SXin LI 						NULL, NULL);
68073ed8e77SXin LI 
68173ed8e77SXin LI 				// If a Block was finished, tell the worker
68273ed8e77SXin LI 				// thread of the next Block (if it is still
68373ed8e77SXin LI 				// running) to start telling the main thread
68473ed8e77SXin LI 				// when new output is available.
68573ed8e77SXin LI 				if (ret == LZMA_STREAM_END)
68673ed8e77SXin LI 					lzma_outq_enable_partial_output(
68773ed8e77SXin LI 						&coder->outq,
68873ed8e77SXin LI 						&worker_enable_partial_update);
68973ed8e77SXin LI 
69073ed8e77SXin LI 				// Loop until a Block wasn't finished.
69173ed8e77SXin LI 				// It's important to loop around even if
69273ed8e77SXin LI 				// *out_pos == out_size because there could
69373ed8e77SXin LI 				// be an empty Block that will return
69473ed8e77SXin LI 				// LZMA_STREAM_END without needing any
69573ed8e77SXin LI 				// output space.
69673ed8e77SXin LI 			} while (ret == LZMA_STREAM_END);
69773ed8e77SXin LI 
69873ed8e77SXin LI 			// Check if lzma_outq_read reported an error from
69973ed8e77SXin LI 			// the Block decoder.
70073ed8e77SXin LI 			if (ret != LZMA_OK)
70173ed8e77SXin LI 				break;
70273ed8e77SXin LI 
70373ed8e77SXin LI 			// If the output buffer is now full but it wasn't full
70473ed8e77SXin LI 			// when this function was called, set out_was_filled.
70573ed8e77SXin LI 			// This way the next call to stream_decode_mt() knows
70673ed8e77SXin LI 			// that some output was produced and no output space
70773ed8e77SXin LI 			// remained in the previous call to stream_decode_mt().
70873ed8e77SXin LI 			if (*out_pos == out_size && *out_pos != out_start)
70973ed8e77SXin LI 				coder->out_was_filled = true;
71073ed8e77SXin LI 
71173ed8e77SXin LI 			// Check if any thread has indicated an error.
71273ed8e77SXin LI 			if (coder->thread_error != LZMA_OK) {
71373ed8e77SXin LI 				// If LZMA_FAIL_FAST was used, report errors
71473ed8e77SXin LI 				// from worker threads immediately.
71573ed8e77SXin LI 				if (coder->fail_fast) {
71673ed8e77SXin LI 					ret = coder->thread_error;
71773ed8e77SXin LI 					break;
71873ed8e77SXin LI 				}
71973ed8e77SXin LI 
72073ed8e77SXin LI 				// Otherwise set pending_error. The value we
72173ed8e77SXin LI 				// set here will not actually get used other
72273ed8e77SXin LI 				// than working as a flag that an error has
72373ed8e77SXin LI 				// occurred. This is because in SEQ_ERROR
72473ed8e77SXin LI 				// all output before the error will be read
72573ed8e77SXin LI 				// first by calling this function, and once we
72673ed8e77SXin LI 				// reach the location of the (first) error the
72773ed8e77SXin LI 				// error code from the above lzma_outq_read()
72873ed8e77SXin LI 				// will be returned to the application.
72973ed8e77SXin LI 				//
73073ed8e77SXin LI 				// Use LZMA_PROG_ERROR since the value should
73173ed8e77SXin LI 				// never leak to the application. It's
73273ed8e77SXin LI 				// possible that pending_error has already
73373ed8e77SXin LI 				// been set but that doesn't matter: if we get
73473ed8e77SXin LI 				// here, pending_error only works as a flag.
73573ed8e77SXin LI 				coder->pending_error = LZMA_PROG_ERROR;
73673ed8e77SXin LI 			}
73773ed8e77SXin LI 
73873ed8e77SXin LI 			// Check if decoding of the next Block can be started.
73973ed8e77SXin LI 			// The memusage of the active threads must be low
74073ed8e77SXin LI 			// enough, there must be a free buffer slot in the
74173ed8e77SXin LI 			// output queue, and there must be a free thread
74273ed8e77SXin LI 			// (that can be either created or an existing one
74373ed8e77SXin LI 			// reused).
74473ed8e77SXin LI 			//
74573ed8e77SXin LI 			// NOTE: This is checked after reading the output
74673ed8e77SXin LI 			// above because reading the output can free a slot in
74773ed8e77SXin LI 			// the output queue and also reduce active memusage.
74873ed8e77SXin LI 			//
74973ed8e77SXin LI 			// NOTE: If output queue is empty, then input will
75073ed8e77SXin LI 			// always be possible.
75173ed8e77SXin LI 			if (input_is_possible != NULL
75273ed8e77SXin LI 					&& coder->memlimit_threading
75373ed8e77SXin LI 						- coder->mem_in_use
75473ed8e77SXin LI 						- coder->outq.mem_in_use
75573ed8e77SXin LI 						>= coder->mem_next_block
75673ed8e77SXin LI 					&& lzma_outq_has_buf(&coder->outq)
75773ed8e77SXin LI 					&& (coder->threads_initialized
75873ed8e77SXin LI 							< coder->threads_max
75973ed8e77SXin LI 						|| coder->threads_free
76073ed8e77SXin LI 							!= NULL)) {
76173ed8e77SXin LI 				*input_is_possible = true;
76273ed8e77SXin LI 				break;
76373ed8e77SXin LI 			}
76473ed8e77SXin LI 
76573ed8e77SXin LI 			// If the caller doesn't want us to block, return now.
76673ed8e77SXin LI 			if (!waiting_allowed)
76773ed8e77SXin LI 				break;
76873ed8e77SXin LI 
76973ed8e77SXin LI 			// This check is needed only when input_is_possible
77073ed8e77SXin LI 			// is NULL. We must return if we aren't waiting for
77173ed8e77SXin LI 			// input to become possible and there is no more
77273ed8e77SXin LI 			// output coming from the queue.
77373ed8e77SXin LI 			if (lzma_outq_is_empty(&coder->outq)) {
77473ed8e77SXin LI 				assert(input_is_possible == NULL);
77573ed8e77SXin LI 				break;
77673ed8e77SXin LI 			}
77773ed8e77SXin LI 
77873ed8e77SXin LI 			// If there is more data available from the queue,
77973ed8e77SXin LI 			// our out buffer must be full and we need to return
78073ed8e77SXin LI 			// so that the application can provide more output
78173ed8e77SXin LI 			// space.
78273ed8e77SXin LI 			//
78373ed8e77SXin LI 			// NOTE: In general lzma_outq_is_readable() can return
78473ed8e77SXin LI 			// true also when there are no more bytes available.
78573ed8e77SXin LI 			// This can happen when a Block has finished without
78673ed8e77SXin LI 			// providing any new output. We know that this is not
78773ed8e77SXin LI 			// the case because in the beginning of this loop we
78873ed8e77SXin LI 			// tried to read as much as possible even when we had
78973ed8e77SXin LI 			// no output space left and the mutex has been locked
79073ed8e77SXin LI 			// all the time (so worker threads cannot have changed
79173ed8e77SXin LI 			// anything). Thus there must be actual pending output
79273ed8e77SXin LI 			// in the queue.
79373ed8e77SXin LI 			if (lzma_outq_is_readable(&coder->outq)) {
79473ed8e77SXin LI 				assert(*out_pos == out_size);
79573ed8e77SXin LI 				break;
79673ed8e77SXin LI 			}
79773ed8e77SXin LI 
79873ed8e77SXin LI 			// If the application stops providing more input
79973ed8e77SXin LI 			// in the middle of a Block, there will eventually
80073ed8e77SXin LI 			// be one worker thread left that is stuck waiting for
80173ed8e77SXin LI 			// more input (that might never arrive) and a matching
80273ed8e77SXin LI 			// outbuf which the worker thread cannot finish due
80373ed8e77SXin LI 			// to lack of input. We must detect this situation,
80473ed8e77SXin LI 			// otherwise we would end up waiting indefinitely
80573ed8e77SXin LI 			// (if no timeout is in use) or keep returning
80673ed8e77SXin LI 			// LZMA_TIMED_OUT while making no progress. Thus, the
80773ed8e77SXin LI 			// application would never get LZMA_BUF_ERROR from
80873ed8e77SXin LI 			// lzma_code() which would tell the application that
80973ed8e77SXin LI 			// no more progress is possible. No LZMA_BUF_ERROR
81073ed8e77SXin LI 			// means that, for example, truncated .xz files could
81173ed8e77SXin LI 			// cause an infinite loop.
81273ed8e77SXin LI 			//
81373ed8e77SXin LI 			// A worker thread doing partial updates will
81473ed8e77SXin LI 			// store not only the output position in outbuf->pos
81573ed8e77SXin LI 			// but also the matching input position in
81673ed8e77SXin LI 			// outbuf->decoder_in_pos. Here we check if that
81773ed8e77SXin LI 			// input position matches the amount of input that
81873ed8e77SXin LI 			// the worker thread has been given (in_filled).
81973ed8e77SXin LI 			// If so, we must return and not wait as no more
82073ed8e77SXin LI 			// output will be coming without first getting more
82173ed8e77SXin LI 			// input to the worker thread. If the application
82273ed8e77SXin LI 			// keeps calling lzma_code() without providing more
82373ed8e77SXin LI 			// input, it will eventually get LZMA_BUF_ERROR.
82473ed8e77SXin LI 			//
82573ed8e77SXin LI 			// NOTE: We can read partial_update and in_filled
82673ed8e77SXin LI 			// without thr->mutex as only the main thread
82773ed8e77SXin LI 			// modifies these variables. decoder_in_pos requires
82873ed8e77SXin LI 			// coder->mutex which we are already holding.
82973ed8e77SXin LI 			if (coder->thr != NULL && coder->thr->partial_update
83073ed8e77SXin LI 					!= PARTIAL_DISABLED) {
83173ed8e77SXin LI 				// There is exactly one outbuf in the queue.
83273ed8e77SXin LI 				assert(coder->thr->outbuf == coder->outq.head);
83373ed8e77SXin LI 				assert(coder->thr->outbuf == coder->outq.tail);
83473ed8e77SXin LI 
83573ed8e77SXin LI 				if (coder->thr->outbuf->decoder_in_pos
83673ed8e77SXin LI 						== coder->thr->in_filled)
83773ed8e77SXin LI 					break;
83873ed8e77SXin LI 			}
83973ed8e77SXin LI 
84073ed8e77SXin LI 			// Wait for input or output to become possible.
84173ed8e77SXin LI 			if (coder->timeout != 0) {
84273ed8e77SXin LI 				// See the comment in stream_encoder_mt.c
84373ed8e77SXin LI 				// about why mythread_condtime_set() is used
84473ed8e77SXin LI 				// like this.
84573ed8e77SXin LI 				//
84673ed8e77SXin LI 				// FIXME?
84773ed8e77SXin LI 				// In contrast to the encoder, this calls
84873ed8e77SXin LI 				// _condtime_set while the mutex is locked.
84973ed8e77SXin LI 				if (!*has_blocked) {
85073ed8e77SXin LI 					*has_blocked = true;
85173ed8e77SXin LI 					mythread_condtime_set(wait_abs,
85273ed8e77SXin LI 							&coder->cond,
85373ed8e77SXin LI 							coder->timeout);
85473ed8e77SXin LI 				}
85573ed8e77SXin LI 
85673ed8e77SXin LI 				if (mythread_cond_timedwait(&coder->cond,
85773ed8e77SXin LI 						&coder->mutex,
85873ed8e77SXin LI 						wait_abs) != 0) {
85973ed8e77SXin LI 					ret = LZMA_TIMED_OUT;
86073ed8e77SXin LI 					break;
86173ed8e77SXin LI 				}
86273ed8e77SXin LI 			} else {
86373ed8e77SXin LI 				mythread_cond_wait(&coder->cond,
86473ed8e77SXin LI 						&coder->mutex);
86573ed8e77SXin LI 			}
86673ed8e77SXin LI 		} while (ret == LZMA_OK);
86773ed8e77SXin LI 	}
86873ed8e77SXin LI 
86973ed8e77SXin LI 	// If we are returning an error, then the application cannot get
87073ed8e77SXin LI 	// more output from us and thus keeping the threads running is
87173ed8e77SXin LI 	// useless and waste of CPU time.
87273ed8e77SXin LI 	if (ret != LZMA_OK && ret != LZMA_TIMED_OUT)
87373ed8e77SXin LI 		threads_stop(coder);
87473ed8e77SXin LI 
87573ed8e77SXin LI 	return ret;
87673ed8e77SXin LI }
87773ed8e77SXin LI 
87873ed8e77SXin LI 
87973ed8e77SXin LI static lzma_ret
88073ed8e77SXin LI decode_block_header(struct lzma_stream_coder *coder,
88173ed8e77SXin LI 		const lzma_allocator *allocator, const uint8_t *restrict in,
88273ed8e77SXin LI 		size_t *restrict in_pos, size_t in_size)
88373ed8e77SXin LI {
88473ed8e77SXin LI 	if (*in_pos >= in_size)
88573ed8e77SXin LI 		return LZMA_OK;
88673ed8e77SXin LI 
88773ed8e77SXin LI 	if (coder->pos == 0) {
88873ed8e77SXin LI 		// Detect if it's Index.
889047153b4SXin LI 		if (in[*in_pos] == INDEX_INDICATOR)
89073ed8e77SXin LI 			return LZMA_INDEX_DETECTED;
89173ed8e77SXin LI 
89273ed8e77SXin LI 		// Calculate the size of the Block Header. Note that
89373ed8e77SXin LI 		// Block Header decoder wants to see this byte too
89473ed8e77SXin LI 		// so don't advance *in_pos.
89573ed8e77SXin LI 		coder->block_options.header_size
89673ed8e77SXin LI 				= lzma_block_header_size_decode(
89773ed8e77SXin LI 					in[*in_pos]);
89873ed8e77SXin LI 	}
89973ed8e77SXin LI 
90073ed8e77SXin LI 	// Copy the Block Header to the internal buffer.
90173ed8e77SXin LI 	lzma_bufcpy(in, in_pos, in_size, coder->buffer, &coder->pos,
90273ed8e77SXin LI 			coder->block_options.header_size);
90373ed8e77SXin LI 
90473ed8e77SXin LI 	// Return if we didn't get the whole Block Header yet.
90573ed8e77SXin LI 	if (coder->pos < coder->block_options.header_size)
90673ed8e77SXin LI 		return LZMA_OK;
90773ed8e77SXin LI 
90873ed8e77SXin LI 	coder->pos = 0;
90973ed8e77SXin LI 
91073ed8e77SXin LI 	// Version 1 is needed to support the .ignore_check option.
91173ed8e77SXin LI 	coder->block_options.version = 1;
91273ed8e77SXin LI 
91373ed8e77SXin LI 	// Block Header decoder will initialize all members of this array
91473ed8e77SXin LI 	// so we don't need to do it here.
91573ed8e77SXin LI 	coder->block_options.filters = coder->filters;
91673ed8e77SXin LI 
91773ed8e77SXin LI 	// Decode the Block Header.
91873ed8e77SXin LI 	return_if_error(lzma_block_header_decode(&coder->block_options,
91973ed8e77SXin LI 			allocator, coder->buffer));
92073ed8e77SXin LI 
92173ed8e77SXin LI 	// If LZMA_IGNORE_CHECK was used, this flag needs to be set.
92273ed8e77SXin LI 	// It has to be set after lzma_block_header_decode() because
92373ed8e77SXin LI 	// it always resets this to false.
92473ed8e77SXin LI 	coder->block_options.ignore_check = coder->ignore_check;
92573ed8e77SXin LI 
92673ed8e77SXin LI 	// coder->block_options is ready now.
92773ed8e77SXin LI 	return LZMA_STREAM_END;
92873ed8e77SXin LI }
92973ed8e77SXin LI 
93073ed8e77SXin LI 
93173ed8e77SXin LI /// Get the size of the Compressed Data + Block Padding + Check.
93273ed8e77SXin LI static size_t
93373ed8e77SXin LI comp_blk_size(const struct lzma_stream_coder *coder)
93473ed8e77SXin LI {
93573ed8e77SXin LI 	return vli_ceil4(coder->block_options.compressed_size)
93673ed8e77SXin LI 			+ lzma_check_size(coder->stream_flags.check);
93773ed8e77SXin LI }
93873ed8e77SXin LI 
93973ed8e77SXin LI 
94073ed8e77SXin LI /// Returns true if the size (compressed or uncompressed) is such that
94173ed8e77SXin LI /// threaded decompression cannot be used. Sizes that are too big compared
94273ed8e77SXin LI /// to SIZE_MAX must be rejected to avoid integer overflows and truncations
94373ed8e77SXin LI /// when lzma_vli is assigned to a size_t.
94473ed8e77SXin LI static bool
94573ed8e77SXin LI is_direct_mode_needed(lzma_vli size)
94673ed8e77SXin LI {
94773ed8e77SXin LI 	return size == LZMA_VLI_UNKNOWN || size > SIZE_MAX / 3;
94873ed8e77SXin LI }
94973ed8e77SXin LI 
95073ed8e77SXin LI 
95173ed8e77SXin LI static lzma_ret
95273ed8e77SXin LI stream_decoder_reset(struct lzma_stream_coder *coder,
95373ed8e77SXin LI 		const lzma_allocator *allocator)
95473ed8e77SXin LI {
95573ed8e77SXin LI 	// Initialize the Index hash used to verify the Index.
95673ed8e77SXin LI 	coder->index_hash = lzma_index_hash_init(coder->index_hash, allocator);
95773ed8e77SXin LI 	if (coder->index_hash == NULL)
95873ed8e77SXin LI 		return LZMA_MEM_ERROR;
95973ed8e77SXin LI 
96073ed8e77SXin LI 	// Reset the rest of the variables.
96173ed8e77SXin LI 	coder->sequence = SEQ_STREAM_HEADER;
96273ed8e77SXin LI 	coder->pos = 0;
96373ed8e77SXin LI 
96473ed8e77SXin LI 	return LZMA_OK;
96573ed8e77SXin LI }
96673ed8e77SXin LI 
96773ed8e77SXin LI 
96873ed8e77SXin LI static lzma_ret
96973ed8e77SXin LI stream_decode_mt(void *coder_ptr, const lzma_allocator *allocator,
97073ed8e77SXin LI 		 const uint8_t *restrict in, size_t *restrict in_pos,
97173ed8e77SXin LI 		 size_t in_size,
97273ed8e77SXin LI 		 uint8_t *restrict out, size_t *restrict out_pos,
97373ed8e77SXin LI 		 size_t out_size, lzma_action action)
97473ed8e77SXin LI {
97573ed8e77SXin LI 	struct lzma_stream_coder *coder = coder_ptr;
97673ed8e77SXin LI 
97773ed8e77SXin LI 	mythread_condtime wait_abs;
97873ed8e77SXin LI 	bool has_blocked = false;
97973ed8e77SXin LI 
98073ed8e77SXin LI 	// Determine if in SEQ_BLOCK_HEADER and SEQ_BLOCK_THR_RUN we should
98173ed8e77SXin LI 	// tell read_output_and_wait() to wait until it can fill the output
98273ed8e77SXin LI 	// buffer (or a timeout occurs). Two conditions must be met:
98373ed8e77SXin LI 	//
98473ed8e77SXin LI 	// (1) If the caller provided no new input. The reason for this
98573ed8e77SXin LI 	//     can be, for example, the end of the file or that there is
98673ed8e77SXin LI 	//     a pause in the input stream and more input is available
98773ed8e77SXin LI 	//     a little later. In this situation we should wait for output
98873ed8e77SXin LI 	//     because otherwise we would end up in a busy-waiting loop where
98973ed8e77SXin LI 	//     we make no progress and the application just calls us again
99073ed8e77SXin LI 	//     without providing any new input. This would then result in
99173ed8e77SXin LI 	//     LZMA_BUF_ERROR even though more output would be available
99273ed8e77SXin LI 	//     once the worker threads decode more data.
99373ed8e77SXin LI 	//
99473ed8e77SXin LI 	// (2) Even if (1) is true, we will not wait if the previous call to
99573ed8e77SXin LI 	//     this function managed to produce some output and the output
99673ed8e77SXin LI 	//     buffer became full. This is for compatibility with applications
99773ed8e77SXin LI 	//     that call lzma_code() in such a way that new input is provided
99873ed8e77SXin LI 	//     only when the output buffer didn't become full. Without this
99973ed8e77SXin LI 	//     trick such applications would have bad performance (bad
100073ed8e77SXin LI 	//     parallelization due to decoder not getting input fast enough).
100173ed8e77SXin LI 	//
100273ed8e77SXin LI 	//     NOTE: Such loops might require that timeout is disabled (0)
100373ed8e77SXin LI 	//     if they assume that output-not-full implies that all input has
100473ed8e77SXin LI 	//     been consumed. If and only if timeout is enabled, we may return
100573ed8e77SXin LI 	//     when output isn't full *and* not all input has been consumed.
100673ed8e77SXin LI 	//
100773ed8e77SXin LI 	// However, if LZMA_FINISH is used, the above is ignored and we always
100873ed8e77SXin LI 	// wait (timeout can still cause us to return) because we know that
100973ed8e77SXin LI 	// we won't get any more input. This matters if the input file is
101073ed8e77SXin LI 	// truncated and we are doing single-shot decoding, that is,
101173ed8e77SXin LI 	// timeout = 0 and LZMA_FINISH is used on the first call to
101273ed8e77SXin LI 	// lzma_code() and the output buffer is known to be big enough
101373ed8e77SXin LI 	// to hold all uncompressed data:
101473ed8e77SXin LI 	//
101573ed8e77SXin LI 	//   - If LZMA_FINISH wasn't handled specially, we could return
101673ed8e77SXin LI 	//     LZMA_OK before providing all output that is possible with the
101773ed8e77SXin LI 	//     truncated input. The rest would be available if lzma_code() was
101873ed8e77SXin LI 	//     called again but then it's not single-shot decoding anymore.
101973ed8e77SXin LI 	//
102073ed8e77SXin LI 	//   - By handling LZMA_FINISH specially here, the first call will
102173ed8e77SXin LI 	//     produce all the output, matching the behavior of the
102273ed8e77SXin LI 	//     single-threaded decoder.
102373ed8e77SXin LI 	//
102473ed8e77SXin LI 	// So it's a very specific corner case but also easy to avoid. Note
102573ed8e77SXin LI 	// that this special handling of LZMA_FINISH has no effect for
102673ed8e77SXin LI 	// single-shot decoding when the input file is valid (not truncated);
102773ed8e77SXin LI 	// premature LZMA_OK wouldn't be possible as long as timeout = 0.
102873ed8e77SXin LI 	const bool waiting_allowed = action == LZMA_FINISH
102973ed8e77SXin LI 			|| (*in_pos == in_size && !coder->out_was_filled);
103073ed8e77SXin LI 	coder->out_was_filled = false;
103173ed8e77SXin LI 
103273ed8e77SXin LI 	while (true)
103373ed8e77SXin LI 	switch (coder->sequence) {
103473ed8e77SXin LI 	case SEQ_STREAM_HEADER: {
103573ed8e77SXin LI 		// Copy the Stream Header to the internal buffer.
103673ed8e77SXin LI 		const size_t in_old = *in_pos;
103773ed8e77SXin LI 		lzma_bufcpy(in, in_pos, in_size, coder->buffer, &coder->pos,
103873ed8e77SXin LI 				LZMA_STREAM_HEADER_SIZE);
103973ed8e77SXin LI 		coder->progress_in += *in_pos - in_old;
104073ed8e77SXin LI 
104173ed8e77SXin LI 		// Return if we didn't get the whole Stream Header yet.
104273ed8e77SXin LI 		if (coder->pos < LZMA_STREAM_HEADER_SIZE)
104373ed8e77SXin LI 			return LZMA_OK;
104473ed8e77SXin LI 
104573ed8e77SXin LI 		coder->pos = 0;
104673ed8e77SXin LI 
104773ed8e77SXin LI 		// Decode the Stream Header.
104873ed8e77SXin LI 		const lzma_ret ret = lzma_stream_header_decode(
104973ed8e77SXin LI 				&coder->stream_flags, coder->buffer);
105073ed8e77SXin LI 		if (ret != LZMA_OK)
105173ed8e77SXin LI 			return ret == LZMA_FORMAT_ERROR && !coder->first_stream
105273ed8e77SXin LI 					? LZMA_DATA_ERROR : ret;
105373ed8e77SXin LI 
105473ed8e77SXin LI 		// If we are decoding concatenated Streams, and the later
105573ed8e77SXin LI 		// Streams have invalid Header Magic Bytes, we give
105673ed8e77SXin LI 		// LZMA_DATA_ERROR instead of LZMA_FORMAT_ERROR.
105773ed8e77SXin LI 		coder->first_stream = false;
105873ed8e77SXin LI 
105973ed8e77SXin LI 		// Copy the type of the Check so that Block Header and Block
106073ed8e77SXin LI 		// decoders see it.
106173ed8e77SXin LI 		coder->block_options.check = coder->stream_flags.check;
106273ed8e77SXin LI 
106373ed8e77SXin LI 		// Even if we return LZMA_*_CHECK below, we want
106473ed8e77SXin LI 		// to continue from Block Header decoding.
106573ed8e77SXin LI 		coder->sequence = SEQ_BLOCK_HEADER;
106673ed8e77SXin LI 
106773ed8e77SXin LI 		// Detect if there's no integrity check or if it is
106873ed8e77SXin LI 		// unsupported if those were requested by the application.
106973ed8e77SXin LI 		if (coder->tell_no_check && coder->stream_flags.check
107073ed8e77SXin LI 				== LZMA_CHECK_NONE)
107173ed8e77SXin LI 			return LZMA_NO_CHECK;
107273ed8e77SXin LI 
107373ed8e77SXin LI 		if (coder->tell_unsupported_check
107473ed8e77SXin LI 				&& !lzma_check_is_supported(
107573ed8e77SXin LI 					coder->stream_flags.check))
107673ed8e77SXin LI 			return LZMA_UNSUPPORTED_CHECK;
107773ed8e77SXin LI 
107873ed8e77SXin LI 		if (coder->tell_any_check)
107973ed8e77SXin LI 			return LZMA_GET_CHECK;
108073ed8e77SXin LI 	}
108173ed8e77SXin LI 
108273ed8e77SXin LI 	// Fall through
108373ed8e77SXin LI 
108473ed8e77SXin LI 	case SEQ_BLOCK_HEADER: {
108573ed8e77SXin LI 		const size_t in_old = *in_pos;
108673ed8e77SXin LI 		const lzma_ret ret = decode_block_header(coder, allocator,
108773ed8e77SXin LI 				in, in_pos, in_size);
108873ed8e77SXin LI 		coder->progress_in += *in_pos - in_old;
108973ed8e77SXin LI 
109073ed8e77SXin LI 		if (ret == LZMA_OK) {
109173ed8e77SXin LI 			// We didn't decode the whole Block Header yet.
109273ed8e77SXin LI 			//
109373ed8e77SXin LI 			// Read output from the queue before returning. This
109473ed8e77SXin LI 			// is important because it is possible that the
109573ed8e77SXin LI 			// application doesn't have any new input available
109673ed8e77SXin LI 			// immediately. If we didn't try to copy output from
109773ed8e77SXin LI 			// the output queue here, lzma_code() could end up
109873ed8e77SXin LI 			// returning LZMA_BUF_ERROR even though queued output
109973ed8e77SXin LI 			// is available.
110073ed8e77SXin LI 			//
110173ed8e77SXin LI 			// If the lzma_code() call provided at least one input
110273ed8e77SXin LI 			// byte, only copy as much data from the output queue
110373ed8e77SXin LI 			// as is available immediately. This way the
110473ed8e77SXin LI 			// application will be able to provide more input
110573ed8e77SXin LI 			// without a delay.
110673ed8e77SXin LI 			//
110773ed8e77SXin LI 			// On the other hand, if lzma_code() was called with
110873ed8e77SXin LI 			// an empty input buffer(*), treat it specially: try
110973ed8e77SXin LI 			// to fill the output buffer even if it requires
111073ed8e77SXin LI 			// waiting for the worker threads to provide output
111173ed8e77SXin LI 			// (timeout, if specified, can still cause us to
111273ed8e77SXin LI 			// return).
111373ed8e77SXin LI 			//
111473ed8e77SXin LI 			//   - This way the application will be able to get all
111573ed8e77SXin LI 			//     data that can be decoded from the input provided
111673ed8e77SXin LI 			//     so far.
111773ed8e77SXin LI 			//
111873ed8e77SXin LI 			//   - We avoid both premature LZMA_BUF_ERROR and
111973ed8e77SXin LI 			//     busy-waiting where the application repeatedly
112073ed8e77SXin LI 			//     calls lzma_code() which immediately returns
112173ed8e77SXin LI 			//     LZMA_OK without providing new data.
112273ed8e77SXin LI 			//
112373ed8e77SXin LI 			//   - If the queue becomes empty, we won't wait
112473ed8e77SXin LI 			//     anything and will return LZMA_OK immediately
112573ed8e77SXin LI 			//     (coder->timeout is completely ignored).
112673ed8e77SXin LI 			//
112773ed8e77SXin LI 			// (*) See the comment at the beginning of this
112873ed8e77SXin LI 			//     function how waiting_allowed is determined
112973ed8e77SXin LI 			//     and why there is an exception to the rule
113073ed8e77SXin LI 			//     of "called with an empty input buffer".
113173ed8e77SXin LI 			assert(*in_pos == in_size);
113273ed8e77SXin LI 
113373ed8e77SXin LI 			// If LZMA_FINISH was used we know that we won't get
113473ed8e77SXin LI 			// more input, so the file must be truncated if we
113573ed8e77SXin LI 			// get here. If worker threads don't detect any
113673ed8e77SXin LI 			// errors, eventually there will be no more output
113773ed8e77SXin LI 			// while we keep returning LZMA_OK which gets
113873ed8e77SXin LI 			// converted to LZMA_BUF_ERROR in lzma_code().
113973ed8e77SXin LI 			//
114073ed8e77SXin LI 			// If fail-fast is enabled then we will return
114173ed8e77SXin LI 			// immediately using LZMA_DATA_ERROR instead of
114273ed8e77SXin LI 			// LZMA_OK or LZMA_BUF_ERROR. Rationale for the
114373ed8e77SXin LI 			// error code:
114473ed8e77SXin LI 			//
114573ed8e77SXin LI 			//   - Worker threads may have a large amount of
114673ed8e77SXin LI 			//     not-yet-decoded input data and we don't
114773ed8e77SXin LI 			//     know for sure if all data is valid. Bad
114873ed8e77SXin LI 			//     data there would result in LZMA_DATA_ERROR
114973ed8e77SXin LI 			//     when fail-fast isn't used.
115073ed8e77SXin LI 			//
115173ed8e77SXin LI 			//   - Immediate LZMA_BUF_ERROR would be a bit weird
115273ed8e77SXin LI 			//     considering the older liblzma code. lzma_code()
115373ed8e77SXin LI 			//     even has an assertion to prevent coders from
115473ed8e77SXin LI 			//     returning LZMA_BUF_ERROR directly.
115573ed8e77SXin LI 			//
115673ed8e77SXin LI 			// The downside of this is that with fail-fast apps
115773ed8e77SXin LI 			// cannot always distinguish between corrupt and
115873ed8e77SXin LI 			// truncated files.
115973ed8e77SXin LI 			if (action == LZMA_FINISH && coder->fail_fast) {
116073ed8e77SXin LI 				// We won't produce any more output. Stop
116173ed8e77SXin LI 				// the unfinished worker threads so they
116273ed8e77SXin LI 				// won't waste CPU time.
116373ed8e77SXin LI 				threads_stop(coder);
116473ed8e77SXin LI 				return LZMA_DATA_ERROR;
116573ed8e77SXin LI 			}
116673ed8e77SXin LI 
116773ed8e77SXin LI 			// read_output_and_wait() will call threads_stop()
116873ed8e77SXin LI 			// if needed so with that we can use return_if_error.
116973ed8e77SXin LI 			return_if_error(read_output_and_wait(coder, allocator,
117073ed8e77SXin LI 				out, out_pos, out_size,
117173ed8e77SXin LI 				NULL, waiting_allowed,
117273ed8e77SXin LI 				&wait_abs, &has_blocked));
117373ed8e77SXin LI 
117473ed8e77SXin LI 			if (coder->pending_error != LZMA_OK) {
117573ed8e77SXin LI 				coder->sequence = SEQ_ERROR;
117673ed8e77SXin LI 				break;
117773ed8e77SXin LI 			}
117873ed8e77SXin LI 
117973ed8e77SXin LI 			return LZMA_OK;
118073ed8e77SXin LI 		}
118173ed8e77SXin LI 
118273ed8e77SXin LI 		if (ret == LZMA_INDEX_DETECTED) {
118373ed8e77SXin LI 			coder->sequence = SEQ_INDEX_WAIT_OUTPUT;
118473ed8e77SXin LI 			break;
118573ed8e77SXin LI 		}
118673ed8e77SXin LI 
118773ed8e77SXin LI 		// See if an error occurred.
118873ed8e77SXin LI 		if (ret != LZMA_STREAM_END) {
118973ed8e77SXin LI 			// NOTE: Here and in all other places where
119073ed8e77SXin LI 			// pending_error is set, it may overwrite the value
119173ed8e77SXin LI 			// (LZMA_PROG_ERROR) set by read_output_and_wait().
119273ed8e77SXin LI 			// That function might overwrite value set here too.
119373ed8e77SXin LI 			// These are fine because when read_output_and_wait()
119473ed8e77SXin LI 			// sets pending_error, it actually works as a flag
119573ed8e77SXin LI 			// variable only ("some error has occurred") and the
119673ed8e77SXin LI 			// actual value of pending_error is not used in
119773ed8e77SXin LI 			// SEQ_ERROR. In such cases SEQ_ERROR will eventually
119873ed8e77SXin LI 			// get the correct error code from the return value of
119973ed8e77SXin LI 			// a later read_output_and_wait() call.
120073ed8e77SXin LI 			coder->pending_error = ret;
120173ed8e77SXin LI 			coder->sequence = SEQ_ERROR;
120273ed8e77SXin LI 			break;
120373ed8e77SXin LI 		}
120473ed8e77SXin LI 
120573ed8e77SXin LI 		// Calculate the memory usage of the filters / Block decoder.
120673ed8e77SXin LI 		coder->mem_next_filters = lzma_raw_decoder_memusage(
120773ed8e77SXin LI 				coder->filters);
120873ed8e77SXin LI 
120973ed8e77SXin LI 		if (coder->mem_next_filters == UINT64_MAX) {
121073ed8e77SXin LI 			// One or more unknown Filter IDs.
121173ed8e77SXin LI 			coder->pending_error = LZMA_OPTIONS_ERROR;
121273ed8e77SXin LI 			coder->sequence = SEQ_ERROR;
121373ed8e77SXin LI 			break;
121473ed8e77SXin LI 		}
121573ed8e77SXin LI 
121673ed8e77SXin LI 		coder->sequence = SEQ_BLOCK_INIT;
121773ed8e77SXin LI 	}
121873ed8e77SXin LI 
121973ed8e77SXin LI 	// Fall through
122073ed8e77SXin LI 
122173ed8e77SXin LI 	case SEQ_BLOCK_INIT: {
122273ed8e77SXin LI 		// Check if decoding is possible at all with the current
122373ed8e77SXin LI 		// memlimit_stop which we must never exceed.
122473ed8e77SXin LI 		//
122573ed8e77SXin LI 		// This needs to be the first thing in SEQ_BLOCK_INIT
122673ed8e77SXin LI 		// to make it possible to restart decoding after increasing
122773ed8e77SXin LI 		// memlimit_stop with lzma_memlimit_set().
122873ed8e77SXin LI 		if (coder->mem_next_filters > coder->memlimit_stop) {
122973ed8e77SXin LI 			// Flush pending output before returning
123073ed8e77SXin LI 			// LZMA_MEMLIMIT_ERROR. If the application doesn't
123173ed8e77SXin LI 			// want to increase the limit, at least it will get
123273ed8e77SXin LI 			// all the output possible so far.
123373ed8e77SXin LI 			return_if_error(read_output_and_wait(coder, allocator,
123473ed8e77SXin LI 					out, out_pos, out_size,
123573ed8e77SXin LI 					NULL, true, &wait_abs, &has_blocked));
123673ed8e77SXin LI 
123773ed8e77SXin LI 			if (!lzma_outq_is_empty(&coder->outq))
123873ed8e77SXin LI 				return LZMA_OK;
123973ed8e77SXin LI 
124073ed8e77SXin LI 			return LZMA_MEMLIMIT_ERROR;
124173ed8e77SXin LI 		}
124273ed8e77SXin LI 
124373ed8e77SXin LI 		// Check if the size information is available in Block Header.
124473ed8e77SXin LI 		// If it is, check if the sizes are small enough that we don't
124573ed8e77SXin LI 		// need to worry *too* much about integer overflows later in
124673ed8e77SXin LI 		// the code. If these conditions are not met, we must use the
124773ed8e77SXin LI 		// single-threaded direct mode.
124873ed8e77SXin LI 		if (is_direct_mode_needed(coder->block_options.compressed_size)
124973ed8e77SXin LI 				|| is_direct_mode_needed(
125073ed8e77SXin LI 				coder->block_options.uncompressed_size)) {
125173ed8e77SXin LI 			coder->sequence = SEQ_BLOCK_DIRECT_INIT;
125273ed8e77SXin LI 			break;
125373ed8e77SXin LI 		}
125473ed8e77SXin LI 
125573ed8e77SXin LI 		// Calculate the amount of memory needed for the input and
125673ed8e77SXin LI 		// output buffers in threaded mode.
125773ed8e77SXin LI 		//
125873ed8e77SXin LI 		// These cannot overflow because we already checked that
125973ed8e77SXin LI 		// the sizes are small enough using is_direct_mode_needed().
126073ed8e77SXin LI 		coder->mem_next_in = comp_blk_size(coder);
126173ed8e77SXin LI 		const uint64_t mem_buffers = coder->mem_next_in
126273ed8e77SXin LI 				+ lzma_outq_outbuf_memusage(
126373ed8e77SXin LI 				coder->block_options.uncompressed_size);
126473ed8e77SXin LI 
126573ed8e77SXin LI 		// Add the amount needed by the filters.
126673ed8e77SXin LI 		// Avoid integer overflows.
126773ed8e77SXin LI 		if (UINT64_MAX - mem_buffers < coder->mem_next_filters) {
126873ed8e77SXin LI 			// Use direct mode if the memusage would overflow.
126973ed8e77SXin LI 			// This is a theoretical case that shouldn't happen
127073ed8e77SXin LI 			// in practice unless the input file is weird (broken
127173ed8e77SXin LI 			// or malicious).
127273ed8e77SXin LI 			coder->sequence = SEQ_BLOCK_DIRECT_INIT;
127373ed8e77SXin LI 			break;
127473ed8e77SXin LI 		}
127573ed8e77SXin LI 
127673ed8e77SXin LI 		// Amount of memory needed to decode this Block in
127773ed8e77SXin LI 		// threaded mode:
127873ed8e77SXin LI 		coder->mem_next_block = coder->mem_next_filters + mem_buffers;
127973ed8e77SXin LI 
128073ed8e77SXin LI 		// If this alone would exceed memlimit_threading, then we must
128173ed8e77SXin LI 		// use the single-threaded direct mode.
128273ed8e77SXin LI 		if (coder->mem_next_block > coder->memlimit_threading) {
128373ed8e77SXin LI 			coder->sequence = SEQ_BLOCK_DIRECT_INIT;
128473ed8e77SXin LI 			break;
128573ed8e77SXin LI 		}
128673ed8e77SXin LI 
128773ed8e77SXin LI 		// Use the threaded mode. Free the direct mode decoder in
128873ed8e77SXin LI 		// case it has been initialized.
128973ed8e77SXin LI 		lzma_next_end(&coder->block_decoder, allocator);
129073ed8e77SXin LI 		coder->mem_direct_mode = 0;
129173ed8e77SXin LI 
129273ed8e77SXin LI 		// Since we already know what the sizes are supposed to be,
129373ed8e77SXin LI 		// we can already add them to the Index hash. The Block
129473ed8e77SXin LI 		// decoder will verify the values while decoding.
129573ed8e77SXin LI 		const lzma_ret ret = lzma_index_hash_append(coder->index_hash,
129673ed8e77SXin LI 				lzma_block_unpadded_size(
129773ed8e77SXin LI 					&coder->block_options),
129873ed8e77SXin LI 				coder->block_options.uncompressed_size);
129973ed8e77SXin LI 		if (ret != LZMA_OK) {
130073ed8e77SXin LI 			coder->pending_error = ret;
130173ed8e77SXin LI 			coder->sequence = SEQ_ERROR;
130273ed8e77SXin LI 			break;
130373ed8e77SXin LI 		}
130473ed8e77SXin LI 
130573ed8e77SXin LI 		coder->sequence = SEQ_BLOCK_THR_INIT;
130673ed8e77SXin LI 	}
130773ed8e77SXin LI 
130873ed8e77SXin LI 	// Fall through
130973ed8e77SXin LI 
131073ed8e77SXin LI 	case SEQ_BLOCK_THR_INIT: {
131173ed8e77SXin LI 		// We need to wait for a multiple conditions to become true
131273ed8e77SXin LI 		// until we can initialize the Block decoder and let a worker
131373ed8e77SXin LI 		// thread decode it:
131473ed8e77SXin LI 		//
131573ed8e77SXin LI 		//   - Wait for the memory usage of the active threads to drop
131673ed8e77SXin LI 		//     so that starting the decoding of this Block won't make
131773ed8e77SXin LI 		//     us go over memlimit_threading.
131873ed8e77SXin LI 		//
131973ed8e77SXin LI 		//   - Wait for at least one free output queue slot.
132073ed8e77SXin LI 		//
132173ed8e77SXin LI 		//   - Wait for a free worker thread.
132273ed8e77SXin LI 		//
132373ed8e77SXin LI 		// While we wait, we must copy decompressed data to the out
132473ed8e77SXin LI 		// buffer and catch possible decoder errors.
132573ed8e77SXin LI 		//
132673ed8e77SXin LI 		// read_output_and_wait() does all the above.
132773ed8e77SXin LI 		bool block_can_start = false;
132873ed8e77SXin LI 
132973ed8e77SXin LI 		return_if_error(read_output_and_wait(coder, allocator,
133073ed8e77SXin LI 				out, out_pos, out_size,
133173ed8e77SXin LI 				&block_can_start, true,
133273ed8e77SXin LI 				&wait_abs, &has_blocked));
133373ed8e77SXin LI 
133473ed8e77SXin LI 		if (coder->pending_error != LZMA_OK) {
133573ed8e77SXin LI 			coder->sequence = SEQ_ERROR;
133673ed8e77SXin LI 			break;
133773ed8e77SXin LI 		}
133873ed8e77SXin LI 
133973ed8e77SXin LI 		if (!block_can_start) {
134073ed8e77SXin LI 			// It's not a timeout because return_if_error handles
134173ed8e77SXin LI 			// it already. Output queue cannot be empty either
134273ed8e77SXin LI 			// because in that case block_can_start would have
134373ed8e77SXin LI 			// been true. Thus the output buffer must be full and
134473ed8e77SXin LI 			// the queue isn't empty.
134573ed8e77SXin LI 			assert(*out_pos == out_size);
134673ed8e77SXin LI 			assert(!lzma_outq_is_empty(&coder->outq));
134773ed8e77SXin LI 			return LZMA_OK;
134873ed8e77SXin LI 		}
134973ed8e77SXin LI 
135073ed8e77SXin LI 		// We know that we can start decoding this Block without
135173ed8e77SXin LI 		// exceeding memlimit_threading. However, to stay below
135273ed8e77SXin LI 		// memlimit_threading may require freeing some of the
135373ed8e77SXin LI 		// cached memory.
135473ed8e77SXin LI 		//
135573ed8e77SXin LI 		// Get a local copy of variables that require locking the
135673ed8e77SXin LI 		// mutex. It is fine if the worker threads modify the real
135773ed8e77SXin LI 		// values after we read these as those changes can only be
135873ed8e77SXin LI 		// towards more favorable conditions (less memory in use,
135973ed8e77SXin LI 		// more in cache).
1360c917796cSXin LI 		//
13611f3ced26SXin LI 		// These are initialized to silence warnings.
1362c917796cSXin LI 		uint64_t mem_in_use = 0;
1363c917796cSXin LI 		uint64_t mem_cached = 0;
1364c917796cSXin LI 		struct worker_thread *thr = NULL;
136573ed8e77SXin LI 
136673ed8e77SXin LI 		mythread_sync(coder->mutex) {
136773ed8e77SXin LI 			mem_in_use = coder->mem_in_use;
136873ed8e77SXin LI 			mem_cached = coder->mem_cached;
136973ed8e77SXin LI 			thr = coder->threads_free;
137073ed8e77SXin LI 		}
137173ed8e77SXin LI 
137273ed8e77SXin LI 		// The maximum amount of memory that can be held by other
137373ed8e77SXin LI 		// threads and cached buffers while allowing us to start
137473ed8e77SXin LI 		// decoding the next Block.
137573ed8e77SXin LI 		const uint64_t mem_max = coder->memlimit_threading
137673ed8e77SXin LI 				- coder->mem_next_block;
137773ed8e77SXin LI 
137873ed8e77SXin LI 		// If the existing allocations are so large that starting
137973ed8e77SXin LI 		// to decode this Block might exceed memlimit_threads,
138073ed8e77SXin LI 		// try to free memory from the output queue cache first.
138173ed8e77SXin LI 		//
138273ed8e77SXin LI 		// NOTE: This math assumes the worst case. It's possible
138373ed8e77SXin LI 		// that the limit wouldn't be exceeded if the existing cached
138473ed8e77SXin LI 		// allocations are reused.
138573ed8e77SXin LI 		if (mem_in_use + mem_cached + coder->outq.mem_allocated
138673ed8e77SXin LI 				> mem_max) {
138773ed8e77SXin LI 			// Clear the outq cache except leave one buffer in
138873ed8e77SXin LI 			// the cache if its size is correct. That way we
138973ed8e77SXin LI 			// don't free and almost immediately reallocate
139073ed8e77SXin LI 			// an identical buffer.
139173ed8e77SXin LI 			lzma_outq_clear_cache2(&coder->outq, allocator,
139273ed8e77SXin LI 				coder->block_options.uncompressed_size);
139373ed8e77SXin LI 		}
139473ed8e77SXin LI 
139573ed8e77SXin LI 		// If there is at least one worker_thread in the cache and
139673ed8e77SXin LI 		// the existing allocations are so large that starting to
139773ed8e77SXin LI 		// decode this Block might exceed memlimit_threads, free
139873ed8e77SXin LI 		// memory by freeing cached Block decoders.
139973ed8e77SXin LI 		//
140073ed8e77SXin LI 		// NOTE: The comparison is different here than above.
140173ed8e77SXin LI 		// Here we don't care about cached buffers in outq anymore
140273ed8e77SXin LI 		// and only look at memory actually in use. This is because
140373ed8e77SXin LI 		// if there is something in outq cache, it's a single buffer
140473ed8e77SXin LI 		// that can be used as is. We ensured this in the above
140573ed8e77SXin LI 		// if-block.
140673ed8e77SXin LI 		uint64_t mem_freed = 0;
140773ed8e77SXin LI 		if (thr != NULL && mem_in_use + mem_cached
140873ed8e77SXin LI 				+ coder->outq.mem_in_use > mem_max) {
140973ed8e77SXin LI 			// Don't free the first Block decoder if its memory
141073ed8e77SXin LI 			// usage isn't greater than what this Block will need.
141173ed8e77SXin LI 			// Typically the same filter chain is used for all
141273ed8e77SXin LI 			// Blocks so this way the allocations can be reused
141373ed8e77SXin LI 			// when get_thread() picks the first worker_thread
141473ed8e77SXin LI 			// from the cache.
141573ed8e77SXin LI 			if (thr->mem_filters <= coder->mem_next_filters)
141673ed8e77SXin LI 				thr = thr->next;
141773ed8e77SXin LI 
141873ed8e77SXin LI 			while (thr != NULL) {
141973ed8e77SXin LI 				lzma_next_end(&thr->block_decoder, allocator);
142073ed8e77SXin LI 				mem_freed += thr->mem_filters;
142173ed8e77SXin LI 				thr->mem_filters = 0;
142273ed8e77SXin LI 				thr = thr->next;
142373ed8e77SXin LI 			}
142473ed8e77SXin LI 		}
142573ed8e77SXin LI 
142673ed8e77SXin LI 		// Update the memory usage counters. Note that coder->mem_*
14271f3ced26SXin LI 		// may have changed since we read them so we must subtract
142873ed8e77SXin LI 		// or add the changes.
142973ed8e77SXin LI 		mythread_sync(coder->mutex) {
143073ed8e77SXin LI 			coder->mem_cached -= mem_freed;
143173ed8e77SXin LI 
143273ed8e77SXin LI 			// Memory needed for the filters and the input buffer.
143373ed8e77SXin LI 			// The output queue takes care of its own counter so
143473ed8e77SXin LI 			// we don't touch it here.
143573ed8e77SXin LI 			//
143673ed8e77SXin LI 			// NOTE: After this, coder->mem_in_use +
143773ed8e77SXin LI 			// coder->mem_cached might count the same thing twice.
143873ed8e77SXin LI 			// If so, this will get corrected in get_thread() when
143973ed8e77SXin LI 			// a worker_thread is picked from coder->free_threads
14401f3ced26SXin LI 			// and its memory usage is subtracted from mem_cached.
144173ed8e77SXin LI 			coder->mem_in_use += coder->mem_next_in
144273ed8e77SXin LI 					+ coder->mem_next_filters;
144373ed8e77SXin LI 		}
144473ed8e77SXin LI 
144573ed8e77SXin LI 		// Allocate memory for the output buffer in the output queue.
144673ed8e77SXin LI 		lzma_ret ret = lzma_outq_prealloc_buf(
144773ed8e77SXin LI 				&coder->outq, allocator,
144873ed8e77SXin LI 				coder->block_options.uncompressed_size);
144973ed8e77SXin LI 		if (ret != LZMA_OK) {
145073ed8e77SXin LI 			threads_stop(coder);
145173ed8e77SXin LI 			return ret;
145273ed8e77SXin LI 		}
145373ed8e77SXin LI 
145473ed8e77SXin LI 		// Set up coder->thr.
145573ed8e77SXin LI 		ret = get_thread(coder, allocator);
145673ed8e77SXin LI 		if (ret != LZMA_OK) {
145773ed8e77SXin LI 			threads_stop(coder);
145873ed8e77SXin LI 			return ret;
145973ed8e77SXin LI 		}
146073ed8e77SXin LI 
146173ed8e77SXin LI 		// The new Block decoder memory usage is already counted in
146273ed8e77SXin LI 		// coder->mem_in_use. Store it in the thread too.
146373ed8e77SXin LI 		coder->thr->mem_filters = coder->mem_next_filters;
146473ed8e77SXin LI 
146573ed8e77SXin LI 		// Initialize the Block decoder.
146673ed8e77SXin LI 		coder->thr->block_options = coder->block_options;
146773ed8e77SXin LI 		ret = lzma_block_decoder_init(
146873ed8e77SXin LI 					&coder->thr->block_decoder, allocator,
146973ed8e77SXin LI 					&coder->thr->block_options);
147073ed8e77SXin LI 
147173ed8e77SXin LI 		// Free the allocated filter options since they are needed
147273ed8e77SXin LI 		// only to initialize the Block decoder.
147373ed8e77SXin LI 		lzma_filters_free(coder->filters, allocator);
147473ed8e77SXin LI 		coder->thr->block_options.filters = NULL;
147573ed8e77SXin LI 
147673ed8e77SXin LI 		// Check if memory usage calculation and Block encoder
147773ed8e77SXin LI 		// initialization succeeded.
147873ed8e77SXin LI 		if (ret != LZMA_OK) {
147973ed8e77SXin LI 			coder->pending_error = ret;
148073ed8e77SXin LI 			coder->sequence = SEQ_ERROR;
148173ed8e77SXin LI 			break;
148273ed8e77SXin LI 		}
148373ed8e77SXin LI 
148473ed8e77SXin LI 		// Allocate the input buffer.
148573ed8e77SXin LI 		coder->thr->in_size = coder->mem_next_in;
148673ed8e77SXin LI 		coder->thr->in = lzma_alloc(coder->thr->in_size, allocator);
148773ed8e77SXin LI 		if (coder->thr->in == NULL) {
148873ed8e77SXin LI 			threads_stop(coder);
148973ed8e77SXin LI 			return LZMA_MEM_ERROR;
149073ed8e77SXin LI 		}
149173ed8e77SXin LI 
149273ed8e77SXin LI 		// Get the preallocated output buffer.
149373ed8e77SXin LI 		coder->thr->outbuf = lzma_outq_get_buf(
149473ed8e77SXin LI 				&coder->outq, coder->thr);
149573ed8e77SXin LI 
149673ed8e77SXin LI 		// Start the decoder.
149773ed8e77SXin LI 		mythread_sync(coder->thr->mutex) {
149873ed8e77SXin LI 			assert(coder->thr->state == THR_IDLE);
149973ed8e77SXin LI 			coder->thr->state = THR_RUN;
150073ed8e77SXin LI 			mythread_cond_signal(&coder->thr->cond);
150173ed8e77SXin LI 		}
150273ed8e77SXin LI 
150373ed8e77SXin LI 		// Enable output from the thread that holds the oldest output
150473ed8e77SXin LI 		// buffer in the output queue (if such a thread exists).
150573ed8e77SXin LI 		mythread_sync(coder->mutex) {
150673ed8e77SXin LI 			lzma_outq_enable_partial_output(&coder->outq,
150773ed8e77SXin LI 					&worker_enable_partial_update);
150873ed8e77SXin LI 		}
150973ed8e77SXin LI 
151073ed8e77SXin LI 		coder->sequence = SEQ_BLOCK_THR_RUN;
151173ed8e77SXin LI 	}
151273ed8e77SXin LI 
151373ed8e77SXin LI 	// Fall through
151473ed8e77SXin LI 
151573ed8e77SXin LI 	case SEQ_BLOCK_THR_RUN: {
151673ed8e77SXin LI 		if (action == LZMA_FINISH && coder->fail_fast) {
151773ed8e77SXin LI 			// We know that we won't get more input and that
151873ed8e77SXin LI 			// the caller wants fail-fast behavior. If we see
151973ed8e77SXin LI 			// that we don't have enough input to finish this
152073ed8e77SXin LI 			// Block, return LZMA_DATA_ERROR immediately.
152173ed8e77SXin LI 			// See SEQ_BLOCK_HEADER for the error code rationale.
152273ed8e77SXin LI 			const size_t in_avail = in_size - *in_pos;
152373ed8e77SXin LI 			const size_t in_needed = coder->thr->in_size
152473ed8e77SXin LI 					- coder->thr->in_filled;
152573ed8e77SXin LI 			if (in_avail < in_needed) {
152673ed8e77SXin LI 				threads_stop(coder);
152773ed8e77SXin LI 				return LZMA_DATA_ERROR;
152873ed8e77SXin LI 			}
152973ed8e77SXin LI 		}
153073ed8e77SXin LI 
153173ed8e77SXin LI 		// Copy input to the worker thread.
153273ed8e77SXin LI 		size_t cur_in_filled = coder->thr->in_filled;
153373ed8e77SXin LI 		lzma_bufcpy(in, in_pos, in_size, coder->thr->in,
153473ed8e77SXin LI 				&cur_in_filled, coder->thr->in_size);
153573ed8e77SXin LI 
153673ed8e77SXin LI 		// Tell the thread how much we copied.
153773ed8e77SXin LI 		mythread_sync(coder->thr->mutex) {
153873ed8e77SXin LI 			coder->thr->in_filled = cur_in_filled;
153973ed8e77SXin LI 
154073ed8e77SXin LI 			// NOTE: Most of the time we are copying input faster
154173ed8e77SXin LI 			// than the thread can decode so most of the time
154273ed8e77SXin LI 			// calling mythread_cond_signal() is useless but
154373ed8e77SXin LI 			// we cannot make it conditional because thr->in_pos
154473ed8e77SXin LI 			// is updated without a mutex. And the overhead should
154573ed8e77SXin LI 			// be very much negligible anyway.
154673ed8e77SXin LI 			mythread_cond_signal(&coder->thr->cond);
154773ed8e77SXin LI 		}
154873ed8e77SXin LI 
154973ed8e77SXin LI 		// Read output from the output queue. Just like in
155073ed8e77SXin LI 		// SEQ_BLOCK_HEADER, we wait to fill the output buffer
155173ed8e77SXin LI 		// only if waiting_allowed was set to true in the beginning
155273ed8e77SXin LI 		// of this function (see the comment there).
155373ed8e77SXin LI 		return_if_error(read_output_and_wait(coder, allocator,
155473ed8e77SXin LI 				out, out_pos, out_size,
155573ed8e77SXin LI 				NULL, waiting_allowed,
155673ed8e77SXin LI 				&wait_abs, &has_blocked));
155773ed8e77SXin LI 
155873ed8e77SXin LI 		if (coder->pending_error != LZMA_OK) {
155973ed8e77SXin LI 			coder->sequence = SEQ_ERROR;
156073ed8e77SXin LI 			break;
156173ed8e77SXin LI 		}
156273ed8e77SXin LI 
156373ed8e77SXin LI 		// Return if the input didn't contain the whole Block.
156473ed8e77SXin LI 		if (coder->thr->in_filled < coder->thr->in_size) {
156573ed8e77SXin LI 			assert(*in_pos == in_size);
156673ed8e77SXin LI 			return LZMA_OK;
156773ed8e77SXin LI 		}
156873ed8e77SXin LI 
156973ed8e77SXin LI 		// The whole Block has been copied to the thread-specific
157073ed8e77SXin LI 		// buffer. Continue from the next Block Header or Index.
157173ed8e77SXin LI 		coder->thr = NULL;
157273ed8e77SXin LI 		coder->sequence = SEQ_BLOCK_HEADER;
157373ed8e77SXin LI 		break;
157473ed8e77SXin LI 	}
157573ed8e77SXin LI 
157673ed8e77SXin LI 	case SEQ_BLOCK_DIRECT_INIT: {
157773ed8e77SXin LI 		// Wait for the threads to finish and that all decoded data
157873ed8e77SXin LI 		// has been copied to the output. That is, wait until the
157973ed8e77SXin LI 		// output queue becomes empty.
158073ed8e77SXin LI 		//
158173ed8e77SXin LI 		// NOTE: No need to check for coder->pending_error as
158273ed8e77SXin LI 		// we aren't consuming any input until the queue is empty
158373ed8e77SXin LI 		// and if there is a pending error, read_output_and_wait()
158473ed8e77SXin LI 		// will eventually return it before the queue is empty.
158573ed8e77SXin LI 		return_if_error(read_output_and_wait(coder, allocator,
158673ed8e77SXin LI 				out, out_pos, out_size,
158773ed8e77SXin LI 				NULL, true, &wait_abs, &has_blocked));
158873ed8e77SXin LI 		if (!lzma_outq_is_empty(&coder->outq))
158973ed8e77SXin LI 			return LZMA_OK;
159073ed8e77SXin LI 
159173ed8e77SXin LI 		// Free the cached output buffers.
159273ed8e77SXin LI 		lzma_outq_clear_cache(&coder->outq, allocator);
159373ed8e77SXin LI 
159473ed8e77SXin LI 		// Get rid of the worker threads, including the coder->threads
159573ed8e77SXin LI 		// array.
159673ed8e77SXin LI 		threads_end(coder, allocator);
159773ed8e77SXin LI 
159873ed8e77SXin LI 		// Initialize the Block decoder.
159973ed8e77SXin LI 		const lzma_ret ret = lzma_block_decoder_init(
160073ed8e77SXin LI 				&coder->block_decoder, allocator,
160173ed8e77SXin LI 				&coder->block_options);
160273ed8e77SXin LI 
160373ed8e77SXin LI 		// Free the allocated filter options since they are needed
160473ed8e77SXin LI 		// only to initialize the Block decoder.
160573ed8e77SXin LI 		lzma_filters_free(coder->filters, allocator);
160673ed8e77SXin LI 		coder->block_options.filters = NULL;
160773ed8e77SXin LI 
160873ed8e77SXin LI 		// Check if Block decoder initialization succeeded.
160973ed8e77SXin LI 		if (ret != LZMA_OK)
161073ed8e77SXin LI 			return ret;
161173ed8e77SXin LI 
161273ed8e77SXin LI 		// Make the memory usage visible to _memconfig().
161373ed8e77SXin LI 		coder->mem_direct_mode = coder->mem_next_filters;
161473ed8e77SXin LI 
161573ed8e77SXin LI 		coder->sequence = SEQ_BLOCK_DIRECT_RUN;
161673ed8e77SXin LI 	}
161773ed8e77SXin LI 
161873ed8e77SXin LI 	// Fall through
161973ed8e77SXin LI 
162073ed8e77SXin LI 	case SEQ_BLOCK_DIRECT_RUN: {
162173ed8e77SXin LI 		const size_t in_old = *in_pos;
162273ed8e77SXin LI 		const size_t out_old = *out_pos;
162373ed8e77SXin LI 		const lzma_ret ret = coder->block_decoder.code(
162473ed8e77SXin LI 				coder->block_decoder.coder, allocator,
162573ed8e77SXin LI 				in, in_pos, in_size, out, out_pos, out_size,
162673ed8e77SXin LI 				action);
162773ed8e77SXin LI 		coder->progress_in += *in_pos - in_old;
162873ed8e77SXin LI 		coder->progress_out += *out_pos - out_old;
162973ed8e77SXin LI 
163073ed8e77SXin LI 		if (ret != LZMA_STREAM_END)
163173ed8e77SXin LI 			return ret;
163273ed8e77SXin LI 
163373ed8e77SXin LI 		// Block decoded successfully. Add the new size pair to
163473ed8e77SXin LI 		// the Index hash.
163573ed8e77SXin LI 		return_if_error(lzma_index_hash_append(coder->index_hash,
163673ed8e77SXin LI 				lzma_block_unpadded_size(
163773ed8e77SXin LI 					&coder->block_options),
163873ed8e77SXin LI 				coder->block_options.uncompressed_size));
163973ed8e77SXin LI 
164073ed8e77SXin LI 		coder->sequence = SEQ_BLOCK_HEADER;
164173ed8e77SXin LI 		break;
164273ed8e77SXin LI 	}
164373ed8e77SXin LI 
164473ed8e77SXin LI 	case SEQ_INDEX_WAIT_OUTPUT:
164573ed8e77SXin LI 		// Flush the output from all worker threads so that we can
164673ed8e77SXin LI 		// decode the Index without thinking about threading.
164773ed8e77SXin LI 		return_if_error(read_output_and_wait(coder, allocator,
164873ed8e77SXin LI 				out, out_pos, out_size,
164973ed8e77SXin LI 				NULL, true, &wait_abs, &has_blocked));
165073ed8e77SXin LI 
165173ed8e77SXin LI 		if (!lzma_outq_is_empty(&coder->outq))
165273ed8e77SXin LI 			return LZMA_OK;
165373ed8e77SXin LI 
165473ed8e77SXin LI 		coder->sequence = SEQ_INDEX_DECODE;
165573ed8e77SXin LI 
165673ed8e77SXin LI 	// Fall through
165773ed8e77SXin LI 
165873ed8e77SXin LI 	case SEQ_INDEX_DECODE: {
165973ed8e77SXin LI 		// If we don't have any input, don't call
166073ed8e77SXin LI 		// lzma_index_hash_decode() since it would return
166173ed8e77SXin LI 		// LZMA_BUF_ERROR, which we must not do here.
166273ed8e77SXin LI 		if (*in_pos >= in_size)
166373ed8e77SXin LI 			return LZMA_OK;
166473ed8e77SXin LI 
166573ed8e77SXin LI 		// Decode the Index and compare it to the hash calculated
166673ed8e77SXin LI 		// from the sizes of the Blocks (if any).
166773ed8e77SXin LI 		const size_t in_old = *in_pos;
166873ed8e77SXin LI 		const lzma_ret ret = lzma_index_hash_decode(coder->index_hash,
166973ed8e77SXin LI 				in, in_pos, in_size);
167073ed8e77SXin LI 		coder->progress_in += *in_pos - in_old;
167173ed8e77SXin LI 		if (ret != LZMA_STREAM_END)
167273ed8e77SXin LI 			return ret;
167373ed8e77SXin LI 
167473ed8e77SXin LI 		coder->sequence = SEQ_STREAM_FOOTER;
167573ed8e77SXin LI 	}
167673ed8e77SXin LI 
167773ed8e77SXin LI 	// Fall through
167873ed8e77SXin LI 
167973ed8e77SXin LI 	case SEQ_STREAM_FOOTER: {
168073ed8e77SXin LI 		// Copy the Stream Footer to the internal buffer.
168173ed8e77SXin LI 		const size_t in_old = *in_pos;
168273ed8e77SXin LI 		lzma_bufcpy(in, in_pos, in_size, coder->buffer, &coder->pos,
168373ed8e77SXin LI 				LZMA_STREAM_HEADER_SIZE);
168473ed8e77SXin LI 		coder->progress_in += *in_pos - in_old;
168573ed8e77SXin LI 
168673ed8e77SXin LI 		// Return if we didn't get the whole Stream Footer yet.
168773ed8e77SXin LI 		if (coder->pos < LZMA_STREAM_HEADER_SIZE)
168873ed8e77SXin LI 			return LZMA_OK;
168973ed8e77SXin LI 
169073ed8e77SXin LI 		coder->pos = 0;
169173ed8e77SXin LI 
169273ed8e77SXin LI 		// Decode the Stream Footer. The decoder gives
169373ed8e77SXin LI 		// LZMA_FORMAT_ERROR if the magic bytes don't match,
169473ed8e77SXin LI 		// so convert that return code to LZMA_DATA_ERROR.
169573ed8e77SXin LI 		lzma_stream_flags footer_flags;
169673ed8e77SXin LI 		const lzma_ret ret = lzma_stream_footer_decode(
169773ed8e77SXin LI 				&footer_flags, coder->buffer);
169873ed8e77SXin LI 		if (ret != LZMA_OK)
169973ed8e77SXin LI 			return ret == LZMA_FORMAT_ERROR
170073ed8e77SXin LI 					? LZMA_DATA_ERROR : ret;
170173ed8e77SXin LI 
170273ed8e77SXin LI 		// Check that Index Size stored in the Stream Footer matches
170373ed8e77SXin LI 		// the real size of the Index field.
170473ed8e77SXin LI 		if (lzma_index_hash_size(coder->index_hash)
170573ed8e77SXin LI 				!= footer_flags.backward_size)
170673ed8e77SXin LI 			return LZMA_DATA_ERROR;
170773ed8e77SXin LI 
170873ed8e77SXin LI 		// Compare that the Stream Flags fields are identical in
170973ed8e77SXin LI 		// both Stream Header and Stream Footer.
171073ed8e77SXin LI 		return_if_error(lzma_stream_flags_compare(
171173ed8e77SXin LI 				&coder->stream_flags, &footer_flags));
171273ed8e77SXin LI 
171373ed8e77SXin LI 		if (!coder->concatenated)
171473ed8e77SXin LI 			return LZMA_STREAM_END;
171573ed8e77SXin LI 
171673ed8e77SXin LI 		coder->sequence = SEQ_STREAM_PADDING;
171773ed8e77SXin LI 	}
171873ed8e77SXin LI 
171973ed8e77SXin LI 	// Fall through
172073ed8e77SXin LI 
172173ed8e77SXin LI 	case SEQ_STREAM_PADDING:
172273ed8e77SXin LI 		assert(coder->concatenated);
172373ed8e77SXin LI 
172473ed8e77SXin LI 		// Skip over possible Stream Padding.
172573ed8e77SXin LI 		while (true) {
172673ed8e77SXin LI 			if (*in_pos >= in_size) {
172773ed8e77SXin LI 				// Unless LZMA_FINISH was used, we cannot
172873ed8e77SXin LI 				// know if there's more input coming later.
172973ed8e77SXin LI 				if (action != LZMA_FINISH)
173073ed8e77SXin LI 					return LZMA_OK;
173173ed8e77SXin LI 
173273ed8e77SXin LI 				// Stream Padding must be a multiple of
173373ed8e77SXin LI 				// four bytes.
173473ed8e77SXin LI 				return coder->pos == 0
173573ed8e77SXin LI 						? LZMA_STREAM_END
173673ed8e77SXin LI 						: LZMA_DATA_ERROR;
173773ed8e77SXin LI 			}
173873ed8e77SXin LI 
173973ed8e77SXin LI 			// If the byte is not zero, it probably indicates
174073ed8e77SXin LI 			// beginning of a new Stream (or the file is corrupt).
174173ed8e77SXin LI 			if (in[*in_pos] != 0x00)
174273ed8e77SXin LI 				break;
174373ed8e77SXin LI 
174473ed8e77SXin LI 			++*in_pos;
174573ed8e77SXin LI 			++coder->progress_in;
174673ed8e77SXin LI 			coder->pos = (coder->pos + 1) & 3;
174773ed8e77SXin LI 		}
174873ed8e77SXin LI 
174973ed8e77SXin LI 		// Stream Padding must be a multiple of four bytes (empty
175073ed8e77SXin LI 		// Stream Padding is OK).
175173ed8e77SXin LI 		if (coder->pos != 0) {
175273ed8e77SXin LI 			++*in_pos;
175373ed8e77SXin LI 			++coder->progress_in;
175473ed8e77SXin LI 			return LZMA_DATA_ERROR;
175573ed8e77SXin LI 		}
175673ed8e77SXin LI 
175773ed8e77SXin LI 		// Prepare to decode the next Stream.
175873ed8e77SXin LI 		return_if_error(stream_decoder_reset(coder, allocator));
175973ed8e77SXin LI 		break;
176073ed8e77SXin LI 
176173ed8e77SXin LI 	case SEQ_ERROR:
176273ed8e77SXin LI 		if (!coder->fail_fast) {
176373ed8e77SXin LI 			// Let the application get all data before the point
176473ed8e77SXin LI 			// where the error was detected. This matches the
176573ed8e77SXin LI 			// behavior of single-threaded use.
176673ed8e77SXin LI 			//
176773ed8e77SXin LI 			// FIXME? Some errors (LZMA_MEM_ERROR) don't get here,
176873ed8e77SXin LI 			// they are returned immediately. Thus in rare cases
176973ed8e77SXin LI 			// the output will be less than in the single-threaded
177073ed8e77SXin LI 			// mode. Maybe this doesn't matter much in practice.
177173ed8e77SXin LI 			return_if_error(read_output_and_wait(coder, allocator,
177273ed8e77SXin LI 					out, out_pos, out_size,
177373ed8e77SXin LI 					NULL, true, &wait_abs, &has_blocked));
177473ed8e77SXin LI 
177573ed8e77SXin LI 			// We get here only if the error happened in the main
177673ed8e77SXin LI 			// thread, for example, unsupported Block Header.
177773ed8e77SXin LI 			if (!lzma_outq_is_empty(&coder->outq))
177873ed8e77SXin LI 				return LZMA_OK;
177973ed8e77SXin LI 		}
178073ed8e77SXin LI 
178173ed8e77SXin LI 		// We only get here if no errors were detected by the worker
178273ed8e77SXin LI 		// threads. Errors from worker threads would have already been
178373ed8e77SXin LI 		// returned by the call to read_output_and_wait() above.
178473ed8e77SXin LI 		return coder->pending_error;
178573ed8e77SXin LI 
178673ed8e77SXin LI 	default:
178773ed8e77SXin LI 		assert(0);
178873ed8e77SXin LI 		return LZMA_PROG_ERROR;
178973ed8e77SXin LI 	}
179073ed8e77SXin LI 
179173ed8e77SXin LI 	// Never reached
179273ed8e77SXin LI }
179373ed8e77SXin LI 
179473ed8e77SXin LI 
179573ed8e77SXin LI static void
179673ed8e77SXin LI stream_decoder_mt_end(void *coder_ptr, const lzma_allocator *allocator)
179773ed8e77SXin LI {
179873ed8e77SXin LI 	struct lzma_stream_coder *coder = coder_ptr;
179973ed8e77SXin LI 
180073ed8e77SXin LI 	threads_end(coder, allocator);
180173ed8e77SXin LI 	lzma_outq_end(&coder->outq, allocator);
180273ed8e77SXin LI 
180373ed8e77SXin LI 	lzma_next_end(&coder->block_decoder, allocator);
180473ed8e77SXin LI 	lzma_filters_free(coder->filters, allocator);
180573ed8e77SXin LI 	lzma_index_hash_end(coder->index_hash, allocator);
180673ed8e77SXin LI 
180773ed8e77SXin LI 	lzma_free(coder, allocator);
180873ed8e77SXin LI 	return;
180973ed8e77SXin LI }
181073ed8e77SXin LI 
181173ed8e77SXin LI 
181273ed8e77SXin LI static lzma_check
181373ed8e77SXin LI stream_decoder_mt_get_check(const void *coder_ptr)
181473ed8e77SXin LI {
181573ed8e77SXin LI 	const struct lzma_stream_coder *coder = coder_ptr;
181673ed8e77SXin LI 	return coder->stream_flags.check;
181773ed8e77SXin LI }
181873ed8e77SXin LI 
181973ed8e77SXin LI 
182073ed8e77SXin LI static lzma_ret
182173ed8e77SXin LI stream_decoder_mt_memconfig(void *coder_ptr, uint64_t *memusage,
182273ed8e77SXin LI 		uint64_t *old_memlimit, uint64_t new_memlimit)
182373ed8e77SXin LI {
182473ed8e77SXin LI 	// NOTE: This function gets/sets memlimit_stop. For now,
182573ed8e77SXin LI 	// memlimit_threading cannot be modified after initialization.
182673ed8e77SXin LI 	//
182773ed8e77SXin LI 	// *memusage will include cached memory too. Excluding cached memory
182873ed8e77SXin LI 	// would be misleading and it wouldn't help the applications to
182973ed8e77SXin LI 	// know how much memory is actually needed to decompress the file
183073ed8e77SXin LI 	// because the higher the number of threads and the memlimits are
183173ed8e77SXin LI 	// the more memory the decoder may use.
183273ed8e77SXin LI 	//
183373ed8e77SXin LI 	// Setting a new limit includes the cached memory too and too low
183473ed8e77SXin LI 	// limits will be rejected. Alternative could be to free the cached
183573ed8e77SXin LI 	// memory immediately if that helps to bring the limit down but
183673ed8e77SXin LI 	// the current way is the simplest. It's unlikely that limit needs
183773ed8e77SXin LI 	// to be lowered in the middle of a file anyway; the typical reason
183873ed8e77SXin LI 	// to want a new limit is to increase after LZMA_MEMLIMIT_ERROR
183973ed8e77SXin LI 	// and even such use isn't common.
184073ed8e77SXin LI 	struct lzma_stream_coder *coder = coder_ptr;
184173ed8e77SXin LI 
184273ed8e77SXin LI 	mythread_sync(coder->mutex) {
184373ed8e77SXin LI 		*memusage = coder->mem_direct_mode
184473ed8e77SXin LI 				+ coder->mem_in_use
184573ed8e77SXin LI 				+ coder->mem_cached
184673ed8e77SXin LI 				+ coder->outq.mem_allocated;
184773ed8e77SXin LI 	}
184873ed8e77SXin LI 
184973ed8e77SXin LI 	// If no filter chains are allocated, *memusage may be zero.
185073ed8e77SXin LI 	// Always return at least LZMA_MEMUSAGE_BASE.
185173ed8e77SXin LI 	if (*memusage < LZMA_MEMUSAGE_BASE)
185273ed8e77SXin LI 		*memusage = LZMA_MEMUSAGE_BASE;
185373ed8e77SXin LI 
185473ed8e77SXin LI 	*old_memlimit = coder->memlimit_stop;
185573ed8e77SXin LI 
185673ed8e77SXin LI 	if (new_memlimit != 0) {
185773ed8e77SXin LI 		if (new_memlimit < *memusage)
185873ed8e77SXin LI 			return LZMA_MEMLIMIT_ERROR;
185973ed8e77SXin LI 
186073ed8e77SXin LI 		coder->memlimit_stop = new_memlimit;
186173ed8e77SXin LI 	}
186273ed8e77SXin LI 
186373ed8e77SXin LI 	return LZMA_OK;
186473ed8e77SXin LI }
186573ed8e77SXin LI 
186673ed8e77SXin LI 
186773ed8e77SXin LI static void
186873ed8e77SXin LI stream_decoder_mt_get_progress(void *coder_ptr,
186973ed8e77SXin LI 		uint64_t *progress_in, uint64_t *progress_out)
187073ed8e77SXin LI {
187173ed8e77SXin LI 	struct lzma_stream_coder *coder = coder_ptr;
187273ed8e77SXin LI 
187373ed8e77SXin LI 	// Lock coder->mutex to prevent finishing threads from moving their
187473ed8e77SXin LI 	// progress info from the worker_thread structure to lzma_stream_coder.
187573ed8e77SXin LI 	mythread_sync(coder->mutex) {
187673ed8e77SXin LI 		*progress_in = coder->progress_in;
187773ed8e77SXin LI 		*progress_out = coder->progress_out;
187873ed8e77SXin LI 
187973ed8e77SXin LI 		for (size_t i = 0; i < coder->threads_initialized; ++i) {
188073ed8e77SXin LI 			mythread_sync(coder->threads[i].mutex) {
188173ed8e77SXin LI 				*progress_in += coder->threads[i].progress_in;
188273ed8e77SXin LI 				*progress_out += coder->threads[i]
188373ed8e77SXin LI 						.progress_out;
188473ed8e77SXin LI 			}
188573ed8e77SXin LI 		}
188673ed8e77SXin LI 	}
188773ed8e77SXin LI 
188873ed8e77SXin LI 	return;
188973ed8e77SXin LI }
189073ed8e77SXin LI 
189173ed8e77SXin LI 
189273ed8e77SXin LI static lzma_ret
189373ed8e77SXin LI stream_decoder_mt_init(lzma_next_coder *next, const lzma_allocator *allocator,
189473ed8e77SXin LI 		       const lzma_mt *options)
189573ed8e77SXin LI {
189673ed8e77SXin LI 	struct lzma_stream_coder *coder;
189773ed8e77SXin LI 
189873ed8e77SXin LI 	if (options->threads == 0 || options->threads > LZMA_THREADS_MAX)
189973ed8e77SXin LI 		return LZMA_OPTIONS_ERROR;
190073ed8e77SXin LI 
190173ed8e77SXin LI 	if (options->flags & ~LZMA_SUPPORTED_FLAGS)
190273ed8e77SXin LI 		return LZMA_OPTIONS_ERROR;
190373ed8e77SXin LI 
190473ed8e77SXin LI 	lzma_next_coder_init(&stream_decoder_mt_init, next, allocator);
190573ed8e77SXin LI 
190673ed8e77SXin LI 	coder = next->coder;
190773ed8e77SXin LI 	if (!coder) {
190873ed8e77SXin LI 		coder = lzma_alloc(sizeof(struct lzma_stream_coder), allocator);
190973ed8e77SXin LI 		if (coder == NULL)
191073ed8e77SXin LI 			return LZMA_MEM_ERROR;
191173ed8e77SXin LI 
191273ed8e77SXin LI 		next->coder = coder;
191373ed8e77SXin LI 
191473ed8e77SXin LI 		if (mythread_mutex_init(&coder->mutex)) {
191573ed8e77SXin LI 			lzma_free(coder, allocator);
191673ed8e77SXin LI 			return LZMA_MEM_ERROR;
191773ed8e77SXin LI 		}
191873ed8e77SXin LI 
191973ed8e77SXin LI 		if (mythread_cond_init(&coder->cond)) {
192073ed8e77SXin LI 			mythread_mutex_destroy(&coder->mutex);
192173ed8e77SXin LI 			lzma_free(coder, allocator);
192273ed8e77SXin LI 			return LZMA_MEM_ERROR;
192373ed8e77SXin LI 		}
192473ed8e77SXin LI 
192573ed8e77SXin LI 		next->code = &stream_decode_mt;
192673ed8e77SXin LI 		next->end = &stream_decoder_mt_end;
192773ed8e77SXin LI 		next->get_check = &stream_decoder_mt_get_check;
192873ed8e77SXin LI 		next->memconfig = &stream_decoder_mt_memconfig;
192973ed8e77SXin LI 		next->get_progress = &stream_decoder_mt_get_progress;
193073ed8e77SXin LI 
193173ed8e77SXin LI 		coder->filters[0].id = LZMA_VLI_UNKNOWN;
193273ed8e77SXin LI 		memzero(&coder->outq, sizeof(coder->outq));
193373ed8e77SXin LI 
193473ed8e77SXin LI 		coder->block_decoder = LZMA_NEXT_CODER_INIT;
193573ed8e77SXin LI 		coder->mem_direct_mode = 0;
193673ed8e77SXin LI 
193773ed8e77SXin LI 		coder->index_hash = NULL;
193873ed8e77SXin LI 		coder->threads = NULL;
193973ed8e77SXin LI 		coder->threads_free = NULL;
194073ed8e77SXin LI 		coder->threads_initialized = 0;
194173ed8e77SXin LI 	}
194273ed8e77SXin LI 
194373ed8e77SXin LI 	// Cleanup old filter chain if one remains after unfinished decoding
194473ed8e77SXin LI 	// of a previous Stream.
194573ed8e77SXin LI 	lzma_filters_free(coder->filters, allocator);
194673ed8e77SXin LI 
194773ed8e77SXin LI 	// By allocating threads from scratch we can start memory-usage
194873ed8e77SXin LI 	// accounting from scratch, too. Changes in filter and block sizes may
194973ed8e77SXin LI 	// affect number of threads.
195073ed8e77SXin LI 	//
195173ed8e77SXin LI 	// FIXME? Reusing should be easy but unlike the single-threaded
195273ed8e77SXin LI 	// decoder, with some types of input file combinations reusing
195373ed8e77SXin LI 	// could leave quite a lot of memory allocated but unused (first
195473ed8e77SXin LI 	// file could allocate a lot, the next files could use fewer
195573ed8e77SXin LI 	// threads and some of the allocations from the first file would not
195673ed8e77SXin LI 	// get freed unless memlimit_threading forces us to clear caches).
195773ed8e77SXin LI 	//
195873ed8e77SXin LI 	// NOTE: The direct mode decoder isn't freed here if one exists.
195973ed8e77SXin LI 	// It will be reused or freed as needed in the main loop.
196073ed8e77SXin LI 	threads_end(coder, allocator);
196173ed8e77SXin LI 
196273ed8e77SXin LI 	// All memusage counters start at 0 (including mem_direct_mode).
196373ed8e77SXin LI 	// The little extra that is needed for the structs in this file
196473ed8e77SXin LI 	// get accounted well enough by the filter chain memory usage
196573ed8e77SXin LI 	// which adds LZMA_MEMUSAGE_BASE for each chain. However,
196673ed8e77SXin LI 	// stream_decoder_mt_memconfig() has to handle this specially so that
196773ed8e77SXin LI 	// it will never return less than LZMA_MEMUSAGE_BASE as memory usage.
196873ed8e77SXin LI 	coder->mem_in_use = 0;
196973ed8e77SXin LI 	coder->mem_cached = 0;
197073ed8e77SXin LI 	coder->mem_next_block = 0;
197173ed8e77SXin LI 
197273ed8e77SXin LI 	coder->progress_in = 0;
197373ed8e77SXin LI 	coder->progress_out = 0;
197473ed8e77SXin LI 
197573ed8e77SXin LI 	coder->sequence = SEQ_STREAM_HEADER;
197673ed8e77SXin LI 	coder->thread_error = LZMA_OK;
197773ed8e77SXin LI 	coder->pending_error = LZMA_OK;
197873ed8e77SXin LI 	coder->thr = NULL;
197973ed8e77SXin LI 
198073ed8e77SXin LI 	coder->timeout = options->timeout;
198173ed8e77SXin LI 
198273ed8e77SXin LI 	coder->memlimit_threading = my_max(1, options->memlimit_threading);
198373ed8e77SXin LI 	coder->memlimit_stop = my_max(1, options->memlimit_stop);
198473ed8e77SXin LI 	if (coder->memlimit_threading > coder->memlimit_stop)
198573ed8e77SXin LI 		coder->memlimit_threading = coder->memlimit_stop;
198673ed8e77SXin LI 
198773ed8e77SXin LI 	coder->tell_no_check = (options->flags & LZMA_TELL_NO_CHECK) != 0;
198873ed8e77SXin LI 	coder->tell_unsupported_check
198973ed8e77SXin LI 			= (options->flags & LZMA_TELL_UNSUPPORTED_CHECK) != 0;
199073ed8e77SXin LI 	coder->tell_any_check = (options->flags & LZMA_TELL_ANY_CHECK) != 0;
199173ed8e77SXin LI 	coder->ignore_check = (options->flags & LZMA_IGNORE_CHECK) != 0;
199273ed8e77SXin LI 	coder->concatenated = (options->flags & LZMA_CONCATENATED) != 0;
199373ed8e77SXin LI 	coder->fail_fast = (options->flags & LZMA_FAIL_FAST) != 0;
199473ed8e77SXin LI 
199573ed8e77SXin LI 	coder->first_stream = true;
199673ed8e77SXin LI 	coder->out_was_filled = false;
199773ed8e77SXin LI 	coder->pos = 0;
199873ed8e77SXin LI 
199973ed8e77SXin LI 	coder->threads_max = options->threads;
200073ed8e77SXin LI 
200173ed8e77SXin LI 	return_if_error(lzma_outq_init(&coder->outq, allocator,
200273ed8e77SXin LI 				       coder->threads_max));
200373ed8e77SXin LI 
200473ed8e77SXin LI 	return stream_decoder_reset(coder, allocator);
200573ed8e77SXin LI }
200673ed8e77SXin LI 
200773ed8e77SXin LI 
200873ed8e77SXin LI extern LZMA_API(lzma_ret)
200973ed8e77SXin LI lzma_stream_decoder_mt(lzma_stream *strm, const lzma_mt *options)
201073ed8e77SXin LI {
201173ed8e77SXin LI 	lzma_next_strm_init(stream_decoder_mt_init, strm, options);
201273ed8e77SXin LI 
201373ed8e77SXin LI 	strm->internal->supported_actions[LZMA_RUN] = true;
201473ed8e77SXin LI 	strm->internal->supported_actions[LZMA_FINISH] = true;
201573ed8e77SXin LI 
201673ed8e77SXin LI 	return LZMA_OK;
201773ed8e77SXin LI }
2018