summaryrefslogtreecommitdiffhomepage
path: root/src/nxt_port_queue.h
blob: d2b2326bf19378b5b5dae439e3f14dca739c41b4 (plain) (blame)
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

/*
 * Copyright (C) NGINX, Inc.
 */

#ifndef _NXT_PORT_QUEUE_H_INCLUDED_
#define _NXT_PORT_QUEUE_H_INCLUDED_


#include <nxt_nncq.h>


/* Using Numeric Naive Circular Queue as a backend. */

#define NXT_PORT_QUEUE_SIZE      NXT_NNCQ_SIZE
#define NXT_PORT_QUEUE_MSG_SIZE  31


typedef struct {
    uint8_t   size;
    uint8_t   data[NXT_PORT_QUEUE_MSG_SIZE];
} nxt_port_queue_item_t;


typedef struct {
    nxt_nncq_atomic_t      nitems;
    nxt_nncq_t             free_items;
    nxt_nncq_t             queue;
    nxt_port_queue_item_t  items[NXT_PORT_QUEUE_SIZE];
} nxt_port_queue_t;


nxt_inline void
nxt_port_queue_init(nxt_port_queue_t volatile *q)
{
    nxt_nncq_atomic_t  i;

    nxt_nncq_init(&q->free_items);
    nxt_nncq_init(&q->queue);

    for (i = 0; i < NXT_PORT_QUEUE_SIZE; i++) {
        nxt_nncq_enqueue(&q->free_items, i);
    }

    q->nitems = 0;
}


nxt_inline nxt_int_t
nxt_port_queue_send(nxt_port_queue_t volatile *q, const void *p, uint8_t size,
    int *notify)
{
    nxt_nncq_atomic_t      i;
    nxt_port_queue_item_t  *qi;

    i = nxt_nncq_dequeue(&q->free_items);
    if (i == nxt_nncq_empty(&q->free_items)) {
        *notify = 0;
        return NXT_AGAIN;
    }

    qi = (nxt_port_queue_item_t *) &q->items[i];

    qi->size = size;
    nxt_memcpy(qi->data, p, size);

    nxt_nncq_enqueue(&q->queue, i);

    i = nxt_atomic_fetch_add(&q->nitems, 1);

    *notify = (i == 0);

    return NXT_OK;
}


nxt_inline ssize_t
nxt_port_queue_recv(nxt_port_queue_t volatile *q, void *p)
{
    ssize_t                res;
    nxt_nncq_atomic_t      i;
    nxt_port_queue_item_t  *qi;

    i = nxt_nncq_dequeue(&q->queue);
    if (i == nxt_nncq_empty(&q->queue)) {
        return -1;
    }

    qi = (nxt_port_queue_item_t *) &q->items[i];

    res = qi->size;
    nxt_memcpy(p, qi->data, qi->size);

    nxt_nncq_enqueue(&q->free_items, i);

    nxt_atomic_fetch_add(&q->nitems, -1);

    return res;
}


#endif /* _NXT_PORT_QUEUE_H_INCLUDED_ */