| 1 |
#ifndef __PLINK2_BGZF_H__ |
| 2 |
#define __PLINK2_BGZF_H__ |
| 3 |
|
| 4 |
// This library is part of PLINK 2.0, copyright (C) 2005-2025 Shaun Purcell, |
| 5 |
// Christopher Chang. |
| 6 |
// |
| 7 |
// This library is free software: you can redistribute it and/or modify it |
| 8 |
// under the terms of the GNU Lesser General Public License as published by the |
| 9 |
// Free Software Foundation, either version 3 of the License, or (at your |
| 10 |
// option) any later version. |
| 11 |
// |
| 12 |
// This library is distributed in the hope that it will be useful, but WITHOUT |
| 13 |
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
| 14 |
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License |
| 15 |
// for more details. |
| 16 |
// |
| 17 |
// You should have received a copy of the GNU Lesser General Public License |
| 18 |
// along with this library. If not, see <http://www.gnu.org/licenses/>. |
| 19 |
|
| 20 |
|
| 21 |
// Binary BGZF readers and writers, based on libdeflate. |
| 22 |
// |
| 23 |
// htslib dependency has been dropped due to impedance mismatches with plink2 |
| 24 |
// in several areas: |
| 25 |
// - input streams (in particular, being forced to open the file once to detect |
| 26 |
// file type, close it, and then reopen it as a BGZF* breaks pipe file |
| 27 |
// descriptors; and while PLINK 2.0 avoids guaranteeing that pipe file |
| 28 |
// descriptors work in any given scenario, there's still a big practical |
| 29 |
// difference between "usually works, with a few exceptions where two-pass |
| 30 |
// processing is simpler" and "always fails") |
| 31 |
// - Windows multithreading |
| 32 |
// - error handling |
| 33 |
// (Note that htslib has great BGZF compression/decompression performance, as |
| 34 |
// long as v1.8+ is used with libdeflate.) |
| 35 |
|
| 36 |
#include "plink2_string.h" |
| 37 |
#include "plink2_thread.h" |
| 38 |
#ifdef IGNORE_BUNDLED_LIBDEFLATE |
| 39 |
# include <libdeflate.h> |
| 40 |
#else |
| 41 |
# include "../libdeflate/libdeflate.h" |
| 42 |
#endif |
| 43 |
|
| 44 |
#ifdef __cplusplus |
| 45 |
namespace plink2 { |
| 46 |
#endif |
| 47 |
|
| 48 |
HEADER_INLINE int32_t IsBgzfHeader(const void* buf) { |
| 49 |
uint32_t magic4; |
| 50 |
memcpy(&magic4, buf, 4); |
| 51 |
return ((magic4 & 0x4ffffff) == 0x4088b1f) && memequal_k(&(S_CAST(const unsigned char*, buf)[10]), "\6\0BC\2", 6); |
| 52 |
} |
| 53 |
|
| 54 |
typedef struct BgzfRawDecompressStreamStruct { |
| 55 |
unsigned char* in; |
| 56 |
struct libdeflate_decompressor* ldc; |
| 57 |
uint32_t in_size; |
| 58 |
uint32_t in_pos; |
| 59 |
} BgzfRawDecompressStream; |
| 60 |
|
| 61 |
// (tested a few different values for this, 1 MiB appears to work well on the |
| 62 |
// systems we care most about) |
| 63 |
CONSTI32(kDecompressChunkSize, 1048576); |
| 64 |
static_assert(!(kDecompressChunkSize % kCacheline), "kDecompressChunkSize must be a multiple of kCacheline."); |
| 65 |
static_assert(kDecompressChunkSize >= kMaxMediumLine, "kDecompressChunkSize too small."); |
| 66 |
|
| 67 |
CONSTI32(kMaxBgzfDecompressThreads, 5); |
| 68 |
CONSTI32(kMaxBgzfCompressedBlockSize, 65536); |
| 69 |
static_assert(kMaxBgzfDecompressThreads * 3 * kMaxBgzfCompressedBlockSize < kDecompressChunkSize, "kMaxBgzfDecompressThreads too large relative to kDecompressChunkSize."); |
| 70 |
CONSTI32(kMaxBgzfDecompressedBlockSize, 65536); |
| 71 |
static_assert((kMaxBgzfDecompressedBlockSize % kCacheline) == 0, "kMaxBgzfDecompressedBlockSize is assumed to be a cacheline multiple."); |
| 72 |
|
| 73 |
// Communication with reader thread (i.e. worker thread 0). |
| 74 |
typedef struct BgzfMtReadCommWithRStruct { |
| 75 |
// Reader -> consumer. Loaded-but-not-decompressed byte interval. |
| 76 |
uint32_t remaining_start; |
| 77 |
uint32_t remaining_end; |
| 78 |
uint32_t remaining_end_is_eof; |
| 79 |
#if __cplusplus >= 201103L |
| 80 |
// Can't just use PglErr, since BgzfRawMtDecompressStream is part of a union, |
| 81 |
// hence BgzfMtReadBody must have a trivial default constructor. |
| 82 |
PglErr::ec reterr; |
| 83 |
#else |
| 84 |
int32_t reterr; |
| 85 |
#endif |
| 86 |
const char* errmsg; |
| 87 |
|
| 88 |
// Consumer -> reader. Currently-being-decompressed byte interval. |
| 89 |
uint32_t locked_start; |
| 90 |
uint32_t locked_end; |
| 91 |
} BgzfMtReadCommWithR; |
| 92 |
|
| 93 |
// Communication with decompressor threads. |
| 94 |
typedef struct BgzfMtReadCommWithDStruct { |
| 95 |
// Decompressors -> consumer. |
| 96 |
unsigned char* overflow; |
| 97 |
// Consumer is responsible for tracking |
| 98 |
// overflow_start/overflow_end/target_written. |
| 99 |
|
| 100 |
// This can be set to 1 by any decompressor thread, but no other changes are |
| 101 |
// possible, so we don't need an extra write-lock (or expand this into a |
| 102 |
// kMaxBgzfDecompressThreads-length array). It takes precedence over |
| 103 |
// reader-thread errors, since it refers to earlier data. |
| 104 |
uint32_t invalid_bgzf; |
| 105 |
|
| 106 |
// Consumer -> decompressors. |
| 107 |
uint32_t target_capacity; |
| 108 |
unsigned char* target; |
| 109 |
uint32_t in_offsets[kMaxBgzfDecompressThreads + 1]; |
| 110 |
uint32_t out_offsets[kMaxBgzfDecompressThreads]; |
| 111 |
} BgzfMtReadCommWithD; |
| 112 |
|
| 113 |
typedef struct BgzfMtReadBodyStruct { |
| 114 |
// Thread 0 performs read-ahead into trs.in. |
| 115 |
// Threads 1..(thread_ct-1) perform decompression from trs.in directly to |
| 116 |
// target when there's sufficient space, and to overflow[] when there isn't. |
| 117 |
// overflow actually points 64KiB after the start of the associated buffer; |
| 118 |
// this simplifies handling of half-overflowing blocks. |
| 119 |
struct libdeflate_decompressor* ldcs[kMaxBgzfDecompressThreads]; |
| 120 |
|
| 121 |
// Borrowed from consumer, not closed by CleanupBgzfRawMtStream(). |
| 122 |
FILE* ff; |
| 123 |
|
| 124 |
unsigned char* in; |
| 125 |
|
| 126 |
BgzfMtReadCommWithR* cwr[2]; |
| 127 |
BgzfMtReadCommWithD* cwd[2]; |
| 128 |
|
| 129 |
uint32_t initial_compressed_byte_ct; |
| 130 |
} BgzfMtReadBody; |
| 131 |
|
| 132 |
typedef struct BgzfRawMtDecompressStreamStruct { |
| 133 |
BgzfMtReadBody body; |
| 134 |
ThreadGroup tg; // stores thread_ct |
| 135 |
|
| 136 |
// Between thread-group-joins, the consumer can safely copy from |
| 137 |
// body.cwd[consumer_parity]->overflow, while the decompressor threads |
| 138 |
// continue writing to body.cwd[1 - consumer_parity]. |
| 139 |
// overflow_start[consumer_parity]..overflow_end[consumer_parity] indicate |
| 140 |
// which body.cwd[consumer_parity]->overflow bytes remain to be copied, while |
| 141 |
// overflow_start[1 - consumer_parity]..overflow_end[1 - consumer_parity] |
| 142 |
// indicate the initial body.cwd[1 - consumer_parity]->overflow bounds after |
| 143 |
// the next thread-group-join. |
| 144 |
uint32_t overflow_start[2]; |
| 145 |
uint32_t overflow_end[2]; |
| 146 |
uint32_t consumer_parity; |
| 147 |
uint32_t eof; |
| 148 |
} BgzfRawMtDecompressStream; |
| 149 |
|
| 150 |
extern const char kShortErrInvalidBgzf[]; |
| 151 |
|
| 152 |
void PreinitBgzfRawMtStream(BgzfRawMtDecompressStream* bgzfp); |
| 153 |
|
| 154 |
// Two modes: |
| 155 |
// - Regular: ff must point 16 bytes into the file, and header[] must contain |
| 156 |
// the first 16 bytes. bgzf_st_ptr must be nullptr. |
| 157 |
// - Move-construction: ff is assumed to point to &(bgzf_st_ptr->in[in_size]). |
| 158 |
// header must be nullptr. |
| 159 |
// decompress_thread_ct must be positive. It is automatically reduced to |
| 160 |
// kMaxBgzfDecompressThreads if necessary. |
| 161 |
PglErr BgzfRawMtStreamInit(const char* header, uint32_t decompress_thread_ct, FILE* ff, BgzfRawDecompressStream* bgzf_st_ptr, BgzfRawMtDecompressStream* bgzfp, const char** errmsgp); |
| 162 |
|
| 163 |
PglErr BgzfRawMtStreamRead(unsigned char* dst_end, BgzfRawMtDecompressStream* bgzfp, unsigned char** dst_iterp, const char** errmsgp); |
| 164 |
|
| 165 |
PglErr BgzfRawMtStreamRetarget(const char* header, BgzfRawMtDecompressStream* bgzfp, FILE* next_ff, const char** errmsgp); |
| 166 |
|
| 167 |
HEADER_INLINE PglErr BgzfRawMtStreamRewind(BgzfRawMtDecompressStream* bgzfp, const char** errmsgp) { |
| 168 |
return BgzfRawMtStreamRetarget(nullptr, bgzfp, nullptr, errmsgp); |
| 169 |
} |
| 170 |
|
| 171 |
void CleanupBgzfRawMtStream(BgzfRawMtDecompressStream* bgzfp); |
| 172 |
|
| 173 |
|
| 174 |
// Compression strategy: |
| 175 |
// - We have N compression-job memory slots, where N is the smallest power of 2 |
| 176 |
// >= 4 * compressor_thread_ct. (This could be adjusted and/or separately |
| 177 |
// configurable, any value >= 2 * compressor_thread_ct is reasonable.) |
| 178 |
// - For the most common plink2 use case (VCF export), compression is over 90% |
| 179 |
// of the compute cost. Thus, a good implementation must be optimized around |
| 180 |
// minimizing compressor-thread waits, in a setting where one core's workload |
| 181 |
// is split between production and compression and the other cores are |
| 182 |
// compressing all the time. |
| 183 |
// I first implemented the trivial load-balancing strategy (compressor thread |
| 184 |
// k processes blocks k, n+k, 2n+k, ..., where n is the number of compressor |
| 185 |
// threads), but that proved to be slightly slower than htslib's bgzf writer |
| 186 |
// in my testing; it didn't do a good enough job of managing the |
| 187 |
// split-between-production-and-compression core. |
| 188 |
// So I've switched to a more flexible thread pool using __atomic_fetch_add() |
| 189 |
// to distribute compression jobs. |
| 190 |
// - There's a dedicated writer thread which flushes the compression results. |
| 191 |
// I will look into adding direct support for this parallelization pattern to |
| 192 |
// plink2_thread; the benefit is small (~5%), but applies to a lot of |
| 193 |
// workloads. It may also be worthwhile to implement some form of |
| 194 |
// work-stealing. |
| 195 |
// |
| 196 |
// I tried making this less granular (each job contains two blocks instead of |
| 197 |
// one) to see if there was still meaningful room for improvement re: reducing |
| 198 |
// thread-synchronization overhead; that didn't seem to make any better use of |
| 199 |
// the extra memory than keeping the basic granularity level and doubling the |
| 200 |
// number of slots. |
| 201 |
|
| 202 |
CONSTI32(kMaxBgzfCompressThreads, 15); |
| 203 |
CONSTI32(kBgzfInputBlockSize, 0xff00); // htslib BGZF_BLOCK_SIZE |
| 204 |
|
| 205 |
typedef struct BgzfCompressStreamMainStruct BgzfCompressStreamMain; |
| 206 |
|
| 207 |
typedef struct BgzfCompressCommWithWStruct { |
| 208 |
// Compressor -> writer. One per block slot. |
| 209 |
unsigned char cbuf[kMaxBgzfCompressedBlockSize]; |
| 210 |
uint32_t nbytes; // UINT32_MAX = open, otherwise filled |
| 211 |
uint32_t eof; |
| 212 |
#ifdef _WIN32 |
| 213 |
HANDLE cbuf_filled_event; |
| 214 |
HANDLE cbuf_open_event; |
| 215 |
#else |
| 216 |
pthread_mutex_t cbuf_mutex; |
| 217 |
pthread_cond_t cbuf_condvar; |
| 218 |
#endif |
| 219 |
} BgzfCompressCommWithW; |
| 220 |
|
| 221 |
typedef struct BgzfCompressCommWithPStruct { |
| 222 |
// Producer -> compressor. One per block slot. |
| 223 |
char ucbuf[kBgzfInputBlockSize]; |
| 224 |
#ifdef _WIN32 |
| 225 |
HANDLE ucbuf_filled_event; |
| 226 |
HANDLE ucbuf_open_event; |
| 227 |
#else |
| 228 |
pthread_mutex_t ucbuf_mutex; |
| 229 |
pthread_cond_t ucbuf_condvar; |
| 230 |
#endif |
| 231 |
uint32_t nbytes; // UINT32_MAX = open, otherwise filled |
| 232 |
uint32_t eof; // bugfix (15 Aug 2024): otherwise BgzfFlush[Try] doesn't work |
| 233 |
} BgzfCompressCommWithP; |
| 234 |
|
| 235 |
typedef struct BgzfCompressorContextStruct { |
| 236 |
BgzfCompressStreamMain* parent; |
| 237 |
struct libdeflate_compressor* lc; |
| 238 |
// don't need tidx any more... |
| 239 |
} BgzfCompressorContext; |
| 240 |
|
| 241 |
struct BgzfCompressStreamMainStruct { |
| 242 |
NONCOPYABLE(BgzfCompressStreamMainStruct); |
| 243 |
FILE* ff; |
| 244 |
pthread_t* threads; // n+1 elements, last element is writer |
| 245 |
BgzfCompressCommWithP** cwps; // N elements |
| 246 |
BgzfCompressCommWithW** cwws; // N elements |
| 247 |
|
| 248 |
BgzfCompressorContext* compressor_args; // n elements |
| 249 |
|
| 250 |
// Atomically read/updated, guaranteed to be on its own cacheline. |
| 251 |
uintptr_t* next_job_idxp; |
| 252 |
|
| 253 |
int32_t write_errno; |
| 254 |
|
| 255 |
uint16_t slot_ct; |
| 256 |
uint16_t compressor_thread_ct; // 0 if no compression |
| 257 |
uint16_t partial_slot_idx; // this ucbuf must be open |
| 258 |
uint16_t partial_nbytes; // always < kBgzfInputBlockSize |
| 259 |
|
| 260 |
// If nonzero, initialization didn't complete, and this value contains enough |
| 261 |
// (platform-specific) information to clean up properly. |
| 262 |
// Not an enum since we perform a bit of arithmetic on it. |
| 263 |
uint16_t unfinished_init_state; |
| 264 |
}; |
| 265 |
|
| 266 |
typedef struct BgzfCompressStreamStruct { |
| 267 |
NONCOPYABLE(BgzfCompressStreamStruct); |
| 268 |
#ifdef __cplusplus |
| 269 |
BgzfCompressStreamMain& GET_PRIVATE_m() { return m; } |
| 270 |
BgzfCompressStreamMain const& GET_PRIVATE_m() const { return m; } |
| 271 |
private: |
| 272 |
#endif |
| 273 |
BgzfCompressStreamMain m; |
| 274 |
} BgzfCompressStream; |
| 275 |
|
| 276 |
void PreinitBgzfCompressStream(BgzfCompressStream* cstream_ptr); |
| 277 |
|
| 278 |
CONSTI32(kBgzfDefaultClvl, 6); |
| 279 |
|
| 280 |
// - Compression level 0 = plaintext (not a BGZF file at all), so application |
| 281 |
// code no longer has to explicitly branch on bgzf/non-bgzf output. |
| 282 |
// - thread_ct only applies when clvl != 0. When that's true, it's internally |
| 283 |
// clipped to [2, kMaxBgzfCompressThreads]. |
| 284 |
// - errno is set on open-fail. |
| 285 |
PglErr InitBgzfCompressStreamEx(const char* out_fname, uint32_t do_append, uint32_t clvl, uint32_t thread_ct, BgzfCompressStream* cstream_ptr); |
| 286 |
|
| 287 |
HEADER_INLINE PglErr InitBgzfCompressStream(const char* out_fname, uint32_t thread_ct, BgzfCompressStream* cstream_ptr) { |
| 288 |
return InitBgzfCompressStreamEx(out_fname, 0, kBgzfDefaultClvl, thread_ct, cstream_ptr); |
| 289 |
} |
| 290 |
|
| 291 |
// errno is set on write-fail. |
| 292 |
BoolErr BgzfWrite(const char* buf, uintptr_t len, BgzfCompressStream* cstream_ptr); |
| 293 |
|
| 294 |
BoolErr BgzfFlushTry(uint32_t capacity_needed_to_defer_flush, BgzfCompressStream* cstream_ptr); |
| 295 |
|
| 296 |
HEADER_INLINE BoolErr BgzfFlush(BgzfCompressStream* cstream_ptr) { |
| 297 |
return BgzfFlushTry(kBgzfInputBlockSize, cstream_ptr); |
| 298 |
} |
| 299 |
|
| 300 |
BoolErr CleanupBgzfCompressStream(BgzfCompressStream* cstream_ptr, PglErr* reterrp); |
| 301 |
|
| 302 |
#ifdef __cplusplus |
| 303 |
} // namespace plink2 |
| 304 |
#endif |
| 305 |
|
| 306 |
#endif // __PLINK2_BGZF_H__ |