You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mynewt.apache.org by cc...@apache.org on 2016/07/08 21:19:48 UTC

[01/50] [abbrv] incubator-mynewt-core git commit: Modify on-flash structures in prep for lastblock change

Repository: incubator-mynewt-core
Updated Branches:
  refs/heads/master 8b3310892 -> 28e2a8b4e
  refs/heads/upf54 1fc36ccac -> 039c7f77b


Modify on-flash structures in prep for lastblock change

Change on-flash data structures including the addition of ndi_lastblock_id
in the nffs_disk_inode struct.  This field will store the last block of each
file for fast restores. That change is not enabled in this set of changes,
it will come in a subsequent commit.
Other changes include:
* Deleting the per inode/block magic number (ndi_magic, ndb_magic)
* Modifying the code to read in disk objects during restore and in ffs2native.
* Incrementing the filesystem version number stored in struct nffs_disk-area
* Add "-s" flag to ffs2native to parse NFFS flash area images (V1 format for now)


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/76e33d95
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/76e33d95
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/76e33d95

Branch: refs/heads/master
Commit: 76e33d9528b054ae2ca38be825d686018c2f6bf3
Parents: de23a8b
Author: Peter Snyder <gi...@peterfs.com>
Authored: Mon Jun 20 13:15:01 2016 -0700
Committer: Peter Snyder <gi...@peterfs.com>
Committed: Mon Jun 20 13:54:13 2016 -0700

----------------------------------------------------------------------
 apps/ffs2native/src/main.c            | 252 ++++++++++++++++++++++++-----
 fs/nffs/src/nffs_area.c               |   6 +
 fs/nffs/src/nffs_block.c              |   3 +-
 fs/nffs/src/nffs_file.c               |   2 +-
 fs/nffs/src/nffs_gc.c                 |   1 -
 fs/nffs/src/nffs_inode.c              |   6 +-
 fs/nffs/src/nffs_priv.h               |  55 ++++++-
 fs/nffs/src/nffs_restore.c            |  37 ++---
 fs/nffs/src/nffs_write.c              |   1 -
 fs/nffs/src/test/arch/sim/nffs_test.c |  24 ++-
 10 files changed, 308 insertions(+), 79 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/76e33d95/apps/ffs2native/src/main.c
----------------------------------------------------------------------
diff --git a/apps/ffs2native/src/main.c b/apps/ffs2native/src/main.c
index 9192f14..1796ca2 100644
--- a/apps/ffs2native/src/main.c
+++ b/apps/ffs2native/src/main.c
@@ -40,9 +40,19 @@
 #include <mcu/mcu_sim.h>
 #endif
 
+#include <stdlib.h>
+#include <fcntl.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+
+static struct log_handler nffs_log_console_handler;
+struct log nffs_log;
 static const char *copy_in_dir;
 static const char *progname;
 
+char *file_flash_area;
+int file_scratch_idx;
+
 #define MAX_AREAS	16
 static struct nffs_area_desc area_descs[MAX_AREAS];
 
@@ -79,6 +89,13 @@ print_inode_entry(struct nffs_inode_entry *inode_entry, int indent)
     int rc;
 
     rc = nffs_inode_from_entry(&inode, inode_entry);
+	/*
+	 * Dummy inode
+	 */
+	if (rc == FS_ENOENT) {
+		printf("    DUMMY %d\n", rc);
+		return;
+	}
     assert(rc == 0);
 
     nffs_flash_loc_expand(inode_entry->nie_hash_entry.nhe_flash_loc,
@@ -109,66 +126,68 @@ process_inode_entry(struct nffs_inode_entry *inode_entry, int indent)
 }
 
 static int
-print_nffs_inode(int idx, uint32_t off)
+print_nffs_inode(struct nffs_disk_inode *ndi, int idx, uint32_t off)
 {
-    struct nffs_disk_inode ndi;
     char filename[128];
     int len;
-    int rc;
-
-    rc = nffs_flash_read(idx, off, &ndi, sizeof(ndi));
-    assert(rc == 0);
+	int rc;
 
     memset(filename, 0, sizeof(filename));
-    len = min(sizeof(filename) - 1, ndi.ndi_filename_len);
-    rc = nffs_flash_read(idx, off + sizeof(ndi), filename, len);
-    printf("      %x-%d inode %d/%d %s\n",
-      off, ndi.ndi_filename_len, ndi.ndi_id, ndi.ndi_seq, filename);
-    return sizeof(ndi) + ndi.ndi_filename_len;
+    len = min(sizeof(filename) - 1, ndi->ndi_filename_len);
+    rc = nffs_flash_read(idx, off + sizeof(struct nffs_disk_inode),
+						 filename, len);
+    printf("      %x-%d inode %d/%d",
+      off, ndi->ndi_filename_len, ndi->ndi_id, ndi->ndi_seq);
+	if (rc == 0)
+		printf(" %s\n", filename);
+	else
+		printf("\n");
+    return (sizeof(struct nffs_disk_inode) + ndi->ndi_filename_len);
 }
 
 static int
-print_nffs_block(int idx, uint32_t off)
+print_nffs_block(struct nffs_disk_block *ndb, int idx, uint32_t off)
 {
-    struct nffs_disk_block ndb;
-    int rc;
-
-    rc = nffs_flash_read(idx, off, &ndb, sizeof(ndb));
-    assert(rc == 0);
-
     printf("      %x-%d block %u/%u belongs to %u\n",
-      off, ndb.ndb_data_len, ndb.ndb_id, ndb.ndb_seq, ndb.ndb_inode_id);
-    return sizeof(ndb) + ndb.ndb_data_len;
+      off, ndb->ndb_data_len, ndb->ndb_id, ndb->ndb_seq, ndb->ndb_inode_id);
+    return sizeof(struct nffs_disk_block) + ndb->ndb_data_len;
 }
 
 static int
 print_nffs_object(int idx, uint32_t off)
 {
-    uint32_t magic;
+	struct nffs_disk_object dobj;
     int rc;
 
-    rc = nffs_flash_read(idx, off, &magic, sizeof(magic));
+    rc = nffs_flash_read(idx, off, &dobj.ndo_un_obj, sizeof(dobj.ndo_un_obj));
     assert(rc == 0);
 
-    switch (magic) {
-    case NFFS_INODE_MAGIC:
-        return print_nffs_inode(idx, off);
+	if (nffs_hash_id_is_inode(dobj.ndo_disk_inode.ndi_id)) {
+        return print_nffs_inode(&dobj.ndo_disk_inode, idx, off);
 
-    case NFFS_BLOCK_MAGIC:
-        return print_nffs_block(idx, off);
-        break;
+	} else if (nffs_hash_id_is_block(dobj.ndo_disk_inode.ndi_id)) {
+        return print_nffs_block(&dobj.ndo_disk_block, idx, off);
 
-    case 0xffffffff:
-        assert(0);
+	} else if (dobj.ndo_disk_inode.ndi_id == NFFS_ID_NONE) {
+		assert(0);
         return 0;
 
-    default:
+	} else {
         printf("      %x Corruption\n", off);
-        return 1;
-    }
+		return 1;
+	}
 }
 
 static void
+print_nffs_darea(struct nffs_disk_area *darea)
+{
+	printf("\tdarea: len %d ver %d gc_seq %d id %x\n",
+		   darea->nda_length, darea->nda_ver,
+		   darea->nda_gc_seq, darea->nda_id);
+}
+
+
+static void
 print_nffs_area(int idx)
 {
     struct nffs_area *area;
@@ -179,10 +198,18 @@ print_nffs_area(int idx)
     area = &nffs_areas[idx];
     rc = nffs_flash_read(idx, 0, &darea, sizeof(darea));
     assert(rc == 0);
+	print_nffs_darea(&darea);
     if (!nffs_area_magic_is_set(&darea)) {
         printf("Area header corrupt!\n");
         return;
     }
+	/*
+	 * XXX Enhance to print but not restore unsupported formats
+	 */
+    if (!nffs_area_is_current_version(&darea)) {
+        printf("Area format is not supported!\n");
+        return;
+    }
     off = sizeof (struct nffs_disk_area);
     while (off < area->na_cur) {
         off += print_nffs_object(idx, off);
@@ -295,14 +322,137 @@ copy_in_directory(const char *src, const char *dst)
     closedir(dr);
 }
 
+static int
+file_flash_read(uint32_t addr, void *dst, int byte_cnt)
+{
+	memcpy(dst, (void*)file_flash_area + addr, byte_cnt);
+	return 0;
+}
+
+static int
+print_flash_inode(struct nffs_area_desc *area, uint32_t off)
+{
+    struct nffs_disk_inode ndi;
+    char filename[128];
+    int len;
+    int rc;
+
+    rc = file_flash_read(area->nad_offset + off, &ndi, sizeof(ndi));
+    assert(rc == 0);
+
+    memset(filename, 0, sizeof(filename));
+    len = min(sizeof(filename) - 1, ndi.ndi_filename_len);
+    rc = file_flash_read(area->nad_offset + off + sizeof(ndi), filename, len);
+
+	printf("  off %x flen %d %s id %x seq %d prnt %x lstb %x %s\n",
+		   off, ndi.ndi_filename_len,
+		   (nffs_hash_id_is_file(ndi.ndi_id) ? "File" :
+			(nffs_hash_id_is_dir(ndi.ndi_id) ? "Dir" : "???")),
+		   ndi.ndi_id, ndi.ndi_seq, ndi.ndi_parent_id,
+		   ndi.ndi_lastblock_id, filename);
+    return sizeof(ndi) + ndi.ndi_filename_len;
+}
+
+static int
+print_flash_block(struct nffs_area_desc *area, uint32_t off)
+{
+    struct nffs_disk_block ndb;
+    int rc;
+
+	rc = file_flash_read(area->nad_offset + off, &ndb, sizeof(ndb));
+    assert(rc == 0);
+
+    printf("  off %x len %d Block id %x seq %d prev %x own ino %x\n",
+		   off, ndb.ndb_data_len, ndb.ndb_id, ndb.ndb_seq,
+		   ndb.ndb_prev_id, ndb.ndb_inode_id);
+    return sizeof(ndb) + ndb.ndb_data_len;
+}
+
+static int
+print_flash_object(struct nffs_area_desc *area, uint32_t off)
+{
+    uint32_t magic;
+
+	file_flash_read(area->nad_offset + off, &magic, sizeof(magic));
+    switch (magic) {
+    case NFFS_INODE_MAGIC:
+        return print_flash_inode(area, off);
+
+    case NFFS_BLOCK_MAGIC:
+        return print_flash_block(area, off);
+        break;
+
+    case 0xffffffff:
+    default:
+        return 1;
+    }
+}
+
+void
+print_file_areas()
+{
+    struct nffs_area_desc *area;
+    int off;
+    int i;
+
+    for (i = 0; i < nffs_num_areas; i++) {
+		area = &area_descs[i];
+        printf("%d: id:%d 0x%x - 0x%x %s\n",
+			   i, area->nad_flash_id, area->nad_offset,
+			   area->nad_offset + area->nad_length,
+			   (i == file_scratch_idx ? "(scratch)" : ""));
+		off = sizeof (struct nffs_disk_area);
+		while (off < area->nad_length) {
+			off += print_flash_object(area, off);
+		}
+    }
+}
+
+int
+file_area_init(char *flash_area, size_t size)
+{
+	char *daptr;		/* Disk Area Pointer */
+	char *eoda;			/* End Of Disk Area */
+	struct nffs_disk_area *nda;
+	int nad_cnt = 0;	/* Nffs Area Descriptor count */
+
+	daptr = flash_area;
+	eoda = flash_area + size;
+	while (daptr < eoda) {
+		if (nffs_area_magic_is_set((struct nffs_disk_area*)daptr)) {
+			nda = (struct nffs_disk_area*)daptr;
+			area_descs[nad_cnt].nad_offset = (daptr - flash_area);
+			area_descs[nad_cnt].nad_length = nda->nda_length;
+			area_descs[nad_cnt].nad_flash_id = nda->nda_id;
+			if (nda->nda_id == 0xff)
+				file_scratch_idx = nad_cnt;
+			printf("area %d: off %d len %d flshid %x gc-seq %d id %x ver %d %s\n",
+				   nad_cnt,
+				   area_descs[nad_cnt].nad_offset,
+				   area_descs[nad_cnt].nad_length,
+				   area_descs[nad_cnt].nad_flash_id,
+				   nda->nda_gc_seq, nda->nda_id, nda->nda_ver,
+				   nda->nda_id == 0xff ? "(scratch)" : "");
+
+			nad_cnt++;
+			daptr = daptr + nda->nda_length;
+		} else {
+			daptr++;
+		}
+	}
+	nffs_num_areas = nad_cnt;
+	return 0;
+}
+
 static void
 usage(int rc)
 {
-    printf("%s [-c]|[-d dir][-f flash_file]\n", progname);
+    printf("%s [-c]|[-d dir][-s][-f flash_file]\n", progname);
     printf("  Tool for operating on simulator flash image file\n");
     printf("   -c: ...\n");
     printf("   -d: use dir as root for NFFS portion and create flash image\n");
     printf("   -f: flash_file is the name of the flash image file\n");
+    printf("   -s: use flash area layout in flash image file\n");
     exit(rc);
 }
 
@@ -310,13 +460,16 @@ int
 main(int argc, char **argv)
 {
     FILE *fp;
+	int fd;
     int rc;
     int ch;
     int cnt;
+	struct stat st;
+	int standalone = 0;
 
     progname = argv[0];
 
-    while ((ch = getopt(argc, argv, "c:d:f:")) != -1) {
+    while ((ch = getopt(argc, argv, "c:d:f:s")) != -1) {
         switch (ch) {
         case 'c':
             fp = fopen(optarg, "rb");
@@ -327,6 +480,9 @@ main(int argc, char **argv)
         case 'd':
             copy_in_dir = optarg;
             break;
+		case 's':
+			standalone++;
+			break;
         case 'f':
             native_flash_file = optarg;
             break;
@@ -337,8 +493,10 @@ main(int argc, char **argv)
     }
 
     os_init();
-    rc = flash_area_to_nffs_desc(FLASH_AREA_NFFS, &cnt, area_descs);
-    assert(rc == 0);
+	if (standalone == 0) {
+		rc = flash_area_to_nffs_desc(FLASH_AREA_NFFS, &cnt, area_descs);
+		assert(rc == 0);
+	}
 
     rc = hal_flash_init();
     assert(rc == 0);
@@ -346,6 +504,26 @@ main(int argc, char **argv)
     rc = nffs_init();
     assert(rc == 0);
 
+	log_init();
+	log_console_handler_init(&nffs_log_console_handler);
+	log_register("nffs-log", &nffs_log, &nffs_log_console_handler);
+
+	if (standalone) {
+		fd = open(native_flash_file, O_RDWR);
+		if ((rc = fstat(fd, &st)))
+			perror("fstat failed");
+		if ((file_flash_area = mmap(0, (size_t)8192, PROT_READ,
+							   MAP_FILE|MAP_SHARED, fd, 0)) == MAP_FAILED) {
+			perror("%s mmap failed");
+		}
+
+		rc = file_area_init(file_flash_area, st.st_size);
+
+		print_file_areas();
+
+		return 0;
+	}
+
     if (copy_in_dir) {
         /*
          * Build filesystem from contents of directory

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/76e33d95/fs/nffs/src/nffs_area.c
----------------------------------------------------------------------
diff --git a/fs/nffs/src/nffs_area.c b/fs/nffs/src/nffs_area.c
index c3b8fac..f389e77 100644
--- a/fs/nffs/src/nffs_area.c
+++ b/fs/nffs/src/nffs_area.c
@@ -47,6 +47,12 @@ nffs_area_is_scratch(const struct nffs_disk_area *disk_area)
            disk_area->nda_id == NFFS_AREA_ID_NONE;
 }
 
+int
+nffs_area_is_current_version(const struct nffs_disk_area *disk_area)
+{
+    return disk_area->nda_ver == NFFS_AREA_VER;
+}
+
 void
 nffs_area_to_disk(const struct nffs_area *area,
                   struct nffs_disk_area *out_disk_area)

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/76e33d95/fs/nffs/src/nffs_block.c
----------------------------------------------------------------------
diff --git a/fs/nffs/src/nffs_block.c b/fs/nffs/src/nffs_block.c
index 486670f..5d51e3b 100644
--- a/fs/nffs/src/nffs_block.c
+++ b/fs/nffs/src/nffs_block.c
@@ -94,7 +94,7 @@ nffs_block_read_disk(uint8_t area_idx, uint32_t area_offset,
     if (rc != 0) {
         return rc;
     }
-    if (out_disk_block->ndb_magic != NFFS_BLOCK_MAGIC) {
+    if (!nffs_hash_id_is_block(out_disk_block->ndb_id)) {
         return FS_EUNEXP;
     }
 
@@ -214,7 +214,6 @@ nffs_block_to_disk(const struct nffs_block *block,
 {
     assert(block->nb_inode_entry != NULL);
 
-    out_disk_block->ndb_magic = NFFS_BLOCK_MAGIC;
     out_disk_block->ndb_id = block->nb_hash_entry->nhe_id;
     out_disk_block->ndb_seq = block->nb_seq;
     out_disk_block->ndb_inode_id =

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/76e33d95/fs/nffs/src/nffs_file.c
----------------------------------------------------------------------
diff --git a/fs/nffs/src/nffs_file.c b/fs/nffs/src/nffs_file.c
index 6745df7..095bf21 100644
--- a/fs/nffs/src/nffs_file.c
+++ b/fs/nffs/src/nffs_file.c
@@ -87,7 +87,6 @@ nffs_file_new(struct nffs_inode_entry *parent, const char *filename,
     }
 
     memset(&disk_inode, 0xff, sizeof disk_inode);
-    disk_inode.ndi_magic = NFFS_INODE_MAGIC;
     if (is_dir) {
         disk_inode.ndi_id = nffs_hash_next_dir_id++;
     } else {
@@ -99,6 +98,7 @@ nffs_file_new(struct nffs_inode_entry *parent, const char *filename,
     } else {
         disk_inode.ndi_parent_id = parent->nie_hash_entry.nhe_id;
     }
+	disk_inode.ndi_lastblock_id = 0; /* will be NFFS_ID_NONE when implemented */
     disk_inode.ndi_filename_len = filename_len;
     nffs_crc_disk_inode_fill(&disk_inode, filename);
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/76e33d95/fs/nffs/src/nffs_gc.c
----------------------------------------------------------------------
diff --git a/fs/nffs/src/nffs_gc.c b/fs/nffs/src/nffs_gc.c
index 01882ea..2f6aa20 100644
--- a/fs/nffs/src/nffs_gc.c
+++ b/fs/nffs/src/nffs_gc.c
@@ -236,7 +236,6 @@ nffs_gc_block_chain_collate(struct nffs_hash_entry *last_entry,
      * block.
      */
     memset(&disk_block, 0, sizeof disk_block);
-    disk_block.ndb_magic = NFFS_BLOCK_MAGIC;
     disk_block.ndb_id = last_block.nb_hash_entry->nhe_id;
     disk_block.ndb_seq = last_block.nb_seq + 1;
     disk_block.ndb_inode_id = last_block.nb_inode_entry->nie_hash_entry.nhe_id;

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/76e33d95/fs/nffs/src/nffs_inode.c
----------------------------------------------------------------------
diff --git a/fs/nffs/src/nffs_inode.c b/fs/nffs/src/nffs_inode.c
index 8a6cee3..4b5a5a5 100644
--- a/fs/nffs/src/nffs_inode.c
+++ b/fs/nffs/src/nffs_inode.c
@@ -99,8 +99,8 @@ nffs_inode_read_disk(uint8_t area_idx, uint32_t offset,
                          sizeof *out_disk_inode);
     if (rc != 0) {
         return rc;
-    }
-    if (out_disk_inode->ndi_magic != NFFS_INODE_MAGIC) {
+	}
+	if (!nffs_hash_id_is_inode(out_disk_inode->ndi_id)) {
         return FS_EUNEXP;
     }
 
@@ -421,7 +421,6 @@ nffs_inode_delete_from_disk(struct nffs_inode *inode)
 
     inode->ni_seq++;
 
-    disk_inode.ndi_magic = NFFS_INODE_MAGIC;
     disk_inode.ndi_id = inode->ni_inode_entry->nie_hash_entry.nhe_id;
     disk_inode.ndi_seq = inode->ni_seq;
     disk_inode.ndi_parent_id = NFFS_ID_NONE;
@@ -541,7 +540,6 @@ nffs_inode_rename(struct nffs_inode_entry *inode_entry,
         return rc;
     }
 
-    disk_inode.ndi_magic = NFFS_INODE_MAGIC;
     disk_inode.ndi_id = inode_entry->nie_hash_entry.nhe_id;
     disk_inode.ndi_seq = inode.ni_seq + 1;
     disk_inode.ndi_parent_id = nffs_inode_parent_id(&inode);

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/76e33d95/fs/nffs/src/nffs_priv.h
----------------------------------------------------------------------
diff --git a/fs/nffs/src/nffs_priv.h b/fs/nffs/src/nffs_priv.h
index 4b54ae9..76c7827 100644
--- a/fs/nffs/src/nffs_priv.h
+++ b/fs/nffs/src/nffs_priv.h
@@ -48,7 +48,9 @@
 #define NFFS_INODE_MAGIC             0x925f8bc0
 
 #define NFFS_AREA_ID_NONE            0xff
-#define NFFS_AREA_VER                0
+#define NFFS_AREA_VER_0				 0
+#define NFFS_AREA_VER_1              1
+#define NFFS_AREA_VER                NFFS_AREA_VER_1
 #define NFFS_AREA_OFFSET_ID          23
 
 #define NFFS_SHORT_FILENAME_LEN      3
@@ -66,7 +68,7 @@ struct nffs_disk_area {
 };
 
 /** On-disk representation of an inode (file or directory). */
-struct nffs_disk_inode {
+struct nffs_disk_inodeV0 {
     uint32_t ndi_magic;         /* NFFS_INODE_MAGIC */
     uint32_t ndi_id;            /* Unique object ID. */
     uint32_t ndi_seq;           /* Sequence number; greater supersedes
@@ -78,10 +80,10 @@ struct nffs_disk_inode {
     /* Followed by filename. */
 };
 
-#define NFFS_DISK_INODE_OFFSET_CRC  18
+#define NFFS_DISK_INODEV0_OFFSET_CRC  18
 
 /** On-disk representation of a data block. */
-struct nffs_disk_block {
+struct nffs_disk_blockV0 {
     uint32_t ndb_magic;     /* NFFS_BLOCK_MAGIC */
     uint32_t ndb_id;        /* Unique object ID. */
     uint32_t ndb_seq;       /* Sequence number; greater supersedes lesser. */
@@ -93,7 +95,38 @@ struct nffs_disk_block {
     /* Followed by 'ndb_data_len' bytes of data. */
 };
 
-#define NFFS_DISK_BLOCK_OFFSET_CRC  20
+#define NFFS_DISK_BLOCKV0_OFFSET_CRC  22
+
+/** On-disk representation of an inode (file or directory). */
+struct nffs_disk_inode {
+    uint32_t ndi_id;            /* Unique object ID. */
+    uint32_t ndi_parent_id;     /* Object ID of parent directory inode. */
+    uint32_t ndi_lastblock_id;     /* Object ID of parent directory inode. */
+    uint16_t ndi_seq;           /* Sequence number; greater supersedes
+                                   lesser. */
+	uint16_t reserved16;
+    uint8_t reserved8;
+    uint8_t ndi_filename_len;   /* Length of filename, in bytes. */
+    uint16_t ndi_crc16;         /* Covers rest of header and filename. */
+    /* Followed by filename. */
+};
+
+#define NFFS_DISK_INODE_OFFSET_CRC  18
+
+/** On-disk representation of a data block. */
+struct nffs_disk_block {
+    uint32_t ndb_id;        /* Unique object ID. */
+    uint32_t ndb_inode_id;  /* Object ID of owning inode. */
+    uint32_t ndb_prev_id;   /* Object ID of previous block in file;
+                               NFFS_ID_NONE if this is the first block. */
+    uint16_t ndb_seq;       /* Sequence number; greater supersedes lesser. */
+    uint16_t reserved16;
+    uint16_t ndb_data_len;  /* Length of data contents, in bytes. */
+    uint16_t ndb_crc16;     /* Covers rest of header and data. */
+    /* Followed by 'ndb_data_len' bytes of data. */
+};
+
+#define NFFS_DISK_BLOCK_OFFSET_CRC  18
 
 /**
  * What gets stored in the hash table.  Each entry represents a data block or
@@ -163,9 +196,12 @@ struct nffs_disk_object {
     union {
         struct nffs_disk_inode ndo_disk_inode;
         struct nffs_disk_block ndo_disk_block;
-    };
+    } ndo_un_obj;
 };
 
+#define ndo_disk_inode	ndo_un_obj.ndo_disk_inode
+#define ndo_disk_block	ndo_un_obj.ndo_disk_block
+
 struct nffs_seek_info {
     struct nffs_block nsi_last_block;
     uint32_t nsi_block_file_off;
@@ -246,6 +282,7 @@ extern struct log nffs_log;
 /* @area */
 int nffs_area_magic_is_set(const struct nffs_disk_area *disk_area);
 int nffs_area_is_scratch(const struct nffs_disk_area *disk_area);
+int nffs_area_is_current_version(const struct nffs_disk_area *disk_area);
 void nffs_area_to_disk(const struct nffs_area *area,
                        struct nffs_disk_area *out_disk_area);
 uint32_t nffs_area_free_space(const struct nffs_area *area);
@@ -443,7 +480,13 @@ int nffs_write_to_file(struct nffs_file *file, const void *data, int len);
 
 #define NFFS_FLASH_LOC_NONE  nffs_flash_loc(NFFS_AREA_ID_NONE, 0)
 
+#ifdef NFFS_DEBUG
+#include <stdio.h>
+#define NFFS_LOG(lvl, ...) \
+  	printf(__VA_ARGS__)
+#else
 #define NFFS_LOG(lvl, ...) \
     LOG_ ## lvl(&nffs_log, LOG_MODULE_NFFS, __VA_ARGS__)
+#endif
 
 #endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/76e33d95/fs/nffs/src/nffs_restore.c
----------------------------------------------------------------------
diff --git a/fs/nffs/src/nffs_restore.c b/fs/nffs/src/nffs_restore.c
index 9289203..eb16c71 100644
--- a/fs/nffs/src/nffs_restore.c
+++ b/fs/nffs/src/nffs_restore.c
@@ -740,7 +740,6 @@ nffs_restore_object(const struct nffs_disk_object *disk_object)
         break;
 
     default:
-        assert(0);
         rc = FS_EINVAL;
         break;
     }
@@ -762,39 +761,27 @@ static int
 nffs_restore_disk_object(int area_idx, uint32_t area_offset,
                          struct nffs_disk_object *out_disk_object)
 {
-    uint32_t magic;
     int rc;
 
-    rc = nffs_flash_read(area_idx, area_offset, &magic, sizeof magic);
+    rc = nffs_flash_read(area_idx, area_offset,
+						 &out_disk_object->ndo_un_obj,
+						 sizeof(out_disk_object->ndo_un_obj));
     if (rc != 0) {
         return rc;
     }
 
-    switch (magic) {
-    case NFFS_INODE_MAGIC:
+	if (nffs_hash_id_is_inode(out_disk_object->ndo_disk_inode.ndi_id)) {
         out_disk_object->ndo_type = NFFS_OBJECT_TYPE_INODE;
-        rc = nffs_inode_read_disk(area_idx, area_offset,
-                                 &out_disk_object->ndo_disk_inode);
-        break;
 
-    case NFFS_BLOCK_MAGIC:
+	} else if (nffs_hash_id_is_block(out_disk_object->ndo_disk_block.ndb_id)) {
         out_disk_object->ndo_type = NFFS_OBJECT_TYPE_BLOCK;
-        rc = nffs_block_read_disk(area_idx, area_offset,
-                                 &out_disk_object->ndo_disk_block);
-        break;
 
-    case 0xffffffff:
-        rc = FS_EEMPTY;
-        break;
-
-    default:
-        rc = FS_ECORRUPT;
-        break;
-    }
+	} else if (out_disk_object->ndo_disk_block.ndb_id == NFFS_ID_NONE) {
+        return FS_EEMPTY;
 
-    if (rc != 0) {
-        return rc;
-    }
+	} else {
+		return FS_ECORRUPT;
+	}
 
     out_disk_object->ndo_area_idx = area_idx;
     out_disk_object->ndo_offset = area_offset;
@@ -896,6 +883,10 @@ nffs_restore_detect_one_area(uint8_t flash_id, uint32_t area_offset,
         return FS_ECORRUPT;
     }
 
+    if (!nffs_area_is_current_version(out_disk_area)) {
+        return FS_EUNEXP;
+    }
+
     return 0;
 }
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/76e33d95/fs/nffs/src/nffs_write.c
----------------------------------------------------------------------
diff --git a/fs/nffs/src/nffs_write.c b/fs/nffs/src/nffs_write.c
index 336be77..b888630 100644
--- a/fs/nffs/src/nffs_write.c
+++ b/fs/nffs/src/nffs_write.c
@@ -225,7 +225,6 @@ nffs_write_append(struct nffs_cache_inode *cache_inode, const void *data,
 
     inode_entry = cache_inode->nci_inode.ni_inode_entry;
 
-    disk_block.ndb_magic = NFFS_BLOCK_MAGIC;
     disk_block.ndb_id = nffs_hash_next_block_id++;
     disk_block.ndb_seq = 0;
     disk_block.ndb_inode_id = inode_entry->nie_hash_entry.nhe_id;

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/76e33d95/fs/nffs/src/test/arch/sim/nffs_test.c
----------------------------------------------------------------------
diff --git a/fs/nffs/src/test/arch/sim/nffs_test.c b/fs/nffs/src/test/arch/sim/nffs_test.c
index bf97ef8..ef9eaa6 100644
--- a/fs/nffs/src/test/arch/sim/nffs_test.c
+++ b/fs/nffs/src/test/arch/sim/nffs_test.c
@@ -434,7 +434,7 @@ nffs_test_assert_branch_touched(struct nffs_inode_entry *inode_entry)
             break;
         }
     }
-    TEST_ASSERT(i < nffs_test_num_touched_entries);
+	TEST_ASSERT(i < nffs_test_num_touched_entries);
     nffs_test_touched_entries[i] = NULL;
 
     if (nffs_hash_id_is_dir(inode_entry->nie_hash_entry.nhe_id)) {
@@ -1984,6 +1984,9 @@ TEST_CASE(nffs_test_incomplete_block)
     nffs_flash_loc_expand(block.nb_hash_entry->nhe_flash_loc, &area_idx,
                          &area_offset);
     flash_offset = nffs_areas[area_idx].na_offset + area_offset;
+	/*
+	 * Overwrite block data - the CRC check should pick this up
+	 */
     rc = flash_native_memset(
             flash_offset + sizeof (struct nffs_disk_block) + 2, 0xff, 2);
     TEST_ASSERT(rc == 0);
@@ -2034,7 +2037,9 @@ TEST_CASE(nffs_test_corrupt_block)
     uint32_t flash_offset;
     uint32_t area_offset;
     uint8_t area_idx;
+	uint8_t off;	/* offset to corrupt */
     int rc;
+	struct nffs_disk_block ndb;
 
     /*** Setup. */
     rc = nffs_format(nffs_area_descs);
@@ -2062,7 +2067,13 @@ TEST_CASE(nffs_test_corrupt_block)
     nffs_flash_loc_expand(block.nb_hash_entry->nhe_flash_loc, &area_idx,
                          &area_offset);
     flash_offset = nffs_areas[area_idx].na_offset + area_offset;
-    rc = flash_native_memset(flash_offset, 0x43, 4);
+
+	/*
+	 * Overwriting the reserved8 field should invalidate the CRC
+	 */
+	off = (char*)&ndb.reserved16 - (char*)&ndb;
+    rc = flash_native_memset(flash_offset + off, 0x43, 1);
+
     TEST_ASSERT(rc == 0);
 
     /* Write a fourth file. This file should get restored even though the
@@ -2205,7 +2216,8 @@ TEST_CASE(nffs_test_lost_found)
     uint32_t area_offset;
     uint8_t area_idx;
     int rc;
-
+	struct nffs_disk_inode ndi;
+	uint8_t off;	/* calculated offset for memset */
 
     /*** Setup. */
     rc = nffs_format(nffs_area_descs);
@@ -2229,7 +2241,11 @@ TEST_CASE(nffs_test_lost_found)
     nffs_flash_loc_expand(inode_entry->nie_hash_entry.nhe_flash_loc,
                          &area_idx, &area_offset);
     flash_offset = nffs_areas[area_idx].na_offset + area_offset;
-    rc = flash_native_memset(flash_offset + 10, 0xff, 1);
+	/*
+	 * Overwrite the sequence number - should be detected as CRC corruption
+	 */
+	off = (char*)&ndi.ndi_seq - (char*)&ndi;
+    rc = flash_native_memset(flash_offset + off, 0xff, 1);
     TEST_ASSERT(rc == 0);
 
     /* Clear cached data and restore from flash (i.e, simulate a reboot). */


[16/50] [abbrv] incubator-mynewt-core git commit: MYNEWT-273; hal - add prototype for bsp_hw_id().

Posted by cc...@apache.org.
MYNEWT-273; hal - add prototype for bsp_hw_id().

This should return unique ID for the BSP. Preferably serial
number of the MCU.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/b633dfb7
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/b633dfb7
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/b633dfb7

Branch: refs/heads/master
Commit: b633dfb7869f14d6502105ef0a0bfc012a76358b
Parents: e0c73d2
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Thu Jun 23 16:31:19 2016 -0700
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Thu Jun 23 16:37:53 2016 -0700

----------------------------------------------------------------------
 hw/hal/include/hal/hal_bsp.h | 9 +++++++++
 1 file changed, 9 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/b633dfb7/hw/hal/include/hal/hal_bsp.h
----------------------------------------------------------------------
diff --git a/hw/hal/include/hal/hal_bsp.h b/hw/hal/include/hal/hal_bsp.h
index 848a7c5..ae96789 100644
--- a/hw/hal/include/hal/hal_bsp.h
+++ b/hw/hal/include/hal/hal_bsp.h
@@ -48,6 +48,9 @@ int bsp_imgr_current_slot(void);
  */
 void *_sbrk(int incr);
 
+/*
+ * Report which memory areas should be included inside a coredump.
+ */
 struct bsp_mem_dump {
     void *bmd_start;
     uint32_t bmd_size;
@@ -55,6 +58,12 @@ struct bsp_mem_dump {
 
 const struct bsp_mem_dump *bsp_core_dump(int *area_cnt);
 
+/*
+ * Get unique HW identifier/serial number for platform.
+ * Returns the number of bytes filled in.
+ */
+int bsp_hw_id(uint8_t *id, int max_len);
+
 #ifdef __cplusplus
 }
 #endif


[11/50] [abbrv] incubator-mynewt-core git commit: BLE Host - Remove extra sec check on ATT write.

Posted by cc...@apache.org.
BLE Host - Remove extra sec check on ATT write.

This looks like a merge mistake.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/9a8d36e1
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/9a8d36e1
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/9a8d36e1

Branch: refs/heads/master
Commit: 9a8d36e17d6e2f3f4d7ba610092f5d9143752cbf
Parents: f664c50
Author: Christopher Collins <cc...@apache.org>
Authored: Wed Jun 22 10:45:44 2016 -0700
Committer: Christopher Collins <cc...@apache.org>
Committed: Wed Jun 22 10:45:44 2016 -0700

----------------------------------------------------------------------
 net/nimble/host/src/ble_att_svr.c | 5 -----
 1 file changed, 5 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/9a8d36e1/net/nimble/host/src/ble_att_svr.c
----------------------------------------------------------------------
diff --git a/net/nimble/host/src/ble_att_svr.c b/net/nimble/host/src/ble_att_svr.c
index 2e4e137..9315c7e 100644
--- a/net/nimble/host/src/ble_att_svr.c
+++ b/net/nimble/host/src/ble_att_svr.c
@@ -366,11 +366,6 @@ ble_att_svr_write(uint16_t conn_handle, struct ble_att_svr_entry *entry,
         }
     }
 
-    rc = ble_att_svr_check_security(conn_handle, 0, entry, &att_err);
-    if (rc != 0) {
-        goto err;
-    }
-
     BLE_HS_DBG_ASSERT(entry->ha_cb != NULL);
     rc = entry->ha_cb(conn_handle, entry->ha_handle_id,
                       entry->ha_uuid, BLE_ATT_ACCESS_OP_WRITE, ctxt,


[05/50] [abbrv] incubator-mynewt-core git commit: BLE Host - Return BLE_HS_ETIMEOUT_HCI on ack tmo.

Posted by cc...@apache.org.
BLE Host - Return BLE_HS_ETIMEOUT_HCI on ack tmo.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/b8b32326
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/b8b32326
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/b8b32326

Branch: refs/heads/master
Commit: b8b32326ccfcc1dfdef1b1d36051a4345e249c20
Parents: af6cb23
Author: Christopher Collins <cc...@apache.org>
Authored: Mon Jun 20 20:06:03 2016 -0700
Committer: Christopher Collins <cc...@apache.org>
Committed: Mon Jun 20 20:31:29 2016 -0700

----------------------------------------------------------------------
 net/nimble/host/include/host/ble_hs.h       |  1 +
 net/nimble/host/src/ble_hci_cmd.c           | 12 +++++++++++-
 net/nimble/host/src/test/ble_hs_conn_test.c |  2 +-
 net/nimble/host/src/test/ble_hs_test_util.c |  2 +-
 4 files changed, 14 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/b8b32326/net/nimble/host/include/host/ble_hs.h
----------------------------------------------------------------------
diff --git a/net/nimble/host/include/host/ble_hs.h b/net/nimble/host/include/host/ble_hs.h
index 1f46f6d..18eb588 100644
--- a/net/nimble/host/include/host/ble_hs.h
+++ b/net/nimble/host/include/host/ble_hs.h
@@ -53,6 +53,7 @@ struct os_event;
 #define BLE_HS_EREJECT              17
 #define BLE_HS_EUNKNOWN             18
 #define BLE_HS_EROLE                19
+#define BLE_HS_ETIMEOUT_HCI         20
 
 #define BLE_HS_ERR_ATT_BASE         0x100   /* 256 */
 #define BLE_HS_ATT_ERR(x)           ((x) ? BLE_HS_ERR_ATT_BASE + (x) : 0)

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/b8b32326/net/nimble/host/src/ble_hci_cmd.c
----------------------------------------------------------------------
diff --git a/net/nimble/host/src/ble_hci_cmd.c b/net/nimble/host/src/ble_hci_cmd.c
index 8580673..c41f038 100644
--- a/net/nimble/host/src/ble_hci_cmd.c
+++ b/net/nimble/host/src/ble_hci_cmd.c
@@ -199,7 +199,7 @@ ble_hci_cmd_wait_for_ack(void)
 
 #if PHONY_HCI_ACKS
     if (ble_hci_cmd_phony_ack_cb == NULL) {
-        rc = BLE_HS_ETIMEOUT;
+        rc = BLE_HS_ETIMEOUT_HCI;
     } else {
         BLE_HS_DBG_ASSERT(ble_hci_cmd_ack_ev == NULL);
         ble_hci_cmd_ack_ev = os_memblock_get(&g_hci_cmd_pool);
@@ -211,6 +211,16 @@ ble_hci_cmd_wait_for_ack(void)
     }
 #else
     rc = os_sem_pend(&ble_hci_cmd_sem, BLE_HCI_CMD_TIMEOUT);
+    switch (rc) {
+    case 0:
+        break;
+    case OS_TIMEOUT:
+        rc = BLE_HS_ETIMEOUT_HCI;
+        break;
+    default:
+        rc = BLE_HS_EOS;
+        break;
+    }
 #endif
 
     return rc;

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/b8b32326/net/nimble/host/src/test/ble_hs_conn_test.c
----------------------------------------------------------------------
diff --git a/net/nimble/host/src/test/ble_hs_conn_test.c b/net/nimble/host/src/test/ble_hs_conn_test.c
index c56efe0..5f86ad1 100644
--- a/net/nimble/host/src/test/ble_hs_conn_test.c
+++ b/net/nimble/host/src/test/ble_hs_conn_test.c
@@ -98,7 +98,7 @@ TEST_CASE(ble_hs_conn_test_direct_connect_hci_errors)
 
     /* Initiate connection; receive no HCI ack. */
     rc = ble_gap_conn_initiate(0, addr, NULL, NULL, NULL);
-    TEST_ASSERT(rc == BLE_HS_ETIMEOUT);
+    TEST_ASSERT(rc == BLE_HS_ETIMEOUT_HCI);
 
     TEST_ASSERT(!ble_gap_master_in_progress());
     TEST_ASSERT(!ble_hs_conn_test_util_any());

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/b8b32326/net/nimble/host/src/test/ble_hs_test_util.c
----------------------------------------------------------------------
diff --git a/net/nimble/host/src/test/ble_hs_test_util.c b/net/nimble/host/src/test/ble_hs_test_util.c
index 782d359..e2f28c7 100644
--- a/net/nimble/host/src/test/ble_hs_test_util.c
+++ b/net/nimble/host/src/test/ble_hs_test_util.c
@@ -245,7 +245,7 @@ ble_hs_test_util_phony_ack_cb(uint8_t *ack, int ack_buf_len)
     struct ble_hs_test_util_phony_ack *entry;
 
     if (ble_hs_test_util_num_phony_acks == 0) {
-        return BLE_HS_ETIMEOUT;
+        return BLE_HS_ETIMEOUT_HCI;
     }
 
     entry = ble_hs_test_util_phony_acks;


[30/50] [abbrv] incubator-mynewt-core git commit: Added BSP for RedBearLabs blenano with MK20 dev board based on nrf51dk

Posted by cc...@apache.org.
Added BSP for RedBearLabs blenano with MK20 dev board based on nrf51dk


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/165f463d
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/165f463d
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/165f463d

Branch: refs/heads/master
Commit: 165f463d0d98a7b933ad8cce1d6ba4dceb47b8aa
Parents: 8b33108
Author: Jan R�th <ru...@comsys.rwth-aachen.de>
Authored: Tue Jun 28 10:08:20 2016 +0200
Committer: Jan R�th <ru...@comsys.rwth-aachen.de>
Committed: Tue Jun 28 10:08:20 2016 +0200

----------------------------------------------------------------------
 hw/bsp/nrf51-blenano/boot-nrf51dk.ld            | 178 +++++++++++++
 hw/bsp/nrf51-blenano/cmsis-dap.cfg              |  12 +
 hw/bsp/nrf51-blenano/include/bsp/bsp.h          |  49 ++++
 hw/bsp/nrf51-blenano/include/bsp/bsp_sysid.h    |  36 +++
 hw/bsp/nrf51-blenano/include/bsp/cmsis_nvic.h   |  30 +++
 hw/bsp/nrf51-blenano/nrf51.cfg                  |  60 +++++
 hw/bsp/nrf51-blenano/nrf51dk.ld                 | 184 +++++++++++++
 hw/bsp/nrf51-blenano/nrf51dk_debug.sh           |  47 ++++
 hw/bsp/nrf51-blenano/nrf51dk_download.sh        | 107 ++++++++
 hw/bsp/nrf51-blenano/nrf51dk_no_boot.ld         | 179 +++++++++++++
 hw/bsp/nrf51-blenano/pkg.yml                    |  41 +++
 .../src/arch/cortex_m0/gcc_startup_nrf51.s      | 267 +++++++++++++++++++
 hw/bsp/nrf51-blenano/src/hal_bsp.c              |  46 ++++
 hw/bsp/nrf51-blenano/src/libc_stubs.c           |  85 ++++++
 hw/bsp/nrf51-blenano/src/os_bsp.c               |  78 ++++++
 hw/bsp/nrf51-blenano/src/sbrk.c                 |  53 ++++
 hw/bsp/nrf51-blenano/src/system_nrf51.c         | 121 +++++++++
 17 files changed, 1573 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/165f463d/hw/bsp/nrf51-blenano/boot-nrf51dk.ld
----------------------------------------------------------------------
diff --git a/hw/bsp/nrf51-blenano/boot-nrf51dk.ld b/hw/bsp/nrf51-blenano/boot-nrf51dk.ld
new file mode 100755
index 0000000..1d514a5
--- /dev/null
+++ b/hw/bsp/nrf51-blenano/boot-nrf51dk.ld
@@ -0,0 +1,178 @@
+/* Linker script for Nordic Semiconductor nRF5 devices
+ *
+ * Version: Sourcery G++ 4.5-1
+ * Support: https://support.codesourcery.com/GNUToolchain/
+ *
+ * Copyright (c) 2007, 2008, 2009, 2010 CodeSourcery, Inc.
+ *
+ * The authors hereby grant permission to use, copy, modify, distribute,
+ * and license this software and its documentation for any purpose, provided
+ * that existing copyright notices are retained in all copies and that this
+ * notice is included verbatim in any distributions.  No written agreement,
+ * license, or royalty fee is required for any of the authorized uses.
+ * Modifications to this software may be copyrighted by their authors
+ * and need not follow the licensing terms described here, provided that
+ * the new terms are clearly indicated on the first page of each file where
+ * they apply.
+ */
+OUTPUT_FORMAT ("elf32-littlearm", "elf32-bigarm", "elf32-littlearm")
+
+MEMORY
+{
+  FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 0x8000
+  RAM (rwx) :  ORIGIN = 0x20000000, LENGTH = 0x8000
+}
+
+/* Linker script to place sections and symbol values. Should be used together
+ * with other linker script that defines memory regions FLASH and RAM.
+ * It references following symbols, which must be defined in code:
+ *   Reset_Handler : Entry of reset handler
+ * 
+ * It defines following symbols, which code can use without definition:
+ *   __exidx_start
+ *   __exidx_end
+ *   __etext
+ *   __data_start__
+ *   __preinit_array_start
+ *   __preinit_array_end
+ *   __init_array_start
+ *   __init_array_end
+ *   __fini_array_start
+ *   __fini_array_end
+ *   __data_end__
+ *   __bss_start__
+ *   __bss_end__
+ *   __HeapBase
+ *   __HeapLimit
+ *   __StackLimit
+ *   __StackTop
+ *   __stack
+ *   __bssnz_start__
+ *   __bssnz_end__
+ */
+ENTRY(Reset_Handler)
+
+SECTIONS
+{
+    .text :
+    {
+        __isr_vector_start = .;
+        KEEP(*(.isr_vector))
+        __isr_vector_end = .;
+        *(.text*)
+
+        KEEP(*(.init))
+        KEEP(*(.fini))
+
+        /* .ctors */
+        *crtbegin.o(.ctors)
+        *crtbegin?.o(.ctors)
+        *(EXCLUDE_FILE(*crtend?.o *crtend.o) .ctors)
+        *(SORT(.ctors.*))
+        *(.ctors)
+
+        /* .dtors */
+        *crtbegin.o(.dtors)
+        *crtbegin?.o(.dtors)
+        *(EXCLUDE_FILE(*crtend?.o *crtend.o) .dtors)
+        *(SORT(.dtors.*))
+        *(.dtors)
+
+        *(.rodata*)
+
+        *(.eh_frame*)
+        . = ALIGN(4);
+    } > FLASH
+
+
+    .ARM.extab : 
+    {
+        *(.ARM.extab* .gnu.linkonce.armextab.*)
+        . = ALIGN(4);
+    } > FLASH
+
+    __exidx_start = .;
+    .ARM.exidx :
+    {
+        *(.ARM.exidx* .gnu.linkonce.armexidx.*)
+        . = ALIGN(4);
+    } > FLASH
+    __exidx_end = .;
+
+    __etext = .;
+
+    .vector_relocation :
+    {
+        . = ALIGN(4);
+        __vector_tbl_reloc__ = .;
+        . = . + (__isr_vector_end - __isr_vector_start);
+        . = ALIGN(4);
+    } > RAM
+            
+    .data : AT (__etext)
+    {
+        __data_start__ = .;
+        *(vtable)
+        *(.data*)
+
+        . = ALIGN(4);
+        /* preinit data */
+        PROVIDE_HIDDEN (__preinit_array_start = .);
+        *(.preinit_array)
+        PROVIDE_HIDDEN (__preinit_array_end = .);
+
+        . = ALIGN(4);
+        /* init data */
+        PROVIDE_HIDDEN (__init_array_start = .);
+        *(SORT(.init_array.*))
+        *(.init_array)
+        PROVIDE_HIDDEN (__init_array_end = .);
+
+
+        . = ALIGN(4);
+        /* finit data */
+        PROVIDE_HIDDEN (__fini_array_start = .);
+        *(SORT(.fini_array.*))
+        *(.fini_array)
+        PROVIDE_HIDDEN (__fini_array_end = .);
+
+        *(.jcr)
+        . = ALIGN(4);
+        /* All data end */
+        __data_end__ = .;
+    } > RAM
+
+    .bss :
+    {
+        . = ALIGN(4);
+        __bss_start__ = .;
+        *(.bss*)
+        *(COMMON)
+        . = ALIGN(4);
+        __bss_end__ = .;
+    } > RAM
+
+    /* Heap starts after BSS */
+    __HeapBase = .;
+
+    /* .stack_dummy section doesn't contains any symbols. It is only
+     * used for linker to calculate size of stack sections, and assign
+     * values to stack symbols later */
+    .stack_dummy (COPY):
+    {
+        *(.stack*)
+    } > RAM
+
+    /* Set stack top to end of RAM, and stack limit move down by
+     * size of stack_dummy section */
+    __StackTop = ORIGIN(RAM) + LENGTH(RAM);
+    __StackLimit = __StackTop - SIZEOF(.stack_dummy);
+    PROVIDE(__stack = __StackTop);
+
+    /* Top of head is the bottom of the stack */
+    __HeapLimit = __StackLimit;
+
+    /* Check if data + heap + stack exceeds RAM limit */
+    ASSERT(__HeapBase <= __HeapLimit, "region RAM overflowed with stack")
+}
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/165f463d/hw/bsp/nrf51-blenano/cmsis-dap.cfg
----------------------------------------------------------------------
diff --git a/hw/bsp/nrf51-blenano/cmsis-dap.cfg b/hw/bsp/nrf51-blenano/cmsis-dap.cfg
new file mode 100644
index 0000000..7251280
--- /dev/null
+++ b/hw/bsp/nrf51-blenano/cmsis-dap.cfg
@@ -0,0 +1,12 @@
+#
+# ARM CMSIS-DAP compliant adapter
+#
+# http://www.keil.com/support/man/docs/dapdebug/
+#
+
+interface cmsis-dap
+
+#set WORKAREASIZE 0x2000
+
+# Optionally specify the serial number of CMSIS-DAP usb device.
+#cmsis_dap_serial 02200201E6661E601B98E3B9

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/165f463d/hw/bsp/nrf51-blenano/include/bsp/bsp.h
----------------------------------------------------------------------
diff --git a/hw/bsp/nrf51-blenano/include/bsp/bsp.h b/hw/bsp/nrf51-blenano/include/bsp/bsp.h
new file mode 100644
index 0000000..520dd67
--- /dev/null
+++ b/hw/bsp/nrf51-blenano/include/bsp/bsp.h
@@ -0,0 +1,49 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+
+#ifndef H_BSP_H
+#define H_BSP_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Define special stackos sections */
+#define sec_data_core   __attribute__((section(".data.core")))
+#define sec_bss_core    __attribute__((section(".bss.core")))
+
+/* More convenient section placement macros. */
+#define bssnz_t
+
+/* LED pins */
+#define LED_BLINK_PIN   (19)
+
+/* UART info */
+#define CONSOLE_UART    0
+
+int bsp_imgr_current_slot(void);
+
+#define NFFS_AREA_MAX    (8)
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* H_BSP_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/165f463d/hw/bsp/nrf51-blenano/include/bsp/bsp_sysid.h
----------------------------------------------------------------------
diff --git a/hw/bsp/nrf51-blenano/include/bsp/bsp_sysid.h b/hw/bsp/nrf51-blenano/include/bsp/bsp_sysid.h
new file mode 100644
index 0000000..7b0a24b
--- /dev/null
+++ b/hw/bsp/nrf51-blenano/include/bsp/bsp_sysid.h
@@ -0,0 +1,36 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+#ifndef BSP_SYSID_H
+#define BSP_SYSID_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* stub until this BSP gets new HAL */
+enum system_device_id  
+{
+    RESERVED,
+};
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* BSP_SYSID_H */
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/165f463d/hw/bsp/nrf51-blenano/include/bsp/cmsis_nvic.h
----------------------------------------------------------------------
diff --git a/hw/bsp/nrf51-blenano/include/bsp/cmsis_nvic.h b/hw/bsp/nrf51-blenano/include/bsp/cmsis_nvic.h
new file mode 100644
index 0000000..fe7fc9a
--- /dev/null
+++ b/hw/bsp/nrf51-blenano/include/bsp/cmsis_nvic.h
@@ -0,0 +1,30 @@
+/* mbed Microcontroller Library - cmsis_nvic
+ * Copyright (c) 2009-2011 ARM Limited. All rights reserved.
+ *
+ * CMSIS-style functionality to support dynamic vectors
+ */
+
+#ifndef MBED_CMSIS_NVIC_H
+#define MBED_CMSIS_NVIC_H
+
+#include <stdint.h>
+
+/* NOTE: the nrf51 SoC has 26 interrupts. */
+#define NVIC_USER_IRQ_OFFSET  16
+#define NVIC_NUM_VECTORS      (NVIC_USER_IRQ_OFFSET + 26)
+
+#include "mcu/nrf51.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void NVIC_Relocate(void);
+void NVIC_SetVector(IRQn_Type IRQn, uint32_t vector);
+uint32_t NVIC_GetVector(IRQn_Type IRQn);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/165f463d/hw/bsp/nrf51-blenano/nrf51.cfg
----------------------------------------------------------------------
diff --git a/hw/bsp/nrf51-blenano/nrf51.cfg b/hw/bsp/nrf51-blenano/nrf51.cfg
new file mode 100644
index 0000000..280dd4f
--- /dev/null
+++ b/hw/bsp/nrf51-blenano/nrf51.cfg
@@ -0,0 +1,60 @@
+#
+# script for Nordic nRF51 series, a Cortex-M0 chip
+#
+
+source [find target/swj-dp.tcl]
+
+if { [info exists CHIPNAME] } {
+   set _CHIPNAME $CHIPNAME
+} else {
+   set _CHIPNAME nrf51
+}
+
+if { [info exists ENDIAN] } {
+   set _ENDIAN $ENDIAN
+} else {
+   set _ENDIAN little
+}
+
+# Work-area is a space in RAM used for flash programming
+# By default use 16kB
+if { [info exists WORKAREASIZE] } {
+   set _WORKAREASIZE $WORKAREASIZE
+} else {
+   set _WORKAREASIZE 0x4000
+}
+
+if { [info exists CPUTAPID] } {
+   set _CPUTAPID $CPUTAPID
+} else {
+   set _CPUTAPID 0x0bb11477
+}
+
+swj_newdap $_CHIPNAME cpu -expected-id $_CPUTAPID
+
+set _TARGETNAME $_CHIPNAME.cpu
+target create $_TARGETNAME cortex_m -chain-position $_TARGETNAME
+
+$_TARGETNAME configure -work-area-phys 0x20000000 -work-area-size $_WORKAREASIZE -work-area-backup 0
+
+if {![using_hla]} {
+   # The chip supports standard ARM/Cortex-M0 SYSRESETREQ signal
+   cortex_m reset_config sysresetreq
+}
+
+flash bank $_CHIPNAME.flash nrf51 0x00000000 0 1 1 $_TARGETNAME
+flash bank $_CHIPNAME.uicr nrf51 0x10001000 0 1 1 $_TARGETNAME
+
+#
+#  The chip should start up from internal 16Mhz RC, so setting adapter
+#  clock to 1Mhz should be OK
+#
+adapter_khz 1000
+
+proc enable_all_ram {} {
+	# nRF51822 Product Anomaly Notice (PAN) #16 explains that not all RAM banks
+	# are reliably enabled after reset on some revisions (contrary to spec.) So after
+	# resetting we enable all banks via the RAMON register
+	mww 0x40000524 0xF
+}
+$_TARGETNAME configure -event reset-end {  enable_all_ram }

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/165f463d/hw/bsp/nrf51-blenano/nrf51dk.ld
----------------------------------------------------------------------
diff --git a/hw/bsp/nrf51-blenano/nrf51dk.ld b/hw/bsp/nrf51-blenano/nrf51dk.ld
new file mode 100755
index 0000000..094f2c4
--- /dev/null
+++ b/hw/bsp/nrf51-blenano/nrf51dk.ld
@@ -0,0 +1,184 @@
+/* Linker script for Nordic Semiconductor nRF5 devices
+ *
+ * Version: Sourcery G++ 4.5-1
+ * Support: https://support.codesourcery.com/GNUToolchain/
+ *
+ * Copyright (c) 2007, 2008, 2009, 2010 CodeSourcery, Inc.
+ *
+ * The authors hereby grant permission to use, copy, modify, distribute,
+ * and license this software and its documentation for any purpose, provided
+ * that existing copyright notices are retained in all copies and that this
+ * notice is included verbatim in any distributions.  No written agreement,
+ * license, or royalty fee is required for any of the authorized uses.
+ * Modifications to this software may be copyrighted by their authors
+ * and need not follow the licensing terms described here, provided that
+ * the new terms are clearly indicated on the first page of each file where
+ * they apply.
+ */
+OUTPUT_FORMAT ("elf32-littlearm", "elf32-bigarm", "elf32-littlearm")
+
+MEMORY
+{
+  FLASH (rx) : ORIGIN = 0x00008000, LENGTH = 0x1b800
+  RAM (rwx) :  ORIGIN = 0x20000000, LENGTH = 0x8000
+}
+
+/* Linker script to place sections and symbol values. Should be used together
+ * with other linker script that defines memory regions FLASH and RAM.
+ * It references following symbols, which must be defined in code:
+ *   Reset_Handler : Entry of reset handler
+ *
+ * It defines following symbols, which code can use without definition:
+ *   __exidx_start
+ *   __exidx_end
+ *   __etext
+ *   __data_start__
+ *   __preinit_array_start
+ *   __preinit_array_end
+ *   __init_array_start
+ *   __init_array_end
+ *   __fini_array_start
+ *   __fini_array_end
+ *   __data_end__
+ *   __bss_start__
+ *   __bss_end__
+ *   __HeapBase
+ *   __HeapLimit
+ *   __StackLimit
+ *   __StackTop
+ *   __stack
+ *   __bssnz_start__
+ *   __bssnz_end__
+ */
+ENTRY(Reset_Handler)
+
+SECTIONS
+{
+    .imghdr (NOLOAD):
+    {
+    	. = . + 0x20;
+    } > FLASH
+
+    .text :
+    {
+        __isr_vector_start = .;
+        KEEP(*(.isr_vector))
+        __isr_vector_end = .;
+        *(.text*)
+
+        KEEP(*(.init))
+        KEEP(*(.fini))
+
+        /* .ctors */
+        *crtbegin.o(.ctors)
+        *crtbegin?.o(.ctors)
+        *(EXCLUDE_FILE(*crtend?.o *crtend.o) .ctors)
+        *(SORT(.ctors.*))
+        *(.ctors)
+
+        /* .dtors */
+        *crtbegin.o(.dtors)
+        *crtbegin?.o(.dtors)
+        *(EXCLUDE_FILE(*crtend?.o *crtend.o) .dtors)
+        *(SORT(.dtors.*))
+        *(.dtors)
+
+        *(.rodata*)
+
+        *(.eh_frame*)
+        . = ALIGN(4);
+    } > FLASH
+
+
+    .ARM.extab :
+    {
+        *(.ARM.extab* .gnu.linkonce.armextab.*)
+        . = ALIGN(4);
+    } > FLASH
+
+    __exidx_start = .;
+    .ARM.exidx :
+    {
+        *(.ARM.exidx* .gnu.linkonce.armexidx.*)
+        . = ALIGN(4);
+    } > FLASH
+    __exidx_end = .;
+
+    __etext = .;
+
+    /* Keep first in RAM, as well as in bootloader */
+    .vector_relocation :
+    {
+        . = ALIGN(4);
+        __vector_tbl_reloc__ = .;
+        . = . + (__isr_vector_end - __isr_vector_start);
+        . = ALIGN(4);
+    } > RAM
+
+    .data : AT (__etext)
+    {
+        __data_start__ = .;
+        *(vtable)
+        *(.data*)
+
+        . = ALIGN(4);
+        /* preinit data */
+        PROVIDE_HIDDEN (__preinit_array_start = .);
+        *(.preinit_array)
+        PROVIDE_HIDDEN (__preinit_array_end = .);
+
+        . = ALIGN(4);
+        /* init data */
+        PROVIDE_HIDDEN (__init_array_start = .);
+        *(SORT(.init_array.*))
+        *(.init_array)
+        PROVIDE_HIDDEN (__init_array_end = .);
+
+
+        . = ALIGN(4);
+        /* finit data */
+        PROVIDE_HIDDEN (__fini_array_start = .);
+        *(SORT(.fini_array.*))
+        *(.fini_array)
+        PROVIDE_HIDDEN (__fini_array_end = .);
+
+        *(.jcr)
+        . = ALIGN(4);
+        /* All data end */
+        __data_end__ = .;
+    } > RAM
+
+    .bss :
+    {
+        . = ALIGN(4);
+        __bss_start__ = .;
+        *(.bss*)
+        *(COMMON)
+        . = ALIGN(4);
+        __bss_end__ = .;
+    } > RAM
+
+    /* Heap starts after BSS */
+    __HeapBase = .;
+
+    /* .stack_dummy section doesn't contains any symbols. It is only
+     * used for linker to calculate size of stack sections, and assign
+     * values to stack symbols later */
+    .stack_dummy (COPY):
+    {
+        *(.stack*)
+    } > RAM
+
+    /* Set stack top to end of RAM, and stack limit move down by
+     * size of stack_dummy section */
+    __StackTop = ORIGIN(RAM) + LENGTH(RAM);
+    __StackLimit = __StackTop - SIZEOF(.stack_dummy);
+    PROVIDE(__stack = __StackTop);
+
+    /* Top of head is the bottom of the stack */
+    __HeapLimit = __StackLimit;
+
+    /* Check if data + heap + stack exceeds RAM limit */
+    ASSERT(__HeapBase <= __HeapLimit, "region RAM overflowed with stack")
+}
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/165f463d/hw/bsp/nrf51-blenano/nrf51dk_debug.sh
----------------------------------------------------------------------
diff --git a/hw/bsp/nrf51-blenano/nrf51dk_debug.sh b/hw/bsp/nrf51-blenano/nrf51dk_debug.sh
new file mode 100755
index 0000000..f090129
--- /dev/null
+++ b/hw/bsp/nrf51-blenano/nrf51dk_debug.sh
@@ -0,0 +1,47 @@
+#!/bin/sh
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+# Called: $0 <bsp_directory_path> <binary> [features...]
+#  - bsp_directory_path is absolute path to hw/bsp/bsp_name
+#  - binary is the path to prefix to target binary, .elf.bin appended to this
+#    name is the raw binary format of the binary.
+#  - features is the project identities string. So you can have e.g. different
+#    flash offset for bootloader 'feature'
+# 
+#
+if [ $# -lt 2 ]; then
+    echo "Need binary to download"
+    exit 1
+fi
+
+MYPATH=$1
+FILE_NAME=$2.elf
+GDB_CMD_FILE=.gdb_cmds
+
+echo "Debugging" $FILE_NAME
+
+set -m
+openocd -s $MYPATH -f cmsis-dap.cfg -f nrf51.cfg -c "nrf51.cpu configure -event gdb-detach {shutdown}" -c init -c "reset halt" &
+set +m
+
+echo "target remote localhost:3333" > $GDB_CMD_FILE
+
+arm-none-eabi-gdb -x $GDB_CMD_FILE $FILE_NAME
+
+rm $GDB_CMD_FILE
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/165f463d/hw/bsp/nrf51-blenano/nrf51dk_download.sh
----------------------------------------------------------------------
diff --git a/hw/bsp/nrf51-blenano/nrf51dk_download.sh b/hw/bsp/nrf51-blenano/nrf51dk_download.sh
new file mode 100755
index 0000000..7ba69f2
--- /dev/null
+++ b/hw/bsp/nrf51-blenano/nrf51dk_download.sh
@@ -0,0 +1,107 @@
+#!/bin/bash
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+# Called: $0 <bsp_directory_path> <binary> [features...]
+#  - bsp_directory_path is absolute path to hw/bsp/bsp_name
+#  - binary is the path to prefix to target binary, .elf.bin appended to this
+#    name is the raw binary format of the binary.
+#  - features is the project features string. So you can have e.g. different
+#    flash offset for bootloader 'feature'
+# 
+#
+if [ $# -lt 2 ]; then
+    echo "Need binary to download"
+    exit 1
+fi
+
+IS_BOOTLOADER=0
+MYPAH=$1
+BASENAME=$2
+#JLINK_SCRIPT=.download.jlink
+GDB_CMD_FILE=.gdb_cmds
+
+# Look for 'bootloader' from 3rd arg onwards
+shift
+shift
+while [ $# -gt 0 ]; do
+    if [ $1 = "bootloader" ]; then
+	IS_BOOTLOADER=1
+    fi
+    shift
+done
+
+if [ $IS_BOOTLOADER -eq 1 ]; then
+    FLASH_OFFSET=0x0
+    FILE_NAME=$BASENAME.elf.bin
+else
+    FLASH_OFFSET=0x8000
+    FILE_NAME=$BASENAME.img
+fi
+
+echo "Downloading" $FILE_NAME "to" $FLASH_OFFSET
+
+# XXX for some reason JLinkExe overwrites flash at offset 0 when
+# downloading somewhere in the flash. So need to figure out how to tell it
+# not to do that, or report failure if gdb fails to write this file
+#
+echo "shell /bin/sh -c 'trap \"\" 2;openocd -s $MYPAH -f cmsis-dap.cfg -f nrf51.cfg' &" > $GDB_CMD_FILE
+echo "target remote localhost:3333" >> $GDB_CMD_FILE
+echo "monitor reset halt" >> $GDB_CMD_FILE
+echo "monitor flash write_image erase $FILE_NAME $FLASH_OFFSET" >> $GDB_CMD_FILE
+echo "monitor reset run" >> $GDB_CMD_FILE
+echo "monitor shutdown" >> $GDB_CMD_FILE
+echo "quit" >> $GDB_CMD_FILE
+
+msgs=`arm-none-eabi-gdb -x $GDB_CMD_FILE 2>&1`
+echo $msgs > .gdb_out
+
+rm $GDB_CMD_FILE
+
+#cat > $JLINK_SCRIPT <<EOF
+#w 4001e504 1
+#loadbin $FILE_NAME,$FLASH_OFFSET
+#q
+#EOF
+
+#msgs=`JLinkExe -device nRF51422_xxAC -speed 4000 -if SWD $JLINK_SCRIPT`
+
+# Echo output from script run, so newt can show it if things go wrong.
+echo $msgs
+#rm $JLINK_SCRIPT
+
+error=`echo $msgs | grep error | grep -v Ignoring`
+if [ -n "$error" ]; then
+    exit 1
+fi
+
+error=`echo $msgs | grep -i failed`
+if [ -n "$error" ]; then
+    exit 1
+fi
+
+error=`echo $msgs | grep -i "unknown / supported"`
+if [ -n "$error" ]; then
+    exit 1
+fi
+
+error=`echo $msgs | grep -i "not found"`
+if [ -n "$error" ]; then
+    exit 1
+fi
+
+exit 0

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/165f463d/hw/bsp/nrf51-blenano/nrf51dk_no_boot.ld
----------------------------------------------------------------------
diff --git a/hw/bsp/nrf51-blenano/nrf51dk_no_boot.ld b/hw/bsp/nrf51-blenano/nrf51dk_no_boot.ld
new file mode 100755
index 0000000..b5547fc
--- /dev/null
+++ b/hw/bsp/nrf51-blenano/nrf51dk_no_boot.ld
@@ -0,0 +1,179 @@
+/* Linker script for Nordic Semiconductor nRF5 devices
+ *
+ * Version: Sourcery G++ 4.5-1
+ * Support: https://support.codesourcery.com/GNUToolchain/
+ *
+ * Copyright (c) 2007, 2008, 2009, 2010 CodeSourcery, Inc.
+ *
+ * The authors hereby grant permission to use, copy, modify, distribute,
+ * and license this software and its documentation for any purpose, provided
+ * that existing copyright notices are retained in all copies and that this
+ * notice is included verbatim in any distributions.  No written agreement,
+ * license, or royalty fee is required for any of the authorized uses.
+ * Modifications to this software may be copyrighted by their authors
+ * and need not follow the licensing terms described here, provided that
+ * the new terms are clearly indicated on the first page of each file where
+ * they apply.
+ */
+OUTPUT_FORMAT ("elf32-littlearm", "elf32-bigarm", "elf32-littlearm")
+
+MEMORY
+{
+  FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 0x40000
+  RAM (rwx) :  ORIGIN = 0x20000000, LENGTH = 0x8000
+}
+
+/* Linker script to place sections and symbol values. Should be used together
+ * with other linker script that defines memory regions FLASH and RAM.
+ * It references following symbols, which must be defined in code:
+ *   Reset_Handler : Entry of reset handler
+ * 
+ * It defines following symbols, which code can use without definition:
+ *   __exidx_start
+ *   __exidx_end
+ *   __etext
+ *   __data_start__
+ *   __preinit_array_start
+ *   __preinit_array_end
+ *   __init_array_start
+ *   __init_array_end
+ *   __fini_array_start
+ *   __fini_array_end
+ *   __data_end__
+ *   __bss_start__
+ *   __bss_end__
+ *   __HeapBase
+ *   __HeapLimit
+ *   __StackLimit
+ *   __StackTop
+ *   __stack
+ *   __bssnz_start__
+ *   __bssnz_end__
+ */
+ENTRY(Reset_Handler)
+
+SECTIONS
+{
+    .text :
+    {
+        __isr_vector_start = .;
+        KEEP(*(.isr_vector))
+        __isr_vector_end = .;
+        *(.text*)
+
+        KEEP(*(.init))
+        KEEP(*(.fini))
+
+        /* .ctors */
+        *crtbegin.o(.ctors)
+        *crtbegin?.o(.ctors)
+        *(EXCLUDE_FILE(*crtend?.o *crtend.o) .ctors)
+        *(SORT(.ctors.*))
+        *(.ctors)
+
+        /* .dtors */
+        *crtbegin.o(.dtors)
+        *crtbegin?.o(.dtors)
+        *(EXCLUDE_FILE(*crtend?.o *crtend.o) .dtors)
+        *(SORT(.dtors.*))
+        *(.dtors)
+
+        *(.rodata*)
+
+        *(.eh_frame*)
+        . = ALIGN(4);
+    } > FLASH
+
+
+    .ARM.extab : 
+    {
+        *(.ARM.extab* .gnu.linkonce.armextab.*)
+        . = ALIGN(4);
+    } > FLASH
+
+    __exidx_start = .;
+    .ARM.exidx :
+    {
+        *(.ARM.exidx* .gnu.linkonce.armexidx.*)
+        . = ALIGN(4);
+    } > FLASH
+    __exidx_end = .;
+
+    __etext = .;
+
+    /* Keep first in RAM, as well as in bootloader */
+    .vector_relocation :
+    {
+        . = ALIGN(4);
+        __vector_tbl_reloc__ = .;
+        . = . + (__isr_vector_end - __isr_vector_start);
+        . = ALIGN(4);
+    } > RAM
+            
+    .data : AT (__etext)
+    {
+        __data_start__ = .;
+        *(vtable)
+        *(.data*)
+
+        . = ALIGN(4);
+        /* preinit data */
+        PROVIDE_HIDDEN (__preinit_array_start = .);
+        *(.preinit_array)
+        PROVIDE_HIDDEN (__preinit_array_end = .);
+
+        . = ALIGN(4);
+        /* init data */
+        PROVIDE_HIDDEN (__init_array_start = .);
+        *(SORT(.init_array.*))
+        *(.init_array)
+        PROVIDE_HIDDEN (__init_array_end = .);
+
+
+        . = ALIGN(4);
+        /* finit data */
+        PROVIDE_HIDDEN (__fini_array_start = .);
+        *(SORT(.fini_array.*))
+        *(.fini_array)
+        PROVIDE_HIDDEN (__fini_array_end = .);
+
+        *(.jcr)
+        . = ALIGN(4);
+        /* All data end */
+        __data_end__ = .;
+    } > RAM
+
+    .bss :
+    {
+        . = ALIGN(4);
+        __bss_start__ = .;
+        *(.bss*)
+        *(COMMON)
+        . = ALIGN(4);
+        __bss_end__ = .;
+    } > RAM
+
+    /* Heap starts after BSS */
+    __HeapBase = .;
+
+    /* .stack_dummy section doesn't contains any symbols. It is only
+     * used for linker to calculate size of stack sections, and assign
+     * values to stack symbols later */
+    .stack_dummy (COPY):
+    {
+        *(.stack*)
+    } > RAM
+
+    /* Set stack top to end of RAM, and stack limit move down by
+     * size of stack_dummy section */
+    __StackTop = ORIGIN(RAM) + LENGTH(RAM);
+    __StackLimit = __StackTop - SIZEOF(.stack_dummy);
+    PROVIDE(__stack = __StackTop);
+
+    /* Top of head is the bottom of the stack */
+    __HeapLimit = __StackLimit;
+
+    /* Check if data + heap + stack exceeds RAM limit */
+    ASSERT(__HeapBase <= __HeapLimit, "region RAM overflowed with stack")
+}
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/165f463d/hw/bsp/nrf51-blenano/pkg.yml
----------------------------------------------------------------------
diff --git a/hw/bsp/nrf51-blenano/pkg.yml b/hw/bsp/nrf51-blenano/pkg.yml
new file mode 100644
index 0000000..ea41d92
--- /dev/null
+++ b/hw/bsp/nrf51-blenano/pkg.yml
@@ -0,0 +1,41 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+
+pkg.name: hw/bsp/nrf51-blenano
+pkg.type: bsp
+pkg.description: BSP definition for the RedBearLabs BLE Nano with 32kB flash based on Nordic nRF51.
+pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org> adapted by Jan R�th <ru...@comsys.rwth-aachen.de>"
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+    - nrf51
+    - mk20
+    - blenano
+
+pkg.arch: cortex_m0
+pkg.compiler: compiler/arm-none-eabi-m0
+pkg.linkerscript: "nrf51dk.ld"
+pkg.linkerscript.bootloader.OVERWRITE: "boot-nrf51dk.ld"
+pkg.downloadscript: nrf51dk_download.sh
+pkg.debugscript: nrf51dk_debug.sh
+pkg.cflags: -DNRF51
+pkg.deps:
+    - hw/mcu/nordic/nrf51xxx
+    - libs/baselibc
+pkg.deps.BLE_DEVICE:
+    - net/nimble/drivers/nrf51

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/165f463d/hw/bsp/nrf51-blenano/src/arch/cortex_m0/gcc_startup_nrf51.s
----------------------------------------------------------------------
diff --git a/hw/bsp/nrf51-blenano/src/arch/cortex_m0/gcc_startup_nrf51.s b/hw/bsp/nrf51-blenano/src/arch/cortex_m0/gcc_startup_nrf51.s
new file mode 100755
index 0000000..431849d
--- /dev/null
+++ b/hw/bsp/nrf51-blenano/src/arch/cortex_m0/gcc_startup_nrf51.s
@@ -0,0 +1,267 @@
+/*
+Copyright (c) 2015, Nordic Semiconductor ASA
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this
+  list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright notice,
+  this list of conditions and the following disclaimer in the documentation
+  and/or other materials provided with the distribution.
+
+* Neither the name of Nordic Semiconductor ASA nor the names of its
+  contributors may be used to endorse or promote products derived from
+  this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/*
+NOTE: Template files (including this one) are application specific and therefore
+expected to be copied into the application project folder prior to its use!
+*/
+
+    .syntax unified
+    .arch armv6-m
+
+    .section .stack
+    .align 3
+    .equ    Stack_Size, 432
+    .globl    __StackTop
+    .globl    __StackLimit
+__StackLimit:
+    .space    Stack_Size
+    .size __StackLimit, . - __StackLimit
+__StackTop:
+    .size __StackTop, . - __StackTop
+
+    .section .heap
+    .align 3
+#ifdef __HEAP_SIZE
+    .equ    Heap_Size, __HEAP_SIZE
+#else
+    .equ    Heap_Size, 0
+#endif
+    .globl    __HeapBase
+    .globl    __HeapLimit
+__HeapBase:
+    .if    Heap_Size
+    .space    Heap_Size
+    .endif
+    .size __HeapBase, . - __HeapBase
+__HeapLimit:
+    .size __HeapLimit, . - __HeapLimit
+
+    .section .isr_vector
+    .align 2
+    .globl __isr_vector
+__isr_vector:
+    .long    __StackTop                 /* Top of Stack */
+    .long   Reset_Handler               /* Reset Handler */
+    .long   _NMI_Handler                /* NMI Handler */
+    .long   _HardFault_Handler          /* Hard Fault Handler */
+    .long   0                           /* Reserved */
+    .long   0                           /* Reserved */
+    .long   0                           /* Reserved */
+    .long   0                           /* Reserved */
+    .long   0                           /* Reserved */
+    .long   0                           /* Reserved */
+    .long   0                           /* Reserved */
+    .long   _SVC_Handler                /* SVCall Handler */
+    .long   0                           /* Reserved */
+    .long   0                           /* Reserved */
+    .long   _PendSV_Handler             /* PendSV Handler */
+    .long   _SysTick_Handler            /* SysTick Handler */
+
+  /* External Interrupts */
+    .long   _POWER_CLOCK_IRQHandler
+    .long   _RADIO_IRQHandler
+    .long   _UART0_IRQHandler
+    .long   _SPI0_TWI0_IRQHandler
+    .long   _SPI1_TWI1_IRQHandler
+    .long   0                         /*Reserved */
+    .long   _GPIOTE_IRQHandler
+    .long   _ADC_IRQHandler
+    .long   _TIMER0_IRQHandler
+    .long   _TIMER1_IRQHandler
+    .long   _TIMER2_IRQHandler
+    .long   _RTC0_IRQHandler
+    .long   _TEMP_IRQHandler
+    .long   _RNG_IRQHandler
+    .long   _ECB_IRQHandler
+    .long   _CCM_AAR_IRQHandler
+    .long   _WDT_IRQHandler
+    .long   _RTC1_IRQHandler
+    .long   _QDEC_IRQHandler
+    .long   _LPCOMP_IRQHandler
+    .long   _SWI0_IRQHandler
+    .long   _SWI1_IRQHandler
+    .long   _SWI2_IRQHandler
+    .long   _SWI3_IRQHandler
+    .long   _SWI4_IRQHandler
+    .long   _SWI5_IRQHandler
+    .long   0                         /*Reserved */
+    .long   0                         /*Reserved */
+    .long   0                         /*Reserved */
+    .long   0                         /*Reserved */
+    .long   0                         /*Reserved */
+    .long   0                         /*Reserved */
+
+    .size    __isr_vector, . - __isr_vector
+
+/* Reset Handler */
+
+    .equ    NRF_POWER_RAMON_ADDRESS,             0x40000524
+    .equ    NRF_POWER_RAMONB_ADDRESS,            0x40000554
+    .equ    NRF_POWER_RAMONx_RAMxON_ONMODE_Msk,  0x3
+
+    .text
+    .thumb
+    .thumb_func
+    .align 1
+    .globl    Reset_Handler
+    .type    Reset_Handler, %function
+Reset_Handler:
+    .fnstart
+
+/* Make sure ALL RAM banks are powered on */
+    MOVS    R1, #NRF_POWER_RAMONx_RAMxON_ONMODE_Msk
+
+    LDR     R0, =NRF_POWER_RAMON_ADDRESS
+    LDR     R2, [R0]
+    ORRS    R2, R1
+    STR     R2, [R0]
+
+    LDR     R0, =NRF_POWER_RAMONB_ADDRESS
+    LDR     R2, [R0]
+    ORRS    R2, R1
+    STR     R2, [R0]
+
+/*     Loop to copy data from read only memory to RAM. The ranges
+ *      of copy from/to are specified by following symbols evaluated in
+ *      linker script.
+ *      __etext: End of code section, i.e., begin of data sections to copy from.
+ *      __data_start__/__data_end__: RAM address range that data should be
+ *      copied to. Both must be aligned to 4 bytes boundary.  */
+
+    ldr    r1, =__etext
+    ldr    r2, =__data_start__
+    ldr    r3, =__data_end__
+
+    subs    r3, r2
+    ble     .LC0
+
+.LC1:
+    subs    r3, 4
+    ldr    r0, [r1,r3]
+    str    r0, [r2,r3]
+    bgt    .LC1
+.LC0:
+
+    LDR     R0, =SystemInit
+    BLX     R0
+    LDR     R0, =_start
+    BX      R0
+
+    .pool
+    .cantunwind
+    .fnend
+    .size   Reset_Handler,.-Reset_Handler
+
+    .section ".text"
+
+
+/* Dummy Exception Handlers (infinite loops which can be modified) */
+
+    .weak   NMI_Handler
+    .type   NMI_Handler, %function
+NMI_Handler:
+    B       .
+    .size   NMI_Handler, . - NMI_Handler
+
+    .weak   SVC_Handler
+    .type   SVC_Handler, %function
+SVC_Handler:
+    B       .
+    .size   SVC_Handler, . - SVC_Handler
+
+
+    .weak   PendSV_Handler
+    .type   PendSV_Handler, %function
+PendSV_Handler:
+    B       .
+    .size   PendSV_Handler, . - PendSV_Handler
+
+
+    .weak   SysTick_Handler
+    .type   SysTick_Handler, %function
+SysTick_Handler:
+    B       .
+    .size   SysTick_Handler, . - SysTick_Handler
+
+/* Default handler. This uses the vector in the relocated vector table */
+    .globl  Default_Handler
+    .type   Default_Handler, %function
+Default_Handler:
+    LDR     R2, =__vector_tbl_reloc__
+    MRS     R0, PSR
+    MOVS    R1, #0x3F
+    ANDS    R0, R1
+    LSLS    R0, R0, #2
+    LDR     R0, [R0, R2]
+    BX      R0
+    .size   Default_Handler, . - Default_Handler
+
+/*
+ * All of the following IRQ Handlers will point to the default handler unless
+ * they are defined elsewhere.
+ */
+    .macro  IRQ handler
+    .weak   \handler
+    .set    \handler, Default_Handler
+    .endm
+
+    IRQ  _NMI_Handler
+    IRQ  _HardFault_Handler
+    IRQ  _SVC_Handler
+    IRQ  _PendSV_Handler
+    IRQ  _SysTick_Handler
+    IRQ  _POWER_CLOCK_IRQHandler
+    IRQ  _RADIO_IRQHandler
+    IRQ  _UART0_IRQHandler
+    IRQ  _SPI0_TWI0_IRQHandler
+    IRQ  _SPI1_TWI1_IRQHandler
+    IRQ  _GPIOTE_IRQHandler
+    IRQ  _ADC_IRQHandler
+    IRQ  _TIMER0_IRQHandler
+    IRQ  _TIMER1_IRQHandler
+    IRQ  _TIMER2_IRQHandler
+    IRQ  _RTC0_IRQHandler
+    IRQ  _TEMP_IRQHandler
+    IRQ  _RNG_IRQHandler
+    IRQ  _ECB_IRQHandler
+    IRQ  _CCM_AAR_IRQHandler
+    IRQ  _WDT_IRQHandler
+    IRQ  _RTC1_IRQHandler
+    IRQ  _QDEC_IRQHandler
+    IRQ  _LPCOMP_IRQHandler
+    IRQ  _SWI0_IRQHandler
+    IRQ  _SWI1_IRQHandler
+    IRQ  _SWI2_IRQHandler
+    IRQ  _SWI3_IRQHandler
+    IRQ  _SWI4_IRQHandler
+    IRQ  _SWI5_IRQHandler
+
+  .end

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/165f463d/hw/bsp/nrf51-blenano/src/hal_bsp.c
----------------------------------------------------------------------
diff --git a/hw/bsp/nrf51-blenano/src/hal_bsp.c b/hw/bsp/nrf51-blenano/src/hal_bsp.c
new file mode 100644
index 0000000..bfca6f9
--- /dev/null
+++ b/hw/bsp/nrf51-blenano/src/hal_bsp.c
@@ -0,0 +1,46 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+
+#include <stdint.h>
+#include <stddef.h>
+#include "mcu/nrf51_hal.h"
+
+static const struct nrf51_uart_cfg uart_cfg = {
+    .suc_pin_tx = 9,
+    .suc_pin_rx = 11,
+    .suc_pin_rts = 8,
+    .suc_pin_cts = 10
+};
+
+const struct nrf51_uart_cfg *bsp_uart_config(void)
+{
+    return &uart_cfg;
+}
+
+const struct hal_flash *
+bsp_flash_dev(uint8_t id)
+{
+    /*
+     * Internal flash mapped to id 0.
+     */
+    if (id != 0) {
+        return NULL;
+    }
+    return &nrf51_flash_dev;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/165f463d/hw/bsp/nrf51-blenano/src/libc_stubs.c
----------------------------------------------------------------------
diff --git a/hw/bsp/nrf51-blenano/src/libc_stubs.c b/hw/bsp/nrf51-blenano/src/libc_stubs.c
new file mode 100644
index 0000000..da54ed1
--- /dev/null
+++ b/hw/bsp/nrf51-blenano/src/libc_stubs.c
@@ -0,0 +1,85 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+
+#include <hal/hal_system.h>
+
+void * _sbrk(int c);
+int _close(int fd);
+int _fstat(int fd, void *s);
+void _exit(int s);
+int _kill(int pid, int sig);
+int _write(int fd, void *b, int nb);
+int _isatty(int c);
+int _lseek(int fd, int off, int w);
+int _read(int fd, void *b, int nb);
+int _getpid(void);
+
+int
+_close(int fd)
+{
+    return -1;
+}
+
+int
+_fstat(int fd, void *s)
+{
+    return -1;
+}
+
+
+void
+_exit(int s)
+{
+    system_reset();
+}
+
+int
+_kill(int pid, int sig)
+{
+    return -1;
+}
+
+int
+_write(int fd, void *b, int nb)
+{
+    return -1;
+}
+
+int
+_isatty(int c)
+{
+    return -1;
+}
+
+int
+_lseek(int fd, int off, int w)
+{
+    return -1;
+}
+
+int
+_read(int fd, void *b, int nb)
+{
+    return -1;
+}
+
+int
+_getpid(void) {
+    return -1;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/165f463d/hw/bsp/nrf51-blenano/src/os_bsp.c
----------------------------------------------------------------------
diff --git a/hw/bsp/nrf51-blenano/src/os_bsp.c b/hw/bsp/nrf51-blenano/src/os_bsp.c
new file mode 100644
index 0000000..2b88f27
--- /dev/null
+++ b/hw/bsp/nrf51-blenano/src/os_bsp.c
@@ -0,0 +1,78 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+#include <hal/flash_map.h>
+
+static struct flash_area bsp_flash_areas[] = {
+    [FLASH_AREA_BOOTLOADER] = {
+        .fa_flash_id = 0,       /* internal flash */
+        .fa_off = 0x00000000,   /* beginning */
+        .fa_size = (32 * 1024)
+    },
+    [FLASH_AREA_IMAGE_0] = {
+        .fa_flash_id = 0,
+        .fa_off = 0x00008000,
+        .fa_size = (110 * 1024)
+    },
+    [FLASH_AREA_IMAGE_1] = {
+        .fa_flash_id = 0,
+        .fa_off = 0x00023800,
+        .fa_size = (110 * 1024)
+    },
+    [FLASH_AREA_IMAGE_SCRATCH] = {
+        .fa_flash_id = 0,
+        .fa_off = 0x0003f000,
+        .fa_size = (2 * 1024)
+    },
+    [FLASH_AREA_NFFS] = {
+        .fa_flash_id = 0,
+        .fa_off = 0x0003f800,
+        .fa_size = (2 * 1024)
+    }
+};
+
+void *_sbrk(int incr);
+void _close(int fd);
+
+/*
+ * Returns the flash map slot where the currently active image is located.
+ * If executing from internal flash from fixed location, that slot would
+ * be easy to find.
+ * If images are in external flash, and copied to RAM for execution, then
+ * this routine would have to figure out which one of those slots is being
+ * used.
+ */
+int
+bsp_imgr_current_slot(void)
+{
+    return FLASH_AREA_IMAGE_0;
+}
+
+void
+os_bsp_init(void)
+{
+    /*
+     * XXX this reference is here to keep this function in.
+     */
+    _sbrk(0);
+    _close(0);
+
+    flash_area_init(bsp_flash_areas,
+      sizeof(bsp_flash_areas) / sizeof(bsp_flash_areas[0]));
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/165f463d/hw/bsp/nrf51-blenano/src/sbrk.c
----------------------------------------------------------------------
diff --git a/hw/bsp/nrf51-blenano/src/sbrk.c b/hw/bsp/nrf51-blenano/src/sbrk.c
new file mode 100644
index 0000000..f06d124
--- /dev/null
+++ b/hw/bsp/nrf51-blenano/src/sbrk.c
@@ -0,0 +1,53 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+
+#include <errno.h>
+
+extern char __HeapBase;
+extern char __HeapLimit;
+
+static char *brk = &__HeapBase;
+void *
+_sbrk(int incr)
+{
+    void *prev_brk;
+
+    if (incr < 0) {
+        /* Returning memory to the heap. */
+        incr = -incr;
+        if (brk - incr < &__HeapBase) {
+            prev_brk = (void *)-1;
+            errno = EINVAL;
+        } else {
+            prev_brk = brk;
+            brk -= incr;
+        }
+    } else {
+        /* Allocating memory from the heap. */
+        if (&__HeapLimit - brk >= incr) {
+            prev_brk = brk;
+            brk += incr;
+        } else {
+            prev_brk = (void *)-1;
+            errno = ENOMEM;
+        }
+    }
+
+    return prev_brk;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/165f463d/hw/bsp/nrf51-blenano/src/system_nrf51.c
----------------------------------------------------------------------
diff --git a/hw/bsp/nrf51-blenano/src/system_nrf51.c b/hw/bsp/nrf51-blenano/src/system_nrf51.c
new file mode 100755
index 0000000..2ca31d1
--- /dev/null
+++ b/hw/bsp/nrf51-blenano/src/system_nrf51.c
@@ -0,0 +1,121 @@
+/* Copyright (c) 2015, Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *   * Redistributions of source code must retain the above copyright notice, this
+ *     list of conditions and the following disclaimer.
+ *
+ *   * Redistributions in binary form must reproduce the above copyright notice,
+ *     this list of conditions and the following disclaimer in the documentation
+ *     and/or other materials provided with the distribution.
+ *
+ *   * Neither the name of Nordic Semiconductor ASA nor the names of its
+ *     contributors may be used to endorse or promote products derived from
+ *     this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <stdint.h>
+#include <stdbool.h>
+#include "bsp/cmsis_nvic.h"
+#include "mcu/nrf.h"
+#include "mcu/system_nrf51.h"
+
+/*lint ++flb "Enter library region" */
+
+
+#define __SYSTEM_CLOCK      (16000000UL)     /*!< nRF51 devices use a fixed System Clock Frequency of 16MHz */
+
+static bool is_manual_peripheral_setup_needed(void);
+static bool is_disabled_in_debug_needed(void);
+
+
+#if defined ( __CC_ARM )
+    uint32_t SystemCoreClock __attribute__((used)) = __SYSTEM_CLOCK;  
+#elif defined ( __ICCARM__ )
+    __root uint32_t SystemCoreClock = __SYSTEM_CLOCK;
+#elif defined   ( __GNUC__ )
+    uint32_t SystemCoreClock __attribute__((used)) = __SYSTEM_CLOCK;
+#endif
+
+void SystemCoreClockUpdate(void)
+{
+    SystemCoreClock = __SYSTEM_CLOCK;
+}
+
+void SystemInit(void)
+{
+    /* If desired, switch off the unused RAM to lower consumption by the use of RAMON register.
+       It can also be done in the application main() function. */
+
+    /* Prepare the peripherals for use as indicated by the PAN 26 "System: Manual setup is required
+       to enable the use of peripherals" found at Product Anomaly document for your device found at
+       https://www.nordicsemi.com/. The side effect of executing these instructions in the devices 
+       that do not need it is that the new peripherals in the second generation devices (LPCOMP for
+       example) will not be available. */
+    if (is_manual_peripheral_setup_needed())
+    {
+        *(uint32_t volatile *)0x40000504 = 0xC007FFDF;
+        *(uint32_t volatile *)0x40006C18 = 0x00008000;
+    }
+    
+    /* Disable PROTENSET registers under debug, as indicated by PAN 59 "MPU: Reset value of DISABLEINDEBUG
+       register is incorrect" found at Product Anomaly document four your device found at 
+       https://www.nordicsemi.com/. There is no side effect of using these instruction if not needed. */
+    if (is_disabled_in_debug_needed())
+    {
+        NRF_MPU->DISABLEINDEBUG = MPU_DISABLEINDEBUG_DISABLEINDEBUG_Disabled << MPU_DISABLEINDEBUG_DISABLEINDEBUG_Pos;
+    }
+
+    NVIC_Relocate();
+}
+
+
+static bool is_manual_peripheral_setup_needed(void) 
+{
+    if ((((*(uint32_t *)0xF0000FE0) & 0x000000FF) == 0x1) && (((*(uint32_t *)0xF0000FE4) & 0x0000000F) == 0x0))
+    {
+        if ((((*(uint32_t *)0xF0000FE8) & 0x000000F0) == 0x00) && (((*(uint32_t *)0xF0000FEC) & 0x000000F0) == 0x0))
+        {
+            return true;
+        }
+        if ((((*(uint32_t *)0xF0000FE8) & 0x000000F0) == 0x10) && (((*(uint32_t *)0xF0000FEC) & 0x000000F0) == 0x0))
+        {
+            return true;
+        }
+        if ((((*(uint32_t *)0xF0000FE8) & 0x000000F0) == 0x30) && (((*(uint32_t *)0xF0000FEC) & 0x000000F0) == 0x0))
+        {
+            return true;
+        }
+    }
+    
+    return false;
+}
+
+static bool is_disabled_in_debug_needed(void) 
+{
+    if ((((*(uint32_t *)0xF0000FE0) & 0x000000FF) == 0x1) && (((*(uint32_t *)0xF0000FE4) & 0x0000000F) == 0x0))
+    {
+        if ((((*(uint32_t *)0xF0000FE8) & 0x000000F0) == 0x40) && (((*(uint32_t *)0xF0000FEC) & 0x000000F0) == 0x0))
+        {
+            return true;
+        }
+    }
+    
+    return false;
+}
+
+/*lint --flb "Leave library region" */


[41/50] [abbrv] incubator-mynewt-core git commit: Fix bug in how V0 objects are read in from flash

Posted by cc...@apache.org.
Fix bug in how V0 objects are read in from flash

V0 disk objects were not being read in correctly. Code was mistakenly
reading in nffs_disk_V0object from flash, but that is an in-core data
structure and only the actual inode or block structures are to be read in.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/7b269d52
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/7b269d52
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/7b269d52

Branch: refs/heads/master
Commit: 7b269d529a25214ce56dac8dd3744cc59a052178
Parents: 27a8888
Author: Peter Snyder <gi...@peterfs.com>
Authored: Sat Jul 2 10:44:29 2016 -0700
Committer: Peter Snyder <gi...@peterfs.com>
Committed: Sat Jul 2 10:44:29 2016 -0700

----------------------------------------------------------------------
 apps/ffs2native/src/main.c | 55 +++++++++++++----------------------------
 1 file changed, 17 insertions(+), 38 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/7b269d52/apps/ffs2native/src/main.c
----------------------------------------------------------------------
diff --git a/apps/ffs2native/src/main.c b/apps/ffs2native/src/main.c
index cfa4688..edaaa31 100644
--- a/apps/ffs2native/src/main.c
+++ b/apps/ffs2native/src/main.c
@@ -89,11 +89,11 @@ struct nffs_disk_V0object {
     union {
         struct nffs_disk_V0inode ndo_disk_V0inode;
         struct nffs_disk_V0block ndo_disk_V0block;
-    } ndo_un_obj;
+    } ndo_un_V0obj;
 };
 
-#define ndo_disk_V0inode    ndo_un_obj.ndo_disk_V0inode
-#define ndo_disk_V0block    ndo_un_obj.ndo_disk_V0block
+#define ndo_disk_V0inode    ndo_un_V0obj.ndo_disk_V0inode
+#define ndo_disk_V0block    ndo_un_V0obj.ndo_disk_V0block
 
 static void usage(int rc);
 
@@ -364,6 +364,7 @@ file_flash_read(uint32_t addr, void *dst, int byte_cnt)
 
 /*
  * Print NFFS V0 structures
+ * XXX could check for CRC errors
  */
 static int
 print_nffs_flash_V0inode(struct nffs_area_desc *area, uint32_t off)
@@ -375,6 +376,7 @@ print_nffs_flash_V0inode(struct nffs_area_desc *area, uint32_t off)
 
     rc = file_flash_read(area->nad_offset + off, &ndi, sizeof(ndi));
     assert(rc == 0);
+	assert(nffs_hash_id_is_inode(ndi.ndi_id));
 
     memset(filename, 0, sizeof(filename));
     len = min(sizeof(filename) - 1, ndi.ndi_filename_len);
@@ -382,10 +384,10 @@ print_nffs_flash_V0inode(struct nffs_area_desc *area, uint32_t off)
     filename[len] = '\0';
     assert(rc == 0);
 
-    printf("   %s off %x id %x magic %x flen %d seq %d prnt %x %s\n",
+    printf("   %s off %d id %x flen %d seq %d prnt %x %s\n",
            (nffs_hash_id_is_file(ndi.ndi_id) ? "File" :
             (nffs_hash_id_is_dir(ndi.ndi_id) ? "Dir" : "???")),
-           off, ndi.ndi_id, ndi.ndi_magic, ndi.ndi_filename_len,
+           off, ndi.ndi_id, ndi.ndi_filename_len,
            ndi.ndi_seq, ndi.ndi_parent_id, filename);
     return sizeof(struct nffs_disk_V0inode) + ndi.ndi_filename_len;
 }
@@ -398,8 +400,10 @@ print_nffs_flash_V0block(struct nffs_area_desc *area, uint32_t off)
 
     rc = file_flash_read(area->nad_offset + off, &ndb, sizeof(ndb));
     assert(rc == 0);
+	assert(nffs_hash_id_is_block(ndb.ndb_id));
+	assert(!nffs_hash_id_is_inode(ndb.ndb_id));
 
-    printf("   Block off %x id %x len %d seq %d prev %x ino %x\n",
+    printf("   Block off %d id %x len %d seq %d prev %x ino %x\n",
            off, ndb.ndb_id, ndb.ndb_data_len, ndb.ndb_seq,
            ndb.ndb_prev_id, ndb.ndb_inode_id);
     return sizeof(struct nffs_disk_V0block) + ndb.ndb_data_len;
@@ -408,22 +412,23 @@ print_nffs_flash_V0block(struct nffs_area_desc *area, uint32_t off)
 static int
 print_nffs_flash_V0object(struct nffs_area_desc *area, uint32_t off)
 {
-    struct nffs_disk_V0object ndo;
+	uint32_t magic;
     int rc;
 
-    rc = file_flash_read(area->nad_offset + off, &ndo, sizeof(ndo));
+    rc = file_flash_read(area->nad_offset + off, &magic, sizeof magic);
     assert(rc == 0);
 
-    if (nffs_hash_id_is_inode(ndo.ndo_disk_V0inode.ndi_id)) {
+	switch (magic) {
+	case NFFS_INODE_MAGIC:
         return print_nffs_flash_V0inode(area, off);
 
-    } else if (nffs_hash_id_is_block(ndo.ndo_disk_V0block.ndb_id)) {
+	case NFFS_BLOCK_MAGIC:
         return print_nffs_flash_V0block(area, off);
 
-    } else if (ndo.ndo_disk_V0block.ndb_id == 0xffffffff) {
+	case 0xffffffff:
         return area->nad_length;
 
-    } else {
+	default:
         return 1;
     }
 }
@@ -497,32 +502,6 @@ print_nffs_flash_object(struct nffs_area_desc *area, uint32_t off)
     }
 }
 
-#if 0
-void
-print_file_areas()
-{
-    struct nffs_area_desc *area;
-    int off;
-    int i;
-
-    for (i = 0; i < nffs_num_areas; i++) {
-        area = &area_descs[i];
-        printf("%d: id:%d 0x%x - 0x%x %s\n",
-               i, area->nad_flash_id, area->nad_offset,
-               area->nad_offset + area->nad_length,
-               (i == file_scratch_idx ? "(scratch)" : ""));
-        off = sizeof (struct nffs_disk_area);
-        while (off < area->nad_length) {
-            if (nffs_version == 0) {
-                off += print_nffsV0_flash_object(area, off);
-            } else if (nffs_version == NFFS_AREA_VER) {
-                off += print_nffs_flash_object(area, off);
-            }
-        }
-    }
-}
-#endif
-
 static void
 print_nffs_file_flash(char *flash_area, size_t size)
 {


[03/50] [abbrv] incubator-mynewt-core git commit: coredump; package depends on bootutil header files and imgmgr.

Posted by cc...@apache.org.
coredump; package depends on bootutil header files and imgmgr.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/af6cb230
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/af6cb230
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/af6cb230

Branch: refs/heads/master
Commit: af6cb230e1991deb65af499a240d6103fe3a505b
Parents: 2efa344
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Mon Jun 20 17:48:07 2016 -0700
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Jun 20 17:48:07 2016 -0700

----------------------------------------------------------------------
 sys/coredump/pkg.yml | 2 ++
 1 file changed, 2 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/af6cb230/sys/coredump/pkg.yml
----------------------------------------------------------------------
diff --git a/sys/coredump/pkg.yml b/sys/coredump/pkg.yml
index cb8787d..b4f05a0 100644
--- a/sys/coredump/pkg.yml
+++ b/sys/coredump/pkg.yml
@@ -26,5 +26,7 @@ pkg.keywords:
 
 pkg.deps:
     - hw/hal
+    - libs/bootutil
+    - libs/imgmgr
 pkg.features:
     - COREDUMP


[40/50] [abbrv] incubator-mynewt-core git commit: MYNEWT-329: More efficient cputime when using 1MHZ clock

Posted by cc...@apache.org.
MYNEWT-329: More efficient cputime when using 1MHZ clock

You can now define a target variable named HAL_CPUTIME_1MHZ. If you include
this in your target the cputime will assume a 1MHZ clock is being used
and the routines for converting usecs to ticks (and vice versa) will
basically become "no-ops".


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/bcfe3fd0
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/bcfe3fd0
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/bcfe3fd0

Branch: refs/heads/master
Commit: bcfe3fd05384ca07d65352bbfcbf02ce3195b383
Parents: baee9cd
Author: William San Filippo <wi...@runtime.io>
Authored: Thu Jun 30 18:11:40 2016 -0700
Committer: William San Filippo <wi...@runtime.io>
Committed: Thu Jun 30 18:13:57 2016 -0700

----------------------------------------------------------------------
 apps/bletest/src/main.c                  |  2 +-
 hw/hal/include/hal/hal_cputime.h         |  5 +++++
 hw/hal/src/hal_cputime.c                 | 11 ++++++++++-
 hw/mcu/native/src/hal_cputime.c          |  7 +++++++
 hw/mcu/nordic/nrf51xxx/src/hal_cputime.c |  6 ++++++
 hw/mcu/nordic/nrf52xxx/src/hal_cputime.c | 13 +++++++------
 hw/mcu/stm/stm32f4xx/src/hal_cputime.c   |  6 ++++++
 7 files changed, 42 insertions(+), 8 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/bcfe3fd0/apps/bletest/src/main.c
----------------------------------------------------------------------
diff --git a/apps/bletest/src/main.c b/apps/bletest/src/main.c
index e132f32..d9efe7e 100755
--- a/apps/bletest/src/main.c
+++ b/apps/bletest/src/main.c
@@ -104,7 +104,7 @@ os_membuf_t g_mbuf_buffer[MBUF_MEMPOOL_SIZE];
 //#define BLETEST_CFG_ROLE                (BLETEST_ROLE_SCANNER)
 
 /* Advertiser config */
-#define BLETEST_CFG_ADV_OWN_ADDR_TYPE   (BLE_HCI_ADV_OWN_ADDR_PRIV_PUB)
+#define BLETEST_CFG_ADV_OWN_ADDR_TYPE   (BLE_HCI_ADV_OWN_ADDR_PUBLIC)
 #define BLETEST_CFG_ADV_PEER_ADDR_TYPE  (BLE_HCI_ADV_PEER_ADDR_PUBLIC)
 #define BLETEST_CFG_ADV_ITVL            (60000 / BLE_HCI_ADV_ITVL)
 #define BLETEST_CFG_ADV_TYPE            BLE_HCI_ADV_TYPE_ADV_IND

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/bcfe3fd0/hw/hal/include/hal/hal_cputime.h
----------------------------------------------------------------------
diff --git a/hw/hal/include/hal/hal_cputime.h b/hw/hal/include/hal/hal_cputime.h
index 001bac5..7932de6 100644
--- a/hw/hal/include/hal/hal_cputime.h
+++ b/hw/hal/include/hal/hal_cputime.h
@@ -108,6 +108,10 @@ uint32_t cputime_nsecs_to_ticks(uint32_t nsecs);
  */
 uint32_t cputime_ticks_to_nsecs(uint32_t ticks);
 
+#if defined(HAL_CPUTIME_1MHZ)
+#define cputime_usecs_to_ticks(x)       (x)
+#define cputime_ticks_to_usecs(x)       (x)
+#else
 /**
  * cputime usecs to ticks
  *
@@ -129,6 +133,7 @@ uint32_t cputime_usecs_to_ticks(uint32_t usecs);
  * @return uint32_t The number of microseconds corresponding to 'ticks'
  */
 uint32_t cputime_ticks_to_usecs(uint32_t ticks);
+#endif
 
 /**
  * cputime delay ticks

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/bcfe3fd0/hw/hal/src/hal_cputime.c
----------------------------------------------------------------------
diff --git a/hw/hal/src/hal_cputime.c b/hw/hal/src/hal_cputime.c
index 980b3e1..69e0407 100644
--- a/hw/hal/src/hal_cputime.c
+++ b/hw/hal/src/hal_cputime.c
@@ -90,7 +90,6 @@ cputime_init(uint32_t clock_freq)
     return rc;
 }
 
-
 /**
  * cputime nsecs to ticks
  *
@@ -105,7 +104,11 @@ cputime_nsecs_to_ticks(uint32_t nsecs)
 {
     uint32_t ticks;
 
+#if defined(HAL_CPUTIME_1MHZ)
+    ticks = (nsecs + 999) / 1000;
+#else
     ticks = ((nsecs * g_cputime.ticks_per_usec) + 999) / 1000;
+#endif
     return ticks;
 }
 
@@ -123,12 +126,17 @@ cputime_ticks_to_nsecs(uint32_t ticks)
 {
     uint32_t nsecs;
 
+#if defined(HAL_CPUTIME_1MHZ)
+    nsecs = ticks * 1000;
+#else
     nsecs = ((ticks * 1000) + (g_cputime.ticks_per_usec - 1)) /
             g_cputime.ticks_per_usec;
+#endif
 
     return nsecs;
 }
 
+#if !defined(HAL_CPUTIME_1MHZ)
 /**
  * cputime usecs to ticks
  *
@@ -164,6 +172,7 @@ cputime_ticks_to_usecs(uint32_t ticks)
     us =  (ticks + (g_cputime.ticks_per_usec - 1)) / g_cputime.ticks_per_usec;
     return us;
 }
+#endif
 
 /**
  * cputime delay ticks

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/bcfe3fd0/hw/mcu/native/src/hal_cputime.c
----------------------------------------------------------------------
diff --git a/hw/mcu/native/src/hal_cputime.c b/hw/mcu/native/src/hal_cputime.c
index e310415..ad49d07 100644
--- a/hw/mcu/native/src/hal_cputime.c
+++ b/hw/mcu/native/src/hal_cputime.c
@@ -129,6 +129,13 @@ native_cputime_task_handler(void *arg)
 int
 cputime_hw_init(uint32_t clock_freq)
 {
+
+#if defined(HAL_CPUTIME_1MHZ)
+    if (clock_freq != 1000000) {
+        return -1;
+    }
+#endif
+
     /* Clock frequency must be at least 1 MHz */
     if (clock_freq < 1000000U) {
         return -1;

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/bcfe3fd0/hw/mcu/nordic/nrf51xxx/src/hal_cputime.c
----------------------------------------------------------------------
diff --git a/hw/mcu/nordic/nrf51xxx/src/hal_cputime.c b/hw/mcu/nordic/nrf51xxx/src/hal_cputime.c
index 8f2815d..f0c67fb 100644
--- a/hw/mcu/nordic/nrf51xxx/src/hal_cputime.c
+++ b/hw/mcu/nordic/nrf51xxx/src/hal_cputime.c
@@ -154,6 +154,12 @@ cputime_hw_init(uint32_t clock_freq)
     uint32_t max_freq;
     uint32_t pre_scaler;
 
+#if defined(HAL_CPUTIME_1MHZ)
+    if (clock_freq != 1000000) {
+        return -1;
+    }
+#endif
+
     /* Clock frequency must be at least 1 MHz */
     if (clock_freq < 1000000U) {
         return -1;

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/bcfe3fd0/hw/mcu/nordic/nrf52xxx/src/hal_cputime.c
----------------------------------------------------------------------
diff --git a/hw/mcu/nordic/nrf52xxx/src/hal_cputime.c b/hw/mcu/nordic/nrf52xxx/src/hal_cputime.c
index d58fee3..ce82242 100644
--- a/hw/mcu/nordic/nrf52xxx/src/hal_cputime.c
+++ b/hw/mcu/nordic/nrf52xxx/src/hal_cputime.c
@@ -43,12 +43,7 @@
 /* Interrupt mask for interrupt enable/clear */
 #define CPUTIMER_INT_MASK(x)    ((1 << (uint32_t)(x)) << 16)
 
-/* XXX:
- *  - Must determine how to set priority of cpu timer interrupt
- *  - Determine if we should use a mutex as opposed to disabling interrupts
- *  - Should I use macro for compare channel?
- *  - Sync to OSTIME.
- */
+/* Disable output compare used for cputimer */
 void
 cputime_disable_ocmp(void)
 {
@@ -152,6 +147,12 @@ cputime_hw_init(uint32_t clock_freq)
     uint32_t max_freq;
     uint32_t pre_scaler;
 
+#if defined(HAL_CPUTIME_1MHZ)
+    if (clock_freq != 1000000) {
+        return -1;
+    }
+#endif
+
     /* Clock frequency must be at least 1 MHz */
     if (clock_freq < 1000000U) {
         return -1;

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/bcfe3fd0/hw/mcu/stm/stm32f4xx/src/hal_cputime.c
----------------------------------------------------------------------
diff --git a/hw/mcu/stm/stm32f4xx/src/hal_cputime.c b/hw/mcu/stm/stm32f4xx/src/hal_cputime.c
index 0025670..e6324c6 100644
--- a/hw/mcu/stm/stm32f4xx/src/hal_cputime.c
+++ b/hw/mcu/stm/stm32f4xx/src/hal_cputime.c
@@ -107,6 +107,12 @@ cputime_hw_init(uint32_t clock_freq)
     uint32_t max_freq;
     uint32_t pre_scalar;
 
+#if defined(HAL_CPUTIME_1MHZ)
+    if (clock_freq != 1000000) {
+        return -1;
+    }
+#endif
+
     /* Clock frequency must be at least 1 MHz */
     if (clock_freq < 1000000U) {
         return -1;


[13/50] [abbrv] incubator-mynewt-core git commit: log2smtest.rb: generates BLE SM unit tests.

Posted by cc...@apache.org.
log2smtest.rb: generates BLE SM unit tests.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/e0c73d24
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/e0c73d24
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/e0c73d24

Branch: refs/heads/master
Commit: e0c73d247bb96c7a825894a469b34845b92ced60
Parents: e942cec
Author: Christopher Collins <cc...@apache.org>
Authored: Thu Jun 23 14:56:58 2016 -0700
Committer: Christopher Collins <cc...@apache.org>
Committed: Thu Jun 23 14:56:58 2016 -0700

----------------------------------------------------------------------
 net/nimble/host/tools/log2smtest.rb | 1010 ++++++++++++++++++++++++++++++
 1 file changed, 1010 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/e0c73d24/net/nimble/host/tools/log2smtest.rb
----------------------------------------------------------------------
diff --git a/net/nimble/host/tools/log2smtest.rb b/net/nimble/host/tools/log2smtest.rb
new file mode 100755
index 0000000..cc7612a
--- /dev/null
+++ b/net/nimble/host/tools/log2smtest.rb
@@ -0,0 +1,1010 @@
+#!/usr/bin/env ruby
+
+### This script converts a bletiny log into a security manager unit test.  The
+### input log must contain the connection establishment and complete pairing
+### procedure.
+###
+### Arguments: None
+### Stdin: bletiny log file
+
+$PAIR_ALG_STRINGS = {
+    0 => [ 'BLE_SM_PAIR_ALG_JW',        'just works',           'jw' ],
+    1 => [ 'BLE_SM_PAIR_ALG_PASSKEY',   'passkey entry',        'pk' ],
+    2 => [ 'BLE_SM_PAIR_ALG_OOB',       'out of band',          'ob' ],
+    3 => [ 'BLE_SM_PAIR_ALG_NUMCMP',    'numeric comparison',   'nc' ]
+}
+
+$ADDR_TYPE_STRINGS = {
+    0 => 'BLE_ADDR_TYPE_PUBLIC',
+    1 => 'BLE_ADDR_TYPE_RANDOM',
+    2 => 'BLE_ADDR_TYPE_RPA_PUB_DEFAULT',
+    3 => 'BLE_ADDR_TYPE_RPA_RND_DEFAULT',
+}
+
+$ACTION_STRINGS = {
+    0 => 'BLE_SM_IOACT_NONE',
+    1 => 'BLE_SM_IOACT_OOB',
+    2 => 'BLE_SM_IOACT_INPUT',
+    3 => 'BLE_SM_IOACT_DISP',
+    4 => 'BLE_SM_IOACT_NUMCMP',
+}
+
+$prev_idx = 0
+$ctxt = {}
+
+def test_case_name
+    type_str = $ctxt[:sc] ? "sc" : "lgcy"
+    init_str = $ctxt[:we_are_init] ? "us" : "peer"
+    alg_str = $PAIR_ALG_STRINGS[$ctxt[:pair_alg]][2]
+    iio_cap_str = "iio#{$ctxt[:pair_req][:io_cap]}"
+    rio_cap_str = "rio#{$ctxt[:pair_rsp][:io_cap]}"
+    bonding_str = "b#{$ctxt[:bonding] ? 1 : 0}"
+    iat_str = "iat#{$ctxt[:addrs][:init_type]}"
+    rat_str = "rat#{$ctxt[:addrs][:resp_type]}"
+    ikey_str = "ik#{$ctxt[:pair_rsp][:init_key_dist]}"
+    rkey_str = "rk#{$ctxt[:pair_rsp][:resp_key_dist]}"
+
+    "ble_sm_" +
+    "#{type_str}_#{init_str}_#{alg_str}_#{iio_cap_str}_#{rio_cap_str}_" +
+    "#{bonding_str}_#{iat_str}_#{rat_str}_#{ikey_str}_#{rkey_str}"
+end
+
+def test_case_comment
+<<-eos
+/**
+ * #{$ctxt[:sc] ? 'Secure connections' : 'Legacy'} pairing
+ * Master: #{$ctxt[:we_are_init] ? "us" : "peer"}
+ * Pair algorithm: #{$PAIR_ALG_STRINGS[$ctxt[:pair_alg]][1]}
+ * Initiator IO capabilities: #{$ctxt[:pair_req][:io_cap]}
+ * Responder IO capabilities: #{$ctxt[:pair_rsp][:io_cap]}
+ * Bonding: #{$ctxt[:bonding]}
+ * Initiator address type: #{$ADDR_TYPE_STRINGS[$ctxt[:addrs][:init_type]]}
+ * Responder address type: #{$ADDR_TYPE_STRINGS[$ctxt[:addrs][:resp_type]]}
+ * Initiator key distribution: #{$ctxt[:pair_rsp][:init_key_dist]}
+ * Responder key distribution: #{$ctxt[:pair_rsp][:resp_key_dist]}
+ */
+eos
+end
+
+def to_hex_s(byte)
+    if byte.is_a?(String)
+        byte = s_to_i(byte)
+    end
+
+    "0x#{byte.to_s(16).rjust(2, '0')}"
+end
+
+# to_i(0) but interpret leading zeros as decimal.
+def s_to_i(s)
+    if s[0..1] == "0x"
+        return s.to_i(16)
+    else
+        return s.to_i(10)
+    end
+end
+
+def invalid_byte_line(msg, line)
+    str = "invalid byte line"
+    if msg != nil
+        str += ": #{msg}"
+    end
+
+    str += "; line=#{line}"
+
+    raise str
+end
+
+def token_string_to_bytes(line, delim = ' ')
+    tokens = line.split(delim)
+    bytes = []
+    tokens.each do |token|
+        begin
+            byte = token.to_i(16)
+            bytes << byte
+        rescue
+            invalid_byte_line("token=#{token}", line)
+        end
+    end
+
+    return bytes
+end
+
+def txrx_prefix(is_tx)
+    if is_tx
+        return "tx"
+    else
+        return "rx"
+    end
+end
+
+def reqrsp_s(is_req)
+    reqrsp = nil
+    if is_req
+        return "req"
+    else
+        return "rsp"
+    end
+end
+
+def bytes_to_arr_body(bytes, indent)
+    lines = []
+
+    idx = 0
+    while idx < bytes.size
+        slice_len = nil
+        if bytes.size - idx >= 8
+            slice_len = 8
+        else
+            slice_len = bytes.size - idx
+        end
+
+        slice = bytes[idx...(idx + slice_len)]
+        line = ' ' * indent +
+            slice.map{|b| to_hex_s(b)}.join(", ") + ","
+        lines << line
+
+        idx += slice_len
+    end
+
+    return lines.join("\n") << "\n"
+end
+
+def bytes_to_arr(bytes, name, indent)
+    str = "#{' ' * indent}.#{name} = {\n"
+    str << bytes_to_arr_body(bytes, indent + 4)
+    str << "#{' ' * indent}},"
+
+    return str
+end
+
+def addr_string_to_bytes(addr_string)
+    token_string_to_bytes(addr_string, ':').reverse
+end
+
+def parse_pair_cmd(line, is_req)
+    suffix = reqrsp_s(is_req)
+    re = %r{
+        pair\s#{suffix};
+        \s
+        conn=\d+
+        \s
+        io_cap=(?<io_cap>\d+)
+        \s
+        oob_data_flag=(?<oob_data_flag>\d+)
+        \s
+        authreq=(?<authreq>0x[0-9a-f]+)
+        \s
+        mac_enc_key_size=(?<max_enc_key_size>\d+)
+        \s
+        init_key_dist=(?<init_key_dist>\d+)
+        \s
+        resp_key_dist=(?<resp_key_dist>\d+)
+    }x
+
+    m = re.match(line)
+    if m == nil
+        return nil
+    end
+
+    cmd = {}
+    cmd[:io_cap] = s_to_i(m[:io_cap])
+    cmd[:oob_data_flag] = s_to_i(m[:oob_data_flag])
+    cmd[:authreq] = s_to_i(m[:authreq])
+    cmd[:max_enc_key_size] = s_to_i(m[:max_enc_key_size])
+    cmd[:init_key_dist] = s_to_i(m[:init_key_dist])
+    cmd[:resp_key_dist] = s_to_i(m[:resp_key_dist])
+
+    return cmd
+end
+
+def parse_privkey(line)
+    if !(line =~ /our privkey=(.+)/)
+        return nil
+    end
+    return token_string_to_bytes($1)
+end
+
+def parse_public_key(line, is_tx)
+    prefix = txrx_prefix(is_tx)
+    if !(line =~ /#{prefix}ed sm command: public key; conn=\d+ x=(.+) y=(.+)/)
+        return nil
+    end
+
+    pubkey = {}
+    pubkey[:x] = token_string_to_bytes($1)
+    pubkey[:y] = token_string_to_bytes($2)
+
+    if pubkey[:x].size != 32
+        raise "invalid public key: x length incorrect; line=#{line}"
+    end
+
+    if pubkey[:y].size != 32
+        raise "invalid public key: y length incorrect; line=#{line}"
+    end
+
+    return pubkey
+end
+
+def parse_confirm(line, is_tx)
+    prefix = txrx_prefix(is_tx)
+    if !(line =~ /#{prefix}ed sm command: confirm; conn=\d+ value=(.+)/)
+        return nil
+    end
+
+    bytes = token_string_to_bytes($1)
+    if bytes.size != 16
+        raise "invalid confirm line (length mismatch): #{line}"
+    end
+
+    return { :value => bytes }
+end
+
+def parse_random(line, is_tx)
+    prefix = txrx_prefix(is_tx)
+    if !(line =~ /#{prefix}ed sm command: random; conn=\d+ value=(.+)/)
+        return nil
+    end
+
+    bytes = token_string_to_bytes($1)
+    if bytes.size != 16
+        raise "invalid random line (length mismatch): #{line}"
+    end
+
+    return { :value => bytes }
+end
+
+def parse_stk(line)
+    if !(line =~ /^    out=(.+)/)
+        return nil
+    end
+
+    bytes = token_string_to_bytes($1)
+    if bytes.size != 16
+        raise "invalid stk line (length mismatch): #{line}"
+    end
+
+    return bytes
+end
+
+def parse_dhkey_check(line, is_tx)
+    prefix = txrx_prefix(is_tx)
+    if !(line =~ /#{prefix}ed sm command: dhkey check; conn=\d+ value=(.+)/)
+        return nil
+    end
+
+    bytes = token_string_to_bytes($1)
+    if bytes.size != 16
+        raise "invalid dhkey_check line (length mismatch): #{line}"
+    end
+
+    return { :value => bytes }
+end
+
+def parse_ltk(line)
+    if !(line =~ /persisting.+ltk=([^ ]+)/)
+        return nil
+    end
+
+    bytes = $1.split(":")
+    if bytes.size != 16
+        raise "invalid ltk line (length mismatch): exp=16 got=#{bytes.size} " +
+              "line=#{line}"
+    end
+
+    return bytes
+end
+
+def parse_enc_info(line, is_tx)
+    prefix = txrx_prefix(is_tx)
+    if !(line =~ /#{prefix}ed sm command: enc info; conn=\d+ ltk=(.+)/)
+        return nil
+    end
+
+    bytes = token_string_to_bytes($1)
+    if bytes.size != 16
+        raise "invalid enc info line (length mismatch): #{line}"
+    end
+
+    return { :ltk => bytes }
+end
+
+def parse_master_id(line, is_tx)
+    prefix = txrx_prefix(is_tx)
+    if !(line =~ /#{prefix}ed sm command: master id; conn=\d+ ediv=(.+) rand=(.+)/)
+        return nil
+    end
+
+    return {
+        :ediv => s_to_i($1),
+        :rand => s_to_i($2),
+    }
+end
+
+def parse_id_info(line, is_tx)
+    prefix = txrx_prefix(is_tx)
+    if !(line =~ /#{prefix}ed sm command: id info; conn=\d+ irk=(.+)/)
+        return nil
+    end
+
+    bytes = token_string_to_bytes($1)
+    if bytes.size != 16
+        raise "invalid id info line (length mismatch): #{line}"
+    end
+
+    return { :irk => bytes }
+end
+
+def parse_id_addr_info(line, is_tx)
+    prefix = txrx_prefix(is_tx)
+    if !(line =~ /#{prefix}ed sm command: id addr info; conn=\d+ addr_type=(\d+) addr=(.+)/)
+        return nil
+    end
+
+    bytes = addr_string_to_bytes($2)
+    if bytes.size != 6
+        raise "invalid id addr info line (length mismatch): #{line}"
+    end
+
+    return {
+        :addr_type => s_to_i($1),
+        :addr => bytes,
+    }
+end
+
+def parse_sign_info(line, is_tx)
+    prefix = txrx_prefix(is_tx)
+    if !(line =~ /#{prefix}ed sm command: sign info; conn=\d+ sig_key=(.+)/)
+        return nil
+    end
+
+    bytes = token_string_to_bytes($1)
+    if bytes.size != 16
+        raise "invalid sign info line (length mismatch): #{line}"
+    end
+
+    return {
+        :sig_key => bytes,
+    }
+end
+
+def parse_passkey_info(line)
+    passkey_info = {}
+
+    case line 
+    when /passkey action event; action=4 numcmp=(\d+)/
+        passkey_info[:action] = 4
+        passkey_info[:numcmp] = $1.to_i(10)
+    when /^b passkey conn=\d+ action=1 oob=(\S+)/
+        passkey_info[:action] = 1
+        passkey_info[:oob] = token_string_to_bytes($1, ':')
+    when /^b passkey conn=\d+ action=2 key=(\d+)/
+        passkey_info[:action] = 2
+        passkey_info[:key] = $1.to_i(10)
+    when /b passkey conn=\d+ action=3 key=(\d+)/
+        passkey_info[:action] = 3
+        passkey_info[:key] = $1.to_i(10)
+    else
+        return nil
+    end
+
+    return passkey_info
+end
+
+def parse_addrs(line)
+    if !(line =~ /our_ota_addr_type=(\d+) our_ota_addr=(\S+) our_id_addr_type=(\d+) our_id_addr=(\S+) peer_ota_addr_type=(\d+) peer_ota_addr=(\S+) peer_id_addr_type=(\d+) peer_id_addr=(\S+)/)
+        return nil
+    end
+
+    our_ota_addr_bytes = addr_string_to_bytes($2)
+    our_id_addr_bytes = addr_string_to_bytes($4)
+    peer_ota_addr_bytes = addr_string_to_bytes($6)
+    peer_id_addr_bytes = addr_string_to_bytes($8)
+
+    if $ctxt[:we_are_init]
+        init_id_bytes = our_id_addr_bytes
+        init_ota_bytes = our_ota_addr_bytes
+        resp_id_bytes = peer_id_addr_bytes
+        resp_ota_bytes = peer_ota_addr_bytes
+        init_addr_type = s_to_i($1)
+        resp_addr_type = s_to_i($5)
+    else
+        init_id_bytes = peer_id_addr_bytes
+        init_ota_bytes = peer_ota_addr_bytes
+        resp_id_bytes = our_id_addr_bytes
+        resp_ota_bytes = our_ota_addr_bytes
+        init_addr_type = s_to_i($5)
+        resp_addr_type = s_to_i($1)
+    end
+
+    if init_id_bytes == init_ota_bytes
+        init_ota_bytes = [0] * 6
+    end
+    if resp_id_bytes == resp_ota_bytes
+        resp_ota_bytes = [0] * 6
+    end
+
+    return {
+        :init_type => init_addr_type,
+        :resp_type => resp_addr_type,
+        :init_id_addr => init_id_bytes,
+        :resp_id_addr => resp_id_bytes,
+        :init_rpa => init_ota_bytes,
+        :resp_rpa => resp_ota_bytes,
+    }
+end
+
+def detect_initiator(lines)
+    lines.each do |line|
+        if line =~ /txed sm command: pair req/
+            $ctxt[:we_are_init] = true
+        elsif line =~ /txed sm command: pair rsp/
+            $ctxt[:we_are_init] = false
+        end
+    end
+
+    if $ctxt[:we_are_init] == nil
+        raise "could not detect which peer is the initiator"
+    end
+end
+
+def pair_cmd_to_s(cmd, is_req)
+    suffix = reqrsp_s(is_req)
+    return <<-eos
+        .pair_#{suffix} = {
+            .io_cap = #{to_hex_s(cmd[:io_cap])},
+            .oob_data_flag = #{to_hex_s(cmd[:oob_data_flag])},
+            .authreq = #{to_hex_s(cmd[:authreq])},
+            .max_enc_key_size = #{to_hex_s(cmd[:max_enc_key_size])},
+            .init_key_dist = #{to_hex_s(cmd[:init_key_dist])},
+            .resp_key_dist = #{to_hex_s(cmd[:resp_key_dist])},
+        },
+    eos
+end
+
+def privkey_to_s(privkey)
+    return bytes_to_arr(privkey, "our_priv_key", 8)
+end
+
+def public_key_to_s(public_key, is_req)
+    suffix = reqrsp_s(is_req)
+    return <<-eos
+        .public_key_#{suffix} = {
+#{bytes_to_arr(public_key[:x], "x", 12)}
+#{bytes_to_arr(public_key[:y], "y", 12)}
+        },
+    eos
+end
+
+def confirm_to_s(confirm, is_req, idx)
+    return <<-eos
+        .confirm_#{reqrsp_s(is_req)}[#{idx}] = {
+#{bytes_to_arr(confirm[:value], "value", 12)}
+        },
+    eos
+end
+
+def random_to_s(random, is_req, idx)
+    return <<-eos
+        .random_#{reqrsp_s(is_req)}[#{idx}] = {
+#{bytes_to_arr(random[:value], "value", 12)}
+        },
+    eos
+end
+
+def ltk_to_s(ltk)
+    return bytes_to_arr(ltk, "ltk", 8)
+end
+
+def stk_to_s(stk)
+    return bytes_to_arr(stk, "stk", 8)
+end
+
+def enc_info_to_s(id_info, is_req)
+    return <<-eos
+        .enc_info_#{reqrsp_s(is_req)} = {
+#{bytes_to_arr(id_info[:ltk], "ltk", 12)}
+        },
+    eos
+end
+
+def master_id_to_s(master_id, is_req)
+    return <<-eos
+        .master_id_#{reqrsp_s(is_req)} = {
+            .ediv = 0x#{master_id[:ediv].to_s(16)},
+            .rand_val = 0x#{master_id[:rand].to_s(16)},
+        },
+    eos
+end
+
+def id_info_to_s(id_info, is_req)
+    return <<-eos
+        .id_info_#{reqrsp_s(is_req)} = {
+#{bytes_to_arr(id_info[:irk], "irk", 12)}
+        },
+    eos
+end
+
+def id_addr_info_to_s(id_addr_info, is_req)
+    return <<-eos
+        .id_addr_info_#{reqrsp_s(is_req)} = {
+            .addr_type = #{id_addr_info[:addr_type]},
+#{bytes_to_arr(id_addr_info[:addr], "bd_addr", 12)}
+        },
+    eos
+end
+
+def sign_info_to_s(sign_info, is_req)
+    return <<-eos
+        .sign_info_#{reqrsp_s(is_req)} = {
+#{bytes_to_arr(sign_info[:sig_key], "sig_key", 12)}
+        },
+    eos
+end
+
+def passkey_info_fill(passkey_info)
+    case passkey_info[:action]
+    # None
+    when 0
+        $ctxt[:pair_alg] = 0
+        $ctxt[:authenticated] = false
+
+    # OOB
+    when 1
+        $ctxt[:pair_alg] = 2
+        $ctxt[:authenticated] = true
+
+    # Input
+    when 2
+        $ctxt[:pair_alg] = 1
+        $ctxt[:authenticated] = true
+
+    # Display
+    when 3
+        $ctxt[:pair_alg] = 1
+        $ctxt[:authenticated] = true
+
+    # Numeric comparison
+    when 4
+        $ctxt[:pair_alg] = 3
+        $ctxt[:authenticated] = true
+
+    else
+        raise "invalid MITM action: #{passkey_info[:action]}"
+    end
+end
+
+def passkey_info_s
+    passkey_info = $ctxt[:passkey_info]
+    action_str = $ACTION_STRINGS[passkey_info[:action]]
+
+    result = <<-eos
+        .pair_alg = #{$ctxt[:pair_alg]},
+        .authenticated = #{$ctxt[:authenticated]},
+        .passkey_info = {
+            .passkey = {
+                .action = #{action_str},
+    eos
+
+    if passkey_info[:key] != nil
+        result << <<-eos
+                .passkey = #{passkey_info[:key].to_i},
+        eos
+    end
+    if passkey_info[:oob] != nil
+        result << <<-eos
+#{bytes_to_arr(passkey_info[:oob], "oob", 16)}
+        eos
+    end
+    if passkey_info[:numcmp] != nil
+        result << <<-eos
+                .numcmp_accept = 1,
+        eos
+    end
+
+    result << <<-eos
+            },
+    eos
+
+    if passkey_info[:numcmp] != nil
+        result << <<-eos
+            .exp_numcmp = #{passkey_info[:numcmp].to_i},
+        eos
+    end
+
+    result << <<-eos
+        },
+    eos
+end
+
+def addrs_to_s(addrs)
+    s = ''
+
+    init_type = addrs[:init_type]
+    resp_type = addrs[:resp_type]
+
+    if init_type != 0
+        s += "        .init_addr_type = #{$ADDR_TYPE_STRINGS[init_type]},\n"
+    end
+    s += bytes_to_arr(addrs[:init_id_addr], "init_id_addr", 8) + "\n"
+    if init_type >= 2
+        s += bytes_to_arr(addrs[:init_rpa], "init_rpa", 8) + "\n"
+    end
+
+    if resp_type != 0
+        s += "        .resp_addr_type = #{$ADDR_TYPE_STRINGS[resp_type]},\n"
+    end
+    s += bytes_to_arr(addrs[:resp_id_addr], "resp_id_addr", 8) + "\n"
+    if resp_type >= 2
+        s += bytes_to_arr(addrs[:resp_rpa], "resp_rpa", 8) + "\n"
+    end
+
+    return s
+end
+
+def dhkey_check_to_s(dhkey_check, is_req)
+    return <<-eos
+        .dhkey_check_#{reqrsp_s(is_req)} = {
+#{bytes_to_arr(dhkey_check[:value], "value", 12)}
+        },
+    eos
+end
+
+def extract_one(lines, ignore_prev = false)
+    if ignore_prev
+        start = 0
+    else
+        start = $prev_idx
+    end
+
+    (start...lines.size).each do |idx|
+        line = lines[idx]
+        result = yield(line)
+        if result != nil
+            if !ignore_prev
+                $prev_idx = idx
+            end
+            return result
+        end
+    end
+
+    return nil
+end
+
+def extract_pair_req(lines)
+    return extract_one(lines) {|line| parse_pair_cmd(line, true)}
+end
+
+def extract_pair_rsp(lines)
+    return extract_one(lines) {|line| parse_pair_cmd(line, false)}
+end
+
+def extract_privkey(lines)
+    return extract_one(lines) {|line| parse_privkey(line)}
+end
+
+def extract_public_key_req(lines)
+    return extract_one(lines) do |line|
+        parse_public_key(line, $ctxt[:we_are_init])
+    end
+end
+
+def extract_public_key_rsp(lines)
+    return extract_one(lines) do |line|
+        parse_public_key(line, !$ctxt[:we_are_init])
+    end
+end
+
+def extract_confirm_req(lines)
+    return extract_one(lines) do |line|
+        parse_confirm(line, $ctxt[:we_are_init])
+    end
+end
+
+def extract_confirm_rsp(lines)
+    return extract_one(lines) do |line|
+        parse_confirm(line, !$ctxt[:we_are_init])
+    end
+end
+
+def extract_random_req(lines)
+    return extract_one(lines) do |line|
+        parse_random(line, $ctxt[:we_are_init])
+    end
+end
+
+def extract_random_rsp(lines)
+    return extract_one(lines) do |line|
+        parse_random(line, !$ctxt[:we_are_init])
+    end
+end
+
+def extract_confirm_random(lines)
+    confirm_reqs = []
+    confirm_rsps = []
+    random_reqs = []
+    random_rsps = []
+
+    idx = 0
+    loop do
+        confirm_req = extract_confirm_req(lines)
+        if confirm_req != nil
+            confirm_reqs << confirm_req
+        end
+
+        confirm_rsp = extract_confirm_rsp(lines)
+        break if confirm_rsp == nil
+        if idx >= 20
+            raise "too many confirm rsps (>20)"
+        end
+        confirm_rsps << confirm_rsp
+
+        random_req = extract_random_req(lines)
+        break if random_req == nil
+        random_reqs << random_req
+
+        random_rsp = extract_random_rsp(lines)
+        break if random_rsp == nil
+        random_rsps << random_rsp
+
+        idx += 1
+    end
+
+    return confirm_reqs, confirm_rsps, random_reqs, random_rsps
+end
+
+def extract_stk(lines)
+    return extract_one(lines, true) do |line|
+        parse_stk(line)
+    end
+end
+
+def extract_dhkey_check_req(lines)
+    return extract_one(lines) do |line|
+        parse_dhkey_check(line, $ctxt[:we_are_init])
+    end
+end
+
+def extract_dhkey_check_rsp(lines)
+    return extract_one(lines) do |line|
+        parse_dhkey_check(line, !$ctxt[:we_are_init])
+    end
+end
+
+def extract_enc_info_req(lines)
+    return extract_one(lines) do |line|
+        parse_enc_info(line, !$ctxt[:we_are_init])
+    end
+end
+
+def extract_enc_info_rsp(lines)
+    return extract_one(lines) do |line|
+        parse_enc_info(line, $ctxt[:we_are_init])
+    end
+end
+
+def extract_master_id_req(lines)
+    return extract_one(lines) do |line|
+        parse_master_id(line, !$ctxt[:we_are_init])
+    end
+end
+
+def extract_master_id_rsp(lines)
+    return extract_one(lines) do |line|
+        parse_master_id(line, $ctxt[:we_are_init])
+    end
+end
+
+def extract_id_info_req(lines)
+    return extract_one(lines) do |line|
+        parse_id_info(line, !$ctxt[:we_are_init])
+    end
+end
+
+def extract_id_info_rsp(lines)
+    return extract_one(lines) do |line|
+        parse_id_info(line, $ctxt[:we_are_init])
+    end
+end
+
+def extract_id_addr_info_req(lines)
+    return extract_one(lines) do |line|
+        parse_id_addr_info(line, !$ctxt[:we_are_init])
+    end
+end
+
+def extract_id_addr_info_rsp(lines)
+    return extract_one(lines) do |line|
+        parse_id_addr_info(line, $ctxt[:we_are_init])
+    end
+end
+
+def extract_sign_info_req(lines)
+    return extract_one(lines) do |line|
+        parse_sign_info(line, !$ctxt[:we_are_init])
+    end
+end
+
+def extract_sign_info_rsp(lines)
+    return extract_one(lines) do |line|
+        parse_sign_info(line, $ctxt[:we_are_init])
+    end
+end
+
+def extract_ltk(lines)
+    return extract_one(lines) do |line|
+        parse_ltk(line)
+    end
+end
+
+def extract_passkey_info(lines)
+    passkey_info = extract_one(lines, true) do |line|
+        parse_passkey_info(line)
+    end
+
+    if passkey_info == nil
+        passkey_info = { :action => 0 }
+    end
+
+    return passkey_info
+end
+
+def extract_addrs(lines)
+    return extract_one(lines) do |line|
+        parse_addrs(line)
+    end
+end
+
+
+lines = STDIN.readlines
+
+detect_initiator(lines)
+$ctxt[:pair_req] = extract_pair_req(lines)
+$ctxt[:pair_rsp] = extract_pair_rsp(lines)
+$ctxt[:privkey] = extract_privkey(lines)
+$ctxt[:public_key_req] = extract_public_key_req(lines)
+$ctxt[:public_key_rsp] = extract_public_key_rsp(lines)
+$ctxt[:confirm_reqs], $ctxt[:confirm_rsps], $ctxt[:random_reqs], $ctxt[:random_rsps] = extract_confirm_random(lines)
+$ctxt[:passkey_info] = extract_passkey_info(lines)
+$ctxt[:dhkey_check_req] = extract_dhkey_check_req(lines)
+$ctxt[:dhkey_check_rsp] = extract_dhkey_check_rsp(lines)
+$ctxt[:enc_info_req] = extract_enc_info_req(lines)
+$ctxt[:master_id_req] = extract_master_id_req(lines)
+$ctxt[:id_info_req] = extract_id_info_req(lines)
+$ctxt[:id_addr_info_req] = extract_id_addr_info_req(lines)
+$ctxt[:sign_info_req] = extract_sign_info_req(lines)
+$ctxt[:enc_info_rsp] = extract_enc_info_rsp(lines)
+$ctxt[:master_id_rsp] = extract_master_id_rsp(lines)
+$ctxt[:id_info_rsp] = extract_id_info_rsp(lines)
+$ctxt[:id_addr_info_rsp] = extract_id_addr_info_rsp(lines)
+$ctxt[:sign_info_rsp] = extract_sign_info_rsp(lines)
+$ctxt[:addrs] = extract_addrs(lines)
+$ctxt[:ltk] = extract_ltk(lines)
+$ctxt[:stk] = extract_stk(lines)
+
+expected_confirm_rsps = nil
+expected_random_reqs = nil
+expected_random_rsps = nil
+if $ctxt[:confirm_reqs].size == 0
+    expected_confirm_rsps = 1
+    expected_random_reqs = 1
+    expected_random_rsps = 1
+else
+    expected_confirm_rsps = $ctxt[:confirm_reqs].size
+    expected_random_reqs = $ctxt[:random_reqs].size
+    expected_random_rsps = $ctxt[:random_rsps].size
+end
+
+if $ctxt[:confirm_rsps].size != expected_confirm_rsps
+    raise "wrong number of confirm responses " +
+          "(exp=#{expected_confirm_rsps}; got=#{$ctxt[:confirm_rsps].size}"
+end
+
+if $ctxt[:random_reqs].size != expected_random_reqs
+    raise "wrong number of random requests " +
+          "(exp=#{expected_random_reqs}; got=#{$ctxt[:random_reqs].size}"
+end
+
+if $ctxt[:random_rsps].size != expected_random_rsps
+    raise "wrong number of random responses " +
+          "(exp=#{expected_random_rsps}; got=#{$ctxt[:random_rsps].size}"
+end
+
+passkey_info_fill($ctxt[:passkey_info])
+
+$ctxt[:sc] = $ctxt[:public_key_req] != nil
+$ctxt[:bonding] = $ctxt[:pair_req][:authreq] & 1 == 1 &&
+                  $ctxt[:pair_rsp][:authreq] & 1 == 1
+
+puts test_case_comment()
+puts <<-eos
+TEST_CASE(#{test_case_name()})
+{
+    struct ble_sm_test_params params;
+
+    params = (struct ble_sm_test_params) {
+eos
+
+puts addrs_to_s($ctxt[:addrs])
+
+puts pair_cmd_to_s($ctxt[:pair_req], true)
+puts pair_cmd_to_s($ctxt[:pair_rsp], false)
+
+if $ctxt[:sc]
+    puts privkey_to_s($ctxt[:privkey])
+    puts public_key_to_s($ctxt[:public_key_req], true)
+    puts public_key_to_s($ctxt[:public_key_req], false)
+end
+
+$ctxt[:confirm_rsps].size.times do |i|
+    confirm_req = $ctxt[:confirm_reqs][i]
+    confirm_rsp = $ctxt[:confirm_rsps][i]
+    random_req = $ctxt[:random_reqs][i]
+    random_rsp = $ctxt[:random_rsps][i]
+
+    if confirm_req != nil
+        puts confirm_to_s(confirm_req, true, i)
+    end
+
+    puts confirm_to_s(confirm_rsp, false, i)
+    puts random_to_s(random_req, true, i)
+    puts random_to_s(random_rsp, false, i)
+end
+
+if $ctxt[:sc]
+    puts dhkey_check_to_s($ctxt[:dhkey_check_req], true)
+    puts dhkey_check_to_s($ctxt[:dhkey_check_rsp], false)
+end
+
+if $ctxt[:enc_info_req] != nil
+    puts enc_info_to_s($ctxt[:enc_info_req], true)
+end
+if $ctxt[:master_id_req] != nil
+    puts master_id_to_s($ctxt[:master_id_req], true)
+end
+if $ctxt[:id_info_req] != nil
+    puts id_info_to_s($ctxt[:id_info_req], true)
+end
+if $ctxt[:id_addr_info_req] != nil
+    puts id_addr_info_to_s($ctxt[:id_addr_info_req], true)
+end
+if $ctxt[:sign_info_req] != nil
+    puts sign_info_to_s($ctxt[:sign_info_req], true)
+end
+if $ctxt[:enc_info_rsp] != nil
+    puts enc_info_to_s($ctxt[:enc_info_rsp], false)
+end
+if $ctxt[:master_id_rsp] != nil
+    puts master_id_to_s($ctxt[:master_id_rsp], false)
+end
+if $ctxt[:id_info_rsp] != nil
+    puts id_info_to_s($ctxt[:id_info_rsp], false)
+end
+if $ctxt[:id_addr_info_rsp] != nil
+    puts id_addr_info_to_s($ctxt[:id_addr_info_rsp], false)
+end
+if $ctxt[:sign_info_rsp] != nil
+    puts sign_info_to_s($ctxt[:sign_info_rsp], false)
+end
+if $ctxt[:sc]
+    puts ltk_to_s($ctxt[:ltk])
+else
+    puts stk_to_s($ctxt[:stk])
+end
+puts passkey_info_s()
+
+puts '    };'
+
+if $ctxt[:sc]
+    if $ctxt[:we_are_init]
+        puts '    ble_sm_test_util_us_sc_good(&params);'
+    else
+        puts '    ble_sm_test_util_peer_sc_good(&params);'
+    end
+else
+    if $ctxt[:we_are_init]
+        puts '    ble_sm_test_util_us_lgcy_good(&params);'
+    else
+        puts '    ble_sm_test_util_peer_lgcy_good(&params);'
+    end
+end
+puts '}'


[48/50] [abbrv] incubator-mynewt-core git commit: NimBLE - Host frees HCI cmd buf on ev alloc fail.

Posted by cc...@apache.org.
NimBLE - Host frees HCI cmd buf on ev alloc fail.

Old behavior: when ble_hci_transport_host_cmd_send() failed to allocate
an event for the HCI command, it tried to free the command buffer to the
g_hci_cmd_pool pool.  This became a problem when the host started using
a single statically-allocated buffer for all of its HCI commands.

New behavior: ble_hci_transport_host_cmd_send() doesn't free the buffer
on failure.  Instead, it is up to the caller to check the return code
and free the buffer on failure.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/53d7e653
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/53d7e653
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/53d7e653

Branch: refs/heads/master
Commit: 53d7e653b9239f1f17e99e7d757dad8b74c805a4
Parents: 9b008aa
Author: Christopher Collins <cc...@apache.org>
Authored: Thu Jul 7 19:49:33 2016 -0700
Committer: Christopher Collins <cc...@apache.org>
Committed: Thu Jul 7 19:49:33 2016 -0700

----------------------------------------------------------------------
 apps/blehci/src/main.c                 |  7 ++++++-
 net/nimble/controller/src/ble_ll_hci.c | 10 +++++++---
 2 files changed, 13 insertions(+), 4 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/53d7e653/apps/blehci/src/main.c
----------------------------------------------------------------------
diff --git a/apps/blehci/src/main.c b/apps/blehci/src/main.c
index ca2e39d..f0736b7 100755
--- a/apps/blehci/src/main.c
+++ b/apps/blehci/src/main.c
@@ -263,6 +263,8 @@ uart_rx_pkt_type(uint8_t data)
 static int
 uart_rx_cmd(uint8_t data)
 {
+    int rc;
+
     hci.tx_cmd.data[hci.tx_cmd.cur++] = data;
 
     if (hci.tx_cmd.cur < HCI_CMD_HDR_LEN) {
@@ -272,7 +274,10 @@ uart_rx_cmd(uint8_t data)
     }
 
     if (hci.tx_cmd.cur == hci.tx_cmd.len) {
-        ble_hci_transport_host_cmd_send(hci.tx_cmd.data);
+        rc = ble_hci_transport_host_cmd_send(hci.tx_cmd.data);
+        if (rc != 0) {
+            os_memblock_put(&g_hci_cmd_pool, hci.tx_cmd.data);
+        }
         hci.tx_type = H4_NONE;
     }
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/53d7e653/net/nimble/controller/src/ble_ll_hci.c
----------------------------------------------------------------------
diff --git a/net/nimble/controller/src/ble_ll_hci.c b/net/nimble/controller/src/ble_ll_hci.c
index a17515f..1d73465 100644
--- a/net/nimble/controller/src/ble_ll_hci.c
+++ b/net/nimble/controller/src/ble_ll_hci.c
@@ -983,20 +983,24 @@ ble_ll_hci_cmd_proc(struct os_event *ev)
 }
 
 /**
+ * Sends an HCI command to the controller.  On success, the supplied buffer is
+ * relinquished to the controller task.  On failure, the caller must free the
+ * buffer.
+ *
+ * @param cmd                   A flat buffer containing the HCI command to
+ *                                  send.
+ *
  * @return                      0 on success;
  *                              BLE_ERR_MEM_CAPACITY on HCI buffer exhaustion.
  */
 int
 ble_hci_transport_host_cmd_send(uint8_t *cmd)
 {
-    os_error_t err;
     struct os_event *ev;
 
     /* Get an event structure off the queue */
     ev = (struct os_event *)os_memblock_get(&g_hci_os_event_pool);
     if (!ev) {
-        err = os_memblock_put(&g_hci_cmd_pool, cmd);
-        assert(err == OS_OK);
         return BLE_ERR_MEM_CAPACITY;
     }
 


[46/50] [abbrv] incubator-mynewt-core git commit: BLE Host - unit tests for reading RSSI.

Posted by cc...@apache.org.
BLE Host - unit tests for reading RSSI.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/127d4259
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/127d4259
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/127d4259

Branch: refs/heads/master
Commit: 127d42593fcffad2f8e7b9b419822bddcd97713d
Parents: 4129157
Author: Christopher Collins <cc...@apache.org>
Authored: Sat Jul 2 19:51:34 2016 -0700
Committer: Christopher Collins <cc...@apache.org>
Committed: Sat Jul 2 19:51:34 2016 -0700

----------------------------------------------------------------------
 net/nimble/host/src/test/ble_host_hci_test.c | 43 +++++++++++++++++++++++
 1 file changed, 43 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/127d4259/net/nimble/host/src/test/ble_host_hci_test.c
----------------------------------------------------------------------
diff --git a/net/nimble/host/src/test/ble_host_hci_test.c b/net/nimble/host/src/test/ble_host_hci_test.c
index d451e7a..52837bd 100644
--- a/net/nimble/host/src/test/ble_host_hci_test.c
+++ b/net/nimble/host/src/test/ble_host_hci_test.c
@@ -38,9 +38,52 @@ TEST_CASE(ble_host_hci_test_event_bad)
     TEST_ASSERT(rc == BLE_HS_ENOTSUP);
 }
 
+TEST_CASE(ble_host_hci_test_rssi)
+{
+    uint8_t params[BLE_HCI_READ_RSSI_ACK_PARAM_LEN];
+    uint16_t opcode;
+    int8_t rssi;
+    int rc;
+
+    opcode = host_hci_opcode_join(BLE_HCI_OGF_STATUS_PARAMS,
+                                  BLE_HCI_OCF_RD_RSSI);
+
+    /*** Success. */
+    /* Connection handle. */
+    htole16(params + 0, 1);
+
+    /* RSSI. */
+    params[2] = -8;
+
+    ble_hs_test_util_set_ack_params(opcode, 0, params, sizeof params);
+
+    rc = ble_hci_util_read_rssi(1, &rssi);
+    TEST_ASSERT_FATAL(rc == 0);
+    TEST_ASSERT(rssi == -8);
+
+    /*** Failure: incorrect connection handle. */
+    htole16(params + 0, 99);
+
+    ble_hs_test_util_set_ack_params(opcode, 0, params, sizeof params);
+
+    rc = ble_hci_util_read_rssi(1, &rssi);
+    TEST_ASSERT(rc == BLE_HS_ECONTROLLER);
+
+    /*** Failure: params too short. */
+    ble_hs_test_util_set_ack_params(opcode, 0, params, sizeof params - 1);
+    rc = ble_hci_util_read_rssi(1, &rssi);
+    TEST_ASSERT(rc == BLE_HS_ECONTROLLER);
+
+    /*** Failure: params too long. */
+    ble_hs_test_util_set_ack_params(opcode, 0, params, sizeof params + 1);
+    rc = ble_hci_util_read_rssi(1, &rssi);
+    TEST_ASSERT(rc == BLE_HS_ECONTROLLER);
+}
+
 TEST_SUITE(ble_host_hci_suite)
 {
     ble_host_hci_test_event_bad();
+    ble_host_hci_test_rssi();
 }
 
 int


[14/50] [abbrv] incubator-mynewt-core git commit: This changes are to write the test code to test the event queue

Posted by cc...@apache.org.
This changes are to write the test code to test the event queue


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/9052048f
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/9052048f
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/9052048f

Branch: refs/heads/master
Commit: 9052048f7f97ee49b8ee180b345edce0538da075
Parents: e0c73d2
Author: NgesB <ng...@gmail.com>
Authored: Fri Jun 24 00:05:41 2016 +0100
Committer: NgesB <ng...@gmail.com>
Committed: Fri Jun 24 00:05:41 2016 +0100

----------------------------------------------------------------------
 libs/os/src/test/eventq_test.c  | 127 +++++++++++++++++++++++++++++++++++
 libs/os/src/test/os_test.c      |   2 +
 libs/os/src/test/os_test_priv.h |   2 +
 3 files changed, 131 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/9052048f/libs/os/src/test/eventq_test.c
----------------------------------------------------------------------
diff --git a/libs/os/src/test/eventq_test.c b/libs/os/src/test/eventq_test.c
new file mode 100644
index 0000000..29e5fe3
--- /dev/null
+++ b/libs/os/src/test/eventq_test.c
@@ -0,0 +1,127 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+ 
+
+#include "testutil/testutil.h"
+#include "os/os.h"
+#include "os_test_priv.h"
+#include "os/os_eventq.h"
+
+#define MY_STACK_SIZE        (5120)
+
+/*Task 1 sending task*/
+/* Define task stack and task object */
+#define SEND_TASK_PRIO        (1)
+struct os_task eventq_task_s;
+os_stack_t eventq_task_stack_s[MY_STACK_SIZE];
+
+/*Task 2 receiving task*/
+#define RECEIVE_TASK_PRIO     (2)
+struct os_task eventq_task_r;
+os_stack_t eventq_task_stack_r[MY_STACK_SIZE];
+
+struct os_eventq my_eventq;
+
+#define SIZE_MULTI_EVENT        (4)
+struct os_eventq multi_eventq[SIZE_MULTI_EVENT];
+
+/* This is to set the events we will use below */
+struct os_event g_event;
+struct os_event m_event[SIZE_MULTI_EVENT];
+
+/* Setting the event to send and receive multiple data */
+uint8_t my_event_type = 1;
+
+/* This is the task function  to send data */
+void
+eventq_task_send(void *arg)
+{
+    int i;
+
+    g_event.ev_queued = 0;
+    g_event.ev_type = my_event_type;
+    g_event.ev_arg = NULL;
+
+    os_eventq_put(&my_eventq, &g_event);
+
+    os_time_delay(OS_TICKS_PER_SEC / 2);
+
+    for (i = 0; i < SIZE_MULTI_EVENT; i++){
+        m_event[i].ev_type = i + 2;
+        m_event[i].ev_arg = NULL;
+
+        /* Put and send */
+        os_eventq_put(&multi_eventq[i], &m_event[i]);
+        os_time_delay(OS_TICKS_PER_SEC / 2);
+    }
+
+    /* This task sleeps until the receive task completes the test. */
+    os_time_delay(1000000);
+}
+
+/* This is the task function is the receiving function */
+void
+eventq_task_receive(void *arg)
+{
+    struct os_event *event;
+    int i;
+
+    event = os_eventq_get(&my_eventq);
+    TEST_ASSERT(event->ev_type == my_event_type);
+
+    /* Receiving multi event from the send task */
+    for (i = 0; i < SIZE_MULTI_EVENT; i++) {
+        event = os_eventq_get(&multi_eventq[i]);
+        TEST_ASSERT(event->ev_type == i + 2);
+    }
+
+    /* Finishes the test when OS has been started */
+    os_test_restart();
+}
+
+TEST_CASE(event_test_sr)
+{
+    int i;
+
+    /* Initializing the OS */
+    os_init();
+    /* Initialize the task */
+    os_task_init(&eventq_task_s, "eventq_task_s", eventq_task_send, NULL,
+        SEND_TASK_PRIO, OS_WAIT_FOREVER, eventq_task_stack_s, MY_STACK_SIZE);
+
+    /* Receive events and check whether the eevnts are correctly received */
+    os_task_init(&eventq_task_r, "eventq_task_r", eventq_task_receive, NULL,
+        RECEIVE_TASK_PRIO, OS_WAIT_FOREVER, eventq_task_stack_r,
+        MY_STACK_SIZE);
+
+    os_eventq_init(&my_eventq);
+
+    for (i = 0; i < SIZE_MULTI_EVENT; i++){
+        os_eventq_init(&multi_eventq[i]);
+    }
+
+    /* Does not return until OS_restart is called */
+    os_start();
+
+}
+
+TEST_SUITE(os_eventq_test_suite)
+{
+    event_test_sr();
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/9052048f/libs/os/src/test/os_test.c
----------------------------------------------------------------------
diff --git a/libs/os/src/test/os_test.c b/libs/os/src/test/os_test.c
index 0f180bb..1b3af1a 100644
--- a/libs/os/src/test/os_test.c
+++ b/libs/os/src/test/os_test.c
@@ -30,6 +30,8 @@ os_test_all(void)
     os_mutex_test_suite();
     os_sem_test_suite();
     os_mbuf_test_suite();
+    os_eventq_test_suite();
+    
 
     return tu_case_failed;
 }

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/9052048f/libs/os/src/test/os_test_priv.h
----------------------------------------------------------------------
diff --git a/libs/os/src/test/os_test_priv.h b/libs/os/src/test/os_test_priv.h
index 7293805..5193c33 100644
--- a/libs/os/src/test/os_test_priv.h
+++ b/libs/os/src/test/os_test_priv.h
@@ -26,5 +26,7 @@ int os_mempool_test_suite(void);
 int os_mbuf_test_suite(void);
 int os_mutex_test_suite(void);
 int os_sem_test_suite(void);
+int os_eventq_test_suite(void);
+
 
 #endif


[19/50] [abbrv] incubator-mynewt-core git commit: nordic MCUs; bug fix for bsp_hw_id(). It was copying 2nd half of the id from wrong registers.

Posted by cc...@apache.org.
nordic MCUs; bug fix for bsp_hw_id().
It was copying 2nd half of the id from wrong registers.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/e221e1e6
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/e221e1e6
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/e221e1e6

Branch: refs/heads/master
Commit: e221e1e620fef2e8adc814198ec9e2f24f0f8748
Parents: 712374a
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Thu Jun 23 18:00:28 2016 -0700
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Thu Jun 23 18:00:28 2016 -0700

----------------------------------------------------------------------
 hw/mcu/nordic/nrf51xxx/src/nrf51_hw_id.c | 2 +-
 hw/mcu/nordic/nrf52xxx/src/nrf52_hw_id.c | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/e221e1e6/hw/mcu/nordic/nrf51xxx/src/nrf51_hw_id.c
----------------------------------------------------------------------
diff --git a/hw/mcu/nordic/nrf51xxx/src/nrf51_hw_id.c b/hw/mcu/nordic/nrf51xxx/src/nrf51_hw_id.c
index 81279ac..cda946a 100644
--- a/hw/mcu/nordic/nrf51xxx/src/nrf51_hw_id.c
+++ b/hw/mcu/nordic/nrf51xxx/src/nrf51_hw_id.c
@@ -42,7 +42,7 @@ bsp_hw_id(uint8_t *id, int max_len)
     len = cnt;
 
     cnt = min(sizeof(NRF_FICR->DEVICEADDR), max_len - len);
-    memcpy(id + len, (void *)NRF_FICR->DEVICEID, cnt);
+    memcpy(id + len, (void *)NRF_FICR->DEVICEADDR, cnt);
 
     return len + cnt;
 }

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/e221e1e6/hw/mcu/nordic/nrf52xxx/src/nrf52_hw_id.c
----------------------------------------------------------------------
diff --git a/hw/mcu/nordic/nrf52xxx/src/nrf52_hw_id.c b/hw/mcu/nordic/nrf52xxx/src/nrf52_hw_id.c
index 9042153..e982993 100644
--- a/hw/mcu/nordic/nrf52xxx/src/nrf52_hw_id.c
+++ b/hw/mcu/nordic/nrf52xxx/src/nrf52_hw_id.c
@@ -42,7 +42,7 @@ bsp_hw_id(uint8_t *id, int max_len)
     len = cnt;
 
     cnt = min(sizeof(NRF_FICR->DEVICEADDR), max_len - len);
-    memcpy(id + len, (void *)NRF_FICR->DEVICEID, cnt);
+    memcpy(id + len, (void *)NRF_FICR->DEVICEADDR, cnt);
 
     return len + cnt;
 }


[35/50] [abbrv] incubator-mynewt-core git commit: Legacy NFFS version support to standalone mode of ffs2native

Posted by cc...@apache.org.
Legacy NFFS version support to standalone mode of ffs2native

Standalone mode (-s) takes an NFFS flash image file and prints the contents
without regards to a specific flash area layout. The layout is determined from
parsing the input file and this allows NFFS format image files from
any device to be printed, regardless of the HW flash layout.

This change adds support for V0 layouts - the version is automatically
detected from parsing the data structures in the image.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/27a8888f
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/27a8888f
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/27a8888f

Branch: refs/heads/master
Commit: 27a8888f460493e3a1f7483e803414c91207c834
Parents: f9ef568
Author: Peter Snyder <gi...@peterfs.com>
Authored: Wed Jun 29 14:04:01 2016 -0700
Committer: Peter Snyder <gi...@peterfs.com>
Committed: Wed Jun 29 14:04:01 2016 -0700

----------------------------------------------------------------------
 apps/ffs2native/src/main.c | 370 ++++++++++++++++++++--------------------
 1 file changed, 183 insertions(+), 187 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/27a8888f/apps/ffs2native/src/main.c
----------------------------------------------------------------------
diff --git a/apps/ffs2native/src/main.c b/apps/ffs2native/src/main.c
index 2b42159..cfa4688 100644
--- a/apps/ffs2native/src/main.c
+++ b/apps/ffs2native/src/main.c
@@ -50,12 +50,12 @@ char *file_flash_area;
 size_t file_flash_size;
 int file_scratch_idx;
 
-#define MAX_AREAS	16
+#define MAX_AREAS    16
 static struct nffs_area_desc area_descs[MAX_AREAS];
 int nffs_version;
 
 /** On-disk representation of a version 0 inode (file or directory). */
-struct nffs_disk_inodeV0 {
+struct nffs_disk_V0inode {
     uint32_t ndi_magic;         /* NFFS_INODE_MAGIC */
     uint32_t ndi_id;            /* Unique object ID. */
     uint32_t ndi_seq;           /* Sequence number; greater supersedes
@@ -66,10 +66,10 @@ struct nffs_disk_inodeV0 {
     uint16_t ndi_crc16;         /* Covers rest of header and filename. */
     /* Followed by filename. */
 };
-#define NFFS_DISK_INODEV0_OFFSET_CRC  18
+#define NFFS_DISK_V0INODE_OFFSET_CRC  18
 
 /** On-disk representation of a version 0 data block. */
-struct nffs_disk_blockV0 {
+struct nffs_disk_V0block {
     uint32_t ndb_magic;     /* NFFS_BLOCK_MAGIC */
     uint32_t ndb_id;        /* Unique object ID. */
     uint32_t ndb_seq;       /* Sequence number; greater supersedes lesser. */
@@ -80,7 +80,20 @@ struct nffs_disk_blockV0 {
     uint16_t ndb_crc16;     /* Covers rest of header and data. */
     /* Followed by 'ndb_data_len' bytes of data. */
 };
-#define NFFS_DISK_BLOCKV0_OFFSET_CRC  22
+#define NFFS_DISK_V0BLOCK_OFFSET_CRC  22
+
+struct nffs_disk_V0object {
+    int ndo_type;
+    uint8_t ndo_area_idx;
+    uint32_t ndo_offset;
+    union {
+        struct nffs_disk_V0inode ndo_disk_V0inode;
+        struct nffs_disk_V0block ndo_disk_V0block;
+    } ndo_un_obj;
+};
+
+#define ndo_disk_V0inode    ndo_un_obj.ndo_disk_V0inode
+#define ndo_disk_V0block    ndo_un_obj.ndo_disk_V0block
 
 static void usage(int rc);
 
@@ -115,13 +128,13 @@ print_inode_entry(struct nffs_inode_entry *inode_entry, int indent)
     int rc;
 
     rc = nffs_inode_from_entry(&inode, inode_entry);
-	/*
-	 * Dummy inode
-	 */
-	if (rc == FS_ENOENT) {
-		printf("    DUMMY %d\n", rc);
-		return;
-	}
+    /*
+     * Dummy inode
+     */
+    if (rc == FS_ENOENT) {
+        printf("    DUMMY %d\n", rc);
+        return;
+    }
     assert(rc == 0);
 
     nffs_flash_loc_expand(inode_entry->nie_hash_entry.nhe_flash_loc,
@@ -151,24 +164,23 @@ process_inode_entry(struct nffs_inode_entry *inode_entry, int indent)
     }
 }
 
-#ifdef OBSOLETE /* XXX To be removed */
 static int
 print_nffs_inode(struct nffs_disk_inode *ndi, int idx, uint32_t off)
 {
     char filename[128];
     int len;
-	int rc;
+    int rc;
 
     memset(filename, 0, sizeof(filename));
     len = min(sizeof(filename) - 1, ndi->ndi_filename_len);
     rc = nffs_flash_read(idx, off + sizeof(struct nffs_disk_inode),
-						 filename, len);
+                         filename, len);
     printf("      %x-%d inode %d/%d",
       off, ndi->ndi_filename_len, ndi->ndi_id, ndi->ndi_seq);
-	if (rc == 0)
-		printf(" %s\n", filename);
-	else
-		printf("\n");
+    if (rc == 0)
+        printf(" %s\n", filename);
+    else
+        printf("\n");
     return (sizeof(struct nffs_disk_inode) + ndi->ndi_filename_len);
 }
 
@@ -183,34 +195,34 @@ print_nffs_block(struct nffs_disk_block *ndb, int idx, uint32_t off)
 static int
 print_nffs_object(int idx, uint32_t off)
 {
-	struct nffs_disk_object dobj;
+    struct nffs_disk_object dobj;
     int rc;
 
     rc = nffs_flash_read(idx, off, &dobj.ndo_un_obj, sizeof(dobj.ndo_un_obj));
     assert(rc == 0);
 
-	if (nffs_hash_id_is_inode(dobj.ndo_disk_inode.ndi_id)) {
+    if (nffs_hash_id_is_inode(dobj.ndo_disk_inode.ndi_id)) {
         return print_nffs_inode(&dobj.ndo_disk_inode, idx, off);
 
-	} else if (nffs_hash_id_is_block(dobj.ndo_disk_inode.ndi_id)) {
+    } else if (nffs_hash_id_is_block(dobj.ndo_disk_inode.ndi_id)) {
         return print_nffs_block(&dobj.ndo_disk_block, idx, off);
 
-	} else if (dobj.ndo_disk_inode.ndi_id == NFFS_ID_NONE) {
-		assert(0);
+    } else if (dobj.ndo_disk_inode.ndi_id == NFFS_ID_NONE) {
+        assert(0);
         return 0;
 
-	} else {
+    } else {
         printf("      %x Corruption\n", off);
-		return 1;
-	}
+        return 1;
+    }
 }
 
 static void
 print_nffs_darea(struct nffs_disk_area *darea)
 {
-	printf("\tdarea: len %d ver %d gc_seq %d id %x\n",
-		   darea->nda_length, darea->nda_ver,
-		   darea->nda_gc_seq, darea->nda_id);
+    printf("\tdarea: len %d ver %d gc_seq %d id %x\n",
+           darea->nda_length, darea->nda_ver,
+           darea->nda_gc_seq, darea->nda_id);
 }
 
 static void
@@ -224,14 +236,14 @@ print_nffs_area(int idx)
     area = &nffs_areas[idx];
     rc = nffs_flash_read(idx, 0, &darea, sizeof(darea));
     assert(rc == 0);
-	print_nffs_darea(&darea);
+    print_nffs_darea(&darea);
     if (!nffs_area_magic_is_set(&darea)) {
         printf("Area header corrupt!\n");
         return;
     }
-	/*
-	 * XXX Enhance to print but not restore unsupported formats
-	 */
+    /*
+     * XXX Enhance to print but not restore unsupported formats
+     */
     if (!nffs_area_is_current_version(&darea)) {
         printf("Area format is not supported!\n");
         return;
@@ -262,7 +274,6 @@ print_nffs_areas(void)
         print_nffs_area(i);
     }
 } 
-#endif /* OBSOLETE */
 
 static int
 copy_in_file(char *src, char *dst)
@@ -320,7 +331,9 @@ copy_in_directory(const char *src, const char *dst)
             printf("Copying %s\n", dst_name);
             rc = copy_in_file(src_name, dst_name);
             if (rc) {
-                printf("  error code %d ", rc);
+                if (print_verbose) {
+                    printf("  error code %d ", rc);
+                }
                 switch (rc) {
                 case FS_ENOMEM:
                     printf("out of memory\n");
@@ -334,7 +347,9 @@ copy_in_directory(const char *src, const char *dst)
                 break;
             }
         } else {
-            printf("Skipping %s\n", src_name);
+            if (print_verbose) {
+                printf("Skipping %s\n", src_name);
+            }
         }
     }
     closedir(dr);
@@ -343,15 +358,17 @@ copy_in_directory(const char *src, const char *dst)
 static int
 file_flash_read(uint32_t addr, void *dst, int byte_cnt)
 {
-	memcpy(dst, (void*)file_flash_area + addr, byte_cnt);
-	return 0;
+    memcpy(dst, (void*)file_flash_area + addr, byte_cnt);
+    return 0;
 }
 
-#ifdef NOTYET
+/*
+ * Print NFFS V0 structures
+ */
 static int
-print_nffsV0_flash_inode(struct nffs_disk_object *ndo, uint32_t off)
+print_nffs_flash_V0inode(struct nffs_area_desc *area, uint32_t off)
 {
-    struct nffs_disk_inode *ndi = &ndo->ndo_disk_inode;
+    struct nffs_disk_V0inode ndi;
     char filename[128];
     int len;
     int rc;
@@ -362,45 +379,54 @@ print_nffsV0_flash_inode(struct nffs_disk_object *ndo, uint32_t off)
     memset(filename, 0, sizeof(filename));
     len = min(sizeof(filename) - 1, ndi.ndi_filename_len);
     rc = file_flash_read(area->nad_offset + off + sizeof(ndi), filename, len);
+    filename[len] = '\0';
+    assert(rc == 0);
 
-	printf("  off %x flen %d %s id %x seq %d prnt %x lstb %x %s\n",
-		   off, ndi.ndi_filename_len,
-		   (nffs_hash_id_is_file(ndi.ndi_id) ? "File" :
-			(nffs_hash_id_is_dir(ndi.ndi_id) ? "Dir" : "???")),
-		   ndi.ndi_id, ndi.ndi_seq, ndi.ndi_parent_id,
-		   ndi.ndi_lastblock_id, filename);
-    return sizeof(struct nffs_disk_inode) + ndi->ndi_filename_len;
+    printf("   %s off %x id %x magic %x flen %d seq %d prnt %x %s\n",
+           (nffs_hash_id_is_file(ndi.ndi_id) ? "File" :
+            (nffs_hash_id_is_dir(ndi.ndi_id) ? "Dir" : "???")),
+           off, ndi.ndi_id, ndi.ndi_magic, ndi.ndi_filename_len,
+           ndi.ndi_seq, ndi.ndi_parent_id, filename);
+    return sizeof(struct nffs_disk_V0inode) + ndi.ndi_filename_len;
 }
 
 static int
-print_nffsV0_flash_block(struct nffs_disk_object *ndo, uint32_t off)
+print_nffs_flash_V0block(struct nffs_area_desc *area, uint32_t off)
 {
-    struct nffs_disk_block *ndb = &ndo->ndo_disk_block;
+    struct nffs_disk_V0block ndb;
     int rc;
 
-    printf("  off %x len %d Block id %x seq %d prev %x own ino %x\n",
-		   off, ndb->ndb_data_len, ndb->ndb_id, ndb->ndb_seq,
-		   ndb->ndb_prev_id, ndb->ndb_inode_id);
-    return sizeof(struct nffs_disk_block) + ndb->ndb_data_len;
+    rc = file_flash_read(area->nad_offset + off, &ndb, sizeof(ndb));
+    assert(rc == 0);
+
+    printf("   Block off %x id %x len %d seq %d prev %x ino %x\n",
+           off, ndb.ndb_id, ndb.ndb_data_len, ndb.ndb_seq,
+           ndb.ndb_prev_id, ndb.ndb_inode_id);
+    return sizeof(struct nffs_disk_V0block) + ndb.ndb_data_len;
 }
 
 static int
-print_nffsV0_flash_object(struct nffs_area_desc *area, uint32_t off)
+print_nffs_flash_V0object(struct nffs_area_desc *area, uint32_t off)
 {
-	struct nffs_disk_object ndo;
-    uint32_t magic;
+    struct nffs_disk_V0object ndo;
+    int rc;
+
+    rc = file_flash_read(area->nad_offset + off, &ndo, sizeof(ndo));
+    assert(rc == 0);
+
+    if (nffs_hash_id_is_inode(ndo.ndo_disk_V0inode.ndi_id)) {
+        return print_nffs_flash_V0inode(area, off);
 
-	file_flash_read(area->nad_offset + off, &ndo, sizeof(ndo));
-	if (nffs_hash_id_is_inode(ndo.ndo_disk_inode.ndi_id)) {
-        return print_nffsV0_flash_inode(&ndo, off);
+    } else if (nffs_hash_id_is_block(ndo.ndo_disk_V0block.ndb_id)) {
+        return print_nffs_flash_V0block(area, off);
 
-	} else if (nffs_hash_id_is_block(ndo.ndo_disk_block.ndb_id)) {
-        return print_nffsV0_flash_block(&ndo, off);
+    } else if (ndo.ndo_disk_V0block.ndb_id == 0xffffffff) {
+        return area->nad_length;
 
-	}
-	return sizeof(ndo);
+    } else {
+        return 1;
+    }
 }
-#endif /* NOTYET */
 
 static int
 print_nffs_flash_inode(struct nffs_area_desc *area, uint32_t off)
@@ -455,7 +481,7 @@ print_nffs_flash_object(struct nffs_area_desc *area, uint32_t off)
 {
     struct nffs_disk_object ndo;
 
-	file_flash_read(area->nad_offset + off, &ndo, sizeof(ndo));
+    file_flash_read(area->nad_offset + off, &ndo, sizeof(ndo));
 
     if (nffs_hash_id_is_inode(ndo.ndo_disk_inode.ndi_id)) {
         return print_nffs_flash_inode(area, off);
@@ -471,6 +497,7 @@ print_nffs_flash_object(struct nffs_area_desc *area, uint32_t off)
     }
 }
 
+#if 0
 void
 print_file_areas()
 {
@@ -479,116 +506,87 @@ print_file_areas()
     int i;
 
     for (i = 0; i < nffs_num_areas; i++) {
-		area = &area_descs[i];
+        area = &area_descs[i];
         printf("%d: id:%d 0x%x - 0x%x %s\n",
-			   i, area->nad_flash_id, area->nad_offset,
-			   area->nad_offset + area->nad_length,
-			   (i == file_scratch_idx ? "(scratch)" : ""));
-		off = sizeof (struct nffs_disk_area);
-		while (off < area->nad_length) {
-#ifdef NOTYET
-			if (nffs_version == 0) {
-				off += print_nffsV0_flash_object(area, off);
-			} else if (nffs_version == NFFS_AREA_VER) {
-				off += print_nffs_flash_object(area, off);
-			}
-#else
-			off += print_nffs_flash_object(area, off);
-#endif /* NOTYET */
-		}
+               i, area->nad_flash_id, area->nad_offset,
+               area->nad_offset + area->nad_length,
+               (i == file_scratch_idx ? "(scratch)" : ""));
+        off = sizeof (struct nffs_disk_area);
+        while (off < area->nad_length) {
+            if (nffs_version == 0) {
+                off += print_nffsV0_flash_object(area, off);
+            } else if (nffs_version == NFFS_AREA_VER) {
+                off += print_nffs_flash_object(area, off);
+            }
+        }
     }
 }
+#endif
 
 static void
-print_nffs_flash_areas(char *flash_area, size_t size)
+print_nffs_file_flash(char *flash_area, size_t size)
 {
-	char *daptr;		/* Disk Area Pointer */
-	char *eoda;			/* End Of Disk Area */
-	struct nffs_disk_area *nda;
-	int nad_cnt = 0;	/* Nffs Area Descriptor count */
-	int off;
-
-	daptr = flash_area;
-	eoda = flash_area + size;
-	while (daptr < eoda) {
-		if (nffs_area_magic_is_set((struct nffs_disk_area*)daptr)) {
-			nda = (struct nffs_disk_area*)daptr;
-			area_descs[nad_cnt].nad_offset = (daptr - flash_area);
-			area_descs[nad_cnt].nad_length = nda->nda_length;
-			area_descs[nad_cnt].nad_flash_id = nda->nda_id;
-			nffs_version = nda->nda_ver;
-
-			if (nda->nda_id == 0xff)
-				file_scratch_idx = nad_cnt;
-
-			printf("area %d: id %d %x-%x len %d flshid %x gcseq %d %s\n",
-				   nad_cnt, nda->nda_id,
-				   area_descs[nad_cnt].nad_offset,
-				   area_descs[nad_cnt].nad_offset +
-				       area_descs[nad_cnt].nad_length,
-				   area_descs[nad_cnt].nad_length,
-				   area_descs[nad_cnt].nad_flash_id,
-				   nda->nda_gc_seq,
-				   nffs_scratch_area_idx == nad_cnt ? "(scratch)" : "");
+    char *daptr;        /* Disk Area Pointer */
+    char *eoda;            /* End Of Disk Area */
+    struct nffs_disk_area *nda;
+    int nad_cnt = 0;    /* Nffs Area Descriptor count */
+    int off;
+
+    daptr = flash_area;
+    eoda = flash_area + size;
+    printf("\nNFFS Flash Areas:\n");
+    while (daptr < eoda) {
+        if (nffs_area_magic_is_set((struct nffs_disk_area*)daptr)) {
+            nda = (struct nffs_disk_area*)daptr;
+            area_descs[nad_cnt].nad_offset = (daptr - flash_area);
+            area_descs[nad_cnt].nad_length = nda->nda_length;
+            area_descs[nad_cnt].nad_flash_id = nda->nda_id;
+            nffs_version = nda->nda_ver;
+
+            if (nda->nda_id == 0xff)
+                file_scratch_idx = nad_cnt;
+
+            printf("Area %d: off %x-%x len %d flshid %x gcseq %d ver %d id %x%s%s\n",
+                   nad_cnt,
+                   area_descs[nad_cnt].nad_offset,
+                   area_descs[nad_cnt].nad_offset +
+                                 area_descs[nad_cnt].nad_length,
+                   area_descs[nad_cnt].nad_length,
+                   area_descs[nad_cnt].nad_flash_id,
+                   nda->nda_gc_seq,
+                   nda->nda_ver,
+                   nda->nda_id,
+                   nda->nda_ver != NFFS_AREA_VER ? " (V0)" : "",
+                   nad_cnt == file_scratch_idx ? " (Scratch)" : "");
 
             off = sizeof (struct nffs_disk_area);
             while (off < area_descs[nad_cnt].nad_length) {
-                off += print_nffs_flash_object(&area_descs[nad_cnt], off);
+                if (nffs_version == 0) {
+                    off += print_nffs_flash_V0object(&area_descs[nad_cnt], off);
+                } else if (nffs_version == NFFS_AREA_VER) {
+                    off += print_nffs_flash_object(&area_descs[nad_cnt], off);
+                }
             }
+            printf("\n");
 
-			nad_cnt++;
-			daptr = daptr + nda->nda_length;
-		} else {
-			daptr++;
-		}
-	}
-	nffs_num_areas = nad_cnt;
+            nad_cnt++;
+            daptr = daptr + nda->nda_length;
+        } else {
+            daptr++;
+        }
+    }
+    nffs_num_areas = nad_cnt;
 }
 
 static void
 printfs(void)
 {
-	printf("NFFS directory:\n");
-	process_inode_entry(nffs_root_dir, print_verbose);
+    printf("\nNFFS directory:\n");
+    process_inode_entry(nffs_root_dir, print_verbose);
 
-    printf("\nNFFS flash areas:\n");
-    print_nffs_flash_areas(file_flash_area, file_flash_size);
-}
+    printf("\nNFFS areas:\n");
+    print_nffs_areas();
 
-int
-file_area_init(char *flash_area, size_t size)
-{
-	char *daptr;		/* Disk Area Pointer */
-	char *eoda;			/* End Of Disk Area */
-	struct nffs_disk_area *nda;
-	int nad_cnt = 0;	/* Nffs Area Descriptor count */
-
-	daptr = flash_area;
-	eoda = flash_area + size;
-	while (daptr < eoda) {
-		if (nffs_area_magic_is_set((struct nffs_disk_area*)daptr)) {
-			nda = (struct nffs_disk_area*)daptr;
-			area_descs[nad_cnt].nad_offset = (daptr - flash_area);
-			area_descs[nad_cnt].nad_length = nda->nda_length;
-			area_descs[nad_cnt].nad_flash_id = nda->nda_id;
-			nffs_version = nda->nda_ver;
-			if (nda->nda_id == 0xff)
-				file_scratch_idx = nad_cnt;
-			printf("area %d: off %d len %d flshid %x gc-seq %d id %x ver %d %s\n",
-				   nad_cnt,
-				   area_descs[nad_cnt].nad_offset,
-				   area_descs[nad_cnt].nad_length,
-				   area_descs[nad_cnt].nad_flash_id,
-				   nda->nda_gc_seq, nda->nda_id, nda->nda_ver,
-				   nda->nda_id == 0xff ? "(scratch)" : "");
-			nad_cnt++;
-			daptr = daptr + nda->nda_length;
-		} else {
-			daptr++;
-		}
-	}
-	nffs_num_areas = nad_cnt;
-	return 0;
 }
 
 static void
@@ -608,12 +606,12 @@ int
 main(int argc, char **argv)
 {
     FILE *fp;
-	int fd;
+    int fd;
     int rc;
     int ch;
     int cnt;
-	struct stat st;
-	int standalone = 0;
+    struct stat st;
+    int standalone = 0;
 
     progname = argv[0];
 
@@ -628,9 +626,9 @@ main(int argc, char **argv)
         case 'd':
             copy_in_dir = optarg;
             break;
-		case 's':
-			standalone++;
-			break;
+        case 's':
+            standalone++;
+            break;
         case 'f':
             native_flash_file = optarg;
             break;
@@ -644,10 +642,10 @@ main(int argc, char **argv)
     }
 
     os_init();
-	if (standalone == 0) {
-		rc = flash_area_to_nffs_desc(FLASH_AREA_NFFS, &cnt, area_descs);
-		assert(rc == 0);
-	}
+    if (standalone == 0) {
+        rc = flash_area_to_nffs_desc(FLASH_AREA_NFFS, &cnt, area_descs);
+        assert(rc == 0);
+    }
 
     rc = hal_flash_init();
     assert(rc == 0);
@@ -655,26 +653,24 @@ main(int argc, char **argv)
     rc = nffs_init();
     assert(rc == 0);
 
-	log_init();
-	log_console_handler_init(&nffs_log_console_handler);
-	log_register("nffs-log", &nffs_log, &nffs_log_console_handler);
-
-	if (standalone) {
-		fd = open(native_flash_file, O_RDWR);
-		if ((rc = fstat(fd, &st)))
-			perror("fstat failed");
-		file_flash_size = st.st_size;
-		if ((file_flash_area = mmap(0, (size_t)8192, PROT_READ,
-							   MAP_FILE|MAP_SHARED, fd, 0)) == MAP_FAILED) {
-			perror("%s mmap failed");
-		}
-
-		rc = file_area_init(file_flash_area, file_flash_size);
+    log_init();
+    log_console_handler_init(&nffs_log_console_handler);
+    log_register("nffs-log", &nffs_log, &nffs_log_console_handler);
+
+    if (standalone) {
+        fd = open(native_flash_file, O_RDWR);
+        if ((rc = fstat(fd, &st)))
+            perror("fstat failed");
+        file_flash_size = st.st_size;
+        if ((file_flash_area = mmap(0, (size_t)8192, PROT_READ,
+                               MAP_FILE|MAP_SHARED, fd, 0)) == MAP_FAILED) {
+            perror("%s mmap failed");
+        }
 
-		print_nffs_flash_areas(file_flash_area, file_flash_size);
+        print_nffs_file_flash(file_flash_area, file_flash_size);
 
-		return 0;
-	}
+        return 0;
+    }
 
     if (copy_in_dir) {
         /*


[17/50] [abbrv] incubator-mynewt-core git commit: MYNEWT-79: fix native cputime and add the common hal source file

Posted by cc...@apache.org.
MYNEWT-79: fix native cputime and add the common hal source file


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/712374ac
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/712374ac
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/712374ac

Branch: refs/heads/master
Commit: 712374ac2ae9a5b8465eab0cb6242f93165cc00a
Parents: 183873d
Author: William San Filippo <wi...@runtime.io>
Authored: Thu Jun 23 16:14:56 2016 -0700
Committer: William San Filippo <wi...@runtime.io>
Committed: Thu Jun 23 16:39:04 2016 -0700

----------------------------------------------------------------------
 hw/hal/src/hal_cputime.c        | 342 +++++++++++++++++++++++++++++++++++
 hw/mcu/native/src/hal_cputime.c |   6 +
 2 files changed, 348 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/712374ac/hw/hal/src/hal_cputime.c
----------------------------------------------------------------------
diff --git a/hw/hal/src/hal_cputime.c b/hw/hal/src/hal_cputime.c
new file mode 100644
index 0000000..980b3e1
--- /dev/null
+++ b/hw/hal/src/hal_cputime.c
@@ -0,0 +1,342 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+
+#include <string.h>
+#include <stdint.h>
+#include <assert.h>
+#include "os/os.h"
+#include "hal/hal_cputime.h"
+
+/* XXX:
+ *  - Must determine how to set priority of cpu timer interrupt
+ *  - Determine if we should use a mutex as opposed to disabling interrupts
+ *  - Should I use macro for compare channel?
+ *  - Sync to OSTIME.
+ */
+struct cputime_data g_cputime;
+
+/* Queue for timers */
+TAILQ_HEAD(cputime_qhead, cpu_timer) g_cputimer_q;
+
+/**
+ * cputime chk expiration
+ *
+ * Iterates through the cputimer queue to determine if any timers have expired.
+ * If the timer has expired the timer is removed from the queue and the timer
+ * callback function is executed.
+ *
+ */
+void
+cputime_chk_expiration(void)
+{
+    os_sr_t sr;
+    struct cpu_timer *timer;
+
+    OS_ENTER_CRITICAL(sr);
+    while ((timer = TAILQ_FIRST(&g_cputimer_q)) != NULL) {
+        if ((int32_t)(cputime_get32() - timer->cputime) >= 0) {
+            TAILQ_REMOVE(&g_cputimer_q, timer, link);
+            timer->link.tqe_prev = NULL;
+            timer->cb(timer->arg);
+        } else {
+            break;
+        }
+    }
+
+    /* Any timers left on queue? If so, we need to set OCMP */
+    timer = TAILQ_FIRST(&g_cputimer_q);
+    if (timer) {
+        cputime_set_ocmp(timer);
+    } else {
+        cputime_disable_ocmp();
+    }
+    OS_EXIT_CRITICAL(sr);
+}
+
+/**
+ * cputime init
+ *
+ * Initialize the cputime module. This must be called after os_init is called
+ * and before any other timer API are used. This should be called only once
+ * and should be called before the hardware timer is used.
+ *
+ * @param clock_freq The desired cputime frequency, in hertz (Hz).
+ *
+ * @return int 0 on success; -1 on error.
+ */
+int
+cputime_init(uint32_t clock_freq)
+{
+    int rc;
+
+    TAILQ_INIT(&g_cputimer_q);
+    rc = cputime_hw_init(clock_freq);
+    return rc;
+}
+
+
+/**
+ * cputime nsecs to ticks
+ *
+ * Converts the given number of nanoseconds into cputime ticks.
+ *
+ * @param usecs The number of nanoseconds to convert to ticks
+ *
+ * @return uint32_t The number of ticks corresponding to 'nsecs'
+ */
+uint32_t
+cputime_nsecs_to_ticks(uint32_t nsecs)
+{
+    uint32_t ticks;
+
+    ticks = ((nsecs * g_cputime.ticks_per_usec) + 999) / 1000;
+    return ticks;
+}
+
+/**
+ * cputime ticks to nsecs
+ *
+ * Convert the given number of ticks into nanoseconds.
+ *
+ * @param ticks The number of ticks to convert to nanoseconds.
+ *
+ * @return uint32_t The number of nanoseconds corresponding to 'ticks'
+ */
+uint32_t
+cputime_ticks_to_nsecs(uint32_t ticks)
+{
+    uint32_t nsecs;
+
+    nsecs = ((ticks * 1000) + (g_cputime.ticks_per_usec - 1)) /
+            g_cputime.ticks_per_usec;
+
+    return nsecs;
+}
+
+/**
+ * cputime usecs to ticks
+ *
+ * Converts the given number of microseconds into cputime ticks.
+ *
+ * @param usecs The number of microseconds to convert to ticks
+ *
+ * @return uint32_t The number of ticks corresponding to 'usecs'
+ */
+uint32_t
+cputime_usecs_to_ticks(uint32_t usecs)
+{
+    uint32_t ticks;
+
+    ticks = (usecs * g_cputime.ticks_per_usec);
+    return ticks;
+}
+
+/**
+ * cputime ticks to usecs
+ *
+ * Convert the given number of ticks into microseconds.
+ *
+ * @param ticks The number of ticks to convert to microseconds.
+ *
+ * @return uint32_t The number of microseconds corresponding to 'ticks'
+ */
+uint32_t
+cputime_ticks_to_usecs(uint32_t ticks)
+{
+    uint32_t us;
+
+    us =  (ticks + (g_cputime.ticks_per_usec - 1)) / g_cputime.ticks_per_usec;
+    return us;
+}
+
+/**
+ * cputime delay ticks
+ *
+ * Wait until the number of ticks has elapsed. This is a blocking delay.
+ *
+ * @param ticks The number of ticks to wait.
+ */
+void
+cputime_delay_ticks(uint32_t ticks)
+{
+    uint32_t until;
+
+    until = cputime_get32() + ticks;
+    while ((int32_t)(cputime_get32() - until) < 0) {
+        /* Loop here till finished */
+    }
+}
+
+/**
+ * cputime delay nsecs
+ *
+ * Wait until 'nsecs' nanoseconds has elapsed. This is a blocking delay.
+ *
+ * @param nsecs The number of nanoseconds to wait.
+ */
+void
+cputime_delay_nsecs(uint32_t nsecs)
+{
+    uint32_t ticks;
+
+    ticks = cputime_nsecs_to_ticks(nsecs);
+    cputime_delay_ticks(ticks);
+}
+
+/**
+ * cputime delay usecs
+ *
+ * Wait until 'usecs' microseconds has elapsed. This is a blocking delay.
+ *
+ * @param usecs The number of usecs to wait.
+ */
+void
+cputime_delay_usecs(uint32_t usecs)
+{
+    uint32_t ticks;
+
+    ticks = cputime_usecs_to_ticks(usecs);
+    cputime_delay_ticks(ticks);
+}
+
+/**
+ * cputime timer init
+ *
+ *
+ * @param timer The timer to initialize. Cannot be NULL.
+ * @param fp    The timer callback function. Cannot be NULL.
+ * @param arg   Pointer to data object to pass to timer.
+ */
+void
+cputime_timer_init(struct cpu_timer *timer, cputimer_func fp, void *arg)
+{
+    assert(timer != NULL);
+    assert(fp != NULL);
+
+    timer->cb = fp;
+    timer->arg = arg;
+    timer->link.tqe_prev = (void *) NULL;
+}
+
+/**
+ * cputime timer start
+ *
+ * Start a cputimer that will expire at 'cputime'. If cputime has already
+ * passed, the timer callback will still be called (at interrupt context).
+ * Cannot be called when the timer has already started.
+ *
+ * @param timer     Pointer to timer to start. Cannot be NULL.
+ * @param cputime   The cputime at which the timer should expire.
+ */
+void
+cputime_timer_start(struct cpu_timer *timer, uint32_t cputime)
+{
+    struct cpu_timer *entry;
+    os_sr_t sr;
+
+    assert(timer != NULL);
+    assert(timer->link.tqe_prev == NULL);
+
+    /* XXX: should this use a mutex? not sure... */
+    OS_ENTER_CRITICAL(sr);
+
+    timer->cputime = cputime;
+    if (TAILQ_EMPTY(&g_cputimer_q)) {
+        TAILQ_INSERT_HEAD(&g_cputimer_q, timer, link);
+    } else {
+        TAILQ_FOREACH(entry, &g_cputimer_q, link) {
+            if ((int32_t)(timer->cputime - entry->cputime) < 0) {
+                TAILQ_INSERT_BEFORE(entry, timer, link);
+                break;
+            }
+        }
+        if (!entry) {
+            TAILQ_INSERT_TAIL(&g_cputimer_q, timer, link);
+        }
+    }
+
+    /* If this is the head, we need to set new OCMP */
+    if (timer == TAILQ_FIRST(&g_cputimer_q)) {
+        cputime_set_ocmp(timer);
+    }
+
+    OS_EXIT_CRITICAL(sr);
+}
+
+/**
+ * cputimer timer relative
+ *
+ * Sets a cpu timer that will expire 'usecs' microseconds from the current
+ * cputime.
+ *
+ * @param timer Pointer to timer. Cannot be NULL.
+ * @param usecs The number of usecs from now at which the timer will expire.
+ */
+void
+cputime_timer_relative(struct cpu_timer *timer, uint32_t usecs)
+{
+    uint32_t cputime;
+
+    assert(timer != NULL);
+
+    cputime = cputime_get32() + cputime_usecs_to_ticks(usecs);
+    cputime_timer_start(timer, cputime);
+}
+
+/**
+ * cputime timer stop
+ *
+ * Stops a cputimer from running. The timer is removed from the timer queue
+ * and interrupts are disabled if no timers are left on the queue. Can be
+ * called even if timer is not running.
+ *
+ * @param timer Pointer to cputimer to stop. Cannot be NULL.
+ */
+void
+cputime_timer_stop(struct cpu_timer *timer)
+{
+    os_sr_t sr;
+    int reset_ocmp;
+    struct cpu_timer *entry;
+
+    assert(timer != NULL);
+
+    OS_ENTER_CRITICAL(sr);
+
+    if (timer->link.tqe_prev != NULL) {
+        reset_ocmp = 0;
+        if (timer == TAILQ_FIRST(&g_cputimer_q)) {
+            /* If first on queue, we will need to reset OCMP */
+            entry = TAILQ_NEXT(timer, link);
+            reset_ocmp = 1;
+        }
+        TAILQ_REMOVE(&g_cputimer_q, timer, link);
+        timer->link.tqe_prev = NULL;
+        if (reset_ocmp) {
+            if (entry) {
+                cputime_set_ocmp(entry);
+            } else {
+                cputime_disable_ocmp();
+            }
+        }
+    }
+
+    OS_EXIT_CRITICAL(sr);
+}
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/712374ac/hw/mcu/native/src/hal_cputime.c
----------------------------------------------------------------------
diff --git a/hw/mcu/native/src/hal_cputime.c b/hw/mcu/native/src/hal_cputime.c
index 850bfc5..e310415 100644
--- a/hw/mcu/native/src/hal_cputime.c
+++ b/hw/mcu/native/src/hal_cputime.c
@@ -32,6 +32,12 @@ static uint32_t g_native_cputime_cputicks_per_ostick;
 static uint64_t g_native_cputime;
 static uint32_t g_native_cputime_last_ostime;
 
+void
+cputime_disable_ocmp(void)
+{
+    os_callout_stop(&g_native_cputimer.cf_c);
+}
+
 /**
  * Convert cpu time ticks to os ticks.
  *


[42/50] [abbrv] incubator-mynewt-core git commit: index of scratch area not initialized

Posted by cc...@apache.org.
index of scratch area not initialized

The index of the area used for scratch was uninitialized which incorrectly
caused the first area to be labelled as a scratch area. Yeah, and I have to
change my vim options to stop automatically adding tabs.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/5cc85484
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/5cc85484
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/5cc85484

Branch: refs/heads/master
Commit: 5cc854842791c9dd87fb44639796354ec86d9ec5
Parents: 7b269d5
Author: Peter Snyder <gi...@peterfs.com>
Authored: Sat Jul 2 11:42:03 2016 -0700
Committer: Peter Snyder <gi...@peterfs.com>
Committed: Sat Jul 2 11:42:03 2016 -0700

----------------------------------------------------------------------
 apps/ffs2native/src/main.c | 22 ++++++++++++----------
 1 file changed, 12 insertions(+), 10 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/5cc85484/apps/ffs2native/src/main.c
----------------------------------------------------------------------
diff --git a/apps/ffs2native/src/main.c b/apps/ffs2native/src/main.c
index edaaa31..570d5af 100644
--- a/apps/ffs2native/src/main.c
+++ b/apps/ffs2native/src/main.c
@@ -376,7 +376,7 @@ print_nffs_flash_V0inode(struct nffs_area_desc *area, uint32_t off)
 
     rc = file_flash_read(area->nad_offset + off, &ndi, sizeof(ndi));
     assert(rc == 0);
-	assert(nffs_hash_id_is_inode(ndi.ndi_id));
+    assert(nffs_hash_id_is_inode(ndi.ndi_id));
 
     memset(filename, 0, sizeof(filename));
     len = min(sizeof(filename) - 1, ndi.ndi_filename_len);
@@ -400,8 +400,8 @@ print_nffs_flash_V0block(struct nffs_area_desc *area, uint32_t off)
 
     rc = file_flash_read(area->nad_offset + off, &ndb, sizeof(ndb));
     assert(rc == 0);
-	assert(nffs_hash_id_is_block(ndb.ndb_id));
-	assert(!nffs_hash_id_is_inode(ndb.ndb_id));
+    assert(nffs_hash_id_is_block(ndb.ndb_id));
+    assert(!nffs_hash_id_is_inode(ndb.ndb_id));
 
     printf("   Block off %d id %x len %d seq %d prev %x ino %x\n",
            off, ndb.ndb_id, ndb.ndb_data_len, ndb.ndb_seq,
@@ -412,23 +412,23 @@ print_nffs_flash_V0block(struct nffs_area_desc *area, uint32_t off)
 static int
 print_nffs_flash_V0object(struct nffs_area_desc *area, uint32_t off)
 {
-	uint32_t magic;
+    uint32_t magic;
     int rc;
 
     rc = file_flash_read(area->nad_offset + off, &magic, sizeof magic);
     assert(rc == 0);
 
-	switch (magic) {
-	case NFFS_INODE_MAGIC:
+    switch (magic) {
+    case NFFS_INODE_MAGIC:
         return print_nffs_flash_V0inode(area, off);
 
-	case NFFS_BLOCK_MAGIC:
+    case NFFS_BLOCK_MAGIC:
         return print_nffs_flash_V0block(area, off);
 
-	case 0xffffffff:
+    case 0xffffffff:
         return area->nad_length;
 
-	default:
+    default:
         return 1;
     }
 }
@@ -591,7 +591,7 @@ main(int argc, char **argv)
     int cnt;
     struct stat st;
     int standalone = 0;
-
+            
     progname = argv[0];
 
     while ((ch = getopt(argc, argv, "c:d:f:sv")) != -1) {
@@ -636,6 +636,8 @@ main(int argc, char **argv)
     log_console_handler_init(&nffs_log_console_handler);
     log_register("nffs-log", &nffs_log, &nffs_log_console_handler);
 
+    file_scratch_idx = MAX_AREAS + 1;
+
     if (standalone) {
         fd = open(native_flash_file, O_RDWR);
         if ((rc = fstat(fd, &st)))


[27/50] [abbrv] incubator-mynewt-core git commit: hal; add a define limiting number of bytes in HW identifier.

Posted by cc...@apache.org.
hal; add a define limiting number of bytes in HW identifier.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/9f3d49f4
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/9f3d49f4
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/9f3d49f4

Branch: refs/heads/master
Commit: 9f3d49f433229c6653803c6a869e67334aab7014
Parents: 9490ca7
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Mon Jun 27 15:31:25 2016 -0700
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Jun 27 15:31:25 2016 -0700

----------------------------------------------------------------------
 hw/hal/include/hal/hal_bsp.h | 1 +
 1 file changed, 1 insertion(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/9f3d49f4/hw/hal/include/hal/hal_bsp.h
----------------------------------------------------------------------
diff --git a/hw/hal/include/hal/hal_bsp.h b/hw/hal/include/hal/hal_bsp.h
index ae96789..e2831eb 100644
--- a/hw/hal/include/hal/hal_bsp.h
+++ b/hw/hal/include/hal/hal_bsp.h
@@ -62,6 +62,7 @@ const struct bsp_mem_dump *bsp_core_dump(int *area_cnt);
  * Get unique HW identifier/serial number for platform.
  * Returns the number of bytes filled in.
  */
+#define BSP_MAX_ID_LEN  32
 int bsp_hw_id(uint8_t *id, int max_len);
 
 #ifdef __cplusplus


[22/50] [abbrv] incubator-mynewt-core git commit: config; allow CLI to display max size variable value.

Posted by cc...@apache.org.
config; allow CLI to display max size variable value.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/6b829a05
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/6b829a05
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/6b829a05

Branch: refs/heads/master
Commit: 6b829a0599587c9caacc082c037708e654715c1a
Parents: cd0793a
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Fri Jun 24 15:24:54 2016 -0700
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Fri Jun 24 15:24:54 2016 -0700

----------------------------------------------------------------------
 sys/config/src/config_cli.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6b829a05/sys/config/src/config_cli.c
----------------------------------------------------------------------
diff --git a/sys/config/src/config_cli.c b/sys/config/src/config_cli.c
index 50cfd23..7c39598 100644
--- a/sys/config/src/config_cli.c
+++ b/sys/config/src/config_cli.c
@@ -74,7 +74,7 @@ shell_conf_command(int argc, char **argv)
 {
     char *name = NULL;
     char *val = NULL;
-    char tmp_buf[16];
+    char tmp_buf[CONF_MAX_VAL_LEN + 1];
     int rc;
 
     switch (argc) {


[15/50] [abbrv] incubator-mynewt-core git commit: MYNEWT-273; implement bsp_hw_id() for nordic and STM32F4.

Posted by cc...@apache.org.
MYNEWT-273; implement bsp_hw_id() for nordic and STM32F4.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/7bd50b3b
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/7bd50b3b
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/7bd50b3b

Branch: refs/heads/master
Commit: 7bd50b3b24d09f3c8e0052d38a440a5013a67450
Parents: b633dfb
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Thu Jun 23 16:36:24 2016 -0700
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Thu Jun 23 16:37:53 2016 -0700

----------------------------------------------------------------------
 hw/mcu/nordic/nrf51xxx/src/nrf51_hw_id.c   | 48 +++++++++++++++++++++++++
 hw/mcu/nordic/nrf52xxx/src/nrf52_hw_id.c   | 48 +++++++++++++++++++++++++
 hw/mcu/stm/stm32f4xx/src/stm32f4xx_hw_id.c | 42 ++++++++++++++++++++++
 3 files changed, 138 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/7bd50b3b/hw/mcu/nordic/nrf51xxx/src/nrf51_hw_id.c
----------------------------------------------------------------------
diff --git a/hw/mcu/nordic/nrf51xxx/src/nrf51_hw_id.c b/hw/mcu/nordic/nrf51xxx/src/nrf51_hw_id.c
new file mode 100644
index 0000000..81279ac
--- /dev/null
+++ b/hw/mcu/nordic/nrf51xxx/src/nrf51_hw_id.c
@@ -0,0 +1,48 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+
+#include <inttypes.h>
+#include <string.h>
+
+#include <hal/hal_bsp.h>
+
+#include "mcu/nrf51.h"
+
+#ifndef min
+#define min(a, b) ((a)<(b)?(a):(b))
+#endif
+
+/*
+ * These values are generated at random.
+ * DEVICEID[0-1] and DEVICEADDR[0-1].
+ */
+int
+bsp_hw_id(uint8_t *id, int max_len)
+{
+    int len, cnt;
+
+    cnt = min(sizeof(NRF_FICR->DEVICEID), max_len);
+    memcpy(id, (void *)NRF_FICR->DEVICEID, cnt);
+    len = cnt;
+
+    cnt = min(sizeof(NRF_FICR->DEVICEADDR), max_len - len);
+    memcpy(id + len, (void *)NRF_FICR->DEVICEID, cnt);
+
+    return len + cnt;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/7bd50b3b/hw/mcu/nordic/nrf52xxx/src/nrf52_hw_id.c
----------------------------------------------------------------------
diff --git a/hw/mcu/nordic/nrf52xxx/src/nrf52_hw_id.c b/hw/mcu/nordic/nrf52xxx/src/nrf52_hw_id.c
new file mode 100644
index 0000000..9042153
--- /dev/null
+++ b/hw/mcu/nordic/nrf52xxx/src/nrf52_hw_id.c
@@ -0,0 +1,48 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+
+#include <inttypes.h>
+#include <string.h>
+
+#include <hal/hal_bsp.h>
+
+#include "mcu/nrf52.h"
+
+#ifndef min
+#define min(a, b) ((a)<(b)?(a):(b))
+#endif
+
+/*
+ * These values are generated at random.
+ * DEVICEID[0-1] and DEVICEADDR[0-1].
+ */
+int
+bsp_hw_id(uint8_t *id, int max_len)
+{
+    int len, cnt;
+
+    cnt = min(sizeof(NRF_FICR->DEVICEID), max_len);
+    memcpy(id, (void *)NRF_FICR->DEVICEID, cnt);
+    len = cnt;
+
+    cnt = min(sizeof(NRF_FICR->DEVICEADDR), max_len - len);
+    memcpy(id + len, (void *)NRF_FICR->DEVICEID, cnt);
+
+    return len + cnt;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/7bd50b3b/hw/mcu/stm/stm32f4xx/src/stm32f4xx_hw_id.c
----------------------------------------------------------------------
diff --git a/hw/mcu/stm/stm32f4xx/src/stm32f4xx_hw_id.c b/hw/mcu/stm/stm32f4xx/src/stm32f4xx_hw_id.c
new file mode 100644
index 0000000..c08e8fe
--- /dev/null
+++ b/hw/mcu/stm/stm32f4xx/src/stm32f4xx_hw_id.c
@@ -0,0 +1,42 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+
+#include <inttypes.h>
+#include <string.h>
+
+#include <hal/hal_bsp.h>
+
+#ifndef min
+#define min(a, b) ((a)<(b)?(a):(b))
+#endif
+
+/*
+ * STM32F4 has a unique 96-bit id at address 0x1FFF7A10.
+ * See ref manual chapter 39.1.
+ */
+int
+bsp_hw_id(uint8_t *id, int max_len)
+{
+    int cnt;
+
+    cnt = min(12, max_len);
+    memcpy(id, (void *)0x1FFF7A10, cnt);
+
+    return cnt;
+}


[21/50] [abbrv] incubator-mynewt-core git commit: native; add pseudo bsp_hw_id()

Posted by cc...@apache.org.
native; add pseudo bsp_hw_id()


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/cd0793ad
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/cd0793ad
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/cd0793ad

Branch: refs/heads/master
Commit: cd0793ada98c32aa47a6bd074675463f9b08f364
Parents: 5e9b6f3
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Fri Jun 24 13:04:41 2016 -0700
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Fri Jun 24 13:05:43 2016 -0700

----------------------------------------------------------------------
 hw/mcu/native/src/hal_hw_id.c | 38 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 38 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/cd0793ad/hw/mcu/native/src/hal_hw_id.c
----------------------------------------------------------------------
diff --git a/hw/mcu/native/src/hal_hw_id.c b/hw/mcu/native/src/hal_hw_id.c
new file mode 100644
index 0000000..d3795d5
--- /dev/null
+++ b/hw/mcu/native/src/hal_hw_id.c
@@ -0,0 +1,38 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+
+#include <inttypes.h>
+#include <string.h>
+
+#include "hal/hal_bsp.h"
+
+#ifndef min
+#define min(a, b) ((a)<(b)?(a):(b))
+#endif
+
+/*
+ * This can be used as the unique hardware identifier for the platform, as
+ * it's supposed to be unique for this particular MCU.
+ */
+int
+bsp_hw_id(uint8_t *id, int max_len)
+{
+    memset(id, 0x42, max_len);
+    return max_len;
+}


[31/50] [abbrv] incubator-mynewt-core git commit: This closes #67 Merge branch 'master' of https://github.com/Eichhoernchen/incubator-mynewt-core into develop

Posted by cc...@apache.org.
This closes #67
Merge branch 'master' of https://github.com/Eichhoernchen/incubator-mynewt-core into develop


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/821b21d9
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/821b21d9
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/821b21d9

Branch: refs/heads/master
Commit: 821b21d9fe89058d6630e5318b4572e97dfde779
Parents: 2f2db14 165f463
Author: William San Filippo <wi...@runtime.io>
Authored: Tue Jun 28 09:42:06 2016 -0700
Committer: William San Filippo <wi...@runtime.io>
Committed: Tue Jun 28 09:42:06 2016 -0700

----------------------------------------------------------------------
 hw/bsp/nrf51-blenano/boot-nrf51dk.ld            | 178 +++++++++++++
 hw/bsp/nrf51-blenano/cmsis-dap.cfg              |  12 +
 hw/bsp/nrf51-blenano/include/bsp/bsp.h          |  49 ++++
 hw/bsp/nrf51-blenano/include/bsp/bsp_sysid.h    |  36 +++
 hw/bsp/nrf51-blenano/include/bsp/cmsis_nvic.h   |  30 +++
 hw/bsp/nrf51-blenano/nrf51.cfg                  |  60 +++++
 hw/bsp/nrf51-blenano/nrf51dk.ld                 | 184 +++++++++++++
 hw/bsp/nrf51-blenano/nrf51dk_debug.sh           |  47 ++++
 hw/bsp/nrf51-blenano/nrf51dk_download.sh        | 107 ++++++++
 hw/bsp/nrf51-blenano/nrf51dk_no_boot.ld         | 179 +++++++++++++
 hw/bsp/nrf51-blenano/pkg.yml                    |  41 +++
 .../src/arch/cortex_m0/gcc_startup_nrf51.s      | 267 +++++++++++++++++++
 hw/bsp/nrf51-blenano/src/hal_bsp.c              |  46 ++++
 hw/bsp/nrf51-blenano/src/libc_stubs.c           |  85 ++++++
 hw/bsp/nrf51-blenano/src/os_bsp.c               |  78 ++++++
 hw/bsp/nrf51-blenano/src/sbrk.c                 |  53 ++++
 hw/bsp/nrf51-blenano/src/system_nrf51.c         | 121 +++++++++
 repository.yml                                  |  29 ++
 18 files changed, 1602 insertions(+)
----------------------------------------------------------------------



[20/50] [abbrv] incubator-mynewt-core git commit: Retrieve and display hw id in bletest

Posted by cc...@apache.org.
Retrieve and display hw id in bletest


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/5e9b6f3f
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/5e9b6f3f
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/5e9b6f3f

Branch: refs/heads/master
Commit: 5e9b6f3f24828dc908f13e563fb40fd0c97a5df4
Parents: e221e1e
Author: William San Filippo <wi...@runtime.io>
Authored: Fri Jun 24 09:18:44 2016 -0700
Committer: William San Filippo <wi...@runtime.io>
Committed: Fri Jun 24 09:18:44 2016 -0700

----------------------------------------------------------------------
 apps/bletest/src/main.c | 8 ++++++++
 1 file changed, 8 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/5e9b6f3f/apps/bletest/src/main.c
----------------------------------------------------------------------
diff --git a/apps/bletest/src/main.c b/apps/bletest/src/main.c
index 73b3cbf..fa32f89 100755
--- a/apps/bletest/src/main.c
+++ b/apps/bletest/src/main.c
@@ -21,6 +21,7 @@
 #include <string.h>
 #include "os/os.h"
 #include "bsp/bsp.h"
+#include "hal/hal_bsp.h"
 #include "hal/hal_gpio.h"
 #include "hal/hal_cputime.h"
 #include "hal/hal_flash.h"
@@ -164,6 +165,7 @@ uint16_t g_bletest_handle;
 uint16_t g_bletest_completed_pkts;
 uint16_t g_bletest_outstanding_pkts;
 uint16_t g_bletest_ltk_reply_handle;
+uint32_t g_bletest_hw_id[4];
 
 /* --- For LE encryption testing --- */
 /* Key: 0x4C68384139F574D836BCF34E9DFB01BF */
@@ -917,6 +919,12 @@ bletest_task_handler(void *arg)
     bletest_init_initiator();
 #endif
 
+    /* Read unique HW id */
+    rc = bsp_hw_id((void *)&g_bletest_hw_id[0], sizeof(g_bletest_hw_id));
+    assert(rc == 16);
+    console_printf("HW id=%04lx%04lx%04lx%04lx\n", g_bletest_hw_id[0],
+                   g_bletest_hw_id[1], g_bletest_hw_id[2], g_bletest_hw_id[3]);
+
     /* Set the event mask we want to display */
     event_mask = 0x7FF;
     rc = bletest_hci_le_set_event_mask(event_mask);


[50/50] [abbrv] incubator-mynewt-core git commit: MYNEWT-83: Controller should use a fixed buffer for reception

Posted by cc...@apache.org.
MYNEWT-83: Controller should use a fixed buffer for reception

In preparation for the rather large code change that will come
with this ticket, I am moving some things from the connection
receive end ISR processing into either the rx start is or the
Link Layer. The reason is that when we use a fixed buffer for
reception we will have to copy the receive buffer into a mbuf.
This will take extra time so we need to do everything we can do
to remove time from the rx end isr.

The changes are pretty simple: move the check for proper access
address into the rx start isr and we can do that there. We also
moved the anchor point processing into the receive start ISR as
we use the receive start time to calculate the anchor point.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/28e2a8b4
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/28e2a8b4
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/28e2a8b4

Branch: refs/heads/master
Commit: 28e2a8b4efcda9d241720f25749137de37ad71e8
Parents: e9f0c16
Author: William San Filippo <wi...@runtime.io>
Authored: Fri Jul 8 13:39:15 2016 -0700
Committer: William San Filippo <wi...@runtime.io>
Committed: Fri Jul 8 13:42:09 2016 -0700

----------------------------------------------------------------------
 net/nimble/controller/src/ble_ll.c           | 10 ++---
 net/nimble/controller/src/ble_ll_conn.c      | 49 ++++++++++++++---------
 net/nimble/controller/src/ble_ll_conn_priv.h |  4 +-
 3 files changed, 35 insertions(+), 28 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/28e2a8b4/net/nimble/controller/src/ble_ll.c
----------------------------------------------------------------------
diff --git a/net/nimble/controller/src/ble_ll.c b/net/nimble/controller/src/ble_ll.c
index f1b5f6c..3a09e3e 100644
--- a/net/nimble/controller/src/ble_ll.c
+++ b/net/nimble/controller/src/ble_ll.c
@@ -667,6 +667,7 @@ ble_ll_rx_start(struct os_mbuf *rxpdu, uint8_t chan)
     int rc;
     uint8_t pdu_type;
     uint8_t *rxbuf;
+    struct ble_mbuf_hdr *ble_hdr;
 
     ble_ll_log(BLE_LL_LOG_ID_RX_START, chan, 0, (uint32_t)rxpdu);
 
@@ -678,11 +679,8 @@ ble_ll_rx_start(struct os_mbuf *rxpdu, uint8_t chan)
          * ongoing connection
          */
         if (g_ble_ll_data.ll_state == BLE_LL_STATE_CONNECTION) {
-            /* Call conection pdu rx start function */
-            ble_ll_conn_rx_isr_start();
-
-            /* Set up to go from rx to tx */
-            rc = 1;
+            ble_hdr = BLE_MBUF_HDR_PTR(rxpdu);
+            rc = ble_ll_conn_rx_isr_start(ble_hdr, ble_phy_access_addr_get());
         } else {
             STATS_INC(ble_ll_stats, bad_ll_state);
             rc = 0;
@@ -778,7 +776,7 @@ ble_ll_rx_end(struct os_mbuf *rxpdu, struct ble_mbuf_hdr *ble_hdr)
          * Data channel pdu. We should be in CONNECTION state with an
          * ongoing connection.
          */
-        rc = ble_ll_conn_rx_isr_end(rxpdu, ble_phy_access_addr_get());
+        rc = ble_ll_conn_rx_isr_end(rxpdu);
         return rc;
     }
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/28e2a8b4/net/nimble/controller/src/ble_ll_conn.c
----------------------------------------------------------------------
diff --git a/net/nimble/controller/src/ble_ll_conn.c b/net/nimble/controller/src/ble_ll_conn.c
index 312c26f..ca94310 100644
--- a/net/nimble/controller/src/ble_ll_conn.c
+++ b/net/nimble/controller/src/ble_ll_conn.c
@@ -2410,9 +2410,11 @@ ble_ll_conn_spvn_timeout(void *arg)
  * been checked yet.
  *
  * Context: Interrupt
+ *
+ * @param rxhdr
  */
-void
-ble_ll_conn_rx_isr_start(void)
+int
+ble_ll_conn_rx_isr_start(struct ble_mbuf_hdr *rxhdr, uint32_t aa)
 {
     struct ble_ll_conn_sm *connsm;
 
@@ -2425,8 +2427,30 @@ ble_ll_conn_rx_isr_start(void)
     ble_ll_wfr_disable();
     connsm = g_ble_ll_conn_cur_sm;
     if (connsm) {
+        /* Double check access address. Better match connection state machine */
+        if (aa != connsm->access_addr) {
+            STATS_INC(ble_ll_conn_stats, rx_data_pdu_bad_aa);
+            ble_ll_state_set(BLE_LL_STATE_STANDBY);
+            ble_ll_event_send(&connsm->conn_ev_end);
+            g_ble_ll_conn_cur_sm = NULL;
+            return -1;
+        }
+
+        /* Set connection handle in mbuf header */
+        rxhdr->rxinfo.handle = connsm->conn_handle;
+
+        /* Set flag denoting we have received a packet in connection event */
         connsm->csmflags.cfbit.pkt_rxd = 1;
+
+        /* Set anchor point (and last) if 1st rxd frame in connection event */
+        if (connsm->csmflags.cfbit.slave_set_last_anchor) {
+            connsm->csmflags.cfbit.slave_set_last_anchor = 0;
+            connsm->last_anchor_point = rxhdr->beg_cputime;
+            connsm->anchor_point = connsm->last_anchor_point;
+        }
     }
+
+    return 1;
 }
 
 /**
@@ -2577,7 +2601,7 @@ conn_rx_data_pdu_end:
  *       > 0: Do not disable PHY as that has already been done.
  */
 int
-ble_ll_conn_rx_isr_end(struct os_mbuf *rxpdu, uint32_t aa)
+ble_ll_conn_rx_isr_end(struct os_mbuf *rxpdu)
 {
     int rc;
     int is_ctrl;
@@ -2607,15 +2631,8 @@ ble_ll_conn_rx_isr_end(struct os_mbuf *rxpdu, uint32_t aa)
         goto conn_exit;
     }
 
-    /* Double check access address. Better match connection state machine! */
-    if (aa != connsm->access_addr) {
-        STATS_INC(ble_ll_conn_stats, rx_data_pdu_bad_aa);
-        goto conn_exit;
-    }
-
     /* Set the handle in the ble mbuf header */
     rxhdr = BLE_MBUF_HDR_PTR(rxpdu);
-    rxhdr->rxinfo.handle = connsm->conn_handle;
     hdr_byte = rxpdu->om_data[0];
     rx_pyld_len = rxpdu->om_data[1];
 
@@ -2725,7 +2742,7 @@ ble_ll_conn_rx_isr_end(struct os_mbuf *rxpdu, uint32_t aa)
                         rc = ble_ll_ctrl_tx_done(txpdu, connsm);
                         if (rc) {
                             /* Means we transmitted a TERMINATE_IND */
-                            goto conn_rx_pdu_end;
+                            goto conn_exit;
                         } else {
                             goto chk_rx_terminate_ind;
                         }
@@ -2792,16 +2809,8 @@ chk_rx_terminate_ind:
         rc = ble_ll_conn_tx_data_pdu(connsm);
     }
 
-conn_rx_pdu_end:
-    /* Set anchor point (and last) if 1st received frame in connection event */
-    if (connsm->csmflags.cfbit.slave_set_last_anchor) {
-        connsm->csmflags.cfbit.slave_set_last_anchor = 0;
-        connsm->last_anchor_point = rxhdr->beg_cputime;
-        connsm->anchor_point = connsm->last_anchor_point;
-    }
-
-    /* Send link layer a connection end event if over */
 conn_exit:
+    /* Send link layer a connection end event if over */
     if (rc) {
         ble_ll_conn_current_sm_over();
         if (connsm) {

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/28e2a8b4/net/nimble/controller/src/ble_ll_conn_priv.h
----------------------------------------------------------------------
diff --git a/net/nimble/controller/src/ble_ll_conn_priv.h b/net/nimble/controller/src/ble_ll_conn_priv.h
index c94093e..218ecbc 100644
--- a/net/nimble/controller/src/ble_ll_conn_priv.h
+++ b/net/nimble/controller/src/ble_ll_conn_priv.h
@@ -106,8 +106,8 @@ void ble_ll_conn_module_reset(void);
 void ble_ll_conn_event_end(void *arg);
 void ble_ll_conn_tx_pkt_in(struct os_mbuf *om, uint16_t handle, uint16_t len);
 void ble_ll_conn_spvn_timeout(void *arg);
-void ble_ll_conn_rx_isr_start(void);
-int ble_ll_conn_rx_isr_end(struct os_mbuf *rxpdu, uint32_t aa);
+int ble_ll_conn_rx_isr_start(struct ble_mbuf_hdr *rxhdr, uint32_t aa);
+int ble_ll_conn_rx_isr_end(struct os_mbuf *rxpdu);
 void ble_ll_conn_rx_data_pdu(struct os_mbuf *rxpdu, struct ble_mbuf_hdr *hdr);
 void ble_ll_init_rx_pkt_in(uint8_t *rxbuf, struct ble_mbuf_hdr *ble_hdr);
 int ble_ll_init_rx_isr_end(struct os_mbuf *rxpdu, uint8_t crcok);


[47/50] [abbrv] incubator-mynewt-core git commit: MYNEWT-313: Low power modifications

Posted by cc...@apache.org.
MYNEWT-313: Low power modifications

There were a number of changes with this commit:
1) Porting the nrf51 code which uses an RTC timer for the OS timer tick to
the nrf52. The nrf52 used to use a higher power timer for its os tick.
2) Changing OS_TICKS_PER_SEC on the nrf51 and nrf52 to 128 (from 1000).
3) Modified blinky as it was doing a os_time_delay(1000) instead of os_time_delay(OS_TICKS_PER_SEC).


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/9b008aa8
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/9b008aa8
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/9b008aa8

Branch: refs/heads/master
Commit: 9b008aa849eea2f6dae5f44cc1d523add450b887
Parents: 127d425
Author: William San Filippo <wi...@runtime.io>
Authored: Tue Jul 5 14:59:42 2016 -0700
Committer: William San Filippo <wi...@runtime.io>
Committed: Tue Jul 5 15:02:17 2016 -0700

----------------------------------------------------------------------
 apps/blinky/src/main.c                         |   4 +-
 hw/bsp/bmd300eval/pkg.yml                      |   2 +-
 hw/bsp/nrf51dk/pkg.yml                         |   4 +-
 hw/bsp/nrf52dk/pkg.yml                         |   2 +-
 hw/mcu/nordic/nrf51xxx/include/mcu/cortex_m0.h |   4 +-
 hw/mcu/nordic/nrf52xxx/include/mcu/cortex_m4.h |   6 +-
 hw/mcu/nordic/nrf52xxx/src/hal_os_tick.c       | 179 ++++++++++++++++++--
 7 files changed, 174 insertions(+), 27 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/9b008aa8/apps/blinky/src/main.c
----------------------------------------------------------------------
diff --git a/apps/blinky/src/main.c b/apps/blinky/src/main.c
index 3d4ff9e..24d0311 100755
--- a/apps/blinky/src/main.c
+++ b/apps/blinky/src/main.c
@@ -6,7 +6,7 @@
  * to you 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,
@@ -89,7 +89,7 @@ task1_handler(void *arg)
         ++g_task1_loops;
 
         /* Wait one second */
-        os_time_delay(1000);
+        os_time_delay(OS_TICKS_PER_SEC);
 
         /* Toggle the LED */
         hal_gpio_toggle(g_led_pin);

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/9b008aa8/hw/bsp/bmd300eval/pkg.yml
----------------------------------------------------------------------
diff --git a/hw/bsp/bmd300eval/pkg.yml b/hw/bsp/bmd300eval/pkg.yml
index ccaf641..60d88ff 100644
--- a/hw/bsp/bmd300eval/pkg.yml
+++ b/hw/bsp/bmd300eval/pkg.yml
@@ -32,7 +32,7 @@ pkg.linkerscript: "bmd300eval.ld"
 pkg.linkerscript.bootloader.OVERWRITE: "boot-bmd300eval.ld"
 pkg.downloadscript: bmd300eval_download.sh
 pkg.debugscript: bmd300eval_debug.sh
-pkg.cflags: -DNRF52
+pkg.cflags: -DNRF52 -DBSP_HAS_32768_XTAL
 pkg.deps:
     - hw/mcu/nordic/nrf52xxx
     - libs/baselibc

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/9b008aa8/hw/bsp/nrf51dk/pkg.yml
----------------------------------------------------------------------
diff --git a/hw/bsp/nrf51dk/pkg.yml b/hw/bsp/nrf51dk/pkg.yml
index 60fb6e6..4a1a93b 100644
--- a/hw/bsp/nrf51dk/pkg.yml
+++ b/hw/bsp/nrf51dk/pkg.yml
@@ -6,7 +6,7 @@
 # to you 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,
@@ -32,7 +32,7 @@ pkg.linkerscript: "nrf51dk.ld"
 pkg.linkerscript.bootloader.OVERWRITE: "boot-nrf51dk.ld"
 pkg.downloadscript: nrf51dk_download.sh
 pkg.debugscript: nrf51dk_debug.sh
-pkg.cflags: -DNRF51
+pkg.cflags: -DNRF51 -DBSP_HAS_32768_XTAL
 pkg.deps:
     - hw/mcu/nordic/nrf51xxx
     - libs/baselibc

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/9b008aa8/hw/bsp/nrf52dk/pkg.yml
----------------------------------------------------------------------
diff --git a/hw/bsp/nrf52dk/pkg.yml b/hw/bsp/nrf52dk/pkg.yml
index 617cea7..d350e70 100644
--- a/hw/bsp/nrf52dk/pkg.yml
+++ b/hw/bsp/nrf52dk/pkg.yml
@@ -32,7 +32,7 @@ pkg.linkerscript: "nrf52dk.ld"
 pkg.linkerscript.bootloader.OVERWRITE: "boot-nrf52dk.ld"
 pkg.downloadscript: nrf52dk_download.sh
 pkg.debugscript: nrf52dk_debug.sh
-pkg.cflags: -DNRF52
+pkg.cflags: -DNRF52 -DBSP_HAS_32768_XTAL
 pkg.deps:
     - hw/mcu/nordic/nrf52xxx
     - libs/baselibc

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/9b008aa8/hw/mcu/nordic/nrf51xxx/include/mcu/cortex_m0.h
----------------------------------------------------------------------
diff --git a/hw/mcu/nordic/nrf51xxx/include/mcu/cortex_m0.h b/hw/mcu/nordic/nrf51xxx/include/mcu/cortex_m0.h
index b8c91a9..3ae4253 100644
--- a/hw/mcu/nordic/nrf51xxx/include/mcu/cortex_m0.h
+++ b/hw/mcu/nordic/nrf51xxx/include/mcu/cortex_m0.h
@@ -6,7 +6,7 @@
  * to you 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,
@@ -27,6 +27,6 @@
  * clocked at 32768Hz. The tick frequency is chosen such that it divides
  * cleanly into 32768 to avoid a systemic bias in the actual tick frequency.
  */
-#define OS_TICKS_PER_SEC    (1024)
+#define OS_TICKS_PER_SEC    (128)
 
 #endif /* __MCU_CORTEX_M0_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/9b008aa8/hw/mcu/nordic/nrf52xxx/include/mcu/cortex_m4.h
----------------------------------------------------------------------
diff --git a/hw/mcu/nordic/nrf52xxx/include/mcu/cortex_m4.h b/hw/mcu/nordic/nrf52xxx/include/mcu/cortex_m4.h
index d7661c7..bb1c14e 100644
--- a/hw/mcu/nordic/nrf52xxx/include/mcu/cortex_m4.h
+++ b/hw/mcu/nordic/nrf52xxx/include/mcu/cortex_m4.h
@@ -6,7 +6,7 @@
  * to you 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,
@@ -22,6 +22,10 @@
 
 #include "mcu/nrf52.h"
 
+#if defined(BSP_HAS_32768_XTAL)
+#define OS_TICKS_PER_SEC    (128)
+#else
 #define OS_TICKS_PER_SEC    (1000)
+#endif
 
 #endif /* __MCU_CORTEX_M4_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/9b008aa8/hw/mcu/nordic/nrf52xxx/src/hal_os_tick.c
----------------------------------------------------------------------
diff --git a/hw/mcu/nordic/nrf52xxx/src/hal_os_tick.c b/hw/mcu/nordic/nrf52xxx/src/hal_os_tick.c
index ba3f0b3..454d2a1 100644
--- a/hw/mcu/nordic/nrf52xxx/src/hal_os_tick.c
+++ b/hw/mcu/nordic/nrf52xxx/src/hal_os_tick.c
@@ -6,7 +6,7 @@
  * to you 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,
@@ -22,16 +22,58 @@
 #include <mcu/nrf52_bitfields.h>
 #include <bsp/cmsis_nvic.h>
 
+#if defined(BSP_HAS_32768_XTAL)
+#define RTC_FREQ            32768       /* in Hz */
+#define OS_TICK_TIMER       NRF_RTC1
+#define OS_TICK_IRQ         RTC1_IRQn
+#define OS_TICK_CMPREG      3   /* generate timer interrupt */
+#define OS_TICK_PRESCALER   1   /* prescaler to generate timer freq */
+#define TIMER_LT(__t1, __t2)    ((((__t1) - (__t2)) & 0xffffff) > 0x800000)
+#define RTC_COMPARE_INT_MASK(ccreg) (1UL << ((ccreg) + 16))
+#else
 #define OS_TICK_TIMER       NRF_TIMER1
 #define OS_TICK_IRQ         TIMER1_IRQn
 #define OS_TICK_CMPREG      0   /* generate timer interrupt */
 #define OS_TICK_COUNTER     1   /* capture current timer value */
 #define OS_TICK_PRESCALER   4   /* prescaler to generate 1MHz timer freq */
 #define TIMER_LT(__t1, __t2)    ((int32_t)((__t1) - (__t2)) < 0)
+#endif
+
+struct hal_os_tick
+{
+    int ticks_per_ostick;
+    os_time_t max_idle_ticks;
+    uint32_t lastocmp;
+};
+
+struct hal_os_tick g_hal_os_tick;
+
+/*
+ * Implement (x - y) where the range of both 'x' and 'y' is limited to 24-bits.
+ *
+ * For example:
+ *
+ * sub24(0, 0xffffff) = 1
+ * sub24(0xffffff, 0xfffffe) = 1
+ * sub24(0xffffff, 0) = -1
+ * sub24(0x7fffff, 0) = 8388607
+ * sub24(0x800000, 0) = -8388608
+ */
+static inline int
+sub24(uint32_t x, uint32_t y)
+{
+    int result;
+
+    assert(x <= 0xffffff);
+    assert(y <= 0xffffff);
 
-static int timer_ticks_per_ostick;
-static os_time_t nrf52_max_idle_ticks;
-static uint32_t lastocmp;
+    result = x - y;
+    if (result & 0x800000) {
+        return (result | 0xff800000);
+    } else {
+        return (result & 0x007fffff);
+    }
+}
 
 static inline uint32_t
 nrf52_os_tick_counter(void)
@@ -42,11 +84,15 @@ nrf52_os_tick_counter(void)
      */
     OS_ASSERT_CRITICAL();
 
+#if defined(BSP_HAS_32768_XTAL)
+    return OS_TICK_TIMER->COUNTER;
+#else
     /*
      * Capture the current timer value and return it.
      */
     OS_TICK_TIMER->TASKS_CAPTURE[OS_TICK_COUNTER] = 1;
     return (OS_TICK_TIMER->CC[OS_TICK_COUNTER]);
+#endif
 }
 
 static inline void
@@ -56,12 +102,33 @@ nrf52_os_tick_set_ocmp(uint32_t ocmp)
 
     OS_ASSERT_CRITICAL();
     while (1) {
+#if defined(BSP_HAS_32768_XTAL)
+        int delta;
+
+        ocmp &= 0xffffff;
+        OS_TICK_TIMER->CC[OS_TICK_CMPREG] = ocmp;
+        counter = nrf52_os_tick_counter();
+        /*
+         * From nRF52 Product specification
+         *
+         * - If Counter is 'N' writing (N) or (N + 1) to CC register
+         *   may not trigger a compare event.
+         *
+         * - If Counter is 'N' writing (N + 2) to CC register is guaranteed
+         *   to trigger a compare event at 'N + 2'.
+         */
+        delta = sub24(ocmp, counter);
+        if (delta > 2) {
+            break;
+        }
+#else
         OS_TICK_TIMER->CC[OS_TICK_CMPREG] = ocmp;
         counter = nrf52_os_tick_counter();
         if (TIMER_LT(counter, ocmp)) {
             break;
         }
-        ocmp += timer_ticks_per_ostick;
+#endif
+        ocmp += g_hal_os_tick.ticks_per_ostick;
     }
 }
 
@@ -74,21 +141,35 @@ nrf52_timer_handler(void)
 
     OS_ENTER_CRITICAL(sr);
 
-    /*
-     * Calculate elapsed ticks and advance OS time.
-     */
+    /* Calculate elapsed ticks and advance OS time. */
+#if defined(BSP_HAS_32768_XTAL)
+    int delta;
+
     counter = nrf52_os_tick_counter();
-    ticks = (counter - lastocmp) / timer_ticks_per_ostick;
+    delta = sub24(counter, g_hal_os_tick.lastocmp);
+    ticks = delta / g_hal_os_tick.ticks_per_ostick;
     os_time_advance(ticks);
 
     /* Clear timer interrupt */
     OS_TICK_TIMER->EVENTS_COMPARE[OS_TICK_CMPREG] = 0;
 
     /* Update the time associated with the most recent tick */
-    lastocmp += ticks * timer_ticks_per_ostick;
+    g_hal_os_tick.lastocmp = (g_hal_os_tick.lastocmp +
+        (ticks * g_hal_os_tick.ticks_per_ostick)) & 0xffffff;
+#else
+    counter = nrf52_os_tick_counter();
+    ticks = (counter - g_hal_os_tick.lastocmp) / g_hal_os_tick.ticks_per_ostick;
+    os_time_advance(ticks);
+
+    /* Clear timer interrupt */
+    OS_TICK_TIMER->EVENTS_COMPARE[OS_TICK_CMPREG] = 0;
+
+    /* Update the time associated with the most recent tick */
+    g_hal_os_tick.lastocmp += ticks * g_hal_os_tick.ticks_per_ostick;
+#endif
 
     /* Update the output compare to interrupt at the next tick */
-    nrf52_os_tick_set_ocmp(lastocmp + timer_ticks_per_ostick);
+    nrf52_os_tick_set_ocmp(g_hal_os_tick.lastocmp + g_hal_os_tick.ticks_per_ostick);
 
     OS_EXIT_CRITICAL(sr);
 }
@@ -104,10 +185,10 @@ os_tick_idle(os_time_t ticks)
         /*
          * Enter tickless regime during long idle durations.
          */
-        if (ticks > nrf52_max_idle_ticks) {
-            ticks = nrf52_max_idle_ticks;
+        if (ticks > g_hal_os_tick.max_idle_ticks) {
+            ticks = g_hal_os_tick.max_idle_ticks;
         }
-        ocmp = lastocmp + ticks * timer_ticks_per_ostick;
+        ocmp = g_hal_os_tick.lastocmp + (ticks*g_hal_os_tick.ticks_per_ostick);
         nrf52_os_tick_set_ocmp(ocmp);
     }
 
@@ -123,18 +204,79 @@ os_tick_idle(os_time_t ticks)
     }
 }
 
+#if defined(BSP_HAS_32768_XTAL)
+void
+os_tick_init(uint32_t os_ticks_per_sec, int prio)
+{
+    uint32_t sr;
+    uint32_t mask;
+
+    assert(RTC_FREQ % os_ticks_per_sec == 0);
+
+    g_hal_os_tick.lastocmp = 0;
+    g_hal_os_tick.ticks_per_ostick = RTC_FREQ / os_ticks_per_sec;
+
+    /*
+     * The maximum number of OS ticks allowed to elapse during idle is
+     * limited to 1/4th the number of timer ticks before the 24-bit counter
+     * rolls over.
+     */
+    g_hal_os_tick.max_idle_ticks = (1UL << 22) / g_hal_os_tick.ticks_per_ostick;
+
+    /* Turn on the LFCLK */
+    NRF_CLOCK->TASKS_LFCLKSTOP = 1;
+    NRF_CLOCK->EVENTS_LFCLKSTARTED = 0;
+    NRF_CLOCK->LFCLKSRC = CLOCK_LFCLKSRC_SRC_Xtal;
+    NRF_CLOCK->TASKS_LFCLKSTART = 1;
+
+    /* Wait here till started! */
+    mask = CLOCK_LFCLKSTAT_STATE_Msk | CLOCK_LFCLKSTAT_SRC_Xtal;
+    while (1) {
+        if (NRF_CLOCK->EVENTS_LFCLKSTARTED) {
+            if ((NRF_CLOCK->LFCLKSTAT & mask) == mask) {
+                break;
+            }
+        }
+    }
+
+    /* disable interrupts */
+    OS_ENTER_CRITICAL(sr);
+
+    /* Set isr in vector table and enable interrupt */
+    NVIC_SetPriority(OS_TICK_IRQ, prio);
+    NVIC_SetVector(OS_TICK_IRQ, (uint32_t)nrf52_timer_handler);
+    NVIC_EnableIRQ(OS_TICK_IRQ);
+
+    /*
+     * Program the OS_TICK_TIMER to operate at 32KHz and trigger an output
+     * compare interrupt at a rate of 'os_ticks_per_sec'.
+     */
+    OS_TICK_TIMER->TASKS_STOP = 1;
+    OS_TICK_TIMER->TASKS_CLEAR = 1;
+
+    OS_TICK_TIMER->EVTENCLR = 0xffffffff;
+    OS_TICK_TIMER->INTENCLR = 0xffffffff;
+    OS_TICK_TIMER->INTENSET = RTC_COMPARE_INT_MASK(OS_TICK_CMPREG);
+
+    OS_TICK_TIMER->EVENTS_COMPARE[OS_TICK_CMPREG] = 0;
+    OS_TICK_TIMER->CC[OS_TICK_CMPREG] = g_hal_os_tick.ticks_per_ostick;
+
+    OS_TICK_TIMER->TASKS_START = 1;
+
+    OS_EXIT_CRITICAL(sr);
+}
+#else
 void
 os_tick_init(uint32_t os_ticks_per_sec, int prio)
 {
-    lastocmp = 0;
-    timer_ticks_per_ostick = 1000000 / os_ticks_per_sec;
+    g_hal_os_tick.ticks_per_ostick = 1000000 / os_ticks_per_sec;
 
     /*
      * The maximum number of timer ticks allowed to elapse during idle is
      * limited to 1/4th the number of timer ticks before the 32-bit counter
      * rolls over.
      */
-    nrf52_max_idle_ticks = (1UL << 30) / timer_ticks_per_ostick;
+    g_hal_os_tick.max_idle_ticks = (1UL << 30) / g_hal_os_tick.ticks_per_ostick;
 
     /*
      * Program OS_TICK_TIMER to operate at 1MHz and trigger an output
@@ -146,7 +288,7 @@ os_tick_init(uint32_t os_ticks_per_sec, int prio)
     OS_TICK_TIMER->BITMODE = TIMER_BITMODE_BITMODE_32Bit;
     OS_TICK_TIMER->PRESCALER = OS_TICK_PRESCALER;
 
-    OS_TICK_TIMER->CC[OS_TICK_CMPREG] = timer_ticks_per_ostick;
+    OS_TICK_TIMER->CC[OS_TICK_CMPREG] = g_hal_os_tick.ticks_per_ostick;
     OS_TICK_TIMER->INTENSET = TIMER_COMPARE_INT_MASK(OS_TICK_CMPREG);
     OS_TICK_TIMER->EVENTS_COMPARE[OS_TICK_CMPREG] = 0;
 
@@ -156,3 +298,4 @@ os_tick_init(uint32_t os_ticks_per_sec, int prio)
 
     OS_TICK_TIMER->TASKS_START = 1;     /* start the os tick timer */
 }
+#endif


[10/50] [abbrv] incubator-mynewt-core git commit: BLE Host - Fix build error caused by prev commit.

Posted by cc...@apache.org.
BLE Host - Fix build error caused by prev commit.

The build errors were caused by:

commit a27e86ffffcaef04dce633901bbecf60c0033027
Author: Christopher Collins <cc...@apache.org>
Date:   Tue Jun 21 15:50:42 2016 -0700

    BLE Host - Clean up runtime settings.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/f664c509
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/f664c509
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/f664c509

Branch: refs/heads/master
Commit: f664c50911b68546e9b11e86f97ef8d0d917d76b
Parents: a27e86f
Author: Christopher Collins <cc...@apache.org>
Authored: Tue Jun 21 16:42:17 2016 -0700
Committer: Christopher Collins <cc...@apache.org>
Committed: Tue Jun 21 16:42:17 2016 -0700

----------------------------------------------------------------------
 net/nimble/host/src/ble_hs_cfg.c            | 4 ----
 net/nimble/host/src/test/ble_hs_test_util.c | 3 ---
 2 files changed, 7 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f664c509/net/nimble/host/src/ble_hs_cfg.c
----------------------------------------------------------------------
diff --git a/net/nimble/host/src/ble_hs_cfg.c b/net/nimble/host/src/ble_hs_cfg.c
index 05f9cfb..6fe0236 100644
--- a/net/nimble/host/src/ble_hs_cfg.c
+++ b/net/nimble/host/src/ble_hs_cfg.c
@@ -24,14 +24,10 @@ const struct ble_hs_cfg ble_hs_cfg_dflt = {
     .max_hci_bufs = 8,
 
     /** Connection settings. */
-    .max_outstanding_pkts_per_conn = 5,
-
 #if NIMBLE_OPT(CONNECT)
     .max_connections = NIMBLE_OPT(MAX_CONNECTIONS),
-    .max_conn_update_entries = 4,
 #else
     .max_connections = 0,
-    .max_conn_update_entries = 0,
 #endif
 
     /** GATT server settings. */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f664c509/net/nimble/host/src/test/ble_hs_test_util.c
----------------------------------------------------------------------
diff --git a/net/nimble/host/src/test/ble_hs_test_util.c b/net/nimble/host/src/test/ble_hs_test_util.c
index e2f28c7..90448da 100644
--- a/net/nimble/host/src/test/ble_hs_test_util.c
+++ b/net/nimble/host/src/test/ble_hs_test_util.c
@@ -848,9 +848,6 @@ ble_hs_test_util_init(void)
 
     ble_hci_set_phony_ack_cb(NULL);
 
-    /* Don't limit a connection's ability to transmit; simplify tests. */
-    ble_hs_cfg.max_outstanding_pkts_per_conn = 0;
-
     ble_hs_test_util_prev_hci_tx_clear();
 
     ble_hs_test_util_set_public_addr(g_dev_addr);


[07/50] [abbrv] incubator-mynewt-core git commit: BLE Host - Stop scan timer when disc. proc. cncld.

Posted by cc...@apache.org.
BLE Host - Stop scan timer when disc. proc. cncld.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/ac9f865d
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/ac9f865d
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/ac9f865d

Branch: refs/heads/master
Commit: ac9f865dafdebfafc2415c7c6ca09705b5c50bb4
Parents: eacea95
Author: Christopher Collins <cc...@apache.org>
Authored: Tue Jun 21 11:57:31 2016 -0700
Committer: Christopher Collins <cc...@apache.org>
Committed: Tue Jun 21 11:57:31 2016 -0700

----------------------------------------------------------------------
 net/nimble/host/src/ble_gap.c | 15 +++++++++++----
 1 file changed, 11 insertions(+), 4 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/ac9f865d/net/nimble/host/src/ble_gap.c
----------------------------------------------------------------------
diff --git a/net/nimble/host/src/ble_gap.c b/net/nimble/host/src/ble_gap.c
index 12a4994..50b1df6 100644
--- a/net/nimble/host/src/ble_gap.c
+++ b/net/nimble/host/src/ble_gap.c
@@ -418,13 +418,20 @@ ble_gap_adv_finished(int event)
 }
 
 static void
+ble_gap_master_reset_state(void)
+{
+    ble_gap_master.op = BLE_GAP_OP_NULL;
+    ble_gap_master.exp_set = 0;
+}
+
+static void
 ble_gap_master_extract_cb(ble_gap_event_fn **out_cb, void **out_cb_arg)
 {
     ble_hs_lock();
 
     *out_cb = ble_gap_master.conn.cb;
     *out_cb_arg = ble_gap_master.conn.cb_arg;
-    ble_gap_master.op = BLE_GAP_OP_NULL;
+    ble_gap_master_reset_state();
 
     ble_hs_unlock();
 }
@@ -505,7 +512,7 @@ ble_gap_call_master_disc_cb(int event, int status, struct ble_hs_adv *adv,
     cb_arg = ble_gap_master.disc.cb_arg;
 
     if (reset_state) {
-        ble_gap_master.op = BLE_GAP_OP_NULL;
+        ble_gap_master_reset_state();
     }
 
     ble_hs_unlock();
@@ -922,7 +929,7 @@ ble_gap_rx_conn_complete(struct hci_le_conn_complete *evt)
         conn->bhc_cb = ble_gap_master.conn.cb;
         conn->our_addr_type = ble_gap_master.conn.our_addr_type;
         conn->bhc_cb_arg = ble_gap_master.conn.cb_arg;
-        ble_gap_master.op = BLE_GAP_OP_NULL;
+        ble_gap_master_reset_state();
     } else {
         conn->bhc_cb = ble_gap_slave.cb;
         conn->bhc_cb_arg = ble_gap_slave.cb_arg;
@@ -1679,7 +1686,7 @@ ble_gap_disc_cancel(void)
         goto done;
     }
 
-    ble_gap_master.op = BLE_GAP_OP_NULL;
+    ble_gap_master_reset_state();
 
 done:
     if (rc != 0) {


[24/50] [abbrv] incubator-mynewt-core git commit: bletest; printf string was not working for some native targets..

Posted by cc...@apache.org.
bletest; printf string was not working for some native targets..


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/fd0a8993
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/fd0a8993
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/fd0a8993

Branch: refs/heads/master
Commit: fd0a8993b4b9557d0baf9bd2562a8e6ab1e40ebb
Parents: 7dbc0d0
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Fri Jun 24 17:32:03 2016 -0700
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Fri Jun 24 17:32:03 2016 -0700

----------------------------------------------------------------------
 apps/bletest/src/main.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/fd0a8993/apps/bletest/src/main.c
----------------------------------------------------------------------
diff --git a/apps/bletest/src/main.c b/apps/bletest/src/main.c
index fa32f89..e132f32 100755
--- a/apps/bletest/src/main.c
+++ b/apps/bletest/src/main.c
@@ -922,8 +922,11 @@ bletest_task_handler(void *arg)
     /* Read unique HW id */
     rc = bsp_hw_id((void *)&g_bletest_hw_id[0], sizeof(g_bletest_hw_id));
     assert(rc == 16);
-    console_printf("HW id=%04lx%04lx%04lx%04lx\n", g_bletest_hw_id[0],
-                   g_bletest_hw_id[1], g_bletest_hw_id[2], g_bletest_hw_id[3]);
+    console_printf("HW id=%04x%04x%04x%04x\n",
+                   (unsigned int)g_bletest_hw_id[0],
+                   (unsigned int)g_bletest_hw_id[1],
+                   (unsigned int)g_bletest_hw_id[2],
+                   (unsigned int)g_bletest_hw_id[3]);
 
     /* Set the event mask we want to display */
     event_mask = 0x7FF;


[28/50] [abbrv] incubator-mynewt-core git commit: sys/id; package which exports hw id, bsp name, app name and configurable serial number via config interface.

Posted by cc...@apache.org.
sys/id; package which exports hw id, bsp name, app name and
configurable serial number via config interface.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/0abba449
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/0abba449
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/0abba449

Branch: refs/heads/master
Commit: 0abba449b49e2021ea1d5f83723146f177bf6b1d
Parents: 9f3d49f
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Mon Jun 27 15:47:22 2016 -0700
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Jun 27 15:47:22 2016 -0700

----------------------------------------------------------------------
 sys/id/include/id/id.h |  33 +++++++++++++
 sys/id/pkg.yml         |  38 +++++++++++++++
 sys/id/src/id.c        | 115 ++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 186 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/0abba449/sys/id/include/id/id.h
----------------------------------------------------------------------
diff --git a/sys/id/include/id/id.h b/sys/id/include/id/id.h
new file mode 100644
index 0000000..228d324
--- /dev/null
+++ b/sys/id/include/id/id.h
@@ -0,0 +1,33 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+
+#ifndef __SYS_ID_H__
+#define __SYS_ID_H__
+
+/*
+ * Maximum configurable serial number.
+ */
+#define ID_SERIAL_MAX_LEN       64
+
+/*
+ * Initialize manufacturing info storage/reporting.
+ */
+int id_init(void);
+
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/0abba449/sys/id/pkg.yml
----------------------------------------------------------------------
diff --git a/sys/id/pkg.yml b/sys/id/pkg.yml
new file mode 100644
index 0000000..c76cf14
--- /dev/null
+++ b/sys/id/pkg.yml
@@ -0,0 +1,38 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+
+pkg.name: sys/id
+pkg.description: Library providing system ID services.
+pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+    - serial
+    - manufacturing
+    - identifier
+
+pkg.deps:
+    - hw/hal
+    - libs/os
+    - libs/util
+    - sys/config
+pkg.deps.SHELL:
+    - libs/shell
+pkg.req_apis.SHELL:
+    - console
+pkg.cflags.SHELL: -DSHELL_PRESENT

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/0abba449/sys/id/src/id.c
----------------------------------------------------------------------
diff --git a/sys/id/src/id.c b/sys/id/src/id.c
new file mode 100644
index 0000000..3d2acc3
--- /dev/null
+++ b/sys/id/src/id.c
@@ -0,0 +1,115 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+#include <inttypes.h>
+#include <string.h>
+#include <stdio.h>
+
+#include <hal/hal_bsp.h>
+#include <os/os.h>
+#include <config/config.h>
+#include <util/base64.h>
+
+#include "id/id.h"
+
+static char *id_conf_get(int argc, char **argv, char *val, int val_len_max);
+static int id_conf_set(int argc, char **argv, char *val);
+static int id_conf_export(void (*export_func)(char *name, char *val),
+  enum conf_export_tgt tgt);
+
+#define STAMP_STR(s) STAMP_STR1(s)
+#define STAMP_STR1(str) #str
+
+#ifdef BSP_NAME
+static const char *bsp_str = STAMP_STR(BSP_NAME);
+static const char *app_str = STAMP_STR(APP_NAME);
+#else
+static const char *bsp_str = "";
+static const char *app_str = "";
+#endif
+
+static char serial[ID_SERIAL_MAX_LEN];
+
+struct conf_handler id_conf = {
+    .ch_name = "id",
+    .ch_get = id_conf_get,
+    .ch_set = id_conf_set,
+    .ch_export = id_conf_export
+};
+
+static char *
+id_conf_get(int argc, char **argv, char *val, int val_len_max)
+{
+    uint8_t src_buf[BSP_MAX_ID_LEN];
+    int len;
+
+    if (argc == 1) {
+        if (!strcmp(argv[0], "hwid")) {
+            len = bsp_hw_id(src_buf, sizeof(src_buf));
+            if (len > 0) {
+                return conf_str_from_bytes(src_buf, len, val, val_len_max);
+            }
+        } else if (!strcmp(argv[0], "bsp")) {
+            return (char *)bsp_str;
+        } else if (!strcmp(argv[0], "app")) {
+            return (char *)app_str;
+        } else if (!strcmp(argv[0], "serial")) {
+            return serial;
+        }
+    }
+    return NULL;
+}
+
+static int
+id_conf_set(int argc, char **argv, char *val)
+{
+    if (argc == 1) {
+        if (!strcmp(argv[0], "serial")) {
+            return CONF_VALUE_SET(val, CONF_STRING, serial);
+        }
+    }
+    return OS_ENOENT;
+}
+
+static int
+id_conf_export(void (*export_func)(char *name, char *val),
+  enum conf_export_tgt tgt)
+{
+    uint8_t src_buf[BSP_MAX_ID_LEN];
+    char str[sizeof(src_buf) * 2];
+    int len;
+
+    if (tgt == CONF_EXPORT_SHOW) {
+        len = bsp_hw_id(src_buf, sizeof(src_buf));
+        if (len > 0) {
+            conf_str_from_bytes(src_buf, len, str, sizeof(str));
+        }
+        export_func("id/hwid", str);
+        export_func("id/bsp", (char *)bsp_str);
+        export_func("id/app", (char *)app_str);
+    }
+    export_func("id/serial", serial);
+
+    return 0;
+}
+
+int
+id_init(void)
+{
+    return conf_register(&id_conf);
+}


[29/50] [abbrv] incubator-mynewt-core git commit: slinky; include sys/id in the sample app.

Posted by cc...@apache.org.
slinky; include sys/id in the sample app.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/2f2db14b
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/2f2db14b
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/2f2db14b

Branch: refs/heads/master
Commit: 2f2db14be16633c3b0b0da787e9ee21a24e15fdc
Parents: 0abba44
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Mon Jun 27 15:48:22 2016 -0700
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Jun 27 15:48:22 2016 -0700

----------------------------------------------------------------------
 apps/slinky/pkg.yml    | 1 +
 apps/slinky/src/main.c | 3 +++
 2 files changed, 4 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/2f2db14b/apps/slinky/pkg.yml
----------------------------------------------------------------------
diff --git a/apps/slinky/pkg.yml b/apps/slinky/pkg.yml
index add0c27..3219caa 100644
--- a/apps/slinky/pkg.yml
+++ b/apps/slinky/pkg.yml
@@ -34,6 +34,7 @@ pkg.deps:
     - libs/shell
     - libs/util
     - sys/config
+    - sys/id
     - sys/log
     - sys/stats
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/2f2db14b/apps/slinky/src/main.c
----------------------------------------------------------------------
diff --git a/apps/slinky/src/main.c b/apps/slinky/src/main.c
index 59c569d..00eec39 100755
--- a/apps/slinky/src/main.c
+++ b/apps/slinky/src/main.c
@@ -47,6 +47,7 @@
 #include <flash_test/flash_test.h>
 #include <reboot/log_reboot.h>
 #include <os/os_time.h>
+#include <id/id.h>
 
 #ifdef ARCH_sim
 #include <mcu/mcu_sim.h>
@@ -374,6 +375,8 @@ main(int argc, char **argv)
     setup_for_fcb();
 #endif
 
+    id_init();
+
     shell_task_init(SHELL_TASK_PRIO, shell_stack, SHELL_TASK_STACK_SIZE,
                     SHELL_MAX_INPUT_LEN);
 


[08/50] [abbrv] incubator-mynewt-core git commit: BLE Host - Single buffer for HCI cmds and acks.

Posted by cc...@apache.org.
BLE Host - Single buffer for HCI cmds and acks.

This fixes the problem where the host is starved of HCI buffers when the
controller sends a flurry of unsolicited events.  Rather than allocating
a buffer from a shared pool, the host uses a single static buffer for
all of its commands.  This solution works for the following two reasons:

1. The host never sends a second command before the previous one is
   acknowledged by the controller.
2. The controller reuses the command buffer when it sends back an
   acknowledgement event (command complete or command status).


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/9b56c3c1
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/9b56c3c1
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/9b56c3c1

Branch: refs/heads/master
Commit: 9b56c3c1038468141b0c7830fba1738572a0bcb8
Parents: ac9f865
Author: Christopher Collins <cc...@apache.org>
Authored: Tue Jun 21 14:18:10 2016 -0700
Committer: Christopher Collins <cc...@apache.org>
Committed: Tue Jun 21 14:18:10 2016 -0700

----------------------------------------------------------------------
 net/nimble/host/include/host/host_hci.h |  4 +++
 net/nimble/host/src/ble_hci_cmd.c       | 49 ++++++++++++----------------
 net/nimble/host/src/ble_hs.c            |  1 -
 net/nimble/host/src/host_hci_cmd.c      | 22 +++++--------
 4 files changed, 33 insertions(+), 43 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/9b56c3c1/net/nimble/host/include/host/host_hci.h
----------------------------------------------------------------------
diff --git a/net/nimble/host/include/host/host_hci.h b/net/nimble/host/include/host/host_hci.h
index 00cb7f5..c33cb39 100644
--- a/net/nimble/host/include/host/host_hci.h
+++ b/net/nimble/host/include/host/host_hci.h
@@ -24,6 +24,10 @@
 struct ble_hs_conn;
 struct os_mbuf;
 
+#define HCI_CMD_BUF_SIZE        260
+
+extern uint8_t host_hci_cmd_buf[HCI_CMD_BUF_SIZE];
+
 int host_hci_os_event_proc(struct os_event *ev);
 int host_hci_event_rx(uint8_t *data);
 uint16_t host_hci_opcode_join(uint8_t ogf, uint16_t ocf);

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/9b56c3c1/net/nimble/host/src/ble_hci_cmd.c
----------------------------------------------------------------------
diff --git a/net/nimble/host/src/ble_hci_cmd.c b/net/nimble/host/src/ble_hci_cmd.c
index 014ef0a..0e14f04 100644
--- a/net/nimble/host/src/ble_hci_cmd.c
+++ b/net/nimble/host/src/ble_hci_cmd.c
@@ -28,7 +28,6 @@
 
 static struct os_mutex ble_hci_cmd_mutex;
 static struct os_sem ble_hci_cmd_sem;
-static uint8_t *ble_hci_cmd_ack_ev;
 
 #if PHONY_HCI_ACKS
 static ble_hci_cmd_phony_ack_fn *ble_hci_cmd_phony_ack_cb;
@@ -62,7 +61,7 @@ ble_hci_cmd_unlock(void)
 
 static int
 ble_hci_cmd_rx_cmd_complete(uint8_t event_code, uint8_t *data, int len,
-                         struct ble_hci_ack *out_ack)
+                            struct ble_hci_ack *out_ack)
 {
     uint16_t opcode;
     uint8_t *params;
@@ -106,7 +105,7 @@ ble_hci_cmd_rx_cmd_complete(uint8_t event_code, uint8_t *data, int len,
 
 static int
 ble_hci_cmd_rx_cmd_status(uint8_t event_code, uint8_t *data, int len,
-                       struct ble_hci_ack *out_ack)
+                          struct ble_hci_ack *out_ack)
 {
     uint16_t opcode;
     uint8_t num_pkts;
@@ -141,16 +140,20 @@ ble_hci_cmd_process_ack(uint8_t *params_buf, uint8_t params_buf_len,
     uint8_t event_len;
     int rc;
 
-    BLE_HS_DBG_ASSERT(ble_hci_cmd_ack_ev != NULL);
+    /***
+     * The controller always reuses the command buffer for its acknowledgement
+     * events.  This function processes the acknowledgement event contained in
+     * the command buffer.
+     */
 
     /* Count events received */
     STATS_INC(ble_hs_stats, hci_event);
 
     /* Display to console */
-    host_hci_dbg_event_disp(ble_hci_cmd_ack_ev);
+    host_hci_dbg_event_disp(host_hci_cmd_buf);
 
-    event_code = ble_hci_cmd_ack_ev[0];
-    param_len = ble_hci_cmd_ack_ev[1];
+    event_code = host_hci_cmd_buf[0];
+    param_len = host_hci_cmd_buf[1];
     event_len = param_len + 2;
 
     /* Clear ack fields up front to silence spurious gcc warnings. */
@@ -158,12 +161,12 @@ ble_hci_cmd_process_ack(uint8_t *params_buf, uint8_t params_buf_len,
 
     switch (event_code) {
     case BLE_HCI_EVCODE_COMMAND_COMPLETE:
-        rc = ble_hci_cmd_rx_cmd_complete(event_code, ble_hci_cmd_ack_ev,
+        rc = ble_hci_cmd_rx_cmd_complete(event_code, host_hci_cmd_buf,
                                          event_len, out_ack);
         break;
 
     case BLE_HCI_EVCODE_COMMAND_STATUS:
-        rc = ble_hci_cmd_rx_cmd_status(event_code, ble_hci_cmd_ack_ev,
+        rc = ble_hci_cmd_rx_cmd_status(event_code, host_hci_cmd_buf,
                                        event_len, out_ack);
         break;
 
@@ -186,9 +189,6 @@ ble_hci_cmd_process_ack(uint8_t *params_buf, uint8_t params_buf_len,
         out_ack->bha_params = params_buf;
     }
 
-    os_memblock_put(&g_hci_cmd_pool, ble_hci_cmd_ack_ev);
-    ble_hci_cmd_ack_ev = NULL;
-
     return rc;
 }
 
@@ -201,13 +201,7 @@ ble_hci_cmd_wait_for_ack(void)
     if (ble_hci_cmd_phony_ack_cb == NULL) {
         rc = BLE_HS_ETIMEOUT_HCI;
     } else {
-        BLE_HS_DBG_ASSERT(ble_hci_cmd_ack_ev == NULL);
-        ble_hci_cmd_ack_ev = os_memblock_get(&g_hci_cmd_pool);
-        if (ble_hci_cmd_ack_ev == NULL) {
-            rc = BLE_HS_ENOMEM_HCI;
-        } else {
-            rc = ble_hci_cmd_phony_ack_cb(ble_hci_cmd_ack_ev, 260);
-        }
+        rc = ble_hci_cmd_phony_ack_cb(host_hci_cmd_buf, 260);
     }
 #else
     rc = os_sem_pend(&ble_hci_cmd_sem, BLE_HCI_CMD_TIMEOUT);
@@ -277,16 +271,17 @@ ble_hci_cmd_tx_empty_ack(void *cmd)
 void
 ble_hci_cmd_rx_ack(uint8_t *ack_ev)
 {
-    int rc;
+    /* The controller should always reuse the command buffer for its acks. */
+    BLE_HS_DBG_ASSERT(ack_ev == host_hci_cmd_buf);
 
-    if (ble_hci_cmd_ack_ev != NULL) {
-        /* The controller sent two acks.  Free the first one. */
-        rc = os_memblock_put(&g_hci_cmd_pool, ble_hci_cmd_ack_ev);
-        BLE_HS_DBG_ASSERT_EVAL(rc == 0);
+    if (ble_hci_cmd_sem.sem_tokens != 0) {
+        /* This ack is unexpected; ignore it. */
+        return;
     }
 
-    /* Hand up the acknowledgement and unblock the application. */
-    ble_hci_cmd_ack_ev = ack_ev;
+    /* Unblock the application now that the HCI command buffer is populated
+     * with the acknowledgement.
+     */
     os_sem_release(&ble_hci_cmd_sem);
 }
 
@@ -300,6 +295,4 @@ ble_hci_cmd_init(void)
 
     rc = os_mutex_init(&ble_hci_cmd_mutex);
     BLE_HS_DBG_ASSERT_EVAL(rc == 0);
-
-    ble_hci_cmd_ack_ev = NULL;
 }

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/9b56c3c1/net/nimble/host/src/ble_hs.c
----------------------------------------------------------------------
diff --git a/net/nimble/host/src/ble_hs.c b/net/nimble/host/src/ble_hs.c
index 72e6ccf..bd09217 100644
--- a/net/nimble/host/src/ble_hs.c
+++ b/net/nimble/host/src/ble_hs.c
@@ -39,7 +39,6 @@
 static struct log_handler ble_hs_log_console_handler;
 struct log ble_hs_log;
 
-#define HCI_CMD_BUF_SIZE    (260)       /* XXX: temporary, Fix later */
 struct os_mempool g_hci_cmd_pool;
 static void *ble_hs_hci_cmd_buf;
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/9b56c3c1/net/nimble/host/src/host_hci_cmd.c
----------------------------------------------------------------------
diff --git a/net/nimble/host/src/host_hci_cmd.c b/net/nimble/host/src/host_hci_cmd.c
index 281b270..baebed3 100644
--- a/net/nimble/host/src/host_hci_cmd.c
+++ b/net/nimble/host/src/host_hci_cmd.c
@@ -32,6 +32,8 @@
 #include "host/ble_hs_test.h"
 #endif
 
+uint8_t host_hci_cmd_buf[HCI_CMD_BUF_SIZE];
+
 static int
 host_hci_cmd_transport(uint8_t *cmdbuf)
 {
@@ -72,25 +74,17 @@ int
 host_hci_cmd_send(uint8_t ogf, uint8_t ocf, uint8_t len, void *cmddata)
 {
     int rc;
-    uint8_t *cmd;
-    uint16_t opcode;
 
-    cmd = os_memblock_get(&g_hci_cmd_pool);
-    if (cmd == NULL) {
-        /* XXX: Increment stat. */
-        return BLE_HS_ENOMEM_HCI;
+    htole16(host_hci_cmd_buf, ogf << 10 | ocf);
+    host_hci_cmd_buf[2] = len;
+    if (len != 0) {
+        memcpy(host_hci_cmd_buf + BLE_HCI_CMD_HDR_LEN, cmddata, len);
     }
 
-    opcode = (ogf << 10) | ocf;
-    htole16(cmd, opcode);
-    cmd[2] = len;
-    if (len) {
-        memcpy(cmd + BLE_HCI_CMD_HDR_LEN, cmddata, len);
-    }
-    rc = host_hci_cmd_transport(cmd);
+    rc = host_hci_cmd_transport(host_hci_cmd_buf);
     BLE_HS_LOG(DEBUG, "host_hci_cmd_send: ogf=0x%02x ocf=0x%02x len=%d "
                       "rc=%d\n", ogf, ocf, len, rc);
-    ble_hs_misc_log_flat_buf(cmd, len + BLE_HCI_CMD_HDR_LEN);
+    ble_hs_misc_log_flat_buf(host_hci_cmd_buf, len + BLE_HCI_CMD_HDR_LEN);
     BLE_HS_LOG(DEBUG, "\n");
 
     if (rc == 0) {


[34/50] [abbrv] incubator-mynewt-core git commit: Implement file lastblock caching in flash

Posted by cc...@apache.org.
Implement file lastblock caching in flash

This change stores the last written block for each file in the metadata
stored in flash. It facilitates restoring and mounting the filesystem
during initialization by removing the requirement to search every block in
flash to find the last block of each file.

This change requires the previous commit changing the on-flash data structures
which include a reference to the lastblock. This change is not backwards
compatible with previous on-flash version of NFFS, and there is a check
to make sure that the current version is used. Users upgrading to this version
of NFFS will need to reformat their flash devices - currently there is no
facility for in-place upgrades of existing filesystems.

One side-effect of this change is that inode updates are written to flash
each time a new block is added to the file. Other changes include additional
state flags with checking to provide additional resilience with minimal
space and compute overhead. There is also additional debugging tools in
nffs_test.c.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/f9ef5686
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/f9ef5686
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/f9ef5686

Branch: refs/heads/master
Commit: f9ef5686269fb626a042bbd2195e4db7d500ddf5
Parents: 76e33d9
Author: Peter Snyder <gi...@peterfs.com>
Authored: Tue Jun 28 16:15:03 2016 -0700
Committer: Peter Snyder <gi...@peterfs.com>
Committed: Tue Jun 28 16:15:03 2016 -0700

----------------------------------------------------------------------
 apps/ffs2native/src/main.c            | 232 +++++++++--
 fs/nffs/src/nffs.c                    |   1 +
 fs/nffs/src/nffs_block.c              |  40 ++
 fs/nffs/src/nffs_dir.c                |   4 +-
 fs/nffs/src/nffs_file.c               |   7 +-
 fs/nffs/src/nffs_format.c             |   2 +
 fs/nffs/src/nffs_gc.c                 |   4 +-
 fs/nffs/src/nffs_hash.c               |  68 +++-
 fs/nffs/src/nffs_inode.c              | 216 +++++++++-
 fs/nffs/src/nffs_misc.c               |   5 +-
 fs/nffs/src/nffs_path.c               |  13 +
 fs/nffs/src/nffs_priv.h               |  70 ++--
 fs/nffs/src/nffs_restore.c            | 598 +++++++++++++++++++---------
 fs/nffs/src/nffs_write.c              |  12 +
 fs/nffs/src/test/arch/sim/nffs_test.c | 611 ++++++++++++++++++++++++++++-
 15 files changed, 1595 insertions(+), 288 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f9ef5686/apps/ffs2native/src/main.c
----------------------------------------------------------------------
diff --git a/apps/ffs2native/src/main.c b/apps/ffs2native/src/main.c
index 1796ca2..2b42159 100644
--- a/apps/ffs2native/src/main.c
+++ b/apps/ffs2native/src/main.c
@@ -17,11 +17,6 @@
  * under the License.
  */
 
-/**
- * XXX
- * This is a hack of a tool which prints the structure of an nffs file system.
- * It needs to be rewritten properly.
- */
 
 #include <assert.h>
 #include <stdio.h>
@@ -49,12 +44,43 @@ static struct log_handler nffs_log_console_handler;
 struct log nffs_log;
 static const char *copy_in_dir;
 static const char *progname;
+static int print_verbose;
 
 char *file_flash_area;
+size_t file_flash_size;
 int file_scratch_idx;
 
 #define MAX_AREAS	16
 static struct nffs_area_desc area_descs[MAX_AREAS];
+int nffs_version;
+
+/** On-disk representation of a version 0 inode (file or directory). */
+struct nffs_disk_inodeV0 {
+    uint32_t ndi_magic;         /* NFFS_INODE_MAGIC */
+    uint32_t ndi_id;            /* Unique object ID. */
+    uint32_t ndi_seq;           /* Sequence number; greater supersedes
+                                   lesser. */
+    uint32_t ndi_parent_id;     /* Object ID of parent directory inode. */
+    uint8_t reserved8;
+    uint8_t ndi_filename_len;   /* Length of filename, in bytes. */
+    uint16_t ndi_crc16;         /* Covers rest of header and filename. */
+    /* Followed by filename. */
+};
+#define NFFS_DISK_INODEV0_OFFSET_CRC  18
+
+/** On-disk representation of a version 0 data block. */
+struct nffs_disk_blockV0 {
+    uint32_t ndb_magic;     /* NFFS_BLOCK_MAGIC */
+    uint32_t ndb_id;        /* Unique object ID. */
+    uint32_t ndb_seq;       /* Sequence number; greater supersedes lesser. */
+    uint32_t ndb_inode_id;  /* Object ID of owning inode. */
+    uint32_t ndb_prev_id;   /* Object ID of previous block in file;
+                               NFFS_ID_NONE if this is the first block. */
+    uint16_t ndb_data_len;  /* Length of data contents, in bytes. */
+    uint16_t ndb_crc16;     /* Covers rest of header and data. */
+    /* Followed by 'ndb_data_len' bytes of data. */
+};
+#define NFFS_DISK_BLOCKV0_OFFSET_CRC  22
 
 static void usage(int rc);
 
@@ -125,6 +151,7 @@ process_inode_entry(struct nffs_inode_entry *inode_entry, int indent)
     }
 }
 
+#ifdef OBSOLETE /* XXX To be removed */
 static int
 print_nffs_inode(struct nffs_disk_inode *ndi, int idx, uint32_t off)
 {
@@ -186,7 +213,6 @@ print_nffs_darea(struct nffs_disk_area *darea)
 		   darea->nda_gc_seq, darea->nda_id);
 }
 
-
 static void
 print_nffs_area(int idx)
 {
@@ -235,16 +261,8 @@ print_nffs_areas(void)
           area->na_offset, area->na_offset + area->na_length);
         print_nffs_area(i);
     }
-}
-
-static void
-printfs(void)
-{
-    printf("\n\nNFFS contents:\n");
-    process_inode_entry(nffs_root_dir, 0);
-    printf("\nNFFS areas:\n");
-    print_nffs_areas();
-}
+} 
+#endif /* OBSOLETE */
 
 static int
 copy_in_file(char *src, char *dst)
@@ -329,10 +347,11 @@ file_flash_read(uint32_t addr, void *dst, int byte_cnt)
 	return 0;
 }
 
+#ifdef NOTYET
 static int
-print_flash_inode(struct nffs_area_desc *area, uint32_t off)
+print_nffsV0_flash_inode(struct nffs_disk_object *ndo, uint32_t off)
 {
-    struct nffs_disk_inode ndi;
+    struct nffs_disk_inode *ndi = &ndo->ndo_disk_inode;
     char filename[128];
     int len;
     int rc;
@@ -350,40 +369,104 @@ print_flash_inode(struct nffs_area_desc *area, uint32_t off)
 			(nffs_hash_id_is_dir(ndi.ndi_id) ? "Dir" : "???")),
 		   ndi.ndi_id, ndi.ndi_seq, ndi.ndi_parent_id,
 		   ndi.ndi_lastblock_id, filename);
+    return sizeof(struct nffs_disk_inode) + ndi->ndi_filename_len;
+}
+
+static int
+print_nffsV0_flash_block(struct nffs_disk_object *ndo, uint32_t off)
+{
+    struct nffs_disk_block *ndb = &ndo->ndo_disk_block;
+    int rc;
+
+    printf("  off %x len %d Block id %x seq %d prev %x own ino %x\n",
+		   off, ndb->ndb_data_len, ndb->ndb_id, ndb->ndb_seq,
+		   ndb->ndb_prev_id, ndb->ndb_inode_id);
+    return sizeof(struct nffs_disk_block) + ndb->ndb_data_len;
+}
+
+static int
+print_nffsV0_flash_object(struct nffs_area_desc *area, uint32_t off)
+{
+	struct nffs_disk_object ndo;
+    uint32_t magic;
+
+	file_flash_read(area->nad_offset + off, &ndo, sizeof(ndo));
+	if (nffs_hash_id_is_inode(ndo.ndo_disk_inode.ndi_id)) {
+        return print_nffsV0_flash_inode(&ndo, off);
+
+	} else if (nffs_hash_id_is_block(ndo.ndo_disk_block.ndb_id)) {
+        return print_nffsV0_flash_block(&ndo, off);
+
+	}
+	return sizeof(ndo);
+}
+#endif /* NOTYET */
+
+static int
+print_nffs_flash_inode(struct nffs_area_desc *area, uint32_t off)
+{
+    struct nffs_disk_inode ndi;
+    char filename[128];
+    int len;
+    int rc;
+
+    rc = file_flash_read(area->nad_offset + off, &ndi, sizeof(ndi));
+    assert(rc == 0);
+
+    memset(filename, 0, sizeof(filename));
+    len = min(sizeof(filename) - 1, ndi.ndi_filename_len);
+    rc = file_flash_read(area->nad_offset + off + sizeof(ndi), filename, len);
+
+    printf("  off %x %s id %x flen %d seq %d last %x prnt %x flgs %x %s\n",
+           off,
+           (nffs_hash_id_is_file(ndi.ndi_id) ? "File" :
+            (nffs_hash_id_is_dir(ndi.ndi_id) ? "Dir" : "???")),
+           ndi.ndi_id,
+           ndi.ndi_filename_len,
+           ndi.ndi_seq,
+           ndi.ndi_lastblock_id,
+           ndi.ndi_parent_id,
+           ndi.ndi_flags,
+           filename);
     return sizeof(ndi) + ndi.ndi_filename_len;
 }
 
 static int
-print_flash_block(struct nffs_area_desc *area, uint32_t off)
+print_nffs_flash_block(struct nffs_area_desc *area, uint32_t off)
 {
     struct nffs_disk_block ndb;
     int rc;
 
-	rc = file_flash_read(area->nad_offset + off, &ndb, sizeof(ndb));
+    rc = file_flash_read(area->nad_offset + off, &ndb, sizeof(ndb));
     assert(rc == 0);
 
-    printf("  off %x len %d Block id %x seq %d prev %x own ino %x\n",
-		   off, ndb.ndb_data_len, ndb.ndb_id, ndb.ndb_seq,
-		   ndb.ndb_prev_id, ndb.ndb_inode_id);
+    printf("  off %x Block id %x len %d seq %d prev %x own ino %x\n",
+           off,
+           ndb.ndb_id,
+           ndb.ndb_data_len,
+           ndb.ndb_seq,
+           ndb.ndb_prev_id,
+           ndb.ndb_inode_id);
     return sizeof(ndb) + ndb.ndb_data_len;
 }
 
 static int
-print_flash_object(struct nffs_area_desc *area, uint32_t off)
+print_nffs_flash_object(struct nffs_area_desc *area, uint32_t off)
 {
-    uint32_t magic;
+    struct nffs_disk_object ndo;
 
-	file_flash_read(area->nad_offset + off, &magic, sizeof(magic));
-    switch (magic) {
-    case NFFS_INODE_MAGIC:
-        return print_flash_inode(area, off);
+	file_flash_read(area->nad_offset + off, &ndo, sizeof(ndo));
 
-    case NFFS_BLOCK_MAGIC:
-        return print_flash_block(area, off);
-        break;
+    if (nffs_hash_id_is_inode(ndo.ndo_disk_inode.ndi_id)) {
+        return print_nffs_flash_inode(area, off);
 
-    case 0xffffffff:
-    default:
+    } else if (nffs_hash_id_is_block(ndo.ndo_disk_block.ndb_id)) {
+        return print_nffs_flash_block(area, off);
+
+    } else if (ndo.ndo_disk_block.ndb_id == 0xffffffff) {
+        return area->nad_length;
+
+    } else {
         return 1;
     }
 }
@@ -403,11 +486,75 @@ print_file_areas()
 			   (i == file_scratch_idx ? "(scratch)" : ""));
 		off = sizeof (struct nffs_disk_area);
 		while (off < area->nad_length) {
-			off += print_flash_object(area, off);
+#ifdef NOTYET
+			if (nffs_version == 0) {
+				off += print_nffsV0_flash_object(area, off);
+			} else if (nffs_version == NFFS_AREA_VER) {
+				off += print_nffs_flash_object(area, off);
+			}
+#else
+			off += print_nffs_flash_object(area, off);
+#endif /* NOTYET */
 		}
     }
 }
 
+static void
+print_nffs_flash_areas(char *flash_area, size_t size)
+{
+	char *daptr;		/* Disk Area Pointer */
+	char *eoda;			/* End Of Disk Area */
+	struct nffs_disk_area *nda;
+	int nad_cnt = 0;	/* Nffs Area Descriptor count */
+	int off;
+
+	daptr = flash_area;
+	eoda = flash_area + size;
+	while (daptr < eoda) {
+		if (nffs_area_magic_is_set((struct nffs_disk_area*)daptr)) {
+			nda = (struct nffs_disk_area*)daptr;
+			area_descs[nad_cnt].nad_offset = (daptr - flash_area);
+			area_descs[nad_cnt].nad_length = nda->nda_length;
+			area_descs[nad_cnt].nad_flash_id = nda->nda_id;
+			nffs_version = nda->nda_ver;
+
+			if (nda->nda_id == 0xff)
+				file_scratch_idx = nad_cnt;
+
+			printf("area %d: id %d %x-%x len %d flshid %x gcseq %d %s\n",
+				   nad_cnt, nda->nda_id,
+				   area_descs[nad_cnt].nad_offset,
+				   area_descs[nad_cnt].nad_offset +
+				       area_descs[nad_cnt].nad_length,
+				   area_descs[nad_cnt].nad_length,
+				   area_descs[nad_cnt].nad_flash_id,
+				   nda->nda_gc_seq,
+				   nffs_scratch_area_idx == nad_cnt ? "(scratch)" : "");
+
+            off = sizeof (struct nffs_disk_area);
+            while (off < area_descs[nad_cnt].nad_length) {
+                off += print_nffs_flash_object(&area_descs[nad_cnt], off);
+            }
+
+			nad_cnt++;
+			daptr = daptr + nda->nda_length;
+		} else {
+			daptr++;
+		}
+	}
+	nffs_num_areas = nad_cnt;
+}
+
+static void
+printfs(void)
+{
+	printf("NFFS directory:\n");
+	process_inode_entry(nffs_root_dir, print_verbose);
+
+    printf("\nNFFS flash areas:\n");
+    print_nffs_flash_areas(file_flash_area, file_flash_size);
+}
+
 int
 file_area_init(char *flash_area, size_t size)
 {
@@ -424,6 +571,7 @@ file_area_init(char *flash_area, size_t size)
 			area_descs[nad_cnt].nad_offset = (daptr - flash_area);
 			area_descs[nad_cnt].nad_length = nda->nda_length;
 			area_descs[nad_cnt].nad_flash_id = nda->nda_id;
+			nffs_version = nda->nda_ver;
 			if (nda->nda_id == 0xff)
 				file_scratch_idx = nad_cnt;
 			printf("area %d: off %d len %d flshid %x gc-seq %d id %x ver %d %s\n",
@@ -433,7 +581,6 @@ file_area_init(char *flash_area, size_t size)
 				   area_descs[nad_cnt].nad_flash_id,
 				   nda->nda_gc_seq, nda->nda_id, nda->nda_ver,
 				   nda->nda_id == 0xff ? "(scratch)" : "");
-
 			nad_cnt++;
 			daptr = daptr + nda->nda_length;
 		} else {
@@ -447,9 +594,10 @@ file_area_init(char *flash_area, size_t size)
 static void
 usage(int rc)
 {
-    printf("%s [-c]|[-d dir][-s][-f flash_file]\n", progname);
+    printf("%s [-v][-c]|[-d dir][-s][-f flash_file]\n", progname);
     printf("  Tool for operating on simulator flash image file\n");
     printf("   -c: ...\n");
+    printf("   -v: verbose\n");
     printf("   -d: use dir as root for NFFS portion and create flash image\n");
     printf("   -f: flash_file is the name of the flash image file\n");
     printf("   -s: use flash area layout in flash image file\n");
@@ -469,7 +617,7 @@ main(int argc, char **argv)
 
     progname = argv[0];
 
-    while ((ch = getopt(argc, argv, "c:d:f:s")) != -1) {
+    while ((ch = getopt(argc, argv, "c:d:f:sv")) != -1) {
         switch (ch) {
         case 'c':
             fp = fopen(optarg, "rb");
@@ -486,6 +634,9 @@ main(int argc, char **argv)
         case 'f':
             native_flash_file = optarg;
             break;
+        case 'v':
+            print_verbose++;
+            break;
         case '?':
         default:
             usage(0);
@@ -512,14 +663,15 @@ main(int argc, char **argv)
 		fd = open(native_flash_file, O_RDWR);
 		if ((rc = fstat(fd, &st)))
 			perror("fstat failed");
+		file_flash_size = st.st_size;
 		if ((file_flash_area = mmap(0, (size_t)8192, PROT_READ,
 							   MAP_FILE|MAP_SHARED, fd, 0)) == MAP_FAILED) {
 			perror("%s mmap failed");
 		}
 
-		rc = file_area_init(file_flash_area, st.st_size);
+		rc = file_area_init(file_flash_area, file_flash_size);
 
-		print_file_areas();
+		print_nffs_flash_areas(file_flash_area, file_flash_size);
 
 		return 0;
 	}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f9ef5686/fs/nffs/src/nffs.c
----------------------------------------------------------------------
diff --git a/fs/nffs/src/nffs.c b/fs/nffs/src/nffs.c
index c90c4ef..f3b0372 100644
--- a/fs/nffs/src/nffs.c
+++ b/fs/nffs/src/nffs.c
@@ -33,6 +33,7 @@ struct nffs_area *nffs_areas;
 uint8_t nffs_num_areas;
 uint8_t nffs_scratch_area_idx;
 uint16_t nffs_block_max_data_sz;
+struct nffs_area_desc *nffs_current_area_descs;
 
 struct os_mempool nffs_file_pool;
 struct os_mempool nffs_dir_pool;

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f9ef5686/fs/nffs/src/nffs_block.c
----------------------------------------------------------------------
diff --git a/fs/nffs/src/nffs_block.c b/fs/nffs/src/nffs_block.c
index 5d51e3b..953e4dd 100644
--- a/fs/nffs/src/nffs_block.c
+++ b/fs/nffs/src/nffs_block.c
@@ -240,6 +240,17 @@ nffs_block_delete_from_ram(struct nffs_hash_entry *block_entry)
     struct nffs_block block;
     int rc;
 
+    if (nffs_hash_entry_is_dummy(block_entry)) {
+        /*
+         * it's very limited to what we can do here as the block doesn't have
+         * any way to get to the inode via hash entry. Just delete the
+         * block and return FS_ECORRUPT
+         */
+        nffs_hash_remove(block_entry);
+        nffs_block_entry_free(block_entry);
+        return FS_ECORRUPT;
+    }
+
     rc = nffs_block_from_hash_entry(&block, block_entry);
     if (rc == 0 || rc == FS_ECORRUPT) {
         /* If file system corruption was detected, the resulting block is still
@@ -326,6 +337,15 @@ nffs_block_from_hash_entry_no_ptrs(struct nffs_block *out_block,
 
     assert(nffs_hash_id_is_block(block_entry->nhe_id));
 
+    if (nffs_hash_entry_is_dummy(block_entry)) {
+        /*
+         * We can't read this from disk so we'll be missing filling in anything
+         * not already in inode_entry (e.g., prev_id).
+         */
+        out_block->nb_hash_entry = block_entry;
+        return FS_ENOENT; /* let caller know it's a partial inode_entry */
+    }
+
     nffs_flash_loc_expand(block_entry->nhe_flash_loc, &area_idx, &area_offset);
     rc = nffs_block_read_disk(area_idx, area_offset, &disk_block);
     if (rc != 0) {
@@ -371,6 +391,20 @@ nffs_block_from_hash_entry(struct nffs_block *out_block,
 
     assert(nffs_hash_id_is_block(block_entry->nhe_id));
 
+    if (nffs_block_is_dummy(block_entry)) {
+        out_block->nb_hash_entry = block_entry;
+        out_block->nb_inode_entry = NULL;
+        out_block->nb_prev = NULL;
+        /*
+         * Dummy block added when inode was read in before real block
+         * (see nffs_restore_inode()). Return success (because there's 
+         * too many places that ned to check for this,
+         * but it's the responsibility fo the upstream code to check
+         * whether this is still a dummy entry.  XXX
+         */
+        return 0;
+        /*return FS_ENOENT;*/
+    }
     nffs_flash_loc_expand(block_entry->nhe_flash_loc, &area_idx, &area_offset);
     rc = nffs_block_read_disk(area_idx, area_offset, &disk_block);
     if (rc != 0) {
@@ -406,3 +440,9 @@ nffs_block_read_data(const struct nffs_block *block, uint16_t offset,
 
     return 0;
 }
+
+int
+nffs_block_is_dummy(struct nffs_hash_entry *entry)
+{
+    return (entry->nhe_flash_loc == NFFS_FLASH_LOC_NONE);
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f9ef5686/fs/nffs/src/nffs_dir.c
----------------------------------------------------------------------
diff --git a/fs/nffs/src/nffs_dir.c b/fs/nffs/src/nffs_dir.c
index 58efa7c..09c3a0f 100644
--- a/fs/nffs/src/nffs_dir.c
+++ b/fs/nffs/src/nffs_dir.c
@@ -72,7 +72,7 @@ nffs_dir_open(const char *path, struct nffs_dir **out_dir)
     }
 
     dir->nd_parent_inode_entry = parent_inode_entry;
-    dir->nd_parent_inode_entry->nie_refcnt++;
+    nffs_inode_inc_refcnt(dir->nd_parent_inode_entry);
     memset(&dir->nd_dirent, 0, sizeof dir->nd_dirent);
 
     *out_dir = dir;
@@ -103,7 +103,7 @@ nffs_dir_read(struct nffs_dir *dir, struct nffs_dirent **out_dirent)
         return FS_ENOENT;
     }
 
-    child->nie_refcnt++;
+    nffs_inode_inc_refcnt(child);
     *out_dirent = &dir->nd_dirent;
 
     return 0;

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f9ef5686/fs/nffs/src/nffs_file.c
----------------------------------------------------------------------
diff --git a/fs/nffs/src/nffs_file.c b/fs/nffs/src/nffs_file.c
index 095bf21..708a493 100644
--- a/fs/nffs/src/nffs_file.c
+++ b/fs/nffs/src/nffs_file.c
@@ -93,13 +93,14 @@ nffs_file_new(struct nffs_inode_entry *parent, const char *filename,
         disk_inode.ndi_id = nffs_hash_next_file_id++;
     }
     disk_inode.ndi_seq = 0;
+    disk_inode.ndi_lastblock_id = NFFS_ID_NONE;
     if (parent == NULL) {
         disk_inode.ndi_parent_id = NFFS_ID_NONE;
     } else {
         disk_inode.ndi_parent_id = parent->nie_hash_entry.nhe_id;
     }
-	disk_inode.ndi_lastblock_id = 0; /* will be NFFS_ID_NONE when implemented */
     disk_inode.ndi_filename_len = filename_len;
+    disk_inode.ndi_flags = 0;
     nffs_crc_disk_inode_fill(&disk_inode, filename);
 
     rc = nffs_inode_write_disk(&disk_inode, filename, area_idx, offset);
@@ -111,6 +112,7 @@ nffs_file_new(struct nffs_inode_entry *parent, const char *filename,
     inode_entry->nie_hash_entry.nhe_flash_loc =
         nffs_flash_loc(area_idx, offset);
     inode_entry->nie_refcnt = 1;
+    inode_entry->nie_last_block_entry = NULL;
 
     if (parent != NULL) {
         rc = nffs_inode_add_child(parent, inode_entry);
@@ -119,6 +121,7 @@ nffs_file_new(struct nffs_inode_entry *parent, const char *filename,
         }
     } else {
         assert(disk_inode.ndi_id == NFFS_ID_ROOT_DIR);
+        nffs_inode_setflags(inode_entry, NFFS_INODE_FLAG_INTREE);
     }
 
     nffs_hash_insert(&inode_entry->nie_hash_entry);
@@ -237,7 +240,7 @@ nffs_file_open(struct nffs_file **out_file, const char *path,
     } else {
         file->nf_offset = 0;
     }
-    file->nf_inode_entry->nie_refcnt++;
+    nffs_inode_inc_refcnt(file->nf_inode_entry);
     file->nf_access_flags = access_flags;
 
     *out_file = file;

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f9ef5686/fs/nffs/src/nffs_format.c
----------------------------------------------------------------------
diff --git a/fs/nffs/src/nffs_format.c b/fs/nffs/src/nffs_format.c
index abd237f..13d97cc 100644
--- a/fs/nffs/src/nffs_format.c
+++ b/fs/nffs/src/nffs_format.c
@@ -178,6 +178,8 @@ nffs_format_full(const struct nffs_area_desc *area_descs)
         goto err;
     }
 
+    nffs_current_area_descs = (struct nffs_area_desc*) area_descs;
+
     return 0;
 
 err:

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f9ef5686/fs/nffs/src/nffs_gc.c
----------------------------------------------------------------------
diff --git a/fs/nffs/src/nffs_gc.c b/fs/nffs/src/nffs_gc.c
index 2f6aa20..ae92953 100644
--- a/fs/nffs/src/nffs_gc.c
+++ b/fs/nffs/src/nffs_gc.c
@@ -195,7 +195,7 @@ nffs_gc_block_chain_collate(struct nffs_hash_entry *last_entry,
     }
 
     memset(&last_block, 0, sizeof(last_block));
-    
+
     to_area = nffs_areas + to_area_idx;
 
     entry = last_entry;
@@ -226,7 +226,7 @@ nffs_gc_block_chain_collate(struct nffs_hash_entry *last_entry,
         }
         entry = block.nb_prev;
     }
-    
+
     /* we had better have found the last block */
     assert(last_block.nb_hash_entry);
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f9ef5686/fs/nffs/src/nffs_hash.c
----------------------------------------------------------------------
diff --git a/fs/nffs/src/nffs_hash.c b/fs/nffs/src/nffs_hash.c
index 6403bd1..805ed26 100644
--- a/fs/nffs/src/nffs_hash.c
+++ b/fs/nffs/src/nffs_hash.c
@@ -59,8 +59,8 @@ nffs_hash_fn(uint32_t id)
     return id % NFFS_HASH_SIZE;
 }
 
-struct nffs_hash_entry *
-nffs_hash_find(uint32_t id)
+static struct nffs_hash_entry *
+nffs_hash_find_reorder(uint32_t id)
 {
     struct nffs_hash_entry *entry;
     struct nffs_hash_entry *prev;
@@ -87,6 +87,25 @@ nffs_hash_find(uint32_t id)
     return NULL;
 }
 
+struct nffs_hash_entry *
+nffs_hash_find(uint32_t id)
+{
+    struct nffs_hash_entry *entry;
+    struct nffs_hash_list *list;
+    int idx;
+
+    idx = nffs_hash_fn(id);
+    list = nffs_hash + idx;
+
+    SLIST_FOREACH(entry, list, nhe_next) {
+        if (entry->nhe_id == id) {
+            return entry;
+        }
+    }
+
+    return NULL;
+}
+
 struct nffs_inode_entry *
 nffs_hash_find_inode(uint32_t id)
 {
@@ -94,7 +113,7 @@ nffs_hash_find_inode(uint32_t id)
 
     assert(nffs_hash_id_is_inode(id));
 
-    entry = nffs_hash_find(id);
+    entry = nffs_hash_find_reorder(id);
     return (struct nffs_inode_entry *)entry;
 }
 
@@ -105,32 +124,72 @@ nffs_hash_find_block(uint32_t id)
 
     assert(nffs_hash_id_is_block(id));
 
-    entry = nffs_hash_find(id);
+    entry = nffs_hash_find_reorder(id);
     return entry;
 }
 
+int
+nffs_hash_entry_is_dummy(struct nffs_hash_entry *he)
+{
+        return(he->nhe_flash_loc == NFFS_FLASH_LOC_NONE);
+}
+
+int
+nffs_hash_id_is_dummy(uint32_t id)
+{
+    struct nffs_hash_entry *he = nffs_hash_find(id);
+    if (he != NULL) {
+        return(he->nhe_flash_loc == NFFS_FLASH_LOC_NONE);
+    }
+    return 0;
+}
+
 void
 nffs_hash_insert(struct nffs_hash_entry *entry)
 {
     struct nffs_hash_list *list;
+    struct nffs_inode_entry *nie;
     int idx;
 
+    assert(nffs_hash_find(entry->nhe_id) == NULL);
     idx = nffs_hash_fn(entry->nhe_id);
     list = nffs_hash + idx;
 
     SLIST_INSERT_HEAD(list, entry, nhe_next);
+
+    if (nffs_hash_id_is_inode(entry->nhe_id)) {
+        nie = nffs_hash_find_inode(entry->nhe_id);
+        assert(nie);
+        nffs_inode_setflags(nie, NFFS_INODE_FLAG_INHASH);
+    } else {
+        assert(nffs_hash_find(entry->nhe_id));
+    }
 }
 
 void
 nffs_hash_remove(struct nffs_hash_entry *entry)
 {
     struct nffs_hash_list *list;
+    struct nffs_inode_entry *nie = NULL;
     int idx;
 
+    if (nffs_hash_id_is_inode(entry->nhe_id)) {
+        nie = nffs_hash_find_inode(entry->nhe_id);
+        assert(nie);
+        assert(nffs_inode_getflags(nie, NFFS_INODE_FLAG_INHASH));
+    } else {
+        assert(nffs_hash_find(entry->nhe_id));
+    }
+
     idx = nffs_hash_fn(entry->nhe_id);
     list = nffs_hash + idx;
 
     SLIST_REMOVE(list, entry, nffs_hash_entry, nhe_next);
+
+    if (nffs_hash_id_is_inode(entry->nhe_id) && nie) {
+        nffs_inode_unsetflags(nie, NFFS_INODE_FLAG_INHASH);
+    }
+    assert(nffs_hash_find(entry->nhe_id) == NULL);
 }
 
 int
@@ -151,4 +210,3 @@ nffs_hash_init(void)
 
     return 0;
 }
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f9ef5686/fs/nffs/src/nffs_inode.c
----------------------------------------------------------------------
diff --git a/fs/nffs/src/nffs_inode.c b/fs/nffs/src/nffs_inode.c
index 4b5a5a5..d8b881c 100644
--- a/fs/nffs/src/nffs_inode.c
+++ b/fs/nffs/src/nffs_inode.c
@@ -99,8 +99,8 @@ nffs_inode_read_disk(uint8_t area_idx, uint32_t offset,
                          sizeof *out_disk_inode);
     if (rc != 0) {
         return rc;
-	}
-	if (!nffs_hash_id_is_inode(out_disk_inode->ndi_id)) {
+    }
+    if (!nffs_hash_id_is_inode(out_disk_inode->ndi_id)) {
         return FS_EUNEXP;
     }
 
@@ -177,6 +177,14 @@ nffs_inode_data_len(struct nffs_inode_entry *inode_entry, uint32_t *out_len)
     return 0;
 }
 
+static void
+nffs_inode_restore_from_dummy_entry(struct nffs_inode *out_inode,
+                                    struct nffs_inode_entry *inode_entry)
+{
+    memset(out_inode, 0, sizeof *out_inode);
+    out_inode->ni_inode_entry = inode_entry;
+}
+
 int
 nffs_inode_from_entry(struct nffs_inode *out_inode,
                       struct nffs_inode_entry *entry)
@@ -187,6 +195,11 @@ nffs_inode_from_entry(struct nffs_inode *out_inode,
     int cached_name_len;
     int rc;
 
+    if (nffs_inode_is_dummy(entry)) {
+        nffs_inode_restore_from_dummy_entry(out_inode, entry);
+        return FS_ENOENT;
+    }
+
     nffs_flash_loc_expand(entry->nie_hash_entry.nhe_flash_loc,
                           &area_idx, &area_offset);
 
@@ -197,6 +210,11 @@ nffs_inode_from_entry(struct nffs_inode *out_inode,
 
     out_inode->ni_inode_entry = entry;
     out_inode->ni_seq = disk_inode.ndi_seq;
+
+    /*
+     * Relink to parent if possible
+     * XXX does this belong here?
+     */
     if (disk_inode.ndi_parent_id == NFFS_ID_NONE) {
         out_inode->ni_parent = NULL;
     } else {
@@ -217,6 +235,11 @@ nffs_inode_from_entry(struct nffs_inode *out_inode,
         }
     }
 
+    if (disk_inode.ndi_flags & NFFS_INODE_FLAG_DELETED) {
+        nffs_inode_setflags(out_inode->ni_inode_entry, NFFS_INODE_FLAG_DELETED);
+        nffs_inode_setflags(entry, NFFS_INODE_FLAG_DELETED);
+    }
+
     return 0;
 }
 
@@ -246,7 +269,9 @@ nffs_inode_delete_blocks_from_ram(struct nffs_inode_entry *inode_entry)
 
     return 0;
 }
-            /* The block references something that does not exist in RAM.  This
+
+            /* Dead comment?? XXX
+             * The block references something that does not exist in RAM.  This
              * is likely because the pointed-to object was in an area that has
              * been garbage collected.  Terminate the delete procedure and
              * report success.
@@ -276,6 +301,11 @@ nffs_inode_delete_from_ram(struct nffs_inode_entry *inode_entry,
     int rc;
 
     if (nffs_hash_id_is_file(inode_entry->nie_hash_entry.nhe_id)) {
+        /*
+         * Record the intention to delete the file
+         */
+        nffs_inode_setflags(inode_entry, NFFS_INODE_FLAG_DELETED);
+
         rc = nffs_inode_delete_blocks_from_ram(inode_entry);
         if (rc == FS_ECORRUPT && ignore_corruption) {
             inode_entry->nie_last_block_entry = NULL;
@@ -285,6 +315,10 @@ nffs_inode_delete_from_ram(struct nffs_inode_entry *inode_entry,
     }
 
     nffs_cache_inode_delete(inode_entry);
+    /*
+     * XXX Not deleting empty inode delete records from hash could prevent
+     * a case where we could lose delete records in a gc operation
+     */
     nffs_hash_remove(&inode_entry->nie_hash_entry);
     nffs_inode_entry_free(inode_entry);
 
@@ -312,6 +346,7 @@ nffs_inode_dec_refcnt_priv(struct nffs_inode_entry *inode_entry,
 {
     int rc;
 
+    assert(inode_entry);
     assert(inode_entry->nie_refcnt > 0);
 
     inode_entry->nie_refcnt--;
@@ -329,6 +364,14 @@ nffs_inode_dec_refcnt_priv(struct nffs_inode_entry *inode_entry,
     return 0;
 }
 
+int
+nffs_inode_inc_refcnt(struct nffs_inode_entry *inode_entry)
+{
+    assert(inode_entry);
+    inode_entry->nie_refcnt++;
+    return 0;
+}
+
 /**
  * Decrements the reference count of the specified inode entry.
  *
@@ -394,6 +437,8 @@ nffs_inode_process_unlink_list(struct nffs_hash_entry **inout_next,
             child = child_next;
         }
 
+
+
         /* The directory is already removed from the hash table; just free its
          * memory.
          */
@@ -424,10 +469,33 @@ nffs_inode_delete_from_disk(struct nffs_inode *inode)
     disk_inode.ndi_id = inode->ni_inode_entry->nie_hash_entry.nhe_id;
     disk_inode.ndi_seq = inode->ni_seq;
     disk_inode.ndi_parent_id = NFFS_ID_NONE;
+    disk_inode.ndi_flags = NFFS_INODE_FLAG_DELETED;
+    if (inode->ni_inode_entry->nie_last_block_entry) {
+        disk_inode.ndi_lastblock_id =
+                          inode->ni_inode_entry->nie_last_block_entry->nhe_id;
+    } else {
+        disk_inode.ndi_lastblock_id = NFFS_ID_NONE;
+    }
     disk_inode.ndi_filename_len = 0;
     nffs_crc_disk_inode_fill(&disk_inode, "");
 
     rc = nffs_inode_write_disk(&disk_inode, "", area_idx, offset);
+    NFFS_LOG(DEBUG, "inode_del_disk: wrote unlinked ino %x to disk ref %d\n",
+               (unsigned int)disk_inode.ndi_id,
+               inode->ni_inode_entry->nie_refcnt);
+
+    /*
+     * Flag the incore inode as deleted to the inode won't get updated to
+     * disk. This could happen if the refcnt > 0 and there are future appends
+     * XXX only do this for files and not directories
+     */
+    if (nffs_hash_id_is_file(inode->ni_inode_entry->nie_hash_entry.nhe_id)) {
+        nffs_inode_setflags(inode->ni_inode_entry, NFFS_INODE_FLAG_DELETED);
+        NFFS_LOG(DEBUG, "inode_delete_from_disk: ino %x flag DELETE\n",
+                   (unsigned int)inode->ni_inode_entry->nie_hash_entry.nhe_id);
+
+    }
+
     if (rc != 0) {
         return rc;
     }
@@ -544,6 +612,11 @@ nffs_inode_rename(struct nffs_inode_entry *inode_entry,
     disk_inode.ndi_seq = inode.ni_seq + 1;
     disk_inode.ndi_parent_id = nffs_inode_parent_id(&inode);
     disk_inode.ndi_filename_len = filename_len;
+    if (inode_entry->nie_last_block_entry &&
+        inode_entry->nie_last_block_entry->nhe_id != NFFS_ID_NONE)
+        disk_inode.ndi_lastblock_id = inode_entry->nie_last_block_entry->nhe_id;
+    else 
+        disk_inode.ndi_lastblock_id = NFFS_ID_NONE;
     nffs_crc_disk_inode_fill(&disk_inode, new_filename);
 
     rc = nffs_inode_write_disk(&disk_inode, new_filename, area_idx,
@@ -558,6 +631,74 @@ nffs_inode_rename(struct nffs_inode_entry *inode_entry,
     return 0;
 }
 
+int
+nffs_inode_update(struct nffs_inode_entry *inode_entry)
+{
+    struct nffs_disk_inode disk_inode;
+    struct nffs_inode inode;
+    uint32_t area_offset;
+    uint8_t area_idx;
+    char *filename;
+    int filename_len;
+    int rc;
+
+    rc = nffs_inode_from_entry(&inode, inode_entry);
+    /*
+     * if rc == FS_ENOENT, file is dummy is unlinked and so
+     * can not be updated to disk.
+     */
+    if (rc == FS_ENOENT)
+        assert(nffs_inode_is_dummy(inode_entry));
+    if (rc != 0) {
+        return rc;
+    }
+
+    assert(inode_entry->nie_hash_entry.nhe_flash_loc != NFFS_FLASH_LOC_NONE);
+
+    filename_len = inode.ni_filename_len;
+    nffs_flash_loc_expand(inode_entry->nie_hash_entry.nhe_flash_loc,
+                          &area_idx, &area_offset);
+    rc = nffs_flash_read(area_idx,
+                         area_offset + sizeof (struct nffs_disk_inode),
+                         nffs_flash_buf, filename_len);
+    if (rc != 0) {
+        return rc;
+    }
+
+    filename = (char *)nffs_flash_buf;
+
+    rc = nffs_misc_reserve_space(sizeof disk_inode + filename_len,
+                                 &area_idx, &area_offset);
+    if (rc != 0) {
+        return rc;
+    }
+
+    disk_inode.ndi_id = inode_entry->nie_hash_entry.nhe_id;
+    disk_inode.ndi_seq = inode.ni_seq + 1;
+    disk_inode.ndi_parent_id = nffs_inode_parent_id(&inode);
+    disk_inode.ndi_flags = 0;
+    disk_inode.ndi_filename_len = filename_len;
+
+    assert(nffs_hash_id_is_block(inode_entry->nie_last_block_entry->nhe_id));
+    disk_inode.ndi_lastblock_id = inode_entry->nie_last_block_entry->nhe_id;
+
+    nffs_crc_disk_inode_fill(&disk_inode, filename);
+
+    NFFS_LOG(DEBUG, "nffs_inode_update writing inode %x last block %x\n",
+             (unsigned int)disk_inode.ndi_id,
+             (unsigned int)disk_inode.ndi_lastblock_id);
+
+    rc = nffs_inode_write_disk(&disk_inode, filename, area_idx,
+                               area_offset);
+    if (rc != 0) {
+        return rc;
+    }
+
+    inode_entry->nie_hash_entry.nhe_flash_loc =
+        nffs_flash_loc(area_idx, area_offset);
+    return 0;
+}
+
 static int
 nffs_inode_read_filename_chunk(const struct nffs_inode *inode,
                                uint8_t filename_offset, void *buf, int len)
@@ -637,6 +778,7 @@ nffs_inode_add_child(struct nffs_inode_entry *parent,
     int rc;
 
     assert(nffs_hash_id_is_dir(parent->nie_hash_entry.nhe_id));
+    assert(!nffs_inode_getflags(child, NFFS_INODE_FLAG_INTREE));
 
     rc = nffs_inode_from_entry(&child_inode, child);
     if (rc != 0) {
@@ -668,6 +810,7 @@ nffs_inode_add_child(struct nffs_inode_entry *parent,
     } else {
         SLIST_INSERT_AFTER(prev, child, nie_sibling_next);
     }
+    nffs_inode_setflags(child, NFFS_INODE_FLAG_INTREE);
 
     return 0;
 }
@@ -677,12 +820,14 @@ nffs_inode_remove_child(struct nffs_inode *child)
 {
     struct nffs_inode_entry *parent;
 
+    assert(nffs_inode_getflags(child->ni_inode_entry, NFFS_INODE_FLAG_INTREE));
     parent = child->ni_parent;
     assert(parent != NULL);
     assert(nffs_hash_id_is_dir(parent->nie_hash_entry.nhe_id));
     SLIST_REMOVE(&parent->nie_child_list, child->ni_inode_entry,
                  nffs_inode_entry, nie_sibling_next);
     SLIST_NEXT(child->ni_inode_entry, nie_sibling_next) = NULL;
+    nffs_inode_unsetflags(child->ni_inode_entry, NFFS_INODE_FLAG_INTREE);
 }
 
 int
@@ -737,6 +882,9 @@ nffs_inode_filename_cmp_ram(const struct nffs_inode *inode,
     return 0;
 }
 
+/*
+ * Compare filenames in flash
+ */
 int
 nffs_inode_filename_cmp_flash(const struct nffs_inode *inode1,
                               const struct nffs_inode *inode2,
@@ -973,6 +1121,12 @@ nffs_inode_unlink_from_ram_priv(struct nffs_inode *inode,
         nffs_inode_remove_child(inode);
     }
 
+    /*
+     * Regardless of whether the inode is removed from hashlist, we record
+     * the intention to delete it here.
+     */
+    nffs_inode_setflags(inode->ni_inode_entry, NFFS_INODE_FLAG_DELETED);
+
     if (nffs_hash_id_is_dir(inode->ni_inode_entry->nie_hash_entry.nhe_id)) {
         nffs_inode_insert_unlink_list(inode->ni_inode_entry);
         rc = nffs_inode_process_unlink_list(out_next, ignore_corruption);
@@ -1073,3 +1227,59 @@ nffs_inode_unlink(struct nffs_inode *inode)
 
     return 0;
 }
+
+/*
+ * Return true if inode is a dummy inode, that was allocated as a
+ * place holder in the case that an inode is restored before it's parent.
+ */
+int
+nffs_inode_is_dummy(struct nffs_inode_entry *inode_entry)
+{
+    if (inode_entry->nie_flash_loc == NFFS_FLASH_LOC_NONE) {
+        /*
+         * set if not already XXX can delete after debug
+         */
+        nffs_inode_setflags(inode_entry, NFFS_INODE_FLAG_DUMMY);
+        return 1;
+    }
+
+    if (inode_entry == nffs_root_dir) {
+        return 0;
+    } else {
+        return nffs_inode_getflags(inode_entry, NFFS_INODE_FLAG_DUMMY);
+    }
+}
+
+/*
+ * Return true if inode is marked as deleted.
+ */
+int
+nffs_inode_is_deleted(struct nffs_inode_entry *inode_entry)
+{
+    assert(inode_entry);
+
+    return nffs_inode_getflags(inode_entry, NFFS_INODE_FLAG_DELETED);
+}
+
+int
+nffs_inode_setflags(struct nffs_inode_entry *entry, uint8_t flag)
+{
+    /*
+     * We shouldn't be setting flags to already deleted inodes
+     */
+    entry->nie_flags |= flag;
+    return (int)entry->nie_flags;
+}
+
+int
+nffs_inode_unsetflags(struct nffs_inode_entry *entry, uint8_t flag)
+{
+    entry->nie_flags &= ~flag;
+    return (int)entry->nie_flags;
+}
+
+int
+nffs_inode_getflags(struct nffs_inode_entry *entry, uint8_t flag)
+{
+    return (int)(entry->nie_flags & flag);
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f9ef5686/fs/nffs/src/nffs_misc.c
----------------------------------------------------------------------
diff --git a/fs/nffs/src/nffs_misc.c b/fs/nffs/src/nffs_misc.c
index 7f9955d..cbf0e45 100644
--- a/fs/nffs/src/nffs_misc.c
+++ b/fs/nffs/src/nffs_misc.c
@@ -48,7 +48,10 @@ nffs_misc_validate_root_dir(void)
     }
 
     rc = nffs_inode_from_entry(&inode, nffs_root_dir);
-    if (rc != 0) {
+    /*
+     * nffs_root_dir is automatically flagged a "dummy" inode but it's special
+     */
+    if (rc != 0 && rc != FS_ENOENT) {
         return rc;
     }
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f9ef5686/fs/nffs/src/nffs_path.c
----------------------------------------------------------------------
diff --git a/fs/nffs/src/nffs_path.c b/fs/nffs/src/nffs_path.c
index 7fae0d1..85772d4 100644
--- a/fs/nffs/src/nffs_path.c
+++ b/fs/nffs/src/nffs_path.c
@@ -98,6 +98,10 @@ nffs_path_find_child(struct nffs_inode_entry *parent,
     return FS_ENOENT;
 }
 
+/*
+ * Return the inode and optionally it's parent associated with the input path
+ * nffs_path_parser struct used to track location in hierarchy
+ */
 int
 nffs_path_find(struct nffs_path_parser *parser,
                struct nffs_inode_entry **out_inode_entry,
@@ -269,6 +273,15 @@ nffs_path_rename(const char *from, const char *to)
             return rc;
         }
 
+        /*
+         * Don't allow renames if the inode has been deleted
+         * Side-effect is that we've restored the inode as needed.
+         */
+        if (nffs_inode_is_deleted(from_inode_entry)) {
+            assert(0);
+            return FS_ENOENT;
+        }
+
         rc = nffs_inode_unlink(&inode);
         if (rc != 0) {
             return rc;

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f9ef5686/fs/nffs/src/nffs_priv.h
----------------------------------------------------------------------
diff --git a/fs/nffs/src/nffs_priv.h b/fs/nffs/src/nffs_priv.h
index 76c7827..b654b85 100644
--- a/fs/nffs/src/nffs_priv.h
+++ b/fs/nffs/src/nffs_priv.h
@@ -39,6 +39,7 @@
 
 #define NFFS_ID_ROOT_DIR             0
 #define NFFS_ID_NONE                 0xffffffff
+#define NFFS_HASH_ENTRY_NONE         0xffffffff
 
 #define NFFS_AREA_MAGIC0             0xb98a31e2
 #define NFFS_AREA_MAGIC1             0x7fb0428c
@@ -48,7 +49,7 @@
 #define NFFS_INODE_MAGIC             0x925f8bc0
 
 #define NFFS_AREA_ID_NONE            0xff
-#define NFFS_AREA_VER_0				 0
+#define NFFS_AREA_VER_0                 0
 #define NFFS_AREA_VER_1              1
 #define NFFS_AREA_VER                NFFS_AREA_VER_1
 #define NFFS_AREA_OFFSET_ID          23
@@ -68,44 +69,14 @@ struct nffs_disk_area {
 };
 
 /** On-disk representation of an inode (file or directory). */
-struct nffs_disk_inodeV0 {
-    uint32_t ndi_magic;         /* NFFS_INODE_MAGIC */
-    uint32_t ndi_id;            /* Unique object ID. */
-    uint32_t ndi_seq;           /* Sequence number; greater supersedes
-                                   lesser. */
-    uint32_t ndi_parent_id;     /* Object ID of parent directory inode. */
-    uint8_t reserved8;
-    uint8_t ndi_filename_len;   /* Length of filename, in bytes. */
-    uint16_t ndi_crc16;         /* Covers rest of header and filename. */
-    /* Followed by filename. */
-};
-
-#define NFFS_DISK_INODEV0_OFFSET_CRC  18
-
-/** On-disk representation of a data block. */
-struct nffs_disk_blockV0 {
-    uint32_t ndb_magic;     /* NFFS_BLOCK_MAGIC */
-    uint32_t ndb_id;        /* Unique object ID. */
-    uint32_t ndb_seq;       /* Sequence number; greater supersedes lesser. */
-    uint32_t ndb_inode_id;  /* Object ID of owning inode. */
-    uint32_t ndb_prev_id;   /* Object ID of previous block in file;
-                               NFFS_ID_NONE if this is the first block. */
-    uint16_t ndb_data_len;  /* Length of data contents, in bytes. */
-    uint16_t ndb_crc16;     /* Covers rest of header and data. */
-    /* Followed by 'ndb_data_len' bytes of data. */
-};
-
-#define NFFS_DISK_BLOCKV0_OFFSET_CRC  22
-
-/** On-disk representation of an inode (file or directory). */
 struct nffs_disk_inode {
     uint32_t ndi_id;            /* Unique object ID. */
     uint32_t ndi_parent_id;     /* Object ID of parent directory inode. */
     uint32_t ndi_lastblock_id;     /* Object ID of parent directory inode. */
     uint16_t ndi_seq;           /* Sequence number; greater supersedes
                                    lesser. */
-	uint16_t reserved16;
-    uint8_t reserved8;
+    uint16_t reserved16;
+    uint8_t ndi_flags;            /* flags */
     uint8_t ndi_filename_len;   /* Length of filename, in bytes. */
     uint16_t ndi_crc16;         /* Covers rest of header and filename. */
     /* Followed by filename. */
@@ -149,10 +120,26 @@ struct nffs_inode_entry {
     union {
         struct nffs_inode_list nie_child_list;           /* If directory */
         struct nffs_hash_entry *nie_last_block_entry;    /* If file */
+        uint32_t nie_lastblock_id;
     };
     uint8_t nie_refcnt;
+    uint8_t nie_flags;
+    uint16_t reserved16;
 };
 
+#define    NFFS_INODE_FLAG_FREE        0x00
+#define    NFFS_INODE_FLAG_DUMMY       0x01    /* inode is a dummy */
+#define    NFFS_INODE_FLAG_DUMMYPARENT 0x02    /* parent not in cache */
+#define    NFFS_INODE_FLAG_DUMMYLSTBLK 0x04    /* lastblock not in cache */
+#define    NFFS_INODE_FLAG_DUMMYINOBLK 0x08    /* dummy inode for blk */
+#define    NFFS_INODE_FLAG_OBSOLETE    0x10    /* always replace if same ID */
+#define    NFFS_INODE_FLAG_INTREE      0x20    /* in directory structure */
+#define    NFFS_INODE_FLAG_INHASH      0x40    /* in hash table */
+#define    NFFS_INODE_FLAG_DELETED     0x80    /* inode deleted */
+
+#define nie_id            nie_hash_entry.nhe_id
+#define nie_flash_loc    nie_hash_entry.nhe_flash_loc
+
 /** Full inode representation; not stored permanently RAM. */
 struct nffs_inode {
     struct nffs_inode_entry *ni_inode_entry; /* Points to real inode entry. */
@@ -199,8 +186,8 @@ struct nffs_disk_object {
     } ndo_un_obj;
 };
 
-#define ndo_disk_inode	ndo_un_obj.ndo_disk_inode
-#define ndo_disk_block	ndo_un_obj.ndo_disk_block
+#define ndo_disk_inode    ndo_un_obj.ndo_disk_inode
+#define ndo_disk_block    ndo_un_obj.ndo_disk_block
 
 struct nffs_seek_info {
     struct nffs_block nsi_last_block;
@@ -269,6 +256,7 @@ extern uint8_t nffs_num_areas;
 extern uint8_t nffs_scratch_area_idx;
 extern uint16_t nffs_block_max_data_sz;
 extern unsigned int nffs_gc_count;
+extern struct nffs_area_desc *nffs_current_area_descs;
 
 #define NFFS_FLASH_BUF_SZ        256
 extern uint8_t nffs_flash_buf[NFFS_FLASH_BUF_SZ];
@@ -313,6 +301,7 @@ int nffs_block_from_hash_entry(struct nffs_block *out_block,
                                struct nffs_hash_entry *entry);
 int nffs_block_read_data(const struct nffs_block *block, uint16_t offset,
                          uint16_t length, void *dst);
+int nffs_block_is_dummy(struct nffs_hash_entry *entry);
 
 /* @cache */
 void nffs_cache_inode_delete(const struct nffs_inode_entry *inode_entry);
@@ -390,6 +379,8 @@ struct nffs_hash_entry *nffs_hash_find_block(uint32_t id);
 void nffs_hash_insert(struct nffs_hash_entry *entry);
 void nffs_hash_remove(struct nffs_hash_entry *entry);
 int nffs_hash_init(void);
+int nffs_hash_entry_is_dummy(struct nffs_hash_entry *he);
+int nffs_hash_id_is_dummy(uint32_t id);
 
 /* @inode */
 struct nffs_inode_entry *nffs_inode_entry_alloc(void);
@@ -407,6 +398,7 @@ int nffs_inode_entry_from_disk(struct nffs_inode_entry *out_inode,
 int nffs_inode_rename(struct nffs_inode_entry *inode_entry,
                       struct nffs_inode_entry *new_parent,
                       const char *new_filename);
+int nffs_inode_update(struct nffs_inode_entry *inode_entry);
 void nffs_inode_insert_block(struct nffs_inode *inode,
                              struct nffs_block *block);
 int nffs_inode_read_disk(uint8_t area_idx, uint32_t offset,
@@ -414,6 +406,7 @@ int nffs_inode_read_disk(uint8_t area_idx, uint32_t offset,
 int nffs_inode_write_disk(const struct nffs_disk_inode *disk_inode,
                           const char *filename, uint8_t area_idx,
                           uint32_t offset);
+int nffs_inode_inc_refcnt(struct nffs_inode_entry *inode_entry);
 int nffs_inode_dec_refcnt(struct nffs_inode_entry *inode_entry);
 int nffs_inode_add_child(struct nffs_inode_entry *parent,
                          struct nffs_inode_entry *child);
@@ -439,6 +432,11 @@ int nffs_inode_unlink_from_ram(struct nffs_inode *inode,
 int nffs_inode_unlink_from_ram_corrupt_ok(struct nffs_inode *inode,
                                           struct nffs_hash_entry **out_next);
 int nffs_inode_unlink(struct nffs_inode *inode);
+int nffs_inode_is_dummy(struct nffs_inode_entry *inode_entry);
+int nffs_inode_is_deleted(struct nffs_inode_entry *inode_entry);
+int nffs_inode_setflags(struct nffs_inode_entry *entry, uint8_t flag);
+int nffs_inode_unsetflags(struct nffs_inode_entry *entry, uint8_t flag);
+int nffs_inode_getflags(struct nffs_inode_entry *entry, uint8_t flag);
 
 /* @misc */
 int nffs_misc_gc_if_oom(void *resource, int *out_rc);
@@ -483,7 +481,7 @@ int nffs_write_to_file(struct nffs_file *file, const void *data, int len);
 #ifdef NFFS_DEBUG
 #include <stdio.h>
 #define NFFS_LOG(lvl, ...) \
-  	printf(__VA_ARGS__)
+      printf(__VA_ARGS__)
 #else
 #define NFFS_LOG(lvl, ...) \
     LOG_ ## lvl(&nffs_log, LOG_MODULE_NFFS, __VA_ARGS__)

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f9ef5686/fs/nffs/src/nffs_restore.c
----------------------------------------------------------------------
diff --git a/fs/nffs/src/nffs_restore.c b/fs/nffs/src/nffs_restore.c
index eb16c71..83b2ef9 100644
--- a/fs/nffs/src/nffs_restore.c
+++ b/fs/nffs/src/nffs_restore.c
@@ -56,6 +56,10 @@ nffs_restore_validate_block_chain(struct nffs_hash_entry *last_block_entry)
     cur = last_block_entry;
 
     while (cur != NULL) {
+        if (nffs_hash_entry_is_dummy(cur)) {
+            return FS_ENOENT;
+        }
+
         nffs_flash_loc_expand(cur->nhe_flash_loc, &area_idx, &area_offset);
 
         rc = nffs_block_read_disk(area_idx, area_offset, &disk_block);
@@ -77,27 +81,27 @@ nffs_restore_validate_block_chain(struct nffs_hash_entry *last_block_entry)
 static void
 u32toa(char *dst, uint32_t val)
 {
-	uint8_t tmp;
-	int idx = 0;
-	int i;
-	int print = 0;
-
-	for (i = 0; i < 8; i++) {
-		tmp = val >> 28;
-		if (tmp || i == 7) {
-			print = 1;
-		}
-		if (tmp < 10) {
-			tmp += '0';
-		} else {
-			tmp += 'a' - 10;
-		}
-		if (print) {
-			dst[idx++] = tmp;
-		}
-		val <<= 4;
-	}
-	dst[idx++] = '\0';
+    uint8_t tmp;
+    int idx = 0;
+    int i;
+    int print = 0;
+
+    for (i = 0; i < 8; i++) {
+        tmp = val >> 28;
+        if (tmp || i == 7) {
+            print = 1;
+        }
+        if (tmp < 10) {
+            tmp += '0';
+        } else {
+            tmp += 'a' - 10;
+        }
+        if (print) {
+            dst[idx++] = tmp;
+        }
+        val <<= 4;
+    }
+    dst[idx++] = '\0';
 }
 
 /**
@@ -121,7 +125,7 @@ nffs_restore_migrate_orphan_children(struct nffs_inode_entry *inode_entry)
         return 0;
     }
 
-    if (inode_entry->nie_refcnt != 0) {
+    if (!nffs_inode_is_dummy(inode_entry)) {
         /* Not a dummy. */
         return 0;
     }
@@ -160,16 +164,44 @@ nffs_restore_should_sweep_inode_entry(struct nffs_inode_entry *inode_entry,
     struct nffs_inode inode;
     int rc;
 
-    /* Determine if the inode is a dummy.  Dummy inodes have a reference count
-     * of 0.  If it is a dummy, increment its reference count back to 1 so that
-     * it can be properly deleted.  The presence of a dummy inode during the
-     * final sweep step indicates file system corruption.  If the inode is a
-     * directory, all its children should have been migrated to the /lost+found
-     * directory prior to this.
+
+    /*
+     * if this inode was tagged to have a dummy block entry and the
+     * flag is still set, that means we didn't find the block and so
+     * should remove this inode and all associated blocks.
      */
-    if (inode_entry->nie_refcnt == 0) {
+    if (nffs_inode_getflags(inode_entry, NFFS_INODE_FLAG_DUMMYLSTBLK)) {
         *out_should_sweep = 1;
-        inode_entry->nie_refcnt++;
+        /*nffs_inode_inc_refcnt(inode_entry);*/
+        inode_entry->nie_refcnt = 1;
+        assert(inode_entry->nie_refcnt >= 1);
+        return 0;
+    }
+
+    /*
+     * This inode was originally created to hold a block that was restored
+     * before the owning inode. If the flag is still set, it means we never
+     * restored the inode from disk and so this entry should be deleted.
+     */
+    if (nffs_inode_getflags(inode_entry, NFFS_INODE_FLAG_DUMMYINOBLK)) {
+        *out_should_sweep = 2;
+        /*nffs_inode_inc_refcnt(inode_entry);*/
+        inode_entry->nie_refcnt = 1;
+        assert(inode_entry->nie_refcnt >= 1);
+        return 0;
+    }
+
+    /*
+     * Determine if the inode is a dummy. Dummy inodes have a flash
+     * location set to LOC_NONE and should have a flag set for the reason.
+     * The presence of a dummy inode during the final sweep step indicates
+     * file system corruption.  It's assumed that directories have
+     * previously migrated all children to /lost+found.
+     */
+    if (nffs_inode_is_dummy(inode_entry)) {
+        *out_should_sweep = 3;
+        nffs_inode_inc_refcnt(inode_entry);
+        assert(inode_entry->nie_refcnt >= 1);
         return 0;
     }
 
@@ -179,17 +211,32 @@ nffs_restore_should_sweep_inode_entry(struct nffs_inode_entry *inode_entry,
      */
     if (inode_entry->nie_hash_entry.nhe_id != NFFS_ID_ROOT_DIR) {
         rc = nffs_inode_from_entry(&inode, inode_entry);
-        if (rc != 0) {
+        if (rc != 0 && rc != FS_ENOENT) {
             *out_should_sweep = 0;
             return rc;
         }
-
         if (inode.ni_parent == NULL) {
-            *out_should_sweep = 1;
+            *out_should_sweep = 4;
             return 0;
         }
     }
 
+    /*
+     * If this inode has been marked as deleted, we can unlink it here.
+     *
+     * XXX Note that the record of a deletion could be lost if garbage
+     * collection erases the delete but leaves inode updates on other
+     * partitions which can then be restored.
+     */
+    if (nffs_inode_getflags(inode_entry, NFFS_INODE_FLAG_DELETED)) {
+        rc = nffs_inode_from_entry(&inode, inode_entry);
+        if (rc != 0) {
+            *out_should_sweep = 0;
+            return rc;
+        }
+        *out_should_sweep = 5;
+    }
+
     /* If this is a file inode, verify that all of its constituent blocks are
      * present.
      */
@@ -197,7 +244,10 @@ nffs_restore_should_sweep_inode_entry(struct nffs_inode_entry *inode_entry,
         rc = nffs_restore_validate_block_chain(
                 inode_entry->nie_last_block_entry);
         if (rc == FS_ECORRUPT) {
-            *out_should_sweep = 1;
+            *out_should_sweep = 6;
+            return 0;
+        } else if (rc == FS_ENOENT) {
+            *out_should_sweep = 7;
             return 0;
         } else if (rc != 0) {
             *out_should_sweep = 0;
@@ -210,85 +260,6 @@ nffs_restore_should_sweep_inode_entry(struct nffs_inode_entry *inode_entry,
     return 0;
 }
 
-static void
-nffs_restore_inode_from_dummy_entry(struct nffs_inode *out_inode,
-                                    struct nffs_inode_entry *inode_entry)
-{
-    memset(out_inode, 0, sizeof *out_inode);
-    out_inode->ni_inode_entry = inode_entry;
-}
-
-static int
-nffs_restore_find_file_end_block(struct nffs_hash_entry *block_entry)
-{
-    struct nffs_inode_entry *inode_entry;
-    struct nffs_block block;
-    int rc;
-
-    rc = nffs_block_from_hash_entry(&block, block_entry);
-    assert(rc == 0);
-
-    inode_entry = block.nb_inode_entry;
-
-    /* Make sure the parent inode (file) points to the latest data block
-     * restored so far.
-     *
-     * XXX: This is an O(n) operation (n = # of blocks in the file), and is
-     * horribly inefficient for large files.  MYNEWT-161 has been opened to
-     * address this.
-     */
-    if (inode_entry->nie_last_block_entry == NULL) {
-        /* This is the first data block restored for this file. */
-        inode_entry->nie_last_block_entry = block_entry;
-        NFFS_LOG(DEBUG, "setting last block: %u\n", block_entry->nhe_id);
-    } else {
-        /* Determine if this this data block comes after our current idea of
-         * the file's last data block.
-         */
-
-        rc = nffs_block_find_predecessor(
-            block_entry, inode_entry->nie_last_block_entry->nhe_id);
-        switch (rc) {
-        case 0:
-            /* The currently-last block is a predecessor of the new block; the
-             * new block comes later.
-             */
-            NFFS_LOG(DEBUG, "replacing last block: %u --> %u\n",
-                     inode_entry->nie_last_block_entry->nhe_id,
-                     block_entry->nhe_id);
-            inode_entry->nie_last_block_entry = block_entry;
-            break;
-
-        case FS_ENOENT:
-            break;
-
-        default:
-            return rc;
-        }
-    }
-
-    return 0;
-}
-
-
-static int
-nffs_restore_find_file_ends(void)
-{
-    struct nffs_hash_entry *block_entry;
-    struct nffs_hash_entry *next;
-    int rc;
-    int i;
-
-    NFFS_HASH_FOREACH(block_entry, i, next) {
-        if (!nffs_hash_id_is_inode(block_entry->nhe_id)) {
-            rc = nffs_restore_find_file_end_block(block_entry);
-            assert(rc == 0);
-        }
-    }
-
-    return 0;
-}
-
 /**
  * Performs a sweep of the RAM representation at the end of a successful
  * restore.  The sweep phase performs the following actions of each inode in
@@ -310,6 +281,7 @@ nffs_restore_sweep(void)
     struct nffs_hash_entry *next;
     struct nffs_hash_list *list;
     struct nffs_inode inode;
+    struct nffs_block block;
     int del;
     int rc;
     int i;
@@ -326,9 +298,10 @@ nffs_restore_sweep(void)
             if (nffs_hash_id_is_inode(entry->nhe_id)) {
                 inode_entry = (struct nffs_inode_entry *)entry;
 
-                /* If this is a dummy inode directory, the file system is
-                 * corrupted.  Move the directory's children inodes to the
-                 * lost+found directory.
+                /*
+                 * If this is a dummy inode directory, the file system
+                 * is corrupt.  Move the directory's children inodes to
+                 * the lost+found directory.
                  */
                 rc = nffs_restore_migrate_orphan_children(inode_entry);
                 if (rc != 0) {
@@ -341,18 +314,23 @@ nffs_restore_sweep(void)
                     return rc;
                 }
 
+                rc = nffs_inode_from_entry(&inode, inode_entry);
+                if (rc != 0 && rc != FS_ENOENT) {
+                    return rc;
+                }
+
+#if 0 /* for now, don't preserve corrupted directories */
+                /*
+                 * if this inode doesn't have a parent, move it to
+                 * the lost_found directory
+                 */
+                if (inode_entry != nffs_root_dir && inode.ni_parent == NULL) {
+                    rc = nffs_inode_rename(inode_entry,
+                                           nffs_lost_found_dir, NULL);
+                }
+#endif
+
                 if (del) {
-                    if (inode_entry->nie_hash_entry.nhe_flash_loc ==
-                        NFFS_FLASH_LOC_NONE) {
-
-                        nffs_restore_inode_from_dummy_entry(&inode,
-                                                           inode_entry);
-                    } else {
-                        rc = nffs_inode_from_entry(&inode, inode_entry);
-                        if (rc != 0) {
-                            return rc;
-                        }
-                    }
 
                     /* Remove the inode and all its children from RAM.  We
                      * expect some file system corruption; the children are
@@ -366,6 +344,15 @@ nffs_restore_sweep(void)
                     }
                     next = SLIST_FIRST(list);
                 }
+            } else if (nffs_hash_id_is_block(entry->nhe_id)) {
+                if (nffs_hash_id_is_dummy(entry->nhe_id)) {
+                    nffs_block_delete_from_ram(entry);
+                } else {
+                    rc = nffs_block_from_hash_entry(&block, entry);
+                    if (rc != 0 && rc != FS_ENOENT) {
+                        nffs_block_delete_from_ram(entry);
+                    }
+                }
             }
 
             entry = next;
@@ -380,7 +367,8 @@ nffs_restore_sweep(void)
  * a temporary placeholder for a real inode that has not been restored yet.
  * These are necessary so that the inter-object links can be maintained until
  * the absent inode is eventually restored.  Dummy inodes are identified by a
- * reference count of 0.
+ * inaccessible flash location (NFFS_FLASH_LOC_NONE). When the real inode
+ * is restored, this flash location will be udpated.
  *
  * @param id                    The ID of the dummy inode to create.
  * @param out_inode_entry       On success, the dummy inode gets written here.
@@ -400,6 +388,8 @@ nffs_restore_dummy_inode(uint32_t id,
     inode_entry->nie_hash_entry.nhe_id = id;
     inode_entry->nie_hash_entry.nhe_flash_loc = NFFS_FLASH_LOC_NONE;
     inode_entry->nie_refcnt = 0;
+    inode_entry->nie_last_block_entry = NULL; /* lastblock not available yet */
+    nffs_inode_setflags(inode_entry, NFFS_INODE_FLAG_DUMMY);
 
     nffs_hash_insert(&inode_entry->nie_hash_entry);
 
@@ -431,11 +421,22 @@ nffs_restore_inode_gets_replaced(struct nffs_inode_entry *old_inode_entry,
 
     assert(old_inode_entry->nie_hash_entry.nhe_id == disk_inode->ndi_id);
 
-    if (old_inode_entry->nie_refcnt == 0) {
+
+    if (nffs_inode_is_dummy(old_inode_entry)) {
+        NFFS_LOG(DEBUG, "inode_gets_replaced dummy!\n");
         *out_should_replace = 1;
         return 0;
     }
 
+    /*
+     * inode is known to be obsolete and needs to be replaced no matter what
+     */
+    if (nffs_inode_getflags(old_inode_entry, NFFS_INODE_FLAG_OBSOLETE)) {
+        NFFS_LOG(DEBUG, "inode_gets_replaced obsolete\n");
+        *out_should_replace = 2;
+        return 0;
+    }
+
     rc = nffs_inode_from_entry(&old_inode, old_inode_entry);
     if (rc != 0) {
         *out_should_replace = 0;
@@ -443,7 +444,8 @@ nffs_restore_inode_gets_replaced(struct nffs_inode_entry *old_inode_entry,
     }
 
     if (old_inode.ni_seq < disk_inode->ndi_seq) {
-        *out_should_replace = 1;
+        NFFS_LOG(DEBUG, "inode_gets_replaced seq\n");
+        *out_should_replace = 3;
         return 0;
     }
 
@@ -452,7 +454,7 @@ nffs_restore_inode_gets_replaced(struct nffs_inode_entry *old_inode_entry,
          * happen.
          */
         *out_should_replace = 0;
-        return FS_ECORRUPT;
+        return FS_EEXIST;
     }
 
     *out_should_replace = 0;
@@ -476,6 +478,7 @@ nffs_restore_inode(const struct nffs_disk_inode *disk_inode, uint8_t area_idx,
     struct nffs_inode_entry *inode_entry;
     struct nffs_inode_entry *parent;
     struct nffs_inode inode;
+    struct nffs_hash_entry *lastblock_entry = NULL;
     int new_inode;
     int do_add;
     int rc;
@@ -489,29 +492,113 @@ nffs_restore_inode(const struct nffs_disk_inode *disk_inode, uint8_t area_idx,
     }
 
     inode_entry = nffs_hash_find_inode(disk_inode->ndi_id);
+
+    /*
+     * Inode has already been restored. Determine whether this version
+     * from disk should replace the previous version referenced in RAM.
+     */
     if (inode_entry != NULL) {
-        rc = nffs_restore_inode_gets_replaced(inode_entry, disk_inode,
-                                              &do_add);
+
+        if (disk_inode->ndi_flags & NFFS_INODE_FLAG_DELETED) {
+            /*
+             * Restore this inode even though deleted on disk
+             * so the additional restored blocks have a place to go
+             */
+            NFFS_LOG(DEBUG, "restoring deleted inode %x\n", disk_inode->ndi_id);
+            nffs_inode_setflags(inode_entry, NFFS_INODE_FLAG_DELETED);
+        }
+
+        /*
+         * inodes get replaced if they're dummy entries (i.e. allocated
+         * as place holders until the actual inode is restored), or this is
+         * a more recent version of the inode which supercedes the old.
+         */
+        rc = nffs_restore_inode_gets_replaced(inode_entry, disk_inode, &do_add);
         if (rc != 0) {
             goto err;
         }
 
-        if (do_add) {
-            if (inode_entry->nie_hash_entry.nhe_flash_loc !=
-                NFFS_FLASH_LOC_NONE) {
-
+        if (do_add) { /* replace in this case */
+            if (!nffs_inode_is_dummy(inode_entry)) {
+                /*
+                 * if it's not a dummy, read block from flash
+                 */
                 rc = nffs_inode_from_entry(&inode, inode_entry);
                 if (rc != 0) {
                     return rc;
                 }
+
+                /*
+                 * inode is known to be obsolete
+                 */
+                if (nffs_inode_getflags(inode_entry, 
+                                        NFFS_INODE_FLAG_OBSOLETE)) {
+                    nffs_inode_unsetflags(inode_entry,
+                                          NFFS_INODE_FLAG_OBSOLETE);
+                }
+
                 if (inode.ni_parent != NULL) {
                     nffs_inode_remove_child(&inode);
                 }
+
+                /*
+                 * If this is a delete record, subsequent inode and restore
+                 * records from flash may be ignored.
+                 * If the parent is NULL, this inode has been deleted. (old)
+                 * XXX if we could count on delete records for every inode,
+                 * we wouldn't need to check for the root directory looking
+                 * like a delete record because of it's parent ID.
+                 */
+                if (inode_entry->nie_hash_entry.nhe_id != NFFS_ID_ROOT_DIR) {
+                    if (disk_inode->ndi_flags & NFFS_INODE_FLAG_DELETED ||
+                        disk_inode->ndi_parent_id == NFFS_ID_NONE) {
+
+                        nffs_inode_setflags(inode_entry,
+                                            NFFS_INODE_FLAG_DELETED);
+                    }
+                }
+
+            } else {
+                /*
+                 * The existing inode entry was added as dummy.
+                 * The restore operation clears that state.
+                 */
+
+                /* If it's a directory, it was added as a parent to
+                 * one of it's children who were restored first.
+                 */
+                if (nffs_inode_getflags(inode_entry, 
+                                         NFFS_INODE_FLAG_DUMMYPARENT)) {
+                    assert(nffs_hash_id_is_dir(inode_entry->nie_hash_entry.nhe_id));
+                    nffs_inode_unsetflags(inode_entry, 
+                                         NFFS_INODE_FLAG_DUMMYPARENT);
+                }
+
+                /*
+                 * If it's a file, it was added to store a lastblock
+                 */
+                if (nffs_inode_getflags(inode_entry, 
+                                         NFFS_INODE_FLAG_DUMMYINOBLK)) {
+                    assert(nffs_hash_id_is_file(inode_entry->nie_hash_entry.nhe_id));
+                    nffs_inode_unsetflags(inode_entry, 
+                                         NFFS_INODE_FLAG_DUMMYINOBLK);
+                }
+
+                /*
+                 * Also, since it's a dummy, clear this flag too
+                 */
+                if (nffs_inode_getflags(inode_entry, NFFS_INODE_FLAG_DUMMY)) {
+                    nffs_inode_unsetflags(inode_entry, NFFS_INODE_FLAG_DUMMY);
+                }
             }
  
+            /*
+             * Update location to reference new location in flash
+             */
             inode_entry->nie_hash_entry.nhe_flash_loc =
-                nffs_flash_loc(area_idx, area_offset);
+                                    nffs_flash_loc(area_idx, area_offset);
         }
+        
     } else {
         inode_entry = nffs_inode_entry_alloc();
         if (inode_entry == NULL) {
@@ -523,19 +610,94 @@ nffs_restore_inode(const struct nffs_disk_inode *disk_inode, uint8_t area_idx,
 
         inode_entry->nie_hash_entry.nhe_id = disk_inode->ndi_id;
         inode_entry->nie_hash_entry.nhe_flash_loc =
-            nffs_flash_loc(area_idx, area_offset);
+                              nffs_flash_loc(area_idx, area_offset);
+        inode_entry->nie_last_block_entry = NULL; /* for now */
 
         nffs_hash_insert(&inode_entry->nie_hash_entry);
     }
 
+    /*
+     * inode object has been restored and the entry is in the hash
+     * Check whether the lastblock and parent have also been restored
+     * and link up or allocate dummy entries as appropriate.
+     */
     if (do_add) {
         inode_entry->nie_refcnt = 1;
 
+        if (disk_inode->ndi_flags & NFFS_INODE_FLAG_DELETED) {
+            /*
+             * Restore this inode even though deleted on disk
+             * so the additional restored blocks have a place to go
+             */
+            NFFS_LOG(DEBUG, "restoring deleted inode %x\n", disk_inode->ndi_id);
+            nffs_inode_setflags(inode_entry, NFFS_INODE_FLAG_DELETED);
+        }
+
+        /*
+         * Inode has a lastblock on disk.
+         * Add reference to last block entry if in hash table
+         * otherwise add a dummy block entry for later update
+         */
+        if (disk_inode->ndi_lastblock_id != NFFS_ID_NONE &&
+                nffs_hash_id_is_file(inode_entry->nie_hash_entry.nhe_id)) {
+            lastblock_entry =
+              nffs_hash_find_block(disk_inode->ndi_lastblock_id);
+
+            /*
+             * Lastblock has already been restored.
+             */
+            if (lastblock_entry != NULL) {
+                if (lastblock_entry->nhe_id == disk_inode->ndi_lastblock_id) {
+                    inode_entry->nie_last_block_entry = lastblock_entry;
+                    /*
+                     * This flag should have been turned unset
+                     * when the block was restored.
+                     */
+                    assert(!nffs_inode_getflags(inode_entry,
+                                               NFFS_INODE_FLAG_DUMMYLSTBLK));
+                }
+
+            } else {
+                /*
+                 * Insert a temporary reference to a 'dummy' block entry
+                 * When block is restored, it will update this dummy and
+                 * the entry of this inode is updated to flash location
+                 */
+                rc = nffs_block_entry_reserve(&lastblock_entry);
+                if (lastblock_entry == NULL) {
+                    rc = FS_ENOMEM;
+                    goto err;
+                }
+
+                lastblock_entry->nhe_id = disk_inode->ndi_lastblock_id;
+                lastblock_entry->nhe_flash_loc = NFFS_FLASH_LOC_NONE;
+                inode_entry->nie_last_block_entry = lastblock_entry;
+                nffs_inode_setflags(inode_entry, NFFS_INODE_FLAG_DUMMYLSTBLK);
+                nffs_hash_insert(lastblock_entry);
+
+                if (lastblock_entry->nhe_id >= nffs_hash_next_block_id) {
+                    nffs_hash_next_block_id = lastblock_entry->nhe_id + 1;
+                }
+            }
+        }
+
         if (disk_inode->ndi_parent_id != NFFS_ID_NONE) {
+            
             parent = nffs_hash_find_inode(disk_inode->ndi_parent_id);
+            /*
+             * The parent directory for this inode hasn't been restored yet.
+             * Add a dummy directory so it can be added as a child.
+             * When the parent inode is restored, it's hash entry will be
+             * updated with the flash location.
+             */
             if (parent == NULL) {
                 rc = nffs_restore_dummy_inode(disk_inode->ndi_parent_id,
                                              &parent);
+                /*
+                 * Set the dummy parent flag in the new parent.
+                 * It's turned off above when restored.
+                 */
+                nffs_inode_setflags(parent, NFFS_INODE_FLAG_DUMMYPARENT);
                 if (rc != 0) {
                     goto err;
                 }
@@ -547,9 +709,9 @@ nffs_restore_inode(const struct nffs_disk_inode *disk_inode, uint8_t area_idx,
             }
         } 
 
-
         if (inode_entry->nie_hash_entry.nhe_id == NFFS_ID_ROOT_DIR) {
             nffs_root_dir = inode_entry;
+            nffs_inode_setflags(nffs_root_dir, NFFS_INODE_FLAG_INTREE);
         }
     }
 
@@ -599,16 +761,22 @@ nffs_restore_block_gets_replaced(const struct nffs_block *old_block,
 {
     assert(old_block->nb_hash_entry->nhe_id == disk_block->ndb_id);
 
-    if (old_block->nb_seq < disk_block->ndb_seq) {
+    if (nffs_block_is_dummy(old_block->nb_hash_entry)) {
+        assert(0);
         *out_should_replace = 1;
         return 0;
     }
 
+    if (old_block->nb_seq < disk_block->ndb_seq) {
+        *out_should_replace = 2;
+        return 0;
+    }
+
     if (old_block->nb_seq == disk_block->ndb_seq) {
-        /* This is a duplicate of an previously-read inode.  This should never
+        /* This is a duplicate of an previously-read block.  This should never
          * happen.
          */
-        return FS_ECORRUPT;
+        return FS_EEXIST;
     }
 
     *out_should_replace = 0;
@@ -648,12 +816,39 @@ nffs_restore_block(const struct nffs_disk_block *disk_block, uint8_t area_idx,
 
     entry = nffs_hash_find_block(disk_block->ndb_id);
     if (entry != NULL) {
+
         rc = nffs_block_from_hash_entry_no_ptrs(&block, entry);
-        if (rc != 0) {
+        if (rc != 0 && rc != FS_ENOENT) {
             goto err;
         }
 
-        rc = nffs_restore_block_gets_replaced(&block, disk_block, &do_replace);
+        /*
+         * If the old block reference is for a 'dummy' block, it was added
+         * because the owning inode's lastblock was not yet restored.
+         * Update the block hash entry and inode to reference the entry.
+         */
+        if (nffs_block_is_dummy(entry)) {
+
+            assert(entry->nhe_id == disk_block->ndb_id);
+
+            /*
+             * Entry is no longer dummy as it references the correct location
+             */
+            entry->nhe_flash_loc = nffs_flash_loc(area_idx, area_offset);
+
+            inode_entry = nffs_hash_find_inode(disk_block->ndb_inode_id);
+
+            /*
+             * Turn off flags in previously restored inode recording the
+             * allocation of a dummy block
+             */
+            if (inode_entry) {
+                nffs_inode_unsetflags(inode_entry, NFFS_INODE_FLAG_DUMMYLSTBLK);
+            }
+        }
+
+        rc = nffs_restore_block_gets_replaced(&block, disk_block,
+                                              &do_replace);
         if (rc != 0) {
             goto err;
         }
@@ -663,24 +858,28 @@ nffs_restore_block(const struct nffs_disk_block *disk_block, uint8_t area_idx,
             return 0;
         }
 
-        nffs_block_delete_from_ram(entry);
-    }
+        /*
+         * update the existing hash entry to reference the new flash location
+         */
+        entry->nhe_flash_loc = nffs_flash_loc(area_idx, area_offset);
 
-    entry = nffs_block_entry_alloc();
-    if (entry == NULL) {
-        rc = FS_ENOMEM;
-        goto err;
-    }
-    new_block = 1;
-    entry->nhe_id = disk_block->ndb_id;
-    entry->nhe_flash_loc = nffs_flash_loc(area_idx, area_offset);
+    } else {
+        entry = nffs_block_entry_alloc();
+        if (entry == NULL) {
+            rc = FS_ENOMEM;
+            goto err;
+        }
+        new_block = 1;
+        entry->nhe_id = disk_block->ndb_id;
+        entry->nhe_flash_loc = nffs_flash_loc(area_idx, area_offset);
 
-    /* The block is ready to be inserted into the hash. */
+        /* The block is ready to be inserted into the hash. */
 
-    nffs_hash_insert(entry);
+        nffs_hash_insert(entry);
 
-    if (disk_block->ndb_id >= nffs_hash_next_block_id) {
-        nffs_hash_next_block_id = disk_block->ndb_id + 1;
+        if (disk_block->ndb_id >= nffs_hash_next_block_id) {
+            nffs_hash_next_block_id = disk_block->ndb_id + 1;
+        }
     }
 
     /* Make sure the maximum block data size is not set lower than the size of
@@ -696,14 +895,33 @@ nffs_restore_block(const struct nffs_disk_block *disk_block, uint8_t area_idx,
              disk_block->ndb_data_len);
 
     inode_entry = nffs_hash_find_inode(disk_block->ndb_inode_id);
+
     if (inode_entry == NULL) {
+        /*
+         * Owning inode not yet restored.
+         * Allocate a dummy inode which temporarily owns this block.
+         * It is not yet linked to a parent.
+         */
         rc = nffs_restore_dummy_inode(disk_block->ndb_inode_id, &inode_entry);
         if (rc != 0) {
             goto err;
         }
+        /*
+         * Record that this inode was created because a block was restored
+         * before the inode
+         */
+        nffs_inode_setflags(inode_entry, NFFS_INODE_FLAG_DUMMYINOBLK);
+        inode_entry->nie_last_block_entry = entry;
+    } else {
+        if (nffs_inode_getflags(inode_entry, NFFS_INODE_FLAG_DELETED)) {
+            /*
+             * don't restore blocks for deleted inodes
+             */
+            rc = FS_ENOENT;
+            goto err;
+        }
     }
 
-
     return 0;
 
 err:
@@ -764,24 +982,24 @@ nffs_restore_disk_object(int area_idx, uint32_t area_offset,
     int rc;
 
     rc = nffs_flash_read(area_idx, area_offset,
-						 &out_disk_object->ndo_un_obj,
-						 sizeof(out_disk_object->ndo_un_obj));
+                         &out_disk_object->ndo_un_obj,
+                         sizeof(out_disk_object->ndo_un_obj));
     if (rc != 0) {
         return rc;
     }
 
-	if (nffs_hash_id_is_inode(out_disk_object->ndo_disk_inode.ndi_id)) {
+    if (nffs_hash_id_is_inode(out_disk_object->ndo_disk_inode.ndi_id)) {
         out_disk_object->ndo_type = NFFS_OBJECT_TYPE_INODE;
 
-	} else if (nffs_hash_id_is_block(out_disk_object->ndo_disk_block.ndb_id)) {
+    } else if (nffs_hash_id_is_block(out_disk_object->ndo_disk_block.ndb_id)) {
         out_disk_object->ndo_type = NFFS_OBJECT_TYPE_BLOCK;
 
-	} else if (out_disk_object->ndo_disk_block.ndb_id == NFFS_ID_NONE) {
+    } else if (out_disk_object->ndo_disk_block.ndb_id == NFFS_ID_NONE) {
         return FS_EEMPTY;
 
-	} else {
-		return FS_ECORRUPT;
-	}
+    } else {
+        return FS_ECORRUPT;
+    }
 
     out_disk_object->ndo_area_idx = area_idx;
     out_disk_object->ndo_offset = area_offset;
@@ -834,13 +1052,28 @@ nffs_restore_area_contents(int area_idx)
         rc = nffs_restore_disk_object(area_idx, area->na_cur,  &disk_object);
         switch (rc) {
         case 0:
+
             /* Valid object; restore it into the RAM representation. */
-            nffs_restore_object(&disk_object);
-            area->na_cur += nffs_restore_disk_object_size(&disk_object);
+            rc = nffs_restore_object(&disk_object);
+
+            /*
+             * If the restore fails the CRC check, the object length field
+             * can't be trusted so just start looking for the next valid
+             * object in the flash area.
+             * XXX Deal with file system corruption
+             */
+            if (rc == FS_ECORRUPT) {
+                area->na_cur++;
+            } else {
+                area->na_cur += nffs_restore_disk_object_size(&disk_object);
+            }
             break;
 
         case FS_ECORRUPT:
-            /* Invalid object; keep scanning for a valid magic number. */
+            /*
+             * Invalid object; keep scanning for a valid object ID and CRC
+             * Can nffs_restore_disk_object return FS_ECORRUPT? XXX
+             */
             area->na_cur++;
             break;
 
@@ -941,7 +1174,7 @@ nffs_restore_corrupt_scratch(void)
                     }
                 } else {
                     inode_entry = (struct nffs_inode_entry *)entry;
-                    inode_entry->nie_refcnt = 0;
+                    nffs_inode_setflags(inode_entry, NFFS_INODE_FLAG_OBSOLETE);
                 }
             }
 
@@ -985,7 +1218,7 @@ nffs_log_contents(void)
     NFFS_HASH_FOREACH(entry, i, next) {
         if (nffs_hash_id_is_block(entry->nhe_id)) {
             rc = nffs_block_from_hash_entry(&block, entry);
-            assert(rc == 0);
+            assert(rc == 0 || rc == FS_ENOENT);
             NFFS_LOG(DEBUG, "block; id=%u inode_id=", entry->nhe_id);
             if (block.nb_inode_entry == NULL) {
                 NFFS_LOG(DEBUG, "null ");
@@ -1005,7 +1238,19 @@ nffs_log_contents(void)
         } else {
             inode_entry = (void *)entry;
             rc = nffs_inode_from_entry(&inode, inode_entry);
-            assert(rc == 0);
+            if (rc == FS_ENOENT) {
+                NFFS_LOG(DEBUG, "DUMMY file; id=%x ref=%d block_id=",
+                         (unsigned int)entry->nhe_id, inode_entry->nie_refcnt);
+                if (inode_entry->nie_last_block_entry == NULL) {
+                    NFFS_LOG(DEBUG, "null");
+                } else {
+                    NFFS_LOG(DEBUG, "%x",
+                             (unsigned int)inode_entry->nie_last_block_entry->nhe_id);
+                }
+            } else if (rc != 0) {
+                continue;
+            }
+            /*assert(rc == 0);*/
 
             if (nffs_hash_id_is_file(entry->nhe_id)) {
                 NFFS_LOG(DEBUG, "file; id=%u name=%.3s block_id=",
@@ -1055,6 +1300,7 @@ nffs_restore_full(const struct nffs_area_desc *area_descs)
         return rc;
     }
     nffs_restore_largest_block_data_len = 0;
+    nffs_current_area_descs = (struct nffs_area_desc*) area_descs;
 
     /* Read each area from flash. */
     for (i = 0; area_descs[i].nad_length != 0; i++) {
@@ -1071,6 +1317,7 @@ nffs_restore_full(const struct nffs_area_desc *area_descs)
             use_area = 1;
             break;
 
+        case FS_EUNEXP:    /* not formatted with current on-disk NFFS format */
         case FS_ECORRUPT:
             use_area = 0;
             break;
@@ -1147,9 +1394,6 @@ nffs_restore_full(const struct nffs_area_desc *area_descs)
         goto err;
     }
 
-    /* Find the last block in each file inode. */
-    nffs_restore_find_file_ends();
-
     /* Delete from RAM any objects that were invalidated when subsequent areas
      * were restored.
      */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f9ef5686/fs/nffs/src/nffs_write.c
----------------------------------------------------------------------
diff --git a/fs/nffs/src/nffs_write.c b/fs/nffs/src/nffs_write.c
index b888630..dd9fb0e 100644
--- a/fs/nffs/src/nffs_write.c
+++ b/fs/nffs/src/nffs_write.c
@@ -247,6 +247,18 @@ nffs_write_append(struct nffs_cache_inode *cache_inode, const void *data,
 
     inode_entry->nie_last_block_entry = entry;
 
+    /*
+     * When a new block is appended to a file, the inode must be written
+     * out to flash so the last block id is is stored persistently.
+     * Need to be written atomically with writing the block out so filesystem
+     * remains consistent. nffs_lock is held in nffs_write().
+     * The inode will not be updated if it's been unlinked on disk and this
+     * is signaled by setting the hash entry's flash location to NONE
+     */
+    if (inode_entry->nie_hash_entry.nhe_flash_loc != NFFS_FLASH_LOC_NONE) {
+        rc = nffs_inode_update(inode_entry);
+    }
+
     /* Update cached inode with the new file size. */
     cache_inode->nci_file_size += len;
 


[12/50] [abbrv] incubator-mynewt-core git commit: BLE Host - ble_att_svr_read_local()

Posted by cc...@apache.org.
BLE Host - ble_att_svr_read_local()

Also add corresponding unit tests.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/e942cec7
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/e942cec7
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/e942cec7

Branch: refs/heads/master
Commit: e942cec79c9774b7da8ec29f88f2ca9540f5d2f6
Parents: 9a8d36e
Author: Christopher Collins <cc...@apache.org>
Authored: Wed Jun 22 11:23:55 2016 -0700
Committer: Christopher Collins <cc...@apache.org>
Committed: Wed Jun 22 11:23:55 2016 -0700

----------------------------------------------------------------------
 net/nimble/host/include/host/ble_att.h      |   2 +
 net/nimble/host/src/ble_att_svr.c           |  29 +++++-
 net/nimble/host/src/test/ble_att_svr_test.c | 113 ++++++++++++++++++++++-
 3 files changed, 139 insertions(+), 5 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/e942cec7/net/nimble/host/include/host/ble_att.h
----------------------------------------------------------------------
diff --git a/net/nimble/host/include/host/ble_att.h b/net/nimble/host/include/host/ble_att.h
index 6f6a7cc..53b4e19 100644
--- a/net/nimble/host/include/host/ble_att.h
+++ b/net/nimble/host/include/host/ble_att.h
@@ -119,6 +119,8 @@ typedef int ble_att_svr_notify_fn(uint16_t conn_handle, uint16_t attr_handle,
                                   uint8_t *attr_val, uint16_t attr_len,
                                   void *arg);
 
+int ble_att_svr_read_local(uint16_t attr_handle, void **out_data,
+                           uint16_t *out_attr_len);
 int ble_att_svr_write_local(uint16_t attr_handle, void *data,
                             uint16_t data_len);
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/e942cec7/net/nimble/host/src/ble_att_svr.c
----------------------------------------------------------------------
diff --git a/net/nimble/host/src/ble_att_svr.c b/net/nimble/host/src/ble_att_svr.c
index 9315c7e..1017fc8 100644
--- a/net/nimble/host/src/ble_att_svr.c
+++ b/net/nimble/host/src/ble_att_svr.c
@@ -348,6 +348,27 @@ ble_att_svr_read_handle(uint16_t conn_handle, uint16_t attr_handle,
     return 0;
 }
 
+int
+ble_att_svr_read_local(uint16_t attr_handle, void **out_data,
+                       uint16_t *out_attr_len)
+{
+    struct ble_att_svr_access_ctxt ctxt;
+    int rc;
+
+    ctxt.offset = 0;
+
+    rc = ble_att_svr_read_handle(BLE_HS_CONN_HANDLE_NONE, attr_handle, &ctxt,
+                                 NULL);
+    if (rc != 0) {
+        return rc;
+    }
+
+    *out_attr_len = ctxt.data_len;
+    *out_data = ctxt.attr_data;
+
+    return 0;
+}
+
 static int
 ble_att_svr_write(uint16_t conn_handle, struct ble_att_svr_entry *entry,
                   struct ble_att_svr_access_ctxt *ctxt, uint8_t *out_att_err)
@@ -357,8 +378,12 @@ ble_att_svr_write(uint16_t conn_handle, struct ble_att_svr_entry *entry,
 
     BLE_HS_DBG_ASSERT(!ble_hs_locked_by_cur_task());
 
-    if (conn_handle != BLE_HS_CONN_HANDLE_NONE &&
-        !(entry->ha_flags & BLE_ATT_F_WRITE)) {
+    if (conn_handle != BLE_HS_CONN_HANDLE_NONE) {
+        if (!(entry->ha_flags & BLE_ATT_F_WRITE)) {
+            att_err = BLE_ATT_ERR_WRITE_NOT_PERMITTED;
+            rc = BLE_HS_ENOTSUP;
+            goto err;
+        }
 
         rc = ble_att_svr_check_security(conn_handle, 0, entry, &att_err);
         if (rc != 0) {

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/e942cec7/net/nimble/host/src/test/ble_att_svr_test.c
----------------------------------------------------------------------
diff --git a/net/nimble/host/src/test/ble_att_svr_test.c b/net/nimble/host/src/test/ble_att_svr_test.c
index 1f54c54..e6f8bdb 100644
--- a/net/nimble/host/src/test/ble_att_svr_test.c
+++ b/net/nimble/host/src/test/ble_att_svr_test.c
@@ -6,7 +6,7 @@
  * to you 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,
@@ -1021,9 +1021,13 @@ TEST_CASE(ble_att_svr_test_mtu)
 TEST_CASE(ble_att_svr_test_read)
 {
     struct ble_att_read_req req;
+    struct ble_hs_conn *conn;
     uint16_t conn_handle;
+    uint16_t attr_len;
     uint8_t buf[BLE_ATT_READ_REQ_SZ];
+    uint8_t uuid_sec[16] = {1};
     uint8_t uuid[16] = {0};
+    void *attr_data;
     int rc;
 
     conn_handle = ble_att_svr_test_misc_init(0);
@@ -1066,6 +1070,44 @@ TEST_CASE(ble_att_svr_test_read)
     TEST_ASSERT(rc == 0);
     ble_att_svr_test_misc_verify_tx_read_rsp(ble_att_svr_test_attr_r_1,
                                              BLE_ATT_MTU_DFLT - 1);
+
+    /*** Read requires encryption. */
+    /* Insufficient authentication. */
+    rc = ble_att_svr_register(uuid_sec, BLE_ATT_F_READ | BLE_ATT_F_READ_ENC,
+                              &req.barq_handle,
+                              ble_att_svr_test_misc_attr_fn_r_1, NULL);
+    TEST_ASSERT(rc == 0);
+
+    ble_att_read_req_write(buf, sizeof buf, &req);
+
+    rc = ble_hs_test_util_l2cap_rx_payload_flat(conn_handle, BLE_L2CAP_CID_ATT,
+                                                buf, sizeof buf);
+    TEST_ASSERT(rc == BLE_HS_ATT_ERR(BLE_ATT_ERR_INSUFFICIENT_AUTHENT));
+    ble_att_svr_test_misc_verify_tx_err_rsp(BLE_ATT_OP_READ_REQ,
+                                            req.barq_handle,
+                                            BLE_ATT_ERR_INSUFFICIENT_AUTHENT);
+
+    /* Security check bypassed for local reads. */
+    rc = ble_att_svr_read_local(req.barq_handle, &attr_data, &attr_len);
+    TEST_ASSERT(rc == 0);
+    TEST_ASSERT(attr_len == ble_att_svr_test_attr_r_1_len);
+    TEST_ASSERT(attr_data == ble_att_svr_test_attr_r_1);
+
+    /* Ensure no response got sent. */
+    ble_hs_test_util_tx_all();
+    TEST_ASSERT(ble_hs_test_util_prev_tx_dequeue() == NULL);
+
+    /* Encrypt link; success. */
+    ble_hs_lock();
+    conn = ble_hs_conn_find(conn_handle);
+    conn->bhc_sec_state.encrypted = 1;
+    ble_hs_unlock();
+
+    rc = ble_hs_test_util_l2cap_rx_payload_flat(conn_handle, BLE_L2CAP_CID_ATT,
+                                                buf, sizeof buf);
+    TEST_ASSERT(rc == 0);
+    ble_att_svr_test_misc_verify_tx_read_rsp(ble_att_svr_test_attr_r_1,
+                                             BLE_ATT_MTU_DFLT - 1);
 }
 
 TEST_CASE(ble_att_svr_test_read_blob)
@@ -1210,9 +1252,12 @@ TEST_CASE(ble_att_svr_test_read_mult)
 TEST_CASE(ble_att_svr_test_write)
 {
     struct ble_att_write_req req;
+    struct ble_hs_conn *conn;
     uint16_t conn_handle;
     uint8_t buf[BLE_ATT_WRITE_REQ_BASE_SZ + 8];
-    uint8_t uuid[16] = {0};
+    uint8_t uuid_sec[16] = {2};
+    uint8_t uuid_rw[16] = {0};
+    uint8_t uuid_r[16] = {1};
     int rc;
 
     conn_handle = ble_att_svr_test_misc_init(0);
@@ -1228,8 +1273,49 @@ TEST_CASE(ble_att_svr_test_write)
     ble_att_svr_test_misc_verify_tx_err_rsp(
         BLE_ATT_OP_WRITE_REQ, 0, BLE_ATT_ERR_INVALID_HANDLE);
 
+    /*** Write not permitted if non-local. */
+    /* Non-local write (fail). */
+    rc = ble_att_svr_register(uuid_r, BLE_ATT_F_READ, &req.bawq_handle,
+                              ble_att_svr_test_misc_attr_fn_w_1, NULL);
+    TEST_ASSERT(rc == 0);
+
+    ble_att_write_req_write(buf, sizeof buf, &req);
+    memcpy(buf + BLE_ATT_WRITE_REQ_BASE_SZ,
+           ((uint8_t[]){0,1,2,3,4,5,6,7}), 8);
+
+    rc = ble_hs_test_util_l2cap_rx_payload_flat(conn_handle, BLE_L2CAP_CID_ATT,
+                                                buf, sizeof buf);
+    TEST_ASSERT(rc == BLE_HS_ENOTSUP);
+    ble_att_svr_test_misc_verify_tx_err_rsp(BLE_ATT_OP_WRITE_REQ,
+                                            req.bawq_handle,
+                                            BLE_ATT_ERR_WRITE_NOT_PERMITTED);
+
+    /* Local write (success). */
+    rc = ble_att_svr_write_local(req.bawq_handle, buf, sizeof buf);
+    TEST_ASSERT(rc == 0);
+
+    /* Ensure no response got sent. */
+    ble_hs_test_util_tx_all();
+    TEST_ASSERT(ble_hs_test_util_prev_tx_dequeue() == NULL);
+
     /*** Successful write. */
-    rc = ble_att_svr_register(uuid, HA_FLAG_PERM_RW, &req.bawq_handle,
+    rc = ble_att_svr_register(uuid_rw, HA_FLAG_PERM_RW, &req.bawq_handle,
+                              ble_att_svr_test_misc_attr_fn_w_1, NULL);
+    TEST_ASSERT(rc == 0);
+
+    ble_att_write_req_write(buf, sizeof buf, &req);
+    memcpy(buf + BLE_ATT_WRITE_REQ_BASE_SZ,
+           ((uint8_t[]){0,1,2,3,4,5,6,7}), 8);
+
+    rc = ble_hs_test_util_l2cap_rx_payload_flat(conn_handle, BLE_L2CAP_CID_ATT,
+                                                buf, sizeof buf);
+    TEST_ASSERT(rc == 0);
+    ble_att_svr_test_misc_verify_tx_write_rsp();
+
+    /*** Write requires encryption. */
+    /* Insufficient authentication. */
+    rc = ble_att_svr_register(uuid_sec, BLE_ATT_F_WRITE | BLE_ATT_F_WRITE_ENC,
+                              &req.bawq_handle,
                               ble_att_svr_test_misc_attr_fn_w_1, NULL);
     TEST_ASSERT(rc == 0);
 
@@ -1239,6 +1325,27 @@ TEST_CASE(ble_att_svr_test_write)
 
     rc = ble_hs_test_util_l2cap_rx_payload_flat(conn_handle, BLE_L2CAP_CID_ATT,
                                                 buf, sizeof buf);
+    TEST_ASSERT(rc == BLE_HS_ATT_ERR(BLE_ATT_ERR_INSUFFICIENT_AUTHENT));
+    ble_att_svr_test_misc_verify_tx_err_rsp(BLE_ATT_OP_WRITE_REQ,
+                                            req.bawq_handle,
+                                            BLE_ATT_ERR_INSUFFICIENT_AUTHENT);
+
+    /* Security check bypassed for local writes. */
+    rc = ble_att_svr_write_local(req.bawq_handle, buf, sizeof buf);
+    TEST_ASSERT(rc == 0);
+
+    /* Ensure no response got sent. */
+    ble_hs_test_util_tx_all();
+    TEST_ASSERT(ble_hs_test_util_prev_tx_dequeue() == NULL);
+
+    /* Encrypt link; success. */
+    ble_hs_lock();
+    conn = ble_hs_conn_find(conn_handle);
+    conn->bhc_sec_state.encrypted = 1;
+    ble_hs_unlock();
+
+    rc = ble_hs_test_util_l2cap_rx_payload_flat(conn_handle, BLE_L2CAP_CID_ATT,
+                                                buf, sizeof buf);
     TEST_ASSERT(rc == 0);
     ble_att_svr_test_misc_verify_tx_write_rsp();
 }


[37/50] [abbrv] incubator-mynewt-core git commit: bootutil; don't stop swapping images if writes to update status file start failing.

Posted by cc...@apache.org.
bootutil; don't stop swapping images if writes to update status
file start failing.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/06788912
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/06788912
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/06788912

Branch: refs/heads/master
Commit: 0678891276a4bc4b8900dd9321ada2c2afcbec09
Parents: 251ba7a
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Thu Jun 30 13:59:31 2016 -0700
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Thu Jun 30 14:00:29 2016 -0700

----------------------------------------------------------------------
 libs/bootutil/src/loader.c | 15 +++------------
 1 file changed, 3 insertions(+), 12 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/06788912/libs/bootutil/src/loader.c
----------------------------------------------------------------------
diff --git a/libs/bootutil/src/loader.c b/libs/bootutil/src/loader.c
index f155779..bd7fbd8 100644
--- a/libs/bootutil/src/loader.c
+++ b/libs/bootutil/src/loader.c
@@ -284,10 +284,7 @@ boot_swap_areas(int idx, uint32_t sz)
         }
 
         boot_state.state = BOOT_PERSIST(idx, 1);
-        rc = boot_write_status(&boot_state);
-        if (rc != 0) {
-            return rc;
-        }
+        (void)boot_write_status(&boot_state);
         state = 1;
     }
     if (state == 1) {
@@ -302,10 +299,7 @@ boot_swap_areas(int idx, uint32_t sz)
         }
 
         boot_state.state = BOOT_PERSIST(idx, 2);
-        rc = boot_write_status(&boot_state);
-        if (rc != 0) {
-            return rc;
-        }
+        (void)boot_write_status(&boot_state);
         state = 2;
     }
     if (state == 2) {
@@ -320,10 +314,7 @@ boot_swap_areas(int idx, uint32_t sz)
         }
 
         boot_state.state = BOOT_PERSIST(idx + 1, 0);
-        rc = boot_write_status(&boot_state);
-        if (rc != 0) {
-            return rc;
-        }
+        (void)boot_write_status(&boot_state);
         state = 3;
     }
     return 0;


[23/50] [abbrv] incubator-mynewt-core git commit: boot_serial; fix test code.

Posted by cc...@apache.org.
boot_serial; fix test code.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/7dbc0d04
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/7dbc0d04
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/7dbc0d04

Branch: refs/heads/master
Commit: 7dbc0d0463db2db6c727e3a49fb1665dbbaa7a68
Parents: 6b829a0
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Fri Jun 24 17:21:54 2016 -0700
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Fri Jun 24 17:21:54 2016 -0700

----------------------------------------------------------------------
 libs/boot_serial/pkg.yml              | 1 +
 libs/boot_serial/src/test/boot_test.c | 8 +++-----
 2 files changed, 4 insertions(+), 5 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/7dbc0d04/libs/boot_serial/pkg.yml
----------------------------------------------------------------------
diff --git a/libs/boot_serial/pkg.yml b/libs/boot_serial/pkg.yml
index 0b66bb6..4a98343 100644
--- a/libs/boot_serial/pkg.yml
+++ b/libs/boot_serial/pkg.yml
@@ -29,6 +29,7 @@ pkg.deps:
     - hw/hal
     - libs/os
     - libs/testutil
+    - libs/bootutil
     - libs/util
 pkg.req_apis:
     - console

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/7dbc0d04/libs/boot_serial/src/test/boot_test.c
----------------------------------------------------------------------
diff --git a/libs/boot_serial/src/test/boot_test.c b/libs/boot_serial/src/test/boot_test.c
index 3859b46..e11a649 100644
--- a/libs/boot_serial/src/test/boot_test.c
+++ b/libs/boot_serial/src/test/boot_test.c
@@ -26,8 +26,6 @@
 #include <util/base64.h>
 #include <util/crc16.h>
 #include <testutil/testutil.h>
-#include <newtmgr/newtmgr.h>
-#include <imgmgr/imgmgr.h>
 #include <hal/hal_flash.h>
 #include <hal/flash_map.h>
 
@@ -101,7 +99,7 @@ TEST_CASE(boot_serial_empty_img_msg)
     hdr = (struct nmgr_hdr *)buf;
     memset(hdr, 0, sizeof(*hdr));
     hdr->nh_op = NMGR_OP_WRITE;
-    hdr->nh_group = NMGR_GROUP_ID_IMAGE;
+    hdr->nh_group = htons(NMGR_GROUP_ID_IMAGE);
     hdr->nh_id = IMGMGR_NMGR_OP_UPLOAD;
     hdr->nh_len = htons(2);
     strcpy((char *)(hdr + 1), "{}");
@@ -126,7 +124,7 @@ TEST_CASE(boot_serial_img_msg)
     hdr = (struct nmgr_hdr *)buf;
     memset(hdr, 0, sizeof(*hdr));
     hdr->nh_op = NMGR_OP_WRITE;
-    hdr->nh_group = NMGR_GROUP_ID_IMAGE;
+    hdr->nh_group = htons(NMGR_GROUP_ID_IMAGE);
     hdr->nh_id = IMGMGR_NMGR_OP_UPLOAD;
 
     len = sprintf((char *)(hdr + 1), "{\"off\":0,\"len\":16,\"data\":\"%s\"}",
@@ -171,7 +169,7 @@ TEST_CASE(boot_serial_upload_bigger_image)
         hdr = (struct nmgr_hdr *)buf;
         memset(hdr, 0, sizeof(*hdr));
         hdr->nh_op = NMGR_OP_WRITE;
-        hdr->nh_group = NMGR_GROUP_ID_IMAGE;
+        hdr->nh_group = htons(NMGR_GROUP_ID_IMAGE);
         hdr->nh_id = IMGMGR_NMGR_OP_UPLOAD;
 
         if (off) {


[06/50] [abbrv] incubator-mynewt-core git commit: BLE Host - Remove obsolete ble_hs_thread_safe() fn

Posted by cc...@apache.org.
BLE Host - Remove obsolete ble_hs_thread_safe() fn


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/eacea950
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/eacea950
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/eacea950

Branch: refs/heads/master
Commit: eacea950a9226533f0a6bd9138ae0986ffdad7dc
Parents: 39660c0
Author: Christopher Collins <cc...@apache.org>
Authored: Mon Jun 20 20:34:49 2016 -0700
Committer: Christopher Collins <cc...@apache.org>
Committed: Mon Jun 20 20:34:49 2016 -0700

----------------------------------------------------------------------
 net/nimble/host/src/ble_hs.c        |  6 ------
 net/nimble/host/src/ble_hs_conn.c   | 12 ++++++------
 net/nimble/host/src/ble_hs_priv.h   |  1 -
 net/nimble/host/src/ble_l2cap_sig.c |  2 +-
 net/nimble/host/src/ble_sm.c        |  2 +-
 net/nimble/host/src/ble_sm_cmd.c    |  2 +-
 6 files changed, 9 insertions(+), 16 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/eacea950/net/nimble/host/src/ble_hs.c
----------------------------------------------------------------------
diff --git a/net/nimble/host/src/ble_hs.c b/net/nimble/host/src/ble_hs.c
index 22797e3..72e6ccf 100644
--- a/net/nimble/host/src/ble_hs.c
+++ b/net/nimble/host/src/ble_hs.c
@@ -104,12 +104,6 @@ ble_hs_locked_by_cur_task(void)
     return owner != NULL && owner == os_sched_get_current_task();
 }
 
-int
-ble_hs_thread_safe(void)
-{
-    return ble_hs_locked_by_cur_task();
-}
-
 /**
  * Indicates whether the host's parent task is currently running.
  */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/eacea950/net/nimble/host/src/ble_hs_conn.c
----------------------------------------------------------------------
diff --git a/net/nimble/host/src/ble_hs_conn.c b/net/nimble/host/src/ble_hs_conn.c
index ff68bc2..a4b0f16 100644
--- a/net/nimble/host/src/ble_hs_conn.c
+++ b/net/nimble/host/src/ble_hs_conn.c
@@ -208,7 +208,7 @@ ble_hs_conn_insert(struct ble_hs_conn *conn)
     return;
 #endif
 
-    BLE_HS_DBG_ASSERT(ble_hs_thread_safe());
+    BLE_HS_DBG_ASSERT(ble_hs_locked_by_cur_task());
 
     BLE_HS_DBG_ASSERT_EVAL(ble_hs_conn_find(conn->bhc_handle) == NULL);
     SLIST_INSERT_HEAD(&ble_hs_conns, conn, bhc_next);
@@ -221,7 +221,7 @@ ble_hs_conn_remove(struct ble_hs_conn *conn)
     return;
 #endif
 
-    BLE_HS_DBG_ASSERT(ble_hs_thread_safe());
+    BLE_HS_DBG_ASSERT(ble_hs_locked_by_cur_task());
 
     SLIST_REMOVE(&ble_hs_conns, conn, ble_hs_conn, bhc_next);
 }
@@ -235,7 +235,7 @@ ble_hs_conn_find(uint16_t conn_handle)
 
     struct ble_hs_conn *conn;
 
-    BLE_HS_DBG_ASSERT(ble_hs_thread_safe());
+    BLE_HS_DBG_ASSERT(ble_hs_locked_by_cur_task());
 
     SLIST_FOREACH(conn, &ble_hs_conns, bhc_next) {
         if (conn->bhc_handle == conn_handle) {
@@ -255,7 +255,7 @@ ble_hs_conn_find_by_addr(uint8_t addr_type, uint8_t *addr)
 
     struct ble_hs_conn *conn;
 
-    BLE_HS_DBG_ASSERT(ble_hs_thread_safe());
+    BLE_HS_DBG_ASSERT(ble_hs_locked_by_cur_task());
 
     SLIST_FOREACH(conn, &ble_hs_conns, bhc_next) {
         if (conn->bhc_addr_type == addr_type &&
@@ -278,7 +278,7 @@ ble_hs_conn_find_by_idx(int idx)
     struct ble_hs_conn *conn;
     int i;
 
-    BLE_HS_DBG_ASSERT(ble_hs_thread_safe());
+    BLE_HS_DBG_ASSERT(ble_hs_locked_by_cur_task());
 
     i = 0;
     SLIST_FOREACH(conn, &ble_hs_conns, bhc_next) {
@@ -311,7 +311,7 @@ ble_hs_conn_first(void)
     return NULL;
 #endif
 
-    BLE_HS_DBG_ASSERT(ble_hs_thread_safe());
+    BLE_HS_DBG_ASSERT(ble_hs_locked_by_cur_task());
     return SLIST_FIRST(&ble_hs_conns);
 }
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/eacea950/net/nimble/host/src/ble_hs_priv.h
----------------------------------------------------------------------
diff --git a/net/nimble/host/src/ble_hs_priv.h b/net/nimble/host/src/ble_hs_priv.h
index 2cb12b4..1be119a 100644
--- a/net/nimble/host/src/ble_hs_priv.h
+++ b/net/nimble/host/src/ble_hs_priv.h
@@ -90,7 +90,6 @@ uint8_t ble_hs_misc_addr_type_to_id(uint8_t addr_type);
 void ble_hs_cfg_init(struct ble_hs_cfg *cfg);
 
 int ble_hs_locked_by_cur_task(void);
-int ble_hs_thread_safe(void);
 int ble_hs_is_parent_task(void);
 void ble_hs_lock(void);
 void ble_hs_unlock(void);

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/eacea950/net/nimble/host/src/ble_l2cap_sig.c
----------------------------------------------------------------------
diff --git a/net/nimble/host/src/ble_l2cap_sig.c b/net/nimble/host/src/ble_l2cap_sig.c
index b9c1244..93ba2e2 100644
--- a/net/nimble/host/src/ble_l2cap_sig.c
+++ b/net/nimble/host/src/ble_l2cap_sig.c
@@ -186,7 +186,7 @@ ble_l2cap_sig_proc_insert(struct ble_l2cap_sig_proc *proc)
 {
     ble_l2cap_sig_dbg_assert_proc_not_inserted(proc);
 
-    BLE_HS_DBG_ASSERT(ble_hs_thread_safe());
+    BLE_HS_DBG_ASSERT(ble_hs_locked_by_cur_task());
     STAILQ_INSERT_HEAD(&ble_l2cap_sig_procs, proc, next);
 }
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/eacea950/net/nimble/host/src/ble_sm.c
----------------------------------------------------------------------
diff --git a/net/nimble/host/src/ble_sm.c b/net/nimble/host/src/ble_sm.c
index 8d7fa74..ab41173 100644
--- a/net/nimble/host/src/ble_sm.c
+++ b/net/nimble/host/src/ble_sm.c
@@ -624,7 +624,7 @@ ble_sm_proc_find(uint16_t conn_handle, uint8_t state, int is_initiator,
     struct ble_sm_proc *proc;
     struct ble_sm_proc *prev;
 
-    BLE_HS_DBG_ASSERT(ble_hs_thread_safe());
+    BLE_HS_DBG_ASSERT(ble_hs_locked_by_cur_task());
 
     prev = NULL;
     STAILQ_FOREACH(proc, &ble_sm_procs, next) {

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/eacea950/net/nimble/host/src/ble_sm_cmd.c
----------------------------------------------------------------------
diff --git a/net/nimble/host/src/ble_sm_cmd.c b/net/nimble/host/src/ble_sm_cmd.c
index 4151856..3d506b2 100644
--- a/net/nimble/host/src/ble_sm_cmd.c
+++ b/net/nimble/host/src/ble_sm_cmd.c
@@ -34,7 +34,7 @@ ble_sm_tx(uint16_t conn_handle, struct os_mbuf *txom)
     struct ble_hs_conn *conn;
     int rc;
 
-    BLE_HS_DBG_ASSERT(ble_hs_thread_safe());
+    BLE_HS_DBG_ASSERT(ble_hs_locked_by_cur_task());
 
     STATS_INC(ble_l2cap_stats, sm_tx);
 


[36/50] [abbrv] incubator-mynewt-core git commit: MYNEWT-332: Return error if initiating and host attempts to enable scanning

Posted by cc...@apache.org.
MYNEWT-332: Return error if initiating and host attempts to enable scanning


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/251ba7a1
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/251ba7a1
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/251ba7a1

Branch: refs/heads/master
Commit: 251ba7a1fce27dd62cc6826bb27e50ef25a68278
Parents: 8c6c5a8
Author: William San Filippo <wi...@runtime.io>
Authored: Thu Jun 30 13:05:36 2016 -0700
Committer: William San Filippo <wi...@runtime.io>
Committed: Thu Jun 30 13:05:36 2016 -0700

----------------------------------------------------------------------
 net/nimble/controller/src/ble_ll_scan.c | 5 +++++
 1 file changed, 5 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/251ba7a1/net/nimble/controller/src/ble_ll_scan.c
----------------------------------------------------------------------
diff --git a/net/nimble/controller/src/ble_ll_scan.c b/net/nimble/controller/src/ble_ll_scan.c
index 8e845c6..e7346ba 100644
--- a/net/nimble/controller/src/ble_ll_scan.c
+++ b/net/nimble/controller/src/ble_ll_scan.c
@@ -1289,6 +1289,11 @@ ble_ll_scan_set_enable(uint8_t *cmd)
             /* Start the scanning state machine */
             scansm->scan_filt_dups = filter_dups;
             rc = ble_ll_scan_sm_start(scansm);
+        } else {
+            /* Controller does not allow initiating and scanning.*/
+            if (scansm->scan_type == BLE_SCAN_TYPE_INITIATE) {
+                rc = BLE_ERR_CMD_DISALLOWED;
+            }
         }
     } else {
         if (scansm->scan_enabled) {


[45/50] [abbrv] incubator-mynewt-core git commit: BLE Host - BLE_HS_EMSGSIZE used incorrectly.

Posted by cc...@apache.org.
BLE Host - BLE_HS_EMSGSIZE used incorrectly.

For many HCI events, BLE_HS_EMSGSIZE was used when the event's length
was unexpected.  The correct error code to use in this case is
BLE_HS_ECONTROLLER.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/41291575
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/41291575
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/41291575

Branch: refs/heads/master
Commit: 41291575c8a4b74a215a46a01fd2ae093fd6d7c5
Parents: dda1c9a
Author: Christopher Collins <cc...@apache.org>
Authored: Sat Jul 2 19:50:15 2016 -0700
Committer: Christopher Collins <cc...@apache.org>
Committed: Sat Jul 2 19:50:15 2016 -0700

----------------------------------------------------------------------
 net/nimble/host/src/ble_hci_cmd.c |  6 +++---
 net/nimble/host/src/host_hci.c    | 24 ++++++++++++------------
 2 files changed, 15 insertions(+), 15 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/41291575/net/nimble/host/src/ble_hci_cmd.c
----------------------------------------------------------------------
diff --git a/net/nimble/host/src/ble_hci_cmd.c b/net/nimble/host/src/ble_hci_cmd.c
index 0e14f04..23eaba3 100644
--- a/net/nimble/host/src/ble_hci_cmd.c
+++ b/net/nimble/host/src/ble_hci_cmd.c
@@ -70,7 +70,7 @@ ble_hci_cmd_rx_cmd_complete(uint8_t event_code, uint8_t *data, int len,
 
     if (len < BLE_HCI_EVENT_CMD_COMPLETE_HDR_LEN) {
         /* XXX: Increment stat. */
-        return BLE_HS_EMSGSIZE;
+        return BLE_HS_ECONTROLLER;
     }
 
     num_pkts = data[2];
@@ -113,7 +113,7 @@ ble_hci_cmd_rx_cmd_status(uint8_t event_code, uint8_t *data, int len,
 
     if (len < BLE_HCI_EVENT_CMD_STATUS_LEN) {
         /* XXX: Increment stat. */
-        return BLE_HS_EMSGSIZE;
+        return BLE_HS_ECONTROLLER;
     }
 
     status = data[2];
@@ -182,7 +182,7 @@ ble_hci_cmd_process_ack(uint8_t *params_buf, uint8_t params_buf_len,
         } else {
             if (out_ack->bha_params_len > params_buf_len) {
                 out_ack->bha_params_len = params_buf_len;
-                rc = BLE_HS_EMSGSIZE;
+                rc = BLE_HS_ECONTROLLER;
             }
             memcpy(params_buf, out_ack->bha_params, out_ack->bha_params_len);
         }

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/41291575/net/nimble/host/src/host_hci.c
----------------------------------------------------------------------
diff --git a/net/nimble/host/src/host_hci.c b/net/nimble/host/src/host_hci.c
index 5f58663..4452dcc 100644
--- a/net/nimble/host/src/host_hci.c
+++ b/net/nimble/host/src/host_hci.c
@@ -151,7 +151,7 @@ host_hci_rx_disconn_complete(uint8_t event_code, uint8_t *data, int len)
     struct hci_disconn_complete evt;
 
     if (len < BLE_HCI_EVENT_DISCONN_COMPLETE_LEN) {
-        return BLE_HS_EMSGSIZE;
+        return BLE_HS_ECONTROLLER;
     }
 
     evt.status = data[2];
@@ -208,14 +208,14 @@ host_hci_rx_num_completed_pkts(uint8_t event_code, uint8_t *data, int len)
     int i;
 
     if (len < BLE_HCI_EVENT_HDR_LEN + BLE_HCI_EVENT_NUM_COMP_PKTS_HDR_LEN) {
-        return BLE_HS_EMSGSIZE;
+        return BLE_HS_ECONTROLLER;
     }
 
     off = BLE_HCI_EVENT_HDR_LEN;
     num_handles = data[off];
     if (len < BLE_HCI_EVENT_NUM_COMP_PKTS_HDR_LEN +
               num_handles * BLE_HCI_EVENT_NUM_COMP_PKTS_ENT_LEN) {
-        return BLE_HS_EMSGSIZE;
+        return BLE_HS_ECONTROLLER;
     }
     off++;
 
@@ -240,7 +240,7 @@ host_hci_rx_le_meta(uint8_t event_code, uint8_t *data, int len)
 
     if (len < BLE_HCI_EVENT_HDR_LEN + BLE_HCI_LE_MIN_LEN) {
         /* XXX: Increment stat. */
-        return BLE_HS_EMSGSIZE;
+        return BLE_HS_ECONTROLLER;
     }
 
     subevent = data[2];
@@ -264,13 +264,13 @@ host_hci_rx_le_conn_complete(uint8_t subevent, uint8_t *data, int len)
     int rc;
 
     if (len < BLE_HCI_LE_CONN_COMPLETE_LEN) {
-        return BLE_HS_EMSGSIZE;
+        return BLE_HS_ECONTROLLER;
     }
 
     /* this code processes two different events that are really similar */
     if ((subevent == BLE_HCI_LE_SUBEV_ENH_CONN_COMPLETE) &&
         ( len < BLE_HCI_LE_ENH_CONN_COMPLETE_LEN)) {
-        return BLE_HS_EMSGSIZE;
+        return BLE_HS_ECONTROLLER;
     }
 
     evt.subevent_code = data[0];
@@ -322,7 +322,7 @@ host_hci_le_adv_rpt_first_pass(uint8_t *data, int len,
     int i;
 
     if (len < BLE_HCI_LE_ADV_RPT_MIN_LEN) {
-        return BLE_HS_EMSGSIZE;
+        return BLE_HS_ECONTROLLER;
     }
 
     num_reports = data[1];
@@ -338,7 +338,7 @@ host_hci_le_adv_rpt_first_pass(uint8_t *data, int len,
            6        /* Address. */
           ) * num_reports;
     if (off + num_reports >= len) {
-        return BLE_HS_EMSGSIZE;
+        return BLE_HS_ECONTROLLER;
     }
 
     data_len = 0;
@@ -351,7 +351,7 @@ host_hci_le_adv_rpt_first_pass(uint8_t *data, int len,
 
     /* Check if RSSI fields fit in the packet. */
     if (off + num_reports > len) {
-        return BLE_HS_EMSGSIZE;
+        return BLE_HS_ECONTROLLER;
     }
 
     *out_num_reports = num_reports;
@@ -409,7 +409,7 @@ host_hci_rx_le_conn_upd_complete(uint8_t subevent, uint8_t *data, int len)
     struct hci_le_conn_upd_complete evt;
 
     if (len < BLE_HCI_LE_CONN_UPD_LEN) {
-        return BLE_HS_EMSGSIZE;
+        return BLE_HS_ECONTROLLER;
     }
 
     evt.subevent_code = data[0];
@@ -467,7 +467,7 @@ host_hci_rx_le_conn_parm_req(uint8_t subevent, uint8_t *data, int len)
     struct hci_le_conn_param_req evt;
 
     if (len < BLE_HCI_LE_REM_CONN_PARM_REQ_LEN) {
-        return BLE_HS_EMSGSIZE;
+        return BLE_HS_ECONTROLLER;
     }
 
     evt.subevent_code = data[0];
@@ -615,7 +615,7 @@ host_hci_data_hdr_strip(struct os_mbuf *om, struct hci_data_hdr *hdr)
 
     rc = os_mbuf_copydata(om, 0, BLE_HCI_DATA_HDR_SZ, hdr);
     if (rc != 0) {
-        return BLE_HS_EMSGSIZE;
+        return BLE_HS_ECONTROLLER;
     }
 
     /* Strip HCI ACL data header from the front of the packet. */


[43/50] [abbrv] incubator-mynewt-core git commit: BLE Host - Fix read-rssi bug.

Posted by cc...@apache.org.
BLE Host - Fix read-rssi bug.

The host was passing a too-short buffer to the HCI tx function.  The
result was a BLE_HS_EMSGSIZE error.

Fix: pass correct buffer size (3) rather than 1.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/2e643fd2
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/2e643fd2
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/2e643fd2

Branch: refs/heads/master
Commit: 2e643fd2515d163b8343b8b72e7b2daea5f55f69
Parents: bcfe3fd
Author: Christopher Collins <cc...@apache.org>
Authored: Sat Jul 2 19:28:41 2016 -0700
Committer: Christopher Collins <cc...@apache.org>
Committed: Sat Jul 2 19:28:41 2016 -0700

----------------------------------------------------------------------
 net/nimble/host/src/ble_hci_util.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/2e643fd2/net/nimble/host/src/ble_hci_util.c
----------------------------------------------------------------------
diff --git a/net/nimble/host/src/ble_hci_util.c b/net/nimble/host/src/ble_hci_util.c
index c792b6e..f9ed2c5 100644
--- a/net/nimble/host/src/ble_hci_util.c
+++ b/net/nimble/host/src/ble_hci_util.c
@@ -87,7 +87,7 @@ ble_hci_util_read_rssi(uint16_t conn_handle, int8_t *out_rssi)
     int rc;
 
     host_hci_cmd_build_read_rssi(conn_handle, buf, sizeof buf);
-    rc = ble_hci_cmd_tx(buf, params, 1, &params_len);
+    rc = ble_hci_cmd_tx(buf, params, sizeof params, &params_len);
     if (rc != 0) {
         return rc;
     }


[09/50] [abbrv] incubator-mynewt-core git commit: BLE Host - Clean up runtime settings.

Posted by cc...@apache.org.
BLE Host - Clean up runtime settings.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/a27e86ff
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/a27e86ff
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/a27e86ff

Branch: refs/heads/master
Commit: a27e86ffffcaef04dce633901bbecf60c0033027
Parents: 9b56c3c
Author: Christopher Collins <cc...@apache.org>
Authored: Tue Jun 21 15:50:42 2016 -0700
Committer: Christopher Collins <cc...@apache.org>
Committed: Tue Jun 21 15:50:42 2016 -0700

----------------------------------------------------------------------
 net/nimble/host/include/host/ble_hs.h | 119 +++++++++++++++++++++++++----
 1 file changed, 104 insertions(+), 15 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/a27e86ff/net/nimble/host/include/host/ble_hs.h
----------------------------------------------------------------------
diff --git a/net/nimble/host/include/host/ble_hs.h b/net/nimble/host/include/host/ble_hs.h
index 63720c3..e493723 100644
--- a/net/nimble/host/include/host/ble_hs.h
+++ b/net/nimble/host/include/host/ble_hs.h
@@ -79,32 +79,115 @@ struct os_event;
 #define BLE_HS_IO_NO_INPUT_OUTPUT           0x03
 #define BLE_HS_IO_KEYBOARD_DISPLAY          0x04
 
+#define BLE_HS_PRIVACY_MODE_NONE            0
+#define BLE_HS_PRIVACY_MODE_RANDOM_STATIC   1
+#define BLE_HS_PRIVACY_MODE_RESOLV_RAND     2
+
 struct ble_hs_cfg {
-    /** HCI settings. */
+    /*** HCI settings. */
+    /**
+     * An HCI buffer is a "flat" 260-byte buffer.  HCI buffers are used by the
+     * controller to send unsolicited events to the host.
+     *
+     * HCI buffers can get tied up when the controller sends lots of
+     * asynchronous / unsolicited events (i.e., non-acks).  When the controller
+     * needs to send one of these events, it allocates an HCI buffer, fills it
+     * with the event payload, and puts it on a host queue.  If the controller
+     * sends a quick burst of these events, the buffer pool may be exhausted,
+     * preventing the host from sending an HCI command to the controller.
+     *
+     * Every time the controller sends a non-ack HCI event to the host, it also
+     * allocates an OS event (it is unfortunate that these are both called
+     * "events").  The OS event is put on the host-parent-task's event queue;
+     * it is what wakes up the host-parent-task and indicates that an HCI event
+     * needs to be processsed.  The pool of OS events is allocated with the
+     * same number of elements as the HCI buffer pool.
+     */
     uint8_t max_hci_bufs;
 
-    /** Connection settings. */
-    uint16_t max_outstanding_pkts_per_conn;
+    /*** Connection settings. */
+    /**
+     * The maximum number of concurrent connections.  This is set
+     * automatically according to the build-time option
+     * NIMBLE_OPT_MAX_CONNECTIONS.
+     */
     uint8_t max_connections;
-    uint8_t max_conn_update_entries;
 
-    /** GATT server settings. */
+    /*** GATT server settings. */
+    /**
+     * These are acquired at service registration time and never freed.  You
+     * need one of these for every service that you register.
+     */
     uint16_t max_services;
+
+    /**
+     * The total number of in-RAM client characteristic configuration
+     * descriptors (CCCDs).  One of these is consumed each time a peer
+     * subscribes to notifications or indications for a characteristic that
+     * your device serves.  In addition, at service registration time, the host
+     * uses one of these for each characteristic that supports notifications or
+     * indications.  So, the formula which guarantees no resource exhaustion
+     * is:
+     *     (num-subscribable-characteristics) * (max-connections + 1)
+     */
     uint16_t max_client_configs;
 
-    /** GATT client settings. */
+    /*** GATT client settings. */
+    /**
+     * The maximum number of concurrent GATT client procedures.  When you
+     * initiate a GATT procedure (e.g., read a characteristic, discover
+     * services, etc.), one of these is consumed.  The resource is freed when
+     * the procedure completes.
+     */
     uint8_t max_gattc_procs;
 
-    /** ATT server settings. */
+    /*** ATT server settings. */
+    /**
+     * The total number of local ATT attributes.  Attributes are consumed at
+     * service registration time and are never freed.  Attributes are used by
+     * GATT server entities: services, characteristics, and descriptors
+     * according to the following formula:
+     *     (num-services + (num-characteristics * 2) + num-descriptors)
+     *
+     * Every characteristic that supports indications or notifications
+     * automatically gets a descriptor.  All other descriptors are specified by
+     * the application at service registration time.
+     */
     uint16_t max_attrs;
+
+    /**
+     * A GATT server uses these when a peer performs a "write long
+     * characteristic values" or "write long characteristic descriptors"
+     * procedure.  One of these resources is consumed each time a peer sends a
+     * partial write.  These procedures are not used often.
+     */
     uint8_t max_prep_entries;
 
-    /** L2CAP settings. */
+    /*** L2CAP settings. */
+    /**
+     * Each connection requires three L2CAP channels (signal, ATT, and security
+     * manager).  In addition, the nimble host may allow channels to be created
+     * "on the fly" (connection-oriented channels).  This functionality is not
+     * available at the moment, so a safe formula to use is:
+     *     (max-connections * 3)
+     */
     uint8_t max_l2cap_chans;
+
+    /**
+     * The maximum number of concurrent L2CAP signalling procedures.  Only one
+     * L2CAP signalling procedure is supported: slave-initiated connection
+     * update.  You will never need more of these than the max number of
+     * connections.
+     */
     uint8_t max_l2cap_sig_procs;
+
+    /**
+     * The maximum number of concurrent security manager procedures.  Security
+     * manager procedures include pairing and restoration of a bonded link.
+     */
     uint8_t max_l2cap_sm_procs;
 
-    /** Security manager settings. */
+    /*** Security manager settings. */
     uint8_t sm_io_cap;
     unsigned sm_oob_data_flag:1;
     unsigned sm_bonding:1;
@@ -113,15 +196,21 @@ struct ble_hs_cfg {
     unsigned sm_keypress:1;
     uint8_t sm_our_key_dist;
     uint8_t sm_their_key_dist;
-    /** Store settings. */
+
+    /*** Store settings. */
+    /**
+     * These function callbacks handle persistence of sercurity material
+     * (bonding).
+     */
     ble_store_read_fn *store_read_cb;
     ble_store_write_fn *store_write_cb;
     ble_store_delete_fn *store_delete_cb;
-    /* privacy settings */
-    uint8_t privacy_mode;
-    #define BLE_HS_PRIVACY_MODE_NONE            (0)
-    #define BLE_HS_PRIVACY_MODE_RANDOM_STATIC   (1)
-    #define BLE_HS_PRIVACY_MODE_RESOLV_RAND     (2)
+
+    /*** privacy settings */
+    /**
+     * The frequency at which new resovlable private addresses are generated.
+     * Units are seconds.
+     */
     uint16_t rpa_timeout;
 };
 


[32/50] [abbrv] incubator-mynewt-core git commit: No need to change repository.yml for pull request #67

Posted by cc...@apache.org.
No need to change repository.yml for pull request #67


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/8c6c5a83
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/8c6c5a83
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/8c6c5a83

Branch: refs/heads/master
Commit: 8c6c5a83687724bf7da6ee061b8e67888f97a8b0
Parents: 821b21d
Author: William San Filippo <wi...@runtime.io>
Authored: Tue Jun 28 09:44:17 2016 -0700
Committer: William San Filippo <wi...@runtime.io>
Committed: Tue Jun 28 09:44:17 2016 -0700

----------------------------------------------------------------------
 repository.yml | 29 -----------------------------
 1 file changed, 29 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/8c6c5a83/repository.yml
----------------------------------------------------------------------
diff --git a/repository.yml b/repository.yml
deleted file mode 100644
index d4d1c64..0000000
--- a/repository.yml
+++ /dev/null
@@ -1,29 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
-
-repo.name: apache-mynewt-core
-repo.versions:
-    "0.0.0": "develop"
-    "0.7.9": "mynewt_0_8_0_b2_tag"
-    "0.8.0": "mynewt_0_8_0_tag"
-    "0.9.0": "mynewt_0_9_0_tag"
-    "0-latest": "0.9.0"
-    "0-dev": "0.0.0"
-    "0.8-latest": "0.8.0"
-    "0.9-latest": "0.9.0"


[44/50] [abbrv] incubator-mynewt-core git commit: bletiny - Add "b rssi" command for reading rssi.

Posted by cc...@apache.org.
bletiny - Add "b rssi" command for reading rssi.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/dda1c9a9
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/dda1c9a9
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/dda1c9a9

Branch: refs/heads/master
Commit: dda1c9a99647f3b61109d9ca35e3d1552e908e8c
Parents: 2e643fd
Author: Christopher Collins <cc...@apache.org>
Authored: Sat Jul 2 19:29:48 2016 -0700
Committer: Christopher Collins <cc...@apache.org>
Committed: Sat Jul 2 19:29:48 2016 -0700

----------------------------------------------------------------------
 apps/bletiny/src/bletiny.h |  1 +
 apps/bletiny/src/cmd.c     | 28 ++++++++++++++++++++++++++++
 apps/bletiny/src/main.c    | 13 +++++++++++++
 3 files changed, 42 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/dda1c9a9/apps/bletiny/src/bletiny.h
----------------------------------------------------------------------
diff --git a/apps/bletiny/src/bletiny.h b/apps/bletiny/src/bletiny.h
index 738e504..29e1d63 100644
--- a/apps/bletiny/src/bletiny.h
+++ b/apps/bletiny/src/bletiny.h
@@ -178,6 +178,7 @@ int bletiny_sec_restart(uint16_t conn_handle, uint8_t *ltk, uint16_t ediv,
                         uint64_t rand_val, int auth);
 int bletiny_tx_start(uint16_t handle, uint16_t len, uint16_t rate,
                      uint16_t num);
+int bletiny_rssi(uint16_t conn_handle, int8_t *out_rssi);
 
 #define BLETINY_LOG_MODULE  (LOG_MODULE_PERUSER + 0)
 #define BLETINY_LOG(lvl, ...) \

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/dda1c9a9/apps/bletiny/src/cmd.c
----------------------------------------------------------------------
diff --git a/apps/bletiny/src/cmd.c b/apps/bletiny/src/cmd.c
index 4c37d4a..f6ad11d 100644
--- a/apps/bletiny/src/cmd.c
+++ b/apps/bletiny/src/cmd.c
@@ -867,6 +867,33 @@ cmd_read(int argc, char **argv)
 }
 
 /*****************************************************************************
+ * $rssi                                                                     *
+ *****************************************************************************/
+
+static int
+cmd_rssi(int argc, char **argv)
+{
+    uint16_t conn_handle;
+    int8_t rssi;
+    int rc;
+
+    conn_handle = parse_arg_uint16("conn", &rc);
+    if (rc != 0) {
+        return rc;
+    }
+
+    rc = bletiny_rssi(conn_handle, &rssi);
+    if (rc != 0) {
+        console_printf("error reading rssi; rc=%d\n", rc);
+        return rc;
+    }
+
+    console_printf("conn=%d rssi=%d\n", conn_handle, rssi);
+
+    return 0;
+}
+
+/*****************************************************************************
  * $scan                                                                     *
  *****************************************************************************/
 
@@ -2153,6 +2180,7 @@ static struct cmd_entry cmd_b_entries[] = {
     { "mtu",        cmd_mtu },
     { "passkey",    cmd_passkey },
     { "read",       cmd_read },
+    { "rssi",       cmd_rssi },
     { "scan",       cmd_scan },
     { "show",       cmd_show },
     { "sec",        cmd_sec },

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/dda1c9a9/apps/bletiny/src/main.c
----------------------------------------------------------------------
diff --git a/apps/bletiny/src/main.c b/apps/bletiny/src/main.c
index a94027b..edb1984 100755
--- a/apps/bletiny/src/main.c
+++ b/apps/bletiny/src/main.c
@@ -1475,6 +1475,19 @@ bletiny_tx_start(uint16_t handle, uint16_t len, uint16_t rate, uint16_t num)
     return 0;
 }
 
+int
+bletiny_rssi(uint16_t conn_handle, int8_t *out_rssi)
+{
+    int rc;
+
+    rc = ble_hci_util_read_rssi(conn_handle, out_rssi);
+    if (rc != 0) {
+        return rc;
+    }
+
+    return 0;
+}
+
 /**
  * BLE test task
  *


[25/50] [abbrv] incubator-mynewt-core git commit: This closes #65.

Posted by cc...@apache.org.
This closes #65.

Merge branch 'os_eventq3' of https://github.com/NgesBrian/incubator-mynewt-core into develop


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/93f2e112
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/93f2e112
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/93f2e112

Branch: refs/heads/master
Commit: 93f2e1127735784fa5a6bb7536b4da31e9479288
Parents: fd0a899 9052048
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Mon Jun 27 12:33:07 2016 -0700
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Jun 27 12:33:07 2016 -0700

----------------------------------------------------------------------
 libs/os/src/test/eventq_test.c  | 127 +++++++++++++++++++++++++++++++++++
 libs/os/src/test/os_test.c      |   2 +
 libs/os/src/test/os_test_priv.h |   2 +
 3 files changed, 131 insertions(+)
----------------------------------------------------------------------



[38/50] [abbrv] incubator-mynewt-core git commit: slinky; increase newtmgr stack size. Coredump implied that file write was triggering NFFS garbage collection.

Posted by cc...@apache.org.
slinky; increase newtmgr stack size. Coredump implied that
file write was triggering NFFS garbage collection.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/55c2e6e9
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/55c2e6e9
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/55c2e6e9

Branch: refs/heads/master
Commit: 55c2e6e95421d7cad585247416edf24672184489
Parents: 0678891
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Thu Jun 30 15:10:07 2016 -0700
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Thu Jun 30 15:10:07 2016 -0700

----------------------------------------------------------------------
 apps/slinky/src/main.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/55c2e6e9/apps/slinky/src/main.c
----------------------------------------------------------------------
diff --git a/apps/slinky/src/main.c b/apps/slinky/src/main.c
index 00eec39..16cb3ac 100755
--- a/apps/slinky/src/main.c
+++ b/apps/slinky/src/main.c
@@ -77,7 +77,7 @@ os_stack_t stack2[TASK2_STACK_SIZE];
 os_stack_t shell_stack[SHELL_TASK_STACK_SIZE];
 
 #define NEWTMGR_TASK_PRIO (4)
-#define NEWTMGR_TASK_STACK_SIZE (OS_STACK_ALIGN(512))
+#define NEWTMGR_TASK_STACK_SIZE (OS_STACK_ALIGN(896))
 os_stack_t newtmgr_stack[NEWTMGR_TASK_STACK_SIZE];
 
 struct log_handler log_cbmem_handler;


[02/50] [abbrv] incubator-mynewt-core git commit: bleprph - Fix build errors.

Posted by cc...@apache.org.
bleprph - Fix build errors.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/2efa3442
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/2efa3442
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/2efa3442

Branch: refs/heads/master
Commit: 2efa34424d5cd3dabb679b2b958465cc1dd7feb8
Parents: 91bc6c2
Author: Christopher Collins <cc...@apache.org>
Authored: Mon Jun 20 14:31:09 2016 -0700
Committer: Christopher Collins <cc...@apache.org>
Committed: Mon Jun 20 14:31:09 2016 -0700

----------------------------------------------------------------------
 apps/bleprph/src/bleprph.h |  1 +
 apps/bleprph/src/main.c    | 24 ++++++++++++++++--------
 apps/bleprph/src/misc.c    | 10 ++++++++++
 3 files changed, 27 insertions(+), 8 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/2efa3442/apps/bleprph/src/bleprph.h
----------------------------------------------------------------------
diff --git a/apps/bleprph/src/bleprph.h b/apps/bleprph/src/bleprph.h
index 742319f..a353bac 100644
--- a/apps/bleprph/src/bleprph.h
+++ b/apps/bleprph/src/bleprph.h
@@ -60,5 +60,6 @@ int store_write(int obj_type, union ble_store_value *val);
 
 /** Misc. */
 void print_bytes(uint8_t *bytes, int len);
+void print_addr(void *addr);
 
 #endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/2efa3442/apps/bleprph/src/main.c
----------------------------------------------------------------------
diff --git a/apps/bleprph/src/main.c b/apps/bleprph/src/main.c
index f2d0c09..69a4c7a 100755
--- a/apps/bleprph/src/main.c
+++ b/apps/bleprph/src/main.c
@@ -95,17 +95,25 @@ static int bleprph_gap_event(int event, struct ble_gap_conn_ctxt *ctxt,
 static void
 bleprph_print_conn_desc(struct ble_gap_conn_desc *desc)
 {
-    BLEPRPH_LOG(INFO, "handle=%d peer_addr_type=%d peer_addr=",
-                desc->conn_handle,
-                desc->peer_addr_type);
-    print_bytes(desc->peer_addr, 6);
+    BLEPRPH_LOG(INFO, "handle=%d our_ota_addr_type=%d our_ota_addr=",
+                desc->conn_handle, desc->our_ota_addr_type);
+    print_addr(desc->our_ota_addr);
+    BLEPRPH_LOG(INFO, " our_id_addr_type=%d our_id_addr=",
+                desc->our_id_addr_type);
+    print_addr(desc->our_id_addr);
+    BLEPRPH_LOG(INFO, " peer_ota_addr_type=%d peer_ota_addr=",
+                desc->peer_ota_addr_type);
+    print_addr(desc->peer_ota_addr);
+    BLEPRPH_LOG(INFO, " peer_id_addr_type=%d peer_id_addr=",
+                desc->peer_id_addr_type);
+    print_addr(desc->peer_id_addr);
     BLEPRPH_LOG(INFO, " conn_itvl=%d conn_latency=%d supervision_timeout=%d "
-                      "encrypted=%d authenticated=%d",
-                desc->conn_itvl,
-                desc->conn_latency,
+                "encrypted=%d authenticated=%d bonded=%d\n",
+                desc->conn_itvl, desc->conn_latency,
                 desc->supervision_timeout,
                 desc->sec_state.encrypted,
-                desc->sec_state.authenticated);
+                desc->sec_state.authenticated,
+                desc->sec_state.bonded);
 }
 
 /**

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/2efa3442/apps/bleprph/src/misc.c
----------------------------------------------------------------------
diff --git a/apps/bleprph/src/misc.c b/apps/bleprph/src/misc.c
index 64dfeed..d5d4808 100644
--- a/apps/bleprph/src/misc.c
+++ b/apps/bleprph/src/misc.c
@@ -31,3 +31,13 @@ print_bytes(uint8_t *bytes, int len)
         BLEPRPH_LOG(INFO, "%s0x%02x", i != 0 ? ":" : "", bytes[i]);
     }
 }
+
+void
+print_addr(void *addr)
+{
+    uint8_t *u8p;
+
+    u8p = addr;
+    BLEPRPH_LOG(INFO, "%02x:%02x:%02x:%02x:%02x:%02x",
+                u8p[5], u8p[4], u8p[3], u8p[2], u8p[1], u8p[0]);
+}


[04/50] [abbrv] incubator-mynewt-core git commit: BLE Host - Return oom errors on no hci buf / no ev.

Posted by cc...@apache.org.
BLE Host - Return oom errors on no hci buf / no ev.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/39660c0f
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/39660c0f
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/39660c0f

Branch: refs/heads/master
Commit: 39660c0fca5899f346574782bc245db553170169
Parents: b8b3232
Author: Christopher Collins <cc...@apache.org>
Authored: Mon Jun 20 20:22:23 2016 -0700
Committer: Christopher Collins <cc...@apache.org>
Committed: Mon Jun 20 20:31:29 2016 -0700

----------------------------------------------------------------------
 net/nimble/controller/src/ble_ll_hci.c |  7 +++--
 net/nimble/host/include/host/ble_hs.h  |  2 ++
 net/nimble/host/src/ble_hci_cmd.c      |  2 +-
 net/nimble/host/src/host_hci_cmd.c     | 42 +++++++++++++++++++----------
 4 files changed, 36 insertions(+), 17 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/39660c0f/net/nimble/controller/src/ble_ll_hci.c
----------------------------------------------------------------------
diff --git a/net/nimble/controller/src/ble_ll_hci.c b/net/nimble/controller/src/ble_ll_hci.c
index fd75fbb..a17515f 100644
--- a/net/nimble/controller/src/ble_ll_hci.c
+++ b/net/nimble/controller/src/ble_ll_hci.c
@@ -982,7 +982,10 @@ ble_ll_hci_cmd_proc(struct os_event *ev)
     ble_ll_hci_event_send(cmdbuf);
 }
 
-/* XXX: For now, put this here */
+/**
+ * @return                      0 on success;
+ *                              BLE_ERR_MEM_CAPACITY on HCI buffer exhaustion.
+ */
 int
 ble_hci_transport_host_cmd_send(uint8_t *cmd)
 {
@@ -994,7 +997,7 @@ ble_hci_transport_host_cmd_send(uint8_t *cmd)
     if (!ev) {
         err = os_memblock_put(&g_hci_cmd_pool, cmd);
         assert(err == OS_OK);
-        return -1;
+        return BLE_ERR_MEM_CAPACITY;
     }
 
     /* Fill out the event and post to Link Layer */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/39660c0f/net/nimble/host/include/host/ble_hs.h
----------------------------------------------------------------------
diff --git a/net/nimble/host/include/host/ble_hs.h b/net/nimble/host/include/host/ble_hs.h
index 18eb588..63720c3 100644
--- a/net/nimble/host/include/host/ble_hs.h
+++ b/net/nimble/host/include/host/ble_hs.h
@@ -54,6 +54,8 @@ struct os_event;
 #define BLE_HS_EUNKNOWN             18
 #define BLE_HS_EROLE                19
 #define BLE_HS_ETIMEOUT_HCI         20
+#define BLE_HS_ENOMEM_HCI           21
+#define BLE_HS_ENOMEM_EVT           22
 
 #define BLE_HS_ERR_ATT_BASE         0x100   /* 256 */
 #define BLE_HS_ATT_ERR(x)           ((x) ? BLE_HS_ERR_ATT_BASE + (x) : 0)

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/39660c0f/net/nimble/host/src/ble_hci_cmd.c
----------------------------------------------------------------------
diff --git a/net/nimble/host/src/ble_hci_cmd.c b/net/nimble/host/src/ble_hci_cmd.c
index c41f038..014ef0a 100644
--- a/net/nimble/host/src/ble_hci_cmd.c
+++ b/net/nimble/host/src/ble_hci_cmd.c
@@ -204,7 +204,7 @@ ble_hci_cmd_wait_for_ack(void)
         BLE_HS_DBG_ASSERT(ble_hci_cmd_ack_ev == NULL);
         ble_hci_cmd_ack_ev = os_memblock_get(&g_hci_cmd_pool);
         if (ble_hci_cmd_ack_ev == NULL) {
-            rc = BLE_HS_ENOMEM;
+            rc = BLE_HS_ENOMEM_HCI;
         } else {
             rc = ble_hci_cmd_phony_ack_cb(ble_hci_cmd_ack_ev, 260);
         }

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/39660c0f/net/nimble/host/src/host_hci_cmd.c
----------------------------------------------------------------------
diff --git a/net/nimble/host/src/host_hci_cmd.c b/net/nimble/host/src/host_hci_cmd.c
index d638ed6..281b270 100644
--- a/net/nimble/host/src/host_hci_cmd.c
+++ b/net/nimble/host/src/host_hci_cmd.c
@@ -39,7 +39,19 @@ host_hci_cmd_transport(uint8_t *cmdbuf)
     ble_hs_test_hci_txed(cmdbuf);
     return 0;
 #else
-    return ble_hci_transport_host_cmd_send(cmdbuf);
+    int rc;
+
+    rc = ble_hci_transport_host_cmd_send(cmdbuf);
+    switch (rc) {
+    case 0:
+        return 0;
+
+    case BLE_ERR_MEM_CAPACITY:
+        return BLE_HS_ENOMEM_EVT;
+
+    default:
+        return BLE_HS_EUNKNOWN;
+    }
 #endif
 }
 
@@ -63,21 +75,23 @@ host_hci_cmd_send(uint8_t ogf, uint8_t ocf, uint8_t len, void *cmddata)
     uint8_t *cmd;
     uint16_t opcode;
 
-    rc = -1;
     cmd = os_memblock_get(&g_hci_cmd_pool);
-    if (cmd) {
-        opcode = (ogf << 10) | ocf;
-        htole16(cmd, opcode);
-        cmd[2] = len;
-        if (len) {
-            memcpy(cmd + BLE_HCI_CMD_HDR_LEN, cmddata, len);
-        }
-        rc = host_hci_cmd_transport(cmd);
-        BLE_HS_LOG(DEBUG, "host_hci_cmd_send: ogf=0x%02x ocf=0x%02x len=%d\n",
-                   ogf, ocf, len);
-        ble_hs_misc_log_flat_buf(cmd, len + BLE_HCI_CMD_HDR_LEN);
-        BLE_HS_LOG(DEBUG, "\n");
+    if (cmd == NULL) {
+        /* XXX: Increment stat. */
+        return BLE_HS_ENOMEM_HCI;
+    }
+
+    opcode = (ogf << 10) | ocf;
+    htole16(cmd, opcode);
+    cmd[2] = len;
+    if (len) {
+        memcpy(cmd + BLE_HCI_CMD_HDR_LEN, cmddata, len);
     }
+    rc = host_hci_cmd_transport(cmd);
+    BLE_HS_LOG(DEBUG, "host_hci_cmd_send: ogf=0x%02x ocf=0x%02x len=%d "
+                      "rc=%d\n", ogf, ocf, len, rc);
+    ble_hs_misc_log_flat_buf(cmd, len + BLE_HCI_CMD_HDR_LEN);
+    BLE_HS_LOG(DEBUG, "\n");
 
     if (rc == 0) {
         STATS_INC(ble_hs_stats, hci_cmd);


[26/50] [abbrv] incubator-mynewt-core git commit: sys/config; change export function prototype. Added argument which tells whether module should export variables it wants to persist, or variables it wants to display.

Posted by cc...@apache.org.
sys/config; change export function prototype.
Added argument which tells whether module should export variables
it wants to persist, or variables it wants to display.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/9490ca70
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/9490ca70
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/9490ca70

Branch: refs/heads/master
Commit: 9490ca7056298b0b00e33a6f59b91ec0e7fbd4aa
Parents: 93f2e11
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Mon Jun 27 15:26:56 2016 -0700
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Jun 27 15:26:56 2016 -0700

----------------------------------------------------------------------
 apps/slinky/src/main.c             |  5 +++--
 sys/config/include/config/config.h |  8 +++++++-
 sys/config/src/config_cli.c        |  2 +-
 sys/config/src/config_store.c      |  2 +-
 sys/config/src/test/conf_test.c    | 18 ++++++++++++------
 5 files changed, 24 insertions(+), 11 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/9490ca70/apps/slinky/src/main.c
----------------------------------------------------------------------
diff --git a/apps/slinky/src/main.c b/apps/slinky/src/main.c
index 569f040..59c569d 100755
--- a/apps/slinky/src/main.c
+++ b/apps/slinky/src/main.c
@@ -131,7 +131,8 @@ struct os_mempool default_mbuf_mpool;
 static char *test_conf_get(int argc, char **argv, char *val, int max_len);
 static int test_conf_set(int argc, char **argv, char *val);
 static int test_conf_commit(void);
-static int test_conf_export(void (*export_func)(char *name, char *val));
+static int test_conf_export(void (*export_func)(char *name, char *val),
+  enum conf_export_tgt tgt);
 
 static struct conf_handler test_conf_handler = {
     .ch_name = "test",
@@ -182,7 +183,7 @@ test_conf_commit(void)
 }
 
 static int
-test_conf_export(void (*func)(char *name, char *val))
+test_conf_export(void (*func)(char *name, char *val), enum conf_export_tgt tgt)
 {
     char buf[4];
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/9490ca70/sys/config/include/config/config.h
----------------------------------------------------------------------
diff --git a/sys/config/include/config/config.h b/sys/config/include/config/config.h
index b0bc8aa..3402b46 100644
--- a/sys/config/include/config/config.h
+++ b/sys/config/include/config/config.h
@@ -42,13 +42,19 @@ enum conf_type {
     CONF_DOUBLE
 } __attribute__((__packed__));
 
+enum conf_export_tgt {
+    CONF_EXPORT_PERSIST,        /* Value is to be persisted. */
+    CONF_EXPORT_SHOW            /* Value is to be displayed. */
+};
+
 struct conf_handler {
     SLIST_ENTRY(conf_handler) ch_list;
     char *ch_name;
     char *(*ch_get)(int argc, char **argv, char *val, int val_len_max);
     int (*ch_set)(int argc, char **argv, char *val);
     int (*ch_commit)(void);
-    int (*ch_export)(void (*export_func)(char *name, char *val));
+    int (*ch_export)(void (*export_func)(char *name, char *val),
+      enum conf_export_tgt tgt);
 };
 
 int conf_init(void);

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/9490ca70/sys/config/src/config_cli.c
----------------------------------------------------------------------
diff --git a/sys/config/src/config_cli.c b/sys/config/src/config_cli.c
index 7c39598..2923845 100644
--- a/sys/config/src/config_cli.c
+++ b/sys/config/src/config_cli.c
@@ -48,7 +48,7 @@ conf_dump_running(void)
 
     SLIST_FOREACH(ch, &conf_handlers, ch_list) {
         if (ch->ch_export) {
-            ch->ch_export(conf_running_one);
+            ch->ch_export(conf_running_one, CONF_EXPORT_SHOW);
         }
     }
 }

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/9490ca70/sys/config/src/config_store.c
----------------------------------------------------------------------
diff --git a/sys/config/src/config_store.c b/sys/config/src/config_store.c
index 6bd94a1..87f9955 100644
--- a/sys/config/src/config_store.c
+++ b/sys/config/src/config_store.c
@@ -159,7 +159,7 @@ conf_save(void)
     rc = 0;
     SLIST_FOREACH(ch, &conf_handlers, ch_list) {
         if (ch->ch_export) {
-            rc2 = ch->ch_export(conf_store_one);
+            rc2 = ch->ch_export(conf_store_one, CONF_EXPORT_PERSIST);
             if (!rc) {
                 rc = rc2;
             }

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/9490ca70/sys/config/src/test/conf_test.c
----------------------------------------------------------------------
diff --git a/sys/config/src/test/conf_test.c b/sys/config/src/test/conf_test.c
index 35ed588..cde1cca 100644
--- a/sys/config/src/test/conf_test.c
+++ b/sys/config/src/test/conf_test.c
@@ -46,15 +46,18 @@ static char *ctest_handle_get(int argc, char **argv, char *val,
   int val_len_max);
 static int ctest_handle_set(int argc, char **argv, char *val);
 static int ctest_handle_commit(void);
-static int ctest_handle_export(void (*cb)(char *name, char *value));
+static int ctest_handle_export(void (*cb)(char *name, char *value),
+  enum conf_export_tgt tgt);
 static char *c2_handle_get(int argc, char **argv, char *val,
   int val_len_max);
 static int c2_handle_set(int argc, char **argv, char *val);
-static int c2_handle_export(void (*cb)(char *name, char *value));
+static int c2_handle_export(void (*cb)(char *name, char *value),
+  enum conf_export_tgt tgt);
 static char *c3_handle_get(int argc, char **argv, char *val,
   int val_len_max);
 static int c3_handle_set(int argc, char **argv, char *val);
-static int c3_handle_export(void (*cb)(char *name, char *value));
+static int c3_handle_export(void (*cb)(char *name, char *value),
+  enum conf_export_tgt tgt);
 
 struct conf_handler config_test_handler = {
     .ch_name = "myfoo",
@@ -98,7 +101,8 @@ ctest_handle_commit(void)
 }
 
 static int
-ctest_handle_export(void (*cb)(char *name, char *value))
+ctest_handle_export(void (*cb)(char *name, char *value),
+  enum conf_export_tgt tgt)
 {
     char value[32];
 
@@ -177,7 +181,8 @@ c2_handle_set(int argc, char **argv, char *val)
 }
 
 static int
-c2_handle_export(void (*cb)(char *name, char *value))
+c2_handle_export(void (*cb)(char *name, char *value),
+  enum conf_export_tgt tgt)
 {
     int i;
     char name[32];
@@ -222,7 +227,8 @@ c3_handle_set(int argc, char **argv, char *val)
 }
 
 static int
-c3_handle_export(void (*cb)(char *name, char *value))
+c3_handle_export(void (*cb)(char *name, char *value),
+  enum conf_export_tgt tgt)
 {
     char value[32];
 


[49/50] [abbrv] incubator-mynewt-core git commit: Merge branch 'nffs-update' into develop This closes #64.

Posted by cc...@apache.org.
Merge branch 'nffs-update' into develop
This closes #64.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/e9f0c16e
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/e9f0c16e
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/e9f0c16e

Branch: refs/heads/master
Commit: e9f0c16e48b883288678ba0391632a18ffaa7a79
Parents: 53d7e65 5cc8548
Author: Christopher Collins <cc...@apache.org>
Authored: Fri Jul 8 10:38:34 2016 -0700
Committer: Christopher Collins <cc...@apache.org>
Committed: Fri Jul 8 10:38:34 2016 -0700

----------------------------------------------------------------------
 apps/ffs2native/src/main.c            | 411 ++++++++++++++++---
 fs/nffs/src/nffs.c                    |   1 +
 fs/nffs/src/nffs_area.c               |   6 +
 fs/nffs/src/nffs_block.c              |  43 +-
 fs/nffs/src/nffs_dir.c                |   4 +-
 fs/nffs/src/nffs_file.c               |   7 +-
 fs/nffs/src/nffs_format.c             |   2 +
 fs/nffs/src/nffs_gc.c                 |   5 +-
 fs/nffs/src/nffs_hash.c               |  68 +++-
 fs/nffs/src/nffs_inode.c              | 216 +++++++++-
 fs/nffs/src/nffs_misc.c               |   5 +-
 fs/nffs/src/nffs_path.c               |  13 +
 fs/nffs/src/nffs_priv.h               |  59 ++-
 fs/nffs/src/nffs_restore.c            | 617 ++++++++++++++++++++---------
 fs/nffs/src/nffs_write.c              |  13 +-
 fs/nffs/src/test/arch/sim/nffs_test.c | 599 +++++++++++++++++++++++++++-
 16 files changed, 1791 insertions(+), 278 deletions(-)
----------------------------------------------------------------------



[33/50] [abbrv] incubator-mynewt-core git commit: Implement file lastblock caching in flash

Posted by cc...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/f9ef5686/fs/nffs/src/test/arch/sim/nffs_test.c
----------------------------------------------------------------------
diff --git a/fs/nffs/src/test/arch/sim/nffs_test.c b/fs/nffs/src/test/arch/sim/nffs_test.c
index ef9eaa6..a61b4bc 100644
--- a/fs/nffs/src/test/arch/sim/nffs_test.c
+++ b/fs/nffs/src/test/arch/sim/nffs_test.c
@@ -369,6 +369,9 @@ static struct nffs_hash_entry
     *nffs_test_touched_entries[NFFS_TEST_TOUCHED_ARR_SZ];
 static int nffs_test_num_touched_entries;
 
+/*
+ * Recursively descend directory structure
+ */
 static void
 nffs_test_assert_file(const struct nffs_test_file_desc *file,
                      struct nffs_inode_entry *inode_entry,
@@ -382,6 +385,9 @@ nffs_test_assert_file(const struct nffs_test_file_desc *file,
     int path_len;
     int rc;
 
+    /*
+     * track of hash entries that have been examined
+     */
     TEST_ASSERT(nffs_test_num_touched_entries < NFFS_TEST_TOUCHED_ARR_SZ);
     nffs_test_touched_entries[nffs_test_num_touched_entries] =
         &inode_entry->nie_hash_entry;
@@ -392,11 +398,18 @@ nffs_test_assert_file(const struct nffs_test_file_desc *file,
     rc = nffs_inode_from_entry(&inode, inode_entry);
     TEST_ASSERT(rc == 0);
 
+    /*
+     * recursively examine each child of directory
+     */
     if (nffs_hash_id_is_dir(inode_entry->nie_hash_entry.nhe_id)) {
         for (child_file = file->children;
              child_file != NULL && child_file->filename != NULL;
              child_file++) {
 
+            /*
+             * Construct full pathname for file
+             * Not null terminated
+             */
             child_filename_len = strlen(child_file->filename);
             child_path = malloc(path_len + 1 + child_filename_len + 1);
             TEST_ASSERT(child_path != NULL);
@@ -406,8 +419,13 @@ nffs_test_assert_file(const struct nffs_test_file_desc *file,
                    child_filename_len);
             child_path[path_len + 1 + child_filename_len] = '\0';
 
+            /*
+             * Verify child inode can be found using full pathname
+             */
             rc = nffs_path_find_inode_entry(child_path, &child_inode_entry);
-            TEST_ASSERT(rc == 0);
+            if (rc != 0) {
+                TEST_ASSERT(rc == 0);
+            }
 
             nffs_test_assert_file(child_file, child_inode_entry, child_path);
 
@@ -434,7 +452,7 @@ nffs_test_assert_branch_touched(struct nffs_inode_entry *inode_entry)
             break;
         }
     }
-	TEST_ASSERT(i < nffs_test_num_touched_entries);
+    TEST_ASSERT(i < nffs_test_num_touched_entries);
     nffs_test_touched_entries[i] = NULL;
 
     if (nffs_hash_id_is_dir(inode_entry->nie_hash_entry.nhe_id)) {
@@ -452,13 +470,22 @@ nffs_test_assert_child_inode_present(struct nffs_inode_entry *child)
     struct nffs_inode inode;
     int rc;
 
+    /*
+     * Sucessfully read inode data from flash
+     */
     rc = nffs_inode_from_entry(&inode, child);
     TEST_ASSERT(rc == 0);
 
+    /*
+     * Validate parent
+     */
     parent = inode.ni_parent;
     TEST_ASSERT(parent != NULL);
     TEST_ASSERT(nffs_hash_id_is_dir(parent->nie_hash_entry.nhe_id));
 
+    /*
+     * Make sure inode is in parents child list
+     */
     SLIST_FOREACH(inode_entry, &parent->nie_child_list, nie_sibling_next) {
         if (inode_entry == child) {
             return;
@@ -476,13 +503,22 @@ nffs_test_assert_block_present(struct nffs_hash_entry *block_entry)
     struct nffs_block block;
     int rc;
 
+    /*
+     * Successfully read block data from flash
+     */
     rc = nffs_block_from_hash_entry(&block, block_entry);
     TEST_ASSERT(rc == 0);
 
+    /*
+     * Validate owning inode
+     */
     inode_entry = block.nb_inode_entry;
     TEST_ASSERT(inode_entry != NULL);
     TEST_ASSERT(nffs_hash_id_is_file(inode_entry->nie_hash_entry.nhe_id));
 
+    /*
+     * Validate that block is in owning inode's block chain
+     */
     cur = inode_entry->nie_last_block_entry;
     while (cur != NULL) {
         if (cur == block_entry) {
@@ -497,6 +533,10 @@ nffs_test_assert_block_present(struct nffs_hash_entry *block_entry)
     TEST_ASSERT(0);
 }
 
+/*
+ * Recursively verify that the children of each directory are sorted
+ * on the directory children linked list by filename length
+ */
 static void
 nffs_test_assert_children_sorted(struct nffs_inode_entry *inode_entry)
 {
@@ -1946,6 +1986,13 @@ TEST_CASE(nffs_test_corrupt_scratch)
     nffs_test_assert_system(expected_system, area_descs_two);
 }
 
+/*
+ * This test no longer works with the current implementation. The
+ * expectation is that intermediate blocks can be removed and the old
+ * method of finding the last current block after restore will allow the
+ * file to be salvaged. Instead, the file should be removed and all data
+ * declared invalid.
+ */
 TEST_CASE(nffs_test_incomplete_block)
 {
     struct nffs_block block;
@@ -1984,9 +2031,9 @@ TEST_CASE(nffs_test_incomplete_block)
     nffs_flash_loc_expand(block.nb_hash_entry->nhe_flash_loc, &area_idx,
                          &area_offset);
     flash_offset = nffs_areas[area_idx].na_offset + area_offset;
-	/*
-	 * Overwrite block data - the CRC check should pick this up
-	 */
+    /*
+     * Overwrite block data - the CRC check should pick this up
+     */
     rc = flash_native_memset(
             flash_offset + sizeof (struct nffs_disk_block) + 2, 0xff, 2);
     TEST_ASSERT(rc == 0);
@@ -1996,8 +2043,14 @@ TEST_CASE(nffs_test_incomplete_block)
     rc = nffs_detect(nffs_area_descs);
     TEST_ASSERT(rc == 0);
 
-    /* The entire second block should be removed; the file should only contain
-     * the first block.
+    /* OLD: The entire second block should be removed; the file should only
+     * contain the first block.
+     * Unless we can salvage the block, the entire file should probably be
+     * removed. This is a contrived example which generates bad data on the
+     * what happens to be the last block, but corruption can actually occur
+     * in any block. Sweep should be updated to search look for blocks that
+     * don't have a correct prev_id and then decide whether to delete the
+     * owning inode. XXX
      */
     struct nffs_test_file_desc *expected_system =
         (struct nffs_test_file_desc[]) { {
@@ -2010,10 +2063,13 @@ TEST_CASE(nffs_test_incomplete_block)
                     .filename = "a",
                     .contents = "aaaa",
                     .contents_len = 4,
+#if 0
+/* keep this out until sweep updated to capture bad blocks XXX */
                 }, {
                     .filename = "b",
                     .contents = "bbbb",
                     .contents_len = 4,
+#endif
                 }, {
                     .filename = "c",
                     .contents = "cccc",
@@ -2037,9 +2093,9 @@ TEST_CASE(nffs_test_corrupt_block)
     uint32_t flash_offset;
     uint32_t area_offset;
     uint8_t area_idx;
-	uint8_t off;	/* offset to corrupt */
+    uint8_t off;    /* offset to corrupt */
     int rc;
-	struct nffs_disk_block ndb;
+    struct nffs_disk_block ndb;
 
     /*** Setup. */
     rc = nffs_format(nffs_area_descs);
@@ -2068,10 +2124,10 @@ TEST_CASE(nffs_test_corrupt_block)
                          &area_offset);
     flash_offset = nffs_areas[area_idx].na_offset + area_offset;
 
-	/*
-	 * Overwriting the reserved8 field should invalidate the CRC
-	 */
-	off = (char*)&ndb.reserved16 - (char*)&ndb;
+    /*
+     * Overwriting the reserved16 field should invalidate the CRC
+     */
+    off = (char*)&ndb.reserved16 - (char*)&ndb;
     rc = flash_native_memset(flash_offset + off, 0x43, 1);
 
     TEST_ASSERT(rc == 0);
@@ -2100,10 +2156,17 @@ TEST_CASE(nffs_test_corrupt_block)
                     .filename = "a",
                     .contents = "aaaa",
                     .contents_len = 4,
+#if 0
+                /*
+                 * In the newer implementation without the find_file_ends
+                 * corrupted inodes are deleted rather than retained with
+                 * partial contents
+                 */
                 }, {
                     .filename = "b",
                     .contents = "bbbb",
                     .contents_len = 4,
+#endif
                 }, {
                     .filename = "c",
                     .contents = "cccc",
@@ -2216,8 +2279,8 @@ TEST_CASE(nffs_test_lost_found)
     uint32_t area_offset;
     uint8_t area_idx;
     int rc;
-	struct nffs_disk_inode ndi;
-	uint8_t off;	/* calculated offset for memset */
+    struct nffs_disk_inode ndi;
+    uint8_t off;    /* calculated offset for memset */
 
     /*** Setup. */
     rc = nffs_format(nffs_area_descs);
@@ -2241,11 +2304,11 @@ TEST_CASE(nffs_test_lost_found)
     nffs_flash_loc_expand(inode_entry->nie_hash_entry.nhe_flash_loc,
                          &area_idx, &area_offset);
     flash_offset = nffs_areas[area_idx].na_offset + area_offset;
-	/*
-	 * Overwrite the sequence number - should be detected as CRC corruption
-	 */
-	off = (char*)&ndi.ndi_seq - (char*)&ndi;
-    rc = flash_native_memset(flash_offset + off, 0xff, 1);
+    /*
+     * Overwrite the sequence number - should be detected as CRC corruption
+     */
+    off = (char*)&ndi.ndi_seq - (char*)&ndi;
+    rc = flash_native_memset(flash_offset + off, 0xaa, 1);
     TEST_ASSERT(rc == 0);
 
     /* Clear cached data and restore from flash (i.e, simulate a reboot). */
@@ -2262,6 +2325,7 @@ TEST_CASE(nffs_test_lost_found)
             .children = (struct nffs_test_file_desc[]) { {
                 .filename = "lost+found",
                 .is_dir = 1,
+#if 0
                 .children = (struct nffs_test_file_desc[]) { {
                     .filename = buf,
                     .is_dir = 1,
@@ -2285,6 +2349,7 @@ TEST_CASE(nffs_test_lost_found)
                 }, {
                     .filename = NULL,
                 } },
+#endif
             }, {
                 .filename = NULL,
             } }
@@ -2663,6 +2728,510 @@ nffs_test_all(void)
     return tu_any_failed;
 }
 
+void
+print_inode_entry(struct nffs_inode_entry *inode_entry, int indent)
+{
+    struct nffs_inode inode;
+    char name[NFFS_FILENAME_MAX_LEN + 1];
+    uint32_t area_offset;
+    uint8_t area_idx;
+    int rc;
+
+    if (inode_entry == nffs_root_dir) {
+        printf("%*s/\n", indent, "");
+        return;
+    }
+
+    rc = nffs_inode_from_entry(&inode, inode_entry);
+    /*
+     * Dummy inode
+     */
+    if (rc == FS_ENOENT) {
+        printf("    DUMMY %d\n", rc);
+        return;
+    }
+
+    nffs_flash_loc_expand(inode_entry->nie_hash_entry.nhe_flash_loc,
+                         &area_idx, &area_offset);
+
+    rc = nffs_flash_read(area_idx,
+                         area_offset + sizeof (struct nffs_disk_inode),
+                         name, inode.ni_filename_len);
+
+    name[inode.ni_filename_len] = '\0';
+
+    printf("%*s%s\n", indent, "", name[0] == '\0' ? "/" : name);
+}
+
+void
+process_inode_entry(struct nffs_inode_entry *inode_entry, int indent)
+{
+    struct nffs_inode_entry *child;
+
+    print_inode_entry(inode_entry, indent);
+
+    if (nffs_hash_id_is_dir(inode_entry->nie_hash_entry.nhe_id)) {
+        SLIST_FOREACH(child, &inode_entry->nie_child_list, nie_sibling_next) {
+            process_inode_entry(child, indent + 2);
+        }
+    }
+}
+
+int
+print_nffs_flash_inode(struct nffs_area *area, uint32_t off)
+{
+    struct nffs_disk_inode ndi;
+    char filename[128];
+    int len;
+    int rc;
+
+    rc = hal_flash_read(area->na_flash_id, area->na_offset + off,
+                         &ndi, sizeof(ndi));
+    assert(rc == 0);
+
+    memset(filename, 0, sizeof(filename));
+    len = min(sizeof(filename) - 1, ndi.ndi_filename_len);
+    rc = hal_flash_read(area->na_flash_id, area->na_offset + off + sizeof(ndi),
+                         filename, len);
+
+    printf("  off %x %s id %x flen %d seq %d last %x prnt %x flgs %x %s\n",
+           off,
+           (nffs_hash_id_is_file(ndi.ndi_id) ? "File" :
+            (nffs_hash_id_is_dir(ndi.ndi_id) ? "Dir" : "???")),
+           ndi.ndi_id,
+           ndi.ndi_filename_len,
+           ndi.ndi_seq,
+           ndi.ndi_lastblock_id,
+           ndi.ndi_parent_id,
+           ndi.ndi_flags,
+           filename);
+    return sizeof(ndi) + ndi.ndi_filename_len;
+}
+
+int
+print_nffs_flash_block(struct nffs_area *area, uint32_t off)
+{
+    struct nffs_disk_block ndb;
+    int rc;
+
+    rc = hal_flash_read(area->na_flash_id, area->na_offset + off,
+                        &ndb, sizeof(ndb));
+    assert(rc == 0);
+
+    printf("  off %x Block id %x len %d seq %d prev %x own ino %x\n",
+           off,
+           ndb.ndb_id,
+           ndb.ndb_data_len,
+           ndb.ndb_seq,
+           ndb.ndb_prev_id,
+           ndb.ndb_inode_id);
+    return sizeof(ndb) + ndb.ndb_data_len;
+}
+
+int
+print_nffs_flash_object(struct nffs_area *area, uint32_t off)
+{
+    struct nffs_disk_object ndo;
+
+    hal_flash_read(area->na_flash_id, area->na_offset + off,
+                        &ndo.ndo_un_obj, sizeof(ndo.ndo_un_obj));
+
+    if (nffs_hash_id_is_inode(ndo.ndo_disk_inode.ndi_id)) {
+        return print_nffs_flash_inode(area, off);
+
+    } else if (nffs_hash_id_is_block(ndo.ndo_disk_block.ndb_id)) {
+        return print_nffs_flash_block(area, off);
+
+    } else if (ndo.ndo_disk_block.ndb_id == 0xffffffff) {
+        return area->na_length;
+
+    } else {
+        return 1;
+    }
+}
+
+void
+print_nffs_flash_areas(int verbose)
+{
+    struct nffs_area area;
+    struct nffs_disk_area darea;
+    int off;
+    int i;
+
+    for (i = 0; nffs_current_area_descs[i].nad_length != 0; i++) {
+        if (i > NFFS_MAX_AREAS) {
+            return;
+        }
+        area.na_offset = nffs_current_area_descs[i].nad_offset;
+        area.na_length = nffs_current_area_descs[i].nad_length;
+        area.na_flash_id = nffs_current_area_descs[i].nad_flash_id;
+        hal_flash_read(area.na_flash_id, area.na_offset, &darea, sizeof(darea));
+        area.na_id = darea.nda_id;
+        area.na_cur = nffs_areas[i].na_cur;
+        if (!nffs_area_magic_is_set(&darea)) {
+            printf("Area header corrupt!\n");
+        }
+        printf("area %d: id %d %x-%x cur %x len %d flashid %x gc-seq %d %s%s\n",
+               i, area.na_id, area.na_offset, area.na_offset + area.na_length,
+               area.na_cur, area.na_length, area.na_flash_id, darea.nda_gc_seq,
+               nffs_scratch_area_idx == i ? "(scratch)" : "",
+               !nffs_area_magic_is_set(&darea) ? "corrupt" : "");
+        if (verbose < 2) {
+            off = sizeof (struct nffs_disk_area);
+            while (off < area.na_length) {
+                off += print_nffs_flash_object(&area, off);
+            }
+        }
+    }
+}
+
+static int
+nffs_hash_fn(uint32_t id)
+{
+    return id % NFFS_HASH_SIZE;
+}
+
+void
+print_hashlist(struct nffs_hash_entry *he)
+{
+    struct nffs_hash_list *list;
+    int idx = nffs_hash_fn(he->nhe_id);
+    list = nffs_hash + idx;
+
+    SLIST_FOREACH(he, list, nhe_next) {
+        printf("hash_entry %s 0x%x: id 0x%x flash_loc 0x%x next 0x%x\n",
+                   nffs_hash_id_is_inode(he->nhe_id) ? "inode" : "block",
+                   (unsigned int)he,
+                   he->nhe_id, he->nhe_flash_loc,
+                   (unsigned int)he->nhe_next.sle_next);
+   }
+}
+
+void
+print_hash(void)
+{
+    int i;
+    struct nffs_hash_entry *he;
+    struct nffs_hash_entry *next;
+    struct nffs_inode ni;
+    struct nffs_disk_inode di;
+    struct nffs_block nb;
+    struct nffs_disk_block db;
+    uint32_t area_offset;
+    uint8_t area_idx;
+    int rc;
+
+    NFFS_HASH_FOREACH(he, i, next) {
+        if (nffs_hash_id_is_inode(he->nhe_id)) {
+            printf("hash_entry inode %d 0x%x: id 0x%x flash_loc 0x%x next 0x%x\n",
+                   i, (unsigned int)he,
+                   he->nhe_id, he->nhe_flash_loc,
+                   (unsigned int)he->nhe_next.sle_next);
+            if (he->nhe_id == NFFS_ID_ROOT_DIR) {
+                continue;
+            }
+            nffs_flash_loc_expand(he->nhe_flash_loc,
+                                  &area_idx, &area_offset);
+            rc = nffs_inode_read_disk(area_idx, area_offset, &di);
+            if (rc) {
+                printf("%d: fail inode read id 0x%x rc %d\n",
+                       i, he->nhe_id, rc);
+            }
+            printf("    Disk inode: id %x seq %d parent %x last %x flgs %x\n",
+                   di.ndi_id,
+                   di.ndi_seq,
+                   di.ndi_parent_id,
+                   di.ndi_lastblock_id,
+                   di.ndi_flags);
+            ni.ni_inode_entry = (struct nffs_inode_entry *)he;
+            ni.ni_seq = di.ndi_seq; 
+            ni.ni_parent = nffs_hash_find_inode(di.ndi_parent_id);
+            printf("    RAM inode: entry 0x%x seq %d parent %x filename %s\n",
+                   (unsigned int)ni.ni_inode_entry,
+                   ni.ni_seq,
+                   (unsigned int)ni.ni_parent,
+                   ni.ni_filename);
+
+        } else if (nffs_hash_id_is_block(he->nhe_id)) {
+            printf("hash_entry block %d 0x%x: id 0x%x flash_loc 0x%x next 0x%x\n",
+                   i, (unsigned int)he,
+                   he->nhe_id, he->nhe_flash_loc,
+                   (unsigned int)he->nhe_next.sle_next);
+            rc = nffs_block_from_hash_entry(&nb, he);
+            if (rc) {
+                printf("%d: fail block read id 0x%x rc %d\n",
+                       i, he->nhe_id, rc);
+            }
+            printf("    block: id %x seq %d inode %x prev %x\n",
+                   nb.nb_hash_entry->nhe_id, nb.nb_seq, 
+                   nb.nb_inode_entry->nie_hash_entry.nhe_id, 
+                   nb.nb_prev->nhe_id);
+            nffs_flash_loc_expand(nb.nb_hash_entry->nhe_flash_loc,
+                                  &area_idx, &area_offset);
+            rc = nffs_block_read_disk(area_idx, area_offset, &db);
+            if (rc) {
+                printf("%d: fail disk block read id 0x%x rc %d\n",
+                       i, nb.nb_hash_entry->nhe_id, rc);
+            }
+            printf("    disk block: id %x seq %d inode %x prev %x len %d\n",
+                   db.ndb_id,
+                   db.ndb_seq,
+                   db.ndb_inode_id,
+                   db.ndb_prev_id,
+                   db.ndb_data_len);
+        } else {
+            printf("hash_entry UNKNONN %d 0x%x: id 0x%x flash_loc 0x%x next 0x%x\n",
+                   i, (unsigned int)he,
+                   he->nhe_id, he->nhe_flash_loc,
+                   (unsigned int)he->nhe_next.sle_next);
+        }
+    }
+
+}
+
+void
+nffs_print_object(struct nffs_disk_object *dobj)
+{
+    struct nffs_disk_inode *di = &dobj->ndo_disk_inode;
+    struct nffs_disk_block *db = &dobj->ndo_disk_block;
+
+    if (dobj->ndo_type == NFFS_OBJECT_TYPE_INODE) {
+        printf("    %s id %x seq %d prnt %x last %x\n",
+               nffs_hash_id_is_file(di->ndi_id) ? "File" :
+                nffs_hash_id_is_dir(di->ndi_id) ? "Dir" : "???",
+               di->ndi_id, di->ndi_seq, di->ndi_parent_id,
+               di->ndi_lastblock_id);
+    } else if (dobj->ndo_type != NFFS_OBJECT_TYPE_BLOCK) {
+        printf("    %s: id %x seq %d ino %x prev %x len %d\n",
+               nffs_hash_id_is_block(db->ndb_id) ? "Block" : "Block?",
+               db->ndb_id, db->ndb_seq, db->ndb_inode_id,
+               db->ndb_prev_id, db->ndb_data_len);
+    }
+}
+
+void
+print_nffs_hash_block(struct nffs_hash_entry *he, int verbose)
+{
+    struct nffs_block nb;
+    struct nffs_disk_block db;
+    uint32_t area_offset;
+    uint8_t area_idx;
+    int rc;
+
+    if (he == NULL) {
+        return;
+    }
+    if (!nffs_hash_entry_is_dummy(he)) {
+        nffs_flash_loc_expand(he->nhe_flash_loc,
+                              &area_idx, &area_offset);
+        rc = nffs_block_read_disk(area_idx, area_offset, &db);
+        if (rc) {
+            printf("%p: fail block read id 0x%x rc %d\n",
+                   he, he->nhe_id, rc);
+        }
+        nb.nb_hash_entry = he;
+        nb.nb_seq = db.ndb_seq;
+        if (db.ndb_inode_id != NFFS_ID_NONE) {
+            nb.nb_inode_entry = nffs_hash_find_inode(db.ndb_inode_id);
+        } else {
+            nb.nb_inode_entry = (void*)db.ndb_inode_id;
+        }
+        if (db.ndb_prev_id != NFFS_ID_NONE) {
+            nb.nb_prev = nffs_hash_find_block(db.ndb_prev_id);
+        } else {
+            nb.nb_prev = (void*)db.ndb_prev_id;
+        }
+        nb.nb_data_len = db.ndb_data_len;
+    } else {
+        nb.nb_inode_entry = NULL;
+        db.ndb_id = 0;
+    }
+    if (!verbose) {
+        printf("%s%s id %x idx/off %d/%x seq %d ino %x prev %x len %d\n",
+               nffs_hash_entry_is_dummy(he) ? "Dummy " : "",
+               nffs_hash_id_is_block(he->nhe_id) ? "Block" : "Unknown",
+               he->nhe_id, area_idx, area_offset, nb.nb_seq,
+               nb.nb_inode_entry->nie_hash_entry.nhe_id,
+               (unsigned int)db.ndb_prev_id, db.ndb_data_len);
+        return;
+    }
+    printf("%s%s id %x loc %x/%x %x ent %p\n",
+           nffs_hash_entry_is_dummy(he) ? "Dummy " : "",
+           nffs_hash_id_is_block(he->nhe_id) ? "Block:" : "Unknown:",
+           he->nhe_id, area_idx, area_offset, he->nhe_flash_loc, he);
+    if (nb.nb_inode_entry) {
+        printf("  Ram: ent %p seq %d ino %p prev %p len %d\n",
+               nb.nb_hash_entry, nb.nb_seq,
+               nb.nb_inode_entry, nb.nb_prev, nb.nb_data_len);
+    }
+    if (db.ndb_id) {
+        printf("  Disk %s id %x seq %d ino %x prev %x len %d\n",
+               nffs_hash_id_is_block(db.ndb_id) ? "Block:" : "???:",
+               db.ndb_id, db.ndb_seq, db.ndb_inode_id,
+               db.ndb_prev_id, db.ndb_data_len);
+    }
+}
+
+void
+print_nffs_hash_inode(struct nffs_hash_entry *he, int verbose)
+{
+    struct nffs_inode ni;
+    struct nffs_disk_inode di;
+    struct nffs_inode_entry *nie = (struct nffs_inode_entry*)he;
+    int cached_name_len;
+    uint32_t area_offset;
+    uint8_t area_idx;
+    int rc;
+
+    if (he == NULL) {
+        return;
+    }
+    if (!nffs_hash_entry_is_dummy(he)) {
+        nffs_flash_loc_expand(he->nhe_flash_loc,
+                              &area_idx, &area_offset);
+        rc = nffs_inode_read_disk(area_idx, area_offset, &di);
+        if (rc) {
+            printf("Entry %p: fail inode read id 0x%x rc %d\n",
+                   he, he->nhe_id, rc);
+        }
+        ni.ni_inode_entry = (struct nffs_inode_entry *)he;
+        ni.ni_seq = di.ndi_seq; 
+        if (di.ndi_parent_id != NFFS_ID_NONE) {
+            ni.ni_parent = nffs_hash_find_inode(di.ndi_parent_id);
+        } else {
+            ni.ni_parent = NULL;
+        }
+        if (ni.ni_filename_len > NFFS_SHORT_FILENAME_LEN) {
+            cached_name_len = NFFS_SHORT_FILENAME_LEN;
+        } else {
+            cached_name_len = ni.ni_filename_len;
+        }
+        if (cached_name_len != 0) {
+            rc = nffs_flash_read(area_idx, area_offset + sizeof di,
+                         ni.ni_filename, cached_name_len);
+            if (rc != 0) {
+                printf("entry %p: fail filename read id 0x%x rc %d\n",
+                       he, he->nhe_id, rc);
+                return;
+            }
+        }
+    } else {
+        ni.ni_inode_entry = NULL;
+        di.ndi_id = 0;
+    }
+    if (!verbose) {
+        printf("%s%s id %x idx/off %x/%x seq %d prnt %x last %x flags %x",
+               nffs_hash_entry_is_dummy(he) ? "Dummy " : "",
+
+               nffs_hash_id_is_file(he->nhe_id) ? "File" :
+                he->nhe_id == NFFS_ID_ROOT_DIR ? "**ROOT Dir" : 
+                nffs_hash_id_is_dir(he->nhe_id) ? "Dir" : "Inode",
+
+               he->nhe_id, area_idx, area_offset, ni.ni_seq, di.ndi_parent_id,
+               di.ndi_lastblock_id, nie->nie_flags);
+        if (ni.ni_inode_entry) {
+            printf(" ref %d\n", ni.ni_inode_entry->nie_refcnt);
+        } else {
+            printf("\n");
+        }
+        return;
+    }
+    printf("%s%s id %x loc %x/%x %x entry %p\n",
+           nffs_hash_entry_is_dummy(he) ? "Dummy " : "",
+           nffs_hash_id_is_file(he->nhe_id) ? "File:" :
+            he->nhe_id == NFFS_ID_ROOT_DIR ? "**ROOT Dir:" : 
+            nffs_hash_id_is_dir(he->nhe_id) ? "Dir:" : "Inode:",
+           he->nhe_id, area_idx, area_offset, he->nhe_flash_loc, he);
+    if (ni.ni_inode_entry) {
+        printf("  ram: ent %p seq %d prnt %p lst %p ref %d flgs %x nm %s\n",
+               ni.ni_inode_entry, ni.ni_seq, ni.ni_parent,
+               ni.ni_inode_entry->nie_last_block_entry,
+               ni.ni_inode_entry->nie_refcnt, ni.ni_inode_entry->nie_flags,
+               ni.ni_filename);
+    }
+    if (rc == 0) {
+        printf("  Disk %s: id %x seq %d prnt %x lst %x flgs %x\n",
+               nffs_hash_id_is_file(di.ndi_id) ? "File" :
+                nffs_hash_id_is_dir(di.ndi_id) ? "Dir" : "???",
+               di.ndi_id, di.ndi_seq, di.ndi_parent_id,
+               di.ndi_lastblock_id, di.ndi_flags);
+    }
+}
+
+void
+print_hash_entries(int verbose)
+{
+    int i;
+    struct nffs_hash_entry *he;
+    struct nffs_hash_entry *next;
+
+    printf("\nnffs_hash_entries:\n");
+    for (i = 0; i < NFFS_HASH_SIZE; i++) {
+        he = SLIST_FIRST(nffs_hash + i);
+        while (he != NULL) {
+            next = SLIST_NEXT(he, nhe_next);
+            if (nffs_hash_id_is_inode(he->nhe_id)) {
+                print_nffs_hash_inode(he, verbose);
+            } else if (nffs_hash_id_is_block(he->nhe_id)) {
+                print_nffs_hash_block(he, verbose);
+            } else {
+                printf("UNKNOWN type hash entry %d: id 0x%x loc 0x%x\n",
+                       i, he->nhe_id, he->nhe_flash_loc);
+            }
+            he = next;
+        }
+    }
+}
+
+void
+print_nffs_hashlist(int verbose)
+{
+    struct nffs_hash_entry *he;
+    struct nffs_hash_entry *next;
+    int i;
+
+    NFFS_HASH_FOREACH(he, i, next) {
+        if (nffs_hash_id_is_inode(he->nhe_id)) {
+            print_nffs_hash_inode(he, verbose);
+        } else if (nffs_hash_id_is_block(he->nhe_id)) {
+            print_nffs_hash_block(he, verbose);
+        } else {
+            printf("UNKNOWN type hash entry %d: id 0x%x loc 0x%x\n",
+                   i, he->nhe_id, he->nhe_flash_loc);
+        }
+    }
+}
+
+static int print_verbose;
+
+void
+printfs()
+{
+    if (nffs_misc_ready()) {
+        printf("NFFS directory:\n");
+        process_inode_entry(nffs_root_dir, print_verbose);
+
+        printf("\nNFFS hash list:\n");
+        print_nffs_hashlist(print_verbose);
+    }
+    printf("\nNFFS flash areas:\n");
+    print_nffs_flash_areas(print_verbose);
+}
+
+#include <unistd.h>
+
+#if 0
+void
+nffs_assert_handler(const char *file, int line, const char *func, const char *e)
+{
+    char msg[256];
+
+    snprintf(msg, sizeof(msg), "assert at %s:%d\n", file, line);
+    write(1, msg, strlen(msg));
+    _exit(1);
+}
+#endif
+
 #ifdef MYNEWT_SELFTEST
 
 int
@@ -2671,6 +3240,8 @@ main(void)
     tu_config.tc_print_results = 1;
     tu_init();
 
+    print_verbose = 1;
+
     nffs_test_all();
 
     return tu_any_failed;


[18/50] [abbrv] incubator-mynewt-core git commit: MYNEWT-79: move common hal code from mcu to hal

Posted by cc...@apache.org.
MYNEWT-79: move common hal code from mcu to hal


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/183873d8
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/183873d8
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/183873d8

Branch: refs/heads/master
Commit: 183873d8890de9fb6579dc3a738937c1b1d8006d
Parents: 7bd50b3
Author: William San Filippo <wi...@runtime.io>
Authored: Fri Jun 17 10:46:20 2016 -0700
Committer: William San Filippo <wi...@runtime.io>
Committed: Thu Jun 23 16:39:04 2016 -0700

----------------------------------------------------------------------
 hw/hal/include/hal/hal_cputime.h         |  30 +-
 hw/mcu/native/src/hal_cputime.c          | 385 +++-----------------------
 hw/mcu/nordic/nrf51xxx/src/hal_cputime.c | 308 +--------------------
 hw/mcu/nordic/nrf52xxx/src/hal_cputime.c | 318 +--------------------
 hw/mcu/stm/stm32f4xx/src/hal_cputime.c   | 355 +++---------------------
 5 files changed, 111 insertions(+), 1285 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/183873d8/hw/hal/include/hal/hal_cputime.h
----------------------------------------------------------------------
diff --git a/hw/hal/include/hal/hal_cputime.h b/hw/hal/include/hal/hal_cputime.h
index 63b723b..001bac5 100644
--- a/hw/hal/include/hal/hal_cputime.h
+++ b/hw/hal/include/hal/hal_cputime.h
@@ -38,6 +38,23 @@ struct cpu_timer {
     TAILQ_ENTRY(cpu_timer) link;
 };
 
+/* CPUTIME data. */
+struct cputime_data
+{
+    uint32_t ticks_per_usec;    /* number of ticks per usec */
+    uint32_t cputime_high;      /* high word of 64-bit cpu time */
+    uint32_t timer_isrs;        /* Number of timer interrupts */
+    uint32_t ocmp_ints;         /* Number of ocmp interrupts */
+    uint32_t uif_ints;          /* Number of overflow interrupts */
+};
+extern struct cputime_data g_cputime;
+
+/* Helpful macros to compare cputimes */
+#define CPUTIME_LT(__t1, __t2) ((int32_t)   ((__t1) - (__t2)) < 0)
+#define CPUTIME_GT(__t1, __t2) ((int32_t)   ((__t1) - (__t2)) > 0)
+#define CPUTIME_GEQ(__t1, __t2) ((int32_t)  ((__t1) - (__t2)) >= 0)
+#define CPUTIME_LEQ(__t1, __t2) ((int32_t)  ((__t1) - (__t2)) <= 0)
+
 /**
  * cputime init
  *
@@ -183,11 +200,16 @@ void cputime_timer_relative(struct cpu_timer *timer, uint32_t usecs);
  */
 void cputime_timer_stop(struct cpu_timer *timer);
 
-#define CPUTIME_LT(__t1, __t2) ((int32_t)   ((__t1) - (__t2)) < 0)
-#define CPUTIME_GT(__t1, __t2) ((int32_t)   ((__t1) - (__t2)) > 0)
-#define CPUTIME_GEQ(__t1, __t2) ((int32_t)  ((__t1) - (__t2)) >= 0)
-#define CPUTIME_LEQ(__t1, __t2) ((int32_t)  ((__t1) - (__t2)) <= 0)
+/*
+ * Used between MCU specific files and generic HAL. Not intended as an API
+ * to be called by the user.
+ */
+void cputime_chk_expiration(void);
 
+/*--- HW specific API. These are not intended to be called by user  ---*/
+void cputime_disable_ocmp(void);
+void cputime_set_ocmp(struct cpu_timer *timer);
+int cputime_hw_init(uint32_t clock_freq);
 
 #ifdef __cplusplus
 }

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/183873d8/hw/mcu/native/src/hal_cputime.c
----------------------------------------------------------------------
diff --git a/hw/mcu/native/src/hal_cputime.c b/hw/mcu/native/src/hal_cputime.c
index b493a7d..850bfc5 100644
--- a/hw/mcu/native/src/hal_cputime.c
+++ b/hw/mcu/native/src/hal_cputime.c
@@ -6,7 +6,7 @@
  * to you 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,
@@ -21,21 +21,6 @@
 #include "os/os.h"
 #include "hal/hal_cputime.h"
 
-/* CPUTIME data */
-struct cputime_data
-{
-    uint32_t ticks_per_usec;    /* number of ticks per usec */
-    uint32_t timer_isrs;        /* Number of timer interrupts */
-    uint32_t ocmp_ints;         /* Number of ocmp interrupts */
-    uint32_t uif_ints;          /* Number of overflow interrupts */
-    uint32_t last_ostime;
-    uint64_t cputime;           /* 64-bit cputime */
-};
-struct cputime_data g_cputime;
-
-/* Queue for timers */
-TAILQ_HEAD(cputime_qhead, cpu_timer) g_cputimer_q;
-
 /* For native cpu implementation */
 #define NATIVE_CPUTIME_STACK_SIZE   (1024)
 os_stack_t g_native_cputime_stack[NATIVE_CPUTIME_STACK_SIZE];
@@ -44,15 +29,16 @@ struct os_task g_native_cputime_task;
 struct os_callout_func g_native_cputimer;
 struct os_eventq g_native_cputime_evq;
 static uint32_t g_native_cputime_cputicks_per_ostick;
-
+static uint64_t g_native_cputime;
+static uint32_t g_native_cputime_last_ostime;
 
 /**
  * Convert cpu time ticks to os ticks.
- * 
- * 
- * @param cputicks 
- * 
- * @return uint32_t 
+ *
+ *
+ * @param cputicks
+ *
+ * @return uint32_t
  */
 static uint32_t
 native_cputime_ticks_to_osticks(uint32_t cputicks)
@@ -64,13 +50,13 @@ native_cputime_ticks_to_osticks(uint32_t cputicks)
 }
 
 /**
- * cputime set ocmp 
- *  
- * Set the OCMP used by the cputime module to the desired cputime. 
- * 
+ * cputime set ocmp
+ *
+ * Set the OCMP used by the cputime module to the desired cputime.
+ *
  * @param timer Pointer to timer.
  */
-static void
+void
 cputime_set_ocmp(struct cpu_timer *timer)
 {
     uint32_t curtime;
@@ -88,43 +74,9 @@ cputime_set_ocmp(struct cpu_timer *timer)
 }
 
 /**
- * cputime chk expiration 
- *  
- * Iterates through the cputimer queue to determine if any timers have expired. 
- * If the timer has expired the timer is removed from the queue and the timer 
- * callback function is executed. 
- * 
- */
-static void
-cputime_chk_expiration(void)
-{
-    os_sr_t sr;
-    struct cpu_timer *timer;
-
-    OS_ENTER_CRITICAL(sr);
-    while ((timer = TAILQ_FIRST(&g_cputimer_q)) != NULL) {
-        if ((int32_t)(cputime_get32() - timer->cputime) >= 0) {
-            TAILQ_REMOVE(&g_cputimer_q, timer, link);
-            timer->cb(timer->arg);
-        } else {
-            break;
-        }
-    }
-
-    /* Any timers left on queue? If so, we need to set OCMP */
-    timer = TAILQ_FIRST(&g_cputimer_q);
-    if (timer) {
-        cputime_set_ocmp(timer);
-    } else {
-        os_callout_stop(&g_native_cputimer.cf_c);
-    }
-    OS_EXIT_CRITICAL(sr);
-}
-
-/**
- * This is the function called when the cputimer fires off. 
- * 
- * @param arg 
+ * This is the function called when the cputimer fires off.
+ *
+ * @param arg
  */
 void
 native_cputimer_cb(void *arg)
@@ -158,38 +110,35 @@ native_cputime_task_handler(void *arg)
 }
 
 /**
- * cputime init 
- *  
- * Initialize the cputime module. This must be called after os_init is called 
- * and before any other timer API are used. This should be called only once 
- * and should be called before the hardware timer is used. 
- * 
+ * cputime init
+ *
+ * Initialize the cputime module. This must be called after os_init is called
+ * and before any other timer API are used. This should be called only once
+ * and should be called before the hardware timer is used.
+ *
  * @param clock_freq The desired cputime frequency, in hertz (Hz).
- * 
+ *
  * @return int 0 on success; -1 on error.
  */
 int
-cputime_init(uint32_t clock_freq)
+cputime_hw_init(uint32_t clock_freq)
 {
     /* Clock frequency must be at least 1 MHz */
     if (clock_freq < 1000000U) {
         return -1;
     }
 
-    /* Initialize the timer queue */
-    TAILQ_INIT(&g_cputimer_q);
-
     /* Set the clock frequency */
     g_cputime.ticks_per_usec = clock_freq / 1000000U;
     g_native_cputime_cputicks_per_ostick = clock_freq / OS_TICKS_PER_SEC;
 
-    os_task_init(&g_native_cputime_task, 
-                 "native_cputimer", 
-                 native_cputime_task_handler, 
-                 NULL, 
-                 OS_TASK_PRI_HIGHEST, 
-                 OS_WAIT_FOREVER, 
-                 g_native_cputime_stack, 
+    os_task_init(&g_native_cputime_task,
+                 "native_cputimer",
+                 native_cputime_task_handler,
+                 NULL,
+                 OS_TASK_PRI_HIGHEST,
+                 OS_WAIT_FOREVER,
+                 g_native_cputime_stack,
                  NATIVE_CPUTIME_STACK_SIZE);
 
     /* Initialize the eventq and task */
@@ -206,23 +155,23 @@ cputime_init(uint32_t clock_freq)
 
 /**
  * cputime get64
- *  
- * Returns cputime as a 64-bit number. 
- * 
+ *
+ * Returns cputime as a 64-bit number.
+ *
  * @return uint64_t The 64-bit representation of cputime.
  */
-uint64_t 
+uint64_t
 cputime_get64(void)
 {
     cputime_get32();
-    return g_cputime.cputime;
+    return g_native_cputime;
 }
 
 /**
- * cputime get32 
- *  
- * Returns the low 32 bits of cputime. 
- * 
+ * cputime get32
+ *
+ * Returns the low 32 bits of cputime.
+ *
  * @return uint32_t The lower 32 bits of cputime
  */
 uint32_t
@@ -234,260 +183,14 @@ cputime_get32(void)
 
     OS_ENTER_CRITICAL(sr);
     ostime = os_time_get();
-    delta_osticks = (uint32_t)(ostime - g_cputime.last_ostime);
+    delta_osticks = (uint32_t)(ostime - g_native_cputime_last_ostime);
     if (delta_osticks) {
-        g_cputime.last_ostime = ostime;
-        g_cputime.cputime +=
+        g_native_cputime_last_ostime = ostime;
+        g_native_cputime +=
             (uint64_t)g_native_cputime_cputicks_per_ostick * delta_osticks;
 
     }
     OS_EXIT_CRITICAL(sr);
 
-    return (uint32_t)g_cputime.cputime;
-}
-
-/**
- * cputime nsecs to ticks 
- *  
- * Converts the given number of nanoseconds into cputime ticks. 
- * 
- * @param usecs The number of nanoseconds to convert to ticks
- * 
- * @return uint32_t The number of ticks corresponding to 'nsecs'
- */
-uint32_t 
-cputime_nsecs_to_ticks(uint32_t nsecs)
-{
-    uint32_t ticks;
-
-    ticks = ((nsecs * g_cputime.ticks_per_usec) + 999) / 1000;
-    return ticks;
-}
-
-/**
- * cputime ticks to nsecs
- *  
- * Convert the given number of ticks into nanoseconds. 
- * 
- * @param ticks The number of ticks to convert to nanoseconds.
- * 
- * @return uint32_t The number of nanoseconds corresponding to 'ticks'
- */
-uint32_t 
-cputime_ticks_to_nsecs(uint32_t ticks)
-{
-    uint32_t nsecs;
-
-    nsecs = ((ticks * 1000) + (g_cputime.ticks_per_usec - 1)) / 
-            g_cputime.ticks_per_usec;
-
-    return nsecs;
-}
-
-/**
- * cputime usecs to ticks 
- *  
- * Converts the given number of microseconds into cputime ticks. 
- * 
- * @param usecs The number of microseconds to convert to ticks
- * 
- * @return uint32_t The number of ticks corresponding to 'usecs'
- */
-uint32_t 
-cputime_usecs_to_ticks(uint32_t usecs)
-{
-    uint32_t ticks;
-
-    ticks = (usecs * g_cputime.ticks_per_usec);
-    return ticks;
-}
-
-/**
- * cputime ticks to usecs
- *  
- * Convert the given number of ticks into microseconds. 
- * 
- * @param ticks The number of ticks to convert to microseconds.
- * 
- * @return uint32_t The number of microseconds corresponding to 'ticks'
- */
-uint32_t 
-cputime_ticks_to_usecs(uint32_t ticks)
-{
-    uint32_t us;
-
-    us =  (ticks + (g_cputime.ticks_per_usec - 1)) / g_cputime.ticks_per_usec;
-    return us;
-}
-
-/**
- * cputime delay ticks
- *  
- * Wait until the number of ticks has elapsed. This is a blocking delay. 
- * 
- * @param ticks The number of ticks to wait.
- */
-void 
-cputime_delay_ticks(uint32_t ticks)
-{
-    uint32_t until;
-
-    until = cputime_get32() + ticks;
-    while ((int32_t)(cputime_get32() - until) < 0) {
-        /* Loop here till finished */
-    }
-}
-
-/**
- * cputime delay nsecs 
- *  
- * Wait until 'nsecs' nanoseconds has elapsed. This is a blocking delay. 
- *  
- * @param nsecs The number of nanoseconds to wait.
- */
-void 
-cputime_delay_nsecs(uint32_t nsecs)
-{
-    uint32_t ticks;
-
-    ticks = cputime_nsecs_to_ticks(nsecs);
-    cputime_delay_ticks(ticks);
-}
-
-/**
- * cputime delay usecs 
- *  
- * Wait until 'usecs' microseconds has elapsed. This is a blocking delay. 
- *  
- * @param usecs The number of usecs to wait.
- */
-void 
-cputime_delay_usecs(uint32_t usecs)
-{
-    uint32_t ticks;
-
-    ticks = cputime_usecs_to_ticks(usecs);
-    cputime_delay_ticks(ticks);
-}
-
-/**
- * cputime timer init
- * 
- * 
- * @param timer The timer to initialize. Cannot be NULL.
- * @param fp    The timer callback function. Cannot be NULL.
- * @param arg   Pointer to data object to pass to timer. 
- */
-void 
-cputime_timer_init(struct cpu_timer *timer, cputimer_func fp, void *arg)
-{
-    assert(timer != NULL);
-    assert(fp != NULL);
-
-    timer->cb = fp;
-    timer->arg = arg;
-    timer->link.tqe_prev = (void *) NULL;
-}
-
-/**
- * cputime timer start 
- *  
- * Start a cputimer that will expire at 'cputime'. If cputime has already 
- * passed, the timer callback will still be called (at interrupt context). 
- * 
- * @param timer     Pointer to timer to start. Cannot be NULL.
- * @param cputime   The cputime at which the timer should expire.
- */
-void 
-cputime_timer_start(struct cpu_timer *timer, uint32_t cputime)
-{
-    struct cpu_timer *entry;
-    os_sr_t sr;
-
-    assert(timer != NULL);
-
-    /* XXX: should this use a mutex? not sure... */
-    OS_ENTER_CRITICAL(sr);
-
-    timer->cputime = cputime;
-    if (TAILQ_EMPTY(&g_cputimer_q)) {
-        TAILQ_INSERT_HEAD(&g_cputimer_q, timer, link);
-    } else {
-        TAILQ_FOREACH(entry, &g_cputimer_q, link) {
-            if ((int32_t)(timer->cputime - entry->cputime) < 0) {
-                TAILQ_INSERT_BEFORE(entry, timer, link);   
-                break;
-            }
-        }
-        if (!entry) {
-            TAILQ_INSERT_TAIL(&g_cputimer_q, timer, link);
-        }
-    }
-
-    /* If this is the head, we need to set new OCMP */
-    if (timer == TAILQ_FIRST(&g_cputimer_q)) {
-        cputime_set_ocmp(timer);
-    }
-
-    OS_EXIT_CRITICAL(sr);
-}
-
-/**
- * cputimer timer relative 
- *  
- * Sets a cpu timer that will expire 'usecs' microseconds from the current 
- * cputime. 
- * 
- * @param timer Pointer to timer. Cannot be NULL.
- * @param usecs The number of usecs from now at which the timer will expire.
- */
-void 
-cputime_timer_relative(struct cpu_timer *timer, uint32_t usecs)
-{
-    uint32_t cputime;
-
-    assert(timer != NULL);
-
-    cputime = cputime_get32() + cputime_usecs_to_ticks(usecs);
-    cputime_timer_start(timer, cputime);
-}
-
-/**
- * cputime timer stop 
- *  
- * Stops a cputimer from running. The timer is removed from the timer queue 
- * and interrupts are disabled if no timers are left on the queue. Can be 
- * called even if timer is running. 
- * 
- * @param timer Pointer to cputimer to stop. Cannot be NULL.
- */
-void 
-cputime_timer_stop(struct cpu_timer *timer)
-{
-    os_sr_t sr;
-    int reset_ocmp;
-    struct cpu_timer *entry;
-
-    assert(timer != NULL);
-
-    OS_ENTER_CRITICAL(sr);
-
-    /* If first on queue, we will need to reset OCMP */
-    if (timer->link.tqe_prev != NULL) {
-        reset_ocmp = 0;
-        if (timer == TAILQ_FIRST(&g_cputimer_q)) {
-            entry = TAILQ_NEXT(timer, link);
-            reset_ocmp = 1;
-        }
-        TAILQ_REMOVE(&g_cputimer_q, timer, link);
-        if (reset_ocmp) {
-            if (entry) {
-                cputime_set_ocmp(entry);
-            } else {
-                os_callout_stop(&g_native_cputimer.cf_c);
-            }
-        }
-    }
-
-    OS_EXIT_CRITICAL(sr);
+    return (uint32_t)g_native_cputime;
 }

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/183873d8/hw/mcu/nordic/nrf51xxx/src/hal_cputime.c
----------------------------------------------------------------------
diff --git a/hw/mcu/nordic/nrf51xxx/src/hal_cputime.c b/hw/mcu/nordic/nrf51xxx/src/hal_cputime.c
index eb12237..8f2815d 100644
--- a/hw/mcu/nordic/nrf51xxx/src/hal_cputime.c
+++ b/hw/mcu/nordic/nrf51xxx/src/hal_cputime.c
@@ -50,21 +50,7 @@
  *  - Sync to OSTIME.
  */
 
-/* CPUTIME data */
-struct cputime_data
-{
-    uint32_t ticks_per_usec;    /* number of ticks per usec */
-    uint32_t cputime_high;      /* high word of 64-bit cpu time */
-    uint32_t timer_isrs;        /* Number of timer interrupts */
-    uint32_t ocmp_ints;         /* Number of ocmp interrupts */
-    uint32_t uif_ints;          /* Number of overflow interrupts */
-};
-struct cputime_data g_cputime;
-
-/* Queue for timers */
-TAILQ_HEAD(cputime_qhead, cpu_timer) g_cputimer_q;
-
-__STATIC_INLINE void
+void
 cputime_disable_ocmp(void)
 {
     CPUTIMER->INTENCLR = CPUTIMER_INT_MASK(CPUTIMER_CC_INT);
@@ -79,7 +65,7 @@ cputime_disable_ocmp(void)
  *
  * @param timer Pointer to timer.
  */
-static void
+void
 cputime_set_ocmp(struct cpu_timer *timer)
 {
     /* Disable ocmp interrupt and set new value */
@@ -101,41 +87,6 @@ cputime_set_ocmp(struct cpu_timer *timer)
 }
 
 /**
- * cputime chk expiration
- *
- * Iterates through the cputimer queue to determine if any timers have expired.
- * If the timer has expired the timer is removed from the queue and the timer
- * callback function is executed.
- *
- */
-static void
-cputime_chk_expiration(void)
-{
-    uint32_t ctx;
-    struct cpu_timer *timer;
-
-    __HAL_DISABLE_INTERRUPTS(ctx);
-    while ((timer = TAILQ_FIRST(&g_cputimer_q)) != NULL) {
-        if ((int32_t)(cputime_get32() - timer->cputime) >= 0) {
-            TAILQ_REMOVE(&g_cputimer_q, timer, link);
-            timer->link.tqe_prev = NULL;
-            timer->cb(timer->arg);
-        } else {
-            break;
-        }
-    }
-
-    /* Any timers left on queue? If so, we need to set OCMP */
-    timer = TAILQ_FIRST(&g_cputimer_q);
-    if (timer) {
-        cputime_set_ocmp(timer);
-    } else {
-        cputime_disable_ocmp();
-    }
-    __HAL_ENABLE_INTERRUPTS(ctx);
-}
-
-/**
  * cputime isr
  *
  * This is the global timer interrupt routine.
@@ -197,7 +148,7 @@ cputime_isr(void)
  * @return int 0 on success; -1 on error.
  */
 int
-cputime_init(uint32_t clock_freq)
+cputime_hw_init(uint32_t clock_freq)
 {
     uint32_t ctx;
     uint32_t max_freq;
@@ -250,9 +201,6 @@ cputime_init(uint32_t clock_freq)
         return -1;
     }
 
-    /* Initialize the timer queue */
-    TAILQ_INIT(&g_cputimer_q);
-
     /* disable interrupts */
     __HAL_DISABLE_INTERRUPTS(ctx);
 
@@ -339,253 +287,3 @@ cputime_get32(void)
 
     return cpu_time;
 }
-
-/**
- * cputime nsecs to ticks
- *
- * Converts the given number of nanoseconds into cputime ticks.
- *
- * @param usecs The number of nanoseconds to convert to ticks
- *
- * @return uint32_t The number of ticks corresponding to 'nsecs'
- */
-uint32_t
-cputime_nsecs_to_ticks(uint32_t nsecs)
-{
-    uint32_t ticks;
-
-    ticks = ((nsecs * g_cputime.ticks_per_usec) + 999) / 1000;
-    return ticks;
-}
-
-/**
- * cputime ticks to nsecs
- *
- * Convert the given number of ticks into nanoseconds.
- *
- * @param ticks The number of ticks to convert to nanoseconds.
- *
- * @return uint32_t The number of nanoseconds corresponding to 'ticks'
- */
-uint32_t
-cputime_ticks_to_nsecs(uint32_t ticks)
-{
-    uint32_t nsecs;
-
-    nsecs = ((ticks * 1000) + (g_cputime.ticks_per_usec - 1)) /
-            g_cputime.ticks_per_usec;
-
-    return nsecs;
-}
-
-/**
- * cputime usecs to ticks
- *
- * Converts the given number of microseconds into cputime ticks.
- *
- * @param usecs The number of microseconds to convert to ticks
- *
- * @return uint32_t The number of ticks corresponding to 'usecs'
- */
-uint32_t
-cputime_usecs_to_ticks(uint32_t usecs)
-{
-    uint32_t ticks;
-
-    ticks = (usecs * g_cputime.ticks_per_usec);
-    return ticks;
-}
-
-/**
- * cputime ticks to usecs
- *
- * Convert the given number of ticks into microseconds.
- *
- * @param ticks The number of ticks to convert to microseconds.
- *
- * @return uint32_t The number of microseconds corresponding to 'ticks'
- */
-uint32_t
-cputime_ticks_to_usecs(uint32_t ticks)
-{
-    uint32_t us;
-
-    us =  (ticks + (g_cputime.ticks_per_usec - 1)) / g_cputime.ticks_per_usec;
-    return us;
-}
-
-/**
- * cputime delay ticks
- *
- * Wait until the number of ticks has elapsed. This is a blocking delay.
- *
- * @param ticks The number of ticks to wait.
- */
-void
-cputime_delay_ticks(uint32_t ticks)
-{
-    uint32_t until;
-
-    until = cputime_get32() + ticks;
-    while ((int32_t)(cputime_get32() - until) < 0) {
-        /* Loop here till finished */
-    }
-}
-
-/**
- * cputime delay nsecs
- *
- * Wait until 'nsecs' nanoseconds has elapsed. This is a blocking delay.
- *
- * @param nsecs The number of nanoseconds to wait.
- */
-void
-cputime_delay_nsecs(uint32_t nsecs)
-{
-    uint32_t ticks;
-
-    ticks = cputime_nsecs_to_ticks(nsecs);
-    cputime_delay_ticks(ticks);
-}
-
-/**
- * cputime delay usecs
- *
- * Wait until 'usecs' microseconds has elapsed. This is a blocking delay.
- *
- * @param usecs The number of usecs to wait.
- */
-void
-cputime_delay_usecs(uint32_t usecs)
-{
-    uint32_t ticks;
-
-    ticks = cputime_usecs_to_ticks(usecs);
-    cputime_delay_ticks(ticks);
-}
-
-/**
- * cputime timer init
- *
- *
- * @param timer The timer to initialize. Cannot be NULL.
- * @param fp    The timer callback function. Cannot be NULL.
- * @param arg   Pointer to data object to pass to timer.
- */
-void
-cputime_timer_init(struct cpu_timer *timer, cputimer_func fp, void *arg)
-{
-    assert(timer != NULL);
-    assert(fp != NULL);
-
-    timer->cb = fp;
-    timer->arg = arg;
-    timer->link.tqe_prev = (void *) NULL;
-}
-
-/**
- * cputime timer start
- *
- * Start a cputimer that will expire at 'cputime'. If cputime has already
- * passed, the timer callback will still be called (at interrupt context).
- * Cannot be called when the timer has already started.
- *
- * @param timer     Pointer to timer to start. Cannot be NULL.
- * @param cputime   The cputime at which the timer should expire.
- */
-void
-cputime_timer_start(struct cpu_timer *timer, uint32_t cputime)
-{
-    struct cpu_timer *entry;
-    uint32_t ctx;
-
-    assert(timer != NULL);
-    assert(timer->link.tqe_prev == NULL);
-
-    /* XXX: should this use a mutex? not sure... */
-    __HAL_DISABLE_INTERRUPTS(ctx);
-
-    timer->cputime = cputime;
-    if (TAILQ_EMPTY(&g_cputimer_q)) {
-        TAILQ_INSERT_HEAD(&g_cputimer_q, timer, link);
-    } else {
-        TAILQ_FOREACH(entry, &g_cputimer_q, link) {
-            if ((int32_t)(timer->cputime - entry->cputime) < 0) {
-                TAILQ_INSERT_BEFORE(entry, timer, link);
-                break;
-            }
-        }
-        if (!entry) {
-            TAILQ_INSERT_TAIL(&g_cputimer_q, timer, link);
-        }
-    }
-
-    /* If this is the head, we need to set new OCMP */
-    if (timer == TAILQ_FIRST(&g_cputimer_q)) {
-        cputime_set_ocmp(timer);
-    }
-
-    __HAL_ENABLE_INTERRUPTS(ctx);
-}
-
-/**
- * cputimer timer relative
- *
- * Sets a cpu timer that will expire 'usecs' microseconds from the current
- * cputime.
- *
- * @param timer Pointer to timer. Cannot be NULL.
- * @param usecs The number of usecs from now at which the timer will expire.
- */
-void
-cputime_timer_relative(struct cpu_timer *timer, uint32_t usecs)
-{
-    uint32_t cputime;
-
-    assert(timer != NULL);
-
-    cputime = cputime_get32() + cputime_usecs_to_ticks(usecs);
-    cputime_timer_start(timer, cputime);
-}
-
-/**
- * cputime timer stop
- *
- * Stops a cputimer from running. The timer is removed from the timer queue
- * and interrupts are disabled if no timers are left on the queue. Can be
- * called even if timer is not running.
- *
- * @param timer Pointer to cputimer to stop. Cannot be NULL.
- */
-void
-cputime_timer_stop(struct cpu_timer *timer)
-{
-    int reset_ocmp;
-    uint32_t ctx;
-    struct cpu_timer *entry;
-
-    assert(timer != NULL);
-
-    __HAL_DISABLE_INTERRUPTS(ctx);
-
-    if (timer->link.tqe_prev != NULL) {
-        reset_ocmp = 0;
-        if (timer == TAILQ_FIRST(&g_cputimer_q)) {
-            /* If first on queue, we will need to reset OCMP */
-            entry = TAILQ_NEXT(timer, link);
-            reset_ocmp = 1;
-        }
-        TAILQ_REMOVE(&g_cputimer_q, timer, link);
-        timer->link.tqe_prev = NULL;
-        if (reset_ocmp) {
-            if (entry) {
-                cputime_set_ocmp(entry);
-            } else {
-                cputime_disable_ocmp();
-            }
-        }
-    }
-
-    __HAL_ENABLE_INTERRUPTS(ctx);
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/183873d8/hw/mcu/nordic/nrf52xxx/src/hal_cputime.c
----------------------------------------------------------------------
diff --git a/hw/mcu/nordic/nrf52xxx/src/hal_cputime.c b/hw/mcu/nordic/nrf52xxx/src/hal_cputime.c
index fbcc96d..d58fee3 100644
--- a/hw/mcu/nordic/nrf52xxx/src/hal_cputime.c
+++ b/hw/mcu/nordic/nrf52xxx/src/hal_cputime.c
@@ -49,22 +49,7 @@
  *  - Should I use macro for compare channel?
  *  - Sync to OSTIME.
  */
-
-/* CPUTIME data */
-struct cputime_data
-{
-    uint32_t ticks_per_usec;    /* number of ticks per usec */
-    uint32_t cputime_high;      /* high word of 64-bit cpu time */
-    uint32_t timer_isrs;        /* Number of timer interrupts */
-    uint32_t ocmp_ints;         /* Number of ocmp interrupts */
-    uint32_t uif_ints;          /* Number of overflow interrupts */
-};
-struct cputime_data g_cputime;
-
-/* Queue for timers */
-TAILQ_HEAD(cputime_qhead, cpu_timer) g_cputimer_q;
-
-__STATIC_INLINE void
+void
 cputime_disable_ocmp(void)
 {
     CPUTIMER->INTENCLR = CPUTIMER_INT_MASK(CPUTIMER_CC_INT);
@@ -79,11 +64,11 @@ cputime_disable_ocmp(void)
  *
  * @param timer Pointer to timer.
  */
-static void
+void
 cputime_set_ocmp(struct cpu_timer *timer)
 {
     /* Disable ocmp interrupt and set new value */
-    cputime_disable_ocmp();
+    CPUTIMER->INTENCLR = CPUTIMER_INT_MASK(CPUTIMER_CC_INT);
 
     /* Set output compare register to timer expiration */
     CPUTIMER->CC[CPUTIMER_CC_INT] = timer->cputime;
@@ -101,41 +86,6 @@ cputime_set_ocmp(struct cpu_timer *timer)
 }
 
 /**
- * cputime chk expiration
- *
- * Iterates through the cputimer queue to determine if any timers have expired.
- * If the timer has expired the timer is removed from the queue and the timer
- * callback function is executed.
- *
- */
-static void
-cputime_chk_expiration(void)
-{
-    uint32_t ctx;
-    struct cpu_timer *timer;
-
-    __HAL_DISABLE_INTERRUPTS(ctx);
-    while ((timer = TAILQ_FIRST(&g_cputimer_q)) != NULL) {
-        if ((int32_t)(cputime_get32() - timer->cputime) >= 0) {
-            TAILQ_REMOVE(&g_cputimer_q, timer, link);
-            timer->link.tqe_prev = NULL;
-            timer->cb(timer->arg);
-        } else {
-            break;
-        }
-    }
-
-    /* Any timers left on queue? If so, we need to set OCMP */
-    timer = TAILQ_FIRST(&g_cputimer_q);
-    if (timer) {
-        cputime_set_ocmp(timer);
-    } else {
-        cputime_disable_ocmp();
-    }
-    __HAL_ENABLE_INTERRUPTS(ctx);
-}
-
-/**
  * cputime isr
  *
  * This is the global timer interrupt routine.
@@ -186,18 +136,17 @@ cputime_isr(void)
 }
 
 /**
- * cputime init
+ * cputime hw init
  *
- * Initialize the cputime module. This must be called after os_init is called
- * and before any other timer API are used. This should be called only once
- * and should be called before the hardware timer is used.
+ * Initialize the cputime hw. This should be called only once and should be
+ * called before the hardware timer is used.
  *
  * @param clock_freq The desired cputime frequency, in hertz (Hz).
  *
  * @return int 0 on success; -1 on error.
  */
 int
-cputime_init(uint32_t clock_freq)
+cputime_hw_init(uint32_t clock_freq)
 {
     uint32_t ctx;
     uint32_t max_freq;
@@ -250,9 +199,6 @@ cputime_init(uint32_t clock_freq)
         return -1;
     }
 
-    /* Initialize the timer queue */
-    TAILQ_INIT(&g_cputimer_q);
-
     /* disable interrupts */
     __HAL_DISABLE_INTERRUPTS(ctx);
 
@@ -339,253 +285,3 @@ cputime_get32(void)
 
     return cpu_time;
 }
-
-/**
- * cputime nsecs to ticks
- *
- * Converts the given number of nanoseconds into cputime ticks.
- *
- * @param usecs The number of nanoseconds to convert to ticks
- *
- * @return uint32_t The number of ticks corresponding to 'nsecs'
- */
-uint32_t
-cputime_nsecs_to_ticks(uint32_t nsecs)
-{
-    uint32_t ticks;
-
-    ticks = ((nsecs * g_cputime.ticks_per_usec) + 999) / 1000;
-    return ticks;
-}
-
-/**
- * cputime ticks to nsecs
- *
- * Convert the given number of ticks into nanoseconds.
- *
- * @param ticks The number of ticks to convert to nanoseconds.
- *
- * @return uint32_t The number of nanoseconds corresponding to 'ticks'
- */
-uint32_t
-cputime_ticks_to_nsecs(uint32_t ticks)
-{
-    uint32_t nsecs;
-
-    nsecs = ((ticks * 1000) + (g_cputime.ticks_per_usec - 1)) /
-            g_cputime.ticks_per_usec;
-
-    return nsecs;
-}
-
-/**
- * cputime usecs to ticks
- *
- * Converts the given number of microseconds into cputime ticks.
- *
- * @param usecs The number of microseconds to convert to ticks
- *
- * @return uint32_t The number of ticks corresponding to 'usecs'
- */
-uint32_t
-cputime_usecs_to_ticks(uint32_t usecs)
-{
-    uint32_t ticks;
-
-    ticks = (usecs * g_cputime.ticks_per_usec);
-    return ticks;
-}
-
-/**
- * cputime ticks to usecs
- *
- * Convert the given number of ticks into microseconds.
- *
- * @param ticks The number of ticks to convert to microseconds.
- *
- * @return uint32_t The number of microseconds corresponding to 'ticks'
- */
-uint32_t
-cputime_ticks_to_usecs(uint32_t ticks)
-{
-    uint32_t us;
-
-    us =  (ticks + (g_cputime.ticks_per_usec - 1)) / g_cputime.ticks_per_usec;
-    return us;
-}
-
-/**
- * cputime delay ticks
- *
- * Wait until the number of ticks has elapsed. This is a blocking delay.
- *
- * @param ticks The number of ticks to wait.
- */
-void
-cputime_delay_ticks(uint32_t ticks)
-{
-    uint32_t until;
-
-    until = cputime_get32() + ticks;
-    while ((int32_t)(cputime_get32() - until) < 0) {
-        /* Loop here till finished */
-    }
-}
-
-/**
- * cputime delay nsecs
- *
- * Wait until 'nsecs' nanoseconds has elapsed. This is a blocking delay.
- *
- * @param nsecs The number of nanoseconds to wait.
- */
-void
-cputime_delay_nsecs(uint32_t nsecs)
-{
-    uint32_t ticks;
-
-    ticks = cputime_nsecs_to_ticks(nsecs);
-    cputime_delay_ticks(ticks);
-}
-
-/**
- * cputime delay usecs
- *
- * Wait until 'usecs' microseconds has elapsed. This is a blocking delay.
- *
- * @param usecs The number of usecs to wait.
- */
-void
-cputime_delay_usecs(uint32_t usecs)
-{
-    uint32_t ticks;
-
-    ticks = cputime_usecs_to_ticks(usecs);
-    cputime_delay_ticks(ticks);
-}
-
-/**
- * cputime timer init
- *
- *
- * @param timer The timer to initialize. Cannot be NULL.
- * @param fp    The timer callback function. Cannot be NULL.
- * @param arg   Pointer to data object to pass to timer.
- */
-void
-cputime_timer_init(struct cpu_timer *timer, cputimer_func fp, void *arg)
-{
-    assert(timer != NULL);
-    assert(fp != NULL);
-
-    timer->cb = fp;
-    timer->arg = arg;
-    timer->link.tqe_prev = (void *) NULL;
-}
-
-/**
- * cputime timer start
- *
- * Start a cputimer that will expire at 'cputime'. If cputime has already
- * passed, the timer callback will still be called (at interrupt context).
- * Cannot be called when the timer has already started.
- *
- * @param timer     Pointer to timer to start. Cannot be NULL.
- * @param cputime   The cputime at which the timer should expire.
- */
-void
-cputime_timer_start(struct cpu_timer *timer, uint32_t cputime)
-{
-    struct cpu_timer *entry;
-    uint32_t ctx;
-
-    assert(timer != NULL);
-    assert(timer->link.tqe_prev == NULL);
-
-    /* XXX: should this use a mutex? not sure... */
-    __HAL_DISABLE_INTERRUPTS(ctx);
-
-    timer->cputime = cputime;
-    if (TAILQ_EMPTY(&g_cputimer_q)) {
-        TAILQ_INSERT_HEAD(&g_cputimer_q, timer, link);
-    } else {
-        TAILQ_FOREACH(entry, &g_cputimer_q, link) {
-            if ((int32_t)(timer->cputime - entry->cputime) < 0) {
-                TAILQ_INSERT_BEFORE(entry, timer, link);
-                break;
-            }
-        }
-        if (!entry) {
-            TAILQ_INSERT_TAIL(&g_cputimer_q, timer, link);
-        }
-    }
-
-    /* If this is the head, we need to set new OCMP */
-    if (timer == TAILQ_FIRST(&g_cputimer_q)) {
-        cputime_set_ocmp(timer);
-    }
-
-    __HAL_ENABLE_INTERRUPTS(ctx);
-}
-
-/**
- * cputimer timer relative
- *
- * Sets a cpu timer that will expire 'usecs' microseconds from the current
- * cputime.
- *
- * @param timer Pointer to timer. Cannot be NULL.
- * @param usecs The number of usecs from now at which the timer will expire.
- */
-void
-cputime_timer_relative(struct cpu_timer *timer, uint32_t usecs)
-{
-    uint32_t cputime;
-
-    assert(timer != NULL);
-
-    cputime = cputime_get32() + cputime_usecs_to_ticks(usecs);
-    cputime_timer_start(timer, cputime);
-}
-
-/**
- * cputime timer stop
- *
- * Stops a cputimer from running. The timer is removed from the timer queue
- * and interrupts are disabled if no timers are left on the queue. Can be
- * called even if timer is not running.
- *
- * @param timer Pointer to cputimer to stop. Cannot be NULL.
- */
-void
-cputime_timer_stop(struct cpu_timer *timer)
-{
-    int reset_ocmp;
-    uint32_t ctx;
-    struct cpu_timer *entry;
-
-    assert(timer != NULL);
-
-    __HAL_DISABLE_INTERRUPTS(ctx);
-
-    if (timer->link.tqe_prev != NULL) {
-        reset_ocmp = 0;
-        if (timer == TAILQ_FIRST(&g_cputimer_q)) {
-            /* If first on queue, we will need to reset OCMP */
-            entry = TAILQ_NEXT(timer, link);
-            reset_ocmp = 1;
-        }
-        TAILQ_REMOVE(&g_cputimer_q, timer, link);
-        timer->link.tqe_prev = NULL;
-        if (reset_ocmp) {
-            if (entry) {
-                cputime_set_ocmp(entry);
-            } else {
-                cputime_disable_ocmp();
-            }
-        }
-    }
-
-    __HAL_ENABLE_INTERRUPTS(ctx);
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/183873d8/hw/mcu/stm/stm32f4xx/src/hal_cputime.c
----------------------------------------------------------------------
diff --git a/hw/mcu/stm/stm32f4xx/src/hal_cputime.c b/hw/mcu/stm/stm32f4xx/src/hal_cputime.c
index f3ada59..0025670 100644
--- a/hw/mcu/stm/stm32f4xx/src/hal_cputime.c
+++ b/hw/mcu/stm/stm32f4xx/src/hal_cputime.c
@@ -6,7 +6,7 @@
  * to you 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,
@@ -31,28 +31,20 @@
  *  - Sync to OSTIME.
  */
 
-/* CPUTIME data */
-struct cputime_data
+void
+cputime_disable_ocmp(void)
 {
-    uint32_t ticks_per_usec;    /* number of ticks per usec */
-    uint32_t cputime_high;      /* high word of 64-bit cpu time */
-    uint32_t timer_isrs;        /* Number of timer interrupts */
-    uint32_t ocmp_ints;         /* Number of ocmp interrupts */
-    uint32_t uif_ints;          /* Number of overflow interrupts */
-};
-struct cputime_data g_cputime;
-
-/* Queue for timers */
-TAILQ_HEAD(cputime_qhead, cpu_timer) g_cputimer_q;
+    TIM5->DIER &= ~TIM_DIER_CC4IE;
+}
 
 /**
- * cputime set ocmp 
- *  
- * Set the OCMP used by the cputime module to the desired cputime. 
- * 
+ * cputime set ocmp
+ *
+ * Set the OCMP used by the cputime module to the desired cputime.
+ *
  * @param timer Pointer to timer.
  */
-static void
+void
 cputime_set_ocmp(struct cpu_timer *timer)
 {
     TIM5->DIER &= ~TIM_DIER_CC4IE;
@@ -66,44 +58,10 @@ cputime_set_ocmp(struct cpu_timer *timer)
 }
 
 /**
- * cputime chk expiration 
- *  
- * Iterates through the cputimer queue to determine if any timers have expired. 
- * If the timer has expired the timer is removed from the queue and the timer 
- * callback function is executed. 
- * 
- */
-static void
-cputime_chk_expiration(void)
-{
-    uint32_t ctx;
-    struct cpu_timer *timer;
-
-    __HAL_DISABLE_INTERRUPTS(ctx);
-    while ((timer = TAILQ_FIRST(&g_cputimer_q)) != NULL) {
-        if ((int32_t)(cputime_get32() - timer->cputime) >= 0) {
-            TAILQ_REMOVE(&g_cputimer_q, timer, link);
-            timer->cb(timer->arg);
-        } else {
-            break;
-        }
-    }
-
-    /* Any timers left on queue? If so, we need to set OCMP */
-    timer = TAILQ_FIRST(&g_cputimer_q);
-    if (timer) {
-        cputime_set_ocmp(timer);
-    } else {
-        TIM5->DIER &= ~TIM_DIER_CC4IE;
-    }
-    __HAL_ENABLE_INTERRUPTS(ctx);
-}
-
-/**
- * tim5 isr 
- *  
- * This is the global timer interrupt routine. 
- * 
+ * tim5 isr
+ *
+ * This is the global timer interrupt routine.
+ *
  */
 static void
 cputime_isr(void)
@@ -133,18 +91,17 @@ cputime_isr(void)
 }
 
 /**
- * cputime init 
- *  
- * Initialize the cputime module. This must be called after os_init is called 
- * and before any other timer API are used. This should be called only once 
- * and should be called before the hardware timer is used. 
- * 
+ * cputime hw init
+ *
+ * Initialize the cputime hw. This should be called only once and should be
+ * called before the hardware timer is used.
+ *
  * @param clock_freq The desired cputime frequency, in hertz (Hz).
- * 
+ *
  * @return int 0 on success; -1 on error.
  */
 int
-cputime_init(uint32_t clock_freq)
+cputime_hw_init(uint32_t clock_freq)
 {
     uint32_t ctx;
     uint32_t max_freq;
@@ -167,9 +124,6 @@ cputime_init(uint32_t clock_freq)
         return -1;
     }
 
-    /* Initialize the timer queue */
-    TAILQ_INIT(&g_cputimer_q);
-
     /* disable interrupts */
     __HAL_DISABLE_INTERRUPTS(ctx);
 
@@ -184,10 +138,10 @@ cputime_init(uint32_t clock_freq)
     /* In debug mode, we want this timer to be halted */
     DBGMCU->APB1FZ |= DBGMCU_APB1_FZ_DBG_TIM5_STOP;
 
-    /* 
+    /*
      * Counter is an up counter with event generation disabled. We disable the
      * timer with this first write, just in case.
-     */ 
+     */
     TIM5->DIER = 0;
     TIM5->CR1 = 0;
     TIM5->CR2 = 0;
@@ -228,12 +182,12 @@ cputime_init(uint32_t clock_freq)
 
 /**
  * cputime get64
- *  
- * Returns cputime as a 64-bit number. 
- * 
+ *
+ * Returns cputime as a 64-bit number.
+ *
  * @return uint64_t The 64-bit representation of cputime.
  */
-uint64_t 
+uint64_t
 cputime_get64(void)
 {
     uint32_t ctx;
@@ -256,10 +210,10 @@ cputime_get64(void)
 }
 
 /**
- * cputime get32 
- *  
- * Returns the low 32 bits of cputime. 
- * 
+ * cputime get32
+ *
+ * Returns the low 32 bits of cputime.
+ *
  * @return uint32_t The lower 32 bits of cputime
  */
 uint32_t
@@ -267,250 +221,3 @@ cputime_get32(void)
 {
     return TIM5->CNT;
 }
-
-/**
- * cputime nsecs to ticks 
- *  
- * Converts the given number of nanoseconds into cputime ticks. 
- * 
- * @param usecs The number of nanoseconds to convert to ticks
- * 
- * @return uint32_t The number of ticks corresponding to 'nsecs'
- */
-uint32_t 
-cputime_nsecs_to_ticks(uint32_t nsecs)
-{
-    uint32_t ticks;
-
-    ticks = ((nsecs * g_cputime.ticks_per_usec) + 999) / 1000;
-    return ticks;
-}
-
-/**
- * cputime ticks to nsecs
- *  
- * Convert the given number of ticks into nanoseconds. 
- * 
- * @param ticks The number of ticks to convert to nanoseconds.
- * 
- * @return uint32_t The number of nanoseconds corresponding to 'ticks'
- */
-uint32_t 
-cputime_ticks_to_nsecs(uint32_t ticks)
-{
-    uint32_t nsecs;
-
-    nsecs = ((ticks * 1000) + (g_cputime.ticks_per_usec - 1)) / 
-            g_cputime.ticks_per_usec;
-
-    return nsecs;
-}
-
-/**
- * cputime usecs to ticks 
- *  
- * Converts the given number of microseconds into cputime ticks. 
- * 
- * @param usecs The number of microseconds to convert to ticks
- * 
- * @return uint32_t The number of ticks corresponding to 'usecs'
- */
-uint32_t 
-cputime_usecs_to_ticks(uint32_t usecs)
-{
-    uint32_t ticks;
-
-    ticks = (usecs * g_cputime.ticks_per_usec);
-    return ticks;
-}
-
-/**
- * cputime ticks to usecs
- *  
- * Convert the given number of ticks into microseconds. 
- * 
- * @param ticks The number of ticks to convert to microseconds.
- * 
- * @return uint32_t The number of microseconds corresponding to 'ticks'
- */
-uint32_t 
-cputime_ticks_to_usecs(uint32_t ticks)
-{
-    uint32_t us;
-
-    us =  (ticks + (g_cputime.ticks_per_usec - 1)) / g_cputime.ticks_per_usec;
-    return us;
-}
-
-/**
- * cputime delay ticks
- *  
- * Wait until the number of ticks has elapsed. This is a blocking delay. 
- * 
- * @param ticks The number of ticks to wait.
- */
-void 
-cputime_delay_ticks(uint32_t ticks)
-{
-    uint32_t until;
-
-    until = cputime_get32() + ticks;
-    while ((int32_t)(cputime_get32() - until) < 0) {
-        /* Loop here till finished */
-    }
-}
-
-/**
- * cputime delay nsecs 
- *  
- * Wait until 'nsecs' nanoseconds has elapsed. This is a blocking delay. 
- *  
- * @param nsecs The number of nanoseconds to wait.
- */
-void 
-cputime_delay_nsecs(uint32_t nsecs)
-{
-    uint32_t ticks;
-
-    ticks = cputime_nsecs_to_ticks(nsecs);
-    cputime_delay_ticks(ticks);
-}
-
-/**
- * cputime delay usecs 
- *  
- * Wait until 'usecs' microseconds has elapsed. This is a blocking delay. 
- *  
- * @param usecs The number of usecs to wait.
- */
-void 
-cputime_delay_usecs(uint32_t usecs)
-{
-    uint32_t ticks;
-
-    ticks = cputime_usecs_to_ticks(usecs);
-    cputime_delay_ticks(ticks);
-}
-
-/**
- * cputime timer init
- * 
- * 
- * @param timer The timer to initialize. Cannot be NULL.
- * @param fp    The timer callback function. Cannot be NULL.
- * @param arg   Pointer to data object to pass to timer. 
- */
-void 
-cputime_timer_init(struct cpu_timer *timer, cputimer_func fp, void *arg)
-{
-    assert(timer != NULL);
-    assert(fp != NULL);
-
-    timer->cb = fp;
-    timer->arg = arg;
-    timer->link.tqe_prev = (void *) NULL;
-}
-
-/**
- * cputime timer start 
- *  
- * Start a cputimer that will expire at 'cputime'. If cputime has already 
- * passed, the timer callback will still be called (at interrupt context). 
- * 
- * @param timer     Pointer to timer to start. Cannot be NULL.
- * @param cputime   The cputime at which the timer should expire.
- */
-void 
-cputime_timer_start(struct cpu_timer *timer, uint32_t cputime)
-{
-    struct cpu_timer *entry;
-    uint32_t ctx;
-
-    assert(timer != NULL);
-
-    /* XXX: should this use a mutex? not sure... */
-    __HAL_DISABLE_INTERRUPTS(ctx);
-
-    timer->cputime = cputime;
-    if (TAILQ_EMPTY(&g_cputimer_q)) {
-        TAILQ_INSERT_HEAD(&g_cputimer_q, timer, link);
-    } else {
-        TAILQ_FOREACH(entry, &g_cputimer_q, link) {
-            if ((int32_t)(timer->cputime - entry->cputime) < 0) {
-                TAILQ_INSERT_BEFORE(entry, timer, link);   
-                break;
-            }
-        }
-        if (!entry) {
-            TAILQ_INSERT_TAIL(&g_cputimer_q, timer, link);
-        }
-    }
-
-    /* If this is the head, we need to set new OCMP */
-    if (timer == TAILQ_FIRST(&g_cputimer_q)) {
-        cputime_set_ocmp(timer);
-    }
-
-    __HAL_ENABLE_INTERRUPTS(ctx);
-}
-
-/**
- * cputimer timer relative 
- *  
- * Sets a cpu timer that will expire 'usecs' microseconds from the current 
- * cputime. 
- * 
- * @param timer Pointer to timer. Cannot be NULL.
- * @param usecs The number of usecs from now at which the timer will expire.
- */
-void 
-cputime_timer_relative(struct cpu_timer *timer, uint32_t usecs)
-{
-    uint32_t cputime;
-
-    assert(timer != NULL);
-
-    cputime = cputime_get32() + cputime_usecs_to_ticks(usecs);
-    cputime_timer_start(timer, cputime);
-}
-
-/**
- * cputime timer stop 
- *  
- * Stops a cputimer from running. The timer is removed from the timer queue 
- * and interrupts are disabled if no timers are left on the queue. Can be 
- * called even if timer is running. 
- * 
- * @param timer Pointer to cputimer to stop. Cannot be NULL.
- */
-void 
-cputime_timer_stop(struct cpu_timer *timer)
-{
-    int reset_ocmp;
-    uint32_t ctx;
-    struct cpu_timer *entry;
-
-    assert(timer != NULL);
-
-    __HAL_DISABLE_INTERRUPTS(ctx);
-
-    /* If first on queue, we will need to reset OCMP */
-    if (timer->link.tqe_prev != NULL) {
-        reset_ocmp = 0;
-        if (timer == TAILQ_FIRST(&g_cputimer_q)) {
-            entry = TAILQ_NEXT(timer, link);
-            reset_ocmp = 1;
-        }
-        TAILQ_REMOVE(&g_cputimer_q, timer, link);
-        if (reset_ocmp) {
-            if (entry) {
-                cputime_set_ocmp(entry);
-            } else {
-                TIM5->DIER &= ~TIM_DIER_CC4IE;
-            }
-        }
-    }
-
-    __HAL_ENABLE_INTERRUPTS(ctx);
-}
-



[39/50] [abbrv] incubator-mynewt-core git commit: BLE Host - Report HCI error code on terminate.

Posted by cc...@apache.org.
BLE Host - Report HCI error code on terminate.

The host reports a disconnect event via the BLE_GAP_EVENT_DISCONNECT
event code.

Prior to this change: locally-terminated connections were reported with
a status code of BLE_HS_ENOTCONN.

Now: locally-terminated connections are reported with a status code of
BLE_HS_HCI_ERR(BLE_ERR_CONN_TERM_LOCAL).


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/baee9cd0
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/baee9cd0
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/baee9cd0

Branch: refs/heads/master
Commit: baee9cd0593d32bacf919aea51527d1859cdfa52
Parents: 55c2e6e
Author: Christopher Collins <cc...@apache.org>
Authored: Thu Jun 30 16:30:04 2016 -0700
Committer: Christopher Collins <cc...@apache.org>
Committed: Thu Jun 30 16:30:04 2016 -0700

----------------------------------------------------------------------
 net/nimble/host/src/ble_gap.c           | 9 +--------
 net/nimble/host/src/test/ble_gap_test.c | 3 ++-
 2 files changed, 3 insertions(+), 9 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/baee9cd0/net/nimble/host/src/ble_gap.c
----------------------------------------------------------------------
diff --git a/net/nimble/host/src/ble_gap.c b/net/nimble/host/src/ble_gap.c
index 50b1df6..309b7cf 100644
--- a/net/nimble/host/src/ble_gap.c
+++ b/net/nimble/host/src/ble_gap.c
@@ -625,14 +625,7 @@ ble_gap_rx_disconn_complete(struct hci_disconn_complete *evt)
     }
 
     if (evt->status == 0) {
-        if (evt->reason == BLE_ERR_CONN_TERM_LOCAL) {
-            /* Don't confuse the application with an HCI error code in the
-             * success case.
-             */
-            status = BLE_HS_ENOTCONN;
-        } else {
-            status = BLE_HS_HCI_ERR(evt->reason);
-        }
+        status = BLE_HS_HCI_ERR(evt->reason);
         ble_gap_conn_broken(&snap, status);
     } else {
         memset(&ctxt, 0, sizeof ctxt);

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/baee9cd0/net/nimble/host/src/test/ble_gap_test.c
----------------------------------------------------------------------
diff --git a/net/nimble/host/src/test/ble_gap_test.c b/net/nimble/host/src/test/ble_gap_test.c
index 7868f2a..fcaba40 100644
--- a/net/nimble/host/src/test/ble_gap_test.c
+++ b/net/nimble/host/src/test/ble_gap_test.c
@@ -907,7 +907,8 @@ TEST_CASE(ble_gap_test_case_conn_terminate_good)
     ble_gap_test_util_terminate(peer_addr, 0);
 
     TEST_ASSERT(ble_gap_test_conn_event == BLE_GAP_EVENT_DISCONNECT);
-    TEST_ASSERT(ble_gap_test_conn_status == BLE_HS_ENOTCONN);
+    TEST_ASSERT(ble_gap_test_conn_status ==
+                BLE_HS_HCI_ERR(BLE_ERR_CONN_TERM_LOCAL));
     TEST_ASSERT(ble_gap_test_conn_desc.conn_handle == 2);
     TEST_ASSERT(ble_gap_test_conn_desc.peer_id_addr_type == BLE_ADDR_TYPE_PUBLIC);
     TEST_ASSERT(memcmp(ble_gap_test_conn_desc.peer_id_addr, peer_addr, 6) == 0);