From 30bede79400b0d1a24bde048fdec0a4abe4c4d76 Mon Sep 17 00:00:00 2001 From: dongjiuzhu1 Date: Fri, 16 Sep 2022 16:55:09 +0800 Subject: [PATCH] mm/mempool: fix bug about size mismatch and binary find Signed-off-by: dongjiuzhu1 --- mm/mempool/mempool.c | 25 +++++++++++--------- mm/mempool/mempool_multiple.c | 43 +++++++++++++++++++++-------------- 2 files changed, 40 insertions(+), 28 deletions(-) diff --git a/mm/mempool/mempool.c b/mm/mempool/mempool.c index 1c2bd0e743..8e6074d318 100644 --- a/mm/mempool/mempool.c +++ b/mm/mempool/mempool.c @@ -99,19 +99,22 @@ int mempool_init(FAR struct mempool_s *pool, FAR const char *name) sq_init(&pool->elist); count = pool->ninitial + pool->ninterrupt; - base = mempool_malloc(pool, sizeof(*base) + - pool->bsize * count); - if (base == NULL) + if (count != 0) { - return -ENOMEM; - } + base = mempool_malloc(pool, sizeof(*base) + + pool->bsize * count); + if (base == NULL) + { + return -ENOMEM; + } - sq_addfirst(base, &pool->elist); - mempool_add_list(&pool->ilist, base + 1, - pool->ninterrupt, pool->bsize); - mempool_add_list(&pool->list, (FAR char *)(base + 1) + - pool->ninterrupt * pool->bsize, - pool->ninitial, pool->bsize); + sq_addfirst(base, &pool->elist); + mempool_add_list(&pool->ilist, base + 1, + pool->ninterrupt, pool->bsize); + mempool_add_list(&pool->list, (FAR char *)(base + 1) + + pool->ninterrupt * pool->bsize, + pool->ninitial, pool->bsize); + } if (pool->wait && pool->nexpand == 0) { diff --git a/mm/mempool/mempool_multiple.c b/mm/mempool/mempool_multiple.c index 092b84f393..a71868c6c7 100644 --- a/mm/mempool/mempool_multiple.c +++ b/mm/mempool/mempool_multiple.c @@ -40,28 +40,29 @@ static inline struct mempool_s * mempool_multiple_find(FAR struct mempool_multiple_s *mpool, size_t size) { - FAR struct mempool_s *low = mpool->pools; - FAR struct mempool_s *mid; - size_t n = mpool->npools; + size_t right = mpool->npools; + size_t left = 0; + size_t mid; - while (1) + while (left < right) { - n >>= 1; - mid = low + n; - if (size > mid->bsize) + mid = (left + right) >> 1; + if (mpool->pools[mid].bsize > size) { - if (n == 0) - { - return NULL; - } - - low = ++mid; + right = mid; } - else if (size == mid->bsize || n == 0) + else { - return mid; + left = mid + 1; } } + + if (left == mpool->npools) + { + return NULL; + } + + return &mpool->pools[left]; } /**************************************************************************** @@ -136,7 +137,11 @@ FAR void *mempool_multiple_alloc(FAR struct mempool_multiple_s *mpool, FAR struct mempool_s *pool; pool = mempool_multiple_find(mpool, size + SIZEOF_HEAD); - DEBUGASSERT(pool != NULL); + if (pool == NULL) + { + return NULL; + } + do { FAR void *blk = mempool_alloc(pool); @@ -266,7 +271,11 @@ FAR void *mempool_multiple_fixed_alloc(FAR struct mempool_multiple_s *mpool, FAR struct mempool_s *pool; pool = mempool_multiple_find(mpool, size); - DEBUGASSERT(pool != NULL); + if (pool == NULL) + { + return NULL; + } + return mempool_alloc(pool); }