Debian Codegraph @

include/plink2_htable.cc

raw
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
18 #include "plink2_bits.h"
19 #include "plink2_htable.h"
20 #include "plink2_memory.h"
21 #include "plink2_string.h"
22 #include "plink2_text.h"
23 #include "plink2_thread.h"
24
25 #include <errno.h>
26
27 #ifdef __cplusplus
28 namespace plink2 {
29 #endif
30
31 // MurmurHash3, from
32 // https://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp
33 CSINLINE uint32_t rotl32(uint32_t x, int8_t r) {
34 return (x << r) | (x >> (32 - r));
35 }
36
37 //-----------------------------------------------------------------------------
38 // Finalization mix - force all bits of a hash block to avalanche
39
40 CSINLINE2 uint32_t fmix32(uint32_t h) {
41 h ^= h >> 16;
42 h *= 0x85ebca6b;
43 h ^= h >> 13;
44 h *= 0xc2b2ae35;
45 h ^= h >> 16;
46
47 return h;
48 }
49
50 uint32_t Hash32(const void* key, uint32_t len) {
51 const unsigned char* data = S_CAST(const unsigned char*, key);
52 const int32_t nblocks = len / 4;
53
54 uint32_t h1 = 0;
55 // uint32_t h1 = seed;
56
57 const uint32_t c1 = 0xcc9e2d51;
58 const uint32_t c2 = 0x1b873593;
59
60 //----------
61 // body
62
63 const unsigned char* tail = data + nblocks*4;
64
65 int32_t i;
66 uint32_t k1;
67 for(i = -nblocks; i; i++) {
68 memcpy_k(&k1, &(tail[i * 4]), 4);
69
70 k1 *= c1;
71 k1 = rotl32(k1,15);
72 k1 *= c2;
73
74 h1 ^= k1;
75 h1 = rotl32(h1,13);
76 h1 = h1*5+0xe6546b64;
77 }
78
79 //----------
80 // tail
81
82 k1 = 0;
83
84 switch(len & 3) {
85 case 3:
86 k1 ^= tail[2] << 16;
87 // fall through
88 case 2:
89 k1 ^= tail[1] << 8;
90 // fall through
91 case 1:
92 k1 ^= tail[0];
93 k1 *= c1;
94 k1 = rotl32(k1,15);
95 k1 *= c2;
96 h1 ^= k1;
97 }
98
99 //----------
100 // finalization
101
102 h1 ^= len;
103
104 return fmix32(h1);
105 }
106
107 uint32_t IdHtableFind(const char* cur_id, const char* const* item_ids, const uint32_t* id_htable, uint32_t cur_id_slen, uint32_t id_htable_size) {
108 // returns UINT32_MAX on failure
109 for (uint32_t hashval = Hashceil(cur_id, cur_id_slen, id_htable_size); ; ) {
110 const uint32_t cur_htable_idval = id_htable[hashval];
111 if ((cur_htable_idval == UINT32_MAX) || (!strcmp(cur_id, item_ids[cur_htable_idval]))) {
112 return cur_htable_idval;
113 }
114 if (++hashval == id_htable_size) {
115 hashval = 0;
116 }
117 }
118 }
119
120 uint32_t IdHtableFindNnt(const char* cur_id, const char* const* item_ids, const uint32_t* id_htable, uint32_t cur_id_slen, uint32_t id_htable_size) {
121 // returns UINT32_MAX on failure
122 for (uint32_t hashval = Hashceil(cur_id, cur_id_slen, id_htable_size); ; ) {
123 const uint32_t cur_htable_idval = id_htable[hashval];
124 if ((cur_htable_idval == UINT32_MAX) || strequal_unsafe(item_ids[cur_htable_idval], cur_id, cur_id_slen)) {
125 return cur_htable_idval;
126 }
127 if (++hashval == id_htable_size) {
128 hashval = 0;
129 }
130 }
131 }
132
133 uint32_t IdHtableAdd(const char* cur_id, const char* const* item_ids, uint32_t cur_id_slen, uint32_t id_htable_size, uint32_t value, uint32_t* id_htable) {
134 for (uint32_t hashval = Hashceil(cur_id, cur_id_slen, id_htable_size); ; ) {
135 const uint32_t cur_htable_entry = id_htable[hashval];
136 if (cur_htable_entry == UINT32_MAX) {
137 id_htable[hashval] = value;
138 return UINT32_MAX;
139 }
140 if (memequal(cur_id, item_ids[cur_htable_entry], cur_id_slen + 1)) {
141 return cur_htable_entry;
142 }
143 if (++hashval == id_htable_size) {
144 hashval = 0;
145 }
146 }
147 }
148
149 uint32_t IdHtableAddNnt(const char* cur_id, const char* const* item_ids, uint32_t cur_id_slen, uint32_t id_htable_size, uint32_t value, uint32_t* id_htable) {
150 for (uint32_t hashval = Hashceil(cur_id, cur_id_slen, id_htable_size); ; ) {
151 const uint32_t cur_htable_entry = id_htable[hashval];
152 if (cur_htable_entry == UINT32_MAX) {
153 id_htable[hashval] = value;
154 return UINT32_MAX;
155 }
156 if (strequal_unsafe(item_ids[cur_htable_entry], cur_id, cur_id_slen)) {
157 return cur_htable_entry;
158 }
159 if (++hashval == id_htable_size) {
160 hashval = 0;
161 }
162 }
163 }
164
165 CONSTI32(kMaxDupflagThreads, 16);
166
167 typedef struct DupflagHtableMakerStruct {
168 const uintptr_t* subset_mask;
169 const char* const* item_ids;
170 uint32_t item_ct;
171 uint32_t id_htable_size;
172 uint32_t item_uidx_starts[kMaxDupflagThreads];
173
174 uint32_t* id_htable;
175 } DupflagHtableMaker;
176
177 void DupflagHtableMakerMain(uint32_t tidx, uint32_t thread_ct, DupflagHtableMaker* ctx) {
178 const uint32_t id_htable_size = ctx->id_htable_size;
179 const uintptr_t* subset_mask = ctx->subset_mask;
180 const char* const* item_ids = ctx->item_ids;
181 const uint32_t item_ct = ctx->item_ct;
182 const uint32_t item_uidx_start = ctx->item_uidx_starts[tidx];
183 const uint32_t item_idx_start = (item_ct * S_CAST(uint64_t, tidx)) / thread_ct;
184 const uint32_t item_idx_end = (item_ct * (S_CAST(uint64_t, tidx) + 1)) / thread_ct;
185 uint32_t* id_htable = ctx->id_htable;
186
187 uintptr_t cur_bits;
188 uintptr_t item_uidx_base;
189 BitIter1Start(subset_mask, item_uidx_start, &item_uidx_base, &cur_bits);
190 for (uint32_t item_idx = item_idx_start; item_idx != item_idx_end; ++item_idx) {
191 const uintptr_t item_uidx = BitIter1(subset_mask, &item_uidx_base, &cur_bits);
192 const char* sptr = item_ids[item_uidx];
193 const uint32_t slen = strlen(sptr);
194 for (uint32_t hashval = Hashceil(sptr, slen, id_htable_size); ; ) {
195 uint32_t old_htable_entry = id_htable[hashval];
196 if (old_htable_entry == UINT32_MAX) {
197 if (ATOMIC_COMPARE_EXCHANGE_N_U32(&(id_htable[hashval]), &old_htable_entry, item_uidx, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) {
198 break;
199 }
200 }
201 if (strequal_overread(sptr, item_ids[old_htable_entry & 0x7fffffff])) {
202 if (!(old_htable_entry & 0x80000000U)) {
203 // ok if multiple threads do this
204 id_htable[hashval] = old_htable_entry | 0x80000000U;
205 }
206 break;
207 }
208 if (++hashval == id_htable_size) {
209 hashval = 0;
210 }
211 }
212 }
213 }
214
215 THREAD_FUNC_DECL DupflagHtableMakerThread(void* raw_arg) {
216 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
217 const uint32_t tidx = arg->tidx;
218 DupflagHtableMaker* ctx = S_CAST(DupflagHtableMaker*, arg->sharedp->context);
219
220 // 1. Initialize id_htable with 1-bits in parallel.
221 const uint32_t id_htable_size = ctx->id_htable_size;
222 const uint32_t thread_ct = GetThreadCt(arg->sharedp) + 1;
223 uint32_t* id_htable = ctx->id_htable;
224 const uint32_t fill_start = RoundDownPow2((id_htable_size * S_CAST(uint64_t, tidx)) / thread_ct, kInt32PerCacheline);
225 const uint32_t fill_end = RoundDownPow2((id_htable_size * (S_CAST(uint64_t, tidx) + 1)) / thread_ct, kInt32PerCacheline);
226 SetAllU32Arr(fill_end - fill_start, &(id_htable[fill_start]));
227
228 // 2. sync.Once
229 if (THREAD_BLOCK_FINISH(arg)) {
230 THREAD_RETURN;
231 }
232
233 // 3. Fill hash table in parallel, and then return.
234 DupflagHtableMakerMain(tidx, thread_ct, ctx);
235 THREAD_RETURN;
236 }
237
238 PglErr MakeDupflagHtable(const uintptr_t* subset_mask, const char* const* item_ids, uintptr_t item_ct, uint32_t id_htable_size, uint32_t max_thread_ct, uint32_t* id_htable) {
239 PglErr reterr = kPglRetSuccess;
240 ThreadGroup tg;
241 PreinitThreads(&tg);
242 DupflagHtableMaker ctx;
243 {
244 uint32_t thread_ct = item_ct / 65536;
245 if (!thread_ct) {
246 thread_ct = 1;
247 } else {
248 if (thread_ct > max_thread_ct) {
249 thread_ct = max_thread_ct;
250 }
251 // bugfix (26 Nov 2019): forgot to force this
252 if (thread_ct > kMaxDupflagThreads) {
253 thread_ct = kMaxDupflagThreads;
254 }
255 }
256 if (unlikely(SetThreadCt0(thread_ct - 1, &tg))) {
257 goto MakeDupflagHtable_ret_NOMEM;
258 }
259
260 ctx.subset_mask = subset_mask;
261 ctx.item_ids = item_ids;
262 ctx.item_ct = item_ct;
263 ctx.id_htable_size = id_htable_size;
264 ctx.id_htable = id_htable;
265
266 FillU32SubsetStarts(subset_mask, thread_ct, 0, item_ct, ctx.item_uidx_starts);
267 if (thread_ct > 1) {
268 SetThreadFuncAndData(DupflagHtableMakerThread, &ctx, &tg);
269 if (unlikely(SpawnThreads(&tg))) {
270 goto MakeDupflagHtable_ret_THREAD_CREATE_FAIL;
271 }
272 }
273 const uint32_t fill_start = RoundDownPow2((id_htable_size * S_CAST(uint64_t, thread_ct - 1)) / thread_ct, kInt32PerCacheline);
274 SetAllU32Arr(id_htable_size - fill_start, &(id_htable[fill_start]));
275 if (thread_ct > 1) {
276 JoinThreads(&tg);
277 DeclareLastThreadBlock(&tg);
278 SpawnThreads(&tg);
279 }
280 DupflagHtableMakerMain(thread_ct - 1, thread_ct, &ctx);
281 JoinThreads0(&tg);
282 }
283 while (0) {
284 MakeDupflagHtable_ret_NOMEM:
285 reterr = kPglRetNomem;
286 break;
287 MakeDupflagHtable_ret_THREAD_CREATE_FAIL:
288 reterr = kPglRetThreadCreateFail;
289 break;
290 }
291 CleanupThreads(&tg);
292 return reterr;
293 }
294
295 CONSTI32(kMaxDupstoreThreads, 15); // probably reduce this after switching to XXH3
296
297 typedef struct DupstoreHtableMakerStruct {
298 const uintptr_t* subset_mask;
299 const char* const* item_ids;
300 uint32_t item_ct;
301 uint32_t id_htable_size;
302 uint32_t* id_htable;
303
304 uint32_t item_uidx_start[2];
305 uint32_t* hashes[2];
306 } DupstoreHtableMaker;
307
308 THREAD_FUNC_DECL DupstoreHtableMakerThread(void* raw_arg) {
309 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
310 const uint32_t tidx = arg->tidx;
311 DupstoreHtableMaker* ctx = S_CAST(DupstoreHtableMaker*, arg->sharedp->context);
312
313 // 1. Initialize id_htable with 1-bits in parallel.
314 const uint32_t id_htable_size = ctx->id_htable_size;
315 const uint32_t thread_ct = GetThreadCt(arg->sharedp);
316 uint32_t* id_htable = ctx->id_htable;
317 // Add 1 to thread_ct in denominator, since unlike the DupflagHtableMaker
318 // case, the parent thread has separate logic to help out here.
319 const uint32_t fill_start = RoundDownPow2((id_htable_size * S_CAST(uint64_t, tidx)) / (thread_ct + 1), kInt32PerCacheline);
320 uint32_t fill_end = RoundDownPow2((id_htable_size * (S_CAST(uint64_t, tidx) + 1)) / (thread_ct + 1), kInt32PerCacheline);
321 SetAllU32Arr(fill_end - fill_start, &(id_htable[fill_start]));
322
323 const uintptr_t* subset_mask = ctx->subset_mask;
324 const char* const* item_ids = ctx->item_ids;
325 uint32_t items_left = ctx->item_ct;
326 const uint32_t idx_start_offset = tidx * kDupstoreBlockSize;
327 uint32_t idx_stop_offset = idx_start_offset + kDupstoreBlockSize;
328 const uint32_t is_last_thread = (tidx + 1 == thread_ct);
329 uint32_t parity = 0;
330 while (!THREAD_BLOCK_FINISH(arg)) {
331 // 2. Compute up to kDupstoreBlockSize hashes. (Parent thread is
332 // responsible for using them to update the hash table.)
333 if (items_left < idx_stop_offset) {
334 if (items_left <= idx_start_offset) {
335 // Must be last iteration. Don't need to update parity.
336 // (Could load-balance this iteration differently, but it shouldn't
337 // really matter.)
338 continue;
339 }
340 idx_stop_offset = items_left;
341 }
342 uint32_t* hashes = ctx->hashes[parity];
343 // bugfix (24 Jan 2020): IsSet(subset_mask, item_uidx) is not always true.
344 uintptr_t item_uidx = FindNth1BitFrom(subset_mask, ctx->item_uidx_start[parity], idx_start_offset + 1);
345
346 uintptr_t cur_bits;
347 uintptr_t item_uidx_base;
348 BitIter1Start(subset_mask, item_uidx, &item_uidx_base, &cur_bits);
349 for (uint32_t item_idx = idx_start_offset; item_idx != idx_stop_offset; ++item_idx) {
350 item_uidx = BitIter1(subset_mask, &item_uidx_base, &cur_bits);
351 const char* sptr = item_ids[item_uidx];
352 const uint32_t slen = strlen(sptr);
353 hashes[item_idx] = Hashceil(sptr, slen, id_htable_size);
354 }
355 items_left -= thread_ct * kDupstoreBlockSize; // final-iteration underflow ok
356 parity = 1 - parity;
357 if (is_last_thread) {
358 ctx->item_uidx_start[parity] = item_uidx + 1;
359 }
360 }
361 THREAD_RETURN;
362 }
363
364 uint32_t PopulateIdHtableMtDupstoreThreadCt(uint32_t max_thread_ct, uint32_t item_ct) {
365 uint32_t thread_ct = item_ct / (2 * kDupstoreBlockSize);
366 if (thread_ct >= max_thread_ct) {
367 // parent thread is sufficiently busy
368 thread_ct = max_thread_ct - 1;
369 }
370 if (!thread_ct) {
371 return 1;
372 }
373 return MINV(thread_ct, kMaxDupstoreThreads);
374 }
375
376 // dup_ct assumed to be initialized to 0 when dup_ct_ptr != nullptr.
377 //
378 // This currently has totally separate code paths for the store_all_dups and
379 // !store_all_dups cases. However, the table formats are nearly identical, so
380 // the code may re-converge, and it's reasonable to have just this API entry
381 // point.
382 //
383 // It will probably be moved out of plink2_cmdline soon.
384 PglErr PopulateIdHtableMt(unsigned char* arena_top, const uintptr_t* subset_mask, const char* const* item_ids, uintptr_t item_ct, uint32_t store_all_dups, uint32_t id_htable_size, uint32_t thread_ct, unsigned char** arena_bottom_ptr, uint32_t* id_htable, uint32_t* dup_ct_ptr) {
385 // Change from plink 1.9: if store_all_dups is false, we don't error out on
386 // the first encountered duplicate ID; instead, we just flag it in the hash
387 // table. So if '.' is the only duplicate ID, and it never appears in a
388 // variant ID list, plink2 never complains.
389 //
390 // When store_all_dups is true, additional linked lists are allocated past
391 // the end of id_htable to track all raw indexes of duplicate names.
392 if (!item_ct) {
393 return kPglRetSuccess;
394 }
395 if (!store_all_dups) {
396 return MakeDupflagHtable(subset_mask, item_ids, item_ct, id_htable_size, thread_ct, id_htable);
397 }
398 PglErr reterr = kPglRetSuccess;
399 unsigned char* arena_bottom_mark = *arena_bottom_ptr;
400 ThreadGroup tg;
401 PreinitThreads(&tg);
402 DupstoreHtableMaker ctx;
403 {
404 thread_ct = PopulateIdHtableMtDupstoreThreadCt(thread_ct, item_ct);
405 uint32_t item_idx_stop = thread_ct * kDupstoreBlockSize;
406 if (arena_end_alloc_u32(arena_bottom_mark, item_idx_stop, &arena_top, &ctx.hashes[0]) ||
407 arena_end_alloc_u32(arena_bottom_mark, item_idx_stop, &arena_top, &ctx.hashes[1]) ||
408 SetThreadCt(thread_ct, &tg)) {
409 goto PopulateIdHtableMt_ret_NOMEM;
410 }
411 uintptr_t cur_arena_left = arena_top - arena_bottom_mark;
412 // We only want to check for out-of-memory once per sync-iteration. The
413 // maximum number of 2x-uint32 entries that might be added per iteration is
414 // thread_ct * kDupstoreBlockSize * 2 (*2 is because, when we find the
415 // first duplicate of a string, we need to add two new entries instead of
416 // just one).
417 // htable_dup_base grows from the bottom of the arena, and during the main
418 // loop, extra_alloc is the next htable_dup_base[] array index that'll be
419 // written to (i.e. it's always an even number). So if extra_alloc plus
420 // twice the aforementioned limit isn't larger than cur_arena_left /
421 // sizeof(int32_t), we can't run out of arena space.
422 uint32_t extra_alloc_stop;
423 #ifdef __LP64__
424 if (cur_arena_left >= 0x400000000LLU + item_idx_stop * 4 * sizeof(int32_t)) {
425 // this can never be hit
426 extra_alloc_stop = 0xfffffffe;
427 } else {
428 #endif
429 if (unlikely(cur_arena_left < item_idx_stop * 4 * sizeof(int32_t))) {
430 goto PopulateIdHtableMt_ret_NOMEM;
431 }
432 extra_alloc_stop = (cur_arena_left / sizeof(int32_t)) - item_idx_stop * 4;
433 #ifdef __LP64__
434 }
435 #endif
436
437 ctx.subset_mask = subset_mask;
438 ctx.item_ids = item_ids;
439 ctx.item_ct = item_ct;
440 ctx.id_htable_size = id_htable_size;
441 ctx.id_htable = id_htable;
442 SetThreadFuncAndData(DupstoreHtableMakerThread, &ctx, &tg);
443 if (unlikely(SpawnThreads(&tg))) {
444 goto PopulateIdHtableMt_ret_THREAD_CREATE_FAIL;
445 }
446
447 const uint32_t fill_start = RoundDownPow2((id_htable_size * S_CAST(uint64_t, thread_ct)) / (thread_ct + 1), kInt32PerCacheline);
448 SetAllU32Arr(id_htable_size - fill_start, &(id_htable[fill_start]));
449
450 const uint32_t item_uidx_start = AdvTo1Bit(subset_mask, 0);
451 JoinThreads(&tg);
452 ctx.item_uidx_start[0] = item_uidx_start;
453 if (item_idx_stop >= item_ct) {
454 DeclareLastThreadBlock(&tg);
455 item_idx_stop = item_ct;
456 }
457 SpawnThreads(&tg);
458 uint32_t items_left = item_ct;
459 uint32_t* htable_dup_base = R_CAST(uint32_t*, arena_bottom_mark);
460 uint32_t extra_alloc = 0;
461 uint32_t prev_llidx = 0;
462 uintptr_t cur_bits;
463 uintptr_t item_uidx_base;
464 BitIter1Start(subset_mask, item_uidx_start, &item_uidx_base, &cur_bits);
465 uint32_t parity = 0;
466 do {
467 JoinThreads(&tg);
468 if (extra_alloc > extra_alloc_stop) {
469 goto PopulateIdHtableMt_ret_NOMEM;
470 }
471 if (item_idx_stop < items_left) {
472 if (item_idx_stop * 2 >= items_left) {
473 DeclareLastThreadBlock(&tg);
474 }
475 SpawnThreads(&tg);
476 } else {
477 item_idx_stop = items_left;
478 }
479 uint32_t* hashes = ctx.hashes[parity];
480 for (uint32_t item_idx = 0; item_idx != item_idx_stop; ++item_idx) {
481 const uintptr_t item_uidx = BitIter1(subset_mask, &item_uidx_base, &cur_bits);
482 const uint32_t hashval_base = hashes[item_idx];
483 uint32_t old_htable_entry = id_htable[hashval_base];
484 if (old_htable_entry == UINT32_MAX) {
485 id_htable[hashval_base] = item_uidx;
486 continue;
487 }
488 const char* sptr = item_ids[item_uidx];
489 for (uint32_t hashval = hashval_base; ; ) {
490 const uint32_t was_dup = old_htable_entry >> 31;
491 uint32_t prev_uidx;
492 if (was_dup) {
493 prev_llidx = old_htable_entry * 2;
494 prev_uidx = htable_dup_base[prev_llidx];
495 } else {
496 prev_uidx = old_htable_entry;
497 }
498 if (strequal_overread(sptr, item_ids[prev_uidx])) {
499 // point to linked list entry instead
500 if (!was_dup) {
501 htable_dup_base[extra_alloc] = old_htable_entry;
502 htable_dup_base[extra_alloc + 1] = UINT32_MAX;
503 prev_llidx = extra_alloc;
504 extra_alloc += 2;
505 }
506 htable_dup_base[extra_alloc] = item_uidx;
507 htable_dup_base[extra_alloc + 1] = prev_llidx;
508 id_htable[hashval] = 0x80000000U | (extra_alloc >> 1);
509 extra_alloc += 2;
510 break; // bugfix
511 }
512 if (++hashval == id_htable_size) {
513 hashval = 0;
514 }
515 // duplicate this code since we want to avoid the item_ids[item_uidx]
516 // read when possible
517 old_htable_entry = id_htable[hashval];
518 if (old_htable_entry == UINT32_MAX) {
519 id_htable[hashval] = item_uidx;
520 break;
521 }
522 }
523 }
524 items_left -= item_idx_stop;
525 parity = 1 - parity;
526 } while (items_left);
527 // bugfix (15 Oct 2019): no threads to join here!
528 if (extra_alloc) {
529 // bugfix: forgot to align this
530 *arena_bottom_ptr += RoundUpPow2(extra_alloc * sizeof(int32_t), kCacheline);
531 if (dup_ct_ptr) {
532 *dup_ct_ptr = extra_alloc / 2;
533 }
534 }
535 }
536 while (0) {
537 PopulateIdHtableMt_ret_NOMEM:
538 *arena_bottom_ptr = arena_bottom_mark;
539 reterr = kPglRetNomem;
540 break;
541 PopulateIdHtableMt_ret_THREAD_CREATE_FAIL:
542 // not currently possible for this to happen after *arena_bottom_ptr moved
543 reterr = kPglRetThreadCreateFail;
544 break;
545 }
546 CleanupThreads(&tg);
547 return reterr;
548 }
549
550 // Similar to DupflagHtableMaker, but we don't need to flag duplicates, we just
551 // "error out" when we find one.
552 typedef struct NondupHtableMakerStruct {
553 const uintptr_t* subset_mask;
554 const char* const* item_ids;
555 uint32_t item_ct;
556 uint32_t id_htable_size;
557 uint32_t item_uidx_starts[kMaxDupflagThreads];
558
559 uint32_t* id_htable;
560
561 uint32_t dup_found;
562 } NondupHtableMaker;
563
564 void NondupHtableMakerMain(uint32_t tidx, uint32_t thread_ct, NondupHtableMaker* ctx) {
565 const uint32_t id_htable_size = ctx->id_htable_size;
566 const uintptr_t* subset_mask = ctx->subset_mask;
567 const char* const* item_ids = ctx->item_ids;
568 const uint32_t item_ct = ctx->item_ct;
569 const uint32_t item_uidx_start = ctx->item_uidx_starts[tidx];
570 const uint32_t item_idx_start = (item_ct * S_CAST(uint64_t, tidx)) / thread_ct;
571 const uint32_t item_idx_end = (item_ct * (S_CAST(uint64_t, tidx) + 1)) / thread_ct;
572 uint32_t* id_htable = ctx->id_htable;
573
574 uintptr_t cur_bits;
575 uintptr_t item_uidx_base;
576 BitIter1Start(subset_mask, item_uidx_start, &item_uidx_base, &cur_bits);
577 for (uint32_t item_idx = item_idx_start; item_idx != item_idx_end; ) {
578 const uint32_t item_idx_cur_end = MINV(item_idx_end, item_idx + 65536);
579 for (; item_idx != item_idx_cur_end; ++item_idx) {
580 const uintptr_t item_uidx = BitIter1(subset_mask, &item_uidx_base, &cur_bits);
581 const char* sptr = item_ids[item_uidx];
582 const uint32_t slen = strlen(sptr);
583 for (uint32_t hashval = Hashceil(sptr, slen, id_htable_size); ; ) {
584 uint32_t old_htable_entry = id_htable[hashval];
585 if (old_htable_entry == UINT32_MAX) {
586 if (ATOMIC_COMPARE_EXCHANGE_N_U32(&(id_htable[hashval]), &old_htable_entry, item_uidx, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) {
587 break;
588 }
589 }
590 if (strequal_overread(sptr, item_ids[old_htable_entry & 0x7fffffff])) {
591 // no synchronization needed since this variable can't change in any
592 // other way
593 ctx->dup_found = 1;
594 return;
595 }
596 if (++hashval == id_htable_size) {
597 hashval = 0;
598 }
599 }
600 }
601 if (ctx->dup_found) {
602 return;
603 }
604 }
605 }
606
607 THREAD_FUNC_DECL NondupHtableMakerThread(void* raw_arg) {
608 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
609 const uint32_t tidx = arg->tidx;
610 NondupHtableMaker* ctx = S_CAST(NondupHtableMaker*, arg->sharedp->context);
611
612 // 1. Initialize id_htable with 1-bits in parallel.
613 const uint32_t id_htable_size = ctx->id_htable_size;
614 const uint32_t thread_ct = GetThreadCt(arg->sharedp) + 1;
615 uint32_t* id_htable = ctx->id_htable;
616 const uint32_t fill_start = RoundDownPow2((id_htable_size * S_CAST(uint64_t, tidx)) / thread_ct, kInt32PerCacheline);
617 const uint32_t fill_end = RoundDownPow2((id_htable_size * (S_CAST(uint64_t, tidx) + 1)) / thread_ct, kInt32PerCacheline);
618 SetAllU32Arr(fill_end - fill_start, &(id_htable[fill_start]));
619
620 // 2. sync.Once
621 if (THREAD_BLOCK_FINISH(arg)) {
622 THREAD_RETURN;
623 }
624
625 // 3. Fill hash table in parallel, and then return.
626 NondupHtableMakerMain(tidx, thread_ct, ctx);
627 THREAD_RETURN;
628 }
629
630 PglErr MakeNondupHtable(const uintptr_t* subset_mask, const char* const* item_ids, uintptr_t item_ct, uint32_t id_htable_size, uint32_t max_thread_ct, uint32_t* id_htable, uint32_t* dup_found_ptr) {
631 PglErr reterr = kPglRetSuccess;
632 ThreadGroup tg;
633 PreinitThreads(&tg);
634 NondupHtableMaker ctx;
635 {
636 uint32_t thread_ct = item_ct / 65536;
637 if (!thread_ct) {
638 thread_ct = 1;
639 } else {
640 if (thread_ct > max_thread_ct) {
641 thread_ct = max_thread_ct;
642 }
643 if (thread_ct > kMaxDupflagThreads) {
644 thread_ct = kMaxDupflagThreads;
645 }
646 }
647 if (unlikely(SetThreadCt0(thread_ct - 1, &tg))) {
648 goto MakeNondupHtable_ret_NOMEM;
649 }
650
651 ctx.subset_mask = subset_mask;
652 ctx.item_ids = item_ids;
653 ctx.item_ct = item_ct;
654 ctx.id_htable_size = id_htable_size;
655 ctx.id_htable = id_htable;
656 ctx.dup_found = 0;
657
658 uint32_t item_uidx = AdvTo1Bit(subset_mask, 0);
659 uint32_t item_idx = 0;
660 ctx.item_uidx_starts[0] = item_uidx;
661 for (uintptr_t tidx = 1; tidx != thread_ct; ++tidx) {
662 const uint32_t item_idx_new = (item_ct * S_CAST(uint64_t, tidx)) / thread_ct;
663 item_uidx = FindNth1BitFrom(subset_mask, item_uidx + 1, item_idx_new - item_idx);
664 ctx.item_uidx_starts[tidx] = item_uidx;
665 item_idx = item_idx_new;
666 }
667
668 if (thread_ct > 1) {
669 SetThreadFuncAndData(NondupHtableMakerThread, &ctx, &tg);
670 if (unlikely(SpawnThreads(&tg))) {
671 goto MakeNondupHtable_ret_THREAD_CREATE_FAIL;
672 }
673 }
674 const uint32_t fill_start = RoundDownPow2((id_htable_size * S_CAST(uint64_t, thread_ct - 1)) / thread_ct, kInt32PerCacheline);
675 SetAllU32Arr(id_htable_size - fill_start, &(id_htable[fill_start]));
676 if (thread_ct > 1) {
677 JoinThreads(&tg);
678 DeclareLastThreadBlock(&tg);
679 SpawnThreads(&tg);
680 }
681 NondupHtableMakerMain(thread_ct - 1, thread_ct, &ctx);
682 JoinThreads0(&tg);
683 *dup_found_ptr = ctx.dup_found;
684 }
685 while (0) {
686 MakeNondupHtable_ret_NOMEM:
687 reterr = kPglRetNomem;
688 break;
689 MakeNondupHtable_ret_THREAD_CREATE_FAIL:
690 reterr = kPglRetThreadCreateFail;
691 break;
692 }
693 CleanupThreads(&tg);
694 return reterr;
695 }
696
697 PglErr AllocAndPopulateNondupHtableMt(unsigned char* arena_top, const uintptr_t* subset_mask, const char* const* item_ids, uintptr_t item_ct, uint32_t max_thread_ct, unsigned char** arena_bottom_ptr, uint32_t** id_htable_ptr, uint32_t* id_htable_size_ptr, uint32_t* dup_found_ptr) {
698 uint32_t id_htable_size = GetHtableFastSize(item_ct);
699 const uintptr_t wkspace_left_rd = RoundDownPow2(S_CAST(uintptr_t, arena_top - (*arena_bottom_ptr)), kCacheline);
700 if (wkspace_left_rd < id_htable_size * sizeof(int32_t)) {
701 id_htable_size = wkspace_left_rd / sizeof(int32_t);
702 const uint32_t min_htable_size = GetHtableMinSize(item_ct);
703 if (id_htable_size < min_htable_size) {
704 return kPglRetNomem;
705 }
706 }
707 *id_htable_ptr = S_CAST(uint32_t*, arena_alloc_raw_rd(id_htable_size * sizeof(int32_t), arena_bottom_ptr));
708 *id_htable_size_ptr = id_htable_size;
709 return MakeNondupHtable(subset_mask, item_ids, item_ct, id_htable_size, max_thread_ct, *id_htable_ptr, dup_found_ptr);
710 }
711
712 void NondupIdLoadProcessTokens(const char* const* item_ids, const uint32_t* item_id_htable, const char* shard_start, const char* shard_end, uint32_t item_id_htable_size, uintptr_t* already_seen) {
713 const char* shard_iter = shard_start;
714 while (1) {
715 shard_iter = FirstPostspaceBounded(shard_iter, shard_end);
716 if (shard_iter == shard_end) {
717 return;
718 }
719 const char* token_end = CurTokenEnd(shard_iter);
720 const uint32_t item_uidx = IdHtableFindNnt(shard_iter, item_ids, item_id_htable, token_end - shard_iter, item_id_htable_size);
721 shard_iter = token_end;
722 if (item_uidx == UINT32_MAX) {
723 continue;
724 }
725 SetBit(item_uidx, already_seen);
726 }
727 }
728
729 CONSTI32(kMaxNondupIdLoadThreads, 8);
730
731 typedef struct NondupIdLoadCtxStruct {
732 const char* const* item_ids;
733 const uint32_t* item_id_htable;
734 uintptr_t item_id_htable_size;
735
736 char* shard_boundaries[kMaxNondupIdLoadThreads + 1];
737 uintptr_t* already_seens[kMaxNondupIdLoadThreads];
738 } NondupIdLoadCtx;
739
740 THREAD_FUNC_DECL NondupIdLoadThread(void* raw_arg) {
741 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
742 const uintptr_t tidx_p1 = arg->tidx + 1;
743 NondupIdLoadCtx* ctx = S_CAST(NondupIdLoadCtx*, arg->sharedp->context);
744
745 const char* const* item_ids = ctx->item_ids;
746 const uint32_t* item_id_htable = ctx->item_id_htable;
747 const uintptr_t item_id_htable_size = ctx->item_id_htable_size;
748 uintptr_t* already_seen = ctx->already_seens[tidx_p1];
749 do {
750 NondupIdLoadProcessTokens(item_ids, item_id_htable, ctx->shard_boundaries[tidx_p1], ctx->shard_boundaries[tidx_p1 + 1], item_id_htable_size, already_seen);
751 } while (!THREAD_BLOCK_FINISH(arg));
752 THREAD_RETURN;
753 }
754
755 PglErr NondupIdLoad(unsigned char* arena_bottom, unsigned char* arena_top, const char* const* item_ids, const char* fname, uint32_t raw_item_ct, uint32_t item_ct, uint32_t max_thread_ct, uintptr_t* item_set, uint32_t* dup_found_ptr, char* errbuf) {
756 PglErr reterr = kPglRetSuccess;
757 TokenStream tks;
758 ThreadGroup tg;
759 PreinitTokenStream(&tks);
760 PreinitThreads(&tg);
761 NondupIdLoadCtx ctx;
762 errbuf[0] = '\0';
763 {
764 const uint32_t calc_thread_ct_m1 = MINV(max_thread_ct, kMaxNondupIdLoadThreads) - 1;
765 if (unlikely(SetThreadCt0(calc_thread_ct_m1, &tg))) {
766 goto NondupIdLoad_ret_NOMEM;
767 }
768 if (!item_ct) {
769 goto NondupIdLoad_ret_1;
770 }
771 uint32_t decompress_thread_ct = 1;
772 if (max_thread_ct > calc_thread_ct_m1 + 2) {
773 decompress_thread_ct = max_thread_ct - calc_thread_ct_m1 - 1;
774 }
775 const uint32_t raw_item_ctl = BitCtToWordCt(raw_item_ct);
776 for (uint32_t tidx = 1; tidx <= calc_thread_ct_m1; ++tidx) {
777 if (unlikely(arena_calloc_w(arena_top, raw_item_ctl, &arena_bottom, &(ctx.already_seens[tidx])))) {
778 goto NondupIdLoad_ret_NOMEM;
779 }
780 }
781 if (unlikely(S_CAST(uintptr_t, arena_top - arena_bottom) < kTokenStreamBlen)) {
782 goto NondupIdLoad_ret_NOMEM;
783 }
784 char* dst = S_CAST(char*, arena_end_alloc_raw(kTokenStreamBlen, &arena_top));
785 reterr = TextStreamOpenEx(fname, 0, kTokenStreamBlen, decompress_thread_ct, nullptr, dst, &(tks.txs));
786 if (unlikely(reterr)) {
787 goto NondupIdLoad_ret_TKSTREAM_FAIL;
788 }
789 // Allocate/initialize hash table last, so we can make the most appropriate
790 // speed/size tradeoff.
791 uint32_t* item_id_htable;
792 uint32_t item_id_htable_size;
793 reterr = AllocAndPopulateNondupHtableMt(arena_top, item_set, item_ids, item_ct, max_thread_ct, &arena_bottom, &item_id_htable, &item_id_htable_size, dup_found_ptr);
794 if (reterr || (*dup_found_ptr)) {
795 goto NondupIdLoad_ret_1;
796 }
797 if (calc_thread_ct_m1) {
798 ctx.item_ids = item_ids;
799 ctx.item_id_htable = item_id_htable;
800 ctx.item_id_htable_size = item_id_htable_size;
801 SetThreadFuncAndData(NondupIdLoadThread, &ctx, &tg);
802 }
803 ZeroWArr(raw_item_ctl, item_set);
804 while (1) {
805 reterr = TksNext(&tks, calc_thread_ct_m1 + 1, ctx.shard_boundaries);
806 if (reterr) {
807 break;
808 }
809 if (calc_thread_ct_m1) {
810 if (unlikely(SpawnThreads(&tg))) {
811 goto NondupIdLoad_ret_THREAD_CREATE_FAIL;
812 }
813 }
814 NondupIdLoadProcessTokens(item_ids, item_id_htable, ctx.shard_boundaries[0], ctx.shard_boundaries[1], item_id_htable_size, item_set);
815 JoinThreads0(&tg);
816 }
817 if (unlikely(reterr != kPglRetEof)) {
818 goto NondupIdLoad_ret_TKSTREAM_FAIL;
819 }
820 reterr = kPglRetSuccess;
821 for (uint32_t tidx = 1; tidx <= calc_thread_ct_m1; ++tidx) {
822 BitvecOr(ctx.already_seens[tidx], raw_item_ctl, item_set);
823 }
824 }
825 while (0) {
826 NondupIdLoad_ret_NOMEM:
827 reterr = kPglRetNomem;
828 break;
829 NondupIdLoad_ret_TKSTREAM_FAIL:
830 // copy TextErrPrint() logic for now, will probably move to plink2_text
831 {
832 reterr = TokenStreamErrcode(&tks);
833 const char* errmsg = TokenStreamError(&tks);
834 if (reterr == kPglRetOpenFail) {
835 snprintf(errbuf, 2 * kMaxMediumLine, "Error: Failed to open %s : %s.\n", fname, errmsg);
836 } else if (reterr == kPglRetReadFail) {
837 snprintf(errbuf, 2 * kMaxMediumLine, "Error: %s read failure: %s.\n", fname, errmsg);
838 } else if (reterr == kPglRetDecompressFail) {
839 snprintf(errbuf, 2 * kMaxMediumLine, "Error: %s decompression failure: %s.\n", fname, errmsg);
840 } else if (reterr == kPglRetMalformedInput) {
841 snprintf(errbuf, 2 * kMaxMediumLine, "Error: Pathologically long token in %s.\n", fname);
842 }
843 }
844 break;
845 NondupIdLoad_ret_THREAD_CREATE_FAIL:
846 reterr = kPglRetThreadCreateFail;
847 }
848 NondupIdLoad_ret_1:
849 CleanupThreads(&tg);
850 if (unlikely(CleanupTokenStream(&tks, &reterr))) {
851 snprintf(errbuf, 2 * kMaxMediumLine, "Error: %s read failure: %s.\n", fname, strerror(errno));
852 }
853 return reterr;
854 }
855
856 #ifdef __cplusplus
857 } // namespace plink2
858 #endif