runtime/kp_mempool.c - ktap

Functions defined

Source code

  1. /*
  2. * kp_mempool.c - ktap memory pool, service for string allocation
  3. *
  4. * This file is part of ktap by Jovi Zhangwei.
  5. *
  6. * Copyright (C) 2012-2013 Jovi Zhangwei <jovi.zhangwei@gmail.com>.
  7. *
  8. * ktap is free software; you can redistribute it and/or modify it
  9. * under the terms and conditions of the GNU General Public License,
  10. * version 2, as published by the Free Software Foundation.
  11. *
  12. * ktap is distributed in the hope it will be useful, but WITHOUT
  13. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  14. * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
  15. * more details.
  16. *
  17. * You should have received a copy of the GNU General Public License along with
  18. * this program; if not, write to the Free Software Foundation, Inc.,
  19. * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
  20. */

  21. #include "../include/ktap_types.h"
  22. #include "kp_obj.h"
  23. #include "kp_str.h"

  24. #include <linux/ctype.h>
  25. #include <linux/module.h>
  26. #include "ktap.h"


  27. /*
  28. * allocate memory from mempool, the allocated memory will be free
  29. * util ktap exit.
  30. * TODO: lock-free allocation
  31. */
  32. void *kp_mempool_alloc(ktap_state_t *ks, int size)
  33. {
  34.     ktap_global_state_t *g = G(ks);
  35.     void *mempool = g->mempool;
  36.     void *freepos = g->mp_freepos;
  37.     void *addr;
  38.     unsigned long flags;

  39.     local_irq_save(flags);
  40.     arch_spin_lock(&g->mp_lock);

  41.     if (unlikely((unsigned long)((char *)freepos + size)) >
  42.              (unsigned long)((char *)mempool + g->mp_size)) {
  43.         addr = NULL;
  44.         goto out;
  45.     }

  46.     addr = freepos;
  47.     g->mp_freepos = (char *)freepos + size;
  48. out:

  49.     arch_spin_unlock(&g->mp_lock);
  50.     local_irq_restore(flags);
  51.     return addr;
  52. }

  53. /*
  54. * destroy mempool.
  55. */
  56. void kp_mempool_destroy(ktap_state_t *ks)
  57. {
  58.     ktap_global_state_t *g = G(ks);

  59.     if (!g->mempool)
  60.         return;

  61.     vfree(g->mempool);
  62.     g->mempool = NULL;
  63.     g->mp_freepos = NULL;
  64.     g->mp_size = 0;
  65. }

  66. /*
  67. * pre-allocate size Kbytes memory pool.
  68. */
  69. int kp_mempool_init(ktap_state_t *ks, int size)
  70. {
  71.     ktap_global_state_t *g = G(ks);

  72.     g->mempool = vmalloc(size * 1024);
  73.     if (!g->mempool)
  74.         return -ENOMEM;

  75.     g->mp_freepos = g->mempool;
  76.     g->mp_size = size * 1024;
  77.     g->mp_lock = (arch_spinlock_t)__ARCH_SPIN_LOCK_UNLOCKED;
  78.     return 0;
  79. }