Contiki 2.5
bundleslot.c
Go to the documentation of this file.
1 /**
2  * \addtogroup bprocess
3  * @{
4  */
5 
6 /**
7  * \file
8  * \brief Bundle Slot memory management
9  *
10  * \author Daniel Willmann <daniel@totalueberwachung.de>
11  */
12 
13 #include <stdint.h>
14 #include <string.h>
15 #include <stdio.h>
16 #include "logging.h"
17 
18 #include "bundle.h"
19 #include "storage.h"
20 #include "agent.h"
21 #include "bundleslot.h"
22 
23 /* Defines how many bundles can be used (in storage, used) on this node at once */
24 #ifdef CONF_BUNDLE_NUM
25 #define BUNDLE_NUM CONF_BUNDLE_NUM
26 #else
27 #define BUNDLE_NUM (BUNDLE_STORAGE_SIZE + 10)
28 #endif
29 
30 #define INIT_GUARD() \
31  do {\
32  if (!inited) {\
33  memset(bundleslots, 0, sizeof(bundleslots));\
34  inited = 1;\
35  }\
36  } while (0)
37 
38 static uint8_t inited = 0;
39 static struct bundle_slot_t bundleslots[BUNDLE_NUM];
40 static uint8_t slots_in_use = 0;
41 
42 /* Returns a pointer to a newly allocated bundle */
43 struct bundle_slot_t *bundleslot_get_free()
44 {
45  uint16_t i;
46  INIT_GUARD();
47 
48  for (i=0; i<BUNDLE_NUM; i++) {
49  if (bundleslots[i].ref == 0) {
50  memset(&bundleslots[i], 0, sizeof(struct bundle_slot_t));
51 
52  bundleslots[i].ref++;
53  bundleslots[i].type = 0;
54  slots_in_use ++;
55 
56  return &bundleslots[i];
57  }
58  }
59  return NULL;
60 }
61 
62 /* Frees the bundle */
63 void bundleslot_free(struct bundle_slot_t *bs)
64 {
65  if( bs->bundle.ptr == NULL ) {
66  LOG(LOGD_DTN, LOG_SLOTS, LOGL_ERR, "DUPLICATE FREE");
67  return;
68  }
69 
70  bs->ref = 0;
71  slots_in_use --;
72 
73  LOG(LOGD_DTN, LOG_SLOTS, LOGL_DBG, "bundleslot_free(%p) %u", bs, slots_in_use);
74 
75  // Zeroify all freed memory
76  memset(bs->bundle.ptr, 0, sizeof(struct bundle_t));
77 
78  mmem_free(&bs->bundle);
79 
80  // And kill the pointer!
81  bs->bundle.ptr = NULL;
82 }
83 
84 /* Increment usage count */
85 int bundleslot_increment(struct bundle_slot_t *bs)
86 {
87  LOG(LOGD_DTN, LOG_SLOTS, LOGL_DBG, "bundleslot_inc(%p) to %u", bs, bs->ref+1);
88 
89  if (!bs->ref)
90  return -1;
91 
92  bs->ref++;
93  return bs->ref;
94 }
95 
96 /* Decrement usage count, free if necessary */
97 int bundleslot_decrement(struct bundle_slot_t *bs)
98 {
99  LOG(LOGD_DTN, LOG_SLOTS, LOGL_DBG, "bundleslot_dec(%p) to %u", bs, bs->ref-1);
100 
101  if (!bs->ref)
102  return -1;
103 
104  bs->ref--;
105  if (!bs->ref)
106  bundleslot_free(bs);
107  return bs->ref;
108 }