rmagick 7.1.7 → 7.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1394 @@
1
+ /**
2
+ * Offloading GVL-free calls to a Fiber scheduler.
3
+ *
4
+ * Copyright (c) 2009 - RMagick contributors
5
+ *
6
+ * @file rmagick_gvl.cpp
7
+ */
8
+
9
+ #include "rmagick.h"
10
+ #include "ruby/ractor.h"
11
+ #include <atomic>
12
+ #if defined(RMAGICK_OFFLOAD_SAFE)
13
+ #include <cstddef>
14
+ #endif
15
+ // TruffleRuby cannot fork, and has no ruby_thread_has_gvl_p
16
+ #if defined(HAVE_WORKING_FORK) && !defined(TRUFFLERUBY)
17
+ #define RMAGICK_ATFORK 1
18
+ #include <pthread.h>
19
+
20
+ // ruby/thread.h declares it from Ruby 4.0
21
+ extern "C" int ruby_thread_has_gvl_p(void);
22
+ #endif
23
+
24
+
25
+ /*
26
+ * rb_thread_call_without_gvl releases the GVL but keeps the calling thread busy
27
+ * until the ImageMagick function returns. Under a Fiber scheduler that has a
28
+ * worker pool (Async with IO::Event::WorkerPool), that stalls every fiber on
29
+ * the thread for the whole operation. Ruby 4.0 lets rb_nogvl hand a call to
30
+ * the scheduler instead (RB_NOGVL_OFFLOAD_SAFE, Feature #20876): the call runs
31
+ * on a worker thread while the calling fiber is suspended.
32
+ *
33
+ * Two things change for the caller when that happens, and rm_gvl_call deals
34
+ * with both:
35
+ *
36
+ * 1. The scheduler can raise into the waiting fiber, for example when the
37
+ * task is stopped or times out. The scheduler waits for the worker to
38
+ * finish first, or cancels the call before a worker starts it, but the
39
+ * exception unwinds through the caller and skips the code after the call.
40
+ * The caller registers what it would have released, and it is released
41
+ * before re-raising. IO::Event::WorkerPool can also cancel a call that no
42
+ * worker has started without raising, when the fiber wakes up early right
43
+ * after a task is stopped, and Ruby then returns as if the call had run.
44
+ * rm_gvl_call offloads such a call once more and otherwise runs it on the
45
+ * calling thread.
46
+ *
47
+ * 2. Other fibers on the same thread run while the call is in flight. While a
48
+ * call reads an object, changing or destroying it raises. While a call
49
+ * changes an image, any use of it raises. Nothing waits, so no fiber is
50
+ * suspended while it holds a pointer that another fiber could free. An
51
+ * Image, Info, KernelInfo, Draw or Montage keeps this state itself, so a
52
+ * call in another Ractor that shares a frozen object sees it too.
53
+ *
54
+ * ImageMagick reads some images through a working area of the pixel cache
55
+ * that every thread outside OpenMP shares, so while an offloaded call uses an
56
+ * image, no other call can use the image. No two Image objects share a pixel
57
+ * cache: an Image object takes one of its own, and a copy that RMagick makes
58
+ * for one call shares it only with the image that the call marks. A call that
59
+ * stays on its thread does not take the image for itself, so an image must
60
+ * not be used by two threads without a scheduler at once. RMagick itself
61
+ * reads and writes pixels through a cache view of its own.
62
+ *
63
+ * The child of a fork keeps none of the workers of the parent, so it drops
64
+ * the marks of every fiber but the one that forked, whose calls go on in the
65
+ * child, and changes back what the dropped calls changed for themselves, such
66
+ * as a channel mask or the links of a list. A dropped call that is resumed
67
+ * there raises instead of running. An image that a call was changing at the
68
+ * fork is in an undefined state in the child. The state of an object holds
69
+ * the fork generation it was taken in, so the child ignores the marks of the
70
+ * calls in other Ractors without finding them. Those calls change only
71
+ * objects that are not shareable, which the child cannot reach.
72
+ *
73
+ * Some cases are not handled. A scheduler must resume a fiber that waits in a
74
+ * call: a fiber collected while it waits leaves its marks behind, and the next
75
+ * fork changes back objects that may be gone. A worker that holds a lock of
76
+ * ImageMagick at the fork can leave the cleanup of a dropped call in the child
77
+ * waiting for good.
78
+ *
79
+ * Without a scheduler that offloads, or on Ruby before 4.0, rm_gvl_call runs
80
+ * the function with rb_thread_call_without_gvl. An interrupt that arrives
81
+ * during the function, such as Thread#raise or Timeout, is raised after the
82
+ * function returns, so what the caller registered is released then too.
83
+ * Interrupts are deferred until then because, where ImageMagick allocates
84
+ * with xmalloc (Magick::MANAGED_MEMORY without malloc_usable_size or a similar
85
+ * function), a GC that xmalloc starts in the function takes the GVL back and
86
+ * would raise them through ImageMagick. An exception raised by a trap handler
87
+ * there is not deferred.
88
+ *
89
+ * Ruby code still runs while such a call is in flight: a trap handler or a
90
+ * finalizer before and after the function and during a GC that it starts, and
91
+ * other threads while it runs. The call is linked in its Ractor until it
92
+ * returns, and like a call that is offloaded, it keeps that code from changing
93
+ * or destroying the objects it uses, and from using the objects it changes.
94
+ * Other Ractors share only frozen objects, which they cannot change. The
95
+ * child of a fork drops the calls of the other threads. The link is on the
96
+ * stack of the call, so that code must not leave the fiber of the call
97
+ * suspended for good.
98
+ */
99
+
100
+ typedef enum
101
+ {
102
+ OffloadRead,
103
+ OffloadUpdate
104
+ } OffloadMode;
105
+
106
+ struct offload_frame;
107
+
108
+ typedef struct
109
+ {
110
+ gvl_function_t *fp;
111
+ void *args;
112
+ void *result;
113
+ struct offload_frame *frame;
114
+ bool started;
115
+ bool done;
116
+ } offload_call_t;
117
+
118
+ #if defined(RMAGICK_OFFLOAD_SAFE)
119
+ static bool frame_dropped(const struct offload_frame *frame);
120
+ #endif
121
+
122
+ // Stores the result here rather than relying on the return value of rb_nogvl
123
+ // or rb_thread_call_without_gvl, which is lost when an exception is raised
124
+ // into the calling fiber after the function returns.
125
+ static void *
126
+ offload_run(void *arg)
127
+ {
128
+ offload_call_t *call = (offload_call_t *)arg;
129
+
130
+ #if defined(RMAGICK_OFFLOAD_SAFE)
131
+ // The fiber of a call that a fork dropped in the child resumed there
132
+ if (call->frame && frame_dropped(call->frame))
133
+ {
134
+ return NULL;
135
+ }
136
+ #endif
137
+ call->started = true;
138
+ call->result = call->fp(call->args);
139
+ call->done = true;
140
+ return call->result;
141
+ }
142
+
143
+ static VALUE
144
+ call_without_gvl(VALUE arg)
145
+ {
146
+ rb_thread_call_without_gvl(offload_run, (void *)arg, RUBY_UBF_PROCESS, NULL);
147
+ return Qnil;
148
+ }
149
+
150
+ static VALUE interrupt_mask = Qnil;
151
+ static ID id_handle_interrupt;
152
+
153
+ static VALUE
154
+ call_without_gvl_block(RB_BLOCK_CALL_FUNC_ARGLIST(yielded_arg, arg))
155
+ {
156
+ return call_without_gvl(arg);
157
+ }
158
+
159
+ static VALUE
160
+ check_interrupts(VALUE unused)
161
+ {
162
+ rb_thread_check_ints();
163
+ return Qnil;
164
+ }
165
+
166
+ static VALUE
167
+ call_deferring_interrupts(VALUE arg)
168
+ {
169
+ return rb_block_call(rb_cThread, id_handle_interrupt, 1, &interrupt_mask, call_without_gvl_block, arg);
170
+ }
171
+
172
+ static void raise_in_use(void) ATTRIBUTE_NORETURN;
173
+
174
+ // A call that stays on its thread, linked in its Ractor while it is in flight
175
+ typedef struct pinned_call
176
+ {
177
+ const rm_gvl_call *call;
178
+ VALUE thread;
179
+ struct pinned_call *next;
180
+ } pinned_call_t;
181
+
182
+ // The calls in flight in a Ractor
183
+ typedef struct offloaded
184
+ {
185
+ struct offload_frame *frames;
186
+ pinned_call_t *pinned;
187
+ } offloaded_t;
188
+
189
+ static rb_ractor_local_key_t offloaded_key;
190
+
191
+ // The entry of the main Ractor, the only one that can fork
192
+ static offloaded_t *main_entry;
193
+
194
+ // Calls that stay on their thread in all Ractors, so that checking an object
195
+ // looks for them only when there are some
196
+ static std::atomic<unsigned int> pinned_in_flight(0);
197
+
198
+ static void
199
+ offloaded_free(void *ptr)
200
+ {
201
+ xfree(ptr);
202
+ }
203
+
204
+ static const struct rb_ractor_local_storage_type offloaded_type = { NULL, offloaded_free };
205
+
206
+ static offloaded_t *
207
+ offloaded_entry(void)
208
+ {
209
+ offloaded_t *entry = (offloaded_t *)rb_ractor_local_storage_ptr(offloaded_key);
210
+
211
+ if (!entry)
212
+ {
213
+ entry = ALLOC(offloaded_t);
214
+ entry->frames = NULL;
215
+ entry->pinned = NULL;
216
+ rb_ractor_local_storage_ptr_set(offloaded_key, entry);
217
+ }
218
+ return entry;
219
+ }
220
+
221
+ // Link a call that stays on its thread
222
+ static void
223
+ pin_call(offloaded_t *entry, pinned_call_t *pin)
224
+ {
225
+ pin->next = entry->pinned;
226
+ entry->pinned = pin;
227
+ pinned_in_flight.fetch_add(1, std::memory_order_relaxed);
228
+ }
229
+
230
+ static void
231
+ unpin_call(offloaded_t *entry, pinned_call_t *pin)
232
+ {
233
+ for (pinned_call_t **link = &entry->pinned; *link; link = &(*link)->next)
234
+ {
235
+ if (*link == pin)
236
+ {
237
+ *link = pin->next;
238
+ pinned_in_flight.fetch_sub(1, std::memory_order_relaxed);
239
+ return;
240
+ }
241
+ }
242
+ }
243
+
244
+ // Whether a call in this Ractor that stays on its thread uses obj, or changes
245
+ // it if update is true
246
+ static bool
247
+ pinned(VALUE obj, bool update)
248
+ {
249
+ offloaded_t *entry;
250
+
251
+ if (pinned_in_flight.load(std::memory_order_relaxed) == 0)
252
+ {
253
+ return false;
254
+ }
255
+ entry = (offloaded_t *)rb_ractor_local_storage_ptr(offloaded_key);
256
+ for (pinned_call_t *pin = entry ? entry->pinned : NULL; pin; pin = pin->next)
257
+ {
258
+ if (pin->call->uses(obj, update))
259
+ {
260
+ return true;
261
+ }
262
+ }
263
+ return false;
264
+ }
265
+
266
+ #if defined(RMAGICK_OFFLOAD_SAFE)
267
+
268
+ // Calls in flight in all Ractors, so that a call that stays on its thread
269
+ // checks its images only when there are some
270
+ static std::atomic<unsigned int> offloads_in_flight(0);
271
+
272
+ // Forks seen by this process; a state from an earlier fork is free
273
+ static unsigned int fork_generation;
274
+
275
+ // The state of an object holds the fork generation above the number of calls
276
+ // that read it, or STATE_UPDATING
277
+ #define STATE_UPDATING UINT_MAX
278
+
279
+ // A mark on the offload state of an object
280
+ typedef struct
281
+ {
282
+ rm_offload_state_t *state;
283
+ OffloadMode mode;
284
+ bool image;
285
+ } offload_mark_t;
286
+
287
+ // A release that changes back an object that the caller passed in
288
+ typedef struct
289
+ {
290
+ void (*release)(void *, intptr_t);
291
+ void *ptr;
292
+ intptr_t arg;
293
+ } offload_restore_t;
294
+
295
+ #define OFFLOAD_MAX_RESTORES 4
296
+
297
+ static size_t
298
+ frame_align(size_t size)
299
+ {
300
+ const size_t align = alignof(std::max_align_t);
301
+
302
+ return (size + align - 1) / align * align;
303
+ }
304
+
305
+ // A call that has marked its objects, with the marks behind it
306
+ typedef struct offload_frame
307
+ {
308
+ offload_mark_t *marks;
309
+ long nmarks;
310
+ offload_restore_t restores[OFFLOAD_MAX_RESTORES];
311
+ int nrestores;
312
+ VALUE thread;
313
+ VALUE fiber;
314
+ bool linked;
315
+ struct offload_frame *prev;
316
+ struct offload_frame *next;
317
+ } offload_frame_t;
318
+
319
+ // The number of calls that read an object, or STATE_UPDATING
320
+ static unsigned int
321
+ state_count(uint64_t value)
322
+ {
323
+ if ((unsigned int)(value >> 32) != fork_generation)
324
+ {
325
+ return 0;
326
+ }
327
+ return (unsigned int)value;
328
+ }
329
+
330
+ static uint64_t
331
+ state_value(unsigned int count)
332
+ {
333
+ return ((uint64_t)fork_generation << 32) | count;
334
+ }
335
+
336
+ // Take a state for a call: a call reads an object that other calls only read,
337
+ // and changes one that no call uses. A call that uses an image is the only one.
338
+ static bool
339
+ state_acquire(rm_offload_state_t *state, OffloadMode mode, bool image)
340
+ {
341
+ uint64_t value = state->load(std::memory_order_relaxed);
342
+
343
+ while (true)
344
+ {
345
+ unsigned int count = state_count(value);
346
+
347
+ if (count == STATE_UPDATING || ((mode == OffloadUpdate || image) && count != 0))
348
+ {
349
+ return false;
350
+ }
351
+ if (state->compare_exchange_weak(value, state_value(mode == OffloadUpdate ? STATE_UPDATING : count + 1), std::memory_order_acq_rel))
352
+ {
353
+ return true;
354
+ }
355
+ }
356
+ }
357
+
358
+ static void
359
+ state_release(rm_offload_state_t *state, OffloadMode mode)
360
+ {
361
+ if (mode == OffloadUpdate)
362
+ {
363
+ state->store(0, std::memory_order_release);
364
+ }
365
+ else
366
+ {
367
+ state->fetch_sub(1, std::memory_order_release);
368
+ }
369
+ }
370
+
371
+ static void
372
+ frame_push(offloaded_t *entry, offload_frame_t *frame)
373
+ {
374
+ frame->prev = NULL;
375
+ frame->next = entry->frames;
376
+ if (entry->frames)
377
+ {
378
+ entry->frames->prev = frame;
379
+ }
380
+ entry->frames = frame;
381
+ frame->linked = true;
382
+ }
383
+
384
+ static bool
385
+ frame_dropped(const offload_frame_t *frame)
386
+ {
387
+ return !frame->linked;
388
+ }
389
+
390
+ static void
391
+ frame_remove(offloaded_t *entry, offload_frame_t *frame)
392
+ {
393
+ if (frame->prev)
394
+ {
395
+ frame->prev->next = frame->next;
396
+ }
397
+ else
398
+ {
399
+ entry->frames = frame->next;
400
+ }
401
+ if (frame->next)
402
+ {
403
+ frame->next->prev = frame->prev;
404
+ }
405
+ frame->linked = false;
406
+ }
407
+ #endif
408
+
409
+ #if defined(RMAGICK_ATFORK)
410
+ // The thread and the fiber that fork, noted before the fork, and whether the
411
+ // thread holds the GVL
412
+ static thread_local VALUE fork_thread;
413
+ #if defined(RMAGICK_OFFLOAD_SAFE)
414
+ static thread_local VALUE fork_fiber;
415
+ #endif
416
+ static thread_local bool fork_with_gvl;
417
+
418
+ // rb_fiber_current allocates the object of a root fiber on its first call,
419
+ // which a frame on the thread rules out.
420
+ static void
421
+ atfork_prepare(void)
422
+ {
423
+ fork_with_gvl = ruby_thread_has_gvl_p() && rb_ractor_local_storage_ptr(offloaded_key) == main_entry;
424
+ if (!fork_with_gvl)
425
+ {
426
+ return;
427
+ }
428
+ fork_thread = rb_thread_current();
429
+ #if defined(RMAGICK_OFFLOAD_SAFE)
430
+ fork_fiber = 0;
431
+ for (offload_frame_t *frame = main_entry->frames; frame; frame = frame->next)
432
+ {
433
+ if (frame->thread == fork_thread)
434
+ {
435
+ fork_fiber = rb_fiber_current();
436
+ break;
437
+ }
438
+ }
439
+ #endif
440
+ }
441
+
442
+ // Runs in the child before Ruby does. A thread without the GVL, such as a
443
+ // delegate of ImageMagick, forks to exec, and the list may be changing under
444
+ // it. The calls of the other fibers never run in the child, so the objects
445
+ // they changed for the call are changed back while nothing in the child can
446
+ // have destroyed them yet. The new generation frees every state, and the
447
+ // calls that go on take theirs again. The calls of the other threads that stay
448
+ // on their thread never return in the child either, and are changed back the
449
+ // same way.
450
+ static void
451
+ atfork_child(void)
452
+ {
453
+ unsigned int pins = 0;
454
+
455
+ if (!fork_with_gvl)
456
+ {
457
+ return;
458
+ }
459
+ #if defined(RMAGICK_OFFLOAD_SAFE)
460
+ unsigned int count = 0;
461
+ offload_frame_t *next;
462
+
463
+ fork_generation++;
464
+ for (offload_frame_t *frame = main_entry->frames; frame; frame = next)
465
+ {
466
+ next = frame->next;
467
+ if (frame->fiber == fork_fiber)
468
+ {
469
+ for (long i = 0; i < frame->nmarks; i++)
470
+ {
471
+ state_acquire(frame->marks[i].state, frame->marks[i].mode, false);
472
+ }
473
+ count++;
474
+ continue;
475
+ }
476
+ for (int i = 0; i < frame->nrestores; i++)
477
+ {
478
+ frame->restores[i].release(frame->restores[i].ptr, frame->restores[i].arg);
479
+ }
480
+ frame_remove(main_entry, frame);
481
+ }
482
+ offloads_in_flight.store(count, std::memory_order_relaxed);
483
+ #endif
484
+ for (pinned_call_t **link = &main_entry->pinned; *link;)
485
+ {
486
+ if ((*link)->thread == fork_thread)
487
+ {
488
+ pins++;
489
+ link = &(*link)->next;
490
+ }
491
+ else
492
+ {
493
+ (*link)->call->restore();
494
+ *link = (*link)->next;
495
+ }
496
+ }
497
+ pinned_in_flight.store(pins, std::memory_order_relaxed);
498
+ }
499
+ #endif
500
+
501
+ static void
502
+ raise_in_use(void)
503
+ {
504
+ rb_raise(rb_eRuntimeError, "object is in use by another fiber");
505
+ }
506
+
507
+ #if defined(RMAGICK_OFFLOAD_SAFE)
508
+
509
+ // The offload state of an Image, Info, KernelInfo, Draw or Montage, or NULL for
510
+ // another object, which is not tracked
511
+ static rm_offload_state_t *
512
+ object_state(VALUE obj)
513
+ {
514
+ const rb_data_type_t *type;
515
+
516
+ if (RB_SPECIAL_CONST_P(obj) || !RB_TYPE_P(obj, T_DATA) || !RTYPEDDATA_P(obj))
517
+ {
518
+ return NULL;
519
+ }
520
+ type = RTYPEDDATA_TYPE(obj);
521
+ if (type == &rm_image_data_type)
522
+ {
523
+ return &((MagickImage *)RTYPEDDATA_DATA(obj))->offload;
524
+ }
525
+ if (type == &rm_info_data_type)
526
+ {
527
+ return &((MagickImageInfo *)RTYPEDDATA_DATA(obj))->offload;
528
+ }
529
+ if (type == &rm_kernel_info_data_type)
530
+ {
531
+ return &((MagickKernelInfo *)RTYPEDDATA_DATA(obj))->offload;
532
+ }
533
+ if (type == &rm_draw_data_type)
534
+ {
535
+ return &((MagickDraw *)RTYPEDDATA_DATA(obj))->offload;
536
+ }
537
+ if (type == &rm_montage_data_type)
538
+ {
539
+ return &((MagickMontage *)RTYPEDDATA_DATA(obj))->offload;
540
+ }
541
+ return NULL;
542
+ }
543
+
544
+ // Number of calls in flight that read obj, or STATE_UPDATING
545
+ static unsigned int
546
+ object_offload_state(VALUE obj)
547
+ {
548
+ rm_offload_state_t *state = object_state(obj);
549
+
550
+ return state ? state_count(state->load(std::memory_order_acquire)) : 0;
551
+ }
552
+
553
+ static VALUE
554
+ offload_call(VALUE arg)
555
+ {
556
+ rb_nogvl(offload_run, (void *)arg, RUBY_UBF_PROCESS, NULL, RB_NOGVL_OFFLOAD_SAFE);
557
+ return Qnil;
558
+ }
559
+
560
+ static int
561
+ offload_p(void)
562
+ {
563
+ static ID id_blocking_operation_wait = 0;
564
+ VALUE scheduler = rb_fiber_scheduler_current();
565
+
566
+ if (scheduler == Qnil)
567
+ {
568
+ return 0;
569
+ }
570
+ if (!id_blocking_operation_wait)
571
+ {
572
+ id_blocking_operation_wait = rb_intern("blocking_operation_wait");
573
+ }
574
+ return rb_respond_to(scheduler, id_blocking_operation_wait);
575
+ }
576
+ #endif
577
+
578
+
579
+ /**
580
+ * Set up rm_gvl_call. Called once, when the extension is loaded.
581
+ *
582
+ * No Ruby usage (internal function)
583
+ */
584
+ void
585
+ rm_gvl_init(void)
586
+ {
587
+ rb_gc_register_address(&interrupt_mask);
588
+ interrupt_mask = rb_hash_new();
589
+ rb_funcall(interrupt_mask, rb_intern("compare_by_identity"), 0);
590
+ rb_hash_aset(interrupt_mask, rb_cObject, ID2SYM(rb_intern("never")));
591
+ #if defined(HAVE_RB_RACTOR_MAKE_SHAREABLE)
592
+ rb_ractor_make_shareable(interrupt_mask);
593
+ #endif
594
+ id_handle_interrupt = rb_intern("handle_interrupt");
595
+
596
+ offloaded_key = rb_ractor_local_storage_ptr_newkey(&offloaded_type);
597
+ main_entry = offloaded_entry();
598
+ #if defined(RMAGICK_ATFORK)
599
+ int err = pthread_atfork(atfork_prepare, NULL, atfork_child);
600
+
601
+ if (err)
602
+ {
603
+ rb_syserr_fail(err, "pthread_atfork");
604
+ }
605
+ #endif
606
+ }
607
+
608
+
609
+ /**
610
+ * Raise if a call in flight is changing the object.
611
+ *
612
+ * No Ruby usage (internal function)
613
+ *
614
+ * @param obj an Image, Info, KernelInfo, Draw or Montage
615
+ */
616
+ void
617
+ rm_gvl_check_readable(VALUE obj)
618
+ {
619
+ #if defined(RMAGICK_OFFLOAD_SAFE)
620
+ if (object_offload_state(obj) == STATE_UPDATING)
621
+ {
622
+ raise_in_use();
623
+ }
624
+ #endif
625
+ if (pinned(obj, true))
626
+ {
627
+ raise_in_use();
628
+ }
629
+ }
630
+
631
+
632
+ /**
633
+ * Whether a call in flight is using the object.
634
+ *
635
+ * No Ruby usage (internal function)
636
+ *
637
+ * @param obj an Image, Info, KernelInfo, Draw or Montage
638
+ * @return true if a call reads or changes the object
639
+ */
640
+ bool
641
+ rm_gvl_in_use(VALUE obj)
642
+ {
643
+ #if defined(RMAGICK_OFFLOAD_SAFE)
644
+ if (object_offload_state(obj) != 0)
645
+ {
646
+ return true;
647
+ }
648
+ #endif
649
+ return pinned(obj, false);
650
+ }
651
+
652
+
653
+ /**
654
+ * Raise if a call in flight is using the object.
655
+ *
656
+ * No Ruby usage (internal function)
657
+ *
658
+ * @param obj an Image, Info, KernelInfo, Draw or Montage
659
+ */
660
+ void
661
+ rm_gvl_check_writable(VALUE obj)
662
+ {
663
+ if (rm_gvl_in_use(obj))
664
+ {
665
+ raise_in_use();
666
+ }
667
+ }
668
+
669
+
670
+ #if defined(RMAGICK_OFFLOAD_SAFE)
671
+ // Mark an object registered with read() or update(), once for each call. An
672
+ // object that the call both reads and changes is marked as changed.
673
+ static void
674
+ add_object_mark(offload_mark_t *marks, long *nmarks, VALUE obj, OffloadMode mode)
675
+ {
676
+ rm_offload_state_t *state = object_state(obj);
677
+
678
+ if (!state)
679
+ {
680
+ return;
681
+ }
682
+ for (long i = 0; i < *nmarks; i++)
683
+ {
684
+ if (marks[i].state == state)
685
+ {
686
+ if (mode == OffloadUpdate)
687
+ {
688
+ marks[i].mode = OffloadUpdate;
689
+ }
690
+ return;
691
+ }
692
+ }
693
+ marks[*nmarks].state = state;
694
+ marks[*nmarks].mode = mode;
695
+ marks[*nmarks].image = RTYPEDDATA_TYPE(obj) == &rm_image_data_type;
696
+ (*nmarks)++;
697
+ }
698
+
699
+ // Take the marks of a frame and link it, or take none and return false if
700
+ // another call holds an object
701
+ static bool
702
+ frame_acquire(offloaded_t *entry, offload_frame_t *frame)
703
+ {
704
+ offloads_in_flight.fetch_add(1, std::memory_order_relaxed);
705
+ for (long i = 0; i < frame->nmarks; i++)
706
+ {
707
+ if (!state_acquire(frame->marks[i].state, frame->marks[i].mode, frame->marks[i].image))
708
+ {
709
+ while (i-- > 0)
710
+ {
711
+ state_release(frame->marks[i].state, frame->marks[i].mode);
712
+ }
713
+ offloads_in_flight.fetch_sub(1, std::memory_order_relaxed);
714
+ return false;
715
+ }
716
+ }
717
+ frame_push(entry, frame);
718
+ return true;
719
+ }
720
+
721
+ // Release the marks of a frame and unlink it, or return false if a fork
722
+ // dropped it in the child
723
+ static bool
724
+ frame_release(offloaded_t *entry, offload_frame_t *frame)
725
+ {
726
+ if (!frame->linked)
727
+ {
728
+ return false;
729
+ }
730
+ for (long i = 0; i < frame->nmarks; i++)
731
+ {
732
+ state_release(frame->marks[i].state, frame->marks[i].mode);
733
+ }
734
+ frame_remove(entry, frame);
735
+ offloads_in_flight.fetch_sub(1, std::memory_order_relaxed);
736
+ return true;
737
+ }
738
+ #endif
739
+
740
+ static void
741
+ release_exception(void *ptr, intptr_t arg ATTRIBUTE_UNUSED)
742
+ {
743
+ DestroyExceptionInfo((ExceptionInfo *)ptr);
744
+ }
745
+
746
+ static void
747
+ destroy_info(void *ptr, intptr_t arg ATTRIBUTE_UNUSED)
748
+ {
749
+ DestroyImageInfo((ImageInfo *)ptr);
750
+ }
751
+
752
+ static void
753
+ destroy_draw_info(void *ptr, intptr_t arg ATTRIBUTE_UNUSED)
754
+ {
755
+ DestroyDrawInfo((DrawInfo *)ptr);
756
+ }
757
+
758
+ static void
759
+ destroy_kernel(void *ptr, intptr_t arg ATTRIBUTE_UNUSED)
760
+ {
761
+ DestroyKernelInfo((KernelInfo *)ptr);
762
+ }
763
+
764
+ static void
765
+ free_ruby_memory(void *ptr, intptr_t arg ATTRIBUTE_UNUSED)
766
+ {
767
+ xfree(ptr);
768
+ }
769
+
770
+ static void
771
+ free_magick_memory(void *ptr, intptr_t arg ATTRIBUTE_UNUSED)
772
+ {
773
+ magick_free(ptr);
774
+ }
775
+
776
+ static void
777
+ destroy_image(void *ptr, intptr_t arg ATTRIBUTE_UNUSED)
778
+ {
779
+ DestroyImageList((Image *)ptr);
780
+ }
781
+
782
+ static void
783
+ split_images(void *ptr, intptr_t arg ATTRIBUTE_UNUSED)
784
+ {
785
+ rm_split((Image *)ptr);
786
+ }
787
+
788
+ #if defined(IMAGEMAGICK_7)
789
+ static void
790
+ restore_channel_mask(void *ptr, intptr_t arg)
791
+ {
792
+ SetPixelChannelMask((Image *)ptr, (ChannelType)arg);
793
+ }
794
+ #endif
795
+
796
+
797
+ /**
798
+ * Prepare a call of fp(args).
799
+ *
800
+ * No Ruby usage (internal function)
801
+ *
802
+ * @param fp the function
803
+ * @param args its argument struct, on the caller's stack
804
+ */
805
+ rm_gvl_call::rm_gvl_call(gvl_function_t *fp, void *args)
806
+ : fp(fp), args(args), nobjects(0), ncleanups(0), result_type(ResultIgnored), keep(false)
807
+ {
808
+ }
809
+
810
+
811
+ rm_gvl_call &
812
+ rm_gvl_call::add_object(VALUE obj, bool update, bool each)
813
+ {
814
+ if (nobjects == MaxObjects)
815
+ {
816
+ rb_bug("too many objects for an offloaded call");
817
+ }
818
+ objects[nobjects].obj = obj;
819
+ objects[nobjects].update = update;
820
+ objects[nobjects].each = each;
821
+ nobjects++;
822
+ return *this;
823
+ }
824
+
825
+
826
+ /**
827
+ * Call release(ptr, arg) if the call is refused or unwound. Nothing is
828
+ * registered when ptr is NULL.
829
+ *
830
+ * @param release the function
831
+ * @param ptr its first argument
832
+ * @param arg its second argument
833
+ * @return self
834
+ */
835
+ rm_gvl_call &
836
+ rm_gvl_call::cleanup(void (*release)(void *, intptr_t), void *ptr, intptr_t arg)
837
+ {
838
+ return add_cleanup(release, ptr, arg, false);
839
+ }
840
+
841
+
842
+ rm_gvl_call &
843
+ rm_gvl_call::add_cleanup(void (*release)(void *, intptr_t), void *ptr, intptr_t arg, bool restore)
844
+ {
845
+ if (!ptr)
846
+ {
847
+ return *this;
848
+ }
849
+ if (ncleanups == MaxCleanups)
850
+ {
851
+ rb_bug("too many cleanups for an offloaded call");
852
+ }
853
+ cleanups[ncleanups].release = release;
854
+ cleanups[ncleanups].ptr = ptr;
855
+ cleanups[ncleanups].arg = arg;
856
+ cleanups[ncleanups].restore = restore;
857
+ ncleanups++;
858
+ return *this;
859
+ }
860
+
861
+
862
+ /**
863
+ * The call reads the data of obj. Other fibers can still read it, but cannot
864
+ * change or destroy it while the call is in flight. Another call cannot use
865
+ * an image that the call reads.
866
+ *
867
+ * @param obj an Image, Info, KernelInfo, Draw or Montage
868
+ * @return self
869
+ */
870
+ rm_gvl_call &
871
+ rm_gvl_call::read(VALUE obj)
872
+ {
873
+ return add_object(obj, false, false);
874
+ }
875
+
876
+
877
+ /**
878
+ * The call changes the data of obj, or the caller replaces it with the result.
879
+ * Other fibers cannot use it while the call is in flight.
880
+ *
881
+ * @param obj an Image, Info, KernelInfo, Draw or Montage
882
+ * @return self
883
+ */
884
+ rm_gvl_call &
885
+ rm_gvl_call::update(VALUE obj)
886
+ {
887
+ return add_object(obj, true, false);
888
+ }
889
+
890
+
891
+ /**
892
+ * The call reads every object in the array, such as the images of an ImageList.
893
+ * A copy of the array keeps the objects alive while the call is in flight,
894
+ * even if another fiber removes them from the array.
895
+ *
896
+ * @param ary the array
897
+ * @return self
898
+ */
899
+ rm_gvl_call &
900
+ rm_gvl_call::read_each(VALUE ary)
901
+ {
902
+ return add_object(rb_ary_dup(ary), false, true);
903
+ }
904
+
905
+
906
+ /**
907
+ * The call changes every object in the array, such as the images of an
908
+ * ImageList. Like read_each(), a copy of the array keeps the objects alive.
909
+ *
910
+ * @param ary the array
911
+ * @return self
912
+ */
913
+ rm_gvl_call &
914
+ rm_gvl_call::update_each(VALUE ary)
915
+ {
916
+ return add_object(rb_ary_dup(ary), true, true);
917
+ }
918
+
919
+
920
+ /**
921
+ * The call reads obj, or changes it if changes is true, and the caller uses
922
+ * its data after the call. obj may be an Array, whose objects the call uses
923
+ * like read_each() and update_each(), or nil, which registers nothing.
924
+ *
925
+ * @param obj an Image, an Array of Images, or nil
926
+ * @param changes whether the call changes the objects
927
+ * @return self
928
+ */
929
+ rm_gvl_call &
930
+ rm_gvl_call::hold(VALUE obj, bool changes)
931
+ {
932
+ if (NIL_P(obj))
933
+ {
934
+ return *this;
935
+ }
936
+ if (RB_TYPE_P(obj, T_ARRAY))
937
+ {
938
+ return changes ? update_each(obj) : read_each(obj);
939
+ }
940
+ return changes ? update(obj) : read(obj);
941
+ }
942
+
943
+
944
+ /**
945
+ * Destroy the exception if the call is refused or unwound.
946
+ *
947
+ * @param exception the ExceptionInfo, may be NULL
948
+ * @return self
949
+ */
950
+ rm_gvl_call &
951
+ rm_gvl_call::release(ExceptionInfo *exception)
952
+ {
953
+ return cleanup(release_exception, exception, 0);
954
+ }
955
+
956
+
957
+ /**
958
+ * Destroy the ImageInfo if the call is refused or unwound.
959
+ *
960
+ * @param info the ImageInfo, may be NULL
961
+ * @return self
962
+ */
963
+ rm_gvl_call &
964
+ rm_gvl_call::release(ImageInfo *info)
965
+ {
966
+ return cleanup(destroy_info, info, 0);
967
+ }
968
+
969
+
970
+ /**
971
+ * Destroy the DrawInfo if the call is refused or unwound.
972
+ *
973
+ * @param draw_info the DrawInfo, may be NULL
974
+ * @return self
975
+ */
976
+ rm_gvl_call &
977
+ rm_gvl_call::release(DrawInfo *draw_info)
978
+ {
979
+ return cleanup(destroy_draw_info, draw_info, 0);
980
+ }
981
+
982
+
983
+ /**
984
+ * Destroy the KernelInfo if the call is refused or unwound.
985
+ *
986
+ * @param kernel the KernelInfo, may be NULL
987
+ * @return self
988
+ */
989
+ rm_gvl_call &
990
+ rm_gvl_call::release(KernelInfo *kernel)
991
+ {
992
+ return cleanup(destroy_kernel, kernel, 0);
993
+ }
994
+
995
+
996
+ /**
997
+ * Free the buffer, allocated with ALLOC_N, if the call is refused or unwound.
998
+ *
999
+ * @param buffer the buffer, may be NULL
1000
+ * @return self
1001
+ */
1002
+ rm_gvl_call &
1003
+ rm_gvl_call::free_buffer(void *buffer)
1004
+ {
1005
+ return cleanup(free_ruby_memory, buffer, 0);
1006
+ }
1007
+
1008
+
1009
+ /**
1010
+ * Free the memory, allocated by ImageMagick, if the call is refused or unwound.
1011
+ *
1012
+ * @param memory the memory, may be NULL
1013
+ * @return self
1014
+ */
1015
+ rm_gvl_call &
1016
+ rm_gvl_call::relinquish(void *memory)
1017
+ {
1018
+ return cleanup(free_magick_memory, memory, 0);
1019
+ }
1020
+
1021
+
1022
+ /**
1023
+ * Destroy the image if the call is refused or unwound.
1024
+ *
1025
+ * @param image the image, may be NULL
1026
+ * @return self
1027
+ */
1028
+ rm_gvl_call &
1029
+ rm_gvl_call::destroy(Image *image)
1030
+ {
1031
+ return cleanup(destroy_image, image, 0);
1032
+ }
1033
+
1034
+
1035
+ /**
1036
+ * Split the linked images if the call is refused or unwound.
1037
+ *
1038
+ * @param images the first image of the list
1039
+ * @return self
1040
+ */
1041
+ rm_gvl_call &
1042
+ rm_gvl_call::split(Image *images)
1043
+ {
1044
+ return add_cleanup(split_images, images, 0, true);
1045
+ }
1046
+
1047
+
1048
+ #if defined(IMAGEMAGICK_7)
1049
+ /**
1050
+ * Restore the channel mask of the image if the call is refused or unwound.
1051
+ *
1052
+ * @param image the image whose channel mask was changed
1053
+ * @param channel_mask its channel mask before the change
1054
+ * @return self
1055
+ */
1056
+ rm_gvl_call &
1057
+ rm_gvl_call::restore_mask(Image *image, ChannelType channel_mask)
1058
+ {
1059
+ return add_cleanup(restore_channel_mask, image, (intptr_t)channel_mask, true);
1060
+ }
1061
+ #endif
1062
+
1063
+
1064
+ /**
1065
+ * The result is memory that the caller frees with magick_free. It is freed if
1066
+ * the call is unwound.
1067
+ *
1068
+ * @return self
1069
+ */
1070
+ rm_gvl_call &
1071
+ rm_gvl_call::free_result()
1072
+ {
1073
+ result_type = ResultMemory;
1074
+ return *this;
1075
+ }
1076
+
1077
+
1078
+ /**
1079
+ * Run the call on the calling thread even under a Fiber scheduler, for
1080
+ * example because it uses a FILE * that another fiber could close.
1081
+ *
1082
+ * @param keep whether to keep the call on the calling thread
1083
+ * @return self
1084
+ */
1085
+ rm_gvl_call &
1086
+ rm_gvl_call::keep_thread(bool keep)
1087
+ {
1088
+ this->keep = keep;
1089
+ return *this;
1090
+ }
1091
+
1092
+
1093
+ /**
1094
+ * Release what the caller registered, and the result.
1095
+ *
1096
+ * No Ruby usage (internal function)
1097
+ *
1098
+ * @param type how to free the result
1099
+ * @param result the result, or NULL
1100
+ * @param abandoned whether the child of a fork dropped the call, which
1101
+ * changed back the objects that the caller passed in at the fork
1102
+ */
1103
+ void
1104
+ rm_gvl_call::unwind(ResultType type, void *result, bool abandoned)
1105
+ {
1106
+ if (result)
1107
+ {
1108
+ if (type == ResultImage)
1109
+ {
1110
+ DestroyImageList((Image *)result);
1111
+ }
1112
+ else if (type == ResultMemory)
1113
+ {
1114
+ magick_free(result);
1115
+ }
1116
+ }
1117
+ for (int i = 0; i < ncleanups; i++)
1118
+ {
1119
+ if (cleanups[i].restore && abandoned)
1120
+ {
1121
+ continue;
1122
+ }
1123
+ cleanups[i].release(cleanups[i].ptr, cleanups[i].arg);
1124
+ }
1125
+ }
1126
+
1127
+
1128
+ /**
1129
+ * Change back the objects that the caller passed in, for a call that the
1130
+ * child of a fork dropped.
1131
+ *
1132
+ * No Ruby usage (internal function)
1133
+ */
1134
+ void
1135
+ rm_gvl_call::restore() const
1136
+ {
1137
+ for (int i = 0; i < ncleanups; i++)
1138
+ {
1139
+ if (cleanups[i].restore)
1140
+ {
1141
+ cleanups[i].release(cleanups[i].ptr, cleanups[i].arg);
1142
+ }
1143
+ }
1144
+ }
1145
+
1146
+
1147
+ void *
1148
+ rm_gvl_call::call(ResultType type)
1149
+ {
1150
+ void *result;
1151
+
1152
+ check_frozen_images(type);
1153
+ result = call_body(type);
1154
+ rm_gc_continue();
1155
+ return result;
1156
+ }
1157
+
1158
+
1159
+ // Raise if the call changes an image that is frozen. An ImageList registers
1160
+ // its frozen images with update_each but writes copies of them, so only the
1161
+ // images registered one by one are checked.
1162
+ void
1163
+ rm_gvl_call::check_frozen_images(ResultType type)
1164
+ {
1165
+ for (int i = 0; i < nobjects; i++)
1166
+ {
1167
+ VALUE obj = objects[i].obj;
1168
+
1169
+ if (objects[i].update && !objects[i].each && OBJ_FROZEN(obj) && rb_typeddata_is_kind_of(obj, &rm_image_data_type))
1170
+ {
1171
+ unwind(type, NULL);
1172
+ rb_check_frozen(obj);
1173
+ }
1174
+ }
1175
+ }
1176
+
1177
+ void *
1178
+ rm_gvl_call::call_body(ResultType type)
1179
+ {
1180
+ #if defined(RMAGICK_OFFLOAD_SAFE)
1181
+ if (!keep && offload_p())
1182
+ {
1183
+ return offload(type);
1184
+ }
1185
+ if (offloads_in_flight.load(std::memory_order_relaxed) != 0)
1186
+ {
1187
+ check_images_idle(type);
1188
+ }
1189
+ #endif
1190
+
1191
+ return call_here(type);
1192
+ }
1193
+
1194
+
1195
+ // Whether f(obj, update) is true for an object that the call registered, or for
1196
+ // an object in an array that it registered with each. update_only skips the
1197
+ // objects that the call does not change.
1198
+ template <typename F>
1199
+ bool
1200
+ rm_gvl_call::any_object(bool update_only, F f) const
1201
+ {
1202
+ for (int i = 0; i < nobjects; i++)
1203
+ {
1204
+ long len = objects[i].each ? RARRAY_LEN(objects[i].obj) : 1;
1205
+
1206
+ if (update_only && !objects[i].update)
1207
+ {
1208
+ continue;
1209
+ }
1210
+ for (long j = 0; j < len; j++)
1211
+ {
1212
+ if (f(objects[i].each ? rb_ary_entry(objects[i].obj, j) : objects[i].obj, objects[i].update))
1213
+ {
1214
+ return true;
1215
+ }
1216
+ }
1217
+ }
1218
+ return false;
1219
+ }
1220
+
1221
+
1222
+ #if defined(RMAGICK_OFFLOAD_SAFE)
1223
+ // A frame for an offloaded call, with a mark for each object it registered
1224
+ offload_frame_t *
1225
+ rm_gvl_call::new_frame()
1226
+ {
1227
+ offload_frame_t *frame;
1228
+ long count = 0;
1229
+
1230
+ for (int i = 0; i < nobjects; i++)
1231
+ {
1232
+ count += objects[i].each ? RARRAY_LEN(objects[i].obj) : 1;
1233
+ }
1234
+ frame = (offload_frame_t *)xmalloc(frame_align(sizeof(offload_frame_t)) + count * sizeof(offload_mark_t));
1235
+ frame->marks = (offload_mark_t *)((char *)frame + frame_align(sizeof(offload_frame_t)));
1236
+ frame->nmarks = 0;
1237
+ any_object(false, [frame](VALUE obj, bool update) {
1238
+ add_object_mark(frame->marks, &frame->nmarks, obj, update ? OffloadUpdate : OffloadRead);
1239
+ return false;
1240
+ });
1241
+
1242
+ static_assert(MaxCleanups <= OFFLOAD_MAX_RESTORES, "a frame holds every cleanup that restores");
1243
+ frame->nrestores = 0;
1244
+ for (int i = 0; i < ncleanups; i++)
1245
+ {
1246
+ if (cleanups[i].restore)
1247
+ {
1248
+ offload_restore_t restore = { cleanups[i].release, cleanups[i].ptr, cleanups[i].arg };
1249
+
1250
+ frame->restores[frame->nrestores++] = restore;
1251
+ }
1252
+ }
1253
+ frame->thread = rb_thread_current();
1254
+ frame->fiber = rb_fiber_current();
1255
+ return frame;
1256
+ }
1257
+
1258
+
1259
+ void *
1260
+ rm_gvl_call::offload(ResultType type)
1261
+ {
1262
+ offload_frame_t *frame = new_frame();
1263
+ offload_call_t call = { fp, args, NULL, frame, false, false };
1264
+ bool dropped;
1265
+ int tag;
1266
+
1267
+ if (!frame_acquire(offloaded_entry(), frame))
1268
+ {
1269
+ xfree(frame);
1270
+ unwind(type, NULL);
1271
+ raise_in_use();
1272
+ }
1273
+
1274
+ rb_protect(offload_call, (VALUE)&call, &tag);
1275
+ if (!tag && !call.started && frame->linked)
1276
+ {
1277
+ rb_protect(offload_call, (VALUE)&call, &tag);
1278
+ }
1279
+
1280
+ dropped = !frame_release(offloaded_entry(), frame);
1281
+ xfree(frame);
1282
+ if (dropped)
1283
+ {
1284
+ // The worker may have finished before the fork
1285
+ unwind(type, call.done ? call.result : NULL, true);
1286
+ if (tag)
1287
+ {
1288
+ rb_jump_tag(tag);
1289
+ }
1290
+ rb_raise(rb_eRuntimeError, "call abandoned in the child of a fork");
1291
+ }
1292
+ if (tag)
1293
+ {
1294
+ // The scheduler raised into this fiber after the worker finished.
1295
+ unwind(type, call.result);
1296
+ rb_jump_tag(tag);
1297
+ }
1298
+ if (!call.started)
1299
+ {
1300
+ return call_here(type);
1301
+ }
1302
+
1303
+ return call.result;
1304
+ }
1305
+
1306
+
1307
+ // Raise if an offloaded call uses an image that this call, which stays on its
1308
+ // thread, uses too
1309
+ void
1310
+ rm_gvl_call::check_images_idle(ResultType type)
1311
+ {
1312
+ bool busy = any_object(false, [](VALUE obj, bool) {
1313
+ rm_offload_state_t *state = object_state(obj);
1314
+
1315
+ return state && RTYPEDDATA_TYPE(obj) == &rm_image_data_type && state_count(state->load(std::memory_order_acquire)) != 0;
1316
+ });
1317
+
1318
+ if (busy)
1319
+ {
1320
+ unwind(type, NULL);
1321
+ raise_in_use();
1322
+ }
1323
+ }
1324
+ #endif
1325
+
1326
+
1327
+ /**
1328
+ * Whether the call uses obj, or changes it if update is true.
1329
+ *
1330
+ * No Ruby usage (internal function)
1331
+ *
1332
+ * @param obj the object
1333
+ * @param update whether to look only at the objects that the call changes
1334
+ * @return true if the call registered obj
1335
+ */
1336
+ bool
1337
+ rm_gvl_call::uses(VALUE obj, bool update) const
1338
+ {
1339
+ return any_object(update, [obj](VALUE registered, bool) { return registered == obj; });
1340
+ }
1341
+
1342
+
1343
+ void *
1344
+ rm_gvl_call::call_here(ResultType type)
1345
+ {
1346
+ offload_call_t call = { fp, args, NULL, NULL, false, false };
1347
+ offloaded_t *entry = offloaded_entry();
1348
+ pinned_call_t pin = { this, rb_thread_current(), NULL };
1349
+ int tag;
1350
+
1351
+ pin_call(entry, &pin);
1352
+ rb_protect(check_interrupts, Qnil, &tag);
1353
+ if (tag)
1354
+ {
1355
+ unpin_call(entry, &pin);
1356
+ unwind(type, NULL);
1357
+ rb_jump_tag(tag);
1358
+ }
1359
+
1360
+ rb_protect(call_deferring_interrupts, (VALUE)&call, &tag);
1361
+ unpin_call(entry, &pin);
1362
+ if (tag)
1363
+ {
1364
+ if (call.done || !call.started)
1365
+ {
1366
+ unwind(type, call.result);
1367
+ }
1368
+ rb_jump_tag(tag);
1369
+ }
1370
+ return call.result;
1371
+ }
1372
+
1373
+
1374
+ /**
1375
+ * Run the call, letting a Fiber scheduler offload it.
1376
+ *
1377
+ * No Ruby usage (internal function)
1378
+ *
1379
+ * @return the result of the call, cast to T
1380
+ */
1381
+ template <>
1382
+ Image *
1383
+ rm_gvl_call::run<Image *>()
1384
+ {
1385
+ return (Image *)call(ResultImage);
1386
+ }
1387
+
1388
+
1389
+ template <>
1390
+ void
1391
+ rm_gvl_call::run<void>()
1392
+ {
1393
+ call(ResultIgnored);
1394
+ }