xref: /src/sys/contrib/openzfs/module/zstd/lib/common/pool.c (revision 8a62a2a5659d1839d8799b4274c04469d7f17c78)
1 // SPDX-License-Identifier: BSD-3-Clause OR GPL-2.0-only
2 /*
3  * Copyright (c) Meta Platforms, Inc. and affiliates.
4  * All rights reserved.
5  *
6  * This source code is licensed under both the BSD-style license (found in the
7  * LICENSE file in the root directory of this source tree) and the GPLv2 (found
8  * in the COPYING file in the root directory of this source tree).
9  * You may select, at your option, one of the above-listed licenses.
10  */
11 
12 
13 /* ======   Dependencies   ======= */
14 #include "../common/allocations.h"  /* ZSTD_customCalloc, ZSTD_customFree */
15 #include "zstd_deps.h" /* size_t */
16 #include "debug.h"     /* assert */
17 #include "pool.h"
18 
19 /* ======   Compiler specifics   ====== */
20 #if defined(_MSC_VER)
21 #  pragma warning(disable : 4204)        /* disable: C4204: non-constant aggregate initializer */
22 #endif
23 
24 
25 #ifdef ZSTD_MULTITHREAD
26 
27 #include "threading.h"   /* pthread adaptation */
28 
29 /* A job is a function and an opaque argument */
30 typedef struct POOL_job_s {
31     POOL_function function;
32     void *opaque;
33 } POOL_job;
34 
35 struct POOL_ctx_s {
36     ZSTD_customMem customMem;
37     /* Keep track of the threads */
38     ZSTD_pthread_t* threads;
39     size_t threadCapacity;
40     size_t threadLimit;
41 
42     /* The queue is a circular buffer */
43     POOL_job *queue;
44     size_t queueHead;
45     size_t queueTail;
46     size_t queueSize;
47 
48     /* The number of threads working on jobs */
49     size_t numThreadsBusy;
50     /* Indicates if the queue is empty */
51     int queueEmpty;
52 
53     /* The mutex protects the queue */
54     ZSTD_pthread_mutex_t queueMutex;
55     /* Condition variable for pushers to wait on when the queue is full */
56     ZSTD_pthread_cond_t queuePushCond;
57     /* Condition variables for poppers to wait on when the queue is empty */
58     ZSTD_pthread_cond_t queuePopCond;
59     /* Indicates if the queue is shutting down */
60     int shutdown;
61 };
62 
63 /* POOL_thread() :
64  * Work thread for the thread pool.
65  * Waits for jobs and executes them.
66  * @returns : NULL on failure else non-null.
67  */
POOL_thread(void * opaque)68 static void* POOL_thread(void* opaque) {
69     POOL_ctx* const ctx = (POOL_ctx*)opaque;
70     if (!ctx) { return NULL; }
71     for (;;) {
72         /* Lock the mutex and wait for a non-empty queue or until shutdown */
73         ZSTD_pthread_mutex_lock(&ctx->queueMutex);
74 
75         while ( ctx->queueEmpty
76             || (ctx->numThreadsBusy >= ctx->threadLimit) ) {
77             if (ctx->shutdown) {
78                 /* even if !queueEmpty, (possible if numThreadsBusy >= threadLimit),
79                  * a few threads will be shutdown while !queueEmpty,
80                  * but enough threads will remain active to finish the queue */
81                 ZSTD_pthread_mutex_unlock(&ctx->queueMutex);
82                 return opaque;
83             }
84             ZSTD_pthread_cond_wait(&ctx->queuePopCond, &ctx->queueMutex);
85         }
86         /* Pop a job off the queue */
87         {   POOL_job const job = ctx->queue[ctx->queueHead];
88             ctx->queueHead = (ctx->queueHead + 1) % ctx->queueSize;
89             ctx->numThreadsBusy++;
90             ctx->queueEmpty = (ctx->queueHead == ctx->queueTail);
91             /* Unlock the mutex, signal a pusher, and run the job */
92             ZSTD_pthread_cond_signal(&ctx->queuePushCond);
93             ZSTD_pthread_mutex_unlock(&ctx->queueMutex);
94 
95             job.function(job.opaque);
96 
97             /* If the intended queue size was 0, signal after finishing job */
98             ZSTD_pthread_mutex_lock(&ctx->queueMutex);
99             ctx->numThreadsBusy--;
100             ZSTD_pthread_cond_signal(&ctx->queuePushCond);
101             ZSTD_pthread_mutex_unlock(&ctx->queueMutex);
102         }
103     }  /* for (;;) */
104     assert(0);  /* Unreachable */
105 }
106 
107 /* ZSTD_createThreadPool() : public access point */
ZSTD_createThreadPool(size_t numThreads)108 POOL_ctx* ZSTD_createThreadPool(size_t numThreads) {
109     return POOL_create (numThreads, 0);
110 }
111 
POOL_create(size_t numThreads,size_t queueSize)112 POOL_ctx* POOL_create(size_t numThreads, size_t queueSize) {
113     return POOL_create_advanced(numThreads, queueSize, ZSTD_defaultCMem);
114 }
115 
POOL_create_advanced(size_t numThreads,size_t queueSize,ZSTD_customMem customMem)116 POOL_ctx* POOL_create_advanced(size_t numThreads, size_t queueSize,
117                                ZSTD_customMem customMem)
118 {
119     POOL_ctx* ctx;
120     /* Check parameters */
121     if (!numThreads) { return NULL; }
122     /* Allocate the context and zero initialize */
123     ctx = (POOL_ctx*)ZSTD_customCalloc(sizeof(POOL_ctx), customMem);
124     if (!ctx) { return NULL; }
125     /* Initialize the job queue.
126      * It needs one extra space since one space is wasted to differentiate
127      * empty and full queues.
128      */
129     ctx->queueSize = queueSize + 1;
130     ctx->queue = (POOL_job*)ZSTD_customCalloc(ctx->queueSize * sizeof(POOL_job), customMem);
131     ctx->queueHead = 0;
132     ctx->queueTail = 0;
133     ctx->numThreadsBusy = 0;
134     ctx->queueEmpty = 1;
135     {
136         int error = 0;
137         error |= ZSTD_pthread_mutex_init(&ctx->queueMutex, NULL);
138         error |= ZSTD_pthread_cond_init(&ctx->queuePushCond, NULL);
139         error |= ZSTD_pthread_cond_init(&ctx->queuePopCond, NULL);
140         if (error) { POOL_free(ctx); return NULL; }
141     }
142     ctx->shutdown = 0;
143     /* Allocate space for the thread handles */
144     ctx->threads = (ZSTD_pthread_t*)ZSTD_customCalloc(numThreads * sizeof(ZSTD_pthread_t), customMem);
145     ctx->threadCapacity = 0;
146     ctx->customMem = customMem;
147     /* Check for errors */
148     if (!ctx->threads || !ctx->queue) { POOL_free(ctx); return NULL; }
149     /* Initialize the threads */
150     {   size_t i;
151         for (i = 0; i < numThreads; ++i) {
152             if (ZSTD_pthread_create(&ctx->threads[i], NULL, &POOL_thread, ctx)) {
153                 ctx->threadCapacity = i;
154                 POOL_free(ctx);
155                 return NULL;
156         }   }
157         ctx->threadCapacity = numThreads;
158         ctx->threadLimit = numThreads;
159     }
160     return ctx;
161 }
162 
163 /*! POOL_join() :
164     Shutdown the queue, wake any sleeping threads, and join all of the threads.
165 */
POOL_join(POOL_ctx * ctx)166 static void POOL_join(POOL_ctx* ctx) {
167     /* Shut down the queue */
168     ZSTD_pthread_mutex_lock(&ctx->queueMutex);
169     ctx->shutdown = 1;
170     ZSTD_pthread_mutex_unlock(&ctx->queueMutex);
171     /* Wake up sleeping threads */
172     ZSTD_pthread_cond_broadcast(&ctx->queuePushCond);
173     ZSTD_pthread_cond_broadcast(&ctx->queuePopCond);
174     /* Join all of the threads */
175     {   size_t i;
176         for (i = 0; i < ctx->threadCapacity; ++i) {
177             ZSTD_pthread_join(ctx->threads[i]);  /* note : could fail */
178     }   }
179 }
180 
POOL_free(POOL_ctx * ctx)181 void POOL_free(POOL_ctx *ctx) {
182     if (!ctx) { return; }
183     POOL_join(ctx);
184     ZSTD_pthread_mutex_destroy(&ctx->queueMutex);
185     ZSTD_pthread_cond_destroy(&ctx->queuePushCond);
186     ZSTD_pthread_cond_destroy(&ctx->queuePopCond);
187     ZSTD_customFree(ctx->queue, ctx->customMem);
188     ZSTD_customFree(ctx->threads, ctx->customMem);
189     ZSTD_customFree(ctx, ctx->customMem);
190 }
191 
192 /*! POOL_joinJobs() :
193  *  Waits for all queued jobs to finish executing.
194  */
POOL_joinJobs(POOL_ctx * ctx)195 void POOL_joinJobs(POOL_ctx* ctx) {
196     ZSTD_pthread_mutex_lock(&ctx->queueMutex);
197     while(!ctx->queueEmpty || ctx->numThreadsBusy > 0) {
198         ZSTD_pthread_cond_wait(&ctx->queuePushCond, &ctx->queueMutex);
199     }
200     ZSTD_pthread_mutex_unlock(&ctx->queueMutex);
201 }
202 
ZSTD_freeThreadPool(ZSTD_threadPool * pool)203 void ZSTD_freeThreadPool (ZSTD_threadPool* pool) {
204   POOL_free (pool);
205 }
206 
POOL_sizeof(const POOL_ctx * ctx)207 size_t POOL_sizeof(const POOL_ctx* ctx) {
208     if (ctx==NULL) return 0;  /* supports sizeof NULL */
209     return sizeof(*ctx)
210         + ctx->queueSize * sizeof(POOL_job)
211         + ctx->threadCapacity * sizeof(ZSTD_pthread_t);
212 }
213 
214 
215 /* @return : 0 on success, 1 on error */
POOL_resize_internal(POOL_ctx * ctx,size_t numThreads)216 static int POOL_resize_internal(POOL_ctx* ctx, size_t numThreads)
217 {
218     if (numThreads <= ctx->threadCapacity) {
219         if (!numThreads) return 1;
220         ctx->threadLimit = numThreads;
221         return 0;
222     }
223     /* numThreads > threadCapacity */
224     {   ZSTD_pthread_t* const threadPool = (ZSTD_pthread_t*)ZSTD_customCalloc(numThreads * sizeof(ZSTD_pthread_t), ctx->customMem);
225         if (!threadPool) return 1;
226         /* replace existing thread pool */
227         ZSTD_memcpy(threadPool, ctx->threads, ctx->threadCapacity * sizeof(ZSTD_pthread_t));
228         ZSTD_customFree(ctx->threads, ctx->customMem);
229         ctx->threads = threadPool;
230         /* Initialize additional threads */
231         {   size_t threadId;
232             for (threadId = ctx->threadCapacity; threadId < numThreads; ++threadId) {
233                 if (ZSTD_pthread_create(&threadPool[threadId], NULL, &POOL_thread, ctx)) {
234                     ctx->threadCapacity = threadId;
235                     return 1;
236             }   }
237     }   }
238     /* successfully expanded */
239     ctx->threadCapacity = numThreads;
240     ctx->threadLimit = numThreads;
241     return 0;
242 }
243 
244 /* @return : 0 on success, 1 on error */
POOL_resize(POOL_ctx * ctx,size_t numThreads)245 int POOL_resize(POOL_ctx* ctx, size_t numThreads)
246 {
247     int result;
248     if (ctx==NULL) return 1;
249     ZSTD_pthread_mutex_lock(&ctx->queueMutex);
250     result = POOL_resize_internal(ctx, numThreads);
251     ZSTD_pthread_cond_broadcast(&ctx->queuePopCond);
252     ZSTD_pthread_mutex_unlock(&ctx->queueMutex);
253     return result;
254 }
255 
256 /**
257  * Returns 1 if the queue is full and 0 otherwise.
258  *
259  * When queueSize is 1 (pool was created with an intended queueSize of 0),
260  * then a queue is empty if there is a thread free _and_ no job is waiting.
261  */
isQueueFull(POOL_ctx const * ctx)262 static int isQueueFull(POOL_ctx const* ctx) {
263     if (ctx->queueSize > 1) {
264         return ctx->queueHead == ((ctx->queueTail + 1) % ctx->queueSize);
265     } else {
266         return (ctx->numThreadsBusy == ctx->threadLimit) ||
267                !ctx->queueEmpty;
268     }
269 }
270 
271 
272 static void
POOL_add_internal(POOL_ctx * ctx,POOL_function function,void * opaque)273 POOL_add_internal(POOL_ctx* ctx, POOL_function function, void *opaque)
274 {
275     POOL_job job;
276     job.function = function;
277     job.opaque = opaque;
278     assert(ctx != NULL);
279     if (ctx->shutdown) return;
280 
281     ctx->queueEmpty = 0;
282     ctx->queue[ctx->queueTail] = job;
283     ctx->queueTail = (ctx->queueTail + 1) % ctx->queueSize;
284     ZSTD_pthread_cond_signal(&ctx->queuePopCond);
285 }
286 
POOL_add(POOL_ctx * ctx,POOL_function function,void * opaque)287 void POOL_add(POOL_ctx* ctx, POOL_function function, void* opaque)
288 {
289     assert(ctx != NULL);
290     ZSTD_pthread_mutex_lock(&ctx->queueMutex);
291     /* Wait until there is space in the queue for the new job */
292     while (isQueueFull(ctx) && (!ctx->shutdown)) {
293         ZSTD_pthread_cond_wait(&ctx->queuePushCond, &ctx->queueMutex);
294     }
295     POOL_add_internal(ctx, function, opaque);
296     ZSTD_pthread_mutex_unlock(&ctx->queueMutex);
297 }
298 
299 
POOL_tryAdd(POOL_ctx * ctx,POOL_function function,void * opaque)300 int POOL_tryAdd(POOL_ctx* ctx, POOL_function function, void* opaque)
301 {
302     assert(ctx != NULL);
303     ZSTD_pthread_mutex_lock(&ctx->queueMutex);
304     if (isQueueFull(ctx)) {
305         ZSTD_pthread_mutex_unlock(&ctx->queueMutex);
306         return 0;
307     }
308     POOL_add_internal(ctx, function, opaque);
309     ZSTD_pthread_mutex_unlock(&ctx->queueMutex);
310     return 1;
311 }
312 
313 
314 #else  /* ZSTD_MULTITHREAD  not defined */
315 
316 /* ========================== */
317 /* No multi-threading support */
318 /* ========================== */
319 
320 
321 /* We don't need any data, but if it is empty, malloc() might return NULL. */
322 struct POOL_ctx_s {
323     int dummy;
324 };
325 static POOL_ctx g_poolCtx;
326 
POOL_create(size_t numThreads,size_t queueSize)327 POOL_ctx* POOL_create(size_t numThreads, size_t queueSize) {
328     return POOL_create_advanced(numThreads, queueSize, ZSTD_defaultCMem);
329 }
330 
331 POOL_ctx*
POOL_create_advanced(size_t numThreads,size_t queueSize,ZSTD_customMem customMem)332 POOL_create_advanced(size_t numThreads, size_t queueSize, ZSTD_customMem customMem)
333 {
334     (void)numThreads;
335     (void)queueSize;
336     (void)customMem;
337     return &g_poolCtx;
338 }
339 
POOL_free(POOL_ctx * ctx)340 void POOL_free(POOL_ctx* ctx) {
341     assert(!ctx || ctx == &g_poolCtx);
342     (void)ctx;
343 }
344 
POOL_joinJobs(POOL_ctx * ctx)345 void POOL_joinJobs(POOL_ctx* ctx){
346     assert(!ctx || ctx == &g_poolCtx);
347     (void)ctx;
348 }
349 
POOL_resize(POOL_ctx * ctx,size_t numThreads)350 int POOL_resize(POOL_ctx* ctx, size_t numThreads) {
351     (void)ctx; (void)numThreads;
352     return 0;
353 }
354 
POOL_add(POOL_ctx * ctx,POOL_function function,void * opaque)355 void POOL_add(POOL_ctx* ctx, POOL_function function, void* opaque) {
356     (void)ctx;
357     function(opaque);
358 }
359 
POOL_tryAdd(POOL_ctx * ctx,POOL_function function,void * opaque)360 int POOL_tryAdd(POOL_ctx* ctx, POOL_function function, void* opaque) {
361     (void)ctx;
362     function(opaque);
363     return 1;
364 }
365 
POOL_sizeof(const POOL_ctx * ctx)366 size_t POOL_sizeof(const POOL_ctx* ctx) {
367     if (ctx==NULL) return 0;  /* supports sizeof NULL */
368     assert(ctx == &g_poolCtx);
369     return sizeof(*ctx);
370 }
371 
372 #endif  /* ZSTD_MULTITHREAD */
373