ofpbuf: Introduce access api for base, data and size.
[sliver-openvswitch.git] / lib / ofpbuf.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "ofpbuf.h"
19 #include <stdlib.h>
20 #include <string.h>
21 #include "dynamic-string.h"
22 #include "netdev-dpdk.h"
23 #include "util.h"
24
25 static void
26 ofpbuf_use__(struct ofpbuf *b, void *base, size_t allocated,
27              enum ofpbuf_source source)
28 {
29     ofpbuf_set_base(b, base);
30     ofpbuf_set_data(b, base);
31     ofpbuf_set_size(b, 0);
32
33     b->allocated = allocated;
34     b->source = source;
35     b->l2 = NULL;
36     b->l2_5_ofs = b->l3_ofs = b->l4_ofs = UINT16_MAX;
37     list_poison(&b->list_node);
38 }
39
40 /* Initializes 'b' as an empty ofpbuf that contains the 'allocated' bytes of
41  * memory starting at 'base'.  'base' should be the first byte of a region
42  * obtained from malloc().  It will be freed (with free()) if 'b' is resized or
43  * freed. */
44 void
45 ofpbuf_use(struct ofpbuf *b, void *base, size_t allocated)
46 {
47     ofpbuf_use__(b, base, allocated, OFPBUF_MALLOC);
48 }
49
50 /* Initializes 'b' as an empty ofpbuf that contains the 'allocated' bytes of
51  * memory starting at 'base'.  'base' should point to a buffer on the stack.
52  * (Nothing actually relies on 'base' being allocated on the stack.  It could
53  * be static or malloc()'d memory.  But stack space is the most common use
54  * case.)
55  *
56  * 'base' should be appropriately aligned.  Using an array of uint32_t or
57  * uint64_t for the buffer is a reasonable way to ensure appropriate alignment
58  * for 32- or 64-bit data.
59  *
60  * An ofpbuf operation that requires reallocating data will assert-fail if this
61  * function was used to initialize it.  Thus, one need not call ofpbuf_uninit()
62  * on an ofpbuf initialized by this function (though doing so is harmless),
63  * because it is guaranteed that 'b' does not own any heap-allocated memory. */
64 void
65 ofpbuf_use_stack(struct ofpbuf *b, void *base, size_t allocated)
66 {
67     ofpbuf_use__(b, base, allocated, OFPBUF_STACK);
68 }
69
70 /* Initializes 'b' as an empty ofpbuf that contains the 'allocated' bytes of
71  * memory starting at 'base'.  'base' should point to a buffer on the stack.
72  * (Nothing actually relies on 'base' being allocated on the stack.  It could
73  * be static or malloc()'d memory.  But stack space is the most common use
74  * case.)
75  *
76  * 'base' should be appropriately aligned.  Using an array of uint32_t or
77  * uint64_t for the buffer is a reasonable way to ensure appropriate alignment
78  * for 32- or 64-bit data.
79  *
80  * An ofpbuf operation that requires reallocating data will copy the provided
81  * buffer into a malloc()'d buffer.  Thus, it is wise to call ofpbuf_uninit()
82  * on an ofpbuf initialized by this function, so that if it expanded into the
83  * heap, that memory is freed. */
84 void
85 ofpbuf_use_stub(struct ofpbuf *b, void *base, size_t allocated)
86 {
87     ofpbuf_use__(b, base, allocated, OFPBUF_STUB);
88 }
89
90 /* Initializes 'b' as an ofpbuf whose data starts at 'data' and continues for
91  * 'size' bytes.  This is appropriate for an ofpbuf that will be used to
92  * inspect existing data, without moving it around or reallocating it, and
93  * generally without modifying it at all.
94  *
95  * An ofpbuf operation that requires reallocating data will assert-fail if this
96  * function was used to initialize it. */
97 void
98 ofpbuf_use_const(struct ofpbuf *b, const void *data, size_t size)
99 {
100     ofpbuf_use__(b, CONST_CAST(void *, data), size, OFPBUF_STACK);
101     ofpbuf_set_size(b, size);
102 }
103
104 /* Initializes 'b' as an empty ofpbuf with an initial capacity of 'size'
105  * bytes. */
106 void
107 ofpbuf_init(struct ofpbuf *b, size_t size)
108 {
109     ofpbuf_use(b, size ? xmalloc(size) : NULL, size);
110 }
111
112 /* Frees memory that 'b' points to. */
113 void
114 ofpbuf_uninit(struct ofpbuf *b)
115 {
116     if (b) {
117         if (b->source == OFPBUF_MALLOC) {
118             free(ofpbuf_base(b));
119         }
120         if (b->source == OFPBUF_DPDK) {
121             free_dpdk_buf(b);
122         }
123     }
124 }
125
126 /* Frees memory that 'b' points to and allocates a new ofpbuf */
127 void
128 ofpbuf_reinit(struct ofpbuf *b, size_t size)
129 {
130     ofpbuf_uninit(b);
131     ofpbuf_init(b, size);
132 }
133
134 /* Creates and returns a new ofpbuf with an initial capacity of 'size'
135  * bytes. */
136 struct ofpbuf *
137 ofpbuf_new(size_t size)
138 {
139     struct ofpbuf *b = xmalloc(sizeof *b);
140     ofpbuf_init(b, size);
141     return b;
142 }
143
144 /* Creates and returns a new ofpbuf with an initial capacity of 'size +
145  * headroom' bytes, reserving the first 'headroom' bytes as headroom. */
146 struct ofpbuf *
147 ofpbuf_new_with_headroom(size_t size, size_t headroom)
148 {
149     struct ofpbuf *b = ofpbuf_new(size + headroom);
150     ofpbuf_reserve(b, headroom);
151     return b;
152 }
153
154 /* Creates and returns a new ofpbuf that initially contains a copy of the
155  * 'ofpbuf_size(buffer)' bytes of data starting at 'buffer->data' with no headroom or
156  * tailroom. */
157 struct ofpbuf *
158 ofpbuf_clone(const struct ofpbuf *buffer)
159 {
160     return ofpbuf_clone_with_headroom(buffer, 0);
161 }
162
163 /* Creates and returns a new ofpbuf whose data are copied from 'buffer'.   The
164  * returned ofpbuf will additionally have 'headroom' bytes of headroom. */
165 struct ofpbuf *
166 ofpbuf_clone_with_headroom(const struct ofpbuf *buffer, size_t headroom)
167 {
168     struct ofpbuf *new_buffer;
169
170     new_buffer = ofpbuf_clone_data_with_headroom(ofpbuf_data(buffer),
171                                                  ofpbuf_size(buffer),
172                                                  headroom);
173     if (buffer->l2) {
174         uintptr_t data_delta = (char *)ofpbuf_data(new_buffer) - (char *)ofpbuf_data(buffer);
175
176         new_buffer->l2 = (char *) buffer->l2 + data_delta;
177     }
178     new_buffer->l2_5_ofs = buffer->l2_5_ofs;
179     new_buffer->l3_ofs = buffer->l3_ofs;
180     new_buffer->l4_ofs = buffer->l4_ofs;
181
182     return new_buffer;
183 }
184
185 /* Creates and returns a new ofpbuf that initially contains a copy of the
186  * 'size' bytes of data starting at 'data' with no headroom or tailroom. */
187 struct ofpbuf *
188 ofpbuf_clone_data(const void *data, size_t size)
189 {
190     return ofpbuf_clone_data_with_headroom(data, size, 0);
191 }
192
193 /* Creates and returns a new ofpbuf that initially contains 'headroom' bytes of
194  * headroom followed by a copy of the 'size' bytes of data starting at
195  * 'data'. */
196 struct ofpbuf *
197 ofpbuf_clone_data_with_headroom(const void *data, size_t size, size_t headroom)
198 {
199     struct ofpbuf *b = ofpbuf_new_with_headroom(size, headroom);
200     ofpbuf_put(b, data, size);
201     return b;
202 }
203
204 static void
205 ofpbuf_copy__(struct ofpbuf *b, uint8_t *new_base,
206               size_t new_headroom, size_t new_tailroom)
207 {
208     const uint8_t *old_base = ofpbuf_base(b);
209     size_t old_headroom = ofpbuf_headroom(b);
210     size_t old_tailroom = ofpbuf_tailroom(b);
211     size_t copy_headroom = MIN(old_headroom, new_headroom);
212     size_t copy_tailroom = MIN(old_tailroom, new_tailroom);
213
214     memcpy(&new_base[new_headroom - copy_headroom],
215            &old_base[old_headroom - copy_headroom],
216            copy_headroom + ofpbuf_size(b) + copy_tailroom);
217 }
218
219 /* Reallocates 'b' so that it has exactly 'new_headroom' and 'new_tailroom'
220  * bytes of headroom and tailroom, respectively. */
221 static void
222 ofpbuf_resize__(struct ofpbuf *b, size_t new_headroom, size_t new_tailroom)
223 {
224     void *new_base, *new_data;
225     size_t new_allocated;
226
227     new_allocated = new_headroom + ofpbuf_size(b) + new_tailroom;
228
229     switch (b->source) {
230     case OFPBUF_DPDK:
231         OVS_NOT_REACHED();
232
233     case OFPBUF_MALLOC:
234         if (new_headroom == ofpbuf_headroom(b)) {
235             new_base = xrealloc(ofpbuf_base(b), new_allocated);
236         } else {
237             new_base = xmalloc(new_allocated);
238             ofpbuf_copy__(b, new_base, new_headroom, new_tailroom);
239             free(ofpbuf_base(b));
240         }
241         break;
242
243     case OFPBUF_STACK:
244         OVS_NOT_REACHED();
245
246     case OFPBUF_STUB:
247         b->source = OFPBUF_MALLOC;
248         new_base = xmalloc(new_allocated);
249         ofpbuf_copy__(b, new_base, new_headroom, new_tailroom);
250         break;
251
252     default:
253         OVS_NOT_REACHED();
254     }
255
256     b->allocated = new_allocated;
257     ofpbuf_set_base(b, new_base);
258
259     new_data = (char *) new_base + new_headroom;
260     if (ofpbuf_data(b) != new_data) {
261         uintptr_t data_delta = (char *) new_data - (char *) ofpbuf_data(b);
262
263         ofpbuf_set_data(b, new_data);
264         if (b->l2) {
265             b->l2 = (char *) b->l2 + data_delta;
266         }
267     }
268 }
269
270 /* Ensures that 'b' has room for at least 'size' bytes at its tail end,
271  * reallocating and copying its data if necessary.  Its headroom, if any, is
272  * preserved. */
273 void
274 ofpbuf_prealloc_tailroom(struct ofpbuf *b, size_t size)
275 {
276     if (size > ofpbuf_tailroom(b)) {
277         ofpbuf_resize__(b, ofpbuf_headroom(b), MAX(size, 64));
278     }
279 }
280
281 /* Ensures that 'b' has room for at least 'size' bytes at its head,
282  * reallocating and copying its data if necessary.  Its tailroom, if any, is
283  * preserved. */
284 void
285 ofpbuf_prealloc_headroom(struct ofpbuf *b, size_t size)
286 {
287     if (size > ofpbuf_headroom(b)) {
288         ofpbuf_resize__(b, MAX(size, 64), ofpbuf_tailroom(b));
289     }
290 }
291
292 /* Trims the size of 'b' to fit its actual content, reducing its tailroom to
293  * 0.  Its headroom, if any, is preserved.
294  *
295  * Buffers not obtained from malloc() are not resized, since that wouldn't save
296  * any memory. */
297 void
298 ofpbuf_trim(struct ofpbuf *b)
299 {
300     ovs_assert(b->source != OFPBUF_DPDK);
301
302     if (b->source == OFPBUF_MALLOC
303         && (ofpbuf_headroom(b) || ofpbuf_tailroom(b))) {
304         ofpbuf_resize__(b, 0, 0);
305     }
306 }
307
308 /* If 'b' is shorter than 'length' bytes, pads its tail out with zeros to that
309  * length. */
310 void
311 ofpbuf_padto(struct ofpbuf *b, size_t length)
312 {
313     if (ofpbuf_size(b) < length) {
314         ofpbuf_put_zeros(b, length - ofpbuf_size(b));
315     }
316 }
317
318 /* Shifts all of the data within the allocated space in 'b' by 'delta' bytes.
319  * For example, a 'delta' of 1 would cause each byte of data to move one byte
320  * forward (from address 'p' to 'p+1'), and a 'delta' of -1 would cause each
321  * byte to move one byte backward (from 'p' to 'p-1'). */
322 void
323 ofpbuf_shift(struct ofpbuf *b, int delta)
324 {
325     ovs_assert(delta > 0 ? delta <= ofpbuf_tailroom(b)
326                : delta < 0 ? -delta <= ofpbuf_headroom(b)
327                : true);
328
329     if (delta != 0) {
330         char *dst = (char *) ofpbuf_data(b) + delta;
331         memmove(dst, ofpbuf_data(b), ofpbuf_size(b));
332         ofpbuf_set_data(b, dst);
333     }
334 }
335
336 /* Appends 'size' bytes of data to the tail end of 'b', reallocating and
337  * copying its data if necessary.  Returns a pointer to the first byte of the
338  * new data, which is left uninitialized. */
339 void *
340 ofpbuf_put_uninit(struct ofpbuf *b, size_t size)
341 {
342     void *p;
343     ofpbuf_prealloc_tailroom(b, size);
344     p = ofpbuf_tail(b);
345     ofpbuf_set_size(b, ofpbuf_size(b) + size);
346     return p;
347 }
348
349 /* Appends 'size' zeroed bytes to the tail end of 'b'.  Data in 'b' is
350  * reallocated and copied if necessary.  Returns a pointer to the first byte of
351  * the data's location in the ofpbuf. */
352 void *
353 ofpbuf_put_zeros(struct ofpbuf *b, size_t size)
354 {
355     void *dst = ofpbuf_put_uninit(b, size);
356     memset(dst, 0, size);
357     return dst;
358 }
359
360 /* Appends the 'size' bytes of data in 'p' to the tail end of 'b'.  Data in 'b'
361  * is reallocated and copied if necessary.  Returns a pointer to the first
362  * byte of the data's location in the ofpbuf. */
363 void *
364 ofpbuf_put(struct ofpbuf *b, const void *p, size_t size)
365 {
366     void *dst = ofpbuf_put_uninit(b, size);
367     memcpy(dst, p, size);
368     return dst;
369 }
370
371 /* Parses as many pairs of hex digits as possible (possibly separated by
372  * spaces) from the beginning of 's', appending bytes for their values to 'b'.
373  * Returns the first character of 's' that is not the first of a pair of hex
374  * digits.  If 'n' is nonnull, stores the number of bytes added to 'b' in
375  * '*n'. */
376 char *
377 ofpbuf_put_hex(struct ofpbuf *b, const char *s, size_t *n)
378 {
379     size_t initial_size = ofpbuf_size(b);
380     for (;;) {
381         uint8_t byte;
382         bool ok;
383
384         s += strspn(s, " \t\r\n");
385         byte = hexits_value(s, 2, &ok);
386         if (!ok) {
387             if (n) {
388                 *n = ofpbuf_size(b) - initial_size;
389             }
390             return CONST_CAST(char *, s);
391         }
392
393         ofpbuf_put(b, &byte, 1);
394         s += 2;
395     }
396 }
397
398 /* Reserves 'size' bytes of headroom so that they can be later allocated with
399  * ofpbuf_push_uninit() without reallocating the ofpbuf. */
400 void
401 ofpbuf_reserve(struct ofpbuf *b, size_t size)
402 {
403     ovs_assert(!ofpbuf_size(b));
404     ofpbuf_prealloc_tailroom(b, size);
405     ofpbuf_set_data(b, (char*)ofpbuf_data(b) + size);
406 }
407
408 /* Reserves 'size' bytes of headroom so that they can be later allocated with
409  * ofpbuf_push_uninit() without reallocating the ofpbuf. */
410 void
411 ofpbuf_reserve_with_tailroom(struct ofpbuf *b, size_t headroom,
412                              size_t tailroom)
413 {
414     ovs_assert(!ofpbuf_size(b));
415     ofpbuf_prealloc_tailroom(b, headroom + tailroom);
416     ofpbuf_set_data(b, (char*)ofpbuf_data(b) + headroom);
417 }
418
419 /* Prefixes 'size' bytes to the head end of 'b', reallocating and copying its
420  * data if necessary.  Returns a pointer to the first byte of the data's
421  * location in the ofpbuf.  The new data is left uninitialized. */
422 void *
423 ofpbuf_push_uninit(struct ofpbuf *b, size_t size)
424 {
425     ofpbuf_prealloc_headroom(b, size);
426     ofpbuf_set_data(b, (char*)ofpbuf_data(b) - size);
427     ofpbuf_set_size(b, ofpbuf_size(b) + size);
428     return ofpbuf_data(b);
429 }
430
431 /* Prefixes 'size' zeroed bytes to the head end of 'b', reallocating and
432  * copying its data if necessary.  Returns a pointer to the first byte of the
433  * data's location in the ofpbuf. */
434 void *
435 ofpbuf_push_zeros(struct ofpbuf *b, size_t size)
436 {
437     void *dst = ofpbuf_push_uninit(b, size);
438     memset(dst, 0, size);
439     return dst;
440 }
441
442 /* Copies the 'size' bytes starting at 'p' to the head end of 'b', reallocating
443  * and copying its data if necessary.  Returns a pointer to the first byte of
444  * the data's location in the ofpbuf. */
445 void *
446 ofpbuf_push(struct ofpbuf *b, const void *p, size_t size)
447 {
448     void *dst = ofpbuf_push_uninit(b, size);
449     memcpy(dst, p, size);
450     return dst;
451 }
452
453 /* Returns the data in 'b' as a block of malloc()'d memory and frees the buffer
454  * within 'b'.  (If 'b' itself was dynamically allocated, e.g. with
455  * ofpbuf_new(), then it should still be freed with, e.g., ofpbuf_delete().) */
456 void *
457 ofpbuf_steal_data(struct ofpbuf *b)
458 {
459     void *p;
460     ovs_assert(b->source != OFPBUF_DPDK);
461
462     if (b->source == OFPBUF_MALLOC && ofpbuf_data(b) == ofpbuf_base(b)) {
463         p = ofpbuf_data(b);
464     } else {
465         p = xmemdup(ofpbuf_data(b), ofpbuf_size(b));
466         if (b->source == OFPBUF_MALLOC) {
467             free(ofpbuf_base(b));
468         }
469     }
470     ofpbuf_set_base(b, NULL);
471     ofpbuf_set_data(b, NULL);
472     return p;
473 }
474
475 /* Returns a string that describes some of 'b''s metadata plus a hex dump of up
476  * to 'maxbytes' from the start of the buffer. */
477 char *
478 ofpbuf_to_string(const struct ofpbuf *b, size_t maxbytes)
479 {
480     struct ds s;
481
482     ds_init(&s);
483     ds_put_format(&s, "size=%"PRIu32", allocated=%"PRIu32", head=%"PRIuSIZE", tail=%"PRIuSIZE"\n",
484                   ofpbuf_size(b), b->allocated,
485                   ofpbuf_headroom(b), ofpbuf_tailroom(b));
486     ds_put_hex_dump(&s, ofpbuf_data(b), MIN(ofpbuf_size(b), maxbytes), 0, false);
487     return ds_cstr(&s);
488 }
489
490 /* Removes each of the "struct ofpbuf"s on 'list' from the list and frees
491  * them.  */
492 void
493 ofpbuf_list_delete(struct list *list)
494 {
495     struct ofpbuf *b, *next;
496
497     LIST_FOR_EACH_SAFE (b, next, list_node, list) {
498         list_remove(&b->list_node);
499         ofpbuf_delete(b);
500     }
501 }
502
503 static inline void
504 ofpbuf_adjust_layer_offset(uint16_t *offset, int increment)
505 {
506     if (*offset != UINT16_MAX) {
507         *offset += increment;
508     }
509 }
510
511 /* Adjust the size of the l2_5 portion of the ofpbuf, updating the l2
512  * pointer and the layer offsets.  The caller is responsible for
513  * modifying the contents. */
514 void *
515 ofpbuf_resize_l2_5(struct ofpbuf *b, int increment)
516 {
517     if (increment >= 0) {
518         ofpbuf_push_uninit(b, increment);
519     } else {
520         ofpbuf_pull(b, -increment);
521     }
522
523     b->l2 = ofpbuf_data(b);
524     /* Adjust layer offsets after l2_5. */
525     ofpbuf_adjust_layer_offset(&b->l3_ofs, increment);
526     ofpbuf_adjust_layer_offset(&b->l4_ofs, increment);
527
528     return b->l2;
529 }
530
531 /* Adjust the size of the l2 portion of the ofpbuf, updating the l2
532  * pointer and the layer offsets.  The caller is responsible for
533  * modifying the contents. */
534 void *
535 ofpbuf_resize_l2(struct ofpbuf *b, int increment)
536 {
537     ofpbuf_resize_l2_5(b, increment);
538     ofpbuf_adjust_layer_offset(&b->l2_5_ofs, increment);
539     return b->l2;
540 }