0001
0002
0003
0004
0005
0006
0007
0008 #include "pstack.h"
0009 #include "debug.h"
0010 #include <linux/kernel.h>
0011 #include <linux/zalloc.h>
0012 #include <stdlib.h>
0013 #include <string.h>
0014
0015 struct pstack {
0016 unsigned short top;
0017 unsigned short max_nr_entries;
0018 void *entries[];
0019 };
0020
0021 struct pstack *pstack__new(unsigned short max_nr_entries)
0022 {
0023 struct pstack *pstack = zalloc((sizeof(*pstack) +
0024 max_nr_entries * sizeof(void *)));
0025 if (pstack != NULL)
0026 pstack->max_nr_entries = max_nr_entries;
0027 return pstack;
0028 }
0029
0030 void pstack__delete(struct pstack *pstack)
0031 {
0032 free(pstack);
0033 }
0034
0035 bool pstack__empty(const struct pstack *pstack)
0036 {
0037 return pstack->top == 0;
0038 }
0039
0040 void pstack__remove(struct pstack *pstack, void *key)
0041 {
0042 unsigned short i = pstack->top, last_index = pstack->top - 1;
0043
0044 while (i-- != 0) {
0045 if (pstack->entries[i] == key) {
0046 if (i < last_index)
0047 memmove(pstack->entries + i,
0048 pstack->entries + i + 1,
0049 (last_index - i) * sizeof(void *));
0050 --pstack->top;
0051 return;
0052 }
0053 }
0054 pr_err("%s: %p not on the pstack!\n", __func__, key);
0055 }
0056
0057 void pstack__push(struct pstack *pstack, void *key)
0058 {
0059 if (pstack->top == pstack->max_nr_entries) {
0060 pr_err("%s: top=%d, overflow!\n", __func__, pstack->top);
0061 return;
0062 }
0063 pstack->entries[pstack->top++] = key;
0064 }
0065
0066 void *pstack__pop(struct pstack *pstack)
0067 {
0068 void *ret;
0069
0070 if (pstack->top == 0) {
0071 pr_err("%s: underflow!\n", __func__);
0072 return NULL;
0073 }
0074
0075 ret = pstack->entries[--pstack->top];
0076 pstack->entries[pstack->top] = NULL;
0077 return ret;
0078 }
0079
0080 void *pstack__peek(struct pstack *pstack)
0081 {
0082 if (pstack->top == 0)
0083 return NULL;
0084 return pstack->entries[pstack->top - 1];
0085 }