Thread safe internal buffer manager
[vpp.git] / src / vlib / buffer.h
1 /*
2  * Copyright (c) 2015 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 /*
16  * buffer.h: VLIB buffers
17  *
18  * Copyright (c) 2008 Eliot Dresselhaus
19  *
20  * Permission is hereby granted, free of charge, to any person obtaining
21  * a copy of this software and associated documentation files (the
22  * "Software"), to deal in the Software without restriction, including
23  * without limitation the rights to use, copy, modify, merge, publish,
24  * distribute, sublicense, and/or sell copies of the Software, and to
25  * permit persons to whom the Software is furnished to do so, subject to
26  * the following conditions:
27  *
28  * The above copyright notice and this permission notice shall be
29  * included in all copies or substantial portions of the Software.
30  *
31  *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
32  *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
33  *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
34  *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
35  *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
36  *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
37  *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
38  */
39
40 #ifndef included_vlib_buffer_h
41 #define included_vlib_buffer_h
42
43 #include <vppinfra/types.h>
44 #include <vppinfra/cache.h>
45 #include <vppinfra/serialize.h>
46 #include <vppinfra/vector.h>
47 #include <vppinfra/lock.h>
48 #include <vlib/error.h>         /* for vlib_error_t */
49
50 #include <vlib/config.h>        /* for __PRE_DATA_SIZE */
51 #define VLIB_BUFFER_DATA_SIZE           (2048)
52 #define VLIB_BUFFER_PRE_DATA_SIZE       __PRE_DATA_SIZE
53
54 /** \file
55     vlib buffer structure definition and a few select
56     access methods. This structure and the buffer allocation
57     mechanism should perhaps live in vnet, but it would take a lot
58     of typing to make it so.
59 */
60
61 /* VLIB buffer representation. */
62 typedef struct
63 {
64   CLIB_CACHE_LINE_ALIGN_MARK (cacheline0);
65   STRUCT_MARK (template_start);
66   /* Offset within data[] that we are currently processing.
67      If negative current header points into predata area. */
68   i16 current_data;  /**< signed offset in data[], pre_data[]
69                         that we are currently processing.
70                         If negative current header points into predata area.
71                      */
72   u16 current_length;  /**< Nbytes between current data and
73                           the end of this buffer.
74                        */
75   u32 flags; /**< buffer flags:
76                 <br> VLIB_BUFFER_FREE_LIST_INDEX_MASK: bits used to store free list index,
77                 <br> VLIB_BUFFER_IS_TRACED: trace this buffer.
78                 <br> VLIB_BUFFER_NEXT_PRESENT: this is a multi-chunk buffer.
79                 <br> VLIB_BUFFER_TOTAL_LENGTH_VALID: as it says
80                 <br> VLIB_BUFFER_REPL_FAIL: packet replication failure
81                 <br> VLIB_BUFFER_RECYCLE: as it says
82                 <br> VLIB_BUFFER_FLOW_REPORT: buffer is a flow report,
83                 <br> VLIB_BUFFER_EXT_HDR_VALID: buffer contains valid external buffer manager header,
84                 set to avoid adding it to a flow report
85                 <br> VLIB_BUFFER_FLAG_USER(n): user-defined bit N
86              */
87
88 /* any change to the following line requres update of
89  * vlib_buffer_get_free_list_index(...) and
90  * vlib_buffer_set_free_list_index(...) functions */
91 #define VLIB_BUFFER_FREE_LIST_INDEX_MASK ((1 << 5) - 1)
92
93 #define VLIB_BUFFER_IS_TRACED (1 << 5)
94 #define VLIB_BUFFER_LOG2_NEXT_PRESENT (6)
95 #define VLIB_BUFFER_NEXT_PRESENT (1 << VLIB_BUFFER_LOG2_NEXT_PRESENT)
96 #define VLIB_BUFFER_IS_RECYCLED (1 << 7)
97 #define VLIB_BUFFER_TOTAL_LENGTH_VALID (1 << 8)
98 #define VLIB_BUFFER_REPL_FAIL (1 << 9)
99 #define VLIB_BUFFER_RECYCLE (1 << 10)
100 #define VLIB_BUFFER_FLOW_REPORT (1 << 11)
101 #define VLIB_BUFFER_EXT_HDR_VALID (1 << 12)
102
103   /* User defined buffer flags. */
104 #define LOG2_VLIB_BUFFER_FLAG_USER(n) (32 - (n))
105 #define VLIB_BUFFER_FLAG_USER(n) (1 << LOG2_VLIB_BUFFER_FLAG_USER(n))
106
107     STRUCT_MARK (template_end);
108
109   u32 next_buffer;   /**< Next buffer for this linked-list of buffers.
110                         Only valid if VLIB_BUFFER_NEXT_PRESENT flag is set.
111                      */
112
113   vlib_error_t error;   /**< Error code for buffers to be enqueued
114                            to error handler.
115                         */
116   u32 current_config_index; /**< Used by feature subgraph arcs to
117                                visit enabled feature nodes
118                             */
119
120   u8 feature_arc_index; /**< Used to identify feature arcs by intermediate
121                            feature node
122                         */
123
124   u8 n_add_refs; /**< Number of additional references to this buffer. */
125
126   u8 dont_waste_me[2]; /**< Available space in the (precious)
127                           first 32 octets of buffer metadata
128                           Before allocating any of it, discussion required!
129                        */
130
131   u32 opaque[10]; /**< Opaque data used by sub-graphs for their own purposes.
132                     See .../vnet/vnet/buffer.h
133                  */
134     CLIB_CACHE_LINE_ALIGN_MARK (cacheline1);
135
136   u32 trace_index; /**< Specifies index into trace buffer
137                       if VLIB_PACKET_IS_TRACED flag is set.
138                    */
139   u32 recycle_count; /**< Used by L2 path recycle code */
140
141   u32 total_length_not_including_first_buffer;
142   /**< Only valid for first buffer in chain. Current length plus
143      total length given here give total number of bytes in buffer chain.
144   */
145   u32 opaque2[13];  /**< More opaque data, currently unused */
146
147   /***** end of second cache line */
148     CLIB_CACHE_LINE_ALIGN_MARK (cacheline2);
149   u8 pre_data[VLIB_BUFFER_PRE_DATA_SIZE];  /**< Space for inserting data
150                                                before buffer start.
151                                                Packet rewrite string will be
152                                                rewritten backwards and may extend
153                                                back before buffer->data[0].
154                                                Must come directly before packet data.
155                                             */
156
157   u8 data[0]; /**< Packet data. Hardware DMA here */
158 } vlib_buffer_t;                /* Must be a multiple of 64B. */
159
160 #define VLIB_BUFFER_HDR_SIZE  (sizeof(vlib_buffer_t) - VLIB_BUFFER_PRE_DATA_SIZE)
161
162 /** \brief Prefetch buffer metadata.
163     The first 64 bytes of buffer contains most header information
164
165     @param b - (vlib_buffer_t *) pointer to the buffer
166     @param type - LOAD, STORE. In most cases, STORE is the right answer
167 */
168
169 #define vlib_prefetch_buffer_header(b,type) CLIB_PREFETCH (b, 64, type)
170
171 always_inline vlib_buffer_t *
172 vlib_buffer_next_contiguous (vlib_buffer_t * b, u32 buffer_bytes)
173 {
174   return (void *) (b + 1) + buffer_bytes;
175 }
176
177 always_inline void
178 vlib_buffer_struct_is_sane (vlib_buffer_t * b)
179 {
180   ASSERT (sizeof (b[0]) % 64 == 0);
181
182   /* Rewrite data must be before and contiguous with packet data. */
183   ASSERT (b->pre_data + VLIB_BUFFER_PRE_DATA_SIZE == b->data);
184 }
185
186 /** \brief Get pointer to current data to process
187
188     @param b - (vlib_buffer_t *) pointer to the buffer
189     @return - (void *) (b->data + b->current_data)
190 */
191
192 always_inline void *
193 vlib_buffer_get_current (vlib_buffer_t * b)
194 {
195   /* Check bounds. */
196   ASSERT ((signed) b->current_data >= (signed) -VLIB_BUFFER_PRE_DATA_SIZE);
197   return b->data + b->current_data;
198 }
199
200 /** \brief Advance current data pointer by the supplied (signed!) amount
201
202     @param b - (vlib_buffer_t *) pointer to the buffer
203     @param l - (word) signed increment
204 */
205 always_inline void
206 vlib_buffer_advance (vlib_buffer_t * b, word l)
207 {
208   ASSERT (b->current_length >= l);
209   b->current_data += l;
210   b->current_length -= l;
211 }
212
213 /** \brief Check if there is enough space in buffer to advance
214
215     @param b - (vlib_buffer_t *) pointer to the buffer
216     @param l - (word) size to check
217     @return - 0 if there is less space than 'l' in buffer
218 */
219 always_inline u8
220 vlib_buffer_has_space (vlib_buffer_t * b, word l)
221 {
222   return b->current_length >= l;
223 }
224
225 /** \brief Reset current header & length to state they were in when
226     packet was received.
227
228     @param b - (vlib_buffer_t *) pointer to the buffer
229 */
230
231 always_inline void
232 vlib_buffer_reset (vlib_buffer_t * b)
233 {
234   b->current_length += clib_max (b->current_data, 0);
235   b->current_data = 0;
236 }
237
238 /** \brief Get pointer to buffer's opaque data array
239
240     @param b - (vlib_buffer_t *) pointer to the buffer
241     @return - (void *) b->opaque
242 */
243 always_inline void *
244 vlib_get_buffer_opaque (vlib_buffer_t * b)
245 {
246   return (void *) b->opaque;
247 }
248
249 /** \brief Get pointer to buffer's opaque2 data array
250
251     @param b - (vlib_buffer_t *) pointer to the buffer
252     @return - (void *) b->opaque2
253 */
254 always_inline void *
255 vlib_get_buffer_opaque2 (vlib_buffer_t * b)
256 {
257   return (void *) b->opaque2;
258 }
259
260 /** \brief Get pointer to the end of buffer's data
261  * @param b     pointer to the buffer
262  * @return      pointer to tail of packet's data
263  */
264 always_inline u8 *
265 vlib_buffer_get_tail (vlib_buffer_t * b)
266 {
267   return b->data + b->current_data + b->current_length;
268 }
269
270 /** \brief Append uninitialized data to buffer
271  * @param b     pointer to the buffer
272  * @param size  number of uninitialized bytes
273  * @return      pointer to beginning of uninitialized data
274  */
275 always_inline void *
276 vlib_buffer_put_uninit (vlib_buffer_t * b, u8 size)
277 {
278   void *p = vlib_buffer_get_tail (b);
279   /* XXX make sure there's enough space */
280   b->current_length += size;
281   return p;
282 }
283
284 /** \brief Prepend uninitialized data to buffer
285  * @param b     pointer to the buffer
286  * @param size  number of uninitialized bytes
287  * @return      pointer to beginning of uninitialized data
288  */
289 always_inline void *
290 vlib_buffer_push_uninit (vlib_buffer_t * b, u8 size)
291 {
292   ASSERT (b->current_data + VLIB_BUFFER_PRE_DATA_SIZE >= size);
293   b->current_data -= size;
294   b->current_length += size;
295
296   return vlib_buffer_get_current (b);
297 }
298
299 /** \brief Make head room, typically for packet headers
300  * @param b     pointer to the buffer
301  * @param size  number of head room bytes
302  * @return      pointer to start of buffer (current data)
303  */
304 always_inline void *
305 vlib_buffer_make_headroom (vlib_buffer_t * b, u8 size)
306 {
307   ASSERT (b->current_data + VLIB_BUFFER_PRE_DATA_SIZE >= size);
308   b->current_data += size;
309   return vlib_buffer_get_current (b);
310 }
311
312 /** \brief Retrieve bytes from buffer head
313  * @param b     pointer to the buffer
314  * @param size  number of bytes to pull
315  * @return      pointer to start of buffer (current data)
316  */
317 always_inline void *
318 vlib_buffer_pull (vlib_buffer_t * b, u8 size)
319 {
320   if (b->current_length + VLIB_BUFFER_PRE_DATA_SIZE < size)
321     return 0;
322
323   void *data = vlib_buffer_get_current (b);
324   vlib_buffer_advance (b, size);
325   return data;
326 }
327
328 /* Forward declaration. */
329 struct vlib_main_t;
330
331 typedef struct vlib_buffer_free_list_t
332 {
333   /* Template buffer used to initialize first 16 bytes of buffers
334      allocated on this free list. */
335   vlib_buffer_t buffer_init_template;
336
337   /* Our index into vlib_main_t's buffer_free_list_pool. */
338   u32 index;
339
340   /* Number of data bytes for buffers in this free list. */
341   u32 n_data_bytes;
342
343   /* Number of buffers to allocate when we need to allocate new buffers
344      from physmem heap. */
345   u32 min_n_buffers_each_physmem_alloc;
346
347   /* Total number of buffers allocated from this free list. */
348   u32 n_alloc;
349
350   /* Vector of free buffers.  Each element is a byte offset into I/O heap. */
351   u32 *buffers;
352
353   /* Memory chunks allocated for this free list
354      recorded here so they can be freed when free list
355      is deleted. */
356   void **buffer_memory_allocated;
357
358   /* Free list name. */
359   u8 *name;
360
361   /* Callback functions to initialize newly allocated buffers.
362      If null buffers are zeroed. */
363   void (*buffer_init_function) (struct vlib_main_t * vm,
364                                 struct vlib_buffer_free_list_t * fl,
365                                 u32 * buffers, u32 n_buffers);
366
367   /* Callback function to announce that buffers have been
368      added to the freelist */
369   void (*buffers_added_to_freelist_function)
370     (struct vlib_main_t * vm, struct vlib_buffer_free_list_t * fl);
371
372   uword buffer_init_function_opaque;
373 } __attribute__ ((aligned (16))) vlib_buffer_free_list_t;
374
375 typedef struct
376 {
377   u32 (*vlib_buffer_alloc_cb) (struct vlib_main_t * vm, u32 * buffers,
378                                u32 n_buffers);
379   u32 (*vlib_buffer_alloc_from_free_list_cb) (struct vlib_main_t * vm,
380                                               u32 * buffers, u32 n_buffers,
381                                               u32 free_list_index);
382   void (*vlib_buffer_free_cb) (struct vlib_main_t * vm, u32 * buffers,
383                                u32 n_buffers);
384   void (*vlib_buffer_free_no_next_cb) (struct vlib_main_t * vm, u32 * buffers,
385                                        u32 n_buffers);
386   void (*vlib_packet_template_init_cb) (struct vlib_main_t * vm, void *t,
387                                         void *packet_data,
388                                         uword n_packet_data_bytes,
389                                         uword
390                                         min_n_buffers_each_physmem_alloc,
391                                         u8 * name);
392   void (*vlib_buffer_delete_free_list_cb) (struct vlib_main_t * vm,
393                                            u32 free_list_index);
394 } vlib_buffer_callbacks_t;
395
396 extern vlib_buffer_callbacks_t *vlib_buffer_callbacks;
397
398 typedef struct
399 {
400   CLIB_CACHE_LINE_ALIGN_MARK (cacheline0);
401   /* Virtual memory address and size of buffer memory, used for calculating
402      buffer index */
403   uword buffer_mem_start;
404   uword buffer_mem_size;
405
406   /* Buffer free callback, for subversive activities */
407     u32 (*buffer_free_callback) (struct vlib_main_t * vm,
408                                  u32 * buffers,
409                                  u32 n_buffers, u32 follow_buffer_next);
410   /* Pool of buffer free lists.
411      Multiple free lists exist for packet generator which uses
412      separate free lists for each packet stream --- so as to avoid
413      initializing static data for each packet generated. */
414   vlib_buffer_free_list_t *buffer_free_list_pool;
415 #define VLIB_BUFFER_DEFAULT_FREE_LIST_INDEX (0)
416 #define VLIB_BUFFER_DEFAULT_FREE_LIST_BYTES VLIB_BUFFER_DATA_SIZE
417
418   /* Hash table mapping buffer size (rounded to next unit of
419      sizeof (vlib_buffer_t)) to free list index. */
420   uword *free_list_by_size;
421
422   /* Hash table mapping buffer index into number
423      0 => allocated but free, 1 => allocated and not-free.
424      If buffer index is not in hash table then this buffer
425      has never been allocated. */
426   uword *buffer_known_hash;
427   clib_spinlock_t buffer_known_hash_lockp;
428
429   /* List of free-lists needing Blue Light Special announcements */
430   vlib_buffer_free_list_t **announce_list;
431
432   /* Callbacks */
433   vlib_buffer_callbacks_t cb;
434   int callbacks_registered;
435 } vlib_buffer_main_t;
436
437 void vlib_buffer_add_mem_range (struct vlib_main_t *vm, uword start,
438                                 uword size);
439 void vlib_buffer_cb_init (struct vlib_main_t *vm);
440
441 typedef struct
442 {
443   struct vlib_main_t *vlib_main;
444
445   u32 first_buffer, last_buffer;
446
447   union
448   {
449     struct
450     {
451       /* Total accumulated bytes in chain starting with first_buffer. */
452       u32 n_total_data_bytes;
453
454       /* Max number of bytes to accumulate in chain starting with first_buffer.
455          As this limit is reached buffers are enqueued to next node. */
456       u32 max_n_data_bytes_per_chain;
457
458       /* Next node to enqueue buffers to relative to current process node. */
459       u32 next_index;
460
461       /* Free list to use to allocate new buffers. */
462       u32 free_list_index;
463     } tx;
464
465     struct
466     {
467       /* CLIB fifo of buffer indices waiting to be unserialized. */
468       u32 *buffer_fifo;
469
470       /* Event type used to signal that RX buffers have been added to fifo. */
471       uword ready_one_time_event;
472     } rx;
473   };
474 } vlib_serialize_buffer_main_t;
475
476 void serialize_open_vlib_buffer (serialize_main_t * m, struct vlib_main_t *vm,
477                                  vlib_serialize_buffer_main_t * sm);
478 void unserialize_open_vlib_buffer (serialize_main_t * m,
479                                    struct vlib_main_t *vm,
480                                    vlib_serialize_buffer_main_t * sm);
481
482 u32 serialize_close_vlib_buffer (serialize_main_t * m);
483 void unserialize_close_vlib_buffer (serialize_main_t * m);
484 void *vlib_set_buffer_free_callback (struct vlib_main_t *vm, void *fp);
485
486 always_inline u32
487 serialize_vlib_buffer_n_bytes (serialize_main_t * m)
488 {
489   serialize_stream_t *s = &m->stream;
490   vlib_serialize_buffer_main_t *sm
491     = uword_to_pointer (m->stream.data_function_opaque,
492                         vlib_serialize_buffer_main_t *);
493   return sm->tx.n_total_data_bytes + s->current_buffer_index +
494     vec_len (s->overflow_buffer);
495 }
496
497 /*
498  */
499
500 /** \brief Compile time buffer trajectory tracing option
501     Turn this on if you run into "bad monkey" contexts,
502     and you want to know exactly which nodes they've visited...
503     See vlib/main.c...
504 */
505 #define VLIB_BUFFER_TRACE_TRAJECTORY 0
506
507 #if VLIB_BUFFER_TRACE_TRAJECTORY > 0
508 #define VLIB_BUFFER_TRACE_TRAJECTORY_INIT(b) (b)->pre_data[0]=0
509 #else
510 #define VLIB_BUFFER_TRACE_TRAJECTORY_INIT(b)
511 #endif /* VLIB_BUFFER_TRACE_TRAJECTORY */
512
513 #endif /* included_vlib_buffer_h */
514
515 #define VLIB_BUFFER_REGISTER_CALLBACKS(x,...)                           \
516     __VA_ARGS__ vlib_buffer_callbacks_t __##x##_buffer_callbacks;       \
517 static void __vlib_add_buffer_callbacks_t_##x (void)                    \
518     __attribute__((__constructor__)) ;                                  \
519 static void __vlib_add_buffer_callbacks_t_##x (void)                    \
520 {                                                                       \
521     if (vlib_buffer_callbacks)                                          \
522       clib_panic ("vlib buffer callbacks already registered");          \
523     vlib_buffer_callbacks = &__##x##_buffer_callbacks;                  \
524 }                                                                       \
525 __VA_ARGS__ vlib_buffer_callbacks_t __##x##_buffer_callbacks
526
527 /*
528  * fd.io coding-style-patch-verification: ON
529  *
530  * Local Variables:
531  * eval: (c-set-style "gnu")
532  * End:
533  */