aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/unittest/test_buffer.c
blob: 584ce589012bc8b34619c4421535785fa85dc340 (plain)
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
/*
 * Copyright (c) 2019 Cisco and/or its affiliates.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <vlib/vlib.h>
#include <vlib/buffer_funcs.h>

#define TEST_I(_cond, _comment, _args...)                                     \
  ({                                                                          \
    int _evald = (0 == (_cond));                                              \
    if (_evald)                                                               \
      {                                                                       \
	fformat (stderr, "FAIL:%d: " _comment "\n", __LINE__, ##_args);       \
      }                                                                       \
    else                                                                      \
      {                                                                       \
	fformat (stderr, "PASS:%d: " _comment "\n", __LINE__, ##_args);       \
      }                                                                       \
    _evald;                                                                   \
  })

#define TEST(_cond, _comment, _args...)                                       \
  {                                                                           \
    if (TEST_I (_cond, _comment, ##_args))                                    \
      {                                                                       \
	goto err;                                                             \
      }                                                                       \
  }

typedef struct
{
  i16 current_data;
  u16 current_length;
  u8 ref_count;
} chained_buffer_template_t;

static int
build_chain (vlib_main_t *vm, const chained_buffer_template_t *tmpl, u32 n,
	     clib_random_buffer_t *randbuf, u8 **rand, vlib_buffer_t **b_,
	     u32 *bi_)
{
  vlib_buffer_t *bufs[2 * VLIB_BUFFER_LINEARIZE_MAX], **b = bufs;
  u32 bis[2 * VLIB_BUFFER_LINEARIZE_MAX + 1], *bi = bis;
  u32 n_alloc;

  if (rand)
    vec_reset_length (*rand);

  ASSERT (n <= ARRAY_LEN (bufs));
  n_alloc = vlib_buffer_alloc (vm, bi, n);
  if (n_alloc != n)
    {
      vlib_buffer_free (vm, bi, n_alloc);
      return 0;
    }

  vlib_get_buffers (vm, bis, bufs, n);

  while (n > 0)
    {
      b[0]->next_buffer = bi[1];
      b[0]->flags |= VLIB_BUFFER_NEXT_PRESENT;
      b[0]->current_data = tmpl->current_data;
      b[0]->current_length = tmpl->current_length;
      b[0]->ref_count = 0xff == tmpl->ref_count ? 1 : tmpl->ref_count;

      if (rand)
	{
	  const u16 len = b[0]->current_length;
	  if (len)
	    {
	      vec_add (*rand, clib_random_buffer_get_data (randbuf, len), len);
	      void *dst = vlib_buffer_get_current (b[0]);
	      const void *src =
		vec_elt_at_index (*rand, vec_len (*rand) - len);
	      clib_memcpy_fast (dst, src, len);
	    }
	}

      b++;
      bi++;
      tmpl++;
      n--;
    }

  b[-1]->flags &= ~VLIB_BUFFER_NEXT_PRESENT;

  *b_ = bufs[0];
  *bi_ = bis[0];
  return 1;
}

static int
check_chain (vlib_main_t *vm, vlib_buffer_t *b, const u8 *rand)
{
  int len_chain = vlib_buffer_length_in_chain (vm, b);
  int len;

  /* check for data corruption */
  if (clib_memcmp (vlib_buffer_get_current (b), vec_elt_at_index (rand, 0),
		   b->current_length))
    return 0;
  len = b->current_length;
  while (b->flags & VLIB_BUFFER_NEXT_PRESENT)
    {
      b = vlib_get_buffer (vm, b->next_buffer);
      if (clib_memcmp (vlib_buffer_get_current (b),
		       vec_elt_at_index (rand, len), b->current_length))
	return 0;
      len += b->current_length;
    }

  /* check for data truncation */
  if (len != vec_len (rand))
    return 0;

  /* check total length update is correct */
  if (len != len_chain)
    return 0;

  return 1;
}

