repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
yrq110/HouseRadar
AMapDemo/HistoryView.h
<reponame>yrq110/HouseRadar // // HistoryView.h // AMapDemo // // Created by yrq_mac on 16/2/10. // Copyright © 2016年 yrq_mac. All rights reserved. // #import <UIKit/UIKit.h> #import "TopView.h" @interface HistoryView : UIView @property(strong,nonatomic)TopView *topView; //@property(strong,nonatomic)UIView *topView; //@property(strong,nonatomic)UILabel *topLabel; @end
Aliex-dev/CP
CARD DECK SIMULATION/main.c
<reponame>Aliex-dev/CP #include <stdio.h> #include <stdlib.h> #include <time.h> int main() { FILE *ptr; ptr=fopen("result.txt","w"); fprintf(ptr," n \t suit \t rank \t match or mismatch"); srand(time(0)); int r1,r2,r3,r4,n=1; char suit[4]={'d','h','s','c'}; char rank[13]={'A','K','Q','J','9','8','7','6','5','4','3','2','1'}; r1=rand(); r2=rand(); fprintf(ptr," \n 1 \t %c \t %c ",suit[r1%4],rank[r2%13]); while(1) { n++; r3=rand(); r4=rand(); if(r1%4==r3%4 && r2%13==r4%13) { fprintf(ptr," \n %d \t %c \t %c \t match found ",n,suit[r3%4],rank[r4%13] ); break; } else { fprintf(ptr," \n %d \t %c \t %c \t match not found ",n,suit[r3%4],rank[r4%13] ); } } fclose(ptr); }
razmik-gharibyan/clear_all_notifications
ios/Classes/ClearAllNotificationsPlugin.h
<reponame>razmik-gharibyan/clear_all_notifications<filename>ios/Classes/ClearAllNotificationsPlugin.h #import <Flutter/Flutter.h> @interface ClearAllNotificationsPlugin : NSObject<FlutterPlugin> @end
borodust/claw-legacy
t/c/cffi/adapter.c
<gh_stars>1-10 /* Generated by :claw at 2019-09-21T21:57:01.172611Z */ #include <stddef.h> #include "c.h" #if !defined(__CLAW_API) # if defined(_WIN32) # define __CLAW_API __declspec(dllexport) # elif defined(__GNUC__) # define __CLAW_API __attribute__((visibility("default"))) # else # define __CLAW_API # endif #endif #if defined(__cplusplus) extern C { #endif #ifdef _WIN32 # include <windows.h> static HMODULE ___claw_module; static int ___claw_init_wrapper() { ___claw_module = GetModuleHandle(NULL); return ___claw_module != NULL; } static void ___claw_close_wrapper(void) { } #else # include <dlfcn.h> static void* ___claw_module; static int ___claw_init_wrapper() { ___claw_module = dlopen(NULL, RTLD_NOW | RTLD_GLOBAL); return ___claw_module != NULL; } static void ___claw_close_wrapper(void) { } #endif static void* claw_get_proc_addr(const char *name) { if(___claw_module == NULL) { return NULL; } #ifdef _WIN32 return (void*) GetProcAddress(___claw_module, name); #else return dlsym(___claw_module, name); #endif } #if defined(__cplusplus) extern "C" { #endif typedef char* (*___claw_tst_get_node_name_t)(struct tst_node_t); typedef void (*___claw_tst_set_node_color_t)(struct tst_node_t*, union tst_color_t); typedef union tst_color_t (*___claw_tst_get_node_color_t)(struct tst_node_t); typedef enum tst_node_kind (*___claw_tst_get_node_kind_t)(struct tst_node_t); typedef void (*___claw_tst_add_child_t)(struct tst_node_t*, struct tst_node_t); typedef void (*___claw_tst_destroy_node_t)(struct tst_node_t); typedef struct tst_node_t (*___claw_tst_create_named_node_t)(char[16]); typedef struct tst_node_t (*___claw_tst_create_colored_node_t)(union tst_color_t); typedef tst_tree_t* (*___claw_tst_create_tree_t)(struct tst_node_t); static ___claw_tst_get_node_name_t __v_claw_tst_get_node_name; static ___claw_tst_set_node_color_t __v_claw_tst_set_node_color; static ___claw_tst_get_node_color_t __v_claw_tst_get_node_color; static ___claw_tst_get_node_kind_t __v_claw_tst_get_node_kind; static ___claw_tst_add_child_t __v_claw_tst_add_child; static ___claw_tst_destroy_node_t __v_claw_tst_destroy_node; static ___claw_tst_create_named_node_t __v_claw_tst_create_named_node; static ___claw_tst_create_colored_node_t __v_claw_tst_create_colored_node; static ___claw_tst_create_tree_t __v_claw_tst_create_tree; __CLAW_API int ___claw_libctest_loader_F6D054DFA7C9E57DFE1F11FC030D38CD79A3411A() { if(___claw_init_wrapper()) { __v_claw_tst_get_node_name = (___claw_tst_get_node_name_t) claw_get_proc_addr("tst_get_node_name"); __v_claw_tst_set_node_color = (___claw_tst_set_node_color_t) claw_get_proc_addr("tst_set_node_color"); __v_claw_tst_get_node_color = (___claw_tst_get_node_color_t) claw_get_proc_addr("tst_get_node_color"); __v_claw_tst_get_node_kind = (___claw_tst_get_node_kind_t) claw_get_proc_addr("tst_get_node_kind"); __v_claw_tst_add_child = (___claw_tst_add_child_t) claw_get_proc_addr("tst_add_child"); __v_claw_tst_destroy_node = (___claw_tst_destroy_node_t) claw_get_proc_addr("tst_destroy_node"); __v_claw_tst_create_named_node = (___claw_tst_create_named_node_t) claw_get_proc_addr("tst_create_named_node"); __v_claw_tst_create_colored_node = (___claw_tst_create_colored_node_t) claw_get_proc_addr("tst_create_colored_node"); __v_claw_tst_create_tree = (___claw_tst_create_tree_t) claw_get_proc_addr("tst_create_tree"); ___claw_close_wrapper(); return 0; } return 1; } __CLAW_API char* ___claw_tst_get_node_name(struct tst_node_t* arg0) { char* result = __v_claw_tst_get_node_name((*arg0)); return result; } __CLAW_API void ___claw_tst_set_node_color(struct tst_node_t* arg0, union tst_color_t* arg1) { __v_claw_tst_set_node_color(arg0, (*arg1)); } __CLAW_API union tst_color_t* ___claw_tst_get_node_color(union tst_color_t* arg0, struct tst_node_t* arg1) { union tst_color_t result = __v_claw_tst_get_node_color((*arg1)); (*arg0) = result; return arg0; } __CLAW_API enum tst_node_kind ___claw_tst_get_node_kind(struct tst_node_t* arg0) { enum tst_node_kind result = __v_claw_tst_get_node_kind((*arg0)); return result; } __CLAW_API void ___claw_tst_add_child(struct tst_node_t* arg0, struct tst_node_t* arg1) { __v_claw_tst_add_child(arg0, (*arg1)); } __CLAW_API void ___claw_tst_destroy_node(struct tst_node_t* arg0) { __v_claw_tst_destroy_node((*arg0)); } __CLAW_API struct tst_node_t* ___claw_tst_create_named_node(struct tst_node_t* arg0, char[16] arg1) { struct tst_node_t result = __v_claw_tst_create_named_node(arg1); (*arg0) = result; return arg0; } __CLAW_API struct tst_node_t* ___claw_tst_create_colored_node(struct tst_node_t* arg0, union tst_color_t* arg1) { struct tst_node_t result = __v_claw_tst_create_colored_node((*arg1)); (*arg0) = result; return arg0; } __CLAW_API tst_tree_t* ___claw_tst_create_tree(struct tst_node_t* arg0) { tst_tree_t* result = __v_claw_tst_create_tree((*arg0)); return result; } #if defined(__cplusplus) } #endif
borodust/claw-legacy
t/c/lib/c.c
<reponame>borodust/claw-legacy<filename>t/c/lib/c.c #include "c.h" #include "stdlib.h" #include "string.h" char tst_version_string_g[16] = "1.0.0"; char* tst_version_string() { return tst_version_string_g; } int count_nodes_and_assign_owner(tst_tree_t* owner, struct tst_node_t* node) { int node_count = 0; for (int i = 0; i < node->child_count; ++i) { node_count += count_nodes_and_assign_owner(owner, &node->children[i]); } node->owner = owner; return node_count + 1; } tst_tree_t* tst_create_tree(struct tst_node_t root) { tst_tree_t* tree = calloc(1, sizeof(tst_tree_t)); tree->root = root; tree->info.node_count = count_nodes_and_assign_owner(tree, &tree->root); return tree; } struct tst_node_t tst_create_colored_node(union tst_color_t color) { struct tst_node_t node; node.children = NULL; node.child_count = 0; node.kind = tst_node_kind_colored; node.owner = NULL; struct tst_colored_node_t* data = calloc(1, sizeof(struct tst_colored_node_t)); data->color = color; node.data = data; return node; } struct tst_node_t tst_create_named_node(char name[TST_NAME_MAX_LENGTH]) { struct tst_node_t node; node.children = NULL; node.child_count = 0; node.kind = tst_node_kind_named; node.owner = NULL; struct tst_named_node_t* data = calloc(1, sizeof(struct tst_named_node_t)); strcpy(data->name, name); node.data = data; return node; } void tst_destroy_node(struct tst_node_t node) { free(node.data); free(node.children); } void tst_add_child(struct tst_node_t* parent, struct tst_node_t child) { struct tst_node_t* old_array = parent->children; parent->children = calloc(parent->child_count + 1, sizeof(struct tst_node_t)); if (old_array != NULL) { memcpy(parent->children, old_array, parent->child_count * sizeof(struct tst_node_t)); free(old_array); } parent->children[parent->child_count] = child; parent->children[parent->child_count].owner = parent->owner; parent->child_count += 1; if (parent->owner != NULL) { parent->owner->info.node_count += 1; } } enum tst_node_kind tst_get_node_kind(struct tst_node_t node) { return node.kind; } union tst_color_t tst_get_node_color(struct tst_node_t node) { return ((struct tst_colored_node_t*)node.data)->color; } void tst_set_node_color(struct tst_node_t* node, union tst_color_t color) { ((struct tst_colored_node_t*)node->data)->color = color; } char* tst_get_node_name(struct tst_node_t node) { return ((struct tst_named_node_t*)node.data)->name; } void tst_set_node_name(struct tst_node_t* node, char* name) { strcpy(((struct tst_named_node_t*)node->data)->name, name); } void tst_visit_nodes(struct tst_node_t* node, tst_node_visitor_t visitor) { visitor(node); for (int i = 0; i < node->child_count; ++i) { tst_visit_nodes(&node->children[i], visitor); } } void tst_visit_tree_nodes(tst_tree_t* tree, tst_node_visitor_t visitor) { tst_visit_nodes(&tree->root, visitor); } void tst_destroy_node_recursively(struct tst_node_t* node) { for(int i = 0; i < node->child_count; ++i) { tst_destroy_node_recursively(&node->children[i]); } tst_destroy_node(*node); } void tst_destroy_tree(tst_tree_t* tree) { tst_destroy_node_recursively(&tree->root); }
borodust/claw-legacy
t/c/lib/c.h
<reponame>borodust/claw-legacy<gh_stars>1-10 /* * THIS API IS SPECIFICALLY MADE TO TEST VARIOUS ASPECTS OF SPEC GENERATION * THIS IS NOT HOW YOU SHOULD DESIGN ANY SANE C API */ #include "stdint.h" #define TST_VERSION 1 #define TST_NAME_MAX_LENGTH 16 extern char tst_version_string_g[16]; enum { tst_black = 0x0, tst_white = 0xFFFFFFFF }; typedef struct { void* __data; } __metadata_t; typedef struct { __metadata_t data; } metadata_t; union tst_color_t { uint32_t encoded; struct { uint8_t r; uint8_t g; uint8_t b; uint8_t a; } component; uint8_t array[4]; }; enum tst_node_kind { tst_node_kind_unknown = 10, tst_node_kind_named, tst_node_kind_colored = 20 }; struct tst_named_node_t { char name[TST_NAME_MAX_LENGTH + 1]; }; struct tst_colored_node_t { union tst_color_t color; }; struct tst_tree_t; struct tst_node_t { struct tst_node_t* children; int child_count; enum tst_node_kind kind; struct tst_tree_t* owner; void* data; }; typedef void (*tst_node_visitor_t)(struct tst_node_t*); typedef struct tst_tree_t { struct tst_node_t root; struct { int node_count; } info; metadata_t _meta; } tst_tree_t; char* tst_version_string(); tst_tree_t* tst_create_tree(struct tst_node_t root); void tst_destroy_tree(tst_tree_t* tree); struct tst_node_t tst_create_colored_node(union tst_color_t); struct tst_node_t tst_create_named_node(char name[TST_NAME_MAX_LENGTH]); void tst_destroy_node(struct tst_node_t node); void tst_add_child(struct tst_node_t* parent, struct tst_node_t child); enum tst_node_kind tst_get_node_kind(struct tst_node_t node); union tst_color_t tst_get_node_color(struct tst_node_t node); void tst_set_node_color(struct tst_node_t* node, union tst_color_t); char* tst_get_node_name(struct tst_node_t node); void tst_set_node_name(struct tst_node_t* node, char*); void tst_visit_tree_nodes(tst_tree_t* tree, tst_node_visitor_t visitor);
borodust/claw-legacy
src/cffi/c/adapter/template/static.c
<reponame>borodust/claw-legacy /* Generated by :claw at {{timestamp}} */ {{includes}} #if !defined(__CLAW_API) # if defined(_WIN32) # define __CLAW_API __declspec(dllexport) # elif defined(__GNUC__) # define __CLAW_API __attribute__((visibility("default"))) # else # define __CLAW_API # endif #endif #if defined(__cplusplus) extern "C" { #endif {{function-definitions}} #if defined(__cplusplus) } #endif
ossc-db/pg_hint_plan
make_join_rel.c
/*------------------------------------------------------------------------- * * make_join_rel.c * Routines copied from PostgreSQL core distribution with some * modifications. * * src/backend/optimizer/path/joinrels.c * * This file contains the following functions from corresponding files. * * static functions: * make_join_rel() * populate_joinrel_with_paths() * * Portions Copyright (c) 2013-2020, NIPPON TELEGRAPH AND TELEPHONE CORPORATION * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * *------------------------------------------------------------------------- */ /* * adjust_rows: tweak estimated row numbers according to the hint. */ static double adjust_rows(double rows, RowsHint *hint) { double result = 0.0; /* keep compiler quiet */ if (hint->value_type == RVT_ABSOLUTE) result = hint->rows; else if (hint->value_type == RVT_ADD) result = rows + hint->rows; else if (hint->value_type == RVT_SUB) result = rows - hint->rows; else if (hint->value_type == RVT_MULTI) result = rows * hint->rows; else Assert(false); /* unrecognized rows value type */ hint->base.state = HINT_STATE_USED; if (result < 1.0) ereport(WARNING, (errmsg("Force estimate to be at least one row, to avoid possible divide-by-zero when interpolating costs : %s", hint->base.hint_str))); result = clamp_row_est(result); elog(DEBUG1, "adjusted rows %d to %d", (int) rows, (int) result); return result; } /* * make_join_rel * Find or create a join RelOptInfo that represents the join of * the two given rels, and add to it path information for paths * created with the two rels as outer and inner rel. * (The join rel may already contain paths generated from other * pairs of rels that add up to the same set of base rels.) * * NB: will return NULL if attempted join is not valid. This can happen * when working with outer joins, or with IN or EXISTS clauses that have been * turned into joins. */ RelOptInfo * make_join_rel(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2) { Relids joinrelids; SpecialJoinInfo *sjinfo; bool reversed; SpecialJoinInfo sjinfo_data; RelOptInfo *joinrel; List *restrictlist; /* We should never try to join two overlapping sets of rels. */ Assert(!bms_overlap(rel1->relids, rel2->relids)); /* Construct Relids set that identifies the joinrel. */ joinrelids = bms_union(rel1->relids, rel2->relids); /* Check validity and determine join type. */ if (!join_is_legal(root, rel1, rel2, joinrelids, &sjinfo, &reversed)) { /* invalid join path */ bms_free(joinrelids); return NULL; } /* Swap rels if needed to match the join info. */ if (reversed) { RelOptInfo *trel = rel1; rel1 = rel2; rel2 = trel; } /* * If it's a plain inner join, then we won't have found anything in * join_info_list. Make up a SpecialJoinInfo so that selectivity * estimation functions will know what's being joined. */ if (sjinfo == NULL) { sjinfo = &sjinfo_data; sjinfo->type = T_SpecialJoinInfo; sjinfo->min_lefthand = rel1->relids; sjinfo->min_righthand = rel2->relids; sjinfo->syn_lefthand = rel1->relids; sjinfo->syn_righthand = rel2->relids; sjinfo->jointype = JOIN_INNER; /* we don't bother trying to make the remaining fields valid */ sjinfo->lhs_strict = false; sjinfo->delay_upper_joins = false; sjinfo->semi_can_btree = false; sjinfo->semi_can_hash = false; sjinfo->semi_operators = NIL; sjinfo->semi_rhs_exprs = NIL; } /* * Find or build the join RelOptInfo, and compute the restrictlist that * goes with this particular joining. */ joinrel = build_join_rel(root, joinrelids, rel1, rel2, sjinfo, &restrictlist); /* !!! START: HERE IS THE PART WHICH IS ADDED FOR PG_HINT_PLAN !!! */ { RowsHint *rows_hint = NULL; int i; RowsHint *justforme = NULL; RowsHint *domultiply = NULL; /* Search for applicable rows hint for this join node */ for (i = 0; i < current_hint_state->num_hints[HINT_TYPE_ROWS]; i++) { rows_hint = current_hint_state->rows_hints[i]; /* * Skip this rows_hint if it is invalid from the first or it * doesn't target any join rels. */ if (!rows_hint->joinrelids || rows_hint->base.state == HINT_STATE_ERROR) continue; if (bms_equal(joinrelids, rows_hint->joinrelids)) { /* * This joinrel is just the target of this rows_hint, so tweak * rows estimation according to the hint. */ justforme = rows_hint; } else if (!(bms_is_subset(rows_hint->joinrelids, rel1->relids) || bms_is_subset(rows_hint->joinrelids, rel2->relids)) && bms_is_subset(rows_hint->joinrelids, joinrelids) && rows_hint->value_type == RVT_MULTI) { /* * If the rows_hint's target relids is not a subset of both of * component rels and is a subset of this joinrel, ths hint's * targets spread over both component rels. This menas that * this hint has been never applied so far and this joinrel is * the first (and only) chance to fire in current join tree. * Only the multiplication hint has the cumulative nature so we * apply only RVT_MULTI in this way. */ domultiply = rows_hint; } } if (justforme) { /* * If a hint just for me is found, no other adjust method is * useles, but this cannot be more than twice becuase this joinrel * is already adjusted by this hint. */ if (justforme->base.state == HINT_STATE_NOTUSED) joinrel->rows = adjust_rows(joinrel->rows, justforme); } else { if (domultiply) { /* * If we have multiple routes up to this joinrel which are not * applicable this hint, this multiply hint will applied more * than twice. But there's no means to know of that, * re-estimate the row number of this joinrel always just * before applying the hint. This is a bit different from * normal planner behavior but it doesn't harm so much. */ set_joinrel_size_estimates(root, joinrel, rel1, rel2, sjinfo, restrictlist); joinrel->rows = adjust_rows(joinrel->rows, domultiply); } } } /* !!! END: HERE IS THE PART WHICH IS ADDED FOR PG_HINT_PLAN !!! */ /* * If we've already proven this join is empty, we needn't consider any * more paths for it. */ if (is_dummy_rel(joinrel)) { bms_free(joinrelids); return joinrel; } /* Add paths to the join relation. */ populate_joinrel_with_paths(root, rel1, rel2, joinrel, sjinfo, restrictlist); bms_free(joinrelids); return joinrel; } /* * populate_joinrel_with_paths * Add paths to the given joinrel for given pair of joining relations. The * SpecialJoinInfo provides details about the join and the restrictlist * contains the join clauses and the other clauses applicable for given pair * of the joining relations. */ static void populate_joinrel_with_paths(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2, RelOptInfo *joinrel, SpecialJoinInfo *sjinfo, List *restrictlist) { /* * Consider paths using each rel as both outer and inner. Depending on * the join type, a provably empty outer or inner rel might mean the join * is provably empty too; in which case throw away any previously computed * paths and mark the join as dummy. (We do it this way since it's * conceivable that dummy-ness of a multi-element join might only be * noticeable for certain construction paths.) * * Also, a provably constant-false join restriction typically means that * we can skip evaluating one or both sides of the join. We do this by * marking the appropriate rel as dummy. For outer joins, a * constant-false restriction that is pushed down still means the whole * join is dummy, while a non-pushed-down one means that no inner rows * will join so we can treat the inner rel as dummy. * * We need only consider the jointypes that appear in join_info_list, plus * JOIN_INNER. */ switch (sjinfo->jointype) { case JOIN_INNER: if (is_dummy_rel(rel1) || is_dummy_rel(rel2) || restriction_is_constant_false(restrictlist, joinrel, false)) { mark_dummy_rel(joinrel); break; } add_paths_to_joinrel(root, joinrel, rel1, rel2, JOIN_INNER, sjinfo, restrictlist); add_paths_to_joinrel(root, joinrel, rel2, rel1, JOIN_INNER, sjinfo, restrictlist); break; case JOIN_LEFT: if (is_dummy_rel(rel1) || restriction_is_constant_false(restrictlist, joinrel, true)) { mark_dummy_rel(joinrel); break; } if (restriction_is_constant_false(restrictlist, joinrel, false) && bms_is_subset(rel2->relids, sjinfo->syn_righthand)) mark_dummy_rel(rel2); add_paths_to_joinrel(root, joinrel, rel1, rel2, JOIN_LEFT, sjinfo, restrictlist); add_paths_to_joinrel(root, joinrel, rel2, rel1, JOIN_RIGHT, sjinfo, restrictlist); break; case JOIN_FULL: if ((is_dummy_rel(rel1) && is_dummy_rel(rel2)) || restriction_is_constant_false(restrictlist, joinrel, true)) { mark_dummy_rel(joinrel); break; } add_paths_to_joinrel(root, joinrel, rel1, rel2, JOIN_FULL, sjinfo, restrictlist); add_paths_to_joinrel(root, joinrel, rel2, rel1, JOIN_FULL, sjinfo, restrictlist); /* * If there are join quals that aren't mergeable or hashable, we * may not be able to build any valid plan. Complain here so that * we can give a somewhat-useful error message. (Since we have no * flexibility of planning for a full join, there's no chance of * succeeding later with another pair of input rels.) */ if (joinrel->pathlist == NIL) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("FULL JOIN is only supported with merge-joinable or hash-joinable join conditions"))); break; case JOIN_SEMI: /* * We might have a normal semijoin, or a case where we don't have * enough rels to do the semijoin but can unique-ify the RHS and * then do an innerjoin (see comments in join_is_legal). In the * latter case we can't apply JOIN_SEMI joining. */ if (bms_is_subset(sjinfo->min_lefthand, rel1->relids) && bms_is_subset(sjinfo->min_righthand, rel2->relids)) { if (is_dummy_rel(rel1) || is_dummy_rel(rel2) || restriction_is_constant_false(restrictlist, joinrel, false)) { mark_dummy_rel(joinrel); break; } add_paths_to_joinrel(root, joinrel, rel1, rel2, JOIN_SEMI, sjinfo, restrictlist); } /* * If we know how to unique-ify the RHS and one input rel is * exactly the RHS (not a superset) we can consider unique-ifying * it and then doing a regular join. (The create_unique_path * check here is probably redundant with what join_is_legal did, * but if so the check is cheap because it's cached. So test * anyway to be sure.) */ if (bms_equal(sjinfo->syn_righthand, rel2->relids) && create_unique_path(root, rel2, rel2->cheapest_total_path, sjinfo) != NULL) { if (is_dummy_rel(rel1) || is_dummy_rel(rel2) || restriction_is_constant_false(restrictlist, joinrel, false)) { mark_dummy_rel(joinrel); break; } add_paths_to_joinrel(root, joinrel, rel1, rel2, JOIN_UNIQUE_INNER, sjinfo, restrictlist); add_paths_to_joinrel(root, joinrel, rel2, rel1, JOIN_UNIQUE_OUTER, sjinfo, restrictlist); } break; case JOIN_ANTI: if (is_dummy_rel(rel1) || restriction_is_constant_false(restrictlist, joinrel, true)) { mark_dummy_rel(joinrel); break; } if (restriction_is_constant_false(restrictlist, joinrel, false) && bms_is_subset(rel2->relids, sjinfo->syn_righthand)) mark_dummy_rel(rel2); add_paths_to_joinrel(root, joinrel, rel1, rel2, JOIN_ANTI, sjinfo, restrictlist); break; default: /* other values not expected here */ elog(ERROR, "unrecognized join type: %d", (int) sjinfo->jointype); break; } /* Apply partitionwise join technique, if possible. */ try_partitionwise_join(root, rel1, rel2, joinrel, sjinfo, restrictlist); }
CCOMJHC/librosasio
include/librosasio/asio_callbackqueue.h
#pragma once #include <ros/callback_queue.h> #include <boost/asio.hpp> class AsioCallbackQueue : public ros::CallbackQueue { public: /// Default constructor #if BOOST_VERSION < 106600 AsioCallbackQueue(boost::asio::io_service& io_context); #else AsioCallbackQueue(boost::asio::io_context& io_context); #endif /// Default destrcutor. virtual ~AsioCallbackQueue() = default; virtual void addCallback(const ros::CallbackInterfacePtr& callback, uint64_t owner_id) override; #if BOOST_VERSION < 106600 static void replaceGlobalQueue(boost::asio::io_service& io_context); #else static void replaceGlobalQueue(boost::asio::io_context& io_context); #endif static void termSignalHandler(int signal_number); void handleSigTerm(const boost::system::error_code& error, std::size_t bytes_received); private: // Boost Event loop handler #if BOOST_VERSION < 106600 boost::asio::io_service& m_io_context; #else boost::asio::io_context& m_io_context; #endif static int m_sigterm_fd[2]; boost::asio::posix::stream_descriptor m_sig_term_stream; char m_socket_read_buffer = 0; };
CCOMJHC/librosasio
examples/timers/node.h
<gh_stars>0 #pragma once #include <boost/asio.hpp> #include <boost/asio/steady_timer.hpp> #include <chrono> #include <ros/timer.h> class TestNode { public: TestNode(boost::asio::io_service& io_context, ros::NodeHandle& _nh); private: void onAsioTimer(const boost::system::error_code& error); boost::asio::steady_timer m_boost_timer; ros::Timer m_periodic_timer; std::chrono::steady_clock::time_point m_start_stamp; std::chrono::steady_clock::time_point m_expected_timer_stamp; };
erikyuzwa/game-programming-start-to-finish
peon-sdk/include/graphics/PeonSceneRenderer.h
/** Peon-SDK --------- Peon-SDK - Copyright (c) 2002-2011 <NAME> - <EMAIL> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. **/ #ifndef __PEONSCENERENDERER_H_ #define __PEONSCENERENDERER_H_ #include "peonstdafx.h" #include "PeonIniConfig.h" #include "PeonVector3.h" #include "PeonSceneFont.h" #include "PeonSprite.h" namespace peon { /** * This is a small object to manage texture data within the system. */ class PEONSDK_API SceneTexture { public: /** handle to our primary key */ GLuint m_uTex; public: /** * Constructor */ SceneTexture(){}; /** * Destructor */ ~SceneTexture(){}; }; /** * This object is our overall manager for rendering to the OpenGL device. */ class PEONSDK_API SceneRenderer { protected: /** OpenGL rendering surface */ SDL_Surface* m_pOGLSurface; /** surface width */ int m_iDeviceWidth; /** surface height */ int m_iDeviceHeight; /** surface bits-per-pixel */ int m_iBitsPerPixel; /** windowed or fullscreen? */ bool m_bWindowed; /** @see Vector3 which is the eye point of the camera */ Vector3 m_vecEye; /** @see Vector3 which is the look at point of the camera */ Vector3 m_vecLookAt; /** @see Vector3 which is the up vector of the camera */ Vector3 m_vecUp; /** @see OGLTexture which is a managed list of our texture objects */ boost::ptr_list<SceneTexture> m_oTextureList; /** @see OGLFont which is a managed list of our font objects */ boost::ptr_list<SceneFont> m_oFontList; /** @see OGLSprite which is a managed display list */ boost::ptr_list<Sprite> m_oDisplayList; protected: /** * This function just returns a pixel from a given SDL_Surface object * at the given coordinates * \param surface - pointer to the SDL_Surface * \param x - int location * \param y - int location * \return the pixel value */ Uint32 getPixel(SDL_Surface *surface, int x, int y); public: /** * Constructor */ SceneRenderer(); /** * Destructor */ ~SceneRenderer(); /** * This method loads our configuration settings in order to prepare * our rendering context * \param pConfig - IniConfigReader object * \return true or false */ bool createCanvas( IniConfig* pConfig ); /** * This method deallocated and cleans up our surfaces */ void destroyCanvas(); /** * This method clears the back buffer and prepares it for us * to send rendering commands to * \return always true */ bool clearCanvas(); /** * This method is responsible for swapping our back buffer with * the front one...thereby rendering a new screen */ void flipCanvas(); /** * This method is called when our window is resized, hence * our aspect ratio may need to be updated... * \param width - int of our window * \param height - int of our window */ void restoreCanvas(int width, int height); /** * This method just loads textuer data from a given image * \param key - int handle of the texture * \param strFilename - string containing the filename * \param bAlpha - bool value, do we want alpha-blending? * \param bMipMaps - bool value, do we want mipmapping * \param bRepeat - do we want a repeating texture? * \return true or false */ bool loadTexture( int key, const string& strFilename, bool bAlpha = true, bool bMipMaps = true, bool bRepeat = false); /** * This method just sets our texture to the given handle * \param key - int of the texture we want * \return -1 if any error */ int setTexture(int key); /** * This method loads a given font data set */ bool loadFont( int key, int width = 16, int height = 16, int spacing = 14, int res_width = 640, int res_height = 480); /** * This is used for drawing / rendering text using a given font handle */ int drawText(int key, const string& strOutput, int x, int y); /** * This method is used to add a new sprite to the display list. Typically in a draw frame, * the purpose of this list is to only add the sprites that need to be drawn that frame. * \param pSprite - Sprite to add * \return true or false */ bool addSpriteToDisplayList( Sprite* pSprite ); /** * This method is used to clean the display list between frames. */ void cleanDisplayList(); /** * This method is used to set the camera for the scene * \param vecEye - the Vector3 eye point * \param vecLookAt - the Vector3 look at point * \param vecUp - the Vector3 up point */ void setCamera( Vector3& vecEye, Vector3& vecLookAt, Vector3& vecUp ); }; } #endif
erikyuzwa/game-programming-start-to-finish
peon-sdk/include/main/PeonFileLogger.h
<gh_stars>1-10 /** Peon-SDK --------- Peon-SDK - Copyright (c) 2002-2011 <NAME> - <EMAIL> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. **/ #ifndef __PEONFILELOGGER_H_ #define __PEONFILELOGGER_H_ #include "peonstdafx.h" #include "PeonISingleton.h" using namespace std; namespace peon { /** * * This object is just used to output any needed log messages to * a file. We COULD make this fancier (like a primitive Log4J * solution) by perhaps creating a LogInterface superclass, which * we can then derive FileLogger from. This would then allow us * to also create an SMTPLogger or HTMLLogger for example (to output * our log messages over SMTP or into a nice and purty HTML document). * * I made derived it from the ISingleton object in order to be * accessible pretty much everywhere in our game and/or Peon. * */ class PEONSDK_API FileLogger : public ISingleton<FileLogger> { protected: /** the file handle */ ofstream m_log_file; /** name of the file */ string m_strLogName; protected: /** * This method is responsible for writing out text to our * logfile. It should not be called directly, so it's * declared as protected. * \param strText - our desired text to append * \return void */ void writeToLogStream(const string& strText); public: /** * Default Constructor - the preferred method */ FileLogger(); /** * Destructor */ ~FileLogger(); /** Override standard Singleton retrieval. */ static FileLogger& getSingleton(void); /** Override standard Singleton retrieval. */ static FileLogger* getSingletonPtr(void); /** * This method simply opens the file handle and prepares the * log file for writing * \param strName - our desired filename * \return true if we succeeded, error code otherwise */ bool openLogStream(const string& strName); /** * This method is responsible for shutting down our logging * and closing any file handles */ void closeLogStream(); /** * This method logs a string setting it to "Info" mode. It then * compares it with the internal log setting to see if it should * be recorded or not. * \param strObject - object making logging call * \param strText - text to output */ void logInfo ( const string& strObject, const string& strText); /** * This method logs a string setting it to "Debug" mode. It then * compares it with the internal log setting to see if it should * be recorded or not. * \param strObject - object making logging call * \param strText - text to output */ void logDebug(const string& strObject, const string& strText); /** * This method logs a string setting it to "Error" mode. It then * compares it with the internal log setting to see if it should * be recorded or not. * \param strObject - object making logging call * \param strText - text to output */ void logError(const string& strObject, const string& strText); /** * This method logs a string setting it to "Fatal" mode. It then * compares it with the internal log setting to see if it should * be recorded or not. * \param strObject - object making logging call * \param strText - text to output */ void logFatal( const string& strObject, const string& strText); }; } #endif
erikyuzwa/game-programming-start-to-finish
peon-sdk/include/main/PeonEngineCore.h
/** Peon-SDK --------- Peon-SDK - Copyright (c) 2002-2011 <NAME> - <EMAIL> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. **/ #ifndef __PEONENGINECORE_H_ #define __PEONENGINECORE_H_ #include "peonstdafx.h" #include "PeonIniConfig.h" #include "PeonISingleton.h" #include "PeonIApplicationState.h" namespace peon { /** * This is the main object in the Peon SDK that you need to use for proper * use of the library and all that it brings you. For base functionality, you * only need to provide a body declaration for the core functions: * <pre> * class MainApplicationState : public IApplicationState * { * public: * MainApplicationState(); * ~MainApplicationState(); * * bool loadState(); * void unloadState(); * void drawState(); * void updateState(); * }; * </pre> * * Then just stick it in a main file in something like... * * <pre> * ##include "MainApplicationState.h" * * using namespace peon; * * int main(int argc, char* argv[]) * { * int ec = 0; * new EngineCore(); * * if(!EngineCore::getSingleton().loadEngine(APP_NAME, INI_FILE)) * { * ec = -1; goto cleanup; * } * * MainApplicationState* pMainAppState = new MainApplicationState(); * * EngineCore::getSingletonPtr()->addAppState( pMainAppState ); * * ec = EngineCore::getSingleton().runEngine(); * * cleanup: * delete EngineCore::getSingletonPtr(); * * return ec; * } * </pre> */ class PEONSDK_API EngineCore : ISingleton<EngineCore> { protected: /** @see IniConfig */ IniConfig* m_pConfig; /** @see SceneRenderer */ SceneRenderer* m_pCanvas; /** @see OGLSprite */ boost::ptr_list<Sprite> m_oDisplayList; /** @see IApplicationState */ boost::ptr_list<IApplicationState> m_oAppStateList; /** @see IApplicationState */ IApplicationState* m_pCurrentState; public: /** * Constructor */ EngineCore(); /** * Destructor */ ~EngineCore(); /** Override standard Singleton retrieval. */ static EngineCore& getSingleton(void); /** Override standard Singleton retrieval. */ static EngineCore* getSingletonPtr(void); /** * This method is used to start things up for your application. * \param strWindowTitle - text to display on window title bar * \param strIniConfig - location of .INI game configuration data * \return true or false */ bool loadEngine(const char* strWindowTitle, char* strIniConfig = NULL ); /** * This method is an internal cleanup process */ void unloadEngine(); /** * This method will be your game's "main" processing loop */ int runEngine(); /** * This method adds an IApplicationState container to our * runtime list * \param pNewState - an IApplicationState */ bool addAppState(IApplicationState* pNewState); /** * This method switches the @IApplicationState list to the * proper "runtime" one * \param id - the int of the state to switch to */ void setAppState( int id ); /** * You need to provide a body for this function, used to create any * specific objects for your game. */ virtual bool createWorld() = 0; /** * You need to provide a body for this function, used to update any * specific objects for your game. */ virtual void updateWorld() = 0; /** * You need to provide a body for this function, used to draw / render any * specific objects for your game. */ virtual void drawWorld() = 0; /** * You need to provide a body for this function, used to destroy / cleanup any * specific objects for your game. */ virtual void destroyWorld() = 0; }; } #endif
erikyuzwa/game-programming-start-to-finish
peon-sdk/include/graphics/PeonVector2.h
/** Peon-SDK --------- Peon-SDK - Copyright (c) 2002-2011 <NAME> - <EMAIL> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. **/ #ifndef __PEONVECTOR2_H_ #define __PEONVECTOR2_H_ #include "Peonstdafx.h" namespace peon { /** * This object is used to represent a 3-tuple entity for use mostly during * object positioning in a 3D gameworld. It's perfectly acceptable to keep * the z-plane variable to 1.0f, if you're only interested in using 2D * graphics. */ class PEONSDK_API Vector2 { public: /** x component */ float x; /** y component */ float y; /** * Constructor * */ Vector2(float x_ = 0.0f, float y_ = 0.0f); /** * Destructor */ ~Vector2(); /** * setter method * \param x_ : x component * \param y_ : y component */ void set(float x_, float y_); /** * calculate the length of this vector * \return float */ float length(void); /** * Normalize the vector. Divide each component by 1.0f */ void normalize(void); // Static utility methods static float distance(const Vector2 &v1, const Vector2 &v2); static float dotProduct(const Vector2 &v1, const Vector2 &v2 ); // Operators... Vector2 operator + (const Vector2 &other); Vector2 operator - (const Vector2 &other); Vector2 operator * (const Vector2 &other); Vector2 operator / (const Vector2 &other); Vector2 operator * (const float scalar); friend Vector2 operator * (const float scalar, const Vector2 &other); Vector2& operator = (const Vector2 &other); Vector2& operator += (const Vector2 &other); Vector2& operator -= (const Vector2 &other); Vector2 operator + (void) const; Vector2 operator - (void) const; }; } #endif
erikyuzwa/game-programming-start-to-finish
peon-sdk/include/main/targetver.h
<gh_stars>1-10 /** Peon-SDK --------- Peon-SDK - Copyright (c) 2002-2011 <NAME> - <EMAIL> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. **/ #pragma once // The following macros define the minimum required platform. The minimum required platform // is the earliest version of Windows, Internet Explorer etc. that has the necessary features to run // your application. The macros work by enabling all features available on platform versions up to and // including the version specified. // Modify the following defines if you have to target a platform prior to the ones specified below. // Refer to MSDN for the latest info on corresponding values for different platforms. #ifndef WINVER // Specifies that the minimum required platform is Windows Vista. #define WINVER 0x0600 // Change this to the appropriate value to target other versions of Windows. #endif #ifndef _WIN32_WINNT // Specifies that the minimum required platform is Windows Vista. #define _WIN32_WINNT 0x0600 // Change this to the appropriate value to target other versions of Windows. #endif #ifndef _WIN32_WINDOWS // Specifies that the minimum required platform is Windows 98. #define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later. #endif #ifndef _WIN32_IE // Specifies that the minimum required platform is Internet Explorer 7.0. #define _WIN32_IE 0x0700 // Change this to the appropriate value to target other versions of IE. #endif
erikyuzwa/game-programming-start-to-finish
peon-sdk/include/main/Peonstdafx.h
<reponame>erikyuzwa/game-programming-start-to-finish<filename>peon-sdk/include/main/Peonstdafx.h /** Peon-SDK --------- Peon-SDK - Copyright (c) 2002-2011 <NAME> - <EMAIL> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. **/ #ifndef __PEONSTDAFX_H_ #define __PEONSTDAFX_H_ #include "PeonDLLHeader.h" #if defined( _MSC_VER ) #include "targetver.h" #endif /*************************************************************** * Various warnings that we need to disable at a compiler level ***************************************************************/ // Turn off warnings generated by long std templates // This warns about truncation to 255 characters in debug/browse info # pragma warning (disable : 4786) // Turn off warnings generated by long std templates // This warns about truncation to 255 characters in debug/browse info # pragma warning (disable : 4503) // disable: "conversion from 'double' to 'float', possible loss of data # pragma warning (disable : 4244) // disable: "truncation from 'double' to 'float' # pragma warning (disable : 4305) // disable: "<type> needs to have dll-interface to be used by clients' # pragma warning (disable : 4251) // disable: "non dll-interface class used as base for dll-interface class" # pragma warning (disable : 4275) // disable: "C++ Exception Specification ignored" # pragma warning( disable : 4290 ) // disable: "no suitable definition provided for explicit template // instantiation request" # pragma warning( disable: 4661) // disable: deprecation warnings when using CRT calls in VC8 # pragma warning( disable: 4996) /*************************************************************** * These headers define our OpenGL subsystem and helper functions ***************************************************************/ #include <SDL.h> #include <SDL_opengl.h> #include <SDL_mixer.h> #include <SDL_image.h> #include <SDL_ttf.h> #include <boost/ptr_container/ptr_list.hpp> #include <boost/ptr_container/ptr_map.hpp> #include <cassert> #include <cstdio> #include <cstdlib> #include <ctime> #include <cstring> #include <cstdarg> #include <cmath> // STL containers #include <vector> #include <map> #include <string> #include <set> #include <list> #include <deque> #include <queue> // STL algorithms & functions #include <algorithm> #include <functional> #include <limits> // C++ Stream stuff #include <fstream> #include <iostream> #include <iomanip> #include <sstream> /** * These following blocks of preproccessor statements are used to * wrap around statements for cleaning up either pointers or * arrays of allocated elements. */ #define PEON_DELETE(p) { if(p) { delete (p); (p)=NULL; } } #define PEON_DELETE_ARRAY(p) { if(p) { delete[] (p); (p)=NULL; } } /** * The following block of preprocessor statements give us a bit of a hand * when we want to do some radian to degree (or vice versa) conversions. Nothing * fancy here. */ #define PEON_PI 3.141592654f #define PEON_DEGTORAD(degree) ((degree) * (PEON_PI / 180.0f)) #define PEON_RADTODEG(radian) ((radian) * (180.0f / PEON_PI)) namespace peon { class AudioEngine; class FileLogger; class IniConfig; class EngineCore; class Matrix33; class Matrix44; class MusicNode; class SoundFxNode; class SceneRenderer; class SceneFont; class Sprite; class SceneTexture; class Vector2; class Vector3; class Vector4; } #endif
erikyuzwa/game-programming-start-to-finish
chapter_01/sample.h
<gh_stars>1-10 #ifndef __SAMPLE_H_ #define __SAMPLE_H_ /** * \mainpage Sample Documentation * * \section intro_sec Introduction * * This sample documentation demonstrates just how flexible, intelligent and * usefull the Doxygen tool is. * * Let's face it. Documenting your code is a pain, but we all know that it's * a critical necessity for both support reasons and for communicating with * others the purpose/goal of your code. * * \section install_sec Installation * * After installing the doxygen compiler, simply type * <b>doxygen sample.cfg</b> to generate this sample documentation * */ #endif
erikyuzwa/game-programming-start-to-finish
peon-sdk/include/main/PeonDLLHeader.h
/** Peon-SDK --------- Peon-SDK - Copyright (c) 2002-2011 <NAME> - <EMAIL> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. **/ #ifndef __PEONDLLHEADER_H_ #define __PEONDLLHEADER_H_ // The following ifdef block is the standard way of creating macros which make exporting // from a DLL simpler. All files within this DLL are compiled with the PEONSDK_EXPORTS // symbol defined on the command line. this symbol should not be defined on any project // that uses this DLL. This way any other project whose source files include this file see // PEONSDK_API functions as being imported from a DLL, whereas this DLL sees symbols // defined with this macro as being exported. #ifdef PEONSDK_EXPORTS #define PEONSDK_API __declspec(dllexport) #else #define PEONSDK_API __declspec(dllimport) #endif #endif
erikyuzwa/game-programming-start-to-finish
peon-sdk/include/audio/PeonAudioEngine.h
/** Peon-SDK --------- Peon-SDK - Copyright (c) 2002-2011 <NAME> - <EMAIL> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. **/ #ifndef __PEONAUDIOENGINE_H_ #define __PEONAUDIOENGINE_H_ #include "PeonISingleton.h" using namespace std; namespace peon { /** * This object is used to handle and encapsulate basic sound effects in a game. * Load up a blaster, level-up or any other sound here */ class PEONSDK_API SoundFxNode { public: /** the primary "id" handle of this sound effect */ int m_key; /** the pointer to the actual sound data */ Mix_Chunk* m_pData; /** the channel this sound effect is using */ int m_channel; public: /** * Constructor */ SoundFxNode(); /** * Destructor */ ~SoundFxNode(); }; /** * This object is used to handle and encapsulate basic music media. * Background music tracks, etc., should probably be using this * object. */ class PEONSDK_API MusicNode { public: /** the primary handle "id" of this music track */ int m_key; /** the actual data of this music track */ Mix_Music* m_pData; public: /** * Constructor */ MusicNode(); /** * Destructor */ ~MusicNode(); }; /** * This object is used to encapsulate our audio hardware. It should * be able to play both MIDI tunes (yes people still use 'em) and * OGG/WAV files. * * The goal of the object is to scan and load up all the desired * media for your game using the .INI configuration file passed * into this object. * */ class PEONSDK_API AudioEngine : public ISingleton<AudioEngine> { protected: /** do we enable/disable sound? Note this only affects OGG and WAV playback */ bool m_bEnableSound; /** do we enable/disable music? Note this only affects MIDI playback */ bool m_bEnableMusic; /** is our audio hardware even supported? */ bool m_bAudioSupported; /** Just a boolean value if EAX is supported or not by the audio layer */ bool m_bIsEAXSupported; /** a list of our MIDI / MP3 / OGG data */ boost::ptr_list<MusicNode> m_oMusicList; /** a list of our WAV sound effect data */ boost::ptr_list<SoundFxNode> m_oSoundFxList; public: /** * Constructor */ AudioEngine(); /** * Destructor */ ~AudioEngine(); /** Override standard Singleton retrieval. */ static AudioEngine& getSingleton(void); /** Override standard Singleton retrieval. */ static AudioEngine* getSingletonPtr(void); /** * This method loads and instantiates the subsystems necessary in * SDL_Mixer and OpenAL to get a device working for each. If the * initialization fails, then you can decide if you want to just * disable all sound, or quit the app entirely. * \param pConfig - The INI information * \return true if audio loaded properly */ bool loadEngine( IniConfig* pConfig ); /** * This method frees up our allocated audio resources */ void unloadEngine(); /** * This method makes the necessary calls to load up a * Mix_Music instance which is used for playback of * MIDI / OGG / MP3 files * \param int - key to store this music data as * \param strFilename - path to the MIDI file * \return error code of any problems */ int loadMusic( int key, const string& strFilename ); /** * This method makes the necessary calls to load up a * Mix_Chunk instance which is used for playback of * MIDI files * \param int key - key to store this sound data as * \param strFilename - path to the WAV file * \return error code of any problems */ int loadSoundFx( int key, const string& strFilename ); /** * This method is used to start the desired sound * effect using the handle / key. * \param key - int value of the key to play * \param loop - true / false * \return error code of any problems */ int startSoundFx( int key, bool loop = false ); /** * This method is used to start the desired music * track using the handle / key. * \param key - int value of the key to play * \param loop - true / false * \return error code of any problems */ int startMusic( int key, bool loop = true ); /** * This method stops the desired playback of the * sound effect * \param key - the int value of the key to stop * \return error code of any problems */ int stopSoundFx( int key ); /** * This method stops the desired playback of the * music track * \param key - the int value of the key to stop * \return error code of any problems */ int stopMusic( int key ); /** * This method just enables the global audio mask */ void enableSound(){ m_bEnableSound = true; } /** * This method disables the global audio mask */ void disableSound(){ m_bEnableSound = false; } /** * This method enables the global music mask */ void enableMusic(){ m_bEnableMusic = true; } /** * This method disables the global music mask */ void disableMusic(){ m_bEnableMusic = false; } }; } #endif
erikyuzwa/game-programming-start-to-finish
peon-sdk/include/graphics/PeonVector4.h
/** Peon-SDK --------- Peon-SDK - Copyright (c) 2002-2011 <NAME> - <EMAIL> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. **/ #ifndef __PEONVECTOR4_H_ #define __PEONVECTOR4_H_ #include "Peonstdafx.h" namespace peon { /** * This object is used as a 4-tuple. So far it's mainly just used for * lighting purposes in the @see SceneLight object, but it could also perhaps * be used to store RGBA color information... * */ class PEONSDK_API Vector4 { public: /** x component */ float x; /** y component */ float y; /** z component */ float z; /** w component */ float w; /** * Constructor */ Vector4(float x_ = 0.0f, float y_ = 0.0f, float z_ = 0.0f, float w_ = 0.0f); /** * Destructor */ ~Vector4(); void set(float x_, float y_, float z_, float w_); float length(void); void normalize(void); // Static utility methods static float distance(const Vector4 &v1, const Vector4 &v2); static float dotProduct(const Vector4 &v1, const Vector4 &v2 ); static Vector4 crossProduct(const Vector4 &v1, const Vector4 &v2); // Operators... Vector4 operator + (const Vector4 &other); Vector4 operator - (const Vector4 &other); Vector4 operator * (const Vector4 &other); Vector4 operator / (const Vector4 &other); Vector4 operator * (const float scalar); friend Vector4 operator * (const float scalar, const Vector4 &other); Vector4& operator = (const Vector4 &other); Vector4& operator += (const Vector4 &other); Vector4& operator -= (const Vector4 &other); Vector4 operator + (void) const; Vector4 operator - (void) const; }; } #endif
erikyuzwa/game-programming-start-to-finish
peon-sdk/include/PeonSDK.h
/** Peon-SDK --------- Peon-SDK - Copyright (c) 2002-2011 <NAME> - <EMAIL> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. **/ #ifndef __PEONSDK_H_ #define __PEONSDK_H_ /** * \mainpage Peon SDK * * \section intro_sec Introduction * * The Peon SDK collection of objects is meant to help the beginner learn and * understand the fundamentals of game programming. The goal of the engine * is to help you do things.<strong>It is not meant to be a heavy framework</strong>. * * I'm not against other frameworks (don't get me wrong), but sometimes they * become so laden and burdened that it becomes difficult for the newbie * to simply pick up the codebase and run with it quickly. * * \section license_sec License * * This game development SDK is licensed under the Creative Commons License. * * * \section dll_sec DLL * * Why is this a Dynamically Linked Library? * Although the <a href="http://wwww.libsdl.org/">Simple DirectMedia Layer</a> that the PeonSDK is built upon * is a platform independent library, the Win32 version of the Peon SDK * library compiles as a DLL. I chose this route, simply because it can make * the support of this library easier in terms of upgrades for any customer * buying/using your game built with Peon. Because the code links with the * DLL during the runtime of your game, you are free to update/upgrade any * code within so long as you don't change how the functions/classes are * interfaced with your modules. * * \section dependencies_sec Dependencies * * The Peon SDK library/collection of objects is built upon some existing popular * libraries that are already being used by professional game developers today! * * <i>Note: The license that comes with Peon SDK only covers the Peon SDK library itself. * Each dependency has its own licensing terms that you are responsible for.</i> * * For the most part these are all successfull open source projects which * are released under the LGPL (the same as Peon). Provided you retain the * copyright headers of each project you can still release commercial * software using them and retain all the bling. * * Here is a list of links to each of the license information pages * for any dependent sub-projects the Peon library includes/uses. * * * - SDL : <a href="http://www.libsdl.org/license.php">SDL v1.2.13</a> * - Boost : <a href="http://www.boost.org/">Boost</a> * * \section install_sec Installation * * Check Appendix A in the book <b><i><a href="http://gameprogrammingstarttofinish.wazooinc.com/">"Game Programming in C++: Start To Finish"</a></i></b> for * some instructions on getting this setup. * * Generally just make sure you let your IDE know where to find the /PeonSDK/include * and /PeonSDK/lib folder. The /PeonSDK/lib folder contains the compiled * version of this library, along with the DLL's that you need to distribute with * any application using Peon. * * Having your installer copy them to the customer's windows\system32 folder is * an option, or you can leave them all in the same folder as your binary executable. * The choice is yours and just depends on how you want to support your own product. * ie. your installer should "be nice" and remove them during an uninstall of * your game, etc. * * \section building_sec Building the Library * * There should be the necessary project files for building the Peon library * in: * - Visual Studio .NET 2005 : PeonSDK_Home\win32\VS2005\PeonSDK_vs2005.sln * - Visual Studio .NET 2008 : PeonSDK_Home\win32\VS2008\PeonSDK_vs2008.sln * * * \section usage_sec General Usage * * * The general usage for this library is meant to be (hopefully) very simple as * I mentioned above. The basic practice is: * * - Derive a new application instance from IApplicationState * - Toss it into the EngineCore * - Enjoy game programming! * * * Note: Always check <a href="http://www.erikyuzwa.com">http://www.erikyuzwa.com</a> for * the latest version of this library and any updates. * * \section further_sec Further Resources * * For additional resources into 3D engines, feel free to download and inspect * the source code to these awesome engines. * * <i>Note that this list is not ranked in any order</i> * * - <a href="http://www.ogre3d.com">Ogre3D - a rendering engine capable of OpenGL/D3D support</a> * - <a href="http://irrlicht.sourceforge.net/">Irrlicht</a> * - <a href="http://www.genesis3d.com/">Genesis3D</a> * - <a href="http://www.crystalspace3d.org/tikiwiki/tiki-view_articles.php">Crystal Space 3D</a> * - <a href="http://www.geometrictools.com">Wild Magic Software</a> - A fantastic collection of * helpful open source math objects, and some additional rendering and pipeline design code. * * For a further list of 3D engines and their specifications, be sure * to also visit the 3D engines database maintained at <a href="http://www.devmaster.net/engines">Devmaster.net</a>. * */ #include "main/Peonstdafx.h" #include "audio/PeonAudioEngine.h" #include "main/PeonIniConfig.h" #include "main/PeonEngineCore.h" #include "main/PeonFileLogger.h" #include "graphics/PeonMatrix44.h" #include "graphics/PeonMatrix33.h" #include "graphics/PeonSceneRenderer.h" #include "graphics/PeonSceneFont.h" #include "graphics/PeonSprite.h" #include "graphics/PeonVector2.h" #include "graphics/PeonVector3.h" #include "graphics/PeonVector4.h" /* // This class is exported from the PeonSDK.dll class PEONSDK_API CPeonSDK { public: CPeonSDK(void); // TODO: add your methods here. }; extern PEONSDK_API int nPeonSDK; PEONSDK_API int fnPeonSDK(void); */ #endif
erikyuzwa/game-programming-start-to-finish
peon-sdk/include/graphics/PeonSprite.h
<reponame>erikyuzwa/game-programming-start-to-finish<filename>peon-sdk/include/graphics/PeonSprite.h /** Peon-SDK --------- Peon-SDK - Copyright (c) 2002-2011 <NAME> - <EMAIL> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. **/ #ifndef __PEONSPRITE_H_ #define __PEONSPRITE_H_ #include "peonstdafx.h" #include "peonvector2.h" #include "peonvector3.h" namespace peon { /*** * This is our base sprite object */ class PEONSDK_API Sprite { public: /** @see Vector3 position */ Vector3 m_vecPos; /** @see Vector2 bounding box for collisions */ Vector2 m_vecBBox; /** is our sprite alive or dead? */ bool m_bIsAlive; public: /** * Constructor */ Sprite(); /** * Destructor */ virtual ~Sprite(); /** * This method sets the position of the sprite * \param x - float pos * \param y - float pos * \param z - float pos */ void setPosition( float x, float y, float z); /** * Check if the sprite is alive / dead * \return alive or dead */ bool isAlive(){ return m_bIsAlive; } }; } #endif
erikyuzwa/game-programming-start-to-finish
chapter_01/HealthObj.h
<reponame>erikyuzwa/game-programming-start-to-finish #ifndef __HEALTHOBJ_H_ #define __HEALTHOBJ_H_ /*! * \brief This object modifies an entity's hit points * * The purpose of this object is to hang around in your game world * until the Player picks it up. Depending upon how much health * points the instance of this object is worth, it is added or * subtracted to the player's overall health score */ class HealthObj : public ObjA { public: /*! * constructor */ HealthObj(); /*! * destructor */ virtual ~HealthObj(); //comment blocks can also begin with... /** * This method places our object in the game world along * with assigning it a health value * @param x - x position * @param y - y position * @param z - z position * @param h - health * @return true or false if this object was allowed */ bool setPosition( float x, float y, float z, int h ); //snip! }; #endif
erikyuzwa/game-programming-start-to-finish
peon-sdk/include/main/PeonIniConfig.h
<reponame>erikyuzwa/game-programming-start-to-finish<filename>peon-sdk/include/main/PeonIniConfig.h /** Peon-SDK --------- Peon-SDK - Copyright (c) 2002-2011 <NAME> - <EMAIL> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. **/ #ifndef __PEONINICONFIGREADER_H_ #define __PEONINICONFIGREADER_H_ // Precompiler options #include "peonstdafx.h" using namespace std; namespace peon { /* This object is useful for loading and storing any information * we might need for our game contained in an .INI file. We can * store anything from our wanted renderer, to our application window * size, to even some basic scripting elements. * * Note that this object is completely Win32-specific. It is using * the GetPrivateProfile* family of API functions which I think are * only available on Windows. */ class PEONSDK_API IniConfig { protected: /** our INI filename */ string m_strFileName; public: /** * Constructor * \param strFile - path to INI file */ IniConfig(const string& strFile); /** * Destructor */ ~IniConfig(); /** * \brief This method is responsible for grabbing any string data from our * INI file * \param sSection our INI section * \param sKey our key name * \param sDefault our default key value * \param sReturn a string object to contain our resulting data * \return the size of our data string */ DWORD getString(const string sSection, const string sKey, const string sDefault, string& sReturn); /** * \brief This method is just responsible for grabbing the UINT value * from our INI file * \param sSection section name * \param sKeyName key name * \param keyval default key value * \return our returned key value */ UINT getInt(const string sSection, const string sKeyName, int keyval); /** * \brief This method is responsible for grabbing any boolean information * stored in our INI file * \param sSection section name * \param sKeyName key name * \param sDefault default key value "TRUE" or "FALSE" * \return our actual key value */ bool getBool(const string sSection, const string sKeyName, const string sDefault); /** * \brief This method is responsible for grabbing any float information stored * in our INI file * \param sSection section name * \param sKeyName key name * \param sDefault default value of float (ie. "1.0f") * \return our determined float value */ float getFloat(const string sSection, const string sKeyName, const string sDefault); }; } #endif
erikyuzwa/game-programming-start-to-finish
peon-sdk/include/main/PeonISingleton.h
/** Peon-SDK --------- Peon-SDK - Copyright (c) 2002-2011 <NAME> - <EMAIL> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. **/ #ifndef __PEONISINGLETON_H__ #define __PEONISINGLETON_H__ /* Original version Copyright (C) <NAME>, 2000. * All rights reserved worldwide. * * This software is provided "as is" without express or implied * warranties. You may freely copy and compile this source into * applications you distribute provided that the copyright text * below is included in the resulting source code, for example: * "Portions Copyright (C) <NAME>, 2000" */ #include "Peonstdafx.h" namespace peon { /** * Template class for creating single-instance global classes. * The code in this file is taken from article 1.3 in the the book: * Game Programming Gems from Charles River Media with the * copyright notice going to Scott Bilas. */ template <typename T> class PEONSDK_API ISingleton { protected: /** The static member object */ static T* ms_Singleton; public: /** * Constructor */ ISingleton( void ) { assert( !ms_Singleton ); ms_Singleton = static_cast< T* >( this ); } /** * Destructor */ ~ISingleton( void ) { assert( ms_Singleton ); ms_Singleton = 0; } /** * This method just returns the internal member by * reference * \return T& - reference to internal abstract Type */ static T& getSingleton( void ) { assert( ms_Singleton ); return ( *ms_Singleton ); } /** * This method just returns the internal member by * a pointer * \return T* - pointer to the internal abstract Type */ static T* getSingletonPtr( void ) { return ms_Singleton; } }; } #endif
erikyuzwa/game-programming-start-to-finish
peon-sdk/include/graphics/PeonMatrix33.h
/** Peon-SDK --------- Peon-SDK - Copyright (c) 2002-2011 <NAME> - <EMAIL> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. **/ #ifndef __PEONMATRIX33_H_ #define __PEONMATRIX33_H_ #include "Peonstdafx.h" #include "PeonVector3.h" namespace peon { /** * This is a bare-bones Matrix object which is of size 3x3. * It's not optimized, so use at your own risk but it demonstrates * how to use some basic matrix operations. * * The matrix is column-major which is exactly how the matrices are * represented in OpenGL. If you're porting this library over to * Direct3D, just remember that Direct3D's format is row-major. * * For other math libraries, check out the Ogre project, the * Irrlicht engine or even the basic objects found at Wild Magic Software. */ class PEONSDK_API Matrix33 { public: /** our matrix data. It's in one contiguous element block. Even though, * we're using a 3x3 matrix, we're just using a subset of a 4x4. */ float m[16]; /** * Constructor */ Matrix33(){ } /** * Constructor containing given values */ Matrix33( float m0, float m3, float m6, float m1, float m4, float m7, float m2, float m5, float m8); void identity(void); void translate(const Vector2 &trans); void translate_x(const float &dist); void translate_y(const float &dist); void translate_z(const float &dist); void rotate(const float &angle, Vector2 &axis); void rotate_x(const float &angle); void rotate_y(const float &angle); void rotate_z(const float &angle); void scale(const Vector2 &scale); void transformPoint( Vector2 *vec ); void transformVector( Vector2 *vec ); // Operators... Matrix33 operator + (const Matrix33 &other); Matrix33 operator - (const Matrix33 &other); Matrix33 operator * (const Matrix33 &other); Matrix33 operator * (const float scalar); }; } #endif
erikyuzwa/game-programming-start-to-finish
peon-sdk/include/graphics/PeonSceneFont.h
<gh_stars>1-10 /** Peon-SDK --------- Peon-SDK - Copyright (c) 2002-2011 <NAME> - <EMAIL> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. **/ #ifndef __PEONSCENEFONT_H_ #define __PEONSCENEFONT_H_ #include "peonstdafx.h" using namespace std; namespace peon { /** * This object of the Peon library is meant to encapsulate a textured * font object for your game. You provide it with a bitmap image * of the alphabet you want to use (in ASCII format), then just notify * this object of the dimensions of the bitmap. ie. how many rows * and columns of characters there are, along with the pixel width * and height of a single character. * * This object is based off of the GLFont object made available by Jeff * Molofee (aka. Nehe) at http://nehe.gamedev.net, an excellent * repository of OpenGL tutorials. */ class PEONSDK_API SceneFont { public: /** key value used to identify this font object */ int m_iKey; protected: /** display list to contain alphabet */ GLuint m_display_list; /** width of a single character */ int m_char_width; /** height of a single character */ int m_char_height; /** spacing between characters */ int m_char_spacing; /** how many characters in a line/row */ int m_fxCount; /** how many characters in a column */ int m_fyCount; /** the current red color when rendering our text*/ float m_r; /** the current green color when rendering our text*/ float m_g; /** the current blue color when rendering our text*/ float m_b; /** the current alpha color when rendering our text*/ float m_a; /** the current resolution width */ int m_iResWidth; /** the current resolution height */ int m_iResHeight; public: /** * Constructor */ SceneFont(); /** * Destructor */ ~SceneFont(); /** * This method is responsible for loading up our SceneFont * instance. * \param width - * \param height - * \param spacing - * \param res_width - * \param res_height - * \return true if everything loaded properly */ bool createFont(int width = 16, int height = 16, int spacing = 14, int res_width = 640, int res_height = 480); /** * This method is just used to unload our SceneFont instance */ void destroyFont(); /** * This method is the "workhorse" which renders our text. We * specify the x and y position of the text and that's where * the SceneFont will render it! * \param xpos - x position of text * \param ypos - y position of text * \param strText - our text to render */ void drawText(int xpos, int ypos, const string& strText); /** * This method just sets our color components in case we want * to apply any color to the text we're about to render. * \param r - red component * \param g - green component * \param b - blue component * \param a - alpha component */ void setColor( float r = 1.0f, float g = 1.0f, float b = 1.0f, float a = 1.0f); }; } #endif
erikyuzwa/game-programming-start-to-finish
peon-sdk/include/main/PeonIApplicationState.h
<gh_stars>1-10 /** Peon-SDK --------- Peon-SDK - Copyright (c) 2002-2011 <NAME> - <EMAIL> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. **/ #ifndef __PEONIAPPLICATIONSTATE_H_ #define __PEONIAPPLICATIONSTATE_H_ #include "peonstdafx.h" namespace peon { /** * The game should be broken down into seperate states which then are used to govern the behaviour * allowed in each state. This keeps things isolated and as modular as possible */ class PEONSDK_API IApplicationState { protected: /** primary key */ int m_iID; public: /** constructor */ IApplicationState(int key = 0); /** destructor */ virtual ~IApplicationState(); /** * return the id of this state * \return the state id */ int getID(){ return m_iID; } /** * \brief set the ID of this application state * \param newID - the new ID of this application state */ void setID(int newID){ m_iID = newID; } /** * \brief call this method to load the initial state * \return true if things are ok */ virtual bool loadState(){ return true; }; /** * \brief call this method to unload the state */ virtual void unloadState(){}; /** * \brief call this method to update the state * \param fTimeKey - the time differential between frames */ virtual void updateState(float fTimeKey){}; /** * \brief this method is used to render this state */ virtual void drawState(){}; /** * This method provides quick keyboard access to the * current state * \param pEvent - a generated SDL_KeyboardEvent handle */ virtual void onKeyEvent( SDL_KeyboardEvent* pEvent ){} /** * This method provides quick mouse access to the * current state * \param pEvent - a generated SDL_Event message */ virtual void onMouseEvent( SDL_Event* pEvent ){} }; } #endif
erikyuzwa/game-programming-start-to-finish
chapter_16/Basic3DS/MeshFactory.h
<gh_stars>1-10 #ifndef __MESHFACTORY_H_ #define __MESHFACTORY_H_ #include "PeonMain.h" // Primary Chunk, at the beginning of each file #define PRIMARY 0x4D4D // Main Chunks #define OBJECTINFO 0x3D3D #define VERSION 0x0002 #define EDITKEYFRAME 0xB000 // Sub defines of OBJECTINFO #define MATERIAL 0xAFFF #define OBJECT 0x4000 // Sub defines of MATERIAL #define MATNAME 0xA000 #define MATDIFFUSE 0xA020 #define MATMAP 0xA200 #define MATMAPFILE 0xA300 #define OBJECT_MESH 0x4100 // Sub defines of OBJECT_MESH #define OBJECT_VERTICES 0x4110 #define OBJECT_FACES 0x4120 #define OBJECT_MATERIAL 0x4130 #define OBJECT_UV 0x4140 namespace peon { ////////////////////////////////////// //The sFace Struct ////////////////////////////////////// struct sFace { int vertIndex[3]; int coordIndex[3]; }; ////////////////////////////////////// //The sMaterialInfo Struct ////////////////////////////////////// struct sMaterialInfo { char strName[255]; char strFile[255]; BYTE color[3]; int texureId; float uTile; float vTile; float uOffset; float vOffset; }; ////////////////////////////////////// //The s3DObject Struct ////////////////////////////////////// struct s3DObject { int numOfVerts; int numOfFaces; int numTexVertex; int materialID; bool bHasTexture; char strName[255]; UINT *pIndices; Vector3 *pVerts; Vector3 *pNormals; Vector2 *pTexVerts; sFace *pFaces; }; ////////////////////////////////////// //The s3DModel Struct ////////////////////////////////////// struct s3DModel { int numOfObjects; int numOfMaterials; vector<sMaterialInfo> pMaterials; vector<s3DObject> pObject; }; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Here is our structure for our 3DS indicies (since .3DS stores 4 unsigned shorts) ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct sIndices { unsigned short a, b, c, bVisible; }; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // This holds the chunk info ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct sChunk { unsigned short int ID; unsigned int length; unsigned int bytesRead; }; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // This class handles all of the loading code ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class MeshFactory { public: MeshFactory(); ~MeshFactory(); bool Import3DS(s3DModel *pModel, char *strFileName); private: int GetString(char *); void ReadChunk(sChunk *); void ProcessNextChunk(s3DModel *pModel, sChunk *); void ProcessNextObjectChunk(s3DModel *pModel, s3DObject *pObject, sChunk *); void ProcessNextMaterialChunk(s3DModel *pModel, sChunk *); void ReadColorChunk(sMaterialInfo *pMaterial, sChunk *pChunk); void ReadVertices(s3DObject *pObject, sChunk *); void ReadVertexIndices(s3DObject *pObject, sChunk *); void ReadUVCoordinates(s3DObject *pObject, sChunk *); void ReadObjectMaterial(s3DModel *pModel, s3DObject *pObject, sChunk *pPreviousChunk); void ComputeNormals(s3DModel *pModel); void CleanUp(); FILE *m_FilePointer; sChunk *m_CurrentChunk; sChunk *m_TempChunk; }; } #endif
erikyuzwa/game-programming-start-to-finish
peon-sdk/include/graphics/PeonVector3.h
<filename>peon-sdk/include/graphics/PeonVector3.h /** Peon-SDK --------- Peon-SDK - Copyright (c) 2002-2011 <NAME> - <EMAIL> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. **/ #ifndef __PEONVECTOR3_H_ #define __PEONVECTOR3_H_ #include "Peonstdafx.h" namespace peon { /** * This object is used to represent a 3-tuple entity for use mostly during * object positioning in a 3D gameworld. It's perfectly acceptable to keep * the z-plane variable to 1.0f, if you're only interested in using 2D * graphics. */ class PEONSDK_API Vector3 { public: /** x component */ float x; /** y component */ float y; /** z component */ float z; /** * Constructor * */ Vector3(float x_ = 0.0f, float y_ = 0.0f, float z_ = 0.0f); /** * Destructor */ ~Vector3(); /** * setter method * \param x_ : x component * \param y_ : y component * \param z_ : z component */ void set(float x_, float y_, float z_); /** * calculate the length of this vector * \return float */ float length(void); /** * Normalize the vector. Divide each component by 1.0f */ void normalize(void); // Static utility methods static float distance(const Vector3 &v1, const Vector3 &v2); inline float dotProduct(const Vector3& vec) const { return x * vec.x + y * vec.y + z * vec.z; } inline Vector3 crossProduct( const Vector3& vecInput ) const { Vector3 vecCross; vecCross.x = y * vecInput.z - z * vecInput.y; vecCross.y = z * vecInput.x - x * vecInput.z; vecCross.z = x * vecInput.y - y * vecInput.x; return vecCross; } // Operators... Vector3 operator + (const Vector3 &other); Vector3 operator - (const Vector3 &other); Vector3 operator * (const Vector3 &other); Vector3 operator / (const Vector3 &other); Vector3 operator / (const float scalar); Vector3 operator * (const float scalar); friend Vector3 operator * (const float scalar, const Vector3 &other); Vector3& operator = (const Vector3 &other); Vector3& operator += (const Vector3 &other); Vector3& operator -= (const Vector3 &other); Vector3 operator + (void) const; Vector3 operator - (void) const; }; } #endif
TXQDM/BeagleBone_I2C_Library
Main.c
/* * Main.c * * Created on: Sep 6, 2017 * Author: <NAME> */ /* Lib Includes */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> /* Header Files */ #include "I2C.h" /* Definitions*/ #define SSD1306_OLED_ADDR 0x3C #define SSD1306_CNTRL_CMD 0x00 /* Externs - I2C.c */ extern I2C_DeviceT I2C_DEV_2; /* Debug Definitions */ #define I2C_DBG_INIT //#define I2C_DBG_SINGLE_WRITE #define I2C_DBG_MULTIPLE_WRITES //#define I2C_DBG_DUAL_WRITE #ifdef I2C_DBG_MULTIPLE_WRITES unsigned char Test_buff[]={0xFF, 0xA0, 0xAA, 0xF0, 0x0F}; #define TEST_BUFF_SIZE sizeof(Test_buff) #endif int main() { #ifdef I2C_DBG_INIT if(init_i2c_dev2(SSD1306_OLED_ADDR) == 0) { printf("(Main)i2c-2: Bus Connected to SSD1306\r\n"); } else { printf("(Main)i2c-2: OOPS! Something Went Wrong\r\n"); exit(1); } #endif while(1) { #ifdef I2C_DBG_SINGLE_WRITE if(i2c_write(I2C_DEV_2.fd_i2c,0x55) == I2C_ONE_BYTE) { printf("(Main)i2c-2: Single Write Test Passed\r\n"); } else { printf("(Main)i2c-2: Single Write Test Failed\r\n"); //exit(1); } #endif #ifdef I2C_DBG_DUAL_WRITE if(i2c_write_register(I2C_DEV_2.fd_i2c, SSD1306_CNTRL_CMD, 0xA0 ) == I2C_TWO_BYTES) { printf("(Main)i2c-2: Dual Write Test Passed\r\n"); } else { printf("(Main)i2c-2: Dual Write Test Failed\r\n"); //exit(1); } #endif #ifdef I2C_DBG_MULTIPLE_WRITES if(i2c_multiple_writes(I2C_DEV_2.fd_i2c, TEST_BUFF_SIZE, Test_buff) == TEST_BUFF_SIZE) { printf("(Main)i2c-2: Multiple Write Test Passed\r\n"); } else { printf("(Main)i2c-2: Multiple Write Test Failed\r\n"); //exit(1); } #endif /*1 sec delay between transactions */ usleep(1000000); } return 0; }
Tap-Payments/TapAdditionsKit-iOS
TapAdditionsKit/TapAdditionsKit.h
<reponame>Tap-Payments/TapAdditionsKit-iOS // // TapAdditionsKit.h // TapAdditionsKit // // Copyright © 2019 Tap Payments. All rights reserved. // @import Foundation.NSObjCRuntime; //! Project version number for TapAdditionsKit. FOUNDATION_EXPORT double TapAdditionsKitVersionNumber; //! Project version string for TapAdditionsKit. FOUNDATION_EXPORT const unsigned char TapAdditionsKitVersionString[];
mh-dev/esp32_reusable_components
app/main/app.c
#include <stdio.h> #include <awesome_component.h> void app_main() { int result = awesome_component_add(123, 321); printf("Result %d\n", result); }
mh-dev/esp32_reusable_components
custom-components/components/awesome_component/include/awesome_component.h
#ifndef _AWESOME_COMPONENT_H_ #define _AWESOME_COMPONENT_H_ int awesome_component_add(int number1, int number2); #endif
mh-dev/esp32_reusable_components
custom-components/components/awesome_component/test/test_awesome_component.c
<filename>custom-components/components/awesome_component/test/test_awesome_component.c #include "unity.h" #include "awesome_component.h" TEST_CASE("add_successful", "[awesome_component]") { int number1 = 123; int number2 = 321; int result = awesome_component_add(number1, number2); TEST_ASSERT_EQUAL_INT32(444, result); }
mh-dev/esp32_reusable_components
custom-components/components/awesome_component/src/awesome_component.c
<reponame>mh-dev/esp32_reusable_components #include "awesome_component.h" int awesome_component_add(int number1, int number2) { return number1 + number2; }
nestlabs/nlplatform
src/nlfault.c
/* * * Copyright (c) 2015-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file defines APIs used in fault preservation. * */ #include <nlplatform.h> #include <nlplatform/nlfault.h> #include <assert.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <nlassert.h> /* Do the stack intensive stuff in a helper function that * can unwind before the actual trap, so that the fault * handler has a larger stack. This is needed for asserts * in ISRs to work with a minimal main stack or else * printfs in the fault handler can double fault. */ static void assert_helper(const char *file, unsigned line) __attribute__((noinline)); static void assert_helper(const char *file, unsigned line) { #ifdef BUILD_FEATURE_RESET_INFO char tmp[NL_FAULT_DIAGS_DESCRIPTION_LENGTH]; char line_string[11]; // 32-bit value should fit in 10 characters plus null-terminator size_t file_len = strlen(file); size_t line_len; size_t max_file_len; // first convert the line number to a string utoa(line, line_string, 10); line_len = strlen(line_string); // reserve enough room for the line string, truncating the // file name if needed, with a space in between and a NULL terminator max_file_len = NL_FAULT_DIAGS_DESCRIPTION_LENGTH - line_len - 2; if (file_len > max_file_len) { #ifndef NL_BOOTLOADER // Doesn't fit in bootloader // truncate file name from the end file = file + file_len - max_file_len; #endif file_len = max_file_len; } // copy (possibly truncated) file name strncpy(tmp, file, file_len); // add space tmp[file_len] = ' '; // append line_length. strncpy(tmp + file_len + 1, line_string, NL_FAULT_DIAGS_DESCRIPTION_LENGTH - file_len - 1); nl_reset_info_prepare_reset(NL_RESET_REASON_ASSERT, tmp); #endif /* BUILD_FEATURE_RESET_INFO */ printf("assert failed: file %s, line %u\n", file, line); } // For use in NLER assert call-out void nl_platform_assert_delegate(const char* file, unsigned line) { assert_helper(file, line); __builtin_trap(); }
nestlabs/nlplatform
include/nlprofile.h
/* * * Copyright (c) 2015-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Description: // This file defines the interfaces needed for nlprofile framework // // #ifndef __NLPROFILE_H__ #define __NLPROFILE_H__ #include <stdint.h> #include <nlprofile_product.h> #ifdef __cplusplus extern "C" { #endif // Return the current timestamp in whatever unit the product // is using to track time uint32_t nl_profile_get_current_time(void); // Start tracking a dynamically togglable resource void nl_profile_start(nl_profile_t profile_index); // Stop tracking a dynamically togglable resource void nl_profile_stop(nl_profile_t profile_index); // Tasks are handled in a different way than other trackable resources. // Called at the end of a profiling interval to total up all the task usage during that interval typedef struct { char name[NL_PROFILE_TASK_NAME_LEN]; uint32_t usage_during_interval; uint16_t max_unused_stack_bytes; } nl_profile_task_info_t; // Information we track about each queue in the system typedef struct { uint32_t location; uint8_t size; uint8_t high_watermark; } nl_profile_queue_info_t; // Populate task_profile_info array with information about task usage void nl_profile_interval_get_task_info(nl_profile_task_info_t task_profile_info[NL_PROFILE_NUM_TASKS]); // Clears structures used to track interval usage void nl_profile_interval_start_new_interval(void); // Product-specific interval cleanup tasks void nl_profile_product_start_new_interval(void); // Total up trackable resource usage for this interval and copy it to profile_buffer void nl_profile_interval_calculate_totals(uint32_t interval_expiry, uint32_t profile_buffer[NL_PROFILE_NUM_TRACKED_ITEMS]); // Record the pbuf high watermark for this interval. If using variable sized pools, specify // which pool with pool_idx. void nl_profile_interval_set_pbuf_highwatermark(uint32_t pbuf_count, uint32_t pool_idx); // Return the pbuf high watermark for this interval. If using variable sized pools, specify // which pool with pool_idx. uint32_t nl_profile_interval_get_pbuf_highwatermark(uint32_t pool_idx); // Populate queue_profile_info with information on tracked queue levels // Returns the number of tracked queues that were recorded uint32_t nl_profile_interval_get_queue_info(nl_profile_queue_info_t queue_profile_info[NL_PROFILE_NUM_QUEUES]); // Product-specific array of tasks in the system extern const char * TaskNames[]; #ifdef __cplusplus } #endif #endif
nestlabs/nlplatform
src/nlram_console.c
<reponame>nestlabs/nlplatform<gh_stars>1-10 /* * * Copyright (c) 2016-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This implements a circular buffer for maintain a copy * of all output sent to the console in a persistent RAM * section. It's a potentially useful debugging tool to * get the context/history prior to a crash beyond just a * register dump. * * It's similar to the Android/Linux kernel feature of the * same name (though more recent versions use pstore I believe) * except we don't use two buffers because we've very RAM * contrained in our devices. We just use one buffer, but * keep track of indices that provide info about the buffer * usage on the previous boot. The ram console should be * flipped at the bootloader and continue appended to * by the app. Ideally the bootloader should not output * very much to the console, and the app should early in * it's boot save the previous ram console buffer contents * out to persistent storage before it starts doing any * console output of it's own. */ #include <nlplatform.h> #include <nlplatform/nlram_console.h> #include <string.h> #define RAM_CONSOLE_MAGIC 0xabedface typedef struct { uint32_t callback_watermark; uint32_t callback_bytes_written; nl_ram_console_cb_t callback; } nl_ram_console_cb_ctx_t; typedef struct { uint32_t magic; uint32_t write_index; uint32_t bytes_written; uint32_t last_write_index; uint32_t last_bytes_written; uint32_t buf_size; /* should match NL_RAM_CONSOLE_BUF_SIZE but we * keep it in RAM to help us check/detect if * NL_RAM_CONSOLE_BUF_SIZE has changed between * images in a SW update */ bool enabled; uint8_t buf[NL_RAM_CONSOLE_BUF_SIZE]; } nl_ram_console_t; static nl_ram_console_cb_ctx_t s_ram_console_cb_ctx; static nl_ram_console_t s_ram_console NL_SYMBOL_AT_SECTION(".ram_console"); #define TEST_DYNAMIC_RAM_CONSOLE_BUF_SIZE_CHANGES 0 #if TEST_DYNAMIC_RAM_CONSOLE_BUF_SIZE_CHANGES // make RAM_CONSOLE_BUF_SIZE a variable to allow easier testing. // with a debugger and a breakpoint on nl_ram_console_init(), // the developer can reset and change the size to step through // the conversion routine during init. uint32_t g_ram_console_buf_size = NL_RAM_CONSOLE_BUF_SIZE; #define RAM_CONSOLE_BUF_SIZE g_ram_console_buf_size #else /* TEST_DYNAMIC_RAM_CONSOLE_BUF_SIZE_CHANGES */ #define RAM_CONSOLE_BUF_SIZE NL_RAM_CONSOLE_BUF_SIZE #endif /* TEST_DYNAMIC_RAM_CONSOLE_BUF_SIZE_CHANGES */ static void init_ram_console(void) { s_ram_console.magic = RAM_CONSOLE_MAGIC; s_ram_console.last_bytes_written = 0; s_ram_console.last_write_index = 0; s_ram_console.bytes_written = 0; s_ram_console.write_index = 0; s_ram_console_cb_ctx.callback_watermark = 0; s_ram_console_cb_ctx.callback_bytes_written = 0; s_ram_console_cb_ctx.callback = NULL; s_ram_console.buf_size = RAM_CONSOLE_BUF_SIZE; } void nl_ram_console_register_callback(nl_ram_console_cb_t aCallback, uint32_t aWatermark) { s_ram_console_cb_ctx.callback_watermark = aWatermark; s_ram_console_cb_ctx.callback_bytes_written = 0; s_ram_console_cb_ctx.callback = aCallback; } void nl_ram_console_init_bootloader(void) { if (s_ram_console.magic != RAM_CONSOLE_MAGIC) { init_ram_console(); } else { /* MAGIC is valid, so push the current info to last */ s_ram_console.last_bytes_written = s_ram_console.bytes_written; s_ram_console.last_write_index = s_ram_console.write_index; s_ram_console.bytes_written = 0; // current write_index is unchanged, we continue writing where we left off } // enable it if it wasn't enabled s_ram_console.enabled = true; } void nl_ram_console_init(uint8_t *aScratchBuf, size_t aScratchBufSize) { // If the magic doesn't match (might happen when old bootloader // with no RAM console boots to an image with a RAM console, or // if the old bootloader had a different location for the RAM // console) initialize it. if (s_ram_console.magic != RAM_CONSOLE_MAGIC) { init_ram_console(); } else if (s_ram_console.buf_size != RAM_CONSOLE_BUF_SIZE) { // if this image's buffer size is not the same as what // we see in s_ram_console, then something has changed. // we try to preserve the contents by copying it out // to a provided scratch buffer and then copying it // back. trying to preserve in place is hard to // impossible if the buffer is smaller. to keep it // simple, we use the same code for the case of growing // or shrinking. uint32_t last_bytes_written = s_ram_console.last_bytes_written; uint32_t bytes_written = s_ram_console.bytes_written; uint32_t bytes_to_preserve = last_bytes_written + bytes_written; if (bytes_to_preserve > RAM_CONSOLE_BUF_SIZE) { bytes_to_preserve = RAM_CONSOLE_BUF_SIZE; } if (bytes_to_preserve > aScratchBufSize) { bytes_to_preserve = aScratchBufSize; } if (bytes_to_preserve > 0) { uint32_t bytes_until_end; uint32_t old_buf_size = s_ram_console.buf_size; uint32_t write_index = s_ram_console.write_index; uint32_t start_index = write_index - bytes_to_preserve; if (start_index > old_buf_size) { // handle wrapping start_index += old_buf_size; } // start_index is the start of the log. // move in up to two chunks, the amount before end of the old // buffer, and if needed the amount from start of old buffer bytes_until_end = old_buf_size - start_index; if (bytes_until_end > bytes_to_preserve) { memcpy(aScratchBuf, &s_ram_console.buf[start_index], bytes_to_preserve); } else { memcpy(aScratchBuf, &s_ram_console.buf[start_index], bytes_until_end); memcpy(aScratchBuf + bytes_until_end, &s_ram_console.buf[0], bytes_to_preserve - bytes_until_end); } s_ram_console.buf_size = RAM_CONSOLE_BUF_SIZE; // copy back from scratch to beginning of the ram_console buffer memcpy(s_ram_console.buf, aScratchBuf, bytes_to_preserve); // now update indices and bytes_written values if (bytes_to_preserve == RAM_CONSOLE_BUF_SIZE) { s_ram_console.write_index = 0; } else { s_ram_console.write_index = bytes_to_preserve; } if (bytes_written > bytes_to_preserve) { bytes_written = bytes_to_preserve; } s_ram_console.bytes_written = bytes_written; bytes_to_preserve -= bytes_written; if (last_bytes_written > bytes_to_preserve) { last_bytes_written = bytes_to_preserve; } if (last_bytes_written > 0) { s_ram_console.last_bytes_written = last_bytes_written; s_ram_console.last_write_index = s_ram_console.write_index - s_ram_console.bytes_written; if (s_ram_console.last_write_index > RAM_CONSOLE_BUF_SIZE) { s_ram_console.last_write_index += RAM_CONSOLE_BUF_SIZE; } } else { s_ram_console.last_bytes_written = 0; s_ram_console.last_write_index = 0; } } else { init_ram_console(); } } // start disabled until product level code can save // to flash as desired before calling enable. s_ram_console.enabled = false; } void nl_ram_console_get_info(nl_ram_console_info_t *aInfo) { aInfo->write_index = s_ram_console.write_index; aInfo->bytes_written = s_ram_console.bytes_written; aInfo->last_write_index = s_ram_console.last_write_index; aInfo->last_bytes_written = s_ram_console.last_bytes_written; aInfo->write_index = s_ram_console.write_index; aInfo->buf = s_ram_console.buf; aInfo->buf_size = s_ram_console.buf_size; aInfo->callback_watermark = s_ram_console_cb_ctx.callback_watermark; aInfo->callback_bytes_written = s_ram_console_cb_ctx.callback_bytes_written; aInfo->callback = s_ram_console_cb_ctx.callback; } void nl_ram_console_enable(void) { s_ram_console.enabled = true; } void nl_ram_console_disable(void) { s_ram_console.enabled = false; } /* Always use the s_ram_console.buf_size and not NL_RAM_CONSOLE_BUF_SIZE * in this function in case the constant has changed. For example, if * a new updated app has a smaller ram_console than the previous image, * on the next boot, we want the bootloader to use that new size instead * of it's compiled in constant. */ void nl_ram_console_write(const uint8_t *data, size_t len) { size_t orig_len = len; /* it's hard to read interleaved content so make the write atomic */ nlplatform_interrupt_disable(); if (s_ram_console.enabled) { const uint32_t buf_size = s_ram_console.buf_size; uint32_t non_current_bytes; while (len > 0) { size_t buf_size_before_wrap = buf_size - s_ram_console.write_index; size_t bytes_to_write; if (len < buf_size_before_wrap) { bytes_to_write = len; } else { bytes_to_write = buf_size_before_wrap; } memcpy(&s_ram_console.buf[s_ram_console.write_index], data, bytes_to_write); data += bytes_to_write; len -= bytes_to_write; s_ram_console.write_index += bytes_to_write; if (s_ram_console.write_index >= buf_size) { s_ram_console.write_index = 0; } } s_ram_console.bytes_written += orig_len; if (s_ram_console.bytes_written > buf_size) { s_ram_console.bytes_written = buf_size; } // adjust last_bytes_written. total should never be more than the buf_size // so the last log shrinks as the current one grows non_current_bytes = buf_size - s_ram_console.bytes_written; if (s_ram_console.last_bytes_written > non_current_bytes) { s_ram_console.last_bytes_written = non_current_bytes; } // Call a high watermark callback if required if (s_ram_console_cb_ctx.callback != NULL) { s_ram_console_cb_ctx.callback_bytes_written += orig_len; if (s_ram_console_cb_ctx.callback_bytes_written >= s_ram_console_cb_ctx.callback_watermark) { s_ram_console_cb_ctx.callback(); s_ram_console_cb_ctx.callback_bytes_written = 0; } } } nlplatform_interrupt_enable(); }
nestlabs/nlplatform
src/nlfs.c
<filename>src/nlfs.c /* * * Copyright (c) 2015-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file implements the a filesystem interface. * FAT is currently not supported. */ #include <nlplatform.h> #if NL_NUM_FLASH_IDS > 0 /* No nlfs if no flash */ #include <errno.h> #include <string.h> #include <nlplatform/nlfs.h> #include <nlplatform/nlflash.h> #include <nlplatform/nlcrc.h> #include <nlenv.h> #include <nlassert.h> #include "nlelf-loader.h" /* Product wide defaults are used if nlfs specific values aren't specified * in nlproduct_config.h */ #ifndef NL_FS_CRC_TRANSPOSE_WRITE #define NL_FS_CRC_TRANSPOSE_WRITE NLCRC_TRANSPOSE_WRITE_DEFAULT #endif #ifndef NL_FS_CRC_TRANSPOSE_READ #define NL_FS_CRC_TRANSPOSE_READ NLCRC_TRANSPOSE_READ_DEFAULT #endif #ifndef NL_FS_CRC_XOR_ON_READ #define NL_FS_CRC_XOR_ON_READ NLCRC_XOR_ON_READ_DEFAULT #endif #ifndef NL_FS_CRC_LEN #define NL_FS_CRC_LEN NLCRC_LEN_DEFAULT #endif #ifndef NL_FS_CRC_POLY #define NL_FS_CRC_POLY NLCRC_POLY_DEFAULT #endif #ifndef NL_FS_CRC_SEED #define NL_FS_CRC_SEED NLCRC_SEED_DEFAULT #endif static int readFile(void* buf, uint32_t from, size_t len, void* context) { size_t retlen; return nlflash_read(NLFLASH_EXTERNAL, from, len, &retlen, buf, NULL); } static int calcCrc(void *buf, size_t len, void * context) { uint32_t *crc_value = (uint32_t *)context; *crc_value = nlcrc_compute(*crc_value, buf, len); return *crc_value; } #ifdef BUILD_FEATURE_FAT_FILES /* * use linker script to set fat functions to stub routines if * fat support isn't wanted in the binary (like in AUPD case). */ int fatfileinit(uint8_t partId, nlfs_fat_file_context_t *fatFileContext) LINKER_REPLACEABLE_FUNCTION(fatfileinit_default); void fatfiledeinit(nl_fat_context *context) LINKER_REPLACEABLE_FUNCTION(fatfiledeinit_default); int fatfileread( void* outBuffer, uint32_t inAddress, size_t inSize, nl_fat_context *contex) LINKER_REPLACEABLE_FUNCTION(fatfileread_default); /* not static so the compiler doesn't inline them and prevent linker script replacement from working */ int fatfileread_default(void* outBuffer, uint32_t inAddress, size_t inSize, nl_fat_context *context); int fatfileinit_default(uint8_t partId, nlfs_fat_file_context_t *fatFileContext); void fatfiledeinit_default(nl_fat_context *context); int fatfileinit_default(uint8_t partId, nlfs_fat_file_context_t *fatFileContext) { int partitionNum; int retval; partitionNum = (partId == GET_PARTITION_ID(kImage0)) ? 0 : 1; retval = nl_fat_init_context(&fatFileContext->context, fatFileContext->bufs, NL_NUM_FAT_BUFFS, partitionNum); return retval; } void fatfiledeinit_default(nl_fat_context *context) { nl_fat_deinit_context(context); } int fatfileread_default(void* outBuffer, uint32_t inAddress, size_t inSize, nl_fat_context *context) { return nl_fat_read_file(outBuffer, inAddress, inSize, context); } #endif /* BUILD_FEATURE_FAT_FILES */ static void get_image_offset(nlfs_image_location_t loc, uint8_t *partId, uint32_t *offset) { // Default to Image0 *partId = GET_PARTITION_ID(kImage0); if (loc == IMAGE1) { *partId = GET_PARTITION_ID(kImage1); } else if (loc != IMAGE0) { char currentImage[8]; int error = nl_env_get_string(kCurrentImageKey, currentImage, sizeof(currentImage)); if (error >= 0) { // Check if should open Image1 instead if ( ((strcmp(currentImage, kImageValue0) == 0) && (loc == ALTERNATE)) || ((strcmp(currentImage, kImageValue1) == 0) && (loc == INSTALLED)) ) { *partId = GET_PARTITION_ID(kImage1); } } else { // Set to default Image0 if current_image didn't exist nl_env_set_string(kCurrentImageKey, kImageValue0); } } *offset = g_flash_partitions[*partId].offset; } static int fileInit(nlfs_fileid_t fid, nlfs_file_mode_t mode, nlfs_image_location_t loc, bool isFat, void *context, nlfs_file_t *file) { int retval = 0; file->currentPos = 0; file->partId = GET_PARTITION_ID(fid); file->partType = GET_PARTITION_TYPE(fid); file->chipId = (file->partType == PARTITION_TYPE_INT) ? NLFLASH_INTERNAL : NLFLASH_EXTERNAL; file->mode = mode; file->isOpen = true; file->context = context; file->isFat = isFat; // If main partition if (file->partType != PARTITION_TYPE_EXT_SUB) { if (file->partId != GET_PARTITION_ID(kImage)) { file->offset = g_flash_partitions[file->partId].offset; file->len = g_flash_partitions[file->partId].size; #if !defined(BUILD_CONFIG_RELEASE) && defined(MAX_ALLOWED_WAV_LENGTH) if (file->partId == GET_PARTITION_ID(kCustomAudio)) { file->len = MAX_ALLOWED_WAV_LENGTH; } #endif } else { // Overwrite the partition ID if kImage get_image_offset(loc, &file->partId, &file->offset); file->len = g_flash_partitions[file->partId].size; #ifdef BUILD_FEATURE_FAT_FILES if (isFat) { nlfs_fat_file_context_t *fatFileContext = (nlfs_fat_file_context_t *)(file->context); retval = fatfileinit(file->partId, fatFileContext); } #endif } } // If sub partition else { uint32_t imageOffset; uint8_t partId; elfSectionDescription_t section; elfReaderHandle_t elfReader; uint32_t crc_value = NL_FS_CRC_SEED; get_image_offset(loc, &partId, &imageOffset); if (!isFat) { // readFile() accesses external flash. readFile() will get called repeatedly within // the call to elf_find_section_crc(...). It is necessary that the flash lock and CRC // lock are acquired in the same order as what is used by getenv(). That order is // flash lock followed by crc lock. this flash_request aims to ensure that order is // maintained, and avoids deadlocks that were witnessed in operation. nlflash_request(NLFLASH_EXTERNAL); elf_loader_init(&elfReader, calcCrc, readFile, imageOffset, NULL, (void *)&crc_value); } else { #ifdef BUILD_FEATURE_FAT_FILES nlfs_fat_file_context_t *fatFileContext = (nlfs_fat_file_context_t *)(file->context); retval = fatfileinit(partId, fatFileContext); nlREQUIRE(retval >= 0, done); elf_loader_init(&elfReader, calcCrc, (elfReadFunctionPtr_t)fatfileread, imageOffset, (void *)&fatFileContext->context, (void *)&crc_value); #else retval = -EINVAL; goto done; #endif } nlcrc_request(NL_FS_CRC_TRANSPOSE_WRITE, NL_FS_CRC_TRANSPOSE_READ, NL_FS_CRC_XOR_ON_READ, NL_FS_CRC_LEN, NL_FS_CRC_POLY); retval = elf_find_section_crc(&elfReader, g_sub_partition_info[file->partId].name, &section); nlcrc_release(); if (!isFat) { // This release pairs with nlflash_request up above when the isFat == false. nlflash_release(NLFLASH_EXTERNAL); } nlREQUIRE(retval >= 0, done); file->len = section.size; file->offset = elfReader.headerOffset + section.offset; } done: return retval; } int nlfs_open_cb(nlfs_fileid_t fid, nlfs_file_mode_t mode, nlfs_image_location_t loc, nlfs_file_t *file, bool isFat, void *context, nlloop_callback_fp callback) { int retval; // Cannot write to a sub-partition if ((mode != READ_ONLY) && (GET_PARTITION_TYPE(fid) == PARTITION_TYPE_EXT_SUB)) { return -EINVAL; } // Only have alternates for sub partitions and kImage if ((loc != INSTALLED) && (GET_PARTITION_TYPE(fid) != PARTITION_TYPE_EXT_SUB) && (GET_PARTITION_ID(fid) != GET_PARTITION_ID(kImage))) { return -EINVAL; } retval = fileInit(fid, mode, loc, isFat, context, file); if (retval >= 0) { // Erase partition if opening for writing if (mode == WRITE_ONLY) { if (!g_flash_partitions[file->partId].isReadOnly) { size_t retlen; // Get the device and tell it to do its own locking during the erase retval = nlflash_erase(file->chipId, file->offset, file->len, &retlen, callback); if ((retval >= 0) && (retlen != file->len)) { retval = -EIO; } } else { retval = -EINVAL; } } } return retval; } size_t nlfs_read_cb(nlfs_file_t *file, void *buf, size_t bytes, nlloop_callback_fp callback) { int retval = 0; size_t len = bytes; uint32_t from; size_t retlen = 0; if (!file->isOpen || (file->mode != READ_ONLY)) { return -EINVAL; } from = file->offset + file->currentPos; if ((file->currentPos + bytes) > file->len) { len = file->len - file->currentPos; } if (file->isFat == false) { retval = nlflash_read(file->chipId, from, len, &retlen, (uint8_t *)buf, callback); } else { #ifdef BUILD_FEATURE_FAT_FILES nlfs_fat_file_context_t *fatFileContext = (nlfs_fat_file_context_t *)(file->context); nl_fat_context *fatContext = &fatFileContext->context; retval = fatfileread(buf, from, len, fatContext); #else return -EINVAL; #endif } if (retval >= 0) { file->currentPos += retlen; } return retlen; } size_t nlfs_write_cb(nlfs_file_t *file, const void *buf, size_t bytes, nlloop_callback_fp callback) { int retval = 0; size_t len = bytes; size_t retlen = 0; if (!file->isOpen || (file->mode != WRITE_ONLY) || (file->isFat == true)) { return retval; } // Don't write past the end of the file if ((file->currentPos + bytes) > file->len) { len = file->len - file->currentPos; } retval = nlflash_write(file->chipId, file->offset + file->currentPos, len, &retlen, (uint8_t *)buf, callback); file->currentPos += retlen; return retlen; } int nlfs_close(nlfs_file_t *file) { int retval = 0; if (file->isOpen == false) return -EINVAL; if (file->mode == WRITE_ONLY) { retval = nlflash_flush(file->chipId); if (retval >= 0) { file->isOpen = false; } } #ifdef BUILD_FEATURE_FAT_FILES if (file->isFat == true) { nlfs_fat_file_context_t *fatFileContext = (nlfs_fat_file_context_t *)(file->context); fatfiledeinit(&fatFileContext->context); } #endif return retval; } int nlfs_seek(nlfs_file_t *file, uint32_t offset, nlfs_origin_pos_t origin) { int retval = 0; if ((file->isOpen != true) || (file->mode != READ_ONLY) || (file->isFat == true)) { return -EINVAL; } if (origin == BEGINNING) { // Make sure offset isn't past the end if (offset >= file->len) { return -EINVAL; } file->currentPos = offset; } else { if (file->currentPos + offset >= file->len) return -EINVAL; file->currentPos += offset; } return retval; } int nlfs_getpos(const nlfs_file_t *file, uint32_t *offset) { if (file->isOpen == false) return -EINVAL; *offset = file->currentPos; return 0; } int nlfs_getlen(const nlfs_file_t *file, size_t *len) { if ((file->isOpen == false) || (file->mode != READ_ONLY)) { return -EINVAL; } *len = file->len; return 0; } bool nlfs_is_open(const nlfs_file_t *file) { return file->isOpen; } #endif /* NL_NUM_FLASH_IDS > 0 */
nestlabs/nlplatform
include/nltrace.h
<reponame>nestlabs/nlplatform /* * * Copyright (c) 2017-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Description: // This file defines the interfaces needed for the nltrace framework // // #ifndef __NLTRACE_H__ #define __NLTRACE_H__ #include <stdint.h> #include <nlplatform.h> #ifdef __cplusplus extern "C" { #endif #if defined(BUILD_FEATURE_NL_TRACE) void nltrace_init(nltimer_id_t timer_id); uint8_t nltrace_event_start(const char *name); uint8_t nltrace_event_start_with_taskname(const char *name, const char *task_name); void nltrace_event_end(uint8_t id, const char *name); void nltrace_print(void); void nltrace_enable(bool enable); bool nltrace_enabled(void); #else #define nltrace_init(X) #define nltrace_event_start(X) (0) #define nltrace_event_start_with_taskname(X, Y) (0) #define nltrace_event_end(X, Y) #define nltrace_print() #define nltrace_enable(X) #define nltrace_enabled(X) (false) #endif // BUILD_FEATURE_NL_TRACE #ifdef __cplusplus } #endif #endif // __NLTRACE_H__
nestlabs/nlplatform
include/nlrtc.h
<gh_stars>1-10 /* * * Copyright (c) 2015-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file defines API for RTC */ #ifndef __NLRTC_H_INCLUDED__ #define __NLRTC_H_INCLUDED__ #ifdef __cplusplus extern "C" { #endif #include <stdint.h> typedef struct nlrtc_s nlrtc_t; nlrtc_t *nlrtc_init(int rtc_id); uint32_t nlrtc_get(nlrtc_t *rtc); uint32_t nlrtc_get_from_isr(nlrtc_t *rtc); #ifdef __cplusplus } #endif #endif /* __NLRTC_H_INCLUDED__ */
nestlabs/nlplatform
src/nlcrc.c
/* * * Copyright (c) 2012-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file implements an object for calculating CRCs by wrapping * the software implementation. If a soc has HW CRC, it should * be implemented in the nlplatform_soc level and BUILD_FEATURE_SW_CRC * should not be defined. */ #ifdef BUILD_FEATURE_SW_CRC #include <stdlib.h> #include <errno.h> #include <nlassert.h> #include <nlplatform/nlcrc.h> #include <nlcrc.h> unsigned nlcrc_compute(unsigned crc, const void *data, size_t len) { return crc32_append(crc, data, len); } int nlcrc_request(nlcrc_transpose_write_t writeType, nlcrc_transpose_read_t readType, bool xorOnRead, nlcrc_len_t crcLen, unsigned poly) { int retval = 0; /* when SW CRC is used, we can only support crc32 ANSI for now. * the SW CRC library routine is equivalent to HW crc configured * with no transpose on read/write, XorOnRead (needs to be confirmed) */ nlREQUIRE_ACTION(writeType == kTransposeTypeWriteNone, done, retval = -EINVAL); nlREQUIRE_ACTION(readType == kTransposeTypeReadNone, done, retval = -EINVAL); nlREQUIRE_ACTION(xorOnRead == true, done, retval = -EINVAL); nlREQUIRE_ACTION(crcLen == kCrcLen32Bits, done, retval = -EINVAL); done: return retval; } int nlcrc_release(void) { /* does nothing when using SW CRC */ return 0; } void nlcrc_set_locking(int (*lock)(void *), int (*unlock)(void *), void* context) { /* unneeded in SW CRC implementation, assert we are never called */ nlASSERT(0); } #endif /* BUILD_FEATURE_SW_CRC */
nestlabs/nlplatform
include/nlpartition.h
<reponame>nestlabs/nlplatform /* * * Copyright (c) 2015-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file defines a partition. */ #ifndef __NLPARTITION_H_INCLUDED__ #define __NLPARTITION_H_INCLUDED__ #include <stddef.h> #include <stdbool.h> #include <nlplatform/nlfs.h> #ifdef __cplusplus extern "C" { #endif typedef struct partition_s { const char *name; size_t offset; size_t size; bool isReadOnly; } __attribute__((__packed__)) nlpartition_t; /* ELF section names and ids for sub-partitions */ typedef struct sub_partition_info_s { const char *name; nlfs_fileid_t fid; } __attribute__((__packed__)) nlsub_partition_info_t; /* to be implemented by each product */ #ifdef BUILD_FEATURE_SOFT_PARTITIONS extern nlpartition_t g_flash_partitions[NL_NUM_FLASH_PARTITIONS]; #else extern const nlpartition_t g_flash_partitions[NL_NUM_FLASH_PARTITIONS]; #endif extern const nlsub_partition_info_t g_sub_partition_info[NL_NUM_SUBPARTITIONS]; #ifdef __cplusplus } #endif #endif /* __NLPARTITION_H_INCLUDED__ */
nestlabs/nlplatform
include/nlmpu.h
<reponame>nestlabs/nlplatform /* * * Copyright (c) 2017-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file implements an API for the memory protection unit registers. */ #ifdef __cplusplus extern "C" { #endif void nl_mpu_init(void); /* if enable == true, enable_default_memory_map and enable_mpu_in_fault_handlers are * used the configure the MPU behavior accordingly. * if enable == false, the other two arguments are ignored. */ void nl_mpu_enable(bool enable, bool enable_default_memory_map, bool enable_mpu_in_fault_handlers); unsigned nl_mpu_get_num_regions(void); /* Different ARM architectures support different attributes/encoding of attributes. * Rather than defining a generic description and then translation to the attributes * supported by the current processor, the attributes should be the ones used * in the corresponding CMSIS header file combined into one unsigned value. * * For example, for cortex-m3, use the core_cm3.h definitions of RASR for the * attributes. Invalid parameters are asserted. Base address and size need * to meet the minimum requirements for the SoC. Type of region_size is uint64_t * to allow specifying a full 4GB region on a 32-bit processor, though it's * unlikely we'll need to specify such a large region in practice. * * Returns the region number just allocated and enabled, or -1 if no free * region available. */ int nl_mpu_request_region(unsigned region_base_address, uint64_t region_size, unsigned attributes); /* Disables and releases a previously requested region. */ void nl_mpu_release_region(int region); #ifdef __cplusplus } #endif
nestlabs/nlplatform
src/nlwatchpoint.c
/* * * Copyright (c) 2016-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file implements an API for the watchdog registers * in an ARM Cortex-M3 and Cortex-M0 (using the CMSIS headers). * Note CMSIS for cm0 and cm0plus don't define the DWT * or CoreDebug registers because they are considered * an optional HW extension. The register locations are * the same as for the cm3. */ #include <assert.h> #include <stdint.h> #include <nlplatform.h> #include <nlplatform_soc.h> #include <nlplatform/nlwatchpoint.h> /* nlplatform_soc.h should include the correct CMSIS header file (or * equivalent), which defines needed values like DWT and CoreDebug. * If these aren't defined, assume for now that this soc isn't supporting * watchpoints and just do nothing. If those soc's want to support * watchpoint APIs, they'll have to define DWT and CoreDbug. */ #if defined(DWT) && defined(CoreDebug) typedef struct { volatile uint32_t comp_reg; volatile uint32_t mask_reg; volatile uint32_t function_reg; volatile uint32_t reserved; } cortex_watchpoint_comparator_regs; void nl_watchpoint_enable(unsigned watchpoint_index, unsigned addr, nl_watchpoint_type_t watchpoint_type, unsigned mask) { unsigned i; cortex_watchpoint_comparator_regs *dwt_wp_regs = (cortex_watchpoint_comparator_regs*)&DWT->COMP0; assert(watchpoint_index < (DWT->CTRL >> DWT_CTRL_NUMCOMP_Pos)); dwt_wp_regs += watchpoint_index; // if this is the first enable of the DWT (which may happen when coming // out of deep sleep), immediately writing a DWT register after enabling // the DWT has been shown to not take. we don't have any documentation // on how long DWT takes to enable when we set the TRCENA bit, but a little // empiracle testing seems to indicate it takes just one or two extra // clock cycles. to be safe, we retry a number of times, and assert in // case the limit we choose was insufficient. #define MAX_DWT_WRITE_CHECK_COUNT 100 for (i = 0; i < MAX_DWT_WRITE_CHECK_COUNT; i++) { dwt_wp_regs->comp_reg = addr; if (dwt_wp_regs->comp_reg == addr) { break; } } assert(dwt_wp_regs->comp_reg == addr); dwt_wp_regs->mask_reg = mask; dwt_wp_regs->function_reg = watchpoint_type; } void nl_watchpoint_set_type(unsigned watchpoint_index, nl_watchpoint_type_t watchpoint_type) { cortex_watchpoint_comparator_regs *dwt_wp_regs = (cortex_watchpoint_comparator_regs*)&DWT->COMP0; assert(watchpoint_index < (DWT->CTRL >> DWT_CTRL_NUMCOMP_Pos)); dwt_wp_regs += watchpoint_index; dwt_wp_regs->function_reg = watchpoint_type; } #endif /* defined(DWT) && defined(CoreDebug) */
nestlabs/nlplatform
include/nlcrypto.h
/* * * Copyright (c) 2013-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file defines the API for a cryptography accelerator. * */ #ifndef __NLCRYPTO_H_INCLUDED__ #define __NLCRYPTO_H_INCLUDED__ #include <stddef.h> #include <stdint.h> #include <stdbool.h> #ifdef __cplusplus extern "C" { #endif /* AES */ // Check whether the AES engine is current available in interrupt context or not. bool nlplatform_AES_available_in_isr(void); void nlplatform_AES128ECB_set_encrypt_key(const uint8_t *userKey, uint8_t *key); void nlplatform_AES128ECB_encrypt(const uint8_t *inBlock, uint8_t *outBlock, const uint8_t *key); void nlplatform_AES128ECB_set_decrypt_key(const uint8_t *userKey, uint8_t *key); void nlplatform_AES128ECB_decrypt(const uint8_t *inBlock, uint8_t *outBlock, const uint8_t *key); void nlplatform_AES256ECB_set_encrypt_key(const uint8_t *userKey, uint8_t *key); void nlplatform_AES256ECB_encrypt(const uint8_t *inBlock, uint8_t *outBlock, const uint8_t *key); void nlplatform_AES256ECB_set_decrypt_key(const uint8_t *userKey, uint8_t *key); void nlplatform_AES256ECB_decrypt(const uint8_t *inBlock, uint8_t *outBlock, const uint8_t *key); typedef struct nlplatform_aes_cmac_s nlplatform_aes_cmac_t; void nlplatform_AES_CMAC_init(nlplatform_aes_cmac_t *ctx, const uint8_t *key); void nlplatform_AES_CMAC_update(nlplatform_aes_cmac_t *ctx, const uint8_t *inData, size_t dataLen); void nlplatform_AES_CMAC_finish(nlplatform_aes_cmac_t *ctx, uint8_t *macBuf); /* SHA-1 */ typedef struct nlplatform_sha1_s nlplatform_sha1_t; void nlplatform_SHA1_init(nlplatform_sha1_t *ctx); void nlplatform_SHA1_update(nlplatform_sha1_t *ctx, const uint8_t *data, size_t len); void nlplatform_SHA1_finish(nlplatform_sha1_t *ctx, uint8_t *digest); /* Single-call variant. Can be used if data is in one contiguous block. */ void nlplatform_SHA1_hash(const uint8_t *data, uint8_t *digest, size_t len); /* SHA-256. Use separate API so from SHA-1 so unused functions can be deadstripped. */ typedef struct nlplatform_sha256_s nlplatform_sha256_t; void nlplatform_SHA256_init(nlplatform_sha256_t *ctx); void nlplatform_SHA256_update(nlplatform_sha256_t *ctx, const uint8_t *data, size_t len); void nlplatform_SHA256_finish(nlplatform_sha256_t *ctx, uint8_t *digest); /* Single-call variant. Can be used if data is in one contiguous block. */ void nlplatform_SHA256_hash(const uint8_t *data, uint8_t *digest, size_t len); typedef enum { ECDSA_SIGNATURE_TYPE_NONE = 0x00, ECDSA_SIGNATURE_TYPE_SHA256_SECP224R1 = 0x01 } ecdsa_signature_t; /* Possible return values for nlplatform_ecdsa_verify(). * Errors are negative. * Success is 0. * No check done (because signature type was NONE) is 1. */ #define ECDSA_VERIFY_INVALID_SIGNATURE_TYPE -2 #define ECDSA_VERIFY_INVALID_SIGNATURE -1 #define ECDSA_VERIFY_SUCCESS 0 #define ECDSA_VERIFY_NO_SIGNATURE 1 /* ECDSA-verify. The length of the public_key and the signature are * determined by the signature_type (e.g. 56 bytes for SIGNATURE_ECDSA_SHA256_SECP224R1) */ int nlplatform_ecdsa_verify(ecdsa_signature_t signature_type, const uint8_t *public_key, const uint8_t *message, size_t length, const uint8_t *signature); #ifdef __cplusplus } #endif #endif /* __NLCRYPTO_H_INCLUDED__ */
nestlabs/nlplatform
include/spi_flash/at45db041e.h
<gh_stars>1-10 /* * * Copyright (c) 2015-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file contains macro defines of the AT45DB041E SPI flash chip. * */ #ifndef __AT45DB041E_H_INCLUDED__ #define __AT45DB041E_H_INCLUDED__ /* ************************************************************************* * Configuration specific to nlflash-spi.cpp driver * *************************************************************************/ /* Uncomment the following to allow partial page buffer being used when Write() is called. Flush() is used to write everything in the page buffer out to the external flash. */ //#define FLASH_SPI_USE_PARTIAL_PAGE_BUFFER /* spi bus, spi freq, and chip select pin should be defined in nlproduct_config.h */ #define AT45DB041E_MAX_SPI_FREQ_HZ (85000000) // 85MHz #define FLASH_SPI_MODE (SPI_MODE_0) /* Size parameters */ #define FLASH_SPI_SIZE (2048 * FLASH_SPI_WRITE_SIZE) // 2048 * 264 = 528KB #define FLASH_SPI_ERASE_SIZE (FLASH_SPI_WRITE_SIZE) // has an 8 page block erase option too #define FLASH_SPI_FAST_ERASE_SIZE (256 * FLASH_SPI_WRITE_SIZE) // 256 pages #define FLASH_SPI_WRITE_SIZE (264) // writable unit #define FLASH_SPI_READ_ID_SIZE (3) // number of bytes of ID #define FLASH_SPI_FAST_READ_DUMMY_CYCLES (1) /* default number of dummy cycles is 1 byte when using FAST_READ */ #define FLASH_SPI_READ_DUMMY_CYCLES (0) /* default number of dummy cycles is 0 byte when using regular READ */ #define FLASH_SPI_FAST_READ_FREQ_HZ (85000000) /* 85MHz */ #define FLASH_SPI_READ_FREQ_HZ (15000000) /* 15MHz */ /* AT45DB041EFBAI Status Register and masks */ #define CMD_RDSR (0xD7) // to read out the status reg #define M_STAT_BUSY_BIT (1<<7) // bit that indicates device is busy or ready #define M_STAT_READY_VALUE (1<<7) /* value of busy bit to indicate device is ready */ #define M_STAT_BUSY_VALUE (0<<7) /* value of busy bit to indicate device is busy */ // Register/Setting Commands #define CMD_WPSEL (0x68) // to enter and enable individual block protect mode #define CMD_DP (0x79) // enter ultra-deep power down mode #define CMD_RDP (0xAB) // release from deep power down mode #define CMD_SBL (0xC0) // to set burst length // Read/Write Array Commands #define CMD_READ (0x01) // low power continous read, max speed 15 MHz #define CMD_FAST_READ (0x0B) // max speed 85 MHz #define CMD_PP (0x02) /* to program the selected page, without built-in erase */ #define CMD_SSE (0x81) /* subsector erase: "256byte subsector" is called "page" on AT45 */ #define CMD_SE (0x7C) /* sector erase: "64K sector" is called "sector" on AT45 */ #define CMD_BE (0xC7) /* bulk erase: "bulk erase" is called "chip erase" on AT45 */ #define CMD_BE_ADDR (0x94809A) /* chip erase needs these three additional opcode bytes, we send it as "addr" */ // Read device ID #define CMD_RDID (0x9F) /* read device ID */ // Disable lockdown sequence #define CMDS_LOCKDOWN_DISABLE 0x34, 0x55, 0xAA, 0x40 #define LEN_LOCKDOWN_DISABLE (4) // Chip IDs #define FLASH_SPI_MANUFACTORY_ID (0x1F) #define FLASH_SPI_MEMORY_TYPE_ID (0x24) #define FLASH_SPI_MEMORY_DENSITY_ID (0x00) /* delay time for different operations. DELAY_MSEC * DELAY_LOOP_COUNT == total delay time */ #define PP_DELAY_MSEC (1) #define PP_DELAY_LOOP_COUNT (5) /* PageProgram 256B, Typ. 1.5ms, Max. 3ms */ #define BE_DELAY_MSEC (500) #define BE_DELAY_LOOP_COUNT (40) /* ChipErase Typ. 6s, Max. 17s */ #define SE_DELAY_MSEC (100) #define SE_DELAY_LOOP_COUNT (20) /* SectorErase64K Typ. 700ms, Max. 1100ms */ #define SSE_DELAY_MSEC (10) #define SSE_DELAY_LOOP_COUNT (5) /* SubSectorErase2K Typ. 30ms, Max. 35ms */ /* These values are based on the data sheet but a product * might want to use longer values based on how the chip * has been connected (e.g. if no active discharge, longer * power down delay might be necessary). */ #define FLASH_SPI_POWER_UP_MAX_DELAY_MSEC (4) #define FLASH_SPI_POWER_DOWN_MAX_DELAY_USEC (1000) // for the non-multiple power of two page size, configure nlflash_spi // driver to use page+offset addressing #define FLASH_SPI_USE_PAGE_OFFSET_ADDRESSING 1 #define FLASH_SPI_NUM_OFFSET_BITS 9 // 264 bytes needs 9 bits of offset #endif /* __AT45DB041E_H_INCLUDED__ */
nestlabs/nlplatform
include/nlspi.h
/* * * Copyright (c) 2015-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file defines API for SPI */ #ifndef __NLSPI_H_INCLUDED__ #define __NLSPI_H_INCLUDED__ #include <stdint.h> #include <stddef.h> #ifdef __cplusplus extern "C" { #endif #define SPI_CPHA 0x01 #define SPI_CPOL 0x02 #define SPI_MODE_0 (0|0) #define SPI_MODE_1 (0|SPI_CPHA) #define SPI_MODE_2 (SPI_CPOL|0) #define SPI_MODE_3 (SPI_CPOL|SPI_CPHA) #define SPI_FLAG_EXTERNAL_ENABLE (0x01) typedef struct nlspi_controller_s nlspi_controller_t; /* slave device drivers should have a const instance of this structure * to pass to transaction calls. When SPI_FLAG_EXTERNAL_ENABLE is set, * nlspi_request() and nlspi_release() will not enable/disable * the spi slave but instead it is expected that the user of the * nlspi interface call nlspi_slave_enable() and nlspi_slave_disable(). * If SPI_FLAG_EXTERNAL_ENABLE is not set, nlspi_slave_enable() and * nlspi_slave_disable() should not be used, or else reference counting * must be done at some layer. */ typedef struct nlspi_slave_s { uint8_t controller_id; uint8_t cs_pin; uint8_t mode; uint8_t flags; uint32_t max_freq_hz; void (*enable_fp)(const struct nlspi_slave_s *spi_slave); void (*disable_fp)(const struct nlspi_slave_s *spi_slave); } nlspi_slave_t; void nlspi_init(void); /* special marker to indicate not to control CS during transfers */ #define NO_CS_GPIO_PIN 0xff /* Request the spi controller associated with the slave and * hold a lock on the controller so one or more operations * can be done. */ int nlspi_request(const nlspi_slave_t *spi_slave); /* Release lock on spi controller associated with a slave */ int nlspi_release(const nlspi_slave_t *spi_slave); /* Explicit enable/disable, to be used if SPI_FLAG_EXTERNAL_ENABLE * is set in the spi_slave_t structure. */ void nlspi_slave_enable(const nlspi_slave_t *spi_slave); void nlspi_slave_disable(const nlspi_slave_t *spi_slave); /* Synchronous uni-directional read/write APIs * read returns number of bytes read, < 0 on error. * write returns number of bytes written, < 0 on error. */ int nlspi_read(const nlspi_slave_t *slave, uint8_t *buf, size_t len); int nlspi_write(const nlspi_slave_t *slave, const uint8_t *buf, size_t len); /* The callback should return 0 if nlspi_transfer() should continue * with the next transfer in the argument array,. If the function * returns a value other than 0, the subsequent transfers are not * done and nlspi_transfer() returns the given non-zero value. */ struct nlspi_transfer_s; typedef int (*nlspi_handler_t)(struct nlspi_transfer_s *xfer, int result); /* Synchronous bi-directional transfers. supports an array of transfers requests. * at end of each transfer, the callback is invoked giving a chance to abort or * modify the fields of transfer structures not yet processed. */ typedef struct nlspi_transfer_s { const uint8_t *tx; /* pointer to tx buffer, NULL == no TX */ uint8_t *rx; /* pointer to rx buffer, NULL == no RX */ uint32_t num; /* number of bytes to transfer */ nlspi_handler_t callback; /* callback when transfer completes */ } nlspi_transfer_t; int nlspi_transfer(const nlspi_slave_t *spi_slave, nlspi_transfer_t *transfers, unsigned num_transfers); /* Asynchronous uni-directional read/write APIs */ /* result == 0 on successful completion of transfer, < 0 on error */ typedef void (*nlspi_async_handler_t)(const nlspi_slave_t *slave, int result); /* read returns 0 on successful start of transfer, < 0 on error * write returns 0 on successful start of transfer, < 0 on error * */ int nlspi_read_async(const nlspi_slave_t *slave, uint8_t *buf, size_t len, nlspi_async_handler_t callback); int nlspi_write_async(const nlspi_slave_t *slave, const uint8_t *buf, size_t len, nlspi_async_handler_t callback); #ifdef __cplusplus } #endif #endif /* __NLSPI_H_INCLUDED__ */
nestlabs/nlplatform
src/nlflash_spi.c
<gh_stars>1-10 /* * * Copyright (c) 2012-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file implements an API for accessing flash through a * SPI interface. It supports FLASH chips like N25Q and * MX25U1635 that have no intermediate SRAM buffers. With * some changes, it could be made to optionally support * FLASH chips with intermediate SRAM buffers. * * The APIs in this file are called by the nlflash.c layer, * which provides mutex (recursive) locking, so no locking * is required here. */ #include <errno.h> #include <string.h> #include <nlassert.h> #include <nlplatform.h> #if FLASH_SPI_SIZE > 0 #include <nlplatform/nlflash_spi.h> #include <nlplatform/nlgpio.h> #include <nlutilities.h> #ifndef FLASH_SPI_SPLIT_TRANSACTIONS #error "Must define FLASH_SPI_SPLIT_TRANSACTIONS to 0 or 1" #endif #ifndef FLASH_SPI_MAX_CHIP_ID_CHECK_COUNT #define FLASH_SPI_MAX_CHIP_ID_CHECK_COUNT 3 #endif #ifndef FLASH_SPI_FAULT_ON_REQUEST_FAILURE #define FLASH_SPI_FAULT_ON_REQUEST_FAILURE 0 #endif #ifndef FLASH_SPI_NUMBER_REQUEST_ATTEMPTS #define FLASH_SPI_NUMBER_REQUEST_ATTEMPTS 3 #endif typedef struct nlflash_spi_device_s { #ifdef FLASH_SPI_USE_PARTIAL_PAGE_BUFFER uint8_t partial_page[FLASH_SPI_MAX_PAGE_SIZE]; uint32_t partial_page_index; uint32_t write_loc; #endif uint8_t enable_ref; } nlflash_spi_device_t; const nlflash_info_t g_flash_spi_info = { .name = "SPIFlash", .base_addr = 0, .size = FLASH_SPI_SIZE, .erase_size = FLASH_SPI_ERASE_SIZE, .fast_erase_size = FLASH_SPI_FAST_ERASE_SIZE, .write_size = FLASH_SPI_WRITE_SIZE }; // only support one flash SPI device currently static nlflash_spi_device_t flash_spi_device = { #ifdef FLASH_SPI_USE_PARTIAL_PAGE_BUFFER .partial_page = {0}, .partial_page_index = 0, .write_loc = 0, #endif .enable_ref = 0 }; static int read_register(uint8_t cmd, uint8_t *buf, uint8_t num_bytes); static int check_chip_id(void) { int retval; uint8_t id_buf[FLASH_SPI_READ_ID_SIZE] = {0}; #if (FLASH_SPI_SPLIT_TRANSACTIONS == 1) retval = nlspi_request(&g_flash_spi_slave); if (retval < 0) return retval; #endif retval = read_register(CMD_RDID, id_buf, sizeof(id_buf)); nlREQUIRE(retval >= 0, done); #ifdef FLASH_SPI_NUM_SOURCES int i; for (i = 0 ; i < FLASH_SPI_NUM_SOURCES ; i++) { if (id_buf[0] == FLASH_SPI_MANUFACTORY_ID(i) && id_buf[1] == FLASH_SPI_MEMORY_TYPE_ID(i) && id_buf[2] == FLASH_SPI_MEMORY_DENSITY_ID(i)) { break; } } if (i < FLASH_SPI_NUM_SOURCES) { FLASH_SPI_SET_SOURCE(i); } else { retval = -1; // check ID failed } #else if (id_buf[0] != FLASH_SPI_MANUFACTORY_ID || id_buf[1] != FLASH_SPI_MEMORY_TYPE_ID || id_buf[2] != FLASH_SPI_MEMORY_DENSITY_ID) { retval = -1; // check ID failed } #endif done: #if (FLASH_SPI_SPLIT_TRANSACTIONS == 1) nlspi_release(&g_flash_spi_slave); #endif return retval; } int nlflash_spi_request(void) { int retval = 0; int attempts = FLASH_SPI_NUMBER_REQUEST_ATTEMPTS; flash_spi_device.enable_ref++; if (flash_spi_device.enable_ref > 1) { goto done; } while (attempts > 0) { #if (FLASH_SPI_SPLIT_TRANSACTIONS == 0) // request the SPI bus and keep it for duration of request. retval = nlspi_request(&g_flash_spi_slave); if (retval < 0) { // undo ref count increment flash_spi_device.enable_ref = 0; goto done; } #else // power up the spi slave now because there's usually high // latency associated with doing so. we only request the // spi controller during read/write transactions, to keep // the spi controller available to other devices that might // want to use it during long flash operations. nlspi_slave_enable(&g_flash_spi_slave); #endif #ifdef FLASH_SPI_USE_POWERDOWN // send return from deep powerdown cmd. this must be a separate // transaction from the rest becaues the chip requires // CS to go high at end of the cmd. { const uint8_t cmd_rdp[1] = {CMD_RDP}; retval = nlspi_write(&g_flash_spi_slave, cmd_rdp, sizeof(cmd_rdp)); if (retval < 0) { // undo ref count increment flash_spi_device.enable_ref = 0; goto done; } } #endif // Use check_chip_id() to determine whether the flash is in a valid // state for interaction. for (unsigned i = 0; i < FLASH_SPI_MAX_CHIP_ID_CHECK_COUNT; i++) { if (check_chip_id() >= 0) { retval = 0; goto done; } nlplatform_delay_ms(1); } // ID check error, turn off flash and possibly try again #if (FLASH_SPI_SPLIT_TRANSACTIONS == 0) nlspi_release(&g_flash_spi_slave); #else nlspi_slave_disable(&g_flash_spi_slave); #endif attempts--; } // We power cycled external flash several times and were unable to get a chip ID // Undo ref count and return error flash_spi_device.enable_ref = 0; retval = -1; done: #if (FLASH_SPI_FAULT_ON_REQUEST_FAILURE) if (retval < 0) { __builtin_trap(); } #endif return retval; } int nlflash_spi_release(void) { nlASSERT(flash_spi_device.enable_ref > 0); flash_spi_device.enable_ref--; if (flash_spi_device.enable_ref == 0) { #ifdef FLASH_SPI_USE_POWERDOWN // send deep powerdown cmd const uint8_t cmd_dp[1] = {CMD_DP}; nlspi_write(&g_flash_spi_slave, cmd_dp, sizeof(cmd_dp)); #endif #if (FLASH_SPI_SPLIT_TRANSACTIONS == 0) // Allow access to SPI bus now that flash regulator is disabled. nlspi_release(&g_flash_spi_slave); #else // Disable the flash spi power and control lines nlspi_slave_disable(&g_flash_spi_slave); #endif } return 0; } // read a register with the given size static int read_register(uint8_t cmd, uint8_t *buf, uint8_t num_bytes) { nlspi_transfer_t xfers[2]; xfers[0].tx = &cmd; xfers[0].rx = NULL; xfers[0].num = sizeof(cmd); xfers[0].callback = NULL; xfers[1].tx = NULL; xfers[1].rx = buf, xfers[1].num = num_bytes; xfers[1].callback = NULL; return nlspi_transfer(&g_flash_spi_slave, xfers, ARRAY_SIZE(xfers)); } static int flash_is_busy(void) { int retval; uint8_t status; retval = read_register(CMD_RDSR, &status, sizeof(status)); if (retval) { return retval; } if ((status & M_STAT_BUSY_BIT) == M_STAT_BUSY_VALUE) { return -EBUSY; } return 0; } // Sends a multi-part transaction via spi. // If this is a write operation, it first sends a WREN cmd as a separate // spi transfer (CS required to go high at end of cmd). // Then it sends the cmd+address. // Optionally, if there is data transfer involved, it will send dummy_bytes // and then the transfer. static int spi_cmd_address_data(uint8_t cmd, uint32_t address, bool write, uint8_t *buf, size_t len, uint8_t dummy_bytes) { int retval; nlspi_transfer_t xfers[2]; // max 2 transactions, one for cmd+addr+dummy, and one for data uint8_t cmd_buf[4]; #ifdef CMD_WREN const uint8_t wren[1] = {CMD_WREN}; #endif // for devices like at45db041e with non-binary multiple page sizes, // the address format is page + page offset #if (FLASH_SPI_USE_PAGE_OFFSET_ADDRESSING == 1) unsigned page = address / FLASH_SPI_WRITE_SIZE; unsigned offset = address % FLASH_SPI_WRITE_SIZE; // convert address 18 bits of "address" into // FLASH_SPI_USE_OFFSET_BITS of offset and the // rest as page address and dummy bits address = (page << FLASH_SPI_NUM_OFFSET_BITS) | offset; #endif cmd_buf[3] = ((address >> 0) & 0xFF); cmd_buf[2] = ((address >> 8) & 0xFF); cmd_buf[1] = ((address >> 16) & 0xFF); cmd_buf[0] = cmd; #if (FLASH_SPI_SPLIT_TRANSACTIONS == 1) retval = nlspi_request(&g_flash_spi_slave); if (retval < 0) return retval; #endif // abort if FLASH chip is busy retval = flash_is_busy(); nlREQUIRE(retval >= 0, err_path); #ifdef CMD_WREN // send WREN cmd if this is a write operation. this must be a separate transaction // from the rest because the chip requires CS to go high at end of WREN cmd. if (write) { retval = nlspi_write(&g_flash_spi_slave, wren, sizeof(wren)); nlREQUIRE(retval >= 0, err_path); } #endif // send cmd and address + dummy bytes. For dummy bytes, it will wind up // sending garbage from stack past cmd address, but that should be okay. xfers[0].tx = cmd_buf; xfers[0].rx = NULL; xfers[0].num = sizeof(cmd_buf) + dummy_bytes; xfers[0].callback = NULL; if (len) { if (write) { xfers[1].tx = buf; xfers[1].rx = NULL; } else { xfers[1].tx = NULL; xfers[1].rx = buf; } xfers[1].num = len; xfers[1].callback = NULL; } retval = nlspi_transfer(&g_flash_spi_slave, xfers, len ? 2 : 1); nlREQUIRE(retval >= 0, err_path); err_path: #if (FLASH_SPI_SPLIT_TRANSACTIONS == 1) nlspi_release(&g_flash_spi_slave); #endif return retval; } // poll status register of chip until it's not busy or we timeout static int wait_until_not_busy(uint32_t retry_cnt, uint32_t retry_delay_ms) { int retval; uint8_t status = 0; do { nlplatform_delay_ms(retry_delay_ms); #if (FLASH_SPI_SPLIT_TRANSACTIONS == 1) retval = nlspi_request(&g_flash_spi_slave); nlREQUIRE(retval >= 0, err_path); #endif retval = read_register(CMD_RDSR, &status, sizeof(status)); #if (FLASH_SPI_SPLIT_TRANSACTIONS == 1) nlspi_release(&g_flash_spi_slave); #endif if ((status & M_STAT_BUSY_BIT) == M_STAT_READY_VALUE) { break; } retry_cnt--; } while ((retry_cnt > 0) && (retval >= 0)); #if (FLASH_SPI_SPLIT_TRANSACTIONS == 1) err_path: #endif if (retry_cnt == 0) { return -EIO; } return retval; } static int erase_sector(uint32_t addr, bool isSubSector) { int retval; uint8_t cmd; uint32_t retry_cnt; uint32_t retry_delay_ms; if (isSubSector) { cmd = CMD_SSE; retry_cnt = SSE_DELAY_LOOP_COUNT; retry_delay_ms = SSE_DELAY_MSEC; } else { cmd = CMD_SE; retry_cnt = SE_DELAY_LOOP_COUNT; retry_delay_ms = SE_DELAY_MSEC; } retval = spi_cmd_address_data(cmd, addr, true, NULL, 0, 0); nlREQUIRE(retval >= 0, err_path); retval = wait_until_not_busy(retry_cnt, retry_delay_ms); err_path: return retval; } int nlflash_spi_init(void) { #ifdef FLASH_SPI_USE_PARTIAL_PAGE_BUFFER memset(flash_spi_device.partial_page, 0xff, sizeof(flash_spi_device.partial_page)); #endif return 0; } int nlflash_spi_erase(uint32_t addr, size_t len, size_t *retlen, nlloop_callback_fp callback) { uint32_t num_sub_sectors_beg = 0; uint32_t num_sectors = 0; uint32_t num_sub_sectors_end = 0; uint32_t i; int retval; #ifdef CMD_WREN const uint8_t wren[1] = {CMD_WREN}; #endif retval = nlflash_spi_request(); nlREQUIRE(retval >= 0, done); // Check for bulk erase first if ((addr == 0) && (len == FLASH_SPI_SIZE)) { // erase the entire chip #if CMD_BE_ADDR retval = spi_cmd_address_data(CMD_BE, CMD_BE_ADDR, true, NULL, 0, 0); #else nlspi_transfer_t xfer; uint8_t cmd = CMD_BE; xfer.tx = &cmd; xfer.rx = NULL; xfer.num = sizeof(cmd); xfer.callback = NULL; retval = nlspi_write(&g_flash_spi_slave, wren, sizeof(wren)); nlREQUIRE(retval >= 0, done); retval = nlspi_transfer(&g_flash_spi_slave, &xfer, 1); #endif nlREQUIRE(retval >= 0, done); retval = wait_until_not_busy(BE_DELAY_LOOP_COUNT, BE_DELAY_MSEC); if (retval >= 0) { *retlen = FLASH_SPI_SIZE; } goto done; } // Assume we're at least sub-sector aligned (addr and length) if (len >= FLASH_SPI_FAST_ERASE_SIZE) { // Check sector alignment (assume power of two for sector size) uint32_t left_over = addr % FLASH_SPI_FAST_ERASE_SIZE; if (left_over) { num_sub_sectors_beg = ((FLASH_SPI_FAST_ERASE_SIZE - left_over) / FLASH_SPI_ERASE_SIZE); } // Calculate number of sectors (could do with mask and shift...) len -= (num_sub_sectors_beg * FLASH_SPI_ERASE_SIZE); num_sectors = (len / FLASH_SPI_FAST_ERASE_SIZE); // Finally, get the number of sub-sectors left at the end len -= (num_sectors * FLASH_SPI_FAST_ERASE_SIZE); num_sub_sectors_end = (len / FLASH_SPI_ERASE_SIZE); } else { num_sub_sectors_beg = (len / FLASH_SPI_ERASE_SIZE); } *retlen = 0; for (i = 0; i < num_sub_sectors_beg; i++) { retval = erase_sector(addr, true); nlREQUIRE(retval >= 0, done); addr += FLASH_SPI_ERASE_SIZE; *retlen += FLASH_SPI_ERASE_SIZE; if (callback != NULL) { retval = callback(); nlREQUIRE(retval >= 0, done); } } for (i = 0; i < num_sectors; i++) { retval = erase_sector(addr, false); nlREQUIRE(retval >= 0, done); addr += FLASH_SPI_FAST_ERASE_SIZE; *retlen += FLASH_SPI_FAST_ERASE_SIZE; if (callback != NULL) { retval = callback(); nlREQUIRE(retval >= 0, done); } } for (i = 0; i < num_sub_sectors_end; i++) { retval = erase_sector(addr, true); nlREQUIRE(retval >= 0, done); addr += FLASH_SPI_ERASE_SIZE; *retlen += FLASH_SPI_ERASE_SIZE; if (callback != NULL) { retval = callback(); nlREQUIRE(retval >= 0, done); } } done: nlflash_spi_release(); return retval; } int nlflash_spi_read(uint32_t addr, size_t len, size_t *retlen, uint8_t *buf, nlloop_callback_fp callback) { int retval; *retlen = 0; retval = nlflash_spi_request(); nlREQUIRE(retval >= 0, done); #if FLASH_SPI_HZ > FLASH_SPI_READ_FREQ_HZ // use fast read if the operating frequecy of spi is faster than the regular speed of the FLASH chip retval = spi_cmd_address_data(CMD_FAST_READ, addr, false, buf, len, FLASH_SPI_FAST_READ_DUMMY_CYCLES); #else retval = spi_cmd_address_data(CMD_READ, addr, false, buf, len, FLASH_SPI_READ_DUMMY_CYCLES); #endif nlREQUIRE(retval >= 0, done); *retlen = len; done: nlflash_spi_release(); return retval; } static int write_internal(uint32_t addr, size_t len, const uint8_t *buf) { int retval = spi_cmd_address_data(CMD_PP, addr, true, (uint8_t *)buf, len, 0); nlREQUIRE(retval >= 0, done); retval = wait_until_not_busy(PP_DELAY_LOOP_COUNT, PP_DELAY_MSEC); done: return retval; } int nlflash_spi_write(uint32_t addr, size_t len, size_t *retlen, const uint8_t *buf, nlloop_callback_fp callback) { #ifdef FLASH_SPI_USE_PARTIAL_PAGE_BUFFER uint32_t address = addr; const uint8_t *buffer = buf; size_t length = len; size_t written = 0; int retval = 0; // If not appending to the previously cached page, flush then acquire the cache. if ((length > 0) && (address != ROUNDDOWN(flash_spi_device.write_loc, FLASH_EXTERNAL_WRITE_SIZE) + flash_spi_device.partial_page_index)) { retval = nlflash_spi_flush(); flash_spi_device.write_loc = address; } // If starting mid-page, cache the data. // If the page boundary is hit, flush the cache. if ((retval >= 0) && (length > 0)) { size_t offset = address % FLASH_EXTERNAL_WRITE_SIZE; size_t stride = MIN(FLASH_EXTERNAL_WRITE_SIZE - offset, length); uint8_t *cache = flash_spi_device.partial_page + offset; if (offset > 0) { memcpy(cache, buffer, stride); flash_spi_device.partial_page_index = offset + stride; address += stride; buffer += stride; length -= stride; written += stride; } if (flash_spi_device.partial_page_index == FLASH_EXTERNAL_WRITE_SIZE) { retval = nlflash_spi_flush(); } } // While there's a full page of data, write the data to flash. if ((retval >= 0) && (length > 0)) { size_t stride = FLASH_EXTERNAL_WRITE_SIZE; while (length >= stride) { retval = write_internal(address, stride, buffer); if (retval < 0) { break; } address += stride; buffer += stride; length -= stride; written += stride; } flash_spi_device.write_loc = address; } // Cache any data that's left. if ((retval >= 0) && (length > 0)) { size_t offset = address % FLASH_EXTERNAL_WRITE_SIZE; size_t stride = length; uint8_t *cache = flash_spi_device.partial_page + offset; memcpy(cache, buffer, stride); flash_spi_device.partial_page_index = offset + stride; address += stride; buffer += stride; length -= stride; written += stride; } if (retlen != NULL) { *retlen = written; } return retval; #else /* !defined(FLASH_SPI_USE_PARTIAL_PAGE_BUFFER) */ int retval; *retlen = 0; retval = nlflash_spi_request(); nlREQUIRE(retval >= 0, done); uint32_t offsetInPage = addr % FLASH_SPI_WRITE_SIZE; // write any leading partial pages that don't start on page boundary if (offsetInPage) { int partial_page_size; if (offsetInPage + len > FLASH_SPI_WRITE_SIZE) { partial_page_size = FLASH_SPI_WRITE_SIZE - offsetInPage; } else { partial_page_size = len; } retval = write_internal(addr, partial_page_size, buf); if (retval == 0) { *retlen += partial_page_size; if (partial_page_size == len) { // we wrote it all requested, we're done goto done; } } else { goto done; } len -= partial_page_size; buf += partial_page_size; addr += partial_page_size; } // write any whole pages while (len >= FLASH_SPI_WRITE_SIZE) { retval = write_internal(addr, FLASH_SPI_WRITE_SIZE, buf); if (retval < 0) break; len -= FLASH_SPI_WRITE_SIZE; addr += FLASH_SPI_WRITE_SIZE; buf += FLASH_SPI_WRITE_SIZE; *retlen += FLASH_SPI_WRITE_SIZE; } // write any trailing partial pages if ((retval == 0) && (len > 0)) { retval = write_internal(addr, len, buf); if (retval == 0) { *retlen += len; } } done: nlflash_spi_release(); return retval; #endif /* defined(FLASH_SPI_USE_PARTIAL_PAGE_BUFFER) */ } int nlflash_spi_flush(void) { #ifdef FLASH_SPI_USE_PARTIAL_PAGE_BUFFER int retval = 0; if (flash_spi_device.partial_page_index != 0) { // The write location is the destination address, // thus the offset into the page represents the offset // into the page buffer where the valid data starts. uint32_t address = flash_spi_device.write_loc; size_t offset = address % FLASH_EXTERNAL_WRITE_SIZE; size_t stride = flash_spi_device.partial_page_index > offset ? flash_spi_device.partial_page_index - offset: 0; uint8_t *cache = flash_spi_device.partial_page + offset; retval = write_internal(address, stride, cache); // Reset the partial page if (retval >= 0) { flash_spi_device.write_loc = 0; flash_spi_device.partial_page_index = 0; memset(flash_spi_device.partial_page, 0xff, sizeof(flash_spi_device.partial_page)); } } return retval; #else /* !defined(FLASH_SPI_USE_PARTIAL_PAGE_BUFFER) */ return 0; #endif /* defined(FLASH_SPI_USE_PARTIAL_PAGE_BUFFER) */ } int nlflash_spi_read_id(uint8_t *id_buf, size_t id_buf_size) { int retval; if (id_buf_size < FLASH_SPI_READ_ID_SIZE) { return -EINVAL; } #if (FLASH_SPI_SPLIT_TRANSACTIONS == 1) retval = nlspi_request(&g_flash_spi_slave); if (retval < 0) return retval; #endif retval = nlflash_spi_request(); nlREQUIRE(retval >= 0, done); retval = flash_is_busy(); nlREQUIRE(retval >= 0, done); retval = read_register(CMD_RDID, id_buf, FLASH_SPI_READ_ID_SIZE); nlREQUIRE(retval >= 0, done); done: nlflash_spi_release(); #if (FLASH_SPI_SPLIT_TRANSACTIONS == 1) retval = nlspi_release(&g_flash_spi_slave); #endif return retval; } const nlflash_info_t *nlflash_spi_get_info(void) { return &g_flash_spi_info; } #endif /* FLASH_SPI_SIZE > 0 */
nestlabs/nlplatform
src/nlreset_info.c
/* * * Copyright (c) 2016-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file... * */ #include <nlplatform.h> #include <nlenv.h> #include <FreeRTOS.h> #include <task.h> #ifdef BUILD_FEATURE_RESET_INFO // g_reset_info needs to be in retained/persistent RAM that // maintains it's values across a reboot. // // Currently, two implementations are supported. Either // g_reset_info is in dedicated retained RAM, or it is // in temporary/overlaid retained RAM that is only valid // between a fault and early in the next boot. The latter // implementation saves RAM, but requires an external FLASH // partition in order to save the reset/fault information // so that it is available for later use by the application, // Once reset info is written to, the system *MUST* continue // with a reset soon after and task switching should be disabled. void nlplatform_reset_info_init_done(void) LINKER_REPLACEABLE_FUNCTION(nlplatform_reset_info_init_done_default); #ifdef BUILD_FEATURE_RESET_INFO_IN_TEMP_RAM // NL_RESETINFO_SYMBOL is defined when special section // is used for RESETINFO. It is assumed this is the case // when the section is overlaid with another RAM section // to reduce RAM usage, instead of just using a dedicated // area in RETAIN section. nl_reset_info_t g_reset_info NL_RESETINFO_SYMBOL __attribute__((used)); #ifdef DEBUG // cache of reset reason for querying after boot since the // overlaid RAM will be used by something else once boot is done. static nl_reset_reason_t s_cached_reset_reason; #endif // DEBUG static int save_fault_to_flash(void) { int retval; char fault_dirty_flag; size_t retlen = sizeof(fault_dirty_flag); retval = nl_env_get(kFaultDiagsDirtyKey, &fault_dirty_flag, &retlen); if (retval >= 0) { printf(UNIQUE_PRINTF_FORMAT_STRING("Fault info already dirty, not overwriting\n")); } else { g_reset_info.fault_info.reason = g_reset_info.reset_reason; fault_dirty_flag = '1'; retval = nlflash_erase(NLFLASH_EXTERNAL, NL_FAULT_DIAGS_FLASH_LOCATION, NL_FAULT_DIAGS_FLASH_SIZE, &retlen, NULL); if (retval < 0) { goto flash_ops_failed; } retval = nlflash_write(NLFLASH_EXTERNAL, NL_FAULT_DIAGS_FLASH_LOCATION, sizeof(g_reset_info.fault_info), &retlen, (uint8_t*)&g_reset_info.fault_info, NULL); if (retval < 0) { goto flash_ops_failed; } retval = nl_env_set(kFaultDiagsDirtyKey, (void*)&fault_dirty_flag, sizeof(fault_dirty_flag)); if (retval < 0) { goto flash_ops_failed; } printf(UNIQUE_PRINTF_FORMAT_STRING("Saved reset+fault info to external flash\n")); } flash_ops_failed: if (retval < 0) { printf(UNIQUE_PRINTF_FORMAT_STRING("Saving reset+fault info to external flash failed\n")); } return retval; } void nl_reset_info_init(void) { if (g_reset_info.magic != NL_RESET_INFO_MAGIC) { // make sure g_reset_info.reset_reason and // g_reset_info.fault_info.reason are initialized g_reset_info.reset_reason = NL_RESET_REASON_UNKNOWN; g_reset_info.fault_info.reason = NL_RESET_REASON_UNKNOWN; } // check the status of the reset_reason to see // if the we have reset from a previous app run due to a fault. // if so, save a copy of the fault info flash so we can // later send it to the service. g_reset_info should be // preserved at this early point in boot. // Only write fault info out if it is a fault and not another // type of reset, and only if the flash block isn't already dirty // (dirty is indicated by existence of dirty env) if ((g_reset_info.magic == NL_RESET_INFO_MAGIC) && IS_VALID_FAULT_REASON(g_reset_info.reset_reason)) { save_fault_to_flash(); } #ifdef DEBUG // save last reset reason so we can print it later if desired if ((g_reset_info.magic == NL_RESET_INFO_MAGIC) && (IS_VALID_RESET_REASON(g_reset_info.reset_reason) || IS_VALID_FAULT_REASON(g_reset_info.reset_reason))) { s_cached_reset_reason = g_reset_info.reset_reason; } else { s_cached_reset_reason = NL_RESET_REASON_UNKNOWN; } nl_reset_info_print(); nl_reset_info_print_saved_fault(); #endif // DEBUG // clear magic to indicate we've processed previous reset reason // and are ready for a new reset g_reset_info.magic = 0; // allow platforms to do things after we're done with // the g_reset_info, in case it is overlaid with some // other section nlplatform_reset_info_init_done(); } static void nl_reset_info_set(nl_reset_reason_t reset_reason, const char *fault_description) { g_reset_info.magic = NL_RESET_INFO_MAGIC; g_reset_info.reset_reason = reset_reason; if (IS_VALID_FAULT_REASON(reset_reason)) { // g_reset_info.fault_info is just a cache, the persistent // information is in external FLASH so we always reset the // RAM copy here g_reset_info.fault_info.reason = NL_RESET_REASON_UNKNOWN; if (fault_description != NULL) { strncpy((void*)&g_reset_info.fault_info.description, fault_description, sizeof(nl_fault_description_t)); } } } void nl_reset_info_prepare_reset(nl_reset_reason_t reset_reason, const char *fault_description) { // disable scheduler since we don't want anyone modifying // .resetinfo if it's in an overlaid section vTaskSuspendAll(); // sometimes there are nested faults. if we've already been set, do // nothing since we want to retain the first reason. if (g_reset_info.magic != NL_RESET_INFO_MAGIC) { nl_reset_info_set(reset_reason, fault_description); } } void nl_reset_info_prepare_reset_bootloader(nl_reset_reason_t reset_reason, const char *fault_description) { // If the reset_reason is a fault, we always want to record this // in the bootloader case (unlike nl_reset_info_prepare_reset(), // which doesn't want to overwrite faults until it's been able // to save it off to flash). Otherwise, a preexisting reset reason // like normal SW reset would prevent the bootloader from recording // a fault. if ((g_reset_info.magic != NL_RESET_INFO_MAGIC) || IS_VALID_FAULT_REASON(reset_reason)) { nl_reset_info_set(reset_reason, fault_description); } } int nl_reset_info_get_saved_fault(nl_fault_info_t *saved_fault_info) { int retval = -1; char fault_dirty_flag; size_t retlen = sizeof(fault_dirty_flag); if (nl_env_get(kFaultDiagsDirtyKey, &fault_dirty_flag, &retlen) >= 0) { // read into the provided buffer retval = nlflash_read(NLFLASH_EXTERNAL, NL_FAULT_DIAGS_FLASH_LOCATION, sizeof(*saved_fault_info), &retlen, (uint8_t*)saved_fault_info, NULL); } // sanity check the previous fault info. especially if there was a // change in reset_reason codes, we could get weird info. if (retval == 0) { if (!IS_VALID_FAULT_REASON(saved_fault_info->reason)) { // not valid previous fault, clear it nl_reset_info_clear_saved_fault(); retval = -1; } } return retval; } void nl_reset_info_clear_saved_fault(void) { nl_env_set(kFaultDiagsDirtyKey, NULL, 0); } #else // BUILD_FEATURE_RESET_INFO_IN_TEMP_RAM nl_reset_info_t g_reset_info NL_RETAIN_SYMBOL __attribute__((used)); void nl_reset_info_init(void) { if (g_reset_info.magic != NL_RESET_INFO_MAGIC) { // make sure g_reset_info.reset_reason and // g_reset_info.fault_info.reason are initialized g_reset_info.reset_reason = NL_RESET_REASON_UNKNOWN; nl_reset_info_clear_saved_fault(); } #ifdef DEBUG nl_reset_info_print(); nl_reset_info_print_saved_fault(); #endif // DEBUG // clear magic to indicate we've processed previous reset reason // and are ready for a new reset g_reset_info.magic = 0; // allow platforms to do things after we're done with // the g_reset_info, in case it is overlaid with some // other section nlplatform_reset_info_init_done(); } static void nl_reset_info_set(nl_reset_reason_t reset_reason, const char *fault_description, bool override_fault_reason) { g_reset_info.magic = NL_RESET_INFO_MAGIC; g_reset_info.reset_reason = reset_reason; if (IS_VALID_FAULT_REASON(reset_reason)) { // don't overwrite last fault info if it's not been cleared by app, // to preserve that info for eventual app processing if ((g_reset_info.fault_info.reason == NL_RESET_REASON_UNKNOWN) || (override_fault_reason == true)) { g_reset_info.fault_info.reason = reset_reason; if (fault_description != NULL) { strncpy((void*)&g_reset_info.fault_info.description, fault_description, sizeof(nl_fault_description_t)); } } } } void nl_reset_info_prepare_reset(nl_reset_reason_t reset_reason, const char *fault_description) { // sometimes there are nested faults. if we've already been set, do // nothing since we want to retain the first reason. if (g_reset_info.magic != NL_RESET_INFO_MAGIC) { nl_reset_info_set(reset_reason, fault_description, false); } } void nl_reset_info_prepare_reset_bootloader(nl_reset_reason_t reset_reason, const char *fault_description) { // If the reset_reason is a fault, we always want to record this // in the bootloader case (unlike nl_reset_info_prepare_reset(), // which doesn't want to overwrite faults until it's been able // to save it off to flash). Otherwise, a preexisting reset reason // like normal SW reset would prevent the bootloader from recording // a fault. if ((g_reset_info.magic != NL_RESET_INFO_MAGIC) || IS_VALID_FAULT_REASON(reset_reason)) { nl_reset_info_set(reset_reason, fault_description, true); } } int nl_reset_info_get_saved_fault(nl_fault_info_t *saved_fault_info) { int retval = -1; // our RAM is not shared so our fault info (if any) is valid if (IS_VALID_FAULT_REASON(g_reset_info.fault_info.reason)) { memcpy(saved_fault_info, &g_reset_info.fault_info, sizeof(g_reset_info.fault_info)); retval = 0; } // sanity check the previous fault info. especially if there was a // change in reset_reason codes, we could get weird info. if (retval == 0) { if (!IS_VALID_FAULT_REASON(saved_fault_info->reason)) { // not valid previous fault, clear it nl_reset_info_clear_saved_fault(); retval = -1; } } return retval; } void nl_reset_info_clear_saved_fault(void) { memset(&g_reset_info.fault_info, 0, sizeof(g_reset_info.fault_info)); g_reset_info.fault_info.reason = NL_RESET_REASON_UNKNOWN; } #endif // BUILD_FEATURE_RESET_INFO_IN_TEMP_RAM nl_reset_reason_t nl_reset_info_get_reset_reason(void) { nl_reset_reason_t reset_reason = NL_RESET_REASON_UNKNOWN; if ((g_reset_info.magic == NL_RESET_INFO_MAGIC) && (IS_VALID_RESET_REASON(g_reset_info.reset_reason) || IS_VALID_FAULT_REASON(g_reset_info.reset_reason))) { reset_reason = g_reset_info.reset_reason; } return reset_reason; } #ifdef DEBUG /* The entries in s_reset_reason_strings and * s_fault_reset_reason_strings should match those in * nl_reset_reason_t enum under nlreset_info.h */ const char *s_reset_reason_strings[NL_RESET_REASON_COUNT] = { [NL_RESET_REASON_UNSPECIFIED] = "unspecified", [NL_RESET_REASON_UNKNOWN] = "unknown", [NL_RESET_REASON_SW_REQUESTED] = "sw requested", [NL_RESET_REASON_SW_UPDATE] = "sw update", [NL_RESET_REASON_FACTORY_RESET] = "factory reset" }; const char *s_fault_reset_reason_strings[NL_RESET_REASON_FAULT_COUNT] = { [NL_RESET_REASON_HARD_FAULT - NL_RESET_REASON_FIRST_FAULT] = "hard fault", [NL_RESET_REASON_ASSERT - NL_RESET_REASON_FIRST_FAULT] = "assert", [NL_RESET_REASON_WATCHDOG - NL_RESET_REASON_FIRST_FAULT] = "watchdog", [NL_RESET_REASON_STACK_OVERFLOW - NL_RESET_REASON_FIRST_FAULT] = "stack overflow" }; void nl_reset_info_print(void) { nl_reset_reason_t reset_reason; #ifdef BUILD_FEATURE_RESET_INFO_IN_TEMP_RAM reset_reason = s_cached_reset_reason; #else reset_reason = g_reset_info.reset_reason; #endif if (IS_VALID_RESET_REASON(reset_reason)) { printf(UNIQUE_PRINTF_FORMAT_STRING("Last reset reason: %s\n"), s_reset_reason_strings[reset_reason]); } else if (IS_VALID_FAULT_REASON(reset_reason)) { printf(UNIQUE_PRINTF_FORMAT_STRING("Last fault reset reason: %s\n"), s_fault_reset_reason_strings[reset_reason - NL_RESET_REASON_FIRST_FAULT]); } else { printf(UNIQUE_PRINTF_FORMAT_STRING("Invalid last reset reason %u\n"), (unsigned)reset_reason); } } static const char * const reg_names[] = { " sp", " lr", " pc", "psr" }; void nl_reset_info_print_saved_fault(void) { nl_fault_info_t fault_info; nl_fault_task_info_t *task_info; unsigned i,j; if (nl_reset_info_get_saved_fault(&fault_info) == 0) { // Found a previous fault_info. Print out all associated data printf(UNIQUE_PRINTF_FORMAT_STRING("Previous fault info found! Printing post-mortem info:\n")); printf(UNIQUE_PRINTF_FORMAT_STRING("Fault reason: %s\n"), s_fault_reset_reason_strings[fault_info.reason - NL_RESET_REASON_FIRST_FAULT]); printf(UNIQUE_PRINTF_FORMAT_STRING("Fault Registers:\n")); for (i = 0; i < 13; i++) { printf(UNIQUE_PRINTF_FORMAT_STRING("r%d\t0x%08lx\n"), i, (long unsigned int)fault_info.registers[i]); } for (i = 0; i < ARRAY_SIZE(reg_names); i++) { printf(UNIQUE_PRINTF_FORMAT_STRING("%s\t0x%08lx\n"), reg_names[i], (long unsigned int)fault_info.registers[i+13]); } if (fault_info.active_task_name[0]) { printf(UNIQUE_PRINTF_FORMAT_STRING("Task at time of fault: %s\n"), fault_info.active_task_name); printf(UNIQUE_PRINTF_FORMAT_STRING("Task Info:\n")); for (i = 0; i < ARRAY_SIZE(fault_info.task_info); i++) { task_info = &fault_info.task_info[i]; if (task_info->backtrace[0]) { printf(UNIQUE_PRINTF_FORMAT_STRING("Task: %s%s\n"), task_info->task_name, task_info->task_state); for (j = 0; j < ARRAY_SIZE(task_info->backtrace) && task_info->backtrace[j] != 0; j++) { printf(UNIQUE_PRINTF_FORMAT_STRING("\t0x%08lx\n"), (long unsigned int)task_info->backtrace[j]); } } } } if (fault_info.machine_backtrace[0]) { printf(UNIQUE_PRINTF_FORMAT_STRING("Machine Backtrace:\n")); for (j = 0; j < ARRAY_SIZE(fault_info.machine_backtrace) && fault_info.machine_backtrace[j] != 0; j++) { printf(UNIQUE_PRINTF_FORMAT_STRING("\t0x%08lx\n"), (long unsigned int)fault_info.machine_backtrace[j]); } } if (fault_info.description[0]) { printf(UNIQUE_PRINTF_FORMAT_STRING("Fault description: [%*s]\n"), (int)sizeof(fault_info.description), fault_info.description); } } else { printf(UNIQUE_PRINTF_FORMAT_STRING("No previous fault info\n")); } } #endif // DEBUG void nlplatform_reset_info_init_done_default(void); void nlplatform_reset_info_init_done_default(void) { } #endif // BUILD_FEATURE_RESET_INFO
nestlabs/nlplatform
src/cpu/arm/cortex-m0/builtin.c
<filename>src/cpu/arm/cortex-m0/builtin.c<gh_stars>1-10 /* * * Copyright (c) 2016-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Description: * The following implementations satisfy GCC built-in support on CM0 * architecture. * * @note * GCC supports these API's with built-in inline assembly on CM3-4 architectures. * However due to the lack of a sufficiently robust instruction Set on CM0, * GCC leaves implementation of these API's to the platform. As there are * modules that use these API's, implementation is provided here for CM0 * based platforms. When GCC fails to provide a solution, it substitutes the * function call for one whose name is foo_n() where "n" is the size in bytes * of the parameter being tested. Hence the function names below have the * "_n" appended which corresponds to the byte width of the value under test. */ #include <stdint.h> #include <nlplatform.h> typedef enum { kOperandAnd = 0, kOperandAdd, kOperandSub, kOperandOr, kOperandXor } operand_t; static bool __sync_bool_compare_and_swap_internal(void *ptr, void *oldval, void *newval, uint8_t size) { bool retval = false; nlplatform_interrupt_disable(); { __sync_synchronize(); switch (size) { case 1: if (*(uint8_t *)ptr == *(uint8_t *)oldval) { *(uint8_t *)ptr = *(uint8_t *)newval; retval = true; } break; case 2: if (*(uint16_t *)ptr == *(uint16_t *)oldval) { *(uint16_t *)ptr = *(uint16_t *)newval; retval = true; } break; case 4: if (*(uint32_t *)ptr == *(uint32_t *)oldval) { *(uint32_t *)ptr = *(uint32_t *)newval; retval = true; } break; default: break; } if (retval) { __sync_synchronize(); } } nlplatform_interrupt_enable(); return retval; } bool __sync_bool_compare_and_swap_1(uint8_t *ptr, uint8_t oldval, uint8_t newval) { return __sync_bool_compare_and_swap_internal(ptr, &oldval, &newval, 1); } bool __sync_bool_compare_and_swap_2(uint16_t *ptr, uint16_t oldval, uint16_t newval) { return __sync_bool_compare_and_swap_internal(ptr, &oldval, &newval, 2); } bool __sync_bool_compare_and_swap_4(uint32_t *ptr, uint32_t oldval, uint32_t newval) { return __sync_bool_compare_and_swap_internal(ptr, &oldval, &newval, 4); } uint8_t __sync_sub_and_fetch_1(uint8_t *ptr, uint8_t val) { uint8_t retval; nlplatform_interrupt_disable(); { __sync_synchronize(); *ptr -= val; retval = *ptr; __sync_synchronize(); } nlplatform_interrupt_enable(); return retval; } static uint8_t __sync_fetch_and_1(uint8_t *ptr, uint8_t val, operand_t oper) { uint8_t retval; nlplatform_interrupt_disable(); { __sync_synchronize(); retval = *ptr; switch (oper) { case kOperandAnd: *ptr &= val; break; case kOperandAdd: *ptr += val; break; case kOperandSub: *ptr -= val; break; case kOperandOr: *ptr |= val; break; case kOperandXor: *ptr ^= val; break; default: break; } __sync_synchronize(); } nlplatform_interrupt_enable(); return retval; } uint8_t __sync_fetch_and_sub_1(uint8_t *ptr, uint8_t val) { return __sync_fetch_and_1(ptr, val, kOperandSub); } uint8_t __sync_fetch_and_add_1(uint8_t *ptr, uint8_t val) { return __sync_fetch_and_1(ptr, val, kOperandAdd); } uint8_t __sync_fetch_and_and_1(uint8_t *ptr, uint8_t val) { return __sync_fetch_and_1(ptr, val, kOperandAnd); } uint8_t __sync_fetch_and_or_1(uint8_t *ptr, uint8_t val) { return __sync_fetch_and_1(ptr, val, kOperandOr); } uint8_t __sync_fetch_and_xor_1(uint8_t *ptr, uint8_t val) { return __sync_fetch_and_1(ptr, val, kOperandXor); }
nestlabs/nlplatform
include/nltimer.h
<gh_stars>1-10 /* * * Copyright (c) 2015-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file defines API for HW timers */ #ifndef __NLTIMER_H_INCLUDED__ #define __NLTIMER_H_INCLUDED__ #include <stdint.h> #include <nlplatform.h> #ifdef __cplusplus extern "C" { #endif /* If in FreeRTOS environment, return 1 if a higher priroity task was woken and * a context switch should occur at end of ISR that invoked the callback. */ typedef int (*nltimer_handler_t)(nltimer_id_t timer_id, void *context); void nltimer_init(void); int nltimer_request(nltimer_id_t timer_id); int nltimer_release(nltimer_id_t timer_id); /* If callback is NULL, timer expiration can be polled with nltimer_active. * nltimer_start must be called to start the timer. */ int nltimer_set(nltimer_id_t timer_id, uint32_t time_us, nltimer_handler_t callback, void *context, bool auto_restart); int nltimer_start(nltimer_id_t timer_id); int nltimer_stop(nltimer_id_t timer_id); /* Restarts the timer from 0. */ int nltimer_reset(nltimer_id_t timer_id); /* Returns the number of microseconds since start for an active timer. * If the timer was not active, it returns the starting elapsed time * if the timer were restarted without a reset. */ uint32_t nltimer_elapsed(nltimer_id_t timer_id); /* Return nonzero if the timer is running. */ int nltimer_active(nltimer_id_t timer_id); #ifdef __cplusplus } #endif #endif /* __NLTIMER_H_INCLUDED__ */
nestlabs/nlplatform
include/nlflash_spi.h
<reponame>nestlabs/nlplatform<filename>include/nlflash_spi.h /* * * Copyright (c) 2015-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file defines an APi for accessing flash through a * SPI interface. * */ #ifndef __NLFLASH_SPI_H_INCLUDED__ #define __NLFLASH_SPI_H_INCLUDED__ #include <nlplatform/nlflash.h> #include <nlplatform/nlspi.h> #ifdef __cplusplus extern "C" { #endif extern const nlspi_slave_t g_flash_spi_slave; extern const nlflash_info_t g_flash_spi_info; int nlflash_spi_init(void); int nlflash_spi_request(void); int nlflash_spi_release(void); const nlflash_info_t *nlflash_spi_get_info(void); int nlflash_spi_read_id(uint8_t *id_buf, size_t id_buf_size); int nlflash_spi_erase(uint32_t addr, size_t len, size_t *retlen, nlloop_callback_fp callback); int nlflash_spi_read(uint32_t addr, size_t len, size_t *retlen, uint8_t *buf, nlloop_callback_fp callback); int nlflash_spi_write(uint32_t addr, size_t len, size_t *retlen, const uint8_t *buf, nlloop_callback_fp callback); int nlflash_spi_flush(void); #ifdef __cplusplus } #endif #endif /* __NLFLASH_SPI_H_INCLUDED__ */
nestlabs/nlplatform
include/nlpwm.h
/* * * Copyright (c) 2017-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file defines the interfaces for the PWM subsystem. * * Usage: * * Initialize the PWM subsystem with nlpwm_init(); this should only be done * once. * * Claim and configure a PWM output using nlpwm_request(); this is a blocking * call, and will wait until the PWM is available. * * Release ownership of a PWM output using nlpwm_release(). It is an error to * release a previously un-requested PWM output. */ #ifndef __NLPWM_H_INCLUDED__ #define __NLPWM_H_INCLUDED__ #include <stdint.h> #include <nlproduct_config.h> #define NL_PWM_FREQ_MAX NL_PLATFORM_PWM_FREQ_MAX #define NL_PWM_DUTY_MAX TYPE_MAX(((nlpwm_config_t*)0)->mDuty) #ifdef __cplusplus extern "C" { #endif typedef uint8_t nlpwm_id_t; typedef struct { uint32_t mFreq; uint8_t mDuty; } nlpwm_config_t; void nlpwm_init(void); int nlpwm_request(nlpwm_id_t aId, const nlpwm_config_t *aConfig); int nlpwm_release(nlpwm_id_t aId); #ifdef __cplusplus } #endif #endif /* __NLPWM_H_INCLUDED__ */
nestlabs/nlplatform
src/compiler/apple/xcode/cxx-symbols.c
/* * * Copyright (c) 2015-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file implments functions used by Clang during C++ static * initialization; specifically, locks to guard that initialization. These * are necessary when linking against a "reduced" standard library. * */ #include <stdint.h> // forward declarations void __cxa_pure_virtual(void); int __cxa_guard_acquire(uint64_t* guard_object); void __cxa_guard_release(uint64_t* guard_object); void __cxa_guard_abort(uint64_t* guard_object); void _ZdlPv(void*); // a global void *__dso_handle; // Defines to squelch warnings #define abort_message(s) void __cxa_pure_virtual(void) { while (1); } #if 0 static pthread_mutex_t __guard_mutex; static pthread_once_t __once_control = PTHREAD_ONCE_INIT; static void makeRecusiveMutex() { pthread_mutexattr_t recursiveMutexAttr; pthread_mutexattr_init(&recursiveMutexAttr); pthread_mutexattr_settype(&recursiveMutexAttr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&__guard_mutex, &recursiveMutexAttr); } __attribute__((noinline)) static pthread_mutex_t* guard_mutex() { pthread_once(&__once_control, &makeRecusiveMutex); return &__guard_mutex; } #endif // helper functions for getting/setting flags in guard_object static uint8_t initializerHasRun(uint64_t* guard_object) { return ( *((uint8_t*)guard_object) != 0 ); } static void setInitializerHasRun(uint64_t* guard_object) { *((uint8_t*)guard_object) = 1; } static uint8_t inUse(uint64_t* guard_object) { return ( ((uint8_t*)guard_object)[1] != 0 ); } static void setInUse(uint64_t* guard_object) { ((uint8_t*)guard_object)[1] = 1; } static void setNotInUse(uint64_t* guard_object) { ((uint8_t*)guard_object)[1] = 0; } // // Returns 1 if the caller needs to run the initializer and then either // call __cxa_guard_release() or __cxa_guard_abort(). If zero is returned, // then the initializer has already been run. This function blocks // if another thread is currently running the initializer. This function // aborts if called again on the same guard object without an intervening // call to __cxa_guard_release() or __cxa_guard_abort(). // int __cxa_guard_acquire(uint64_t* guard_object) { // Double check that the initializer has not already been run if ( initializerHasRun(guard_object) ) return 0; // We now need to acquire a lock that allows only one thread // to run the initializer. If a different thread calls // __cxa_guard_acquire() with the same guard object, we want // that thread to block until this thread is done running the // initializer and calls __cxa_guard_release(). But if the same // thread calls __cxa_guard_acquire() with the same guard object, // we want to abort. // To implement this we have one global pthread recursive mutex // shared by all guard objects, but only one at a time. #if 0 int result = ::pthread_mutex_lock(guard_mutex()); if ( result != 0 ) { abort_message("__cxa_guard_acquire(): pthread_mutex_lock " "failed with %d\n", result); } #endif // At this point all other threads will block in __cxa_guard_acquire() // Check if another thread has completed initializer run if ( initializerHasRun(guard_object) ) { #if 0 int result = ::pthread_mutex_unlock(guard_mutex()); if ( result != 0 ) { abort_message("__cxa_guard_acquire(): pthread_mutex_unlock " "failed with %d\n", result); } #endif return 0; } // The pthread mutex is recursive to allow other lazy initialized // function locals to be evaluated during evaluation of this one. // But if the same thread can call __cxa_guard_acquire() on the // *same* guard object again, we call abort(); if ( inUse(guard_object) ) { abort_message("__cxa_guard_acquire(): initializer for function " "local static variable called enclosing function\n"); } // mark this guard object as being in use setInUse(guard_object); // return non-zero to tell caller to run initializer return 1; } // // Sets the first byte of the guard_object to a non-zero value. // Releases any locks acquired by __cxa_guard_acquire(). // void __cxa_guard_release(uint64_t* guard_object) { // first mark initalizer as having been run, so // other threads won't try to re-run it. setInitializerHasRun(guard_object); #if 0 // release global mutex int result = ::pthread_mutex_unlock(guard_mutex()); if ( result != 0 ) { abort_message("__cxa_guard_acquire(): pthread_mutex_unlock " "failed with %d\n", result); } #endif } // // Releases any locks acquired by __cxa_guard_acquire(). // void __cxa_guard_abort(uint64_t* guard_object) { #if 0 int result = ::pthread_mutex_unlock(guard_mutex()); if ( result != 0 ) { abort_message("__cxa_guard_abort(): pthread_mutex_unlock " "failed with %d\n", result); } #endif // now reset state, so possible to try to initialize again setNotInUse(guard_object); }
nestlabs/nlplatform
src/cpu/arm/cortex-m0/fault.c
<reponame>nestlabs/nlplatform /* * * Copyright (c) 2016-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file implements an API for handling crashes and provides fault * handlers. This file also defines data structures, that are saved to RAM * on a hard fault, that are useful for debugging. * */ #include <nlplatform.h> #include <nlplatform/nlfault.h> #include <stdio.h> #include <stddef.h> #include <string.h> #include <FreeRTOS.h> #include <task.h> #include <nlertask.h> #include <nlplatform.h> #include <nlplatform/nlfault.h> #if defined(BUILD_FEATURE_RAM_CONSOLE) #include <nlplatform/nlram_console.h> #endif #include <nlplatform/nlwatchdog.h> #include <nlbacktrace.h> #ifdef BUILD_FEATURE_BREADCRUMBS #include <nlbreadcrumbs.h> #include <nlbreadcrumbs-local.h> #include <nlbreadcrumbs-all.h> #endif /* BUILD_FEATURE_BREADCRUMBS */ #include <nlutilities.h> #define SCB_CFSR_IACCVIOL ((uint32_t)0x00000001) #define SCB_CFSR_DACCVIOL ((uint32_t)0x00000002) #define SCB_CFSR_MUNSTKERR ((uint32_t)0x00000008) #define SCB_CFSR_MSTKERR ((uint32_t)0x00000010) #define SCB_CFSR_MMARVALID ((uint32_t)0x00000080) #define SCB_CFSR_IBUSERR ((uint32_t)0x00000100) #define SCB_CFSR_PRECISERR ((uint32_t)0x00000200) #define SCB_CFSR_IMPRECISERR ((uint32_t)0x00000400) #define SCB_CFSR_UNSTKERR ((uint32_t)0x00000800) #define SCB_CFSR_STKERR ((uint32_t)0x00001000) #define SCB_CFSR_BFARVALID ((uint32_t)0x00008000) #define SCB_CFSR_UNDEFINSTR ((uint32_t)0x00010000) #define SCB_CFSR_INVSTATE ((uint32_t)0x00020000) #define SCB_CFSR_INVPC ((uint32_t)0x00040000) #define SCB_CFSR_NOCP ((uint32_t)0x00080000) #define SCB_CFSR_UNALIGNED ((uint32_t)0x01000000) #define SCB_CFSR_DIVBYZERO ((uint32_t)0x02000000) /* For stack overflows, we want nlbacktrace()/nlbacktrace_with_lr() to return a minimum * number of backtrace levels, since a stack overflow should have many call levels. * If the minimum is not met, we call nlbacktrace_no_context() * instead to get a longer list of possible LR values from the stack because we * presume that the former failed for some reason (bad pc or lr or both). */ #define MIN_BACKTRACE_LEVELS_FOR_STACK_OVERFLOW 3 typedef enum { FAULT = 0, WDT } crashType; // table to convert from crashType to nl_reset_reason_t const nl_reset_reason_t kCrashTypeToResetReason[] = { NL_RESET_REASON_HARD_FAULT, // FAULT, generic NL_RESET_REASON_WATCHDOG // WDT }; /* r0-r3: low registers saved on process stack by CPU automatically on exception */ #define NUM_LOW_REGISTERS_ON_PROCESS_STACK 4 /* r12, lr (r14), pc (r15), psr: high reigsters saved on process stack */ #define NUM_HIGH_REGISTERS_ON_PROCESS_STACK 4 /* r4-r11 are registers we saved in common_fault_handler_c onto the main stack */ #define NUM_REGISTERS_ON_MAIN_STACK 8 /* number of entries to dump from the stack */ #define NUM_STACK_DUMP_ENTRIES 16 /* Struct representing what FreeRTOS pushed onto the stack of a non-current task */ typedef struct { /* r4-r11 is pushed by the PendSV SW interrupt handler of FreeRTOS */ uint32_t r4; uint32_t r5; uint32_t r6; uint32_t r7; uint32_t r8; uint32_t r9; uint32_t r10; uint32_t r11; /* r0-r3, r12, lr, pc, psr are pushed by the PendSV HW interrupt of Cortex M0 */ ExceptionStackFrame_t pendSVFrame; } switched_out_stack_frame_t; /* saved/restored stack has an extra word if bit 9 of psr is set */ #define PSR_EXTRA_STACK_ALIGN_BIT (1 << 9) #ifdef DEBUG #define faultDebugPrint(...) printf(__VA_ARGS__) #else #define faultDebugPrint(...) #endif /* Special macro to put string literals into named sections so dead * stripping works in older versions of gcc. This does prevent * merging of the same string, so it's best if these are unique. */ #define UNIQUE_STRING_LITERAL(str) ({ static const char __str[] = str; __str; }) /* When tokenizing, the first argument to printf must be a * string literal, but when not tokenizing, we want the * string to named so it can be dead stripped by the * current version of gcc we're using (future versions don't * need this). */ #ifdef BUILD_FEATURE_PRINTF_TOKENIZATION #define UNIQUE_PRINTF_FORMAT_STRING(str) str #else #define UNIQUE_PRINTF_FORMAT_STRING(str) UNIQUE_STRING_LITERAL(str) #endif #if !defined(BUILD_FEATURE_RESET_INFO) || (defined(BUILD_FEATURE_RESET_INFO) && !defined(BUILD_FEATURE_RESET_INFO_IN_TEMP_RAM)) static uint32_t s_backtrace[NL_FAULT_DIAGS_NUM_BT_ENTRIES]; #endif /* Functions that are designed to be replaced by linker scripts for * different binaries. Binaries that have no freertos should replace * crash_dump with crash_dump_nortos, or use crash_dump_default but * replace some of the subroutines called with stubs to get just * a subset of the information depending on FLASH limitations * (e.g. one could get just the registers without backtraces, or * registers and backtraces but no breadcrumbs, etc). */ void crash_dump(uint32_t *faultingStackAddress , uint32_t *machineStackAddress, crashType type) LINKER_REPLACEABLE_FUNCTION(crash_dump_default); /* Parts of crash_dump_default() that can be stubbed to reduce FLASH footprint. * Bootloader/AUPD can use crash_dump_nortos() for of crash_dump() to get * the smallest size, but will have no fault information. Alternatively, * they can use crash_dump_default(), but stub out parts of it to reduce * flash size but still get some crash information. * nortos builds using crash_dump_default() should always stub the following * since they don't have tasks: * * get_and_dump_current_task_info() * dump_watchdog_flags() * dump_all_tasks() * * They can also stub out these to reduce info collected, and reduce flash size: * * crash_dump_breadcrumbs() - probably don't want to write to flash in bootloader * dump_context_to_reset_info() * dump_backtrace() - backtrace library is pretty large * dump_context() - if no printf, this is not useful */ void get_and_dump_current_task_info(const char **name, nl_reset_reason_t *reset_reason, uint32_t *stackTop) LINKER_REPLACEABLE_FUNCTION(get_and_dump_current_task_info_default); void dump_watchdog_flags(void) LINKER_REPLACEABLE_FUNCTION(dump_watchdog_flags_default); void dump_context(uint32_t *faultingStackAddress , uint32_t *machineStackAddress, crashType type, uint32_t prefault_sp) LINKER_REPLACEABLE_FUNCTION(dump_context_default); void dump_backtrace(ExceptionStackFrame_t *faultFrame, uint32_t *backtrace_buf, unsigned *backtrace_count, uint32_t prefault_sp, uint32_t stackTop, nl_reset_reason_t reset_reason) LINKER_REPLACEABLE_FUNCTION(dump_backtrace_default); #ifdef BUILD_FEATURE_RESET_INFO #define STACK_TRACE_DEPTH NL_FAULT_DIAGS_NUM_BT_ENTRIES #define TASK_NAME_LEN NL_FAULT_DIAGS_TASK_NAME_LEN #else #define STACK_TRACE_DEPTH 7 #define TASK_NAME_LEN 4 #endif // The TCB might have more characters in the name than 4, but to keep things // small for breadcrumbs, we just use 4 (3 for name, and 1 for task state). typedef struct ThreadDumpInfo { uint32_t stackDepth; uint32_t stackTrace[STACK_TRACE_DEPTH]; char name[TASK_NAME_LEN]; //make it aligned } ThreadDumpInfo_t; int threadNum = 0; // Optional API to dump SOC-specific context information on fault void nlplatform_soc_dump_context(void) NL_WEAK_ATTRIBUTE; // Optional API to dump product-specific context information on fault void nlproduct_dump_context(void) NL_WEAK_ATTRIBUTE; static uint32_t get_task_stack_top(const xTaskHandle taskHandle) { uint32_t stackTop; nltask_t *nltask_p = (nltask_t*)taskHandle; if (nltask_p == NULL) { // Not an NLER task, just use 0 and use the looser check for valid SP. // This is probably the FreeRTOS idle task. stackTop = 0; } else { // Get the stack top from the nltask_t stackTop = (uint32_t)nltask_p->mStackTop; } return stackTop; } void nlfault_dump_callstack(void) { uint32_t buffer[8]; int j; int num_backtraces; uint32_t stackTop = 0; uint32_t sp = nlplatform_get_sp(); uint32_t pc = nlplatform_get_pc(); xTaskHandle taskHandle = xTaskGetCurrentTaskHandle(); if (taskHandle) { stackTop = get_task_stack_top(taskHandle); } num_backtraces = nlbacktrace(pc, sp, stackTop, buffer, ARRAY_SIZE(buffer)); for (j = 0; j < num_backtraces; j++) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("0x%08lx\n"), buffer[j]); } } static void __attribute__( ( naked ) ) __attribute__( ( used ) ) common_fault_handler_c(void) { __asm volatile ( // push r4-r12 and lr on the stack. in ARMV7m, this is equivalent to // "stmdb sp!, {r4-r12,lr}" but ARMV6 has no stmdb and push can // only push r0-r7. must push registers in multiples of 2 to // keep stack aligned on 8-byte boundaries. " push {r4-r7} \n" " movs r0, r8 \n" " movs r1, r9 \n" " movs r2, r10 \n" " movs r3, r11 \n" " movs r4, r12 \n" " push {r0-r4, lr} \n" // test lr bit #4 to see if this was a fault on the main stack // or on the process/thread stack " movs r0, #4 \n" " movs r1, lr \n" " tst r1, r0 \n" // If fault on main stack, load main stack pointer plus 36 (for the // registers we just pushed above) to r0, so that r0 points to // the exception frame (i.e. does not have the extra registers // we just pushed) " bne hard_fault_on_process_stack \n" " hard_fault_on_main_stack: \n" " mrs r0, msp \n" " add r0, r0, #40 \n" " b call_crash_dump \n" " hard_fault_on_process_stack: \n" // If fault on process/thread stack, load r0 with psp " mrs r0, psp \n" " call_crash_dump: \n" // Load r1 with msp " mrs r1, msp \n" // Call our generic crash_dump function. " bl crash_dump \n" // In case we're told to resume, restore registers from stack. // Equivalent on ARMV7 to "ldmia sp!, {r4-r12,pc} " pop {r0-r5} \n" " movs r8, r0 \n" " movs r9, r1 \n" " movs r10, r2 \n" " movs r11, r3 \n" " movs r12, r4 \n" " movs lr, r5 \n" " pop {r4-r7} \n" " bx lr \n" ); } void __attribute__( ( naked ) ) nlfault_hard_fault_handler_c(void) { __asm volatile ( " mov r2, #0 \n" " b common_fault_handler_c \n" ); } void __attribute__( ( naked ) ) nlfault_pre_watchdog_handler_c(void) { __asm volatile ( " mov r2, #1 \n" " b common_fault_handler_c \n" ); } #if defined(BUILD_FEATURE_FAULT_DUMP_TASK_STACKS) void dump_all_tasks(bool task_fault) LINKER_REPLACEABLE_FUNCTION(dump_all_tasks_default); #if !defined(configMAX_NUM_TASKS) #define THREAD_DUMP_MAX_NUM_THREADS 11 #else #define THREAD_DUMP_MAX_NUM_THREADS configMAX_NUM_TASKS #endif typedef struct fakeTCB { volatile switched_out_stack_frame_t *switched_out_stack_frame_p; } fakeTCB_t; //(gdb) p/d &((tskTCB *)0)->pcTaskName //$3 = 52 #define TCB_OFFSET_NAME 52 #define tskACTIVE_CHAR ( 'A' ) #define tskBLOCKED_CHAR ( 'B' ) #define tskREADY_CHAR ( 'R' ) #define tskDELETED_CHAR ( 'D' ) #define tskSUSPENDED_CHAR ( 'S' ) // Don't allow this to be inlined to minimize stack usage of calling function. // The calling task does printf calls which, with tokenization and ram_console, // needs a lot of stack space. static uint32_t threadDump(TaskStatus_t *task_status, char *task_name, char *task_state, uint32_t *backtrace_buf, ExceptionStackFrame_t *custom_exception_frame) __attribute__((noinline)); static uint32_t threadDump(TaskStatus_t *task_status, char *task_name, char *task_state, uint32_t *backtrace_buf, ExceptionStackFrame_t *custom_exception_frame) { volatile fakeTCB_t *tcb = (volatile fakeTCB_t *)task_status->xHandle; uint32_t lr; uint32_t pc; uint32_t psr; uint32_t sp; char cStatus; switch (task_status->eCurrentState) { case eRunning: cStatus = tskACTIVE_CHAR; break; case eReady: cStatus = tskREADY_CHAR; break; case eBlocked: cStatus = tskBLOCKED_CHAR; break; case eSuspended: cStatus = tskSUSPENDED_CHAR; break; case eDeleted: cStatus = tskDELETED_CHAR; break; default: /* Should not get here, but it is included to prevent static checking errors. */ cStatus = 0x00; break; } if (custom_exception_frame == NULL) { lr = tcb->switched_out_stack_frame_p->pendSVFrame.lr; pc = tcb->switched_out_stack_frame_p->pendSVFrame.pc; psr = tcb->switched_out_stack_frame_p->pendSVFrame.psr; sp = (uint32_t)&tcb->switched_out_stack_frame_p->pendSVFrame.stack[0]; } else { lr = custom_exception_frame->lr; pc = custom_exception_frame->pc; psr = custom_exception_frame->psr; sp = (uint32_t)&custom_exception_frame->stack[0]; } if (psr & PSR_EXTRA_STACK_ALIGN_BIT) { sp += 4; } strncpy(task_name, pcTaskGetTaskName(task_status->xHandle), TASK_NAME_LEN-1); task_state[0] = cStatus; return nlbacktrace_with_lr(pc, lr, sp, get_task_stack_top(task_status->xHandle), backtrace_buf, STACK_TRACE_DEPTH); } // Don't allow this to be inlined to minimize stack usage of calling function static void threadDumpLocalBuf(TaskStatus_t *task_status, ExceptionStackFrame_t *custom_exception_frame) __attribute__((noinline)); static void threadDumpLocalBuf(TaskStatus_t *task_status, ExceptionStackFrame_t *custom_exception_frame) { ThreadDumpInfo_t localThreadState = {0}; uint32_t backtrace_count = threadDump(task_status, localThreadState.name, &localThreadState.name[sizeof(localThreadState.name)-1], localThreadState.stackTrace, custom_exception_frame); faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("Task: %.*s%c\n"), sizeof(localThreadState.name), localThreadState.name, localThreadState.name[sizeof(localThreadState.name)-1]); for (unsigned i = 0; i < backtrace_count; i++) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING(" 0x%08lx\n"), localThreadState.stackTrace[i]); } } void dump_all_tasks_default(bool task_fault); void dump_all_tasks_default(bool task_fault) { // Get task handles into statusArray, then set their statuses, // get task and backtrace information using threadDump(), and // then print that info static TaskStatus_t statusArray[THREAD_DUMP_MAX_NUM_THREADS]; unsigned backtrace_idx; xTaskHandle active_task_handle = xTaskGetCurrentTaskHandle(); faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("All tasks\n")); #if defined(BUILD_FEATURE_RESET_INFO) bool save_fault_to_reset_info; #ifdef BUILD_FEATURE_RESET_INFO_IN_TEMP_RAM // g_reset_info is just a cache so we always save to it and // let the subsequent boot decide whether to move the RAM // copy to the external FLASH backing store save_fault_to_reset_info = true; #else // BUILD_FEATURE_RESET_INFO_IN_TEMP_RAM // g_reset_info is our backing store since it is dedicated // retained RAM. only save this fault info if the any previous // fault has been cleared. if ((g_reset_info.fault_info.reason == NL_RESET_REASON_UNKNOWN) || (g_reset_info.fault_info.reason == NL_RESET_REASON_ASSERT)) { save_fault_to_reset_info = true; } else { save_fault_to_reset_info = false; } #endif // BUILD_FEATURE_RESET_INFO_IN_TEMP_RAM if (save_fault_to_reset_info) { if (!task_fault) { strcpy(g_reset_info.fault_info.active_task_name, "N/A"); backtrace_idx = 0; } else { // Current task always occupies index 0 of fault_info struct. It has already been populated by backtrace dump // routine. Populate the name field and skip copying the backtrace. memset(&g_reset_info.fault_info.active_task_name, 0, sizeof(g_reset_info.fault_info.active_task_name)); memset(&g_reset_info.fault_info.task_info[0].task_name, 0, sizeof(g_reset_info.fault_info.task_info[0].task_name)); strncpy(g_reset_info.fault_info.active_task_name, pcTaskGetTaskName(active_task_handle), NL_FAULT_DIAGS_TASK_NAME_LEN - 1); strncpy(g_reset_info.fault_info.task_info[0].task_name, pcTaskGetTaskName(active_task_handle), NL_FAULT_DIAGS_TASK_NAME_LEN - 1); g_reset_info.fault_info.task_info[0].task_state[0] = tskREADY_CHAR; backtrace_idx = 1; } } #endif // BUILD_FEATURE_RESET_INFO // Note that uxTaskGetNumberOfTasks() might not return the same // count as uxTaskGetSystemStateFromFault() if a fault occurred in // FreeRTOS when the current task was being removed from the // ready list but before it was placed on a blocked list. In // this special case, uxTaskGetNumberOfTasks() would return one // more than the value uxTaskGetSystemStateFromFault() returns. unsigned numTasks = (unsigned) uxTaskGetSystemStateFromFault(statusArray, THREAD_DUMP_MAX_NUM_THREADS, NULL); for (unsigned idx = 0; idx < numTasks; idx++) { ExceptionStackFrame_t *active_task_psp = NULL; /* The information about the current task was dumped from the * exception context. The FreeRTOS TCB context will not be valid * and trying to dump from it might lead to double faults because * the values from the TCB stack top won't be valid. */ if (!task_fault && active_task_handle == statusArray[idx].xHandle) { /* This is a fault on the machine stack, and we are trying to dump the active task when the * interrupt or exception occurred. We want to get the stack pointer from the PSP, and get the * PC and LR from the exception frame dumped on the machine stack */ active_task_psp = (ExceptionStackFrame_t*)nlplatform_get_psp(); } else if (statusArray[idx].xHandle == active_task_handle) { /* This is a fault on a task stack, and this is the TCB of that task. We have already dumped out * the backtrace so just skip this one. */ continue; } #if defined(BUILD_FEATURE_RESET_INFO) if (save_fault_to_reset_info) { memset(&g_reset_info.fault_info.task_info[backtrace_idx], 0, sizeof(g_reset_info.fault_info.task_info[backtrace_idx])); uint32_t backtrace_count = threadDump(&statusArray[idx], g_reset_info.fault_info.task_info[backtrace_idx].task_name, g_reset_info.fault_info.task_info[backtrace_idx].task_state, g_reset_info.fault_info.task_info[backtrace_idx].backtrace, active_task_psp); // print outside of thread_dump() to give faultDebugPrintf() as much free stack as possible. // tokenized logs w/ ram_console takes over 200 bytes of stack! faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("Task: %.*s%c\n"), sizeof(g_reset_info.fault_info.task_info[backtrace_idx].task_name), g_reset_info.fault_info.task_info[backtrace_idx].task_name, g_reset_info.fault_info.task_info[backtrace_idx].task_state[0]); for (unsigned i = 0; i < backtrace_count; i++) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING(" 0x%08lx\n"), g_reset_info.fault_info.task_info[backtrace_idx].backtrace[i]); } } else { threadDumpLocalBuf(&statusArray[idx], active_task_psp); } #else threadDumpLocalBuf(&statusArray[idx], active_task_psp); #endif backtrace_idx++; } } #endif /* defined(BUILD_FEATURE_FAULT_DUMP_TASK_STACKS) */ #ifdef BUILD_FEATURE_BREADCRUMBS /* Use linker script to replace crash_dump_breadcrumbs with * a stub function if no breadcrumbs from faults is desired. */ void crash_dump_breadcrumbs(const uint32_t *backtrace, size_t num_backtrace_entries, const char * current_task_name, bool dump_all_tasks) LINKER_REPLACEABLE_FUNCTION(nltransfer_fault_to_breadcrumbs); void nltransfer_fault_to_breadcrumbs(const uint32_t *backtrace, size_t num_backtrace_entries, const char * current_task_name, bool dump_all_tasks) { ThreadDumpInfo_t faultState = {0}; faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("breadcrumbs'ing\n")); faultState.stackDepth = num_backtrace_entries; memcpy(faultState.stackTrace, backtrace, MIN(num_backtrace_entries * sizeof(uint32_t), sizeof(faultState.stackTrace))); if (current_task_name != NULL) { memcpy(faultState.name, current_task_name, sizeof(faultState.name)); } /* This is a macro so we can't alias it directly in linker script */ nlBREADCRUMBS_crash_dump(&faultState, sizeof(faultState)); #if defined(BUILD_FEATURE_FAULT_DUMP_TASK_STACKS) && (tskKERNEL_VERSION_MAJOR < 8) if (dump_all_tasks) { for (int i = 0; i < threadNum && i < THREAD_DUMP_MAX_NUM_THREADS; i++) { nlBREADCRUMBS_crash_dump(&threadState[i], sizeof(ThreadDumpInfo_t)); } } #endif } #endif /* BUILD_FEATURE_BREADCRUMBS */ #ifdef BUILD_FEATURE_RESET_INFO uint32_t *dump_context_to_reset_info(uint32_t *faultingStackAddress , uint32_t *machineStackAddress, nl_reset_reason_t reset_reason, uint32_t prefault_sp, const char *current_task_name, bool task_fault) LINKER_REPLACEABLE_FUNCTION(dump_context_to_reset_info_default); void dump_stack_overflow_info_to_reset_info(const char *current_task_name) LINKER_REPLACEABLE_FUNCTION(dump_stack_overflow_info_to_reset_info_default); static size_t append_string_to_fault_info_description(size_t index, const char *src) { while (index < sizeof(g_reset_info.fault_info.description) - 1) { g_reset_info.fault_info.description[index++] = *src++; if (*src == '\0') { break; } } return index; } void dump_stack_overflow_info_to_reset_info_default(const char *current_task_name); void dump_stack_overflow_info_to_reset_info_default(const char *current_task_name) { size_t i = append_string_to_fault_info_description(0, "stack_overflow"); if (current_task_name) { // append the task name if there is one. don't // use snprintf because it bloats bootloaders too much. i = append_string_to_fault_info_description(i, ": "); i = append_string_to_fault_info_description(i, current_task_name); } // guarantee null termination g_reset_info.fault_info.description[i] = '\0'; } uint32_t *dump_context_to_reset_info_default(uint32_t *faultingStackAddress , uint32_t *machineStackAddress, nl_reset_reason_t reset_reason, uint32_t prefault_sp, const char *current_task_name, bool task_fault); uint32_t *dump_context_to_reset_info_default(uint32_t *faultingStackAddress , uint32_t *machineStackAddress, nl_reset_reason_t reset_reason, uint32_t prefault_sp, const char *current_task_name, bool task_fault) { ExceptionStackFrame_t *faultFrame = (ExceptionStackFrame_t*) faultingStackAddress; bool save_fault_to_reset_info; uint32_t *backtrace_buf; #ifndef BUILD_FEATURE_RESET_INFO_IN_TEMP_RAM // g_reset_info is our backing store since it is dedicated // retained RAM. only save this fault info if the any previous // fault has been cleared. if ((g_reset_info.fault_info.reason == NL_RESET_REASON_UNKNOWN) || (g_reset_info.fault_info.reason == NL_RESET_REASON_ASSERT)) { #endif // BUILD_FEATURE_RESET_INFO_IN_TEMP_RAM save_fault_to_reset_info = true; // we directly use the g_reset_info.fault_info.task_info[0] buffer // when we generate the backtrace so we don't need to save it // again if (task_fault) { backtrace_buf = g_reset_info.fault_info.task_info[0].backtrace; memset(&g_reset_info.fault_info.task_info[0], 0, sizeof(g_reset_info.fault_info.task_info[0])); } else { backtrace_buf = g_reset_info.fault_info.machine_backtrace; } memset(&g_reset_info.fault_info.machine_backtrace, 0, sizeof(g_reset_info.fault_info.machine_backtrace)); // If this is an assert, this API will return NL_RESET_REASON_ASSERT. If it is a hard fault, it will read unknown if (nl_reset_info_get_reset_reason() == NL_RESET_REASON_UNKNOWN) { memset(g_reset_info.fault_info.description, 0, sizeof(g_reset_info.fault_info.description)); } #ifndef BUILD_FEATURE_RESET_INFO_IN_TEMP_RAM } else { save_fault_to_reset_info = false; // fault_info isn't clean, so generate backtrace to // static buffer and don't save fault_info. backtrace_buf = s_backtrace; } #endif // BUILD_FEATURE_RESET_INFO_IN_TEMP_RAM if (save_fault_to_reset_info) { // save r0-r3 memcpy((void*)&g_reset_info.fault_info.registers, (void*)faultingStackAddress, NUM_LOW_REGISTERS_ON_PROCESS_STACK * sizeof(uint32_t)); // save r4-r11 memcpy((void*)&g_reset_info.fault_info.registers[4], machineStackAddress, NUM_REGISTERS_ON_MAIN_STACK * sizeof(uint32_t)); // save r12 g_reset_info.fault_info.registers[12] = faultFrame->r12; // save psp (r13) g_reset_info.fault_info.registers[13] = prefault_sp; // save lr (r14), pc (r15), psr g_reset_info.fault_info.registers[14] = faultFrame->lr; g_reset_info.fault_info.registers[15] = faultFrame->pc; g_reset_info.fault_info.registers[16] = faultFrame->psr; if (reset_reason == NL_RESET_REASON_WATCHDOG) { dump_watchdog_flags(); } else if (reset_reason == NL_RESET_REASON_STACK_OVERFLOW) { dump_stack_overflow_info_to_reset_info(current_task_name); } } return backtrace_buf; } #endif /* BUILD_FEATURE_RESET_INFO */ void dump_context_default(uint32_t *faultingStackAddress , uint32_t *machineStackAddress, crashType type, uint32_t prefault_sp); void dump_context_default(uint32_t *faultingStackAddress , uint32_t *machineStackAddress, crashType type, uint32_t prefault_sp) { unsigned i; if (type == FAULT) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("Oops!\n")); } else if (type == WDT) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("!!wdog!!\n")); } #if defined(BUILD_FEATURE_RAM_CONSOLE) // Remaining fault dump does not go into RAM console because it goes to // service via an event. Allow above print to go to RAM console, so that // RAM console indicates that a fault has occured. nl_ram_console_disable(); #endif // register dump: r0-r3 for (i = 0; i < NUM_LOW_REGISTERS_ON_PROCESS_STACK; i++) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("r%d\t0x%08lx\n"), i, faultingStackAddress[i]); } // register dump: r4-r11 for (i = 0; i < NUM_REGISTERS_ON_MAIN_STACK; i++) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("r%d\t0x%08lx\n"), i+4, machineStackAddress[i]); } // register dump: r12, lr, pc, psr #ifdef DEBUG const char* names[] = { "r12", " lr", " pc", "psr" }; #endif for (i = 0; i < NUM_HIGH_REGISTERS_ON_PROCESS_STACK; i++) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("%s\t0x%08lx\n"), names[i], faultingStackAddress[i+NUM_LOW_REGISTERS_ON_PROCESS_STACK]); } // register dump: psp. faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("psp\t0x%08lx\n"), prefault_sp); nlplatform_soc_dump_context(); nlproduct_dump_context(); // stack dump faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("- stack -\n")); for ( i = 0; i < NUM_STACK_DUMP_ENTRIES; i++ ) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("%08lx\n"), *(((uint32_t*)(prefault_sp)) + i)); } } void dump_backtrace_default(ExceptionStackFrame_t *faultFrame, uint32_t *backtrace_buf, unsigned *backtrace_count, uint32_t prefault_sp, uint32_t stackTop, nl_reset_reason_t reset_reason); void dump_backtrace_default(ExceptionStackFrame_t *faultFrame, uint32_t *backtrace_buf, unsigned *backtrace_count, uint32_t prefault_sp, uint32_t stackTop, nl_reset_reason_t reset_reason) { int size; size_t i; nlwatchdog_refresh(); size = nlbacktrace_with_lr(faultFrame->pc, faultFrame->lr, prefault_sp, stackTop, backtrace_buf, NL_FAULT_DIAGS_NUM_BT_ENTRIES); // If the nlbacktrace_with_lr() returned no backtrace // then use nlbacktrace_no_context() to get a longer backtrace. if (size == 0) { backtrace_buf[0] = faultFrame->pc; backtrace_buf[1] = faultFrame->lr; nlwatchdog_refresh(); size = nlbacktrace_no_context(prefault_sp, stackTop, backtrace_buf+2, NL_FAULT_DIAGS_NUM_BT_ENTRIES-2, 3, 16) + 2; } *backtrace_count = size; nlwatchdog_refresh(); for (i = 0; i < size; i++) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING(" 0x%08lx\n"), backtrace_buf[i]); } } void get_and_dump_current_task_info_default(const char **name, nl_reset_reason_t *reset_reason, uint32_t *stackTop); void get_and_dump_current_task_info_default(const char **name, nl_reset_reason_t *reset_reason, uint32_t *stackTop) { const char *current_task_name; xTaskHandle handle = xTaskGetCurrentTaskHandle(); current_task_name = (const char*)pcTaskGetTaskName(handle); faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("Task: %sR\n"), current_task_name); *name = current_task_name; if (handle) { *stackTop = get_task_stack_top(handle); } } void dump_watchdog_flags_default(void); void dump_watchdog_flags_default(void) { #if defined(BUILD_FEATURE_RESET_INFO) // save watchdog flags to the description nlwatchdog_log_flags((char*)&g_reset_info.fault_info.description, sizeof(g_reset_info.fault_info.description)); #endif // print the watchdog flags to the console nlwatchdog_print_flags(); } void crash_dump_default( uint32_t *faultingStackAddress , uint32_t *machineStackAddress, crashType type); void crash_dump_default( uint32_t *faultingStackAddress , uint32_t *machineStackAddress, crashType type) { ExceptionStackFrame_t *faultFrame = (ExceptionStackFrame_t*) faultingStackAddress; uint32_t *backtrace_buf; unsigned backtrace_count = 0; nl_reset_reason_t reset_reason; const char *current_task_name = NULL; uint32_t stackTop = 0; #if !defined(BUILD_CONFIG_RELEASE) || defined(BUILD_FEATURE_RESET_INFO) || defined(BUILD_FEATURE_FAULT_DUMP_TASK_STACKS) // check if it's a fault on the main stack or a process (task) stack fault bool task_fault = (faultingStackAddress == machineStackAddress + 10) ? false : true; #endif uint32_t prefault_sp = (uint32_t)&faultFrame->stack[0]; if (faultFrame->psr & PSR_EXTRA_STACK_ALIGN_BIT) { prefault_sp += 4; } if (type < ARRAY_SIZE(kCrashTypeToResetReason)) { reset_reason = kCrashTypeToResetReason[type]; } else { reset_reason = NL_RESET_REASON_HARD_FAULT; // if all else fails } #if BUILD_FEATURE_PRE_WATCHDOG_ISR_EXTENSION if ((type == WDT) && (nlwatchdog_ignore_pre_watchdog_isr() == true)) { goto done; } #else // pet the watchdog so we have enough time to hopefully do the dump nlwatchdog_refresh(); #endif // quiesce system. this also could be used to disable watchdog if desired. nlplatform_quiesce_on_fault(); dump_context(faultingStackAddress, machineStackAddress, type, prefault_sp); #if !defined(BUILD_CONFIG_RELEASE) if (task_fault) { get_and_dump_current_task_info(&current_task_name, &reset_reason, &stackTop); } else { /* To get the end of the Main stack, we expect a linker script to * provide the symbol "_eusrstack". The linker script might have * other symbols with the same value, but this file will expect * all products to export a _eusrstack symbol. */ extern const uint32_t _eusrstack; /* linker symbol for end of MSP stack */ faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("- Fault on main stack (ISR?)) -\n")); stackTop = (uint32_t)&_eusrstack; } #endif #ifdef BUILD_FEATURE_RESET_INFO // Copy R0-R12, sp, LR, PC, xPSR backtrace_buf = dump_context_to_reset_info(faultingStackAddress, machineStackAddress, reset_reason, prefault_sp, current_task_name, task_fault); #else // BUILD_FEATURE_RESET_INFO backtrace_buf = s_backtrace; #endif // BUILD_FEATURE_RESET_INFO // dump backtrace of current context dump_backtrace(faultFrame, backtrace_buf, &backtrace_count, prefault_sp, stackTop, reset_reason); //all thread backtrace #if defined(BUILD_FEATURE_FAULT_DUMP_TASK_STACKS) dump_all_tasks(task_fault); #endif #ifdef BUILD_FEATURE_BREADCRUMBS //writing breadcrumb //fault breadcrumbs goes here: crash_dump_breadcrumbs(backtrace_buf, backtrace_count, current_task_name, type == WDT); #endif #if defined(BUILD_CONFIG_RELEASE) // always reset in release builds faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("resetting\n")); nlplatform_reset(reset_reason); #else /* BUILD_CONFIG_RELEASE */ #if defined(BUILD_FEATURE_NO_BKPT_ON_FAULT) if (0) { } #else // cortex-m0 does not (may not?) have cpu accessible CoreDebug registers // so use a SOC specific API to determine if debugger is connected if (nlplatform_debugger_is_attached()) { // if a debugger is connected, this should trigger a breakpoint. faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("breaking\n")); __asm__ __volatile__("bkpt #0"); // just single step in the debugger to restore the frame that // caused the fault to see what happened. } #endif else { #if defined(BUILD_FEATURE_RESET_ON_FAULT) faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("resetting\n")); nlplatform_reset(reset_reason); #else #if defined(BUILD_FEATURE_RESET_INFO) // when no debugger is connected, spin. if watchdog isn't // disabled, it will cause a reset. otherwise the spinning // will allow connecting a debugger later. nl_reset_info_prepare_reset(reset_reason, NULL); #endif while (1); #endif // defined(BUILD_FEATURE_RESET_ON_FAULT) } #endif // defined(BUILD_CONFIG_RELEASE) #if BUILD_FEATURE_PRE_WATCHDOG_ISR_EXTENSION done: return; #endif } /* no freertos linking, alias crash_dump to this function * to dead strip the rtos using version and it's symbols. * not static to avoid unused function warnings. */ void crash_dump_nortos( uint32_t *faultingStackAddress , uint32_t *machineStackAddress, crashType type); void crash_dump_nortos( uint32_t *faultingStackAddress , uint32_t *machineStackAddress, crashType type) { nl_reset_reason_t reset_reason = (type == WDT) ? NL_RESET_REASON_WATCHDOG : NL_RESET_REASON_HARD_FAULT; ExceptionStackFrame_t *faultFrame = (ExceptionStackFrame_t*) faultingStackAddress; uint32_t prefault_sp = (uint32_t)&faultFrame->stack[0]; if (faultFrame->psr & PSR_EXTRA_STACK_ALIGN_BIT) { prefault_sp += 4; } #if BUILD_FEATURE_PRE_WATCHDOG_ISR_EXTENSION if ((type == WDT) && (nlwatchdog_ignore_pre_watchdog_isr() == true)) { goto done; } #else // pet the watchdog so we have enough time to hopefully do the dump nlwatchdog_refresh(); #endif dump_context(faultingStackAddress, machineStackAddress, type, prefault_sp); #if defined(BUILD_FEATURE_NO_BKPT_ON_FAULT) if (0) { } #else // cortex-m0 does not (may not?) have cpu accessible CoreDebug registers // so use a SOC specific API to determine if debugger is connected if (nlplatform_debugger_is_attached()) { // if a debugger is connected, this should trigger a breakpoint. faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("breaking\n")); __asm__ __volatile__("bkpt #0"); // just single step in the debugger to restore the frame that // caused the fault to see what happened. } #endif else { // when no debugger is connected, we reset to not spin consuming // our battery needlessly faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("resetting\n")); nlplatform_reset(reset_reason); } #if BUILD_FEATURE_PRE_WATCHDOG_ISR_EXTENSION done: return; #endif } /* Use this as the FreeRTOS vApplicationStackOverflowHook to dump backtrace * about the task that overflowed it's stack. */ void nlfault_freertos_stack_overflow_handler_c(xTaskHandle pxTask, signed char *pcTaskName); void nlfault_freertos_stack_overflow_handler_c(xTaskHandle pxTask, signed char *pcTaskName) { /* Run time stack overflow checking is performed if configCHECK_FOR_STACK_OVERFLOW is defined to 1 or 2. This hook function is called if a stack overflow is detected. */ switched_out_stack_frame_t *stack_frame_p; uint32_t *backtrace_buf; uint32_t top_of_stack; size_t num_backtraces; uint32_t prefault_sp; uint32_t stackTop = get_task_stack_top(pxTask); taskDISABLE_INTERRUPTS(); // pet the watchdog so we have enough time to hopefully do the dump nlwatchdog_refresh(); // quiesce system. this also could be used to disable watchdog if desired. nlplatform_quiesce_on_fault(); faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("\nSTACK_OVERFLOW_DETECTED\n")); faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("%s\n"), (const char *)pcTaskName); /* FreeRTOS doesn't give an API for getting the top of the stack * but we know it's the first entry in the TCB pointed to by pxTask. */ top_of_stack = (((uint32_t*)pxTask)[0]); stack_frame_p = (switched_out_stack_frame_t*)top_of_stack; prefault_sp = (uint32_t)&stack_frame_p->pendSVFrame.stack[0]; if (stack_frame_p->pendSVFrame.psr & PSR_EXTRA_STACK_ALIGN_BIT) { prefault_sp += 4; } #ifdef BUILD_FEATURE_RESET_INFO bool save_fault_to_reset_info; #ifdef BUILD_FEATURE_RESET_INFO_IN_TEMP_RAM // g_reset_info is just a cache so we always save to it and // let the subsequent boot decide whether to move the RAM // copy to the external FLASH backing store save_fault_to_reset_info = true; // we directly use the g_reset_info.fault_info.task_info[0] buffer // when we generate the backtrace so we don't need to save it // again backtrace_buf = g_reset_info.fault_info.task_info[0].backtrace; memset(&g_reset_info.fault_info.task_info[0], 0, sizeof(g_reset_info.fault_info.task_info[0])); #else // BUILD_FEATURE_RESET_INFO_IN_TEMP_RAM // g_reset_info is our backing store since it is dedicated // retained RAM. only save this fault info if the any previous // fault has been cleared. if ((g_reset_info.fault_info.reason == NL_RESET_REASON_UNKNOWN) || (g_reset_info.fault_info.reason == NL_RESET_REASON_ASSERT)) { save_fault_to_reset_info = true; // directly use the g_reset_info.fault_info.task_info[0].backtrace buffer // so no need to copy it backtrace_buf = g_reset_info.fault_info.task_info[0].backtrace; memset(&g_reset_info.fault_info.task_info[0], 0, sizeof(g_reset_info.fault_info.task_info[0])); } else { save_fault_to_reset_info = false; // fault_info isn't clean, so generate backtrace to // static buffer and don't save fault_info. backtrace_buf = s_backtrace; } #endif // BUILD_FEATURE_RESET_INFO_IN_TEMP_RAM if (save_fault_to_reset_info) { // save r0-r3 g_reset_info.fault_info.registers[0] = stack_frame_p->pendSVFrame.r0; g_reset_info.fault_info.registers[1] = stack_frame_p->pendSVFrame.r1; g_reset_info.fault_info.registers[2] = stack_frame_p->pendSVFrame.r2; g_reset_info.fault_info.registers[3] = stack_frame_p->pendSVFrame.r3; // save r4-r11 g_reset_info.fault_info.registers[4] = stack_frame_p->r4; g_reset_info.fault_info.registers[5] = stack_frame_p->r5; g_reset_info.fault_info.registers[6] = stack_frame_p->r6; g_reset_info.fault_info.registers[7] = stack_frame_p->r7; g_reset_info.fault_info.registers[8] = stack_frame_p->r8; g_reset_info.fault_info.registers[9] = stack_frame_p->r9; g_reset_info.fault_info.registers[10] = stack_frame_p->r10; g_reset_info.fault_info.registers[11] = stack_frame_p->r11; // save r12 g_reset_info.fault_info.registers[12] = stack_frame_p->pendSVFrame.r12; // save psp (r13) g_reset_info.fault_info.registers[13] = prefault_sp; // save lr (r14), pc (r15), psr g_reset_info.fault_info.registers[14] = stack_frame_p->pendSVFrame.lr; g_reset_info.fault_info.registers[15] = stack_frame_p->pendSVFrame.pc; g_reset_info.fault_info.registers[16] = stack_frame_p->pendSVFrame.psr; snprintf(g_reset_info.fault_info.description, sizeof(g_reset_info.fault_info.description), UNIQUE_STRING_LITERAL("%s stack overflow"), pcTaskName); } #else // BUILD_FEATURE_RESET_INFO backtrace_buf = s_backtrace; #endif // BUILD_FEATURE_RESET_INFO num_backtraces = nlbacktrace_with_lr(stack_frame_p->pendSVFrame.pc, stack_frame_p->pendSVFrame.lr, prefault_sp, stackTop, backtrace_buf, NL_FAULT_DIAGS_NUM_BT_ENTRIES); if (num_backtraces < MIN_BACKTRACE_LEVELS_FOR_STACK_OVERFLOW) { // nlbacktrace_with_lr didn't find anything useful. since we // have a stack overflow, try alternative method num_backtraces = nlbacktrace_no_context(prefault_sp, stackTop, backtrace_buf + 2, NL_FAULT_DIAGS_NUM_BT_ENTRIES - 2, MIN_BACKTRACE_LEVELS_FOR_STACK_OVERFLOW, 16); /* max LRs to test from stack */ backtrace_buf[0] = stack_frame_p->pendSVFrame.pc; backtrace_buf[1] = stack_frame_p->pendSVFrame.lr; } #if !defined(BUILD_FEATURE_RESET_INFO) for (unsigned i = 0; i < num_backtraces; i++) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING(" 0x%08lx\n"), backtrace_buf[i]); } #endif faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("resetting\n")); nlplatform_reset(NL_RESET_REASON_STACK_OVERFLOW); }
nestlabs/nlplatform
include/nlfs.h
<gh_stars>1-10 /* * * Copyright (c) 2015-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file defines a filesystem interface. */ #ifndef __NLFS_H_INCLUDED__ #define __NLFS_H_INCLUDED__ #include <stdint.h> #include <stddef.h> #if NL_FEATURE_SIMULATEABLE_HW #include <stdio.h> #endif #ifdef __cplusplus extern "C" { #endif /* A nlfs_fileid_t is a uint8_t divided into two parts. * The highest 2 bits are the PARTITION_TYPE, either INTERNAL, EXTERNAL, * or EXTERNAL_SUBPARTITION (abbreviated INT, EXT, and EXT_SUB respectively). * The remaining bits are the PARTITION_ID. */ typedef uint8_t nlfs_fileid_t; #define PARTITION_TYPE_MASK (0x3<<6) #define PARTITION_ID_MASK (0x3f) #define GET_PARTITION_TYPE(x) (((x)>>6) & 0x3) #define GET_PARTITION_ID(x) ((x) & PARTITION_ID_MASK) #define DEFINE_FILEID(type, id) (((type) << 6) | (id)) #define PARTITION_TYPE_INT (0x0) #define PARTITION_TYPE_EXT (0x1) #define PARTITION_TYPE_EXT_SUB (0x2) /* Set aside max value for invalid */ #define PARITION_ID_INVALID PARTITION_ID_MASK #include <nlplatform/nlflash.h> typedef enum { READ_ONLY, WRITE_ONLY, } nlfs_file_mode_t; typedef enum { BEGINNING, CURRENT, } nlfs_origin_pos_t; typedef enum { IMAGE0, IMAGE1, INSTALLED, ALTERNATE, } nlfs_image_location_t; typedef struct { #if NL_FEATURE_SIMULATEABLE_HW FILE *fileHandle; #endif uint32_t offset; uint32_t currentPos; size_t len; void *context; uint8_t partId; uint8_t partType; uint8_t chipId; nlfs_file_mode_t mode; bool isOpen; bool isFat; } nlfs_file_t; #ifdef BUILD_FEATURE_FAT_FILES #include <nlfat.h> #include <nlblocks.h> #define NL_NUM_FAT_BUFFS 2 typedef struct { nl_fat_context context; uint8_t readBuf[BLOCK_SIZE]; volume_buffer_spec bufs[NL_NUM_FAT_BUFFS]; } nlfs_fat_file_context_t; #endif int nlfs_open_cb(nlfs_fileid_t fid, nlfs_file_mode_t mode, nlfs_image_location_t loc, nlfs_file_t *file, bool isFat, void *context, nlloop_callback_fp callback); size_t nlfs_read_cb(nlfs_file_t *file, void *buf, size_t bytes, nlloop_callback_fp callback); size_t nlfs_write_cb(nlfs_file_t *file, const void *buf, size_t bytes, nlloop_callback_fp callback); int nlfs_close(nlfs_file_t *file); int nlfs_getlen(const nlfs_file_t *file, size_t *len); int nlfs_getpos(const nlfs_file_t *file, uint32_t *offset); int nlfs_seek(nlfs_file_t *file, uint32_t offset, nlfs_origin_pos_t origin); bool nlfs_is_open(const nlfs_file_t *file); #define nlfs_read(file, buf, bytes) nlfs_read_cb(file, buf, bytes, NULL) #define nlfs_write(file, buf, bytes) nlfs_write_cb(file, buf, bytes, NULL) #define nlfs_open(fid, mode, loc, file) nlfs_open_cb(fid, mode, loc, file, false, NULL, NULL) /* Compatibilty macros until coding conventions are settled */ #define nl_fs_file_mode_t nlfs_file_mode_t #define nl_fs_origin_pos_t nlfs_origin_pos_t #define nl_fs_image_location_t nlfs_image_location_t #define nl_fs_fileid_t nlfs_fileid_t #define nl_fs_file_t nlfs_file_t #define nl_fs_fat_file_context_t nlfs_fat_file_context_t #define nl_fs_open_cb nlfs_open_cb #define nl_fs_read_cb nlfs_read_cb #define nl_fs_write_cb nlfs_write_cb #define nl_fs_close nlfs_close #define nl_fs_getlen nlfs_getlen #define nl_fs_getpos nlfs_getpos #define nl_fs_seek nlfs_seek #define nl_fs_is_open nlfs_is_open #define nl_fs_read nlfs_read #define nl_fs_write nlfs_write #define nl_fs_open nlfs_open #ifdef __cplusplus } #endif #endif /* __NLFS_H_INCLUDED__ */
nestlabs/nlplatform
src/nlspi_ipc.c
/* * * Copyright (c) 2017-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file has source for the SPI IPC subsystem. * */ #include <stdio.h> #include <nlplatform.h> #include <nlplatform/nlgpio.h> #include <nlplatform/nlspi_ipc.h> #include <nlcrc.h> #ifndef NL_NO_RTOS #include <FreeRTOS.h> #include <semphr.h> #include <task.h> #include <nlertime.h> #ifdef BUILD_FEATURE_BREADCRUMBS #include <nlbreadcrumbs.h> #include <nlbreadcrumbs-local.h> #include <nlbreadcrumbs-all.h> #endif static TaskHandle_t sTaskToNotify; static StaticSemaphore_t spi_ipc_mutex; static bool sInitialized; #else // NL_NO_RTOS static volatile uint8_t srdy_edge_triggered; #endif // NL_NO_RTOS static int irq_registered; #ifdef PRODUCT_IPC_OPCODE_ENABLE_ACK_MODE static bool s_use_ack_nak_mode; #endif #if 0 #define DEBUG_TRACE(x) printf x #else #define DEBUG_TRACE(x) (void)0 #endif // Store received data plus CRC static uint8_t rx_buffer[MAX_IPC_DATA_LEN_FROM_SLAVE + 1]; /* Used to detect rising edge interrupt when waiting for slave to be ready * for us to start clocking SPI bus. */ static void srdy_deasserted_isr(const nlgpio_id_t gpio, void *data) { #ifndef NL_NO_RTOS signed portBASE_TYPE yield = pdFALSE; #endif /* disable interrupt until next time */ irq_registered = 0; nlgpio_irq_release(g_spi_ipc_device.srdy_gpio); #ifndef NL_NO_RTOS vTaskNotifyGiveFromISR(sTaskToNotify, &yield); portEND_SWITCHING_ISR(yield); #else srdy_edge_triggered = 1; #endif } #ifndef NL_NO_RTOS /* Used to detect when slave has something to send to us. */ static void srdy_asserted_isr(const nlgpio_id_t gpio, void *data) { int should_yield; /* disable interrupt until next time */ irq_registered = 0; nlgpio_irq_release(g_spi_ipc_device.srdy_gpio); /* notify of pending ipc, which should ready a thread to call spi_ipc_work() * to do the transfer and invoke receive handlers */ should_yield = g_spi_ipc_device.rx_pending_handler(); portEND_SWITCHING_ISR(should_yield ? pdTRUE : pdFALSE); } static int fetch_rx_len_func(struct nlspi_transfer_s *xfer, int res) { uint8_t len; nlspi_transfer_t *data_xfer = xfer + 1; DEBUG_TRACE(("%s: xfer = %p, res = %d\n", __func__, xfer, res)); /* if we already have an error, just return */ if (res < 0) return res; /* if we received a 0 length byte, then there is no actual transaction * to conduct. abort with a result which will not trigger a panic. */ len = xfer->rx[0]; if (!len) { printf("%s: len byte is 0, nothing to do\n", __func__); return IPC_RESULT_NO_MSG; } /* if the length of the packet is too large to fit into the * rx buffer, trigger an error. Reserve one byte for CRC. * The received length includes the opcode and the length byte itself * as well as the CRC trailer. Subtract 2 bytes for length/opcode. * This yields the data payload length plus CRC trailer. */ len -= 2; if (len > data_xfer->num) { printf("%s: data_xfer->num %d too small to fit transfer of %d\n", __func__, data_xfer->num, len); return IPC_RESULT_RX_BUF_TOO_SMALL; } /* Change data_xfer->num to be equal to the number of bytes being received */ DEBUG_TRACE(("%s: receiving %d data bytes\n", __func__, len)); data_xfer->num = len; return 0; } #endif /* !defined(NL_NO_RTOS) */ void nlspi_ipc_init(void) { #ifndef NL_NO_RTOS if (sInitialized == false) { xSemaphoreCreateMutexStatic(&spi_ipc_mutex); sInitialized = true; } DEBUG_TRACE(("%s: SPI IPC clock at %d\n", __func__, g_spi_ipc_device.spi_slave->max_freq_hz)); // register interrupt for the case where slave has something to send to us. irq_registered = 1; nlgpio_irq_request(g_spi_ipc_device.srdy_gpio, IRQF_TRIGGER_LOW, srdy_asserted_isr, NULL); #endif } static int check_crc_and_dispatch(uint8_t *length_and_opcode, uint8_t *rx_buf, uint8_t rx_data_len) { int result = 0; if (length_and_opcode[0]) { uint8_t crc_calc; #ifdef PRODUCT_IPC_OPCODE_ENABLE_ACK_MODE if (s_use_ack_nak_mode) { // passed in rx_data_len is one greater than it should // be because slave is sending a repeated CRC byte. // it was easier for calling code to use the off-by-one // value so we adjust here. rx_data_len--; } #endif /* Compute CRC over length, opcode, data (excludes received CRC). */ crc_calc = crc8_ccitt(length_and_opcode, 2); crc_calc = crc8_ccitt_append(crc_calc, rx_buf, rx_data_len); #ifdef PRODUCT_IPC_OPCODE_ENABLE_ACK_MODE if (s_use_ack_nak_mode) { /* Compare CRCs. Received CRC is the last two bytes in the rx data buffer. * In release builds, only one has to be valid. In non-release builds, we * expect both to match the computed CRC and if not, we call the corrupt_handler. */ #if BUILD_CONFIG_RELEASE if ((crc_calc == rx_buf[rx_data_len]) || (crc_calc == rx_buf[rx_data_len + 1])) #else if ((crc_calc == rx_buf[rx_data_len]) && (crc_calc == rx_buf[rx_data_len + 1])) #endif { /* Send an ACK to slave */ result = 1; g_spi_ipc_device.rx_data_handler(length_and_opcode[1], rx_data_len, rx_buf); } else { /* Send a NAK to slave */ result = -1; g_spi_ipc_device.rx_corrupt_handler(length_and_opcode[1], rx_data_len, rx_buf); } } else #endif // PRODUCT_IPC_OPCODE_ENABLE_ACK_MODE { /* Compare CRCs. Received CRC is the last byte in the rx data buffer. */ if (crc_calc != rx_buf[rx_data_len]) { g_spi_ipc_device.rx_corrupt_handler(length_and_opcode[1], rx_data_len, rx_buf); } else { g_spi_ipc_device.rx_data_handler(length_and_opcode[1], rx_data_len, rx_buf); } } } return result; } #ifndef NL_NO_RTOS // Don't need this function in NO_RTOS builds void nlspi_ipc_work(void) { /* check if there's something to receive, if so, do the * transfer and dispatch it */ nlspi_transfer_t xfer[2]; uint8_t len_opcode_rx[2]; int result; if (sInitialized == false) { printf("spi_ipc_init() hasn't been called\n"); return; } DEBUG_TRACE(("%s: Grabbing spi_ipc_mutex\n", __func__)); xSemaphoreTake(&spi_ipc_mutex, portMAX_DELAY); if (nlgpio_get_value(g_spi_ipc_device.srdy_gpio)) { DEBUG_TRACE(("%s: SRDY not asserted\n", __func__)); /* SRDY not asserted, nothing to do */ // irq might have already been registered in the case where // a nlspi_ipc_send() was done after the last wake interrupt occurred, // and the nlspi_ipc_send() already rescheduled another wake interrupt. // to be safe, we release and request the interrupt again because the // gpio system would otherwise register a separate interrupt on // a different gpio port pin. if (irq_registered) { nlgpio_irq_release(g_spi_ipc_device.srdy_gpio); } // register interrupt for the case where slave has something to send to us. irq_registered = 2; nlgpio_irq_request(g_spi_ipc_device.srdy_gpio, IRQF_TRIGGER_LOW, srdy_asserted_isr, NULL); xSemaphoreGive(&spi_ipc_mutex); return; } DEBUG_TRACE(("%s: Requesting spi bus\n", __func__)); nlspi_request(g_spi_ipc_device.spi_slave); DEBUG_TRACE(("%s: SRDY is asserted (val = %d)\n", __func__, nlgpio_get_value(g_spi_ipc_device.srdy_gpio))); /* Before asserting MRDY, register rising edge interrupt so we avoid any * races with the slave signaling via SRDY for a requested transfer. If the * slave was waiting for us to assert MRDY, it could quickly give the * rising edge and polling for an edge transition would fail. */ if (irq_registered) { // cancel previously scheduled interrupt (most likely // the handler for assert) DEBUG_TRACE(("%s: Releasing previous irq request\n", __func__)); nlgpio_irq_release(g_spi_ipc_device.srdy_gpio); } irq_registered = 3; nlgpio_irq_request(g_spi_ipc_device.srdy_gpio, IRQF_TRIGGER_RISING, srdy_deasserted_isr, NULL); DEBUG_TRACE(("%s: asserting MRDY\n", __func__)); /* assert MRDY now that we're ready */ nlgpio_request(g_spi_ipc_device.mrdy_gpio, GPIOF_OUT_LOW); /* The slave wants to send us something so do the transfer. * Setup the transaction so that we check in the callback * after the first byte (length) is received what the length * is and update it dynamically. */ xfer[0].tx = NULL; xfer[0].rx = len_opcode_rx; xfer[0].num = sizeof(len_opcode_rx); xfer[0].callback = fetch_rx_len_func; xfer[1].tx = NULL; xfer[1].rx = rx_buffer; xfer[1].num = sizeof(rx_buffer); /* to be changed by fetch_rx_len_func */ xfer[1].callback = NULL; DEBUG_TRACE(("%s: waiting for SRDY rising edge\n", __func__)); /* now wait for rising edge, which is the slave signal that * they've seen our chip select and are ready to do a transfer */ { nl_time_native_t srdy_timeout; srdy_timeout = nl_time_ms_to_time_native(g_spi_ipc_device.srdy_timeout_ms); sTaskToNotify = xTaskGetCurrentTaskHandle(); if (ulTaskNotifyTake(pdTRUE, srdy_timeout) != 1) { DEBUG_TRACE(("%s: SRDY timeout (%u ticks)\n", __func__, srdy_timeout)); nlgpio_release(g_spi_ipc_device.mrdy_gpio); nlgpio_irq_release(g_spi_ipc_device.srdy_gpio); irq_registered = 0; nlspi_release(g_spi_ipc_device.spi_slave); g_spi_ipc_device.srdy_timeout_handler(); xSemaphoreGive(&spi_ipc_mutex); return; } } DEBUG_TRACE(("%s: SRDY rising edge seen, calling spi->transfer() to read\n", __func__)); result = nlspi_transfer(g_spi_ipc_device.spi_slave, xfer, 2); DEBUG_TRACE(("%s: after calling spi->transfer() to read\n", __func__)); if (result) { printf("Error %d on spi xfer read\n", result); } // register interrupt for the case where slave has something to send to us. if (irq_registered) { printf("%s: irq_registered (%d) when we didn't expect it to be\n", __func__, irq_registered); } irq_registered = 4; nlgpio_irq_request(g_spi_ipc_device.srdy_gpio, IRQF_TRIGGER_LOW, srdy_asserted_isr, NULL); nlgpio_release(g_spi_ipc_device.mrdy_gpio); nlspi_release(g_spi_ipc_device.spi_slave); result = check_crc_and_dispatch(len_opcode_rx, rx_buffer, xfer[1].num - 1); xSemaphoreGive(&spi_ipc_mutex); DEBUG_TRACE(("%s: ending, result %d\n", __func__, result)); #if !defined(NL_NO_RTOS) && defined(PRODUCT_IPC_OPCODE_ENABLE_ACK_MODE) if (result == -1) { /* Print some additional debug information to help * diagnose circumstances when corruption occurred */ printf("%s: sending NAK\n", __func__); nlspi_ipc_send(PRODUCT_IPC_OPCODE_NAK, 0, NULL); } else if (result == 1) { nlspi_ipc_send(PRODUCT_IPC_OPCODE_ACK, 0, NULL); } #endif // !defined(NL_NO_RTOS) && defined(PRODUCT_IPC_OPCODE_ENABLE_ACK_MODE) } #ifdef PRODUCT_IPC_OPCODE_ENABLE_ACK_MODE void nlspi_ipc_enable_ack_mode(void) { // send slave msg to enable ack mode nlspi_ipc_send(PRODUCT_IPC_OPCODE_ENABLE_ACK_MODE, 0, NULL); s_use_ack_nak_mode = true; } #endif // PRODUCT_IPC_OPCODE_ENABLE_ACK_MODE #endif /* !defined(NL_NO_RTOS) */ int nlspi_ipc_send(uint8_t opcode, uint8_t data_len, const uint8_t *data) { int result; nlspi_transfer_t xfer[3]; uint8_t len_opcode_tx[2]; uint8_t len_opcode_rx[2]; uint8_t crc_calc; uint8_t rx_len = 0; uint8_t rx_data_len = 0; #ifndef NL_NO_RTOS if (sInitialized == false) { printf("spi_ipc_init() hasn't been called\n"); return IPC_RESULT_NOT_INITIALIZED; } #endif if (!g_spi_ipc_device.connected()) { return IPC_RESULT_NO_SLAVE; } DEBUG_TRACE(("%s: start\n", __func__)); #ifndef NL_NO_RTOS DEBUG_TRACE(("%s: Grabbing spi_ipc_mutex\n", __func__)); xSemaphoreTake(&spi_ipc_mutex, portMAX_DELAY); #endif DEBUG_TRACE(("%s: Requesting spi bus\n", __func__)); nlspi_request(g_spi_ipc_device.spi_slave); /* Before asserting MRDY, register rising edge interrupt so we avoid any * races with the slave signaling via SRDY for a requested transfer. If the * slave was waiting for us to assert MRDY, it could quickly give the * rising edge and polling for an edge transition would fail. */ if (irq_registered) { // cancel previously scheduled interrupt (most likely // the handler for assert) DEBUG_TRACE(("%s: Releasing previous irq request %d\n", __func__, irq_registered)); nlgpio_irq_release(g_spi_ipc_device.srdy_gpio); } irq_registered = 5; #ifdef NL_NO_RTOS srdy_edge_triggered = 0; #endif nlgpio_irq_request(g_spi_ipc_device.srdy_gpio, IRQF_TRIGGER_RISING, srdy_deasserted_isr, NULL); /* Assert MRDY after registering rising edge interrupt request */ DEBUG_TRACE(("%s: asserting MRDY\n", __func__)); nlgpio_request(g_spi_ipc_device.mrdy_gpio, GPIOF_OUT_LOW); /* a packet/frame consists of the header of the length * and opcode, then the data, then the CRC */ len_opcode_tx[0] = data_len + sizeof(len_opcode_tx) + sizeof(crc_calc); len_opcode_tx[1] = opcode; len_opcode_rx[0] = 0; xfer[0].tx = len_opcode_tx; xfer[0].rx = len_opcode_rx; xfer[0].num = sizeof(len_opcode_tx); xfer[0].callback = NULL; DEBUG_TRACE(("%s: waiting for SRDY rising edge\n", __func__)); /* now wait for rising edge, which is the slave signal that * they've seen our chip select and are ready to do a transfer */ #ifndef NL_NO_RTOS { nl_time_native_t srdy_timeout; srdy_timeout = nl_time_ms_to_time_native(g_spi_ipc_device.srdy_timeout_ms); sTaskToNotify = xTaskGetCurrentTaskHandle(); if (ulTaskNotifyTake(pdTRUE, srdy_timeout) != 1) { DEBUG_TRACE(("%s: SRDY timeout (%u ticks)\n", __func__, srdy_timeout)); nlgpio_release(g_spi_ipc_device.mrdy_gpio); nlgpio_irq_release(g_spi_ipc_device.srdy_gpio); irq_registered = 0; nlspi_release(g_spi_ipc_device.spi_slave); g_spi_ipc_device.srdy_timeout_handler(); xSemaphoreGive(&spi_ipc_mutex); return IPC_RESULT_SRDY_TIMEOUT; } } #else while (srdy_edge_triggered == 0); #endif DEBUG_TRACE(("%s: SRDY rising edge seen\n", __func__)); crc_calc = crc8_ccitt(len_opcode_tx, sizeof(len_opcode_tx)); if (data_len) { xfer[1].tx = data; xfer[1].rx = rx_buffer; xfer[1].num = data_len; xfer[1].callback = NULL; xfer[2].tx = &crc_calc; xfer[2].rx = rx_buffer + data_len; xfer[2].num = sizeof(crc_calc); xfer[2].callback = NULL; DEBUG_TRACE(("%s: calling spi->transfer of header+data\n", __func__)); crc_calc = crc8_ccitt_append(crc_calc, data, data_len); result = nlspi_transfer(g_spi_ipc_device.spi_slave, xfer, 3); } else { xfer[1].tx = &crc_calc; xfer[1].rx = rx_buffer; xfer[1].num = sizeof(crc_calc); xfer[1].callback = NULL; DEBUG_TRACE(("%s: calling spi->transfer of just header, no data\n", __func__)); result = nlspi_transfer(g_spi_ipc_device.spi_slave, xfer, 2); } DEBUG_TRACE(("%s: spi->transfer returned %d\n", __func__, result)); if (result) { printf("Error %d on spi xfer\n", result); goto done; } /* did the slave have data to send to us? if so, the rx_len * (first received byte of the packet) will be non-zero */ rx_len = len_opcode_rx[0]; if (rx_len) { rx_data_len = rx_len - sizeof(len_opcode_rx) - sizeof(crc_calc); if (rx_data_len <= sizeof(rx_buffer)) { if (rx_data_len > data_len) { /* there is more data to receive then we've clocked so far */ uint8_t bytes_left = rx_data_len - data_len; xfer[0].tx = NULL; // We have already received data_len bytes, plus CRC transfer from master to slave xfer[0].rx = rx_buffer + data_len + sizeof(crc_calc); xfer[0].num = bytes_left; result = nlspi_transfer(g_spi_ipc_device.spi_slave, xfer, 1); if (result) { printf("Error %d on spi xfer\n", result); } } } else { printf("%s: rx_buffer size %d too small to fit packet slave wants to send of %d data bytes\n", __func__, sizeof(rx_buffer), rx_data_len); result = IPC_RESULT_RX_BUF_TOO_SMALL; } } done: #ifndef NL_NO_RTOS // register interrupt for the case where slave has something to send to us. if (irq_registered) { printf("%s: irq_registered (%d) when we didn't expect it to be\n", __func__, irq_registered); } irq_registered = 6; nlgpio_irq_request(g_spi_ipc_device.srdy_gpio, IRQF_TRIGGER_LOW, srdy_asserted_isr, NULL); #endif nlgpio_release(g_spi_ipc_device.mrdy_gpio); nlspi_release(g_spi_ipc_device.spi_slave); result = check_crc_and_dispatch(len_opcode_rx, rx_buffer, rx_data_len); #ifndef NL_NO_RTOS xSemaphoreGive(&spi_ipc_mutex); #endif DEBUG_TRACE(("%s: ending, result %d\n", __func__, result)); #if !defined(NL_NO_RTOS) && defined(PRODUCT_IPC_OPCODE_ENABLE_ACK_MODE) if (result == -1) { /* Print some additional debug information to help * diagnose circumstances when corruption occurred */ printf("%s: sending NAK, tx len = %u, op = %u\n", __func__, len_opcode_tx[0], len_opcode_tx[1]); nlspi_ipc_send(PRODUCT_IPC_OPCODE_NAK, 0, NULL); } else if (result == 1) { nlspi_ipc_send(PRODUCT_IPC_OPCODE_ACK, 0, NULL); } #endif // !defined(NL_NO_RTOS) && defined(PRODUCT_IPC_OPCODE_ENABLE_ACK_MODE) return result; }
nestlabs/nlplatform
src/cpu/arm/cortex-m3/fault.c
/* * * Copyright (c) 2015-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file implements an API for handling crashes and provides fault * handlers. This file also defines data structures, that are saved to RAM * on a hard fault, that are useful for debugging. * */ #include <stdio.h> #include <stddef.h> #include <string.h> #include <FreeRTOS.h> #include <task.h> #include <nlertask.h> #include <nlplatform.h> #include <nlplatform/arch/nlplatform_arm_cm3.h> #include <nlplatform/nlfault.h> #if defined(BUILD_FEATURE_RAM_CONSOLE) #include <nlplatform/nlram_console.h> #endif #include <nlplatform/nlwatchdog.h> #include <nlbacktrace.h> #ifdef BUILD_FEATURE_BREADCRUMBS #include <nlbreadcrumbs.h> #include <nlbreadcrumbs-local.h> #include <nlbreadcrumbs-all.h> #endif /* BUILD_FEATURE_BREADCRUMBS */ #include <nlutilities.h> #define SCB_CFSR_IACCVIOL ((uint32_t)0x00000001) #define SCB_CFSR_DACCVIOL ((uint32_t)0x00000002) #define SCB_CFSR_MUNSTKERR ((uint32_t)0x00000008) #define SCB_CFSR_MSTKERR ((uint32_t)0x00000010) #define SCB_CFSR_MMARVALID ((uint32_t)0x00000080) #define SCB_CFSR_IBUSERR ((uint32_t)0x00000100) #define SCB_CFSR_PRECISERR ((uint32_t)0x00000200) #define SCB_CFSR_IMPRECISERR ((uint32_t)0x00000400) #define SCB_CFSR_UNSTKERR ((uint32_t)0x00000800) #define SCB_CFSR_STKERR ((uint32_t)0x00001000) #define SCB_CFSR_BFARVALID ((uint32_t)0x00008000) #define SCB_CFSR_UNDEFINSTR ((uint32_t)0x00010000) #define SCB_CFSR_INVSTATE ((uint32_t)0x00020000) #define SCB_CFSR_INVPC ((uint32_t)0x00040000) #define SCB_CFSR_NOCP ((uint32_t)0x00080000) #define SCB_CFSR_UNALIGNED ((uint32_t)0x01000000) #define SCB_CFSR_DIVBYZERO ((uint32_t)0x02000000) /* For stack overflows, we want nlbacktrace()/nlbacktrace_with_lr() to return a minimum * number of backtrace levels, since a stack overflow should have many call levels. * If the minimum is not met, we call nlbacktrace_no_context() * instead to get a longer list of possible LR values from the stack because we * presume that the former failed for some reason (bad pc or lr or both). */ #define MIN_BACKTRACE_LEVELS_FOR_STACK_OVERFLOW 3 typedef enum { FAULT = 0, WDT, DBGMON /* watchpoints */ } crashType; // table to convert from crashType to nl_reset_reason_t const nl_reset_reason_t kCrashTypeToResetReason[] = { NL_RESET_REASON_HARD_FAULT, // FAULT, generic NL_RESET_REASON_WATCHDOG, // WDT NL_RESET_REASON_STACK_OVERFLOW, // DBGMON }; /* r0-r3: low registers saved on process stack by CPU automatically on exception */ #define NUM_LOW_REGISTERS_ON_PROCESS_STACK 4 /* r12, lr (r14), pc (r15), psr: high reigsters saved on process stack */ #define NUM_HIGH_REGISTERS_ON_PROCESS_STACK 4 /* r4-r11 are registers we saved in common_fault_handler_c onto the main stack */ #define NUM_REGISTERS_ON_MAIN_STACK 8 /* number of entries to dump from the stack */ #define NUM_STACK_DUMP_ENTRIES 16 /* Struct representing what FreeRTOS pushed onto the stack of a non-current task */ typedef struct { /* r4-r11 is pushed by the PendSV SW interrupt handler of FreeRTOS */ uint32_t r4; uint32_t r5; uint32_t r6; uint32_t r7; uint32_t r8; uint32_t r9; uint32_t r10; uint32_t r11; #if __CORTEX_M == 0x04 // Cortex M4F has an extra word pushed that tells us if FP registers are in use // and also saved on the stack. Right now we don't expect FP registers to // be saved so have this word, but don't look at it. In the future, if we // start using HW FP, we need to check this value in order to find the pendSVFrame // location correctly on the stack. uint32_t r14_FP_flags; #endif /* r0-r3, r12, lr, pc, psr are pushed by the PendSV HW interrupt of Cortex M3/M4 */ ExceptionStackFrame_t pendSVFrame; } switched_out_stack_frame_t; /* saved/restored stack has an extra word if bit 9 of psr is set */ #define PSR_EXTRA_STACK_ALIGN_BIT (1 << 9) #ifdef DEBUG #define faultDebugPrint(...) printf(__VA_ARGS__) #else #define faultDebugPrint(...) #endif #ifdef FAULT_VERBOSE static void putlabel(const char *label); static void putreg(const char *label, uint32_t value); #endif #if !defined(BUILD_FEATURE_RESET_INFO) || (defined(BUILD_FEATURE_RESET_INFO) && !defined(BUILD_FEATURE_RESET_INFO_IN_TEMP_RAM)) static uint32_t s_backtrace[NL_FAULT_DIAGS_NUM_BT_ENTRIES]; #endif /* Functions that are designed to be replaced by linker scripts for * different binaries. Binaries that have no freertos should replace * crash_dump with crash_dump_nortos, or use crash_dump_default but * replace some of the subroutines called with stubs to get just * a subset of the information depending on FLASH limitations * (e.g. one could get just the registers without backtraces, or * registers and backtraces but no breadcrumbs, etc). */ void crash_dump(uint32_t *faultingStackAddress , uint32_t *machineStackAddress, crashType type) LINKER_REPLACEABLE_FUNCTION(crash_dump_default); void usage_fault(uint32_t *faultingStackAddress , uint32_t *machineStackAddress, crashType type) LINKER_REPLACEABLE_FUNCTION(usage_fault_default); /* Parts of crash_dump_default() that can be stubbed to reduce FLASH footprint. * Bootloader/AUPD can use crash_dump_nortos() for of crash_dump() to get * the smallest size, but will have no fault information. Alternatively, * they can use crash_dump_default(), but stub out parts of it to reduce * flash size but still get some crash information. * nortos builds using crash_dump_default() should always stub the following * since they don't have tasks: * * get_and_dump_current_task_info() * dump_watchdog_flags() * dump_all_tasks() * * They can also stub out these to reduce info collected, and reduce flash size: * * crash_dump_breadcrumbs() - probably don't want to write to flash in bootloader * dump_context_to_reset_info() * dump_backtrace() - backtrace library is pretty large * dump_context() - if no printf, this is not useful */ void get_and_dump_current_task_info(const char **name, nl_reset_reason_t *reset_reason, uint32_t *stackTop) LINKER_REPLACEABLE_FUNCTION(get_and_dump_current_task_info_default); void dump_watchdog_flags(void) LINKER_REPLACEABLE_FUNCTION(dump_watchdog_flags_default); void dump_context(uint32_t *faultingStackAddress , uint32_t *machineStackAddress, crashType type, uint32_t prefault_sp) LINKER_REPLACEABLE_FUNCTION(dump_context_default); void dump_backtrace(ExceptionStackFrame_t *faultFrame, uint32_t *backtrace_buf, unsigned *backtrace_count, uint32_t prefault_sp, uint32_t stackTop, nl_reset_reason_t reset_reason) LINKER_REPLACEABLE_FUNCTION(dump_backtrace_default); #ifdef BUILD_FEATURE_RESET_INFO #define STACK_TRACE_DEPTH NL_FAULT_DIAGS_NUM_BT_ENTRIES #define TASK_NAME_LEN NL_FAULT_DIAGS_TASK_NAME_LEN #else #define STACK_TRACE_DEPTH 7 #define TASK_NAME_LEN 4 #endif // The TCB might have more characters in the name than 4, but to keep things // small for breadcrumbs, we just use 4 (3 for name, and 1 for task state). typedef struct ThreadDumpInfo { uint32_t stackDepth; uint32_t stackTrace[STACK_TRACE_DEPTH]; char name[TASK_NAME_LEN]; //make it aligned } ThreadDumpInfo_t; int threadNum = 0; // Optional API to dump SOC-specific context information on fault void nlplatform_soc_dump_context(void) NL_WEAK_ATTRIBUTE; // Optional API to dump product-specific context information on fault void nlproduct_dump_context(void) NL_WEAK_ATTRIBUTE; static uint32_t get_task_stack_top(const TaskHandle_t taskHandle) { uint32_t stackTop; nltask_t *nltask_p = (nltask_t*)taskHandle; if (nltask_p == NULL) { // Not an NLER task, just use 0 and use the looser check for valid SP. // This is probably the FreeRTOS idle task. stackTop = 0; } else { // Get the stack top from the nltask_t stackTop = (uint32_t)nltask_p->mStackTop; } return stackTop; } void nlfault_dump_callstack(void) { uint32_t buffer[8]; int j; int num_backtraces; uint32_t stackTop = 0; uint32_t sp = nlplatform_get_sp(); uint32_t pc = nlplatform_get_pc(); TaskHandle_t taskHandle = xTaskGetCurrentTaskHandle(); if (taskHandle) { stackTop = get_task_stack_top(taskHandle); } num_backtraces = nlbacktrace(pc, sp, stackTop, buffer, ARRAY_SIZE(buffer)); for (j = 0; j < num_backtraces; j++) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("0x%08lx\n"), buffer[j]); } } static void __attribute__( ( naked ) ) __attribute__( ( used ) ) common_fault_handler_c(void) { // must push registers in multiples of 2 to keep stack aligned on 8-bytes boundaries __asm volatile ( " tst lr, #4 \n" " stmdb sp!, {r4-r12,lr} \n" " itte eq \n" " mrseq r0, msp \n" " addeq r0, r0, #40 \n" " mrsne r0, psp \n" " mrs r1, msp \n" " bl crash_dump \n" " ldmia sp!, {r4-r12,pc} \n" ); } void __attribute__( ( naked ) ) nlfault_hard_fault_handler_c(void) { __asm volatile ( " mov r2, #0 \n" " b common_fault_handler_c \n" ); } void __attribute__( ( naked ) ) nlfault_usage_fault_handler_c(void) { __asm volatile ( " tst lr, #4 \n" " stmdb sp!, {r4-r12,lr} \n" " itte eq \n" " mrseq r0, msp \n" " addeq r0, r0, #32 \n" " mrsne r0, psp \n" " mrs r1, msp \n" " mov r2, #0 \n" " bl usage_fault \n" " add sp, #36 \n" " pop {lr} \n" " bx lr \n" ); } #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif static uint32_t *getRegisterPtr(uint32_t r, uint32_t *faultingStackAddress, uint32_t *machineStackAddress) { if (r < 4) return &(faultingStackAddress[r]); else if (r < 12) return &(machineStackAddress[r-4]); else if (r == 12) return &(faultingStackAddress[4]); else if (r > 13) return &(faultingStackAddress[r-14+5]); else return 0; } void usage_fault_default( uint32_t *faultingStackAddress, uint32_t *machineStackAddress, crashType type); void usage_fault_default( uint32_t *faultingStackAddress, uint32_t *machineStackAddress, crashType type) { ExceptionStackFrame_t *faultFrame = (ExceptionStackFrame_t*)faultingStackAddress; uint32_t pc = faultFrame->pc; uint32_t armFaultInstruction = (*((uint16_t*) pc) << 16) | *(((uint16_t*) pc)+1); uint16_t thumbFaultInstruction = * ((uint16_t *) pc); //faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("Usage fault: ")); // usage fault due to alignment and one that we know how to fix if ((SCB->CFSR == SCB_CFSR_UNALIGNED) && (((armFaultInstruction & 0xffc00000) == 0xe8800000) || // arm ldmia, stmia ((thumbFaultInstruction & 0xf000) == 0xc000))) // thumb ldmia, stmia { uint32_t reglist; // register list to ld/st uint32_t base; // register holding the pointer uint8_t writeback = TRUE; uint8_t ld = FALSE; uint32_t i; uint32_t *basePtr; // memory for actual loads/stores uint32_t *regPtr; // location where we can fetch the register value if ((thumbFaultInstruction & 0xf000) == 0xc000) { //faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING(" inst %x at %lx\n"), thumbFaultInstruction,pc); reglist = thumbFaultInstruction & 0x00ff; ld = thumbFaultInstruction & 0x0800 ? TRUE : FALSE; base = (thumbFaultInstruction >> 8) & 0x0007; pc += 2; } else { //faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING(" inst %lx at %lx\n"), armFaultInstruction,pc); reglist = armFaultInstruction & 0x0000ffff; writeback = armFaultInstruction & 0x00200000 ? TRUE: FALSE; ld = armFaultInstruction & 0x00100000? TRUE:FALSE; base = (armFaultInstruction >> 16) & 0x0f; pc += 4; } regPtr = getRegisterPtr(base, faultingStackAddress, machineStackAddress); if (regPtr == 0) { // this should really never happen: regPtr could be 0 for r13, // and if we're doing usage fault on SP pushes we've got // bigger problems and we will not attempt to handle that. goto crash; } basePtr = (uint32_t *) (*regPtr); for (i = 0; reglist; i++, reglist = reglist>> 1) { if (reglist & 0x01) { regPtr = getRegisterPtr(i, faultingStackAddress, machineStackAddress); if (regPtr == 0) { goto crash; } if (ld) { *regPtr = *basePtr; } else { *basePtr = *regPtr; } basePtr++; } } if (writeback) { regPtr = getRegisterPtr(base, faultingStackAddress, machineStackAddress); if (regPtr == 0) { goto crash; } *regPtr = (uint32_t) basePtr; } // fixup the return address faultFrame->pc = pc; // clear fault condition SCB->CFSR = SCB_CFSR_UNALIGNED; //faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("handled!\n")); return; } crash: crash_dump(faultingStackAddress, machineStackAddress, type); } void __attribute__( ( naked ) ) nlfault_pre_watchdog_handler_c(void) { __asm volatile ( " mov r2, #1 \n" " b common_fault_handler_c \n" ); } void __attribute__( ( naked ) ) nlfault_debug_monitor_handler_c(void) { __asm volatile ( " mov r2, #2 \n" " b common_fault_handler_c \n" ); } #ifdef FAULT_VERBOSE static void putlabel(const char *label) { if (label != NULL) { while (*label) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("%c"), *label++); } } } static void putreg(const char *label, uint32_t value) { putlabel(label); faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("%08lx\n"), value); } #endif #if defined(BUILD_FEATURE_FAULT_DUMP_TASK_STACKS) void dump_all_tasks(bool task_fault) LINKER_REPLACEABLE_FUNCTION(dump_all_tasks_default); #if !defined(configMAX_NUM_TASKS) #define THREAD_DUMP_MAX_NUM_THREADS 11 #else #define THREAD_DUMP_MAX_NUM_THREADS configMAX_NUM_TASKS #endif typedef struct fakeTCB { volatile switched_out_stack_frame_t *switched_out_stack_frame_p; } fakeTCB_t; //(gdb) p/d &((tskTCB *)0)->pcTaskName //$3 = 52 #define TCB_OFFSET_NAME 52 #define tskACTIVE_CHAR ( 'A' ) #define tskBLOCKED_CHAR ( 'B' ) #define tskREADY_CHAR ( 'R' ) #define tskDELETED_CHAR ( 'D' ) #define tskSUSPENDED_CHAR ( 'S' ) // Don't allow this to be inlined to minimize stack usage of calling function. // The calling task does printf calls which, with tokenization and ram_console, // needs a lot of stack space. static uint32_t threadDump(TaskStatus_t *task_status, char *task_name, char *task_state, uint32_t *backtrace_buf, ExceptionStackFrame_t *custom_exception_frame) __attribute__((noinline)); static uint32_t threadDump(TaskStatus_t *task_status, char *task_name, char *task_state, uint32_t *backtrace_buf, ExceptionStackFrame_t *custom_exception_frame) { volatile fakeTCB_t *tcb = (volatile fakeTCB_t *)task_status->xHandle; uint32_t lr; uint32_t pc; uint32_t psr; uint32_t sp; char cStatus; switch (task_status->eCurrentState) { case eRunning: cStatus = tskACTIVE_CHAR; break; case eReady: cStatus = tskREADY_CHAR; break; case eBlocked: cStatus = tskBLOCKED_CHAR; break; case eSuspended: cStatus = tskSUSPENDED_CHAR; break; case eDeleted: cStatus = tskDELETED_CHAR; break; default: /* Should not get here, but it is included to prevent static checking errors. */ cStatus = 0x00; break; } if (custom_exception_frame == NULL) { lr = tcb->switched_out_stack_frame_p->pendSVFrame.lr; pc = tcb->switched_out_stack_frame_p->pendSVFrame.pc; psr = tcb->switched_out_stack_frame_p->pendSVFrame.psr; sp = (uint32_t)&tcb->switched_out_stack_frame_p->pendSVFrame.stack[0]; } else { lr = custom_exception_frame->lr; pc = custom_exception_frame->pc; psr = custom_exception_frame->psr; sp = (uint32_t)&custom_exception_frame->stack[0]; } if (psr & PSR_EXTRA_STACK_ALIGN_BIT) { sp += 4; } strncpy(task_name, pcTaskGetName(task_status->xHandle), TASK_NAME_LEN-1); task_state[0] = cStatus; return nlbacktrace_with_lr(pc, lr, sp, get_task_stack_top(task_status->xHandle), backtrace_buf, STACK_TRACE_DEPTH); } // Don't allow this to be inlined to minimize stack usage of calling function static void threadDumpLocalBuf(TaskStatus_t *task_status, ExceptionStackFrame_t *custom_exception_frame) __attribute__((noinline)); static void threadDumpLocalBuf(TaskStatus_t *task_status, ExceptionStackFrame_t *custom_exception_frame) { ThreadDumpInfo_t localThreadState = {0}; uint32_t backtrace_count = threadDump(task_status, localThreadState.name, &localThreadState.name[sizeof(localThreadState.name)-1], localThreadState.stackTrace, custom_exception_frame); faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("Task: %.*s%c\n"), sizeof(localThreadState.name), localThreadState.name, localThreadState.name[sizeof(localThreadState.name)-1]); for (unsigned i = 0; i < backtrace_count; i++) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING(" 0x%08lx\n"), localThreadState.stackTrace[i]); } } void dump_all_tasks_default(bool task_fault); void dump_all_tasks_default(bool task_fault) { // Get task handles into statusArray, then set their statuses, // get task and backtrace information using threadDump(), and // then print that info static TaskStatus_t statusArray[THREAD_DUMP_MAX_NUM_THREADS]; unsigned backtrace_idx = 0; TaskHandle_t active_task_handle = xTaskGetCurrentTaskHandle(); faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("All tasks\n")); #if defined(BUILD_FEATURE_RESET_INFO) bool save_fault_to_reset_info; #ifdef BUILD_FEATURE_RESET_INFO_IN_TEMP_RAM // g_reset_info is just a cache so we always save to it and // let the subsequent boot decide whether to move the RAM // copy to the external FLASH backing store save_fault_to_reset_info = true; #else // BUILD_FEATURE_RESET_INFO_IN_TEMP_RAM // g_reset_info is our backing store since it is dedicated // retained RAM. only save this fault info if the any previous // fault has been cleared. if ((g_reset_info.fault_info.reason == NL_RESET_REASON_UNKNOWN) || (g_reset_info.fault_info.reason == NL_RESET_REASON_ASSERT)) { save_fault_to_reset_info = true; } else { save_fault_to_reset_info = false; } #endif // BUILD_FEATURE_RESET_INFO_IN_TEMP_RAM if (save_fault_to_reset_info) { if (!task_fault) { strcpy(g_reset_info.fault_info.active_task_name, "N/A"); backtrace_idx = 0; } else { // Current task always occupies index 0 of fault_info struct. It has already been populated by backtrace dump // routine. Populate the name field and skip copying the backtrace. memset(&g_reset_info.fault_info.active_task_name, 0, sizeof(g_reset_info.fault_info.active_task_name)); memset(&g_reset_info.fault_info.task_info[0].task_name, 0, sizeof(g_reset_info.fault_info.task_info[0].task_name)); strncpy(g_reset_info.fault_info.active_task_name, pcTaskGetName(active_task_handle), NL_FAULT_DIAGS_TASK_NAME_LEN - 1); strncpy(g_reset_info.fault_info.task_info[0].task_name, pcTaskGetName(active_task_handle), NL_FAULT_DIAGS_TASK_NAME_LEN - 1); g_reset_info.fault_info.task_info[0].task_state[0] = tskACTIVE_CHAR; backtrace_idx = 1; } } #endif // BUILD_FEATURE_RESET_INFO // Note that uxTaskGetNumberOfTasks() might not return the same // count as uxTaskGetSystemStateFromFault() if a fault occurred in // FreeRTOS when the current task was being removed from the // ready list but before it was placed on a blocked list. In // this special case, uxTaskGetNumberOfTasks() would return one // more than the value uxTaskGetSystemStateFromFault() returns. unsigned numTasks = (unsigned) uxTaskGetSystemStateFromFault(statusArray, THREAD_DUMP_MAX_NUM_THREADS, NULL); for (unsigned idx = 0; idx < numTasks; idx++) { ExceptionStackFrame_t *active_task_psp = NULL; /* The information about the current task was dumped from the * exception context. The FreeRTOS TCB context will not be valid * and trying to dump from it might lead to double faults because * the values from the TCB stack top won't be valid. */ if (!task_fault && active_task_handle == statusArray[idx].xHandle) { /* This is a fault on the machine stack, and we are trying to dump the active task when the * interrupt or exception occurred. We want to get the stack pointer from the PSP, and get the * PC and LR from the exception frame dumped on the machine stack */ active_task_psp = (ExceptionStackFrame_t*)nlplatform_get_psp(); } else if (statusArray[idx].xHandle == active_task_handle) { /* This is a fault on a task stack, and this is the TCB of that task. We have already dumped out * the backtrace so just skip this one. */ continue; } #if defined(BUILD_FEATURE_RESET_INFO) if (save_fault_to_reset_info) { memset(&g_reset_info.fault_info.task_info[backtrace_idx], 0, sizeof(g_reset_info.fault_info.task_info[backtrace_idx])); uint32_t backtrace_count = threadDump(&statusArray[idx], g_reset_info.fault_info.task_info[backtrace_idx].task_name, g_reset_info.fault_info.task_info[backtrace_idx].task_state, g_reset_info.fault_info.task_info[backtrace_idx].backtrace, active_task_psp); // print outside of thread_dump() to give faultDebugPrintf() as much free stack as possible. // tokenized logs w/ ram_console takes over 200 bytes of stack! faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("Task: %.*s%c\n"), sizeof(g_reset_info.fault_info.task_info[backtrace_idx].task_name), g_reset_info.fault_info.task_info[backtrace_idx].task_name, g_reset_info.fault_info.task_info[backtrace_idx].task_state[0]); for (unsigned i = 0; i < backtrace_count; i++) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING(" 0x%08lx\n"), g_reset_info.fault_info.task_info[backtrace_idx].backtrace[i]); } } else { threadDumpLocalBuf(&statusArray[idx], active_task_psp); } #else threadDumpLocalBuf(&statusArray[idx], active_task_psp); #endif backtrace_idx++; } } #endif /* defined(BUILD_FEATURE_FAULT_DUMP_TASK_STACKS) */ #ifdef BUILD_FEATURE_BREADCRUMBS /* Use linker script to replace crash_dump_breadcrumbs with * a stub function if no breadcrumbs from faults is desired. */ void crash_dump_breadcrumbs(const uint32_t *backtrace, size_t num_backtrace_entries, const char * current_task_name, bool dump_all_tasks) LINKER_REPLACEABLE_FUNCTION(nltransfer_fault_to_breadcrumbs); void nltransfer_fault_to_breadcrumbs(const uint32_t *backtrace, size_t num_backtrace_entries, const char * current_task_name, bool dump_all_tasks) { ThreadDumpInfo_t faultState = {0}; faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("breadcrumbs'ing\n")); faultState.stackDepth = num_backtrace_entries; memcpy(faultState.stackTrace, backtrace, MIN(num_backtrace_entries * sizeof(uint32_t), sizeof(faultState.stackTrace))); if (current_task_name != NULL) { memcpy(faultState.name, current_task_name, sizeof(faultState.name)); } /* This is a macro so we can't alias it directly in linker script */ nlBREADCRUMBS_crash_dump(&faultState, sizeof(faultState)); #if defined(BUILD_FEATURE_FAULT_DUMP_TASK_STACKS) && (tskKERNEL_VERSION_MAJOR < 8) if (dump_all_tasks) { for (int i = 0; i < threadNum && i < THREAD_DUMP_MAX_NUM_THREADS; i++) { nlBREADCRUMBS_crash_dump(&threadState[i], sizeof(ThreadDumpInfo_t)); } } #endif } #endif /* BUILD_FEATURE_BREADCRUMBS */ static void faultDecode(uint32_t lr, uint32_t pc) { #ifdef FAULT_VERBOSE uint32_t MMFAR = 0; uint32_t BFAR = 0; faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("-----------------\n")); if ((SCB->HFSR & SCB_HFSR_VECTTBL_Msk) != 0) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("Vector Table Hard Fault\n")); } else if ((SCB->HFSR & SCB_HFSR_FORCED_Msk) != 0) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("Other Hard Fault\n")); if ((SCB->CFSR & SCB_CFSR_MMARVALID ) != 0) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("Memory Management Fault\n")); MMFAR = SCB->MMFAR; putreg("mmfar = ", MMFAR); } if ((SCB->CFSR & SCB_CFSR_BFARVALID ) != 0) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("Bus Fault\n")); BFAR = SCB->BFAR; putreg("bfar = ", BFAR); } if ((SCB->CFSR & SCB_CFSR_IACCVIOL ) != 0) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("Instruction Access Violation Fault\n")); putreg("lr = ", lr); putreg("pc = ", pc); } else if ((SCB->CFSR & SCB_CFSR_DACCVIOL ) != 0) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("Data Access Violation Fault\n")); putreg("pc = ", pc); putreg("mmfar = ", MMFAR); } else if ((SCB->CFSR & SCB_CFSR_MUNSTKERR ) != 0) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("Memory Unstacking Fault\n")); } else if ((SCB->CFSR & SCB_CFSR_MSTKERR ) != 0) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("Memory Stacking Fault\n")); } else if ((SCB->CFSR & SCB_CFSR_IBUSERR ) != 0) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("Instruction Bus Fault\n")); } else if ((SCB->CFSR & SCB_CFSR_PRECISERR ) != 0) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("Precise Data Bus Error Fault\n")); putreg("pc = ", pc); putreg("bfar = ", BFAR); } else if ((SCB->CFSR & SCB_CFSR_IMPRECISERR ) != 0) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("Imprecise Data Bus Error Fault\n")); } else if ((SCB->CFSR & SCB_CFSR_UNSTKERR ) != 0) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("Bus Unstacking Fault\n")); } else if ((SCB->CFSR & SCB_CFSR_STKERR ) != 0) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("Bus Stacking Fault\n")); } else if ((SCB->CFSR & SCB_CFSR_UNDEFINSTR ) != 0) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("Undefined Instruction Usage Fault\n")); putreg("pc = ", pc); } else if ((SCB->CFSR & SCB_CFSR_INVSTATE ) != 0) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("Invalid State Fault\n")); putreg("pc = ", pc); } else if ((SCB->CFSR & SCB_CFSR_INVPC ) != 0) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("Invalid Program Counter Fault\n")); putreg("pc = ", pc); } else if ((SCB->CFSR & SCB_CFSR_NOCP ) != 0) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("No Coprocessor Fault\n")); putreg("pc = ", pc); } else if ((SCB->CFSR & SCB_CFSR_UNALIGNED ) != 0) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("Unaligned Access Fault\n")); putreg("pc = ", pc); } else if ((SCB->CFSR & SCB_CFSR_DIVBYZERO ) != 0) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("Divide By Zero Fault\n")); putreg("pc = ", pc); } else { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("Unknown Fault\n")); } } else if (SCB->DFSR) { if (SCB->DFSR & SCB_DFSR_EXTERNAL_Msk) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("External debug event\n")); } if (SCB->DFSR & SCB_DFSR_VCATCH_Msk) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("Vector catch\n")); } if (SCB->DFSR & SCB_DFSR_DWTTRAP_Msk) { unsigned i; typedef struct { __IO uint32_t COMP; __IO uint32_t MASK; __IO uint32_t FUNCTION; __IO uint32_t RESERVED; } comp_regs_t; comp_regs_t *comp_regs = (comp_regs_t *)&DWT->COMP0; faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("DWT debug event\n")); for (i = 0; i < (DWT->CTRL >> DWT_CTRL_NUMCOMP_Pos); i++, comp_regs++) { // dump comparator register if enabled if (comp_regs->FUNCTION & DWT_FUNCTION_FUNCTION_Msk) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("DWT->COMP[%u] = 0x%08lx\n"), i, comp_regs->COMP); faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("DWT->MASK[%u] = 0x%08lx\n"), i, comp_regs->MASK); faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("DWT->FUNCTION[%u] = 0x%08lx\n"), i, comp_regs->FUNCTION); } } } if (SCB->DFSR & SCB_DFSR_BKPT_Msk) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("Breakpoint debug event\n")); } if (SCB->DFSR & SCB_DFSR_HALTED_Msk) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("HALT debug event\n")); } } else { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("Unknown Hard Fault\n")); } #else // !FAULT_VERBOSE faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("Fault! %08lx %08lx %08lx %08lx %08lx\n"), SCB->HFSR, SCB->CFSR, SCB->MMFAR, SCB->BFAR, SCB->DFSR); #endif // FAULT_VERBOSE } #ifdef BUILD_FEATURE_RESET_INFO uint32_t *dump_context_to_reset_info(uint32_t *faultingStackAddress , uint32_t *machineStackAddress, nl_reset_reason_t reset_reason, uint32_t prefault_sp, const char *current_task_name, bool task_fault) LINKER_REPLACEABLE_FUNCTION(dump_context_to_reset_info_default); void dump_stack_overflow_info_to_reset_info(const char *current_task_name) LINKER_REPLACEABLE_FUNCTION(dump_stack_overflow_info_to_reset_info_default); static size_t append_string_to_fault_info_description(size_t index, const char *src) { while (index < sizeof(g_reset_info.fault_info.description) - 1) { g_reset_info.fault_info.description[index++] = *src++; if (*src == '\0') { break; } } return index; } void dump_stack_overflow_info_to_reset_info_default(const char *current_task_name); void dump_stack_overflow_info_to_reset_info_default(const char *current_task_name) { size_t i = append_string_to_fault_info_description(0, UNIQUE_STRING_LITERAL("stack_overflow")); if (current_task_name) { // append the task name if there is one. don't // use snprintf because it bloats bootloaders too much. i = append_string_to_fault_info_description(i, ": "); i = append_string_to_fault_info_description(i, current_task_name); } // guarantee null termination g_reset_info.fault_info.description[i] = '\0'; } uint32_t *dump_context_to_reset_info_default(uint32_t *faultingStackAddress , uint32_t *machineStackAddress, nl_reset_reason_t reset_reason, uint32_t prefault_sp, const char *current_task_name, bool task_fault); uint32_t *dump_context_to_reset_info_default(uint32_t *faultingStackAddress , uint32_t *machineStackAddress, nl_reset_reason_t reset_reason, uint32_t prefault_sp, const char *current_task_name, bool task_fault) { ExceptionStackFrame_t *faultFrame = (ExceptionStackFrame_t*) faultingStackAddress; bool save_fault_to_reset_info; uint32_t *backtrace_buf; #ifndef BUILD_FEATURE_RESET_INFO_IN_TEMP_RAM // g_reset_info is our backing store since it is dedicated // retained RAM. only save this fault info if the any previous // fault has been cleared. if ((g_reset_info.fault_info.reason == NL_RESET_REASON_UNKNOWN) || (g_reset_info.fault_info.reason == NL_RESET_REASON_ASSERT)) { #endif // BUILD_FEATURE_RESET_INFO_IN_TEMP_RAM save_fault_to_reset_info = true; // we directly use the g_reset_info.fault_info.task_info[0] buffer // when we generate the backtrace so we don't need to save it // again if (task_fault) { backtrace_buf = g_reset_info.fault_info.task_info[0].backtrace; } else { backtrace_buf = g_reset_info.fault_info.machine_backtrace; } // clear all entries in task_info memset(g_reset_info.fault_info.task_info, 0, sizeof(g_reset_info.fault_info.task_info)); // clear machine_backtrace buffer memset(&g_reset_info.fault_info.machine_backtrace, 0, sizeof(g_reset_info.fault_info.machine_backtrace)); // If this is an assert, this API will return NL_RESET_REASON_ASSERT. If it is a hard fault, it will read unknown if (nl_reset_info_get_reset_reason() == NL_RESET_REASON_UNKNOWN) { memset(g_reset_info.fault_info.description, 0, sizeof(g_reset_info.fault_info.description)); } #ifndef BUILD_FEATURE_RESET_INFO_IN_TEMP_RAM } else { save_fault_to_reset_info = false; // fault_info isn't clean, so generate backtrace to // static buffer and don't save fault_info. backtrace_buf = s_backtrace; } #endif // BUILD_FEATURE_RESET_INFO_IN_TEMP_RAM if (save_fault_to_reset_info) { // save r0-r3 memcpy((void*)&g_reset_info.fault_info.registers, (void*)faultingStackAddress, NUM_LOW_REGISTERS_ON_PROCESS_STACK * sizeof(uint32_t)); // save r4-r11 memcpy((void*)&g_reset_info.fault_info.registers[4], machineStackAddress, NUM_REGISTERS_ON_MAIN_STACK * sizeof(uint32_t)); // save r12 g_reset_info.fault_info.registers[12] = faultFrame->r12; // save psp (r13) g_reset_info.fault_info.registers[13] = prefault_sp; // save lr (r14), pc (r15), psr g_reset_info.fault_info.registers[14] = faultFrame->lr; g_reset_info.fault_info.registers[15] = faultFrame->pc; g_reset_info.fault_info.registers[16] = faultFrame->psr; if (reset_reason == NL_RESET_REASON_WATCHDOG) { dump_watchdog_flags(); } else if (reset_reason == NL_RESET_REASON_STACK_OVERFLOW) { dump_stack_overflow_info_to_reset_info(current_task_name); } } return backtrace_buf; } #endif /* BUILD_FEATURE_RESET_INFO */ /* When tokenizing, the first argument to printf must be a * string literal, but when not tokenizing, we want the * string to be named so it can be dead stripped by the * current version of gcc we're using (future versions don't * need this). Can't use UNIQUE_PRINTF_FORMAT_STRING() in * this case because we're using the same literal string twice. */ #ifdef BUILD_FEATURE_PRINTF_TOKENIZATION #define PRINT_REG_FORMAT_STRING "r%d\t0x%08lx\n" #else #ifdef DEBUG static const char PRINT_REG_FORMAT_STRING[] = "r%d\t0x%08lx\n"; #endif // DEBUG #endif // BUILD_FEATURE_PRINTF_TOKENIZATION void dump_context_default(uint32_t *faultingStackAddress , uint32_t *machineStackAddress, crashType type, uint32_t prefault_sp); void dump_context_default(uint32_t *faultingStackAddress , uint32_t *machineStackAddress, crashType type, uint32_t prefault_sp) { unsigned i; ExceptionStackFrame_t *faultFrame = (ExceptionStackFrame_t*) faultingStackAddress; if (type == FAULT) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("Oops!\n")); } else if (type == WDT) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("!!wdog!!\n")); } else if (type == DBGMON) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("DbgMon - StackOverflow\n")); } // fault type dump faultDecode(faultFrame->lr, faultFrame->pc); #if defined(BUILD_FEATURE_RAM_CONSOLE) // Remaining fault dump does not go into RAM console because it goes to // service via an event. Allow above print to go to RAM console, so that // RAM console indicates that a fault has occured. nl_ram_console_disable(); #endif // register dump: r0-r3 for (i = 0; i < NUM_LOW_REGISTERS_ON_PROCESS_STACK; i++) { faultDebugPrint(PRINT_REG_FORMAT_STRING, i, faultingStackAddress[i]); } // register dump: r4-r11 for (i = 0; i < NUM_REGISTERS_ON_MAIN_STACK; i++) { faultDebugPrint(PRINT_REG_FORMAT_STRING, i+4, machineStackAddress[i]); } // register dump: r12, lr, pc, psr #ifdef DEBUG const char* names[] = { "r12", " lr", " pc", "psr" }; #endif for (i = 0; i < NUM_HIGH_REGISTERS_ON_PROCESS_STACK; i++) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("%s\t0x%08lx\n"), names[i], faultingStackAddress[i+NUM_LOW_REGISTERS_ON_PROCESS_STACK]); } // register dump: psp. faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("psp\t0x%08lx\n"), prefault_sp); nlplatform_soc_dump_context(); nlproduct_dump_context(); // stack dump faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("- stack -\n")); for ( i = 0; i < NUM_STACK_DUMP_ENTRIES; i++ ) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("%08lx\n"), *(((uint32_t*)(prefault_sp)) + i)); } } void dump_backtrace_default(ExceptionStackFrame_t *faultFrame, uint32_t *backtrace_buf, unsigned *backtrace_count, uint32_t prefault_sp, uint32_t stackTop, nl_reset_reason_t reset_reason); void dump_backtrace_default(ExceptionStackFrame_t *faultFrame, uint32_t *backtrace_buf, unsigned *backtrace_count, uint32_t prefault_sp, uint32_t stackTop, nl_reset_reason_t reset_reason) { int size; size_t i; nlwatchdog_refresh(); size = nlbacktrace_with_lr(faultFrame->pc, faultFrame->lr, prefault_sp, stackTop, backtrace_buf, NL_FAULT_DIAGS_NUM_BT_ENTRIES); // If the nlbacktrace_with_lr() returned no backtrace (possibly due to MPU preventing // an exception frame from being pushed onto the faulting stack), or if the fault // was due to a stack overflow but returned too few levels (again, bad pc or lr), // then use nlbacktrace_no_context() to get a longer backtrace. if ((size == 0) || ((reset_reason == NL_RESET_REASON_STACK_OVERFLOW) && (size < MIN_BACKTRACE_LEVELS_FOR_STACK_OVERFLOW))) { backtrace_buf[0] = faultFrame->pc; backtrace_buf[1] = faultFrame->lr; nlwatchdog_refresh(); size = nlbacktrace_no_context(prefault_sp, stackTop, backtrace_buf+2, NL_FAULT_DIAGS_NUM_BT_ENTRIES-2, 3, 16) + 2; } *backtrace_count = size; nlwatchdog_refresh(); for (i = 0; i < size; i++) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING(" 0x%08lx\n"), backtrace_buf[i]); } } void get_and_dump_current_task_info_default(const char **name, nl_reset_reason_t *reset_reason, uint32_t *stackTop); void get_and_dump_current_task_info_default(const char **name, nl_reset_reason_t *reset_reason, uint32_t *stackTop) { const char *current_task_name; TaskHandle_t handle = xTaskGetCurrentTaskHandle(); current_task_name = (const char*)pcTaskGetName(handle); faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("Task: %sR\n"), current_task_name); *name = current_task_name; if (handle) { *stackTop = get_task_stack_top(handle); } // If the MPU is used to guard stacks, it could prevent an exception // frame from being pushed onto the task stack. This can be detected // by the MSTKERR bit in the CFSR register. Print a message if this // bit is set to warn that the register dump could be garbage. if (SCB->CFSR & SCB_CFSR_MSTKERR) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("MemManage fault on saving exception context, likely stack overflow\n")); *reset_reason = NL_RESET_REASON_STACK_OVERFLOW; } } void dump_watchdog_flags_default(void); void dump_watchdog_flags_default(void) { #if defined(BUILD_FEATURE_RESET_INFO) // save watchdog flags to the description nlwatchdog_log_flags((char*)&g_reset_info.fault_info.description, sizeof(g_reset_info.fault_info.description)); #endif // print the watchdog flags to the console nlwatchdog_print_flags(); } void crash_dump_default( uint32_t *faultingStackAddress , uint32_t *machineStackAddress, crashType type); void crash_dump_default( uint32_t *faultingStackAddress , uint32_t *machineStackAddress, crashType type) { ExceptionStackFrame_t *faultFrame = (ExceptionStackFrame_t*) faultingStackAddress; uint32_t *backtrace_buf; unsigned backtrace_count = 0; nl_reset_reason_t reset_reason; #if !defined(BUILD_CONFIG_RELEASE) || defined(BUILD_FEATURE_RESET_INFO) || defined(BUILD_FEATURE_BREADCRUMBS) const char *current_task_name = NULL; #endif uint32_t stackTop = 0; #if !defined(BUILD_CONFIG_RELEASE) || defined(BUILD_FEATURE_RESET_INFO) || defined(BUILD_FEATURE_FAULT_DUMP_TASK_STACKS) // check if it's a fault on the main stack or a process (task) stack fault bool task_fault = (faultingStackAddress == machineStackAddress + 10) ? false : true; #endif uint32_t prefault_sp = (uint32_t)&faultFrame->stack[0]; if (faultFrame->psr & PSR_EXTRA_STACK_ALIGN_BIT) { prefault_sp += 4; } if (type < ARRAY_SIZE(kCrashTypeToResetReason)) { reset_reason = kCrashTypeToResetReason[type]; } else { reset_reason = NL_RESET_REASON_HARD_FAULT; // if all else fails } #if BUILD_FEATURE_PRE_WATCHDOG_ISR_EXTENSION if ((type == WDT) && (nlwatchdog_ignore_pre_watchdog_isr() == true)) { goto done; } #else // pet the watchdog so we have enough time to hopefully do the dump nlwatchdog_refresh(); #endif // quiesce system. this also could be used to disable watchdog if desired. nlplatform_quiesce_on_fault(); dump_context(faultingStackAddress, machineStackAddress, type, prefault_sp); #if !defined(BUILD_CONFIG_RELEASE) if (task_fault) { get_and_dump_current_task_info(&current_task_name, &reset_reason, &stackTop); } else { /* To get the end of the Main stack, we expect a linker script to * provide the symbol "_eusrstack". The linker script might have * other symbols with the same value, but this file will expect * all products to export a _eusrstack symbol. */ extern const uint32_t _eusrstack; /* linker symbol for end of MSP stack */ faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("- Fault on main stack (ISR?)) -\n")); stackTop = (uint32_t)&_eusrstack; } #endif #ifdef BUILD_FEATURE_RESET_INFO // Copy R0-R12, sp, LR, PC, xPSR backtrace_buf = dump_context_to_reset_info(faultingStackAddress, machineStackAddress, reset_reason, prefault_sp, current_task_name, task_fault); #else // BUILD_FEATURE_RESET_INFO backtrace_buf = s_backtrace; #endif // BUILD_FEATURE_RESET_INFO // dump backtrace of current context dump_backtrace(faultFrame, backtrace_buf, &backtrace_count, prefault_sp, stackTop, reset_reason); //all thread backtrace #if defined(BUILD_FEATURE_FAULT_DUMP_TASK_STACKS) dump_all_tasks(task_fault); #endif #ifdef BUILD_FEATURE_BREADCRUMBS //writing breadcrumb //fault breadcrumbs goes here: crash_dump_breadcrumbs(backtrace_buf, backtrace_count, current_task_name, type == WDT); #endif #if defined(BUILD_CONFIG_RELEASE) // always reset in release builds faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("resetting\n")); nlplatform_reset(reset_reason); #else /* BUILD_CONFIG_RELEASE */ #if defined(BUILD_FEATURE_NO_BKPT_ON_FAULT) if (0) { } #else if (CoreDebug->DHCSR & CoreDebug_DHCSR_C_DEBUGEN_Msk) { // if a debugger is connected, this should trigger a breakpoint. faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("breaking\n")); __asm__ __volatile__("bkpt #0"); // just single step in the debugger to restore the frame that // caused the fault to see what happened. } #endif else { #if defined(BUILD_FEATURE_RESET_ON_FAULT) faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("resetting\n")); nlplatform_reset(reset_reason); #else #if defined(BUILD_FEATURE_RESET_INFO) // when no debugger is connected, spin. if watchdog isn't // disabled, it will cause a reset. otherwise the spinning // will allow connecting a debugger later. nl_reset_info_prepare_reset(reset_reason, NULL); #endif while (1); #endif // defined(BUILD_FEATURE_RESET_ON_FAULT) } #endif // defined(BUILD_CONFIG_RELEASE) #if BUILD_FEATURE_PRE_WATCHDOG_ISR_EXTENSION done: return; #endif } /* no freertos linking, alias crash_dump to this function * to dead strip the rtos using version and it's symbols. * not static to avoid unused function warnings. */ void crash_dump_nortos( uint32_t *faultingStackAddress , uint32_t *machineStackAddress, crashType type); void crash_dump_nortos( uint32_t *faultingStackAddress , uint32_t *machineStackAddress, crashType type) { nl_reset_reason_t reset_reason = (type == WDT) ? NL_RESET_REASON_WATCHDOG : NL_RESET_REASON_HARD_FAULT; ExceptionStackFrame_t *faultFrame = (ExceptionStackFrame_t*) faultingStackAddress; uint32_t prefault_sp = (uint32_t)&faultFrame->stack[0]; if (faultFrame->psr & PSR_EXTRA_STACK_ALIGN_BIT) { prefault_sp += 4; } #if BUILD_FEATURE_PRE_WATCHDOG_ISR_EXTENSION if ((type == WDT) && (nlwatchdog_ignore_pre_watchdog_isr() == true)) { goto done; } #else // pet the watchdog so we have enough time to hopefully do the dump nlwatchdog_refresh(); #endif dump_context(faultingStackAddress, machineStackAddress, type, prefault_sp); #if defined(BUILD_FEATURE_NO_BKPT_ON_FAULT) if (0) { } #else if (CoreDebug->DHCSR & CoreDebug_DHCSR_C_DEBUGEN_Msk) { // if a debugger is connected, this should trigger a breakpoint. faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("breaking\n")); __asm__ __volatile__("bkpt #0"); // just single step in the debugger to restore the frame that // caused the fault to see what happened. } #endif else { // when no debugger is connected, we reset to not spin consuming // our battery needlessly faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("resetting\n")); nlplatform_reset(reset_reason); } #if BUILD_FEATURE_PRE_WATCHDOG_ISR_EXTENSION done: return; #endif } /* Use this as the FreeRTOS vApplicationStackOverflowHook to dump backtrace * about the task that overflowed it's stack. */ void nlfault_freertos_stack_overflow_handler_c(TaskHandle_t pxTask, signed char *pcTaskName); void nlfault_freertos_stack_overflow_handler_c(TaskHandle_t pxTask, signed char *pcTaskName) { /* Run time stack overflow checking is performed if configCHECK_FOR_STACK_OVERFLOW is defined to 1 or 2. This hook function is called if a stack overflow is detected. */ switched_out_stack_frame_t *stack_frame_p; uint32_t *backtrace_buf; uint32_t top_of_stack; size_t num_backtraces; uint32_t prefault_sp; uint32_t stackTop = get_task_stack_top(pxTask); taskDISABLE_INTERRUPTS(); // pet the watchdog so we have enough time to hopefully do the dump nlwatchdog_refresh(); // quiesce system. this also could be used to disable watchdog if desired. nlplatform_quiesce_on_fault(); faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("\nSTACK_OVERFLOW_DETECTED\n")); faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("%s\n"), (const char *)pcTaskName); /* FreeRTOS doesn't give an API for getting the top of the stack * but we know it's the first entry in the TCB pointed to by pxTask. */ top_of_stack = (((uint32_t*)pxTask)[0]); stack_frame_p = (switched_out_stack_frame_t*)top_of_stack; prefault_sp = (uint32_t)&stack_frame_p->pendSVFrame.stack[0]; if (stack_frame_p->pendSVFrame.psr & PSR_EXTRA_STACK_ALIGN_BIT) { prefault_sp += 4; } #ifdef BUILD_FEATURE_RESET_INFO bool save_fault_to_reset_info; #ifdef BUILD_FEATURE_RESET_INFO_IN_TEMP_RAM // g_reset_info is just a cache so we always save to it and // let the subsequent boot decide whether to move the RAM // copy to the external FLASH backing store save_fault_to_reset_info = true; // we directly use the g_reset_info.fault_info.task_info[0] buffer // when we generate the backtrace so we don't need to save it // again backtrace_buf = g_reset_info.fault_info.task_info[0].backtrace; // clear all entries in task_info memset(g_reset_info.fault_info.task_info, 0, sizeof(g_reset_info.fault_info.task_info)); #else // BUILD_FEATURE_RESET_INFO_IN_TEMP_RAM // g_reset_info is our backing store since it is dedicated // retained RAM. only save this fault info if the any previous // fault has been cleared. if ((g_reset_info.fault_info.reason == NL_RESET_REASON_UNKNOWN) || (g_reset_info.fault_info.reason == NL_RESET_REASON_ASSERT)) { save_fault_to_reset_info = true; // directly use the g_reset_info.fault_info.task_info[0].backtrace buffer // so no need to copy it backtrace_buf = g_reset_info.fault_info.task_info[0].backtrace; // clear all entries in task_info memset(g_reset_info.fault_info.task_info, 0, sizeof(g_reset_info.fault_info.task_info)); } else { save_fault_to_reset_info = false; // fault_info isn't clean, so generate backtrace to // static buffer and don't save fault_info. backtrace_buf = s_backtrace; } #endif // BUILD_FEATURE_RESET_INFO_IN_TEMP_RAM if (save_fault_to_reset_info) { // save r0-r3 g_reset_info.fault_info.registers[0] = stack_frame_p->pendSVFrame.r0; g_reset_info.fault_info.registers[1] = stack_frame_p->pendSVFrame.r1; g_reset_info.fault_info.registers[2] = stack_frame_p->pendSVFrame.r2; g_reset_info.fault_info.registers[3] = stack_frame_p->pendSVFrame.r3; // save r4-r11 g_reset_info.fault_info.registers[4] = stack_frame_p->r4; g_reset_info.fault_info.registers[5] = stack_frame_p->r5; g_reset_info.fault_info.registers[6] = stack_frame_p->r6; g_reset_info.fault_info.registers[7] = stack_frame_p->r7; g_reset_info.fault_info.registers[8] = stack_frame_p->r8; g_reset_info.fault_info.registers[9] = stack_frame_p->r9; g_reset_info.fault_info.registers[10] = stack_frame_p->r10; g_reset_info.fault_info.registers[11] = stack_frame_p->r11; // save r12 g_reset_info.fault_info.registers[12] = stack_frame_p->pendSVFrame.r12; // save psp (r13) g_reset_info.fault_info.registers[13] = prefault_sp; // save lr (r14), pc (r15), psr g_reset_info.fault_info.registers[14] = stack_frame_p->pendSVFrame.lr; g_reset_info.fault_info.registers[15] = stack_frame_p->pendSVFrame.pc; g_reset_info.fault_info.registers[16] = stack_frame_p->pendSVFrame.psr; snprintf(g_reset_info.fault_info.description, sizeof(g_reset_info.fault_info.description), UNIQUE_STRING_LITERAL("%s stack overflow"), pcTaskName); } #else // BUILD_FEATURE_RESET_INFO backtrace_buf = s_backtrace; #endif // BUILD_FEATURE_RESET_INFO num_backtraces = nlbacktrace_with_lr(stack_frame_p->pendSVFrame.pc, stack_frame_p->pendSVFrame.lr, prefault_sp, stackTop, backtrace_buf, NL_FAULT_DIAGS_NUM_BT_ENTRIES); if (num_backtraces < MIN_BACKTRACE_LEVELS_FOR_STACK_OVERFLOW) { // nlbacktrace_with_lr didn't find anything useful. since we // have a stack overflow, try alternative method num_backtraces = nlbacktrace_no_context(prefault_sp, stackTop, backtrace_buf + 2, NL_FAULT_DIAGS_NUM_BT_ENTRIES - 2, MIN_BACKTRACE_LEVELS_FOR_STACK_OVERFLOW, 16); /* max LRs to test from stack */ backtrace_buf[0] = stack_frame_p->pendSVFrame.pc; backtrace_buf[1] = stack_frame_p->pendSVFrame.lr; } #if !defined(BUILD_FEATURE_RESET_INFO) for (unsigned i = 0; i < num_backtraces; i++) { faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING(" 0x%08lx\n"), backtrace_buf[i]); } #endif faultDebugPrint(UNIQUE_PRINTF_FORMAT_STRING("resetting\n")); nlplatform_reset(NL_RESET_REASON_STACK_OVERFLOW); }
nestlabs/nlplatform
include/nlplatform_diags.h
<filename>include/nlplatform_diags.h /* * * Copyright (c) 2016-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file defines the interface for the radio (OpenThread) diagnostics * functions. */ #ifndef __NLPLATFORMDIAGS_H__ #define __NLPLATFORMDIAGS_H__ #include <openthread/types.h> #ifdef __cplusplus extern "C" { #endif /** * Process the platform specific radio diagnostics features. * * @param[in] aInstance The context needed when invoking other otPlatRadio APIs. * @param[in] argc The argument counter of diagnostics command line. * @param[in] argv The argument vector of diagnostics command line. * @param[out] aOutput The diagnostics execution result. * @param[in] aOutputMaxLen The output buffer size. */ void nlplatform_diags(otInstance *aInstance, int argc, char *argv[], char *aOutput, size_t aOutputMaxLen); /** * Process the platform specific radio diagnostics alarm * * @param[in] aInstance The context needed when invoking other otPlatRadio APIs */ void nlplatform_diags_alarm(otInstance *aInstance); #ifdef __cplusplus } #endif #endif /* __NLPLATFORMDIAGS_H__ */
nestlabs/nlplatform
include/nlradio.h
/* * * Copyright (c) 2016-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file defines the interfaces for controlling and configuring the * device's Thread radio (IEEE 802.15.4). */ #ifndef __NLRADIO_H__ #define __NLRADIO_H__ #include <stdint.h> #ifdef __cplusplus extern "C" { #endif /** * The radio PHY layer parameters, could be used to calculate the ota time of the radio packet, * it is required when the radio supports IEEE 802.15.4-2015 Header IEs (Information Element) * process (PLATFORM-451). */ #define PHY_US_PER_SYMBOL 16 ///< Duration of single symbol in microseconds #define PHY_SYMBOLS_PER_OCTET 2 ///< Number of symbols in single byte (octet) #define PHR_SIZE 1 ///< Size of PHR field /** * The possible radio states returned by nlradio_get_state(). */ typedef enum nlradio_state { /** * The transceiver is completely disabled and no configuration * parameters are retained. */ k_nlradio_state_disabled = 0, /** * The transceiver is in a sleep state and configuration * parameters are retained. */ k_nlradio_state_sleep = 1, /** * The receive path is enabled and searching for preamble + SFD. */ k_nlradio_state_receive = 2, /** * The transmit path is enabled. */ k_nlradio_state_transmit = 3, /* DO NOT USE idle state - it's going away */ k_nlradio_state_idle = 4, /** * The radio is performing an energy scan. */ k_nlradio_state_energy_scan = 5 } nlradio_state_t; /** * The possible radio transmission errors passed as an argument to transmit_complete_cb(). */ typedef enum nlradio_tx_error { /** * The transmission completed successfully, no error. */ k_nlradio_tx_error_none = 0, /** * The transmission failed because no ack frame was received. */ k_nlradio_tx_error_no_ack = -1, /** * The transmission failed because the channel was busy. */ k_nlradio_tx_error_channel_busy = -2, /** * The transmission failed due to a platform specific error. */ k_nlradio_tx_error_platform = -3, /** * The transmission failed due to tx done notification timeout. */ k_nlradio_tx_error_done_timeout = -4, } nlradio_tx_error_t; /** * The possible radio receive errors passed as an argument to receive_complete_cb(). */ typedef enum nlradio_rx_error { /** * The receive completed successfully, no error. */ k_nlradio_rx_error_none = 0, /** * The receive failed because there was no rx buffer */ k_nlradio_rx_error_no_buffer = -1, /** * The receive failed because the buffer was too small. */ k_nlradio_rx_error_buffer_too_small = -2, /** * The receive operation was cancelled. */ k_nlradio_rx_error_cancelled = -3, } nlradio_rx_error_t; /** * The possible nlradio API errors. */ typedef enum nlradio_error { k_nlradio_error_none = 0, k_nlradio_error_fail = -1 } nlradio_error_t; /** * The possible radio capabilities that can be queried via nlradio_get_capabilities() */ typedef enum nlradio_capabilities { k_nlradio_capability_none = 0x00, k_nlradio_capability_ack_timeout = 0x01, k_nlradio_capability_energy_scan = 0x02, k_nlradio_capability_tx_retries = 0x04, k_nlradio_capability_csma_backoff = 0x08, } nlradio_capabilities_t; /** * The possible radio receive errors passed as an argument to receive_complete_cb(). */ typedef enum nlradio_filter_mode { /** * Normal MAC filtering is in place. */ k_nlradio_filter_mode_normal = 0, /** * All MAC packets matching the network (PANID) are passed up the stack. */ k_nlradio_filter_mode_network_promiscuous = 1, /** * All decoded MAC packets are passed up the stack. */ k_nlradio_filter_mode_full_promiscuous = 2, } nlradio_filter_mode_t; /** * The possible radio receive errors passed as an argument to receive_complete_cb(). */ typedef struct nlradio_tx_params { const uint8_t *buffer; uint32_t length; uint8_t channel; int8_t power; bool is_cca_enabled; } nlradio_tx_params_t; /** * A callback provided by the caller to nlradio_transmit. * This callback will be called by the ISR when the transmission completes. * @param[in] error The Tx error code. * @param[in] framePending The frame pending value in the received ACK frame, * or false if no ACK was received. * @param[in] ackPower The rssi (in dBm) of the received ACK frame, * or kRadioRssiUnknown if no ACK was received * or no support for providing rssi for ACKs. * @param[in] ackLqi The lqi of the received ACK frame, * or 0 if no ACK was received or not supported. * @param[in] fromIsr True if the callback is being executed from ISR * context, false otherwise. */ typedef void (*transmit_complete_cb)(nlradio_tx_error_t error, bool framePending, int8_t ackPower, int8_t ackLqi, bool fromIsr); /** * A callback provided by the caller to nlradio_receive. * This callback will be called by the ISR when the receive completes. * @param[in] error The Rx error code. * @param[in] fromIsr True if the callback is being executed from ISR * context, false otherwise. */ typedef void (*receive_complete_cb)(nlradio_rx_error_t error, bool fromIsr); /** * A callback provided by the caller to nlradio_transmit. * This callback will be called by the ISR when the transmission starts (tx sfd: start-of-frame delimiter). * * @param[in] psdu A pointer to the psdu which is going to be sent by radio. * @param[in] fromIsr True if the callback is being executed from ISR * context, false otherwise. */ typedef void (*transmit_start_cb)(const uint8_t *psdu, bool fromeIsr); /** * A callback provided by the caller to nlradio_start_energyscan. * This callback will be called by the driver when the energy scan completes. * @param[in] rssi The signal strength result in dbm. * @param[in] fromIsr True if the callback is being executed from ISR * context, false otherwise. */ typedef void (*escan_complete_cb)(int8_t rssi, bool fromIsr); /** * Intialize the radio. * * @param[in] inContext A pointer to a nlradio specific context * provided by nlradio client. * * @retval k_nlradio_error_none If radio driver initialization succeeded. * @retval k_nlradio_error_fail If radio driver initialization failed. */ int nlradio_init(void *inContext); /** * Initialize and enable the radio, then transition to sleep state. * * @retval k_nlradio_error_none If radio driver transitioned to sleep. * @retval k_nlradio_error_fail If radio driver initialization failed. */ int nlradio_enable(void); /** * Disable radio and transition to disabled. * * @retval k_nlradio_error_none If transitioned to disabled state. * @retval k_nlradio_error_fail If failed to disable radio. */ int nlradio_disable(void); /** * Get the current state of the radio driver. * * @retval The current radio driver state, one of nlradio_state_t. */ nlradio_state_t nlradio_get_state(void); /** * Set the PAN ID for address filtering. * * @param[in] pan_id The IEEE 802.15.4 PAN ID. * * @retval k_nlradio_error_none If the PAN ID set operation succeeded. * @retval k_nlradio_error_fail If the PAN ID set operation failed. */ int nlradio_set_pan_id(uint16_t pan_id); /** * Set the default TX power, used for ACK. * * @param[in] aPower The TX power to use in dBm * * @retval k_nlradio_error_none If the default TX power set operation succeeded. * @retval k_nlradio_error_fail If the default TX power set operation failed. */ int nlradio_set_tx_power(int8_t aPower); /** * Set the Extended Address for address filtering. * * @param[in] extended_address A pointer of 8 bytes containing the IEEE 802.15.4 Extended Address. * * @retval k_nlradio_error_none If the Extended Address set operation succeeded. * @retval k_nlradio_error_fail If the Extended Address set operation failed. */ int nlradio_set_extended_address(const uint8_t *extended_address); /** * Set the Short Address for address filtering. * * @param[in] short_address The IEEE 802.15.4 Short Address. * * @retval k_nlradio_error_none If the Short Address set operation succeeded. * @retval k_nlradio_error_fail If the Short Address set operation failed. */ int nlradio_set_short_address(uint16_t short_address); /** * Put the radio to sleep and the driver into the sleep state. * * @retval k_nlradio_error_none If the radio was successfully put in sleep mode. * @retval k_nlradio_error_fail If the function failed. */ int nlradio_sleep(void); #ifdef BUILD_FEATURE_RADIO_HEADER_IE /** * Transmit the provided buffer on the specified channel. * * @note * The buffer cannot be reused until the transmit_complete_cb function is * called because it may be referenced by the HW DMA engine. * A successful return indicates that the radio driver has transitioned * into the k_nlradio_state_transmit state. The radio will remain in this state * until the transmit operation completes upon which it will execute the optional * callback (tx_complete_cb) if provided. * Both tx_complete_cb and tx_start_cb are executed by the ISR and must therefore be * ISR safe. * * * @param[in] radio_tx_params Tx packet and other params. Contents of this struct can be changed by the caller. Please make a copy if using elsewhere. * @param[in] tx_complete_cb An optional callback that will be called when the transmit completes. Can be NULL. * @param[in] tx_start_cb An optional callback that will be called when the transmit starts. Can be NULL. * * @retval k_nlradio_error_none If the transmission was started successfully and the radio transitioned to the k_nlradio_state_transmit. * @retval k_nlradio_error_fail If the transmission failed to start. */ int nlradio_transmit(nlradio_tx_params_t *radio_tx_params, transmit_complete_cb tx_complete_cb, transmit_start_cb tx_start_cb); #else /** * Transmit the provided buffer on the specified channel. * * @note * The buffer cannot be reused until the transmit_complete_cb function is * called because it may be referenced by the HW DMA engine. * A successful return indicates that the radio driver has transitioned * into the k_nlradio_state_transmit state. The radio will remain in this state * until the transmit operation completes upon which it will execute the optional * callback (cb) if provided. The callback is executed by the ISR and must therefore be * ISR safe. * * * @param[in] radio_tx_params Tx packet and other params. Contents of this struct can be changed by the caller. Please make a copy if using elsewhere. * @param[in] cb An optional callback that will be called when the transmit completes. Can be NULL. * * @retval k_nlradio_error_none If the transmission was started successfully and the radio transitioned to the k_nlradio_state_transmit. * @retval k_nlradio_error_fail If the transmission failed to start. */ int nlradio_transmit(nlradio_tx_params_t *radio_tx_params, transmit_complete_cb cb); #endif // BUILD_FEATURE_RADIO_HEADER_IE /** * Transition the radio to receive and execute the callback when complete. * * @note * A successful return indicates that the radio driver has transitioned * into the k_nlradio_state_receive state. The radio will remain in this state * until the receive operation completes upon which it will execute the callback * (cb). The callback is executed by the ISR and must therefore be * ISR safe. * * @param[in] channel The radio channel upon which the receive operation shall occur. * @param[in] cb A callback that will be called when the receive completes. * * @retval k_nlradio_error_none If the reception was started successfully and the radio transitioned to the k_nlradio_state_receive. * @retval k_nlradio_error_fail If the reception failed to start. */ int nlradio_receive(uint8_t channel, receive_complete_cb cb); /** * Read radio RSSI. * * @note * RSSI should be read when there are no detectable ongoing * 15.4 packet transmissions. * * @param[out] rssi A pointer to hold the RSSI value. * * @retval k_nlradio_error_none Successfully read RSSI. * @retval k_nlradio_error_fail Radio was busy, could not read RSSI. */ int nlradio_get_rssi(int8_t *rssi); #ifdef BUILD_FEATURE_RADIO_HEADER_IE /** * Called to perform post-processing of a previously received frame. * * @note * The caller is expected to call this API only after having been notified * by execution of the receive_complete_cb that was passed into nlradio_receive(). * * @param[out] buffer A buffer pointer to hold the received frame on completion. * @param[out] num_bytes The number of bytes used in buffer to store the RX frame. * @param[out] channel The channel the radio was on when it received the frame. * @param[out] power The signal strength (RSSI) of the received frame. * @param[out] lqi The link quality indicator for the received frame. * @param[out] timestamp The time since boot when the radio began to receive the frame (rx sfd), in microseconds. * * @retval k_nlradio_error_none If the driver specific operation completed successfully. * @retval k_nlradio_error_fail If the driver specific operation failed. */ int nlradio_post_process_receive(uint8_t **buffer, uint32_t *num_bytes, uint8_t *channel, int8_t *power, uint8_t *lqi, uint64_t *timestamp); #else /** * Called to perform post-processing of a previously received frame. * * @note * The caller is expected to call this API only after having been notified * by execution of the receive_complete_cb that was passed into nlradio_receive(). * * @param[out] buffer A buffer pointer to hold the received frame on completion. * @param[out] num_bytes The number of bytes used in buffer to store the RX frame. * @param[out] channel The channel the radio was on when it received the frame. * @param[out] power The signal strength (RSSI) of the received frame. * @param[out] lqi The link quality indicator for the received frame. * * @retval k_nlradio_error_none If the driver specific operation completed successfully. * @retval k_nlradio_error_fail If the driver specific operation failed. */ int nlradio_post_process_receive(uint8_t **buffer, uint32_t *num_bytes, uint8_t *channel, int8_t *power, uint8_t *lqi); #endif // BUILD_FEATURE_RADIO_HEADER_IE /** * Called to free a buffer received in nlradio_post_process_receive. * * @note * The caller is expected to call this API when it is ready to free a buffer it * acquired from nlradio_post_process_receive. * * @param[in] buffer A buffer to be freed. * * @retval k_nlradio_error_none If the driver specific operation completed successfully. * @retval k_nlradio_error_fail If the driver specific operation failed. */ int nlradio_buffer_free(uint8_t *buffer); /** * Returns the capabilities of the radio. * * @retval A bitfield consisting of zero or more nlradio_capabilities_t values. */ nlradio_capabilities_t nlradio_get_capabilities(void); /** * Override source address matching and set frame pending * for all short and extended address data polls. * * @param[in] enable true, to set frame pending for all acks * false, to use the frame pending source address match tables * to determine whether to set frame pending in ack * * @retval k_nlradio_error_none If the override source match operation succeeded. * @retval k_nlradio_error_fail If the override source match operation failed. */ int nlradio_override_source_match(bool enable); /** * Clear all Extended Address source match entries. * * @retval k_nlradio_error_none If the clear all extended address match operation succeeded. * @retval k_nlradio_error_fail If the clear all extended address match operation failed. */ int nlradio_clear_extended_source_match_address_entries(void); /** * Set/Clear the Extended Address source match entry. * * @param[in] extended_address A pointer of 8 bytes containing the IEEE 802.15.4 Extended Address. * @param[in] pending true, to add this extended address to the source match table, * false, to remove this extended address from the source match table * * @retval k_nlradio_error_none If the set extended address match operation succeeded. * @retval k_nlradio_error_fail If the address could not be added to the table when pending == true * or if the address was not found when pending == false */ int nlradio_set_extended_source_match_address_entry(const uint8_t *extended_address, bool pending); /** * Clear all Short Address source match entries. * * @retval k_nlradio_error_none If the clear all short address match operation succeeded. * @retval k_nlradio_error_fail If the clear all short address match operation failed. */ int nlradio_clear_short_source_match_address_entries(void); /** * Set/Clear the Short Address source match entry. * * @param[in] short_address The IEEE 802.15.4 Short Address. * @param[in] pending true, to add this short address to the source match table, * false, to remove this short address from the source match table * * @retval k_nlradio_error_none If the set short address match operation succeeded. * @retval k_nlradio_error_fail If the address could not be added to the table when pending == true * or if the address was not found when pending == false */ int nlradio_set_short_source_match_address_entry(uint16_t short_address, bool pending); /** * Get the radio filter mode. * * @retval The current filter mode. */ nlradio_filter_mode_t nlradio_get_filter_mode(void); /** * Set the radio filter mode to either normal (destination address filtering), * promiscuous (all to a given panid), or monitor mode (all on given channel). * * @param[in] filter_mode The radio filter mode. * * @retval k_nlradio_error_none If the set filter mode operation succeeded. * @retval k_nlradio_error_fail If the given filter mode could not be set. */ int nlradio_set_filter_mode(nlradio_filter_mode_t filter_mode); /** * Initiate an energy scan on the specified channel for the specified duration. * * @param[in] channel The radio channel upon which the energy scan operation shall occur. * @param[in] duration_msec The duration in milliseconds for the energy scan. * @param[in] cb A callback that will be called when the energy scan completes. * * @retval k_nlradio_error_none If the start energy scan operation succeeded. * @retval k_nlradio_error_fail If the start energy scan operation failed. */ int nlradio_start_energy_scan(uint8_t channel, uint32_t duration_msec, escan_complete_cb cb); /** * Get the factory-assigned IEEE EUI-64 for this interface. * * @param[in] aInstance The OpenThread instance structure. * @param[out] aIeeeEui64 A pointer to where the factory-assigned IEEE EUI-64 will be placed. * * @retval k_nlradio_error_none If the Extended Address set operation succeeded. * @retval k_nlradio_error_fail If the Extended Address set operation failed. */ int nlradio_get_ieee_eui64(uint8_t *aIeeeEui64); /** * Get radio receive sensitivity. * * @retval The radio receive sensitivity value in dBm. */ int nlradio_get_rx_sensitivity(void); #ifdef BUILD_FEATURE_ANTENNA_DIVERSITY void nlradio_set_prevent_antenna_switch(bool prevent_switching); #endif /** * set the tx power backoff in dBm * * @param[in] power backoff in units of 0.01 dBm. * * @retval k_nlradio_error_none If the TX power backoff set operation succeeded. * @retval k_nlradio_error_fail If the TX power backoff set operation failed. */ int nlradio_set_txpower_backoff(int aBackoff); /** * Set the target TX power to be used for packet transmission & * acks. * * @param[in] target TX power in units of 0.01 dBm. * * @retval k_nlradio_error_none If the default TX power set operation succeeded. * @retval k_nlradio_error_fail If the default TX power set operation failed. */ int nlradio_set_target_txpower(int aPower); #ifdef __cplusplus } #endif #endif /* __NLRADIO_H__ */
nestlabs/nlplatform
include/spi_flash/n25q.h
<reponame>nestlabs/nlplatform<filename>include/spi_flash/n25q.h /* * * Copyright (c) 2015-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file contains macro defines of the N25Q SPI flash chip. * */ #ifndef __N25Q_H_INCLUDED__ #define __N25Q_H_INCLUDED__ /* spi bus, spi freq, and chip select pin should be defined in nlproduct_config.h */ #define N25Q_MAX_SPI_FREQ_HZ (108000000) /* 108MHz */ #define FLASH_SPI_MODE SPI_MODE_0 /* Size parameters */ #define FLASH_SPI_SIZE (0x200000) /* 2,097,152 Bytes or 2MB */ #define FLASH_SPI_ERASE_SIZE (4096) /* 4KB (smallest erasable unit) */ #define FLASH_SPI_FAST_ERASE_SIZE (0x10000) /* 65,536 Bytes or 64KB */ #define FLASH_SPI_WRITESIZE (256) /* writable unit */ #define FLASH_SPI_READ_ID_SIZE (20) #define FLASH_SPI_FAST_READ_DUMMY_CYCLES (1) /* default number of dummy cycles is 1 byte when using FAST_READ */ #define FLASH_SPI_READ_DUMMY_CYCLES (0) /* default number of dummy cycles is 0 byte when using regular READ */ #define FLASH_SPI_FAST_READ_FREQ_HZ (104000000) /* 104MHz */ #define FLASH_SPI_READ_FREQ_HZ (50000000) /* 50MHz */ /* Status Register and masks */ #define CMD_RDSR (0x05) /* to read out the status reg */ #define CMD_WRSR (0x01) /* to write new val to the status reg */ #define M_STAT_SRWD (1<<7) /* status reg write disable */ #define M_STAT_BOT (1<<6) #define M_STAT_BP3 (1<<5) /* level of protected block */ #define M_STAT_BP2 (1<<4) #define M_STAT_BP1 (1<<3) #define M_STAT_BP0 (1<<2) #define M_STAT_WEL (1<<1) /* write enable latch */ #define M_STAT_BUSY_BIT (1<<0) /* busy bit mask */ #define M_STAT_READY_VALUE (0<<0) /* value of busy bit to indicate device is ready */ #define M_STAT_BUSY_VALUE (1<<0) /* value of busy bit to indicate device is busy */ /* Register/Setting Commands */ #define CMD_WREN (0x06) /* write enable */ #define CMD_WRDI (0x04) /* write disable */ /* Read/Write Array Commands */ #define CMD_READ (0x03) /* max speed 50 MHz */ #define CMD_FAST_READ (0x0B) /* max speed 108 MHz */ #define CMD_PP (0x02) /* to program the selected page */ #define CMD_SSE (0x20) /* subsector erase: "4K subsector" is called "sector" on MX25 */ #define CMD_SE (0xD8) /* sector erase: "64K sector" is called "block" on MX25 */ #define CMD_BE (0xC7) /* bulk erase: "bulk erase" is called "chip erase" on MX25 */ /* Read device ID */ #define CMD_RDID (0x9E) /* read device ID */ /* Chip IDs */ #define FLASH_SPI_MANUFACTORY_ID (0x20) #define FLASH_SPI_MEMORY_TYPE_ID (0xBB) #define FLASH_SPI_MEMORY_DENSITY_ID (0x15) /* delay time for different operations. DELAY_MSEC * DELAY_LOOP_COUNT == total delay time */ #define PP_DELAY_MSEC (1) #define PP_DELAY_LOOP_COUNT (200) /* max delay 200ms */ #define BE_DELAY_MSEC (2) #define BE_DELAY_LOOP_COUNT (15000) /* max delay 150s */ #define SE_DELAY_MSEC (2) #define SE_DELAY_LOOP_COUNT (2000) /* max delay 4s */ #define SSE_DELAY_MSEC (2) #define SSE_DELAY_LOOP_COUNT (2000) /* max delay 4s */ #define FLASH_SPI_POWER_UP_MAX_DELAY_MSEC (1) #define FLASH_SPI_POWER_DOWN_MAX_DELAY_USEC (100) #endif /* __N25Q_H_INCLUDED__ */
nestlabs/nlplatform
include/nlcrc.h
/* * * Copyright (c) 2015-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file defines an API for hw accelerated CRC * */ #ifndef __NLCRC_H_INCLUDED__ #define __NLCRC_H_INCLUDED__ #include <stdint.h> #include <stdbool.h> #ifdef __cplusplus extern "C" { #endif typedef enum { kTransposeTypeWriteNone = 0, kTransposeTypeWriteBitsOnly, kTransposeTypeWriteBoth, kTransposeTypeWriteBytesOnly, } nlcrc_transpose_write_t; typedef enum { kTransposeTypeReadNone = 0, kTransposeTypeReadBitsOnly, kTransposeTypeReadBoth, kTransposeTypeReadBytesOnly, } nlcrc_transpose_read_t; typedef enum { kCrcLen8Bits = 0, kCrcLen16Bits, kCrcLen32Bits } nlcrc_len_t; #ifdef NLCRC_TRANSPOSE_WRITE_PRODUCT_DEFAULT #define NLCRC_TRANSPOSE_WRITE_DEFAULT NLCRC_TRANSPOSE_WRITE_PRODUCT_DEFAULT #else #define NLCRC_TRANSPOSE_WRITE_DEFAULT kTransposeTypeWriteNone #endif #ifdef NLCRC_TRANSPOSE_READ_PRODUCT_DEFAULT #define NLCRC_TRANSPOSE_READ_DEFAULT NLCRC_TRANSPOSE_READ_PRODUCT_DEFAULT #else #define NLCRC_TRANSPOSE_READ_DEFAULT kTransposeTypeReadNone #endif #ifdef NLCRC_XOR_ON_READ_PRODUCT_DEFAULT #define NLCRC_XOR_ON_READ_DEFAULT NLCRC_XOR_ON_READ_PRODUCT_DEFAULT #else #define NLCRC_XOR_ON_READ_DEFAULT true #endif #ifdef NLCRC_LEN_PRODUCT_DEFAULT #define NLCRC_LEN_DEFAULT NLCRC_LEN_PRODUCT_DEFAULT #else #define NLCRC_LEN_DEFAULT kCrcLen32Bits #endif #ifdef NLCRC_POLY_PRODUCT_DEFAULT #define NLCRC_POLY_DEFAULT NLCRC_POLY_PRODUCT_DEFAULT #else #define NLCRC_POLY_DEFAULT 0x04C11DB7 #endif #ifdef NLCRC_SEED_PRODUCT_DEFAULT #define NLCRC_SEED_DEFAULT NLCRC_SEED_PRODUCT_DEFAULT #else #define NLCRC_SEED_DEFAULT 0xffffffff #endif typedef void (*nlcrc_handler_t)(unsigned crc_result, int error_code); int nlcrc_request(nlcrc_transpose_write_t writeType, nlcrc_transpose_read_t readType, bool xorOnRead, nlcrc_len_t crcLen, unsigned poly); int nlcrc_release(void); unsigned nlcrc_compute(unsigned crc, const void *data, size_t len); unsigned nlcrc_compute_async(unsigned crc, const void *data, size_t len, nlcrc_handler_t callback); void nlcrc_set_locking(int (*lock)(void *), int (*unlock)(void *), void* context); #ifdef __cplusplus } #endif #endif /* __NLCRC_H_INCLUDED__ */
nestlabs/nlplatform
include/nlplatform.h
<gh_stars>1-10 /* * * Copyright (c) 2015-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file defines generic platform API */ #ifndef _NLPLATFORM_H_INCLUDED__ #define _NLPLATFORM_H_INCLUDED__ #ifdef __cplusplus extern "C" { #endif #include <stdint.h> #include <stdbool.h> #ifndef ARRAY_SIZE #define ARRAY_SIZE(array) (sizeof(array)/sizeof(array[0])) #endif #ifndef ALIGN_TO_WORDSIZE #define ALIGN_TO_WORDSIZE(sz) ( ((sz) + (sizeof(size_t) - 1 )) / sizeof(size_t) ) #endif /* Special macro to put string literals into named sections so dead * stripping works in older versions of gcc. This does prevent * merging of the same string, so it's best if these are unique. */ #define UNIQUE_STRING_LITERAL(str) ({ static const char __str[] = str; __str; }) /* When tokenizing, the first argument to printf must be a * string literal, but when not tokenizing, we want the * string to be named so it can be dead stripped by the * current version of gcc we're using (future versions don't * need this). */ #ifdef BUILD_FEATURE_PRINTF_TOKENIZATION #define UNIQUE_PRINTF_FORMAT_STRING(str) str #else #define UNIQUE_PRINTF_FORMAT_STRING(str) UNIQUE_STRING_LITERAL(str) #endif /* When tokenizing, the format string to NL_LOG_XXX() macros * must be a string literal, but when not tokenizing, we want the * string to be named so it can be dead stripped by the * current version of gcc we're using (future versions don't * need this). */ #ifdef BUILD_FEATURE_LOG_TOKENIZATION #define UNIQUE_LOG_FORMAT_STRING(str) str #else #define UNIQUE_LOG_FORMAT_STRING(str) UNIQUE_STRING_LITERAL(str) #endif typedef int (*nlloop_callback_fp)(void); #include <nlplatform/nlreset_info.h> #include <nlplatform_soc.h> void nlplatform_init(void); void nlplatform_product_init(void); void nlplatform_reset(nl_reset_reason_t reset_reason); void nlplatform_quiesce_on_fault(void); /* nlplatform_block_sleep: * Disable / enable all forms of sleep depending on value of 'block' parameter. * If 'block' is true, a global counter is incremented. If false, counter is decremented. * If counter is non-zero, idle hook will be skipped entirely. */ void nlplatform_block_sleep(bool block); /* Block sleep for a specified number of milliseconds. */ void nlplatform_block_sleep_ms(unsigned ms); /* Return true if sleep block counter is non-zero */ bool nlplatform_is_sleep_blocked(void); void nlplatform_force_sleep(void); void nlplatform_delay_ms(unsigned delay_ms); void nlplatform_delay_us(unsigned delay_us); void nlplatform_antenna_switch_enable(void); void nlplatform_antenna_switch_disable(void); void nlregulator_enable(unsigned regulator_id); void nlregulator_disable(unsigned regulator_id); void nlplatform_print_reset_cause(void); void nlplatform_print_wakeup_cause(void); int nlplatform_get_entropy(uint8_t *buf, size_t len); int nlplatform_get_unique_id(const uint8_t **uid, size_t *len); /* Some functions are designed to be replaced/aliased using linker scripts, * to allow the same library to be used in different ways without building * alternate versions. Sometimes the default version is fine. Sometimes * a stub is desired instead. Use this alias to indicate such special * functions. */ #include <nlcompiler.h> #define LINKER_REPLACEABLE_FUNCTION(default_function_name) NL_WEAK_ALIAS(default_function_name) /* Stub functions which can be used/shared when the default is not desired. these * return the value specified in the name. */ void void_stub_function(void); int zero_stub_function(void); /* returns 0 */ int einval_stub_function(void); /* returns -EINVAL */ /* This stub causes an assertion failure because it's a stub * that is never expected to be called, so if it is, the * fault will help diagnose why. */ void fault_stub_function(void); const char *emptystring_stub_function(void); #ifdef __cplusplus } #endif #endif /*_NLPLATFORM_H_INCLUDED__ */
nestlabs/nlplatform
include/nlgpio.h
<reponame>nestlabs/nlplatform<filename>include/nlgpio.h<gh_stars>1-10 /* * * Copyright (c) 2015-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file defines API for GPIO */ #ifndef __NLGPIO_H_INCLUDED__ #define __NLGPIO_H_INCLUDED__ #include <stdint.h> #include <stdbool.h> #ifdef __cplusplus extern "C" { #endif /* include soc specific header file that provides the * definitions of gpio flags so we don't have to convert * from generic values to specific values. * nlgio_id_t is also product specific. */ #include <nlgpio_defines.h> typedef void (*nlgpio_irq_handler_t)(const nlgpio_id_t gpio, void *arg); void nlgpio_init(void); bool nlgpio_is_valid(unsigned number); int nlgpio_request(const nlgpio_id_t gpio, nlgpio_flags_t gpio_flags); int nlgpio_release(const nlgpio_id_t gpio); int nlgpio_setmode(const nlgpio_id_t gpio, unsigned mode); unsigned nlgpio_getmode(const nlgpio_id_t gpio); int nlgpio_set_input(const nlgpio_id_t gpio); int nlgpio_set_output(const nlgpio_id_t gpio, unsigned value); int nlgpio_get_value(const nlgpio_id_t gpio); int nlgpio_set_value(const nlgpio_id_t gpio, unsigned value); int nlgpio_irq_request(const nlgpio_id_t gpio, unsigned irq_flags, nlgpio_irq_handler_t callback, void *arg); int nlgpio_irq_release(const nlgpio_id_t gpio); bool nlgpio_irq_pending(const nlgpio_id_t gpio); #ifdef __cplusplus } #endif #endif /* __NLGPIO_H_INCLUDED__ */
nestlabs/nlplatform
src/nlflash.c
<gh_stars>1-10 /* * * Copyright (c) 2012-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file contains wrappers for flash drivers * */ #include <nlassert.h> #include <errno.h> #include <nlplatform.h> #if NL_NUM_FLASH_IDS > 0 #include <nlplatform/nlflash.h> typedef struct { int (* lock)(void *); int (* unlock)(void *); void *lock_ctx; } flash_ctx_t; static flash_ctx_t s_flash_ctxs[NL_NUM_FLASH_IDS]; static bool erase_alignment_is_ok(nlflash_id_t flash_id, uint32_t start, size_t len) { const nlflash_info_t *flash_info = nlflash_get_info(flash_id); // Return true if the area to be erased starts and ends on an erase_size boundary. return ((start % flash_info->erase_size == 0) && (len % flash_info->erase_size == 0)); } void nlflash_set_lock(nlflash_id_t flash_id, int ( *lock)(void *), int (* unlock)(void *), void *lock_ctx) { s_flash_ctxs[flash_id].lock = lock; s_flash_ctxs[flash_id].unlock = unlock; s_flash_ctxs[flash_id].lock_ctx = lock_ctx; } int nlflash_lock(nlflash_id_t flash_id) { if (s_flash_ctxs[flash_id].lock != NULL) { return s_flash_ctxs[flash_id].lock(s_flash_ctxs[flash_id].lock_ctx); } return 0; } int nlflash_unlock(nlflash_id_t flash_id) { if (s_flash_ctxs[flash_id].unlock != NULL) { return s_flash_ctxs[flash_id].unlock(s_flash_ctxs[flash_id].lock_ctx); } return 0; } void nlflash_init(void) { unsigned i; for (i = 0; i < NL_NUM_FLASH_IDS; i++) { // init is optional if (g_flash_device_table[i].init != NULL) { int err = g_flash_device_table[i].init(); nlASSERT(err == 0); } } } int nlflash_request(nlflash_id_t flash_id) { int retval = nlflash_lock(flash_id); if (retval >= 0) { // request is optional if (g_flash_device_table[flash_id].request) { retval = g_flash_device_table[flash_id].request(); } } return retval; } int nlflash_release(nlflash_id_t flash_id) { int retval = 0; int lock_retval; // release is optional if (g_flash_device_table[flash_id].release) { retval = g_flash_device_table[flash_id].release(); } lock_retval = nlflash_unlock(flash_id); if ((lock_retval < 0) && (retval >= 0)) { retval = lock_retval; } return retval; } int nlflash_flush(nlflash_id_t flash_id) { int retval; int lock_retval; // flush is optional if (g_flash_device_table[flash_id].flush == NULL) { return 0; } lock_retval = nlflash_lock(flash_id); if (lock_retval < 0) { return lock_retval; } retval = g_flash_device_table[flash_id].flush(); lock_retval = nlflash_unlock(flash_id); if ((lock_retval < 0) && (retval >= 0)) { retval = lock_retval; } return retval; } int nlflash_read_id(nlflash_id_t flash_id, uint8_t *id_buf, size_t id_buf_size) { int retval; int lock_retval; // read_id is optional if (g_flash_device_table[flash_id].read_id == NULL) { return 0; } lock_retval = nlflash_lock(flash_id); if (lock_retval < 0) { return lock_retval; } retval = g_flash_device_table[flash_id].read_id(id_buf, id_buf_size); lock_retval = nlflash_unlock(flash_id); if ((lock_retval < 0) && (retval >= 0)) { retval = lock_retval; } return retval; } const nlflash_info_t *nlflash_get_info(nlflash_id_t flash_id) { const nlflash_info_t *info; int lock_retval; // get_info is not optional nlASSERT(g_flash_device_table[flash_id].get_info != NULL); lock_retval = nlflash_lock(flash_id); if (lock_retval < 0) { return NULL; } info = g_flash_device_table[flash_id].get_info(); lock_retval = nlflash_unlock(flash_id); if (lock_retval < 0) { return NULL; } return info; } int nlflash_erase(nlflash_id_t flash_id, uint32_t from, size_t len, size_t *retlen, nlloop_callback_fp callback) { int retval; int lock_retval; // erase is not optional nlASSERT(g_flash_device_table[flash_id].erase != NULL); // Start and end of the area to be erased must be on erase_size boundaries. nlASSERT(erase_alignment_is_ok(flash_id, from, len)); lock_retval = nlflash_lock(flash_id); if (lock_retval < 0) { return lock_retval; } retval = g_flash_device_table[flash_id].erase(from, len, retlen, callback); lock_retval = nlflash_unlock(flash_id); if ((lock_retval < 0) && (retval >= 0)) { retval = lock_retval; } return retval; } int nlflash_read(nlflash_id_t flash_id, uint32_t from, size_t len, size_t *retlen, uint8_t *buf, nlloop_callback_fp callback) { int retval; int lock_retval; // read is not optional nlASSERT(g_flash_device_table[flash_id].read != NULL); lock_retval = nlflash_lock(flash_id); if (lock_retval < 0) { return lock_retval; } retval = g_flash_device_table[flash_id].read(from, len, retlen, buf, callback); lock_retval = nlflash_unlock(flash_id); if ((lock_retval < 0) && (retval >= 0)) { retval = lock_retval; } return retval; } int nlflash_write(nlflash_id_t flash_id, uint32_t to, size_t len, size_t *retlen, const uint8_t *buf, nlloop_callback_fp callback) { int retval; int lock_retval; // write is not optional nlASSERT(g_flash_device_table[flash_id].write != NULL); lock_retval = nlflash_lock(flash_id); if (lock_retval < 0) { return lock_retval; } // No need to check alignment of area to be written; our write functions // either accept unaligned addresses or contain their own assertions. retval = g_flash_device_table[flash_id].write(to, len, retlen, buf, callback); lock_retval = nlflash_unlock(flash_id); if ((lock_retval < 0) && (retval >= 0)) { retval = lock_retval; } return retval; } #endif /* NL_NUM_FLASH_IDS > 0 */
nestlabs/nlplatform
include/nltime.h
<reponame>nestlabs/nlplatform /* * * Copyright (c) 2017-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file defines time API */ #ifndef __NLTIME_H_INCLUDED__ #define __NLTIME_H_INCLUDED__ #include <stdint.h> #include <nlplatform.h> #ifdef __cplusplus extern "C" { #endif /* system time (time since boot) specified in milliseconds. */ typedef int64_t nltime_system_64_t; /* system time (time since boot) specified in microseconds. */ typedef int64_t nltime_system_us_64_t; /** get current system time (time since boot) in milliseconds * * @return Current system time in milliseconds */ nltime_system_64_t nltime_get_system_ms(void); /** get current system time (time since boot) in microseconds * * @return Current system time in microseconds */ nltime_system_us_64_t nltime_get_system_us(void); #ifdef __cplusplus } #endif #endif /* __NLTIME_H_INCLUDED__ */
nestlabs/nlplatform
include/nlwatchdog.h
/* * * Copyright (c) 2015-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file defines API for HW watchdog * */ #ifndef __NLWATCHDOG_H_INCLUDED__ #define __NLWATCHDOG_H_INCLUDED__ #include <stdint.h> #include <stdbool.h> #ifdef __cplusplus extern "C" { #endif void nlwatchdog_init(void); void nlwatchdog_set_enable(bool enable); bool nlwatchdog_is_enabled(void); void nlwatchdog_refresh(void); void nlwatchdog_test(void); void nlwatchdog_stop(void); bool nlwatchdog_is_sleep_safe(void); int nlwatchdog_allocate_id(void); void nlwatchdog_enable_tracking(bool enable, unsigned id); void nlwatchdog_refresh_flag(unsigned id); void nlwatchdog_print_flags(void); void nlwatchdog_log_flags (char *dest, int len); #if BUILD_FEATURE_PRE_WATCHDOG_ISR_EXTENSION // optional function to let the pre_watchdog_isr() routine // in fault.c to ignore the pre_watchdog isr, which // effectively extends the HW watchdog timeout bool nlwatchdog_ignore_pre_watchdog_isr(void); #endif bool nlwatchdog_get_time_to_expiry(int *time_to_expiry); #ifdef __cplusplus } #endif #endif /* __NLWATCHDOG_H_INCLUDED__ */
nestlabs/nlplatform
src/compiler/apple/llvm-armv7m/eabi.c
<reponame>nestlabs/nlplatform<filename>src/compiler/apple/llvm-armv7m/eabi.c /* * * Copyright (c) 2012-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file implements EABI symbols that aren't * defined by nllibclite. */ #include <stddef.h> #include <string.h> #include <stdint.h> #ifdef __ARM_EABI__ void __aeabi_memcpy(void *dest, const void *src, size_t n); void __aeabi_memset (void *dest, size_t n, int c); void __aeabi_memcpy(void *dest, const void *src, size_t n) { size_t i; uint8_t *d = (uint8_t*) dest; uint8_t *s = (uint8_t*) src; for( i=0; i<n; i++) { *d++ = *s++; } } // note: __aeabi_memset has different parameter order than // the usual memset void __aeabi_memset (void *dest, size_t n, int c) { size_t i; uint8_t *d = (uint8_t*) dest; for( i=0; i<n; i++) { *d++ = c; } } unsigned long long __aeabi_uldivmod(unsigned long long n, unsigned long long d); unsigned long long __aeabi_uldivmod(unsigned long long n, unsigned long long d) { // Clang output is not executed on ARM, so this is not // required. __builtin_trap(); return 0; } double __aeabi_f2d(float n); double __aeabi_f2d(float n) { // Clang output is not executed on ARM, so this is not // required. __builtin_trap(); return 0; } #endif
nestlabs/nlplatform
include/nlswtimer.h
/* * * Copyright (c) 2016-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file defines API for SW timers */ #ifndef __NLSWTIMER_H_INCLUDED__ #define __NLSWTIMER_H_INCLUDED__ #include <stdint.h> #include <string.h> #include <stdbool.h> #ifdef BUILD_FEATURE_SW_TIMER_USES_RTOS_TICK #include <FreeRTOS.h> #include <task.h> #endif #ifdef __cplusplus extern "C" { #endif /* SW timer memory is provided by the caller but we keep * it opaque so that the implemenation can change. */ typedef struct { uint32_t hidden[4]; } nl_swtimer_t; /* callback function that is run in interrupt context when * the delay has expired. the resolution & accuracy * is based on the implementation but the function * should never be called earlier than the requested * delay. the return value of the function is used * as a restart delay. 0 means no restart. it's allowed * to call nl_swtimer_start() from the timer function instead * but this is more efficient, and the periodicity is more * accurate if the delay is returned this way (the delay * argument to nl_swtimer_start() might be rounded up or * padded to take into account implementation issues. */ typedef uint32_t nl_swtimer_func_t(nl_swtimer_t *timer, void *arg); /* initialize the timer object with the function and arg * to invoke when the timer delay expires */ void nl_swtimer_init(nl_swtimer_t *timer, nl_swtimer_func_t *func, void *arg); /* start a timer so that it's function is invoked when the specified * delay expires. the delay is time in milliseconds from the current * time. it is an error (asserted in debug) if the timer is already * running. */ void nl_swtimer_start(nl_swtimer_t *timer, uint32_t delay_ms); /* returns true if the timer was active and the cancel * removed it. returns false if the timer was not active * (it might have already run, or was never started). */ bool nl_swtimer_cancel(nl_swtimer_t *timer); /* returns true if the timer is active (i.e. had * been started and hasn't run yet) */ bool nl_swtimer_is_active(const nl_swtimer_t *timer); #ifdef BUILD_FEATURE_SW_TIMER_USES_RTOS_TICK /* function to be called on each rtos tick */ void nl_swtimer_rtos_tick_handler(void); /* called by platform sleep hook before attempting to enter sleep */ bool nl_swtimer_pre_sleep(TickType_t *before_sleep_tick_count, uint32_t *xExpectedIdleTime); /* called by platform sleep hook after wake from sleep */ void nl_swtimer_post_sleep(TickType_t before_sleep_tick_count); /** get system time (time since boot) in nanoseconds * * @return Current system time in nanoseconds */ uint64_t nl_swtimer_get_time_ns(void); #endif #ifdef __cplusplus } #endif #endif /* __NLSWTIMER_H_INCLUDED__ */
nestlabs/nlplatform
include/nladc.h
<gh_stars>1-10 /* * * Copyright (c) 2015-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file defines API for ADC */ #ifndef __NLADC_H_INCLUDED__ #define __NLADC_H_INCLUDED__ #include <stdint.h> #include <stddef.h> #ifdef __cplusplus extern "C" { #endif /* configuration information is implementation specific */ typedef struct nladc_config_s nladc_config_t; /* callback to be called when async sample is finished * context - Pointer to structure that was specified when nladc_read_async was called * */ typedef void (*adc_cb_t)(void *context); void nladc_init(void); /* buffer should be a pointer to a buffer of size (samples * ADC_SAMPLE_SIZE), * where ADC_SAMPLE_SIZE is implementation specific */ int nladc_read(const nladc_config_t *config, void *buffer, size_t samples); /* Asynchronously take ADC reading * * config - implementation-specific ADC configuration * buffer - pointer to a buffer of size (samples * ADC_SAMPLE_SIZE) where ADC_SAMPLE_SIZE is * implementation-specific * samples - number of ADC samples to take * cb - callback to call when sampling has finished * context - pointer to context passed to callback */ int nladc_read_async(const nladc_config_t *config, void *buffer, size_t samples, adc_cb_t cb, void *context); int nladc_calibrate(void); typedef struct nladc_calibration_s { uint16_t gain; int16_t offset; } nladc_calibration_t; int nladc_get_calibration(nladc_calibration_t *cal); #if defined(BUILD_CONFIG_DIAGNOSTICS) void nladc_reset_calibration(void); void nladc_apply_calibration(uint16_t gain, int16_t offset); void nladc_print_calibration(void); #endif #ifdef __cplusplus } #endif #endif /* __NLADC_H_INCLUDED__ */
nestlabs/nlplatform
src/nlprofile.c
/* * * Copyright (c) 2015-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file implements an interval based system usage profiling service * */ #include <nlplatform.h> #include <nlplatform/nlprofile.h> #include <FreeRTOS.h> #include <queue.h> #include <task.h> #include <nlassert.h> #include <string.h> // Structures to track enable times and total usage per interval static uint32_t nl_profile_enable_times[NL_PROFILE_NUM_TRACKED_ITEMS] = {0}; static uint32_t nl_profile_total_times[NL_PROFILE_NUM_TRACKED_ITEMS] = {0}; static uint8_t nl_profile_enabled[NL_PROFILE_NUM_TRACKED_ITEMS] = {0}; void nl_profile_start(nl_profile_t profile_index) { if (profile_index != NL_PROFILE_T_INVALID) { nl_profile_enable_times[profile_index] = nl_profile_get_current_time(); nl_profile_enabled[profile_index] = 1; } } void nl_profile_stop(nl_profile_t profile_index) { nlplatform_interrupt_disable(); if (profile_index != NL_PROFILE_T_INVALID && nl_profile_enabled[profile_index]) { nl_profile_total_times[profile_index] += nl_profile_get_current_time() - nl_profile_enable_times[profile_index]; nl_profile_enabled[profile_index] = 0; } nlplatform_interrupt_enable(); } void nl_profile_interval_start_new_interval(void) { nlplatform_interrupt_disable(); memset(nl_profile_total_times, 0, sizeof(nl_profile_total_times)); nlplatform_interrupt_enable(); nl_profile_product_start_new_interval(); } void nl_profile_interval_calculate_totals(uint32_t interval_expiry, uint32_t profile_buffer[NL_PROFILE_NUM_TRACKED_ITEMS]) { int i; // If a tracked item is enabled when we calculate totals, add the time it has been enabled // to the total time and bring the enable time up to the current interval nlplatform_interrupt_disable(); for (i = 0; i < NL_PROFILE_NUM_TRACKED_ITEMS; i++) { if (nl_profile_enabled[i]) { nl_profile_total_times[i] += interval_expiry - nl_profile_enable_times[i]; nl_profile_enable_times[i] = interval_expiry; } profile_buffer[i] = nl_profile_total_times[i]; } nlplatform_interrupt_enable(); } void nl_profile_interval_get_task_info(nl_profile_task_info_t task_profile_info[NL_PROFILE_NUM_TASKS]) { static uint32_t last_tick_snapshot[NL_PROFILE_NUM_TASKS] = {0}; TaskStatus_t task_status_array[NL_PROFILE_NUM_TASKS]; uint32_t total_run_time; int i, j; // We only intend to support profiling stats on a steady state system. // No dynamic starting or stopping of tasks. // If this assumption changes, need to revisit this assert, as well as the // mechanism we use to report nlASSERT(uxTaskGetNumberOfTasks() == NL_PROFILE_NUM_TASKS); #if configUSE_TRACE_FACILITY == 1 // Populate system info to get runtime stats and thread names uxTaskGetSystemState(task_status_array, NL_PROFILE_NUM_TASKS, &total_run_time); // Extract runtime from each task, populate profile structure // Since runtime stats are returned in the order of tasks as they appear in // FreeRTOS queues, need to sort the stats by task name. for (i = 0; i < NL_PROFILE_NUM_TASKS; i++) { for (j = 0; j < NL_PROFILE_NUM_TASKS; j++) { if (!strncmp(TaskNames[j], task_status_array[i].pcTaskName, configMAX_TASK_NAME_LEN-1)) { break; } } nlASSERT(j != NL_PROFILE_NUM_TASKS); memcpy(task_profile_info[j].name, task_status_array[i].pcTaskName, sizeof(task_profile_info[j].name)); task_profile_info[j].usage_during_interval = task_status_array[i].ulRunTimeCounter - last_tick_snapshot[j]; task_profile_info[j].max_unused_stack_bytes = task_status_array[i].usStackHighWaterMark * sizeof(StackType_t); last_tick_snapshot[j] = task_status_array[i].ulRunTimeCounter; } #else memset(task_profile_info, 0, sizeof(task_profile_info)); #endif /* configUSE_TRACE_FACILITY == 1 */ } #if defined configQUEUE_METRICS static int s_queue_index = 0; static nl_profile_queue_info_t *s_queue_info_ptr; static void nl_queue_info_cb(freertos_queue_metric_t *m, QueueHandle_t queue_handle) { // Ignore queues with size one, these are likely mutexes and semaphores, or // uninteresting queues whose high watermark isn't as interesting as deep message queues if(m->uxSize != 1) { nlASSERT(s_queue_index < NL_PROFILE_NUM_QUEUES); s_queue_info_ptr[s_queue_index].location = (uint32_t)m->pvBufAddr; s_queue_info_ptr[s_queue_index].size = (uint8_t)m->uxSize; s_queue_info_ptr[s_queue_index].high_watermark = (uint8_t)m->uxMaxMessagesWaiting; s_queue_index++; } } uint32_t nl_profile_interval_get_queue_info(nl_profile_queue_info_t queue_profile_info[NL_PROFILE_NUM_QUEUES]) { s_queue_info_ptr = queue_profile_info; s_queue_index = 0; vQueueGetMetrics(nl_queue_info_cb); return s_queue_index; } #endif
nestlabs/nlplatform
src/nlswtimer.c
/* * * Copyright (c) 2016-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file... * */ #include <nlplatform.h> #include <nlplatform/nlswtimer.h> #include <stdio.h> #include <nlerassert.h> #define DEBUG_TRACE 0 typedef struct nl_swtimer_entry_s { nl_swtimer_func_t *func; void *arg; uint32_t delay; /* unit depends on implementation */ struct nl_swtimer_entry_s *next; } nl_swtimer_entry_t; static nl_swtimer_entry_t *s_timer_list; _Static_assert(sizeof(nl_swtimer_entry_t) == sizeof(nl_swtimer_t), "sizeof(nl_swtimer_t) != sizeof(nl_swtimer_entry_t)"); #ifdef BUILD_FEATURE_SW_TIMER_USES_RTOS_TICK #include <FreeRTOS.h> #include <task.h> // flag to prevent sleep if a unit test wants to test accuracy // of times and sleep would mess that up volatile bool g_swtimer_prevent_sleep = false; /* Our own tick count. FreeRTOS doesn't increment it's tick * counter when the scheduler is suspended, which happens all * the time in FreeRTOS's idle task. The tick interrupt still * calls the tick hook function, but consecutive hook function * invocations might see the same value returned from * xTaskGetTickCount(). To keep time more accurately, we * have our own tick count, which always increments whenever * our hook function is called, and which we resync to the * FreeRTOS tick count after sleep because that's the only time * when it might jump by more than one tick. */ static TickType_t s_swtimer_tick_count; #define NS_PER_TICK (1000000000 /*nanoseconds/second*/ / configTICK_RATE_HZ) /* System time (time since boot) in nanoseconds. This time is * incremented when system tick is incremented. Unlike a tick * counter, this counter essentially does not wrap because it * would take hundreds of years. */ static uint64_t s_system_time_ns = 0; /* List of timers whose delays are processed once the current * tick count has overflowed and wrapped back to 0. */ static nl_swtimer_entry_t *s_timer_overflow_list; #if DEBUG_TRACE == 1 static void dump_swtimer_list(void) { nl_swtimer_entry_t *timer_p = s_timer_list; while (timer_p) { printf("\ttimer %p, delay = %u, func = %p\n", timer_p, timer_p->delay, timer_p->func); timer_p = timer_p->next; } timer_p = s_timer_overflow_list; printf("overflow list:\n"); while (timer_p) { printf("\ttimer %p, delay = %u, func = %p\n", timer_p, timer_p->delay, timer_p->func); timer_p = timer_p->next; } } #endif static bool timer_in_list_locked(const nl_swtimer_entry_t *timer_list, const nl_swtimer_entry_t *timer_p) { bool result = false; while (timer_list) { if (timer_list == timer_p) { result = true; break; } timer_list = timer_list->next; } return result; } static bool timer_is_active_locked(const nl_swtimer_entry_t *timer_p) { return (timer_in_list_locked(s_timer_list, timer_p) || timer_in_list_locked(s_timer_overflow_list, timer_p)); } bool nl_swtimer_is_active(const nl_swtimer_t *timer_arg) { bool result; const nl_swtimer_entry_t *timer_p = (const nl_swtimer_entry_t*)timer_arg; nlplatform_interrupt_disable(); result = timer_is_active_locked(timer_p); nlplatform_interrupt_enable(); return result; } bool nl_swtimer_pre_sleep(TickType_t *before_sleep_tick_count, uint32_t *xExpectedIdleTime) { bool retval = false; /* Since this is called from the FreeRTOS idle thread with interrupts * still enabled, have to enter a critical section to examine * the s_timer_list */ nlplatform_interrupt_disable(); #ifdef BUILD_FEATURE_UNIT_TEST if (g_swtimer_prevent_sleep) { /* in case unit-test set xTickCount for test reasons, * sync our counter with xTickCount */ s_swtimer_tick_count = xTaskGetTickCount(); s_system_time_ns = (uint64_t)s_swtimer_tick_count * NS_PER_TICK; goto done; } #endif if (s_timer_list) { if (s_timer_list->delay > s_swtimer_tick_count) { TickType_t delay_in_ticks = s_timer_list->delay - s_swtimer_tick_count; if (delay_in_ticks < *xExpectedIdleTime) { #if DEBUG_TRACE == 1 printf("[%u] %s: xExpectedIdleTime = %u, s_timer_list->delay = %u, delay_in_ticks = %u\n", s_swtimer_tick_count, __func__, *xExpectedIdleTime, s_timer_list->delay, delay_in_ticks); #endif *xExpectedIdleTime = delay_in_ticks; } } else { /* Skip sleep if our timer was supposed to have run but hasn't. * This can sometimes happen if two consecutive calls to * sleep occurred without even one tick interrupt firing. * If the idle loop is very efficient relative to the tick * period, this could happen. */ goto done; } } retval = true; done: *before_sleep_tick_count = xTaskGetTickCount(); /* our time can be a little different from FreeRTOS's tick count because * the latter doesn't advance when the scheduler is suspended but those * ticks are accounted for in uxPendedTicks counter and added to xTickCount * when the scheduler is resumed. To check for drift that we're not * accounting for, make sure we're not too far off. */ assert(s_swtimer_tick_count >= *before_sleep_tick_count); /* accuracy check, value is somewhat arbitrary. mostly concerned * about a bug causing long term drift between our count and FreeRTOS's. */ assert(s_swtimer_tick_count - *before_sleep_tick_count <= 3); nlplatform_interrupt_enable(); return retval; } void nl_swtimer_post_sleep(TickType_t before_sleep_tick_count) { TickType_t after_sleep_tick_count; nlplatform_interrupt_disable(); after_sleep_tick_count = xTaskGetTickCount(); /* add time slept. we compute time sleep by computing the difference * of the FreeRTOS tick count before and after sleep. We could have tried * to tie into the call to vTaskStepTick() instead but this keeps our * implementation more self-contained. The sleep should never span * the wrap point of the tick counter. */ assert(after_sleep_tick_count >= before_sleep_tick_count); TickType_t sleep_ticks = (after_sleep_tick_count - before_sleep_tick_count); s_swtimer_tick_count += sleep_ticks; s_system_time_ns += (uint64_t)sleep_ticks * NS_PER_TICK; nlplatform_interrupt_enable(); } /* * Initialize the fields of our private timer structure */ void nl_swtimer_init(nl_swtimer_t *timer_arg, nl_swtimer_func_t *func, void *arg) { nl_swtimer_entry_t *timer = (nl_swtimer_entry_t*)timer_arg; timer->func = func; timer->arg = arg; timer->next = NULL; } static void nl_swtimer_insert_locked(nl_swtimer_entry_t *timer, uint32_t delay_in_ticks) { const TickType_t current_tick_count = s_swtimer_tick_count; nl_swtimer_entry_t **timer_pp; nl_swtimer_entry_t *timer_p; assert(timer_is_active_locked(timer) == false); // If an instantaneous timeout is being requested, expire on the next tick // boundary if (delay_in_ticks == 0) { delay_in_ticks = 1; } timer->delay = current_tick_count + delay_in_ticks; /* since we always add 1 tick, the only time we're equal * is when we've overflowed and completely wrapped * around again. */ if (timer->delay > current_tick_count) { /* timer will be processed on the current timer list */ timer_pp = &s_timer_list; } else { /* timer will be processed when the tick count overflows */ timer_pp = &s_timer_overflow_list; } timer_p = *timer_pp; #if DEBUG_TRACE == 1 printf("\n\n[%u] %s: Starting timer %p, %u ticks\n", current_tick_count, __func__, timer, delay_in_ticks); printf("timer list before insert:\n"); dump_swtimer_list(); #endif while (timer_p) { if (timer->delay < timer_p->delay) { break; } timer_pp = &timer_p->next; timer_p = timer_p->next; } // timer_p is a pointer to the timer we're // inserting the new timer before. // timer_pp is a pointer to the pointer to // timer_p, which we adjust to point to the new // timer. *timer_pp = timer; timer->next = timer_p; #if DEBUG_TRACE == 1 printf("timer list after insert:\n"); dump_swtimer_list(); #endif } /* Add timer to our sorted timer list atomically. The delay field * in the timer struct stores the target tick count for when the * timer should run and not a delta of ticks from the current tick * count. This is needed for handling large jumps in ticks * that might happen coming out of sleep and for the situation * where the timer restarts itself from the timer function. * The list is sorted by delays to make the tick handler check for * expired timers faster, so it doesn't have to traverse the entire * list of timers at interrupt time. * * Have to use a critical section since our timer function runs at * interrupt time. * * Since our list is unbounded, this takes non-deterministic time, but * we don't expect a huge number of timers in our small devices. */ void nl_swtimer_start(nl_swtimer_t *timer_arg, uint32_t delay_ms) { nl_swtimer_entry_t *timer = (nl_swtimer_entry_t*)timer_arg; TickType_t delay_in_ticks = nl_time_ms_to_delay_time_native(delay_ms); assert(timer->func); nlplatform_interrupt_disable(); nl_swtimer_insert_locked(timer, delay_in_ticks); nlplatform_interrupt_enable(); } static bool remove_from_list_locked(nl_swtimer_entry_t **timer_pp, nl_swtimer_entry_t *timer) { bool result = false; while (*timer_pp) { if (*timer_pp == timer) { // Found the timer in the list. result = true; #if DEBUG_TRACE == 1 printf("Removing timer %p with delay %u, func %p\n", timer, timer->delay, timer->func); printf("timer list before removal:\n"); dump_swtimer_list(); #endif // Fixup the pointer to us to point // to our next *timer_pp = timer->next; #if DEBUG_TRACE == 1 printf("list after timer removal:\n"); dump_swtimer_list(); #endif break; } timer_pp = &((*timer_pp)->next); } return result; } bool nl_swtimer_cancel(nl_swtimer_t *timer_arg) { nl_swtimer_entry_t *timer = (nl_swtimer_entry_t*)timer_arg; bool result; nlplatform_interrupt_disable(); result = remove_from_list_locked(&s_timer_list, timer); if (!result) { result = remove_from_list_locked(&s_timer_overflow_list, timer); } nlplatform_interrupt_enable(); return result; } void nl_swtimer_rtos_tick_handler(void) { /* increment our tick count and check for wrap. */ const TickType_t last_tick_count = s_swtimer_tick_count++; /* compiler optimization, since this won't change in this function */ const TickType_t current_tick_count = s_swtimer_tick_count; s_system_time_ns += NS_PER_TICK; if (current_tick_count < last_tick_count) { /* Tick count has wrapped. All timers in the s_timer_list * can be run, and some timers in the s_timer_overflow_list * might be runnable too. To handle restarts and cancels * calls from timer functions, we merge both lists at this time, * setting the delay of all timers in s_timer_list to 0, * then adding all the timers from s_timer_overflow_list to * the end of s_timer_list. */ nl_swtimer_entry_t **timer_pp = &s_timer_list; nl_swtimer_entry_t *timer_p = *timer_pp; #if DEBUG_TRACE == 1 printf("Tick count overflowed, zeroing delay of s_timer_list timers and moving s_timer_overflow_list timers to end\n"); #endif while (timer_p) { timer_p->delay = 0; timer_pp = &timer_p->next; timer_p = timer_p->next; } *timer_pp = s_timer_overflow_list; s_timer_overflow_list = NULL; #if DEBUG_TRACE == 1 printf("timer list after merge:\n"); dump_swtimer_list(); #endif } while (s_timer_list) { if (current_tick_count >= s_timer_list->delay) { nl_swtimer_entry_t *timer_p = s_timer_list; uint32_t new_delay; /* Remove from timer list so it can restart itself if desired */ s_timer_list = timer_p->next; #if DEBUG_TRACE == 1 printf("[%u] Running timer %p, func = %p\n", current_tick_count, timer_p, timer_p->func); #endif new_delay = (timer_p->func)((nl_swtimer_t*)timer_p, timer_p->arg); if (new_delay) { /* Since this delay is aligned on the tick interrupt, * we don't want the extra tick like we do for * the normal start case */ TickType_t delay_in_ticks = nl_time_ms_to_delay_time_native(new_delay) - 1; nl_swtimer_insert_locked(timer_p, delay_in_ticks); } } else { break; } } } uint64_t nl_swtimer_get_time_ns(void) { uint64_t result; nlplatform_interrupt_disable(); result = s_system_time_ns; nlplatform_interrupt_enable(); return result; } #if defined(DEBUG) && defined(BUILD_FEATURE_UNIT_TEST) #include <nlertime.h> #define TIMER0_TICKS 25 #define TIMER1_TICKS 50 #define TIMER2_TICKS 100 #define TIMER3_TICKS 200 #define TIMER4_TICKS 500 #define NUM_TEST_TIMERS 5 static const uint32_t timer_delays[NUM_TEST_TIMERS] = { TIMER0_TICKS, TIMER1_TICKS, TIMER2_TICKS, TIMER3_TICKS, TIMER4_TICKS }; static nl_swtimer_t timers[NUM_TEST_TIMERS]; // checks if the list is ordered correctly for the 5 timers // we create in different order. If the removed_timer is // not NULL, then assume this timer was removed and don't // look for it. static void verify_list1(nl_swtimer_t *removed_timer) { nl_swtimer_entry_t *timer_p = s_timer_list; unsigned i; for (i = 0; i < NUM_TEST_TIMERS; i++) { if (removed_timer != &timers[i]) { assert(timer_p == (nl_swtimer_entry_t*)&timers[i]); assert(timer_p->delay == timer_delays[i]); timer_p = timer_p->next; } } assert(timer_p == NULL); } // checks if the list is ordered correctly for the 5 timers // we create with the same delay static void verify_list2(void) { nl_swtimer_entry_t *timer_p; // timer1 check timer_p = s_timer_list; assert(timer_p == (nl_swtimer_entry_t*)&timers[0]); assert(timer_p->delay == TIMER0_TICKS); // timer2 check timer_p = timer_p->next; assert(timer_p == (nl_swtimer_entry_t*)&timers[1]); assert(timer_p->delay == TIMER0_TICKS); // timer3 check timer_p = timer_p->next; assert(timer_p == (nl_swtimer_entry_t*)&timers[2]); assert(timer_p->delay == TIMER0_TICKS); // timer4 check timer_p = timer_p->next; assert(timer_p == (nl_swtimer_entry_t*)&timers[3]); assert(timer_p->delay == TIMER0_TICKS); // timer5 check timer_p = timer_p->next; assert(timer_p == (nl_swtimer_entry_t*)&timers[4]); assert(timer_p->delay == TIMER0_TICKS); assert(timer_p->next == NULL); } // Call this in main, before threading has started, to // do a sanity test of the list implementation void nl_swtimer_sanity_test(void); void nl_swtimer_sanity_test(void) { nluart_force_sync(CONSOLE_UART_ID); printf("\n\n%s: start\n", __func__); nlplatform_interrupt_disable(); // tests order of timer list after various combinations // of start/cancel. the function isn't actually // ever used since we do this test with interrupts // disabled, so we just pass a dummy ptr in order // not to trip the NULL assert. the actual runtime // testing is done in the unit test code. nl_swtimer_init(&timers[0], (nl_swtimer_func_t*)nl_swtimer_sanity_test, NULL); nl_swtimer_init(&timers[1], (nl_swtimer_func_t*)nl_swtimer_sanity_test, NULL); nl_swtimer_init(&timers[2], (nl_swtimer_func_t*)nl_swtimer_sanity_test, NULL); nl_swtimer_init(&timers[3], (nl_swtimer_func_t*)nl_swtimer_sanity_test, NULL); nl_swtimer_init(&timers[4], (nl_swtimer_func_t*)nl_swtimer_sanity_test, NULL); assert(s_timer_list == NULL); nl_swtimer_start(&timers[0], nl_time_native_to_time_ms(TIMER0_TICKS-1)); nl_swtimer_start(&timers[1], nl_time_native_to_time_ms(TIMER1_TICKS-1)); nl_swtimer_start(&timers[2], nl_time_native_to_time_ms(TIMER2_TICKS-1)); nl_swtimer_start(&timers[3], nl_time_native_to_time_ms(TIMER3_TICKS-1)); nl_swtimer_start(&timers[4], nl_time_native_to_time_ms(TIMER4_TICKS-1)); verify_list1(NULL); nl_swtimer_cancel(&timers[0]); nl_swtimer_cancel(&timers[1]); nl_swtimer_cancel(&timers[2]); nl_swtimer_cancel(&timers[3]); nl_swtimer_cancel(&timers[4]); assert(s_timer_list == NULL); nl_swtimer_start(&timers[1], nl_time_native_to_time_ms(TIMER1_TICKS-1)); nl_swtimer_start(&timers[0], nl_time_native_to_time_ms(TIMER0_TICKS-1)); nl_swtimer_start(&timers[2], nl_time_native_to_time_ms(TIMER2_TICKS-1)); nl_swtimer_start(&timers[3], nl_time_native_to_time_ms(TIMER3_TICKS-1)); nl_swtimer_start(&timers[4], nl_time_native_to_time_ms(TIMER4_TICKS-1)); verify_list1(NULL); nl_swtimer_cancel(&timers[0]); nl_swtimer_cancel(&timers[1]); nl_swtimer_cancel(&timers[2]); nl_swtimer_cancel(&timers[3]); nl_swtimer_cancel(&timers[4]); assert(s_timer_list == NULL); nl_swtimer_start(&timers[1], nl_time_native_to_time_ms(TIMER1_TICKS-1)); nl_swtimer_start(&timers[2], nl_time_native_to_time_ms(TIMER2_TICKS-1)); nl_swtimer_start(&timers[0], nl_time_native_to_time_ms(TIMER0_TICKS-1)); nl_swtimer_start(&timers[3], nl_time_native_to_time_ms(TIMER3_TICKS-1)); nl_swtimer_start(&timers[4], nl_time_native_to_time_ms(TIMER4_TICKS-1)); verify_list1(NULL); nl_swtimer_cancel(&timers[0]); nl_swtimer_cancel(&timers[1]); nl_swtimer_cancel(&timers[2]); nl_swtimer_cancel(&timers[3]); nl_swtimer_cancel(&timers[4]); assert(s_timer_list == NULL); nl_swtimer_start(&timers[1], nl_time_native_to_time_ms(TIMER1_TICKS-1)); nl_swtimer_start(&timers[2], nl_time_native_to_time_ms(TIMER2_TICKS-1)); nl_swtimer_start(&timers[3], nl_time_native_to_time_ms(TIMER3_TICKS-1)); nl_swtimer_start(&timers[0], nl_time_native_to_time_ms(TIMER0_TICKS-1)); nl_swtimer_start(&timers[4], nl_time_native_to_time_ms(TIMER4_TICKS-1)); verify_list1(NULL); nl_swtimer_cancel(&timers[0]); nl_swtimer_cancel(&timers[1]); nl_swtimer_cancel(&timers[2]); nl_swtimer_cancel(&timers[3]); nl_swtimer_cancel(&timers[4]); assert(s_timer_list == NULL); nl_swtimer_start(&timers[1], nl_time_native_to_time_ms(TIMER1_TICKS-1)); nl_swtimer_start(&timers[2], nl_time_native_to_time_ms(TIMER2_TICKS-1)); nl_swtimer_start(&timers[3], nl_time_native_to_time_ms(TIMER3_TICKS-1)); nl_swtimer_start(&timers[4], nl_time_native_to_time_ms(TIMER4_TICKS-1)); nl_swtimer_start(&timers[0], nl_time_native_to_time_ms(TIMER0_TICKS-1)); verify_list1(NULL); nl_swtimer_cancel(&timers[0]); nl_swtimer_cancel(&timers[1]); nl_swtimer_cancel(&timers[2]); nl_swtimer_cancel(&timers[3]); nl_swtimer_cancel(&timers[4]); assert(s_timer_list == NULL); nl_swtimer_start(&timers[4], nl_time_native_to_time_ms(TIMER4_TICKS-1)); nl_swtimer_start(&timers[3], nl_time_native_to_time_ms(TIMER3_TICKS-1)); nl_swtimer_start(&timers[2], nl_time_native_to_time_ms(TIMER2_TICKS-1)); nl_swtimer_start(&timers[1], nl_time_native_to_time_ms(TIMER1_TICKS-1)); nl_swtimer_start(&timers[0], nl_time_native_to_time_ms(TIMER0_TICKS-1)); verify_list1(NULL); nl_swtimer_cancel(&timers[0]); nl_swtimer_cancel(&timers[1]); nl_swtimer_cancel(&timers[2]); nl_swtimer_cancel(&timers[3]); nl_swtimer_cancel(&timers[4]); assert(s_timer_list == NULL); nl_swtimer_start(&timers[4], nl_time_native_to_time_ms(TIMER4_TICKS-1)); nl_swtimer_start(&timers[3], nl_time_native_to_time_ms(TIMER3_TICKS-1)); nl_swtimer_start(&timers[2], nl_time_native_to_time_ms(TIMER2_TICKS-1)); nl_swtimer_start(&timers[0], nl_time_native_to_time_ms(TIMER0_TICKS-1)); nl_swtimer_start(&timers[1], nl_time_native_to_time_ms(TIMER1_TICKS-1)); verify_list1(NULL); nl_swtimer_cancel(&timers[0]); nl_swtimer_cancel(&timers[1]); nl_swtimer_cancel(&timers[2]); nl_swtimer_cancel(&timers[3]); nl_swtimer_cancel(&timers[4]); assert(s_timer_list == NULL); nl_swtimer_start(&timers[4], nl_time_native_to_time_ms(TIMER4_TICKS-1)); nl_swtimer_start(&timers[3], nl_time_native_to_time_ms(TIMER3_TICKS-1)); nl_swtimer_start(&timers[0], nl_time_native_to_time_ms(TIMER0_TICKS-1)); nl_swtimer_start(&timers[2], nl_time_native_to_time_ms(TIMER2_TICKS-1)); nl_swtimer_start(&timers[1], nl_time_native_to_time_ms(TIMER1_TICKS-1)); verify_list1(NULL); nl_swtimer_cancel(&timers[0]); nl_swtimer_cancel(&timers[1]); nl_swtimer_cancel(&timers[2]); nl_swtimer_cancel(&timers[3]); nl_swtimer_cancel(&timers[4]); assert(s_timer_list == NULL); nl_swtimer_start(&timers[4], nl_time_native_to_time_ms(TIMER4_TICKS-1)); nl_swtimer_start(&timers[0], nl_time_native_to_time_ms(TIMER0_TICKS-1)); nl_swtimer_start(&timers[3], nl_time_native_to_time_ms(TIMER3_TICKS-1)); nl_swtimer_start(&timers[2], nl_time_native_to_time_ms(TIMER2_TICKS-1)); nl_swtimer_start(&timers[1], nl_time_native_to_time_ms(TIMER1_TICKS-1)); verify_list1(NULL); nl_swtimer_cancel(&timers[0]); nl_swtimer_cancel(&timers[1]); nl_swtimer_cancel(&timers[2]); nl_swtimer_cancel(&timers[3]); nl_swtimer_cancel(&timers[4]); assert(s_timer_list == NULL); nl_swtimer_start(&timers[0], nl_time_native_to_time_ms(TIMER0_TICKS-1)); nl_swtimer_start(&timers[4], nl_time_native_to_time_ms(TIMER4_TICKS-1)); nl_swtimer_start(&timers[3], nl_time_native_to_time_ms(TIMER3_TICKS-1)); nl_swtimer_start(&timers[2], nl_time_native_to_time_ms(TIMER2_TICKS-1)); nl_swtimer_start(&timers[1], nl_time_native_to_time_ms(TIMER1_TICKS-1)); verify_list1(NULL); nl_swtimer_cancel(&timers[0]); nl_swtimer_cancel(&timers[1]); nl_swtimer_cancel(&timers[2]); nl_swtimer_cancel(&timers[3]); nl_swtimer_cancel(&timers[4]); assert(s_timer_list == NULL); nl_swtimer_start(&timers[0], nl_time_native_to_time_ms(TIMER0_TICKS-1)); nl_swtimer_start(&timers[1], nl_time_native_to_time_ms(TIMER0_TICKS-1)); nl_swtimer_start(&timers[2], nl_time_native_to_time_ms(TIMER0_TICKS-1)); nl_swtimer_start(&timers[3], nl_time_native_to_time_ms(TIMER0_TICKS-1)); nl_swtimer_start(&timers[4], nl_time_native_to_time_ms(TIMER0_TICKS-1)); verify_list2(); nl_swtimer_cancel(&timers[0]); nl_swtimer_cancel(&timers[1]); nl_swtimer_cancel(&timers[2]); nl_swtimer_cancel(&timers[3]); nl_swtimer_cancel(&timers[4]); assert(s_timer_list == NULL); // test list validity with removal from different places in list nl_swtimer_start(&timers[0], nl_time_native_to_time_ms(TIMER0_TICKS-1)); nl_swtimer_start(&timers[1], nl_time_native_to_time_ms(TIMER1_TICKS-1)); nl_swtimer_start(&timers[2], nl_time_native_to_time_ms(TIMER2_TICKS-1)); nl_swtimer_start(&timers[3], nl_time_native_to_time_ms(TIMER3_TICKS-1)); nl_swtimer_start(&timers[4], nl_time_native_to_time_ms(TIMER4_TICKS-1)); nl_swtimer_cancel(&timers[0]); verify_list1(&timers[0]); nl_swtimer_cancel(&timers[0]); nl_swtimer_cancel(&timers[1]); nl_swtimer_cancel(&timers[2]); nl_swtimer_cancel(&timers[3]); nl_swtimer_cancel(&timers[4]); assert(s_timer_list == NULL); nl_swtimer_start(&timers[0], nl_time_native_to_time_ms(TIMER0_TICKS-1)); nl_swtimer_start(&timers[1], nl_time_native_to_time_ms(TIMER1_TICKS-1)); nl_swtimer_start(&timers[2], nl_time_native_to_time_ms(TIMER2_TICKS-1)); nl_swtimer_start(&timers[3], nl_time_native_to_time_ms(TIMER3_TICKS-1)); nl_swtimer_start(&timers[4], nl_time_native_to_time_ms(TIMER4_TICKS-1)); nl_swtimer_cancel(&timers[1]); verify_list1(&timers[1]); nl_swtimer_cancel(&timers[0]); nl_swtimer_cancel(&timers[1]); nl_swtimer_cancel(&timers[2]); nl_swtimer_cancel(&timers[3]); nl_swtimer_cancel(&timers[4]); assert(s_timer_list == NULL); nl_swtimer_start(&timers[0], nl_time_native_to_time_ms(TIMER0_TICKS-1)); nl_swtimer_start(&timers[1], nl_time_native_to_time_ms(TIMER1_TICKS-1)); nl_swtimer_start(&timers[2], nl_time_native_to_time_ms(TIMER2_TICKS-1)); nl_swtimer_start(&timers[3], nl_time_native_to_time_ms(TIMER3_TICKS-1)); nl_swtimer_start(&timers[4], nl_time_native_to_time_ms(TIMER4_TICKS-1)); nl_swtimer_cancel(&timers[2]); verify_list1(&timers[2]); nl_swtimer_cancel(&timers[0]); nl_swtimer_cancel(&timers[1]); nl_swtimer_cancel(&timers[2]); nl_swtimer_cancel(&timers[3]); nl_swtimer_cancel(&timers[4]); assert(s_timer_list == NULL); nl_swtimer_start(&timers[0], nl_time_native_to_time_ms(TIMER0_TICKS-1)); nl_swtimer_start(&timers[1], nl_time_native_to_time_ms(TIMER1_TICKS-1)); nl_swtimer_start(&timers[2], nl_time_native_to_time_ms(TIMER2_TICKS-1)); nl_swtimer_start(&timers[3], nl_time_native_to_time_ms(TIMER3_TICKS-1)); nl_swtimer_start(&timers[4], nl_time_native_to_time_ms(TIMER4_TICKS-1)); nl_swtimer_cancel(&timers[3]); verify_list1(&timers[3]); nl_swtimer_cancel(&timers[0]); nl_swtimer_cancel(&timers[1]); nl_swtimer_cancel(&timers[2]); nl_swtimer_cancel(&timers[3]); nl_swtimer_cancel(&timers[4]); assert(s_timer_list == NULL); nl_swtimer_start(&timers[0], nl_time_native_to_time_ms(TIMER0_TICKS-1)); nl_swtimer_start(&timers[1], nl_time_native_to_time_ms(TIMER1_TICKS-1)); nl_swtimer_start(&timers[2], nl_time_native_to_time_ms(TIMER2_TICKS-1)); nl_swtimer_start(&timers[3], nl_time_native_to_time_ms(TIMER3_TICKS-1)); nl_swtimer_start(&timers[4], nl_time_native_to_time_ms(TIMER4_TICKS-1)); nl_swtimer_cancel(&timers[4]); verify_list1(&timers[4]); nl_swtimer_cancel(&timers[0]); nl_swtimer_cancel(&timers[1]); nl_swtimer_cancel(&timers[2]); nl_swtimer_cancel(&timers[3]); nl_swtimer_cancel(&timers[4]); assert(s_timer_list == NULL); printf("%s: end: all tests passed\n\n", __func__); nlplatform_interrupt_enable(); } #endif // DEBUG && BUILD_FEATURE_UNIT_TEST #endif // BUILD_FEATURE_SW_TIMER_USES_RTOS_TICK
nestlabs/nlplatform
include/spi_flash/mx25u1635.h
<reponame>nestlabs/nlplatform /* * * Copyright (c) 2015-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file contains macro defines of the MX25U1635FBAI SPI flash chip. * */ #ifndef __MX25U1635_H_INCLUDED__ #define __MX25U1635_H_INCLUDED__ /* ************************************************************************* * Configuration specific to nlflash-spi.cpp driver * *************************************************************************/ /* Uncomment the following to allow partial page buffer being used when Write() is called. Flush() is used to write everything in the page buffer out to the external flash. */ //#define FLASH_SPI_USE_PARTIAL_PAGE_BUFFER /* Try for 20 msec to read chip ID. Reading a valid chip ID indicates the flash * is ready for interaction. Micron says the flash should complete all internal * processes and return a valid chip ID within 17 msec. */ #define FLASH_SPI_MAX_CHIP_ID_CHECK_COUNT 20 /* Special configurations */ #define FLASH_SPI_REQUEST_SPI_CONTROLLER_ON_REQUEST 1 #define FLASH_SPI_TRISTATE_CS_RST_DURING_POWER_UP 1 /* spi bus, spi freq, and chip select pin should be defined in nlplatform_product_config.h */ #define MX25U1635_MAX_SPI_FREQ_HZ (104000000) /* 104MHz */ #define FLASH_SPI_MODE SPI_MODE_0 /* Size parameters */ #define FLASH_SPI_SIZE (0x200000) /* 2,097,152 Bytes or 2MB */ #define FLASH_SPI_ERASE_SIZE (4096) /* 4KB (smallest erasable unit) */ #define FLASH_SPI_FAST_ERASE_SIZE (0x10000) /* 65,536 Bytes or 64KB */ #define FLASH_SPI_WRITE_SIZE (256) /* writable unit */ #define FLASH_SPI_READ_ID_SIZE (3) #define FLASH_SPI_FAST_READ_DUMMY_CYCLES (1) /* default number of dummy cycles is 1 byte when using FAST_READ */ #define FLASH_SPI_READ_DUMMY_CYCLES (0) /* default number of dummy cycles is 0 byte when using regular READ */ #define FLASH_SPI_FAST_READ_FREQ_HZ (104000000) /* 104MHz */ #define FLASH_SPI_READ_FREQ_HZ (50000000) /* 50MHz */ /* MX25U1635FBAI Status Register and masks */ #define CMD_RDSR (0x05) /* to read out the status reg */ #define CMD_WRSR (0x01) /* to write new val to the status reg */ #define M_STAT_SRWD (1<<7) /* status reg write disable */ #define M_STAT_QE (1<<6) /* Quad mode enable */ #define M_STAT_BP3 (1<<5) /* level of protected block */ #define M_STAT_BP2 (1<<4) #define M_STAT_BP1 (1<<3) #define M_STAT_BP0 (1<<2) #define M_STAT_WEL (1<<1) /* write enable latch */ #define M_STAT_BUSY_BIT (1<<0) /* busy bit mask */ #define M_STAT_READY_VALUE (0<<0) /* value of busy bit to indicate device is ready */ #define M_STAT_BUSY_VALUE (1<<0) /* value of busy bit to indicate device is busy */ /* Register/Setting Commands */ #define CMD_WREN (0x06) /* write enable */ #define CMD_WRDI (0x04) /* write disable */ #define CMD_WPSEL (0x68) /* to enter and enable individual block protect mode */ #define CMD_DP (0xB9) /* enter deep power down mode */ #define CMD_RDP (0xAB) /* release from deep power down mode */ #define CMD_SBL (0xC0) /* to set burst length */ /* Read/Write Array Commands */ #define CMD_READ (0x03) /* max speed 50 MHz */ #define CMD_FAST_READ (0x0B) /* max speed 104 MHz */ #define CMD_PP (0x02) /* to program the selected page */ #define CMD_SSE (0x20) /* subsector erase: "4K subsector" is called "sector" on MX25 */ #define CMD_SE (0xD8) /* sector erase: "64K sector" is called "block" on MX25 */ #define CMD_BE (0xC7) /* bulk erase: "bulk erase" is called "chip erase" on MX25 */ /* Read device ID */ #define CMD_RDID (0x9F) /* read device ID */ /* MX25U1635FBAI Chip IDs */ #define FLASH_SPI_MANUFACTORY_ID (0xC2) #define FLASH_SPI_MEMORY_TYPE_ID (0x25) #define FLASH_SPI_MEMORY_DENSITY_ID (0x35) /* delay time for different operations. DELAY_MSEC * DELAY_LOOP_COUNT == total delay time */ #define PP_DELAY_MSEC (1) #define PP_DELAY_LOOP_COUNT (2) /* PageProgram 256B, Typ. 0.5ms, Max. 1.5ms */ #define BE_DELAY_MSEC (500) #define BE_DELAY_LOOP_COUNT (50) /* ChipErase Typ. 10s, Max. 20s */ #define SE_DELAY_MSEC (50) #define SE_DELAY_LOOP_COUNT (50) /* BlockErase64K Typ. 350ms, Max. 2000ms */ #define SSE_DELAY_MSEC (10) #define SSE_DELAY_LOOP_COUNT (25) /* SectorErase4K Typ. 35ms, Max. 200ms */ /* I've observed the following on a development board: * -The power rail can take 250uS or more to rise * -Falling takes about 75uS * -Device stability after power-on requires a minimum of 2mS including the * 250uS rise time. * * The MX25's VCC slew rate can safely range from 20uS/V to 500mS/V, which * our timings fall safely within. We're padding the power-on delay to the mS * level to ensure the flash is completely stable before proceeding. Tests have * shown that delays less than 2mS will cause the flash to behave erratically * (ignore commands, etc). * * Also notable is that the MX25 requires its power supply to be LOW for a * minimum of 300uS when switching the device ON->OFF->ON. Additional safety time * after the power rail has risen in order to allow the chip time to reset is * also good manners. */ #define FLASH_SPI_POWER_UP_MAX_DELAY_MSEC (2) #define FLASH_SPI_POWER_DOWN_MAX_DELAY_USEC (425) #endif /* __MX25U1635_H_INCLUDED__ */
nestlabs/nlplatform
include/nlspi_ipc.h
/* * * Copyright (c) 2017-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file the API for the SPI IPC subsystem. */ #ifndef __NLSPI_IPC_H_INCLUDED__ #define __NLSPI_IPC_H_INCLUDED__ #include <stdbool.h> #ifndef NL_NO_RTOS #include <FreeRTOS.h> #endif #include <nlplatform/nlspi.h> #ifdef __cplusplus extern "C" { #endif /* struct nlspi_ipc_device_t - provides SPI slave device, GPIOs, and handlers * to be used in nlspi_ipc.c. Since it's expected that there will only be one * such device, nlspi_ipc.c, if built, expects the global g_spi_ipc_device to * be defined. * * @spi_slave: SPI slave device to communicate with. * @srdy_gpio: "slave ready" GPIO pin number. * @mrdy_gpio: "master ready" or chip-select GPIO pin number. * @reset_gpio: GPIO pin number which will reset slave. * @srdy_timeout_ms: Milliseconds to wait before giving up on SRDY signal. * @rx_pending_handler: Called when slave requests a transfer. Client should * call nlspi_ipc_work in thread context. * @rx_data_handler: Called to pass a received message to client. * @rx_corrupt_handler: Called to notify client when a received message is * corrupted (CRC). * @srdy_timeout_handler: Called to notify client when SRDY signal has been * unresponsive for srdy_timeout_ms. Only on RTOS variant. * @connected: Determine whether slave is connected. */ typedef struct nlspi_ipc_device_s { const nlspi_slave_t *spi_slave; uint8_t srdy_gpio; uint8_t mrdy_gpio; uint32_t srdy_timeout_ms; int (*rx_pending_handler)(void); void (*rx_data_handler)(uint8_t opcode, uint8_t data_len, const uint8_t *data); void (*rx_corrupt_handler)(uint8_t opcode, uint8_t data_len, const uint8_t *data); void (*srdy_timeout_handler)(void); bool (*connected)(void); } nlspi_ipc_device_t; extern const nlspi_ipc_device_t g_spi_ipc_device; /* Since some code may need to allocate static max receive buffers and we want * to keep those as small as possible, we set different max packet lengths * depending on the direction of the IPC. */ #ifndef MAX_IPC_DATA_LEN_FROM_SLAVE #define MAX_IPC_DATA_LEN_FROM_SLAVE 244 #endif #ifndef MAX_IPC_DATA_LEN_FROM_MASTER #define MAX_IPC_DATA_LEN_FROM_MASTER 70 #endif void nlspi_ipc_init(void); /* Send a packet to the slave. */ #define IPC_RESULT_DONE 0 #define IPC_RESULT_BAD_ARGS -1 #define IPC_RESULT_RX_BUF_TOO_SMALL -2 #define IPC_RESULT_NO_MSG -3 #define IPC_RESULT_NOT_INITIALIZED -4 #define IPC_RESULT_NO_SLAVE -5 #define IPC_RESULT_SRDY_TIMEOUT -6 int nlspi_ipc_send(uint8_t opcode, uint8_t data_len, const uint8_t *data); #ifndef NL_NO_RTOS /* To be called in thread context by client after rx_pending_handler is called * to process incoming packets from slave. */ void nlspi_ipc_work(void); #ifdef PRODUCT_IPC_OPCODE_ENABLE_ACK_MODE void nlspi_ipc_enable_ack_mode(void); #endif // PRODUCT_IPC_OPCODE_ENABLE_ACK_MODE #endif // NL_NO_RTOS #ifdef __cplusplus } #endif #endif //__NLSPI_IPC_H_INCLUDED__
nestlabs/nlplatform
include/arch/nlplatform_arm_cm3.h
/* * * Copyright (c) 2015-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file defines API for cortex M3 specific */ #ifndef __NLPLATFORM_ARCH_CM3_H_INCLUDED__ #define __NLPLATFORM_ARCH_CM3_H_INCLUDED__ #include <stdbool.h> #include <assert.h> #ifdef __cplusplus extern "C" { #endif /* This file is normally included by a nlplatform_soc.h file specific * to a processor. That header file should set USE_INLINE_FUNCTIONS * to 0 or 1 before including this header. Inline functions * might be faster but take more code space. */ #ifndef USE_INLINE_FUNCTIONS #define USE_INLINE_FUNCTIONS 1 #endif static inline bool nlplatform_in_interrupt(void) { uint32_t __regIPSR; __asm__ volatile ("MRS %0, ipsr" : "=r" (__regIPSR) ); return ((__regIPSR) ? true : false); } #if USE_INLINE_FUNCTIONS == 1 extern uint8_t int_lock_count; static inline void nlplatform_interrupt_disable(void) { #ifdef PRODUCT_INTERRUPT_DISABLE_BASE_PRIORITY_VALUE __set_BASEPRI(PRODUCT_INTERRUPT_DISABLE_BASE_PRIORITY_VALUE); #else __asm__ volatile ("cpsid i"); #endif int_lock_count++; } static inline void nlplatform_interrupt_enable(void) { assert(int_lock_count > 0); int_lock_count--; if (int_lock_count == 0) { #ifdef PRODUCT_INTERRUPT_DISABLE_BASE_PRIORITY_VALUE __set_BASEPRI(0); #else __asm__ volatile ("cpsie i"); #endif } } #else /* USE_INLINE_FUNCTIONS */ void nlplatform_interrupt_disable(void); void nlplatform_interrupt_enable(void); /* When USE_INLINE_FUNCTIONS == 0, the platform.c for the soc * can include this file and set NLPLATFORM_INTERRUPT_FUNCTIONS * to get the actual code. */ #ifdef NLPLATFORM_INTERRUPT_FUNCTIONS static uint8_t int_lock_count; #ifdef PRODUCT_INTERRUPT_DISABLE_BASE_PRIORITY_VALUE /* Functions needed by FreeRTOS. Use linker script to replace: * ulPortSetInterruptMask = nlplatform_set_interrupt_mask; * vPortClearInterruptMask = nlplatform_clear_interrupt_mask; * vPortEnterCritical = nlplatform_interrupt_disable; * vPortExitCritical = nlplatform_interrupt_enable; * so that there is only one int_lock_count used and one * priority mask for atomic priority. */ uint32_t nlplatform_set_interrupt_mask(void); void nlplatform_clear_interrupt_mask(uint32_t basepri_value); uint32_t nlplatform_set_interrupt_mask(void) { uint32_t old_base_pri = __get_BASEPRI(); __set_BASEPRI(PRODUCT_INTERRUPT_DISABLE_BASE_PRIORITY_VALUE); return old_base_pri; } void nlplatform_clear_interrupt_mask(uint32_t base_pri_value) { __set_BASEPRI(base_pri_value); } #endif void nlplatform_interrupt_disable(void) { // If PRODUCT_INTERRUPT_DISABLE_BASE_PRIORITY_VALUE is defined, // set BASEPRI to that value to disable interrupts via masking // instead of using PRIMASK. This allows interrupts with higher // priority to not be masked off. #ifdef PRODUCT_INTERRUPT_DISABLE_BASE_PRIORITY_VALUE __set_BASEPRI(PRODUCT_INTERRUPT_DISABLE_BASE_PRIORITY_VALUE); #else __asm__ volatile ("cpsid i"); #endif int_lock_count++; } void nlplatform_interrupt_enable(void) { assert(int_lock_count > 0); int_lock_count--; if (int_lock_count == 0) { #ifdef PRODUCT_INTERRUPT_DISABLE_BASE_PRIORITY_VALUE __set_BASEPRI(0); #else __asm__ volatile ("cpsie i"); #endif } } #endif /* NLPLATFORM_INTERRUPT_FUNCTIONS */ #endif /* USE_INLINE_FUNCTIONS */ /* This function must be inlined. */ static inline uint32_t nlplatform_get_lr(void) { register uint32_t result; __asm volatile ("mov %0, lr\n" : "=r" (result) ); return result; } /* This function must be inlined. */ static inline uint32_t nlplatform_get_pc(void) { register uint32_t result; __asm volatile ("mov %0, pc\n" : "=r" (result) ); return result; } /* This function must be inlined. */ static inline uint32_t nlplatform_get_sp(void) { register uint32_t result; __asm volatile ("mov %0, sp\n" : "=r" (result) ); return result; } /* This function must be inlined. */ static inline uint32_t nlplatform_get_psp(void) { register uint32_t result; __asm volatile ("mrs %0, psp\n" : "=r" (result)); return result; } #ifdef __cplusplus } #endif #endif /* __NLPLATFORM_ARCH_CM3_H_INCLUDED__ */
nestlabs/nlplatform
include/nlfault.h
/* * * Copyright (c) 2015-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file defines the structures saved to RAM on a hard fault. * It also declares the API for handling crashes (used as * fault vectors handlers or callable from other ISRs). */ #ifndef __NLFAULT_H_INCLUDED__ #define __NLFAULT_H_INCLUDED__ #include <nlplatform.h> #include <stdint.h> #include <assert.h> #ifdef __cplusplus extern "C" { #endif // Exception stack layout per // http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0552a/Babefdjc.html typedef struct { uint32_t r0; uint32_t r1; uint32_t r2; uint32_t r3; uint32_t r12; uint32_t lr; uint32_t pc; uint32_t psr; uint32_t stack[0]; /* &stack[0] is the original stack address if psr bit[9] is 0 * &stack[1] is the original stack address if psr bit[9] is 1 */ } ExceptionStackFrame_t; /* Can be used to hook into fault preservation framework when we assert */ void nl_platform_assert_delegate(const char* file, unsigned line); /* Fault vector handlers */ void nlfault_hard_fault_handler_c(void); void nlfault_usage_fault_handler_c(void); void nlfault_pre_watchdog_handler_c(void); void nlfault_debug_monitor_handler_c(void); /* Function to dump callstack to console */ void nlfault_dump_callstack(void); #ifdef BUILD_FEATURE_BREADCRUMBS /* Function to dump preserved backtrace to breadcrumbs on bootup */ void nltransfer_fault_to_breadcrumbs(const uint32_t *backtrace, size_t num_backtrace_entries, const char * current_task_name, bool dump_all_tasks); #endif /* Function to dump SOC-specific context information * Weak symbol, must be defined in nlplatform_soc repository */ void nlplatform_soc_dump_context(void); /* Function to dump product-specific context information * Weak symbol, must be defined in product repository */ void nlproduct_dump_context(void); #ifdef __cplusplus } #endif #endif /* __NLFAULT_H_INCLUDED__ */
nestlabs/nlplatform
test/nlswtimer-test.c
/* * * Copyright (c) 2016-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file implements a unit test suite, * testing nl_swtimer functions * */ // This is for unit tests only. We can't simulate this unit test #ifdef BUILD_FEATURE_UNIT_TEST #ifdef BUILD_FEATURE_SW_TIMER_USES_RTOS_TICK #include <nlmacros.h> #include <nlplatform.h> #include <nlplatform/nlswtimer.h> #include <nlplatform/nlwatchdog.h> #include "nltest.h" #include <nlplatform/nlswtimer-test.h> #include <nlertask.h> #include <FreeRTOS.h> #include <task.h> #include <semphr.h> #include <stdlib.h> extern bool g_swtimer_prevent_sleep; static bool s_test_with_tick_count_near_wrap = false; typedef struct { nlTestSuite *test_suite; uint32_t num_repeats; // number of times timer function should restart itself uint32_t count; // count of times the timer function was invoked uint32_t repeat_delay; // delay for the timer function restart TickType_t expectedRunTimeMin; TickType_t expectedRunTimeMax; } timer_test_info_t; typedef struct timer_test_info2_s { nlTestSuite *test_suite; uint32_t count; // count of times the timer function was invoked TickType_t expectedRunTimeMin; TickType_t expectedRunTimeMax; uint32_t num_timers; // number of timers in the list nl_swtimer_t **timers; struct timer_test_info2_s **timer_infos; uint32_t *timer_delays; TaskHandle_t notifyTaskHandle; } timer_test_info2_t; static TaskHandle_t sTaskHandle; static bool s_test_with_tick_count_near_wrap; #define TIMER_TEST_DELAY_1_MS 1 #define TIMER_TEST_DELAY_10_MS 10 #define TIMER_TEST_DELAY_50_MS 50 #define TIMER_TEST_DELAY_100_MS 100 #define TIMER_TEST_DELAY_200_MS 200 #define TIMER_TEST_DELAY_500_MS 500 #define TIMER_TEST_DELAY_1000_MS 1000 #define TIMER_TEST_DELAY_2000_MS 2000 #define TIMER_TEST_DELAY_4000_MS 4000 #define TIMER_TEST_DELAY_5000_MS 5000 #define TIMER_TEST_DELAY_10000_MS 10000 // timer functions should be invoked at the expected time or at most one or two // ticks later (never early). late is due to delta added by the implementation // (1 tick usually) to guarantee we're not early in case a tick interrupt was // just about to fire, and 1 more in case there was delay associated with the // time we recorded the expected time and another tick arriving, or other added latency. #define TIMING_ERROR_TOLERANCE_TICKS 2 // when sleep is enabled, there's a lot more latency/inaccuracy involved with coming // out of sleep. we give a higher tolerance, but this might vary by implementation. #define TIMING_ERROR_TOLERANCE_WITH_SLEEP_TICKS 10 static uint32_t should_not_run_func(nl_swtimer_t *timer, void *arg) { timer_test_info_t *test_info = (timer_test_info_t*)arg; NL_TEST_ASSERT(test_info->test_suite, 1 == 0); return 0; } static uint32_t one_shot_timer_test(nl_swtimer_t *timer, void *arg) { BaseType_t yield = pdFALSE; timer_test_info_t *test_info = (timer_test_info_t*)arg; TickType_t current_tick_count = xTaskGetTickCount(); test_info->count++; // ticks later (never early). late is due to delta added // by the implementation (1 tick usually) to guarantee // we're not early, and 1 more in case there was delay // associated with the time we recorded the expected time // and another tick arriving, or other added latency. if ((current_tick_count < test_info->expectedRunTimeMin) || (current_tick_count > test_info->expectedRunTimeMax)) { printf("%s: failure: current_tick_count = %u, expectedRunTimeMin = %u, expectedRunTimeMax = %u\n", __func__, current_tick_count, test_info->expectedRunTimeMin, test_info->expectedRunTimeMax); } NL_TEST_ASSERT(test_info->test_suite, (current_tick_count >= test_info->expectedRunTimeMin) && (current_tick_count <= test_info->expectedRunTimeMax)); vTaskNotifyGiveFromISR(sTaskHandle, &yield); portEND_SWITCHING_ISR(yield); return 0; } static uint32_t repeat_timer_test(nl_swtimer_t *timer, void *arg) { timer_test_info_t *test_info = (timer_test_info_t*)arg; TickType_t current_tick_count = xTaskGetTickCount(); uint32_t repeat_delay_ms; test_info->count++; NL_TEST_ASSERT(test_info->test_suite, (current_tick_count >= test_info->expectedRunTimeMin) && (current_tick_count <= test_info->expectedRunTimeMax)); if (test_info->count <= test_info->num_repeats) { test_info->expectedRunTimeMin = current_tick_count + nl_time_ms_to_delay_time_native(test_info->repeat_delay) - 1; test_info->expectedRunTimeMax = test_info->expectedRunTimeMin + TIMING_ERROR_TOLERANCE_TICKS; repeat_delay_ms = test_info->repeat_delay; } else { BaseType_t yield = pdFALSE; vTaskNotifyGiveFromISR(sTaskHandle, &yield); portEND_SWITCHING_ISR(yield); repeat_delay_ms = 0; } return repeat_delay_ms; } static uint32_t cancel_timer_test(nl_swtimer_t *timer, void *arg) { timer_test_info_t *test_info = (timer_test_info_t*)arg; TickType_t current_tick_count = xTaskGetTickCount(); nl_swtimer_t *timer_to_cancel = (nl_swtimer_t*)test_info->num_repeats; bool cancel_result; test_info->count++; NL_TEST_ASSERT(test_info->test_suite, (current_tick_count >= test_info->expectedRunTimeMin) && (current_tick_count <= test_info->expectedRunTimeMax)); cancel_result = nl_swtimer_cancel(timer_to_cancel); NL_TEST_ASSERT(test_info->test_suite, cancel_result == true); return 0; } // adjust ticks so that the count is close to wrap static void AdjustTickCount(uint32_t ticks_before_wrap) { TickType_t ticks_to_jump; bool old_prevent_value = g_swtimer_prevent_sleep; TickType_t before_sleep_tick_count; uint32_t ticks_to_sleep = 0; // delay 1 tick to make sure xNextTaskUnblockTime is cleared in FreeRTOS vTaskDelay(1); ticks_to_jump = 0 - ticks_before_wrap - xTaskGetTickCount() - 1; vTaskStepTick(ticks_to_jump); // call function to force nlswtimer to sync it's internal tick counter // to match FreeRTOS's g_swtimer_prevent_sleep = true; nl_swtimer_pre_sleep(&before_sleep_tick_count, &ticks_to_sleep); g_swtimer_prevent_sleep = old_prevent_value; // wait for 1 tick for FreeRTOS to settle after the big jump vTaskDelay(1); } static void Test_one_shot(nlTestSuite *inSuite, void *inContext) { BaseType_t wait_result; timer_test_info_t test_info1; nl_swtimer_t timer1; TickType_t delay_ticks; if (s_test_with_tick_count_near_wrap) { AdjustTickCount(nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_50_MS)); } // test a simple one shot timer printf("%s: start\n", __func__); memset(&test_info1, 0, sizeof(test_info1)); ulTaskNotifyTake(pdTRUE, 0); // clear any old notifications nl_swtimer_init(&timer1, one_shot_timer_test, &test_info1); delay_ticks = nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_100_MS); test_info1.test_suite = inSuite; test_info1.expectedRunTimeMin = xTaskGetTickCount() + delay_ticks; test_info1.expectedRunTimeMax = test_info1.expectedRunTimeMin + TIMING_ERROR_TOLERANCE_TICKS; nl_swtimer_start(&timer1, TIMER_TEST_DELAY_100_MS); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer1)); wait_result = ulTaskNotifyTake(pdTRUE, delay_ticks + TIMING_ERROR_TOLERANCE_TICKS); NL_TEST_ASSERT(inSuite, wait_result != 0); NL_TEST_ASSERT(inSuite, test_info1.count == test_info1.num_repeats + 1); // cleanup just in case of failure before we run next test, else // our stack timer structure will corrupt the nl_swtimer implementation (void)nl_swtimer_cancel(&timer1); } static void Test_single_repeat(nlTestSuite *inSuite, void *inContext) { BaseType_t wait_result; timer_test_info_t test_info1; nl_swtimer_t timer1; TickType_t delay_ticks; if (s_test_with_tick_count_near_wrap) { AdjustTickCount(nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_50_MS)); } // test a timer that restarts itself once from within it's function printf("%s: start\n", __func__); memset(&test_info1, 0, sizeof(test_info1)); ulTaskNotifyTake(pdTRUE, 0); // clear any old notifications delay_ticks = nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_100_MS); nl_swtimer_init(&timer1, repeat_timer_test, &test_info1); test_info1.test_suite = inSuite; test_info1.num_repeats = 1; test_info1.repeat_delay = TIMER_TEST_DELAY_100_MS; test_info1.expectedRunTimeMin = xTaskGetTickCount() + delay_ticks; test_info1.expectedRunTimeMax = test_info1.expectedRunTimeMin + TIMING_ERROR_TOLERANCE_TICKS; nl_swtimer_start(&timer1, TIMER_TEST_DELAY_100_MS); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer1)); wait_result = ulTaskNotifyTake(pdTRUE, (delay_ticks + TIMING_ERROR_TOLERANCE_TICKS)*2); NL_TEST_ASSERT(inSuite, wait_result != 0); NL_TEST_ASSERT(inSuite, test_info1.count == test_info1.num_repeats + 1); // cleanup just in case of failure before we run next test, else // our stack timer structure will corrupt the nl_swtimer implementation (void)nl_swtimer_cancel(&timer1); } static void Test_one_shot_cancel(nlTestSuite *inSuite, void *inContext) { BaseType_t wait_result; timer_test_info_t test_info1; nl_swtimer_t timer1; TickType_t delay_ticks; bool cancel_result; if (s_test_with_tick_count_near_wrap) { AdjustTickCount(nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_50_MS)); } // test a timer that has a long delay and we cancel // it before it runs printf("%s: start\n", __func__); memset(&test_info1, 0, sizeof(test_info1)); ulTaskNotifyTake(pdTRUE, 0); // clear any old notifications delay_ticks = nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_1000_MS); nl_swtimer_init(&timer1, should_not_run_func, &test_info1); nl_swtimer_start(&timer1, TIMER_TEST_DELAY_1000_MS); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer1)); vTaskDelay(nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_100_MS)); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer1)); cancel_result = nl_swtimer_cancel(&timer1); NL_TEST_ASSERT(inSuite, cancel_result == true); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer1) == false); wait_result = ulTaskNotifyTake(pdTRUE, delay_ticks); NL_TEST_ASSERT(inSuite, wait_result == 0); // check for timeout NL_TEST_ASSERT(inSuite, test_info1.count == 0); // cleanup just in case of failure before we run next test, else // our stack timer structure will corrupt the nl_swtimer implementation (void)nl_swtimer_cancel(&timer1); } static void Test_one_shot_cancel_restart(nlTestSuite *inSuite, void *inContext) { BaseType_t wait_result; timer_test_info_t test_info1; nl_swtimer_t timer1; TickType_t delay_ticks; bool cancel_result; if (s_test_with_tick_count_near_wrap) { AdjustTickCount(nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_50_MS)); } // test a timer that has a long delay and we // cancel it and change the time printf("%s: start\n", __func__); memset(&test_info1, 0, sizeof(test_info1)); test_info1.test_suite = inSuite; ulTaskNotifyTake(pdTRUE, 0); // clear any old notifications delay_ticks = nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_100_MS); nl_swtimer_init(&timer1, should_not_run_func, &test_info1); nl_swtimer_start(&timer1, TIMER_TEST_DELAY_1000_MS); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer1)); vTaskDelay(nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_100_MS)); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer1)); cancel_result = nl_swtimer_cancel(&timer1); NL_TEST_ASSERT(inSuite, cancel_result == true); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer1) == false); NL_TEST_ASSERT(inSuite, test_info1.count == 0); nl_swtimer_init(&timer1, one_shot_timer_test, &test_info1); test_info1.expectedRunTimeMin = xTaskGetTickCount() + delay_ticks; test_info1.expectedRunTimeMax = test_info1.expectedRunTimeMin + TIMING_ERROR_TOLERANCE_TICKS; nl_swtimer_start(&timer1, TIMER_TEST_DELAY_100_MS); wait_result = ulTaskNotifyTake(pdTRUE, delay_ticks + TIMING_ERROR_TOLERANCE_TICKS); NL_TEST_ASSERT(inSuite, wait_result != 0); NL_TEST_ASSERT(inSuite, test_info1.count == test_info1.num_repeats + 1); // cleanup just in case of failure before we run next test, else // our stack timer structure will corrupt the nl_swtimer implementation (void)nl_swtimer_cancel(&timer1); } static void Test_repeat_100(nlTestSuite *inSuite, void *inContext) { BaseType_t wait_result; timer_test_info_t test_info1; nl_swtimer_t timer1; TickType_t delay_ticks; if (s_test_with_tick_count_near_wrap) { AdjustTickCount(nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_50_MS)); } // test a timer that repeats itself 100 times (pseudo // indefinitely) at 100ms period printf("%s: start. test takes about 10 seconds...\n", __func__); memset(&test_info1, 0, sizeof(test_info1)); ulTaskNotifyTake(pdTRUE, 0); // clear any old notifications delay_ticks = nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_100_MS); nl_swtimer_init(&timer1, repeat_timer_test, &test_info1); test_info1.test_suite = inSuite; test_info1.num_repeats = 100; test_info1.repeat_delay = TIMER_TEST_DELAY_100_MS; test_info1.expectedRunTimeMin = xTaskGetTickCount() + delay_ticks; test_info1.expectedRunTimeMax = test_info1.expectedRunTimeMin + TIMING_ERROR_TOLERANCE_TICKS; nl_swtimer_start(&timer1, TIMER_TEST_DELAY_100_MS); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer1)); wait_result = ulTaskNotifyTake(pdTRUE, (delay_ticks + TIMING_ERROR_TOLERANCE_TICKS) * test_info1.num_repeats); NL_TEST_ASSERT(inSuite, wait_result != 0); NL_TEST_ASSERT(inSuite, test_info1.count == test_info1.num_repeats + 1); // cleanup just in case of failure before we run next test, else // our stack timer structure will corrupt the nl_swtimer implementation (void)nl_swtimer_cancel(&timer1); } static void Test_timers_with_sleep_enabled(nlTestSuite *inSuite, void *inContext) { BaseType_t wait_result; timer_test_info_t test_info1; nl_swtimer_t timer1; TickType_t delay_ticks; if (s_test_with_tick_count_near_wrap) { AdjustTickCount(nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_50_MS)); } // test a timer that has a long delay to make sure // it wakes up even when sleep occurs printf("%s: start\n", __func__); memset(&test_info1, 0, sizeof(test_info1)); ulTaskNotifyTake(pdTRUE, 0); // clear any old notifications delay_ticks = nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_1000_MS); nl_swtimer_init(&timer1, one_shot_timer_test, &test_info1); test_info1.test_suite = inSuite; // xTaskGetCount() can be slow when a tick occurs with the scheduler suspended // in the FreeRTOS Idle function, so allow a min which is one tick early. test_info1.expectedRunTimeMin = xTaskGetTickCount() + delay_ticks - 1; test_info1.expectedRunTimeMax = test_info1.expectedRunTimeMin + TIMING_ERROR_TOLERANCE_WITH_SLEEP_TICKS; nl_swtimer_start(&timer1, TIMER_TEST_DELAY_1000_MS); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer1)); wait_result = ulTaskNotifyTake(pdTRUE, delay_ticks + TIMING_ERROR_TOLERANCE_WITH_SLEEP_TICKS); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer1) == false); NL_TEST_ASSERT(inSuite, wait_result != 0); NL_TEST_ASSERT(inSuite, test_info1.count == test_info1.num_repeats + 1); // test a timer that has a short delay, but long enough that // we should sleep. make sure timer wakes up on time. memset(&test_info1, 0, sizeof(test_info1)); delay_ticks = nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_10_MS); nl_swtimer_init(&timer1, one_shot_timer_test, &test_info1); test_info1.test_suite = inSuite; // xTaskGetCount() can be slow when a tick occurs with the scheduler suspended // in the FreeRTOS Idle function, so allow a min which is one tick early. test_info1.expectedRunTimeMin = xTaskGetTickCount() + delay_ticks - 1; test_info1.expectedRunTimeMax = test_info1.expectedRunTimeMin + TIMING_ERROR_TOLERANCE_WITH_SLEEP_TICKS; nl_swtimer_start(&timer1, TIMER_TEST_DELAY_10_MS); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer1)); wait_result = ulTaskNotifyTake(pdTRUE, portMAX_DELAY); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer1) == false); NL_TEST_ASSERT(inSuite, wait_result != 0); NL_TEST_ASSERT(inSuite, test_info1.count == test_info1.num_repeats + 1); // cleanup just in case of failure before we run next test, else // our stack timer structure will corrupt the nl_swtimer implementation (void)nl_swtimer_cancel(&timer1); } static void Test_five_timers(nlTestSuite *inSuite, void *inContext) { timer_test_info_t test_info1; timer_test_info_t test_info2; timer_test_info_t test_info3; timer_test_info_t test_info4; timer_test_info_t test_info5; nl_swtimer_t timer1; nl_swtimer_t timer2; nl_swtimer_t timer3; nl_swtimer_t timer4; nl_swtimer_t timer5; if (s_test_with_tick_count_near_wrap) { AdjustTickCount(nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_50_MS)); } // test five repeating timers running at different delays. // total runtime of 10 seconds. // timer1 has a period of 100ms, repeats 99 times // timer2 has a period of 500ms, repeats 19 times // timer3 has a period of 1000ms, repeats 9 times // timer4 has a period of 2000ms, repeats 4 times // timer5 has a period of 5000ms, repeats once printf("%s: start. test takes about 10 seconds...\n", __func__); memset(&test_info1, 0, sizeof(test_info1)); memset(&test_info2, 0, sizeof(test_info2)); memset(&test_info3, 0, sizeof(test_info3)); memset(&test_info4, 0, sizeof(test_info4)); memset(&test_info5, 0, sizeof(test_info5)); nl_swtimer_init(&timer1, repeat_timer_test, &test_info1); nl_swtimer_init(&timer2, repeat_timer_test, &test_info2); nl_swtimer_init(&timer3, repeat_timer_test, &test_info3); nl_swtimer_init(&timer4, repeat_timer_test, &test_info4); nl_swtimer_init(&timer5, repeat_timer_test, &test_info5); test_info1.test_suite = inSuite; test_info1.repeat_delay = TIMER_TEST_DELAY_100_MS; test_info1.num_repeats = TIMER_TEST_DELAY_10000_MS / TIMER_TEST_DELAY_100_MS - 1; test_info2.test_suite = inSuite; test_info2.repeat_delay = TIMER_TEST_DELAY_500_MS; test_info2.num_repeats = TIMER_TEST_DELAY_10000_MS / TIMER_TEST_DELAY_500_MS - 1; test_info3.test_suite = inSuite; test_info3.repeat_delay = TIMER_TEST_DELAY_1000_MS; test_info3.num_repeats = TIMER_TEST_DELAY_10000_MS / TIMER_TEST_DELAY_1000_MS - 1; test_info4.test_suite = inSuite; test_info4.repeat_delay = TIMER_TEST_DELAY_2000_MS; test_info4.num_repeats = TIMER_TEST_DELAY_10000_MS / TIMER_TEST_DELAY_2000_MS - 1; test_info5.test_suite = inSuite; test_info5.repeat_delay = TIMER_TEST_DELAY_5000_MS; test_info5.num_repeats = TIMER_TEST_DELAY_10000_MS / TIMER_TEST_DELAY_5000_MS - 1; test_info1.expectedRunTimeMin = xTaskGetTickCount() + nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_100_MS); test_info1.expectedRunTimeMax = test_info1.expectedRunTimeMin + TIMING_ERROR_TOLERANCE_TICKS; nl_swtimer_start(&timer1, TIMER_TEST_DELAY_100_MS); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer1)); test_info2.expectedRunTimeMin = xTaskGetTickCount() + nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_500_MS); test_info2.expectedRunTimeMax = test_info2.expectedRunTimeMin + TIMING_ERROR_TOLERANCE_TICKS; nl_swtimer_start(&timer2, TIMER_TEST_DELAY_500_MS); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer2)); test_info3.expectedRunTimeMin = xTaskGetTickCount() + nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_1000_MS); test_info3.expectedRunTimeMax = test_info3.expectedRunTimeMin + TIMING_ERROR_TOLERANCE_TICKS; nl_swtimer_start(&timer3, TIMER_TEST_DELAY_1000_MS); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer3)); test_info4.expectedRunTimeMin = xTaskGetTickCount() + nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_2000_MS); test_info4.expectedRunTimeMax = test_info4.expectedRunTimeMin + TIMING_ERROR_TOLERANCE_TICKS; nl_swtimer_start(&timer4, TIMER_TEST_DELAY_2000_MS); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer4)); test_info5.expectedRunTimeMin = xTaskGetTickCount() + nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_5000_MS); test_info5.expectedRunTimeMax = test_info5.expectedRunTimeMin + TIMING_ERROR_TOLERANCE_TICKS; nl_swtimer_start(&timer5, TIMER_TEST_DELAY_5000_MS); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer5)); // delay until we expect everything to have been run. since // restarting a timer from within itself isn't quite the same // as true periodic, because of the extra tick added to the // each start, we have to wait a bit longer than 10 seconds vTaskDelay((nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_5000_MS)*2 + (test_info1.num_repeats * (TIMING_ERROR_TOLERANCE_TICKS + 1)))); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer1) == false); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer2) == false); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer3) == false); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer4) == false); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer5) == false); NL_TEST_ASSERT(inSuite, test_info1.count == test_info1.num_repeats + 1); NL_TEST_ASSERT(inSuite, test_info2.count == test_info2.num_repeats + 1); NL_TEST_ASSERT(inSuite, test_info3.count == test_info3.num_repeats + 1); NL_TEST_ASSERT(inSuite, test_info4.count == test_info4.num_repeats + 1); NL_TEST_ASSERT(inSuite, test_info5.count == test_info5.num_repeats + 1); // cleanup just in case of failure before we run next test, else // our stack timer structure will corrupt the nl_swtimer implementation (void)nl_swtimer_cancel(&timer1); (void)nl_swtimer_cancel(&timer2); (void)nl_swtimer_cancel(&timer3); (void)nl_swtimer_cancel(&timer4); (void)nl_swtimer_cancel(&timer5); } static void Test_immediate_expiration(nlTestSuite *inSuite, void *inContext) { BaseType_t wait_result; timer_test_info_t test_info1; nl_swtimer_t timer1; TickType_t delay_ticks; if (s_test_with_tick_count_near_wrap) { AdjustTickCount(nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_50_MS)); } // test a simple one shot timer with immediate expiry printf("%s: start\n", __func__); memset(&test_info1, 0, sizeof(test_info1)); ulTaskNotifyTake(pdTRUE, 0); // clear any old notifications nl_swtimer_init(&timer1, one_shot_timer_test, &test_info1); delay_ticks = 1; test_info1.test_suite = inSuite; test_info1.expectedRunTimeMin = xTaskGetTickCount() + delay_ticks; test_info1.expectedRunTimeMax = test_info1.expectedRunTimeMin + TIMING_ERROR_TOLERANCE_TICKS; nl_swtimer_start(&timer1, 0); wait_result = ulTaskNotifyTake(pdTRUE, delay_ticks + TIMING_ERROR_TOLERANCE_TICKS); NL_TEST_ASSERT(inSuite, wait_result != 0); NL_TEST_ASSERT(inSuite, test_info1.count == test_info1.num_repeats + 1); // cleanup just in case of failure before we run next test, else // our stack timer structure will corrupt the nl_swtimer implementation (void)nl_swtimer_cancel(&timer1); } static void Test_five_timers_mixed(nlTestSuite *inSuite, void *inContext) { timer_test_info_t test_info1; timer_test_info_t test_info2; timer_test_info_t test_info3; timer_test_info_t test_info4; timer_test_info_t test_info5; nl_swtimer_t timer1; nl_swtimer_t timer2; nl_swtimer_t timer3; nl_swtimer_t timer4; nl_swtimer_t timer5; if (s_test_with_tick_count_near_wrap) { AdjustTickCount(nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_50_MS)); } // test five repeating timers running at different delays. // total runtime of 10 seconds. mixup the order of // the timer inserts. // timer1 has a period of 100ms, repeats 99 times // timer2 has a period of 500ms, repeats 19 times // timer3 has a period of 1000ms, repeats 9 times // timer4 has a period of 2000ms, repeats 4 times // timer5 has a period of 5000ms, repeats once printf("%s: start. test takes about 10 seconds...\n", __func__); memset(&test_info1, 0, sizeof(test_info1)); memset(&test_info2, 0, sizeof(test_info2)); memset(&test_info3, 0, sizeof(test_info3)); memset(&test_info4, 0, sizeof(test_info4)); memset(&test_info5, 0, sizeof(test_info5)); nl_swtimer_init(&timer1, repeat_timer_test, &test_info1); nl_swtimer_init(&timer2, repeat_timer_test, &test_info2); nl_swtimer_init(&timer3, repeat_timer_test, &test_info3); nl_swtimer_init(&timer4, repeat_timer_test, &test_info4); nl_swtimer_init(&timer5, repeat_timer_test, &test_info5); test_info1.test_suite = inSuite; test_info1.repeat_delay = TIMER_TEST_DELAY_100_MS; test_info1.num_repeats = TIMER_TEST_DELAY_10000_MS / TIMER_TEST_DELAY_100_MS - 1; test_info2.test_suite = inSuite; test_info2.repeat_delay = TIMER_TEST_DELAY_500_MS; test_info2.num_repeats = TIMER_TEST_DELAY_10000_MS / TIMER_TEST_DELAY_500_MS - 1; test_info3.test_suite = inSuite; test_info3.repeat_delay = TIMER_TEST_DELAY_1000_MS; test_info3.num_repeats = TIMER_TEST_DELAY_10000_MS / TIMER_TEST_DELAY_1000_MS - 1; test_info4.test_suite = inSuite; test_info4.repeat_delay = TIMER_TEST_DELAY_2000_MS; test_info4.num_repeats = TIMER_TEST_DELAY_10000_MS / TIMER_TEST_DELAY_2000_MS - 1; test_info5.test_suite = inSuite; test_info5.repeat_delay = TIMER_TEST_DELAY_5000_MS; test_info5.num_repeats = TIMER_TEST_DELAY_10000_MS / TIMER_TEST_DELAY_5000_MS - 1; test_info4.expectedRunTimeMin = xTaskGetTickCount() + nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_2000_MS); test_info4.expectedRunTimeMax = test_info4.expectedRunTimeMin + TIMING_ERROR_TOLERANCE_TICKS; nl_swtimer_start(&timer4, TIMER_TEST_DELAY_2000_MS); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer4)); test_info1.expectedRunTimeMin = xTaskGetTickCount() + nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_100_MS); test_info1.expectedRunTimeMax = test_info1.expectedRunTimeMin + TIMING_ERROR_TOLERANCE_TICKS; nl_swtimer_start(&timer1, TIMER_TEST_DELAY_100_MS); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer1)); test_info5.expectedRunTimeMin = xTaskGetTickCount() + nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_5000_MS); test_info5.expectedRunTimeMax = test_info5.expectedRunTimeMin + TIMING_ERROR_TOLERANCE_TICKS; nl_swtimer_start(&timer5, TIMER_TEST_DELAY_5000_MS); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer5)); test_info2.expectedRunTimeMin = xTaskGetTickCount() + nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_500_MS); test_info2.expectedRunTimeMax = test_info2.expectedRunTimeMin + TIMING_ERROR_TOLERANCE_TICKS; nl_swtimer_start(&timer2, TIMER_TEST_DELAY_500_MS); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer2)); test_info3.expectedRunTimeMin = xTaskGetTickCount() + nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_1000_MS); test_info3.expectedRunTimeMax = test_info3.expectedRunTimeMin + TIMING_ERROR_TOLERANCE_TICKS; nl_swtimer_start(&timer3, TIMER_TEST_DELAY_1000_MS); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer3)); // delay until we expect everything to have been run. since // restarting a timer from within itself isn't quite the same // as true periodic, because of the extra tick added to the // each start, we have to wait a bit longer than 10 seconds vTaskDelay((nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_5000_MS)*2 + (test_info1.num_repeats * (TIMING_ERROR_TOLERANCE_TICKS + 1)))); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer1) == false); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer2) == false); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer3) == false); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer4) == false); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer5) == false); NL_TEST_ASSERT(inSuite, test_info1.count == test_info1.num_repeats + 1); NL_TEST_ASSERT(inSuite, test_info2.count == test_info2.num_repeats + 1); NL_TEST_ASSERT(inSuite, test_info3.count == test_info3.num_repeats + 1); NL_TEST_ASSERT(inSuite, test_info4.count == test_info4.num_repeats + 1); NL_TEST_ASSERT(inSuite, test_info5.count == test_info5.num_repeats + 1); // cleanup just in case of failure before we run next test, else // our stack timer structure will corrupt the nl_swtimer implementation (void)nl_swtimer_cancel(&timer1); (void)nl_swtimer_cancel(&timer2); (void)nl_swtimer_cancel(&timer3); (void)nl_swtimer_cancel(&timer4); (void)nl_swtimer_cancel(&timer5); } static uint32_t cascade_timer_test(nl_swtimer_t *timer, void *arg) { timer_test_info2_t *test_info = (timer_test_info2_t*)arg; TickType_t current_tick_count = xTaskGetTickCount(); unsigned i; test_info->count++; // we should run at the expected time or at most one or two // ticks later (never early). late is due to delta added // by the implementation (1 tick usually) to guarantee // we're not early, and 1 more in case there was delay // associated with the time we recorded the expected time // and another tick arriving, or other added latency. NL_TEST_ASSERT(test_info->test_suite, (current_tick_count >= test_info->expectedRunTimeMin) && (current_tick_count <= test_info->expectedRunTimeMax)); for (i = 0; i < test_info->num_timers; i++) { test_info->timer_infos[i]->expectedRunTimeMin = xTaskGetTickCount() + nl_time_ms_to_delay_time_native(test_info->timer_delays[i]); test_info->timer_infos[i]->expectedRunTimeMax = test_info->timer_infos[i]->expectedRunTimeMin + TIMING_ERROR_TOLERANCE_TICKS; nl_swtimer_start(test_info->timers[i], test_info->timer_delays[i]); } if (test_info->notifyTaskHandle) { BaseType_t yield = pdFALSE; vTaskNotifyGiveFromISR(test_info->notifyTaskHandle, &yield); portEND_SWITCHING_ISR(yield); } return 0; } static void Test_cascade_five_timers(nlTestSuite *inSuite, void *inContext) { BaseType_t wait_result; timer_test_info2_t test_info1; timer_test_info2_t test_info2; timer_test_info2_t test_info3; timer_test_info2_t test_info4; timer_test_info2_t test_info5; nl_swtimer_t timer1; nl_swtimer_t timer2; nl_swtimer_t timer3; nl_swtimer_t timer4; nl_swtimer_t timer5; nl_swtimer_t *timer_list1[1]; uint32_t timer_delays1[1]; timer_test_info2_t *timer_infos1[1]; nl_swtimer_t *timer_list2[3]; uint32_t timer_delays2[3]; timer_test_info2_t *timer_infos2[3]; if (s_test_with_tick_count_near_wrap) { AdjustTickCount(nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_50_MS)); } // test five one shot timers where timer1 starts timer2 from // it's timer function, and timer2 starts timer3, timer4, and // timer5 from it's timer function. // timer1 has a timeout of 100MS // timer2 has a timeout of 500MS // timer3 has a timeout of 1000MS // timer4 has a timeout of 1000MS // timer5 has a timeout of 2000MS printf("%s: start. test takes about 3 seconds...\n", __func__); ulTaskNotifyTake(pdTRUE, 0); // clear any old notifications memset(&test_info1, 0, sizeof(test_info1)); memset(&test_info2, 0, sizeof(test_info2)); memset(&test_info3, 0, sizeof(test_info3)); memset(&test_info4, 0, sizeof(test_info4)); memset(&test_info5, 0, sizeof(test_info5)); nl_swtimer_init(&timer1, cascade_timer_test, &test_info1); nl_swtimer_init(&timer2, cascade_timer_test, &test_info2); nl_swtimer_init(&timer3, cascade_timer_test, &test_info3); nl_swtimer_init(&timer4, cascade_timer_test, &test_info4); nl_swtimer_init(&timer5, cascade_timer_test, &test_info5); test_info1.test_suite = inSuite; test_info1.num_timers = 1; timer_list1[0] = &timer2; timer_delays1[0] = TIMER_TEST_DELAY_500_MS; timer_infos1[0] = &test_info2; test_info1.timers = timer_list1; test_info1.timer_infos = timer_infos1; test_info1.timer_delays = timer_delays1; test_info2.test_suite = inSuite; test_info2.num_timers = 3; timer_list2[0] = &timer3; timer_list2[1] = &timer4; timer_list2[2] = &timer5; timer_delays2[0] = TIMER_TEST_DELAY_1000_MS; timer_delays2[1] = TIMER_TEST_DELAY_1000_MS; timer_delays2[2] = TIMER_TEST_DELAY_2000_MS; timer_infos2[0] = &test_info3; timer_infos2[1] = &test_info4; timer_infos2[2] = &test_info5; test_info2.timers = timer_list2; test_info2.timer_infos = timer_infos2; test_info2.timer_delays = timer_delays2; test_info3.test_suite = inSuite; test_info4.test_suite = inSuite; test_info5.test_suite = inSuite; test_info5.notifyTaskHandle = xTaskGetCurrentTaskHandle(); test_info1.expectedRunTimeMin = xTaskGetTickCount() + nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_100_MS); test_info1.expectedRunTimeMax = test_info1.expectedRunTimeMin + TIMING_ERROR_TOLERANCE_TICKS; nl_swtimer_start(&timer1, TIMER_TEST_DELAY_100_MS); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer1)); // delay until we expect everything to have been run. since // restarting a timer from within itself isn't quite the same // as true periodic, because of the extra tick added to the // each start, we have to wait a bit longer than 10 seconds wait_result = ulTaskNotifyTake(pdTRUE, nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_5000_MS)); NL_TEST_ASSERT(inSuite, wait_result != 0); // assert did not timeout NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer1) == false); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer2) == false); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer3) == false); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer4) == false); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer5) == false); NL_TEST_ASSERT(inSuite, test_info1.count == 1); NL_TEST_ASSERT(inSuite, test_info2.count == 1); NL_TEST_ASSERT(inSuite, test_info3.count == 1); NL_TEST_ASSERT(inSuite, test_info4.count == 1); NL_TEST_ASSERT(inSuite, test_info5.count == 1); // cleanup just in case of failure before we run next test, else // our stack timer structure will corrupt the nl_swtimer implementation (void)nl_swtimer_cancel(&timer1); (void)nl_swtimer_cancel(&timer2); (void)nl_swtimer_cancel(&timer3); (void)nl_swtimer_cancel(&timer4); (void)nl_swtimer_cancel(&timer5); } static void Test_cancel_from_timer_func(nlTestSuite *inSuite, void *inContext) { timer_test_info_t test_info1; timer_test_info_t test_info2; timer_test_info_t test_info3; nl_swtimer_t timer1; nl_swtimer_t timer2; nl_swtimer_t timer3; if (s_test_with_tick_count_near_wrap) { AdjustTickCount(nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_50_MS)); } // Start timer 1 as a repeating timer with 100ms period, repeating 9 times // Start timer 2 as a repeating timer with 100ms period, repeating 9 times // Start timer 3 as a one shot timer with 550ms delay, that cancels timer 1 printf("%s: start\n", __func__); memset(&test_info1, 0, sizeof(test_info1)); memset(&test_info2, 0, sizeof(test_info2)); memset(&test_info3, 0, sizeof(test_info3)); test_info1.test_suite = inSuite; test_info1.num_repeats = 9; test_info1.repeat_delay = TIMER_TEST_DELAY_100_MS; test_info2.test_suite = inSuite; test_info2.num_repeats = 9; test_info2.repeat_delay = TIMER_TEST_DELAY_100_MS; test_info3.test_suite = inSuite; // overload num_repeats to pass a ptr to the timer we want to cancel test_info3.num_repeats = (uint32_t)&timer1; nl_swtimer_init(&timer1, repeat_timer_test, &test_info1); nl_swtimer_init(&timer2, repeat_timer_test, &test_info2); nl_swtimer_init(&timer3, cancel_timer_test, &test_info3); test_info1.expectedRunTimeMin = xTaskGetTickCount() + nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_100_MS); test_info1.expectedRunTimeMax = test_info1.expectedRunTimeMin + TIMING_ERROR_TOLERANCE_TICKS; nl_swtimer_start(&timer1, TIMER_TEST_DELAY_100_MS); test_info2.expectedRunTimeMin = xTaskGetTickCount() + nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_100_MS); test_info2.expectedRunTimeMax = test_info2.expectedRunTimeMin + TIMING_ERROR_TOLERANCE_TICKS; nl_swtimer_start(&timer2, TIMER_TEST_DELAY_100_MS); test_info3.expectedRunTimeMin = xTaskGetTickCount() + nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_500_MS + TIMER_TEST_DELAY_50_MS); test_info3.expectedRunTimeMax = test_info3.expectedRunTimeMin + TIMING_ERROR_TOLERANCE_TICKS; nl_swtimer_start(&timer3, (TIMER_TEST_DELAY_500_MS + TIMER_TEST_DELAY_50_MS)); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer1)); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer2)); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer3)); vTaskDelay(nl_time_ms_to_delay_time_native(TIMER_TEST_DELAY_2000_MS)); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer1) == false); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer2) == false); NL_TEST_ASSERT(inSuite, nl_swtimer_is_active(&timer3) == false); NL_TEST_ASSERT(inSuite, test_info1.count == 5); NL_TEST_ASSERT(inSuite, test_info2.count == 10); NL_TEST_ASSERT(inSuite, test_info3.count == 1); // cleanup just in case of failure before we run next test, else // our stack timer structure will corrupt the nl_swtimer implementation (void)nl_swtimer_cancel(&timer1); (void)nl_swtimer_cancel(&timer2); (void)nl_swtimer_cancel(&timer3); } static const nlTest sTests[] = { NL_TEST_DEF("one shot timer test", Test_one_shot), NL_TEST_DEF("single repeat timer test", Test_single_repeat), NL_TEST_DEF("one shot cancelled timer test", Test_one_shot_cancel), NL_TEST_DEF("one shot cancel and restart timer test", Test_one_shot_cancel_restart), NL_TEST_DEF("cascade five timer test", Test_cascade_five_timers), NL_TEST_DEF("cancel from timer func test", Test_cancel_from_timer_func), NL_TEST_DEF("repeat 100 timer test", Test_repeat_100), NL_TEST_DEF("five timer test", Test_five_timers), NL_TEST_DEF("five timer test mixed", Test_five_timers_mixed), NL_TEST_DEF("immediate expiration", Test_immediate_expiration), NL_TEST_SENTINEL() }; static const nlTest sSleepTests[] = { NL_TEST_DEF("timers with sleep enabled test", Test_timers_with_sleep_enabled), NL_TEST_SENTINEL() }; #define DO_STRESS_TESTS 0 #if DO_STRESS_TESTS #define SHORT_ITERATIONS 1 #if SHORT_ITERATIONS /* Controls how long to run each iteration of the stress test. With * timer1 set at 100ms repeating rate, this should cause each iteration * of the test to take about 120 seconds (2 minutes) */ #define MAX_STRESS_TEST_COUNT 1200 /* Controls what we reset the tick count to be before each iteration is * run in order to make sure we're testing the tick counter wrapping case. * We try to have the wrap occur roughly halfway through the test, * which is about 60 seconds */ #define TICK_COUNT_TARGET_AT_START_OF_STRESS_TEST (nl_time_ms_to_delay_time_native(60000)) #else /* SHORT_ITERATIONS */ /* Controls how long to run each iteration of the stress test. With * timer1 set at 100ms repeating rate, this should cause each iteration * of the test to take about 120000 seconds (200 minutes or 3.33hrs) */ #define MAX_STRESS_TEST_COUNT 120000 /* Controls what we reset the tick count to be before each iteration is * run in order to make sure we're testing the tick counter wrapping case. * We try to have the wrap occur roughly halfway through the test, * which is about 6000 seconds or 100 minutes */ #define TICK_COUNT_TARGET_AT_START_OF_STRESS_TEST (nl_time_ms_to_delay_time_native(6000000)) #endif /* SHORT_ITERATIONS */ /* Controls how many iterations we run. Currently set to run almost * forever. */ #define MAX_STRESS_TEST_ITERATIONS 0xffffffff typedef struct { uint32_t start_count; // number of times the timer was started uint32_t cancel_count; // number of times the timer was cancelled uint32_t run_count; // number of times the timer function ran nlTestSuite *test_suite; uint32_t repeat_delay_min; uint32_t repeat_delay_max; TickType_t expectedRunTimeMin; TickType_t expectedRunTimeMax; } timer_test_info_stress_t; static nl_swtimer_t stress_timer0; static nl_swtimer_t stress_timer1; static nl_swtimer_t stress_timer2; static nl_swtimer_t stress_timer3; static nl_swtimer_t stress_timer4; static nl_swtimer_t stress_timer5; static nl_swtimer_t stress_timer6; static nl_swtimer_t stress_timer7; static nl_swtimer_t stress_timer8; static nl_swtimer_t stress_timer9; static timer_test_info_stress_t stress_test_info0; static timer_test_info_stress_t stress_test_info1; static timer_test_info_stress_t stress_test_info2; static timer_test_info_stress_t stress_test_info3; static timer_test_info_stress_t stress_test_info4; static timer_test_info_stress_t stress_test_info5; static timer_test_info_stress_t stress_test_info6; static timer_test_info_stress_t stress_test_info7; static timer_test_info_stress_t stress_test_info8; static timer_test_info_stress_t stress_test_info9; static void cancel_stress_timer(nl_swtimer_t *timer, timer_test_info_stress_t *test_info) { if (nl_swtimer_cancel(timer)) { test_info->cancel_count++; } } static void start_stress_timer(nl_swtimer_t *timer, timer_test_info_stress_t *test_info, uint32_t delay_ms, TickType_t current_tick_count) { test_info->expectedRunTimeMin = current_tick_count + nl_time_ms_to_delay_time_native(delay_ms); test_info->expectedRunTimeMax = test_info->expectedRunTimeMin + TIMING_ERROR_TOLERANCE_TICKS; nl_swtimer_start(timer, delay_ms); test_info->start_count++; } static void repeat_stress_timer(nl_swtimer_t *timer, timer_test_info_stress_t *test_info, uint32_t delay_ms, TickType_t current_tick_count) { // when using the repeat return argument feature of timer functions, the // extra tick isn't added to the delay internally so subtract one that was // added by the macro nl_time_ms_to_delay_time_native test_info->expectedRunTimeMin = current_tick_count + nl_time_ms_to_delay_time_native(delay_ms) - 1; test_info->expectedRunTimeMax = test_info->expectedRunTimeMin + TIMING_ERROR_TOLERANCE_TICKS; test_info->start_count++; } // we should run at the expected time or at most one or two // ticks later (never early). late is due to delta added // by the implementation (1 tick usually) to guarantee // we're not early, and 1 more in case there was delay // associated with the time we recorded the expected time // and another tick arriving, or other added latency. static void check_timer_run_time(const char *func, timer_test_info_stress_t *test_info, TickType_t current_tick_count) { test_info->run_count++; // check unwrapped and wrapped cases if (((test_info->expectedRunTimeMin <= test_info->expectedRunTimeMax) && (((current_tick_count < test_info->expectedRunTimeMin) || (current_tick_count > test_info->expectedRunTimeMax)))) || ((test_info->expectedRunTimeMin > test_info->expectedRunTimeMax) && (((current_tick_count < test_info->expectedRunTimeMin) && (current_tick_count > test_info->expectedRunTimeMax))))) { printf("%s: current_ticks = %u, expected_min = %u, expected_max = %u\n", func, current_tick_count, test_info->expectedRunTimeMin, test_info->expectedRunTimeMax); assert(0); } } static void check_timer_counts(unsigned timer_num, timer_test_info_stress_t *test_info) { printf("timer %u\n", timer_num); printf("\tstart_count = %lu\n", test_info->start_count); printf("\tcancel_count = %lu\n", test_info->cancel_count); printf("\trun_count = %lu\n", test_info->run_count); if (test_info->run_count != test_info->start_count - test_info->cancel_count) { printf("\tERROR: run_count != start_count - cancel_count\n"); assert(0); } } static uint32_t stress_timer0_func(nl_swtimer_t *timer, void *arg) { timer_test_info_stress_t *test_info = (timer_test_info_stress_t*)arg; TickType_t current_tick_count = xTaskGetTickCount(); uint32_t repeat_delay_ms; check_timer_run_time(__func__, test_info, current_tick_count); if (rand() > 0x80000000) { cancel_stress_timer(&stress_timer4, &stress_test_info4); cancel_stress_timer(&stress_timer5, &stress_test_info5); start_stress_timer(&stress_timer4, &stress_test_info4, TIMER_TEST_DELAY_500_MS, current_tick_count); start_stress_timer(&stress_timer5, &stress_test_info5, TIMER_TEST_DELAY_500_MS, current_tick_count); /* use return value to schedule repeat */ repeat_delay_ms = test_info->repeat_delay_min; repeat_stress_timer(timer, test_info, test_info->repeat_delay_min, current_tick_count); } else { /* use function to schedule repeat */ repeat_delay_ms = 0; start_stress_timer(timer, test_info, test_info->repeat_delay_min, current_tick_count); } return repeat_delay_ms; } static uint32_t stress_timer1_func(nl_swtimer_t *timer, void *arg) { timer_test_info_stress_t *test_info = (timer_test_info_stress_t*)arg; TickType_t current_tick_count = xTaskGetTickCount(); uint32_t repeat_delay_ms; check_timer_run_time(__func__, test_info, current_tick_count); if (rand() > 0x80000000) { cancel_stress_timer(&stress_timer6, &stress_test_info6); start_stress_timer(&stress_timer6, &stress_test_info6, TIMER_TEST_DELAY_500_MS, current_tick_count); cancel_stress_timer(&stress_timer7, &stress_test_info7); start_stress_timer(&stress_timer7, &stress_test_info7, TIMER_TEST_DELAY_500_MS, current_tick_count); /* use return value to schedule repeat */ repeat_delay_ms = test_info->repeat_delay_min; repeat_stress_timer(timer, test_info, test_info->repeat_delay_min, current_tick_count); } else { /* use start function to schedule repeat */ repeat_delay_ms = 0; start_stress_timer(timer, test_info, test_info->repeat_delay_min, current_tick_count); } return repeat_delay_ms; } static uint32_t stress_timer2_func(nl_swtimer_t *timer, void *arg) { timer_test_info_stress_t *test_info = (timer_test_info_stress_t*)arg; TickType_t current_tick_count = xTaskGetTickCount(); uint32_t repeat_delay_ms; check_timer_run_time(__func__, test_info, current_tick_count); if (rand() > 0x80000000) { cancel_stress_timer(&stress_timer8, &stress_test_info8); cancel_stress_timer(&stress_timer9, &stress_test_info9); start_stress_timer(&stress_timer8, &stress_test_info8, TIMER_TEST_DELAY_500_MS, current_tick_count); start_stress_timer(&stress_timer9, &stress_test_info9, TIMER_TEST_DELAY_500_MS, current_tick_count); /* use start function to schedule repeat */ repeat_delay_ms = 0; start_stress_timer(timer, test_info, test_info->repeat_delay_min, current_tick_count); } else { /* use return value to schedule repeat */ repeat_delay_ms = test_info->repeat_delay_min; repeat_stress_timer(timer, test_info, test_info->repeat_delay_min, current_tick_count); } return repeat_delay_ms; } static uint32_t stress_timer3_func(nl_swtimer_t *timer, void *arg) { timer_test_info_stress_t *test_info = (timer_test_info_stress_t*)arg; TickType_t current_tick_count = xTaskGetTickCount(); uint32_t stress_number; check_timer_run_time(__func__, test_info, current_tick_count); stress_number = rand(); if (stress_number > 0xB0000000) { cancel_stress_timer(&stress_timer4, &stress_test_info4); start_stress_timer(&stress_timer4, &stress_test_info4, TIMER_TEST_DELAY_500_MS, current_tick_count); } stress_number = rand(); if (stress_number > 0xB0000000) { cancel_stress_timer(&stress_timer6, &stress_test_info6); start_stress_timer(&stress_timer6, &stress_test_info6, TIMER_TEST_DELAY_500_MS, current_tick_count); } stress_number = rand(); if (stress_number > 0xB0000000) { cancel_stress_timer(&stress_timer8, &stress_test_info8); start_stress_timer(&stress_timer8, &stress_test_info8, TIMER_TEST_DELAY_500_MS, current_tick_count); } start_stress_timer(timer, test_info, test_info->repeat_delay_min, current_tick_count); return 0; } /* The code for timer functions 4-9 are the same, but we keep them separate * so that the trace messages are distinct when a problem is encountered. */ static uint32_t stress_timer4_func(nl_swtimer_t *timer, void *arg) { timer_test_info_stress_t *test_info = (timer_test_info_stress_t*)arg; TickType_t current_tick_count = xTaskGetTickCount(); TickType_t repeat_delay; uint32_t stress_number = rand(); check_timer_run_time(__func__, test_info, current_tick_count); repeat_delay = (stress_number % (test_info->repeat_delay_max - test_info->repeat_delay_min)) + test_info->repeat_delay_min; repeat_stress_timer(timer, test_info, repeat_delay, current_tick_count); return repeat_delay; } static uint32_t stress_timer5_func(nl_swtimer_t *timer, void *arg) { timer_test_info_stress_t *test_info = (timer_test_info_stress_t*)arg; TickType_t current_tick_count = xTaskGetTickCount(); TickType_t repeat_delay; uint32_t stress_number = rand(); check_timer_run_time(__func__, test_info, current_tick_count); repeat_delay = (stress_number % (test_info->repeat_delay_max - test_info->repeat_delay_min)) + test_info->repeat_delay_min; repeat_stress_timer(timer, test_info, repeat_delay, current_tick_count); return repeat_delay; } static uint32_t stress_timer6_func(nl_swtimer_t *timer, void *arg) { timer_test_info_stress_t *test_info = (timer_test_info_stress_t*)arg; TickType_t current_tick_count = xTaskGetTickCount(); TickType_t repeat_delay; uint32_t stress_number = rand(); check_timer_run_time(__func__, test_info, current_tick_count); repeat_delay = (stress_number % (test_info->repeat_delay_max - test_info->repeat_delay_min)) + test_info->repeat_delay_min; repeat_stress_timer(timer, test_info, repeat_delay, current_tick_count); return repeat_delay; } static uint32_t stress_timer7_func(nl_swtimer_t *timer, void *arg) { timer_test_info_stress_t *test_info = (timer_test_info_stress_t*)arg; TickType_t current_tick_count = xTaskGetTickCount(); TickType_t repeat_delay; uint32_t stress_number = rand(); check_timer_run_time(__func__, test_info, current_tick_count); repeat_delay = (stress_number % (test_info->repeat_delay_max - test_info->repeat_delay_min)) + test_info->repeat_delay_min; repeat_stress_timer(timer, test_info, repeat_delay, current_tick_count); return repeat_delay; } static uint32_t stress_timer8_func(nl_swtimer_t *timer, void *arg) { timer_test_info_stress_t *test_info = (timer_test_info_stress_t*)arg; TickType_t current_tick_count = xTaskGetTickCount(); TickType_t repeat_delay; uint32_t stress_number = rand(); check_timer_run_time(__func__, test_info, current_tick_count); repeat_delay = (stress_number % (test_info->repeat_delay_max - test_info->repeat_delay_min)) + test_info->repeat_delay_min; repeat_stress_timer(timer, test_info, repeat_delay, current_tick_count); return repeat_delay; } static uint32_t stress_timer9_func(nl_swtimer_t *timer, void *arg) { timer_test_info_stress_t *test_info = (timer_test_info_stress_t*)arg; TickType_t current_tick_count = xTaskGetTickCount(); TickType_t repeat_delay; uint32_t stress_number = rand(); check_timer_run_time(__func__, test_info, current_tick_count); repeat_delay = (stress_number % (test_info->repeat_delay_max - test_info->repeat_delay_min)) + test_info->repeat_delay_min; repeat_stress_timer(timer, test_info, repeat_delay, current_tick_count); return repeat_delay; } static void Test_stress_timers(nlTestSuite *inSuite, void *inContext) { /* Create 10 timers that do a bunch of stress tests until * one of our counters wrap and then exit. * * timer0: repeats every 100ms, stressly cancels and starts timer4 and timer5 * timer1: repeats every 100ms, stressly cancels and starts timer6 and timer7 * timer2: repeats every 100ms, stressly cancels and starts timer8 and timer9 * timer3: repeats every 500ms, stressly cancels timer4, timer6, and timer8 * timer4: starts with initial delay of 500ms, self repeats stressly from 1ms to 200ms, * timer5: starts with initial delay of 500ms, self repeats stressly from 1ms to 200ms, * timer6: starts with initial delay of 500ms, self repeats stressly from 100ms to 500ms, * timer7: starts with initial delay of 500ms, self repeats stressly from 100ms to 2000ms, * timer8: starts with initial delay of 500ms, self repeats stressly from 500ms to 1000ms, * timer9: starts with initial delay of 500ms, self repeats stressly from 50ms to 1000ms, * TestThread: vTaskDelay() for stress times between 1ms and 5000ms, * cancels timer5 and timer7, checks * counts and stops test when counts > limit. */ printf("%s: start. test takes a long time!\n", __func__); memset(&stress_test_info0, 0, sizeof(stress_test_info0)); memset(&stress_test_info1, 0, sizeof(stress_test_info1)); memset(&stress_test_info2, 0, sizeof(stress_test_info2)); memset(&stress_test_info3, 0, sizeof(stress_test_info3)); memset(&stress_test_info4, 0, sizeof(stress_test_info4)); memset(&stress_test_info5, 0, sizeof(stress_test_info5)); memset(&stress_test_info6, 0, sizeof(stress_test_info6)); memset(&stress_test_info7, 0, sizeof(stress_test_info7)); memset(&stress_test_info8, 0, sizeof(stress_test_info8)); memset(&stress_test_info9, 0, sizeof(stress_test_info9)); stress_test_info0.test_suite = inSuite; stress_test_info0.repeat_delay_min = TIMER_TEST_DELAY_100_MS; stress_test_info0.repeat_delay_max = TIMER_TEST_DELAY_100_MS; stress_test_info1.test_suite = inSuite; stress_test_info1.repeat_delay_min = TIMER_TEST_DELAY_100_MS; stress_test_info1.repeat_delay_max = TIMER_TEST_DELAY_100_MS; stress_test_info2.test_suite = inSuite; stress_test_info2.repeat_delay_min = TIMER_TEST_DELAY_100_MS; stress_test_info2.repeat_delay_max = TIMER_TEST_DELAY_100_MS; stress_test_info3.test_suite = inSuite; stress_test_info3.repeat_delay_min = TIMER_TEST_DELAY_500_MS; stress_test_info3.repeat_delay_max = TIMER_TEST_DELAY_500_MS; stress_test_info4.test_suite = inSuite; stress_test_info4.repeat_delay_min = TIMER_TEST_DELAY_1_MS; stress_test_info4.repeat_delay_max = TIMER_TEST_DELAY_200_MS; stress_test_info5.test_suite = inSuite; stress_test_info5.repeat_delay_min = TIMER_TEST_DELAY_1_MS; stress_test_info5.repeat_delay_max = TIMER_TEST_DELAY_200_MS; stress_test_info6.test_suite = inSuite; stress_test_info6.repeat_delay_min = TIMER_TEST_DELAY_100_MS; stress_test_info6.repeat_delay_max = TIMER_TEST_DELAY_500_MS; stress_test_info7.test_suite = inSuite; stress_test_info7.repeat_delay_min = TIMER_TEST_DELAY_100_MS; stress_test_info7.repeat_delay_max = TIMER_TEST_DELAY_2000_MS; stress_test_info8.test_suite = inSuite; stress_test_info8.repeat_delay_min = TIMER_TEST_DELAY_500_MS; stress_test_info8.repeat_delay_max = TIMER_TEST_DELAY_1000_MS; stress_test_info9.test_suite = inSuite; stress_test_info9.repeat_delay_min = TIMER_TEST_DELAY_50_MS; stress_test_info9.repeat_delay_max = TIMER_TEST_DELAY_1000_MS; nl_swtimer_init(&stress_timer0, stress_timer0_func, &stress_test_info0); nl_swtimer_init(&stress_timer1, stress_timer1_func, &stress_test_info1); nl_swtimer_init(&stress_timer2, stress_timer2_func, &stress_test_info2); nl_swtimer_init(&stress_timer3, stress_timer3_func, &stress_test_info3); nl_swtimer_init(&stress_timer4, stress_timer4_func, &stress_test_info4); nl_swtimer_init(&stress_timer5, stress_timer5_func, &stress_test_info5); nl_swtimer_init(&stress_timer6, stress_timer6_func, &stress_test_info6); nl_swtimer_init(&stress_timer7, stress_timer7_func, &stress_test_info7); nl_swtimer_init(&stress_timer8, stress_timer8_func, &stress_test_info8); nl_swtimer_init(&stress_timer9, stress_timer9_func, &stress_test_info9); nlplatform_interrupt_disable(); TickType_t current_tick_count = xTaskGetTickCount(); start_stress_timer(&stress_timer0, &stress_test_info0, TIMER_TEST_DELAY_100_MS, current_tick_count); start_stress_timer(&stress_timer1, &stress_test_info1, TIMER_TEST_DELAY_100_MS, current_tick_count); start_stress_timer(&stress_timer2, &stress_test_info2, TIMER_TEST_DELAY_100_MS, current_tick_count); start_stress_timer(&stress_timer3, &stress_test_info3, TIMER_TEST_DELAY_500_MS, current_tick_count); start_stress_timer(&stress_timer4, &stress_test_info4, TIMER_TEST_DELAY_500_MS, current_tick_count); start_stress_timer(&stress_timer5, &stress_test_info5, TIMER_TEST_DELAY_500_MS, current_tick_count); start_stress_timer(&stress_timer6, &stress_test_info6, TIMER_TEST_DELAY_500_MS, current_tick_count); start_stress_timer(&stress_timer7, &stress_test_info7, TIMER_TEST_DELAY_500_MS, current_tick_count); start_stress_timer(&stress_timer8, &stress_test_info8, TIMER_TEST_DELAY_500_MS, current_tick_count); start_stress_timer(&stress_timer9, &stress_test_info9, TIMER_TEST_DELAY_500_MS, current_tick_count); nlplatform_interrupt_enable(); while (1) { TickType_t delay = nl_time_ms_to_delay_time_native(rand() % 5000); vTaskDelay(delay); nlplatform_interrupt_disable(); current_tick_count = xTaskGetTickCount(); cancel_stress_timer(&stress_timer5, &stress_test_info5); cancel_stress_timer(&stress_timer7, &stress_test_info7); printf("\n%s: curent_tick_count = %u\n", __func__, current_tick_count); printf("stress_test_info0.run_count = %lu\n", stress_test_info0.run_count); printf("stress_test_info1.run_count = %lu\n", stress_test_info1.run_count); printf("stress_test_info2.run_count = %lu\n", stress_test_info2.run_count); printf("stress_test_info3.run_count = %lu\n", stress_test_info3.run_count); printf("stress_test_info4.run_count = %lu\n", stress_test_info4.run_count); printf("stress_test_info5.run_count = %lu\n", stress_test_info5.run_count); printf("stress_test_info6.run_count = %lu\n", stress_test_info6.run_count); printf("stress_test_info7.run_count = %lu\n", stress_test_info7.run_count); printf("stress_test_info8.run_count = %lu\n", stress_test_info8.run_count); printf("stress_test_info9.run_count = %lu\n", stress_test_info9.run_count); nlplatform_interrupt_enable(); if ((stress_test_info0.run_count > MAX_STRESS_TEST_COUNT) || (stress_test_info1.run_count > MAX_STRESS_TEST_COUNT) || (stress_test_info2.run_count > MAX_STRESS_TEST_COUNT) || (stress_test_info3.run_count > MAX_STRESS_TEST_COUNT) || (stress_test_info4.run_count > MAX_STRESS_TEST_COUNT) || (stress_test_info5.run_count > MAX_STRESS_TEST_COUNT) || (stress_test_info6.run_count > MAX_STRESS_TEST_COUNT) || (stress_test_info7.run_count > MAX_STRESS_TEST_COUNT) || (stress_test_info8.run_count > MAX_STRESS_TEST_COUNT) || (stress_test_info9.run_count > MAX_STRESS_TEST_COUNT)) { break; } } // disable all timers in critical section to make sure none restart others nlplatform_interrupt_disable(); cancel_stress_timer(&stress_timer0, &stress_test_info0); cancel_stress_timer(&stress_timer1, &stress_test_info1); cancel_stress_timer(&stress_timer2, &stress_test_info2); cancel_stress_timer(&stress_timer3, &stress_test_info3); cancel_stress_timer(&stress_timer4, &stress_test_info4); cancel_stress_timer(&stress_timer5, &stress_test_info5); cancel_stress_timer(&stress_timer6, &stress_test_info6); cancel_stress_timer(&stress_timer7, &stress_test_info7); cancel_stress_timer(&stress_timer8, &stress_test_info8); cancel_stress_timer(&stress_timer9, &stress_test_info9); nlplatform_interrupt_enable(); check_timer_counts(0, &stress_test_info0); check_timer_counts(1, &stress_test_info1); check_timer_counts(2, &stress_test_info2); check_timer_counts(3, &stress_test_info3); check_timer_counts(4, &stress_test_info4); check_timer_counts(5, &stress_test_info5); check_timer_counts(6, &stress_test_info6); check_timer_counts(7, &stress_test_info7); check_timer_counts(8, &stress_test_info8); check_timer_counts(9, &stress_test_info9); } static const nlTest sStressTests[] = { NL_TEST_DEF("long running stress timer test", Test_stress_timers), NL_TEST_SENTINEL() }; #endif /* DO_STRESS_TESTS */ static void dummy_task(void *arg) { volatile int *end_flag = (int*)arg; printf("dummy_task start\n"); while (*end_flag == 0) { nlwatchdog_refresh(); } printf("dummy_task end\n"); vTaskSuspend(NULL); } int nl_swtimer_test(void) { nltask_t task; int end_dummy_task = 0; uint8_t dummy_stack[512]; sTaskHandle = xTaskGetCurrentTaskHandle(); /* Align the dummy_stack_ptr to required alignment */ uint8_t *dummy_stack_ptr = ALIGN_POINTER(dummy_stack, NLER_REQUIRED_STACK_ALIGNMENT); nlTestSuite theSuite = { "nl_swtimer", &sTests[0], }; nlTestSuite theSleepSuite = { "nl_swtimer", &sSleepTests[0], }; #if DO_STRESS_TESTS nlTestSuite theStressSuite = { "nl_swtimer", &sStressTests[0], }; #endif /* Run the sleep tests first. The rest of the tests * run with sleep disabled in order to do accuracy * tests which would get messed up by sleep. */ nlTestRunner(&theSleepSuite, NULL); nlTestRunnerStats(&theSleepSuite); printf("\nRerunning sleep timer tests with tick count near wrap\n\n"); s_test_with_tick_count_near_wrap = true; nlTestRunner(&theSleepSuite, NULL); nlTestRunnerStats(&theSleepSuite); s_test_with_tick_count_near_wrap = false; /* To allow our timer functions to test timer accuracy, * we spawn a thread that just spins at low (but not lowest * priority). The FreeRTOS idle thread function disables * task scheduling in it's main loop, and if the tick * interrupt happens during scheduler suspend, the tick * function is called, but the tick count reported by * xTaskGetTickCount() won't be right, so any tests of * accuracy from within timer functions can fail. */ nltask_create(dummy_task, "dum", dummy_stack_ptr, sizeof(dummy_stack) - (dummy_stack_ptr - dummy_stack), kIdleTaskPrio + 1, &end_dummy_task, &task); /* block sleep since many of our tests check for timer accuracy. * will be released by the last test */ g_swtimer_prevent_sleep = true; nlTestRunner(&theSuite, NULL); printf("\nRerunning timer tests with tick count near wrap\n\n"); g_swtimer_prevent_sleep = true; s_test_with_tick_count_near_wrap = true; nlTestRunner(&theSuite, NULL); #if DO_STRESS_TESTS for (unsigned i = 0; i < MAX_STRESS_TEST_ITERATIONS; i++) { printf("\nRunning stress timer test, iteration %u\n\n", i); // set tick count close to wrap so we test wrap handling AdjustTickCount(TICK_COUNT_TARGET_AT_START_OF_STRESS_TEST); // block sleep since many of our tests check for timer accuracy. // will be released by the last test g_swtimer_prevent_sleep = true; nlTestRunner(&theStressSuite, NULL); g_swtimer_prevent_sleep = false; } #endif end_dummy_task = 1; // yield to give chance for dummy task to exit since it's using our stack for its own vTaskDelay(10); return nlTestRunnerStats(&theSuite); } #endif // BUILD_FEATURE_SW_TIMER_USES_RTOS_TICK #endif // BUILD_FEATURE_UNIT_TEST
nestlabs/nlplatform
src/nlgpio_button.c
<filename>src/nlgpio_button.c /* * * Copyright (c) 2015-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file implements a gpio_button * */ #include <errno.h> #include <nlassert.h> #include <nlplatform.h> #include <nlplatform/nlgpio_button.h> #ifdef BUILD_FEATURE_BUTTON_DEBOUNCE #include <nlplatform/nlswtimer.h> #endif #if NL_NUM_GPIO_BUTTONS > 0 typedef struct { #ifdef BUILD_FEATURE_BUTTON_DEBOUNCE nl_swtimer_t timer; bool raw_button; bool debounced_button; bool prev_debounced_button; #endif #if NL_FEATURE_SIMULATEABLE_HW bool simulated_state; #endif bool was_down; } button_state_t; static volatile button_state_t s_button_states[NL_NUM_GPIO_BUTTONS]; #if !NL_FEATURE_SIMULATEABLE_HW #include <nlplatform/nlgpio.h> #ifdef BUILD_FEATURE_BUTTON_DEBOUNCE static uint32_t nlgpio_button_debounce_handler(nl_swtimer_t *timer, void *arg) { uint32_t button_id = (uint32_t)arg; volatile button_state_t * state = &s_button_states[button_id]; const nlgpio_button_config_t *config; state->prev_debounced_button = state->debounced_button; state->debounced_button = state->raw_button; if (state->debounced_button != state->prev_debounced_button) { config = &nlgpio_button_config_table[button_id]; config->callback(button_id, state->debounced_button, config->callback_context); } return 0; } #endif /* BUILD_FEATURE_BUTTON_DEBOUNCE */ static void nlgpio_button_isr(const nlgpio_id_t gpio, void *data) { unsigned button_id = (unsigned)data; s_button_states[button_id].was_down = true; #ifdef BUILD_FEATURE_BUTTON_DEBOUNCE s_button_states[button_id].raw_button = nlgpio_button_is_down(button_id); nl_swtimer_cancel((nl_swtimer_t*)&s_button_states[button_id].timer); nl_swtimer_start((nl_swtimer_t*)&s_button_states[button_id].timer, NL_BUTTON_DEBOUNCE_TIME_INTERVAL_MS); #else bool button_down; const nlgpio_button_config_t *config = &nlgpio_button_config_table[button_id]; button_down = nlgpio_button_is_down(button_id); config->callback(button_id, button_down, config->callback_context); #endif } int nlgpio_button_init(void) { unsigned i; int status = 0; // configure GPIO IRQ for all buttons that we want // a callback for for (i = 0; i < NL_NUM_GPIO_BUTTONS; i++) { if (nlgpio_button_config_table[i].callback) { #ifdef BUILD_CONFIG_DIAGNOSTICS // this function can be called after a shell command replaced a GPIO button ISR // temporarily in order to handle the GPIO interrupt itself. Then they // call this function to restore the button ISR handler. In case there is more // than one button and the shell command only replaced/released one of them, // we want to make sure the old gpio irqs handler is released before we request // it again to avoid tripping an assert that the gpio irq is already in use. nlgpio_irq_release(nlgpio_button_config_table[i].gpio); #endif status = nlgpio_irq_request(nlgpio_button_config_table[i].gpio, nlgpio_button_config_table[i].gpio_irq_flags, nlgpio_button_isr, (void*)i); #ifdef BUILD_FEATURE_BUTTON_DEBOUNCE nl_swtimer_init((nl_swtimer_t*)&s_button_states[i].timer, nlgpio_button_debounce_handler, (void*)i); s_button_states[i].debounced_button = s_button_states[i].prev_debounced_button = nlgpio_button_is_down(i); #endif nlREQUIRE_SUCCESS(status, done); } } done: return status; } bool nlgpio_button_is_down(const nlbutton_id_t button_id) { int button_down = nlgpio_get_value(nlgpio_button_config_table[button_id].gpio); if (nlgpio_button_config_table[button_id].low_is_button_down) { button_down = !button_down; } return button_down; } #else /* NL_FEATURE_SIMULATEABLE_HW */ void nlgpio_button_simulate_state(const nlbutton_id_t button_id, bool button_down) { const nlgpio_button_config_t *config = &nlgpio_button_config_table[button_id]; if (button_down == true) { s_button_states[button_id].was_down = true; } s_button_states[button_id].simulated_state = button_down; if (config->callback) { config->callback(button_id, button_down, config->callback_context); } } bool nlgpio_button_is_down(const nlbutton_id_t button_id) { return s_button_states[button_id].simulated_state; } #endif /* NL_FEATURE_SIMULATEABLE_HW */ bool nlgpio_button_was_down(const nlbutton_id_t button_id) { return s_button_states[button_id].was_down; } #endif /* NL_NUM_GPIO_BUTTONS > 0 */
nestlabs/nlplatform
include/nlflash.h
/* * * Copyright (c) 2015-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file defines an API for accessing flash. * */ #ifndef __NLFLASH_H_INCLUDED__ #define __NLFLASH_H_INCLUDED__ #include <stdint.h> #include <stddef.h> /* nlflash_id_t is provided by nlproduct_config.h, which is included via nlplatform.h * nlplatform.h includes nlplatform_soc.h, which may include soc specific flash driver * header, which needs nlflash_info_t. To break circular dependency, define * nlflash_info_t before including nlplatform.h. */ typedef struct { const char *name; uint32_t base_addr; uint32_t size; uint32_t erase_size; uint32_t fast_erase_size; uint32_t write_size; } nlflash_info_t; #include <nlplatform.h> #ifdef __cplusplus extern "C" { #endif /* For operations that might take a long time and be done in * multiple steps (i.e. in a loop), a callback can be specified * that will be invoked in between steps to allow callers to * do something like cancel, or pet watchdog, etc. */ void nlflash_init(void); int nlflash_request(nlflash_id_t flash_id); int nlflash_release(nlflash_id_t flash_id); int nlflash_flush(nlflash_id_t flash_id); int nlflash_read_id(nlflash_id_t flash_id, uint8_t *id_buf, size_t id_buf_size); const nlflash_info_t *nlflash_get_info(nlflash_id_t flash_id); int nlflash_erase(nlflash_id_t flash_id, uint32_t from, size_t len, size_t *retlen, nlloop_callback_fp callback); int nlflash_read(nlflash_id_t flash_id, uint32_t from, size_t len, size_t *retlen, uint8_t *buf, nlloop_callback_fp callback); int nlflash_write(nlflash_id_t flash_id, uint32_t to, size_t len, size_t *retlen, const uint8_t *buf, nlloop_callback_fp callback); void nlflash_set_lock(nlflash_id_t flash_id, int ( *lock)(void *), int (* unlock)(void *), void *lock_ctx); int nlflash_lock(nlflash_id_t flash_id); int nlflash_unlock(nlflash_id_t flash_id); typedef struct nlflash_func_table_s { int (*init)(void); int (*request)(void); int (*release)(void); int (*flush)(void); int (*read_id)(uint8_t *id_buf, size_t id_buf_size); const nlflash_info_t * (*get_info)(void); int (*erase)(uint32_t from, size_t len, size_t *retlen, nlloop_callback_fp inLoopCallback); int (*read)(uint32_t from, size_t len, size_t *retlen, uint8_t *buf, nlloop_callback_fp inLoopCallback); int (*write)(uint32_t to, size_t len, size_t *retlen, const uint8_t *buf, nlloop_callback_fp inLoopCallback); } nlflash_func_table_t; extern const nlflash_func_table_t g_flash_device_table[NL_NUM_FLASH_IDS]; /* Compatibilty macros until coding conventions are settled */ #define nl_flash_read nlflash_read #define nl_flash_init nlflash_init #define nl_flash_request nlflash_request #define nl_flash_release nlflash_release #define nl_flash_flush nlflash_flush #define nl_flash_read_id nlflash_read_id #define nl_flash_get_info nlflash_get_info #define nl_flash_erase nlflash_erase #define nl_flash_read nlflash_read #define nl_flash_write nlflash_write #define nl_flash_set_lock nlflash_set_lock #define nl_flash_lock nlflash_lock #define nl_flash_unlock nlflash_unlock #define nl_flash_func_table_t nlflash_func_table_t #define nl_flash_info_t nlflash_info_t #ifdef __cplusplus } #endif #endif /* __NLFLASH_H_INCLUDED__ */
nestlabs/nlplatform
src/cpu/arm/cortex-m3/nlmpu.c
/* * * Copyright (c) 2017-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file implements an API for the memory protection unit registers. */ #include <nlplatform.h> #include <nlplatform_soc.h> #include <nlplatform/nlmpu.h> #if (__MPU_PRESENT == 1) /* Same check used in CMSIS header */ void nl_mpu_init(void) { unsigned i; const unsigned num_regions = nl_mpu_get_num_regions(); // start by making sure MPU is off and all regions disabled. // assumes being run at boot so no critical section taken. MPU->CTRL = 0; for (i = 0; i < num_regions; i++) { MPU->RBAR = MPU_RBAR_VALID_Msk | i; MPU->RASR = 0; } } void nl_mpu_enable(bool enable, bool enable_default_memory_map, bool enable_mpu_in_fault_handlers) { unsigned control_value; if (enable) { control_value = MPU_CTRL_ENABLE_Msk; // generated requested control register value and set it if (enable_default_memory_map) { control_value |= MPU_CTRL_PRIVDEFENA_Msk; } if (enable_mpu_in_fault_handlers) { control_value |= MPU_CTRL_HFNMIENA_Msk; } } else { control_value = 0; } /* this is atomic so no critical section needed */ MPU->CTRL = control_value; } unsigned nl_mpu_get_num_regions(void) { return (MPU->TYPE & MPU_TYPE_DREGION_Msk) >> MPU_TYPE_DREGION_Pos; } /* A mask of all the reserved bits, to validate the attributes passed to nl_mpu_request_region(). * None of these bits should be set in the attributes value. */ #define MPU_RASR_ATTRIBUTES_Msk (MPU_RASR_XN_Msk | MPU_RASR_AP_Msk | MPU_RASR_TEX_Msk | \ MPU_RASR_S_Msk | MPU_RASR_C_Msk | MPU_RASR_B_Msk | MPU_RASR_SRD_Msk) /* Different ARM architectures support different attributes/encoding of attributes. * Rather than defining a generic description and then translation to the attributes * supported by the current processor, the attributes should be the ones used * in the corresponding CMSIS header file combined into one unsigned value. * * For example, for cortex-m3, use the core_cm3.h definitions of RASR for the * attributes. * * Returns the region number just allocated and enabled. */ int nl_mpu_request_region(unsigned region_base_address, uint64_t region_size, unsigned attributes) { int i; const unsigned num_regions = nl_mpu_get_num_regions(); unsigned size_value; // check that the inputs are reasonable. // base address must be 32-byte aligned. // region size must be a power of 2, with a minimum of 32-bytes. // attributes must be RASR. assert((region_base_address & ~MPU_RBAR_ADDR_Msk) == 0); assert(region_size >= 32); // >= 32 assert(region_size <= 4*1024*1024*1024ULL); // <= 4GB // only attribute bits should be set in the attributes argument assert((attributes & ~MPU_RASR_ATTRIBUTES_Msk) == 0); // handle special case of 4GB region_size if (region_size == 4*1024*1024*1024ULL) { size_value = 31; } else { // for cortex-m3 MPU, size must be a power of 2. assert((region_size & (region_size - 1)) == 0); // convert to what the RBAR wants for SIZE field size_value = __builtin_ffs(region_size) - 2; } nlplatform_interrupt_disable(); // look for an unused region for (i = 0; i < num_regions; i++) { MPU->RNR = i; if ((MPU->RBAR == i) && (MPU->RASR == 0)) { // found one, configure it. first find the real minimum region // size by writing all 1's to the RBAR[31:5] and reading it back. MPU->RBAR = MPU_RBAR_ADDR_Msk; #ifndef NDEBUG { unsigned min_region_size; unsigned rbar_invalid_addr_bits; rbar_invalid_addr_bits = ~(MPU->RBAR & MPU_RBAR_ADDR_Msk); min_region_size = rbar_invalid_addr_bits + 1; assert(region_size >= min_region_size); assert((region_base_address & rbar_invalid_addr_bits) == 0); } #endif // now write the RBAR register with the base address MPU->RBAR = region_base_address; // now write the attributes to RASR MPU->RASR = attributes | (size_value << MPU_RASR_SIZE_Pos) | MPU_RASR_ENABLE_Msk; break; } } if (i == num_regions) { // failed to find a free region i = -1; } nlplatform_interrupt_enable(); return i; } /* Disables and releases a previously requested region. */ void nl_mpu_release_region(int region) { #ifndef NDEBUG const unsigned num_regions = nl_mpu_get_num_regions(); assert((region >= 0) && (region < num_regions)); #endif nlplatform_interrupt_disable(); MPU->RBAR = MPU_RBAR_VALID_Msk | region; MPU->RASR = 0; nlplatform_interrupt_enable(); } #endif /* (__MPU_PRESENT == 1) */
nestlabs/nlplatform
src/nltrace.c
/* * * Copyright (c) 2017-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file implements a low-level trace utility using time stamped events * */ #include <nlerassert.h> #include <nlplatform.h> #include <nlplatform/nltrace.h> #include <nlplatform/nltimer.h> #include <nlplatform/nlwatchdog.h> #include <FreeRTOS.h> #include <task.h> typedef struct nltrace_event_s { const char *task_name; const char *name; uint32_t start_timestamp_us; uint32_t end_timestamp_us; uint8_t next_ind; uint8_t prev_ind; } nltrace_event_t; #ifndef NL_TRACE_MAX_EVENTS #define NL_TRACE_MAX_EVENTS (64) #endif NLER_STATIC_ASSERT(NL_TRACE_MAX_EVENTS < UINT8_MAX, "nltrace event buffer size must be less than UINT8_MAX elements"); #define INVALID_INDEX (NL_TRACE_MAX_EVENTS + 1) typedef struct { nltrace_event_t events[NL_TRACE_MAX_EVENTS]; uint8_t head_ind; uint8_t tail_ind; } nltrace_t; static nltrace_t s_trace; static bool s_trace_enable = false; static nltimer_id_t s_trace_timer_id; static uint8_t nltrace_alloc_index_locked(void) { uint8_t ret = INVALID_INDEX; for (uint8_t i = 0; i < NL_TRACE_MAX_EVENTS; i++) { if (s_trace.events[i].name == NULL) { ret = i; break; } } return ret; } static void nltrace_insert_locked(uint8_t ind) { if (s_trace.head_ind == INVALID_INDEX && s_trace.tail_ind == INVALID_INDEX) { s_trace.head_ind = ind; } else { s_trace.events[ind].prev_ind = s_trace.tail_ind; s_trace.events[s_trace.tail_ind].next_ind = ind; s_trace.events[ind].next_ind = INVALID_INDEX; } s_trace.tail_ind = ind; } static uint8_t nltrace_remove_locked(uint8_t ind) { uint8_t next = s_trace.events[ind].next_ind; uint8_t prev = s_trace.events[ind].prev_ind; // Remove sole event if (next == INVALID_INDEX && prev == INVALID_INDEX) { s_trace.head_ind = INVALID_INDEX; s_trace.tail_ind = INVALID_INDEX; } // Remove tail else if (next == INVALID_INDEX) { s_trace.tail_ind = prev; s_trace.events[prev].next_ind = INVALID_INDEX; } // Remove head else if (prev == INVALID_INDEX) { s_trace.head_ind = next; s_trace.events[next].prev_ind = INVALID_INDEX; } // Remove from middle else { s_trace.events[prev].next_ind = next; s_trace.events[next].prev_ind = prev; } s_trace.events[ind].name = NULL; s_trace.events[ind].start_timestamp_us = 0; s_trace.events[ind].end_timestamp_us = 0; s_trace.events[ind].next_ind = INVALID_INDEX; s_trace.events[ind].prev_ind = INVALID_INDEX; return next; } static void nltrace_print_locked(void) { uint8_t ind = s_trace.head_ind; while (ind != INVALID_INDEX) { if (s_trace.events[ind].end_timestamp_us != 0) { nlwatchdog_refresh(); NL_LOG_CLEARTEXT(lrAPP, "%s_%s: %u usec (start) %u usec (elapsed)\n", s_trace.events[ind].task_name, s_trace.events[ind].name, s_trace.events[ind].start_timestamp_us, s_trace.events[ind].end_timestamp_us - s_trace.events[ind].start_timestamp_us ); // Remove the event after printing it to make space for new events ind = nltrace_remove_locked(ind); } else { break; } } } void nltrace_init(nltimer_id_t timer_id) { nlplatform_interrupt_disable(); NLER_ASSERT(s_trace_enable == false); s_trace.head_ind = INVALID_INDEX; s_trace.tail_ind = INVALID_INDEX; s_trace_timer_id = timer_id; for (uint8_t ind = 0; ind < NL_TRACE_MAX_EVENTS; ind++) { s_trace.events[ind].name = NULL; s_trace.events[ind].start_timestamp_us = 0; s_trace.events[ind].end_timestamp_us = 0; s_trace.events[ind].next_ind = INVALID_INDEX; s_trace.events[ind].prev_ind = INVALID_INDEX; } nlplatform_interrupt_enable(); } void nltrace_enable(bool enable) { s_trace_enable = enable; } bool nltrace_enabled(void) { return s_trace_enable; } uint8_t nltrace_event_start_with_taskname(const char *name, const char *task_name) { uint8_t ind = INVALID_INDEX; nlplatform_interrupt_disable(); if (s_trace_enable) { ind = nltrace_alloc_index_locked(); if (ind != INVALID_INDEX) { s_trace.events[ind].task_name = task_name; s_trace.events[ind].name = name; s_trace.events[ind].start_timestamp_us = nltimer_elapsed(s_trace_timer_id); nltrace_insert_locked(ind); } else { NL_LOG_CLEARTEXT(lrAPP, "Not enough space to trace event: %s\n", name); } } nlplatform_interrupt_enable(); return ind; } uint8_t nltrace_event_start(const char *name) { const char *task_name; if (nlplatform_in_interrupt()) { task_name = "ISR"; } else { task_name = pcTaskGetTaskName(xTaskGetCurrentTaskHandle()); } return nltrace_event_start_with_taskname(name, task_name); } void nltrace_event_end(uint8_t id, const char *name) { nlplatform_interrupt_disable(); if (s_trace_enable) { if (id < INVALID_INDEX) { // Set the end timestamp if it has not already been set and if the event name matches if (s_trace.events[id].name == name && s_trace.events[id].end_timestamp_us == 0) { s_trace.events[id].end_timestamp_us = nltimer_elapsed(s_trace_timer_id); } } } nlplatform_interrupt_enable(); } void nltrace_print(void) { nlplatform_interrupt_disable(); nltrace_print_locked(); nlplatform_interrupt_enable(); }
nestlabs/nlplatform
src/compiler/gnu/gcc/eabi.c
<reponame>nestlabs/nlplatform /* * * Copyright (c) 2012-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file implements EABI symbols that aren't * defined by nllibclite. */ #include <stddef.h> #include <string.h> #include <stdint.h> #ifdef __ARM_EABI__ void __aeabi_memcpy(void *dest, const void *src, size_t n); void __aeabi_memset (void *dest, size_t n, int c); long long __aeabi_llsr(long long val, int n); int __aeabi_atexit(void (*fn) (void*), void *arg, void *d); void __aeabi_memcpy(void *dest, const void *src, size_t n) { size_t i; uint8_t *d = (uint8_t*) dest; uint8_t *s = (uint8_t*) src; for (i=0; i<n; i++) { *d++ = *s++; } } // note: __aeabi_memset has different parameter order than // the usual memset void __aeabi_memset (void *dest, size_t n, int c) { size_t i; uint8_t *d = (uint8_t*) dest; for (i=0; i<n; i++) { *d++ = c; } } #if defined(__arm__) // Doesn't port to __aarch64__ __attribute__ ((naked)) long long __aeabi_llsr(long long val, int n) { __asm volatile ( ".syntax unified \n\t" "lsrs r0, r2 \n\t" "adds r3, r1, #0 \n\t" "lsrs r1, r2 \n\t" "mov ip, r3 \n\t" "subs r2, #32 \n\t" "lsrs r3, r2 \n\t" "orrs r0, r3 \n\t" "negs r2, r2 \n\t" "mov r3, ip \n\t" "lsls r3, r2 \n\t" "orrs r0, r3 \n\t" "bx lr \n\t"); } #endif #endif /* __ARM_EABI__ */
nestlabs/nlplatform
src/nltime.c
<filename>src/nltime.c /* * * Copyright (c) 2017-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file... * */ #include <nlertime.h> #include <nlmacros.h> #include <nlplatform.h> #include <nlplatform/nltime.h> #ifdef BUILD_FEATURE_SW_TIMER #include <nlplatform/nlswtimer.h> nltime_system_64_t nltime_get_system_ms(void) { // Need to divide by 1,000,000 to convert ns to ms. Rather than divide, // multiply by a millionth, in Q49 fixed point. const uint32_t millionth = 0x218DEF41; // Q49: 19 leading zeros bits and 30 significant bits uint64_t sys_time = nl_swtimer_get_time_ns(); uint64_t upper = sys_time >> 32; uint64_t lower = sys_time & 0xffffffff; upper *= millionth; lower *= millionth; upper += lower >> 32; upper += 1<<16; // Round upper >>= 17; // Q49 - 32 bits in lower return (nltime_system_64_t)upper; // Convert from unsigned to signed. } #else nltime_system_64_t nltime_get_system_ms(void) { // Notes: // - Returning 64 bit type, but only have 32 bits of data // - Millisecond value will rollover, so only use result for computing differences // - When native units rollover, millisecond value will have a sudden // jump in value (not a smooth rollover). return nl_time_native_to_time_ms(nl_get_time_native()); } #endif nltime_system_us_64_t nltime_get_system_us(void) { // TODO: Add microsecond-level system time. Use nltime_get_system_ms() in // the interim. return nltime_get_system_ms() * US_PER_MS; }
nestlabs/nlplatform
include/nlspi_slave.h
/* * * Copyright (c) 2016-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file defines API for SPI slave device. */ #ifndef __NLSPI_SLAVE_H_INCLUDED__ #define __NLSPI_SLAVE_H_INCLUDED__ #include <stdint.h> #include <stddef.h> #include <stdbool.h> #ifdef __cplusplus extern "C" { #endif /* * Slave device drivers should have a const instance of this structure * to pass to transaction calls. It is expected that the user of the * nlspi interface call nlspi_slave_request() and nlspi_slave_release(). */ typedef struct nlspi_slave_config_s { uint8_t mControllerId; uint8_t mHostIntPin; uint8_t mMode; } nlspi_slave_config_t; /** * Indicates that a SPI transaction has completed with * the given length. The data written to the slave has been * written to the pointer indicated by the `anInputBuf` argument * to the previous call to nlspi_slave_prepare_transaction(). * * Once this function is called, nlspi_slave_prepare_transaction() * is invalid and must be called again for the next transaction to be * valid. * * Note that this function is always called at the end of a transaction, * even if nlspi_slave_prepare_transaction() has not yet been called. * * @param[in] aConfig Pointer to SPI nlspi_slave_config_t configuration. * @param[in] aOutputBuf Value of aOutputBuf from last call to * nlspi_slave_prepare_transaction(). * @param[in] aOutputBufLen Value of aOutputBufLen from last call to * nlspi_slave_prepare_transaction(). * @param[in] aInputBuf Value of aInputBuf from last call to * nlspi_slave_prepare_transaction(). * @param[in] aInputBufLen Value of aInputBufLen from last call to * nlspi_slave_prepare_transaction(). * @param[in] aTransactionLen Length of the completed transaction, in bytes. * @param[in] aFromIsr `true` if the callback is being executed from * ISR context, `false` otherwise. */ typedef void (*nlspi_slave_transaction_complete_callback)( const nlspi_slave_config_t *aConfig, uint8_t *aOutputBuf, size_t aOutputBufLen, uint8_t *aInputBuf, size_t aInputBufLen, size_t aTransactionLen, bool aFromIsr ); /** * Initialize the SPI slave interface. * Note that the SPI slave is not fully ready until a transaction is * prepared using nlspi_slave_prepare_transaction(). * * If nlspi_slave_prepare_transaction() is not called before * the master begins a transaction, the resulting SPI transaction * will send all `0xFF` bytes and discard all received bytes. * * @param[in] aConfig Pointer to SPI nlspi_slave_config_t configuration. * @param[in] aCallback Pointer to transaction complete callback * * @retval 0 Successfully request (enabled) the SPI Slave interface. * @retval -EALREADY SPI Slave interface is already requested (enabled). * @retval -EIO Failed to request (enable) the SPI Slave interface. */ int nlspi_slave_request(const nlspi_slave_config_t *aConfig, nlspi_slave_transaction_complete_callback aCallback); /** * Shutdown and release (disable) the SPI slave interface. * * @param[in] aConfig Pointer to SPI nlspi_slave_config_t configuration. */ void nlspi_slave_release(const nlspi_slave_config_t *aConfig); /** * Prepare data for the next SPI transaction. Data pointers * MUST remain valid until the transaction complete callback * is called by the SPI slave driver, or until after the * next call to nlspi_slave_prepare_transaction(). * * This function may be called more than once before the SPI * master initiates the transaction. Each *successful* call to this * function will cause the previous values from earlier calls to * be discarded. * * Not calling this function after a completed transaction is the * same as if this function was previously called with both buffer * lengths set to zero and aRequestTransactionFlag set to `false`. * * Once aOutputBufLen bytes of anOutputBuf has been clocked out, the * MISO pin shall be set high until the master finishes the SPI * transaction. This is the functional equivalent of padding the end * of anOutputBuf with 0xFF bytes out to the length of the transaction. * * Once aInputBufLen bytes of aInputBuf have been clocked in from * MOSI, all subsequent values from the MOSI pin are ignored until the * SPI master finishes the transaction. * * Note that even if `aInputBufLen` or `aOutputBufLen` (or both) are * exhausted before the SPI master finishes a transaction, the ongoing * size of the transaction must still be kept track of to be passed * to the transaction complete callback. For example, if `aInputBufLen` * is equal to 10 and `aOutputBufLen` equal to 20 and the SPI master * clocks out 30 bytes, the value 30 is passed to the transaction * complete callback. * * If a `NULL` pointer is passed in as `aOutputBuf` or `aInputBuf` it * means that that buffer pointer should not change from its current * value. In such a case, the corresponding length argument should be * ignored. For example,`nlspi_slave_prepare_transaction(NULL, 0, * aInputBuf, aInputLen, false)` changes the input buffer pointer and * its length but keeps the output buffer pointer same as it was * before. * * Any call to this function while a transaction is in progress will * cause all of the arguments to be ignored and the return value to * be -EBUSY. * * @param[in] aConfig Pointer to SPI nlspi_slave_config_t configuration. * @param[in] aOutputBuf Data to be written to MISO pin. * @param[in] aOutputBufLen Size of the output buffer, in bytes. * @param[in] aInputBuf Data to be read from MOSI pin. * @param[in] aInputBufLen Size of the input buffer, in bytes. * @param[in] aRequestTransactionFlag Set to true if host interrupt should be set. * * @retval 0 Transaction was successfully prepared. * @retval -EBUSY A transaction is currently in progress. * @retval -ENOENT nlspi_slave_request() hasn't been called. */ int nlspi_slave_prepare_transaction( const nlspi_slave_config_t *aConfig, uint8_t *aOutputBuf, size_t aOutputBufLen, uint8_t *aInputBuf, size_t aInputBufLen, bool aRequestTransactionFlag ); /** * Suspend all active SPI slave controllers before going to sleep. */ void nlspi_slave_suspend(void); /** * Resume all previously active SPI slave controllers after sleep. */ void nlspi_slave_resume(void); #ifdef BUILD_FEATURE_PLATFORM_SPI_SLAVE_STATISTICS /** * This struct defines the SPI slave driver statistics info (counters). */ typedef struct nlspi_slave_statistics_s { uint32_t mNumTrans; /* Number of SPI transactions */ uint32_t mNumRequestedTrans; /* Number of slave requested transactions */ uint32_t mNumResumes; /* Number of SPI resumes from sleep */ uint32_t mNumWakes; /* Number of wakes triggered by SPI */ uint32_t mNumWakeTimeouts; /* Number of wake timeouts */ } nlspi_slave_statistics_t; /** * This function gets the current statistics information. * * @param[in] aConfig Pointer to SPI configuration struct. * @param[out] aStat Pointer to a statistics struct where * the statistics info is copied into. * */ void nlspi_slave_get_statistics(const nlspi_slave_config_t *aConfig, nlspi_slave_statistics_t *aStat); /** * Reset the statistics info (all counters are reset to zero). * * @param[in] aConfig Pointer to SPI configuration struct. * */ void nlspi_slave_reset_statistics(const nlspi_slave_config_t *aConfig); #endif /* defined(BUILD_FEATURE_PLATFORM_SPI_SLAVE_STATISTICS) */ #ifdef NL_NO_RTOS /* Synchronous blocking API used by bootloaders. */ int nlspi_slave_receive(const nlspi_slave_config_t *aConfig, uint8_t *aRxBuf, size_t aRxBufLen, size_t *aRxBytes); int nlspi_slave_transmit(const nlspi_slave_config_t *aConfig, uint8_t *aTxBuf, size_t aTxBufLen, bool aWaitForCompletion); void nlspi_slave_wait_for_transmit_complete(const nlspi_slave_config_t *aConfig); #endif #ifdef __cplusplus } #endif #endif /* __NLSPI_SLAVE_H_INCLUDED__ */
nestlabs/nlplatform
include/spi_flash/mx25r3235.h
<reponame>nestlabs/nlplatform /* * * Copyright (c) 2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file contains macro defines of the MX25R3235F SPI flash chip. * */ #ifndef __MX25R3235_H_INCLUDED__ #define __MX25R3235_H_INCLUDED__ /* ************************************************************************* * Configuration specific to nlflash-spi.c driver * *************************************************************************/ /* Uncomment the following to allow partial page buffer being used when Write() is called. Flush() is used to write everything in the page buffer out to the external flash. */ //#define FLASH_SPI_USE_PARTIAL_PAGE_BUFFER /* Try for 20 msec to read chip ID. Reading a valid chip ID indicates the flash * is ready for interaction. Micron says the flash should complete all internal * processes and return a valid chip ID within 17 msec. */ #define FLASH_SPI_MAX_CHIP_ID_CHECK_COUNT 20 /* Special configurations */ #define FLASH_SPI_REQUEST_SPI_CONTROLLER_ON_REQUEST 1 #define FLASH_SPI_TRISTATE_CS_RST_DURING_POWER_UP 1 /* spi bus, spi freq, and chip select pin should be defined in nlplatform_product_config.h */ #define MX25R3235_MAX_SPI_FREQ_HZ (80000000) /* 80MHz */ #define FLASH_SPI_MODE SPI_MODE_0 /* Size parameters */ #define FLASH_SPI_SIZE (0x400000) /* 4,194,304 Bytes or 4MB */ #define FLASH_SPI_ERASE_SIZE (4096) /* 4KB (smallest erasable unit) */ #define FLASH_SPI_FAST_ERASE_SIZE (0x10000) /* 65,536 Bytes or 64KB */ #define FLASH_SPI_WRITE_SIZE (256) /* writable unit */ #define FLASH_SPI_READ_ID_SIZE (3) #define FLASH_SPI_FAST_READ_DUMMY_CYCLES (1) /* default number of dummy cycles is 1 byte when using FAST_READ */ #define FLASH_SPI_READ_DUMMY_CYCLES (0) /* default number of dummy cycles is 0 byte when using regular READ */ #define FLASH_SPI_FAST_READ_FREQ_HZ (80000000) /* 80MHz */ #define FLASH_SPI_READ_FREQ_HZ (33000000) /* 33MHz */ /* MX25R3235F Status Register and masks */ #define CMD_RDSR (0x05) /* to read out the status reg */ #define CMD_WRSR (0x01) /* to write new val to the status reg */ #define M_STAT_SRWD (1<<7) /* status reg write disable */ #define M_STAT_QE (1<<6) /* Quad mode enable */ #define M_STAT_BP3 (1<<5) /* level of protected block */ #define M_STAT_BP2 (1<<4) #define M_STAT_BP1 (1<<3) #define M_STAT_BP0 (1<<2) #define M_STAT_WEL (1<<1) /* write enable latch */ #define M_STAT_BUSY_BIT (1<<0) /* busy bit mask */ #define M_STAT_READY_VALUE (0<<0) /* value of busy bit to indicate device is ready */ #define M_STAT_BUSY_VALUE (1<<0) /* value of busy bit to indicate device is busy */ /* Register/Setting Commands */ #define CMD_WREN (0x06) /* write enable */ #define CMD_WRDI (0x04) /* write disable */ #define CMD_DP (0xB9) /* enter deep power down mode */ #define CMD_RDP (0x00) /* release from deep power down mode - cs low for tCRDP */ #define CMD_SBL (0xC0) /* to set burst length */ /* Read/Write Array Commands */ #define CMD_READ (0x03) /* max speed 33 MHz */ #define CMD_FAST_READ (0x0B) /* max speed 80 MHz */ #define CMD_PP (0x02) /* to program the selected page */ #define CMD_SSE (0x20) /* subsector erase: "4K subsector" is called "sector" on MX25 */ #define CMD_SE (0xD8) /* sector erase: "64K sector" is called "block" on MX25 */ #define CMD_BE (0xC7) /* bulk erase: "bulk erase" is called "chip erase" on MX25 */ /* Read device ID */ #define CMD_RDID (0x9F) /* read device ID */ /* MX25R3235F Chip IDs */ #define FLASH_SPI_MANUFACTORY_ID (0xC2) #define FLASH_SPI_MEMORY_TYPE_ID (0x28) #define FLASH_SPI_MEMORY_DENSITY_ID (0x16) /* delay time for different operations. DELAY_MSEC * DELAY_LOOP_COUNT == total delay time */ #define PP_DELAY_MSEC (1) #define PP_DELAY_LOOP_COUNT (12) /* PageProgram 256B, Typ./Max.: High Perf 0.85ms/4ms, Low Power 3.2ms/10ms */ #define BE_DELAY_MSEC (1000) #define BE_DELAY_LOOP_COUNT (125) /* ChipErase Typ./Max.: High Perf 26s/70s, Low Power 60s/120s */ #define SE_DELAY_MSEC (75) #define SE_DELAY_LOOP_COUNT (50) /* BlockErase64K Typ./Max.: High Perf 0.48s/3s, Low Power 0.8s/3.5s */ #define SSE_DELAY_MSEC (10) #define SSE_DELAY_LOOP_COUNT (25) /* SectorErase4K Typ./Max.: High Perf 40ms/240ms, Low Power 58ms/240ms */ #endif /* __MX25R3235_H_INCLUDED__ */
nestlabs/nlplatform
include/nlwatchpoint.h
/* * * Copyright (c) 2016-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file implements an API for the watchpoint registers * in an ARM Cortex-M3 and Cortex-M0 (using the CMSIS headers). * Note CMSIS for cm0 and cm0plus don't define the DWT * or CoreDebug registers because they are considered * an optional HW extension. The register locations are * the same as for the cm3. */ #ifdef __cplusplus extern "C" { #endif typedef enum { WATCHPOINT_DISABLED = 0x0, WATCHPOINT_ON_PC_MATCH = 0x4, WATCHPOINT_ON_READ = 0x5, WATCHPOINT_ON_WRITE = 0x6, WATCHPOINT_ON_READ_OR_WRITE = 0x7 } nl_watchpoint_type_t; void nl_watchpoint_enable(unsigned watchpoint_index, unsigned addr, nl_watchpoint_type_t watchpoint_type, unsigned mask); /* change the watchpoint type to a previously configured watchpoint */ void nl_watchpoint_set_type(unsigned watchpoint_index, nl_watchpoint_type_t watchpoint_type); #define nl_watchpoint_disable(watchpoint_index) nl_watchpoint_set_type(watchpoint_index, WATCHPOINT_DISABLED) #ifdef __cplusplus } #endif
nestlabs/nlplatform
include/nlgpio_button.h
/* * * Copyright (c) 2015-2018 Nest Labs, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file defines a gpio button interface. */ #ifndef __NLGPIO_BUTTON_H_INCLUDED__ #define __NLGPIO_BUTTON_H_INCLUDED__ #include <stdint.h> #include <nlplatform.h> #if NL_NUM_GPIO_BUTTONS > 0 #ifndef NL_BUTTON_DEBOUNCE_TIME_INTERVAL_MS #define NL_BUTTON_DEBOUNCE_TIME_INTERVAL_MS 24 #endif #ifdef __cplusplus extern "C" { #endif typedef void (* nlgpio_button_callback_t)(unsigned int button_id, bool button_down, void *context); typedef struct nlgpio_button_config_s { uint8_t gpio; uint8_t gpio_irq_flags; uint8_t low_is_button_down; uint8_t unused; nlgpio_button_callback_t callback; void *callback_context; } nlgpio_button_config_t; extern const nlgpio_button_config_t nlgpio_button_config_table[NL_NUM_GPIO_BUTTONS]; #if !NL_FEATURE_SIMULATEABLE_HW int nlgpio_button_init(void); #else void nlgpio_button_simulate_state(const nlbutton_id_t button_id, bool button_down); #endif bool nlgpio_button_is_down(const nlbutton_id_t button_id); bool nlgpio_button_was_down(const nlbutton_id_t button_id); #ifdef __cplusplus } #endif #endif /* NL_NUM_GPIO_BUTTONS > 0 */ #endif /* __NLBUTTON_H_INCLUDED__ */
nestlabs/nlplatform
include/nli2c.h
/* * * Copyright (c) 2015-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file defines API for accessing a I2C bus. * */ #ifndef __NLI2C_H_INCLUDED__ #define __NLI2C_H_INCLUDED__ #include <stdint.h> #include <stddef.h> #ifdef __cplusplus extern "C" { #endif /* slave device drivers should have a const instace of this structure * to pass to transaction calls. */ #define I2C_FLAG_REG_ADDRESS_SIZE_MASK 0x03 #define I2C_FLAG_REG_ADDRESS_SIZE_0_BYTE 0x00 /* no registers addresses used */ #define I2C_FLAG_REG_ADDRESS_SIZE_1_BYTE 0x01 #define I2C_FLAG_REG_ADDRESS_SIZE_2_BYTE 0x02 #define I2C_FLAG_SLAVE_ADDRESS_SIZE_MASK 0x10 #define I2C_FLAG_SLAVE_ADDRESS_SIZE_7_BITS 0x00 #define I2C_FLAG_SLAVE_ADDRESS_SIZE_10_BITS 0x10 /* slave device drivers should have a const instance of this structure * to pass to transaction calls */ typedef struct nli2c_slave_s { uint8_t controller_id; uint8_t flags; uint16_t slave_addr; /* 7 or 10 bits depending on flags */ } nli2c_slave_t; typedef void (*nli2c_handler_t)(nli2c_slave_t *i2c_slave, int result); void nli2c_init(void); int nli2c_request(const nli2c_slave_t *i2c_slave); int nli2c_release(const nli2c_slave_t *i2c_slave); /* Supply callback for asynchronous read or write. * read returns number of bytes read in synchronous mode, < 0 on error. * write returns number of bytes written in synchronous mode, < 0 on error. * read returns 0 on successful start of transfer in asynchronous mode, < 0 on error. * write returns 0 on successful start of transfer in asynchronous mode, < 0 on error. */ int nli2c_read(const nli2c_slave_t *i2c_slave, uint16_t regAddr, uint8_t *buf, size_t len, nli2c_handler_t callback); int nli2c_write(const nli2c_slave_t *i2c_slave, uint16_t regAddr, const uint8_t *buf, size_t len, nli2c_handler_t callback); #ifdef __cplusplus } #endif #endif /* __NLI2C_H_INCLUDED__ */
nestlabs/nlplatform
include/nlreset_info.h
/* * * Copyright (c) 2015-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file defines the a mechanism for saving SW reset * reasons and fault information (if reset was due to a fault). * HW reset reasons are not currently included (separate API * may exist in an architectural specific way) though we may want * add this in the future. */ #ifndef __NLRESET_INFO_H_INCLUDED__ #define __NLRESET_INFO_H_INCLUDED__ #include <stdint.h> #include <assert.h> #ifdef __cplusplus extern "C" { #endif /* The Phoenix schema enum * Nest::Trait::Firmware::FirmwareTrait::ResetType * must agree with this enum. */ typedef enum { NL_RESET_REASON_UNSPECIFIED = 0, NL_RESET_REASON_UNKNOWN, NL_RESET_REASON_SW_REQUESTED, NL_RESET_REASON_SW_UPDATE, NL_RESET_REASON_FACTORY_RESET, NL_RESET_REASON_COUNT, NL_RESET_REASON_FIRST_FAULT = NL_RESET_REASON_COUNT, /* faults have interesting data in * fault_metadata part of .resetinfo */ NL_RESET_REASON_HARD_FAULT = NL_RESET_REASON_FIRST_FAULT, NL_RESET_REASON_ASSERT, NL_RESET_REASON_WATCHDOG, NL_RESET_REASON_STACK_OVERFLOW, NL_RESET_REASON_LAST_FAULT = NL_RESET_REASON_STACK_OVERFLOW, NL_RESET_REASON_FAULT_COUNT = NL_RESET_REASON_LAST_FAULT - NL_RESET_REASON_FIRST_FAULT + 1 } nl_reset_reason_t; #ifdef __cplusplus } #endif #include <nlproduct_config.h> #ifdef __cplusplus extern "C" { #endif /* nlfault.h references nl_reset_reason_t */ #ifndef NL_FAULT_DIAGS_NUM_CONTEXT_REGISTERS /* Default number of register to save for a fault. * For a CortexM3, these consist of the registers (in order): * r0-r12, sp, pc, lr, xpsr */ #define NL_FAULT_DIAGS_NUM_CONTEXT_REGISTERS 17 #endif #ifndef NL_FAULT_DIAGS_NUM_BT_ENTRIES #define NL_FAULT_DIAGS_NUM_BT_ENTRIES 10 #endif #ifndef NL_FAULT_DIAGS_DESCRIPTION_LENGTH #define NL_FAULT_DIAGS_DESCRIPTION_LENGTH 32 #endif #ifndef NL_FAULT_DIAGS_TASK_NAME_LEN #define NL_FAULT_DIAGS_TASK_NAME_LEN 4 #endif #ifndef NL_FAULT_DIAGS_TASK_STATE_LEN #define NL_FAULT_DIAGS_TASK_STATE_LEN 4 #endif #ifndef NL_FAULT_DIAGS_MAX_NUM_TASKS #define NL_FAULT_DIAGS_MAX_NUM_TASKS 8 #endif #define NL_RESET_INFO_MAGIC 0x1234abcd #define IS_VALID_RESET_REASON(reason) ((reason) < NL_RESET_REASON_COUNT) #define IS_VALID_FAULT_REASON(reason) (((reason) >= NL_RESET_REASON_FIRST_FAULT) && \ ((reason) <= NL_RESET_REASON_LAST_FAULT)) typedef struct { char task_name[NL_FAULT_DIAGS_TASK_NAME_LEN]; uint32_t backtrace[NL_FAULT_DIAGS_NUM_BT_ENTRIES]; char task_state[NL_FAULT_DIAGS_TASK_STATE_LEN]; } nl_fault_task_info_t; typedef uint32_t nl_fault_registers_t[NL_FAULT_DIAGS_NUM_CONTEXT_REGISTERS]; typedef char nl_fault_description_t[NL_FAULT_DIAGS_DESCRIPTION_LENGTH]; typedef struct { uint32_t reason; nl_fault_registers_t registers; char active_task_name[NL_FAULT_DIAGS_TASK_NAME_LEN]; nl_fault_description_t description; uint32_t machine_backtrace[NL_FAULT_DIAGS_NUM_BT_ENTRIES]; nl_fault_task_info_t task_info[NL_FAULT_DIAGS_MAX_NUM_TASKS]; } nl_fault_info_t; typedef struct { uint32_t magic; uint32_t reset_reason; nl_fault_info_t fault_info; } nl_reset_info_t; extern nl_reset_info_t g_reset_info; void nl_reset_info_init(void); /* Sets the reset reason if it has not already been set. * Also sets the fault_description (if not NULL) * and there was no previously uncleared fault. * If the implementation is using temp/overlaid RAM, disables task * switching to reduce likelihood of conflicting usage of the same RAM * addresses. */ void nl_reset_info_prepare_reset(nl_reset_reason_t reset_reason, const char *fault_description); /* Similar to nl_reset_info_prepare_reset() except * that if reset_reason is a fault, an already * set reset reason and fault_description will be * replaced with this new one because a bootloader * fault is more important to record than a reset * reason from an app. * Typically used in bootloaders by linker * aliasing to replace nl_reset_info_prepare_reset() */ void nl_reset_info_prepare_reset_bootloader(nl_reset_reason_t reset_reason, const char *fault_description); /* Get last fault info, if any. Returns 0 if there was a previous fault. */ int nl_reset_info_get_saved_fault(nl_fault_info_t *saved_fault_info); /* Clear fault state, once we've processed the fault info */ void nl_reset_info_clear_saved_fault(void); /* Get last reset reason. Possibly NL_RESET_REASON_UNKNOWN. */ nl_reset_reason_t nl_reset_info_get_reset_reason(void); #ifdef DEBUG void nl_reset_info_print(void); void nl_reset_info_print_saved_fault(void); #endif #ifdef __cplusplus } #endif #endif /* __NLRESET_INFO_H_INCLUDED__ */
nestlabs/nlplatform
include/nlram_console.h
/* * * Copyright (c) 2016-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file defines the interface for a persistent ram console. * The ram console is a two-copy circular buffer used for logging. * It is located in persistent RAM, so that it is possible in a * subsequent boot to see the logs of a previous run. */ #ifndef __NLRAM_CONSOLE_H_INCLUDED__ #define __NLRAM_CONSOLE_H_INCLUDED__ #include <stdint.h> #include <stddef.h> #ifdef __cplusplus extern "C" { #endif typedef void (*nl_ram_console_cb_t)(void); typedef struct { uint32_t write_index; uint32_t bytes_written; uint32_t last_write_index; uint32_t last_bytes_written; uint32_t callback_watermark; uint32_t callback_bytes_written; nl_ram_console_cb_t callback; const uint8_t *buf; uint32_t buf_size; } nl_ram_console_info_t; /* Scratch buffer is optional (pass NULL,0 if none) that gives * init a work place for converting the ram_console if the size * has changed between images. Conversion is never done in the * bootloader, just the app init, since we don't expect bootloaders * to change very often or ever in the field. Conversion only * works if the new size is bigger, or smaller but the items in RAM * that overlap the old buffer size don't get touched before * init is called. The buffer should be as large as the buffer * being converted or else only the last aScratchBufSize bytes will * be preserved. */ void nl_ram_console_init(uint8_t *aScratchBuf, size_t aScratchBufSize); /* Bootloader should use this init function instead of the other * one. It only initializes the ram_console if it's not currently * valid, like on a cold boot. */ void nl_ram_console_init_bootloader(void); /* Enable new data to be written to the RAM console */ void nl_ram_console_enable(void); /* Disable new data being written to the RAM console */ void nl_ram_console_disable(void); /* Fetch information about the RAM console * aInfo - pointer to nl_ram_console_info_t that should be * populated with RAM console info */ void nl_ram_console_get_info(nl_ram_console_info_t *aInfo); /* Write data to the RAM console. * aData - pointer to data to be written to RAM console * aLen - number of bytes to write */ void nl_ram_console_write(const uint8_t *aData, size_t aLen); /* Register a callback to call when RAM console has accumulated * the specified number of characters. * aCallback - callback to be called when fullness threshold reached * aWatermark - callback will be called after accumulating aWatermark bytes * To disable callbacks, call this function with aCallback=NULL, aWatermark=0 */ void nl_ram_console_register_callback(nl_ram_console_cb_t aCallback, uint32_t aWatermark); #ifdef __cplusplus } #endif #endif /* __NLRAM_CONSOLE_H_INCLUDED__ */
nestlabs/nlplatform
include/arch/nlplatform_arm_cm0.h
<reponame>nestlabs/nlplatform<filename>include/arch/nlplatform_arm_cm0.h<gh_stars>1-10 /* * * Copyright (c) 2017-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file implements some cortex M0 specific functions. */ #ifndef __NLPLATFORM_ARCH_CM0_H_INCLUDED__ #define __NLPLATFORM_ARCH_CM0_H_INCLUDED__ #include <stdbool.h> #include <assert.h> #ifdef __cplusplus extern "C" { #endif /* This file is normally included by a nlplatform_soc.h file specific * to a processor. That header file should set USE_INLINE_FUNCTIONS * to 0 or 1 before including this header. Inline functions * might be faster but take more code space. */ #ifndef USE_INLINE_FUNCTIONS #define USE_INLINE_FUNCTIONS 1 #endif static inline bool nlplatform_in_interrupt(void) { uint32_t __regIPSR; __asm__ volatile ("MRS %0, ipsr" : "=r" (__regIPSR) ); return ((__regIPSR) ? true : false); } #if USE_INLINE_FUNCTIONS == 1 extern uint8_t int_lock_count; static inline void nlplatform_interrupt_disable(void) { __asm__ volatile ("cpsid i"); int_lock_count++; } static inline void nlplatform_interrupt_enable(void) { assert(int_lock_count > 0); int_lock_count--; if (int_lock_count == 0) { __asm__ volatile ("cpsie i"); } } #else /* USE_INLINE_FUNCTIONS */ void nlplatform_interrupt_disable(void); void nlplatform_interrupt_enable(void); /* When USE_INLINE_FUNCTIONS == 0, the platform.c for the soc * can include this file and set NLPLATFORM_INTERRUPT_FUNCTIONS * to get the actual code. */ #ifdef NLPLATFORM_INTERRUPT_FUNCTIONS static uint8_t int_lock_count; void nlplatform_interrupt_disable(void) { __asm__ volatile ("cpsid i"); int_lock_count++; } void nlplatform_interrupt_enable(void) { assert(int_lock_count > 0); int_lock_count--; if (int_lock_count == 0) { __asm__ volatile ("cpsie i"); } } #endif /* NLPLATFORM_INTERRUPT_FUNCTIONS */ #endif /* USE_INLINE_FUNCTIONS */ /* This function must be inlined. */ static inline uint32_t nlplatform_get_lr(void) { register uint32_t result; __asm volatile ("mov %0, lr\n" : "=r" (result) ); return result; } /* This function must be inlined. */ static inline uint32_t nlplatform_get_pc(void) { register uint32_t result; __asm volatile ("mov %0, pc\n" : "=r" (result) ); return result; } /* This function must be inlined. */ static inline uint32_t nlplatform_get_sp(void) { register uint32_t result; __asm volatile ("mov %0, sp\n" : "=r" (result) ); return result; } /* This function must be inlined. */ static inline uint32_t nlplatform_get_psp(void) { register uint32_t result; __asm volatile ("mrs %0, psp\n" : "=r" (result)); return result; } /* CoreDebug and DWT registers, for nlwatchpoint. CMCIS core_cm0.h/core_cm0plus.h * dont't define these, maybe because they are considered optional HW extensions. * These definitions come from CMSIS core_cm3.h. */ #if !defined(DWT_BASE) && !defined(CoreDebug_BASE) /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CMSIS_glob_defs CMSIS Global Defines <strong>IO Type Qualifiers</strong> are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /** \brief Structure type to access the Core Debug Register (CoreDebug). */ typedef struct { __IO uint32_t DHCSR; /*!< Offset: 0x000 (R/W) Debug Halting Control and Status Register */ __O uint32_t DCRSR; /*!< Offset: 0x004 ( /W) Debug Core Register Selector Register */ __IO uint32_t DCRDR; /*!< Offset: 0x008 (R/W) Debug Core Register Data Register */ __IO uint32_t DEMCR; /*!< Offset: 0x00C (R/W) Debug Exception and Monitor Control Register */ } CoreDebug_Type; /* Debug Halting Control and Status Register */ #define CoreDebug_DHCSR_DBGKEY_Pos 16 /*!< CoreDebug DHCSR: DBGKEY Position */ #define CoreDebug_DHCSR_DBGKEY_Msk (0xFFFFUL << CoreDebug_DHCSR_DBGKEY_Pos) /*!< CoreDebug DHCSR: DBGKEY Mask */ #define CoreDebug_DHCSR_S_RESET_ST_Pos 25 /*!< CoreDebug DHCSR: S_RESET_ST Position */ #define CoreDebug_DHCSR_S_RESET_ST_Msk (1UL << CoreDebug_DHCSR_S_RESET_ST_Pos) /*!< CoreDebug DHCSR: S_RESET_ST Mask */ #define CoreDebug_DHCSR_S_RETIRE_ST_Pos 24 /*!< CoreDebug DHCSR: S_RETIRE_ST Position */ #define CoreDebug_DHCSR_S_RETIRE_ST_Msk (1UL << CoreDebug_DHCSR_S_RETIRE_ST_Pos) /*!< CoreDebug DHCSR: S_RETIRE_ST Mask */ #define CoreDebug_DHCSR_S_LOCKUP_Pos 19 /*!< CoreDebug DHCSR: S_LOCKUP Position */ #define CoreDebug_DHCSR_S_LOCKUP_Msk (1UL << CoreDebug_DHCSR_S_LOCKUP_Pos) /*!< CoreDebug DHCSR: S_LOCKUP Mask */ #define CoreDebug_DHCSR_S_SLEEP_Pos 18 /*!< CoreDebug DHCSR: S_SLEEP Position */ #define CoreDebug_DHCSR_S_SLEEP_Msk (1UL << CoreDebug_DHCSR_S_SLEEP_Pos) /*!< CoreDebug DHCSR: S_SLEEP Mask */ #define CoreDebug_DHCSR_S_HALT_Pos 17 /*!< CoreDebug DHCSR: S_HALT Position */ #define CoreDebug_DHCSR_S_HALT_Msk (1UL << CoreDebug_DHCSR_S_HALT_Pos) /*!< CoreDebug DHCSR: S_HALT Mask */ #define CoreDebug_DHCSR_S_REGRDY_Pos 16 /*!< CoreDebug DHCSR: S_REGRDY Position */ #define CoreDebug_DHCSR_S_REGRDY_Msk (1UL << CoreDebug_DHCSR_S_REGRDY_Pos) /*!< CoreDebug DHCSR: S_REGRDY Mask */ #define CoreDebug_DHCSR_C_SNAPSTALL_Pos 5 /*!< CoreDebug DHCSR: C_SNAPSTALL Position */ #define CoreDebug_DHCSR_C_SNAPSTALL_Msk (1UL << CoreDebug_DHCSR_C_SNAPSTALL_Pos) /*!< CoreDebug DHCSR: C_SNAPSTALL Mask */ #define CoreDebug_DHCSR_C_MASKINTS_Pos 3 /*!< CoreDebug DHCSR: C_MASKINTS Position */ #define CoreDebug_DHCSR_C_MASKINTS_Msk (1UL << CoreDebug_DHCSR_C_MASKINTS_Pos) /*!< CoreDebug DHCSR: C_MASKINTS Mask */ #define CoreDebug_DHCSR_C_STEP_Pos 2 /*!< CoreDebug DHCSR: C_STEP Position */ #define CoreDebug_DHCSR_C_STEP_Msk (1UL << CoreDebug_DHCSR_C_STEP_Pos) /*!< CoreDebug DHCSR: C_STEP Mask */ #define CoreDebug_DHCSR_C_HALT_Pos 1 /*!< CoreDebug DHCSR: C_HALT Position */ #define CoreDebug_DHCSR_C_HALT_Msk (1UL << CoreDebug_DHCSR_C_HALT_Pos) /*!< CoreDebug DHCSR: C_HALT Mask */ #define CoreDebug_DHCSR_C_DEBUGEN_Pos 0 /*!< CoreDebug DHCSR: C_DEBUGEN Position */ #define CoreDebug_DHCSR_C_DEBUGEN_Msk (1UL /*<< CoreDebug_DHCSR_C_DEBUGEN_Pos*/) /*!< CoreDebug DHCSR: C_DEBUGEN Mask */ /* Debug Core Register Selector Register */ #define CoreDebug_DCRSR_REGWnR_Pos 16 /*!< CoreDebug DCRSR: REGWnR Position */ #define CoreDebug_DCRSR_REGWnR_Msk (1UL << CoreDebug_DCRSR_REGWnR_Pos) /*!< CoreDebug DCRSR: REGWnR Mask */ #define CoreDebug_DCRSR_REGSEL_Pos 0 /*!< CoreDebug DCRSR: REGSEL Position */ #define CoreDebug_DCRSR_REGSEL_Msk (0x1FUL /*<< CoreDebug_DCRSR_REGSEL_Pos*/) /*!< CoreDebug DCRSR: REGSEL Mask */ /* Debug Exception and Monitor Control Register */ #define CoreDebug_DEMCR_TRCENA_Pos 24 /*!< CoreDebug DEMCR: TRCENA Position */ #define CoreDebug_DEMCR_TRCENA_Msk (1UL << CoreDebug_DEMCR_TRCENA_Pos) /*!< CoreDebug DEMCR: TRCENA Mask */ #define CoreDebug_DEMCR_MON_REQ_Pos 19 /*!< CoreDebug DEMCR: MON_REQ Position */ #define CoreDebug_DEMCR_MON_REQ_Msk (1UL << CoreDebug_DEMCR_MON_REQ_Pos) /*!< CoreDebug DEMCR: MON_REQ Mask */ #define CoreDebug_DEMCR_MON_STEP_Pos 18 /*!< CoreDebug DEMCR: MON_STEP Position */ #define CoreDebug_DEMCR_MON_STEP_Msk (1UL << CoreDebug_DEMCR_MON_STEP_Pos) /*!< CoreDebug DEMCR: MON_STEP Mask */ #define CoreDebug_DEMCR_MON_PEND_Pos 17 /*!< CoreDebug DEMCR: MON_PEND Position */ #define CoreDebug_DEMCR_MON_PEND_Msk (1UL << CoreDebug_DEMCR_MON_PEND_Pos) /*!< CoreDebug DEMCR: MON_PEND Mask */ #define CoreDebug_DEMCR_MON_EN_Pos 16 /*!< CoreDebug DEMCR: MON_EN Position */ #define CoreDebug_DEMCR_MON_EN_Msk (1UL << CoreDebug_DEMCR_MON_EN_Pos) /*!< CoreDebug DEMCR: MON_EN Mask */ #define CoreDebug_DEMCR_VC_HARDERR_Pos 10 /*!< CoreDebug DEMCR: VC_HARDERR Position */ #define CoreDebug_DEMCR_VC_HARDERR_Msk (1UL << CoreDebug_DEMCR_VC_HARDERR_Pos) /*!< CoreDebug DEMCR: VC_HARDERR Mask */ #define CoreDebug_DEMCR_VC_INTERR_Pos 9 /*!< CoreDebug DEMCR: VC_INTERR Position */ #define CoreDebug_DEMCR_VC_INTERR_Msk (1UL << CoreDebug_DEMCR_VC_INTERR_Pos) /*!< CoreDebug DEMCR: VC_INTERR Mask */ #define CoreDebug_DEMCR_VC_BUSERR_Pos 8 /*!< CoreDebug DEMCR: VC_BUSERR Position */ #define CoreDebug_DEMCR_VC_BUSERR_Msk (1UL << CoreDebug_DEMCR_VC_BUSERR_Pos) /*!< CoreDebug DEMCR: VC_BUSERR Mask */ #define CoreDebug_DEMCR_VC_STATERR_Pos 7 /*!< CoreDebug DEMCR: VC_STATERR Position */ #define CoreDebug_DEMCR_VC_STATERR_Msk (1UL << CoreDebug_DEMCR_VC_STATERR_Pos) /*!< CoreDebug DEMCR: VC_STATERR Mask */ #define CoreDebug_DEMCR_VC_CHKERR_Pos 6 /*!< CoreDebug DEMCR: VC_CHKERR Position */ #define CoreDebug_DEMCR_VC_CHKERR_Msk (1UL << CoreDebug_DEMCR_VC_CHKERR_Pos) /*!< CoreDebug DEMCR: VC_CHKERR Mask */ #define CoreDebug_DEMCR_VC_NOCPERR_Pos 5 /*!< CoreDebug DEMCR: VC_NOCPERR Position */ #define CoreDebug_DEMCR_VC_NOCPERR_Msk (1UL << CoreDebug_DEMCR_VC_NOCPERR_Pos) /*!< CoreDebug DEMCR: VC_NOCPERR Mask */ #define CoreDebug_DEMCR_VC_MMERR_Pos 4 /*!< CoreDebug DEMCR: VC_MMERR Position */ #define CoreDebug_DEMCR_VC_MMERR_Msk (1UL << CoreDebug_DEMCR_VC_MMERR_Pos) /*!< CoreDebug DEMCR: VC_MMERR Mask */ #define CoreDebug_DEMCR_VC_CORERESET_Pos 0 /*!< CoreDebug DEMCR: VC_CORERESET Position */ #define CoreDebug_DEMCR_VC_CORERESET_Msk (1UL /*<< CoreDebug_DEMCR_VC_CORERESET_Pos*/) /*!< CoreDebug DEMCR: VC_CORERESET Mask */ /*@} end of group CMSIS_CoreDebug */ /** \brief Structure type to access the Data Watchpoint and Trace Register (DWT). */ typedef struct { __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) Control Register */ __IO uint32_t CYCCNT; /*!< Offset: 0x004 (R/W) Cycle Count Register */ __IO uint32_t CPICNT; /*!< Offset: 0x008 (R/W) CPI Count Register */ __IO uint32_t EXCCNT; /*!< Offset: 0x00C (R/W) Exception Overhead Count Register */ __IO uint32_t SLEEPCNT; /*!< Offset: 0x010 (R/W) Sleep Count Register */ __IO uint32_t LSUCNT; /*!< Offset: 0x014 (R/W) LSU Count Register */ __IO uint32_t FOLDCNT; /*!< Offset: 0x018 (R/W) Folded-instruction Count Register */ __I uint32_t PCSR; /*!< Offset: 0x01C (R/ ) Program Counter Sample Register */ __IO uint32_t COMP0; /*!< Offset: 0x020 (R/W) Comparator Register 0 */ __IO uint32_t MASK0; /*!< Offset: 0x024 (R/W) Mask Register 0 */ __IO uint32_t FUNCTION0; /*!< Offset: 0x028 (R/W) Function Register 0 */ uint32_t RESERVED0[1]; __IO uint32_t COMP1; /*!< Offset: 0x030 (R/W) Comparator Register 1 */ __IO uint32_t MASK1; /*!< Offset: 0x034 (R/W) Mask Register 1 */ __IO uint32_t FUNCTION1; /*!< Offset: 0x038 (R/W) Function Register 1 */ uint32_t RESERVED1[1]; __IO uint32_t COMP2; /*!< Offset: 0x040 (R/W) Comparator Register 2 */ __IO uint32_t MASK2; /*!< Offset: 0x044 (R/W) Mask Register 2 */ __IO uint32_t FUNCTION2; /*!< Offset: 0x048 (R/W) Function Register 2 */ uint32_t RESERVED2[1]; __IO uint32_t COMP3; /*!< Offset: 0x050 (R/W) Comparator Register 3 */ __IO uint32_t MASK3; /*!< Offset: 0x054 (R/W) Mask Register 3 */ __IO uint32_t FUNCTION3; /*!< Offset: 0x058 (R/W) Function Register 3 */ } DWT_Type; /* DWT Control Register Definitions */ #define DWT_CTRL_NUMCOMP_Pos 28 /*!< DWT CTRL: NUMCOMP Position */ #define DWT_CTRL_NUMCOMP_Msk (0xFUL << DWT_CTRL_NUMCOMP_Pos) /*!< DWT CTRL: NUMCOMP Mask */ #define DWT_CTRL_NOTRCPKT_Pos 27 /*!< DWT CTRL: NOTRCPKT Position */ #define DWT_CTRL_NOTRCPKT_Msk (0x1UL << DWT_CTRL_NOTRCPKT_Pos) /*!< DWT CTRL: NOTRCPKT Mask */ #define DWT_CTRL_NOEXTTRIG_Pos 26 /*!< DWT CTRL: NOEXTTRIG Position */ #define DWT_CTRL_NOEXTTRIG_Msk (0x1UL << DWT_CTRL_NOEXTTRIG_Pos) /*!< DWT CTRL: NOEXTTRIG Mask */ #define DWT_CTRL_NOCYCCNT_Pos 25 /*!< DWT CTRL: NOCYCCNT Position */ #define DWT_CTRL_NOCYCCNT_Msk (0x1UL << DWT_CTRL_NOCYCCNT_Pos) /*!< DWT CTRL: NOCYCCNT Mask */ #define DWT_CTRL_NOPRFCNT_Pos 24 /*!< DWT CTRL: NOPRFCNT Position */ #define DWT_CTRL_NOPRFCNT_Msk (0x1UL << DWT_CTRL_NOPRFCNT_Pos) /*!< DWT CTRL: NOPRFCNT Mask */ #define DWT_CTRL_CYCEVTENA_Pos 22 /*!< DWT CTRL: CYCEVTENA Position */ #define DWT_CTRL_CYCEVTENA_Msk (0x1UL << DWT_CTRL_CYCEVTENA_Pos) /*!< DWT CTRL: CYCEVTENA Mask */ #define DWT_CTRL_FOLDEVTENA_Pos 21 /*!< DWT CTRL: FOLDEVTENA Position */ #define DWT_CTRL_FOLDEVTENA_Msk (0x1UL << DWT_CTRL_FOLDEVTENA_Pos) /*!< DWT CTRL: FOLDEVTENA Mask */ #define DWT_CTRL_LSUEVTENA_Pos 20 /*!< DWT CTRL: LSUEVTENA Position */ #define DWT_CTRL_LSUEVTENA_Msk (0x1UL << DWT_CTRL_LSUEVTENA_Pos) /*!< DWT CTRL: LSUEVTENA Mask */ #define DWT_CTRL_SLEEPEVTENA_Pos 19 /*!< DWT CTRL: SLEEPEVTENA Position */ #define DWT_CTRL_SLEEPEVTENA_Msk (0x1UL << DWT_CTRL_SLEEPEVTENA_Pos) /*!< DWT CTRL: SLEEPEVTENA Mask */ #define DWT_CTRL_EXCEVTENA_Pos 18 /*!< DWT CTRL: EXCEVTENA Position */ #define DWT_CTRL_EXCEVTENA_Msk (0x1UL << DWT_CTRL_EXCEVTENA_Pos) /*!< DWT CTRL: EXCEVTENA Mask */ #define DWT_CTRL_CPIEVTENA_Pos 17 /*!< DWT CTRL: CPIEVTENA Position */ #define DWT_CTRL_CPIEVTENA_Msk (0x1UL << DWT_CTRL_CPIEVTENA_Pos) /*!< DWT CTRL: CPIEVTENA Mask */ #define DWT_CTRL_EXCTRCENA_Pos 16 /*!< DWT CTRL: EXCTRCENA Position */ #define DWT_CTRL_EXCTRCENA_Msk (0x1UL << DWT_CTRL_EXCTRCENA_Pos) /*!< DWT CTRL: EXCTRCENA Mask */ #define DWT_CTRL_PCSAMPLENA_Pos 12 /*!< DWT CTRL: PCSAMPLENA Position */ #define DWT_CTRL_PCSAMPLENA_Msk (0x1UL << DWT_CTRL_PCSAMPLENA_Pos) /*!< DWT CTRL: PCSAMPLENA Mask */ #define DWT_CTRL_SYNCTAP_Pos 10 /*!< DWT CTRL: SYNCTAP Position */ #define DWT_CTRL_SYNCTAP_Msk (0x3UL << DWT_CTRL_SYNCTAP_Pos) /*!< DWT CTRL: SYNCTAP Mask */ #define DWT_CTRL_CYCTAP_Pos 9 /*!< DWT CTRL: CYCTAP Position */ #define DWT_CTRL_CYCTAP_Msk (0x1UL << DWT_CTRL_CYCTAP_Pos) /*!< DWT CTRL: CYCTAP Mask */ #define DWT_CTRL_POSTINIT_Pos 5 /*!< DWT CTRL: POSTINIT Position */ #define DWT_CTRL_POSTINIT_Msk (0xFUL << DWT_CTRL_POSTINIT_Pos) /*!< DWT CTRL: POSTINIT Mask */ #define DWT_CTRL_POSTPRESET_Pos 1 /*!< DWT CTRL: POSTPRESET Position */ #define DWT_CTRL_POSTPRESET_Msk (0xFUL << DWT_CTRL_POSTPRESET_Pos) /*!< DWT CTRL: POSTPRESET Mask */ #define DWT_CTRL_CYCCNTENA_Pos 0 /*!< DWT CTRL: CYCCNTENA Position */ #define DWT_CTRL_CYCCNTENA_Msk (0x1UL /*<< DWT_CTRL_CYCCNTENA_Pos*/) /*!< DWT CTRL: CYCCNTENA Mask */ /* DWT CPI Count Register Definitions */ #define DWT_CPICNT_CPICNT_Pos 0 /*!< DWT CPICNT: CPICNT Position */ #define DWT_CPICNT_CPICNT_Msk (0xFFUL /*<< DWT_CPICNT_CPICNT_Pos*/) /*!< DWT CPICNT: CPICNT Mask */ /* DWT Exception Overhead Count Register Definitions */ #define DWT_EXCCNT_EXCCNT_Pos 0 /*!< DWT EXCCNT: EXCCNT Position */ #define DWT_EXCCNT_EXCCNT_Msk (0xFFUL /*<< DWT_EXCCNT_EXCCNT_Pos*/) /*!< DWT EXCCNT: EXCCNT Mask */ /* DWT Sleep Count Register Definitions */ #define DWT_SLEEPCNT_SLEEPCNT_Pos 0 /*!< DWT SLEEPCNT: SLEEPCNT Position */ #define DWT_SLEEPCNT_SLEEPCNT_Msk (0xFFUL /*<< DWT_SLEEPCNT_SLEEPCNT_Pos*/) /*!< DWT SLEEPCNT: SLEEPCNT Mask */ /* DWT LSU Count Register Definitions */ #define DWT_LSUCNT_LSUCNT_Pos 0 /*!< DWT LSUCNT: LSUCNT Position */ #define DWT_LSUCNT_LSUCNT_Msk (0xFFUL /*<< DWT_LSUCNT_LSUCNT_Pos*/) /*!< DWT LSUCNT: LSUCNT Mask */ /* DWT Folded-instruction Count Register Definitions */ #define DWT_FOLDCNT_FOLDCNT_Pos 0 /*!< DWT FOLDCNT: FOLDCNT Position */ #define DWT_FOLDCNT_FOLDCNT_Msk (0xFFUL /*<< DWT_FOLDCNT_FOLDCNT_Pos*/) /*!< DWT FOLDCNT: FOLDCNT Mask */ /* DWT Comparator Mask Register Definitions */ #define DWT_MASK_MASK_Pos 0 /*!< DWT MASK: MASK Position */ #define DWT_MASK_MASK_Msk (0x1FUL /*<< DWT_MASK_MASK_Pos*/) /*!< DWT MASK: MASK Mask */ /* DWT Comparator Function Register Definitions */ #define DWT_FUNCTION_MATCHED_Pos 24 /*!< DWT FUNCTION: MATCHED Position */ #define DWT_FUNCTION_MATCHED_Msk (0x1UL << DWT_FUNCTION_MATCHED_Pos) /*!< DWT FUNCTION: MATCHED Mask */ #define DWT_FUNCTION_DATAVADDR1_Pos 16 /*!< DWT FUNCTION: DATAVADDR1 Position */ #define DWT_FUNCTION_DATAVADDR1_Msk (0xFUL << DWT_FUNCTION_DATAVADDR1_Pos) /*!< DWT FUNCTION: DATAVADDR1 Mask */ #define DWT_FUNCTION_DATAVADDR0_Pos 12 /*!< DWT FUNCTION: DATAVADDR0 Position */ #define DWT_FUNCTION_DATAVADDR0_Msk (0xFUL << DWT_FUNCTION_DATAVADDR0_Pos) /*!< DWT FUNCTION: DATAVADDR0 Mask */ #define DWT_FUNCTION_DATAVSIZE_Pos 10 /*!< DWT FUNCTION: DATAVSIZE Position */ #define DWT_FUNCTION_DATAVSIZE_Msk (0x3UL << DWT_FUNCTION_DATAVSIZE_Pos) /*!< DWT FUNCTION: DATAVSIZE Mask */ #define DWT_FUNCTION_LNK1ENA_Pos 9 /*!< DWT FUNCTION: LNK1ENA Position */ #define DWT_FUNCTION_LNK1ENA_Msk (0x1UL << DWT_FUNCTION_LNK1ENA_Pos) /*!< DWT FUNCTION: LNK1ENA Mask */ #define DWT_FUNCTION_DATAVMATCH_Pos 8 /*!< DWT FUNCTION: DATAVMATCH Position */ #define DWT_FUNCTION_DATAVMATCH_Msk (0x1UL << DWT_FUNCTION_DATAVMATCH_Pos) /*!< DWT FUNCTION: DATAVMATCH Mask */ #define DWT_FUNCTION_CYCMATCH_Pos 7 /*!< DWT FUNCTION: CYCMATCH Position */ #define DWT_FUNCTION_CYCMATCH_Msk (0x1UL << DWT_FUNCTION_CYCMATCH_Pos) /*!< DWT FUNCTION: CYCMATCH Mask */ #define DWT_FUNCTION_EMITRANGE_Pos 5 /*!< DWT FUNCTION: EMITRANGE Position */ #define DWT_FUNCTION_EMITRANGE_Msk (0x1UL << DWT_FUNCTION_EMITRANGE_Pos) /*!< DWT FUNCTION: EMITRANGE Mask */ #define DWT_FUNCTION_FUNCTION_Pos 0 /*!< DWT FUNCTION: FUNCTION Position */ #define DWT_FUNCTION_FUNCTION_Msk (0xFUL /*<< DWT_FUNCTION_FUNCTION_Pos*/) /*!< DWT FUNCTION: FUNCTION Mask */ /*@}*/ /* end of group CMSIS_DWT */ #define DWT_BASE (0xE0001000UL) /*!< DWT Base Address */ #define CoreDebug_BASE (0xE000EDF0UL) /*!< Core Debug Base Address */ #define DWT ((DWT_Type *) DWT_BASE ) /*!< DWT configuration struct */ #define CoreDebug ((CoreDebug_Type *) CoreDebug_BASE) /*!< Core Debug configuration struct */ #endif /* !defined(DWT_BASE) && !defined(CoreDebug_BASE) */ #ifdef __cplusplus } #endif #endif /* __NLPLATFORM_ARCH_CM0_H_INCLUDED__ */
nestlabs/nlplatform
include/nlconsole.h
<reponame>nestlabs/nlplatform /* * * Copyright (c) 2015-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file defines a console API. */ #ifndef __NLCONSOLE_H_INCLUDED__ #define __NLCONSOLE_H_INCLUDED__ #include <stdint.h> #include <stdbool.h> #ifdef __cplusplus extern "C" { #endif typedef void (*nlconsole_rx_t)(void); int nlconsole_request(void); int nlconsole_release(void); /* Detect whether there is a transmitter connected. * Returns 0 - not connected, > 0 - connected, < 0 - unknown/error. */ bool nlconsole_is_connected(void); bool nlconsole_canget(void); void nlconsole_putchar(uint8_t ch); int nlconsole_getchar(uint8_t *ch); int nlconsole_flush(void); /* Register a function to be called when a character is received. Set to NULL * to disable. */ void nlconsole_set_rx_callback(nlconsole_rx_t callback); /* Register a function to be called when the system wakes on receive. Set to * NULL to disable. */ void nlconsole_set_rx_wakeup_callback(nlconsole_rx_t callback); #ifdef __cplusplus } #endif #endif /* __NLCONSOLE_H_INCLUDED__ */
nestlabs/nlplatform
include/nluart.h
<filename>include/nluart.h /* * * Copyright (c) 2015-2018 <NAME>, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Description: * This file defines API for UART */ #ifndef __NLUART_H_INCLUDED__ #define __NLUART_H_INCLUDED__ #ifdef __cplusplus extern "C" { #endif #include <stdint.h> #include <stddef.h> #include <nlplatform.h> typedef void (*nluart_handler_t)(const nluart_id_t uart_id, int result); typedef void (*nluart_wakeup_t)(const nluart_id_t uart_id); typedef void (*nluart_rx_t)(const nluart_id_t uart_id); typedef void (*nluart_tx_blocking_cb_t)(void); void nluart_init(void); typedef enum { NL_UART_PARITY_NONE, NL_UART_PARITY_ODD, NL_UART_PARITY_EVEN, } nluart_parity_t; typedef struct nluart_config_s { uint32_t baud_rate; uint8_t nl_cr_enable:1; uint8_t flow_control_enable:1; uint8_t echo_recv_chars:1; uint8_t power_save:1; nluart_parity_t parity:2; uint8_t unused:2; #if NL_FEATURE_SIMULATEABLE_HW const char *dev_tty; #endif } __attribute__((__packed__)) nluart_config_t; int nluart_request(const nluart_id_t uart_id, const nluart_config_t *config); int nluart_release(const nluart_id_t uart_id); /* Supply callback for asynchronous read or write. * read returns number of bytes read in synchronous mode, < 0 on error. * write returns number of bytes written in synchronous mode, < 0 on error. * read returns 0 on successful start of transfer in asynchronous mode, < 0 on error. * write returns 0 on successful start of transfer in asynchronous mode, < 0 on error. */ int nluart_read(const nluart_id_t uart_id, uint8_t *buf, size_t len, nluart_handler_t callback); int nluart_write(const nluart_id_t uart_id, const uint8_t *buf, size_t len, nluart_handler_t callback); /* Blocks until character is written, with timeout. */ int nluart_putchar(const nluart_id_t uart_id, uint8_t ch, unsigned timeout_ms); /* Blocks until character is written, with timeout. Calls callback while waiting for the conditions that will * allow the driver to write the byte to the UART. */ int nluart_putchar_callback(const nluart_id_t uart_id, uint8_t ch, unsigned timeout_ms, nluart_tx_blocking_cb_t callback); /* Stores a character into ch if one is available, with timeout. */ int nluart_getchar(const nluart_id_t uart_id, uint8_t *ch, unsigned timeout_ms); /* Multi-byte put/get API */ size_t nluart_putchars(const nluart_id_t uart_id, const uint8_t *data, size_t len, unsigned timeout_ms); size_t nluart_getchars(const nluart_id_t uart_id, uint8_t *data, size_t max_len, unsigned timeout_ms); /* Return 0 (false) or 1 (true). */ bool nluart_canput(const nluart_id_t uart_id); bool nluart_canget(const nluart_id_t uart_id); bool nluart_tx_idle(const nluart_id_t uart_id); bool nluart_flush(const nluart_id_t uart_id, unsigned timeout_ms); bool nluart_tx_flush(const nluart_id_t uart_id, unsigned timeout_ms); void nluart_rx_flush(const nluart_id_t uart_id); /* Wakeup callback. Set a callback function which is called when the * device wakes up from deep sleep due to rx. Set to NULL to disable callback. */ void nluart_set_wakeup_callback(const nluart_id_t uart_id, nluart_wakeup_t callback); /* Character received callback. Set a callback function which is called * each time a character is received. Set to NULL to disable callback. */ void nluart_set_rx_callback(const nluart_id_t uart_id, nluart_rx_t callback); /* Force mode to async, used in fault handling case. */ void nluart_force_sync(const nluart_id_t uart_id); /* Detect whether there is a transmitter connected. * Returns 0 - not connected, > 0 - connected, < 0 - unknown/error. */ int nluart_is_connected(const nluart_id_t uart_id); /* Suspend all active uart controllers before going to sleep. */ void nluart_suspend(void); /* Resume all previously active uart controllers after sleep. */ void nluart_resume(void); #ifdef __cplusplus } #endif #endif /* __NLUART_H_INCLUDED__ */
ergl/theBeamBook
code/beam_chapter/src/token_threaded_vsm.c
#include <stdio.h> #include <stdlib.h> #define STOP 0 #define ADD 1 #define MUL 2 #define PUSH 3 #define pop() (stack[--sp]) #define push(X) (stack[sp++] = (X)) typedef void (*instructionp_t)(void); int stack[1000]; int sp; instructionp_t *ip; int running; void add() { int x,y; x = pop(); y = pop(); push(x + y); } void mul() { int x,y; x = pop(); y = pop(); push(x * y); } void pushi(){ int x; x = (int)*ip++; push(x); } void stop() { running = 0; } instructionp_t *read_file(char *name) { FILE *file; instructionp_t *code; instructionp_t *cp; long size; char ch; unsigned int val; file = fopen(name, "r"); if(file == NULL) exit(1); fseek(file, 0L, SEEK_END); size = ftell(file); code = calloc(size, sizeof(instructionp_t)); if(code == NULL) exit(1); cp = code; fseek(file, 0L, SEEK_SET); while ( ( ch = fgetc(file) ) != EOF ) { switch (ch) { case ADD: *cp++ = &add; break; case MUL: *cp++ = &mul; break; case PUSH: *cp++ = &pushi; ch = fgetc(file); val = 0; while (ch--) { val = val * 256 + fgetc(file); } *cp++ = (instructionp_t) val; break; } } *cp = &stop; fclose(file); return code; } int run() { sp = 0; running = 1; while (running) (*ip++)(); return pop(); } int main(int argc, char *argv[]) { if (argc > 1) { ip = read_file(argv[1]); printf("The value is: %i\n", run()); return 0; } else { printf("Give the file name of a byte code program as argument\n"); return -1; } }
zxcvdavid/php-yaf
yaf_response.h
/* +----------------------------------------------------------------------+ | Yet Another Framework | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: <NAME> <<EMAIL>> | +----------------------------------------------------------------------+ */ /* $Id: yaf_response.h 329197 2013-01-18 05:55:37Z laruence $ */ #ifndef PHP_YAF_RESPONSE_H #define PHP_YAF_RESPONSE_H #define YAF_RESPONSE_PROPERTY_NAME_HEADER "_header" #define YAF_RESPONSE_PROPERTY_NAME_BODY "_body" #define YAF_RESPONSE_PROPERTY_NAME_HEADEREXCEPTION "_sendheader" #define YAF_RESPONSE_PROPERTY_NAME_DEFAULTBODY "content" #define YAF_RESPONSE_PROPERTY_NAME_DEFAULTBODYNAME "DEFAULT_BODY" #define YAF_RESPONSE_REPLACE 0 #define YAF_RESPONSE_PREPEND 1 #define YAF_RESPONSE_APPEND 2 extern zend_class_entry *yaf_response_ce; extern zend_class_entry *yaf_response_http_ce; extern zend_class_entry *yaf_response_cli_ce; yaf_response_t * yaf_response_instance(yaf_response_t *this_ptr, char *sapi_name TSRMLS_DC); int yaf_response_alter_body(yaf_response_t *response, char *name, int name_len, char *body, long body_len, int flag TSRMLS_DC); int yaf_response_send(yaf_response_t *response TSRMLS_DC); int yaf_response_set_redirect(yaf_response_t *response, char *url, int len TSRMLS_DC); int yaf_response_clear_body(yaf_response_t *response, char *name, uint name_len TSRMLS_DC); YAF_STARTUP_FUNCTION(response); #endif /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
zxcvdavid/php-yaf
yaf_response.c
<filename>yaf_response.c<gh_stars>1-10 /* +----------------------------------------------------------------------+ | Yet Another Framework | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: <NAME> <<EMAIL>> | +----------------------------------------------------------------------+ */ /* $Id: yaf_response.c 329197 2013-01-18 05:55:37Z laruence $ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "main/SAPI.h" /* for sapi_header_line */ #include "ext/standard/php_string.h" /* for php_implode */ #include "Zend/zend_interfaces.h" #include "php_yaf.h" #include "yaf_namespace.h" #include "yaf_response.h" #include "yaf_exception.h" #include "responses/yaf_response_http.h" #include "responses/yaf_response_cli.h" zend_class_entry *yaf_response_ce; /** {{{ ARG_INFO */ ZEND_BEGIN_ARG_INFO_EX(yaf_response_void_arginfo, 0, 0, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(yaf_response_get_body_arginfo, 0, 0, 0) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(yaf_response_set_body_arginfo, 0, 0, 1) ZEND_ARG_INFO(0, body) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(yaf_response_clear_body_arginfo, 0, 0, 0) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO() /* }}} */ /** {{{ yaf_response_t * yaf_response_instance(yaf_response_t *this_ptr, char *sapi_name TSRMLS_DC) */ yaf_response_t * yaf_response_instance(yaf_response_t *this_ptr, char *sapi_name TSRMLS_DC) { zval *header, *body; zend_class_entry *ce; yaf_response_t *instance; if (strncasecmp(sapi_name, "cli", 3)) { ce = yaf_response_http_ce; } else { ce = yaf_response_cli_ce; } if (this_ptr) { instance = this_ptr; } else { MAKE_STD_ZVAL(instance); object_init_ex(instance, ce); } MAKE_STD_ZVAL(header); array_init(header); zend_update_property(ce, instance, ZEND_STRL(YAF_RESPONSE_PROPERTY_NAME_HEADER), header TSRMLS_CC); zval_ptr_dtor(&header); MAKE_STD_ZVAL(body); array_init(body); zend_update_property(ce, instance, ZEND_STRL(YAF_RESPONSE_PROPERTY_NAME_BODY), body TSRMLS_CC); zval_ptr_dtor(&body); return instance; } /* }}} */ /** {{{ static int yaf_response_set_body(yaf_response_t *response, char *name, int name_len, char *body, long body_len TSRMLS_DC) */ #if 0 static int yaf_response_set_body(yaf_response_t *response, char *name, int name_len, char *body, long body_len TSRMLS_DC) { zval *zbody; zend_class_entry *response_ce; if (!body_len) { return 1; } response_ce = Z_OBJCE_P(response); zbody = zend_read_property(response_ce, response, ZEND_STRL(YAF_RESPONSE_PROPERTY_NAME_BODY), 1 TSRMLS_CC); zval_ptr_dtor(&zbody); MAKE_STD_ZVAL(zbody); ZVAL_STRINGL(zbody, body, body_len, 1); zend_update_property(response_ce, response, ZEND_STRL(YAF_RESPONSE_PROPERTY_NAME_BODY), zbody TSRMLS_CC); return 1; } #endif /* }}} */ /** {{{ int yaf_response_alter_body(yaf_response_t *response, char *name, int name_len, char *body, long body_len, int flag TSRMLS_DC) */ int yaf_response_alter_body(yaf_response_t *response, char *name, int name_len, char *body, long body_len, int flag TSRMLS_DC) { zval *zbody, **ppzval; char *obody; long obody_len; if (!body_len) { return 1; } zbody = zend_read_property(yaf_response_ce, response, ZEND_STRL(YAF_RESPONSE_PROPERTY_NAME_BODY), 1 TSRMLS_CC); if (!name) { name = YAF_RESPONSE_PROPERTY_NAME_DEFAULTBODY; name_len = sizeof(YAF_RESPONSE_PROPERTY_NAME_DEFAULTBODY) - 1; } if (zend_hash_find(Z_ARRVAL_P(zbody), name, name_len + 1, (void **)&ppzval) == FAILURE) { zval *body; obody = NULL; MAKE_STD_ZVAL(body); ZVAL_NULL(body); zend_hash_update(Z_ARRVAL_P(zbody), name, name_len +1, (void **)&body, sizeof(zval *), (void **)&ppzval); } else { obody = Z_STRVAL_PP(ppzval); obody_len = Z_STRLEN_PP(ppzval); } if (obody) { char *result; long result_len; switch (flag) { case YAF_RESPONSE_PREPEND: result_len = body_len + obody_len; result = emalloc(result_len + 1); memcpy(result, body, body_len); memcpy(result + body_len, obody, obody_len); result[result_len] = '\0'; ZVAL_STRINGL(*ppzval, result, result_len, 0); break; case YAF_RESPONSE_APPEND: result_len = body_len + obody_len; result = emalloc(result_len + 1); memcpy(result, obody, obody_len); memcpy(result + obody_len, body, body_len); result[result_len] = '\0'; ZVAL_STRINGL(*ppzval, result, result_len, 0); break; case YAF_RESPONSE_REPLACE: default: ZVAL_STRINGL(*ppzval, body, body_len, 1); break; } efree(obody); } else { ZVAL_STRINGL(*ppzval, body, body_len, 1); } return 1; } /* }}} */ /** {{{ int yaf_response_clear_body(yaf_response_t *response, char *name, uint name_len TSRMLS_DC) */ int yaf_response_clear_body(yaf_response_t *response, char *name, uint name_len TSRMLS_DC) { zval *zbody; zbody = zend_read_property(yaf_response_ce, response, ZEND_STRL(YAF_RESPONSE_PROPERTY_NAME_BODY), 1 TSRMLS_CC); if (name) { zend_hash_del(Z_ARRVAL_P(zbody), name, name_len + 1); } else { zend_hash_clean(Z_ARRVAL_P(zbody)); } return 1; } /* }}} */ /** {{{ zval * yaf_response_get_body(yaf_response_t *response, char *name, uint name_len TSRMLS_DC) */ zval * yaf_response_get_body(yaf_response_t *response, char *name, uint name_len TSRMLS_DC) { zval **ppzval; zval *zbody = zend_read_property(yaf_response_ce, response, ZEND_STRL(YAF_RESPONSE_PROPERTY_NAME_BODY), 1 TSRMLS_CC); if (!name) { return zbody; } if (zend_hash_find(Z_ARRVAL_P(zbody), name, name_len + 1, (void **)&ppzval) == FAILURE) { return NULL; } return *ppzval; } /* }}} */ /** {{{ int yaf_response_send(yaf_response_t *response TSRMLS_DC) */ int yaf_response_send(yaf_response_t *response TSRMLS_DC) { zval *zbody; zval **val; zbody = zend_read_property(yaf_response_ce, response, ZEND_STRL(YAF_RESPONSE_PROPERTY_NAME_BODY), 1 TSRMLS_CC); zend_hash_internal_pointer_reset(Z_ARRVAL_P(zbody)); while (SUCCESS == zend_hash_get_current_data(Z_ARRVAL_P(zbody), (void**)&val)) { convert_to_string_ex(val); php_write(Z_STRVAL_PP(val), Z_STRLEN_PP(val) TSRMLS_CC); zend_hash_move_forward(Z_ARRVAL_P(zbody)); } return 1; } /* }}} */ /** {{{ proto private Yaf_Response_Abstract::__construct() */ PHP_METHOD(yaf_response, __construct) { (void)yaf_response_instance(getThis(), sapi_module.name TSRMLS_CC); } /* }}} */ /** {{{ proto public Yaf_Response_Abstract::__destruct(void) */ PHP_METHOD(yaf_response, __destruct) { } /* }}} */ /** {{{ proto public Yaf_Response_Abstract::appendBody($body, $name = NULL) */ PHP_METHOD(yaf_response, appendBody) { char *body, *name = NULL; uint body_len, name_len = 0; yaf_response_t *self; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s", &body, &body_len, &name, &name_len) == FAILURE) { return; } self = getThis(); if (yaf_response_alter_body(self, name, name_len, body, body_len, YAF_RESPONSE_APPEND TSRMLS_CC)) { RETURN_ZVAL(self, 1, 0); } RETURN_FALSE; } /* }}} */ /** {{{ proto public Yaf_Response_Abstract::prependBody($body, $name = NULL) */ PHP_METHOD(yaf_response, prependBody) { char *body, *name = NULL; uint body_len, name_len = 0; yaf_response_t *self; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s", &body, &body_len, &name, &name_len) == FAILURE) { return; } self = getThis(); if (yaf_response_alter_body(self, name, name_len, body, body_len, YAF_RESPONSE_PREPEND TSRMLS_CC)) { RETURN_ZVAL(self, 1, 0); } RETURN_FALSE; } /* }}} */ /** {{{ proto public Yaf_Response_Abstract::setHeader($name, $value, $replace = 0) */ PHP_METHOD(yaf_response, setHeader) { RETURN_FALSE; } /* }}} */ /** {{{ proto protected Yaf_Response_Abstract::setAllHeaders(void) */ PHP_METHOD(yaf_response, setAllHeaders) { RETURN_FALSE; } /* }}} */ /** {{{ proto public Yaf_Response_Abstract::getHeader(void) */ PHP_METHOD(yaf_response, getHeader) { RETURN_NULL(); } /* }}} */ /** {{{ proto public Yaf_Response_Abstract::clearHeaders(void) */ PHP_METHOD(yaf_response, clearHeaders) { RETURN_FALSE; } /* }}} */ /** {{{ proto public Yaf_Response_Abstract::setRedirect(string $url) */ PHP_METHOD(yaf_response, setRedirect) { char *url; uint url_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &url, &url_len) == FAILURE) { return; } if (!url_len) { RETURN_FALSE; } RETURN_BOOL(yaf_response_set_redirect(getThis(), url, url_len TSRMLS_CC)); } /* }}} */ /** {{{ proto public Yaf_Response_Abstract::setBody($body, $name = NULL) */ PHP_METHOD(yaf_response, setBody) { char *body, *name = NULL; uint body_len, name_len = 0; yaf_response_t *self; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s", &body, &body_len, &name, &name_len) == FAILURE) { return; } self = getThis(); if (yaf_response_alter_body(self, name, name_len, body, body_len, YAF_RESPONSE_REPLACE TSRMLS_CC)) { RETURN_ZVAL(self, 1, 0); } RETURN_FALSE; } /* }}} */ /** {{{ proto public Yaf_Response_Abstract::clearBody(string $name = NULL) */ PHP_METHOD(yaf_response, clearBody) { char *name = NULL; uint name_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &name, &name_len) == FAILURE) { return; } if (yaf_response_clear_body(getThis(), name, name_len TSRMLS_CC)) { RETURN_ZVAL(getThis(), 1, 0); } RETURN_FALSE; } /* }}} */ /** {{{ proto public Yaf_Response_Abstract::getBody(string $name = NULL) */ PHP_METHOD(yaf_response, getBody) { zval *body = NULL; zval *name = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z", &name) == FAILURE) { return; } if (!name) { body = yaf_response_get_body(getThis(), YAF_RESPONSE_PROPERTY_NAME_DEFAULTBODY, sizeof(YAF_RESPONSE_PROPERTY_NAME_DEFAULTBODY) - 1 TSRMLS_CC); } else { if (ZVAL_IS_NULL(name)) { body = yaf_response_get_body(getThis(), NULL, 0 TSRMLS_CC); } else { convert_to_string_ex(&name); body = yaf_response_get_body(getThis(), Z_STRVAL_P(name), Z_STRLEN_P(name) TSRMLS_CC); } } if (body) { RETURN_ZVAL(body, 1, 0); } RETURN_EMPTY_STRING(); } /* }}} */ /** {{{ proto public Yaf_Response_Abstract::response(void) */ PHP_METHOD(yaf_response, response) { RETURN_BOOL(yaf_response_send(getThis() TSRMLS_CC)); } /* }}} */ /** {{{ proto public Yaf_Response_Abstract::__toString(void) */ PHP_METHOD(yaf_response, __toString) { zval delim; zval *zbody = zend_read_property(yaf_response_ce, getThis(), ZEND_STRL(YAF_RESPONSE_PROPERTY_NAME_BODY), 1 TSRMLS_CC); ZVAL_EMPTY_STRING(&delim); php_implode(&delim, zbody, return_value TSRMLS_CC); zval_dtor(&delim); } /* }}} */ /** {{{ proto public Yaf_Response_Abstract::__clone(void) */ PHP_METHOD(yaf_response, __clone) { } /* }}} */ /** {{{ yaf_response_methods */ zend_function_entry yaf_response_methods[] = { PHP_ME(yaf_response, __construct, yaf_response_void_arginfo, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR) PHP_ME(yaf_response, __destruct, yaf_response_void_arginfo, ZEND_ACC_PUBLIC|ZEND_ACC_DTOR) PHP_ME(yaf_response, __clone, NULL, ZEND_ACC_PRIVATE) PHP_ME(yaf_response, __toString, NULL, ZEND_ACC_PUBLIC) PHP_ME(yaf_response, setBody, yaf_response_set_body_arginfo, ZEND_ACC_PUBLIC) PHP_ME(yaf_response, appendBody, yaf_response_set_body_arginfo, ZEND_ACC_PUBLIC) PHP_ME(yaf_response, prependBody, yaf_response_set_body_arginfo, ZEND_ACC_PUBLIC) PHP_ME(yaf_response, clearBody, yaf_response_clear_body_arginfo, ZEND_ACC_PUBLIC) PHP_ME(yaf_response, getBody, yaf_response_get_body_arginfo, ZEND_ACC_PUBLIC) PHP_ME(yaf_response, response, yaf_response_void_arginfo, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; /* }}} */ /** {{{ YAF_STARTUP_FUNCTION */ YAF_STARTUP_FUNCTION(response) { zend_class_entry ce; YAF_INIT_CLASS_ENTRY(ce, "Yaf_Response_Abstract", "Yaf\\Response_Abstract", yaf_response_methods); yaf_response_ce = zend_register_internal_class_ex(&ce, NULL, NULL TSRMLS_CC); yaf_response_ce->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; zend_declare_property_null(yaf_response_ce, ZEND_STRL(YAF_RESPONSE_PROPERTY_NAME_HEADER), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(yaf_response_ce, ZEND_STRL(YAF_RESPONSE_PROPERTY_NAME_BODY), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_bool(yaf_response_ce, ZEND_STRL(YAF_RESPONSE_PROPERTY_NAME_HEADEREXCEPTION), 0, ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_class_constant_stringl(yaf_response_ce, ZEND_STRL(YAF_RESPONSE_PROPERTY_NAME_DEFAULTBODYNAME), ZEND_STRL(YAF_RESPONSE_PROPERTY_NAME_DEFAULTBODY) TSRMLS_CC); YAF_STARTUP(response_http); YAF_STARTUP(response_cli); return SUCCESS; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
zxcvdavid/php-yaf
routes/yaf_route_simple.c
<reponame>zxcvdavid/php-yaf /* +----------------------------------------------------------------------+ | Yet Another Framework | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: <NAME> <<EMAIL>> | +----------------------------------------------------------------------+ */ /* $Id: simple.c 329200 2013-01-18 06:26:40Z laruence $ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_yaf.h" #include "yaf_namespace.h" #include "yaf_exception.h" #include "yaf_application.h" /* for yaf_application_is_module_name */ #include "yaf_request.h" #include "yaf_router.h" #include "routes/yaf_route_interface.h" #include "routes/yaf_route_simple.h" #include "ext/standard/php_smart_str.h" /* for smart_str */ zend_class_entry *yaf_route_simple_ce; /** {{{ ARG_INFO */ ZEND_BEGIN_ARG_INFO_EX(yaf_route_simple_construct_arginfo, 0, 0, 3) ZEND_ARG_INFO(0, module_name) ZEND_ARG_INFO(0, controller_name) ZEND_ARG_INFO(0, action_name) ZEND_END_ARG_INFO() /* }}} */ /** {{{ int yaf_route_simple_route(yaf_route_t *route, yaf_request_t *request TSRMLS_DC) */ int yaf_route_simple_route(yaf_route_t *route, yaf_request_t *request TSRMLS_DC) { zval *module, *controller, *action; zval *nmodule, *ncontroller, *naction; nmodule = zend_read_property(yaf_route_simple_ce, route, ZEND_STRL(YAF_ROUTE_SIMPLE_VAR_NAME_MODULE), 1 TSRMLS_CC); ncontroller = zend_read_property(yaf_route_simple_ce, route, ZEND_STRL(YAF_ROUTE_SIMPLE_VAR_NAME_CONTROLLER), 1 TSRMLS_CC); naction = zend_read_property(yaf_route_simple_ce, route, ZEND_STRL(YAF_ROUTE_SIMPLE_VAR_NAME_ACTION), 1 TSRMLS_CC); /* if there is no expect parameter in supervars, then null will be return */ module = yaf_request_query(YAF_GLOBAL_VARS_GET, Z_STRVAL_P(nmodule), Z_STRLEN_P(nmodule) TSRMLS_CC); controller = yaf_request_query(YAF_GLOBAL_VARS_GET, Z_STRVAL_P(ncontroller), Z_STRLEN_P(ncontroller) TSRMLS_CC); action = yaf_request_query(YAF_GLOBAL_VARS_GET, Z_STRVAL_P(naction), Z_STRLEN_P(naction) TSRMLS_CC); if (ZVAL_IS_NULL(module) && ZVAL_IS_NULL(controller) && ZVAL_IS_NULL(action)) { return 0; } if (Z_TYPE_P(module) == IS_STRING && yaf_application_is_module_name(Z_STRVAL_P(module), Z_STRLEN_P(module) TSRMLS_CC)) { zend_update_property(yaf_request_ce, request, ZEND_STRL(YAF_REQUEST_PROPERTY_NAME_MODULE), module TSRMLS_CC); } zend_update_property(yaf_request_ce, request, ZEND_STRL(YAF_REQUEST_PROPERTY_NAME_CONTROLLER), controller TSRMLS_CC); zend_update_property(yaf_request_ce, request, ZEND_STRL(YAF_REQUEST_PROPERTY_NAME_ACTION), action TSRMLS_CC); return 1; } /* }}} */ /** {{{ yaf_route_t * yaf_route_simple_instance(yaf_route_t *this_ptr, zval *module, zval *controller, zval *action TSRMLS_DC) */ yaf_route_t * yaf_route_simple_instance(yaf_route_t *this_ptr, zval *module, zval *controller, zval *action TSRMLS_DC) { yaf_route_t *instance; if (this_ptr) { instance = this_ptr; } else { MAKE_STD_ZVAL(instance); object_init_ex(instance, yaf_route_simple_ce); } zend_update_property(yaf_route_simple_ce, instance, ZEND_STRL(YAF_ROUTE_SIMPLE_VAR_NAME_MODULE), module TSRMLS_CC); zend_update_property(yaf_route_simple_ce, instance, ZEND_STRL(YAF_ROUTE_SIMPLE_VAR_NAME_CONTROLLER), controller TSRMLS_CC); zend_update_property(yaf_route_simple_ce, instance, ZEND_STRL(YAF_ROUTE_SIMPLE_VAR_NAME_ACTION), action TSRMLS_CC); return instance; } /* }}} */ /** {{{ proto public Yaf_Route_Simple::route(Yaf_Request $req) */ PHP_METHOD(yaf_route_simple, route) { yaf_request_t *request; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O", &request, yaf_request_ce) == FAILURE) { return; } else { RETURN_BOOL(yaf_route_simple_route(getThis(), request TSRMLS_CC)); } } /* }}} */ /** {{{ zval * yaf_route_simple_assemble(zval *mvc, zval *query TSRMLS_DC) */ zval * yaf_route_simple_assemble(yaf_route_t *this_ptr, zval *mvc, zval *query TSRMLS_DC) { smart_str tvalue = {0}; zval *nmodule, *ncontroller, *naction; zval *uri; MAKE_STD_ZVAL(uri); smart_str_appendc(&tvalue, '?'); nmodule = zend_read_property(yaf_route_simple_ce, this_ptr, ZEND_STRL(YAF_ROUTE_SIMPLE_VAR_NAME_MODULE), 1 TSRMLS_CC); ncontroller = zend_read_property(yaf_route_simple_ce, this_ptr, ZEND_STRL(YAF_ROUTE_SIMPLE_VAR_NAME_CONTROLLER), 1 TSRMLS_CC); naction = zend_read_property(yaf_route_simple_ce, this_ptr, ZEND_STRL(YAF_ROUTE_SIMPLE_VAR_NAME_ACTION), 1 TSRMLS_CC); do { zval **tmp; if (zend_hash_find(Z_ARRVAL_P(mvc), ZEND_STRS(YAF_ROUTE_ASSEMBLE_MOUDLE_FORMAT), (void **)&tmp) == SUCCESS) { smart_str_appendl(&tvalue, Z_STRVAL_P(nmodule), Z_STRLEN_P(nmodule)); smart_str_appendc(&tvalue, '='); smart_str_appendl(&tvalue, Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp)); smart_str_appendc(&tvalue, '&'); } if (zend_hash_find(Z_ARRVAL_P(mvc), ZEND_STRS(YAF_ROUTE_ASSEMBLE_CONTROLLER_FORMAT), (void **)&tmp) == FAILURE) { yaf_trigger_error(YAF_ERR_TYPE_ERROR TSRMLS_CC, "%s", "You need to specify the controller by ':c'"); break; } smart_str_appendl(&tvalue, Z_STRVAL_P(ncontroller), Z_STRLEN_P(ncontroller)); smart_str_appendc(&tvalue, '='); smart_str_appendl(&tvalue, Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp)); smart_str_appendc(&tvalue, '&'); if(zend_hash_find(Z_ARRVAL_P(mvc), ZEND_STRS(YAF_ROUTE_ASSEMBLE_ACTION_FORMAT), (void **)&tmp) == FAILURE) { yaf_trigger_error(YAF_ERR_TYPE_ERROR TSRMLS_CC, "%s", "You need to specify the action by ':a'"); break; } smart_str_appendl(&tvalue, Z_STRVAL_P(naction), Z_STRLEN_P(naction)); smart_str_appendc(&tvalue, '='); smart_str_appendl(&tvalue, Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp)); if (IS_ARRAY == Z_TYPE_P(query)) { uint key_len; char *key; ulong key_idx; for (zend_hash_internal_pointer_reset(Z_ARRVAL_P(query)); zend_hash_get_current_data(Z_ARRVAL_P(query), (void **)&tmp) == SUCCESS; zend_hash_move_forward(Z_ARRVAL_P(query))) { if (IS_STRING == Z_TYPE_PP(tmp) && HASH_KEY_IS_STRING == zend_hash_get_current_key_ex(Z_ARRVAL_P(query), &key, &key_len, &key_idx, 0, NULL)) { smart_str_appendc(&tvalue, '&'); smart_str_appendl(&tvalue, key, key_len - 1); smart_str_appendc(&tvalue, '='); smart_str_appendl(&tvalue, Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp)); } } } smart_str_0(&tvalue); ZVAL_STRING(uri, tvalue.c, 1); smart_str_free(&tvalue); return uri; } while (0); smart_str_free(&tvalue); ZVAL_NULL(uri); return uri; } /* }}} */ /** {{{ proto public Yaf_Route_Simple::__construct(string $module, string $controller, string $action) */ PHP_METHOD(yaf_route_simple, __construct) { zval *module, *controller, *action; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zzz", &module, &controller, &action) == FAILURE) { YAF_UNINITIALIZED_OBJECT(getThis()); return; } if (IS_STRING != Z_TYPE_P(module) || IS_STRING != Z_TYPE_P(controller) || IS_STRING != Z_TYPE_P(action)) { YAF_UNINITIALIZED_OBJECT(getThis()); yaf_trigger_error(YAF_ERR_TYPE_ERROR TSRMLS_CC, "Expect 3 string parameters", yaf_route_simple_ce->name); RETURN_FALSE; } else { (void)yaf_route_simple_instance(getThis(), module, controller, action TSRMLS_CC); } } /* }}} */ /** {{{ proto public Yaf_Route_Simple::assemble(array $mvc[, array $query = NULL]) */ PHP_METHOD(yaf_route_simple, assemble) { zval *mvc, *query; zval *return_uri; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|a", &mvc, &query) == FAILURE) { return; } else { if ((return_uri = yaf_route_simple_assemble(getThis(), mvc, query TSRMLS_CC))) { RETURN_ZVAL(return_uri, 0, 1); } } } /* }}} */ /** {{{ yaf_route_simple_methods */ zend_function_entry yaf_route_simple_methods[] = { PHP_ME(yaf_route_simple, __construct, yaf_route_simple_construct_arginfo, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR) PHP_ME(yaf_route_simple, route, yaf_route_route_arginfo, ZEND_ACC_PUBLIC) PHP_ME(yaf_route_simple, assemble, yaf_route_assemble_arginfo, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; /* }}} */ /** {{{ YAF_STARTUP_FUNCTION */ YAF_STARTUP_FUNCTION(route_simple) { zend_class_entry ce; YAF_INIT_CLASS_ENTRY(ce, "Yaf_Route_Simple", "Yaf\\Route\\Simple", yaf_route_simple_methods); yaf_route_simple_ce = zend_register_internal_class_ex(&ce, NULL, NULL TSRMLS_CC); zend_class_implements(yaf_route_simple_ce TSRMLS_CC, 1, yaf_route_ce); yaf_route_simple_ce->ce_flags |= ZEND_ACC_FINAL_CLASS; zend_declare_property_null(yaf_route_simple_ce, ZEND_STRL(YAF_ROUTE_SIMPLE_VAR_NAME_CONTROLLER), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(yaf_route_simple_ce, ZEND_STRL(YAF_ROUTE_SIMPLE_VAR_NAME_MODULE), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(yaf_route_simple_ce, ZEND_STRL(YAF_ROUTE_SIMPLE_VAR_NAME_ACTION), ZEND_ACC_PROTECTED TSRMLS_CC); return SUCCESS; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
zxcvdavid/php-yaf
yaf_exception.c
/* +----------------------------------------------------------------------+ | Yet Another Framework | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: <NAME> <<EMAIL>> | +----------------------------------------------------------------------+ */ /* $Id: yaf_exception.c 329197 2013-01-18 05:55:37Z laruence $ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "Zend/zend_exceptions.h" #include "php_yaf.h" #include "yaf_application.h" #include "yaf_namespace.h" #include "yaf_exception.h" zend_class_entry *yaf_ce_RuntimeException; zend_class_entry *yaf_exception_ce; zend_class_entry *yaf_buildin_exceptions[YAF_MAX_BUILDIN_EXCEPTION]; /** {{{void yaf_trigger_error(int type TSRMLS_DC, char *format, ...) */ void yaf_trigger_error(int type TSRMLS_DC, char *format, ...) { va_list args; char *message; uint msg_len; va_start(args, format); msg_len = vspprintf(&message, 0, format, args); va_end(args); if (YAF_G(throw_exception)) { #if PHP_MAJOR_VERSION == 5 && PHP_MINOR_VERSION < 3 if (!EG(exception)) { yaf_throw_exception(type, message TSRMLS_CC); } #else yaf_throw_exception(type, message TSRMLS_CC); #endif } else { yaf_application_t *app = zend_read_static_property(yaf_application_ce, ZEND_STRL(YAF_APPLICATION_PROPERTY_NAME_APP), 1 TSRMLS_CC); zend_update_property_long(yaf_application_ce, app, ZEND_STRL(YAF_APPLICATION_PROPERTY_NAME_ERRNO), type TSRMLS_CC); zend_update_property_stringl(yaf_application_ce, app, ZEND_STRL(YAF_APPLICATION_PROPERTY_NAME_ERRMSG), message, msg_len TSRMLS_CC); php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "%s", message); } efree(message); } /* }}} */ /** {{{ zend_class_entry * yaf_get_exception_base(int root TSRMLS_DC) */ zend_class_entry * yaf_get_exception_base(int root TSRMLS_DC) { #if can_handle_soft_dependency_on_SPL && defined(HAVE_SPL) && ((PHP_MAJOR_VERSION > 5) || (PHP_MAJOR_VERSION == 5 && PHP_MINOR_VERSION >= 1)) if (!root) { if (!spl_ce_RuntimeException) { zend_class_entry **pce; if (zend_hash_find(CG(class_table), "runtimeexception", sizeof("RuntimeException"), (void **) &pce) == SUCCESS) { spl_ce_RuntimeException = *pce; return *pce; } } else { return spl_ce_RuntimeException; } } #endif #if (PHP_MAJOR_VERSION == 5) && (PHP_MINOR_VERSION < 2) return zend_exception_get_default(); #else return zend_exception_get_default(TSRMLS_C); #endif } /* }}} */ /** {{{ void yaf_throw_exception(long code, char *message TSRMLS_DC) */ void yaf_throw_exception(long code, char *message TSRMLS_DC) { zend_class_entry *base_exception = yaf_exception_ce; if ((code & YAF_ERR_BASE) == YAF_ERR_BASE && yaf_buildin_exceptions[YAF_EXCEPTION_OFFSET(code)]) { base_exception = yaf_buildin_exceptions[YAF_EXCEPTION_OFFSET(code)]; } zend_throw_exception(base_exception, message, code TSRMLS_CC); } /* }}} */ #if ((PHP_MAJOR_VERSION == 5) && (PHP_MINOR_VERSION < 3)) || (PHP_MAJOR_VERSION < 5) /** {{{ proto Yaf_Exception::__construct($mesg = 0, $code = 0, Exception $previous = NULL) */ PHP_METHOD(yaf_exception, __construct) { char *message = NULL; zval *object, *previous = NULL; int message_len, code = 0; int argc = ZEND_NUM_ARGS(); if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "|slO!", &message, &message_len, &code, &previous, yaf_get_exception_base(0 TSRMLS_CC)) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Wrong parameters for Exception([string $exception [, long $code [, Exception $previous = NULL]]])"); } object = getThis(); if (message) { zend_update_property_string(Z_OBJCE_P(object), object, "message", sizeof("message")-1, message TSRMLS_CC); } if (code) { zend_update_property_long(Z_OBJCE_P(object), object, "code", sizeof("code")-1, code TSRMLS_CC); } if (previous) { zend_update_property(Z_OBJCE_P(object), object, ZEND_STRL("previous"), previous TSRMLS_CC); } } /* }}} */ /** {{{ proto Yaf_Exception::getPrevious(void) */ PHP_METHOD(yaf_exception, getPrevious) { zval *prev = zend_read_property(Z_OBJCE_P(getThis()), getThis(), ZEND_STRL("previous"), 1 TSRMLS_CC); RETURN_ZVAL(prev, 1, 0); } /* }}} */ #endif /** {{{ yaf_exception_methods */ zend_function_entry yaf_exception_methods[] = { #if ((PHP_MAJOR_VERSION == 5) && (PHP_MINOR_VERSION < 3)) || (PHP_MAJOR_VERSION < 5) PHP_ME(yaf_exception, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR) PHP_ME(yaf_exception, getPrevious, NULL, ZEND_ACC_PUBLIC) #endif {NULL, NULL, NULL} }; /* }}} */ /** {{{ YAF_STARTUP_FUNCTION */ YAF_STARTUP_FUNCTION(exception) { zend_class_entry ce; zend_class_entry startup_ce; zend_class_entry route_ce; zend_class_entry dispatch_ce; zend_class_entry loader_ce; zend_class_entry module_notfound_ce; zend_class_entry controller_notfound_ce; zend_class_entry action_notfound_ce; zend_class_entry view_notfound_ce; zend_class_entry type_ce; YAF_INIT_CLASS_ENTRY(ce, "Yaf_Exception", "Yaf\\Exception", yaf_exception_methods); yaf_exception_ce = zend_register_internal_class_ex(&ce, yaf_get_exception_base(0 TSRMLS_CC), NULL TSRMLS_CC); zend_declare_property_null(yaf_exception_ce, ZEND_STRL("message"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_long(yaf_exception_ce, ZEND_STRL("code"), 0, ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(yaf_exception_ce, ZEND_STRL("previous"), ZEND_ACC_PROTECTED TSRMLS_CC); YAF_INIT_CLASS_ENTRY(startup_ce, "Yaf_Exception_StartupError", "Yaf\\Exception\\StartupError", NULL); yaf_buildin_exceptions[YAF_EXCEPTION_OFFSET(YAF_ERR_STARTUP_FAILED)] = zend_register_internal_class_ex(&startup_ce, yaf_exception_ce, NULL TSRMLS_CC); YAF_INIT_CLASS_ENTRY(route_ce, "Yaf_Exception_RouterFailed", "Yaf\\Exception\\RouterFailed", NULL); yaf_buildin_exceptions[YAF_EXCEPTION_OFFSET(YAF_ERR_ROUTE_FAILED)] = zend_register_internal_class_ex(&route_ce, yaf_exception_ce, NULL TSRMLS_CC); YAF_INIT_CLASS_ENTRY(dispatch_ce, "Yaf_Exception_DispatchFailed", "Yaf\\Exception\\DispatchFailed", NULL); yaf_buildin_exceptions[YAF_EXCEPTION_OFFSET(YAF_ERR_DISPATCH_FAILED)] = zend_register_internal_class_ex(&dispatch_ce, yaf_exception_ce, NULL TSRMLS_CC); YAF_INIT_CLASS_ENTRY(loader_ce, "Yaf_Exception_LoadFailed", "Yaf\\Exception\\LoadFailed", NULL); yaf_buildin_exceptions[YAF_EXCEPTION_OFFSET(YAF_ERR_AUTOLOAD_FAILED)] = zend_register_internal_class_ex(&loader_ce, yaf_exception_ce, NULL TSRMLS_CC); YAF_INIT_CLASS_ENTRY(module_notfound_ce, "Yaf_Exception_LoadFailed_Module", "Yaf\\Exception\\LoadFailed\\Module", NULL); yaf_buildin_exceptions[YAF_EXCEPTION_OFFSET(YAF_ERR_NOTFOUND_MODULE)] = zend_register_internal_class_ex(&module_notfound_ce, yaf_buildin_exceptions[YAF_EXCEPTION_OFFSET(YAF_ERR_AUTOLOAD_FAILED)], NULL TSRMLS_CC); YAF_INIT_CLASS_ENTRY(controller_notfound_ce, "Yaf_Exception_LoadFailed_Controller", "Yaf\\Exception\\LoadFailed\\Controller", NULL); yaf_buildin_exceptions[YAF_EXCEPTION_OFFSET(YAF_ERR_NOTFOUND_CONTROLLER)] = zend_register_internal_class_ex(&controller_notfound_ce, yaf_buildin_exceptions[YAF_EXCEPTION_OFFSET(YAF_ERR_AUTOLOAD_FAILED)], NULL TSRMLS_CC); YAF_INIT_CLASS_ENTRY(action_notfound_ce, "Yaf_Exception_LoadFailed_Action", "Yaf\\Exception\\LoadFailed\\Action", NULL); yaf_buildin_exceptions[YAF_EXCEPTION_OFFSET(YAF_ERR_NOTFOUND_ACTION)] = zend_register_internal_class_ex(&action_notfound_ce, yaf_buildin_exceptions[YAF_EXCEPTION_OFFSET(YAF_ERR_AUTOLOAD_FAILED)], NULL TSRMLS_CC); YAF_INIT_CLASS_ENTRY(view_notfound_ce, "Yaf_Exception_LoadFailed_View", "Yaf\\Exception\\LoadFailed\\View", NULL); yaf_buildin_exceptions[YAF_EXCEPTION_OFFSET(YAF_ERR_NOTFOUND_VIEW)] = zend_register_internal_class_ex(&view_notfound_ce, yaf_buildin_exceptions[YAF_EXCEPTION_OFFSET(YAF_ERR_AUTOLOAD_FAILED)], NULL TSRMLS_CC); YAF_INIT_CLASS_ENTRY(type_ce, "Yaf_Exception_TypeError", "Yaf\\Exception\\TypeError", NULL); yaf_buildin_exceptions[YAF_EXCEPTION_OFFSET(YAF_ERR_TYPE_ERROR)] = zend_register_internal_class_ex(&type_ce, yaf_exception_ce, NULL TSRMLS_CC); return SUCCESS; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */