mempool: add function to iterate the memory chunks
[dpdk.git] / lib / librte_mempool / rte_mempool.c
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright(c) 2010-2014 Intel Corporation. All rights reserved.
5  *   Copyright(c) 2016 6WIND S.A.
6  *   All rights reserved.
7  *
8  *   Redistribution and use in source and binary forms, with or without
9  *   modification, are permitted provided that the following conditions
10  *   are met:
11  *
12  *     * Redistributions of source code must retain the above copyright
13  *       notice, this list of conditions and the following disclaimer.
14  *     * Redistributions in binary form must reproduce the above copyright
15  *       notice, this list of conditions and the following disclaimer in
16  *       the documentation and/or other materials provided with the
17  *       distribution.
18  *     * Neither the name of Intel Corporation nor the names of its
19  *       contributors may be used to endorse or promote products derived
20  *       from this software without specific prior written permission.
21  *
22  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
25  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
28  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
32  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  */
34
35 #include <stdio.h>
36 #include <string.h>
37 #include <stdint.h>
38 #include <stdarg.h>
39 #include <unistd.h>
40 #include <inttypes.h>
41 #include <errno.h>
42 #include <sys/queue.h>
43
44 #include <rte_common.h>
45 #include <rte_log.h>
46 #include <rte_debug.h>
47 #include <rte_memory.h>
48 #include <rte_memzone.h>
49 #include <rte_malloc.h>
50 #include <rte_atomic.h>
51 #include <rte_launch.h>
52 #include <rte_eal.h>
53 #include <rte_eal_memconfig.h>
54 #include <rte_per_lcore.h>
55 #include <rte_lcore.h>
56 #include <rte_branch_prediction.h>
57 #include <rte_ring.h>
58 #include <rte_errno.h>
59 #include <rte_string_fns.h>
60 #include <rte_spinlock.h>
61
62 #include "rte_mempool.h"
63
64 TAILQ_HEAD(rte_mempool_list, rte_tailq_entry);
65
66 static struct rte_tailq_elem rte_mempool_tailq = {
67         .name = "RTE_MEMPOOL",
68 };
69 EAL_REGISTER_TAILQ(rte_mempool_tailq)
70
71 #define CACHE_FLUSHTHRESH_MULTIPLIER 1.5
72 #define CALC_CACHE_FLUSHTHRESH(c)       \
73         ((typeof(c))((c) * CACHE_FLUSHTHRESH_MULTIPLIER))
74
75 /*
76  * return the greatest common divisor between a and b (fast algorithm)
77  *
78  */
79 static unsigned get_gcd(unsigned a, unsigned b)
80 {
81         unsigned c;
82
83         if (0 == a)
84                 return b;
85         if (0 == b)
86                 return a;
87
88         if (a < b) {
89                 c = a;
90                 a = b;
91                 b = c;
92         }
93
94         while (b != 0) {
95                 c = a % b;
96                 a = b;
97                 b = c;
98         }
99
100         return a;
101 }
102
103 /*
104  * Depending on memory configuration, objects addresses are spread
105  * between channels and ranks in RAM: the pool allocator will add
106  * padding between objects. This function return the new size of the
107  * object.
108  */
109 static unsigned optimize_object_size(unsigned obj_size)
110 {
111         unsigned nrank, nchan;
112         unsigned new_obj_size;
113
114         /* get number of channels */
115         nchan = rte_memory_get_nchannel();
116         if (nchan == 0)
117                 nchan = 4;
118
119         nrank = rte_memory_get_nrank();
120         if (nrank == 0)
121                 nrank = 1;
122
123         /* process new object size */
124         new_obj_size = (obj_size + RTE_MEMPOOL_ALIGN_MASK) / RTE_MEMPOOL_ALIGN;
125         while (get_gcd(new_obj_size, nrank * nchan) != 1)
126                 new_obj_size++;
127         return new_obj_size * RTE_MEMPOOL_ALIGN;
128 }
129
130 /**
131  * A mempool object iterator callback function.
132  */
133 typedef void (*rte_mempool_obj_iter_t)(void * /*obj_iter_arg*/,
134         void * /*obj_start*/,
135         void * /*obj_end*/,
136         uint32_t /*obj_index */,
137         phys_addr_t /*physaddr*/);
138
139 static void
140 mempool_add_elem(struct rte_mempool *mp, void *obj, phys_addr_t physaddr)
141 {
142         struct rte_mempool_objhdr *hdr;
143         struct rte_mempool_objtlr *tlr __rte_unused;
144
145         /* set mempool ptr in header */
146         hdr = RTE_PTR_SUB(obj, sizeof(*hdr));
147         hdr->mp = mp;
148         hdr->physaddr = physaddr;
149         STAILQ_INSERT_TAIL(&mp->elt_list, hdr, next);
150         mp->populated_size++;
151
152 #ifdef RTE_LIBRTE_MEMPOOL_DEBUG
153         hdr->cookie = RTE_MEMPOOL_HEADER_COOKIE2;
154         tlr = __mempool_get_trailer(obj);
155         tlr->cookie = RTE_MEMPOOL_TRAILER_COOKIE;
156 #endif
157
158         /* enqueue in ring */
159         rte_ring_sp_enqueue(mp->ring, obj);
160 }
161
162 /* Iterate through objects at the given address
163  *
164  * Given the pointer to the memory, and its topology in physical memory
165  * (the physical addresses table), iterate through the "elt_num" objects
166  * of size "elt_sz" aligned at "align". For each object in this memory
167  * chunk, invoke a callback. It returns the effective number of objects
168  * in this memory.
169  */
170 static uint32_t
171 rte_mempool_obj_mem_iter(void *vaddr, uint32_t elt_num, size_t total_elt_sz,
172         size_t align, const phys_addr_t paddr[], uint32_t pg_num,
173         uint32_t pg_shift, rte_mempool_obj_iter_t obj_iter, void *obj_iter_arg)
174 {
175         uint32_t i, j, k;
176         uint32_t pgn, pgf;
177         uintptr_t end, start, va;
178         uintptr_t pg_sz;
179         phys_addr_t physaddr;
180
181         pg_sz = (uintptr_t)1 << pg_shift;
182         va = (uintptr_t)vaddr;
183
184         i = 0;
185         j = 0;
186
187         while (i != elt_num && j != pg_num) {
188
189                 start = RTE_ALIGN_CEIL(va, align);
190                 end = start + total_elt_sz;
191
192                 /* index of the first page for the next element. */
193                 pgf = (end >> pg_shift) - (start >> pg_shift);
194
195                 /* index of the last page for the current element. */
196                 pgn = ((end - 1) >> pg_shift) - (start >> pg_shift);
197                 pgn += j;
198
199                 /* do we have enough space left for the element. */
200                 if (pgn >= pg_num)
201                         break;
202
203                 for (k = j;
204                                 k != pgn &&
205                                 paddr[k] + pg_sz == paddr[k + 1];
206                                 k++)
207                         ;
208
209                 /*
210                  * if next pgn chunks of memory physically continuous,
211                  * use it to create next element.
212                  * otherwise, just skip that chunk unused.
213                  */
214                 if (k == pgn) {
215                         physaddr = paddr[k] + (start & (pg_sz - 1));
216                         if (obj_iter != NULL)
217                                 obj_iter(obj_iter_arg, (void *)start,
218                                         (void *)end, i, physaddr);
219                         va = end;
220                         j += pgf;
221                         i++;
222                 } else {
223                         va = RTE_ALIGN_CEIL((va + 1), pg_sz);
224                         j++;
225                 }
226         }
227
228         return i;
229 }
230
231 /* call obj_cb() for each mempool element */
232 uint32_t
233 rte_mempool_obj_iter(struct rte_mempool *mp,
234         rte_mempool_obj_cb_t *obj_cb, void *obj_cb_arg)
235 {
236         struct rte_mempool_objhdr *hdr;
237         void *obj;
238         unsigned n = 0;
239
240         STAILQ_FOREACH(hdr, &mp->elt_list, next) {
241                 obj = (char *)hdr + sizeof(*hdr);
242                 obj_cb(mp, obj_cb_arg, obj, n);
243                 n++;
244         }
245
246         return n;
247 }
248
249 /* call mem_cb() for each mempool memory chunk */
250 uint32_t
251 rte_mempool_mem_iter(struct rte_mempool *mp,
252         rte_mempool_mem_cb_t *mem_cb, void *mem_cb_arg)
253 {
254         struct rte_mempool_memhdr *hdr;
255         unsigned n = 0;
256
257         STAILQ_FOREACH(hdr, &mp->mem_list, next) {
258                 mem_cb(mp, mem_cb_arg, hdr, n);
259                 n++;
260         }
261
262         return n;
263 }
264
265 /* get the header, trailer and total size of a mempool element. */
266 uint32_t
267 rte_mempool_calc_obj_size(uint32_t elt_size, uint32_t flags,
268         struct rte_mempool_objsz *sz)
269 {
270         struct rte_mempool_objsz lsz;
271
272         sz = (sz != NULL) ? sz : &lsz;
273
274         sz->header_size = sizeof(struct rte_mempool_objhdr);
275         if ((flags & MEMPOOL_F_NO_CACHE_ALIGN) == 0)
276                 sz->header_size = RTE_ALIGN_CEIL(sz->header_size,
277                         RTE_MEMPOOL_ALIGN);
278
279         sz->trailer_size = sizeof(struct rte_mempool_objtlr);
280
281         /* element size is 8 bytes-aligned at least */
282         sz->elt_size = RTE_ALIGN_CEIL(elt_size, sizeof(uint64_t));
283
284         /* expand trailer to next cache line */
285         if ((flags & MEMPOOL_F_NO_CACHE_ALIGN) == 0) {
286                 sz->total_size = sz->header_size + sz->elt_size +
287                         sz->trailer_size;
288                 sz->trailer_size += ((RTE_MEMPOOL_ALIGN -
289                                   (sz->total_size & RTE_MEMPOOL_ALIGN_MASK)) &
290                                  RTE_MEMPOOL_ALIGN_MASK);
291         }
292
293         /*
294          * increase trailer to add padding between objects in order to
295          * spread them across memory channels/ranks
296          */
297         if ((flags & MEMPOOL_F_NO_SPREAD) == 0) {
298                 unsigned new_size;
299                 new_size = optimize_object_size(sz->header_size + sz->elt_size +
300                         sz->trailer_size);
301                 sz->trailer_size = new_size - sz->header_size - sz->elt_size;
302         }
303
304         if (! rte_eal_has_hugepages()) {
305                 /*
306                  * compute trailer size so that pool elements fit exactly in
307                  * a standard page
308                  */
309                 int page_size = getpagesize();
310                 int new_size = page_size - sz->header_size - sz->elt_size;
311                 if (new_size < 0 || (unsigned int)new_size < sz->trailer_size) {
312                         printf("When hugepages are disabled, pool objects "
313                                "can't exceed PAGE_SIZE: %d + %d + %d > %d\n",
314                                sz->header_size, sz->elt_size, sz->trailer_size,
315                                page_size);
316                         return 0;
317                 }
318                 sz->trailer_size = new_size;
319         }
320
321         /* this is the size of an object, including header and trailer */
322         sz->total_size = sz->header_size + sz->elt_size + sz->trailer_size;
323
324         return sz->total_size;
325 }
326
327
328 /*
329  * Calculate maximum amount of memory required to store given number of objects.
330  */
331 size_t
332 rte_mempool_xmem_size(uint32_t elt_num, size_t total_elt_sz, uint32_t pg_shift)
333 {
334         size_t n, pg_num, pg_sz, sz;
335
336         pg_sz = (size_t)1 << pg_shift;
337
338         if ((n = pg_sz / total_elt_sz) > 0) {
339                 pg_num = (elt_num + n - 1) / n;
340                 sz = pg_num << pg_shift;
341         } else {
342                 sz = RTE_ALIGN_CEIL(total_elt_sz, pg_sz) * elt_num;
343         }
344
345         return sz;
346 }
347
348 /* Callback used by rte_mempool_xmem_usage(): it sets the opaque
349  * argument to the end of the object.
350  */
351 static void
352 mempool_lelem_iter(void *arg, __rte_unused void *start, void *end,
353         __rte_unused uint32_t idx, __rte_unused phys_addr_t physaddr)
354 {
355         *(uintptr_t *)arg = (uintptr_t)end;
356 }
357
358 /*
359  * Calculate how much memory would be actually required with the
360  * given memory footprint to store required number of elements.
361  */
362 ssize_t
363 rte_mempool_xmem_usage(void *vaddr, uint32_t elt_num, size_t total_elt_sz,
364         const phys_addr_t paddr[], uint32_t pg_num, uint32_t pg_shift)
365 {
366         uint32_t n;
367         uintptr_t va, uv;
368         size_t pg_sz, usz;
369
370         pg_sz = (size_t)1 << pg_shift;
371         va = (uintptr_t)vaddr;
372         uv = va;
373
374         if ((n = rte_mempool_obj_mem_iter(vaddr, elt_num, total_elt_sz, 1,
375                         paddr, pg_num, pg_shift, mempool_lelem_iter,
376                         &uv)) != elt_num) {
377                 return -(ssize_t)n;
378         }
379
380         uv = RTE_ALIGN_CEIL(uv, pg_sz);
381         usz = uv - va;
382         return usz;
383 }
384
385 #ifndef RTE_LIBRTE_XEN_DOM0
386 /* stub if DOM0 support not configured */
387 struct rte_mempool *
388 rte_dom0_mempool_create(const char *name __rte_unused,
389                         unsigned n __rte_unused,
390                         unsigned elt_size __rte_unused,
391                         unsigned cache_size __rte_unused,
392                         unsigned private_data_size __rte_unused,
393                         rte_mempool_ctor_t *mp_init __rte_unused,
394                         void *mp_init_arg __rte_unused,
395                         rte_mempool_obj_ctor_t *obj_init __rte_unused,
396                         void *obj_init_arg __rte_unused,
397                         int socket_id __rte_unused,
398                         unsigned flags __rte_unused)
399 {
400         rte_errno = EINVAL;
401         return NULL;
402 }
403 #endif
404
405 /* create the mempool */
406 struct rte_mempool *
407 rte_mempool_create(const char *name, unsigned n, unsigned elt_size,
408                    unsigned cache_size, unsigned private_data_size,
409                    rte_mempool_ctor_t *mp_init, void *mp_init_arg,
410                    rte_mempool_obj_ctor_t *obj_init, void *obj_init_arg,
411                    int socket_id, unsigned flags)
412 {
413         if (rte_xen_dom0_supported())
414                 return rte_dom0_mempool_create(name, n, elt_size,
415                                                cache_size, private_data_size,
416                                                mp_init, mp_init_arg,
417                                                obj_init, obj_init_arg,
418                                                socket_id, flags);
419         else
420                 return rte_mempool_xmem_create(name, n, elt_size,
421                                                cache_size, private_data_size,
422                                                mp_init, mp_init_arg,
423                                                obj_init, obj_init_arg,
424                                                socket_id, flags,
425                                                NULL, NULL, MEMPOOL_PG_NUM_DEFAULT,
426                                                MEMPOOL_PG_SHIFT_MAX);
427 }
428
429 /* create the internal ring */
430 static int
431 rte_mempool_ring_create(struct rte_mempool *mp)
432 {
433         int rg_flags = 0;
434         char rg_name[RTE_RING_NAMESIZE];
435         struct rte_ring *r;
436
437         snprintf(rg_name, sizeof(rg_name), RTE_MEMPOOL_MZ_FORMAT, mp->name);
438
439         /* ring flags */
440         if (mp->flags & MEMPOOL_F_SP_PUT)
441                 rg_flags |= RING_F_SP_ENQ;
442         if (mp->flags & MEMPOOL_F_SC_GET)
443                 rg_flags |= RING_F_SC_DEQ;
444
445         /* Allocate the ring that will be used to store objects.
446          * Ring functions will return appropriate errors if we are
447          * running as a secondary process etc., so no checks made
448          * in this function for that condition.
449          */
450         r = rte_ring_create(rg_name, rte_align32pow2(mp->size + 1),
451                 mp->socket_id, rg_flags);
452         if (r == NULL)
453                 return -rte_errno;
454
455         mp->ring = r;
456         return 0;
457 }
458
459 /* Free memory chunks used by a mempool. Objects must be in pool */
460 static void
461 rte_mempool_free_memchunks(struct rte_mempool *mp)
462 {
463         struct rte_mempool_memhdr *memhdr;
464         void *elt;
465
466         while (!STAILQ_EMPTY(&mp->elt_list)) {
467                 rte_ring_sc_dequeue(mp->ring, &elt);
468                 (void)elt;
469                 STAILQ_REMOVE_HEAD(&mp->elt_list, next);
470                 mp->populated_size--;
471         }
472
473         while (!STAILQ_EMPTY(&mp->mem_list)) {
474                 memhdr = STAILQ_FIRST(&mp->mem_list);
475                 STAILQ_REMOVE_HEAD(&mp->mem_list, next);
476                 rte_free(memhdr);
477                 mp->nb_mem_chunks--;
478         }
479 }
480
481 /* Add objects in the pool, using a physically contiguous memory
482  * zone. Return the number of objects added, or a negative value
483  * on error.
484  */
485 static int
486 rte_mempool_populate_phys(struct rte_mempool *mp, char *vaddr,
487         phys_addr_t paddr, size_t len)
488 {
489         unsigned total_elt_sz;
490         unsigned i = 0;
491         size_t off;
492         struct rte_mempool_memhdr *memhdr;
493
494         /* mempool is already populated */
495         if (mp->populated_size >= mp->size)
496                 return -ENOSPC;
497
498         total_elt_sz = mp->header_size + mp->elt_size + mp->trailer_size;
499
500         memhdr = rte_zmalloc("MEMPOOL_MEMHDR", sizeof(*memhdr), 0);
501         if (memhdr == NULL)
502                 return -ENOMEM;
503
504         memhdr->mp = mp;
505         memhdr->addr = vaddr;
506         memhdr->phys_addr = paddr;
507         memhdr->len = len;
508
509         if (mp->flags & MEMPOOL_F_NO_CACHE_ALIGN)
510                 off = RTE_PTR_ALIGN_CEIL(vaddr, 8) - vaddr;
511         else
512                 off = RTE_PTR_ALIGN_CEIL(vaddr, RTE_CACHE_LINE_SIZE) - vaddr;
513
514         while (off + total_elt_sz <= len && mp->populated_size < mp->size) {
515                 off += mp->header_size;
516                 mempool_add_elem(mp, (char *)vaddr + off, paddr + off);
517                 off += mp->elt_size + mp->trailer_size;
518                 i++;
519         }
520
521         /* not enough room to store one object */
522         if (i == 0)
523                 return -EINVAL;
524
525         STAILQ_INSERT_TAIL(&mp->mem_list, memhdr, next);
526         mp->nb_mem_chunks++;
527         return i;
528 }
529
530 /* Add objects in the pool, using a table of physical pages. Return the
531  * number of objects added, or a negative value on error.
532  */
533 static int
534 rte_mempool_populate_phys_tab(struct rte_mempool *mp, char *vaddr,
535         const phys_addr_t paddr[], uint32_t pg_num, uint32_t pg_shift)
536 {
537         uint32_t i, n;
538         int ret, cnt = 0;
539         size_t pg_sz = (size_t)1 << pg_shift;
540
541         /* mempool must not be populated */
542         if (mp->nb_mem_chunks != 0)
543                 return -EEXIST;
544
545         for (i = 0; i < pg_num && mp->populated_size < mp->size; i += n) {
546
547                 /* populate with the largest group of contiguous pages */
548                 for (n = 1; (i + n) < pg_num &&
549                              paddr[i] + pg_sz == paddr[i+n]; n++)
550                         ;
551
552                 ret = rte_mempool_populate_phys(mp, vaddr + i * pg_sz,
553                         paddr[i], n * pg_sz);
554                 if (ret < 0) {
555                         rte_mempool_free_memchunks(mp);
556                         return ret;
557                 }
558                 cnt += ret;
559         }
560         return cnt;
561 }
562
563 /*
564  * Create the mempool over already allocated chunk of memory.
565  * That external memory buffer can consists of physically disjoint pages.
566  * Setting vaddr to NULL, makes mempool to fallback to original behaviour
567  * and allocate space for mempool and it's elements as one big chunk of
568  * physically continuos memory.
569  * */
570 struct rte_mempool *
571 rte_mempool_xmem_create(const char *name, unsigned n, unsigned elt_size,
572                 unsigned cache_size, unsigned private_data_size,
573                 rte_mempool_ctor_t *mp_init, void *mp_init_arg,
574                 rte_mempool_obj_cb_t *obj_init, void *obj_init_arg,
575                 int socket_id, unsigned flags, void *vaddr,
576                 const phys_addr_t paddr[], uint32_t pg_num, uint32_t pg_shift)
577 {
578         char mz_name[RTE_MEMZONE_NAMESIZE];
579         struct rte_mempool_list *mempool_list;
580         struct rte_mempool *mp = NULL;
581         struct rte_tailq_entry *te = NULL;
582         const struct rte_memzone *mz;
583         size_t mempool_size;
584         int mz_flags = RTE_MEMZONE_1GB|RTE_MEMZONE_SIZE_HINT_ONLY;
585         void *obj;
586         struct rte_mempool_objsz objsz;
587         void *startaddr;
588         int page_size = getpagesize();
589         int ret;
590
591         /* compilation-time checks */
592         RTE_BUILD_BUG_ON((sizeof(struct rte_mempool) &
593                           RTE_CACHE_LINE_MASK) != 0);
594         RTE_BUILD_BUG_ON((sizeof(struct rte_mempool_cache) &
595                           RTE_CACHE_LINE_MASK) != 0);
596 #ifdef RTE_LIBRTE_MEMPOOL_DEBUG
597         RTE_BUILD_BUG_ON((sizeof(struct rte_mempool_debug_stats) &
598                           RTE_CACHE_LINE_MASK) != 0);
599         RTE_BUILD_BUG_ON((offsetof(struct rte_mempool, stats) &
600                           RTE_CACHE_LINE_MASK) != 0);
601 #endif
602
603         mempool_list = RTE_TAILQ_CAST(rte_mempool_tailq.head, rte_mempool_list);
604
605         /* asked cache too big */
606         if (cache_size > RTE_MEMPOOL_CACHE_MAX_SIZE ||
607             CALC_CACHE_FLUSHTHRESH(cache_size) > n) {
608                 rte_errno = EINVAL;
609                 return NULL;
610         }
611
612         /* check that we have both VA and PA */
613         if (vaddr != NULL && paddr == NULL) {
614                 rte_errno = EINVAL;
615                 return NULL;
616         }
617
618         /* Check that pg_num and pg_shift parameters are valid. */
619         if (pg_num == 0 || pg_shift > MEMPOOL_PG_SHIFT_MAX) {
620                 rte_errno = EINVAL;
621                 return NULL;
622         }
623
624         /* "no cache align" imply "no spread" */
625         if (flags & MEMPOOL_F_NO_CACHE_ALIGN)
626                 flags |= MEMPOOL_F_NO_SPREAD;
627
628         /* calculate mempool object sizes. */
629         if (!rte_mempool_calc_obj_size(elt_size, flags, &objsz)) {
630                 rte_errno = EINVAL;
631                 return NULL;
632         }
633
634         rte_rwlock_write_lock(RTE_EAL_MEMPOOL_RWLOCK);
635
636         /*
637          * reserve a memory zone for this mempool: private data is
638          * cache-aligned
639          */
640         private_data_size = (private_data_size +
641                              RTE_MEMPOOL_ALIGN_MASK) & (~RTE_MEMPOOL_ALIGN_MASK);
642
643         if (! rte_eal_has_hugepages()) {
644                 /*
645                  * expand private data size to a whole page, so that the
646                  * first pool element will start on a new standard page
647                  */
648                 int head = sizeof(struct rte_mempool);
649                 int new_size = (private_data_size + head) % page_size;
650                 if (new_size)
651                         private_data_size += page_size - new_size;
652         }
653
654         /* try to allocate tailq entry */
655         te = rte_zmalloc("MEMPOOL_TAILQ_ENTRY", sizeof(*te), 0);
656         if (te == NULL) {
657                 RTE_LOG(ERR, MEMPOOL, "Cannot allocate tailq entry!\n");
658                 goto exit_unlock;
659         }
660
661         /*
662          * If user provided an external memory buffer, then use it to
663          * store mempool objects. Otherwise reserve a memzone that is large
664          * enough to hold mempool header and metadata plus mempool objects.
665          */
666         mempool_size = MEMPOOL_HEADER_SIZE(mp, cache_size);
667         mempool_size += private_data_size;
668         mempool_size = RTE_ALIGN_CEIL(mempool_size, RTE_MEMPOOL_ALIGN);
669         if (vaddr == NULL)
670                 mempool_size += (size_t)objsz.total_size * n;
671
672         if (! rte_eal_has_hugepages()) {
673                 /*
674                  * we want the memory pool to start on a page boundary,
675                  * because pool elements crossing page boundaries would
676                  * result in discontiguous physical addresses
677                  */
678                 mempool_size += page_size;
679         }
680
681         snprintf(mz_name, sizeof(mz_name), RTE_MEMPOOL_MZ_FORMAT, name);
682
683         mz = rte_memzone_reserve(mz_name, mempool_size, socket_id, mz_flags);
684         if (mz == NULL)
685                 goto exit_unlock;
686
687         if (rte_eal_has_hugepages()) {
688                 startaddr = (void*)mz->addr;
689         } else {
690                 /* align memory pool start address on a page boundary */
691                 unsigned long addr = (unsigned long)mz->addr;
692                 if (addr & (page_size - 1)) {
693                         addr += page_size;
694                         addr &= ~(page_size - 1);
695                 }
696                 startaddr = (void*)addr;
697         }
698
699         /* init the mempool structure */
700         mp = startaddr;
701         memset(mp, 0, sizeof(*mp));
702         snprintf(mp->name, sizeof(mp->name), "%s", name);
703         mp->phys_addr = mz->phys_addr;
704         mp->socket_id = socket_id;
705         mp->size = n;
706         mp->flags = flags;
707         mp->elt_size = objsz.elt_size;
708         mp->header_size = objsz.header_size;
709         mp->trailer_size = objsz.trailer_size;
710         mp->cache_size = cache_size;
711         mp->cache_flushthresh = CALC_CACHE_FLUSHTHRESH(cache_size);
712         mp->private_data_size = private_data_size;
713         STAILQ_INIT(&mp->elt_list);
714         STAILQ_INIT(&mp->mem_list);
715
716         if (rte_mempool_ring_create(mp) < 0)
717                 goto exit_unlock;
718
719         /*
720          * local_cache pointer is set even if cache_size is zero.
721          * The local_cache points to just past the elt_pa[] array.
722          */
723         mp->local_cache = (struct rte_mempool_cache *)
724                 RTE_PTR_ADD(mp, MEMPOOL_HEADER_SIZE(mp, 0));
725
726         /* call the initializer */
727         if (mp_init)
728                 mp_init(mp, mp_init_arg);
729
730         /* mempool elements allocated together with mempool */
731         if (vaddr == NULL) {
732                 /* calculate address of the first elt for continuous mempool. */
733                 obj = (char *)mp + MEMPOOL_HEADER_SIZE(mp, cache_size) +
734                         private_data_size;
735                 obj = RTE_PTR_ALIGN_CEIL(obj, RTE_MEMPOOL_ALIGN);
736
737                 ret = rte_mempool_populate_phys(mp, obj,
738                         mp->phys_addr + ((char *)obj - (char *)mp),
739                         objsz.total_size * n);
740                 if (ret != (int)mp->size)
741                         goto exit_unlock;
742         } else {
743                 ret = rte_mempool_populate_phys_tab(mp, vaddr,
744                         paddr, pg_num, pg_shift);
745                 if (ret != (int)mp->size)
746                         goto exit_unlock;
747         }
748
749         /* call the initializer */
750         if (obj_init)
751                 rte_mempool_obj_iter(mp, obj_init, obj_init_arg);
752
753         te->data = (void *) mp;
754
755         rte_rwlock_write_lock(RTE_EAL_TAILQ_RWLOCK);
756         TAILQ_INSERT_TAIL(mempool_list, te, next);
757         rte_rwlock_write_unlock(RTE_EAL_TAILQ_RWLOCK);
758         rte_rwlock_write_unlock(RTE_EAL_MEMPOOL_RWLOCK);
759
760         return mp;
761
762 exit_unlock:
763         rte_rwlock_write_unlock(RTE_EAL_MEMPOOL_RWLOCK);
764         if (mp != NULL) {
765                 rte_mempool_free_memchunks(mp);
766                 rte_ring_free(mp->ring);
767         }
768         rte_free(te);
769
770         return NULL;
771 }
772
773 /* Return the number of entries in the mempool */
774 unsigned
775 rte_mempool_count(const struct rte_mempool *mp)
776 {
777         unsigned count;
778         unsigned lcore_id;
779
780         count = rte_ring_count(mp->ring);
781
782         if (mp->cache_size == 0)
783                 return count;
784
785         for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++)
786                 count += mp->local_cache[lcore_id].len;
787
788         /*
789          * due to race condition (access to len is not locked), the
790          * total can be greater than size... so fix the result
791          */
792         if (count > mp->size)
793                 return mp->size;
794         return count;
795 }
796
797 /* dump the cache status */
798 static unsigned
799 rte_mempool_dump_cache(FILE *f, const struct rte_mempool *mp)
800 {
801         unsigned lcore_id;
802         unsigned count = 0;
803         unsigned cache_count;
804
805         fprintf(f, "  cache infos:\n");
806         fprintf(f, "    cache_size=%"PRIu32"\n", mp->cache_size);
807
808         if (mp->cache_size == 0)
809                 return count;
810
811         for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) {
812                 cache_count = mp->local_cache[lcore_id].len;
813                 fprintf(f, "    cache_count[%u]=%u\n", lcore_id, cache_count);
814                 count += cache_count;
815         }
816         fprintf(f, "    total_cache_count=%u\n", count);
817         return count;
818 }
819
820 #ifndef __INTEL_COMPILER
821 #pragma GCC diagnostic ignored "-Wcast-qual"
822 #endif
823
824 /* check and update cookies or panic (internal) */
825 void rte_mempool_check_cookies(const struct rte_mempool *mp,
826         void * const *obj_table_const, unsigned n, int free)
827 {
828 #ifdef RTE_LIBRTE_MEMPOOL_DEBUG
829         struct rte_mempool_objhdr *hdr;
830         struct rte_mempool_objtlr *tlr;
831         uint64_t cookie;
832         void *tmp;
833         void *obj;
834         void **obj_table;
835
836         /* Force to drop the "const" attribute. This is done only when
837          * DEBUG is enabled */
838         tmp = (void *) obj_table_const;
839         obj_table = (void **) tmp;
840
841         while (n--) {
842                 obj = obj_table[n];
843
844                 if (rte_mempool_from_obj(obj) != mp)
845                         rte_panic("MEMPOOL: object is owned by another "
846                                   "mempool\n");
847
848                 hdr = __mempool_get_header(obj);
849                 cookie = hdr->cookie;
850
851                 if (free == 0) {
852                         if (cookie != RTE_MEMPOOL_HEADER_COOKIE1) {
853                                 rte_log_set_history(0);
854                                 RTE_LOG(CRIT, MEMPOOL,
855                                         "obj=%p, mempool=%p, cookie=%" PRIx64 "\n",
856                                         obj, (const void *) mp, cookie);
857                                 rte_panic("MEMPOOL: bad header cookie (put)\n");
858                         }
859                         hdr->cookie = RTE_MEMPOOL_HEADER_COOKIE2;
860                 } else if (free == 1) {
861                         if (cookie != RTE_MEMPOOL_HEADER_COOKIE2) {
862                                 rte_log_set_history(0);
863                                 RTE_LOG(CRIT, MEMPOOL,
864                                         "obj=%p, mempool=%p, cookie=%" PRIx64 "\n",
865                                         obj, (const void *) mp, cookie);
866                                 rte_panic("MEMPOOL: bad header cookie (get)\n");
867                         }
868                         hdr->cookie = RTE_MEMPOOL_HEADER_COOKIE1;
869                 } else if (free == 2) {
870                         if (cookie != RTE_MEMPOOL_HEADER_COOKIE1 &&
871                             cookie != RTE_MEMPOOL_HEADER_COOKIE2) {
872                                 rte_log_set_history(0);
873                                 RTE_LOG(CRIT, MEMPOOL,
874                                         "obj=%p, mempool=%p, cookie=%" PRIx64 "\n",
875                                         obj, (const void *) mp, cookie);
876                                 rte_panic("MEMPOOL: bad header cookie (audit)\n");
877                         }
878                 }
879                 tlr = __mempool_get_trailer(obj);
880                 cookie = tlr->cookie;
881                 if (cookie != RTE_MEMPOOL_TRAILER_COOKIE) {
882                         rte_log_set_history(0);
883                         RTE_LOG(CRIT, MEMPOOL,
884                                 "obj=%p, mempool=%p, cookie=%" PRIx64 "\n",
885                                 obj, (const void *) mp, cookie);
886                         rte_panic("MEMPOOL: bad trailer cookie\n");
887                 }
888         }
889 #else
890         RTE_SET_USED(mp);
891         RTE_SET_USED(obj_table_const);
892         RTE_SET_USED(n);
893         RTE_SET_USED(free);
894 #endif
895 }
896
897 #ifdef RTE_LIBRTE_MEMPOOL_DEBUG
898 static void
899 mempool_obj_audit(struct rte_mempool *mp, __rte_unused void *opaque,
900         void *obj, __rte_unused unsigned idx)
901 {
902         __mempool_check_cookies(mp, &obj, 1, 2);
903 }
904
905 static void
906 mempool_audit_cookies(struct rte_mempool *mp)
907 {
908         unsigned num;
909
910         num = rte_mempool_obj_iter(mp, mempool_obj_audit, NULL);
911         if (num != mp->size) {
912                 rte_panic("rte_mempool_obj_iter(mempool=%p, size=%u) "
913                         "iterated only over %u elements\n",
914                         mp, mp->size, num);
915         }
916 }
917 #else
918 #define mempool_audit_cookies(mp) do {} while(0)
919 #endif
920
921 #ifndef __INTEL_COMPILER
922 #pragma GCC diagnostic error "-Wcast-qual"
923 #endif
924
925 /* check cookies before and after objects */
926 static void
927 mempool_audit_cache(const struct rte_mempool *mp)
928 {
929         /* check cache size consistency */
930         unsigned lcore_id;
931
932         if (mp->cache_size == 0)
933                 return;
934
935         for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) {
936                 if (mp->local_cache[lcore_id].len > mp->cache_flushthresh) {
937                         RTE_LOG(CRIT, MEMPOOL, "badness on cache[%u]\n",
938                                 lcore_id);
939                         rte_panic("MEMPOOL: invalid cache len\n");
940                 }
941         }
942 }
943
944 /* check the consistency of mempool (size, cookies, ...) */
945 void
946 rte_mempool_audit(struct rte_mempool *mp)
947 {
948         mempool_audit_cache(mp);
949         mempool_audit_cookies(mp);
950
951         /* For case where mempool DEBUG is not set, and cache size is 0 */
952         RTE_SET_USED(mp);
953 }
954
955 /* dump the status of the mempool on the console */
956 void
957 rte_mempool_dump(FILE *f, struct rte_mempool *mp)
958 {
959 #ifdef RTE_LIBRTE_MEMPOOL_DEBUG
960         struct rte_mempool_debug_stats sum;
961         unsigned lcore_id;
962 #endif
963         struct rte_mempool_memhdr *memhdr;
964         unsigned common_count;
965         unsigned cache_count;
966         size_t mem_len = 0;
967
968         RTE_ASSERT(f != NULL);
969         RTE_ASSERT(mp != NULL);
970
971         fprintf(f, "mempool <%s>@%p\n", mp->name, mp);
972         fprintf(f, "  flags=%x\n", mp->flags);
973         fprintf(f, "  ring=<%s>@%p\n", mp->ring->name, mp->ring);
974         fprintf(f, "  phys_addr=0x%" PRIx64 "\n", mp->phys_addr);
975         fprintf(f, "  nb_mem_chunks=%u\n", mp->nb_mem_chunks);
976         fprintf(f, "  size=%"PRIu32"\n", mp->size);
977         fprintf(f, "  populated_size=%"PRIu32"\n", mp->populated_size);
978         fprintf(f, "  header_size=%"PRIu32"\n", mp->header_size);
979         fprintf(f, "  elt_size=%"PRIu32"\n", mp->elt_size);
980         fprintf(f, "  trailer_size=%"PRIu32"\n", mp->trailer_size);
981         fprintf(f, "  total_obj_size=%"PRIu32"\n",
982                mp->header_size + mp->elt_size + mp->trailer_size);
983
984         fprintf(f, "  private_data_size=%"PRIu32"\n", mp->private_data_size);
985
986         STAILQ_FOREACH(memhdr, &mp->mem_list, next)
987                 mem_len += memhdr->len;
988         if (mem_len != 0) {
989                 fprintf(f, "  avg bytes/object=%#Lf\n",
990                         (long double)mem_len / mp->size);
991         }
992
993         cache_count = rte_mempool_dump_cache(f, mp);
994         common_count = rte_ring_count(mp->ring);
995         if ((cache_count + common_count) > mp->size)
996                 common_count = mp->size - cache_count;
997         fprintf(f, "  common_pool_count=%u\n", common_count);
998
999         /* sum and dump statistics */
1000 #ifdef RTE_LIBRTE_MEMPOOL_DEBUG
1001         memset(&sum, 0, sizeof(sum));
1002         for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) {
1003                 sum.put_bulk += mp->stats[lcore_id].put_bulk;
1004                 sum.put_objs += mp->stats[lcore_id].put_objs;
1005                 sum.get_success_bulk += mp->stats[lcore_id].get_success_bulk;
1006                 sum.get_success_objs += mp->stats[lcore_id].get_success_objs;
1007                 sum.get_fail_bulk += mp->stats[lcore_id].get_fail_bulk;
1008                 sum.get_fail_objs += mp->stats[lcore_id].get_fail_objs;
1009         }
1010         fprintf(f, "  stats:\n");
1011         fprintf(f, "    put_bulk=%"PRIu64"\n", sum.put_bulk);
1012         fprintf(f, "    put_objs=%"PRIu64"\n", sum.put_objs);
1013         fprintf(f, "    get_success_bulk=%"PRIu64"\n", sum.get_success_bulk);
1014         fprintf(f, "    get_success_objs=%"PRIu64"\n", sum.get_success_objs);
1015         fprintf(f, "    get_fail_bulk=%"PRIu64"\n", sum.get_fail_bulk);
1016         fprintf(f, "    get_fail_objs=%"PRIu64"\n", sum.get_fail_objs);
1017 #else
1018         fprintf(f, "  no statistics available\n");
1019 #endif
1020
1021         rte_mempool_audit(mp);
1022 }
1023
1024 /* dump the status of all mempools on the console */
1025 void
1026 rte_mempool_list_dump(FILE *f)
1027 {
1028         struct rte_mempool *mp = NULL;
1029         struct rte_tailq_entry *te;
1030         struct rte_mempool_list *mempool_list;
1031
1032         mempool_list = RTE_TAILQ_CAST(rte_mempool_tailq.head, rte_mempool_list);
1033
1034         rte_rwlock_read_lock(RTE_EAL_MEMPOOL_RWLOCK);
1035
1036         TAILQ_FOREACH(te, mempool_list, next) {
1037                 mp = (struct rte_mempool *) te->data;
1038                 rte_mempool_dump(f, mp);
1039         }
1040
1041         rte_rwlock_read_unlock(RTE_EAL_MEMPOOL_RWLOCK);
1042 }
1043
1044 /* search a mempool from its name */
1045 struct rte_mempool *
1046 rte_mempool_lookup(const char *name)
1047 {
1048         struct rte_mempool *mp = NULL;
1049         struct rte_tailq_entry *te;
1050         struct rte_mempool_list *mempool_list;
1051
1052         mempool_list = RTE_TAILQ_CAST(rte_mempool_tailq.head, rte_mempool_list);
1053
1054         rte_rwlock_read_lock(RTE_EAL_MEMPOOL_RWLOCK);
1055
1056         TAILQ_FOREACH(te, mempool_list, next) {
1057                 mp = (struct rte_mempool *) te->data;
1058                 if (strncmp(name, mp->name, RTE_MEMPOOL_NAMESIZE) == 0)
1059                         break;
1060         }
1061
1062         rte_rwlock_read_unlock(RTE_EAL_MEMPOOL_RWLOCK);
1063
1064         if (te == NULL) {
1065                 rte_errno = ENOENT;
1066                 return NULL;
1067         }
1068
1069         return mp;
1070 }
1071
1072 void rte_mempool_walk(void (*func)(struct rte_mempool *, void *),
1073                       void *arg)
1074 {
1075         struct rte_tailq_entry *te = NULL;
1076         struct rte_mempool_list *mempool_list;
1077
1078         mempool_list = RTE_TAILQ_CAST(rte_mempool_tailq.head, rte_mempool_list);
1079
1080         rte_rwlock_read_lock(RTE_EAL_MEMPOOL_RWLOCK);
1081
1082         TAILQ_FOREACH(te, mempool_list, next) {
1083                 (*func)((struct rte_mempool *) te->data, arg);
1084         }
1085
1086         rte_rwlock_read_unlock(RTE_EAL_MEMPOOL_RWLOCK);
1087 }