realloc.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * Copyright Institute of Communication and Computer Systems (ICCS)
  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. /**
  18. * @file bitmap/realloc.c
  19. * @author Ilias Pliotas, Ioannis Koutras
  20. * @date September 2012
  21. * @brief realloc() implementation for bitmap-organized raw blocks
  22. */
  23. #include "bitmap/bitmap.h"
  24. #include "dmmlib/dmmlib.h"
  25. #include "memcpy.h"
  26. #include "locks.h"
  27. /**
  28. * Reallocates a memory block from a bitmap-organized raw block
  29. *
  30. * @param raw_block The pointer of the bitmap raw block.
  31. * @param ptr The pointer of the memory block to be re-allocated.
  32. * @param req_size The requested memory size.
  33. * @retval The address to serve the request.
  34. * @retval NULL No available memory space.
  35. */
  36. void * bitmap_realloc(bitmap_rb_t *raw_block, void * ptr,
  37. size_t req_size) {
  38. void *ret;
  39. chunk_header_t *chunk_header;
  40. size_t old_size;
  41. chunk_header = (chunk_header_t *)((uintptr_t) ptr - CHUNK_HDR_SIZE);
  42. old_size = chunk_header->num_of_cells * raw_block->bytes_per_cell -
  43. CHUNK_HDR_SIZE;
  44. if(old_size >= req_size) {
  45. ret = ptr;
  46. // TODO Free possibly unneeded cells
  47. } else {
  48. #ifdef HAVE_LOCKS
  49. raw_block_header_t *rb;
  50. rb = (raw_block_header_t *)
  51. ((uintptr_t) raw_block - sizeof(raw_block_header_t));
  52. #endif /* HAVE_LOCKS */
  53. /* Try initially to allocate space from the same raw block */
  54. lock_raw_block(rb);
  55. ret = bitmap_malloc(raw_block, req_size);
  56. unlock_raw_block(rb);
  57. /* If no space can be found, try your luck in other raw blocks */
  58. if(ret == NULL) {
  59. ret = malloc(req_size);
  60. }
  61. if(ret != NULL) {
  62. memcpy(ret, ptr, old_size);
  63. lock_raw_block(rb);
  64. bitmap_free(raw_block, ptr);
  65. unlock_raw_block(rb);
  66. }
  67. }
  68. return ret;
  69. }