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