Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
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
/*-------------------------------------------------------------------------
 *
 * method_io_uring.c
 *    AIO - perform AIO using Linux' io_uring
 *
 * For now we create one io_uring instance for each backend. These io_uring
 * instances have to be created in postmaster, during startup, to allow other
 * backends to process IO completions, if the issuing backend is currently
 * busy doing other things. Other backends may not use another backend's
 * io_uring instance to submit IO, that'd require additional locking that
 * would likely be harmful for performance.
 *
 * We likely will want to introduce a backend-local io_uring instance in the
 * future, e.g. for FE/BE network IO.
 *
 * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 * IDENTIFICATION
 *    src/backend/storage/aio/method_io_uring.c
 *
 *-------------------------------------------------------------------------
 */
 
#include "postgres.h"
 
/* included early, for IOMETHOD_IO_URING_ENABLED */
#include "storage/aio.h"
 
#ifdef IOMETHOD_IO_URING_ENABLED
 
#include <sys/mman.h>
#include <unistd.h>
 
#include <liburing.h>
 
#include "miscadmin.h"
#include "storage/aio_internal.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/proc.h"
#include "storage/shmem.h"
#include "storage/lwlock.h"
#include "storage/procnumber.h"
#include "utils/wait_event.h"
 
 
/* number of completions processed at once */
#define PGAIO_MAX_LOCAL_COMPLETED_IO 32
 
 
/* Entry points for IoMethodOps. */
static void pgaio_uring_shmem_request(void *arg);
static void pgaio_uring_shmem_init(void *arg);
static void pgaio_uring_init_backend(void);
static int  pgaio_uring_submit(uint16 num_staged_ios, PgAioHandle **staged_ios);
static void pgaio_uring_wait_one(PgAioHandle *ioh, uint64 ref_generation);
static void pgaio_uring_check_one(PgAioHandle *ioh, uint64 ref_generation);
 
/* helper functions */
static void pgaio_uring_sq_from_io(PgAioHandle *ioh, struct io_uring_sqe *sqe);
 
 
const IoMethodOps pgaio_uring_ops = {
    /*
     * While io_uring mostly is OK with FDs getting closed while the IO is in
     * flight, that is not true for IOs submitted with IOSQE_ASYNC.
     *
     * See
     * https://postgr.es/m/5ons2rtmwarqqhhexb3dnqulw5rjgwgoct57vpdau4rujlrffj%403fls6d2mkiwc
     */
    .wait_on_fd_before_close = true,
 
    .shmem_callbacks.request_fn = pgaio_uring_shmem_request,
    .shmem_callbacks.init_fn = pgaio_uring_shmem_init,
    .init_backend = pgaio_uring_init_backend,
 
    .submit = pgaio_uring_submit,
    .wait_one = pgaio_uring_wait_one,
    .check_one = pgaio_uring_check_one,
};
 
/*
 * Per-backend state when using io_method=io_uring
 */
typedef struct PgAioUringContext
{
    /*
     * Align the whole struct to a cacheline boundary, to prevent false
     * sharing between completion_lock and prior backend's io_uring_ring.
     */
    alignas(PG_CACHE_LINE_SIZE)
 
    /*
     * Multiple backends can process completions for this backend's io_uring
     * instance (e.g. when the backend issuing IO is busy doing something
     * else).  To make that safe we have to ensure that only a single backend
     * gets io completions from the io_uring instance at a time.
     */
    LWLock      completion_lock;
 
    struct io_uring io_uring_ring;
} PgAioUringContext;
 
/*
 * Information about the capabilities that io_uring has.
 *
 * Depending on liburing and kernel version different features are
 * supported. At least for the kernel a kernel version check does not suffice
 * as various vendors do backport features to older kernels :(.
 */
