| 1 |
// This library is part of PLINK 2.0, copyright (C) 2005-2025 Shaun Purcell, |
| 2 |
// Christopher Chang. |
| 3 |
// |
| 4 |
// This library is free software: you can redistribute it and/or modify it |
| 5 |
// under the terms of the GNU Lesser General Public License as published by the |
| 6 |
// Free Software Foundation, either version 3 of the License, or (at your |
| 7 |
// option) any later version. |
| 8 |
// |
| 9 |
// This library is distributed in the hope that it will be useful, but WITHOUT |
| 10 |
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
| 11 |
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License |
| 12 |
// for more details. |
| 13 |
// |
| 14 |
// You should have received a copy of the GNU Lesser General Public License |
| 15 |
// along with this library. If not, see <http://www.gnu.org/licenses/>. |
| 16 |
|
| 17 |
#include <errno.h> |
| 18 |
#include "plink2_bgzf.h" |
| 19 |
|
| 20 |
#ifdef __cplusplus |
| 21 |
namespace plink2 { |
| 22 |
#endif |
| 23 |
|
| 24 |
static inline BgzfCompressStreamMain* GetBgzfp(BgzfCompressStream* cstream_ptr) { |
| 25 |
return &GET_PRIVATE(*cstream_ptr, m); |
| 26 |
} |
| 27 |
|
| 28 |
void PreinitBgzfRawMtStream(BgzfRawMtDecompressStream* bgzfp) { |
| 29 |
PreinitThreads(&bgzfp->tg); |
| 30 |
bgzfp->body.in = nullptr; |
| 31 |
// Main unconditional allocation starts from cfr[0]; cfr[1], twc[0], twc[1], |
| 32 |
// and the twc[] overflow buffers are fixed offsets within that allocation, |
| 33 |
// so we only have to cache-align once. |
| 34 |
bgzfp->body.cwr[0] = nullptr; |
| 35 |
} |
| 36 |
|
| 37 |
const char kShortErrInvalidBgzf[] = "Malformed BGZF block"; |
| 38 |
|
| 39 |
CONSTI32(kBgzfRawMtStreamRetargetCode, 0x7fffffff); |
| 40 |
static_assert(kBgzfRawMtStreamRetargetCode > kMaxBgzfCompressedBlockSize, "kBgzfRawMtStreamRetargetCode must be outside the valid locked_start range."); |
| 41 |
|
| 42 |
CONSTI32(kBgzfRawMtStreamMaxCapacity, 0x7fffffc0); |
| 43 |
|
| 44 |
// This function usually repeatedly joins and respawns the reader and |
| 45 |
// decompressor worker threads, until *dst_iterp reaches dst_end or we've hit |
| 46 |
// EOF. In the EOF case, *dst_iterp is set to 1 past the last read byte; |
| 47 |
// otherwise it's set to dst_end (assuming no error). |
| 48 |
// There's one special case: if dst_end and dst_iterp are nullptr, this |
| 49 |
// performs exactly one join-and-respawn (relevant during initialization and |
| 50 |
// rewind). |
| 51 |
// |
| 52 |
// Preconditions: |
| 53 |
// - bgzfp->overflow_start[bgzfp->consumer_parity] == |
| 54 |
// bgzfp->overflow_end[bgzfp->consumer_parity], i.e. all previously-dumped |
| 55 |
// overflow bytes were previously appended to dst_iter. |
| 56 |
// - In the non-null case, *dst_iterp points to where |
| 57 |
// bgzfp->body.cwr[1 - bgzfp->consumer_parity]->overflow[0] should be |
| 58 |
// appended. |
| 59 |
// - Thread-group is unjoined, and bgzfp->eof must be false. |
| 60 |
PglErr BgzfReadJoinAndRespawn(unsigned char* dst_end, BgzfRawMtDecompressStream* bgzfp, unsigned char** dst_iterp, const char** errmsgp) { |
| 61 |
PglErr reterr = kPglRetSuccess; |
| 62 |
ThreadGroup* tgp = &bgzfp->tg; |
| 63 |
unsigned char* dst_iter = nullptr; |
| 64 |
if (dst_iterp) { |
| 65 |
dst_iter = *dst_iterp; |
| 66 |
} |
| 67 |
unsigned char* next_target; |
| 68 |
do { |
| 69 |
JoinThreads(tgp); |
| 70 |
|
| 71 |
// 1. Check for decompression and read errors. |
| 72 |
const uint32_t next_producer_parity = bgzfp->consumer_parity; |
| 73 |
const uint32_t prev_producer_parity = 1 - next_producer_parity; |
| 74 |
BgzfMtReadBody* bodyp = &bgzfp->body; |
| 75 |
BgzfMtReadCommWithD* cwd = bodyp->cwd[prev_producer_parity]; |
| 76 |
if (unlikely(cwd->invalid_bgzf)) { |
| 77 |
goto BgzfReadJoinAndRespawn_ret_INVALID_BGZF; |
| 78 |
} |
| 79 |
BgzfMtReadCommWithR* cwr = bodyp->cwr[prev_producer_parity]; |
| 80 |
if (unlikely(cwr->reterr != kPglRetSuccess)) { |
| 81 |
*errmsgp = cwr->errmsg; |
| 82 |
reterr = S_CAST(PglErr, cwr->reterr); |
| 83 |
goto BgzfReadJoinAndRespawn_ret_1; |
| 84 |
} |
| 85 |
|
| 86 |
// 2. Determine amount of remaining dst space after existing-overflow-copy. |
| 87 |
const uint32_t remaining_start = cwr->remaining_start; |
| 88 |
const uint32_t remaining_end = cwr->remaining_end; |
| 89 |
const uint32_t remaining_end_is_eof = cwr->remaining_end_is_eof; |
| 90 |
const uint32_t new_overflow_ct = bgzfp->overflow_end[prev_producer_parity]; |
| 91 |
unsigned char* overflow_dst_start = dst_iter; |
| 92 |
next_target = nullptr; |
| 93 |
uint32_t overflow_copy_ct = 0; |
| 94 |
uint32_t target_capacity = 0; |
| 95 |
if (dst_iter) { |
| 96 |
uintptr_t dst_capacity = dst_end - dst_iter; |
| 97 |
if (dst_capacity > new_overflow_ct) { |
| 98 |
overflow_copy_ct = new_overflow_ct; |
| 99 |
next_target = &(dst_iter[new_overflow_ct]); |
| 100 |
dst_capacity -= new_overflow_ct; |
| 101 |
if (dst_capacity <= kBgzfRawMtStreamMaxCapacity) { |
| 102 |
target_capacity = dst_capacity; |
| 103 |
} else { |
| 104 |
// May as well clip to int32. |
| 105 |
target_capacity = kBgzfRawMtStreamMaxCapacity; |
| 106 |
} |
| 107 |
} else { |
| 108 |
overflow_copy_ct = dst_capacity; |
| 109 |
} |
| 110 |
} |
| 111 |
// 3. Skip thread relaunch on eof. |
| 112 |
if (remaining_start == remaining_end) { |
| 113 |
assert(remaining_end_is_eof); |
| 114 |
bgzfp->eof = 1; |
| 115 |
// bugfix (2 Oct 2019): new_overflow_ct -> overflow_copy_ct |
| 116 |
dst_iter = &(dst_iter[overflow_copy_ct]); |
| 117 |
next_target = nullptr; |
| 118 |
} else { |
| 119 |
// 4. Determine block boundaries in in[remaining_start, remaining_end), |
| 120 |
// and mark a multiple-of-decompress_thread_ct blocks for concurrent |
| 121 |
// decompression, taking advantage of any remaining dst space. (If |
| 122 |
// there's no dst space left, the overflow buffer still lets us |
| 123 |
// decompress the next decompress_thread_ct blocks in the background.) |
| 124 |
const uint32_t decompress_thread_ct = GetThreadCtTg(tgp) - 1; |
| 125 |
// We actually iterate through the blocks twice. The first iteration |
| 126 |
// counts the number of blocks that target_capacity allows for, and the |
| 127 |
// second iteration fills next_cwd->{in_offsets, out_offsets}. |
| 128 |
unsigned char* in = bodyp->in; |
| 129 |
uint32_t n_blocks_per_thread = 0; |
| 130 |
unsigned char* in_iter = &(in[remaining_start]); |
| 131 |
unsigned char* in_end = &(in[remaining_end]); |
| 132 |
uint32_t write_offset = 0; |
| 133 |
uint32_t n_eof_blocks = 0; |
| 134 |
while (write_offset <= target_capacity) { |
| 135 |
uint32_t uii = 0; |
| 136 |
for (; uii != decompress_thread_ct; ++uii) { |
| 137 |
const uint32_t n_inbytes = in_end - in_iter; |
| 138 |
if (n_inbytes <= 25) { |
| 139 |
if (unlikely(remaining_end_is_eof && n_inbytes)) { |
| 140 |
goto BgzfReadJoinAndRespawn_ret_INVALID_BGZF; |
| 141 |
} |
| 142 |
break; |
| 143 |
} |
| 144 |
if (unlikely(!IsBgzfHeader(in_iter))) { |
| 145 |
goto BgzfReadJoinAndRespawn_ret_INVALID_BGZF; |
| 146 |
} |
| 147 |
uint16_t bsize_minus1_u16; |
| 148 |
memcpy(&bsize_minus1_u16, &(in_iter[16]), 2); |
| 149 |
const uint32_t bsize_minus1 = bsize_minus1_u16; |
| 150 |
if (unlikely(bsize_minus1 < 25)) { |
| 151 |
goto BgzfReadJoinAndRespawn_ret_INVALID_BGZF; |
| 152 |
} |
| 153 |
if (bsize_minus1 >= n_inbytes) { |
| 154 |
if (unlikely(remaining_end_is_eof)) { |
| 155 |
goto BgzfReadJoinAndRespawn_ret_INVALID_BGZF; |
| 156 |
} |
| 157 |
break; |
| 158 |
} |
| 159 |
const uint32_t in_size = bsize_minus1 - 25; |
| 160 |
uint32_t out_size; |
| 161 |
memcpy(&out_size, &(in_iter[in_size + 22]), 4); |
| 162 |
if (unlikely(out_size > 65536)) { |
| 163 |
goto BgzfReadJoinAndRespawn_ret_INVALID_BGZF; |
| 164 |
} |
| 165 |
in_iter = &(in_iter[bsize_minus1 + 1]); |
| 166 |
write_offset += out_size; |
| 167 |
} |
| 168 |
if (uii != decompress_thread_ct) { |
| 169 |
if (remaining_end_is_eof && (in_iter == in_end)) { |
| 170 |
n_eof_blocks = uii; |
| 171 |
} |
| 172 |
break; |
| 173 |
} |
| 174 |
++n_blocks_per_thread; |
| 175 |
} |
| 176 |
|
| 177 |
// Second iteration. |
| 178 |
in_iter = &(in[remaining_start]); |
| 179 |
write_offset = 0; |
| 180 |
BgzfMtReadCommWithD* next_cwd = bodyp->cwd[next_producer_parity]; |
| 181 |
next_cwd->target = next_target; |
| 182 |
next_cwd->target_capacity = target_capacity; |
| 183 |
uint32_t* in_offsets = next_cwd->in_offsets; |
| 184 |
uint32_t* out_offsets = next_cwd->out_offsets; |
| 185 |
for (uint32_t out_tidx = 0; out_tidx != decompress_thread_ct; ++out_tidx) { |
| 186 |
in_offsets[out_tidx] = in_iter - in; |
| 187 |
out_offsets[out_tidx] = write_offset; |
| 188 |
const uint32_t nblocks = n_blocks_per_thread + (n_eof_blocks > out_tidx); |
| 189 |
for (uint32_t uii = 0; uii != nblocks; ++uii) { |
| 190 |
uint16_t bsize_minus1_u16; |
| 191 |
memcpy(&bsize_minus1_u16, &(in_iter[16]), 2); |
| 192 |
const uint32_t bsize_minus1 = bsize_minus1_u16; |
| 193 |
const uint32_t in_size = bsize_minus1 - 25; |
| 194 |
uint32_t out_size; |
| 195 |
memcpy(&out_size, &(in_iter[in_size + 22]), 4); |
| 196 |
in_iter = &(in_iter[bsize_minus1 + 1]); |
| 197 |
write_offset += out_size; |
| 198 |
} |
| 199 |
} |
| 200 |
const uint32_t locked_end = in_iter - in; |
| 201 |
in_offsets[decompress_thread_ct] = locked_end; |
| 202 |
|
| 203 |
BgzfMtReadCommWithR* next_cwr = bodyp->cwr[next_producer_parity]; |
| 204 |
next_cwr->locked_start = remaining_start; |
| 205 |
next_cwr->locked_end = locked_end; |
| 206 |
SpawnThreads(tgp); |
| 207 |
|
| 208 |
bgzfp->overflow_start[next_producer_parity] = 0; |
| 209 |
uint32_t next_overflow_end = 0; |
| 210 |
if (write_offset < target_capacity) { |
| 211 |
dst_iter = &(next_target[write_offset]); |
| 212 |
} else { |
| 213 |
next_overflow_end = write_offset - target_capacity; |
| 214 |
dst_iter = dst_end; |
| 215 |
} |
| 216 |
bgzfp->overflow_end[next_producer_parity] = next_overflow_end; |
| 217 |
} |
| 218 |
bgzfp->consumer_parity = prev_producer_parity; |
| 219 |
if (overflow_copy_ct) { |
| 220 |
// Critical for this to happen after SpawnThreads() call. |
| 221 |
memcpy(overflow_dst_start, cwd->overflow, overflow_copy_ct); |
| 222 |
bgzfp->overflow_start[prev_producer_parity] = overflow_copy_ct; |
| 223 |
} |
| 224 |
} while (next_target != nullptr); |
| 225 |
if (dst_iterp) { |
| 226 |
*dst_iterp = dst_iter; |
| 227 |
} |
| 228 |
while (0) { |
| 229 |
BgzfReadJoinAndRespawn_ret_INVALID_BGZF: |
| 230 |
*errmsgp = kShortErrInvalidBgzf; |
| 231 |
reterr = kPglRetDecompressFail; |
| 232 |
break; |
| 233 |
} |
| 234 |
BgzfReadJoinAndRespawn_ret_1: |
| 235 |
return reterr; |
| 236 |
} |
| 237 |
|
| 238 |
THREAD_FUNC_DECL BgzfRawMtStreamThread(void* raw_arg) { |
| 239 |
ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg); |
| 240 |
BgzfRawMtDecompressStream* context = S_CAST(BgzfRawMtDecompressStream*, arg->sharedp->context); |
| 241 |
BgzfMtReadBody* bodyp = &context->body; |
| 242 |
unsigned char* in = bodyp->in; |
| 243 |
uint32_t tidx = arg->tidx; |
| 244 |
uint32_t parity = 0; |
| 245 |
if (!tidx) { |
| 246 |
// Thread 0 reads raw compressed bytes into bodyp->in. This only uses a |
| 247 |
// small fraction of a processor core, but fread has enough latency |
| 248 |
// (especially when the input file isn't in cache) that we don't want the |
| 249 |
// consumer thread to block on it. |
| 250 |
FILE* ff = bodyp->ff; |
| 251 |
// in[] has space for kDecompressChunkSize bytes. |
| 252 |
// The current buffer-usage logic assumes that thresh1 <= 1/3 of the buffer |
| 253 |
// size, and thresh2 >= 2/3. |
| 254 |
const uint32_t thresh1 = (GetThreadCtTg(&context->tg) - 1) * (26 + kMaxBgzfCompressedBlockSize); |
| 255 |
const uint32_t thresh2 = kDecompressChunkSize - thresh1; |
| 256 |
uint32_t remaining_read_start = bodyp->initial_compressed_byte_ct; |
| 257 |
uint32_t is_eof = 0; |
| 258 |
do { |
| 259 |
BgzfMtReadCommWithR* cwr = bodyp->cwr[parity]; |
| 260 |
uint32_t locked_start = cwr->locked_start; |
| 261 |
uint32_t locked_end = cwr->locked_end; |
| 262 |
// in[locked_start, locked_end) is being decompressed by the other |
| 263 |
// threads, and must not be touched on this iteration. |
| 264 |
// |
| 265 |
// We have the following three regular states: |
| 266 |
// 1. locked_start <= locked_end < thresh1 (always true on function |
| 267 |
// entry) Try to load up to &(in[thresh2]). |
| 268 |
// 2. locked_start < thresh1 <= locked_end <= thresh2. Try to load up to |
| 269 |
// &(in[kDecompressChunkSize]) (the end of the buffer). |
| 270 |
// 3. thresh1 <= locked_start <= thresh2 < locked_end. Copy |
| 271 |
// [locked_end, kDecompressChunkSize) back to the beginning of the |
| 272 |
// buffer, and try to load up to &(in[prev_start_offset]). |
| 273 |
// We also have the following special case: |
| 274 |
// 4. locked_start == kBgzfRawMtStreamRetargetCode indicates that the |
| 275 |
// consumer has rewound or retargeted ff. |
| 276 |
if (locked_start == kBgzfRawMtStreamRetargetCode) { |
| 277 |
ff = bodyp->ff; |
| 278 |
locked_start = 0; |
| 279 |
// Consumer is expected to set cwr->locked_end = 0 here. |
| 280 |
remaining_read_start = 16; // bugfix |
| 281 |
is_eof = 0; |
| 282 |
} |
| 283 |
uint32_t remaining_end; |
| 284 |
if (locked_end < thresh1) { |
| 285 |
// state 1 |
| 286 |
remaining_end = thresh2; |
| 287 |
} else if (locked_end <= thresh2) { |
| 288 |
// state 2 |
| 289 |
remaining_end = kDecompressChunkSize; |
| 290 |
} else { |
| 291 |
// state 3 |
| 292 |
remaining_read_start -= locked_end; |
| 293 |
memcpy(in, &(in[locked_end]), remaining_read_start); |
| 294 |
locked_end = 0; |
| 295 |
remaining_end = locked_start; |
| 296 |
} |
| 297 |
uint32_t nbytes = 0; |
| 298 |
if (remaining_end > remaining_read_start) { |
| 299 |
if (!is_eof) { |
| 300 |
nbytes = fread_unlocked(&(in[remaining_read_start]), 1, remaining_end - remaining_read_start, ff); |
| 301 |
if (unlikely(ferror_unlocked(ff))) { |
| 302 |
cwr->errmsg = strerror(errno); |
| 303 |
cwr->reterr = kPglRetReadFail; |
| 304 |
continue; |
| 305 |
} |
| 306 |
is_eof = feof_unlocked(ff); |
| 307 |
} |
| 308 |
remaining_end = remaining_read_start + nbytes; |
| 309 |
} |
| 310 |
cwr->remaining_start = locked_end; |
| 311 |
cwr->remaining_end = remaining_end; |
| 312 |
cwr->remaining_end_is_eof = is_eof; |
| 313 |
remaining_read_start = remaining_end; |
| 314 |
parity = 1 - parity; |
| 315 |
} while (!THREAD_BLOCK_FINISH(arg)); |
| 316 |
} else { |
| 317 |
// Threads 1..decompress_thread_ct decompress from bodyp->in to |
| 318 |
// bodyp->target, storing overflow bytes in the cwd->overflow buffers. |
| 319 |
--tidx; // 0-based decompressor-thread indexes are more convenient here. |
| 320 |
struct libdeflate_decompressor* ldc = bodyp->ldcs[tidx]; |
| 321 |
|
| 322 |
// Note that we do nothing on the first iteration: in_offsets[] is |
| 323 |
// initialized to all-zero, while we wait for enough raw bytes to load. |
| 324 |
do { |
| 325 |
BgzfMtReadCommWithD* cwd = bodyp->cwd[parity]; |
| 326 |
unsigned char* overflow = cwd->overflow; |
| 327 |
unsigned char* target = cwd->target; |
| 328 |
uint32_t in_offset = cwd->in_offsets[tidx]; |
| 329 |
const uint32_t in_offset_stop = cwd->in_offsets[tidx + 1]; |
| 330 |
uint32_t out_offset = cwd->out_offsets[tidx]; |
| 331 |
const uint32_t out_capacity = cwd->target_capacity; |
| 332 |
while (in_offset != in_offset_stop) { |
| 333 |
uint16_t in_size_plus25_u16; |
| 334 |
memcpy(&in_size_plus25_u16, &(in[in_offset + 16]), 2); |
| 335 |
uint32_t in_size = in_size_plus25_u16; |
| 336 |
in_size -= 25; |
| 337 |
uint32_t out_size; |
| 338 |
memcpy(&out_size, &(in[in_offset + in_size + 22]), 4); |
| 339 |
if (out_size) { |
| 340 |
// avoid undefined behavior when target == nullptr |
| 341 |
const uint32_t out_offset_end = out_offset + out_size; |
| 342 |
unsigned char* dst; |
| 343 |
if (out_offset_end > out_capacity) { |
| 344 |
dst = &(overflow[S_CAST(int32_t, out_offset - out_capacity)]); |
| 345 |
} else { |
| 346 |
dst = &(target[out_offset]); |
| 347 |
} |
| 348 |
if (unlikely(libdeflate_deflate_decompress(ldc, &(in[in_offset + 18]), in_size, dst, out_size, nullptr))) { |
| 349 |
cwd->invalid_bgzf = 1; |
| 350 |
break; |
| 351 |
} |
| 352 |
if ((out_offset_end > out_capacity) && (out_offset < out_capacity)) { |
| 353 |
memcpy(&(target[out_offset]), dst, out_capacity - out_offset); |
| 354 |
} |
| 355 |
out_offset = out_offset_end; |
| 356 |
} |
| 357 |
in_offset += in_size + 26; |
| 358 |
} |
| 359 |
parity = 1 - parity; |
| 360 |
} while (!THREAD_BLOCK_FINISH(arg)); |
| 361 |
} |
| 362 |
THREAD_RETURN; |
| 363 |
} |
| 364 |
|
| 365 |
PglErr BgzfRawMtStreamInit(const char* header, uint32_t decompress_thread_ct, FILE* ff, BgzfRawDecompressStream* bgzf_st_ptr, BgzfRawMtDecompressStream* bgzfp, const char** errmsgp) { |
| 366 |
PglErr reterr = kPglRetSuccess; |
| 367 |
{ |
| 368 |
PreinitBgzfRawMtStream(bgzfp); |
| 369 |
assert(decompress_thread_ct); |
| 370 |
if (decompress_thread_ct > kMaxBgzfDecompressThreads) { |
| 371 |
decompress_thread_ct = kMaxBgzfDecompressThreads; |
| 372 |
} |
| 373 |
BgzfMtReadBody* bodyp = &bgzfp->body; |
| 374 |
ZeroPtrArr(decompress_thread_ct, bodyp->ldcs); |
| 375 |
ThreadGroup* tgp = &bgzfp->tg; |
| 376 |
if (unlikely(SetThreadCt(decompress_thread_ct + 1, tgp))) { |
| 377 |
// May as well avoid these leaks. |
| 378 |
if (bgzf_st_ptr) { |
| 379 |
free(bgzf_st_ptr->in); |
| 380 |
libdeflate_free_decompressor(bgzf_st_ptr->ldc); |
| 381 |
} |
| 382 |
goto BgzfRawMtStreamInit_ret_NOMEM; |
| 383 |
} |
| 384 |
if (bgzf_st_ptr) { |
| 385 |
bodyp->in = bgzf_st_ptr->in; |
| 386 |
const uint32_t in_pos = bgzf_st_ptr->in_pos; |
| 387 |
const uint32_t initial_compressed_byte_ct = bgzf_st_ptr->in_size - in_pos; |
| 388 |
memmove(bodyp->in, &(bodyp->in[in_pos]), initial_compressed_byte_ct); |
| 389 |
bodyp->initial_compressed_byte_ct = initial_compressed_byte_ct; |
| 390 |
} else { |
| 391 |
bodyp->in = S_CAST(unsigned char*, malloc(kDecompressChunkSize)); |
| 392 |
if (unlikely(!bodyp->in)) { |
| 393 |
goto BgzfRawMtStreamInit_ret_NOMEM; |
| 394 |
} |
| 395 |
memcpy(bodyp->in, header, 16); |
| 396 |
bodyp->initial_compressed_byte_ct = 16; |
| 397 |
} |
| 398 |
for (uint32_t tidx = 0; tidx < decompress_thread_ct; ++tidx) { |
| 399 |
if ((!tidx) && bgzf_st_ptr) { |
| 400 |
bodyp->ldcs[0] = bgzf_st_ptr->ldc; |
| 401 |
} else { |
| 402 |
bodyp->ldcs[tidx] = libdeflate_alloc_decompressor(); |
| 403 |
if (!bodyp->ldcs[tidx]) { |
| 404 |
goto BgzfRawMtStreamInit_ret_NOMEM; |
| 405 |
} |
| 406 |
} |
| 407 |
} |
| 408 |
assert(!bodyp->cwr[0]); |
| 409 |
const uint32_t cwr_aligned_size = RoundUpPow2(sizeof(BgzfMtReadCommWithR), kCacheline); |
| 410 |
const uint32_t cwd_aligned_size = RoundUpPow2(sizeof(BgzfMtReadCommWithD), kCacheline); |
| 411 |
const uint32_t overflow_buf_size = kMaxBgzfDecompressedBlockSize * (decompress_thread_ct + 1); |
| 412 |
unsigned char* raw_alloc; |
| 413 |
if (unlikely(cachealigned_malloc(2 * (cwr_aligned_size + cwd_aligned_size + overflow_buf_size), &raw_alloc))) { |
| 414 |
goto BgzfRawMtStreamInit_ret_NOMEM; |
| 415 |
} |
| 416 |
bodyp->cwr[0] = R_CAST(BgzfMtReadCommWithR*, raw_alloc); |
| 417 |
raw_alloc = &(raw_alloc[cwr_aligned_size]); |
| 418 |
bodyp->cwr[1] = R_CAST(BgzfMtReadCommWithR*, raw_alloc); |
| 419 |
raw_alloc = &(raw_alloc[cwr_aligned_size]); |
| 420 |
bodyp->cwd[0] = R_CAST(BgzfMtReadCommWithD*, raw_alloc); |
| 421 |
raw_alloc = &(raw_alloc[cwd_aligned_size]); |
| 422 |
bodyp->cwd[1] = R_CAST(BgzfMtReadCommWithD*, raw_alloc); |
| 423 |
raw_alloc = &(raw_alloc[cwd_aligned_size]); |
| 424 |
bodyp->cwd[0]->overflow = &(raw_alloc[kMaxBgzfDecompressedBlockSize]); |
| 425 |
raw_alloc = &(raw_alloc[overflow_buf_size]); |
| 426 |
bodyp->cwd[1]->overflow = &(raw_alloc[kMaxBgzfDecompressedBlockSize]); |
| 427 |
// raw_alloc = &(raw_alloc[overflow_buf_size]); |
| 428 |
|
| 429 |
bodyp->ff = ff; |
| 430 |
for (uint32_t parity = 0; parity != 2; ++parity) { |
| 431 |
bodyp->cwr[parity]->errmsg = nullptr; |
| 432 |
bodyp->cwr[parity]->reterr = kPglRetSuccess; |
| 433 |
bodyp->cwr[parity]->locked_start = 0; |
| 434 |
bodyp->cwr[parity]->locked_end = 0; |
| 435 |
bodyp->cwd[parity]->invalid_bgzf = 0; |
| 436 |
bodyp->cwd[parity]->target_capacity = 0; |
| 437 |
bodyp->cwd[parity]->target = nullptr; |
| 438 |
ZeroU32Arr(kMaxBgzfDecompressThreads + 1, bodyp->cwd[parity]->in_offsets); |
| 439 |
// out_offsets doesn't matter when in_offsets is zeroed |
| 440 |
} |
| 441 |
|
| 442 |
SetThreadFuncAndData(BgzfRawMtStreamThread, bgzfp, tgp); |
| 443 |
if (unlikely(SpawnThreads(tgp))) { |
| 444 |
goto BgzfRawMtStreamInit_ret_THREAD_CREATE_FAIL; |
| 445 |
} |
| 446 |
bgzfp->overflow_start[0] = 0; |
| 447 |
bgzfp->overflow_start[1] = 0; |
| 448 |
bgzfp->overflow_end[0] = 0; |
| 449 |
bgzfp->overflow_end[1] = 0; |
| 450 |
bgzfp->consumer_parity = 1; |
| 451 |
bgzfp->eof = 0; |
| 452 |
|
| 453 |
// Bottleneck is usually decompression, so we want it to be happening in |
| 454 |
// the background when BgzfRawMtStreamInit() returns. This |
| 455 |
// currently requires a join-and-respawn. |
| 456 |
reterr = BgzfReadJoinAndRespawn(nullptr, bgzfp, nullptr, errmsgp); |
| 457 |
} |
| 458 |
while (0) { |
| 459 |
BgzfRawMtStreamInit_ret_NOMEM: |
| 460 |
reterr = kPglRetNomem; |
| 461 |
break; |
| 462 |
BgzfRawMtStreamInit_ret_THREAD_CREATE_FAIL: |
| 463 |
reterr = kPglRetThreadCreateFail; |
| 464 |
break; |
| 465 |
} |
| 466 |
return reterr; |
| 467 |
} |
| 468 |
|
| 469 |
PglErr BgzfRawMtStreamRead(unsigned char* dst_end, BgzfRawMtDecompressStream* bgzfp, unsigned char** dst_iterp, const char** errmsgp) { |
| 470 |
const uint32_t consumer_parity = bgzfp->consumer_parity; |
| 471 |
const uint32_t overflow_start = bgzfp->overflow_start[consumer_parity]; |
| 472 |
const uint32_t overflow_end = bgzfp->overflow_end[consumer_parity]; |
| 473 |
const uint32_t overflow_remaining = overflow_end - overflow_start; |
| 474 |
const uintptr_t dst_capacity = dst_end - (*dst_iterp); |
| 475 |
unsigned char* overflow_src_start = &(bgzfp->body.cwd[consumer_parity]->overflow[overflow_start]); |
| 476 |
if (overflow_remaining >= dst_capacity) { |
| 477 |
memcpy(*dst_iterp, overflow_src_start, dst_capacity); |
| 478 |
bgzfp->overflow_start[consumer_parity] += dst_capacity; |
| 479 |
*dst_iterp = dst_end; |
| 480 |
return kPglRetSuccess; |
| 481 |
} |
| 482 |
bgzfp->overflow_start[consumer_parity] += overflow_remaining; |
| 483 |
*dst_iterp = memcpyua(*dst_iterp, overflow_src_start, overflow_remaining); |
| 484 |
if (bgzfp->eof) { |
| 485 |
return kPglRetSuccess; |
| 486 |
} |
| 487 |
return BgzfReadJoinAndRespawn(dst_end, bgzfp, dst_iterp, errmsgp); |
| 488 |
} |
| 489 |
|
| 490 |
PglErr BgzfRawMtStreamRetarget(const char* header, BgzfRawMtDecompressStream* bgzfp, FILE* next_ff, const char** errmsgp) { |
| 491 |
BgzfMtReadBody* bodyp = &bgzfp->body; |
| 492 |
ThreadGroup* tgp = &bgzfp->tg; |
| 493 |
if (!bgzfp->eof) { |
| 494 |
JoinThreads(tgp); |
| 495 |
const uint32_t prev_producer_parity = 1 - bgzfp->consumer_parity; |
| 496 |
BgzfMtReadCommWithD* prev_cwd = bodyp->cwd[prev_producer_parity]; |
| 497 |
if (unlikely(prev_cwd->invalid_bgzf)) { |
| 498 |
*errmsgp = kShortErrInvalidBgzf; |
| 499 |
return kPglRetDecompressFail; |
| 500 |
} |
| 501 |
BgzfMtReadCommWithR* prev_cwr = bodyp->cwr[prev_producer_parity]; |
| 502 |
if (unlikely(prev_cwr->reterr != kPglRetSuccess)) { |
| 503 |
*errmsgp = prev_cwr->errmsg; |
| 504 |
return S_CAST(PglErr, prev_cwr->reterr); |
| 505 |
} |
| 506 |
bgzfp->consumer_parity = prev_producer_parity; |
| 507 |
} |
| 508 |
const uint32_t next_producer_parity = 1 - bgzfp->consumer_parity; |
| 509 |
for (uint32_t parity = 0; parity != 2; ++parity) { |
| 510 |
bodyp->cwr[parity]->locked_start = 0; |
| 511 |
bodyp->cwr[parity]->locked_end = 0; |
| 512 |
bodyp->cwd[parity]->target_capacity = 0; |
| 513 |
bodyp->cwd[parity]->target = nullptr; |
| 514 |
ZeroU32Arr(kMaxBgzfDecompressThreads + 1, bodyp->cwd[parity]->in_offsets); |
| 515 |
// bugfix (3 Oct 2019): forgot this |
| 516 |
bgzfp->overflow_start[parity] = 0; |
| 517 |
bgzfp->overflow_end[parity] = 0; |
| 518 |
} |
| 519 |
BgzfMtReadCommWithR* next_cwr = bodyp->cwr[next_producer_parity]; |
| 520 |
next_cwr->locked_start = kBgzfRawMtStreamRetargetCode; |
| 521 |
if (next_ff == nullptr) { |
| 522 |
rewind(bodyp->ff); |
| 523 |
// bugfix (8 Feb 2020): need to explicitly read the first 16 bytes. |
| 524 |
if (unlikely(!fread_unlocked(bodyp->in, 16, 1, bodyp->ff))) { |
| 525 |
return kPglRetRewindFail; |
| 526 |
} |
| 527 |
} else { |
| 528 |
// Caller is responsible for closing previous bodyp->ff, etc. |
| 529 |
bodyp->ff = next_ff; |
| 530 |
// bugfix (5 Oct 2019): forgot this |
| 531 |
memcpy(bodyp->in, header, 16); |
| 532 |
} |
| 533 |
SpawnThreads(tgp); |
| 534 |
bgzfp->eof = 0; |
| 535 |
// Turn the crank once, for the same reason we do so during stream creation. |
| 536 |
return BgzfReadJoinAndRespawn(nullptr, bgzfp, nullptr, errmsgp); |
| 537 |
} |
| 538 |
|
| 539 |
void CleanupBgzfRawMtStream(BgzfRawMtDecompressStream* bgzfp) { |
| 540 |
uint32_t decompress_thread_ct = GetThreadCtTg(&bgzfp->tg); |
| 541 |
if (decompress_thread_ct) { |
| 542 |
--decompress_thread_ct; |
| 543 |
} |
| 544 |
CleanupThreads(&bgzfp->tg); |
| 545 |
BgzfMtReadBody* bodyp = &bgzfp->body; |
| 546 |
for (uint32_t tidx = 0; tidx < decompress_thread_ct; ++tidx) { |
| 547 |
if (bodyp->ldcs[tidx]) { |
| 548 |
libdeflate_free_decompressor(bodyp->ldcs[tidx]); |
| 549 |
} |
| 550 |
} |
| 551 |
if (bodyp->in) { |
| 552 |
free(bodyp->in); |
| 553 |
bodyp->in = nullptr; |
| 554 |
} |
| 555 |
if (bodyp->cwr[0]) { |
| 556 |
aligned_free(bodyp->cwr[0]); |
| 557 |
bodyp->cwr[0] = nullptr; |
| 558 |
} |
| 559 |
} |
| 560 |
|
| 561 |
|
| 562 |
void PreinitBgzfCompressStream(BgzfCompressStream* cstream_ptr) { |
| 563 |
BgzfCompressStreamMain* bgzfp = GetBgzfp(cstream_ptr); |
| 564 |
bgzfp->ff = nullptr; |
| 565 |
bgzfp->threads = nullptr; |
| 566 |
} |
| 567 |
|
| 568 |
static const unsigned char kBgzfEofBlock[] = "\37\213\10\4\0\0\0\0\0\377\6\0\102\103\2\0\33\0\3\0\0\0\0\0\0\0\0"; |
| 569 |
|
| 570 |
THREAD_FUNC_DECL BgzfCompressorThread(void* raw_arg) { |
| 571 |
BgzfCompressorContext* context = S_CAST(BgzfCompressorContext*, raw_arg); |
| 572 |
struct libdeflate_compressor* compressor = context->lc; |
| 573 |
BgzfCompressStreamMain* bgzfp = context->parent; |
| 574 |
const uint32_t slot_mask = bgzfp->slot_ct - 1; |
| 575 |
BgzfCompressCommWithP** cwps = bgzfp->cwps; |
| 576 |
BgzfCompressCommWithW** cwws = bgzfp->cwws; |
| 577 |
uintptr_t* next_job_idxp = bgzfp->next_job_idxp; |
| 578 |
while (1) { |
| 579 |
const uint32_t slot_idx = __atomic_fetch_add(next_job_idxp, 1, __ATOMIC_ACQ_REL) & slot_mask; |
| 580 |
BgzfCompressCommWithP* cwp = cwps[slot_idx]; |
| 581 |
BgzfCompressCommWithW* cww = cwws[slot_idx]; |
| 582 |
#ifdef _WIN32 |
| 583 |
HANDLE wait_pair[2]; |
| 584 |
wait_pair[0] = cwp->ucbuf_filled_event; |
| 585 |
wait_pair[1] = cww->cbuf_open_event; |
| 586 |
WaitForMultipleObjects(2, wait_pair, 1, INFINITE); |
| 587 |
#else |
| 588 |
pthread_mutex_lock(&(cww->cbuf_mutex)); |
| 589 |
while (cww->nbytes != UINT32_MAX) { |
| 590 |
pthread_cond_wait(&(cww->cbuf_condvar), &(cww->cbuf_mutex)); |
| 591 |
} |
| 592 |
pthread_mutex_lock(&(cwp->ucbuf_mutex)); |
| 593 |
while (cwp->nbytes == UINT32_MAX) { |
| 594 |
pthread_cond_wait(&(cwp->ucbuf_condvar), &(cwp->ucbuf_mutex)); |
| 595 |
} |
| 596 |
// hold both mutexes during compress operation |
| 597 |
#endif |
| 598 |
uint32_t src_byte_ct = cwp->nbytes; |
| 599 |
uint32_t nwrite = 0; |
| 600 |
if (src_byte_ct) { |
| 601 |
char* src = cwp->ucbuf; |
| 602 |
// 0..15 = prefilled header |
| 603 |
// 16..17 = compressed size + 25 |
| 604 |
// 18..(compressed size + 17) = compressed data |
| 605 |
// (compressed size + 18..21) = crc32 |
| 606 |
// (compressed size + 22..25) = src_byte_ct |
| 607 |
unsigned char* dst = cww->cbuf; |
| 608 |
uint16_t bsize = libdeflate_deflate_compress(compressor, src, src_byte_ct, &(dst[18]), kMaxBgzfCompressedBlockSize - 26) + 25; |
| 609 |
const uint32_t crc = libdeflate_crc32(0, src, src_byte_ct); |
| 610 |
memcpy(&(dst[16]), &bsize, 2); |
| 611 |
memcpy(&(dst[bsize - 7]), &crc, 4); |
| 612 |
memcpy(&(dst[bsize - 3]), &src_byte_ct, 4); |
| 613 |
nwrite = S_CAST(uint32_t, bsize) + 1; |
| 614 |
} |
| 615 |
cww->nbytes = nwrite; |
| 616 |
const uint32_t eof = cwp->eof; |
| 617 |
cww->eof = eof; |
| 618 |
cwp->nbytes = UINT32_MAX; |
| 619 |
#ifdef _WIN32 |
| 620 |
SetEvent(cwp->ucbuf_open_event); |
| 621 |
SetEvent(cww->cbuf_filled_event); |
| 622 |
#else |
| 623 |
pthread_cond_signal(&(cwp->ucbuf_condvar)); |
| 624 |
pthread_mutex_unlock(&(cwp->ucbuf_mutex)); |
| 625 |
pthread_cond_signal(&(cww->cbuf_condvar)); |
| 626 |
pthread_mutex_unlock(&(cww->cbuf_mutex)); |
| 627 |
#endif |
| 628 |
if (eof) { |
| 629 |
THREAD_RETURN; |
| 630 |
} |
| 631 |
} |
| 632 |
} |
| 633 |
|
| 634 |
THREAD_FUNC_DECL BgzfCompressWriterThread(void* raw_arg) { |
| 635 |
BgzfCompressStreamMain* context = S_CAST(BgzfCompressStreamMain*, raw_arg); |
| 636 |
const uint32_t slot_ct = context->slot_ct; |
| 637 |
FILE* ff = context->ff; |
| 638 |
BgzfCompressCommWithW** cwws = context->cwws; |
| 639 |
for (uint32_t slot_idx = 0; ; ++slot_idx) { |
| 640 |
if (slot_idx == slot_ct) { |
| 641 |
slot_idx = 0; |
| 642 |
} |
| 643 |
BgzfCompressCommWithW* cww = cwws[slot_idx]; |
| 644 |
#ifdef _WIN32 |
| 645 |
WaitForSingleObject(cww->cbuf_filled_event, INFINITE); |
| 646 |
#else |
| 647 |
pthread_mutex_lock(&(cww->cbuf_mutex)); |
| 648 |
while (cww->nbytes == UINT32_MAX) { |
| 649 |
pthread_cond_wait(&(cww->cbuf_condvar), &(cww->cbuf_mutex)); |
| 650 |
} |
| 651 |
// hold mutex during write operation |
| 652 |
#endif |
| 653 |
if (ff) { |
| 654 |
const uint32_t nbytes = cww->nbytes; |
| 655 |
if (nbytes) { |
| 656 |
if (unlikely(!fwrite_unlocked(cww->cbuf, nbytes, 1, ff))) { |
| 657 |
context->write_errno = errno; |
| 658 |
fclose(ff); |
| 659 |
ff = nullptr; |
| 660 |
context->ff = nullptr; |
| 661 |
} |
| 662 |
} |
| 663 |
} |
| 664 |
const uint32_t eof = cww->eof; |
| 665 |
cww->nbytes = UINT32_MAX; |
| 666 |
#ifdef _WIN32 |
| 667 |
SetEvent(cww->cbuf_open_event); |
| 668 |
#else |
| 669 |
pthread_cond_signal(&(cww->cbuf_condvar)); |
| 670 |
pthread_mutex_unlock(&(cww->cbuf_mutex)); |
| 671 |
#endif |
| 672 |
if (eof) { |
| 673 |
if (ff) { |
| 674 |
if (unlikely(!fwrite_unlocked(kBgzfEofBlock, 28, 1, ff))) { |
| 675 |
context->write_errno = errno; |
| 676 |
} |
| 677 |
fclose(ff); |
| 678 |
ff = nullptr; |
| 679 |
context->ff = nullptr; |
| 680 |
} |
| 681 |
THREAD_RETURN; |
| 682 |
} |
| 683 |
} |
| 684 |
} |
| 685 |
|
| 686 |
// smallest power of 2 larger than kMaxBgzfCompressThreads * 4 |
| 687 |
CONSTI32(kMaxBgzfSlotCt, 64); |
| 688 |
static_assert(kMaxBgzfCompressThreads < 16, "InitBgzfCompressStreamEx and CleanupBgzfCompressStream must be updated."); |
| 689 |
|
| 690 |
PglErr InitBgzfCompressStreamEx(const char* out_fname, uint32_t do_append, uint32_t clvl, uint32_t compressor_thread_ct, BgzfCompressStream* cstream_ptr) { |
| 691 |
BgzfCompressStreamMain* bgzfp = GetBgzfp(cstream_ptr); |
| 692 |
if (bgzfp->ff || bgzfp->threads || (clvl > 12)) { |
| 693 |
// Unlike BgzfRawMtDecompressStream (which should be wrapped by |
| 694 |
// TextStream), this is designed for direct use in application code, so we |
| 695 |
// include defensive checks. |
| 696 |
return kPglRetImproperFunctionCall; |
| 697 |
} |
| 698 |
bgzfp->slot_ct = 0; |
| 699 |
bgzfp->ff = fopen(out_fname, do_append? FOPEN_AB : FOPEN_WB); |
| 700 |
if (unlikely(!bgzfp->ff)) { |
| 701 |
// slot_ct set to 0, so we'll immediately segfault on write attempt |
| 702 |
return kPglRetOpenFail; |
| 703 |
} |
| 704 |
if (!clvl) { |
| 705 |
bgzfp->write_errno = 0; |
| 706 |
return kPglRetSuccess; |
| 707 |
} |
| 708 |
if (compressor_thread_ct > kMaxBgzfCompressThreads) { |
| 709 |
compressor_thread_ct = kMaxBgzfCompressThreads; |
| 710 |
} else if (!compressor_thread_ct) { |
| 711 |
compressor_thread_ct = 1; |
| 712 |
} |
| 713 |
// smallest power of 2 >= (compressor_thread_ct * 4) |
| 714 |
const uint32_t slot_ct = 1 << bsru32(compressor_thread_ct * 8 - 1); |
| 715 |
bgzfp->slot_ct = slot_ct; |
| 716 |
bgzfp->compressor_thread_ct = compressor_thread_ct; |
| 717 |
bgzfp->write_errno = -1; // in case of initialization failure early-exit |
| 718 |
|
| 719 |
const uintptr_t ptrs_aligned_size = RoundUpPow2((compressor_thread_ct + 1 + 2 * slot_ct) * sizeof(intptr_t), kCacheline); |
| 720 |
const uintptr_t compressor_args_aligned_size = RoundUpPow2(compressor_thread_ct * sizeof(BgzfCompressorContext), kCacheline); |
| 721 |
const uintptr_t cwp_aligned_size = RoundUpPow2(sizeof(BgzfCompressCommWithP), kCacheline); |
| 722 |
const uintptr_t cww_aligned_size = RoundUpPow2(sizeof(BgzfCompressCommWithW), kCacheline); |
| 723 |
unsigned char* raw_alloc; |
| 724 |
if (cachealigned_malloc(ptrs_aligned_size + compressor_args_aligned_size + kCacheline + slot_ct * (cwp_aligned_size + cww_aligned_size), &raw_alloc)) { |
| 725 |
return kPglRetNomem; |
| 726 |
} |
| 727 |
bgzfp->threads = R_CAST(pthread_t*, raw_alloc); |
| 728 |
ZeroPtrArr(compressor_thread_ct + 1 + 2 * slot_ct, bgzfp->threads); |
| 729 |
bgzfp->cwps = R_CAST(BgzfCompressCommWithP**, &(bgzfp->threads[compressor_thread_ct + 1])); |
| 730 |
bgzfp->cwws = R_CAST(BgzfCompressCommWithW**, &(bgzfp->cwps[slot_ct])); |
| 731 |
raw_alloc = &(raw_alloc[ptrs_aligned_size]); |
| 732 |
|
| 733 |
bgzfp->compressor_args = R_CAST(BgzfCompressorContext*, raw_alloc); |
| 734 |
raw_alloc = &(raw_alloc[compressor_args_aligned_size]); |
| 735 |
|
| 736 |
bgzfp->next_job_idxp = R_CAST(uintptr_t*, raw_alloc); |
| 737 |
raw_alloc = &(raw_alloc[kCacheline]); |
| 738 |
|
| 739 |
for (uint32_t slot_idx = 0; slot_idx != slot_ct; ++slot_idx) { |
| 740 |
BgzfCompressCommWithP* cwp = R_CAST(BgzfCompressCommWithP*, raw_alloc); |
| 741 |
bgzfp->cwps[slot_idx] = cwp; |
| 742 |
raw_alloc = &(raw_alloc[cwp_aligned_size]); |
| 743 |
|
| 744 |
#ifdef _WIN32 |
| 745 |
HANDLE new_event = CreateEvent(nullptr, FALSE, FALSE, nullptr); |
| 746 |
if (unlikely(!new_event)) { |
| 747 |
bgzfp->unfinished_init_state = (slot_idx << 3) | 1; |
| 748 |
return kPglRetThreadCreateFail; |
| 749 |
} |
| 750 |
cwp->ucbuf_filled_event = new_event; |
| 751 |
|
| 752 |
new_event = CreateEvent(nullptr, FALSE, slot_idx? TRUE : FALSE, nullptr); |
| 753 |
if (unlikely(!new_event)) { |
| 754 |
bgzfp->unfinished_init_state = (slot_idx << 3) | 2; |
| 755 |
return kPglRetThreadCreateFail; |
| 756 |
} |
| 757 |
cwp->ucbuf_open_event = new_event; |
| 758 |
#else |
| 759 |
if (unlikely(pthread_mutex_init(&cwp->ucbuf_mutex, nullptr))) { |
| 760 |
bgzfp->unfinished_init_state = (slot_idx << 3) | 1; |
| 761 |
return kPglRetThreadCreateFail; |
| 762 |
} |
| 763 |
if (unlikely(pthread_cond_init(&cwp->ucbuf_condvar, nullptr))) { |
| 764 |
bgzfp->unfinished_init_state = (slot_idx << 3) | 2; |
| 765 |
return kPglRetThreadCreateFail; |
| 766 |
} |
| 767 |
#endif |
| 768 |
cwp->nbytes = UINT32_MAX; |
| 769 |
cwp->eof = 0; |
| 770 |
|
| 771 |
BgzfCompressCommWithW* cww = R_CAST(BgzfCompressCommWithW*, raw_alloc); |
| 772 |
bgzfp->cwws[slot_idx] = cww; |
| 773 |
raw_alloc = &(raw_alloc[cww_aligned_size]); |
| 774 |
#ifdef _WIN32 |
| 775 |
new_event = CreateEvent(nullptr, FALSE, FALSE, nullptr); |
| 776 |
if (unlikely(!new_event)) { |
| 777 |
bgzfp->unfinished_init_state = (slot_idx << 3) | 3; |
| 778 |
return kPglRetThreadCreateFail; |
| 779 |
} |
| 780 |
cww->cbuf_filled_event = new_event; |
| 781 |
new_event = CreateEvent(nullptr, FALSE, TRUE, nullptr); |
| 782 |
if (unlikely(!new_event)) { |
| 783 |
bgzfp->unfinished_init_state = (slot_idx << 3) | 4; |
| 784 |
return kPglRetThreadCreateFail; |
| 785 |
} |
| 786 |
cww->cbuf_open_event = new_event; |
| 787 |
#else |
| 788 |
if (unlikely(pthread_mutex_init(&cww->cbuf_mutex, nullptr))) { |
| 789 |
bgzfp->unfinished_init_state = (slot_idx << 3) | 3; |
| 790 |
return kPglRetThreadCreateFail; |
| 791 |
} |
| 792 |
if (unlikely(pthread_cond_init(&cww->cbuf_condvar, nullptr))) { |
| 793 |
bgzfp->unfinished_init_state = (slot_idx << 3) | 4; |
| 794 |
return kPglRetThreadCreateFail; |
| 795 |
} |
| 796 |
#endif |
| 797 |
memcpy(cww->cbuf, kBgzfEofBlock, 16); |
| 798 |
cww->nbytes = UINT32_MAX; |
| 799 |
cww->eof = 0; |
| 800 |
} |
| 801 |
|
| 802 |
for (uint32_t tidx = 0; tidx != compressor_thread_ct; ++tidx) { |
| 803 |
struct libdeflate_compressor* lc = libdeflate_alloc_compressor(clvl); |
| 804 |
if (unlikely(!lc)) { |
| 805 |
bgzfp->unfinished_init_state = (kMaxBgzfSlotCt << 3) | tidx; |
| 806 |
return kPglRetNomem; |
| 807 |
} |
| 808 |
bgzfp->compressor_args[tidx].parent = bgzfp; |
| 809 |
bgzfp->compressor_args[tidx].lc = lc; |
| 810 |
} |
| 811 |
*(bgzfp->next_job_idxp) = 0; |
| 812 |
bgzfp->partial_slot_idx = 0; |
| 813 |
bgzfp->partial_nbytes = 0; |
| 814 |
#ifndef _WIN32 |
| 815 |
# ifndef __cplusplus |
| 816 |
pthread_attr_t smallstack_thread_attr; |
| 817 |
if (unlikely(pthread_attr_init(&smallstack_thread_attr))) { |
| 818 |
bgzfp->unfinished_init_state = (kMaxBgzfSlotCt << 3); |
| 819 |
return kPglRetThreadCreateFail; |
| 820 |
} |
| 821 |
# endif |
| 822 |
#endif |
| 823 |
for (uint32_t tidx = 0; tidx != compressor_thread_ct; ++tidx) { |
| 824 |
#ifdef _WIN32 |
| 825 |
bgzfp->threads[tidx] = R_CAST(HANDLE, _beginthreadex(nullptr, kDefaultThreadStack, BgzfCompressorThread, &(bgzfp->compressor_args[tidx]), 0, nullptr)); |
| 826 |
if (unlikely(!bgzfp->threads[tidx])) { |
| 827 |
bgzfp->unfinished_init_state = (kMaxBgzfSlotCt << 4) | tidx; |
| 828 |
return kPglRetThreadCreateFail; |
| 829 |
} |
| 830 |
#else |
| 831 |
# ifdef __cplusplus |
| 832 |
if (unlikely(pthread_create(&(bgzfp->threads[tidx]), |
| 833 |
&g_thread_startup.smallstack_thread_attr, |
| 834 |
BgzfCompressorThread, &(bgzfp->compressor_args[tidx])))) { |
| 835 |
bgzfp->unfinished_init_state = (kMaxBgzfSlotCt << 4) | tidx; |
| 836 |
return kPglRetThreadCreateFail; |
| 837 |
} |
| 838 |
# else |
| 839 |
if (unlikely(pthread_create(&(bgzfp->threads[tidx]), |
| 840 |
&smallstack_thread_attr, |
| 841 |
BgzfCompressorThread, &(bgzfp->compressor_args[tidx])))) { |
| 842 |
pthread_attr_destroy(&smallstack_thread_attr); |
| 843 |
bgzfp->unfinished_init_state = (kMaxBgzfSlotCt << 4) | tidx; |
| 844 |
return kPglRetThreadCreateFail; |
| 845 |
} |
| 846 |
# endif |
| 847 |
#endif |
| 848 |
} |
| 849 |
#ifdef _WIN32 |
| 850 |
bgzfp->threads[compressor_thread_ct] = R_CAST(HANDLE, _beginthreadex(nullptr, kDefaultThreadStack, BgzfCompressWriterThread, bgzfp, 0, nullptr)); |
| 851 |
if (unlikely(!bgzfp->threads[compressor_thread_ct])) { |
| 852 |
bgzfp->unfinished_init_state = (kMaxBgzfSlotCt << 4) | compressor_thread_ct; |
| 853 |
return kPglRetThreadCreateFail; |
| 854 |
} |
| 855 |
#else |
| 856 |
# ifdef __cplusplus |
| 857 |
if (unlikely(pthread_create(&(bgzfp->threads[compressor_thread_ct]), |
| 858 |
&g_thread_startup.smallstack_thread_attr, |
| 859 |
BgzfCompressWriterThread, bgzfp))) { |
| 860 |
bgzfp->unfinished_init_state = (kMaxBgzfSlotCt << 4) | compressor_thread_ct; |
| 861 |
return kPglRetThreadCreateFail; |
| 862 |
} |
| 863 |
# else |
| 864 |
if (unlikely(pthread_create(&(bgzfp->threads[compressor_thread_ct]), |
| 865 |
&smallstack_thread_attr, |
| 866 |
BgzfCompressWriterThread, bgzfp))) { |
| 867 |
pthread_attr_destroy(&smallstack_thread_attr); |
| 868 |
bgzfp->unfinished_init_state = (kMaxBgzfSlotCt << 4) | compressor_thread_ct; |
| 869 |
return kPglRetThreadCreateFail; |
| 870 |
} |
| 871 |
pthread_attr_destroy(&smallstack_thread_attr); |
| 872 |
# endif |
| 873 |
#endif |
| 874 |
bgzfp->write_errno = 0; |
| 875 |
bgzfp->unfinished_init_state = 0; |
| 876 |
return kPglRetSuccess; |
| 877 |
} |
| 878 |
|
| 879 |
BoolErr BgzfWrite(const char* buf, uintptr_t len, BgzfCompressStream* cstream_ptr) { |
| 880 |
BgzfCompressStreamMain* bgzfp = GetBgzfp(cstream_ptr); |
| 881 |
const uint32_t slot_ct = bgzfp->slot_ct; |
| 882 |
if (!slot_ct) { |
| 883 |
// No compression. |
| 884 |
if (unlikely(fwrite_checked(buf, len, bgzfp->ff))) { |
| 885 |
// If caller ignores error-return and keeps trying to write, force |
| 886 |
// segfault instead of silently proceeding. |
| 887 |
fclose(bgzfp->ff); |
| 888 |
bgzfp->ff = nullptr; |
| 889 |
return 1; |
| 890 |
} |
| 891 |
return 0; |
| 892 |
} |
| 893 |
if (bgzfp->write_errno) { |
| 894 |
errno = bgzfp->write_errno; |
| 895 |
return 1; |
| 896 |
} |
| 897 |
uint32_t slot_idx = bgzfp->partial_slot_idx; |
| 898 |
BgzfCompressCommWithP* cwp = bgzfp->cwps[slot_idx]; |
| 899 |
uint32_t dst_offset = bgzfp->partial_nbytes; |
| 900 |
while (dst_offset + len >= kBgzfInputBlockSize) { |
| 901 |
const uint32_t ncopy = kBgzfInputBlockSize - dst_offset; |
| 902 |
memcpy(&(cwp->ucbuf[dst_offset]), buf, ncopy); |
| 903 |
#ifdef _WIN32 |
| 904 |
cwp->nbytes = kBgzfInputBlockSize; |
| 905 |
SetEvent(cwp->ucbuf_filled_event); |
| 906 |
#else |
| 907 |
pthread_mutex_lock(&(cwp->ucbuf_mutex)); |
| 908 |
cwp->nbytes = kBgzfInputBlockSize; |
| 909 |
pthread_cond_signal(&(cwp->ucbuf_condvar)); |
| 910 |
pthread_mutex_unlock(&(cwp->ucbuf_mutex)); |
| 911 |
#endif |
| 912 |
if (++slot_idx == slot_ct) { |
| 913 |
slot_idx = 0; |
| 914 |
} |
| 915 |
cwp = bgzfp->cwps[slot_idx]; |
| 916 |
#ifdef _WIN32 |
| 917 |
WaitForSingleObject(cwp->ucbuf_open_event, INFINITE); |
| 918 |
#else |
| 919 |
pthread_mutex_lock(&(cwp->ucbuf_mutex)); |
| 920 |
while (cwp->nbytes != UINT32_MAX) { |
| 921 |
pthread_cond_wait(&(cwp->ucbuf_condvar), &(cwp->ucbuf_mutex)); |
| 922 |
} |
| 923 |
pthread_mutex_unlock(&(cwp->ucbuf_mutex)); |
| 924 |
#endif |
| 925 |
if (bgzfp->write_errno) { |
| 926 |
errno = bgzfp->write_errno; |
| 927 |
bgzfp->partial_slot_idx = slot_idx; |
| 928 |
bgzfp->partial_nbytes = 0; |
| 929 |
return 1; |
| 930 |
} |
| 931 |
len -= ncopy; |
| 932 |
buf = &(buf[ncopy]); |
| 933 |
dst_offset = 0; |
| 934 |
} |
| 935 |
memcpy(&(cwp->ucbuf[dst_offset]), buf, len); |
| 936 |
bgzfp->partial_slot_idx = slot_idx; |
| 937 |
bgzfp->partial_nbytes = dst_offset + len; |
| 938 |
return 0; |
| 939 |
} |
| 940 |
|
| 941 |
BoolErr BgzfFlushTry(uint32_t capacity_needed_to_defer_flush, BgzfCompressStream* cstream_ptr) { |
| 942 |
BgzfCompressStreamMain* bgzfp = GetBgzfp(cstream_ptr); |
| 943 |
const uint32_t slot_ct = bgzfp->slot_ct; |
| 944 |
if (!slot_ct) { |
| 945 |
// No compression. |
| 946 |
return 0; |
| 947 |
} |
| 948 |
if (bgzfp->write_errno) { |
| 949 |
errno = bgzfp->write_errno; |
| 950 |
return 1; |
| 951 |
} |
| 952 |
uint32_t slot_idx = bgzfp->partial_slot_idx; |
| 953 |
BgzfCompressCommWithP* cwp = bgzfp->cwps[slot_idx]; |
| 954 |
uint32_t dst_offset = bgzfp->partial_nbytes; |
| 955 |
if (dst_offset + capacity_needed_to_defer_flush <= kBgzfInputBlockSize) { |
| 956 |
return 0; |
| 957 |
} |
| 958 |
#ifdef _WIN32 |
| 959 |
cwp->nbytes = dst_offset; |
| 960 |
SetEvent(cwp->ucbuf_filled_event); |
| 961 |
#else |
| 962 |
pthread_mutex_lock(&(cwp->ucbuf_mutex)); |
| 963 |
cwp->nbytes = dst_offset; |
| 964 |
pthread_cond_signal(&(cwp->ucbuf_condvar)); |
| 965 |
pthread_mutex_unlock(&(cwp->ucbuf_mutex)); |
| 966 |
#endif |
| 967 |
if (++slot_idx == slot_ct) { |
| 968 |
slot_idx = 0; |
| 969 |
} |
| 970 |
cwp = bgzfp->cwps[slot_idx]; |
| 971 |
#ifdef _WIN32 |
| 972 |
WaitForSingleObject(cwp->ucbuf_open_event, INFINITE); |
| 973 |
#else |
| 974 |
pthread_mutex_lock(&(cwp->ucbuf_mutex)); |
| 975 |
while (cwp->nbytes != UINT32_MAX) { |
| 976 |
pthread_cond_wait(&(cwp->ucbuf_condvar), &(cwp->ucbuf_mutex)); |
| 977 |
} |
| 978 |
pthread_mutex_unlock(&(cwp->ucbuf_mutex)); |
| 979 |
#endif |
| 980 |
bgzfp->partial_slot_idx = slot_idx; |
| 981 |
bgzfp->partial_nbytes = 0; |
| 982 |
if (bgzfp->write_errno) { |
| 983 |
errno = bgzfp->write_errno; |
| 984 |
return 1; |
| 985 |
} |
| 986 |
return 0; |
| 987 |
} |
| 988 |
|
| 989 |
BoolErr CleanupBgzfCompressStream(BgzfCompressStream* cstream_ptr, PglErr* reterrp) { |
| 990 |
BgzfCompressStreamMain* bgzfp = GetBgzfp(cstream_ptr); |
| 991 |
pthread_t* threads = bgzfp->threads; |
| 992 |
if (threads) { |
| 993 |
uint32_t slot_ct = bgzfp->slot_ct; |
| 994 |
const uint32_t unfinished_init = bgzfp->unfinished_init_state; |
| 995 |
if ((!unfinished_init) || (unfinished_init >= (kMaxBgzfSlotCt << 3))) { |
| 996 |
const uint32_t cthread_ct = bgzfp->compressor_thread_ct; |
| 997 |
uint32_t launched_cthread_ct = 0; |
| 998 |
uint32_t launched_thread_ct = 0; |
| 999 |
if (!unfinished_init) { |
| 1000 |
launched_cthread_ct = cthread_ct; |
| 1001 |
launched_thread_ct = cthread_ct + 1; |
| 1002 |
} else if (unfinished_init >= (kMaxBgzfSlotCt << 4)) { |
| 1003 |
launched_cthread_ct = unfinished_init - (kMaxBgzfSlotCt << 4); |
| 1004 |
launched_thread_ct = launched_cthread_ct; |
| 1005 |
} |
| 1006 |
if (launched_cthread_ct) { |
| 1007 |
uint32_t slot_idx = bgzfp->partial_slot_idx; |
| 1008 |
uint32_t slot_idx_stop = slot_idx + launched_cthread_ct; |
| 1009 |
if (slot_idx_stop >= slot_ct) { |
| 1010 |
slot_idx_stop -= slot_ct; |
| 1011 |
} |
| 1012 |
uint32_t nbytes = bgzfp->partial_nbytes; |
| 1013 |
BgzfCompressCommWithP* cwp = bgzfp->cwps[slot_idx]; |
| 1014 |
do { |
| 1015 |
// ok to send nbytes > 0 even in error-return case: the precise value |
| 1016 |
// will be ignored, the worker will just see that it's less than |
| 1017 |
// kBgzfInputBlockSize and return |
| 1018 |
#ifdef _WIN32 |
| 1019 |
cwp->nbytes = nbytes; |
| 1020 |
cwp->eof = 1; |
| 1021 |
SetEvent(cwp->ucbuf_filled_event); |
| 1022 |
#else |
| 1023 |
pthread_mutex_lock(&(cwp->ucbuf_mutex)); |
| 1024 |
cwp->nbytes = nbytes; |
| 1025 |
cwp->eof = 1; |
| 1026 |
pthread_cond_signal(&(cwp->ucbuf_condvar)); |
| 1027 |
pthread_mutex_unlock(&(cwp->ucbuf_mutex)); |
| 1028 |
#endif |
| 1029 |
if (++slot_idx == slot_ct) { |
| 1030 |
slot_idx = 0; |
| 1031 |
} |
| 1032 |
cwp = bgzfp->cwps[slot_idx]; |
| 1033 |
#ifdef _WIN32 |
| 1034 |
WaitForSingleObject(cwp->ucbuf_open_event, INFINITE); |
| 1035 |
#else |
| 1036 |
pthread_mutex_lock(&(cwp->ucbuf_mutex)); |
| 1037 |
while (cwp->nbytes != UINT32_MAX) { |
| 1038 |
pthread_cond_wait(&(cwp->ucbuf_condvar), &(cwp->ucbuf_mutex)); |
| 1039 |
} |
| 1040 |
pthread_mutex_unlock(&(cwp->ucbuf_mutex)); |
| 1041 |
#endif |
| 1042 |
nbytes = 0; |
| 1043 |
} while (slot_idx != slot_idx_stop); |
| 1044 |
#ifdef _WIN32 |
| 1045 |
WaitForAllObjects(launched_thread_ct, threads); |
| 1046 |
for (uint32_t tidx = 0; tidx != launched_thread_ct; ++tidx) { |
| 1047 |
CloseHandle(threads[tidx]); |
| 1048 |
} |
| 1049 |
#else |
| 1050 |
for (uint32_t tidx = 0; tidx != launched_thread_ct; ++tidx) { |
| 1051 |
pthread_join(threads[tidx], nullptr); |
| 1052 |
} |
| 1053 |
#endif |
| 1054 |
} |
| 1055 |
uint32_t compressor_ct = cthread_ct; |
| 1056 |
if (unfinished_init & (kMaxBgzfSlotCt << 3)) { |
| 1057 |
compressor_ct = unfinished_init - (kMaxBgzfSlotCt << 3); |
| 1058 |
} |
| 1059 |
for (uint32_t tidx = 0; tidx != compressor_ct; ++tidx) { |
| 1060 |
libdeflate_free_compressor(bgzfp->compressor_args[tidx].lc); |
| 1061 |
} |
| 1062 |
} else { |
| 1063 |
slot_ct = unfinished_init >> 3; |
| 1064 |
const uint32_t slot_partial_init = unfinished_init & 7; |
| 1065 |
do { |
| 1066 |
if (slot_partial_init == 1) { |
| 1067 |
break; |
| 1068 |
} |
| 1069 |
BgzfCompressCommWithP* cwp = bgzfp->cwps[slot_ct]; |
| 1070 |
#ifdef _WIN32 |
| 1071 |
CloseHandle(cwp->ucbuf_filled_event); |
| 1072 |
if (slot_partial_init == 2) { |
| 1073 |
break; |
| 1074 |
} |
| 1075 |
CloseHandle(cwp->ucbuf_open_event); |
| 1076 |
if (slot_partial_init == 3) { |
| 1077 |
break; |
| 1078 |
} |
| 1079 |
BgzfCompressCommWithW* cww = bgzfp->cwws[slot_ct]; |
| 1080 |
CloseHandle(cww->cbuf_filled_event); |
| 1081 |
#else |
| 1082 |
pthread_mutex_destroy(&cwp->ucbuf_mutex); |
| 1083 |
if (slot_partial_init == 2) { |
| 1084 |
break; |
| 1085 |
} |
| 1086 |
pthread_cond_destroy(&cwp->ucbuf_condvar); |
| 1087 |
if (slot_partial_init == 3) { |
| 1088 |
break; |
| 1089 |
} |
| 1090 |
BgzfCompressCommWithW* cww = bgzfp->cwws[slot_ct]; |
| 1091 |
pthread_mutex_destroy(&cww->cbuf_mutex); |
| 1092 |
#endif |
| 1093 |
assert(slot_partial_init == 4); |
| 1094 |
} while (0); |
| 1095 |
} |
| 1096 |
for (uint32_t slot_idx = 0; slot_idx != slot_ct; ++slot_idx) { |
| 1097 |
BgzfCompressCommWithP* cwp = bgzfp->cwps[slot_idx]; |
| 1098 |
BgzfCompressCommWithW* cww = bgzfp->cwws[slot_idx]; |
| 1099 |
#ifdef _WIN32 |
| 1100 |
CloseHandle(cwp->ucbuf_filled_event); |
| 1101 |
CloseHandle(cwp->ucbuf_open_event); |
| 1102 |
CloseHandle(cww->cbuf_filled_event); |
| 1103 |
CloseHandle(cww->cbuf_open_event); |
| 1104 |
#else |
| 1105 |
pthread_mutex_destroy(&cwp->ucbuf_mutex); |
| 1106 |
pthread_cond_destroy(&cwp->ucbuf_condvar); |
| 1107 |
pthread_mutex_destroy(&cww->cbuf_mutex); |
| 1108 |
pthread_cond_destroy(&cww->cbuf_condvar); |
| 1109 |
#endif |
| 1110 |
} |
| 1111 |
aligned_free(threads); |
| 1112 |
bgzfp->threads = nullptr; |
| 1113 |
if (unfinished_init) { |
| 1114 |
assert(*reterrp != kPglRetSuccess); |
| 1115 |
fclose(bgzfp->ff); |
| 1116 |
bgzfp->ff = nullptr; |
| 1117 |
// don't need to clear bgzfp->unfinished_init_state |
| 1118 |
} else { |
| 1119 |
errno = bgzfp->write_errno; |
| 1120 |
} |
| 1121 |
} else if (bgzfp->ff) { // uncompressed case |
| 1122 |
if (unlikely(fclose(bgzfp->ff))) { |
| 1123 |
if (*reterrp == kPglRetSuccess) { |
| 1124 |
bgzfp->ff = nullptr; |
| 1125 |
*reterrp = kPglRetWriteFail; |
| 1126 |
return 1; |
| 1127 |
} |
| 1128 |
} |
| 1129 |
bgzfp->ff = nullptr; |
| 1130 |
} |
| 1131 |
return 0; |
| 1132 |
} |
| 1133 |
|
| 1134 |
#ifdef __cplusplus |
| 1135 |
} |
| 1136 |
#endif |