kutil/queue: use util_snprintf() in util_queue_init
[mesa.git] / src / util / u_queue.c
1 /*
2 * Copyright © 2016 Advanced Micro Devices, Inc.
3 * All Rights Reserved.
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining
6 * a copy of this software and associated documentation files (the
7 * "Software"), to deal in the Software without restriction, including
8 * without limitation the rights to use, copy, modify, merge, publish,
9 * distribute, sub license, and/or sell copies of the Software, and to
10 * permit persons to whom the Software is furnished to do so, subject to
11 * the following conditions:
12 *
13 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
14 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
15 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
16 * NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS, AUTHORS
17 * AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 * USE OR OTHER DEALINGS IN THE SOFTWARE.
21 *
22 * The above copyright notice and this permission notice (including the
23 * next paragraph) shall be included in all copies or substantial portions
24 * of the Software.
25 */
26
27 #include "u_queue.h"
28
29 #include <time.h>
30
31 #include "util/os_time.h"
32 #include "util/u_string.h"
33 #include "util/u_thread.h"
34 #include "u_process.h"
35
36 static void util_queue_killall_and_wait(struct util_queue *queue);
37
38 /****************************************************************************
39 * Wait for all queues to assert idle when exit() is called.
40 *
41 * Otherwise, C++ static variable destructors can be called while threads
42 * are using the static variables.
43 */
44
45 static once_flag atexit_once_flag = ONCE_FLAG_INIT;
46 static struct list_head queue_list;
47 static mtx_t exit_mutex = _MTX_INITIALIZER_NP;
48
49 static void
50 atexit_handler(void)
51 {
52 struct util_queue *iter;
53
54 mtx_lock(&exit_mutex);
55 /* Wait for all queues to assert idle. */
56 LIST_FOR_EACH_ENTRY(iter, &queue_list, head) {
57 util_queue_killall_and_wait(iter);
58 }
59 mtx_unlock(&exit_mutex);
60 }
61
62 static void
63 global_init(void)
64 {
65 LIST_INITHEAD(&queue_list);
66 atexit(atexit_handler);
67 }
68
69 static void
70 add_to_atexit_list(struct util_queue *queue)
71 {
72 call_once(&atexit_once_flag, global_init);
73
74 mtx_lock(&exit_mutex);
75 LIST_ADD(&queue->head, &queue_list);
76 mtx_unlock(&exit_mutex);
77 }
78
79 static void
80 remove_from_atexit_list(struct util_queue *queue)
81 {
82 struct util_queue *iter, *tmp;
83
84 mtx_lock(&exit_mutex);
85 LIST_FOR_EACH_ENTRY_SAFE(iter, tmp, &queue_list, head) {
86 if (iter == queue) {
87 LIST_DEL(&iter->head);
88 break;
89 }
90 }
91 mtx_unlock(&exit_mutex);
92 }
93
94 /****************************************************************************
95 * util_queue_fence
96 */
97
98 #ifdef UTIL_QUEUE_FENCE_FUTEX
99 static bool
100 do_futex_fence_wait(struct util_queue_fence *fence,
101 bool timeout, int64_t abs_timeout)
102 {
103 uint32_t v = fence->val;
104 struct timespec ts;
105 ts.tv_sec = abs_timeout / (1000*1000*1000);
106 ts.tv_nsec = abs_timeout % (1000*1000*1000);
107
108 while (v != 0) {
109 if (v != 2) {
110 v = p_atomic_cmpxchg(&fence->val, 1, 2);
111 if (v == 0)
112 return true;
113 }
114
115 int r = futex_wait(&fence->val, 2, timeout ? &ts : NULL);
116 if (timeout && r < 0) {
117 if (errno == ETIMEDOUT)
118 return false;
119 }
120
121 v = fence->val;
122 }
123
124 return true;
125 }
126
127 void
128 _util_queue_fence_wait(struct util_queue_fence *fence)
129 {
130 do_futex_fence_wait(fence, false, 0);
131 }
132
133 bool
134 _util_queue_fence_wait_timeout(struct util_queue_fence *fence,
135 int64_t abs_timeout)
136 {
137 return do_futex_fence_wait(fence, true, abs_timeout);
138 }
139
140 #endif
141
142 #ifdef UTIL_QUEUE_FENCE_STANDARD
143 void
144 util_queue_fence_signal(struct util_queue_fence *fence)
145 {
146 mtx_lock(&fence->mutex);
147 fence->signalled = true;
148 cnd_broadcast(&fence->cond);
149 mtx_unlock(&fence->mutex);
150 }
151
152 void
153 _util_queue_fence_wait(struct util_queue_fence *fence)
154 {
155 mtx_lock(&fence->mutex);
156 while (!fence->signalled)
157 cnd_wait(&fence->cond, &fence->mutex);
158 mtx_unlock(&fence->mutex);
159 }
160
161 bool
162 _util_queue_fence_wait_timeout(struct util_queue_fence *fence,
163 int64_t abs_timeout)
164 {
165 /* This terrible hack is made necessary by the fact that we really want an
166 * internal interface consistent with os_time_*, but cnd_timedwait is spec'd
167 * to be relative to the TIME_UTC clock.
168 */
169 int64_t rel = abs_timeout - os_time_get_nano();
170
171 if (rel > 0) {
172 struct timespec ts;
173
174 timespec_get(&ts, TIME_UTC);
175
176 ts.tv_sec += abs_timeout / (1000*1000*1000);
177 ts.tv_nsec += abs_timeout % (1000*1000*1000);
178 if (ts.tv_nsec >= (1000*1000*1000)) {
179 ts.tv_sec++;
180 ts.tv_nsec -= (1000*1000*1000);
181 }
182
183 mtx_lock(&fence->mutex);
184 while (!fence->signalled) {
185 if (cnd_timedwait(&fence->cond, &fence->mutex, &ts) != thrd_success)
186 break;
187 }
188 mtx_unlock(&fence->mutex);
189 }
190
191 return fence->signalled;
192 }
193
194 void
195 util_queue_fence_init(struct util_queue_fence *fence)
196 {
197 memset(fence, 0, sizeof(*fence));
198 (void) mtx_init(&fence->mutex, mtx_plain);
199 cnd_init(&fence->cond);
200 fence->signalled = true;
201 }
202
203 void
204 util_queue_fence_destroy(struct util_queue_fence *fence)
205 {
206 assert(fence->signalled);
207
208 /* Ensure that another thread is not in the middle of
209 * util_queue_fence_signal (having set the fence to signalled but still
210 * holding the fence mutex).
211 *
212 * A common contract between threads is that as soon as a fence is signalled
213 * by thread A, thread B is allowed to destroy it. Since
214 * util_queue_fence_is_signalled does not lock the fence mutex (for
215 * performance reasons), we must do so here.
216 */
217 mtx_lock(&fence->mutex);
218 mtx_unlock(&fence->mutex);
219
220 cnd_destroy(&fence->cond);
221 mtx_destroy(&fence->mutex);
222 }
223 #endif
224
225 /****************************************************************************
226 * util_queue implementation
227 */
228
229 struct thread_input {
230 struct util_queue *queue;
231 int thread_index;
232 };
233
234 static int
235 util_queue_thread_func(void *input)
236 {
237 struct util_queue *queue = ((struct thread_input*)input)->queue;
238 int thread_index = ((struct thread_input*)input)->thread_index;
239
240 free(input);
241
242 if (strlen(queue->name) > 0) {
243 char name[16];
244 util_snprintf(name, sizeof(name), "%s%i", queue->name, thread_index);
245 u_thread_setname(name);
246 }
247
248 while (1) {
249 struct util_queue_job job;
250
251 mtx_lock(&queue->lock);
252 assert(queue->num_queued >= 0 && queue->num_queued <= queue->max_jobs);
253
254 /* wait if the queue is empty */
255 while (!queue->kill_threads && queue->num_queued == 0)
256 cnd_wait(&queue->has_queued_cond, &queue->lock);
257
258 if (queue->kill_threads) {
259 mtx_unlock(&queue->lock);
260 break;
261 }
262
263 job = queue->jobs[queue->read_idx];
264 memset(&queue->jobs[queue->read_idx], 0, sizeof(struct util_queue_job));
265 queue->read_idx = (queue->read_idx + 1) % queue->max_jobs;
266
267 queue->num_queued--;
268 cnd_signal(&queue->has_space_cond);
269 mtx_unlock(&queue->lock);
270
271 if (job.job) {
272 job.execute(job.job, thread_index);
273 util_queue_fence_signal(job.fence);
274 if (job.cleanup)
275 job.cleanup(job.job, thread_index);
276 }
277 }
278
279 /* signal remaining jobs before terminating */
280 mtx_lock(&queue->lock);
281 for (unsigned i = queue->read_idx; i != queue->write_idx;
282 i = (i + 1) % queue->max_jobs) {
283 if (queue->jobs[i].job) {
284 util_queue_fence_signal(queue->jobs[i].fence);
285 queue->jobs[i].job = NULL;
286 }
287 }
288 queue->read_idx = queue->write_idx;
289 queue->num_queued = 0;
290 mtx_unlock(&queue->lock);
291 return 0;
292 }
293
294 bool
295 util_queue_init(struct util_queue *queue,
296 const char *name,
297 unsigned max_jobs,
298 unsigned num_threads,
299 unsigned flags)
300 {
301 unsigned i;
302
303 /* Form the thread name from process_name and name, limited to 13
304 * characters. Characters 14-15 are reserved for the thread number.
305 * Character 16 should be 0. Final form: "process:name12"
306 *
307 * If name is too long, it's truncated. If any space is left, the process
308 * name fills it.
309 */
310 const char *process_name = util_get_process_name();
311 int process_len = process_name ? strlen(process_name) : 0;
312 int name_len = strlen(name);
313 const int max_chars = sizeof(queue->name) - 1;
314
315 name_len = MIN2(name_len, max_chars);
316
317 /* See if there is any space left for the process name, reserve 1 for
318 * the colon. */
319 process_len = MIN2(process_len, max_chars - name_len - 1);
320 process_len = MAX2(process_len, 0);
321
322 memset(queue, 0, sizeof(*queue));
323
324 if (process_len) {
325 util_snprintf(queue->name, sizeof(queue->name), "%.*s:%s",
326 process_len, process_name, name);
327 } else {
328 util_snprintf(queue->name, sizeof(queue->name), "%s", name);
329 }
330
331 queue->flags = flags;
332 queue->num_threads = num_threads;
333 queue->max_jobs = max_jobs;
334
335 queue->jobs = (struct util_queue_job*)
336 calloc(max_jobs, sizeof(struct util_queue_job));
337 if (!queue->jobs)
338 goto fail;
339
340 (void) mtx_init(&queue->lock, mtx_plain);
341 (void) mtx_init(&queue->finish_lock, mtx_plain);
342
343 queue->num_queued = 0;
344 cnd_init(&queue->has_queued_cond);
345 cnd_init(&queue->has_space_cond);
346
347 queue->threads = (thrd_t*) calloc(num_threads, sizeof(thrd_t));
348 if (!queue->threads)
349 goto fail;
350
351 /* start threads */
352 for (i = 0; i < num_threads; i++) {
353 struct thread_input *input =
354 (struct thread_input *) malloc(sizeof(struct thread_input));
355 input->queue = queue;
356 input->thread_index = i;
357
358 queue->threads[i] = u_thread_create(util_queue_thread_func, input);
359
360 if (!queue->threads[i]) {
361 free(input);
362
363 if (i == 0) {
364 /* no threads created, fail */
365 goto fail;
366 } else {
367 /* at least one thread created, so use it */
368 queue->num_threads = i;
369 break;
370 }
371 }
372
373 if (flags & UTIL_QUEUE_INIT_USE_MINIMUM_PRIORITY) {
374 #if defined(__linux__) && defined(SCHED_IDLE)
375 struct sched_param sched_param = {0};
376
377 /* The nice() function can only set a maximum of 19.
378 * SCHED_IDLE is the same as nice = 20.
379 *
380 * Note that Linux only allows decreasing the priority. The original
381 * priority can't be restored.
382 */
383 pthread_setschedparam(queue->threads[i], SCHED_IDLE, &sched_param);
384 #endif
385 }
386 }
387
388 add_to_atexit_list(queue);
389 return true;
390
391 fail:
392 free(queue->threads);
393
394 if (queue->jobs) {
395 cnd_destroy(&queue->has_space_cond);
396 cnd_destroy(&queue->has_queued_cond);
397 mtx_destroy(&queue->lock);
398 free(queue->jobs);
399 }
400 /* also util_queue_is_initialized can be used to check for success */
401 memset(queue, 0, sizeof(*queue));
402 return false;
403 }
404
405 static void
406 util_queue_killall_and_wait(struct util_queue *queue)
407 {
408 unsigned i;
409
410 /* Signal all threads to terminate. */
411 mtx_lock(&queue->lock);
412 queue->kill_threads = 1;
413 cnd_broadcast(&queue->has_queued_cond);
414 mtx_unlock(&queue->lock);
415
416 for (i = 0; i < queue->num_threads; i++)
417 thrd_join(queue->threads[i], NULL);
418 queue->num_threads = 0;
419 }
420
421 void
422 util_queue_destroy(struct util_queue *queue)
423 {
424 util_queue_killall_and_wait(queue);
425 remove_from_atexit_list(queue);
426
427 cnd_destroy(&queue->has_space_cond);
428 cnd_destroy(&queue->has_queued_cond);
429 mtx_destroy(&queue->finish_lock);
430 mtx_destroy(&queue->lock);
431 free(queue->jobs);
432 free(queue->threads);
433 }
434
435 void
436 util_queue_add_job(struct util_queue *queue,
437 void *job,
438 struct util_queue_fence *fence,
439 util_queue_execute_func execute,
440 util_queue_execute_func cleanup)
441 {
442 struct util_queue_job *ptr;
443
444 mtx_lock(&queue->lock);
445 if (queue->kill_threads) {
446 mtx_unlock(&queue->lock);
447 /* well no good option here, but any leaks will be
448 * short-lived as things are shutting down..
449 */
450 return;
451 }
452
453 util_queue_fence_reset(fence);
454
455 assert(queue->num_queued >= 0 && queue->num_queued <= queue->max_jobs);
456
457 if (queue->num_queued == queue->max_jobs) {
458 if (queue->flags & UTIL_QUEUE_INIT_RESIZE_IF_FULL) {
459 /* If the queue is full, make it larger to avoid waiting for a free
460 * slot.
461 */
462 unsigned new_max_jobs = queue->max_jobs + 8;
463 struct util_queue_job *jobs =
464 (struct util_queue_job*)calloc(new_max_jobs,
465 sizeof(struct util_queue_job));
466 assert(jobs);
467
468 /* Copy all queued jobs into the new list. */
469 unsigned num_jobs = 0;
470 unsigned i = queue->read_idx;
471
472 do {
473 jobs[num_jobs++] = queue->jobs[i];
474 i = (i + 1) % queue->max_jobs;
475 } while (i != queue->write_idx);
476
477 assert(num_jobs == queue->num_queued);
478
479 free(queue->jobs);
480 queue->jobs = jobs;
481 queue->read_idx = 0;
482 queue->write_idx = num_jobs;
483 queue->max_jobs = new_max_jobs;
484 } else {
485 /* Wait until there is a free slot. */
486 while (queue->num_queued == queue->max_jobs)
487 cnd_wait(&queue->has_space_cond, &queue->lock);
488 }
489 }
490
491 ptr = &queue->jobs[queue->write_idx];
492 assert(ptr->job == NULL);
493 ptr->job = job;
494 ptr->fence = fence;
495 ptr->execute = execute;
496 ptr->cleanup = cleanup;
497 queue->write_idx = (queue->write_idx + 1) % queue->max_jobs;
498
499 queue->num_queued++;
500 cnd_signal(&queue->has_queued_cond);
501 mtx_unlock(&queue->lock);
502 }
503
504 /**
505 * Remove a queued job. If the job hasn't started execution, it's removed from
506 * the queue. If the job has started execution, the function waits for it to
507 * complete.
508 *
509 * In all cases, the fence is signalled when the function returns.
510 *
511 * The function can be used when destroying an object associated with the job
512 * when you don't care about the job completion state.
513 */
514 void
515 util_queue_drop_job(struct util_queue *queue, struct util_queue_fence *fence)
516 {
517 bool removed = false;
518
519 if (util_queue_fence_is_signalled(fence))
520 return;
521
522 mtx_lock(&queue->lock);
523 for (unsigned i = queue->read_idx; i != queue->write_idx;
524 i = (i + 1) % queue->max_jobs) {
525 if (queue->jobs[i].fence == fence) {
526 if (queue->jobs[i].cleanup)
527 queue->jobs[i].cleanup(queue->jobs[i].job, -1);
528
529 /* Just clear it. The threads will treat as a no-op job. */
530 memset(&queue->jobs[i], 0, sizeof(queue->jobs[i]));
531 removed = true;
532 break;
533 }
534 }
535 mtx_unlock(&queue->lock);
536
537 if (removed)
538 util_queue_fence_signal(fence);
539 else
540 util_queue_fence_wait(fence);
541 }
542
543 static void
544 util_queue_finish_execute(void *data, int num_thread)
545 {
546 util_barrier *barrier = data;
547 util_barrier_wait(barrier);
548 }
549
550 /**
551 * Wait until all previously added jobs have completed.
552 */
553 void
554 util_queue_finish(struct util_queue *queue)
555 {
556 util_barrier barrier;
557 struct util_queue_fence *fences = malloc(queue->num_threads * sizeof(*fences));
558
559 util_barrier_init(&barrier, queue->num_threads);
560
561 /* If 2 threads were adding jobs for 2 different barries at the same time,
562 * a deadlock would happen, because 1 barrier requires that all threads
563 * wait for it exclusively.
564 */
565 mtx_lock(&queue->finish_lock);
566
567 for (unsigned i = 0; i < queue->num_threads; ++i) {
568 util_queue_fence_init(&fences[i]);
569 util_queue_add_job(queue, &barrier, &fences[i], util_queue_finish_execute, NULL);
570 }
571
572 for (unsigned i = 0; i < queue->num_threads; ++i) {
573 util_queue_fence_wait(&fences[i]);
574 util_queue_fence_destroy(&fences[i]);
575 }
576 mtx_unlock(&queue->finish_lock);
577
578 util_barrier_destroy(&barrier);
579
580 free(fences);
581 }
582
583 int64_t
584 util_queue_get_thread_time_nano(struct util_queue *queue, unsigned thread_index)
585 {
586 /* Allow some flexibility by not raising an error. */
587 if (thread_index >= queue->num_threads)
588 return 0;
589
590 return u_thread_get_time_nano(queue->threads[thread_index]);
591 }