typedef struct PgAioUringCaps
{
    bool        checked;
    /* -1 if io_uring_queue_init_mem() is unsupported */
    int         mem_init_size;
} PgAioUringCaps;
 
 
/* PgAioUringContexts for all backends */
static PgAioUringContext *pgaio_uring_contexts;
 
/* the current backend's context */
static PgAioUringContext *pgaio_my_uring_context;
 
static PgAioUringCaps pgaio_uring_caps =
{
    .checked = false,
    .mem_init_size = -1,
};
 
static uint32
pgaio_uring_procs(void)
{
    /*
     * We can subtract MAX_IO_WORKERS here as io workers are never used at the
     * same time as io_method=io_uring.
     */
    return MaxBackends + NUM_AUXILIARY_PROCS - MAX_IO_WORKERS;
}
 
/*
 * Initializes pgaio_uring_caps, unless that's already done.
 */
static void
pgaio_uring_check_capabilities(void)
{
    if (pgaio_uring_caps.checked)
        return;
 
    /*
     * By default io_uring creates a shared memory mapping for each io_uring
     * instance, leading to a large number of memory mappings. Unfortunately a
     * large number of memory mappings slows things down, backend exit is
     * particularly affected.  To address that, newer kernels (6.5) support
     * using user-provided memory for the memory, by putting the relevant
     * memory into shared memory we don't need any additional mappings.
     *
     * To know whether this is supported, we unfortunately need to probe the
     * kernel by trying to create a ring with userspace-provided memory. This
     * also has a secondary benefit: We can determine precisely how much
     * memory we need for each io_uring instance.
     */
#if defined(HAVE_IO_URING_QUEUE_INIT_MEM) && defined(IORING_SETUP_NO_MMAP)
    {
        struct io_uring test_ring;
        size_t      ring_size;
        void       *ring_ptr;
        struct io_uring_params p = {0};
        int         ret;
 
        /*
         * Liburing does not yet provide an API to query how much memory a
         * ring will need. So we over-estimate it here. As the memory is freed
         * just below that's small temporary waste of memory.
         *
         * 1MB is more than enough for rings within io_max_concurrency's
         * range.
         */
        ring_size = 1024 * 1024;
 
        /*
         * Hard to believe a system exists where 1MB would not be a multiple
         * of the page size. But it's cheap to ensure...
         */
        ring_size -= ring_size % sysconf(_SC_PAGESIZE);
 
        ring_ptr = mmap(NULL, ring_size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
        if (ring_ptr == MAP_FAILED)
            elog(ERROR,
                 "mmap(%zu) to determine io_uring_queue_init_mem() support failed: %m",
                 ring_size);
 
        ret = io_uring_queue_init_mem(io_max_concurrency, &test_ring, &p, ring_ptr, ring_size);
        if (ret > 0)
        {
            pgaio_uring_caps.mem_init_size = ret;
 
            elog(DEBUG1,
                 "can use combined memory mapping for io_uring, each ring needs %d bytes",
                 ret);
 
            /* clean up the created ring, it was just for a test */
            io_uring_queue_exit(&test_ring);
        }
        else
        {
            /*
             * There are different reasons for ring creation to fail, but it's
             * ok to treat that just as io_uring_queue_init_mem() not being
             * supported. We'll report a more detailed error in
             * pgaio_uring_shmem_init().
             */
            errno = -ret;
            elog(DEBUG1,
                 "cannot use combined memory mapping for io_uring, ring creation failed: %m");
 
        }
 
        if (munmap(ring_ptr, ring_size) != 0)
            elog(ERROR, "munmap() failed: %m");
    }
#else
    {
        elog(DEBUG1,
             "can't use combined memory mapping for io_uring, kernel or liburing too old");
    }
#endif
 
    pgaio_uring_caps.checked = true;
}
 
/*
 * Memory for all PgAioUringContext instances
 */
static size_t
pgaio_uring_context_shmem_size(void)
{
    return mul_size(pgaio_uring_procs(), sizeof(PgAioUringContext));
}
 
/*
 * Memory for the combined memory used by io_uring instances. Returns 0 if
 * that is not supported by kernel/liburing.
 */
static size_t
pgaio_uring_ring_shmem_size(void)
{
    size_t      sz = 0;
 
    if (pgaio_uring_caps.mem_init_size > 0)
    {
        /*
         * Memory for rings needs to be allocated to the page boundary,
         * reserve space. Luckily it does not need to be aligned to hugepage
         * boundaries, even if huge pages are used.
         */
        sz = add_size(sz, sysconf(_SC_PAGESIZE));
        sz = add_size(sz, mul_size(pgaio_uring_procs(),
                                   pgaio_uring_caps.mem_init_size));
    }
 
    return sz;
}
 
static size_t
pgaio_uring_shmem_size(void)
{
    size_t      sz;
 
    sz = pgaio_uring_context_shmem_size();
    sz = add_size(sz, pgaio_uring_ring_shmem_size());
 
    return sz;
}
 
static void
pgaio_uring_shmem_request(void *arg)
{
    /*
     * Kernel and liburing support for various features influences how much
     * shmem we need, perform the necessary checks.
     */
    pgaio_uring_check_capabilities();
 
    ShmemRequestStruct(.name = "AioUringContext",
                       .size = pgaio_uring_shmem_size(),
                       .ptr = (void **) &pgaio_uring_contexts,
        );
}
 
/*
 * on_shmem_exit() callback that releases the io_uring instances created by
 * pgaio_uring_shmem_init().  Besides process exit, this is called when the
 * postmaster reinitializes shared memory after a backend crash.
 */
static void
pgaio_uring_cleanup(int code, Datum arg)
{
    int         TotalProcs = pgaio_uring_procs();
 
    Assert(!IsUnderPostmaster);
    Assert(pgaio_uring_contexts != NULL);
 
    for (int i = 0; i < TotalProcs; i++)
        io_uring_queue_exit(&pgaio_uring_contexts[i].io_uring_ring);
 
    pgaio_uring_contexts = NULL;
}
 
static void
pgaio_uring_shmem_init(void *arg)
{
    int         TotalProcs = pgaio_uring_procs();
    char       *shmem;
    size_t      ring_mem_remain = 0;
    char       *ring_mem_next = 0;
 
    /*
     * We allocate memory for all PgAioUringContext instances and, if
     * supported, the memory required for each of the io_uring instances, in
     * one combined allocation.
     *
     * pgaio_uring_contexts is already set to the base of the allocation.
     */
    shmem = (char *) pgaio_uring_contexts;
    shmem += pgaio_uring_context_shmem_size();
 
    /* if supported, handle memory alignment / sizing for io_uring memory */
    if (pgaio_uring_caps.mem_init_size > 0)
    {
        ring_mem_remain = pgaio_uring_ring_shmem_size();
        ring_mem_next = shmem;
 
        /* align to page boundary, see also pgaio_uring_ring_shmem_size() */
        ring_mem_next = (char *) TYPEALIGN(sysconf(_SC_PAGESIZE), ring_mem_next);
 
        /* account for alignment */
        ring_mem_remain -= ring_mem_next - shmem;
        shmem += ring_mem_next - shmem;
 
        shmem += ring_mem_remain;
    }
 
    for (int contextno = 0; contextno < TotalProcs; contextno++)
    {
        PgAioUringContext *context = &pgaio_uring_contexts[contextno];
        int         ret;
 
        /*
         * Right now a high TotalProcs will cause problems in two ways:
         *
         * - RLIMIT_NOFILE needs to be big enough to allow all
         * io_uring_queue_init() calls to succeed.
         *
         * - RLIMIT_NOFILE needs to be big enough to still have enough file
         * descriptors to satisfy set_max_safe_fds() left over. Or, even
         * better, have max_files_per_process left over FDs.
         *
         * We probably should adjust the soft RLIMIT_NOFILE to ensure that.
         *
         *
         * XXX: Newer versions of io_uring support sharing the workers that
         * execute some asynchronous IOs between io_uring instances. It might
         * be worth using that - also need to evaluate if that causes
         * noticeable additional contention?
         */
 
        /*
         * If supported (c.f. pgaio_uring_check_capabilities()), create ring
         * with its data in shared memory. Otherwise fall back io_uring
         * creating a memory mapping for each ring.
         */
#if defined(HAVE_IO_URING_QUEUE_INIT_MEM) && defined(IORING_SETUP_NO_MMAP)
        if (pgaio_uring_caps.mem_init_size > 0)
        {
            struct io_uring_params p = {0};
 
            ret = io_uring_queue_init_mem(io_max_concurrency, &context->io_uring_ring, &p, ring_mem_next, ring_mem_remain);
 
            ring_mem_remain -= ret;
            ring_mem_next += ret;
        }
        else
#endif
        {
            ret = io_uring_queue_init(io_max_concurrency, &context->io_uring_ring, 0);
        }
 
        if (ret < 0)
        {
            char       *hint = NULL;
            int         err = ERRCODE_INTERNAL_ERROR;
 
            /* add hints for some failures that errno explains sufficiently */
            if (-ret == EPERM)
            {
                err = ERRCODE_INSUFFICIENT_PRIVILEGE;
                hint = _("Check if io_uring is disabled via /proc/sys/kernel/io_uring_disabled.");
            }
            else if (-ret == EMFILE)
            {
                err = ERRCODE_INSUFFICIENT_RESOURCES;
                hint = psprintf(_("Consider increasing \"ulimit -n\" to at least %d."),
                                TotalProcs + max_files_per_process);
            }
            else if (-ret == ENOSYS)
            {
                err = ERRCODE_FEATURE_NOT_SUPPORTED;
                hint = _("The kernel does not support io_uring.");
            }
 
            /* update errno to allow %m to work */
            errno = -ret;
 
            ereport(ERROR,
                    errcode(err),
                    errmsg("could not setup io_uring queue: %m"),
                    hint != NULL ? errhint("%s", hint) : 0);
        }
 
        LWLockInitialize(&context->completion_lock, LWTRANCHE_AIO_URING_COMPLETION);
    }
 
    on_shmem_exit(pgaio_uring_cleanup, 0);
}
 
static void
pgaio_uring_init_backend(void)
{
    Assert(MyProcNumber < pgaio_uring_procs());
 
    pgaio_my_uring_context = &pgaio_uring_contexts[MyProcNumber];
}
 
static int
pgaio_uring_submit(uint16 num_staged_ios, PgAioHandle **staged_ios)
{
    struct io_uring *uring_instance = &pgaio_my_uring_context->io_uring_ring;
 
    Assert(num_staged_ios <= PGAIO_SUBMIT_BATCH_SIZE);
 
    for (int i = 0; i < num_staged_ios; i++)
    {
        PgAioHandle *ioh = staged_ios[i];
        struct io_uring_sqe *sqe;
 
        sqe = io_uring_get_sqe(uring_instance);
 
        if (!sqe)
            elog(ERROR, "io_uring submission queue is unexpectedly full");
 
        pgaio_io_prepare_submit(ioh);
        pgaio_uring_sq_from_io(ioh, sqe);
    }
 
    while (true)
    {
        int         ret;
 
        pgstat_report_wait_start(WAIT_EVENT_AIO_IO_URING_SUBMIT);
        ret = io_uring_submit(uring_instance);
        pgstat_report_wait_end();
 
        if (ret == -EINTR)
        {
            pgaio_debug(DEBUG3,
                        "aio method uring: submit EINTR, nios: %d",
                        num_staged_ios);
        }
        else if (ret < 0)
        {
            /*
             * The io_uring_enter() manpage suggests that the appropriate
             * reaction to EAGAIN is:
             *
             * "The application should wait for some completions and try
             * again"
             *
             * However, it seems unlikely that that would help in our case, as
             * we apply a low limit to the number of outstanding IOs and thus
             * also outstanding completions, making it unlikely that we'd get
             * EAGAIN while the OS is in good working order.
             *
             * Additionally, it would be problematic to just wait here, our
             * caller might hold critical locks. It'd possibly lead to
             * delaying the crash-restart that seems likely to occur when the
             * kernel is under such heavy memory pressure.
             *
             * Update errno to allow %m to work.
             */
            errno = -ret;
            elog(PANIC, "io_uring submit failed: %m");
        }
        else if (ret != num_staged_ios)
        {
            /* likely unreachable, but if it is, we would need to re-submit */
            elog(PANIC, "io_uring submit submitted only %d of %d",
                 ret, num_staged_ios);
        }
        else
        {
            pgaio_debug(DEBUG4,
                        "aio method uring: submitted %d IOs",
                        num_staged_ios);
            break;
        }
    }
 
    return num_staged_ios;
}
 
static void
pgaio_uring_completion_error_callback(void *arg)
{
    ProcNumber  owner;
    PGPROC     *owner_proc;
    int32       owner_pid;
    PgAioHandle *ioh = arg;
 
    if (!ioh)
        return;
 
    /* No need for context if a backend is completing the IO for itself */
    if (ioh->owner_procno == MyProcNumber)
        return;
 
    owner = ioh->owner_procno;
    owner_proc = GetPGProcByNumber(owner);
    owner_pid = owner_proc->pid;
 
    errcontext("completing I/O on behalf of process %d", owner_pid);
}
 
static void
pgaio_uring_drain_locked(PgAioUringContext *context)
{
    int         ready;
    int         orig_ready;
    ErrorContextCallback errcallback = {0};
 
    Assert(LWLockHeldByMeInMode(&context->completion_lock, LW_EXCLUSIVE));
 
    errcallback.callback = pgaio_uring_completion_error_callback;
    errcallback.previous = error_context_stack;
    error_context_stack = &errcallback;
 
    /*
     * Don't drain more events than available right now. Otherwise it's
     * plausible that one backend could get stuck, for a while, receiving CQEs
     * without actually processing them.
     */
    orig_ready = ready = io_uring_cq_ready(&context->io_uring_ring);
 
    while (ready > 0)
    {
        struct io_uring_cqe *cqes[PGAIO_MAX_LOCAL_COMPLETED_IO];
        uint32      ncqes;
 
        START_CRIT_SECTION();
        ncqes =
            io_uring_peek_batch_cqe(&context->io_uring_ring,
                                    cqes,
                                    Min(PGAIO_MAX_LOCAL_COMPLETED_IO, ready));
        Assert(ncqes <= ready);
 
        ready -= ncqes;
 
        for (int i = 0; i < ncqes; i++)
        {
            struct io_uring_cqe *cqe = cqes[i];
            PgAioHandle *ioh = io_uring_cqe_get_data(cqe);
            int         result = cqe->res;
 
            errcallback.arg = ioh;
 
            io_uring_cqe_seen(&context->io_uring_ring, cqe);
 
            pgaio_io_process_completion(ioh, result);
            errcallback.arg = NULL;
        }
 
        END_CRIT_SECTION();
 
        pgaio_debug(DEBUG3,
                    "drained %d/%d, now expecting %d",
                    ncqes, orig_ready, io_uring_cq_ready(&context->io_uring_ring));
    }
 
    error_context_stack = errcallback.previous;
}
 
static void
pgaio_uring_wait_one(PgAioHandle *ioh, uint64 ref_generation)
{
    PgAioHandleState state;
    ProcNumber  owner_procno = ioh->owner_procno;
    PgAioUringContext *owner_context = &pgaio_uring_contexts[owner_procno];
    bool        expect_cqe;
    int         waited = 0;
 
    /*
     * XXX: It would be nice to have a smarter locking scheme, nearly all the
     * time the backend owning the ring will consume the completions, making
     * the locking unnecessarily expensive.
     */
    LWLockAcquire(&owner_context->completion_lock, LW_EXCLUSIVE);
 
    while (true)
    {
        pgaio_debug_io(DEBUG3, ioh,
                       "wait_one io_gen: %" PRIu64 ", ref_gen: %" PRIu64 ", cycle %d",
                       ioh->generation,
                       ref_generation,
                       waited);
 
        if (pgaio_io_was_recycled(ioh, ref_generation, &state) ||
            state != PGAIO_HS_SUBMITTED)
        {
            /* the IO was completed by another backend */
            break;
        }
        else if (io_uring_cq_ready(&owner_context->io_uring_ring))
        {
            /* no need to wait in the kernel, io_uring has a completion */
            expect_cqe = true;
        }
        else
        {
            int         ret;
            struct io_uring_cqe *cqes;
 
            /* need to wait in the kernel */
            pgstat_report_wait_start(WAIT_EVENT_AIO_IO_URING_EXECUTION);
            ret = io_uring_wait_cqes(&owner_context->io_uring_ring, &cqes, 1, NULL, NULL);
            pgstat_report_wait_end();
 
            if (ret == -EINTR)
            {
                continue;
            }
            else if (ret != 0)
            {
                /* see comment after io_uring_submit() */
                errno = -ret;
                elog(PANIC, "io_uring wait failed: %m");
            }
            else
            {
                Assert(cqes != NULL);
                expect_cqe = true;
                waited++;
            }
        }
 
        if (expect_cqe)
        {
            pgaio_uring_drain_locked(owner_context);
        }
    }
 
    LWLockRelease(&owner_context->completion_lock);
 
    pgaio_debug(DEBUG3,
                "wait_one with %d sleeps",
                waited);
}
 
static void
pgaio_uring_check_one(PgAioHandle *ioh, uint64 ref_generation)
{
    ProcNumber  owner_procno = ioh->owner_procno;
    PgAioUringContext *owner_context = &pgaio_uring_contexts[owner_procno];
 
    /*
     * This check is not reliable when not holding the completion lock, but
     * it's a useful cheap pre-check to see if it's worth trying to get the
     * completion lock.
     */
    if (!io_uring_cq_ready(&owner_context->io_uring_ring))
        return;
 
    /*
     * If the completion lock is currently held, the holder will likely
     * process any pending completions, give up.
     */
    if (!LWLockConditionalAcquire(&owner_context->completion_lock, LW_EXCLUSIVE))
        return;
 
    pgaio_debug_io(DEBUG3, ioh,
                   "check_one io_gen: %" PRIu64 ", ref_gen: %" PRIu64,
                   ioh->generation,
                   ref_generation);
 
    /*
     * Recheck if there are any completions, another backend could have
     * processed them since we checked above, or our unlocked pre-check could
     * have been reading outdated values.
     *
     * It is possible that the IO handle has been reused since the start of
     * the call, but now that we have the lock, we can just as well drain all
     * completions.
     */
    if (io_uring_cq_ready(&owner_context->io_uring_ring))
        pgaio_uring_drain_locked(owner_context);
 
    LWLockRelease(&owner_context->completion_lock);
}
 
/*
 * io_uring executes IO in process context if possible. That's generally good,
 * as it reduces context switching. When performing a lot of buffered IO that
 * means that copying between page cache and userspace memory happens in the
 * foreground, as it can't be offloaded to DMA hardware as is possible when
 * using direct IO. When executing a lot of buffered IO this causes io_uring
 * to be slower than worker mode, as worker mode parallelizes the
 * copying. io_uring can be told to offload work to worker threads instead.
 *
 * If the IOs are small, we only benefit from forcing things into the
 * background if there is a lot of IO, as otherwise the overhead from context
 * switching is higher than the gain.
 *
 * If IOs are large, there is benefit from asynchronous processing at lower
 * queue depths, as IO latency is less of a crucial factor and parallelizing
 * memory copies is more important.  In addition, it is important to trigger
 * asynchronous processing even at low queue depth, as with foreground
 * processing we might never actually reach deep enough IO depths to trigger
 * asynchronous processing, which in turn would deprive readahead control
 * logic of information about whether a deeper look-ahead distance would be
 * advantageous.
 *
 * We have done some basic benchmarking to validate the thresholds used, but
 * it's quite plausible that there are better values.  See
 * https://postgr.es/m/3gkuvs3lz3u3skuaxfkxnsysfqslf2srigl6546vhesekve6v2%40va3r5esummvg
 * for some details of this benchmarking.
 */
static bool
pgaio_uring_should_use_async(PgAioHandle *ioh, size_t io_size)
{
    /*
     * With DIO there's no benefit from forcing asynchronous processing, as
     * io_uring will never execute direct IO synchronously during submission.
     */
    if (!(ioh->flags & PGAIO_HF_BUFFERED))
        return false;
 
    /*
     * Once the IO queue depth is not that shallow anymore, the overhead of
     * dispatching to the background is a less significant factor.
     */
    if (dclist_count(&pgaio_my_backend->in_flight_ios) > 4)
        return true;
 
    /*
     * If the IO is larger, the gains from parallelizing the memory copy are
     * larger and typically the impact of the latency is smaller.
     */
    if (io_size >= (BLCKSZ * 4))
        return true;
 
    return false;
}
 
static void
pgaio_uring_sq_from_io(PgAioHandle *ioh, struct io_uring_sqe *sqe)
{
    struct iovec *iov;
    size_t      io_size = 0;
 
    switch ((PgAioOp) ioh->op)
    {
        case PGAIO_OP_READV:
            iov = &pgaio_ctl->iovecs[ioh->iovec_off];
            if (ioh->op_data.read.iov_length == 1)
            {
                io_uring_prep_read(sqe,
                                   ioh->op_data.read.fd,
                                   iov->iov_base,
                                   iov->iov_len,
                                   ioh->op_data.read.offset);
 
                io_size = iov->iov_len;
            }
            else
            {
                io_uring_prep_readv(sqe,
                                    ioh->op_data.read.fd,
                                    iov,
                                    ioh->op_data.read.iov_length,
                                    ioh->op_data.read.offset);
 
                for (int i = 0; i < ioh->op_data.read.iov_length; i++, iov++)
                    io_size += iov->iov_len;
            }
 
            if (pgaio_uring_should_use_async(ioh, io_size))
                io_uring_sqe_set_flags(sqe, IOSQE_ASYNC);
 
            break;
 
        case PGAIO_OP_WRITEV:
            iov = &pgaio_ctl->iovecs[ioh->iovec_off];
            if (ioh->op_data.write.iov_length == 1)
            {
                io_uring_prep_write(sqe,
                                    ioh->op_data.write.fd,
                                    iov->iov_base,
                                    iov->iov_len,
                                    ioh->op_data.write.offset);
            }
            else
            {
                io_uring_prep_writev(sqe,
                                     ioh->op_data.write.fd,
                                     iov,
                                     ioh->op_data.write.iov_length,
                                     ioh->op_data.write.offset);
            }
 
            /*
             * For now don't trigger use of IOSQE_ASYNC for writes, it's not
             * clear there is a performance benefit in doing so.
             */
 
            break;
 
        case PGAIO_OP_INVALID:
            elog(ERROR, "trying to prepare invalid IO operation for execution");
    }
 
    io_uring_sqe_set_data(sqe, ioh);
}
 
#endif                          /* IOMETHOD_IO_URING_ENABLED */