static int
test_chain (vlib_main_t *vm, const chained_buffer_template_t *tmpl,
	    const u32 n, const int clone_off, clib_random_buffer_t *randbuf,
	    u8 **rand)
{
  vlib_buffer_t *b;
  u32 bi[2];
  int ret = 0;

  if (!build_chain (vm, tmpl, n, randbuf, rand, &b, bi))
    goto err0;

  if (clone_off)
    {
      if (2 != vlib_buffer_clone (vm, bi[0], bi, 2, clone_off))
	goto err1;
      b = vlib_get_buffer (vm, bi[0]);
    }

  if (!(ret = vlib_buffer_chain_linearize (vm, b)))
    goto err2;

  if (!check_chain (vm, b, *rand))
    {
      ret = 0;
      goto err2;
    }

err2:
  if (clone_off)
    vlib_buffer_free_one (vm, bi[1]);
err1:
  vlib_buffer_free_one (vm, bi[0]);
err0:
  return ret;
}

static int
linearize_test (vlib_main_t *vm)
{
  chained_buffer_template_t tmpl[VLIB_BUFFER_LINEARIZE_MAX];
  clib_random_buffer_t randbuf;
  u32 data_size = vlib_buffer_get_default_data_size (vm);
  u8 *rand = 0;
  int ret = 0;
  int i;

  clib_random_buffer_init (&randbuf, 0);

  clib_memset (tmpl, 0xff, sizeof (tmpl));
  for (i = 0; i < 2; i++)
    {
      tmpl[i].current_data = -14;
      tmpl[i].current_length = 14 + data_size;
    }
  TEST (2 == test_chain (vm, tmpl, 2, 0, &randbuf, &rand),
	"linearize chain with negative current data");

  clib_memset (tmpl, 0xff, sizeof (tmpl));
  tmpl[0].current_data = 12;
  tmpl[0].current_length = data_size - 12;
  tmpl[1].current_data = 0;
  tmpl[1].current_length = 0;
  TEST (1 == test_chain (vm, tmpl, 2, 0, &randbuf, &rand),
	"linearize chain with empty next");

  clib_memset (tmpl, 0xff, sizeof (tmpl));
  tmpl[0].current_data = 0;
  tmpl[0].current_length = data_size - 17;
  tmpl[1].current_data = -5;
  tmpl[1].current_length = 3;
  tmpl[2].current_data = 17;
  tmpl[2].current_length = 9;
  tmpl[3].current_data = 3;
  tmpl[3].current_length = 5;
  TEST (1 == test_chain (vm, tmpl, 4, 0, &randbuf, &rand),
	"linearize chain into a single buffer");

  clib_memset (tmpl, 0xff, sizeof (tmpl));
  tmpl[0].current_data = 0;
  tmpl[0].current_length = data_size - 2;
  tmpl[1].current_data = -VLIB_BUFFER_PRE_DATA_SIZE;
  tmpl[1].current_length = 20;
  tmpl[2].current_data = data_size - 10;
  tmpl[2].current_length = 10;
  tmpl[3].current_data = 0;
  tmpl[3].current_length = data_size;
  TEST (2 == test_chain (vm, tmpl, 4, data_size - 1, &randbuf, &rand),
	"linearize cloned chain");

  clib_memset (tmpl, 0xff, sizeof (tmpl));
  for (i = 0; i < 100; i++)
    {
      u8 *r = clib_random_buffer_get_data (&randbuf, 1);
      int n = clib_max (r[0] % ARRAY_LEN (tmpl), 1);
      int j;
      for (j = 0; j < n; j++)
	{
	  r = clib_random_buffer_get_data (&randbuf, 3);
	  i16 current_data = (i16) r[0] - VLIB_BUFFER_PRE_DATA_SIZE;
	  u16 current_length = *(u16 *) (r + 1) % (data_size - current_data);
	  tmpl[j].current_data = current_data;
	  tmpl[j].current_length = current_length;
	}
      r = clib_random_buffer_get_data (&randbuf, 1);
      TEST (
	test_chain (vm, tmpl, n, r[0] > 250 ? r[0] % 128 : 0, &randbuf, &rand),
	"linearize random chain %d", i);
    }

  ret = 1;
err:
  clib_random_buffer_free (&randbuf);
  vec_free (rand);
  return ret;
}

