Support atomic printks
[akaros.git] / kern / include / ros / ring_buffer.h
1 /******************************************************************************
2  * ring.h
3  *
4  * Shared producer-consumer ring macros.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to
8  * deal in the Software without restriction, including without limitation the
9  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10  * sell copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22  * DEALINGS IN THE SOFTWARE.
23  *
24  * Tim Deegan and Andrew Warfield November 2004.
25  */
26
27 #pragma once
28 #include <string.h>
29 #include <ros/arch/membar.h>
30
31 #define xen_mb()  mb()
32 #define xen_rmb() rmb()
33 #define xen_wmb() wmb()
34
35 /* Helpers for generic power-of-2 ring buffers */
36 #define __ring_nr_empty(sz, prod, cons) ((sz) - ((prod) - (cons)))
37 #define __ring_empty(prod, cons) ((prod) == (cons))
38 #define __ring_nr_full(prod, cons) ((prod) - (cons))
39 #define __ring_full(sz, prod, cons) (__ring_nr_empty((sz), (prod), (cons)) == 0)
40
41 typedef unsigned int RING_IDX;
42
43 /* Round a 32-bit unsigned constant down to the nearest power of two. */
44 #define __RD2(_x)  (((_x) & 0x00000002UL) ? 0x2                  : ((_x) & 0x1))
45 #define __RD4(_x)  (((_x) & 0x0000000cUL) ? __RD2((_x)>>2)<<2    : __RD2(_x))
46 #define __RD8(_x)  (((_x) & 0x000000f0UL) ? __RD4((_x)>>4)<<4    : __RD4(_x))
47 #define __RD16(_x) (((_x) & 0x0000ff00UL) ? __RD8((_x)>>8)<<8    : __RD8(_x))
48 #define __RD32(_x) (((_x) & 0xffff0000UL) ? __RD16((_x)>>16)<<16 : __RD16(_x))
49
50 /*
51  * Calculate size of a shared ring, given the total available space for the
52  * ring and indexes (_sz), and the name tag of the request/response structure.
53  * A ring contains as many entries as will fit, rounded down to the nearest
54  * power of two (so we can mask with (size-1) to loop around).
55  */
56 #define __CONST_RING_SIZE(_s, _sz) \
57     (__RD32(((_sz) - offsetof(struct _s##_sring, ring)) / \
58             sizeof(((struct _s##_sring *)0)->ring[0])))
59 /*
60  * The same for passing in an actual pointer instead of a name tag.
61  */
62 #define __RING_SIZE(_s, _sz) \
63     (__RD32(((_sz) - (long)(_s)->ring + (long)(_s)) / sizeof((_s)->ring[0])))
64
65 /*
66  * Macros to make the correct C datatypes for a new kind of ring.
67  *
68  * To make a new ring datatype, you need to have two message structures,
69  * let's say request_t, and response_t already defined.
70  *
71  * In a header where you want the ring datatype declared, you then do:
72  *
73  *     DEFINE_RING_TYPES(mytag, request_t, response_t);
74  *
75  * These expand out to give you a set of types, as you can see below.
76  * The most important of these are:
77  *
78  *     mytag_sring_t      - The shared ring.
79  *     mytag_front_ring_t - The 'front' half of the ring.
80  *     mytag_back_ring_t  - The 'back' half of the ring.
81  *
82  * To initialize a ring in your code you need to know the location and size
83  * of the shared memory area (PAGE_SIZE, for instance). To initialise
84  * the front half:
85  *
86  *     mytag_front_ring_t front_ring;
87  *     SHARED_RING_INIT((mytag_sring_t *)shared_page);
88  *     FRONT_RING_INIT(&front_ring, (mytag_sring_t *)shared_page, PAGE_SIZE);
89  *
90  * Initializing the back follows similarly (note that only the front
91  * initializes the shared ring):
92  *
93  *     mytag_back_ring_t back_ring;
94  *     BACK_RING_INIT(&back_ring, (mytag_sring_t *)shared_page, PAGE_SIZE);
95  */
96
97 #define DEFINE_RING_TYPES(__name, __req_t, __rsp_t)                     \
98                                                                         \
99 /* Shared ring entry */                                                 \
100 union __name##_sring_entry {                                            \
101     __req_t req;                                                        \
102     __rsp_t rsp;                                                        \
103 };                                                                      \
104                                                                         \
105 /* Shared ring page */                                                  \
106 struct __name##_sring {                                                 \
107     RING_IDX req_prod, req_event;                                       \
108     RING_IDX rsp_prod, rsp_event;                                       \
109     union {                                                             \
110         struct {                                                        \
111             uint8_t smartpoll_active;                                   \
112         } netif;                                                        \
113         struct {                                                        \
114             uint8_t msg;                                                \
115         } tapif_user;                                                   \
116         uint8_t pvt_pad[4];                                             \
117     } priv;                                                             \
118     uint8_t __pad[44];                                                  \
119     union __name##_sring_entry ring[1]; /* variable-length */           \
120 };                                                                      \
121                                                                         \
122 /* "Front" end's private variables */                                   \
123 struct __name##_front_ring {                                            \
124     RING_IDX req_prod_pvt;                                              \
125     RING_IDX rsp_cons;                                                  \
126     unsigned int nr_ents;                                               \
127     struct __name##_sring *sring;                                       \
128 };                                                                      \
129                                                                         \
130 /* "Back" end's private variables */                                    \
131 struct __name##_back_ring {                                             \
132     RING_IDX rsp_prod_pvt;                                              \
133     RING_IDX req_cons;                                                  \
134     unsigned int nr_ents;                                               \
135     struct __name##_sring *sring;                                       \
136 };                                                                      \
137                                                                         \
138 /* Syntactic sugar */                                                   \
139 typedef struct __name##_sring __name##_sring_t;                         \
140 typedef struct __name##_front_ring __name##_front_ring_t;               \
141 typedef struct __name##_back_ring __name##_back_ring_t
142
143 /*
144  * Macros for manipulating rings.
145  *
146  * FRONT_RING_whatever works on the "front end" of a ring: here
147  * requests are pushed on to the ring and responses taken off it.
148  *
149  * BACK_RING_whatever works on the "back end" of a ring: here
150  * requests are taken off the ring and responses put on.
151  *
152  * N.B. these macros do NO INTERLOCKS OR FLOW CONTROL.
153  * This is OK in 1-for-1 request-response situations where the
154  * requestor (front end) never has more than RING_SIZE()-1
155  * outstanding requests.
156  */
157
158 /* Initialising empty rings */
159 #define SHARED_RING_INIT(_s) do {                                       \
160     (_s)->req_prod  = (_s)->rsp_prod  = 0;                              \
161     (_s)->req_event = (_s)->rsp_event = 1;                              \
162     (void)memset((_s)->priv.pvt_pad, 0, sizeof((_s)->priv.pvt_pad));    \
163     (void)memset((_s)->__pad, 0, sizeof((_s)->__pad));                  \
164 } while(0)
165
166 #define FRONT_RING_INIT(_r, _s, __size) do {                            \
167     (_r)->req_prod_pvt = 0;                                             \
168     (_r)->rsp_cons = 0;                                                 \
169     (_r)->nr_ents = __RING_SIZE(_s, __size);                            \
170     (_r)->sring = (_s);                                                 \
171 } while (0)
172
173 #define BACK_RING_INIT(_r, _s, __size) do {                             \
174     (_r)->rsp_prod_pvt = 0;                                             \
175     (_r)->req_cons = 0;                                                 \
176     (_r)->nr_ents = __RING_SIZE(_s, __size);                            \
177     (_r)->sring = (_s);                                                 \
178 } while (0)
179
180 /* Initialize to existing shared indexes -- for recovery */
181 #define FRONT_RING_ATTACH(_r, _s, __size) do {                          \
182     (_r)->sring = (_s);                                                 \
183     (_r)->req_prod_pvt = (_s)->req_prod;                                \
184     (_r)->rsp_cons = (_s)->rsp_prod;                                    \
185     (_r)->nr_ents = __RING_SIZE(_s, __size);                            \
186 } while (0)
187
188 #define BACK_RING_ATTACH(_r, _s, __size) do {                           \
189     (_r)->sring = (_s);                                                 \
190     (_r)->rsp_prod_pvt = (_s)->rsp_prod;                                \
191     (_r)->req_cons = (_s)->req_prod;                                    \
192     (_r)->nr_ents = __RING_SIZE(_s, __size);                            \
193 } while (0)
194
195 /* How big is this ring? */
196 #define RING_SIZE(_r)                                                   \
197     ((_r)->nr_ents)
198
199 /* Number of free requests (for use on front side only). */
200 #define RING_FREE_REQUESTS(_r)                                          \
201     (RING_SIZE(_r) - ((_r)->req_prod_pvt - (_r)->rsp_cons))
202
203 /* Test if there is an empty slot available on the front ring.
204  * (This is only meaningful from the front. )
205  */
206 #define RING_FULL(_r)                                                   \
207     (RING_FREE_REQUESTS(_r) == 0)
208
209 /* Test if there are outstanding messages to be processed on a ring. */
210 #define RING_HAS_UNCONSUMED_RESPONSES(_r)                               \
211     ((_r)->sring->rsp_prod - (_r)->rsp_cons)
212
213 #ifdef __GNUC__
214 #define RING_HAS_UNCONSUMED_REQUESTS(_r) ({                             \
215     unsigned int req = (_r)->sring->req_prod - (_r)->req_cons;          \
216     unsigned int rsp = RING_SIZE(_r) -                                  \
217         ((_r)->req_cons - (_r)->rsp_prod_pvt);                          \
218     req < rsp ? req : rsp;                                              \
219 })
220 #else
221 /* Same as above, but without the nice GCC ({ ... }) syntax. */
222 #define RING_HAS_UNCONSUMED_REQUESTS(_r)                                \
223     ((((_r)->sring->req_prod - (_r)->req_cons) <                        \
224       (RING_SIZE(_r) - ((_r)->req_cons - (_r)->rsp_prod_pvt))) ?        \
225      ((_r)->sring->req_prod - (_r)->req_cons) :                         \
226      (RING_SIZE(_r) - ((_r)->req_cons - (_r)->rsp_prod_pvt)))
227 #endif
228
229 /* Direct access to individual ring elements, by index. */
230 #define RING_GET_REQUEST(_r, _idx)                                      \
231     (&((_r)->sring->ring[((_idx) & (RING_SIZE(_r) - 1))].req))
232
233 #define RING_GET_RESPONSE(_r, _idx)                                     \
234     (&((_r)->sring->ring[((_idx) & (RING_SIZE(_r) - 1))].rsp))
235
236 /* Loop termination condition: Would the specified index overflow the ring? */
237 #define RING_REQUEST_CONS_OVERFLOW(_r, _cons)                           \
238     (((_cons) - (_r)->rsp_prod_pvt) >= RING_SIZE(_r))
239
240 #define RING_PUSH_REQUESTS(_r) do {                                     \
241     xen_wmb(); /* back sees requests /before/ updated producer index */ \
242     (_r)->sring->req_prod = (_r)->req_prod_pvt;                         \
243 } while (0)
244
245 #define RING_PUSH_RESPONSES(_r) do {                                    \
246     xen_wmb(); /* front sees resps /before/ updated producer index */   \
247     (_r)->sring->rsp_prod = (_r)->rsp_prod_pvt;                         \
248 } while (0)
249
250 /*
251  * Notification hold-off (req_event and rsp_event):
252  *
253  * When queueing requests or responses on a shared ring, it may not always be
254  * necessary to notify the remote end. For example, if requests are in flight
255  * in a backend, the front may be able to queue further requests without
256  * notifying the back (if the back checks for new requests when it queues
257  * responses).
258  *
259  * When enqueuing requests or responses:
260  *
261  *  Use RING_PUSH_{REQUESTS,RESPONSES}_AND_CHECK_NOTIFY(). The second argument
262  *  is a boolean return value. True indicates that the receiver requires an
263  *  asynchronous notification.
264  *
265  * After dequeuing requests or responses (before sleeping the connection):
266  *
267  *  Use RING_FINAL_CHECK_FOR_REQUESTS() or RING_FINAL_CHECK_FOR_RESPONSES().
268  *  The second argument is a boolean return value. True indicates that there
269  *  are pending messages on the ring (i.e., the connection should not be put
270  *  to sleep).
271  *
272  *  These macros will set the req_event/rsp_event field to trigger a
273  *  notification on the very next message that is enqueued. If you want to
274  *  create batches of work (i.e., only receive a notification after several
275  *  messages have been enqueued) then you will need to create a customised
276  *  version of the FINAL_CHECK macro in your own code, which sets the event
277  *  field appropriately.
278  */
279
280 #define RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(_r, _notify) do {           \
281     RING_IDX __old = (_r)->sring->req_prod;                             \
282     RING_IDX __new = (_r)->req_prod_pvt;                                \
283     xen_wmb(); /* back sees requests /before/ updated producer index */ \
284     (_r)->sring->req_prod = __new;                                      \
285     xen_mb(); /* back sees new requests /before/ we check req_event */  \
286     (_notify) = ((RING_IDX)(__new - (_r)->sring->req_event) <           \
287                  (RING_IDX)(__new - __old));                            \
288 } while (0)
289
290 #define RING_PUSH_RESPONSES_AND_CHECK_NOTIFY(_r, _notify) do {          \
291     RING_IDX __old = (_r)->sring->rsp_prod;                             \
292     RING_IDX __new = (_r)->rsp_prod_pvt;                                \
293     xen_wmb(); /* front sees resps /before/ updated producer index */   \
294     (_r)->sring->rsp_prod = __new;                                      \
295     xen_mb(); /* front sees new resps /before/ we check rsp_event */    \
296     (_notify) = ((RING_IDX)(__new - (_r)->sring->rsp_event) <           \
297                  (RING_IDX)(__new - __old));                            \
298 } while (0)
299
300 #define RING_FINAL_CHECK_FOR_REQUESTS(_r, _work_to_do) do {             \
301     (_work_to_do) = RING_HAS_UNCONSUMED_REQUESTS(_r);                   \
302     if (_work_to_do) break;                                             \
303     (_r)->sring->req_event = (_r)->req_cons + 1;                        \
304     xen_mb();                                                           \
305     (_work_to_do) = RING_HAS_UNCONSUMED_REQUESTS(_r);                   \
306 } while (0)
307
308 #define RING_FINAL_CHECK_FOR_RESPONSES(_r, _work_to_do) do {            \
309     (_work_to_do) = RING_HAS_UNCONSUMED_RESPONSES(_r);                  \
310     if (_work_to_do) break;                                             \
311     (_r)->sring->rsp_event = (_r)->rsp_cons + 1;                        \
312     xen_mb();                                                           \
313     (_work_to_do) = RING_HAS_UNCONSUMED_RESPONSES(_r);                  \
314 } while (0)
315
316 /*
317  * Local variables:
318  * mode: C
319  * c-set-style: "BSD"
320  * c-basic-offset: 4
321  * tab-width: 4
322  * indent-tabs-mode: nil
323  * End:
324  */