xref: /dpdk/drivers/net/bnxt/tf_core/stack.c (revision c81e3f21d1ea05e5123278b15d9d5e1257b6ba99)
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright(c) 2019-2020 Broadcom
3  * All rights reserved.
4  */
5 
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <stdbool.h>
9 #include <stdint.h>
10 #include <errno.h>
11 #include "stack.h"
12 
13 #define STACK_EMPTY -1
14 
15 /* Initialize stack
16  */
17 int
18 stack_init(int num_entries, uint32_t *items, struct stack *st)
19 {
20 	if (items == NULL || st == NULL)
21 		return -EINVAL;
22 
23 	st->max = num_entries;
24 	st->top = STACK_EMPTY;
25 	st->items = items;
26 
27 	return 0;
28 }
29 
30 /* Return the size of the stack
31  */
32 int32_t
33 stack_size(struct stack *st)
34 {
35 	return st->top + 1;
36 }
37 
38 /* Check if the stack is empty
39  */
40 bool
41 stack_is_empty(struct stack *st)
42 {
43 	return st->top == STACK_EMPTY;
44 }
45 
46 /* Check if the stack is full
47  */
48 bool
49 stack_is_full(struct stack *st)
50 {
51 	return st->top == st->max - 1;
52 }
53 
54 /* Add  element x to  the stack
55  */
56 int
57 stack_push(struct stack *st, uint32_t x)
58 {
59 	if (stack_is_full(st))
60 		return -EOVERFLOW;
61 
62 	/* add an element and increments the top index
63 	 */
64 	st->items[++st->top] = x;
65 
66 	return 0;
67 }
68 
69 /* Pop top element x from the stack and return
70  * in user provided location.
71  */
72 int
73 stack_pop(struct stack *st, uint32_t *x)
74 {
75 	if (stack_is_empty(st))
76 		return -ENOENT;
77 
78 	*x = st->items[st->top];
79 	st->top--;
80 
81 	return 0;
82 }
83 
84 /* Dump the stack
85  */
86 void stack_dump(struct stack *st)
87 {
88 	int i, j;
89 
90 	printf("top=%d\n", st->top);
91 	printf("max=%d\n", st->max);
92 
93 	if (st->top == -1) {
94 		printf("stack is empty\n");
95 		return;
96 	}
97 
98 	for (i = 0; i < st->max + 7 / 8; i++) {
99 		printf("item[%d] 0x%08x", i, st->items[i]);
100 
101 		for (j = 0; j < 7; j++) {
102 			if (i++ < st->max - 1)
103 				printf(" 0x%08x", st->items[i]);
104 		}
105 		printf("\n");
106 	}
107 }
108