-
Notifications
You must be signed in to change notification settings - Fork 376
/
fiber.h
1256 lines (1141 loc) · 30.7 KB
/
fiber.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifndef TARANTOOL_LIB_CORE_FIBER_H_INCLUDED
#define TARANTOOL_LIB_CORE_FIBER_H_INCLUDED
/*
* Copyright 2010-2016, Tarantool AUTHORS, please see AUTHORS file.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* 1. Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* <COPYRIGHT HOLDER> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "trivia/config.h"
#include <stdbool.h>
#include <stdint.h>
#include "tt_pthread.h"
#include <tarantool_ev.h>
#include "cord_on_demand.h"
#include "diag.h"
#include "trivia/util.h"
#include "small/mempool.h"
#include "small/region.h"
#include "small/rlist.h"
#include "salad/stailq.h"
#include "clock_lowres.h"
#include "backtrace.h"
#include "exception.h"
#include <coro/coro.h>
/*
* This constant is the same as LUA_NOREF. It should be used
* to initialize all Lua references in struct fiber.
* Since this module is independent on Lua the constant is
* defined directly. Value should be checked with
* static_assert in appropriate places to catch possible
* LUA_NOREF value changes in future.
*/
#define FIBER_LUA_NOREF (-2)
#if defined(__cplusplus)
extern "C" {
#endif /* defined(__cplusplus) */
/* A fiber reports used up CPU time with nanosecond resolution. */
#define FIBER_TIME_RES 1000000000
/**
* A struct containing all the info gathered for current fiber or
* thread as a whole when fiber.top() is enabled.
*/
struct clock_stat {
/**
* Accumulated clock value calculated using exponential
* moving average.
*/
uint64_t acc;
/**
* Clock delta counter used on current event loop
* iteration.
*/
uint64_t delta;
/**
* Clock delta calculated on previous event loop
* iteration.
*/
uint64_t prev_delta;
/**
* Total processor time this fiber (or cord as a whole)
* has spent with 1 / FIBER_TIME_RES second precision.
*/
uint64_t cputime;
};
/**
* A struct encapsulating all knowledge this cord has about cpu
* clocks and their state.
*/
struct cpu_stat {
uint64_t prev_clock;
/**
* This thread's CPU time at the beginning of event loop
* iteration. Used to calculate how much cpu time has
* each loop iteration consumed and update fiber cpu
* times propotionally. The resolution is
* 1 / FIBER_TIME_RES seconds.
*/
uint64_t prev_cputime;
};
enum {
/** Both limits include terminating 0. */
FIBER_NAME_INLINE = 40,
FIBER_NAME_MAX = 256
};
/**
* Fiber ids [0; 100] are reserved.
*/
enum {
FIBER_ID_SCHED = 1,
FIBER_ID_MAX_RESERVED = 100
};
enum {
/**
* Indicates that a fiber has been requested to end
* prematurely.
*/
FIBER_IS_CANCELLED = 1 << 0,
/**
* The fiber will garbage collect automatically
* when fiber function ends. The alternative
* is that some other fiber will wait for
* the end of this fiber and garbage collect it
* with fiber_join().
*/
FIBER_IS_JOINABLE = 1 << 1,
/**
* The fiber is in cord->ready list or in
* a call chain created by fiber_schedule_list().
* The flag is set to help fiber_wakeup() avoid
* double wakeup of an already scheduled fiber.
*/
FIBER_IS_READY = 1 << 2,
/**
* This flag is set when fiber function ends and before
* the fiber is recycled.
*/
FIBER_IS_DEAD = 1 << 3,
/**
* This flag is set when fiber uses custom stack size.
*/
FIBER_CUSTOM_STACK = 1 << 4,
/**
* The flag is set for the fiber currently being executed by the cord.
*/
FIBER_IS_RUNNING = 1 << 5,
/**
* This flag is set when fiber is in the idle list
* of fiber_pool.
*/
FIBER_IS_IDLE = 1 << 6,
/**
* This flag is set when fiber has custom max slice.
*/
FIBER_CUSTOM_SLICE = 1 << 7,
/**
* This flag idicates, if the fiber can be killed from the Lua world.
*/
FIBER_IS_SYSTEM = 1 << 8,
FIBER_DEFAULT_FLAGS = 0
};
/** \cond public */
/**
* Fiber attributes container
*/
struct fiber_attr;
/**
* Create a new fiber attribute container and initialize it
* with default parameters.
* Can be used for many fibers creation, corresponding fibers
* will not take ownership.
*/
API_EXPORT struct fiber_attr *
fiber_attr_new(void);
/**
* Delete the fiber_attr and free all allocated resources.
* This is safe when fibers created with this attribute still exist.
*
*\param fiber_attr fiber attribute
*/
API_EXPORT void
fiber_attr_delete(struct fiber_attr *fiber_attr);
/**
* Set stack size for the fiber attribute.
*
* \param fiber_attr fiber attribute container
* \param stack_size stack size for new fibers
*/
API_EXPORT int
fiber_attr_setstacksize(struct fiber_attr *fiber_attr, size_t stack_size);
/**
* Get stack size from the fiber attribute.
*
* \param fiber_attr fiber attribute container or NULL for default
* \retval stack size
*/
API_EXPORT size_t
fiber_attr_getstacksize(struct fiber_attr *fiber_attr);
struct fiber;
/**
* Fiber - contains information about fiber
*/
typedef int (*fiber_func)(va_list);
/**
* Return the current fiber
*/
API_EXPORT struct fiber *
fiber_self(void);
/**
* Create a new fiber.
*
* Takes a fiber from fiber cache, if it's not empty.
* Can fail only if there is not enough memory for
* the fiber structure or fiber stack.
*
* The created fiber automatically returns itself
* to the fiber cache when its "main" function
* completes.
*
* \param name string with fiber name
* \param f func for run inside fiber
*
* \sa fiber_start
*/
API_EXPORT struct fiber *
fiber_new(const char *name, fiber_func f);
/**
* Create a new fiber with defined attributes.
*
* Can fail only if there is not enough memory for
* the fiber structure or fiber stack.
*
* The created fiber automatically returns itself
* to the fiber cache if has default stack size
* when its "main" function completes.
*
* \param name string with fiber name
* \param fiber_attr fiber attributes
* \param f func for run inside fiber
*
* \sa fiber_start
*/
API_EXPORT struct fiber *
fiber_new_ex(const char *name, const struct fiber_attr *fiber_attr, fiber_func f);
/**
* Return control to another fiber and wait until it'll be woken.
*
* \note this is not a cancellation point (\sa fiber_testcancel()), but it is
* considered a good practice to call fiber_testcancel() after each yield.
*
* \sa fiber_wakeup
*/
API_EXPORT void
fiber_yield(void);
/**
* Start execution of created fiber.
*
* \param callee fiber to start
* \param ... arguments to start the fiber with
*
* \sa fiber_new
*/
API_EXPORT void
fiber_start(struct fiber *callee, ...);
/**
* Set a pointer to context for the fiber. Can be used to avoid calling
* fiber_start which means no yields.
*
* \param f fiber to set the context for
* \param f_arg context for the fiber function
*/
API_EXPORT void
fiber_set_ctx(struct fiber *f, void *f_arg);
/**
* Get the context for the fiber which was set via the fiber_set_ctx
* function. Can be used to avoid calling fiber_start which means no yields.
*
* \retval context for the fiber function set by fiber_set_ctx function
*
* \sa fiber_set_ctx
*/
API_EXPORT void *
fiber_get_ctx(struct fiber *f);
/**
* Interrupt a synchronous wait of a fiber. Nop for the currently running fiber.
*
* \param f fiber to be woken up
*/
API_EXPORT void
fiber_wakeup(struct fiber *f);
/**
* Cancel the subject fiber.
*
* Cancellation is asynchronous. Use fiber_join() to wait for the cancellation
* to complete.
*
* After fiber_cancel() is called, the fiber may or may not check whether it
* was cancelled. If the fiber does not check it, it cannot ever be cancelled.
* However, as long as most of the cooperative code calls fiber_testcancel(),
* most of the fibers are cancellable.
*
* \param f fiber to be cancelled
*/
API_EXPORT void
fiber_cancel(struct fiber *f);
/**
* Deprecated.
*
* @return true
*/
API_EXPORT bool
fiber_set_cancellable(bool yesno);
/**
* Set fiber to be joinable (false by default).
* \param fiber to (un)set the joinable property
* \param yesno status to set
*/
API_EXPORT void
fiber_set_joinable(struct fiber *fiber, bool yesno);
/**
* Wait until the fiber is dead and then move its execution
* status to the caller.
* The fiber must not be detached (@sa fiber_set_joinable()).
* @pre FIBER_IS_JOINABLE flag is set.
*
* \param f fiber to be woken up
* \return fiber function ret code
*/
API_EXPORT int
fiber_join(struct fiber *f);
/**
* Wait until the fiber is dead or timeout exceeded.
* In case timeout == TIMEOUT_INFINITY, this function
* same as fiber_join function.
* Return fiber execution status to the caller or -1
* if timeout exceeded and set diag.
* The fiber must not be detached @sa fiber_set_joinable()
* @pre FIBER_IS_JOINABLE flag is set.
*
* \param f fiber to be woken up
* \param timeout time during which we wait for the fiber completion
* \return fiber function ret code or -1 in case if timeout exceeded
*/
API_EXPORT int
fiber_join_timeout(struct fiber *f, double timeout);
/**
* Put the current fiber to sleep for at least 's' seconds.
*
* \param s time to sleep
*
* \note this is a cancellation point \sa fiber_is_cancelled
*/
API_EXPORT void
fiber_sleep(double s);
/**
* Check current fiber for cancellation (it must be checked
* manually).
*/
API_EXPORT bool
fiber_is_cancelled(void);
/**
* Report loop begin time as double (cheap).
* Uses real time clock.
*/
API_EXPORT double
fiber_time(void);
/**
* Report loop begin time as 64-bit int.
* Uses real time clock.
*/
API_EXPORT int64_t
fiber_time64(void);
/**
* Report loop begin time as double (cheap).
* Uses monotonic clock.
*/
API_EXPORT double
fiber_clock(void);
/**
* Report loop begin time as 64-bit int.
* Uses monotonic clock.
*/
API_EXPORT int64_t
fiber_clock64(void);
/**
* Reschedule fiber to end of event loop cycle.
*/
API_EXPORT void
fiber_reschedule(void);
/**
* box region allocator
*
* It is the region allocator from the small library. It is useful
* for allocating tons of small objects and free them at once.
*
* Typical usage is illustrated in the sketch below.
*
* \code
* size_t region_svp = box_region_used();
* while (<...>) {
* char *buf = box_region_alloc(<...>);
* <...>
* }
* box_region_truncate(region_svp);
* \endcode
*
* There are module API functions that return a result on
* this region. In this case a caller is responsible to free the
* result:
*
* \code
* size_t region_svp = box_region_used();
* char *buf = box_<...>(<...>);
* <...>
* box_region_truncate(region_svp);
* \endcode
*
* This API provides better compatibility guarantees over using
* the small library directly in a module. A binary layout of
* internal structures may be changed in a future, but
* <box_region_*>() functions will remain API and ABI compatible.
*
* Each fiber has its own box region. It means that a call of,
* say, box_region_used() will give its own value in different
* fibers. It also means that a yield does not invalidate data in
* the box region.
*
* Prior to version 2.11, the box region was implicitly cleaned up
* on transaction commit (see box_txn_commit()) so that
* box_region_truncate() wasn't strictly necessary. Starting from
* version 2.11, it isn't true anymore, and the client code must free
* all its allocations explicitly.
*/
/** How much memory is used by the box region. */
API_EXPORT size_t
box_region_used(void);
/**
* Allocate size bytes from the box region.
*
* Don't use this function to allocate a memory block for a value
* or array of values of a type with alignment requirements. A
* violation of alignment requirements leads to undefined
* behaviour.
*
* In case of a memory error set a diag and return NULL.
* @sa box_error_last().
*/
API_EXPORT void *
box_region_alloc(size_t size);
/**
* Allocate size bytes from the box region with given alignment.
*
* Alignment must be a power of 2.
*
* In case of a memory error set a diag and return NULL.
* @sa box_error_last().
*/
API_EXPORT void *
box_region_aligned_alloc(size_t size, size_t alignment);
/**
* Truncate the box region to the given size.
*/
API_EXPORT void
box_region_truncate(size_t size);
/** \endcond public */
/**
* Fiber attribute container
*/
struct fiber_attr {
/** Fiber stack size. */
size_t stack_size;
/** Fiber flags. */
uint32_t flags;
};
/**
* Init fiber attr with default values
*/
void
fiber_attr_create(struct fiber_attr *fiber_attr);
/**
* Under no circumstances this header file is allowed to include
* application-specific headers like session.h or txn.h. One only
* is allowed to announce a struct and add opaque pointer to it.
*/
struct session;
struct txn;
struct credentials;
struct lua_State;
struct ipc_wait_pad;
/**
* Warning and error slices.
*/
struct fiber_slice {
/**
* If warning slice is exceeded, the warning will
* be written in log when you check slice.
*/
double warn;
/**
* If error slice is exceeded, fiber_check_slice()
* will set diag and return -1.
*/
double err;
};
struct fiber {
coro_context ctx;
/** Coro stack slab. */
struct slab *stack_slab;
/** Coro stack addr. */
void *stack;
#ifdef HAVE_MADV_DONTNEED
/**
* We want to keep total stack memory usage low while still
* allowing tasks that need a greater than average stack.
* To achieve that, we write some poison values to stack
* at "watermark" position and call madvise(MADV_DONTNEED)
* when a fiber is recycled in case a poison value has been
* overwritten. This allows to keep per-fiber stack memory
* usage below the watermark while avoiding any performance
* penalty if there are no tasks eager for stack.
*/
void *stack_watermark;
#endif
/** Coro stack size. */
size_t stack_size;
/** Fiber's custom slice if fiber has it, zero otherwise. */
struct fiber_slice max_slice;
/** Valgrind stack id. */
unsigned int stack_id;
/** A garbage-collected memory pool. */
struct region gc;
#ifdef ENABLE_BACKTRACE
/**
* Backtrace of the first fiber gc allocation that does not
* truncated yet. NULL if backtrace is not supported by the
* platform or fiber_leak_backtrace_enable == false.
*/
struct backtrace *first_alloc_bt;
#endif
/**
* This much size of fiber gc at the beginning is used for
* fiber internal purpuses.
*/
size_t gc_initial_size;
/**
* The fiber which should be scheduled when
* this fiber yields.
*/
struct fiber *caller;
/** Number of context switches. */
int csw;
/** Fiber id. */
uint64_t fid;
/** Fiber flags */
uint32_t flags;
struct clock_stat clock_stat;
/** Link in cord->alive or cord->dead list. */
struct rlist link;
/** Link in cord->ready list. */
struct rlist state;
/** Triggers invoked before this fiber yields. Must not throw. */
struct rlist on_yield;
/**
* Triggers invoked before this fiber is stopped/reset/
* recycled/destroyed/reused. In other words, each time
* when the fiber has finished execution of a request.
* In particular, for fibers not from a fiber pool the
* stop event is emitted before destruction and death.
* Pooled fibers receive the stop event after each
* request, even if they are never destroyed.
*/
struct rlist on_stop;
/**
* The list of fibers awaiting for this fiber's timely
* (or untimely) death.
*/
struct rlist wake;
/**
* This struct is considered as non-POD when compiling by g++.
* You can safely ignore all offset_of-related warnings.
* See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=31488
*/
fiber_func f;
union {
/**
* Argument list passed when the fiber is invoked in a blocking
* way, so the caller may pass arguments from its own stack.
*/
va_list f_data;
/**
* Fiber function argument which passed asynchronously. Can be
* used not to call fiber_start to avoid yields, but still pass
* something into the fiber.
*/
void *f_arg;
};
int f_ret;
/** Fiber local storage. */
struct {
/**
* Current transaction, session and the active
* user credentials are shared among multiple
* requests and valid even out of a former.
*/
struct session *session;
struct credentials *credentials;
struct txn *txn;
/** Fields related to Lua code execution. */
struct {
/**
* Optional Lua state (may be NULL).
* Useful as a temporary Lua state to save
* time and resources on creating it.
* Should not be used in other fibers.
*/
struct lua_State *stack;
/**
* Optional reference to userdata
* representing current fiber id in Lua.
*/
int fid_ref;
/**
* Optional fiber.storage Lua reference.
*/
int storage_ref;
} lua;
/**
* Iproto sync.
*/
struct {
uint64_t sync;
} net;
} storage;
/** An object to wait for incoming message or a reader. */
struct ipc_wait_pad *wait_pad;
/** Exception which caused this fiber's death. */
struct diag diag;
/**
* Name points at inline_name in case it is short. Long
* name is allocated on the heap.
*/
char *name;
char inline_name[FIBER_NAME_INLINE];
#ifdef ENABLE_BACKTRACE
/* Fiber parent's backtrace allocated on the 'gc' region. */
struct backtrace_lua *parent_bt;
#endif /* ENABLE_BACKTRACE */
};
/** Invoke on_stop triggers and delete them. */
void
fiber_on_stop(struct fiber *f);
struct cord_on_exit;
/**
* @brief An independent execution unit that can be managed by a separate OS
* thread. Each cord consists of fibers to implement cooperative multitasking
* model.
*/
struct cord {
/** The fiber that is currently being executed. */
struct fiber *fiber;
struct ev_loop *loop;
/**
* Every new fiber gets a new monotonic id. Ids 0 - 100 are
* reserved.
*/
uint64_t next_fid;
struct clock_stat clock_stat;
struct cpu_stat cpu_stat;
pthread_t id;
const struct cord_on_exit *on_exit;
/** A helper hash to map id -> fiber. */
struct mh_i64ptr_t *fiber_registry;
/** All fibers */
struct rlist alive;
/** Fibers, ready for execution */
struct rlist ready;
/** A cache of dead fibers for reuse */
struct rlist dead;
/**
* Latest dead fiber which couldn't be reused and waits for its
* deletion. A fiber can't be reused if it is somehow non-standard. For
* instance, has a special stack.
* A fiber can't be deleted if it is the current fiber - can't delete
* own stack safely. Then it schedules own deletion for later. The
* approach is very similar to pthread stacks deletion - pthread can't
* delete own stack, so they are saved and deleted later by a newer
* pthread or by some other dying pthread. Same here with fibers.
*/
struct fiber *garbage;
/** A watcher to have a single async event for all ready fibers.
* This technique is necessary to be able to suspend
* a single fiber on a few watchers (for example,
* a timeout and an event from network, whichever comes
* first).
* */
ev_async wakeup_event;
/**
* libev sleeps at least backend_mintime, which is 1 ms in
* case of poll()/Linux, unless there are idle watchers.
* This is a special hack to speed up fiber_sleep(0),
* i.e. a sleep with a zero timeout, to ensure that there
* is no 1 ms delay in case of zero sleep timeout.
*/
ev_idle idle_event;
/** An event triggered on every event loop iteration start. */
ev_check check_event;
/**
* An event triggered on every event loop iteration end.
* Just like the event above it is used in per-fiber cpu
* time calculations.
*/
ev_prepare prepare_event;
/** A memory cache for (struct fiber) */
struct mempool fiber_mempool;
/** A runtime slab cache for general use in this cord. */
struct slab_cache slabc;
/** The "main" fiber of this cord, the scheduler. */
struct fiber sched;
/**
* Time when the current fiber was called.
* Needed for checking slices. A low resolution
* monotonic clock is used to measure the time
* to reduce performance as little as possible.
*/
double call_time;
/**
* Default max slice for fibers in seconds.
* It is used if running fiber has no custom max slice.
*/
struct fiber_slice max_slice;
/** Slice for current fiber execution in seconds. */
struct fiber_slice slice;
char name[FIBER_NAME_INLINE];
};
extern __thread struct cord *cord_ptr;
/**
* Returns a thread-local cord object.
*
* If the cord object wasn't initialized at thread start (cord_create()
* wasn't called), a cord object is created automatically and destroyed
* at thread exit.
*/
#define cord() ({ \
if (unlikely(cord_ptr == NULL)) \
cord_ptr = cord_on_demand(); \
cord_ptr; \
})
#define fiber() cord()->fiber
#define loop() (cord()->loop)
void
cord_create(struct cord *cord, const char *name);
/**
* Perform all the thread-specific deinitialization. Must be called in the
* exiting thread.
*/
void
cord_exit(struct cord *cord);
void
cord_destroy(struct cord *cord);
/**
* Start a cord with the given thread function.
* The return value of the function can be collected
* with cord_join(). The function *must catch* all
* exceptions and leave them in the diagnostics
* area, cord_join() moves the exception from the
* terminated cord to the caller of cord_join().
*/
int
cord_start(struct cord *cord, const char *name,
void *(*f)(void *), void *arg);
/**
* Like cord_start(), but starts the event loop and
* a fiber in the event loop. The event loop ends when the
* fiber in main fiber dies/returns. The exception of the main
* fiber is propagated to cord_cojoin().
*/
int
cord_costart(struct cord *cord, const char *name, fiber_func f, void *arg);
/**
* Yield until \a cord has terminated.
*
* On success:
*
* If \a cord has terminated with an uncaught exception
* the exception is moved to the current fiber's diagnostics
* area, otherwise the current fiber's diagnostics area is
* cleared.
* @param cord cord
* @sa pthread_join()
*
* @return 0 on success, -1 if pthread_join failed or the
* thread function terminated with an exception.
*/
int
cord_cojoin(struct cord *cord);
/**
* Wait for \a cord to terminate. If \a cord has already
* terminated, then returns immediately.
*
* @post If the subject cord terminated with an exception,
* preserves the exception in the caller's cord.
*
* @param cord cord
* @return 0 on success, -1 if pthread_join failed or the
* thread function terminated with an exception.
*/
int
cord_join(struct cord *cord);
void
cord_set_name(const char *name);
static inline const char *
cord_name(struct cord *cord)
{
return cord->name;
}
/** True if this cord represents the process main thread. */
bool
cord_is_main(void);
/**
* Delete the latest garbage fiber which couldn't be deleted somewhy before. Can
* safely rely on the fiber being not the current one. Because if it was added
* here before, it means some previous fiber put itself here, then died
* immediately afterwards for good, and gave control to another fiber. It
* couldn't be scheduled again.
*/
void
cord_collect_garbage(struct cord *cord);
/**
* Pthread-cancel the thread and join it in a blocking way, without yielding.
* That way is the only possible one if the event loop is already destroyed.
* Should only be used as an emergency, because all the cord resources simply
* leak.
*/
void
cord_cancel_and_join(struct cord *cord);
/**
* Return slab_cache suitable to use with tarantool/small library
*/
static inline struct slab_cache *
cord_slab_cache(void)
{
return &cord()->slabc;
}
/**
* @brief Create a new system fiber.
*
* @details
* Works the same way as fiber_new(), but uses fiber_attr_default
* supplemented by the FIBER_IS_SYSTEM flag in order to create a
* fiber.
*
* @param name string with fiber name
* @param f func for run inside fiber
*/
struct fiber *
fiber_new_system(const char *name, fiber_func f);
void
fiber_init(int (*fiber_invoke)(fiber_func f, va_list ap));
void
fiber_free(void);
/**
* Manually init signals needed for fiber module.
* This function is re-entrant.
* All needed signals are initialized in fiber_init,
* but you may need this functions to init signals
* after they have been reset before fork.
*/
void
fiber_signal_init(void);
/**
* Reset signals needed for fiber module.
* See fiber_signal_init description.
*/
void
fiber_signal_reset(void);
/**
* Set fiber name.
* @param fiber Fiber to set name for.
* @param name A new name of @a fiber.
*/
void
fiber_set_name(struct fiber *fiber, const char *name);
static inline const char *
fiber_name(struct fiber *f)
{
return f->name;
}
/** Helper function to check if slice is valid. */
static inline bool
fiber_slice_is_valid(struct fiber_slice slice)
{
return slice.err >= 0 && slice.warn >= 0;
}
/**
* Time since current fiber was called.
* A low resolution monotonic clock is used to measure
* the time to reduce performance as little as possible.
*/
static inline double
fiber_time_from_call(void)
{
return clock_lowres_monotonic() - cord()->call_time;
}
/**
* Set slice for current fiber execution.
* Slices must be greater than 0.
*/
static inline void
fiber_set_slice(struct fiber_slice slice)
{
assert(cord_is_main());
assert(fiber_slice_is_valid(slice));
cord()->slice = slice;
}
/**
* Extend slice for current fiber execution.