static clib_error_t *
test_linearize_fn (vlib_main_t * vm, unformat_input_t * input,
		   vlib_cli_command_t * cmd)
{

  if (!linearize_test (vm))
    {
      return clib_error_return (0, "linearize test failed");
    }

  return 0;
}

/* *INDENT-OFF* */
VLIB_CLI_COMMAND (test_linearize_command, static) =
{
  .path = "test chained-buffer-linearization",
  .short_help = "test chained-buffer-linearization",
  .function = test_linearize_fn,
};
/* *INDENT-ON* */

static clib_error_t *
test_linearize_speed_fn (vlib_main_t *vm, unformat_input_t *input,
			 vlib_cli_command_t *cmd)
{
  /* typical 9000-bytes TCP jumbo frames */
  const chained_buffer_template_t tmpl[5] = { { 14, 2034, 1 },
					      { 0, 2048, 1 },
					      { 0, 2048, 1 },
					      { 0, 2048, 1 },
					      { 0, 808, 1 } };
  int i, j;

  for (i = 0; i < 10; i++)
    {
      u64 tot = 0;
      for (j = 0; j < 100000; j++)
	{
	  vlib_buffer_t *b;
	  u32 bi;

	  if (!build_chain (vm, tmpl, 5, 0, 0, &b, &bi))
	    return clib_error_create ("build_chain() failed");

	  CLIB_COMPILER_BARRIER ();
	  u64 start = clib_cpu_time_now ();
	  CLIB_COMPILER_BARRIER ();

	  vlib_buffer_chain_linearize (vm, b);

	  CLIB_COMPILER_BARRIER ();
	  tot += clib_cpu_time_now () - start;
	  CLIB_COMPILER_BARRIER ();

	  vlib_buffer_free_one (vm, bi);
	}
      vlib_cli_output (vm, "%.03f ticks/call", (f64) tot / j);
    }

  return 0;
}

VLIB_CLI_COMMAND (test_linearize_speed_command, static) = {
  .path = "test chained-buffer-linearization speed",
  .short_help = "test chained-buffer-linearization speed",
  .function = test_linearize_speed_fn,
};

/*
 * fd.io coding-style-patch-verification: ON
 *
 * Local Variables:
 * eval: (c-set-style "gnu")
 * End:
 */
/span> break; case 'l': number = va_arg (*va, long); o.n_bits = BITS (long); break; case 'w': number = va_arg (*va, word); o.n_bits = BITS (uword); break; default: number = va_arg (*va, int); o.n_bits = BITS (int); break; } s = format_integer (s, number, &o); } break; case 's': case 'S': { char *cstring = va_arg (*va, char *); uword len; if (!cstring) { cstring = "(nil)"; len = 5; } else if (fi.width[1] != 0) len = clib_min (strlen (cstring), fi.width[1]); else len = strlen (cstring); /* %S => format string as C identifier (replace _ with space). */ if (c == 'S') { for (i = 0; i < len; i++) vec_add1 (s, cstring[i] == '_' ? ' ' : cstring[i]); } else vec_add (s, cstring, len); } break; case 'v': { u8 *v = va_arg (*va, u8 *); uword len; if (fi.width[1] != 0) len = clib_min (vec_len (v), fi.width[1]); else len = vec_len (v); vec_add (s, v, len); } break; case 'f': case 'g': case 'e': /* Floating point. */ ASSERT (fi.how_long == 0 || fi.how_long == 'l'); s = format_float (s, va_arg (*va, double), fi.width[1], c); break; case 'U': /* User defined function. */ { typedef u8 *(user_func_t) (u8 * s, va_list * args); user_func_t *u = va_arg (*va, user_func_t *); s = (*u) (s, va); } break; } s = justify (s, &fi, s_initial_len); } done: *_s = s; return f; } u8 * va_format (u8 * s, const char *fmt, va_list * va) { const u8 *f = (u8 *) fmt, *g; u8 c; g = f; while (1) { c = *f; if (!c) break; if (c == '%') { if (f > g) vec_add (s, g, f - g); f = g = do_percent (&s, f, va); } else { f++; } } if (f > g) vec_add (s, g, f - g); return s; } u8 * format (u8 * s, const char *fmt, ...) { va_list va; va_start (va, fmt); s = va_format (s, fmt, &va); va_end (va); return s; } word va_fformat (FILE * f, char *fmt, va_list * va) { word ret; u8 *s; s = va_format (0, fmt, va); #ifdef CLIB_UNIX if (f) { ret = fwrite (s, vec_len (s), 1, f); } else #endif /* CLIB_UNIX */ { ret = 0; os_puts (s, vec_len (s), /* is_error */ 0); } vec_free (s); return ret; } word fformat (FILE * f, char *fmt, ...) { va_list va; word ret; va_start (va, fmt); ret = va_fformat (f, fmt, &va); va_end (va); return (ret); } #ifdef CLIB_UNIX void fformat_append_cr (FILE * ofp, const char *fmt, ...) { va_list va; va_start (va, fmt); (void) va_fformat (ofp, (char *) fmt, &va); va_end (va); fformat (ofp, "\n"); } word fdformat (int fd, char *fmt, ...) { word ret; u8 *s; va_list va; va_start (va, fmt); s = va_format (0, fmt, &va); va_end (va); ret = write (fd, s, vec_len (s)); vec_free (s); return ret; } #endif /* Format integral type. */ static u8 * format_integer (u8 * s, u64 number, format_integer_options_t * options) { u64 q; u32 r; u8 digit_buffer[128]; u8 *d = digit_buffer + sizeof (digit_buffer); word c, base; if (options->is_signed && (i64) number < 0) { number = -number; vec_add1 (s, '-'); } if (options->n_bits < BITS (number)) number &= ((u64) 1 << options->n_bits) - 1; base = options->base; while (1) { q = number / base; r = number % base; if (r < 10 + 26 + 26) { if (r < 10) c = '0' + r; else if (r < 10 + 26) c = 'a' + (r - 10); else c = 'A' + (r - 10 - 26); if (options->uppercase_digits && base <= 10 + 26 && c >= 'a' && c <= 'z') c += 'A' - 'a'; *--d = c; } else /* will never happen, warning be gone */ { *--d = '?'; } if (q == 0) break; number = q; } vec_add (s, d, digit_buffer + sizeof (digit_buffer) - d); return s; } /* Floating point formatting. */ /* Deconstruct IEEE 64 bit number into sign exponent and fraction. */ #define f64_down(f,sign,expon,fraction) \ do { \ union { u64 u; f64 f; } _f64_down_tmp; \ _f64_down_tmp.f = (f); \ (sign) = (_f64_down_tmp.u >> 63); \ (expon) = ((_f64_down_tmp.u >> 52) & 0x7ff) - 1023; \ (fraction) = ((_f64_down_tmp.u << 12) >> 12) | ((u64) 1 << 52); \ } while (0) /* Construct IEEE 64 bit number. */ static f64 f64_up (uword sign, word expon, u64 fraction) { union { u64 u; f64 f; } tmp; tmp.u = (u64) ((sign) != 0) << 63; expon += 1023; if (expon > 1023) expon = 1023; if (expon < 0) expon = 0; tmp.u |= (u64) expon << 52; tmp.u |= fraction & (((u64) 1 << 52) - 1); return tmp.f; } /* Returns approximate precision of number given its exponent. */ static f64 f64_precision (int base2_expon) { static int n_bits = 0; if (!n_bits) { /* Compute number of significant bits in floating point representation. */ f64 one = 0; f64 small = 1; while (one != 1) { small *= .5; n_bits++; one = 1 + small; } } return f64_up (0, base2_expon - n_bits, 0); } /* Return x 10^n */ static f64 times_power_of_ten (f64 x, int n) { if (n >= 0) { static f64 t[8] = { 1e+0, 1e+1, 1e+2, 1e+3, 1e+4, 1e+5, 1e+6, 1e+7, }; while (n >= 8) { x *= 1e+8; n -= 8; } return x * t[n]; } else { static f64 t[8] = { 1e-0, 1e-1, 1e-2, 1e-3, 1e-4, 1e-5, 1e-6, 1e-7, }; while (n <= -8) { x *= 1e-8; n += 8; } return x * t[-n]; } } /* Write x = y * 10^expon with 1 < y < 10. */ static f64 normalize (f64 x, word * expon_return, f64 * prec_return) { word expon2, expon10; CLIB_UNUSED (u64 fraction); CLIB_UNUSED (word sign); f64 prec; f64_down (x, sign, expon2, fraction); expon10 = .5 + expon2 * .301029995663981195213738894724493 /* Log (2) / Log (10) */ ; prec = f64_precision (expon2); x = times_power_of_ten (x, -expon10); prec = times_power_of_ten (prec, -expon10); while (x < 1) { x *= 10; prec *= 10; expon10--; } while (x > 10) { x *= .1; prec *= .1; expon10++; } if (x + prec >= 10) { x = 1; expon10++; } *expon_return = expon10; *prec_return = prec; return x; } static u8 * add_some_zeros (u8 * s, uword n_zeros) { while (n_zeros > 0) { vec_add1 (s, '0'); n_zeros--; } return s; } /* Format a floating point number with the given number of fractional digits (e.g. 1.2345 with 2 fraction digits yields "1.23") and output style. */ static u8 * format_float (u8 * s, f64 x, uword n_fraction_digits, uword output_style) { f64 prec; word sign, expon, n_fraction_done, added_decimal_point; /* Position of decimal point relative to where we are. */ word decimal_point; /* Default number of digits to print when its not specified. */ if (n_fraction_digits == ~0) n_fraction_digits = 7; n_fraction_done = 0; decimal_point = 0; added_decimal_point = 0; sign = expon = 0; /* Special case: zero. */ if (x == 0) { do_zero: vec_add1 (s, '0'); goto done; } if (x < 0) { x = -x; sign = 1; } /* Check for not-a-number. */ if (isnan (x)) return format (s, "%cNaN", sign ? '-' : '+'); /* Check for infinity. */ if (isinf (x)) return format (s, "%cinfinity", sign ? '-' : '+'); x = normalize (x, &expon, &prec); /* Not enough digits to print anything: so just print 0 */ if ((word) - expon > (word) n_fraction_digits && (output_style == 'f' || (output_style == 'g'))) goto do_zero; if (sign) vec_add1 (s, '-'); if (output_style == 'f' || (output_style == 'g' && expon > -10 && expon < 10)) { if (expon < 0) { /* Add decimal point and leading zeros. */ vec_add1 (s, '.'); n_fraction_done = clib_min (-(expon + 1), n_fraction_digits); s = add_some_zeros (s, n_fraction_done); decimal_point = -n_fraction_done; added_decimal_point = 1; } else decimal_point = expon + 1; } else { /* Exponential output style. */ decimal_point = 1; output_style = 'e'; } while (1) { uword digit; /* Number is smaller than precision: call it zero. */ if (x < prec) break; digit = x; x -= digit; if (x + prec >= 1) { digit++; x -= 1; } /* Round last printed digit. */ if (decimal_point <= 0 && n_fraction_done + 1 == n_fraction_digits && digit < 9) digit += x >= .5; vec_add1 (s, '0' + digit); /* Move rightwards towards/away from decimal point. */ decimal_point--; n_fraction_done += decimal_point < 0; if (decimal_point <= 0 && n_fraction_done >= n_fraction_digits) break; if (decimal_point == 0 && x != 0) { vec_add1 (s, '.'); added_decimal_point = 1; } x *= 10; prec *= 10; } done: if (decimal_point > 0) { s = add_some_zeros (s, decimal_point); decimal_point = 0; } if (n_fraction_done < n_fraction_digits) { if (!added_decimal_point) vec_add1 (s, '.'); s = add_some_zeros (s, n_fraction_digits - n_fraction_done); } if (output_style == 'e') s = format (s, "e%wd", expon); return s; } /* * fd.io coding-style-patch-verification: ON * * Local Variables: * eval: (c-set-style "gnu") * End: */